فهرست منبع

Structure builder and rays: dispatches counted in threads, empty slots never entered, pages that are not there never hit; vertex signatures as DXC orders them

From DexNom/VIctory (GPL-3.0-or-later) bc3cd4b0 and 5f4c3df4:
- DispatchX's flag 0x20 says the counts are threads (bc3cd4b0). Taken for
  groups, a rehydration stage ran up to 64 times its threads and stored over
  the structures after its own. The lanes past the count leave at once, in
  every builder program of one dimension without a group barrier (there: in
  two, by digest). VICTORY_THREAD_DIMENSIONS=0: as before.
- A child that is not there may have inverted infinite bounds: it was entered
  at minus infinity, came first and ended the walk (bc3cd4b0).
- A node in a page without a copy reads zeros, a child and a box: no hit
  (bc3cd4b0).
- Signature rows in the order of their names; vertex outputs interpolated as
  the title's PSV0 says; an unread input packed beside a per-vertex one is
  constant too (5f4c3df4), with their tests.
Every shader is translated again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 1 روز پیش
والد
کامیت
810efe5829

+ 61 - 1
crates/victory-gpu/src/draw.rs

@@ -1161,6 +1161,10 @@ impl State {
         if kind == USER_MEMORY_BASE {
         if kind == USER_MEMORY_BASE {
             return memory.map_or(0, |m| m.base);
             return memory.map_or(0, |m| m.base);
         }
         }
+        // All of every group, unless the dispatch says otherwise.
+        if kind == victory_shader::emit::USER_DISPATCH_THREADS_X {
+            return 0;
+        }
         if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 {
         if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 {
             return match self.roots_ref(compute).get(usize::from(slot)) {
             return match self.roots_ref(compute).get(usize::from(slot)) {
                 Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32,
                 Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32,
@@ -2526,7 +2530,7 @@ impl State {
     }
     }
 
 
     /// Runs a dispatch on the host.
     /// Runs a dispatch on the host.
-    pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
+    pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32, flags: u32) {
         // It may write the arguments a window holds clamped.
         // It may write the arguments a window holds clamped.
         self.window = None;
         self.window = None;
         #[cfg(feature = "diagnostics")]
         #[cfg(feature = "diagnostics")]
@@ -2578,6 +2582,23 @@ impl State {
             crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name));
             crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name));
             self.list_dropped_roots([x, y, z]);
             self.list_dropped_roots([x, y, z]);
         }
         }
+        // Counted in threads: whole groups of them, and the program is told
+        // how many of the last one run, where it asks (its `bind` set that to
+        // all of them).
+        let size = (flags & THREAD_DIMENSIONS != 0 && thread_dimensions())
+            .then(|| p.stages.first().and_then(|s| s.translated().threads))
+            .flatten();
+        let threads = [x, y, z];
+        let [x, y, z] = size.map_or(threads, |size| dispatch_groups(threads, size));
+        if size.is_some() {
+            if !crate::pipeline::is_builder(self.pipeline as This) {
+                once!(pipeline = p.name, "a dispatch counted in threads that is not the structure builder's");
+            }
+            if let Some((param, word)) = compute_word(p, victory_shader::emit::USER_DISPATCH_THREADS_X) {
+                // SAFETY: an open list; the root signature has the word.
+                unsafe { list.list.SetComputeRoot32BitConstant(param, threads[0], word) };
+            }
+        }
         // SAFETY: an open list with everything set.
         // SAFETY: an open list with everything set.
         unsafe { list.list.Dispatch(x, y, z) };
         unsafe { list.list.Dispatch(x, y, z) };
         self.buffers_written();
         self.buffers_written();
@@ -3765,6 +3786,45 @@ impl State {
     }
     }
 }
 }
 
 
+/// `DispatchX`: the counts are threads (the console's dispatch initiator bit
+/// "use thread dimensions"; DexNom/VIctory bc3cd4b0). Taken for groups, a
+/// rehydration stage of the structure builder ran up to 64 times its threads
+/// and stored over the structures after its own (runs light-1 to light-9).
+const THREAD_DIMENSIONS: u32 = 0x20;
+
+/// `VICTORY_THREAD_DIMENSIONS=0`: such counts are taken for groups, as before.
+fn thread_dimensions() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_THREAD_DIMENSIONS").is_none_or(|v| v != "0"))
+}
+
+/// The groups of `size` threads that hold `threads`.
+fn dispatch_groups(threads: [u32; 3], size: [u32; 3]) -> [u32; 3] {
+    std::array::from_fn(|i| threads[i].div_ceil(size[i]))
+}
+
+/// Where a compute pipeline's user data has a word the host computes: the
+/// root parameter and the dword in it.
+fn compute_word(p: &HostPipeline, kind: u32) -> Option<(u32, u32)> {
+    let stage = p.stages.first().filter(|_| p.compute)?;
+    let (param, _) = stage.user_data?;
+    let word = stage.translated().host.user_data.iter().find(|u| u.root == RootType::Other(kind))?;
+    Some((param, word.index))
+}
+
+#[cfg(test)]
+mod thread_tests {
+    use super::*;
+
+    #[test]
+    fn threads_are_counted_in_the_programs_groups() {
+        assert_eq!(dispatch_groups([8847, 1, 1], [64, 1, 1]), [139, 1, 1]);
+        assert_eq!(dispatch_groups([74, 1, 1], [64, 1, 1]), [2, 1, 1]);
+        assert_eq!(dispatch_groups([32, 1, 1], [32, 1, 1]), [1, 1, 1]);
+        assert_eq!(dispatch_groups([0, 12, 9], [64, 4, 4]), [0, 3, 3]);
+    }
+}
+
 /// The host command signature for one argument of `kind` with records
 /// The host command signature for one argument of `kind` with records
 /// `stride` bytes apart (no root arguments, so no root signature), made
 /// `stride` bytes apart (no root arguments, so no root signature), made
 /// once.
 /// once.

