Experimental patch: d16 loads of integer formats where the host does not merge them #2087

Open
opened 2026-11-26 04:54:27 +00:00 by github-bot · 3 comments
Owner

@⁠Speartone on GitHub · 2026-11-25 04:34 UTC · original

Submitted as an experimental patch, not a production-ready fix, because of a known floating-point regression (first limit below). Author: Speartone. Based on 70564ae.

A typed d16 load is lowered to a float load and legacyF32ToF16. On a host that does not merge the two into its own 16-bit load, integer texels arrive as float bits and become 0 or NaN. AMD's driver merges them, so an RDNA2 GPU was right already; an RTX 5080 and WARP were not.

The load and conversion stay. Only where every half is 0 or NaN is the texel loaded again as integers, and 16 bits of each channel kept if all of it is integers of up to 16 bits.

Tests (synthetic): without the change 11,142 wrong channels; with it the covered cases pass on RTX 5080, AMD RDNA2 and WARP. 14 of 15 mutations fail a test; the other cannot change a result. victory-shader: 209 pass, 3 fail; the same 3 fail without the change. Only victory-shader was built.

Limits: coverage is incomplete.

  • Known floating-point regression, on every host: a texel of four 32-bit floats that are all 0, below 2^-133 or NaNs from 0xFFFF8000, and not all 0, can load as integers; the console gives 0 or a NaN.
  • Where the host does not merge, texels of four 16-bit signed integers that are all 0, -32768, -24576, -16384 or -8192 still load as floats.
  • Integers past 16 bits stay wrong where the host does not merge.
  • d16 samples, gathers and stores are as before.
  • Shaders with such loads need tiled resources. Intel GPUs were not tried.

A small conflict with #1693 is likely.

General compatibility defect with no demonstrated GTA VI impact. Actual GTA VI gameplay has not been tested.

AI-assisted: analysis, code, tests and text by Claude Code (Claude Opus 5.5). No game data.

