Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 198 additions & 1 deletion crates/xcl/src/hle/d3d12x/targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
//! nothing (a stand-in while the pipeline is built), went to the PC untranslated, skipped – and
//! the `targets` drawn into most (default eight, 64 at most) are written next to the presented
//! frame (`target<k>_<n>.bmp`) with how many of their texels are not zero and how many differ from
//! the first one. A black picture over a scene that was drawn tells a lost composite from a scene
//! the first one. A float target also gets a line with how many of its texels hold a NaN or an
//! infinity, the range and the mean of the finite ones and its first texels (`float_census`): the
//! pictures clamp. A black picture over a scene that was drawn tells a lost composite from a scene
//! that never was; the passes after the scene's (a few draws each) are among the last ranks.
//! `XCL_DUMP_AFTER_S=<s>`: no frame is dumped until `s` seconds after the first present.
//! `XCL_DUMP_ON=<file>`: no frame is dumped until `file` appears (`touch` it at the scene to look
Expand Down Expand Up @@ -755,8 +757,124 @@ pub unsafe fn log_census(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOT
let len = (rb.GetDesc().Width as usize).saturating_sub(fp.Offset as usize);
let data = std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize), len);
let (lit, differ, n) = census(data, f.Width as usize, f.Height as usize, f.RowPitch as usize, f.Format);
let floats = float_census(data, f.Width as usize, f.Height as usize, f.RowPitch as usize, f.Format);
rb.Unmap(0, None);
crate::xlog_info!("D3D12.X: target dump: {tag}: {lit} of {n} texels sampled not zero, {differ} differ from the first texel (format {})", f.Format.0);
if let Some(floats) = floats {
crate::xlog_info!("D3D12.X: target dump: {tag}: {floats}");
}
}

/// A half float's value.
fn half(v: u16) -> f32 {
let (s, e, m) = ((v >> 15) as u32, ((v >> 10) & 0x1F) as u32, (v & 0x3FF) as u32);
match e {
0 => (if s == 1 { -1.0 } else { 1.0 }) * m as f32 * 2f32.powi(-24),
31 => f32::from_bits((s << 31) | 0x7F80_0000 | (m << 13)),
_ => f32::from_bits((s << 31) | ((e + 112) << 23) | (m << 13)),
}
}

/// An unsigned float of 5 exponent bits and `mant` mantissa bits: a channel of R11G11B10_FLOAT
/// (6 bits in red and green, 5 in blue).
fn small_float(v: u32, mant: u32) -> f32 {
let (e, m) = (v >> mant, v & ((1 << mant) - 1));
match e {
0 => m as f32 * 2f32.powi(-14 - mant as i32),
31 if m == 0 => f32::INFINITY,
31 => f32::NAN,
_ => (1.0 + m as f32 / (1u32 << mant) as f32) * 2f32.powi(e as i32 - 15),
}
}

/// The channels of a texel of a float format, and how many it has; None: not a float format.
fn float_texel(t: &[u8], format: DXGI_FORMAT) -> Option<([f32; 4], usize)> {
let h = |i: usize| half(u16::from_le_bytes([t[2 * i], t[2 * i + 1]]));
let f = |i: usize| f32::from_le_bytes([t[4 * i], t[4 * i + 1], t[4 * i + 2], t[4 * i + 3]]);
Some(match format {
DXGI_FORMAT_R32G32B32A32_FLOAT => ([f(0), f(1), f(2), f(3)], 4),
DXGI_FORMAT_R16G16B16A16_FLOAT => ([h(0), h(1), h(2), h(3)], 4),
DXGI_FORMAT_R32G32_FLOAT => ([f(0), f(1), 0.0, 0.0], 2),
DXGI_FORMAT_R16G16_FLOAT => ([h(0), h(1), 0.0, 0.0], 2),
DXGI_FORMAT_R32_FLOAT => ([f(0), 0.0, 0.0, 0.0], 1),
DXGI_FORMAT_R16_FLOAT => ([h(0), 0.0, 0.0, 0.0], 1),
DXGI_FORMAT_R11G11B10_FLOAT => {
let v = u32::from_le_bytes([t[0], t[1], t[2], t[3]]);
([small_float(v & 0x7FF, 6), small_float((v >> 11) & 0x7FF, 6), small_float(v >> 22, 5), 0.0], 3)
}
_ => return None,
})
}

/// A target of this many texels or fewer has all of them read for `float_census`.
const FLOATS_ALL: usize = 4096;