+ 8 - 9
crates/victory-gpu/src/list.rs

@@ -1435,16 +1435,15 @@ extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
     0
     0
 }
 }
 
 
-/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
-/// host has no use for (the ray-tracing builder dispatches this way).
-extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
+/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, of which the
+/// host follows one: the counts are threads, not groups (`draw.rs`
+/// `THREAD_DIMENSIONS`; the ray-tracing structure builder dispatches this way).
+extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, flags: u32) {
+    count_dispatch();
     #[cfg(windows)]
     #[cfg(windows)]
-    state::dispatch(this, x, y, z);
+    with_state(this, |list, s| s.dispatch(list, x, y, z, flags));
     #[cfg(not(windows))]
     #[cfg(not(windows))]
-    {
-        let _ = (this, x, y, z);
-        count_dispatch();
-    }
+    let _ = (this, x, y, z, flags);
 }
 }
 
 
 /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
 /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
@@ -1756,7 +1755,7 @@ mod state {
     }
     }
     pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
     pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
         super::count_dispatch();
         super::count_dispatch();
-        with_state(this, |list, s| s.dispatch(list, x, y, z));
+        with_state(this, |list, s| s.dispatch(list, x, y, z, 0));
     }
     }
     /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
     /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
     /// programs take `x` groups only.
     /// programs take `x` groups only.

+ 7 - 0
crates/victory-gpu/src/pipeline.rs

@@ -122,6 +122,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
 #[cfg(windows)]
 #[cfg(windows)]
 pub(crate) struct Translated {
 pub(crate) struct Translated {
     pub(crate) host: victory_shader::emit::HostShader,
     pub(crate) host: victory_shader::emit::HostShader,
+    /// A compute program's threads in a group.
+    pub(crate) threads: Option<[u32; 3]>,
     pub(crate) used: Vec<victory_shader::UsedResource>,
     pub(crate) used: Vec<victory_shader::UsedResource>,
     /// Whether the shader's code can store to buffer memory ([`stores`]);
     /// Whether the shader's code can store to buffer memory ([`stores`]);
     /// true when its code is not known.
     /// true when its code is not known.
@@ -200,6 +202,10 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
     };
     };
     let host = crate::shader_cache::host_shader(container)?;
     let host = crate::shader_cache::host_shader(container)?;
     let stores = programs.is_empty() || programs.iter().any(stores);
     let stores = programs.is_empty() || programs.iter().any(stores);
+    let threads = programs.iter().find_map(|p| match &p.io {
+        victory_shader::native::StageIo::Cs(cs) if cs.threads.iter().all(|&n| n > 0) => Some(cs.threads),
+        _ => None,
+    });
     let stores_by_address = programs.is_empty() || programs.iter().any(stores_by_address);
     let stores_by_address = programs.is_empty() || programs.iter().any(stores_by_address);
     let used = programs
     let used = programs
         .into_iter()
         .into_iter()
@@ -213,6 +219,7 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
         .unwrap_or_default();
         .unwrap_or_default();
     Ok(Translated {
     Ok(Translated {
         host,
         host,
+        threads,
         used,
         used,
         stores,
         stores,
         stores_by_address,
         stores_by_address,

+ 16 - 2
crates/victory-shader/src/bvh.rs

@@ -196,8 +196,11 @@ pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool)
         }
         }
         let enter = near[0].max(near[1]).max(near[2]);
         let enter = near[0].max(near[1]).max(near[2]);
         let leave = far[0].min(far[1]).min(far[2]);
         let leave = far[0].min(far[1]).min(far[2]);
-        // A box whose minimum x is NaN is switched off.
-        if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
+        // A box whose minimum x is NaN is switched off. A child that is not
+        // there may have inverted infinite bounds, which every ray enters at
+        // minus infinity: it would be first of the sorted children and end
+        // the walk before them (DexNom/VIctory bc3cd4b0).
+        if children[n] != NONE && !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
             ids[n] = children[n];
             ids[n] = children[n];
             distances[n] = enter;
             distances[n] = enter;
         }
         }
