fix(gpu,metal): lazily populate texture_buffer views for typed and structured buffers #278

Merged
Sheffy007 merged 1 commit from upstream-pr/278 into main 2026-11-27 13:20:19 +00:00
Sheffy007 commented 2026-11-27 07:52:44 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Sheffy007 on 2026-11-27T07:52:44Z.


What this changes

Refs #255
Refs #258

There are two separate host causes behind indexed buffer accesses on the native Metal backend:

  1. Untyped indexed buffer accesses (!typed, such as buffer_store_dword* ... idxen on a view without static stride metadata) take Lower::view_stride (lower.rs:12595) and read root SRV t255 (VIEW_STRIDES), which #264 binds.
  2. Formatted buffer accesses (typed == true, buffer_load_format_* / buffer_store_format_* and typed-buffer getDimensions) skip view_stride (&& !typed at lower.rs:12595) and lower to DXIL TypedBuffer (bufferLoad.f32, bufferStore.f32, getDimensions). Tested on a small synthetic DXIL program of our own compiled locally through metal-shaderconverter 4.0.3 (not from the title; no listing in the repository or comments), all three operations compile to @air.read_texture_buffer_1d.v4f32, @air.write_texture_buffer_1d.v4f32, and @air.is_null_texture_buffer_1d + @air.get_width_texture_buffer_1d, loading word 1 (textureViewID at byte +8) of the 24-byte IRDescriptorTableEntry, whereas rawBufferStore.i32 (buffer_store_dwordx4) loads word 0 (gpuVA at byte +0).

Metal::write_buffer previously wrote [gpu, 0, size as u64], leaving textureViewID = 0 (a null MTLResourceID). On Apple Silicon, write_texture_buffer_1d to a null texture_buffer is a silent no-op and read_texture_buffer_1d / get_width_texture_buffer_1d return 0.

This PR:

  • Zero-texture mirror() with lazy materialization (PendingTyped + Binding::typed_buffers): NativeHost::mirror continues to call write_buffer (0 MTLTexture allocations at mirror time) and records two pending bits per entry (PendingTyped, ~10 KiB for a 40,000-entry heap; +16 KiB measured phys_footprint delta over raw mirror()). Binding::of scans the DXIL symbol and constant tables once (dxil_uses_typed_buffers) to flag shaders that use bufferLoad, bufferStore, or TypedBuffer getDimensions (Texture2D getDimensions stays false). At draw/dispatch submission, NativeHost::materialize_typed_buffers is a no-op unless a bound stage sets typed_buffers; when set, it promotes only pending entries inside bound Root::Table ranges (plus explicit stride == 0 typed buffer views in the bound heap if the shader also indexes ResourceDescriptorHeap directly), leaving unbound structured buffers unmaterialized.
  • Zero-copy TypeTextureBuffer (ResourceBackend::write_typed_buffer): Creates an MTLTextureType::TypeTextureBuffer view over buffer.buf (aligned to minimumTextureBufferAlignmentForPixelFormat, 16 B on Apple Silicon; warns once and falls back to write_buffer if unaligned) and writes [gpu, tex_id, size as u64], retaining the MTLTexture in Heap::refs while counting only buffer.buf in alloc_counts / MTLResidencySet.
  • Conflict-free with #264: Keeps Decoded::Buffer and descriptors::decode unchanged, adding descriptors::typed_buffer separately and placing NativeHeap::typed_pending disjoint from #264's strides hunks.

How it was tested

  • heap_tests::formatted_buffer_stores_and_loads_through_structured_and_typed_uavs (on Apple Silicon GPU): verifies !Binding::of(&cs_raw).typed_buffers, !Binding::of(&cs_img).typed_buffers (Texture2D getDimensions), Binding::of(&cs_fmt).typed_buffers, lazy materialization (0 typed_views after mirror() and after pso_raw, 1 after pso_fmt, while an unbound structured UAV outside the table stays unmaterialized), and round-trips buffer_store_format_xyzw ... idxen, buffer_load_format_xyzw ... idxen, getDimensions, and raw buffer_store_dwordx4 across 16-byte structured, R32G32B32A32_UINT, R32G32B32A32_FLOAT, R8G8B8A8_UNORM, R16G16B16A16_FLOAT, R16G16B16A16_UINT, R32_SINT (43, negative 0xDEAD_BEEF), and R16G16_SNORM (37).
  • gfx::heap_set_tests::a_heaps_set_follows_its_entries (aligned textureViewID != 0, unaligned +4 fallback textureViewID == 0 with gpuVA intact, and residency-set allocatedSize invariance).
  • Release benchmarks gfx::heap_set_tests::typed_buffer_view_cost_benchmark and heap_tests::world_heap_mirror_lazy_benchmark (Apple M5 Pro, macOS 27.2.1).
  • cargo test -p victory-hle -p victory -p victory-gpu -p victory-metal -p victory-shader -p xtask
  • cargo clippy --workspace --all-targets --target x86_64-pc-windows-gnullvm -- -D warnings (and --all-features)
  • cargo xtask policy
