Procházet zdrojové kódy

Merge Merge local/next

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local před 2 dny
rodič
revize
4a8244cea7

+ 59 - 0
apps/victory/src/replay.rs

@@ -136,6 +136,35 @@ pub(crate) struct Replay {
     /// Only write the frame's buffers and the commands of these lists (`3..7`).
     #[arg(long)]
     listing: Option<String>,
+    /// Only write what the dispatches of these lists have bound (`3..7`).
+    #[arg(long)]
+    flow: Option<String>,
+    /// With --flow: draws too.
+    #[arg(long)]
+    flow_draws: bool,
+    /// With --flow: heap slots shown from each place named.
+    #[arg(long, default_value_t = 40)]
+    flow_slots: u32,
+    /// Run the frame once and save textures as pictures in this folder, with
+    /// what values they hold (see --texture, --until).
+    #[arg(long)]
+    images: Option<PathBuf>,
+    /// With --images: `<resource>[.<subresource>]` (repeatable); none: all
+    /// that the frame's shaders write.
+    #[arg(long)]
+    texture: Vec<String>,
+    /// With --images and no --texture: from this many texels on.
+    #[arg(long, default_value_t = 4096)]
+    least: u64,
+    /// With --images: the widest picture.
+    #[arg(long, default_value_t = 960)]
+    width: u32,
+    /// With --images: the values too.
+    #[arg(long)]
+    raw: bool,
+    /// The last command that runs, `<list>:<command>`; after it only barriers.
+    #[arg(long)]
+    until: Option<String>,
     /// Say which commands change the pixel: `<x>,<y>` of the presented
     /// picture, or `<resource>[.<subresource>]:<x>,<y>` of a texture
     /// (repeatable). With --lists, only those are looked into.
@@ -186,6 +215,18 @@ pub(crate) fn run(r: Replay) -> Result<()> {
         let lists = range(text).with_context(|| format!("--listing {text}"))?;
         return play::listing(&r.folder, lists, &mut |line| println!("{line}"));
     }
+    if let Some(text) = &r.flow {
+        let lists = range(text).with_context(|| format!("--flow {text}"))?;
+        return play::look::flow(&r.folder, lists, r.flow_draws, r.flow_slots, &mut |line| println!("{line}"));
+    }
+    let until = match &r.until {
+        Some(text) => Some(
+            text.split_once(':')
+                .and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?)))
+                .with_context(|| format!("--until {text}: not <list>:<command>"))?,
+        ),
+        None => None,
+    };
     let only = match &r.only {
         Some(text) => Some(
             range(text)
@@ -215,6 +256,7 @@ pub(crate) fn run(r: Replay) -> Result<()> {
         wait_all: r.wait_all,
         wait_lists: r.wait_lists,
         only,
+        until,
         skip_shaders: r.skip_shader,
         compare: r.compare,
         debug: r.debug_layer,
@@ -227,6 +269,23 @@ pub(crate) fn run(r: Replay) -> Result<()> {
         let player = play::Player::load(&r.folder, &options)?;
         return player.slots(list, command, &mut |line| println!("{line}"));
     }
+    if let Some(folder) = &r.images {
+        let mut which = Vec::new();
+        for text in &r.texture {
+            let (id, sub) = text.split_once('.').unwrap_or((text, "0"));
+            let bad = || format!("--texture {text}");
+            which.push((id.parse().with_context(bad)?, sub.parse().with_context(bad)?));
+        }
+        let images = play::look::Images {
+            which,
+            least: r.least,
+            folder: folder.clone(),
+            width: r.width,
+            raw: r.raw,
+        };
+        let mut player = play::Player::load(&r.folder, &options)?;
+        return player.images(&options, &images, &mut |line| println!("{line}"));
+    }
     if !r.pixel.is_empty() {
         let mut player = play::Player::load(&r.folder, &options)?;
         let mut pixels = play::pixel::Pixels {

+ 3 - 1
apps/victory/src/shader.rs

@@ -169,7 +169,9 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
                     None => "no parsable DXIL program".to_owned(),
                 } + &native;
                 if verbose {
-                    println!("{}{}: {line}", path.display(), source.label());
+                    // As a run's log and a replay name it (`hash=`).
+                    let hash = blake3::hash(&bytes).to_hex();
+                    println!("{}{} #{}: {line}", path.display(), source.label(), &hash[..16]);
                     for l in &listing {
                         println!("{l}");
                     }

+ 14 - 0
crates/victory-gpu/src/descriptor/host.rs

@@ -1653,6 +1653,20 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
     ))
 }
 
+/// The address a shader finds in a descriptor of title memory: where a
+/// buffer view starts, or the ray-tracing structure of a structure's view
+/// (no resource: the view's description holds the address, and the shader
+/// walks the structure from there itself).
+pub(crate) fn view_address(view: &View) -> Option<u64> {
+    const STRUCTURE: u32 = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32;
+    match view {
+        View::Shader(_, Some(desc)) if desc[1] == STRUCTURE => {
+            Some(u64::from(desc[4]) | u64::from(desc[5]) << 32)
+        }
+        _ => buffer_range(view).map(|range| range.0),
+    }
+}
+
 /// The title memory the host slot of buffer view `view` is made on
 /// (address, bytes): the whole buffer the view is of, which is what
 /// [`make`] finds the host copy by. [`buffer_range`] is the part of it the

+ 40 - 11
crates/victory-gpu/src/draw.rs

@@ -960,15 +960,17 @@ impl State {
             once!(kind, "a shader reads a host value this build does not know");
             return 0;
         }
-        // The title address of the buffer view at that dword of the table.
-        let address = match self.roots_ref(compute).get(usize::from(slot)) {
-            Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4)
-                .and_then(|view| crate::descriptor::host::buffer_range(&view))
-                .map_or(0, |range| range.0),
-            _ => 0,
-        };
+        let address = self.view_address(compute, slot, dword);
         if address == 0 {
-            once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0");
+            // The first few say what lies there instead.
+            static SAID: AtomicU64 = AtomicU64::new(0);
+            if SAID.fetch_add(1, Ordering::Relaxed) < 8 {
+                let view = match self.roots_ref(compute).get(usize::from(slot)) {
+                    Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4),
+                    _ => None,
+                };
+                tracing::warn!(slot, dword, ?view, "a shader takes the address of a buffer view that is not there: it reads 0");
+            }
         }
         if kind == USER_VIEW_ADDRESS {
             address as u32
@@ -977,10 +979,29 @@ impl State {
         }
     }
 