@@ -287,6 +290,17 @@ pub fn half_to_f32(h: u16) -> f32 {
 pub(crate) mod tests {
 pub(crate) mod tests {
     use super::*;
     use super::*;
 
 
+    /// An empty slot's inverted infinite bounds do not come before the
+    /// children a ray enters (after DexNom/VIctory bc3cd4b0).
+    #[test]
+    fn an_empty_slot_is_never_entered() {
+        let inside = |x: f32| [x - 1.0, -1.0, -1.0, x + 1.0, 1.0, 1.0];
+        let (up, down) = (f32::INFINITY, f32::NEG_INFINITY);
+        let bounds = [inside(30.0), [up, up, up, down, down, down], inside(10.0), [up, up, up, down, down, down]];
+        let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
+        assert_eq!(boxes(&[8, NONE, 16, NONE], &bounds, &ray, true), [16, 8, NONE, NONE]);
+    }
+
     /// The smallest 16-bit float not below `x` (`up`) or not above it.
     /// The smallest 16-bit float not below `x` (`up`) or not above it.
     pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
     pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
         let mut best: Option<u16> = None;
         let mut best: Option<u16> = None;

+ 56 - 2
crates/victory-shader/src/emit/container.rs

@@ -72,7 +72,7 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
     // Validator 1.6 writes one name per element in element order, repeats
     // Validator 1.6 writes one name per element in element order, repeats
     // included, except that system values share theirs (it keys names by
     // included, except that system values share theirs (it keys names by
     // the semantic's string, which is one static string per system value);
     // the semantic's string, which is one static string per system value);
-    // the rows sorted by register (unallocated last).
+    // the rows sorted by register (unallocated last), then name offset.
     let mut offsets: Vec<u32> = Vec::new();
     let mut offsets: Vec<u32> = Vec::new();
     let mut next = 8 + 32 * elements.len() as u32;
     let mut next = 8 + 32 * elements.len() as u32;
     let mut names = Vec::new();
     let mut names = Vec::new();
@@ -90,7 +90,7 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
         }
         }
     }
     }
     let mut order: Vec<usize> = (0..elements.len()).collect();
     let mut order: Vec<usize> = (0..elements.len()).collect();
