Faces move, ray tracing mostly off, intro video fix, picture fixes

- Faces: the face network's 16-bit values travel through integer views; they
  were read as floats and came back as zeros on NVIDIA. Port of
  fxceless/victory-fork pull request 927 (tippythetaidum): emit/halves.rs,
  lower.rs, descriptor/host.rs, draw.rs.
- Ray tracing mostly off: scripts/rt_off_hashes.txt lists the 1,000
  CS_RaytracingResolve and 34 traced-shadow shaders, skipped by
  play-nvidia.ps1 through VICTORY_SKIP_PIPELINES (-RayTracing keeps them).
  The structure builder cannot run on NVIDIA, so every ray missed and rooms
  went white depending on the view angle. The screen-probe and visibility
  traces keep running; skipping them left rainbow glitter.
- Intro video flicker: linear one-level R8 video planes always record their
  copy (texture.rs), so frames of the ring no longer show out of order.
- VICTORY_AMBIENT_MOST (ambient.rs), VICTORY_NAN_SCRUB (emit/lower.rs) and
  VICTORY_PIPELINE_WAIT_ONCE (pipeline/make.rs, on by default).
- Off by default: VICTORY_CONSTANT_MARKS (port of fxceless pull request
  1216), VICTORY_TARGET_VARIANTS (port of fxceless a35c557393), F9 frame
  capture (capture.rs).
- play-nvidia.ps1: the speed set by default, -Quality for the slower set
  with fewer stretched bodies and less rainbow skin. README updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
trustno1-coderandClaude Opus 5.5 committed 2026-11-25 19:13:08 -08:00
1 parent 3e5fb36392
commit 77e13a974a
27 files changed
+1868 -73

No files matched your search

