gpu+shader: encode sRGB UAV stores and fill unknown RTV format on typeless textures #3436

Open
Monard2033 wants to merge 2 commits from upstream-pr/3436 into main
Monard2033 commented 2026-11-27 01:42:53 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Monard2033 on 2026-11-27T01:42:53Z.


Summary

Host D3D12 does not support sRGB unordered access views (R8G8B8A8_UNORM_SRGB, B8G8R8A8_UNORM_SRGB, B8G8R8X8_UNORM_SRGB). victory-gpu already promotes sRGB+UAV textures to TYPELESS (resource.rs) and strips sRGB UAV formats to their linear UNORM twins (descriptor/host.rs), but victory-shader's float image_store still wrote raw linear values without sRGB OETF encoding. Quantizing linear light directly into 8-bit UNORM crushes dark tones (linear 0.0..0.05 -> only ~13 discrete levels) and causes severe ~4-bit banding/posterization in shadows and skies.

Separately, RtvRecord::host_desc left words[0] == 0 (DXGI_FORMAT_UNKNOWN) when a title passed a non-null RTV/DSV descriptor with Format = UNKNOWN on a resource promoted to TYPELESS, which host D3D12 rejects.

Changes

  • victory-shader (emit/shader.rs, emit/mod.rs, emit/lower.rs, emit/host.rs):
    • Narrow VIEW_STRIDE_BITS to (1 << 29) - 1 and add VIEW_SRGB = 1 << 29 in the VIEW_STRIDES table (t255).
    • Mask stride with VIEW_STRIDE_BITS in buffer_guard so setting bit 29 on texture UAV slots never bypasses NULL_BUFFER_VIEW redirection.
    • Track texture UAV heap indices in a dedicated Shader::texture_uav_index map (separate from view_index and texture_index).
    • In float image_store, conditionally branch on (view_word & VIEW_SRGB) != 0 to apply exact IEC 61966-2-1 linear_to_srgb() to RGB channels (leaving alpha linear), with zero SFU overhead on linear UAVs.
  • victory-gpu (descriptor/host.rs, descriptor.rs):
    • Mark direct and placed non-buffer sRGB UAVs (29, 91, 93) with VIEW_SRGB in view_kind() while keeping view_stride() == 0.
    • In RtvRecord::host_desc, substitute resource::view_format(self.resource) when self.described != 0 && words[0] == 0.
  • Tests (emit/stride_tests.rs, descriptor/host.rs, descriptor.rs):
    • texture_uav_image_store_encodes_srgb_when_marked (hardware + WARP)
    • buffer_guard_redirects_slot_with_only_view_srgb_set (WARP + hardware heap-size check)
    • srgb_texture_uavs_are_marked_in_the_stride_table
    • described_rtv_with_unknown_format_fills_typeless_resource_format

Verification

  • cargo clippy --workspace --all-targets --locked -- -D warnings — passed (0 warnings)
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings — passed (0 warnings)
  • VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --features diagnostics --locked — 248 passed, 0 failed
  • cargo test -p xtask --locked (repository_passes_policy) — 6 passed, 0 failed
  • All 4 new shader/GPU unit tests pass.

Runtime Screenshots (RTX 5080 Laptop 16 GB, smooth gradients / clean shadows)