-    order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
+    order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), offsets[i]));
     for i in order {
     for i in order {
         let (e, offset) = (&elements[i], offsets[i]);
         let (e, offset) = (&elements[i], offsets[i]);
         let used = e.usage << e.col;
         let used = e.usage << e.col;
@@ -419,6 +419,60 @@ fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
 mod tests {
 mod tests {
     use super::*;
     use super::*;
 
 
+    #[test]
+    fn packed_vertex_outputs_preserve_name_order_and_declared_interpolation() {
+        let integer = SigElement {
+            name: "TEXCOORD".into(),
+            index: 1,
+            kind: 0,
+            comp: 5,
+            interp: 1,
+            row: Some(0),
+            col: 2,
+            cols: 2,
+            usage: 3,
+            half: false,
+        };
+        let flat_float = SigElement {
+            name: "COLOR".into(),
+            index: 0,
+            comp: 9,
+            col: 0,
+            ..integer.clone()
+        };
+        let smooth_float = SigElement {
+            index: 2,
+            row: Some(1),
+            interp: 2,
+            comp: 9,
+            ..integer.clone()
+        };
+        let outputs = [integer, flat_float, smooth_float];
+        let mut recovered = super::super::signature(&signature(&outputs, false)).unwrap();
+        // DXC orders the row by semantic-name offset even though TEXCOORD
+        // occupies z/w and COLOR occupies x/y.
+        assert_eq!(recovered[0].name, "TEXCOORD");
+        assert_eq!(recovered[1].name, "COLOR");
+        // PSV records can be in a different order again.
+        let psv = psv(&Psv {
+            stage: 1,
+            flag: false,
+            inputs: &[],
+            outputs: &[outputs[2].clone(), outputs[1].clone(), outputs[0].clone()],
+            prims: &[],
+            mesh: None,
+            geometry: None,
+            bindings: &[],
+            threads: [0; 3],
+            wave_size: None,
+        });
+        recovered[1].interp = 2;
+        super::super::vertex_output_interpolation(&psv, &mut recovered).unwrap();
+        assert_eq!(recovered.iter().map(|e| e.interp).collect::<Vec<_>>(), [1, 1, 2]);
+        assert!(super::super::vertex_output_interpolation(&psv[..psv.len() - 1], &mut recovered)
+            .is_err());
+    }
+
     #[test]
     #[test]
     fn md5_core_matches_the_standard() {
     fn md5_core_matches_the_standard() {
         // Standard MD5 of "abc" with standard padding, through md5_block.
         // Standard MD5 of "abc" with standard padding, through md5_block.

+ 64 - 24
crates/victory-shader/src/emit/intersect.rs

@@ -46,8 +46,9 @@ enum NodeAt {
     Buffer { handle: V, byte: V },
     Buffer { handle: V, byte: V },
     /// In title memory: the raw view of the host copy holding the node's
     /// In title memory: the raw view of the host copy holding the node's
     /// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
     /// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
-    /// and the node's address, for the second half of a 128-byte node.
-    Memory { handle: V, byte: V, low: V, high: V },
+    /// the node's address, for the second half of a 128-byte node, and
+    /// whether there is a copy.
+    Memory { handle: V, byte: V, low: V, high: V, mapped: V },
 }
 }
 
 
 /// The ray operands, as floats.
 /// The ray operands, as floats.
@@ -163,12 +164,13 @@ impl<'a> Lower<'a> {
                 // One look for the node's copy, before the branches: a
                 // One look for the node's copy, before the branches: a
                 // node is 64 bytes on 64, so its first half lies in one
                 // node is 64 bytes on 64, so its first half lies in one
                 // 64 KiB page whatever its kind.
                 // 64 KiB page whatever its kind.
-                let (handle, byte) = self.bvh_memory(low, high, guard);
+                let (handle, byte, mapped) = self.bvh_memory(low, high, guard);
                 NodeAt::Memory {
                 NodeAt::Memory {
                     handle,
                     handle,
                     byte,
                     byte,
                     low,
                     low,
                     high,
                     high,
+                    mapped,
                 }
                 }
             }
             }
         };
         };
@@ -225,7 +227,7 @@ impl<'a> Lower<'a> {
     /// host copy holding the address and the byte in that view
     /// host copy holding the address and the byte in that view
     /// ([`Lower::memory`]: a page the host has no copy of reads zeros and
     /// ([`Lower::memory`]: a page the host has no copy of reads zeros and
     /// is left for the host to fetch, for lanes that run).
     /// is left for the host to fetch, for lanes that run).
-    fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) {
+    fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V, V) {
         #[cfg(test)]
         #[cfg(test)]
         if let Some((slot, base)) = TEST_MEMORY.get() {
         if let Some((slot, base)) = TEST_MEMORY.get() {
             // The buffer at heap slot `slot` holds the bytes from title
             // The buffer at heap slot `slot` holds the bytes from title
@@ -242,34 +244,49 @@ impl<'a> Lower<'a> {
             let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
             let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
             let outside = self.s.m.i32(0xffff_ff00);
             let outside = self.s.m.i32(0xffff_ff00);
             let at = self.s.m.select(c, inside, at, outside);
             let at = self.s.m.select(c, inside, at, outside);
-            return (handle, at);
+            return (handle, at, inside);
         }
         }
-        self.memory(low, high, guard, false)
+        let (handle, byte) = self.memory(low, high, guard, false);
+        let mapped = self.page_there.expect("memory says");
+        (handle, byte, mapped)
     }
     }
 
 
-    /// `count` dwords of the node from its byte `base` + `offset` (`base`
-    /// computed, `offset` fixed; none of the node's bytes past 127), read
-    /// four at a time.
+    /// The second 64 bytes of a 128-byte node: in a page, and in a copy, of
+    /// their own maybe. Goes on in another block.
+    fn bvh_second_half(&mut self, at: NodeAt) -> NodeAt {
+        match at {
+            NodeAt::Buffer { handle, byte } => {
+                let size = self.s.m.i32(64);
+                let byte = self.s.m.bin(self.cur, Bin::Add, byte, size);
+                NodeAt::Buffer { handle, byte }
+            }
+            NodeAt::Memory { low, high, .. } => {
+                let (low, high) = self.address_plus(low, high, 64);
+                // Every lane in this block runs the instruction.
+                let (handle, byte, mapped) = self.bvh_memory(low, high, None);
+                NodeAt::Memory {
+                    handle,
+                    byte,
+                    low,
+                    high,
+                    mapped,
+                }
+            }
+        }
+    }
+
+    /// `count` dwords of 64 bytes of a node from their byte `base` + `offset`
+    /// (`base` computed, `offset` fixed), read four at a time.
     fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
     fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
         let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
         let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
-        // The second half of a 128-byte node may lie in the next 64 KiB
-        // page, which may be in another copy: its own look, made once.
-        let mut second = None;
+        let (handle, start_byte) = match at {
+            NodeAt::Buffer { handle, byte } | NodeAt::Memory { handle, byte, .. } => (handle, byte),
+        };
         let mut out = Vec::with_capacity(count as usize);
         let mut out = Vec::with_capacity(count as usize);
         for start in (0..count).step_by(4) {
         for start in (0..count).step_by(4) {
             let n = (count - start).min(4);
             let n = (count - start).min(4);
             let node_byte = offset + 4 * start;
             let node_byte = offset + 4 * start;
-            let (handle, mut byte) = match at {
-                NodeAt::Buffer { handle, byte } => (handle, byte),
-                NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte),
-                NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| {
-                    let (low, high) = self.address_plus(low, high, 64);
-                    // Every lane in this block runs the instruction.
-                    let (handle, byte) = self.bvh_memory(low, high, None);
-                    let (k64, c) = (self.s.m.i32(64), self.cur);
-                    (handle, self.s.m.bin(c, Bin::Sub, byte, k64))
-                }),
-            };
+            let mut byte = start_byte;
             let c = self.cur;
             let c = self.cur;
             if let Some(b) = base {
             if let Some(b) = base {
                 byte = self.s.m.bin(c, Bin::Add, byte, b);
                 byte = self.s.m.bin(c, Bin::Add, byte, b);
@@ -328,7 +345,9 @@ impl<'a> Lower<'a> {
         // 32-bit floats: 24 dwords from byte 16.
         // 32-bit floats: 24 dwords from byte 16.
         self.cur = wide_block;
         self.cur = wide_block;
         let k16 = self.s.m.i32(16);
         let k16 = self.s.m.i32(16);
-        let words = self.bvh_node_words(at, None, 16, 24);
+        let mut words = self.bvh_node_words(at, None, 16, 12);
+        let second = self.bvh_second_half(at);
+        words.extend(self.bvh_node_words(second, None, 0, 12));
         let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
         let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
         // (The look for the second half goes on in another block.)
         // (The look for the second half goes on in another block.)
         let wide_block = self.cur;
         let wide_block = self.cur;
@@ -356,6 +375,21 @@ impl<'a> Lower<'a> {
         }
         }
         self.s.m.terminate(half_block, Term::Br(join));
         self.s.m.terminate(half_block, Term::Br(join));
         self.cur = join;
         self.cur = join;
+        // A page that is not there reads zeros, which are a child and a box:
+        // no child of it is hit. (The last two boxes of a 128-byte node are in
+        // its second half.)
+        let there = match (at, second) {
+            (NodeAt::Memory { mapped: first, .. }, NodeAt::Memory { mapped: last, .. }) => {
+                let i1t = self.s.m.type_of(first);
+                let mapped = self.s.m.phi(join, i1t);
+                self.s
+                    .m
+                    .set_phi(mapped, vec![(last, wide_block), (first, half_block)]);
+                let both = self.s.m.bin(join, Bin::And, first, mapped);
+                Some([first, first, both, both])
+            }
+            _ => None,
+        };
         let mut coords = Vec::with_capacity(24);
         let mut coords = Vec::with_capacity(24);
         for n in 0..24 {
         for n in 0..24 {
             let phi = self.s.m.phi(join, f32t);
             let phi = self.s.m.phi(join, f32t);
@@ -405,6 +439,12 @@ impl<'a> Lower<'a> {
             let on = self.s.m.bin(c, Bin::Xor, off, on);
             let on = self.s.m.bin(c, Bin::Xor, off, on);
             let hit = self.s.m.bin(c, Bin::And, through, before);
             let hit = self.s.m.bin(c, Bin::And, through, before);
             let hit = self.s.m.bin(c, Bin::And, hit, on);
             let hit = self.s.m.bin(c, Bin::And, hit, on);
+            let child = self.s.m.cmp(c, pred::NE, children[n], none);
+            let hit = self.s.m.bin(c, Bin::And, hit, child);
+            let hit = match there {
+                Some(there) => self.s.m.bin(c, Bin::And, hit, there[n]),
+                None => hit,
+            };
             ids[n] = self.s.m.select(c, hit, children[n], none);
             ids[n] = self.s.m.select(c, hit, children[n], none);
             distances[n] = self.s.m.select(c, hit, enter, infinity);
             distances[n] = self.s.m.select(c, hit, enter, infinity);
         }
         }

+ 6 - 0
crates/victory-shader/src/emit/intersect_tests.rs

@@ -295,6 +295,12 @@ fn scene() -> (Scene, Vec<Vec<Case>>) {
     let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
     let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
     box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
     box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
     box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
     box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
+    // A child that is not there with inverted infinite bounds (the title's
+    // builder leaves such slots): every ray "enters" it at minus infinity.
+    let mut empty = lined;
+    empty[1] = [f32::INFINITY, f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
+    let ids3 = [0x105, bvh::NONE, 0x304, 0x400];
+    box_nodes.push((s.add(nodes::box32(ids3, empty), 32), 5));
     // Random boxes.
     // Random boxes.
     for n in 0..6 {
     for n in 0..6 {
         let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {
         let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {

+ 54 - 2
crates/victory-shader/src/emit/lower.rs

@@ -87,9 +87,33 @@ enum Stop {
 }
 }
 
 
 pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
 pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
+    lower_counted(parts, counted_in_threads(parts))
+}
+
+/// Whether the title dispatches the program by a count of threads whose last
+/// group may be partial: the structure builder's programs of one dimension.
+/// Their lanes past the count must not run (they count the lanes of a wave
+/// and store). Not where a group barrier would wait for lanes that left, nor
+/// where two host waves of 32 stand for a console wave (they exchange, which
+/// takes all lanes).
+fn counted_in_threads(parts: &Parts) -> bool {
+    let crate::native::StageIo::Cs(cs) = &parts.native.io else {
+        return false;
+    };
+    cs.threads[0] > 1
+        && cs.threads[1..] == [1, 1]
+        && crate::spill::is_spilled(parts.native)
+        && (!parts.native.wave64 || host_max_wave() >= 64)
+        && !parts.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_barrier")
+}
+
+/// [`lower`]; `counted`: the lanes past a dispatch's count of threads leave
+/// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory
+/// bc3cd4b0, which does so for two of the programs by their digests).
+pub(super) fn lower_counted(parts: &Parts, counted: bool) -> Result<Lowered, ShaderError> {
     let mut bad = HashMap::new();
     let mut bad = HashMap::new();
     loop {
     loop {
-        match Lower::new(parts, &bad).run() {
+        match Lower::new(parts, &bad).run(counted) {
             Ok(l) => return Ok(l),
             Ok(l) => return Ok(l),
             Err(Stop::Retry(v, why)) => {
             Err(Stop::Retry(v, why)) => {
                 if bad.insert(v, why).is_some() {
                 if bad.insert(v, why).is_some() {
@@ -262,6 +286,8 @@ struct Lower<'a> {
     /// In the instruction being lowered: the host copy its root view's bytes
     /// In the instruction being lowered: the host copy its root view's bytes
     /// are in ([`Lower::root_memory`]).
     /// are in ([`Lower::root_memory`]).
     root_copy: Option<V>,
     root_copy: Option<V>,
+    /// Whether the page [`Lower::memory`] last looked for has a copy.
+    page_there: Option<V>,
     mask_phis: HashMap<Value, V>,
     mask_phis: HashMap<Value, V>,
     pending_masks: Vec<(V, usize, usize)>,
     pending_masks: Vec<(V, usize, usize)>,
     data_phis: Vec<(V, usize, usize)>,
     data_phis: Vec<(V, usize, usize)>,
@@ -1576,6 +1602,7 @@ impl<'a> Lower<'a> {
             stale: HashSet::new(),
             stale: HashSet::new(),
             coherent: HashSet::new(),
             coherent: HashSet::new(),
             root_copy: None,
             root_copy: None,
+            page_there: None,
             ordered: if x.native.stage == HwStage::Ps {
             ordered: if x.native.stage == HwStage::Ps {
                 ordered_section(p)
                 ordered_section(p)
             } else {
             } else {
@@ -2257,8 +2284,32 @@ impl<'a> Lower<'a> {
         Ok(self.s.m.bin(c, Bin::Or, first, total))
         Ok(self.s.m.bin(c, Bin::Or, first, total))
     }
     }
 
 
-    fn run(mut self) -> Result<Lowered, Stop> {
+    fn run(mut self, counted: bool) -> Result<Lowered, Stop> {
         let p = self.x.p;
         let p = self.x.p;
+        if counted {
+            // Before anything else, so that wave counts, reads of the first
+            // lane and stores know only the lanes that run.
+            let original = self.s.entry;
+            let width = self.s.threads.expect("compute thread count")[0];
+            let limit = self.host_word(RootType::Other(super::shader::USER_DISPATCH_THREADS_X), 0, width);
+            let Val::I32(group) = self.compute_id("groupId.i32", 94, 0) else {
+                unreachable!()
+            };
+            let Val::I32(thread) = self.thread_id(0) else {
+                unreachable!()
+            };
+            let width = self.s.m.i32(width);
+            let first = self.s.m.bin(original, Bin::Mul, group, width);
+            let x = self.s.m.bin(original, Bin::Add, first, thread);
+            let zero = self.s.m.i32(0);
+            let all = self.s.m.cmp(original, pred::EQ, limit, zero);
+            let inside = self.s.m.cmp(original, pred::IULT, x, limit);
+            let runs = self.s.m.bin(original, Bin::Or, all, inside);
+            let (body, done) = (self.s.m.new_block(), self.s.m.new_block());
+            self.s.m.terminate(original, Term::CondBr(runs, body, done));
+            self.s.m.terminate(done, Term::Ret);
+            self.s.entry = body;
+        }
         self.find_coherent();
         self.find_coherent();
         let order = crate::ir::reverse_postorder(&p.blocks);
         let order = crate::ir::reverse_postorder(&p.blocks);
         for (n, &b) in order.iter().enumerate() {
         for (n, &b) in order.iter().enumerate() {
@@ -3077,6 +3128,7 @@ impl<'a> Lower<'a> {
         );
         );
         self.end_guarded(noting, &[]);
         self.end_guarded(noting, &[]);
         let c = self.cur;
         let c = self.cur;
+        self.page_there = Some(self.s.m.cmp(c, pred::NE, copy, zero));
         let copy = if store {
         let copy = if store {
             let closed = self.s.m.cmp(c, pred::SLT, number, zero);
             let closed = self.s.m.cmp(c, pred::SLT, number, zero);
             self.s.m.select(c, closed, zero, copy)
             self.s.m.select(c, closed, zero, copy)

+ 92 - 2
crates/victory-shader/src/emit/mod.rs

@@ -118,7 +118,7 @@ pub use lower::{host_settings, set_host_max_wave};
 pub use rect::rect_list_gs;
 pub use rect::rect_list_gs;
 pub use shader::{
 pub use shader::{
     MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
     MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
-    SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
+    SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
     raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
     raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
 };
 };
 
 
@@ -650,6 +650,12 @@ fn emit_program(
             _ => 0,
             _ => 0,
         };
         };
     }
     }
+    // (DexNom/VIctory 5f4c3df4.)
+    if native.stage == HwStage::Vs
+        && let Some(psv) = c.part(FourCC::PSV0)
+    {
+        vertex_output_interpolation(psv.data, &mut outputs)?;
+    }
     // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
     // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
     // wants the position centroid (or per sample), as DXC declares it then.
     // wants the position centroid (or per sample), as DXC declares it then.
     if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
     if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
@@ -719,6 +725,67 @@ fn emit_program(
     Ok((shader, wave_size))
     Ok((shader, wave_size))
 }
 }
 
 
+/// The title's vertex output interpolation lives in PSV0. A float packed
+/// beside an integer can be explicitly constant, as can a float on its own.
+/// OSG1 supplies the physical rows and columns used to match both tables.
+fn vertex_output_interpolation(
+    mut data: &[u8],
+    outputs: &mut [container::SigElement],
+) -> Result<(), ShaderError> {
+    const TRUNCATED: ShaderError =
+        ShaderError::Malformed("truncated vertex pipeline validation data");
+    fn take<'a>(data: &mut &'a [u8], len: usize) -> Result<&'a [u8], ShaderError> {
+        let (head, tail) = data.split_at_checked(len).ok_or(TRUNCATED)?;
+        *data = tail;
+        Ok(head)
+    }
+    fn size(data: &mut &[u8]) -> Result<usize, ShaderError> {
+        Ok(u32::from_le_bytes(take(data, 4)?.try_into().unwrap()) as usize)
+    }
+    let info_size = size(&mut data)?;
+    let info = take(&mut data, info_size)?;
+    // PSVRuntimeInfo0 has no signature. PSVRuntimeInfo1 and later share
+    // these stage and signature count fields.
+    if info.len() < 36 || info[24] != 1 || info[29] == 0 {
+        return Ok(());
+    }
+    let resources = size(&mut data)?;
+    if resources != 0 {
+        let stride = size(&mut data)?;
+        take(&mut data, resources.checked_mul(stride).ok_or(TRUNCATED)?)?;
+    }
+    let strings = size(&mut data)?;
+    take(&mut data, strings)?;
+    let indices = size(&mut data)?;
+    take(&mut data, indices.checked_mul(4).ok_or(TRUNCATED)?)?;
+    let stride = size(&mut data)?;
+    if stride < 16 {
+        return Err(TRUNCATED);
+    }
+    let count = usize::from(info[28]) + usize::from(info[29]);
+    let elements = take(&mut data, count.checked_mul(stride).ok_or(TRUNCATED)?)?;
+    for record in elements.chunks_exact(stride).skip(usize::from(info[28])) {
+        let packed = record[10];
+        if packed & 0x40 == 0 {
+            continue;
+        }
+        if record[13] > 7 {
+            return Err(ShaderError::Malformed("invalid vertex output interpolation"));
+        }
+        let first = u32::from(record[9]);
+        let rows = first..first + u32::from(record[8]);
+        for output in outputs.iter_mut().filter(|e| {
+            e.row.is_some_and(|r| rows.contains(&r))
+                && e.col == ((packed >> 4) & 3)
+                && e.cols == (packed & 15)
+                && e.kind == record[11]
+        }) {
+            output.interp = record[13];
+        }
+    }
+    Ok(())
+}
+
 /// The rows of an `ISG1`/`OSG1` part.
 /// The rows of an `ISG1`/`OSG1` part.
 fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
 fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
     use crate::dxbc::u32_at;
     use crate::dxbc::u32_at;
@@ -2232,6 +2299,10 @@ mod barycentric_tests {
     /// Translates a pixel program with the input VGPRs `input_addr`
     /// Translates a pixel program with the input VGPRs `input_addr`
     /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
     /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
     fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
     fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
+        pixel_with_inputs(words, input_addr, &[element("TEXCOORD", 0, 0)])
+    }
+
+    fn pixel_with_inputs(words: &[u32], input_addr: u32, inputs: &[container::SigElement]) -> Result<HostShader, ShaderError> {
         let native = NativeProgram {
         let native = NativeProgram {
             stage: HwStage::Ps,
             stage: HwStage::Ps,
             wave64: false,
             wave64: false,
@@ -2257,7 +2328,7 @@ mod barycentric_tests {
         };
         };
         let mut target = element("SV_Target", 16, 0);
         let mut target = element("SV_Target", 16, 0);
         target.usage = 15;
         target.usage = 15;
-        let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true);
+        let isg1 = container::signature(inputs, true);
         let osg1 = container::signature(&[target], false);
         let osg1 = container::signature(&[target], false);
         let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
         let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
         let c = Container::parse(&bytes).unwrap();
         let c = Container::parse(&bytes).unwrap();
@@ -2268,6 +2339,25 @@ mod barycentric_tests {
         emit(&c, &native, &p, &st, &io, &res)
         emit(&c, &native, &p, &st, &io, &res)
     }
     }
 
 
+    #[test]
+    fn an_unused_packed_input_matches_its_provoking_vertex_sibling() {
+        let [e0, e1] = exp_mrt0(3);
+        // v_interp_mov_f32 v3, p0, attr0.z followed by exp mrt0.
+        let words = [0xC80E_0202, e0, e1, 0xBF81_0000];
+        let xy = container::SigElement { cols: 2, ..element("TEXCOORD", 0, 0) };
+        let zw = container::SigElement { col: 2, cols: 2, ..element("NORMAL", 0, 0) };
+        let shader = pixel_with_inputs(&words, PERSP_CENTER, &[xy, zw]).unwrap();
+        let c = Container::parse(&shader.dxil).unwrap();
+        let psv = c.part(FourCC::PSV0).unwrap().data;
+        for columns in [0x42, 0x62] {
+            let record = [1, 0, columns, 0, 3, 1];
+            assert!(psv.windows(record.len()).any(|w| w == record));
+        }
+        let inputs = c.part(FourCC::ISG1).unwrap().data;
+        assert_eq!((inputs[8 + 25], inputs[8 + 32 + 25]), (0, 4));
+        validate(&shader);
+    }
+
     /// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker
     /// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker
     /// knows) asks for helper lanes, which is valid DXIL (upstream #946's program).
     /// knows) asks for helper lanes, which is valid DXIL (upstream #946's program).
     #[test]
     #[test]

+ 27 - 0
crates/victory-shader/src/emit/shader.rs

@@ -80,6 +80,12 @@ pub const USER_VIEW_BIAS: u32 = 0x103;
 /// has no size, and the host's copy of what it names may end in the middle of
 /// has no size, and the host's copy of what it names may end in the middle of
 /// it (a structure of megabytes crosses the 4 MiB windows).
 /// it (a structure of megabytes crosses the 4 MiB windows).
 pub const USER_ROOT_ADDRESS: u32 = 0x104;
 pub const USER_ROOT_ADDRESS: u32 = 0x104;
+/// `RootType::Other` code of a user-data dword the host sets at a dispatch
+/// counted in threads (the console's `DispatchX`): how many of the threads
+/// numbered along X run (0: all of every group). The metadata's `dword` is
+/// the group's width. Asked for by the structure builder's programs
+/// ([`crate::spill::is_spilled`]).
+pub const USER_DISPATCH_THREADS_X: u32 = 0x106;
 
 
 /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
 /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
 pub(crate) mod flags {
 pub(crate) mod flags {
@@ -507,6 +513,27 @@ impl Shader {
 
 
     /// The finished container.
     /// The finished container.
     pub fn finish(mut self) -> Vec<u8> {
     pub fn finish(mut self) -> Vec<u8> {
+        if self.pixel {
+            // Reading a per-vertex value with attributeAtVertex needs a
+            // constant input, even when the source declaration was smooth.
+            // D3D requires all components packed into the same register to
+            // share a mode, including the ones the shader never reads.
+            for index in 0..self.inputs.len() {
+                let unused = &self.inputs[index];
+                if unused.kind != 0 || unused.usage != 0 || unused.row.is_none() {
+                    continue;
+                }
+                let mut modes = self.inputs.iter()
+                    .filter(|e| e.row == unused.row && e.usage != 0)
+                    .map(|e| e.interp);
+                if let Some(mode) = modes.next()
+                    && (mode == 1 || unused.comp == 9)
+                    && modes.all(|other| other == mode)
+                {
+                    self.inputs[index].interp = mode;
+                }
+            }
+        }
         let ud_size = (self.user_data * 4).next_multiple_of(16);
         let ud_size = (self.user_data * 4).next_multiple_of(16);
         self.fix_user_data_size(ud_size);
         self.fix_user_data_size(ud_size);
         // The clean-up, before anything is declared about the code: a
         // The clean-up, before anything is declared about the code: a

+ 52 - 2
crates/victory-shader/src/emit/wave64_tests.rs

@@ -104,12 +104,22 @@ fn lowered_on(
     p: &ir::Program,
     p: &ir::Program,
     wide: &HashSet<usize>,
     wide: &HashSet<usize>,
     host_wave: u32,
     host_wave: u32,
+) -> Result<HostShader, ShaderError> {
+    lowered_counted(native, p, wide, host_wave, false)
+}
+
+fn lowered_counted(
+    native: &NativeProgram,
+    p: &ir::Program,
+    wide: &HashSet<usize>,
+    host_wave: u32,
+    counted: bool,
 ) -> Result<HostShader, ShaderError> {
 ) -> Result<HostShader, ShaderError> {
     let st = structure::structure_wide(p, wide).expect("structure");
     let st = structure::structure_wide(p, wide).expect("structure");
     let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
     let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
     let io = io::raise(p, native).expect("io::raise");
     let io = io::raise(p, native).expect("io::raise");
     let was = lower::TEST_HOST_WAVE.replace(Some(host_wave));
     let was = lower::TEST_HOST_WAVE.replace(Some(host_wave));
-    let lowered = lower::lower(&lower::Parts {
+    let lowered = lower::lower_counted(&lower::Parts {
         native,
         native,
         p,
         p,
         st: &st,
         st: &st,
@@ -119,7 +129,7 @@ fn lowered_on(
         outputs: Vec::new(),
         outputs: Vec::new(),
         prims: Vec::new(),
         prims: Vec::new(),
         mesh_stride: 0,
         mesh_stride: 0,
-    });
+    }, counted);
     lower::TEST_HOST_WAVE.set(was);
     lower::TEST_HOST_WAVE.set(was);
     let lowered = lowered?;
     let lowered = lowered?;
     Ok(HostShader {
     Ok(HostShader {
@@ -686,3 +696,43 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide()
     }
     }
     eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside");
     eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside");
 }
 }
+
+/// A dispatch counted in threads: of the last group only the lanes below the
+/// count store (after DexNom/VIctory bc3cd4b0).
+#[test]
+fn the_lanes_past_a_count_of_threads_do_not_run() {
+    // Each lane that runs adds 1 to counter[local x].
+    let native = native(&[
+        0x3402_0082, // v_lshlrev_b32 v1, 2, v0
+        0x7e04_0281, // v_mov_b32 v2, 1
+        0xe0c8_1000, 0x8002_0201, // buffer_atomic_add v2, v1, s[8:11], 0 offen
+    ]);
+    let p = ir::build(&native.code, native.wave64, native.vgprs).unwrap();
+    let shader = lowered_counted(&native, &p, &HashSet::new(), 64, true).unwrap();
+    let limit = shader
+        .user_data
+        .iter()
+        .find(|u| u.root == RootType::Other(super::USER_DISPATCH_THREADS_X))
+        .unwrap();
+    assert_eq!((limit.slot, limit.dword), (0, 64));
+    let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
+    let Ok(host) = Host::new(true) else { return };
+    let Ok((root, pso)) = host.compute_pipeline(&shader) else { return };
+    for count in [0u32, 1, 7, 63, 64, 65, 74, 77, 127, 128] {
+        let mut constants = vec![0; shader.user_data_dwords() as usize];
+        constants[limit.index as usize] = count;
+        let result = host
+            .dispatch(&root, &pso, &Dispatch {
+                roots: vec![(0, Root::Constants(constants))],
+                views: &[View::RawUav(68)],
+                samplers: &[],
+                groups: [2, 1, 1],
+            })
+            .unwrap();
+        let active = if count == 0 { 128 } else { count };
+        for (i, &word) in result[0].iter().enumerate().take(64) {
+            let i = i as u32;
+            assert_eq!(word, u32::from(i < active) + u32::from(i + 64 < active), "count {count}, word {i}");
+        }
+    }
+}