+16 -1
View File
@@ -112,6 +112,18 @@ fn air() -> f32 {
})
}
/// LOCAL: how many times the estimate the title's own result may keep
/// (`VICTORY_AMBIENT_MOST=<multiple>`, 4 when unset). Without rays the
/// probes hold the sky's light indoors too; at 4 times the estimate a room
/// looked towards a window or the sky goes very bright.
fn most() -> f32 {
static SET: OnceLock<f32> = OnceLock::new();
*SET.get_or_init(|| {
let set = std::env::var("VICTORY_AMBIENT_MOST").unwrap_or_default();
set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(4.0)
})
}
/// Strength and radius of the creases' shade.
fn shade() -> [f32; 2] {
static SET: OnceLock<[f32; 2]> = OnceLock::new();
@@ -243,6 +255,9 @@ void clear_air(uint3 at : SV_DispatchThreadID) {
float far = float(at.z) / float(d);
float cap = air * lerp(dot(cells[CELLS].rgb, LUMA), dot(seen_there, LUMA), far);
float3 c = scattered[at];
// LOCAL: a NaN or infinity in the air is summed along every view ray
// through it: black or white patches floating in the room.
if (any(isnan(c)) || any(isinf(c))) { scattered[at] = 0; return; }
float has = dot(c, LUMA);
if (has > cap) scattered[at] = c * (cap / has);
}
@@ -459,7 +474,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool {
words[6] = views.size[0];
words[7] = views.size[1];
words[8] = 0.04f32.to_bits();
words[9] = 4.0f32.to_bits();
words[9] = most().to_bits();
words[10] = air().to_bits();
let l = &list.list;
// SAFETY: an open list with the heap of the views set; the title's
+23 -1
View File
@@ -27,7 +27,8 @@ pub(crate) fn listed(n: u64) -> bool {
.filter_map(|f| f.trim().parse().ok())
.collect()
})
.contains(&n);
.contains(&n)
|| n == KEY_FRAME.load(std::sync::atomic::Ordering::Relaxed);
// `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first
// one that ran 500 draws or more (a title's first 3D frames: their
// numbers depend on how long the menus were shown), and the 30th and
@@ -120,12 +121,33 @@ fn world_on() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some())
}
/// LOCAL: the frame F9 asked for ([`frame_drew`]); `u64::MAX`: none.
static KEY_FRAME: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
/// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`).
static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
/// At the present of `frame`: the draws run on the host so far.
pub(crate) fn frame_drew(frame: u64, drawn: u64) {
use std::sync::atomic::Ordering::Relaxed;
// LOCAL: with a capture folder, F9 captures the next frame as a listed
// one (its picture, its ops and, with VICTORY_DUMP_TARGETS=1, every
// target it drew): to catch a picture fault the moment it shows.
if folder().is_some() {
static WAS_DOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
// SAFETY: a plain query of the keyboard's state.
let down = unsafe {
windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState(i32::from(
windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_F9,
))
} < 0;
if down && !WAS_DOWN.swap(true, Relaxed) {
KEY_FRAME.store(frame + 1, Relaxed);
tracing::info!(frame = frame + 1, "F9: this frame is captured");
} else if !down {
WAS_DOWN.store(false, Relaxed);
}
}
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let before = LAST.swap(drawn, Relaxed);
if world_on()
+68
View File
@@ -1588,6 +1588,74 @@ mod tests {
);
}
/// A table made afresh for a draw holds the descriptors its shader
/// moves halves through (`HostShader::half_views`), also past the range
/// starts its used-resource entries give: with one entry for a range
/// from dword 0 and a 16-bit float buffer view at dword 8, the table
/// takes two dynamic slots, so the next allocation does not land on the
/// view's. (The case avt0m4t48 found in review on #927.)
#[cfg(windows)]
#[test]
fn a_fresh_table_holds_the_half_views_past_its_range_starts() {
use victory_shader::{ResourceType, RootType, UsedResource};
let Some(device) = crate::host::host() else {
return; // no host GPU
};
let list = device.new_list().expect("a host list");
let desc = HeapDesc {
kind: VIEWS_KIND,
count: 2,
flags: SHADER_VISIBLE,
nodes: 1,
};
let none = Placement {
address: 0,
size: 0,
};
let mut h: This = std::ptr::null();
assert_eq!(create(desc, none, &mut h), S_OK);
let title = heap(h);
let host_heap = title.host().expect("a host view heap");
let (first, second) = (title.handle(0).unwrap(), title.handle(1).unwrap());
// An R16G16B16A16_FLOAT buffer view of memory in the second slot.
let memory = [0u64; 64];
let address = memory.as_ptr() as u64;
let resource = [1, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0];
let mut words = [0u32; 16];
words[..10].copy_from_slice(&[10, 1, 5768, 0, 0, 0, 64, 0, 0, 0]);
words[10] = address as u32;
words[11] = (address >> 32) as u32;
create_placed_srv(std::ptr::null(), &resource, &words, second);
assert!(view(second).as_ref().and_then(host::half_view).is_some());
let mut state = crate::draw::State::default();
state.set_heaps(&[h]);
state.set_table(true, 1, first);
let range = UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 8,
dwords: 4,
user_data: 4,
slot: 1,
};
let made = state.tables(&list, &[range], &[], &[(1, 8)], true);
let [(1, offset)] = made[..] else {
panic!("one fresh table for root parameter 1, not {:?}", &made[..]);
};
assert_ne!(offset, u32::MAX, "the table found no dynamic slots");
let next = host_heap.dynamic(1).expect("a dynamic slot");
host_heap.release(next, 1);
drop(state);
slot::<extern "system" fn(This) -> u32>(h, 0x10)(h);
assert_eq!(
next,
offset / 32 + 2,
"the next allocation took the table's second slot"
);
}
#[test]
fn heaps_hold_count_descriptors_from_their_start() {
let null = std::ptr::null();
+386 -14
View File
@@ -893,6 +893,14 @@ struct Waiting {
checked: (u64, u64, u64, u8, u64),
}
/// Whether due texture slots are served in turns, a slot looked at before
/// and one never looked at ([`TextureQueue::due`]; on unless
/// `VICTORY_FAIR_DUE=0`).
fn fair_due() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_FAIR_DUE").is_none_or(|v| v != "0"))
}
/// The queue of title slots whose texture view waits to be brought up to
/// date for shaders that pick textures by index: which are due, and in
/// which order (no host heap needed, so it is tested without one).
@@ -926,14 +934,20 @@ impl TextureQueue {
/// Up to `max` slots due at `frame`, each with its write number, in
/// the order to serve them:
/// - first the ones looked at before (their memory was not mapped, or
/// only part of it): the look is a query, and memory that has
/// arrived since is what the title streamed in last;
/// - then the others, the newest write first and the oldest next, in
/// turns: slot order served the low slots of a backlog of
/// 25,000-40,000 while the textures of the shot on screen waited
/// (run 52: 98% of the drawn pixels had no colour texture in the
/// first 3D frames).
/// - the ones looked at before (their memory was not mapped, or only
/// part of it), newest write first: the look is a query, and memory
/// that has arrived since is what the title streamed in last;
/// - the others, the newest write first and the oldest next, in turns:
/// slot order served the low slots of a backlog of 25,000-40,000
/// while the textures of the shot on screen waited (run 52: 98% of
/// the drawn pixels had no colour texture in the first 3D frames);
/// - the two kinds one after the other, a slot looked at before first
/// (`VICTORY_FAIR_DUE=0`: all those looked at before first, as
/// before). With them all first, a backlog of thousands of slots
/// streaming in a part at a time filled every pass in the opening
/// cutscene, which the pass's time then cut, and slots never looked
/// at waited 300 to 1,500 frames: faces whose textures are picked by
/// index read an empty slot (black) or an older view (red, noise).
fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> {
let mut again: Vec<(u64, u32, u64)> = Vec::new();
let mut fresh: Vec<(u64, u32, u64)> = Vec::new();
@@ -945,16 +959,33 @@ impl TextureQueue {
let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2);
again.sort_unstable_by(newest_first);
fresh.sort_unstable_by(newest_first);
let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect();
let mut fresh_order: Vec<(u32, u64)> = Vec::with_capacity(fresh.len().min(max));
let (mut new, mut old) = (0, fresh.len());
while new < old && order.len() < max {
order.push((fresh[new].1, fresh[new].2));
while new < old && fresh_order.len() < max {
fresh_order.push((fresh[new].1, fresh[new].2));
new += 1;
if new < old && order.len() < max {
if new < old && fresh_order.len() < max {
old -= 1;
order.push((fresh[old].1, fresh[old].2));
fresh_order.push((fresh[old].1, fresh[old].2));
}
}
let mut again_order = again.iter().map(|&(_, index, write)| (index, write));
if !fair_due() {
let mut order: Vec<(u32, u64)> = again_order.collect();
order.extend(fresh_order);
order.truncate(max);
return order;
}
let mut fresh_order = fresh_order.into_iter();
let mut order = Vec::with_capacity(max.min(fresh.len() + again.len()));
while order.len() < max {
let (a, b) = (again_order.next(), fresh_order.next());
if a.is_none() && b.is_none() {
break;
}
order.extend(a);
order.extend(b);
}
order.truncate(max);
order
}
@@ -2520,9 +2551,18 @@ impl HostHeap {
if let Some((_, _, data)) = &self.strides
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
{
// LOCAL (port of fxceless #1216): constant buffer views marked;
// programs read no other non-buffer slot as one.
let entry = match (stride, view) {
(Some(s), _) => s | kind,
(None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => {
victory_shader::emit::SLOT_STRIDE_CONSTANT
}
_ => kind,
};
// SAFETY: inside the mapping; shaders read it while we write (a
// dword, either value is one the slot had).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
unsafe { (*data as *mut u32).add(index as usize).write_volatile(entry) };
}
let was = if stride.is_some() {
self.buffers.put(index);
@@ -3259,6 +3299,76 @@ fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC {
}
}
/// The unsigned integer format with the layout of a 16-bit float or
/// signed integer format (one, two or four channels), if `format` is one.
pub(crate) fn half_format(format: u32) -> Option<u32> {
match format {
// R16G16B16A16_FLOAT and _SINT: R16G16B16A16_UINT.
10 | 14 => Some(12),
// R16G16_FLOAT and _SINT: R16G16_UINT.
34 | 38 => Some(36),
// R16_FLOAT and _SINT: R16_UINT.
54 | 59 => Some(57),
_ => None,
}
}
/// `view` as a shader is shown it where it moves a buffer's 16-bit
/// channels as unsigned integers
/// (`victory_shader::emit::HostShader::half_views`): a buffer view in a
/// 16-bit float or signed format, in the unsigned format of the same
/// layout, through which every 16-bit pattern is read and stored as it
/// is. `None` for every other view: the title's own serves (an unsigned
/// one already carries the bits; a texture can only be viewed in the
/// formats it was made for).
pub(crate) fn half_view(view: &View) -> Option<View> {
// Buffer views: dimension 1 in the title's description of either kind.
const BUFFER: u32 = 1;
match view {
View::Shader(resource, Some(desc)) if desc[1] == BUFFER => {
let mut desc = *desc;
desc[0] = half_format(desc[0])?;
Some(View::Shader(*resource, Some(desc)))
}
View::Unordered(resource, counter, Some(desc)) if desc[1] == BUFFER => {
let mut desc = *desc;
desc[0] = half_format(desc[0])?;
Some(View::Unordered(*resource, *counter, Some(desc)))
}
View::Placed(unordered, resource, desc) if resource[0] == BUFFER && desc[1] == BUFFER => {
let mut desc = *desc;
desc[0] = half_format(desc[0])?;
Some(View::Placed(*unordered, *resource, desc))
}
_ => None,
}
}
/// The format of `view`, a buffer view through which a shader moves
/// 16-bit channels as unsigned integers
/// (`victory_shader::emit::HostShader::half_views`), if those integers
/// are not what the console gives: a format of wider channels, a
/// normalised one or a signed 8-bit one, whose values the console converts
/// to and from halves. `None` for the formats the integers serve exactly
/// (16 bits a channel of any kind, through [`half_view`] where needed, and
/// unsigned channels of fewer bits; the title's are 16-bit unsigned) and
/// for any other view.
pub(crate) fn half_inexact(view: &View) -> Option<u32> {
// Buffer views: dimension 1 in the title's description of either kind.
const BUFFER: u32 = 1;
// R16G16B16A16, R16G16 and R16 (float, unsigned, signed), then
// R10G10B10A2, R8G8B8A8, R8G8 and R8 unsigned.
const EXACT: [u32; 13] = [10, 12, 14, 34, 36, 38, 54, 57, 59, 25, 30, 50, 62];
let format = match view {
View::Shader(_, Some(desc)) | View::Unordered(_, _, Some(desc)) if desc[1] == BUFFER => {
desc[0]
}
View::Placed(_, resource, desc) if resource[0] == BUFFER && desc[1] == BUFFER => desc[0],
_ => return None,
};
(!EXACT.contains(&format)).then_some(format)
}
fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
let mut words = *words;
words[0] = crate::resource::pc_format(words[0]);
@@ -4688,6 +4798,243 @@ mod tests {
super::read_all(start);
}
/// The unsigned twin of a 16-bit float or signed format has its layout,
/// and only buffer views in such a format are shown as another view.
#[test]
fn only_16_bit_float_and_signed_buffer_views_get_an_unsigned_twin() {
for (format, unsigned) in [(10, 12), (14, 12), (34, 36), (38, 36), (54, 57), (59, 57)] {
assert_eq!(half_format(format), Some(unsigned));
assert_eq!(
crate::resource::element(format),
crate::resource::element(unsigned),
"format {format}"
);
}
// The unsigned formats themselves, normalised 16-bit formats, and
// wider and narrower ones.
for other in [0, 12, 36, 57, 11, 13, 35, 37, 56, 58, 42, 17, 30, 61] {
assert_eq!(half_format(other), None, "format {other}");
}
const BUFFER: u32 = 1;
let words = |format: u32, dimension: u32| [format, dimension, 5768, 0, 0, 0, 64, 0, 0, 0];
// R16G16B16A16_FLOAT: a buffer of halves a program moves as they are.
assert_eq!(
half_view(&View::Unordered(7, 0, Some(words(10, BUFFER)))),
Some(View::Unordered(7, 0, Some(words(12, BUFFER))))
);
assert_eq!(
half_view(&View::Shader(7, Some(words(54, BUFFER)))),
Some(View::Shader(7, Some(words(57, BUFFER))))
);
let mut placed = [0u32; 16];
placed[..10].copy_from_slice(&words(38, BUFFER));
placed[10] = 0x1234_0000;
let mut twin = placed;
twin[0] = 36;
let memory = [BUFFER, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0];
assert_eq!(
half_view(&View::Placed(true, memory, placed)),
Some(View::Placed(true, memory, twin))
);
// The title's kind (R16G16B16A16_UINT and R16_UINT buffers), a
// texture view (dimension 4: 2D), a view without a description, a
// constant buffer: the title's own.
assert_eq!(
half_view(&View::Unordered(7, 0, Some(words(12, BUFFER)))),
None
);
assert_eq!(half_view(&View::Shader(7, Some(words(57, BUFFER)))), None);
assert_eq!(half_view(&View::Unordered(7, 0, Some(words(10, 4)))), None);
assert_eq!(half_view(&View::Shader(7, None)), None);
assert_eq!(half_view(&View::Constant(0x1000, 256)), None);
}
/// The buffer views through which the integers a shader moves halves
/// as are not what the console gives are named; the title's are not.
#[test]
fn views_whose_values_the_console_would_convert_are_named() {
const BUFFER: u32 = 1;
let words = |format: u32, dimension: u32| [format, dimension, 5768, 0, 0, 0, 64, 0, 0, 0];
for exact in [10, 12, 14, 34, 36, 38, 54, 57, 59, 25, 30, 50, 62] {
let view = View::Unordered(7, 0, Some(words(exact, BUFFER)));
assert_eq!(half_inexact(&view), None, "format {exact}");
}
// R32_FLOAT, R32_UINT, R16G16B16A16_UNORM, R8G8B8A8_UNORM, R8_SINT,
// and a structured or raw view (no format).
for inexact in [41, 42, 11, 28, 64, 0] {
let view = View::Shader(7, Some(words(inexact, BUFFER)));
assert_eq!(half_inexact(&view), Some(inexact));
}
let mut placed = [0u32; 16];
placed[..10].copy_from_slice(&words(41, BUFFER));
let memory = [BUFFER, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0];
assert_eq!(half_inexact(&View::Placed(true, memory, placed)), Some(41));
// Not a buffer view.
assert_eq!(half_inexact(&View::Shader(7, Some(words(41, 4)))), None);
assert_eq!(half_inexact(&View::Constant(0x1000, 256)), None);
}
/// The two ways a translated `buffer_load_format_d16_xyzw` and
/// `buffer_store_format_d16_xyzw` have moved a typed buffer's 16-bit
/// channels, on the host device, over a buffer that holds every 16-bit
/// pattern. As unsigned integers through an unsigned view (the title's
/// own R16G16B16A16_UINT, or the twin `half_view` gives a float one)
/// every pattern comes back as it was. By way of floats, as before
/// (load as floats, each to its half's bits; each half widened and
/// stored as a float): through the title's integer view that is
/// outside what D3D12 defines, and what the device gives is printed,
/// not checked (1 pattern of 65,536 on the cards tried: the network
/// that moves the title's faces computed zeros).
#[test]
fn halves_cross_an_unsigned_buffer_view_unchanged() {
const MOVES: &str = r#"
#define RS "DescriptorTable(UAV(u0, numDescriptors=2))"
#ifdef BY_FLOATS
RWBuffer<float4> from : register(u0);
RWBuffer<float4> to : register(u1);
#else
RWBuffer<uint4> from : register(u0);
RWBuffer<uint4> to : register(u1);
#endif
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) {
#ifdef BY_FLOATS
uint4 h = f32tof16(from[id.x]);
#else
uint4 h = from[id.x] & 0xffff;
#endif
uint low = h.x | h.y << 16;
uint high = h.z | h.w << 16;
#ifdef BY_FLOATS
to[id.x] = float4(f16tof32(low), f16tof32(low >> 16), f16tof32(high), f16tof32(high >> 16));
#else
to[id.x] = uint4(low & 0xffff, low >> 16, high & 0xffff, high >> 16);
#endif
}
"#;
const ELEMENTS: usize = 1 << 14;
const BYTES: u64 = ELEMENTS as u64 * 8;
const TITLES: u32 = 12; // R16G16B16A16_UINT
let Some(host) = host() else {
return; // no host GPU
};
let heap: ID3D12DescriptorHeap = {
let desc = D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: 2,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
};
// SAFETY: plain heap creation.
unsafe { host.device.CreateDescriptorHeap(&desc) }.expect("a view heap")
};
// How many of the 65,536 patterns come back as they were, moved by
// the program `by_floats` or not, through views in `format`.
let moved = |by_floats: bool, format: u32| -> usize {
let source = if by_floats {
MOVES
.replace("BY_FLOATS_OR_NOT", "main")
.replace("#ifdef BY_FLOATS", "#if 1")
} else {
MOVES
.replace("BY_FLOATS_OR_NOT", "main")
.replace("#ifdef BY_FLOATS", "#if 0")
};
let code = crate::host::compile(
&source,
windows::core::s!("main"),
windows::core::s!("cs_5_1"),
)
.expect("the test's shader");
let (from, filled) = host.shared_buffer(BYTES).expect("a buffer");
let (to, result) = host.shared_buffer(BYTES).expect("a buffer");
// SAFETY: the shader's own root signature and plain creation
// calls; both mappings hold `BYTES` bytes; the views are of
// live buffers, in slots of the heap made above; an open list.
unsafe {
let root: ID3D12RootSignature = host
.device
.CreateRootSignature(0, &code)
.expect("a root signature");
let pso: ID3D12PipelineState = host
.device
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: code.as_ptr().cast(),
BytecodeLength: code.len(),
},
..Default::default()
})
.expect("a pipeline");
let filled = std::slice::from_raw_parts_mut(filled.cast::<u16>(), ELEMENTS * 4);
for (pattern, half) in filled.iter_mut().enumerate() {
*half = pattern as u16;
}
std::ptr::write_bytes(result, 0xee, BYTES as usize);
let view = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT(format as i32),
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV {
NumElements: ELEMENTS as u32,
..Default::default()
},
},
};
let start = heap.GetCPUDescriptorHandleForHeapStart();
let step = host
.device
.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
as usize;
host.device.CreateUnorderedAccessView(
&from,
None::<&ID3D12Resource>,
Some(&view),
start,
);
let second = D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: start.ptr + step,
};
host.device.CreateUnorderedAccessView(
&to,
None::<&ID3D12Resource>,
Some(&view),
second,
);
let list = host.new_list().expect("a host list");
list.list.SetDescriptorHeaps(&[Some(heap.clone())]);
list.list.SetComputeRootSignature(&root);
list.list.SetPipelineState(&pso);
list.list
.SetComputeRootDescriptorTable(0, heap.GetGPUDescriptorHandleForHeapStart());
list.list.Dispatch(ELEMENTS as u32 / 64, 1, 1);
list.close();
host.execute(&[&list]);
assert!(
host.device.GetDeviceRemovedReason().is_ok(),
"the device, after views in format {format}"
);
let result = std::slice::from_raw_parts(result.cast::<u16>(), ELEMENTS * 4);
(0..=u16::MAX)
.filter(|&p| result[usize::from(p)] == p)
.count()
}
};
// A float view of halves is shown as the title's kind of view.
assert_eq!(half_format(10), Some(TITLES));
let unsigned = moved(false, TITLES);
let by_floats = moved(true, TITLES);
eprintln!(
"halves through an R16G16B16A16_UINT buffer view: {unsigned} of 65536 patterns came back unchanged moved as unsigned integers, {by_floats} moved by way of floats"
);
assert_eq!(
unsigned, 65_536,
"patterns unchanged, moved as unsigned integers"
);
}
/// A null texture UAV keeps the title's dimension (3D for the world's
/// wind field), and is 2D when the title names none.
#[test]
@@ -5101,6 +5448,31 @@ mod tests {
assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
}
/// Slots looked at before and slots never looked at are served in
/// turns, one looked at before first: a pass that can take only some
/// of a backlog of slots streaming in a part at a time still reaches
/// the slots never looked at.
#[test]
fn the_texture_queue_serves_looked_at_and_fresh_slots_in_turns() {
let mut q = TextureQueue::default();
// Slots 100..110 looked at before (their memory not there yet).
for i in 0..10u32 {
q.written(100 + i, 1, 0, false);
}
for i in 0..10u32 {
let w = q.due(u64::MAX, 100).iter().find(|d| d.0 == 100 + i).unwrap().1;
q.later(100 + i, w, 1, 1);
}
// Slots 1..4 never looked at.
for i in 1..4u32 {
q.written(i, 2, 0, false);
}
let order: Vec<u32> = q.due(10, 6).into_iter().map(|d| d.0).collect();
assert_eq!(order.len(), 6);
assert!(order[0] >= 100, "a slot looked at before comes first: {order:?}");
assert_eq!(order.iter().filter(|&&i| i < 100).count(), 3, "every fresh slot is reached: {order:?}");
}
/// Slots held back for lack of room on the card are not handed out
/// until their frame, keep their place, are not counted as waiting
/// for their memory, and all come back at once when the card has room;
+103 -5
View File
@@ -306,6 +306,10 @@ pub(crate) struct State {
target_handles: Vec<u64>,
depth_handle: u64,
targets_set: bool,
/// LOCAL (fxceless a35c557393): the formats of the views
/// [`State::set_targets`] bound (eight targets, then depth), for the
/// draws' pipelines (`crate::pipeline::host_pipeline_for`).
target_formats: crate::pipeline::host::TargetFormats,
/// The render target views and the depth view the host list has, once
/// it has any ([`State::set_targets`]): per view the host texture (0:
/// a null view) and what its descriptor says.
@@ -1060,6 +1064,16 @@ impl State {
crate::capture::note_target(record.resource);
Some((texture, record))
});
// The formats of the host views, for the draws' pipelines (before
// the bind cache below, which can return early).
let mut formats = [0u32; 9];
for (i, (texture, desc)) in views.iter().take(8).enumerate() {
formats[i] = bound_format(*texture, desc.as_ref().map(|d| d.Format));
}
if let Some((texture, record)) = dsv.as_ref() {
formats[8] = bound_format(Some(*texture), record.depth_desc().as_ref().map(|d| d.Format));
}
self.target_formats = formats;
let now = (keys, dsv.as_ref().map(|(texture, record)| (texture.as_raw() as usize, record.key())));
static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *CACHE.get_or_init(|| std::env::var("VICTORY_BIND_CACHE").map_or(true, |v| v != "0"))
@@ -1336,7 +1350,7 @@ impl State {
if crate::pipeline::is_skipped(self.pipeline as This) {
return false;
}
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) else {
return false;
};
if p.compute || p.mesh != mesh {
@@ -1493,7 +1507,13 @@ impl State {
if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) {
crate::picked::runs_in(list);
}
let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
let made = self.tables(
list,
&t.used,
&t.host.root_indexed_views,
&t.host.half_views,
compute,
);
STORES.set(true);
if made.iter().any(|m| m.1 == u32::MAX) {
once!("a draw whose descriptor table found no free slots is dropped");
@@ -2198,7 +2218,18 @@ impl State {
static PASSED: AtomicU64 = AtomicU64::new(0);
let now = crate::host::now_ms();
let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1);
let most = (4000 / took).clamp(16, 256);
// `VICTORY_RELOOK_MS` (20,000 unless said; 4,000 before): at 4,000 the
// opening cutscene's 4 frames a second looked at its ~20,000 slots
// waiting for their memory every 16 frames, thousands of queries
// a second and most of the pass's time, while slots never looked
// at waited. The runtime's mappings already make a slot due
// (`texture_slots_remapped`); these looks are only for what that
// does not tell.
static RELOOK_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let relook = *RELOOK_MS.get_or_init(|| {
std::env::var("VICTORY_RELOOK_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(20_000)
});
let most = (relook / took).clamp(16, 1024);
// What a table entry of a texture a shader samples says.
let sampled = UsedResource {
kind: ResourceType::Srv,
@@ -3145,11 +3176,19 @@ impl State {
/// once: its constant data is copied at submission either way, and the
/// big tables the world binds would otherwise take hundreds of slots per
/// draw, wrapping the dynamic slots onto lists not yet submitted.
///
/// `half`: the table descriptors the shader moves sixteen bits a
/// channel as unsigned integers (`HostShader::half_views`). A table
/// with a 16-bit float or signed buffer view at one of them is made
/// afresh as well, with that view in the unsigned format of the same
/// layout (`descriptor::host::half_view`): the title's own slot keeps
/// the title's format for the shaders that read it as floats.
pub(crate) fn tables(
&mut self,
list: &HostList,
used: &[UsedResource],
indexed: &[RootIndexedView],
half: &[(u8, u32)],
compute: bool,
) -> Few<(u8, u32), 16> {
let tables = |u: &&UsedResource| u.root == RootType::Table;
@@ -3159,6 +3198,36 @@ impl State {
fresh.push(u.slot);
}
}
// The view shown in place of the title's at dword `at` of the table
// in root parameter `slot`, if the shader moves halves there and
// the title's view is a 16-bit float or signed buffer view.
let halved = |state: &Self, slot: u8, at: u32| -> Option<View> {
if !half.contains(&(slot, at)) {
return None;
}
let Some(&Root::Table(table)) = state.roots_ref(compute).get(usize::from(slot)) else {
return None;
};
crate::descriptor::host::half_view(&crate::descriptor::view(table + u64::from(at) * 4)?)
};
for &(slot, at) in half {
let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
continue;
};
let Some(view) = crate::descriptor::view(table + u64::from(at) * 4) else {
continue;
};
if crate::descriptor::host::half_view(&view).is_some() {
if !fresh.contains(&slot) {
fresh.push(slot);
}
} else if let Some(format) = crate::descriptor::host::half_inexact(&view) {
once!(
format,
"a shader moves a buffer's 16-bit channels as integers through a view whose values the console converts: they are read and written unconverted"
);
}
}
// Tables reaching past a host heap smaller than the title's (the
// host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
// title's slots there have no host slot of their own.
@@ -3220,6 +3289,15 @@ impl State {
index.byte_offset.wrapping_add(constant << index.shift) / 32
})
.collect();
// The descriptors the shader moves halves through are made too,
// and the table reaches them: they may lie past the range starts
// the entries give (a range of several views names only its
// first; review on #927).
selected.extend(
half.iter()
.filter(|&&(s, _)| s == slot)
.map(|&(_, at)| at / 8),
);
selected.sort_unstable();
selected.dedup();
let n = entries()
@@ -3242,6 +3320,11 @@ impl State {
let at = table + u64::from(k) * 32;
// SAFETY: a descriptor slot in title memory.
h.add(unsafe { (at as *const [u32; 3]).read_unaligned() });
// (Another table than the same slots made for a shader
// that reads them in the title's formats.)
if half.contains(&(slot, k * 8)) {
h.add([u32::MAX, slot.into(), k]);
}
}
(table, n, h.0)
};
@@ -3382,7 +3465,10 @@ impl State {
host.constant_at(index, &buffer, gpu, size);
}
Some(view) => {
host.make_at(index, &view);
match halved(self, slot, k * 8) {
Some(shown) => host.make_at(index, &shown),
None => host.make_at(index, &view),
}
let kind = used.map(|u| u.kind).or_else(|| {
selected.binary_search(&k).ok().and_then(|_| view_kind(&view))
});
@@ -4014,6 +4100,18 @@ pub(crate) fn view_kind(view: &View) -> Option<ResourceType> {
}
}
/// LOCAL (fxceless a35c557393): the format of a host view of `texture`
/// whose description names `described`: that one, else the texture's own
/// (what the host gives a view without a format); 0 if neither is known.
fn bound_format(texture: Option<&ID3D12Resource>, described: Option<DXGI_FORMAT>) -> u32 {
match (described, texture) {
(Some(format), _) if format.0 != 0 => format.0 as u32,
// SAFETY: a live texture.
(_, Some(texture)) => unsafe { texture.GetDesc() }.Format.0 as u32,
_ => 0,
}
}
/// The host state a depth view needs of its texture: the read state if the
/// view writes no plane the format has (the title's read-only flags), else
/// the write state.
@@ -4044,7 +4142,7 @@ fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_
/// A few things, up to `N` of them without memory of the heap: what a draw's
/// tables are gone through with, some six lists a stage.
struct Few<T, const N: usize> {
pub(crate) struct Few<T, const N: usize> {
few: [T; N],
len: usize,
/// All of them, if they are more.
+15
View File
@@ -456,6 +456,21 @@ pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> {
make::ready(&pipeline(this).host)
}
/// LOCAL (fxceless a35c557393): as [`host_pipeline`], for a draw into views
/// of the formats `bound`: if one has another format than the pipeline
/// declares for its slot, the host pipeline made for the bound formats.
#[cfg(windows)]
pub(crate) fn host_pipeline_for<'a>(this: This, bound: &host::TargetFormats) -> Option<&'a host::HostPipeline> {
if this.is_null() {
return None;
}
let p = &pipeline(this).host;
if p.formats != *bound && host::formats_differ(&p.formats, bound) {
return make::for_formats(p, bound);
}
make::ready(p)
}
/// Host pipelines queued and not made yet.
#[cfg(windows)]
pub(crate) fn making() -> u64 {
+78
View File
@@ -150,6 +150,84 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1
host
}
/// LOCAL (fxceless a35c557393, `VICTORY_TARGET_VARIANTS`): the formats of
/// what a draw draws into, as the host has them: the eight render targets
/// (0 where there is none), then depth (0 for none).
pub(crate) type TargetFormats = [u32; 9];
/// Whether a draw into views of the formats `bound` cannot go to the host
/// with a pipeline that declares `declared`: a render target slot for which
/// the pipeline declares a format has a view of another format bound. On
/// the console the view's format rules (fxceless run 289: a full-screen
/// zoom and blur declaring R10G10B10A2_UNORM drawn into R11G11B10_FLOAT);
/// on the host that draw is an invalid call, undefined without the debug
/// layer. Empty slots, views in undeclared slots and depth do not count.
pub(crate) fn formats_differ(declared: &TargetFormats, bound: &TargetFormats) -> bool {
declared[..8].iter().zip(&bound[..8]).any(|(&d, &b)| d != 0 && b != 0 && b != d)
}
/// The formats a pipeline for a draw into `bound` declares: the title's,
/// but the declared render target slots with a view bound take its format.
pub(crate) fn formats_for(declared: &TargetFormats, bound: &TargetFormats) -> TargetFormats {
let mut formats = *declared;
for i in 0..8 {
if declared[i] != 0 && bound[i] != 0 {
formats[i] = bound[i];
}
}
formats
}
impl GraphicsState {
/// The formats the state declares ([`TargetFormats`]).
pub(crate) fn formats(&self) -> TargetFormats {
let mut formats = [0; 9];
let n = (self.targets.NumRenderTargets as usize).min(8);
for (to, from) in formats.iter_mut().zip(&self.targets.RTFormats[..n]) {
*to = from.0 as u32;
}
formats[8] = self.depth_format.0 as u32;
formats
}
/// The same state for a draw into views of the formats `bound` (from
/// [`formats_for`]): those render target formats, everything else the
/// title's (blending on integer targets goes off when the host pipeline
/// is made, [`host_blend`]). Its description differs, so it has a name
/// of its own in the library.
pub(crate) fn with_formats(&self, bound: &TargetFormats) -> GraphicsState {
let names = self.names.clone();
let inputs: Vec<D3D12_INPUT_ELEMENT_DESC> = self
.inputs
.iter()
.zip(&names)
.map(|(e, name)| D3D12_INPUT_ELEMENT_DESC {
SemanticName: windows::core::PCSTR(name.as_ptr().cast()),
..*e
})
.collect();
let mut targets = self.targets;
let n = (targets.NumRenderTargets as usize).min(8);
for (to, &from) in targets.RTFormats[..n].iter_mut().zip(bound) {
*to = DXGI_FORMAT(from as i32);
}
GraphicsState {
blend: self.blend,
sample_mask: self.sample_mask,
rasterizer: self.rasterizer,
depth: self.depth,
depth_bounds: self.depth_bounds,
inputs,
names,
strip_cut: self.strip_cut,
topology: self.topology,
targets,
depth_format: self.depth_format,
samples: self.samples,
}
}
}
impl GraphicsState {
/// Whether the draws are a pass over the screen: no vertex input, no
/// depth or stencil, a target. Such passes fill tables once; their shaders
+94 -2
View File
@@ -27,7 +27,7 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
use super::Shader;
use super::host::{GraphicsState, HostPipeline};
use super::host::{GraphicsState, HostPipeline, TargetFormats};
/// What a host pipeline is made from, and the host pipeline once made.
pub(crate) struct Pending {
@@ -43,6 +43,14 @@ pub(crate) struct Pending {
used: AtomicBool,
/// A pass over the screen ([`GraphicsState::screen_pass`]).
screen: bool,
/// LOCAL: how long draws have waited for it so far, in microseconds
/// ([`wait_once`]).
waited_us: AtomicU64,
/// LOCAL (fxceless a35c557393): the formats its state declares (zeros
/// without a graphics state), and the same shaders and state for other
/// formats bound at a draw ([`for_formats`]): a chain, one link per set.
pub(crate) formats: TargetFormats,
variant: OnceLock<Arc<Pending>>,
}
// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
@@ -60,6 +68,8 @@ impl Pending {
}
key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
Pending {
formats: graphics.as_ref().map_or([0; 9], |g| g.formats()),
variant: OnceLock::new(),
screen: graphics.as_ref().is_some_and(|g| g.screen_pass()),
shaders,
graphics,
@@ -68,6 +78,7 @@ impl Pending {
made: OnceLock::new(),
key: key.finalize().to_hex()[..32].to_owned(),
used: AtomicBool::new(false),
waited_us: AtomicU64::new(0),
}
}
@@ -156,6 +167,52 @@ pub(crate) fn waiting() -> u64 {
WAITING.load(Ordering::Relaxed)
}
/// Pipelines made again for the formats bound at a draw, since the start.
static VARIANTS: AtomicU64 = AtomicU64::new(0);
/// Whether a draw into views of other formats than its pipeline declares
/// gets a host pipeline for those formats ([`for_formats`]); on unless
/// `VICTORY_TARGET_VARIANTS=0`.
fn variants_on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_TARGET_VARIANTS").is_none_or(|v| v != "0"))
}
/// The host pipeline for a draw with `p` into views of the formats `bound`
/// that `p` does not declare: that of the same shaders and state for those
/// formats, queued and waited for like the title's own.
#[cold]
pub(crate) fn for_formats<'a>(p: &'a Arc<Pending>, bound: &TargetFormats) -> Option<&'a HostPipeline> {
match p.graphics.as_deref() {
Some(g) if variants_on() => ready(variant(p, g, &super::host::formats_for(&p.formats, bound))),
_ => ready(p),
}
}
/// The pipeline of `p`'s shaders and state `g` for the formats `bound`:
/// found in the chain from `p`, or added to it (logged once per set).
fn variant<'a>(p: &'a Arc<Pending>, g: &GraphicsState, bound: &TargetFormats) -> &'a Arc<Pending> {
let mut at = p;
for _ in 0..64 {
let next = at.variant.get_or_init(|| {
let so_far = VARIANTS.fetch_add(1, Ordering::Relaxed) + 1;
tracing::info!(
pipeline = %hashes(p),
declared = ?p.formats,
bound = ?bound,
so_far,
"a pipeline is made again for the render target formats bound at its draw (VICTORY_TARGET_VARIANTS=0: the draw goes out with the title's pipeline)"
);
Arc::new(Pending::new(p.shaders.clone(), Some(Box::new(g.with_formats(bound)))))
});
if next.formats == *bound {
return next;
}
at = next;
}
p
}
/// The host pipeline if it is made (or is made within the frame's budget);
/// queues it on first use.
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
@@ -200,6 +257,21 @@ fn shared_budget() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0"))
}
/// LOCAL (the problem of fxceless issue #1181): whether one pipeline is
/// waited for at most one budget over the whole run, not one budget every
/// frame. A pipeline whose make takes longer than the budget (a driver
/// compile of tens of seconds, or one that never ends) otherwise cost the
/// whole budget in every frame in which a draw asked for it: with
/// `VICTORY_PIPELINE_WAIT_MS=10000` the picture stood still while the thing
/// drawn with it was in view, and moved again when the camera turned away.
/// After its budget its draws are dropped until it is made, as with any
/// pipeline past the frame's budget. On by default;
/// `VICTORY_PIPELINE_WAIT_ONCE=0` waits as before.
fn wait_once() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_ONCE").is_none_or(|v| v != "0"))
}
/// Waits for `p` while frame `frame` has budget left.
fn wait(p: &Pending, frame: u64) {
let screen = p.screen && screens_first();
@@ -207,6 +279,16 @@ fn wait(p: &Pending, frame: u64) {
if budget.is_zero() {
return;
}
// LOCAL: what is left of this pipeline's own budget ([`wait_once`]).
let own = if wait_once() {
let own = budget.saturating_sub(Duration::from_micros(p.waited_us.load(Ordering::Relaxed)));
if own.is_zero() {
return;
}
own
} else {
Duration::MAX
};
// The frame the budget belongs to, and what was waited of it (or is
// taken by a thread waiting now); of the passes over the screen too.
static SPENT: [Mutex<(u64, Duration)>; 2] = [const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2];
@@ -217,7 +299,7 @@ fn wait(p: &Pending, frame: u64) {
if spent.0 != frame {
*spent = (frame, Duration::ZERO);
}
let left = budget.saturating_sub(spent.1);
let left = budget.saturating_sub(spent.1).min(own);
if shared {
spent.1 += left;
}
@@ -238,6 +320,16 @@ fn wait(p: &Pending, frame: u64) {
}
drop(held);
let waited = started.elapsed().min(left);
if wait_once() && p.made.get().is_none() {
let before = p.waited_us.fetch_add(waited.as_micros() as u64, Ordering::Relaxed);
if Duration::from_micros(before) + waited >= budget {
tracing::info!(
shaders = ?p.shaders,
ms = budget.as_millis() as u64,
"a pipeline not made within its wait: its draws are dropped until it is (VICTORY_PIPELINE_WAIT_ONCE=0: waited for every frame)"
);
}
}
if screen && waited > Duration::from_millis(500) {
tracing::info!(
ms = waited.as_millis() as u64,
+16
View File
@@ -64,6 +64,10 @@ fn build() -> [u8; 32] {
// executable had cached with the switch unset.
for name in [
"VICTORY_BVH_MISS",
// LOCAL: colours and image stores with NaN made 0.
"VICTORY_NAN_SCRUB",
// LOCAL (fxceless #1216): constant buffer slots marked.
"VICTORY_CONSTANT_MARKS",
"VICTORY_WAVE_WIDE",
"VICTORY_WAVE_DEEP_SKIPS",
"VICTORY_WAVE_OWN_BITS",
@@ -268,6 +272,11 @@ fn encode(s: &HostShader) -> Vec<u8> {
word(&mut out, value);
}
}
word(&mut out, s.half_views.len() as u32);
for &(slot, dword) in &s.half_views {
word(&mut out, u32::from(slot));
word(&mut out, dword);
}
out
}
@@ -336,6 +345,11 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?,
});
}
let n = r.word()? as usize;
let mut half_views = Vec::with_capacity(n.min(256));
for _ in 0..n {
half_views.push((u8::try_from(r.word()?).ok()?, r.word()?));
}
r.0.is_empty().then_some(HostShader {
stage,
dxil,
@@ -346,6 +360,7 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
root_srvs,
root_uavs,
root_indexed_views,
half_views,
})
}
@@ -380,6 +395,7 @@ mod tests {
byte_offset: 32,
shift: 5,
}],
half_views: vec![(0, 8), (4, 0)],
}
}
+58 -2
View File
@@ -65,6 +65,10 @@ pub(crate) struct Staging {
/// The staging buffer's bytes (counted in `STAGED` while it lives).
bytes: u64,
memory: *const u8,
/// Whether the guard may stand for a hash of this texture (LOCAL,
/// fxceless #489): not for a video's picture planes, which the decoder
/// writes through another view of the same pages.
guard_view: bool,
last: Mutex<Last>,
/// Whether the staging buffer was detiled since a submitted list last
/// uploaded it, and whether one has uploaded it at all: a list records
@@ -111,6 +115,20 @@ struct Last {
/// and after the hash found a change the guard did not see.
const HOT_FRAMES: u64 = 64;
/// LOCAL (wt5 build38, bodnjenie14 12457b43 "Bink video flickering"): after
/// the hash finds a change the guard did not see, the texture stays hot this
/// many frames (`VICTORY_VIDEO_HOT_FRAMES`, 1,024 unless said; 64 before).
/// With 64 the intro video's ring slots went cold between their own changes
/// and showed frames from earlier again (wt5 r_fps2; the user confirmed
/// 1,024 fixed it). Only textures caught changing unseen get it, so the
/// world's static textures do not pay for it.
fn blind_hot_frames() -> u64 {
static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
*N.get_or_init(|| {
std::env::var("VICTORY_VIDEO_HOT_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1024)
})
}
/// Whether a guarded texture whose memory the hash found changed although
/// the guard saw no write is hashed at every check for a while
/// ([`HOT_FRAMES`]), not every eighth frame. A title that writes such a
@@ -788,7 +806,15 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
// frame was recorded before that check).
if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
// LOCAL: not for a video's picture planes (`guard_view` false). Their
// check at submission finds the frame the decoder wrote since, but the
// copy came only with the next list that samples the plane: three
// frames later in the video's ring of three, and the brightness and
// colour planes each on their own turn, so the intro showed colour
// ghosts and pictures from earlier (r_avm23, the user's recording).
// With the copy recorded here, it takes what that check puts in the
// staging buffer at this list's submission.
if staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexSkipped, 1);
list.defer_texture(staging);
@@ -1211,6 +1237,7 @@ impl Staging {
// The guard saw no write: a change the hash finds came another way.
let mut blind = false;
if !alone
&& self.guard_view
&& *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0"))
&& let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true))
{
@@ -1235,7 +1262,7 @@ impl Staging {
// A change the guard did not see: hashed at every check for a while.
let found_blind = |last: &mut Last| {
if blind && hot_textures() {
last.hot_until = crate::frame::current() + HOT_FRAMES;
last.hot_until = crate::frame::current() + blind_hot_frames();
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexHot, 1);
}
@@ -1774,6 +1801,34 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
let host = host()?;
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
// LOCAL (fxceless #489, "Fix stale frames in the opening video"): the
// software-decoded movie's planes are linear single-level R8 textures
// the decoder can write through another view of the same pages, which
// the guard on the sampled view does not see: with a hash every eighth
// frame the movie replayed its ring of three old frames (A, B, C, A, B,
// C). Those are hashed at every check. `VICTORY_VIDEO_PLANES=0`: as before.
static PLANES: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let guard_view = !(*PLANES.get_or_init(|| std::env::var_os("VICTORY_VIDEO_PLANES").is_none_or(|v| v != "0"))
&& d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D
&& d.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM
&& d.MipLevels == 1
&& d.DepthOrArraySize == 1
&& layout.desc.swizzle == victory_formats::texture::Swizzle::LINEAR);
// Which one-level R8 textures count as video planes, to check the rule
// against the title's (the first few only).
if d.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM && d.MipLevels == 1 {
static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 24 {
tracing::info!(
width = d.Width,
height = d.Height,
layers = d.DepthOrArraySize,
swizzle = ?layout.desc.swizzle,
video_plane = !guard_view,
"a one-level R8 texture staged"
);
}
}
let level0 = copy.base;
let mips = level0 + u32::from(d.MipLevels);
let first = crate::resource::read_from(&layout, first).max(level0).min(mips - 1);
@@ -1834,6 +1889,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
once: std::sync::atomic::AtomicBool::new(once() && !on_demand && PICKING.get().is_some()),
bytes: total,
memory,
guard_view,
last: Mutex::default(),
dirty: std::sync::atomic::AtomicBool::new(true),
uploaded: std::sync::atomic::AtomicBool::new(false),
+18 -1
View File
@@ -1237,7 +1237,24 @@ fn translated_compute_matches_pc() {
};
roots.push((1 + n as u32, Root::View { srv, data }));
}
let ours = host.dispatch(&root_t, &pso_t, &dispatch(roots));
// A buffer of halves the translated program moves as unsigned
// integers is shown to it as its unsigned twin, as the host does
// (`HostShader::half_views`); the PC program keeps the float view.
let twins: Vec<View> = views
.iter()
.map(|&v| match v {
View::HalfUav(n) if !cs_c.half_views.is_empty() => View::HalfUintUav(n),
v => v,
})
.collect();
let ours = host.dispatch(
&root_t,
&pso_t,
&Dispatch {
views: &twins,
..dispatch(roots)
},
);
if name.starts_with("terminates") {
match ours {
Ok(_) => eprintln!("{name}: finished"),
+148
View File
@@ -0,0 +1,148 @@
//! Typed buffer loads that move 16-bit halves without the d16 form: a
//! format load of whole dwords whose result the program reads only one
//! half of, as a half float, moves 16-bit integers, like a d16 access
//! ([`super::super::HostShader::half_views`]).
use std::collections::HashSet;
use super::{Fields, Inst, Lower, Operand, Reg, Role, RootType, Source, Value};
impl<'a> Lower<'a> {
/// Whether every use of `value`, a typed buffer load's result, reads
/// one 16-bit half of it as a half float: a `v_fma_mix*` source with
/// its `op_sel_hi` bit set, or `v_cvt_f32_f16`. A program that takes a
/// format load apart like that reads a 16-bit integer view on the
/// console (the load gives the zero-extended integer, whose bits are a
/// half; a float view's value it would not take apart). A use is a
/// read as an operand ([`crate::ir::operand_reads`]): a later write of
/// the register reads the value only to keep it in the lanes EXEC
/// leaves alone, and a phi carries it on, its own uses counting. False
/// without a use.
pub(super) fn read_only_as_halves(&self, value: Value) -> bool {
let p = self.x.p;
let mut used = false;
let mut seen = HashSet::from([value]);
let mut todo = vec![value];
while let Some(value) = todo.pop() {
for b in &p.blocks {
for phi in b.phis.iter().filter(|phi| phi.args.contains(&value)) {
if seen.insert(phi.value) {
todo.push(phi.value);
}
}
for i in &b.insts {
if !i.reads.iter().any(|r| r.1 == value) {
continue;
}
let operands = crate::ir::operand_reads(p, i);
let regs: Vec<Reg> = i
.reads
.iter()
.filter(|r| r.1 == value && operands.contains(&r.0))
.map(|r| r.0)
.collect();
if regs.is_empty() {
continue;
}
used = true;
let Fields::Valu(v) = &i.fields else {
return false;
};
match i.name() {
"v_cvt_f32_f16" => {}
"v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
let whole = v.src.iter().enumerate().any(|(k, op)| {
matches!(*op, Operand::Vector { reg, .. } if regs.contains(&Reg::V(reg)))
&& v.opsel_hi >> k & 1 == 0
});
if whole {
return false;
}
}
_ => return false,
}
}
}
}
used
}
/// Whether `inst` is a format load of whole dwords (not d16) whose
/// every channel is read only as halves ([`Self::read_only_as_halves`]).
pub(super) fn format_load_read_as_halves(&self, inst: &Inst) -> bool {
let Fields::Buffer {
data: Some(Operand::Vector { reg, .. }),
..
} = inst.fields
else {
return false;
};
let name = inst.name();
let count = match name
.strip_prefix("buffer_load_format_")
.or(name.strip_prefix("tbuffer_load_format_"))
{
Some("x") => 1,
Some("xy") => 2,
Some("xyz") => 3,
Some("xyzw") => 4,
_ => return false,
};
(0..count).all(|k| {
inst.write(Reg::V(reg + k))
.is_some_and(|v| self.read_only_as_halves(v))
})
}
/// The table places ([`Self::table_place`]) every access through which
/// moves halves: a d16 access, or a format load read only as halves
/// ([`Self::format_load_read_as_halves`]). A place the program reaches
/// otherwise too is left out (a format load of numbers beside one of
/// halves, a raw or scalar load, a descriptor chosen by control flow),
/// and so is every place of a table the program also picks from at run
/// time: what the program makes of such a view is not halves alone.
pub(super) fn places_read_as_halves(&self) -> std::collections::BTreeSet<(u8, u32)> {
let mut halves = std::collections::BTreeSet::new();
let mut other = std::collections::BTreeSet::new();
let mut picked = HashSet::new();
for d in &self.x.res.descriptors {
if d.role == Role::Sampler {
continue;
}
let inst = self
.x
.p
.blocks
.get(d.site.0)
.and_then(|b| b.insts.get(d.site.1));
let half = matches!(d.source, Source::Loaded { .. })
&& inst.is_some_and(|i| {
(i.name().starts_with("buffer_") && i.name().contains("_format_d16_"))
|| self.format_load_read_as_halves(i)
});
for leaf in d.source.leaves() {
let Source::Loaded { load, .. } = leaf else {
continue;
};
let Some(a) = self.scalar.get(load) else {
continue;
};
if a.dynamic.is_some() {
if let Some(rp) = self.x.native.layout.get(a.param)
&& rp.root == RootType::Table
{
picked.insert(rp.slot);
}
} else if let Some(place) = self.table_place(leaf) {
if half {
halves.insert(place);
} else {
other.insert(place);
}
}
}
}
halves.retain(|p| !other.contains(p) && !picked.contains(&p.0));
halves
}
}
+12 -1
View File
@@ -612,6 +612,7 @@ fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader {
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
half_views: Vec::new(),
}
}
@@ -991,6 +992,7 @@ fn transition(
/// A view in the heap for [`Host::dispatch`].
#[cfg(test)]
#[derive(Clone, Copy)]
pub enum View<'a> {
/// An RGBA32F texture SRV (width, height, texels).
Texture(u32, u32, &'a [[f32; 4]]),
@@ -1004,6 +1006,9 @@ pub enum View<'a> {
UintTextureUav(u32, u32),
/// A typed RGBA16F buffer UAV of this many elements, zeroed.
HalfUav(u32),
/// The same buffer viewed as R16G16B16A16_UINT: what a translated
/// program that moves halves is shown ([`super::HostShader::half_views`]).
HalfUintUav(u32),
/// A constant buffer of these dwords.
Cbv(&'a [u32]),
/// A buffer SRV over these dwords.
@@ -1240,7 +1245,7 @@ impl Host {
);
keep.push(tex);
}
View::RawUav(_) | View::HalfUav(_) => {
View::RawUav(_) | View::HalfUav(_) | View::HalfUintUav(_) => {
// (dwords, format, elements, flags)
let (n, format, elements, flags) = match *v {
View::HalfUav(e) => (
@@ -1249,6 +1254,12 @@ impl Host {
e,
D3D12_BUFFER_UAV_FLAG_NONE,
),
View::HalfUintUav(e) => (
2 * e,
DXGI_FORMAT_R16G16B16A16_UINT,
e,
D3D12_BUFFER_UAV_FLAG_NONE,
),
View::RawUav(n) => {
(n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW)
}
@@ -194,6 +194,7 @@ pub(super) fn build_compute_shader(
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views.clone(),
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
+199 -34
View File
@@ -25,6 +25,11 @@ use crate::structure::{Atom, Bool, LaneExit, Structured};
#[path = "intersect.rs"]
pub(super) mod intersect;
/// Format loads that move 16-bit halves without the d16 form, a child
/// module so it shares the emitter's state.
#[path = "halves.rs"]
mod halves;
type Why = &'static str;
/// How an interpolation evaluates an input channel.
@@ -55,6 +60,8 @@ pub(crate) struct Lowered {
pub root_cbvs: Vec<u8>,
pub root_srvs: Vec<u8>,
pub root_uavs: Vec<u8>,
/// See [`super::HostShader::half_views`].
pub half_views: Vec<(u8, u32)>,
pub user_data: Vec<UserData>,
pub samplers: Vec<[u32; 4]>,
/// The wave size the shader requires of the host, if any.
@@ -96,6 +103,12 @@ pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
/// 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).
/// LOCAL: `VICTORY_NAN_SCRUB=1` (off by default): see `Lower::scrub_nan`.
pub(crate) fn nan_scrub() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_NAN_SCRUB").is_some_and(|v| v == "1"))
}
fn counted_in_threads(parts: &Parts) -> bool {
let crate::native::StageIo::Cs(cs) = &parts.native.io else {
return false;
@@ -295,6 +308,11 @@ struct Lower<'a> {
params: HashMap<Value, (usize, u32)>,
user_data: Option<V>,
user_reads: BTreeMap<u32, UserData>,
/// Table descriptors read or written sixteen bits a channel
/// ([`super::HostShader::half_views`]): root parameter, dword offset.
half_views: std::collections::BTreeSet<(u8, u32)>,
/// [`Self::places_read_as_halves`], found before the code is lowered.
halves_only: std::collections::BTreeSet<(u8, u32)>,
samplers: Vec<[u32; 4]>,
descriptors: HashMap<(Site, bool), &'a Source>,
scalar: HashMap<Site, Address>,
@@ -1635,6 +1653,8 @@ impl<'a> Lower<'a> {
params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
user_data: None,
user_reads: BTreeMap::new(),
half_views: Default::default(),
halves_only: Default::default(),
samplers: Vec::new(),
descriptors: x
.res
@@ -2335,6 +2355,7 @@ impl<'a> Lower<'a> {
self.s.entry = body;
}
self.find_coherent();
self.halves_only = self.places_read_as_halves();
let order = crate::ir::reverse_postorder(&p.blocks);
for (n, &b) in order.iter().enumerate() {
self.rpo[b] = n;
@@ -2420,6 +2441,7 @@ impl<'a> Lower<'a> {
let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
let half_views = std::mem::take(&mut self.half_views).into_iter().collect();
let cmp_samplers = self.s.cmp_samplers;
let wave_size = self.s.wave_size;
Ok(Lowered {
@@ -2428,6 +2450,7 @@ impl<'a> Lower<'a> {
root_cbvs,
root_srvs,
root_uavs,
half_views,
#[cfg(test)]
nonuniform_handles: self.s.nonuniform_handles,
#[cfg(test)]
@@ -6197,7 +6220,12 @@ impl<'a> Lower<'a> {
raw.push((x, zero));
}
let raw = self.end_guarded(at, &raw);
let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
// LOCAL (fxceless #1216): only a slot marked as a constant
// buffer is read as one; any other non-buffer gives zeros.
let other = match self.slot_is_constant(src)? {
Some(is_constant) => is_constant,
None => self.s.m.cmp(self.cur, pred::EQ, stride, zero),
};
let at = self.begin_guarded(Some(other));
let h = self.handle(site, src, false, (13, 0x1_0000))?;
let mut both = Vec::new();
@@ -6482,7 +6510,15 @@ impl<'a> Lower<'a> {
let props = if un.starts_with("buffer_load_format")
|| un.starts_with("buffer_store_format")
{
(10 | u, 0x409)
// (Unsigned integers where the access moves halves.)
let halves = self
.table_place(&Source::Loaded { load: site, first })
.is_some_and(|p| {
self.halves_only.contains(&p)
&& (un.contains("_format_d16_")
|| self.format_load_read_as_halves(ui))
});
(10 | u, if halves { 0x405 } else { 0x409 })
} else if !counted
&& *idxen
&& format.is_none()
@@ -7122,6 +7158,22 @@ impl<'a> Lower<'a> {
(kind == Some(ResourceType::Uav)).then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
}
/// The table descriptor `src` is, as (root parameter, dword in the
/// table), when the code loads it from a fixed place in a table: the
/// load's own place, not the start of the range its used-resource
/// entry describes (a range of several descriptors starts before most
/// of them). `None` for a descriptor picked at run time, built in the
/// code or chosen by control flow.
fn table_place(&self, src: &Source) -> Option<(u8, u32)> {
let Source::Loaded { load, first } = src else {
return None;
};
let a = self.scalar.get(load)?;
let rp = self.x.native.layout.get(a.param)?;
(rp.root == RootType::Table && a.dynamic.is_none())
.then(|| (rp.slot, a.offset / 4 + u32::from(*first)))
}
/// The used-resource entry a descriptor loaded from a table falls in.
fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
@@ -7477,10 +7529,33 @@ impl<'a> Lower<'a> {
let word = self.slot_word(src)?;
Ok(word.map(|word| {
let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
self.s.m.bin(self.cur, Bin::And, word, bits)
let stride = self.s.m.bin(self.cur, Bin::And, word, bits);
if super::shader::constant_marks() {
// LOCAL (fxceless #1216): the mark of a constant buffer
// slot is no stride.
let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT);
let is_constant = self.s.m.cmp(self.cur, pred::EQ, word, mark);
let zero = self.s.m.i32(0);
self.s.m.select(self.cur, is_constant, zero, stride)
} else {
stride
}
}))
}
/// LOCAL (fxceless #1216): with [`super::shader::constant_marks`],
/// whether the slot `src` names holds a constant buffer view.
fn slot_is_constant(&mut self, src: &Source) -> Result<Option<V>, Why> {
if !super::shader::constant_marks() {
return Ok(None);
}
let Some(word) = self.slot_word(src)? else {
return Ok(None);
};
let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT);
Ok(Some(self.s.m.cmp(self.cur, pred::EQ, word, mark)))
}
/// Whether the typed buffer view `src` names is one of an integer format,
/// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the
/// program does not pick from the heap).
@@ -10932,6 +11007,10 @@ impl<'a> Lower<'a> {
self.float_of(v)?
});
}
// LOCAL: `VICTORY_NAN_SCRUB=1` (see `scrub_nan`).
for v in &mut vals {
*v = self.scrub_nan(*v);
}
let h = self.handle(site, src, false, props)?;
let at = self.begin_guarded(guard);
let mut args = vec![h];
@@ -11630,6 +11709,23 @@ impl<'a> Lower<'a> {
.copied()
.ok_or("an untracked buffer")?;
let used = self.used_kind(src);
// Sixteen bits a channel through a view of a table: the bits go as
// they are, as unsigned integers, and the host is told, which shows
// the shader a 16-bit float view there as its unsigned twin
// ([`super::HostShader::half_views`]).
// A format load of whole dwords whose every use reads one half of a
// result as a half float moves 16-bit integers too (the head
// program's reads of the face network's output), where every
// access through its view does ([`Self::places_read_as_halves`]).
// A d16 access too only where every access does: a whole float
// read through the same place would see the unsigned twin.
let place = typed.then(|| self.table_place(src)).flatten().filter(|p| {
self.halves_only.contains(p) && (d16 || self.format_load_read_as_halves(inst))
});
let halves = place.is_some();
if let Some(place) = place {
self.half_views.insert(place);
}
let (base, extra) = self.built_offset(src)?;
if base != 0 {
let b = self.s.m.i32(base);
@@ -11861,14 +11957,16 @@ impl<'a> Lower<'a> {
let mut vals =
self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
if d16 {
// d16 data is taken as f16, widened for the 32-bit float
// store; through a view of an integer format it is a 16-bit
// Through a view of a table each half is stored as it is
// (`halves`, fxceless #927). Reached another way, d16 data
// is taken as f16, widened for the 32-bit float store;
// through a view of an integer format it is a 16-bit
// integer, zero- or sign-extended (VIctory 4243a96a: the face
// network keeps its halves in UINT views; its output was
// noise). shortcut: that is known of the views a program
// picks from the heap, not of those in its tables; and the
// handle stays a float one, whose bits the drivers pass.
let integer = if typed { self.integer_view(src)? } else { None };
// picks from the heap; and the handle stays a float one,
// whose bits the drivers pass.
let integer = if typed && !halves { self.integer_view(src)? } else { None };
let mut wide = Vec::new();
for k in 0..count {
let mut x = vals[(k / 2) as usize];
@@ -11876,6 +11974,11 @@ impl<'a> Lower<'a> {
let k16 = self.s.m.i32(16);
x = self.s.m.bin(c, Bin::LShr, x, k16);
}
if halves {
let low = self.s.m.i32(0xffff);
wide.push(self.s.m.bin(c, Bin::And, x, low));
continue;
}
let f32t = self.s.t.f32;
let f = self
.s
@@ -11900,12 +12003,21 @@ impl<'a> Lower<'a> {
if count != 4 || *offen || *offset != 0 {
return Err("a typed buffer store of some channels or at an offset");
}
args.push(self.handle(site, src, false, (10 | u, 0x409))?);
// Four unsigned integers for halves, four floats otherwise.
let component = if halves { 0x405 } else { 0x409 };
args.push(self.handle(site, src, false, (10 | u, component))?);
args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
for x in vals {
args.push(self.as_float(x));
args.push(if halves { x } else { self.as_float(x) });
}
(69, "bufferStore.f32")
(
69,
if halves {
"bufferStore.i32"
} else {
"bufferStore.f32"
},
)
} else {
match index {
// A raw buffer (stride 1) written by index: the index is the byte.
@@ -11965,16 +12077,30 @@ impl<'a> Lower<'a> {
if uav {
self.s.flags |= flags::TYPED_UAV_LOADS;
}
let h = self.handle(site, src, false, (10 | u, 0x409))?;
let index = index.unwrap_or(self.s.m.i32(0));
self.s.op(
c,
"bufferLoad.f32",
Attr::ReadOnly,
self.s.t.res_ret,
68,
&[h, index, iu],
)
if halves {
let h = self.handle(site, src, false, (10 | u, 0x405))?;
let i32t = self.s.t.i32;
let ret = self.s.m.named_struct("dx.types.ResRet.i32", vec![i32t; 5]);
self.s.op(
c,
"bufferLoad.i32",
Attr::ReadOnly,
ret,
68,
&[h, index, iu],
)
} else {
let h = self.handle(site, src, false, (10 | u, 0x409))?;
self.s.op(
c,
"bufferLoad.f32",
Attr::ReadOnly,
self.s.t.res_ret,
68,
&[h, index, iu],
)
}
} else {
let mask = self.s.m.i8((1u8 << count) - 1);
let align = self.s.m.i32(4);
@@ -12024,24 +12150,32 @@ impl<'a> Lower<'a> {
return Err("a buffer result");
};
if d16 {
// Two f16 channels per VGPR (an odd last high half 0); the low
// 16 bits of an integer view's (see the stores above).
let integer = if typed { self.integer_view(src)? } else { None };
// Two f16 channels per VGPR (an odd last high half 0); through
// a view of a table, the 16 bits of each as they are (fxceless
// #927); the low 16 bits of an integer view's picked from the
// heap (see the stores above).
let integer = if typed && !halves { self.integer_view(src)? } else { None };
let k16 = self.s.m.i32(16);
let i32t = self.s.t.i32;
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 mut h = self
.s
.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
if let Some((int, _)) = integer {
let bits = self.as_int(f);
let low = self.s.m.i32(0xFFFF);
let low = self.s.m.bin(c, Bin::And, bits, low);
h = self.s.m.select(c, int, low, h);
}
let h = if halves {
let low = self.s.m.i32(0xffff);
self.s.m.bin(c, Bin::And, f, low)
} else {
let mut h = self
.s
.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
if let Some((int, _)) = integer {
let bits = self.as_int(f);
let low = self.s.m.i32(0xFFFF);
let low = self.s.m.bin(c, Bin::And, bits, low);
h = self.s.m.select(c, int, low, h);
}
h
};
x = Some(match x {
Some(hi) => {
let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
@@ -12056,12 +12190,34 @@ impl<'a> Lower<'a> {
}
for k in 0..count {
let x = self.s.m.extract(c, r, k);
let x = self.as_int(x);
// (Integers already where the load moved halves.)
let x = if halves { x } else { self.as_int(x) };
self.write(inst, Reg::V(reg + k as u8), x, guard);
}
Ok(())
}
/// LOCAL: with `VICTORY_NAN_SCRUB=1` (off by default), `f` or 0 where it
/// is NaN. Used on the colours pixel shaders write and on float image
/// stores: a NaN that reaches the title's bloom, blur or temporal
/// upscaler spreads into black patches that stay in its history (seen on
/// NVIDIA as black blobs on faces and in the air). Not what the console
/// does, so it is a switch; part of the shader cache key.
fn scrub_nan(&mut self, f: V) -> V {
if !nan_scrub() {
return f;
}
// NaN or an infinity (11/26: the whole picture went white at one
// angle with only NaN scrubbed: an infinity through bloom or the
// exposure does the same). |f| >= inf, unordered: true for NaN too.
let c = self.cur;
let a = self.unary(6, f);
let inf = self.s.m.f32(0x7f80_0000);
let bad = self.s.m.cmp(c, pred::UGE, a, inf);
let zero = self.s.m.f32(0);
self.s.m.select(c, bad, zero, f)
}
fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
let e = *self
.exports
@@ -12247,6 +12403,8 @@ impl<'a> Lower<'a> {
(true, false) => ("storeVertexOutput", 171),
(true, true) => ("storePrimitiveOutput", 172),
};
// LOCAL: a colour a pixel shader writes (`VICTORY_NAN_SCRUB`).
let colour = self.s.pixel && matches!(e.target, Target::Color(_));
for (id, col, value, half) in stores {
let mut x = self.i32_of(value)?;
if let Some(high) = half {
@@ -12265,12 +12423,19 @@ impl<'a> Lower<'a> {
let el = &mut elements(self, primitive)[id];
el.usage |= 1 << col;
let (suffix, x) = match el.comp {
9 if half.is_some() => (".f32", self.as_float(x)),
9 if half.is_some() => {
let f = self.as_float(x);
(".f32", if colour { self.scrub_nan(f) } else { f })
}
9 => {
let f = match self.floats.get(&value) {
Some(&f) => f,
None => self.as_float(x),
};
// LOCAL: `VICTORY_NAN_SCRUB=1`: a colour a pixel shader
// writes is 0 where it is NaN, so one bad value does not
// spread through the title's blur and temporal passes.
let f = if colour { self.scrub_nan(f) } else { f };
(".f32", f)
}
_ => (".i32", x),
+23 -2
View File
@@ -122,8 +122,8 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, 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,
SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
constant_marks, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
};
/// The loop limit without an override: 2^20.
@@ -354,6 +354,21 @@ pub struct HostShader {
pub root_uavs: Vec<u8>,
/// Heap descriptors that can be selected from root state at bind time.
pub root_indexed_views: Vec<crate::resource::RootIndexedView>,
/// Table descriptors (root parameter, dword offset in the table) whose
/// buffer the shader reads or writes sixteen bits a channel
/// (`buffer_load_format_d16_*`, `buffer_store_format_d16_*`), in
/// order. On the console each channel's 16 bits move as they are
/// through a 16-bit float view and through a 16-bit integer one alike
/// (the title keeps half floats, and indices beside them, in
/// `R16G16B16A16_UINT` and `R16_UINT` buffers). The DXIL moves them as
/// unsigned integers, which an unsigned 16-bit view carries unchanged;
/// the host shows the shader a 16-bit float or signed buffer view at
/// these places as the unsigned format of the same layout.
/// shortcut: a view in a normalised 16-bit format, whose values the
/// console would convert to halves, is read as its integers; a
/// descriptor picked at run time keeps the float path (its slot, and so
/// its format, is known only then).
pub half_views: Vec<(u8, u32)>,
}
impl HostShader {
@@ -796,6 +811,7 @@ fn emit_program(
root_srvs: l.root_srvs,
root_uavs: l.root_uavs,
root_indexed_views: res.root_indexed_views.clone(),
half_views: l.half_views,
};
Ok((shader, wave_size))
}
@@ -1578,6 +1594,7 @@ mod tests {
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
half_views: Vec::new(),
};
let file = |var: &str, stage| {
std::env::var(var).ok().map(|p| super::HostShader {
@@ -1590,6 +1607,7 @@ mod tests {
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
half_views: Vec::new(),
})
};
let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
@@ -2199,6 +2217,7 @@ mod tests {
root_srvs: l.root_srvs,
root_uavs: l.root_uavs,
root_indexed_views: Vec::new(),
half_views: Vec::new(),
};
let (root, pso) = host.compute_pipeline(&cs).unwrap();
// Twelve dwords: the loads below run across the view's end.
@@ -2352,6 +2371,7 @@ mod tests {
root_srvs: l.root_srvs,
root_uavs: l.root_uavs,
root_indexed_views: Vec::new(),
half_views: l.half_views,
};
let (root, pso) = host.compute_pipeline(&cs).unwrap();
let inputs: Vec<u32> = [
@@ -2768,6 +2788,7 @@ mod barycentric_tests {
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
half_views: Vec::new(),
};
validate(&vs);
// One triangle covers an 8x8 target, with attribute values 2, 6, 10.
@@ -106,6 +106,7 @@ fn lowered(native: &NativeProgram, host_wave: u32) -> Result<HostShader, ShaderE
root_srvs: result.root_srvs,
root_uavs: result.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: Vec::new(),
};
match validator::Validator::load(validator::Validator::default_path().as_deref()) {
Ok(mut v) => {
@@ -34,6 +34,7 @@ fn probe() {
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
half_views: Vec::new(),
};
let (root, pso) = match host.compute_pipeline(&shader) {
Ok(made) => made,
+1
View File
@@ -415,6 +415,7 @@ mod tests {
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
half_views: Vec::new(),
};
(
host(crate::native::HwStage::Vs, vs),
+19
View File
@@ -34,6 +34,25 @@ pub const VIEW_INTEGER: u32 = 1 << 31;
pub const VIEW_SIGNED: u32 = 1 << 30;
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
/// LOCAL (port of fxceless/victory-fork PR #1216, GamingRipperDoc): the
/// [`SLOT_STRIDES`] dword of a slot that holds a constant buffer view (a
/// stride no buffer has, no kind bits). A program reads a slot it picks as a
/// constant buffer only where this mark is; a slot whose dword is 0 holds
/// neither a buffer nor a constant buffer, and the read gives zeros. Read as
/// a constant buffer, a texture's descriptor is taken as a buffer's: the
/// meshlet culling `_Prev` passes then read whatever lies at a made-up
/// address (a page fault on AMD).
/// `VICTORY_CONSTANT_MARKS=1` turns it on. Off by default here (on in the
/// PR): not yet run in the game on this tree, where a constant buffer slot
/// whose mark is not written yet would read zeros.
pub const SLOT_STRIDE_CONSTANT: u32 = VIEW_STRIDE_BITS;
/// Whether [`SLOT_STRIDE_CONSTANT`] is in use: read once, by the host and
/// the translator alike.
pub fn constant_marks() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_CONSTANT_MARKS").is_some_and(|v| v == "1"))
}
/// Title memory by address (`resource::MEMORY`): console code reads and
/// writes through raw 40-bit addresses it takes from root constants,
@@ -73,6 +73,7 @@ fn build(words: &[u32], srv: (u8, u32)) -> Result<HostShader, ShaderError> {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
half_views: Vec::new(),
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
v.validate(&mut shader.dxil.clone())
@@ -181,6 +181,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
@@ -1918,6 +1919,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
@@ -2057,3 +2059,488 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() {
}
}
}
/// A program that moves a typed buffer's 16-bit channels
/// (`buffer_load_format_d16_xyzw` from the table's first view,
/// `buffer_store_format_d16_xyzw` to its second) names both places for the
/// host (`HostShader::half_views`) and moves every pattern as it is through
/// unsigned views: half floats, the not-a-number ones among them, and
/// plain 16-bit integers (the title keeps both in such buffers; the
/// network that moves its faces reads indices this way). A program that
/// moves no halves names nothing.
#[test]
fn halves_go_through_a_table_as_they_are_and_name_their_views() {
use super::host::Stride;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_UINT;
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_D16_XYZW: u32 = 0x83;
const STORE_D16_XYZW: u32 = 0x87;
const THREADS: u32 = 32;
// The table's second descriptor, 0x20 bytes on.
let mut second = s_load_dwordx4(12, 4);
second[1] |= 0x20;
let mut words = vec![s_mov_b32(5, 0x80)];
words.extend_from_slice(&s_load_dwordx4(8, 4));
words.extend_from_slice(&second);
// v[1:2] = first[thread] (four halves), second[thread] = v[1:2].
words.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
words.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
words.push(S_ENDPGM);
let view = |kind: ResourceType, table_offset_dwords: u32| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
};
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![view(ResourceType::Srv, 0), view(ResourceType::Uav, 8)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [THREADS, 1, 1],
}),
code: words.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("resource::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");
assert_eq!(lowered.half_views, [(1, 0), (1, 8)]);
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,
root_indexed_views: res.root_indexed_views,
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut dxil = shader.dxil.clone();
v.validate(&mut dxil).expect("DXIL validation failed");
}
// A raw store through the same table: no halves, nothing named.
assert!(build_valu_cs(&[]).half_views.is_empty());
// Four halves a thread: numbers, both zeros, subnormals, infinities,
// not-a-numbers of both signs, and integers past the largest number's
// pattern, as indices are.
const SPECIAL: [u16; 16] = [
0x0000, 0x0001, 0x03ff, 0x0400, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e00, 0x7fff, 0x8000,
0x8001, 0xbc00, 0xfc00, 0xfc01, 0xffff,
];
let halves: Vec<u16> = (0..4 * THREADS as usize)
.map(|i| match i {
0..16 => SPECIAL[i],
_ => (i as u16).wrapping_mul(0x0203).wrapping_add(0x7b00),
})
.collect();
let data: Vec<u32> = halves
.chunks(2)
.map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16)
.collect();
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = 0;
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {label} device; skipped");
continue;
};
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer {
data: &data,
stride: Stride::Format(DXGI_FORMAT_R16G16B16A16_UINT, 8),
},
View::HalfUintUav(THREADS),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
assert_eq!(
out[0], data,
"{label}: the halves stored are the halves loaded"
);
ran += 1;
}
assert!(ran > 0, "no SM 6.6 device available");
}
/// The places a program that moves halves names are the descriptors it
/// loads, not the start of the range their used-resource entry describes:
/// with one entry for a range from dword 0, a load at byte 0x20 names
/// dword 8 (a host view there in a 16-bit float format is the one shown
/// as its unsigned twin). A descriptor picked at run time (the load's
/// offset in an SGPR) names nothing and keeps the float path: which slot
/// it reads, and in which format, is known only then.
#[test]
fn half_places_are_the_descriptors_the_program_loads() {
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_D16_XYZW: u32 = 0x83;
const STORE_D16_XYZW: u32 = 0x87;
let lowered = |words: &[u32]| {
let range = |kind: ResourceType, table_offset_dwords: u32| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
};
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
// One entry for a range of views from dword 0, one at 16.
used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 16)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [32, 1, 1],
}),
code: words.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("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
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")
};
// `s_load_dwordx4 s[dst:dst+3], s[4:5], offset` (soffset null), or with
// the offset in `soffset` instead.
let at = |dst: u8, offset: u32| {
let mut w = s_load_dwordx4(dst, 4);
w[1] |= offset;
w
};
let picked = |dst: u8, soffset: u8| {
let mut w = s_load_dwordx4(dst, 4);
w[1] = u32::from(soffset) << 25;
w
};
let mut fixed = vec![s_mov_b32(5, 0x80)];
fixed.extend_from_slice(&at(8, 0x20));
fixed.extend_from_slice(&at(12, 0x40));
fixed.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
fixed.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
fixed.push(S_ENDPGM);
assert_eq!(lowered(&fixed).half_views, [(1, 8), (1, 16)]);
// The load's offset in s20, from the first lane's thread index
// (`v_readfirstlane_b32 s20, v0`): picked at run time. The pick may land
// on the store's place too, so no place of that table is named: the d16
// accesses there take the float path, as before half views.
let mut runtime = vec![s_mov_b32(5, 0x80), vop1(0x02, 20, vgpr(0))];
runtime.extend_from_slice(&picked(8, 20));
runtime.extend_from_slice(&at(12, 0x40));
runtime.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
runtime.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
runtime.push(S_ENDPGM);
assert!(lowered(&runtime).half_views.is_empty());
}
/// A format load of whole dwords (`buffer_load_format_x`, not d16) whose
/// result the program only reads one half of as a half float
/// (`v_cvt_f32_f16`) is moving 16-bit integers: the head program reads the
/// face network's output so, from an `R16_UINT` view. It names its view for
/// the host and loads the integer: 0x3c00 comes through as 1.0. Used as a
/// whole float instead (`v_add_f32`), the load stays a float load and names
/// nothing; so does a load of halves beside a load of the same view read as
/// a whole float (a view of numbers the program also picks one half float
/// out of, as hundreds of the title's pixel programs do).
#[test]
fn a_format_load_read_as_halves_loads_the_integer() {
use super::host::Stride;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT;
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_FORMAT_X: u32 = 0x00;
const V_CVT_F32_F16: u16 = 0x0B;
const V_ADD_F32: u8 = 0x03;
let lowered = |body: &[u32]| {
let view = |kind: ResourceType, table_offset_dwords: u32, stride: u32| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
stride,
dwords: 4,
user_data: 4,
slot: 1,
};
let mut second = s_load_dwordx4(12, 4);
second[1] |= 0x20;
let mut words = vec![s_mov_b32(5, 0x80)];
words.extend_from_slice(&s_load_dwordx4(8, 4));
words.extend_from_slice(&second);
// `body` leaves v2, stored raw.
words.extend_from_slice(body);
words.extend_from_slice(&buffer_store_dword(2, 12, 0));
words.push(S_ENDPGM);
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![view(ResourceType::Srv, 0, 4), view(ResourceType::Uav, 8, 0)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [1, 1, 1],
}),
code: words.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("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
let l = 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");
HostShader {
stage: HwStage::Cs,
dxil: l.dxil,
user_data: l.user_data,
samplers: l.samplers,
static_samplers: Vec::new(),
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
root_uavs: l.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: l.half_views,
}
};
// v1 = first[v0] (one channel).
let load = mubuf_idxen(LOAD_FORMAT_X, 1, 0, 8);
let half = vop1(V_CVT_F32_F16, 2, vgpr(1));
let as_halves = lowered(&[&load[..], &[half]].concat());
assert_eq!(as_halves.half_views, [(1, 0)]);
let as_float = lowered(&[&load[..], &[vop2(V_ADD_F32, 2, vgpr(1), 1)]].concat());
assert!(as_float.half_views.is_empty());
// v3 = first[v0] too, read as a whole float: v2 = half(v1) + v3.
let mut beside = load.to_vec();
beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8));
beside.push(half);
beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2));
assert!(lowered(&beside).half_views.is_empty());
// Behind a branch, as the head program has it: where the lanes meet
// again the loaded value goes on through a phi, and a later write of
// v1 under EXEC reads it only to keep it in the lanes it leaves alone.
const SAVE_EXEC: u32 = 0xBE90_037E; // s_mov_b32 s16, exec_lo
const ONLY_LANE_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec_lo, 0, v0
const SKIP_3: u32 = 0xBF88_0003; // s_cbranch_execz over the next 3 words
const RESTORE_EXEC: u32 = 0xBEFE_0310; // s_mov_b32 exec_lo, s16
let zero = vop1(0x01, 2, 128); // v_mov_b32 v2, 0
let rewrite = vop1(0x01, 1, 128); // v_mov_b32 v1, 0
let branched = lowered(
&[
&[zero, SAVE_EXEC, ONLY_LANE_0, SKIP_3][..],
&load,
&[
half,
RESTORE_EXEC,
SAVE_EXEC,
ONLY_LANE_0,
rewrite,
RESTORE_EXEC,
],
]
.concat(),
);
assert_eq!(branched.half_views, [(1, 0)]);
// A d16 load names its place where it is the only access there...
const LOAD_FORMAT_D16_X: u32 = 0x80;
let d16 = mubuf_idxen(LOAD_FORMAT_D16_X, 1, 0, 8);
let d16_alone = lowered(&[&d16[..], &[half]].concat());
assert_eq!(d16_alone.half_views, [(1, 0)]);
// ...and not beside a whole float read through the same place, which
// would see the unsigned twin: v2 = half(d16 v1) + v3.
let mut d16_beside = d16.to_vec();
d16_beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8));
d16_beside.push(half);
d16_beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2));
assert!(lowered(&d16_beside).half_views.is_empty());
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
for shader in [&as_halves, &branched, &d16_alone] {
let mut dxil = shader.dxil.clone();
v.validate(&mut dxil).expect("DXIL validation failed");
}
}
// Element 0 of an R16_UINT buffer holds the half 1.0 (0x3c00).
let data = [0x0000_3c00u32, 0];
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = 0;
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {label} device; skipped");
continue;
};
for (name, shader) in [("straight", &as_halves), ("branched", &branched)] {
let (root, pso) = host
.compute_pipeline(shader)
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer {
data: &data,
stride: Stride::Format(DXGI_FORMAT_R16_UINT, 2),
},
View::RawUav(1),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
assert_eq!(
out[0][0],
1.0f32.to_bits(),
"{label}, {name}: the half read as an integer's bits"
);
}
ran += 1;
}
assert!(ran > 0, "no SM 6.6 device available");
}
@@ -84,6 +84,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
v.validate(&mut shader.dxil.clone())
@@ -386,6 +387,7 @@ fn immediate_sampler_chosen_by_control_flow() {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
half_views: Vec::new(),
};
if let Ok(mut v) =
validator::Validator::load(validator::Validator::default_path().as_deref())
@@ -142,6 +142,7 @@ fn lowered_counted(
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: lowered.half_views,
})
}
@@ -281,6 +282,7 @@ fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: Vec::new(),
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();