Screenshot_130 Screenshot_129
<!-- greyfinch-sync:Marvisak/VIctory:issue:5519717963 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3436). Originally posted by [Monard2033](https://github.com/Monard2033) on 2026-11-27T01:42:53Z. --- ### Summary Host D3D12 does not support sRGB unordered access views (`R8G8B8A8_UNORM_SRGB`, `B8G8R8A8_UNORM_SRGB`, `B8G8R8X8_UNORM_SRGB`). `victory-gpu` already promotes sRGB+UAV textures to `TYPELESS` (`resource.rs`) and strips sRGB UAV formats to their linear `UNORM` twins (`descriptor/host.rs`), but `victory-shader`'s float `image_store` still wrote raw linear values without sRGB OETF encoding. Quantizing linear light directly into 8-bit `UNORM` crushes dark tones (`linear 0.0..0.05` -> only ~13 discrete levels) and causes severe ~4-bit banding/posterization in shadows and skies. Separately, `RtvRecord::host_desc` left `words[0] == 0` (`DXGI_FORMAT_UNKNOWN`) when a title passed a non-null RTV/DSV descriptor with `Format = UNKNOWN` on a resource promoted to `TYPELESS`, which host D3D12 rejects. ### Changes - **`victory-shader` (`emit/shader.rs`, `emit/mod.rs`, `emit/lower.rs`, `emit/host.rs`):** - Narrow `VIEW_STRIDE_BITS` to `(1 << 29) - 1` and add `VIEW_SRGB = 1 << 29` in the `VIEW_STRIDES` table (`t255`). - Mask `stride` with `VIEW_STRIDE_BITS` in `buffer_guard` so setting bit 29 on texture UAV slots never bypasses `NULL_BUFFER_VIEW` redirection. - Track texture UAV heap indices in a dedicated `Shader::texture_uav_index` map (separate from `view_index` and `texture_index`). - In float `image_store`, conditionally branch on `(view_word & VIEW_SRGB) != 0` to apply exact IEC 61966-2-1 `linear_to_srgb()` to RGB channels (leaving alpha linear), with zero SFU overhead on linear UAVs. - **`victory-gpu` (`descriptor/host.rs`, `descriptor.rs`):** - Mark direct and placed non-buffer sRGB UAVs (`29`, `91`, `93`) with `VIEW_SRGB` in `view_kind()` while keeping `view_stride() == 0`. - In `RtvRecord::host_desc`, substitute `resource::view_format(self.resource)` when `self.described != 0 && words[0] == 0`. - **Tests (`emit/stride_tests.rs`, `descriptor/host.rs`, `descriptor.rs`):** - `texture_uav_image_store_encodes_srgb_when_marked` (hardware + WARP) - `buffer_guard_redirects_slot_with_only_view_srgb_set` (WARP + hardware heap-size check) - `srgb_texture_uavs_are_marked_in_the_stride_table` - `described_rtv_with_unknown_format_fills_typeless_resource_format` ### Verification - `cargo clippy --workspace --all-targets --locked -- -D warnings` — passed (0 warnings) - `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings` — passed (0 warnings) - `VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --features diagnostics --locked` — 248 passed, 0 failed - `cargo test -p xtask --locked` (`repository_passes_policy`) — 6 passed, 0 failed - All 4 new shader/GPU unit tests pass. ### Runtime Screenshots (RTX 5080 Laptop 16 GB, smooth gradients / clean shadows) <!-- Drag & drop Screenshot_129.png and Screenshot_130.png here --> <img width="1919" height="1032" alt="Screenshot_130" src="https://github.com/user-attachments/assets/dfc18139-17be-4afd-9972-46b6585a1f85" /> <img width="1919" height="1030" alt="Screenshot_129" src="https://github.com/user-attachments/assets/e96c9e46-fb6c-465f-ad69-cc3e2d67df19" />
Dukestar69 commented 2026-11-27 01:47:54 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-27T01:47:54Z.

Review: APPROVED


LGTM — verified on Windows (RTX 5090 + WARP):

  • cargo test -p victory-shader --lib srgb passed (2/2: texture_uav_image_store_encodes_srgb_when_marked and buffer_guard_redirects_slot_with_only_view_srgb_set) on RTX 5090 and under VICTORY_WARP=1
  • cargo test -p victory-gpu --lib descriptor:: (23/23, including srgb_texture_uavs_are_marked_in_the_stride_table and described_rtv_with_unknown_format_fills_typeless_resource_format, skipping the pre-existing origin/main RTX 5090 failure) and draw:: (20/20) passed on RTX 5090
  • cargo clippy -p victory-shader -p victory-gpu --all-targets -- -D warnings passed with 0 warnings
  • cargo xtask policy passed (191 files ok)

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

<!-- greyfinch-sync:Marvisak/VIctory:review:6082416651 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3436#pullrequestreview-6082416651). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-27T01:47:54Z. **Review:** APPROVED --- LGTM — verified on Windows (RTX 5090 + WARP): - `cargo test -p victory-shader --lib srgb` passed (2/2: `texture_uav_image_store_encodes_srgb_when_marked` and `buffer_guard_redirects_slot_with_only_view_srgb_set`) on RTX 5090 and under `VICTORY_WARP=1` - `cargo test -p victory-gpu --lib descriptor::` (23/23, including `srgb_texture_uavs_are_marked_in_the_stride_table` and `described_rtv_with_unknown_format_fills_typeless_resource_format`, skipping the pre-existing `origin/main` RTX 5090 failure) and `draw::` (20/20) passed on RTX 5090 - `cargo clippy -p victory-shader -p victory-gpu --all-targets -- -D warnings` passed with 0 warnings - `cargo xtask policy` passed (`191 files ok`) Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
fuzeofficlal commented 2026-11-27 02:00:25 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fuzeofficlal on 2026-11-27T02:00:25Z.

Review: APPROVED


Looks good to me — both the typeless RTV format fill and the sRGB UAV store encoding are cleanly wired and properly isolated from buffer-view strides.

Review & Verification Notes

  • crates/victory-gpu/src/descriptor.rs:381-386: filling DXGI_FORMAT_UNKNOWN (0) on described RTVs (and shared DSV handling) from resource::view_format(self.resource) before pc_format allows D3D12 view creation to succeed on typeless host copies.
  • crates/victory-gpu/src/descriptor/host.rs:1017-1046 & crates/victory-shader/src/emit/lower.rs:4630-4648, 5582, 8650-8675:
    • VIEW_SRGB (1 << 29) is set strictly for sRGB texture UAVs (View::Unordered and View::Placed(true, ...) for formats 29/91/93 after pc_format), leaving linear UAVs and sRGB SRVs untouched.
    • Every VIEW_STRIDES consumer in emit/lower.rs masks with VIEW_STRIDE_BITS ((1 << 29) - 1), so texture UAV slots with VIEW_SRGB still resolve stride 0 and redirect to NULL_BUFFER_VIEW under buffer_guard.
    • Float image_store applies IEC 61966-2-1 encoding to RGB only (clamped via saturate and floored at 1e-12 before log2 to avoid NaNs) while preserving linear alpha.
  • Verified locally on 7b87d312:
    • cargo xtask policy passes (191 files ok; crates/victory-shader/src/emit/lower.rs stays under the 512 KiB limit at 523,162 bytes).
    • cargo clippy (--lib, --tests, and --features diagnostics --tests, -D warnings) is clean across victory-shader and victory-gpu.
    • victory-gpu descriptor::tests + descriptor::host::tests pass on discrete D3D12 (10/10, VICTORY_D3D12_DEBUG=1 + VICTORY_D3D12_GBV=1) and WARP (24/24, --features diagnostics, VICTORY_D3D12_DEBUG=1 + VICTORY_D3D12_WARP=1).
    • Both new victory-shader stride_tests (texture_uav_image_store_encodes_srgb_when_marked and buffer_guard_redirects_slot_with_only_view_srgb_set) pass on discrete D3D12 and WARP with dxil.dll.
    • Also verified direct ID3D12Device::CreateRenderTargetView on typeless sRGB+UAV host textures for both DXGI_FORMAT_R8G8B8A8_UNORM_SRGB (29) and DXGI_FORMAT_B8G8R8A8_UNORM_SRGB (91) under the D3D12 Debug Layer with zero debug errors.
<!-- greyfinch-sync:Marvisak/VIctory:review:6082523773 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3436#pullrequestreview-6082523773). Originally posted by [fuzeofficlal](https://github.com/fuzeofficlal) on 2026-11-27T02:00:25Z. **Review:** APPROVED --- Looks good to me — both the typeless RTV format fill and the sRGB UAV store encoding are cleanly wired and properly isolated from buffer-view strides. ### Review & Verification Notes - `crates/victory-gpu/src/descriptor.rs:381-386`: filling `DXGI_FORMAT_UNKNOWN` (`0`) on described RTVs (and shared DSV handling) from `resource::view_format(self.resource)` before `pc_format` allows D3D12 view creation to succeed on typeless host copies. - `crates/victory-gpu/src/descriptor/host.rs:1017-1046` & `crates/victory-shader/src/emit/lower.rs:4630-4648, 5582, 8650-8675`: - `VIEW_SRGB` (`1 << 29`) is set strictly for sRGB texture UAVs (`View::Unordered` and `View::Placed(true, ...)` for formats `29`/`91`/`93` after `pc_format`), leaving linear UAVs and sRGB SRVs untouched. - Every `VIEW_STRIDES` consumer in `emit/lower.rs` masks with `VIEW_STRIDE_BITS` (`(1 << 29) - 1`), so texture UAV slots with `VIEW_SRGB` still resolve stride `0` and redirect to `NULL_BUFFER_VIEW` under `buffer_guard`. - Float `image_store` applies IEC 61966-2-1 encoding to RGB only (clamped via `saturate` and floored at `1e-12` before `log2` to avoid NaNs) while preserving linear alpha. - Verified locally on `7b87d312`: - `cargo xtask policy` passes (`191 files ok`; `crates/victory-shader/src/emit/lower.rs` stays under the 512 KiB limit at `523,162` bytes). - `cargo clippy` (`--lib`, `--tests`, and `--features diagnostics --tests`, `-D warnings`) is clean across `victory-shader` and `victory-gpu`. - `victory-gpu` `descriptor::tests` + `descriptor::host::tests` pass on discrete D3D12 (`10/10`, `VICTORY_D3D12_DEBUG=1` + `VICTORY_D3D12_GBV=1`) and WARP (`24/24`, `--features diagnostics`, `VICTORY_D3D12_DEBUG=1` + `VICTORY_D3D12_WARP=1`). - Both new `victory-shader` `stride_tests` (`texture_uav_image_store_encodes_srgb_when_marked` and `buffer_guard_redirects_slot_with_only_view_srgb_set`) pass on discrete D3D12 and WARP with `dxil.dll`. - Also verified direct `ID3D12Device::CreateRenderTargetView` on typeless sRGB+UAV host textures for both `DXGI_FORMAT_R8G8B8A8_UNORM_SRGB` (29) and `DXGI_FORMAT_B8G8R8A8_UNORM_SRGB` (91) under the D3D12 Debug Layer with zero debug errors.
AndyLatimer commented 2026-11-27 02:30:50 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by AndyLatimer on 2026-11-27T02:30:50Z.

Review: CHANGES_REQUESTED


Tested 7b87d31 locally against origin/main (63bcca4, clean merge) on Windows 11, NVIDIA GeForce RTX 3060 Ti + Microsoft WARP, Rust 1.98.1 MSVC. All 4 PR tests pass (texture_uav_image_store_encodes_srgb_when_marked, buffer_guard_redirects_slot_with_only_view_srgb_set, srgb_texture_uavs_are_marked_in_the_stride_table, described_rtv_with_unknown_format_fills_typeless_resource_format), but image_load on sRGB texture UAVs is missing the matching decode.

Blocking issue: image_load on sRGB texture UAVs causes double gamma on read-modify-write

Because host D3D12 backs sRGB texture UAVs with their linear UNORM twins, image_store now encodes linear RGB to sRGB (VIEW_SRGB), so textureLoad.f32 (image_load with op == 66 && uav) returns raw sRGB-encoded values instead of linear light unless decoded symmetrically with srgb_to_linear. Any shader doing a read-modify-write (image_store -> image_load -> image_store, or loading an sRGB UAV to blend and store back) applies sRGB gamma a second time.

Reproduced on 7b87d31 with an identity image_store -> image_load -> image_store dispatch on DXGI_FORMAT_R8G8B8A8_UNORM_SRGB (texture_uav_srgb_read_modify_write_preserves_encoded_texel):

thread 'emit::stride_tests::texture_uav_srgb_read_modify_write_preserves_encoded_texel' panicked:
hardware RMW UNORM_SRGB texel 0 ch 1: got 88, want 25

(For linear 0.01, iec_linear_to_srgb(0.01) * 255 ≈ 25; reading it back un-decoded and storing again encodes 0.098 to 88.)

Two smaller notes

  • lower.rs file size vs xtask policy: On 7b87d31, crates/victory-shader/src/emit/lower.rs is 523,162 bytes — only 1,126 bytes under xtask/src/policy.rs's 512 KiB (524,288-byte) MAX_FILE_SIZE. Moving the IEC 61966-2-1 encode/decode helpers into a submodule crates/victory-shader/src/emit/lower/srgb.rs (alongside lower/bvh.rs) keeps lower.rs comfortably under the limit (520,957 bytes).
  • Null-pointer hardening (minor): resource::view_format does not check this.is_null() before dereferencing resource(this); existing production callers check host_resource(this) first, so it is safe today, though a !this.is_null() check (matching title_format) would guard direct callers.

With the patch below applied on top of 7b87d31:

  • cargo test -p victory-shader --lib --locked srgb -- --test-threads=1: 3 passed, 0 failed (RTX 3060 Ti hardware + WARP, including the new RMW regression).
  • cargo clippy -p victory-shader --all-targets --locked -- -D warnings: 0 warnings.
  • cargo xtask policy: 192 files ok (lower.rs at 520,957 bytes).
Tested patch (emit/lower/srgb.rs + UAV image_load decode) and RMW regression against 7b87d31
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index e9ad68a..6b64ad1 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -12,7 +12,7 @@ use super::UserData;
 use super::bitcode::{Attr, Bin, Cast, Term, V, pred};
 use super::container::SigElement;
 use super::shader::{
-    Shader, VIEW_INTEGER, VIEW_SIGNED, VIEW_SRGB, VIEW_STRIDE_BITS, VIEW_STRIDES, flags,
+    Shader, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, flags,
 };
 use crate::ShaderError;
 use crate::gfx10::{Dpp, Fields, NULL, Operand};
@@ -23,6 +23,7 @@ use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER
 use crate::structure::{Atom, Bool, LaneExit, Structured};
 
 mod bvh;
+mod srgb;
 
 type Why = &'static str;
 
@@ -4615,7 +4616,7 @@ impl<'a> Lower<'a> {
     }
 
     /// Dword `index` of the view-stride table: the stride and the format
-    /// kind bits ([`VIEW_INTEGER`], [`VIEW_SIGNED`], [`VIEW_SRGB`]).
+    /// kind bits ([`VIEW_INTEGER`], [`VIEW_SIGNED`], `VIEW_SRGB`).
     fn view_word(&mut self, index: V) -> V {
         let c = self.cur;
         let four = self.s.m.i32(4);
@@ -4624,29 +4625,6 @@ impl<'a> Lower<'a> {
         self.raw_dword(table, at)
     }
 
-    /// IEC 61966-2-1 linear-to-sRGB transfer function for one float channel:
-    /// clamps to `[0, 1]` (NaN to 0), uses `12.92 * c` for `c <= 0.0031308`,
-    /// and `1.055 * exp2(log2(fmax(c, 1e-12)) / 2.4) - 0.055` otherwise.
-    fn linear_to_srgb(&mut self, v: V) -> V {
-        let c = self.unary(7, v);
-        let cur = self.cur;
-        let threshold = self.s.m.f32(0.003_130_8f32.to_bits());
-        let scale_lo = self.s.m.f32(12.92f32.to_bits());
-        let eps = self.s.m.f32(1e-12f32.to_bits());
-        let gamma = self.s.m.f32(2.4f32.to_bits());
-        let scale_hi = self.s.m.f32(1.055f32.to_bits());
-        let bias = self.s.m.f32(0.055f32.to_bits());
-        let lo = self.s.m.bin(cur, Bin::Mul, c, scale_lo);
-        let safe = self.binary(35, c, eps);
-        let lg = self.unary(23, safe);
-        let scaled = self.s.m.bin(cur, Bin::SDiv, lg, gamma);
-        let pw = self.unary(21, scaled);
-        let hi_mul = self.s.m.bin(cur, Bin::Mul, pw, scale_hi);
-        let hi = self.s.m.bin(cur, Bin::Sub, hi_mul, bias);
-        let is_lo = self.s.m.cmp(cur, pred::OLE, c, threshold);
-        self.s.m.select(cur, is_lo, lo, hi)
-    }
-
     /// Whether the typed buffer view a handle names has an integer format,
     /// and whether a signed one, from the view-stride table; `None` if the
     /// handle's heap index is not known.
@@ -8647,33 +8625,7 @@ impl<'a> Lower<'a> {
             }
             let h = self.handle(site, src, false, props)?;
             let at = self.begin_guarded(guard);
-            if let Some(idx) = self.s.texture_uav_index(h) {
-                let word = self.view_word(idx);
-                let head = self.cur;
-                let bit = self.s.m.i32(VIEW_SRGB);
-                let zero = self.s.m.i32(0);
-                let masked = self.s.m.bin(head, Bin::And, word, bit);
-                let is_srgb = self.s.m.cmp(head, pred::NE, masked, zero);
-                let srgb_bb = self.s.m.new_block();
-                let merge_bb = self.s.m.new_block();
-                self.s
-                    .m
-                    .terminate(head, Term::CondBr(is_srgb, srgb_bb, merge_bb));
-                self.cur = srgb_bb;
-                let mut encoded = [vals[0]; 3];
-                for (slot, &v) in encoded.iter_mut().zip(&vals[..3]) {
-                    *slot = self.linear_to_srgb(v);
-                }
-                let srgb_end = self.cur;
-                self.s.m.terminate(srgb_end, Term::Br(merge_bb));
-                self.cur = merge_bb;
-                let f32t = self.s.t.f32;
-                for (val, enc) in vals[..3].iter_mut().zip(encoded) {
-                    let phi = self.s.m.phi(merge_bb, f32t);
-                    self.s.m.set_phi(phi, vec![(*val, head), (enc, srgb_end)]);
-                    *val = phi;
-                }
-            }
+            self.srgb_uav_channels(h, &[0, 1, 2], &mut vals[..3], true);
             let mut args = vec![h];
             args.extend(cs);
             args.extend(vals);
@@ -9074,9 +9026,13 @@ impl<'a> Lower<'a> {
         } else {
             (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
         };
+        let mut floats: Vec<V> = channels.iter().map(|&ch| self.s.m.extract(c, r, ch)).collect();
+        if op == 66 && uav {
+            self.srgb_uav_channels(h, &channels, &mut floats, false);
+        }
+        let c = self.cur;
         let mut xs = Vec::new();
-        for ch in channels {
-            let x = self.s.m.extract(c, r, ch);
+        for x in floats {
             xs.push(if *d16 {
                 // shortcut: d16 results are taken as floats (rounded to
                 // nearest even); integer formats would keep 16 bits.
diff --git a/crates/victory-shader/src/emit/lower/srgb.rs b/crates/victory-shader/src/emit/lower/srgb.rs
new file mode 100644
index 0000000..9dfb662
--- /dev/null
+++ b/crates/victory-shader/src/emit/lower/srgb.rs
@@ -0,0 +1,99 @@
+//! IEC 61966-2-1 sRGB transfer functions for texture UAVs backed by linear
+//! host views (`VIEW_SRGB` in the view-stride table).
+
+use super::Lower;
+use super::super::bitcode::{Bin, Term, V, pred};
+use super::super::shader::VIEW_SRGB;
+
+impl<'a> Lower<'a> {
+    /// IEC 61966-2-1 linear-to-sRGB transfer function for one float channel:
+    /// clamps to `[0, 1]` (NaN to 0), uses `12.92 * c` for `c <= 0.0031308`,
+    /// and `1.055 * exp2(log2(fmax(c, 1e-12)) / 2.4) - 0.055` otherwise.
+    fn linear_to_srgb(&mut self, v: V) -> V {
+        let c = self.unary(7, v);
+        let cur = self.cur;
+        let threshold = self.s.m.f32(0.003_130_8f32.to_bits());
+        let scale_lo = self.s.m.f32(12.92f32.to_bits());
+        let eps = self.s.m.f32(1e-12f32.to_bits());
+        let gamma = self.s.m.f32(2.4f32.to_bits());
+        let scale_hi = self.s.m.f32(1.055f32.to_bits());
+        let bias = self.s.m.f32(0.055f32.to_bits());
+        let lo = self.s.m.bin(cur, Bin::Mul, c, scale_lo);
+        let safe = self.binary(35, c, eps);
+        let lg = self.unary(23, safe);
+        let scaled = self.s.m.bin(cur, Bin::SDiv, lg, gamma);
+        let pw = self.unary(21, scaled);
+        let hi_mul = self.s.m.bin(cur, Bin::Mul, pw, scale_hi);
+        let hi = self.s.m.bin(cur, Bin::Sub, hi_mul, bias);
+        let is_lo = self.s.m.cmp(cur, pred::OLE, c, threshold);
+        self.s.m.select(cur, is_lo, lo, hi)
+    }
+
+    /// IEC 61966-2-1 sRGB-to-linear transfer function for one float channel:
+    /// clamps to `[0, 1]` (NaN to 0), uses `c / 12.92` for `c <= 0.04045`,
+    /// and `exp2(log2(fmax((c + 0.055) / 1.055, 1e-12)) * 2.4)` otherwise.
+    fn srgb_to_linear(&mut self, v: V) -> V {
+        let c = self.unary(7, v);
+        let cur = self.cur;
+        let threshold = self.s.m.f32(0.040_45f32.to_bits());
+        let scale_lo = self.s.m.f32(12.92f32.to_bits());
+        let eps = self.s.m.f32(1e-12f32.to_bits());
+        let gamma = self.s.m.f32(2.4f32.to_bits());
+        let scale_hi = self.s.m.f32(1.055f32.to_bits());
+        let bias = self.s.m.f32(0.055f32.to_bits());
+        let lo = self.s.m.bin(cur, Bin::SDiv, c, scale_lo);
+        let shifted = self.s.m.bin(cur, Bin::Add, c, bias);
+        let norm = self.s.m.bin(cur, Bin::SDiv, shifted, scale_hi);
+        let safe = self.binary(35, norm, eps);
+        let lg = self.unary(23, safe);
+        let scaled = self.s.m.bin(cur, Bin::Mul, lg, gamma);
+        let hi = self.unary(21, scaled);
+        let is_lo = self.s.m.cmp(cur, pred::OLE, c, threshold);
+        self.s.m.select(cur, is_lo, lo, hi)
+    }
+
+    /// If `h` is a texture UAV handle and its view-stride word has `VIEW_SRGB`,
+    /// encodes (`encode == true`) or decodes (`encode == false`) every RGB
+    /// channel (`ch < 3`) in `vals`, leaving alpha untouched.
+    pub(super) fn srgb_uav_channels(&mut self, h: V, channels: &[u32], vals: &mut [V], encode: bool) {
+        let Some(idx) = self.s.texture_uav_index(h) else {
+            return;
+        };
+        if !channels.iter().any(|&ch| ch < 3) {
+            return;
+        }
+        let word = self.view_word(idx);
+        let head = self.cur;
+        let bit = self.s.m.i32(VIEW_SRGB);
+        let zero = self.s.m.i32(0);
+        let masked = self.s.m.bin(head, Bin::And, word, bit);
+        let is_srgb = self.s.m.cmp(head, pred::NE, masked, zero);
+        let srgb_bb = self.s.m.new_block();
+        let merge_bb = self.s.m.new_block();
+        self.s.m.terminate(head, Term::CondBr(is_srgb, srgb_bb, merge_bb));
+        self.cur = srgb_bb;
+        let mut converted = Vec::with_capacity(vals.len());
+        for (&ch, &v) in channels.iter().zip(vals.iter()) {
+            converted.push(if ch < 3 {
+                if encode {
+                    self.linear_to_srgb(v)
+                } else {
+                    self.srgb_to_linear(v)
+                }
+            } else {
+                v
+            });
+        }
+        let srgb_end = self.cur;
+        self.s.m.terminate(srgb_end, Term::Br(merge_bb));
+        self.cur = merge_bb;
+        let f32t = self.s.t.f32;
+        for ((&ch, val), conv) in channels.iter().zip(vals.iter_mut()).zip(converted) {
+            if ch < 3 {
+                let phi = self.s.m.phi(merge_bb, f32t);
+                self.s.m.set_phi(phi, vec![(*val, head), (conv, srgb_end)]);
+                *val = phi;
+            }
+        }
+    }
+}
diff --git a/crates/victory-shader/src/emit/stride_tests.rs b/crates/victory-shader/src/emit/stride_tests.rs
index 65a0d77..ae0c195 100644
--- a/crates/victory-shader/src/emit/stride_tests.rs
+++ b/crates/victory-shader/src/emit/stride_tests.rs
@@ -954,3 +954,85 @@ fn buffer_guard_redirects_slot_with_only_view_srgb_set() {
     }
     assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available");
 }
+
+/// Identity read-modify-write on a 2D texture UAV: stores linear inputs to
+/// `(lane, 0)`, loads them back via `image_load`, and stores them back again.
+const TEXTURE_UAV_RMW_WAVE32: &[u32] = &[
+    0xBE84_0300, // s_mov_b32 s4, s0
+    0xBE85_0380, // s_mov_b32 s5, 0
+    0xF40C_0202,
+    0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0x0
+    0xBE86_0301, // s_mov_b32 s6, s1
+    0xBE87_0380, // s_mov_b32 s7, 0
+    0xF408_0403,
+    0xFA00_0000, // s_load_dwordx4 s[16:19], s[6:7], 0x0
+    0x3402_0084, // v_lshlrev_b32 v1, 4, v0
+    0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
+    0xE038_1000,
+    0x8004_0201, // buffer_load_dwordx4 v[2:5], v1, s[16:19], 0 offen
+    0xBF8C_3F70, // s_waitcnt vmcnt(0)
+    0x7E02_0280, // v_mov_b32 v1, 0
+    0xF020_1F08,
+    0x0002_0200, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf dim:2D unorm
+    0xBF8C_3F70, // s_waitcnt vmcnt(0)
+    0xF000_1F08,
+    0x0002_0200, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf dim:2D unorm
+    0xBF8C_3F70, // s_waitcnt vmcnt(0)
+    0xF020_1F08,
+    0x0002_0200, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf dim:2D unorm
+    0xBF81_0000, // s_endpgm
+];
+
+/// An identity read-modify-write (`image_store` -> `image_load` -> `image_store`)
+/// on an sRGB texture UAV must not double-encode gamma: `image_load` must decode
+/// sRGB to linear when `VIEW_SRGB` is set, matching `image_store`'s encoding.
+#[test]
+fn texture_uav_srgb_read_modify_write_preserves_encoded_texel() {
+    let shader = build(
+        TEXTURE_UAV_RMW_WAVE32,
+        vec![param(RootType::Table, 0), param(RootType::Table, 1)],
+        vec![entry(ResourceType::Uav, 8, 0), entry(ResourceType::Srv, 4, 1)],
+        8,
+    );
+    let inputs: [[f32; 4]; 8] = [
+        [0.0, 0.01, 0.18, 0.25],
+        [0.05, 0.25, 0.5, 0.5],
+        [0.75, 1.0, 0.002, 0.75],
+        [0.1, 0.2, 0.3, 1.0],
+        [0.003, 0.004, 0.2, 0.3],
+        [0.33, 0.66, 0.99, 0.1],
+        [0.05, 0.1, 0.4, 0.8],
+        [0.85, 0.9, 0.95, 0.0],
+    ];
+    let data: Vec<u32> = inputs
+        .iter()
+        .flat_map(|px| px.map(f32::to_bits))
+        .collect();
+    let srgb_views = [
+        View::TypedTextureUav(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 8, 1),
+        View::Buffer {
+            data: &data,
+            stride: Stride::Raw,
+        },
+    ];
+    let strides = view_strides(&srgb_views);
+    for (label, words) in run_tables(&shader, &srgb_views, strides) {
+        for (i, input) in inputs.iter().enumerate() {
+            let bytes = words[0][i].to_le_bytes();
+            for c in 0..3 {
+                let want = (iec_linear_to_srgb(input[c]) * 255.0).round() as i32;
+                assert!(
+                    (i32::from(bytes[c]) - want).abs() <= 2,
+                    "{label} RMW UNORM_SRGB texel {i} ch {c}: got {}, want {want}",
+                    bytes[c]
+                );
+            }
+            let want_a = (input[3].clamp(0.0, 1.0) * 255.0).round() as i32;
+            assert!(
+                (i32::from(bytes[3]) - want_a).abs() <= 1,
+                "{label} RMW UNORM_SRGB texel {i} alpha: got {}, want {want_a}",
+                bytes[3]
+            );
+        }
+    }
+}

Synthetic tests only; AI-assisted review.

<!-- greyfinch-sync:Marvisak/VIctory:review:6082710632 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3436#pullrequestreview-6082710632). Originally posted by [AndyLatimer](https://github.com/AndyLatimer) on 2026-11-27T02:30:50Z. **Review:** CHANGES_REQUESTED --- Tested `7b87d31` locally against `origin/main` (`63bcca4`, clean merge) on Windows 11, NVIDIA GeForce RTX 3060 Ti + Microsoft WARP, Rust 1.98.1 MSVC. All 4 PR tests pass (`texture_uav_image_store_encodes_srgb_when_marked`, `buffer_guard_redirects_slot_with_only_view_srgb_set`, `srgb_texture_uavs_are_marked_in_the_stride_table`, `described_rtv_with_unknown_format_fills_typeless_resource_format`), **but `image_load` on sRGB texture UAVs is missing the matching decode**. ### Blocking issue: `image_load` on sRGB texture UAVs causes double gamma on read-modify-write Because host D3D12 backs sRGB texture UAVs with their linear `UNORM` twins, `image_store` now encodes linear RGB to sRGB (`VIEW_SRGB`), so `textureLoad.f32` (`image_load` with `op == 66 && uav`) returns raw sRGB-encoded values instead of linear light unless decoded symmetrically with `srgb_to_linear`. Any shader doing a read-modify-write (`image_store` -> `image_load` -> `image_store`, or loading an sRGB UAV to blend and store back) applies sRGB gamma a second time. Reproduced on `7b87d31` with an identity `image_store` -> `image_load` -> `image_store` dispatch on `DXGI_FORMAT_R8G8B8A8_UNORM_SRGB` (`texture_uav_srgb_read_modify_write_preserves_encoded_texel`): ```text thread 'emit::stride_tests::texture_uav_srgb_read_modify_write_preserves_encoded_texel' panicked: hardware RMW UNORM_SRGB texel 0 ch 1: got 88, want 25 ``` (For linear `0.01`, `iec_linear_to_srgb(0.01) * 255 ≈ 25`; reading it back un-decoded and storing again encodes `0.098` to `88`.) ### Two smaller notes - **`lower.rs` file size vs `xtask policy`:** On `7b87d31`, `crates/victory-shader/src/emit/lower.rs` is `523,162` bytes — only `1,126` bytes under `xtask/src/policy.rs`'s `512 KiB` (`524,288`-byte) `MAX_FILE_SIZE`. Moving the IEC 61966-2-1 encode/decode helpers into a submodule `crates/victory-shader/src/emit/lower/srgb.rs` (alongside `lower/bvh.rs`) keeps `lower.rs` comfortably under the limit (`520,957` bytes). - **Null-pointer hardening (minor):** `resource::view_format` does not check `this.is_null()` before dereferencing `resource(this)`; existing production callers check `host_resource(this)` first, so it is safe today, though a `!this.is_null()` check (matching `title_format`) would guard direct callers. With the patch below applied on top of `7b87d31`: - `cargo test -p victory-shader --lib --locked srgb -- --test-threads=1`: **3 passed, 0 failed** (RTX 3060 Ti hardware + WARP, including the new RMW regression). - `cargo clippy -p victory-shader --all-targets --locked -- -D warnings`: **0 warnings**. - `cargo xtask policy`: **192 files ok** (`lower.rs` at `520,957` bytes). <details> <summary>Tested patch (emit/lower/srgb.rs + UAV image_load decode) and RMW regression against 7b87d31</summary> ```diff diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index e9ad68a..6b64ad1 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -12,7 +12,7 @@ use super::UserData; use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; use super::container::SigElement; use super::shader::{ - Shader, VIEW_INTEGER, VIEW_SIGNED, VIEW_SRGB, VIEW_STRIDE_BITS, VIEW_STRIDES, flags, + Shader, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, VIEW_STRIDES, flags, }; use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; @@ -23,6 +23,7 @@ use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source, USER use crate::structure::{Atom, Bool, LaneExit, Structured}; mod bvh; +mod srgb; type Why = &'static str; @@ -4615,7 +4616,7 @@ impl<'a> Lower<'a> { } /// Dword `index` of the view-stride table: the stride and the format - /// kind bits ([`VIEW_INTEGER`], [`VIEW_SIGNED`], [`VIEW_SRGB`]). + /// kind bits ([`VIEW_INTEGER`], [`VIEW_SIGNED`], `VIEW_SRGB`). fn view_word(&mut self, index: V) -> V { let c = self.cur; let four = self.s.m.i32(4); @@ -4624,29 +4625,6 @@ impl<'a> Lower<'a> { self.raw_dword(table, at) } - /// IEC 61966-2-1 linear-to-sRGB transfer function for one float channel: - /// clamps to `[0, 1]` (NaN to 0), uses `12.92 * c` for `c <= 0.0031308`, - /// and `1.055 * exp2(log2(fmax(c, 1e-12)) / 2.4) - 0.055` otherwise. - fn linear_to_srgb(&mut self, v: V) -> V { - let c = self.unary(7, v); - let cur = self.cur; - let threshold = self.s.m.f32(0.003_130_8f32.to_bits()); - let scale_lo = self.s.m.f32(12.92f32.to_bits()); - let eps = self.s.m.f32(1e-12f32.to_bits()); - let gamma = self.s.m.f32(2.4f32.to_bits()); - let scale_hi = self.s.m.f32(1.055f32.to_bits()); - let bias = self.s.m.f32(0.055f32.to_bits()); - let lo = self.s.m.bin(cur, Bin::Mul, c, scale_lo); - let safe = self.binary(35, c, eps); - let lg = self.unary(23, safe); - let scaled = self.s.m.bin(cur, Bin::SDiv, lg, gamma); - let pw = self.unary(21, scaled); - let hi_mul = self.s.m.bin(cur, Bin::Mul, pw, scale_hi); - let hi = self.s.m.bin(cur, Bin::Sub, hi_mul, bias); - let is_lo = self.s.m.cmp(cur, pred::OLE, c, threshold); - self.s.m.select(cur, is_lo, lo, hi) - } - /// Whether the typed buffer view a handle names has an integer format, /// and whether a signed one, from the view-stride table; `None` if the /// handle's heap index is not known. @@ -8647,33 +8625,7 @@ impl<'a> Lower<'a> { } let h = self.handle(site, src, false, props)?; let at = self.begin_guarded(guard); - if let Some(idx) = self.s.texture_uav_index(h) { - let word = self.view_word(idx); - let head = self.cur; - let bit = self.s.m.i32(VIEW_SRGB); - let zero = self.s.m.i32(0); - let masked = self.s.m.bin(head, Bin::And, word, bit); - let is_srgb = self.s.m.cmp(head, pred::NE, masked, zero); - let srgb_bb = self.s.m.new_block(); - let merge_bb = self.s.m.new_block(); - self.s - .m - .terminate(head, Term::CondBr(is_srgb, srgb_bb, merge_bb)); - self.cur = srgb_bb; - let mut encoded = [vals[0]; 3]; - for (slot, &v) in encoded.iter_mut().zip(&vals[..3]) { - *slot = self.linear_to_srgb(v); - } - let srgb_end = self.cur; - self.s.m.terminate(srgb_end, Term::Br(merge_bb)); - self.cur = merge_bb; - let f32t = self.s.t.f32; - for (val, enc) in vals[..3].iter_mut().zip(encoded) { - let phi = self.s.m.phi(merge_bb, f32t); - self.s.m.set_phi(phi, vec![(*val, head), (enc, srgb_end)]); - *val = phi; - } - } + self.srgb_uav_channels(h, &[0, 1, 2], &mut vals[..3], true); let mut args = vec![h]; args.extend(cs); args.extend(vals); @@ -9074,9 +9026,13 @@ impl<'a> Lower<'a> { } else { (0..4).filter(|ch| dmask >> ch & 1 != 0).collect() }; + let mut floats: Vec<V> = channels.iter().map(|&ch| self.s.m.extract(c, r, ch)).collect(); + if op == 66 && uav { + self.srgb_uav_channels(h, &channels, &mut floats, false); + } + let c = self.cur; let mut xs = Vec::new(); - for ch in channels { - let x = self.s.m.extract(c, r, ch); + for x in floats { xs.push(if *d16 { // shortcut: d16 results are taken as floats (rounded to // nearest even); integer formats would keep 16 bits. diff --git a/crates/victory-shader/src/emit/lower/srgb.rs b/crates/victory-shader/src/emit/lower/srgb.rs new file mode 100644 index 0000000..9dfb662 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/srgb.rs @@ -0,0 +1,99 @@ +//! IEC 61966-2-1 sRGB transfer functions for texture UAVs backed by linear +//! host views (`VIEW_SRGB` in the view-stride table). + +use super::Lower; +use super::super::bitcode::{Bin, Term, V, pred}; +use super::super::shader::VIEW_SRGB; + +impl<'a> Lower<'a> { + /// IEC 61966-2-1 linear-to-sRGB transfer function for one float channel: + /// clamps to `[0, 1]` (NaN to 0), uses `12.92 * c` for `c <= 0.0031308`, + /// and `1.055 * exp2(log2(fmax(c, 1e-12)) / 2.4) - 0.055` otherwise. + fn linear_to_srgb(&mut self, v: V) -> V { + let c = self.unary(7, v); + let cur = self.cur; + let threshold = self.s.m.f32(0.003_130_8f32.to_bits()); + let scale_lo = self.s.m.f32(12.92f32.to_bits()); + let eps = self.s.m.f32(1e-12f32.to_bits()); + let gamma = self.s.m.f32(2.4f32.to_bits()); + let scale_hi = self.s.m.f32(1.055f32.to_bits()); + let bias = self.s.m.f32(0.055f32.to_bits()); + let lo = self.s.m.bin(cur, Bin::Mul, c, scale_lo); + let safe = self.binary(35, c, eps); + let lg = self.unary(23, safe); + let scaled = self.s.m.bin(cur, Bin::SDiv, lg, gamma); + let pw = self.unary(21, scaled); + let hi_mul = self.s.m.bin(cur, Bin::Mul, pw, scale_hi); + let hi = self.s.m.bin(cur, Bin::Sub, hi_mul, bias); + let is_lo = self.s.m.cmp(cur, pred::OLE, c, threshold); + self.s.m.select(cur, is_lo, lo, hi) + } + + /// IEC 61966-2-1 sRGB-to-linear transfer function for one float channel: + /// clamps to `[0, 1]` (NaN to 0), uses `c / 12.92` for `c <= 0.04045`, + /// and `exp2(log2(fmax((c + 0.055) / 1.055, 1e-12)) * 2.4)` otherwise. + fn srgb_to_linear(&mut self, v: V) -> V { + let c = self.unary(7, v); + let cur = self.cur; + let threshold = self.s.m.f32(0.040_45f32.to_bits()); + let scale_lo = self.s.m.f32(12.92f32.to_bits()); + let eps = self.s.m.f32(1e-12f32.to_bits()); + let gamma = self.s.m.f32(2.4f32.to_bits()); + let scale_hi = self.s.m.f32(1.055f32.to_bits()); + let bias = self.s.m.f32(0.055f32.to_bits()); + let lo = self.s.m.bin(cur, Bin::SDiv, c, scale_lo); + let shifted = self.s.m.bin(cur, Bin::Add, c, bias); + let norm = self.s.m.bin(cur, Bin::SDiv, shifted, scale_hi); + let safe = self.binary(35, norm, eps); + let lg = self.unary(23, safe); + let scaled = self.s.m.bin(cur, Bin::Mul, lg, gamma); + let hi = self.unary(21, scaled); + let is_lo = self.s.m.cmp(cur, pred::OLE, c, threshold); + self.s.m.select(cur, is_lo, lo, hi) + } + + /// If `h` is a texture UAV handle and its view-stride word has `VIEW_SRGB`, + /// encodes (`encode == true`) or decodes (`encode == false`) every RGB + /// channel (`ch < 3`) in `vals`, leaving alpha untouched. + pub(super) fn srgb_uav_channels(&mut self, h: V, channels: &[u32], vals: &mut [V], encode: bool) { + let Some(idx) = self.s.texture_uav_index(h) else { + return; + }; + if !channels.iter().any(|&ch| ch < 3) { + return; + } + let word = self.view_word(idx); + let head = self.cur; + let bit = self.s.m.i32(VIEW_SRGB); + let zero = self.s.m.i32(0); + let masked = self.s.m.bin(head, Bin::And, word, bit); + let is_srgb = self.s.m.cmp(head, pred::NE, masked, zero); + let srgb_bb = self.s.m.new_block(); + let merge_bb = self.s.m.new_block(); + self.s.m.terminate(head, Term::CondBr(is_srgb, srgb_bb, merge_bb)); + self.cur = srgb_bb; + let mut converted = Vec::with_capacity(vals.len()); + for (&ch, &v) in channels.iter().zip(vals.iter()) { + converted.push(if ch < 3 { + if encode { + self.linear_to_srgb(v) + } else { + self.srgb_to_linear(v) + } + } else { + v + }); + } + let srgb_end = self.cur; + self.s.m.terminate(srgb_end, Term::Br(merge_bb)); + self.cur = merge_bb; + let f32t = self.s.t.f32; + for ((&ch, val), conv) in channels.iter().zip(vals.iter_mut()).zip(converted) { + if ch < 3 { + let phi = self.s.m.phi(merge_bb, f32t); + self.s.m.set_phi(phi, vec![(*val, head), (conv, srgb_end)]); + *val = phi; + } + } + } +} diff --git a/crates/victory-shader/src/emit/stride_tests.rs b/crates/victory-shader/src/emit/stride_tests.rs index 65a0d77..ae0c195 100644 --- a/crates/victory-shader/src/emit/stride_tests.rs +++ b/crates/victory-shader/src/emit/stride_tests.rs @@ -954,3 +954,85 @@ fn buffer_guard_redirects_slot_with_only_view_srgb_set() { } assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } + +/// Identity read-modify-write on a 2D texture UAV: stores linear inputs to +/// `(lane, 0)`, loads them back via `image_load`, and stores them back again. +const TEXTURE_UAV_RMW_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0202, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0x0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0403, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[6:7], 0x0 + 0x3402_0084, // v_lshlrev_b32 v1, 4, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE038_1000, + 0x8004_0201, // buffer_load_dwordx4 v[2:5], v1, s[16:19], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xF020_1F08, + 0x0002_0200, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf dim:2D unorm + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF000_1F08, + 0x0002_0200, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf dim:2D unorm + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xF020_1F08, + 0x0002_0200, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf dim:2D unorm + 0xBF81_0000, // s_endpgm +]; + +/// An identity read-modify-write (`image_store` -> `image_load` -> `image_store`) +/// on an sRGB texture UAV must not double-encode gamma: `image_load` must decode +/// sRGB to linear when `VIEW_SRGB` is set, matching `image_store`'s encoding. +#[test] +fn texture_uav_srgb_read_modify_write_preserves_encoded_texel() { + let shader = build( + TEXTURE_UAV_RMW_WAVE32, + vec![param(RootType::Table, 0), param(RootType::Table, 1)], + vec![entry(ResourceType::Uav, 8, 0), entry(ResourceType::Srv, 4, 1)], + 8, + ); + let inputs: [[f32; 4]; 8] = [ + [0.0, 0.01, 0.18, 0.25], + [0.05, 0.25, 0.5, 0.5], + [0.75, 1.0, 0.002, 0.75], + [0.1, 0.2, 0.3, 1.0], + [0.003, 0.004, 0.2, 0.3], + [0.33, 0.66, 0.99, 0.1], + [0.05, 0.1, 0.4, 0.8], + [0.85, 0.9, 0.95, 0.0], + ]; + let data: Vec<u32> = inputs + .iter() + .flat_map(|px| px.map(f32::to_bits)) + .collect(); + let srgb_views = [ + View::TypedTextureUav(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 8, 1), + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + ]; + let strides = view_strides(&srgb_views); + for (label, words) in run_tables(&shader, &srgb_views, strides) { + for (i, input) in inputs.iter().enumerate() { + let bytes = words[0][i].to_le_bytes(); + for c in 0..3 { + let want = (iec_linear_to_srgb(input[c]) * 255.0).round() as i32; + assert!( + (i32::from(bytes[c]) - want).abs() <= 2, + "{label} RMW UNORM_SRGB texel {i} ch {c}: got {}, want {want}", + bytes[c] + ); + } + let want_a = (input[3].clamp(0.0, 1.0) * 255.0).round() as i32; + assert!( + (i32::from(bytes[3]) - want_a).abs() <= 1, + "{label} RMW UNORM_SRGB texel {i} alpha: got {}, want {want_a}", + bytes[3] + ); + } + } +} ``` </details> Synthetic tests only; AI-assisted review.
Monard2033 commented 2026-11-27 09:17:56 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Monard2033 on 2026-11-27T09:17:56Z.


Addressed all 3 review items in 13d205c: decoded image_load on sRGB texture UAVs (srgb_to_linear) + added the RMW test, moved sRGB helpers to lower/srgb.rs (keeping lower.rs under the policy limit), and added !this.is_null() in resource::view_format.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7214514444 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3436#issuecomment-7214514444). Originally posted by [Monard2033](https://github.com/Monard2033) on 2026-11-27T09:17:56Z. --- Addressed all 3 review items in 13d205c: decoded image_load on sRGB texture UAVs (srgb_to_linear) + added the RMW test, moved sRGB helpers to lower/srgb.rs (keeping lower.rs under the policy limit), and added !this.is_null() in resource::view_format.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3436:upstream-pr/3436'
git switch 'upstream-pr/3436'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3436'
git switch 'upstream-pr/3436'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3436'
git switch 'upstream-pr/3436'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3436'
git switch 'main'
git merge --squash 'upstream-pr/3436'
git switch 'main'
git merge --ff-only 'upstream-pr/3436'
git switch 'main'
git merge 'upstream-pr/3436'
git push origin 'main'
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
Marvisak/VIctory!3436
No description provided.