Patch (source and tests)
diff --git a/crates/victory-shader/src/emit/d16_tests.rs b/crates/victory-shader/src/emit/d16_tests.rs
new file mode 100644
index 0000000..b0cced1
--- /dev/null
+++ b/crates/victory-shader/src/emit/d16_tests.rs
@@ -0,0 +1,543 @@
+//! End-to-end tests of `d16` typed loads: synthetic GFX10 programs lowered to
+//! DXIL, validated by `dxil.dll` when present, and run on the host GPU and
+//! WARP over typed buffers and textures of integer and float formats.
+
+use windows::Win32::Graphics::Dxgi::Common::*;
+
+use super::host::{Dispatch, Host, Root, Stride, View};
+use super::{HostShader, lower, validator};
+use crate::native::{
+    ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
+};
+use crate::{io, ir, resource, structure};
+
+/// Texels per view, one per lane.
+const LANES: usize = 32;
+
+/// Which instruction loads the texel.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Load {
+    Buffer,
+    /// The first channel only.
+    BufferX,
+    Image,
+    /// The first channel only.
+    ImageX,
+    ImageMip,
+}
+
+impl Load {
+    fn buffer(self) -> bool {
+        matches!(self, Load::Buffer | Load::BufferX)
+    }
+
+    fn channels(self) -> usize {
+        if matches!(self, Load::BufferX | Load::ImageX) {
+            1
+        } else {
+            4
+        }
+    }
+}
+
+/// A wave32 program of 32 lanes: lane n loads texel n of the view at heap
+/// index 0 with a `d16` load, and stores two dwords of halves at byte 8 * n
+/// of the raw UAV at heap index 1. `s0` is the table of views.
+fn program(load: Load) -> Vec<u32> {
+    let mut words = vec![
+        0xBE84_0300, // s_mov_b32 s4, s0
+        0xBE85_0380, // s_mov_b32 s5, 0
+        0xF408_0A02,
+        0xFA00_0020, // s_load_dwordx4 s[40:43], s[4:5], 0x20
+        0x3420_0083, // v_lshlrev_b32 v16, 3, v0
+        0x7E1A_0280, // v_mov_b32 v13, 0
+    ];
+    words.extend_from_slice(match load {
+        Load::Buffer => &[
+            0xF408_0602,
+            0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0
+            0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
+            0xE20C_2000,
+            0x8006_0C00, // buffer_load_format_d16_xyzw v[12:13], v0, s[24:27], 0 idxen
+        ],
+        Load::BufferX => &[
+            0xF408_0602,
+            0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0
+            0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
+            0xE200_2000,
+            0x8006_0C00, // buffer_load_format_d16_x v12, v0, s[24:27], 0 idxen
+        ],
+        Load::ImageX => &[
+            0xF40C_0602,
+            0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
+            0x7E04_0300, // v_mov_b32 v2, v0
+            0x7E06_0280, // v_mov_b32 v3, 0
+            0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
+            0xF000_0108,
+            0x8006_0C02, // image_load v12, v[2:3], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D d16
+        ],
+        Load::Image => &[
+            0xF40C_0602,
+            0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
+            0x7E04_0300, // v_mov_b32 v2, v0
+            0x7E06_0280, // v_mov_b32 v3, 0
+            0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
+            0xF000_0F08,
+            0x8006_0C02, // image_load v[12:13], v[2:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D d16
+        ],
+        Load::ImageMip => &[
+            0xF40C_0602,
+            0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
+            0x7E04_0300, // v_mov_b32 v2, v0
+            0x7E06_0280, // v_mov_b32 v3, 0
+            0x7E08_0280, // v_mov_b32 v4, 0
+            0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
+            0xF004_0F08,
+            0x8006_0C02, // image_load_mip v[12:13], v[2:4], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D d16
+        ],
+    });
+    words.extend_from_slice(&[
+        0xBF8C_3F70, // s_waitcnt vmcnt(0)
+        0xE074_1000,
+        0x800A_0C10, // buffer_store_dwordx2 v[12:13], v16, s[40:43], 0 offen
+        0xBF81_0000, // s_endpgm
+    ]);
+    words
+}
+
+fn build(load: Load) -> HostShader {
+    let range = |kind, table_offset_dwords, dwords| UsedResource {
+        kind,
+        root: RootType::Table,
+        table_offset_dwords,
+        lower_bound: 0,
+        stride: 0,
+        dwords,
+        user_data: 0,
+        slot: 0,
+    };
+    let native = NativeProgram {
+        stage: HwStage::Cs,
+        wave64: false,
+        vgprs: 32,
+        layout: vec![RootParam {
+            root: RootType::Table,
+            table_offset_dwords: 0,
+            sgprs: 1,
+            base_register: 0,
+            user_data: 0,
+            slot: 0,
+        }],
+        used: vec![
+            range(ResourceType::Srv, 0, if load.buffer() { 4 } else { 8 }),
+            range(ResourceType::Uav, 8, 4),
+        ],
+        io: StageIo::Cs(ComputeIo {
+            rsrc2: 1 << 1, // 1 user SGPR: s0
+            threads: [LANES as u32, 1, 1],
+        }),
+        code: program(load).iter().flat_map(|w| w.to_le_bytes()).collect(),
+    };
+    let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
+    let st = structure::structure(&p).expect("structure");
+    let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track");
+    let io = io::raise(&p, &native).expect("io::raise");
+    let lowered = lower::lower(&lower::Parts {
+        native: &native,
+        p: &p,
+        st: &st,
+        io: &io,
+        res: &res,
+        inputs: Vec::new(),
+        outputs: Vec::new(),
+        prims: Vec::new(),
+        mesh_stride: 0,
+    })
+    .expect("lower");
+    let shader = HostShader {
+        stage: HwStage::Cs,
+        dxil: lowered.dxil,
+        user_data: lowered.user_data,
+        samplers: lowered.samplers,
+        static_samplers: Vec::new(),
+        root_cbvs: lowered.root_cbvs,
+        root_srvs: lowered.root_srvs,
+        root_uavs: lowered.root_uavs,
+        memory: lowered.memory,
+        memory_writes: lowered.memory_writes,
+        view_addresses: lowered.view_addresses,
+        heap: lowered.heap,
+        heap_writes: lowered.heap_writes,
+    };
+    if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
+        v.validate(&mut shader.dxil.clone())
+            .expect("DXIL validation failed");
+    } else {
+        eprintln!("no dxil.dll; validation skipped");
+    }
+    shader
+}
+
+/// What a channel should load as.
+#[derive(Clone, Copy)]
+enum Want {
+    Half(u16),
+    /// Any f16 NaN.
+    Nan,
+    NanOr(u16),
+}
+
+impl Want {
+    fn is(self, got: u16) -> bool {
+        let nan = got & 0x7C00 == 0x7C00 && got & 0x3FF != 0;
+        match self {
+            Want::Half(w) => got == w,
+            Want::Nan => nan,
+            Want::NanOr(w) => nan || got == w,
+        }
+    }
+}
+
+/// What channel `c` of a texel loads as.
+type Wanted = Box<dyn Fn(&[u32], usize) -> Want>;
+
+/// A format, its stored channels and their width in bits, and 32 texels of
+/// that many channels each.
+struct Case {
+    name: &'static str,
+    format: DXGI_FORMAT,
+    bits: usize,
+    texels: Vec<Vec<u32>>,
+    want: Wanted,
+}
+
+impl Case {
+    fn bytes(&self) -> u32 {
+        (self.texels[0].len() * self.bits / 8) as u32
+    }
+
+    /// The texels as dwords in memory.
+    fn data(&self) -> Vec<u32> {
+        let bytes: Vec<u8> = self
+            .texels
+            .iter()
+            .flatten()
+            .flat_map(|x| x.to_le_bytes()[..self.bits / 8].to_vec())
+            .collect();
+        bytes
+            .chunks(4)
+            .map(|b| u32::from_le_bytes(b.try_into().expect("whole dwords")))
+            .collect()
+    }
+}
+
+/// 32 texels of `channels` channels whose values cover `values`, the
+/// channels of a texel taking different ones.
+fn texels(values: &[u32], channels: usize) -> Vec<Vec<u32>> {
+    (0..LANES)
+        .map(|t| {
+            (0..channels)
+                .map(|c| values[(t + 5 * c) % values.len()])
+                .collect()
+        })
+        .collect()
+}
+
+/// Runs every case with every load that takes its format, on hardware and
+/// WARP, and lists the channels that differ from what they should be.
+fn failures(cases: &[Case]) -> Vec<String> {
+    let mut out = Vec::new();
+    let _one = super::valu_tests::ONE_AT_A_TIME
+        .lock()
+        .unwrap_or_else(|e| e.into_inner());
+    let mut ran = 0;
+    for load in [
+        Load::Buffer,
+        Load::BufferX,
+        Load::Image,
+        Load::ImageX,
+        Load::ImageMip,
+    ] {
+        let shader = build(load);
+        for (label, warp) in [("hardware", false), ("warp", true)] {
+            let Ok(host) = Host::new(warp) else {
+                eprintln!("no SM 6.6 {label} device; skipped");
+                continue;
+            };
+            ran += 1;
+            let (root, pso) = host
+                .compute_pipeline(&shader)
+                .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
+            // The table starts at heap index 0.
+            let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
+            for case in cases {
+                assert_eq!(case.texels.len(), LANES, "{}", case.name);
+                let data = case.data();
+                let view = if load.buffer() {
+                    View::Buffer {
+                        data: &data,
+                        stride: Stride::Format(case.format, case.bytes()),
+                    }
+                } else {
+                    View::TextureRow(case.format, case.bytes(), &data)
+                };
+                let words = host
+                    .dispatch(
+                        &root,
+                        &pso,
+                        &Dispatch {
+                            roots: vec![(0, Root::Constants(ud.clone()))],
+                            views: &[view, View::RawUav(2 * LANES as u32)],
+                            samplers: &[],
+                            groups: [1, 1, 1],
+                        },
+                    )
+                    .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
+                for (t, texel) in case.texels.iter().enumerate() {
+                    for c in 0..load.channels() {
+                        let got = (words[0][2 * t + c / 2] >> (16 * (c % 2))) as u16;
+                        let want = (case.want)(texel, c);
+                        if !want.is(got) {
+                            let want = match want {
+                                Want::Half(w) => format!("{w:#06x}"),
+                                Want::Nan => "a NaN".into(),
+                                Want::NanOr(w) => format!("a NaN or {w:#06x}"),
+                            };
+                            out.push(format!(
+                                "{label} {load:?} {} {texel:x?} channel {c}: {got:#06x}, not {want}",
+                                case.name,
+                            ));
+                        }
+                    }
+                }
+            }
+        }
+    }
+    assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available");
+    out
+}
+
+fn assert_none(failures: &[String]) {
+    assert!(
+        failures.is_empty(),
+        "{} channels differ, among them:\n{}",
+        failures.len(),
+        failures
+            .iter()
+            .step_by((failures.len() / 12).max(1))
+            .cloned()
+            .collect::<Vec<_>>()
+            .join("\n")
+    );
+}
+
+/// The channels of an integer texel keep their low 16 bits; absent ones are
+/// the integers 0, 0 and 1.
+fn integer(
+    name: &'static str,
+    format: DXGI_FORMAT,
+    bits: usize,
+    values: &[u32],
+    channels: usize,
+    signed: bool,
+) -> Case {
+    Case {
+        name,
+        format,
+        bits,
+        texels: texels(values, channels),
+        want: Box::new(move |texel, c| {
+            let Some(&x) = texel.get(c) else {
+                return Want::Half(u16::from(c == 3));
+            };
+            Want::Half(match (bits, signed) {
+                (8, true) => i16::from(x as i8) as u16,
+                _ => x as u16,
+            })
+        }),
+    }
+}
+
+#[test]
+fn d16_loads_keep_integer_texels() {
+    // Ends and middles of both ranges, and the bits of f16 1.0, 0xFFFC (a
+    // NaN) and others that mean something else as a float.
+    let word = [
+        0, 1, 2, 7, 0xFF, 0x100, 500, 0x1FFF, 0x2000, 0x3BFF, 0x3C00, 0x7BFF, 0x7C00, 0x7FFE,
+        0x7FFF, 0x8001, 0x8000, 0xA000, 0xC000, 0xE000, 0x8002, 0xBC00, 0xFC00, 0xFE00, 0xFFFB,
+        0xFFFC, 0xFFFD, 0xFFFE, 0xFFFF,
+    ];
+    // Four channels whose low 13 bits are all 0, and four that are all
+    // negative: each texel shows one way to be no half.
+    let steps = [0, 0x2000, 0x4000, 0x6000, 0x8000, 0xA000, 0xC000, 0xE000];
+    let minus = [0xFFFF, 0xFFFE, 0xFFFC, 0x8001, 0xE001, 0x8000, 0xC000];
+    let byte = [
+        0, 1, 2, 7, 0x3C, 0x7E, 0x7F, 0x80, 0x81, 0xBC, 0xFB, 0xFE, 0xFF,
+    ];
+    // 32 bits a channel: the values that fit in 16.
+    let small = [0, 1, 7, 500, 0x7FFF];
+    let unsigned = [0, 1, 7, 500, 0x7FFF, 0x8000, 0xFFFF];
+    let negative = [
+        0,
+        1,
+        0x7FFF,
+        0xFFFF_FFFF,
+        0xFFFF_FFFE,
+        0xFFFF_FF80,
+        0xFFFF_8001,
+        0xFFFF_8000,
+    ];
+    let u = |n, f, bits, v: &[u32], ch| integer(n, f, bits, v, ch, false);
+    let s = |n, f, bits, v: &[u32], ch| integer(n, f, bits, v, ch, true);
+    let cases = [
+        u("R16_UINT", DXGI_FORMAT_R16_UINT, 16, &word, 1),
+        s("R16_SINT", DXGI_FORMAT_R16_SINT, 16, &word, 1),
+        u("R16G16_UINT", DXGI_FORMAT_R16G16_UINT, 16, &word, 2),
+        s("R16G16_SINT", DXGI_FORMAT_R16G16_SINT, 16, &word, 2),
+        u("RGBA16_UINT", DXGI_FORMAT_R16G16B16A16_UINT, 16, &word, 4),
+        s("RGBA16_SINT", DXGI_FORMAT_R16G16B16A16_SINT, 16, &word, 4),
+        u(
+            "RGBA16_UINT steps",
+            DXGI_FORMAT_R16G16B16A16_UINT,
+            16,
+            &steps[1..],
+            4,
+        ),
+        s(
+            "RGBA16_SINT minus",
+            DXGI_FORMAT_R16G16B16A16_SINT,
+            16,
+            &minus,
+            4,
+        ),
+        u("R8_UINT", DXGI_FORMAT_R8_UINT, 8, &byte, 1),
+        s("R8_SINT", DXGI_FORMAT_R8_SINT, 8, &byte, 1),
+        u("R8G8_UINT", DXGI_FORMAT_R8G8_UINT, 8, &byte, 2),
+        s("R8G8_SINT", DXGI_FORMAT_R8G8_SINT, 8, &byte, 2),
+        u("RGBA8_UINT", DXGI_FORMAT_R8G8B8A8_UINT, 8, &byte, 4),
+        s("RGBA8_SINT", DXGI_FORMAT_R8G8B8A8_SINT, 8, &byte, 4),
+        u("R32_UINT", DXGI_FORMAT_R32_UINT, 32, &unsigned, 1),
+        s("R32_SINT", DXGI_FORMAT_R32_SINT, 32, &negative, 1),
+        u("R32G32_UINT", DXGI_FORMAT_R32G32_UINT, 32, &small, 2),
+    ];
+    assert_none(&failures(&cases));
+}
+
+/// The channels of a float or normalized texel become f16; absent ones are
+/// 0, 0 and 1.0.
+fn float(
+    name: &'static str,
+    format: DXGI_FORMAT,
+    bits: usize,
+    channels: usize,
+    values: &[(u32, u16)],
+) -> Case {
+    let stored: Vec<u32> = values.iter().map(|v| v.0).collect();
+    let values = values.to_vec();
+    Case {
+        name,
+        format,
+        bits,
+        texels: texels(&stored, channels),
+        want: Box::new(move |texel, c| {
+            let Some(&x) = texel.get(c) else {
+                return Want::Half(if c == 3 { 0x3C00 } else { 0 });
+            };
+            let f16 = values.iter().find(|v| v.0 == x).expect("a value").1;
+            if Want::Nan.is(f16) {
+                Want::Nan
+            } else {
+                Want::Half(f16)
+            }
+        }),
+    }
+}
+
+#[test]
+fn d16_loads_convert_float_and_normalized_texels() {
+    // Half floats keep their bits: zeros, denormals, the ends of the range,
+    // infinities and NaNs, among them the four (0xFFFC..=0xFFFF) whose f32
+    // bits are also those of 16-bit integers.
+    let half: Vec<(u32, u16)> = [
+        0u16, 0x8000, 1, 0x8001, 0x3FF, 0x400, 0x3C00, 0xBC00, 0x3555, 0x7BFF, 0xFBFF, 0x7C00,
+        0xFC00, 0x7E00, 0xFE00, 0x7FFF, 0xFFFB, 0xFFFC, 0xFFFD, 0xFFFE, 0xFFFF,
+    ]
+    .into_iter()
+    .map(|h| (u32::from(h), h))
+    .collect();
+    let unorm8 = [(0, 0), (0xFF, 0x3C00)];
+    let snorm8 = [(0, 0), (0x7F, 0x3C00), (0x80, 0xBC00), (0x81, 0xBC00)];
+    let unorm16 = [(0, 0), (0xFFFF, 0x3C00)];
+    let snorm16 = [(0, 0), (0x7FFF, 0x3C00), (0x8000, 0xBC00), (0x8001, 0xBC00)];
+    let f32s: Vec<(u32, u16)> = [
+        (0.0f32, 0),
+        (-0.0, 0x8000),
+        (1.0, 0x3C00),
+        (-2.5, 0xC100),
+        (65504.0, 0x7BFF),
+        (2.0f32.powi(-14), 0x0400),
+        (2.0f32.powi(-24), 0x0001),
+        (f32::INFINITY, 0x7C00),
+        (f32::NEG_INFINITY, 0xFC00),
+        (f32::NAN, 0x7E00),
+    ]
+    .into_iter()
+    .map(|(x, h)| (x.to_bits(), h))
+    .collect();
+    // 32 bits a channel with an absent last one: also values and NaNs whose
+    // bits are those of 16-bit integers.
+    let mut odd = f32s.clone();
+    odd.extend([(1, 0), (0x7C00, 0), (0xFFFF, 0)]);
+    odd.extend([0xFFFF_8000, 0xFFFF_8001, 0xFFFF_FC01, u32::MAX].map(|x| (x, 0x7E00)));
+    // Texels of nothing but zeros and NaNs: those four and others.
+    let nans: Vec<(u32, u16)> = [0u16, 0xFFFC, 0xFFFD, 0xFFFE, 0xFFFF, 0, 0x7E00, 0x7FFF]
+        .into_iter()
+        .map(|h| (u32::from(h), h))
+        .collect();
+    let cases = [
+        float("R16_FLOAT", DXGI_FORMAT_R16_FLOAT, 16, 1, &half),
+        float("R16G16_FLOAT", DXGI_FORMAT_R16G16_FLOAT, 16, 2, &half),
+        float("RGBA16_FLOAT", DXGI_FORMAT_R16G16B16A16_FLOAT, 16, 4, &half),
+        float(
+            "RGBA16_FLOAT NaNs",
+            DXGI_FORMAT_R16G16B16A16_FLOAT,
+            16,
+            4,
+            &nans,
+        ),
+        float("R32_FLOAT", DXGI_FORMAT_R32_FLOAT, 32, 1, &odd),
+        float("R32G32_FLOAT", DXGI_FORMAT_R32G32_FLOAT, 32, 2, &odd),
+        float("RGBA32_FLOAT", DXGI_FORMAT_R32G32B32A32_FLOAT, 32, 4, &f32s),
+        float("R8_UNORM", DXGI_FORMAT_R8_UNORM, 8, 1, &unorm8),
+        float("RGBA8_UNORM", DXGI_FORMAT_R8G8B8A8_UNORM, 8, 4, &unorm8),
+        float("RGBA8_SNORM", DXGI_FORMAT_R8G8B8A8_SNORM, 8, 4, &snorm8),
+        float("R16_UNORM", DXGI_FORMAT_R16_UNORM, 16, 1, &unorm16),
+        float("R16_SNORM", DXGI_FORMAT_R16_SNORM, 16, 1, &snorm16),
+    ];
+    assert_none(&failures(&cases));
+}
+
+/// Two known limits, not wishes: the shader does not know the view's format,
+/// and what it loads is the same 32-bit words either way. A change that tells
+/// them apart should turn this test around.
+#[test]
+fn d16_loads_cannot_tell_these_texels_apart() {
+    // Four 16-bit integers all 0, -0x8000, -0x6000, -0x4000 or -0x2000 are
+    // taken for zeros and the f16 NaNs 0xFFFC..=0xFFFF. The console keeps the
+    // integers, as does a host that merges the load with its conversion.
+    let mut nans = integer(
+        "RGBA16_SINT",
+        DXGI_FORMAT_R16G16B16A16_SINT,
+        16,
+        &[0x8000, 0xA000, 0xC000, 0xE000],
+        4,
+        true,
+    );
+    nans.want = Box::new(|texel, c| Want::NanOr(texel[c] as u16));
+    // Four 32-bit floats below 2^-133 are taken for integers; the console
+    // gives 0.
+    let tiny = [(1, 1), (0x7C00, 0x7C00), (0xFFFF, 0xFFFF), (0, 0)];
+    let mut tiny = float("RGBA32_FLOAT", DXGI_FORMAT_R32G32B32A32_FLOAT, 32, 4, &tiny);
+    tiny.want = Box::new(|texel, c| Want::Half(texel[c] as u16));
+    assert_none(&failures(&[nans, tiny]));
+}
diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs
index 816d8e2..191445f 100644
--- a/crates/victory-shader/src/emit/host.rs
+++ b/crates/victory-shader/src/emit/host.rs
@@ -1193,6 +1193,9 @@ pub enum View<'a> {
     Cbv(&'a [u32]),
     /// A buffer SRV over these dwords.
     Buffer { data: &'a [u32], stride: Stride },
+    /// A texture SRV of one row, its texels these dwords in this format of
+    /// this many bytes.
+    TextureRow(DXGI_FORMAT, u32, &'a [u32]),
     /// Title memory: a buffer holding these dwords viewed raw, as an SRV at
     /// its index and a UAV at the next (whose entry is [`View::Pair`]),
     /// read back like the UAVs.
@@ -1493,6 +1496,32 @@ impl Host {
                         dev.CreateShaderResourceView(&tex, None, at);
                         keep.push(tex);
                     }
+                    View::TextureRow(format, bytes, data) => {
+                        let w = data.len() as u32 * 4 / bytes;
+                        let tex = make(
+                            D3D12_HEAP_TYPE_DEFAULT,
+                            &texture_as(w, 1, D3D12_RESOURCE_FLAG_NONE, format),
+                            D3D12_RESOURCE_STATE_COPY_DEST,
+                        )?;
+                        let b = upload(data)?;
+                        let mut from = footprint(&b, w, 1);
+                        from.Anonymous.PlacedFootprint.Footprint = D3D12_SUBRESOURCE_FOOTPRINT {
+                            Format: format,
+                            Width: w,
+                            Height: 1,
+                            Depth: 1,
+                            RowPitch: (w * bytes).next_multiple_of(256),
+                        };
+                        list.CopyTextureRegion(&subresource(&tex), 0, 0, 0, &from, None);
+                        list.ResourceBarrier(&[transition(
+                            &tex,
+                            D3D12_RESOURCE_STATE_COPY_DEST,
+                            D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
+                        )]);
+                        dev.CreateShaderResourceView(&tex, None, at);
+                        keep.push(b);
+                        keep.push(tex);
+                    }
                     View::RawUav(_) | View::HalfUav(_) => {
                         // (dwords, format, elements, flags)
                         let (n, format, elements, flags) = match *v {
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index 65bd8f2..e9e5477 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -7312,6 +7312,91 @@ impl<'a> Lower<'a> {
         self.s.m.bin(c, Bin::Or, old, x)
     }
 
+    /// The listed channels of the typed float load `r` as `d16` data, each
+    /// in the low half; `again` repeats the load with integer channels.
+    ///
+    /// The view's format is not known here: the console's load gives 16 bits
+    /// of an integer and makes anything else an f16. A host compiler that
+    /// merges a load and its conversion to f16 (AMD's) emits that very load,
+    /// as long as nothing else uses the load. On other hosts the channels of
+    /// an integer format arrive as the bits of floats, all of which become 0
+    /// or NaN: only where every half is one of these are the bits looked at.
+    /// (By a load with status: AMD's compiler takes a plain second load for
+    /// the first, which then has another use.)
+    ///
+    /// A texel is taken as integers where all four channels are integers of
+    /// up to 16 bits, 0..=0xFFFF or -0x8000..=-1, and one of them is no
+    /// 16-bit float. A channel the format lacks takes part: it is 0, the last
+    /// one 1, the integer or the float. Of the f16 values only 0 and four
+    /// NaNs load as such integers: 0xFFFC..=0xFFFF as 0xFFFF_8000,
+    /// 0xFFFF_A000, 0xFFFF_C000 and 0xFFFF_E000.
+    // shortcut: without the format, texels of four 16-bit signed integers
+    // all 0, -0x8000, -0x6000, -0x4000 or -0x2000 are taken as floats where
+    // the host does not merge, and texels of four 32-bit floats that are all
+    // 0, below 2^-133 or NaNs from 0xFFFF_8000 as integers. Integers past 16
+    // bits, which the console saturates, are right only where the host
+    // merges.
+    fn d16_load(
+        &mut self,
+        r: V,
+        channels: &[u32],
+        again: impl FnOnce(&mut Self) -> Result<V, Why>,
+    ) -> Result<Vec<V>, Why> {
+        let c = self.cur;
+        let i32t = self.s.t.i32;
+        let (zero, low13, word) = (self.s.m.i32(0), self.s.m.i32(0x1FFF), self.s.m.i32(0xFFFF));
+        let (k8000, last) = (self.s.m.i32(0x8000), self.s.m.i32(0x1_7FFF));
+        let (no_sign, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
+        let mut halves = Vec::new();
+        let mut odd = self.s.m.bool(true);
+        for &ch in channels {
+            let x = self.s.m.extract(c, r, ch);
+            let h = self
+                .s
+                .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]);
+            halves.push(h);
+            let none = self.s.m.cmp(c, pred::EQ, h, zero);
+            let a = self.s.m.bin(c, Bin::And, h, no_sign);
+            let nan = self.s.m.cmp(c, pred::IUGT, a, infinity);
+            let either = self.s.m.bin(c, Bin::Or, none, nan);
+            odd = self.s.m.bin(c, Bin::And, odd, either);
+        }
+        let begin = self.begin_guarded(Some(odd));
+        let r = again(self)?;
+        let c = self.cur;
+        self.s.flags |= flags::TILED_RESOURCES;
+        let status = self.s.m.extract(c, r, 4);
+        let i1 = self.s.t.i1;
+        let name = "checkAccessFullyMapped.i32";
+        let mapped = self.s.op(c, name, Attr::ReadOnly, i1, 71, &[status]);
+        // Biased by 0x8000 the integers of up to 16 bits are 0..=0x1_7FFF,
+        // those above 0x8000 positive.
+        let bits: Vec<V> = (0..4).map(|ch| self.s.m.extract(c, r, ch)).collect();
+        let (mut any, mut most) = (zero, zero);
+        for &x in &bits {
+            any = self.s.m.bin(c, Bin::Or, any, x);
+            let x = self.s.m.bin(c, Bin::Add, x, k8000);
+            let more = self.s.m.cmp(c, pred::IUGT, x, most);
+            most = self.s.m.select(c, more, x, most);
+        }
+        let fit = self.s.m.cmp(c, pred::IULE, most, last);
+        let positive = self.s.m.cmp(c, pred::IUGT, most, k8000);
+        let low = self.s.m.bin(c, Bin::And, any, low13);
+        let low = self.s.m.cmp(c, pred::NE, low, zero);
+        let no_half = self.s.m.bin(c, Bin::Or, positive, low);
+        let integers = self.s.m.bin(c, Bin::And, fit, no_half);
+        let integers = self.s.m.bin(c, Bin::And, integers, mapped);
+        let values: Vec<(V, V)> = channels
+            .iter()
+            .zip(halves)
+            .map(|(&ch, h)| {
+                let x = self.s.m.bin(c, Bin::And, bits[ch as usize], word);
+                (self.s.m.select(c, integers, x, h), h)
+            })
+            .collect();
+        Ok(self.end_guarded(begin, &values))
+    }
+
     fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
         let Fields::Image {
             data,
@@ -7632,6 +7717,8 @@ impl<'a> Lower<'a> {
         let h = self.handle(site, src, false, props)?;
         let fu = self.s.m.undef(self.s.t.f32);
         let iu = self.s.m.undef(self.s.t.i32);
+        // A plain load's operands.
+        let mut load = None;
         let r = if sample {
             let ss = self
                 .descriptors
@@ -7944,6 +8031,7 @@ impl<'a> Lower<'a> {
             let mut args = vec![h, mip];
             args.extend(&cs);
             args.extend([iu, iu, iu]);
+            load = Some(args.clone());
             self.s.op(
                 c,
                 "textureLoad.f32",
@@ -7962,18 +8050,28 @@ impl<'a> Lower<'a> {
             (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
         };
         let mut xs = Vec::new();
-        for ch in channels {
-            let x = self.s.m.extract(c, r, ch);
-            xs.push(if *d16 {
-                // shortcut: d16 results are taken as floats (rounded to
-                // nearest even); integer formats would keep 16 bits.
-                let i32t = self.s.t.i32;
-                self.s
-                    .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
-            } else {
-                self.as_int(x)
-            });
+        if let (true, Some(mut args)) = (*d16, load) {
+            xs = self.d16_load(r, &channels, |l| {
+                let ret = l.s.int_ret();
+                args[0] = l.handle(site, src, false, (props.0, 0x405))?;
+                Ok(l.s.op(l.cur, "textureLoad.i32", Attr::ReadOnly, ret, 66, &args))
+            })?;
+        } else {
+            for ch in channels {
+                let x = self.s.m.extract(c, r, ch);
+                xs.push(if *d16 {
+                    // shortcut: sampled and gathered d16 results are taken
+                    // as floats (rounded to nearest even); integer formats
+                    // would keep 16 bits.
+                    let i32t = self.s.t.i32;
+                    self.s
+                        .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
+                } else {
+                    self.as_int(x)
+                });
+            }
         }
+        let c = self.cur;
         if *d16 {
             // Two channels per VGPR, low half first (an odd last high half 0).
             let k16 = self.s.m.i32(16);
@@ -8719,16 +8817,20 @@ impl<'a> Lower<'a> {
             return Err("a buffer result");
         };
         if d16 {
-            // Two f16 channels per VGPR (an odd last high half 0).
+            // Two 16-bit channels per VGPR (an odd last high half 0).
             let k16 = self.s.m.i32(16);
-            let i32t = self.s.t.i32;
+            let channels: Vec<u32> = (0..count).collect();
+            let halves = self.d16_load(r, &channels, |l| {
+                let ret = l.s.int_ret();
+                let h = l.handle(site, src, false, (10 | u, 0x405))?;
+                let args = [h, index.unwrap_or(l.s.m.i32(0)), iu];
+                Ok(l.s.op(l.cur, "bufferLoad.i32", Attr::ReadOnly, ret, 68, &args))
+            })?;
+            let c = self.cur;
             for k in 0..count.div_ceil(2) {
                 let mut x = None;
                 for ch in (2 * k..(2 * k + 2).min(count)).rev() {
-                    let f = self.s.m.extract(c, r, ch);
-                    let h = self
-                        .s
-                        .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
+                    let h = halves[ch as usize];
                     x = Some(match x {
                         Some(hi) => {
                             let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs
index 498e2aa..9d29ed8 100644
--- a/crates/victory-shader/src/emit/mod.rs
+++ b/crates/victory-shader/src/emit/mod.rs
@@ -171,6 +171,8 @@ mod bitcode;
 mod bvh_tests;
 mod container;
 #[cfg(all(test, windows))]
+mod d16_tests;
+#[cfg(all(test, windows))]
 mod diff_tests;
 #[cfg(all(test, windows))]
 mod flow_tests;
diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs
index 51e170c..f357052 100644
--- a/crates/victory-shader/src/emit/shader.rs
+++ b/crates/victory-shader/src/emit/shader.rs
@@ -34,6 +34,7 @@ pub const NULL_BUFFER_VIEW: u32 = HEAP_VIEWS - 2;
 pub(crate) mod flags {
     pub const RAW_BUFFERS: u64 = 1 << 4;
     pub const STENCIL_REF: u64 = 1 << 11;
+    pub const TILED_RESOURCES: u64 = 1 << 12;
     pub const TYPED_UAV_LOADS: u64 = 1 << 13;
     pub const ROVS: u64 = 1 << 18;
     pub const WAVE_OPS: u64 = 1 << 19;
@@ -227,6 +228,12 @@ impl Shader {
         self.m.select(block, cond, r, other)
     }
 
+    /// The result type of a typed load with integer channels.
+    pub fn int_ret(&mut self) -> Ty {
+        let i32t = self.t.i32;
+        self.m.named_struct("dx.types.ResRet.i32", vec![i32t; 5])
+    }
+
     /// The handle of the user-data constant buffer, made in the entry block.
     pub fn user_data_handle(&mut self) -> V {
         let bind = [
@@ -802,6 +809,9 @@ impl Shader {
         dxil.extend(&bitcode);
 
         let mut features = 0u64;
+        if self.flags & flags::TILED_RESOURCES != 0 {
+            features |= 0x100;
+        }
         if self.flags & flags::STENCIL_REF != 0 {
             features |= 0x200;
         }

🤖 Generated with Claude Code

**@⁠Speartone** on GitHub · 2026-11-25 04:34 UTC · [original](https://github.com/Marvisak/VIctory/issues/2087) Submitted as an **experimental** patch, not a production-ready fix, because of a known floating-point regression (first limit below). Author: Speartone. Based on `70564ae`. A typed d16 load is lowered to a float load and legacyF32ToF16. On a host that does not merge the two into its own 16-bit load, integer texels arrive as float bits and become 0 or NaN. AMD's driver merges them, so an RDNA2 GPU was right already; an RTX 5080 and WARP were not. The load and conversion stay. Only where every half is 0 or NaN is the texel loaded again as integers, and 16 bits of each channel kept if all of it is integers of up to 16 bits. **Tests (synthetic):** without the change 11,142 wrong channels; with it the covered cases pass on RTX 5080, AMD RDNA2 and WARP. 14 of 15 mutations fail a test; the other cannot change a result. victory-shader: 209 pass, 3 fail; the same 3 fail without the change. Only victory-shader was built. **Limits: coverage is incomplete.** - **Known floating-point regression, on every host:** a texel of four 32-bit floats that are all 0, below 2^-133 or NaNs from 0xFFFF8000, and not all 0, can load as integers; the console gives 0 or a NaN. - Where the host does not merge, texels of four 16-bit signed integers that are all 0, -32768, -24576, -16384 or -8192 still load as floats. - Integers past 16 bits stay wrong where the host does not merge. - d16 samples, gathers and stores are as before. - Shaders with such loads need tiled resources. Intel GPUs were not tried. A small conflict with #1693 is likely. General compatibility defect with no demonstrated GTA VI impact. Actual GTA VI gameplay has not been tested. AI-assisted: analysis, code, tests and text by Claude Code (Claude Opus 5.5). No game data. <details><summary>Patch (source and tests)</summary> ````diff diff --git a/crates/victory-shader/src/emit/d16_tests.rs b/crates/victory-shader/src/emit/d16_tests.rs new file mode 100644 index 0000000..b0cced1 --- /dev/null +++ b/crates/victory-shader/src/emit/d16_tests.rs @@ -0,0 +1,543 @@ +//! End-to-end tests of `d16` typed loads: synthetic GFX10 programs lowered to +//! DXIL, validated by `dxil.dll` when present, and run on the host GPU and +//! WARP over typed buffers and textures of integer and float formats. + +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::host::{Dispatch, Host, Root, Stride, View}; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +/// Texels per view, one per lane. +const LANES: usize = 32; + +/// Which instruction loads the texel. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Load { + Buffer, + /// The first channel only. + BufferX, + Image, + /// The first channel only. + ImageX, + ImageMip, +} + +impl Load { + fn buffer(self) -> bool { + matches!(self, Load::Buffer | Load::BufferX) + } + + fn channels(self) -> usize { + if matches!(self, Load::BufferX | Load::ImageX) { + 1 + } else { + 4 + } + } +} + +/// A wave32 program of 32 lanes: lane n loads texel n of the view at heap +/// index 0 with a `d16` load, and stores two dwords of halves at byte 8 * n +/// of the raw UAV at heap index 1. `s0` is the table of views. +fn program(load: Load) -> Vec<u32> { + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0020, // s_load_dwordx4 s[40:43], s[4:5], 0x20 + 0x3420_0083, // v_lshlrev_b32 v16, 3, v0 + 0x7E1A_0280, // v_mov_b32 v13, 0 + ]; + words.extend_from_slice(match load { + Load::Buffer => &[ + 0xF408_0602, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE20C_2000, + 0x8006_0C00, // buffer_load_format_d16_xyzw v[12:13], v0, s[24:27], 0 idxen + ], + Load::BufferX => &[ + 0xF408_0602, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE200_2000, + 0x8006_0C00, // buffer_load_format_d16_x v12, v0, s[24:27], 0 idxen + ], + Load::ImageX => &[ + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0x7E04_0300, // v_mov_b32 v2, v0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF000_0108, + 0x8006_0C02, // image_load v12, v[2:3], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 + ], + Load::Image => &[ + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0x7E04_0300, // v_mov_b32 v2, v0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF000_0F08, + 0x8006_0C02, // image_load v[12:13], v[2:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D d16 + ], + Load::ImageMip => &[ + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0x7E04_0300, // v_mov_b32 v2, v0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x7E08_0280, // v_mov_b32 v4, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF004_0F08, + 0x8006_0C02, // image_load_mip v[12:13], v[2:4], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D d16 + ], + }); + words.extend_from_slice(&[ + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE074_1000, + 0x800A_0C10, // buffer_store_dwordx2 v[12:13], v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]); + words +} + +fn build(load: Load) -> HostShader { + let range = |kind, table_offset_dwords, dwords| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride: 0, + dwords, + user_data: 0, + slot: 0, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![ + range(ResourceType::Srv, 0, if load.buffer() { 4 } else { 8 }), + range(ResourceType::Uav, 8, 4), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 1, // 1 user SGPR: s0 + threads: [LANES as u32, 1, 1], + }), + code: program(load).iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }) + .expect("lower"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + memory: lowered.memory, + memory_writes: lowered.memory_writes, + view_addresses: lowered.view_addresses, + heap: lowered.heap, + heap_writes: lowered.heap_writes, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + shader +} + +/// What a channel should load as. +#[derive(Clone, Copy)] +enum Want { + Half(u16), + /// Any f16 NaN. + Nan, + NanOr(u16), +} + +impl Want { + fn is(self, got: u16) -> bool { + let nan = got & 0x7C00 == 0x7C00 && got & 0x3FF != 0; + match self { + Want::Half(w) => got == w, + Want::Nan => nan, + Want::NanOr(w) => nan || got == w, + } + } +} + +/// What channel `c` of a texel loads as. +type Wanted = Box<dyn Fn(&[u32], usize) -> Want>; + +/// A format, its stored channels and their width in bits, and 32 texels of +/// that many channels each. +struct Case { + name: &'static str, + format: DXGI_FORMAT, + bits: usize, + texels: Vec<Vec<u32>>, + want: Wanted, +} + +impl Case { + fn bytes(&self) -> u32 { + (self.texels[0].len() * self.bits / 8) as u32 + } + + /// The texels as dwords in memory. + fn data(&self) -> Vec<u32> { + let bytes: Vec<u8> = self + .texels + .iter() + .flatten() + .flat_map(|x| x.to_le_bytes()[..self.bits / 8].to_vec()) + .collect(); + bytes + .chunks(4) + .map(|b| u32::from_le_bytes(b.try_into().expect("whole dwords"))) + .collect() + } +} + +/// 32 texels of `channels` channels whose values cover `values`, the +/// channels of a texel taking different ones. +fn texels(values: &[u32], channels: usize) -> Vec<Vec<u32>> { + (0..LANES) + .map(|t| { + (0..channels) + .map(|c| values[(t + 5 * c) % values.len()]) + .collect() + }) + .collect() +} + +/// Runs every case with every load that takes its format, on hardware and +/// WARP, and lists the channels that differ from what they should be. +fn failures(cases: &[Case]) -> Vec<String> { + let mut out = Vec::new(); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for load in [ + Load::Buffer, + Load::BufferX, + Load::Image, + Load::ImageX, + Load::ImageMip, + ] { + let shader = build(load); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + ran += 1; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + // The table starts at heap index 0. + let ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for case in cases { + assert_eq!(case.texels.len(), LANES, "{}", case.name); + let data = case.data(); + let view = if load.buffer() { + View::Buffer { + data: &data, + stride: Stride::Format(case.format, case.bytes()), + } + } else { + View::TextureRow(case.format, case.bytes(), &data) + }; + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud.clone()))], + views: &[view, View::RawUav(2 * LANES as u32)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + for (t, texel) in case.texels.iter().enumerate() { + for c in 0..load.channels() { + let got = (words[0][2 * t + c / 2] >> (16 * (c % 2))) as u16; + let want = (case.want)(texel, c); + if !want.is(got) { + let want = match want { + Want::Half(w) => format!("{w:#06x}"), + Want::Nan => "a NaN".into(), + Want::NanOr(w) => format!("a NaN or {w:#06x}"), + }; + out.push(format!( + "{label} {load:?} {} {texel:x?} channel {c}: {got:#06x}, not {want}", + case.name, + )); + } + } + } + } + } + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); + out +} + +fn assert_none(failures: &[String]) { + assert!( + failures.is_empty(), + "{} channels differ, among them:\n{}", + failures.len(), + failures + .iter() + .step_by((failures.len() / 12).max(1)) + .cloned() + .collect::<Vec<_>>() + .join("\n") + ); +} + +/// The channels of an integer texel keep their low 16 bits; absent ones are +/// the integers 0, 0 and 1. +fn integer( + name: &'static str, + format: DXGI_FORMAT, + bits: usize, + values: &[u32], + channels: usize, + signed: bool, +) -> Case { + Case { + name, + format, + bits, + texels: texels(values, channels), + want: Box::new(move |texel, c| { + let Some(&x) = texel.get(c) else { + return Want::Half(u16::from(c == 3)); + }; + Want::Half(match (bits, signed) { + (8, true) => i16::from(x as i8) as u16, + _ => x as u16, + }) + }), + } +} + +#[test] +fn d16_loads_keep_integer_texels() { + // Ends and middles of both ranges, and the bits of f16 1.0, 0xFFFC (a + // NaN) and others that mean something else as a float. + let word = [ + 0, 1, 2, 7, 0xFF, 0x100, 500, 0x1FFF, 0x2000, 0x3BFF, 0x3C00, 0x7BFF, 0x7C00, 0x7FFE, + 0x7FFF, 0x8001, 0x8000, 0xA000, 0xC000, 0xE000, 0x8002, 0xBC00, 0xFC00, 0xFE00, 0xFFFB, + 0xFFFC, 0xFFFD, 0xFFFE, 0xFFFF, + ]; + // Four channels whose low 13 bits are all 0, and four that are all + // negative: each texel shows one way to be no half. + let steps = [0, 0x2000, 0x4000, 0x6000, 0x8000, 0xA000, 0xC000, 0xE000]; + let minus = [0xFFFF, 0xFFFE, 0xFFFC, 0x8001, 0xE001, 0x8000, 0xC000]; + let byte = [ + 0, 1, 2, 7, 0x3C, 0x7E, 0x7F, 0x80, 0x81, 0xBC, 0xFB, 0xFE, 0xFF, + ]; + // 32 bits a channel: the values that fit in 16. + let small = [0, 1, 7, 500, 0x7FFF]; + let unsigned = [0, 1, 7, 500, 0x7FFF, 0x8000, 0xFFFF]; + let negative = [ + 0, + 1, + 0x7FFF, + 0xFFFF_FFFF, + 0xFFFF_FFFE, + 0xFFFF_FF80, + 0xFFFF_8001, + 0xFFFF_8000, + ]; + let u = |n, f, bits, v: &[u32], ch| integer(n, f, bits, v, ch, false); + let s = |n, f, bits, v: &[u32], ch| integer(n, f, bits, v, ch, true); + let cases = [ + u("R16_UINT", DXGI_FORMAT_R16_UINT, 16, &word, 1), + s("R16_SINT", DXGI_FORMAT_R16_SINT, 16, &word, 1), + u("R16G16_UINT", DXGI_FORMAT_R16G16_UINT, 16, &word, 2), + s("R16G16_SINT", DXGI_FORMAT_R16G16_SINT, 16, &word, 2), + u("RGBA16_UINT", DXGI_FORMAT_R16G16B16A16_UINT, 16, &word, 4), + s("RGBA16_SINT", DXGI_FORMAT_R16G16B16A16_SINT, 16, &word, 4), + u( + "RGBA16_UINT steps", + DXGI_FORMAT_R16G16B16A16_UINT, + 16, + &steps[1..], + 4, + ), + s( + "RGBA16_SINT minus", + DXGI_FORMAT_R16G16B16A16_SINT, + 16, + &minus, + 4, + ), + u("R8_UINT", DXGI_FORMAT_R8_UINT, 8, &byte, 1), + s("R8_SINT", DXGI_FORMAT_R8_SINT, 8, &byte, 1), + u("R8G8_UINT", DXGI_FORMAT_R8G8_UINT, 8, &byte, 2), + s("R8G8_SINT", DXGI_FORMAT_R8G8_SINT, 8, &byte, 2), + u("RGBA8_UINT", DXGI_FORMAT_R8G8B8A8_UINT, 8, &byte, 4), + s("RGBA8_SINT", DXGI_FORMAT_R8G8B8A8_SINT, 8, &byte, 4), + u("R32_UINT", DXGI_FORMAT_R32_UINT, 32, &unsigned, 1), + s("R32_SINT", DXGI_FORMAT_R32_SINT, 32, &negative, 1), + u("R32G32_UINT", DXGI_FORMAT_R32G32_UINT, 32, &small, 2), + ]; + assert_none(&failures(&cases)); +} + +/// The channels of a float or normalized texel become f16; absent ones are +/// 0, 0 and 1.0. +fn float( + name: &'static str, + format: DXGI_FORMAT, + bits: usize, + channels: usize, + values: &[(u32, u16)], +) -> Case { + let stored: Vec<u32> = values.iter().map(|v| v.0).collect(); + let values = values.to_vec(); + Case { + name, + format, + bits, + texels: texels(&stored, channels), + want: Box::new(move |texel, c| { + let Some(&x) = texel.get(c) else { + return Want::Half(if c == 3 { 0x3C00 } else { 0 }); + }; + let f16 = values.iter().find(|v| v.0 == x).expect("a value").1; + if Want::Nan.is(f16) { + Want::Nan + } else { + Want::Half(f16) + } + }), + } +} + +#[test] +fn d16_loads_convert_float_and_normalized_texels() { + // Half floats keep their bits: zeros, denormals, the ends of the range, + // infinities and NaNs, among them the four (0xFFFC..=0xFFFF) whose f32 + // bits are also those of 16-bit integers. + let half: Vec<(u32, u16)> = [ + 0u16, 0x8000, 1, 0x8001, 0x3FF, 0x400, 0x3C00, 0xBC00, 0x3555, 0x7BFF, 0xFBFF, 0x7C00, + 0xFC00, 0x7E00, 0xFE00, 0x7FFF, 0xFFFB, 0xFFFC, 0xFFFD, 0xFFFE, 0xFFFF, + ] + .into_iter() + .map(|h| (u32::from(h), h)) + .collect(); + let unorm8 = [(0, 0), (0xFF, 0x3C00)]; + let snorm8 = [(0, 0), (0x7F, 0x3C00), (0x80, 0xBC00), (0x81, 0xBC00)]; + let unorm16 = [(0, 0), (0xFFFF, 0x3C00)]; + let snorm16 = [(0, 0), (0x7FFF, 0x3C00), (0x8000, 0xBC00), (0x8001, 0xBC00)]; + let f32s: Vec<(u32, u16)> = [ + (0.0f32, 0), + (-0.0, 0x8000), + (1.0, 0x3C00), + (-2.5, 0xC100), + (65504.0, 0x7BFF), + (2.0f32.powi(-14), 0x0400), + (2.0f32.powi(-24), 0x0001), + (f32::INFINITY, 0x7C00), + (f32::NEG_INFINITY, 0xFC00), + (f32::NAN, 0x7E00), + ] + .into_iter() + .map(|(x, h)| (x.to_bits(), h)) + .collect(); + // 32 bits a channel with an absent last one: also values and NaNs whose + // bits are those of 16-bit integers. + let mut odd = f32s.clone(); + odd.extend([(1, 0), (0x7C00, 0), (0xFFFF, 0)]); + odd.extend([0xFFFF_8000, 0xFFFF_8001, 0xFFFF_FC01, u32::MAX].map(|x| (x, 0x7E00))); + // Texels of nothing but zeros and NaNs: those four and others. + let nans: Vec<(u32, u16)> = [0u16, 0xFFFC, 0xFFFD, 0xFFFE, 0xFFFF, 0, 0x7E00, 0x7FFF] + .into_iter() + .map(|h| (u32::from(h), h)) + .collect(); + let cases = [ + float("R16_FLOAT", DXGI_FORMAT_R16_FLOAT, 16, 1, &half), + float("R16G16_FLOAT", DXGI_FORMAT_R16G16_FLOAT, 16, 2, &half), + float("RGBA16_FLOAT", DXGI_FORMAT_R16G16B16A16_FLOAT, 16, 4, &half), + float( + "RGBA16_FLOAT NaNs", + DXGI_FORMAT_R16G16B16A16_FLOAT, + 16, + 4, + &nans, + ), + float("R32_FLOAT", DXGI_FORMAT_R32_FLOAT, 32, 1, &odd), + float("R32G32_FLOAT", DXGI_FORMAT_R32G32_FLOAT, 32, 2, &odd), + float("RGBA32_FLOAT", DXGI_FORMAT_R32G32B32A32_FLOAT, 32, 4, &f32s), + float("R8_UNORM", DXGI_FORMAT_R8_UNORM, 8, 1, &unorm8), + float("RGBA8_UNORM", DXGI_FORMAT_R8G8B8A8_UNORM, 8, 4, &unorm8), + float("RGBA8_SNORM", DXGI_FORMAT_R8G8B8A8_SNORM, 8, 4, &snorm8), + float("R16_UNORM", DXGI_FORMAT_R16_UNORM, 16, 1, &unorm16), + float("R16_SNORM", DXGI_FORMAT_R16_SNORM, 16, 1, &snorm16), + ]; + assert_none(&failures(&cases)); +} + +/// Two known limits, not wishes: the shader does not know the view's format, +/// and what it loads is the same 32-bit words either way. A change that tells +/// them apart should turn this test around. +#[test] +fn d16_loads_cannot_tell_these_texels_apart() { + // Four 16-bit integers all 0, -0x8000, -0x6000, -0x4000 or -0x2000 are + // taken for zeros and the f16 NaNs 0xFFFC..=0xFFFF. The console keeps the + // integers, as does a host that merges the load with its conversion. + let mut nans = integer( + "RGBA16_SINT", + DXGI_FORMAT_R16G16B16A16_SINT, + 16, + &[0x8000, 0xA000, 0xC000, 0xE000], + 4, + true, + ); + nans.want = Box::new(|texel, c| Want::NanOr(texel[c] as u16)); + // Four 32-bit floats below 2^-133 are taken for integers; the console + // gives 0. + let tiny = [(1, 1), (0x7C00, 0x7C00), (0xFFFF, 0xFFFF), (0, 0)]; + let mut tiny = float("RGBA32_FLOAT", DXGI_FORMAT_R32G32B32A32_FLOAT, 32, 4, &tiny); + tiny.want = Box::new(|texel, c| Want::Half(texel[c] as u16)); + assert_none(&failures(&[nans, tiny])); +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 816d8e2..191445f 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1193,6 +1193,9 @@ pub enum View<'a> { Cbv(&'a [u32]), /// A buffer SRV over these dwords. Buffer { data: &'a [u32], stride: Stride }, + /// A texture SRV of one row, its texels these dwords in this format of + /// this many bytes. + TextureRow(DXGI_FORMAT, u32, &'a [u32]), /// Title memory: a buffer holding these dwords viewed raw, as an SRV at /// its index and a UAV at the next (whose entry is [`View::Pair`]), /// read back like the UAVs. @@ -1493,6 +1496,32 @@ impl Host { dev.CreateShaderResourceView(&tex, None, at); keep.push(tex); } + View::TextureRow(format, bytes, data) => { + let w = data.len() as u32 * 4 / bytes; + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &texture_as(w, 1, D3D12_RESOURCE_FLAG_NONE, format), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + let b = upload(data)?; + let mut from = footprint(&b, w, 1); + from.Anonymous.PlacedFootprint.Footprint = D3D12_SUBRESOURCE_FOOTPRINT { + Format: format, + Width: w, + Height: 1, + Depth: 1, + RowPitch: (w * bytes).next_multiple_of(256), + }; + list.CopyTextureRegion(&subresource(&tex), 0, 0, 0, &from, None); + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + dev.CreateShaderResourceView(&tex, None, at); + keep.push(b); + keep.push(tex); + } View::RawUav(_) | View::HalfUav(_) => { // (dwords, format, elements, flags) let (n, format, elements, flags) = match *v { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 65bd8f2..e9e5477 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -7312,6 +7312,91 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Or, old, x) } + /// The listed channels of the typed float load `r` as `d16` data, each + /// in the low half; `again` repeats the load with integer channels. + /// + /// The view's format is not known here: the console's load gives 16 bits + /// of an integer and makes anything else an f16. A host compiler that + /// merges a load and its conversion to f16 (AMD's) emits that very load, + /// as long as nothing else uses the load. On other hosts the channels of + /// an integer format arrive as the bits of floats, all of which become 0 + /// or NaN: only where every half is one of these are the bits looked at. + /// (By a load with status: AMD's compiler takes a plain second load for + /// the first, which then has another use.) + /// + /// A texel is taken as integers where all four channels are integers of + /// up to 16 bits, 0..=0xFFFF or -0x8000..=-1, and one of them is no + /// 16-bit float. A channel the format lacks takes part: it is 0, the last + /// one 1, the integer or the float. Of the f16 values only 0 and four + /// NaNs load as such integers: 0xFFFC..=0xFFFF as 0xFFFF_8000, + /// 0xFFFF_A000, 0xFFFF_C000 and 0xFFFF_E000. + // shortcut: without the format, texels of four 16-bit signed integers + // all 0, -0x8000, -0x6000, -0x4000 or -0x2000 are taken as floats where + // the host does not merge, and texels of four 32-bit floats that are all + // 0, below 2^-133 or NaNs from 0xFFFF_8000 as integers. Integers past 16 + // bits, which the console saturates, are right only where the host + // merges. + fn d16_load( + &mut self, + r: V, + channels: &[u32], + again: impl FnOnce(&mut Self) -> Result<V, Why>, + ) -> Result<Vec<V>, Why> { + let c = self.cur; + let i32t = self.s.t.i32; + let (zero, low13, word) = (self.s.m.i32(0), self.s.m.i32(0x1FFF), self.s.m.i32(0xFFFF)); + let (k8000, last) = (self.s.m.i32(0x8000), self.s.m.i32(0x1_7FFF)); + let (no_sign, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00)); + let mut halves = Vec::new(); + let mut odd = self.s.m.bool(true); + for &ch in channels { + let x = self.s.m.extract(c, r, ch); + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]); + halves.push(h); + let none = self.s.m.cmp(c, pred::EQ, h, zero); + let a = self.s.m.bin(c, Bin::And, h, no_sign); + let nan = self.s.m.cmp(c, pred::IUGT, a, infinity); + let either = self.s.m.bin(c, Bin::Or, none, nan); + odd = self.s.m.bin(c, Bin::And, odd, either); + } + let begin = self.begin_guarded(Some(odd)); + let r = again(self)?; + let c = self.cur; + self.s.flags |= flags::TILED_RESOURCES; + let status = self.s.m.extract(c, r, 4); + let i1 = self.s.t.i1; + let name = "checkAccessFullyMapped.i32"; + let mapped = self.s.op(c, name, Attr::ReadOnly, i1, 71, &[status]); + // Biased by 0x8000 the integers of up to 16 bits are 0..=0x1_7FFF, + // those above 0x8000 positive. + let bits: Vec<V> = (0..4).map(|ch| self.s.m.extract(c, r, ch)).collect(); + let (mut any, mut most) = (zero, zero); + for &x in &bits { + any = self.s.m.bin(c, Bin::Or, any, x); + let x = self.s.m.bin(c, Bin::Add, x, k8000); + let more = self.s.m.cmp(c, pred::IUGT, x, most); + most = self.s.m.select(c, more, x, most); + } + let fit = self.s.m.cmp(c, pred::IULE, most, last); + let positive = self.s.m.cmp(c, pred::IUGT, most, k8000); + let low = self.s.m.bin(c, Bin::And, any, low13); + let low = self.s.m.cmp(c, pred::NE, low, zero); + let no_half = self.s.m.bin(c, Bin::Or, positive, low); + let integers = self.s.m.bin(c, Bin::And, fit, no_half); + let integers = self.s.m.bin(c, Bin::And, integers, mapped); + let values: Vec<(V, V)> = channels + .iter() + .zip(halves) + .map(|(&ch, h)| { + let x = self.s.m.bin(c, Bin::And, bits[ch as usize], word); + (self.s.m.select(c, integers, x, h), h) + }) + .collect(); + Ok(self.end_guarded(begin, &values)) + } + fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { let Fields::Image { data, @@ -7632,6 +7717,8 @@ impl<'a> Lower<'a> { let h = self.handle(site, src, false, props)?; let fu = self.s.m.undef(self.s.t.f32); let iu = self.s.m.undef(self.s.t.i32); + // A plain load's operands. + let mut load = None; let r = if sample { let ss = self .descriptors @@ -7944,6 +8031,7 @@ impl<'a> Lower<'a> { let mut args = vec![h, mip]; args.extend(&cs); args.extend([iu, iu, iu]); + load = Some(args.clone()); self.s.op( c, "textureLoad.f32", @@ -7962,18 +8050,28 @@ impl<'a> Lower<'a> { (0..4).filter(|ch| dmask >> ch & 1 != 0).collect() }; let mut xs = Vec::new(); - for ch in channels { - let x = self.s.m.extract(c, r, ch); - xs.push(if *d16 { - // shortcut: d16 results are taken as floats (rounded to - // nearest even); integer formats would keep 16 bits. - let i32t = self.s.t.i32; - self.s - .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]) - } else { - self.as_int(x) - }); + if let (true, Some(mut args)) = (*d16, load) { + xs = self.d16_load(r, &channels, |l| { + let ret = l.s.int_ret(); + args[0] = l.handle(site, src, false, (props.0, 0x405))?; + Ok(l.s.op(l.cur, "textureLoad.i32", Attr::ReadOnly, ret, 66, &args)) + })?; + } else { + for ch in channels { + let x = self.s.m.extract(c, r, ch); + xs.push(if *d16 { + // shortcut: sampled and gathered d16 results are taken + // as floats (rounded to nearest even); integer formats + // would keep 16 bits. + let i32t = self.s.t.i32; + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]) + } else { + self.as_int(x) + }); + } } + let c = self.cur; if *d16 { // Two channels per VGPR, low half first (an odd last high half 0). let k16 = self.s.m.i32(16); @@ -8719,16 +8817,20 @@ impl<'a> Lower<'a> { return Err("a buffer result"); }; if d16 { - // Two f16 channels per VGPR (an odd last high half 0). + // Two 16-bit channels per VGPR (an odd last high half 0). let k16 = self.s.m.i32(16); - let i32t = self.s.t.i32; + let channels: Vec<u32> = (0..count).collect(); + let halves = self.d16_load(r, &channels, |l| { + let ret = l.s.int_ret(); + let h = l.handle(site, src, false, (10 | u, 0x405))?; + let args = [h, index.unwrap_or(l.s.m.i32(0)), iu]; + Ok(l.s.op(l.cur, "bufferLoad.i32", Attr::ReadOnly, ret, 68, &args)) + })?; + let c = self.cur; for k in 0..count.div_ceil(2) { let mut x = None; for ch in (2 * k..(2 * k + 2).min(count)).rev() { - let f = self.s.m.extract(c, r, ch); - let h = self - .s - .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + let h = halves[ch as usize]; x = Some(match x { Some(hi) => { let hi = self.s.m.bin(c, Bin::Shl, hi, k16); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 498e2aa..9d29ed8 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -171,6 +171,8 @@ mod bitcode; mod bvh_tests; mod container; #[cfg(all(test, windows))] +mod d16_tests; +#[cfg(all(test, windows))] mod diff_tests; #[cfg(all(test, windows))] mod flow_tests; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 51e170c..f357052 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -34,6 +34,7 @@ pub const NULL_BUFFER_VIEW: u32 = HEAP_VIEWS - 2; pub(crate) mod flags { pub const RAW_BUFFERS: u64 = 1 << 4; pub const STENCIL_REF: u64 = 1 << 11; + pub const TILED_RESOURCES: u64 = 1 << 12; pub const TYPED_UAV_LOADS: u64 = 1 << 13; pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; @@ -227,6 +228,12 @@ impl Shader { self.m.select(block, cond, r, other) } + /// The result type of a typed load with integer channels. + pub fn int_ret(&mut self) -> Ty { + let i32t = self.t.i32; + self.m.named_struct("dx.types.ResRet.i32", vec![i32t; 5]) + } + /// The handle of the user-data constant buffer, made in the entry block. pub fn user_data_handle(&mut self) -> V { let bind = [ @@ -802,6 +809,9 @@ impl Shader { dxil.extend(&bitcode); let mut features = 0u64; + if self.flags & flags::TILED_RESOURCES != 0 { + features |= 0x100; + } if self.flags & flags::STENCIL_REF != 0 { features |= 0x200; } ```` </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:54:27 +00:00
Author
Owner

@⁠YaBulochka on GitHub · 2026-11-25 04:58 UTC · original

Data point that this patch targets, measured on the GPU here: on RADV/RDNA3 the host does not merge the d16 loads.

Linux, Vulkan 1.4, Radeon RX 7600 (NAVI33). Minimal compute: R8_UNORM 256x1 and R16_UNORM 256x256 filled with every code, imageLoad(...).r into an SSBO, compared bit-for-bit with nearest-even (float)((double)code/(2^n-1)):

R8_UNORM : 0/256 differ,   max diff 0
R16_UNORM: 0/65536 differ, max diff 0

So the shader receives the correctly rounded f32, and the round-toward-zero legacyF32ToF16 is the only loss - i.e. this is one of the hosts where the "not merged" path applies. Full method and caveat in #2006.

**@⁠YaBulochka** on GitHub · 2026-11-25 04:58 UTC · [original](https://github.com/Marvisak/VIctory/issues/2087#issuecomment-7153335533) Data point that this patch targets, measured on the GPU here: on RADV/RDNA3 the host does **not** merge the d16 loads. Linux, Vulkan 1.4, Radeon RX 7600 (NAVI33). Minimal compute: `R8_UNORM` 256x1 and `R16_UNORM` 256x256 filled with every code, `imageLoad(...).r` into an SSBO, compared bit-for-bit with nearest-even `(float)((double)code/(2^n-1))`: ``` R8_UNORM : 0/256 differ, max diff 0 R16_UNORM: 0/65536 differ, max diff 0 ``` So the shader receives the correctly rounded f32, and the round-toward-zero `legacyF32ToF16` is the only loss - i.e. this is one of the hosts where the "not merged" path applies. Full method and caveat in #2006.
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 12:52 UTC · original · edited 2026-11-25 15:48 UTC

Automated triage for the maintainers.

On current main (da82e44), the three load paths this patch covers stand as follows. Everything is in crates/victory-shader/src/emit/lower.rs:

  • Image loads: confirmed. Lower::image still lowers every d16 result through legacyF32ToF16 of a float textureLoad. The shortcut: comment there says integer formats should keep 16 bits. This is the part of the patch that is still needed.
  • Typed loads through views: fixed in main by 4243a96 ("Shader: 16-bit typed buffer accesses pass bits through integer views"). The view-stride table now carries a view's format kind (VIEW_INTEGER, VIEW_SIGNED, read by integer_view). A d16 typed load through a UINT or SINT buffer view keeps each channel's low 16 bits instead of converting, so no guessing from the loaded bits is needed there.
  • Buffer-format loads (d16_channels): as upipibi notes, these already know the format and keep the low 16 bits of integer channels.

Pull requests are open to everyone: please open this patch as a PR against current main, limited to Lower::image. For textures, a per-view format tag like 4243a96's (or #2030's for #2006) would avoid the known float regression of guessing from the bits. Keep d16_channels untouched to stay clear of #1927.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 12:52 UTC · [original](https://github.com/Marvisak/VIctory/issues/2087#issuecomment-7162974449) · edited 2026-11-25 15:48 UTC <!-- victory-issue-triage v1 verdict=confirmed seen=2026-11-25T13:19:40Z at=2026-11-25T15:50:30Z --> Automated triage for the maintainers. On current `main` (da82e44), the three load paths this patch covers stand as follows. Everything is in `crates/victory-shader/src/emit/lower.rs`: - **Image loads: confirmed.** `Lower::image` still lowers every `d16` result through `legacyF32ToF16` of a float `textureLoad`. The `shortcut:` comment there says integer formats should keep 16 bits. This is the part of the patch that is still needed. - **Typed loads through views: fixed in `main`** by 4243a96 ("Shader: 16-bit typed buffer accesses pass bits through integer views"). The view-stride table now carries a view's format kind (`VIEW_INTEGER`, `VIEW_SIGNED`, read by `integer_view`). A `d16` typed load through a UINT or SINT buffer view keeps each channel's low 16 bits instead of converting, so no guessing from the loaded bits is needed there. - **Buffer-format loads** (`d16_channels`): as upipibi notes, these already know the format and keep the low 16 bits of integer channels. Pull requests are open to everyone: please open this patch as a PR against current `main`, limited to `Lower::image`. For textures, a per-view format tag like 4243a96's (or #2030's for #2006) would avoid the known float regression of guessing from the bits. Keep `d16_channels` untouched to stay clear of #1927. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠upipibi on GitHub · 2026-11-25 13:19 UTC · original

For scoping the PR asked for above: the buffer-format path doesn't need this fix. d16_channels (emit/lower.rs:4719 on main 940d32f), used by tbuffer_load_format_d16_* / buffer_load_format_d16_*, knows the format from the instruction or V#. It already keeps the low 16 bits of UINT/SINT channels and doesn't convert them with legacyF32ToF16. Our #1927 changes only that function, so 32-bit integer channels saturate instead of being masked.

So the integer-bits-arriving-as-floats problem here is in the view paths (Lower::image and the typed view loads that call legacyF32ToF16 on a float load), and a PR for it wouldn't overlap #1927 in code. If it does touch d16_channels, it would conflict with #1927 in the same lines.

AI-assisted (Claude Code). Read from the source only.

**@⁠upipibi** on GitHub · 2026-11-25 13:19 UTC · [original](https://github.com/Marvisak/VIctory/issues/2087#issuecomment-7163616088) For scoping the PR asked for above: the buffer-format path doesn't need this fix. `d16_channels` (`emit/lower.rs:4719` on `main` `940d32f`), used by `tbuffer_load_format_d16_*` / `buffer_load_format_d16_*`, knows the format from the instruction or V#. It already keeps the low 16 bits of UINT/SINT channels and doesn't convert them with `legacyF32ToF16`. Our #1927 changes only that function, so 32-bit integer channels saturate instead of being masked. So the integer-bits-arriving-as-floats problem here is in the view paths (`Lower::image` and the typed view loads that call `legacyF32ToF16` on a float load), and a PR for it wouldn't overlap #1927 in code. If it does touch `d16_channels`, it would conflict with #1927 in the same lines. AI-assisted (Claude Code). Read from the source only.
This discussion has been locked. Commenting is limited to contributors.
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.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory#2087
No description provided.