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 +#include #include #include #include +#include #include namespace rt::dxgi { @@ -101,12 +104,19 @@ private: class SwapChain final : public IDXGISwapChain3 { public: - SwapChain(leonida::VulkanContext& context, PFN_vkGetInstanceProcAddr gipa, VkInstance instance, - VkPhysicalDevice physical, PFN_vkGetDeviceProcAddr gdpa, VkQueue queue, std::uint32_t queue_family) - : context_(context), - swapchain_(gipa, instance, physical, gdpa, context.device(), queue, queue_family, context.submit_mutex()) {} + SwapChain(IDXGIFactory4* parent, leonida::VulkanContext& context, PFN_vkGetInstanceProcAddr gipa, + VkInstance instance, VkPhysicalDevice physical, PFN_vkGetDeviceProcAddr gdpa, VkQueue queue, + std::uint32_t queue_family) + : parent_(parent), + context_(context), + swapchain_(gipa, instance, physical, gdpa, context.device(), queue, queue_family, context.submit_mutex()) { + if (parent_) parent_->AddRef(); + } - ~SwapChain() { unregister_buffers(); } + ~SwapChain() { + unregister_buffers(); + if (parent_) parent_->Release(); + } bool init(HWND hwnd, const DXGI_SWAP_CHAIN_DESC1& desc) { hwnd_ = hwnd; @@ -149,7 +159,12 @@ public: HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } - HRESULT STDMETHODCALLTYPE GetParent(REFIID, void**) override { stub("IDXGISwapChain::GetParent"); return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!parent_) return E_NOINTERFACE; + return parent_->QueryInterface(riid, out); + } // IDXGIDeviceSubObject HRESULT STDMETHODCALLTYPE GetDevice(REFIID, void**) override { stub("IDXGISwapChain::GetDevice"); return E_NOTIMPL; } @@ -160,6 +175,7 @@ public: if (flags & DXGI_PRESENT_TEST) return S_OK; // only asks whether a present would succeed const std::uint32_t cur = swapchain_.current_back_buffer_index(); if (!swapchain_.present(cur)) return E_FAIL; + ++present_count_; std::uint32_t next = 0; return swapchain_.acquire_next_image(next) ? S_OK : E_FAIL; } @@ -215,7 +231,11 @@ public: HRESULT STDMETHODCALLTYPE ResizeTarget(const DXGI_MODE_DESC*) override { return S_OK; } HRESULT STDMETHODCALLTYPE GetContainingOutput(IDXGIOutput**) override { return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; } HRESULT STDMETHODCALLTYPE GetFrameStatistics(DXGI_FRAME_STATISTICS*) override { return E_NOTIMPL; } - HRESULT STDMETHODCALLTYPE GetLastPresentCount(UINT* p) override { if (p) *p = 0; return S_OK; } + HRESULT STDMETHODCALLTYPE GetLastPresentCount(UINT* p) override { + if (!p) return E_INVALIDARG; + *p = present_count_.load(std::memory_order_relaxed); + return S_OK; + } // IDXGISwapChain1 HRESULT STDMETHODCALLTYPE GetDesc1(DXGI_SWAP_CHAIN_DESC1* desc) override { @@ -255,8 +275,16 @@ public: if (h) *h = swapchain_.extent().height; return S_OK; } - HRESULT STDMETHODCALLTYPE SetMaximumFrameLatency(UINT) override { return S_OK; } - HRESULT STDMETHODCALLTYPE GetMaximumFrameLatency(UINT* n) override { if (n) *n = 2; return S_OK; } + HRESULT STDMETHODCALLTYPE SetMaximumFrameLatency(UINT max_latency) override { + if (max_latency == 0 || max_latency > 16) return E_INVALIDARG; + max_frame_latency_.store(max_latency, std::memory_order_relaxed); + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetMaximumFrameLatency(UINT* n) override { + if (!n) return E_INVALIDARG; + *n = max_frame_latency_.load(std::memory_order_relaxed); + return S_OK; + } HANDLE STDMETHODCALLTYPE GetFrameLatencyWaitableObject() override { return nullptr; } HRESULT STDMETHODCALLTYPE SetMatrixTransform(const DXGI_MATRIX_3X2_F*) override { return S_OK; } HRESULT STDMETHODCALLTYPE GetMatrixTransform(DXGI_MATRIX_3X2_F*) override { return E_NOTIMPL; } @@ -312,10 +340,285 @@ private: } std::atomic refs_{1}; + IDXGIFactory4* parent_ = nullptr; leonida::VulkanContext& context_; leonida::VulkanSwapchain swapchain_; HWND hwnd_ = nullptr; std::vector buffers_; + std::atomic present_count_{0}; + std::atomic max_frame_latency_{2}; +}; + +struct ReservationState { + std::atomic local{0}; + std::atomic non_local{0}; +}; + +// Video-memory reservations are scoped per physical adapter in the process (matching native DXGI, +// where separate IDXGIAdapter3 handles opened for the same LUID observe each other's reservations). +std::shared_ptr adapter_reservation_state(LUID luid, VkPhysicalDevice physical) { + static std::mutex mutex; + static std::map, std::shared_ptr> table; + const bool has_luid = (luid.LowPart != 0 || luid.HighPart != 0); + const auto key = + has_luid ? std::make_tuple(std::uint32_t(luid.LowPart), std::int32_t(luid.HighPart), std::uintptr_t(0)) + : std::make_tuple(std::uint32_t(0), std::int32_t(0), reinterpret_cast(physical)); + std::lock_guard lock(mutex); + auto& entry = table[key]; + if (!entry) entry = std::make_shared(); + return entry; +} + +// On discrete GPUs without Resizable BAR, Vulkan exposes a second smaller DEVICE_LOCAL heap for the +// CPU-visible BAR1 aperture (typically 256 MiB) that aliases the same physical VRAM as the primary heap. +// Pick the largest DEVICE_LOCAL heap so DedicatedVideoMemory and LOCAL budget/usage match Windows DXGI +// instead of double-counting BAR1. +std::uint32_t primary_device_local_heap(const VkPhysicalDeviceMemoryProperties& mem) { + std::uint32_t best = UINT32_MAX; + VkDeviceSize best_size = 0; + for (std::uint32_t i = 0; i < mem.memoryHeapCount; ++i) { + if ((mem.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) continue; + if (best == UINT32_MAX || mem.memoryHeaps[i].size > best_size) { + best = i; + best_size = mem.memoryHeaps[i].size; + } + } + return best; +} + +// Vulkan-backed IDXGIAdapter3 reporting the physical device's name, IDs, LUID (matching +// ID3D12Device::GetAdapterLuid), memory heap sizes, and video memory budget info. +class Adapter final : public IDXGIAdapter3 { +public: + Adapter(IDXGIFactory4* parent, PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical) + : parent_(parent), gipa_(gipa), instance_(instance), physical_(physical) { + if (parent_) parent_->AddRef(); + populate_desc(); + reservations_ = adapter_reservation_state(desc_.AdapterLuid, physical_); + } + + ~Adapter() { + if (parent_) parent_->Release(); + } + + LUID luid() const { return desc_.AdapterLuid; } + + // IUnknown + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG left = --refs_; + if (!left) delete this; + return left; + } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (riid == __uuidof(IUnknown) || riid == __uuidof(IDXGIObject) || riid == __uuidof(IDXGIAdapter) || + riid == __uuidof(IDXGIAdapter1) || riid == __uuidof(IDXGIAdapter2) || riid == __uuidof(IDXGIAdapter3)) { + *out = static_cast(this); + AddRef(); + return S_OK; + } + return E_NOINTERFACE; + } + + // IDXGIObject + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } + HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!parent_) return E_NOINTERFACE; + return parent_->QueryInterface(riid, out); + } + + // IDXGIAdapter + HRESULT STDMETHODCALLTYPE EnumOutputs(UINT, IDXGIOutput** out) override { + if (out) *out = nullptr; + return DXGI_ERROR_NOT_FOUND; + } + HRESULT STDMETHODCALLTYPE GetDesc(DXGI_ADAPTER_DESC* desc) override { + if (!desc) return E_INVALIDARG; + std::memcpy(desc->Description, desc_.Description, sizeof(desc->Description)); + desc->VendorId = desc_.VendorId; + desc->DeviceId = desc_.DeviceId; + desc->SubSysId = desc_.SubSysId; + desc->Revision = desc_.Revision; + desc->DedicatedVideoMemory = desc_.DedicatedVideoMemory; + desc->DedicatedSystemMemory = desc_.DedicatedSystemMemory; + desc->SharedSystemMemory = desc_.SharedSystemMemory; + desc->AdapterLuid = desc_.AdapterLuid; + return S_OK; + } + HRESULT STDMETHODCALLTYPE CheckInterfaceSupport(REFGUID interface_name, LARGE_INTEGER* umd_version) override { + if (interface_name == __uuidof(IDXGIDevice)) { + if (umd_version) umd_version->QuadPart = 0; + return S_OK; + } + return DXGI_ERROR_UNSUPPORTED; + } + + // IDXGIAdapter1 + HRESULT STDMETHODCALLTYPE GetDesc1(DXGI_ADAPTER_DESC1* desc) override { + if (!desc) return E_INVALIDARG; + std::memcpy(desc->Description, desc_.Description, sizeof(desc->Description)); + desc->VendorId = desc_.VendorId; + desc->DeviceId = desc_.DeviceId; + desc->SubSysId = desc_.SubSysId; + desc->Revision = desc_.Revision; + desc->DedicatedVideoMemory = desc_.DedicatedVideoMemory; + desc->DedicatedSystemMemory = desc_.DedicatedSystemMemory; + desc->SharedSystemMemory = desc_.SharedSystemMemory; + desc->AdapterLuid = desc_.AdapterLuid; + desc->Flags = desc_.Flags; + return S_OK; + } + + // IDXGIAdapter2 + HRESULT STDMETHODCALLTYPE GetDesc2(DXGI_ADAPTER_DESC2* desc) override { + if (!desc) return E_INVALIDARG; + *desc = desc_; + return S_OK; + } + + // IDXGIAdapter3 + HRESULT STDMETHODCALLTYPE RegisterHardwareContentProtectionTeardownStatusEvent(HANDLE, DWORD* cookie) override { + if (cookie) *cookie = 0; + return E_NOTIMPL; + } + void STDMETHODCALLTYPE UnregisterHardwareContentProtectionTeardownStatus(DWORD) override {} + HRESULT STDMETHODCALLTYPE QueryVideoMemoryInfo(UINT node_index, DXGI_MEMORY_SEGMENT_GROUP group, + DXGI_QUERY_VIDEO_MEMORY_INFO* info) override { + if (node_index != 0 || !info) return E_INVALIDARG; + if (group != DXGI_MEMORY_SEGMENT_GROUP_LOCAL && group != DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL) + return E_INVALIDARG; + std::memset(info, 0, sizeof(*info)); + const bool want_local = (group == DXGI_MEMORY_SEGMENT_GROUP_LOCAL); + if (has_memory_budget_ && gipa_ && instance_ && physical_) { + if (const auto get_mem2 = reinterpret_cast( + gipa_(instance_, "vkGetPhysicalDeviceMemoryProperties2"))) { + VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT}; + VkPhysicalDeviceMemoryProperties2 mem2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, &budget}; + get_mem2(physical_, &mem2); + const auto& mem = mem2.memoryProperties; + if (want_local) { + const std::uint32_t local_heap = primary_device_local_heap(mem); + if (local_heap != UINT32_MAX) { + info->Budget = budget.heapBudget[local_heap]; + info->CurrentUsage = budget.heapUsage[local_heap]; + } + } else { + for (std::uint32_t i = 0; i < mem.memoryHeapCount; ++i) { + if ((mem.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) { + info->Budget += budget.heapBudget[i]; + info->CurrentUsage += budget.heapUsage[i]; + } + } + } + } + } + if (info->Budget == 0) { + info->Budget = want_local ? desc_.DedicatedVideoMemory : desc_.SharedSystemMemory; + } + info->AvailableForReservation = info->Budget / 2; + info->CurrentReservation = want_local ? reservations_->local.load(std::memory_order_relaxed) + : reservations_->non_local.load(std::memory_order_relaxed); + return S_OK; + } + HRESULT STDMETHODCALLTYPE SetVideoMemoryReservation(UINT node_index, DXGI_MEMORY_SEGMENT_GROUP group, + UINT64 reservation) override { + if (node_index != 0) return E_INVALIDARG; + if (group == DXGI_MEMORY_SEGMENT_GROUP_LOCAL) { + reservations_->local.store(reservation, std::memory_order_relaxed); + return S_OK; + } + if (group == DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL) { + reservations_->non_local.store(reservation, std::memory_order_relaxed); + return S_OK; + } + return E_INVALIDARG; + } + HRESULT STDMETHODCALLTYPE RegisterVideoMemoryBudgetChangeNotificationEvent(HANDLE, DWORD* cookie) override { + if (cookie) *cookie = 0; + return E_NOTIMPL; + } + void STDMETHODCALLTYPE UnregisterVideoMemoryBudgetChangeNotification(DWORD) override {} + +private: + void populate_desc() { + std::memset(&desc_, 0, sizeof(desc_)); + desc_.GraphicsPreemptionGranularity = DXGI_GRAPHICS_PREEMPTION_DMA_BUFFER_BOUNDARY; + desc_.ComputePreemptionGranularity = DXGI_COMPUTE_PREEMPTION_DMA_BUFFER_BOUNDARY; + if (!gipa_ || !instance_ || !physical_) return; + + VkPhysicalDeviceProperties props{}; + bool got_props = false; + if (const auto get_props2 = reinterpret_cast( + gipa_(instance_, "vkGetPhysicalDeviceProperties2"))) { + VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; + VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; + get_props2(physical_, &props2); + props = props2.properties; + got_props = true; + static_assert(sizeof(LUID) == VK_LUID_SIZE); + if (id.deviceLUIDValid) std::memcpy(&desc_.AdapterLuid, id.deviceLUID, sizeof(LUID)); + } else if (const auto get_props = reinterpret_cast( + gipa_(instance_, "vkGetPhysicalDeviceProperties"))) { + get_props(physical_, &props); + got_props = true; + } + if (got_props) { + MultiByteToWideChar(CP_UTF8, 0, props.deviceName, -1, desc_.Description, + static_cast(std::size(desc_.Description) - 1)); + desc_.Description[std::size(desc_.Description) - 1] = L'\0'; + desc_.VendorId = props.vendorID; + desc_.DeviceId = props.deviceID; + desc_.Revision = props.driverVersion; + if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) desc_.Flags = DXGI_ADAPTER_FLAG_SOFTWARE; + } + + if (const auto get_mem = reinterpret_cast( + gipa_(instance_, "vkGetPhysicalDeviceMemoryProperties"))) { + VkPhysicalDeviceMemoryProperties mem{}; + get_mem(physical_, &mem); + const std::uint32_t local_heap = primary_device_local_heap(mem); + const std::uint64_t dedicated = (local_heap != UINT32_MAX) ? mem.memoryHeaps[local_heap].size : 0; + std::uint64_t shared = 0; + for (std::uint32_t i = 0; i < mem.memoryHeapCount; ++i) { + if ((mem.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) + shared += mem.memoryHeaps[i].size; + } + desc_.DedicatedVideoMemory = static_cast(dedicated); + desc_.SharedSystemMemory = static_cast(shared); + } + + if (const auto enum_exts = reinterpret_cast( + gipa_(instance_, "vkEnumerateDeviceExtensionProperties"))) { + std::uint32_t count = 0; + if (enum_exts(physical_, nullptr, &count, nullptr) == VK_SUCCESS && count > 0) { + std::vector exts(count); + if (enum_exts(physical_, nullptr, &count, exts.data()) == VK_SUCCESS) { + for (const auto& e : exts) { + if (std::strcmp(e.extensionName, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME) == 0) { + has_memory_budget_ = true; + break; + } + } + } + } + } + } + + std::atomic refs_{1}; + IDXGIFactory4* parent_ = nullptr; + PFN_vkGetInstanceProcAddr gipa_ = nullptr; + VkInstance instance_ = VK_NULL_HANDLE; + VkPhysicalDevice physical_ = VK_NULL_HANDLE; + DXGI_ADAPTER_DESC2 desc_{}; + bool has_memory_budget_ = false; + std::shared_ptr reservations_; }; class Factory final : public IDXGIFactory4 { @@ -351,7 +654,14 @@ public: HRESULT STDMETHODCALLTYPE GetParent(REFIID, void**) override { return E_NOTIMPL; } // IDXGIFactory - HRESULT STDMETHODCALLTYPE EnumAdapters(UINT, IDXGIAdapter**) override { return DXGI_ERROR_NOT_FOUND; } + HRESULT STDMETHODCALLTYPE EnumAdapters(UINT index, IDXGIAdapter** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (index != 0) return DXGI_ERROR_NOT_FOUND; + auto* adapter = new Adapter(this, gipa_, instance_, physical_); + *out = static_cast(adapter); + return S_OK; + } HRESULT STDMETHODCALLTYPE MakeWindowAssociation(HWND hwnd, UINT) override { assoc_hwnd_ = hwnd; return S_OK; } HRESULT STDMETHODCALLTYPE GetWindowAssociation(HWND* hwnd) override { if (!hwnd) return E_INVALIDARG; @@ -365,7 +675,14 @@ public: HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(HMODULE, IDXGIAdapter**) override { return E_NOTIMPL; } // IDXGIFactory1 - HRESULT STDMETHODCALLTYPE EnumAdapters1(UINT, IDXGIAdapter1**) override { return DXGI_ERROR_NOT_FOUND; } + HRESULT STDMETHODCALLTYPE EnumAdapters1(UINT index, IDXGIAdapter1** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (index != 0) return DXGI_ERROR_NOT_FOUND; + auto* adapter = new Adapter(this, gipa_, instance_, physical_); + *out = static_cast(adapter); + return S_OK; + } BOOL STDMETHODCALLTYPE IsCurrent() override { return TRUE; } // IDXGIFactory2 @@ -376,7 +693,7 @@ public: if (!out) return E_POINTER; *out = nullptr; if (!hwnd || !desc) return E_INVALIDARG; - auto* sc = new SwapChain(context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_); + auto* sc = new SwapChain(this, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_); if (!sc->init(hwnd, *desc)) { sc->Release(); return E_FAIL; @@ -404,7 +721,19 @@ public: UINT STDMETHODCALLTYPE GetCreationFlags() override { return 0; } // IDXGIFactory4 - HRESULT STDMETHODCALLTYPE EnumAdapterByLuid(LUID, REFIID, void**) override { return DXGI_ERROR_NOT_FOUND; } + HRESULT STDMETHODCALLTYPE EnumAdapterByLuid(LUID luid, REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + auto* adapter = new Adapter(this, gipa_, instance_, physical_); + const LUID actual = adapter->luid(); + if (actual.LowPart != luid.LowPart || actual.HighPart != luid.HighPart) { + adapter->Release(); + return DXGI_ERROR_NOT_FOUND; + } + const HRESULT hr = adapter->QueryInterface(riid, out); + adapter->Release(); + return hr; + } HRESULT STDMETHODCALLTYPE EnumWarpAdapter(REFIID, void**) override { return DXGI_ERROR_NOT_FOUND; } private: diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index dff35d5b2..77a478a1a 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -642,7 +642,8 @@ public: // Copies. The rules D3D12 states for the call itself are checked here; ranges against the resources are // checked at replay, when the resources are known. bool copy_buffer(const CopyBuffer& copy) { - if (!copy.dst || !copy.src || !copy.size) return false; + if (!copy.dst || !copy.src) return false; + if (!copy.size) return !closed_; // Native D3D12 accepts a zero-byte CopyBufferRegion as a no-op. return append(copy); } diff --git a/runtime/src/depth24_convert.comp b/runtime/src/depth24_convert.comp index eb4795a35..688f68d78 100644 --- a/runtime/src/depth24_convert.comp +++ b/runtime/src/depth24_convert.comp @@ -36,10 +36,11 @@ float depth24_to_float(uint d) { // The 24-bit UNORM of f as WARP and AMD's D3D12 drivers write it: the product with 2^24 - 1 is rounded to a float // first, then to the nearest integer with ties to even (NVIDIA's hardware breaks some ties the other way; see // depth24.h). NaN and negatives give 0, 1 and above the maximum. -uint depth24_from_float(float f) { - if (!(f > 0.0)) return 0u; - if (f >= 1.0) return 0xffffffu; - return uint(roundEven(f * 16777215.0)); +uint depth24_from_bits(uint bits) { + // In unsigned order, all negative encodings and positive NaNs lie above positive infinity. + if (bits > 0x7f800000u) return 0u; + if (bits >= 0x3f800000u) return 0xffffffu; + return uint(roundEven(uintBitsToFloat(bits) * 16777215.0)); } void main() { @@ -48,5 +49,5 @@ void main() { uint a = pc.app_base + g.z * pc.app_slice + g.y * pc.app_row + g.x; uint s = pc.scratch_base + (g.z * pc.height + g.y) * pc.width + g.x; if (pc.to_float != 0u) scratch[s] = floatBitsToUint(depth24_to_float(app[a] & 0xffffffu)); - else app[a] = depth24_from_float(uintBitsToFloat(scratch[s])); + else app[a] = depth24_from_bits(scratch[s]); } diff --git a/runtime/src/depth24_convert.inc b/runtime/src/depth24_convert.inc index a237a5af4..9438af65b 100644 --- a/runtime/src/depth24_convert.inc +++ b/runtime/src/depth24_convert.inc @@ -27,17 +27,18 @@ 0x00000000,0x00000023,0x00000000,0x00040047, 0x000000a7,0x00000021,0x00000000,0x00040047, 0x000000a7,0x00000022,0x00000000,0x00040047, -0x000000bb,0x0000000b,0x00000019,0x00020013, +0x000000ba,0x0000000b,0x00000019,0x00020013, 0x00000002,0x00030021,0x00000003,0x00000002, 0x00040015,0x00000006,0x00000020,0x00000000, 0x00030016,0x00000008,0x00000020,0x0004002b, -0x00000006,0x00000013,0x00000000,0x00020014, -0x00000014,0x0004002b,0x00000008,0x00000018, -0x00000000,0x00040015,0x0000001a,0x00000020, -0x00000001,0x0004002b,0x0000001a,0x00000021, -0x00000017,0x0004002b,0x00000006,0x00000027, -0x00000001,0x0004002b,0x00000008,0x0000003c, -0x3f800000,0x0004002b,0x00000006,0x00000040, +0x00000006,0x00000012,0x00000000,0x00020014, +0x00000013,0x0004002b,0x00000008,0x00000017, +0x00000000,0x00040015,0x00000019,0x00000020, +0x00000001,0x0004002b,0x00000019,0x00000020, +0x00000017,0x0004002b,0x00000006,0x00000026, +0x00000001,0x0004002b,0x00000006,0x00000035, +0x7f800000,0x0004002b,0x00000006,0x0000003b, +0x3f800000,0x0004002b,0x00000006,0x0000003f, 0x00ffffff,0x0004002b,0x00000008,0x00000043, 0x4b7fffff,0x00040017,0x00000049,0x00000006, 0x00000003,0x00040020,0x0000004c,0x00000001, @@ -47,15 +48,15 @@ 0x00000006,0x00000006,0x00000006,0x00040020, 0x00000052,0x00000009,0x00000051,0x0004003b, 0x00000052,0x00000053,0x00000009,0x0004002b, -0x0000001a,0x00000054,0x00000000,0x00040020, +0x00000019,0x00000054,0x00000000,0x00040020, 0x00000055,0x00000009,0x00000006,0x0004002b, -0x0000001a,0x0000005e,0x00000001,0x0004002b, -0x0000001a,0x00000069,0x00000002,0x0004002b, -0x0000001a,0x00000072,0x00000004,0x0004002b, -0x0000001a,0x00000077,0x00000006,0x0004002b, -0x0000001a,0x0000007e,0x00000005,0x0004002b, -0x0000001a,0x00000087,0x00000007,0x0004002b, -0x0000001a,0x00000099,0x00000003,0x0003001d, +0x00000019,0x0000005e,0x00000001,0x0004002b, +0x00000019,0x00000069,0x00000002,0x0004002b, +0x00000019,0x00000072,0x00000004,0x0004002b, +0x00000019,0x00000077,0x00000006,0x0004002b, +0x00000019,0x0000007e,0x00000005,0x0004002b, +0x00000019,0x00000087,0x00000007,0x0004002b, +0x00000019,0x00000099,0x00000003,0x0003001d, 0x0000009f,0x00000006,0x0003001e,0x000000a0, 0x0000009f,0x00040020,0x000000a1,0x0000000c, 0x000000a0,0x0004003b,0x000000a1,0x000000a2, @@ -64,43 +65,43 @@ 0x000000a6,0x0000000c,0x000000a5,0x0004003b, 0x000000a6,0x000000a7,0x0000000c,0x00040020, 0x000000a9,0x0000000c,0x00000006,0x0004002b, -0x00000006,0x000000ba,0x00000008,0x0006002c, -0x00000049,0x000000bb,0x000000ba,0x000000ba, -0x00000027,0x0004002b,0x0000001a,0x00000109, +0x00000006,0x000000b9,0x00000008,0x0006002c, +0x00000049,0x000000ba,0x000000b9,0x000000b9, +0x00000026,0x0004002b,0x00000019,0x00000109, 0x00000050,0x00050036,0x00000002,0x00000004, 0x00000000,0x00000003,0x000200f8,0x00000005, -0x000300f7,0x000000bc,0x00000000,0x000300fb, -0x00000013,0x000000bd,0x000200f8,0x000000bd, +0x000300f7,0x000000bb,0x00000000,0x000300fb, +0x00000012,0x000000bc,0x000200f8,0x000000bc, 0x0004003d,0x00000049,0x0000004e,0x0000004d, 0x00050051,0x00000006,0x00000050,0x0000004e, 0x00000000,0x00050041,0x00000055,0x00000056, 0x00000053,0x00000054,0x0004003d,0x00000006, -0x00000057,0x00000056,0x000500ae,0x00000014, +0x00000057,0x00000056,0x000500ae,0x00000013, 0x00000058,0x00000050,0x00000057,0x000400a8, -0x00000014,0x00000059,0x00000058,0x000300f7, +0x00000013,0x00000059,0x00000058,0x000300f7, 0x0000005b,0x00000000,0x000400fa,0x00000059, 0x0000005a,0x0000005b,0x000200f8,0x0000005a, 0x00050051,0x00000006,0x0000005d,0x0000004e, 0x00000001,0x00050041,0x00000055,0x0000005f, 0x00000053,0x0000005e,0x0004003d,0x00000006, -0x00000060,0x0000005f,0x000500ae,0x00000014, +0x00000060,0x0000005f,0x000500ae,0x00000013, 0x00000061,0x0000005d,0x00000060,0x000200f9, 0x0000005b,0x000200f8,0x0000005b,0x000700f5, -0x00000014,0x00000062,0x00000058,0x000000bd, -0x00000061,0x0000005a,0x000400a8,0x00000014, +0x00000013,0x00000062,0x00000058,0x000000bc, +0x00000061,0x0000005a,0x000400a8,0x00000013, 0x00000063,0x00000062,0x000300f7,0x00000065, 0x00000000,0x000400fa,0x00000063,0x00000064, 0x00000065,0x000200f8,0x00000064,0x00050051, 0x00000006,0x00000068,0x0000004e,0x00000002, 0x00050041,0x00000055,0x0000006a,0x00000053, 0x00000069,0x0004003d,0x00000006,0x0000006b, -0x0000006a,0x000500ae,0x00000014,0x0000006c, +0x0000006a,0x000500ae,0x00000013,0x0000006c, 0x00000068,0x0000006b,0x000200f9,0x00000065, -0x000200f8,0x00000065,0x000700f5,0x00000014, +0x000200f8,0x00000065,0x000700f5,0x00000013, 0x0000006d,0x00000062,0x0000005b,0x0000006c, 0x00000064,0x000300f7,0x0000006f,0x00000000, 0x000400fa,0x0000006d,0x0000006e,0x0000006f, -0x000200f8,0x0000006e,0x000200f9,0x000000bc, +0x000200f8,0x0000006e,0x000200f9,0x000000bb, 0x000200f8,0x0000006f,0x00050041,0x00000055, 0x00000073,0x00000053,0x00000072,0x0004003d, 0x00000006,0x00000074,0x00000073,0x00050051, @@ -130,63 +131,63 @@ 0x00000098,0x00000095,0x00000050,0x00050041, 0x00000055,0x0000009a,0x00000053,0x00000099, 0x0004003d,0x00000006,0x0000009b,0x0000009a, -0x000500ab,0x00000014,0x0000009c,0x0000009b, -0x00000013,0x000300f7,0x0000009e,0x00000000, +0x000500ab,0x00000013,0x0000009c,0x0000009b, +0x00000012,0x000300f7,0x0000009e,0x00000000, 0x000400fa,0x0000009c,0x0000009d,0x000000b1, 0x000200f8,0x0000009d,0x00060041,0x000000a9, 0x000000aa,0x000000a7,0x00000054,0x00000085, 0x0004003d,0x00000006,0x000000ab,0x000000aa, 0x000500c7,0x00000006,0x000000ac,0x000000ab, -0x00000040,0x000300f7,0x000000e8,0x00000000, -0x000300fb,0x00000013,0x000000d2,0x000200f8, -0x000000d2,0x000500aa,0x00000014,0x000000d4, -0x000000ac,0x00000013,0x000300f7,0x000000d6, +0x0000003f,0x000300f7,0x000000e8,0x00000000, +0x000300fb,0x00000012,0x000000d2,0x000200f8, +0x000000d2,0x000500aa,0x00000013,0x000000d4, +0x000000ac,0x00000012,0x000300f7,0x000000d6, 0x00000000,0x000400fa,0x000000d4,0x000000d5, 0x000000d6,0x000200f8,0x000000d5,0x000200f9, 0x000000e8,0x000200f8,0x000000d6,0x0006000c, -0x0000001a,0x000000d8,0x00000001,0x0000004b, -0x000000ac,0x00050082,0x0000001a,0x000000db, -0x00000021,0x000000d8,0x0004007c,0x00000006, +0x00000019,0x000000d8,0x00000001,0x0000004b, +0x000000ac,0x00050082,0x00000019,0x000000db, +0x00000020,0x000000d8,0x0004007c,0x00000006, 0x000000dc,0x000000db,0x000500c4,0x00000006, 0x000000dd,0x000000ac,0x000000dc,0x00050080, -0x00000006,0x000000df,0x000000dd,0x00000027, +0x00000006,0x000000df,0x000000dd,0x00000026, 0x00040070,0x00000008,0x000000e0,0x000000df, -0x00050080,0x0000001a,0x000000e3,0x000000d8, +0x00050080,0x00000019,0x000000e3,0x000000d8, 0x00000109,0x0004007c,0x00000006,0x000000e4, 0x000000e3,0x000500c4,0x00000006,0x000000e5, -0x000000e4,0x00000021,0x0004007c,0x00000008, +0x000000e4,0x00000020,0x0004007c,0x00000008, 0x000000e6,0x000000e5,0x00050085,0x00000008, 0x000000e7,0x000000e0,0x000000e6,0x000200f9, 0x000000e8,0x000200f8,0x000000e8,0x000700f5, -0x00000008,0x00000108,0x00000018,0x000000d5, +0x00000008,0x00000108,0x00000017,0x000000d5, 0x000000e7,0x000000d6,0x0004007c,0x00000006, 0x000000af,0x00000108,0x00060041,0x000000a9, 0x000000b0,0x000000a2,0x00000054,0x00000098, 0x0003003e,0x000000b0,0x000000af,0x000200f9, 0x0000009e,0x000200f8,0x000000b1,0x00060041, -0x000000a9,0x000000b4,0x000000a2,0x00000054, -0x00000098,0x0004003d,0x00000006,0x000000b5, -0x000000b4,0x0004007c,0x00000008,0x000000b6, +0x000000a9,0x000000b5,0x000000a2,0x00000054, +0x00000098,0x0004003d,0x00000006,0x000000b6, 0x000000b5,0x000300f7,0x000000fc,0x00000000, -0x000300fb,0x00000013,0x000000ee,0x000200f8, -0x000000ee,0x000500bd,0x00000014,0x000000f1, -0x000000b6,0x00000018,0x000300f7,0x000000f3, -0x00000000,0x000400fa,0x000000f1,0x000000f2, -0x000000f3,0x000200f8,0x000000f2,0x000200f9, -0x000000fc,0x000200f8,0x000000f3,0x000500be, -0x00000014,0x000000f5,0x000000b6,0x0000003c, -0x000300f7,0x000000f7,0x00000000,0x000400fa, -0x000000f5,0x000000f6,0x000000f7,0x000200f8, -0x000000f6,0x000200f9,0x000000fc,0x000200f8, -0x000000f7,0x00050085,0x00000008,0x000000f9, -0x000000b6,0x00000043,0x0006000c,0x00000008, +0x000300fb,0x00000012,0x000000ee,0x000200f8, +0x000000ee,0x000500ac,0x00000013,0x000000f0, +0x000000b6,0x00000035,0x000300f7,0x000000f2, +0x00000000,0x000400fa,0x000000f0,0x000000f1, +0x000000f2,0x000200f8,0x000000f1,0x000200f9, +0x000000fc,0x000200f8,0x000000f2,0x000500ae, +0x00000013,0x000000f4,0x000000b6,0x0000003b, +0x000300f7,0x000000f6,0x00000000,0x000400fa, +0x000000f4,0x000000f5,0x000000f6,0x000200f8, +0x000000f5,0x000200f9,0x000000fc,0x000200f8, +0x000000f6,0x0004007c,0x00000008,0x000000f8, +0x000000b6,0x00050085,0x00000008,0x000000f9, +0x000000f8,0x00000043,0x0006000c,0x00000008, 0x000000fa,0x00000001,0x00000002,0x000000f9, 0x0004006d,0x00000006,0x000000fb,0x000000fa, 0x000200f9,0x000000fc,0x000200f8,0x000000fc, -0x000900f5,0x00000006,0x00000107,0x00000013, -0x000000f2,0x00000040,0x000000f6,0x000000fb, -0x000000f7,0x00060041,0x000000a9,0x000000b9, +0x000900f5,0x00000006,0x00000107,0x00000012, +0x000000f1,0x0000003f,0x000000f5,0x000000fb, +0x000000f6,0x00060041,0x000000a9,0x000000b8, 0x000000a7,0x00000054,0x00000085,0x0003003e, -0x000000b9,0x00000107,0x000200f9,0x0000009e, -0x000200f8,0x0000009e,0x000200f9,0x000000bc, -0x000200f8,0x000000bc,0x000100fd,0x00010038} +0x000000b8,0x00000107,0x000200f9,0x0000009e, +0x000200f8,0x0000009e,0x000200f9,0x000000bb, +0x000200f8,0x000000bb,0x000100fd,0x00010038} diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index 39f967460..ad3605d4e 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -556,7 +556,8 @@ inline constexpr VkSamplerReductionMode vulkan_reduction_mode(FilterMode mode) { // MIP_FILTER_NONE samples the base level only, which Vulkan expresses as nearest mip filtering with the LOD held // in [0, 0.25] (the Vulkan specification's note on samplers without mipmapping). An unnormalised sampler gets // what Vulkan requires of one: no mips, no anisotropy, no comparison. -inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler) { +// A decoded GFX10 bias has absolute value at most 32. When creating a device sampler, pass its smaller limit. +inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_bias = 32.0f) { static_assert(int(CompareFunction::never) == int(VK_COMPARE_OP_NEVER) && int(CompareFunction::less) == int(VK_COMPARE_OP_LESS) && int(CompareFunction::equal) == int(VK_COMPARE_OP_EQUAL) && @@ -576,7 +577,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler) { info.addressModeU = vulkan_address_mode(sampler.address_u); info.addressModeV = vulkan_address_mode(sampler.address_v); info.addressModeW = vulkan_address_mode(sampler.address_w); - info.mipLodBias = sampler.lod_bias; + info.mipLodBias = std::clamp(sampler.lod_bias, -max_lod_bias, max_lod_bias); info.anisotropyEnable = sampler.max_anisotropy > 1 ? VK_TRUE : VK_FALSE; info.maxAnisotropy = float(std::max(sampler.max_anisotropy, 1u)); info.compareEnable = (sampler.compare_never || sampler.compare != CompareFunction::never) ? VK_TRUE : VK_FALSE; diff --git a/runtime/src/predicate_reduce.comp b/runtime/src/predicate_reduce.comp new file mode 100644 index 000000000..86b07d67f --- /dev/null +++ b/runtime/src/predicate_reduce.comp @@ -0,0 +1,6 @@ +// Synthetic internal shader: one invocation captures a D3D12 64-bit predicate as a Vulkan condition. +#version 450 +layout(local_size_x=1) in; +layout(set=0,binding=0,std430) buffer Words { uint words[]; } data; +layout(push_constant) uniform Index { uint base; } index; +void main() { data.words[index.base+2] = data.words[index.base] | data.words[index.base+1]; } diff --git a/runtime/src/predicate_reduce_spv.h b/runtime/src/predicate_reduce_spv.h new file mode 100644 index 000000000..2d703597f --- /dev/null +++ b/runtime/src/predicate_reduce_spv.h @@ -0,0 +1,36 @@ +// Generated with glslang 16.6.0: +// glslang -V --target-env vulkan1.1 -Os --spirv-val predicate_reduce.comp -o predicate_reduce.spv +#pragma once +#include +namespace leonida { +inline constexpr std::uint32_t predicate_reduce_spirv[] = { + 0x07230203u, 0x00010300u, 0x0008000bu, 0x00000024u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, + 0x0005000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060010u, 0x00000004u, 0x00000011u, + 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, + 0x6e69616du, 0x00000000u, 0x00040005u, 0x00000008u, 0x64726f57u, 0x00000073u, 0x00050006u, 0x00000008u, + 0x00000000u, 0x64726f77u, 0x00000073u, 0x00040005u, 0x0000000au, 0x61746164u, 0x00000000u, 0x00040005u, + 0x0000000du, 0x65646e49u, 0x00000078u, 0x00050006u, 0x0000000du, 0x00000000u, 0x65736162u, 0x00000000u, + 0x00040005u, 0x0000000fu, 0x65646e69u, 0x00000078u, 0x00040047u, 0x00000007u, 0x00000006u, 0x00000004u, + 0x00030047u, 0x00000008u, 0x00000002u, 0x00050048u, 0x00000008u, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00040047u, 0x0000000au, 0x00000021u, 0x00000000u, 0x00040047u, 0x0000000au, 0x00000022u, 0x00000000u, + 0x00030047u, 0x0000000du, 0x00000002u, 0x00050048u, 0x0000000du, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00040047u, 0x00000023u, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, + 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x0003001du, 0x00000007u, 0x00000006u, + 0x0003001eu, 0x00000008u, 0x00000007u, 0x00040020u, 0x00000009u, 0x0000000cu, 0x00000008u, 0x0004003bu, + 0x00000009u, 0x0000000au, 0x0000000cu, 0x00040015u, 0x0000000bu, 0x00000020u, 0x00000001u, 0x0004002bu, + 0x0000000bu, 0x0000000cu, 0x00000000u, 0x0003001eu, 0x0000000du, 0x00000006u, 0x00040020u, 0x0000000eu, + 0x00000009u, 0x0000000du, 0x0004003bu, 0x0000000eu, 0x0000000fu, 0x00000009u, 0x00040020u, 0x00000010u, + 0x00000009u, 0x00000006u, 0x0004002bu, 0x00000006u, 0x00000013u, 0x00000002u, 0x00040020u, 0x00000017u, + 0x0000000cu, 0x00000006u, 0x0004002bu, 0x00000006u, 0x0000001cu, 0x00000001u, 0x00040017u, 0x00000022u, + 0x00000006u, 0x00000003u, 0x0006002cu, 0x00000022u, 0x00000023u, 0x0000001cu, 0x0000001cu, 0x0000001cu, + 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u, + 0x00000010u, 0x00000011u, 0x0000000fu, 0x0000000cu, 0x0004003du, 0x00000006u, 0x00000012u, 0x00000011u, + 0x00050080u, 0x00000006u, 0x00000014u, 0x00000012u, 0x00000013u, 0x00060041u, 0x00000017u, 0x00000018u, + 0x0000000au, 0x0000000cu, 0x00000012u, 0x0004003du, 0x00000006u, 0x00000019u, 0x00000018u, 0x00050080u, + 0x00000006u, 0x0000001du, 0x00000012u, 0x0000001cu, 0x00060041u, 0x00000017u, 0x0000001eu, 0x0000000au, + 0x0000000cu, 0x0000001du, 0x0004003du, 0x00000006u, 0x0000001fu, 0x0000001eu, 0x000500c5u, 0x00000006u, + 0x00000020u, 0x00000019u, 0x0000001fu, 0x00060041u, 0x00000017u, 0x00000021u, 0x0000000au, 0x0000000cu, + 0x00000014u, 0x0003003eu, 0x00000021u, 0x00000020u, 0x000100fdu, 0x00010038u, +}; +} diff --git a/runtime/src/predicated_copy.comp b/runtime/src/predicated_copy.comp new file mode 100644 index 000000000..0a105554d --- /dev/null +++ b/runtime/src/predicated_copy.comp @@ -0,0 +1,11 @@ +// Synthetic byte-granular buffer copy, executed inside the captured conditional-rendering scope. +#version 450 +#extension GL_EXT_shader_8bit_storage : require +layout(local_size_x=64) in; +layout(set=0,binding=0,std430) readonly buffer Source { uint8_t bytes[]; } source; +layout(set=0,binding=1,std430) buffer Destination { uint8_t bytes[]; } destination; +layout(push_constant) uniform Copy { uint source_offset; uint destination_offset; uint size; } copy; +void main() { + uint i=gl_GlobalInvocationID.x; + if(i +namespace leonida { inline constexpr std::uint32_t predicated_copy_spirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000037u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x00001160u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, + 0x00000000u, 0x00000001u, 0x0009000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, + 0x00000013u, 0x00000021u, 0x0000002bu, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, + 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00080004u, 0x455f4c47u, 0x735f5458u, 0x65646168u, + 0x62385f72u, 0x735f7469u, 0x61726f74u, 0x00006567u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, + 0x00080005u, 0x0000000bu, 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, + 0x00040005u, 0x00000011u, 0x79706f43u, 0x00000000u, 0x00070006u, 0x00000011u, 0x00000000u, 0x72756f73u, + 0x6f5f6563u, 0x65736666u, 0x00000074u, 0x00080006u, 0x00000011u, 0x00000001u, 0x74736564u, 0x74616e69u, + 0x5f6e6f69u, 0x7366666fu, 0x00007465u, 0x00050006u, 0x00000011u, 0x00000002u, 0x657a6973u, 0x00000000u, + 0x00040005u, 0x00000013u, 0x79706f63u, 0x00000000u, 0x00050005u, 0x0000001fu, 0x74736544u, 0x74616e69u, + 0x006e6f69u, 0x00050006u, 0x0000001fu, 0x00000000u, 0x65747962u, 0x00000073u, 0x00050005u, 0x00000021u, + 0x74736564u, 0x74616e69u, 0x006e6f69u, 0x00040005u, 0x00000029u, 0x72756f53u, 0x00006563u, 0x00050006u, + 0x00000029u, 0x00000000u, 0x65747962u, 0x00000073u, 0x00040005u, 0x0000002bu, 0x72756f73u, 0x00006563u, + 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu, 0x00030047u, 0x00000011u, 0x00000002u, 0x00050048u, + 0x00000011u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000011u, 0x00000001u, 0x00000023u, + 0x00000004u, 0x00050048u, 0x00000011u, 0x00000002u, 0x00000023u, 0x00000008u, 0x00040047u, 0x0000001eu, + 0x00000006u, 0x00000001u, 0x00030047u, 0x0000001fu, 0x00000002u, 0x00050048u, 0x0000001fu, 0x00000000u, + 0x00000023u, 0x00000000u, 0x00040047u, 0x00000021u, 0x00000021u, 0x00000001u, 0x00040047u, 0x00000021u, + 0x00000022u, 0x00000000u, 0x00040047u, 0x00000028u, 0x00000006u, 0x00000001u, 0x00030047u, 0x00000029u, + 0x00000002u, 0x00040048u, 0x00000029u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000029u, 0x00000000u, + 0x00000023u, 0x00000000u, 0x00030047u, 0x0000002bu, 0x00000018u, 0x00040047u, 0x0000002bu, 0x00000021u, + 0x00000000u, 0x00040047u, 0x0000002bu, 0x00000022u, 0x00000000u, 0x00040047u, 0x00000036u, 0x0000000bu, + 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, + 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au, + 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u, + 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x0005001eu, 0x00000011u, + 0x00000006u, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000012u, 0x00000009u, 0x00000011u, 0x0004003bu, + 0x00000012u, 0x00000013u, 0x00000009u, 0x00040015u, 0x00000014u, 0x00000020u, 0x00000001u, 0x0004002bu, + 0x00000014u, 0x00000015u, 0x00000002u, 0x00040020u, 0x00000016u, 0x00000009u, 0x00000006u, 0x00020014u, + 0x00000019u, 0x00040015u, 0x0000001du, 0x00000008u, 0x00000000u, 0x0003001du, 0x0000001eu, 0x0000001du, + 0x0003001eu, 0x0000001fu, 0x0000001eu, 0x00040020u, 0x00000020u, 0x0000000cu, 0x0000001fu, 0x0004003bu, + 0x00000020u, 0x00000021u, 0x0000000cu, 0x0004002bu, 0x00000014u, 0x00000022u, 0x00000000u, 0x0004002bu, + 0x00000014u, 0x00000023u, 0x00000001u, 0x0003001du, 0x00000028u, 0x0000001du, 0x0003001eu, 0x00000029u, + 0x00000028u, 0x00040020u, 0x0000002au, 0x0000000cu, 0x00000029u, 0x0004003bu, 0x0000002au, 0x0000002bu, + 0x0000000cu, 0x00040020u, 0x00000030u, 0x0000000cu, 0x0000001du, 0x0004002bu, 0x00000006u, 0x00000034u, + 0x00000040u, 0x0004002bu, 0x00000006u, 0x00000035u, 0x00000001u, 0x0006002cu, 0x00000009u, 0x00000036u, + 0x00000034u, 0x00000035u, 0x00000035u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, + 0x000200f8u, 0x00000005u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu, 0x0004003du, + 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, 0x00000016u, 0x00000017u, 0x00000013u, 0x00000015u, + 0x0004003du, 0x00000006u, 0x00000018u, 0x00000017u, 0x000500b0u, 0x00000019u, 0x0000001au, 0x0000000fu, + 0x00000018u, 0x000300f7u, 0x0000001cu, 0x00000000u, 0x000400fau, 0x0000001au, 0x0000001bu, 0x0000001cu, + 0x000200f8u, 0x0000001bu, 0x00050041u, 0x00000016u, 0x00000024u, 0x00000013u, 0x00000023u, 0x0004003du, + 0x00000006u, 0x00000025u, 0x00000024u, 0x00050080u, 0x00000006u, 0x00000027u, 0x00000025u, 0x0000000fu, + 0x00050041u, 0x00000016u, 0x0000002cu, 0x00000013u, 0x00000022u, 0x0004003du, 0x00000006u, 0x0000002du, + 0x0000002cu, 0x00050080u, 0x00000006u, 0x0000002fu, 0x0000002du, 0x0000000fu, 0x00060041u, 0x00000030u, + 0x00000031u, 0x0000002bu, 0x00000022u, 0x0000002fu, 0x0004003du, 0x0000001du, 0x00000032u, 0x00000031u, + 0x00060041u, 0x00000030u, 0x00000033u, 0x00000021u, 0x00000022u, 0x00000027u, 0x0003003eu, 0x00000033u, + 0x00000032u, 0x000200f9u, 0x0000001cu, 0x000200f8u, 0x0000001cu, 0x000100fdu, 0x00010038u, +}; } diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h index 73ec54dea..a27da8d7a 100644 --- a/runtime/src/uav_clear.h +++ b/runtime/src/uav_clear.h @@ -8,10 +8,13 @@ // and ...Float, which the D3D12 methods keep): // - Uint copies the low n bits of value i into channel i, where n is the channel's width, with no conversion, // whatever the format's type: 0x3f800000 into an R32_FLOAT channel is 1.0, 0xff into an R8_UNORM one is 1.0. -// A raw or structured buffer view takes value 0 for every 32-bit word. +// A raw or structured buffer view takes value 0 for every 32-bit word. R9G9B9E5_SHAREDEXP has no independent +// per-channel integer bit layout and WARP clears it to 0 for any uint input. // - Float converts to the format: UNORM and SNORM clamp to [0, 1] / [-1, 1] and round to nearest (NaN is 0); // 16-bit and the packed 11/10-bit floats round toward zero, a finite value too large becoming the largest finite // (D3D11.3 3.2.2; WARP and NVIDIA agree), and the small floats have no sign: negative is 0. +// R9G9B9E5_SHAREDEXP clamps negative/NaN to 0 and +Inf/overflow to 65408.0, shares the largest channel's +// exponent and rounds mantissas half-up (bumping the exponent on 512), matching WARP. // D3D11 calls Float on an integer view invalid and D3D12 does not say; here the value is converted to the // integer (rounded toward zero, clamped, NaN is 0) so the result is defined. A raw or structured buffer view // takes value 0's bits. @@ -35,7 +38,7 @@ namespace leonida::uav_clear { -enum class Kind : std::uint8_t { unorm, snorm, uint, sint, sfloat, ufloat }; +enum class Kind : std::uint8_t { unorm, snorm, uint, sint, sfloat, ufloat, shared_exp }; // One channel: where its bits are in the element (little-endian, from bit 0 of byte 0) and how many. struct Channel { @@ -66,6 +69,7 @@ inline constexpr Layout layouts[] = { {VK_FORMAT_A2B10G10R10_UNORM_PACK32, Kind::unorm, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, {VK_FORMAT_A2B10G10R10_UINT_PACK32, Kind::uint, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, {VK_FORMAT_B10G11R11_UFLOAT_PACK32, Kind::ufloat, 4, {{{0, 11}, {11, 11}, {22, 10}, {}}}}, + {VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, Kind::shared_exp, 4, {{{0, 9}, {9, 9}, {18, 9}, {27, 5}}}}, {VK_FORMAT_R8G8B8A8_UNORM, Kind::unorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, {VK_FORMAT_R8G8B8A8_SNORM, Kind::snorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, {VK_FORMAT_R8G8B8A8_UINT, Kind::uint, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, @@ -184,6 +188,33 @@ inline std::uint32_t to_integer(float value, bool is_signed, unsigned bits) { return std::uint32_t(std::clamp(std::trunc(double(value)), 0.0, std::ldexp(1.0, int(bits)) - 1)); } +// Shared-exponent 9:9:9:5 unsigned float (EXT_texture_shared_exponent / D3D11.3). +// Clamps negative and NaN to 0 and overflow/+Inf to 65408.0 ((511/512) * 2^16), shares the largest channel's +// exponent, rounds mantissas half-up (floor(c / denom + 0.5)), and bumps the exponent if the largest mantissa +// rounds to 512. Matches ClearUnorderedAccessViewFloat on WARP. +inline std::uint32_t to_rgb9e5(float r, float g, float b) { + constexpr float max_value = 65408.0f; + const auto clamp_channel = [](float v) { return !(v > 0.0f) ? 0.0f : (v > max_value ? max_value : v); }; + r = clamp_channel(r); + g = clamp_channel(g); + b = clamp_channel(b); + const float max_c = std::max(r, std::max(g, b)); + if (max_c == 0.0f) return 0u; + int exp_raw = 0; + std::frexp(max_c, &exp_raw); // floor(log2(max_c)) == exp_raw - 1 + int exp_shared = std::max(0, exp_raw + 15); + double denom = std::ldexp(1.0, exp_shared - 24); // 2^(exp_shared - 15 - 9) + const int max_m = static_cast(std::floor(double(max_c) / denom + 0.5)); + if (max_m == 512) { + ++exp_shared; + denom *= 2.0; + } + const auto rm = static_cast(std::floor(double(r) / denom + 0.5)); + const auto gm = static_cast(std::floor(double(g) / denom + 0.5)); + const auto bm = static_cast(std::floor(double(b) / denom + 0.5)); + return rm | (gm << 9) | (bm << 18) | (static_cast(exp_shared) << 27); +} + } // namespace detail // The element a clear writes into a view of `format`. `values` are the call's four UINTs, or the bits of its four @@ -193,6 +224,14 @@ inline bool encode(VkFormat format, bool is_float, const std::arraybytes; + if (l->kind == Kind::shared_exp) { + const std::uint32_t word = is_float ? detail::to_rgb9e5(std::bit_cast(values[0]), + std::bit_cast(values[1]), + std::bit_cast(values[2])) + : 0u; + std::memcpy(out.bytes.data(), &word, 4); + return true; + } for (unsigned i = 0; i < 4; ++i) { const Channel c = l->rgba[i]; if (!c.bits) continue; @@ -215,6 +254,7 @@ inline bool encode(VkFormat format, bool is_float, const std::arraybytes != element.size) return false; out = {}; + if (l->kind == Kind::shared_exp) { + std::uint32_t word = 0; + std::memcpy(&word, element.bytes.data(), 4); + const float scale = std::ldexp(1.0f, static_cast(word >> 27) - 24); + out.float32[0] = float(word & 0x1ffu) * scale; + out.float32[1] = float((word >> 9) & 0x1ffu) * scale; + out.float32[2] = float((word >> 18) & 0x1ffu) * scale; + out.float32[3] = 1.0f; + return true; + } for (unsigned i = 0; i < 4; ++i) { const Channel c = l->rgba[i]; if (!c.bits) continue; @@ -246,6 +296,7 @@ inline bool decode(VkFormat format, const Element& element, VkClearColorValue& o } case Kind::sfloat: case Kind::ufloat: out.float32[i] = detail::from_float_bits(raw, *l, c.bits); break; + case Kind::shared_exp: break; } } return true; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index fc4c666a4..8e43cdaa5 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -716,6 +716,17 @@ public: VulkanContext& operator=(const VulkanContext&) = delete; bool loaded() const { return loaded_; } + void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, + VkDeviceSize max_range, std::uint32_t family) { + std::unique_lock lock(resource_mutex_); + predicate_family_ = family; + predicate_reducer_ = std::make_unique(get, device_, memory, max_range); + } + // Configure before submitting work, only when storageBuffer8BitAccess is enabled on the device. + void configure_predicated_copy(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { + std::unique_lock lock(resource_mutex_); + predicated_copier_ = std::make_unique(get, device_, limits); + } VkDevice device() const { return device_; } // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets @@ -966,11 +977,12 @@ private: info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; info.format = r.format; info.subresourceRange = range; - // Reinterpreted RTVs need only color-attachment usage. Inheriting STORAGE usage from the resource - // would incorrectly require it from an sRGB view, even though this view is never used as storage. + // Attachment views need only color-attachment usage. Inheriting STORAGE usage from a mutable/extended + // resource (typeless RGBA8 sRGB views, or R32_UINT-backed R9G9B9E5 UAV images) would require unrelated usages. VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; usage.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - if (r.rgba8_typeless) info.pNext = &usage; + if (r.rgba8_typeless || (range.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT && r.color_attachment)) + info.pNext = &usage; VkImageView view = VK_NULL_HANDLE; if (vk.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return VK_NULL_HANDLE; views_[key] = view; @@ -1002,6 +1014,9 @@ private: double timestamp_period_ = 0; VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; ReplayFunctions replay_; + std::unique_ptr predicate_reducer_; + std::unique_ptr predicated_copier_; + std::uint32_t predicate_family_ = UINT32_MAX; DebugLabelFunctions labels_; }; #ifdef _MSC_VER @@ -1078,7 +1093,7 @@ public: } VulkanQueue(VulkanContext& context, VkQueue queue, std::uint32_t family, QueueKind kind = QueueKind::direct) - : context_(context), queue_(queue), kind_(kind) { + : context_(context), queue_(queue), kind_(kind), family_(family) { auto& vk = context.vk; VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; @@ -1117,18 +1132,67 @@ public: VkCommandBuffer command_buffer = VK_NULL_HANDLE; std::function bindless_commit; // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. - // Shared read-lock allows concurrent prepare() lookups; when depth24_ is active, tracker_mutex_ is also - // acquired before prepare() so Depth24Converter::prepare/collect/retire stay serialized per execution. - // Otherwise tracker_mutex_ is held from emit() through submit() so emit order == submit order across queues. + // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during + // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before + // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. std::shared_lock resource_lock(context_.resource_mutex_); std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); - if (context_.depth24_) { - tracker_lock.lock(); - context_.depth24_->collect(); - } + // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools + // with ticket 0 while tracker_lock is still held. + struct Depth24Guard { + Depth24Converter* d24 = nullptr; + VkSemaphore progress = VK_NULL_HANDLE; + bool active = false; + ~Depth24Guard() { + if (active && d24) d24->retire(progress, 0); + } + } depth24_guard{context_.depth24_.get(), progress_, false}; bindless_commit = context_.bindless_commit_; std::vector prepared(lists.size()); ReplayFunctions replay = context_.replay_; + std::uint64_t captures = 0; + for (const auto* list : lists) + for (const auto& command : list->commands()) + if (const auto* p = std::get_if(&command); p && p->buffer) ++captures; + std::unique_ptr batch; + std::unique_ptr copy_batch; + if (captures) { + if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) + return ReplayResult::unsupported; + // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, + // retaining main's resource -> tracker -> submit lock order through emit and submission. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + batch = context_.predicate_reducer_->batch(captures); + if (!batch) return ReplayResult::unsupported; + replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { + return batch->prepare(buffer, offset, out); + }; + replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { + context_.predicate_reducer_->capture(cb, p); + }; + if (context_.predicated_copier_) { + copy_batch = context_.predicated_copier_->batch(); + replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, + VkDeviceSize dst, VkDeviceSize size, + std::vector& out) { + return copy_batch->prepare(source, destination, src, dst, size, out); + }; + replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector& jobs) { + context_.predicated_copier_->emit(cb, jobs); + }; + } + } + if (context_.depth24_) { + replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, + std::vector& parts) { + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + if (!depth24_guard.active) { + context_.depth24_->collect(); + depth24_guard.active = true; + } + return context_.depth24_->prepare(job, parts); + }; + } const auto& occlusion_memory = context_.occlusion_resolve_memory_; const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; if (can_resolve_occlusion) { @@ -1191,21 +1255,26 @@ public: discard(); return ReplayResult::unsupported; } + if (!tracker_lock.owns_lock()) tracker_lock.lock(); if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; resource_lock.unlock(); - if (tracker_lock.owns_lock()) tracker_lock.unlock(); const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); if (!submitted) discard(); + if (depth24_guard.active) { + context_.depth24_->retire(progress_, 0); + depth24_guard.active = false; + } + tracker_lock.unlock(); if (bindless_commit) bindless_commit(submitted); return ReplayResult::unsupported; } - if (!tracker_lock.owns_lock()) tracker_lock.lock(); + auto next_tracker = context_.tracker_; bool wrote_readback = false; VkPipelineStageFlags2 readback_stages = 0; std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists for (const auto& list : prepared) { - emit(list, command_buffer, replay, &context_.tracker_, &open_labels); + emit(list, command_buffer, replay, &next_tracker, &open_labels); wrote_readback |= list.wrote_readback; readback_stages |= list.readback_src_stages; } @@ -1244,12 +1313,18 @@ public: resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); if (submitted) { + context_.tracker_ = std::move(next_tracker); + slot->predicate = std::move(batch); + slot->predicated_copy = std::move(copy_batch); queries.commit(); slot->segments = std::move(queries.retained); } else { discard(); } - if (context_.depth24_) context_.depth24_->retire(progress_, submitted ? submitted_ : 0); + if (depth24_guard.active) { + context_.depth24_->retire(progress_, submitted ? submitted_ : 0); + depth24_guard.active = false; + } tracker_lock.unlock(); if (bindless_commit) bindless_commit(submitted); return submitted ? ReplayResult::success : ReplayResult::unsupported; @@ -1295,6 +1370,8 @@ private: VkCommandBuffer buffer; std::uint64_t ticket; std::vector> segments; + std::unique_ptr predicated_copy; + std::unique_ptr predicate; // retained until this slot completes }; CommandSlot* acquire() { @@ -1310,6 +1387,8 @@ private: } if (reuse) { if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; + reuse->predicate.reset(); + reuse->predicated_copy.reset(); reuse->ticket = UINT64_MAX; // in use until submitted return reuse; } @@ -1376,6 +1455,7 @@ private: VulkanContext& context_; VkQueue queue_; QueueKind kind_ = QueueKind::direct; + std::uint32_t family_; VkCommandPool pool_ = VK_NULL_HANDLE; VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done std::uint64_t submitted_ = 0; diff --git a/runtime/src/vulkan_predicate.h b/runtime/src/vulkan_predicate.h new file mode 100644 index 000000000..cedb8af81 --- /dev/null +++ b/runtime/src/vulkan_predicate.h @@ -0,0 +1,183 @@ +// GPU snapshot of D3D12's 64-bit predicate. No host readback and no per-predicate queue wait. +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include +#include "predicate_reduce_spv.h" + +namespace leonida { +struct PredicateCapture { + VkBuffer source = VK_NULL_HANDLE; + VkDeviceSize source_offset = 0; + VkBuffer scratch = VK_NULL_HANDLE; + VkDeviceSize offset = 0; // two input words, then the reduced condition + VkDescriptorSet set = VK_NULL_HANDLE; +}; + +class PredicateReducer { +public: + PredicateReducer(PFN_vkGetDeviceProcAddr get, VkDevice device, VkPhysicalDeviceMemoryProperties memory, + VkDeviceSize max_range) : get_(get), device_(device), memory_(memory), max_range_(max_range) {} + ~PredicateReducer() { + if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); + if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); + if (set_layout_) fn("vkDestroyDescriptorSetLayout")(device_, set_layout_, nullptr); + } + PredicateReducer(const PredicateReducer&) = delete; + PredicateReducer& operator=(const PredicateReducer&) = delete; + + // Owned by a command-buffer slot until its timeline ticket completes (or a failed recording is reset). + struct Batch { + PredicateReducer& owner; + VkBuffer buffer = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + VkDescriptorPool pool = VK_NULL_HANDLE; + VkDescriptorSet set = VK_NULL_HANDLE; + VkDeviceSize bytes = 0; + std::uint32_t count = 0, next = 0; + explicit Batch(PredicateReducer& r) : owner(r) {} + ~Batch() { + if (pool) owner.fn("vkDestroyDescriptorPool")(owner.device_, pool, nullptr); + if (buffer) owner.fn("vkDestroyBuffer")(owner.device_, buffer, nullptr); + if (memory) owner.fn("vkFreeMemory")(owner.device_, memory, nullptr); + } + Batch(const Batch&) = delete; + Batch& operator=(const Batch&) = delete; + bool prepare(VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { + if (next >= count || !source) return false; + out = {source, offset, buffer, VkDeviceSize(next++) * 16, set}; + return true; + } + }; + + std::unique_ptr batch(std::uint64_t count) { + // One descriptor starts at offset zero; a push constant selects each aligned 16-byte slot. + if (!count || count > max_range_ / 16 || count > UINT32_MAX / 4 || !make_pipeline()) return {}; + auto b = std::make_unique(*this); + b->count = static_cast(count); + b->bytes = count * 16; + VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + buffer.size = b->bytes; + buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + if (fn("vkCreateBuffer")(device_, &buffer, nullptr, &b->buffer) != VK_SUCCESS) return {}; + VkMemoryRequirements requirements{}; + fn("vkGetBufferMemoryRequirements")(device_, b->buffer, &requirements); + std::uint32_t type = UINT32_MAX; + for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) { + if (!(requirements.memoryTypeBits & (1u << i))) continue; + if (type == UINT32_MAX) type = i; + if (memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { type = i; break; } + } + if (type == UINT32_MAX) return {}; + VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = type; + if (fn("vkAllocateMemory")(device_, &allocation, nullptr, &b->memory) != VK_SUCCESS || + fn("vkBindBufferMemory")(device_, b->buffer, b->memory, 0) != VK_SUCCESS) return {}; + const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; + VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + pool.maxSets = 1; pool.poolSizeCount = 1; pool.pPoolSizes = &size; + if (fn("vkCreateDescriptorPool")(device_, &pool, nullptr, &b->pool) != VK_SUCCESS) return {}; + VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + sets.descriptorPool = b->pool; sets.descriptorSetCount = 1; sets.pSetLayouts = &set_layout_; + if (fn("vkAllocateDescriptorSets")(device_, &sets, &b->set) != VK_SUCCESS) return {}; + const VkDescriptorBufferInfo info{b->buffer, 0, b->bytes}; + VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; + write.dstSet = b->set; write.dstBinding = 0; write.descriptorCount = 1; + write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &info; + fn("vkUpdateDescriptorSets")(device_, 1, &write, 0, nullptr); + return b; + } + + void capture(VkCommandBuffer cb, const PredicateCapture& p) const { + // End an earlier conditional scope before entering this helper: dispatch is itself conditional. + // The descriptor spans the arena, so order all prior accesses before reusing it for another slot. + VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_MEMORY_READ_BIT; + before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + const auto barrier = fn("vkCmdPipelineBarrier"); + barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); + const VkBufferCopy copy{p.source_offset, p.offset, 8}; + fn("vkCmdCopyBuffer")(cb, p.source, p.scratch, 1, ©); + // The application's PREDICATION state does not describe this internal transfer read. Preserve snapshot + // semantics when it subsequently transitions and overwrites the source in the same command list. + VkBufferMemoryBarrier source_done{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; + source_done.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + source_done.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + source_done.srcQueueFamilyIndex = source_done.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + source_done.buffer = p.source; source_done.offset = p.source_offset; source_done.size = 8; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + 0, 0, nullptr, 1, &source_done, 0, nullptr); + VkMemoryBarrier compute{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + compute.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + compute.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &compute, 0, nullptr, 0, nullptr); + fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + fn("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &p.set, 0, nullptr); + const std::uint32_t index = static_cast(p.offset / 4); + fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, 4, &index); + fn("vkCmdDispatch")(cb, 1, 1, 1); + VkMemoryBarrier condition{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + condition.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + condition.dstAccessMask = VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, + 0, 1, &condition, 0, nullptr, 0, nullptr); + } + +private: + template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } + bool make_pipeline() { + if (pipeline_) return true; + // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. + for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", "vkAllocateMemory", + "vkFreeMemory", "vkBindBufferMemory", "vkCreateDescriptorPool", "vkDestroyDescriptorPool", + "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", + "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", + "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", "vkCmdCopyBuffer", + "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) + if (!get_(device_, name)) return false; + VkDescriptorSetLayout set = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkShaderModule shader = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + set_info.bindingCount = 1; set_info.pBindings = &binding; + bool ok = fn("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 4}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; + layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; + ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; + VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module.codeSize = sizeof(predicate_reduce_spirv); module.pCode = predicate_reduce_spirv; + ok = ok && fn("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; + info.layout = layout; + ok = ok && fn("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (shader) fn("vkDestroyShaderModule")(device_, shader, nullptr); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + if (set) fn("vkDestroyDescriptorSetLayout")(device_, set, nullptr); + return false; + } + set_layout_ = set; layout_ = layout; pipeline_ = pipeline; + return true; + } + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceMemoryProperties memory_; + VkDeviceSize max_range_; + VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; +}; +} // namespace leonida diff --git a/runtime/src/vulkan_predicated_copy.h b/runtime/src/vulkan_predicated_copy.h new file mode 100644 index 000000000..6a225ced7 --- /dev/null +++ b/runtime/src/vulkan_predicated_copy.h @@ -0,0 +1,154 @@ +// Byte-granular conditional CopyBufferRegion. Requires enabled storageBuffer8BitAccess, not shaderInt8. +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include +#include +#include +#include "predicated_copy_spv.h" +namespace leonida { +struct PredicatedCopyDispatch { + VkDescriptorSet set = VK_NULL_HANDLE; + std::uint32_t source = 0, destination = 0, bytes = 0; +}; +class PredicatedBufferCopier { +public: + PredicatedBufferCopier(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) + : get_(get), device_(device), limits_(limits) {} + ~PredicatedBufferCopier() { + if(pipeline_)fn("vkDestroyPipeline")(device_,pipeline_,nullptr); + if(layout_)fn("vkDestroyPipelineLayout")(device_,layout_,nullptr); + if(set_layout_)fn("vkDestroyDescriptorSetLayout")(device_,set_layout_,nullptr); + } + PredicatedBufferCopier(const PredicatedBufferCopier&)=delete; + PredicatedBufferCopier& operator=(const PredicatedBufferCopier&)=delete; + struct Batch { + PredicatedBufferCopier& owner; + std::vector pools; + explicit Batch(PredicatedBufferCopier& value):owner(value){} + ~Batch(){for(auto pool:pools)owner.fn("vkDestroyDescriptorPool")(owner.device_,pool,nullptr);} + bool prepare(VkBuffer source,VkBuffer destination,VkDeviceSize src,VkDeviceSize dst,VkDeviceSize bytes, + std::vector& out) { + out.clear(); + if(!bytes)return true; + if(!source||!destination||bytes>UINT64_MAX-src||bytes>UINT64_MAX-dst)return false; + if(source==destination && src windows; + const auto alignment=std::max(1,owner.limits_.minStorageBufferOffsetAlignment); + const VkDeviceSize maximum=owner.limits_.maxStorageBufferRange; + const VkDeviceSize threads=VkDeviceSize(owner.limits_.maxComputeWorkGroupCount[0])*64; + for(VkDeviceSize done=0;done=maximum||dp>=maximum||!threads)return false; + const auto n=std::min({bytes-done,maximum-sp,maximum-dp,threads}); + if(!n||n>UINT32_MAX)return false; + windows.push_back({{source,s-sp,sp+n},{destination,d-dp,dp+n}, + static_cast(sp),static_cast(dp),static_cast(n)}); + if(windows.size()>UINT32_MAX/2)return false; + done+=n; + } + const auto count=static_cast(windows.size()); + const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,count*2}; + VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + pool_info.maxSets=count;pool_info.poolSizeCount=1;pool_info.pPoolSizes=&size; + VkDescriptorPool pool=VK_NULL_HANDLE; + if(owner.fn("vkCreateDescriptorPool")(owner.device_,&pool_info,nullptr,&pool)!=VK_SUCCESS)return false; + // The batch is retained with the command buffer until its timeline ticket completes. + pools.push_back(pool); + const std::vector layouts(count,owner.set_layout_); + std::vector sets(count); + VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + allocate.descriptorPool=pool;allocate.descriptorSetCount=count;allocate.pSetLayouts=layouts.data(); + if(owner.fn("vkAllocateDescriptorSets")(owner.device_,&allocate,sets.data())!=VK_SUCCESS)return false; + for(std::uint32_t i=0;i("vkUpdateDescriptorSets")(owner.device_,2,writes,0,nullptr); + out.push_back({sets[i],windows[i].src,windows[i].dst,windows[i].bytes}); + } + return true; + } + }; + std::unique_ptr batch(){return std::make_unique(*this);} + void emit(VkCommandBuffer cb,const std::vector& jobs)const{ + const auto barrier=fn("vkCmdPipelineBarrier"); + // Barriers are unconditional even when the dispatch is skipped by conditional rendering. They order + // transfer producers, dependent copies, and adjacent windows whose aligned descriptors may overlap. + for(const auto& job:jobs){ + VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + before.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT; + before.dstAccessMask=VK_ACCESS_SHADER_READ_BIT|VK_ACCESS_SHADER_WRITE_BIT; + barrier(cb,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,0,1,&before,0,nullptr,0,nullptr); + fn("vkCmdBindPipeline")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pipeline_); + fn("vkCmdBindDescriptorSets")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,layout_,0,1,&job.set,0,nullptr); + const std::uint32_t push[]={job.source,job.destination,job.bytes}; + fn("vkCmdPushConstants")(cb,layout_,VK_SHADER_STAGE_COMPUTE_BIT,0,sizeof(push),push); + fn("vkCmdDispatch")(cb,(job.bytes-1u)/64u+1u,1,1); + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask=VK_ACCESS_SHADER_WRITE_BIT|VK_ACCESS_SHADER_READ_BIT; + after.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT; + barrier(cb,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&after,0,nullptr,0,nullptr); + } + } +private: + templateT fn(const char* name)const{return reinterpret_cast(get_(device_,name));} + bool make_pipeline() { + if (pipeline_) return true; + // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. + for (const char* name : {"vkCreateDescriptorPool", "vkDestroyDescriptorPool", + "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", + "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", + "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", + "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) + if (!get_(device_, name)) return false; + VkDescriptorSetLayout set = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkShaderModule shader = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + const VkDescriptorSetLayoutBinding bindings[]={{0,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr},{1,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr}}; + VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + set_info.bindingCount = 2; set_info.pBindings = bindings; + bool ok = fn("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 12}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; + layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; + ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; + VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module.codeSize = sizeof(predicated_copy_spirv); module.pCode = predicated_copy_spirv; + ok = ok && fn("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; + info.layout = layout; + ok = ok && fn("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (shader) fn("vkDestroyShaderModule")(device_, shader, nullptr); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + if (set) fn("vkDestroyDescriptorSetLayout")(device_, set, nullptr); + return false; + } + set_layout_ = set; layout_ = layout; pipeline_ = pipeline; + return true; + } + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceLimits limits_; + VkDescriptorSetLayout set_layout_=VK_NULL_HANDLE; + VkPipelineLayout layout_=VK_NULL_HANDLE; + VkPipeline pipeline_=VK_NULL_HANDLE; +}; +} diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index f5d428e7a..8c34a1000 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -24,6 +24,8 @@ // rectangles need color_attachment usage on the image (ResourceBinding::color_attachment); // - query commands need the query functions, fill_buffer and query_pool; resolve destinations have TRANSFER_DST // usage and binary occlusion resolves need resolve_binary_occlusion. +// - predicated buffer copies need the byte-copy helper and buffers with STORAGE_BUFFER usage; helper descriptors +// must remain alive through submission completion (VulkanQueue owns them). // A list that needs a missing function fails with ReplayResult::unsupported before anything is written. #include "command_list.h" @@ -31,6 +33,8 @@ #include "uav_clear.h" #include +#include "vulkan_predicate.h" +#include "vulkan_predicated_copy.h" #include #include @@ -730,6 +734,12 @@ struct ReplayFunctions { // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; std::function resolve_acceleration_structure; + // Preparation only allocates a slot; capture records the GPU snapshot at the SetPredication command. + std::function prepare_predicate; + std::function capture_predicate; + std::function&)> prepare_predicated_copy; + std::function&)> emit_predicated_copy; // Returns a 2D-array view of the range (caller-owned, alive until execution completes); rectangle clears. std::function image_view; // Footprint copies of a depth24_as_float texture (depth24.h): `depth24_prepare` makes the scratch and descriptors @@ -776,6 +786,8 @@ struct PreparedQuery { }; struct Prepared { + PredicateCapture predicate; + std::vector predicated_copy; ResourceBinding binding; VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) VkImageView view = VK_NULL_HANDLE; @@ -1794,13 +1806,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command)) { if (!copies) return ReplayResult::unsupported; - if (predicated) ++out.unpredicated_copies; + if (predicated && !std::holds_alternative(command)) ++out.unpredicated_copies; const auto [dst_id, src_id] = copy_ids(command); const ResourceBinding* source = resolve(src_id); if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; if (p.binding.host_readable) { out.wrote_readback = true; - out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT; + out.readback_src_stages |= predicated && std::holds_alternative(command) + ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT; } p.source = *source; ReplayResult result = ReplayResult::success; @@ -1809,8 +1822,19 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun !detail::within(buffer_copy->dst_offset, buffer_copy->size, p.binding.size) || !detail::within(buffer_copy->src_offset, buffer_copy->size, p.source.size)) return ReplayResult::invalid_copy; - p.buffer_copies.push_back({p.source.buffer_offset + buffer_copy->src_offset, - p.binding.buffer_offset + buffer_copy->dst_offset, buffer_copy->size}); + if (buffer_copy->src_offset > UINT64_MAX - p.source.buffer_offset || + buffer_copy->dst_offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_copy; + const VkDeviceSize src = p.source.buffer_offset + buffer_copy->src_offset; + const VkDeviceSize dst = p.binding.buffer_offset + buffer_copy->dst_offset; + if (buffer_copy->size > UINT64_MAX - src || buffer_copy->size > UINT64_MAX - dst) + return ReplayResult::invalid_copy; + if (p.source.buffer == p.binding.buffer && src < dst + buffer_copy->size && dst < src + buffer_copy->size) + return ReplayResult::invalid_copy; + if (predicated) { + if (statistics_active || !vk.prepare_predicated_copy || !vk.emit_predicated_copy || + !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy)) + return ReplayResult::unsupported; + } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); } else if (const auto* texture_copy = std::get_if(&command)) { result = detail::prepare_texture_copy(*texture_copy, p); // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. @@ -1903,11 +1927,16 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun predicated = predication->buffer != 0; if (!predicated) continue; if (!conditional) return ReplayResult::unsupported; + // The internal dispatch must not appear in the application's pipeline-statistics result. Virtualising + // that query is separate work; reject the combination before emitting any commands instead of lying. + if (statistics_active) return ReplayResult::unsupported; if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; - // Vulkan reads one 32-bit word at a 4-byte aligned offset; D3D12's value is 64 bits at an 8-byte - // aligned one, so its low word is read (docs/d3d12_vulkan.md section 4.7). - if (!p.binding.buffer || !detail::within(predication->offset, 4, p.binding.size)) + if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || + predication->offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_predication; + if (!vk.prepare_predicate || !vk.capture_predicate || + !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate)) + return ReplayResult::unsupported; } else if (const QueryRange range = query_range(command); range.count) { // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, and Vulkan's // conditional rendering leaves query commands and transfers alone, so a predicate changes nothing here. @@ -2171,10 +2200,12 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c if (const auto* predication = std::get_if(&command)) { // Conditional rendering cannot nest, so a new predicate ends the previous one first. if (predicate.buffer) vk.end_conditional_rendering(command_buffer); - predicate.buffer = p.binding.buffer; + predicate.buffer = predication->buffer ? p.predicate.scratch : VK_NULL_HANDLE; if (predicate.buffer) { - // A default-heap buffer is a range of the GPU address arena's VkBuffer, starting at buffer_offset. - predicate.offset = p.binding.buffer_offset + predication->offset; + // The word was captured from the resource at prepare's offset (buffer_offset + the command's, so a + // default-heap buffer inside the GPU address arena reads its own range); the test reads the capture. + vk.capture_predicate(command_buffer, p.predicate); + predicate.offset = p.predicate.offset + 8; // Vulkan discards the commands when the word is 0, which is EQUAL_ZERO; INVERTED gives NOT_EQUAL_ZERO. predicate.flags = predication->op == d3d12_predication::not_equal_zero ? VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT @@ -2410,7 +2441,9 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } else if (std::holds_alternative(command) || std::holds_alternative(command) || std::holds_alternative(command)) { const auto [dst_id, src_id] = copy_ids(command); - if (!p.buffer_copies.empty()) { + if (!p.predicated_copy.empty()) { + vk.emit_predicated_copy(command_buffer, p.predicated_copy); + } else if (!p.buffer_copies.empty()) { vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), p.buffer_copies.data()); } else if (!p.image_copies.empty()) { diff --git a/runtime/test/check_loaded_async.cmake b/runtime/test/check_loaded_async.cmake new file mode 100644 index 000000000..4217b173f --- /dev/null +++ b/runtime/test/check_loaded_async.cmake @@ -0,0 +1,14 @@ +# Observe the guest verdict and the loader from outside the process. Under Wine an +# exit status alone can look successful even when the mapped program reported failure. +get_filename_component(guest_dir "${GUEST}" DIRECTORY) +get_filename_component(guest_name "${GUEST}" NAME) +execute_process( + COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" + WORKING_DIRECTORY "${guest_dir}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output) +string(REPLACE "\r\n" "\n" output "${output}") +if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_async: PASS(\n|$)" + OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") + message(FATAL_ERROR "Loaded async fixture returned ${code}\n${output}") +endif() diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp index 4e5735946..69fe14679 100644 --- a/runtime/test/command_list_test.cpp +++ b/runtime/test/command_list_test.cpp @@ -107,7 +107,7 @@ int main() { // Copies: D3D12's own call rules (aligned footprints, a non-empty box, distinct CopyResource operands). CHECK(list.reset()); CHECK(list.copy_buffer({1, 0, 2, 16, 64})); - CHECK(!list.copy_buffer({1, 0, 2, 16, 0})); + CHECK(list.copy_buffer({1, 0, 2, 16, 0})); CHECK(!list.copy_buffer({0, 0, 2, 16, 64})); const CopyLocation texture{3, false, 0, 0, 0, 0, 0, 0}; const CopyLocation placed{4, true, 0, 512, 8, 8, 1, 256}; diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp index 8ef814d53..7bc0e35d8 100644 --- a/runtime/test/d3d12_descriptor_test.cpp +++ b/runtime/test/d3d12_descriptor_test.cpp @@ -724,6 +724,14 @@ int main() { EXPECT(rt::d3d12::register_samplers(device.p, {&literal_words, 1}) == S_OK); EXPECT(rt::d3d12::register_samplers(nullptr, {&literal_words, 1}) == E_INVALIDARG); + // GFX10 literal S#s can encode a larger LOD bias than vkCreateSampler accepts on this device. + literal.lod_bias = -32.0f; + const auto negative_bias = g::encode(literal); + literal.lod_bias = 31.0f; + const auto positive_bias = g::encode(literal); + const g::SamplerWords biased_samplers[] = {negative_bias, positive_bias}; + EXPECT(rt::d3d12::register_samplers(device.p, biased_samplers) == S_OK); + // The UINT texture's view in slot 0, and three border samplers after the first: UINT (0,0,0,0) and // (1,1,1,1) from CreateSampler2, which the proxy does not have (the inner device does), and float white. constexpr UINT uint_slot = 0, uint_black = 1, uint_white = 2, float_white = 3; @@ -1276,6 +1284,22 @@ int main() { std::printf("literal S#s: registered %u/%u texels wrapped, unregistered %u/%u clamped\n", wrapped, texels, clamped, texels); EXPECT(wrapped == texels && clamped == texels); + + // With LOD zero requested, opposite bias extremes select the first and last mips. + for (const auto& words : biased_samplers) { + SampleKeys key = keys[0]; + std::memcpy(key.ssharp, words.data(), sizeof(key.ssharp)); + std::array pixels{}; + EXPECT(sample_through_set(d, set0, set0_layout, {&key, 1}, pixels.data())); + UINT matches = 0; + for (UINT i = 0; i < texels; ++i) { + const auto expected = words == negative_bias ? texel(i % size, i / size) : mip_colors[1]; + matches += std::memcmp(pixels.data() + 4 * i, expected.data(), 4) == 0; + } + std::printf("literal sampler bias %.0f: %u/%u samples match, first RGBA %u,%u,%u,%u\n", + g::decode(words).lod_bias, matches, texels, pixels[0], pixels[1], pixels[2], pixels[3]); + EXPECT(matches == texels); + } } if (bc.p) { SampleKeys bc_key = keys[0]; diff --git a/runtime/test/d3d12_fence_timing_test.cpp b/runtime/test/d3d12_fence_timing_test.cpp index 7ef5e6555..49eef01df 100644 --- a/runtime/test/d3d12_fence_timing_test.cpp +++ b/runtime/test/d3d12_fence_timing_test.cpp @@ -1,6 +1,6 @@ // D3D-30 on the Vulkan device, through the Xbox-ABI proxy: SetEventOnMultipleFenceCompletion (ALL and ANY, with an // event and blocking), queue GetClockCalibration on both paths (calibrated timestamps on the standalone device when -// the GPU has them, the submitted timestamp query on a device without the extension), GetAdapterLuid (must name a +// it exposes both clock domains, the submitted timestamp query otherwise), GetAdapterLuid (must name a // DXGI adapter) and GetCustomHeapProperties (compared with the host PC runtime's answer when the host adapter is // NUMA, as the layer reports itself). No shaders or game data. LEONIDA_VK_VALIDATION=1 runs the test-made device // under VK_LAYER_KHRONOS_validation; any validation error fails the test. @@ -10,6 +10,7 @@ #include +#include #include #include #include @@ -59,6 +60,7 @@ int check_calibration(ID3D12CommandQueue* queue, double gpu_frequency, const cha const UINT64 before1 = qpc(); EXPECT(SUCCEEDED(queue->GetClockCalibration(&gpu1, &cpu1))); const UINT64 after1 = qpc(); + EXPECT(before1 <= cpu1 && cpu1 <= after1); EXPECT(gpu1 > gpu0 && cpu1 > cpu0); const double gpu_s = double(gpu1 - gpu0) / gpu_frequency, cpu_s = double(cpu1 - cpu0) / double(qpf.QuadPart); std::printf("%s: GPU %.6f s, CPU %.6f s between two calibrations (%.1f us apart)\n", path, gpu_s, cpu_s, @@ -275,18 +277,37 @@ int main() { const auto extensions_of = d.instance_fn( "vkEnumerateDeviceExtensionProperties"); std::uint32_t count = 0; - extensions_of(d.physical, nullptr, &count, nullptr); + EXPECT(extensions_of(d.physical, nullptr, &count, nullptr) == VK_SUCCESS); std::vector extensions(count); - extensions_of(d.physical, nullptr, &count, extensions.data()); - bool available = false; - for (const auto& e : extensions) - available = available || !std::strcmp(e.extensionName, VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME) || - !std::strcmp(e.extensionName, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME); + EXPECT(extensions_of(d.physical, nullptr, &count, extensions.data()) == VK_SUCCESS); + extensions.resize(count); + const auto has_extension = [&](const char* name) { + return std::any_of(extensions.begin(), extensions.end(), + [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); + }; + const bool khr = has_extension(VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME); + const bool ext = has_extension(VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME); + bool device_clock = false, qpc_clock = false; + if (khr || ext) { + // A driver can expose the extension without a Vulkan time domain for Win32 QPC (e.g. llvmpipe in Wine). + const auto domains_of = d.instance_fn( + khr ? "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR" : "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT"); + EXPECT(domains_of); + EXPECT(domains_of(d.physical, &count, nullptr) == VK_SUCCESS); + std::vector domains(count); + EXPECT(domains_of(d.physical, &count, domains.data()) == VK_SUCCESS); + domains.resize(count); + device_clock = std::find(domains.begin(), domains.end(), VK_TIME_DOMAIN_DEVICE_KHR) != domains.end(); + qpc_clock = std::find(domains.begin(), domains.end(), VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR) != + domains.end(); + } const bool calibrated = rt::d3d12::queue_uses_calibrated_timestamps(queue.p); - std::printf("calibrated timestamps: %s on the GPU, %s by the queue\n", available ? "available" : "missing", - calibrated ? "used" : "not used"); - EXPECT(calibrated == available); // Windows drivers calibrate DEVICE against QueryPerformanceCounter - EXPECT(check_calibration(queue.p, gpu_frequency, calibrated ? "calibrated timestamps" : "fallback") == 0); + std::printf("calibrated timestamps: extension %s, DEVICE domain %s, QPC domain %s, queue capability %s\n", + khr || ext ? "present" : "missing", device_clock ? "present" : "missing", + qpc_clock ? "present" : "missing", calibrated ? "enabled" : "disabled"); + EXPECT(calibrated == (device_clock && qpc_clock)); + const char* clock_path = calibrated ? "calibration-capable queue" : "standalone fallback"; + EXPECT(check_calibration(queue.p, gpu_frequency, clock_path) == 0); EXPECT(check_multiple_fences(standalone.p, queue.p) == 0); EXPECT(check_luid(standalone.p) == 0); } diff --git a/runtime/test/d3d12_indirect_rt_test.cpp b/runtime/test/d3d12_indirect_rt_test.cpp index 20dc0169e..8dd0c3127 100644 --- a/runtime/test/d3d12_indirect_rt_test.cpp +++ b/runtime/test/d3d12_indirect_rt_test.cpp @@ -80,7 +80,7 @@ int main() { const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); if (!gipa) { std::printf("SKIP: vulkan-1.dll not available\n"); - return 0; + return 77; // ctest skips, as in the other GPU tests } const auto create_inst = reinterpret_cast(gipa(nullptr, "vkCreateInstance")); const auto enum_layers = @@ -133,7 +133,13 @@ int main() { } VkInstance instance = VK_NULL_HANDLE; - if (create_inst(&ici, nullptr, &instance) != VK_SUCCESS) return fail("vkCreateInstance"); + const VkResult inst_result = create_inst(&ici, nullptr, &instance); + if (inst_result == VK_ERROR_INCOMPATIBLE_DRIVER) { + // The loader is present but there is no ICD (CI runners, headless machines): ctest skips. + std::printf("SKIP: no Vulkan driver (vkCreateInstance returned VK_ERROR_INCOMPATIBLE_DRIVER)\n"); + return 77; + } + if (inst_result != VK_SUCCESS) return fail("vkCreateInstance"); const auto destroy_inst = reinterpret_cast(gipa(instance, "vkDestroyInstance")); const auto gdpa = reinterpret_cast(gipa(instance, "vkGetDeviceProcAddr")); VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; @@ -195,7 +201,7 @@ int main() { std::printf("SKIP: no Vulkan 1.3 GPU found\n"); if (messenger && destroy_dbg) destroy_dbg(instance, messenger, nullptr); destroy_inst(instance, nullptr); - return 0; + return 77; // ctest skips, as in the other GPU tests } bool rt_supported = false; diff --git a/runtime/test/d3d12_predicated_copy_test.cpp b/runtime/test/d3d12_predicated_copy_test.cpp new file mode 100644 index 000000000..8cf7f81cf --- /dev/null +++ b/runtime/test/d3d12_predicated_copy_test.cpp @@ -0,0 +1,251 @@ +// Synthetic byte-for-byte CopyBufferRegion oracle. --warp-only measures the native reference without Vulkan. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include +#include +#include +#include +#include +#include +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return false; } } while (0) +namespace { +template struct Ref { T* p = nullptr; ~Ref() { if (p) p->Release(); } T* operator->() const { return p; } }; +struct Case { UINT64 source_bytes, destination_bytes, source_offset, destination_offset, bytes; }; +bool buffer(ID3D12Device* device, UINT64 size, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_STATES state, Ref& out) { + const D3D12_HEAP_PROPERTIES properties{heap}; + D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + CHECK(SUCCEEDED(device->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&out.p)))); + return true; +} +bool write(ID3D12Resource* resource, const void* bytes, SIZE_T size) { + void* mapped = nullptr; const D3D12_RANGE none{}; + CHECK(SUCCEEDED(resource->Map(0, &none, &mapped)) && mapped); + std::memcpy(mapped, bytes, size); const D3D12_RANGE written{0, size}; resource->Unmap(0, &written); return true; +} +bool finish(ID3D12GraphicsCommandList* list, ID3D12CommandQueue* queue, ID3D12Fence* fence) { + CHECK(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list}; queue->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue->Signal(fence, 1))); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); CHECK(event); + const HRESULT hr = fence->SetEventOnCompletion(1, event); + const DWORD wait = SUCCEEDED(hr) ? WaitForSingleObject(event, 10000) : WAIT_FAILED; + CloseHandle(event); CHECK(SUCCEEDED(hr) && wait == WAIT_OBJECT_0); + return true; +} +void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, + D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; barrier.Transition.StateAfter = after; + list->ResourceBarrier(1, &barrier); +} +bool run(ID3D12Device* device, const Case& c, UINT64 predicate, D3D12_PREDICATION_OP op, + bool enabled, std::vector& actual) { + Ref source, destination, seed, condition, readback; + CHECK(buffer(device,c.source_bytes,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,source)); + CHECK(buffer(device,c.destination_bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_COPY_DEST,destination)); + CHECK(buffer(device,c.destination_bytes,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,seed)); + CHECK(buffer(device,24,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,condition)); + CHECK(buffer(device,c.destination_bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST,readback)); + std::vector input(SIZE_T(c.source_bytes)), sentinel(SIZE_T(c.destination_bytes)); + for (SIZE_T i=0;i(i*37+11); + for (SIZE_T i=0;i(i*13+173); + const UINT64 conditions[3]={UINT64_MAX,predicate,0}; + CHECK(write(source.p,input.data(),input.size()) && write(seed.p,sentinel.data(),sentinel.size()) && write(condition.p,conditions,sizeof(conditions))); + Ref queue; Ref allocator; Ref list; Ref fence; + const D3D12_COMMAND_QUEUE_DESC desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&desc,IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,allocator.p,nullptr,IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(device->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence.p)))); + list->CopyBufferRegion(destination.p,0,seed.p,0,c.destination_bytes); + // Explicit dependency also covers the unpredicated control path. + D3D12_RESOURCE_BARRIER seed_barrier{}; seed_barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + seed_barrier.Transition.pResource=destination.p; + seed_barrier.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + seed_barrier.Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_DEST; + seed_barrier.Transition.StateAfter=D3D12_RESOURCE_STATE_COMMON; + list->ResourceBarrier(1,&seed_barrier); + std::swap(seed_barrier.Transition.StateBefore,seed_barrier.Transition.StateAfter); + list->ResourceBarrier(1,&seed_barrier); + if(enabled) list->SetPredication(condition.p,8,op); + list->CopyBufferRegion(destination.p,c.destination_offset,source.p,c.source_offset,c.bytes); + list->SetPredication(nullptr,0,D3D12_PREDICATION_OP_EQUAL_ZERO); + D3D12_RESOURCE_BARRIER barrier{}; barrier.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource=destination.p; barrier.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore=D3D12_RESOURCE_STATE_COPY_DEST; barrier.Transition.StateAfter=D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1,&barrier); list->CopyBufferRegion(readback.p,0,destination.p,0,c.destination_bytes); + CHECK(finish(list.p, queue.p, fence.p)); + void* mapped=nullptr; const D3D12_RANGE range{0,SIZE_T(c.destination_bytes)}; + CHECK(SUCCEEDED(readback->Map(0,&range,&mapped))&&mapped); + actual.assign(static_cast(mapped),static_cast(mapped)+c.destination_bytes); + const D3D12_RANGE none{}; readback->Unmap(0,&none); + const bool executes=!enabled || (op==D3D12_PREDICATION_OP_EQUAL_ZERO ? predicate!=0 : predicate==0); + if(executes && c.bytes) std::memcpy(sentinel.data()+c.destination_offset,input.data()+c.source_offset,SIZE_T(c.bytes)); + for(SIZE_T i=0;i& actual) { + constexpr SIZE_T destination_bytes = 128, condition_bytes = 48, total_bytes = 184; + Ref source, seed, condition_seed, destination, condition, readback, replacement_source; + CHECK(!overwrite || op==D3D12_PREDICATION_OP_NOT_EQUAL_ZERO); + CHECK(buffer(device,8,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,replacement_source)); + const UINT64 high_word=UINT64_C(1)<<32; + CHECK(write(replacement_source.p,&high_word,sizeof(high_word))); + CHECK(buffer(device,32,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,source)); + CHECK(buffer(device,destination_bytes,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,seed)); + CHECK(buffer(device,condition_bytes,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ,condition_seed)); + CHECK(buffer(device,destination_bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_COPY_DEST,destination)); + CHECK(buffer(device,condition_bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_COPY_DEST,condition)); + CHECK(buffer(device,total_bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST,readback)); + std::array input{}; + std::array expected{}; expected.fill(0xcd); + std::array guard{}; guard.fill(0xa7); + for(SIZE_T i=0;i(37*i+11); + CHECK(write(source.p,input.data(),input.size()) && write(seed.p,expected.data(),expected.size()) && + write(condition_seed.p,guard.data(),guard.size())); + Ref occlusion; + const D3D12_QUERY_HEAP_DESC occlusion_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION,1,0}; + CHECK(SUCCEEDED(device->CreateQueryHeap(&occlusion_desc,IID_PPV_ARGS(&occlusion.p)))); + Ref queue; Ref allocator; + Ref list; Ref fence; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc,IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,allocator.p,nullptr,IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(device->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence.p)))); + list->CopyBufferRegion(destination.p,0,seed.p,0,destination_bytes); + list->CopyBufferRegion(condition.p,0,condition_seed.p,0,condition_bytes); + for(auto* resource:{destination.p,condition.p}) { + transition(list.p,resource,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COMMON); + transition(list.p,resource,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_DEST); + } + list->BeginQuery(occlusion.p,query_type,0); + list->EndQuery(occlusion.p,query_type,0); + list->ResolveQueryData(occlusion.p,query_type,0,1,condition.p,offset); + transition(list.p,condition.p,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_PREDICATION); + list->SetPredication(condition.p,offset,op); + list->CopyBufferRegion(destination.p,3,source.p,2,7); + if(overwrite) { + // With zero + NOT_EQUAL_ZERO, this copy executes on both backends. Verify its eight bytes below. + transition(list.p,condition.p,D3D12_RESOURCE_STATE_PREDICATION,D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(condition.p,offset,replacement_source.p,0,8); + transition(list.p,condition.p,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_PREDICATION); + } + list->CopyBufferRegion(destination.p,25,source.p,5,11); + if(recapture) list->SetPredication(condition.p,offset,op); + list->CopyBufferRegion(destination.p,57,source.p,9,13); + list->SetPredication(nullptr,0,D3D12_PREDICATION_OP_EQUAL_ZERO); + list->CopyBufferRegion(destination.p,91,source.p,1,17); + transition(list.p,destination.p,D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_COPY_SOURCE); + transition(list.p,condition.p,D3D12_RESOURCE_STATE_PREDICATION,D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(readback.p,0,destination.p,0,destination_bytes); + list->CopyBufferRegion(readback.p,destination_bytes,condition.p,0,condition_bytes); + list->ResolveQueryData(occlusion.p,query_type,0,1,readback.p,176); + CHECK(finish(list.p,queue.p,fence.p)); + void* mapped=nullptr; const D3D12_RANGE range{0,total_bytes}; + CHECK(SUCCEEDED(readback->Map(0,&range,&mapped)) && mapped); + std::array bytes{}; std::memcpy(bytes.data(),mapped,bytes.size()); + const D3D12_RANGE none{}; readback->Unmap(0,&none); + UINT64 zero=UINT64_MAX, overwritten=0; + const UINT64 replacement=overwrite ? high_word : 0; + std::memcpy(&zero,bytes.data()+176,8); + std::memcpy(&overwritten,bytes.data()+destination_bytes+offset,8); + if(zero!=0 || overwritten!=replacement) { + std::fprintf(stderr,"query evidence type %u op %u offset %llu overwrite %d recapture %d: occlusion=%llu predicate=%llu\n", + unsigned(query_type),unsigned(op),offset,int(overwrite),int(recapture),zero,overwritten); + return false; + } + std::memcpy(guard.data()+offset,&replacement,8); + CHECK(std::memcmp(bytes.data()+destination_bytes,guard.data(),guard.size())==0); + const bool initially_runs=op==D3D12_PREDICATION_OP_NOT_EQUAL_ZERO; + if(initially_runs) { + std::memcpy(expected.data()+3,input.data()+2,7); + std::memcpy(expected.data()+25,input.data()+5,11); + } + if((overwrite && recapture) ? !initially_runs : initially_runs) std::memcpy(expected.data()+57,input.data()+9,13); + std::memcpy(expected.data()+91,input.data()+1,17); + actual.assign(bytes.begin(),bytes.begin()+destination_bytes); + for(SIZE_T i=0;i factory; Ref adapter; Ref host,ours; + if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p))) || + FAILED(D3D12CreateDevice(adapter.p,D3D_FEATURE_LEVEL_11_0,IID_PPV_ARGS(&host.p)))) return 1; + if(!native_only) { + if(!vk.create())return 77; // no Vulkan GPU: ctest skips (SKIP_RETURN_CODE 77), as the other registered runtime tests do + if(!vk.conditional_rendering || !vk.storage_buffer_8bit) { + std::puts("predicated buffer copies: skipped (requires conditional rendering and storageBuffer8BitAccess)"); + return 0; + } + rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc=vk.instance_proc; info.instance=vk.instance; + info.physical=vk.physical; info.device=vk.device; info.queue=vk.queue; info.queue_family=vk.family; + info.conditional_rendering=vk.conditional_rendering; + info.storage_buffer_8bit=vk.storage_buffer_8bit; + info.occlusion_query_precise=vk.occlusion_query_precise; + if(FAILED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&ours.p))))return 1; + } + const Case cases[]={{1,1,0,0,1},{2,3,1,2,1},{7,11,1,3,5},{13,17,3,1,7},{33,35,0,3,32}, + {257,259,1,3,256},{4099,4103,3,7,4096},{4099,4103,4098,4102,1},{13,17,13,17,0}}; + unsigned count=0; + for(const auto& c:cases)for(UINT64 value:{UINT64_C(0),UINT64_C(1),UINT64_C(1)<<32,(UINT64_C(1)<<32)|7,UINT64_MAX}) + for(auto op:{D3D12_PREDICATION_OP_EQUAL_ZERO,D3D12_PREDICATION_OP_NOT_EQUAL_ZERO})for(bool enabled:{false,true}) { + std::vector expected,actual; + if(!run(host.p,c,value,op,enabled,expected)) {std::fprintf(stderr,"WARP reference failed\n");return 1;} + if(!native_only&&(!run(ours.p,c,value,op,enabled,actual)||actual!=expected)){std::fprintf(stderr,"Vulkan comparison failed\n");return 1;} + ++count; + } + unsigned query_cases=0, recapture_controls=0; + for(auto type:{D3D12_QUERY_TYPE_OCCLUSION,D3D12_QUERY_TYPE_BINARY_OCCLUSION}) + for(auto op:{D3D12_PREDICATION_OP_EQUAL_ZERO,D3D12_PREDICATION_OP_NOT_EQUAL_ZERO}) + for(UINT64 offset:{UINT64_C(0),UINT64_C(16)}) { + std::vector without_recapture; + // Baseline on both operators; overwrite controls only where the predicate permits the write. + const unsigned variants=op==D3D12_PREDICATION_OP_NOT_EQUAL_ZERO ? 3 : 1; + for(unsigned variant=0;variant expected,actual; + if(!run_query_copy(host.p,type,op,offset,overwrite,recapture,expected)) { + std::fprintf(stderr,"WARP query-copy oracle failed\n");return 1; + } + if(!native_only && (!run_query_copy(ours.p,type,op,offset,overwrite,recapture,actual) || actual!=expected)) { + std::fprintf(stderr,"Vulkan query-copy comparison failed\n");return 1; + } + if(variant==1) without_recapture=expected; + if(recapture) { + unsigned changed=0; + for(SIZE_T i=0;i=70)return 1; + ++changed; + } + if(changed!=13)return 1; + ++recapture_controls; + } + ++query_cases; + } + } + if(!native_only&&vk.validation_errors())return 1; + std::printf("query-to-predicated-copy: %u exact cases, %u recapture controls; GPU overwrite and predicate guards exact\n",query_cases,recapture_controls); + std::printf("predicated buffer copies: %u exact cases (%s)\n",count,native_only?"WARP + literal byte oracle":"Vulkan + WARP + literal byte oracle"); +} diff --git a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp new file mode 100644 index 000000000..5417e7ca5 --- /dev/null +++ b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp @@ -0,0 +1,782 @@ +// Emulation of DXGI_FORMAT_R9G9B9E5_SHAREDEXP textures with D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS on Vulkan +// GPUs whose VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE support (docs/d3d12_vulkan.md Appendix A.3). +// +// Exercises: +// 1. CheckFeatureSupport(FORMAT_SUPPORT) for R9G9B9E5_SHAREDEXP (typed UAV on, render target off) +// 2. CreateCommittedResource (1D/2D 1920x1080/2D-array+mips/3D), GetResourceAllocationInfo (4 KiB + 64 KiB), +// CreateReservedResource + GetResourceTiling, and refusals (ALLOW_RENDER_TARGET, ALLOW_DEPTH_STENCIL, +// DENY_SHADER_RESOURCE, MSAA, null RTV) +// 3. SRV and UAV T# creation (FORMAT 132, channels_rgb, ResourceMinLODClamp, SRV->UAV upgrade on same T#, +// and null-descriptor rejection of invalid casts in both directions) +// 4. Differential ClearUnorderedAccessViewFloat / ClearUnorderedAccessViewUint (whole views and rectangles) +// against Windows WARP (when available) +// 5. CopyResource / CopyTextureRegion between UAV and non-UAV R9G9B9E5 textures + WriteToSubresource / +// ReadFromSubresource round-trip +// 6. Set-0 bindless GPU compute write (R32_UINT storage bindings 9 & 4) -> sampled HDR float read (binding 0, +// VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) when glslangValidator compiled the test shader +// +// Synthetic data only; no game files. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/gfx10_descriptors.h" +#include "../src/uav_clear.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +namespace g = leonida::gfx10; + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +D3D12_RESOURCE_DESC tex_desc(D3D12_RESOURCE_DIMENSION dim, UINT64 width, UINT height, UINT16 depth_or_layers, + UINT16 mips, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags, UINT samples = 1, + UINT64 alignment = 0, D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = dim; + d.Alignment = alignment; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = depth_or_layers; + d.MipLevels = mips; + d.Format = format; + d.SampleDesc = {samples, 0}; + d.Layout = layout; + d.Flags = flags; + return d; +} + +D3D12_RESOURCE_DESC buf_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return d; +} + +D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, + UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, subresource, before, after}; + return b; +} + +bool all_zero(const void* ptr, std::size_t bytes) { + const auto* p = static_cast(ptr); + for (std::size_t i = 0; i < bytes; ++i) + if (p[i]) return false; + return true; +} + +// Runs a sequence of UAV clears on a 4x4 DXGI_FORMAT_R9G9B9E5_SHAREDEXP texture on any ID3D12Device (Vulkan or WARP) +// and reads back the 16 packed uint32 words. +struct ClearStep { + bool is_float; + std::array fvals; + std::array uvals; + std::vector rects; +}; + +bool run_uav_clear_sequence(ID3D12Device* dev, bool vulkan_device, const std::vector& steps, + std::vector& out_words) { + Ref queue; + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))) return false; + Ref alloc; + if (FAILED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))) return false; + Ref list; + if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p)))) + return false; + Ref fence; + if (FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) return false; + + const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto td = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, 1, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref tex; + if (FAILED(dev->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &td, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&tex.p)))) + return false; + + const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK}; + const auto bd = buf_desc(4 * 256); + Ref rb; + if (FAILED(dev->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &bd, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&rb.p)))) + return false; + + Ref cpu_heap, gpu_heap; + const D3D12_DESCRIPTOR_HEAP_DESC hd_cpu{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + const D3D12_DESCRIPTOR_HEAP_DESC hd_gpu{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + if (FAILED(dev->CreateDescriptorHeap(&hd_cpu, IID_PPV_ARGS(&cpu_heap.p))) || + FAILED(dev->CreateDescriptorHeap(&hd_gpu, IID_PPV_ARGS(&gpu_heap.p)))) + return false; + + D3D12_UNORDERED_ACCESS_VIEW_DESC uavd{}; + uavd.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + uavd.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + const auto cpu_h = cpu_heap->GetCPUDescriptorHandleForHeapStart(); + const auto gpu_h = gpu_heap->GetGPUDescriptorHandleForHeapStart(); + dev->CreateUnorderedAccessView(tex.p, nullptr, &uavd, cpu_h); + dev->CreateUnorderedAccessView(tex.p, nullptr, &uavd, gpu_heap->GetCPUDescriptorHandleForHeapStart()); + + ID3D12DescriptorHeap* heaps[] = {gpu_heap.p}; + list->SetDescriptorHeaps(1, heaps); + for (const auto& step : steps) { + const auto* rects = step.rects.empty() ? nullptr : step.rects.data(); + if (step.is_float) { + list->ClearUnorderedAccessViewFloat(gpu_h, cpu_h, tex.p, step.fvals.data(), UINT(step.rects.size()), rects); + } else { + list->ClearUnorderedAccessViewUint(gpu_h, cpu_h, tex.p, step.uvals.data(), UINT(step.rects.size()), rects); + } + D3D12_RESOURCE_BARRIER uav_b{}; + uav_b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + uav_b.UAV.pResource = tex.p; + list->ResourceBarrier(1, &uav_b); + } + const auto to_src = transition(tex.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_src); + D3D12_TEXTURE_COPY_LOCATION dst{rb.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R9G9B9E5_SHAREDEXP, 4, 4, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION src{tex.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.SubresourceIndex = 0; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + if (FAILED(list->Close())) return false; + + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (vulkan_device && rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; + if (FAILED(queue->Signal(fence.p, 1)) || FAILED(fence->SetEventOnCompletion(1, nullptr))) return false; + + void* mapped = nullptr; + if (FAILED(rb->Map(0, nullptr, &mapped))) return false; + out_words.resize(16); + for (UINT y = 0; y < 4; ++y) + std::memcpy(&out_words[y * 4], static_cast(mapped) + y * 256, 4 * sizeof(std::uint32_t)); + rb->Unmap(0, nullptr); + return true; +} + +#ifdef LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV +bool read_spirv(const char* path, std::vector& out) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file) return false; + const auto size = file.tellg(); + if (size <= 0 || size % 4 != 0) return false; + out.resize(std::size_t(size) / 4); + file.seekg(0); + return bool(file.read(reinterpret_cast(out.data()), size)); +} + +struct ShaderParams { + std::uint32_t tsharp[8]; + std::uint32_t ssharp[4]; + std::uint32_t mode; + std::uint32_t width; + std::uint32_t height; + std::uint32_t pad; +}; + +bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescriptorSetLayout set0_layout, + const g::ImageWords& uav_words, const g::ImageWords& srv_words, + const g::SamplerWords& sampler_words, bool do_uint_write, + const std::array& input_words, + std::array& out_rgba) { + std::vector code; + if (!read_spirv(LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV, code)) return false; + + void* in_ptr = nullptr; + void* out_ptr = nullptr; + const VkBuffer in_buf = d.buffer(sizeof(input_words), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &in_ptr); + const VkBuffer out_buf = d.buffer(sizeof(out_rgba), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &out_ptr); + if (!in_buf || !out_buf) return false; + std::memcpy(in_ptr, input_words.data(), sizeof(input_words)); + + const auto create_dsl = d.fn("vkCreateDescriptorSetLayout"); + const auto destroy_dsl = d.fn("vkDestroyDescriptorSetLayout"); + const auto create_pool = d.fn("vkCreateDescriptorPool"); + const auto destroy_pool = d.fn("vkDestroyDescriptorPool"); + const auto alloc_sets = d.fn("vkAllocateDescriptorSets"); + const auto update_sets = d.fn("vkUpdateDescriptorSets"); + const auto create_layout = d.fn("vkCreatePipelineLayout"); + const auto destroy_layout = d.fn("vkDestroyPipelineLayout"); + const auto create_mod = d.fn("vkCreateShaderModule"); + const auto destroy_mod = d.fn("vkDestroyShaderModule"); + const auto create_pipe = d.fn("vkCreateComputePipelines"); + const auto destroy_pipe = d.fn("vkDestroyPipeline"); + + VkDescriptorSetLayoutBinding bindings[2]{}; + bindings[0] = {0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + bindings[1] = {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + VkDescriptorSetLayoutCreateInfo dsl_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + dsl_info.bindingCount = 2; + dsl_info.pBindings = bindings; + VkDescriptorSetLayout set1_layout = VK_NULL_HANDLE; + VkDescriptorPool pool = VK_NULL_HANDLE; + VkPipelineLayout pipe_layout = VK_NULL_HANDLE; + VkShaderModule module = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + const auto cleanup = [&](bool ok) { + if (pipeline) destroy_pipe(d.device, pipeline, nullptr); + if (module) destroy_mod(d.device, module, nullptr); + if (pipe_layout) destroy_layout(d.device, pipe_layout, nullptr); + if (pool) destroy_pool(d.device, pool, nullptr); + if (set1_layout) destroy_dsl(d.device, set1_layout, nullptr); + return ok; + }; + if (create_dsl(d.device, &dsl_info, nullptr, &set1_layout) != VK_SUCCESS) return cleanup(false); + + VkDescriptorPoolSize pool_size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2}; + VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; + pool_info.maxSets = 1; + pool_info.poolSizeCount = 1; + pool_info.pPoolSizes = &pool_size; + if (create_pool(d.device, &pool_info, nullptr, &pool) != VK_SUCCESS) return cleanup(false); + + VkDescriptorSetAllocateInfo alloc_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; + alloc_info.descriptorPool = pool; + alloc_info.descriptorSetCount = 1; + alloc_info.pSetLayouts = &set1_layout; + VkDescriptorSet set1 = VK_NULL_HANDLE; + if (alloc_sets(d.device, &alloc_info, &set1) != VK_SUCCESS) return cleanup(false); + + VkDescriptorBufferInfo buf_infos[2] = {{in_buf, 0, sizeof(input_words)}, {out_buf, 0, sizeof(out_rgba)}}; + VkWriteDescriptorSet writes[2]{}; + for (UINT i = 0; i < 2; ++i) { + writes[i] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; + writes[i].dstSet = set1; + writes[i].dstBinding = i; + writes[i].descriptorCount = 1; + writes[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[i].pBufferInfo = &buf_infos[i]; + } + update_sets(d.device, 2, writes, 0, nullptr); + + VkDescriptorSetLayout set_layouts[2] = {set0_layout, set1_layout}; + VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ShaderParams)}; + VkPipelineLayoutCreateInfo pl_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + pl_info.setLayoutCount = 2; + pl_info.pSetLayouts = set_layouts; + pl_info.pushConstantRangeCount = 1; + pl_info.pPushConstantRanges = ⦥ + if (create_layout(d.device, &pl_info, nullptr, &pipe_layout) != VK_SUCCESS) return cleanup(false); + + VkShaderModuleCreateInfo mod_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + mod_info.codeSize = code.size() * sizeof(std::uint32_t); + mod_info.pCode = code.data(); + if (create_mod(d.device, &mod_info, nullptr, &module) != VK_SUCCESS) return cleanup(false); + + VkComputePipelineCreateInfo pipe_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipe_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipe_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipe_info.stage.module = module; + pipe_info.stage.pName = "main"; + pipe_info.layout = pipe_layout; + if (create_pipe(d.device, VK_NULL_HANDLE, 1, &pipe_info, nullptr, &pipeline) != VK_SUCCESS) return cleanup(false); + + const bool ok = d.run([&](VkCommandBuffer cb) { + const auto bind_pipe = d.fn("vkCmdBindPipeline"); + const auto bind_sets = d.fn("vkCmdBindDescriptorSets"); + const auto push = d.fn("vkCmdPushConstants"); + const auto dispatch = d.fn("vkCmdDispatch"); + const auto barrier = d.fn("vkCmdPipelineBarrier"); + + VkDescriptorSet sets[2] = {set0, set1}; + bind_pipe(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); + bind_sets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipe_layout, 0, 2, sets, 0, nullptr); + + if (do_uint_write) { + ShaderParams wp{}; + std::memcpy(wp.tsharp, uav_words.data(), sizeof(wp.tsharp)); + std::memcpy(wp.ssharp, sampler_words.data(), sizeof(wp.ssharp)); + wp.mode = 0; + wp.width = 4; + wp.height = 4; + push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(wp), &wp); + dispatch(cb, 1, 1, 1); + + VkMemoryBarrier mem{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + mem.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + mem.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &mem, 0, + nullptr, 0, nullptr); + } + + ShaderParams sp{}; + std::memcpy(sp.tsharp, srv_words.data(), sizeof(sp.tsharp)); + std::memcpy(sp.ssharp, sampler_words.data(), sizeof(sp.ssharp)); + sp.mode = 1; + sp.width = 4; + sp.height = 4; + push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(sp), &sp); + dispatch(cb, 1, 1, 1); + + VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, + nullptr); + return true; + }); + if (ok) std::memcpy(out_rgba.data(), out_ptr, sizeof(out_rgba)); + return cleanup(ok); +} +#endif + +} // namespace + +int main() { + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + + VkFormatProperties e5_props{}; + d.instance_fn("vkGetPhysicalDeviceFormatProperties")( + d.physical, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, &e5_props); + const bool native_storage = (e5_props.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; + const bool native_attach = (e5_props.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; + const bool rect_clears_supported = !native_storage || native_attach; + + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.bindless = d.bindless; + info.bindless_partially_bound = d.partially_bound; + info.image_view_min_lod = d.image_view_min_lod; + info.host_image_copy = d.host_image_copy; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + + // 1. CheckFeatureSupport(FORMAT_SUPPORT): typed UAV is advertised; render target and depth-stencil stay off. + D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs)))); + if (!(fs.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { + std::printf("R9G9B9E5_SHAREDEXP UAV not supported natively or via mutable R32_UINT on this GPU, skipping\n"); + return 77; + } + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE1D) != 0); + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D) != 0); + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D) != 0); + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURECUBE) != 0); + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_LOAD) != 0); + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) != 0); + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET) == 0); + EXPECT((fs.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL) == 0); + EXPECT((fs.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE) != 0); + std::printf("R9G9B9E5 UAV mode: %s (Support1=0x%08x Support2=0x%08x)\n", + native_storage ? "native" : "emulated mutable R32_UINT", + static_cast(fs.Support1), static_cast(fs.Support2)); + + // 2. Resource creation (1D, 2D 1920x1080, 2D array + mips, 3D), GetResourceAllocationInfo, + // CreateReservedResource + GetResourceTiling, and flag refusals. + const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc_1080p = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 1920, 1080, 1, 1, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto alloc_1080p = device->GetResourceAllocationInfo(0, 1, &desc_1080p); + EXPECT(alloc_1080p.SizeInBytes != UINT64_MAX && alloc_1080p.SizeInBytes >= 1920ull * 1080 * 4); + EXPECT(alloc_1080p.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT); + + // Small 16x16 2D UAV qualifies for 4 KiB placement alignment (matches host GetResourceAllocationInfo rules). + const auto desc_small_4k = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + 1, D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT); + const auto alloc_small = device->GetResourceAllocationInfo(0, 1, &desc_small_4k); + EXPECT(alloc_small.SizeInBytes != UINT64_MAX && alloc_small.Alignment == D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT); + + Ref tex_1080p; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_1080p, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&tex_1080p.p)))); + EXPECT(tex_1080p->GetDesc().Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP); + EXPECT(tex_1080p->GetDesc().Flags == D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + + const auto desc_arr = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 8, 4, 3, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref tex_arr; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_arr, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&tex_arr.p)))); + + const auto desc_1d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 64, 1, 2, 2, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref tex_1d; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_1d, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&tex_1d.p)))); + + const auto desc_3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 2, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref tex_3d; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_3d, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&tex_3d.p)))); + + // Reserved resource with 64KB_UNDEFINED_SWIZZLE + GetResourceTiling. + const auto desc_reserved = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 1920, 1080, 1, 1, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + 1, 0, D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE); + Ref reserved; + EXPECT(SUCCEEDED(device->CreateReservedResource(&desc_reserved, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&reserved.p)))); + UINT total_tiles = 0; + D3D12_TILE_SHAPE tile_shape{}; + device->GetResourceTiling(reserved.p, &total_tiles, nullptr, &tile_shape, nullptr, 0, nullptr); + EXPECT(total_tiles > 0 && tile_shape.WidthInTexels == 128 && tile_shape.HeightInTexels == 128 && + tile_shape.DepthInTexels == 1); + + // Refusals: render target, render target + UAV, depth-stencil, DENY_SHADER_RESOURCE + UAV, MSAA. + const D3D12_RESOURCE_DESC bad_descs[] = { + tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE), + tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, 4), + }; + for (const auto& bad : bad_descs) { + Ref refused; + EXPECT(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &bad, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG); + EXPECT(!refused.p); + EXPECT(device->GetResourceAllocationInfo(0, 1, &bad).SizeInBytes == UINT64_MAX); + } + + // CreateRenderTargetView on an emulated R9G9B9E5 UAV leaves a null RTV (never exposes backing R32_UINT RT). + Ref rtv_heap; + const D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&rtv_heap.p)))); + const auto rtv_h = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + const UINT rtv_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + std::memset(reinterpret_cast(rtv_h.ptr), 0x55, rtv_step); + device->CreateRenderTargetView(tex_1080p.p, nullptr, rtv_h); + EXPECT(all_zero(reinterpret_cast(rtv_h.ptr), sizeof(leonida::TargetView))); + + // 3. Descriptors (SRV, UAV, ResourceMinLODClamp, SRV->UAV upgrade, invalid casts in both directions). + Ref heap; + const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p)))); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto* base = reinterpret_cast(heap->GetCPUDescriptorHandleForHeapStart().ptr); + const auto slot = [&](UINT i) -> D3D12_CPU_DESCRIPTOR_HANDLE { + return {reinterpret_cast(base + std::size_t(i) * step)}; + }; + const auto words_at = [&](UINT i) { + g::ImageWords w{}; + std::memcpy(w.data(), base + std::size_t(i) * step, sizeof(w)); + return w; + }; + + // Create SRV first on mip 0 of a 1-mip texture, then UAV with the exact same range: T# bytes must match and + // decode as GFX10_FORMAT_5_9_9_9_FLOAT (132) with RGB1 channels. + device->CreateShaderResourceView(tex_1080p.p, nullptr, slot(0)); + device->CreateUnorderedAccessView(tex_1080p.p, nullptr, nullptr, slot(1)); + const g::ImageWords srv_1080p = words_at(0); + const g::ImageWords uav_1080p = words_at(1); + EXPECT(!all_zero(srv_1080p.data(), sizeof(srv_1080p))); + EXPECT(srv_1080p == uav_1080p); + g::Image decoded{}; + EXPECT(g::decode(uav_1080p, decoded)); + EXPECT(decoded.format == 132u && decoded.swizzle == g::channels_rgb); + EXPECT(decoded.width == 1920u && decoded.height == 1080u); + + // 2D-array UAV + SRV with ResourceMinLODClamp (verifies VkImageViewMinLodCreateInfoEXT chains with usage). + D3D12_UNORDERED_ACCESS_VIEW_DESC arr_uav{}; + arr_uav.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + arr_uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + arr_uav.Texture2DArray = {1, 1, 2, 0}; + device->CreateUnorderedAccessView(tex_arr.p, nullptr, &arr_uav, slot(2)); + EXPECT(g::decode(words_at(2), decoded)); + EXPECT(decoded.format == 132u && decoded.first_mip == 1u && decoded.first_layer == 1u && + decoded.layer_count == 2u); + + D3D12_SHADER_RESOURCE_VIEW_DESC lod_srv{}; + lod_srv.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + lod_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + lod_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + lod_srv.Texture2DArray = {0, 3, 0, 4, 0, d.image_view_min_lod ? 1.5f : 0.0f}; + device->CreateShaderResourceView(tex_arr.p, &lod_srv, slot(3)); + EXPECT(g::decode(words_at(3), decoded) && decoded.format == 132u); + + // Invalid casts on R9G9B9E5_SHAREDEXP must leave null descriptors. + for (DXGI_FORMAT bad_fmt : {DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R8G8B8A8_UNORM}) { + D3D12_SHADER_RESOURCE_VIEW_DESC bad_srv{}; + bad_srv.Format = bad_fmt; + bad_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + bad_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + bad_srv.Texture2D.MipLevels = 1; + std::memset(base + std::size_t(4) * step, 0xaa, step); + device->CreateShaderResourceView(tex_1080p.p, &bad_srv, slot(4)); + EXPECT(all_zero(base + std::size_t(4) * step, step)); + + D3D12_UNORDERED_ACCESS_VIEW_DESC bad_uav{}; + bad_uav.Format = bad_fmt; + bad_uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + std::memset(base + std::size_t(5) * step, 0xaa, step); + device->CreateUnorderedAccessView(tex_1080p.p, nullptr, &bad_uav, slot(5)); + EXPECT(all_zero(base + std::size_t(5) * step, step)); + } + + // Reverse invalid cast: R9G9B9E5 view on a real R32_UINT UAV texture must leave a null descriptor. + const auto desc_r32 = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 8, 8, 1, 1, DXGI_FORMAT_R32_UINT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref tex_r32; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_r32, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&tex_r32.p)))); + D3D12_SHADER_RESOURCE_VIEW_DESC rev_srv{}; + rev_srv.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + rev_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + rev_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + rev_srv.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(tex_r32.p, &rev_srv, slot(6)); + EXPECT(all_zero(base + std::size_t(6) * step, step)); + + // 4. Differential UAV clear comparison against Windows WARP. + Ref warp; + { + Ref factory; + Ref adapter; + if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) && + SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) { + D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&warp.p)); + } + } + std::vector> clear_cases = { + {{true, {1.0f, 2.0f, 4.0f, 0.0f}, {}, {}}}, + {{true, {1.0f + 0.5f / 256, 1.0f + 1.5f / 256, 1.0f + 2.5f / 256, 0.0f}, {}, {}}}, + {{true, {1.0f - 0.5f / 512, std::ldexp(511.5f, -24), std::ldexp(0.5f, -24), 0.0f}, {}, {}}}, + {{true, {-1.0f, std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN(), 0.0f}, {}, {}}}, + {{true, {1.0f, 2.0f, 4.0f, 0.0f}, {}, {}}, + {false, {}, {0x3f800000u, 0xffffffffu, 0x12345678u, 7u}, {}}}, + }; + if (rect_clears_supported) { + clear_cases.push_back({ + {true, {1.0f, 2.0f, 4.0f, 0.0f}, {}, {}}, + {true, {0.5f, 0.25f, 0.125f, 0.0f}, {}, {{1, 1, 3, 3}}}, + {false, {}, {0xdeadbeefu, 0x3f800000u, 0u, 0u}, {{2, 2, 4, 4}}}, + }); + } + for (std::size_t c = 0; c < clear_cases.size(); ++c) { + std::vector vk_words; + EXPECT(run_uav_clear_sequence(device.p, true, clear_cases[c], vk_words)); + if (warp.p) { + std::vector warp_words; + EXPECT(run_uav_clear_sequence(warp.p, false, clear_cases[c], warp_words)); + if (vk_words != warp_words) { + std::fprintf(stderr, "WARP mismatch on clear case %zu: vk[0]=0x%08x warp[0]=0x%08x\n", + c, vk_words[0], warp_words[0]); + return 1; + } + } + } + std::printf("UAV clears: %zu/%zu cases %s\n", clear_cases.size(), clear_cases.size(), + warp.p ? "matched WARP bit-for-bit" : "succeeded (WARP unavailable)"); + + // 5. CopyResource / CopyTextureRegion between UAV (emulated R32_UINT) and plain non-UAV (E5B9G9R9) textures, + // plus WriteToSubresource / ReadFromSubresource on a CPU-visible custom-heap UAV texture. + { + const std::array pattern = { + 0x94010040u, 0x79010100u, 0x7556ab55u, 0x840e0501u, + 0x80000100u, 0x80020000u, 0x84000000u, 0xb0080190u, + 0xf80001ffu, 0xffffffffu, 0x08000100u, 0x00000100u, + 0x00000001u, 0x000c0202u, 0x00100602u, 0x00000000u, + }; + const D3D12_HEAP_PROPERTIES custom_heap = device->GetCustomHeapProperties(0, D3D12_HEAP_TYPE_UPLOAD); + const auto desc_uav4 = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, 1, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto desc_plain4 = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, 1, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_NONE); + Ref cpu_uav, plain_tex, dst_uav; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&custom_heap, D3D12_HEAP_FLAG_NONE, &desc_uav4, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&cpu_uav.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_plain4, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&plain_tex.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&custom_heap, D3D12_HEAP_FLAG_NONE, &desc_uav4, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&dst_uav.p)))); + + EXPECT(SUCCEEDED(cpu_uav->WriteToSubresource(0, nullptr, pattern.data(), 16, 64))); + std::array cpu_readback{}; + EXPECT(SUCCEEDED(cpu_uav->ReadFromSubresource(cpu_readback.data(), 16, 64, 0, nullptr))); + EXPECT(cpu_readback == pattern); + + // UAV -> plain E5B9G9R9 (CopyResource) -> UAV (CopyTextureRegion), then ReadFromSubresource. + Ref queue; + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + Ref alloc; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + const auto b1 = transition(cpu_uav.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b1); + list->CopyResource(plain_tex.p, cpu_uav.p); + const auto b2 = transition(plain_tex.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b2); + D3D12_TEXTURE_COPY_LOCATION copy_dst{dst_uav.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION copy_src{plain_tex.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(©_dst, 0, 0, 0, ©_src, nullptr); + const auto b3 = transition(dst_uav.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + list->ResourceBarrier(1, &b3); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + + std::array roundtrip{}; + EXPECT(SUCCEEDED(dst_uav->ReadFromSubresource(roundtrip.data(), 16, 64, 0, nullptr))); + EXPECT(roundtrip == pattern); + std::printf("Copies & CPU subresource access: UAV <-> non-UAV R9G9B9E5 matched 16/16 texels\n"); + } + + // 6. Set-0 bindless GPU compute round-trip: write packed RGB9E5 through R32_UINT storage views (bindings 9 + // and 4) and sample back decoded HDR floats through the E5B9G9R9 sampled view (binding 0). +#ifdef LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV + if (d.bindless) { + const VkDescriptorSet set0 = rt::d3d12::bindless_set(device.p); + const VkDescriptorSetLayout set0_layout = rt::d3d12::bindless_set_layout(device.p); + EXPECT(set0 && set0_layout); + + const auto desc_rt = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 4, 4, 1, 1, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref rt_tex; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_rt, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&rt_tex.p)))); + device->CreateUnorderedAccessView(rt_tex.p, nullptr, nullptr, slot(8)); + device->CreateShaderResourceView(rt_tex.p, nullptr, slot(9)); + const g::ImageWords rt_uav_words = words_at(8); + const g::ImageWords rt_srv_words = words_at(9); + EXPECT(!all_zero(rt_uav_words.data(), sizeof(rt_uav_words)) && rt_uav_words == rt_srv_words); + + Ref smp_heap; + const D3D12_DESCRIPTOR_HEAP_DESC shd{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&shd, IID_PPV_ARGS(&smp_heap.p)))); + D3D12_SAMPLER_DESC sd{}; + sd.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sd.AddressU = sd.AddressV = sd.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + const auto smp_h = smp_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateSampler(&sd, smp_h); + g::SamplerWords smp_words{}; + std::memcpy(smp_words.data(), reinterpret_cast(smp_h.ptr), sizeof(smp_words)); + + // Flush set-0 descriptors and transition texture into GENERAL (UAV / bindless-sampled state). + Ref queue; + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + Ref alloc; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + const float seed[4] = {1.0f, 2.0f, 4.0f, 0.0f}; + list->ClearUnorderedAccessViewFloat({0}, slot(8), rt_tex.p, seed, 0, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + + // 16 distinct packed RGB9E5 words spanning subnormals, normal HDR, and max finite 65408. + const std::array input_words = { + 0x94010040u, // (1, 2, 4) + 0x79010100u, // (0.5, 0.25, 0.125) + 0x80000100u, // (1, 0, 0) + 0x80020000u, // (0, 1, 0) + 0x84000000u, // (0, 0, 1) + 0xb0080190u, // (100, 0, 0.5) + 0xf80001ffu, // (65408, 0, 0) + 0xffffffffu, // (65408, 65408, 65408) + 0x08000100u, // (2^-15, 0, 0) -- second half written through binding 4 (r32ui) + 0x00000100u, // (2^-16, 0, 0) + 0x00000001u, // (2^-24, 0, 0) + 0x7556ab55u, // (1/3, 1/3, 1/3) quantised + 0x840e0501u, // (257/256, 258/256, 259/256) + 0x98040100u, // (2, 1, 8)? exact decode checked via uav_clear::decode + 0x00000000u, // (0, 0, 0) + 0x88040280u, // (2.5, 1.0, 2.0) + }; + std::array sampled{}; + EXPECT(run_bindless_roundtrip(d, set0, set0_layout, rt_uav_words, rt_srv_words, smp_words, + !native_storage, input_words, sampled)); + for (UINT i = 0; i < 16; ++i) { + const std::uint32_t want_word = native_storage ? 0x94010040u : input_words[i]; + leonida::uav_clear::Element elem{}; + elem.size = 4; + std::memcpy(elem.bytes.data(), &want_word, 4); + VkClearColorValue want{}; + EXPECT(leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, elem, want)); + for (UINT c = 0; c < 4; ++c) { + const float got = sampled[i * 4 + c]; + const float exp_v = want.float32[c]; + const float tol = std::max(1e-6f, std::fabs(exp_v) * 1e-5f); + if (std::fabs(got - exp_v) > tol) { + std::fprintf(stderr, "bindless sample texel %u ch %u: got %g, want %g (word 0x%08x)\n", + i, c, got, exp_v, want_word); + return 1; + } + } + } + std::printf("Bindless set-0 GPU round-trip: 16/16 HDR RGB9E5 texels matched (%s)\n", + native_storage ? "clear -> sampled E5B9G9R9" + : "storage R32_UINT [bindings 9 & 4] -> sampled E5B9G9R9 [binding 0]"); + } +#endif + } + + if (d.validation_errors()) { + std::fprintf(stderr, "%u Vulkan validation errors\n", d.validation_errors()); + return 1; + } + std::printf("d3d12_r9g9b9e5_uav_test: OK (0 validation errors)\n"); + return 0; +} diff --git a/runtime/test/d3d12_typeless_rtv_test.cpp b/runtime/test/d3d12_typeless_rtv_test.cpp index 663491aef..fbd41508b 100644 --- a/runtime/test/d3d12_typeless_rtv_test.cpp +++ b/runtime/test/d3d12_typeless_rtv_test.cpp @@ -28,8 +28,10 @@ struct Event { struct ClearOptions { bool automatic_mips = false; - int predicate = -1; // -1: disabled; otherwise the upload buffer contains this value. + bool predication = false; + std::uint64_t predicate = 0; D3D12_PREDICATION_OP operation = D3D12_PREDICATION_OP_EQUAL_ZERO; + bool overwrite_predicate = false; }; bool clear_and_read(ID3D12Device* device, DXGI_FORMAT whole_format, DXGI_FORMAT rect_format, bool partial, @@ -111,21 +113,43 @@ bool clear_and_read(ID3D12Device* device, DXGI_FORMAT whole_format, DXGI_FORMAT device->CreateRenderTargetView(image.p, &view, handle); view.Format = rect_format; device->CreateRenderTargetView(image.p, &view, other); - Ref predicate; - if (options.predicate >= 0) { + Ref predicate, predicate_upload; + if (options.predication) { D3D12_RESOURCE_DESC predicate_desc = buffer; - predicate_desc.Width = 8; + predicate_desc.Width = 16; const D3D12_HEAP_PROPERTIES upload{D3D12_HEAP_TYPE_UPLOAD}; CHECK(SUCCEEDED(device->CreateCommittedResource(&upload, D3D12_HEAP_FLAG_NONE, &predicate_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&predicate.p)))); + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&predicate_upload.p)))); void* mapped = nullptr; const D3D12_RANGE none{}; - CHECK(SUCCEEDED(predicate->Map(0, &none, &mapped)) && mapped); - const UINT64 value = UINT64(options.predicate); - std::memcpy(mapped, &value, sizeof(value)); - const D3D12_RANGE written{0, sizeof(value)}; - predicate->Unmap(0, &written); - list->SetPredication(predicate.p, 0, options.operation); + CHECK(SUCCEEDED(predicate_upload->Map(0, &none, &mapped)) && mapped); + const UINT64 values[] = {options.predicate, options.predicate ? 0u : 1u}; + std::memcpy(mapped, values, sizeof(values)); + const D3D12_RANGE written{0, sizeof(values)}; + predicate_upload->Unmap(0, &written); + const auto transition_predicate = [&](D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = predicate.p; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = before; barrier.Transition.StateAfter = after; + list->ResourceBarrier(1, &barrier); + }; + if (options.overwrite_predicate) { + const D3D12_HEAP_PROPERTIES local{D3D12_HEAP_TYPE_DEFAULT}; + CHECK(SUCCEEDED(device->CreateCommittedResource(&local, D3D12_HEAP_FLAG_NONE, &predicate_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&predicate.p)))); + list->CopyBufferRegion(predicate.p, 0, predicate_upload.p, 0, 8); + transition_predicate(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PREDICATION); + } + list->SetPredication(predicate.p ? predicate.p : predicate_upload.p, 0, options.operation); + if (options.overwrite_predicate) { + // Choose only predicates that execute this copy on both backends. Subsequent clears must still use + // the captured value, even though the predicate buffer now has the opposite zero/nonzero value. + transition_predicate(D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(predicate.p, 0, predicate_upload.p, 8, 8); + transition_predicate(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PREDICATION); + } } list->ClearRenderTargetView(handle, full, 0, nullptr); if (rewrite) { @@ -136,7 +160,7 @@ bool clear_and_read(ID3D12Device* device, DXGI_FORMAT whole_format, DXGI_FORMAT const D3D12_RECT rect = array || mip_chain ? D3D12_RECT{mip == 2 ? 0 : 1, 0, LONG(std::max(1u, width >> mip)), LONG(std::max(1u, height >> mip))} : D3D12_RECT{1, 1, 4, 3}; if (partial) list->ClearRenderTargetView(other, part, 1, &rect); - if (predicate.p) list->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + if (options.predication) list->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); D3D12_RESOURCE_BARRIER barrier{}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Transition.pResource = image.p; @@ -229,6 +253,7 @@ int main() { info.queue = vk.queue; info.queue_family = vk.family; info.conditional_rendering = vk.conditional_rendering; + info.storage_buffer_8bit = vk.storage_buffer_8bit; if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; Ref factory; Ref warp; @@ -335,12 +360,16 @@ int main() { for (const auto whole : formats) { for (const auto part : formats) { if (!partial && part != whole) continue; // No rectangle: one case per whole-view format. - for (int predicate : {-1, 0, 1}) { - if (predicate >= 0 && !vk.conditional_rendering) continue; + for (const auto predicate : {std::pair{false, UINT64_C(0)}, std::pair{true, UINT64_C(0)}, + std::pair{true, UINT64_C(1)}, std::pair{true, UINT64_C(1) << 32}, + std::pair{true, (UINT64_C(1) << 32) | 7}, std::pair{true, UINT64_MAX}}) { + if (predicate.first && !vk.conditional_rendering) continue; for (bool inverted : {false, true}) { - if (predicate < 0 && inverted) continue; - ClearOptions options{automatic, predicate, inverted ? D3D12_PREDICATION_OP_NOT_EQUAL_ZERO + if (!predicate.first && inverted) continue; + ClearOptions options{automatic, predicate.first, predicate.second, inverted ? D3D12_PREDICATION_OP_NOT_EQUAL_ZERO : D3D12_PREDICATION_OP_EQUAL_ZERO}; + options.overwrite_predicate = vk.storage_buffer_8bit && automatic && predicate.first && + (inverted ? predicate.second == 0 : predicate.second != 0); const UINT first = array ? 1 : 0, layers = array ? 2 : 1; std::vector actual, expected; if (!clear_and_read(ours.p, whole, part, partial, true, false, actual, @@ -349,7 +378,7 @@ int main() { mip, first, layers, array, true, options)) return 1; ++comparisons; ++regressions; if (actual.size() != expected.size()) return 1; - const bool executes = predicate < 0 || (inverted ? predicate == 0 : predicate != 0); + const bool executes = !predicate.first || (inverted ? predicate.second == 0 : predicate.second != 0); std::size_t offset = 0; for (UINT layer = 0; layer < (array ? 4u : 1u); ++layer) { for (UINT level = 0; level < 3; ++level) { @@ -365,8 +394,8 @@ int main() { const std::size_t i = offset + (y * w + x) * 4 + channel; if ((!selected && (actual[i] != seed[channel] || expected[i] != seed[channel])) || std::abs(int(actual[i]) - int(expected[i])) > tolerance) { - std::fprintf(stderr, "subresource regression partial %d array %d auto %d mip %u formats %d/%d predicate %d inverted %d layer %u level %u texel %u,%u channel %u: Vulkan %u WARP %u\n", - int(partial), int(array), int(automatic), mip, int(whole), int(part), predicate, int(inverted), layer, level, x, y, channel, + std::fprintf(stderr, "subresource regression partial %d array %d auto %d mip %u formats %d/%d predicate %llu inverted %d layer %u level %u texel %u,%u channel %u: Vulkan %u WARP %u\n", + int(partial), int(array), int(automatic), mip, int(whole), int(part), static_cast(predicate.second), int(inverted), layer, level, x, y, channel, unsigned(actual[i]), unsigned(expected[i])); return 1; } diff --git a/runtime/test/d3d12_uav_clear_test.cpp b/runtime/test/d3d12_uav_clear_test.cpp index 55b344ac8..2e13f033b 100644 --- a/runtime/test/d3d12_uav_clear_test.cpp +++ b/runtime/test/d3d12_uav_clear_test.cpp @@ -88,6 +88,20 @@ int conversion_checks() { // Too large is the largest finite on every channel (host: 0xf7fdffbf), and 1/3 truncates (host: 0x1aa). EXPECT(word(element(VK_FORMAT_B10G11R11_UFLOAT_PACK32, true, floats(1e6f, 1e6f, 1e6f, 0))) == 0xf7fdffbfu); EXPECT(word(element(VK_FORMAT_B10G11R11_UFLOAT_PACK32, true, floats(0, 0, 1.0f / 3, 0))) >> 22 == 0x1aau); + // Shared-exponent 9:9:9:5 float (pinned against WARP): round half-up, bump on 512, clamp negatives/NaN to 0 + // and +Inf/overflow to 65408; Uint clears to zero. + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(0, 0, 0, 1))) == 0x00000000u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(1.0f, 2.0f, 4.0f, 0))) == 0x94010040u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(0.5f, 0.25f, 0.125f, 0))) == 0x79010100u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(1.0f / 3, 1.0f / 3, 1.0f / 3, 0))) == 0x7556ab55u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, + floats(1.0f + 0.5f / 256, 1.0f + 1.5f / 256, 1.0f + 2.5f / 256, 0))) == 0x840e0501u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(1.0f - 0.25f / 256, 0, 0, 0))) == 0x80000100u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(65408.0f, 65472.0f, INFINITY, 0))) == 0xffffffffu); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(std::ldexp(1.0f, -25), 0, 0, 0))) == 0x00000001u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(std::ldexp(511.5f, -24), 0, 0, 0))) == 0x08000100u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(-1.0f, 1.0f, NAN, 0))) == 0x80020000u); + EXPECT(word(element(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, false, {0x3f800000u, 0xffffffffu, 1u, 2u})) == 0u); // Float into an integer channel: toward zero, clamped. EXPECT(word(element(VK_FORMAT_R32_SINT, true, floats(-3.7f, 0, 0, 0))) == std::uint32_t(-3)); EXPECT((element(VK_FORMAT_R8G8_UINT, true, floats(300.0f, -5.0f, 0, 0)) == V{0xff, 0x00})); @@ -101,6 +115,11 @@ int conversion_checks() { EXPECT(value.uint32[0] == 0xff && value.uint32[1] == 0x80 && value.uint32[2] == 0 && value.uint32[3] == 0xff); EXPECT(uc::encode(VK_FORMAT_R8_UINT, false, {0x80, 0, 0, 0}, e) && uc::decode(VK_FORMAT_R8_SINT, e, value) && value.int32[0] == -128); + // R9G9B9E5 decodes both to R32_UINT (emulated backing) and to float RGB (native backing). + EXPECT(uc::encode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(1.0f, 2.0f, 4.0f, 0), e) && + uc::decode(VK_FORMAT_R32_UINT, e, value) && value.uint32[0] == 0x94010040u); + EXPECT(uc::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, e, value) && value.float32[0] == 1.0f && + value.float32[1] == 2.0f && value.float32[2] == 4.0f); EXPECT(!uc::encode(VK_FORMAT_BC1_RGBA_UNORM_BLOCK, false, {}, e)); // not a typed-UAV format EXPECT(!uc::decode(VK_FORMAT_R16_UINT, e, value)); // e is one byte, R16 is two return 0; @@ -570,7 +589,36 @@ int main() { {"RGBA8_UNORM volume, one mip", DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 2, 4, true, {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {1, 2, 3, 4}, 1, 0, 1)}}, }; - for (const auto& test : textures) + std::vector all_textures = textures; + { + D3D12_FEATURE_DATA_FORMAT_SUPPORT e5_support{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; + if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &e5_support, sizeof(e5_support))) && + (e5_support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) { + // Full-view Float and Uint clears work whether R9G9B9E5 UAV is native or backed by mutable R32_UINT. + TextureCase e5{"R9G9B9E5_SHAREDEXP array, Float and Uint", DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 8, 8, 2, 2, false, + {texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, floats(1.0f, 2.0f, 4.0f, 0.0f), + 0, 0, 2), + texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, + floats(0.5f, 0.25f, 0.125f, 0.0f), 1, 1, 1), + texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, false, + {0x3f800000u, 0xffffffffu, 1u, 2u}, 0, 1, 1)}}; + VkFormatProperties e5_props{}; + d.instance_fn("vkGetPhysicalDeviceFormatProperties")( + d.physical, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, &e5_props); + const bool native_storage = (e5_props.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; + const bool native_attach = (e5_props.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; + if (!native_storage || native_attach) { + // Emulated R32_UINT images (or native ones with COLOR_ATTACHMENT) also clear partial rectangles. + e5.clears.push_back(texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true, + floats(100.0f, 0.001f, 0.5f, 0.0f), 0, 0, 1, {{1, 2, 5, 6}})); + e5.clears.push_back(texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, false, + {0x12345678u, 0x9abcdef0u, 0u, 0u}, 0, 0, 1, {{2, 3, 4, 5}})); + } + all_textures.push_back(std::move(e5)); + } + } + for (const auto& test : all_textures) if (run_texture(h, test)) return 1; // Refused while recording (Close says E_INVALIDARG): no values, an empty slot, no resource. diff --git a/runtime/test/d3d12_xs_root_signature_test.cpp b/runtime/test/d3d12_xs_root_signature_test.cpp index 07b9e3f82..aee02246f 100644 --- a/runtime/test/d3d12_xs_root_signature_test.cpp +++ b/runtime/test/d3d12_xs_root_signature_test.cpp @@ -202,11 +202,16 @@ void test_version_1_1(SerializeFn serialize, DeserializeFn deserialize, ID3D12De } void test_version_1_2(SerializeFn serialize, DeserializeFn deserialize, ID3D12Device& device) { - // Older in-box D3D12 runtimes (e.g. Windows 11 23H2) refuse root signature - // 1.2 entirely, so the whole 1.2 path is skipped there. + // Older in-box D3D12 runtimes refuse root signature 1.2, so the whole 1.2 path is skipped there. + // Windows 11 23H2 answers with a lower HighestVersion; Windows 10 doesn't know 1.2 and fails the + // query with E_INVALIDARG instead. D3D12_FEATURE_DATA_ROOT_SIGNATURE feature{D3D_ROOT_SIGNATURE_VERSION_1_2}; - require_success(device.CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &feature, sizeof(feature)), - "query WARP root signature support"); + const HRESULT query = device.CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &feature, sizeof(feature)); + if (query == E_INVALIDARG) { + std::puts("SKIP root signature 1.2 (runtime does not know version 1.2)"); + return; + } + require_success(query, "query WARP root signature support"); if (feature.HighestVersion < D3D_ROOT_SIGNATURE_VERSION_1_2) { std::puts("SKIP root signature 1.2 (runtime HighestVersion < 1.2)"); return; diff --git a/runtime/test/depth24_convert_test.cpp b/runtime/test/depth24_convert_test.cpp index 55030dd19..00933b0ff 100644 --- a/runtime/test/depth24_convert_test.cpp +++ b/runtime/test/depth24_convert_test.cpp @@ -12,11 +12,14 @@ // GPU without D24. Steps 3 and 4 use converters with a 1 MiB and a 1 KiB storage range, so copies split into dispatches. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. #include "vk_test_device.h" +#include "../src/vulkan_backend.h" #include "../src/vulkan_depth24.h" +#include #include #include #include +#include #include #define EXPECT(condition) do { \ @@ -44,10 +47,12 @@ std::uint32_t as_bits(float f) { int main() { vktest::Device gpu; - if (!gpu.create()) { + const auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) { std::printf("depth24_convert_test: no Vulkan device, skipped\n"); - return 0; + return 77; } + if (status != vktest::DeviceStatus::ready) return 1; // The converter allocates nothing here (every job brings its scratch buffer), but the callback must exist. Depth24Converter converter(gpu.device_proc, gpu.device, [](const VkMemoryRequirements&) { return VK_NULL_HANDLE; }); @@ -114,6 +119,21 @@ int main() { EXPECT(wrong == 0); std::printf("depth24: all %u words survive float and back\n", words); + // All payloads and both signs with an all-ones exponent. Only positive infinity saturates. + for (std::uint32_t i = 0; i < words; ++i) + scratch_words[i] = 0x7f800000u | ((i & 0x800000u) << 8) | (i & 0x7fffffu); + std::memset(app_words, 0xcd, std::size_t(words) * 4); + EXPECT(convert(false, 4096, 4096, 1, 4096, words, 0)); + wrong = 0; + for (std::uint32_t i = 0; i < words; ++i) { + const std::uint32_t want = i == 0 ? 0xffffffu : 0u; + if (app_words[i] != want && wrong++ < 8) + std::fprintf(stderr, "special: f=%08x got %u want %u\n", scratch_words[i], app_words[i], want); + } + if (wrong) std::fprintf(stderr, "special: %llu mismatches\n", static_cast(wrong)); + EXPECT(wrong == 0); + std::printf("depth24: both infinities and all NaN payloads quantise correctly\n"); + // 3. float patterns to words, against the reference. { std::uint32_t x = 7; @@ -184,6 +204,149 @@ int main() { std::printf("depth24: a pitched copy at an offset touches only its texels\n"); } + // 5. Concurrent VulkanQueue::execute() with enable_depth24 active: one queue runs depth24_as_float + // CopyTexture roundtrips (lazy tracker_mutex_ acquisition + collect/retire), while a second queue + // runs non-depth24 CopyBuffer batches concurrently (parallel prepare()), plus an early-failure batch + // that triggers Depth24Guard retirement. + { + VkPhysicalDeviceMemoryProperties mem_props{}; + gpu.instance_fn("vkGetPhysicalDeviceMemoryProperties")( + gpu.physical, &mem_props); + const auto alloc_device_local = [&](const VkMemoryRequirements& req) -> VkDeviceMemory { + for (std::uint32_t i = 0; i < mem_props.memoryTypeCount; ++i) { + if (!(req.memoryTypeBits & (1u << i))) continue; + if ((mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) + continue; + VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + info.allocationSize = req.size; + info.memoryTypeIndex = i; + VkDeviceMemory mem = VK_NULL_HANDLE; + if (gpu.fn("vkAllocateMemory")(gpu.device, &info, nullptr, &mem) == VK_SUCCESS) + return mem; + return VK_NULL_HANDLE; + } + return VK_NULL_HANDLE; + }; + + VulkanContext context(gpu.device_proc, gpu.device, true); + EXPECT(context.loaded()); + context.enable_depth24(gpu.device_proc, alloc_device_local); + + constexpr int kIters = 16; + constexpr std::uint32_t tex_w = 64, tex_h = 16; + constexpr std::uint32_t tex_words = tex_w * tex_h; + constexpr std::uint64_t tex_bytes = std::uint64_t(tex_words) * 4; + const VkImage depth_img = + gpu.image(VK_FORMAT_D32_SFLOAT_S8_UINT, tex_w, tex_h, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + EXPECT(depth_img != VK_NULL_HANDLE); + + std::uint32_t *d24_up_ptr = nullptr, *d24_rb_ptr = nullptr; + std::uint32_t *buf_src_ptr = nullptr, *buf_dst_ptr = nullptr; + const VkBuffer d24_up = gpu.buffer(tex_bytes, usage, reinterpret_cast(&d24_up_ptr)); + const VkBuffer d24_rb = gpu.buffer(tex_bytes * kIters, usage, reinterpret_cast(&d24_rb_ptr)); + const VkBuffer buf_src = gpu.buffer(tex_bytes, usage, reinterpret_cast(&buf_src_ptr)); + const VkBuffer buf_dst = gpu.buffer(tex_bytes * kIters, usage, reinterpret_cast(&buf_dst_ptr)); + EXPECT(d24_up && d24_rb && buf_src && buf_dst); + + for (std::uint32_t i = 0; i < tex_words; ++i) { + d24_up_ptr[i] = ((i * 15973u + 13u) & depth24_max) | (0x7eu << 24); + buf_src_ptr[i] = 0x12340000u + i; + } + + constexpr ResourceId id_depth = 1, id_d24_up = 2, id_d24_rb = 3, id_buf_src = 4, id_buf_dst = 5; + ResourceBinding img_b{}; + img_b.image = depth_img; + img_b.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + img_b.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + img_b.width = tex_w; + img_b.height = tex_h; + img_b.mip_levels = 1; + img_b.array_layers = 1; + img_b.depth = 1; + img_b.samples = 1; + img_b.depth24 = true; + img_b.depth24_as_float = true; + context.add_resource(id_depth, img_b, VK_IMAGE_LAYOUT_UNDEFINED); + + const auto reg_buf = [&](ResourceId id, VkBuffer buf, VkDeviceSize sz, bool readback) { + ResourceBinding b{}; + b.buffer = buf; + b.size = sz; + b.host_readable = readback; + context.add_resource(id, b); + }; + reg_buf(id_d24_up, d24_up, tex_bytes, false); + reg_buf(id_d24_rb, d24_rb, tex_bytes * kIters, true); + reg_buf(id_buf_src, buf_src, tex_bytes, false); + reg_buf(id_buf_dst, buf_dst, tex_bytes * kIters, true); + + VulkanQueue queue_a(context, gpu.queue, gpu.family); + VulkanQueue queue_b(context, gpu.queue, gpu.family); + EXPECT(queue_a.ok() && queue_b.ok()); + + std::vector d24_lists(kIters); + std::vector buf_lists(kIters); + for (int iter = 0; iter < kIters; ++iter) { + const std::uint64_t off = std::uint64_t(iter) * tex_bytes; + CopyLocation fp_up{id_d24_up, true, 0, 0, tex_w, tex_h, 1, tex_w * 4}; + CopyLocation fp_rb{id_d24_rb, true, 0, off, tex_w, tex_h, 1, tex_w * 4}; + CopyLocation tex_loc{id_depth, false, 0, 0, 0, 0, 0, 0}; + EXPECT(d24_lists[iter].copy_texture(CopyTexture{tex_loc, 0, 0, 0, fp_up, false, {}})); + EXPECT(d24_lists[iter].copy_texture(CopyTexture{fp_rb, 0, 0, 0, tex_loc, false, {}})); + EXPECT(d24_lists[iter].close()); + + EXPECT(buf_lists[iter].copy_buffer(CopyBuffer{id_buf_dst, off, id_buf_src, 0, tex_bytes})); + EXPECT(buf_lists[iter].close()); + } + + // Early-failure batch: valid depth24_as_float copy followed by an unknown resource copy must fail cleanly + // and retire the uncommitted depth24 scratch via Depth24Guard without corrupting subsequent executions. + { + CommandList failing_list; + CopyLocation fp_up{id_d24_up, true, 0, 0, tex_w, tex_h, 1, tex_w * 4}; + CopyLocation tex_loc{id_depth, false, 0, 0, 0, 0, 0, 0}; + EXPECT(failing_list.copy_texture(CopyTexture{tex_loc, 0, 0, 0, fp_up, false, {}})); + EXPECT(failing_list.copy_buffer(CopyBuffer{99999, 0, id_buf_src, 0, 4})); + EXPECT(failing_list.close()); + const CommandList* ptrs[] = {&failing_list}; + EXPECT(queue_a.execute(ptrs) == ReplayResult::unresolved_resource); + } + + std::atomic failed{false}; + std::thread ta([&] { + for (int iter = 0; iter < kIters; ++iter) { + const CommandList* ptrs[] = {&d24_lists[iter]}; + if (queue_a.execute(ptrs) != ReplayResult::success) { + failed.store(true); + break; + } + } + }); + std::thread tb([&] { + for (int iter = 0; iter < kIters; ++iter) { + const CommandList* ptrs[] = {&buf_lists[iter]}; + if (queue_b.execute(ptrs) != ReplayResult::success) { + failed.store(true); + break; + } + } + }); + ta.join(); + tb.join(); + EXPECT(!failed.load()); + EXPECT(gpu.fn("vkDeviceWaitIdle")(gpu.device) == VK_SUCCESS); + + for (int iter = 0; iter < kIters; ++iter) { + const std::size_t base = std::size_t(iter) * tex_words; + for (std::uint32_t i = 0; i < tex_words; ++i) { + EXPECT(d24_rb_ptr[base + i] == (d24_up_ptr[i] & depth24_max)); + EXPECT(buf_dst_ptr[base + i] == buf_src_ptr[i]); + } + } + std::printf("depth24: concurrent VulkanQueue::execute (lazy depth24 lock + parallel non-d24 prepare) ok\n"); + } + EXPECT(gpu.validation_errors() == 0); std::printf("depth24_convert_test: ok\n"); return 0; diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp index fb6f2a6b4..1451ba6de 100644 --- a/runtime/test/dxgi_swapchain_test.cpp +++ b/runtime/test/dxgi_swapchain_test.cpp @@ -527,13 +527,133 @@ int main() { return fail("ResizeBuffers should reject unsupported format DXGI_FORMAT_R32_UINT"); // Measured on host DXGI (RTX 5070 and WARP): DXGI_PRESENT_TEST returns S_OK without presenting, so the back - // buffer index stays; a sync interval above 4 is DXGI_ERROR_INVALID_CALL and presents nothing either. + // buffer index and last present count stay; a sync interval above 4 is DXGI_ERROR_INVALID_CALL and presents nothing. { const UINT before = sc->GetCurrentBackBufferIndex(); + UINT count_before = 0; + if (FAILED(sc->GetLastPresentCount(&count_before)) || count_before == 0) + return fail("GetLastPresentCount should be non-zero after earlier Presents"); if (sc->Present(0, DXGI_PRESENT_TEST) != S_OK || sc->GetCurrentBackBufferIndex() != before) return fail("Present(0, DXGI_PRESENT_TEST) presented a frame"); + UINT count_after_test = 0; + if (FAILED(sc->GetLastPresentCount(&count_after_test)) || count_after_test != count_before) + return fail("DXGI_PRESENT_TEST should not increment GetLastPresentCount"); if (sc->Present(5, 0) != DXGI_ERROR_INVALID_CALL || sc->GetCurrentBackBufferIndex() != before) return fail("Present(5, 0) should be DXGI_ERROR_INVALID_CALL and present nothing"); + if (sc->GetLastPresentCount(nullptr) != E_INVALIDARG) + return fail("GetLastPresentCount(nullptr) should return E_INVALIDARG"); + } + + // SwapChain::GetParent and SetMaximumFrameLatency/GetMaximumFrameLatency. + { + IDXGIFactory4* parent = nullptr; + if (FAILED(sc->GetParent(IID_PPV_ARGS(&parent))) || parent != factory) + return fail("SwapChain::GetParent did not return the parent factory"); + parent->Release(); + UINT lat = 0; + if (FAILED(sc->GetMaximumFrameLatency(&lat)) || lat != 2) + return fail("Default GetMaximumFrameLatency should be 2"); + if (sc->SetMaximumFrameLatency(0) != E_INVALIDARG || sc->SetMaximumFrameLatency(17) != E_INVALIDARG) + return fail("SetMaximumFrameLatency should reject 0 and > 16 with E_INVALIDARG"); + if (FAILED(sc->SetMaximumFrameLatency(3)) || FAILED(sc->GetMaximumFrameLatency(&lat)) || lat != 3) + return fail("SetMaximumFrameLatency(3) round-trip failed"); + } + + // IDXGIFactory4 adapter enumeration, IDXGIAdapter3 descriptors, EnumAdapterByLuid, and QueryVideoMemoryInfo. + { + IDXGIAdapter1* adapter1 = nullptr; + if (FAILED(factory->EnumAdapters1(0, &adapter1)) || !adapter1) + return fail("EnumAdapters1(0) failed"); + IDXGIAdapter1* missing = nullptr; + if (factory->EnumAdapters1(1, &missing) != DXGI_ERROR_NOT_FOUND || missing != nullptr) + return fail("EnumAdapters1(1) should return DXGI_ERROR_NOT_FOUND"); + + IDXGIAdapter* adapter0 = nullptr; + if (FAILED(factory->EnumAdapters(0, &adapter0)) || !adapter0) + return fail("EnumAdapters(0) failed"); + adapter0->Release(); + + IDXGIFactory4* adapter_parent = nullptr; + if (FAILED(adapter1->GetParent(IID_PPV_ARGS(&adapter_parent))) || adapter_parent != factory) + return fail("Adapter::GetParent did not return the parent factory"); + adapter_parent->Release(); + + IDXGIAdapter3* adapter3 = nullptr; + if (FAILED(adapter1->QueryInterface(IID_PPV_ARGS(&adapter3))) || !adapter3) + return fail("QueryInterface(IDXGIAdapter3) failed"); + + DXGI_ADAPTER_DESC desc0{}; + DXGI_ADAPTER_DESC1 desc1{}; + DXGI_ADAPTER_DESC2 desc2{}; + if (FAILED(adapter3->GetDesc(&desc0)) || FAILED(adapter3->GetDesc1(&desc1)) || FAILED(adapter3->GetDesc2(&desc2))) + return fail("Adapter GetDesc/GetDesc1/GetDesc2 failed"); + if (desc1.Description[0] == L'\0' || desc1.VendorId != chosen.vendorID || desc1.DeviceId != chosen.deviceID) + return fail("Adapter desc did not match Vulkan physical device"); + if (desc1.DedicatedVideoMemory + desc1.SharedSystemMemory == 0) + return fail("Adapter reported zero total memory"); + if (const auto get_mem = reinterpret_cast( + gipa(instance, "vkGetPhysicalDeviceMemoryProperties"))) { + VkPhysicalDeviceMemoryProperties mem{}; + get_mem(physical, &mem); + VkDeviceSize max_local = 0; + for (std::uint32_t i = 0; i < mem.memoryHeapCount; ++i) { + if ((mem.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) && mem.memoryHeaps[i].size > max_local) + max_local = mem.memoryHeaps[i].size; + } + if (desc1.DedicatedVideoMemory != static_cast(max_local)) + return fail("DedicatedVideoMemory should match the primary DEVICE_LOCAL heap (without double-counting BAR1)"); + } + if (desc0.VendorId != desc1.VendorId || desc2.DeviceId != desc1.DeviceId) + return fail("Adapter desc mismatch between GetDesc/GetDesc1/GetDesc2"); + + // EnumAdapterByLuid with matching LUID succeeds; bogus LUID returns DXGI_ERROR_NOT_FOUND. + IDXGIAdapter3* by_luid = nullptr; + if (FAILED(factory->EnumAdapterByLuid(desc1.AdapterLuid, IID_PPV_ARGS(&by_luid))) || !by_luid) + return fail("EnumAdapterByLuid(matching) failed"); + by_luid->Release(); + LUID bogus = desc1.AdapterLuid; + bogus.LowPart ^= 0x5a5a5a5au; + bogus.HighPart ^= 0x13572468; + if (factory->EnumAdapterByLuid(bogus, IID_PPV_ARGS(&by_luid)) != DXGI_ERROR_NOT_FOUND || by_luid != nullptr) + return fail("EnumAdapterByLuid(bogus) should return DXGI_ERROR_NOT_FOUND"); + + // QueryVideoMemoryInfo + SetVideoMemoryReservation (shared across distinct handles for the same LUID). + IDXGIAdapter3* by_luid_b = nullptr; + if (FAILED(factory->EnumAdapterByLuid(desc1.AdapterLuid, IID_PPV_ARGS(&by_luid_b))) || !by_luid_b) + return fail("EnumAdapterByLuid(second handle) failed"); + DXGI_QUERY_VIDEO_MEMORY_INFO local_info{}; + if (FAILED(adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local_info)) || + local_info.Budget == 0) + return fail("QueryVideoMemoryInfo(LOCAL) failed or reported 0 budget"); + if (FAILED(adapter3->SetVideoMemoryReservation(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, 64u * 1024u * 1024u))) + return fail("SetVideoMemoryReservation(LOCAL) failed"); + if (FAILED(adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local_info)) || + local_info.CurrentReservation != 64u * 1024u * 1024u) + return fail("SetVideoMemoryReservation did not reflect on handle A"); + DXGI_QUERY_VIDEO_MEMORY_INFO local_info_b{}; + if (FAILED(by_luid_b->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local_info_b)) || + local_info_b.CurrentReservation != 64u * 1024u * 1024u) + return fail("SetVideoMemoryReservation(LOCAL) did not reflect across second IDXGIAdapter3 handle"); + + DXGI_QUERY_VIDEO_MEMORY_INFO nonlocal_info{}; + if (FAILED(adapter3->SetVideoMemoryReservation(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, 32u * 1024u * 1024u)) || + FAILED(by_luid_b->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &nonlocal_info)) || + nonlocal_info.CurrentReservation != 32u * 1024u * 1024u) + return fail("SetVideoMemoryReservation(NON_LOCAL) did not reflect across second IDXGIAdapter3 handle"); + // Restore reservations to 0 and verify both handles see 0. + if (FAILED(adapter3->SetVideoMemoryReservation(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, 0)) || + FAILED(adapter3->SetVideoMemoryReservation(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, 0)) || + FAILED(by_luid_b->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local_info_b)) || + local_info_b.CurrentReservation != 0) + return fail("Restoring SetVideoMemoryReservation to 0 failed"); + by_luid_b->Release(); + + if (adapter3->QueryVideoMemoryInfo(1, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local_info) != E_INVALIDARG || + adapter3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, nullptr) != E_INVALIDARG) + return fail("QueryVideoMemoryInfo invalid args should return E_INVALIDARG"); + + adapter3->Release(); + adapter1->Release(); } // Host DXGI refuses ResizeBuffers with DXGI_ERROR_INVALID_CALL while the app still holds a back buffer, diff --git a/runtime/test/fixtures/tiny_async.cpp b/runtime/test/fixtures/tiny_async.cpp new file mode 100644 index 000000000..d2fcf4537 --- /dev/null +++ b/runtime/test/fixtures/tiny_async.cpp @@ -0,0 +1,83 @@ +// A mapped caller submits through its imports; the shim calls back into this image twice, +// once on the worker and once on the thread manually dispatching completions. +#include +#include + +#include +#include + +extern "C" __declspec(dllimport) HRESULT __stdcall XGameRuntimeInitialize(); +extern "C" __declspec(dllimport) void __stdcall XGameRuntimeUninitialize(); + +namespace { +struct Observation { + std::atomic work_calls{0}; + std::atomic completions{0}; + std::atomic worker_thread{0}; + std::atomic completion_thread{0}; + std::atomic result{E_PENDING}; +}; +Observation observed; +XAsyncBlock operation{}; // Outlives callbacks even if the test times out. + +HRESULT CALLBACK work(XAsyncBlock* block) { + auto* state = static_cast(block->context); + ++state->work_calls; + state->worker_thread = GetCurrentThreadId(); + return E_ACCESSDENIED; // Distinguish the operation result from XAsyncRun accepting the request. +} + +void CALLBACK completed(XAsyncBlock* block) { + auto* state = static_cast(block->context); + state->result = XAsyncGetStatus(block, false); + state->completion_thread = GetCurrentThreadId(); + ++state->completions; +} + +int fail(const char* stage, HRESULT hr) { + std::printf("tiny_async: FAIL %s (0x%08lx)\n", stage, static_cast(hr)); + return 1; +} + +int run_operation() { + XTaskQueueHandle queue = nullptr; + HRESULT hr = XTaskQueueCreate(XTaskQueueDispatchMode::ThreadPool, XTaskQueueDispatchMode::Manual, &queue); + if (hr != S_OK || !queue) return fail("queue creation", hr); + + operation.queue = queue; + operation.context = &observed; + operation.callback = completed; + hr = XAsyncRun(&operation, work); + if (hr != S_OK) { + XTaskQueueCloseHandle(queue); + return fail("submission", hr); + } + + const auto start = GetTickCount64(); + while (!observed.completions && GetTickCount64() - start < 5000) + XTaskQueueDispatch(queue, XTaskQueuePort::Completion, 50); + // Drain any already queued duplicate, with the same bounded deadline. + while (GetTickCount64() - start < 5000 && XTaskQueueDispatch(queue, XTaskQueuePort::Completion, 0)) {} + XTaskQueueCloseHandle(queue); + + const DWORD caller = GetCurrentThreadId(); + std::printf("tiny_async: work=%u completion=%u worker=%lu dispatcher=%lu caller=%lu result=0x%08lx\n", + observed.work_calls.load(), observed.completions.load(), observed.worker_thread.load(), + observed.completion_thread.load(), caller, static_cast(observed.result.load())); + if (observed.work_calls != 1 || observed.worker_thread == caller || + observed.completions != 1 || observed.completion_thread != caller || observed.result != E_ACCESSDENIED) + return 1; + return 0; +} +} // namespace + +int main() { + const HRESULT hr = XGameRuntimeInitialize(); + if (hr != S_OK) return fail("runtime initialization", hr); + const int result = run_operation(); + XGameRuntimeUninitialize(); + if (result != 0) return result; + std::puts("tiny_async: PASS"); + std::fflush(stdout); + return 0; +} diff --git a/runtime/test/fixtures/xgameruntime_stub.cpp b/runtime/test/fixtures/xgameruntime_stub.cpp index 749eda8fc..5f88736ea 100644 --- a/runtime/test/fixtures/xgameruntime_stub.cpp +++ b/runtime/test/fixtures/xgameruntime_stub.cpp @@ -4,7 +4,19 @@ #include #include +#include extern "C" __declspec(dllexport) HRESULT __stdcall XGameRuntimeInitialize() { return E_FAIL; } extern "C" __declspec(dllexport) void __stdcall XGameRuntimeUninitialize() {} extern "C" __declspec(dllexport) uint32_t __stdcall XSystemGetDeviceType() { return 0; } + +STDAPI XTaskQueueCreate( + XTaskQueueDispatchMode, XTaskQueueDispatchMode, XTaskQueueHandle* queue) noexcept { + *queue = nullptr; + return E_NOTIMPL; +} +STDAPI_(bool) XTaskQueueDispatch( + XTaskQueueHandle, XTaskQueuePort, uint32_t) noexcept { return false; } +STDAPI_(void) XTaskQueueCloseHandle(XTaskQueueHandle) noexcept {} +STDAPI XAsyncRun(XAsyncBlock*, XAsyncWork*) noexcept { return E_NOTIMPL; } +STDAPI XAsyncGetStatus(XAsyncBlock*, bool) noexcept { return E_NOTIMPL; } diff --git a/runtime/test/fixtures/xgameruntime_stub.def b/runtime/test/fixtures/xgameruntime_stub.def new file mode 100644 index 000000000..5c45833e6 --- /dev/null +++ b/runtime/test/fixtures/xgameruntime_stub.def @@ -0,0 +1,6 @@ +EXPORTS + XAsyncGetStatus + XAsyncRun + XTaskQueueCloseHandle + XTaskQueueCreate + XTaskQueueDispatch diff --git a/runtime/test/fsr_dispatch_test.cpp b/runtime/test/fsr_dispatch_test.cpp index 7b9be9461..1755ffd1d 100644 --- a/runtime/test/fsr_dispatch_test.cpp +++ b/runtime/test/fsr_dispatch_test.cpp @@ -4,6 +4,7 @@ // // LEONIDA_GAME_DIR= (contains amd_fidelityfx_upscaler_xbox.dll) // LEONIDA_FSR_WARP=1 (optional: use the WARP adapter instead of the default hardware adapter) +// LEONIDA_FSR_DEVICE=vulkan (optional: use the Vulkan-backed ID3D12Device instead of a PC device) // // Without LEONIDA_GAME_DIR it prints "SKIP (no package)" and exits 0. Nothing from the DLL is written to disk. // @@ -45,6 +46,9 @@ #include #include "../shims/d3d12_xs_device.h" +#ifdef LEONIDA_VULKAN_DEVICE +#include "../shims/d3d12_com.h" +#endif #include "../shims/shims.h" #include "../src/pe_loader.h" #include "ffx_api_min.h" @@ -722,8 +726,20 @@ int main() { check(!c.faulted && c.rc == ffx::RETURN_OK && rw == 2560 && rh == 1440, "QUALITY at 3840x2160 renders at 2560x1440"); // 5/6 need a device. - ID3D12Device* pc = create_pc_device(env("LEONIDA_FSR_WARP") == "1"); - check(pc != nullptr, "PC D3D12 device created"); + ID3D12Device* pc = nullptr; + const bool on_vulkan = env("LEONIDA_FSR_DEVICE") == "vulkan"; + if (on_vulkan) { +#ifdef LEONIDA_VULKAN_DEVICE + const HRESULT vhr = rt::d3d12::create_vulkan_device_standalone(__uuidof(ID3D12Device), + reinterpret_cast(&pc)); + note("LEONIDA_FSR_DEVICE=vulkan -> " + hex(static_cast(vhr))); +#else + check(false, "LEONIDA_FSR_DEVICE=vulkan needs a build with the Vulkan SDK (gta6rt_d3d12_com)"); +#endif + } else { + pc = create_pc_device(env("LEONIDA_FSR_WARP") == "1"); + } + check(pc != nullptr, on_vulkan ? "Vulkan-backed D3D12 device created" : "PC D3D12 device created"); if (!pc) return 1; void* proxy = nullptr; const HRESULT hr = rt::d3d12_xs::create_device_proxy(pc, __uuidof(ID3D12Device), &proxy); @@ -942,16 +958,20 @@ int main() { note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " + std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast(g_slot62_hr))); if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted)); - // On a PC device both pipeline paths fail (67 is refused, 62's code is not a PC shader), the - // dispatch goes on with a null pipeline and faults when it records it (RVA 0x65ff reads the - // pipeline's +0x10, the same pointer it passes to SetPipelineState): - // the documented end of what a PC device can run, not a test failure. + // On a PC device both pipeline paths fail (67 is refused, 62's code is not a PC shader); on the + // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes + // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10, + // the same pointer it passes to SetPipelineState): a documented stop, not a test failure. pipeline_stop = c.faulted && c.code == EXCEPTION_ACCESS_VIOLATION && g_slot62_calls > 0 && FAILED(g_slot62_hr); + const bool vulkan_stop = on_vulkan && c.faulted && c.code == EXCEPTION_ACCESS_VIOLATION; if (pipeline_stop) note("ffxDispatch stopped where the PC refused the DLL's compute pipeline, not a crash"); - check(!c.faulted || pipeline_stop || (c.code == kMsvcCppException && g_formatted > 0), - "ffxDispatch returns, or stops at a documented PC limit"); + else if (vulkan_stop) + note("ffxDispatch stopped where the Vulkan device returned E_NOTIMPL for CreateRootSignature"); + check(!c.faulted || pipeline_stop || vulkan_stop || + (c.code == kMsvcCppException && g_formatted > 0), + "ffxDispatch returns, or stops at a documented limit"); note("ffxDispatch: device slots below are the ones it called"); print_list_hits(); note("command list Close -> " + hex(static_cast(list->Close()))); diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index 30f8565b5..68066f58d 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp @@ -300,6 +300,9 @@ int main() { CHECK(info.borderColor == VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE && info.anisotropyEnable == VK_FALSE); // MIP_FILTER_NONE: the base level only. CHECK(info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST && info.minLod == 0.0f && info.maxLod == 0.25f); + CHECK(vulkan_sampler({.lod_bias = -32.0f}, 15.0f).mipLodBias == -15.0f); + CHECK(vulkan_sampler({.lod_bias = 31.0f}, 15.0f).mipLodBias == 15.0f); + CHECK(vulkan_sampler({.lod_bias = 2.25f}, 15.0f).mipLodBias == 2.25f); info = vulkan_sampler(point); CHECK(info.magFilter == VK_FILTER_NEAREST && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); CHECK(info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.mipLodBias == -0.75f); diff --git a/runtime/test/glsl/cs_r9g9b9e5_uav.comp b/runtime/test/glsl/cs_r9g9b9e5_uav.comp new file mode 100644 index 000000000..c9879064a --- /dev/null +++ b/runtime/test/glsl/cs_r9g9b9e5_uav.comp @@ -0,0 +1,69 @@ +#version 460 +// Compute shader for d3d12_r9g9b9e5_uav_test: verifies that an R9G9B9E5_SHAREDEXP UAV texture registered in set 0 +// can be written as packed RGB9E5 uint32 words through its R32_UINT storage views (binding 9 uimage2D and binding 4 +// r32ui) and then sampled back through set 0 binding 0 (VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) as decoded HDR float RGB +// values without validation errors. +#extension GL_EXT_nonuniform_qualifier : require + +layout(local_size_x = 16) in; + +layout(push_constant) uniform Params { + uint tsharp[8]; + uint ssharp[4]; + uint mode; // 0: write via binding 9 (first half) + binding 4 (second half); 1: sample via binding 0 + uint width; + uint height; + uint pad; +} pc; + +layout(set = 0, binding = 0) uniform texture2D sampled_images[]; +layout(set = 0, binding = 1) uniform sampler samplers[]; +layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { + uint map[]; +}; +layout(set = 0, binding = 4, r32ui) uniform writeonly uimage2D storage_r32ui_images[]; +layout(set = 0, binding = 9, r32ui) uniform writeonly uimage2D storage_uint_images[]; + +layout(set = 1, binding = 0, std430) readonly buffer InputWords { + uint packed_words[]; +}; +layout(set = 1, binding = 1, std430) writeonly buffer OutputFloats { + vec4 out_values[]; +}; + +uint lookup(uint key[8]) { + uint h = 2166136261u; + for (int i = 0; i < 8; ++i) h = (h ^ key[i]) * 16777619u; + const uint mask = map[0]; + for (uint k = 0; k < 8; ++k) { + const uint slot = 1 + ((h + k) & mask) * 10; + bool same = true; + for (int i = 0; i < 8; ++i) same = same && map[slot + i] == key[i]; + if (same) return map[slot + 8]; + } + return 0; +} + +void main() { + const uint i = gl_GlobalInvocationID.x; + const uint total = pc.width * pc.height; + if (i >= total) return; + uint image_key[8]; + for (int k = 0; k < 8; ++k) image_key[k] = pc.tsharp[k]; + const uint image = lookup(image_key); + const ivec2 xy = ivec2(i % pc.width, i / pc.width); + + if (pc.mode == 0u) { + if (i < total / 2u) { + imageStore(storage_uint_images[image], xy, uvec4(packed_words[i], 0u, 0u, 0u)); + } else { + imageStore(storage_r32ui_images[image], xy, uvec4(packed_words[i], 0u, 0u, 0u)); + } + } else { + uint sampler_key[8]; + for (int k = 0; k < 8; ++k) sampler_key[k] = k < 4 ? pc.ssharp[k] : 0xffffffffu; + const uint smp = lookup(sampler_key); + const vec2 uv = (vec2(xy) + 0.5) / vec2(float(pc.width), float(pc.height)); + out_values[i] = textureLod(sampler2D(sampled_images[image], samplers[smp]), uv, 0.0); + } +} diff --git a/runtime/test/predicated_copy_controls.h b/runtime/test/predicated_copy_controls.h new file mode 100644 index 000000000..6577dc712 --- /dev/null +++ b/runtime/test/predicated_copy_controls.h @@ -0,0 +1,44 @@ +// Independent byte destinations alongside the graphics-query fixtures. No game data. +#pragma once +#include "vk_test_device.h" +#include "../src/vulkan_backend.h" +#include +#include +struct PredicatedCopyControl { + static constexpr leonida::ResourceId source_id = 0x10001, destination_id = 0x10002; + bool active = false; + void* mapped = nullptr; + std::array input{}; + bool create(vktest::Device& d, leonida::VulkanContext& context, const VkPhysicalDeviceLimits& limits) { + active = d.conditional_rendering && d.storage_buffer_8bit; + if (!active) { + std::puts("occlusion copy controls: skipped (requires conditional rendering and storageBuffer8BitAccess)"); + return true; + } + context.configure_predicated_copy(d.device_proc, limits); + void* source = nullptr; + const auto src = d.buffer(16, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &source); + const auto dst = d.buffer(32, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &mapped); + if (!src || !dst || !source || !mapped) return false; + for (std::size_t i = 0; i < input.size(); ++i) input[i] = static_cast(37 * i + 11); + std::memcpy(source, input.data(), input.size()); + std::memset(mapped, 0xcd, 32); + leonida::ResourceBinding a{}, b{}; + a.buffer = src; a.size = 16; + b.buffer = dst; b.size = 32; b.host_readable = true; + context.add_resource(source_id, a); context.add_resource(destination_id, b); + return true; + } + // Caller has a false predicate set; the first half stays untouched, the second copies after reset. + bool record(leonida::CommandList& list) const { + return !active || (list.copy_buffer({destination_id, 0, source_id, 0, 16}) && + list.set_predication({0, 0, 0}) && list.copy_buffer({destination_id, 16, source_id, 0, 16})); + } + bool check() const { + if (!active) return true; + const auto* bytes = static_cast(mapped); + for (std::size_t i = 0; i < 16; ++i) if (bytes[i] != 0xcd || bytes[16 + i] != input[i]) return false; + std::puts("occlusion copy controls: false-predicate preservation and reset copy exact; query results unaffected"); + return true; + } +}; diff --git a/runtime/test/predicated_copy_test.cpp b/runtime/test/predicated_copy_test.cpp new file mode 100644 index 000000000..95e8da685 --- /dev/null +++ b/runtime/test/predicated_copy_test.cpp @@ -0,0 +1,95 @@ +// Preparation-only checks: no Vulkan calls, loader, shaders, GPU or game data. +#include "../src/vulkan_replay.h" +#include +#define EXPECT(x) do { if(!(x)){std::fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;} }while(0) +// Non-null capability markers; prepare() never calls these entry points. Nothing is emitted by this test. +templateT available(){return reinterpret_cast(+[](){});} +templateT handle(std::uintptr_t n){return reinterpret_cast(n);} +int main(){ + using namespace leonida; + ReplayFunctions vk{}; + vk.copy_buffer=available();vk.copy_buffer_to_image=available(); + vk.copy_image_to_buffer=available();vk.copy_image=available(); + vk.begin_conditional_rendering=available(); + vk.end_conditional_rendering=available(); + vk.prepare_predicate=[](VkBuffer,VkDeviceSize,PredicateCapture& out){out.scratch=handle(4);return true;}; + vk.capture_predicate=[](VkCommandBuffer,const PredicateCapture&){}; + ResourceBinding source{},destination{},predicate{}; + source.buffer=handle(1);source.size=64;source.buffer_offset=(UINT64_C(1)<<33)+1; + destination.buffer=handle(2);destination.size=64;destination.buffer_offset=(UINT64_C(1)<<34)+3; + predicate.buffer=handle(3);predicate.size=16; + auto resolve=[&](ResourceId id)->const ResourceBinding*{return id==1?&source:id==2?&destination:id==3?&predicate:nullptr;}; + VkDeviceSize got_src=0,got_dst=0,got_bytes=0;unsigned prepared=0; + auto copier=[&](VkBuffer a,VkBuffer b,VkDeviceSize src,VkDeviceSize dst,VkDeviceSize bytes,std::vector& jobs){ + if(a!=source.buffer||b!=destination.buffer)return false; + got_src=src;got_dst=dst;got_bytes=bytes;++prepared; + jobs.push_back({handle(5),0,0,static_cast(bytes)});return true; + }; + PreparedList result; + auto check=[&](CopyBuffer copy,bool predicated=true){ + CommandList list; + if(predicated)list.set_predication({3,8,d3d12_predication::equal_zero}); + list.copy_buffer(copy);list.close(); + return prepare(list,resolve,vk,result); + }; + EXPECT(check({2,3,1,1,7})==ReplayResult::unsupported); // optional capability absent + vk.prepare_predicated_copy=copier; + EXPECT(check({2,3,1,1,7})==ReplayResult::unsupported); // emitter absent + vk.emit_predicated_copy=[](VkCommandBuffer,const std::vector&){}; + EXPECT(check({2,3,1,1,7})==ReplayResult::success); + EXPECT(prepared==1&&got_src==source.buffer_offset+1&&got_dst==destination.buffer_offset+3&&got_bytes==7); + EXPECT(result.unpredicated_copies==0&&result.commands.back().buffer_copies.empty()); + EXPECT(check({2,63,1,63,1},false)==ReplayResult::success); + EXPECT(result.commands.back().buffer_copies[0].srcOffset==source.buffer_offset+63); + EXPECT(result.commands.back().buffer_copies[0].dstOffset==destination.buffer_offset+63&&prepared==1); + EXPECT(check({2,64,1,64,0})==ReplayResult::success&&prepared==1); // native no-op; no shader/descriptor + EXPECT(check({2,64,1,0,1})==ReplayResult::invalid_copy); + EXPECT(check({2,0,1,64,1})==ReplayResult::invalid_copy); + EXPECT(check({9,0,1,0,1})==ReplayResult::unresolved_resource); + const auto saved=source; + source.buffer_offset=UINT64_MAX; + EXPECT(check({2,0,1,1,1})==ReplayResult::invalid_copy); // offset addition + EXPECT(check({2,0,1,0,2})==ReplayResult::invalid_copy); // end addition + source=saved; + destination.buffer=source.buffer;destination.buffer_offset=source.buffer_offset; + EXPECT(check({2,1,1,0,7})==ReplayResult::invalid_copy); // physical overlap across resource IDs + EXPECT(check({2,8,1,0,7})==ReplayResult::success); // same buffer, disjoint ranges + destination.buffer=handle(2);destination.buffer_offset=0; + vk.prepare_predicated_copy=[](VkBuffer,VkBuffer,VkDeviceSize,VkDeviceSize,VkDeviceSize,std::vector&){return false;}; + EXPECT(check({2,0,1,0,1})==ReplayResult::unsupported); // allocation/preparation failure cannot fall back + vk.prepare_predicated_copy=copier; + CommandList resource_copy; + EXPECT(resource_copy.set_predication({3,0,d3d12_predication::equal_zero})); + EXPECT(resource_copy.copy_resource({2,1})&&resource_copy.close()); + EXPECT(prepare(resource_copy,resolve,vk,result)==ReplayResult::success&&result.unpredicated_copies==1); + vk.reset_query_pool=available();vk.begin_query=available(); + vk.end_query=available();vk.write_timestamp=available(); + vk.copy_query_pool_results=available();vk.fill_buffer=available(); + QueryPool pool{};pool.pool=handle(6);pool.heap_type=d3d12_query_heap::pipeline_statistics;pool.count=1; + vk.query_pool=[&](QueryHeapId){return &pool;}; + CommandList statistics; + EXPECT(statistics.set_predication({3,0,d3d12_predication::equal_zero})); + EXPECT(statistics.begin_query({1,d3d12_query::pipeline_statistics,0})); + EXPECT(statistics.copy_buffer({2,0,1,0,1})); + EXPECT(statistics.end_query({1,d3d12_query::pipeline_statistics,0})&&statistics.close()); + EXPECT(prepare(statistics,resolve,vk,result)==ReplayResult::unsupported); + // Readback visibility follows the actual producer, including mixed command lists. + destination.host_readable = false; + EXPECT(check({2,0,1,0,1})==ReplayResult::success && !result.wrote_readback && !result.readback_src_stages); + destination.host_readable = true; + EXPECT(check({2,0,1,0,1})==ReplayResult::success && result.wrote_readback); + EXPECT(result.readback_src_stages==VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT); + EXPECT(check({2,0,1,0,1},false)==ReplayResult::success && result.wrote_readback); + EXPECT(result.readback_src_stages==VK_PIPELINE_STAGE_2_COPY_BIT); + CommandList mixed; + EXPECT(mixed.set_predication({3,0,d3d12_predication::equal_zero})); + EXPECT(mixed.copy_buffer({2,0,1,0,1}) && mixed.set_predication({0,0,0})); + EXPECT(mixed.copy_buffer({2,1,1,1,1}) && mixed.close()); + EXPECT(prepare(mixed,resolve,vk,result)==ReplayResult::success && result.wrote_readback); + EXPECT(result.readback_src_stages==(VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT|VK_PIPELINE_STAGE_2_COPY_BIT)); + EXPECT(check({2,0,1,0,0})==ReplayResult::success && !result.wrote_readback && !result.readback_src_stages); + PredicatedBufferCopier missing(+[](VkDevice,const char*)->PFN_vkVoidFunction{return nullptr;},VK_NULL_HANDLE,{}); + std::vector jobs; + EXPECT(!missing.batch()->prepare(source.buffer,destination.buffer,0,0,1,jobs)); + std::puts("predicated copy preparation: capability, routing, 64-bit offsets, bounds, overflow, overlap, zero size, failure and statistics-query controls passed"); +} diff --git a/runtime/test/replay_cpu_bench.cpp b/runtime/test/replay_cpu_bench.cpp index dfa217d0f..de60b60f8 100644 --- a/runtime/test/replay_cpu_bench.cpp +++ b/runtime/test/replay_cpu_bench.cpp @@ -159,6 +159,11 @@ struct Scene { vk.update_buffer = nop(); vk.begin_conditional_rendering = nop(); vk.end_conditional_rendering = nop(); + vk.prepare_predicate = [](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { + out = {source, offset, fake_handle(0x5000), 0, VK_NULL_HANDLE}; + return true; + }; + vk.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) {}; vk.reset_query_pool = nop(); vk.begin_query = nop(); vk.end_query = nop(); diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 384b97d20..ddbc0ae70 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -78,7 +78,7 @@ def translate_tests(work, names): cmd.append(f"-mattr={mattr}") cmd.append("-show-encoding") # Feed the text on stdin: an LLVM_MC command that runs in WSL cannot open a Windows path argument. - r = subprocess.run(cmd, input=raw, capture_output=True, text=True) + r = mc_command.run(cmd, input=raw, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: sys.exit(f"{n}.asm did not assemble:\n{r.stderr}") # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first. diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index c1901dc90..ab3d74b0b 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -84,7 +84,17 @@ WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wr # otherwise pick a narrower size and return different words (#774). WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const") -CS_DUMPS = [("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), +CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), + ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), + ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), + ("cs_dpp8", [7, 6, 5, 4, 3, 2, 1, 0]), + ("cs_dpp_ops", [100, 10, 11, 12, 13, 14, 15, 16]), + ("cs_dpp_bound", [10, 10, 11, 12, 13, 14, 15, 16]), + ("cs_dpp_bank", [0xffffffff, 0xfffffffe, 0xfffffffd, 0xfffffffc, 7, 7, 7, 7]), + ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777])] +WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) +WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) +CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), # SHADER-52: wave32 lane select is & 31; lane 40 wraps to 8 ("cs_w32_lane_wrap", [25, 16, 777, 777]), # v_movrelsd_2_b32: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]] @@ -143,12 +153,14 @@ CVT_F32_SAT_CASES = ( (0x4F800000, 0xFFFFFFFF, 0x7FFFFFFF), (0xCEFFFFFF, 0, 0x80000080), (0xCF000000, 0, 0x80000000), (0xCF000001, 0, 0x80000000), (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), (0xFF800000, 0, 0x80000000), (0x7F800001, 0, 0), (0xFFC00000, 0, 0)) -# Cross-half wave64 tests (x = cross-half): exact results need 64 lanes, or an emulation of them on narrower subgroups. +# Wave64-only dump tests (mostly the x = cross-half checks): exact results need 64 lanes, or an emulation of them +# on narrower subgroups. cs_dpp_w64 is not cross-half, but its lane id needs both halves. W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1" # LEONIDA_BARY_FALLBACK=1 (set for build.py too): a pixel shader that reads raw barycentrics was translated with # --bary-fallback and is drawn through its pass-through geometry shader, .bary_gs.spv. BARY_FALLBACK = os.environ.get("LEONIDA_BARY_FALLBACK") == "1" -W64X_DUMPS = [("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), +W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), + ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), ("cs_w64x_writelane", [4660, 77, 99, 2748, 0, 0, 4660, 99]), ("cs_w64x_readfirstlane", [140, 140, 163, 132, 100, 105, 133, 48]), ("cs_w64x_bpermute", [36, 316, 253, 218, 435, 225, 0, 442]), @@ -193,7 +205,14 @@ PIXEL_BITS = {"ps_legacy_mul": (0, 0, 0, 0x40c00000), "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200), "ps_sff_imm": (2, 1, 20, 16), "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000), - "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000)} + "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), + # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) + "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000), + "ps_cvt_off": (0xbf000000, 0x3ee00000, 0xbe800000, 0x3f800000), + "ps_fmac_f16_mods": (0xaaaa3c00, 0xaaaa3e00, 0xaaaa0000, 0xaaaa4000), + "ps_vop3_const_mods": (0xc0000000, 0xbf800000, 0x3f800000, 0xaaaabc00), + "ps_interp_f32_mods": (0x3f800000, 0x00000000, 0x3f400000, 0x3f800000), + "ps_interp_mov_mods": (0x3f800000, 0x3fc00000, 0x40000000, 0x3f400000)} # Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as # tests/semantic/test_value_semantics.py does for the interpreter. PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x11223344,0x1004=0x55667788"}, @@ -212,7 +231,8 @@ CLIP_TESTS = ("vs_clip", "vs_clip_param4", "vs_clip_undeclared") PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", "ps_texoff_implicit", "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high")) # Pixel fixtures drawn with another vertex shader than vs_ids. -PIXEL_VERTEX = {"ps_interp_f16_high": "vs_f16_pack"} +PIXEL_VERTEX = {"ps_interp_f16_high": "vs_f16_pack", + "ps_interp_f32_mods": "vs_interp_consts", "ps_interp_mov_mods": "vs_interp_consts"} TEXOFF_ARGS = ("2", "92", "0", "0", "0") # ps_texoff: T# pointer in s2, then the shader's literal S# TEXTURE_MIP_TEST = "ps_texture_mip0" GATHER_LOD_TEST = "ps_gather_sampler_lod" @@ -252,12 +272,13 @@ def gpu_test_timeout(): text = (os.environ.get("LEONIDA_GPU_TEST_TIMEOUT") or "").strip() if not text: return DEFAULT_GPU_TEST_TIMEOUT + error = f"LEONIDA_GPU_TEST_TIMEOUT must be a finite number of seconds (0 = no limit), not {text!r}" try: limit = float(text) except ValueError: - sys.exit(f"LEONIDA_GPU_TEST_TIMEOUT must be a number of seconds (0 = no limit), not {text!r}") - if math.isnan(limit): - sys.exit("LEONIDA_GPU_TEST_TIMEOUT must be a number of seconds (0 = no limit), not nan") + sys.exit(error) + if not math.isfinite(limit): + sys.exit(error) return None if limit <= 0 else limit @@ -273,11 +294,12 @@ def run(*cmd, env=None): except subprocess.TimeoutExpired: return 1, timed_out(cmd[0], limit) except OSError as e: - if not isinstance(e, FileNotFoundError): - return 1, start_failure(cmd[0], e) - tools = os.path.abspath(os.path.dirname(cmd[0])) - missing = [t + EXE for t in TEST_PROGRAMS if not os.path.isfile(os.path.join(tools, t + EXE))] - sys.exit(not_found_message(tools, missing)) + if isinstance(e, FileNotFoundError): + tools = os.path.abspath(os.path.dirname(cmd[0])) + missing = [t + EXE for t in TEST_PROGRAMS if not os.path.isfile(os.path.join(tools, t + EXE))] + if missing: + sys.exit(not_found_message(tools, missing)) + return 1, start_failure(cmd[0], e) return r.returncode, r.stdout + r.stderr @@ -418,6 +440,22 @@ def wave32_lane_skip(out): return narrow_subgroup_skip(out) or unpinned_subgroup_skip(out) +def bitmask_perm_narrow_skip(out, px): + """A Skip when ps_bitmask_perm ran narrower than 32 lanes on a device whose subgroup range permits it (#618). + Requires every lane 0..width-1 of a power-of-two width in [min, 32), so a broken v_mbcnt still fails.""" + m = re.search(r"subgroup (\d+)\.\.(\d+)", out) + if not m or len(px) != 64 * 64: + return None + lo, hi = int(m.group(1)), int(m.group(2)) + if lo >= 32: + return None + lanes = {p[0] for p in px} + width = max(lanes) + 1 + if lo <= width < 32 and width & (width - 1) == 0 and lanes == set(range(width)): + return Skip(f"SKIP (fragment subgroup ran at {width} lanes on {lo}..{hi} device; needs 32)") + return None + + def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None, needs_32_lanes=False, env=None): """Return an empty string for a pass, None for unsupported wave64, a Skip for a wave32 lane-mask test on a device @@ -431,12 +469,19 @@ def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expe args.append("--require-wave64") if needs_32_lanes: env = {**WAVE32_LANE_ENV, **(env or {})} + # Run at the wave size the translator recorded, as run_gpu_tests.py does: a wave32 test left to the device's + # default runs 64-wide on AMD (subgroups 32..64), and cs_barrier_loop's four waves of 32 became two. + sg = None if "VKC_SUBGROUP_SIZE" in (env or {}) else subgroup_size(spirv, name) + if sg: + env = {**(env or {}), "VKC_SUBGROUP_SIZE": str(sg)} extra = {"env": dict(os.environ, **env)} if env else {} code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, groups, mode, *args, **extra) if require_wave64 and code == 77: # vk_compute_test: the device cannot run a 64-wide compute subgroup return None if needs_32_lanes and (skip := wave32_lane_skip(out)): return skip + if sg and (skip := unpinned_subgroup_skip(out)): + return skip if code != 0: return failure(code, out, 2) if require_wave64 and "compute subgroup size: 64" not in out.splitlines(): @@ -714,8 +759,14 @@ def interp_f16_high_problem(px): w = 64 half = lambda b: struct.unpack(" out[0..7] = 1 0 3 2 5 4 7 6 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v1, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp8.asm b/runtime/test/shaders/cs_dpp8.asm new file mode 100644 index 000000000..f4979be51 --- /dev/null +++ b/runtime/test/shaders/cs_dpp8.asm @@ -0,0 +1,8 @@ +; DPP8 reverse within 8-lane groups: dpp8:[7,6,5,4,3,2,1,0], fi:1. Lanes 0-7 store +; [7,6,5,4,3,2,1,0] to out[0..7]. +; Run: vk_compute_test cs_dpp8.spv 1 dump -> out[0..7] = 7 6 5 4 3 2 1 0 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32_dpp v1, v0 dpp8:[7,6,5,4,3,2,1,0] fi:1 +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v1, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp_bank.asm b/runtime/test/shaders/cs_dpp_bank.asm new file mode 100644 index 000000000..569185099 --- /dev/null +++ b/runtime/test/shaders/cs_dpp_bank.asm @@ -0,0 +1,9 @@ +; DPP bank_mask on a VOP1 op: bank 0 is enabled, so lanes 0-3 compute ~lane; lanes 4-7 are not written and +; keep 7. Lanes 0-7 store [0xffffffff,0xfffffffe,0xfffffffd,0xfffffffc,7,7,7,7] to out[0..7]. +; Run: vk_compute_test cs_dpp_bank.spv 1 dump -> out[0..7] = 4294967295 4294967294 4294967293 4294967292 7 7 7 7 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32 v10, 7 +v_not_b32_dpp v10, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0x1 +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v10, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp_bound.asm b/runtime/test/shaders/cs_dpp_bound.asm new file mode 100644 index 000000000..9ac5ba86f --- /dev/null +++ b/runtime/test/shaders/cs_dpp_bound.asm @@ -0,0 +1,10 @@ +; DPP on a VOP2 op with an invalid source and bound_ctrl:1: lane 0 uses 0 as src0, so it writes op(0, 10); +; the other lanes use the lane below them. Lanes 0-7 store [10,10,11,12,13,14,15,16] to out[0..7]. +; Run: vk_compute_test cs_dpp_bound.spv 1 dump -> out[0..7] = 10 10 11 12 13 14 15 16 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32 v1, 10 +v_mov_b32 v10, 100 +v_add_nc_u32_dpp v10, v0, v1 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1 +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v10, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp_fi.asm b/runtime/test/shaders/cs_dpp_fi.asm new file mode 100644 index 000000000..dbfd202c6 --- /dev/null +++ b/runtime/test/shaders/cs_dpp_fi.asm @@ -0,0 +1,11 @@ +; DPP16 fi:1 with EXEC 0x77777777 (lane 3 of each quad off). lane 2 reads the inactive lane 3; lane 3 is +; itself inactive and keeps 0x7777. Lanes 0-7 store [1,2,3,0x7777,5,6,7,0x7777] to out[0..7]. +; Run: vk_compute_test cs_dpp_fi.spv 1 dump -> out[0..7] = 1 2 3 30583 5 6 7 30583 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32 v10, 0x7777 +s_mov_b32 exec_lo, 0x77777777 +v_mov_b32_dpp v10, v0 quad_perm:[1,2,3,0] row_mask:0xf bank_mask:0xf fi:1 +s_mov_b32 exec_lo, -1 +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v10, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp_mask.asm b/runtime/test/shaders/cs_dpp_mask.asm new file mode 100644 index 000000000..3eb6b8ca6 --- /dev/null +++ b/runtime/test/shaders/cs_dpp_mask.asm @@ -0,0 +1,9 @@ +; DPP row_mask/bank_mask: quad_perm:[1,0,3,2] with row 0 and bank 0 enabled only. Lanes 0-3 get the +; permutation; lanes 4-7 keep the output buffer's initial 0xEE. Lanes 0-3 store to out[0..3] only. +; Run: vk_compute_test cs_dpp_mask.spv 1 dump -> out[0..7] = 1 0 3 2 4008636142 4008636142 4008636142 4008636142 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0x1 bank_mask:0x1 +v_lshlrev_b32 v2, 2, v0 +v_cmpx_lt_u32 v0, 4 +buffer_store_dword v1, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp_ops.asm b/runtime/test/shaders/cs_dpp_ops.asm new file mode 100644 index 000000000..a9214f53f --- /dev/null +++ b/runtime/test/shaders/cs_dpp_ops.asm @@ -0,0 +1,11 @@ +; DPP on a VOP2 op with an invalid source and no bound_ctrl: lane 0 reads outside its row, so it must not be +; written and keeps 100. The other lanes compute op(source lane, 10). Lanes 0-7 store +; [100,10,11,12,13,14,15,16] to out[0..7]. +; Run: vk_compute_test cs_dpp_ops.spv 1 dump -> out[0..7] = 100 10 11 12 13 14 15 16 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32 v1, 10 +v_mov_b32 v10, 100 +v_add_nc_u32_dpp v10, v0, v1 row_shr:1 row_mask:0xf bank_mask:0xf +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v10, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp_row.asm b/runtime/test/shaders/cs_dpp_row.asm new file mode 100644 index 000000000..3109485a8 --- /dev/null +++ b/runtime/test/shaders/cs_dpp_row.asm @@ -0,0 +1,8 @@ +; DPP row_shr:1 with bound_ctrl:1: each lane reads the lane below it in its 16-lane row; lane 0 (and lane 16, +; 32, 48) has an invalid source and reads zero. Lanes 0-7 store [0,0,1,2,3,4,5,6] to out[0..7]. +; Run: vk_compute_test cs_dpp_row.spv 1 dump -> out[0..7] = 0 0 1 2 3 4 5 6 +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1 +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v1, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_dpp_w64.asm b/runtime/test/shaders/cs_dpp_w64.asm new file mode 100644 index 000000000..29394e2a4 --- /dev/null +++ b/runtime/test/shaders/cs_dpp_w64.asm @@ -0,0 +1,9 @@ +; Wave64 DPP: the lane id needs both halves, so this is a wave64 shader. Without emulation it needs a 64-wide +; subgroup; LEONIDA_W64_EMULATE=1 sends the DPP source/EXEC exchange through %x_buf and runs on any subgroup. +; Run: vk_compute_test cs_dpp_w64.spv 1 dump -> out[0..7] = 1 0 3 2 5 4 7 6. +v_mbcnt_lo_u32_b32 v0, -1, 0 +v_mbcnt_hi_u32_b32 v0, -1, v0 +v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_lshlrev_b32 v2, 2, v0 +buffer_store_dword v1, v2, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_imgload.asm b/runtime/test/shaders/cs_imgload.asm index aad66f725..d8c1fca0b 100644 --- a/runtime/test/shaders/cs_imgload.asm +++ b/runtime/test/shaders/cs_imgload.asm @@ -1,5 +1,8 @@ -; Typed image_load: like cs_imgstore, but each thread reads back its uint texel (image_load through the uint view) and -; stores it into the sint image. Run: vk_store_test cs_imgload.spv load -> sint = 100 + 8y + x everywhere. +; Typed image_load (SHADER-151): vk_store_test fills the r32 uint image with 100 + 8y + x and the r32 sint image with +; -2 (8y + x) before the dispatch. Each thread loads both of its texels with image_load, which the translator fetches +; through the uint and sint aliases of the sampled array (no storage image read, so no read-without-format), and +; stores their sum into the sint image; the rgba8 image is stored as in cs_imgstore. Nothing is read back after a +; write in the same dispatch. Run: vk_store_test cs_imgload.spv load -> sint = 100 - (8y + x), uint unchanged. v_and_b32_e32 v1, 7, v0 v_lshrrev_b32_e32 v2, 3, v0 v_cvt_f32_u32_e32 v3, v1 @@ -17,11 +20,6 @@ s_mov_b32 s13, 0x11 s_mov_b32 s14, 0x11 s_mov_b32 s15, 0x11 image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -v_lshl_add_u32 v7, v2, 3, v1 -v_add_nc_u32_e32 v7, 100, v7 -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 0 -v_mov_b32_e32 v10, 0 s_mov_b32 s16, 0x2000 s_mov_b32 s17, 0x1400000 s_mov_b32 s18, 0x22 @@ -30,12 +28,7 @@ s_mov_b32 s20, 0x22 s_mov_b32 s21, 0x22 s_mov_b32 s22, 0x22 s_mov_b32 s23, 0x22 -image_store v[7:10], v[1:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -image_load v[11:14], v[1:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_waitcnt vmcnt(0) -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 +image_load v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm s_mov_b32 s24, 0x3000 s_mov_b32 s25, 0x1500000 s_mov_b32 s26, 0x33 @@ -44,5 +37,11 @@ s_mov_b32 s28, 0x33 s_mov_b32 s29, 0x33 s_mov_b32 s30, 0x33 s_mov_b32 s31, 0x33 +image_load v11, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_waitcnt vmcnt(0) +v_add_nc_u32_e32 v11, v7, v11 +v_mov_b32_e32 v12, 0 +v_mov_b32_e32 v13, 0 +v_mov_b32_e32 v14, 0 image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm s_endpgm diff --git a/runtime/test/shaders/cs_imgload_d16.asm b/runtime/test/shaders/cs_imgload_d16.asm index f1b4c98da..a233ad444 100644 --- a/runtime/test/shaders/cs_imgload_d16.asm +++ b/runtime/test/shaders/cs_imgload_d16.asm @@ -1,5 +1,7 @@ -; d16 typed image_load: cs_imgload with the read-back as a d16 load (low 16 bits of the uint texel, masked). -; Run: vk_store_test cs_imgload_d16.spv load -> sint = 100 + 8y + x everywhere. +; d16 typed image_load: cs_imgload with both read-backs as d16 loads. vk_store_test fills the r32 uint image with +; 100 + 8y + x and the r32 sint image with -2 (8y + x) before the dispatch; each d16 load returns the low 16 bits of +; its texel (masked for the uint one, sign-extended from bit 15 for the sint one), and their sum is stored into the +; sint image. Run: vk_store_test cs_imgload_d16.spv load -> sint = 100 - (8y + x), uint unchanged. v_and_b32_e32 v1, 7, v0 v_lshrrev_b32_e32 v2, 3, v0 v_cvt_f32_u32_e32 v3, v1 @@ -17,11 +19,6 @@ s_mov_b32 s13, 0x11 s_mov_b32 s14, 0x11 s_mov_b32 s15, 0x11 image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -v_lshl_add_u32 v7, v2, 3, v1 -v_add_nc_u32_e32 v7, 100, v7 -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 0 -v_mov_b32_e32 v10, 0 s_mov_b32 s16, 0x2000 s_mov_b32 s17, 0x1400000 s_mov_b32 s18, 0x22 @@ -30,13 +27,7 @@ s_mov_b32 s20, 0x22 s_mov_b32 s21, 0x22 s_mov_b32 s22, 0x22 s_mov_b32 s23, 0x22 -image_store v[7:10], v[1:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -image_load v11, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16 -s_waitcnt vmcnt(0) -v_and_b32_e32 v11, 0xffff, v11 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 +image_load v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16 s_mov_b32 s24, 0x3000 s_mov_b32 s25, 0x1500000 s_mov_b32 s26, 0x33 @@ -45,5 +36,13 @@ s_mov_b32 s28, 0x33 s_mov_b32 s29, 0x33 s_mov_b32 s30, 0x33 s_mov_b32 s31, 0x33 +image_load v11, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16 +s_waitcnt vmcnt(0) +v_and_b32_e32 v7, 0xffff, v7 +v_bfe_i32 v11, v11, 0, 16 +v_add_nc_u32_e32 v11, v7, v11 +v_mov_b32_e32 v12, 0 +v_mov_b32_e32 v13, 0 +v_mov_b32_e32 v14, 0 image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm s_endpgm diff --git a/runtime/test/shaders/ps_cmp_nlg.asm b/runtime/test/shaders/ps_cmp_nlg.asm new file mode 100644 index 000000000..70ea7c861 --- /dev/null +++ b/runtime/test/shaders/ps_cmp_nlg.asm @@ -0,0 +1,84 @@ +; v_cmp_nlg / v_cmpx_nlg (docs/design.md "Constant and ordered VOPC"): nlg ("not less or greater") is true when +; x == y or either source is NaN (unordered equal). Each case ORs its bit into a mask; channels are mask | 0x40000000. +; x, f32 cases: bit0 1.0 vs 1.0 (1), bit1 +0 vs -0 (1), bit2 quiet NaN vs 1.0 (1), bit3 1.0 vs 2.5 (0), +; bit4 signalling NaN 0x7f800001 vs 1.0 (1), bit5 +inf vs +inf (1), bit6 -inf vs +inf (0): mask 0x37 +; y, f16 cases (high halves 0xABCD / 0x1234 must be ignored): bit0 1.0h vs 1.0h (1), bit1 +0h vs -0h (1), +; bit2 NaN 0x7e00 vs 1.0h (1), bit3 1.0h vs 2.5h (0): mask 0x7 +; z, the e64 form with source modifiers: bit0 nlg(-|-1.0|, -1.0) (1), bit1 nlg(|x|, 2.5) with x = -1.0 (0): mask 0x1 +; w: v_cmpx_nlg_f32 and _f16 on equal, +-0 and NaN operands keep every lane, so the pixel is still written: 1.0 +; Expected mrt0 bits: 0x40000037, 0x40000007, 0x40000001, 0x3f800000 +v_mov_b32_e32 v10, 0 +v_mov_b32_e32 v0, 1.0 +v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 +v_cndmask_b32_e64 v1, 0, 1, vcc_lo +v_or_b32_e32 v10, v10, v1 +v_mov_b32_e32 v0, 0x80000000 +v_cmp_nlg_f32_e32 vcc_lo, 0, v0 +v_cndmask_b32_e64 v1, 0, 2, vcc_lo +v_or_b32_e32 v10, v10, v1 +v_mov_b32_e32 v0, 0x7fc00000 +v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 +v_cndmask_b32_e64 v1, 0, 4, vcc_lo +v_or_b32_e32 v10, v10, v1 +v_mov_b32_e32 v0, 0x40200000 +v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 +v_cndmask_b32_e64 v1, 0, 8, vcc_lo +v_or_b32_e32 v10, v10, v1 +v_mov_b32_e32 v0, 0x7f800001 +v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 +v_cndmask_b32_e64 v1, 0, 16, vcc_lo +v_or_b32_e32 v10, v10, v1 +v_mov_b32_e32 v0, 0x7f800000 +v_mov_b32_e32 v2, 0x7f800000 +v_cmp_nlg_f32_e32 vcc_lo, v2, v0 +v_cndmask_b32_e64 v1, 0, 32, vcc_lo +v_or_b32_e32 v10, v10, v1 +v_mov_b32_e32 v2, 0xff800000 +v_cmp_nlg_f32_e32 vcc_lo, v2, v0 +v_cndmask_b32_e64 v1, 0, 64, vcc_lo +v_or_b32_e32 v10, v10, v1 +v_or_b32_e32 v10, 0x40000000, v10 +v_mov_b32_e32 v11, 0 +v_mov_b32_e32 v0, 0xabcd3c00 +v_mov_b32_e32 v2, 0x12343c00 +v_cmp_nlg_f16_e32 vcc_lo, v0, v2 +v_cndmask_b32_e64 v1, 0, 1, vcc_lo +v_or_b32_e32 v11, v11, v1 +v_mov_b32_e32 v0, 0xabcd0000 +v_mov_b32_e32 v2, 0x12348000 +v_cmp_nlg_f16_e32 vcc_lo, v0, v2 +v_cndmask_b32_e64 v1, 0, 2, vcc_lo +v_or_b32_e32 v11, v11, v1 +v_mov_b32_e32 v0, 0xabcd7e00 +v_mov_b32_e32 v2, 0x12343c00 +v_cmp_nlg_f16_e32 vcc_lo, v0, v2 +v_cndmask_b32_e64 v1, 0, 4, vcc_lo +v_or_b32_e32 v11, v11, v1 +v_mov_b32_e32 v0, 0xabcd3c00 +v_mov_b32_e32 v2, 0x12344100 +v_cmp_nlg_f16_e32 vcc_lo, v0, v2 +v_cndmask_b32_e64 v1, 0, 8, vcc_lo +v_or_b32_e32 v11, v11, v1 +v_or_b32_e32 v11, 0x40000000, v11 +v_mov_b32_e32 v12, 0 +v_mov_b32_e32 v0, -1.0 +v_cmp_nlg_f32_e64 s1, -|v0|, v0 +v_cndmask_b32_e64 v1, 0, 1, s1 +v_or_b32_e32 v12, v12, v1 +v_mov_b32_e32 v2, 0x40200000 +v_cmp_nlg_f32_e64 s1, |v0|, v2 +v_cndmask_b32_e64 v1, 0, 2, s1 +v_or_b32_e32 v12, v12, v1 +v_or_b32_e32 v12, 0x40000000, v12 +v_mov_b32_e32 v0, 1.0 +v_cmpx_nlg_f32_e32 1.0, v0 +v_mov_b32_e32 v0, 0x80000000 +v_cmpx_nlg_f32_e32 0, v0 +v_mov_b32_e32 v0, 0x7fc00000 +v_cmpx_nlg_f32_e32 1.0, v0 +v_mov_b32_e32 v0, 0x7e00 +v_mov_b32_e32 v2, 0x3c00 +v_cmpx_nlg_f16_e32 v0, v2 +v_mov_b32_e32 v13, 1.0 +exp mrt0 v10, v11, v12, v13 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_cvt_off.asm b/runtime/test/shaders/ps_cvt_off.asm new file mode 100644 index 000000000..a68ecc9c2 --- /dev/null +++ b/runtime/test/shaders/ps_cvt_off.asm @@ -0,0 +1,17 @@ +; v_cvt_off_f32_i4 (docs/design.md "Constant and ordered VOPC, ..."): D = sext(S0[3:0]) / 16, the ISA's CVT_OFF table +; (0 .. 0.4375, then -0.5 .. -0.0625); bits 4-31 are ignored and the VOP3 output modifiers apply, omod before clamp. +; x: S0 = 0x12345678, low nibble 8: -0.5 +; y: S0 = 7: 0.4375 +; z: S0 = 0xF with mul:4: -0.0625 * 4 = -0.25 +; w: S0 = 7 with mul:4 clamp: 1.75 clamped to 1.0 (clamping first would give 1.75) +; Expected mrt0 bits: 0xbf000000, 0x3ee00000, 0xbe800000, 0x3f800000 +v_mov_b32_e32 v0, 0x12345678 +v_cvt_off_f32_i4_e32 v2, v0 +v_mov_b32_e32 v0, 7 +v_cvt_off_f32_i4_e32 v3, v0 +v_mov_b32_e32 v0, 15 +v_cvt_off_f32_i4_e64 v4, v0 mul:4 +v_mov_b32_e32 v0, 7 +v_cvt_off_f32_i4_e64 v5, v0 clamp mul:4 +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_fmac_f16_mods.asm b/runtime/test/shaders/ps_fmac_f16_mods.asm new file mode 100644 index 000000000..6623a3467 --- /dev/null +++ b/runtime/test/shaders/ps_fmac_f16_mods.asm @@ -0,0 +1,18 @@ +; VOP3 output modifiers on v_fmac_f16_e64 (docs/design.md "v_fmac_f16, v_interp_p2/mov_f32 output modifiers"): +; D.f16 = S0 * S1 + D, then mul:2 / mul:4 / div:2, then clamp to [0, 1], before narrowing to f16; the destination's +; high half (0xAAAA) is kept. +; x: 1.0 + 1.0 * 1.0 = 2.0, clamp: 1.0 (0x3c00) +; y: 0.5 + 0.5 * 0.5 = 0.75, mul:2: 1.5 (0x3e00) +; z: -1.0 + 0.5 * 0.5 = -0.75, clamp: 0.0 (0x0000) +; w: 2.0 + 1.0 * 2.0 = 4.0, div:2: 2.0 (0x4000) +; Expected mrt0 bits: 0xaaaa3c00, 0xaaaa3e00, 0xaaaa0000, 0xaaaa4000 +v_mov_b32_e32 v2, 0xaaaa3c00 +v_fmac_f16_e64 v2, 1.0, 1.0 clamp +v_mov_b32_e32 v3, 0xaaaa3800 +v_fmac_f16_e64 v3, 0.5, 0.5 mul:2 +v_mov_b32_e32 v4, 0xaaaabc00 +v_fmac_f16_e64 v4, 0.5, 0.5 clamp +v_mov_b32_e32 v5, 0xaaaa4000 +v_fmac_f16_e64 v5, 1.0, 2.0 div:2 +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_interp_f32_mods.asm b/runtime/test/shaders/ps_interp_f32_mods.asm new file mode 100644 index 000000000..ae09a6a24 --- /dev/null +++ b/runtime/test/shaders/ps_interp_f32_mods.asm @@ -0,0 +1,16 @@ +; VOP3 output modifiers on v_interp_p2_f32_e64 (docs/design.md "v_fmac_f16, v_interp_p2/mov_f32 output modifiers"), +; omod before clamp. Drawn with vs_interp_consts: attr0 = (1.5, -0.25, 0.375, 0.625) at every pixel. +; x: clamp(1.5) = 1.0; y: clamp(-0.25) = 0.0; z: 0.375 mul:2 = 0.75; w: 0.625 mul:2 = 1.25, clamp: 1.0 +; (clamping before the multiply would give 1.25) +; Run: vk_harness vs_interp_consts.spv ps_interp_f32_mods.spv out.raw +; Expected mrt0 bits: 0x3f800000, 0x00000000, 0x3f400000, 0x3f800000 +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e64 v2, v1, attr0.x clamp +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e64 v3, v1, attr0.y clamp +v_interp_p1_f32_e32 v4, v0, attr0.z +v_interp_p2_f32_e64 v4, v1, attr0.z mul:2 +v_interp_p1_f32_e32 v5, v0, attr0.w +v_interp_p2_f32_e64 v5, v1, attr0.w clamp mul:2 +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_interp_mov_mods.asm b/runtime/test/shaders/ps_interp_mov_mods.asm new file mode 100644 index 000000000..d9e1c98c2 --- /dev/null +++ b/runtime/test/shaders/ps_interp_mov_mods.asm @@ -0,0 +1,15 @@ +; VOP3 output modifiers on v_interp_p2_f32_e64 and v_interp_mov_f32_e64 (docs/design.md "v_fmac_f16, +; v_interp_p2/mov_f32 output modifiers"). Drawn with vs_interp_consts: attr2 = (0.25, 3.0, 0, 0) interpolated, +; attr1 = (1.5, -0.5, 0.25, 4.0) read only with v_interp_mov (so its location is Flat). +; x: interp 0.25 mul:4 = 1.0; y: interp 3.0 div:2 = 1.5; z: mov 4.0 div:2 = 2.0; +; w: mov 1.5 div:2 = 0.75, then clamp (clamping first would give 0.5) +; Run: vk_harness vs_interp_consts.spv ps_interp_mov_mods.spv out.raw +; Expected mrt0 bits: 0x3f800000, 0x3fc00000, 0x40000000, 0x3f400000 +v_interp_p1_f32_e32 v2, v0, attr2.x +v_interp_p2_f32_e64 v2, v1, attr2.x mul:4 +v_interp_p1_f32_e32 v3, v0, attr2.y +v_interp_p2_f32_e64 v3, v1, attr2.y div:2 +v_interp_mov_f32_e64 v4, p0, attr1.w div:2 +v_interp_mov_f32_e64 v5, p0, attr1.x clamp div:2 +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/ps_vop3_const_mods.asm b/runtime/test/shaders/ps_vop3_const_mods.asm new file mode 100644 index 000000000..d0cac1546 --- /dev/null +++ b/runtime/test/shaders/ps_vop3_const_mods.asm @@ -0,0 +1,14 @@ +; VOP3 FP source modifiers on constants (docs/design.md "VOP3 FP modifiers on constants"): on an inline constant or a +; literal, abs clears the sign bit first and neg flips it second; neg on a literal is not an integer negation. +; x: v_add_f32_e64 0 + -|-2.0| = -2.0 (folding - into the constant first gave +2.0) +; y: v_add_f32_e64 0 + neg(0x3f800000) = -1.0 (two's-complement negation gave 0xc0800000, -4.0) +; z: v_add_f32_e64 0 + |0xbf800000| = 1.0 (dropping abs gave -1.0) +; w: v_add_f16_e64 0 + -|0x3c00| = -1.0h in the low half, the destination's high half 0xAAAA kept +; Expected mrt0 bits: 0xc0000000, 0xbf800000, 0x3f800000, 0xaaaabc00 +v_add_f32_e64 v2, 0, -|-2.0| +v_add_f32_e64 v3, 0, neg(0x3f800000) +v_add_f32_e64 v4, 0, |0xbf800000| +v_mov_b32_e32 v5, 0xaaaa1234 +v_add_f16_e64 v5, 0, -|0x3c00| +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/vs_interp_consts.asm b/runtime/test/shaders/vs_interp_consts.asm new file mode 100644 index 000000000..29217e82d --- /dev/null +++ b/runtime/test/shaders/vs_interp_consts.asm @@ -0,0 +1,26 @@ +; Vertex shader for ps_interp_f32_mods and ps_interp_mov_mods: the vs_ids full-screen triangle, with the same constant +; in each param channel at all three vertices, so interpolation gives that constant at every pixel: +; param0 = (1.5, -0.25, 0.375, 0.625), param1 = (1.5, -0.5, 0.25, 4.0), param2 = (0.25, 3.0, 0, 0). +v_lshlrev_b32_e32 v1, 1, v0 +v_and_b32_e32 v1, 2, v1 +v_and_b32_e32 v2, 2, v0 +v_cvt_f32_u32_e32 v1, v1 +v_cvt_f32_u32_e32 v2, v2 +v_fma_f32 v3, v1, 2.0, -1.0 +v_fma_f32 v4, v2, 2.0, -1.0 +v_mov_b32_e32 v5, 0 +v_mov_b32_e32 v6, 1.0 +exp pos0 v3, v4, v5, v6 done +v_mov_b32_e32 v7, 0x3fc00000 +v_mov_b32_e32 v8, 0xbe800000 +v_mov_b32_e32 v9, 0x3ec00000 +v_mov_b32_e32 v10, 0x3f200000 +exp param0 v7, v8, v9, v10 +v_mov_b32_e32 v8, -0.5 +v_mov_b32_e32 v9, 0.25 +v_mov_b32_e32 v10, 4.0 +exp param1 v7, v8, v9, v10 +v_mov_b32_e32 v7, 0.25 +v_mov_b32_e32 v8, 0x40400000 +exp param2 v7, v8, v5, v5 +s_endpgm diff --git a/runtime/test/typeless_rtv_test.cpp b/runtime/test/typeless_rtv_test.cpp index 7959a8af1..09f704eef 100644 --- a/runtime/test/typeless_rtv_test.cpp +++ b/runtime/test/typeless_rtv_test.cpp @@ -107,6 +107,10 @@ int main() { auto conditional = vk; conditional.begin_conditional_rendering = +[](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT*) {}; conditional.end_conditional_rendering = end; + conditional.prepare_predicate = [](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { + out = {source, offset, reinterpret_cast(std::uintptr_t{3}), 0, VK_NULL_HANDLE}; return true; + }; + conditional.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) {}; ResourceBinding predicate{}; predicate.buffer = reinterpret_cast(std::uintptr_t{2}); predicate.size = 8; @@ -124,6 +128,50 @@ int main() { EXPECT(requested_format == expected); ++checks; } + // Eight bytes, not just the low word, must fit; missing/rejected preparation cannot emit any clears. + { + CommandList list; + EXPECT(list.set_predication({2, 0, d3d12_predication::equal_zero})); + EXPECT(list.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_uint}, color) && list.close()); + auto short_buffer = predicate; short_buffer.size = 4; + PreparedList prepared; + auto resolve = [&](ResourceId id) { return id == 2 ? &short_buffer : &binding; }; + EXPECT(prepare(list, resolve, conditional, prepared) == ReplayResult::invalid_predication); + short_buffer.size = 8; + EXPECT(prepare(list, resolve, conditional, prepared) == ReplayResult::success); + auto unavailable = conditional; unavailable.prepare_predicate = {}; + EXPECT(prepare(list, resolve, unavailable, prepared) == ReplayResult::unsupported); + unavailable = conditional; + unavailable.prepare_predicate = [](VkBuffer, VkDeviceSize, PredicateCapture&) { return false; }; + EXPECT(prepare(list, resolve, unavailable, prepared) == ReplayResult::unsupported); + checks += 4; + } + { + QueryPool statistics{}; + statistics.pool = reinterpret_cast(std::uintptr_t{4}); + statistics.heap_type = d3d12_query_heap::pipeline_statistics; statistics.count = 1; + auto queries = conditional; + queries.reset_query_pool = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) {}; + queries.begin_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, VkQueryControlFlags) {}; + queries.end_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t) {}; + queries.write_timestamp = +[](VkCommandBuffer, VkPipelineStageFlagBits, VkQueryPool, std::uint32_t) {}; + queries.copy_query_pool_results = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, + VkBuffer, VkDeviceSize, VkDeviceSize, VkQueryResultFlags) {}; + queries.fill_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {}; + queries.query_pool = [&](QueryHeapId) { return &statistics; }; + for (bool inside : {false, true}) { + CommandList list; + if (!inside) EXPECT(list.set_predication({2, 0, d3d12_predication::equal_zero})); + EXPECT(list.begin_query({3, d3d12_query::pipeline_statistics, 0})); + if (inside) EXPECT(list.set_predication({2, 0, d3d12_predication::equal_zero})); + EXPECT(list.end_query({3, d3d12_query::pipeline_statistics, 0}) && list.close()); + PreparedList prepared; + const auto resolve = [&](ResourceId id) { return id == 2 ? &predicate : &binding; }; + EXPECT(prepare(list, resolve, queries, prepared) == + (inside ? ReplayResult::unsupported : ReplayResult::success)); + ++checks; + } + } auto layered = binding; layered.mip_levels = 3; layered.array_layers = 4; for (const auto& [format, expected] : formats) { diff --git a/runtime/test/vk_binary_occlusion_test.cpp b/runtime/test/vk_binary_occlusion_test.cpp index 221b4e73b..39b76ca5a 100644 --- a/runtime/test/vk_binary_occlusion_test.cpp +++ b/runtime/test/vk_binary_occlusion_test.cpp @@ -1,3 +1,4 @@ +#include "predicated_copy_controls.h" // Seed an occlusion heap with independent Vulkan draws, then resolve it through the D3D12 replay queue. // This exercises the real GPU query copy and normalization without needing D3D12 draw commands. #include "vk_test_device.h" @@ -154,6 +155,11 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); context.set_occlusion_resolve_memory(memory); + VkPhysicalDeviceProperties properties{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); + context.configure_predication(d.device_proc, memory, properties.limits.maxStorageBufferRange, d.family); + PredicatedCopyControl copy_control; + EXPECT(copy_control.create(d, context, properties.limits)); VulkanQueue queue(context, d.queue, d.family); EXPECT(queue.ok()); constexpr QueryHeapId query_id = 1, stats_id = 2; @@ -191,7 +197,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { void* predicate_mapping = nullptr; ResourceBinding predicate{}; predicate.size = 8; - predicate.buffer = d.buffer(predicate.size, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, + predicate.buffer = d.buffer(predicate.size, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &predicate_mapping); EXPECT(predicate.buffer && predicate_mapping); std::memset(predicate_mapping, 0, predicate.size); @@ -203,6 +209,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { range_offset})); EXPECT(binary.resolve_queries({query_id, d3d12_query::occlusion, ordinary_index, 1, destination_id, ordinary_offset})); + EXPECT(copy_control.record(binary)); EXPECT(binary.close()); CommandList rerun; EXPECT(rerun.resolve_queries({query_id, d3d12_query::binary_occlusion, first_visible + 1, 3, destination_id, @@ -253,6 +260,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { } std::printf("binary occlusion: %u visible, 3 zero, 3 repeated; ordinary result %llu; offsets and sentinels exact\n", visible_count, static_cast(raw)); + EXPECT(copy_control.check()); return 0; } diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index e81773941..e245cf828 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #define CHECK(x) \ @@ -73,6 +74,16 @@ std::vector read_spv(const char* path) { return words; } +// Expected RGBA values in this test are finite. Report the worst channel error per pixel. +float pixel_error(const float* pixel, const float* want) { + float error = 0; + for (int c = 0; c < 4; ++c) { + if (!std::isfinite(pixel[c])) return std::numeric_limits::infinity(); + error = std::max(error, std::fabs(pixel[c] - want[c])); + } + return error; +} + DescriptorKey numbered(std::uint32_t n) { return {n, 0x9e3779b9u * n, n ^ 0x55555555u, n >> 3, 7, n * n, 0x80000000u, ~n}; } @@ -96,6 +107,13 @@ int main(int argc, char** argv) { std::fprintf(stderr, "usage: vk_bindless_test \n"); return 2; } + // A bad readback in a single channel must still fail when all three others match. + const float black[4]{}; + for (int c = 0; c < 4; ++c) { + float pixel[4]{}; + pixel[c] = std::numeric_limits::quiet_NaN(); + EXPECT(std::isinf(pixel_error(pixel, black))); + } constexpr std::uint32_t W = 64, H = 64, TW = 8; constexpr std::uint32_t table_va = 256; // console VA of the descriptor table: T# at +0, S# at +32 const DescriptorKey tsharp{0x11111111, 0x22222222, 0x33333333, 0x44444444, @@ -499,8 +517,7 @@ int main(int argc, char** argv) { const float gradient_texel[4] = {float(x * TW / W * 32) / 255.0f, float(y * TW / H * 32) / 255.0f, 128.0f / 255.0f, 1.0f}; const float* want = colour ? colour : gradient_texel; const float* pixel = got + (std::size_t(y) * W + x) * 4; - float error = 0; - for (int c = 0; c < 4; ++c) error = std::max(error, std::fabs(pixel[c] - want[c])); + const float error = pixel_error(pixel, want); worst = std::max(worst, error); if (error <= 1e-6f) continue; if (mismatches++ < 6) diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp index 55fea976e..9c3131268 100644 --- a/runtime/test/vk_command_replay_test.cpp +++ b/runtime/test/vk_command_replay_test.cpp @@ -546,7 +546,7 @@ int part_e(vktest::Device& d) { constexpr std::uint32_t size = 4, layers = 5, texels = size * size; const VkImage color = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, layers, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); void* predicate_words = nullptr; - const VkBuffer predicate = d.buffer(32, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, &predicate_words); + const VkBuffer predicate = d.buffer(32, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &predicate_words); void* mapped = nullptr; const VkBuffer readback = d.buffer(texels * layers * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); EXPECT(color && predicate && readback); @@ -587,6 +587,17 @@ int part_e(vktest::Device& d) { d.fn("vkCmdBeginConditionalRenderingEXT"); vk.end_conditional_rendering = d.fn("vkCmdEndConditionalRenderingEXT"); EXPECT(vk.begin_conditional_rendering && vk.end_conditional_rendering); + VkPhysicalDeviceMemoryProperties memory{}; + d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); + VkPhysicalDeviceProperties properties{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); + PredicateReducer reducer(d.device_proc, d.device, memory, properties.limits.maxStorageBufferRange); + auto conditions = reducer.batch(32); + EXPECT(conditions); + vk.prepare_predicate = [&](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { + return conditions->prepare(source, offset, out); + }; + vk.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { reducer.capture(cb, p); }; // Lists that are rejected, and the count of copies Vulkan cannot predicate. Nothing is written by prepare(). const auto prepared_with = [&](auto&& record, const ReplayFunctions& functions, PreparedList& out) { @@ -612,8 +623,17 @@ int part_e(vktest::Device& d) { l.set_predication({0, 0, 0}); l.copy_buffer({predicate_id, 16, predicate_id, 0, 8}); // after it: counted 0 }; - EXPECT(prepared_with(copies, vk, scratch) == ReplayResult::success); - EXPECT(scratch.unpredicated_copies == 1); + EXPECT(prepared_with(copies, vk, scratch) == ReplayResult::unsupported); + ReplayFunctions copy_functions = vk; + // Preparation-only routing test; no fake descriptor set is ever submitted. + copy_functions.prepare_predicated_copy = [](VkBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, VkDeviceSize bytes, + std::vector& out) { + out.push_back({VK_NULL_HANDLE, 0, 0, static_cast(bytes)}); + return true; + }; + copy_functions.emit_predicated_copy = [](VkCommandBuffer, const std::vector&) {}; + EXPECT(prepared_with(copies, copy_functions, scratch) == ReplayResult::success); + EXPECT(scratch.unpredicated_copies == 0); const Rect corner{0, 0, 2, 2}; CommandList list; diff --git a/runtime/test/vk_image_fuzz.cpp b/runtime/test/vk_image_fuzz.cpp index 96e1fa45e..5e629163a 100644 --- a/runtime/test/vk_image_fuzz.cpp +++ b/runtime/test/vk_image_fuzz.cpp @@ -203,11 +203,11 @@ int main(int argc, char** argv) { VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &props12}; vkGetPhysicalDeviceProperties2(pd, &props); std::printf("device: %s%s\n", props.properties.deviceName, validation ? " (validation on)" : ""); - const bool integer = spec.format == VK_FORMAT_R8G8B8A8_UINT || spec.format == VK_FORMAT_R8G8B8A8_SINT; + // Every format, UINT/SINT included, is a sampled image: a translated image_load fetches it from the sampled + // array, through a uint/sint alias for integer formats (SHADER-151), as the runtime binds a read-only texture. VkFormatProperties format_props{}; vkGetPhysicalDeviceFormatProperties(pd, spec.format, &format_props); - const VkFormatFeatureFlags required = integer ? VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT : VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT; - if (!(format_props.optimalTilingFeatures & required)) { + if (!(format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { std::printf("unsupported: %s lacks the required image feature\n", spec.format_name.c_str()); return unsupported; } @@ -234,15 +234,10 @@ int main(int argc, char** argv) { need(have.features.shaderInt64, "shaderInt64"); need(have.features.shaderSampledImageArrayDynamicIndexing, "shaderSampledImageArrayDynamicIndexing"); need(have.features.fragmentStoresAndAtomics, "fragmentStoresAndAtomics"); - need(have.features.shaderStorageImageReadWithoutFormat, "shaderStorageImageReadWithoutFormat"); - need(have.features.shaderStorageImageWriteWithoutFormat, "shaderStorageImageWriteWithoutFormat"); + // No without-format storage-image feature: a translated image_load fetches every format from the sampled + // arrays (SHADER-151), so Intel Xe-LP, which lacks shaderStorageImageReadWithoutFormat, runs these cases too. if (!missing.empty()) { std::printf("unsupported: the device lacks %s\n", missing.c_str()); - if (missing.find("shaderStorageImageReadWithoutFormat") != std::string::npos || - missing.find("shaderStorageImageWriteWithoutFormat") != std::string::npos) - std::printf(" (the translated image_load declares the without-format storage-image capabilities: its " - "uint/sint path is chosen from the T# FORMAT at run time, even when the case only reads a " - "float format)\n"); return unsupported; } BindlessFeatures device_flags{ @@ -260,8 +255,6 @@ int main(int argc, char** argv) { VkPhysicalDeviceFeatures2 enable{.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &enable12, .features = {.fragmentStoresAndAtomics = VK_TRUE, - .shaderStorageImageReadWithoutFormat = VK_TRUE, - .shaderStorageImageWriteWithoutFormat = VK_TRUE, .shaderSampledImageArrayDynamicIndexing = VK_TRUE, .shaderInt64 = VK_TRUE}}; std::uint32_t qn = 0; @@ -350,9 +343,8 @@ int main(int argc, char** argv) { std::memcpy(staging_map, texels.data(), texels.size()); VkImage image = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; - const VkImageLayout image_layout = integer ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - CHECK(make_image(spec.format, spec.width, spec.height, - (integer ? VK_IMAGE_USAGE_STORAGE_BIT : VK_IMAGE_USAGE_SAMPLED_BIT) | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + const VkImageLayout image_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + CHECK(make_image(spec.format, spec.width, spec.height, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, &image, &view)); // Render target, pass and framebuffer. constexpr VkFormat target_format = VK_FORMAT_R32G32B32A32_SFLOAT; @@ -475,10 +467,7 @@ int main(int argc, char** argv) { std::printf("unsupported: cannot create the bindless set\n"); return unsupported; } - StorageViews storage{}; - if (spec.format == VK_FORMAT_R8G8B8A8_UINT) storage.as_uint = view; - if (spec.format == VK_FORMAT_R8G8B8A8_SINT) storage.as_sint = view; - const std::uint32_t index = set->add_image(ImageDimension::dim_2d, integer ? VK_NULL_HANDLE : view, image_layout, storage); + const std::uint32_t index = set->add_image(ImageDimension::dim_2d, view, image_layout); if (index < 1) { std::fprintf(stderr, "FAILED add_image -> 0 (line %d)\n", __LINE__); return 1; diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp index f491a7ea9..66e133484 100644 --- a/runtime/test/vk_overlapping_occlusion_test.cpp +++ b/runtime/test/vk_overlapping_occlusion_test.cpp @@ -1,3 +1,4 @@ +#include "predicated_copy_controls.h" // Record synthetic draws between the physical query boundaries emitted by the Leonida replay queue. #include "vk_test_device.h" #include "../src/vulkan_backend.h" @@ -169,7 +170,12 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { const auto get_memory = d.instance_fn("vkGetPhysicalDeviceMemoryProperties"); get_memory(d.physical, &memory); context.set_occlusion_resolve_memory(memory); + VkPhysicalDeviceProperties properties{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); + context.configure_predication(get_device_proc, memory, properties.limits.maxStorageBufferRange, d.family); VulkanFence gate(context, 0); + PredicatedCopyControl copy_control; + EXPECT(copy_control.create(d, context, properties.limits)); VulkanQueue queue(context, d.queue, d.family); EXPECT(queue.ok() && gate.semaphore()); struct OpenGate { VulkanFence& fence; ~OpenGate() { fence.signal(1); } } open_gate{gate}; @@ -194,7 +200,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { void* words = nullptr; ResourceBinding predicate{}; predicate.size = 8; - predicate.buffer = d.buffer(8, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, &words); + predicate.buffer = d.buffer(8, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &words); EXPECT(predicate.buffer && words); std::memset(words, 0, 8); context.add_resource(predicate_id, predicate); @@ -228,6 +234,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { EXPECT(later.resolve_queries({a, binary, 3, 1, dst_id, 64})); EXPECT(later.resolve_queries({a, occ, 0, 1, dst_id, 72})); EXPECT(later.resolve_queries({a, binary, 3, 1, dst_id, 80})); + EXPECT(copy_control.record(later)); EXPECT(later.close()); const CommandList* second[] = {&later}; EXPECT(queue.execute(second) == ReplayResult::success); @@ -301,6 +308,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment) { std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; " "offsets and gated overwrites exact\n", 2 * bursts + 1); + EXPECT(copy_control.check()); return 0; } diff --git a/runtime/test/vk_predicate_capture_test.cpp b/runtime/test/vk_predicate_capture_test.cpp new file mode 100644 index 000000000..13c9c4592 --- /dev/null +++ b/runtime/test/vk_predicate_capture_test.cpp @@ -0,0 +1,157 @@ +// Synthetic GPU lifetime test: gate the queue so no predicate arena can retire before all submissions exist. +#include "vk_test_device.h" +#include "../src/vulkan_backend.h" +#include +#include +#include +#define EXPECT(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) +namespace { +PFN_vkCmdPipelineBarrier2 real_barrier2 = nullptr; +unsigned host_barriers = 0; +VkPipelineStageFlags2 host_source_stages = 0; +VKAPI_ATTR void VKAPI_CALL observe_barrier2(VkCommandBuffer cb, const VkDependencyInfo* info) { + for (std::uint32_t i = 0; i < info->memoryBarrierCount; ++i) { + const auto& barrier = info->pMemoryBarriers[i]; + if (barrier.dstStageMask & VK_PIPELINE_STAGE_2_HOST_BIT) { + ++host_barriers; + host_source_stages |= barrier.srcStageMask; + } + } + real_barrier2(cb, info); +} +} +int main() { + vktest::Device d; + if (!d.create()) return 1; + if (!d.conditional_rendering) { std::puts("predicate capture: skipped (no conditional rendering)"); return 0; } + using namespace leonida; + VkPhysicalDeviceMemoryProperties memory{}; + d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); + VkPhysicalDeviceProperties properties{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); + PredicateReducer limits(d.device_proc, d.device, memory, 16); + EXPECT(!limits.batch(0) && !limits.batch(2)); + PredicateReducer missing(+[](VkDevice, const char*) -> PFN_vkVoidFunction { return nullptr; }, d.device, memory, 16); + EXPECT(!missing.batch(1)); + auto no_memory = memory; no_memory.memoryTypeCount = 0; + PredicateReducer allocation_failure(d.device_proc, d.device, no_memory, 16); + EXPECT(!allocation_failure.batch(1)); + VulkanContext context(d.device_proc, d.device, true, true); + context.configure_predication(d.device_proc, memory, properties.limits.maxStorageBufferRange, d.family); + VulkanQueue queue(context, d.queue, d.family); + VulkanFence gate(context, 0); + EXPECT(context.loaded() && queue.ok() && gate.semaphore()); + constexpr unsigned count = 32; + void* mapped = nullptr; + const VkBuffer predicate = d.buffer(16, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &mapped); + EXPECT(predicate && mapped); + const std::uint64_t values[] = {UINT64_C(1) << 32, 0}; + std::memcpy(mapped, values, sizeof(values)); + const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UINT, 2, 1, count, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + void* pixels = nullptr; + const VkBuffer readback = d.buffer(count * 8, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &pixels); + EXPECT(image && readback && pixels); + ResourceBinding source{}; source.buffer = predicate; source.size = 16; + ResourceBinding target{}; target.image = image; target.format = VK_FORMAT_R8G8B8A8_UINT; + target.width = 2; target.height = 1; target.array_layers = count; + context.add_resource(1, source); + context.add_resource(2, target, VK_IMAGE_LAYOUT_UNDEFINED); + // Each list captures high-only -> zero -> high-only with two offsets, all while no prior batch can finish. + std::array lists; + queue.wait(gate.semaphore(), 1); + bool submitted = true; + for (unsigned i = 0; i < count; ++i) { + auto& list = lists[i]; + submitted = submitted && list.set_predication({1, 0, d3d12_predication::equal_zero}); + submitted = submitted && list.clear_render_target({2, 0, i, 1}, {7, 8, 9, 10}); + submitted = submitted && list.set_predication({1, 8, d3d12_predication::equal_zero}); + submitted = submitted && list.clear_render_target({2, 0, i, 1}, {99, 99, 99, 99}); + submitted = submitted && list.set_predication({1, 0, d3d12_predication::not_equal_zero}); + submitted = submitted && list.clear_render_target({2, 0, i, 1}, {100, 100, 100, 100}); + submitted = submitted && list.set_predication({0, 0, 0}); + const Rect right{1, 0, 2, 1}; + submitted = submitted && list.clear_render_target({2, 0, i, 1}, {float(i), 31, 73, 127}, {&right, 1}); + submitted = submitted && list.close(); + const CommandList* pointer = &list; + if (!submitted || queue.execute({&pointer, 1}) != ReplayResult::success) { submitted = false; break; } + } + // Always release the gate, including on failure, so destructors cannot wait forever on queued work. + EXPECT(gate.signal(1)); + EXPECT(queue.idle()); + EXPECT(submitted); + // Completed command-buffer slots must release their old arenas before being reused. + for (auto& list : lists) { + const CommandList* pointer = &list; + EXPECT(queue.execute({&pointer, 1}) == ReplayResult::success); + } + EXPECT(queue.idle()); + // Failed submissions must not commit their speculative layout transitions. + EXPECT(context.layout(2, 0) == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + CommandList failed; + EXPECT(failed.transition({2, 0, d3d12_state::render_target, d3d12_state::copy_source}) && failed.close()); + const CommandList* failed_pointer = &failed; + const auto real_submit = context.vk.vkQueueSubmit; + context.vk.vkQueueSubmit = +[](VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) -> VkResult { + return VK_ERROR_OUT_OF_HOST_MEMORY; // no GPU work and no device loss + }; + const auto failed_result = queue.execute({&failed_pointer, 1}); + context.vk.vkQueueSubmit = real_submit; + EXPECT(failed_result == ReplayResult::unsupported); + EXPECT(context.layout(2, 0) == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + + // Preserve main's readback-stage collection on every logical queue kind, using real transfer readbacks. + ResourceBinding output{}; output.buffer = readback; output.size = count * 8; output.host_readable = true; + context.add_resource(3, output); + CommandList copy, capture_only, empty; + EXPECT(copy.copy_buffer({3, 0, 1, 0, 16}) && copy.close()); + EXPECT(capture_only.set_predication({1, 0, d3d12_predication::equal_zero}) && capture_only.close()); + EXPECT(empty.close()); + real_barrier2 = context.vk.vkCmdPipelineBarrier2; + EXPECT(real_barrier2); + context.vk.vkCmdPipelineBarrier2 = observe_barrier2; + for (const auto kind : {VulkanQueue::QueueKind::direct, VulkanQueue::QueueKind::compute, VulkanQueue::QueueKind::copy}) { + VulkanQueue typed(context, d.queue, d.family, kind); + EXPECT(typed.ok()); + const CommandList* no_write = ∅ + host_barriers = 0; host_source_stages = 0; + EXPECT(typed.execute({&no_write, 1}) == ReplayResult::success); + EXPECT(host_barriers == 0); + const CommandList* capture = &capture_only; + EXPECT(typed.execute({&capture, 1}) == (kind == VulkanQueue::QueueKind::copy + ? ReplayResult::unsupported : ReplayResult::success)); + EXPECT(host_barriers == 0); + const CommandList* transfer = © + EXPECT(typed.execute({&transfer, 1}) == ReplayResult::success); + EXPECT(typed.idle()); + EXPECT(host_barriers == 1 && host_source_stages != 0); + EXPECT((host_source_stages & ~VulkanQueue::queue_supported_stages(kind)) == 0); + EXPECT((host_source_stages & ~(VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT)) == 0); + EXPECT(std::memcmp(pixels, values, sizeof(values)) == 0); + } + context.vk.vkCmdPipelineBarrier2 = real_barrier2; + EXPECT(d.run([&](VkCommandBuffer cb) { + VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, count}; + context.vk.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &barrier); + VkBufferImageCopy region{}; region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, count}; + region.imageExtent = {2, 1, 1}; + context.vk.vkCmdCopyImageToBuffer(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, ®ion); + VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + context.vk.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, + 0, 1, &host, 0, nullptr, 0, nullptr); + return true; + })); + const auto* bytes = static_cast(pixels); + for (unsigned i = 0; i < count; ++i) { + EXPECT(bytes[i * 8] == 7 && bytes[i * 8 + 1] == 8 && bytes[i * 8 + 2] == 9 && bytes[i * 8 + 3] == 10); + EXPECT(bytes[i * 8 + 4] == i && bytes[i * 8 + 5] == 31 && bytes[i * 8 + 6] == 73 && bytes[i * 8 + 7] == 127); + } + EXPECT(d.validation_errors() == 0); + std::puts("predicate capture: 32 gated + 32 reused submissions, 192 snapshots, offset rebinding and reset passed"); + std::puts("predicate capture integration: failed-submit tracker rollback and direct/compute/copy readback stages passed"); +} diff --git a/runtime/test/vk_predicated_copy_test.cpp b/runtime/test/vk_predicated_copy_test.cpp new file mode 100644 index 000000000..fd214ae0d --- /dev/null +++ b/runtime/test/vk_predicated_copy_test.cpp @@ -0,0 +1,112 @@ +// Synthetic byte-copy, forced descriptor windows and pending-submit lifetime regression. No game data. +#include "vk_test_device.h" +#include "../src/vulkan_backend.h" +#include +#include +#include +#define EXPECT(x) do { if (!(x)) { std::fprintf(stderr,"line %d: %s\n",__LINE__,#x); return 1; } } while(0) +namespace { +PFN_vkCmdPipelineBarrier2 real_barrier2 = nullptr; +unsigned host_barriers = 0; +VkPipelineStageFlags2 host_stages = 0; +VKAPI_ATTR void VKAPI_CALL observe_host(VkCommandBuffer cb, const VkDependencyInfo* info) { + for (std::uint32_t i = 0; i < info->memoryBarrierCount; ++i) { + const auto& b = info->pMemoryBarriers[i]; + if (b.dstStageMask & VK_PIPELINE_STAGE_2_HOST_BIT) { ++host_barriers; host_stages |= b.srcStageMask; } + } + real_barrier2(cb, info); +} +} +int main() { + vktest::Device d; + if(!d.create())return 1; + if(!d.conditional_rendering || !d.storage_buffer_8bit) { + std::puts("predicated copy: skipped (requires conditional rendering and storageBuffer8BitAccess)"); return 0; + } + using namespace leonida; + VkPhysicalDeviceMemoryProperties memory{}; + d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical,&memory); + VkPhysicalDeviceProperties properties{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical,&properties); + auto limits=properties.limits; + // Smaller advertised limits force both dispatch and descriptor-window splits on ordinary GPUs. + limits.maxStorageBufferRange=static_cast(std::max(256,limits.minStorageBufferOffsetAlignment)); + limits.maxComputeWorkGroupCount[0]=1; + VulkanContext context(d.device_proc,d.device,true,true); + context.configure_predication(d.device_proc,memory,properties.limits.maxStorageBufferRange,d.family); + VulkanQueue queue(context,d.queue,d.family); + VulkanFence gate(context,0); + EXPECT(context.loaded() && queue.ok() && gate.semaphore()); + constexpr std::size_t bytes=8207; + constexpr auto usage=VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT; + void *src_data=nullptr,*dst_data=nullptr,*pred_data=nullptr; + auto src=d.buffer(bytes,usage,&src_data),dst=d.buffer(bytes,usage,&dst_data); + auto pred=d.buffer(16,usage,&pred_data); + EXPECT(src&&dst&&pred&&src_data&&dst_data&&pred_data); + std::array input{},expected{}; + for(std::size_t i=0;i(37*i+11); expected[i]=static_cast(13*i+173); } + std::memcpy(src_data,input.data(),bytes); std::memcpy(dst_data,expected.data(),bytes); + const std::uint64_t predicates[]={UINT64_C(1)<<32,0}; std::memcpy(pred_data,predicates,sizeof(predicates)); + ResourceBinding a{};a.buffer=src;a.buffer_offset=1;a.size=bytes-1; + ResourceBinding b{};b.buffer=dst;b.buffer_offset=3;b.size=bytes-3;b.host_readable=true; + ResourceBinding p{};p.buffer=pred;p.size=16; + context.add_resource(1,a);context.add_resource(2,b);context.add_resource(3,p); + CommandList list; + EXPECT(list.set_predication({3,0,d3d12_predication::equal_zero})); + EXPECT(list.copy_buffer({2,4,1,2,4096})); // high-word-only condition; offsets include arena prefixes + EXPECT(list.copy_buffer({2,6000,2,4,33})); // dependent, non-overlapping copy within one VkBuffer + EXPECT(list.set_predication({3,8,d3d12_predication::equal_zero})); + EXPECT(list.copy_buffer({2,0,1,0,3})); // suppressed: preserves destination prefix exactly + EXPECT(list.set_predication({3,0,d3d12_predication::not_equal_zero})); + EXPECT(list.copy_buffer({2,7000,1,0,37}));// suppressed: high word must not be truncated + EXPECT(list.set_predication({0,0,0})); + EXPECT(list.copy_buffer({2,5000,1,0,17}));// reset restores ordinary transfer path + EXPECT(list.close()); + std::memcpy(expected.data()+7,input.data()+3,4096); + std::memcpy(expected.data()+6003,expected.data()+7,33); + std::memcpy(expected.data()+5003,input.data()+1,17); + const CommandList* pointer=&list; + // A device without the helper must submit nothing, rather than run a transfer unconditionally. + EXPECT(queue.execute({&pointer,1})==ReplayResult::unsupported); + EXPECT(std::memcmp(dst_data,expected.data(),bytes)!=0); // expected includes the not-yet-executed copies + for(std::size_t i=0;i(dst_data)[i]==static_cast(13*i+173)); + context.configure_predicated_copy(d.device_proc,limits); + const auto real_submit=context.vk.vkQueueSubmit; + context.vk.vkQueueSubmit=+[](VkQueue,std::uint32_t,const VkSubmitInfo*,VkFence)->VkResult{return VK_ERROR_OUT_OF_HOST_MEMORY;}; + const auto rejected=queue.execute({&pointer,1}); + context.vk.vkQueueSubmit=real_submit; + EXPECT(rejected==ReplayResult::unsupported); + for(std::size_t i=0;i(dst_data)[i]==static_cast(13*i+173)); + queue.wait(gate.semaphore(),1); + bool submitted=true; + for(unsigned i=0;i<32;++i) if(queue.execute({&pointer,1})!=ReplayResult::success){submitted=false;break;} + // Release even on preparation failure, before any destructor can wait for the queue. + EXPECT(gate.signal(1));EXPECT(queue.idle());EXPECT(submitted); + EXPECT(std::memcmp(dst_data,expected.data(),bytes)==0 && std::memcmp(src_data,input.data(),bytes)==0); + for(unsigned i=0;i<32;++i) EXPECT(queue.execute({&pointer,1})==ReplayResult::success); + EXPECT(queue.idle()); + EXPECT(std::memcmp(dst_data,expected.data(),bytes)==0 && std::memcmp(src_data,input.data(),bytes)==0); + real_barrier2=context.vk.vkCmdPipelineBarrier2; EXPECT(real_barrier2); + context.vk.vkCmdPipelineBarrier2=observe_host; + CommandList ordinary; EXPECT(ordinary.copy_buffer({2,5000,1,0,17}) && ordinary.close()); + const CommandList* plain=&ordinary; + for(auto kind:{VulkanQueue::QueueKind::direct,VulkanQueue::QueueKind::compute,VulkanQueue::QueueKind::copy}) { + VulkanQueue typed(context,d.queue,d.family,kind); EXPECT(typed.ok()); + host_barriers=0;host_stages=0; + if(kind==VulkanQueue::QueueKind::copy) { + EXPECT(typed.execute({&pointer,1})==ReplayResult::unsupported && host_barriers==0); + EXPECT(typed.execute({&plain,1})==ReplayResult::success); + EXPECT(host_stages==VK_PIPELINE_STAGE_2_COPY_BIT); + } else { + EXPECT(typed.execute({&pointer,1})==ReplayResult::success); + EXPECT(host_stages==(VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT|VK_PIPELINE_STAGE_2_COPY_BIT)); + } + EXPECT(typed.idle() && host_barriers==1); + EXPECT((host_stages & ~VulkanQueue::queue_supported_stages(kind))==0); + EXPECT(std::memcmp(dst_data,expected.data(),bytes)==0); + } + context.vk.vkCmdPipelineBarrier2=real_barrier2; + EXPECT(d.validation_errors()==0); + std::puts("predicated copy integration: failed-submit cleanup and direct/compute/copy host stages passed"); + std::puts("predicated copy: 32 gated + 32 reused submissions; byte offsets, forced windows, copy dependency, rebinding/reset and untouched bytes passed"); +} diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index ad7fa64ab..9e970434a 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -1,8 +1,14 @@ -// Headless Vulkan test for translated typed image stores (runtime/test/shaders/cs_imgstore.asm). -// Usage: vk_store_test cs.spv +// Headless Vulkan test for translated typed image stores and loads (runtime/test/shaders/cs_imgstore.asm and +// cs_imgload.asm). +// Usage: vk_store_test cs.spv [load] // The shader builds three T#s (word1 FORMAT = 56 rgba8 unorm, 20 r32 uint, 21 r32 sint) and stores to three 8x8 // images. The translator picks the float / uint / sint view (set 0, bindings 8 / 9 / 10 for 2D) from the FORMAT -// field, and the bindless index from the descriptor hash table (binding 2). Checks every texel. +// field, and the bindless index from the descriptor hash table (binding 2). As in the runtime, each image has its +// own index in the 2D arrays (1, 2, 3; index 0 is the fallback) and its view in its own format at that index of the +// sampled array (binding 0), which typed image_load fetches from. Checks every texel. +// "load" (cs_imgload.asm): the uint and sint images are filled before the dispatch, and the shader loads both +// texels with image_load and stores their sum into the sint image. The device is made without +// shaderStorageImageReadWithoutFormat, and a module that declares StorageImageReadWithoutFormat fails (SHADER-151). #include "vulkan_loader.h" #include "vk_device_pick.h" @@ -80,11 +86,11 @@ int main(int argc, char** argv) { float prio = 1; VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; - // The typed stores/loads need format-less storage image access. Some GPUs (e.g. Intel Gen9) lack the read side: - // report that and exit 77 (unsupported, as vk_compute_test does) instead of failing vkCreateDevice. + // The typed stores need format-less storage image writes: without them, report that and exit 77 (unsupported, + // as vk_compute_test does) instead of failing vkCreateDevice. Typed loads need no storage image feature. VkPhysicalDeviceFeatures have{}; vkGetPhysicalDeviceFeatures(pd, &have); - if (!have.shaderStorageImageWriteWithoutFormat || !have.shaderInt64) { // every mode; reads: load mode, below + if (!have.shaderStorageImageWriteWithoutFormat || !have.shaderInt64) { std::printf("unsupported: shaderStorageImageWriteWithoutFormat=%u shaderInt64=%u\n", have.shaderStorageImageWriteWithoutFormat, have.shaderInt64); return 77; @@ -95,15 +101,25 @@ int main(int argc, char** argv) { f12.shaderSampledImageArrayNonUniformIndexing = VK_TRUE; VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; - // "load" mode (cs_imgload.asm): the sint image receives the uint texel read back with image_load. + // "load" mode (cs_imgload.asm): the sint image receives the sum of the two texels read back with image_load. const bool load_mode = argc > 2 && !std::strcmp(argv[2], "load"); + std::ifstream f(argv[1], std::ios::binary); + std::vector code((std::istreambuf_iterator(f)), {}); + if (code.size() < 20 || code.size() % 4) { std::fprintf(stderr, "%s: not a SPIR-V module\n", argv[1]); return 1; } if (load_mode) { - // Only image_load needs it, and some GPUs (Intel Gen9) lack it: report that instead of a failed vkCreateDevice. - if (!have.shaderStorageImageReadWithoutFormat) { - std::printf("unsupported: shaderStorageImageReadWithoutFormat\n"); - return 77; + // Typed image_load fetches through the sampled arrays, so it must not need a feature Intel Xe-LP lacks + // (SHADER-151). shaderStorageImageReadWithoutFormat stays off; a module declaring it would be invalid here. + std::vector words(code.size() / 4); + std::memcpy(words.data(), code.data(), code.size()); + for (std::size_t i = 5; i < words.size() && (words[i] >> 16);) { + const uint32_t op = words[i] & 0xffff, count = words[i] >> 16; + // OpCapability (17) StorageImageReadWithoutFormat (55; spirv/unified1/spirv.h) + if (op == 17 && count == 2 && i + 1 < words.size() && words[i + 1] == 55) { + std::printf("FAILED: the module declares StorageImageReadWithoutFormat\n"); + return 1; + } + i += count; } - f2.features.shaderStorageImageReadWithoutFormat = VK_TRUE; } f2.features.shaderInt64 = VK_TRUE; f2.pNext = &f12; @@ -119,7 +135,8 @@ int main(int argc, char** argv) { LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets); LOADD(vkUpdateDescriptorSets); LOADD(vkCreateCommandPool); LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); LOADD(vkCmdBindPipeline); LOADD(vkCmdBindDescriptorSets); LOADD(vkCmdPushConstants); LOADD(vkCmdDispatch); - LOADD(vkCmdPipelineBarrier); LOADD(vkCmdCopyImageToBuffer); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); + LOADD(vkCmdPipelineBarrier); LOADD(vkCmdCopyImageToBuffer); LOADD(vkCmdCopyBufferToImage); + LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); LOADD(vkQueueWaitIdle); VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); @@ -151,7 +168,7 @@ int main(int argc, char** argv) { for (uint32_t k = 0; k < 3; k++) { uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); - table_insert(table, t, 0); // index 0 in its class's array + table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime } VkBuffer tb; void* tbp; CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); @@ -163,7 +180,8 @@ int main(int argc, char** argv) { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT; CHECK(vkCreateImage(dev, &ii, nullptr, &img[k])); VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, img[k], &mr); VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; @@ -178,19 +196,23 @@ int main(int argc, char** argv) { VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler)); // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays. + // Four elements each: index 0 stands for the runtime's fallback, image k is at index k + 1. Binding 0 holds each + // image's view in its own format (typed image_load reads the uint and sint ones through integer aliases); every + // element of a storage array holds the image of its class, so all of them are valid descriptors. + constexpr uint32_t N = 4; VkDescriptorSetLayoutBinding b[6]{}; - b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 6; dli.pBindings = b; VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); VkDescriptorPoolSize ps[4] = { - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1}, + {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 3}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 3 * N}, }; VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps; @@ -199,22 +221,25 @@ int main(int argc, char** argv) { dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); VkDescriptorBufferInfo tbi{tb, 0, VK_WHOLE_SIZE}; - VkDescriptorImageInfo sii{VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}; + VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, view[1], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, view[2], VK_IMAGE_LAYOUT_GENERAL}}; VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; - VkDescriptorImageInfo dii[3]; + VkDescriptorImageInfo dii[3][N]; VkWriteDescriptorSet wr[6]{}; for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; } - wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = &sii; + wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii; + wr[0].descriptorCount = N; wr[1].dstBinding = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &smpi; wr[2].dstBinding = 2; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tbi; for (int k = 0; k < 3; k++) { - dii[k] = {VK_NULL_HANDLE, view[k], VK_IMAGE_LAYOUT_GENERAL}; - wr[3 + k].dstBinding = 8 + k; wr[3 + k].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; wr[3 + k].pImageInfo = &dii[k]; + for (uint32_t e = 0; e < N; e++) dii[k][e] = {VK_NULL_HANDLE, view[k], VK_IMAGE_LAYOUT_GENERAL}; + wr[3 + k].dstBinding = 8 + k; wr[3 + k].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + wr[3 + k].pImageInfo = dii[k]; wr[3 + k].descriptorCount = N; } vkUpdateDescriptorSets(dev, 6, wr, 0, nullptr); - std::ifstream f(argv[1], std::ios::binary); - std::vector code((std::istreambuf_iterator(f)), {}); VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size(); smi.pCode = reinterpret_cast(code.data()); VkShaderModule sm; CHECK(vkCreateShaderModule(dev, &smi, nullptr, &sm)); @@ -230,6 +255,16 @@ int main(int argc, char** argv) { VkBuffer rb[3]; void* rbp[3]; for (int k = 0; k < 3; k++) CHECK(make_buffer(W * W * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); + // Load mode: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. + VkBuffer fill[2]{}; void* fillp[2]{}; + if (load_mode) { + for (int j = 0; j < 2; j++) + CHECK(make_buffer(W * W * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[j], &fillp[j])); + for (uint32_t i = 0; i < W * W; i++) { + static_cast(fillp[0])[i] = 100 + i; + static_cast(fillp[1])[i] = -2 * int32_t(i); + } + } VkCommandPoolCreateInfo cpci{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpci.queueFamilyIndex = qi; VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpci, nullptr, &pool)); VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; @@ -244,8 +279,25 @@ int main(int argc, char** argv) { ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].srcQueueFamilyIndex = ib[k].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + if (load_mode && k > 0) { // filled by a copy first + ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + } + } + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, + nullptr, 3, ib); + if (load_mode) { + for (int k = 1; k < 3; k++) { + VkBufferImageCopy bic{}; + bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; + vkCmdCopyBufferToImage(cmd, fill[k - 1], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bic); + ib[k].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; + ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + } + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, + nullptr, 0, nullptr, 2, ib + 1); } - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 3, ib); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); uint32_t pc[36] = {}; @@ -274,7 +326,8 @@ int main(int argc, char** argv) { int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255)); if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - 128) > 1 || c[3] != 255) bad[0]++; if (static_cast(rbp[1])[i] != 100 + 8 * y + x) bad[1]++; - const int32_t want_s = load_mode ? int32_t(100 + 8 * y + x) : -int32_t(8 * y + x); + // load: the uint texel (100 + 8y + x) plus the sint one (-2 (8y + x)), both read with image_load + const int32_t want_s = load_mode ? 100 - int32_t(8 * y + x) : -int32_t(8 * y + x); if (static_cast(rbp[2])[i] != want_s) bad[2]++; } const uint8_t* c = static_cast(rbp[0]) + 4 * (3 * W + 5); diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index cf223921f..89220559b 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -67,6 +67,7 @@ public: bool bindless = false; // the features the bindless set 0 needs are enabled bool partially_bound = false; // and its slots can stay empty bool image_view_min_lod = false; + bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled bool occlusion_query_precise = false; // occlusionQueryPrecise enabled @@ -281,6 +282,8 @@ public: VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable13}; enable12.timelineSemaphore = VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; + storage_buffer_8bit = features12.storageBuffer8BitAccess == VK_TRUE; + enable12.storageBuffer8BitAccess = storage_buffer_8bit; // What the bindless set 0 of the translated shaders needs, where the device has it: runtime arrays of // images indexed dynamically, updated while the set is bound; and, to leave slots empty, partially bound // bindings. diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py index 0785a0999..ac22c856c 100644 --- a/scripts/audit_shader4_regs.py +++ b/scripts/audit_shader4_regs.py @@ -353,13 +353,30 @@ def main(argv=None): a = ap.parse_args(argv) if a.limit is not None and a.limit < 0: ap.exit(2, f"{ap.prog}: error: --limit must be non-negative\n") + # A bad path is one ERROR line, not a traceback out of os.listdir: the audit of a whole corpus can + # run for minutes, and an explicit --fssm/--dxbc that does not exist would otherwise be counted as + # "(missing fssm)" and print a report that looks right. + for label, path in (("", a.disasm_dir), ("--fssm: ", a.fssm), ("--dxbc: ", a.dxbc)): + if path is None: + continue + if not os.path.exists(path): + print(f"ERROR: {label}{path}: no such folder", file=sys.stderr) + return 2 + if not os.path.isdir(path): + print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) + return 2 rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit) print_report(rep) if a.json_out: - with open(a.json_out, "w", encoding="utf-8") as f: - json.dump(rep, f, indent=2) - f.write("\n") + try: + os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True) + with open(a.json_out, "w", encoding="utf-8") as f: + json.dump(rep, f, indent=2) + f.write("\n") + except OSError as e: + print(f"ERROR: {a.json_out}: cannot write: {e.strerror or e}", file=sys.stderr) + return 1 print(f"wrote {a.json_out}") return 0 diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1 index 66508971b..2f58f6130 100644 --- a/scripts/build_llvm_mc.ps1 +++ b/scripts/build_llvm_mc.ps1 @@ -6,9 +6,13 @@ # # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -Dest D:\tools\llvm-mc -NoEnv +# +# The default -Dest is outside AppData on purpose: `python` from the Python install manager (the app execution alias +# in WindowsApps) doesn't see folders that other programs create under %LOCALAPPDATA% or %APPDATA%, so an llvm-mc.exe +# there looks missing to make_game.py and the tools, although LLVM_MC names it. param( [string]$Version = "21.1.8", - [string]$Dest = (Join-Path $env:LOCALAPPDATA "Leonida\llvm-mc"), + [string]$Dest = (Join-Path $env:USERPROFILE ".leonida\llvm-mc"), [string]$Temp = (Join-Path $env:TEMP "leonida-llvm-mc"), [switch]$NoEnv, # don't set LLVM_MC for the current user [switch]$Keep # keep the sources and build folder (faster rebuilds) diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 2ac61356b..76179acda 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -49,6 +49,11 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_bindless_test.cpp" /Fe:vk_bindless_test.exe || exit /b 1 if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_descriptor_bench.cpp" /Fe:vk_descriptor_bench.exe || exit /b 1 +rem The GPU test harnesses check.py and run_gpu_tests.py require and the fuzzers run (tests\test_build_runtime_fallback.py). +if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_harness.cpp" /Fe:vk_harness.exe || exit /b 1 +if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_compute_test.cpp" /Fe:vk_compute_test.exe || exit /b 1 +if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_store_test.cpp" /Fe:vk_store_test.exe || exit /b 1 +if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_image_fuzz.cpp" /Fe:vk_image_fuzz.exe || exit /b 1 "@ } diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index d0c6c9c4f..5f4354ef3 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -34,7 +34,8 @@ from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT) from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS -from check import WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, narrow_subgroup_skip, wave32_lane_skip # as in check.py +from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, + wave32_lane_skip) # as in check.py from check import PIXEL_VERTEX, interp_f16_high_problem # ps_interp_f16_high's producers and check @@ -79,7 +80,8 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_ def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" - raw = open(asm_path, encoding="utf-8").read() + with open(asm_path, encoding="utf-8") as source: + raw = source.read() cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] for ln in raw.splitlines(): s = ln.strip() @@ -94,8 +96,9 @@ def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: if name in CLIP_CASES: cmd.append(f"-defsym=PARAM_SLOT={CLIP_CASES[name]}") cmd.append("-show-encoding") - p = subprocess.run( + p = mc_command.run( # a missing llvm-mc: a short message naming LLVM_MC/--llvm-mc, not a traceback cmd, + flag="--llvm-mc", input=raw, capture_output=True, text=True, @@ -209,13 +212,15 @@ def make_fs_passthru(loc: int) -> str: def read_raw_rgba32f(path: str) -> list[tuple[float, float, float, float]]: - data = open(path, "rb").read() + with open(path, "rb") as source: + data = source.read() n = len(data) // 16 return [struct.unpack_from("<4f", data, 16 * i) for i in range(n)] def read_raw_u32(path: str) -> list[tuple[int, int, int, int]]: - data = open(path, "rb").read() + with open(path, "rb") as source: + data = source.read() n = len(data) // 16 return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)] @@ -322,8 +327,10 @@ def check_bary(raw_path: str) -> tuple[bool, str]: return (bad == 0), (first if bad else "4096/4096 pixels exact") -def check_bitmask_perm(raw_path: str) -> tuple[bool, str]: +def check_bitmask_perm(raw_path: str, msg: str = "") -> tuple[bool | None, str]: px = read_raw_u32(raw_path) + if skip := bitmask_perm_narrow_skip(msg, px): + return None, str(skip) bad = 0 first = "" judged = 0 @@ -353,7 +360,8 @@ PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x1 def check_flat(raw_path: str) -> tuple[bool, str]: """ps_flat with vs_ids: the integer IDs come from the first (provoking) vertex, the UVs still interpolate.""" - data = open(raw_path, "rb").read() + with open(raw_path, "rb") as source: + data = source.read() px = list(struct.iter_unpack("<2I2f", data)) w = int(len(px) ** 0.5) wrong = sum((a, b) != (0x101, 0x102) for a, b, _, _ in px) @@ -484,7 +492,8 @@ DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_textur "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", "ps_gather_wrap": "vs_ids.asm", **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_ops.asm", - "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm"} + "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", + "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm"} def with_draw_shaders(asm_files: list[str]) -> list[str]: @@ -656,7 +665,8 @@ def run_suite(a, work: str) -> int: index = {} idx_path = os.path.join(spirv_dir, "index.json") if os.path.isfile(idx_path): - index = json.load(open(idx_path, encoding="utf-8")) + with open(idx_path, encoding="utf-8") as source: + index = json.load(source) ext = ".exe" if os.name == "nt" else "" vk_compute = os.path.join(a.build, "vk_compute_test" + ext) @@ -749,7 +759,8 @@ def run_suite(a, work: str) -> int: # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) elif name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_exec_const", "cs_w32_lds_u8_d16", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", - + "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", + "cs_dpp_bound", "cs_dpp_w64", "cs_w64_mask_detect", "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", @@ -772,6 +783,15 @@ def run_suite(a, work: str) -> int: "cs_w32_lds_u8_d16": [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234], # constant EXEC masks (cs_exec_const.asm): each lane takes its own bit of the constant "cs_exec_const": [16, 8, 2, 16, 0, 16], + "cs_dpp": [1, 0, 3, 2, 5, 4, 7, 6], + "cs_dpp_row": [0, 0, 1, 2, 3, 4, 5, 6], + "cs_dpp_mask": [1, 0, 3, 2, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE], + "cs_dpp8": [7, 6, 5, 4, 3, 2, 1, 0], + "cs_dpp_ops": [100, 10, 11, 12, 13, 14, 15, 16], + "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16], + "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], + "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], + "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], "cs_wave64_ballot": [32, 16, 24, 40, 8, 48], "cs_wm_half_ops": [32, 16, 16, 0, 16], "cs_wm_half_cmp": [1, 0, 1, 1], @@ -810,10 +830,10 @@ def run_suite(a, work: str) -> int: } want = cs_dump_wants[name] # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / - # cs_w32_lds_u8_d16 and the wave32 cs_wqm_w32 / cs_bpermute32 is a whole-wave (wave64) mask test: - # ask for a 64-wide subgroup and skip, as check.py does, where the device has none (vk_compute_test - # exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were translated with - # --wave64-emulate and run on any subgroup size. + # cs_w32_lds_u8_d16, the wave32 cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) + # mask test: ask for a 64-wide subgroup and skip, as check.py does, where the device has none + # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were + # translated with --wave64-emulate and run on any subgroup size. # cs_w64x_partial and cs_w64x_partial_scmp (40-thread groups) can't have full subgroups: they ask for # size 64 without them. emulated = w64_emulated() @@ -821,8 +841,8 @@ def run_suite(a, work: str) -> int: wave64 = name not in ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", "cs_w32_partial_scmp", - "cs_exec_const") and not emulated and not partial - + "cs_exec_const", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", + "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi") and not emulated and not partial if partial and not emulated: cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) @@ -922,7 +942,7 @@ def run_suite(a, work: str) -> int: raw = os.path.join(raw_dir, f"{name}.raw") vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_flat" else vs_tri # check.py draws ps_flat with vs_ids if name in PIXEL_VERTEX: - if bary_fallback(): # no PerVertexKHR inputs under --bary-fallback (docs/design.md) + if bary_fallback() and name == "ps_interp_f16_high": # no PerVertexKHR inputs under --bary-fallback results.append((name, None, "SKIP (per-vertex f16 interpolants need barycentrics)")) continue vs = os.path.join(spirv_dir, PIXEL_VERTEX[name] + ".spv") @@ -968,6 +988,13 @@ def run_suite(a, work: str) -> int: "ps_sff_imm": (2, 1, 20, 16), # SHADER-46: s_ff0/s_ff1 of an immediate "ps_fnan_med3": (0x40A00000, 0xC0200000, 0xC0200000, 0x40600000), # measured on RDNA2 hardware "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000), + # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) + "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), + "ps_cvt_off": (0xBF000000, 0x3EE00000, 0xBE800000, 0x3F800000), + "ps_fmac_f16_mods": (0xAAAA3C00, 0xAAAA3E00, 0xAAAA0000, 0xAAAA4000), + "ps_vop3_const_mods": (0xC0000000, 0xBF800000, 0x3F800000, 0xAAAABC00), + "ps_interp_f32_mods": (0x3F800000, 0x00000000, 0x3F400000, 0x3F800000), # drawn with vs_interp_consts + "ps_interp_mov_mods": (0x3F800000, 0x3FC00000, 0x40000000, 0x3F400000), } if name in const_wants: ok, detail = check_pixel_const(raw, const_wants[name]) @@ -978,7 +1005,7 @@ def run_suite(a, work: str) -> int: if m and int(m.group(1)) < 32: ok, detail = None, f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)" else: - ok, detail = check_bitmask_perm(raw) + ok, detail = check_bitmask_perm(raw, msg) elif name in ("ps_uniform_branch", "ps_scc_mask32"): # same expected pattern (see the .asm headers) ok, detail = check_uniform_branch(raw) elif name == "ps_wqm": @@ -986,7 +1013,8 @@ def run_suite(a, work: str) -> int: elif name == "ps_flat": ok, detail = check_flat(raw) elif name == "ps_interp_f16_high": - problem = interp_f16_high_problem(list(struct.iter_unpack("<4I", open(raw, "rb").read()))) + with open(raw, "rb") as source: + problem = interp_f16_high_problem(list(struct.iter_unpack("<4I", source.read()))) ok, detail = not problem, problem or "f16 low/high halves and f32 control within 2e-3" else: ok, detail = False, "no checker defined" @@ -1040,7 +1068,8 @@ def run_suite(a, work: str) -> int: elif rc != 0: results.append((name, False, msg)) else: - problem = interp_f16_high_problem(list(struct.iter_unpack("<4I", open(raw, "rb").read()))) + with open(raw, "rb") as source: + problem = interp_f16_high_problem(list(struct.iter_unpack("<4I", source.read()))) results.append((name, not problem, problem or "f16 low/high halves and f32 control within 2e-3")) elif name == "ms_clip": raw = os.path.join(raw_dir, f"{name}.raw") diff --git a/tests/semantic/README.md b/tests/semantic/README.md index 9d33f1d75..c54e5fb14 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -48,6 +48,11 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): - `test_float_nan_fract.py` runs float min/max/min3/max3/med3 with a quiet NaN and `v_fract` next to 1.0 (f32 and f16) with inputs from memory, and the GPU fixtures `ps_fnan_med3` and `ps_fnan_fract`; the expected words were measured on an AMD Radeon RX 6800 (gfx1030). A NaN result is asserted as "a NaN", not by its bits. +- `test_rule_gpu_fixtures.py` runs the GPU fixtures for the `docs/design.md` rules that used to be CPU-only (TEST-175: + `v_cmp(x)_nlg`, `v_cvt_off_f32_i4`, the `v_fmac_f16` / `v_interp_p2/mov_f32` output modifiers and VOP3 modifiers on + constants) through the interpreter, and checks that the words each `.asm` header derives are the ones `check.py` + and `scripts/run_gpu_tests.py` expect. The two interp fixtures get the constants their vertex shader, + `vs_interp_consts`, exports. - `test_interp.py` tests the interpreter against the SPIR-V / GLSL.std.450 definitions. The interpreter raises `UnsupportedConstruct` for anything it does not model instead of approximating it. It can seed Input variables, PushConstant words and a flat physical-address memory map for the tests above. diff --git a/tests/semantic/fixtures/disasm/ps_cmp_nlg.s b/tests/semantic/fixtures/disasm/ps_cmp_nlg.s new file mode 100644 index 000000000..67e697fb0 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_cmp_nlg.s @@ -0,0 +1,76 @@ +; ps_cmp_nlg test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_cmp_nlg.asm + v_mov_b32_e32 v10, 0 + v_mov_b32_e32 v0, 1.0 + v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 + v_cndmask_b32_e64 v1, 0, 1, vcc_lo + v_or_b32_e32 v10, v10, v1 + v_mov_b32_e32 v0, 0x80000000 + v_cmp_nlg_f32_e32 vcc_lo, 0, v0 + v_cndmask_b32_e64 v1, 0, 2, vcc_lo + v_or_b32_e32 v10, v10, v1 + v_mov_b32_e32 v0, 0x7fc00000 + v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 + v_cndmask_b32_e64 v1, 0, 4, vcc_lo + v_or_b32_e32 v10, v10, v1 + v_mov_b32_e32 v0, 0x40200000 + v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 + v_cndmask_b32_e64 v1, 0, 8, vcc_lo + v_or_b32_e32 v10, v10, v1 + v_mov_b32_e32 v0, 0x7f800001 + v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 + v_cndmask_b32_e64 v1, 0, 16, vcc_lo + v_or_b32_e32 v10, v10, v1 + v_mov_b32_e32 v0, 0x7f800000 + v_mov_b32_e32 v2, 0x7f800000 + v_cmp_nlg_f32_e32 vcc_lo, v2, v0 + v_cndmask_b32_e64 v1, 0, 32, vcc_lo + v_or_b32_e32 v10, v10, v1 + v_mov_b32_e32 v2, 0xff800000 + v_cmp_nlg_f32_e32 vcc_lo, v2, v0 + v_cndmask_b32_e64 v1, 0, 64, vcc_lo + v_or_b32_e32 v10, v10, v1 + v_or_b32_e32 v10, 0x40000000, v10 + v_mov_b32_e32 v11, 0 + v_mov_b32_e32 v0, 0xabcd3c00 + v_mov_b32_e32 v2, 0x12343c00 + v_cmp_nlg_f16_e32 vcc_lo, v0, v2 + v_cndmask_b32_e64 v1, 0, 1, vcc_lo + v_or_b32_e32 v11, v11, v1 + v_mov_b32_e32 v0, 0xabcd0000 + v_mov_b32_e32 v2, 0x12348000 + v_cmp_nlg_f16_e32 vcc_lo, v0, v2 + v_cndmask_b32_e64 v1, 0, 2, vcc_lo + v_or_b32_e32 v11, v11, v1 + v_mov_b32_e32 v0, 0xabcd7e00 + v_mov_b32_e32 v2, 0x12343c00 + v_cmp_nlg_f16_e32 vcc_lo, v0, v2 + v_cndmask_b32_e64 v1, 0, 4, vcc_lo + v_or_b32_e32 v11, v11, v1 + v_mov_b32_e32 v0, 0xabcd3c00 + v_mov_b32_e32 v2, 0x12344100 + v_cmp_nlg_f16_e32 vcc_lo, v0, v2 + v_cndmask_b32_e64 v1, 0, 8, vcc_lo + v_or_b32_e32 v11, v11, v1 + v_or_b32_e32 v11, 0x40000000, v11 + v_mov_b32_e32 v12, 0 + v_mov_b32_e32 v0, -1.0 + v_cmp_nlg_f32_e64 s1, -|v0|, v0 + v_cndmask_b32_e64 v1, 0, 1, s1 + v_or_b32_e32 v12, v12, v1 + v_mov_b32_e32 v2, 0x40200000 + v_cmp_nlg_f32_e64 s1, |v0|, v2 + v_cndmask_b32_e64 v1, 0, 2, s1 + v_or_b32_e32 v12, v12, v1 + v_or_b32_e32 v12, 0x40000000, v12 + v_mov_b32_e32 v0, 1.0 + v_cmpx_nlg_f32_e32 1.0, v0 + v_mov_b32_e32 v0, 0x80000000 + v_cmpx_nlg_f32_e32 0, v0 + v_mov_b32_e32 v0, 0x7fc00000 + v_cmpx_nlg_f32_e32 1.0, v0 + v_mov_b32_e32 v0, 0x7e00 + v_mov_b32_e32 v2, 0x3c00 + v_cmpx_nlg_f16_e32 v0, v2 + v_mov_b32_e32 v13, 1.0 + exp mrt0 v10, v11, v12, v13 done vm + s_endpgm diff --git a/tests/semantic/fixtures/disasm/ps_cvt_off.s b/tests/semantic/fixtures/disasm/ps_cvt_off.s new file mode 100644 index 000000000..8f95909d7 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_cvt_off.s @@ -0,0 +1,11 @@ +; ps_cvt_off test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_cvt_off.asm + v_mov_b32_e32 v0, 0x12345678 + v_cvt_off_f32_i4_e32 v2, v0 + v_mov_b32_e32 v0, 7 + v_cvt_off_f32_i4_e32 v3, v0 + v_mov_b32_e32 v0, 15 + v_cvt_off_f32_i4_e64 v4, v0 mul:4 + v_mov_b32_e32 v0, 7 + v_cvt_off_f32_i4_e64 v5, v0 clamp mul:4 + exp mrt0 v2, v3, v4, v5 done vm + s_endpgm diff --git a/tests/semantic/fixtures/disasm/ps_fmac_f16_mods.s b/tests/semantic/fixtures/disasm/ps_fmac_f16_mods.s new file mode 100644 index 000000000..6c72254f7 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_fmac_f16_mods.s @@ -0,0 +1,11 @@ +; ps_fmac_f16_mods test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_fmac_f16_mods.asm + v_mov_b32_e32 v2, 0xaaaa3c00 + v_fmac_f16_e64 v2, 1.0, 1.0 clamp + v_mov_b32_e32 v3, 0xaaaa3800 + v_fmac_f16_e64 v3, 0.5, 0.5 mul:2 + v_mov_b32_e32 v4, 0xaaaabc00 + v_fmac_f16_e64 v4, 0.5, 0.5 clamp + v_mov_b32_e32 v5, 0xaaaa4000 + v_fmac_f16_e64 v5, 1.0, 2.0 div:2 + exp mrt0 v2, v3, v4, v5 done vm + s_endpgm diff --git a/tests/semantic/fixtures/disasm/ps_interp_f32_mods.s b/tests/semantic/fixtures/disasm/ps_interp_f32_mods.s new file mode 100644 index 000000000..456922470 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_interp_f32_mods.s @@ -0,0 +1,11 @@ +; ps_interp_f32_mods test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_interp_f32_mods.asm + v_interp_p1_f32_e32 v2, v0, attr0.x + v_interp_p2_f32_e64 v2, v1, attr0.x clamp + v_interp_p1_f32_e32 v3, v0, attr0.y + v_interp_p2_f32_e64 v3, v1, attr0.y clamp + v_interp_p1_f32_e32 v4, v0, attr0.z + v_interp_p2_f32_e64 v4, v1, attr0.z mul:2 + v_interp_p1_f32_e32 v5, v0, attr0.w + v_interp_p2_f32_e64 v5, v1, attr0.w clamp mul:2 + exp mrt0 v2, v3, v4, v5 done vm + s_endpgm diff --git a/tests/semantic/fixtures/disasm/ps_interp_mov_mods.s b/tests/semantic/fixtures/disasm/ps_interp_mov_mods.s new file mode 100644 index 000000000..907c12ffc --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_interp_mov_mods.s @@ -0,0 +1,9 @@ +; ps_interp_mov_mods test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_interp_mov_mods.asm + v_interp_p1_f32_e32 v2, v0, attr2.x + v_interp_p2_f32_e64 v2, v1, attr2.x mul:4 + v_interp_p1_f32_e32 v3, v0, attr2.y + v_interp_p2_f32_e64 v3, v1, attr2.y div:2 + v_interp_mov_f32_e64 v4, p0, attr1.w div:2 + v_interp_mov_f32_e64 v5, p0, attr1.x clamp div:2 + exp mrt0 v2, v3, v4, v5 done vm + s_endpgm diff --git a/tests/semantic/fixtures/disasm/ps_vop3_const_mods.s b/tests/semantic/fixtures/disasm/ps_vop3_const_mods.s new file mode 100644 index 000000000..439dd12f9 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_vop3_const_mods.s @@ -0,0 +1,8 @@ +; ps_vop3_const_mods test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_vop3_const_mods.asm + v_add_f32_e64 v2, 0, -|-2.0| + v_add_f32_e64 v3, 0, neg(0x3f800000) + v_add_f32_e64 v4, 0, |0xbf800000| + v_mov_b32_e32 v5, 0xaaaa1234 + v_add_f16_e64 v5, 0, -|0x3c00| + exp mrt0 v2, v3, v4, v5 done vm + s_endpgm diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index 27d9298b5..f2b6439b6 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py @@ -24,7 +24,9 @@ SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_bu "cs_w64x_load_ballot_load", "cs_w64x_partial", "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp", "cs_wavemask", "cs_cvt_f32_sat", "ps_scc_minmax", "ps_fma_literal", "ps_f16_vop2", "ps_f32_mods", "ps_f64_mods", "ps_sff_imm", "cs_w32_lds_u8_d16", "cs_w32_lane_wrap", "ps_bary", - "cs_oob_select", "cs_oob_tail") + "cs_oob_select", "cs_oob_tail", + # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only + "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods") def render(name): diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 54bc6e16a..c4520e814 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -927,12 +927,16 @@ def _invocation(text, inputs, push_constants, memory, step=False): # Two's complement: the most negative value is its own absolute value (as on the hardware). values[res] = abs(_s32(args[0])) & MASK elif name in ("FMax", "FClamp"): - if any(math.isnan(v) for v in args) or (name == "FClamp" and args[1] > args[2]): - raise UnsupportedConstruct(f"GLSL.std.450 {name} with these operands (undefined)") - # Equal zeros: -0 is ordered below +0, as in NMin/NMax above (the order RDNA2 hardware uses, so a - # med3 built from these ops is the hardware's median for signed zeros too). - v = _nmin_nmax("NMax", args[0], args[1]) - values[res] = f32(v if name == "FMax" else _nmin_nmax("NMin", v, args[2])) + def fmax_clamp(*xs): + if any(math.isnan(v) for v in xs) or (name == "FClamp" and xs[1] > xs[2]): + raise UnsupportedConstruct(f"GLSL.std.450 {name} with these operands (undefined)") + # Equal zeros: -0 is ordered below +0, as in NMin/NMax above (the order RDNA2 hardware uses, + # so a med3 built from these ops is the hardware's median for signed zeros too). + v = _nmin_nmax("NMax", xs[0], xs[1]) + return f32(v if name == "FMax" else _nmin_nmax("NMin", v, xs[2])) + # Vector operands (v_pk_* clamp) are component-wise. + values[res] = (tuple(fmax_clamp(*c) for c in zip(*args)) if isinstance(args[0], tuple) + else fmax_clamp(*args)) elif name in ("RoundEven", "Floor", "Ceil", "Trunc"): # round() breaks ties to even. An integral result keeps the operand's sign (IEEE 754 # roundToIntegral), so RoundEven(-0.4), Ceil(-0.5) and Trunc(-0.5) are -0.0, not +0.0. diff --git a/tests/semantic/test_bary_fallback.py b/tests/semantic/test_bary_fallback.py index 178443d4b..0a0c4aada 100644 --- a/tests/semantic/test_bary_fallback.py +++ b/tests/semantic/test_bary_fallback.py @@ -12,6 +12,8 @@ run_gpu_tests.py / check.py with LEONIDA_BARY_FALLBACK=1 check ps_bary through t * the GS text has the vertex count, the one-hot weights and the locations the PS expects, and refuses a collision. """ import gc +import json +from pathlib import Path import os import re import shutil @@ -142,6 +144,53 @@ class BaryFallbackGeometryShader(unittest.TestCase): self.assertIn("%bary1 = OpConstantComposite %v3float %f0 %f1 %f0", text) self.assertIn("%bary2 = OpConstantComposite %v3float %f0 %f0 %f1", text) + def test_pair_forwards_the_producers_clip_array_for_each_vertex(self): + index = {"vs_clip": {"stage": "vs", "capabilities": ["ClipDistance"], "clip_distance_count": 2}, + "ps_bary": {"stage": "ps", "inputs": [1], "bary_fallback_input": {"location": 0}}} + with tempfile.TemporaryDirectory() as tmp: + index_file = Path(tmp, "index.json") + index_file.write_text(json.dumps(index), encoding="utf-8") + ordinary, = bary_fallback_gs.write_for_index(tmp) + paired, = bary_fallback_gs.write_for_index(tmp, pair=("vs_clip", "ps_bary")) + self.assertNotEqual(ordinary, paired) + self.assertNotIn("BuiltIn ClipDistance", Path(ordinary).read_text()) + asm = Path(paired).read_text() + self.assertIn("%clip_count = OpConstant %uint 2", asm) + self.assertEqual(asm.count("BuiltIn ClipDistance"), 2) + for vertex, emission in enumerate(asm.split("OpEmitVertex")[:-1]): + self.assertIn(f"OpAccessChain %ptr_in_clip %in_clip %int_{vertex}", emission) + self.assertIn(f"OpStore %out_clip %distances{vertex}", emission) + del index["vs_clip"]["clip_distance_count"] + index_file.write_text(json.dumps(index), encoding="utf-8") + with self.assertRaisesRegex(ValueError, "regenerate"): + bary_fallback_gs.write_for_index(tmp, pair=("vs_clip", "ps_bary")) + + def test_pair_forwards_cull_distances_and_checks_the_layout(self): + vs = {"stage": "vs", "capabilities": ["CullDistance"], "cull_distance_count": 2} + index = {"vs": vs, "ps": {"stage": "ps", "bary_fallback_input": {"location": 0}}} + with tempfile.TemporaryDirectory() as tmp: + index_file = Path(tmp, "index.json") + index_file.write_text(json.dumps(index), encoding="utf-8") + path, = bary_fallback_gs.write_for_index(tmp, pair=("vs", "ps")) + self.assertEqual(Path(path).name, "ps.bary_gs.cull2.spvasm") + asm = Path(path).read_text() + self.assertEqual(asm.count("BuiltIn CullDistance"), 2) + self.assertNotIn("ClipDistance", asm) + self.assertIn("%cull_count = OpConstant %uint 2", asm) + for vertex, emission in enumerate(asm.split("OpEmitVertex")[:-1]): + self.assertIn(f"OpAccessChain %ptr_in_cull %in_cull %int_{vertex}", emission) + self.assertIn(f"OpLoad %cull %cull_ptr{vertex}", emission) + self.assertIn(f"OpStore %out_cull %distances{vertex}", emission) + del vs["cull_distance_count"] + index_file.write_text(json.dumps(index), encoding="utf-8") + with self.assertRaisesRegex(ValueError, "cull_distance_count"): + bary_fallback_gs.write_for_index(tmp, pair=("vs", "ps")) + vs.update(capabilities=["ClipDistance", "CullDistance"], clip_distance_count=1, cull_distance_count=1) + index_file.write_text(json.dumps(index), encoding="utf-8") + with self.assertRaisesRegex(ValueError, "mixed"): + bary_fallback_gs.write_for_index(tmp, pair=("vs", "ps")) + self.assertEqual(list(Path(tmp).glob("*.spvasm")), [Path(path)]) + def test_collision_is_refused(self): with self.assertRaises(ValueError): bary_fallback_gs.gs_spvasm([0, 1], 1) @@ -152,7 +201,6 @@ class BaryFallbackGeometryShader(unittest.TestCase): "ps_b": {"stage": "ps", "inputs": [0]}, "cs_c": {"stage": "cs"}} with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as f: - import json json.dump(index, f) written = bary_fallback_gs.write_for_index(tmp) self.assertEqual([os.path.basename(p) for p in written], ["ps_a.bary_gs.spvasm"]) @@ -165,13 +213,14 @@ class BaryFallbackGeometryShader(unittest.TestCase): def test_assembles_and_validates(self): with tempfile.TemporaryDirectory() as tmp: asm = os.path.join(tmp, "gs.spvasm") - with open(asm, "w", encoding="utf-8", newline="\n") as f: - f.write(bary_fallback_gs.gs_spvasm([0, 1, 5], 6)) - spv = os.path.join(tmp, "gs.spv") - for cmd in (["spirv-as", "--target-env", "vulkan1.2", asm, "-o", spv], - ["spirv-val", "--target-env", "vulkan1.2", spv]): - r = subprocess.run(cmd, capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + for clip, cull in ((0, 0), (1, 0), (2, 0), (3, 0), (8, 0), (0, 1), (0, 2), (0, 8)): + with open(asm, "w", encoding="utf-8", newline="\n") as f: + f.write(bary_fallback_gs.gs_spvasm([0, 1, 5], 6, clip, cull)) + spv = os.path.join(tmp, "gs.spv") + for cmd in (["spirv-as", "--target-env", "vulkan1.2", asm, "-o", spv], + ["spirv-val", "--target-env", "vulkan1.2", spv]): + r = subprocess.run(cmd, capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) if __name__ == "__main__": diff --git a/tests/semantic/test_buffer_load_format.py b/tests/semantic/test_buffer_load_format.py index aa72d581b..7a1499b8e 100644 --- a/tests/semantic/test_buffer_load_format.py +++ b/tests/semantic/test_buffer_load_format.py @@ -69,6 +69,7 @@ def load_format(fmt: int, offset: int, ncomp: int = 4, dst_sel: int = DST_SEL_XY nregs = (ncomp + 1) // 2 if d16 else ncomp vdata = "v2" if nregs == 1 else f"v[2:{1 + nregs}]" regs = [f"v{2 + min(i, nregs - 1)}" for i in range(4)] + seed = "\tv_mov_b32 v2, 0x12345678\n\tv_mov_b32 v3, 0xa9bcdef0\n" if d16 else "" asm = ( "; test_buffer_load_format\n" f"\ts_mov_b32 s0, {BASE:#x}\n" @@ -76,6 +77,7 @@ def load_format(fmt: int, offset: int, ncomp: int = 4, dst_sel: int = DST_SEL_XY "\ts_mov_b32 s2, 0x100\n" # num_records (bytes) f"\ts_mov_b32 s3, {fmt << 12 | dst_sel | 0x30000000:#x}\n" f"\tv_mov_b32 v1, {offset:#x}\n" + f"{seed}" f"\t{op}_{suffix} {vdata}, v1, s[0:3], 0{mods} offen\n" "\ts_waitcnt vmcnt(0)\n" f"\texp mrt0 {', '.join(regs)} done vm\n" @@ -122,6 +124,19 @@ class SubDwordElements(unittest.TestCase): self.assertEqual(load_format(FMT_F16, off, 1)[0], f16_word(half)) +class D16DestinationHalves(unittest.TestCase): + def test_odd_and_even_component_writes(self): + # Little-endian UINT8 components at byte 0 are 44,33,22,11 (hex). + for offset, words in ( + (0, ((0x12340044,), (0x00330044,), (0x00330044, 0xA9BC0022), (0x00330044, 0x00110022))), + (0x100, ((0x12340000,), (0,), (0, 0xA9BC0000), (0, 0))), + ): + for ncomp, want in enumerate(words, 1): + with self.subTest(offset=offset, ncomp=ncomp): + got = load_format(FMT_UINT8X4, offset, ncomp, d16=True) + self.assertEqual(got[:len(want)], want) + + class D16NormalizedRounding(unittest.TestCase): """d16 narrows a normalized value to f16 with round to nearest even, like the d16 image results (#489; inferred for the hardware, not measured). These bytes are among the about half of unorm8 values where round toward zero, @@ -129,7 +144,7 @@ class D16NormalizedRounding(unittest.TestCase): def test_unorm8_x(self): # byte 5 is 0xbe: 190/255 is 0x39f6 to nearest even, 0x39f5 toward zero - self.assertEqual(load_format(FMT_UNORM8, 5, 1, d16=True)[0] & 0xFFFF, 0x39F6) + self.assertEqual(load_format(FMT_UNORM8, 5, 1, d16=True)[0], 0x123439F6) def test_unorm8x4_xyzw(self): # bytes 4..7 are 0xef, 0xbe, 0xad, 0xde: 0x3b7f, 0x39f6, 0x396d, 0x3af7 (0x39f5 and 0x3af6 toward zero) @@ -231,6 +246,20 @@ class TbufferDefaultFormat(unittest.TestCase): self.assertEqual(got[0], 0x3F800000) self.assertEqual(got, self.tload(0, ncomp, self.EXPLICIT)[:ncomp]) + def test_packed_load_uses_instruction_format(self): + # The V# declares one u32. The instruction specifies four u8s at byte 4: EF BE AD DE. + expected = ((0x123400EF,), (0x00BE00EF,), (0x00BE00EF, 0xA9BC00AD), (0x00BE00EF, 0x00DE00AD)) + for ncomp, want in enumerate(expected, 1): + with self.subTest(ncomp=ncomp): + got = load_format(FMT_U32, 4, ncomp, d16=True, op="tbuffer_load_format", + mods=" format:[BUF_FMT_8_8_8_8_UINT]") + self.assertEqual(got[:len(want)], want) + + def test_packed_default_8_unorm(self): + # The first byte is 0xff: 1.0 in f16 is 0x3c00. Preserve the upper destination half. + got = load_format(FMT_U32, 0, 1, memory=self.MEM, d16=True, op="tbuffer_load_format") + self.assertEqual(got[0], 0x12343C00) + def test_explicit_invalid_still_rejected(self): with self.assertRaises(rdna2spirv.Unsupported): self.tload(0, 1, " format:[BUF_FMT_INVALID]") diff --git a/tests/semantic/test_interp_guards.py b/tests/semantic/test_interp_guards.py new file mode 100644 index 000000000..711512d2c --- /dev/null +++ b/tests/semantic/test_interp_guards.py @@ -0,0 +1,202 @@ +"""SHADER-177: v_interp reads the barycentric pair through its VGPR source (I = v0, J = v1), and +v_interp_mov_f32 names the vertex with p0 (p10/p20 would be the other two vertices). The single-lane +model returns the attribute's own value, which is only that when the operand really holds the pair, +so anything else is refused instead of silently translating wrong (docs/design.md, PS system inputs): + +* v_interp_p1/p2 (f32 and f16 forms) must read their OWN coordinate of the pair — p1 reads I = v0, + p2 reads J = v1, per op — as the hardware register or a qualifying copy: anything else, including a + swapped p1(v1)/p2(v0) pair or both-v0, -> Unsupported naming the register and the role (the corpus + has none: 117,001 v0 and 116,997 v1 over 26,503 shaders); +* v_interp_mov_f32 with p10/p20 -> Unsupported naming the select (all 6,926 in the corpus are p0); +* a plain v_mov_b32 copy of the op's coordinate (rooted at v0 for p1, at v1 for p2) is still accepted, + including a chain of copies: its single write in the whole shader is the mov, and its source v0/v1 + is itself unwritten up to the copy (a copy of an already-overwritten v0/v1 carries a computed value — + the zero-before-copy measurement renders (0,0) on hardware — while zeroing after the copy is fine, + the copy saved the value). One corpus shader reads its J through a copy of v1 and must keep + translating (bit-identical .spv); +* a register written twice (the mov, then anything else) no longer qualifies; +* the standard forms (v0/v1 pairs, p0 mov) translate and compute exactly as before. + +On main (before the guards) the refused cases translated silently and passed spirv-val: the operand +was ignored outright, so a second-pair I/J produced the very module of the standard pair. +""" +import struct +import unittest + +import support +import rdna2spirv + +ATTR0 = (0.5, 0.25, 0.0, 1.0) +FLAT_ATTR1_X = 0x101 # attr1.x read through v_interp_mov only: the provoking vertex's word + + +def f32_bits(x): + return struct.unpack(" (u, v). + lines = ["v_mov_b32_e32 v6, v0", "v_mov_b32_e32 v7, v6", "v_mov_b32_e32 v8, v1", + "v_interp_p1_f32_e32 v2, v7, attr0.x", + "v_interp_p2_f32_e32 v2, v8, attr0.x", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm"] + spv = support.translate_lines("ps_rolk", lines) + words = support.mrt0_words(spv, inputs={"%in_attr0": ATTR0}) + self.assertEqual(words, [f32_bits(ATTR0[0])] * 4) + + def test_copy_saves_pair_from_later_zero(self): + # Vonsek measurement row 2: copy v0/v1 out first, then zero them, read through the copies + # -> (u, v): the copy saved the value, a write to the source after the copy does not + # disqualify it. + lines = ["v_mov_b32_e32 v6, v0", "v_mov_b32_e32 v7, v1", + "v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", + "v_interp_p1_f32_e32 v2, v6, attr0.x", + "v_interp_p2_f32_e32 v2, v7, attr0.x", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm"] + spv = support.translate_lines("ps_rols", lines) + words = support.mrt0_words(spv, inputs={"%in_attr0": ATTR0}) + self.assertEqual(words, [f32_bits(ATTR0[0])] * 4) + + def test_copy_of_overwritten_source_refused(self): + # Vonsek measurement row 3: zeroing v0/v1 BEFORE the copy means the copy carries the + # computed (0) value, not the barycentric pair — hardware renders (0,0) — so the copy no + # longer qualifies. (The corpus's one copy PS copies v1 while it is still unwritten, then + # overwrites it: the saved-copy case above, which keeps translating.) + with self.assertRaises(rdna2spirv.Unsupported) as cm: + support.translate_lines("ps_rolz", ["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", + "v_mov_b32_e32 v6, v0", "v_mov_b32_e32 v7, v1", + "v_interp_p1_f32_e32 v2, v6, attr0.x", + "v_interp_p2_f32_e32 v2, v7, attr0.x", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm"]) + self.assertIn("v_interp_p1_f32 I source v6", str(cm.exception)) + + def test_standard_pairs_and_p0_mov_unchanged(self): + spv = support.translate_lines("ps_std", ["v_interp_p1_f32_e32 v2, v0, attr0.x", + "v_interp_p2_f32_e32 v2, v1, attr0.x", + "v_interp_mov_f32_e32 v3, p0, attr1.x", + "exp mrt0 v2, v3, v3, v3 done vm", + "s_endpgm"]) + words = support.mrt0_words(spv, inputs={"%in_attr0": ATTR0, "%in_attr1": (FLAT_ATTR1_X,) * 4}) + self.assertEqual(words, [f32_bits(ATTR0[0]), FLAT_ATTR1_X, FLAT_ATTR1_X, FLAT_ATTR1_X]) + self.assertIn("OpDecorate %in_attr1 Flat", spv) # mov-only input stays Flat + self.assertNotIn("OpDecorate %in_attr0 Flat", spv) + + def test_f16_standard_forms_still_translate(self): + spv = support.translate_lines("ps_f16", ["v_interp_p1ll_f16 v4, v0, attr1.x", + "v_interp_p2_f16 v4, v1, attr1.x, v4", + "exp mrt0 v4, v4, v4, v4 done vm", + "s_endpgm"]) + self.assertIn("OpEntryPoint Fragment", spv) + + def test_guard_uses_the_copy_analysis(self): + # Mutation check: with interp_copy_sources returning nothing, the copy case must refuse, so + # the acceptance above really flows through the tracking and not through a vacuous guard. + lines = ["v_mov_b32_e32 v6, v1", + "v_interp_p1_f32_e32 v2, v0, attr0.x", + "v_interp_p2_f32_e32 v2, v6, attr0.x", + "exp mrt0 v2, v2, v2, v2 done vm", + "s_endpgm"] + self.assertIn("OpEntryPoint Fragment", support.translate_lines("ps_vc", lines)) + orig = rdna2spirv.interp_copy_sources + rdna2spirv.interp_copy_sources = lambda insns: {} + try: + with self.assertRaises(rdna2spirv.Unsupported): + support.translate_lines("ps_vc", lines) + finally: + rdna2spirv.interp_copy_sources = orig + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_mutations.py b/tests/semantic/test_mutations.py index 0fb6a5e48..c2bb74322 100644 --- a/tests/semantic/test_mutations.py +++ b/tests/semantic/test_mutations.py @@ -63,21 +63,9 @@ MUTATIONS = [ 'self.emit(f"{amt} = OpBitFieldUExtract %uint {sh_src} {self.cu(16 * sl[0])} {self.cu(4)}")', 'self.emit(f"{amt} = OpBitFieldUExtract %uint {sh_src} {self.cu(0)} {self.cu(4)}")', "test_ps_ops4"), - ("v_sin_f16 omits turns-to-radians 2*pi factor", TRANSLATOR, - ' elif op in ("v_sin_f16", "v_cos_f16"):\n' - ' u = self.src_h(a[1])\n' - ' v2, f, t, r, w2, pk, lo = (self.tmp() for _ in range(7))\n' - ' self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}")\n' - ' self.emit(f"{f} = OpCompositeExtract %float {v2} 0")\n' - ' f = self.modify_f(f, a[1])\n' - ' self.emit(f"{t} = OpFMul %float {f} {self.fconst(6.283185307179586)}")', - ' elif op in ("v_sin_f16", "v_cos_f16"):\n' - ' u = self.src_h(a[1])\n' - ' v2, f, t, r, w2, pk, lo = (self.tmp() for _ in range(7))\n' - ' self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}")\n' - ' self.emit(f"{f} = OpCompositeExtract %float {v2} 0")\n' - ' f = self.modify_f(f, a[1])\n' - ' self.emit(f"{t} = OpFMul %float {f} {self.fconst(1.0)}")', + ("v_sin/v_cos omits turns-to-radians 2*pi factor", TRANSLATOR, + 'self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}")', + 'self.emit(f"{arg} = OpFMul %float {t} {self.fconst(1.0)}")', "test_ps_ops4"), ("v_mul_legacy_f32 drops zero-times-anything guard", TRANSLATOR, ' elif op == "v_mul_legacy_f32":\n' diff --git a/tests/semantic/test_pk_f16_clamp.py b/tests/semantic/test_pk_f16_clamp.py new file mode 100644 index 000000000..deaf56bf1 --- /dev/null +++ b/tests/semantic/test_pk_f16_clamp.py @@ -0,0 +1,95 @@ +"""Semantic tests for the clamp bit on packed f16 VOP3P ops (v_pk_add/mul/fma/max/min_f16 ... clamp). + +With clamp, each f16 half of the result is clamped to [0.0, 1.0] (RDNA2 ISA, VOP3P CLMP), the same as the scalar +f16 ops. The translator clamps the vec2 with GLSL FClamp; the semantic interpreter used to take FClamp/FMax on +scalars only and failed with a TypeError on any packed clamp. Both halves leave through exp with a zero high half. +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +sys.path.insert(0, TOOLS_DIR) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 23) & 0xFF + with self.subTest(name=name, word=f"{w:#010x}"): + self.assertTrue(w & 0x7FFFFFFF == 0 or 0 < exp < 0xFF) + + def test_interp_fixtures_are_drawn_with_the_constant_vertex_shader(self): + params = vertex_params(INTERP_VERTEX) + self.assertEqual(params[0], (1.5, -0.25, 0.375, 0.625)) + self.assertEqual(params[1], (1.5, -0.5, 0.25, 4.0)) + self.assertEqual(params[2], (0.25, 3.0, 0.0, 0.0)) + for name in ("ps_interp_f32_mods", "ps_interp_mov_mods"): + self.assertEqual(check.PIXEL_VERTEX[name], INTERP_VERTEX) + self.assertIn(f"vk_harness {INTERP_VERTEX}.spv {name}.spv", read(name)) + + def test_attr1_is_flat_and_the_others_interpolate(self): + # attr1 is read only with v_interp_mov, so the translator declares it Flat; attr2 goes through p1/p2. + spv = support.translate_fixture("ps_interp_mov_mods") + self.assertIn("OpDecorate %in_attr1 Flat", spv) + self.assertNotIn("OpDecorate %in_attr2 Flat", spv) + self.assertNotIn("PerVertexKHR", spv) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_valu_sin_cos_turns.py b/tests/semantic/test_valu_sin_cos_turns.py new file mode 100644 index 000000000..5c4aad398 --- /dev/null +++ b/tests/semantic/test_valu_sin_cos_turns.py @@ -0,0 +1,71 @@ +"""v_sin_f32/v_cos_f32: range reduction in turns, not after scaling by 2*pi. + +The hardware takes the operand in turns and reduces to [0, 1) before evaluating. Scaling first loses bits for large +inputs and leaves Sin outside [-pi, pi], where Vulkan's precision is not guaranteed. The old translation is up to +1e-4 off near 255 turns; reducing first is within an f32 ulp of the double result. +""" +import math +import struct +import unittest + +import support + + +def _bits(x): + return struct.unpack(" int: + return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) + + +def f16_half(word: int, hi: int) -> float: + bits = (word >> 16) & 0xFFFF if hi else (word & 0xFFFF) + return struct.unpack(" int: + return (word >> 16) & 0xFFFF if hi else (word & 0xFFFF) + + +def i16_half(word: int, hi: int) -> int: + v = u16_half(word, hi) + return v - 0x10000 if v & 0x8000 else v + + +def f16_rel(cond: str, x: float, y: float) -> int: + nan = math.isnan(x) or math.isnan(y) + if cond == "o": + return int(not nan) + if cond == "u": + return int(nan) + if cond == "lt": + return int(x < y) + if cond == "le": + return int(x <= y) + if cond == "gt": + return int(x > y) + if cond == "ge": + return int(x >= y) + if cond == "eq": + return int(x == y) + if cond == "lg": + return int((not nan) and x != y) + if cond == "neq": + return int(nan or x != y) + raise ValueError(cond) + + +def int_rel(cond: str, x: int, y: int) -> int: + return int({ + "eq": x == y, + "ne": x != y, + "lg": x != y, + "lt": x < y, + "le": x <= y, + "gt": x > y, + "ge": x >= y, + }[cond]) + + +_TMP_DIR = None +_PS_PATH = None + + +def setUpModule(): + global _TMP_DIR, _PS_PATH + _TMP_DIR = tempfile.TemporaryDirectory() + dis = os.path.join(_TMP_DIR.name, "disasm") + os.mkdir(dis) + _PS_PATH = os.path.join(dis, "ps_vcmp16_opsel.s") + with open(os.path.join(_TMP_DIR.name, "ps_vcmp16_opsel.dxbc"), "wb") as f: + f.write(STUB_DXBC) + + +def tearDownModule(): + global _TMP_DIR + if _TMP_DIR is not None: + _TMP_DIR.cleanup() + _TMP_DIR = None + + +def translate_ps(lines): + if _TMP_DIR is None: + setUpModule() + asm = "; ps_vcmp16_opsel\n" + "".join(f"\t{ln}\n" for ln in lines) + with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + return rdna2spirv.translate(_PS_PATH) + + +def run_ps_bit(x_word: int, y_word: int, cmp_line: str, mask: str = "s4") -> int: + lines = [ + f"v_mov_b32 v1, {x_word:#x}", + f"v_mov_b32 v2, {y_word:#x}", + cmp_line, + f"v_cndmask_b32_e64 v0, 0x40000000, 0x40000001, {mask}", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", + ] + w = mrt0_words(translate_ps(lines))[0] + assert (w >> 1) == 0x20000000, hex(w) + return w & 1 + + +def run_cs(name: str, body_lines, wave_size: int): + """Translate a synthetic compute shader and run all lanes in spirv_mini_interp.run_workgroup.""" + with tempfile.TemporaryDirectory() as tmp: + os.mkdir(os.path.join(tmp, "disasm")) + os.mkdir(os.path.join(tmp, "fssm")) + s_path = os.path.join(tmp, "disasm", name + ".s") + with open(s_path, "w", encoding="utf-8", newline="") as f: + f.write(f"; {name}\n") + for ln in body_lines: + f.write(f"\t{ln}\n") + f.write("\ts_endpgm\n") + with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: + f.write(STUB_DXBC) + # COMPUTE_PGM_RSRC2: 0x8088 -> 4 user SGPRs (s[0:3] = output V#), TGID_X. + with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: + f.write(bytes(0x138) + struct.pack("<4I", 0x8088, wave_size, 1, 1)) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(s_path) + gc.collect() + assert rdna2spirv.translate.last_gen.wave64 == (wave_size == 64) + pc = VSHARP + [0] * 28 + return si.run_workgroup( + spv, wave_size, wave_size, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=pc, memory={}, + ) + + +class F16CompareOpSelTests(unittest.TestCase): + def test_f16_opsel_relations(self): + # Packed pairs chosen so each (s0, s1) combination tests distinct ordering & equality cases: + # Pair A: v1=(1.0, 4.0), v2=(2.0, 1.0) -> (lo,lo): 1<2; (hi,lo): 4>2; (lo,hi): 1==1; (hi,hi): 4>1 + # Pair B: v1=(3.0, 2.0), v2=(2.0, 2.0) -> (lo,lo): 3>2; (hi,lo): 2==2; (lo,hi): 3>2; (hi,hi): 2==2 + # Pair C: v1=(-2.0, 0.5), v2=(0.5, -1.0) -> signed negatives in both halves + pairs = [ + (pack16(H_ONE, H_FOUR), pack16(H_TWO, H_ONE)), + (pack16(H_THREE, H_TWO), pack16(H_TWO, H_TWO)), + (pack16(H_MTWO, H_HALF), pack16(H_HALF, H_MONE)), + ] + for cond in ("lt", "le", "gt", "ge", "eq", "lg", "neq"): + for xw, yw in pairs: + for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): + want = f16_rel(cond, f16_half(xw, s0), f16_half(yw, s1)) + with self.subTest(cond=cond, x=hex(xw), y=hex(yw), opsel=(s0, s1)): + got = run_ps_bit( + xw, yw, + f"v_cmp_{cond}_f16_e64 s4, v1, v2 op_sel:[{s0},{s1}]", + mask="s4", + ) + self.assertEqual(got, want) + + def test_f16_opsel_ordered_unordered_nan(self): + # NaN in high half of v1, finite in low half; NaN in low half of v2, finite in high half: + # (0,0): finite vs NaN -> unordered; (1,0): NaN vs NaN -> unordered; + # (0,1): finite vs finite -> ordered; (1,1): NaN vs finite -> unordered. + xw = pack16(H_ONE, H_QNAN) + yw = pack16(H_QNAN, H_TWO) + # Also test finite-lo/NaN-hi vs finite-lo/finite-hi so [0,0] is ordered and [1,0] is unordered. + cases = [ + (xw, yw), + (pack16(H_ONE, H_QNAN), pack16(H_TWO, H_THREE)), + (pack16(H_QNAN, H_ONE), pack16(H_TWO, H_QNAN)), + ] + for cond in ("o", "u", "lt", "eq", "neq"): + for a, b in cases: + for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): + want = f16_rel(cond, f16_half(a, s0), f16_half(b, s1)) + with self.subTest(cond=cond, a=hex(a), b=hex(b), opsel=(s0, s1)): + got = run_ps_bit( + a, b, + f"v_cmp_{cond}_f16_e64 vcc_lo, v1, v2 op_sel:[{s0},{s1}]", + mask="vcc_lo", + ) + self.assertEqual(got, want) + + def test_f16_opsel_neg_abs_modifiers(self): + # v1 = (lo=+1.0, hi=-4.0), v2 = (lo=+2.0, hi=+4.0) + # Selecting hi of v1 (-4.0): + # -v1 -> +4.0: eq v2.hi (+4.0) is 1, gt v2.lo (+2.0) is 1 + # |v1| -> +4.0: eq v2.hi (+4.0) is 1, lt v2.lo (+2.0) is 0 + # -|v1| -> -4.0: lt v2.lo (+2.0) is 1 + # Reading lo of v1 (+1.0) instead would flip every case below. + xw = pack16(H_ONE, H_MFOUR) + yw = pack16(H_TWO, H_FOUR) + cases = [ + ("v_cmp_eq_f16_e64 s4, -v1, v2 op_sel:[1,1]", 1), + ("v_cmp_gt_f16_e64 s4, -v1, v2 op_sel:[1,0]", 1), + ("v_cmp_eq_f16_e64 s4, |v1|, v2 op_sel:[1,1]", 1), + ("v_cmp_lt_f16_e64 s4, |v1|, v2 op_sel:[1,0]", 0), + ("v_cmp_lt_f16_e64 s4, v1, -v2 op_sel:[0,1]", 0), # +1.0 < -4.0 -> 0 (lo of v2 would give +1.0 < -2.0 -> 0, check gt below) + ("v_cmp_lt_f16_e64 s4, -|v1|, v2 op_sel:[1,0]", 1), # -4.0 < +2.0 -> 1 + ("v_cmp_gt_f16_e64 s4, -|v1|, -v2 op_sel:[1,0]", 0), # -4.0 > -2.0 -> 0 (lo would be -1.0 > -2.0 -> 1!) + ("v_cmp_eq_f16_e64 s4, v1, -v2 op_sel:[1,1]", 1), # -4.0 == -4.0 -> 1 + ] + for line, want in cases: + with self.subTest(line=line): + self.assertEqual(run_ps_bit(xw, yw, line, mask="s4"), want) + + +class Int16CompareOpSelTests(unittest.TestCase): + def test_u16_opsel_all_combos(self): + # Pair 1: v1=(lo=0x0001, hi=0xFFFF), v2=(lo=0x0002, hi=0x0001) + # (0,0): 1 < 2; (1,0): 65535 > 2; (0,1): 1 == 1; (1,1): 65535 > 1 + # Pair 2: v1=(lo=0x8000, hi=0x0005), v2=(lo=0x7FFF, hi=0x0005) + # (0,0): 32768 > 32767; (1,0): 5 < 32767; (0,1): 32768 > 5; (1,1): 5 == 5 + pairs = [ + (pack16(0x0001, 0xFFFF), pack16(0x0002, 0x0001)), + (pack16(0x8000, 0x0005), pack16(0x7FFF, 0x0005)), + ] + for cond in ("eq", "ne", "lg", "lt", "le", "gt", "ge"): + for xw, yw in pairs: + for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): + want = int_rel(cond, u16_half(xw, s0), u16_half(yw, s1)) + with self.subTest(cond=cond, x=hex(xw), y=hex(yw), opsel=(s0, s1)): + got = run_ps_bit( + xw, yw, + f"v_cmp_{cond}_u16_e64 s4, v1, v2 op_sel:[{s0},{s1}]", + mask="s4", + ) + self.assertEqual(got, want) + + def test_i16_opsel_all_combos(self): + # Negative signed i16 in high half vs positive in low half: + # Pair 1: v1=(lo=+1, hi=-1=0xFFFF), v2=(lo=+2, hi=+1) + # (0,0): +1 < +2; (1,0): -1 < +2; (0,1): +1 == +1; (1,1): -1 < +1 (unsigned would say 0xFFFF > 1!) + # Pair 2: v1=(lo=+32767=0x7FFF, hi=-32768=0x8000), v2=(lo=-1=0xFFFF, hi=+0) + # (0,0): +32767 > -1; (1,0): -32768 < -1; (0,1): +32767 > 0; (1,1): -32768 < 0 + # Pair 3: v1=(lo=+5, hi=-2=0xFFFE), v2=(lo=-2=0xFFFE, hi=-2=0xFFFE) + # (0,0): +5 > -2; (1,0): -2 == -2; (0,1): +5 > -2; (1,1): -2 == -2 + pairs = [ + (pack16(0x0001, 0xFFFF), pack16(0x0002, 0x0001)), + (pack16(0x7FFF, 0x8000), pack16(0xFFFF, 0x0000)), + (pack16(0x0005, 0xFFFE), pack16(0xFFFE, 0xFFFE)), + ] + for cond in ("eq", "ne", "lg", "lt", "le", "gt", "ge"): + for xw, yw in pairs: + for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): + want = int_rel(cond, i16_half(xw, s0), i16_half(yw, s1)) + with self.subTest(cond=cond, x=hex(xw), y=hex(yw), opsel=(s0, s1)): + got = run_ps_bit( + xw, yw, + f"v_cmp_{cond}_i16_e64 s4, v1, v2 op_sel:[{s0},{s1}]", + mask="s4", + ) + self.assertEqual(got, want) + + +class CmpxWaveExecOpSelTests(unittest.TestCase): + def test_cmpx_compute_wave32_and_wave64(self): + # For each type (f16, u16, i16) and wave size (32, 64), give even lanes a packed value whose + # high half PASSES the compare (low half FAILS), and odd lanes a packed value whose high half + # FAILS (low half PASSES). v_cmpx_*_e64 with op_sel:[1,0] must keep even lanes active and + # switch off odd lanes, writing lane|0x100 only for even lanes and leaving SENTINEL on odd lanes. + cases = [ + # (tag, cmp_line, even_v1, odd_v1, v2) + ("f16_lt_10", "v_cmpx_lt_f16_e64 v1, v2 op_sel:[1,0]", + pack16(H_FOUR, H_ONE), pack16(H_ONE, H_FOUR), pack16(H_TWO, H_TWO)), + ("f16_gt_01", "v_cmpx_gt_f16_e64 v1, v2 op_sel:[0,1]", + pack16(H_FOUR, H_ONE), pack16(H_ONE, H_FOUR), pack16(H_FOUR, H_TWO)), + ("u16_gt_10", "v_cmpx_gt_u16_e64 v1, v2 op_sel:[1,0]", + pack16(0x0001, 0xFFFF), pack16(0xFFFF, 0x0001), pack16(0x0010, 0x0010)), + ("i16_lt_10", "v_cmpx_lt_i16_e64 v1, v2 op_sel:[1,0]", + pack16(0x0005, 0xFFFF), pack16(0xFFFF, 0x0005), pack16(0x0001, 0x0001)), + ] + for wave in (32, 64): + vcc = "vcc" if wave == 64 else "vcc_lo" + save_exec = "s_mov_b64 s[8:9], exec" if wave == 64 else "s_mov_b32 s8, exec_lo" + for tag, cmp_line, even_v1, odd_v1, v2_word in cases: + with self.subTest(wave=wave, case=tag): + body = [ + save_exec, + # Pre-fill output[lane] = SENTINEL while all lanes are active. + "v_lshlrev_b32_e32 v4, 2, v0", + f"v_mov_b32 v5, {SENTINEL:#x}", + "buffer_store_dword v5, v4, s[0:3], 0 offen", + # v3 = lane & 1; even lanes get even_v1, odd lanes get odd_v1. + "v_and_b32_e32 v3, 1, v0", + f"v_cmp_eq_u32_e64 {vcc}, v3, 0", + f"v_mov_b32 v6, {even_v1:#x}", + f"v_mov_b32 v7, {odd_v1:#x}", + f"v_cndmask_b32_e64 v1, v7, v6, {vcc}", + f"v_mov_b32 v2, {v2_word:#x}", + cmp_line, + # Only lanes that survived v_cmpx execute this store. + "v_or_b32_e32 v5, 0x100, v0", + "buffer_store_dword v5, v4, s[0:3], 0 offen", + ] + mem = run_cs(f"cs_cmpx_{tag}_w{wave}", body, wave_size=wave) + for lane in range(wave): + want = (0x100 | lane) if (lane % 2 == 0) else SENTINEL + self.assertEqual(mem.get(lane * 4), want, f"lane {lane}") + + def test_cmpx_int16_spirv_wave_interp(self): + # Run v_cmpx_*_u16_e64 and v_cmpx_*_i16_e64 with op_sel directly through spirv_wave_interp + # across both wave32 and wave64, verifying lane-exact EXEC kill on pixel export. + cases = [ + # (tag, cmp_line, even_v1, odd_v1, v2) + ("u16_gt_10", "v_cmpx_gt_u16_e64 v1, v2 op_sel:[1,0]", + pack16(0x0001, 0xFFFF), pack16(0xFFFF, 0x0001), pack16(0x0010, 0x0010)), + ("u16_lt_01", "v_cmpx_lt_u16_e64 v1, v2 op_sel:[0,1]", + pack16(0x0002, 0x0100), pack16(0x0100, 0x0002), pack16(0x0001, 0x0050)), + ("i16_lt_10", "v_cmpx_lt_i16_e64 v1, v2 op_sel:[1,0]", + pack16(0x0005, 0xFFFF), pack16(0xFFFF, 0x0005), pack16(0x0001, 0x0001)), + ("i16_gt_01", "v_cmpx_gt_i16_e64 v1, v2 op_sel:[0,1]", + pack16(0x0001, 0xFFFE), pack16(0xFFFE, 0x0001), pack16(0x0005, 0xFFFF)), + ] + for wave in (32, 64): + vcc = "vcc" if wave == 64 else "vcc_lo" + lane_setup = [ + "v_mbcnt_lo_u32_b32 v3, -1, 0", + ] + if wave == 64: + lane_setup.append("v_mbcnt_hi_u32_b32 v3, -1, v3") + for tag, cmp_line, even_v1, odd_v1, v2_word in cases: + with self.subTest(wave=wave, case=tag): + lines = lane_setup + [ + "v_and_b32_e32 v4, 1, v3", + f"v_cmp_eq_u32_e64 {vcc}, v4, 0", + f"v_mov_b32 v6, {even_v1:#x}", + f"v_mov_b32 v7, {odd_v1:#x}", + f"v_cndmask_b32_e64 v1, v7, v6, {vcc}", + f"v_mov_b32 v2, {v2_word:#x}", + cmp_line, + "v_or_b32_e32 v0, 0x40000000, v3", + "exp mrt0 v0, v0, v0, v0 done vm", + "s_endpgm", + ] + spv = translate_ps(lines) + self.assertEqual(rdna2spirv.translate.last_gen.wave64, wave == 64) + outputs = wi.run_wave(spv, wave=wave)["outputs"] + for lane in range(wave): + if lane % 2 == 0: + self.assertIsNotNone(outputs[lane], f"lane {lane} should stay active") + self.assertEqual(outputs[lane]["%out_mrt0"][0], 0x40000000 | lane) + else: + self.assertIsNone(outputs[lane], f"lane {lane} should be killed by v_cmpx") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_workgroup_yz.py b/tests/semantic/test_workgroup_yz.py new file mode 100644 index 000000000..c1cb9f3c7 --- /dev/null +++ b/tests/semantic/test_workgroup_yz.py @@ -0,0 +1,137 @@ +"""Semantic test for compute workgroup IDs Y/Z. + +The contract row "Compute workgroup IDs Y/Z" in docs/design.md is checked only by the GPU +fixture ``runtime/test/shaders/cs_workgroup_yz.asm`` (plus an explicit EXEC set, which hardware +provides). This test runs the same hand-written listing through tools/rdna2spirv.py and +tests/semantic/spirv_mini_interp.py on a 2 x 3 x 4 +dispatch: with COMPUTE_PGM_RSRC2 = 0x308 (4 user SGPRs, TGID_Y and TGID_Z enabled, TGID_X +disabled) the translator must put WorkgroupId.y in s4 and WorkgroupId.z in s5. The listing +clamps Y to 3 and Z to 4, packs the pair into a bin index and increments that bin with a +buffer atomic, so the expected counts come from a plain-Python model of the dispatch. + +No game files, GPU, LLVM or SPIRV-Tools are needed; the listing and FSSM header are synthetic. +""" +import os +import struct +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +sys.path.insert(0, TOOLS_DIR) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16))) if fn == "PackHalf2x16": @@ -208,7 +212,11 @@ def run(spvasm): val[res] = get(args[1]) elif op == "OpBitcast": t, v = types[args[0]][0], get(args[1]) - if t == "Float": + if types[args[0]] == ("Float", "64"): # v2uint (lo, hi) -> double + val[res] = struct.unpack(" v2uint (lo, hi) + val[res] = struct.unpack(" str: + """The cl.exe branch: from the line-starting `} else {` after the CMake test to the end of its here-string.""" + start = re.search(r"^\} else \{", text, re.M).start() + return text[start:text.index('"@', text.index('$body = @"', start))] + + +class FallbackBuildsTheHarnesses(unittest.TestCase): + def setUp(self): + self.body = fallback_body(SCRIPT.read_text(encoding="utf-8")) + self.programs = set(re.findall(r"/Fe:([A-Za-z0-9_]+)\.exe", self.body)) + + def test_the_harnesses_the_gpu_tools_require_are_built(self): + needed = set(run_gpu_tests.REQUIRED_TEST_PROGRAMS) | set(check.TEST_PROGRAMS) | {image_fuzz.HARNESS} + self.assertEqual(needed - self.programs, set(), "missing from build_runtime.ps1's cl.exe fallback") + + def test_every_test_source_it_compiles_exists(self): + sources = re.findall(r'"\$src\\test\\([A-Za-z0-9_]+\.cpp)"', self.body) + self.assertTrue(sources) + for name in sources: + with self.subTest(source=name): + self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_carve_all_paths.py b/tests/test_carve_all_paths.py index 560a8cfc0..55dd95421 100644 --- a/tests/test_carve_all_paths.py +++ b/tests/test_carve_all_paths.py @@ -24,7 +24,12 @@ class CarveAllGamePathTest(unittest.TestCase): for name in ("common", "pack_p1_p1"): (out / name).mkdir(parents=True) (out / name / "index.json").write_text(json.dumps(INDEX), encoding="utf-8") - for arg in ("game", ".\\game", str(game) + "\\"): + args = ["game", ".\\game", str(game) + "\\"] + short_game = ctypes.create_unicode_buffer(32768) + short_path_length = ctypes.windll.kernel32.GetShortPathNameW(str(game), short_game, len(short_game)) + if short_path_length and short_game.value.casefold() != str(game).casefold(): + args.append(short_game.value + "\\") + for arg in args: with self.subTest(game=arg): result = subprocess.run( ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), diff --git a/tests/test_crosslane_fuzz.py b/tests/test_crosslane_fuzz.py index 598a4d1f9..3573f659d 100644 --- a/tests/test_crosslane_fuzz.py +++ b/tests/test_crosslane_fuzz.py @@ -4,12 +4,16 @@ from the RDNA ISA rules in its docstring. No GPU, no llvm-mc, no game files. python -I tests/test_crosslane_fuzz.py """ import argparse +import contextlib +import io import os import random import re import subprocess import sys +import tempfile import unittest +from unittest import mock TOOLS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools") TOOL = os.path.join(TOOLS, "crosslane_fuzz.py") @@ -282,6 +286,77 @@ class HardwareOracle(unittest.TestCase): for st in stats.values(): self.assertEqual((st["mismatch"], st["hyp_only"], st["rejected"]), (0, 0, 0)) +class HarnessErrors(unittest.TestCase): + """A program the GPU harness hangs or crashes on is one reported failure, not the end of the run.""" + + def test_timeout_is_a_harness_error(self): + prog = X.make_program(1, 32, 4) + with tempfile.TemporaryDirectory() as work, \ + mock.patch.object(X.subprocess, "run", side_effect=subprocess.TimeoutExpired(["x"], 60)): + with self.assertRaises(X.HarnessError) as ctx: + X.run_gpu("vk_compute_test", "p.spv", prog, work, False) + self.assertIn("timed out after 60 s", str(ctx.exception)) + + def test_missing_dump_is_a_harness_error_with_the_exit_code(self): + prog = X.make_program(1, 32, 4) + done = subprocess.CompletedProcess(["x"], 3, stdout="", stderr="device lost\n") + with tempfile.TemporaryDirectory() as work, mock.patch.object(X.subprocess, "run", return_value=done): + with self.assertRaises(X.HarnessError) as ctx: + X.run_gpu("vk_compute_test", "p.spv", prog, work, False) + self.assertIn("no dump (exit 3): device lost", str(ctx.exception)) + + def _main(self, run_gpu, argv): + """main() with the assembler, translator and GPU replaced: every program 'translates'.""" + def translate(work, emulate): + spdir = os.path.join(work, "spirv_emu" if emulate else "spirv_nat") + os.makedirs(spdir, exist_ok=True) + for name in names: + open(os.path.join(spdir, name + ".spv"), "wb").close() + return spdir, "" + + names = [] + out = io.StringIO() + with mock.patch.object(X, "assemble", side_effect=lambda mc, p, *a: names.append(p.name)), \ + mock.patch.object(X, "translate", side_effect=translate), \ + mock.patch.object(X, "run_gpu", side_effect=run_gpu), \ + mock.patch.object(sys, "argv", ["crosslane_fuzz.py"] + argv), \ + contextlib.redirect_stdout(out): + code = X.main() + return code, out.getvalue() + + @staticmethod + def _expected_words(prog): + exp, _ = prog.expected() + words = [0] * (prog.group * len(X.OUT_REGS)) + for (tid, j), v in exp.items(): + words[tid * len(X.OUT_REGS) + j] = v + return words + + def test_run_goes_on_after_a_hang_and_exits_2(self): + calls = [] + + def run_gpu(exe, spv, prog, work, emulate): + calls.append(prog.name) + if len(calls) == 2: + raise X.HarnessError("vk_compute_test timed out after 60 s") + return self._expected_words(prog) + + with tempfile.TemporaryDirectory() as keep: + code, out = self._main(run_gpu, ["--programs", "4", "--wave", "32", "--modes", "native", + "--no-maskdata", "--keep", keep]) + kept = os.listdir(keep) + self.assertEqual(len(calls), 4) + self.assertEqual(code, 2) + self.assertIn(f"{calls[1]} [native] harness error: vk_compute_test timed out after 60 s", out) + self.assertIn("programs 4, match 3, mismatch 0, hyp_only 0, rejected 0, harness_errors 1", out) + self.assertEqual(kept, [f"{calls[1]}_native.asm"]) + + def test_clean_run_still_exits_0(self): + code, out = self._main(lambda exe, spv, prog, work, emulate: self._expected_words(prog), + ["--programs", "3", "--wave", "32", "--modes", "native", "--no-maskdata"]) + self.assertEqual(code, 0) + self.assertIn("match 3, mismatch 0, hyp_only 0, rejected 0, harness_errors 0", out) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_ctest_registration.py b/tests/test_ctest_registration.py new file mode 100644 index 000000000..cfaad282f --- /dev/null +++ b/tests/test_ctest_registration.py @@ -0,0 +1,68 @@ +"""Every test executable the runtime builds must be registered with ctest. + +``add_executable(foo_test ...)`` without an ``add_test(... COMMAND foo_test)`` builds +the test but never runs it -- in ``ctest``, in the Windows runtime job or under Wine. +This happened to ``d3d12_indirect_rt_test``; the only intentional exception is +``d3d12_clear_test`` (see the comment next to its target in runtime/CMakeLists.txt). +""" +import os +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +CMAKE = Path(os.environ.get("LEONIDA_RUNTIME_CMAKE", str(ROOT / "runtime" / "CMakeLists.txt"))) +SOURCE = Path(os.environ.get("LEONIDA_RUNTIME_TEST_SOURCE", + str(ROOT / "runtime" / "test" / "d3d12_indirect_rt_test.cpp"))) + +# d3d12_clear_test is deliberately run by hand until #521's tie rounding lands. +NOT_IN_CTEST = {"d3d12_clear_test"} + + +def built_test_executables(text): + return {name for name in re.findall(r"add_executable\(\s*([A-Za-z0-9_]+)", text) + if name.endswith("_test")} + + +def registered_commands(text): + # add_test may span lines, e.g. add_test(NAME x\n COMMAND foo_test ...). + return set(re.findall(r"add_test\([^)]*?\bCOMMAND\s+\"?([A-Za-z0-9_]+)", text, re.S)) + + +class CTestRegistrationTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cmake = CMAKE.read_text(encoding="utf-8") + + def test_all_test_executables_have_an_add_test(self): + missing = built_test_executables(self.cmake) - registered_commands(self.cmake) - NOT_IN_CTEST + self.assertEqual(missing, set(), f"built but never run by ctest: {sorted(missing)}") + + def test_the_exception_is_still_the_only_one(self): + # An allowlist that grows unnoticed is how this bug happens again. + self.assertEqual(NOT_IN_CTEST & built_test_executables(self.cmake), {"d3d12_clear_test"}) + + def test_indirect_rt_skips_with_the_ctest_skip_code(self): + self.assertTrue( + "add_test(NAME d3d12_indirect_rt COMMAND d3d12_indirect_rt_test)" in self.cmake, + "d3d12_indirect_rt_test is built but not registered with ctest", + ) + self.assertTrue( + "set_tests_properties(d3d12_indirect_rt PROPERTIES SKIP_RETURN_CODE 77)" in self.cmake, + "d3d12_indirect_rt must skip with 77 on a machine without a Vulkan GPU", + ) + + lines = SOURCE.read_text(encoding="utf-8").splitlines() + skips = [] + for i, line in enumerate(lines): + if 'std::printf("SKIP:' in line: + window = "\n".join(lines[i:i + 6]) + codes = re.findall(r"return (\d+);", window) + skips.append(int(codes[0]) if codes else None) + # no loader, no ICD, no Vulkan 1.3 GPU -- all three are a ctest SKIP, not a failure. + self.assertEqual(len(skips), 3, f"expected three whole-test SKIP paths, got {len(skips)}") + self.assertEqual(skips, [77, 77, 77], "SKIP paths must return 77 for SKIP_RETURN_CODE 77") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_docs_links.py b/tests/test_docs_links.py new file mode 100644 index 000000000..28547729e --- /dev/null +++ b/tests/test_docs_links.py @@ -0,0 +1,152 @@ +"""Every relative Markdown link and heading anchor in the repository resolves. + + python -I tests/test_docs_links.py + +Reads only tracked Markdown files (`git ls-files '*.md'`, with a directory walk when git is not available); no game +files, no build tools. The checker itself is exercised on a synthetic tree with one good and one broken page, so a +checker that silently accepts everything cannot pass. +""" +import os +import re +import subprocess +import tempfile +import unittest +from urllib.parse import unquote + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +FENCE = re.compile(r"```.*?```", re.S) +LINK = re.compile(r"!?\[[^\]]*\]\((?:<([^>]+)>|([^)\s]+))(?:\s+\"[^\"]*\")?\)") +HTML = re.compile(r'(?:href|src)\s*=\s*"([^"]+)"') +HEADING = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$", re.M) +EXTERNAL = ("http://", "https://", "mailto:", "tel:", "data:") + + +def strip_fences(text): + """Drop fenced code blocks: headings and links inside them are not rendered.""" + return FENCE.sub("", text) + + +def slug(heading): + """GitHub's heading anchor: lower case, punctuation dropped, spaces become hyphens.""" + text = heading.strip().lower().replace("`", "") + text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE) + return text.replace(" ", "-") + + +def anchors(path): + """Every anchor a heading on the page generates, including the -N suffix of a duplicate.""" + seen = {} + found = set() + with open(path, encoding="utf-8", errors="replace") as f: + text = strip_fences(f.read()) + for match in HEADING.finditer(text): + base = slug(match.group(2)) + count = seen.get(base, 0) + seen[base] = count + 1 + found.add(base if count == 0 else f"{base}-{count}") + return found + + +def links(text): + """Markdown link/image targets and HTML href/src values, fenced code excluded.""" + text = strip_fences(text) + found = [m.group(1) or m.group(2) for m in LINK.finditer(text)] + found.extend(HTML.findall(text)) + return found + + +def markdown_files(root): + result = subprocess.run(["git", "ls-files", "*.md"], cwd=root, capture_output=True, text=True) + if result.returncode == 0: + return [os.path.join(root, name) for name in result.stdout.splitlines() if name] + found = [] + for base, dirs, names in os.walk(root): + dirs[:] = [d for d in dirs if d not in (".git", "third_party", "node_modules", "__pycache__")] + found.extend(os.path.join(base, name) for name in names if name.endswith(".md")) + return found + + +def broken_links(root, files): + """(page, link, reason) for every relative link whose file or anchor does not resolve.""" + cache = {} + + def anchors_of(path): + if path not in cache: + try: + cache[path] = anchors(path) + except OSError: + cache[path] = set() + return cache[path] + + problems = [] + for path in files: + try: + with open(path, encoding="utf-8", errors="replace") as f: + text = f.read() + except OSError: + continue + for link in links(text): + link = link.strip() + if not link or link.startswith(EXTERNAL): + continue + if link.startswith("#"): + anchor = unquote(link[1:]) + if anchor and anchor not in anchors_of(path): + problems.append((os.path.relpath(path, root), link, "same-page anchor not found")) + continue + target, _, anchor = link.partition("#") + if not target: + continue + target = unquote(target.split("?", 1)[0]) + destination = os.path.normpath(os.path.join(os.path.dirname(path), target)) + if not os.path.exists(destination): + problems.append((os.path.relpath(path, root), link, "missing file")) + elif anchor and os.path.isfile(destination) and anchor not in anchors_of(destination): + problems.append((os.path.relpath(path, root), link, "anchor not found")) + return problems + + +class SlugTest(unittest.TestCase): + def test_inline_code_keeps_its_text(self): + self.assertEqual(slug("Rejected candidates at `917e9b9`"), "rejected-candidates-at-917e9b9") + self.assertEqual(slug("`63 30 00 00` mesh pages"), "63-30-00-00-mesh-pages") + + def test_punctuation_is_dropped(self): + self.assertEqual(slug("The Windows runtime on Linux, under Wine or Proton"), + "the-windows-runtime-on-linux-under-wine-or-proton") + + def test_duplicate_headings_get_a_suffix(self): + with tempfile.TemporaryDirectory() as tmp: + page = os.path.join(tmp, "page.md") + with open(page, "w", encoding="utf-8") as f: + f.write("# Same\n\n# Same\n") + self.assertEqual(anchors(page), {"same", "same-1"}) + + +class RepositoryLinksTest(unittest.TestCase): + def test_every_relative_link_resolves(self): + files = markdown_files(ROOT) + self.assertGreaterEqual(len(files), 30, "expected the tracked Markdown files to be found") + problems = broken_links(ROOT, files) + self.assertEqual(problems, [], + "\n".join(f"{page}: {link} ({why})" for page, link, why in problems)) + + def test_the_checker_flags_a_missing_file_and_a_bad_anchor(self): + with tempfile.TemporaryDirectory() as tmp: + def write(name, text): + with open(os.path.join(tmp, name), "w", encoding="utf-8") as f: + f.write(text) + write("good.md", "# Intro\n\n[other](other.md)\n[section](other.md#heading-one)\n[here](#intro)\n") + write("other.md", "## Heading one\n") + write("bad.md", "[missing](nope.md)\n[bad anchor](other.md#nope)\n") + files = [os.path.join(tmp, name) for name in ("bad.md", "good.md", "other.md")] + problems = sorted(broken_links(tmp, files)) + self.assertEqual(problems, [ + ("bad.md", "nope.md", "missing file"), + ("bad.md", "other.md#nope", "anchor not found"), + ]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_f16_trans_sweep.py b/tests/test_f16_trans_sweep.py new file mode 100644 index 000000000..c08d67b33 --- /dev/null +++ b/tests/test_f16_trans_sweep.py @@ -0,0 +1,150 @@ +"""tools/f16_trans_sweep.py: the f16 reference and its rounding, which input each kernel thread computes and where it +stores it, the classification, and the exit-77 contract. The last test runs on the hardware when the oracle tools +are present and is skipped otherwise. Standard library only.""" +import os +from decimal import Decimal +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +TOOLS = Path(__file__).resolve().parents[1] / "tools" +sys.path.insert(0, str(TOOLS)) +import f16_trans_sweep as sw # noqa: E402 +from hw_oracle import asm, runner # noqa: E402 + + +class Reference(unittest.TestCase): + def test_self_test(self): + self.assertEqual(sw.self_test(), 0) + + def test_rounding_to_f16(self): + self.assertEqual(sw.from_dec(Decimal(1) + Decimal(2) ** -11), 0x3C00) # tie: to even + self.assertEqual(sw.from_dec(Decimal(1) + Decimal(2) ** -11 * 3), 0x3C02) # tie: to even + self.assertEqual(sw.from_dec(Decimal(1) + Decimal(2) ** -11 + Decimal(2) ** -40), 0x3C01) + self.assertEqual(sw.from_dec(-(Decimal(1) + Decimal(2) ** -10 * Decimal("0.99")), rtz=True), 0xBC00) + self.assertEqual(sw.from_dec(Decimal(2) ** -14 - Decimal(2) ** -25), 0x0400) # rounds up to normal + self.assertEqual(sw.from_dec(Decimal(-70000)), 0xFC00) + self.assertEqual(sw.from_dec(Decimal(-70000), rtz=True), 0xFBFF) + + def test_undefined_inputs_are_the_ones_spirv_leaves_undefined(self): + undef = {op: [h for h, r in enumerate(sw.reference(op)) if r is None] for op in ("v_rcp_f16", "v_sqrt_f16")} + self.assertEqual(undef["v_rcp_f16"], [0x0000, 0x8000]) + self.assertEqual(len(undef["v_sqrt_f16"]), 31744) # every negative but -0, -inf included + self.assertNotIn(0x8000, undef["v_sqrt_f16"]) + self.assertIn(0xFC00, undef["v_sqrt_f16"]) + self.assertEqual(sw.exact("v_log_f16", 0x8000), "undef") + self.assertEqual(sw.exact("v_rsq_f16", 0x0000), "undef") + self.assertEqual(sw.exact("v_exp_f16", 0x7E00), "nan") + + def test_the_sine_reduces_in_turns_and_the_f32_product_does_not(self): + # x = 1000.5: sin(2 pi x) = sin(pi) = 0, but 6.2831855 * x in f32 is 6286.3726, about 1.6e-3 rad off + h = 0x63D1 + self.assertEqual(float(sw.to_dec(h)), 1000.5) + self.assertEqual(sw.to_bits(sw.exact("v_sin_f16", h)), 0) + self.assertNotEqual(sw.to_bits(sw.product_turns("v_sin_f16", h)), 0) + + +class Kernels(unittest.TestCase): + def test_every_input_is_computed_once_and_stored_at_its_own_half(self): + seen = {} + for j in range(65536 // sw.PER_KERNEL): + base = j * sw.PER_KERNEL + lines = sw.kernel_lines("v_exp_f16", base) + self.assertEqual(lines[1], f"v_add_nc_u32 v1, 0x{base:x}, v1") + for t in range(sw.THREADS): + for k in range(sw.PER_THREAD): + word = base // 2 + 4 * t + k // 2 # global_store_b128 at 16 * t, v8 + k // 2 + seen[word * 2 + k % 2] = base + 8 * t + k + self.assertEqual(sorted(seen), list(range(65536))) + self.assertTrue(all(seen[i] == i for i in seen)) + + def test_kernels_assemble_for_rdna2(self): + try: + clang = runner.find_clang() + except runner.Unavailable as e: + self.skipTest(str(e)) + kernels = [asm.Kernel(sw.kernel_lines(op, 0, "gfx1030"), w, sw.THREADS, sw.PER_KERNEL // 2, raw=True, + mode=sw.MODES["keep16"]) for op in sw.OPS for w in (32,)] + text, names, _ = asm.module_text(kernels, "gfx1030", wave=32) + with tempfile.TemporaryDirectory() as d: + s = Path(d) / "k.s" + s.write_text(text, encoding="utf-8") + r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-c", str(s), "-o", + str(Path(d) / "k.o")], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr[:800]) + self.assertEqual(len(names), len(sw.OPS)) + self.assertIn(".amdhsa_float_denorm_mode_16_64 3", text) + self.assertIn("global_store_dwordx4 v24, v[8:11], s[2:3]", text) + + +class Classify(unittest.TestCase): + def setUp(self): + self.ref = sw.reference("v_rcp_f16") + + def test_the_rule_itself_is_all_exact(self): + hw = [r if r is not None else 0x7E00 for r in self.ref] + c, worst = sw.classify("v_rcp_f16", hw, self.ref) + self.assertEqual(c["exact"] + c["nan_ok"] + c["undefined"], 65536) + self.assertEqual(c["undefined"], 2) + self.assertEqual(worst, []) + + def test_each_kind_of_difference_is_counted_apart(self): + hw = [r if r is not None else 0 for r in self.ref] + hw[0x0000], hw[0x8000] = 0x7C00, 0xFC00 # undefined in the rule: the hardware's +-inf + hw[0x3C00] = 0x3C01 # rcp(1) off by 1 ulp + hw[0x4000] = 0x3802 # rcp(2) off by 2 ulp + hw[0x03FF] = 0x7C00 # rcp(largest denormal) as the hardware's rcp(+0) + hw[0x7BFF] = 0x0000 # rcp(65504) = 2^-16 * (1 + ...) is a denormal, flushed + hw[0x7E00] = 0x3C00 # NaN in, a number out + hw[0x7D00] = 0x7F00 # a signalling NaN quieted + hw[0x7C01] = 0x7C01 # a signalling NaN passed through + c, worst = sw.classify("v_rcp_f16", hw, self.ref) + self.assertTrue(sw.is_denorm(self.ref[0x7BFF])) + self.assertEqual((c["ulp1"], c["ulp_more"], c["max_ulp"]), (1, 1, 2)) + self.assertEqual((c["denorm_in_as_zero"], c["denorm_out_flushed"], c["other"]), (1, 1, 1)) + self.assertEqual((c["snan_quieted"], c["snan_kept"], c["snan_other"]), (1, 1, 1020)) + self.assertEqual({w[0] for w in worst}, {0x4000, 0x7E00}) + + +class Cli(unittest.TestCase): + def test_exits_77_without_the_tools(self): + env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") + r = subprocess.run([sys.executable, "-I", str(TOOLS / "f16_trans_sweep.py"), "--ops", "v_exp_f16"], + capture_output=True, text=True, env=env) + self.assertEqual(r.returncode, 77, r.stdout + r.stderr) + self.assertIn("unavailable", r.stdout) + + def test_unknown_names_are_a_usage_error(self): + r = subprocess.run([sys.executable, "-I", str(TOOLS / "f16_trans_sweep.py"), "--ops", "v_exp_f32"], + capture_output=True, text=True) + self.assertEqual(r.returncode, 2) + self.assertIn("v_exp_f32", r.stderr) + + +class OnHardware(unittest.TestCase): + @classmethod + def setUpClass(cls): + try: + cls.oracle = runner.open_oracle() + except runner.Unavailable as e: + raise unittest.SkipTest(f"hardware oracle unavailable: {e}") from None + + @classmethod + def tearDownClass(cls): + cls.oracle.close() + + def test_exp_sweep_is_the_same_in_both_wave_sizes_and_exact_on_integers(self): + sw.check_modes(self.oracle, ["keep16"]) + w32 = sw.sweep(self.oracle, "v_exp_f16", "keep16", 32) + w64 = sw.sweep(self.oracle, "v_exp_f16", "keep16", 64) + self.assertEqual(w32, w64) + for x, want in ((0x0000, 0x3C00), (0x3C00, 0x4000), (0x4000, 0x4400), (0xBC00, 0x3800), (0x7C00, 0x7C00), + (0xFC00, 0x0000)): + self.assertEqual(w32[x], want, f"exp2(0x{x:04x})") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_f32_fuzz.py b/tests/test_f32_fuzz.py index 32cc53539..14b7a7ede 100644 --- a/tests/test_f32_fuzz.py +++ b/tests/test_f32_fuzz.py @@ -4,6 +4,7 @@ """ import os import random +import subprocess import sys import unittest @@ -89,5 +90,111 @@ class HarnessTests(unittest.TestCase): self.assertIn("denormal", detail) +class HardwareOracle(unittest.TestCase): + """--oracle hw: kernel text, verdicts, GFX11 skips and the exit-77 contract (no GPU needed), plus a run on the + GPU when the oracle tools are present.""" + TOOL = os.path.join(ROOT, "tools", "f32_fuzz.py") + + def case(self, op, vals, srcs, mods=(), e64=False): + return ff.Case(op, list(vals) + [0] * (9 - len(vals)), srcs, e64, list(mods)) + + def test_kernel_body(self): + c = self.case("v_add_f32", [ff.bits(1.0), ff.bits(2.0)], [(0, {}), (1, {})], ["mul:2", "clamp"], True) + lines = ff.hw_lines(c, "gfx1150") + self.assertIn("v_add_f32_e64 v8, v0, v1 clamp mul:2", lines) # GFX11 wants clamp before omod + self.assertEqual(lines[-3:], ["v_mov_b32 v20, 0", "global_store_b64 v20, v[8:9], s[2:3]", "s_endpgm"]) + self.assertEqual(ff.hw_lines(c, "gfx1030")[-2], "global_store_dwordx2 v20, v[8:9], s[2:3]") + self.assertEqual(len(ff.hw_lines(c, "gfx1150", guard=False)), len(lines) - 1) + + def test_removed_opcodes_are_skipped_not_substituted(self): + from hw_oracle import asm + for op in ("v_mad_f32", "v_mac_f32", "v_madak_f32", "v_mad_legacy_f32"): + self.assertIn(op, asm.valu_skip_reason(op, "gfx1150")) + self.assertIn(op, asm.valu_skip_reason(op, "gfx1030")) + self.assertIsNone(asm.valu_skip_reason(op, "gfx1013")) + self.assertIsNone(asm.valu_skip_reason("v_mul_legacy_f32", "gfx1150")) + + def test_mode_words(self): + self.assertEqual(ff.mode_word(ff.HW_MODES["flush"]), 0x1C0) + self.assertEqual(ff.mode_word(ff.HW_MODES["keep"]), 0x1F0) + self.assertEqual(ff.mode_word(ff.HW_MODES["ieee"]), 0x3C0) + self.assertFalse(ff.omod_active("keep", "v_add_f32")) + self.assertTrue(ff.omod_active("keep", "v_rcp_f32")) + + def test_verdicts(self): + a = self.case("v_add_f32", [ff.bits(1.0), ff.bits(2.0)], [(0, {}), (1, {})]) + self.assertEqual(ff.hw_verdict(a, [ff.bits(3.0), 0])[0], "match") + self.assertEqual(ff.hw_verdict(a, [ff.bits(3.0) ^ 1, 0])[0], "mismatch") + d = self.case("v_ceil_f32", [ff.bits(-0.75)], [(0, {})], ["mul:2"], True) + self.assertEqual(ff.hw_verdict(d, [0, 0])[0], "deviation:omod_neg_zero") # omod: -0 becomes +0 + self.assertEqual(ff.hw_verdict(d, [0x80000000, 0])[0], "match") + self.assertEqual(ff.hw_verdict(d, [ff.bits(1.0), 0])[0], "mismatch") + dn = self.case("v_add_f32", [1, ff.bits(1.0)], [(0, {}), (1, {})]) + self.assertEqual(ff.hw_verdict(dn, [ff.bits(1.0), 0])[0], "skip") + + def test_omod_deviation_needs_an_active_omod(self): + d = self.case("v_ceil_f32", [ff.bits(-0.75)], [(0, {})], ["mul:2"], True) + want = [0x80000000, 0] + self.assertEqual(ff.dev_omod_neg_zero(d, want), [0, 0]) + self.assertIsNone(ff.dev_omod_neg_zero(d, want, "ieee")) + self.assertIsNone(ff.dev_omod_neg_zero(d, want, "keep")) + self.assertIsNone(ff.dev_omod_neg_zero(self.case("v_ceil_f32", [0], [(0, {})], [], True), want)) + + def test_zero_inf_probes_catch_a_plain_multiply(self): + import random + cases = [ff.gen_probe(random.Random(i), "v_mul_legacy_f32", "zero_inf") for i in range(8)] + self.assertTrue(all(c is not None for c in cases)) + with ff.perturbed("legacy_is_ieee"): + bad = sum(ff.hw_verdict(c, [0, 0])[0] == "match" for c in cases) + self.assertLess(bad, len(cases)) + + def test_f16_nan_halves_compare_as_nan(self): + self.assertTrue(ff.hw_same([0x7E00, 0], [0x7E06, 0], "v_cvt_f16_f32")) + self.assertFalse(ff.hw_same([0x7E00, 0], [0x3C00, 0], "v_cvt_f16_f32")) + self.assertFalse(ff.hw_same([0x00007E00, 0], [0x00017E00, 0], "v_cvt_f16_f32")) # high half is kept exactly + + def test_negative_control_detects_each_perturbation(self): + self.assertTrue(ff.hw_self_test()) + + def test_denormal_variants_distinguish_flush_from_keep(self): + m = self.case("v_mul_f32", [1, ff.bits(1048576.0)], [(0, {}), (1, {})]) + self.assertEqual(ff.denorm_label(m, [0, 0]), ("operand", "ftz|ftz_in|ftz_out")) + self.assertEqual(ff.denorm_label(m, [ff.bits(2.0 ** -129), 0]), ("operand", "keep")) + + def test_hardware_only_ops_stay_out_of_the_translator_run(self): + self.assertTrue(set(ff.HW_ONLY_OPS).isdisjoint(ff.OPS)) + r = subprocess.run([sys.executable, "-I", self.TOOL, "--ops", "v_min_f32"], capture_output=True, text=True) + self.assertEqual(r.returncode, 2) + + def test_exit_77_without_the_oracle_tools(self): + env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(ROOT, "tools", "no-such-clang.exe")) + r = subprocess.run([sys.executable, "-I", self.TOOL, "--oracle", "hw", "--programs", "2"], + capture_output=True, text=True, env=env) + self.assertEqual(r.returncode, 77, r.stdout + r.stderr) + self.assertIn("unavailable", r.stdout) + + def test_unknown_oracle_is_a_usage_error(self): + r = subprocess.run([sys.executable, "-I", self.TOOL, "--oracle", "gpu"], capture_output=True, text=True) + self.assertEqual(r.returncode, 2) + + def test_on_hardware(self): + from hw_oracle import runner + try: + oracle = runner.open_oracle() + except runner.Unavailable as e: + self.skipTest(f"hardware oracle unavailable: {e}") + try: + ff.hw_probe_modes(oracle) + cases = ff.gen_cases(300, 21, tuple(ff.ALL_OPS)) + ff.gen_probes(2, 21, tuple(ff.ALL_OPS)) + rep = ff.hw_suite(oracle, cases, info_modes=("keep",)) + finally: + oracle.close() + self.assertEqual([(c.op, c.index) for c, _, _ in rep.mismatches], []) + self.assertGreater(sum(r["match"] for r in rep.per_op.values()), 150) + for name, (n, bad) in ff.negative_control(rep).items(): + if n >= 20 and name in ("add_lsb", "mul_rtz", "rndne_floor", "min_ieee_nan"): + self.assertGreater(bad, 0, name) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_feature_scan_bad_index.py b/tests/test_feature_scan_bad_index.py new file mode 100644 index 000000000..60900dfcf --- /dev/null +++ b/tests/test_feature_scan_bad_index.py @@ -0,0 +1,81 @@ +"""Malformed index shapes must be one-line errors or empty counts, never a traceback. + +Run with ``python -I tests/test_feature_scan_bad_index.py``. Set ``LEONIDA_FEATURE_SCAN`` +to another copy of the tool to use as a negative control (main's version fails these +tests). All inputs are built here by hand; no game data is used. +""" +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TOOL = Path(os.environ.get("LEONIDA_FEATURE_SCAN", str(ROOT / "tools" / "feature_scan.py"))) + + +def make_work(folder, dxbc_rows, spirv=None, spirv_text=None): + shaders = Path(folder) / "shaders" + (shaders / "dxbc").mkdir(parents=True) + (shaders / "spirv").mkdir(parents=True) + (shaders / "dxbc" / "index.json").write_text(json.dumps(dxbc_rows), encoding="utf-8") + if spirv_text is not None: + (shaders / "spirv" / "index.json").write_text(spirv_text, encoding="utf-8") + elif spirv is not None: + (shaders / "spirv" / "index.json").write_text(json.dumps(spirv), encoding="utf-8") + return shaders + + +class BadFeatureScanIndexTest(unittest.TestCase): + def run_scan(self, shaders, out=None): + argv = [sys.executable, "-I", str(TOOL), str(shaders)] + if out: + argv += ["--out", str(out)] + return subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=60) + + def assert_clean(self, result): + self.assertNotIn("Traceback", result.stderr, result.stderr) + + def test_non_object_spirv_indexes_are_empty_counts(self): + for value in (None, 42, True, "x"): + with self.subTest(value=value), tempfile.TemporaryDirectory() as td: + shaders = make_work(td, [], spirv_text=json.dumps(value)) + result = self.run_scan(shaders) + self.assertEqual(result.returncode, 0, result.stderr) + self.assert_clean(result) + self.assertIn("uses_code_base by stage: {}", result.stdout) + + def test_broken_spirv_json_is_one_error_line(self): + with tempfile.TemporaryDirectory() as td: + shaders = make_work(td, [], spirv_text="{oops") + result = self.run_scan(shaders) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("ERROR: cannot read", result.stderr) + self.assertEqual(len(result.stderr.strip().splitlines()), 1, result.stderr) + self.assert_clean(result) + + def test_non_object_dxbc_rows_are_counted_as_unreadable(self): + with tempfile.TemporaryDirectory() as td: + rows = [1, "x", None, {}, {"name": "good", "file": "good.dxbc", "stage": "ps"}] + shaders = make_work(td, rows) + result = self.run_scan(shaders) + self.assertEqual(result.returncode, 0, result.stderr) + self.assert_clean(result) + self.assertIn("could not be read", result.stdout) + + def test_valid_indexes_are_still_counted(self): + with tempfile.TemporaryDirectory() as td: + rows = [{"name": "ps_a", "file": "ps_a.dxbc", "stage": "ps"}] + shaders = make_work(td, rows, spirv={"ps_a": {"stage": "ps", "uses_code_base": True}}) + out = Path(td) / "report.json" + result = self.run_scan(shaders, out) + self.assertEqual(result.returncode, 0, result.stderr) + report = json.loads(out.read_text(encoding="utf-8")) + self.assertEqual(report["spirv"]["translated"], {"ps": 1}) + self.assertEqual(report["spirv"]["uses_code_base"], {"ps": 1}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fssm_header.py b/tests/test_fssm_header.py index 5d1771cd7..23f1a4961 100644 --- a/tests/test_fssm_header.py +++ b/tests/test_fssm_header.py @@ -95,6 +95,34 @@ class PixelInputTest(unittest.TestCase): self.assertEqual(fssm_header.interpolants(b), (2, 0)) +class ReadMethodTest(unittest.TestCase): + """Flags bits 0-1, the read method: 1 = v_interp_mov (flat), 2 = v_interp_p1/p2 (interpolated); SHADER-181.""" + + def test_read_methods_by_table_position(self): + b = blob([record(1, 0xF, 0, 0, 0x02), + record(2, 0xF, 1, 1, 0x01), + record(3, 0x3, 2, 2, 0x1A), # the corpus' 16-bit records: fp16 | bit 3 | linear + record(4, 0x1, 3, 3, 0x09)]) + self.assertEqual(fssm_header.read_methods(b), [2, 1, 2, 1]) + + def test_read_bits_do_not_touch_the_fp16_mask(self): + b = blob([record(1, 0xF, 0, 0, 0x03), record(2, 0xF, 1, 1, 0x13)]) + self.assertEqual(fssm_header.read_methods(b), [3, 3]) + self.assertEqual(fssm_header.interpolants(b), (2, 0b10)) + + def test_no_table_no_read_methods(self): + self.assertEqual(fssm_header.read_methods(blob(first=0)), []) + + def test_names(self): + self.assertEqual([fssm_header.read_name(m) for m in range(4)], ["read0", "mov", "interp", "read3"]) + + def test_tally_counts_ps_read_methods_only(self): + rows = [{"stage": "ps", "directory_ok": True, "entries": 2, "fp16_mask": 0, + "inputs": [{"flags": 0x02}, {"flags": 0x00}]}, + {"stage": "vs", "directory_ok": True, "entries": 1, "fp16_mask": 0, "inputs": [{"flags": 0x01}]}] + self.assertEqual(fssm_header.tally(rows, True)["read_methods"], {"interp": 1, "read0": 1}) + + class DirectoryTest(unittest.TestCase): def test_identity_holds(self): self.assertTrue(fssm_header.directory_ok(blob(directory=(0x100, 0x20, 0x120)))) @@ -156,7 +184,7 @@ class CliTest(unittest.TestCase): fssm_dir = os.path.join(self.dir, "fssm") os.makedirs(fssm_dir) with open(os.path.join(fssm_dir, "a.fssm"), "wb") as f: - f.write(blob([record(1, 0xF, 0, 0, 0x10), record(2, 0x3, 1, 1, 0)])) + f.write(blob([record(1, 0xF, 0, 0, 0x12), record(2, 0x3, 1, 1, 0x01)])) with open(os.path.join(fssm_dir, "b.fssm"), "wb") as f: f.write(blob(first=0)) with open(os.path.join(self.dir, "index.json"), "w", encoding="utf-8") as f: @@ -221,6 +249,7 @@ class CliTest(unittest.TestCase): self.assertEqual(p.returncode, 0, p.stderr) self.assertIn("2 files, directory_ok 2, PS with table 1, entries 2", p.stdout) self.assertIn("a.fssm: stage=ps directory_ok=True entries=2 fp16=0x1", p.stdout) + self.assertIn("read methods: interp:1, mov:1", p.stdout) def test_json_tally(self): p = subprocess.run([sys.executable, "-I", TOOL, self.fssm_dir, "--json"], @@ -229,6 +258,7 @@ class CliTest(unittest.TestCase): doc = json.loads(p.stdout) self.assertEqual(doc["tally"]["ps_with_table"], 1) self.assertEqual(doc["tally"]["entries"], 2) + self.assertEqual(doc["tally"]["read_methods"], {"interp": 1, "mov": 1}) def test_table_only_entry_counts_exclude_blobs_without_a_table(self): os.remove(os.path.join(self.dir, "index.json")) diff --git a/tests/test_fssm_unpack.py b/tests/test_fssm_unpack.py index a0f30e2d5..51acb42a1 100644 --- a/tests/test_fssm_unpack.py +++ b/tests/test_fssm_unpack.py @@ -249,6 +249,78 @@ class TestXbchContainerCarvingAndUnpack(unittest.TestCase): fssm_unpack.unpack(dxbc) self.assertIn("size mismatch", str(ctx.exception)) + def test_unpack_rejects_declared_size_over_fixed_limit_before_inflating(self): + fssm_payload = make_fssm(pad_to=64) + xbch_blob = make_xbch(fssm_payload, unpacked_override=65) + dxil = make_xdat({0x0D: xbch_blob}) + dxbc = make_dxbc([(b"DXIL", dxil)]) + real_decompressobj = zlib.decompressobj + + with mock.patch.object(fssm_unpack, "MAX_FSSM_BYTES", 64, create=True), \ + mock.patch.object(fssm_unpack.zlib, "decompressobj", wraps=real_decompressobj) as decompressobj: + with self.assertRaisesRegex(ValueError, "exceeds limit"): + fssm_unpack.unpack(dxbc) + decompressobj.assert_not_called() + + def test_unpack_caps_expansion_at_declared_size_plus_one(self): + fssm_payload = make_fssm(pad_to=4096) + xbch_blob = make_xbch(fssm_payload, unpacked_override=32) + dxil = make_xdat({0x0D: xbch_blob}) + dxbc = make_dxbc([(b"DXIL", dxil)]) + real_decompressobj = zlib.decompressobj + observed = [] + + class RecordingDecompressor: + def __init__(self, *args, **kwargs): + self.inner = real_decompressobj(*args, **kwargs) + + def decompress(self, data, max_length=0): + output = self.inner.decompress(data, max_length) + observed.append((max_length, len(output))) + return output + + @property + def eof(self): + return self.inner.eof + + with mock.patch.object(fssm_unpack, "MAX_FSSM_BYTES", 64, create=True), \ + mock.patch.object(fssm_unpack.zlib, "decompressobj", side_effect=RecordingDecompressor): + with self.assertRaisesRegex(ValueError, "exceeds declared size"): + fssm_unpack.unpack(dxbc) + + self.assertEqual(observed, [(33, 33)]) + + def test_unpack_rejects_truncated_zlib_stream(self): + fssm_payload = make_fssm() + compressed = zlib.compress(fssm_payload)[:-4] + header = struct.pack("<4sIIIII", b"XBCH", 0, len(compressed), 0, len(fssm_payload), 0) + xbch_blob = header + compressed + dxil = make_xdat({0x0D: xbch_blob}) + dxbc = make_dxbc([(b"DXIL", dxil)]) + + with self.assertRaisesRegex(ValueError, "truncated XBCH zlib stream"): + fssm_unpack.unpack(dxbc) + + def test_unpack_rejects_trailing_data_after_zlib_stream(self): + fssm_payload = make_fssm() + compressed = zlib.compress(fssm_payload) + b"trailing" + header = struct.pack("<4sIIIII", b"XBCH", 0, len(compressed), 0, len(fssm_payload), 0) + xbch_blob = header + compressed + dxil = make_xdat({0x0D: xbch_blob}) + dxbc = make_dxbc([(b"DXIL", dxil)]) + + with self.assertRaisesRegex(ValueError, "trailing data after XBCH zlib stream"): + fssm_unpack.unpack(dxbc) + + def test_unpack_rejects_mismatched_stored_size(self): + fssm_payload = make_fssm() + xbch_blob = make_xbch(fssm_payload, stored_override=1) + dxil = make_xdat({0x0D: xbch_blob}) + dxbc = make_dxbc([(b"DXIL", dxil)]) + + with self.assertRaisesRegex(ValueError, "stored size"): + fssm_unpack.unpack(dxbc) + def test_unpack_corrupt_zlib_raises_error(self): fssm_payload = make_fssm() xbch_blob = make_xbch(fssm_payload, corrupt_zlib=True) diff --git a/tests/test_gamedata_xml_bad_index.py b/tests/test_gamedata_xml_bad_index.py new file mode 100644 index 000000000..b10707632 --- /dev/null +++ b/tests/test_gamedata_xml_bad_index.py @@ -0,0 +1,74 @@ +"""Bad carve indexes must give one ERROR line in gamedata_xml.py, never a traceback. + +Run with ``python -I tests/test_gamedata_xml_bad_index.py``. Set ``LEONIDA_GAMEDATA_XML`` +to another copy of the tool to use as a negative control (main's version fails these +tests). All inputs are hand-built; no game data is used. +""" +import json +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +ROOT = pathlib.Path(__file__).resolve().parent.parent +TOOL = pathlib.Path(os.environ.get("LEONIDA_GAMEDATA_XML", str(ROOT / "tools" / "gamedata_xml.py"))) +XML = (b'\n' + b'fixture') + + +class BadGamedataXmlIndexTest(unittest.TestCase): + def run_tool(self, carve, extra=None): + argv = [sys.executable, "-I", str(TOOL), str(carve)] + if extra: + argv += extra + return subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=60) + + def make_carve(self, folder, doc=None, text=None, payload=None): + carve = pathlib.Path(folder) / "x.rpf" + carve.mkdir() + index = carve / "index.json" + if text is not None: + index.write_text(text, encoding="utf-8") + else: + index.write_text(json.dumps(doc), encoding="utf-8") + if payload is not None: + (carve / "000000000000.bin").write_bytes(payload) + return carve + + def assert_one_error(self, result): + self.assertNotIn("Traceback", result.stderr, result.stderr) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertEqual(len(result.stderr.strip().splitlines()), 1, result.stderr) + self.assertTrue(result.stderr.startswith("ERROR: cannot read "), result.stderr) + + def test_missing_files_key(self): + with tempfile.TemporaryDirectory() as td: + self.assert_one_error(self.run_tool(self.make_carve(td, {}))) + + def test_row_missing_stored(self): + with tempfile.TemporaryDirectory() as td: + doc = {"files": [{"off": 0, "size": 4}]} + self.assert_one_error(self.run_tool(self.make_carve(td, doc))) + + def test_files_is_a_string(self): + with tempfile.TemporaryDirectory() as td: + self.assert_one_error(self.run_tool(self.make_carve(td, {"files": "oops"}))) + + def test_malformed_json(self): + with tempfile.TemporaryDirectory() as td: + self.assert_one_error(self.run_tool(self.make_carve(td, text="{oops"))) + + def test_valid_carve_still_reports(self): + with tempfile.TemporaryDirectory() as td: + doc = {"files": [{"off": 0, "stored": len(XML), "size": len(XML), "head": XML[:16].hex()}]} + carve = self.make_carve(td, doc, payload=XML) + result = self.run_tool(carve) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertIn("CDataFileMgr__ContentChangeSetDef", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gpu_build_dir.py b/tests/test_gpu_build_dir.py index acb8c7023..fcfaf40a7 100644 --- a/tests/test_gpu_build_dir.py +++ b/tests/test_gpu_build_dir.py @@ -162,5 +162,25 @@ class MainUsesTheResolvedFolder(unittest.TestCase): self.assertIn("test programs:", out.getvalue()) +class MissingTestProgram(unittest.TestCase): + def test_missing_texture_executable_is_a_test_failure(self): + with tempfile.TemporaryDirectory() as tmp: + build = Path(tmp) + touch(build) + program = "vk_texture_test" + check.EXE + code, message = check.run(str(build / program)) + self.assertNotEqual(code, 0) + self.assertIn(program, message) + + def test_missing_core_executable_preserves_build_diagnostic(self): + with tempfile.TemporaryDirectory() as tmp: + build = Path(tmp) + touch(build, names=PROGRAMS[:-1]) + with self.assertRaises(SystemExit) as caught: + check.run(str(build / PROGRAMS[-1])) + self.assertIn(PROGRAMS[-1], str(caught.exception)) + self.assertIn("subfolders were searched", str(caught.exception)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_gpu_test_timeout.py b/tests/test_gpu_test_timeout.py index 47df7f4b2..8b6aed3e1 100644 --- a/tests/test_gpu_test_timeout.py +++ b/tests/test_gpu_test_timeout.py @@ -35,11 +35,14 @@ class Limit(unittest.TestCase): self.assertIsNone(self.limit("0")) self.assertIsNone(self.limit("-1")) - def test_not_a_number_is_an_error(self): - for bad in ("soon", "nan"): - with self.subTest(bad=bad), self.assertRaises(SystemExit) as ctx: - self.limit(bad) - self.assertIn("LEONIDA_GPU_TEST_TIMEOUT", str(ctx.exception.code)) + def test_non_numeric_or_non_finite_limit_is_an_error(self): + for bad in ("soon", "nan", "inf", "-inf", "1e9999"): + with self.subTest(bad=bad): + with self.assertRaises(SystemExit) as ctx: + self.limit(bad) + message = str(ctx.exception.code) + self.assertIn("LEONIDA_GPU_TEST_TIMEOUT", message) + self.assertIn(repr(bad), message) class HungProgram(unittest.TestCase): diff --git a/tests/test_hw_oracle.py b/tests/test_hw_oracle.py index e007c480d..f27580248 100644 --- a/tests/test_hw_oracle.py +++ b/tests/test_hw_oracle.py @@ -1,16 +1,19 @@ -"""tools/hw_oracle: kernel text, literal and opcode filters, error mapping, and the exit-77 contract. No GPU needed; -the last test runs on the hardware when the oracle tools are present and is skipped otherwise. +"""tools/hw_oracle: kernel text, literal and opcode filters, error mapping, the exit-77 contract, and the parts of +the Linux backend that need no GPU (reading the assembled object, the launcher's tokens, the display check). The +last tests run on the hardware when the oracle tools are present and are skipped otherwise. Standard library only.""" import os from pathlib import Path +import struct import subprocess import sys +import tempfile import unittest import unittest.mock TOOLS = Path(__file__).resolve().parents[1] / "tools" sys.path.insert(0, str(TOOLS)) -from hw_oracle import asm, runner # noqa: E402 +from hw_oracle import asm, drm, runner # noqa: E402 PROG = ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 7", "s_add_u32 s6, s4, s5", "s_cselect_b32 s30, 1, 0", "v_mov_b32 v8, s4", "v_mov_b32 v9, s5", "v_mov_b32 v10, s6", "v_mov_b32 v11, s30"] @@ -21,22 +24,34 @@ class Text(unittest.TestCase): self.assertEqual(asm.family("gfx1150"), "gfx11") self.assertEqual(asm.family("gfx1030"), "gfx10") self.assertEqual(asm.family("gfx1013"), "gfx10") + self.assertEqual(asm.family("gfx1201"), "gfx12") with self.assertRaises(ValueError): asm.family("gfx90a") def test_kernel_uses_the_mnemonics_of_its_family(self): k11, k10 = asm.kernel_text("k0", PROG, "gfx1150"), asm.kernel_text("k0", PROG, "gfx1030") - self.assertIn("s_load_b64 s[2:3], s[0:1], 0x0", k11) - self.assertIn("global_store_b128 v0, v[8:11], s[2:3]", k11) + k12 = asm.kernel_text("k0", PROG, "gfx1201") + for k in (k11, k12): + self.assertIn("s_load_b64 s[2:3], s[0:1], 0x0", k) + self.assertIn("global_store_b128 v0, v[8:11], s[2:3]", k) self.assertIn("s_load_dwordx2", k10) self.assertIn("global_store_dwordx4", k10) - for k in (k11, k10): + for k in (k11, k12, k10): self.assertIn(" s_add_u32 s6, s4, s5\n", k) self.assertIn(".amdhsa_wavefront_size32 1", k) # the program runs between the output-pointer load and the store self.assertLess(k.index("s_waitcnt lgkmcnt(0)"), k.index("s_add_u32")) self.assertLess(k.index("s_add_u32"), k.index("v[8:11]")) + def test_raw_kernels_get_the_memory_mnemonics_of_their_family(self): + body = ["v_mov_b32 v20, 7", "global_store_b32 v22, v20, s[2:3] offset:4", "s_endpgm"] + k10, k11 = asm.raw_kernel_text("k0", body, "gfx1036"), asm.raw_kernel_text("k0", body, "gfx1150") + self.assertIn(" global_store_dword v22, v20, s[2:3] offset:4\n", k10) # GFX10 has no global_store_b32 + self.assertNotIn("global_store_b32", k10) + self.assertIn(" global_store_b32 v22, v20, s[2:3] offset:4\n", k11) + self.assertEqual(asm.gfx10_spelling("global_load_b128 v[4:7], v0, s[2:3]"), "global_load_dwordx4 v[4:7], v0, s[2:3]") + self.assertEqual(asm.gfx10_spelling("v_mov_b32 v20, 7"), "v_mov_b32 v20, 7") + def test_metadata_is_required_and_lists_every_kernel(self): text, names, starts = asm.module_text([PROG, PROG, PROG], "gfx1150") self.assertEqual(names, ["k0", "k1", "k2"]) @@ -71,6 +86,13 @@ class Filters(unittest.TestCase): self.assertIn("s_ff0", asm.skip_reason(PROG + ["s_ff0_i32_b32 s4, s5"], "gfx1150")) self.assertIsNone(asm.skip_reason(PROG + ["s_ff0_i32_b32 s4, s5"], "gfx1030")) # GFX10 still has it self.assertIn("two different literals", asm.skip_reason(["s_and_b32 s4, 0x100, 0x200"], "gfx1030")) + # GFX12 keeps GFX11's removals and drops the SOPK compares, which GFX11 still has. + cmpk = PROG + ["s_cmpk_lt_i32 s4, 0x12"] + self.assertIsNone(asm.skip_reason(PROG, "gfx1201")) + self.assertIsNone(asm.skip_reason(cmpk, "gfx1150")) + self.assertIn("GFX12", asm.skip_reason(cmpk, "gfx1201")) + self.assertIn("s_ff0", asm.skip_reason(PROG + ["s_ff0_i32_b64 s[4:5], s[6:7]"], "gfx1201")) + self.assertEqual(len([op for op in asm.GFX12_REMOVED if op.startswith("s_cmpk_")]), 12) class Unavailable(unittest.TestCase): @@ -82,6 +104,49 @@ class Unavailable(unittest.TestCase): with self.assertRaises(runner.Unavailable): runner.find_hip_dll() + def test_host_compiler_choice(self): + here = str(Path(__file__)) # any file that exists stands in for a compiler + cl = str(Path(here).with_name("cl.exe")) + which = {"gcc": None, "cl": None} + real_isfile = os.path.isfile + no_msys = lambda p: False if "msys64" in p else real_isfile(p) # noqa: E731 (hide an installed MSYS2) + with unittest.mock.patch.object(runner.shutil, "which", side_effect=lambda n: which.get(n)), \ + unittest.mock.patch.object(runner.os.path, "isfile", side_effect=no_msys), \ + unittest.mock.patch.object(runner, "find_vcvars", return_value=None), \ + unittest.mock.patch.dict(os.environ, {"LEONIDA_HOST_CC": ""}): + with self.assertRaises(runner.Unavailable) as cm: + runner.find_cc() + self.assertIn("Visual Studio", str(cm.exception)) + which["gcc"] = here + self.assertEqual(runner.find_cc(), ("gcc", here)) # gcc stays first + if os.name == "nt": + which["gcc"], which["cl"] = None, here + self.assertEqual(runner.find_cc(), ("msvc", here)) # a Developer shell's cl + which["cl"] = None + with unittest.mock.patch.object(runner, "find_vcvars", return_value=here): + self.assertEqual(runner.find_cc(), ("vcvars", here)) # VS found through vswhere + with unittest.mock.patch.dict(os.environ, {"LEONIDA_HOST_CC": here}): + self.assertEqual(runner.find_cc(), ("gcc", here)) + with unittest.mock.patch.object(runner.os.path, "isfile", return_value=True), \ + unittest.mock.patch.dict(os.environ, {"LEONIDA_HOST_CC": cl}): + self.assertEqual(runner.find_cc(), ("msvc", cl)) # the override may be cl.exe + + def test_host_compiler_commands(self): + work = os.path.join(os.sep, "w") + self.assertEqual(runner.build_command("gcc", "gcc", "a.c", "o.exe", work), ["gcc", "-O1", "a.c", "-o", "o.exe"]) + cl = runner.build_command("msvc", "cl.exe", "a.c", "o.exe", work) + self.assertEqual(cl[:4], ["cl.exe", "/nologo", "/O1", "a.c"]) + self.assertIn("/Feo.exe", cl) + self.assertIn("/Fo" + os.path.join(work, ""), cl) # objects stay out of the cwd + import tempfile + with tempfile.TemporaryDirectory() as tmp: + argv = runner.build_command("vcvars", r"C:\VS 2022\vcvars64.bat", "a.c", "o.exe", tmp) + self.assertEqual(argv[:3], ["cmd.exe", "/d", "/c"]) + script = Path(argv[3]).read_text(encoding="ascii") + self.assertIn('call "C:\\VS 2022\\vcvars64.bat"', script) # quoted: the path has a space + self.assertIn("cl /nologo /O1 a.c /Feo.exe", script) + self.assertIn("Installer", script) # vcvars needs vswhere on PATH + def test_salu_diff_exits_77_without_the_tools(self): env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe")) r = subprocess.run([sys.executable, "-I", str(TOOLS / "salu_diff.py"), "--oracle", "hw", "--programs", "3"], @@ -89,12 +154,143 @@ class Unavailable(unittest.TestCase): self.assertEqual(r.returncode, 77, r.stdout + r.stderr) self.assertIn("unavailable", r.stdout) + def test_an_unsupported_architecture_is_unavailable_not_a_traceback(self): + # Oracle() checks the architecture right after finding the tools; stub those so this runs anywhere. + with unittest.mock.patch.object(runner, "find_clang", return_value="clang"), \ + unittest.mock.patch.object(runner, "_find_lld", return_value="ld.lld"), \ + unittest.mock.patch.object(runner, "find_hip_dll", return_value="amdhip64_7.dll"): + with self.assertRaises(runner.Unavailable) as cm: + runner.Oracle(arch="gfx90a") + self.assertIn("gfx90a", str(cm.exception)) + def test_unknown_oracle_is_a_usage_error(self): r = subprocess.run([sys.executable, "-I", str(TOOLS / "salu_diff.py"), "--oracle", "gpu"], capture_output=True, text=True) self.assertEqual(r.returncode, 2) +def relocatable(sections, symbols): + """A little-endian ELF64 relocatable object: sections is [(name, bytes, address)], symbols [(name, section + number from 1, value)]. Only what drm.text_section reads is filled in.""" + names = [""] + [s[0] for s in sections] + [".symtab", ".strtab", ".shstrtab"] + shstr, name_at = b"", [] + for n in names: + name_at.append(len(shstr)) + shstr += n.encode() + b"\0" + strtab, symtab = b"\0", bytes(24) + for name, shndx, value in symbols: + symtab += struct.pack(" Load came back as garbage. +The runtime binds each image's view in its own format in the sampled array of its dimension, and the translator reads +UINT/SINT formats through uint/sint aliases of that array (docs/design.md, Typed image loads; SHADER-151): a float +fetch of an integer view is undefined in Vulkan. A d16 load used to skip the T# FORMAT branch and always read the float +sampled view, then pack f16: a Texture2D Load came back as garbage. """ import re @@ -19,7 +20,8 @@ def test_d16_image_load_reads_integer_views(make_shader, mask, dst): f"image_load {dst}, v[1:2], s[8:15] dmask:{mask} dim:SQ_RSRC_IMG_2D unorm d16\n" "s_waitcnt vmcnt(0)\nexp mrt0 v3, v4, v3, v4 done vm\ns_endpgm\n", name="ps_d16_load") spv = sh.translate() - reads = re.findall(r"OpImageRead %(\w+) ", spv) - assert "v4uint_st" in reads and "v4int_st" in reads, "d16 image_load never reads the uint/sint views" + fetches = re.findall(r"OpImageFetch %(\w+) ", spv) + assert "v4uint_st" in fetches and "v4int_st" in fetches, "d16 image_load never reads the uint/sint views" + assert "OpImageRead" not in spv and "StorageImageReadWithoutFormat" not in spv # sampled aliases, not storage assert "PackHalf2x16" not in spv # the float branch keeps the integer RTE f16 pack (#489) sh.validate(spv) diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py new file mode 100644 index 000000000..d89120bfe --- /dev/null +++ b/tests/test_image_load_typed.py @@ -0,0 +1,282 @@ +"""Typed image_load in tools/rdna2spirv.py reads every format from the sampled array (SHADER-151; standard library only: +no GPU, LLVM or game files; SPIRV-Tools only for the optional validation test). + + python -I tests/test_image_load_typed.py + +The image's numeric type lives in the T# (word 1 FORMAT [28:20]), so the translator branches on it at run time. +UINT and SINT formats are fetched through uint and sint aliases of the dimension's sampled array (same set and +binding), everything else and a lookup miss (index 0, the RGBA8_UNORM fallback) through the float array. Nothing +reads a storage image, so a shader that only loads declares no StorageImageReadWithoutFormat (which Intel Xe-LP +lacks, #619) and no StorageImageWriteWithoutFormat. These tests translate small pixel shaders and check the SPIR-V: +the capabilities, which binding and component type each fetch reads, and, with a small evaluator of the code that +picks the branch, the branch taken for all 512 FORMAT values with a hit and with a miss. +runtime/test/shaders/cs_imgload.asm checks the result on a GPU (vk_store_test load). +""" +import os +import re +import shutil +import struct +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.join(ROOT, "tools")) +import rdna2spirv # noqa: E402 + +EMPTY_DXBC = b"DXBC" + bytes(16) + struct.pack(" (address registers, sampled binding, SPIR-V Dim, arrayed) +DIMS = {"2D": ("v[4:5]", 0, "2D", "0"), "2D_ARRAY": ("v[4:6]", 3, "2D", "1"), + "3D": ("v[4:6]", 6, "3D", "0"), "1D": ("v4", 5, "1D", "0")} +STORAGE_IMAGE_CAPS = {"StorageImageReadWithoutFormat", "StorageImageWriteWithoutFormat", "Image1D"} + + +def translate(lines): + """SPIR-V assembly text of a pixel shader made of these instruction lines (and an export of v3).""" + with tempfile.TemporaryDirectory() as tmp: + os.mkdir(os.path.join(tmp, "disasm")) + with open(os.path.join(tmp, "ps_load.dxbc"), "wb") as f: + f.write(EMPTY_DXBC) + path = os.path.join(tmp, "disasm", "ps_load.s") + with open(path, "w", encoding="utf-8") as f: + f.write("; ps_load code 0x0..0x100\n" + "".join("\t" + ln + "\n" for ln in lines + EPILOGUE)) + return rdna2spirv.translate(path) + + +def load_shader(dim, dmask=0xF): + addr = DIMS[dim][0] + return translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 0", + f"image_load v[0:3], {addr}, s[0:7] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_{dim} unorm", + "s_waitcnt vmcnt(0)"]) + + +class Module: + """The instructions of a SPIR-V assembly text by result id, its decorations and capabilities.""" + + def __init__(self, text): + self.text = text + self.defs, self.binding, self.order = {}, {}, [] + self.caps = set(re.findall(r"^\s*OpCapability (\w+)", text, re.M)) + for line in text.splitlines(): + m = re.match(r"\s*(%\w+) = (Op\w+)\s*(.*)$", line) + if m: + self.defs[m.group(1)] = (m.group(2), m.group(3).split()) + self.order.append((m.group(1), m.group(2), m.group(3).split())) + continue + m = re.match(r"\s*OpDecorate (%\w+) Binding (\d+)$", line) + if m: + self.binding[m.group(1)] = int(m.group(2)) + m = re.match(r"\s*(OpBranchConditional) (.*)$", line) + if m: + self.order.append((None, m.group(1), m.group(2).split())) + + def fetches(self): + """(result id, image variable, OpTypeImage operands) of every OpImageFetch.""" + out = [] + for rid, op, args in self.order: + if op != "OpImageFetch": + continue + load_op, load = self.defs[args[1]] + assert load_op == "OpLoad", load_op + chain_op, chain = self.defs[load[1]] + assert chain_op == "OpAccessChain", chain_op + out.append((rid, chain[1], self.defs[load[0]][1])) + return out + + def value(self, x, word1, index): + """Evaluate the uint/bool id x given the T#'s word 1 and the bindless index of the lookup.""" + if x in ("%true", "%false"): + return x == "%true" + op, a = self.defs[x] + if op == "OpConstant": + return int(a[1], 0) + if op == "OpConstantTrue": + return True + if op == "OpFunctionCall" and a[1] == "%desc_lookup_fn": + return index + if op == "OpLoad": + ptr_op, p = self.defs[a[1]] + assert ptr_op == "OpAccessChain", ptr_op + if p[1] == "%sgpr": + assert self.value(p[2], word1, index) == 1, "only T# word 1 is read" + return word1 + var_op, v = self.defs[p[1]] + assert var_op == "OpVariable" and v[1] == "Private", (var_op, v) + words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr + return self.value(words[self.value(p[2], word1, index)], word1, index) + u = [self.value(y, word1, index) for y in a[1:]] + if op == "OpBitFieldUExtract": + return (u[0] >> u[1]) & ((1 << u[2]) - 1) + if op == "OpShiftRightLogical": + return u[0] >> u[1] + if op == "OpBitwiseAnd": + return u[0] & u[1] + if op == "OpINotEqual": + return u[0] != u[1] + if op == "OpLogicalAnd": + return u[0] and u[1] + raise AssertionError(f"unexpected {op} in the branch condition") + + def branch(self, word1, index): + """'sint', 'uint' or 'float': which fetch the typed load's two selections lead to.""" + conds, last = {}, None + for rid, op, args in self.order: + if op == "OpBranchConditional": + last = args[0] + elif op == "OpAccessChain" and re.fullmatch(r"%itx[12]_\d", args[1]): + conds["sint" if args[1].startswith("%itx2") else "uint"] = last + assert set(conds) == {"sint", "uint"}, conds + for kind in ("sint", "uint"): # the sint selection encloses the uint one + if self.value(conds[kind], word1, index): + return kind + return "float" + + +def format_class(fmt): + name = rdna2spirv.GFX10_FORMATS.get(fmt, "") + return "uint" if name.endswith("_UINT") else "sint" if name.endswith("_SINT") else "float" + + +class LoadOnlyShaders(unittest.TestCase): + def test_2d_explicit_mip_reaches_every_typed_fetch(self): + m = Module(translate(["image_load_mip v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D", + "s_waitcnt vmcnt(0)"])) + fetches = m.fetches() + self.assertEqual({image[0] for _, _, image in fetches}, {"%float", "%uint", "%int"}) + for rid, var, _ in fetches: + self.assertEqual(m.binding[var], 0) + operands = m.defs[rid][1] + self.assertEqual(operands[-2], "Lod") + op, cast = m.defs[operands[-1]] + self.assertEqual(op, "OpBitcast") + op, load = m.defs[cast[1]] + self.assertEqual(op, "OpLoad") + op, source = m.defs[load[1]] + self.assertEqual((op, source[1]), ("OpAccessChain", "%vgpr")) + self.assertEqual(m.value(source[2], 0, 0), 6) + + def test_2d_explicit_mip_d16_packs_only_selected_components(self): + listing = ["image_load_mip v0, v[4:6], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D d16", + "s_waitcnt vmcnt(0)"] + m = Module(translate(listing)) + self.assertEqual({image[0] for _, _, image in m.fetches()}, {"%float", "%uint", "%int"}) + for rid, _, _ in m.fetches(): + bits, = (r for r, op, args in m.order if op == "OpBitcast" and args[1] == rid) + components = [int(args[2]) for _, op, args in m.order if op == "OpCompositeExtract" and args[1] == bits] + self.assertEqual(components, [0, 3]) + # All three branches write just v0: R in the low half and A in the high half. + writes = [m.defs[ptr][1] for ptr in re.findall(r"^\s*OpStore (%\w+) ", m.text, re.MULTILINE)] + vgprs = [m.value(pointer[2], 0, 0) for pointer in writes if len(pointer) > 2 and pointer[1] == "%vgpr"] + self.assertEqual(vgprs.count(0), 3) + self.assertNotIn(1, vgprs) + + def test_no_storage_image_capability_and_no_storage_binding(self): + for dim in DIMS: + with self.subTest(dim=dim): + m = Module(load_shader(dim)) + self.assertFalse(m.caps & STORAGE_IMAGE_CAPS, sorted(m.caps)) + self.assertNotIn("OpImageRead", m.text) + # Set 0 bindings 4 and 7-19 are storage images (runtime/src/vulkan_bindless.h). + self.assertEqual(set(m.binding.values()), {0, 1, 2, DIMS[dim][1]}) + + def test_each_component_type_is_fetched_from_the_sampled_binding_of_its_dimension(self): + for dim, (_, binding, sdim, arrayed) in DIMS.items(): + with self.subTest(dim=dim): + m = Module(load_shader(dim)) + seen = {} + for _, var, image in m.fetches(): + # OpTypeImage + self.assertEqual(image[1:], [sdim, "0", arrayed, "0", "1", "Unknown"]) + self.assertEqual(m.binding[var], binding) + seen[image[0]] = var + self.assertEqual(set(seen), {"%int", "%uint", "%float"}) + self.assertEqual(len(set(seen.values())), 3, "one variable per component type") + + def test_the_tsharp_format_picks_the_fetch_and_a_miss_takes_the_float_one(self): + """All 512 FORMAT values: the 30 UINT and 15 SINT GFX10 formats read as uint and sint when the T# was found + (index 5), everything reads float on a miss (index 0). Bits outside FORMAT [28:20] don't matter.""" + m = Module(load_shader("2D")) + counts = {"uint": 0, "sint": 0, "float": 0} + for fmt in range(512): + want = format_class(fmt) + counts[want] += 1 + for other in (0, 0xE00FFFFF): + word1 = (fmt << 20) | other + self.assertEqual(m.branch(word1, 5), want, f"FORMAT {fmt} word1 {word1:#x}") + self.assertEqual(m.branch(word1, 0), "float", f"FORMAT {fmt} miss") + self.assertEqual(counts, {"uint": 30, "sint": 15, "float": 512 - 45}) + + def test_only_the_dmask_components_are_written(self): + m = Module(load_shader("2D", dmask=0x9)) + for rid, _, _ in m.fetches(): + uses = [args for _, op, args in m.order if op == "OpBitcast" and rid in args] + self.assertEqual(len(uses), 1) + bits = next(r for r, op, args in m.order if op == "OpBitcast" and args[1] == rid) + comps = sorted(int(args[2]) for _, op, args in m.order if op == "OpCompositeExtract" and args[1] == bits) + self.assertEqual(comps, [0, 3], "dmask 0x9: R into v0, A into v1") + + +class TypedGatherShaders(unittest.TestCase): + def test_2d_gather_picks_the_sampled_type_and_selected_component(self): + for dst, modifier in (("v[0:3]", ""), ("v[0:1]", " d16")): + with self.subTest(modifier=modifier): + m = Module(translate([f"image_gather4_lz {dst}, v[4:5], s[0:7], s[8:11] " + f"dmask:0x2 dim:SQ_RSRC_IMG_2D{modifier}", "s_waitcnt vmcnt(0)"])) + types = set() + for rid, op, args in m.order: + if op != "OpImageGather": + continue + types.add(args[0]) + self.assertEqual(m.value(args[3], 0, 0), 1) # green + sampled_op, sampled = m.defs[args[1]] + self.assertEqual(sampled_op, "OpSampledImage") + image_load, image = m.defs[sampled[1]] + self.assertEqual(image_load, "OpLoad") + _, chain = m.defs[image[1]] + self.assertEqual(m.binding[chain[1]], 0) + if modifier and args[0] != "%v4float": + def uses(opcode, operand): + return [(r, a) for r, op, a in m.order if op == opcode and operand in a[1:]] + ((raw, _),) = uses("OpBitcast", rid) + taps = {int(a[2]): r for r, a in uses("OpCompositeExtract", raw)} + self.assertEqual(set(taps), {0, 1, 2, 3}) + for tap in (0, 2): + ((lo, mask),) = uses("OpBitwiseAnd", taps[tap]) + ((hi, shift),) = uses("OpShiftLeftLogical", taps[tap + 1]) + self.assertEqual(m.value(mask[2], 0, 0), 0xffff) + self.assertEqual(m.value(shift[2], 0, 0), 16) + self.assertTrue(any(hi in a for _, a in uses("OpBitwiseOr", lo))) + + self.assertEqual(types, {"%v4uint_st", "%v4int_st", "%v4float"}) + + +class StoreAndLoad(unittest.TestCase): + def test_a_shader_that_also_stores_needs_only_the_write_feature(self): + m = Module(translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", + "image_store v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm", + "image_load v[0:3], v[4:5], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm", + "s_waitcnt vmcnt(0)"])) + self.assertIn("StorageImageWriteWithoutFormat", m.caps) + self.assertNotIn("StorageImageReadWithoutFormat", m.caps) + self.assertNotIn("OpImageRead", m.text) + self.assertEqual(set(m.binding.values()), {0, 1, 2, 8, 9, 10}) + + +@unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") +class Validation(unittest.TestCase): + def test_spirv_val_accepts_every_dimension(self): + with tempfile.TemporaryDirectory() as tmp: + for dim in DIMS: + with self.subTest(dim=dim): + sa, sv = os.path.join(tmp, f"{dim}.spvasm"), os.path.join(tmp, f"{dim}.spv") + with open(sa, "w", encoding="utf-8") as f: + f.write(load_shader(dim)) + result = rdna2spirv.assemble_spirv(sa, sv) + self.assertEqual(result.returncode, 0, result.stderr + result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_make_game_argparse.py b/tests/test_make_game_argparse.py index 935fc27ea..020e00338 100644 --- a/tests/test_make_game_argparse.py +++ b/tests/test_make_game_argparse.py @@ -26,7 +26,7 @@ class ArgparseDefaultsAndTypesTest(unittest.TestCase): with patch("make_game.below_normal"): with patch("make_game.choose_game", return_value=os.path.abspath("C:/dummy_game")): with patch("make_game.check", return_value={"expected_exe": "game.exe"}): - with patch("make_game.preflight"): + with patch("make_game.preflight"), patch("make_game.cross_build_missing", return_value=[]): with patch("make_game.shaders"): with patch("make_game.assets"): with patch("make_game.runtime"): @@ -241,9 +241,10 @@ class StageValidationAndSequencingTest(unittest.TestCase): expected_calls = [ call.shaders(os.path.abspath(self.game_dir), os.path.abspath(self.work_dir), unittest.mock.ANY, - emulate=unittest.mock.ANY, keep_emulated=True), + emulate=unittest.mock.ANY, keep_emulated=True, fallbacks=unittest.mock.ANY), call.assets(os.path.abspath(self.game_dir), os.path.abspath(self.work_dir), False, unittest.mock.ANY), - call.runtime(os.path.abspath(self.game_dir), os.path.abspath(self.out_dir), unittest.mock.ANY, None), + call.runtime(os.path.abspath(self.game_dir), os.path.abspath(self.out_dir), unittest.mock.ANY, None, + unittest.mock.ANY), call.pipelines(os.path.abspath(self.work_dir), os.path.abspath(self.out_dir), unittest.mock.ANY), ] self.assertEqual(manager.mock_calls, expected_calls) @@ -321,9 +322,9 @@ class JobsHandlingTest(unittest.TestCase): probe.assert_called_once_with("auto") mock_preflight.assert_called_once_with( ["shaders"], os.path.abspath(work), False, None, - emulate=True, keep_emulated=True) + emulate=True, keep_emulated=True, fallbacks=(), jobs=6) mock_shaders.assert_called_once_with(os.path.abspath(game), os.path.abspath(work), 6, - emulate=True, keep_emulated=True) + emulate=True, keep_emulated=True, fallbacks=()) def test_custom_jobs_forwarded_to_assets(self): with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/test_make_game_pipeline_preflight.py b/tests/test_make_game_pipeline_preflight.py index 31db9a849..34074ed00 100644 --- a/tests/test_make_game_pipeline_preflight.py +++ b/tests/test_make_game_pipeline_preflight.py @@ -19,7 +19,7 @@ if ROOT not in sys.path: import make_game # noqa: E402 -class PipelinePreflightTest(unittest.TestCase): +class PreflightEnv: def setUp(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) @@ -43,8 +43,10 @@ class PipelinePreflightTest(unittest.TestCase): self.assertIn(match, err.getvalue()) return err.getvalue() + +class PipelinePreflightTest(PreflightEnv, unittest.TestCase): def test_pipelines_without_checker_fails_in_preflight(self): - with mock.patch.object(make_game, "pipeline_check_exe", return_value=None): + with mock.patch("os.name", "nt"), mock.patch.object(make_game, "pipeline_check_exe", return_value=None): err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") self.assertIn("Install these first, then run the build again:", err) @@ -55,6 +57,7 @@ class PipelinePreflightTest(unittest.TestCase): argv = ["make_game.py", "--game", game, "--work", self.work, "--out", out, "--stages", "shaders,pipelines"] with mock.patch.object(sys, "argv", argv), \ + mock.patch("os.name", "nt"), \ mock.patch.object(make_game, "below_normal"), \ mock.patch.object(make_game, "check", return_value={"expected_exe": "game.exe"}), \ mock.patch.object(make_game, "pipeline_check_exe", return_value=None), \ @@ -96,12 +99,65 @@ class PipelinePreflightTest(unittest.TestCase): self.assertIn("vk_pipeline_check", err) def test_missing_checker_is_listed_with_other_missing_prerequisites(self): - with mock.patch("make_game.tool_available", return_value=False), \ + with mock.patch("os.name", "nt"), mock.patch("make_game.tool_available", return_value=False), \ mock.patch.object(make_game, "pipeline_check_exe", return_value=None): err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") self.assertIn("llvm-mc (LLVM 21+ with the AMDGPU target)", err) self.assertEqual(err.count("vk_pipeline_check"), 1) + +class LinuxPipelineCheckTest(PreflightEnv, unittest.TestCase): + """Off Windows preflight builds the checker itself once every other prerequisite is there.""" + + def setUp(self): + super().setUp() + for patcher in (mock.patch("os.name", "posix"), + mock.patch.object(make_game, "pipeline_check_exe", return_value=None)): + patcher.start() + self.addCleanup(patcher.stop) + + def test_builds_the_checker_after_the_checks(self): + with mock.patch.object(make_game, "pipeline_check_exe", side_effect=[None, None, "/bin/vk_pipeline_check"]), \ + mock.patch.object(make_game, "build_pipeline_check") as build: + make_game.preflight(["pipelines"], self.work, jobs=3) + build.assert_called_once_with(3) + + def test_a_checker_built_where_it_isnt_looked_for_fails_in_preflight(self): + with mock.patch.object(make_game, "build_pipeline_check") as build: + self.assert_preflight_fails(["shaders", "pipelines"], "delete runtime/build/linux") + build.assert_called_once() + + def test_without_cmake_nothing_is_built(self): + with mock.patch("shutil.which", side_effect=lambda t: None if t == "cmake" else "/bin/tool"), \ + mock.patch.object(make_game, "build_pipeline_check") as build: + err = self.assert_preflight_fails(["pipelines"], "CMake 3.24 or newer") + self.assertIn("vk_pipeline_check", err) + build.assert_not_called() + + def test_another_missing_prerequisite_stops_before_the_build(self): + with mock.patch("make_game.tool_available", return_value=False), \ + mock.patch.object(make_game, "build_pipeline_check") as build: + self.assert_preflight_fails(["shaders", "pipelines"], "llvm-mc") + build.assert_not_called() + + def test_a_built_checker_is_not_rebuilt(self): + with mock.patch.object(make_game, "pipeline_check_exe", return_value="/bin/vk_pipeline_check"), \ + mock.patch.object(make_game, "build_pipeline_check") as build: + make_game.preflight(["pipelines"], self.work) + build.assert_not_called() + + def test_the_build_uses_the_readme_folder(self): + with mock.patch.object(make_game, "ROOT", self.root), \ + mock.patch.object(make_game, "log"), \ + mock.patch.object(make_game, "run") as run: + make_game.build_pipeline_check(2) + configure, build = (c.args[0] for c in run.call_args_list) + folder = os.path.join(self.root, "runtime", "build", "linux") + self.assertEqual(configure[:5], ["cmake", "-S", os.path.join(self.root, "runtime"), "-B", folder]) + self.assertEqual(build, ["cmake", "--build", folder, "--parallel", "2", "--target", "vk_pipeline_check"]) + self.assertIn("Vulkan headers", run.call_args_list[1].kwargs["hint"]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_make_game_platform.py b/tests/test_make_game_platform.py index 01c7afb4a..deb434517 100644 --- a/tests/test_make_game_platform.py +++ b/tests/test_make_game_platform.py @@ -29,11 +29,12 @@ class DefaultStagesTest(unittest.TestCase): def tearDown(self): self.tmp.cleanup() - def run_main(self, os_name, *args): + def run_main(self, os_name, *args, lacking=("clang-cl",)): argv = ["make_game.py", "--game", self.game, "--out", os.path.join(self.tmp.name, "out"), *args] mocks = {n: mock.MagicMock() for n in STAGE_FUNCS} with mock.patch.object(sys, "argv", argv), \ mock.patch.object(make_game.os, "name", os_name), \ + mock.patch.object(make_game, "cross_build_missing", return_value=list(lacking)), \ mock.patch.object(make_game, "below_normal"), \ mock.patch.object(make_game, "check", return_value={"expected_exe": "game.exe"}), \ mock.patch.object(make_game, "preflight") as preflight, \ @@ -42,11 +43,16 @@ class DefaultStagesTest(unittest.TestCase): self.assertEqual(make_game.main(), 0) return preflight.call_args.args[0], {n: m.called for n, m in mocks.items()} - def test_default_stages_leave_runtime_out_off_windows(self): + def test_default_stages_leave_runtime_out_off_windows_without_the_cross_build(self): stages, ran = self.run_main("posix") self.assertEqual(stages, ["check", "shaders", "assets", "pipelines"]) self.assertEqual(ran, {"shaders": True, "assets": True, "runtime": False, "pipelines": True}) + def test_default_stages_keep_runtime_off_windows_with_the_cross_build(self): + stages, ran = self.run_main("posix", lacking=()) + self.assertEqual(stages, make_game.STAGES) + self.assertTrue(ran["runtime"]) + def test_default_stages_keep_runtime_on_windows(self): stages, ran = self.run_main("nt") self.assertEqual(stages, make_game.STAGES) @@ -67,19 +73,106 @@ class DefaultStagesTest(unittest.TestCase): class PreflightTest(unittest.TestCase): - def test_runtime_asked_for_off_windows_fails_before_any_work(self): + def preflight(self, lacking, work): + with mock.patch.object(make_game.os, "name", "posix"), \ + mock.patch.object(make_game.sys, "version_info", (3, 12, 0)), \ + mock.patch.object(make_game, "cross_build_missing", return_value=lacking), \ + mock.patch.object(make_game, "cross_configure") as configure, \ + mock.patch.object(make_game, "visual_cpp_tools_ok") as vs: + make_game.preflight(["runtime"], work) + vs.assert_not_called() + return configure + + def test_runtime_off_windows_without_the_cross_build_fails_before_any_work(self): err = io.StringIO() with tempfile.TemporaryDirectory() as work, \ - mock.patch.object(make_game.os, "name", "posix"), \ mock.patch("sys.stderr", err), \ mock.patch.object(make_game.shutil, "disk_usage") as usage: with self.assertRaises(SystemExit) as ctx: - make_game.preflight(["shaders", "runtime"], os.path.join(work, "w")) + self.preflight(["clang-cl", "the xwin SDK"], os.path.join(work, "w")) self.assertEqual(ctx.exception.code, 1) - self.assertIn("runtime stage builds on Windows only", err.getvalue()) + self.assertIn("clang-cl (for the runtime stage, or pass --runtime-build)", err.getvalue()) + self.assertIn("the xwin SDK (for the runtime stage", err.getvalue()) usage.assert_not_called() self.assertFalse(os.path.exists(os.path.join(work, "w"))) + def test_runtime_off_windows_configures_the_cross_build_before_any_work(self): + with tempfile.TemporaryDirectory() as work: + self.preflight([], os.path.join(work, "w")).assert_called_once_with() + + +class CrossBuildMissingTest(unittest.TestCase): + def setUp(self): + self.sdk = self.enterContext(tempfile.TemporaryDirectory()) + os.makedirs(os.path.join(self.sdk, "VC", "Tools", "MSVC")) + os.makedirs(os.path.join(self.sdk, "Windows Kits", "10", "Lib", "10.0.26100", "um", "x64")) + + def missing(self, have=("cmake", *make_game.CROSS_TOOLS), major=23, sdk=None, configured=None): + def which(t): + return t if t.startswith("/") and t in have else f"/usr/bin/{t}" if t in have else None + majors = major if callable(major) else (lambda exe="clang-cl": major) + with mock.patch.object(make_game.shutil, "which", side_effect=which), \ + mock.patch.object(make_game, "clang_cl_major", side_effect=majors) as self.major, \ + mock.patch.object(make_game, "configured_cross_tools", return_value=configured or {}), \ + mock.patch.dict(os.environ, {"XWIN_DIR": sdk if sdk is not None else self.sdk}): + return make_game.cross_build_missing() + + def test_a_full_versioned_set_counts(self): + self.assertEqual(self.missing(have=("cmake", *(f"{t}-21" for t in make_game.CROSS_TOOLS))), []) + self.major.assert_called_once_with("clang-cl-21") + + def test_an_old_plain_set_does_not_hide_a_newer_versioned_one(self): + have = ("cmake", *make_game.CROSS_TOOLS, *(f"{t}-21" for t in make_game.CROSS_TOOLS)) + self.assertEqual(self.missing(have=have, major=lambda exe="clang-cl": 18 if exe == "clang-cl" else 21), []) + + def test_versions_are_not_mixed_and_the_missing_one_is_named(self): + have = ("cmake", "clang-cl-21", "lld-link-21", "llvm-lib-21", "llvm-rc-21", "llvm-mt-20") + (item,) = self.missing(have=have) + self.assertTrue(item.startswith("llvm-mt-21: LLVM 19 or newer"), item) + + def test_a_configured_build_folder_needs_only_its_own_tools(self): + tools = {"CMAKE_CXX_COMPILER": "/opt/llvm-21/bin/clang-cl", "CMAKE_LINKER": "/opt/llvm-21/bin/lld-link", + "CMAKE_AR": "llvm-lib", "CMAKE_MT": "/opt/llvm-21/bin/llvm-mt", "CMAKE_RC_COMPILER": "llvm-rc"} + have = ("cmake", "llvm-lib", "llvm-rc", "/opt/llvm-21/bin/clang-cl", "/opt/llvm-21/bin/lld-link", + "/opt/llvm-21/bin/llvm-mt") + self.assertEqual(self.missing(have=have, configured=tools), []) + self.major.assert_not_called() + (item,) = self.missing(have=have[:-1], configured=tools) + self.assertTrue(item.startswith("/opt/llvm-21/bin/llvm-mt, which runtime/build/windows was configured with")) + self.assertIn("delete runtime/build/windows", item) + + def test_everything_there(self): + self.assertEqual(self.missing(), []) + + def test_missing_llvm_tools_are_named_together(self): + (item,) = self.missing(have=("cmake", "clang-cl", "llvm-lib", "llvm-rc", "llvm-mt")) + self.assertTrue(item.startswith("lld-link: LLVM 19 or newer")) + (item,) = self.missing(have=("cmake",)) + self.assertTrue(item.startswith(", ".join(make_game.CROSS_TOOLS) + ":")) + + def test_clang_older_than_19_is_refused(self): + (item,) = self.missing(major=18) + self.assertIn("this one is 18", item) + self.assertEqual(self.missing(major=None), []) + + def test_cmake_and_the_sdk(self): + missing = self.missing(have=make_game.CROSS_TOOLS, sdk=os.path.join(self.sdk, "nothing")) + self.assertEqual(len(missing), 2) + self.assertEqual(missing[0], "CMake 3.24 or newer") + self.assertIn("xwin", missing[1]) + + def test_xwin_dir_defaults_to_the_documented_folder(self): + home = self.enterContext(tempfile.TemporaryDirectory()) + env = {k: v for k, v in os.environ.items() if k != "XWIN_DIR"} + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.object(make_game.os.path, "expanduser", side_effect=lambda p: p.replace("~", home, 1)): + self.assertIsNone(make_game.xwin_dir()) + sdk = os.path.join(home, ".local", "share", "xwin-sdk") + os.makedirs(os.path.join(sdk, "VC", "Tools", "MSVC")) + self.assertIsNone(make_game.xwin_dir()) + os.makedirs(os.path.join(sdk, "Windows Kits", "10", "Lib", "10.0.26100", "um", "x64")) + self.assertEqual(make_game.xwin_dir(), sdk) + class RuntimeBuildPreflightTest(unittest.TestCase): def preflight(self, build, files, err=None): @@ -151,6 +244,102 @@ class RuntimePackagingTest(unittest.TestCase): self.assertFalse(os.path.exists(self.out)) +class ConfiguredCrossToolsTest(unittest.TestCase): + def test_reads_cmakes_compiler_files_newest_last(self): + root = self.enterContext(tempfile.TemporaryDirectory()) + files = os.path.join(root, "runtime", "build", "windows", "CMakeFiles") + with mock.patch.object(make_game, "ROOT", root): + self.assertEqual(make_game.configured_cross_tools(), {}) + for version, compiler in (("3.31.0", "/old/clang-cl"), ("4.5.1", "/usr/bin/clang-cl")): + os.makedirs(os.path.join(files, version)) + with open(os.path.join(files, version, "CMakeCXXCompiler.cmake"), "w", encoding="utf-8") as f: + f.write(f'set(CMAKE_CXX_COMPILER "{compiler}")\nset(CMAKE_CXX_COMPILER_ARG1 "")\n' + 'set(CMAKE_AR "llvm-lib")\nset(CMAKE_LINKER "/usr/bin/lld-link")\n' + 'set(CMAKE_MT "/usr/bin/llvm-mt")\n') + os.utime(os.path.join(files, version, "CMakeCXXCompiler.cmake"), (1, 1 if version == "3.31.0" else 2)) + with open(os.path.join(files, "4.5.1", "CMakeRCCompiler.cmake"), "w", encoding="utf-8") as f: + f.write('set(CMAKE_RC_COMPILER "llvm-rc")\n') + with mock.patch.object(make_game, "ROOT", root): + self.assertEqual(make_game.configured_cross_tools(), { + "CMAKE_CXX_COMPILER": "/usr/bin/clang-cl", "CMAKE_AR": "llvm-lib", "CMAKE_LINKER": "/usr/bin/lld-link", + "CMAKE_MT": "/usr/bin/llvm-mt", "CMAKE_RC_COMPILER": "llvm-rc"}) + + +class CrossBuildTest(unittest.TestCase): + def setUp(self): + self.root = self.enterContext(tempfile.TemporaryDirectory()) + self.build = os.path.join(self.root, "runtime", "build", "windows") + self.game = os.path.join(self.root, "game") + self.out = os.path.join(self.root, "out") + os.makedirs(self.game) + + def runtime(self, xwin="/sdk", ninja=True, suffix="", configured=None): + def which(t): + if t == "ninja": + return "/usr/bin/ninja" if ninja else None + return f"/usr/bin/{t}" if suffix else None + def fake_run(args, hint="", **kw): + if args[1] == "--build": + os.makedirs(self.build, exist_ok=True) + for name in make_game.RUNTIME_FILES: + with open(os.path.join(self.build, name), "wb") as f: + f.write(name.encode()) + with mock.patch.object(make_game.os, "name", "posix"), \ + mock.patch.object(make_game, "ROOT", self.root), \ + mock.patch.object(make_game, "xwin_dir", return_value=xwin), \ + mock.patch.object(make_game.shutil, "which", side_effect=which), \ + mock.patch.object(make_game, "cross_tool_suffix", return_value=suffix), \ + mock.patch.object(make_game, "configured_cross_tools", return_value=configured or {}), \ + mock.patch.object(make_game, "run", side_effect=fake_run) as self.run_mock, \ + mock.patch.object(make_game, "log"): + make_game.runtime(self.game, self.out, {"expected_exe": "game.exe"}, None, 4) + return [c.args[0] for c in self.run_mock.call_args_list] + + def test_cross_builds_the_loader_and_packages_it_for_wine(self): + configure, build = self.runtime() + toolchain = os.path.join(self.root, "runtime", "cmake", "clang-cl-xwin.cmake") + self.assertEqual(configure, ["cmake", "-S", os.path.join(self.root, "runtime"), "-B", self.build, + "-G", "Ninja", "-DCMAKE_BUILD_TYPE=RelWithDebInfo", + "--toolchain", toolchain, "-DXWIN_DIR=/sdk"]) + self.assertEqual(build, ["cmake", "--build", self.build, "--parallel", "4", + "--target", "gta6rt", "gta6rt_tls_host"]) + for name in make_game.RUNTIME_FILES: + with open(os.path.join(self.out, name), "rb") as f: + self.assertEqual(f.read(), name.encode()) + self.assertTrue(os.path.isfile(os.path.join(self.out, "gta6rt.sh"))) + + def test_versioned_tools_are_passed_until_the_folder_records_its_tools(self): + for cache in (False, True): + if cache: + open(os.path.join(self.build, "CMakeCache.txt"), "w").close() + configure, _ = self.runtime(suffix="-21") + for var, name in make_game.CROSS_VARS.items(): + self.assertIn(f"-DCMAKE_{var}=/usr/bin/{name}-21", configure) + configure, _ = self.runtime(suffix="-21", configured={"CMAKE_CXX_COMPILER": "/usr/bin/clang-cl-21"}) + self.assertFalse(any(a.startswith("-DCMAKE_CXX_COMPILER") for a in configure)) + + def test_without_ninja_cmake_picks_the_generator(self): + configure, _ = self.runtime(ninja=False) + self.assertNotIn("-G", configure) + self.assertIn("-DCMAKE_BUILD_TYPE=RelWithDebInfo", configure) + + def test_an_existing_build_folder_keeps_its_generator_and_build_type(self): + os.makedirs(self.build) + open(os.path.join(self.build, "CMakeCache.txt"), "w").close() + configure, _ = self.runtime() + self.assertNotIn("-G", configure) + self.assertFalse(any(a.startswith("-DCMAKE_BUILD_TYPE") for a in configure)) + self.assertIn("-DXWIN_DIR=/sdk", configure) + + def test_without_an_sdk_nothing_runs(self): + err = io.StringIO() + with mock.patch("sys.stderr", err), self.assertRaises(SystemExit): + self.runtime(xwin=None) + self.run_mock.assert_not_called() + self.assertIn("xwin", err.getvalue()) + self.assertFalse(os.path.exists(self.out)) + + class RuntimeBuildPackagingTest(unittest.TestCase): def test_off_windows_copies_the_build_and_writes_a_wine_launcher(self): with tempfile.TemporaryDirectory() as root: diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py index 91f2cca06..9fdcfb0bb 100644 --- a/tests/test_make_game_preflight.py +++ b/tests/test_make_game_preflight.py @@ -323,6 +323,28 @@ class ToolchainDetectionTest(PreflightTestBase): self.assertFalse(make_game.tool_available(" ")) self.assertFalse(make_game.tool_available('""')) + APPDATA_ENV = {"LOCALAPPDATA": r"C:\Users\u\AppData\Local", "APPDATA": r"C:\Users\u\AppData\Roaming"} + + def test_appdata_hint_names_the_folder_llvm_mc_is_in(self): + with mock.patch("os.name", "nt"), mock.patch.dict(os.environ, self.APPDATA_ENV): + for cmd, var in ((r"C:\Users\u\AppData\Local\Leonida\llvm-mc\llvm-mc.exe", "LOCALAPPDATA"), + (r'"c:\users\U\appdata\roaming\llvm\llvm-mc.exe"', "APPDATA")): + with self.subTest(cmd=cmd): + hint = make_game.appdata_hint(cmd) + self.assertIn(f"LLVM_MC points into %{var}%", hint) + self.assertIn(r"%USERPROFILE%\.leonida\llvm-mc", hint) + + def test_appdata_hint_is_empty_outside_appdata(self): + with mock.patch("os.name", "nt"), mock.patch.dict(os.environ, self.APPDATA_ENV): + for cmd in ("llvm-mc", r"D:\Tools\llvm-mc\llvm-mc.exe", r"C:\Users\u\.leonida\llvm-mc\llvm-mc.exe", + r"C:\Users\u\AppData\LocalLow\llvm-mc.exe", "wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"): + with self.subTest(cmd=cmd): + self.assertEqual(make_game.appdata_hint(cmd), "") + + def test_appdata_hint_is_empty_off_windows(self): + with mock.patch("os.name", "posix"), mock.patch.dict(os.environ, self.APPDATA_ENV): + self.assertEqual(make_game.appdata_hint(r"C:\Users\u\AppData\Local\llvm-mc.exe"), "") + def test_need_success_returns_tool(self): self.assertEqual(make_game.need(sys.executable, "Install python"), sys.executable) @@ -348,7 +370,7 @@ class PreflightPrerequisiteTest(PreflightTestBase): mock.patch("make_game.ensure_submodule", return_value=None), \ mock.patch("make_game.visual_cpp_tools_ok", return_value=True), \ mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 200 * 2**30, 800 * 2**30)): - # runtime is refused before any check off Windows (tests/test_make_game_platform.py) + # off Windows runtime checks the cross-build instead (tests/test_make_game_platform.py) stages = ["shaders", "assets"] + (["runtime"] if os.name == "nt" else []) make_game.preflight(stages, tmp_work, wav=True) @@ -369,6 +391,19 @@ class PreflightPrerequisiteTest(PreflightTestBase): self.assertIn(".NET 8 SDK", err) self.assertIn("Visual Studio 2022", err) + def test_preflight_explains_llvm_mc_hidden_in_appdata(self): + env = {"LOCALAPPDATA": r"C:\Users\u\AppData\Local", + "LLVM_MC": r"C:\Users\u\AppData\Local\Leonida\llvm-mc\llvm-mc.exe"} + with tempfile.TemporaryDirectory() as tmp_work, \ + mock.patch.dict(os.environ, env), \ + mock.patch("os.name", "nt"), \ + mock.patch("sys.version_info", (3, 12, 0)), \ + mock.patch("shutil.which", return_value="/usr/bin/tool"), \ + mock.patch("make_game.tool_available", return_value=False): + err = self.assert_fails(make_game.preflight, ["shaders"], tmp_work, + match="llvm-mc (LLVM 21+ with the AMDGPU target)") + self.assertIn("LLVM_MC points into %LOCALAPPDATA%", err) + def test_preflight_rejects_visual_studio_installer_without_cpp_tools(self): with tempfile.TemporaryDirectory() as tmp_work, \ mock.patch("os.name", "nt"), \ diff --git a/tests/test_make_game_resume.py b/tests/test_make_game_resume.py index 0e75c123a..f411f2be8 100644 --- a/tests/test_make_game_resume.py +++ b/tests/test_make_game_resume.py @@ -58,7 +58,8 @@ class ResumeShardsTest(unittest.TestCase): def test_a_fresh_run_starts_every_shard_and_records_its_plan(self): self.assertEqual(self.translate(3), [0, 1, 2]) with open(os.path.join(self.spirv, make_game.SHARD_PLAN), encoding="utf-8") as f: - self.assertEqual(json.load(f), {"jobs": 3, "wave64_emulate": False, "translator": "d1"}) + self.assertEqual(json.load(f), {"jobs": 3, "wave64_emulate": False, "fallbacks": [], + "translator": "d1"}) def test_a_stop_during_the_merge_only_merges_again(self): self.translate(3, tag="a") # the merge is mocked, so no index.json: as if stopped there @@ -130,7 +131,7 @@ class EarlierStepDropsThePlanTest(unittest.TestCase): json.dump({"jobs": 2, "wave64_emulate": False, "translator": "d1"}, f) seen = {} - def fake_translate(disasm, out, jobs, emulate=False): + def fake_translate(disasm, out, jobs, emulate=False, fallbacks=()): seen["plan"] = os.path.exists(plan) with mock.patch.object(make_game, "py"), mock.patch.object(make_game, "need"), \ mock.patch.object(make_game, "llvm_mc_signature", return_value="test llvm-mc 21"), \ diff --git a/tests/test_make_game_translator_flags.py b/tests/test_make_game_translator_flags.py new file mode 100644 index 000000000..0cf5f6ef5 --- /dev/null +++ b/tests/test_make_game_translator_flags.py @@ -0,0 +1,178 @@ +"""make_game.py forwards the translator's fallback flags (--no-float-controls, --bary-fallback, +--texel-offset-fallback, --mesh-compute) and records them beside the translation like the wave64 mode +(SHADER-99 follow-up to #664, @WHOISJARDAS's finding). + +Standard library only; no GPU, no Vulkan SDK, no game data: vulkaninfo and the translator are mocked. + + python -I tests/test_make_game_translator_flags.py +""" +import argparse +import json +import os +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +import make_game # noqa: E402 + +ALL_FLAGS = ("--no-float-controls", "--bary-fallback", "--texel-offset-fallback", "--mesh-compute") + + +class FallbackFlagsTest(unittest.TestCase): + """fallback_flags(): the flags the parsed arguments ask for, in FALLBACK_FLAGS order.""" + + def args_with(self, *flags): + return argparse.Namespace(**{attr: flag in flags for flag, attr in make_game.FALLBACK_FLAGS}) + + def test_none_by_default(self): + self.assertEqual(make_game.fallback_flags(self.args_with()), ()) + + def test_each_flag_alone(self): + for flag, _attr in make_game.FALLBACK_FLAGS: + self.assertEqual(make_game.fallback_flags(self.args_with(flag)), (flag,)) + + def test_all_flags_in_record_order(self): + self.assertEqual(make_game.fallback_flags(self.args_with(*reversed(ALL_FLAGS))), ALL_FLAGS) + + +class TranslateFallbacksTest(unittest.TestCase): + """translate() passes the fallback flags to every shard, and re-plans when they change.""" + + def shards_in(self, spirv, fallbacks=(), jobs=2, pre_parts=0): + started = [] + for i in range(pre_parts): + with open(os.path.join(spirv, f"index.part{i}.json"), "w", encoding="utf-8") as f: + json.dump({"old": True}, f) + + class FakeProc: + def __init__(self, args): + started.append(args) + + def wait(self): + return 0 + + with mock.patch.object(make_game.subprocess, "Popen", side_effect=FakeProc), \ + mock.patch.object(make_game, "py"), \ + mock.patch.object(make_game, "log", lambda *a: None): + make_game.translate("disasm", spirv, jobs, fallbacks=fallbacks) + return started + + def shards(self, fallbacks=(), jobs=2, pre_parts=0): + with tempfile.TemporaryDirectory() as spirv: + return self.shards_in(spirv, fallbacks=fallbacks, jobs=jobs, pre_parts=pre_parts) + + def test_shards_get_the_fallback_flags(self): + for args in self.shards(fallbacks=("--no-float-controls", "--bary-fallback")): + self.assertEqual(args.count("--no-float-controls"), 1, args) + self.assertEqual(args.count("--bary-fallback"), 1, args) + + def test_no_fallback_flags_by_default(self): + for args in self.shards(): + for flag in ALL_FLAGS: + self.assertNotIn(flag, args) + + def test_the_same_flags_keep_finished_shards(self): + with tempfile.TemporaryDirectory() as spirv: + self.shards_in(spirv, fallbacks=ALL_FLAGS) # writes the plan + for i in range(2): # as if the shards had finished + with open(os.path.join(spirv, f"index.part{i}.json"), "w", encoding="utf-8") as f: + json.dump({"old": True}, f) + again = self.shards_in(spirv, fallbacks=ALL_FLAGS) + self.assertEqual(again, []) + + def test_changing_fallbacks_discards_finished_shards(self): + again = self.shards(fallbacks=("--mesh-compute", "--bary-fallback"), pre_parts=2) + self.assertEqual(len(again), 2, again) # the parts were translated with other flags + + +class RecordedFlagsTest(unittest.TestCase): + """shaders() records the flags in spirv/translator_flags.txt and re-translates when they change.""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.work = tmp.name + self.dxbc = os.path.join(self.work, "shaders", "dxbc") + self.spirv = os.path.join(self.work, "shaders", "spirv") + + def touch(self, *parts): + p = os.path.join(*parts) + os.makedirs(os.path.dirname(p), exist_ok=True) + open(p, "w").close() + + def run_stage(self, fallbacks=()): + ran = [] + + def fake_py(tool, *args): + if tool == "shader_carve.py": + self.touch(self.dxbc, "index.json") + elif tool == "fssm_unpack.py": + self.touch(self.dxbc, "fssm_index.json") + elif tool == "shader_disasm.py": + os.makedirs(os.path.join(self.dxbc, "disasm"), exist_ok=True) + + def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): + ran.append("translate") + self.touch(spirv, "index.json") + + with mock.patch.object(make_game, "py", fake_py), \ + mock.patch.object(make_game, "need", lambda *a: None), \ + mock.patch.object(make_game, "translate", fake_translate), \ + mock.patch.object(make_game, "llvm_mc_signature", return_value="test llvm-mc 21"), \ + mock.patch.object(make_game, "log", lambda *a: None): + make_game.shaders(os.path.join(self.work, "game"), self.work, 2, fallbacks=fallbacks) + return ran + + def test_flags_are_recorded_beside_the_translation(self): + self.assertEqual(self.run_stage(fallbacks=("--no-float-controls",)), ["translate"]) + with open(os.path.join(self.spirv, "translator_flags.txt"), encoding="utf-8") as f: + self.assertEqual(f.read(), "--no-float-controls\n") + self.assertEqual(self.run_stage(fallbacks=("--no-float-controls",)), []) + + def test_changing_flags_translates_again(self): + self.run_stage(fallbacks=("--no-float-controls",)) + self.assertEqual(self.run_stage(fallbacks=("--no-float-controls", "--mesh-compute")), ["translate"]) + + def test_a_folder_from_before_the_file_existed_stays_reusable_without_flags(self): + self.run_stage() # no flags: an old folder (no translator_flags.txt) behaves the same + os.remove(os.path.join(self.spirv, "translator_flags.txt")) + self.assertEqual(self.run_stage(), []) + + def test_flags_asked_on_a_folder_translated_without_them_retranslate(self): + self.run_stage() + os.remove(os.path.join(self.spirv, "translator_flags.txt")) + self.assertEqual(self.run_stage(fallbacks=("--bary-fallback",)), ["translate"]) + + +class MainWiringTest(unittest.TestCase): + """main() parses the four flags and hands the same tuple to preflight() and shaders().""" + + def run_main(self, *extra_argv): + argv = ["make_game.py", "--stages", "shaders", *extra_argv] + with mock.patch.object(sys, "argv", argv), \ + mock.patch("make_game.below_normal"), \ + mock.patch("make_game.choose_game", return_value=os.path.abspath("C:/dummy_game")), \ + mock.patch("make_game.check", return_value={"expected_exe": "game.exe"}), \ + mock.patch("make_game.wave64_emulate", return_value=False), \ + mock.patch("make_game.preflight") as preflight, \ + mock.patch("make_game.shaders") as shaders, \ + mock.patch("make_game.log"): + self.assertEqual(make_game.main(), 0) + return preflight.call_args.kwargs["fallbacks"], shaders.call_args.kwargs["fallbacks"] + + def test_the_flags_reach_the_shaders_stage(self): + pre, sh = self.run_main("--no-float-controls", "--bary-fallback", "--mesh-compute") + self.assertEqual(pre, ("--no-float-controls", "--bary-fallback", "--mesh-compute")) + self.assertEqual(sh, pre) + + def test_no_flags_by_default(self): + pre, sh = self.run_main() + self.assertEqual(pre, ()) + self.assertEqual(sh, ()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_manifest_verifier.py b/tests/test_manifest_verifier.py index 7c0e5da13..97fa61d26 100644 --- a/tests/test_manifest_verifier.py +++ b/tests/test_manifest_verifier.py @@ -7,6 +7,7 @@ Zero game data used. """ from __future__ import annotations +import contextlib import hashlib import io import json @@ -115,6 +116,105 @@ class TestManifestVerifier(unittest.TestCase): entries = mv.load_manifest(flat_path) self.assertEqual(len(entries), len(SYNTHETIC_SIZES)) + def test_load_manifest_flat_skips_metadata_keys(self) -> None: + flat_path = os.path.join(self.root, "manifest_flat_meta.json") + doc = { + "created": "2026-11-22 00:00:00", + "title": "synthetic", + "version": "1.0", + "note": "top-level metadata", + "alpha.bin": { + "size": len(self.payloads["alpha.bin"]), + "sha256": hashlib.sha256(self.payloads["alpha.bin"]).hexdigest(), + }, + } + with open(flat_path, "w", encoding="utf-8") as f: + json.dump(doc, f) + entries = mv.load_manifest(flat_path) + self.assertEqual(list(entries.keys()), ["alpha.bin"]) + + def test_nested_manifest_verifies_files_named_like_metadata_keys(self) -> None: + meta_dir = os.path.join(self.root, "meta_game") + os.makedirs(meta_dir, exist_ok=True) + meta_files = { + "created": b"created-payload", + "title": b"title-payload!!", + "version": b"version-payload", + "note": b"note-payload", + } + for name, data in meta_files.items(): + with open(os.path.join(meta_dir, name), "wb") as f: + f.write(data) + manifest_p = self.write_manifest(os.path.join(self.root, "meta_manifest.json"), meta_files, wrapper=True) + + entries = mv.load_manifest(manifest_p) + self.assertEqual(sorted(entries.keys()), sorted(meta_files.keys())) + + ok_report = mv.verify_manifest(meta_dir, manifest_p, jobs=2, strict=True) + self.assertTrue(ok_report.passed) + self.assertEqual(sorted(ok_report.matched), sorted(meta_files.keys())) + self.assertEqual(ok_report.untracked, []) + + # Tamper (same size -> CHANGED), truncate (-> SIZE), remove (-> MISSING) + with open(os.path.join(meta_dir, "version"), "wb") as f: + f.write(b"VERSION-PAYLOAD") + with open(os.path.join(meta_dir, "title"), "wb") as f: + f.write(b"short") + os.remove(os.path.join(meta_dir, "note")) + + bad_report = mv.verify_manifest(meta_dir, manifest_p, jobs=1, strict=True) + self.assertFalse(bad_report.passed) + self.assertEqual(bad_report.problems, { + "note": "MISSING", + "title": "SIZE", + "version": "CHANGED", + }) + self.assertEqual(bad_report.matched, ["created"]) + self.assertEqual(bad_report.untracked, []) + + def test_load_manifest_non_dict_files_raises(self) -> None: + for bad_value in ("abc", [], 123, None): + with self.subTest(files_value=bad_value): + bad_path = os.path.join(self.root, f"bad_files_{type(bad_value).__name__}.json") + with open(bad_path, "w", encoding="utf-8") as f: + json.dump({"created": "2026-11-22", "files": bad_value}, f) + with self.assertRaisesRegex(mv.ManifestError, "'files' must be a JSON object"): + mv.load_manifest(bad_path) + + def test_load_manifest_boolean_size_raises(self) -> None: + digest = hashlib.sha256(b"x").hexdigest() + for bool_size in (True, False): + for wrapper in (True, False): + with self.subTest(size=bool_size, wrapper=wrapper): + bad_path = os.path.join(self.root, f"bool_size_{bool_size}_{wrapper}.json") + entry = {"a.bin": {"size": bool_size, "sha256": digest}} + doc = {"files": entry} if wrapper else entry + with open(bad_path, "w", encoding="utf-8") as f: + json.dump(doc, f) + with self.assertRaises(mv.ManifestError): + mv.load_manifest(bad_path) + + def test_walk_unreadable_directory_raises_and_cli_exits_2(self) -> None: + def failing_walk(top: str, *args, onerror=None, **kwargs): + err = PermissionError(13, "Permission denied", os.path.join(top, "nested")) + if onerror is not None: + onerror(err) + return + yield # pragma: no cover + + with patch("tools.manifest_verifier.os.walk", side_effect=failing_walk): + with self.assertRaises(PermissionError): + list(mv.walk(self.game_dir)) + with self.assertRaises(PermissionError): + mv.verify_manifest(self.game_dir, self.manifest_path, jobs=1) + + stderr_buf = io.StringIO() + with contextlib.redirect_stderr(stderr_buf): + rc = mv.main([self.game_dir, "--manifest", self.manifest_path, "--quiet"]) + self.assertEqual(rc, 2) + self.assertIn("ERROR:", stderr_buf.getvalue()) + self.assertIn("Permission denied", stderr_buf.getvalue()) + def test_load_manifest_invalid_json(self) -> None: bad_json = os.path.join(self.root, "bad.json") with open(bad_json, "w", encoding="utf-8") as f: diff --git a/tests/test_mc_command.py b/tests/test_mc_command.py index ea01a5528..24a05860d 100644 --- a/tests/test_mc_command.py +++ b/tests/test_mc_command.py @@ -7,6 +7,7 @@ Windows runs llvm-mc through WSL (the official Windows LLVM build has no AMDGPU python -I tests/test_mc_command.py """ import os +import subprocess import sys import tempfile import unittest @@ -100,5 +101,61 @@ class SplitCommandTest(unittest.TestCase): self.assertEqual(mc_command.mc_command(), ["llvm-mc"]) +class MissingLlvmMcTest(unittest.TestCase): + """An llvm-mc that can't be started ends each tool with one line, not a FileNotFoundError traceback.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.missing = os.path.join(self.tmp.name, "no-llvm-mc.exe") + + def tearDown(self): + self.tmp.cleanup() + + def test_run_names_the_command_and_how_to_set_it(self): + with self.assertRaises(SystemExit) as cm: + mc_command.run([self.missing, "-show-encoding"], input="", capture_output=True, text=True) + message = str(cm.exception.code) + self.assertIn(f"'{self.missing}' could not be started", message) + self.assertIn("LLVM_MC", message) + self.assertIn("build_llvm_mc.ps1", message) + self.assertNotIn("--llvm-mc", message) # only a tool that has the option names it + + def test_run_names_the_tools_own_option(self): + with self.assertRaises(SystemExit) as cm: + mc_command.run([self.missing], flag="--llvm-mc", input="", capture_output=True, text=True) + self.assertIn("set LLVM_MC (or pass --llvm-mc)", str(cm.exception.code)) + + def test_run_passes_a_command_that_starts_through(self): + r = mc_command.run([sys.executable, "-c", "import sys; print(sys.stdin.read()); sys.exit(3)"], + input="hi", capture_output=True, text=True) + self.assertEqual((r.returncode, r.stdout.strip()), (3, "hi")) + + def test_every_tool_that_assembles_gives_one_line(self): + build = os.path.join(self.tmp.name, "build") + os.mkdir(build) + for name in ("vk_compute_test", "vk_store_test", "vk_harness"): # run_gpu_tests.py only checks they exist + open(os.path.join(build, name + (".exe" if os.name == "nt" else "")), "wb").close() + tools = { + "run_gpu_tests.py": [os.path.join(ROOT, "scripts", "run_gpu_tests.py"), "--build", build], + "valu_fuzz.py": [os.path.join(ROOT, "tools", "valu_fuzz.py"), "--family", "f16", "--programs", "1", + "--build", build], + "lds_fuzz.py": [os.path.join(ROOT, "tools", "lds_fuzz.py"), "--programs", "1", "--build", build], + "crosslane_fuzz.py": [os.path.join(ROOT, "tools", "crosslane_fuzz.py"), "--programs", "1"], + "image_fuzz.py": [os.path.join(ROOT, "tools", "image_fuzz.py"), "--programs", "1", "--build", build], + "build.py": [os.path.join(ROOT, "runtime", "test", "shaders", "build.py"), + os.path.join(self.tmp.name, "spirv"), "cs_store"], + } + env = dict(os.environ, LLVM_MC=self.missing) + for name, argv in tools.items(): + with self.subTest(tool=name): + p = subprocess.run([sys.executable, "-I", *argv], capture_output=True, text=True, env=env, + cwd=self.tmp.name, timeout=300) + self.assertEqual(p.returncode, 1, p.stdout + p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertIn("could not be started", p.stderr) + # Only run_gpu_tests.py has an --llvm-mc option; the others read LLVM_MC alone. + self.assertEqual("--llvm-mc" in p.stderr, name == "run_gpu_tests.py", p.stderr) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_mesh_compute_vs.py b/tests/test_mesh_compute_vs.py new file mode 100644 index 000000000..f7c27ad1e --- /dev/null +++ b/tests/test_mesh_compute_vs.py @@ -0,0 +1,131 @@ +"""Unit tests for tools/mesh_compute_vs.py (standard library; the assembly checks need SPIRV-Tools on PATH).""" +import contextlib +import io +import json +import os +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +import mesh_compute_vs as vs # noqa: E402 +import rdna2spirv # noqa: E402 + +HAVE_SPIRV_TOOLS = bool(shutil.which("spirv-as") and shutil.which("spirv-val")) + + +def layout(maxv=64, maxp=3, clip=0, cull=0, params=()): + """A real `mesh_compute` index entry, from the translator's own layout function.""" + return rdna2spirv.mesh_compute_layout(maxv, maxp, clip, cull, list(params)) + + +def write_index(directory, index): + path = os.path.join(directory, "index.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(index, f) + return path + + +class Interface(unittest.TestCase): + def test_entry_point_carries_the_mesh_shader_locations(self): + asm = vs.vs_spvasm(layout(clip=5, cull=2, params=(2, 9))) + entry = asm.split("OpEntryPoint Vertex", 1)[1].splitlines()[0] + for name in ("%vertex_index", "%pc", "%out_pos", "%out_clip", "%out_cull", "%out2", "%out9"): + self.assertIn(name, entry) + for decoration in ("BuiltIn ClipDistance", "BuiltIn CullDistance", "Location 2", "Location 9"): + self.assertIn(decoration, asm) + + def test_no_clip_or_cull_means_no_such_outputs(self): + asm = vs.vs_spvasm(layout(params=(3,))) + self.assertNotIn("ClipDistance", asm) + self.assertNotIn("CullDistance", asm) + self.assertNotIn("%out_clip", asm) + self.assertIn("Location 3", asm) + + def test_the_index_drives_write_for_index(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(vs.write_for_index(tmp), []) # no index.json: nothing to do + write_index(tmp, {"ms_none": {"subgroup_size": 64}, "ms_null": None, + "ms_a": {"mesh_compute": layout(clip=1)}}) + written = vs.write_for_index(tmp) + self.assertEqual([os.path.basename(p) for p in written], ["ms_a.mesh_vs.spvasm"]) + with open(written[0], encoding="utf-8") as f: + self.assertEqual(f.read(), vs.vs_spvasm(layout(clip=1))) + + +class Assembly(unittest.TestCase): + def test_every_layout_assembles_and_validates(self): + if not HAVE_SPIRV_TOOLS: + self.skipTest("spirv-as / spirv-val not on PATH") + layouts = { + "ms_plain": layout(), + "ms_clip": layout(clip=1), + "ms_full": layout(clip=5, cull=2, params=(2, 5)), + "ms_small": layout(maxv=1, maxp=256), + "ms_large": layout(maxv=128, maxp=64, clip=4, params=(0,)), + } + with tempfile.TemporaryDirectory() as tmp: + write_index(tmp, {name: {"mesh_compute": lay} for name, lay in layouts.items()}) + built = vs.build_for_index(tmp) + self.assertEqual([os.path.basename(p) for p in built], + [name + ".mesh_vs.spv" for name in sorted(layouts)]) + for spv in built: + self.assertGreater(os.path.getsize(spv), 0) + self.assertTrue(os.path.isfile(spv[: -len(".spv")] + ".spvasm")) + + def test_a_rejected_shader_names_the_tool(self): + if not HAVE_SPIRV_TOOLS: + self.skipTest("spirv-as / spirv-val not on PATH") + with tempfile.TemporaryDirectory() as tmp: + asm = os.path.join(tmp, "bad.mesh_vs.spvasm") + with open(asm, "w", encoding="utf-8") as f: + f.write("OpCapability NothingOfTheSort\n") + with mock.patch.object(vs, "write_for_index", return_value=[asm]): + with self.assertRaises(RuntimeError) as ctx: + vs.build_for_index(tmp) + self.assertIn("spirv-as failed for", str(ctx.exception)) + + +class Cli(unittest.TestCase): + def run_main(self, argv, **env): + out, err = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ, env): + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + rc = vs.main(argv) + return rc, out.getvalue(), err.getvalue() + + def test_a_missing_spirv_tool_is_one_error_line(self): + with tempfile.TemporaryDirectory() as tmp: + write_index(tmp, {"ms_a": {"mesh_compute": layout()}}) + rc, stdout, stderr = self.run_main(["mesh_compute_vs.py", tmp], PATH="") + self.assertEqual(rc, 1) + self.assertEqual(stdout, "") + self.assertEqual(len(stderr.splitlines()), 1) + self.assertIn("spirv-as not found on PATH", stderr) + + def test_a_wrong_argument_count_is_a_usage_error(self): + rc, stdout, stderr = self.run_main(["mesh_compute_vs.py"]) + self.assertEqual(rc, 2) + self.assertEqual(stdout, "") + self.assertIn("Vertex shaders that draw", stderr) + + def test_an_unreadable_index_is_one_error_line(self): + with tempfile.TemporaryDirectory() as tmp: + path = write_index(tmp, {}) + os.mkdir(os.path.join(tmp, "dir")) + # tool_path() runs first, so stub it out too: otherwise a machine without SPIRV-Tools reports + # the missing tool instead of the write error this test is about. + with mock.patch.object(vs, "tool_path", return_value="spirv-as"), \ + mock.patch.object(vs, "write_for_index", + side_effect=OSError(13, "Permission denied", path)): + rc, _, stderr = self.run_main(["mesh_compute_vs.py", tmp]) + self.assertEqual(rc, 1) + self.assertEqual(len(stderr.splitlines()), 1) + self.assertIn("Permission denied", stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mode_round.py b/tests/test_mode_round.py new file mode 100644 index 000000000..6dc4c3bd3 --- /dev/null +++ b/tests/test_mode_round.py @@ -0,0 +1,194 @@ +"""MODE.FP_ROUND[3:2] (f16/f64 rounding) written with s_setreg_imm32_b32, run in the SPIR-V interpreter. + +The game switches f16/f64 rounding to toward zero (value 3) and back to nearest even (value 0) inside programs. +Values are picked so the two modes give different bits: 1 + 0.75 * 2^-10 rounds up to the next f16 under nearest +even and down under toward zero; 1 - 2^-60 rounds to 1.0 in f64 under nearest even and to 1 - 2^-53 toward zero. +""" +import pytest + +import rdna2spirv +import spirv_interp as si +from listing import translate_listing + +RTZ = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3\n" +RNE = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0\n" +X = 0x3F801800 # f32 1 + 0.75 * 2^-10 +NX = X | 0x80000000 + + +def vgprs(tmp_path, asm): + return si.run(translate_listing(tmp_path, asm)).vgpr + + +@pytest.mark.parametrize("prefix,src,want", [ + ("", X, 0x3C01), # no MODE write: nearest even, as before + (RTZ, X, 0x3C00), + (RTZ, NX, 0xBC00), + (RNE, X, 0x3C01), + (RTZ, 0x4788B800, 0x7BFF), # 70000.0: toward zero saturates to 65504 instead of inf + (RTZ, 0x7F800000, 0x7C00), # inf stays inf + (RTZ, 0x33C00000, 0x0001), # 1.5 * 2^-24: f16 subnormal, truncated (nearest even gives 0x0002) + ("", 0x33C00000, 0x0002), + (RTZ, 0x33000000, 0x0000), # 2^-25: below the smallest f16 subnormal + (RTZ, 0xC7800000, 0xFBFF), # -65536.0 saturates to -65504 +]) +def test_cvt_f16_f32(prefix, src, want, tmp_path): + asm = f"v_mov_b32 v1, {src:#x}\n{prefix}v_cvt_f16_f32_e32 v2, v1\n" + assert vgprs(tmp_path, asm)[2] & 0xFFFF == want + + +def test_mode_switches_back(tmp_path): + asm = f"v_mov_b32 v1, {X:#x}\n{RTZ}v_cvt_f16_f32_e32 v2, v1\n{RNE}v_cvt_f16_f32_e32 v3, v1\n" + v = vgprs(tmp_path, asm) + assert (v[2] & 0xFFFF, v[3] & 0xFFFF) == (0x3C00, 0x3C01) + + +def test_pk_add_f16_both_halves(tmp_path): + # lo: 1.0 + 1.5 * 2^-11 (0.75 f16 ulp past 1.0), hi: the same negated; toward zero gives 1.0 and -1.0 + one, small = 0x3C00, 0x1200 # 1.0, 1.5 * 2^-11 + asm = (f"v_mov_b32 v1, {(one | 0x8000) << 16 | one:#x}\nv_mov_b32 v2, {(small | 0x8000) << 16 | small:#x}\n" + f"{RTZ}v_pk_add_f16 v3, v1, v2\n") + assert vgprs(tmp_path, asm)[3] == 0xBC00 << 16 | 0x3C00 + + +# 2 - 2^-24: an f32 tie that rounds up to 2.0, so toward zero must look at the exact sum (0x3FFF), not the f32 one. +TWO, TINY, NTINY = 0x4000, 0x0001, 0x8001 + + +@pytest.mark.parametrize("prefix,asm,want", [ + ("", "v_sub_f16_e32 v3, v1, v2", 0x4000), + (RTZ, "v_sub_f16_e32 v3, v1, v2", 0x3FFF), + (RTZ, "v_add_f16_e32 v3, v1, v4", 0x3FFF), + (RTZ, "v_add_f16_e32 v3, v1, v2", 0x4000), # 2 + 2^-24 toward zero is 2.0 + (RTZ, "v_fma_f16 v3, v1, v5, v4", 0x3FFF), # 2 * 1 - 2^-24 + (RTZ, "v_add_f16_e64 v3, v1, v4 op_sel:[0,0,1]", 0x3FFF << 16 | 0x5555), # high destination half +]) +def test_f16_sum_rounds_from_the_exact_value(prefix, asm, want, tmp_path): + setup = (f"v_mov_b32 v1, {TWO:#x}\nv_mov_b32 v2, {TINY:#x}\nv_mov_b32 v4, {NTINY:#x}\nv_mov_b32 v5, 0x3c00\n" + "v_mov_b32 v3, 0x5555\n") + got = vgprs(tmp_path, setup + prefix + asm + "\n")[3] + assert (got if want > 0xFFFF else got & 0xFFFF) == want + + +def test_pk_fma_f16_exact_toward_zero(tmp_path): + # both halves: 2 * 1 + (-2^-24) -> 0x3FFF, and -(2 * 1) + 2^-24 -> 0xBFFF + asm = (f"v_mov_b32 v1, {(TWO | 0x8000) << 16 | TWO:#x}\nv_mov_b32 v2, 0x3c003c00\n" + f"v_mov_b32 v4, {TINY << 16 | NTINY:#x}\n{RTZ}v_pk_fma_f16 v3, v1, v2, v4\n") + assert vgprs(tmp_path, asm)[3] == 0xBFFF << 16 | 0x3FFF + + +@pytest.mark.parametrize("prefix,want", [("", (0, 0x3FF00000)), (RTZ, (0xFFFFFFFF, 0x3FEFFFFF))]) +def test_add_f64(prefix, want, tmp_path): + asm = ("v_mov_b32 v0, 0\nv_mov_b32 v1, 0x3ff00000\nv_mov_b32 v2, 0\nv_mov_b32 v3, 0xbc300000\n" + f"{prefix}v_add_f64 v[4:5], v[0:1], v[2:3]\n") + v = vgprs(tmp_path, asm) + assert (v[4], v[5]) == want + + +@pytest.mark.parametrize("a,b,prefix,want", [ + (0x4000, 0x0001, "", 0x4000), # 2 + 2^-24: a quarter f16 ulp above 2.0; both modes give 2.0 + (0x4000, 0x0001, RTZ, 0x4000), + (0x7BFF, 0x4C00, "", 0x7C00), # 65504 + 16 = 65520: the tie rounds to inf, toward zero stays 65504 + (0x7BFF, 0x4C00, RTZ, 0x7BFF), +]) +def test_f16_add_hardware_rows(a, b, prefix, want, tmp_path): + # words measured on an RX 6800 (SHADER-35) + asm = f"v_mov_b32 v1, {a:#x}\nv_mov_b32 v2, {b:#x}\n{prefix}v_add_f16_e32 v3, v1, v2\n" + assert vgprs(tmp_path, asm)[3] & 0xFFFF == want + + +@pytest.mark.parametrize("prefix,want", [("", 0xBC01), (RTZ, 0xBC00)]) +def test_f16_sub_hardware_row(prefix, want, tmp_path): + # -1 - (2^-11 + 2^-21): above the half-ulp tie, so nearest rounds away (RX 6800) + asm = f"v_mov_b32 v1, 0xbc00\nv_mov_b32 v2, 0x1001\n{prefix}v_sub_f16_e32 v3, v1, v2\n" + assert vgprs(tmp_path, asm)[3] & 0xFFFF == want + + +@pytest.mark.parametrize("prefix,want", [("", (0, 0x3FF00000)), (RTZ, (0xFFFFFFFF, 0x3FEFFFFF))]) +def test_add_f64_with_omod_not_asserted(prefix, want, tmp_path): + # (1 - 2^-60) + 0 toward zero, no omod. The hardware ignores omod when f64 denormals are kept (3ff00000:0 and + # 3fefffff:ffffffff unscaled with mul:2, RX 6800), the translator applies it either way: that is unmodelled + # (docs/design.md), so no omod order is claimed here. + asm = ("v_mov_b32 v0, 0\nv_mov_b32 v1, 0x3ff00000\nv_mov_b32 v2, 0\nv_mov_b32 v3, 0xbc300000\n" + f"{prefix}v_add_f64 v[4:5], v[0:1], v[2:3]\n") + v = vgprs(tmp_path, asm) + assert (v[4], v[5]) == want + + +@pytest.mark.parametrize("op,src", [ + ("v_rcp_f16_e32", 0x3037), ("v_rsq_f16_e32", 0x3037), ("v_sqrt_f16_e32", 0x4200), ("v_sin_f16_e32", 0x3037), + ("v_cos_f16_e32", 0x3037), ("v_exp_f16_e32", 0x3037), ("v_log_f16_e32", 0x4a37), +]) +def test_transcendental_f16_ignores_mode(op, src, tmp_path): + # RX 6800: rcp/sqrt/rsq/sin give the same words in every rounding mode; cos, exp and log are unmeasured, assumed alike + got = [] + for prefix in ("", RNE, RTZ): + asm = f"v_mov_b32 v1, {src:#x}\n{prefix}{op} v2, v1\n" + got.append(vgprs(tmp_path, asm)[2] & 0xFFFF) + assert got[0] == got[1] == got[2] + + +def test_transcendental_f16_nearest_after_rtz_write(tmp_path): + # MODE is set toward zero before the ops: they still give the nearest-even words + for op, src, want in (("v_rcp_f16_e32", 0x3037, 0x4798), ("v_rsq_f16_e32", 0x3037, 0x4183), + ("v_sqrt_f16_e32", 0x4200, 0x3EEE), ("v_sin_f16_e32", 0x3037, 0x39E4)): + asm = f"v_mov_b32 v1, {src:#x}\n{RTZ}{op} v2, v1\n" + assert vgprs(tmp_path, asm)[2] & 0xFFFF == want, op + + +@pytest.mark.parametrize("prefix,want", [("", 0x4000), (RTZ, 0x3FFF)]) +def test_fma_mix_single_rounding(prefix, want, tmp_path): + # 1 * 2 - 2^-30 with f32 operands: toward zero the hardware rounds the exact value once to f16 (0x3fff); rounding + # to f32 first (2.0) then narrowing would give 0x4000 (RX 6800) + asm = ("v_mov_b32 v1, 0x3f800000\nv_mov_b32 v2, 0x40000000\nv_mov_b32 v4, 0xb0800000\n" + f"{prefix}v_fma_mixlo_f16 v3, v1, v2, v4\n") + assert vgprs(tmp_path, asm)[3] & 0xFFFF == want + + +def test_fma_mix_toward_zero_negative_and_hi(tmp_path): + # -(1 * 2) + 2^-30 -> -0x3fff in the high half, the low half kept + asm = ("v_mov_b32 v1, 0x3f800000\nv_mov_b32 v2, 0xc0000000\nv_mov_b32 v4, 0x30800000\nv_mov_b32 v3, 0x1234\n" + f"{RTZ}v_fma_mixhi_f16 v3, v1, v2, v4\n") + assert vgprs(tmp_path, asm)[3] == 0xBFFF << 16 | 0x1234 + + +def test_add_f64_overflow_saturates(tmp_path): + asm = ("v_mov_b32 v0, -1\nv_mov_b32 v1, 0x7fefffff\n" + f"{RTZ}v_add_f64 v[4:5], v[0:1], v[0:1]\n") + v = vgprs(tmp_path, asm) + assert (v[4], v[5]) == (0xFFFFFFFF, 0x7FEFFFFF) + + +@pytest.mark.parametrize("asm", [ + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 3\n", # f32 rounding: not modelled + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 4), 15\n", # denormal controls: not modelled + "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 1\n", # round toward +inf + "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s0\n", # value from a register +]) +def test_unmodelled_mode_writes_are_refused(asm, tmp_path): + with pytest.raises(rdna2spirv.Unsupported): + translate_listing(tmp_path, asm) + + +@pytest.mark.parametrize("x,y,z,want", [ + (0x99800000, 0x19800000, 0x3F800000, 0x3BFF), # 1 - 2^-152: the product error underflows in f32 + (0x9F000000, 0x1F000000, 0x3F800000, 0x3BFF), # 1 - 2^-130: the product is an f32 subnormal (flushed on some drivers) + (0x1F000000, 0x1F000000, 0x3F800000, 0x3C00), # 1 + 2^-130 toward zero is 1.0 + (0x99800000, 0x19800000, 0xBF800000, 0xBC00), # -1 - 2^-152 toward zero is -1.0 + (0x19800000, 0x19800000, 0xBF800000, 0xBBFF), # -1 + 2^-152 toward zero is -(1 - 2^-11) +]) +def test_fma_mix_tiny_product(x, y, z, want, tmp_path): + asm = (f"v_mov_b32 v1, {x:#x}\nv_mov_b32 v2, {y:#x}\nv_mov_b32 v4, {z:#x}\n" + f"{RTZ}v_fma_mixlo_f16 v3, v1, v2, v4\n") + assert vgprs(tmp_path, asm)[3] & 0xFFFF == want + + +@pytest.mark.parametrize("x,y,z,want", [ + (0x5F800000, 0x5F800000, 0x00000000, 0x7BFF), # 2^128 is finite exactly: f32 Fma gives inf, toward zero 65504 + (0xDF800000, 0x5F800000, 0x00000000, 0xFBFF), + (0x7F800000, 0x3F800000, 0x00000000, 0x7C00), # a real inf stays inf +]) +def test_fma_mix_f32_overflow_toward_zero(x, y, z, want, tmp_path): + asm = (f"v_mov_b32 v1, {x:#x}\nv_mov_b32 v2, {y:#x}\nv_mov_b32 v4, {z:#x}\n" + f"{RTZ}v_fma_mixlo_f16 v3, v1, v2, v4\n") + assert vgprs(tmp_path, asm)[3] & 0xFFFF == want diff --git a/tests/test_navmesh_decode.py b/tests/test_navmesh_decode.py index e4bd9db06..bb2e16610 100644 --- a/tests/test_navmesh_decode.py +++ b/tests/test_navmesh_decode.py @@ -617,6 +617,40 @@ class NavmeshDecodeTest(unittest.TestCase): self.assertIn("--out and --csv must use different paths", result.stderr) self.assertFalse(os.path.exists(output)) + def test_cli_creates_missing_output_folders(self): + with tempfile.TemporaryDirectory() as tmp: + archive = os.path.join(tmp, "nav.rpf") + make_rpf(archive, build_0drp()) + out_json = os.path.join(tmp, "reports", "deep", "nav.json") + out_csv = os.path.join(tmp, "tables", "nav.csv") + result = subprocess.run( + [sys.executable, "-I", TOOL, archive, "--out", out_json, "--csv", out_csv, "--quiet"], + capture_output=True, text=True, check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("Traceback", result.stderr) + with open(out_json, encoding="utf-8") as f: + self.assertEqual(json.load(f)["resources"]["0drp"]["resources"], 1) + with open(out_csv, newline="", encoding="utf-8") as f: + self.assertEqual(len(list(csv.DictReader(f))), 1) + + def test_cli_refuses_to_overwrite_its_input(self): + with tempfile.TemporaryDirectory() as tmp: + archive = os.path.join(tmp, "nav.rpf") + make_rpf(archive, build_0drp()) + with open(archive, "rb") as f: + original = f.read() + for flag in ("--out", "--csv"): + result = subprocess.run( + [sys.executable, "-I", TOOL, archive, flag, archive, "--quiet"], + capture_output=True, text=True, check=False, + ) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("would overwrite the input", result.stderr) + self.assertNotIn("Traceback", result.stderr) + with open(archive, "rb") as f: + self.assertEqual(f.read(), original, f"{flag} touched the input") + def test_cli_rejects_bad_arguments_and_files(self): with tempfile.TemporaryDirectory() as tmp: empty = os.path.join(tmp, "empty.rpf") diff --git a/tests/test_navmesh_index.py b/tests/test_navmesh_index.py index bff13cae5..2f74562b3 100644 --- a/tests/test_navmesh_index.py +++ b/tests/test_navmesh_index.py @@ -136,6 +136,61 @@ class NavmeshIndexTest(unittest.TestCase): self.assertEqual(len(lines), 2) self.assertIn("0DRP@16", lines[1]) + def assert_output_collision(self, *args): + r = subprocess.run([sys.executable, "-I", TOOL, *args], cwd=self.root, capture_output=True, text=True) + self.assertEqual(r.returncode, 2, r.stderr) + self.assertIn("--out and --csv must refer to different files", r.stderr) + + def test_explicit_output_collision_before_scan(self): + # A missing input would give a different error if the scan started. + self.assert_output_collision("missing.rpf", "--out", "new.json", "--csv", "./new.json") + self.assertFalse(os.path.exists(os.path.join(self.root, "new.json"))) + + def test_default_output_collision_preserves_report(self): + make_rpf(os.path.join(self.root, "nav.rpf")) + report = os.path.join(self.root, "nav.navmesh-index.json") + with open(report, "wb") as f: + f.write(b"previous report") + self.assert_output_collision("nav.rpf", "--csv", report) + with open(report, "rb") as f: + self.assertEqual(f.read(), b"previous report") + + def test_hard_link_output_collision(self): + report = os.path.join(self.root, "out.json") + with open(report, "wb") as f: + f.write(b"previous report") + try: + os.link(report, os.path.join(self.root, "out.csv")) + except OSError as exc: + self.skipTest(f"cannot create a hard link: {exc}") + self.assert_output_collision(self.root, "--out", "out.json", "--csv", "out.csv") + with open(report, "rb") as f: + self.assertEqual(f.read(), b"previous report") + + def test_report_path_cannot_be_scanned_input(self): + # Before: --out/--csv naming a file the scan reads replaced that file with the report, exit 0. + folder = os.path.join(self.root, "carve") + os.makedirs(folder) + carved = os.path.join(folder, "page.bin") + with open(carved, "wb") as f: + f.write(page(pages=4)) + rpf = os.path.join(self.root, "nav.rpf") + make_rpf(rpf) + originals = {} + for path in (carved, rpf): + with open(path, "rb") as f: + originals[path] = f.read() + cases = [((folder, "--out", carved), carved), ((folder, "--csv", carved), carved), + ((rpf, "--out", rpf), rpf), ((rpf, "--csv", rpf), rpf)] + for args, path in cases: + r = subprocess.run([sys.executable, "-I", TOOL, *args], cwd=ROOT, capture_output=True, text=True, + check=False) + self.assertEqual(r.returncode, 2, r.stderr) + self.assertIn("would overwrite the input", r.stderr) + self.assertNotIn("Traceback", r.stderr) + with open(path, "rb") as f: + self.assertEqual(f.read(), originals[path], f"{args} touched the input") + def test_not_an_rpf(self): path = os.path.join(self.root, "not.rpf") with open(path, "wb") as f: diff --git a/tests/test_ps_interp_modes.py b/tests/test_ps_interp_modes.py new file mode 100644 index 000000000..88d13e153 --- /dev/null +++ b/tests/test_ps_interp_modes.py @@ -0,0 +1,284 @@ +"""The PS interpolation-mode decoder reads PSV0 elements, ISG1 read masks, FSSM read methods +and classifies the single barycentric pair; malformed containers are refused. + +Covers tools/ps_interp_modes.py (SHADER-181). All containers here are synthetic: the PSV0 +layout is the one dxc writes (lib/DxilContainer/DxilPipelineStateValidation.cpp), the +interpolation-mode numbers are DXIL::InterpolationMode ("must match D3D_INTERPOLATION_MODE") +and the class names come from the SPI_PS_INPUT_ENA fields (Mesa gfx103.json). +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(ROOT, "tools") +TOOL = os.path.join(TOOLS, "ps_interp_modes.py") +sys.path.insert(0, TOOLS) + +import ps_interp_modes # noqa: E402 + + +def psv0(elements, inputs=None, strings=b"\0TEXCOORD\0", semidx=(0,), resources=0): + """Build a PSV0 chunk payload. elements are (row, cols, kind, ctype, mode) tuples.""" + if inputs is None: + inputs = len(elements) + heap = strings.ljust((len(strings) + 3) & ~3, b"\0") + body = b"".join(struct.pack(" (class, ENA bit), bit numbers from Mesa gfx103.json SPI_PS_INPUT_ENA + expect = {2: ("persp_center", 0x2), 3: ("persp_centroid", 0x4), 6: ("persp_sample", 0x1), + 4: ("linear_center", 0x20), 5: ("linear_centroid", 0x40), + 7: ("linear_sample", 0x10), 1: ("flat", 0)} + for mode, (cls, bit) in expect.items(): + self.assertEqual(ps_interp_modes.interp_class(0, mode), (cls, bit)) + self.assertEqual(ps_interp_modes.interp_class(3, 4), ("linear_center", 0x20)) + + def test_system_value_kinds_are_system_inputs(self): + self.assertEqual(ps_interp_modes.interp_class(13, 1), ("system", 0)) + self.assertEqual(ps_interp_modes.interp_class(12, 1), ("system", 0)) + + def test_unknown_mode_is_other(self): + self.assertEqual(ps_interp_modes.interp_class(0, 0), ("other", 0)) + self.assertEqual(ps_interp_modes.interp_class(0, 8), ("other", 0)) + + +class ReadMethodTest(unittest.TestCase): + def test_flag_bits_decode_to_read_methods(self): + self.assertEqual(ps_interp_modes.read_method(0x01), {"mov": True, "p1p2": False, + "param16": False, "f16_ops": False}) + self.assertEqual(ps_interp_modes.read_method(0x02), {"mov": False, "p1p2": True, + "param16": False, "f16_ops": False}) + self.assertEqual(ps_interp_modes.read_method(0x1A), {"mov": False, "p1p2": True, + "param16": True, "f16_ops": True}) + self.assertEqual(ps_interp_modes.read_method(0x09), {"mov": True, "p1p2": False, + "param16": True, "f16_ops": False}) + + +class DisasmFactsTest(unittest.TestCase): + def test_v_interp_lines_decode_to_kinds_and_ij(self): + text = ("\tv_interp_p1_f32_e32 v2, v0, attr2.x\n" + "\tv_interp_p2_f32_e32 v2, v1, attr2.x\n" + "\tv_interp_mov_f32 v5, p0, attr3.x\n" + "\tv_interp_p1ll_f16 v6, v0, attr1.x\n") + per, ij = ps_interp_modes.disasm_facts(text) + self.assertEqual(per, {2: {"p1p2"}, 3: {"mov"}, 1: {"f16"}}) + self.assertEqual(ij, {"v0", "v1"}) + + def test_mov_p0_is_not_an_ij_operand(self): + per, ij = ps_interp_modes.disasm_facts("\tv_interp_mov_f32 v5, p10, attr0.x\n") + self.assertEqual(per, {0: {"mov"}}) + self.assertEqual(ij, set()) + + +class PairClassTest(unittest.TestCase): + def rows(self, *specs): + return [{"kind": k, "mode": m, "rw": rw} for k, m, rw in specs] + + def test_perspective_generic_wins_the_pair(self): + rows = self.rows((3, 4, 0xF), (0, 2, 0xF)) + self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "persp_center") + + def test_live_position_alone_interpolates_linear(self): + rows = self.rows((3, 4, 0xF), (0, 2, 0)) + self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "linear_center") + + def test_mode5_position_is_linear_centroid(self): + rows = self.rows((3, 5, 0xF)) + self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "linear_centroid") + + def test_position_plus_flat_row_stays_flat(self): + # a shader that reads SV_Position and a Constant row: the interpolation reads the + # flat row (P0 semantics, any pair) and the position comes from the system VGPRs + rows = self.rows((3, 5, 0xF), (0, 1, 0xF)) + self.assertEqual(ps_interp_modes.pair_class(rows, [], {1: {"p1p2"}}, {"v0"}), "flat_only") + + def test_constant_rows_only_is_flat(self): + rows = self.rows((0, 1, 0xF)) + self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "flat_only") + + def test_no_interpolation_at_all(self): + self.assertEqual(ps_interp_modes.pair_class(self.rows((3, 4, 0xF)), [], {}, set()), "none") + + def test_raw_barycentric_read_without_v_interp(self): + self.assertEqual(ps_interp_modes.pair_class(self.rows(), [], {}, {"v0"}), "raw_bary") + + +class ShaderRowTest(unittest.TestCase): + def test_end_to_end_row_from_synthetic_container(self): + c = dxbc_container({ + b"PSV0": psv0([(0, 4, 3, 3, 4), (1, 4, 0, 3, 2)]), + b"ISG1": isg1([(0, 0xF, "SV_Position"), (1, 0xF, "TEXCOORD0")]), + }) + with tempfile.TemporaryDirectory() as tmp: + dx = os.path.join(tmp, "a.dxbc") + fs = os.path.join(tmp, "fssm", "a.fssm") + ds = os.path.join(tmp, "disasm", "a.s") + os.mkdir(os.path.join(tmp, "fssm")) + os.mkdir(os.path.join(tmp, "disasm")) + with open(dx, "wb") as f: f.write(c) + with open(fs, "wb") as f: f.write(fssm([(0, 0xF, 0x02), (1, 0xF, 0x02)])) + with open(ds, "w") as f: f.write("v_interp_p1_f32_e32 v2, v0, attr1.x\n") + row = ps_interp_modes.shader_row(dx, fs, ds) + self.assertEqual(row["pair_class"], "persp_center") + self.assertEqual([i["class"] for i in row["inputs"]], ["linear_center", "persp_center"]) + self.assertEqual([i["rw"] for i in row["inputs"]], [15, 15]) + self.assertEqual([t["p1p2"] for t in row["table"]], [True, True]) + self.assertEqual(row["usage"], {"1": ["p1p2"]}) + + def test_unparsable_psv0_returns_none(self): + with tempfile.TemporaryDirectory() as tmp: + dx = os.path.join(tmp, "b.dxbc") + with open(dx, "wb") as f: f.write(dxbc_container({b"PSV0": psv0([])[:20]})) + self.assertIsNone(ps_interp_modes.shader_row(dx, None, None)) + + +class TallyTest(unittest.TestCase): + def test_census_counts_modes_and_pairs(self): + rows = [ + {"inputs": [{"kind": 0, "mode": 2, "rw": 15, "class": "persp_center"}, + {"kind": 3, "mode": 4, "rw": 15, "class": "linear_center"}], + "table": [{"mov": False, "p1p2": True, "param16": False, "f16_ops": False, "mask": 15, "flags": 2}], + "usage": {"0": ["p1p2"]}, "ij": ["v0", "v1"], "pair_class": "persp_center"}, + {"inputs": [{"kind": 3, "mode": 4, "rw": 15, "class": "linear_center"}], + "table": [], "usage": {}, "ij": [], "pair_class": "linear_center"}, + ] + t = ps_interp_modes.tally(rows) + self.assertEqual(t["shaders"], 2) + self.assertEqual(t["inputs"], 3) + self.assertEqual(t["live_inputs"], 3) + self.assertEqual(t["mode_by_kind"], {"kind0 mode2": 1, "kind3 mode4": 2}) + self.assertEqual(t["live_non_persp_center_inputs"], 2) + self.assertEqual(t["shaders_with_non_persp_center"], 2) + self.assertEqual(t["pair_class"], {"persp_center": 1, "linear_center": 1}) + self.assertEqual(t["flag_vs_usage"], {"mov=0 p1p2=1 f16=0 -> p1p2": 1}) + + +class CliTest(unittest.TestCase): + def test_directory_census_with_stage_index(self): + with tempfile.TemporaryDirectory() as tmp: + os.mkdir(os.path.join(tmp, "fssm")) + os.mkdir(os.path.join(tmp, "disasm")) + with open(os.path.join(tmp, "ps1.dxbc"), "wb") as f: + f.write(dxbc_container({b"PSV0": psv0([(0, 4, 0, 3, 2)]), + b"ISG1": isg1([(0, 0xF, "TEXCOORD0")])})) + with open(os.path.join(tmp, "fssm", "ps1.fssm"), "wb") as f: + f.write(fssm([(0, 0xF, 0x02)])) + with open(os.path.join(tmp, "disasm", "ps1.s"), "w") as f: + f.write("v_interp_p1_f32_e32 v2, v0, attr0.x\n") + with open(os.path.join(tmp, "vs1.dxbc"), "wb") as f: + f.write(dxbc_container({b"PSV0": psv0([(0, 4, 0, 3, 2)])})) + with open(os.path.join(tmp, "index.json"), "w") as f: + json.dump([{"name": "ps1", "file": "ps1.dxbc", "stage": "ps"}, + {"name": "vs1", "file": "vs1.dxbc", "stage": "vs"}], f) + out = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json"], + capture_output=True, text=True, check=True) + doc = json.loads(out.stdout) + self.assertEqual(len(doc["files"]), 1) + self.assertEqual(doc["tally"]["pair_class"], {"persp_center": 1}) + self.assertEqual(doc["tally"]["mode_by_kind"], {"kind0 mode2": 1}) + + def test_missing_path_is_an_error(self): + out = subprocess.run([sys.executable, "-I", TOOL, "Z:/nope"], + capture_output=True, text=True) + self.assertEqual(out.returncode, 2) + self.assertIn("does not exist", out.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_rdna2spirv_pixelinput.py b/tests/test_rdna2spirv_pixelinput.py index c3c029c39..c834d6ef9 100644 --- a/tests/test_rdna2spirv_pixelinput.py +++ b/tests/test_rdna2spirv_pixelinput.py @@ -38,6 +38,9 @@ from spirv_mini_interp import run_fragment # noqa: E402 STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" list[tuple[int, str]]: class ResourceHygieneTest(unittest.TestCase): def test_no_unmanaged_open_calls(self): - for rel in ("tools/rdna2spirv.py", "tools/amd_swizzle.py", "tools/awc_opus.py"): + for rel in ( + "tools/rdna2spirv.py", + "tools/amd_swizzle.py", + "tools/awc_opus.py", + "tools/wave64_graphics_scan.py", + "tools/tex_export.py", + "tools/tex_mode_probe.py", + "tools/shader_disasm.py", + "tools/hashdict.py", + "tools/d3d12_xs_surface.py", + ): with self.subTest(file=rel): bare = _bare_open_calls(ROOT / rel) self.assertEqual(bare, [], f"unmanaged open() calls in {rel}: {bare}") diff --git a/tests/test_rtti_scan.py b/tests/test_rtti_scan.py index a5b7be723..f5644bf45 100644 --- a/tests/test_rtti_scan.py +++ b/tests/test_rtti_scan.py @@ -260,6 +260,23 @@ class RttiScanCoreTest(unittest.TestCase): self.assertEqual(v1["offset_in_object"], 8) self.assertEqual(v1["slots"], 1) + def test_vtable_slots_stop_at_the_end_of_their_section(self): + rdata = bytearray(0x1000) + rdata[0x10:0x1D] = b".?AVProbe@@\x00\x00" + # The vtable's first slot ends at .rdata's declared VirtualSize (0x200). + struct.pack_into("<6I", rdata, 0x40, 1, 0, 0, 0x2000, 0, 0x2040) + struct.pack_into("<3Q", rdata, 0x1F0, + self.image_base + 0x2040, self.image_base + 0x1000, self.image_base + 0x1008) + pe = bytearray(make_synthetic_pe(rdata_bytes=rdata)) + section_virtual_size = 0x80 + 24 + 240 + 40 + 8 + struct.pack_into(" int: + # Only the low 16 bits of the first three exports carry an interpolation result. + return 0xffff0000 | struct.unpack("= 16 (out of bounds), returning 0 or wrapped values. + data = b"".join(struct.pack("<4I", i % width, (i % width) ^ 9, 0, 0) for i in range(64 * 64)) + problem = self.run_pixel("ps_bitmask_perm", 0, out, data=data) + self.assertIsInstance(problem, check.Skip) + self.assertIn(f"{width} lanes", problem) + + def test_bitmask_perm_judges_variable_device_at_32_lanes(self): + out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n" + self.assertEqual(self.run_pixel("ps_bitmask_perm", 0, out, data=self.bitmask_pixels(32)), "") + bad = b"".join(struct.pack("<4I", i % 32, (i % 32) ^ 9, 0, 0) for i in range(64 * 64)) + problem = self.run_pixel("ps_bitmask_perm", 0, out, data=bad) + self.assertNotIsInstance(problem, check.Skip) + self.assertIn("wrong", problem) + + def test_bitmask_perm_fails_broken_lanes_instead_of_skipping(self): + # Fixed 32..32 device producing only lanes 0..15, or 8..32 device producing incomplete/too-narrow lanes. + simd16 = b"".join(struct.pack("<4I", i % 16, (i % 16) ^ 9, 0, 0) for i in range(64 * 64)) + problem = self.run_pixel("ps_bitmask_perm", 0, "device: fake (subgroup 32..32)\nok 64x64\n", data=simd16) + self.assertNotIsInstance(problem, check.Skip) + self.assertIn("wrong", problem) + + out = "device: fake (subgroup 8..32)\nok 64x64\n" + for lanes in (1, 4, 15): + with self.subTest(lanes=lanes): + bad = b"".join(struct.pack("<4I", i % lanes, (i % lanes) ^ 9, 0, 0) for i in range(64 * 64)) + problem = self.run_pixel("ps_bitmask_perm", 0, out, data=bad) + self.assertNotIsInstance(problem, check.Skip) + self.assertIn("wrong", problem) + class SeededPixelTests(unittest.TestCase): """ps_vcc_x2 reads a V# from s[0:3]; check.py hands vk_harness that V# and the heap words behind it (TEST-19).""" @@ -473,6 +507,33 @@ class Wave32LaneDumps(unittest.TestCase): check.compute_test("tools", "spirv", "cs_store", "1", "dump", expected_words=check.CS_STORE) self.assertNotIn("env", run.call_args.kwargs) + def test_recorded_wave_size_is_requested(self): + # cs_barrier_loop is wave32 but not a lane dump: left to the default it ran 64-wide on an RX 9070 (32..64), + # two waves instead of four, and failed in check.py while run_gpu_tests.py (which reads index.json) passed. + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "index.json").write_text(json.dumps({"cs_barrier_loop": {"subgroup_size": 32}, + "cs_store": {}}), encoding="utf-8") + with patch.object(check, "run", return_value=(0, "out[0..7] = 128 96 64 32 128 96 64 0\n")) as run: + self.assertEqual(check.compute_test("tools", tmp, "cs_barrier_loop", "1", "dump", + expected_words=[128, 96, 64, 32, 128, 96, 64]), "") + self.assertEqual(run.call_args.kwargs["env"]["VKC_SUBGROUP_SIZE"], "32") + with patch.object(check, "run", return_value=(0, self.words("cs_store"))) as run: + check.compute_test("tools", tmp, "cs_store", "1", "dump", expected_words=check.CS_STORE) + self.assertNotIn("env", run.call_args.kwargs) # nothing recorded: the default size + with patch.object(check, "run", return_value=(0, "out[0..7] = 0 0 0 0 0 0 0 0\n")) as run: + check.compute_test("tools", tmp, "cs_barrier_loop", "1", "dump", expected_words=[1], + env={"VKC_SUBGROUP_SIZE": "64"}) + self.assertEqual(run.call_args.kwargs["env"]["VKC_SUBGROUP_SIZE"], "64") # a caller's choice wins + + def test_recorded_wave_size_that_cannot_be_pinned_is_a_skip(self): + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "index.json").write_text(json.dumps({"cs_barrier_loop": {"subgroup_size": 32}}), + encoding="utf-8") + out = "compute subgroup size: 32 not available\nout[0..7] = 0 0 0 0 0 0 0 0\n" + with patch.object(check, "run", return_value=(0, out)): + problem = check.compute_test("tools", tmp, "cs_barrier_loop", "1", "dump", expected_words=[128]) + self.assertIsInstance(problem, check.Skip) + def test_skipped_when_32_lanes_cannot_be_pinned(self): for name in check.WAVE32_LANE_DUMPS: for flip in (False, True): diff --git a/tests/test_shader_stage_resume.py b/tests/test_shader_stage_resume.py index a5cabf122..178ec2310 100644 --- a/tests/test_shader_stage_resume.py +++ b/tests/test_shader_stage_resume.py @@ -99,7 +99,7 @@ class ShaderStageResumeTest(unittest.TestCase): elif tool == "shader_disasm.py": os.makedirs(os.path.join(self.dxbc, "disasm"), exist_ok=True) - def fake_translate(self, disasm, spirv, jobs, emulate=False): + def fake_translate(self, disasm, spirv, jobs, emulate=False, fallbacks=()): self.ran.append("translate (emulated)" if emulate else "translate") self.touch(spirv, "index.json") @@ -246,7 +246,7 @@ class ShaderStageResumeTest(unittest.TestCase): # A kill between the merge (index.json appears) and the end of shaders() must not leave a finished folder # whose mode is unknown or wrong. def kill_after_merge(self, emulate): - def translate_then_die(disasm, spirv, jobs, emulate=False): + def translate_then_die(disasm, spirv, jobs, emulate=False, fallbacks=()): self.touch(spirv, "index.json") # rdna2spirv.py --merge finished ... raise KeyboardInterrupt # ... and the PC died right after with mock.patch.object(make_game, "py", self.fake_py), \ @@ -360,7 +360,7 @@ class ShaderStageResumeTest(unittest.TestCase): self.run_stage(emulate=True) self.record_sources("0" * 64) - def failing_translate(disasm, spirv, jobs, emulate=False): + def failing_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): self.assertTrue(emulate) raise SystemExit(1) with mock.patch.object(make_game, "py", self.fake_py), \ diff --git a/tests/test_tex_headers.py b/tests/test_tex_headers.py index ba8bcbe65..5b1d6079a 100644 --- a/tests/test_tex_headers.py +++ b/tests/test_tex_headers.py @@ -895,6 +895,24 @@ class CliInputTest(unittest.TestCase): self.assertEqual(p.returncode, 0, p.stderr) self.assertIn("0 textures", p.stdout) + def test_malformed_index_is_one_error_line(self): + # An index.json of the wrong shape ended in a KeyError/TypeError traceback after the carve had finished; + # gamedata_index.py already reports this as one ERROR line with exit 2. + cases = {"no files key": {}, "files not a list": {"files": "oops"}, "files null": {"files": None}, + "row not an object": {"files": [1, 2]}, "row without head": {"files": [{"off": 0}, {"off": 16}]}} + for label, index in cases.items(): + with self.subTest(index=label), tempfile.TemporaryDirectory() as tmp: + os.makedirs(os.path.join(tmp, "carve", "a")) + with open(os.path.join(tmp, "carve", "a", "index.json"), "w", encoding="utf-8") as f: + json.dump(index, f) + out = os.path.join(tmp, "t.json") + p = self.run_tool(os.path.join(tmp, "carve"), "--out", out) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertIn("ERROR: cannot read", p.stderr) + self.assertIn("index.json", p.stderr) + self.assertFalse(os.path.exists(out)) + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_texel_offsets.py b/tests/test_texel_offsets.py index a10d9174a..46fb7cbf8 100644 --- a/tests/test_texel_offsets.py +++ b/tests/test_texel_offsets.py @@ -32,11 +32,14 @@ FORMS = [ # (instruction, SPIR-V op that takes the Offset, offset components) def offset_fields(spv, op): - """[(first bit, width, signed)] of the fields that make up the Offset operand of the one ``op`` in ``spv``.""" + """[(first bit, width, signed)] of the Offset operand shared by every numeric path for ``op``.""" consts = {m[1]: int(m[2]) for m in re.finditer(r"(%\w+) = OpConstant %uint (\d+)", spv)} - line, = [ln for ln in spv.splitlines() if f"= {op} " in ln] - assert "Offset" in line and "ConstOffset" not in line - vec = line.split()[-1] # Offset is the last image operand: its id ends the line + lines = [ln for ln in spv.splitlines() if f"= {op} " in ln] + assert lines and all("Offset" in ln and "ConstOffset" not in ln for ln in lines), lines + # Typed gathers have one path per numeric class. Each path must apply the same offset. + offsets = {line.split()[-1] for line in lines} + assert len(offsets) == 1, lines + vec = offsets.pop() parts = re.search(rf"{re.escape(vec)} = OpCompositeConstruct %v\dint (.+)", spv)[1].split() fields = [] for part in parts: diff --git a/tests/test_translate.py b/tests/test_translate.py index de7a5689d..b96c5d33d 100644 --- a/tests/test_translate.py +++ b/tests/test_translate.py @@ -66,6 +66,53 @@ def test_supported_instruction(case, make_shader): shader.validate(shader.translate()) +# VOP1/VOP2 DPP source controls. The source lane is a shuffle followed by row/bank masking; a lane that the +# instruction leaves unwritten keeps its old destination, including for non-mov ops. +DPP_CASES = { + "quad_perm": "v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "quad_perm_masked": "v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0x1 bank_mask:0x3", + "row_shl": "v_mov_b32_dpp v1, v0 row_shl:1 row_mask:0xf bank_mask:0xf", + "row_shr_bound": "v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1", + "row_ror": "v_mov_b32_dpp v1, v0 row_ror:4 row_mask:0xf bank_mask:0xf", + "row_share": "v_mov_b32_dpp v1, v0 row_share:2 row_mask:0xf bank_mask:0xf", + "row_xmask": "v_mov_b32_dpp v1, v0 row_xmask:4 row_mask:0xf bank_mask:0xf", + "row_mirror": "v_mov_b32_dpp v1, v0 row_mirror row_mask:0xf bank_mask:0xf", + "row_half_mirror": "v_mov_b32_dpp v1, v0 row_half_mirror row_mask:0xf bank_mask:0xf", + "dpp8": "v_mov_b32_dpp v1, v0 dpp8:[7,6,5,4,3,2,1,0] fi:1", + "vop1_not_bank": "v_not_b32_dpp v1, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0x1", + "vop2_add_shr": "v_add_nc_u32_dpp v1, v0, v2 row_shr:1 row_mask:0xf bank_mask:0xf", +} + + +@pytest.mark.parametrize("case", sorted(DPP_CASES)) +def test_dpp_controls_translate_and_validate(case, make_shader): + shader = make_shader(program("v_mov_b32 v0, v0\n" + DPP_CASES[case])) + spvasm = shader.translate() + shader.validate(spvasm) + assert "OpGroupNonUniformShuffle" in spvasm + + +@pytest.mark.parametrize("mods", [[], ["row_share:20"], ["row_shl:0"], ["row_shl:1", "row_shr:2"]]) +def test_dpp_bad_control_is_rejected(mods): + """A missing, out-of-range or duplicate DPP control must fail instead of guessing.""" + gen = rdna2spirv.Gen("ps") + ins = {"op": "v_mov_b32_dpp", "args": [{"k": "vgpr", "r": 1}, {"k": "vgpr", "r": 0}], "mods": mods} + with pytest.raises(rdna2spirv.Unsupported): + gen.insn(ins) + + +def test_dpp_wave64_emulation_goes_through_workgroup_memory(make_shader, monkeypatch): + """--wave64-emulate must not leave a subgroup shuffle in a DPP shader.""" + shader = make_shader("s_mov_b64 exec, -1\n" + "v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf\n" + "s_endpgm\n", name="cs_dpp_w64") + monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) + spvasm = shader.translate() + shader.validate(spvasm) + assert "OpGroupNonUniform" not in spvasm and "%sg_lane" not in spvasm + assert "%x_buf" in spvasm and "OpControlBarrier" in spvasm + + def test_translation_is_deterministic(make_shader): shader = make_shader(program(SUPPORTED["v_fma_f32"])) assert shader.translate() == shader.translate() @@ -342,6 +389,7 @@ def test_vs_clip_distance_pos1(make_shader, n_comp, exp_line, mask): assert [int(x) for x in chains] == list(range(n_comp)) assert _vgpr_to_index_map(spvasm, "%out_clip", "%_ptr_Output_float") == {i: 10 + i for i in range(n_comp)} meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) + assert meta["clip_distance_count"] == n_comp assert "shaderClipDistance" in meta["features"] assert "shaderCullDistance" not in meta["features"] assert 1 not in meta.get("outputs", []) @@ -392,6 +440,8 @@ def test_vs_clip_and_cull_distances_across_pos1_pos2(make_shader): meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) assert "shaderClipDistance" in meta["features"] assert "shaderCullDistance" in meta["features"] + assert meta["clip_distance_count"] == 2 + assert meta["cull_distance_count"] == 3 assert not ({1, 2} & set(meta.get("outputs", []))) assert not ({1, 2} & set(meta.get("params", []))) @@ -420,6 +470,7 @@ def test_pos1_without_osg1_is_ignored(make_shader): assert "OpCapability ClipDistance" not in vs_spv assert "BuiltIn ClipDistance" not in vs_spv vs_meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, vs_spv) + assert "clip_distance_count" not in vs_meta assert "shaderClipDistance" not in vs_meta["features"] assert 1 not in vs_meta.get("outputs", []) @@ -1203,6 +1254,40 @@ def test_encode_format_f16_uses_f16_bits_rte(suffix, fmt_code, expected_word, ma assert mem[base] == expected_word +@pytest.mark.parametrize("fmt, expected", [(56, 0x80000000), (57, 0x40810000)]) +@pytest.mark.parametrize("packed", [False, True]) +def test_normalized_buffer_store_nan(fmt, expected, packed, make_shader): + # RGBA = positive signaling NaN, negative quiet NaN, -infinity, +0.5. + # gfx1036 stored zero for both NaNs, clamped infinity and rounded 0.5 to even. + if packed: + inputs = "v_mov_b32 v4, 0xfe017c01\nv_mov_b32 v5, 0x3800fc00\n" + store = "buffer_store_format_d16_xyzw v[4:5]" + else: + inputs = ("v_mov_b32 v4, 0x7f800001\nv_mov_b32 v5, 0xffc01000\n" + "v_mov_b32 v6, 0xff800000\nv_mov_b32 v7, 0.5\n") + store = "buffer_store_format_xyzw v[4:7]" + src = ("s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, 4\n" + f"s_mov_b32 s3, {0x31000fac | fmt << 12:#x}\n" + inputs + + f"{store}, off, s[0:3], 0\ns_waitcnt vmcnt(0)\ns_endpgm\n") + shader = make_shader(src, name="ps_store_nan") + spv = shader.translate() + shader.validate(spv) + memory = {0x1000: 0xDEADBEEF} + _load_mini_interp().run_fragment(spv, memory=memory) + assert memory[0x1000] == expected + + +@pytest.mark.parametrize("fmt", [22, 20]) # 32_FLOAT, 32_UINT +def test_unnormalized_buffer_store_keeps_nan_bits(fmt, make_shader): + src = ("s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, 4\n" + f"s_mov_b32 s3, {0x31000fac | fmt << 12:#x}\n" + "v_mov_b32 v4, 0xffc01000\nbuffer_store_format_x v4, off, s[0:3], 0\ns_endpgm\n") + shader = make_shader(src, name="ps_raw_store_nan") + memory = {0x1000: 0} + _load_mini_interp().run_fragment(shader.translate(), memory=memory) + assert memory[0x1000] == 0xFFC01000 + + def test_remaining_d16_paths_avoid_packhalf2x16(make_shader): """buffer_format d16 and image_sample_c_lz d16 avoid PackHalf2x16 and validate with spirv-val.""" tbuf_asm = ( diff --git a/tests/test_ttpf_export_resume.py b/tests/test_ttpf_export_resume.py index ecd295eac..f50a918c0 100644 --- a/tests/test_ttpf_export_resume.py +++ b/tests/test_ttpf_export_resume.py @@ -11,7 +11,7 @@ import unittest import zlib sys.path.insert(0, str(Path(__file__).resolve().parent)) -from test_ttpf_mips import pack_etpf_record, write_rds5_pool +from test_ttpf_mips import build_bc1_bcpack_pool, pack_etpf_record, write_rds5_pool def write_pool(pool): @@ -102,6 +102,33 @@ class TtpfExportResumeTest(unittest.TestCase): self.assertEqual(state(), saved) self.assertEqual(sorted(p.name for p in folder.glob("*.dds")), [rows[1]["File"]]) + def test_confirmed_bcpack_decodes_directly_and_provisional_is_a_limitation(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + + confirmed = root / "confirmed.ttpf" + _, linear, _ = build_bc1_bcpack_pool(confirmed, meta=1) + res = export(confirmed, root / "out_confirmed") + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + confirmed_dir = root / "out_confirmed" / confirmed.stem + rows = textures(confirmed_dir) + self.assertEqual(len(rows), 1) + self.assertIsNotNone(rows[0]["File"]) + self.assertIsNone(rows[0]["Limitation"]) + self.assertEqual((rows[0]["Mips"], rows[0]["BaseMipLevel"]), (5, 0)) + self.assertEqual((confirmed_dir / rows[0]["File"]).read_bytes()[148:], b"".join(linear.values())) + + provisional = root / "provisional.ttpf" + build_bc1_bcpack_pool(provisional, meta=1, ref_dists=[250] + [0] * 1023) + res = export(provisional, root / "out_provisional") + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + provisional_dir = root / "out_provisional" / provisional.stem + rows = textures(provisional_dir) + self.assertEqual(len(rows), 1) + self.assertIsNone(rows[0]["File"]) + self.assertIn("unconfirmed", rows[0]["Limitation"].lower()) + self.assertEqual(list(provisional_dir.glob("*.dds")), []) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_vertex_types.py b/tests/test_vertex_types.py index c7d13dacf..e7d63f857 100644 --- a/tests/test_vertex_types.py +++ b/tests/test_vertex_types.py @@ -31,11 +31,11 @@ def pack_position(x, y, z): return (y & 0xFF) | (x << 8) | ((y >> 8) << 32) | (z << 48) -def grid_triangles(): +def grid_triangles(grid=GRID): tris = [] - for j in range(GRID - 1): - for i in range(GRID - 1): - a, b, c, d = j * GRID + i, j * GRID + i + 1, (j + 1) * GRID + i, (j + 1) * GRID + i + 1 + for j in range(grid - 1): + for i in range(grid - 1): + a, b, c, d = j * grid + i, j * grid + i + 1, (j + 1) * grid + i, (j + 1) * grid + i + 1 tris += [(a, b, c), (b, d, c)] return tris @@ -56,14 +56,15 @@ def group_for(tris, n): return struct.pack("<3I", 0x80000000 | len(chunks), tbase, vbase) + bytes(recs + words + refs) -def block(uv_offset=-5, colour=(10, 20, 30, 255)): - """A 42 40 00 00 block on a flat grid: slots 0 (0x42 position), 1 (0x26), 2 (0x21 = snorm8 +z), 3 (0x28).""" - n = GRID * GRID +def block(uv_offset=-5, colour=(10, 20, 30, 255), grid=GRID, with_group=True): + """A 42 40 00 00 block on a flat grid: slots 0 (0x42 position), 1 (0x26), 2 (0x21 = snorm8 +z), 3 (0x28), + followed by its meshlet group unless with_group is false.""" + n = grid * grid streams = [ - (0, 0x42, b"".join(struct.pack(" { @@ -419,3 +425,38 @@ test('generated test terrain loads without network requests', () => { assert(f.state.live.get('chunk_0').obj); assert.equal(f.state.live.get('chunk_0').loading, false); }); + +test('a valid LOD manifest is accepted', async () => { + const manifest = { spawn: [0, 0, 0], lod_bands: { hd: [0, 130], lod: [130, 450] }, + chunks: [{ ...worldChunk, lod: 'hd', cell: [0, 0, 256, 256] }] }; + const world = await loadWorld(manifestResponse(manifest)); + assert.equal(world.test, false); +}); + +test('LOD sets show one tier per cell by horizontal distance, with slack before unloading', async () => { + const f = fixture(0); + const cell = [0, 0, 256, 256]; + f.context.world = { test: false, lod_bands: { hd: [0, 130], lod: [130, 450], slod1: [450, 1000] }, chunks: [ + { id: 'hd', url: 'hd.glb', bounds: [0, 0, 0, 256, 50, 256], lod: 'hd', cell }, + { id: 'lod', url: 'lod.glb', bounds: [0, 0, 0, 256, 80, 256], lod: 'lod', cell }, + { id: 'slod1', url: 'slod1.glb', bounds: [0, 0, 0, 256, 90, 256], lod: 'slod1', cell }, + ] }; + const pos = f.context.camera.position; + Object.assign(pos, { x: 300, y: 500, z: 100 }); // 44 m east of the cell, high up: still HD + f.frame(); + assert.deepEqual(f.requests.map(r => r.url), ['hd.glb']); + await f.succeed(0, f.object()); + Object.assign(pos, { x: 256 + 150, y: 0, z: 100 }); // 150 m: LOD replaces HD (HD kept inside the slack) + f.frame(); + assert.deepEqual(f.requests.map(r => r.url), ['hd.glb', 'lod.glb']); + assert.ok(f.state.live.has('hd')); + Object.assign(pos, { x: 256 + 200, y: 0, z: 100 }); // past the slack: HD unloads + f.frame(); + assert.ok(!f.state.live.has('hd')); + assert.ok(f.state.live.has('lod')); + Object.assign(pos, { x: 256 + 600, y: 0, z: 100 }); // 600 m: SLOD1 only + f.frame(); + assert.ok(!f.state.live.has('lod')); + assert.equal(f.requests.at(-1).url, 'slod1.glb'); +}); + diff --git a/tests/test_wave64_graphics_scan.py b/tests/test_wave64_graphics_scan.py index 4c9062f36..45945cd29 100644 --- a/tests/test_wave64_graphics_scan.py +++ b/tests/test_wave64_graphics_scan.py @@ -2,6 +2,8 @@ python -I tests/test_wave64_graphics_scan.py -v """ +import contextlib +import io import json import os from pathlib import Path @@ -129,12 +131,67 @@ class ScanTests(unittest.TestCase): report = scan.scan_directory(directory) with open(out, "w", encoding="utf-8") as f: json.dump(report, f) - blob = open(out, encoding="utf-8").read() + with open(out, encoding="utf-8") as f: + blob = f.read() self.assertNotIn(".s", blob) self.assertNotIn("ps_w64a", blob) self.assertNotIn("comment", blob) self.assertIn("v_mbcnt_hi_u32_b32", blob) +class CliTests(unittest.TestCase): + def test_missing_source_directory_raises_error(self): + with self.assertRaises(SystemExit) as cm: + with contextlib.redirect_stderr(io.StringIO()): + scan.main(["nonexistent_shaders_dir_xyz"]) + self.assertNotEqual(cm.exception.code, 0) + + def test_out_is_directory_rejected(self): + with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out_dir: + with self.assertRaises(SystemExit) as cm: + with contextlib.redirect_stderr(io.StringIO()): + scan.main([src, "--out", out_dir]) + self.assertNotEqual(cm.exception.code, 0) + + def test_out_parent_directory_missing_rejected(self): + with tempfile.TemporaryDirectory() as src: + missing_dir = os.path.join(src, "no_such_folder", "out.json") + with self.assertRaises(SystemExit) as cm: + with contextlib.redirect_stderr(io.StringIO()): + scan.main([src, "--out", missing_dir]) + self.assertNotEqual(cm.exception.code, 0) + + def test_out_same_as_source_rejected(self): + with tempfile.TemporaryDirectory() as src: + with self.assertRaises(SystemExit) as cm: + with contextlib.redirect_stderr(io.StringIO()): + scan.main([src, "--out", src]) + self.assertNotEqual(cm.exception.code, 0) + + def test_cli_execution_with_out_json(self): + with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as outdir: + for name, text in (PS_W64_SENSITIVE, VS_W64): + with open(os.path.join(src, name), "w", encoding="utf-8") as f: + f.write(text) + out = os.path.join(outdir, "report.json") + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + code = scan.main([src, "--out", out]) + self.assertEqual(code, 0) + self.assertIn("ps: 1 shaders, 1 wave64", stdout.getvalue()) + self.assertIn("wrote " + out, stdout.getvalue()) + with open(out, encoding="utf-8") as f: + saved = json.load(f) + self.assertIn("per_stage", saved) + self.assertIn("other_stages", saved) + self.assertEqual(saved["per_stage"]["ps"]["shaders"], 1) + self.assertEqual(saved["per_stage"]["vs"]["shaders"], 1) + with open(out, encoding="utf-8") as f: + blob = f.read() + self.assertNotIn(".s", blob) + self.assertNotIn("ps_w64a", blob) + self.assertIn("v_mbcnt_hi_u32_b32", blob) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_world_instancing.py b/tests/test_world_instancing.py new file mode 100644 index 000000000..399baca1b --- /dev/null +++ b/tests/test_world_instancing.py @@ -0,0 +1,393 @@ +"""Tests for the instanced placement build (no game data). + +Covers glb_writer.pack_primitive / build_instanced_glb and world_build.py --placements with --instancing +gpu (EXT_mesh_gpu_instancing), nodes and bake: the per-placement TRS against the baked transform, mirrored +placements, one stored mesh per model and chunk, chunk bounds and triangle counts against the baked build, +process workers, textures and the outcome counts. Every model, entity and texture is synthetic. + + python -I tests/test_world_instancing.py +""" +import json +import math +import os +import random +import shutil +import struct +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TESTS = os.path.dirname(os.path.abspath(__file__)) +for p in (os.path.join(ROOT, "tools"), TESTS): + if p not in sys.path: + sys.path.insert(0, p) + +import glb_writer # noqa: E402 +import test_world_build as twb # noqa: E402 (independent GLB reader, synthetic DDS fixtures) +import test_world_place as twp # noqa: E402 (synthetic box model and entity rows) +import world_build # noqa: E402 + +EXT = "EXT_mesh_gpu_instancing" + + +def matmul(a, b): + return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)] + + +def trs_matrix(q, s): + r = glb_writer._quat_matrix(q) + return [[r[i][j] * s[j] for j in range(3)] for i in range(3)] + + +# RAGE (x, y, z) -> glTF (x, z, -y) +C = [[1, 0, 0], [0, 0, 1], [0, -1, 0]] +CT = [[1, 0, 0], [0, 0, -1], [0, 1, 0]] +MIRROR_Y = [[1, 0, 0], [0, -1, 0], [0, 0, 1]] + + +def read_chunk(world_dir, chunk_id): + with open(os.path.join(world_dir, "chunks", f"{chunk_id}.glb"), "rb") as f: + return twb.parse_and_validate_glb(f.read()) + + +def read_indices(gltf, bin_data, acc_idx): + acc = gltf["accessors"][acc_idx] + bv = gltf["bufferViews"][acc["bufferView"]] + fmt = "<%d%s" % (acc["count"], "H" if acc["componentType"] == 5123 else "I") + return list(struct.unpack_from(fmt, bin_data, bv.get("byteOffset", 0) + acc.get("byteOffset", 0))) + + +class PlacementTrsTest(unittest.TestCase): + def test_trs_equals_the_baked_transform(self): + rnd = random.Random(7) + for _ in range(500): + q = [rnd.uniform(-1, 1) for _ in range(4)] + sxy = rnd.choice([1.0, 2.5, 0.3, -1.0, -2.0]) + sz = rnd.choice([1.0, 0.5, 3.0, -1.0, -0.7]) + pos = [rnd.uniform(-5000, 5000) for _ in range(3)] + t, qi, si, mirrored = world_build.placement_trs(q, sxy, sz, pos) + self.assertTrue(all(v > 0 for v in si)) + self.assertEqual(mirrored, sz < 0) + m_rage, _, mirror = world_build.entity_transform(q, sxy, sz) + self.assertEqual(mirror, mirrored) + want = matmul(matmul(C, m_rage), CT) # the baked transform, in glTF axes + got = trs_matrix(qi, si) + if mirrored: + got = matmul(got, MIRROR_Y) # a mirrored placement draws the Y-mirrored mesh + for i in range(3): + for j in range(3): + self.assertAlmostEqual(got[i][j], want[i][j], places=9) + self.assertTrue(twp.close(t, (pos[0], pos[2], -pos[1]))) + self.assertAlmostEqual(sum(v * v for v in qi), 1.0, places=12) + + def test_instance_bounds_of_a_turned_box(self): + # Unit box, scale 2, turned 90 degrees about +Y, moved by (10, 0, 0): x 10..12, z -2..0 after the turn. + h = math.sqrt(0.5) + b = glb_writer.instance_bounds([0, 0, 0], [1, 1, 1], [10, 0, 0], [0, h, 0, h], [2, 2, 2]) + self.assertTrue(twp.close(b, [10, 0, -2, 12, 2, 0], 1e-12)) + + +def tri_prim(): + return glb_writer.pack_primitive({"positions": [(0, 0, 0), (1, 0, 0), (0, 1, 0)], "normals": [], + "indices": [0, 1, 2], "uvs": []}) + + +class InstancedGlbTest(unittest.TestCase): + def test_gpu_mode(self): + meshes = [{"name": "a", "primitives": [tri_prim()], + "instances": [((0, 0, 0), (0, 0, 0, 1), (1, 1, 1)), ((5, 0, 0), (0, 0, 0, 1), (2, 2, 2))]}, + {"name": "b", "primitives": [tri_prim()], "instances": [((0, 9, 0), (0, 0, 0, 1), (1, 1, 1))]}] + data, st = glb_writer.build_instanced_glb(meshes) + gltf, bin_data = twb.parse_and_validate_glb(data) + glb_writer.read_glb_summary(data) + self.assertEqual(gltf["extensionsUsed"], [EXT]) + self.assertEqual(gltf["extensionsRequired"], [EXT]) + self.assertEqual(len(gltf["meshes"]), 2) + self.assertEqual(len(gltf["nodes"]), 2) + self.assertEqual(gltf["scenes"][0]["nodes"], [0, 1]) + attrs = gltf["nodes"][0]["extensions"][EXT]["attributes"] + self.assertEqual(twb.read_accessor_floats(gltf, bin_data, attrs["TRANSLATION"]), [(0, 0, 0), (5, 0, 0)]) + self.assertEqual(twb.read_accessor_floats(gltf, bin_data, attrs["SCALE"]), [(1, 1, 1), (2, 2, 2)]) + self.assertEqual(gltf["accessors"][attrs["ROTATION"]]["type"], "VEC4") + self.assertNotIn("target", gltf["bufferViews"][gltf["accessors"][attrs["ROTATION"]]["bufferView"]]) + self.assertEqual((st["triangles"], st["stored_triangles"], st["instances"], st["meshes"]), (3, 2, 3, 2)) + self.assertTrue(twp.close(st["bounds"], [0, 0, 0, 7, 10, 0])) + + def test_nodes_mode_writes_one_node_per_instance(self): + h = math.sqrt(0.5) + meshes = [{"primitives": [tri_prim()], + "instances": [((0, 0, 0), (0, 0, 0, 1), (1, 1, 1)), ((1, 2, 3), (0, 0, h, h), (1, 1, 4))]}] + data, st = glb_writer.build_instanced_glb(meshes, mode="nodes") + gltf, _ = twb.parse_and_validate_glb(data) + self.assertNotIn("extensionsUsed", gltf) + self.assertEqual(gltf["nodes"][0], {"mesh": 0}) + self.assertEqual(gltf["nodes"][1]["translation"], [1, 2, 3]) + self.assertEqual(gltf["nodes"][1]["scale"], [1, 1, 4]) + self.assertTrue(twp.close(gltf["nodes"][1]["rotation"], [0, 0, h, h], 1e-12)) + self.assertEqual(len(gltf["meshes"]), 1) + self.assertEqual(st["instances"], 2) + + def test_rejects_mirroring_scale_and_bad_input(self): + bad = [{"primitives": [tri_prim()], "instances": [((0, 0, 0), (0, 0, 0, 1), (1, -1, 1))]}] + with self.assertRaisesRegex(glb_writer.GlbError, "determinant"): + glb_writer.build_instanced_glb(bad) + with self.assertRaisesRegex(glb_writer.GlbError, "no mesh"): + glb_writer.build_instanced_glb([{"primitives": [tri_prim()], "instances": []}]) + with self.assertRaisesRegex(glb_writer.GlbError, "mode"): + glb_writer.build_instanced_glb(bad, mode="other") + + def test_mirror_packed(self): + p = glb_writer.pack_primitive({"positions": [(0, 1, 0), (1, 2, 0), (0, 3, 1)], "normals": [], + "indices": [0, 1, 2], "uvs": []}) + m = world_build._mirror_packed(p) + pos = struct.unpack("<9f", m["positions"]) + self.assertEqual(pos[1::3], (-1.0, -2.0, -3.0)) + self.assertEqual(struct.unpack("<3H", m["indices"]), (0, 2, 1)) + self.assertEqual((m["min"][1], m["max"][1]), (-3.0, -1.0)) + nrm = struct.unpack("<9f", m["normals"]) + orig = struct.unpack("<9f", p["normals"]) + self.assertEqual(nrm[1::3], tuple(-v for v in orig[1::3])) + + def test_pack_round_trip(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "m.lpk") + p = tri_prim() + p["material"] = "tex_x" + world_build._write_pack(path, [p, tri_prim()]) + back = world_build._read_pack(path) + self.assertEqual(len(back), 2) + for k in ("positions", "normals", "uvs", "indices", "index_type", "vertices", "index_count", "min", "max"): + self.assertEqual(back[0][k], p[k]) + self.assertEqual(back[0]["material"], "tex_x") + + +# A placement set that exercises turns, non-uniform scale, both negative scales and two chunks. +def mixed_rows(): + S2 = math.sqrt(0.5) + return [ + twp.entity("test_box", (100, 200, 10), twp.stored_rotation_about_z(90), sxy=2.0, sz=1.0), + twp.entity("test_box", (110, 205, 12), [0.1, 0.2, 0.3, 0.9], sxy=1.5, sz=0.5), + twp.entity("test_box", (120, 210, 0), [0.0, S2, 0.0, S2], sxy=1.0, sz=-1.0), # mirrored + twp.entity("test_box", (130, 220, 0), [0.0, 0.0, 0.0, 1.0], sxy=-2.0, sz=1.0), # XY turn, not a mirror + twp.entity("test_box", (1000, 1000, 0), lod=5, key=False), # second chunk + twp.entity("test_box", (5, 5, 5), sxy=0.0), # degenerate + twp.entity("other_box", (0, 0, 0)), # unresolved + ] + + +class InstancedBuildTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(lambda: shutil.rmtree(self.tmp, ignore_errors=True)) + self.assets = twp.write_assets(self.tmp) + + def build(self, rows, name="world", **kw): + ents = os.path.join(self.tmp, f"{name}.jsonl") + twp.write_entities(ents, rows) + kw.setdefault("textures", False) + out = os.path.join(self.tmp, name) + return world_build.build_world(self.assets, out, placements=ents, **kw), out + + def test_shared_geometry_per_chunk(self): + rows = [twp.entity("test_box", (10 + i, 10, 0)) for i in range(3)] + doc, out = self.build(rows) + self.assertEqual(doc["instancing"], "gpu") + (chunk,) = doc["chunks"] + self.assertEqual((chunk["models"], chunk["distinct_models"], chunk["triangles"], chunk["stored_triangles"]), + (3, 1, 36, 12)) + gltf, bin_data = read_chunk(out, chunk["id"]) + self.assertEqual((len(gltf["meshes"]), len(gltf["nodes"])), (1, 1)) + attrs = gltf["nodes"][0]["extensions"][EXT]["attributes"] + got = twb.read_accessor_floats(gltf, bin_data, attrs["TRANSLATION"]) + self.assertEqual(sorted(got), [(10, 0, -10), (11, 0, -10), (12, 0, -10)]) + self.assertEqual(doc["stats"]["stored_triangles"], 12) + self.assertEqual(doc["stats"]["max_chunk_bytes"], doc["stats"]["chunk_bytes"]) + + def test_same_chunks_bounds_and_counts_as_the_baked_build(self): + rows = [r for r in mixed_rows() if r["scale_xy"] != 0] # bake also places a flat (zero-scale) copy + gpu, _ = self.build(rows, "gpu") + bake, _ = self.build(rows, "bake", instancing="bake") + self.assertEqual([c["id"] for c in gpu["chunks"]], [c["id"] for c in bake["chunks"]]) + for a, b in zip(gpu["chunks"], bake["chunks"]): + self.assertTrue(twp.close(a["bounds"], b["bounds"], 1e-4), (a["bounds"], b["bounds"])) + self.assertEqual((a["models"], a["triangles"]), (b["models"], b["triangles"])) + pg, pb = gpu["stats"]["placements"], bake["stats"]["placements"] + for k in ("rows", "selected", "placed", "placed_unverified", "unresolved_archetype", "key_mismatch"): + self.assertEqual(pg[k], pb[k], k) + self.assertEqual((pg["degenerate_scale"], pg["mirrored"]), (0, 1)) + + def test_zero_scale_is_counted_not_placed(self): + doc, _ = self.build(mixed_rows()) + pl = doc["stats"]["placements"] + self.assertEqual((pl["degenerate_scale"], pl["placed"], pl["placed_unverified"]), (1, 4, 1)) + + def test_mirrored_placement_draws_a_mirrored_mesh(self): + doc, out = self.build([twp.entity("test_box", (10, 10, 0), sz=-1.0), twp.entity("test_box", (12, 10, 0))]) + gltf, bin_data = read_chunk(out, doc["chunks"][0]["id"]) + names = sorted(m.get("name", "") for m in gltf["meshes"]) + self.assertEqual(len(names), 2) + self.assertTrue(names[1].endswith("_mirror")) + by_name = {m["name"]: m for m in gltf["meshes"]} + plain, mirror = by_name[names[0]]["primitives"][0], by_name[names[1]]["primitives"][0] + a = read_indices(gltf, bin_data, plain["indices"]) + b = read_indices(gltf, bin_data, mirror["indices"]) + self.assertEqual(b, [x for t in zip(a[0::3], a[2::3], a[1::3]) for x in t]) + pa = twb.read_accessor_floats(gltf, bin_data, plain["attributes"]["POSITION"]) + pb = twb.read_accessor_floats(gltf, bin_data, mirror["attributes"]["POSITION"]) + self.assertEqual(pb, [(x, -y, z) for x, y, z in pa]) + # Mirrored about the model's Z (glTF Y): the box spans y 0..1 below the placement instead of above. + self.assertTrue(twp.close(doc["chunks"][0]["bounds"][1:5:3], [-1, 1], 1e-6)) + + def test_nodes_mode(self): + doc, out = self.build([twp.entity("test_box", (10 + i, 10, 0)) for i in range(4)], instancing="nodes") + gltf, _ = read_chunk(out, doc["chunks"][0]["id"]) + self.assertEqual((len(gltf["meshes"]), len(gltf["nodes"])), (1, 4)) + self.assertNotIn("extensionsRequired", gltf) + self.assertEqual(doc["instancing"], "nodes") + + def test_process_workers_give_the_same_world(self): + one, out1 = self.build(mixed_rows(), "one", jobs=1) + two, out2 = self.build(mixed_rows(), "two", jobs=2) + one.pop("spawn"), two.pop("spawn") + for c in one["chunks"] + two["chunks"]: + c.pop("url") + self.assertEqual(one, two) + for c in one["chunks"]: + with open(os.path.join(out1, "chunks", c["id"] + ".glb"), "rb") as f1, \ + open(os.path.join(out2, "chunks", c["id"] + ".glb"), "rb") as f2: + self.assertEqual(f1.read(), f2.read()) + + def test_missing_model_file_is_counted(self): + os.remove(os.path.join(self.assets, "levels", "models", "box.obj")) + with self.assertRaisesRegex(ValueError, "could be placed"): + self.build([twp.entity("test_box", (10, 10, 0))]) + self.assertFalse(os.path.exists(os.path.join(self.tmp, "world", "world.json"))) + + def test_pack_cache_is_removed(self): + _, out = self.build([twp.entity("test_box", (10, 10, 0))]) + self.assertEqual(sorted(os.listdir(out)), ["chunks", "world.json"]) + + def test_textured_instances_embed_the_texture_once(self): + assets = os.path.join(self.tmp, "tex_assets") + twb._write_param_fixture(assets, twb.PARAM_CASES["albedo-first"]) + ents = os.path.join(self.tmp, "tex.jsonl") + twp.write_entities(ents, [twp.entity("tri", (10 + i, 10, 0)) for i in range(5)]) + out = os.path.join(self.tmp, "tex_world") + doc = world_build.build_world(assets, out, placements=ents) + self.assertEqual(doc["stats"]["textures_embedded"], 1) + glb = os.path.join(out, "chunks", doc["chunks"][0]["id"] + ".glb") + _, rgba = twb._glb_first_base_color_pixel(glb) + self.assertEqual(rgba, tuple(twb.ALBEDO_RGBA)) + gltf, _ = read_chunk(out, doc["chunks"][0]["id"]) + self.assertEqual((len(gltf["images"]), len(gltf["meshes"])), (1, 1)) + + def test_cli_instancing_option(self): + ents = os.path.join(self.tmp, "cli.jsonl") + twp.write_entities(ents, [twp.entity("test_box", (10, 10, 0))]) + out = os.path.join(self.tmp, "cli") + import contextlib + import io + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rc = world_build.main([self.assets, "--out", out, "--no-textures", "--placements", ents, + "--instancing", "nodes"]) + self.assertEqual(rc, 0) + self.assertIn("placements", buf.getvalue()) + with open(os.path.join(out, "world.json"), encoding="utf-8") as f: + self.assertEqual(json.load(f)["instancing"], "nodes") + + +class LodSetsTest(unittest.TestCase): + def test_bands_follow_the_parent_child_distances(self): + child = {1: [120, 130, 140], 2: [450], 3: [1000], 4: [1976], 6: [6000]} + own = {0: [124], 1: [450], 2: [1000], 3: [2000], 4: [4000], 5: [900, 1100], 6: [20000]} + bands, measured = world_build.lod_bands(child, own, [0, 1, 2, 3, 4, 5, 6]) + self.assertEqual(bands, {"hd": [0.0, 130.0], "lod": [130.0, 450.0], "slod1": [450.0, 1000.0], + "slod2": [1000.0, 1976.0], "slod3": [1976.0, 6000.0], "slod4": [6000.0, 20000.0], + "orphan_hd": [0.0, 1000.0]}) + self.assertEqual(measured["lod"]["child_lod_dist_median"], 130.0) + + def test_missing_tiers_still_give_contiguous_bands(self): + bands, _ = world_build.lod_bands({2: [450]}, {2: [1000]}, [0, 2]) + self.assertEqual(bands, {"hd": [0.0, 450.0], "slod1": [450.0, 1000.0]}) + + def build(self, rows, **kw): + tmp = tempfile.mkdtemp() + self.addCleanup(lambda: shutil.rmtree(tmp, ignore_errors=True)) + assets = twp.write_assets(tmp) + ents = os.path.join(tmp, "e.jsonl") + twp.write_entities(ents, rows) + out = os.path.join(tmp, "w") + return world_build.build_world(assets, out, placements=ents, textures=False, **kw), out + + def lod_row(self, pos, lod, child=None, own=None): + r = twp.entity("test_box", pos, lod=lod) + r["child_lod_dist"] = child + r["lod_dist"] = own + return r + + def test_one_chunk_per_tier_and_cell(self): + rows = [self.lod_row((10, 10, 0), 0, own=-1.0), self.lod_row((12, 10, 0), 0), + self.lod_row((10, 10, 0), 1, child=130.0, own=450.0), self.lod_row((10, 10, 0), 2, child=450.0, own=1000.0), + self.lod_row((300, 10, 0), 5, own=800.0)] + doc, out = self.build(rows, lod_sets=True, lod_levels=world_build.ALL_LOD_LEVELS) + ids = sorted(c["id"] for c in doc["chunks"]) + self.assertEqual(ids, ["c_hd_0_-1", "c_lod_0_-1", "c_orphan_hd_1_-1", "c_slod1_0_-1"]) + by = {c["id"]: c for c in doc["chunks"]} + self.assertEqual(by["c_hd_0_-1"]["cell"], [0.0, -256.0, 256.0, 0.0]) + self.assertEqual(by["c_hd_0_-1"]["lod"], "hd") + self.assertEqual(by["c_hd_0_-1"]["models"], 2) + self.assertEqual(doc["lod_bands"], {"hd": [0.0, 130.0], "lod": [130.0, 450.0], "slod1": [450.0, 1000.0], + "orphan_hd": [0.0, 800.0]}) + self.assertEqual(doc["stats"]["lod_tiers"]["hd"]["placements"], 2) + with open(os.path.join(out, "world.json"), encoding="utf-8") as f: + self.assertEqual(json.load(f)["lod_bands"]["lod"], [130.0, 450.0]) + + def test_option_rules(self): + with self.assertRaisesRegex(ValueError, "lod-sets needs --instancing"): + self.build([self.lod_row((0, 0, 0), 0)], lod_sets=True, instancing="bake") + with tempfile.TemporaryDirectory() as tmp: + assets = twp.write_assets(tmp) + with self.assertRaisesRegex(ValueError, "lod-sets needs --placements"): + world_build.build_world(assets, os.path.join(tmp, "w"), lod_sets=True) + + def test_cli_places_every_level_with_lod_sets(self): + import contextlib + import io + with tempfile.TemporaryDirectory() as tmp: + assets = twp.write_assets(tmp) + ents = os.path.join(tmp, "e.jsonl") + twp.write_entities(ents, [self.lod_row((10, 10, 0), 0), self.lod_row((10, 10, 0), 3, child=1000.0)]) + out = os.path.join(tmp, "w") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, + "--lod-sets"]), 0) + with open(os.path.join(out, "world.json"), encoding="utf-8") as f: + self.assertEqual(sorted(json.load(f)["lod_bands"]), ["hd", "slod2"]) + self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, + "--lod-sets", "--lod-levels", "0"]), 0) + with open(os.path.join(out, "world.json"), encoding="utf-8") as f: + self.assertEqual(sorted(json.load(f)["lod_bands"]), ["hd"]) + + +class IterPlacementsTest(unittest.TestCase): + def test_same_rows_and_counts_as_load_placements(self): + good = [twp.entity("test_box", (1, 2, 3), sxy=2.0, sz=3.0), twp.entity("test_box", (9, 8, 7), lod=5), + twp.entity("test_box", (5, 5, 5), lod=1), twp.entity("test_box", (500, 5, 5))] + odd = [dict(twp.entity("test_box", (4, 5, 6)), lod_level=[]), + dict(twp.entity("test_box", (4, 5, 6)), position=[10 ** 400, 0, 0]), + dict(twp.entity("test_box", (4, 5, 6)), scale_xy="2.0", scale_z=10 ** 400)] + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "e.jsonl") + twp.write_entities(path, good + odd, extra_lines=["{not json"]) + for kw in ({}, {"lod_levels": (0, 1)}, {"region": (0, 0, 100, 100)}): + rows, counts = world_build.load_placements(path, **kw) + c2 = world_build._placement_counts() + rows2 = list(world_build.iter_placements(path, c2, **kw)) + self.assertEqual(rows2, rows, kw) + self.assertEqual(c2, counts, kw) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_world_place.py b/tests/test_world_place.py index 1457e336e..13361ce9c 100644 --- a/tests/test_world_place.py +++ b/tests/test_world_place.py @@ -177,6 +177,55 @@ class TransformTest(unittest.TestCase): self.assertEqual(world_build.place_primitives(prims, [0, 0, 0, 1], 1.0, 1.0, (0, 0, 0))[0]["indices"], [0, 1, 2]) +class PlacementLoadTest(unittest.TestCase): + def load(self, rows, **kwargs): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "entities.jsonl") + write_entities(path, rows) + return world_build.load_placements(path, **kwargs) + + def test_malformed_values_preserve_valid_neighbors(self): + before = entity("test_box", (1, 2, 3), sxy=2.0, sz=3.0) + after = entity("test_box", (9, 8, 7), sxy=-1.0, sz=0.5) + patches = ( + {"lod_level": []}, {"lod_level": {}}, + {"position": [10**400, 0, 0]}, {"rotation": [0, 0, 0, -(10**400)]}, + ) + for patch in patches: + with self.subTest(field=next(iter(patch))): + bad = dict(entity("test_box", (4, 5, 6)), **patch) + rows, counts = self.load([before, bad, after]) + self.assertEqual([row["_pos"] for row in rows], [[1.0, 2.0, 3.0], [9.0, 8.0, 7.0]]) + self.assertEqual([(row["_sxy"], row["_sz"]) for row in rows], [(2.0, 3.0), (-1.0, 0.5)]) + self.assertEqual(counts, {"rows": 3, "malformed": 1, "other_lod_level": 0, + "outside_region": 0, "selected": 2}) + + def test_invalid_optional_scales_keep_unit_fallback(self): + for field in ("scale_xy", "scale_z"): + for value in (None, "2.0", [], {}, float("nan"), float("inf"), -float("inf"), 10**400, -(10**400)): + with self.subTest(field=field, value=value): + middle = entity("test_box", (4, 5, 6), sxy=2.0, sz=3.0) + middle[field] = value + rows, counts = self.load([entity("test_box", (0, 0, 0)), middle, entity("test_box", (9, 8, 7))]) + self.assertEqual(counts["selected"], 3) + self.assertEqual(counts["malformed"], 0) + self.assertEqual((rows[1]["_sxy"], rows[1]["_sz"]), + (1.0, 3.0) if field == "scale_xy" else (2.0, 1.0)) + + def test_finite_scales_and_filter_counts_unchanged(self): + missing_lod = entity("test_box", (1, 1, 0)) + del missing_lod["lod_level"] + rows, counts = self.load([ + entity("test_box", (1, 1, 0), sxy=0, sz=-2.5), + entity("test_box", (2, 2, 0), sxy=-3, sz=0, lod=5), + entity("test_box", (1, 1, 0), lod=1), missing_lod, + entity("test_box", (10, 10, 0)), + ], region=(0, 0, 5, 5)) + self.assertEqual([(row["_sxy"], row["_sz"]) for row in rows], [(0.0, -2.5), (-3.0, 0.0)]) + self.assertEqual(counts, {"rows": 5, "malformed": 0, "other_lod_level": 2, + "outside_region": 1, "selected": 2}) + + class PlacedBuildTest(unittest.TestCase): def build(self, rows, extra_lines=(), **kw): tmp = tempfile.mkdtemp() @@ -218,6 +267,20 @@ class PlacedBuildTest(unittest.TestCase): pl = self.build(rows, region=(0, 0, 100, 100), lod_levels=(0, 1))["stats"]["placements"] self.assertEqual((pl["selected"], pl["outside_region"], pl["placed"]), (2, 1, 2)) + def test_build_continues_after_malformed_placement_rows(self): + rows = [entity("test_box", (10, 10, 0)), + entity("test_box", (0, 0, 0), lod=[]), + entity("test_box", (10**400, 0, 0)), + entity("test_box", (20, 20, 0), sxy=10**400, sz=-(10**400)), + entity("test_box", (30, 30, 0))] + doc = self.build(rows) + counts = doc["stats"]["placements"] + self.assertEqual((counts["rows"], counts["malformed"], counts["selected"], counts["placed"]), (5, 2, 3, 3)) + # Overflowing optional scales act like the existing missing-scale defaults, including geometry bounds. + control = self.build([rows[0], entity("test_box", (20, 20, 0)), rows[-1]]) + self.assertEqual(doc["stats"]["triangles"], control["stats"]["triangles"]) + self.assertEqual([chunk["bounds"] for chunk in doc["chunks"]], [chunk["bounds"] for chunk in control["chunks"]]) + def test_nothing_placeable_leaves_output_unchanged(self): with self.assertRaisesRegex(ValueError, "could be placed"): self.build([entity("other_box", (0, 0, 0))]) diff --git a/third_party/rpf9-explorer b/third_party/rpf9-explorer index 917e9b9c7..e2939175c 160000 --- a/third_party/rpf9-explorer +++ b/third_party/rpf9-explorer @@ -1 +1 @@ -Subproject commit 917e9b9c75d7a200d143565740abab6026173bce +Subproject commit e2939175c36a02d6ed25fa2c217b9d6ddcb8b516 diff --git a/tools/anim_clips.py b/tools/anim_clips.py index 02a3da1bb..d2a88735b 100644 --- a/tools/anim_clips.py +++ b/tools/anim_clips.py @@ -51,6 +51,10 @@ TRACK_TYPE_NAMES = ("bonerotation", "bonetranslation", "bonescale", "genericcont TRACK_TYPES = {anim_index.joaat32(n): n for n in TRACK_TYPE_NAMES} TRACK_FORMATS = {0: "quaternion", 2: "vector3", 4: "float"} +# `.motion` axis names: joaat32 of the lower-case name, recovered by brute force over a word list +AXIS_NAMES = {anim_index.joaat32(n): n for n in ("yawangle", "rotationz", "facingdirection", "speed", "surfaceincline", + "roll", "verticalheight", "pitch", "pitchangle", "height")} + class DecodeError(ValueError): pass @@ -144,6 +148,44 @@ def parse_animation(s, at): } +def motion_times(s, at): + """`.motion` +0x70: one 0x28-byte entry per child, {f32 child duration, f32 duration in the blend, + {ptr, u16 count} curve of (child time, blend time) f32 pairs, 16 zero bytes}. -> [(duration, blend, points)]""" + p, n = s.array(at + 0x70) + out = [] + for i in range(n if p is not None else 0): + e = p + 0x28 * i + cp, cn = s.array(e + 8) + points = [(s.f32(cp + 8 * j), s.f32(cp + 8 * j + 4)) for j in range(cn)] if cp is not None else [] + out.append((s.f32(e), s.f32(e + 4), points)) + return out + + +def parameter_node(s, at, parameters): + """The node that places a `.motion`'s children in parameter space: the pointer at +0x138 when +0x58 is 1; + when +0x58 is 2, +0x120 points at a block whose +0x18 is the node. A node starts {u64 0, u32 type, u32 0}. + Type 3 is one sampled axis: {array of u32 name hashes, array of (u32 sample index, f32 value) sorted by + value, f32 min, f32 max}. Other types are not decoded. -> (type, axis or None) or None""" + if parameters == 1: + node = s.ptr(at + 0x138) + elif parameters == 2: + block = s.ptr(at + 0x120) + node = s.ptr(block + 0x18) if block is not None else None + else: + return None + if node is None or s.u64(node) != 0 or s.u32(node + 12) != 0: + return None + kind, axis = s.u32(node + 8), None + if kind == 3: + names, nn = s.array(node + 0x10) + samples, ns = s.array(node + 0x20) + if names is not None and samples is not None: + axis = {"names": [s.u32(names + 4 * i) for i in range(nn)], + "samples": [(s.u32(samples + 8 * i), s.f32(samples + 8 * i + 4)) for i in range(ns)], + "min": s.f32(node + 0x30), "max": s.f32(node + 0x34)} + return kind, axis + + def parse_clip(s, at): kind = s.u32(at + 0x20) if kind >= 16: # +0x20 is a pointer: a parametric clip that refers to packs outside the dictionary @@ -162,6 +204,11 @@ def parse_clip(s, at): motion["parameters"] = s.u32(at + 0x58) except (DecodeError, struct.error): pass + try: + motion["times"] = motion_times(s, at) + motion["node"] = parameter_node(s, at, motion["parameters"]) + except (DecodeError, struct.error): + motion["times"], motion["node"] = None, None return motion # `.motionmatcher`: a 16-byte id at +0x28, name at +0x38 return {"kind": "motionmatcher", "name": s.string(at + 0x38), "animations": []} @@ -544,6 +591,49 @@ def group(m, rows): return out, unresolved, gaps +def child_times(c): + """A `.motion`'s +0x70 entries lined up with its children (None where they don't line up).""" + times = c.get("times") + return times if times is not None and len(times) == len(c["children"]) else [None] * len(c["children"]) + + +def count_motion_blend(c, stats): + """Counts for a `.motion`'s +0x70 child times and its parameter node (no values).""" + times = c.get("times") + if times is None: + stats["motion_times_unreadable"] += 1 + else: + stats["motion_times_one_per_child"] += len(times) == len(c["children"]) + for duration, blend, points in times: + stats["motion_child_times"] += 1 + if len(points) == 2 and points == [(0.0, 0.0), (duration, blend)] and duration == blend: + stats["motion_child_times_identity"] += 1 + elif (len(points) > 2 and points[0] == (0.0, 0.0) and points[-1] == (duration, blend) and + all(a[0] <= b[0] and a[1] <= b[1] for a, b in zip(points, points[1:]))): + stats["motion_child_times_warped"] += 1 + else: + stats["motion_child_times_other"] += 1 + node = c.get("node") + if node is None: + stats["motion_node_unreadable"] += 1 + return + kind, axis = node + stats[f"motion_node_type:{kind}"] += 1 + if axis is None: + return + values = [v for _i, v in axis["samples"]] + stats["motion_axes"] += 1 + stats["motion_axis_samples"] += len(values) + stats["motion_axis_one_name"] += len(axis["names"]) == 1 + stats["motion_axis_sorted"] += all(a <= b for a, b in zip(values, values[1:])) + stats["motion_axis_range_is_first_last"] += bool(values) and (axis["min"], axis["max"]) == (values[0], values[-1]) + stats["motion_axis_indices_are_0_to_n"] += sorted(i for i, _v in axis["samples"]) == list(range(len(values))) + stats["motion_axis_samples_equal_children"] += len(values) == len(c["children"] or []) + stats[f"motion_axis_sample_count:{len(values)}"] += 1 + for h in axis["names"]: + stats["motion_axis_name:" + AXIS_NAMES.get(h, f"0x{h:08x}")] += 1 + + def new_stats(): return collections.Counter() @@ -592,6 +682,7 @@ def decode_resource(path, segments, budget=None): stats[f"motion_parameters:{c['parameters']}"] += 1 stats["motion_children"] += len(c["children"]) stats["motion_children_in_external_refs"] += sum(dh in external for _ch, dh in c["children"]) + count_motion_blend(c, stats) stats["clip_animation_refs"] += sum(len(c["animations"]) for c in d["clips"]) stats["packs_local"] += len(d["packs"]) stats["packs_external"] += d["external_packs"] @@ -623,7 +714,10 @@ def decode_resource(path, segments, budget=None): row["over_budget"] = True # for the archive-wide join in scan(); scan() removes these lists from the rows it returns row["_clip_hashes"] = [c["hash"] for c in d["clips"] if c["kind"] == "clip"] + row["_clip_durations"] = [c["duration"] for c in d["clips"] if c["kind"] == "clip"] row["_children"] = [ch for c in d["clips"] if c["kind"] == "motion" and c["children"] for ch in c["children"]] + row["_child_durations"] = [t[0] if t else None for c in d["clips"] if c["kind"] == "motion" and c["children"] + for t in child_times(c)] row["_external"] = d["external_hashes"] row.update(hash=f"0x{d['hash']:08x}", name=d["name"], clips=len(d["clips"]), packs=len(d["packs"]), external_packs=d["external_packs"], animations=ok + failed + skipped, decoded=ok, @@ -635,9 +729,12 @@ def join_references(rows, stats): """Resolve hash-only references across the archive: a root `+0x70` item with a null pointer names another dictionary (its joaat32 name hash), and a `.motion` child is {clip hash, dictionary hash}.""" clips_by_dict = collections.defaultdict(set) + duration = {} for r in rows: if "_clip_hashes" in r: clips_by_dict[int(r["hash"], 16)].update(r["_clip_hashes"]) + for h, t in zip(r["_clip_hashes"], r.get("_clip_durations", [])): + duration[(int(r["hash"], 16), h)] = t ext_seen = set() for r in rows: for h in r.pop("_external", []): @@ -646,11 +743,15 @@ def join_references(rows, stats): ext_seen.add(h) stats["external_hashes_distinct"] += 1 stats["external_hashes_distinct_found_here"] += h in clips_by_dict - for ch, dh in r.pop("_children", []): + kids = r.pop("_children", []) + for (ch, dh), t in zip(kids, r.pop("_child_durations", [None] * len(kids))): if dh in clips_by_dict: stats["motion_children_dictionary_here"] += 1 stats["motion_children_resolved_to_clip"] += ch in clips_by_dict[dh] + if ch in clips_by_dict[dh] and t is not None: + stats["motion_child_duration_equals_clip"] += duration.get((dh, ch)) == t r.pop("_clip_hashes", None) + r.pop("_clip_durations", None) def _decode_star(args): diff --git a/tools/bary_fallback_gs.py b/tools/bary_fallback_gs.py index 1f2c31ad3..7e440c138 100644 --- a/tools/bary_fallback_gs.py +++ b/tools/bary_fallback_gs.py @@ -10,8 +10,12 @@ BaryCoordKHR has, so the pixel shader's .y/.z are AMD's i/j. python -I tools/bary_fallback_gs.py # .bary_gs.spv per such PS in index.json -Standard library only; build_for_index assembles and validates with spirv-as / spirv-val from PATH. + python -I tools/bary_fallback_gs.py --pair VS PS + +The paired helper forwards a VS ClipDistance or CullDistance array. The suffix identifies the kind and length. +Mixed clip/cull layouts are rejected. Standard library only; build_for_index assembles and validates with spirv-as / spirv-val from PATH. """ +import argparse import json import os import subprocess @@ -20,7 +24,7 @@ import sys SUFFIX = ".bary_gs" # .bary_gs.spvasm / .spv next to the pixel shader -def gs_spvasm(locations, bary_location): +def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0): """SPIR-V assembly for a triangle pass-through GS: Position and the vec4 inputs at `locations`, copied per vertex, plus the one-hot barycentric vec3 at `bary_location`.""" locations = sorted(set(int(n) for n in locations)) @@ -28,9 +32,20 @@ def gs_spvasm(locations, bary_location): raise ValueError(f"bary location {bary_location} collides with a pass-through location") ins = [f"%in{n}" for n in locations] outs = [f"%out{n}" for n in locations] - iface = " ".join(["%in_pos", "%out_pos", *ins, *outs, "%out_bary"]) + if type(clip_count) is not int or not 0 <= clip_count <= 8: + raise ValueError("clip distance count must be an integer from 0 to 8") + if type(cull_count) is not int or not 0 <= cull_count <= 8: + raise ValueError("cull distance count must be an integer from 0 to 8") + if clip_count and cull_count: + raise ValueError("paired helper cannot forward mixed ClipDistance and CullDistance") + count = clip_count or cull_count + kind = "cull" if cull_count else "clip" + builtin = kind.title() + "Distance" + distance_iface = [f"%in_{kind}", f"%out_{kind}"] if count else [] + iface = " ".join(["%in_pos", "%out_pos", *ins, *outs, "%out_bary", *distance_iface]) lines = [ "OpCapability Geometry", + *([f"OpCapability {builtin}"] if count else []), "OpMemoryModel Logical GLSL450", f'OpEntryPoint Geometry %main "main" {iface}', "OpExecutionMode %main Triangles", @@ -39,6 +54,8 @@ def gs_spvasm(locations, bary_location): "OpExecutionMode %main OutputVertices 3", "OpDecorate %in_pos BuiltIn Position", "OpDecorate %out_pos BuiltIn Position", + *([f"OpDecorate %in_{kind} BuiltIn {builtin}", f"OpDecorate %out_{kind} BuiltIn {builtin}"] + if count else []), *[f"OpDecorate %in{n} Location {n}" for n in locations], *[f"OpDecorate %out{n} Location {n}" for n in locations], f"OpDecorate %out_bary Location {int(bary_location)}", @@ -55,6 +72,12 @@ def gs_spvasm(locations, bary_location): "%ptr_in_v4 = OpTypePointer Input %v4float", "%ptr_out_v4 = OpTypePointer Output %v4float", "%ptr_out_v3 = OpTypePointer Output %v3float", + *([f"%{kind}_count = OpConstant %uint {count}", + f"%{kind} = OpTypeArray %float %{kind}_count", + f"%triangle_{kind} = OpTypeArray %{kind} %uint_3", + f"%ptr_in_triangle_{kind} = OpTypePointer Input %triangle_{kind}", + f"%ptr_in_{kind} = OpTypePointer Input %{kind}", + f"%ptr_out_{kind} = OpTypePointer Output %{kind}"] if count else []), "%f0 = OpConstant %float 0", "%f1 = OpConstant %float 1", "%bary0 = OpConstantComposite %v3float %f1 %f0 %f0", @@ -66,6 +89,8 @@ def gs_spvasm(locations, bary_location): *[f"{v} = OpVariable %ptr_in_arr Input" for v in ins], *[f"{v} = OpVariable %ptr_out_v4 Output" for v in outs], "%out_bary = OpVariable %ptr_out_v3 Output", + *([f"%in_{kind} = OpVariable %ptr_in_triangle_{kind} Input", f"%out_{kind} = OpVariable %ptr_out_{kind} Output"] + if count else []), "%main = OpFunction %void None %fn", "%entry = OpLabel", ] @@ -74,36 +99,66 @@ def gs_spvasm(locations, bary_location): p, x = f"%p{v}_{src[1:]}", f"%x{v}_{src[1:]}" lines += [f"{p} = OpAccessChain %ptr_in_v4 {src} %int_{v}", f"{x} = OpLoad %v4float {p}", f"OpStore {dst} {x}"] + if count: + lines += [f"%{kind}_ptr{v} = OpAccessChain %ptr_in_{kind} %in_{kind} %int_{v}", + f"%distances{v} = OpLoad %{kind} %{kind}_ptr{v}", f"OpStore %out_{kind} %distances{v}"] lines += [f"OpStore %out_bary %bary{v}", "OpEmitVertex"] lines += ["OpEndPrimitive", "OpReturn", "OpFunctionEnd"] return "\n".join(lines) + "\n" -def write_for_index(spirv_dir): - """Write .bary_gs.spvasm for every pixel shader in /index.json that has a "bary_fallback_input". - Returns the written paths (empty when there is no index or no such shader).""" +def write_for_index(spirv_dir, pair: tuple[str, str] | None = None): + """Write helpers for all fallback PS entries, or one distance-layout-specific helper for an explicit (VS, PS) pair.""" index_path = os.path.join(spirv_dir, "index.json") - if not os.path.isfile(index_path): + if pair is None and not os.path.isfile(index_path): return [] with open(index_path, encoding="utf-8") as f: index = json.load(f) + clip_count = cull_count = 0 + names = sorted(index) + suffix = "" + if pair is not None: + vertex, pixel = pair + producer = index.get(vertex, {}) + consumer = index.get(pixel, {}) + if producer.get("stage") != "vs" or consumer.get("stage") != "ps" or not consumer.get("bary_fallback_input"): + raise ValueError("--pair requires a translated VS and a barycentric-fallback PS from the index") + caps = set(producer.get("capabilities", [])) + unsupported = caps & {"ShaderLayer", "ShaderViewportIndex"} + if unsupported: + raise ValueError("paired helper cannot forward " + ", ".join(sorted(unsupported))) + def distance_count(kind): + if kind.title() + "Distance" not in caps: + return 0 + field = f"{kind}_distance_count" + count = producer.get(field) + if type(count) is not int or not 1 <= count <= 8: + raise ValueError(f"missing or invalid VS {field}; regenerate the translation index") + return count + + clip_count = distance_count("clip") + cull_count = distance_count("cull") + suffix = f".cull{cull_count}" if cull_count else f".clip{clip_count}" + names = [pixel] written = [] - for name, meta in sorted(index.items()): + for name in names: + meta = index[name] fb = meta.get("bary_fallback_input") if isinstance(meta, dict) else None if not fb: continue - path = os.path.join(spirv_dir, name + SUFFIX + ".spvasm") + path = os.path.join(spirv_dir, name + SUFFIX + suffix + ".spvasm") + shader = gs_spvasm(meta.get("inputs", []), fb["location"], clip_count, cull_count) with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(gs_spvasm(meta.get("inputs", []), fb["location"])) + f.write(shader) written.append(path) return written -def build_for_index(spirv_dir): +def build_for_index(spirv_dir, pair: tuple[str, str] | None = None): """write_for_index, then assemble each file to .bary_gs.spv and validate it (spirv-as / spirv-val on PATH, Vulkan 1.2 as for the translator). Returns the .spv paths; raises RuntimeError with the tool output on failure.""" built = [] - for asm in write_for_index(spirv_dir): + for asm in write_for_index(spirv_dir, pair): spv = asm[: -len(".spvasm")] + ".spv" for cmd in (["spirv-as", "--target-env", "vulkan1.2", asm, "-o", spv], ["spirv-val", "--target-env", "vulkan1.2", spv]): @@ -115,9 +170,15 @@ def build_for_index(spirv_dir): def main(argv): - if len(argv) != 2: - sys.exit(__doc__) - for path in build_for_index(argv[1]): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("spirv_dir") + parser.add_argument("--pair", nargs=2, metavar=("VS", "PS"), help="build for these index entries") + args = parser.parse_args(argv[1:]) + try: + paths = build_for_index(args.spirv_dir, tuple(args.pair) if args.pair else None) + except (OSError, ValueError, RuntimeError) as err: + parser.exit(1, f"{err}\n") + for path in paths: print(path) diff --git a/tools/bink_index.py b/tools/bink_index.py index 334ba0252..76e450659 100644 --- a/tools/bink_index.py +++ b/tools/bink_index.py @@ -282,6 +282,16 @@ def write_json(path, target, rows, summary, probe): fh, indent=1) +def same_output_path(first, second): + """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("target", help="an .rpf archive, a .bk2 file, or a directory") @@ -289,6 +299,8 @@ def main(argv=None): ap.add_argument("--format", choices=["csv", "json"], help="inferred from --out if omitted") ap.add_argument("--probe", action="store_true", help="run ffprobe on each stream") a = ap.parse_args(argv) + if a.out and same_output_path(a.target, a.out): + ap.error("--out must not overwrite the source") if not os.path.exists(a.target): print(f"bink_index: error: {a.target}: no such file or directory", file=sys.stderr) return 2 diff --git a/tools/bvh_index.py b/tools/bvh_index.py index 517346f4b..0a46e9ac2 100644 --- a/tools/bvh_index.py +++ b/tools/bvh_index.py @@ -405,6 +405,10 @@ def main(argv=None): a = ap.parse_args(argv) if a.out and a.csv and same_output_path(a.out, a.csv): ap.error("--out and --csv must use different paths") + if a.out and same_output_path(a.target, a.out): + ap.error("--out must not overwrite the source") + if a.csv and same_output_path(a.target, a.csv): + ap.error("--csv must not overwrite the source") if os.path.isdir(a.target) and (a.start is not None or a.limit is not None): ap.error("--start and --limit apply to a single archive, not a directory") below_normal() diff --git a/tools/crosslane_fuzz.py b/tools/crosslane_fuzz.py index 8e5e1c4e4..772ee1c1b 100644 --- a/tools/crosslane_fuzz.py +++ b/tools/crosslane_fuzz.py @@ -16,6 +16,10 @@ VKC_DUMP, and every word every thread stores is compared. docs/shader_validation # when tools/hw_oracle's tools are missing. --oracle translator,hw # does both. No llvm-mc, Vulkan or vk_compute_test for hw alone. +Exit code: 0 when every program that ran matches (or differs only in a program with a hypothesis op), 1 on a +mismatch or an untranslated program, 2 when the only failures are harness errors: vk_compute_test timed out or +gave no dump for a program. Such a program is listed with the others (and kept with --keep) and the run goes on. + Needs LLVM_MC (llvm-mc with AMDGPU, as for the shaders stage), the Vulkan SDK and a built vk_compute_test (cmake --build runtime/build --target vk_compute_test). No game files. @@ -48,6 +52,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) sys.path.insert(0, HERE) sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) +import mc_command # noqa: E402 M32 = 0xFFFFFFFF M64 = (1 << 64) - 1 @@ -726,7 +731,7 @@ def assemble(mc, prog, src, disasm, fssm): cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", f"-mattr={mattr}", "-show-encoding"] if "@" in src: src = resolve_branches(cmd, prog, src) - r = subprocess.run(cmd, input=src, capture_output=True, text=True) + r = mc_command.run(cmd, input=src, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{src}") code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) @@ -746,7 +751,7 @@ def resolve_branches(cmd, prog, src): lines = src.splitlines() insns = [i for i, ln in enumerate(lines) if ln.strip() and not ln.strip().startswith(";")] first = "\n".join(re.sub(r"@\d+$", "0", ln) for ln in lines) + "\n" - r = subprocess.run(cmd, input=first, capture_output=True, text=True) + r = mc_command.run(cmd, input=first, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{first}") sizes = [len(re.findall(r"0x[0-9a-f]{2}", m)) // 4 for m in re.findall(r"encoding: \[([^\]]*)\]", r.stdout)] @@ -784,14 +789,25 @@ def gpu_env(prog, emulate, dump, base=None): return env +class HarnessError(RuntimeError): + """vk_compute_test did not give a result for one program: it hung, crashed or wrote no dump.""" + + +GPU_TIMEOUT = 60 # seconds for one program; a translated program that never ends shows up as this + + def run_gpu(exe, spv, prog, work, emulate): dump = os.path.join(work, "dump.bin") if os.path.exists(dump): os.remove(dump) # never compare a stale dump env = gpu_env(prog, emulate, dump) - r = subprocess.run([exe, spv, "1", "dump"], capture_output=True, text=True, env=env, timeout=60) + try: + r = subprocess.run([exe, spv, "1", "dump"], capture_output=True, text=True, env=env, timeout=GPU_TIMEOUT) + except subprocess.TimeoutExpired: + raise HarnessError(f"vk_compute_test timed out after {GPU_TIMEOUT} s") from None if not os.path.exists(dump): - raise RuntimeError(f"vk_compute_test gave no dump for {prog.name}: {r.stdout}{r.stderr}") + detail = " ".join(f"{r.stdout}{r.stderr}".split()) + raise HarnessError(f"vk_compute_test gave no dump (exit {r.returncode}){': ' + detail if detail else ''}") with open(dump, "rb") as f: data = f.read() return list(struct.unpack(f"<{len(data) // 4}I", data)) @@ -843,7 +859,10 @@ def still_fails(prog, ops, mode, ctx): spv = os.path.join(spdir, prog.name + ".spv") if not os.path.exists(spv): return False - bad, hyp = compare(prog, run_gpu(exe, spv, prog, work, mode == "emulate"), ops) + try: + bad, hyp = compare(prog, run_gpu(exe, spv, prog, work, mode == "emulate"), ops) + except HarnessError: + return False # a reduction that hangs or crashes is not the mismatch being reduced return bool(bad) and not hyp @@ -973,7 +992,9 @@ def main(): print("summary:") for key, st in sorted(stats.items()): print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items())) - return 1 if any(st["mismatch"] or st["rejected"] for st in stats.values()) else 0 + if any(st["mismatch"] or st["rejected"] for st in stats.values()): + return 1 + return 2 if any(st.get("harness_errors") for st in stats.values()) else 0 def kept_source(prog, mode, ops, guard): @@ -1064,14 +1085,21 @@ def run_translator(args, mc, progs, waves, modes, stats, fails): continue key = f"wave{p.wave} {mode}" st = stats.setdefault(key, {"programs": 0, "match": 0, "mismatch": 0, "hyp_only": 0, - "rejected": 0}) + "rejected": 0, "harness_errors": 0}) st["programs"] += 1 spv = os.path.join(spdir, p.name + ".spv") if not os.path.exists(spv): st["rejected"] += 1 fails.append((p, mode, "not translated", None)) continue - bad, hyp = compare(p, run_gpu(args.exe, spv, p, work, mode == "emulate")) + try: + bad, hyp = compare(p, run_gpu(args.exe, spv, p, work, mode == "emulate")) + except HarnessError as e: + # One program that hangs or crashes the harness used to end the run with a traceback and + # lose every result before it. It is reported like the other failures and the run goes on. + st["harness_errors"] += 1 + fails.append((p, mode, f"harness error: {e}", None)) + continue if not bad: st["match"] += 1 elif hyp: diff --git a/tools/d3d12_xs_surface.py b/tools/d3d12_xs_surface.py index 7b64c3517..3ae4ec080 100644 --- a/tools/d3d12_xs_surface.py +++ b/tools/d3d12_xs_surface.py @@ -411,7 +411,8 @@ def parse_sdk_guids(um_dir, shared_dir): continue for path in glob.glob(os.path.join(d, "*.h")): try: - text = open(path, encoding="utf-8", errors="replace").read() + with open(path, encoding="utf-8", errors="replace") as f: + text = f.read() except OSError: continue for m in re.finditer(r"DEFINE_GUID\(\s*((?:IID|DXGI_DEBUG)_[A-Za-z0-9_]+)\s*,\s*([^)]*)\)", text): @@ -450,7 +451,8 @@ def check_sdk(): def parse_scarab_iid_table(path): - text = open(path, encoding="utf-8").read() + with open(path, encoding="utf-8") as f: + text = f.read() out = {} for name, body in re.findall(r"GUID\s+((?:IID|DXGI_DEBUG)_[A-Za-z0-9_]+)\s*=\s*\{([^;]*)\};", text): nums = tuple(int(x, 16) for x in re.findall(r"0x([0-9A-Fa-f]+)", body)) @@ -460,7 +462,8 @@ def parse_scarab_iid_table(path): def parse_scarab_iid_console(path): - text = open(path, encoding="utf-8").read() + with open(path, encoding="utf-8") as f: + text = f.read() out = {} for m in re.finditer(r"GUID\s+(IID_[A-Za-z0-9_]+).*?ordinal\s+(\d+)", text): out[m.group(1)] = int(m.group(2)) diff --git a/tools/f16_trans_sweep.py b/tools/f16_trans_sweep.py new file mode 100644 index 000000000..46c4ea96e --- /dev/null +++ b/tools/f16_trans_sweep.py @@ -0,0 +1,463 @@ +r"""Every f16 input through the f16 transcendentals on an AMD GPU (FUZZ-29). Standard library only. + +v_exp_f16, v_log_f16, v_rcp_f16, v_rsq_f16, v_sqrt_f16, v_sin_f16 and v_cos_f16 run natively through the hardware +oracle (tools/hw_oracle/) on all 65,536 f16 bit patterns, in wave32 and wave64 and under several float MODEs, and +each result is compared with the rule the translator implements (tools/rdna2spirv.py: widen to f32, the GLSL.std.450 +function, round to nearest even back to f16, f16 denormals kept): + + * v_exp_f16 = Exp2, v_log_f16 = Log2, v_rcp_f16 = 1 / x, v_rsq_f16 = InverseSqrt, v_sqrt_f16 = Sqrt. The + reference is the exact value, correctly rounded to f16 (decimal arithmetic, 60 digits), which is the best a + Vulkan driver can return for the translated SPIR-V. + * v_sin_f16 / v_cos_f16 take turns: the reference is sin / cos of 2 pi x, reduced in turns, correctly rounded. A + second table compares the hardware with Sin / Cos of the f32 product 6.2831855 * x, which is what the translator + computed before reducing in turns (#594). + * Where the rule's SPIR-V is undefined (Log2 / Sqrt / InverseSqrt of a negative, Log2 / InverseSqrt of 0, a + division by 0), the hardware result is tabulated instead of judged. + +Nothing is assumed about how close the hardware is: the tables count bit-exact results, 1 ulp, more than 1 ulp, +denormal operands read as zero, denormal results flushed, and NaN, and list the hardware word for each special +input. Each MODE is read back inside a kernel first, so a launcher that ignored the descriptor fails instead of +producing plausible tables. + +Usage: + python -I tools/f16_trans_sweep.py [--ops v_exp_f16,v_log_f16] [--modes keep16,flush16] [--json out.json] + python -I tools/f16_trans_sweep.py --self-test + +Exit 0 when the sweep ran (differences from the rule are findings, not failures), 1 when wave32 and wave64 +disagree, 2 on a harness error (a MODE that did not apply, a kernel without its words), 77 when the hardware +oracle is unavailable. On Linux the +oracle needs LEONIDA_HW_DRM_NODE (docs/shader_validation.md). Nothing here reads game files. +""" +import argparse +import functools +import json +import os +import struct +import sys +from decimal import ROUND_HALF_EVEN, Decimal, localcontext + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +if HERE not in sys.path: + sys.path.insert(0, HERE) + +OPS = ("v_exp_f16", "v_log_f16", "v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_sin_f16", "v_cos_f16") + +# f32 denormals flushed and IEEE off is the state docs/design.md infers for the game's shaders; the f16 denormal +# field is the open question, so both settings are run, then IEEE on, then f16 rounding toward zero. +MODES = { + "keep16": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3}, + "flush16": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 0}, + "ieee_keep16": {"ieee": 1, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3}, + "ieee_flush16": {"ieee": 1, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 0}, + "keep16_rtz": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3, "round16_64": 3}, +} + +THREADS = 1024 +PER_THREAD = 8 # inputs per thread, packed two to a dword +PER_KERNEL = THREADS * PER_THREAD # 8192 inputs, 4096 words: the launcher's limit +QNAN = 0x7E00 +TWO_PI_F32 = struct.unpack("= Decimal(2) ** (e + 1) and e < 15: + e += 1 + ulp = Decimal(2) ** (e - 10) + with localcontext() as c: + c.prec = 80 + n = int((a / ulp).to_integral_value(rounding="ROUND_DOWN" if rtz else ROUND_HALF_EVEN)) + val = n * ulp + if val > 65504: + return sign | (0x7BFF if rtz else 0x7C00) + return sign | struct.unpack("= 1: + f -= 1 + q = f * 4 + if q == q.to_integral_value(): + return [Decimal(0), Decimal(1), Decimal(0), Decimal(-1)][int(q)] + if f > Decimal("0.5"): + f -= 1 # (-0.5, 0.5] + return _sin(2 * _pi() * f) + + +def exact(op, h): + """The exact real result of the op on f16 h as a Decimal, or a str for a result that is not a finite real: + 'nan', '+inf', '-inf', '+0', '-0', or 'undef' where the translated SPIR-V is undefined.""" + if is_nan(h): + return "nan" + s = neg(h) + if is_inf(h): + return {"v_exp_f16": "+0" if s else "+inf", "v_log_f16": "undef" if s else "+inf", + "v_rcp_f16": "-0" if s else "+0", "v_rsq_f16": "undef" if s else "+0", + "v_sqrt_f16": "undef" if s else "+inf", "v_sin_f16": "undef", "v_cos_f16": "undef"}[op] + if is_zero(h): + return {"v_exp_f16": Decimal(1), "v_log_f16": "undef", "v_rcp_f16": "undef", "v_rsq_f16": "undef", + "v_sqrt_f16": "-0" if s else "+0", "v_sin_f16": "-0" if s else "+0", "v_cos_f16": Decimal(1)}[op] + x = to_dec(h) + if s and op in ("v_log_f16", "v_rsq_f16", "v_sqrt_f16"): + return "undef" + with localcontext() as c: + c.prec = 60 + if op == "v_exp_f16": + return Decimal(2) ** x if x != x.to_integral_value() else (Decimal(2) ** int(x) if abs(x) < 64 else + (Decimal(0) if x < 0 else Decimal(10) ** 30)) + if op == "v_log_f16": + return x.ln() / Decimal(2).ln() + if op == "v_rcp_f16": + return 1 / x + if op == "v_rsq_f16": + return 1 / x.sqrt() + if op == "v_sqrt_f16": + return x.sqrt() + return sin_turns(x, op == "v_cos_f16") + + +def product_turns(op, h): + """sin / cos of the f32 product 6.2831855 * x for finite h (the translator before #594 was fixed).""" + with localcontext() as c: + c.prec = 60 + t = Decimal(struct.unpack("> 16] + return out + + +def classify(op, hw, ref): + """Counts for one op and mode. A denormal operand whose word equals the hardware's own word for a zero of the + same sign counts as read as zero (the rule is undefined at 0 for log, rcp and rsq, so the rule can't say).""" + zero_hw = {False: hw[0x0000], True: hw[0x8000]} + c = {"inputs": 0, "exact": 0, "ulp1": 0, "ulp_more": 0, "max_ulp": 0, "nan_ok": 0, "zero_sign": 0, + "denorm_in_as_zero": 0, "denorm_out_flushed": 0, "undefined": 0, "nan_payload_kept": 0, "snan_kept": 0, + "snan_quieted": 0, "snan_other": 0, "other": 0} + worst = [] + for h in range(65536): + r, g = ref[h], hw[h] + c["inputs"] += 1 + if r is None: + c["undefined"] += 1 + continue + if is_nan(r): + if is_nan(g): + c["nan_ok"] += 1 + if is_nan(h) and (g & 0x1FF) == (h & 0x1FF): + c["nan_payload_kept"] += 1 + if is_nan(h) and not h & 0x200: + c["snan_kept" if g == h else "snan_quieted" if g == h | 0x200 else "snan_other"] += 1 + else: + c["other"] += 1 + worst.append((h, g, r)) + continue + if g == r: + c["exact"] += 1 + elif is_denorm(h) and g == zero_hw[neg(h)]: + c["denorm_in_as_zero"] += 1 + elif is_denorm(r) and is_zero(g) and (g & 0x8000) == (r & 0x8000): + c["denorm_out_flushed"] += 1 + elif is_zero(g) and is_zero(r): + c["zero_sign"] += 1 + elif is_nan(g): + c["other"] += 1 + worst.append((h, g, r)) + else: + d = ulps(g, r) + c["max_ulp"] = max(c["max_ulp"], d) + if d == 1: + c["ulp1"] += 1 + else: + c["ulp_more"] += 1 + worst.append((h, g, r)) + worst.sort(key=lambda t: -ulps(t[1], t[2]) if not (is_nan(t[1]) or is_nan(t[2])) else -1 << 20) + return c, worst[:8] + + +def product_reference(op, rtz=False): + return [None if is_nan(h) or is_inf(h) else to_bits(product_turns(op, h), rtz) for h in range(65536)] + + +def range_stats(hw, turns): + """sin / cos only: ulps against sin / cos of the f32 product, by |x| band.""" + bands = {"|x|<=1": (0, 1), "1<|x|<=256": (1, 256), "|x|>256": (256, 1e9)} + out = {} + for name, (lo, hi) in bands.items(): + n = ex = u1 = more = 0 + worst = 0 + for h in range(65536): + if is_nan(h) or is_inf(h): + continue + a = abs(float(to_dec(h))) + if not (lo < a <= hi or (lo == 0 and a == 0)): + continue + r = turns[h] + g = hw[h] + n += 1 + if is_nan(g): + more += 1 + continue + d = 0 if (g == r or (is_zero(g) and is_zero(r))) else ulps(g, r) + worst = max(worst, d) + ex += d == 0 + u1 += d == 1 + more += d > 1 + out[name] = {"inputs": n, "exact": ex, "ulp1": u1, "ulp_more": more, "max_ulp": worst} + return out + + +def fmt(h): + if h is None: + return "undef" + v = struct.unpack(" {v}" for h, v in report["ops"][op][modes[0]]["specials"].items())) + except RuntimeError as e: + print(f"harness error: {e}") + return 2 + finally: + oracle.close() + if a.json: + with open(a.json, "w", encoding="utf-8") as f: + json.dump(report, f, indent=1) + return rc + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py index 70c526714..c68ecc492 100644 --- a/tools/f32_fuzz.py +++ b/tools/f32_fuzz.py @@ -18,8 +18,17 @@ What a comparison can and cannot say: 0, ...) while the ISA defines the result is reported as its own class, "undefined in SPIR-V": the interpreter refuses to guess, and so does this tool. +With --oracle hw (or translator,hw) the same programs also run natively on an AMD GPU (tools/hw_oracle/, wave32) and +the hardware is judged against F32Model: match / mismatch where the model has an answer, "known deviation" where the +hardware equals an analysed alternative (omod turns -0 into +0), and informational tables where the model declines +(denormals under four MODE settings, NaN payloads, clamp of NaN, omod under IEEE/denormal modes). GFX10.1-only opcodes +(v_mad_f32, v_mac_f32, v_madak_f32, v_mad_legacy_f32) are skipped on gfx1030/GFX11 with a reason, never substituted. +v_min/max/min3/max3/med3_f32 are hardware-only ops. Exit 77 when the hardware tools are missing. See +docs/shader_validation.md ("32-bit float VALU on the GPU"). + Usage: python -I tools/f32_fuzz.py [--programs N] [--seed S] [--ops v_add_f32,...] [--show N] + python -I tools/f32_fuzz.py --oracle hw [--probes N] [--negative-control | --perturb NAME] [--no-info] python -I tools/f32_fuzz.py --list-ops python -I tools/f32_fuzz.py --self-test @@ -391,11 +400,44 @@ def apply_out_mods(r, mods): # ---- op table: name -> (sources, kind, model) ---- # kinds: "f" float source (takes neg/abs), "u" integer source, "k" literal float constant (fmaak/madak). -def _op(srcs, fn, mods=True, sel="any"): - return {"srcs": srcs, "fn": fn, "mods": mods, "sel": sel} +def _op(srcs, fn, mods=True, sel="any", hw_only=False): + return {"srcs": srcs, "fn": fn, "mods": mods, "sel": sel, "hw_only": hw_only} -OPS = { +def _fval(b): + return struct.unpack(" _fval(y) else y + + +def fmed3(x, y, z): + """With any NaN operand: min3(s0, s1, s2); otherwise the median, -0 < +0.""" + if is_nan(x) or is_nan(y) or is_nan(z): + return fmin(fmin(x, y), z) + return sorted((x, y, z), key=lambda b: (_fval(b), 0 if sign(b) else 1))[1] + + +ALL_OPS = { "v_add_f32": _op("ff", lambda x, y: add(x, y)), "v_sub_f32": _op("ff", lambda x, y: add(x, neg(y))), "v_subrev_f32": _op("ff", lambda x, y: add(y, neg(x))), @@ -432,9 +474,19 @@ OPS = { "v_cubetc_f32": _op("fff", lambda x, y, z: cube("v_cubetc_f32", x, y, z)), "v_cubema_f32": _op("fff", lambda x, y, z: cube("v_cubema_f32", x, y, z)), "v_cmp_class_f32": _op("fu", None, mods=False), # writes VCC, handled in step() + # Hardware-only: the RDNA2 NaN / signed-zero rules measured by #634 (docs/design.md), which the translator + # emits as NMin / NMax. They are in the table so --oracle hw can say whether gfx1150 follows the same rules; the + # translator comparison leaves them out (the SPIR-V interpreter has no defined result for every case). + "v_min_f32": _op("ff", fmin, hw_only=True), + "v_max_f32": _op("ff", fmax, hw_only=True), + "v_min3_f32": _op("fff", lambda x, y, z: fmin(fmin(x, y), z), hw_only=True), + "v_max3_f32": _op("fff", lambda x, y, z: fmax(fmax(x, y), z), hw_only=True), + "v_med3_f32": _op("fff", fmed3, hw_only=True), } VOP3_ONLY = {"v_mad_legacy_f32", "v_mad_f32", "v_fma_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", - "v_cubema_f32", "v_cvt_pk_u8_f32", "v_cvt_pkrtz_f16_f32"} + "v_cubema_f32", "v_cvt_pk_u8_f32", "v_cvt_pkrtz_f16_f32", "v_min3_f32", "v_max3_f32", "v_med3_f32"} +OPS = {k: v for k, v in ALL_OPS.items() if not v["hw_only"]} # what the translator comparison covers +HW_ONLY_OPS = tuple(k for k, v in ALL_OPS.items() if v["hw_only"]) # Ops the hardware gives an output modifier in their VOP3 form but whose float output is an integer or packed # value: no omod/clamp generated for them. NO_OUT_MODS = {"v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32", "v_cvt_pk_u8_f32", "v_cmp_class_f32", "v_fmaak_f32", @@ -485,7 +537,7 @@ def fmt_src(reg, m): def gen(rng, op): - spec = OPS[op] + spec = ALL_OPS[op] vals = [rand_float(rng) for _ in SEED_REGS] srcs, mods_src, text_srcs = [], [], [] e64 = op in VOP3_ONLY or (spec["mods"] and rng.random() < 0.5) @@ -535,45 +587,69 @@ def source_value(vals, s): return v -def model(op, vals, srcs, out_mods): - """Words of v8 (result) and v9 (VCC as 0/1).""" - spec = OPS[op] +def flush(b): + """A denormal read or written as a zero of its sign (what a flush-to-zero f32 unit does).""" + return b & 0x80000000 if is_denorm(b) else b + + +# model(..., denorm=): what happens to f32 denormals. +# "skip" raise Denormal (the default: this tool does not claim to know) +# "keep" exact IEEE behaviour, denormals read and written as they are +# "ftz" inputs read as signed zero and denormal results written as signed zero +# "ftz_in", "ftz_out" only one of the two +DENORM_MODES = ("skip", "keep", "ftz", "ftz_in", "ftz_out") + + +def model(op, vals, srcs, out_mods, denorm="skip", translator=True): + """Words of v8 (result) and v9 (VCC as 0/1). `translator`: refuse inputs the SPIR-V interpreter cannot carry + (they are fine on a GPU).""" + spec = ALL_OPS[op] ins = [] for s in srcs: ins.append(s[1] if s[0] == "k" else source_value(vals, s)) if "d" in spec["srcs"]: ins.append(vals[8]) - floats = [v for v, k in zip(ins, spec["srcs"].replace("d", "f")) if k in "fktde"] - if any(is_denorm(v) for v in floats): - raise Denormal("operand") + kinds = spec["srcs"].replace("d", "f") + fpos = [i for i, k in enumerate(kinds) if k in "fktde"] + if denorm == "skip": + if any(is_denorm(ins[i]) for i in fpos): + raise Denormal("operand") + elif denorm in ("ftz", "ftz_in"): + for i in fpos: + ins[i] = flush(ins[i]) + out_flush = denorm in ("ftz", "ftz_out") vcc = 0 if op == "v_cvt_f16_f32": r = (vals[8] & 0xFFFF0000) | round_rne_f16(ins[0]) - if is_denorm(ins[0]): - raise Denormal("operand") elif op == "v_cmp_class_f32": - if is_nan(ins[0]) and not ins[0] & 0x400000: + if translator and is_nan(ins[0]) and not ins[0] & 0x400000: # The translator reads the class from the bits after an OpBitcast to float and back, exact on a # GPU; the interpreter holds floats as Python floats, which quiets a signalling NaN on the way. raise NotModelled("signalling NaN through the interpreter's float bitcast") r, vcc = vals[8], cmp_class(ins[0], ins[1]) else: r = spec["fn"](*ins) - if spec["mods"] or op in ("v_fmaak_f32", "v_madak_f32"): - if is_denorm(r): + floaty = spec["mods"] or op in ("v_fmaak_f32", "v_madak_f32") + if floaty and is_denorm(r): + if denorm == "skip": raise Denormal("result") + if out_flush: + r = flush(r) if op in ("v_mad_f32", "v_mac_f32", "v_madak_f32", "v_mad_legacy_f32"): prod = legacy_mul(ins[0], ins[1]) if op == "v_mad_legacy_f32" else mul(ins[0], ins[1]) - if is_denorm(prod): + if is_denorm(prod) and denorm == "skip": raise Denormal("intermediate product") r = apply_out_mods(r, out_mods) if is_denorm(r): - raise Denormal("result") + if denorm == "skip": + raise Denormal("result") + if out_flush: + r = flush(r) return [r & M32, vcc] def line(op, vals, srcs, e64, out_mods): - spec = OPS[op] + spec = ALL_OPS[op] parts = [] for s in srcs: parts.append(f"0x{s[1]:x}" if s[0] == "k" else fmt_src(*s)) @@ -665,12 +741,20 @@ def fdesc(b): def run_suite(programs, seed, ops, show=2, quiet=False): - rng = random.Random(seed) + return translate_cases(gen_cases(programs, seed, ops), seed, show, quiet) + + +def translate_cases(cases, seed, show=2, quiet=False): + """Judge each case against the translated SPIR-V. Cases of hardware-only ops are not sent to the translator.""" counts = {"match": 0, "mismatch": 0, "undefined": 0, "skip": {}} by_op, undef_by_op, shown = {}, {}, {} - for i in range(programs): - op = rng.choice(ops) - vals, srcs, e64, out_mods = gen(rng, op) + programs = 0 + for case in cases: + if case.op in HW_ONLY_OPS or case.group != "random": + continue + programs += 1 + i = case.index + op, vals, srcs, e64, out_mods = case.args() status, detail = check(op, vals, srcs, e64, out_mods) if status == "skip": counts["skip"][detail] = counts["skip"].get(detail, 0) + 1 @@ -687,7 +771,7 @@ def run_suite(programs, seed, ops, show=2, quiet=False): want, got, text = detail src_line = [ln for ln in text.splitlines() if ln.startswith("\t" + op)][0].strip() print(f"--- program {i}: {src_line}") - used = sorted({s[0] for s in srcs if s[0] != "k"} | ({8} if "d" in OPS[op]["srcs"] or op in ( + used = sorted({s[0] for s in srcs if s[0] != "k"} | ({8} if "d" in ALL_OPS[op]["srcs"] or op in ( "v_cvt_f16_f32",) else set())) print(" inputs: " + " ".join(f"v{r}={fdesc(vals[r])}" for r in used)) print(" model v8/vcc: " + " ".join(fdesc(w) for w in want[:2])) @@ -704,6 +788,744 @@ def run_suite(programs, seed, ops, show=2, quiet=False): return counts, by_op, undef_by_op +def translator_verdict(case, want, got): + """For a hardware mismatch: what the translated SPIR-V does with the same program.""" + text, _ = listing(*case.args()) + status, tr = run_translated(text) + if status != "ok": + return f"{status}: {tr}" + mine = tr[:2] + if hw_same(mine, got, case.op): + return "matches the hardware (the model is the one that is off)" + if hw_same(mine, want, case.op): + return "matches the model, so it shares the model's answer (" + " ".join(fdesc(w) for w in mine) + ")" + return "matches neither: " + " ".join(fdesc(w) for w in mine) + + +# ---- the hardware oracle (--oracle hw) ---- +# The same programs, natively on the AMD GPU (tools/hw_oracle/), compared against F32Model. One wave32 thread per +# program; the kernel seeds v0..v8, runs the instruction, and stores v8 and VCC (as 0/1) through the output +# pointer. Where the model declines (denormals, NaN under clamp, ...) the program still runs, and what the +# hardware did is recorded, not judged. + +# Float MODE a kernel starts with. "flush" is the state inferred for the game's pixel shaders (docs/design.md: the +# corpus writes only MODE.FP_ROUND and carries omod on 102,365 float instructions, so IEEE is off; f32 denormals +# flushed). The other three change one thing each, to answer what the hardware does there. +HW_MODES = { + "flush": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0}, # MODE 0x1c0 + "keep": {"ieee": 0, "dx10_clamp": 1, "denorm32": 3}, # 0x1f0: f32 denormals kept + "no_dx10": {"ieee": 0, "dx10_clamp": 0, "denorm32": 0}, # 0x0c0: DX10_CLAMP off + "ieee": {"ieee": 1, "dx10_clamp": 1, "denorm32": 0}, # 0x3c0: the assembler default for a compute kernel +} +HW_PRIMARY = "flush" + + +# Ops whose omod does not depend on the f32 denormal mode: the transcendental unit and the cube ops flush or select +# whatever MODE says, and gfx1150 applies their omod with denormals kept (measured, 'omod' table). +OMOD_IGNORES_DENORM_MODE = ("v_rcp_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", "v_log_f32", "v_cubeid_f32", + "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32") + + +def omod_active(mode, op=None): + """Whether mul:2 / mul:4 / div:2 act in this mode (measured on gfx1150): never with MODE.IEEE = 1 (LLVM's + SIFoldOperands.cpp: "omod is ignored by hardware if IEEE bit is enabled" and, for f32, if output denormals are + enabled), and for the ALU ops only with f32 denormals flushed.""" + m = HW_MODES[mode] + return not m["ieee"] and (op in OMOD_IGNORES_DENORM_MODE or not m["denorm32"]) + + +def strip_omod(case): + return Case(case.op, case.vals, case.srcs, case.e64, [m for m in case.out_mods if m not in OMOD], case.group, + case.index) +HW_STORE = {"gfx11": "global_store_b64", "gfx10": "global_store_dwordx2"} +HW_ZERO_REG = 20 # v20 = 0, the store's address register (v0..v8 are the program's) + + +def mode_word(m): + """The MODE register value a kernel descriptor with these fields yields (FP_ROUND 3:0, FP_DENORM 7:4, DX10_CLAMP + bit 8, IEEE bit 9); unset fields are the assembler defaults: round to nearest, f16/f64 denormals kept.""" + return (m.get("round32", 0) | m.get("round16_64", 0) << 2 | m.get("denorm32", 0) << 4 | + m.get("denorm16_64", 3) << 6 | m.get("dx10_clamp", 1) << 8 | m.get("ieee", 1) << 9) + + +class Case: + """One generated program: the op, seed values, sources, encoding, output modifiers and where it came from.""" + __slots__ = ("op", "vals", "srcs", "e64", "out_mods", "group", "index") + + def __init__(self, op, vals, srcs, e64, out_mods, group="random", index=0): + self.op, self.vals, self.srcs, self.e64, self.out_mods = op, vals, srcs, e64, out_mods + self.group, self.index = group, index + + def args(self): + return self.op, self.vals, self.srcs, self.e64, self.out_mods + + +def hw_lines(case, arch="gfx1150", guard=True): + """The native kernel body: seeds, the instruction, VCC as 0/1 in v9, store v8 and v9. `guard` puts s_nop 7 + after the instruction (the transcendental unit and SGPR/VCC writes have wait-state rules the model lacks).""" + from hw_oracle import asm + op, vals, srcs, e64, out_mods = case.args() + out = [f"v_mov_b32 v{r}, 0x{vals[r]:x}" for r in SEED_REGS] + out.append("s_mov_b32 vcc_lo, 0") + # GFX11's assembler takes `clamp` before the omod (GFX10's takes either order): the same bits either way. + out.append(line(op, vals, srcs, e64, sorted(out_mods, key=lambda m: m != "clamp"))) + if guard: + out.append("s_nop 7") + out += ["v_cndmask_b32_e64 v9, 0, 1, vcc_lo", f"v_mov_b32 v{HW_ZERO_REG}, 0", + f"{HW_STORE[asm.family(arch)]} v{HW_ZERO_REG}, v[8:9], s[2:3]", "s_endpgm"] + return out + + +def hw_run(oracle, cases, mode=HW_PRIMARY, guard=True): + """[v8, vcc] per case, or the assembler's complaint as a str.""" + from hw_oracle import asm + kernels = [asm.Kernel(hw_lines(c, oracle.arch, guard), 32, 1, 2, raw=True, mode=HW_MODES[mode]) for c in cases] + return oracle.run(kernels, words=2) + + +def hw_probe_modes(oracle): + """Read MODE back inside a kernel for every mode and compare with what the directives should give, so a + runtime that ignored them fails here instead of producing plausible-looking data. Returns {mode: word}.""" + from hw_oracle import asm + body = ["s_getreg_b32 s4, hwreg(HW_REG_MODE, 0, 32)", "v_mov_b32 v1, s4", "v_mov_b32 v20, 0", + "global_store_b32 v20, v1, s[2:3]" if asm.family(oracle.arch) == "gfx11" else + "global_store_dword v20, v1, s[2:3]", "s_endpgm"] + names = list(HW_MODES) + got = oracle.run([asm.Kernel(body, 32, 1, 1, raw=True, mode=HW_MODES[n]) for n in names], words=1) + out = {} + for n, w in zip(names, got): + if isinstance(w, str) or w[0] != mode_word(HW_MODES[n]): + raise RuntimeError(f"MODE probe: mode {n} reads back {w!r}, expected 0x{mode_word(HW_MODES[n]):x}; the " + "kernel descriptor's float mode was not applied") + out[n] = w[0] + return out + + +F16_HALVES = {"v_cvt_f16_f32": (0,), "v_cvt_pkrtz_f16_f32": (0, 1)} # f16 results in v8: which halves + + +def is_nan16(h): + return h & 0x7C00 == 0x7C00 and h & 0x3FF != 0 + + +def hw_same(want, got, op=None): + """Model [v8, vcc] against the hardware's: NaN matches any NaN (an f16 NaN in a result half too), everything else + bit for bit.""" + if want[1] != got[1]: + return False + halves = F16_HALVES.get(op) + if halves is None: + return same(want[0], got[0]) + for h in (0, 1): + w, g = (want[0] >> 16 * h) & 0xFFFF, (got[0] >> 16 * h) & 0xFFFF + if not (w == g or (h in halves and is_nan16(w) and is_nan16(g))): + return False + return True + + +# ---- known deviations: hardware behaviour measured on gfx1150 that the ISA-text model does not have ---- +# Each maps (case, want) to the words the hardware gives instead, or None when it does not apply. A hardware result +# that equals the deviation's words is filed under "known deviation", not "match"; anything else stays a mismatch. + +def dev_omod_neg_zero(case, want, mode=None): + """On gfx1150 VOP3 omod (mul:2, mul:4, div:2) turns a -0 result into +0 (RDNA2 unmeasured). LLVM notes that omod + mishandles signed zeros (SIFoldOperands.cpp) and D30209 describes -0 being forced to +0 before the modifier. Only + where the omod was active: not with MODE.IEEE = 1, not for ALU ops with f32 denormals kept (omod_active).""" + if mode is None: + mode = HW_PRIMARY + if want[0] == 0x80000000 and any(m in OMOD for m in case.out_mods) and omod_active(mode, case.op): + return [0, want[1]] + return None + + +KNOWN_DEVIATIONS = {"omod_neg_zero": dev_omod_neg_zero} + + +def hw_verdict(case, got, model_fn=model): + """('match' | 'mismatch', want) when the model has an answer, ('skip', reason) when it declines.""" + try: + want = model_fn(case.op, case.vals, case.srcs, case.out_mods, translator=False) + except Denormal as e: + return "skip", f"denormal {e}" + except NotModelled as e: + return "skip", str(e) + if hw_same(want, got, case.op): + return "match", want + for name, fn in KNOWN_DEVIATIONS.items(): + alt = fn(case, want) + if alt is not None and hw_same(alt, got, case.op): + return "deviation:" + name, want + return "mismatch", want + + +# What the model gets wrong on purpose, to prove the comparison can fail (--perturb, --negative-control). Each +# entry: op -> replacement for ALL_OPS[op]["fn"]; none of them shares code with the real model's result path. +def _mul_rtz(x, y): + r = mul(x, y) + if is_nan(r) or is_inf(r) or is_zero(r): + return r + exact = to_frac(x) * to_frac(y) + return r - 1 if abs(to_frac(r)) > abs(exact) else r + + +PERTURBATIONS = { + "add_lsb": ("v_add_f32", lambda x, y: add(x, y) ^ 1), + "mul_rtz": ("v_mul_f32", _mul_rtz), + "fma_unfused": ("v_fma_f32", lambda x, y, z: add(mul(x, y), z)), + "legacy_is_ieee": ("v_mul_legacy_f32", mul), + "rndne_floor": ("v_rndne_f32", lambda x: rounding(x, "floor")), + "min_ieee_nan": ("v_min_f32", lambda x, y: QNAN if is_nan(x) or is_nan(y) else fmin(x, y)), +} + + +class perturbed: + """Context manager: swap one op's model function.""" + + def __init__(self, name): + self.op, self.fn = PERTURBATIONS[name] + self.old = None + + def __enter__(self): + self.old = ALL_OPS[self.op]["fn"] + ALL_OPS[self.op]["fn"] = self.fn + return self + + def __exit__(self, *exc): + ALL_OPS[self.op]["fn"] = self.old + + +# ---- informational classification: what the hardware did where the model declines ---- + +DENORM_LABELS = {"keep": "kept", "ftz": "flushed in+out", "ftz_in": "inputs flushed only", "ftz_out": "results flushed only"} + + +def denorm_label(case, got): + """Which denormal variants of the model the hardware's words equal: 'where' ('operand' / 'result') and the + matching variant names ('none' when no variant does).""" + op, vals, srcs, e64, out_mods = case.args() + spec = ALL_OPS[op] + ins = [s[1] if s[0] == "k" else source_value(vals, s) for s in srcs] + ([vals[8]] if "d" in spec["srcs"] else []) + kinds = spec["srcs"].replace("d", "f") + operand = any(is_denorm(ins[i]) for i, k in enumerate(kinds) if k in "fktde") + hit = [] + for d in ("keep", "ftz", "ftz_in", "ftz_out"): + try: + w = model(op, vals, srcs, out_mods, denorm=d, translator=False) + except (NotModelled, ValueError): + continue + alt = dev_omod_neg_zero(case, w) # a flushed zero is -0 too, and omod turns that into +0 + if hw_same(w, got, op) or (alt is not None and hw_same(alt, got, op)): + hit.append(d) + return ("operand" if operand else "result"), "|".join(hit) or "none" + + +def has_denorm_in(case): + op, vals, srcs, e64, out_mods = case.args() + spec = ALL_OPS[op] + ins = [s[1] if s[0] == "k" else source_value(vals, s) for s in srcs] + ([vals[8]] if "d" in spec["srcs"] else []) + kinds = spec["srcs"].replace("d", "f") + return any(is_denorm(ins[i]) for i, k in enumerate(kinds) if k in "fktde") + + +def float_inputs(case): + """[(position, value after neg/abs)] for the float sources, in instruction order.""" + spec = ALL_OPS[case.op] + ins = [s[1] if s[0] == "k" else source_value(case.vals, s) for s in case.srcs] + if "d" in spec["srcs"]: + ins.append(case.vals[8]) + kinds = spec["srcs"].replace("d", "f") + return [(i, v) for i, (v, k) in enumerate(zip(ins, kinds)) if k in "fktde"] + + +CUBE_OPS = ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32") +NAN_NOT_F32 = ("v_cmp_class_f32", "v_cvt_pk_u8_f32", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32") + + +def nan_facts(case, result): + """What the hardware did with NaNs, as short strings (one case can give several). Source n is src n of the + instruction after neg/abs. 'quieted' = the same payload with bit 22 set. Not for ops whose result is not an f32.""" + if case.op in NAN_NOT_F32: + return nan_facts_f16(case, result) if case.op.startswith("v_cvt_") and "f16" in case.op else [] + nans = [(i, v) for i, v in float_inputs(case) if is_nan(v)] + facts = [] + if not is_nan(result): + return ["NaN in, no NaN out"] if nans else [] + if not nans: + return [f"no NaN in, NaN out: 0x{result:08x}"] + first_i, first = nans[0] + if case.op in CUBE_OPS: + pass # the result is a selected source: no 'first' rule + elif result in (first, first | 0x400000, first ^ 0x80000000, (first ^ 0x80000000) | 0x400000): + facts.append("result = first NaN source" + (" (a signalling one)" if not first & 0x400000 else "")) + elif any(result in (v, v | 0x400000) for _, v in nans[1:]): + facts.append("result = a later NaN source") + elif result in (0xFFC00000, 0x7FC00000): + facts.append(f"result = default NaN 0x{result:08x}") + else: + facts.append(f"result = other 0x{result:08x}") + for i, v in nans: + if not v & 0x400000 and result == v: + facts.append("signalling NaN passes unchanged") + break + if not v & 0x400000 and result in (v | 0x400000, (v ^ 0x80000000) | 0x400000): + facts.append("signalling NaN quieted") + break + if any(result == (v ^ 0x80000000) | 0x400000 or result == v ^ 0x80000000 for _, v in nans): + facts.append("sign of the NaN flipped") + return facts + + +def nan_facts_f16(case, result): + """v_cvt_f16_f32 (low half) and v_cvt_pkrtz_f16_f32 (both halves): the f16 NaN against the f32 NaN it came from.""" + ins = [v for _, v in float_inputs(case)] + facts = [] + for h in F16_HALVES[case.op]: + x, half = ins[h], (result >> 16 * h) & 0xFFFF + if not is_nan(x): + continue + trunc = ((x >> 16) & 0x8000) | 0x7C00 | ((x >> 13) & 0x3FF) | 0x200 + facts.append("f16 NaN = f32 payload truncated to 10 bits, quiet bit set" if half == trunc else + "f16 NaN = canonical 0x7e00" if half & 0x7FFF == 0x7E00 else f"f16 NaN other 0x{half:04x}") + return facts + + +def omod_label(case, got): + """What an omod (mul:2, mul:4, div:2) did, judged where it changes the result and nothing is denormal.""" + if not any(m in OMOD for m in case.out_mods): + return None + try: + with_ = model(case.op, case.vals, case.srcs, case.out_mods, translator=False) + without = model(case.op, case.vals, case.srcs, [m for m in case.out_mods if m not in OMOD], + translator=False) + except (NotModelled, ValueError): + return None + if hw_same(with_, without, case.op) and with_[0] != 0x80000000: + return None + if hw_same(with_, got, case.op): + return "applied" + alt = dev_omod_neg_zero(case, with_) + if alt is not None and hw_same(alt, got, case.op): + return "applied, but a -0 result becomes +0" + if hw_same(without, got, case.op): + return "ignored" + return "other" + + +def clamp_label(case, got): + """What a clamp bit did to a NaN or -0 result (the model declines): measured against the unclamped result.""" + op, vals, srcs, e64, out_mods = case.args() + try: + raw = model(op, vals, srcs, [m for m in out_mods if m != "clamp"], denorm="keep", translator=False)[0] + except (NotModelled, ValueError): + return "n/a" + r = got[0] + if is_nan(raw): + if r == 0: + return "NaN -> +0" + if is_nan(r): + return "NaN passes through" + (" (quieted)" if raw & 0x400000 == 0 and r & 0x400000 else "") + return f"NaN -> 0x{r:08x}" + if raw == 0x80000000: + return {0: "-0 -> +0", 0x80000000: "-0 stays -0"}.get(r, f"-0 -> 0x{r:08x}") + return "other" + + +FAMILIES = [ + ("add / sub / mul", ("v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32")), + ("DX9 legacy mul / mad", ("v_mul_legacy_f32", "v_mad_legacy_f32")), + ("mad / mac / madak", ("v_mad_f32", "v_mac_f32", "v_madak_f32")), + ("fma / fmac / fmaak", ("v_fma_f32", "v_fmac_f32", "v_fmaak_f32")), + ("int -> f32 convert", ("v_cvt_f32_i32", "v_cvt_f32_u32", "v_cvt_f32_ubyte0", "v_cvt_f32_ubyte1", + "v_cvt_f32_ubyte2", "v_cvt_f32_ubyte3")), + ("f16 convert", ("v_cvt_f32_f16", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32")), + ("v_cvt_pk_u8_f32", ("v_cvt_pk_u8_f32",)), + ("floor / ceil / trunc / rndne", ("v_floor_f32", "v_ceil_f32", "v_trunc_f32", "v_rndne_f32")), + ("rcp / rsq / sqrt / exp / log (exact inputs)", ("v_rcp_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", + "v_log_f32")), + ("cube", ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")), + ("v_cmp_class_f32", ("v_cmp_class_f32",)), + ("min / max / med3 (hardware only)", HW_ONLY_OPS), +] + + +def family_of(op): + return next(name for name, ops in FAMILIES if op in ops) + + +# ---- generated probes: structured inputs the random generator never produces ---- + +DENORMS = [0x00000001, 0x00000002, 0x007FFFFF, 0x00400000, 0x00000100, 0x00123456, 0x80000001, 0x807FFFFF, + 0x80400000] +POW2_DENORMS = [0x00400000, 0x00200000, 0x00000001, 0x00080000] # 2^-127, 2^-128, 2^-149, 2^-130 +NANS = [0x7FC00000, 0xFFC00000, 0x7FC00001, 0xFFC12345, 0x7FA00000, 0xFFA00000, 0x7F800001, 0xFF800001, + 0x7FFFFFFF, 0xFFFFFFFF, 0x7FC0DEAD, 0x7FBFFFFF] +NEAR_MIN = [bits(2.0 ** -126), bits(1.5 * 2.0 ** -126), bits(2.0 ** -125), bits(-(2.0 ** -126)), + bits(-1.5 * 2.0 ** -126), bits(2.0 ** -126 * 1.0000001)] +SMALLS = [bits(0.5), bits(0.25), bits(-0.5), bits(1.0), bits(-1.0), bits(1.5), bits(0.75), bits(2.0 ** -10)] + + +def _float_slots(case): + """Registers (or the literal) holding float operands: [(srcs index, kind char)].""" + kinds = ALL_OPS[case.op]["srcs"].replace("d", "") + return [(i, k) for i, k in enumerate(kinds) if k in "fkte"] + + +def _set(case, i, v): + s = case.srcs[i] + if s[0] == "k": + case.srcs[i] = ("k", v) + else: + case.vals[s[0]] = v + + +def gen_probe(rng, op, kind): + """A Case of the given probe kind, or None when the op has no such probe.""" + vals, srcs, e64, out_mods = gen(rng, op) + case = Case(op, vals, list(srcs), e64, out_mods, group=kind) + slots = _float_slots(case) + spec = ALL_OPS[op] + if kind == "denorm_in": + pos = [(i, k) for i, k in slots if k in "ftk"] + if not pos: + return None + for i, k in rng.sample(pos, rng.randrange(1, min(2, len(pos)) + 1)): + _set(case, i, rng.choice(POW2_DENORMS if k == "t" else DENORMS)) + if "d" in spec["srcs"] and rng.random() < 0.3: + case.vals[8] = rng.choice(DENORMS) + return case + if kind == "denorm_out": + for _ in range(80): + for i, k in slots: + if k == "t": + _set(case, i, rng.choice(TRANS + [bits(2.0 ** 127)])) + elif k == "e": + _set(case, i, rng.choice(EXPS + [bits(-127.0), bits(-140.0), bits(-149.0), bits(-150.0)])) + elif k == "f": + _set(case, i, rng.choice(NEAR_MIN + SMALLS) if rng.random() < 0.7 else rand_float(rng)) + else: + _set(case, i, rng.choice(NEAR_MIN + SMALLS)) + if "d" in spec["srcs"]: + case.vals[8] = rng.choice(NEAR_MIN + [0] + SMALLS) + try: + if not is_denorm(model(op, case.vals, case.srcs, case.out_mods, denorm="keep", + translator=False)[0]): + continue + except (NotModelled, ValueError): + continue + return case + return None + if kind == "nan": + pos = [(i, k) for i, k in slots if k in "fkt"] + if not pos: + return None + picked = [p for p in pos if rng.random() < 0.6] or [rng.choice(pos)] + for i, k in picked: + _set(case, i, rng.choice(NANS)) + return case + if kind == "zero_inf": + # the DX9 rule: a zero times anything (inf, NaN included) is +0; small samples need these to see a plain multiply + if op not in ("v_mul_legacy_f32", "v_mad_legacy_f32"): + return None + _set(case, 0, rng.choice([0, 0x80000000])) + _set(case, 1, rng.choice([PINF, NINF, QNAN, 0x7F800001, bits(3.0)])) + if rng.random() < 0.5: + x, y = case.srcs[0], case.srcs[1] + case.srcs[0], case.srcs[1] = y, x + return case + if kind == "cancel": + # z = -round(x * y): a fused multiply-add keeps the rounding residue of the product, an unfused one gives 0 + if op not in ("v_fma_f32", "v_fmac_f32", "v_fmaak_f32"): + return None + x = (rng.getrandbits(1) << 31) | (rng.randrange(120, 135) << 23) | rng.getrandbits(23) + y = (rng.getrandbits(1) << 31) | (rng.randrange(120, 135) << 23) | rng.getrandbits(23) + z = neg(mul(x, y)) + _set(case, 0, x) + _set(case, 1, y) + if op == "v_fmac_f32": + case.vals[8] = z + else: + _set(case, 2, z) + return case + if kind == "invalid": + pool = [0, 0x80000000, PINF, NINF, bits(1.0), bits(-1.0), bits(2.0), bits(0.5), bits(-4.0)] + for _ in range(80): + for i, k in slots: + _set(case, i, rng.choice(pool)) + if "d" in spec["srcs"]: + case.vals[8] = rng.choice(pool) + try: + r = model(op, case.vals, case.srcs, case.out_mods, denorm="keep", translator=False)[0] + except (NotModelled, ValueError): + continue + if is_nan(r) and not any(is_nan(v) for _, v in float_inputs(case)): + return case + return None + if kind == "clamp": + if not spec["mods"] or op in NO_OUT_MODS: + return None + case.e64 = True + case.out_mods = ["clamp"] + ([rng.choice(tuple(OMOD))] if rng.random() < 0.3 else []) + for _ in range(80): + for i, k in slots: + if k in "ft": + _set(case, i, rng.choice([QNAN, 0xFFC00000, 0x80000000, 0, bits(-1.0), bits(2.0), PINF, NINF, + bits(0.5), bits(-0.0)])) + if "d" in spec["srcs"]: + case.vals[8] = rng.choice([0, 0x80000000, QNAN]) + try: + model(op, case.vals, case.srcs, case.out_mods, denorm="keep", translator=False) + except NotModelled: + return case + except ValueError: + continue + return None + raise ValueError(kind) + + +PROBE_KINDS = ("denorm_in", "denorm_out", "nan", "clamp", "invalid", "cancel", "zero_inf") + + +def gen_cases(programs, seed, ops): + """The seeded random programs, in the order run_suite draws them.""" + rng = random.Random(seed) + cases = [] + for i in range(programs): + op = rng.choice(ops) + vals, srcs, e64, out_mods = gen(rng, op) + cases.append(Case(op, vals, srcs, e64, out_mods, "random", i)) + return cases + + +def gen_probes(per_kind, seed, ops): + rng = random.Random(seed * 7919 + 13) + cases = [] + for op in ops: + for kind in PROBE_KINDS: + for j in range(per_kind): + c = gen_probe(rng, op, kind) + if c is not None: + c.index = j + cases.append(c) + return cases + + +class HwReport: + """Everything one hardware run learned.""" + + def __init__(self): + self.per_op = {} # op -> counters + self.mismatches = [] # (case, want, got) + self.denorm = {} # (mode, family, where, label) -> n + self.nan = {} # (mode, op, label) -> n + self.clamp = {} # (mode, label) -> n + self.skips = {} # reason -> n + self.minmax = {} # (mode, label) -> n + self.results = [] # (case, primary-mode words) for every case that ran + self.groups = {} # group -> counters + self.deviations = [] # (name, case, want, got): hardware = the known deviation's words + self.omod = {} # (mode, label) -> n + + def row(self, op): + return self.per_op.setdefault(op, {"programs": 0, "match": 0, "mismatch": 0, "dev": 0, "gfx11": 0, + "denorm": 0, "other": 0, "asm": 0}) + + def bump(self, table, key): + table[key] = table.get(key, 0) + 1 + + +def hw_suite(oracle, cases, guard=True, info_modes=("keep", "no_dx10", "ieee"), translator=False, model_fn=model): + """Run every case in the primary mode and compare with the model; then rerun the cases the model declines (and + those with NaNs) in the other modes for the informational tables. Returns an HwReport.""" + from hw_oracle import asm + rep = HwReport() + runnable = [] + for c in cases: + row = rep.row(c.op) + row["programs"] += 1 + why = asm.valu_skip_reason(c.op, oracle.arch) + if why: + row["gfx11"] += 1 + rep.bump(rep.skips, why) + continue + runnable.append(c) + primary = hw_run(oracle, runnable, HW_PRIMARY, guard) + info = [] + for c, got in zip(runnable, primary): + row = rep.row(c.op) + if isinstance(got, str): + row["asm"] += 1 + rep.bump(rep.skips, got) + continue + rep.results.append((c, got)) + verdict, want = hw_verdict(c, got, model_fn) + grp = rep.groups.setdefault(c.group, {"programs": 0, "match": 0, "mismatch": 0, "dev": 0, + "skip": 0}) + grp["programs"] += 1 + if verdict == "match": + row["match"] += 1 + grp["match"] += 1 + elif verdict.startswith("deviation:"): + row["dev"] += 1 + grp["dev"] += 1 + rep.deviations.append((verdict.split(":", 1)[1], c, want, got)) + elif verdict == "mismatch": + row["mismatch"] += 1 + grp["mismatch"] += 1 + rep.mismatches.append((c, want, got)) + else: + row["denorm" if want.startswith("denormal") else "other"] += 1 + grp["skip"] += 1 + rep.bump(rep.skips, want) + interesting = verdict == "skip" or has_denorm_in(c) or any(is_nan(v) for _, v in float_inputs(c)) \ + or is_nan(got[0]) or c.op in HW_ONLY_OPS or "clamp" in c.out_mods or any(m in OMOD for m in c.out_mods) + if interesting: + info.append(c) + classify(rep, HW_PRIMARY, c, got, verdict, want) + for mode in info_modes: + for c, got in zip(info, hw_run(oracle, info, mode, guard)): + if isinstance(got, str): + continue + ce = c if omod_active(mode, c.op) else strip_omod(c) # the model has no omod to judge there + verdict, want = hw_verdict(ce, got, model_fn) + classify(rep, mode, ce, got, verdict, want, orig=c) + return rep + + +def classify(rep, mode, c, got, verdict, want, orig=None): + fam = family_of(c.op) + if has_denorm_in(c) or (verdict == "skip" and want.startswith("denormal")): + rep.bump(rep.denorm, (mode, fam, *denorm_label(c, got))) + src = orig or c + if "clamp" not in src.out_mods and not any(m in OMOD for m in src.out_mods): + for fact in nan_facts(c, got[0]): + rep.bump(rep.nan, (mode, c.op, fact)) + if "clamp" in c.out_mods and verdict == "skip" and not want.startswith("denormal"): + rep.bump(rep.clamp, (mode, fam, clamp_label(c, got))) + if c.op in HW_ONLY_OPS and not any(m in OMOD for m in c.out_mods): + rep.bump(rep.minmax, (mode, "model matches" if verdict in ("match",) or verdict.startswith("deviation") else + "model differs" if verdict == "mismatch" else f"model declines ({want})")) + lab = omod_label(orig or c, got) + if lab: + rep.bump(rep.omod, (mode, lab)) + + +def negative_control(rep): + """Re-judge the hardware words already collected with each deliberately wrong model. Returns {name: (cases of + that op, mismatches the perturbation caused)}; every entry with cases must show mismatches.""" + out = {} + for name, (op, _) in PERTURBATIONS.items(): + n = bad = 0 + with perturbed(name): + for c, got in rep.results: + if c.op != op: + continue + n += 1 + if hw_verdict(c, got)[0] == "mismatch": + bad += 1 + out[name] = (n, bad) + return out + + +def hw_print(rep, show=2, translator_check=None, quiet=False): + """Tables and mismatch details. Returns the number of mismatches.""" + n_mis = len(rep.mismatches) + if quiet: + return n_mis + for g, r in sorted(rep.groups.items()): + print(f" group {g:10s} {r['programs']:6d} ran: {r['match']} match, {r['mismatch']} mismatch, " + f"{r['dev']} known deviation, {r['skip']} not judged") + fam_rows = {} + for op, r in rep.per_op.items(): + f = fam_rows.setdefault(family_of(op), dict.fromkeys(r, 0)) + for k, v in r.items(): + f[k] += v + head = (f"{'family':46s} {'programs':>8s} {'match':>7s} {'mismatch':>8s} {'known dev':>9s} {'GFX11 skip':>10s} " + f"{'denormal':>8s} {'other':>6s} {'asm rej':>7s}") + print(head) + tot = dict.fromkeys(("programs", "match", "mismatch", "dev", "gfx11", "denorm", "other", "asm"), 0) + for name, _ in FAMILIES: + r = fam_rows.get(name) + if not r: + continue + print(f"{name:46s} {r['programs']:8d} {r['match']:7d} {r['mismatch']:8d} {r['dev']:9d} {r['gfx11']:10d} " + f"{r['denorm']:8d} {r['other']:6d} {r['asm']:7d}") + for k in tot: + tot[k] += r[k] + print(f"{'total':46s} {tot['programs']:8d} {tot['match']:7d} {tot['mismatch']:8d} {tot['dev']:9d} " + f"{tot['gfx11']:10d} {tot['denorm']:8d} {tot['other']:6d} {tot['asm']:7d}") + if tot["asm"]: + print(f"WARNING: the assembler rejected {tot['asm']} program(s) the GFX11 table did not list; this is a harness " + "problem, not a skip, and the run fails (exit 2)") + for reason, n in sorted(rep.skips.items(), key=lambda t: -t[1]): + if reason.startswith("assembler rejected"): + print(f" {n} x {reason}") + by_dev = {} + for name, c, _, _ in rep.deviations: + by_dev.setdefault(name, {}).setdefault(c.op, 0) + by_dev[name][c.op] += 1 + for name, ops in sorted(by_dev.items()): + print(f" known deviation {name} x{sum(ops.values())}: " + ", ".join(f"{o} {n}" for o, n in sorted(ops.items()))) + for reason, n in sorted(rep.skips.items(), key=lambda t: -t[1]): + print(f" skip x{n}: {reason}") + shown = {} + for c, want, got in rep.mismatches: + if shown.get(c.op, 0) >= show: + continue + shown[c.op] = shown.get(c.op, 0) + 1 + print(f"--- {c.group} program {c.index}: {line(*c.args())}") + used = sorted({s[0] for s in c.srcs if s[0] != "k"} | ({8} if "d" in ALL_OPS[c.op]["srcs"] else set())) + print(" inputs: " + " ".join(f"v{r}={fdesc(c.vals[r])}" for r in used) + + "".join(f" literal={fdesc(s[1])}" for s in c.srcs if s[0] == "k")) + print(" model v8/vcc: " + " ".join(fdesc(w) for w in want)) + print(" hardware v8/vcc: " + " ".join(fdesc(w) for w in got)) + if translator_check: + print(" translator: " + translator_check(c, want, got)) + return n_mis + + +def info_print(rep): + """The informational tables: what the hardware does where the model does not judge.""" + print("\nhardware behaviour (informational; not counted as match or mismatch)") + modes = list(HW_MODES) + if rep.denorm: + print("\n f32 denormals (label = which model variants the hardware equals: kept = exact denormals, " + "flushed in+out = operands read as zero and denormal results written as zero)") + tab = {} + for (mode, fam, where, label), n in rep.denorm.items(): + tab.setdefault((fam, where, label), {})[mode] = n + for (fam, where, label), by in sorted(tab.items()): + print(f" {fam:44s} {where:8s} {label:28s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) + if rep.clamp: + print("\n clamp bit on a NaN or -0 result (DX10_CLAMP on = 'flush' and the other modes, off = 'no_dx10')") + tab = {} + for (mode, fam, label), n in rep.clamp.items(): + tab.setdefault(label, {})[mode] = tab.get(label, {}).get(mode, 0) + n + for label, by in sorted(tab.items()): + print(f" {label:34s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) + if rep.omod: + print("\n output modifier (mul:2, mul:4, div:2) where it changes the result; IEEE on = 'ieee'") + tab = {} + for (mode, label), n in rep.omod.items(): + tab.setdefault(label, {})[mode] = n + for label, by in sorted(tab.items()): + print(f" {label:40s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) + if rep.nan: + print("\n NaN handling (programs without clamp or omod; same program counts in every mode, so a column that " + "differs is a mode effect)") + tab = {} + for (mode, op, fact), n in rep.nan.items(): + tab.setdefault((op, fact), {})[mode] = n + for (op, fact), by in sorted(tab.items()): + print(f" {op:20s} {fact:62s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) + if rep.minmax: + print("\n min / max / med3 against the RDNA2 rules measured in #634") + tab = {} + for (mode, label), n in rep.minmax.items(): + tab.setdefault(label, {})[mode] = n + for label, by in sorted(tab.items()): + print(f" {label:60s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) + + def self_test(): """The model and the harness must both be able to pass and to fail.""" ok = True @@ -743,35 +1565,179 @@ def self_test(): if status != "mismatch": print("canary FAILED: a corrupted model result was not flagged") ok = False + ok &= hw_self_test() if ok: print("canaries: model checks ok, match ok, mismatch detected") return ok +def hw_self_test(): + """The hardware side without hardware: kernel text, the verdicts, the classifiers and the negative control.""" + ok = True + cases = gen_cases(300, 5, tuple(ALL_OPS)) + for op, _ in PERTURBATIONS.values(): + cases += gen_cases(150, 6, (op,)) + fake = [] + for c in cases: + try: + w = model(c.op, c.vals, c.srcs, c.out_mods, denorm="ftz", translator=False) + except (NotModelled, ValueError): + continue + fake.append((c, w)) + rep = HwReport() + rep.results = list(fake) + bad = [c.op for c, w in fake if hw_verdict(c, w)[0] == "mismatch"] + if bad or len(fake) < 100: + print(f"canary FAILED: the model disagrees with itself on {bad[:3]} ({len(fake)} cases)") + ok = False + nc = negative_control(rep) + silent = [n for n, (cases_n, bad_n) in nc.items() if cases_n >= 5 and not bad_n] + if silent: + print(f"canary FAILED: perturbations not detected: {silent}") + ok = False + for c, _ in fake[:40]: + text = "\n".join(hw_lines(c, "gfx1150")) + if "global_store_b64 v20, v[8:9], s[2:3]" not in text or not text.endswith("s_endpgm") or "@" in text: + print(f"canary FAILED: malformed kernel body for {c.op}") + ok = False + break + a = Case("v_add_f32", [bits(1.0), bits(2.0)] + [0] * 7, [(0, {}), (1, {})], False, []) + if hw_verdict(a, [bits(3.0), 0])[0] != "match" or hw_verdict(a, [bits(3.0) ^ 1, 0])[0] != "mismatch": + print("canary FAILED: hw_verdict") + ok = False + if hw_verdict(a, [QNAN, 0])[0] != "mismatch" or hw_verdict(a, [bits(3.0), 1])[0] != "mismatch": + print("canary FAILED: hw_verdict value/vcc") + ok = False + d = Case("v_add_f32", [0x00000001, bits(1.0)] + [0] * 7, [(0, {}), (1, {})], False, []) + if hw_verdict(d, [bits(1.0), 0])[0] != "skip": + print("canary FAILED: a denormal operand is not skipped") + ok = False + m = Case("v_mul_f32", [0x00000001, bits(1048576.0)] + [0] * 7, [(0, {}), (1, {})], False, []) + if denorm_label(m, [0, 0]) != ("operand", "ftz|ftz_in|ftz_out") or \ + denorm_label(m, [bits(2.0 ** -129), 0]) != ("operand", "keep"): + print("canary FAILED: denorm_label") + ok = False + n = Case("v_add_f32", [0x7FA00000, bits(1.0)] + [0] * 7, [(0, {}), (1, {})], False, []) + if nan_facts(n, 0x7FE00000) != ["result = first NaN source (a signalling one)", "signalling NaN quieted"] or \ + nan_facts(n, 0x7FA00000)[1:] != ["signalling NaN passes unchanged"]: + print("canary FAILED: nan_facts") + ok = False + return ok + + def main(argv=None): - ap = argparse.ArgumentParser(description="32-bit float VALU differential fuzzer for the translator.") + ap = argparse.ArgumentParser(description="32-bit float VALU differential fuzzer: the model against the translator " + "and/or the AMD GPU.") ap.add_argument("--programs", type=int, default=1000) ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--ops", default=None, help="comma-separated op names (default: all)") + ap.add_argument("--ops", default=None, help="comma-separated op names (default: all the oracle covers)") ap.add_argument("--show", type=int, default=2, help="failures to print per op") ap.add_argument("--list-ops", action="store_true") ap.add_argument("--self-test", action="store_true") + ap.add_argument("--oracle", default="translator", + help="comma-separated: translator (default; needs llvm-mc for gfx1013) or hw (natively on the AMD " + "GPU, wave32; tools/hw_oracle/), or translator,hw. Exit 77 when the hardware tools are missing") + ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") + ap.add_argument("--probes", type=int, default=12, + help="with hw: structured probes per op and kind (denormal operand, denormal result, NaN payloads, " + "clamp of NaN); they are judged where the model has an answer and recorded where it has not") + ap.add_argument("--no-hw-guard", action="store_true", help="no s_nop 7 after the instruction in the native kernels") + ap.add_argument("--no-info", action="store_true", help="leave out the informational hardware tables") + ap.add_argument("--perturb", choices=sorted(PERTURBATIONS), help="judge the hardware against a deliberately wrong " + "model (mismatches must appear)") + ap.add_argument("--negative-control", action="store_true", + help="after the hardware run, re-judge its words with every perturbed model; exit 1 if one is not caught") + ap.add_argument("--keep", help="write the kernel body of every hardware mismatch to this folder") a = ap.parse_args(argv) if a.programs < 1: ap.error("--programs must be at least 1") + if a.probes < 0: + ap.error("--probes cannot be negative") if a.list_ops: - print("\n".join(OPS)) + print("\n".join(ALL_OPS)) return 0 if a.self_test: return 0 if self_test() else 1 - ops = tuple(OPS) + backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) + if not backends or any(t not in ("translator", "hw") for t in backends): + ap.error("--oracle takes translator, hw or translator,hw") + if (a.perturb or a.negative_control or a.keep) and "hw" not in backends: + ap.error("--perturb, --negative-control and --keep need --oracle hw") + ops = tuple(ALL_OPS if "hw" in backends else OPS) if a.ops: ops = tuple(o.strip() for o in a.ops.split(",") if o.strip()) - unknown = [o for o in ops if o not in OPS] + unknown = [o for o in ops if o not in ALL_OPS] if unknown: ap.error(f"unknown ops: {', '.join(unknown)} (see --list-ops)") - counts, _, _ = run_suite(a.programs, a.seed, ops, show=a.show) - return 1 if counts["mismatch"] else 0 + if "hw" not in backends and any(o in HW_ONLY_OPS for o in ops): + ap.error(f"{', '.join(o for o in ops if o in HW_ONLY_OPS)} can only be run with --oracle hw") + oracle = None + if "hw" in backends: + from hw_oracle import runner + try: + oracle = runner.open_oracle(arch=a.hw_arch) + except runner.Unavailable as e: + print(f"hardware oracle unavailable: {e}") + return 77 + print(f"hardware oracle: {oracle.device}") + rc = 0 + harness = False + try: + cases = gen_cases(a.programs, a.seed, ops) + if "translator" in backends: + counts, _, _ = translate_cases(cases, a.seed, show=a.show) + rc |= bool(counts["mismatch"]) + if oracle: + words = hw_probe_modes(oracle) + print("MODE read back in the kernels: " + ", ".join(f"{n} 0x{w:x}" for n, w in words.items())) + if a.probes: + cases += gen_probes(a.probes, a.seed, ops) + model_ctx = perturbed(a.perturb) if a.perturb else None + if model_ctx: + model_ctx.__enter__() + try: + rep = hw_suite(oracle, cases, guard=not a.no_hw_guard, + info_modes=() if a.no_info else tuple(m for m in HW_MODES if m != HW_PRIMARY)) + finally: + if model_ctx: + model_ctx.__exit__(None, None, None) + print(f"\nhardware vs F32Model{' (perturbed: ' + a.perturb + ')' if a.perturb else ''}, " + f"{len(cases)} programs, mode {HW_PRIMARY} (MODE 0x{words[HW_PRIMARY]:x}), seed {a.seed}:") + tr = translator_verdict if "translator" in backends else None + n_mis = hw_print(rep, show=a.show, translator_check=tr) + if any(r["asm"] for r in rep.per_op.values()): + harness = True + if tr and rep.deviations: + tally = {} + for name, c, want, got in rep.deviations: + if c.op in HW_ONLY_OPS: + continue + verdict = tr(c, want, got).split(" (")[0] + tally[(name, verdict)] = tally.get((name, verdict), 0) + 1 + for (name, verdict), n in sorted(tally.items()): + print(f" translator on known deviation {name} x{n}: {verdict}") + if not a.no_info: + info_print(rep) + if a.keep and rep.mismatches: + os.makedirs(a.keep, exist_ok=True) + for k, (c, _, _) in enumerate(rep.mismatches): + with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8") as f: + f.write("\n".join(hw_lines(c, oracle.arch, not a.no_hw_guard)) + "\n") + if a.perturb: + print(f"perturbed model '{a.perturb}': {n_mis} mismatches" + ("" if n_mis else " -- NOT DETECTED")) + rc |= not n_mis + return 2 if harness else int(bool(rc)) + if a.negative_control: + print("\nnegative control (wrong models judged against the same hardware words):") + for name, (n, bad) in negative_control(rep).items(): + status = "caught" if bad else ("no programs of that op ran" if not n else "NOT CAUGHT") + print(f" {name:16s} {n:5d} programs of {PERTURBATIONS[name][0]}: {bad} mismatches ({status})") + rc |= bool(n and not bad) + rc |= bool(n_mis) + finally: + if oracle: + oracle.close() + return 2 if harness else int(bool(rc)) if __name__ == "__main__": diff --git a/tools/feature_scan.py b/tools/feature_scan.py index 79f475d01..ad0c88cdd 100644 --- a/tools/feature_scan.py +++ b/tools/feature_scan.py @@ -87,9 +87,12 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict: non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0 missing = 0 for e in index: + if not isinstance(e, dict): + missing += 1 + continue stage = e.get("stage") or "?" stages[stage] += 1 - path = os.path.join(dxbc_dir, e["file"]) + path = os.path.join(dxbc_dir, e.get("file") or "") try: with open(path, "rb") as f: p = parts(f.read()) @@ -242,7 +245,14 @@ def scan_disasm(disasm_dir: str, stage_of: dict) -> dict: def scan_spirv(spirv_index: str) -> dict: with open(spirv_index, encoding="utf-8") as f: idx = json.load(f) - entries = idx.values() if isinstance(idx, dict) else idx + # An object maps shader names to rows; a list is the other accepted shape. A scalar is a + # broken index, not something to iterate -- report no translated shaders for it. + if isinstance(idx, dict): + entries = idx.values() + elif isinstance(idx, list): + entries = idx + else: + entries = () total, code_base = Counter(), Counter() for m in entries: if not isinstance(m, dict): @@ -280,14 +290,21 @@ def main() -> int: return 2 result = {"shaders": len(index), "dxbc": scan_dxbc(dxbc_dir, index)} # Original names can be shared by variants, so indexed filenames take precedence. - stage_of = {e["name"]: e.get("stage") or "?" for e in index} - stage_of |= {os.path.splitext(e["file"])[0]: e.get("stage") or "?" for e in index} + # Non-object rows are already counted as unreadable by scan_dxbc; skip them here too. + rows = [e for e in index if isinstance(e, dict)] + stage_of = {e["name"]: e.get("stage") or "?" for e in rows if isinstance(e.get("name"), str)} + stage_of |= {os.path.splitext(e["file"])[0]: e.get("stage") or "?" + for e in rows if isinstance(e.get("file"), str)} disasm = os.path.join(dxbc_dir, "disasm") if os.path.isdir(disasm): result["disasm"] = scan_disasm(disasm, stage_of) spirv = os.path.join(a.shaders, "spirv", "index.json") if os.path.isfile(spirv): - result["spirv"] = scan_spirv(spirv) + try: + result["spirv"] = scan_spirv(spirv) + except (OSError, ValueError) as e: + print(f"ERROR: cannot read {spirv}: {getattr(e, 'strerror', None) or e}", file=sys.stderr) + return 2 d = result["dxbc"] print(f"{result['shaders']} shaders") diff --git a/tools/fssm_header.py b/tools/fssm_header.py index f862a8682..16ef0de10 100644 --- a/tools/fssm_header.py +++ b/tools/fssm_header.py @@ -9,7 +9,9 @@ table of 8-byte input records starts at offset 0x138. A record is present while byte 3 running index (same semantic id, next index) bytes 4-5 unused here byte 6 parameter slot - byte 7 flags; bit 4 (0x10) marks a 16-bit interpolant + byte 7 flags, the read method: bit 0 (0x01) read through v_interp_mov_f32 (flat), + bit 1 (0x02) through v_interp_p1/p2 or the f16 forms (interpolated), bit 3 + (0x08) a Float16-typed parameter (#1256), bit 4 (0x10) a 16-bit interpolant The record's position in the table is the `v_interp attr` number the code uses, not byte 6 - 1. @@ -31,6 +33,14 @@ opcodes in 12,067/12,101 (99.7%). `rdna2spirv.py` consumes it in the PS input p every table position declared as a fragment input, 16-bit-flagged positions rounded f32->f16->f32 on 32-bit reads). +Read method (SHADER-181). Bits 0-1 say how the compiled code reads each input, not the D3D +interpolation mode (that is PSV0's, decoded by `tools/ps_interp_modes.py`, #1256). On the same +corpus exactly one of the two is set: bit 1 in 51,191 records, bit 0 in 4,600, neither or both in +none. They agree with the code 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 `v_interp_p1/p2` or the +f16 forms (49,594), and no position is read both ways. The FSSM stores no SPI_PS_INPUT_ENA/ADDR +word. Bit 3 (0x08) is set in 11,619 records. + The post-`code_end` tail carries a binding table. After 16 bytes of `0xBF9F0000` filler and an 8-byte header, 20-byte records run until a `0xFFFFFFFF` sentinel; then `u32 0`, `u16 0`, `u16` name length and the name. `binding_table()` returns those records. On the local 26,503-blob @@ -54,6 +64,10 @@ TABLE_OFFSET = 0x138 RECORD_SIZE = 8 RECORD_KIND = 6 FLAG_FP16 = 0x10 +READ_MASK = 0x03 +READ_MOV = 0x01 # v_interp_mov_f32: flat +READ_INTERP = 0x02 # v_interp_p1/p2 and the f16 forms: interpolated with the v0/v1 pair +READ_NAMES = {READ_MOV: "mov", READ_INTERP: "interp"} DIRECTORY_OFFSET = 0x120 DIRECTORY_SIZE = 0x12C DIRECTORY_NEXT = 0x130 @@ -108,6 +122,20 @@ def interpolants(blob): return len(inputs), mask +def read_methods(blob): + """Return the read method (flags bits 0-1) of each pixel input, in table order. + + READ_MOV (1): read through v_interp_mov_f32, a flat input. READ_INTERP (2): read through + v_interp_p1/p2 or the f16 forms, interpolated with the v0/v1 pair. 0 and 3 (neither or both + bits) never occur in the corpus. + """ + return [entry["flags"] & READ_MASK for entry in pixel_inputs(blob)] + + +def read_name(method): + return READ_NAMES.get(method, f"read{method}") + + def directory_ok(blob): """True when offset + size == next offset in the section directory (0x120/0x12C/0x130).""" if len(blob) < DIRECTORY_NEXT + 4: @@ -237,6 +265,7 @@ def tally(rows, stages_known): # and must not show up as a 0:N bucket in the reported corpus counts. counts = Counter(row["entries"] for row in ps) scope = "all" + methods = Counter(read_name(entry["flags"] & READ_MASK) for row in ps for entry in row["inputs"]) return { "files": len(rows), "directory_ok": sum(row["directory_ok"] for row in rows), @@ -244,6 +273,7 @@ def tally(rows, stages_known): "entries": sum(row["entries"] for row in ps), "entry_counts": dict(sorted(counts.items())), "entry_counts_scope": scope, + "read_methods": dict(sorted(methods.items())), "stage_source": "index.json" if stages_known else "table-only", } @@ -304,6 +334,8 @@ def main(argv=None): total = summary print(f"{total['files']} files, directory_ok {total['directory_ok']}, " f"PS with table {total['ps_with_table']}, entries {total['entries']}") + if total["read_methods"]: + print("read methods: " + ", ".join(f"{k}:{v}" for k, v in total["read_methods"].items())) label = "PS entry counts" if total["entry_counts_scope"] == "ps" else "entry counts" print(label + ": " + ", ".join(f"{k}:{v}" for k, v in total["entry_counts"].items())) if total["stage_source"] == "table-only": diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py index 4e4f8ea4a..a9abddb9a 100644 --- a/tools/fssm_unpack.py +++ b/tools/fssm_unpack.py @@ -32,6 +32,10 @@ import sys import zlib from collections import Counter +# Defensive per-blob ceiling, not a maximum defined by the XBCH format. +# 64 MiB matches the repository's existing per-resource cap in tools/world_index.py. +MAX_FSSM_BYTES = 64 << 20 + def parts(d: bytes) -> dict: out = {} @@ -75,8 +79,22 @@ def unpack(dxbc: bytes, payload: str = "last"): raise ValueError(f"payload must be 'first' or 'last', not {payload!r}") if not blob or blob[:4] != b"XBCH": return None, ents + stored = struct.unpack_from(" MAX_FSSM_BYTES: + raise ValueError(f"XBCH declared size {unpacked} exceeds limit {MAX_FSSM_BYTES}") + compressed = blob[24:] + if stored != len(compressed): + raise ValueError(f"XBCH stored size {stored} does not match payload size {len(compressed)}") + decompressor = zlib.decompressobj() + # The extra byte detects a stream that expands past the declared size without inflating it all. + data = decompressor.decompress(compressed, unpacked + 1) + if len(data) > unpacked: + raise ValueError(f"decompressed XBCH exceeds declared size {unpacked}") + if not decompressor.eof: + raise ValueError("truncated XBCH zlib stream") + if decompressor.unused_data: + raise ValueError("trailing data after XBCH zlib stream") if len(data) != unpacked: raise ValueError(f"size mismatch {len(data)} != {unpacked}") if len(data) < 6: diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py index cfc4da0cf..c3b2a1d69 100644 --- a/tools/gamedata_xml.py +++ b/tools/gamedata_xml.py @@ -556,6 +556,14 @@ def main() -> int: except FileNotFoundError as exc: print(f"not found: {exc}", file=sys.stderr) return 2 + except RuntimeError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + except (OSError, ValueError, KeyError, TypeError) as exc: + # Same one-line contract as gamedata_index.py: a bad carve index is an error, not a traceback. + where = getattr(exc, "filename", None) or args.targets[0] + print(f"ERROR: cannot read {where}: {getattr(exc, 'strerror', None) or exc!r}", file=sys.stderr) + return 2 agg = aggregate(rows) summary = summarize(rows, agg, mode) diff --git a/tools/glb_writer.py b/tools/glb_writer.py index 74db82624..036efffea 100644 --- a/tools/glb_writer.py +++ b/tools/glb_writer.py @@ -606,6 +606,107 @@ def _append_buffer_view( return bv_idx +def pack_primitive(prim: dict) -> dict: + """Packed little-endian glTF buffers for one primitive from ``parse_obj``. + + Returns ``positions``/``normals``/``uvs``/``indices`` as bytes (``uvs`` is b"" without UVs), the index + component type, the vertex and index counts, the POSITION ``min``/``max`` and the primitive's ``material`` + key. The same packed primitive can be written into a GLB once and drawn by many instances. + """ + positions = list(prim["positions"]) + indices = list(prim["indices"]) + vert_count = len(positions) + normals_in = prim.get("normals") + if normals_in is None or len(normals_in) == 0: + normals = _compute_smooth_normals(positions, indices) + elif len(normals_in) == vert_count: + normals = [ + _normalize3(float(n[0]), float(n[1]), float(n[2])) + for n in normals_in + ] + else: + raise GlbError( + f"normals length ({len(normals_in)}) does not match positions length ({vert_count})" + ) + pos_bytes, pos_f32 = _pack_f32(positions, 3) + xs = pos_f32[0::3] + ys = pos_f32[1::3] + zs = pos_f32[2::3] + nrm_bytes, _ = _pack_f32(normals, 3) + uv_bytes = b"" + uvs_in = prim.get("uvs") + if uvs_in is not None and len(uvs_in) > 0: + if len(uvs_in) != vert_count: + raise GlbError( + f"uvs length ({len(uvs_in)}) does not match positions length ({vert_count})" + ) + clean_uvs = [ + ( + _clean_zero(float(uv[0])) if math.isfinite(float(uv[0])) else 0.0, + _clean_zero(float(uv[1])) if math.isfinite(float(uv[1])) else 0.0, + ) + for uv in uvs_in + ] + uv_bytes, _ = _pack_f32(clean_uvs, 2) + idx_bytes, idx_comp_type = _pack_indices(indices, vert_count) + material = prim.get("material", "") + return { + "positions": pos_bytes, + "normals": nrm_bytes, + "uvs": uv_bytes, + "indices": idx_bytes, + "index_type": idx_comp_type, + "vertices": vert_count, + "index_count": len(indices), + "min": [_clean_zero(min(xs)), _clean_zero(min(ys)), _clean_zero(min(zs))], + "max": [_clean_zero(max(xs)), _clean_zero(max(ys)), _clean_zero(max(zs))], + "material": material if isinstance(material, (str, int)) and not isinstance(material, bool) else "", + } + + +def _append_packed(bin_buf: bytearray, buffer_views: list[dict], accessors: list[dict], packed: dict) -> tuple[dict, int]: + """Write one packed primitive's views and accessors; returns (attributes, indices accessor).""" + vert_count = packed["vertices"] + pos_bv = _append_buffer_view(bin_buf, buffer_views, packed["positions"], target=TARGET_ARRAY_BUFFER) + pos_acc = len(accessors) + accessors.append({ + "bufferView": pos_bv, + "componentType": COMPONENT_FLOAT, + "count": vert_count, + "type": "VEC3", + "min": list(packed["min"]), + "max": list(packed["max"]), + }) + nrm_bv = _append_buffer_view(bin_buf, buffer_views, packed["normals"], target=TARGET_ARRAY_BUFFER) + nrm_acc = len(accessors) + accessors.append({ + "bufferView": nrm_bv, + "componentType": COMPONENT_FLOAT, + "count": vert_count, + "type": "VEC3", + }) + attributes: dict[str, int] = {"POSITION": pos_acc, "NORMAL": nrm_acc} + if packed["uvs"]: + uv_bv = _append_buffer_view(bin_buf, buffer_views, packed["uvs"], target=TARGET_ARRAY_BUFFER) + uv_acc = len(accessors) + accessors.append({ + "bufferView": uv_bv, + "componentType": COMPONENT_FLOAT, + "count": vert_count, + "type": "VEC2", + }) + attributes["TEXCOORD_0"] = uv_acc + idx_bv = _append_buffer_view(bin_buf, buffer_views, packed["indices"], target=TARGET_ELEMENT_ARRAY_BUFFER) + idx_acc = len(accessors) + accessors.append({ + "bufferView": idx_bv, + "componentType": packed["index_type"], + "count": packed["index_count"], + "type": "SCALAR", + }) + return attributes, idx_acc + + def _parse_base_color_factor(value: object, default: list[float]) -> list[float]: if value is None: return list(default) @@ -637,6 +738,117 @@ def _parse_alpha_mode(mode: object, cutoff: object, factor_alpha: float) -> dict return out +class _MaterialTable: + """glTF materials, images and textures for one GLB, shared by every primitive that uses them.""" + + def __init__(self, materials, bin_buf: bytearray, buffer_views: list[dict]) -> None: + self.materials = materials + self.bin_buf = bin_buf + self.buffer_views = buffer_views + self.gltf_materials: list[dict] = [] + self.images: list[dict] = [] + self.textures: list[dict] = [] + self.mat_index_by_key: dict[tuple[str | int, bool], int] = {} + self.default_mat_index: int | None = None + self.tex_index_by_sha256: dict[bytes, int] = {} + + def get_texture_index(self, png_bytes: bytes) -> int: + digest = hashlib.sha256(png_bytes).digest() + existing = self.tex_index_by_sha256.get(digest) + if existing is not None: + return existing + bv_idx = _append_buffer_view(self.bin_buf, self.buffer_views, png_bytes, target=None) + img_idx = len(self.images) + self.images.append({ + "bufferView": bv_idx, + "mimeType": "image/png", + }) + tex_idx = len(self.textures) + self.textures.append({ + "sampler": 0, + "source": img_idx, + }) + self.tex_index_by_sha256[digest] = tex_idx + return tex_idx + + def _lookup_material_spec(self, prim: dict) -> tuple[str | int, dict] | None: + materials = self.materials + if materials is None: + return None + mat_key = prim.get("material", "") + if mat_key is None: + mat_key = "" + if isinstance(materials, dict): + if mat_key in materials: + return mat_key, materials[mat_key] or {} + if "material_index" in prim: + midx = prim["material_index"] + if isinstance(midx, int) and not isinstance(midx, bool) and midx in materials: + return midx, materials[midx] or {} + elif isinstance(materials, (list, tuple)): + midx = prim.get("material_index") + if isinstance(midx, int) and not isinstance(midx, bool) and 0 <= midx < len(materials): + return midx, materials[midx] or {} + return None + + def get_material_index(self, prim: dict, *, has_uv: bool) -> int: + found = self._lookup_material_spec(prim) + if found is not None: + resolved_key, spec = found + raw_png = spec.get("png_bytes") + has_png = has_uv and isinstance(raw_png, (bytes, bytearray, memoryview)) and len(raw_png) > 0 + cache_key = (resolved_key, has_png) + existing = self.mat_index_by_key.get(cache_key) + if existing is not None: + return existing + default_color = DEFAULT_TEXTURED_COLOR if has_png else DEFAULT_CLAY_COLOR + base_color = _parse_base_color_factor(spec.get("base_color_factor"), default_color) + alpha_fields = _parse_alpha_mode(spec.get("alpha_mode"), spec.get("alpha_cutoff"), base_color[3]) + + pbr: dict = { + "baseColorFactor": base_color, + "metallicFactor": DEFAULT_METALLIC, + "roughnessFactor": DEFAULT_ROUGHNESS, + } + if has_png: + tex_idx = self.get_texture_index(bytes(raw_png)) + pbr["baseColorTexture"] = {"index": tex_idx} + + mat_obj: dict = {"pbrMetallicRoughness": pbr} + mat_name = spec.get("name") + if mat_name is None and isinstance(resolved_key, str): + mat_name = resolved_key + if isinstance(mat_name, str) and mat_name: + mat_obj["name"] = mat_name + if spec.get("double_sided"): + mat_obj["doubleSided"] = True + mat_obj.update(alpha_fields) + + mat_idx = len(self.gltf_materials) + self.gltf_materials.append(mat_obj) + self.mat_index_by_key[cache_key] = mat_idx + return mat_idx + + if self.default_mat_index is None: + self.default_mat_index = len(self.gltf_materials) + self.gltf_materials.append({ + "name": "default_clay", + "pbrMetallicRoughness": { + "baseColorFactor": list(DEFAULT_CLAY_COLOR), + "metallicFactor": DEFAULT_METALLIC, + "roughnessFactor": DEFAULT_ROUGHNESS, + }, + }) + return self.default_mat_index + + def apply(self, gltf: dict) -> None: + gltf["materials"] = self.gltf_materials + if self.textures: + gltf["samplers"] = [dict(DEFAULT_SAMPLER)] + gltf["images"] = self.images + gltf["textures"] = self.textures + + def _build_glb_with_stats( primitives: list[dict], materials: dict[str, dict] | None = None, @@ -656,197 +868,18 @@ def _build_glb_with_stats( bin_buf = bytearray() buffer_views: list[dict] = [] accessors: list[dict] = [] - gltf_materials: list[dict] = [] - images: list[dict] = [] - textures: list[dict] = [] - - mat_index_by_key: dict[tuple[str | int, bool], int] = {} - default_mat_index: int | None = None - tex_index_by_sha256: dict[bytes, int] = {} - - def get_texture_index(png_bytes: bytes) -> int: - digest = hashlib.sha256(png_bytes).digest() - existing = tex_index_by_sha256.get(digest) - if existing is not None: - return existing - bv_idx = _append_buffer_view(bin_buf, buffer_views, png_bytes, target=None) - img_idx = len(images) - images.append({ - "bufferView": bv_idx, - "mimeType": "image/png", - }) - tex_idx = len(textures) - textures.append({ - "sampler": 0, - "source": img_idx, - }) - tex_index_by_sha256[digest] = tex_idx - return tex_idx - - def _lookup_material_spec(prim: dict) -> tuple[str | int, dict] | None: - if materials is None: - return None - mat_key = prim.get("material", "") - if mat_key is None: - mat_key = "" - if isinstance(materials, dict): - if mat_key in materials: - return mat_key, materials[mat_key] or {} - if "material_index" in prim: - midx = prim["material_index"] - if isinstance(midx, int) and not isinstance(midx, bool) and midx in materials: - return midx, materials[midx] or {} - elif isinstance(materials, (list, tuple)): - midx = prim.get("material_index") - if isinstance(midx, int) and not isinstance(midx, bool) and 0 <= midx < len(materials): - return midx, materials[midx] or {} - return None - - def get_material_index(prim: dict, *, has_uv: bool) -> int: - nonlocal default_mat_index - found = _lookup_material_spec(prim) - if found is not None: - resolved_key, spec = found - raw_png = spec.get("png_bytes") - has_png = has_uv and isinstance(raw_png, (bytes, bytearray, memoryview)) and len(raw_png) > 0 - cache_key = (resolved_key, has_png) - existing = mat_index_by_key.get(cache_key) - if existing is not None: - return existing - default_color = DEFAULT_TEXTURED_COLOR if has_png else DEFAULT_CLAY_COLOR - base_color = _parse_base_color_factor(spec.get("base_color_factor"), default_color) - alpha_fields = _parse_alpha_mode(spec.get("alpha_mode"), spec.get("alpha_cutoff"), base_color[3]) - - pbr: dict = { - "baseColorFactor": base_color, - "metallicFactor": DEFAULT_METALLIC, - "roughnessFactor": DEFAULT_ROUGHNESS, - } - if has_png: - tex_idx = get_texture_index(bytes(raw_png)) - pbr["baseColorTexture"] = {"index": tex_idx} - - mat_obj: dict = {"pbrMetallicRoughness": pbr} - mat_name = spec.get("name") - if mat_name is None and isinstance(resolved_key, str): - mat_name = resolved_key - if isinstance(mat_name, str) and mat_name: - mat_obj["name"] = mat_name - if spec.get("double_sided"): - mat_obj["doubleSided"] = True - mat_obj.update(alpha_fields) - - mat_idx = len(gltf_materials) - gltf_materials.append(mat_obj) - mat_index_by_key[cache_key] = mat_idx - return mat_idx - - if default_mat_index is None: - default_mat_index = len(gltf_materials) - gltf_materials.append({ - "name": "default_clay", - "pbrMetallicRoughness": { - "baseColorFactor": list(DEFAULT_CLAY_COLOR), - "metallicFactor": DEFAULT_METALLIC, - "roughnessFactor": DEFAULT_ROUGHNESS, - }, - }) - return default_mat_index + table = _MaterialTable(materials, bin_buf, buffer_views) + get_material_index = table.get_material_index gltf_primitives: list[dict] = [] total_verts = 0 total_tris = 0 for prim in non_empty: - positions = list(prim["positions"]) - indices = list(prim["indices"]) - vert_count = len(positions) - total_verts += vert_count - total_tris += len(indices) // 3 - - normals_in = prim.get("normals") - if normals_in is None or len(normals_in) == 0: - normals = _compute_smooth_normals(positions, indices) - elif len(normals_in) == vert_count: - normals = [ - _normalize3(float(n[0]), float(n[1]), float(n[2])) - for n in normals_in - ] - else: - raise GlbError( - f"normals length ({len(normals_in)}) does not match positions length ({vert_count})" - ) - - # POSITION - pos_bytes, pos_f32 = _pack_f32(positions, 3) - xs = pos_f32[0::3] - ys = pos_f32[1::3] - zs = pos_f32[2::3] - pos_min = [_clean_zero(min(xs)), _clean_zero(min(ys)), _clean_zero(min(zs))] - pos_max = [_clean_zero(max(xs)), _clean_zero(max(ys)), _clean_zero(max(zs))] - pos_bv = _append_buffer_view(bin_buf, buffer_views, pos_bytes, target=TARGET_ARRAY_BUFFER) - pos_acc = len(accessors) - accessors.append({ - "bufferView": pos_bv, - "componentType": COMPONENT_FLOAT, - "count": vert_count, - "type": "VEC3", - "min": pos_min, - "max": pos_max, - }) - - # NORMAL - nrm_bytes, _ = _pack_f32(normals, 3) - nrm_bv = _append_buffer_view(bin_buf, buffer_views, nrm_bytes, target=TARGET_ARRAY_BUFFER) - nrm_acc = len(accessors) - accessors.append({ - "bufferView": nrm_bv, - "componentType": COMPONENT_FLOAT, - "count": vert_count, - "type": "VEC3", - }) - - attributes: dict[str, int] = { - "POSITION": pos_acc, - "NORMAL": nrm_acc, - } - - # TEXCOORD_0 (only when non-empty uvs match vertex count) - uvs_in = prim.get("uvs") - if uvs_in is not None and len(uvs_in) > 0: - if len(uvs_in) != vert_count: - raise GlbError( - f"uvs length ({len(uvs_in)}) does not match positions length ({vert_count})" - ) - clean_uvs = [ - ( - _clean_zero(float(uv[0])) if math.isfinite(float(uv[0])) else 0.0, - _clean_zero(float(uv[1])) if math.isfinite(float(uv[1])) else 0.0, - ) - for uv in uvs_in - ] - uv_bytes, _ = _pack_f32(clean_uvs, 2) - uv_bv = _append_buffer_view(bin_buf, buffer_views, uv_bytes, target=TARGET_ARRAY_BUFFER) - uv_acc = len(accessors) - accessors.append({ - "bufferView": uv_bv, - "componentType": COMPONENT_FLOAT, - "count": vert_count, - "type": "VEC2", - }) - attributes["TEXCOORD_0"] = uv_acc - - # INDICES - idx_bytes, idx_comp_type = _pack_indices(indices, vert_count) - idx_bv = _append_buffer_view(bin_buf, buffer_views, idx_bytes, target=TARGET_ELEMENT_ARRAY_BUFFER) - idx_acc = len(accessors) - accessors.append({ - "bufferView": idx_bv, - "componentType": idx_comp_type, - "count": len(indices), - "type": "SCALAR", - }) - + packed = pack_primitive(prim) + total_verts += packed["vertices"] + total_tris += packed["index_count"] // 3 + attributes, idx_acc = _append_packed(bin_buf, buffer_views, accessors, packed) mat_idx = get_material_index(prim, has_uv="TEXCOORD_0" in attributes) gltf_primitives.append({ @@ -876,16 +909,16 @@ def _build_glb_with_stats( "scenes": [{"nodes": [0]}], "nodes": [{"mesh": 0}], "meshes": [mesh_obj], - "materials": gltf_materials, + "materials": table.gltf_materials, "accessors": accessors, "bufferViews": buffer_views, "buffers": [{"byteLength": len(bin_buf)}], } - if textures: + if table.textures: gltf["samplers"] = [dict(DEFAULT_SAMPLER)] - gltf["images"] = images - gltf["textures"] = textures + gltf["images"] = table.images + gltf["textures"] = table.textures json_bytes = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") json_pad = (-len(json_bytes)) % 4 @@ -905,7 +938,7 @@ def _build_glb_with_stats( "triangles": total_tris, "vertices": total_verts, "primitives": len(non_empty), - "textures": len(textures), + "textures": len(table.textures), "bounds": bounds, } return glb_bytes, stats @@ -971,6 +1004,12 @@ def write_glb( ``materials`` takes the spec keys documented on ``build_glb``. """ glb_bytes, stats = _build_glb_with_stats(primitives, materials) + _write_bytes_atomic(path, glb_bytes) + return stats + + +def _write_bytes_atomic(path: str, glb_bytes: bytes) -> None: + """Publish ``glb_bytes`` at ``path`` through a private staging file in the same directory.""" out_path = os.fspath(path) parent = os.path.dirname(os.path.abspath(out_path)) if parent: @@ -993,6 +1032,180 @@ def write_glb( except OSError: pass raise + + +INSTANCING_EXTENSION = "EXT_mesh_gpu_instancing" +INSTANCING_MODES = ("gpu", "nodes") + + +def _quat_matrix(q) -> list[list[float]]: + x, y, z, w = (float(v) for v in q) + return [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + + +def instance_bounds(box_min, box_max, translation, rotation, scale) -> list[float]: + """Exact axis-aligned bounds of the box [box_min, box_max] after scale, rotation (unit x, y, z, w) and + translation, the order glTF applies a node's TRS in.""" + r = _quat_matrix(rotation) + m = [[r[i][j] * float(scale[j]) for j in range(3)] for i in range(3)] + c = [(float(box_min[j]) + float(box_max[j])) * 0.5 for j in range(3)] + h = [(float(box_max[j]) - float(box_min[j])) * 0.5 for j in range(3)] + out_min, out_max = [], [] + for i in range(3): + ci = m[i][0] * c[0] + m[i][1] * c[1] + m[i][2] * c[2] + float(translation[i]) + hi = abs(m[i][0]) * h[0] + abs(m[i][1]) * h[1] + abs(m[i][2]) * h[2] + out_min.append(ci - hi) + out_max.append(ci + hi) + return out_min + out_max + + +def build_instanced_glb( + meshes: list[dict], + materials: dict[str, dict] | None = None, + *, + mode: str = "gpu", + generator: str = "Leonida glb_writer", +) -> tuple[bytes, dict]: + """One GLB in which each mesh is stored once and drawn by many instances. + + ``meshes`` is a list of ``{"name": str or None, "primitives": [pack_primitive(...)], "instances": + [(translation xyz, rotation xyzw, scale xyz), ...]}``. Every instance transform must have a positive + determinant (no mirroring scale); give mirrored instances their own mirrored mesh instead, so the winding is + right in every loader. ``mode`` "gpu" writes one node per mesh with ``EXT_mesh_gpu_instancing`` (listed in + extensionsUsed and extensionsRequired); "nodes" writes one plain glTF node per instance, which every loader + reads but which costs a draw call per instance. ``materials`` takes the spec keys documented on + ``build_glb``, looked up by each packed primitive's ``material``. Returns (GLB bytes, stats) where stats + counts rendered triangles (each mesh's triangles times its instances) and the bounds of every instance. + """ + if mode not in INSTANCING_MODES: + raise GlbError(f"instancing mode must be one of {INSTANCING_MODES}, got {mode!r}") + bin_buf = bytearray() + buffer_views: list[dict] = [] + accessors: list[dict] = [] + table = _MaterialTable(materials, bin_buf, buffer_views) + gltf_meshes: list[dict] = [] + nodes: list[dict] = [] + stored_verts = stored_tris = drawn_tris = primitives = instances_total = 0 + lo = [math.inf] * 3 + hi = [-math.inf] * 3 + for mesh in meshes: + prims = [p for p in mesh.get("primitives") or () if p.get("vertices") and p.get("index_count")] + insts = list(mesh.get("instances") or ()) + if not prims or not insts: + continue + gltf_prims = [] + box_min = [math.inf] * 3 + box_max = [-math.inf] * 3 + mesh_tris = 0 + for packed in prims: + attributes, idx_acc = _append_packed(bin_buf, buffer_views, accessors, packed) + gltf_prims.append({ + "attributes": attributes, + "indices": idx_acc, + "material": table.get_material_index(packed, has_uv="TEXCOORD_0" in attributes), + "mode": MODE_TRIANGLES, + }) + stored_verts += packed["vertices"] + mesh_tris += packed["index_count"] // 3 + for k in range(3): + box_min[k] = min(box_min[k], packed["min"][k]) + box_max[k] = max(box_max[k], packed["max"][k]) + primitives += len(prims) + stored_tris += mesh_tris + mesh_obj: dict = {"primitives": gltf_prims} + if isinstance(mesh.get("name"), str) and mesh["name"]: + mesh_obj["name"] = mesh["name"] + mesh_idx = len(gltf_meshes) + gltf_meshes.append(mesh_obj) + ts, rs, ss = [], [], [] + for t, q, sc in insts: + t = [float(v) for v in t] + sc = [float(v) for v in sc] + q = [float(v) for v in q] + n = math.sqrt(sum(v * v for v in q)) + if not n or not math.isfinite(n): + raise GlbError("instance rotation must be a finite non-zero quaternion") + q = [v / n for v in q] + if sc[0] * sc[1] * sc[2] <= 0: + raise GlbError("instance scale must have a positive determinant; mirror the mesh instead") + if not all(math.isfinite(v) for v in t + sc): + raise GlbError("instance translation and scale must be finite") + b = instance_bounds(box_min, box_max, t, q, sc) + for k in range(3): + lo[k] = min(lo[k], b[k]) + hi[k] = max(hi[k], b[k + 3]) + ts.append(t) + rs.append(q) + ss.append(sc) + instances_total += len(insts) + drawn_tris += mesh_tris * len(insts) + if mode == "gpu": + attrs = {} + for key, values, kind in (("TRANSLATION", ts, "VEC3"), ("ROTATION", rs, "VEC4"), ("SCALE", ss, "VEC3")): + data, _ = _pack_f32(values, 4 if kind == "VEC4" else 3) + bv = _append_buffer_view(bin_buf, buffer_views, data, target=None) + attrs[key] = len(accessors) + accessors.append({"bufferView": bv, "componentType": COMPONENT_FLOAT, "count": len(values), "type": kind}) + nodes.append({"mesh": mesh_idx, "extensions": {INSTANCING_EXTENSION: {"attributes": attrs}}}) + else: + for t, q, sc in zip(ts, rs, ss): + node: dict = {"mesh": mesh_idx} + if any(t): + node["translation"] = [_clean_zero(v) for v in t] + if q != [0.0, 0.0, 0.0, 1.0]: + node["rotation"] = [_clean_zero(v) for v in q] + if sc != [1.0, 1.0, 1.0]: + node["scale"] = [_clean_zero(v) for v in sc] + nodes.append(node) + if not nodes: + raise GlbError("cannot build GLB: no mesh with primitives and instances") + bin_pad = (-len(bin_buf)) % 4 + if bin_pad: + bin_buf.extend(b"\x00" * bin_pad) + gltf: dict = { + "asset": {"version": "2.0", "generator": generator}, + "scene": 0, + "scenes": [{"nodes": list(range(len(nodes)))}], + "nodes": nodes, + "meshes": gltf_meshes, + "accessors": accessors, + "bufferViews": buffer_views, + "buffers": [{"byteLength": len(bin_buf)}], + } + table.apply(gltf) + if mode == "gpu": + gltf["extensionsUsed"] = [INSTANCING_EXTENSION] + gltf["extensionsRequired"] = [INSTANCING_EXTENSION] + json_bytes = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") + json_bytes += b" " * ((-len(json_bytes)) % 4) + total_length = 12 + 8 + len(json_bytes) + 8 + len(bin_buf) + glb_bytes = b"".join(( + struct.pack("<4sII", GLB_MAGIC, GLB_VERSION, total_length), + struct.pack(" dict: + """``build_instanced_glb`` published atomically at ``path`` (same staging rules as ``write_glb``).""" + glb_bytes, stats = build_instanced_glb(meshes, materials, mode=mode) + _write_bytes_atomic(path, glb_bytes) return stats diff --git a/tools/hashdict.py b/tools/hashdict.py index 4bad01431..5986bf246 100644 --- a/tools/hashdict.py +++ b/tools/hashdict.py @@ -126,7 +126,8 @@ def main(): for fn in files: strings.add(os.path.splitext(fn)[0]) elif os.path.isfile(x): - harvest(open(x, "rb").read(), strings, a.min) + with open(x, "rb") as f: + harvest(f.read(), strings, a.min) d = {} for s in sorted(strings): d.setdefault(f"{joaat(s):08x}", s) diff --git a/tools/hw_oracle/asm.py b/tools/hw_oracle/asm.py index 41f169fd5..095d1e645 100644 --- a/tools/hw_oracle/asm.py +++ b/tools/hw_oracle/asm.py @@ -15,15 +15,22 @@ GFX11_REMOVED = { "s_ff0_i32_b32": "removed in GFX11 (no find-first-zero; the ISA has only s_ctz = ff1)", "s_ff0_i32_b64": "removed in GFX11 (no find-first-zero; the ISA has only s_ctz = ff1)", } +# GFX12 also drops the SOPK compares: AMD clang (rocm-sdk-core 10.0.0) assembles all twelve for gfx1150 and rejects +# every one for gfx1201 ("instruction not supported on this GPU"). +GFX12_REMOVED = dict(GFX11_REMOVED, **{ + f"s_cmpk_{cond}_{ty}": "removed in GFX12 (no SOPK compares; s_cmp with a literal is the replacement)" + for cond in ("eq", "lg", "gt", "ge", "lt", "le") for ty in ("i32", "u32") +}) _LITERAL_FREE = ("s_movk_i32", "s_addk_i32", "s_mulk_i32") def family(arch): - """'gfx10' for gfx10xx, 'gfx11' for gfx11xx (the only two flavours the mnemonics differ between).""" + """'gfx10', 'gfx11' or 'gfx12' for gfx10xx, gfx11xx and gfx12xx. GFX12 uses GFX11's spellings for everything + the kernels here emit; it differs only in which SALU opcodes exist (GFX12_REMOVED).""" m = re.fullmatch(r"gfx(\d+?)[0-9a-f]{2}", arch) - if not m or m.group(1) not in ("10", "11"): - raise ValueError(f"unsupported GPU architecture {arch!r} (expected gfx10xx or gfx11xx)") + if not m or m.group(1) not in ("10", "11", "12"): + raise ValueError(f"unsupported GPU architecture {arch!r} (expected gfx10xx, gfx11xx or gfx12xx)") return "gfx" + m.group(1) @@ -46,7 +53,7 @@ def literals(line): def skip_reason(lines, arch): """Why a program cannot be run on this architecture, or None. Hardware allows one literal per instruction.""" - removed = GFX11_REMOVED if family(arch) == "gfx11" else {} + removed = {"gfx10": {}, "gfx11": GFX11_REMOVED, "gfx12": GFX12_REMOVED}[family(arch)] for line in lines: op = line.partition(" ")[0] if op in removed: @@ -59,16 +66,49 @@ def skip_reason(lines, arch): class Kernel: """One program to run. lines: the instructions. raw=False wraps them (output pointer load, v[8:11] store); raw=True means the lines already end with their own stores and s_endpgm and only get the output pointer in - s[2:3]. threads: workgroup size; words: dwords read back; wave: 32 or 64.""" + s[2:3]. threads: workgroup size; words: dwords read back; wave: 32 or 64. mode: the float MODE the kernel + starts with (raw kernels only), a dict of MODE_FIELDS names to values; None keeps the assembler's defaults.""" - def __init__(self, lines, wave=32, threads=1, words=4, raw=False): + def __init__(self, lines, wave=32, threads=1, words=4, raw=False, mode=None): self.lines, self.wave, self.threads, self.words, self.raw = list(lines), wave, threads, words, raw + self.mode = dict(mode or {}) + unknown = set(self.mode) - set(MODE_FIELDS) + if unknown: + raise ValueError(f"unknown MODE fields {sorted(unknown)} (known: {sorted(MODE_FIELDS)})") -def raw_kernel_text(name, lines, arch, wave=32): +# Float MODE the kernel descriptor starts a wave with, as .amdhsa_* directives. The assembler's defaults (checked on +# gfx1150 by reading the register back, see docs/shader_validation.md): IEEE 1, DX10_CLAMP 1, f32 denormals +# flushed (denorm_mode_32 = 0), f16/f64 denormals kept (3), all rounding to nearest even (0). +MODE_FIELDS = { + "ieee": ".amdhsa_ieee_mode", + "dx10_clamp": ".amdhsa_dx10_clamp", + "denorm32": ".amdhsa_float_denorm_mode_32", + "denorm16_64": ".amdhsa_float_denorm_mode_16_64", + "round32": ".amdhsa_float_round_mode_32", + "round16_64": ".amdhsa_float_round_mode_16_64", +} + + +# The global memory instructions GFX11 renamed, under their GFX10 names. A raw kernel body is written with the +# GFX11 ones (crosslane_fuzz stores with global_store_b32); a GFX10 assembler only takes the old spelling. +_GFX10_NAMES = {f"global_{kind}_b{bits}": f"global_{kind}_dword{suffix}" + for kind in ("load", "store") for bits, suffix in ((32, ""), (64, "x2"), (96, "x3"), (128, "x4"))} + + +def gfx10_spelling(line): + """A raw kernel line with a renamed memory mnemonic put back to its GFX10 name (the same instruction).""" + op, sep, rest = line.partition(" ") + return _GFX10_NAMES.get(op, op) + sep + rest + + +def raw_kernel_text(name, lines, arch, wave=32, mode=None): """A kernel whose body does its own stores. s[0:1] is the kernarg pointer, s[2:3] gets the output pointer.""" fam = family(arch) + modes = "".join(f"\n {MODE_FIELDS[k]} {int(v)}" for k, v in sorted((mode or {}).items())) load = "s_load_b64" if fam == "gfx11" else "s_load_dwordx2" + if fam == "gfx10": + lines = [gfx10_spelling(ln) for ln in lines] body = "\n".join(" " + ln for ln in lines) return f""".globl {name} .p2align 8 @@ -84,7 +124,7 @@ def raw_kernel_text(name, lines, arch, wave=32): .amdhsa_next_free_vgpr 32 .amdhsa_next_free_sgpr 40 .amdhsa_wavefront_size32 {1 if wave == 32 else 0} - .amdhsa_system_vgpr_workitem_id 0 + .amdhsa_system_vgpr_workitem_id 0{modes} .end_amdhsa_kernel .text """ @@ -93,8 +133,8 @@ def raw_kernel_text(name, lines, arch, wave=32): def kernel_text(name, lines, arch): """Assembly for one kernel.""" fam = family(arch) - load = "s_load_b64" if fam == "gfx11" else "s_load_dwordx2" - store = "global_store_b128" if fam == "gfx11" else "global_store_dwordx4" + load = "s_load_dwordx2" if fam == "gfx10" else "s_load_b64" + store = "global_store_dwordx4" if fam == "gfx10" else "global_store_b128" body = "\n".join(" " + line for line in lines) return f""".globl {name} .p2align 8 @@ -141,7 +181,7 @@ def module_text(programs, arch, prefix="k", wave=32): for i, prog in enumerate(programs): name = f"{prefix}{i}" if isinstance(prog, Kernel): - text = raw_kernel_text(name, prog.lines, arch, prog.wave) if prog.raw else kernel_text(name, prog.lines, arch) + text = raw_kernel_text(name, prog.lines, arch, prog.wave, prog.mode) if prog.raw else kernel_text(name, prog.lines, arch) else: text = kernel_text(name, prog, arch) names.append(name) @@ -152,6 +192,33 @@ def module_text(programs, arch, prefix="k", wave=32): return "\n".join(parts) + "\n", names, starts +# ---- f32 vector ALU: what GFX11 does not have, or has under another name (tools/f32_fuzz.py --oracle hw) ---- +# Checked by assembling every f32_fuzz opcode with llvm-mc for gfx1013 (the console), gfx1010, gfx1030, gfx1100, +# gfx1150 and gfx1200. The four mad opcodes exist on GFX10.1 only (gfx1010, gfx1011, gfx1013): gfx1030 (RDNA2 +# desktop) and every GFX11 part reject them. They are not "renamed": v_fma_f32, v_fmac_f32, v_fmaak_f32 and +# v_fma_dx9_zero_f32 round once where the mad opcodes round the product first, so substituting one would compare a +# different instruction. +_MAD_GONE = "exists on GFX10.1 only (gfx1010/1011/1013), not on gfx1030 or GFX11; {} is fused, a different instruction" +VALU_REMOVED = { + "v_mad_f32": _MAD_GONE.format("v_fma_f32"), + "v_mac_f32": _MAD_GONE.format("v_fmac_f32"), + "v_madak_f32": _MAD_GONE.format("v_fmaak_f32"), + "v_mad_legacy_f32": _MAD_GONE.format("v_fma_dx9_zero_f32"), +} +# Same instruction, new mnemonic: the assembler takes the GFX10 spelling for GFX11 and encodes the GFX11 name. +GFX11_VALU_RENAMED = { + "v_mul_legacy_f32": "v_mul_dx9_zero_f32", # DX9 rule: 0 * anything = 0 (the oracle itself checks it) + "v_cvt_pkrtz_f16_f32": "v_cvt_pk_rtz_f16_f32", +} + + +def valu_skip_reason(op, arch): + """Why an f32 VALU opcode cannot be run on this architecture, or None.""" + if op in VALU_REMOVED and arch not in ("gfx1010", "gfx1011", "gfx1012", "gfx1013"): + return f"{op}: {VALU_REMOVED[op]}" + return None + + def failing_kernels(stderr, starts): """Indices of the kernels an assembler error message points into (error lines are 'file:LINE:COL: error').""" bad = set() diff --git a/tools/hw_oracle/drm.py b/tools/hw_oracle/drm.py new file mode 100644 index 000000000..c5bd4db42 --- /dev/null +++ b/tools/hw_oracle/drm.py @@ -0,0 +1,214 @@ +"""The Linux backend of the hardware oracle: the same kernels, run as raw compute dispatches through the kernel +driver (libdrm_amdgpu) by hw_oracle_drm.c. Standard library only. No ROCm: an assembler with the amdgcn target +(clang from the distribution's LLVM), gcc and the libdrm headers are enough. + + LEONIDA_HW_DRM_NODE the render node of the GPU to use, for example /dev/dri/renderD129. Required: there + is no default, so that a raw command stream never goes to a GPU by accident. + `ls -l /dev/dri/by-path` shows which node belongs to which PCI device. + LEONIDA_HW_DRM_ALLOW_DISPLAY set to 1 to use a GPU that has a display connected. A kernel that hangs makes the + kernel driver reset the GPU, and with it everything shown on that display. + LEONIDA_AMD_CLANG, LEONIDA_HOST_CC, LEONIDA_HW_ARCH as in runner.py + +The launcher supports compute engine version 10 only: GFX10, which is RDNA1 and RDNA2. +""" +import glob +import hashlib +import os +import shutil +import struct +import subprocess +import tempfile + +try: + from . import asm, runner +except ImportError: # run as a script, or imported by runner.py run as a script + import asm + import runner + +HERE = os.path.dirname(os.path.abspath(__file__)) +SOURCE = os.path.join(HERE, "hw_oracle_drm.c") +Unavailable = runner.Unavailable + + +def connected_displays(node, sysfs="/sys/class/drm"): + """The connectors of the GPU behind a render node that have a display attached, as sysfs names them.""" + found = [] + for status in sorted(glob.glob(os.path.join(sysfs, os.path.basename(node), "device", "drm", "card*", "card*-*", + "status"))): + try: + with open(status, encoding="ascii") as f: + if f.read().strip() == "connected": + found.append(os.path.basename(os.path.dirname(status))) + except OSError: + pass + return found + + +def find_node(environ=None, sysfs="/sys/class/drm"): + """The render node to use, or raise Unavailable.""" + environ = os.environ if environ is None else environ + node = environ.get("LEONIDA_HW_DRM_NODE") + if not node: + raise Unavailable("set LEONIDA_HW_DRM_NODE to the render node of a GFX10 AMD GPU that drives no display " + "(`ls -l /dev/dri/by-path` lists them)") + if not os.path.exists(node): + raise Unavailable(f"LEONIDA_HW_DRM_NODE={node} does not exist") + displays = connected_displays(node, sysfs) + if displays and environ.get("LEONIDA_HW_DRM_ALLOW_DISPLAY") != "1": + raise Unavailable(f"{node} drives a display ({', '.join(displays)}): a kernel that hangs resets that GPU. " + "Use a GPU without one, or set LEONIDA_HW_DRM_ALLOW_DISPLAY=1") + return node + + +def _symbols(elf): + """([(section name, address, file offset, size)], [(symbol, section number, value)]) of a little-endian ELF64.""" + if elf[:6] != b"\x7fELF\x02\x01": + raise ValueError("not a little-endian ELF64 file") + shoff, = struct.unpack_from(".kd + symbols) of an assembled module. + + The descriptor is where the assembler puts what a runtime must program before it starts the kernel: the + register counts and the float mode (rounding, denormals, IEEE, DX10 clamp) in RSRC1, the user and system SGPRs + in RSRC2, the wave size in the code properties. The HIP runtime follows it, and so does the launcher. What the + launcher does not provide is refused here instead of being run differently.""" + sections, symbols = _symbols(elf) + out = {} + for name, shndx, value in symbols: + if not name.endswith(".kd"): + continue + _section, address, offset, size = sections[shndx] + if value - address + 64 > size: + raise ValueError(f"{name}: the kernel descriptor runs past its section") + at = offset + value - address + group, private = struct.unpack_from("> 15) & 0x1FF: + raise RuntimeError(f"{kernel}: LDS, scratch memory and COMPUTE_PGM_RSRC3 are not supported by the launcher") + if (rsrc2 >> 1) & 0x1F != 2: + raise RuntimeError(f"{kernel}: {(rsrc2 >> 1) & 0x1F} user SGPRs; the launcher fills two") + out[kernel] = (rsrc1, rsrc2, 32 if properties & 0x0400 else 64) + return out + + +def launcher_tokens(tokens, offsets, registers): + """name[:threads[:words]] -> name@offset/rsrc1/rsrc2/wave[:threads[:words]], the form hw_oracle_drm takes.""" + out = [] + for token in tokens: + name, sep, rest = token.partition(":") + if name not in offsets or name not in registers: + raise RuntimeError(f"kernel {name} is not in the assembled module") + rsrc1, rsrc2, wave = registers[name] + out.append(f"{name}@{offsets[name]}/{rsrc1:#x}/{rsrc2:#x}/{wave}{sep}{rest}") + return out + + +class DrmOracle(runner.Oracle): + """runner.Oracle with the assembling and launching done for the kernel driver instead of the HIP runtime.""" + + def __init__(self, arch=None, workdir=None, chunk=500): + if not os.path.isfile(SOURCE): + raise Unavailable("hw_oracle_drm.c is missing") + self.node = find_node() + self.clang = runner.find_clang() + self.chunk = chunk + self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") + self._offsets, self._registers = {}, {} + self.exe = self._build_launcher() + self.arch = arch or os.environ.get("LEONIDA_HW_ARCH") or self._device_arch() + try: + asm.family(self.arch) + except ValueError as e: # as in runner.Oracle: an architecture without spellings is a skip + raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None + self.device = self._probe() + if hasattr(self, "_probe_waves"): # runner.Oracle has it once it runs kernels of both wave sizes + self._probe_waves() + + def _build_launcher(self): + with open(SOURCE, "rb") as f: + tag = hashlib.sha1(f.read()).hexdigest()[:10] + exe = os.path.join(tempfile.gettempdir(), f"leonida_hw_oracle_drm_{tag}") + if not os.path.isfile(exe): + flags = ["-I/usr/include/libdrm", "-ldrm_amdgpu"] + pkg_config = shutil.which("pkg-config") + if pkg_config: + r = subprocess.run([pkg_config, "--cflags", "--libs", "libdrm_amdgpu"], capture_output=True, text=True) + if r.returncode == 0 and r.stdout.strip(): + flags = r.stdout.split() + tmp = exe + f".{os.getpid()}" + kind, cc = runner.find_cc() + if kind != "gcc": # only an override named cl gives anything else on Linux + raise Unavailable(f"hw_oracle_drm.c needs gcc or a compiler that takes its options, not {cc}") + r = subprocess.run([cc, "-O1", SOURCE, "-o", tmp, *flags], capture_output=True, text=True) + if r.returncode: + raise Unavailable("hw_oracle_drm.c did not build (it needs the libdrm headers): " + r.stderr.strip()[:300]) + os.replace(tmp, exe) + return exe + + def _device_arch(self): + """What the launcher says the GPU is; it prints its device line before it reads any code.""" + r = subprocess.run([self.exe, os.devnull, "4", self.node], input="", capture_output=True, text=True) + head = r.stdout.splitlines()[0] if r.stdout else "" + if not head.startswith("#"): + raise Unavailable((r.stderr.strip() or "the launcher printed no device line")[:300]) + arch = next((field[5:] for field in head.split() if field.startswith("arch=")), "") + return "gfx1030" if arch in ("", "gfx10xx") else arch # every GFX10 chip takes the same encodings + + def _assemble(self, text, wave=32): + s = os.path.join(self.workdir, "k.s") + o = os.path.join(self.workdir, "k.o") + code = os.path.join(self.workdir, "k.bin") + with open(s, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + r = subprocess.run([self.clang, "--target=amdgcn-amd-amdhsa", f"-mcpu={self.arch}", + *(["-mwavefrontsize64"] if wave == 64 else []), "-c", s, "-o", o], + capture_output=True, text=True) + if r.returncode: + return None, r.stderr + with open(o, "rb") as f: + elf = f.read() + binary, self._offsets = text_section(elf) + self._registers = kernel_registers(elf) + with open(code, "wb") as f: + f.write(binary) + return code, "" + + def _launch(self, code, tokens, words=4): + r = subprocess.run([self.exe, code, str(words), self.node], + input="\n".join(launcher_tokens(tokens, self._offsets, self._registers)) + "\n", + capture_output=True, text=True) + return r.returncode, r.stdout, r.stderr diff --git a/tools/hw_oracle/hw_oracle_drm.c b/tools/hw_oracle/hw_oracle_drm.c new file mode 100644 index 000000000..3703faf76 --- /dev/null +++ b/tools/hw_oracle/hw_oracle_drm.c @@ -0,0 +1,298 @@ +/* Hardware oracle launcher for Linux. Runs kernels as raw compute dispatches through the kernel driver + * (libdrm_amdgpu): no ROCm, no Vulkan, nothing between the instructions and the GPU. + * + * hw_oracle_drm + * + * is the .text section of the assembled module. Kernel tokens come on stdin, whitespace separated: + * name@offset/rsrc1/rsrc2/wave[:threads[:words]] + * offset where the kernel starts in code.bin, a multiple of 256 + * rsrc1, rsrc2 COMPUTE_PGM_RSRC1 and COMPUTE_PGM_RSRC2 from the kernel's descriptor: its register counts and + * float mode, and its user and system SGPRs (drm.py reads them out of the assembled object) + * wave 32 or 64, from the descriptor too + * Each kernel gets what the Windows launcher (hw_oracle.c) gives it: s[0:1] points at an 8-byte kernarg holding + * the address of a dword buffer pre-filled with 0xDEAD0000, and it runs as one workgroup of `threads` + * threads (1..1024), started the way its descriptor says. + * Output, one line per kernel: ... The first line is "# device= arch= ...". + * Exit 0 ok, 77 no usable device, 2 usage, 3 failure (a kernel that does not finish within five seconds is one: + * the kernel driver then resets the GPU). + * + * The command stream is libdrm's own compute dispatch test for this GPU generation (libdrm 2.4.115, + * tests/amdgpu/shader_test_util.c, amdgpu_test_dispatch_memset, the gfx10 path), register for register. What + * differs is what belongs to the kernel: its entry point, COMPUTE_PGM_RSRC1 and COMPUTE_PGM_RSRC2 as its + * descriptor has them, the kernarg pointer as its two user SGPRs, the group size, and CS_W32_EN in the dispatch + * for 32-lane waves. + * That sequence is the one for compute engine version 10 (GFX10: RDNA1 and RDNA2), so anything else is refused. + * A raw stream bypasses the Vulkan driver: run it on a GPU that drives no display (runner.py checks). + * + * Every submission gets command buffer memory of its own, never rewritten. Measured on a Ryzen 9 7950X3D's + * integrated GPU: when one buffer was rewritten in place right after its fence, the second dispatch of a process + * ran the first one's commands in 200 of 200 runs; with a fresh place for each, 24,500 distinct kernels (both + * wave sizes) each returned their own words. + * + * Build: gcc -O1 hw_oracle_drm.c -o hw_oracle_drm $(pkg-config --cflags --libs libdrm_amdgpu) + */ +#include +#include + +#include +#include +#include +#include +#include +#include + +#define PACKET3(op, n) ((3u << 30) | (((op) & 0xFF) << 8) | ((n) & 0x3FFF) << 16) +#define PACKET3_COMPUTE(op, n) (PACKET3(op, n) | (1 << 1)) +#define PACKET3_DISPATCH_DIRECT 0x15 +#define PACKET3_SET_SH_REG 0x76 +#define PACKET3_SET_UCONFIG_REG 0x79 +#define PACKET3_SET_SH_REG_INDEX 0x9B + +#define SENTINEL 0xDEAD0000u +#define IB_BYTES 1024u /* one submission's commands; about 80 dwords are used */ +#define IB_BLOCK (1u << 20) /* command memory is allocated a block at a time */ + +struct buffer { + amdgpu_bo_handle bo; + amdgpu_va_handle va; + uint64_t address; + void *cpu; + unsigned size; +}; + +static int allocate(amdgpu_device_handle dev, struct buffer *b, unsigned size, unsigned heap) { + struct amdgpu_bo_alloc_request request = {0}; + size = (size + 4095u) & ~4095u; + request.alloc_size = size; + request.phys_alignment = 4096; + request.preferred_heap = heap; + b->size = size; + if (amdgpu_bo_alloc(dev, &request, &b->bo)) return -1; + if (amdgpu_va_range_alloc(dev, amdgpu_gpu_va_range_general, size, 4096, 0, &b->address, &b->va, 0)) return -1; + if (amdgpu_bo_va_op_raw(dev, b->bo, 0, size, b->address, + AMDGPU_VM_PAGE_READABLE | AMDGPU_VM_PAGE_WRITEABLE | AMDGPU_VM_PAGE_EXECUTABLE, + AMDGPU_VA_OP_MAP)) + return -1; + return amdgpu_bo_cpu_map(b->bo, &b->cpu); +} + +/* The LLVM processor name of a GFX10 chip, from the kernel's family id and revision (the ranges are the ones + * Mesa's ac_gpu_info.c uses). Every GFX10 chip takes the same encodings, so this only labels the result. */ +static const char *arch_name(const struct amdgpu_gpu_info *gpu) { + const unsigned rev = gpu->chip_external_rev; + switch (gpu->family_id) { + case 143: /* AMDGPU_FAMILY_NV */ + if (rev < 0x0A) return "gfx1010"; + if (rev < 0x14) return "gfx1011"; + if (rev < 0x28) return "gfx1012"; + if (rev < 0x32) return "gfx1030"; + if (rev < 0x3C) return "gfx1031"; + if (rev < 0x46) return "gfx1032"; + return "gfx1034"; + case 144: return "gfx1033"; /* AMDGPU_FAMILY_VGH */ + case 146: return "gfx1035"; /* AMDGPU_FAMILY_YC */ + case 149: return "gfx1036"; /* AMDGPU_FAMILY_GC_10_3_6 */ + case 151: return "gfx1037"; /* AMDGPU_FAMILY_GC_10_3_7 */ + default: return "gfx10xx"; + } +} + +int main(int argc, char **argv) { + if (argc < 4) { + fprintf(stderr, "usage: hw_oracle_drm code.bin words /dev/dri/renderD < kernel-tokens\n"); + return 2; + } + const unsigned words = (unsigned)strtoul(argv[2], NULL, 0); + if (words < 1 || words > 4096) { fprintf(stderr, "words must be 1..4096\n"); return 2; } + + const int fd = open(argv[3], O_RDWR); + if (fd < 0) { perror(argv[3]); return 77; } + uint32_t major = 0, minor = 0; + amdgpu_device_handle dev; + if (amdgpu_device_initialize(fd, &major, &minor, &dev)) { + fprintf(stderr, "%s is not an AMD GPU the amdgpu kernel driver runs\n", argv[3]); + return 77; + } + struct amdgpu_gpu_info gpu = {0}; + struct drm_amdgpu_info_hw_ip ip = {0}; + if (amdgpu_query_gpu_info(dev, &gpu) || amdgpu_query_hw_ip_info(dev, AMDGPU_HW_IP_COMPUTE, 0, &ip)) { + fprintf(stderr, "device queries failed\n"); + return 77; + } + if (ip.hw_ip_version_major != 10 || !(ip.available_rings & 1)) { + fprintf(stderr, "compute engine %u.%u: only version 10 (GFX10, RDNA1 and RDNA2) is supported\n", + ip.hw_ip_version_major, ip.hw_ip_version_minor); + return 77; + } + const char *name = amdgpu_get_marketing_name(dev); + printf("# device=%s (0x%04x) arch=%s engine=%u.%u\n", name ? name : "AMD GPU", gpu.asic_id, arch_name(&gpu), + ip.hw_ip_version_major, ip.hw_ip_version_minor); + fflush(stdout); + + FILE *file = fopen(argv[1], "rb"); + if (!file) { perror(argv[1]); return 2; } + fseek(file, 0, SEEK_END); + const long code_bytes = ftell(file); + fseek(file, 0, SEEK_SET); + if (code_bytes < 4 || code_bytes % 4 || code_bytes > (64 << 20)) { + fprintf(stderr, "%s: %ld bytes; expected whole dwords, at most 64 MiB\n", argv[1], code_bytes); + return 2; + } + + amdgpu_context_handle context; + struct buffer cmd = {0}, code = {0}, kernarg = {0}, out = {0}; + /* The code gets a page of zeros behind it: the GPU fetches instructions ahead, past a kernel's s_endpgm. */ + if (amdgpu_cs_ctx_create(dev, &context) || + allocate(dev, &code, (unsigned)code_bytes + 4096, AMDGPU_GEM_DOMAIN_VRAM) || + allocate(dev, &kernarg, 4096, AMDGPU_GEM_DOMAIN_VRAM) || allocate(dev, &out, words * 4, AMDGPU_GEM_DOMAIN_VRAM)) { + fprintf(stderr, "context or buffer creation failed\n"); + return 3; + } + memset(code.cpu, 0, code.size); + if (fread(code.cpu, 1, (size_t)code_bytes, file) != (size_t)code_bytes) { fprintf(stderr, "short read\n"); return 2; } + fclose(file); + memset(kernarg.cpu, 0, kernarg.size); + memcpy(kernarg.cpu, &out.address, 8); /* the kernel's one argument: where its output goes */ + + amdgpu_bo_list_handle list = NULL; + unsigned ib_used = IB_BLOCK; /* no block yet */ + + char token[512]; + while (scanf("%511s", token) == 1) { + /* name@offset/rsrc1/rsrc2/wave[:threads[:words]] */ + char *at = strchr(token, '@'); + if (!at) { fprintf(stderr, "bad kernel token %s (no @offset)\n", token); return 2; } + *at++ = 0; + char *rest = NULL; + const unsigned long offset = strtoul(at, &rest, 0); + uint32_t rsrc1 = 0, rsrc2 = 0; + unsigned wave = 0, threads = 1, w = words; + if (*rest == '/') rsrc1 = (uint32_t)strtoul(rest + 1, &rest, 0); + if (*rest == '/') rsrc2 = (uint32_t)strtoul(rest + 1, &rest, 0); + if (*rest == '/') wave = (unsigned)strtoul(rest + 1, &rest, 10); + if (*rest == ':') { + threads = (unsigned)strtoul(rest + 1, &rest, 10); + if (*rest == ':') w = (unsigned)strtoul(rest + 1, &rest, 10); + } + if (*rest || offset % 256 || offset >= (unsigned long)code_bytes || (wave != 32 && wave != 64) || threads < 1 || + threads > 1024 || w < 1 || w > words) { + fprintf(stderr, "bad kernel token for %s\n", token); + return 2; + } + uint32_t *result = out.cpu; + for (unsigned i = 0; i < w; i++) result[i] = SENTINEL; + + if (ib_used + IB_BYTES > IB_BLOCK) { + /* A new block of command memory. The old one stays mapped: nothing may reuse it. */ + if (list) amdgpu_bo_list_destroy(list); + memset(&cmd, 0, sizeof cmd); + if (allocate(dev, &cmd, IB_BLOCK, AMDGPU_GEM_DOMAIN_GTT)) { fprintf(stderr, "command buffer allocation failed\n"); return 3; } + amdgpu_bo_handle resources[4] = {out.bo, kernarg.bo, code.bo, cmd.bo}; + if (amdgpu_bo_list_create(dev, 4, resources, NULL, &list)) { fprintf(stderr, "bo list creation failed\n"); return 3; } + ib_used = 0; + } + const uint64_t entry = code.address + offset; + const uint64_t ib_address = cmd.address + ib_used; + uint32_t *p = (uint32_t *)((char *)cmd.cpu + ib_used); + ib_used += IB_BYTES; + int i = 0; + /* amdgpu_dispatch_init_gfx9 (no context control on the compute engine): COMPUTE_START_X..Z, TMPRING_SIZE. */ + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 3); + p[i++] = 0x204; + p[i++] = 0; + p[i++] = 0; + p[i++] = 0; + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); + p[i++] = 0x218; + p[i++] = 0; + /* amdgpu_dispatch_init_gfx10: COMPUTE_SHADER_CHKSUM, COMPUTE_REQ_CTRL (6 registers), CP_COHER_START_DELAY. */ + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); + p[i++] = 0x22a; + p[i++] = 0; + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 6); + p[i++] = 0x222; + for (int k = 0; k < 6; k++) p[i++] = 0; + p[i++] = PACKET3(PACKET3_SET_UCONFIG_REG, 1); + p[i++] = 0x7b; + p[i++] = 0x20; + /* amdgpu_dispatch_write_cumask (gfx10): COMPUTE_STATIC_THREAD_MGMT_SE0..3. */ + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG_INDEX, 2); + p[i++] = 0x30000216; + p[i++] = 0xffffffff; + p[i++] = 0xffffffff; + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG_INDEX, 2); + p[i++] = 0x30000219; + p[i++] = 0xffffffff; + p[i++] = 0xffffffff; + /* amdgpu_dispatch_write2hw_gfx10: COMPUTE_PGM_LO/HI (the entry point, in 256-byte units), the shader's + * registers, COMPUTE_PGM_RSRC3. */ + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 2); + p[i++] = 0x20c; + p[i++] = (uint32_t)(entry >> 8); + p[i++] = (uint32_t)(entry >> 40); + const uint32_t registers[][2] = { + {0x2e12, rsrc1}, /* COMPUTE_PGM_RSRC1, from the kernel's descriptor (0x000C0041 in the reference) */ + {0x2e13, rsrc2}, /* COMPUTE_PGM_RSRC2, from the kernel's descriptor (0x00000090 in the reference) */ + {0x2e07, threads}, /* COMPUTE_NUM_THREAD_X */ + {0x2e08, 1}, /* COMPUTE_NUM_THREAD_Y */ + {0x2e09, 1}, /* COMPUTE_NUM_THREAD_Z */ + }; + for (unsigned r = 0; r < sizeof(registers) / sizeof(registers[0]); ++r) { + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); + p[i++] = registers[r][0] - 0x2c00; + p[i++] = registers[r][1]; + } + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); + p[i++] = 0x228; + p[i++] = 0; + /* COMPUTE_USER_DATA_0..1: the kernarg pointer. */ + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 2); + p[i++] = 0x240; + p[i++] = (uint32_t)kernarg.address; + p[i++] = (uint32_t)(kernarg.address >> 32); + /* amdgpu_dispatch_write_dispatch_cmd: COMPUTE_RESOURCE_LIMITS, then one group. The initiator is + * COMPUTE_SHADER_EN, with CS_W32_EN (bit 15) for 32-lane waves. */ + p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); + p[i++] = 0x215; + p[i++] = 0; + p[i++] = PACKET3_COMPUTE(PACKET3_DISPATCH_DIRECT, 3); + p[i++] = 1; + p[i++] = 1; + p[i++] = 1; + p[i++] = 1u | (wave == 32 ? 1u << 15 : 0); + while (i & 7) p[i++] = 0xffff1000; /* type-3 nop */ + + struct amdgpu_cs_ib_info ib = {0}; + ib.ib_mc_address = ib_address; + ib.size = (uint32_t)i; + struct amdgpu_cs_request request = {0}; + request.ip_type = AMDGPU_HW_IP_COMPUTE; + request.ring = 0; + request.resources = list; + request.number_of_ibs = 1; + request.ibs = &ib; + const int submitted = amdgpu_cs_submit(context, 0, &request, 1); + if (submitted) { fprintf(stderr, "%s: amdgpu_cs_submit failed: %d\n", token, submitted); return 3; } + struct amdgpu_cs_fence fence = {0}; + fence.context = context; + fence.ip_type = AMDGPU_HW_IP_COMPUTE; + fence.ring = 0; + fence.fence = request.seq_no; + uint32_t expired = 0; + const int waited = amdgpu_cs_query_fence_status(&fence, 5000000000ull, 0, &expired); /* five seconds */ + if (waited || !expired) { + fprintf(stderr, "%s did not finish within 5 s (wait returned %d): the kernel driver will time the job out " + "and reset this GPU\n", token, waited); + return 3; + } + printf("%s", token); + for (unsigned k = 0; k < w; k++) printf(" %08x", result[k]); + printf("\n"); + } + fflush(stdout); + if (list) amdgpu_bo_list_destroy(list); + amdgpu_cs_ctx_free(context); + amdgpu_device_deinitialize(dev); + close(fd); + return 0; +} diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py index 9abc3f841..345d8b1f0 100644 --- a/tools/hw_oracle/runner.py +++ b/tools/hw_oracle/runner.py @@ -1,10 +1,15 @@ """Find the tools, build the launcher, assemble kernels and run them on the GPU. Standard library only. +Two launchers: on Windows the HIP runtime that ships in the AMD driver (hw_oracle.c, this file), on Linux raw +dispatches through the kernel driver (hw_oracle_drm.c, drm.py, which also lists its own variables). open_oracle() +picks the one for the platform. + Tools are located through environment variables first, then by looking in the usual places: LEONIDA_AMD_CLANG AMD clang (its folder must also hold ld.lld); default: amdclang / clang on PATH that lists the amdgcn target, %HIP_PATH% / %ROCM_PATH%, a .venv holding the `rocm-sdk-core` wheel LEONIDA_HIP_DLL the HIP runtime (amdhip64_7.dll); default: the one in System32 (it ships with the driver) - LEONIDA_HOST_CC a C compiler for hw_oracle.c (MinGW gcc); default: gcc on PATH, C:\\msys64\\ucrt64\\bin + LEONIDA_HOST_CC a C compiler for hw_oracle.c (MinGW gcc, or cl.exe from a Developer shell); default: gcc on + PATH, C:\\msys64\\ucrt64\\bin, then on Windows a cl on PATH or Visual Studio's (vswhere) LEONIDA_HW_ARCH the GPU architecture to assemble for; default: what amdgpu-arch reports, else gfx1150 Anything missing raises Unavailable, which callers turn into exit 77 ("skipped"). """ @@ -77,16 +82,64 @@ def find_hip_dll(): raise Unavailable("no amdhip64_7.dll in System32 (the AMD Windows driver provides it)") +def _is_msvc(cc): + """cl.exe (MSVC or clang-cl) takes /Fe, not -o.""" + return os.path.basename(cc).lower() in ("cl.exe", "cl", "clang-cl.exe", "clang-cl") + + +def find_vcvars(): + """vcvars64.bat of the newest Visual Studio with the x64 C++ tools, as scripts/build_runtime.ps1 finds it.""" + pf86 = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)") + vswhere = os.path.join(pf86, "Microsoft Visual Studio", "Installer", "vswhere.exe") + if not os.path.isfile(vswhere): + return None + try: + out = subprocess.run([vswhere, "-latest", "-products", "*", "-requires", + "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"], + capture_output=True, text=True, timeout=60).stdout.strip().splitlines() + except (OSError, subprocess.SubprocessError): + return None + bat = os.path.join(out[0].strip(), "VC", "Auxiliary", "Build", "vcvars64.bat") if out else "" + return bat if os.path.isfile(bat) else None + + def find_cc(): + """The host compiler for hw_oracle.c: ('gcc', path), ('msvc', cl path) or ('vcvars', vcvars64.bat path).""" env = os.environ.get("LEONIDA_HOST_CC") if env: if not os.path.isfile(env): raise Unavailable(f"LEONIDA_HOST_CC={env} does not exist") - return env + return ("msvc" if _is_msvc(env) else "gcc"), env for c in (shutil.which("gcc"), r"C:\msys64\ucrt64\bin\gcc.exe", r"C:\msys64\mingw64\bin\gcc.exe"): if c and os.path.isfile(c): - return c - raise Unavailable("no MinGW gcc for hw_oracle.c (set LEONIDA_HOST_CC)") + return "gcc", c + if os.name == "nt": + # A cl already on PATH (a Developer shell) has its environment; otherwise set it up from vcvars64.bat. + cl = shutil.which("cl") + if cl: + return "msvc", cl + bat = find_vcvars() + if bat: + return "vcvars", bat + raise Unavailable("no C compiler for hw_oracle.c: MinGW gcc or Visual Studio's C++ tools (set LEONIDA_HOST_CC)") + + +def build_command(kind, cc, src, out, workdir): + """argv that compiles src into out; MSVC's objects and the vcvars script go to workdir.""" + if kind == "gcc": + return [cc, "-O1", src, "-o", out] + cl = [cc if kind == "msvc" else "cl", "/nologo", "/O1", src, f"/Fe{out}", f"/Fo{os.path.join(workdir, '')}"] + if kind == "msvc": + return cl + # cmd.exe strips the outer quotes of /c's argument, so the call goes through a script file. + # vcvars64.bat runs vswhere itself, so its folder goes on PATH first (as scripts/build_llvm_mc.ps1 does). + installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), + "Microsoft Visual Studio", "Installer") + script = os.path.join(workdir, "build_hw_oracle.cmd") + with open(script, "w", encoding="ascii") as f: + f.write(f'@echo off\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n' + + subprocess.list2cmdline(cl) + "\r\n") + return ["cmd.exe", "/d", "/c", script] def detect_arch(clang): @@ -124,7 +177,10 @@ class Oracle: self.lld = _find_lld(self.clang) self.dll = find_hip_dll() self.arch = arch or detect_arch(self.clang) - asm.family(self.arch) + try: + asm.family(self.arch) + except ValueError as e: # a GPU the kernels have no spellings for is a skip, like a missing tool + raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None self.chunk = chunk self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") self.exe = self._build_launcher() @@ -137,10 +193,14 @@ class Oracle: tag = hashlib.sha1(f.read()).hexdigest()[:10] exe = os.path.join(tempfile.gettempdir(), f"leonida_hw_oracle_{tag}{'.exe' if os.name == 'nt' else ''}") if not os.path.isfile(exe): - tmp = exe + f".{os.getpid()}" - r = subprocess.run([find_cc(), "-O1", src, "-o", tmp], capture_output=True, text=True) + # cl appends .exe to an /Fe name without one, so the temporary name keeps the extension last + tmp = exe[:-4] + f".{os.getpid()}.exe" if os.name == "nt" else exe + f".{os.getpid()}" + kind, cc = find_cc() + r = subprocess.run(build_command(kind, cc, src, tmp, self.workdir), capture_output=True, text=True, + cwd=self.workdir) if r.returncode: - raise Unavailable("hw_oracle.c did not build: " + r.stderr.strip()[:300]) + # cl reports compile errors on stdout + raise Unavailable("hw_oracle.c did not build: " + (r.stderr.strip() or r.stdout.strip())[:300]) os.replace(tmp, exe) return exe @@ -246,15 +306,28 @@ class Oracle: def open_oracle(**kw): - """An Oracle, or raise Unavailable.""" + """An Oracle for this platform, or raise Unavailable.""" + if sys.platform.startswith("linux"): + try: + from . import drm + except ImportError: # run as a script + import drm + return drm.DrmOracle(**kw) return Oracle(**kw) -if __name__ == "__main__": +def main(): try: - o = Oracle() + o = open_oracle() except Unavailable as e: print(f"hardware oracle unavailable: {e}") - sys.exit(77) + return 77 print(f"hardware oracle ready: {o.device}; clang {o.clang}") o.close() + return 0 + + +if __name__ == "__main__": + # Through the importable module: drm.py imports runner, and both must share one Unavailable and one Oracle. + import runner as _runner + sys.exit(_runner.main()) diff --git a/tools/image_fuzz.py b/tools/image_fuzz.py index 9a531b9b2..acf58fe7e 100644 --- a/tools/image_fuzz.py +++ b/tools/image_fuzz.py @@ -9,7 +9,8 @@ What this covers today: 2D `image_load`, nonzero `dmask` values, `R8G8B8A8_UNORM `R32G32B32A32_SFLOAT` and `R32_SFLOAT`, at sizes that divide the 64x64 draw (8/16/32/64), every texel read at least once. -Integer coverage uses 8-bit UINT/SINT storage views and converts loaded integers to exactly representable floats. +Integer coverage uses 8-bit UINT/SINT sampled images (the translator reads them through uint/sint aliases of the +sampled array) and converts loaded integers to exactly representable floats. Not covered yet: wider integer formats, mips, 1D/2D-array/3D/cube, `image_sample`/`gather` with filters and borders, and texel offsets with `VK_KHR_maintenance8`. @@ -56,7 +57,7 @@ DMASKS = (0xf, *range(1, 0xf)) def assemble(asm: str, name: str, work: str) -> None: """Assemble with llvm-mc like runtime/test/shaders/build.py, into work/disasm/.s.""" cmd = mc_command.mc_command() + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] - r = subprocess.run(cmd, input=asm, capture_output=True, text=True) + r = mc_command.run(cmd, input=asm, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: raise SystemExit(f"llvm-mc rejected {name}:\n{r.stderr}") code = "".join(line for line in r.stdout.splitlines(keepends=True) diff --git a/tools/lds_fuzz.py b/tools/lds_fuzz.py index 224c2f2e7..3b3c55e34 100644 --- a/tools/lds_fuzz.py +++ b/tools/lds_fuzz.py @@ -534,7 +534,7 @@ def translate(progs, work, emulate): cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] if p.wave == 64: cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") - r = subprocess.run(cmd, input=text, capture_output=True, text=True) + r = mc_command.run(cmd, input=text, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) diff --git a/tools/manifest_verifier.py b/tools/manifest_verifier.py index d512b9503..5cafa242c 100644 --- a/tools/manifest_verifier.py +++ b/tools/manifest_verifier.py @@ -63,13 +63,17 @@ def sha256_file(path: str, chunk_size: int = CHUNK) -> str: def walk(target_dir: str, *, exclude: str | None = None): """Yields (relative_path, absolute_path) using forward slashes, excluding the selected manifest.""" + def scan_failed(error: OSError) -> None: + raise error + excluded_dir = excluded_name = None if exclude is not None: directory, name = os.path.split(os.path.abspath(exclude)) excluded_dir = os.path.normcase(os.path.realpath(directory)) excluded_name = os.path.normcase(name) - for root, _, files in os.walk(target_dir): + # os.walk otherwise treats missing or unreadable directories as empty. + for root, _, files in os.walk(target_dir, onerror=scan_failed): contains_manifest = excluded_dir is not None and os.path.normcase(os.path.realpath(root)) == excluded_dir for name in sorted(files): if contains_manifest and os.path.normcase(name) == excluded_name: @@ -102,13 +106,17 @@ def load_manifest(path: str) -> dict[str, dict]: if not isinstance(doc, dict): raise ManifestError(f"{path}: root must be a JSON object") - raw_files = doc.get("files") if "files" in doc and isinstance(doc["files"], dict) else doc - if not isinstance(raw_files, dict): - raise ManifestError(f"{path} has no valid files table") + nested = "files" in doc + if nested: + raw_files = doc["files"] + if not isinstance(raw_files, dict): + raise ManifestError(f"{path}: 'files' must be a JSON object") + else: + raw_files = doc entries: dict[str, dict] = {} for raw_rel, info in raw_files.items(): - if raw_rel in ("created", "title", "version", "note"): + if not nested and raw_rel in ("created", "title", "version", "note"): continue rel = str(raw_rel).replace("\\", "/") if isinstance(info, dict): @@ -116,7 +124,7 @@ def load_manifest(path: str) -> dict[str, dict]: digest = info.get("sha256") if not isinstance(digest, str): raise ManifestError(f"{path}: entry {rel!r} missing 'sha256' string") - if size is not None and not (isinstance(size, int) and size >= 0): + if size is not None and not (isinstance(size, int) and not isinstance(size, bool) and size >= 0): raise ManifestError(f"{path}: entry {rel!r} has invalid integer 'size'") entries[rel] = {"size": size, "sha256": digest.lower()} elif isinstance(info, str): diff --git a/tools/mc_command.py b/tools/mc_command.py index 9c1f14946..2a65cdb43 100644 --- a/tools/mc_command.py +++ b/tools/mc_command.py @@ -5,12 +5,15 @@ needs the command-line form when llvm-mc runs inside WSL, because the official W target: set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc + +run() starts such a command and turns a missing llvm-mc into one line instead of a FileNotFoundError traceback. """ from __future__ import annotations import os import shlex import shutil +import subprocess def split_command(raw: str) -> list: @@ -41,3 +44,20 @@ def mc_command(raw: str | None = None) -> list: if raw is None: raw = os.environ.get("LLVM_MC", "llvm-mc") return split_command(raw) or ["llvm-mc"] + + +def not_found(exe: str, error: OSError, flag: str | None = None) -> str: + """The message for an llvm-mc that can't be started (shader_disasm.py's wording). `flag` is the tool's own + option for the command, if it has one (run_gpu_tests.py's --llvm-mc); the others read LLVM_MC only.""" + where = f"set LLVM_MC (or pass {flag})" if flag else "set LLVM_MC" + return (f"'{exe}' could not be started: {error}. Put llvm-mc on PATH or {where} to it\n" + f"(on Windows, scripts\\build_llvm_mc.ps1 builds one and sets it), e.g.\n" + f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") + + +def run(cmd: list, flag: str | None = None, **kwargs) -> subprocess.CompletedProcess: + """subprocess.run for an llvm-mc command line; one that can't be started ends the tool with not_found().""" + try: + return subprocess.run(cmd, **kwargs) + except OSError as e: + raise SystemExit(not_found(cmd[0], e, flag)) from None diff --git a/tools/mesh_compute_vs.py b/tools/mesh_compute_vs.py index 847106e82..35f26cf39 100644 --- a/tools/mesh_compute_vs.py +++ b/tools/mesh_compute_vs.py @@ -20,6 +20,7 @@ Standard library only; build_for_index assembles and validates with spirv-as / s """ import json import os +import shutil import subprocess import sys @@ -177,27 +178,48 @@ def write_for_index(spirv_dir): return written +def tool_path(name): + """The SPIR-V tool's full path, or RuntimeError naming it: subprocess's own FileNotFoundError says only + "the system cannot find the file specified", which does not say which tool is missing.""" + path = shutil.which(name) + if path is None: + raise RuntimeError(f"{name} not found on PATH (it ships with SPIRV-Tools, e.g. VulkanSDK/Bin)") + return path + + def build_for_index(spirv_dir): """write_for_index, then assemble to .mesh_vs.spv and validate (Vulkan 1.2, as for the translator). Returns the .spv paths; raises RuntimeError with the tool output on failure.""" + steps = [("spirv-as", tool_path("spirv-as")), ("spirv-val", tool_path("spirv-val"))] built = [] for asm in write_for_index(spirv_dir): spv = asm[: -len(".spvasm")] + ".spv" - for cmd in (["spirv-as", "--target-env", "vulkan1.2", asm, "-o", spv], - ["spirv-val", "--target-env", "vulkan1.2", spv]): + for name, tool in steps: + args = [asm, "-o", spv] if name == "spirv-as" else [spv] + cmd = [tool, "--target-env", "vulkan1.2"] + args r = subprocess.run(cmd, capture_output=True, text=True) if r.returncode: - raise RuntimeError(f"{cmd[0]} failed for {asm}:\n{r.stdout}{r.stderr}") + raise RuntimeError(f"{name} failed for {asm}:\n{r.stdout}{r.stderr}") built.append(spv) return built def main(argv): if len(argv) != 2: - sys.exit(__doc__) - for path in build_for_index(argv[1]): + print(__doc__, file=sys.stderr) + return 2 + try: + built = build_for_index(argv[1]) + except RuntimeError as e: + print(f"ERROR: {e}", file=sys.stderr) + return 1 + except OSError as e: + print(f"ERROR: {e.filename or argv[1]}: {e.strerror or e}", file=sys.stderr) + return 1 + for path in built: print(path) + return 0 if __name__ == "__main__": - main(sys.argv) + sys.exit(main(sys.argv)) diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py index 135c8a0b6..82b568899 100644 --- a/tools/navmesh_decode.py +++ b/tools/navmesh_decode.py @@ -905,7 +905,16 @@ def _summary(path, mode, start, end, carver, classes, checks, stats, elapsed): } +def _make_parent(path): + """Create the folder an output path lives in: the scan is over by the time we write, so a missing + folder used to end the run in a FileNotFoundError and lose the result.""" + parent = os.path.dirname(os.path.abspath(path)) + if parent: + os.makedirs(parent, exist_ok=True) + + def write_csv(path, rows): + _make_parent(path) with open(path, "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=COLUMNS, extrasaction="ignore") w.writeheader() @@ -954,12 +963,16 @@ def main(argv=None): out = a.out or os.path.splitext(base)[0] + ".navmesh-decode.json" if a.csv and same_report_path(out, a.csv): ap.error("--out and --csv must use different paths") + for flag, path in (("--out", out), ("--csv", a.csv)): + if path and same_report_path(path, a.input): + ap.error(f"{flag} would overwrite the input {a.input}") rows = [] if a.csv else None try: summary = scan(a.input, a.start, a.limit, a.deep, rows) except ValueError as exc: print("error: %s" % exc, file=sys.stderr) return 2 + _make_parent(out) with open(out, "w", encoding="utf-8") as f: json.dump(summary, f, indent=1, allow_nan=False) if a.csv: diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py index 2f6c8a321..8e99f2ffa 100644 --- a/tools/navmesh_index.py +++ b/tools/navmesh_index.py @@ -22,6 +22,7 @@ Usage: """ import argparse import csv +import fnmatch import glob import json import mmap @@ -232,6 +233,29 @@ def offset(text): return value +def same_report_path(first, second): + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + +def is_scanned_input(path, input_path, pattern): + """True when a report path is one of the files the scan reads: writing it would destroy the input.""" + if same_report_path(path, input_path): + return True + if not os.path.isdir(input_path) or not os.path.isfile(path): + return False + root, target = os.path.abspath(input_path), os.path.abspath(path) + if os.path.dirname(target) != root and not target.startswith(root + os.sep): + return False + pattern = pattern or "*.bin" + return (fnmatch.fnmatch(os.path.relpath(target, root), pattern) + or fnmatch.fnmatch(os.path.basename(target), pattern)) + + def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("input", help="RPF9 archive, or a directory of carved .bin files") @@ -246,6 +270,13 @@ def main() -> int: ap.error("--start and --limit apply to a single archive, not a directory") if not is_dir and a.pattern is not None: ap.error("--pattern applies to a directory, not an archive") + base = os.path.basename(os.path.normpath(a.input)) + out_path = a.out or os.path.splitext(base)[0] + ".navmesh-index.json" + if a.csv and same_report_path(out_path, a.csv): + ap.error("--out and --csv must refer to different files") + for flag, path in (("--out", out_path), ("--csv", a.csv)): + if path and is_scanned_input(path, a.input, a.pattern): + ap.error(f"{flag} would overwrite the input {path}") below_normal() if is_dir: @@ -261,8 +292,6 @@ def main() -> int: rows, summary = scan_archive(a.input, a.start, a.limit) add_distribution(summary, rows) - base = os.path.basename(os.path.normpath(a.input)) - out_path = a.out or os.path.splitext(base)[0] + ".navmesh-index.json" written = write_outputs(rows, summary, out_path, a.csv) print(json.dumps(summary, indent=1)) print(f"wrote {out_path}" + (f", {', '.join(written)}" if written else "")) diff --git a/tools/ps_interp_modes.py b/tools/ps_interp_modes.py new file mode 100644 index 000000000..6addef040 --- /dev/null +++ b/tools/ps_interp_modes.py @@ -0,0 +1,435 @@ +"""Decode pixel-shader interpolation modes from a DXBC container and its FSSM sidecar. + +The translator declares every pixel-shader interpolant as a perspective-centre input +(tools/rdna2spirv.py Gen.attribute; the PS system-input layout comment says the pair is +"the perspective-center one, the only pair this layout models"). Which inputs are +actually centre/centroid/sample and perspective/linear is not in the FSSM header word set: +a scan of every u16 in the first 0x138 bytes of all 12,101 corpus pixel shaders against the +SPI_PS_INPUT_ENA value reconstructed from the DXBC signature finds no matching word (the +only equalities are constants that coincide for the persp-centre-only cohort). The mode +lives in the DXBC container that is carved next to the FSSM: + +PSV0 chunk (writer: dxc lib/DxilContainer/DxilPipelineStateValidation.{h,cpp}, +DxilPSVWriter in lib/DxilContainer/DxilContainerAssembler.cpp): + + u32 runtime-info size, runtime info bytes, + u32 resource count, [u32 bind-info size, bind records], + u32 string-table size, strings, + u32 semantic-index entries, u32 per entry, + u32 signature-element size (16 on the corpus), then input elements, output elements, + each element 16 bytes: + u32 semantic-name offset (0 = system value, no string) + u32 semantic-index offset + u8 rows + u8 start row (register) + u8 cols [3:0], start col [5:4], allocated [6] + u8 semantic kind (DXIL::SemanticKind: 0 Arbitrary, 3 Position, 6 ClipDistance, + 7 CullDistance, 12 SampleIndex, 13 IsFrontFace, 14 Coverage) + u8 component type (DxilProgramSigCompType: 1 UInt32, 3 Float32, 6 Float16) + u8 interpolation mode (DXIL::InterpolationMode, "must match D3D_INTERPOLATION_MODE": + 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, + 5 LinearNoperspectiveCentroid, 6 LinearSample, + 7 LinearNoperspectiveSample) + u8 dynamic mask [3:0] | output stream [5:4] + u8 reserved + +The mode maps onto the barycentric pair the hardware must enable, named by the +SPI_PS_INPUT_ENA/SPI_PS_INPUT_ADDR fields shared by both registers +(Mesa src/amd/registers/gfx103.json, mm 165580/0x286CC and 165584/0x286D0): + + mode 2 Linear -> PERSP_CENTER_ENA (bit 1) + mode 3 LinearCentroid -> PERSP_CENTROID_ENA (bit 2) + mode 6 LinearSample -> PERSP_SAMPLE_ENA (bit 0) + mode 4 LinearNoperspective -> LINEAR_CENTER_ENA (bit 5) + mode 5 LinearNoperspectiveCentroid-> LINEAR_CENTROID_ENA(bit 6) + mode 7 LinearNoperspectiveSample -> LINEAR_SAMPLE_ENA (bit 4) + mode 1 Constant -> none (flat: P0 coefficient) + +D3D forces noperspective on SV_Position, so Position rows carry mode 4 (a few 5) everywhere; +an SV_Position delivered through the parameter cache is interpolated with the *linear* pair, +while one read as a system input arrives in the POS_X/Y/Z/W_FLOAT VGPRs after the barycentric +pair. The FSSM input table itself (tools/fssm_header.py, 8-byte records from 0x138) carries +the read method, not the mode - corpus-wide the record flags agree with the disassembly as +bit 0 (0x01) read through v_interp_mov_f32, bit 1 (0x02) read through 32-bit v_interp_p1/p2, +bit 3 (0x08) 16-bit parameter (Float16 component type), bit 4 (0x10, FLAG_FP16) read through +the *_f16 interpolation opcodes. + +Usage: + python -I ps_interp_modes.py [--json] [--limit N] + +For a directory, one row per pixel shader (stage from index.json) with the PSV0 input +modes, the FSSM table read-method decode and the v_interp usage from a sibling disasm/ +directory, then a census tally. Output is counts and bit layouts only; no game data. +""" + +import argparse +import json +import os +import re +import struct +import sys +from collections import Counter + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import fssm_header # noqa: E402 + +# DXIL::SemanticKind values that reach the shader as system inputs, not parameter-cache +# interpolation (names from dxc include/dxc/DXIL/DxilConstants.h). +SYSTEM_KINDS = {1: "vertex-id", 2: "instance-id", 12: "sample-index", 13: "front-face", + 14: "coverage", 15: "inner-coverage", 25: "barycentrics", 26: "shading-rate"} + +# (kind class, mode) -> (class name, SPI_PS_INPUT_ENA bit). Mode numbers are +# DXIL::InterpolationMode ("must match D3D_INTERPOLATION_MODE"); bit numbers and names are +# Mesa gfx103.json register type SPI_PS_INPUT_ENA. +MODE_CLASS = { + 1: ("flat", 0), + 2: ("persp_center", 1 << 1), + 3: ("persp_centroid", 1 << 2), + 6: ("persp_sample", 1 << 0), + 4: ("linear_center", 1 << 5), + 5: ("linear_centroid", 1 << 6), + 7: ("linear_sample", 1 << 4), +} + +COMPONENT_TYPES = {1: "uint", 2: "sint", 3: "float", 4: "uint16", 5: "sint16", 6: "float16"} + +VINTERP = re.compile(r"v_interp_(p1_f32|p2_f32|mov_f32|p1ll_f16|p1lv_f16|p2_f16)\S*\s+\S+,\s*(\S+)," + r"\s*attr(\d+)\.([xyzw])") + + +def chunk_table(data): + """fourcc -> (offset, size) for a DXBC container, or {} when the header does not parse.""" + if len(data) < 32 or data[:4] != b"DXBC": + return {} + count = struct.unpack_from(" len(data): + return {} + out = {} + for i in range(count): + off = struct.unpack_from(" len(data): + continue + out[data[off:off + 4]] = (off, struct.unpack_from(" len(data): + raise ValueError("PSV0 past end of container") + p = data[off + 8:off + 8 + size] + pos = 4 + struct.unpack_from(" len(p): + raise ValueError("truncated before resource count") + resources = struct.unpack_from(" len(p): + raise ValueError("truncated before bind-info size") + bind = struct.unpack_from(" len(p): + raise ValueError("truncated before string table") + strings = struct.unpack_from(" len(p): + raise ValueError("truncated before semantic-index table") + semantic = struct.unpack_from(" len(p): + raise ValueError("truncated before element size") + esz = struct.unpack_from(" len(p): + raise ValueError("runtime info too short for element counts") + count = p[r1 + 4] + if pos + esz * count > len(p): + raise ValueError("element array past chunk end") + out = [] + for i in range(count): + b = p[pos + i * esz:pos + (i + 1) * esz] + noff = struct.unpack_from(" noff: + name = heap[noff:end].decode("latin-1") + out.append({ + "row": b[9], + "cols": b[10] & 0xF, + "start_col": (b[10] >> 4) & 0x3, + "kind": b[11], + "ctype": b[12], + "mode": b[13], + "name": name, + }) + return out + + +def isg1_elements(data): + """ISG1 elements as dicts (register, mask, rw, name); the repo's 32-byte layout.""" + chunks = chunk_table(data) + if b"ISG1" not in chunks: + return [] + off, size = chunks[b"ISG1"] + p = data[off + 8:off + 8 + size] + if len(p) < 8: + return [] + count, first = struct.unpack_from(" len(p): + break + _, noff, sem_idx, sysv, ctype, reg = struct.unpack_from("<6I", p, base) + name = "" + if 8 <= noff < len(p): + end = p.find(b"\0", noff) + if end > noff: + name = p[noff:end].decode("latin-1") + out.append({"register": reg, "semantic_index": sem_idx, "system_value": sysv, + "component_type": ctype, "mask": p[base + 24], "rw": p[base + 25], + "name": name}) + return out + + +def interp_class(kind, mode): + """(class, SPI_PS_INPUT_ENA bit) of one input row, or ("system", 0) for system inputs.""" + if kind in SYSTEM_KINDS: + return "system", 0 + if mode not in MODE_CLASS: + return "other", 0 + return MODE_CLASS[mode] + + +def read_method(flags): + """FSSM record flags -> the read method the corpus disassembly agrees with.""" + return { + "mov": bool(flags & 0x01), + "p1p2": bool(flags & 0x02), + "param16": bool(flags & 0x08), + "f16_ops": bool(flags & 0x10), + } + + +def disasm_facts(text): + """attr -> set of read kinds, plus the I/J operand set of the non-mov interpolations.""" + per = {} + ij = set() + for line in text.splitlines(): + m = VINTERP.search(line.split(";")[0]) + if not m: + continue + op, src, attr = m.group(1), m.group(2), int(m.group(3)) + kind = "mov" if op == "mov_f32" else ("f16" if op.endswith("_f16") else "p1p2") + per.setdefault(attr, set()).add(kind) + if kind != "mov": + ij.add(src) + return per, ij + + +def pair_class(rows, table, usage, ij): + """The one barycentric pair the code reads, as a class name. + + Every corpus pixel shader that interpolates reads the same single pair (v0/v1, plus one + shader that moves it to v14), so a shader's pair has one class even though + SPI_PS_INPUT_ENA itself is not stored anywhere in the FSSM: + + persp_center - a read arbitrary/clip/cull row with a perspective mode: the pair is + PERSP_CENTER (centroid/sample would need their own pair, and no shader + reads a second pair) + linear_* - SV_Position rows are the only read inputs: the position is interpolated + through the parameter cache with the linear pair (D3D forces + noperspective on SV_Position; mode 5 asks for the centroid variant). + A shader that reads any other row interpolates that row instead and + takes SV_Position from the system VGPRs after the pair. + flat_only - interpolation reads only Constant rows (P0 semantics): any enabled pair + gives the same value + none - no v_interp at all (system inputs only) + """ + read = [r for r in rows if r["rw"]] + persp = [r for r in read if r["kind"] in (0, 6, 7) + and interp_class(r["kind"], r["mode"])[0] in ("persp_center", "persp_centroid", + "persp_sample")] + positions = [r for r in read if r["kind"] == 3] + others = [r for r in read if r["kind"] != 3] + interpolates = any(k - {"mov"} for k in usage.values()) + if interpolates and persp: + return "persp_center" + if interpolates and positions and not others: + # the position rows are the only read inputs, so the interpolation reads them + # through the parameter cache with the linear pair (D3D forces noperspective on + # SV_Position; mode 5 asks for the centroid variant). A shader that also reads + # other rows interpolates those and takes SV_Position from the system VGPRs. + mode = max(r["mode"] for r in positions) + return "linear_centroid" if mode == 5 else "linear_center" + if interpolates: + return "flat_only" + if ij: + return "raw_bary" + return "none" + + +def shader_row(dxbc_path, fssm_path, disasm_path): + """Decode one pixel shader; returns None when the PSV0 chunk is absent/unparsable.""" + with open(dxbc_path, "rb") as f: + data = f.read() + try: + rows = psv0_inputs(data) + except ValueError: + return None + isg = isg1_elements(data) + rw = {e["register"]: e["rw"] for e in isg} + named = {e["register"]: e for e in isg} + for r in rows: + r["rw"] = rw.get(r["row"], 0) + e = named.get(r["row"]) + if e and not r["name"] and e["name"]: + r["name"] = e["name"] + r["class"], r["ena_bit"] = interp_class(r["kind"], r["mode"]) + table = [] + if fssm_path and os.path.isfile(fssm_path): + with open(fssm_path, "rb") as f: + table = fssm_header.pixel_inputs(f.read()) + usage, ij = {}, set() + if disasm_path and os.path.isfile(disasm_path): + with open(disasm_path, encoding="utf-8", errors="replace") as f: + usage, ij = disasm_facts(f.read()) + pair = pair_class(rows, table, usage, ij) + ena = 0 + for r in rows: + ena |= r["ena_bit"] + return { + "name": os.path.splitext(os.path.basename(dxbc_path))[0], + "inputs": [{k: r[k] for k in ("row", "cols", "kind", "ctype", "mode", "rw", "class", + "name")} for r in rows], + "table": [{**read_method(t["flags"]), "mask": t["mask"], "flags": t["flags"]} + for t in table], + "usage": {str(a): sorted(k) for a, k in sorted(usage.items())}, + "ij": sorted(ij), + "pair_class": pair, + "ena_bits": ena, + } + + +def tally(rows): + """Census over per-shader rows: counts only.""" + inputs = [i for r in rows for i in r["inputs"]] + live = [i for i in inputs if i["rw"]] + modes = Counter((i["kind"], i["mode"]) for i in inputs) + live_modes = Counter((i["kind"], i["mode"]) for i in live) + non_pc = [i for i in live if i["class"] in ("persp_centroid", "persp_sample", + "linear_center", "linear_centroid", + "linear_sample")] + method = Counter() + for r in rows: + for t in r["table"]: + method[(t["mov"], t["p1p2"], t["param16"], t["f16_ops"])] += 1 + flag_use = Counter() + for r in rows: + for pos, kinds in r["usage"].items(): + t = r["table"][int(pos)] if int(pos) < len(r["table"]) else None + if t: + flag_use[(t["mov"], t["p1p2"], t["f16_ops"], tuple(kinds))] += 1 + flag_vs_usage = {} + for (mov, p1p2, f16ops, kinds), n in sorted(flag_use.items()): + key = (f"mov={int(mov)} p1p2={int(p1p2)} f16={int(f16ops)}" + f" -> {'+'.join(kinds) or 'unread'}") + flag_vs_usage[key] = flag_vs_usage.get(key, 0) + n + return { + "shaders": len(rows), + "inputs": len(inputs), + "live_inputs": len(live), + "mode_by_kind": {f"kind{k} mode{m}": n for (k, m), n in sorted(modes.items())}, + "live_mode_by_kind": {f"kind{k} mode{m}": n for (k, m), n in sorted(live_modes.items())}, + "live_non_persp_center_inputs": len(non_pc), + "shaders_with_non_persp_center": sum(1 for r in rows + if any(i["class"] in ("persp_centroid", "persp_sample", + "linear_center", "linear_centroid", + "linear_sample") and i["rw"] + for i in r["inputs"])), + "pair_class": dict(Counter(r["pair_class"] for r in rows)), + "ij_sets": {",".join(ij) or "(none)": n + for ij, n in Counter(tuple(r["ij"]) for r in rows).items()}, + "table_records": sum(len(r["table"]) for r in rows), + "table_flags": {f"mov={a} p1p2={b} p16={c} f16={d}": n + for (a, b, c, d), n in sorted(method.items())}, + "flag_vs_usage": flag_vs_usage, + } + + +def files_of(path): + if os.path.isfile(path): + return [path] + return [os.path.join(path, n) for n in sorted(os.listdir(path)) if n.endswith(".dxbc")] + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Decode PS interpolation modes (PSV0 + FSSM + disasm).") + ap.add_argument("path", help="a .dxbc file or a directory of them") + ap.add_argument("--json", action="store_true", help="print one JSON document") + ap.add_argument("--limit", type=int, default=None, help="stop after this many pixel shaders") + args = ap.parse_args(argv) + + if not os.path.exists(args.path): + print(f"ERROR: {args.path} does not exist", file=sys.stderr) + return 2 + base = args.path if os.path.isdir(args.path) else os.path.dirname(args.path) + stages = fssm_header.stage_index(base) + rows = [] + skipped = Counter() + for path in files_of(args.path): + stem = os.path.splitext(os.path.basename(path))[0] + if stages and stages.get(stem) != "ps": + continue + fssm = os.path.join(base, "fssm", stem + ".fssm") + disasm = os.path.join(base, "disasm", stem + ".s") + row = shader_row(path, fssm, disasm) + if row is None: + skipped["no psv0"] += 1 + continue + row["stage"] = stages.get(stem) + rows.append(row) + if args.limit is not None and len(rows) >= args.limit: + break + + if args.json: + json.dump({"files": rows, "tally": tally(rows), "skipped": dict(skipped)}, + sys.stdout, indent=1) + sys.stdout.write("\n") + return 0 + for r in rows: + ins = ", ".join(f"{i['name'] or 'kind' + str(i['kind'])}@{i['row']}" + f":{COMPONENT_TYPES.get(i['ctype'], i['ctype'])}" + f"/mode{i['mode']}{'/rw' if i['rw'] else ''}" for i in r["inputs"]) + print(f"{r['name']}: pair={r['pair_class']} ij={','.join(r['ij']) or '-'}") + if ins: + print(f" inputs: {ins}") + t = tally(rows) + print(f"{t['shaders']} shaders, {t['inputs']} inputs ({t['live_inputs']} read), " + f"{t['table_records']} FSSM records") + print("pair classes:", ", ".join(f"{k}:{v}" for k, v in sorted(t["pair_class"].items()))) + print("I/J operand sets:", ", ".join(f"{k}:{v}" for k, v in sorted(t["ij_sets"].items()))) + print("modes (kind, mode):", ", ".join(f"{k}:{v}" for k, v in sorted(t["mode_by_kind"].items()))) + print("live modes:", ", ".join(f"{k}:{v}" for k, v in sorted(t["live_mode_by_kind"].items()))) + print(f"live non-perspective-centre inputs: {t['live_non_persp_center_inputs']} " + f"in {t['shaders_with_non_persp_center']} shaders") + if skipped: + print("skipped:", ", ".join(f"{k}:{v}" for k, v in skipped.items())) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py index e2657a416..9705117ca 100644 --- a/tools/rbf0_index.py +++ b/tools/rbf0_index.py @@ -502,6 +502,16 @@ def byte_count(text): return value +def same_output_path(first, second): + """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("source", help="an .rpf archive or a directory of carved streams") @@ -512,6 +522,8 @@ def main(): ap.add_argument("--all-strings", action="store_true", help="write every readable string to JSON (game data)") ap.add_argument("--quiet", action="store_true") a = ap.parse_args() + if same_output_path(a.source, a.out): + ap.error("output must not overwrite the source") if a.strings < 0: ap.exit(2, f"{ap.prog}: error: argument --strings: must be 0 or more\n") if os.path.isdir(a.source) and (a.start is not None or a.limit is not None): diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 6f5a34640..6d7fb8cf6 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -138,12 +138,14 @@ class Gen: self.uses_tex_3d = False self.uses_v4uint = False self.uses_store_views = set() # image_store dims used (index into STORE_DIMS) - self.uses_store_reads = False # typed image_load through the uint/sint views + self.uses_int_gather = False # 2D typed sampled-image types for image_gather4_lz(_o) + self.uses_int_fetch = set() # typed image_load dims (index into STORE_DIMS): uint/sint sampled aliases self.writes_depth = False self.uses_smul = False self.uses_minlod = False self.uses_img_offset = False self.uses_pops = False + self.round_mode = False # the program writes MODE.FP_ROUND[3:2] (f16/f64 rounding): kept in %mode_r16 self.uses_fhalf = False # %fhalf_g (0.5) constant self.uses_f64 = False self.uses_bvh = False @@ -156,6 +158,7 @@ class Gen: self.cur_masks = {} self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR self.write_all_lanes = False + self.dpp_guard = None # per-lane bool: a DPP instruction's row/bank/valid write mask self.parked = {} # (vgpr, lane) a mask is parked in -> the spare SGPR slot that keeps it per lane self.uses_lds = False self.lds_dwords = 16384 # CS: set from RSRC2 LDS_SIZE (power of two, covers every offset used) @@ -195,6 +198,8 @@ class Gen: self.fixed_format_codes = set() # static tbuffer/fixed format codes seen (validated against FORMATS) self.frag_inputs = {} # PS: VGPR -> gl_FragCoord component, from the verified system-VGPR layout self.pixel_interpolants = None # PS: (count, fp16_mask) from the FSSM pixel-input table; None = no table + self.v_interp_copy = {} # PS: vgpr -> (root barycentric register v0/v1, program-order index of its + # single defining plain v_mov of it); valid I/J sources (SHADER-177) self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there) self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it @@ -278,6 +283,8 @@ class Gen: elif k == "special" and a["t"] in ("vcc_lo", "vcc"): v = self.tmp() self.emit(f"{v} = OpLoad %uint %vcc") + elif k == "ssa": + v = a["v"] # a value already in SSA form (DPP's shuffled source) else: raise Unsupported(f"operand {a.get('t', k)}") if "sdwa_sel" in a: @@ -443,6 +450,137 @@ class Gen: self.emit(f"{r} = OpBitwiseAnd %uint {v} {self.cu(k)}") return r + def f16_res(self, f): + """f32 ``f`` -> f16 bits (low 16) as a VALU f16 result rounds it: to nearest even (f16_bits), or, when the + program writes MODE.FP_ROUND[3:2], by the current mode in %mode_r16 (0 nearest even, 3 toward zero with + f16_bits(rtz=True); 1 and 2 are refused when the setreg is translated). Shaders that never write the field + get exactly f16_bits. Integer ops only either way (SHADER-56).""" + lo = self.f16_bits(f) + if not self.round_mode: + return lo + z, m, is_z, r = self.f16_bits(f, rtz=True), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{m} = OpLoad %uint %mode_r16") + self.emit(f"{is_z} = OpIEqual %bool {m} {self.cu(3)}") + self.emit(f"{r} = OpSelect %uint {is_z} {z} {lo}") + return r + + def sum_toward_zero(self, x, y, r): + """f32 ``r`` = x + y (nearest even) for an f16 add/sub that will be narrowed by f16_res. Under MODE toward zero + the f32 rounding must not decide the f16 result: x + y = 2 - 2^-24 rounds to 2.0 in f32, but toward zero + it is 0x3FFF in f16. When the exact TwoSum error shows r rounded away from zero, step r one f32 ulp toward + zero: the exact sum then lies strictly between r and the stepped value, with no f16 value between them, + so the toward-zero narrowing gives the exact result. (f16 FMAs don't need this: fma_f16_odd's round-to-odd + f32 value narrows exactly in any direction.) The sums here (f16 operands) never overflow or + reach f32 subnormals. Returns r unchanged when the program never writes MODE.""" + if not self.round_mode: + return r + bb, t1, t2, t3, e = (self.tmp() for _ in range(5)) + self.emit(f"{bb} = OpFSub %float {r} {x}") + self.emit(f"{t1} = OpFSub %float {r} {bb}") + self.emit(f"{t2} = OpFSub %float {x} {t1}") + self.emit(f"{t3} = OpFSub %float {y} {bb}") + self.emit(f"{e} = OpFAdd %float {t2} {t3}") + rp, rn, ep, en, a1, a2, away, m, isz, step = (self.tmp() for _ in range(10)) + self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} %f0") + self.emit(f"{rn} = OpFOrdLessThan %bool {r} %f0") + self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} %f0") + self.emit(f"{en} = OpFOrdLessThan %bool {e} %f0") + self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") + self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") + self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") + self.emit(f"{m} = OpLoad %uint %mode_r16") + self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") + self.emit(f"{step} = OpLogicalAnd %bool {away} {isz}") + u, dec, su = self.tou(r), self.tmp(), self.tmp() + self.emit(f"{dec} = OpISub %uint {u} {self.cu(1)}") + self.emit(f"{su} = OpSelect %uint {step} {dec} {u}") + return self.tof(su) + + def sum_toward_zero2(self, x, y, r): + """sum_toward_zero on each half of v2float operands; returns a v2float.""" + if not self.round_mode: + return r + out = [] + for i in (0, 1): + xi, yi, ri = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{xi} = OpCompositeExtract %float {x} {i}") + self.emit(f"{yi} = OpCompositeExtract %float {y} {i}") + self.emit(f"{ri} = OpCompositeExtract %float {r} {i}") + out.append(self.sum_toward_zero(xi, yi, ri)) + v = self.tmp() + self.emit(f"{v} = OpCompositeConstruct %v2float {out[0]} {out[1]}") + return v + + def f64_add_mode(self, x, y, r, lo, hi): + """v_add_f64 under MODE.FP_ROUND[3:2]: ``r`` = x + y rounded to nearest (bits lo/hi). When the mode is + toward zero (3) and the nearest result rounded away from zero, step one ulp back. The rounding error comes + from TwoSum (exact: every float op is NoContraction): e = (x - (r - (r - x))) + (y - (r - x)); r was + rounded away from zero when e and r have opposite signs. A finite sum that overflowed to inf becomes + +-DBL_MAX. Returns the new (lo, hi).""" + bb, t1, t2, t3, e = (self.tmp() for _ in range(5)) + self.emit(f"{bb} = OpFSub %double {r} {x}") + self.emit(f"{t1} = OpFSub %double {r} {bb}") + self.emit(f"{t2} = OpFSub %double {x} {t1}") + self.emit(f"{t3} = OpFSub %double {y} {bb}") + self.emit(f"{e} = OpFAdd %double {t2} {t3}") + z2, zd = self.tmp(), self.tmp() + self.emit(f"{z2} = OpCompositeConstruct %v2uint_d {self.cu(0)} {self.cu(0)}") + self.emit(f"{zd} = OpBitcast %double {z2}") + en, rp, ep, rn, a1, a2, away = (self.tmp() for _ in range(7)) + self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} {zd}") + self.emit(f"{rn} = OpFOrdLessThan %bool {r} {zd}") + self.emit(f"{en} = OpFOrdLessThan %bool {e} {zd}") + self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} {zd}") + self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") + self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") + self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") + # overflow: r is inf while x and y are finite + ri, xi, yi, xn, yn, xs, ys, xf, of = (self.tmp() for _ in range(9)) + self.emit(f"{ri} = OpIsInf %bool {r}") + self.emit(f"{xi} = OpIsInf %bool {x}") + self.emit(f"{yi} = OpIsInf %bool {y}") + self.emit(f"{xn} = OpIsNan %bool {x}") + self.emit(f"{yn} = OpIsNan %bool {y}") + self.emit(f"{xs} = OpLogicalOr %bool {xi} {xn}") + self.emit(f"{ys} = OpLogicalOr %bool {yi} {yn}") + self.emit(f"{xf} = OpLogicalOr %bool {xs} {ys}") + nf = self.tmp() + self.emit(f"{nf} = OpLogicalNot %bool {xf}") + self.emit(f"{of} = OpLogicalAnd %bool {ri} {nf}") + step, any_, m, isz = (self.tmp() for _ in range(4)) + self.emit(f"{any_} = OpLogicalOr %bool {away} {of}") + self.emit(f"{m} = OpLoad %uint %mode_r16") + self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") + self.emit(f"{step} = OpLogicalAnd %bool {any_} {isz}") + # one ulp toward zero on the magnitude bits: (hi:lo) - 1 (inf - 1 = DBL_MAX) + nlo, bor, bu, nhi, rlo, rhi = (self.tmp() for _ in range(6)) + self.emit(f"{nlo} = OpISub %uint {lo} {self.cu(1)}") + self.emit(f"{bor} = OpIEqual %bool {lo} {self.cu(0)}") + self.emit(f"{bu} = OpSelect %uint {bor} {self.cu(1)} {self.cu(0)}") + self.emit(f"{nhi} = OpISub %uint {hi} {bu}") + self.emit(f"{rlo} = OpSelect %uint {step} {nlo} {lo}") + self.emit(f"{rhi} = OpSelect %uint {step} {nhi} {hi}") + return rlo, rhi + + def mode_write(self, op, a): + """s_setreg* on HW_REG_MODE. Only FP_ROUND[3:2] (f16/f64 rounding) is modelled, the one MODE field the + corpus writes (9,417 writes: value 3 = toward zero 6,694, value 0 = nearest even 2,723). A write that + reaches another MODE bit or only part of the field, sets directed rounding (+inf/-inf), or takes its value + from an SGPR is refused, so nothing changes silently. Other hardware registers (FLAT_SCR, POPS packer) are not MODE: ignored.""" + t = a[0].get("t", "") if a and a[0]["k"] == "special" else "" + m = re.match(r"hwreg\((\w+)(?:,\s*(\d+),\s*(\d+))?\)", t) + if not m or m.group(1) != "HW_REG_MODE": + return + off, size = (int(m.group(2)), int(m.group(3))) if m.group(2) else (0, 32) + if (off, size) != (2, 2): + raise Unsupported(f"{op} on MODE bits {off}..{off + size - 1} (only FP_ROUND[3:2] as a whole is modelled)") + if op != "s_setreg_imm32_b32" or a[1]["k"] != "imm": + raise Unsupported(f"{op} with a register value on MODE.FP_ROUND") + new = a[1]["v"] & 3 + if new in (1, 2): + raise Unsupported("MODE.FP_ROUND[3:2] directed rounding (+inf/-inf)") + self.emit(f"OpStore %mode_r16 {self.cu(new)}") + def emit_ne0(self, v): r = self.tmp() self.emit(f"{r} = OpINotEqual %bool {v} {self.cu(0)}") @@ -485,24 +623,106 @@ class Gen: self.emit(f"{r} = OpBitcast %float {res}") return r + def fma_mix_odd(self, x, y, z): + """fma(x, y, z) for f32 operands rounded to f32 with round-to-odd, so that narrowing it to f16 in any direction + gives the exactly rounded f16 (the hardware rounds v_fma_mix once, straight to f16, under MODE toward zero). + Unlike fma_f16_odd the product is not exact in f32: r = Fma (nearest) is corrected by the sign of + exact - r = (s - r) + (se + pe), where p = x*y, pe = Fma(x, y, -p) is the exact product error, s = p + z and se + the TwoSum error of that sum. When that is non-zero and r is even, r moves one f32 ulp towards it (the exact + value lies between r and its neighbour, so the neighbour is the odd one). A zero, infinite or NaN r is + left alone (an f32 subnormal narrows to +-0 either way), except that a finite exact value whose f32 Fma + overflowed to +-inf becomes +-FLT_MAX (toward zero it is 65504 in f16). A tiny product takes the residual + sign from its operands (below). Sign-exact except where se + pe itself rounds to the opposite side of + s - r, which needs an f32-ulp-level cancellation, or where x*y overflows while z cancels it.""" + t = self.tmp + r, p, np_, pe, s_, bb, sb, da, db, se = (t() for _ in range(10)) + self.emit(f"{r} = OpExtInst %float %glsl Fma {x} {y} {z}") + self.emit(f"{p} = OpFMul %float {x} {y}") + self.emit(f"{np_} = OpFNegate %float {p}") + self.emit(f"{pe} = OpExtInst %float %glsl Fma {x} {y} {np_}") + self.emit(f"{s_} = OpFAdd %float {p} {z}") + self.emit(f"{bb} = OpFSub %float {s_} {p}") + self.emit(f"{sb} = OpFSub %float {s_} {bb}") + self.emit(f"{da} = OpFSub %float {p} {sb}") + self.emit(f"{db} = OpFSub %float {z} {bb}") + self.emit(f"{se} = OpFAdd %float {da} {db}") + tt, d0, res = t(), t(), t() + self.emit(f"{tt} = OpFAdd %float {se} {pe}") + self.emit(f"{d0} = OpFSub %float {s_} {r}") + self.emit(f"{res} = OpFAdd %float {d0} {tt}") + rbits, mag, lsb, even, nzr, ok, need = (t() for _ in range(7)) + self.emit(f"{rbits} = OpBitcast %uint {r}") + self.emit(f"{mag} = OpBitwiseAnd %uint {rbits} {self.cu(0x7FFFFFFF)}") + self.emit(f"{lsb} = OpBitwiseAnd %uint {rbits} {self.cu(1)}") + self.emit(f"{even} = OpIEqual %bool {lsb} {self.cu(0)}") + self.emit(f"{nzr} = OpULessThan %bool {self.cu(0)} {mag}") + self.emit(f"{ok} = OpULessThan %bool {mag} {self.cu(0x7F800000)}") # finite + rnz, rfin = t(), t() + self.emit(f"{rnz} = OpFUnordNotEqual %bool {res} %f0") # true for a NaN residual too... + self.emit(f"{rfin} = OpFOrdEqual %bool {res} {res}") # ...so require a non-NaN one + inexact = self.emit_land(rnz, rfin) + # A tiny product (|x*y| < 2^-64, or flushed to 0) has its error pe below the f32 normal range (pe's lowest bit is + # 2^-47 of p's), so pe and the residual can underflow or be flushed and read as exact. z dominates there + # (anything the f16 result can see has an f32 ulp far above 2^-64), so the residual's sign is the + # product's: sign(x) xor sign(y), whatever the driver does with denormals. + xb, yb, pb, pmag, ptiny, xnz, ynz, tiny, tsign, ebits0 = (t() for _ in range(10)) + self.emit(f"{pb} = OpBitcast %uint {p}") + self.emit(f"{pmag} = OpBitwiseAnd %uint {pb} {self.cu(0x7FFFFFFF)}") + self.emit(f"{ptiny} = OpULessThan %bool {pmag} {self.cu(0x1F800000)}") + self.emit(f"{xnz} = OpFUnordNotEqual %bool {x} %f0") + self.emit(f"{ynz} = OpFUnordNotEqual %bool {y} %f0") + self.emit(f"{tiny} = OpLogicalAnd %bool {ptiny} {self.emit_land(xnz, ynz)}") + self.emit(f"{xb} = OpBitcast %uint {x}") + self.emit(f"{yb} = OpBitcast %uint {y}") + self.emit(f"{tsign} = OpBitwiseXor %uint {xb} {yb}") + inexact2, ebits = t(), t() + self.emit(f"{inexact2} = OpLogicalOr %bool {inexact} {tiny}") + self.emit(f"{need} = OpLogicalAnd %bool {self.emit_land(even, inexact2)} {self.emit_land(nzr, ok)}") + self.emit(f"{ebits0} = OpBitcast %uint {res}") + self.emit(f"{ebits} = OpSelect %uint {tiny} {tsign} {ebits0}") + xs, same, up, dn, adj, out, rr = (t() for _ in range(7)) + self.emit(f"{xs} = OpBitwiseXor %uint {rbits} {ebits}") + self.emit(f"{same} = OpULessThan %bool {xs} {self.cu(0x80000000)}") # same sign: away from zero + self.emit(f"{up} = OpIAdd %uint {rbits} {self.cu(1)}") + self.emit(f"{dn} = OpISub %uint {rbits} {self.cu(1)}") + self.emit(f"{adj} = OpSelect %uint {same} {up} {dn}") + self.emit(f"{out} = OpSelect %uint {need} {adj} {rbits}") + self.emit(f"{rr} = OpBitcast %float {out}") + # Fma overflowed to +-inf with finite operands: the exact value is finite, so toward zero it is +-FLT_MAX. + ri, xi, yi, zi, anyi, ovf, sg, mx, fin, rfl = (t() for _ in range(10)) + self.emit(f"{ri} = OpIsInf %bool {r}") + self.emit(f"{xi} = OpIsInf %bool {x}") + self.emit(f"{yi} = OpIsInf %bool {y}") + self.emit(f"{zi} = OpIsInf %bool {z}") + xyi, nai = t(), t() + self.emit(f"{xyi} = OpLogicalOr %bool {xi} {yi}") + self.emit(f"{anyi} = OpLogicalOr %bool {xyi} {zi}") + self.emit(f"{nai} = OpLogicalNot %bool {anyi}") + self.emit(f"{ovf} = OpLogicalAnd %bool {ri} {nai}") + self.emit(f"{sg} = OpBitwiseAnd %uint {rbits} {self.cu(0x80000000)}") + self.emit(f"{mx} = OpBitwiseOr %uint {sg} {self.cu(0x7F7FFFFF)}") + self.emit(f"{fin} = OpSelect %uint {ovf} {mx} {out}") + self.emit(f"{rfl} = OpBitcast %float {fin}") + return rfl + def emit_land(self, a, b): r = self.tmp() self.emit(f"{r} = OpLogicalAnd %bool {a} {b}") return r def f16_pack2(self, lo, hi): - """Two f32 values -> one %uint of two RTE f16 halves (lo | hi << 16), without PackHalf2x16.""" - a, b, sh, r = self.f16_bits(lo), self.f16_bits(hi), self.tmp(), self.tmp() + """Two f32 values -> one %uint of two f16 halves (lo | hi << 16), each rounded as f16_res, without PackHalf2x16.""" + a, b, sh, r = self.f16_res(lo), self.f16_res(hi), self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {b} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {a} {sh}") return r - def f16_out(self, d, r, hi=0, fract=False): - """Narrow f32 ``r`` to f16 (round to nearest even, f16_bits) and write it to the low half of ``d``, or to the high half when + def f16_out(self, d, r, hi=0, fract=False, mode=True): + """Narrow f32 ``r`` to f16 (f16_res: nearest even, or toward zero under MODE) and write it to the low half of ``d``, or to the high half when ``hi`` (op_sel destination bit). Either way the other half is kept (see write_lo16). ``fract`` (v_fract_f16): a result that rounded up to 1.0 (0x3c00) becomes 0x3bff, the largest f16 below 1, as on hardware (docs/design.md, float min/max/med3 with NaN and v_fract).""" - lo = self.f16_bits(r) + lo = self.f16_res(r) if mode else self.f16_bits(r) # mode=False: the op ignores MODE rounding (rcp/rsq/sqrt) if fract: one, below = self.tmp(), self.tmp() self.emit(f"{one} = OpIEqual %bool {lo} {self.cu(0x3C00)}") @@ -609,13 +829,22 @@ class Gen: self.emit(f"{old} = OpLoad %uint {p}") if eager: mask = self.exec_value() + if self.dpp_guard is not None: + guarded = self.tmp() + self.emit(f"{guarded} = OpSelect %uint {self.dpp_guard} {mask} {self.cu(0)}") + mask = guarded keep, write, preserve = self.tmp(), self.tmp(), self.tmp() self.emit(f"{keep} = OpNot %uint {mask}") self.emit(f"{write} = OpBitwiseAnd %uint {val} {mask}") self.emit(f"{preserve} = OpBitwiseAnd %uint {old} {keep}") self.emit(f"{r} = OpBitwiseOr %uint {write} {preserve}") else: - self.emit(f"{r} = OpSelect %uint {self.active_b()} {val} {old}") + active = self.active_b() + if self.dpp_guard is not None: + guarded = self.tmp() + self.emit(f"{guarded} = OpLogicalAnd %bool {active} {self.dpp_guard}") + active = guarded + self.emit(f"{r} = OpSelect %uint {active} {val} {old}") self.emit(f"OpStore {p} {r}") elif a["k"] == "sgpr" and a.get("n", 1) == 1: self.store_reg(a["k"], a["r"], val) @@ -663,7 +892,7 @@ class Gen: self.store_reg("sgpr", d["r"], lo) self.store_reg("sgpr", d["r"] + 1, hi) - def compare(self, op, a, scalar, exec_only=False): + def compare(self, op, a, scalar, exec_only=False, mods=()): """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx).""" parts = op.split("_") # v_cmp_lt_f32 / s_cmp_eq_u32 cond, ty = parts[2], parts[3] @@ -672,25 +901,20 @@ class Gen: if ty in ("f32", "f16"): if ty == "f32": x, y = self.src_f(srcs[0]), self.src_f(srcs[1]) - else: # f16 compare: the low half of each source, compared as f32 (exact for f16 values) - vals = [] - for s in srcs: - u = self.src_h(s) - v2, f = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - self.emit(f"{f} = OpCompositeExtract %float {v2} 0") - vals.append(self.modify_f(f, s)) - x, y = vals + else: # f16 compare: op_sel selects lo/hi half of each source, compared as f32 (exact for f16 values) + sel, _ = self.opsel_bits(mods, 2) + x, y = self.f16_in(srcs[0], sel[0]), self.f16_in(srcs[1], sel[1]) ops = {"lt": "OpFOrdLessThan", "le": "OpFOrdLessThanEqual", "gt": "OpFOrdGreaterThan", "ge": "OpFOrdGreaterThanEqual", "eq": "OpFOrdEqual", "neq": "OpFUnordNotEqual", "lg": "OpFOrdNotEqual", "nlg": "OpFUnordEqual", "nlt": "OpFUnordGreaterThanEqual", "ngt": "OpFUnordLessThanEqual", "nle": "OpFUnordGreaterThan", "nge": "OpFUnordLessThan"} elif ty in ("u16", "i16"): + sel, _ = self.opsel_bits(mods, 2) x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) xs, ys = self.tmp(), self.tmp() f = "OpBitFieldSExtract" if ty == "i16" else "OpBitFieldUExtract" - self.emit(f"{xs} = {f} %uint {x} {self.cu(0)} {self.cu(16)}") - self.emit(f"{ys} = {f} %uint {y} {self.cu(0)} {self.cu(16)}") + self.emit(f"{xs} = {f} %uint {x} {self.cu(16 if sel[0] else 0)} {self.cu(16)}") + self.emit(f"{ys} = {f} %uint {y} {self.cu(16 if sel[1] else 0)} {self.cu(16)}") x, y = xs, ys if ty == "i16": x, y = self.as_int(x), self.as_int(y) @@ -794,11 +1018,11 @@ class Gen: else: raise Unsupported("v_cmp destination") - def compare_x(self, op, a): + def compare_x(self, op, a, mods=()): """v_cmpx_*: like v_cmp but the result ANDs into EXEC. e32 form has only the two sources; e64 also names a destination (vcc/sgpr) which gets the compare result too.""" srcs = a[-2:] - self.compare("v_cmp_" + op[len("v_cmpx_"):], [None] + list(srcs), scalar=False, exec_only=True) + self.compare("v_cmp_" + op[len("v_cmpx_"):], [None] + list(srcs), scalar=False, exec_only=True, mods=mods) def bitcmp(self, op, a): """s_bitcmp0/1_b32/b64: test if bit (a[1]) of scalar a[0] is 0 or 1, result in SCC.""" @@ -1356,14 +1580,23 @@ class Gen: self.emit(f"{o} = OpLogicalOr %bool {is_int} {e}") is_int = o for i in range(0, len(outs), 2): - lo, hi = outs[i], (outs[i + 1] if i + 1 < len(outs) else self.cu(0)) - ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi)) # a memory d16 result, see there - il, ih, pi, r = (self.tmp() for _ in range(4)) + dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} + lo = outs[i] + il, r = self.tmp(), self.tmp() self.emit(f"{il} = OpBitwiseAnd %uint {lo} {self.cu(0xFFFF)}") + if i + 1 == len(outs): + # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. + fl = self.f16_bits(self.tof(lo)) + self.emit(f"{r} = OpSelect %uint {is_int} {il} {fl}") + self.write_lo16(dest, r) + continue + hi = outs[i + 1] + ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi)) + ih, pi = self.tmp(), self.tmp() self.emit(f"{ih} = OpShiftLeftLogical %uint {hi} {self.cu(16)}") self.emit(f"{pi} = OpBitwiseOr %uint {il} {ih}") self.emit(f"{r} = OpSelect %uint {is_int} {pi} {ph}") - self.dst({"k": "vgpr", "r": vd["r"] + i // 2, "n": 1}, r) + self.dst(dest, r) def global_mem(self, op, a, mods): """global_load_dword[xN] vD, vaddr, saddr|off offset:N / global_store_dword[xN] vaddr, vD, saddr|off. @@ -1700,6 +1933,14 @@ class Gen: # Every format in FORMATS (the same table the loads decode); unknown formats store nothing. fc = comps + [self.cu(0)] * (4 - len(comps)) ic = icomps + [self.cu(0)] * (4 - len(icomps)) + # Normalized stores map either sign of NaN to zero before clamping. + # Compute this once per source component; float and integer formats use the original bits. + normalized = [] + for component, float_value in zip(comps, fl): + nan, value = self.tmp(), self.tmp() + self.emit(f"{nan} = OpIsNan %bool {float_value}") + self.emit(f"{value} = OpSelect %uint {nan} {self.cu(0)} {component}") + normalized.append(value) for code, (size, kind, widths) in self.FORMATS.items(): e = self.tmp() self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") @@ -1708,7 +1949,8 @@ class Gen: self.emit(f"OpBranchConditional {e} {ld} {le}") self.emit(f"{ld} = OpLabel") ncomp = min(len(widths), n) - fcs = fc[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) + source = normalized if kind in ("unorm", "snorm") else fc + fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) ics = ic[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) if size >= 4: @@ -1961,6 +2203,13 @@ class Gen: self.emit(f"{li} = OpIAdd %uint {lx} {t2}") return li + def subgroup_lane(self): + """This invocation's lane within its Vulkan subgroup (0..31 or 0..63).""" + self.uses_subgroup = True + r = self.tmp() + self.emit(f"{r} = OpLoad %uint %sg_lane") + return r + def wave_lane(self): """This invocation's hardware lane within its wave. Compute and mesh shaders: LocalInvocationIndex mod the wave size (exact: thread i of a group is wave i / W, lane i % W). Other stages: the subgroup lane, which is @@ -2634,6 +2883,24 @@ class Gen: return g return v + def turn_angle(self, x): + """Reduce a turn count to [-0.5, 0.5) before scaling by 2*pi. + + RDNA's v_sin/v_cos take turns and range-reduce in turns. Scaling first loses the fractional part for large + inputs (one f32 ulp at 255 turns is ~1.2e-4 rad) and leaves Sin outside the [-pi, pi] range where Vulkan + guarantees its precision. Fract first; keep -0 as -0 so Sin's sign survives. NaN and infinity stay NaN + through Fract/compare/select. + """ + frac, gt, adj, sel, zero, t, arg = (self.tmp() for _ in range(7)) + self.emit(f"{frac} = OpExtInst %float %glsl Fract {x}") + self.emit(f"{gt} = OpFOrdGreaterThan %bool {frac} {self.fconst(0.5)}") + self.emit(f"{adj} = OpFSub %float {frac} {self.fconst(1.0)}") + self.emit(f"{sel} = OpSelect %float {gt} {adj} {frac}") + self.emit(f"{zero} = OpFOrdEqual %bool {x} {self.fconst(0.0)}") + self.emit(f"{t} = OpSelect %float {zero} {x} {sel}") + self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}") + return arg + def fconst(self, x): bits = struct.unpack("= GFX10). x = self.src_f(a[1]) - self.write_lo16(a[0], self.f16_bits(x)) + self.write_lo16(a[0], self.f16_res(x)) elif op == "s_mulk_i32": v = a[1]["v"] & 0xFFFF k = v - 0x10000 if v & 0x8000 else v @@ -2877,14 +3399,14 @@ class Gen: self.image_op(op, a, mods) elif op in ("v_sin_f16", "v_cos_f16"): u = self.src_h(a[1]) - v2, f, t, r, w2, pk, lo = (self.tmp() for _ in range(7)) + v2, f, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") self.emit(f"{f} = OpCompositeExtract %float {v2} 0") f = self.modify_f(f, a[1]) - self.emit(f"{t} = OpFMul %float {f} {self.fconst(6.283185307179586)}") + t = self.turn_angle(f) self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") r = self.clamp_mods(r, mods) - self.write_lo16(a[0], self.f16_bits(r)) + self.write_lo16(a[0], self.f16_bits(r)) # sin ignores MODE rounding on hardware (RX 6800, SHADER-35); cos is unmeasured, assumed like it elif op in ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16"): # Packed 16-bit shifts (VOP3P): result half h = src1 half (op_sel / op_sel_hi) shifted by src0 half & 15. def bits(name, default): @@ -2908,10 +3430,10 @@ class Gen: self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) elif op in ("v_sin_f32", "v_cos_f32"): - # RDNA takes the angle in turns: sin(x * 2*pi). + # RDNA takes the angle in turns: reduce in turns, then sin/cos(x * 2*pi). x = self.src_f(a[1]) - t, r = self.tmp(), self.tmp() - self.emit(f"{t} = OpFMul %float {x} {self.fconst(6.283185307179586)}") + t = self.turn_angle(x) + r = self.tmp() self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op == "v_rndne_f32": @@ -3278,6 +3800,16 @@ class Gen: x, y = f64(a[1]), f64(a[2]) r, v2, lo, hi = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{r} = OpFAdd %double {x} {y}") + if self.round_mode: + # MODE rounds the sum itself; clamp/omod then apply to the rounded value, as on the hardware. + m2, mlo, mhi, n2, rd = (self.tmp() for _ in range(5)) + self.emit(f"{m2} = OpBitcast %v2uint_d {r}") + self.emit(f"{mlo} = OpCompositeExtract %uint {m2} 0") + self.emit(f"{mhi} = OpCompositeExtract %uint {m2} 1") + mlo, mhi = self.f64_add_mode(x, y, r, mlo, mhi) + self.emit(f"{n2} = OpCompositeConstruct %v2uint_d {mlo} {mhi}") + self.emit(f"{rd} = OpBitcast %double {n2}") + r = rd # VOP3_Profile: HasClamp and HasOMod (LLVM VOPProfile, f64 is a modifier type). r = self.clamp_mods_f64(r, mods) self.emit(f"{v2} = OpBitcast %v2uint_d {r}") @@ -3461,7 +3993,8 @@ class Gen: "buffer_load_format_d16_xyz", "buffer_load_format_d16_xyzw"): self.buffer_load_format(op, a, mods) elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", - "tbuffer_load_format_xyzw"): + "tbuffer_load_format_xyzw", "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy", + "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw"): # MTBUF encodes its own format. LLVM omits the modifier for GFX10's default, BUF_FMT_8_UNORM. fm = next((m for m in mods if m.startswith("format:")), "format:[BUF_FMT_8_UNORM]") name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]") @@ -3854,6 +4387,8 @@ class Gen: self.emit(f"{r} = OpCompositeConstruct %v2float {comps[0]} {comps[1]}") elif op in ("v_pk_add_f16", "v_pk_mul_f16"): self.emit(f"{r} = {'OpFAdd' if 'add' in op else 'OpFMul'} %v2float {vx} {vy}") + if "add" in op: + r = self.sum_toward_zero2(vx, vy, r) else: self.emit(f"{r} = OpExtInst %v2float %glsl {'NMax' if 'max' in op else 'NMin'} {vx} {vy}") if "clamp" in mods: @@ -4086,7 +4621,10 @@ class Gen: r = self.clamp_mods(r, mods) # 0x3c00 -> 0x3bff only when 0x3c00 is Fract's own rounding: after mul:2 fract(0.5) is a true 1.0. omod = any(m in ("mul:2", "mul:4", "div:2") for m in mods) - self.f16_out(a[0], r, dhi, fract=fn == "Fract" and not omod) # GFX10: f16 ops keep the other half + # rcp/rsq/sqrt (and sin below) ignore MODE rounding on hardware (RX 6800, SHADER-35); exp, log (and cos + # below) are unmeasured, assumed like them: nearest even always. + self.f16_out(a[0], r, dhi, fract=fn == "Fract" and not omod, + mode=op not in ("v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_exp_f16", "v_log_f16")) # GFX10: f16 ops keep the other half elif op == "v_not_b32": x = self.src_u(a[1]) r = self.tmp() @@ -4111,6 +4649,12 @@ class Gen: k = {"v_add_f16": "OpFAdd", "v_sub_f16": "OpFSub", "v_subrev_f16": "OpFSub", "v_mul_f16": "OpFMul"}.get(op) if k: self.emit(f"{r} = {k} %float {vals[0]} {vals[1]}") + if k == "OpFAdd": + r = self.sum_toward_zero(vals[0], vals[1], r) + elif k == "OpFSub" and self.round_mode: + ny = self.tmp() + self.emit(f"{ny} = OpFNegate %float {vals[1]}") + r = self.sum_toward_zero(vals[0], ny, r) else: self.emit(f"{r} = OpExtInst %float %glsl {'NMax' if 'max' in op else 'NMin'} {vals[0]} {vals[1]}") r = self.clamp_mods(r, mods) @@ -4471,6 +5015,13 @@ class Gen: attr = next((x for x in a if x["k"] == "attr"), None) if attr is None or self.stage != "ps": raise Unsupported(op + " form") + if op == "v_interp_mov_f32": + sel = a[1] if len(a) > 1 else None + if not (sel and sel.get("k") == "interp" and sel.get("t") == "p0"): + what = sel.get("t") if sel is not None and sel.get("k") == "interp" else "operand" + raise Unsupported(f"v_interp_mov_f32 vertex select {what}: only p0 is modelled") + else: + self.interp_pair_src(op, a, ins) f = self.attribute(attr["a"], attr["c"], flat=op == "v_interp_mov_f32") if self.pixel_interpolants is not None and (self.pixel_interpolants[1] >> attr["a"]) & 1: # 16-bit interpolant (FSSM table flag bit 4) read through a 32-bit op: the stored value only @@ -4500,9 +5051,9 @@ class Gen: self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {x} {old}") self.dst(a[0], r) elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class") and not op.endswith(("_u64", "_i64")): - self.compare(op, a, scalar=False) + self.compare(op, a, scalar=False, mods=mods) elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class") and not op.endswith(("_u64", "_i64")): - self.compare_x(op, a) + self.compare_x(op, a, mods=mods) elif op in ("s_and_saveexec_b64", "s_or_saveexec_b64", "s_andn2_saveexec_b64", "s_and_saveexec_b32", "s_or_saveexec_b32", "s_andn2_saveexec_b32"): saved = self.exec_value() @@ -4702,14 +5253,15 @@ class Gen: attr = next((x for x in a if x["k"] == "attr"), None) if attr is None or self.stage != "ps": raise Unsupported(op + " form") + self.interp_pair_src(op, a, ins) # `high` (on both ops of the pair) selects the upper f16 of the packed channel (Mesa ACO - # emit_interp_instr passes high_16bits to p1ll and p2). Under --bary-fallback there are no per-vertex + # emit-interp_instr passes high_16bits to p1ll and p2). Under --bary-fallback there are no per-vertex # inputs, so the old smooth-f32 read stands and `high` cannot be told apart (docs/design.md). f = self.attribute(attr["a"], attr["c"], half=1 if "high" in mods else 0) if op == "v_interp_p2_f16": # VOP3 clamp applies to the f16 result (ACO: dst(F16); llvm-mc takes clamp but no omod on this op). # Until 2026-11-22 it was dropped. - self.dst(a[0], self.f16_bits(self.clamp_mods(f, mods))) + self.dst(a[0], self.f16_res(self.clamp_mods(f, mods))) else: # p1ll/p1lv produce the f32 intermediate consumed by p2_f16 self.dst(a[0], self.tou(f)) elif op.startswith("s_cmp_"): @@ -4752,6 +5304,14 @@ class Gen: vals = self.fma_mix_srcs(a, mods) r = self.tmp() self.emit(f"{r} = OpExtInst %float %glsl Fma {vals[0]} {vals[1]} {vals[2]}") + if self.round_mode: + # Toward zero the hardware rounds the exact fma once, to f16; round-to-odd at f32 narrows exactly. + # Nearest even keeps the f32 Fma then narrow (unchanged). + ro, m, isz, rs = self.fma_mix_odd(*vals), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{m} = OpLoad %uint %mode_r16") + self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") + self.emit(f"{rs} = OpSelect %float {isz} {ro} {r}") + r = rs r = self.clamp_mods(r, mods) self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) elif op == "v_cvt_pk_u8_f32": @@ -5519,7 +6079,8 @@ class Gen: iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if ncoord == 2 else '%v3int'} {' '.join(ints)}") if dim in self.STORE_DIMS: - self.image_load_typed(dim, self.load_reg("sgpr", a[2]["r"] + 1), iv, img, img_idx, dmask, vdata, d16) + self.image_load_typed(dim, self.load_reg("sgpr", a[2]["r"] + 1), iv, img, img_idx, + dmask, vdata, self.cu(0), d16) return res = self.tmp() self.emit(f"{res} = OpImageFetch %v4float {img} {iv} Lod {self.cu(0)}") @@ -5529,7 +6090,8 @@ class Gen: sp, smp, si = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sp} = OpAccessChain %_ptr_UC_smp %samplers {smp_idx}") self.emit(f"{smp} = OpLoad %smp {sp}") - self.emit(f"{si} = OpSampledImage %{stype} {img} {smp}") + if op not in ("image_gather4_lz", "image_gather4_lz_o"): + self.emit(f"{si} = OpSampledImage %{stype} {img} {smp}") f = [self.tof(c) for c in coords] goff = None if op in ("image_gather4_lz_o", "image_gather4_l_o"): @@ -5611,13 +6173,29 @@ class Gen: raise Unsupported("image_gather4_lz form") if dim == "dim:SQ_RSRC_IMG_CUBE": f = self.cube_coords(f) - uv, res = self.tmp(), self.tmp() + uv = self.tmp() if ncoord == 3: # 2D array (or cube as a 6-layer array): layer is the 3rd coordinate self.emit(f"{uv} = OpCompositeConstruct %v3float {f[0]} {f[1]} {f[2]}") else: self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") - self.emit(f"{res} = OpImageGather %v4float {si} {uv} {self.cu(dmask.bit_length() - 1)}" - + (f" Offset {goff}" if goff is not None else "")) + component = self.cu(dmask.bit_length() - 1) + offset = f" Offset {goff}" if goff is not None else "" + + def gather(image, cls, ty): + sampled = self.tmp() + sampler_type = f"itxsamp{cls}_0" if cls else stype + self.emit(f"{sampled} = OpSampledImage %{sampler_type} {image} {smp}") + res = self.tmp() + self.emit(f"{res} = OpImageGather {ty} {sampled} {uv} {component}{offset}") + return res + + if dim == "dim:SQ_RSRC_IMG_2D": + self.uses_int_gather = True + # dmask selects one texture channel; all four taps are written. + self.image_read_typed(dim, self.load_reg("sgpr", a[2]["r"] + 1), img, img_idx, + 0xf, vdata, d16, gather) + return + res = gather(img, 0, "%v4float") comps = [] for c in range(4): comp = self.tmp() @@ -5766,6 +6344,9 @@ class Gen: # class 0 = float, 1 = uint, 2 = sint (Vulkan needs the shader's component type to match the image format). STORE_DIMS = {"dim:SQ_RSRC_IMG_2D": (0, "2D", 0, 2), "dim:SQ_RSRC_IMG_2D_ARRAY": (1, "2D", 1, 3), "dim:SQ_RSRC_IMG_3D": (2, "3D", 0, 3), "dim:SQ_RSRC_IMG_1D": (3, "1D", 0, 1)} + # The sampled array of each STORE_DIMS index: its binding in set 0 (assemble declares %images, %images_arr, + # %images_3d and %images_1d there). Typed image_load reads UINT/SINT images through uint/sint aliases of it. + SAMPLED_BINDINGS = {0: 0, 1: 3, 2: 6, 3: 5} INT_FORMATS = None # (uint mask words, sint mask words) over the 512 GFX10 formats @classmethod @@ -5798,17 +6379,27 @@ class Gen: flags.append(nz) return flags - def image_load_typed(self, dim, t1, iv, img, idx, dmask, vdata, d16=False): - """image_load with the image's numeric type decided at run time (T# FORMAT): UINT/SINT formats are read - through the uint/sint storage views (OpImageRead, read-without-format), everything else through the float - sampled view (OpImageFetch, as before). Vulkan requires the view's component type to match the format, so a - float view of an integer image would be undefined. Results are the raw bits of the dmask components. - t1 is the T#'s second dword (FORMAT), idx the bindless index image_load already looked up.""" + def image_load_typed(self, dim, t1, iv, img, idx, dmask, vdata, lod, d16=False): + def fetch(image, _cls, ty): + res = self.tmp() + self.emit(f"{res} = OpImageFetch {ty} {image} {iv} Lod {lod}") + return res + self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch) + + def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read): + """Read a sampled image using the component type selected by FORMAT in T# word 1. + read(image, cls, ty) emits the fetch or gather and returns its four components. The float view also + handles a lookup miss: index zero holds the RGBA8_UNORM fallback. UINT and SINT views share the + dimension's sampled binding through typed aliases (SHADER-151), so no storage image feature is needed. + dmask selects the output components; d16 packs two per VGPR.""" di = self.STORE_DIMS[dim][0] - self.uses_store_views.add(di) - self.uses_store_reads = True + self.uses_int_fetch.add(di) is_u, is_s = self.fmt_int_flags(t1) - act = self.active_b() + hit = self.tmp() + self.emit(f"{hit} = OpINotEqual %bool {idx} {self.cu(0)}") + use_u, use_s = self.tmp(), self.tmp() + self.emit(f"{use_u} = OpLogicalAnd %bool {is_u} {hit}") + self.emit(f"{use_s} = OpLogicalAnd %bool {is_s} {hit}") L = {k: self.tmp() + "_" + k for k in ("s", "rest", "e2", "u", "f", "e3")} def write(v4u, f16=False): @@ -5836,29 +6427,28 @@ class Gen: self.emit(f"{w} = OpBitwiseOr %uint {lo} {hi}") self.dst({"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1}, w) - def read(cls, ty): - ip, im, r, b = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ip} = OpAccessChain %_ptr_UC_stv{cls}_{di} %stv{cls}_{di} {idx}") - self.emit(f"{im} = OpLoad %stimg{cls}_{di} {ip}") - self.emit(f"{r} = OpImageRead {ty} {im} {iv}") + def read_integer(cls, ty): + ip, im, b = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{ip} = OpAccessChain %_ptr_UC_itx{cls}_{di} %itx{cls}_{di} {idx}") + self.emit(f"{im} = OpLoad %itximg{cls}_{di} {ip}") + r = read(im, cls, ty) self.emit(f"{b} = OpBitcast %v4uint_st {r}") write(b) - _ = act self.emit(f"OpSelectionMerge {L['e2']} None") - self.emit(f"OpBranchConditional {is_s} {L['s']} {L['rest']}") + self.emit(f"OpBranchConditional {use_s} {L['s']} {L['rest']}") self.emit(f"{L['s']} = OpLabel") - read(2, "%v4int_st") + read_integer(2, "%v4int_st") self.emit(f"OpBranch {L['e2']}") self.emit(f"{L['rest']} = OpLabel") self.emit(f"OpSelectionMerge {L['e3']} None") - self.emit(f"OpBranchConditional {is_u} {L['u']} {L['f']}") + self.emit(f"OpBranchConditional {use_u} {L['u']} {L['f']}") self.emit(f"{L['u']} = OpLabel") - read(1, "%v4uint_st") + read_integer(1, "%v4uint_st") self.emit(f"OpBranch {L['e3']}") self.emit(f"{L['f']} = OpLabel") - res, b = self.tmp(), self.tmp() - self.emit(f"{res} = OpImageFetch %v4float {img} {iv} Lod {self.cu(0)}") + res = read(img, 0, "%v4float") + b = self.tmp() self.emit(f"{b} = OpBitcast %v4uint_st {res}") write(b, f16=True) self.emit(f"OpBranch {L['e3']}") @@ -5971,7 +6561,8 @@ class Gen: self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp)) out += 1 return - if (dim != "dim:SQ_RSRC_IMG_2D" and not is3d_atomic) or "d16" in mods or "a16" in mods: + if ((dim != "dim:SQ_RSRC_IMG_2D" and not is3d_atomic) or "a16" in mods + or ("d16" in mods and op != "image_load_mip")): raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) vdata, addr = a[0], self.addr_regs(a[1]) idx = self.desc_lookup_sgpr(a[2], 8) @@ -6080,20 +6671,28 @@ class Gen: self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, u) out += 1 return - # image_load_mip: x, y, mip + # image_load_mip: x, y, mip, with the same typed SRV as image_load. if len(addr) < 3: raise Unsupported("image_load_mip coords") xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:3]] - iv, res = self.tmp(), self.tmp() + iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct %v2int {xs[0]} {xs[1]}") - self.emit(f"{res} = OpImageFetch %v4float {img} {iv} Lod {xs[2]}") - out = 0 - for c in range(4): - if dmask >> c & 1: - comp = self.tmp() - self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") - self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp)) - out += 1 + self.image_load_typed(dim, self.load_reg("sgpr", a[2]["r"] + 1), iv, img, idx, dmask, vdata, xs[2], d16="d16" in mods) + + + def interp_pair_src(self, op, a, ins): + """SHADER-177: the VGPR source of a v_interp_p1/p2 is the barycentric coordinate that op interpolates + with — p1 reads I = v0, p2 reads J = v1, per op. The model returns the attribute's interpolated value, + which is only that when the register really holds that coordinate: the hardware register, or a plain + v_mov copy rooted at it (self.v_interp_copy, from interp_copy_sources, which tracks each copy's root). + Anything else — the other coordinate, a copy rooted at the other one — is refused, not guessed at.""" + want, role = (0, "I") if op.startswith("v_interp_p1") else (1, "J") + s = a[1] if len(a) > 1 else None + c = self.v_interp_copy.get(s["r"]) if (s is not None and s.get("k") == "vgpr") else None + if not (s and s.get("k") == "vgpr" and s.get("n", 1) == 1 and + (s["r"] == want or (c is not None and c[0] == want and c[1] < ins.get("seq", 1 << 62)))): + what = f"v{s['r']}" if s is not None and s.get("k") == "vgpr" else "operand" + raise Unsupported(f"{op} {role} source {what}: only v{want} (or a plain v_mov copy of it) is modelled") def attribute(self, n, comp, flat=False, half=None): """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n). @@ -6924,8 +7523,9 @@ def assemble(gen): [f"%ms_out_param{n}" for n in sorted(gen.ms_params)])) if ms else []) + ( ["%x_buf"] if gen.emulate or gen.bar_rounds else []) + ( ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] + - [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + ((["%fmt_uint_mask", "%fmt_sint_mask"] + - [f"%stv{c}_{d}" for d in sorted(gen.uses_store_views) for c in range(3)]) if gen.uses_store_views else []) + [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + (["%fmt_uint_mask", "%fmt_sint_mask"] if gen.uses_store_views or gen.uses_int_fetch else []) + \ + [f"%stv{c}_{d}" for d in sorted(gen.uses_store_views) for c in range(3)] + \ + [f"%itx{c}_{d}" for d in sorted(gen.uses_int_fetch) for c in (1, 2)] psb = gen.uses_psb tex = gen.uses_tex sg = gen.uses_subgroup @@ -6978,8 +7578,6 @@ def assemble(gen): caps.append("StorageImageWriteWithoutFormat") # shaderStorageImageWriteWithoutFormat if 3 in gen.uses_store_views: caps.append("Image1D") - if gen.uses_store_reads: - caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat if gsx: caps.append("Geometry") if ms and not msc: @@ -7201,7 +7799,7 @@ def assemble(gen): types += ["%double = OpTypeFloat 64", "%v2uint_d = OpTypeVector %uint 2"] if gen.uses_ballot: types += ["%v4uint_bal = OpTypeVector %uint 4"] - if gen.uses_store_views: + if gen.uses_store_views or gen.uses_int_fetch: u, si = Gen.int_format_masks() types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4", f"%fmt_mask_arr = OpTypeArray %uint {gen.cu(16)}", @@ -7211,6 +7809,21 @@ def assemble(gen): ids = " ".join(gen.cu(w) for w in words) types += [f"%fmt_{nm}_init = OpConstantComposite %fmt_mask_arr {ids}"] gvars += [f"%fmt_{nm}_mask = OpVariable %_ptr_Private_fmt Private %fmt_{nm}_init"] + # Typed image_load: uint/sint aliases of the dimension's sampled array (same set and binding; Vulkan allows + # several variables on one binding when the descriptor type fits). The runtime binds each image's view in + # its own format there, so the alias whose component type matches it is the one a shader reads through. + for di in sorted(gen.uses_int_fetch): + _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) + for cls, st in ((1, "%uint"), (2, "%int")): + types += [f"%itximg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 1 Unknown", + f"%rt_itx{cls}_{di} = OpTypeRuntimeArray %itximg{cls}_{di}", + f"%_ptr_UC_rt_itx{cls}_{di} = OpTypePointer UniformConstant %rt_itx{cls}_{di}", + f"%_ptr_UC_itx{cls}_{di} = OpTypePointer UniformConstant %itximg{cls}_{di}"] + if gen.uses_int_gather and di == 0: + types.append(f"%itxsamp{cls}_{di} = OpTypeSampledImage %itximg{cls}_{di}") + dec += [f"OpDecorate %itx{cls}_{di} DescriptorSet 0", + f"OpDecorate %itx{cls}_{di} Binding {Gen.SAMPLED_BINDINGS[di]}"] + gvars += [f"%itx{cls}_{di} = OpVariable %_ptr_UC_rt_itx{cls}_{di} UniformConstant"] for di in sorted(gen.uses_store_views): _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) for cls, st in enumerate(("%float", "%uint", "%int")): @@ -7369,6 +7982,7 @@ def assemble(gen): "%vcc = OpVariable %_ptr_Function_uint Function %c0", "%m0 = OpVariable %_ptr_Function_uint Function %c0", "%vcc_hi = OpVariable %_ptr_Function_uint Function %c0", "%scc = OpVariable %_ptr_Function_uint Function %c0", + *(["%mode_r16 = OpVariable %_ptr_Function_uint Function %c0"] if gen.round_mode else []), "%active = OpVariable %_ptr_Function_bool Function %true"] if gen.emulate: fn += ["%x_it = OpVariable %_ptr_Function_uint Function %c0", @@ -7950,6 +8564,27 @@ def pos_export_layout(osg1, insns): return pos_map, misc_svs, clip_n, cull_n +def check_read_methods(methods, insns): + """Refuse a PS whose FSSM read methods (tools/fssm_header.py, flags bits 0-1) disagree with its code. + + Bit 0 says the code reads the input through v_interp_mov_f32 (declared Flat here), bit 1 through + v_interp_p1/p2 or the f16 forms (a plain input: perspective, pixel centre, BaryCoordKHR for raw + i/j). In the corpus each read position agrees (12,101 of 12,101 PS) and neither-or-both never + occurs. A disagreement means a table this translator does not understand, so it is rejected + instead of being read as perspective-centre. That every interpolated input is perspective-centre + comes from PSV0 (docs/design.md "PS interpolation modes", #1256), not from these bits. Positions + past the table are not checked (the 10 kind-7 tables undercount).""" + for ins in insns: + op = base_op(ins["op"]) + if not op.startswith("v_interp_"): + continue + attr = next((x for x in ins["args"] if x["k"] == "attr"), None) + if attr is None or attr["a"] >= len(methods): + continue + want = fssm_header.READ_MOV if op == "v_interp_mov_f32" else fssm_header.READ_INTERP + if methods[attr["a"]] != want: + raise Unsupported(f"PS input {attr['a']} read method {methods[attr['a']]} read by {op}") + def mesh_psv(path, name): """PSV0 runtime info of a mesh shader: MSInfo (GroupSharedBytesUsed, GroupSharedViewIDDependentBytes, PayloadSizeInBytes, u16 MaxOutputVertices, u16 MaxOutputPrimitives), wave lane counts, then PSVRuntimeInfo1 @@ -8012,6 +8647,7 @@ def translate(path): if any(i.get("normalized") for i in insns): raise Unsupported("reachable instruction with normalized encoding") g = Gen(stage) + g.round_mode = any(i["op"].startswith("s_setreg") and "HW_REG_MODE" in i["args"][0].get("t", "") for i in insns) g.wave64 = any(WAVE64_RE.search(" ".join([i["op"]] + [x.get("t", "") for x in i["args"]])) or (base_op(i["op"]).endswith("_b64") and any(x.get("t") in ("exec", "vcc") for x in i["args"])) for i in insns) @@ -8159,11 +8795,15 @@ def translate(path): try: with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), "fssm", info["name"] + ".fssm"), "rb") as f: - count, fp16 = fssm_header.interpolants(f.read()) + blob = f.read() + count, fp16 = fssm_header.interpolants(blob) + methods = fssm_header.read_methods(blob) except OSError: - count, fp16 = 0, 0 + count, fp16, methods = 0, 0, [] + check_read_methods(methods, insns) if count: g.pixel_interpolants = (count, fp16) + g.pixel_flat = [n for n, m in enumerate(methods) if m == fssm_header.READ_MOV] for n in range(count): g.inputs.setdefault(f"%in_attr{n}", n) if stage in ("vs", "ms"): @@ -8195,6 +8835,8 @@ def translate(path): size = (g.cs or g.ms)["size"] g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 insns = fold_far_branches(insns) + if stage == "ps": + g.v_interp_copy = interp_copy_sources(insns) # before v_interp runs: I/J guards (SHADER-177) branchy = any(base_op(i["op"]) in BRANCHES for i in insns) if not branchy and not g.emulate: g.park_masks(([insns], [[]])) @@ -8363,6 +9005,45 @@ def needs_barrier_rounds(g, blocks, succ): top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set() return not with_barrier <= top +def interp_copy_sources(insns): + """SHADER-177: the VGPRs a v_interp may name as its I/J barycentric source besides v0/v1, as + {vgpr: (root coordinate v0/v1 the copy chain carries, program-order index of the defining instruction)}. + A register qualifies when its single write in the whole shader is one plain v_mov_b32 from v0/v1 — which + must itself be unwritten up to that point: a copy of an already-overwritten v0/v1 carries a computed value, + not the pair, while a write after the copy is fine (the copy saved the value) — or from another + qualifying register defined earlier (compilers copy the pair out of v0/v1; the corpus has one + shader that reads its J through such a copy). One definition means every read that is not undefined + garbage reads the copied barycentric + value, whatever the control flow. Every VGPR destination counts as a write (memory stores only + read their data operand; tfe's extra status VGPR is one too).""" + writes = {} + for i, ins in enumerate(insns): + ins["seq"] = i # program order: also unique without encoding comments (test fixtures share a pc) + a = ins["args"] + if not (a and a[0].get("k") == "vgpr") or base_op(ins["op"]).startswith( + ("buffer_store", "tbuffer_store", "scratch_store", "global_store", "image_store", "ds_write")): + continue + for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1) + (1 if "tfe" in ins["mods"] else 0)): + writes.setdefault(r, []).append(ins) + copies = {} + grew = True + while grew: # copy chains resolve over passes: v15 = v14 after v14 = v1 + grew = False + for r, ws in writes.items(): + if r in copies or len(ws) != 1: + continue + ins = ws[0] + a = ins["args"] + s = a[1] if len(a) > 1 else None + plain = (base_op(ins["op"]) == "v_mov_b32" and not ins["mods"] and a[0].get("n", 1) == 1 + and not a[0].get("sdwa_dst") + and s is not None and s.get("k") == "vgpr" and s.get("n", 1) == 1 + and not s.get("neg") and not s.get("abs") and not s.get("sdwa_sel")) + if plain and ((s["r"] in (0, 1) and not any(w["seq"] < ins["seq"] for w in writes.get(s["r"], ()))) or + (s["r"] in copies and copies[s["r"]][1] < ins["seq"])): + copies[r] = (s["r"] if s["r"] in (0, 1) else copies[s["r"]][0], ins["seq"]) + grew = True + return copies def x_spill(g, parts): """Emulated wave64 and barrier rounds: the segments of one block run in different rounds, i.e. in different @@ -8700,9 +9381,15 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): count, fp16 = g.pixel_interpolants m["ps_interpolants"] = count m["ps_fp16_interpolants"] = [n for n in range(count) if (fp16 >> n) & 1] + # Table positions whose read method is v_interp_mov (flags bit 0): the inputs declared Flat. + m["ps_flat_interpolants"] = getattr(g, "pixel_flat", []) outs = sorted(int("".join(ch for ch in t if ch.isdigit()) or 0) for t in g.outputs.values() if not t.startswith("pos")) if outs: m["outputs"] = outs + if g.stage == "vs" and g.uses_clip: + m["clip_distance_count"] = g.clip_count + if g.stage == "vs" and g.uses_cull: + m["cull_distance_count"] = g.cull_count if g.writes_depth: m["writes_depth"] = True if g.inputs: diff --git a/tools/rpf9dump/Program.cs b/tools/rpf9dump/Program.cs index 47c2e4914..f1965ac31 100644 --- a/tools/rpf9dump/Program.cs +++ b/tools/rpf9dump/Program.cs @@ -32,7 +32,7 @@ if (mode == "ttpf") // cancellation and anything unexpected stay failures. byte[]? dds = null; try { dds = TtpfReader.CreateDds(src, t.Index); } - catch (Exception e) when (e.GetType() == typeof(NotSupportedException) || e.GetType() == typeof(InvalidDataException)) + catch (Exception e) when (e is NotSupportedException or InvalidDataException) { skip++; file = null; limitation = e.Message; } if (dds != null) { Util.WriteAllBytes(path, dds); ok++; } } diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py index e7f4522f9..5957ff422 100644 --- a/tools/rtti_scan.py +++ b/tools/rtti_scan.py @@ -176,7 +176,7 @@ def scan_pe64_rtti(data: bytes) -> dict: if q in col_vas: vt = p + 8 n = 0 - while vt + 8 * (n + 1) <= len(img): + while vt + 8 * (n + 1) <= hi: f = struct.unpack_from("> 16) & 0x7F # A field that runs past bit 31 stops there: s_bfe_i32 sign-extends from the top bit that exists (LLVM # constantFoldBFE does for v_bfe; 5-bit width there). The s_bfe rule itself rests on the gfx1150 measurement - # (4000 random control words, --oracle hw); RDNA2 is unmeasured. + # (4000 random control words, --oracle hw), and RDNA2 agrees: gfx1036, 20,000 programs with --bfe-any. width = min(width, 32 - off) if width == 0: return 0 @@ -221,6 +230,25 @@ def _sopc(): OPS = {**_sop2(), **_sop2_64(), **_sop1(), **_sopc()} +SCC_CONSUMERS = ("s_cselect_b32", "s_addc_u32", "s_subb_u32") +SCC_BRANCHES = ("s_cbranch_scc0", "s_cbranch_scc1") + + +def writes_scc(name): + """Whether the opcode writes SCC (each one always does or never does).""" + form, fn = OPS[name] + return (fn(1, 2, 0, 3) if form == "sop1_rmw" else fn(1, 2, 0))[1] is not None + + +def branch_skip(line): + """For `s_cbranch_scc0/1 +N`: (mnemonic, N); None for any other line.""" + op, _, rest = line.partition(" ") + if op not in SCC_BRANCHES: + return None + if not rest.startswith("+"): + raise RefError(f"branch {line!r}: expected +N (instructions skipped)") + return op, int(rest[1:]) + # ---- program generation --------------------------------------------------------------------------- @@ -282,15 +310,38 @@ def emit(rng, name): return f"{name} s{d}, 0x{k:x}" # movk, sopk -def generate(rng, n_ops, ops): +def generate(rng, n_ops, ops, branches=False): lines = [f"s_mov_b32 s{r}, 0x{_value(rng):x}" for r in REGS] lines.append(f"s_cmp_eq_u32 s{rng.choice(REGS)}, s{rng.choice(REGS)}") # a known SCC to start with - for _ in range(n_ops): - lines.append(emit(rng, rng.choice(ops))) + if branches: + lines += _cf_body(rng, n_ops, ops) + else: + for _ in range(n_ops): + lines.append(emit(rng, rng.choice(ops))) lines += observe(rng.sample(REGS, 3)) return lines +def _cf_body(rng, n_ops, ops): + """n_ops instructions, half of them SCC producers. After a producer: sometimes a chain of SCC consumers, + sometimes s_cbranch_scc0/1 forward over the next 1..3 instructions (which never branch themselves).""" + producers = [o for o in ops if writes_scc(o)] or ops + body = [] + for _ in range(n_ops): + op = rng.choice(producers if rng.random() < 0.5 else ops) + body.append(emit(rng, op)) + if not writes_scc(op): + continue + r = rng.random() + if r < 0.35: + body += [emit(rng, rng.choice(SCC_CONSUMERS)) for _ in range(rng.randint(1, 3))] + elif r < 0.8: + k = rng.randint(1, 3) + body.append(f"{rng.choice(SCC_BRANCHES)} +{k}") + body += [emit(rng, rng.choice(ops + list(SCC_CONSUMERS))) for _ in range(k)] + return body + + def observe(regs): return [f"s_cselect_b32 s{OUT_SCC}, 1, 0", f"v_mov_b32 v8, s{regs[0]}", f"v_mov_b32 v9, s{regs[1]}", f"v_mov_b32 v10, s{regs[2]}", @@ -333,7 +384,17 @@ def _write(sgpr, tok, value, width): def reference(lines): """Run the scalar program; returns the four exported words.""" sgpr, scc, vgpr = {}, 0, {} + skip = 0 for line in lines: + if skip: + skip -= 1 + continue + br = branch_skip(line) + if br: + # SOPP: if SCC == 0 (scc0) / SCC == 1 (scc1) then PC = PC + SIMM16 * 4 + 4; SCC is not written. + if scc == (0 if br[0] == "s_cbranch_scc0" else 1): + skip = br[1] + continue op, _, rest = line.partition(" ") args = [a.strip() for a in rest.split(", ")] if rest else [] if op == "v_mov_b32": @@ -387,6 +448,43 @@ def reference(lines): # ---- the translator side ------------------------------------------------------------------------- +def _is_literal(tok): + """A 32-bit source that needs a literal dword: not a register or an integer inline constant (-16..64).""" + tok = tok.strip() + if tok[0] in "sv": + return False + return not -16 <= s32(int(tok, 0)) <= 64 + + +def insn_size(line): + """Encoded bytes of one generated line: 4, or 8 with a literal (a SOPK immediate sits in SIMM16).""" + op, _, rest = line.partition(" ") + if op == "exp": + return 8 + if op in SCC_BRANCHES or op == "s_endpgm" or (op in OPS and OPS[op][0] in ("sopk", "movk", "cmpk")): + return 4 + args = rest.split(", ") if rest else [] + srcs = args if op in OPS and OPS[op][0] in ("sopc", "sopc_64") else args[1:] + return 8 if any(_is_literal(a) for a in srcs) else 4 + + +def listing(lines): + """(text, size) per line, with `s_cbranch_scc0/1 +N` turned into the dword offset over the next N lines.""" + sizes = [insn_size(line) for line in lines] + out = [] + for i, line in enumerate(lines): + br = branch_skip(line) + if br: + if i + 1 + br[1] > len(lines): + raise RefError(f"branch {line!r} past the end of the program") + line = f"{br[0]} {sum(sizes[i + 1:i + 1 + br[1]]) // 4}" + out.append((line, sizes[i])) + return out + + +def has_branches(lines): + return any(branch_skip(line) for line in lines) + def translated(lines, name="ps_salu"): """Translate and execute; returns the four exported words, or raises Skip.""" import rdna2spirv @@ -396,10 +494,17 @@ def translated(lines, name="ps_salu"): os.mkdir(dis) path = os.path.join(dis, name + ".s") with open(path, "w", encoding="utf-8") as f: - f.write(f"; {name} salu_diff case\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") + if has_branches(lines): + # The translator places branch targets from the encoding sizes; it does not read the bytes. + body = listing(lines + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]) + f.write(f"; {name} code 0x0..0x{sum(n for _, n in body):x}\n") + for text, n in body: + f.write("\t" + text + " ; encoding: [" + ",".join(["0x00"] * n) + "]\n") + else: + f.write(f"; {name} salu_diff case\n") + for line in lines: + f.write("\t" + line + "\n") + f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: f.write(STUB_DXBC) try: @@ -451,6 +556,19 @@ def check(lines, backends=("translator",), hw=None): return "; ".join(p for p in problems if p) or None +def drop(body, i): + """body without line i; a branch that skipped over that line now skips one line fewer.""" + out = [] + for j, line in enumerate(body): + if j == i: + continue + br = branch_skip(line) + if br and j < i <= j + br[1]: + line = f"{br[0]} +{br[1] - 1}" + out.append(line) + return out + + def shrink(lines, check_fn=check): """Drop instructions (not seeds or the observation) while the program still mismatches.""" n_seed = len(REGS) @@ -459,10 +577,10 @@ def shrink(lines, check_fn=check): while changed: changed = False for i in range(len(body)): - trial = lines[:n_seed] + body[:i] + body[i + 1:] + lines[-5:] + trial = lines[:n_seed] + drop(body, i) + lines[-5:] try: if check_fn(trial): - body = body[:i] + body[i + 1:] + body = drop(body, i) changed = True break except (Skip, RefError): @@ -486,11 +604,11 @@ def hw_prepare(oracle, programs): return out -def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None): +def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None, branches=False): counts = {"pass": 0, "mismatch": 0, "skip": {}} failures = [] rng = random.Random(seed) - progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)] + progs = [generate(rng, rng.randrange(1, max_ops + 1), ops, branches) for _ in range(programs)] hw_words = hw_prepare(oracle, progs) if "hw" in backends else [None] * programs for i, lines in enumerate(progs): try: @@ -529,19 +647,24 @@ def main(argv=None): ap.add_argument("--self-test", action="store_true") ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") ap.add_argument("--bfe-any", action="store_true", - help="also give s_bfe_* control words past offset + width = 32 (measured on gfx1150: the field stops at bit 31; RDNA2 unmeasured)") + help="also give s_bfe_* control words past offset + width = 32 (measured on gfx1150 and gfx1036: the field stops at bit 31)") ap.add_argument("--inline64", action="store_true", help="also use inline constants as 64-bit sources (the translator reads them as lane masks)") ap.add_argument("--oracle", default="translator", help="comma-separated comparison targets: translator (default), hw (natively on the AMD GPU; see " "tools/hw_oracle/). 'hw' alone compares the hardware with the reference only") ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") + ap.add_argument("--branches", action="store_true", + help="SCC in control flow: consumer chains and s_cbranch_scc0/1 forward over 1..3 instructions " + "after SCC producers (translator oracle only)") a = ap.parse_args(argv) if a.programs < 1 or a.max_ops < 1: ap.error("--programs and --max-ops must be at least 1") backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) if not backends or any(t not in ("translator", "hw") for t in backends): ap.error("--oracle takes translator, hw or translator,hw") + if a.branches and "hw" in backends: + ap.error("--branches runs against the translator only (the hardware kernels are straight-line)") global INLINE64, BFE_ANY INLINE64, BFE_ANY = a.inline64, a.bfe_any if a.list_ops: @@ -570,9 +693,10 @@ def main(argv=None): return 77 print(f"hardware oracle: {oracle.device}") try: - counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle) + counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle, a.branches) skips = sum(counts["skip"].values()) - print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}): {counts['pass']} pass, " + mode = "+".join(backends) + (", branches" if a.branches else "") + print(f"{a.programs} programs (seed {a.seed}, {mode}): {counts['pass']} pass, " f"{counts['mismatch']} mismatch, {skips} skipped") for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): print(f" skip x{n}: {reason}") @@ -582,7 +706,8 @@ def main(argv=None): for i, problem, lines in failures[: None if a.all_failures else 1]: small = shrink(lines, check_fn) print(f"MISMATCH program {i}: {check_fn(small) or problem}") - print("\n".join("\t" + line for line in small)) + shown = [text for text, _ in listing(small)] if has_branches(small) else small + print("\n".join("\t" + line for line in shown)) finally: if oracle: oracle.close() diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index 48ecc54af..b881a5d03 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -98,7 +98,8 @@ def code_range(b: bytes): def one(path, out, mcpu): - b = open(path, "rb").read() + with open(path, "rb") as f: + b = f.read() start, end, how = code_range(b) if end is None: return "no s_endpgm" diff --git a/tools/tex_export.py b/tools/tex_export.py index 235d0f9b5..d8018ad98 100644 --- a/tools/tex_export.py +++ b/tools/tex_export.py @@ -164,7 +164,8 @@ def main(): ap.add_argument("out") ap.add_argument("--limit", type=positive_int, help="export only the first N textures (N >= 1)") a = ap.parse_args() - texs = json.load(open(a.index, encoding="utf-8")) + with open(a.index, encoding="utf-8") as f: + texs = json.load(f) texs.sort(key=lambda t: (t["archive"], t["gpu"])) if a.limit is not None: # 0 used to read as "no limit", and a negative N dropped the last N texs = texs[: a.limit] diff --git a/tools/tex_headers.py b/tools/tex_headers.py index c26889a14..726068f7d 100644 --- a/tools/tex_headers.py +++ b/tools/tex_headers.py @@ -722,7 +722,12 @@ def main(): ap.error(f"no carved archive (a folder with index.json) in {a.carve}") allt = [] for arch in archs: - t = scan_archive(a.carve, arch) + try: + t = scan_archive(a.carve, arch) + except (OSError, ValueError, KeyError, TypeError) as e: # a malformed index.json: one line, as gamedata_index + where = getattr(e, "filename", None) or os.path.join(a.carve, arch, "index.json") + print(f"ERROR: cannot read {where}: {getattr(e, 'strerror', None) or e!r}", file=sys.stderr) + return 2 print(f"{arch}: {len(t)} texture headers", flush=True) allt += t path = a.out or os.path.join(a.carve, "textures_index.json") diff --git a/tools/tex_mode_probe.py b/tools/tex_mode_probe.py index 441934e3c..f486f79a3 100644 --- a/tools/tex_mode_probe.py +++ b/tools/tex_mode_probe.py @@ -67,8 +67,9 @@ def main(): if bc_bpe(a.fmt) is None: ap.error(f"no color scorer for {a.fmt!r}; expected BC1, BC2, or BC3") nib, tab = load() - texs = [t for t in json.load(open(a.index)) if t["fmt_name"].startswith(a.fmt) - and bc_bpe(t["fmt_name"]) is not None and t["w"] >= 256 and t["h"] >= 256] + with open(a.index, encoding="utf-8") as f: + texs = [t for t in json.load(f) if t["fmt_name"].startswith(a.fmt) + and bc_bpe(t["fmt_name"]) is not None and t["w"] >= 256 and t["h"] >= 256] texs = texs[: a.n] cands = {} for tname, ents in tab.items(): diff --git a/tools/valu_fuzz.py b/tools/valu_fuzz.py index 1a4638d9a..e66d0b386 100644 --- a/tools/valu_fuzz.py +++ b/tools/valu_fuzz.py @@ -634,7 +634,7 @@ def translate(progs, work, emulate): cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] if p.wave == 64: cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") - r = subprocess.run(cmd, input=text, capture_output=True, text=True) + r = mc_command.run(cmd, input=text, capture_output=True, text=True) if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) diff --git a/tools/vertex_types.py b/tools/vertex_types.py index 9a2798422..f4c6d04f3 100644 --- a/tools/vertex_types.py +++ b/tools/vertex_types.py @@ -1,5 +1,8 @@ """Measure the component types of the vertex streams in `42 40 00 00` blocks (follow-up to ASSET-57). +A stream can hold several blocks back to back, with their meshlet groups after the whole run in the same order +(group i belongs to block i); every paired block is measured. + docs/restofworld.md measures each tag's bytes per vertex on `42 40 00 00` blocks: 8 for 0x42, 4 for 0x21, 0x25, 0x26, 0x27 and 0x28, 16 for 0x8c. This tool tests what those bytes are, using checks that need no textures and no other file: the vertex count and the triangle edges come from the meshlet group that follows the streams (validated @@ -83,13 +86,23 @@ def vertex_count(slots, order): return span // 8 -def find_group(data, at, slots, order, n): - """The meshlet group after the last stream: end of the last stream, padded to 16 bytes, over zero words.""" - last = order[-1] - end = at + slots[last][1] + stride(slots[last][0]) * n - pos = (end + 15) & ~15 +def skip_padding(data, pos): + """Round up to 16 bytes, then step over zero words.""" + pos = (pos + 15) & ~15 while pos + 4 <= len(data) and struct.unpack_from(" len(data) or struct.unpack_from(" int: ap = argparse.ArgumentParser( description="Count candidate cross-half wave ops in wave64 graphics shaders (counts only, no names)") ap.add_argument("src", help="/shaders/dxbc/disasm from the shaders stage") ap.add_argument("--out", help="write the same aggregates to a JSON file") - args = ap.parse_args() + args = ap.parse_args(argv) if not os.path.isdir(args.src): - raise SystemExit("not a directory: %s" % args.src) + ap.error(f"not a directory: {args.src}") + if args.out: + if os.path.isdir(args.out): + ap.error(f"{args.out} is a directory, not a JSON file") + out_dir = os.path.dirname(os.path.abspath(args.out)) + if not os.path.isdir(out_dir): + ap.error(f"output directory does not exist: {out_dir}") + try: + if os.path.samefile(os.path.abspath(args.src), os.path.abspath(args.out)): + ap.error("output must not overwrite the source directory") + except (FileNotFoundError, OSError): + pass report = scan_directory(args.src) for stage, b in report["per_stage"].items(): occ = ", ".join("%s x%d" % (op, n) for op, n in b["occurrences"].items()) or "none" @@ -150,7 +161,8 @@ def main(): with open(args.out, "w", encoding="utf-8") as f: json.dump(report, f, indent=1) print("wrote %s" % args.out) + return 0 if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/tools/world_build.py b/tools/world_build.py index 236dbed93..cee87d54e 100644 --- a/tools/world_build.py +++ b/tools/world_build.py @@ -12,10 +12,14 @@ With --placements, models are instanced at their map placements instead: each en carries it, the 64-bit Murmur3 archetype key, as in world_names.py), then scaled, rotated by the conjugate of the stored quaternion and translated into world space. +Each placed model is parsed once and stored once per chunk; its placements in that chunk are instance +transforms (EXT_mesh_gpu_instancing by default, or plain glTF nodes with --instancing nodes), and every chunk is +written as soon as it is built, so memory stays bounded by the largest chunk rather than the size of the map. + Usage: python -I tools/world_build.py --out [options] python -I tools/world_build.py --out --placements - [--lod-levels 0,5] [--region MINX,MINY,MAXX,MAXY] + [--lod-levels 0,5] [--region MINX,MINY,MAXX,MAXY] [--instancing gpu|nodes|bake] """ from __future__ import annotations @@ -59,12 +63,24 @@ def _get_world_names(): return world_names +def _placement_scale(value) -> float: + """Optional scales that cannot be represented as finite floats use the existing unit default.""" + if not isinstance(value, (int, float)): + return 1.0 + try: + scale = float(value) + except OverflowError: + return 1.0 + return scale if math.isfinite(scale) else 1.0 + + def load_placements(path: str, lod_levels=DEFAULT_LOD_LEVELS, region=None) -> tuple[list[dict], dict]: """Read ``world_index.py --entities-out`` rows. Returns (selected rows, counts). A row is kept when its lod_level is in lod_levels and, with region = (minx, miny, maxx, maxy) in RAGE world metres, its position lies inside it. Rows without a finite position, rotation or archetype are - counted as malformed and skipped. + counted as malformed and skipped, as are unhashable LOD values. Optional scales that are missing, + non-numeric or not representable as finite floats default to 1.0. """ levels = set(lod_levels) counts = {"rows": 0, "malformed": 0, "other_lod_level": 0, "outside_region": 0, "selected": 0} @@ -80,13 +96,14 @@ def load_placements(path: str, lod_levels=DEFAULT_LOD_LEVELS, region=None) -> tu arch = int(str(row["archetype"]), 16) pos = [float(v) for v in row["position"]] rot = [float(v) for v in row["rotation"]] - except (ValueError, KeyError, TypeError): + selected_lod = row.get("lod_level") in levels + except (ValueError, KeyError, TypeError, OverflowError): counts["malformed"] += 1 continue if len(pos) != 3 or len(rot) != 4 or not all(math.isfinite(v) for v in pos + rot): counts["malformed"] += 1 continue - if row.get("lod_level") not in levels: + if not selected_lod: counts["other_lod_level"] += 1 continue if region is not None and not (region[0] <= pos[0] <= region[2] and region[1] <= pos[1] <= region[3]): @@ -95,13 +112,56 @@ def load_placements(path: str, lod_levels=DEFAULT_LOD_LEVELS, region=None) -> tu sxy, sz = row.get("scale_xy"), row.get("scale_z") row["_arch"] = arch & 0xFFFFFFFF row["_pos"], row["_rot"] = pos, rot - row["_sxy"] = float(sxy) if isinstance(sxy, (int, float)) and math.isfinite(sxy) else 1.0 - row["_sz"] = float(sz) if isinstance(sz, (int, float)) and math.isfinite(sz) else 1.0 + row["_sxy"] = _placement_scale(sxy) + row["_sz"] = _placement_scale(sz) rows.append(row) counts["selected"] += 1 return rows, counts +def _placement_counts() -> dict: + return {"rows": 0, "malformed": 0, "other_lod_level": 0, "outside_region": 0, "selected": 0} + + +def iter_placements(path: str, counts: dict, lod_levels=DEFAULT_LOD_LEVELS, region=None): + """The rows ``load_placements`` selects, one at a time, adding to ``counts`` (a whole city need not be held). + + The row checks are the same as ``load_placements``'; keep the two in step. + """ + levels = set(lod_levels) + with open(path, encoding="utf-8-sig") as handle: + for line in handle: + line = line.strip() + if not line: + continue + counts["rows"] += 1 + try: + row = json.loads(line) + arch = int(str(row["archetype"]), 16) + pos = [float(v) for v in row["position"]] + rot = [float(v) for v in row["rotation"]] + selected_lod = row.get("lod_level") in levels + except (ValueError, KeyError, TypeError, OverflowError): + counts["malformed"] += 1 + continue + if len(pos) != 3 or len(rot) != 4 or not all(math.isfinite(v) for v in pos + rot): + counts["malformed"] += 1 + continue + if not selected_lod: + counts["other_lod_level"] += 1 + continue + if region is not None and not (region[0] <= pos[0] <= region[2] and region[1] <= pos[1] <= region[3]): + counts["outside_region"] += 1 + continue + sxy, sz = row.get("scale_xy"), row.get("scale_z") + row["_arch"] = arch & 0xFFFFFFFF + row["_pos"], row["_rot"] = pos, rot + row["_sxy"] = _placement_scale(sxy) + row["_sz"] = _placement_scale(sz) + counts["selected"] += 1 + yield row + + def entity_transform(rotation, scale_xy: float, scale_z: float) -> tuple[list[list[float]], list[list[float]], bool]: """3x3 position and normal matrices (RAGE Z-up) for one entity, and whether it mirrors. @@ -191,6 +251,437 @@ def resolve_placement(index, arch: int, key_hex) -> tuple[tuple[str, dict] | Non return (cands[0][0], cands[0][1]), "placed_unverified" +INSTANCING_MODES = ("gpu", "nodes", "bake") +# lodLevel -> chunk-set name for --lod-sets, and the parent chain HD -> LOD -> SLOD1 -> SLOD2 -> SLOD3 -> SLOD4. +LOD_TIER_NAMES = {0: "hd", 1: "lod", 2: "slod1", 3: "slod2", 4: "slod3", 5: "orphan_hd", 6: "slod4"} +LOD_CHAIN = (0, 1, 2, 3, 4, 6) +ALL_LOD_LEVELS = tuple(sorted(LOD_TIER_NAMES)) + + +def _median(values) -> float | None: + vals = sorted(values) + if not vals: + return None + mid = len(vals) // 2 + return float(vals[mid]) if len(vals) % 2 else 0.5 * (vals[mid - 1] + vals[mid]) + + +def lod_bands(child_lod: dict, lod_dist: dict, present) -> tuple[dict, dict]: + """Camera distance band [start, end) per tier, from the selected entities' medians. + + A parent's childLodDist is the distance inside which its children are drawn instead of it, so a tier starts + at its own median childLodDist (HD at 0) and ends where the next coarser tier present starts; the coarsest + tier ends at its median lodDist. ORPHAN_HD has no parent and is drawn from 0 to its median lodDist. Returns + (bands by tier name, the measured medians by tier name).""" + measured = {} + for lvl in present: + measured[LOD_TIER_NAMES[lvl]] = {"child_lod_dist_median": _median(child_lod.get(lvl, ())), + "lod_dist_median": _median(lod_dist.get(lvl, ()))} + bands = {} + chain = [lvl for lvl in LOD_CHAIN if lvl in present] + starts = [] + for i, lvl in enumerate(chain): + start = 0.0 if i == 0 else (measured[LOD_TIER_NAMES[lvl]]["child_lod_dist_median"] or 0.0) + starts.append(max(start, starts[-1] if starts else 0.0)) + for i, lvl in enumerate(chain): + if i + 1 < len(chain): + end = starts[i + 1] + else: + end = measured[LOD_TIER_NAMES[lvl]]["lod_dist_median"] or max(4.0 * starts[i], 1000.0) + bands[LOD_TIER_NAMES[lvl]] = [starts[i], max(end, starts[i])] + if 5 in present: + end = measured["orphan_hd"]["lod_dist_median"] + if end is None: + end = bands["hd"][1] if "hd" in bands else 1000.0 + bands["orphan_hd"] = [0.0, float(end)] + return bands, measured +_PACK_MAGIC = b"LPK1" + + +def placement_trs(rotation, scale_xy: float, scale_z: float, position): + """glTF (Y-up) instance transform for one entity: (translation, rotation xyzw, scale, mirrored). + + The same transform as ``entity_transform`` + the Z-up to Y-up conversion, split into a node TRS with a + positive determinant. A negative XY scale is a turn by 180 degrees about the model's Z axis, so it is folded + into the rotation. A negative Z scale mirrors, which no TRS with positive scale can express: ``mirrored`` is + then True and the instance must draw the model mirrored along its Z axis (glTF Y), with reversed winding. + """ + x, y, z, w = (float(v) for v in rotation) + n = math.sqrt(x * x + y * y + z * z + w * w) + if n == 0 or not math.isfinite(n): + qx, qy, qz, qw = 0.0, 0.0, 0.0, 1.0 + else: + qx, qy, qz, qw = -x / n, -y / n, -z / n, w / n # the world rotation is the stored quaternion's conjugate + sxy, sz = float(scale_xy), float(scale_z) + if sxy < 0: + qx, qy, qz, qw = qy, -qx, qw, -qz # q * (0, 0, 1, 0): turn 180 degrees about model Z first + sxy = -sxy + mirrored = sz < 0 + if mirrored: + sz = -sz + px, py, pz = (float(v) for v in position) + # RAGE (x, y, z) -> glTF (x, z, -y) for the translation, the rotation axis and the scale axes. + return (px, pz, -py), (qx, qz, -qy, qw), (sxy, sz, sxy), mirrored + + +def _write_pack(path: str, packed: list[dict]) -> int: + """Store packed primitives in one file: magic, u32 header length, JSON header, then the buffers.""" + header = [] + blobs = [] + for prim in packed: + meta = {k: prim[k] for k in ("index_type", "vertices", "index_count", "min", "max", "material")} + meta["lengths"] = [len(prim[k]) for k in ("positions", "normals", "uvs", "indices")] + header.append(meta) + blobs.extend(prim[k] for k in ("positions", "normals", "uvs", "indices")) + head = json.dumps(header, separators=(",", ":"), ensure_ascii=True).encode("ascii") + with open(path, "wb") as f: + f.write(_PACK_MAGIC + len(head).to_bytes(4, "little") + head) + for blob in blobs: + f.write(blob) + return f.tell() + + +def _read_pack(path: str) -> list[dict]: + with open(path, "rb") as f: + data = f.read() + if data[:4] != _PACK_MAGIC: + raise ValueError(f"{path} is not a packed model") + n = int.from_bytes(data[4:8], "little") + header = json.loads(data[8:8 + n].decode("ascii")) + at = 8 + n + out = [] + for meta in header: + prim = {k: meta[k] for k in ("index_type", "vertices", "index_count", "min", "max", "material")} + for key, length in zip(("positions", "normals", "uvs", "indices"), meta["lengths"]): + prim[key] = data[at:at + length] + at += length + out.append(prim) + return out + + +def _le_array(code: str, raw: bytes) -> array.array: + arr = array.array(code) + arr.frombytes(raw) + if sys.byteorder == "big": + arr.byteswap() + return arr + + +def _le_bytes(arr: array.array) -> bytes: + if sys.byteorder == "big": + arr = array.array(arr.typecode, arr) + arr.byteswap() + return arr.tobytes() + + +def _mirror_packed(prim: dict) -> dict: + """The primitive mirrored along glTF Y (the model's RAGE Z): y of positions and normals negated, winding + reversed, so a positive-determinant instance of it draws a mirrored placement correctly.""" + pos = _le_array("f", prim["positions"]) + pos[1::3] = array.array("f", [-v for v in pos[1::3]]) + nrm = _le_array("f", prim["normals"]) + nrm[1::3] = array.array("f", [-v for v in nrm[1::3]]) + code = "H" if prim["index_type"] == 5123 else "I" + if array.array(code).itemsize != (2 if code == "H" else 4): + code = "L" if code == "I" else code + idx = _le_array(code, prim["indices"]) + a, b = idx[1::3], idx[2::3] + idx[1::3], idx[2::3] = b, a + out = dict(prim) + out.update(positions=_le_bytes(pos), normals=_le_bytes(nrm), indices=_le_bytes(idx), + min=[prim["min"][0], -prim["max"][1], prim["min"][2]], + max=[prim["max"][0], -prim["min"][1], prim["max"][2]]) + return out + + +def _pack_model_job(job: tuple) -> tuple[int, dict | None]: + """Parse one model's OBJ once (glTF Y-up model space), pack it to its cache file and return its summary.""" + model_id, obj_path, mesh_shaders, tex_map, textures, cache_path = job + glb_mod = _get_glb_writer() + try: + prims = glb_mod.parse_obj(obj_path, is_path=True, up_axis="z") + except (OSError, glb_mod.GlbError, ValueError): + return model_id, None + mat_to_dds = _assign_materials(prims, mesh_shaders, tex_map, textures) + try: + packed = [glb_mod.pack_primitive(p) for p in prims if p.get("positions") and p.get("indices")] + except glb_mod.GlbError: + return model_id, None + if not packed: + return model_id, None + lo = [min(p["min"][k] for p in packed) for k in range(3)] + hi = [max(p["max"][k] for p in packed) for k in range(3)] + if not all(math.isfinite(v) for v in lo + hi): + return model_id, None + size = _write_pack(cache_path, packed) + used = {p["material"] for p in packed} + return model_id, { + "box": lo + hi, + "triangles": sum(p["index_count"] // 3 for p in packed), + "mat_to_dds": {k: v for k, v in mat_to_dds.items() if k in used}, + "pack_bytes": size, + } + + +_PNG_CACHE: dict[str, bytes | None] = {} +_PNG_CACHE_BUDGET = 256 * 1024 * 1024 + + +def _png_for(dds_path: str, max_tex_size: int) -> bytes | None: + """Decode a DDS to PNG once per worker, keeping at most about 256 MB of PNGs (oldest dropped first).""" + key = os.path.normcase(os.path.abspath(dds_path)) + if key in _PNG_CACHE: + return _PNG_CACHE[key] + dds_mod = _get_dds_png() + try: + png = dds_mod.dds_file_to_png_bytes(dds_path, max_size=max_tex_size) + except (dds_mod.DdsError, OSError): + png = None + _PNG_CACHE[key] = png + while sum(len(v or b"") for v in _PNG_CACHE.values()) > _PNG_CACHE_BUDGET and len(_PNG_CACHE) > 1: + del _PNG_CACHE[next(iter(_PNG_CACHE))] + return png + + +def _build_chunk_job(job: tuple) -> tuple[dict, int, int, int]: + """Write one chunk: every distinct (model, mirrored) once, drawn by its instances. Returns + (chunk record, textures embedded, textures skipped, bytes), after checking the written file.""" + (chunk_id, staging_dir, mode, insts, packs, mat_to_dds, textures, max_tex_size) = job + glb_mod = _get_glb_writer() + groups: dict[tuple[int, bool], list] = {} + for model_id, mirrored, t, q, sc in insts: + groups.setdefault((model_id, mirrored), []).append((t, q, sc)) + loaded: dict[int, list[dict]] = {} + meshes = [] + for (model_id, mirrored), instances in sorted(groups.items()): + if model_id not in loaded: + loaded[model_id] = _read_pack(packs[model_id]) + prims = loaded[model_id] + if mirrored: + prims = [_mirror_packed(p) for p in prims] + meshes.append({"name": f"m{model_id}{'_mirror' if mirrored else ''}", "primitives": prims, + "instances": instances}) + materials: dict[str, dict] = {} + skipped = 0 + if textures: + keys = sorted({p["material"] for m in meshes for p in m["primitives"] if p["material"]}) + for key in keys: + dds = mat_to_dds.get(key) + png = _png_for(dds, max_tex_size) if dds else None + if png is None: + skipped += 1 + continue + materials[key] = {"name": os.path.splitext(os.path.basename(dds))[0], "png_bytes": png, + "base_color_factor": [1.0, 1.0, 1.0, 1.0], "double_sided": True} + path = os.path.join(staging_dir, f"{chunk_id}.glb") + info = glb_mod.write_instanced_glb(path, meshes, materials or None, mode=mode) + _verify_staged_chunk(path, int(info["bytes"]), glb_mod) + rec = { + "id": chunk_id, + "url": f"world/chunks/{chunk_id}.glb", + "bounds": info["bounds"], + "models": info["instances"], + "triangles": info["triangles"], + "distinct_models": info["meshes"], + "stored_triangles": info["stored_triangles"], + } + return rec, int(info.get("textures", 0)), skipped, int(info["bytes"]) + + +def _run_jobs(fn, jobs, workers: int): + """Yield fn(job) for every job, in order. With workers > 1 the jobs run in one process pool (fn and jobs + must be picklable), and at most 4 * workers jobs are taken from ``jobs`` ahead of the results, so a lazy + ``jobs`` iterator is never materialised.""" + if workers <= 1: + for job in jobs: + yield fn(job) + return + import collections + from concurrent.futures import ProcessPoolExecutor + window = 4 * workers + with ProcessPoolExecutor(max_workers=workers) as pool: + pending = collections.deque() + try: + for job in jobs: + pending.append(pool.submit(fn, job)) + if len(pending) >= window: + yield pending.popleft().result() + while pending: + yield pending.popleft().result() + except BaseException: + for f in pending: + f.cancel() + raise + + +def _build_instanced_world(entries, ttpf_index, *, placements, lod_levels, region, out_dir, chunk_size, + textures, max_tex_size, base_color_param, workers, mode, glb_mod, limit, + lod_sets=False) -> dict: + """``build_world --placements`` with shared geometry: memory holds about 100 bytes per placement plus the + models of the chunk being written, not a copy of every placed model.""" + counts = _placement_counts() + for outcome in ("placed", "placed_unverified", "unresolved_archetype", "key_mismatch", "model_not_loadable", + "degenerate_scale", "mirrored"): + counts[outcome] = 0 + index = model_name_index(entries, _get_world_names()) + model_ids: dict[tuple[str, str], int] = {} + model_src: list[tuple[str, dict]] = [] + inst_model = array.array("l") + inst_flags = array.array("b") # bit 0 mirrored, bit 1 unverified + inst_trs = array.array("d") # 10 per instance: translation xyz, rotation xyzw, scale xyz + inst_tier = array.array("b") # lodLevel, used with lod_sets + child_lod: dict[int, array.array] = {} + lod_dist: dict[int, array.array] = {} + for row in iter_placements(placements, counts, lod_levels, region): + lvl = row.get("lod_level") + if lod_sets: + for src, dst in (("child_lod_dist", child_lod), ("lod_dist", lod_dist)): + v = row.get(src) + if isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v > 0: + dst.setdefault(lvl, array.array("d")).append(float(v)) + found, outcome = resolve_placement(index, row["_arch"], row.get("key")) + if found is None: + counts[outcome] += 1 + continue + t, q, sc, mirrored = placement_trs(row["_rot"], row["_sxy"], row["_sz"], row["_pos"]) + if sc[0] == 0 or sc[1] == 0: + counts["degenerate_scale"] += 1 + continue + models_dir, item = found + ck = (models_dir, str(item.get("File"))) + mid = model_ids.get(ck) + if mid is None: + mid = model_ids[ck] = len(model_src) + model_src.append(found) + inst_model.append(mid) + inst_flags.append((1 if mirrored else 0) | (2 if outcome == "placed_unverified" else 0)) + inst_trs.extend(t + q + sc) + inst_tier.append(lvl if lod_sets else 0) + + abs_out = os.path.abspath(out_dir) + chunks_dir = os.path.join(abs_out, "chunks") + created_dirs = [d for d in (abs_out, chunks_dir) if not os.path.isdir(d)] + os.makedirs(abs_out, exist_ok=True) + _remove_stale_staging(abs_out) + staging_dir = tempfile.mkdtemp(prefix=CHUNK_STAGING_PREFIX, dir=abs_out) + pack_dir = os.path.join(staging_dir, "packs") + os.makedirs(pack_dir) + try: + jobs = [] + for mid, (models_dir, item) in enumerate(model_src): + rel_file = item.get("File") + obj_path = os.path.join(models_dir, rel_file) if isinstance(rel_file, str) and rel_file.strip() else "" + tex_map = resolve_model_textures(models_dir, item, ttpf_index, base_color_param) if textures else {} + jobs.append((mid, obj_path, _list_field(item, "MeshShaders"), tex_map, textures, + os.path.join(pack_dir, f"{mid}.lpk"))) + info: list[dict | None] = [None] * len(model_src) + for mid, summary in _run_jobs(_pack_model_job, jobs, workers): + info[mid] = summary + del jobs + + cells: dict[tuple[int, int], array.array] = {} + for i in range(len(inst_model)): + summary = info[inst_model[i]] + if summary is None: + counts["model_not_loadable"] += 1 + continue + counts["placed_unverified" if inst_flags[i] & 2 else "placed"] += 1 + counts["mirrored"] += inst_flags[i] & 1 + box = summary["box"] + if inst_flags[i] & 1: + box = [box[0], -box[4], box[2], box[3], -box[1], box[5]] + v = inst_trs[i * 10:i * 10 + 10] + b = glb_mod.instance_bounds(box[:3], box[3:], v[0:3], v[3:7], v[7:10]) + key = (inst_tier[i], math.floor(0.5 * (b[0] + b[3]) / chunk_size), + math.floor(0.5 * (b[2] + b[5]) / chunk_size)) + cells.setdefault(key, array.array("l")).append(i) + used = {inst_model[i] for arr in cells.values() for i in arr} + counts["distinct_models"] = len(used) + if not cells and limit != 0: + raise ValueError(f"No entity in {placements} could be placed ({counts}); output left unchanged") + + packs = {mid: os.path.join(pack_dir, f"{mid}.lpk") for mid in used} + + def chunk_id(tier, ix, iz): + return f"c_{LOD_TIER_NAMES[tier]}_{ix}_{iz}" if lod_sets else f"c_{ix}_{iz}" + + def chunk_jobs(): + for (tier, ix, iz), arr in sorted(cells.items()): + insts = [] + mids = set() + for i in arr: + v = inst_trs[i * 10:i * 10 + 10] + mid = inst_model[i] + mids.add(mid) + insts.append((mid, bool(inst_flags[i] & 1), tuple(v[0:3]), tuple(v[3:7]), tuple(v[7:10]))) + dds = {} + for mid in mids: + dds.update(info[mid]["mat_to_dds"]) + yield (chunk_id(tier, ix, iz), staging_dir, mode, insts, {m: packs[m] for m in mids}, dds, + textures, max_tex_size) + + chunks = [] + total_triangles = stored_triangles = textures_embedded = textures_skipped = 0 + total_bytes = max_bytes = 0 + cell_keys = iter(sorted(cells)) + for rec, embedded, skipped, size in _run_jobs(_build_chunk_job, chunk_jobs(), workers): + tier, ix, iz = next(cell_keys) + if lod_sets: + rec["lod"] = LOD_TIER_NAMES[tier] + rec["cell"] = [ix * chunk_size, iz * chunk_size, (ix + 1) * chunk_size, (iz + 1) * chunk_size] + chunks.append(rec) + total_triangles += rec["triangles"] + stored_triangles += rec["stored_triangles"] + textures_embedded += embedded + textures_skipped += skipped + total_bytes += size + max_bytes = max(max_bytes, size) + shutil.rmtree(pack_dir, ignore_errors=True) + + bands = measured = None + if lod_sets: + present = sorted({k[0] for k in cells}) + bands, measured = lod_bands(child_lod, lod_dist, present) + for name, m in measured.items(): + m["chunks"] = sum(1 for c in chunks if c["lod"] == name) + m["placements"] = sum(c["models"] for c in chunks if c["lod"] == name) + world_doc = { + "spawn": _compute_spawn([c for c in chunks if c.get("lod", "hd") in ("hd", "orphan_hd")] or chunks), + "chunk_size": float(chunk_size), + "layout": "placements", + "instancing": mode, + "chunks": chunks, + "stats": { + "models": counts["placed"] + counts["placed_unverified"], + "chunks": len(chunks), + "triangles": total_triangles, + "stored_triangles": stored_triangles, + "chunk_bytes": total_bytes, + "max_chunk_bytes": max_bytes, + "textures_embedded": textures_embedded, + "textures_skipped": textures_skipped, + "placements": dict(counts), + }, + } + if lod_sets: + world_doc["lod_bands"] = bands + world_doc["stats"]["lod_tiers"] = measured + _publish_world(staging_dir, chunks_dir, [f"{c['id']}.glb" for c in chunks], + os.path.join(abs_out, "world.json"), world_doc, glb_mod) + except BaseException: + if not _holds_unrestored_chunks(staging_dir): + shutil.rmtree(staging_dir, ignore_errors=True) + for d in reversed(created_dirs): + try: + os.rmdir(d) + except OSError: + pass + raise + shutil.rmtree(staging_dir, ignore_errors=True) + _prune_stale_chunks(chunks_dir, {f"{c['id']}.glb" for c in world_doc["chunks"]}) + return world_doc + + SPAWN_SPAN_CAP = 1200.0 @@ -496,6 +987,32 @@ def resolve_model_textures( return result +def _assign_materials(prims: list[dict], mesh_shaders: list, tex_map: dict, textures: bool) -> dict[str, str]: + """Set each primitive's ``material`` key from its shader's resolved DDS; returns key -> DDS path.""" + mat_to_dds: dict[str, str] = {} + for p in prims: + gidx = p.get("group_index", 0) + if isinstance(gidx, int) and not isinstance(gidx, bool) and 0 <= gidx < len(mesh_shaders): + sidx = mesh_shaders[gidx] + else: + sidx = gidx + has_uv = bool(p.get("uvs")) + if ( + textures + and has_uv + and isinstance(sidx, int) + and not isinstance(sidx, bool) + and sidx in tex_map + ): + dds_path = os.path.abspath(tex_map[sidx]) + mat_key = f"tex_{os.path.normcase(dds_path)}" + p["material"] = mat_key + mat_to_dds[mat_key] = dds_path + else: + p["material"] = "" + return mat_to_dds + + def _translate_primitives(prims: list[dict], dx: float, dy: float, dz: float) -> None: """Translate primitive vertex positions in-place by (dx, dy, dz).""" if dx == 0.0 and dy == 0.0 and dz == 0.0: @@ -793,6 +1310,8 @@ def build_world( placements: str | None = None, lod_levels=DEFAULT_LOD_LEVELS, region=None, + instancing: str = "gpu", + lod_sets: bool = False, ) -> dict: """Build world.json and chunk .glb files from rpf9dump asset exports. @@ -831,6 +1350,12 @@ def build_world( raise FileNotFoundError(f"placements file does not exist: {placements}") if region is not None and (len(region) != 4 or not (region[0] < region[2] and region[1] < region[3])): raise ValueError(f"region must be MINX,MINY,MAXX,MAXY with min < max, got {region!r}") + if instancing not in INSTANCING_MODES: + raise ValueError(f"instancing must be one of {INSTANCING_MODES}, got {instancing!r}") + if lod_sets and instancing == "bake": + raise ValueError("--lod-sets needs --instancing gpu or nodes") + elif lod_sets: + raise ValueError("--lod-sets needs --placements") workers = max(1, int(jobs)) if not os.path.exists(assets_dir): @@ -860,6 +1385,14 @@ def build_world( ttpf_index = index_ttpf_textures(assets_dir) if textures else {} + if placements is not None and instancing != "bake": + return _build_instanced_world( + entries, ttpf_index, placements=placements, lod_levels=lod_levels, region=region, out_dir=out_dir, + chunk_size=chunk_size, textures=textures, max_tex_size=max_tex_size, + base_color_param=base_color_param, workers=workers, mode=instancing, glb_mod=glb_mod, limit=limit, + lod_sets=lod_sets, + ) + def load_model(models_dir: str, item: dict, axis: str) -> dict | None: rel_file = item.get("File") if not isinstance(rel_file, str) or not rel_file.strip(): @@ -882,30 +1415,7 @@ def build_world( if textures else {} ) - mesh_shaders = _list_field(item, "MeshShaders") - mat_to_dds: dict[str, str] = {} - - for p in prims: - gidx = p.get("group_index", 0) - if isinstance(gidx, int) and not isinstance(gidx, bool) and 0 <= gidx < len(mesh_shaders): - sidx = mesh_shaders[gidx] - else: - sidx = gidx - has_uv = bool(p.get("uvs")) - if ( - textures - and has_uv - and isinstance(sidx, int) - and not isinstance(sidx, bool) - and sidx in tex_map - ): - dds_path = os.path.abspath(tex_map[sidx]) - mat_key = f"tex_{os.path.normcase(dds_path)}" - p["material"] = mat_key - mat_to_dds[mat_key] = dds_path - else: - p["material"] = "" - + mat_to_dds = _assign_materials(prims, _list_field(item, "MeshShaders"), tex_map, textures) return {"prims": prims, "bounds": bounds, "mat_to_dds": mat_to_dds} loaded_models: list[dict] = [] @@ -1250,7 +1760,8 @@ def main(argv: list[str] | None = None) -> int: type=_positive_int, default=1, metavar="N", - help="Number of worker threads for parallel chunk building (default: %(default)s).", + help="Number of parallel workers: threads for chunk building, or processes for packing models and " + "writing chunks with --placements (default: %(default)s).", ) ap.add_argument( "--base-color-param", @@ -1282,7 +1793,26 @@ def main(argv: list[str] | None = None) -> int: metavar="MINX,MINY,MAXX,MAXY", help="With --placements: only entities whose RAGE world X/Y position lies in this box (metres).", ) + ap.add_argument( + "--instancing", + choices=INSTANCING_MODES, + default="gpu", + help="With --placements: 'gpu' stores each model once per chunk and draws its placements with " + "EXT_mesh_gpu_instancing (default); 'nodes' writes one plain glTF node per placement for loaders " + "without that extension; 'bake' copies the geometry into every placement (memory grows with the " + "number of placements).", + ) + ap.add_argument( + "--lod-sets", + action="store_true", + help="With --placements: one chunk set per LOD tier (HD, LOD, SLOD1-4, ORPHAN_HD; all lodLevel values " + "unless --lod-levels is given), plus each tier's camera distance band in world.json, measured from the " + "entities' childLodDist/lodDist, so the viewer shows one tier per grid cell.", + ) args = ap.parse_args(argv) + lod_levels = args.lod_levels + if args.lod_sets and not any(a == "--lod-levels" or a.startswith("--lod-levels=") for a in (argv or sys.argv[1:])): + lod_levels = ALL_LOD_LEVELS try: result = build_world( @@ -1297,15 +1827,17 @@ def main(argv: list[str] | None = None) -> int: jobs=args.jobs, base_color_param=args.base_color_param, placements=args.placements, - lod_levels=args.lod_levels, + lod_levels=lod_levels, region=args.region, + instancing=args.instancing, + lod_sets=args.lod_sets, ) except (FileNotFoundError, ValueError, OSError) as exc: print(f"ERROR: {exc}", file=sys.stderr) return 1 st = result["stats"] print( - f"world built: {st['models']} models -> {st['chunks']} chunks, " + f"world built: {st['models']} {'placements' if 'placements' in st else 'models'} -> {st['chunks']} chunks, " f"{st['triangles']} tris, {st['textures_embedded']} textures " f"({st['textures_skipped']} skipped) -> {os.path.abspath(args.out)}", flush=True, diff --git a/viewer/index.html b/viewer/index.html index 742006c25..dfc6dad4b 100644 --- a/viewer/index.html +++ b/viewer/index.html @@ -48,6 +48,8 @@ import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; // ---------- world description ---------- // world/world.json: { "spawn": [x,y,z], "chunks": [ { "id", "url", "bounds": [minx,miny,minz,maxx,maxy,maxz] } ] } +// A world built with world_build --lod-sets also has "lod_bands": { tier: [start, end] } (metres), and each +// chunk names its "lod" tier and its grid "cell": [minx, minz, maxx, maxz]. // Each chunk is a .glb in world space (Y up, metres). Validate the manifest before // the camera and streaming code use its coordinates and chunk identifiers. function manifestError(world) { @@ -63,6 +65,14 @@ function manifestError(world) { const b = chunk.bounds; if (!isPosition(b, 6) || b[0] > b[3] || b[1] > b[4] || b[2] > b[5]) return `chunks[${i}].bounds must contain six finite, ordered coordinates`; + if (chunk.lod !== undefined) { + const band = world.lod_bands?.[chunk.lod]; + if (!isPosition(band, 2) || band[0] < 0 || band[0] > band[1]) + return `chunks[${i}].lod must name a lod_bands entry with two finite, ordered distances`; + const c = chunk.cell; + if (!isPosition(c, 4) || c[0] > c[2] || c[1] > c[3]) + return `chunks[${i}].cell must contain four finite, ordered coordinates`; + } ids.add(chunk.id); } return null; @@ -242,6 +252,21 @@ function dist(c, p) { const dx = Math.max(b[0] - p.x, 0, p.x - b[3]), dy = Math.max(b[1] - p.y, 0, p.y - b[4]), dz = Math.max(b[2] - p.z, 0, p.z - b[5]); return Math.hypot(dx, dy, dz); } +// LOD sets: every grid cell has one chunk per detail tier, and a tier is shown only while the camera's +// horizontal distance to the cell lies in that tier's band, so one tier per cell is drawn. LOD_SLACK +// keeps a loaded tier a little past its band so crossing an edge does not reload it every frame. +const LOD_SLACK = 32; +function cellDist(c, p) { + const r = c.cell; + return Math.hypot(Math.max(r[0] - p.x, 0, p.x - r[2]), Math.max(r[1] - p.z, 0, p.z - r[3])); +} +// The distance used to rank a chunk, and whether it should load (slack 0) or stay loaded (LOD_SLACK). +function range(def, p) { + const band = def.lod !== undefined ? world.lod_bands?.[def.lod] : undefined; + if (!band) { const d = dist(def, p); return { d, load: d < LOAD_R, keep: d <= UNLOAD_R }; } + const d = cellDist(def, p); + return { d, load: d >= band[0] && d < band[1], keep: d >= band[0] - LOD_SLACK && d < band[1] + LOD_SLACK }; +} function drop(id) { const c = live.get(id); if (!c) return; live.delete(id); @@ -279,7 +304,7 @@ async function loadChunk(entry) { function stream(now = performance.now()) { const p = camera.position; for (const [id, c] of live) { - if ((!c.obj && !c.loading) || dist(c.def, p) <= UNLOAD_R) continue; + if ((!c.obj && !c.loading) || range(c.def, p).keep) continue; drop(id); // A canceled retry does not erase the previous failures or spend another attempt. if (c.previous) live.set(id, c.previous); @@ -291,8 +316,8 @@ function stream(now = performance.now()) { for (const def of world.chunks) { const entry = live.get(def.id); if (entry && (entry.obj || entry.loading || entry.attempts >= MAX_LOAD_ATTEMPTS || now < entry.retryAt)) continue; - const distance = dist(def, p); - if (distance < LOAD_R) want.push({ def, distance }); + const { d: distance, load } = range(def, p); + if (load) want.push({ def, distance }); } want.sort((a, b) => a.distance - b.distance); for (const { def } of want) {