/// What the texels of a float target hold (`float_census`).
#[derive(Debug, PartialEq)]
struct Floats {
/// texels with a NaN in a channel
nan: u64,
/// texels with an infinity in a channel
inf: u64,
/// texels read
n: u64,
/// the least and the largest finite channel (None: no channel is finite)
range: Option<(f32, f32)>,
/// each channel's mean over its finite values (None: the channel has none)
mean: Vec<Option<f64>>,
/// the first texels read, as they are
first: Vec<Vec<f32>>,
}

impl std::fmt::Display for Floats {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "float texels: {} with a NaN and {} with an infinity of {} read", self.nan, self.inf, self.n)?;
match self.range {
Some((lo, hi)) => {
let mean: Vec<String> = self.mean.iter().map(|m| m.map_or("n/a".into(), |m| format!("{m:.4e}"))).collect();
write!(f, "; finite channels from {lo:e} to {hi:e}, mean [{}]", mean.join(", "))?
}
None => write!(f, "; no finite channel")?,
}
write!(f, "; first {:?}", self.first)
}
}

/// Of a float target's texels (all of one of `FLOATS_ALL` texels or fewer, every 4th of every 4th
/// row of a larger one, as the dumps sample): how many hold a NaN and how many an infinity, the
/// least and the largest finite channel, each channel's mean over its finite values (`n/a` for a
/// channel that has none), and the first four texels as they are. The pictures clamp, so one that reads white may hold 1.5 or
/// 40 000, and a NaN that a later pass spreads over the frame shows in no picture. None: not a
/// float format, or no texel in `data`.
fn float_census(data: &[u8], width: usize, height: usize, pitch: usize, format: DXGI_FORMAT) -> Option<Floats> {
let bytes = texel_bytes(format);
let step = if width.saturating_mul(height) <= FLOATS_ALL { 1 } else { 4 };
let mut out = Floats { nan: 0, inf: 0, n: 0, range: None, mean: Vec::new(), first: Vec::new() };
let (mut sum, mut finite) = ([0f64; 4], [0u64; 4]);
for y in (0..height).step_by(step) {
for x in (0..width).step_by(step) {
let at = y * pitch + x * bytes;
let Some(t) = data.get(at..at + bytes) else { continue };
let (c, k) = float_texel(t, format)?;
let c = &c[..k];
out.n += 1;
out.nan += c.iter().any(|v| v.is_nan()) as u64;
out.inf += c.iter().any(|v| v.is_infinite()) as u64;
for (i, &v) in c.iter().enumerate().filter(|(_, v)| v.is_finite()) {
out.range = Some(out.range.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v))));
sum[i] += v as f64;
finite[i] += 1;
}
if out.first.len() < 4 {
out.first.push(c.to_vec());
}
out.mean.resize(k, None);
}
}
for (i, m) in out.mean.iter_mut().enumerate() {
*m = (finite[i] > 0).then(|| sum[i] / finite[i] as f64);
}
(out.n > 0).then_some(out)
}

#[cfg(test)]
Expand Down Expand Up @@ -959,6 +1077,85 @@ mod tests {
assert_eq!(compute_stem(399, 0xab), "compute399_cs_00000000000000ab");
}

#[test]
fn half_and_packed_floats_decode() {
assert_eq!(half(0x3C00), 1.0);
assert_eq!(half(0xC000), -2.0);
assert_eq!(half(0x7BFF), 65504.0);
assert_eq!(half(0x0001), 2f32.powi(-24));
assert_eq!(half(0x8000).to_bits(), (-0.0f32).to_bits());
assert_eq!(half(0x7C00), f32::INFINITY);
assert_eq!(half(0xFC00), f32::NEG_INFINITY);
assert!(half(0x7E00).is_nan());
// R11G11B10: 1.0 is exponent 15 with no mantissa, in 11 bits and in 10
assert_eq!(small_float(15 << 6, 6), 1.0);
assert_eq!(small_float(15 << 5, 5), 1.0);
assert_eq!(small_float((16 << 6) | 32, 6), 3.0);
assert_eq!(small_float(1, 6), 2f32.powi(-20));
assert_eq!(small_float(31 << 6, 6), f32::INFINITY);
assert!(small_float((31 << 5) | 1, 5).is_nan());
// red 1.0, green 3.0, blue 1.0 in one texel
let t = ((15u32 << 6) | (((16 << 6) | 32) << 11) | ((15 << 5) << 22)).to_le_bytes();
assert_eq!(float_texel(&t, DXGI_FORMAT_R11G11B10_FLOAT), Some(([1.0, 3.0, 1.0, 0.0], 3)));
assert_eq!(float_texel(&t, DXGI_FORMAT_R8G8B8A8_UNORM), None);
}