+    /// The title address the view at dword `dword` of the table in root
+    /// slot `slot` starts at, 0 without one.
+    fn view_address(&self, compute: bool, slot: u8, dword: u32) -> u64 {
+        match self.roots_ref(compute).get(usize::from(slot)) {
+            Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4)
+                .and_then(|view| crate::descriptor::host::view_address(&view))
+                .unwrap_or(0),
+            _ => 0,
+        }
+    }
+
     /// For a shader that reads title memory by address
     /// ([`crate::memory`]): its directory, fault notes and view slots,
-    /// with the pages of the root views the list has set made ready.
-    fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option<crate::memory::Ready> {
+    /// with the pages made ready of the root views the list has set and of
+    /// the views whose addresses it takes (`t`: the ray-tracing structures
+    /// it walks).
+    fn memory_ready(
+        &self,
+        list: &HostList,
+        t: &crate::pipeline::Translated,
+        compute: bool,
+        writes: bool,
+    ) -> Option<crate::memory::Ready> {
         let heap = match self.heaps[0] {
             0 => None,
             h => crate::descriptor::heap(h as This).host(),
@@ -993,6 +1014,11 @@ impl State {
                 _ => {}
             }
         }
+        for u in &t.host.user_data {
+            if u.root == RootType::Other(victory_shader::emit::USER_VIEW_ADDRESS) {
+                addresses.push(self.view_address(compute, u.slot, u.dword));
+            }
+        }
         crate::memory::ready(list, heap, &addresses, &constants, writes)
     }
 
@@ -1179,7 +1205,10 @@ impl State {
                 && !crate::pipeline::builder_quarantined(self.pipeline as This);
             // Title memory by address: what the shader finds it by.
             let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) {
-                let Some(ready) = self.memory_ready(list, compute, writes) else {
+                // Only through a store by address: what it stores through
+                // views is declared with them.
+                let writes = writes && t.stores_by_address;
+                let Some(ready) = self.memory_ready(list, &t, compute, writes) else {
                     once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped");
                     return false;
                 };

+ 34 - 7
crates/victory-gpu/src/list.rs

@@ -1396,16 +1396,43 @@ extern "system" fn set_pipeline(this: This, pipeline: This) {
 }
 
 /// Pipeline syncs: waits for earlier work and cache flushes, at the top or
-/// bottom of the pipe `(flags, control, address, size)`. Host lists order
-/// their own work and every submission is waited for, so there is nothing
-/// to do.
+/// bottom of the pipe `(flags, control, address, size)`. The host orders
+/// nothing between dispatches by itself: what shaders wrote is waited for
+/// here as at the title's barriers (the ray-tracing structure builder has
+/// no other wait between its stages).
 /// (Arguments may be what earlier shaders wrote from here on:
 /// `State::synced`.)
-extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) {
+extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size: u64) {
     #[cfg(windows)]
-    with_state(this, |_, state| state.synced());
-    #[cfg(not(windows))]
-    let _ = this;
+    {
+        with_state(this, |_, state| state.synced());
+        if let Some(list) = host_list(this) {
+            use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
+            #[cfg(feature = "diagnostics")]
+            {
+                // The shapes of the title's calls, each once.
+                static SEEN: std::sync::Mutex<Vec<(u32, u32, bool)>> = std::sync::Mutex::new(Vec::new());
+                let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
+                let shape = (flags, control, address == 0);
+                if seen.len() < 64 && !seen.contains(&shape) {
+                    seen.push(shape);
+                    tracing::info!(
+                        flags = format_args!("{flags:#x}"),
+                        control = format_args!("{control:#x}"),
+                        address = format_args!("{address:#x}"),
+                        size = format_args!("{size:#x}"),
+                        "a pipeline sync"
+                    );
+                }
+                crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
+            }
+            // SAFETY: the same layout; no resource named.
+            let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
+            // SAFETY: an open list.
+            unsafe { list.list.ResourceBarrier(&[barrier]) };
+        }
+    }
+    let _ = (this, flags, control, address, size);
 }
 
 /// Reset with console flags `(allocator, pipeline, flags)`; the flags only

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

@@ -126,6 +126,8 @@ pub(crate) struct Translated {
     /// Whether the shader's code can store to buffer memory ([`stores`]);
     /// true when its code is not known.
     pub(crate) stores: bool,
+    /// Whether it can store through raw addresses ([`stores_by_address`]).
+    pub(crate) stores_by_address: bool,
     /// Whether it stores through a view it picks from the heap by an index,
     /// once asked (`crate::picked`).
     pub(crate) picks: std::sync::atomic::AtomicU8,
@@ -198,6 +200,7 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
     };
     let host = crate::shader_cache::host_shader(container)?;
     let stores = programs.is_empty() || programs.iter().any(stores);
+    let stores_by_address = programs.is_empty() || programs.iter().any(stores_by_address);
     let used = programs
         .into_iter()
         .find(|p| {
@@ -212,6 +215,7 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
         host,
         used,
         stores,
+        stores_by_address,
         picks: Default::default(),
     })
 }
@@ -360,6 +364,23 @@ fn stores(program: &victory_shader::NativeProgram) -> bool {
     })
 }
 