<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:issue:5523147901 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278). Originally posted by [Sheffy007](https://github.com/Sheffy007) on 2026-11-27T07:52:44Z. --- ## What this changes Refs #255 Refs #258 There are two separate host causes behind indexed buffer accesses on the native Metal backend: 1. Untyped indexed buffer accesses (`!typed`, such as `buffer_store_dword* ... idxen` on a view without static stride metadata) take `Lower::view_stride` (`lower.rs:12595`) and read root SRV `t255` (`VIEW_STRIDES`), which #264 binds. 2. **Formatted buffer accesses (`typed == true`, `buffer_load_format_*` / `buffer_store_format_*` and typed-buffer `getDimensions`) skip `view_stride` (`&& !typed` at `lower.rs:12595`) and lower to DXIL `TypedBuffer` (`bufferLoad.f32`, `bufferStore.f32`, `getDimensions`).** Tested on a small synthetic DXIL program of our own compiled locally through `metal-shaderconverter` 4.0.3 (not from the title; no listing in the repository or comments), all three operations compile to `@air.read_texture_buffer_1d.v4f32`, `@air.write_texture_buffer_1d.v4f32`, and `@air.is_null_texture_buffer_1d` + `@air.get_width_texture_buffer_1d`, loading **word 1 (`textureViewID` at byte `+8`)** of the 24-byte `IRDescriptorTableEntry`, whereas `rawBufferStore.i32` (`buffer_store_dwordx4`) loads **word 0 (`gpuVA` at byte `+0`)**. `Metal::write_buffer` previously wrote `[gpu, 0, size as u64]`, leaving `textureViewID = 0` (a null `MTLResourceID`). On Apple Silicon, `write_texture_buffer_1d` to a null `texture_buffer` is a silent no-op and `read_texture_buffer_1d` / `get_width_texture_buffer_1d` return `0`. This PR: - **Zero-texture `mirror()` with lazy materialization (`PendingTyped` + `Binding::typed_buffers`):** `NativeHost::mirror` continues to call `write_buffer` (`0` `MTLTexture` allocations at mirror time) and records two pending bits per entry (`PendingTyped`, `~10 KiB` for a 40,000-entry heap; `+16 KiB` measured `phys_footprint` delta over raw `mirror()`). `Binding::of` scans the DXIL symbol and constant tables once (`dxil_uses_typed_buffers`) to flag shaders that use `bufferLoad`, `bufferStore`, or `TypedBuffer` `getDimensions` (`Texture2D` `getDimensions` stays `false`). At draw/dispatch submission, `NativeHost::materialize_typed_buffers` is a no-op unless a bound stage sets `typed_buffers`; when set, it promotes only pending entries inside bound `Root::Table` ranges (plus explicit `stride == 0` typed buffer views in the bound heap if the shader also indexes `ResourceDescriptorHeap` directly), leaving unbound structured buffers unmaterialized. - **Zero-copy `TypeTextureBuffer` (`ResourceBackend::write_typed_buffer`):** Creates an `MTLTextureType::TypeTextureBuffer` view over `buffer.buf` (aligned to `minimumTextureBufferAlignmentForPixelFormat`, 16 B on Apple Silicon; warns once and falls back to `write_buffer` if unaligned) and writes `[gpu, tex_id, size as u64]`, retaining the `MTLTexture` in `Heap::refs` while counting only `buffer.buf` in `alloc_counts` / `MTLResidencySet`. - **Conflict-free with #264:** Keeps `Decoded::Buffer` and `descriptors::decode` unchanged, adding `descriptors::typed_buffer` separately and placing `NativeHeap::typed_pending` disjoint from #264's `strides` hunks. ## How it was tested - `heap_tests::formatted_buffer_stores_and_loads_through_structured_and_typed_uavs` (on Apple Silicon GPU): verifies `!Binding::of(&cs_raw).typed_buffers`, `!Binding::of(&cs_img).typed_buffers` (`Texture2D` `getDimensions`), `Binding::of(&cs_fmt).typed_buffers`, lazy materialization (`0` `typed_views` after `mirror()` and after `pso_raw`, `1` after `pso_fmt`, while an unbound structured UAV outside the table stays unmaterialized), and round-trips `buffer_store_format_xyzw ... idxen`, `buffer_load_format_xyzw ... idxen`, `getDimensions`, and raw `buffer_store_dwordx4` across 16-byte structured, `R32G32B32A32_UINT`, `R32G32B32A32_FLOAT`, `R8G8B8A8_UNORM`, `R16G16B16A16_FLOAT`, `R16G16B16A16_UINT`, `R32_SINT` (`43`, negative `0xDEAD_BEEF`), and `R16G16_SNORM` (`37`). - `gfx::heap_set_tests::a_heaps_set_follows_its_entries` (aligned `textureViewID != 0`, unaligned `+4` fallback `textureViewID == 0` with `gpuVA` intact, and residency-set `allocatedSize` invariance). - Release benchmarks `gfx::heap_set_tests::typed_buffer_view_cost_benchmark` and `heap_tests::world_heap_mirror_lazy_benchmark` (Apple M5 Pro, macOS 27.2.1). - `cargo test -p victory-hle -p victory -p victory-gpu -p victory-metal -p victory-shader -p xtask` - `cargo clippy --workspace --all-targets --target x86_64-pc-windows-gnullvm -- -D warnings` (and `--all-features`) - `cargo xtask policy`
LakshanSivakumar commented 2026-11-27 08:08:15 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T08:08:15Z.


Thank you. A second cause that the stride table does not touch is what #255 needed, and a GPU test that stores through the same entry both ways is the right test.

Before it can merge:

  1. Cost. It makes one Metal texture per mirrored typed buffer and per 4-, 8- and 16-byte structured buffer entry, and keeps it alive in the heap. A world heap has about 40,000 entries. Please count how many entries get a texture in a world run, and measure the time to mirror and the process footprint before and after, on any Mac you have. I will weigh it for 16 GB (#8, #79).
  2. The guess about structured buffers of 4, 8 and 16 bytes. It is marked, which is right, but it turns on a texture view for every such buffer whether or not a shader reads it by format. Can the view be made lazily, or only for entries a shader that uses format access reads? If not, please say why.
  3. Please say what happens when a view does not start on 16 bytes inside its buffer, and whether the signed formats (SINT) map to the unsigned format on purpose: does the converter take the integer kind from the DXIL type or from the view?
  4. "Closes #255": #255 also needs the stride table in #264, so please write "Refs #255". The two pull requests change the same lines of descriptors.rs and host.rs; please look at #264 and rebase over it once it lands.
  5. Please confirm that the converter output you describe is from your own test program and that no listing from it is in the repository or the comments.
<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7213190517 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278#issuecomment-7213190517). Originally posted by [LakshanSivakumar](https://github.com/LakshanSivakumar) on 2026-11-27T08:08:15Z. --- Thank you. A second cause that the stride table does not touch is what #255 needed, and a GPU test that stores through the same entry both ways is the right test. Before it can merge: 1. Cost. It makes one Metal texture per mirrored typed buffer and per 4-, 8- and 16-byte structured buffer entry, and keeps it alive in the heap. A world heap has about 40,000 entries. Please count how many entries get a texture in a world run, and measure the time to mirror and the process footprint before and after, on any Mac you have. I will weigh it for 16 GB (#8, #79). 2. The guess about structured buffers of 4, 8 and 16 bytes. It is marked, which is right, but it turns on a texture view for every such buffer whether or not a shader reads it by format. Can the view be made lazily, or only for entries a shader that uses format access reads? If not, please say why. 3. Please say what happens when a view does not start on 16 bytes inside its buffer, and whether the signed formats (SINT) map to the unsigned format on purpose: does the converter take the integer kind from the DXIL type or from the view? 4. "Closes #255": #255 also needs the stride table in #264, so please write "Refs #255". The two pull requests change the same lines of `descriptors.rs` and `host.rs`; please look at #264 and rebase over it once it lands. 5. Please confirm that the converter output you describe is from your own test program and that no listing from it is in the repository or the comments.
AnastasisKon commented 2026-11-27 10:18:30 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by AnastasisKon on 2026-11-27T10:18:30Z.


Reviewed this against the translator side, which I've read closely this week — the diagnosis checks out from both ends: formatted accesses lower to DXIL TypedBuffer ops (bufferLoad/Store.f32, getDimensions) while buffer_store_dwordx4 lowers to rawBufferStore.i32, and the native backend decoded every buffer view to a raw range, so the textureViewID word was never written. Your AIR disassembly (word 1 vs word 0 of IRDescriptorTableEntry) explains #255's exact symptom — format stores silently no-op, dwordx4 through the same entry works — and the word-0/word-1 split confirms both can live in one entry.

Three notes, none blocking:

The structured-stride guess is sound for bit-preservation: 4/8/16 → FLOAT keeps raw 32-bit lanes intact, which is what format ops on a stride V# mean on RDNA2 (a structured V# carries no normalized format). Once this merges, a corpus sweep (#282/#286) counting how many shaders take the typed path through structured views would confirm the reach of the guess on real titles.
No interaction with the d16 path: integer_view (the d16 typed store's integer-extension choice) reads the view-stride table at root SRV t255 (#264), not the descriptor entry this PR populates — I checked; the two channels are independent, so nothing changes there.
Coverage gap, minor: the 1- and 2-channel typed formats (R32_UINT via code 43, RG32_UINT via 18, and the SNORM set) are decode-tested but not exercised on the GPU — the GPU test covers only 4-channel formats. If it's cheap, one extra case with buffer_store_format_x through an R32_UINT view would close that; fine as a follow-up too.
The heap_tests GPU test with bit patterns (0xDEADBEEF, signaling NaN) round-tripping through UNORM/FLOAT/UINT views is exactly the right kind of verification for this. Nice work.

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7215726530 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278#issuecomment-7215726530). Originally posted by [AnastasisKon](https://github.com/AnastasisKon) on 2026-11-27T10:18:30Z. --- Reviewed this against the translator side, which I've read closely this week — the diagnosis checks out from both ends: formatted accesses lower to DXIL TypedBuffer ops (bufferLoad/Store.f32, getDimensions) while buffer_store_dwordx4 lowers to rawBufferStore.i32, and the native backend decoded every buffer view to a raw range, so the textureViewID word was never written. Your AIR disassembly (word 1 vs word 0 of IRDescriptorTableEntry) explains #255's exact symptom — format stores silently no-op, dwordx4 through the same entry works — and the word-0/word-1 split confirms both can live in one entry. Three notes, none blocking: The structured-stride guess is sound for bit-preservation: 4/8/16 → FLOAT keeps raw 32-bit lanes intact, which is what format ops on a stride V# mean on RDNA2 (a structured V# carries no normalized format). Once this merges, a corpus sweep (#282/#286) counting how many shaders take the typed path through structured views would confirm the reach of the guess on real titles. No interaction with the d16 path: integer_view (the d16 typed store's integer-extension choice) reads the view-stride table at root SRV t255 (#264), not the descriptor entry this PR populates — I checked; the two channels are independent, so nothing changes there. Coverage gap, minor: the 1- and 2-channel typed formats (R32_UINT via code 43, RG32_UINT via 18, and the SNORM set) are decode-tested but not exercised on the GPU — the GPU test covers only 4-channel formats. If it's cheap, one extra case with buffer_store_format_x through an R32_UINT view would close that; fine as a follow-up too. The heap_tests GPU test with bit patterns (0xDEADBEEF, signaling NaN) round-tripping through UNORM/FLOAT/UINT views is exactly the right kind of verification for this. Nice work.
LakshanSivakumar commented 2026-11-27 10:32:24 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T10:32:24Z.


My five questions above are still open: the count and the cost of the textures in a world run, whether the view can be made lazily, 16-byte alignment and SINT, "Refs #255" instead of "Closes #255", and the confirmation about the converter output.

Another account (AnastasisKon) wrote answers on #115 and a review here. They are not measurements and they are not yours, so I cannot count them. The branch is also behind main, and #264 and #267 move descriptors.rs and host.rs under you.

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7216006138 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278#issuecomment-7216006138). Originally posted by [LakshanSivakumar](https://github.com/LakshanSivakumar) on 2026-11-27T10:32:24Z. --- My five questions above are still open: the count and the cost of the textures in a world run, whether the view can be made lazily, 16-byte alignment and SINT, "Refs #255" instead of "Closes #255", and the confirmation about the converter output. Another account (AnastasisKon) wrote answers on #115 and a review here. They are not measurements and they are not yours, so I cannot count them. The branch is also behind main, and #264 and #267 move `descriptors.rs` and `host.rs` under you.
Sheffy007 commented 2026-11-27 10:48:33 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Sheffy007 on 2026-11-27T10:48:33Z.


Rebased onto c1b95875 (38112699) and addressed all five review points (plus @AnastasisKon's 1- and 2-channel format test suggestion):

  1. Cost & Apple Silicon measurements (#8, #79):
    We do not have the game installed in this environment to count world-run descriptors directly, so we added NativeHost::typed_views() AND switched mirror() to zero-texture lazy materialization, then measured both the eager write_typed_buffer cost per view and the new lazy 40,000-entry mirror() cost on an Apple M5 Pro (48 GB, macOS 27.2.1, --release, task_info(TASK_VM_INFO) phys_footprint; reproducible via cargo test --release -p victory-metal typed_buffer_view_cost_benchmark -- --ignored --nocapture and cargo test --release -p victory-gpu world_heap_mirror_lazy_benchmark -- --ignored --nocapture):

    Path (40,000-entry resource heap) Time phys_footprint delta MTLTextures created heap_set
    Baseline NativeHost::mirror (40,000 raw buffer UAVs) 26.67 ms (0.67 us/entry) baseline 0 3.38 MiB
    New lazy NativeHost::mirror (40,000 structured + typed UAVs) 22.25 ms (0.56 us/entry) +16.0 KiB (~10 KiB PendingTyped bitsets) 0 3.38 MiB
    Materialize 64 write_typed_buffer entries 0.17 ms (2.62 us/view) +240.0 KiB 64 3.38 MiB
    Materialize 512 write_typed_buffer entries 0.56 ms (1.09 us/view) +752.0 KiB 512 3.38 MiB
    Materialize 1,000 write_typed_buffer entries 0.93 ms (0.93 us/view) +688.0 KiB (~0.7 KiB/view) 1,000 3.38 MiB
    Materialize 10,000 write_typed_buffer entries 10.25 ms (1.03 us/view) +15,248.0 KiB (~1.5 KiB/view) 10,000 3.38 MiB
    Eager 40,000 write_typed_buffer entries (previous commit worst case) 36.77 ms (0.92 us/view) +46,320.0 KiB (+45.2 MiB, ~1.2 KiB/view) 40,000 3.38 MiB

    Eager creation across 40,000 entries would have cost ~45.2 MiB of kernel phys_footprint (~1.2 KiB per retained MTLTextureTypeTextureBuffer). With lazy materialization, mirror() creates 0 Metal textures and adds +16 KiB total for a 40,000-entry heap.

  2. Lazy materialization gated on shaders that actually use TypedBuffer:

    • NativeHost::mirror always calls write_buffer ([gpu, 0, size]) and sets two bits per entry in NativeHeap::typed_pending (PendingTyped: typed for all typed and 4-, 8-, or 16-byte structured views; explicit for stride == 0 typed views).
    • Binding::of(shader) scans the module's DXIL TYPE_BLOCK, CONSTANTS_BLOCK, and VALUE_SYMTAB_BLOCK once (list::dxil_uses_typed_buffers) to check whether kept instructions call dx.op.bufferLoad.*, dx.op.bufferStore.*, or dx.op.getDimensions on a TypedBuffer (dx.types.ResourceProperties kind 10 — so Texture2D getDimensions stays false, verified in heap_tests).
    • At draw/dispatch (NativeHost::materialize_typed_buffers), draws and dispatches whose bound stages have typed_buffers == false return immediately. When typed_buffers == true, only pending entries inside the bound Root::Table ranges are promoted via write_typed_buffer (plus explicit stride == 0 typed buffer views in the bound heap when heap_typed_buffers == true), leaving unbound structured buffers across the heap unmaterialized.
  3. Unaligned (< 16 B) buffer offsets & SINT -> UINT mapping:

    • Unaligned offsets: dev.minimumTextureBufferAlignmentForPixelFormat is 16 bytes across all tested formats on Apple Silicon. Calling newTextureWithDescriptor_offset_bytesPerRow at a non-16-byte offset trips Metal validation, so Metal::write_typed_buffer now logs a tracing::warn! on the first unaligned typed buffer view (debug! thereafter) and falls back to write_buffer ([gpu, 0, size]). Raw/structured accesses at word 0 (gpuVA, 4-byte aligned) continue to work; formatted accesses at word 1 read 0 / no-op instead of asserting (gfx::heap_set_tests::a_heaps_set_follows_its_entries now tests an unaligned +4 view).
    • SINT -> UINT: Yes, mapping 32-bit SINT (4, 18, 43) to Uint while leaving 8- and 16-bit SINT (14, 32, 38, 52, 59, 64) unmapped is intentional. victory-shader lowers all formatted buffer loads/stores through float-typed DXIL handles (TypedBuffer<float4>, props = (10 | u, 0x409), bitcast i32 <-> float), so metal-shaderconverter takes v4f32 from the DXIL handle (@air.read/write_texture_buffer_1d.v4f32), while Apple Silicon's texture hardware unpacks/packs according to the MTLTexture view's MTLPixelFormat (proven on GPU by 0x0000_0012 — subnormal float 2.5e-44 — packing to 0x0012 and reading back 0x0000_0012 on RGBA16Uint). For 32-bit channels there is no sub-32-bit sign extension or clamping, so Uint transfers all 32 two's-complement bits identically (now GPU-tested for R32_SINT code 43 with 0xDEAD_BEEF, alongside R16G16_SNORM code 37); 8/16-bit SINT would zero-extend under Uint, so they stay excluded.
  4. Refs #255 & #264 overlap:
    Updated both commit message and PR description to Refs #255, and restructured descriptors.rs, list.rs, and host.rs against #264's diff (Decoded::Buffer and decode are now untouched vs origin/main, typed_buffer sits after sampler, and typed_pending sits after images), eliminating line overlap with #264; happy to rebase again as soon as #264 lands.

  5. Synthetic test program confirmation:
    Confirmed: the llvm-dis inspection of metal-shaderconverter output described here and in #255 was run solely on a small synthetic DXIL test program of our own, never on any game shader or title file, and no listing from it is in the repository or in the comments (cargo xtask policy passes across all 371 files).

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7216330780 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278#issuecomment-7216330780). Originally posted by [Sheffy007](https://github.com/Sheffy007) on 2026-11-27T10:48:33Z. --- Rebased onto `c1b95875` (`38112699`) and addressed all five review points (plus @AnastasisKon's 1- and 2-channel format test suggestion): 1. **Cost & Apple Silicon measurements (`#8`, `#79`):** We do not have the game installed in this environment to count world-run descriptors directly, so we added `NativeHost::typed_views()` AND switched `mirror()` to **zero-texture lazy materialization**, then measured both the eager `write_typed_buffer` cost per view and the new lazy 40,000-entry `mirror()` cost on an Apple M5 Pro (48 GB, macOS 27.2.1, `--release`, `task_info(TASK_VM_INFO)` `phys_footprint`; reproducible via `cargo test --release -p victory-metal typed_buffer_view_cost_benchmark -- --ignored --nocapture` and `cargo test --release -p victory-gpu world_heap_mirror_lazy_benchmark -- --ignored --nocapture`): | Path (40,000-entry resource heap) | Time | `phys_footprint` delta | `MTLTexture`s created | `heap_set` | |---|---:|---:|---:|---:| | Baseline `NativeHost::mirror` (40,000 raw buffer UAVs) | `26.67 ms` (`0.67 us/entry`) | baseline | `0` | `3.38 MiB` | | **New lazy `NativeHost::mirror` (40,000 structured + typed UAVs)** | **`22.25 ms` (`0.56 us/entry`)** | **`+16.0 KiB` (`~10 KiB` `PendingTyped` bitsets)** | **`0`** | `3.38 MiB` | | Materialize `64` `write_typed_buffer` entries | `0.17 ms` (`2.62 us/view`) | `+240.0 KiB` | `64` | `3.38 MiB` | | Materialize `512` `write_typed_buffer` entries | `0.56 ms` (`1.09 us/view`) | `+752.0 KiB` | `512` | `3.38 MiB` | | Materialize `1,000` `write_typed_buffer` entries | `0.93 ms` (`0.93 us/view`) | `+688.0 KiB` (`~0.7 KiB/view`) | `1,000` | `3.38 MiB` | | Materialize `10,000` `write_typed_buffer` entries | `10.25 ms` (`1.03 us/view`) | `+15,248.0 KiB` (`~1.5 KiB/view`) | `10,000` | `3.38 MiB` | | Eager `40,000` `write_typed_buffer` entries *(previous commit worst case)* | `36.77 ms` (`0.92 us/view`) | `+46,320.0 KiB` (`+45.2 MiB`, `~1.2 KiB/view`) | `40,000` | `3.38 MiB` | Eager creation across 40,000 entries would have cost `~45.2 MiB` of kernel `phys_footprint` (`~1.2 KiB` per retained `MTLTextureTypeTextureBuffer`). With lazy materialization, `mirror()` creates `0` Metal textures and adds `+16 KiB` total for a 40,000-entry heap. 2. **Lazy materialization gated on shaders that actually use `TypedBuffer`:** - `NativeHost::mirror` always calls `write_buffer` (`[gpu, 0, size]`) and sets two bits per entry in `NativeHeap::typed_pending` (`PendingTyped`: `typed` for all typed and 4-, 8-, or 16-byte structured views; `explicit` for `stride == 0` typed views). - `Binding::of(shader)` scans the module's DXIL `TYPE_BLOCK`, `CONSTANTS_BLOCK`, and `VALUE_SYMTAB_BLOCK` once (`list::dxil_uses_typed_buffers`) to check whether kept instructions call `dx.op.bufferLoad.*`, `dx.op.bufferStore.*`, or `dx.op.getDimensions` on a `TypedBuffer` (`dx.types.ResourceProperties` kind `10` — so `Texture2D` `getDimensions` stays `false`, verified in `heap_tests`). - At draw/dispatch (`NativeHost::materialize_typed_buffers`), draws and dispatches whose bound stages have `typed_buffers == false` return immediately. When `typed_buffers == true`, only pending entries inside the bound `Root::Table` ranges are promoted via `write_typed_buffer` (plus explicit `stride == 0` typed buffer views in the bound heap when `heap_typed_buffers == true`), leaving unbound structured buffers across the heap unmaterialized. 3. **Unaligned (< 16 B) buffer offsets & `SINT` -> `UINT` mapping:** - **Unaligned offsets:** `dev.minimumTextureBufferAlignmentForPixelFormat` is `16` bytes across all tested formats on Apple Silicon. Calling `newTextureWithDescriptor_offset_bytesPerRow` at a non-16-byte offset trips Metal validation, so `Metal::write_typed_buffer` now logs a `tracing::warn!` on the first unaligned typed buffer view (`debug!` thereafter) and falls back to `write_buffer` (`[gpu, 0, size]`). Raw/structured accesses at word 0 (`gpuVA`, 4-byte aligned) continue to work; formatted accesses at word 1 read `0` / no-op instead of asserting (`gfx::heap_set_tests::a_heaps_set_follows_its_entries` now tests an unaligned `+4` view). - **`SINT` -> `UINT`:** Yes, mapping **32-bit** `SINT` (`4`, `18`, `43`) to `Uint` while leaving **8- and 16-bit** `SINT` (`14`, `32`, `38`, `52`, `59`, `64`) unmapped is intentional. `victory-shader` lowers all formatted buffer loads/stores through float-typed DXIL handles (`TypedBuffer<float4>`, `props = (10 | u, 0x409)`, `bitcast i32 <-> float`), so `metal-shaderconverter` takes `v4f32` from the DXIL handle (`@air.read/write_texture_buffer_1d.v4f32`), while Apple Silicon's texture hardware unpacks/packs according to the `MTLTexture` view's `MTLPixelFormat` (proven on GPU by `0x0000_0012` — subnormal float `2.5e-44` — packing to `0x0012` and reading back `0x0000_0012` on `RGBA16Uint`). For 32-bit channels there is no sub-32-bit sign extension or clamping, so `Uint` transfers all 32 two's-complement bits identically (now GPU-tested for `R32_SINT` code `43` with `0xDEAD_BEEF`, alongside `R16G16_SNORM` code `37`); 8/16-bit `SINT` would zero-extend under `Uint`, so they stay excluded. 4. **`Refs #255` & #264 overlap:** Updated both commit message and PR description to `Refs #255`, and restructured `descriptors.rs`, `list.rs`, and `host.rs` against #264's diff (`Decoded::Buffer` and `decode` are now untouched vs `origin/main`, `typed_buffer` sits after `sampler`, and `typed_pending` sits after `images`), eliminating line overlap with #264; happy to rebase again as soon as #264 lands. 5. **Synthetic test program confirmation:** Confirmed: the `llvm-dis` inspection of `metal-shaderconverter` output described here and in #255 was run solely on a small synthetic DXIL test program of our own, never on any game shader or title file, and no listing from it is in the repository or in the comments (`cargo xtask policy` passes across all 371 files).
LakshanSivakumar commented 2026-11-27 11:54:28 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T11:54:28Z.


Thank you for answering all five points with numbers, and for making the mirror lazy.

I ran bff96ea6 in the game, together with #263, #253 and #264 on main ce2b7860 (Series S, headless). The 1280x720 G-buffer targets are 60 to 87% covered. The run made 70,492 typed views, all in the first block of world frames, and logged one "typed buffer view offset is not aligned" warning (offset 0x83aee88), which fell back to the raw entry as you intend. Views that wrap the title's pages (#267) also got their typed word. The lighting output is still noise, and the run ended in the known GPU time-out and title fault.

Two questions before I merge. When a shader's DXIL scan says "no typed buffer" but it does use one, what does it read? Please add a test where the scan result is wrong on purpose, so we know the failure is a zero read and not a crash. And 70,492 is a count of promotions: can you add a count of entries that hold a typed view at one time, so we know the memory it keeps?

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7217612892 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278#issuecomment-7217612892). Originally posted by [LakshanSivakumar](https://github.com/LakshanSivakumar) on 2026-11-27T11:54:28Z. --- Thank you for answering all five points with numbers, and for making the mirror lazy. I ran bff96ea6 in the game, together with #263, #253 and #264 on main ce2b7860 (Series S, headless). The 1280x720 G-buffer targets are 60 to 87% covered. The run made 70,492 typed views, all in the first block of world frames, and logged one "typed buffer view offset is not aligned" warning (offset 0x83aee88), which fell back to the raw entry as you intend. Views that wrap the title's pages (#267) also got their typed word. The lighting output is still noise, and the run ended in the known GPU time-out and title fault. Two questions before I merge. When a shader's DXIL scan says "no typed buffer" but it does use one, what does it read? Please add a test where the scan result is wrong on purpose, so we know the failure is a zero read and not a crash. And 70,492 is a count of promotions: can you add a count of entries that hold a typed view at one time, so we know the memory it keeps?
Sheffy007 commented 2026-11-27 12:16:52 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by Sheffy007 on 2026-11-27T12:16:52Z.


Rebased onto main (92e0cd5b -> 16732233) and addressed both questions:

  1. What happens if Binding's DXIL scan falsely says "no typed buffer" (typed_buffers == false):

    • NativeHost::mirror writes [gpu, 0, size] via Metal::write_buffer, leaving word 1 (textureViewID) at 0 (null MTLResourceID) — and whenever an already-promoted slot is re-mirrored by mirror(), write_buffer zeroes word 1 back to 0 and drops the previous MTLTexture view, so there is never a stale or dangling gpuResourceID.
    • On Apple Silicon Metal, air.read_texture_buffer_1d and air.get_width_texture_buffer_1d on MTLResourceID(0) return [0, 0, 0, 0] and 0, and air.write_texture_buffer_1d on MTLResourceID(0) is a no-op, with no GPU fault or command-buffer error.
    • Added native::tests::heap_tests::wrong_typed_buffer_scan_reads_zero_without_crashing, which compiles both a typed SRV shader (buffer_load_format_xyzw + getDimensions) and a typed UAV shader (buffer_store_format_xyzw + buffer_load_format_xyzw + getDimensions), forces b.typed_buffers = false and b.heap_typed_buffers = false on purpose, and verifies on Metal both for a fresh mirror() slot and for a previously promoted slot (live_typed_views == 1) that was overwritten by mirror() (live_typed_views == 0): no crash, buffer_store_format_xyzw leaves title memory untouched, and buffer_load_format_xyzw + getDimensions write [0, 0, 0, 0, 0] over a 0xCAFE_BABE output canary.
  2. Live count of entries holding a texture_buffer view at one time (live_typed_views):

    • Added Heap::typed_views (ResourceBackend::heap_typed_views, maintained in Metal::heap_entry whenever Some(tex_view) is inserted vs overwritten/cleared) and NativeHost::live_typed_views(&self) -> usize, plus write_typed_buffer -> bool so unaligned fallbacks to write_buffer are not counted as promotions.
    • Logged typed_views (cumulative promotions) alongside typed_views_live (entries currently holding a MTLTexture view across all heaps) in glue::log_draw_counts (native typed buffer views, placed below the native draws so far line so it will not conflict with #264), and pinned both counts in a_heaps_set_follows_its_entries and formatted_buffer_stores_and_loads_through_structured_and_typed_uavs (typed_views == 8, live_typed_views == 1).
<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7218053845 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278#issuecomment-7218053845). Originally posted by [Sheffy007](https://github.com/Sheffy007) on 2026-11-27T12:16:52Z. --- Rebased onto `main` (`92e0cd5b` -> `16732233`) and addressed both questions: 1. **What happens if `Binding`'s DXIL scan falsely says "no typed buffer" (`typed_buffers == false`):** - `NativeHost::mirror` writes `[gpu, 0, size]` via `Metal::write_buffer`, leaving word 1 (`textureViewID`) at `0` (null `MTLResourceID`) — and whenever an already-promoted slot is re-mirrored by `mirror()`, `write_buffer` zeroes word 1 back to `0` and drops the previous `MTLTexture` view, so there is never a stale or dangling `gpuResourceID`. - On Apple Silicon Metal, `air.read_texture_buffer_1d` and `air.get_width_texture_buffer_1d` on `MTLResourceID(0)` return **`[0, 0, 0, 0]` and `0`**, and `air.write_texture_buffer_1d` on `MTLResourceID(0)` is a **no-op**, with **no GPU fault or command-buffer error**. - Added `native::tests::heap_tests::wrong_typed_buffer_scan_reads_zero_without_crashing`, which compiles both a typed SRV shader (`buffer_load_format_xyzw` + `getDimensions`) and a typed UAV shader (`buffer_store_format_xyzw` + `buffer_load_format_xyzw` + `getDimensions`), forces `b.typed_buffers = false` and `b.heap_typed_buffers = false` on purpose, and verifies on Metal both for a fresh `mirror()` slot and for a previously promoted slot (`live_typed_views == 1`) that was overwritten by `mirror()` (`live_typed_views == 0`): no crash, `buffer_store_format_xyzw` leaves title memory untouched, and `buffer_load_format_xyzw` + `getDimensions` write `[0, 0, 0, 0, 0]` over a `0xCAFE_BABE` output canary. 2. **Live count of entries holding a `texture_buffer` view at one time (`live_typed_views`):** - Added `Heap::typed_views` (`ResourceBackend::heap_typed_views`, maintained in `Metal::heap_entry` whenever `Some(tex_view)` is inserted vs overwritten/cleared) and `NativeHost::live_typed_views(&self) -> usize`, plus `write_typed_buffer -> bool` so unaligned fallbacks to `write_buffer` are not counted as promotions. - Logged `typed_views` (cumulative promotions) alongside `typed_views_live` (entries currently holding a `MTLTexture` view across all heaps) in `glue::log_draw_counts` (`native typed buffer views`, placed below the `native draws so far` line so it will not conflict with `#264`), and pinned both counts in `a_heaps_set_follows_its_entries` and `formatted_buffer_stores_and_loads_through_structured_and_typed_uavs` (`typed_views == 8`, `live_typed_views == 1`).
LakshanSivakumar commented 2026-11-27 12:22:43 +00:00 (Migrated from github.com)

Imported from LakshanSivakumar/Native-Victory-macOS. Originally posted by LakshanSivakumar on 2026-11-27T12:22:43Z.


Your earlier head bff96ea6 is on main now: it went in together with #264, after my game run of the two with #253 (G-buffer 60 to 87% covered, 70,492 typed views made, one unaligned-offset fallback). Thank you for the answer about a wrong scan and the new test. Your rebased commit 16732233 conflicts with what is on main in four files, because I had added a similar test and counter; I am putting the two together myself, keeping yours where they do the same job, and I will merge that so this pull request closes. You do not need to rebase again.

<!-- greyfinch-sync:LakshanSivakumar/Native-Victory-macOS:comment:7218170893 --> Imported from [LakshanSivakumar/Native-Victory-macOS](https://github.com/LakshanSivakumar/Native-Victory-macOS/pull/278#issuecomment-7218170893). Originally posted by [LakshanSivakumar](https://github.com/LakshanSivakumar) on 2026-11-27T12:22:43Z. --- Your earlier head bff96ea6 is on main now: it went in together with #264, after my game run of the two with #253 (G-buffer 60 to 87% covered, 70,492 typed views made, one unaligned-offset fallback). Thank you for the answer about a wrong scan and the new test. Your rebased commit 16732233 conflicts with what is on main in four files, because I had added a similar test and counter; I am putting the two together myself, keeping yours where they do the same job, and I will merge that so this pull request closes. You do not need to rebase again.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
LakshanSivakumar/Native-Victory-macOS!278
No description provided.