diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d764539cb..b18a22eb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,8 +4,42 @@ on: [push, pull_request] permissions: contents: read +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + jobs: + change-scope: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + outputs: + docs-only: ${{ steps.paths.outputs.docs-only }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + - name: Check whether only documentation changed + id: paths + shell: pwsh + run: | + # A pull_request checkout is the test merge; its first parent is the PR base. + # Treat missing history, an empty diff, and renames out of code conservatively. + $PSNativeCommandUseErrorActionPreference = $false + $docsOnly = $false + git diff --quiet "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- + if ($LASTEXITCODE -eq 1) { + git diff --quiet --no-renames "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- . ` + ':(exclude,top)README.md' ':(exclude,top)CONTRIBUTING.md' ` + ':(exclude,top)AGENTS.md' ':(exclude,top)SECURITY.md' ':(exclude,top,glob)docs/**/*.md' + $docsOnly = $LASTEXITCODE -eq 0 + } + "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT + exit 0 # GitHub's pwsh wrapper would otherwise forward git diff's status. + check: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: windows-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -36,6 +70,8 @@ jobs: bad=$(git ls-files | grep -iE '\.(rpf|ttpf|xvd|dxbc|fssm|spv|spvasm|dds|bk2|awc|exe|dll)$' || true) if [ -n "$bad" ]; then echo "Game or binary files tracked:"; echo "$bad"; exit 1; fi translator-tests: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: ubuntu-24.04 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -50,6 +86,8 @@ jobs: - name: Translator tests run: python -m pytest tests -q --ignore=tests/semantic semantic-tests: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: ${{ matrix.os }} strategy: matrix: @@ -63,6 +101,8 @@ jobs: run: python -m unittest discover -s tests/semantic -v viewer-tests: + needs: change-scope + if: ${{ !cancelled() && needs.change-scope.outputs.docs-only != 'true' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/AGENTS.md b/AGENTS.md index bb9a75a58..8b1052725 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,9 @@ loader that maps the game's executable and resolves its imports to shims. Nothin Check its tables and the open pull requests first. If someone has claimed the item or has a pull request for it, stop and tell the user instead of writing it a second time. - Put the item ID from #156 in the pull request, and `Depends on: #N` for every pull request yours builds on. +- For the D3D12 → Vulkan layer (`runtime/shims/d3d12_*`, `runtime/src/vulkan_*`), also read + [#313](https://github.com/ItsNotRexed/Leonida/issues/313): most of that work builds on a few open pull requests, + and it lists which D3D12 methods are still open. ## Before you guess, look diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 24f2627e2..e29ffeb0f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,7 +15,9 @@ Thanks for helping. A few rules keep the project safe to host: Claim the work in [#156](https://github.com/ItsNotRexed/Leonida/issues/156) first: check its tables and the open pull requests, post `claiming: ` there (or a one-line description for something not listed yet), and put the ID in your pull request. When two pull requests overlap anyway, the one that lands first is merged and the other is -asked to rebase or close. GPU test results go in [#166](https://github.com/ItsNotRexed/Leonida/issues/166). +asked to rebase or close. GPU test results go in [#166](https://github.com/ItsNotRexed/Leonida/issues/166). Work on +the D3D12 → Vulkan layer has its own page, [#313](https://github.com/ItsNotRexed/Leonida/issues/313): the critical +path, who builds what, and which D3D12 methods are still open. ## Working on the code @@ -36,6 +38,7 @@ asked to rebase or close. GPU test results go in [#166](https://github.com/ItsNo - GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. `build.py` there turns them into SPIR-V (it needs `llvm-mc`, so WSL or a Linux container), and `check.py` runs them on your GPU and compares the results. A new test gets its expected values in the comment at its top and a check in `check.py`. + [docs/testing.md](docs/testing.md) has the setup per OS and the problems testers have run into. - Say what you tested and on which GPU in the pull request. - Run the translator tests with `python -m unittest discover -s tests/semantic -v` (see `tests/semantic/README.md`). A new translator rule should come with a small hand-written `.asm` fixture and its expected output words. diff --git a/README.md b/README.md index cc51cc5e9..d68d2d296 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ work on booting can start as soon as one is available to a developer. | Texture dictionaries and world texture pools (DDS) | ✅ Exported. Some pool entries (BCPack) are skipped | | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | -| PE loader and import shims | ⚠️ Skeleton. Untested against the real executable | +| PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Untested against the real executable | | Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, views and committed resources; barriers, clears, uploads and copies (BC included) run on Vulkan, checked on one GPU. No shader views, pipelines, draws or swapchain yet ([plan](docs/d3d12_vulkan.md)) | | Booting, story mode, anything playable | ❌ No | diff --git a/docs/README.md b/docs/README.md index 3a885352a..d21196a04 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,6 +11,7 @@ method, scope and caveats. No game data is included. | [design.md](design.md) | Overall project design, asset status, translator contract and open blockers. | | [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. | | [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | +| [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, and known problems. | ## Archives and assets @@ -24,6 +25,7 @@ method, scope and caveats. No game data is included. | [bvh.md](bvh.md) | 565,596 `core_bvh4.rpf` streams; 271,627 BVH4 streams and 269,106 instances, prebuilt acceleration data. | | [rbf0.md](rbf0.md) | 1,263 RBF0 resources, 475,461 elements; UI/Scaleform definitions, not a sectioned container; strict JSON/CSV/XML tree decoder. | | [gamedata.md](gamedata.md) | `common.rpf`: 954 streams, 266 XML documents / 118 roots; 0 RBF0/PSIN. | +| [gamedata_graph.md](gamedata_graph.md) | `common.rpf` mount graph: 25 manifest documents, 30 content-set ids, 14 include refs (12 resolve), 3,386 target refs, 0 cycles. | | [world.md](world.md) | `levels.rpf` placement: 9,918 map files / 680,228 entities measured in 55% of the archive (lower bound; estimate 16k-39.6k / 1.03M-2.64M); `0x7a` resource layout. | | [world_census.md](world_census.md) | Full `levels.rpf` pass: 23,535 maps / 1,670,442 entities, 98.32% stream coverage, sharded and exact. | | [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. 79,738 local names resolve 8,263/203,799 sampled entities; 5/23,535 map names, all five confirmed by the map 64-bit key. | diff --git a/docs/animation.md b/docs/animation.md index 8d082eb24..8fa1a27dc 100644 --- a/docs/animation.md +++ b/docs/animation.md @@ -390,7 +390,9 @@ python -I tools/anim_index.py \anim-carve \anim-index.json ``` `tools/anim_index.py` reports `MoVE`, `0DRP`, `pack:/`, `SKEL_`, `RBF0`, `PSIN`, type-hash and 2/3 clip headers, -plus `raw:` for anything it does not recognise. It writes no payloads. +plus `raw:` for anything it does not recognise. It writes no payloads. `--start` must be 0 or more and +`--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a one-line error and exit code 2 +before an index is written. ## No-sharing rule diff --git a/docs/bvh.md b/docs/bvh.md index 9439b800f..aa784ba8d 100644 --- a/docs/bvh.md +++ b/docs/bvh.md @@ -67,25 +67,88 @@ inflated bytes belong to the BVH family. The archive is not a mixed asset pack. **Verified** on 271,627 complete streams and 10 chunked streams (271,637/271,637): -* 32-bit tag `0x81020006` at offset `0x100`. -* `u32@0x104` = size of the node area in 64-byte units. -* `u32@0x20` = `0x140 + 64 * size_in_64b_units` (end of the declared node area). -* `u32@0x28` = `u32@0x20 - 0x100` (a 256-byte tail table inside the node area). -* `0x140` is the first 64-byte node; the declared node area ends at `u32@0x20`. -* `0x110` holds six floats consistent with a 3D AABB (`min xyz`, `max xyz`). In `core_bvh4.rpf` all 271,627 - complete streams are ordered (`min <= max` on every axis); in `shared_minigame000_bvh4.rpf` 1,184 of 1,237 are - ordered and 53 are not (sentinel or non-finite values). -* `0x108` is a hash-like 32-bit value; `0x10C` is a small varying word. -* `0x130`/`0x134`/`0x138` are an offset, an even byte size and a signed base. The pointed range is inside the - stream and is often a near-monotonic `u16` sequence (274/400 sampled streams non-zero; 127/400 monotonic). This - is consistent with a primitive/index remap table, not with a vertex buffer, but the exact role is **Open**. -* The 256-byte tail at `u32@0x28` contains `u32` tables, including groups of four references that begin with - `0x04000000` in the sample. The node/table encoding was not decoded. +* The 64-byte `XboxBvh4Header` begins at payload offset `0x100`. Its `flags` word is `0x81020006` in these + packs. +* `u32@0x20` = `0x140 + 64 * totalSizeIn64BNodes` (the declared end of the 64-byte node address space). +* `u32@0x28` = `u32@0x20 - 0x100`. These two words sit before the header and are not header fields. +* `0x110` holds six floats for `sceneBounds` (`min xyz`, `max xyz`). In `core_bvh4.rpf` all 271,627 complete + streams are ordered (`min <= max` on every axis); in `shared_minigame000_bvh4.rpf` 1,184 of 1,237 are ordered + and 53 are not (sentinel or non-finite values). + +The field names and offsets now match the public `XboxBvh4Header` used by the Xbox DXR traversal shaders: + +| header offset | field | sample value | +|---|---|---:| +| `0x100` | `flags` | `0x81020006` | +| `0x104` | `totalSizeIn64BNodes` | 9,943 | +| `0x108` | `crc32` | `0xeab7667e` | +| `0x10c` | `numElements` | 5,447 | +| `0x110` | `sceneBounds.min` (3 floats) | `-47.416, -25.742, -5.624` | +| `0x11c` | `sceneBounds.max` (3 floats) | `47.416, 25.742, 5.624` | +| `0x128` | `offsetToNodes` | `0x59480` | +| `0x12c` | `offsetToPrimRemap` | 0 | +| `0x130` | `rootNodePtr` | `0x136ac` | +| `0x134` | `offsetToElements` | `0x4280` | +| `0x138` | `offsetToParents` | `0xffffab40` | +| `0x13c` | `compressionParams` | `0x808c8a89` | + +The offsets are relative to the header at `0x100`, not to the start of the payload. In the sample, +`offsetToNodes` therefore addresses `0x59580` and `offsetToElements` addresses `0x4380`. The node and element +regions are not necessarily the simple `0x140` onward array that the first indexer assumed. `offsetToParents` +is a raw `u32`; its signed/relative interpretation is still **Open**. + +The `flags` word has version `6` in its low 16 bits. It also sets `0x80000000` (bottom level), `0x00020000` +(offline) and `0x01000000` (dehydrated). It does not set `0x00010000` (compressed). The sample is therefore a +bottom-level, offline, dehydrated BVH, not a ready-to-traverse runtime tree. The name "BVH4" is the builder's own: `XboxBvh4Header`, `ConstructBVH4`, `RefitBVH4`, `PT_ConstructBVH4` and `totalSizeIn64BNodes` appear in `XboxBvhBuilder.dll`. The measured field at `0x104` is a count of 64-byte units whose product plus `0x140` lands exactly on the end pointer in 271,627/271,627 complete streams. That agrees with -the builder's naming but does not prove that `0x81020006` is the builder's header tag. +the builder's naming. + +#### Node pointers and the runtime node records + +A `rootNodePtr` or child pointer packs the node type in the low three bits and a 64-byte unit index in the high +29 bits: + +``` +type = ptr & 7 +node_address = header + (ptr >> 3) * 64 +``` + +The type values are `0..3` = `TRI0..TRI3`, `4` = `BOX16`, `5` = `BOX32`, `6` = `INSTANCE`, `7` = +`AABB_GEOMETRY`. `0xffffffff` is the invalid pointer. A `BOX32` node occupies 128 bytes, so it consumes two +64-byte units; all other node records occupy 64 bytes. + +The runtime records, which are what the traversal shaders read, are: + +| record | size | layout | +|---|---:|---| +| `Node16` | 64 | four `u32` children at `+0`; four 12-byte half-float bounds at `+16` | +| `Node32` | 128 | four `u32` children at `+0`; four 24-byte float bounds at `+16`; four padding words at `+112` | +| `Leaf` | 64 | four `float3` vertices at `+0`; `GeometryIndexAndFlags` at `+48`; `BasePrimitiveIndex` at `+52`; `PrimitiveIndex2` at `+56`; `baryRemap` at `+60` | + +The `Node16` bounds are six IEEE half values packed into three `u32` words. The shader expands them with +`XdxrDecompressBox16`; the first word holds `min.x`/`min.y`, the second `min.z`/`max.x`, and the third +`max.y`/`max.z`. + +For the sample, `rootNodePtr = 0x136ac` decodes to index 9941, type `BOX16`, at payload address `0x9b640`. +That record begins `0x04000000, 0x13694, 0x1369c, 0x117b5`, so its first child is not a valid runtime +pointer. This is the dehydrated form, not a runtime `Node16`. + +#### Packed dehydrated forms + +The same public headers define the packed records used before rehydration: + +| record | size | layout | +|---|---:|---| +| `NodePacked` | 16 | four `u32` children | +| `LeafPacked` | 12 | `GeometryIndexAndFlags`, `BasePrimitiveIndex`, `PrimitiveIndex2AndBaryRemap` | +| `BVVDHeader` | 8 | `variantNodeIndex` plus a six-bit mask and two-bit child selector | + +The dehydrated stream is not a contiguous array of runtime `Node16` records. Its record order, the `BVVDHeader` +table and the exact traversal of `NodePacked`/`LeafPacked` remain **Open**. A decoder must not feed the sample +root to the runtime traversal path until that packing is understood. ### 3.2 Instance descriptor (208 bytes) @@ -184,21 +247,23 @@ into three 64 KiB/26 KiB chunks. These list the per-tile BVH packs; they are the 3. **Pair descriptor to buffer.** The 208-byte descriptor precedes its BVH chunk in stream order in 269,106/269,106 cases. The other descriptor sizes account for 2,528 more BVH buffers; 3 more are preceded by other streams. -4. **Parse the header, then stop guessing.** `0x81020006`, `n64`, end, root, AABB and the `0x130` table can be read - now. The 64-byte node encoding (child references, box encoding, leaf form) is still **Open** and must be - recovered against `XboxBvh4Header`/`ConstructBVH4` or by validation, not assumed. +4. **Parse the header, then stop guessing.** The exact header table, node pointer encoding and runtime + `Node16`/`Node32`/`Leaf` records are in section 3.1. The packed dehydrated stream (`NodePacked`, `LeafPacked`, + `BVVDHeader`) remains **Open**; do not infer a runtime child array from the `0x140` slot space. 5. **Skip fill.** Ignore all-zero nodes and the `0x81`/`0x94`/`0x29` repeated blocks; they are not primitives. 6. **Do not feed these nodes to the AMD traversal.** The translator's `image_bvh_intersect_ray` path expects the - AMD hardware node format (256-byte base units), while these payloads use the builder's 64-byte units. A - converter or a rebuild is required; see `docs/d3d12_vulkan.md` §4.8. -7. **Result format.** Any decoder should emit world-space bounds plus primitive references, and validate counts - against the header (`0x140 + 64*n == end`, ordered AABB) before use. + AMD hardware node format (256-byte base units), while these payloads use the builder's 64-byte units. The + sample is also dehydrated, so its root is not a runtime child array. A rehydrator, converter or rebuild is + required; see `docs/d3d12_vulkan.md` §4.8. +7. **Result format.** Any decoder should emit world-space bounds plus primitive references, and validate the + wrapper (`0x140 + 64*n == end`, `u32@0x28 == end - 0x100`) and ordered AABB before use. ## 7. Tooling `tools/bvh_index.py` (standard library only) scans an RPF9 archive or a directory of `.rpf`/`.bin` payloads and -writes JSON and/or CSV with offset, stored size, inflated size, kind, signature, node count, root offset, declared -bytes, bounds, descriptor key/transform and fill counts. It reads only headers and emits no payload bytes. +writes JSON and/or CSV with offset, stored size, inflated size, kind, signature, node count, tail offset, the +`XboxBvh4Header` fields, root pointer/index/type, declared bytes, bounds, descriptor key/transform and fill +counts. It reads only headers and emits no payload bytes. ```powershell python -I tools/bvh_index.py --out index.json --csv index.csv @@ -211,10 +276,11 @@ the end of the archive, stops the tool with a one-line error and exit code 2. An than its 8-byte header, has no streams. In directory mode an archive that cannot be read is reported on stderr as `skipped` and the other archives are still indexed. -The `bvh4` signature is reported only when the tag, the `0x140 + 64*n == end` formula and the `root == end - 0x100` -relation all hold; a larger payload whose declared end is past the chunk but which is a 64 KiB multiple is reported -as `bvh4-chunk`. The synthetic tests cover the tag, the formula rejection, the chunk case, the 208-byte template, -the other descriptor template, XML and XML fragments, the two-stream advance bug and CSV/JSON output. +The `bvh4` signature is reported only when `flags == 0x81020006`, the `0x140 + 64*n == end` formula and the +`u32@0x28 == end - 0x100` wrapper relation all hold; a larger payload whose declared end is past the chunk but +which is a 64 KiB multiple is reported as `bvh4-chunk`. The synthetic tests cover the tag, the formula rejection, +the exact header fields and root pointer/type, the chunk case, the 208-byte template, the other descriptor +template, XML and XML fragments, the two-stream advance bug and CSV/JSON output. Measured with the tool on `shared_minigame000_bvh4.rpf`: 2,560 streams, 59,142,787 stored, 970,044,012 inflated, 1,237 complete `bvh4`, 1,233 `instance208`, 85 descriptors, 5 XML. That matches the carver summary exactly. diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2dc43ac00..0c1c03571 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -150,7 +150,7 @@ What is implemented (all of it testable without the game): - **IR** (`runtime/src/command_list.h`): legacy barriers (transition, UAV, aliasing; split barriers record their end half), enhanced barriers (global, buffer, texture; the half with `SyncAfter = SPLIT` is dropped and the other is replayed as a full barrier), `ClearRenderTargetView` / `ClearDepthStencilView`, whole view or rectangles, - `CopyBufferRegion` / `CopyTextureRegion` / `CopyResource`, and `ResolveSubresource`. + `CopyBufferRegion` / `CopyTextureRegion` / `CopyResource`, and colour resolves. Views and rectangles are copied while recording, so the CPU descriptor slot can be rewritten afterwards. - **Replay** (`runtime/src/vulkan_replay.h`): `prepare` resolves and checks a list without writing anything, `emit` writes it. Legacy states map through the section 4.3 table (`vulkan_access`), enhanced barriers through @@ -163,9 +163,11 @@ What is implemented (all of it testable without the game): in place in `GENERAL` when the texture is in `COMMON`: that is D3D12's implicit promotion to a copy state. A 3D mip is one subresource. Boxed volume transfers preserve the full footprint's row and slice strides. `ResolveSubresource` becomes `vkCmdResolveImage` in the same layouts as a copy: a multisampled colour - subresource into a single-sampled one of the same size and format. Depth-stencil resolves, and resolves between - two formats of one typeless family, are refused as unsupported. A multisampled texture copies only to one with - the same sample count and has no footprint. + subresource into a single-sampled one of the same size and format. `ResolveSubresourceRegion` uses the same + Vulkan operation for non-integer colour with average mode, taking a source rectangle (or the entire subresource) + and a destination offset. Depth-stencil resolves, other resolve modes, and resolves between two formats of + one typeless family remain open. A multisampled texture copies only to one with the same sample count and has + no footprint. - **Layout tracking** (`LayoutTracker`): the current Vulkan layout of every image subresource, so barriers start from the real layout instead of the application's `before`. This is how implicit promotion and decay work: a texture in `COMMON` sits in `GENERAL`, which every promotable access can use, so a later barrier naming the @@ -240,11 +242,10 @@ Two pieces of milestone M2 that the device does not use yet, built and tested on either, so the owner can wait until no command buffer that uses the set is still running. Known gaps: shader-resource, UAV and constant-buffer views, samplers, root signatures, PSOs, draws, volume attachment -views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), depth-stencil resolves and -`ResolveSubresourceRegion`, 1D textures and the swapchain; +views, placed and reserved resources, `GetGPUVirtualAddress` (the shared buffer arena), depth-stencil resolves, +1D textures and the swapchain; default-heap buffers are not zero-filled yet; a fence cannot be signalled to a lower value (Vulkan timelines only -increase; such a signal is reported and dropped); enhanced-barrier access bits are not filtered against the -sync scope, so a combination D3D12 accepts but Vulkan does not would show up as a validation error; the GCL8 +increase; such a signal is reported and dropped); the GCL8 front/back stencil references are recorded but not applied, because there is no pipeline or draw path for them to affect. @@ -266,6 +267,9 @@ and any validation error fails them. and read back; a 4x multisampled target cleared and resolved; and the copies and resolves that must be refused (a z range past the volume or its footprint, a footprint past the buffer, a resolve from a single-sampled texture or into another size, a multisampled texture copied to a footprint or to another sample count). +- `vk_command_replay_test`, part D: every D3D12 sync bit against every access bit (360 pairs), each as a global, + a buffer and a texture barrier. Under the validation layer none may be rejected; before + `vulkan_barrier_scope` there were 462 validation errors on Intel(R) Graphics. - `vk_bindless_test` (run by `runtime/test/shaders/check.py` and `scripts/run_gpu_tests.py`): the translator's own lookup against the table and the set. `ps_tex.asm`, a hand-written RDNA2 pixel shader built by `build.py`, loads a T# and an S# from a descriptor table and samples. The test draws the gradient with the T# at the fourth @@ -456,6 +460,17 @@ Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature a the build on the first contradiction. Until the console mapping in §3.5 is confirmed by a PSO, this check — not a rendered frame — is the acceptance gate for the mapping above. +Blob format: `rt::rootsig::parse_rts0` reads the `RTS0` chunk of a serialized root signature, versions 1.0, 1.1 +and 1.2. `root_signature_oracle_test` checks it on Windows against blobs the PC `d3d12.dll` serializes. These +layouts are measured, not assumed: +- a descriptor table's payload is `{num_ranges, ranges_offset}`, with the ranges at that offset; +- ranges are 20 bytes, or 24 with the 1.1/1.2 flags dword; +- root descriptors carry a flags dword from 1.1 on; +- static samplers are 13 dwords (`D3D12_STATIC_SAMPLER_DESC` order). In 1.2 they are 14: `D3D12_STATIC_SAMPLER_DESC1` + appends `Flags`, i.e. UINT border colours and non-normalized coordinates. + +Static samplers take no user-data dwords, so 1.2 changes nothing in `pack`. + **Root-signature flag quirk.** Prior art measured Xbox root-signature descriptors carrying flags `0x03000000`; the PC serializer rejects them with `E_INVALIDARG` because its flags live in the low 16 bits. Clear the high byte on a private copy before calling the host serializer/deserializer; never modify the game's descriptor. The meaning of the @@ -602,7 +617,15 @@ The trace will enumerate them. arena's limits, not the console's. - `GetResourceAllocationInfo` and `GetCopyableFootprints`: implement D3D12's rules locally; the game uses them to suballocate and to lay out uploads. They are deterministic and public. Validate against a host D3D12 device in - tests if one is available; do not require one at runtime. + tests if one is available; do not require one at runtime. `GetResourceAllocationInfo` (and `1`/`2`): a buffer + takes its width rounded up to 64 KiB, aligned to 64 KiB. A texture's size is the memory its `VkImage` needs + (`vkGetDeviceImageMemoryRequirements`), rounded up to its D3D12 alignment. That alignment is 64 KiB, or 4 MiB with + MSAA. The small alignments (4 KiB, or 64 KiB with MSAA) apply only when the application asks for them. 4 KiB + also needs the texture to fit in 64 KiB and not be a render target or depth buffer; if it doesn't qualify, the + description is invalid (`UINT64_MAX`), as the PC runtime answers. The MSAA 64 KiB alignment has no size limit + on the PC runtime, so none here either. Texture sizes are the driver's on both runtimes, so only buffer sizes, + alignments and invalid descriptions are compared with the host. One known difference: a mip count beyond the + full chain is invalid here (Vulkan can't create it), while the PC runtime still answers with a size. ### 4.2 Resources, heaps, placed and reserved @@ -638,11 +661,19 @@ The trace will enumerate them. images copy dimension, format, mip levels, array layers and sample count. - Copies: `CopyBufferRegion` → `vkCmdCopyBuffer` with arena offsets; `CopyTextureRegion` → `vkCmdCopyBufferToImage`/`vkCmdCopyImageToBuffer`/`vkCmdCopyImage`, using the `D3D12_PLACED_SUBRESOURCE_FOOTPRINT` - row pitch and height; `CopyResource` → a whole-subresource copy; `ResolveSubresource` → `vkCmdResolveImage`. + row pitch and height; `CopyResource` → a whole-subresource copy; colour resolves → `vkCmdResolveImage`. Partial resolve regions need a shader or a region copy. - Clears: a full-subresource clear maps to `vkCmdClearColorImage`/`vkCmdClearDepthStencilImage` (UAV buffers to `vkCmdFillBuffer`); a rect clear uses `vkCmdClearAttachments` inside the rendering scope. UAV image clears use `vkCmdClearColorImage` in `GENERAL`; non-32-bit buffer patterns need a compute clear. +- **Typed UINT RTV clears:** `ClearRenderTargetView` still takes `FLOAT[4]`. For the currently exposed + `R8G8B8A8_UINT`, `R32_UINT` and `R32G32B32A32_UINT` resources, convert those values numerically into + `VkClearColorValue::uint32` for both image and rectangle clears; copying float bits gives incorrect stored + integers without a Vulkan validation error. **Measured:** Windows D3D12 on WARP and AMD RX 5700 XT clamps + negatives/NaN to zero, positive overflow/infinity to the component maximum, and truncates fractions. + `d3d12_uint_clear_test` compares full and rectangular D3D12 readbacks with WARP over seven input sets on all + three formats; `clear_color_test` checks both replay paths without a GPU, including unchanged float values. + This does not add typed-view reinterpretation of typeless resources or new integer formats. - `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` (public release note) and DCC: ignore the flag, let the Vulkan driver choose compression, and fail loudly if the game aliases a buffer over a compressed image or reads raw DCC metadata. @@ -681,6 +712,21 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a `VkPipelineStageFlags2`, `VkAccessFlags2` and `VkImageLayout` (`vulkan_sync`, `vulkan_barrier_access`, `vulkan_layout`). Queue-specific layouts map like their generic forms; ray tracing, video and split scopes use `ALL_COMMANDS`; `LayoutBefore = UNDEFINED` or the discard flag becomes `oldLayout = UNDEFINED`. +- Access bits and sync scopes are not one-to-one. D3D12 lets an access be named with a sync scope whose Vulkan + stages cannot perform it: `SYNC_ALL_SHADING` with `ACCESS_VERTEX_BUFFER` is valid D3D12, but + `VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT` needs `VERTEX_ATTRIBUTE_INPUT`, which shading stages are not. Vulkan + rejects such a barrier. `vulkan_barrier_scope` therefore widens each side's stages by the narrowest stage that + can perform each access without one. The table is the synchronization2 chapter's "supported access types". The + stages it adds: + - `DRAW_INDIRECT` for indirect arguments; + - `INDEX_INPUT` and `VERTEX_ATTRIBUTE_INPUT` for index and vertex buffers; + - all shading for constant buffers, SRVs and UAVs; + - `COLOR_ATTACHMENT_OUTPUT` for render targets; + - the fragment tests for depth/stencil; + - `ALL_TRANSFER` for copies and resolves. `CLEAR` alone cannot read, and `ALL_GRAPHICS` contains no transfer stage. + + The access itself is never dropped, so the dependency still covers everything the application named, over a + slightly larger scope. - Render passes: `BeginRenderPass`/`EndRenderPass` map to `vkCmdBeginRendering`/`vkCmdEndRendering` (dynamic rendering). The `D3D12_RENDER_PASS_BEGINNING_ACCESS`/`ENDING_ACCESS` types give the load/store ops and resolve targets. Suspending/resuming passes have no direct Vulkan equivalent; split them into two rendering scopes with @@ -879,6 +925,10 @@ contract, not a runtime bug: adds a descriptor binding and a load per `s_getpc`, but avoids growing push constants. Decide after measuring how many real PSOs have two code-base stages. +Measured per stage (all 26,503, `tools/feature_scan.py`): `s_getpc_b64` is kept to read code-embedded data in 54 +VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or +MS+PS pipeline can therefore need a code base. + **Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). On Intel Arc (Alchemist, Battlemage), Vulkan exposes the 128-byte specification minimum (`maxPushConstantsSize == 128`), which cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback. Measured per stage (all 26,503, `tools/feature_scan.py`): `s_getpc_b64` is kept to read code-embedded data in 54 VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or @@ -888,6 +938,8 @@ MS+PS pipeline can therefore need a code base. supports 128 bytes, the current 144-byte contract already fails; the layer needs a fallback (uniform buffer for the tail) regardless. +**Open:** the exact count of such PSOs; the pairing is in the executable, not in `shaders.rpf`. + ### 5.3 Descriptor T#/S# parsing The runtime needs a C++ decoder for the structures the shaders read. The fields it needs: diff --git a/docs/design.md b/docs/design.md index 0cdfbb858..0a53f1f22 100644 --- a/docs/design.md +++ b/docs/design.md @@ -239,7 +239,7 @@ How the generated SPIR-V expects the runtime to work: | Wave size | **Most of the game's shaders are wave64: 21,545 of 26,503.** An earlier marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 of 12,101 PS, 8,666 of 9,282 mesh shaders, 1,115 of 2,236 VS and 923 of 2,689 CS. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | | Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. | -| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1. **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm`. | +| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). | | Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. | | Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. | | Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip round(LOD) in gather order, coordinates clamped to the edge (**approximation**: the sampler's wrap/mirror isn't reproduced at the border). `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | @@ -249,6 +249,7 @@ How the generated SPIR-V expects the runtime to work: | 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, back to f32); 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). | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. Instructions that explicitly fuse multiply-add still emit `Fma`. | +| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). | | Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_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; before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | | Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do; not ordered: scalar loads of memory the wave wrote, and sampling an image it wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). 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). | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64: 64-wide subgroups can only be requested for compute/mesh, so graphics wave64 stays emulated 2x32 until cross-half ops go through LDS; also true for compute/mesh translated with `--wave64-emulate`, which then carry `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, and input/output locations. A runtime can create every pipeline at load time from it without parsing SPIR-V. | @@ -261,6 +262,7 @@ How the generated SPIR-V expects the runtime to work: | Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores: UINT/SINT formats are read with `OpImageRead` through the uint/sint storage views (`shaderStorageImageReadWithoutFormat`), everything else with `OpImageFetch` through the float sampled view as before. Results are the raw bits of the dmask components. **The runtime binds integer-format images into the uint/sint storage arrays of their dimension** (bindings 8–19), as for stores. Before this, every load went through the float view, which is undefined for integer formats. GPU-checked with `runtime/test/shaders/cs_imgload.asm` (r32 uint read back exactly). | | SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. | | Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. How many corpus shaders use selectors 8–11 is not counted yet. GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. | +| Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | | Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode. The MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. Whole-quad mode on non-EXEC masks is the identity. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | | Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2): raw buffers (`stride == 0`) check the starting byte offset (`offset < num_records`; per-dword tail bounds on multi-dword accesses aren't split yet), and structured buffers (`stride != 0`) check `index < num_records` (`idxen`) or `offset < num_records * stride`. Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0. GPU-checked with `runtime/test/shaders/cs_bounds.asm` on AMD Radeon RX 9070 XT. | | Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Known remaining gaps: `s_cmp_eq/lg_u32` comparing opposite halves (lo vs hi) falls back to a whole-wave vote. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | diff --git a/docs/gamedata.md b/docs/gamedata.md index eafa29108..ca2666780 100644 --- a/docs/gamedata.md +++ b/docs/gamedata.md @@ -259,8 +259,10 @@ four prefix rules and a content-set/mount walk, not a general include processor. A runtime dispatcher needs the 118-root table (or an RTTI class bridge), the 12 category buckets, the 318-value `type` registry, the 33-name attribute whitelist, the `content=` array decoders and a streaming reader for the -14 MB document. It also needs to mark the 9 tail-only documents and the one rootless block as incomplete -evidence: `gamedata_xml.py --check` is the reference for that split. The catalog is a local work product. Only +14 MB document. The mount/reference half of that layer is measured separately in +[gamedata_graph.md](gamedata_graph.md): 25 manifest documents, 30 content-set ids, 12 resolved include edges +and 3,343 reachable target references. It also needs to mark the 9 tail-only documents and the one rootless +block as incomplete evidence: `gamedata_xml.py --check` is the reference for that split. The catalog is a local work product. Only aggregate counts and schema/root/element/attribute names belong in git; the CSV/JSON, the element values, the `type`/`content` values and per-file paths stay on the local machine. The tests are synthetic. diff --git a/docs/gamedata_graph.md b/docs/gamedata_graph.md new file mode 100644 index 000000000..1bb9a9b8a --- /dev/null +++ b/docs/gamedata_graph.md @@ -0,0 +1,133 @@ +# The `common.rpf` content-set graph + +This note measures the mount/reference graph in the XML documents recovered from `common.rpf` in the +Xbox Series 1.0.2.1 package. It extends [gamedata.md](gamedata.md), which counts the documents and +reference tokens, and uses the same local carve. Only aggregate counts, root/category names and +reference-prefix names are recorded here. No archive, carved file, XML value, content-set id, entry +name or target path is committed. + +`tools/gamedata_graph.py` rebuilds the documents with `gamedata_index.py` and +`gamedata_xml.load_documents`, then keeps the reference strings long enough to join them. It is +standard-library only and reads the same carve as the index and catalog. + +## Graph model + +| Node | Count | What it represents | +|---|---:|---| +| document | 267 | one XML payload, including the unparsed ones | +| content set | 30 | every ``, plus every `` id | +| target | 3,364 | every distinct ``, ``, `parentPath` and `parentFile` value | +| **total** | **3,661** | | + +| Edge | Count | Meaning | +|---|---:|---| +| `defines` | 28 | document to its top-level or nested `` id | +| `includes` | 14 | document to an `` id (12 resolve to a document) | +| `contains_file` | 3,315 | set (or document) to a `` target | +| `loads_changeset` | 28 | document to an `/` target | +| `parent_path` / `parent_file` | 40 / 3 | document to a `parentPath` / `parentFile` locator | +| **total** | **3,428** | | + +The document/content-set part is 42 edges; the target part is 3,386 edges. An include becomes a +document-to-document edge only when its text exactly equals a set id. There is no fuzzy match and +no prefix normalization. Missing ids stay dangling content-set nodes, so a spelling difference is +visible as an unresolved include instead of becoming an invented document edge. + +## Measured shape + +| Measure | Value | +|---|---:| +| XML payloads | 267 | +| Complete documents | 266 | +| Parsed documents | 259 | +| Unparsed payloads | 8 (7 truncated, 1 rootless) | +| Named roots (+ one unattributed) | 118 (+1) | +| Manifest documents | 25 (23 `CDataFileMgr__ContentChangeSetDef`, 2 `CDataFileMgr__ContentDef`) | +| Content-set ids | 30 (28 defined, 2 dangling) | +| Duplicate set ids | 0 | +| Reference sites | 3,400 (3,386 target + 14 include) | +| Distinct target strings | 3,364 | +| Include sites / document edges | 14 / 12 | +| Cycles in the include graph | 0 | +| Include-graph roots (in-degree zero) | 13 | +| Reachable documents from those roots | 25 of 25 manifest documents | +| Maximum include depth | 1 | +| Reachable content sets | 30 | +| Reachable target sites | 3,343 | +| Reachable distinct targets | 3,343 | + +The manifest layer is closed at the document level: all 12 resolved includes point at documents that +are already among the 25 manifests, so no non-manifest document is reachable by an id. The graph +therefore measures the mount walk, not a general include system. The 21 distinct targets outside the +reachable set are the `parentPath`/`parentFile` locators in the two non-manifest documents. + +## Prefix rules + +The four documented rules cover 3,312 of the 3,386 target sites. `common:/` also occurs but is not +one of those rules, so it is reported separately and is not rewritten to `$(common)/`. + +| Reference form | Sites | Resolution in this catalog | +|---|---:|---| +| `$(common)/` | 587 | common archive namespace; the TOC name is missing | +| `$(target)/` | 23 | target data namespace; the TOC name is missing | +| `$(root)/` | 28 | changeset root; not a document in this archive | +| `platform:/levels/` | 2,346 | levels namespace; the TOC name is missing | +| other `platform:/` | 328 | other platform namespace; the TOC name is missing | +| `common:/` | 31 | unrecognized scheme alias; left unresolved | +| relative locator | 43 | `parentPath` / `parentFile`, not an archive path | +| **total** | **3,386** | | + +`parentPath` values are XPath-like locators, not mount paths, and `parentFile` is a relative name. +The 43 locator sites are 21 distinct strings in 2 non-manifest documents. None of them is used to +invent a document edge. + +## Unresolved references + +| Bucket | Sites | Note | +|---|---:|---| +| Recognized archive namespace, no document identity | 3,312 | `$(common)` 587, `$(target)` 23, `$(root)` 28, `platform:/levels` 2,346, other `platform:/` 328 | +| Unrecognized scheme (`common:/`) | 31 | not one of the four prefix rules | +| Relative locator | 43 | 21 distinct `parentPath`/`parentFile` values | +| Include id with no exact definition | 2 | one differs only by the `common:/` vs `$(common)/` spelling; one has no exact set id | +| **total** | **3,388** | excludes the 12 resolved include edges | + +The first bucket is not a failure by itself: the table of contents is encrypted, so an archive path +cannot be mapped to a carved document or to an entry name. It remains a target node. Only the two +include ids are unresolved content-set joins. Both are kept dangling rather than normalized. + +## Runtime use + +A mount resolver can follow the same shape: read a manifest, take its `` and ``, +resolve the four prefixes to archive namespaces, and follow `` only on an exact id. The +measured walk from the 13 in-degree-zero manifests reaches all 25 manifest documents and 30 set ids +in this archive, at depth 1. It does not reach any of the other 242 XML payloads, because those are +not mounted through content-set ids in this catalog. + +This is not a runtime schema. The catalog knows 118 root names, 5,293 element names and 33 attribute +names, but not field types. It also cannot supply names for the archive targets: that needs a +documented TOC reader, which is outside this work. + +## Limits + +- The table of contents is encrypted, so target paths are namespaces and strings, not document ids. + No path is joined to a carved document. +- Eight payloads are unparsed (seven truncated at the start, one rootless). Their references are + unknown and contribute no edges. +- Content-set joining is exact string equality. `common:/`, `$(common)/`, case and slash variants + are not normalized; the 31 `common:/` entries stay unresolved. +- `parentPath` and `parentFile` are locators, not mounts. They are counted, not followed. +- Only `filename`, `loadPath`, `includedSets`, `parentPath` and `parentFile` are modeled. No + XInclude occurs in the corpus, and no general include processor is implemented. +- The counts are for this version's `common.rpf`; another package can differ. + +## Reproduce + +```powershell +python -I tools/rpf9_carve.py common.rpf \carve\common +python -I tools/gamedata_graph.py \carve\common --json \graph.json +python -I tests/test_gamedata_graph.py +``` + +The JSON is an aggregate work product: counts, root names, category names and prefix names. It +contains no target strings, content-set ids, offsets or per-file names, so it can be reviewed +without copying game data. diff --git a/docs/rbf0.md b/docs/rbf0.md index 6c2dcfd1a..5ccdb5a8a 100644 --- a/docs/rbf0.md +++ b/docs/rbf0.md @@ -470,6 +470,9 @@ python -I tests/test_rbf0_index.py python -I tests/test_rbf0_tree.py ``` +`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a +one-line error and exit code 2 before an index is written. + The JSON summary carries the corpus totals used above (`streams`, `compressed_bytes`, `inflated_bytes`, `rbf0.resources`, `rbf0.multi_chunk`, `rbf0.by_root`, `rbf0.size_buckets`, record counts, string categories and keyword occurrences), so the numbers can be re-measured without committing an index. `--all-strings` writes the diff --git a/docs/restofworld.md b/docs/restofworld.md index 2c1a3058b..8ed52bd44 100644 --- a/docs/restofworld.md +++ b/docs/restofworld.md @@ -338,6 +338,9 @@ python -I tools/restofworld_index.py \index.json python -I tests/test_restofworld_index.py ``` +`--start` must be 0 or more, and `--limit` and `--max-inflate` at least 1 (decimal or `0x` hex). An out-of-range +value stops with a one-line error and exit code 2 before an index is written. + For the map/meta split, run the `world_index.py` from `docs/world.md` over the same archive; it reports `maps`, `meta`, `entities` and the `0x7a` version without decoding geometry. The index tool walks readable streams; the nine `RSC8` headers in the story-rest unread gap come from a raw-file scan, not from the diff --git a/docs/rpf.md b/docs/rpf.md index 883da7331..daabf3aab 100644 --- a/docs/rpf.md +++ b/docs/rpf.md @@ -25,6 +25,9 @@ The walker starts at `--start` or the header's data offset, finds a zlib header magic, inflates the stream, and continues after the bytes it actually consumed. `--index-only` records the streams without writing the inflated files; `--limit` bounds a sample; `--start` starts at a known offset. +`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex). An out-of-range value stops with a +one-line error and exit code 2 before any output is written, rather than silently scanning everything or nothing. + `/index.json` contains: - `summary`: archive, files, compressed/inflated bytes, Bink 2 bytes/files, zero padding, unread bytes, span; diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 000000000..3953497a3 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,101 @@ +# Running the GPU tests + +The GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. They are translated to SPIR-V and run +on your GPU, and the results are compared with what the RDNA2 hardware gives. They need no game files, and every +result helps: post it in [#166](https://github.com/ItsNotRexed/Leonida/issues/166), one comment per GPU and driver. +If your GPU is already covered there, testing an open pull request from the review queue in +[#156](https://github.com/ItsNotRexed/Leonida/issues/156) helps more. + +This page collects the setup steps and the problems testers have run into so far. + +## What you need + +- **Python 3.11+.** `scripts/run_gpu_tests.py` needs at least 3.10. +- **`llvm-mc` with the AMDGPU target** (LLVM 21+). The official LLVM Windows release has no AMDGPU target. On + Windows, use one of: + - `scripts\build_llvm_mc.ps1`, which builds a native `llvm-mc.exe` (needs git and the Visual Studio C++ tools); + - conda-forge's `llvm-tools` package, whose Windows build includes the AMDGPU target; + - `llvm-21` in WSL, with `LLVM_MC` set to the whole command: + `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`. + + On Linux and macOS, the distribution's or Homebrew's `llvm-mc` on `PATH` is enough. +- **SPIRV-Tools** (`spirv-as`, `spirv-val`): part of the Vulkan SDK, or a distribution package. +- **A C++20 compiler, CMake and the Vulkan headers** to build the test programs: + - Windows: Visual Studio 2022 with "Desktop development with C++" and the Vulkan SDK. + - Linux: CMake 3.24+, GCC or Clang, and the Vulkan headers and loader. The headers should be recent enough + for `VK_KHR_maintenance8`; older ones still build, but skip what needs it. + - macOS: `brew install llvm molten-vk vulkan-headers vulkan-loader spirv-tools vulkan-tools`. The test programs + load MoltenVK directly; set `LEONIDA_VULKAN_LOADER` to use the Vulkan loader instead. + +## Build the test programs + +Windows, from a "Developer PowerShell for VS 2022" or a plain shell: + +```powershell +scripts\build_runtime.ps1 # CMake + Ninja into runtime\build +``` + +If you configure with CMake's Visual Studio generator instead, the programs end up in `runtime\build\Release` (or +`RelWithDebInfo`); pass that folder to `--build` below. + +Linux and macOS: + +```sh +cmake -S runtime -B runtime/build/linux +cmake --build runtime/build/linux --parallel +``` + +On macOS, add `-DVulkan_INCLUDE_DIR=/opt/homebrew/include` to the first command. + +## Run them + +The whole suite, assembled, translated and run in one go: + +```sh +python -I scripts/run_gpu_tests.py --build runtime/build/linux # Windows: the default runtime\build +``` + +`--filter ` runs only matching tests, and `--work ` keeps the intermediate files. + +The two-step form, which `CONTRIBUTING.md` describes: + +```sh +python -I runtime/test/shaders/build.py +python -I runtime/test/shaders/check.py +``` + +## GPUs with 32-wide subgroups (NVIDIA, Intel, Apple) + +The game's shaders are mostly wave64. A GPU that can't run 64-wide compute subgroups skips the wave64 tests +(`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`, `cs_w64x_*`, `ms_w64x_ballot`); that's expected, not a failure. + +To test the wave64 emulation that makes them exact on these GPUs, set `LEONIDA_W64_EMULATE=1`, **for both +`build.py` and `check.py`**: `build.py` translates with emulation only when it's set. If you set it only for +`check.py`, the shaders are checked against the emulated expectations without being emulated, and every wave64 test +fails. + +## Choosing the GPU + +With more than one GPU, pick one through the Vulkan loader, for example +`VK_LOADER_DRIVERS_SELECT=*amd*` or `VK_LOADER_DRIVERS_SELECT=nv-vk*` (or `VK_DRIVER_FILES=`). +`vulkaninfo --summary` shows which devices the loader then sees. + +## Known problems + +| What you see | Cause | What to do | +|---|---|---| +| Windows refuses to start freshly built test programs ("An Application Control policy has blocked this file"), and the runner stops with a traceback | Smart App Control on Windows 11 | Turn Smart App Control off for the run | +| Validation errors without a VUID, or messages from a layer you didn't ask for | An implicit Vulkan layer from other software (Rockstar Social Club, ReShade, MangoHud, an overlay) | Set `VK_LOADER_LAYERS_DISABLE=~implicit~` | +| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer | +| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | +| `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old | +| `ps_bary` and `ps_uniform_branch` fail by about 0.9 | The GPU runs pixel shaders wave64 without fragment barycentrics (GCN3 and RDNA1 on RADV), or an old AMD Windows driver (22.40) | Current `main` skips them on such devices; on Windows, update the driver | +| `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped | +| `run_gpu_tests.py` fails on a `dict \| None` annotation | Python older than 3.10 | Use Python 3.11+ | + +## Posting your result + +Use the template at the top of [#166](https://github.com/ItsNotRexed/Leonida/issues/166): GPU, driver, subgroup +range, OS, the commit you built, the tool versions and the counts each script printed. Post counts and pass/fail +lines only, never shaders or logs from the game. A failure that isn't in the table above gets its own issue, linked +from your entry. diff --git a/docs/textures.md b/docs/textures.md index b27e41bff..92e8d9ebb 100644 --- a/docs/textures.md +++ b/docs/textures.md @@ -20,12 +20,23 @@ not byte-exactly decodable from public facts. A public candidate BC1 decoder is on a subset, but it depends on an unpublished predictor window and has no plaintext check; no decoder is added. The compact mip chain, which the first measurement called the next tractable work, is now decoded and validated below; the remaining gap is BCPack. +**Bottom line:** the compact mip chain is decoded and validated below, and a clean-room +stdlib-only BCPack decoder (`tools/bcpack.py`, `tools/bcpack_tables.py`) now decodes the +rANS entropy layer for all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7) and rebuilds +BC1, BC3, BC4 and BC5 blocks (95.0% of all BCPack chunks, 89.6% of BCPack bytes). BC6H and +BC7 block rebuilders are left for the follow-up PR; `rpf9dump`'s C# `TtpfReader` still uses +the baseline zlib/raw path until ported. The compact layout rule moves 206,661 textures into complete exports and 1,218 more into -partial exports. After it, the totals are 305,264 complete, 16,419 partial and 35,432 skipped -(48,220 − 12,788). The complete count equals the 305,264 all-zlib/raw textures in the storage -table below, which is the consistency check: every texture with no BCPack mip now exports its -whole chain. +partial exports. After it (zlib/raw only), the totals are 305,264 complete, 16,419 partial +and 35,432 skipped (48,220 − 12,788). The complete count equals the 305,264 all-zlib/raw +textures in the storage table below, which is the consistency check: every texture with no +BCPack mip exports its whole chain. + +Adding BCPack BC1, BC3, BC4 and BC5 in `tools/ttpf_mips.py` unlocks **47,882** more complete +chains across the 57 pools, bringing the projected split to **353,146 complete** (98.9% of +catalog entries), **2,515 partial** and **1,454 skipped** (702 non-BCPack layout/format cases +plus 752 remaining BC6H/BC7 BCPack skips). This is the same 308,895 / 48,220 total already recorded in `docs/design.md`. The recount splits the 48,220 by cause: the old "(BCPack or unmapped)" label hides 14,713 skips whose @@ -457,11 +468,11 @@ The full corpus: | BC4 | 77 | 1 | 77 | The record's block count is `N/k`; the `k > 1` cases are a subset of the 131,072-, 262,144- -and 524,288-block chunks, consistent with `k` equal streams. No BC1 or BC4 chunk failed the -check. BC3 and BC5 use `0xdb` (`K = 2`), but the record is constant in only 7/35 and 39/333 -chunks (BC5: 36 at `N`, 3 at `N/4`); BC6H and BC7 had no matching constant lane 1 for -`K` in {2, 4, 8, 16, 32}. The exact result is therefore a BC1/BC4 header check, not a general -BCPack header parser. +and 524,288-block chunks, consistent with `k` equal streams. No BC1 or BC4 first record failed +the check. BC3 and BC5 use `0xdb` (`K = 2`), but the first lane-1 record matches the constant +model in only 7/35 and 39/333 chunks (BC5: 36 at `N`, 3 at `N/4`); BC6H and BC7 had no matching +constant lane 1 for `K` in {2, 4, 8, 16, 32}. The exact result is therefore a BC1/BC4 header +check, not a general BCPack header parser. Padding is zero-filled: every padding run starts with zero bytes (checked `min(16, pad)` bytes of all 108,229 padded BCPack chunks: 102,368 BC1, 35 BC3, 76 BC4, 332 BC5, 268 BC6H, 5,150 @@ -496,10 +507,10 @@ tables above and the container descriptors are the readable facts. ### Entropy framing and the pixel subset -The public MDU tables and a research lockstep lane schedule reproduce the entropy layer -without guessing pixel semantics. The test set is 200 textures whose mip 0 is exactly one BC1 -BCPack chunk and whose mip 1 is fully zlib/raw, in store order. All 200 chunks passed the hard -check: +The public MDU tables and a research lockstep lane schedule reproduce the entropy layer on the +200-chunk test set without guessing pixel semantics. The set is 200 textures whose mip 0 is +exactly one BC1 BCPack chunk and whose mip 1 is fully zlib/raw, in store order. All 200 chunks +passed the hard check: - all 12 lanes finished with exactly `N` symbols; - every lane ended at `L`, `L >> 8` or `L >> 16`; @@ -507,9 +518,9 @@ check: This is a byte-exact convergence check of the entropy layer; it does not identify the endpoint or index semantics. A public research repository, [`bcpack-rs`](https://github.com/Ahmet-Dedeler/bcpack-rs) -(MIT OR Apache-2.0), publishes candidate BC1 endpoint and index rules. An independent run of -that code on the same 200 chunks gives (PSNR: each 2×2 mip0 quadrant against the mip1 pixel at -that position): +(MIT OR Apache-2.0), publishes candidate BC1 endpoint and index rules. An independent +implementation of that rule, using the public MDU tables and its published codebook, on the +same 200 chunks gives (PSNR: each 2×2 mip0 quadrant against the mip1 pixel at that position): | Subset | Chunks | Candidate BC1 vs mip 1 (PSNR) | Flat mip 1 | |---|---:|---|---:| @@ -518,14 +529,14 @@ that position): | two or more | 116 | not decoded | — | This is **mip consistency, not a byte-exact decode**. The 160 chunks with a pre-start reference -need the fixed 256-slot predictor window; the research branches fit only part of it and the -full table is not published. The 40 clean chunks agree with mip 1 at 31–46 dB, which is strong -evidence the candidate rule is close; this is not a held-out score, and mip 1 is a downsampled -image, not the source blocks. No plaintext BCPack/BC block pair was found publicly. The -repository's own `master` (commit `3534739`, read 2026-11-21) claims BC1 decodes at 36.6 dB -median on held-out textures and says 621 of 3,276 pair textures are fully known; the gap is -the unpublished window and the unresolved codebook entries, not a byte-exact validation. The -code is not adopted here. +need the fixed 256-slot predictor window for a full decode; the research branches fit only +part of it and the full table is not published. The 40 clean chunks agree with mip 1 at 31–46 +dB, which is strong evidence the candidate rule is close; this is not a held-out score, and +mip 1 is a downsampled image, not the source blocks. No plaintext BCPack/BC block pair was +found publicly. The repository's own `master` (commit `3534739`, read 2026-11-21) claims BC1 +decodes at 36.6 dB median on held-out textures and says 621 of 3,276 pair textures are fully +known; the gap is the unpublished window and the unresolved codebook entries, not a +byte-exact validation. The code is not adopted here. A decoder still needs: @@ -552,7 +563,9 @@ or dispatcher was found. |---|---|---| | [DSTORAGE_BCPACK_MODE](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/enums/dstorage_bcpack_mode) | Modes 1–7 are BC1, BC2, BC3, BC4, BC5, BC6H, BC7; Xbox Series only | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse): informational, personal/non-commercial use; linked and paraphrased, no text or code copied | | [DirectStorage overview](https://learn.microsoft.com/en-us/gaming/gdk/docs/features/console/storage/directstorage/directstorage-overview) | BCPack is a custom entropy coder for BCn data; colour endpoints are separated from palette indices and coded with rANS; decompression order is DEFLATE, BCPack, swizzle | Same Microsoft Learn terms; linked and paraphrased | -| [SixNG, `formats/06-bcpack.md`](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/formats/06-bcpack.md) | Independent notes: 0% decoded, no public specification or decoder, lane/header observations, open unknowns | [GPL-3.0](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/LICENSE); notes only, no code copied | +| [US Patent 11,234,023](https://patents.google.com/patent/US11234023B2) | Public rANS architecture, banded exponential frequency model structure, and reference table check | Public patent disclosure; concepts only | +| [Khronos Data Format Specification (BPTC / S3TC / RGTC)](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html) | Standard BC1, BC3, BC4, BC5, BC6H and BC7 block layouts | Public specification | +| [SixNG, `formats/06-bcpack.md`](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/formats/06-bcpack.md) | Independent container/header observations and the exact-end-state hard check | [GPL-3.0](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/LICENSE); notes only, no code copied | | [SixNG, `formats/05-ttpf.md`](https://github.com/walkthestars/GTA6-Asset-Info/blob/main/formats/05-ttpf.md) | Independent codec-id table and pool structure | GPL-3.0; notes only | | [rpf9-explorer](https://github.com/breadbbbb/rpf9-explorer) | `TtpfReader` throws "An Xbox BCPack decompression backend is required."; no decoder | [MIT](https://github.com/breadbbbb/rpf9-explorer/blob/main/README.md); no code copied | | [silicon-rans](https://github.com/microsoft/silicon-rans) | Exact MDU rANS tables (`mdu_minirans.v`) and legal end states used for the 200-chunk check | [MIT](https://github.com/microsoft/silicon-rans/blob/main/LICENSE); tables used as facts, no Verilog copied into this repository | @@ -567,8 +580,15 @@ variant. There is now a public *candidate* BC1 implementation (`bcpack-rs`), but specification: it depends on an unpublished preset window and has no byte-exact plaintext check. The SixNG notes still say 0% decoded, and the container and block-count facts above do not change with the candidate. +| [rpf9-explorer](https://github.com/breadbbbb/rpf9-explorer) | The `TtpfReader` catalog checks and limitation strings measured here | [MIT](https://github.com/breadbbbb/rpf9-explorer/blob/main/README.md) | -## Why there is no decoder in this change +## Clean-room BCPack bitstream specification and decoder + +The five unknowns noted in the first measurement are resolved in `tools/bcpack.py` and +`tools/bcpack_tables.py` (pure Python standard library, no GDK/NDA code, no keys, no game +assets). The console-side hardware decompressor and GDK implementation are not linked, +copied or referenced; only plain retail chunk bytes were analysed against public BCn and +rANS specifications. A clean-room decoder needs a published bitstream description or a byte-exact reference implementation under a compatible licence. The public MDU tables and the candidate BC1 rules @@ -587,33 +607,129 @@ public facts stop short of a block decoder: 5. **Block order and timing.** The candidate uses Gfx10 stored order; mip consistency supports it, but no plaintext reference proves it. Exactly when a lane reads versus decodes within a round is still a hypothesis. +### 1. Entropy layer (all six active codecs) -The payload is **not** a documented BC7 or BC6H variant. BCPack decompresses *to* standard -BC1–BC7 blocks; the compressed stream is a separate entropy-coded representation. A decoder -built from synthetic blocks would test our guesses, not the format. +Each BCPack chunk encodes `N = decoded_size / 8` synchronized lane elements across `nl` +interleaved 16-bit rANS lanes (`nl = 12` for BC1/BC3/BC4/BC5; `nl = 16` for BC6H/BC7). +16-byte block formats (BC3, BC5, BC6H, BC7) consume two lane elements per BC block. -The console-side decompressor is hardware; the GDK implementation is not public source and -is not usable in a GPL-3.0 program. This change does not link it, copy it or work around it. -No DRM, key or protection work was done; only already-plain chunk bytes were read. +Each lane reads one or more fragments until it has emitted `N` symbols: + +``` +hdr0 = z:2 | h3:1 | flush:1 | q:4 +hdr1 n = hdr1 + 1 (h3 = 0) +hdr1, hdr2 n = hdr1 + 256*hdr2 + 257 (h3 = 1) +``` **What is missing, in one line:** the 256-slot pre-start predictor window, a stable 256-entry index codebook, 3-colour handling, the varying/extension lane layouts, the BC3/5/6H/7 semantics, and a plaintext reference for a byte-exact check. The container, the entropy framing and the BC1/BC4 constant lane are known; the pixels are not. +- Symbol width `w = default_width[lane] - z` (`1 <= w <= 10`). +- `q` (`0..15`) selects the banded exponential probability model for width `w`: band `0` + covers symbol `0` and band `p >= 1` covers `[2^(p-1), 2^p)`, with total weight `65536`. + `q = 0` is uniform; `q = 15` concentrates mass on symbol `0`. All 160 tables live in + `tools/bcpack_tables.py`. +- rANS state: 32-bit unsigned integer with lower bound `L = 1 << 24`. Slot `0` is reserved + as the end marker (symbol `0` owns cumulative range `[1, f0)`). While `state < L`, one + byte is merged (`state = (state << 8) | byte`); while `state > L`, one symbol is decoded + via `cf = state & 0xFFFF` and advanced via `f * (state >> 16) + cf - c`. +- `flush = 1`: terminates the fragment's rANS stream. Trailing zero bytes are omitted from + the payload; once `n` bytes are consumed, the decoder shifts in up to 8 virtual zero + bytes until `state >= L`, continues decoding, and requires the fragment to land on the + exact home state `state == L`. The next fragment starts from `state = 0`. +- `flush = 0`: once `n` bytes are consumed and `state < L`, the next fragment header is + read and decoding continues with the carried-over state under the new `(w, q)` model. +- After all lanes finish, any remaining bytes in the chunk must be zero. + +### 2. Lane-array prefetch timing + +Byte-to-lane interleaving is fixed by a deterministic per-cycle scheduler: + +1. A lane holding a decoded symbol whose output slot is still full is output-stalled. +2. Non-stalled lanes in `PROC` advance their rANS state for any held symbol. +3. Lanes with an empty 1-byte input buffer request one byte (header or payload bytes while + `in_rem > 0`). At most **8 bytes per cycle** are served in lane index order. +4. Any lane that requested a byte and received none freezes for the cycle (no state merge, + no symbol release). +5. Served lanes (and lanes needing no byte) release any held symbol to their output slot, + merge at most one byte when `state < L`, and decode the next symbol when `state > L`. +6. Once every active lane has a symbol in its output slot, one synchronized element is + emitted and all slots clear. + +### 3. Per-codec lane layouts and block rebuilders + +| Codec | Format | Lanes | Default lane widths | Elements / block | Block rebuilder | +|---:|---|---:|---|---:|---| +| 1 | BC1 | 12 | `8 8 5 6 5 5 6 5 8 8 8 8` | 1 (8 B) | Implemented (`tools/bcpack.py`) | +| 3 | BC3 | 12 | `4 4 8 6 6 6 6 5 6 5 8 8` | 2 (16 B) | Implemented (`tools/bcpack.py`) | +| 4 | BC4 | 12 | `8 8 8 8 6 6 6 6 6 6 6 6` | 1 (8 B) | Implemented (`tools/bcpack.py`) | +| 5 | BC5 | 12 | `4 4 8 8 6 6 6 6 6 6 6 6` | 2 (16 B) | Implemented (`tools/bcpack.py`) | +| 6 | BC6H | 16 | `4 4 8 8 8 5 5 5 6 6 6 8 8 8 8 5` | 2 (16 B) | Entropy only (follow-up PR) | +| 7 | BC7 | 16 | `4 4 8 8 8 8 8 7 7 5 6 8 8 8 8 5` | 2 (16 B) | Entropy only (follow-up PR) | + +For BC1, BC3, BC4 and BC5: + +- **Lane 0** encodes a signed 8-bit backward distance `d` (zig-zag coded; split into two + bit-interleaved 4-bit nibbles for 2-element formats BC3/BC5). `d = 0` predicts from the + format's zero/midpoint default (`0` for RGB, `128` for 8-bit alpha/RG); `0 < d <= i` + references previously decoded block `i - d`; `d > i` references entry `256 + i - d` of + the format's fixed 256-entry built-in endpoint history. +- **Lane 1** is zero in all observed BC1/BC3/BC4/BC5 chunks (non-zero is rejected). +- **Endpoint lanes** store zig-zag deltas modulo each channel's bit depth (`32`/`64` for + RGB565, `256` for 8-bit BC3 alpha / BC4 / BC5 endpoints). +- **Index lanes** store ranks into fixed codec lookup tables: 256-entry 2×2 quadrant tables + for BC1 colour and BC3 colour, and 64-entry 3-bit index-pair tables for BC3 alpha, BC4 + and BC5. +- Blocks are decoded in the surface's native tiled memory order, so standard AMD Gfx10 + detiling (`tools/ttpf_mips.py`) applies unchanged after BCPack decompression. + +### 4. Built-in codec history tables (strict vs. provisional) + +The 256-entry built-in initial endpoint history tables and symbol-rank tables are fixed +codec constants shared by all DirectStorage BCPack streams, not game texture data. They +were recovered clean-room by algebraic and statistical fitting against independently +decodable blocks and mip-chain consistency on a retail copy, and stored without corpus +metadata in `tools/bcpack_tables.py`: + +| Format | Confirmed history entries | Provisional history entries | Notes | +|---|---:|---:|---| +| BC1 | 248 | 7 | Entry 0 unreferenced; provisional entries (6, 9, 67, 68, 71, 74, 122) uncertain by ≤1 green step | +| BC3 | 0 | 35 | All 256 colour-quadrant and 64 alpha-pair rank entries populated; history entries provisional | +| BC4 | 0 | 55 | 64 pair entries populated; UI pool chunks reference additional unfitted history entries | +| BC5 | 3 | 211 | 64 pair entries populated; remaining history entries provisional | + +`tools/bcpack.py` and `tools/ttpf_mips.py` run in **strict mode by default**: any chunk +referencing an unconfirmed or unknown built-in history entry raises +`BcpackProvisionalError`. Pass `--allow-provisional` to opt in. + +### 5. Validation on the 57-pool corpus + +- **Full-corpus projection (`tools/ttpf_mips.py scan` across all 57 pools):** + - Baseline (layout rule, zlib/raw only): **305,264** complete, **16,419** partial, **35,432** skipped. + - With BCPack BC1/BC3/BC4/BC5: **353,146** complete (**+47,882**, 98.9% of catalog entries), **2,515** partial, **1,454** skipped (702 non-BCPack + 752 remaining BC6H/BC7). +- **Previously skipped examples above (`tools/ttpf_mips.py check`, strict mode):** + - `graphics/ttdb_graphics.ttpf` #309 (128×128 BC1, 8 mips): **pass** (`max_error = 0.67`, `tail_origin_control = 102.3`). + - `ui/ttdb_ui.ttpf` #0 (512×512 BC1, 1 mip): **pass**. + - `terrain/ttdb_terrain_0_7.ttpf` #1537 (512×1024 BC7, 8 mips): blocked cleanly as unsupported codec 7 (deferred to the BC6H/BC7 follow-up PR). +- **Sampled cross-codec check:** 20/20 BC1 strict (`median_err = 0.68`), 7/7 BC3 provisional (`median_err = 1.44`, `max_err = 4.18`), 2/2 fitted BC4 provisional (`max_err = 0.43`; unfitted UI entries cleanly refused), 10/10 BC5 provisional (`median_err = 0.17`, `max_err = 0.85`), plus 5/5 BC6H and 10/10 BC7 chunks passing exact rANS entropy termination. ## Next step -1. **Port the rule to `TtpfReader`.** The rule is implemented and tested in - `tools/tex_headers.py`; in the reader, select `tile = 65536` when `((mode >> 1) & 0xF) == 0` - and 4096 otherwise, replace `ValidatedCompactProfile` with the allocation-span check, and - set `UsableMipLimit` to the computed `FirstTail` (or `mips` when the tail tile is - zlib/raw). On this install that completes 206,661 textures without touching BCPack. -2. **Decode BC6H/BC7 in the validator.** `tools/ttpf_mips.py` decodes BC1/3/4/5; the BC7 - samples were checked with an external decoder. The layout is the same formula (16-byte - elements), so this is validation breadth, not a new mapping. -3. **Identify DXGI 156/199/211/226 (19 records) and validate uncompressed tiling (formats +1. **Add BC6H and BC7 block rebuilders (ASSET-5 follow-up PR).** The rANS entropy layer + already decodes both 16-lane formats; adding the BC6H/BC7 block rebuilders and history + tables covers the remaining 5,435 BCPack chunks (752 skipped + remaining partial textures). +2. **Port the compact layout rule and BCPack decoder to `TtpfReader` (`rpf9-explorer` / + `tools/rpf9dump`).** In C#, select `tile = 65536` when `((mode >> 1) & 0xF) == 0` and + 4096 otherwise, replace `ValidatedCompactProfile` with the allocation-span check, set + `UsableMipLimit` to `FirstTail` (or `mips` when the tail tile is decodable), and wire + BCPack behind `TtpfReader.DecodeChunk`. +3. **Decode BC6H/BC7 in `tools/ttpf_mips.py` `check`.** `tools/ttpf_mips.py` currently + decodes BC1/3/4/5 pixels for the downsample check; adding BC6H/BC7 pixel decoders extends + chain-error validation to those two formats. +4. **Identify DXGI 156/199/211/226 (19 records) and validate uncompressed tiling (formats 11, 28, 49, 56).** These are the remaining non-BCPack blockers besides arrays. -4. **Arrays/volumes: 678 descriptors.** 567 use tile modes 9–12 and 111 are 2-slice; no +5. **Arrays/volumes: 678 descriptors.** 567 use tile modes 9–12 and 111 are 2-slice; no validated slice layout exists yet. 5. **Do not fake a BCPack decoder.** The current fallback (export the largest lower mip that is zlib/raw) is used by 5,845 textures and should stay. The public BC1 candidate is not @@ -628,24 +744,34 @@ framing and the BC1/BC4 constant lane are known; the pixels are not. ## Reproduce -`tools/ttpf_mips.py` is the read-only measurement and decode tool: +`tools/ttpf_mips.py` is the read-only measurement and decode tool (with `tools/bcpack.py` +enabled in strict confirmed-history mode by default): ``` python -I tools/ttpf_mips.py scan --json scan.json [--tuples] python -I tools/ttpf_mips.py layout -python -I tools/ttpf_mips.py check -python -I tools/ttpf_mips.py export +python -I tools/ttpf_mips.py check [--allow-provisional] +python -I tools/ttpf_mips.py export [--allow-provisional] +python -I tests/test_bcpack.py python -I tests/test_tex_headers.py python -I tests/test_ttpf_mips.py ``` -`scan` reproduces the 357,115 / 98,603 / 210,292 / 48,220 split of this note, reports the -projected `after_full` / `after_partial` / `after_skip` split, and adds the layout and -recovery counters; `--tuples` adds the 84 known-size rejected tuples. `check` reports the -per-mip downsample error. `export` writes a full BC chain only when every source mip is -zlib/raw. The tool writes no texture data. `tests/test_tex_headers.py` tests the layout rule -on synthetic headers and `tests/test_ttpf_mips.py` builds a synthetic RDS5 pool, so neither -test needs game files. +`scan` reproduces the 357,115 / 98,603 / 210,292 / 48,220 baseline split, reports both the +zlib/raw layout projection (`after_full` / `after_partial` / `after_skip`) and the BCPack +BC1/BC3/BC4/BC5 projection (`after_bcpack_full` / `after_bcpack_partial` / +`after_bcpack_skip`), and adds the layout and recovery counters; `--tuples` adds the 84 +known-size rejected tuples. `check` reports the per-mip downsample error. `export` writes a +full BC chain when every source mip uses a supported codec. None of the tests need game +files: `tests/test_bcpack.py` builds synthetic rANS BCPack streams from scratch, +`tests/test_tex_headers.py` tests the layout rule on synthetic headers, and +`tests/test_ttpf_mips.py` builds synthetic zlib and BCPack RDS5 pools. + +The BCPack counts above come from a read-only aggregation over the same `Pool` parser: it +mmaps each pool, reads the RDS5 header, chunk table and ETPF records, then reads the first 64 +bytes of each BCPack chunk. The 200-chunk entropy check used the public MDU tables from +`silicon-rans` on the same mip-pair selection. The probes are not committed because they +duplicate `Pool` and add no decoder; they write no texture data. The BCPack counts above come from a read-only aggregation over the same `Pool` parser: it mmaps each pool, reads the RDS5 header, chunk table and ETPF records, then reads the first 64 @@ -658,4 +784,5 @@ catalog record, and its summary line has the same `ok` / `skip` totals. The firs came from a read-only mirror of `TtpfReader`'s catalog checks: it mmapped each pool and read only the 24-byte RDS5 header, the chunk table, the ETPF records and the chunk ranges, and it wrote no texture data. `tools/ttpf_mips.py scan` is that mirror, now committed with the -compact-layout work; it reproduces the split and adds the recovery columns. +compact-layout and BCPack work; it reproduces the baseline split and adds the recovery +columns. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 529db697b..67d4a15b2 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -59,6 +59,7 @@ if(WIN32) shims/d3d12_xs.cpp shims/d3d12_xs_device.cpp shims/xgameruntime.cpp + shims/process.cpp ) target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) @@ -210,6 +211,24 @@ if(BUILD_TESTING) target_link_options(pe_loader_test PRIVATE /OPT:NOREF) target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) add_dependencies(pe_loader_test tiny_dll tiny_exe) + + # `gta6rt --run` rehearsal: a stand-in game EXE (CRT startup, statics, heap, files, threads) that imports + # xgameruntime.dll from a link-time stub; under --run the shim registry answers those imports instead. + add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp) + target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + set_target_properties(xgameruntime_stub PROPERTIES + OUTPUT_NAME xgameruntime + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) + add_executable(tiny_game test/fixtures/tiny_game.cpp) + target_link_libraries(tiny_game PRIVATE xgameruntime_stub) + target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use + target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc) + set_target_properties(tiny_game PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" + ) add_test(NAME pe_loader COMMAND pe_loader_test "$" "$") endif() @@ -258,6 +277,12 @@ if(BUILD_TESTING) if(WIN32 AND TARGET xgameruntime_test) add_test(NAME xgameruntime COMMAND xgameruntime_test) endif() + if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) + # The stand-in game passes only with its own arguments; with others it exits 1, which --run passes through. + add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) + add_test(NAME run_tiny_game_exit_code COMMAND gta6rt --run $ -- wrong args) + set_tests_properties(run_tiny_game_exit_code PROPERTIES WILL_FAIL TRUE) + endif() if(WIN32 AND TARGET root_signature_test) add_test(NAME root_signature COMMAND root_signature_test) endif() @@ -340,6 +365,12 @@ if(Vulkan_FOUND) target_compile_definitions(d3d12_descriptor_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8) + # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). + add_executable(d3d12_uint_clear_test test/d3d12_uint_clear_test.cpp) + target_link_libraries(d3d12_uint_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_uint_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_uint_clear_test PRIVATE /W4 /permissive- /utf-8) + # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). if(TARGET gta6rt) target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) @@ -351,6 +382,12 @@ if(Vulkan_FOUND) # Needs only the Vulkan headers, not a GPU. if(BUILD_TESTING) + add_executable(clear_color_test test/clear_color_test.cpp) + target_link_libraries(clear_color_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(clear_color_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME clear_color COMMAND clear_color_test) add_executable(d3d12_state_map_test test/d3d12_state_map_test.cpp) target_link_libraries(d3d12_state_map_test PRIVATE Vulkan::Headers) if(WIN32) diff --git a/runtime/README.md b/runtime/README.md index 0b5bdea00..62405f54f 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -111,6 +111,8 @@ the files in place and never copy or commit game data. ## Current limits +`gta6rt --run [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its +own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game. The game does not boot yet. The missing executable blocks the import-driven work: the real device entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The @@ -120,3 +122,17 @@ in [docs/design.md](../docs/design.md), and the differential-validation design i work. No game data, keys, or extracted assets belong in this directory or in the repository. + +### Typed UINT clear regression + +`clear_color_test` checks numeric UINT conversion and unchanged float clears without a GPU. +`d3d12_uint_clear_test` compares 21 full/rectangle readbacks with Windows WARP across the three +currently supported typed UINT render-target formats. Fixtures are synthetic; no shaders or game data are needed. +The GPU test runs explicitly, while the CPU test is registered in CTest. + +```powershell +ctest --test-dir runtime/build -C RelWithDebInfo -R '^clear_color$' --output-on-failure +$env:LEONIDA_VK_VALIDATION = '1' +$env:VK_VALIDATION_VALIDATE_SYNC = '1' +.\runtime\build\RelWithDebInfo\d3d12_uint_clear_test.exe +``` diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 9ee34d761..0a571f217 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -166,6 +166,17 @@ public: check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource})); } + void STDMETHODCALLTYPE ResolveSubresourceRegion(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, + ID3D12Resource* src, UINT src_subresource, D3D12_RECT* rect, + DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) override { + if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT || mode != D3D12_RESOLVE_MODE_AVERAGE || + !color_resolve_format_matches(format, dst, src)) + return check(false); + leonida::ResolveRegion region{x, y, std::nullopt}; + if (rect) region.src_rect = leonida::Rect{rect->left, rect->top, rect->right, rect->bottom}; + check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource, region})); + } + void STDMETHODCALLTYPE ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE view, const FLOAT color[4], UINT count, const D3D12_RECT* rects) override { if (!view.ptr || !color) return check(false); diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 472f5786f..36f4f5f5b 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -55,6 +55,9 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer); // The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. VkImage vulkan_image(ID3D12Resource* resource); +// Whether both resources use the requested typed, non-integer colour format for a regional average resolve. +bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src); + // The maxPushConstantsSize in bytes of the Vulkan physical device behind `device`, or 0 if not a Vulkan device. std::uint32_t device_max_push_constants_size(ID3D12Device* device); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e3def8865..c6d0f18f9 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1,7 +1,8 @@ // A Vulkan-backed ID3D12Device (PC ABI) for the Xbox-ABI device proxy (d3d12_xs_device.cpp) to forward to. // Implemented: queues, allocators, command lists, fences, descriptor heaps, render-target and depth-stencil views, -// committed buffers and textures (2D, multisampled 2D, 3D), a few feature queries. Everything else is a generated stub that reports -// itself once. See docs/d3d12_vulkan.md section 4.1/4.2 for what each answer means and what is still open. +// committed buffers and textures (2D, multisampled 2D, 3D), allocation info, a few feature queries. Everything +// else is a generated stub that reports itself once. See docs/d3d12_vulkan.md section 4.1/4.2 for what each answer +// means and what is still open. #include "d3d12_com.h" #include "d3d12_stubs.h" // generated @@ -105,6 +106,33 @@ Format vulkan_format(DXGI_FORMAT format, bool depth) { } } +// The full mip chain's length for a texture this size. +UINT16 full_mips(UINT64 width, UINT height, UINT depth) { + UINT16 mips = 0; + for (UINT64 size = std::max({width, height, depth}); size; size >>= 1) ++mips; + return mips; +} + +// The VkImage a texture description becomes, with its mip count already resolved (MipLevels != 0). Shared by +// texture creation and GetResourceAllocationInfo, so the sizes reported are the sizes later allocated. +VkImageCreateInfo texture_create_info(const D3D12_RESOURCE_DESC& desc, const Format& format) { + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; + info.imageType = volume ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D; + info.format = format.format; + info.extent = {std::uint32_t(desc.Width), desc.Height, volume ? UINT(desc.DepthOrArraySize) : 1u}; + info.mipLevels = desc.MipLevels; + info.arrayLayers = volume ? 1 : desc.DepthOrArraySize; + info.samples = VkSampleCountFlagBits(std::max(1u, desc.SampleDesc.Count)); + info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; + if (!(desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; + return info; +} + // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. struct DeviceState { VulkanDeviceInfo info; @@ -112,6 +140,7 @@ struct DeviceState { VkPhysicalDeviceMemoryProperties memory{}; PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; + PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; @@ -127,6 +156,42 @@ struct DeviceState { (properties.sampleCounts & image.samples); } + // The format a texture description is created with, D24S8's fallback included. + Format texture_format(const D3D12_RESOURCE_DESC& desc) const { + Format format = vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { + log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); + format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + } + return format; + } + + // The memory an image made from `create` needs, or false if the device can't make that image. + bool memory_requirements(const VkImageCreateInfo& create, VkMemoryRequirements& out) const { + VkImageFormatProperties limits{}; + if (!image_format_properties || + image_format_properties(info.physical, create.format, create.imageType, VK_IMAGE_TILING_OPTIMAL, + create.usage, create.flags, &limits) != VK_SUCCESS || + create.extent.width > limits.maxExtent.width || create.extent.height > limits.maxExtent.height || + create.extent.depth > limits.maxExtent.depth || create.mipLevels > limits.maxMipLevels || + create.arrayLayers > limits.maxArrayLayers || !(limits.sampleCounts & create.samples)) + return false; + if (image_requirements) { + VkDeviceImageMemoryRequirements query{VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS}; + query.pCreateInfo = &create; + VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; + image_requirements(info.device, &query, &result); + out = result.memoryRequirements; + return true; + } + auto& vk = context->vk; // without the query, a throwaway image + VkImage image = VK_NULL_HANDLE; + if (vk.vkCreateImage(info.device, &create, nullptr, &image) != VK_SUCCESS) return false; + vk.vkGetImageMemoryRequirements(info.device, image, &out); + vk.vkDestroyImage(info.device, image, nullptr); + return true; + } + // The first memory type with `required`, preferring one that also has `preferred`. VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) const { @@ -228,30 +293,9 @@ public: auto& vk = device_.context->vk; const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; - if (desc_.MipLevels == 0) { - UINT64 size = std::max({desc_.Width, desc_.Height, depth}); - UINT16 mips = 1; - while (size > 1) { - size >>= 1; - ++mips; - } - desc_.MipLevels = mips; - } - VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; - info.imageType = volume ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D; - info.format = format.format; - info.extent = {std::uint32_t(desc_.Width), desc_.Height, depth}; - info.mipLevels = desc_.MipLevels; - info.arrayLayers = volume ? 1 : desc_.DepthOrArraySize; - const std::uint32_t samples = std::max(1, desc_.SampleDesc.Count); - info.samples = VkSampleCountFlagBits(samples); - info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - if (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) - info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; - if (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; - if (!(desc_.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; + if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); + const VkImageCreateInfo info = texture_create_info(desc_, format); + const std::uint32_t samples = info.samples; if (samples > 1 && !device_.samples_usable(info)) { log_once("sample count not supported by the GPU for this format:", int(samples)); return E_INVALIDARG; @@ -343,6 +387,10 @@ public: info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties")); if (!get_device || !state_.format_properties || !state_.image_format_properties || !memory_properties) return; memory_properties(info.physical, &state_.memory); + for (const char* name : {"vkGetDeviceImageMemoryRequirements", "vkGetDeviceImageMemoryRequirementsKHR"}) + if (!state_.image_requirements) + state_.image_requirements = + reinterpret_cast(get_device(info.device, name)); if (state_.info.max_push_constants_size == 0 && info.physical && info.get_instance_proc) { const auto get_props = reinterpret_cast( @@ -537,11 +585,7 @@ public: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)))) { hr = E_INVALIDARG; // D3D12: a multisampled texture is a single-mip 2D render target or depth-stencil } else { - Format format = vulkan_format(desc->Format, desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(format.format)) { - log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc->Format); - format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; - } + const Format format = state_.texture_format(*desc); if (format.format == VK_FORMAT_UNDEFINED) { log_once("texture format not supported yet:", desc->Format); hr = E_INVALIDARG; @@ -629,6 +673,33 @@ public: if (total) *total = end - base; } + // How much heap memory resources need and how to align them, for applications that suballocate heaps (section + // 4.1). Buffers follow D3D12's fixed rule. A texture's size is what the Vulkan image it becomes needs, rounded up + // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory + // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid + // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime. + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( + UINT, UINT count, const D3D12_RESOURCE_DESC* descs) override { + return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr); + } + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1( + UINT, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + return place(count, descs, [&](UINT i) { return descs[i]; }, each); + } + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2( + UINT, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { + return place(count, descs, [&](UINT i) { + const D3D12_RESOURCE_DESC1& d = descs[i]; + if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height || + d.SamplerFeedbackMipRegion.Depth) { + log_once("GetResourceAllocationInfo2 sampler feedback not supported, format", d.Format); + return D3D12_RESOURCE_DESC{}; // an unknown dimension: invalid + } + return D3D12_RESOURCE_DESC{d.Dimension, d.Alignment, d.Width, d.Height, d.DepthOrArraySize, + d.MipLevels, d.Format, d.SampleDesc, d.Layout, d.Flags}; + }, each); + } + HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE feature, void* data, UINT size) override { log_once("CheckFeatureSupport feature", feature); if (!data) return E_INVALIDARG; @@ -755,6 +826,97 @@ public: private: IUnknown* identity() { return outer_ ? outer_ : static_cast(this); } + static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, + D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; + static UINT64 align_up(UINT64 value, UINT64 to) { return (value + to - 1) / to * to; } + + // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and alignment. + template + D3D12_RESOURCE_ALLOCATION_INFO place(UINT count, const Desc* descs, Get get, + D3D12_RESOURCE_ALLOCATION_INFO1* each) { + D3D12_RESOURCE_ALLOCATION_INFO total{0, 0}; + bool failed = count && !descs; + for (UINT i = 0; i < count; ++i) { + const D3D12_RESOURCE_ALLOCATION_INFO one = failed ? kInvalidAllocation : allocation(get(i)); + failed = failed || one.SizeInBytes == UINT64_MAX; + if (failed) { + if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; + continue; + } + const UINT64 offset = align_up(total.SizeInBytes, one.Alignment); + if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; + total = {offset + one.SizeInBytes, std::max(total.Alignment, one.Alignment)}; + } + return failed ? kInvalidAllocation : total; + } + + // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. + D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& desc) const { + constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, + align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, + align_msaa_4m = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT; + constexpr D3D12_RESOURCE_FLAGS attachment = + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + if (!desc.Width || desc.Width > UINT64_MAX - align_64k || desc.Height != 1 || desc.DepthOrArraySize != 1 || + desc.MipLevels != 1 || desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || + desc.SampleDesc.Quality != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || + (desc.Alignment && desc.Alignment != align_64k) || (desc.Flags & attachment)) + return kInvalidAllocation; + return {align_up(desc.Width, align_64k), align_64k}; + } + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if (!volume && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN) + log_once("GetResourceAllocationInfo dimension not supported:", desc.Dimension); + return kInvalidAllocation; + } + const UINT samples = desc.SampleDesc.Count, depth = volume ? desc.DepthOrArraySize : 1; + const UINT64 max_extent = + volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; + const UINT max_layers = + volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION; + if (!desc.Width || !desc.Height || !desc.DepthOrArraySize || desc.Width > max_extent || + desc.Height > max_extent || desc.DepthOrArraySize > max_layers || !samples || samples > 16 || + (samples & (samples - 1)) || desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR) + return kInvalidAllocation; + const UINT16 full = full_mips(desc.Width, desc.Height, depth); + D3D12_RESOURCE_DESC resolved = desc; + if (!resolved.MipLevels) resolved.MipLevels = full; + if (resolved.MipLevels > full) return kInvalidAllocation; + if (samples > 1 && + (volume || resolved.MipLevels != 1 || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) + return kInvalidAllocation; + if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) + log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout); + + const Format format = state_.texture_format(desc); + if (!format.format) { + log_once("GetResourceAllocationInfo format not supported yet:", desc.Format); + return kInvalidAllocation; + } + VkMemoryRequirements need{}; + if (!state_.memory_requirements(texture_create_info(resolved, format), need)) return kInvalidAllocation; + + // D3D12's alignment: 64 KiB, or 4 MiB with MSAA, unless the description asks for a small one (4 KiB, 64 KiB + // with MSAA). 4 KiB needs the resource to fit in 64 KiB and not be a render target or depth buffer; if it + // doesn't qualify, the PC runtime calls the description invalid rather than answering with 64 KiB. The MSAA + // 64 KiB alignment has no size limit there. Both measured in d3d12_vulkan_device_test. + UINT64 alignment = 0; + if (samples > 1) { + if (desc.Alignment && desc.Alignment != align_msaa_64k && desc.Alignment != align_msaa_4m) + return kInvalidAllocation; + alignment = desc.Alignment ? desc.Alignment : align_msaa_4m; + } else { + if (desc.Alignment && desc.Alignment != align_4k && desc.Alignment != align_64k) return kInvalidAllocation; + if (desc.Alignment == align_4k && ((desc.Flags & attachment) || need.size > align_64k)) + return kInvalidAllocation; + alignment = desc.Alignment ? desc.Alignment : align_64k; + } + return {align_up(need.size, alignment), alignment}; + } + DeviceState state_; OwnedRuntime owned_; IUnknown* outer_ = nullptr; // the Xbox-ABI proxy, which owns a reference to this device @@ -782,6 +944,21 @@ VkImage vulkan_image(ID3D12Resource* resource) { return r ? r->image() : VK_NULL_HANDLE; } +bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src) { + if (!dst || !src) return false; + const Format requested = vulkan_format(format, false); + if (requested.typeless || requested.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return false; + if (format == DXGI_FORMAT_R32G32B32A32_UINT || format == DXGI_FORMAT_R8G8B8A8_UINT || + format == DXGI_FORMAT_R32_UINT) + return false; + const auto matches = [&](ID3D12Resource* resource) { + const D3D12_RESOURCE_DESC desc = resource->GetDesc(); + return vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL).format == + requested.format; + }; + return matches(dst) && matches(src); +} + std::uint32_t device_max_push_constants_size(ID3D12Device* device) { if (!device) return 0; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp new file mode 100644 index 000000000..79fb73de9 --- /dev/null +++ b/runtime/shims/process.cpp @@ -0,0 +1,199 @@ +// Process-level imports of a mapped executable: its command line and its way out. +// +// `gta6rt --run` calls a mapped EXE's entry point inside the gta6rt process. The EXE's CRT startup asks for its +// arguments and finally calls exit(); both go through the EXE's own import table, so they can be answered here: +// - argv/argc and the command line are the game's (set by run_entry), not gta6rt's; +// - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host: +// the exit code is recorded, the run is signalled as finished and the calling thread ends. atexit handlers +// and static destructors of the game are not run (its CRT shares the host's, whose process-wide atexit table +// also holds gta6rt's own). +// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links) and +// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. +#include + +#include +#include +#include +#include +#include +#include + +#include "process.h" +#include "shims.h" + +namespace rt::process { +namespace { + +std::vector g_args; +std::vector g_wargs; +std::vector g_argv; +std::vector g_wargv; +std::string g_cmdline; +std::wstring g_wcmdline; +int g_argc = 0; +char** g_argv_ptr = nullptr; +wchar_t** g_wargv_ptr = nullptr; +char** g_env = nullptr; +wchar_t** g_wenv = nullptr; + +std::atomic g_exited{false}; +std::atomic g_exit_code{0}; +HANDLE g_done = nullptr; + +std::string quote(const std::string& a) { + if (!a.empty() && a.find_first_of(" \t\"") == std::string::npos) return a; + std::string out = "\""; + for (char c : a) { + if (c == '"') out += '\\'; + out += c; + } + return out + "\""; +} + +std::wstring widen(const std::string& s) { + int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0); + std::wstring w(n > 0 ? n - 1 : 0, L'\0'); + if (n > 1) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, w.data(), n); + return w; +} + +[[noreturn]] void end_run(int code) { + bool expected = false; + if (g_exited.compare_exchange_strong(expected, true)) { + g_exit_code = code; + if (g_done) SetEvent(g_done); + ExitThread(static_cast(code)); + } + // The run is already over: this is game code running during host shutdown (an atexit handler the game + // registered with the shared CRT calling exit again). Finish the process with the game's exit code; ending + // just this thread here would make the host's last thread, and so the process, exit with `code` instead. + ExitProcess(static_cast(g_exit_code.load())); +} + +// ---- the way out +void __cdecl game_exit(int code) { end_run(code); } +void __stdcall game_exit_process(UINT code) { end_run(static_cast(code)); } +void __cdecl game_abort() { + std::fprintf(stderr, "[rt] process: the game called abort()\n"); + end_run(3); // the CRT's abort exit code +} + +// ---- arguments +int* __cdecl game_p_argc() { return &g_argc; } +char*** __cdecl game_p_argv() { return &g_argv_ptr; } +wchar_t*** __cdecl game_p_wargv() { return &g_wargv_ptr; } +int __cdecl game_configure_argv(int) { return 0; } // already parsed: run_entry set them +LPSTR __stdcall game_get_command_line_a() { return g_cmdline.data(); } +LPWSTR __stdcall game_get_command_line_w() { return g_wcmdline.data(); } +char** __cdecl game_p_acmdln_storage() { + static char* p = nullptr; + p = g_cmdline.data(); + return &p; +} +wchar_t** __cdecl game_p_wcmdln_storage() { + static wchar_t* p = nullptr; + p = g_wcmdline.data(); + return &p; +} + +// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo) +int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) { + *argc = g_argc; + *argv = g_argv_ptr; + if (env) *env = g_env; + return 0; +} +int __cdecl game_wgetmainargs(int* argc, wchar_t*** argv, wchar_t*** env, int, void*) { + *argc = g_argc; + *argv = g_wargv_ptr; + if (env) *env = g_wenv; + return 0; +} + +struct EntryCall { + void* entry; +}; + +DWORD WINAPI game_thread(void* p) { + auto* call = static_cast(p); + // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code. + auto entry = reinterpret_cast(call->entry); + const DWORD code = entry(nullptr); + end_run(static_cast(code)); // returning from the entry point is an exit too +} + +} // namespace + +void set_command_line(const std::string& program, const std::vector& args) { + g_args.clear(); + g_args.push_back(program); + g_args.insert(g_args.end(), args.begin(), args.end()); + g_wargs.clear(); + g_cmdline.clear(); + for (auto& a : g_args) { + g_wargs.push_back(widen(a)); + if (!g_cmdline.empty()) g_cmdline += ' '; + g_cmdline += quote(a); + } + g_wcmdline = widen(g_cmdline); + g_argv.clear(); + g_wargv.clear(); + for (auto& a : g_args) g_argv.push_back(a.data()); + for (auto& a : g_wargs) g_wargv.push_back(a.data()); + g_argv.push_back(nullptr); + g_wargv.push_back(nullptr); + g_argc = static_cast(g_args.size()); + g_argv_ptr = g_argv.data(); + g_wargv_ptr = g_wargv.data(); + g_env = _environ; + g_wenv = _wenviron; +} + +int run_entry(void* entry, size_t stack_bytes) { + g_exited = false; + g_exit_code = 0; + g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + EntryCall call{entry}; + HANDLE thread = CreateThread(nullptr, stack_bytes, game_thread, &call, STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr); + if (!thread) { + CloseHandle(g_done); + g_done = nullptr; + return -1; + } + // The run ends when any game thread exits the process (exit/ExitProcess/abort) or the entry point returns. + HANDLE waits[] = {g_done, thread}; + WaitForMultipleObjects(2, waits, FALSE, INFINITE); + CloseHandle(thread); + CloseHandle(g_done); + g_done = nullptr; + return g_exit_code.load(); +} + +} // namespace rt::process + +namespace { +using namespace rt::process; +#define UCRT(dll) \ + {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_exit)}, \ + {dll, "_Exit", reinterpret_cast(&game_exit)}, {dll, "quick_exit", reinterpret_cast(&game_exit)}, \ + {dll, "abort", reinterpret_cast(&game_abort)}, {dll, "__p___argc", reinterpret_cast(&game_p_argc)}, \ + {dll, "__p___argv", reinterpret_cast(&game_p_argv)}, \ + {dll, "__p___wargv", reinterpret_cast(&game_p_wargv)}, \ + {dll, "_configure_narrow_argv", reinterpret_cast(&game_configure_argv)}, \ + {dll, "_configure_wide_argv", reinterpret_cast(&game_configure_argv)}, \ + {dll, "__p__acmdln", reinterpret_cast(&game_p_acmdln_storage)}, \ + {dll, "__p__wcmdln", reinterpret_cast(&game_p_wcmdln_storage)} +} // namespace + +SHIM_TABLE(process, + UCRT("api-ms-win-crt-runtime-l1-1-0.dll"), + UCRT("ucrtbase.dll"), + {"msvcrt.dll", "exit", reinterpret_cast(&game_exit)}, + {"msvcrt.dll", "_exit", reinterpret_cast(&game_exit)}, + {"msvcrt.dll", "abort", reinterpret_cast(&game_abort)}, + {"msvcrt.dll", "__getmainargs", reinterpret_cast(&game_getmainargs)}, + {"msvcrt.dll", "__wgetmainargs", reinterpret_cast(&game_wgetmainargs)}, + {"kernel32.dll", "ExitProcess", reinterpret_cast(&game_exit_process)}, + {"kernel32.dll", "GetCommandLineA", reinterpret_cast(&game_get_command_line_a)}, + {"kernel32.dll", "GetCommandLineW", reinterpret_cast(&game_get_command_line_w)}, +); diff --git a/runtime/shims/process.h b/runtime/shims/process.h new file mode 100644 index 000000000..62bc828c3 --- /dev/null +++ b/runtime/shims/process.h @@ -0,0 +1,17 @@ +// The game's command line and exit, for `gta6rt --run` (shims/process.cpp). +#pragma once +#include +#include +#include + +namespace rt::process { + +// What the game sees as argv[0..] and GetCommandLine: `program` then `args`, quoted where needed. +void set_command_line(const std::string& program, const std::vector& args); + +// Runs a mapped EXE's entry point on a new thread with `stack_bytes` of reserved stack and returns the game's +// exit code: the entry point's return value, or what it passed to exit/ExitProcess (3 for abort). Returns when +// the first of those happens; other game threads are left running (the host process ends them when it exits). +int run_entry(void* entry, std::size_t stack_bytes = 8u << 20); + +} // namespace rt::process diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 83b5df40d..cded8c843 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -269,13 +270,20 @@ struct CopyResource { ResourceId src; }; -// ResolveSubresource: a multisampled subresource into a single-sampled one of the same size. The call's format is -// not kept: the resolve uses the textures' own format, which D3D12 requires to be compatible. +struct ResolveRegion { + std::uint32_t dst_x; + std::uint32_t dst_y; + std::optional src_rect; +}; + +// Without a region, both subresources have the same extent. A region with no source rectangle takes the +// entire source to the given destination offset. The resolve uses the images' own format. struct ResolveSubresource { ResourceId dst; std::uint32_t dst_subresource; ResourceId src; std::uint32_t src_subresource; + std::optional region = std::nullopt; }; // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. @@ -363,6 +371,12 @@ public: // A resource has one sample count, so it cannot be resolved into itself. bool resolve_subresource(const ResolveSubresource& resolve) { if (!resolve.dst || !resolve.src || resolve.dst == resolve.src) return false; + if (const auto& region = resolve.region) { + if (region->dst_x > INT32_MAX || region->dst_y > INT32_MAX) return false; + if (const auto& r = region->src_rect; + r && (r->left < 0 || r->top < 0 || r->right <= r->left || r->bottom <= r->top)) + return false; + } return append(resolve); } diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 4477c4a69..d79ff97dc 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -6,13 +6,21 @@ // // gta6rt --init [--game-dir DIR] // The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. +// +// gta6rt --run [--game-dir DIR] [-- game arguments...] +// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and +// command line are plus the arguments after "--"; exit/ExitProcess from the game end the run +// (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code. #include #include #include #include +#include #include "pe_loader.h" +#include "../shims/process.h" +#include "../shims/shims.h" namespace { @@ -28,7 +36,8 @@ const char* binding_name(rt::Binding b) { int usage() { std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR]\n" - " gta6rt --init [--game-dir DIR]\n"); + " gta6rt --init [--game-dir DIR]\n" + " gta6rt --run [--game-dir DIR] [-- game arguments...]\n"); return 2; } @@ -36,28 +45,29 @@ int usage() { int wmain(int argc, wchar_t** argv) { std::filesystem::path image, game_dir; - bool dry_run = false, init = false; + bool dry_run = false, init = false, run = false; + std::vector game_args; for (int i = 1; i < argc; ++i) { std::wstring a = argv[i]; + if (a == L"--") { + for (++i; i < argc; ++i) game_args.push_back(std::filesystem::path(argv[i]).string()); + break; + } if (a == L"--dry-run") dry_run = true; else if (a == L"--init") init = true; + else if (a == L"--run") run = true; else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; else if (image.empty()) image = a; else return usage(); } if (image.empty()) return usage(); - if (!dry_run && !init) { - std::fprintf(stderr, - "Only --dry-run and --init exist so far: running game code needs the shims listed by " - "--dry-run first.\n"); - return 2; - } + if (!dry_run && !init && !run) return usage(); if (game_dir.empty()) game_dir = image.parent_path(); try { rt::Loader loader(game_dir); - loader.load(image); - if (init) { + rt::Module& main_module = loader.load(image); + if (init || run) { loader.initialise(); std::printf("%zu module(s) initialised\n", loader.modules().size()); } @@ -76,7 +86,23 @@ int wmain(int argc, wchar_t** argv) { } } std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); - return 0; + if (!run) return 0; + if (!main_module.entry_rva) { + std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); + return 1; + } + rt::process::set_command_line(image.filename().string(), game_args); + std::printf("running %s\n", main_module.name.c_str()); + std::fflush(stdout); + const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); + std::fflush(stdout); + std::printf("game exited with code %d\n", code); + rt::shims::report_called_unimplemented(); + std::fflush(stdout); + std::fflush(stderr); + // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its + // handlers would run against a game that has stopped) and whose last word decides the exit status. + ExitProcess(static_cast(code)); } catch (const std::exception& e) { std::fprintf(stderr, "error: %s\n", e.what()); return 1; diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp index 79a633b61..bdd181f08 100644 --- a/runtime/src/root_signature.cpp +++ b/runtime/src/root_signature.cpp @@ -92,6 +92,13 @@ private: constexpr uint32_t kCanonicalMagic = 0x3153524Cu; // "LRS1" little-endian constexpr uint32_t kCanonicalVersion = 1; +// D3D_ROOT_SIGNATURE_VERSION 1 (1.0), 2 (1.1), 3 (1.2): the numbering RTS0 and the canonical codec both store. +bool known_version(uint32_t v, Version& out) { + if (v < 1 || v > 3) return false; + out = static_cast(v); + return true; +} + } // namespace std::vector encode_canonical(const RootSignature& sig) { @@ -130,6 +137,7 @@ std::vector encode_canonical(const RootSignature& sig) { put_u32(out, s.shader_register); put_u32(out, s.register_space); put_u32(out, static_cast(s.visibility)); + if (sig.version == Version::V1_2) put_u32(out, s.flags); } return out; } @@ -155,7 +163,7 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { out.error = "truncated canonical header"; return out; } - if (ver != 1 && ver != 2) { + if (!known_version(ver, out.sig.version)) { out.error = "unknown root-signature version"; return out; } @@ -167,7 +175,6 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { out.error = "absurd sampler count"; return out; } - out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1; out.sig.params.reserve(nparams); for (uint32_t i = 0; i < nparams; ++i) { RootParameter p; @@ -206,7 +213,8 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { if (!r.u32(s.filter) || !r.u32(s.address_u) || !r.u32(s.address_v) || !r.u32(s.address_w) || !r.f32(s.mip_lod_bias) || !r.u32(s.max_anisotropy) || !r.u32(s.comparison_func) || !r.u32(s.border_color) || !r.f32(s.min_lod) || !r.f32(s.max_lod) || - !r.u32(s.shader_register) || !r.u32(s.register_space) || !r.u32(vis)) { + !r.u32(s.shader_register) || !r.u32(s.register_space) || !r.u32(vis) || + (out.sig.version == Version::V1_2 && !r.u32(s.flags))) { out.error = "truncated canonical sampler"; return out; } @@ -221,10 +229,12 @@ DecodeResult decode_canonical(const uint8_t* data, size_t size) { return out; } -// RTS0 payload hypothesis: u32 version (1 = 1.0, 2 = 1.1), u32 num_params, +// RTS0 payload: u32 version (1 = 1.0, 2 = 1.1, 3 = 1.2), u32 num_params, // u32 num_static_samplers, u32 flags, then per-parameter fields in d3d12.h -// order. Static samplers follow the same field order as D3D12_STATIC_SAMPLER_DESC. -// Anything else (v1.2 blobs, extra dwords, truncation) is a hard error. +// order. Static samplers follow the field order of D3D12_STATIC_SAMPLER_DESC, and +// of D3D12_STATIC_SAMPLER_DESC1 (one more dword, Flags) in 1.2. Root descriptors +// and ranges have a flags dword from 1.1 on. Anything else (unknown versions, +// truncation) is a hard error. // Payload decoder: the RTS0 chunk contents (see header for the hypothesis). static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { DecodeResult out; @@ -264,8 +274,8 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "truncated RTS0 header"; return out; } - if (ver != 1 && ver != 2) { - out.error = "unknown RTS0 version (not 1.0/1.1)"; + if (!known_version(ver, out.sig.version)) { + out.error = "unknown RTS0 version (not 1.0/1.1/1.2)"; return out; } if (nparams > 64) { @@ -276,7 +286,7 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "RTS0 with absurd sampler count"; return out; } - out.sig.version = ver == 1 ? Version::V1_0 : Version::V1_1; + const bool flags_v11 = ver >= 2; // descriptor and range flags (1.1 and 1.2) out.sig.flags = flags; // Parameter table at params_off: num_params x {u32 d3d_type, u32 // visibility, u32 offset}. d3d_type follows D3D12_ROOT_PARAMETER_TYPE @@ -307,7 +317,7 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { } else if (dtype == 2 || dtype == 3 || dtype == 4) { p.type = ParamType::Descriptor; uint32_t dflags = 0; - const size_t need = ver == 2 ? 12 : 8; + const size_t need = flags_v11 ? 12 : 8; if (poff > size || need > size - static_cast(poff)) { out.error = "truncated RTS0 descriptor payload"; return out; @@ -316,15 +326,17 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "truncated RTS0 descriptor payload"; return out; } - if (ver == 2 && !u32_at(poff + 8, dflags)) { + if (flags_v11 && !u32_at(poff + 8, dflags)) { out.error = "truncated RTS0 descriptor flags"; return out; } (void)dflags; // descriptor flags do not affect the user-SGPR map } else if (dtype == 0) { p.type = ParamType::Table; - uint32_t nranges = 0; - if (!u32_at(poff, nranges)) { + // Table payload: {u32 num_ranges, u32 ranges_offset}; the ranges sit at ranges_offset (from the payload + // start), like every other table in RTS0. Measured against the PC serializer (root_signature_oracle_test). + uint32_t nranges = 0, ranges_off = 0; + if (!u32_at(poff, nranges) || !u32_at(static_cast(poff) + 4, ranges_off)) { out.error = "truncated RTS0 table payload"; return out; } @@ -332,22 +344,21 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { out.error = "absurd RTS0 range count"; return out; } - // Range record: {type, num, base_reg, space, offset} (+ flags on 1.1). - const size_t stride = ver == 2 ? 24 : 20; - if (nranges > 0 && - (poff + 4 > size || nranges > (size - (poff + 4)) / stride)) { + // Range record: {type, num, base_reg, space, offset} (+ flags on 1.1 and 1.2). + const size_t stride = flags_v11 ? 24 : 20; + if (nranges > 0 && (ranges_off > size || nranges > (size - ranges_off) / stride)) { out.error = "RTS0 ranges overrun their payload"; return out; } p.ranges.reserve(nranges); for (uint32_t j = 0; j < nranges; ++j) { - const size_t roff = static_cast(poff) + 4 + j * stride; + const size_t roff = static_cast(ranges_off) + j * stride; DescriptorRange range; uint32_t base_reg = 0, space = 0, disp_off = 0, rflags = 0; if (!u32_at(roff, range.range_type) || !u32_at(roff + 4, range.num_descriptors) || !u32_at(roff + 8, base_reg) || !u32_at(roff + 12, space) || !u32_at(roff + 16, disp_off) || - (ver == 2 && !u32_at(roff + 20, rflags))) { + (flags_v11 && !u32_at(roff + 20, rflags))) { out.error = "truncated RTS0 range"; return out; } @@ -363,8 +374,9 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { } out.sig.params.push_back(std::move(p)); } - // Sampler records mirror D3D12_STATIC_SAMPLER_DESC field order. - constexpr size_t kSamplerBytes = 13 * 4; + // Sampler records mirror D3D12_STATIC_SAMPLER_DESC field order; 1.2 appends Flags (D3D12_STATIC_SAMPLER_DESC1). + const bool sampler_flags = ver == 3; + const size_t kSamplerBytes = (sampler_flags ? 14 : 13) * 4; if (nsamplers > 0 && (samplers_off > size || nsamplers > (size - samplers_off) / kSamplerBytes)) { out.error = "RTS0 samplers overrun their payload"; @@ -381,7 +393,7 @@ static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { !u32_at(soff + 24, s.comparison_func) || !u32_at(soff + 28, s.border_color) || !f32_at(soff + 32, s.min_lod) || !f32_at(soff + 36, s.max_lod) || !u32_at(soff + 40, s.shader_register) || !u32_at(soff + 44, s.register_space) || - !u32_at(soff + 48, vis)) { + !u32_at(soff + 48, vis) || (sampler_flags && !u32_at(soff + 52, s.flags))) { out.error = "truncated RTS0 sampler"; return out; } diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h index 4c19cf72d..d5edcf2f0 100644 --- a/runtime/src/root_signature.h +++ b/runtime/src/root_signature.h @@ -17,8 +17,8 @@ namespace rt::rootsig { -// D3D12_ROOT_SIGNATURE_VERSION subset the layer handles. -enum class Version : uint32_t { V1_0 = 1, V1_1 = 2 }; +// D3D12_ROOT_SIGNATURE_VERSION subset the layer handles. 1.2 is 1.1 plus a flags dword on each static sampler. +enum class Version : uint32_t { V1_0 = 1, V1_1 = 2, V1_2 = 3 }; // D3D12_ROOT_PARAMETER_TYPE subset (order matches D3D12 docs). enum class ParamType : uint32_t { @@ -59,6 +59,9 @@ struct StaticSampler { uint32_t shader_register = 0; uint32_t register_space = 0; Visibility visibility = Visibility::All; + // D3D12_SAMPLER_FLAGS (D3D12_STATIC_SAMPLER_DESC1, version 1.2 only): 1 UINT border colour, 2 non-normalized + // coordinates. Earlier versions have no such field; it stays 0 and the codecs neither write nor read it. + uint32_t flags = 0; }; struct RootParameter { @@ -123,6 +126,8 @@ constexpr uint32_t kMaxD3d12Cost = 64; // little-endian). This is Leonida's own layout, NOT the Microsoft RTS0 // format: it round-trips pack() inputs byte-exactly and is fully tested on // every CI leg. Never write game blobs in this format and claim otherwise. +// Static samplers carry their flags dword only in version 1.2 signatures, so +// 1.0/1.1 encodings are unchanged. [[nodiscard]] std::vector encode_canonical(const RootSignature& sig); struct DecodeResult { @@ -144,6 +149,9 @@ struct DecodeResult { // numbering). A bare payload without the DXBC header is also accepted // (unit-test path). Every deviation the oracle test finds is a hard failure // to investigate, not a quirk to absorb. +// Versions 1 (1.0), 2 (1.1) and 3 (1.2): 1.1 and 1.2 add a flags dword to +// root descriptors and ranges; 1.2 adds one to each static sampler (13 dwords +// before, 14 after), as the PC serializer writes them (root_signature_oracle_test). // Returns ok == false with a reason for unknown versions or truncation. [[nodiscard]] DecodeResult parse_rts0(const uint8_t* data, size_t size); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 1bcee80a3..1bd38ae93 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -225,6 +226,90 @@ inline VkAccessFlags2 vulkan_barrier_access(std::uint32_t access) { return out; } +// For one VkAccessFlagBits2 that vulkan_barrier_access produces: the stages Vulkan lets perform it (the "supported +// access types" table of the synchronization2 chapter, with the meta stages that contain them), and the narrowest +// stage to add when a barrier's stages have none of those. MEMORY_READ/WRITE are valid in every stage. +struct AccessStages { + VkAccessFlags2 access; + VkPipelineStageFlags2 supported; + VkPipelineStageFlags2 narrowest; +}; + +inline constexpr VkPipelineStageFlags2 shader_stages2 = + VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT | + VK_PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT | + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; + +inline constexpr AccessStages access_stages[] = { + {VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT, + VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, + {VK_ACCESS_2_INDEX_READ_BIT, + VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT | VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT}, + {VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT, + VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT | VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT | + VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT}, + // Shader accesses: D3D12 does not say which shader stage, so every one that can run (all shading). + {VK_ACCESS_2_UNIFORM_READ_BIT, shader_stages2, + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, + {VK_ACCESS_2_SHADER_READ_BIT, shader_stages2, + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, + {VK_ACCESS_2_SHADER_WRITE_BIT, shader_stages2, + VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, + {VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, + {VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | + VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, + {VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT | + VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, + {VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT | + VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, + // Transfers: ALL_GRAPHICS does not contain the transfer stages, and CLEAR only writes. + {VK_ACCESS_2_TRANSFER_READ_BIT, + VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_BLIT_BIT | VK_PIPELINE_STAGE_2_RESOLVE_BIT | + VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT}, + {VK_ACCESS_2_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_BLIT_BIT | VK_PIPELINE_STAGE_2_RESOLVE_BIT | + VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT}, +}; + +// One side of an enhanced barrier: D3D12 sync and access to a Vulkan stage mask and access mask that Vulkan accepts +// together. D3D12 lets an access be named with a sync scope whose Vulkan stages cannot perform it (SYNC_ALL_SHADING +// with ACCESS_VERTEX_BUFFER is valid D3D12, but VERTEX_ATTRIBUTE_READ needs VERTEX_ATTRIBUTE_INPUT). The stages are +// widened by the narrowest stage that can, never the access dropped: the dependency still covers every access the +// application named, only over a slightly larger scope. With no stages (SYNC_NONE) there is no access either. +struct BarrierScope { + VkPipelineStageFlags2 stages; + VkAccessFlags2 access; +}; + +inline BarrierScope vulkan_barrier_scope(std::uint32_t sync, std::uint32_t access) { + BarrierScope out{vulkan_sync(sync), 0}; + if (!out.stages) return out; + out.access = vulkan_barrier_access(access); + for (const AccessStages& entry : access_stages) + if ((out.access & entry.access) && !(out.stages & entry.supported)) out.stages |= entry.narrowest; + return out; +} + // D3D12_BARRIER_LAYOUT -> VkImageLayout. Queue-specific layouts map like their generic forms. inline VkImageLayout vulkan_layout(std::uint32_t layout, bool presentable) { namespace l = d3d12_layout; @@ -499,6 +584,32 @@ struct Prepared { VkImageResolve resolve{}; // resolves }; +// ClearRenderTargetView takes FLOATs even for integer RTVs. For the UINT formats currently exposed by +// the device, Windows D3D12 (WARP and AMD) clamps to the component range and truncates fractions. Vulkan +// instead interprets the matching union member as an integer already; copying float bits changes the value. +inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearColor& input) { + std::uint32_t maximum = 0; + switch (format) { + case VK_FORMAT_R8G8B8A8_UINT: maximum = 255; break; + case VK_FORMAT_R32_UINT: + case VK_FORMAT_R32G32B32A32_UINT: maximum = std::numeric_limits::max(); break; + default: break; + } + VkClearColorValue value{}; + for (std::size_t i = 0; i < input.size(); ++i) { + if (!maximum) { + value.float32[i] = input[i]; + } else if (!(input[i] > 0.0f)) { + value.uint32[i] = 0; // NaN, negative values and either zero; no out-of-range float-to-int cast. + } else if (double(input[i]) >= double(maximum)) { + value.uint32[i] = maximum; // Includes +infinity; UINT32_MAX itself is not representable as float. + } else { + value.uint32[i] = static_cast(input[i]); + } + } + return value; +} + inline bool view_range(const ResourceBinding& resource, const TargetView& view, VkImageAspectFlags aspects, VkImageSubresourceRange& out) { if (view.mip >= resource.mip_levels) return false; @@ -724,9 +835,7 @@ inline ReplayResult prepare_resource_copy(Prepared& p) { return ReplayResult::success; } -// ResolveSubresource through vkCmdResolveImage: a multisampled colour subresource into a single-sampled one of -// the same size and format. Depth-stencil resolves, and resolves between two formats of a typeless family, are -// not supported yet. +// Resolve a multisampled colour image into a single-sampled image of the same format. inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& p) { VkImageSubresourceRange dst{}, src{}; if (!copy_subresource(p.binding, resolve.dst_subresource, dst) || @@ -734,13 +843,26 @@ inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& return ReplayResult::invalid_subresource; if (p.source.samples <= 1 || p.binding.samples != 1 || p.binding.volume) return ReplayResult::invalid_copy; const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); - if (from.width != to.width || from.height != to.height) return ReplayResult::invalid_copy; + VkOffset3D src_offset{}, dst_offset{}; + VkExtent3D extent{from.width, from.height, 1}; + if (const auto& region = resolve.region) { + dst_offset = {std::int32_t(region->dst_x), std::int32_t(region->dst_y), 0}; + if (const auto& r = region->src_rect) { + if (std::uint32_t(r->right) > from.width || std::uint32_t(r->bottom) > from.height) + return ReplayResult::invalid_copy; + src_offset = {r->left, r->top, 0}; + extent = {std::uint32_t(r->right - r->left), std::uint32_t(r->bottom - r->top), 1}; + } + if (!within(region->dst_x, extent.width, to.width) || !within(region->dst_y, extent.height, to.height)) + return ReplayResult::invalid_copy; + } else if (from.width != to.width || from.height != to.height) { + return ReplayResult::invalid_copy; + } if (src.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || dst.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || p.source.format != p.binding.format) return ReplayResult::unsupported; - p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, {0, 0, 0}, - {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, {0, 0, 0}, - {from.width, from.height, 1}}; + p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, src_offset, + {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, dst_offset, extent}; p.range = dst; p.source_range = src; return ReplayResult::success; @@ -963,11 +1085,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c return {}; }, command); + const BarrierScope src = vulkan_barrier_scope(sync_before, access_before); + const BarrierScope dst = vulkan_barrier_scope(sync_after, access_after); VkMemoryBarrier2 barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER_2}; - barrier.srcStageMask = vulkan_sync(sync_before); - barrier.dstStageMask = vulkan_sync(sync_after); - barrier.srcAccessMask = barrier.srcStageMask ? vulkan_barrier_access(access_before) : 0; - barrier.dstAccessMask = barrier.dstStageMask ? vulkan_barrier_access(access_after) : 0; + barrier.srcStageMask = src.stages; + barrier.dstStageMask = dst.stages; + barrier.srcAccessMask = src.access; + barrier.dstAccessMask = dst.access; VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; dependency.memoryBarrierCount = 1; dependency.pMemoryBarriers = &barrier; @@ -987,13 +1111,15 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c pieces = detail::current(tracker, id, range, before); detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); } + const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before); + const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after); std::vector barriers; for (const auto& piece : pieces) { VkImageMemoryBarrier2 b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; - b.srcStageMask = vulkan_sync(texture->sync_before); - b.dstStageMask = vulkan_sync(texture->sync_after); - b.srcAccessMask = b.srcStageMask ? vulkan_barrier_access(texture->access_before) : 0; - b.dstAccessMask = b.dstStageMask ? vulkan_barrier_access(texture->access_after) : 0; + b.srcStageMask = src.stages; + b.dstStageMask = dst.stages; + b.srcAccessMask = src.access; + b.dstAccessMask = dst.access; b.oldLayout = piece.layout; b.newLayout = new_layout; b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; @@ -1012,8 +1138,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); - VkClearColorValue color{}; - std::copy(color_clear->color.begin(), color_clear->color.end(), color.float32); + const VkClearColorValue color = detail::render_target_clear_color(p.binding.format, color_clear->color); if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding.image, pieces, image_layout(p.binding, transfer_dst.layout), state, transfer_dst.access, transfer_dst.stages, [&] { diff --git a/runtime/test/clear_color_test.cpp b/runtime/test/clear_color_test.cpp new file mode 100644 index 000000000..8da8c9eef --- /dev/null +++ b/runtime/test/clear_color_test.cpp @@ -0,0 +1,81 @@ +// Value-level replay regression: full and rectangular UINT clears must carry integer values, not float bits. +// No Vulkan loader, GPU, shaders or game data. Expected conversions also match the WARP differential GPU test. +#include "../src/vulkan_replay.h" +#include +#include +#include +#include + +namespace { +VkClearColorValue captured{}; +unsigned calls = 0; +VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) {} +VKAPI_ATTR void VKAPI_CALL clear(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue* color, + std::uint32_t, const VkImageSubresourceRange*) { captured = *color; ++calls; } +VKAPI_ATTR void VKAPI_CALL begin(VkCommandBuffer, const VkRenderingInfo*) {} +VKAPI_ATTR void VKAPI_CALL end(VkCommandBuffer) {} +VKAPI_ATTR void VKAPI_CALL attachments(VkCommandBuffer, std::uint32_t n, const VkClearAttachment* a, + std::uint32_t, const VkClearRect*) { if (n == 1) { captured = a[0].clearValue.color; ++calls; } } + +bool replay_color(VkFormat format, const leonida::ClearColor& color, bool rectangle) { + leonida::CommandList list; + const leonida::Rect rect{1, 1, 3, 3}; + if (!list.clear_render_target({1, 0, 0, 1}, color, + rectangle ? std::span(&rect, 1) : std::span{}) || !list.close()) return false; + leonida::ResourceBinding binding{}; + binding.image = reinterpret_cast(std::uintptr_t{1}); + binding.format = format; + binding.width = binding.height = 4; + leonida::ReplayFunctions vk{}; + vk.pipeline_barrier = barrier; + vk.clear_color_image = clear; + vk.begin_rendering = begin; + vk.end_rendering = end; + vk.clear_attachments = attachments; + vk.image_view = [](const auto&, const auto&) { return reinterpret_cast(std::uintptr_t{1}); }; + calls = 0; + return leonida::replay(list, VK_NULL_HANDLE, [&](auto) { return &binding; }, vk) == leonida::ReplayResult::success && calls == 1; +} +} // namespace + +int main() { + const float nan = std::numeric_limits::quiet_NaN(), inf = std::numeric_limits::infinity(); + struct Case { leonida::ClearColor color; std::array u8, u32; }; + const Case cases[] = { + {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}}, + {{1.5f, 2.5f, 3.5f, 4.5f}, {1, 2, 3, 4}, {1, 2, 3, 4}}, + {{-1, -0.0f, 254.5f, 255.5f}, {0, 0, 254, 255}, {0, 0, 254, 255}}, + {{256, 65536, 16777216, 4294967296.0f}, {255, 255, 255, 255}, {256, 65536, 16777216, 0xffffffffu}}, + {{nan, inf, -inf, 0.5f}, {0, 255, 0, 0}, {0, 0xffffffffu, 0, 0}}, + {{0.499f, 0.501f, 1.499f, 1.501f}, {0, 0, 1, 1}, {0, 0, 1, 1}}, + {{4294967040.0f, std::numeric_limits::max(), 255, 0}, {255, 255, 255, 0}, {0xffffff00u, 0xffffffffu, 255, 0}}, + }; + unsigned checks = 0; + for (const auto& c : cases) { + for (const VkFormat format : {VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R32_UINT, VK_FORMAT_R32G32B32A32_UINT}) { + for (const bool rect : {false, true}) { + const auto& expected = format == VK_FORMAT_R8G8B8A8_UINT ? c.u8 : c.u32; + if (!replay_color(format, c.color, rect)) return 1; + for (unsigned i = 0; i < 4; ++i) { + if (captured.uint32[i] != expected[i]) { + std::fprintf(stderr, "UINT clear: format %d rect %d channel %u: got %u, expected %u\n", + int(format), int(rect), i, captured.uint32[i], expected[i]); + return 1; + } + } + ++checks; + } + } + for (const VkFormat format : {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_SFLOAT}) { + for (const bool rect : {false, true}) { + if (!replay_color(format, c.color, rect) || std::memcmp(captured.float32, c.color.data(), sizeof(captured)) != 0) + return 1; + ++checks; + } + } + } + std::printf("clear_color_test: %u full/rectangle UINT and float replay checks passed\n", checks); + return 0; +} diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index 49d52d6be..1983dbad2 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp @@ -255,6 +255,46 @@ int main() { CHECK(vulkan_barrier_access(a::common) == (VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT)); CHECK(vulkan_barrier_access(a::copy_source | a::shader_resource) == (VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_SHADER_READ_BIT)); + + // vulkan_barrier_scope: the stages are widened until every access has one that can perform it; the access is + // never dropped. (vk_command_replay_test part C checks every pair against the validation layer.) + { + const auto scope = [](std::uint32_t sync, std::uint32_t access) { return vulkan_barrier_scope(sync, access); }; + // Valid D3D12, invalid as mapped before: vertex-buffer reads under SYNC_ALL_SHADING. + BarrierScope widened = scope(y::all_shading, a::vertex_buffer); + CHECK(widened.access == VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT); + CHECK(widened.stages == (vulkan_sync(y::all_shading) | VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT)); + widened = scope(y::non_pixel_shading, a::index_buffer); + CHECK(widened.stages & VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT); + widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes + CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT); + widened = scope(y::copy, a::unordered_access); + CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)); + // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them. + const std::pair unchanged[] = { + {y::copy, a::copy_dest}, {y::pixel_shading, a::shader_resource}, + {y::render_target, a::render_target}, {y::depth_stencil, a::depth_stencil_write}, + {y::draw, a::vertex_buffer}, {y::vertex_shading, a::vertex_buffer}, + {y::index_input, a::index_buffer}, {y::execute_indirect, a::indirect_argument}, + {y::all, a::common}, {y::compute_shading, a::unordered_access}, + {y::clear_unordered_access_view, a::unordered_access}}; + for (const auto& [sync, access] : unchanged) { + const BarrierScope same = scope(sync, access); + CHECK(same.stages == vulkan_sync(sync) && same.access == vulkan_barrier_access(access)); + } + // No stages, no access (SYNC_NONE pairs with ACCESS_NO_ACCESS in D3D12). + CHECK(scope(y::none, a::no_access).stages == 0 && scope(y::none, a::no_access).access == 0); + CHECK(scope(y::none, a::shader_resource).access == 0); + // Every single sync bit against every single access bit: the stages only grow, the access never changes. + for (std::uint32_t s_bit = 1; s_bit; s_bit <<= 1) { + for (std::uint32_t a_bit = 1; a_bit; a_bit <<= 1) { + const BarrierScope any = scope(s_bit, a_bit); + CHECK((any.stages & vulkan_sync(s_bit)) == vulkan_sync(s_bit)); + CHECK(any.access == (vulkan_sync(s_bit) ? vulkan_barrier_access(a_bit) : 0)); + } + } + } CHECK(vulkan_layout(l::undefined, false) == VK_IMAGE_LAYOUT_UNDEFINED); CHECK(vulkan_layout(l::common, false) == VK_IMAGE_LAYOUT_GENERAL); CHECK(vulkan_layout(l::present, true) == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); diff --git a/runtime/test/d3d12_uint_clear_test.cpp b/runtime/test/d3d12_uint_clear_test.cpp new file mode 100644 index 000000000..b2f157a4a --- /dev/null +++ b/runtime/test/d3d12_uint_clear_test.cpp @@ -0,0 +1,166 @@ + +// Compare integer RTV clears against native Windows D3D12/WARP, through D3D12 clear/copy/Map on both sides. +// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include +#include +#include +#include +#include +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { +template +struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } +}; +struct Event { + HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); + ~Event() { if (handle) CloseHandle(handle); } +}; + +bool clear_and_read(ID3D12Device* device, DXGI_FORMAT format, unsigned bytes, const FLOAT* full, const FLOAT* part, + std::vector& pixels) { + Ref queue; + Ref allocator; + Ref list; + Ref fence; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + constexpr UINT width = 5, height = 3; // Odd dimensions expose incorrect treatment of footprint padding. + Ref image, readback; + D3D12_HEAP_PROPERTIES heap_properties{}; + heap_properties.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = width; + texture.Height = height; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = format; + texture.SampleDesc.Count = 1; + texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&image.p)))); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{}; + UINT64 total = 0; + device->GetCopyableFootprints(&texture, 0, 1, 0, &placed, nullptr, nullptr, &total); + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = total; + buffer.Height = buffer.SampleDesc.Count = 1; + buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + heap_properties.Type = D3D12_HEAP_TYPE_READBACK; + CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); + Ref heap; + const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)))); + const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(image.p, nullptr, handle); + list->ClearRenderTargetView(handle, full, 0, nullptr); + const D3D12_RECT rect{1, 1, 4, 3}; + list->ClearRenderTargetView(handle, part, 1, &rect); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = image.p; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = image.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = placed; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + CHECK(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); + Event event; + CHECK(event.handle); + CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle))); + CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); + void* mapped = nullptr; + const D3D12_RANGE range{0, SIZE_T(total)}; + CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped); + pixels.resize(width * height * bytes); + for (UINT y = 0; y < height; ++y) + std::memcpy(pixels.data() + y * width * bytes, + static_cast(mapped) + y * placed.Footprint.RowPitch, width * bytes); + const D3D12_RANGE none{}; + readback->Unmap(0, &none); + return true; +} +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 1; + const unsigned errors_before = vk.validation_errors(); + unsigned cases_checked = 0; + { + Ref ours, host; + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; + Ref factory; + Ref warp; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || + FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || + FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { + std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); + return 1; + } + const float nan = std::numeric_limits::quiet_NaN(), inf = std::numeric_limits::infinity(); + const std::array values[] = { + {1, 2, 3, 4}, {1.5f, 2.5f, 3.5f, 4.5f}, {-1, -0.0f, 254.5f, 255.5f}, + {256, 65536, 16777216, 4294967296.0f}, {nan, inf, -inf, 0.5f}, + {0.499f, 0.501f, 1.499f, 1.501f}, {4294967040.0f, std::numeric_limits::max(), 255, 0} + }; + const std::pair formats[] = { + {DXGI_FORMAT_R8G8B8A8_UINT, 4}, {DXGI_FORMAT_R32_UINT, 4}, {DXGI_FORMAT_R32G32B32A32_UINT, 16} + }; + for (const auto& [format, bytes] : formats) { + for (unsigned i = 0; i < std::size(values); ++i) { + // Different colours outside and inside the rectangle exercise both Vulkan clear paths. + const auto& full = values[i]; + const auto& part = values[(i + 1) % std::size(values)]; + std::vector actual, expected; + if (!clear_and_read(ours.p, format, bytes, full.data(), part.data(), actual) || + !clear_and_read(host.p, format, bytes, full.data(), part.data(), expected)) return 1; + if (actual != expected) { + for (std::size_t b = 0; b < actual.size(); ++b) { + if (actual[b] != expected[b]) { + std::fprintf(stderr, "format %d case %u byte %zu: Vulkan %02x, WARP %02x\n", + int(format), i, b, unsigned(actual[b]), unsigned(expected[b])); + break; + } + } + return 1; + } + ++cases_checked; + } + } + } // Destroy the D3D12 objects before checking the Vulkan validation counter. + if (vk.validation_errors() != errors_before) return 1; + std::printf("UINT RTV clears: %u full/rectangle readbacks matched WARP on three formats\n", cases_checked); + return 0; +} diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index dc69dcf6e..2298262ca 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -2,7 +2,8 @@ // the proxy the way the game will call it: device methods (forwarded slots), descriptor heaps from slot 14 with // start handles read in the Xbox shape (RAX), a texture from slot 76 with the Xbox layout word, committed // resources, views, command lists, a queue and a fence. Results are read back through D3D12 itself -// (CopyTextureRegion into a readback heap, then Map). GetCopyableFootprints is compared with the host PC runtime's. +// (CopyTextureRegion into a readback heap, then Map). GetCopyableFootprints and GetResourceAllocationInfo are +// compared with the host PC runtime's. // No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation // error fails the test. #include "vk_test_device.h" @@ -12,6 +13,7 @@ #include #include #include +#include #include #define EXPECT(condition) do { \ @@ -115,15 +117,20 @@ D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATE return barrier; } -// GetCopyableFootprints must match the PC runtime's exactly, since applications size and fill upload buffers from -// it. Returns the number of mismatches, or -1 when the host has no D3D12 device to compare with. -int compare_footprints(ID3D12Device* ours) { +// The host PC runtime's D3D12 device on the default adapter, to compare answers with; false if there is none. +bool create_host_device(Ref& host) { const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); const auto create = d3d12 ? reinterpret_cast( reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))) : nullptr; + return create && SUCCEEDED(create(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p))); +} + +// GetCopyableFootprints must match the PC runtime's exactly, since applications size and fill upload buffers from +// it. Returns the number of mismatches, or -1 when the host has no D3D12 device to compare with. +int compare_footprints(ID3D12Device* ours) { Ref host; - if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) return -1; + if (!create_host_device(host)) return -1; struct Case { D3D12_RESOURCE_DESC desc; UINT subresources; @@ -180,6 +187,123 @@ int compare_footprints(ID3D12Device* ours) { return mismatches; } +// GetResourceAllocationInfo against the PC runtime. Buffer sizes, every alignment and which descriptions are invalid +// must match it exactly. A texture's size is the driver's choice on both sides, so ours is only checked to be a +// whole number of alignments and at least the texels of its top mip; both sizes are printed. Also checks the +// Device4/Device8 variants' per-resource layout. Returns the number of mismatches, or -1 without a host device. +int compare_allocation_info(ID3D12Device* ours) { + Ref host; + if (!create_host_device(host)) return -1; + const auto with = [](D3D12_RESOURCE_DESC desc, UINT64 alignment, UINT samples = 1) { + desc.Alignment = alignment; + desc.SampleDesc.Count = samples; + return desc; + }; + constexpr UINT64 k4 = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, k64 = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + constexpr D3D12_RESOURCE_FLAGS none = D3D12_RESOURCE_FLAG_NONE, rt = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + constexpr DXGI_FORMAT rgba8 = DXGI_FORMAT_R8G8B8A8_UNORM; + struct Case { + const char* name; + D3D12_RESOURCE_DESC desc; + UINT64 top_mip_bytes; // 0: the size must match the host's exactly (buffers, invalid descriptions) + }; + D3D12_RESOURCE_DESC bad_buffer = buffer_desc(256); + bad_buffer.Height = 2; + D3D12_RESOURCE_DESC typed_buffer = buffer_desc(256); + typed_buffer.Format = DXGI_FORMAT_R8_UNORM; + D3D12_RESOURCE_DESC big_volume = volume_desc(1); + big_volume.Width = big_volume.Height = 32; + big_volume.DepthOrArraySize = 8; + const Case cases[] = { + {"buffer 300", buffer_desc(300), 0}, + {"buffer 64 KiB", buffer_desc(65536), 0}, + {"buffer 64 KiB + 1", buffer_desc(65537), 0}, + {"buffer aligned 64 KiB", with(buffer_desc(1000), k64), 0}, + {"buffer width 0", buffer_desc(0), 0}, + {"buffer height 2", bad_buffer, 0}, + {"buffer with a format", typed_buffer, 0}, + {"256x256 full chain", texture_desc(256, 256, rgba8, none, 0), 256 * 256 * 4}, + {"16x16 small", with(texture_desc(16, 16, rgba8, none), k4), 16 * 16 * 4}, + {"16x16 small render target", with(texture_desc(16, 16, rgba8, rt), k4), 16 * 16 * 4}, + {"1024x1024 small (too big)", with(texture_desc(1024, 1024, rgba8, none), k4), 1024 * 1024 * 4}, + {"64x64 BC1 small", with(texture_desc(64, 64, DXGI_FORMAT_BC1_UNORM, none, 3), k4), 16 * 16 * 8}, + {"64x64 depth", texture_desc(64, 64, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + 64 * 64 * 4}, + {"8x8 array of 6", texture_desc(8, 8, rgba8, none, 4, 6), 8 * 8 * 4 * 6}, + {"32x32x8 volume", big_volume, 32 * 32 * 8 * 4}, + {"64x64 4x MSAA", with(texture_desc(64, 64, rgba8, rt), 0, 4), 64 * 64 * 4 * 4}, + {"64x64 4x MSAA small", with(texture_desc(64, 64, rgba8, rt), k64, 4), 64 * 64 * 4 * 4}, + {"1024x1024 4x MSAA small", with(texture_desc(1024, 1024, rgba8, rt), k64, 4), 1024 * 1024 * 4 * 4}, + {"zero width", texture_desc(0, 16, rgba8, none), 0}, + {"alignment 12345", with(texture_desc(16, 16, rgba8, none), 12345), 0}, + {"4x MSAA with 2 mips", with(texture_desc(64, 64, rgba8, rt, 2), 0, 4), 0}, + }; + int mismatches = 0; + const auto mismatch = [&](const char* name, const D3D12_RESOURCE_ALLOCATION_INFO& a, + const D3D12_RESOURCE_ALLOCATION_INFO& b) { + if (mismatches++ < 24) + std::fprintf(stderr, "allocation info %s: ours size %llu alignment %llu, host size %llu alignment %llu\n", + name, (unsigned long long)a.SizeInBytes, (unsigned long long)a.Alignment, + (unsigned long long)b.SizeInBytes, (unsigned long long)b.Alignment); + }; + for (const Case& c : cases) { + const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 1, &c.desc); + const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 1, &c.desc); + if (b.SizeInBytes == UINT64_MAX || !c.top_mip_bytes) { + if (a.SizeInBytes != b.SizeInBytes || (b.SizeInBytes != UINT64_MAX && a.Alignment != b.Alignment)) + mismatch(c.name, a, b); + continue; + } + if (a.Alignment != b.Alignment || a.SizeInBytes == UINT64_MAX || a.SizeInBytes % a.Alignment || + a.SizeInBytes < c.top_mip_bytes) + mismatch(c.name, a, b); + std::printf("allocation info %s: alignment %llu, size ours %llu host %llu\n", c.name, + (unsigned long long)a.Alignment, (unsigned long long)a.SizeInBytes, + (unsigned long long)b.SizeInBytes); + } + + // Several resources at once: each at its own alignment after the one before, the largest alignment overall. + // Buffers only for the host comparison (their sizes are fixed); the texture checks our own layout. + const D3D12_RESOURCE_DESC buffers[] = {buffer_desc(300), buffer_desc(70000), buffer_desc(1)}; + const D3D12_RESOURCE_ALLOCATION_INFO a = ours->GetResourceAllocationInfo(0, 3, buffers); + const D3D12_RESOURCE_ALLOCATION_INFO b = host->GetResourceAllocationInfo(0, 3, buffers); + if (a.SizeInBytes != b.SizeInBytes || a.Alignment != b.Alignment) mismatch("three buffers", a, b); + + Ref ours8; + if (FAILED(ours->QueryInterface(IID_PPV_ARGS(&ours8.p)))) return mismatches + 1; + const D3D12_RESOURCE_DESC mixed[] = {with(texture_desc(16, 16, rgba8, none), k4), buffer_desc(300), + with(texture_desc(64, 64, rgba8, rt), 0, 4)}; + D3D12_RESOURCE_DESC1 mixed1[3]{}; + for (int i = 0; i < 3; ++i) std::memcpy(&mixed1[i], &mixed[i], sizeof(mixed[i])); + D3D12_RESOURCE_ALLOCATION_INFO1 each[3]{}, each2[3]{}; + const D3D12_RESOURCE_ALLOCATION_INFO total = ours8->GetResourceAllocationInfo1(0, 3, mixed, each); + const D3D12_RESOURCE_ALLOCATION_INFO total2 = ours8->GetResourceAllocationInfo2(0, 3, mixed1, each2); + const auto aligned = [](UINT64 v, UINT64 to) { return (v + to - 1) / to * to; }; + bool layout_ok = total.SizeInBytes == total2.SizeInBytes && total.Alignment == total2.Alignment && + each[0].Offset == 0 && each[0].Alignment == k4 && each[1].Alignment == k64 && + each[2].Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT && + total.Alignment == D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT && + total.SizeInBytes == each[2].Offset + each[2].SizeInBytes; + for (int i = 0; i < 3; ++i) { + const D3D12_RESOURCE_ALLOCATION_INFO single = ours->GetResourceAllocationInfo(0, 1, &mixed[i]); + layout_ok = layout_ok && each[i].SizeInBytes == single.SizeInBytes && + each[i].Alignment == single.Alignment && each[i].Offset == each2[i].Offset && + each[i].SizeInBytes == each2[i].SizeInBytes && each[i].Alignment == each2[i].Alignment && + (i == 0 || each[i].Offset == aligned(each[i - 1].Offset + each[i - 1].SizeInBytes, + each[i].Alignment)); + } + // An invalid description in the list makes the whole answer invalid. + const D3D12_RESOURCE_DESC with_bad[] = {buffer_desc(300), buffer_desc(0)}; + layout_ok = layout_ok && ours8->GetResourceAllocationInfo1(0, 2, with_bad, each).SizeInBytes == UINT64_MAX && + host->GetResourceAllocationInfo(0, 2, with_bad).SizeInBytes == UINT64_MAX; + if (!layout_ok) { + ++mismatches; + std::fprintf(stderr, "allocation info: Device4/Device8 per-resource layout wrong (total %llu/%llu)\n", + (unsigned long long)total.SizeInBytes, (unsigned long long)total.Alignment); + } + return mismatches; +} + } // namespace int main() { @@ -274,6 +398,10 @@ int main() { if (footprint_mismatches < 0) std::printf("GetCopyableFootprints: no host D3D12 device to compare with, skipped\n"); EXPECT(footprint_mismatches <= 0); + const int allocation_mismatches = compare_allocation_info(device.p); + if (allocation_mismatches < 0) + std::printf("GetResourceAllocationInfo: no host D3D12 device to compare with, skipped\n"); + EXPECT(allocation_mismatches <= 0); // Command objects; their GetDevice is the proxy, never the inner device. D3D12_COMMAND_QUEUE_DESC queue_desc{}; @@ -644,6 +772,86 @@ int main() { down + resolved_place.Offset + row * resolved_place.Footprint.RowPitch + col * 4, resolved_green, 4); + // Move a cropped two-colour region into a larger red texture. + constexpr UINT region_width = 10, region_height = 9; + constexpr auto region_format = DXGI_FORMAT_R8G8B8A8_UNORM; + const auto region_desc = + texture_desc(region_width, region_height, region_format, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + Ref region_target; + EXPECT(SUCCEEDED(create(default_heap, region_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, region_target))); + device->CreateRenderTargetView(region_target.p, nullptr, rtv0); + cursor = 0; + const auto region_place = place(device.p, region_target.p, 0, cursor); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + barrier = transition(msaa.p, D3D12_RESOURCE_STATE_RESOLVE_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &barrier); + const D3D12_RECT blue_patch{2, 3, 4, 5}; + list->ClearRenderTargetView(rtv1, blue, 1, &blue_patch); + list->ClearRenderTargetView(rtv0, red, 0, nullptr); + const D3D12_RESOURCE_BARRIER resolve_barriers[] = { + transition(msaa.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE), + transition(region_target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_DEST)}; + list->ResourceBarrier(2, resolve_barriers); + D3D12_RECT region{1, 2, 5, 5}; + const auto region_copy = subresource(region_target.p, 0), region_out = footprint(readback.p, region_place); + const auto resolve_and_readback = [&](UINT x, D3D12_RECT* rect, UINT64 fence_value) { + list7->ResolveSubresourceRegion(region_target.p, 0, x, 1, msaa.p, 0, rect, region_format, + D3D12_RESOLVE_MODE_AVERAGE); + const auto to_copy = transition(region_target.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + list->CopyTextureRegion(®ion_out, 0, 0, 0, ®ion_copy, nullptr); + if (list->Close() != S_OK) return false; + queue->ExecuteCommandLists(1, lists); + return rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success && + SUCCEEDED(queue->Signal(fence.p, fence_value)) && + SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr)); + }; + EXPECT(resolve_and_readback(4, ®ion, 5)); + const std::uint8_t resolved_red[4] = {255, 0, 0, 255}, resolved_blue[4] = {0, 0, 255, 255}; + for (UINT row = 0; row < region_height; ++row) + for (UINT col = 0; col < region_width; ++col) { + const bool in_region = row >= 1 && row < 4 && col >= 4 && col < 8; + const bool in_blue = row >= 2 && row < 4 && col >= 5 && col < 7; + report("partial resolve texel", row * region_width + col, + down + region_place.Offset + row * region_place.Footprint.RowPitch + col * 4, + in_blue ? resolved_blue : in_region ? resolved_green : resolved_red, 4); + } + + // A null rectangle resolves the entire source at the destination offset. + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); + const auto to_resolve = transition(region_target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RESOLVE_DEST); + list->ResourceBarrier(1, &to_resolve); + EXPECT(resolve_and_readback(1, nullptr, 6)); + for (UINT row = 0; row < region_height; ++row) + for (UINT col = 0; col < region_width; ++col) { + const bool in_source = row >= 1 && col >= 1 && col < 9; + const bool in_blue = row >= 4 && row < 6 && col >= 3 && col < 5; + report("whole source at offset", row * region_width + col, + down + region_place.Offset + row * region_place.Footprint.RowPitch + col * 4, + in_blue ? resolved_blue : in_source ? resolved_green : resolved_red, 4); + } + + D3D12_RECT out_of_source{0, 0, LONG(size + 1), 1}; + for (auto [x, rect] : {std::pair{0u, &out_of_source}, std::pair{7u, ®ion}}) { + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->ResourceBarrier(1, &to_resolve); + list7->ResolveSubresourceRegion(region_target.p, 0, x, 1, msaa.p, 0, rect, region_format, + D3D12_RESOLVE_MODE_AVERAGE); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::invalid_copy); + } + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list7->ResolveSubresourceRegion(region_target.p, 0, 4, 1, msaa.p, 0, ®ion, region_format, + D3D12_RESOLVE_MODE_MAX); + EXPECT(list->Close() == E_INVALIDARG); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list7->ResolveSubresourceRegion(region_target.p, 0, 4, 1, msaa.p, 0, ®ion, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOLVE_MODE_AVERAGE); + EXPECT(list->Close() == E_INVALIDARG); + // A resolve of a resource into itself is refused when it is recorded, one from a single-sampled // texture when it is executed; nothing is submitted. EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp new file mode 100644 index 000000000..3cb08937f --- /dev/null +++ b/runtime/test/fixtures/tiny_game.cpp @@ -0,0 +1,106 @@ +// A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the +// loader instead of the Windows one. Test code, not game content. Run as +// gta6rt --run tiny_game.exe -- hello 42 +// It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the +// xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then +// calls exit() with 0 when everything held. thread_local and a C++ exception need static TLS (#93) and unwind +// registration (#176) in the loader; LEONIDA_RUN_TLS=1 / LEONIDA_RUN_EH=1 turn those checks on. +#include + +#include +#include +#include +#include +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT __stdcall XGameRuntimeInitialize(); +extern "C" __declspec(dllimport) void __stdcall XGameRuntimeUninitialize(); +extern "C" __declspec(dllimport) uint32_t __stdcall XSystemGetDeviceType(); + +namespace { + +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("tiny_game: %s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +struct StaticInit { + int value; + StaticInit() : value(1234) {} +}; +StaticInit g_static; + +bool env_on(const char* name) { + char buf[8] = {}; + return GetEnvironmentVariableA(name, buf, sizeof buf) > 0 && buf[0] == '1'; +} + +thread_local int t_counter = 5; + +} // namespace + +int main(int argc, char** argv) { + std::printf("tiny_game: started, argc=%d\n", argc); + check(argc == 3 && std::strcmp(argv[1], "hello") == 0 && std::strcmp(argv[2], "42") == 0, + "argv is the game's command line (\"hello\" \"42\"), not gta6rt's"); + check(std::strstr(GetCommandLineA(), "hello 42") != nullptr, "GetCommandLineA is the game's command line"); + check(g_static.value == 1234, "a static initializer ran before main"); + + std::vector v(1 << 20); + for (size_t i = 0; i < v.size(); ++i) v[i] = int(i); + check(v[123456] == 123456, "a 4 MiB heap allocation works"); + + char tmp[MAX_PATH] = {}; + GetTempPathA(MAX_PATH, tmp); + std::string path = std::string(tmp) + "leonida_tiny_game_" + std::to_string(GetCurrentProcessId()) + ".txt"; + bool file_ok = false; + if (FILE* f = std::fopen(path.c_str(), "wb")) { + std::fputs("leonida", f); + std::fclose(f); + char back[16] = {}; + if (FILE* r = std::fopen(path.c_str(), "rb")) { + std::fread(back, 1, 7, r); + std::fclose(r); + file_ok = std::strcmp(back, "leonida") == 0; + } + std::remove(path.c_str()); + } + check(file_ok, "a file round trip through the CRT works"); + + long long sum = 0; + std::thread worker([&] { for (int i = 1; i <= 1000; ++i) sum += i; }); + worker.join(); + check(sum == 500500, "a second thread ran and joined"); + + check(XGameRuntimeInitialize() == S_OK, "XGameRuntimeInitialize is answered by the gta6rt shim (S_OK)"); + check(XSystemGetDeviceType() == 7, "XSystemGetDeviceType is answered by the gta6rt shim (Series X)"); + XGameRuntimeUninitialize(); + + if (env_on("LEONIDA_RUN_TLS")) { + int seen = -1; + std::thread t([&] { seen = t_counter; t_counter = 9; }); + t.join(); + check(t_counter == 5 && seen == 5, "thread_local starts at its initializer on each thread"); + } else { + std::printf("tiny_game: SKIP thread_local (needs static TLS, #93; LEONIDA_RUN_TLS=1)\n"); + } + if (env_on("LEONIDA_RUN_EH")) { + bool caught = false; + try { + throw std::string("boom"); + } catch (const std::string& e) { + caught = e == "boom"; + } + check(caught, "a C++ exception is thrown and caught inside the image"); + } else { + std::printf("tiny_game: SKIP C++ exception (needs unwind registration, #176; LEONIDA_RUN_EH=1)\n"); + } + + std::printf("tiny_game: %s\n", g_failures ? "FAILED" : "OK"); + std::fflush(stdout); + std::exit(g_failures ? 1 : 0); // through the shimmed exit(): ends the run, not gta6rt +} diff --git a/runtime/test/fixtures/xgameruntime_stub.cpp b/runtime/test/fixtures/xgameruntime_stub.cpp new file mode 100644 index 000000000..749eda8fc --- /dev/null +++ b/runtime/test/fixtures/xgameruntime_stub.cpp @@ -0,0 +1,10 @@ +// Link-time stand-in for the GDK's xgameruntime.dll, so tiny_game.exe gets real imports of these names. Under +// `gta6rt --run` the shim registry answers them first and this DLL never loads; run directly, these failing answers +// are what tiny_game would see. Test code, not game content. +#include + +#include + +extern "C" __declspec(dllexport) HRESULT __stdcall XGameRuntimeInitialize() { return E_FAIL; } +extern "C" __declspec(dllexport) void __stdcall XGameRuntimeUninitialize() {} +extern "C" __declspec(dllexport) uint32_t __stdcall XSystemGetDeviceType() { return 0; } diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp index d60dfae3a..e2f05b1a3 100644 --- a/runtime/test/root_signature_oracle_test.cpp +++ b/runtime/test/root_signature_oracle_test.cpp @@ -5,6 +5,7 @@ // and requires rt::rootsig::parse_rts0 to recover the same model. If the // hypothesis layout in root_signature.cpp ever disagrees with the real // serializer, this fails loudly here instead of corrupting draws silently. +// Versions 1.0, 1.1 and 1.2 are each checked with static samplers. // NOT portable: runs on Windows CI only, like root_sig_test.cpp. #include #include @@ -55,6 +56,10 @@ bool parse_blob(ID3DBlob* blob, rt::rootsig::RootSignature& model) { std::printf("%02x", bytes[i]); } std::printf("\n"); + if (GetEnvironmentVariableA("LEONIDA_ORACLE_DUMP", nullptr, 0)) { // the whole blob as u32 words, for layouts + for (size_t i = 0; i + 4 <= size; i += 4) + std::printf(" +%3zu: %08x\n", i, unsigned(bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24)); + } std::fflush(stdout); const rt::rootsig::DecodeResult d = rt::rootsig::parse_rts0(bytes, size); if (!d.ok) { @@ -115,6 +120,136 @@ int main() { const PackResult packed = pack(model); check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords"); + // Static samplers, one signature per version: every field round-trips through the real serializer, and 1.2 + // adds D3D12_STATIC_SAMPLER_DESC1::Flags (a 14th dword) to each sampler record. Each also carries a table and a + // root descriptor, so the 1.1/1.2 descriptor and range flags sit between the samplers and the header. + D3D12_STATIC_SAMPLER_DESC1 samplers[2]{}; + samplers[0].Filter = D3D12_FILTER_ANISOTROPIC; + samplers[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; + samplers[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_MIRROR; + samplers[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER; + samplers[0].MipLODBias = -1.5f; + samplers[0].MaxAnisotropy = 8; + samplers[0].ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; + samplers[0].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE; + samplers[0].MinLOD = 1.0f; + samplers[0].MaxLOD = 9.0f; + samplers[0].ShaderRegister = 4; + samplers[0].RegisterSpace = 2; + samplers[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + samplers[1].Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + samplers[1].AddressU = samplers[1].AddressV = samplers[1].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + samplers[1].MaxLOD = D3D12_FLOAT32_MAX; + samplers[1].ShaderRegister = 7; + samplers[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + samplers[1].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; + D3D12_STATIC_SAMPLER_DESC samplers0[2]{}; + for (int i = 0; i < 2; ++i) { + const D3D12_STATIC_SAMPLER_DESC1& s = samplers[i]; + samplers0[i] = {s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, + s.ComparisonFunc, s.BorderColor, s.MinLOD, s.MaxLOD, s.ShaderRegister, s.RegisterSpace, + s.ShaderVisibility}; + } + // Two ranges, so the range stride (20 bytes in 1.0, 24 with flags) is under test too. + D3D12_DESCRIPTOR_RANGE range0[2] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 1, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}}; + D3D12_DESCRIPTOR_RANGE1 range1[2] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 3, 1, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC, + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}}; + D3D12_ROOT_PARAMETER params0[2]{}; + params0[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params0[0].DescriptorTable = {2, range0}; + params0[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params0[1].Descriptor = {5, 1}; + D3D12_ROOT_PARAMETER1 params1[2]{}; + params1[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params1[0].DescriptorTable = {2, range1}; + params1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params1[1].Descriptor = {5, 1, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE}; + + const auto same_sampler = [](const StaticSampler& got, const D3D12_STATIC_SAMPLER_DESC1& want, bool flags) { + return got.filter == uint32_t(want.Filter) && got.address_u == uint32_t(want.AddressU) && + got.address_v == uint32_t(want.AddressV) && got.address_w == uint32_t(want.AddressW) && + got.mip_lod_bias == want.MipLODBias && got.max_anisotropy == want.MaxAnisotropy && + got.comparison_func == uint32_t(want.ComparisonFunc) && + got.border_color == uint32_t(want.BorderColor) && got.min_lod == want.MinLOD && + got.max_lod == want.MaxLOD && got.shader_register == want.ShaderRegister && + got.register_space == want.RegisterSpace && + got.visibility == static_cast(want.ShaderVisibility) && + got.flags == (flags ? uint32_t(want.Flags) : 0u); + }; + const auto serialize = [&](const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& d, Version version, const char* name, + bool sampler_flags) { + Blobs out; + char what[160]; + const HRESULT result = D3D12SerializeVersionedRootSignature(&d, &out.blob, &out.error); + std::snprintf(what, sizeof(what), "%s: Microsoft serializer accepts it", name); + check(result == S_OK, what); + if (result != S_OK) { + if (out.error) std::printf("serializer error: %s\n", static_cast(out.error->GetBufferPointer())); + return; + } + RootSignature got; + std::snprintf(what, sizeof(what), "%s: parses", name); + const bool parsed = parse_blob(out.blob, got); + check(parsed, what); + if (!parsed) return; + std::snprintf(what, sizeof(what), "%s: version, a two-range table, a root SRV and two samplers", name); + check(got.version == version && got.params.size() == 2 && got.params[0].type == ParamType::Table && + got.params[0].ranges.size() == 2 && got.params[0].ranges[0].range_type == 0 && + got.params[0].ranges[0].num_descriptors == 3 && got.params[0].ranges[1].range_type == 1 && + got.params[0].ranges[1].num_descriptors == 2 && + got.params[1].type == ParamType::Descriptor && got.params[1].descriptor_register == 5 && + got.params[1].descriptor_space == 1 && got.static_samplers.size() == 2, + what); + if (got.static_samplers.size() != 2) return; + std::snprintf(what, sizeof(what), "%s: every sampler field round-trips", name); + check(same_sampler(got.static_samplers[0], samplers[0], sampler_flags) && + same_sampler(got.static_samplers[1], samplers[1], sampler_flags), + what); + // The canonical cache codec keeps all of it, flags included. + const std::vector bytes = encode_canonical(got); + const DecodeResult again = decode_canonical(bytes.data(), bytes.size()); + std::snprintf(what, sizeof(what), "%s: canonical codec round-trips the parsed model", name); + check(again.ok && again.sig.version == version && again.sig.static_samplers.size() == 2 && + same_sampler(again.sig.static_samplers[0], samplers[0], sampler_flags) && + same_sampler(again.sig.static_samplers[1], samplers[1], sampler_flags), + what); + }; + + D3D12_VERSIONED_ROOT_SIGNATURE_DESC v10{}; + v10.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + v10.Desc_1_0 = {2, params0, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + serialize(v10, Version::V1_0, "1.0 with static samplers", false); + + D3D12_VERSIONED_ROOT_SIGNATURE_DESC v11{}; + v11.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + v11.Desc_1_1 = {2, params1, 2, samplers0, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + serialize(v11, Version::V1_1, "1.1 with static samplers", false); + + // 1.2: a UINT border colour on one sampler, no flags on the other. + samplers[0].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT; + samplers[0].Flags = D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC v12{}; + v12.Version = D3D_ROOT_SIGNATURE_VERSION_1_2; + v12.Desc_1_2 = {2, params1, 2, samplers, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + serialize(v12, Version::V1_2, "1.2 with sampler flags", true); + + // 1.2: non-normalized coordinates, which D3D12 allows only with point/linear filtering, no mips, no anisotropy, + // no comparison and clamp or border addressing. + samplers[0] = {}; + samplers[0].Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; + samplers[0].AddressU = samplers[0].AddressV = samplers[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + samplers[0].ShaderRegister = 4; + samplers[0].RegisterSpace = 2; + samplers[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + samplers[0].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; + samplers[0].Flags = D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; + serialize(v12, Version::V1_2, "1.2 with non-normalized coordinates", true); + if (g_failures != 0) std::printf("%d FAILURES\n", g_failures); return g_failures == 0 ? 0 : 1; } diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp index 92ef8347f..7a27aa43c 100644 --- a/runtime/test/root_signature_test.cpp +++ b/runtime/test/root_signature_test.cpp @@ -216,6 +216,99 @@ int main() { "walked RTS0 model matches payload"); } + // RTS0 descriptor tables: the payload is {num_ranges, ranges_offset} and the ranges sit at that offset, as the + // PC serializer writes them (root_signature_oracle_test); here a 1.1 table with two 24-byte ranges placed after + // a gap, so reading them inline after the count would fail. + { + std::vector p; + put_u32(p, 2); // version 1.1 + put_u32(p, 1); // 1 param + put_u32(p, 24); // params table offset + put_u32(p, 0); // 0 samplers + put_u32(p, 0); + put_u32(p, 0); // flags + put_u32(p, 0); // entry 0: descriptor table + put_u32(p, 5); // pixel + put_u32(p, 36); // table payload + put_u32(p, 2); // 2 ranges + put_u32(p, 52); // at 52 + put_u32(p, 0xdeadbeefu); // gap + put_u32(p, 0xdeadbeefu); + for (const uint32_t v : {0u, 4u, 0u, 0u, 0xffffffffu, 0u, // SRV x4 + 2u, 1u, 3u, 1u, 0xffffffffu, 0u}) // CBV x1 + put_u32(p, v); + const DecodeResult d = parse_rts0(p.data(), p.size()); + check(d.ok && d.sig.params.size() == 1 && d.sig.params[0].type == ParamType::Table && + d.sig.params[0].visibility == Visibility::Pixel && d.sig.params[0].ranges.size() == 2 && + d.sig.params[0].ranges[0].range_type == 0 && d.sig.params[0].ranges[0].num_descriptors == 4 && + d.sig.params[0].ranges[1].range_type == 2 && d.sig.params[0].ranges[1].num_descriptors == 1, + "RTS0 table ranges read from their offset"); + std::vector wild = p; + wild[40] = 0xF0; // ranges offset far past the payload + check(!parse_rts0(wild.data(), wild.size()).ok, "RTS0 ranges offset past the payload rejected"); + } + + // Version 1.2: the canonical codec carries the static-sampler flags, and only for 1.2, so 1.0/1.1 encodings are + // byte-for-byte what they were before 1.2 existed. + { + RootSignature sig; + sig.version = Version::V1_2; + sig.params = {consts(1)}; + StaticSampler s; + s.border_color = 5; // D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT + s.flags = 1; // D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR + StaticSampler plain; + plain.shader_register = 1; + sig.static_samplers = {s, plain}; + const std::vector v12 = encode_canonical(sig); + const DecodeResult d = decode_canonical(v12.data(), v12.size()); + check(d.ok && d.sig.version == Version::V1_2 && d.sig.static_samplers.size() == 2 && + d.sig.static_samplers[0].flags == 1 && d.sig.static_samplers[0].border_color == 5 && + d.sig.static_samplers[1].flags == 0 && d.sig.static_samplers[1].shader_register == 1, + "canonical 1.2 round-trips sampler flags"); + check(!decode_canonical(v12.data(), v12.size() - 4).ok, "canonical 1.2 without the last flags is truncated"); + sig.version = Version::V1_1; + const std::vector v11 = encode_canonical(sig); + check(v11.size() + 2 * 4 == v12.size(), "canonical 1.1 has no sampler flags dword"); + const DecodeResult d11 = decode_canonical(v11.data(), v11.size()); + check(d11.ok && d11.sig.static_samplers[0].flags == 0, "canonical 1.1 decodes with flags 0"); + } + + // RTS0 version 3 (1.2): 1.1-style descriptor flags, then a 14-dword sampler whose last dword is its flags. + { + std::vector p; + put_u32(p, 3); // version 1.2 + put_u32(p, 1); // 1 param + put_u32(p, 24); // params table offset + put_u32(p, 1); // 1 sampler + put_u32(p, 48); // samplers offset + put_u32(p, 0); // flags + put_u32(p, 2); // entry 0: CBV + put_u32(p, 0); + put_u32(p, 36); + put_u32(p, 9); // register + put_u32(p, 0); // space + put_u32(p, 4); // descriptor flags (DATA_STATIC_WHILE_SET_AT_EXECUTE) + const uint32_t sampler[14] = {0x15, 1, 2, 3, 0, 16, 4, 5, 0, 0x7f7fffffu, 3, 1, 5, 2}; + for (const uint32_t v : sampler) put_u32(p, v); + const DecodeResult d = parse_rts0(p.data(), p.size()); + check(d.ok, "hand-built RTS0 1.2 parses"); + check(d.ok && d.sig.version == Version::V1_2 && d.sig.params.size() == 1 && + d.sig.params[0].descriptor_register == 9 && d.sig.static_samplers.size() == 1 && + d.sig.static_samplers[0].filter == 0x15 && d.sig.static_samplers[0].max_anisotropy == 16 && + d.sig.static_samplers[0].border_color == 5 && d.sig.static_samplers[0].shader_register == 3 && + d.sig.static_samplers[0].register_space == 1 && + d.sig.static_samplers[0].visibility == Visibility::Pixel && + d.sig.static_samplers[0].flags == 2, + "RTS0 1.2 sampler fields and flags"); + std::vector cut = p; + cut.resize(cut.size() - 4); // a 13-dword (1.0/1.1-sized) sampler in a 1.2 blob + check(!parse_rts0(cut.data(), cut.size()).ok, "RTS0 1.2 sampler without flags rejected"); + std::vector v4 = p; + v4[0] = 4; + check(!parse_rts0(v4.data(), v4.size()).ok, "RTS0 version 4 rejected"); + } + if (g_failures != 0) std::printf("%d FAILURES\n", g_failures); return g_failures == 0 ? 0 : 1; } diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 32fb7fab5..1ed268017 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -39,6 +39,7 @@ CS_DUMPS = [("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), ("cs_wave6 ("cs_w64_mask_detect", [48])] # num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE])] +CMPX_CLASS_WORDS = [0xEEEEEEEE] * 3 + [0x22] + [0x11] * 4 # Cross-half wave64 tests (x = cross-half): exact results need 64 lanes, or an emulation of them on narrower subgroups. W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1" W64X_DUMPS = [("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), @@ -65,7 +66,8 @@ PIXEL_BITS = {"ps_legacy_mul": (0, 0, 0, 0x40c00000), "ps_ops7": (0x00ff8077, 0xff0000ff, 0x89abcdef, 0x00070003), "ps_ops8": (0x80000000, 0xffffffff, 0x000f100e, 0x0f0f0f1f), "ps_scc": (1, 1, 3, 0x80000000), "ps_sdwa": (0x000000f1, 0xfffefff2, 0x3c003344, 0xfff70000), - "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0)} + "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), + "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203)} # Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as # tests/semantic/test_value_semantics.py does for the interpreter. PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x11223344,0x1004=0x55667788"}} @@ -385,6 +387,8 @@ def main(): expected_words=want))) for name, want in BOUNDS: results.append((name, compute_test(tools, spirv, name, "1", "dump", expected_words=want))) + results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump", + expected_words=CMPX_CLASS_WORDS))) for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED, expected_words=want))) diff --git a/runtime/test/shaders/cs_cmpx_class_f32.asm b/runtime/test/shaders/cs_cmpx_class_f32.asm new file mode 100644 index 000000000..75dcdd4be --- /dev/null +++ b/runtime/test/shaders/cs_cmpx_class_f32.asm @@ -0,0 +1,28 @@ +; group: 8,1,1 +; mattr: +wavefrontsize32,-wavefrontsize64 +; CMPX class keeps qNaN and +0 across both compares. E32 (mask 0x242) drops -0, E64 (mask 0x62) +; drops +infinity. Neither compare can reactivate lane 0, which was disabled even though it holds qNaN. +; VCC selects the distinctive value in lane 3 and must survive both EXEC-only compares. +; Run: vk_compute_test cs_cmpx_class_f32.spv 1 dump +; out[0..7] = EEEEEEEE EEEEEEEE EEEEEEEE 00000022 00000011 00000011 00000011 00000011 (hex) +v_mov_b32_e32 v1, 0x7fc00000 +v_mov_b32_e32 v2, 0x7f800000 +v_cmp_eq_u32_e32 vcc_lo, 1, v0 +v_cndmask_b32_e32 v1, v1, v2, vcc_lo +v_mov_b32_e32 v2, 0x80000000 +v_cmp_eq_u32_e32 vcc_lo, 2, v0 +v_cndmask_b32_e32 v1, v1, v2, vcc_lo +v_mov_b32_e32 v2, 0 +v_cmp_eq_u32_e32 vcc_lo, 3, v0 +v_cndmask_b32_e32 v1, v1, v2, vcc_lo +v_mov_b32_e32 v2, 0x242 +v_mov_b32_e32 v7, 0x62 +v_mov_b32_e32 v3, 0x11 +v_mov_b32_e32 v4, 0x22 +v_lshlrev_b32_e32 v5, 2, v0 +v_cmpx_ne_u32_e32 0, v0 +v_cmpx_class_f32_e32 v1, v2 +v_cmpx_class_f32_e64 v1, v7 +v_cndmask_b32_e32 v6, v3, v4, vcc_lo +buffer_store_dword v6, v5, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_cvt_f32_sat.asm b/runtime/test/shaders/cs_cvt_f32_sat.asm new file mode 100644 index 000000000..52227367f --- /dev/null +++ b/runtime/test/shaders/cs_cvt_f32_sat.asm @@ -0,0 +1,13 @@ +; s[0:3] is the output V#, s4 is one binary32 input as a raw word. +; RDNA 2 ISA, VOP1 opcodes 7 and 8: truncate toward zero, saturate to +; the destination range, and return zero for NaN. +; At offset 0: unsigned result. At offset 4: signed result, as raw bits. +; Example s4 = 0x4f000000 (+2^31): out = 0x80000000, 0x7fffffff. +; group: 1,1,1 +; rsrc2: 0x808a +v_mov_b32_e32 v0, s4 +v_mov_b32_e32 v1, 0 +v_cvt_u32_f32_e32 v2, v0 +v_cvt_i32_f32_e32 v3, v0 +buffer_store_dwordx2 v[2:3], v1, s[0:3], 0 offen +s_endpgm diff --git a/runtime/test/shaders/ps_scc_minmax.asm b/runtime/test/shaders/ps_scc_minmax.asm new file mode 100644 index 000000000..c14c1f5db --- /dev/null +++ b/runtime/test/shaders/ps_scc_minmax.asm @@ -0,0 +1,47 @@ +; SCC from s_min_i32/s_max_i32 (signed) and s_min_u32/s_max_u32: 1 only when S0 is strictly smaller (min) or larger +; (max), since D = S0 < S1 ? S0 : S1 picks S1 on a tie. Per word: byte 0 = the op's result on equal operands, +; byte 1 = s_cselect 1/2 after that tie (2: SCC 0), byte 2 = s_cselect 3/4 after a pair that -1 vs 1 decides by +; signedness (3: SCC 1). A tie that set SCC gives byte 1 = 1, a compare of the wrong signedness byte 2 = 4. +; Expected mrt0 bits: 0x00030205, 0x00030207, 0x00030209, 0x00030203 +s_mov_b32 s0, 5 +s_min_i32 s1, s0, 5 +s_cselect_b32 s2, 1, 2 +s_min_i32 s3, -1, 1 +s_cselect_b32 s4, 3, 4 +s_lshl_b32 s2, s2, 8 +s_lshl_b32 s4, s4, 16 +s_or_b32 s1, s1, s2 +s_or_b32 s1, s1, s4 +s_mov_b32 s0, 7 +s_max_i32 s5, s0, 7 +s_cselect_b32 s6, 1, 2 +s_max_i32 s7, 1, -1 +s_cselect_b32 s8, 3, 4 +s_lshl_b32 s6, s6, 8 +s_lshl_b32 s8, s8, 16 +s_or_b32 s5, s5, s6 +s_or_b32 s5, s5, s8 +s_mov_b32 s0, 9 +s_min_u32 s9, s0, 9 +s_cselect_b32 s10, 1, 2 +s_min_u32 s11, 1, -1 +s_cselect_b32 s12, 3, 4 +s_lshl_b32 s10, s10, 8 +s_lshl_b32 s12, s12, 16 +s_or_b32 s9, s9, s10 +s_or_b32 s9, s9, s12 +s_mov_b32 s0, 3 +s_max_u32 s13, s0, 3 +s_cselect_b32 s14, 1, 2 +s_max_u32 s15, -1, 1 +s_cselect_b32 s16, 3, 4 +s_lshl_b32 s14, s14, 8 +s_lshl_b32 s16, s16, 16 +s_or_b32 s13, s13, s14 +s_or_b32 s13, s13, s16 +v_mov_b32_e32 v0, s1 +v_mov_b32_e32 v1, s5 +v_mov_b32_e32 v2, s9 +v_mov_b32_e32 v3, s13 +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp index 29a87f50e..e0813c840 100644 --- a/runtime/test/vk_command_replay_test.cpp +++ b/runtime/test/vk_command_replay_test.cpp @@ -2,7 +2,8 @@ // Part A uses only Vulkan 1.0 functions and no layout tracker. Part B uses the tracker with separate depth/stencil // layouts: rectangle clears, a depth clear while the stencil plane is in another state, a texture used after // implicit promotion from common, and enhanced barriers. Part C copies a volume (footprint, box and whole) and -// resolves a multisampled target. +// resolves a multisampled target. Part D records every D3D12 sync/access pair as enhanced barriers, which the +// validation layer must accept. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. #include "vk_test_device.h" #include "../src/vulkan_replay.h" @@ -460,12 +461,83 @@ int part_c(vktest::Device& d) { return 0; } +// Part D: every D3D12 sync bit against every access bit, as global, buffer and texture barriers. Whatever pair the +// application names, the Vulkan barrier must be valid, so every access has a stage in its scope that can perform it +// (vulkan_barrier_scope). Under LEONIDA_VK_VALIDATION=1 a pair that breaks that rule is a validation error. The +// image is simultaneous-access, so it stays in GENERAL, which every access may use: only the stage/access rule is +// under test. +int part_d(vktest::Device& d) { + namespace y = d3d12_sync; + namespace a = d3d12_access; + namespace l = d3d12_layout; + const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + EXPECT(image); + constexpr ResourceId image_id = 30, buffer_id = 31; + ResourceBinding image_binding{}; + image_binding.image = image; + image_binding.format = VK_FORMAT_R8G8B8A8_UNORM; + image_binding.width = image_binding.height = 4; + image_binding.simultaneous_access = true; + const ResourceBinding buffer_binding{}; // a buffer: no image + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { + if (id == image_id) return &image_binding; + return id == buffer_id ? &buffer_binding : nullptr; + }; + ReplayFunctions vk{}; + vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); + vk.clear_color_image = d.fn("vkCmdClearColorImage"); + vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); + vk.pipeline_barrier2 = d.fn("vkCmdPipelineBarrier2"); + vk.separate_depth_stencil_layouts = true; + LayoutTracker tracker(true); + tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_GENERAL); + + // Ray-tracing, video and split syncs map to ALL_COMMANDS, which every access accepts; they are kept anyway. + const std::uint32_t syncs[] = {y::all, y::draw, y::index_input, y::vertex_shading, y::pixel_shading, + y::depth_stencil, y::render_target, y::compute_shading, y::raytracing, y::copy, + y::resolve, y::execute_indirect, y::all_shading, y::non_pixel_shading, + y::emit_raytracing_acceleration_structure_postbuild_info, + y::clear_unordered_access_view, y::video_decode, + y::build_raytracing_acceleration_structure}; + const std::uint32_t accesses[] = {a::common, a::vertex_buffer, a::constant_buffer, a::index_buffer, + a::render_target, a::unordered_access, a::depth_stencil_write, + a::depth_stencil_read, a::shader_resource, a::stream_output, + a::indirect_argument, a::copy_dest, a::copy_source, a::resolve_dest, + a::resolve_source, a::raytracing_acceleration_structure_read, + a::raytracing_acceleration_structure_write, a::shading_rate_source, + a::video_decode_read, a::no_access}; + const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0}; + CommandList list; + unsigned pairs = 0; + for (const std::uint32_t sync : syncs) { + for (const std::uint32_t access : accesses) { + EXPECT(list.barrier(GlobalBarrier{sync, sync, access, access})); + EXPECT(list.barrier(BufferBarrier{sync, sync, access, access, buffer_id})); + EXPECT(list.barrier(TextureBarrier{sync, sync, access, access, l::common, l::common, image_id, all, 0})); + ++pairs; + } + } + EXPECT(list.close()); + const unsigned errors_before = d.validation_errors(); + const bool ok = d.run([&](VkCommandBuffer cb) { + d.initial_layout(cb, image, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_GENERAL); + return replay(list, cb, resolve, vk, &tracker) == ReplayResult::success; + }); + EXPECT(ok); + const unsigned errors = d.validation_errors() - errors_before; + std::printf("D: %u sync/access pairs as global, buffer and texture barriers%s\n", pairs, + d.validation ? (errors ? ": validation errors" : ", no validation errors") : " (validation off)"); + return 0; +} + } // namespace int main() { vktest::Device device; EXPECT(device.create()); - if (part_a(device) || part_b(device) || part_c(device)) return 1; + if (part_a(device) || part_b(device) || part_c(device) || part_d(device)) return 1; if (g_mismatches) return 1; if (device.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", device.validation_errors()); diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 71a0b7ab4..aff8b85f5 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -230,7 +230,12 @@ struct JsonParser { if (error) return m; if (!consume(':')) { fail("expected ':' in shader metadata"); return m; } if (k == "stage") m.stage = parse_string(); - else if (k == "subgroup_size") m.subgroup_size = parse_u32(); + else if (k == "subgroup_size") { + // null: translated with --wave64-emulate, exact on any subgroup size, so request none (0) + ws(); + if (s.compare(i, 4, "null") == 0) { i += 4; m.subgroup_size = 0; } + else m.subgroup_size = parse_u32(); + } else if (k == "writes_depth") m.writes_depth = parse_bool(); else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); else if (k == "features") m.features = parse_str_array(); diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index ada705503..b39c902c3 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -23,7 +23,8 @@ sys.path.insert(0, os.path.join(ROOT, "tools")) import mc_command # noqa: E402 sys.path.insert(0, SHADER_DIR) from compute_fixture import compute_header -from check import TEXTURE_MIP_DEPENDENCIES, TEXTURE_MIP_TEST, Skip, mesh_v5_test, start_failure, texture_mip_test +from check import (CMPX_CLASS_WORDS, TEXTURE_MIP_DEPENDENCIES, TEXTURE_MIP_TEST, Skip, + mesh_v5_test, start_failure, texture_mip_test) def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: @@ -396,9 +397,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, return ok, detail -# Shaders a selected test draws with, built even when the filter leaves them out (#192): ps_flat and -# ps_texture_sample (vk_texture_test) are drawn with vs_ids. -DRAWN_WITH = {"ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm"} +# Shaders a selected test draws with, built even when the filter leaves them out (#192). +DRAWN_WITH = {"ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm"} def with_draw_shaders(asm_files: list[str]) -> list[str]: @@ -414,11 +414,35 @@ def with_draw_shaders(asm_files: list[str]) -> list[str]: return build +# Multi-config CMake generators (Visual Studio, Xcode, Ninja Multi-Config) put each program in build/. +CONFIG_DIRS = ("RelWithDebInfo", "Release", "Debug", "MinSizeRel") + + +def resolve_build_dir(build: str, programs: tuple[str, ...]) -> str: + """The folder that holds all of `programs` (file names with their extension). + + Makefile and Ninja builds leave them in `build`. With the Visual Studio generator they land in + build/RelWithDebInfo, build/Release and so on. `build` itself wins when it has them all; otherwise the + configuration folder that has them all and was built last. If none has them, `build` is returned, so the + caller's "not found" message names the folder the user gave.""" + def complete(d: str) -> bool: + return all(os.path.isfile(os.path.join(d, n)) for n in programs) + + if complete(build): + return build + found = [d for d in (os.path.join(build, c) for c in CONFIG_DIRS) if complete(d)] + if not found: + return build + return max(found, key=lambda d: max(os.path.getmtime(os.path.join(d, n)) for n in programs)) + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") - ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) + ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), + help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " + "subfolder that has the test programs is found by itself") ap.add_argument("--work", default=None) ap.add_argument("--filter", default="") a = ap.parse_args() @@ -429,8 +453,9 @@ def main() -> int: a.work = os.path.abspath(a.work) ext = ".exe" if os.name == "nt" else "" - missing = [t + ext for t in ("vk_compute_test", "vk_store_test", "vk_harness") - if not os.path.isfile(os.path.join(a.build, t + ext))] + required = tuple(t + ext for t in ("vk_compute_test", "vk_store_test", "vk_harness")) + a.build = resolve_build_dir(a.build, required) + missing = [t for t in required if not os.path.isfile(os.path.join(a.build, t))] if missing: sys.exit(f"Test programs not found in {a.build}:{', '.join(missing)}\n" "Build them with cmake -S runtime -B runtime/build, then cmake --build runtime/build.\n" @@ -539,11 +564,10 @@ def run_suite(a, work: str) -> int: elif name == "cs_bvh": rc, msg = run_cmd([vk_compute, spv, "1", "bvh"], env=cs_env) results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) - elif name == "cs_bounds": - # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds - # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. + elif name in ("cs_bounds", "cs_cmpx_class_f32"): + # These per-lane results do not require a particular subgroup width. rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) - want = [0x12345678, 0x12345678, 0, 0xEEEEEEEE] + want = CMPX_CLASS_WORDS if name == "cs_cmpx_class_f32" else [0x12345678, 0x12345678, 0, 0xEEEEEEEE] words = dump_words(msg) vals = words[:len(want)] if words else [] results.append((name, rc == 0 and vals == want, @@ -657,6 +681,7 @@ def run_suite(a, work: str) -> int: if rc == 77: # vk_harness: the device lacks a feature this shader needs (e.g. barycentrics) m = re.search(r"unsupported: .*", msg) results.append((name, None, f"SKIP ({m.group(0) if m else 'unsupported device'})")) + results.append((name, None, unsupported_skip(msg))) continue if rc != 0: results.append((name, False, msg)) @@ -674,6 +699,7 @@ def run_suite(a, work: str) -> int: "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), "ps_ops8": (0x80000000, 0xFFFFFFFF, 0x000F100E, 0x0F0F0F1F), "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), + "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), } if name in const_wants: ok, detail = check_pixel_const(raw, const_wants[name]) diff --git a/tests/semantic/README.md b/tests/semantic/README.md index bf8b9a81e..017e049d9 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md @@ -18,10 +18,24 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): are also asserted there, duplicating the matching `test_ps_semantics.py` cases. As above, constants are written by hand and recomputed by plain-Python references checked against each other. `cs_fmt_1010102` runs as compute too and asserts 16 dwords: 10:10:10:2 words read through formats 50 and 44 (from the V# and from - tbuffer's own format) and stored in both. + tbuffer's own format) and stored in both. `ps_scc_minmax` asserts SCC after `s_min`/`s_max` `_i32`/`_u32`: + 0 on a tie, and 1 on a pair (-1 against 1) that only the right signedness orders that way. - `test_interp.py` tests the interpreter against the SPIR-V / GLSL.std.450 definitions. The interpreter raises `UnsupportedConstruct` for anything it does not model instead of approximating it. It can seed Input variables, PushConstant words and a flat physical-address memory map for the tests above. +- `test_wave64_cross_half.py` translates the GPU tests `cs_w64x_readlane`, `cs_w64x_writelane` and + `cs_w64x_bpermute` (no `--wave64-emulate`) and runs all 64 lanes in lockstep with + `spirv_mini_interp.run_workgroup`. On one 64-wide subgroup the 24 words must equal the GPU check's values + (`runtime/test/shaders/check.py`). On two 32-wide subgroups (NVIDIA without emulation) `ds_bpermute` stays + exact, `v_writelane` writes stay exact, and a `v_readlane` from the other half is a shuffle from lane >= 32, + undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU + shows (all 24 matched on an RTX 4070 SUPER, driver 610.88, without `--wave64-emulate`). Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the + 64-wide result. +- `test_wave64_subgroup_ops.py` runs eight more wave64 GPU tests the same way (`cs_w64x_ballot`, + `_readfirstlane`, `_load_ballot_load`, `_partial`, `cs_wave64_ballot`, `cs_wm_bfm64`, `cs_wm_half_cmp`, + `cs_wavemask`): on one 64-wide subgroup every word equals the GPU check; on two 32-wide subgroups the + words pinned there are the ones an RTX 4070 SUPER (driver 610.88) wrote without `--wave64-emulate`. The + cs_w64x tests with branches need llvm-mc encodings and are not covered. - `test_negative_controls.py` sabotages the translated SPIR-V text and requires the result to change. - `test_mutations.py` sabotages a temporary copy of `tools/` (13 regressions across SDWA, min3/max3, `v_bfe_i32`, `v_pk_fma_f16`, `v_fma_f16 op_sel`, `v_subrev_co_ci_u32`, `v_cmpx_eq_u64`, `v_mul_i32_i24`, `v_ffbh_i32`, @@ -30,9 +44,11 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): - `test_fixtures.py` checks `tests/semantic/fixtures/disasm/*.s` equals what `regen_fixtures.py` makes from `runtime/test/shaders/*.asm` (`python tests/semantic/regen_fixtures.py` rewrites them). -Limits: single lane, forward-only structured control flow (the fragment-exit discard test and the compute +Limits: single lane (or lanes in lockstep, one instruction per lane per round, that exchange values only through +`OpGroupNonUniformShuffle`, `Ballot`, `Any`, `All` and `BitwiseOr` Reduce), forward-only structured control flow (the fragment-exit discard test and the compute dynamic-bounds merge; no backward branches, loops, calls or switches), no texture access. PushConstant words, -Input variables and a flat physical-address `{address: word}` map can be supplied per run. Values that pass +Input variables and a flat physical-address `{address: word}` map can be supplied per run. A shift by at least the bit width is an undefined value: arithmetic on it stays +undefined and any other use (store, branch or select condition, shuffle, output) raises. Values that pass through a float op lose NaN payloads (Python floats), so expected output words avoid NaN bit patterns. `Fma` is computed in double precision then rounded to binary32 (exact for the f16-derived operands used). The `.asm` sources are written for `llvm-mc -mcpu=gfx1013`; these tests do not assemble them, so assembler syntax is not diff --git a/tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s b/tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s new file mode 100644 index 000000000..c22f609b5 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_cvt_f32_sat.s @@ -0,0 +1,7 @@ +; cs_cvt_f32_sat test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_cvt_f32_sat.asm + v_mov_b32_e32 v0, s4 + v_mov_b32_e32 v1, 0 + v_cvt_u32_f32_e32 v2, v0 + v_cvt_i32_f32_e32 v3, v0 + buffer_store_dwordx2 v[2:3], v1, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_ballot.s b/tests/semantic/fixtures/disasm/cs_w64x_ballot.s new file mode 100644 index 000000000..f44905677 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_ballot.s @@ -0,0 +1,14 @@ +; cs_w64x_ballot test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_ballot.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_and_b32_e32 v2, 7, v1 + v_cmp_eq_u32_e64 s[4:5], 5, v2 + s_bcnt1_i32_b64 s6, s[4:5] + v_mbcnt_lo_u32_b32 v3, s4, 0 + v_mbcnt_hi_u32_b32 v3, s5, v3 + v_lshlrev_b32_e32 v4, 2, v3 + s_lshl_b32 s7, s6, 8 + v_add_nc_u32_e32 v5, s7, v1 + s_mov_b64 exec, s[4:5] + buffer_store_dword v5, v4, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_bpermute.s b/tests/semantic/fixtures/disasm/cs_w64x_bpermute.s new file mode 100644 index 000000000..808a80645 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_bpermute.s @@ -0,0 +1,60 @@ +; cs_w64x_bpermute test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_bpermute.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mad_u32_u24 v2, v1, 7, 1 + v_add_nc_u32_e32 v3, 5, v1 + v_lshlrev_b32_e32 v3, 2, v3 + ds_bpermute_b32 v4, v3, v2 + v_and_b32_e32 v5, 31, v1 + v_sub_nc_u32_e32 v5, 63, v5 + v_lshlrev_b32_e32 v5, 2, v5 + ds_bpermute_b32 v5, v5, v2 + s_waitcnt lgkmcnt(0) + v_mov_b32_e32 v6, 99 + v_add_nc_u32_e32 v7, 14, v1 + v_lshlrev_b32_e32 v7, 2, v7 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, 0xffff0000 + ds_bpermute_b32 v6, v7, v2 + s_waitcnt lgkmcnt(0) + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 50, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 49, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_load_ballot_load.s b/tests/semantic/fixtures/disasm/cs_w64x_load_ballot_load.s new file mode 100644 index 000000000..d4bb28149 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_load_ballot_load.s @@ -0,0 +1,62 @@ +; cs_w64x_load_ballot_load test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_load_ballot_load.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_add_nc_u32_e32 v2, 10, v1 + v_lshlrev_b32_e32 v3, 2, v1 + buffer_store_dword v2, v3, s[0:3], 0 offen + s_waitcnt_vscnt null, 0x0 + s_waitcnt vmcnt(0) + v_xor_b32_e32 v7, 32, v1 + v_lshlrev_b32_e32 v7, 2, v7 + buffer_load_dword v4, v7, s[0:3], 0 offen + s_waitcnt vmcnt(0) + v_cmp_gt_u32_e64 s[4:5], v4, 41 + s_bcnt1_i32_b64 s6, s[4:5] + v_add_nc_u32_e32 v8, 1, v1 + v_and_b32_e32 v8, 63, v8 + v_lshlrev_b32_e32 v8, 2, v8 + buffer_load_dword v5, v8, s[0:3], 0 offen + s_waitcnt vmcnt(0) + v_add_nc_u32_e32 v6, s6, v5 + buffer_store_dword v6, v3, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 31, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 32, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v6 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 5, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_partial.s b/tests/semantic/fixtures/disasm/cs_w64x_partial.s new file mode 100644 index 000000000..5630b590c --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_partial.s @@ -0,0 +1,62 @@ +; cs_w64x_partial test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_partial.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_add_nc_u32_e32 v2, 500, v1 + s_mov_b64 s[6:7], exec + s_bcnt1_i32_b64 s8, exec + v_cmp_eq_u32_e64 s[4:5], v1, v1 + s_bcnt1_i32_b64 s11, s[4:5] + v_add_nc_u32_e32 v3, 8, v1 + v_lshlrev_b32_e32 v3, 2, v3 + ds_bpermute_b32 v4, v3, v2 + v_xor_b32_e32 v6, 1, v1 + v_lshlrev_b32_e32 v6, 2, v6 + ds_bpermute_b32 v5, v6, v2 + s_waitcnt lgkmcnt(0) + v_cmpx_lt_u32_e32 31, v1 + v_readfirstlane_b32 s9, v2 + s_bcnt1_i32_b64 s10, exec + s_mov_b64 exec, s[6:7] + s_lshl_b32 s10, s10, 16 + s_add_u32 s9, s9, s10 + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s8 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 39, v1 + v_mov_b32_e32 v20, s11 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 20, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 39, v1 + v_mov_b32_e32 v20, v4 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 38, v1 + v_mov_b32_e32 v20, v5 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, s[6:7] + v_cmpx_eq_u32_e32 2, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_readfirstlane.s b/tests/semantic/fixtures/disasm/cs_w64x_readfirstlane.s new file mode 100644 index 000000000..c00007de9 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_readfirstlane.s @@ -0,0 +1,73 @@ +; cs_w64x_readfirstlane test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_readfirstlane.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_add_nc_u32_e32 v2, 100, v1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xffffff00 + v_readfirstlane_b32 s6, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0x80000000 + v_readfirstlane_b32 s7, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 1 + v_readfirstlane_b32 s8, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0 + v_readfirstlane_b32 s9, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0x20 + s_mov_b32 exec_hi, 0xe + v_readfirstlane_b32 s10, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xe + v_readfirstlane_b32 s11, v2 + s_mov_b64 exec, -1 + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xffff0000 + v_readfirstlane_b32 s12, v1 + s_mov_b64 exec, -1 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 5, v1 + v_mov_b32_e32 v20, s7 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, s8 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 34, v1 + v_mov_b32_e32 v20, s10 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s11 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 49, v1 + v_mov_b32_e32 v20, s12 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_readlane.s b/tests/semantic/fixtures/disasm/cs_w64x_readlane.s new file mode 100644 index 000000000..bf27ecde5 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_readlane.s @@ -0,0 +1,51 @@ +; cs_w64x_readlane test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_readlane.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mad_u32_u24 v2, v1, 3, 1 + v_readlane_b32 s6, v2, 40 + v_readlane_b32 s7, v2, 5 + v_readlane_b32 s8, v2, 32 + s_mov_b32 s10, 97 + v_readlane_b32 s9, v2, s10 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 33, v1 + v_mov_b32_e32 v20, s6 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, s7 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s8 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 45, v1 + v_mov_b32_e32 v20, s7 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 7, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 60, v1 + v_mov_b32_e32 v20, s9 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_readlane_b32 s11, v2, 40 + v_mov_b32_e32 v20, s11 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_w64x_writelane.s b/tests/semantic/fixtures/disasm/cs_w64x_writelane.s new file mode 100644 index 000000000..fa4eb732f --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_w64x_writelane.s @@ -0,0 +1,56 @@ +; cs_w64x_writelane test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_w64x_writelane.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mov_b32_e32 v10, 0 + s_mov_b32 s6, 0x1234 + s_mov_b32 s7, 77 + s_mov_b32 s8, 99 + s_mov_b32 s11, 0xabc + s_mov_b32 s9, 96 + v_writelane_b32 v10, s6, 40 + v_writelane_b32 v10, s7, 3 + v_writelane_b32 v10, s8, 63 + v_writelane_b32 v10, s11, s9 + v_readlane_b32 s12, v10, 40 + v_readlane_b32 s13, v10, 63 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 40, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 0 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 3, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 4 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 63, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 8 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 32, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 12 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 39, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 16 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 41, v1 + v_mov_b32_e32 v20, v10 + v_mov_b32_e32 v21, 20 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v1 + v_mov_b32_e32 v20, s12 + v_mov_b32_e32 v21, 24 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 8, v1 + v_mov_b32_e32 v20, s13 + v_mov_b32_e32 v21, 28 + buffer_store_dword v20, v21, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wave64_ballot.s b/tests/semantic/fixtures/disasm/cs_wave64_ballot.s new file mode 100644 index 000000000..6b353b44f --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wave64_ballot.s @@ -0,0 +1,34 @@ +; cs_wave64_ballot test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wave64_ballot.asm + v_cmp_ge_u32_e64 s[4:5], v0, 16 + v_cmp_lt_u32_e64 s[6:7], v0, 48 + s_and_b64 s[4:5], s[4:5], s[6:7] + s_bcnt1_i32_b64 s8, s[4:5] + s_ff1_i32_b64 s9, s[4:5] + v_cmp_ge_u32_e64 s[10:11], v0, 40 + s_bcnt1_i32_b64 s12, s[10:11] + s_ff1_i32_b64 s13, s[10:11] + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0x00ff0000 + s_bcnt1_i32_b64 s14, exec + s_ff1_i32_b64 s15, exec + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v0 + v_mov_b32_e32 v1, s8 + v_mov_b32_e32 v2, s9 + v_mov_b32_e32 v3, s12 + v_mov_b32_e32 v4, s13 + v_mov_b32_e32 v5, s14 + v_mov_b32_e32 v6, s15 + v_mov_b32_e32 v10, 0 + v_mov_b32_e32 v11, 4 + v_mov_b32_e32 v12, 8 + v_mov_b32_e32 v13, 12 + v_mov_b32_e32 v14, 16 + v_mov_b32_e32 v15, 20 + buffer_store_dword v1, v10, s[0:3], 0 offen + buffer_store_dword v2, v11, s[0:3], 0 offen + buffer_store_dword v3, v12, s[0:3], 0 offen + buffer_store_dword v4, v13, s[0:3], 0 offen + buffer_store_dword v5, v14, s[0:3], 0 offen + buffer_store_dword v6, v15, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wavemask.s b/tests/semantic/fixtures/disasm/cs_wavemask.s new file mode 100644 index 000000000..e88ed1ae3 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wavemask.s @@ -0,0 +1,54 @@ +; cs_wavemask test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wavemask.asm + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_lshlrev_b32_e32 v3, 2, v1 + v_mov_b32_e32 v4, 0 + s_mov_b32 exec_lo, 0xffff0000 + s_mov_b32 exec_hi, 0xffff + s_mov_b64 s[6:7], exec + s_bcnt1_i32_b64 s8, exec + s_bcnt1_i32_b64 s10, s[6:7] + s_add_i32 s8, s8, s10 + s_cmp_lg_u32 s6, 0 + s_cselect_b32 s14, 1, 0 + s_add_i32 s8, s8, s14 + s_cmp_eq_u64 s[6:7], 0 + s_cselect_b32 s14, 2, 0 + s_add_i32 s8, s8, s14 + s_ff1_i32_b64 s9, exec + v_cmp_gt_u32_e32 vcc_lo, 24, v1 + s_bcnt1_i32_b64 s11, vcc + v_mbcnt_lo_u32_b32 v4, s6, 0 + v_mbcnt_hi_u32_b32 v4, s7, v4 + v_mov_b32_e32 v6, s6 + v_or3_b32 v6, s6, s6, v6 + v_readfirstlane_b32 s12, v6 + v_mov_b32_e32 v6, s7 + v_readfirstlane_b32 s13, v6 + v_writelane_b32 v10, s6, 0 + v_writelane_b32 v10, s7, 1 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, -1 + s_mov_b32 s6, 0 + s_mov_b32 s7, 0 + v_mov_b32_e32 v5, 0 + v_readlane_b32 s6, v10, 0 + v_readlane_b32 s7, v10, 1 + s_mov_b64 exec, s[6:7] + v_mov_b32_e32 v5, 0x80 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, -1 + v_mov_b32_e32 v7, 0 + s_mov_b64 exec, s[12:13] + v_mov_b32_e32 v7, 0x40 + s_mov_b32 exec_lo, -1 + s_mov_b32 exec_hi, -1 + s_lshl_b32 s9, s9, 8 + s_lshl_b32 s11, s11, 16 + s_or_b32 s8, s8, s9 + s_or_b32 s8, s8, s11 + v_or3_b32 v4, v4, v5, v7 + v_lshlrev_b32_e32 v4, 24, v4 + v_or_b32_e32 v2, s8, v4 + buffer_store_dword v2, v3, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wm_bfm64.s b/tests/semantic/fixtures/disasm/cs_wm_bfm64.s new file mode 100644 index 000000000..3535dca66 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wm_bfm64.s @@ -0,0 +1,22 @@ +; cs_wm_bfm64 test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wm_bfm64.asm + s_mov_b64 exec, -1 + s_bfm_b64 s[6:7], 16, 8 + s_bcnt1_i32_b64 s8, s[6:7] + s_ff1_i32_b64 s9, s[6:7] + s_bfm_b64 s[10:11], 8, 40 + s_bcnt1_i32_b64 s12, s[10:11] + s_ff1_i32_b64 s13, s[10:11] + v_cmpx_eq_u32_e32 0, v0 + v_mov_b32_e32 v1, s8 + v_mov_b32_e32 v2, 0 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s9 + v_mov_b32_e32 v2, 4 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s12 + v_mov_b32_e32 v2, 8 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s13 + v_mov_b32_e32 v2, 12 + buffer_store_dword v1, v2, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/cs_wm_half_cmp.s b/tests/semantic/fixtures/disasm/cs_wm_half_cmp.s new file mode 100644 index 000000000..bed78213b --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_wm_half_cmp.s @@ -0,0 +1,27 @@ +; cs_wm_half_cmp test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_wm_half_cmp.asm + s_mov_b32 exec_lo, 0 + s_mov_b32 exec_hi, 0xffff + s_mov_b64 s[6:7], exec + s_cmp_eq_u32 s6, 0 + s_cselect_b32 s8, 1, 0 + s_cmp_lg_u32 s6, 0 + s_cselect_b32 s9, 1, 0 + s_cmp_lg_u32 s7, 0 + s_cselect_b32 s10, 1, 0 + s_cmp_eq_u32 exec_lo, 0 + s_cselect_b32 s11, 1, 0 + s_mov_b64 exec, -1 + v_cmpx_eq_u32_e32 0, v0 + v_mov_b32_e32 v1, s8 + v_mov_b32_e32 v2, 0 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s9 + v_mov_b32_e32 v2, 4 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s10 + v_mov_b32_e32 v2, 8 + buffer_store_dword v1, v2, s[0:3], 0 offen + v_mov_b32_e32 v1, s11 + v_mov_b32_e32 v2, 12 + buffer_store_dword v1, v2, s[0:3], 0 offen + s_endpgm diff --git a/tests/semantic/fixtures/disasm/ps_scc_minmax.s b/tests/semantic/fixtures/disasm/ps_scc_minmax.s new file mode 100644 index 000000000..033ac4416 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_scc_minmax.s @@ -0,0 +1,43 @@ +; ps_scc_minmax test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_scc_minmax.asm + s_mov_b32 s0, 5 + s_min_i32 s1, s0, 5 + s_cselect_b32 s2, 1, 2 + s_min_i32 s3, -1, 1 + s_cselect_b32 s4, 3, 4 + s_lshl_b32 s2, s2, 8 + s_lshl_b32 s4, s4, 16 + s_or_b32 s1, s1, s2 + s_or_b32 s1, s1, s4 + s_mov_b32 s0, 7 + s_max_i32 s5, s0, 7 + s_cselect_b32 s6, 1, 2 + s_max_i32 s7, 1, -1 + s_cselect_b32 s8, 3, 4 + s_lshl_b32 s6, s6, 8 + s_lshl_b32 s8, s8, 16 + s_or_b32 s5, s5, s6 + s_or_b32 s5, s5, s8 + s_mov_b32 s0, 9 + s_min_u32 s9, s0, 9 + s_cselect_b32 s10, 1, 2 + s_min_u32 s11, 1, -1 + s_cselect_b32 s12, 3, 4 + s_lshl_b32 s10, s10, 8 + s_lshl_b32 s12, s12, 16 + s_or_b32 s9, s9, s10 + s_or_b32 s9, s9, s12 + s_mov_b32 s0, 3 + s_max_u32 s13, s0, 3 + s_cselect_b32 s14, 1, 2 + s_max_u32 s15, -1, 1 + s_cselect_b32 s16, 3, 4 + s_lshl_b32 s14, s14, 8 + s_lshl_b32 s16, s16, 16 + s_or_b32 s13, s13, s14 + s_or_b32 s13, s13, s16 + v_mov_b32_e32 v0, s1 + v_mov_b32_e32 v1, s5 + v_mov_b32_e32 v2, s9 + v_mov_b32_e32 v3, s13 + exp mrt0 v0, v1, v2, v3 done vm + s_endpgm diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index 22f859766..a1dba1b27 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py @@ -17,7 +17,10 @@ ROOT = os.path.dirname(os.path.dirname(HERE)) ASM_DIR = os.path.join(ROOT, "runtime", "test", "shaders") FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") SHADERS = ("ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", - "ps_legacy_mul", "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_fmt_1010102") + "ps_legacy_mul", "ps_vcc_x2", "ps_flat", "cs_bounds", "cs_fmt_1010102", "cs_w64x_readlane", + "cs_w64x_writelane", "cs_w64x_bpermute", "cs_w64x_ballot", "cs_w64x_readfirstlane", + "cs_w64x_load_ballot_load", "cs_w64x_partial", "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp", + "cs_wavemask", "cs_cvt_f32_sat", "ps_scc_minmax") def render(name): diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index 85a8a485a..7a4f1fe43 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -7,7 +7,9 @@ Design rules (see tests/semantic/README.md): * Strict: any opcode, extended instruction, type or storage class not listed below raises UnsupportedConstruct. Nothing is skipped or approximated silently, so a translator change that starts emitting something new makes the test error out instead of passing. - * One invocation (one lane). Control flow is the forward-only discard test and the forward merge/dynamic-bounds + * One invocation (one lane), or with run_workgroup several in lockstep, which meet only at + subgroup operations (Shuffle, Ballot, Any, All, BitwiseOr Reduce; BallotBitExtract and BallotFindLSB + are per lane). Control flow is the forward-only discard test and the forward merge/dynamic-bounds branches the translator emits: OpBranch / OpBranchConditional to a later label plus OpPhi at the merge block. Backward branches, loops, calls and switches are rejected. Function/Output/Input variables live in Python boxes; PushConstant reads can be seeded with a word list; physical-storage-buffer loads/stores use a flat @@ -40,6 +42,27 @@ _IGNORED = frozenset({ _LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") +class _Undef: + """An undefined value (SPIR-V: a shift by at least the bit width). Pure arithmetic on it gives another + undefined value; any other use (a store, a branch or select condition, a subgroup operation, an output) + raises, so a result that does not depend on it, such as the unselected side of OpSelect, is still exact.""" + + def __repr__(self): + return "" + + +UNDEF = _Undef() + +# Operations whose result is undefined when an operand is (they have no side effect and no control). +_PURE = frozenset({ + "OpBitwiseAnd", "OpBitwiseOr", "OpBitwiseXor", "OpNot", "OpShiftLeftLogical", "OpShiftRightLogical", + "OpShiftRightArithmetic", "OpIAdd", "OpISub", "OpIMul", "OpUConvert", "OpBitCount", "OpIEqual", + "OpINotEqual", "OpSLessThan", "OpULessThan", "OpUGreaterThan", "OpUGreaterThanEqual", "OpCopyObject", + "OpBitcast", + "OpBitFieldUExtract", "OpBitFieldSExtract", "OpBitFieldInsert", +}) + + def f32(x): """Round a Python float to binary32 (overflow to infinity).""" try: @@ -124,7 +147,110 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): PhysicalStorageBuffer loads and stores. Returns {output_variable_name: tuple_of_32bit_words}. Float outputs are returned as their bit patterns. + A module with a subgroup operation is rejected here; see run_workgroup. """ + gen = _invocation(text, inputs, push_constants, memory) + try: + req = next(gen) + except StopIteration as done: + return done.value + gen.close() + raise UnsupportedConstruct(f"{req[0]} in a single invocation (use run_workgroup)") + + +class UndefinedResult(Exception): + """A subgroup operation whose result SPIR-V leaves undefined (for example a shuffle from a lane that is not in + the subgroup). Raised instead of inventing a value.""" + + +def run_workgroup(text, invocations, subgroup_size, inputs_for=None, push_constants=None, memory=None, + out_of_range="raise"): + """Execute `invocations` invocations of `text` in lockstep and return the shared `memory`. + + Invocation i is subgroup i // subgroup_size, lane i % subgroup_size (a 1-D workgroup split into subgroups in + invocation order). When `invocations` is not a multiple of `subgroup_size` the last subgroup is partial: its + missing lanes are not running. `inputs_for(i)` gives invocation i's Input values (see run_fragment); push + constants and the physical-address memory are shared. Every invocation must reach every subgroup operation, + in the same order (the translator emits them in uniform control flow and models EXEC with a variable, so a + lane that is off in EXEC still executes them). + + Subgroup operations (Subgroup scope), over the running lanes of the caller's subgroup: + * OpGroupNonUniformShuffle returns the value of lane Id. An Id at or past `subgroup_size` is undefined in + SPIR-V: `out_of_range="raise"` raises UndefinedResult; `out_of_range="wrap"` takes lane Id mod + subgroup_size instead, a model of one observed driver behaviour and not of the specification (Leonida + issue #94: on a 32-wide NVIDIA subgroup lane 40 read lane 8). An Id inside the subgroup whose lane is not + running gives an undefined value (raises only if used, see _Undef). + * OpGroupNonUniformBallot sets bit l for each running lane l whose predicate is true. + * OpGroupNonUniformAny / All: the predicate of any / every running lane. + * OpGroupNonUniformBitwiseOr Reduce: the OR of every running lane's value. + """ + if out_of_range not in ("raise", "wrap"): + raise ValueError(f"out_of_range: {out_of_range!r}") + memory = {} if memory is None else memory + gens = [_invocation(text, (inputs_for(i) if inputs_for else None), push_constants, memory, step=True) + for i in range(invocations)] + pending = [None] * invocations # what each invocation yielded last; None once it has returned + + def advance(i, value): + try: + pending[i] = gens[i].send(value) + except StopIteration: + pending[i] = None + + for i in range(invocations): + advance(i, None) + while True: + # One instruction per invocation per round, in invocation order: invocations at the same instruction + # execute it one after the other before any goes on, as the lanes of a SIMD wave do, so a load that + # follows a store in program order sees every lane's store and none from a later instruction. + while any(req is not None and req[0] == "tick" for req in pending): + for i in range(invocations): + if pending[i] is not None and pending[i][0] == "tick": + advance(i, None) + live = [i for i in range(invocations) if pending[i] is not None] + if not live: + break + if len(live) != invocations or len({pending[i][1] for i in live}) != 1: + raise UnsupportedConstruct("subgroup operation not reached by every invocation at the same point") + results = [] + for i in range(invocations): + kind, _, _value, ident = pending[i] + base = (i // subgroup_size) * subgroup_size + group = [pending[j] for j in range(base, min(base + subgroup_size, invocations))] + if kind == "OpGroupNonUniformBallot": + # Bit l of the 128-bit mask = lane l of this subgroup is running with a true predicate. + bits = sum(1 << l for l, req in enumerate(group) if req[2]) + results.append(tuple((bits >> (32 * w)) & MASK for w in range(4))) + elif kind == "OpGroupNonUniformAny": + results.append(any(req[2] for req in group)) + elif kind == "OpGroupNonUniformAll": + results.append(all(req[2] for req in group)) + elif kind == "OpGroupNonUniformBitwiseOr": + acc = 0 + for req in group: + acc |= req[2] + results.append(acc) + elif kind == "OpGroupNonUniformShuffle": + if not 0 <= ident < subgroup_size: + if out_of_range == "raise": + raise UndefinedResult(f"invocation {i}: shuffle from lane {ident} of a " + f"{subgroup_size}-wide subgroup") + ident %= subgroup_size + results.append(group[ident][2] if ident < len(group) else UNDEF) + else: + raise UnsupportedConstruct(kind) + for i in range(invocations): + advance(i, results[i]) + return memory + + +_TICK = ("tick", None, None, None) + + +def _invocation(text, inputs, push_constants, memory, step=False): + """One invocation as a generator. It yields (opcode, instruction index, value, id) at each subgroup operation + and expects that operation's result back; with `step` it also yields _TICK before each instruction. It + returns run_fragment's result.""" inputs = inputs or {} push_constants = list(push_constants or []) memory = {} if memory is None else memory @@ -265,6 +391,8 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): killed = False cur_label = prev_label = None while pc < len(body): + if step: + yield _TICK res, op, a, line = body[pc] pc += 1 if res and a: @@ -297,6 +425,12 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): raise UnsupportedConstruct("OpPhi with an unknown predecessor") values[res] = val(incoming[0]) continue + if op in _PURE and any(values.get(x) is UNDEF for x in a[1:]): + values[res] = UNDEF + continue + used = a[1:2] if op == "OpSelect" else a # OpSelect may pass the chosen undefined value on + if any(values.get(x) is UNDEF for x in used): + raise UnsupportedConstruct(f"{op} uses an undefined value: {line}") if op == "OpVariable": cls, pointee = ptr_types[a[0]] if cls != "Function": @@ -386,17 +520,20 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): elif op == "OpShiftLeftLogical": bits = types.bits(a[0]) if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = UNDEF # undefined in SPIR-V; raises only if it is used + continue values[res] = (val(a[1]) << val(a[2])) & wmask(a[0]) elif op == "OpShiftRightLogical": bits = types.bits(a[0]) if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = UNDEF # undefined in SPIR-V; raises only if it is used + continue values[res] = (val(a[1]) & wmask(a[0])) >> val(a[2]) elif op == "OpShiftRightArithmetic": bits = types.bits(a[0]) if val(a[2]) >= bits: - raise UnsupportedConstruct(f"shift amount >= {bits} (undefined in SPIR-V)") + values[res] = UNDEF # undefined in SPIR-V; raises only if it is used + continue values[res] = (signed(val(a[1]), bits) >> val(a[2])) & wmask(a[0]) elif op == "OpIAdd": values[res] = (val(a[1]) + val(a[2])) & wmask(a[0]) @@ -445,6 +582,40 @@ def run_fragment(text, inputs=None, push_constants=None, memory=None): values[res] = val(a[1]) > val(a[2]) elif op == "OpUGreaterThanEqual": values[res] = val(a[1]) >= val(a[2]) + elif op == "OpGroupNonUniformShuffle": + # OpGroupNonUniformShuffle ; the scope must be Subgroup (3). + if types.t[a[0]][0] != "int" or val(a[1]) != 3: + raise UnsupportedConstruct("OpGroupNonUniformShuffle other than a Subgroup-scope integer") + values[res] = yield (op, pc - 1, val(a[2]), val(a[3])) + elif op == "OpGroupNonUniformBallot": + # OpGroupNonUniformBallot + k = types.t[a[0]] + if k[0] != "vec" or k[2] != 4 or val(a[1]) != 3 or not isinstance(val(a[2]), bool): + raise UnsupportedConstruct("OpGroupNonUniformBallot other than a Subgroup-scope uvec4") + values[res] = yield (op, pc - 1, val(a[2]), None) + elif op in ("OpGroupNonUniformAny", "OpGroupNonUniformAll"): + # + if val(a[1]) != 3 or not isinstance(val(a[2]), bool): + raise UnsupportedConstruct(f"{op} other than a Subgroup-scope bool") + values[res] = yield (op, pc - 1, val(a[2]), None) + elif op == "OpGroupNonUniformBitwiseOr": + # : only Reduce over a 32-bit integer. + if val(a[1]) != 3 or a[2] != "Reduce" or types.t[a[0]][:2] != ("int", 32): + raise UnsupportedConstruct("OpGroupNonUniformBitwiseOr other than a Subgroup-scope 32-bit Reduce") + values[res] = yield (op, pc - 1, val(a[3]) & MASK, None) + elif op == "OpGroupNonUniformBallotFindLSB": + # : the lowest set bit; undefined when no bit is set. + ballot = val(a[2]) + if val(a[1]) != 3: + raise UnsupportedConstruct("OpGroupNonUniformBallotFindLSB scope") + bits = sum(w << (32 * k) for k, w in enumerate(ballot)) + values[res] = (bits & -bits).bit_length() - 1 if bits else UNDEF + elif op == "OpGroupNonUniformBallotBitExtract": + # OpGroupNonUniformBallotBitExtract : needs no other lane. + ballot, idx = val(a[2]), val(a[3]) + if val(a[1]) != 3 or not 0 <= idx < 128: + raise UnsupportedConstruct("OpGroupNonUniformBallotBitExtract scope or index") + values[res] = bool((ballot[idx // 32] >> (idx % 32)) & 1) elif op == "OpLogicalAnd": x, y = val(a[1]), val(a[2]) if not (isinstance(x, bool) and isinstance(y, bool)): diff --git a/tests/semantic/test_float_to_int.py b/tests/semantic/test_float_to_int.py new file mode 100644 index 000000000..99a9bd106 --- /dev/null +++ b/tests/semantic/test_float_to_int.py @@ -0,0 +1,44 @@ +"""VOP1 conversions with known binary32 inputs and integer output words.""" +import struct +import unittest + +import support + + +# Input bits, unsigned result, signed result (as an untyped 32-bit word). +CASES = ( + (0x00000000, 0, 0), # +0 + (0x80000000, 0, 0), # -0 + (0x00000001, 0, 0), # subnormal + (0x3FC00000, 1, 1), # +1.5 + (0xBFC00000, 0, 0xFFFFFFFF), # -1.5 + (0x4EFFFFFF, 0x7FFFFF80, 0x7FFFFF80), # largest binary32 below +2^31 + (0x4F000000, 0x80000000, 0x7FFFFFFF), # +2^31 + (0x4F7FFFFF, 0xFFFFFF00, 0x7FFFFFFF), # largest binary32 below +2^32 + (0x4F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +2^32 + (0xCEFFFFFF, 0, 0x80000080), # -(2^31 - 128) + (0xCF000000, 0, 0x80000000), # -2^31 + (0xCF000001, 0, 0x80000000), # next binary32 below -2^31 + (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +infinity + (0xFF800000, 0, 0x80000000), # -infinity + (0x7F800001, 0, 0), # first positive NaN encoding + (0xFFC00000, 0, 0), # negative quiet NaN +) + + +class FloatToIntTest(unittest.TestCase): + def test_saturating_conversions(self): + # Five user SGPRs, with s4 carrying the input after the output V#. + fssm = bytes(0x138) + struct.pack("<4I", 0x808A, 1, 1, 1) + spv = support.translate_fixture("cs_cvt_f32_sat", fssm=fssm) + for bits, unsigned, signed in CASES: + with self.subTest(bits=f"{bits:08x}"): + memory = {} + support.run_fragment( + spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, + push_constants=[0, 0, 8, 0, bits] + [0] * 27, memory=memory) + self.assertEqual(memory, {0: unsigned, 4: signed}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_value_semantics.py b/tests/semantic/test_value_semantics.py index c7ea121b9..34db5ac9b 100644 --- a/tests/semantic/test_value_semantics.py +++ b/tests/semantic/test_value_semantics.py @@ -25,6 +25,7 @@ ISA semantics used (AMD RDNA2 ISA reference, VALU/VOP3/VOP3P chapters): v_bcnt_u32_b32 D = popcount(S0) + S1. v_ffbl_b32/ffbh_u32 index of the lowest set bit / count of leading zeros; 0xffffffff when S0 = 0. v_xad_u32/add3_u32 D = (S0 ^ S1) + S2 / D = S0 + S1 + S2, both mod 2^32. + s_min/max_i32/u32 D = S0 < S1 ? S0 : S1 (max: >), SCC = 1 when S0 is chosen, so a tie gives S1 and SCC 0. The appended cases for ps_ops5/ps_ops6 also pin the op_sel source-half selection for packed shifts, which the GPU-checked ps_ops4 does not exercise. cs_bounds (compute) pins the buffer num_records bounds checks: an @@ -47,6 +48,7 @@ EXPECTED_OPS7 = [0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003] EXPECTED_OPS8 = [0x80000000, 0xFFFFFFFF, 0x000F100E, 0x0F0F0F1F] EXPECTED_VCC_X2 = [0x11223344, 0x55667788, 0x00000000, 0x00000000] EXPECTED_FLAT = [0x00000101, 0x00000102, 0x3F000000, 0x3E800000] +EXPECTED_SCC_MINMAX = [0x00030205, 0x00030207, 0x00030209, 0x00030203] EXPECTED_BOUNDS = {0x00: 0x12345678, 0x04: 0x12345678, 0x08: 0x00000000, 0x0C: 0xEEEEEEEE} EXPECTED_FMT_1010102 = {0x00: 0x00000000, 0x04: 0x3F800000, 0x08: 0x00000000, 0x0C: 0x3F800000, 0x10: 0x3F800000, 0x14: 0x00000000, 0x18: 0x3F800000, 0x1C: 0x00000000, @@ -163,6 +165,23 @@ def reference_ops8(): (xad + 16 + m) & m] # v_ffbh_u32(0) = 0xffffffff +def reference_scc_minmax(): + def minmax(op, x, y): + """(D, SCC) of s_min/s_max _i32/_u32 on 32-bit words: SCC = 1 only when S0 is the one chosen.""" + kx, ky = (_s(x), _s(y)) if op.endswith("i32") else (x, y) + pick = kx < ky if op.startswith("min") else kx > ky + return x if pick else y, int(pick) + + words = [] + m1 = 0xFFFFFFFF # the inline constant -1 as a register word + for op, tie, strict in (("min_i32", 5, (m1, 1)), ("max_i32", 7, (1, m1)), + ("min_u32", 9, (1, m1)), ("max_u32", 3, (m1, 1))): + d, scc_tie = minmax(op, tie, tie) + _, scc_strict = minmax(op, *strict) + words.append(d | ((1 if scc_tie else 2) << 8) | ((3 if scc_strict else 4) << 16)) + return words + + def reference_vcc_x2(): return [0x11223344, 0x55667788, 0, 0] @@ -247,6 +266,7 @@ class OracleTests(unittest.TestCase): self.assertEqual(reference_ops8(), EXPECTED_OPS8) self.assertEqual(reference_vcc_x2(), EXPECTED_VCC_X2) self.assertEqual(reference_flat(), EXPECTED_FLAT) + self.assertEqual(reference_scc_minmax(), EXPECTED_SCC_MINMAX) self.assertEqual(reference_bounds(), EXPECTED_BOUNDS) self.assertEqual(reference_fmt_1010102(), EXPECTED_FMT_1010102) @@ -287,6 +307,11 @@ class TranslatorValueSemantics(unittest.TestCase): # v_ffbh_u32(0) = -1 feeding a wrapping v_add3_u32, and v_xad_u32. self.check("ps_ops8", EXPECTED_OPS8) + def test_s_min_max_scc_on_a_tie(self): + # Equal operands give S1 and SCC 0 for s_min/s_max _i32 and _u32; -1 vs 1 sets SCC only when compared + # with the op's own signedness. A tie that set SCC turns byte 1 of a word from 2 into 1. + self.check("ps_scc_minmax", EXPECTED_SCC_MINMAX) + def test_s_buffer_load_dwordx2_into_vcc(self): # The V# in s[0:3] points at 0x1000; the two dwords must come back in vcc_lo and vcc_hi, not be lost. push = [0x1000, 0, 16, 0] + [0] * 28 diff --git a/tests/semantic/test_wave64_cross_half.py b/tests/semantic/test_wave64_cross_half.py new file mode 100644 index 000000000..903fc1545 --- /dev/null +++ b/tests/semantic/test_wave64_cross_half.py @@ -0,0 +1,175 @@ +"""Wave64 cross-half lane operations, executed across all 64 lanes of the translated SPIR-V. + +The inputs are the GPU tests runtime/test/shaders/cs_w64x_readlane, cs_w64x_writelane and cs_w64x_bpermute +(hand-written, no game data; fixtures from regen_fixtures.py). Each is translated without --wave64-emulate and run +by spirv_mini_interp.run_workgroup as one 64-thread workgroup, in two layouts: + +* one 64-wide subgroup (AMD with requiredSubgroupSize = 64). The eight output words must equal the values the + GPU check expects (runtime/test/shaders/check.py W64X_DUMPS, scripts/run_gpu_tests.py), derived in each .asm + header from the RDNA2 ISA: v_readlane/v_writelane select lane S1 % 64 and ignore EXEC; ds_bpermute_b32 works + on each 32-lane half as an independent wave32 (ISA 10.4.4) and reads 0 from a lane that is off in EXEC. +* two 32-wide subgroups, invocations 0-31 and 32-63 (NVIDIA, e.g. an RTX 4070 Super, without emulation). This is + the documented gap in docs/design.md ("Wave64 handling": cross-lane ops between the two halves stay approximate + on 32-wide subgroups). The tests pin which results stay exact there and which do not: + - ds_bpermute_b32 never crosses halves, so all eight words stay exact; + - v_writelane_b32 writes the right lane in both halves (the wave lane comes from LocalInvocationIndex); + - a v_readlane_b32 from the other half shuffles from lane >= 32 of a 32-wide subgroup, which SPIR-V leaves + undefined. Strictly that is UndefinedResult. Under the wrap model (lane Id mod 32, the symptom in issue + #94, an observation and not the specification) the expected words below are what a 32-wide GPU without + --wave64-emulate shows. Measured: NVIDIA GeForce RTX 4070 SUPER (subgroup 32), driver 610.88, Vulkan SDK + 1.4.363.0, `vk_compute_test .spv 1 dump` on the non-emulated build of run_gpu_tests.py: all 24 + words equal WRAP32_EXPECTED. That is one driver's behaviour, not a requirement. + +Limits: --wave64-emulate output uses Workgroup memory and a round loop, which the interpreter rejects, so the +emulated path is covered only by the GPU tests. The subgroup layout (invocation i in subgroup i // 32) is the +usual one for a 1-D workgroup but Vulkan does not guarantee it. +""" +import re +import struct +import unittest + +import support +import spirv_mini_interp as si + +# 4 user SGPRs (the output V#), workgroup id in s4, 512 bytes of LDS, 64x1x1 threads: build.py's default header. +FSSM = bytearray(0x148) +struct.pack_into("<4I", FSSM, 0x138, 0x8088, 64, 1, 1) +FSSM = bytes(FSSM) +# V# in s[0:3]: base 0, stride 0, num_records 0x1000 bytes. out[k] is the dword at byte 4k. +VSHARP = [0, 0, 0x1000, 0] + +# Expected on a 64-wide subgroup: the GPU check's values (check.py W64X_DUMPS). +GPU_EXPECTED = { + "cs_w64x_readlane": [121, 121, 16, 97, 16, 100, 100, 121], + "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 4660, 99], + "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], +} + +# Two 32-wide subgroups, wrap model. readlane: v2 = 3 * lane + 1 and each subgroup reads lane (S1 % 64) % 32 of +# its own half. The low half reads lane 8 for lane 40 (25), lane 0 for 32 (1) and lane 1 for 33 (4); the upper +# half reads lane 32 + 5 = 37 for lane 5 (112). Words stored by lanes of the half the source lane is in stay right: +# out[0] lane 0: s6 = v2[8] = 25 out[1] lane 33: s6 = v2[40] = 121 out[2] lane 63: s7 = v2[37] = 112 +# out[3] lane 0: s8 = v2[0] = 1 out[4] lane 45: s7 = v2[37] = 112 out[5] lane 7: s9 = v2[1] = 4 +# out[6] lane 60: s9 = v2[33] = 100 out[7] lane 63: v2[40] = 121 +# writelane: the writes are exact, the two readlanes from lanes 0 and 8 read lanes 8 and 31 of the low half, +# which nobody wrote (0). +WRAP32_EXPECTED = { + "cs_w64x_readlane": [25, 121, 112, 1, 112, 4, 100, 121], + "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 0, 0], + "cs_w64x_bpermute": GPU_EXPECTED["cs_w64x_bpermute"], +} + + +def translate(name): + return support.translate_fixture(name, fssm=FSSM) + + +def run(spv, subgroup_size, out_of_range="raise"): + """Run one 64-thread workgroup; return out[0..7] and check nothing was written past them.""" + memory = si.run_workgroup( + spv, 64, subgroup_size, + inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, + push_constants=VSHARP + [0] * 28, memory={}, out_of_range=out_of_range) + stray = sorted(a for a in memory if not 0 <= a < 32 or a % 4) + if stray: + raise AssertionError(f"stores outside out[0..7]: {stray}") + return [memory.get(4 * k) for k in range(8)] + + +class Wave64OnSubgroup64(unittest.TestCase): + """Exact on a 64-wide subgroup: the values the GPU check expects.""" + + def test_each_shader(self): + for name, want in GPU_EXPECTED.items(): + with self.subTest(shader=name): + self.assertEqual(run(translate(name), 64), want) + + +class Wave64OnTwoSubgroups32(unittest.TestCase): + """The same modules on two 32-wide subgroups, no --wave64-emulate.""" + + def test_bpermute_stays_exact(self): + spv = translate("cs_w64x_bpermute") + self.assertEqual(run(spv, 32), GPU_EXPECTED["cs_w64x_bpermute"]) + + def test_cross_half_readlane_is_undefined(self): + for name in ("cs_w64x_readlane", "cs_w64x_writelane"): + with self.subTest(shader=name): + with self.assertRaisesRegex(si.UndefinedResult, r"lane 40 of a 32-wide subgroup"): + run(translate(name), 32) + + def test_wrap_model_prediction(self): + for name, want in WRAP32_EXPECTED.items(): + with self.subTest(shader=name): + got = run(translate(name), 32, out_of_range="wrap") + self.assertEqual(got, want) + wrong = [k for k in range(8) if got[k] != GPU_EXPECTED[name][k]] + self.assertEqual(bool(wrong), name != "cs_w64x_bpermute", f"{name}: words {wrong} differ") + + def test_writelane_writes_are_exact(self): + # out[0..5] are the written lanes and their untouched neighbours; only the readlanes (out[6..7]) cross. + got = run(translate("cs_w64x_writelane"), 32, out_of_range="wrap") + self.assertEqual(got[:6], GPU_EXPECTED["cs_w64x_writelane"][:6]) + + +class NegativeControls(unittest.TestCase): + """Sabotage the translated SPIR-V the way a translator regression would; the 64-wide result must change.""" + + def sabotage(self, name, pattern, repl, count): + spv = translate(name) + bad, n = re.subn(pattern, repl, spv) + self.assertEqual(n, count, f"anchor {pattern!r} matched {n} times in {name}") + got = run(bad, 64) + self.assertNotEqual(got, GPU_EXPECTED[name]) + return got + + def test_readlane_lane_select_mod_32(self): + # v_readlane lane = S1 & 31 instead of & 63 (the issue #94 symptom, moved into the translator). + got = self.sabotage("cs_w64x_readlane", + r"(OpBitwiseAnd %uint \S+ )%c3f(\n\s*%\w+ = OpGroupNonUniformShuffle)", r"\1%c1f\2", 5) + self.assertEqual(got[0], 25) # lane 40 -> lane 8 + + def test_bpermute_upper_half_reads_low_half(self): + # The half base from the subgroup lane dropped (the bug fixed on 2026-11-21, see docs/design.md "LDS"). + got = self.sabotage("cs_w64x_bpermute", + r"(= OpLoad %uint %sg_lane\n\s*%\w+ = OpBitwiseAnd %uint %\w+ )%c20", r"\1%c0", 3) + self.assertEqual(got[1], 7 * 13 + 1) # lane 40 reads lane 13 of the low half instead of lane 45 + + +_SHIFT_MODULE = """ +%uint = OpTypeInt 32 0 +%bool = OpTypeBool +%c1 = OpConstant %uint 1 +%c7 = OpConstant %uint 7 +%c40 = OpConstant %uint 40 +%true = OpConstantTrue %bool +%false = OpConstantFalse %bool +%_ptr_Output_uint = OpTypePointer Output %uint +%out = OpVariable %_ptr_Output_uint Output +%main = OpFunction +%entry = OpLabel +%big = OpShiftLeftLogical %uint %c1 %c40 +%dec = OpISub %uint %big %c1 +%pick = OpSelect %uint {cond} %c7 %dec +OpStore %out %pick +OpReturn +OpFunctionEnd +""" + + +class InterpreterContract(unittest.TestCase): + def test_undefined_shift_only_fails_when_used(self): + # 1 << 40 on a 32-bit type is undefined; the translator's v_mbcnt computes it for lanes >= 32 and selects + # it away. The unselected side is fine, storing it is not. + self.assertEqual(si.run_fragment(_SHIFT_MODULE.format(cond="%true")), {"%out": (7,)}) + with self.assertRaisesRegex(si.UnsupportedConstruct, "undefined value"): + si.run_fragment(_SHIFT_MODULE.format(cond="%false")) + + def test_single_invocation_rejects_a_shuffle(self): + with self.assertRaisesRegex(si.UnsupportedConstruct, "run_workgroup"): + si.run_fragment(translate("cs_w64x_readlane"), + inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, push_constants=VSHARP) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantic/test_wave64_subgroup_ops.py b/tests/semantic/test_wave64_subgroup_ops.py new file mode 100644 index 000000000..e7c5b39f0 --- /dev/null +++ b/tests/semantic/test_wave64_subgroup_ops.py @@ -0,0 +1,138 @@ +"""Wave64 whole-wave mask and vote tests, run across every lane of the translated SPIR-V. + +Eight GPU tests from runtime/test/shaders (hand-written, no game data; fixtures from regen_fixtures.py), translated +without --wave64-emulate and run by spirv_mini_interp.run_workgroup the way vk_compute_test runs them: one group +of the size in the .asm header (64 threads, 40 for cs_w64x_partial), a heap filled with 0xEE bytes, s[0:3] = a V# +with base 0 and num_records 0xFFFFFFFF. + +* One 64-wide subgroup: every word equals the GPU check's value (check.py CS_DUMPS, W64X_DUMPS, W64X_PARTIAL; for + cs_wavemask the per-lane formula of vk_compute_test's "wavemask" mode). This covers ballots and s_bcnt1 / + s_ff1 of 64-bit masks, readfirstlane with only upper lanes on, the votes behind wave-uniform branches, and the + missing lanes of a partial wave (21cef25's ds_bpermute guard: a shuffle from them is undefined and must be + selected away). +* Two 32-wide subgroups (NVIDIA without emulation): the words differ, and WAVE32_EXPECTED pins them. Measured: + NVIDIA GeForce RTX 4070 SUPER (subgroup 32), driver 610.88, `vk_compute_test .spv 1 dump` on + run_gpu_tests.py's non-emulated build, three runs each: every word equals WAVE32_EXPECTED, and cs_wavemask + reports 64 mismatches with lane 0 = 0x00081021, as here. These follow from SPIR-V (each subgroup votes over its + own 32 lanes) except cs_w64x_load_ballot_load, whose loads read the other subgroup's stores: the order between + subgroups is not specified, and the interpreter's (subgroup 0's instruction, then subgroup 1's) is the order + that GPU showed. + +Not covered: the cs_w64x tests with branches (branch, sbarrier, wg128_branches, and cs_wm_half_ops / +cs_wm_scc_rfl), because the translator needs llvm-mc's encodings for branch targets and these fixtures are +unassembled; and the --wave64-emulate output (Workgroup memory and a round loop). +""" +import os +import re +import struct +import sys +import unittest + +import support +import spirv_mini_interp as si + +sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) +import check # noqa: E402 (the GPU check's expected words) +from compute_fixture import compute_header # noqa: E402 + +ASM_DIR = os.path.join(support.ROOT, "runtime", "test", "shaders") +GPU_DUMPS = dict(check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL) +DUMPS = ("cs_w64x_ballot", "cs_w64x_readfirstlane", "cs_w64x_load_ballot_load", "cs_w64x_partial", + "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp") +HEAP_FILL = 0xEEEEEEEE +VSHARP = [0, 0, 0xFFFFFFFF, 0] + +# Two 32-wide subgroups: each half votes, counts and picks its first lane on its own. +WAVE32_EXPECTED = { + "cs_w64x_ballot": [1061, 1069, 1077, 1085] + [HEAP_FILL] * 4, + "cs_w64x_readfirstlane": [100, 140, 100, 132, 132, 133, 100, 48], + "cs_w64x_load_ballot_load": [43, 74, 43, 10, 42, 18, 41, 32], + "cs_w64x_partial": [32, 8, 528, 0, 0, 532, 539, 500], + "cs_wave64_ballot": [16, 16, 0, 0xFFFFFFFF, 0, 0xFFFFFFFF], + "cs_wm_bfm64": [16, 8, 0, 0xFFFFFFFF], + "cs_wm_half_cmp": [1, 0, 0, 1], +} + + +class Heap(dict): + """vk_compute_test's heap: every byte starts as 0xEE.""" + + def get(self, key, default=None): + return super().get(key, HEAP_FILL) + + +def wavemask_want(lane): + # vk_compute_test.cpp "wavemask": lanes 16-47 come back on after the parked mask (0x80) and the one through a + # VGPR (0x40), plus how many set lanes are below this one. + top = 0xC0 + lane - 16 if 16 <= lane < 48 else 0 + return 65 | 16 << 8 | 8 << 16 | top << 24 + + +def run(name, subgroup_size): + header = compute_header(os.path.join(ASM_DIR, name + ".asm")) + threads = struct.unpack_from("> (2 * k)) & 1) << k + b |= ((v >> (2 * k + 1)) & 1) << k + return a, b + + +def _encode_rans_syms(syms, model, x): + """Reverse-encode `syms` starting from end state `x`, returning `(new_x, bytes_reversed)`.""" + buf = [] + for s in reversed(syms): + p = s.bit_length() + f = model.freq[p] + c = model.base[p] + f * (s - (0 if p == 0 else 1 << (p - 1))) + if c == 0: + f, c = f - 1, 1 + limit = f << 16 + while x >= limit: + buf.append(x & 0xFF) + x >>= 8 + q_div, r_mod = divmod(x, f) + x = (q_div << 16) + c + r_mod + return x, buf + + +def _make_hdr(default_w, w, q, flush, n): + z = default_w - w + assert 0 <= z <= 3 and n >= 1 + if n <= 256: + return [((z & 3) << 6) | ((1 if flush else 0) << 4) | (q & 15), n - 1] + n2 = n - 257 + return [ + ((z & 3) << 6) | (1 << 5) | ((1 if flush else 0) << 4) | (q & 15), + n2 & 0xFF, + (n2 >> 8) & 0xFF, + ] + + +def _encode_fragment(syms, default_w, w, q, *, flush=True, strip_zeros=True): + """Encode `syms` into one standalone flush fragment (header + rANS payload).""" + assert flush + model = bcpack._get_model(w, q) + assert model is not None + x, buf = _encode_rans_syms(syms, model, bcpack.RANS_L) + payload = [(x >> 24) & 0xFF, (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF] + list(reversed(buf)) + if strip_zeros: + stripped = 0 + while len(payload) > 1 and payload[-1] == 0 and stripped < bcpack.MAX_VIRTUAL_ZEROS: + payload.pop() + stripped += 1 + return bytes(_make_hdr(default_w, w, q, True, len(payload)) + payload), 0 + + +def _encode_lane_stream(fragments, default_w): + """Chain one or more `(syms, w, q, flush)` fragments for a single lane. + + The final fragment must have `flush=True`. For a non-flush fragment followed + by another fragment, the boundary state is shifted below `RANS_L` so the + decoder finishes fragment `i` at `st < RANS_L` and renormalizes from fragment `i+1`. + """ + encoded = [None] * len(fragments) + x = bcpack.RANS_L + for idx in range(len(fragments) - 1, -1, -1): + syms, w, q, flush = fragments[idx] + model = bcpack._get_model(w, q) + assert model is not None + if flush: + x = bcpack.RANS_L + x, buf = _encode_rans_syms(syms, model, x) + prev_flush = True if idx == 0 else fragments[idx - 1][3] + if prev_flush: + # This fragment starts from state 0: prepend all 4 initial state bytes. + payload = [(x >> 24) & 0xFF, (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF] + list(reversed(buf)) + if flush: + stripped = 0 + while len(payload) > 1 and payload[-1] == 0 and stripped < bcpack.MAX_VIRTUAL_ZEROS: + payload.pop() + stripped += 1 + else: + # Previous fragment is non-flush: emit renormalization bytes into this + # fragment until `x < RANS_L` so the previous fragment hands off `x < RANS_L`. + while x >= bcpack.RANS_L: + buf.append(x & 0xFF) + x >>= 8 + payload = list(reversed(buf)) + encoded[idx] = bytes(_make_hdr(default_w, w, q, flush, len(payload)) + payload) + return b"".join(encoded) + + +def interleave_lanes(lane_streams, widths, nsym): + """Interleave per-lane byte streams according to the BCPack 8-byte/cycle scheduler.""" + nl = len(widths) + HDR0, HDR1, HDR2, PROC = 0, 1, 2, 3 + L = bcpack.RANS_L + ctrl = [HDR0] * nl + out_rem = [nsym] * nl + w = [0] * nl + q = [0] * nl + h3 = [0] * nl + flush = [0] * nl + done = [nsym <= 0] * nl + full = [False] * nl + held = [False] * nl + vz = [0] * nl + inbuf = [0] * nl + sym = [0] * nl + in_rem = [0] * nl + p0 = [0] * nl + p1 = [0] * nl + model = [None] * nl + slotfull = [False] * nl + stall = [False] * nl + lpos = [0] * nl + interleaved = bytearray() + max_cycles = max(1000, nsym * 64 + sum(len(s) for s in lane_streams) * 8) + + for _ in range(max_cycles): + if all(done[i] and not slotfull[i] for i in range(nl)): + for i in range(nl): + assert lpos[i] == len(lane_streams[i]), f"lane {i} left {len(lane_streams[i]) - lpos[i]} bytes" + return bytes(interleaved) + left = bcpack.PREFETCH_BUDGET + for i in range(nl): + if done[i] or (held[i] and slotfull[i]): + stall[i] = True + continue + stall[i] = False + if ctrl[i] == PROC: + p0[i] = model[i].advance(sym[i], p1[i]) if held[i] else p1[i] + if not full[i] and (ctrl[i] != PROC or in_rem[i] > 0): + if left == 0: + stall[i] = True + continue + b = lane_streams[i][lpos[i]] + lpos[i] += 1 + interleaved.append(b) + inbuf[i] = b + full[i] = True + left -= 1 + if held[i]: + slotfull[i] = True + held[i] = False + for i in range(nl): + if done[i] or stall[i]: + continue + c = ctrl[i] + if c == HDR0: + if not full[i]: + continue + h = inbuf[i] + q[i] = h & 15 + flush[i] = (h >> 4) & 1 + h3[i] = (h >> 5) & 1 + w[i] = widths[i] - (h >> 6) + full[i] = False + ctrl[i] = HDR1 + vz[i] = 0 + elif c == HDR1: + if not full[i]: + continue + full[i] = False + model[i] = bcpack._get_model(w[i], q[i]) + if h3[i]: + in_rem[i] = inbuf[i] + ctrl[i] = HDR2 + else: + in_rem[i] = inbuf[i] + 1 + ctrl[i] = PROC + elif c == HDR2: + if not full[i]: + continue + in_rem[i] = ((inbuf[i] << 8) | (in_rem[i] & 0xFF)) + 257 + ctrl[i] = PROC + full[i] = False + else: + st = p0[i] + if st < L: + if in_rem[i] > 0: + if full[i]: + st = (st << 8) | inbuf[i] + in_rem[i] -= 1 + full[i] = False + if in_rem[i] == 0 and flush[i]: + while st < L and st != 0 and vz[i] < bcpack.MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + elif flush[i]: + while st < L and st != 0 and vz[i] < bcpack.MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + else: + p1[i] = st + if out_rem[i] > 0: + ctrl[i] = HDR0 + else: + done[i] = True + continue + nxt = st > L and out_rem[i] > 0 + if nxt: + sym[i] = model[i].lookup(st & 0xFFFF) + out_rem[i] -= 1 + held[i] = nxt + p1[i] = st + if in_rem[i] == 0: + if flush[i]: + if st == L: + if out_rem[i] > 0: + ctrl[i] = HDR0 + p0[i] = 0 + p1[i] = 0 + else: + done[i] = True + elif out_rem[i] == 0 and not nxt: + done[i] = True + ready = True + anyfull = False + for i in range(nl): + if slotfull[i]: + anyfull = True + elif not (done[i] and not held[i]): + ready = False + break + if ready and anyfull: + for i in range(nl): + slotfull[i] = False + for i in range(nl): + if done[i] and held[i] and not slotfull[i]: + slotfull[i] = True + held[i] = False + raise AssertionError("interleave_lanes exceeded max_cycles") + + +def encode_lanes(lanes, codec, *, q=0): + """Encode per-lane symbol lists into a complete BCPack chunk.""" + widths = bcpack.LANE_WIDTHS[codec] + nsym = len(lanes[0]) + streams = [] + for i, (syms, dw) in enumerate(zip(lanes, widths)): + qi = q[i] if isinstance(q, (list, tuple)) else q + frag, _ = _encode_fragment(syms, dw, dw, qi, flush=True) + streams.append(frag) + return interleave_lanes(streams, widths, nsym) + + +def encode_bc1_blocks(blocks, *, ref_dists=None): + """Encode raw BC1 blocks (8 bytes each) into a valid codec-1 BCPack chunk.""" + n = len(blocks) // 8 + inv_quad = {v: i for i, v in enumerate(tables.BC1_QUADRANT)} + mods = (32, 64, 32, 32, 64, 32) + lanes = [[] for _ in range(12)] + hist = [] + for i in range(n): + c0, c1, r0, r1, r2, r3 = struct.unpack_from("> 11) & 31, (c0 >> 5) & 63, c0 & 31, + (c1 >> 11) & 31, (c1 >> 5) & 63, c1 & 31) + d = 0 if ref_dists is None else ref_dists[i] + if d == 0: + base = (0, 0, 0, 0, 0, 0) + elif i - d >= 0: + base = hist[i - d] + else: + entry = 256 + i - d + base = tables.BC1_HISTORY_CONFIRMED.get(entry) or tables.BC1_HISTORY_PROVISIONAL.get(entry) or (0, 0, 0, 0, 0, 0) + signed_d = d if d < 128 else d - 256 + lanes[0].append(_zig(signed_d)) + lanes[1].append(0) + for k in range(6): + delta = (e[k] - base[k]) % mods[k] + if delta >= mods[k] // 2: + delta -= mods[k] + lanes[2 + k].append(_zig(delta)) + hist.append(e) + qa = (r0 & 15) | ((r1 & 15) << 4) + qb = (r0 >> 4) | ((r1 >> 4) << 4) + qc = (r2 & 15) | ((r3 & 15) << 4) + qd = (r2 >> 4) | ((r3 >> 4) << 4) + lanes[8].append(inv_quad[qa]) + lanes[9].append(inv_quad[qb]) + lanes[10].append(inv_quad[qc]) + lanes[11].append(inv_quad[qd]) + return encode_lanes(lanes, 1) + + +# --- Unit tests ------------------------------------------------------------ + +class ProbTablesTest(unittest.TestCase): + def test_all_160_tables_valid_and_invertible(self): + self.assertEqual(len(tables.PROB_TABLES), 160) + for w in range(1, 11): + for q in range(16): + m = bcpack._get_model(w, q) + self.assertIsNotNone(m) + # Verify boundary symbols (0, 1, mid, max) invert cleanly. + for s in {0, 1, (1 << (w - 1)), (1 << w) - 1}: + p = s.bit_length() + f = m.freq[p] + c = m.base[p] + f * (s - (0 if p == 0 else 1 << (p - 1))) + if c == 0: + f, c = f - 1, 1 + x = (256 << 16) + c + self.assertEqual(m.lookup(x & 0xFFFF), s) + self.assertEqual(m.advance(s, x), 256 * f) + + +class EntropyLayerTest(unittest.TestCase): + def test_round_trip_12_and_16_lanes(self): + for codec in (1, 3, 4, 5, 6, 7): + widths = bcpack.LANE_WIDTHS[codec] + nsym = 24 + lanes = [[((i * 13 + j * 7) & ((1 << dw) - 1)) for j in range(nsym)] + for i, dw in enumerate(widths)] + qs = [(i * 3) % 15 for i in range(len(widths))] + raw = encode_lanes(lanes, codec, q=qs) + decoded, used = bcpack.decode_lanes(raw + b"\x00\x00\x00", codec, nsym * 8) + self.assertEqual(used, len(raw)) + self.assertEqual(decoded, lanes) + + def test_multi_fragment_flush_and_non_flush_and_3byte_header(self): + codec = 1 + widths = bcpack.LANE_WIDTHS[codec] + # 400 symbols forces a >256-byte fragment (3-byte header, h3=1) on 8-bit lanes. + nsym = 400 + lanes = [[((i * 29 + j * 17) & ((1 << dw) - 1)) for j in range(nsym)] + for i, dw in enumerate(widths)] + streams = [] + for i, (syms, dw) in enumerate(zip(lanes, widths)): + if i == 0: + # Two flush fragments with reduced width on the second half. + s1 = [x & 0x3F for x in syms[:100]] + s2 = [x & 0x1F for x in syms[100:]] + lanes[0] = s1 + s2 + streams.append(_encode_lane_stream([ + (s1, dw - 2, 2, True), + (s2, dw - 3, 5, True), + ], dw)) + elif i == 2: + # Chained non-flush -> flush fragments with a model change mid-stream. + streams.append(_encode_lane_stream([ + (syms[:150], dw, 1, False), + (syms[150:], dw, 4, True), + ], dw)) + else: + # Single large flush fragment (3-byte header on 8-bit lanes). + streams.append(_encode_lane_stream([(syms, dw, 0, True)], dw)) + raw = interleave_lanes(streams, widths, nsym) + decoded, used = bcpack.decode_lanes(raw, codec, nsym * 8) + self.assertEqual(used, len(raw)) + self.assertEqual(decoded, lanes) + + def test_rejects_corrupt_and_trailing_data(self): + lanes = [[0] * 8 for _ in range(12)] + raw = encode_lanes(lanes, 1) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw + b"\x01", 1, 64) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw[:-2], 1, 64) + flipped = bytearray(raw) + flipped[-1] ^= 0xFF + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(bytes(flipped), 1, 64) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw, 99, 64) + with self.assertRaises(bcpack.BcpackError): + bcpack.decode_lanes(raw, 1, 60) + + def test_unsupported_codec_rebuild_raises(self): + lanes = [[0] * 4 for _ in range(16)] + raw = encode_lanes(lanes, 7) + # Entropy layer succeeds for BC7... + dec, _ = bcpack.decode_lanes(raw, 7, 32) + self.assertEqual(dec, lanes) + # ...while block rebuild raises BcpackUnsupportedCodec in PR 1. + with self.assertRaises(bcpack.BcpackUnsupportedCodec): + bcpack.decode(raw, 7, 32) + + +class BlockRebuildTest(unittest.TestCase): + def test_bc1_confirmed_and_provisional_history(self): + # Block 0: d=0 (zero base); Block 1: dynamic ref to block 0 (d=1); + # Block 2: confirmed built-in preset 1 (256 + 2 - d == 1 => d=257? no, 256+2-255=3, use entry 255 -> d=3). + blocks = b"".join([ + struct.pack(" 256 + 2 - 3 = 255 (confirmed in BC1_HISTORY_CONFIRMED). + self.assertIn(255, tables.BC1_HISTORY_CONFIRMED) + raw = encode_bc1_blocks(blocks, ref_dists=[0, 1, 3]) + out, prov = bcpack.decode_with_info(raw, 1, len(blocks)) + self.assertEqual(out, blocks) + self.assertEqual(prov, set()) + + # Reference provisional entry 6 from block 0: 256 + 0 - d = 6 => d = 250. + self.assertIn(6, tables.BC1_HISTORY_PROVISIONAL) + raw_prov = encode_bc1_blocks(blocks[:8], ref_dists=[250]) + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(raw_prov, 1, 8) + out_p, prov_p = bcpack.decode_with_info(raw_prov, 1, 8, allow_provisional=True) + self.assertEqual(out_p, blocks[:8]) + self.assertEqual(prov_p, {"BC1 history 6"}) + + def test_bc4_round_trip(self): + inv_pair = {p: i for i, p in enumerate(tables.BC4_PAIR)} + # Build 2 BC4 blocks: block 0 uses d=0 (base 128,128), block 1 refs block 0 (d=1). + b0_bits = sum(((r + p) & 7) << (3 * (4 * r + p)) for r in range(4) for p in range(4)) + b1_bits = sum(((7 - r - p) & 7) << (3 * (4 * r + p)) for r in range(4) for p in range(4)) + expected = ( + bytes([130, 120]) + b0_bits.to_bytes(6, "little") + + bytes([140, 110]) + b1_bits.to_bytes(6, "little") + ) + lanes = [[] for _ in range(12)] + for i, (d, base, (a0, a1), bits) in enumerate([ + (0, (128, 128), (130, 120), b0_bits), + (1, (130, 120), (140, 110), b1_bits), + ]): + lanes[0].append(_zig(d)) + lanes[1].append(0) + lanes[2].append(_zig(a0 - base[0])) + lanes[3].append(_zig(a1 - base[1])) + for r in range(4): + row = (bits >> (12 * r)) & 0xFFF + lanes[4 + 2 * r].append(inv_pair[(row & 7, (row >> 3) & 7)]) + lanes[4 + 2 * r + 1].append(inv_pair[((row >> 6) & 7, (row >> 9) & 7)]) + raw = encode_lanes(lanes, 4) + self.assertEqual(bcpack.decode(raw, 4, len(expected)), expected) + + # Provisional BC4 history entry (entry 25 -> block 0 uses d = 231). + self.assertIn(25, tables.BC4_HISTORY_PROVISIONAL) + prov_a0, prov_a1 = tables.BC4_HISTORY_PROVISIONAL[25] + lanes_p = [[_zig(231 - 256)], [0], [0], [0]] + [[0]] * 8 + raw_p = encode_lanes(lanes_p, 4) + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(raw_p, 4, 8) + out_p, info_p = bcpack.decode_with_info(raw_p, 4, 8, allow_provisional=True) + self.assertEqual((out_p[0], out_p[1]), (prov_a0, prov_a1)) + self.assertEqual(info_p, {"BC4 history 25"}) + + def test_bc5_round_trip(self): + inv_pair = {p: i for i, p in enumerate(tables.BC5_PAIR)} + # Block 0 uses confirmed BC5 entry if present, plus block 1 dynamic ref. + confirmed_entry = next(iter(sorted(tables.BC5_HISTORY_CONFIRMED))) + base0 = tables.BC5_HISTORY_CONFIRMED[confirmed_entry] + d0 = 256 - confirmed_entry # block 0: 256 + 0 - d0 == confirmed_entry + e0 = ((base0[0] + 2) & 255, (base0[1] - 3) & 255, (base0[2] + 1) & 255, (base0[3] - 1) & 255) + e1 = ((e0[0] + 5) & 255, (e0[1] - 4) & 255, (e0[2] + 3) & 255, (e0[3] + 2) & 255) + bits = [ + (0x0123456789AB, 0xFEDCBA987654), + (0x112233445566, 0x778899AABBCC), + ] + expected = bytearray() + for e, (br, bg) in zip((e0, e1), bits): + expected += bytes([e[0], e[1]]) + br.to_bytes(6, "little") + expected += bytes([e[2], e[3]]) + bg.to_bytes(6, "little") + lanes = [[] for _ in range(12)] + for d, base, e, (br, bg) in ((d0, base0, e0, bits[0]), (1, e0, e1, bits[1])): + sd = d if d < 128 else d - 256 + da, db = _deint4(_zig(sd)) + lanes[0].extend([da, db]) + lanes[1].extend([0, 0]) + for lane_idx, (c_a, c_b, b_a, b_b) in ((2, (e[0], e[1], base[0], base[1])), + (3, (e[2], e[3], base[2], base[3]))): + d_a = (c_a - b_a + 128) % 256 - 128 + d_b = (c_b - b_b + 128) % 256 - 128 + lanes[lane_idx].extend([_zig(d_a), _zig(d_b)]) + for ch, bval in enumerate((br, bg)): + for r in range(4): + row = (bval >> (12 * r)) & 0xFFF + lanes[4 + 4 * ch + r].extend([ + inv_pair[(row & 7, (row >> 3) & 7)], + inv_pair[((row >> 6) & 7, (row >> 9) & 7)], + ]) + raw = encode_lanes(lanes, 5) + out, prov = bcpack.decode_with_info(raw, 5, len(expected)) + self.assertEqual(out, bytes(expected)) + self.assertEqual(prov, set()) + + def test_bc3_round_trip(self): + inv_pair = {p: i for i, p in enumerate(tables.BC3_ALPHA_PAIR)} + inv_quad = {v: i for i, v in enumerate(tables.BC3_COLOUR_QUADRANT)} + # Block 0 with d=0: base is (128, 128, 0, 0, 0, 0, 0, 0). + a0, a1 = 135, 120 + abits = 0x0123456789AB + c0 = (5 << 11) | (10 << 5) | 3 + c1 = (2 << 11) | (6 << 5) | 1 + r0, r1, r2, r3 = 0x12, 0x34, 0x56, 0x78 + expected = bytes([a0, a1]) + abits.to_bytes(6, "little") + struct.pack("> (12 * r)) & 0xFFF + lanes[3 + r].extend([ + inv_pair[(row & 7, (row >> 3) & 7)], + inv_pair[((row >> 6) & 7, (row >> 9) & 7)], + ]) + lanes[7].extend([_zig(5), _zig(2)]) + lanes[8].extend([_zig(10), _zig(6)]) + lanes[9].extend([_zig(3), _zig(1)]) + qa = (r0 & 15) | ((r1 & 15) << 4) + qb = (r0 >> 4) | ((r1 >> 4) << 4) + qc = (r2 & 15) | ((r3 & 15) << 4) + qd = (r2 >> 4) | ((r3 >> 4) << 4) + lanes[10].extend([inv_quad[qa], inv_quad[qb]]) + lanes[11].extend([inv_quad[qc], inv_quad[qd]]) + raw = encode_lanes(lanes, 3) + out, prov = bcpack.decode_with_info(raw, 3, len(expected)) + self.assertEqual(out, expected) + self.assertEqual(prov, set()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_bink_index.py b/tests/test_bink_index.py index 20f7ca146..7e2514ee4 100644 --- a/tests/test_bink_index.py +++ b/tests/test_bink_index.py @@ -2,8 +2,10 @@ python -I tests/test_bink_index.py """ +import contextlib import csv import importlib.util +import io import json import os import struct @@ -116,5 +118,36 @@ class TestScanAndWrite(unittest.TestCase): self.assertNotIn("decodes", doc["streams"][0]) +class TestCommandLine(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.path = os.path.join(self.tmp.name, "one.bk2") + with open(self.path, "wb") as fh: + fh.write(make_stream(frames=7)) + + def tearDown(self): + self.tmp.cleanup() + + def test_csv_on_stdout_has_one_line_end_per_row(self): + # A text stream that writes "\n" as "\r\n", as Windows' stdout does, on any platform. + raw = io.BytesIO() + out = io.TextIOWrapper(raw, encoding="utf-8", newline="\r\n") + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(bink.main([self.path]), 0) + out.flush() + data = raw.getvalue() + self.assertNotIn(b"\r\r\n", data) + rows = list(csv.reader(io.StringIO(data.decode("utf-8"), newline=""))) + self.assertEqual(len(rows), 2) # header and the one stream, no blank rows + self.assertEqual(rows[0][:len(bink.BASE_FIELDS)], bink.BASE_FIELDS) + + def test_missing_target_is_an_error_not_a_traceback(self): + missing = os.path.join(self.tmp.name, "nonexistent.bk2") + err = io.StringIO() + with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(bink.main([missing]), 2) + self.assertIn("no such file or directory", err.getvalue()) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_bvh_index.py b/tests/test_bvh_index.py index c2fcd63af..099423f74 100644 --- a/tests/test_bvh_index.py +++ b/tests/test_bvh_index.py @@ -25,10 +25,15 @@ def bvh_payload(n=10, tag=bvh_index.TAG, end_delta=0): end = 0x140 + n * 64 + end_delta struct.pack_into("> 8 + self.assertEqual(self.vgpr(r, 4), 0x223344AA) # {v0, v1} >> 24 + self.assertEqual(self.vgpr(r, 5), 0xAABBCCDD) # a zero shift keeps src1 + self.assertEqual(self.vgpr(r, 6), 0x000044DD) # bytes 0, 4; sign 0; zero + self.assertEqual(self.vgpr(r, 7), 0xFFFFDDDD) # byte 0, sign of src1 half, 0xff + + def test_mul_hi_and_mad(self): + r = self.execute(""" + v_mul_hi_u32 v0, 0xffffffff, 0xffffffff + v_mul_hi_i32 v1, 0xffffffff, 1 + v_mul_hi_i32 v2, 0x40000000, 0x40000000 + v_mul_hi_i32 v3, 0x80000000, 0x40000000 + v_mad_u32_u24 v4, 0xffffff, 0xffffff, 5 + v_mad_i32_i24 v5, 0xffffff, 0xffffff, 5 + v_mad_i32_i24 v6, 0x800000, 0x800000, 1 + s_endpgm + """) + self.assertEqual(self.vgpr(r, 0), 0xFFFFFFFE) + self.assertEqual(self.vgpr(r, 1), 0xFFFFFFFF) + self.assertEqual(self.vgpr(r, 2), 0x10000000) + self.assertEqual(self.vgpr(r, 3), 0xE0000000) + self.assertEqual(self.vgpr(r, 4), 0xFE000006) # 0xffffff**2 + 5, low 32 bits + self.assertEqual(self.vgpr(r, 5), 6) + self.assertEqual(self.vgpr(r, 6), 1) # 2**46 + 1, low 32 bits + def test_mov_inline_constants_and_literals(self): r = self.execute(""" v_mov_b32 v0, 1.0 diff --git a/tests/test_gamedata_graph.py b/tests/test_gamedata_graph.py new file mode 100644 index 000000000..650976550 --- /dev/null +++ b/tests/test_gamedata_graph.py @@ -0,0 +1,271 @@ +"""gamedata_graph.py must measure a synthetic content-set graph without game data. + + python -I tests/test_gamedata_graph.py + +The fixtures are hand-written manifests: two change-set documents that include each other, one +content definition that includes the first, a missing set id, all four documented prefix rules, an +unknown ``common:/`` scheme, two parent locators, a tail-only document and a malformed document. +No game data is used. +""" +import json +import os +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOL = os.path.join(ROOT, "tools", "gamedata_graph.py") +TOOLS = os.path.join(ROOT, "tools") +if TOOLS not in sys.path: + sys.path.insert(0, TOOLS) +import gamedata_graph as gg # noqa: E402 + +ALPHA = ( + b'\n' + b'\n' + b' set.alpha\n' + b' \n' + b' $(common)/fixture/a.bk2\n' + b' platform:/levels/fixture/a.rpf\n' + b' $(target)/fixture/a\n' + b' common:/FIXTURE/A.XML\n' + b' \n' + b' set.betamissing.set\n' + b'' +) +BETA = ( + b'\n' + b' set.beta\n' + b' platform:/data/fixture\n' + b' set.alpha\n' + b'' +) +GAMMA = ( + b'\n' + b'\n' + b' \n' + b' set.gamma' + b'$(common)/fixture/g.xml' + b'\n' + b' \n' + b' set.alpha\n' + b' $(root)/fixture/g.meta' + b'\n' + b'' +) +DELTA = ( + b'' +) +PLAIN = b'' +TAIL = b'\n' +BAD = b'' + + +class GamedataGraphTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = self.tmp.name + self.carve = os.path.join(self.root, "carve") + os.makedirs(self.carve) + self.rows = [] + self.next_off = 0x1000 + + def tearDown(self): + self.tmp.cleanup() + + def add(self, payload, parts=None): + parts = parts if parts is not None else [payload] + for part in parts: + offset = self.next_off + self.next_off += 0x1000 + with open(os.path.join(self.carve, f"{offset:012x}.bin"), "wb") as f: + f.write(part) + self.rows.append({ + "off": offset, + "stored": len(part), + "size": len(part), + "head": part[:16].hex(), + "pre": "", + }) + + def finish(self): + with open(os.path.join(self.carve, "index.json"), "w", encoding="utf-8") as f: + json.dump({"summary": {"archive": "synthetic", "files": len(self.rows)}, "files": self.rows}, f) + + def run_tool(self, *args): + return subprocess.run([sys.executable, "-I", TOOL, *args], cwd=self.root, + capture_output=True, text=True, encoding="utf-8", errors="replace") + + def test_carve_graph_counts_cycles_reachability_and_no_leak(self): + self.add(ALPHA) + self.add(BETA) + split = GAMMA.index(b"") + self.add(GAMMA, [GAMMA[:split], GAMMA[split:]]) + self.add(DELTA) + self.add(PLAIN) + self.add(TAIL) + self.add(BAD) + self.finish() + + out = os.path.join(self.root, "graph.json") + p = self.run_tool(self.carve, "--json", out) + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + with open(out, encoding="utf-8") as f: + data = json.load(f) + s = data["summary"] + + self.assertEqual(s["mode"], "carve") + self.assertEqual(s["payloads"], 7) + self.assertEqual(s["documents"], 6) + self.assertEqual(s["parsed"], 5) + self.assertEqual(s["unparsed"], 2) + self.assertEqual(s["root_count"], 6) + self.assertEqual(s["rootless"], 0) + self.assertEqual(s["manifest_documents"], 3) + self.assertEqual(s["content_sets"], 4) + self.assertEqual(s["defined_content_sets"], 3) + self.assertEqual(s["dangling_content_sets"], 1) + self.assertEqual(s["duplicate_set_ids"], 0) + self.assertEqual(s["reference_sites"], 13) + self.assertEqual(s["target_sites"], 9) + self.assertEqual(s["include_sites"], 4) + self.assertEqual(s["references"], { + "filename": 6, "includedSets": 4, "loadPath": 1, "parentFile": 1, "parentPath": 1, + }) + self.assertEqual(s["prefixes"], { + "$(common)": 2, "$(root)": 1, "$(target)": 1, "common:/": 1, + "platform:/levels": 1, "platform:/other": 1, "relative/locator": 2, + }) + self.assertEqual(s["resolution"], { + "document": 3, "document_unmapped": 6, "include_id_missing": 1, + "relative_locator": 2, "unrecognized_prefix": 1, + }) + self.assertEqual(s["unique"], { + "targets": 9, + "targets_by_namespace": { + "$(common)": 2, "$(root)": 1, "$(target)": 1, "common:/": 1, + "platform:/levels": 1, "platform:/other": 1, "relative/locator": 2, + }, + "document_unmapped": 6, + "unknown_macro": 0, + "unrecognized_prefix": 1, + "relative_locator": 2, + "content_set_ids": 4, + "include_ids": 3, + }) + self.assertEqual(s["nodes"], {"documents": 7, "content_sets": 4, "targets": 9, "total": 20}) + self.assertEqual(s["edges"], { + "total": 16, "defines": 3, "includes": 4, "contains_file": 6, + "loads_changeset": 1, "parent_path": 1, "parent_file": 1, + "document_edges": 7, "target_edges": 9, + }) + self.assertEqual(s["content_graph"], { + "include_edges": 3, + "documents_with_incoming_includes": 2, + "documents_with_outgoing_includes": 3, + "root_documents": 1, + "root_fallback": False, + "reachable_documents": 3, + "max_depth": 2, + "cycles": 1, + "cycle_nodes": 2, + }) + self.assertEqual(s["reachable"], { + "documents": 3, "content_sets": 4, "targets": 7, "target_sites": 7, + }) + + mount = s["categories"]["mount / content manifests"] + self.assertEqual(mount["documents"], 3) + self.assertEqual(mount["manifest_documents"], 3) + self.assertEqual(mount["content_sets"], 3) + self.assertEqual(mount["include_references"], 4) + self.assertEqual(mount["target_references"], 7) + self.assertEqual(mount["references"], 11) + self.assertEqual(mount["roots"], 2) + unknown = s["categories"]["uncatalogued"] + self.assertEqual(unknown["documents"], 4) + self.assertEqual(unknown["target_references"], 2) + self.assertEqual(unknown["references"], 2) + self.assertEqual(unknown["roots"], 4) + + change_set = s["roots"]["CDataFileMgr__ContentChangeSetDef"] + self.assertEqual(change_set["documents"], 2) + self.assertEqual(change_set["content_sets"], 2) + self.assertEqual(change_set["include_references"], 3) + self.assertEqual(change_set["target_references"], 5) + self.assertEqual(change_set["references"], 8) + self.assertEqual(change_set["manifest_documents"], 2) + content_def = s["roots"]["CDataFileMgr__ContentDef"] + self.assertEqual(content_def["documents"], 1) + self.assertEqual(content_def["content_sets"], 1) + self.assertEqual(content_def["include_references"], 1) + self.assertEqual(content_def["target_references"], 2) + self.assertEqual(content_def["references"], 3) + + self.assertEqual(data["unresolved"], { + "document_unmapped": { + "$(common)": 2, "$(root)": 1, "$(target)": 1, + "platform:/levels": 1, "platform:/other": 1, + }, + "unknown_macro": {}, + "unrecognized_prefix": {"common:/": 1}, + "relative_locator": 2, + "include_id_missing": 1, + "total_sites": 10, + }) + + # Values, ids, locators and per-file names must not leak into the aggregate output. + with open(out, encoding="utf-8") as f: + blob = f.read() + for value in ("a.bk2", "fixture/a.rpf", "FIXTURE/A.XML", "set.alpha", "set.beta", + "missing.set", "../Item", "parent.dat", "fixture/g.meta", + "alpha.xml", "g.xml"): + self.assertNotIn(value, blob) + + def test_file_mode_keeps_manifest_documents_and_missing_ids(self): + alpha = os.path.join(self.root, "alpha.xml") + gamma = os.path.join(self.root, "gamma.xml") + delta = os.path.join(self.root, "delta.xml") + for path, payload in ((alpha, ALPHA), (gamma, GAMMA), (delta, DELTA)): + with open(path, "wb") as f: + f.write(payload) + + out = os.path.join(self.root, "files.json") + p = self.run_tool(alpha, gamma, delta, "--json", out) + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + with open(out, encoding="utf-8") as f: + data = json.load(f) + s = data["summary"] + self.assertEqual(s["mode"], "files") + self.assertEqual(s["payloads"], 3) + self.assertEqual(s["parsed"], 3) + self.assertEqual(s["manifest_documents"], 2) + self.assertEqual(s["content_sets"], 4) # alpha, beta, gamma and the second missing id + self.assertEqual(s["defined_content_sets"], 2) + self.assertEqual(s["dangling_content_sets"], 2) + self.assertEqual(s["resolution"]["document"], 1) + self.assertEqual(s["resolution"]["include_id_missing"], 2) + self.assertEqual(s["content_graph"]["include_edges"], 1) + self.assertEqual(s["content_graph"]["reachable_documents"], 2) + self.assertEqual(s["content_graph"]["cycles"], 0) + + def test_prefix_classification_keeps_unknown_schemes_unresolved(self): + self.assertEqual(gg.classify_target("$(common)/fixture/a.bk2"), + ("$(common)", "fixture/a.bk2", "document_unmapped")) + self.assertEqual(gg.classify_target("$(root)/fixture/x.meta"), + ("$(root)", "fixture/x.meta", "document_unmapped")) + self.assertEqual(gg.classify_target("platform:/levels/fixture/a.rpf"), + ("platform:/levels", "levels/fixture/a.rpf", "document_unmapped")) + self.assertEqual(gg.classify_target("platform:/data/fixture"), + ("platform:/other", "data/fixture", "document_unmapped")) + self.assertEqual(gg.classify_target("common:/FIXTURE/A.XML"), + ("common:/", "FIXTURE/A.XML", "unrecognized_prefix")) + self.assertEqual(gg.classify_target("$(future)/a"), + ("$(future)", "a", "unknown_macro")) + self.assertEqual(gg.classify_target("../Item[@key='X']"), + ("relative/locator", "../Item[@key='X']", "relative_locator")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gpu_build_dir.py b/tests/test_gpu_build_dir.py new file mode 100644 index 000000000..5e124f5e2 --- /dev/null +++ b/tests/test_gpu_build_dir.py @@ -0,0 +1,76 @@ +"""run_gpu_tests.py finds the test programs where the CMake generator put them: in the build folder (Makefiles, +Ninja) or in build/ (Visual Studio generator, TEST-38). Fake files only, so this runs on any OS.""" +from pathlib import Path +import os +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) +sys.path.insert(0, str(ROOT / "scripts")) +import run_gpu_tests + +PROGRAMS = ("vk_compute_test.exe", "vk_store_test.exe", "vk_harness.exe") + + +def touch(folder: Path, names=PROGRAMS, mtime=None): + folder.mkdir(parents=True, exist_ok=True) + for n in names: + f = folder / n + f.write_bytes(b"") + if mtime is not None: + os.utime(f, (mtime, mtime)) + + +class ResolveBuildDir(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.build = Path(tmp.name) / "build" + self.build.mkdir() + + def resolve(self): + return run_gpu_tests.resolve_build_dir(str(self.build), PROGRAMS) + + def test_programs_directly_in_the_build_folder(self): + touch(self.build) + self.assertEqual(self.resolve(), str(self.build)) + + def test_visual_studio_generator_subfolder(self): + touch(self.build / "RelWithDebInfo") + self.assertEqual(self.resolve(), str(self.build / "RelWithDebInfo")) + + def test_release_subfolder(self): + touch(self.build / "Release") + self.assertEqual(self.resolve(), str(self.build / "Release")) + + def test_build_folder_wins_over_a_subfolder(self): + touch(self.build) + touch(self.build / "Release") + self.assertEqual(self.resolve(), str(self.build)) + + def test_most_recently_built_configuration_wins(self): + touch(self.build / "Debug", mtime=1_000_000) + touch(self.build / "Release", mtime=3_000_000) + touch(self.build / "RelWithDebInfo", mtime=2_000_000) + self.assertEqual(self.resolve(), str(self.build / "Release")) + + def test_a_configuration_missing_a_program_is_skipped(self): + touch(self.build / "Release", names=PROGRAMS[:2], mtime=9_000_000) # newer but incomplete + touch(self.build / "Debug", mtime=1_000_000) + self.assertEqual(self.resolve(), str(self.build / "Debug")) + + def test_nothing_found_returns_the_folder_given(self): + # so the "Test programs not found in " message names what the user passed + self.assertEqual(self.resolve(), str(self.build)) + touch(self.build / "Release", names=PROGRAMS[:1]) + self.assertEqual(self.resolve(), str(self.build)) + + def test_unknown_configuration_folder_is_not_searched(self): + touch(self.build / "Custom") + self.assertEqual(self.resolve(), str(self.build)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py index cae2837ee..70ee3913f 100644 --- a/tests/test_pe_inspect.py +++ b/tests/test_pe_inspect.py @@ -283,5 +283,69 @@ class PeInspectTest(unittest.TestCase): self.assertIn("not a PE image", err.getvalue()) +class TruncatedImageTest(unittest.TestCase): + """A file cut off inside a header or table is a bad image, not a struct.error that stops the run.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = self.tmp.name + + def write(self, name: str, data: bytes) -> str: + path = os.path.join(self.dir, name) + with open(path, "wb") as f: + f.write(data) + return path + + def cut_inside(self, full: bytes, index: int, into: int) -> bytes: + """The image cut `into` bytes after the start of data directory `index`.""" + rva, _size = pe_inspect.PeImage(full).directory(index) + return full[:pe_inspect.PeImage(full).offset(rva) + into] + + def test_each_table_cut_short_is_a_pe_format_error(self): + for is64 in (True, False): + full = build_image(is64=is64) + cases = { + "optional header": full[:0x58 + 2 + 16], # magic present, AddressOfEntryPoint cut off + "export directory": self.cut_inside(full, pe_inspect.DIR_EXPORT, 10), + "tls directory": self.cut_inside(full, pe_inspect.DIR_TLS, 20 if is64 else 10), + } + for what, data in cases.items(): + with self.subTest(is64=is64, cut=what): + path = self.write("cut.dll", data) + with self.assertRaises(pe_inspect.PeFormatError): + pe_inspect.inspect(path, None) + + def test_every_cut_length_gives_a_report_or_a_pe_format_error(self): + for is64 in (True, False): + full = build_image(is64=is64) + for n in range(0, len(full), 16): + with self.subTest(is64=is64, length=n): + path = self.write("sweep.dll", full[:n]) + try: + pe_inspect.inspect(path, None) + except pe_inspect.PeFormatError: + pass + + def test_cli_reports_a_truncated_file_and_keeps_going(self): + cut = self.write("cut.dll", build_image()[:0x58 + 2 + 16]) + good = self.write("good.dll", build_image()) + out = os.path.join(self.dir, "reports") + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + self.assertEqual(pe_inspect.main([cut, good, "--out", out]), 1) + self.assertIn("cut.dll: not a PE image (truncated optional header)", err.getvalue()) + self.assertEqual(sorted(os.listdir(out)), ["good.json", "good.md"]) + + def test_export_counts_past_the_table_cap_do_not_run_away(self): + full = bytearray(build_image()) + img = pe_inspect.PeImage(bytes(full)) + at = img.offset(img.directory(pe_inspect.DIR_EXPORT)[0]) + struct.pack_into("= 0 && worldEnd > worldBegin, 'viewer world description section must exist'); +const worldSource = html.slice(worldBegin, worldEnd); + +function loadWorld(fetch, search = '') { + return vm.runInNewContext(worldSource + '\nloadWorld()', { fetch, location: { search }, URLSearchParams }); +} + +function manifestResponse(manifest) { + return async () => ({ ok: true, json: async () => manifest }); +} + +const worldChunk = { id: 'cell', url: 'world/chunks/cell.glb', bounds: [-1, -2, -3, 1, 2, 3] }; + +test('a valid manifest is used, including an intentionally empty world', async () => { + for (const chunks of [[worldChunk], []]) { + const world = await loadWorld(manifestResponse({ spawn: [1, 2, 3], chunks })); + assert.equal(world.test, false); + assert.equal(world.spawn.join(','), '1,2,3'); + assert.deepEqual(world.chunks, chunks); + } +}); + +test('malformed manifests keep the viewer usable and identify the invalid field', async t => { + const cases = [ + ['missing spawn', {}, /spawn/], + ['non-finite spawn', { spawn: [0, Infinity, 0], chunks: [] }, /spawn/], + ['invalid chunks array', { spawn: [0, 0, 0], chunks: {} }, /chunks/], + ['missing chunk', { spawn: [0, 0, 0], chunks: [null] }, /chunks\[0\]\.id/], + ['missing URL', { spawn: [0, 0, 0], chunks: [{ ...worldChunk, url: '' }] }, /chunks\[0\]\.url/], + ['bad bounds', { spawn: [0, 0, 0], chunks: [{ ...worldChunk, bounds: [0, 0, 0, -1, 1, 1] }] }, + /chunks\[0\]\.bounds/], + ['duplicate chunk ID', { spawn: [0, 0, 0], chunks: [worldChunk, worldChunk] }, /chunks\[1\]\.id/], + ]; + for (const [label, manifest, field] of cases) { + await t.test(label, async () => { + const world = await loadWorld(manifestResponse(manifest)); + assert.equal(world.test, true); + assert.ok(world.chunks.length > 0); + assert.match(world.reason, field); + }); + } +}); + +test('test mode, a missing manifest, and an unreadable manifest have distinct messages', async () => { + const explicit = await loadWorld(async () => assert.fail('test mode must not fetch'), '?test'); + const missing = await loadWorld(async () => ({ ok: false, status: 404 })); + const invalid = await loadWorld(async () => ({ ok: true, json: async () => { throw new SyntaxError(); } })); + const unreachable = await loadWorld(async () => { throw new TypeError(); }); + for (const world of [explicit, missing, invalid, unreachable]) assert.equal(world.test, true); + assert.match(explicit.reason, /requested/); + assert.match(missing.reason, /not found/); + assert.match(invalid.reason, /valid JSON/); + assert.match(unreachable.reason, /could not be loaded/); +}); + const begin = html.indexOf('// ---------- chunk streaming ----------'); const end = html.indexOf('// ---------- main loop ----------', begin); assert(begin >= 0 && end > begin, 'viewer streaming section must exist'); diff --git a/tests/test_world_census.py b/tests/test_world_census.py index 23fa5eb23..0c6d79d5e 100644 --- a/tests/test_world_census.py +++ b/tests/test_world_census.py @@ -6,6 +6,8 @@ import importlib.util import json import os import struct +import subprocess +import sys import tempfile import unittest import zlib @@ -102,5 +104,45 @@ class WorldCensusTest(unittest.TestCase): self.assertGreater(WC.required_len(blob[:0x150]), 0x150) +class CensusArgumentTest(unittest.TestCase): + """--shard-size 0 planned shards forever (memory grew without bound); --jobs 0 crashed in ProcessPoolExecutor.""" + + def test_expected_shards_rejects_a_size_below_one(self): + self.assertEqual(WC._expected_shards(0, 10, 4), + [{"index": 0, "start": 0, "end": 4}, {"index": 1, "start": 4, "end": 8}, + {"index": 2, "start": 8, "end": 10}]) + + class Counted(int): + """Counts pos + shard_size, so a missing guard fails here instead of looping forever.""" + adds = 0 + + def __radd__(self, other): + Counted.adds += 1 + if Counted.adds > 1000: + raise RuntimeError("shard planning never finished") + return other + int(self) + + for size in (0, -5): + Counted.adds = 0 + with self.subTest(size=size), self.assertRaises(ValueError): + WC._expected_shards(0, 10, Counted(size)) + + def test_cli_rejects_shard_size_and_jobs_below_one(self): + with tempfile.TemporaryDirectory() as tmp: + arc = os.path.join(tmp, "sample.rpf") + make_archive(arc) + out = os.path.join(tmp, "out") + tool = os.path.join(ROOT, "tools", "world_census.py") + for flag, value in (("--shard-size", "0"), ("--shard-size", "-1"), ("--jobs", "0")): + with self.subTest(flag=flag, value=value): + # A subprocess with a timeout, so the old endless loop fails the test instead of hanging it. + p = subprocess.run([sys.executable, "-I", tool, arc, "--out", out, flag, value], + capture_output=True, text=True, timeout=10) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn("must be at least 1", p.stderr) + self.assertNotIn("Traceback", p.stderr) + self.assertFalse(os.path.exists(out)) + + if __name__ == "__main__": unittest.main() diff --git a/tools/anim_index.py b/tools/anim_index.py index cc519248d..c0a90f62e 100644 --- a/tools/anim_index.py +++ b/tools/anim_index.py @@ -447,12 +447,34 @@ def write_output(path, rows, summary): for i, c in enumerate(COLUMNS)]) +def offset(text): + """--start: 0 or more, decimal or 0x hex.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be 0 or more") from None + if value < 0: + raise argparse.ArgumentTypeError("must be 0 or more") + return value + + +def byte_count(text): + """--limit: at least 1; 0 used to mean no limit and a negative value silently scanned less.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be at least 1") from None + if value < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return value + + def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("source", help="an .rpf archive or a directory of carved .bin files") ap.add_argument("out", help="output path ending in .csv or .json") - ap.add_argument("--start", type=lambda s: int(s, 0), help="first byte to scan (default: the RPF data start)") - ap.add_argument("--limit", type=lambda s: int(s, 0), help="number of bytes to scan") + ap.add_argument("--start", type=offset, help="first byte to scan (default: the RPF data start)") + ap.add_argument("--limit", type=byte_count, help="number of bytes to scan") ap.add_argument("--rigs", metavar="PATH", help="write parsed RBF0 rig-set/rig and SKEL_ JSON here") ap.add_argument("--quiet", action="store_true") a = ap.parse_args() diff --git a/tools/bcpack.py b/tools/bcpack.py new file mode 100644 index 000000000..588ea41ac --- /dev/null +++ b/tools/bcpack.py @@ -0,0 +1,617 @@ +"""Clean-room BCPack bitstream decoder (Python standard library only). + +Implements the Xbox Series DirectStorage BCPack entropy layer (interleaved +12/16-lane 16-bit rANS with 8-byte/cycle prefetch scheduling and exponential +frequency tables) for all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7) and +block rebuilders for BC1, BC3, BC4 and BC5 (codecs 1, 3, 4 and 5). + +Codec identifiers follow `DSTORAGE_BCPACK_MODE` (matching `tools/ttpf_mips.py` +and `docs/textures.md`): + 1 = BC1, 3 = BC3, 4 = BC4, 5 = BC5, 6 = BC6H, 7 = BC7. + +Strict decoding (`decode(..., allow_provisional=False)`, the default) refuses +any chunk that depends on an unconfirmed built-in history entry. Pass +`allow_provisional=True` (or use `decode_with_info`) to allow provisional +entries and inspect which ones were used. + +See `docs/textures.md` for the bitstream specification and provenance. +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bcpack_tables as _tables # noqa: E402 + +# rANS and lane-array constants +RANS_L = 1 << 24 +MAX_WIDTH = 10 +PREFETCH_BUDGET = 8 +MAX_VIRTUAL_ZEROS = 8 + +CODEC_NAMES = { + 1: "BC1", + 3: "BC3", + 4: "BC4", + 5: "BC5", + 6: "BC6H", + 7: "BC7", +} + +# Bytes represented by one lane symbol-tuple (BC3/BC5/BC6H/BC7 use 2 elements per 16-byte block). +ELEMENT_BYTES = 8 + +BLOCK_BYTES = { + 1: 8, + 3: 16, + 4: 8, + 5: 16, + 6: 16, + 7: 16, +} + +# Default per-lane symbol widths (bits) for each DSTORAGE_BCPACK_MODE. +LANE_WIDTHS = { + 1: (8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8), + 3: (4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8), + 4: (8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), + 5: (4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), + 6: (4, 4, 8, 8, 8, 5, 5, 5, 6, 6, 6, 8, 8, 8, 8, 5), + 7: (4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5), +} + +ALL_CODECS = frozenset(CODEC_NAMES) +SUPPORTED_REBUILD_CODECS = frozenset({1, 3, 4, 5}) + + +class BcpackError(ValueError): + """Raised when a BCPack stream fails structural or rANS validation.""" + + +class BcpackProvisionalError(BcpackError): + """Raised when strict decoding encounters an unconfirmed or unknown history entry.""" + + +class BcpackUnsupportedCodec(NotImplementedError): + """Raised when a BCPack codec has no block rebuilder yet.""" + + +class _Model: + """16-bit rANS banded frequency model for one (symbol_width, q) pair.""" + + __slots__ = ("w", "freq", "base") + + def __init__(self, w, freq): + self.w = w + self.freq = freq + base = [] + acc = 0 + for p, f in enumerate(freq): + base.append(acc) + acc += f * (1 if p == 0 else 1 << (p - 1)) + if acc != 65536: + raise BcpackError(f"probability table ({w}) does not sum to 65536 (got {acc})") + self.base = tuple(base) + + def lookup(self, cf): + p = self.w + base = self.base + while p > 0 and cf < base[p]: + p -= 1 + return 0 if p == 0 else (1 << (p - 1)) + (cf - base[p]) // self.freq[p] + + def advance(self, s, x): + p = s.bit_length() + f = self.freq[p] + c = self.base[p] + f * (s - (0 if p == 0 else 1 << (p - 1))) + if c == 0: + f, c = f - 1, 1 + return f * (x >> 16) + (x & 0xFFFF) - c + + +_MODEL_CACHE = {} + + +def _get_model(w, q): + key = (w, q) + m = _MODEL_CACHE.get(key) + if m is None: + freq = _tables.PROB_TABLES.get(key) + if freq is None: + return None + m = _Model(w, freq) + _MODEL_CACHE[key] = m + return m + + +def _decode_lanes_raw(raw, widths, nsym): + """Decode the interleaved rANS lane array into one symbol list per lane. + + Returns `(lanes, bytes_used)`. Raises `BcpackError` if any fragment fails + to land at the exact rANS lower bound `RANS_L`, runs out of input, or + produces an out-of-range symbol. + """ + nl = len(widths) + HDR0, HDR1, HDR2, PROC = 0, 1, 2, 3 + L = RANS_L + ctrl = [HDR0] * nl + out_rem = [nsym] * nl + w = [0] * nl + q = [0] * nl + h3 = [0] * nl + flush = [0] * nl + done = [nsym <= 0] * nl + full = [False] * nl + held = [False] * nl + vz = [0] * nl + inbuf = [0] * nl + sym = [0] * nl + in_rem = [0] * nl + p0 = [0] * nl + p1 = [0] * nl + model = [None] * nl + slotfull = [False] * nl + slotval = [0] * nl + stall = [False] * nl + out = [[] for _ in range(nl)] + pos = 0 + nraw = len(raw) + + def fail(msg, lane): + raise BcpackError( + f"lane {lane} (width {w[lane]}, q {q[lane]}) at input byte {pos}: {msg}" + ) + + while True: + if all(done[i] and not slotfull[i] for i in range(nl)): + return out, pos + + # Phase 1: state update, prefetch arbitration (at most 8 bytes/cycle), + # and symbol release for non-stalled lanes. + left = PREFETCH_BUDGET + for i in range(nl): + if done[i]: + stall[i] = True + continue + if held[i] and slotfull[i]: + stall[i] = True + continue + stall[i] = False + if ctrl[i] == PROC: + p0[i] = model[i].advance(sym[i], p1[i]) if held[i] else p1[i] + if not full[i] and (ctrl[i] != PROC or in_rem[i] > 0): + if left == 0: + stall[i] = True + continue + if pos >= nraw: + fail("input ran out", i) + inbuf[i] = raw[pos] + pos += 1 + full[i] = True + left -= 1 + if held[i]: + slotfull[i] = True + slotval[i] = sym[i] + held[i] = False + + # Phase 2: header parsing, byte merge, virtual zero fill on flush, and symbol lookup. + for i in range(nl): + if done[i] or stall[i]: + continue + c = ctrl[i] + if c == HDR0: + if not full[i]: + continue + h = inbuf[i] + q[i] = h & 15 + flush[i] = (h >> 4) & 1 + h3[i] = (h >> 5) & 1 + w[i] = widths[i] - (h >> 6) + full[i] = False + ctrl[i] = HDR1 + vz[i] = 0 + elif c == HDR1: + if not full[i]: + continue + full[i] = False + wi = w[i] + if not 1 <= wi <= MAX_WIDTH: + fail("symbol width out of range", i) + m = _get_model(wi, q[i]) + if m is None: + fail("probability table for this width and q is not known", i) + model[i] = m + if h3[i]: + in_rem[i] = inbuf[i] + ctrl[i] = HDR2 + else: + in_rem[i] = inbuf[i] + 1 + ctrl[i] = PROC + elif c == HDR2: + if not full[i]: + continue + in_rem[i] = ((inbuf[i] << 8) | (in_rem[i] & 0xFF)) + 257 + ctrl[i] = PROC + full[i] = False + else: + st = p0[i] + if st < L: + if in_rem[i] > 0: + if full[i]: + st = (st << 8) | inbuf[i] + in_rem[i] -= 1 + full[i] = False + if in_rem[i] == 0 and flush[i]: + while st < L and st != 0 and vz[i] < MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + elif flush[i]: + if st == 0 or vz[i] >= MAX_VIRTUAL_ZEROS: + fail("fragment did not end at its home state", i) + while st < L and st != 0 and vz[i] < MAX_VIRTUAL_ZEROS: + st <<= 8 + vz[i] += 1 + else: + p1[i] = st + if out_rem[i] > 0: + ctrl[i] = HDR0 + else: + done[i] = True + continue + nxt = st > L and out_rem[i] > 0 + if nxt: + s = model[i].lookup(st & 0xFFFF) + sym[i] = s + out_rem[i] -= 1 + if s >> w[i]: + fail("symbol outside its width", i) + held[i] = nxt + p1[i] = st + if in_rem[i] == 0: + if flush[i]: + if st == L: + if out_rem[i] > 0: + ctrl[i] = HDR0 + p0[i] = 0 + p1[i] = 0 + else: + done[i] = True + elif st > L and not nxt: + fail("fragment did not end at its home state", i) + elif out_rem[i] == 0 and not nxt: + done[i] = True + elif st == L or (out_rem[i] == 0 and not nxt and st > L): + fail("fragment did not end at its home state", i) + + # Phase 3: emit one synchronized element when every active lane has filled its slot. + ready = True + anyfull = False + for i in range(nl): + if slotfull[i]: + anyfull = True + elif not (done[i] and not held[i]): + ready = False + break + if ready and anyfull: + for i in range(nl): + if slotfull[i]: + out[i].append(slotval[i]) + slotfull[i] = False + for i in range(nl): + if done[i] and held[i] and not slotfull[i]: + slotfull[i] = True + slotval[i] = sym[i] + held[i] = False + + +def decode_lanes(raw, codec, out_size): + """Entropy layer: decode `raw` into per-lane symbol lists and bytes consumed. + + Works for all six active codecs (`1, 3, 4, 5, 6, 7`). Trailing non-zero + bytes after the last lane finishes are rejected. + """ + if codec not in LANE_WIDTHS: + raise BcpackError(f"unsupported BCPack codec id: {codec}") + if out_size < 0 or out_size % BLOCK_BYTES[codec] != 0: + raise BcpackError( + f"decoded size {out_size} is not a whole number of {CODEC_NAMES[codec]} blocks" + ) + nsym = out_size // ELEMENT_BYTES + data = memoryview(raw) + lanes, used = _decode_lanes_raw(data, LANE_WIDTHS[codec], nsym) + if any(data[used:]): + raise BcpackError("non-zero data left over after the last lane finished") + return lanes, used + + +def _unzig(v): + return -((v + 1) >> 1) if (v & 1) else (v >> 1) + + +def _inter8(a, b): + d = 0 + for k in range(4): + d |= (((a >> k) & 1) << (2 * k)) | (((b >> k) & 1) << (2 * k + 1)) + return d + + +def _loose_limit(nblocks): + """Maximum undetermined blocks permitted in provisional mode (1 in 1,024, min 2).""" + return max(2, nblocks // 1024) + + +def _bc1_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC1 lane 1 is non-zero (unexpected)") + quad = _tables.BC1_QUADRANT + confirmed = _tables.BC1_HISTORY_CONFIRMED + loose = _tables.BC1_HISTORY_PROVISIONAL + out = bytearray(nblocks * 8) + hist = [None] * nblocks + mods = (32, 64, 32, 32, 64, 32) + l0 = lanes[0] + cols = lanes[2:8] + q0, q1, q2, q3 = lanes[8:12] + for i in range(nblocks): + v = l0[i] + d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) + if d == 0: + base = (0, 0, 0, 0, 0, 0) + elif i - d >= 0: + base = hist[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None: + if provisional is not None and entry in loose: + base = loose[entry] + provisional.add(f"BC1 history {entry}") + else: + state = "unconfirmed" if entry in loose else "unknown" + raise BcpackProvisionalError( + f"BC1 block {i} references {state} built-in history entry {entry}" + ) + e0 = (base[0] + _unzig(cols[0][i])) % mods[0] + e1 = (base[1] + _unzig(cols[1][i])) % mods[1] + e2 = (base[2] + _unzig(cols[2][i])) % mods[2] + e3 = (base[3] + _unzig(cols[3][i])) % mods[3] + e4 = (base[4] + _unzig(cols[4][i])) % mods[4] + e5 = (base[5] + _unzig(cols[5][i])) % mods[5] + hist[i] = (e0, e1, e2, e3, e4, e5) + c0 = (e0 << 11) | (e1 << 5) | e2 + c1 = (e3 << 11) | (e4 << 5) | e5 + a, b, c, dd = quad[q0[i]], quad[q1[i]], quad[q2[i]], quad[q3[i]] + # Quadrant byte: pixels TL, TR, BL, BR in bits 0-1, 2-3, 4-5, 6-7. + struct.pack_into( + "> 4) | ((b >> 4) << 4), + (c & 15) | ((dd & 15) << 4), + (c >> 4) | ((dd >> 4) << 4), + ) + return bytes(out) + + +_BC3_MODS = (256, 256, 32, 64, 32, 32, 64, 32) +_BC3_NONE = (128, 128, 0, 0, 0, 0, 0, 0) + + +def _bc3_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC3 lane 1 is non-zero (unexpected)") + pairs = _tables.BC3_ALPHA_PAIR + quads = _tables.BC3_COLOUR_QUADRANT + confirmed = _tables.BC3_HISTORY_CONFIRMED + loose = _tables.BC3_HISTORY_PROVISIONAL + out = bytearray(nblocks * 16) + hist = [None] * nblocks + lost = [False] * nblocks + l0, alpha = lanes[0], lanes[2] + rows = lanes[3:7] + lr, lg, lb = lanes[7], lanes[8], lanes[9] + top, bottom = lanes[10], lanes[11] + unknown = set() + mods = _BC3_MODS + for i in range(nblocks): + a, b = 2 * i, 2 * i + 1 + d = _unzig(_inter8(l0[a], l0[b])) & 255 + if d == 0: + base = _BC3_NONE + elif i - d >= 0: + base = hist[i - d] + lost[i] = lost[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None and entry in loose: + if provisional is None: + raise BcpackProvisionalError( + f"BC3 block {i} references unconfirmed built-in history entry {entry}" + ) + base = loose[entry] + provisional.add(f"BC3 history {entry}") + if base is None: + if provisional is None: + raise BcpackProvisionalError( + f"BC3 block {i} references unknown built-in history entry {entry}" + ) + base = _BC3_NONE + lost[i] = True + unknown.add(entry) + dz = (alpha[a], alpha[b], lr[a], lg[a], lb[a], lr[b], lg[b], lb[b]) + e = tuple((base[k] + _unzig(dz[k])) % mods[k] for k in range(8)) + hist[i] = e + bits = 0 + for r in range(4): + left, right = pairs[rows[r][a]], pairs[rows[r][b]] + bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) + at = i * 16 + out[at] = e[0] + out[at + 1] = e[1] + out[at + 2:at + 8] = bits.to_bytes(6, "little") + c0 = (e[2] << 11) | (e[3] << 5) | e[4] + c1 = (e[5] << 11) | (e[6] << 5) | e[7] + qa, qb = quads[top[a]], quads[top[b]] + qc, qd = quads[bottom[a]], quads[bottom[b]] + struct.pack_into( + "> 4) | ((qb >> 4) << 4), + (qc & 15) | ((qd & 15) << 4), + (qc >> 4) | ((qd >> 4) << 4), + ) + if unknown: + total = sum(lost) + if total > _loose_limit(nblocks): + raise BcpackProvisionalError( + f"BC3 chunk has {total}/{nblocks} blocks from unknown built-in history entries" + ) + provisional.add(f"BC3 unknown history {sorted(unknown)} ({total} blocks)") + return bytes(out) + + +def _bc4_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC4 lane 1 is non-zero (unexpected)") + pairs = _tables.BC4_PAIR + confirmed = _tables.BC4_HISTORY_CONFIRMED + loose = _tables.BC4_HISTORY_PROVISIONAL + out = bytearray(nblocks * 8) + hist = [None] * nblocks + l0, l2, l3 = lanes[0], lanes[2], lanes[3] + rows = lanes[4:12] + for i in range(nblocks): + v = l0[i] + d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) + if d == 0: + base = (128, 128) + elif i - d >= 0: + base = hist[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None: + if provisional is not None and entry in loose: + base = loose[entry] + provisional.add(f"BC4 history {entry}") + else: + state = "unconfirmed" if entry in loose else "unknown" + raise BcpackProvisionalError( + f"BC4 block {i} references {state} built-in history entry {entry}" + ) + a0 = (base[0] + _unzig(l2[i])) & 255 + a1 = (base[1] + _unzig(l3[i])) & 255 + hist[i] = (a0, a1) + bits = 0 + for r in range(4): + left, right = pairs[rows[2 * r][i]], pairs[rows[2 * r + 1][i]] + bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) + at = i * 8 + out[at] = a0 + out[at + 1] = a1 + out[at + 2:at + 8] = bits.to_bytes(6, "little") + return bytes(out) + + +def _bc5_blocks(lanes, nblocks, provisional): + if any(lanes[1]): + raise BcpackError("BC5 lane 1 is non-zero (unexpected)") + pairs = _tables.BC5_PAIR + confirmed = _tables.BC5_HISTORY_CONFIRMED + loose = _tables.BC5_HISTORY_PROVISIONAL + out = bytearray(nblocks * 16) + hist = [None] * nblocks + lost = [False] * nblocks + l0, red, green = lanes[0], lanes[2], lanes[3] + rows = lanes[4:12] + unknown = set() + for i in range(nblocks): + a, b = 2 * i, 2 * i + 1 + d = _unzig(_inter8(l0[a], l0[b])) & 255 + if d == 0: + base = (128, 128, 128, 128) + elif i - d >= 0: + base = hist[i - d] + lost[i] = lost[i - d] + else: + entry = 256 + i - d + base = confirmed.get(entry) + if base is None and entry in loose: + if provisional is None: + raise BcpackProvisionalError( + f"BC5 block {i} references unconfirmed built-in history entry {entry}" + ) + base = loose[entry] + provisional.add(f"BC5 history {entry}") + if base is None: + if provisional is None: + raise BcpackProvisionalError( + f"BC5 block {i} references unknown built-in history entry {entry}" + ) + base = (128, 128, 128, 128) + lost[i] = True + unknown.add(entry) + e = ( + (base[0] + _unzig(red[a])) & 255, + (base[1] + _unzig(red[b])) & 255, + (base[2] + _unzig(green[a])) & 255, + (base[3] + _unzig(green[b])) & 255, + ) + hist[i] = e + at = i * 16 + for ch in range(2): + bits = 0 + for r in range(4): + left, right = pairs[rows[4 * ch + r][a]], pairs[rows[4 * ch + r][b]] + bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) + out[at + 8 * ch] = e[2 * ch] + out[at + 8 * ch + 1] = e[2 * ch + 1] + out[at + 8 * ch + 2:at + 8 * ch + 8] = bits.to_bytes(6, "little") + if unknown: + total = sum(lost) + if total > _loose_limit(nblocks): + raise BcpackProvisionalError( + f"BC5 chunk has {total}/{nblocks} blocks from unknown built-in history entries" + ) + provisional.add(f"BC5 unknown history {sorted(unknown)} ({total} blocks)") + return bytes(out) + + +_REBUILDERS = { + 1: _bc1_blocks, + 3: _bc3_blocks, + 4: _bc4_blocks, + 5: _bc5_blocks, +} + + +def decode_with_info(raw, codec, out_size, *, allow_provisional=False): + """Decode one BCPack chunk, returning `(decoded_bytes, provisional_labels)`. + + When `allow_provisional` is False (strict mode), any unconfirmed or unknown + built-in history reference raises `BcpackProvisionalError` and the returned + set is always empty. + """ + rebuilder = _REBUILDERS.get(codec) + if rebuilder is None: + name = CODEC_NAMES.get(codec, str(codec)) + raise BcpackUnsupportedCodec(f"BCPack block rebuilder for codec {codec} ({name}) is not implemented yet") + lanes, _ = decode_lanes(raw, codec, out_size) + nblocks = out_size // BLOCK_BYTES[codec] + prov = set() if allow_provisional else None + data = rebuilder(lanes, nblocks, prov) + return data, (prov if prov is not None else set()) + + +def decode(raw, codec, out_size, *, allow_provisional=False): + """Decode one BCPack chunk into `out_size` bytes of standard BCn blocks.""" + data, _ = decode_with_info(raw, codec, out_size, allow_provisional=allow_provisional) + return data diff --git a/tools/bcpack_tables.py b/tools/bcpack_tables.py new file mode 100644 index 000000000..fe1b17cc4 --- /dev/null +++ b/tools/bcpack_tables.py @@ -0,0 +1,463 @@ +"""Fixed codec constant tables for the clean-room BCPack decoder. + +All values here are codec-level constants (rANS exponential probability models, +symbol-rank tables, and built-in initial endpoint history entries), not game +texture assets. Recovered clean-room from public specifications (US patent +11,234,023 and BCn block formats) and statistical/algebraic fitting; confirmed +and provisional built-in history entries are kept strictly separate so callers +can refuse unconfirmed entries by default. +""" + +# (symbol_width, q) -> per-band rANS frequencies (band 0 is symbol 0; +# band p >= 1 covers symbols [2^(p-1), 2^p)); total weight is 65536. +PROB_TABLES = { + (1, 0): (32768, 32768), + (1, 1): (38761, 26775), + (1, 2): (44484, 21052), + (1, 3): (49818, 15718), + (1, 4): (54623, 10913), + (1, 5): (58721, 6815), + (1, 6): (61911, 3625), + (1, 7): (64036, 1500), + (1, 8): (65121, 415), + (1, 9): (65477, 59), + (1, 10): (65534, 2), + (1, 11): (65535, 1), + (1, 12): (65535, 1), + (1, 13): (65535, 1), + (1, 14): (65535, 1), + (1, 15): (65535, 1), + (2, 0): (16384, 16384, 16384), + (2, 1): (21168, 17592, 13388), + (2, 2): (26354, 18130, 10526), + (2, 3): (31900, 17918, 7859), + (2, 4): (37750, 16874, 5456), + (2, 5): (43800, 14920, 3408), + (2, 6): (49850, 12062, 1812), + (2, 7): (55537, 8499, 750), + (2, 8): (60308, 4812, 208), + (2, 9): (63575, 1901, 30), + (2, 10): (65132, 402, 1), + (2, 11): (65511, 23, 1), + (2, 12): (65533, 1, 1), + (2, 13): (65533, 1, 1), + (2, 14): (65533, 1, 1), + (2, 15): (65533, 1, 1), + (3, 0): (8192, 8192, 8192, 8192), + (3, 1): (11073, 10095, 8796, 6694), + (3, 2): (14406, 11948, 9065, 5263), + (3, 3): (18234, 13666, 8958, 3930), + (3, 4): (22624, 15126, 8437, 2728), + (3, 5): (27657, 16143, 7460, 1704), + (3, 6): (33414, 16436, 6031, 906), + (3, 7): (39920, 15616, 4250, 375), + (3, 8): (47024, 13284, 2406, 104), + (3, 9): (54201, 9375, 950, 15), + (3, 10): (60388, 4744, 200, 1), + (3, 11): (64250, 1262, 10, 1), + (3, 12): (65456, 74, 1, 1), + (3, 13): (65529, 1, 1, 1), + (3, 14): (65529, 1, 1, 1), + (3, 15): (65529, 1, 1, 1), + (4, 0): (4096, 4096, 4096, 4096, 4096), + (4, 1): (5665, 5407, 5048, 4398, 3347), + (4, 2): (7539, 6867, 5973, 4532, 2632), + (4, 3): (9773, 8461, 6833, 4479, 1965), + (4, 4): (12447, 10177, 7564, 4218, 1364), + (4, 5): (15679, 11977, 8072, 3730, 852), + (4, 6): (19640, 13774, 8217, 3016, 453), + (4, 7): (24559, 15361, 7808, 2124, 188), + (4, 8): (30704, 16320, 6642, 1203, 52), + (4, 9): (38280, 15920, 4688, 476, 7), + (4, 10): (47169, 13219, 2372, 99, 1), + (4, 11): (56354, 7896, 631, 4, 1), + (4, 12): (63248, 2208, 34, 1, 1), + (4, 13): (65465, 57, 1, 1, 1), + (4, 14): (65521, 1, 1, 1, 1), + (4, 15): (65521, 1, 1, 1, 1), + (5, 0): (2048, 2048, 2048, 2048, 2048, 2048), + (5, 1): (2865, 2799, 2704, 2524, 2200, 1673), + (5, 2): (3858, 3682, 3434, 2986, 2266, 1316), + (5, 3): (5063, 4709, 4230, 3418, 2240, 982), + (5, 4): (6536, 5912, 5088, 3782, 2109, 682), + (5, 5): (8366, 7314, 5988, 4036, 1865, 426), + (5, 6): (10688, 8952, 6888, 4108, 1507, 227), + (5, 7): (13713, 10847, 7680, 3904, 1062, 94), + (5, 8): (17758, 12946, 8160, 3320, 602, 26), + (5, 9): (23272, 15008, 7960, 2344, 237, 4), + (5, 10): (30841, 16327, 6610, 1187, 48, 1), + (5, 11): (41006, 15348, 3947, 316, 1, 1), + (5, 12): (53291, 9957, 1104, 14, 1, 1), + (5, 13): (63380, 2084, 22, 1, 1, 1), + (5, 14): (65505, 1, 1, 1, 1, 1), + (5, 15): (65505, 1, 1, 1, 1, 1), + (6, 0): (1024, 1024, 1024, 1024, 1024, 1024, 1024), + (6, 1): (1441, 1423, 1400, 1352, 1262, 1099, 837), + (6, 2): (1951, 1907, 1841, 1717, 1493, 1133, 658), + (6, 3): (2577, 2487, 2354, 2115, 1709, 1120, 491), + (6, 4): (3350, 3186, 2956, 2544, 1890, 1055, 341), + (6, 5): (4324, 4042, 3657, 2994, 2019, 932, 213), + (6, 6): (5581, 5107, 4476, 3444, 2055, 754, 113), + (6, 7): (7258, 6454, 5424, 3840, 1952, 531, 47), + (6, 8): (9579, 8179, 6473, 4080, 1660, 301, 13), + (6, 9): (12907, 10365, 7504, 3980, 1171, 119, 2), + (6, 10): (17852, 12988, 8164, 3304, 594, 23, 1), + (6, 11): (25441, 15565, 7673, 1974, 155, 1, 1), + (6, 12): (37208, 16084, 4978, 552, 4, 1, 1), + (6, 13): (53649, 9731, 1042, 4, 1, 1, 1), + (6, 14): (65147, 327, 1, 1, 1, 1, 1), + (6, 15): (65473, 1, 1, 1, 1, 1, 1), + (7, 0): (512, 512, 512, 512, 512, 512, 512, 512), + (7, 1): (722, 718, 712, 700, 676, 632, 550, 418), + (7, 2): (981, 971, 952, 920, 858, 748, 566, 329), + (7, 3): (1300, 1276, 1244, 1178, 1058, 854, 559, 246), + (7, 4): (1696, 1654, 1593, 1478, 1272, 946, 526, 171), + (7, 5): (2198, 2126, 2022, 1828, 1498, 1009, 467, 106), + (7, 6): (2852, 2728, 2554, 2238, 1721, 1028, 376, 57), + (7, 7): (3736, 3522, 3227, 2712, 1920, 977, 266, 23), + (7, 8): (4979, 4601, 4090, 3236, 2040, 831, 151, 6), + (7, 9): (6807, 6101, 5182, 3752, 1991, 586, 59, 1), + (7, 10): (9634, 8218, 6494, 4082, 1652, 296, 11, 1), + (7, 11): (14275, 11165, 7784, 3836, 988, 74, 1, 1), + (7, 12): (22449, 14759, 8042, 2489, 272, 1, 1, 1), + (7, 13): (37625, 16023, 4866, 509, 1, 1, 1, 1), + (7, 14): (60485, 4663, 132, 1, 1, 1, 1, 1), + (7, 15): (65409, 1, 1, 1, 1, 1, 1, 1), + (8, 0): (256, 256, 256, 256, 256, 256, 256, 256, 256), + (8, 1): (362, 360, 359, 356, 350, 338, 316, 275, 209), + (8, 2): (492, 488, 486, 476, 460, 429, 374, 284, 164), + (8, 3): (653, 647, 638, 622, 589, 529, 426, 280, 123), + (8, 4): (853, 843, 828, 796, 739, 636, 473, 264, 85), + (8, 5): (1108, 1090, 1063, 1011, 914, 748, 504, 234, 53), + (8, 6): (1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28), + (8, 7): (1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12), + (8, 8): (2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3), + (8, 9): (3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1), + (8, 10): (5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1), + (8, 11): (7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1), + (8, 12): (12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1), + (8, 13): (22767, 14857, 8012, 2432, 240, 1, 1, 1, 1), + (8, 14): (47343, 13141, 2332, 35, 1, 1, 1, 1, 1), + (8, 15): (65281, 1, 1, 1, 1, 1, 1, 1, 1), + (9, 0): (128, 128, 128, 128, 128, 128, 128, 128, 128, 128), + (9, 1): (181, 181, 179, 180, 178, 175, 169, 157, 137, 105), + (9, 2): (246, 246, 244, 243, 238, 231, 214, 187, 142, 82), + (9, 3): (327, 325, 324, 319, 310, 294, 265, 213, 141, 61), + (9, 4): (428, 424, 422, 414, 397, 370, 319, 236, 131, 43), + (9, 5): (557, 551, 546, 530, 506, 457, 374, 252, 116, 27), + (9, 6): (725, 717, 705, 683, 638, 560, 430, 256, 95, 14), + (9, 7): (955, 941, 920, 880, 807, 677, 481, 244, 66, 6), + (9, 8): (1282, 1256, 1219, 1150, 1023, 810, 510, 207, 37, 2), + (9, 9): (1772, 1724, 1656, 1524, 1295, 938, 498, 147, 13, 1), + (9, 10): (2554, 2454, 2312, 2054, 1625, 1020, 414, 74, 1, 1), + (9, 11): (3904, 3672, 3350, 2791, 1946, 959, 247, 14, 1, 1), + (9, 12): (6523, 5873, 5026, 3690, 2011, 621, 58, 1, 1, 1), + (9, 13): (12593, 10175, 7428, 4006, 1216, 105, 1, 1, 1, 1), + (9, 14): (31009, 16335, 6572, 1136, 1, 1, 1, 1, 1, 1), + (9, 15): (65025, 1, 1, 1, 1, 1, 1, 1, 1, 1), + (10, 0): (64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64), + (10, 1): (91, 89, 90, 90, 90, 90, 88, 85, 79, 69, 52), + (10, 2): (123, 123, 123, 123, 121, 120, 115, 108, 93, 71, 41), + (10, 3): (164, 164, 162, 161, 160, 155, 148, 131, 108, 69, 31), + (10, 4): (214, 214, 212, 211, 206, 199, 184, 160, 117, 67, 21), + (10, 5): (279, 277, 276, 273, 265, 252, 229, 187, 126, 59, 13), + (10, 6): (364, 360, 358, 352, 342, 319, 280, 215, 129, 47, 7), + (10, 7): (479, 477, 470, 460, 441, 404, 339, 240, 122, 33, 3), + (10, 8): (644, 638, 627, 610, 576, 511, 405, 254, 105, 18, 1), + (10, 9): (892, 880, 862, 828, 763, 647, 469, 248, 73, 6, 1), + (10, 10): (1290, 1264, 1227, 1156, 1028, 812, 510, 207, 34, 1, 1), + (10, 11): (1982, 1922, 1836, 1674, 1396, 972, 481, 123, 4, 1, 1), + (10, 12): (3347, 3177, 2936, 2513, 1846, 1004, 311, 22, 1, 1, 1), + (10, 13): (6632, 5962, 5087, 3714, 2003, 609, 37, 1, 1, 1, 1), + (10, 14): (17963, 13041, 8168, 3285, 506, 1, 1, 1, 1, 1, 1), + (10, 15): (64513, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), +} + +# BC1 index lanes: symbol -> 2x2 quadrant byte (TL, TR, BL, BR in bits 0-1, 2-3, 4-5, 6-7). +BC1_QUADRANT = bytes([ + 0xaa, 0xff, 0x00, 0x55, 0xfa, 0xaf, 0xfb, 0xbf, 0xfe, 0xef, 0xbb, 0xee, 0xdf, 0xba, 0x5a, 0xae, + 0x7f, 0xea, 0xab, 0xf7, 0xfd, 0xa5, 0x5f, 0xf5, 0xdd, 0x77, 0x66, 0x99, 0x2a, 0x8a, 0xa2, 0x50, + 0x05, 0xa8, 0x11, 0x9a, 0x44, 0x3f, 0xa6, 0xa9, 0xcf, 0xbe, 0xfc, 0xf3, 0x6a, 0xeb, 0x7e, 0xe7, + 0xdb, 0xbd, 0x7a, 0xa7, 0xda, 0x0f, 0xad, 0x57, 0xd5, 0x0a, 0x5d, 0x75, 0x2f, 0x6e, 0xf0, 0x8f, + 0xf8, 0xe6, 0x3d, 0xf2, 0xb9, 0x25, 0x7c, 0x9b, 0x3b, 0x85, 0xce, 0xec, 0x58, 0xb3, 0xd3, 0xa0, + 0x52, 0xde, 0x7b, 0x2b, 0xb7, 0x5e, 0xc7, 0xed, 0x5b, 0xb2, 0x8e, 0xcc, 0x6f, 0x19, 0xf6, 0x9f, + 0x64, 0xe8, 0xe5, 0x29, 0xf9, 0x33, 0x46, 0x22, 0xb5, 0xd7, 0x2d, 0x78, 0x56, 0x86, 0x88, 0x68, + 0x91, 0x95, 0x92, 0xd2, 0x87, 0x7d, 0x76, 0x67, 0x9d, 0x59, 0x65, 0xd9, 0x15, 0x37, 0x93, 0x5c, + 0xc6, 0x35, 0x6c, 0xcd, 0x39, 0x45, 0xdc, 0x54, 0x73, 0x51, 0x53, 0xc5, 0x2e, 0x8b, 0x8d, 0x27, + 0xe2, 0x1f, 0xf4, 0x1d, 0xd8, 0xf1, 0x72, 0xa3, 0x4f, 0x74, 0xb8, 0xca, 0x3a, 0xac, 0xd1, 0x89, + 0x47, 0x26, 0x62, 0x98, 0x70, 0x0d, 0xa1, 0x1a, 0x4a, 0x6b, 0x1b, 0xd0, 0xa4, 0xe9, 0x07, 0xb1, + 0x9e, 0xb6, 0xe4, 0x4e, 0xbc, 0xe3, 0x3e, 0xcb, 0x82, 0x31, 0x02, 0x28, 0x4c, 0x13, 0xc4, 0x20, + 0x0e, 0x0b, 0x08, 0x96, 0x80, 0xe0, 0x09, 0xb0, 0x69, 0x60, 0x06, 0x90, 0x23, 0x97, 0x8c, 0xd6, + 0x21, 0x6d, 0x79, 0x32, 0xc8, 0x48, 0x84, 0x17, 0x12, 0xd4, 0x4d, 0x71, 0x01, 0x36, 0x63, 0x9c, + 0xc9, 0x40, 0x04, 0x10, 0xe1, 0x16, 0x94, 0x49, 0x4b, 0x1e, 0xb4, 0x61, 0x03, 0x0c, 0xc0, 0x42, + 0x81, 0x18, 0x30, 0x24, 0xc3, 0x3c, 0xc2, 0x41, 0x14, 0x83, 0x2c, 0x38, 0x43, 0x34, 0x1c, 0xc1, +]) + +# BC1 built-in 256-entry endpoint history: index -> (r0, g0, b0, r1, g1, b1). +BC1_HISTORY_CONFIRMED = { + 1: (7, 29, 6, 8, 30, 7), 2: (15, 29, 15, 16, 36, 17), 3: (20, 38, 14, 3, 5, 2), + 4: (12, 27, 13, 6, 12, 6), 5: (10, 22, 11, 6, 14, 7), 7: (12, 26, 12, 7, 14, 7), + 8: (22, 36, 15, 20, 32, 14), 10: (23, 5, 30, 9, 5, 30), 11: (11, 22, 11, 7, 15, 7), + 12: (17, 22, 7, 10, 11, 3), 13: (12, 25, 12, 7, 16, 7), 14: (13, 28, 8, 5, 11, 3), + 15: (11, 20, 8, 16, 31, 14), 16: (23, 32, 30, 17, 12, 29), 17: (8, 44, 30, 6, 26, 30), + 18: (10, 24, 30, 6, 45, 30), 19: (10, 12, 4, 8, 8, 2), 20: (16, 23, 30, 14, 6, 26), + 21: (12, 25, 13, 10, 22, 12), 22: (19, 27, 10, 12, 15, 5), 23: (11, 24, 12, 4, 11, 6), + 24: (29, 60, 29, 6, 13, 6), 25: (17, 31, 11, 1, 2, 1), 26: (26, 54, 24, 12, 24, 10), + 27: (23, 49, 30, 20, 36, 30), 28: (16, 23, 10, 10, 14, 6), 29: (11, 24, 10, 6, 13, 5), + 30: (18, 52, 30, 14, 22, 30), 31: (14, 51, 30, 9, 34, 30), 32: (2, 3, 1, 19, 37, 16), + 33: (14, 15, 30, 9, 31, 30), 34: (29, 57, 27, 27, 52, 25), 35: (13, 29, 15, 8, 20, 11), + 36: (13, 17, 5, 9, 10, 3), 37: (18, 50, 29, 15, 10, 29), 38: (11, 25, 13, 8, 19, 10), + 39: (17, 32, 12, 6, 11, 4), 40: (22, 18, 30, 19, 41, 30), 41: (10, 22, 11, 8, 18, 9), + 42: (18, 30, 31, 10, 44, 30), 43: (25, 50, 24, 2, 4, 1), 44: (11, 30, 31, 7, 15, 29), + 45: (12, 19, 8, 11, 16, 7), 46: (19, 29, 30, 14, 55, 28), 47: (9, 20, 10, 4, 10, 5), + 48: (12, 24, 10, 7, 13, 5), 49: (26, 53, 25, 6, 13, 6), 50: (19, 27, 31, 11, 19, 30), + 51: (21, 31, 30, 22, 31, 30), 52: (10, 19, 5, 11, 21, 6), 53: (30, 50, 3, 29, 46, 2), + 54: (15, 9, 30, 7, 9, 30), 55: (14, 18, 6, 11, 14, 4), 56: (28, 56, 26, 4, 7, 3), + 57: (9, 20, 10, 5, 13, 7), 58: (28, 58, 26, 15, 32, 14), 59: (11, 19, 8, 6, 9, 4), + 60: (16, 22, 9, 13, 17, 7), 61: (1, 2, 1, 14, 28, 12), 62: (22, 45, 30, 9, 15, 30), + 63: (19, 22, 30, 16, 23, 31), 64: (25, 50, 24, 21, 43, 20), 65: (6, 11, 4, 16, 31, 13), + 66: (13, 25, 8, 3, 6, 1), 69: (20, 38, 16, 13, 25, 10), 70: (18, 35, 15, 5, 9, 3), + 72: (11, 21, 7, 7, 13, 4), 73: (20, 39, 16, 11, 20, 8), 75: (22, 41, 30, 18, 23, 30), + 76: (24, 50, 24, 9, 19, 8), 77: (3, 12, 7, 4, 16, 8), 78: (18, 27, 12, 16, 22, 10), + 79: (24, 49, 23, 13, 28, 12), 80: (24, 50, 24, 18, 37, 18), 81: (17, 33, 12, 14, 27, 9), + 82: (20, 10, 31, 13, 10, 31), 83: (7, 8, 2, 5, 5, 1), 84: (1, 2, 1, 10, 21, 9), + 85: (10, 18, 6, 1, 1, 0), 86: (22, 46, 21, 1, 3, 1), 87: (11, 20, 8, 8, 14, 5), + 88: (17, 35, 31, 14, 14, 29), 89: (16, 22, 31, 12, 40, 31), 90: (12, 22, 9, 8, 15, 6), + 91: (18, 15, 30, 15, 33, 31), 92: (19, 32, 30, 15, 43, 31), 93: (18, 35, 15, 8, 15, 5), + 94: (21, 43, 20, 18, 37, 17), 95: (10, 17, 6, 9, 15, 6), 96: (14, 27, 12, 7, 13, 5), + 97: (8, 16, 7, 12, 25, 11), 98: (18, 37, 17, 1, 1, 0), 99: (17, 45, 30, 15, 33, 31), + 100: (13, 25, 11, 8, 16, 7), 101: (23, 47, 22, 16, 32, 15), 102: (18, 33, 13, 11, 21, 8), + 103: (4, 10, 4, 8, 17, 7), 104: (1, 2, 1, 3, 7, 3), 105: (11, 22, 9, 6, 11, 4), + 106: (16, 29, 11, 13, 23, 9), 107: (12, 24, 12, 6, 12, 6), 108: (23, 47, 22, 7, 14, 6), + 109: (11, 32, 30, 11, 31, 30), 110: (14, 26, 11, 10, 18, 7), 111: (20, 41, 19, 1, 3, 1), + 112: (14, 28, 12, 8, 16, 6), 113: (11, 21, 9, 8, 15, 6), 114: (1, 2, 1, 7, 13, 6), + 115: (19, 35, 14, 16, 29, 12), 116: (13, 27, 13, 7, 15, 7), 117: (15, 33, 16, 8, 18, 9), + 118: (15, 42, 31, 11, 22, 30), 119: (23, 48, 23, 4, 9, 4), 120: (22, 45, 21, 11, 22, 10), + 121: (31, 62, 30, 31, 61, 29), 123: (19, 39, 19, 9, 20, 10), 124: (7, 14, 2, 6, 12, 2), + 125: (21, 42, 20, 3, 7, 3), 126: (10, 17, 7, 8, 13, 5), 127: (11, 20, 8, 9, 17, 7), + 128: (19, 33, 31, 12, 31, 31), 129: (21, 43, 20, 5, 11, 5), 130: (10, 20, 9, 7, 13, 6), + 131: (10, 21, 10, 6, 13, 6), 132: (15, 29, 12, 11, 20, 8), 133: (21, 43, 20, 9, 18, 8), + 134: (3, 8, 3, 5, 11, 5), 135: (16, 31, 13, 9, 17, 7), 136: (11, 22, 11, 6, 12, 6), + 137: (10, 21, 10, 7, 15, 7), 138: (27, 3, 1, 26, 1, 0), 139: (18, 37, 18, 16, 32, 16), + 140: (12, 23, 10, 9, 17, 7), 141: (12, 25, 12, 8, 17, 8), 142: (11, 21, 9, 2, 4, 1), + 143: (7, 15, 7, 8, 18, 9), 144: (17, 33, 15, 13, 24, 11), 145: (9, 19, 9, 7, 15, 7), + 146: (21, 43, 20, 13, 27, 12), 147: (17, 36, 17, 2, 4, 2), 148: (10, 20, 9, 6, 12, 5), + 149: (20, 41, 19, 7, 14, 7), 150: (3, 9, 6, 2, 8, 5), 151: (13, 24, 10, 11, 20, 8), + 152: (18, 38, 18, 4, 7, 3), 153: (19, 38, 18, 8, 17, 8), 154: (16, 35, 17, 4, 10, 4), + 155: (11, 23, 11, 10, 21, 10), 156: (17, 36, 17, 7, 14, 7), 157: (13, 27, 13, 6, 12, 6), + 158: (9, 15, 4, 8, 13, 4), 159: (10, 19, 7, 5, 9, 3), 160: (19, 40, 19, 11, 24, 11), + 161: (11, 23, 11, 8, 17, 8), 162: (14, 29, 14, 7, 15, 7), 163: (12, 22, 9, 5, 8, 3), + 164: (10, 20, 9, 8, 17, 8), 165: (21, 42, 19, 15, 31, 14), 166: (14, 29, 13, 1, 1, 0), + 167: (8, 16, 8, 7, 14, 7), 168: (9, 18, 8, 8, 16, 7), 169: (10, 17, 7, 3, 4, 1), + 170: (14, 28, 13, 2, 4, 1), 171: (14, 30, 14, 3, 6, 3), 172: (19, 38, 18, 5, 11, 5), + 173: (12, 26, 12, 1, 2, 1), 174: (9, 16, 6, 8, 13, 5), 175: (8, 13, 4, 7, 11, 4), + 176: (16, 34, 16, 3, 7, 3), 177: (13, 28, 13, 4, 9, 4), 178: (15, 31, 15, 6, 13, 6), + 179: (12, 24, 11, 9, 19, 9), 180: (9, 19, 8, 7, 14, 6), 181: (14, 28, 13, 5, 10, 4), + 182: (10, 20, 7, 4, 6, 2), 183: (16, 34, 17, 11, 25, 12), 184: (15, 30, 15, 8, 16, 8), + 185: (13, 27, 13, 10, 20, 10), 186: (9, 20, 9, 0, 1, 0), 187: (16, 32, 15, 2, 4, 2), + 188: (13, 27, 12, 3, 6, 3), 189: (13, 26, 12, 12, 23, 11), 190: (12, 25, 12, 5, 10, 5), + 191: (11, 23, 11, 5, 11, 5), 192: (16, 34, 16, 6, 12, 5), 193: (16, 35, 31, 15, 25, 31), + 194: (16, 33, 16, 7, 15, 7), 195: (13, 27, 13, 8, 18, 8), 196: (18, 36, 17, 11, 22, 10), + 197: (18, 37, 18, 13, 27, 13), 198: (12, 25, 12, 4, 8, 4), 199: (9, 18, 7, 6, 11, 4), + 200: (15, 30, 14, 9, 19, 9), 201: (17, 35, 16, 9, 18, 9), 202: (11, 24, 11, 2, 4, 2), + 203: (16, 33, 16, 0, 1, 0), 204: (15, 31, 15, 4, 9, 4), 205: (16, 31, 15, 14, 27, 13), + 206: (14, 29, 14, 13, 25, 12), 207: (11, 23, 11, 3, 6, 3), 208: (16, 32, 16, 10, 21, 10), + 209: (11, 22, 11, 4, 9, 4), 210: (11, 22, 10, 1, 2, 0), 211: (8, 14, 5, 2, 4, 1), + 212: (9, 16, 6, 6, 10, 4), 213: (10, 21, 10, 9, 19, 9), 214: (14, 30, 14, 11, 22, 11), + 215: (9, 18, 8, 6, 13, 6), 216: (6, 13, 6, 5, 11, 5), 217: (7, 14, 6, 0, 1, 0), + 218: (4, 7, 2, 3, 4, 1), 219: (10, 20, 9, 4, 8, 4), 220: (9, 17, 7, 5, 9, 3), + 221: (7, 14, 7, 1, 2, 1), 222: (10, 20, 10, 5, 10, 5), 223: (8, 15, 5, 4, 6, 2), + 224: (8, 17, 8, 1, 2, 1), 225: (10, 20, 10, 3, 6, 3), 226: (7, 10, 3, 6, 8, 3), + 227: (8, 15, 7, 6, 12, 6), 228: (9, 19, 9, 2, 4, 2), 229: (6, 11, 4, 3, 4, 1), + 230: (6, 11, 4, 0, 1, 0), 231: (8, 16, 7, 2, 4, 2), 232: (16, 34, 16, 15, 29, 15), + 233: (7, 16, 7, 5, 10, 5), 234: (8, 14, 5, 5, 9, 3), 235: (9, 18, 8, 4, 8, 4), + 236: (5, 9, 3, 4, 7, 2), 237: (9, 18, 8, 5, 10, 5), 238: (6, 12, 6, 2, 4, 2), + 239: (7, 12, 5, 4, 7, 3), 240: (5, 11, 5, 1, 2, 1), 241: (8, 17, 8, 3, 6, 3), + 242: (16, 31, 31, 16, 32, 31), 243: (7, 14, 7, 3, 6, 3), 244: (5, 11, 6, 4, 9, 4), + 245: (7, 15, 7, 4, 8, 4), 246: (2, 4, 2, 0, 0, 1), 247: (5, 11, 5, 3, 6, 3), + 248: (4, 8, 4, 1, 1, 1), 249: (3, 6, 3, 1, 2, 1), 250: (2, 4, 1, 1, 2, 1), + 251: (4, 8, 4, 3, 6, 3), 252: (3, 6, 3, 2, 4, 2), 253: (4, 9, 4, 2, 4, 2), + 254: (17, 27, 31, 15, 34, 31), 255: (0, 0, 1, 0, 0, 0), +} + +BC1_HISTORY_PROVISIONAL = { + 6: (12, 24, 11, 7, 14, 6), 9: (14, 23, 8, 1, 2, 1), 67: (5, 9, 3, 12, 24, 10), + 68: (16, 29, 13, 7, 13, 5), 71: (13, 25, 11, 6, 11, 4), 74: (16, 31, 12, 4, 8, 2), + 122: (13, 26, 11, 5, 8, 3), +} + +# BC3 3-bit alpha index pair rank table (64 entries) and colour quadrant rank table (256 entries). +BC3_ALPHA_PAIR = ( + (0, 0), (1, 1), (6, 6), (4, 4), (3, 3), (5, 5), (7, 7), (1, 6), + (6, 1), (0, 1), (1, 0), (7, 1), (1, 7), (0, 3), (3, 0), (0, 2), + (2, 0), (2, 2), (5, 4), (3, 4), (4, 3), (4, 5), (1, 5), (5, 1), + (0, 4), (4, 0), (2, 3), (3, 2), (5, 3), (3, 5), (6, 5), (5, 6), + (6, 7), (7, 6), (5, 7), (4, 6), (6, 4), (7, 5), (6, 0), (0, 6), + (4, 2), (2, 4), (4, 1), (1, 4), (5, 0), (0, 5), (6, 3), (3, 6), + (3, 1), (5, 2), (1, 3), (2, 5), (7, 4), (4, 7), (7, 3), (3, 7), + (2, 6), (6, 2), (2, 1), (1, 2), (0, 7), (7, 0), (2, 7), (7, 2), +) + +BC3_COLOUR_QUADRANT = bytes([ + 0x55, 0xaa, 0xff, 0x00, 0x50, 0x05, 0xaf, 0xfa, 0xae, 0xea, 0xab, 0xba, 0xee, 0xbb, 0xfe, 0xbf, + 0xef, 0xfb, 0xa5, 0x5a, 0xf0, 0x11, 0x0f, 0x44, 0xf5, 0x5f, 0xa0, 0x0a, 0x8a, 0xa2, 0xa8, 0x2a, + 0x7f, 0xf7, 0x77, 0xdf, 0xfd, 0xdd, 0x66, 0x99, 0x88, 0xbe, 0xeb, 0x22, 0xcc, 0x33, 0x8f, 0xf8, + 0x57, 0x75, 0xd5, 0x5d, 0x2f, 0xf2, 0x7a, 0x85, 0xa7, 0xda, 0x58, 0x25, 0xad, 0x52, 0x3f, 0xf3, + 0xcf, 0xe8, 0xfc, 0x8e, 0x2b, 0x7e, 0x6a, 0xa6, 0x9a, 0x70, 0x07, 0x0d, 0xa9, 0x78, 0x80, 0x08, + 0x02, 0xe7, 0xb2, 0x20, 0xdb, 0xd0, 0x87, 0x5e, 0xbd, 0x7c, 0x2d, 0xe5, 0xc7, 0xec, 0xce, 0x5b, + 0xb3, 0xd2, 0x2e, 0xb5, 0x3b, 0xe0, 0xe6, 0x6e, 0x68, 0x8b, 0x9b, 0xe2, 0xb9, 0x0e, 0xb8, 0x0b, + 0x3d, 0xd3, 0x51, 0x86, 0x27, 0x45, 0x15, 0xde, 0x54, 0x8d, 0xb7, 0xed, 0x7b, 0xb0, 0xd8, 0x29, + 0x72, 0x92, 0x7d, 0xd7, 0x35, 0xa3, 0xc5, 0x82, 0x37, 0x53, 0x28, 0x5c, 0x56, 0x65, 0x76, 0x95, + 0x59, 0xcd, 0x9f, 0x3a, 0x73, 0x89, 0xca, 0xac, 0x67, 0x9d, 0xf6, 0xd9, 0xf9, 0x91, 0x19, 0xdc, + 0x98, 0x6c, 0x46, 0x64, 0x6f, 0x26, 0x39, 0x62, 0xc6, 0x93, 0x09, 0x23, 0x06, 0x60, 0x8c, 0xc8, + 0x90, 0x32, 0x03, 0x3e, 0xc0, 0x13, 0x31, 0xe3, 0x4c, 0x9e, 0x0c, 0xc4, 0xcb, 0xbc, 0xb6, 0xe9, + 0x30, 0x6b, 0x1f, 0xf1, 0x1d, 0xd1, 0x47, 0x74, 0x4f, 0x10, 0x40, 0xf4, 0x01, 0x04, 0xa1, 0x1a, + 0xa4, 0x1b, 0x4a, 0xb1, 0xe4, 0x4e, 0x36, 0xc9, 0x9c, 0x63, 0x97, 0x71, 0x79, 0x17, 0x48, 0x69, + 0x21, 0x12, 0x3c, 0x84, 0x83, 0x6d, 0xd6, 0x96, 0xc3, 0x38, 0x1e, 0x4d, 0xe1, 0xd4, 0xc2, 0x2c, + 0x18, 0x81, 0xb4, 0x4b, 0x16, 0x61, 0xc1, 0x24, 0x1c, 0x49, 0x14, 0x42, 0x94, 0x41, 0x34, 0x43, +]) + +# BC3 built-in endpoint history: index -> (a0, a1, r0, g0, b0, r1, g1, b1). +BC3_HISTORY_CONFIRMED = {} + +BC3_HISTORY_PROVISIONAL = { + 2: (177, 134, 27, 55, 24, 14, 54, 24), 26: (255, 255, 21, 34, 8, 15, 22, 3), + 29: (220, 109, 17, 35, 17, 15, 30, 15), 30: (219, 96, 2, 53, 14, 2, 59, 16), + 35: (95, 65, 16, 31, 16, 15, 31, 15), 37: (136, 13, 16, 33, 16, 15, 32, 15), + 47: (146, 108, 18, 37, 18, 13, 26, 13), 52: (255, 255, 20, 38, 16, 3, 5, 2), + 71: (200, 51, 17, 34, 17, 15, 31, 15), 76: (170, 150, 2, 60, 20, 1, 61, 20), + 78: (248, 10, 3, 4, 2, 0, 1, 0), 95: (237, 229, 26, 51, 25, 1, 3, 1), + 98: (255, 0, 19, 38, 18, 14, 29, 13), 104: (255, 6, 13, 27, 13, 8, 17, 8), + 109: (254, 4, 15, 27, 11, 3, 4, 2), 112: (117, 39, 21, 41, 21, 1, 3, 1), + 126: (170, 119, 16, 31, 16, 15, 30, 15), 138: (122, 121, 14, 29, 14, 13, 27, 13), + 139: (247, 1, 15, 28, 13, 9, 16, 7), 153: (105, 126, 2, 7, 4, 1, 3, 2), + 154: (93, 100, 20, 40, 20, 15, 30, 15), 166: (91, 99, 17, 35, 17, 15, 30, 15), + 167: (155, 99, 16, 33, 16, 15, 31, 15), 177: (255, 255, 13, 24, 12, 11, 23, 10), + 185: (254, 255, 10, 17, 7, 2, 3, 1), 197: (253, 255, 11, 20, 9, 6, 11, 4), + 210: (254, 255, 5, 10, 5, 1, 2, 1), 220: (255, 255, 11, 20, 9, 9, 18, 7), + 225: (106, 113, 24, 39, 23, 0, 13, 0), 226: (1, 255, 8, 15, 7, 5, 10, 4), + 230: (1, 2, 0, 1, 1, 0, 0, 0), 232: (140, 131, 16, 31, 16, 15, 34, 16), + 237: (255, 254, 5, 11, 5, 4, 9, 3), 244: (255, 255, 1, 1, 1, 0, 0, 0), + 246: (253, 254, 3, 5, 2, 1, 2, 1), +} + +# BC4 3-bit index pair rank table (64 entries) and built-in endpoint history: index -> (a0, a1). +BC4_PAIR = ( + (1, 1), (0, 0), (3, 3), (6, 6), (4, 4), (5, 5), (3, 0), (0, 3), + (6, 1), (1, 6), (7, 7), (2, 2), (6, 3), (3, 6), (1, 0), (0, 1), + (4, 1), (1, 4), (3, 1), (1, 3), (6, 0), (0, 6), (4, 2), (7, 5), + (5, 7), (2, 4), (0, 5), (5, 0), (6, 4), (4, 6), (5, 3), (3, 5), + (4, 0), (0, 4), (1, 5), (5, 1), (3, 4), (4, 3), (2, 6), (6, 2), + (7, 3), (3, 7), (1, 2), (2, 1), (0, 7), (7, 0), (2, 5), (5, 2), + (7, 4), (4, 7), (4, 5), (5, 4), (3, 2), (2, 3), (0, 2), (2, 0), + (1, 7), (7, 1), (6, 5), (5, 6), (6, 7), (7, 6), (2, 7), (7, 2), +) + +BC4_HISTORY_CONFIRMED = {} + +BC4_HISTORY_PROVISIONAL = { + 25: (81, 50), 33: (58, 31), 77: (164, 124), 84: (204, 140), + 93: (208, 61), 101: (171, 137), 102: (212, 125), 116: (77, 34), + 119: (193, 127), 121: (178, 118), 126: (138, 108), 127: (132, 115), + 131: (165, 52), 142: (142, 80), 145: (74, 16), 148: (150, 124), + 154: (195, 103), 157: (71, 51), 163: (55, 33), 172: (139, 119), + 173: (42, 15), 178: (91, 47), 179: (48, 8), 184: (72, 34), + 185: (158, 136), 187: (105, 12), 188: (142, 38), 190: (43, 25), + 197: (133, 133), 200: (55, 17), 202: (82, 43), 207: (127, 129), + 208: (39, 9), 209: (134, 27), 211: (39, 23), 213: (19, 41), + 214: (39, 17), 217: (115, 21), 218: (118, 60), 221: (47, 17), + 223: (64, 25), 224: (119, 33), 227: (33, 16), 232: (78, 5), + 234: (33, 60), 235: (57, 24), 236: (69, 2), 239: (105, 24), + 240: (96, 34), 241: (111, 44), 243: (47, 25), 244: (84, 23), + 247: (22, 17), 252: (27, 8), 254: (12, 6), +} + +# BC5 3-bit index pair rank table (64 entries) and built-in endpoint history: index -> (r0, r1, g0, g1). +BC5_PAIR = ( + (0, 0), (1, 1), (4, 4), (3, 3), (6, 6), (7, 7), (4, 0), (0, 4), + (0, 1), (2, 2), (1, 0), (3, 0), (0, 3), (5, 5), (2, 0), (0, 2), + (1, 6), (6, 1), (4, 3), (1, 7), (3, 4), (1, 4), (7, 1), (6, 0), + (0, 6), (6, 3), (6, 4), (3, 6), (3, 2), (4, 6), (1, 5), (1, 3), + (2, 3), (5, 4), (5, 3), (5, 0), (4, 1), (7, 6), (4, 5), (4, 2), + (3, 1), (3, 5), (5, 1), (6, 7), (2, 4), (7, 5), (7, 4), (0, 5), + (6, 5), (4, 7), (5, 7), (7, 0), (5, 6), (0, 7), (7, 3), (3, 7), + (5, 2), (2, 5), (1, 2), (6, 2), (2, 1), (2, 6), (7, 2), (2, 7), +) + +BC5_HISTORY_CONFIRMED = { + 182: (133, 126, 124, 55), 183: (128, 126, 116, 112), 222: (131, 128, 123, 37), +} + +BC5_HISTORY_PROVISIONAL = { + 3: (130, 218, 45, 192), 4: (172, 109, 158, 94), 5: (183, 136, 113, 69), + 6: (125, 129, 86, 34), 7: (171, 196, 33, 82), 9: (142, 149, 102, 118), + 14: (82, 62, 26, 23), 15: (100, 94, 32, 32), 16: (97, 123, 61, 97), + 19: (133, 140, 118, 123), 20: (206, 194, 128, 123), 22: (147, 145, 64, 66), + 24: (76, 189, 55, 171), 27: (94, 115, 86, 102), 28: (163, 38, 152, 29), + 29: (143, 133, 89, 80), 30: (197, 67, 172, 50), 31: (164, 218, 130, 127), + 32: (141, 145, 111, 132), 33: (177, 125, 131, 32), 34: (49, 113, 26, 94), + 36: (173, 169, 40, 28), 38: (117, 125, 43, 50), 39: (139, 111, 99, 72), + 40: (123, 93, 83, 49), 41: (189, 166, 135, 116), 42: (198, 97, 178, 73), + 43: (205, 201, 76, 86), 44: (172, 174, 73, 72), 46: (157, 210, 136, 188), + 47: (126, 149, 115, 129), 48: (158, 67, 137, 41), 49: (214, 120, 131, 80), + 51: (147, 150, 119, 119), 52: (169, 107, 135, 65), 54: (231, 168, 223, 154), + 55: (115, 144, 99, 120), 56: (74, 104, 50, 83), 57: (220, 132, 32, 123), + 58: (150, 136, 110, 96), 60: (139, 147, 124, 108), 61: (121, 124, 78, 94), + 63: (169, 151, 124, 103), 64: (120, 106, 103, 88), 65: (134, 147, 110, 109), + 67: (133, 125, 103, 107), 68: (160, 133, 118, 123), 69: (175, 78, 163, 68), + 70: (229, 133, 166, 121), 71: (233, 147, 224, 134), 72: (127, 142, 104, 121), + 73: (134, 150, 99, 121), 74: (110, 149, 83, 129), 75: (175, 187, 129, 141), + 77: (115, 124, 96, 104), 78: (164, 128, 141, 109), 79: (129, 85, 114, 22), + 80: (246, 131, 241, 125), 82: (168, 186, 145, 165), 83: (192, 133, 158, 100), + 84: (107, 143, 105, 133), 85: (201, 212, 172, 181), 86: (124, 138, 116, 121), + 87: (92, 60, 71, 40), 88: (203, 134, 149, 126), 90: (61, 123, 25, 114), + 91: (123, 160, 113, 145), 92: (150, 169, 135, 150), 93: (134, 139, 101, 109), + 94: (253, 94, 255, 63), 95: (123, 87, 106, 67), 96: (238, 133, 121, 121), + 98: (24, 18, 15, 10), 99: (117, 41, 97, 25), 100: (123, 121, 70, 67), + 101: (64, 59, 51, 49), 102: (11, 103, 12, 88), 103: (144, 133, 111, 123), + 104: (189, 200, 65, 52), 105: (219, 153, 195, 135), 106: (150, 110, 138, 98), + 107: (118, 142, 60, 117), 108: (139, 145, 114, 118), 109: (216, 225, 191, 200), + 110: (46, 46, 38, 33), 111: (91, 132, 85, 126), 112: (154, 178, 115, 132), + 114: (131, 127, 125, 17), 115: (136, 134, 15, 123), 116: (131, 129, 105, 123), + 119: (132, 215, 122, 149), 120: (129, 138, 112, 111), 123: (136, 145, 119, 131), + 124: (179, 196, 165, 183), 125: (126, 125, 111, 92), 126: (136, 150, 122, 123), + 127: (168, 158, 136, 126), 128: (146, 153, 129, 134), 129: (127, 130, 85, 124), + 130: (132, 241, 120, 126), 131: (155, 124, 125, 85), 132: (121, 115, 115, 108), + 133: (106, 72, 89, 51), 134: (136, 155, 118, 137), 135: (121, 145, 106, 133), + 136: (119, 220, 102, 209), 137: (179, 136, 150, 122), 138: (120, 133, 102, 113), + 139: (145, 142, 111, 112), 140: (130, 108, 123, 62), 141: (121, 132, 37, 122), + 142: (157, 142, 135, 119), 143: (80, 201, 59, 191), 144: (130, 133, 122, 104), + 145: (138, 136, 112, 120), 146: (131, 107, 123, 37), 147: (122, 120, 107, 119), + 148: (126, 181, 121, 146), 149: (143, 141, 137, 135), 150: (134, 178, 121, 161), + 151: (103, 135, 55, 126), 152: (193, 132, 128, 123), 153: (141, 129, 111, 114), + 154: (79, 77, 53, 51), 155: (133, 72, 127, 64), 157: (102, 101, 83, 80), + 159: (92, 137, 39, 125), 160: (108, 136, 87, 122), 161: (102, 97, 65, 57), + 162: (163, 149, 151, 134), 163: (133, 17, 121, 15), 165: (179, 162, 153, 133), + 166: (119, 132, 98, 125), 167: (175, 132, 130, 124), 169: (132, 92, 124, 81), + 170: (40, 31, 27, 19), 171: (188, 211, 180, 202), 172: (139, 121, 117, 101), + 173: (150, 125, 130, 106), 174: (129, 184, 123, 131), 175: (132, 158, 126, 148), + 176: (130, 155, 126, 129), 177: (131, 167, 124, 127), 178: (155, 131, 132, 125), + 179: (198, 139, 170, 124), 180: (200, 196, 190, 186), 184: (173, 157, 163, 147), + 185: (197, 175, 158, 137), 186: (102, 129, 98, 126), 187: (131, 216, 121, 198), + 188: (127, 135, 115, 130), 189: (139, 196, 94, 111), 190: (132, 106, 123, 94), + 191: (219, 130, 193, 116), 192: (212, 133, 127, 124), 193: (196, 176, 173, 151), + 194: (56, 192, 15, 27), 195: (129, 198, 124, 131), 196: (131, 124, 125, 99), + 197: (176, 130, 169, 126), 198: (137, 127, 121, 111), 199: (144, 137, 131, 123), + 200: (132, 130, 114, 120), 201: (182, 165, 169, 153), 202: (138, 136, 113, 109), + 203: (185, 172, 179, 164), 204: (131, 127, 123, 81), 205: (124, 141, 121, 137), + 206: (173, 131, 136, 92), 208: (120, 133, 108, 123), 209: (147, 134, 123, 110), + 210: (130, 142, 125, 129), 211: (136, 137, 122, 131), 212: (130, 119, 127, 114), + 214: (117, 136, 111, 131), 215: (199, 181, 187, 167), 216: (132, 215, 124, 125), + 217: (135, 138, 120, 114), 218: (131, 85, 123, 45), 219: (197, 131, 193, 126), + 221: (69, 206, 57, 195), 223: (161, 156, 96, 92), 225: (130, 136, 123, 121), + 226: (126, 60, 118, 46), 227: (139, 137, 120, 124), 228: (140, 130, 124, 123), + 229: (122, 127, 118, 123), 231: (130, 141, 127, 138), 232: (54, 205, 50, 185), + 233: (75, 74, 69, 68), 234: (223, 130, 217, 125), 235: (111, 129, 108, 127), + 236: (160, 129, 157, 126), 237: (129, 217, 126, 217), 238: (148, 128, 146, 126), + 239: (130, 129, 127, 118), 241: (60, 200, 50, 200), 242: (131, 130, 120, 124), + 243: (123, 132, 116, 127), 244: (132, 135, 130, 132), 245: (129, 41, 126, 37), + 246: (122, 133, 120, 133), 247: (118, 128, 116, 126), 248: (136, 128, 133, 126), + 249: (128, 133, 123, 131), 250: (82, 81, 78, 77), 251: (124, 130, 122, 128), + 252: (130, 130, 125, 124), 253: (128, 128, 127, 127), 254: (127, 126, 126, 125), + 255: (129, 127, 128, 126), +} diff --git a/tools/bink_index.py b/tools/bink_index.py index 5d633c4c7..92597ea2e 100644 --- a/tools/bink_index.py +++ b/tools/bink_index.py @@ -282,6 +282,9 @@ def main(argv=None): ap.add_argument("--format", choices=["csv", "json"], help="inferred from --out if omitted") ap.add_argument("--probe", action="store_true", help="run ffprobe on each stream") a = ap.parse_args(argv) + if not os.path.exists(a.target): + print(f"bink_index: error: {a.target}: no such file or directory", file=sys.stderr) + return 2 rows, summary = scan_target(a.target) probe = False @@ -309,7 +312,9 @@ def main(argv=None): "streams": [_flat(r, fields) for r in rows]}, indent=1)) else: fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) - writer = csv.DictWriter(sys.stdout, fieldnames=fields) + # stdout is a text stream that already turns "\n" into the platform's line end; + # csv's default "\r\n" would come out as "\r\r\n" on Windows + writer = csv.DictWriter(sys.stdout, fieldnames=fields, lineterminator="\n") writer.writeheader() for row in rows: writer.writerow(_flat(row, fields)) diff --git a/tools/bvh_index.py b/tools/bvh_index.py index 04781b008..f6c64875c 100644 --- a/tools/bvh_index.py +++ b/tools/bvh_index.py @@ -5,13 +5,15 @@ does not try. It walks the data area, decompresses every zlib stream that decode classifies the inflated bytes from their headers. Nothing it writes contains game payload bytes: the rows hold offsets, sizes, counts, a header tag and a bounding box. -The one signature it relies on was measured over the whole `*_bvh4` pack: a BVH stream has the 32-bit tag -0x81020006 at offset 0x100, a size in 64-byte units at 0x104, and pointers at 0x20/0x28 such that +The one signature it relies on was measured over the whole `*_bvh4` pack: a BVH stream has `flags = 0x81020006` +at offset 0x100, `totalSizeIn64BNodes` at 0x104, and wrapper words at 0x20/0x28 such that - 0x140 + 64 * size_in_64b_units == u32@0x20 and u32@0x28 == u32@0x20 - 0x100 + 0x140 + 64 * totalSizeIn64BNodes == u32@0x20 and u32@0x28 == u32@0x20 - 0x100 -A stream is reported as `bvh4` only when all of that holds. A 208-byte instance record is reported separately: it -has the constant descriptor words listed in INSTANCE_WORDS and a 3x4 float matrix at 0x50. +A stream is reported as `bvh4` only when all of that holds. The row also carries the exact XboxBvh4Header fields: +`crc32`, `numElements`, scene bounds, `offsetToNodes`, `offsetToPrimRemap`, `rootNodePtr`, `offsetToElements`, +`offsetToParents`, `compressionParams`, and the decoded root node index/type. A 208-byte instance record is +reported separately: it has the constant descriptor words listed in INSTANCE_WORDS and a 3x4 float matrix at 0x50. Usage: python -I tools/bvh_index.py [--out index.json] [--csv index.csv] @@ -38,8 +40,11 @@ HEAD = 0x140 TAG_OFF = 0x100 N_OFF = 0x104 END_OFF = 0x20 -ROOT_OFF = 0x28 +TAIL_OFF = 0x28 AABB_OFF = 0x110 +INVALID_NODE = 0xFFFFFFFF +NODE_TYPE_NAMES = {0: "tri0", 1: "tri1", 2: "tri2", 3: "tri3", + 4: "box16", 5: "box32", 6: "instance", 7: "aabb_geometry"} INSTANCE_WORDS = ((0x08, 0x50000080), (0x10, 1), (0x18, 0x500000A0), (0x20, 0x60000000), (0x28, 0x500000B0), (0x30, 0x500000C0), (0x38, 0x50000050)) FILL_BYTES = (0x00, 0x81, 0x94, 0x29) @@ -52,6 +57,49 @@ def below_normal(): k.SetPriorityClass(k.GetCurrentProcess(), 0x00004000) +def decode_node_pointer(value): + """Decode the low three type bits and the high 29-bit 64-byte node index.""" + typ = value & 7 + return {"ptr": value, "index": value >> 3, "type": typ, + "name": NODE_TYPE_NAMES.get(typ, "invalid"), "invalid": value == INVALID_NODE} + + +def parse_header(head): + """Parse the 64-byte XboxBvh4Header at payload offset 0x100. + + The field names and offsets match the public XboxBvh4Header used by the Xbox DXR traversal + shaders. The offsets in the header are relative to 0x100, the start of this header. + """ + if len(head) < HEAD or struct.unpack_from("= HEAD and len(head) >= HEAD and struct.unpack_from(" 0). Registers not initialized by the caller read as zero, matching the translator's deterministic register arrays. @@ -81,6 +85,11 @@ SUPPORTED_OPS = { "s_mov_b32", "s_add_u32", "s_lshl_b32", "s_lshr_b32", "v_mov_b32", "v_cndmask_b32", "v_and_b32", "v_or_b32", "v_xor_b32", "v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32", + "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_mul_u32_u24", "v_mul_i32_i24", + "v_mul_lo_u32", "v_mul_hi_u32", "v_mul_hi_i32", "v_mad_u32_u24", "v_mad_i32_i24", + "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32", + "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_alignbit_b32", "v_alignbyte_b32", + "v_perm_b32", "v_med3_i32", "v_med3_u32", "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", "s_endpgm", } @@ -551,6 +560,116 @@ class Machine: signed = value - (1 << 32) if value & SIGN32 else value r = (signed >> shift) & MASK32 self._write_vgpr(args[0], lane, r) + elif base in ("v_add_nc_u32", "v_sub_nc_u32", "v_mul_u32_u24", "v_mul_lo_u32", + "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32"): + self._expect(ins, 3) + for lane in self._active_lanes(): + a = self._int_src(args[1], lane) + b = self._int_src(args[2], lane) + if base == "v_add_nc_u32": + r = (a + b) & MASK32 + elif base == "v_sub_nc_u32": + r = (a - b) & MASK32 + elif base == "v_mul_u32_u24": + r = ((a & 0xFFFFFF) * (b & 0xFFFFFF)) & MASK32 + elif base == "v_mul_lo_u32": + r = (a * b) & MASK32 + elif base in ("v_min_u32", "v_max_u32"): + r = (max if base == "v_max_u32" else min)(a, b) + else: + sa = a - (1 << 32) if a & SIGN32 else a + sb = b - (1 << 32) if b & SIGN32 else b + r = (max if base == "v_max_i32" else min)(sa, sb) & MASK32 + self._write_vgpr(args[0], lane, r) + elif base == "v_subrev_nc_u32": + self._expect(ins, 3) + for lane in self._active_lanes(): + a = self._int_src(args[1], lane) + b = self._int_src(args[2], lane) + self._write_vgpr(args[0], lane, (b - a) & MASK32) + elif base in ("v_mul_hi_u32", "v_mul_hi_i32"): + self._expect(ins, 3) + for lane in self._active_lanes(): + a = self._int_src(args[1], lane) + b = self._int_src(args[2], lane) + if base == "v_mul_hi_i32": + a = a - (1 << 32) if a & SIGN32 else a + b = b - (1 << 32) if b & SIGN32 else b + self._write_vgpr(args[0], lane, ((a * b) >> 32) & MASK32) + elif base in ("v_mad_u32_u24", "v_mad_i32_i24"): + self._expect(ins, 4) + for lane in self._active_lanes(): + x = self._int_src(args[1], lane) & 0xFFFFFF + y = self._int_src(args[2], lane) & 0xFFFFFF + if base == "v_mad_i32_i24": + x = x - (1 << 24) if x & 0x800000 else x + y = y - (1 << 24) if y & 0x800000 else y + z = self._int_src(args[3], lane) + self._write_vgpr(args[0], lane, (x * y + z) & MASK32) + elif base == "v_mul_i32_i24": + self._expect(ins, 3) + for lane in self._active_lanes(): + x = self._int_src(args[1], lane) & 0xFFFFFF + y = self._int_src(args[2], lane) & 0xFFFFFF + sx = x - (1 << 24) if x & 0x800000 else x + sy = y - (1 << 24) if y & 0x800000 else y + self._write_vgpr(args[0], lane, (sx * sy) & MASK32) + elif base in ("v_bfe_u32", "v_bfe_i32"): + self._expect(ins, 4) + for lane in self._active_lanes(): + value = self._int_src(args[1], lane) + off = self._int_src(args[2], lane) & 31 + width = min(self._int_src(args[3], lane) & 31, 32 - off) + if width == 0: + r = 0 + else: + r = (value >> off) & ((1 << width) - 1) + if base == "v_bfe_i32" and r & (1 << (width - 1)): + r = (r - (1 << width)) & MASK32 + self._write_vgpr(args[0], lane, r) + elif base == "v_bfi_b32": + self._expect(ins, 4) + for lane in self._active_lanes(): + x = self._int_src(args[1], lane) + y = self._int_src(args[2], lane) + z = self._int_src(args[3], lane) + self._write_vgpr(args[0], lane, (x & y) | (~x & z)) + elif base in ("v_alignbit_b32", "v_alignbyte_b32"): + self._expect(ins, 4) + for lane in self._active_lanes(): + hi = self._int_src(args[1], lane) + lo = self._int_src(args[2], lane) + shift = self._int_src(args[3], lane) + shift = (shift & 31) if base == "v_alignbit_b32" else (shift & 3) * 8 + self._write_vgpr(args[0], lane, (((hi << 32) | lo) >> shift) & MASK32) + elif base == "v_perm_b32": + self._expect(ins, 4) + for lane in self._active_lanes(): + hi = self._int_src(args[1], lane) + lo = self._int_src(args[2], lane) + sel = self._int_src(args[3], lane) + packed = (hi << 32) | lo + r = 0 + for i in range(4): + sb = (sel >> (8 * i)) & 0xFF + if sb < 8: + val = (packed >> (8 * (sb & 7))) & 0xFF + elif sb < 12: + k = sb & 3 + src = lo if k < 2 else hi + val = 0xFF if (src >> (15 + 8 * (k & 1))) & 1 else 0 + else: + val = 0 if sb == 12 else 0xFF + r |= val << (8 * i) + self._write_vgpr(args[0], lane, r) + elif base in ("v_med3_i32", "v_med3_u32"): + self._expect(ins, 4) + for lane in self._active_lanes(): + vals = [self._int_src(args[i], lane) for i in (1, 2, 3)] + if base == "v_med3_i32": + vals = [v - (1 << 32) if v & SIGN32 else v for v in vals] + x, y, z = vals + self._write_vgpr(args[0], lane, max(min(x, y), min(max(x, y), z)) & MASK32) elif base == "s_mov_b32": self._expect(ins, 2) self._write_scalar_dst(args[0], self._int_src(args[1], 0, scalar=True)) diff --git a/tools/feature_scan.py b/tools/feature_scan.py index 32f385e94..1becef3a7 100644 --- a/tools/feature_scan.py +++ b/tools/feature_scan.py @@ -46,6 +46,8 @@ WATCHED = ("WAVE_MMA", "SHADING_RATE", "VIEW_ID", "ROVS", "STENCIL_REF", "INNER_ ALL_STAGES = ("vs", "ps", "gs", "hs", "ds", "cs", "ms", "as", "lib") MMA = re.compile(r"^\s*(v_mfma\w*|v_wmma\w*|v_smfmac\w*)\b") +# Ordered count, GWS and the GS-register adds are the GDS-side instructions NGG stream output relies on. ds_append / +# ds_consume are included as the other counter-style DS ops (LDS unless they carry `gds`, which GDS below catches). ORDERED = re.compile(r"^\s*(ds_ordered_count|ds_gws_\w+|ds_append|ds_consume|ds_add_gs_reg\w*|ds_sub_gs_reg\w*)\b") GDS = re.compile(r"^\s*ds_\w+\b[^;]*\bgds\b") diff --git a/tools/gamedata_graph.py b/tools/gamedata_graph.py new file mode 100644 index 000000000..8d76c4a11 --- /dev/null +++ b/tools/gamedata_graph.py @@ -0,0 +1,509 @@ +"""Build a content-set and reference graph for the ``common.rpf`` XML catalog. + +``gamedata_xml.py`` catalogs the XML documents recovered from an RPF9 carve and counts reference +tokens, but it drops the target strings. This tool keeps them long enough to build and measure a +directed graph: + + python -I gamedata_graph.py [--json FILE] + python -I gamedata_graph.py [ ...] [--json FILE] + +A carve directory is read through ``gamedata_xml.load_documents``, so multi-stream documents are +rebuilt the same way as the index and catalog. For each parsed document the graph has: + +* a document node; +* a content-set node for every ```` (a top-level id or an id inside ````); +* a target node for every ````, ````, ``parentPath`` and ``parentFile`` value. + +Edges are ``defines`` (document to its sets), ``includes`` (document to an ```` id), +``contains_file`` (set or document to a filename target), ``loads_changeset`` (document to a +```` target), and ``parent_path`` / ``parent_file`` for the two attributes. An include is +joined to a document only when its text equals a set id exactly. Missing ids become dangling +content-set nodes. They are never guessed from a similar spelling. + +The four documented prefix rules are measured: ``$(common)``, ``$(root)``, ``$(target)``, and +``platform:/`` split into ``levels`` and everything else. ``common:/`` occurs in the corpus but is +not one of those rules, so it is reported as an unrecognized scheme and is not normalized to +``$(common)``. ``parentPath`` values are XPath-like locators, not archive paths. + +The output is aggregate and schema-only: counts, root names, category names and reference prefixes. +Target strings, ids, offsets, source names and element values are never written. This keeps the JSON reviewable without copying game data, and the tests are +synthetic. The encrypted RPF9 table of contents is still the reason an archive path cannot be +mapped to a carved document; those targets remain target nodes rather than invented document +edges. This is a mount/reference graph, not a full runtime schema: the catalog carries names and +categories, not field types. +""" +import argparse +import json +import os +import re +import sys +import xml.etree.ElementTree as ET +from collections import Counter, defaultdict, deque + +ROOT = os.path.dirname(os.path.abspath(__file__)) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +import gamedata_xml as gx # noqa: E402 + +MANIFEST_ROOTS = ("CDataFileMgr__ContentChangeSetDef", "CDataFileMgr__ContentDef") +MANIFEST_ROOT_SET = frozenset(MANIFEST_ROOTS) +KNOWN_MACROS = frozenset(("common", "target", "root")) +PARENT_ATTRIBUTES = ("parentPath", "parentFile") + +MACRO_REF = re.compile(r"^\$\(([A-Za-z_][\w.-]*)\)(.*)$", re.S) +PLATFORM_REF = re.compile(r"^platform:/([^/]*)(.*)$", re.I | re.S) +SCHEME_REF = re.compile(r"^([A-Za-z][\w.-]*):/(.*)$", re.S) +RELATIVE = "relative/locator" + + +def classify_target(text: str) -> tuple: + """Return (namespace, remainder, resolution reason) for one reference string.""" + value = text.strip() + match = MACRO_REF.match(value) + if match: + name = match.group(1) + namespace = "$(" + name + ")" + remainder = match.group(2).lstrip("/") + if name.lower() in KNOWN_MACROS: + return namespace, remainder, "document_unmapped" + return namespace, remainder, "unknown_macro" + match = PLATFORM_REF.match(value) + if match: + first = (match.group(1) or "").lower() + namespace = "platform:/levels" if first == "levels" else "platform:/other" + return namespace, (match.group(1) or "") + match.group(2), "document_unmapped" + match = SCHEME_REF.match(value) + if match: + return match.group(1).lower() + ":/", match.group(2), "unrecognized_prefix" + return RELATIVE, value, "relative_locator" + + +def _text(element) -> str: + return (element.text or "").strip() if element is not None else "" + + +def _direct_id(element) -> str: + for child in element: + if child.tag == "id": + value = _text(child) + if value: + return value + return "" + + +def _add_filename_refs(report: dict, file_list, owner: str) -> None: + if file_list is None: + return + for filename in file_list.iter("filename"): + value = _text(filename) + if value: + report["refs"].append({"kind": "filename", "target": value, "owner": owner}) + + +def scan_document(doc: dict) -> dict: + """Parse one payload and keep only the graph-relevant names and reference strings.""" + report = { + "root": "", + "parsed": False, + "complete": bool(doc.get("complete", False)), + "sets": [], + "refs": [], + "includes": [], + } + try: + root = ET.fromstring(doc["data"]) + except (ET.ParseError, ValueError): + # A truncated tail can still carry a closing-root hint from the index. It is a named but + # unparsed document, not a rootless fragment; only an empty hint is rootless. + report["root"] = doc.get("root_hint") or "" + return report + report["parsed"] = True + report["root"] = root.tag + report["complete"] = bool(doc.get("complete", True)) + + own = _direct_id(root) + if own: + report["sets"].append(own) + + content_sets = root.find("contentSets") + if content_sets is not None: + for item in content_sets: + set_id = _direct_id(item) + if set_id: + report["sets"].append(set_id) + + seen = set() + report["sets"] = [set_id for set_id in report["sets"] + if not (set_id in seen or seen.add(set_id))] + + _add_filename_refs(report, root.find("fileList"), own) + + if content_sets is not None: + for item in content_sets: + set_id = _direct_id(item) + if set_id: + _add_filename_refs(report, item.find("fileList"), set_id) + + changesets = root.find("includedChangesets") + if changesets is not None: + for load_path in changesets.iter("loadPath"): + value = _text(load_path) + if value: + report["refs"].append({"kind": "loadPath", "target": value, "owner": ""}) + + included = root.find("includedSets") + if included is not None: + for item in included: + value = "".join(item.itertext()).strip() + if value: + report["includes"].append(value) + + for element in root.iter(): + for attribute in PARENT_ATTRIBUTES: + value = (element.attrib.get(attribute) or "").strip() + if value: + report["refs"].append({"kind": attribute, "target": value, "owner": ""}) + return report + + +def _strongly_connected(nodes: list, adjacency: dict) -> list: + """Tarjan's algorithm; recursion depth is bounded by the document count.""" + index = {} + low = {} + stack = [] + on_stack = set() + components = [] + counter = 0 + + def visit(node): + nonlocal counter + index[node] = low[node] = counter + counter += 1 + stack.append(node) + on_stack.add(node) + for neighbour in adjacency.get(node, ()): + if neighbour not in index: + visit(neighbour) + low[node] = min(low[node], low[neighbour]) + elif neighbour in on_stack: + low[node] = min(low[node], index[neighbour]) + if low[node] == index[node]: + component = [] + while True: + member = stack.pop() + on_stack.discard(member) + component.append(member) + if member == node: + break + components.append(component) + + for node in nodes: + if node not in index: + visit(node) + return components + + +def build_graph(documents: list) -> dict: + """Build nodes, edges, unresolved buckets and aggregates from scanned documents.""" + reports = [scan_document(doc) for doc in documents] + set_docs = defaultdict(list) + all_set_ids = set() + for index, report in enumerate(reports): + for set_id in report["sets"]: + set_docs[set_id].append(index) + all_set_ids.add(set_id) + for set_id in report["includes"]: + all_set_ids.add(set_id) + + target_ids = {} + for report in reports: + for ref in report["refs"]: + namespace, remainder, _ = classify_target(ref["target"]) + key = (namespace, remainder) + if key not in target_ids: + target_ids[key] = len(target_ids) + + edges = Counter() + references = Counter() + prefixes = Counter() + resolution = Counter() + unresolved_sites = Counter() + unresolved_namespaces = defaultdict(Counter) + unique_resolution = defaultdict(set) + target_edges = [] + include_edges = [] + dangling_sets = set() + + for index, report in enumerate(reports): + for set_id in report["sets"]: + edges["defines"] += 1 + for set_id in report["includes"]: + references["includedSets"] += 1 + edges["includes"] += 1 + if set_id in set_docs: + resolution["document"] += 1 + for target_doc in set_docs[set_id]: + include_edges.append((index, target_doc)) + else: + resolution["include_id_missing"] += 1 + unresolved_sites["include_id_missing"] += 1 + dangling_sets.add(set_id) + + for ref in report["refs"]: + kind = ref["kind"] + namespace, remainder, reason = classify_target(ref["target"]) + references[kind] += 1 + prefixes[namespace] += 1 + resolution[reason] += 1 + unique_resolution[reason].add((namespace, remainder)) + if reason == "document_unmapped": + unresolved_sites["document_unmapped"] += 1 + unresolved_namespaces["document_unmapped"][namespace] += 1 + elif reason == "unrecognized_prefix": + unresolved_sites["unrecognized_prefix"] += 1 + unresolved_namespaces["unrecognized_prefix"][namespace] += 1 + elif reason == "unknown_macro": + unresolved_sites["unknown_macro"] += 1 + unresolved_namespaces["unknown_macro"][namespace] += 1 + elif reason == "relative_locator": + unresolved_sites["relative_locator"] += 1 + if kind == "filename": + edges["contains_file"] += 1 + edge_kind = "contains_file" + elif kind == "loadPath": + edges["loads_changeset"] += 1 + edge_kind = "loads_changeset" + elif kind == "parentPath": + edges["parent_path"] += 1 + edge_kind = "parent_path" + else: + edges["parent_file"] += 1 + edge_kind = "parent_file" + target_edges.append((index, ref["owner"], edge_kind, (namespace, remainder))) + + include_edges = sorted(set(include_edges)) + adjacency = defaultdict(set) + for source, target in include_edges: + adjacency[source].add(target) + in_degree = Counter() + for _, target in include_edges: + in_degree[target] += 1 + + manifest_documents = [index for index, report in enumerate(reports) + if report["parsed"] and report["root"] in MANIFEST_ROOT_SET] + roots = [index for index in manifest_documents if in_degree[index] == 0] + root_fallback = False + if not roots and manifest_documents: + roots = list(manifest_documents) + root_fallback = True + + depth = {index: 0 for index in roots} + queue = deque(roots) + reachable_docs = set() + while queue: + source = queue.popleft() + if source in reachable_docs: + continue + reachable_docs.add(source) + for target in adjacency.get(source, ()): + if target not in depth: + depth[target] = depth[source] + 1 + queue.append(target) + + components = _strongly_connected(list(range(len(reports))), adjacency) + cycle_components = [component for component in components + if len(component) > 1 or component[0] in adjacency.get(component[0], ())] + cycle_nodes = sum(len(component) for component in cycle_components) + + reachable_sets = set() + reachable_targets = set() + reachable_target_sites = 0 + for index in reachable_docs: + report = reports[index] + reachable_sets.update(report["sets"]) + reachable_sets.update(report["includes"]) + for index, owner, _, key in target_edges: + if index in reachable_docs and (not owner or owner in reachable_sets): + reachable_target_sites += 1 + reachable_targets.add(key) + + category_stats = defaultdict(Counter) + root_stats = defaultdict(Counter) + for report in reports: + root = report["root"] + category = gx.category_for(root) if root else gx.UNCATALOGUED + for stats in (category_stats[category], root_stats[root]): + stats["documents"] += 1 + stats["parsed"] += int(report["parsed"]) + stats["complete"] += int(report["complete"]) + stats["content_sets"] += len(report["sets"]) + stats["include_references"] += len(report["includes"]) + stats["target_references"] += len(report["refs"]) + stats["references"] += len(report["refs"]) + len(report["includes"]) + if root in MANIFEST_ROOT_SET: + category_stats[category]["manifest_documents"] += 1 + root_stats[root]["manifest_documents"] += 1 + + # Root names are stable schema names; category is the only derived label. + for root, stats in root_stats.items(): + stats["category"] = gx.category_for(root) if root else gx.UNCATALOGUED + + unique_by_namespace = Counter() + for namespace, _ in target_ids: + unique_by_namespace[namespace] += 1 + + summary = { + "mode": "", + "payloads": len(reports), + "documents": sum(1 for report in reports if report["complete"]), + "parsed": sum(1 for report in reports if report["parsed"]), + "unparsed": sum(1 for report in reports if not report["parsed"]), + "root_count": len([root for root in root_stats if root]), + "rootless": sum(1 for report in reports if not report["root"]), + "manifest_documents": len(manifest_documents), + "manifest_roots": len(MANIFEST_ROOTS), + "content_sets": len(all_set_ids), + "defined_content_sets": len(set_docs), + "dangling_content_sets": len(dangling_sets), + "duplicate_set_ids": sum(1 for indexes in set_docs.values() if len(indexes) > 1), + "reference_sites": sum(references.values()), + "target_sites": sum(references[kind] for kind in + ("filename", "loadPath", "parentPath", "parentFile")), + "include_sites": references["includedSets"], + "references": dict(sorted(references.items())), + "prefixes": dict(sorted(prefixes.items())), + "resolution": dict(sorted(resolution.items())), + "unique": { + "targets": len(target_ids), + "targets_by_namespace": dict(sorted(unique_by_namespace.items())), + "document_unmapped": len(unique_resolution["document_unmapped"]), + "unknown_macro": len(unique_resolution["unknown_macro"]), + "unrecognized_prefix": len(unique_resolution["unrecognized_prefix"]), + "relative_locator": len(unique_resolution["relative_locator"]), + "content_set_ids": len(all_set_ids), + "include_ids": len({set_id for report in reports for set_id in report["includes"]}), + }, + "nodes": { + "documents": len(reports), + "content_sets": len(all_set_ids), + "targets": len(target_ids), + "total": len(reports) + len(all_set_ids) + len(target_ids), + }, + "edges": { + "total": sum(edges.values()), + "defines": edges["defines"], + "includes": edges["includes"], + "contains_file": edges["contains_file"], + "loads_changeset": edges["loads_changeset"], + "parent_path": edges["parent_path"], + "parent_file": edges["parent_file"], + "document_edges": edges["defines"] + edges["includes"], + "target_edges": (edges["contains_file"] + edges["loads_changeset"] + + edges["parent_path"] + edges["parent_file"]), + }, + "content_graph": { + "include_edges": len(include_edges), + "documents_with_incoming_includes": len(in_degree), + "documents_with_outgoing_includes": sum(1 for report in reports + if report["includes"]), + "root_documents": len(roots), + "root_fallback": root_fallback, + "reachable_documents": len(reachable_docs), + "max_depth": max(depth.values(), default=0), + "cycles": len(cycle_components), + "cycle_nodes": cycle_nodes, + }, + "reachable": { + "documents": len(reachable_docs), + "content_sets": len(reachable_sets), + "targets": len(reachable_targets), + "target_sites": reachable_target_sites, + }, + "categories": dict(sorted(category_stats.items(), key=lambda kv: (-kv[1]["documents"], + kv[0]))), + "roots": dict(sorted(root_stats.items(), key=lambda kv: (-kv[1]["documents"], kv[0]))), + } + # Count roots per category from the root table, not from documents. A root belongs to exactly + # one category, so this also checks that the category totals line up with the 118 named roots. + for category, stats in summary["categories"].items(): + stats["roots"] = sum(1 for root in summary["roots"] + if (gx.category_for(root) if root else gx.UNCATALOGUED) == category) + stats.setdefault("manifest_documents", 0) + for stats in summary["roots"].values(): + stats.setdefault("manifest_documents", 0) + stats.setdefault("category", gx.UNCATALOGUED) + + return { + "summary": summary, + "unresolved": { + "document_unmapped": dict(sorted(unresolved_namespaces["document_unmapped"].items())), + "unknown_macro": dict(sorted(unresolved_namespaces["unknown_macro"].items())), + "unrecognized_prefix": dict(sorted(unresolved_namespaces["unrecognized_prefix"].items())), + "relative_locator": unresolved_sites["relative_locator"], + "include_id_missing": unresolved_sites["include_id_missing"], + "total_sites": sum(unresolved_sites.values()), + }, + } + + +def print_summary(graph: dict) -> None: + summary = graph["summary"] + print(f'{summary["payloads"]} payloads ({summary["documents"]} complete, ' + f'{summary["parsed"]} parsed), {summary["manifest_documents"]} manifest documents') + print(f'{summary["content_sets"]} content-set ids ' + f'({summary["defined_content_sets"]} defined, ' + f'{summary["dangling_content_sets"]} dangling, ' + f'{summary["duplicate_set_ids"]} duplicate)') + print(f'{summary["reference_sites"]:,} reference sites: ' + f'{summary["references"].get("filename", 0):,} filename, ' + f'{summary["references"].get("loadPath", 0)} loadPath, ' + f'{summary["references"].get("parentPath", 0)} parentPath, ' + f'{summary["references"].get("parentFile", 0)} parentFile, ' + f'{summary["include_sites"]} includedSets') + prefixes = ", ".join(f"{name} {count:,}" for name, count in summary["prefixes"].items()) + print(f'prefixes: {prefixes}') + print(f'resolution: {summary["resolution"]}') + print(f'graph: {summary["nodes"]["total"]:,} nodes, {summary["edges"]["total"]:,} edges ' + f'({summary["edges"]["defines"]} defines, {summary["edges"]["includes"]} includes, ' + f'{summary["edges"]["contains_file"]:,} file, ' + f'{summary["edges"]["loads_changeset"]} changeset, ' + f'{summary["edges"]["parent_path"]} parentPath, ' + f'{summary["edges"]["parent_file"]} parentFile)') + content = summary["content_graph"] + print(f'content graph: {content["root_documents"]} roots, ' + f'{content["reachable_documents"]} reachable documents, ' + f'{summary["reachable"]["content_sets"]} sets, depth {content["max_depth"]}, ' + f'{content["cycles"]} cycles') + print(f'reachable: {summary["reachable"]["targets"]:,} unique targets ' + f'({summary["reachable"]["target_sites"]:,} sites)') + unresolved = graph["unresolved"] + print(f'unresolved: {unresolved["total_sites"]:,} sites ' + f'({len(unresolved["document_unmapped"])} archive namespaces, ' + f'{sum(unresolved["unrecognized_prefix"].values())} unknown scheme, ' + f'{unresolved["relative_locator"]} relative, ' + f'{unresolved["include_id_missing"]} missing include id)') + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("targets", nargs="+", help="carve directory or XML file(s)") + parser.add_argument("--json", help="write the aggregate graph summary to this JSON") + args = parser.parse_args() + + try: + documents = list(gx.load_documents(args.targets)) + except FileNotFoundError as exc: + print(f"not found: {exc}", file=sys.stderr) + return 2 + graph = build_graph(documents) + graph["summary"]["mode"] = gx.document_mode(args.targets) + print_summary(graph) + if args.json: + with open(args.json, "w", encoding="utf-8") as f: + json.dump(graph, f, indent=1) + print("wrote", args.json) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py index 503656777..c3c36a56c 100644 --- a/tools/pe_inspect.py +++ b/tools/pe_inspect.py @@ -68,6 +68,8 @@ class PeImage: magic = struct.unpack_from(" len(data): # the fixed fields read below end with DllCharacteristics at +70 + raise PeFormatError("truncated optional header") self.is64 = magic == 0x20B self.entry_rva = struct.unpack_from(" list[str]: addr_names, addr_ordinals) = struct.unpack_from(" list[str]: symbol = img.string_at(struct.unpack_from(" str: def inspect(path: str, game_dir: str | None) -> dict: + """The report for one image. A file cut off inside a table raises PeFormatError like any other bad image; + the struct.error it used to raise escaped main() and stopped a multi-file run at that file.""" + try: + return _inspect(path, game_dir) + except struct.error as e: + raise PeFormatError(f"truncated or corrupt table: {e}") from None + + +def _inspect(path: str, game_dir: str | None) -> dict: with open(path, "rb") as f: img = PeImage(f.read()) sections = [] diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py index 9f91a7045..e27eec545 100644 --- a/tools/rbf0_index.py +++ b/tools/rbf0_index.py @@ -481,12 +481,34 @@ def write_output(path, records, summary, all_strings=False): r["floats"], r["depth"], r["status"], sample]) +def offset(text): + """--start: 0 or more, decimal or 0x hex.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be 0 or more") from None + if value < 0: + raise argparse.ArgumentTypeError("must be 0 or more") + return value + + +def byte_count(text): + """--limit: at least 1; 0 used to mean no limit and a negative value silently scanned less.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be at least 1") from None + if value < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return value + + def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("source", help="an .rpf archive or a directory of carved streams") ap.add_argument("out", help="output path ending in .csv or .json") - ap.add_argument("--start", type=lambda s: int(s, 0), help="first byte to scan (default: the RPF data start)") - ap.add_argument("--limit", type=lambda s: int(s, 0), help="number of bytes to scan") + ap.add_argument("--start", type=offset, help="first byte to scan (default: the RPF data start)") + ap.add_argument("--limit", type=byte_count, help="number of bytes to scan") ap.add_argument("--strings", type=int, default=16, help="readable strings kept per resource (default 16)") ap.add_argument("--all-strings", action="store_true", help="write every readable string to JSON (game data)") ap.add_argument("--quiet", action="store_true") diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index f4df058a5..6a62571cb 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -1200,8 +1200,8 @@ class Gen: self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") - def cmp_class(self, a): - """v_cmp_class_f32 dst, x, mask: true if x's class bit is set in mask. + def cmp_class(self, a, exec_only=False): + """Test x's class against the mask and write the result to VCC/SGPR or EXEC. Bits: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf.""" x, mask = self.src_f(a[-2]), self.src_u(a[-1]) u = self.tou(x) @@ -1241,6 +1241,10 @@ class Gen: hit = b(f"OpLogicalAnd %bool {on} {c}") acc = b(f"OpLogicalOr %bool {acc} {hit}") acc = b(f"OpLogicalAnd %bool {acc} {self.active_b()}") # inactive lanes write 0 + if exec_only: + self.emit(f"OpStore %active {acc}") + self.uses_active = True + return r = b(f"OpSelect %uint {acc} {self.cu(0xFFFFFFFF)} {self.cu(0)}") d = a[0] if len(a) == 2 or (d["k"] == "special" and d["t"] in ("vcc", "vcc_lo")): @@ -2035,8 +2039,8 @@ class Gen: self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) - elif op == "v_cmp_class_f32": - self.cmp_class(a) + elif op in ("v_cmp_class_f32", "v_cmpx_class_f32"): + self.cmp_class(a, exec_only=op == "v_cmpx_class_f32") elif op in ("v_ffbl_b32", "v_ffbh_u32", "s_flbit_i32_b32") or \ (op == "s_ff1_i32_b32" and not self.holds_lane_mask(a[1])): # of a lane mask: further down x = self.src_u(a[1]) @@ -2677,10 +2681,12 @@ class Gen: r = self.tmp() self.emit(f"{r} = OpExtInst %uint %glsl {'SMin' if 'min' in op else 'SMax'} {x} {y}") self.dst(a[0], r) - # SCC = (src0 selected) per ISA; select-src0 iff src0 <= src1 (min) / >= (max) + # SCC = 1 when S0 is the one chosen: the ISA's D = S0 < S1 ? S0 : S1 (min) / S0 > S1 ? S0 : S1 (max) + # picks S1 on a tie, so SCC = S0 < S1 / S0 > S1, compared signed (as s_min_u32/s_max_u32 do unsigned). + # Until 2026-11-21 equal operands set SCC to 1. c, z = self.tmp(), self.tmp() xi, yi = self.as_int(x), self.as_int(y) - self.emit(f"{c} = {'OpSLessThanEqual' if 'min' in op else 'OpSGreaterThanEqual'} %bool {xi} {yi}") + self.emit(f"{c} = {'OpSLessThan' if 'min' in op else 'OpSGreaterThan'} %bool {xi} {yi}") self.emit(f"{z} = OpSelect %uint {c} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") elif op == "v_fma_f16": @@ -3431,15 +3437,36 @@ class Gen: self.emit(f"{r} = OpConvertUToF %float {m}") self.dst(a[0], self.tou(r)) elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"): - x = self.src_f(a[1]) - r = self.tmp() + # Compare binary32 words before converting: the raw SPIR-V conversion + # must only see a representable operand, even when its result is discarded. + bits = self.src_u(a[1]) + zero = self.cu(0) + past_inf = self.cu(0x7F800001) + in_range, saturated, safe, converted, result = (self.tmp() for _ in range(5)) if op == "v_cvt_u32_f32": - self.emit(f"{r} = OpConvertFToU %uint {x}") + positive = self.tmp() + self.emit(f"{in_range} = OpULessThan %bool {bits} {self.cu(0x4F800000)}") # +2^32 + # Positive overflow through +inf saturates. Negative values and NaNs give zero. + self.emit(f"{positive} = OpULessThan %bool {bits} {past_inf}") + self.emit(f"{saturated} = OpSelect %uint {positive} {self.cu(0xFFFFFFFF)} {zero}") else: - i = self.tmp() - self.emit(f"{i} = OpConvertFToS %int {x}") - self.emit(f"{r} = OpBitcast %uint {i}") - self.dst(a[0], r) + magnitude, negative, not_nan, bound = (self.tmp() for _ in range(4)) + self.emit(f"{magnitude} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") + self.emit(f"{in_range} = OpULessThan %bool {magnitude} {self.cu(0x4F000000)}") # 2^31 + self.emit(f"{negative} = OpINotEqual %bool {bits} {magnitude}") + self.emit(f"{not_nan} = OpULessThan %bool {magnitude} {past_inf}") + self.emit(f"{bound} = OpSelect %uint {negative} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") + self.emit(f"{saturated} = OpSelect %uint {not_nan} {bound} {zero}") + self.emit(f"{safe} = OpSelect %uint {in_range} {bits} {zero}") + x = self.tof(safe) + if op == "v_cvt_u32_f32": + self.emit(f"{converted} = OpConvertFToU %uint {x}") + else: + signed = self.tmp() + self.emit(f"{signed} = OpConvertFToS %int {x}") + self.emit(f"{converted} = OpBitcast %uint {signed}") + self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") + self.dst(a[0], result) elif op in U2 or op in S2: x, y = self.src_u(a[1]), self.src_u(a[2]) r = self.tmp() @@ -5560,9 +5587,65 @@ def assemble(gen): "%live = OpLabel\n OpReturn\n OpFunctionEnd\n") else: tail = end_lock + " OpReturn\n OpFunctionEnd\n" - return no_contraction(dedupe_types( + return split_big_switch(no_contraction(dedupe_types( "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + - "\n" + "\n".join(gen.body) + "\n" + tail)) + "\n" + "\n".join(gen.body) + "\n" + tail))) + + +# SPIR-V caps an instruction at 65,535 words. The dispatch loop's OpSwitch has one (literal, label) pair per block, +# and with --wave64-emulate the two ScreenProbes compute shaders reach ~37k blocks (74k words). Past the limit the +# switch becomes two levels: an outer one on pc / SWITCH_CHUNK picks a chunk; each chunk is its own selection +# construct (inner OpSwitch on pc, merge %swm), and that chunk's blocks branch to %swm, which goes on to +# %sw_merge. Every block keeps its label and code, so only the routing changes. +SWITCH_CHUNK = 16000 # spirv-val also caps a switch at 16,383 (literal, label) pairs +_BIG_SWITCH = re.compile(r"^(\s*)OpSwitch %pcv %sw_default ((?:\d+ %\w+ ?)+)$", re.M) + + +def split_big_switch(text): + m = _BIG_SWITCH.search(text) + if not m: + return text + pairs = m.group(2).split() + cases = [(int(pairs[i]), pairs[i + 1]) for i in range(0, len(pairs), 2)] + if len(cases) <= 16383 and 3 + 2 * len(cases) <= 65535: + return text + ind = m.group(1) + chunk_of = {lbl: v // SWITCH_CHUNK for v, lbl in cases} + chunks = sorted(set(chunk_of.values())) + outer = f"{ind}OpSwitch %pcc %sw_default " + " ".join(f"{k} %swc{k}" for k in chunks) + heads = [] + for k in chunks: + inner = " ".join(f"{v} {lbl}" for v, lbl in cases if chunk_of[lbl] == k) + heads += [f"%swc{k} = OpLabel", f"{ind}OpSelectionMerge %swm{k} None", f"{ind}OpSwitch %pcv %swm{k} {inner}"] + # OpSelectionMerge must stay right before its switch, so the chunk index is computed above it + pre = text[:m.start()] + sel = pre.rfind("OpSelectionMerge %sw_merge None") + sel = pre.rfind("\n", 0, sel) + 1 + pre = pre[:sel] + f"{ind}%pcc = OpUDiv %uint %pcv %c_swchunk\n" + pre[sel:] + lines = pre.split("\n") + [outer] + heads + text[m.end():].split("\n")[1:] + # route each block's exits to its chunk's merge: a block runs from its label to the next case label + out, cur = [], None + for line in lines: + st = line.strip() + if st.endswith("= OpLabel"): + lbl = st.split(" = ")[0] + if lbl in chunk_of: + cur = chunk_of[lbl] + elif lbl in ("%sw_default", "%sw_merge") or lbl.startswith("%swc"): + cur = None + if lbl_is_sw_default(st): + out += [f"%swm{k} = OpLabel\n{ind}OpBranch %sw_merge" for k in chunks] # after every chunk's blocks + if cur is not None and st == "OpBranch %sw_merge": + line = line.replace("OpBranch %sw_merge", f"OpBranch %swm{cur}") + out.append(line) + text = "\n".join(out) + # the chunk-size constant, next to the other uint constants + first = re.search(r"^\s*%\w+ = OpConstant %uint \d+$", text, re.M) + return text[:first.start()] + f"%c_swchunk = OpConstant %uint {SWITCH_CHUNK}\n" + text[first.start():] + + +def lbl_is_sw_default(st): + return st == "%sw_default = OpLabel" _FLOAT_ARITH = re.compile(r"^\s*(%\w+) = Op(?:FMul|FAdd|FSub|FDiv|FNegate|FRem|FMod) ", re.M) diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py index 07fed1239..9cb0d2364 100644 --- a/tools/restofworld_index.py +++ b/tools/restofworld_index.py @@ -328,13 +328,35 @@ def write_output(path, rows, summary): for i, c in enumerate(COLUMNS)]) +def offset(text): + """--start: 0 or more, decimal or 0x hex.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be 0 or more") from None + if value < 0: + raise argparse.ArgumentTypeError("must be 0 or more") + return value + + +def byte_count(text): + """--limit/--max-inflate: at least 1; 0 used to mean no limit.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be at least 1") from None + if value < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return value + + def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("source", help="an .rpf archive or a directory of carved .bin/.bk2 files") ap.add_argument("out", help="output path ending in .csv or .json") - ap.add_argument("--start", type=lambda s: int(s, 0), help="first byte to scan (default: RPF data start)") - ap.add_argument("--limit", type=lambda s: int(s, 0), help="number of bytes to scan") - ap.add_argument("--max-inflate", type=lambda s: int(s, 0), default=MAX_INFLATE, + ap.add_argument("--start", type=offset, help="first byte to scan (default: RPF data start)") + ap.add_argument("--limit", type=byte_count, help="number of bytes to scan") + ap.add_argument("--max-inflate", type=byte_count, default=MAX_INFLATE, help="skip a stream that inflates above this many bytes (default: 512 MiB)") ap.add_argument("--quiet", action="store_true") args = ap.parse_args() diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py index 27326071e..8d92b8c11 100644 --- a/tools/rpf9_carve.py +++ b/tools/rpf9_carve.py @@ -28,12 +28,34 @@ def below_normal(): k.SetPriorityClass(k.GetCurrentProcess(), 0x00004000) +def offset(text): + """--start: 0 or more, decimal or 0x hex.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be 0 or more") from None + if value < 0: + raise argparse.ArgumentTypeError("must be 0 or more") + return value + + +def byte_count(text): + """--limit: at least 1; 0 used to mean no limit and a negative value silently scanned less.""" + try: + value = int(text, 0) + except ValueError: + raise argparse.ArgumentTypeError("must be at least 1") from None + if value < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return value + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("archive") ap.add_argument("out") - ap.add_argument("--start", type=int) - ap.add_argument("--limit", type=int) + ap.add_argument("--start", type=offset) + ap.add_argument("--limit", type=byte_count) ap.add_argument("--index-only", action="store_true") a = ap.parse_args() below_normal() diff --git a/tools/shader_carve.py b/tools/shader_carve.py index f1f319211..c5a5bb1aa 100644 --- a/tools/shader_carve.py +++ b/tools/shader_carve.py @@ -25,18 +25,30 @@ RESERVED = {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f" def parts(dxbc: bytes) -> dict: - n = struct.unpack_from(" len(dxbc): + raise ValueError("truncated DXBC part table") out = {} - for k in range(n): - off = struct.unpack_from(" len(dxbc): + raise ValueError("truncated DXBC part payload") + out[fourcc.decode("latin-1")] = (off + 8, size) return out def shader_model(dxbc: bytes, p: dict): if "DXIL" not in p: return None, None - off, _ = p["DXIL"] + off, size = p["DXIL"] + if size < 4: + raise ValueError("truncated DXIL version and stage") ver, kind = struct.unpack_from("> 4}.{ver & 0xF}" @@ -81,8 +93,12 @@ def main() -> int: if data[:4] != b"DXBC" or len(data) != size: bad += 1 continue - p = parts(data) - stage, sm = shader_model(data, p) + try: + p = parts(data) + stage, sm = shader_model(data, p) + except ValueError: + bad += 1 + continue fname = file_name(name, seen, used) with open(os.path.join(out, fname), "wb") as f: f.write(data) diff --git a/tools/shader_diff.py b/tools/shader_diff.py index 0dd1cfb17..e98cdb0ba 100644 --- a/tools/shader_diff.py +++ b/tools/shader_diff.py @@ -76,6 +76,28 @@ def _op_templates(): ("v_lshlrev_b32", lambda r, d, s: f"v_lshlrev_b32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), ("v_lshrrev_b32", lambda r, d, s: f"v_lshrrev_b32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), ("v_ashrrev_i32", lambda r, d, s: f"v_ashrrev_i32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), + ("v_add_nc_u32", lambda r, d, s: f"v_add_nc_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_sub_nc_u32", lambda r, d, s: f"v_sub_nc_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_subrev_nc_u32", lambda r, d, s: f"v_subrev_nc_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_u32_u24", lambda r, d, s: f"v_mul_u32_u24 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_i32_i24", lambda r, d, s: f"v_mul_i32_i24 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_lo_u32", lambda r, d, s: f"v_mul_lo_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_hi_u32", lambda r, d, s: f"v_mul_hi_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mul_hi_i32", lambda r, d, s: f"v_mul_hi_i32 v{d}, v{s[0]}, v{s[1]}"), + ("v_mad_u32_u24", lambda r, d, s: f"v_mad_u32_u24 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_mad_i32_i24", lambda r, d, s: f"v_mad_i32_i24 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_min_u32", lambda r, d, s: f"v_min_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_max_u32", lambda r, d, s: f"v_max_u32 v{d}, v{s[0]}, v{s[1]}"), + ("v_min_i32", lambda r, d, s: f"v_min_i32 v{d}, v{s[0]}, v{s[1]}"), + ("v_max_i32", lambda r, d, s: f"v_max_i32 v{d}, v{s[0]}, v{s[1]}"), + ("v_bfe_u32", lambda r, d, s: f"v_bfe_u32 v{d}, v{s[0]}, {r.randrange(0, 40)}, {r.randrange(0, 40)}"), + ("v_bfe_i32", lambda r, d, s: f"v_bfe_i32 v{d}, v{s[0]}, {r.randrange(0, 40)}, {r.randrange(0, 40)}"), + ("v_bfi_b32", lambda r, d, s: f"v_bfi_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_alignbit_b32", lambda r, d, s: f"v_alignbit_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_alignbyte_b32", lambda r, d, s: f"v_alignbyte_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_perm_b32", lambda r, d, s: f"v_perm_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_med3_i32", lambda r, d, s: f"v_med3_i32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), + ("v_med3_u32", lambda r, d, s: f"v_med3_u32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), ("s_add_u32", lambda r, d, s: f"s_add_u32 s{d}, s{s[0]}, s{s[1]}"), ] @@ -88,7 +110,14 @@ def _op_templates(): # mini-interp (not this runner) re-enables scalar ALU coverage. _VEC_OPS = ("v_mov_b32", "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", "v_and_b32", "v_or_b32", "v_xor_b32", "v_lshlrev_b32", - "v_lshrrev_b32", "v_ashrrev_i32") + "v_lshrrev_b32", "v_ashrrev_i32", + "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_mul_u32_u24", + "v_mul_i32_i24", "v_mul_lo_u32", "v_mul_hi_u32", "v_mul_hi_i32", + "v_mad_u32_u24", "v_mad_i32_i24", "v_min_u32", "v_max_u32", + "v_min_i32", "v_max_i32", + "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_alignbit_b32", + "v_alignbyte_b32", "v_perm_b32", "v_med3_i32", "v_med3_u32") +_FLOAT_OPS = ("v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32") def _seed_value(rng): @@ -113,12 +142,24 @@ def generate_program(rng, n_ops): for s in s_regs: lines.append(f"s_mov_b32 s{s}, {_seed_value(rng) % 256}") vec_ops = [t for t in _op_templates() if t[0] in _VEC_OPS and t[0] != "v_mov_b32"] + # A float op may return any NaN payload (Vulkan does not promise one) and the + # comparison accepts both-NaN. If that value then fed an integer op, the two + # payloads would produce different integer results, so integer ops never read + # the destination of a float op. Every untainted register is bit-identical on + # both oracles; a later integer write clears the taint. + tainted = set() for _ in range(n_ops): name, emit = rng.choice(vec_ops) dst = rng.choice(SCRATCH) - srcs = [rng.choice(SCRATCH) for _ in range(4)] + clean = [v for v in SCRATCH if v not in tainted] + pool = SCRATCH if name in _FLOAT_OPS or not clean else clean + srcs = [rng.choice(pool) for _ in range(4)] lines.append(emit(rng, dst, srcs)) writers[dst] = (name, len(lines)) + if name in _FLOAT_OPS: + tainted.add(dst) + else: + tainted.discard(dst) # Observe one scalar through a VGPR so scalar ops are covered too. lines.append(f"v_mov_b32 v15, s{rng.choice(s_regs)}") writers[15] = ("v_mov_b32/sgpr-copy", len(lines)) diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py index 15c295883..5c0db936b 100644 --- a/tools/ttpf_mips.py +++ b/tools/ttpf_mips.py @@ -6,20 +6,23 @@ first. `TtpfReader` only trusts a hand-validated tuple table and stops at the descriptor's `nonTail` field, which is not the layout boundary. The layout rule lives in `tex_headers.py` (`compact_surface_layout` and the helpers around it); this tool supplies the RDS5 reader, decoders and commands. It computes the layout from the -descriptor, validates it against the native allocation span, then decodes the mips -that are zlib/raw (no BCPack backend is used or guessed). +descriptor, validates it against the native allocation span, then decodes zlib/raw +mips and supported BCPack codecs (BC1, BC3, BC4 and BC5 via `bcpack.py`, strict +confirmed-history mode by default; pass `--allow-provisional` to opt into unconfirmed +built-in history entries). Read-only: no texture bytes are printed or committed. `scan` emits aggregate -counters only. `layout` prints descriptor fields and offsets. `check` prints the -BC block-average error against a 2x2 downsample of the parent mip; it decodes -BC1, BC3, BC4_UNORM and BC5_UNORM (BC2, the SNORM BC4/5 variants, BC6H and BC7 -are sized but not decoded, and uncompressed tiling is not validated). `export` -writes a full BC chain only when every source mip is zlib/raw. +counters only (both the zlib/raw baseline and the BCPack-enabled projection). +`layout` prints descriptor fields and offsets. `check` prints the BC block-average +error against a 2x2 downsample of the parent mip; it decodes BC1, BC3, BC4_UNORM +and BC5_UNORM (BC2, the SNORM BC4/5 variants, BC6H and BC7 are sized but not +decoded, and uncompressed tiling is not validated). `export` writes a full BC chain +when every source mip uses a supported codec. python -I tools/ttpf_mips.py scan [--json out] [--tuples] python -I tools/ttpf_mips.py layout - python -I tools/ttpf_mips.py check - python -I tools/ttpf_mips.py export [--mips N] [--force] + python -I tools/ttpf_mips.py check [--allow-provisional] + python -I tools/ttpf_mips.py export [--mips N] [--force] [--allow-provisional] Standard library only. The RDS5/ETPF checks mirror rpf9-explorer's `TtpfReader` (MIT); the tile patterns and tail formula are the AMD Gfx10 4 KiB/64 KiB layouts @@ -35,6 +38,7 @@ import sys import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bcpack # noqa: E402 from tex_headers import ( # noqa: E402 compact_surface_layout, gfx10_tile_bytes, gfx10_tile_mode, parse_etpf_texture_record, @@ -242,10 +246,10 @@ def decode_pixels(fmt, data, blocks_w, blocks_h): elif fmt in (77, 78): blk = decode_bc1_block(data, at + 8) elif fmt in (80,): - blk = decode_bc4_block(data, (by * blocks_w + bx) * 8, False) + blk = decode_bc4_block(data, (by * blocks_w + bx) * 8) elif fmt in (83,): - a = decode_bc4_block(data, at, False) - b = decode_bc4_block(data, at + 8, False) + a = decode_bc4_block(data, at) + b = decode_bc4_block(data, at + 8) blk = [(p[0], q[0], 0.0) for p, q in zip(a, b)] else: return None @@ -393,22 +397,31 @@ class Pool: def codecs(self, start, size): return {c[4] for c in self.chunks_for(start, size)} - def readable(self, start, size): - return self.codecs(start, size) <= {0, 8} + def readable(self, start, size, *, allow_bcpack=False): + allowed = ({0, 8} | bcpack.SUPPORTED_REBUILD_CODECS) if allow_bcpack else {0, 8} + return self.codecs(start, size) <= allowed - def read_range(self, start, size, cache=None): + def read_range(self, start, size, cache=None, *, bcpack_mode="strict"): + if bcpack_mode not in ("strict", "provisional", "off"): + raise ValueError(f"invalid bcpack_mode: {bcpack_mode!r}") cache = {} if cache is None else cache out = bytearray(size) for virt, csize, src, packed, codec, pad in self.chunks_for(start, size): - key = (src, packed, codec) + key = (src, packed, codec, bcpack_mode if codec not in (0, 8) else "raw") if key not in cache: raw = self.data[src:src + packed] if codec == 0: cache[key] = bytes(raw) elif codec == 8: cache[key] = zlib.decompress(raw) + elif bcpack_mode != "off" and codec in bcpack.SUPPORTED_REBUILD_CODECS: + cache[key] = bcpack.decode( + raw, codec, csize, allow_provisional=(bcpack_mode == "provisional") + ) else: - raise BcpackRequired("range touches a BCPack chunk") + raise BcpackRequired( + f"range touches a BCPack chunk (codec {codec})" + ) if len(cache[key]) != csize: raise ValueError("decoded chunk length disagrees with its range") lo, hi = max(start, virt), min(start + size, virt + csize) @@ -445,7 +458,7 @@ def validated_aux(desc): ELEMENT_BYTES.get(desc["format"]) == a["bytes_b"]))) -def analyze(pool, index): +def analyze(pool, index, *, allow_bcpack=True): """Descriptor + layout + per-mip codec availability for one texture.""" d = pool.descriptor(index) out = dict(descriptor=d, tile_mode=tile_mode(d["mode"]), tile=tile_bytes(d["mode"])) @@ -469,13 +482,19 @@ def analyze(pool, index): out["blocked"] = "layout does not match the allocation span" return out avail = [] + mip_codecs = [] for mip in layout["mips"]: try: - avail.append(pool.readable(d["base"] + mip["offset"], mip["region"])) + codecs = sorted(pool.codecs(d["base"] + mip["offset"], mip["region"])) + mip_codecs.append(codecs) + avail.append(pool.readable(d["base"] + mip["offset"], mip["region"], + allow_bcpack=allow_bcpack)) except ValueError: avail = [] + mip_codecs = [] break out["available"] = avail + out["mip_codecs"] = mip_codecs if avail: limit = d["non_tail"] if compact_row(d) else d["mips"] limit = max(0, min(limit, len(avail))) @@ -518,8 +537,10 @@ def scan_pools(paths, as_json=None, include_tuples=False): compact_rows_measured=0, compact_non_tail_before_tail=0, compact_standalone_beyond_limit=0, compact_standalone_decodable_beyond_limit=0, - compact_full_rows=0, tile_modes={}) + compact_full_rows=0, after_bcpack_full=0, + after_bcpack_partial=0, tile_modes={}) gated_tuples = {} + bcpack_allowed = {0, 8} | bcpack.SUPPORTED_REBUILD_CODECS for path in paths: pool = Pool(path) try: @@ -564,18 +585,36 @@ def scan_pools(paths, as_json=None, include_tuples=False): total["gated_span_mismatch"] += 1 continue avail = [] + avail_bc = [] for mip in layout["mips"]: try: - avail.append(pool.readable(d["base"] + mip["offset"], mip["region"])) + cs = pool.codecs(d["base"] + mip["offset"], mip["region"]) except ValueError: avail = [] + avail_bc = [] break + avail.append(cs <= {0, 8}) + avail_bc.append(cs <= bcpack_allowed) if not avail: total["layout_mismatch"] += 1 if gated: total["whitelist_gated"] += 1 total["gated_unreadable_range"] += 1 continue + if all(avail_bc): + total["after_bcpack_full"] += 1 + else: + ft = layout["first_tail"] + usable_tail_bc = (ft < d["mips"] and all(avail_bc[ft:])) + lim_bc = (d["mips"] if (not compact_row(d) or usable_tail_bc) + else min(ft, len(avail_bc))) + bm_bc = next((k for k in range(lim_bc) if avail_bc[k]), None) + exp_bc = 0 + if bm_bc is not None: + while bm_bc + exp_bc < lim_bc and avail_bc[bm_bc + exp_bc]: + exp_bc += 1 + if exp_bc: + total["after_bcpack_partial"] += 1 if gated: total["whitelist_gated"] += 1 total["gated_layout_ok"] += 1 @@ -665,6 +704,9 @@ def scan_pools(paths, as_json=None, include_tuples=False): total["after_partial"] = (total["reader_partial"] - total["compact_full_rows"] + total["gated_partial"]) total["after_skip"] = total["entries"] - total["after_full"] - total["after_partial"] + total["after_bcpack_skip"] = (total["entries"] - total["after_bcpack_full"] - + total["after_bcpack_partial"]) + total["bcpack_unlocked_full"] = total["after_bcpack_full"] - total["after_full"] if include_tuples: total["gated_tuples"] = [ {"tuple": list(key), "count": count} @@ -689,9 +731,11 @@ def describe(pool, index): out["allocation_span"] = a.get("allocation_span") out["span_matches"] = a.get("span_matches") out["first_tail_mip"] = a["layout"]["first_tail"] + mip_codecs = a.get("mip_codecs") or [] out["mips_detail"] = [ dict(index=m["index"], blocks=[m["blocks_w"], m["blocks_h"]], offset=m["offset"], - region=m["region"], tail=m["in_tail"], tile_origin=[m["tile_x"], m["tile_y"]]) + region=m["region"], tail=m["in_tail"], tile_origin=[m["tile_x"], m["tile_y"]], + **({"codecs": mip_codecs[m["index"]]} if m["index"] < len(mip_codecs) else {})) for m in a["layout"]["mips"]] if "available" in a: out["available"] = a["available"] @@ -703,7 +747,7 @@ def describe(pool, index): return out -def check(pool, index): +def check(pool, index, *, allow_provisional=False): a = analyze(pool, index) if "layout" not in a: print(json.dumps(dict(index=index, blocked=a.get("blocked")), indent=1)) @@ -711,10 +755,17 @@ def check(pool, index): layout = a["layout"] d = a["descriptor"] cache = {} + bcpack_mode = "provisional" if allow_provisional else "strict" try: - tiled = pool.read_range(d["base"], layout["size"], cache) - except BcpackRequired: - print(json.dumps(dict(index=index, blocked="BCPack in allocation"), indent=1)) + tiled = pool.read_range(d["base"], layout["size"], cache, bcpack_mode=bcpack_mode) + except BcpackRequired as exc: + print(json.dumps(dict(index=index, blocked=str(exc)), indent=1)) + return 2 + except bcpack.BcpackProvisionalError as exc: + print(json.dumps(dict( + index=index, + blocked=f"provisional BCPack history required ({exc}); pass --allow-provisional", + ), indent=1)) return 2 decoded, means = [], [] for mip in layout["mips"]: @@ -770,7 +821,7 @@ def dds_bytes(width, height, fmt, mips, linear, payload): return bytes(hdr) + struct.pack(" d["mips"]: @@ -790,10 +841,20 @@ def export(pool, index, out_path, mips=None, force=False): return 2 layout = a["layout"] cache = {} + bcpack_mode = "provisional" if allow_provisional else "strict" payload = bytearray() - for mip in layout["mips"][:count]: - tiled = pool.read_range(d["base"] + mip["offset"], mip["region"], cache) - payload += detile(layout, mip, tiled) + try: + for mip in layout["mips"][:count]: + tiled = pool.read_range(d["base"] + mip["offset"], mip["region"], cache, + bcpack_mode=bcpack_mode) + payload += detile(layout, mip, tiled) + except BcpackRequired as exc: + print(f"texture {index}: {exc}", file=sys.stderr) + return 2 + except bcpack.BcpackProvisionalError as exc: + print(f"texture {index}: provisional BCPack history required ({exc}); " + "pass --allow-provisional", file=sys.stderr) + return 2 if 148 + len(payload) > MAX_OUTPUT: print("DDS exceeds the 256 MiB output limit", file=sys.stderr) return 2 @@ -824,12 +885,16 @@ def main(argv=None): pc = sub.add_parser("check", help="decode a chain and report downsample error") pc.add_argument("pool") pc.add_argument("index", type=int) - pe = sub.add_parser("export", help="write the full zlib/raw chain as DDS") + pc.add_argument("--allow-provisional", action="store_true", + help="allow unconfirmed built-in BCPack history entries") + pe = sub.add_parser("export", help="write the full chain as DDS") pe.add_argument("pool") pe.add_argument("index", type=int) pe.add_argument("out") pe.add_argument("--mips", type=int) pe.add_argument("--force", action="store_true") + pe.add_argument("--allow-provisional", action="store_true", + help="allow unconfirmed built-in BCPack history entries") a = ap.parse_args(argv) if a.cmd == "scan": pools = [] @@ -843,8 +908,9 @@ def main(argv=None): print(json.dumps(describe(pool, a.index), indent=1)) return 0 if a.cmd == "check": - return check(pool, a.index) - return export(pool, a.index, a.out, a.mips, a.force) + return check(pool, a.index, allow_provisional=a.allow_provisional) + return export(pool, a.index, a.out, a.mips, a.force, + allow_provisional=a.allow_provisional) finally: pool.close() diff --git a/tools/world_census.py b/tools/world_census.py index 651733473..e63eef84b 100644 --- a/tools/world_census.py +++ b/tools/world_census.py @@ -495,6 +495,8 @@ def _audit_gap(m, a, b, result, allow_zlib): def _expected_shards(start, end, shard_size): + if shard_size < 1: # pos would never advance, and the list would grow until memory ran out + raise ValueError(f"shard_size must be at least 1, not {shard_size}") out = [] index = 0 pos = start @@ -626,12 +628,23 @@ def summarize(archive, outdir, start, end, shard_size, data_start): return summary +def positive_int(text): + """--shard-size 0 or less never finished planning shards, and --jobs 0 made ProcessPoolExecutor raise.""" + try: + value = int(text) + except ValueError: + raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None + if value < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return value + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("archive") ap.add_argument("--out", default=os.path.join("work", "world", "census")) - ap.add_argument("--shard-size", type=int, default=2 << 30) - ap.add_argument("--jobs", type=int, default=max(1, min(12, (os.cpu_count() or 2) // 2))) + ap.add_argument("--shard-size", type=positive_int, default=2 << 30) + ap.add_argument("--jobs", type=positive_int, default=max(1, min(12, (os.cpu_count() or 2) // 2))) ap.add_argument("--start", type=int) ap.add_argument("--limit", type=int) ap.add_argument("--resume", action="store_true") diff --git a/viewer/index.html b/viewer/index.html index e3996cdc6..ed5d80495 100644 --- a/viewer/index.html +++ b/viewer/index.html @@ -25,7 +25,11 @@
- +
W A S D move · Q/E down/up · Shift fast · Ctrl slow · wheel: speed
F wireframe · T textures/clay · G chunk bounds · R back to spawn · Esc release mouse @@ -44,26 +48,55 @@ import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; // ---------- world description ---------- // world/world.json: { "spawn": [x,y,z], "chunks": [ { "id", "url", "bounds": [minx,miny,minz,maxx,maxy,maxz] } ] } -// Each chunk is a .glb in world space (Y up, metres). When no world.json exists the viewer -// generates TEST terrain locally and says so on screen. -async function loadWorld() { - if (new URLSearchParams(location.search).has("test")) return testWorld(); - try { - const r = await fetch("world/world.json", { cache: "no-store" }); - if (!r.ok) throw new Error(r.status); - const w = await r.json(); - w.test = false; - return w; - } catch { return testWorld(); } +// Each chunk is a .glb in world space (Y up, metres). Validate the manifest before +// the camera and streaming code use its coordinates and chunk identifiers. +function manifestError(world) { + const isPosition = (value, length) => + Array.isArray(value) && value.length === length && value.every(Number.isFinite); + const isNonemptyString = value => typeof value === "string" && value.trim().length > 0; + if (!isPosition(world?.spawn, 3)) return "spawn must contain three finite coordinates"; + if (!Array.isArray(world.chunks)) return "chunks must be an array"; + const ids = new Set(); + for (const [i, chunk] of world.chunks.entries()) { + if (!isNonemptyString(chunk?.id) || ids.has(chunk.id)) return `chunks[${i}].id must be a unique, nonempty string`; + if (!isNonemptyString(chunk.url)) return `chunks[${i}].url must be a nonempty string`; + const b = chunk.bounds; + if (!isPosition(b, 6) || b[0] > b[3] || b[1] > b[4] || b[2] > b[5]) + return `chunks[${i}].bounds must contain six finite, ordered coordinates`; + ids.add(chunk.id); + } + return null; } -function testWorld() { +async function loadWorld() { + if (new URLSearchParams(location.search).has("test")) return testWorld("Test mode was requested."); + let response; + try { + response = await fetch("world/world.json", { cache: "no-store" }); + } catch { + return testWorld("world/world.json could not be loaded."); + } + if (response.status === 404) return testWorld("world/world.json was not found."); + if (!response.ok) return testWorld(`world/world.json returned HTTP ${response.status}.`); + + let world; + try { + world = await response.json(); + } catch { + return testWorld("world/world.json could not be read as valid JSON."); + } + const error = manifestError(world); + if (error) return testWorld(`Invalid world/world.json: ${error}.`); + return { ...world, test: false }; +} + +function testWorld(reason) { const size = 256, n = 24, chunks = []; for (let z = -n / 2; z < n / 2; z++) for (let x = -n / 2; x < n / 2; x++) chunks.push({ id: `test_${x}_${z}`, test: [x, z, size], bounds: [x * size, -50, z * size, (x + 1) * size, 200, (z + 1) * size] }); - return { test: true, spawn: [0, 120, 0], chunks }; + return { test: true, reason, spawn: [0, 120, 0], chunks }; } // Deterministic test terrain: rolling hills plus a grid of boxes. Nothing here comes from the game. @@ -252,11 +285,10 @@ function stream(now = performance.now()) { // ---------- main loop ---------- const world = await loadWorld(); camera.position.fromArray(world.spawn); -const banner = document.getElementById("banner"); -if (world.test) banner.innerHTML = "TEST TERRAIN: generated in the browser. No world/world.json found.
" + - "Build chunks with python -I tools/world_build.py <work>\\assets --out <work>\\world and serve with " + - "python -I viewer/serve.py --world <work>\\world."; -else banner.classList.add("hidden"); +if (world.test) { + document.getElementById("world-status").textContent = world.reason; + document.getElementById("banner").classList.remove("hidden"); +} for (const c of world.chunks) { const b = c.bounds, box = new THREE.Box3(new THREE.Vector3(b[0], b[1], b[2]), new THREE.Vector3(b[3], b[4], b[5])); boundsGroup.add(new THREE.Box3Helper(box, 0x5fb3ff));