+/// Whether a console program can store to memory through raw addresses
+/// (`crate::memory`): a flat or global store or atomic, or code that does
+/// not decode. The programs that only walk ray-tracing structures do not,
+/// whatever they store through views.
+#[cfg(windows)]
+fn stores_by_address(program: &victory_shader::NativeProgram) -> bool {
+    use victory_shader::gfx10::{Encoding, decode};
+    let Ok(code) = decode(&program.code) else {
+        return true;
+    };
+    code.iter().any(|i| {
+        matches!(i.encoding, Encoding::Flat | Encoding::Global)
+            && i.name()
+                .is_none_or(|n| (n.contains("store") || n.contains("atomic")) && !n.contains("scratch"))
+    })
+}
+
 #[repr(C)]
 struct Pipeline {
     object: Object,

+ 11 - 0
crates/victory-gpu/src/replay/play.rs

@@ -30,6 +30,7 @@ use super::wire::{
 };
 
 pub mod diverge;
+pub mod look;
 mod merge;
 pub mod pixel;
 mod upcopies;
@@ -85,6 +86,8 @@ pub struct Options {
     pub wait_lists: bool,
     /// Run only these lists (by their place in the frame).
     pub only: Option<(u32, u32)>,
+    /// The last command that runs (list, command); after it only barriers.
+    pub until: Option<(u32, usize)>,
     /// Skip what runs a pipeline whose name or shader hash has one of
     /// these in it.
     pub skip_shaders: Vec<String>,
@@ -114,6 +117,7 @@ impl Default for Options {
             wait_all: false,
             wait_lists: false,
             only: None,
+            until: None,
             skip_shaders: Vec::new(),
             compare: false,
             debug: false,
@@ -1929,6 +1933,13 @@ impl Player {
                     lists.push(edit::barriers_only(cmds));
                     continue;
                 }
+                if let Some((list, command)) = o.until
+                    && here >= list
+                {
+                    let from = if here > list { 0 } else { (command + 1).min(cmds.len()) };
+                    let rest = cmds.split_off(from);
+                    cmds.extend(edit::barriers_only(rest));
+                }
                 if o.skip_clamps
                     && let Some(c) = clamps.get(here as usize)
                 {

+ 445 - 0
crates/victory-gpu/src/replay/play/look.rs

@@ -0,0 +1,445 @@
+//! What the passes of a frame read and write, and what textures hold after a
+//! command: `--flow` and `--images`.
+
+use super::*;
+
+/// The bytes of a view's description as words.
+fn word(s: &Slot, i: usize) -> u32 {
+    u32::from_le_bytes([s.desc[i * 4], s.desc[i * 4 + 1], s.desc[i * 4 + 2], s.desc[i * 4 + 3]])
+}
+
+/// A heap slot, where a frame's resources are known by their numbers only.
+fn slot_text(s: &Slot, called: &dyn Fn(u32) -> String) -> String {
+    let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"]
+        .get(s.kind as usize)
+        .copied()
+        .unwrap_or("?");
+    let res = if s.res == NONE { "null".into() } else { called(s.res) };
+    match s.kind {
+        slot::EMPTY => "never written".into(),
+        slot::CBV => format!("cbv {res} +{:#x} size {:#x}", s.address(), word(s, 2)),
+        slot::SAMPLER => format!(
+            "sampler filter {:#x} address {} {} {} bias {} compare {} lod {}..{}",
+            word(s, 0),
+            word(s, 1),
+            word(s, 2),
+            word(s, 3),
+            f32::from_bits(word(s, 4)),
+            word(s, 6),
+            f32::from_bits(word(s, 11)),
+            f32::from_bits(word(s, 12)),
+        ),
+        _ if s.described == 0 => format!("{kind} of all: {res}"),
+        slot::SRV if word(s, 1) == 1 => format!(
+            "srv f{} first {} count {} stride {} flags {}: {res}",
+            word(s, 0),
+            word(s, 4),
+            word(s, 6),
+            word(s, 7),
+            word(s, 8)
+        ),
+        slot::UAV if word(s, 1) == 1 => format!(
+            "uav f{} first {} count {} stride {} flags {}: {res}",
+            word(s, 0),
+            word(s, 2),
+            word(s, 4),
+            word(s, 5),
+            word(s, 8)
+        ),
+        slot::SRV => format!(
+            "srv f{} dim {} [{} {} {} {} {}]: {res}",
+            word(s, 0),
+            word(s, 1),
+            word(s, 4),
+            word(s, 5),
+            word(s, 6),
+            word(s, 7),
+            word(s, 8)
+        ),
+        _ => format!(
+            "{kind} f{} dim {} [{} {} {} {}]: {res}",
+            word(s, 0),
+            word(s, 1),
+            word(s, 2),
+            word(s, 3),
+            word(s, 4),
+            word(s, 5)
+        ),
+    }
+}
+
+/// What the lists' dispatches (with `draws`: draws too) have bound: pipeline,
+/// root arguments, and what lies in the heap where a root constant that is a
+/// place in it (32 bytes a slot) leads, `most` slots of each. Read from the
+/// capture alone; no device is made.
+pub fn flow(
+    folder: &Path,
+    lists: (u32, u32),
+    draws: bool,
+    most: u32,
+    line: &mut dyn FnMut(&str),
+) -> Result<()> {
+    let frame = Frame::read(&find(folder)?.join("frame.bin"))?;
+    let pipelines: HashMap<u32, &wire::Pipeline> = frame.pipelines.iter().map(|p| (p.id, p)).collect();
+    let resources: HashMap<u32, &wire::Resource> = frame.resources.iter().map(|r| (r.id, r)).collect();
+    let called = |id: u32| match resources.get(&id) {
+        None => format!("#{id} (not there)"),
+        Some(r) if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 => {
+            format!("#{id} '{}' buffer {:#x}", r.name, r.desc.width)
+        }
+        Some(r) => format!(
+            "#{id} '{}' {}x{}x{} m{} f{}",
+            r.name, r.desc.width, r.desc.height, r.desc.depth, r.desc.mips, r.desc.format
+        ),
+    };
+    let heaps: HashMap<u32, &wire::DescriptorHeap> =
+        frame.descriptor_heaps.iter().map(|h| (h.id, h)).collect();
+    let mut late: HashMap<(u32, u32), Slot> = HashMap::new();
+    let mut place = 0;
+    for (i, s) in frame.submits.iter().enumerate() {
+        for (heap, at, slot) in &s.views {
+            late.insert((*heap, *at), *slot);
+        }
+        let slot_at = |heap: u32, at: u32| -> Slot {
+            if let Some(s) = late.get(&(heap, at)) {
+                return *s;
+            }
+            let Some(h) = heaps.get(&heap) else {
+                return Slot::EMPTY;
+            };
+            let after = h.runs.partition_point(|r| r.0 <= at);
+            match after.checked_sub(1).map(|n| &h.runs[n]) {
+                Some((first, count, slot)) if at - first < *count => *slot,
+                _ => Slot::EMPTY,
+            }
+        };
+        for &l in s.lists.iter().filter(|&&l| l != MISSING) {
+            let here = place;
+            place += 1;
+            if here < lists.0 || here > lists.1 {
+                continue;
+            }
+            line(&format!("list {here} of submission {i}"));
+            let mut pso = NONE;
+            let mut compute = false;
+            let mut heap = NONE;
+            let mut binds: BTreeMap<(bool, u32), (String, Vec<u32>)> = BTreeMap::new();
+            let mut targets = String::new();
+            for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() {
+                match c {
+                    Cmd::Pipeline { pso: p } => {
+                        pso = *p;
+                        compute = pipelines.get(p).is_some_and(|p| {
+                            p.parts.iter().any(|part| {
+                                matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0)
+                            })
+                        });
+                    }
+                    Cmd::RootSignature { graphics, .. } => binds.retain(|k, _| k.0 != *graphics),
+                    Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE),
+                    Cmd::RootView { graphics, kind, param, va } => {
+                        let kind = ["?", "cbv", "srv", "uav"].get(*kind as usize).copied().unwrap_or("?");
+                        let text = match va {
+                            Va::At { res, offset } => format!("{kind} {} +{offset:#x}", called(*res)),
+                            Va::Null {} => format!("{kind} null"),
+                            Va::Unknown { address } => format!("{kind} unknown {address:#x}"),
+                        };
+                        binds.insert((*graphics, *param), (text, Vec::new()));
+                    }
+                    Cmd::Table { graphics, param, heap, slot } => {
+                        binds.insert(
+                            (*graphics, *param),
+                            (format!("table heap {heap} slot {slot}"), Vec::new()),
+                        );
+                    }
+                    Cmd::Constants { graphics, param, offset, values } => {
+                        let (_, all) = binds
+                            .entry((*graphics, *param))
+                            .or_insert_with(|| ("constants".into(), Vec::new()));
+                        let end = *offset as usize + values.len();
+                        if all.len() < end {
+                            all.resize(end, 0);
+                        }
+                        all[*offset as usize..end].copy_from_slice(values);
+                    }
+                    Cmd::Targets { colors, depth } => {
+                        targets = colors
+                            .iter()
+                            .chain(depth)
+                            .map(|s| slot_text(s, &called))
+                            .collect::<Vec<_>>()
+                            .join("; ");
+                    }
+                    Cmd::CopyTexture { .. }
+                    | Cmd::CopyResource { .. }
+                    | Cmd::Resolve { .. }
+                    | Cmd::ClearDepth { .. }
+                    | Cmd::ClearTarget { .. } => line(&format!("{here}:{n} {c:?}")),
+                    c if c.runs_shaders() && (compute || draws) => {
+                        let name = pipelines.get(&pso).map_or("", |p| p.name.as_str());
+                        line(&format!("{here}:{n} {c:?} pso {pso} {name}"));
+                        if !compute {
+                            line(&format!("  targets {targets}"));
+                        }
+                        for ((graphics, param), (text, values)) in &binds {
+                            if *graphics == compute {
+                                continue;
+                            }
+                            if values.is_empty() {
+                                line(&format!("  {param}: {text}"));
+                                continue;
+                            }
+                            line(&format!("  {param}: {text} {values:x?}"));
+                            for (k, v) in values.iter().enumerate() {
+                                if v & 31 != 0
+                                    || v >> 5 < 64
+                                    || heaps.get(&heap).is_none_or(|h| v >> 5 >= h.count)
+                                {
+                                    continue;
+                                }
+                                for m in 0..most {
+                                    let s = slot_at(heap, (v >> 5) + m);
+                                    if s.kind != slot::EMPTY {
+                                        let text = slot_text(&s, &called);
+                                        line(&format!("    [{k}]+{m} slot {}: {text}", (v >> 5) + m));
+                                    }
+                                }
+                            }
+                        }
+                    }
+                    _ => {}
+                }
+            }
+        }
+    }
+    Ok(())
+}
+
+fn half(b: &[u8]) -> f32 {
+    let h = u32::from(u16::from_le_bytes([b[0], b[1]]));
+    small(h & 0x7fff, 10) * if h >> 15 == 1 { -1.0 } else { 1.0 }
+}
+
+/// A float of five exponent bits and `bits` of mantissa.
+fn small(v: u32, bits: u32) -> f32 {
+    let m = (v & ((1 << bits) - 1)) as f32 / (1u32 << bits) as f32;
+    match v >> bits & 31 {
+        0 => m * 2f32.powi(-14),
+        31 if m > 0.0 => f32::NAN,
+        31 => f32::INFINITY,
+        e => (1.0 + m) * 2f32.powi(e as i32 - 15),
+    }
+}
+
+/// Bytes of a texel that [`texel`] knows.
+fn texel_bytes(format: i32) -> Option<usize> {
+    Some(match format {
+        1..=4 => 16,
+        5..=8 => 12,
+        9..=22 => 8,
+        23..=47 | 67 | 87..=93 => 4,
+        48..=59 => 2,
+        60..=65 => 1,
+        _ => return None,
+    })
+}
+
+/// A texel as numbers (typeless formats as their usual ones; R32 as a
+/// number as R9G9B9E5, which is what it mostly stands for).
+fn texel(format: i32, b: &[u8]) -> [f32; 4] {
+    let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
+    let f32_at = |i: usize| f32::from_bits(u32_at(i));
+    let u16_at = |i: usize| f32::from(u16::from_le_bytes([b[i], b[i + 1]]));
+    let u8_at = |i: usize| f32::from(b[i]);
+    match format {
+        1 | 2 => [f32_at(0), f32_at(4), f32_at(8), f32_at(12)],
+        3 | 4 => [u32_at(0) as f32, u32_at(4) as f32, u32_at(8) as f32, u32_at(12) as f32],
+        5..=8 => [f32_at(0), f32_at(4), f32_at(8), 1.0],
+        9 | 10 => [half(b), half(&b[2..]), half(&b[4..]), half(&b[6..])],
+        11 => [0, 2, 4, 6].map(|i| u16_at(i) / 65535.0),
+        12..=14 => [0, 2, 4, 6].map(u16_at),
+        15 | 16 => [f32_at(0), f32_at(4), 0.0, 1.0],
+        17 | 18 => [u32_at(0) as f32, u32_at(4) as f32, 0.0, 1.0],
+        19..=22 => [f32_at(0), (u32_at(4) & 255) as f32, 0.0, 1.0],
+        23..=25 => {
+            let v = u32_at(0);
+            [
+                (v & 1023) as f32 / 1023.0,
+                (v >> 10 & 1023) as f32 / 1023.0,
+                (v >> 20 & 1023) as f32 / 1023.0,
+                (v >> 30) as f32 / 3.0,
+            ]
+        }
+        26 => {
+            let v = u32_at(0);
+            [small(v & 2047, 6), small(v >> 11 & 2047, 6), small(v >> 22, 5), 1.0]
+        }
+        27..=29 | 31 | 87..=93 => [0, 1, 2, 3].map(|i| u8_at(i) / 255.0),
+        30 | 32 => [0, 1, 2, 3].map(u8_at),
+        33 | 34 => [half(b), half(&b[2..]), 0.0, 1.0],
+        35 => [u16_at(0) / 65535.0, u16_at(2) / 65535.0, 0.0, 1.0],
+        36..=38 => [u16_at(0), u16_at(2), 0.0, 1.0],
+        39..=41 => [f32_at(0); 4],
+        42 | 43 | 67 => {
+            let v = u32_at(0);
+            let scale = 2f32.powi((v >> 27) as i32 - 24);
+            [(v & 511) as f32 * scale, (v >> 9 & 511) as f32 * scale, (v >> 18 & 511) as f32 * scale, 1.0]
+        }
+        44..=47 => [(u32_at(0) & 0xff_ffff) as f32 / 16_777_215.0; 4],
+        48 | 49 => [u8_at(0) / 255.0, u8_at(1) / 255.0, 0.0, 1.0],
+        50..=52 => [u8_at(0), u8_at(1), 0.0, 1.0],
+        53 | 54 => [half(b); 4],
+        55 | 56 => [u16_at(0) / 65535.0; 4],
+        57..=59 => [u16_at(0); 4],
+        60 | 61 | 65 => [u8_at(0) / 255.0; 4],
+        62..=64 => [u8_at(0); 4],
+        _ => [0.0; 4],
+    }
+}
+
+/// Which textures to save, and how.
+#[derive(Clone, Debug, Default)]
+pub struct Images {
+    /// Resource and subresource; of none: all textures the frame's shaders
+    /// write, from this many texels on.
+    pub which: Vec<(u32, u32)>,
+    pub least: u64,
+    pub folder: PathBuf,
+    /// The widest picture.
+    pub width: u32,
+    /// The values too (`.bin`: rows of texels without padding).
+    pub raw: bool,
+}
+
+impl Player {
+    /// Runs the frame once as the options say (`until` ends it early) and
+    /// saves what textures hold, with their least, mean and greatest values.
+    pub fn images(&mut self, o: &Options, images: &Images, say: &mut dyn FnMut(String)) -> Result<()> {
+        let mut made = self.prepare(o)?;
+        self.once(o, &mut made)?;
+        drop(made);
+        let mut which = images.which.clone();
+        if which.is_empty() {
+            let texels = |r: &wire::Resource| r.desc.width * u64::from(r.desc.height) * u64::from(r.desc.depth);
+            which = self
+                .frame
+                .resources
+                .iter()
+                .filter(|r| {
+                    r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0
+                        && self.card_writes.contains(&r.id)
+                        && texels(r) >= images.least
+                })
+                .map(|r| (r.id, 0))
+                .collect();
+        }
+        std::fs::create_dir_all(&images.folder)?;
+        for (id, sub) in which {
+            let Some(at) = self.objects.get(&id).map(|o| o.index) else {
+                say(format!("{id}: not there"));
+                continue;
+            };
+            let r = &self.frame.resources[at];
+            if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 || r.desc.samples[0] > 1 {
+                say(format!("{id}: a buffer or multisampled"));
+                continue;
+            }
+            let (name, own) = (r.name.clone(), r.desc.format);
+            let (f, _) = gpu::footprints(&self.device, &gpu::to_desc(&r.desc), sub, 1);
+            let f = f[0].Footprint;
+            let called = self.called(id);
+            // The planes of depth formats come back as these.
+            let format = if matches!(f.Format.0, 39 | 53 | 60) { f.Format.0 } else { own };
+            let Some(bytes) = texel_bytes(format) else {
+                say(format!("{called}.{sub}: format {format} is not shown"));
+                continue;
+            };
+            let Some(all) = self.contents_of(id, sub)? else {
+                continue;
+            };
+            let (mut least, mut most, mut sum) = ([f32::INFINITY; 4], [f32::NEG_INFINITY; 4], [0f64; 4]);
+            let (mut zero, mut bad, mut n) = (0u64, 0u64, 0u64);
+            let slice = f.RowPitch as usize * f.Height as usize;
+            let mut raw = Vec::new();
+            for y in 0..f.Height as usize * f.Depth as usize {
+                let from = y * f.RowPitch as usize;
+                let row = &all[from..from + f.Width as usize * bytes];
+                if images.raw {
+                    raw.extend_from_slice(row);
+                }
+                for t in row.chunks_exact(bytes) {
+                    let v = texel(format, t);
+                    n += 1;
+                    if v.iter().any(|x| !x.is_finite()) {
+                        bad += 1;
+                        continue;
+                    }
+                    zero += u64::from(v[..3] == [0.0; 3]);
+                    for c in 0..4 {
+                        least[c] = least[c].min(v[c]);
+                        most[c] = most[c].max(v[c]);
+                        sum[c] += f64::from(v[c]);
+                    }
+                }
+            }
+            let mean = sum.map(|s| s / (n - bad).max(1) as f64);
+            say(format!(
+                "{called}.{sub}: {}x{}x{} least {least:.4?} mean {mean:.4?} greatest {most:.4?}, {:.1}% zero, {bad} not numbers",
+                f.Width,
+                f.Height,
+                f.Depth,
+                zero as f64 * 100.0 / n.max(1) as f64,
+            ));
+            let stem: String = name
+                .chars()
+                .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
+                .take(40)
+                .collect();
+            let file = |end: String| images.folder.join(format!("{id:05}.{sub}_{stem}{end}"));
+            if images.raw {
+                std::fs::write(file(format!("_f{format}_{}x{}x{}.bin", f.Width, f.Height, f.Depth)), &raw)?;
+            }
+            // Values from 0 to 1 as they are, others bent so that the mean
+            // is a middle grey. Slices of a 3D texture beside each other.
+            let unit = most[..3].iter().all(|&m| m <= 1.0) && least[..3].iter().all(|&m| m >= 0.0);
+            let grey = ((mean[0] + mean[1] + mean[2]) / 3.0).max(1e-9) as f32;
+            let slices = f.Depth.clamp(1, 16);
+            let step = (f.Width * slices).div_ceil(images.width.max(64)).max(1);
+            let (w, h) = ((f.Width / step).max(1), (f.Height / step).max(1));
+            let mut rgb = Vec::with_capacity((w * slices * h * 3) as usize);
+            for y in 0..h as usize {
+                for s in 0..slices as usize {
+                    let z = s * f.Depth as usize / slices as usize;
+                    for x in 0..w as usize {
+                        let from = z * slice + y * step as usize * f.RowPitch as usize + x * step as usize * bytes;
+                        let v = texel(format, &all[from..from + bytes]);
+                        for c in &v[..3] {
+                            let c = match c.max(0.0) {
+                                _ if c.is_nan() => 1.0,
+                                c if unit => c,
+                                c => c / (c + grey),
+                            };
+                            rgb.push((c.clamp(0.0, 1.0).powf(1.0 / 2.2) * 255.0) as u8);
+                        }
+                    }
+                }
+            }
+            std::fs::write(file(".png".into()), crate::capture::png(w * slices, h, &rgb))?;
+        }
+        Ok(())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn texels() {
+        assert_eq!(texel(10, &[0, 0x3c, 0, 0xc0, 0, 0, 0, 0x38]), [1.0, -2.0, 0.0, 0.5]);
+        assert_eq!(texel(26, &(15u32 << 6 | 16 << 17 | 14 << 27).to_le_bytes()), [1.0, 2.0, 0.5, 1.0]);
+        assert_eq!(texel(67, &(16u32 << 27 | 256).to_le_bytes()), [1.0, 0.0, 0.0, 1.0]);
+        assert_eq!(texel(24, &(1023u32 << 10).to_le_bytes()), [0.0, 1.0, 0.0, 0.0]);
+        assert!(texel(54, &[1, 0x7c])[0].is_nan());
+    }
+}

+ 3 - 0
docs/replay.md

@@ -121,6 +121,9 @@ report counts them). `--no-merge` runs the copies as recorded.
 | `--slots <list>:<command>` | the heap slots its constants name |
 | `--check-written` | that everything the frame changes is put back |
 | `--upcopies` | runs the frame twice: which words the copies of the CPU's sides of card buffers bring that the card holds another value of (those the card wrote alike in both runs are the ones to look at), and which pieces shaders wrote that were not declared as written. The live check is `VICTORY_UPCOPY_CHECK=1` (`host/upcheck.rs`) |
+| `--flow <lists>` | what the dispatches (`--flow-draws`: draws too) have bound: pipeline, root arguments, heap slots their constants lead to; no device is made |
+| `--images <folder>` | runs the frame once and saves the textures its shaders write (or `--texture <id>[.<sub>]`, repeatable) as pictures, with least, mean and greatest values; `--raw`: the values too |
+| `--until <list>:<command>` | nothing but barriers after that command |
 | `--dump <text>` | the DXIL of the pipelines named, in `shaders` |
 
 The `--diverge` family runs the recorded copies without the merge.