#[test]
fn a_float_targets_census_counts_nan_and_infinity_and_keeps_the_finite_range() {
// 2 x 2 texels of R16G16B16A16_FLOAT in rows of 24 bytes: (1, 2, 4, 1), (NaN, 0, 0, 1),
// (0.5, +inf, 0, 1), (-2, 0, 65504, 1)
let texel = |c: [u16; 4]| c.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
let (w, h, pitch) = (2usize, 2usize, 24usize);
let mut data = vec![0xAAu8; pitch * h];
for (k, c) in [[0x3C00, 0x4000, 0x4400, 0x3C00], [0x7E00, 0, 0, 0x3C00], [0x3800, 0x7C00, 0, 0x3C00], [0xC000, 0, 0x7BFF, 0x3C00]].into_iter().enumerate() {
let at = (k / w) * pitch + (k % w) * 8;
data[at..at + 8].copy_from_slice(&texel(c));
}
let c = float_census(&data, w, h, pitch, DXGI_FORMAT_R16G16B16A16_FLOAT).unwrap();
assert_eq!((c.nan, c.inf, c.n), (1, 1, 4));
assert_eq!(c.range, Some((-2.0, 65504.0)));
// red: 1, 0.5 and -2 are finite; green: 2, 0 and 0; blue and alpha: all four
assert_eq!(c.mean, vec![Some((1.0 + 0.5 - 2.0) / 3.0), Some(2.0 / 3.0), Some((4.0 + 65504.0) / 4.0), Some(1.0)]);
assert_eq!(c.first[0], vec![1.0, 2.0, 4.0, 1.0]);
assert_eq!(c.first.len(), 4);
let line = c.to_string();
assert!(line.starts_with("float texels: 1 with a NaN and 1 with an infinity of 4 read; finite channels from -2e0 to 6.5504e4"), "{line}");
// not a float format: no line; a float one with no texel in the buffer: none either
assert_eq!(float_census(&data, w, h, pitch, DXGI_FORMAT_R16G16B16A16_UNORM), None);
assert_eq!(float_census(&[], w, h, pitch, DXGI_FORMAT_R16G16B16A16_FLOAT), None);
// a target of NaNs only has no finite range
let nans = texel([0x7E00; 4]);
let c = float_census(&nans, 1, 1, 8, DXGI_FORMAT_R16G16B16A16_FLOAT).unwrap();
assert_eq!((c.nan, c.inf, c.n, c.range), (1, 0, 1, None));
assert!(c.to_string().contains("no finite channel"));
}

#[test]
fn a_channel_with_no_finite_value_has_no_mean() {
// 2 x 1 texels of R32G32_FLOAT: (1, NaN), (3, +inf): red has a mean, green has none
let data: Vec<u8> = [1.0f32, f32::NAN, 3.0, f32::INFINITY].iter().flat_map(|v| v.to_le_bytes()).collect();
let c = float_census(&data, 2, 1, 16, DXGI_FORMAT_R32G32_FLOAT).unwrap();
assert_eq!((c.nan, c.inf, c.n), (1, 1, 2));
assert_eq!(c.range, Some((1.0, 3.0)));
assert_eq!(c.mean, vec![Some(2.0), None]);
let line = c.to_string();
assert!(line.contains("finite channels from 1e0 to 3e0, mean [2.0000e0, n/a]"), "{line}");
}

#[test]
fn a_large_float_target_is_sampled_as_the_dumps_are() {
// 128 x 64 texels of R32_FLOAT (more than `FLOATS_ALL`): every 4th of every 4th row
let (w, h) = (128usize, 64usize);
let data: Vec<u8> = (0..w * h).flat_map(|k| (k as f32).to_le_bytes()).collect();
let c = float_census(&data, w, h, w * 4, DXGI_FORMAT_R32_FLOAT).unwrap();
assert_eq!(c.n, (w / 4 * h / 4) as u64);
assert_eq!(c.first, vec![vec![0.0], vec![4.0], vec![8.0], vec![12.0]]);
assert_eq!(c.range, Some((0.0, ((h - 4) * w + w - 4) as f32)));
// 64 x 64 (`FLOATS_ALL` texels): all of them
let c = float_census(&data, 64, 64, 64 * 4, DXGI_FORMAT_R32_FLOAT).unwrap();
assert_eq!(c.n, 4096);
}

#[test]
fn the_census_stops_at_the_end_of_the_buffer() {
// 8 x 8 of D32S8X24 (8 bytes), a 256-byte pitch, but the buffer ends in the last row
Expand Down
Loading