Selaa lähdekoodia

Argument clamps in batches (VICTORY_INDIRECT_BATCH)

One pass clamps the arguments of all indirect executions between two
points where they may change; its jobs are in upload memory that is filled
while the list is recorded. The replayed frame: 2,355 clamps become 980
passes, 86.1 -> 77.7 ms; with VICTORY_INDIRECT_BATCH=2 133 passes,
84.6 -> 75.3 ms.

Replay: --batch-clamps, --only-buffers, --listing; --compare runs turn by
turn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 1 päivä sitten
vanhempi
sitoutus
037596241a

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

@@ -53,12 +53,21 @@ pub(crate) struct Replay {
     /// Leave out the argument clamps: what they bound is kept from a first run.
     #[arg(long)]
     skip_clamps: bool,
+    /// The argument clamps in batches, as VICTORY_INDIRECT_BATCH does (2:
+    /// a wait before every indirect dispatch).
+    #[arg(long, num_args = 0..=1, default_missing_value = "1", default_value_t = 0)]
+    batch_clamps: u32,
     /// Leave out the hash and compare passes over card buffers.
     #[arg(long)]
     skip_hash_passes: bool,
     /// Where buffers lie.
     #[arg(long, value_enum, default_value_t = Buffers::AsRecorded)]
     buffers: Buffers,
+    /// With --buffers, only the buffers all of these match: `name=<text>`,
+    /// `min=<bytes>`, `max=<bytes>`, `seen=<No, Cached, Combined>`,
+    /// `id=<a>..<b>`, or `!` and one of those (may be given several times).
+    #[arg(long)]
+    only_buffers: Vec<String>,
     /// One ExecuteCommandLists for the whole frame.
     #[arg(long)]
     one_submit: bool,
@@ -119,6 +128,9 @@ pub(crate) struct Replay {
     /// capture's `shaders` folder.
     #[arg(long)]
     dump: Option<String>,
+    /// Only write the frame's buffers and the commands of these lists (`3..7`).
+    #[arg(long)]
+    listing: Option<String>,
     /// Use the D3D12 debug layer (slow).
     #[arg(long)]
     debug_layer: bool,
@@ -139,6 +151,10 @@ pub(crate) fn run(r: Replay) -> Result<()> {
         }
         return Ok(());
     }
+    if let Some(text) = &r.listing {
+        let lists = range(text).with_context(|| format!("--listing {text}"))?;
+        return play::listing(&r.folder, lists, &mut |line| println!("{line}"));
+    }
     let only = match &r.only {
         Some(text) => Some(
             range(text)
@@ -157,9 +173,11 @@ pub(crate) fn run(r: Replay) -> Result<()> {
             Buffers::Vram => play::Buffers::Card,
             Buffers::Sysmem => play::Buffers::Pc,
         },
+        only_buffers: r.only_buffers,
         no_barriers: r.no_barriers,
         merge_barriers: r.merge_barriers,
         skip_clamps: r.skip_clamps,
+        batch_clamps: r.batch_clamps,
         skip_hash_passes: r.skip_hash_passes,
         one_submit: r.one_submit,
         merge: !r.no_merge,

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

@@ -186,6 +186,67 @@ fn windows() -> bool {
     *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1"))
 }
 
+/// Whether indirect executions of one record are clamped in batches
+/// (`crate::indirect::batch`; `VICTORY_INDIRECT_BATCH=0`: each on its own,
+/// or in windows ([`windows`])).
+///
+/// A frame of gameplay has 4,809 indirect executions (a capture: 3,523 mesh
+/// draws, 948 dispatches, 338 draws), and with the windows still 2,355
+/// clamps: each a dispatch between two full waits, with the scratch buffer
+/// moved twice. The replayed frame's 84.6 ms are 75.3 ms with the clamps in
+/// 133 passes, and 77.7 ms in the 980 of this.
+///
+/// A batch is opened by the first execution after a point where arguments
+/// may have changed, and all executions up to the next such point read
+/// theirs from it, each exactly the record it asks for (windows guess which
+/// are next, and clamp what they do not know). Arguments in buffers change
+/// by dispatches and by draws whose shaders store to buffers; those end the
+/// batch, so the record an execution reads is clamped after all that was
+/// recorded before it, and the pass waits for all of it, exactly as the
+/// clamp of its own did. Between two executions of a batch is no wait of
+/// ours: there is nothing between them to wait for but draws that store to
+/// no buffer.
+///
+/// `VICTORY_INDIRECT_BATCH=2`: a dispatch does not end the batch before the
+/// title waits for it (a barrier, or a pipeline sync) or draws: what a
+/// dispatch writes is not there for a later command without a wait, and
+/// dispatches the title runs side by side (its tile classes, up to 92 at a
+/// time) are not held up by waits of ours. Off: whether the title has ways
+/// to wait that do not pass through its lists' methods is not known.
+fn batches() -> u8 {
+    static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| match std::env::var("VICTORY_INDIRECT_BATCH").as_deref() {
+        Ok("0") => 0,
+        Ok("2") => 2,
+        _ => 1,
+    })
+}
+
+/// The records clamped by the pass opened last ([`batches`]).
+struct Batch {
+    table: crate::indirect::batch::Table,
+    scratch: ID3D12Resource,
+    /// Dispatches since, which may have written arguments
+    /// (`VICTORY_INDIRECT_BATCH=2`).
+    wrote: bool,
+}
+
+/// The host copies arguments were read from last: what a batch opens with,
+/// as the executions after the first may read theirs from another one.
+static ARGUMENT_COPIES: std::sync::Mutex<Vec<std::sync::Weak<crate::shadow::Shadow>>> = std::sync::Mutex::new(Vec::new());
+
+/// [`ARGUMENT_COPIES`] that live, and `first` put in front of them.
+fn argument_copies(first: &std::sync::Arc<crate::shadow::Shadow>) -> Vec<(u64, ID3D12Resource)> {
+    let mut copies = ARGUMENT_COPIES.lock().unwrap_or_else(|e| e.into_inner());
+    let live: Vec<_> = copies.iter().filter_map(std::sync::Weak::upgrade).filter(|s| s.id() != first.id()).collect();
+    *copies = std::iter::once(first)
+        .chain(&live)
+        .take(crate::indirect::batch::SOURCES)
+        .map(std::sync::Arc::downgrade)
+        .collect();
+    live.iter().map(|s| (s.id(), s.buffer.clone())).collect()
+}
+
 /// What one title list has set, and what its host list was last given.
 #[derive(Default)]
 pub(crate) struct State {
@@ -219,6 +280,9 @@ pub(crate) struct State {
     /// The indirect records clamped last, if later draws may still read
     /// them ([`windows`]).
     window: Option<Window>,
+    /// The records clamped in a batch, if later executions may still read
+    /// them ([`batches`]).
+    batch: Option<Batch>,
     /// What the host list has: pipeline, root signature, heaps.
     host_pipeline: usize,
     /// Graphics, compute.
@@ -2031,6 +2095,7 @@ impl State {
         list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
         // SAFETY: an open list with everything set.
         unsafe { list.list.Dispatch(x, y, z) };
+        self.buffers_written();
         DISPATCHED.fetch_add(1, Ordering::Relaxed);
     }
 
@@ -2301,6 +2366,7 @@ impl State {
                     self.mesh_scissor(list, true);
                     // SAFETY: an open list with everything set.
                     unsafe { l6.DispatchMesh(x, 1, 1) };
+                    self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
                     self.mesh_scissor(list, false);
                     DRAWN.fetch_add(1, Ordering::Relaxed);
                     true
@@ -2702,6 +2768,7 @@ impl State {
                 list.list
                     .DrawInstanced(count, instances, from, first_instance)
             };
+            self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
             DRAWN.fetch_add(1, Ordering::Relaxed);
         }
         if !ran {
@@ -2803,6 +2870,7 @@ impl State {
                 list.list
                     .DrawIndexedInstanced(indices, instances, first, base, first_instance)
             };
+            self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
             DRAWN.fetch_add(1, Ordering::Relaxed);
         }
         if !ran {
@@ -2814,6 +2882,65 @@ impl State {
 }
 
 impl State {
+    /// Shaders that can write buffers were recorded: arguments may be others
+    /// from here on.
+    fn buffers_written(&mut self) {
+        match &mut self.batch {
+            Some(batch) if batches() == 2 => batch.wrote = true,
+            batch => *batch = None,
+        }
+    }
+
+    /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`]
+    /// if its shaders can store to buffers).
+    fn drew(&mut self, p: Option<&HostPipeline>) {
+        if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) {
+            self.batch = None;
+        }
+    }
+
+    /// The title waits for earlier work (a barrier or a pipeline sync).
+    pub(crate) fn synced(&mut self) {
+        if self.batch.as_ref().is_some_and(|b| b.wrote) {
+            self.batch = None;
+        }
+    }
+
+    /// Where the clamped record of `kind` at `arguments` of the copy `args`
+    /// is, from the open batch or a new one ([`batches`]). `None` if it
+    /// cannot be clamped in one.
+    fn batched(
+        &mut self,
+        list: &HostList,
+        args: &std::sync::Arc<crate::shadow::Shadow>,
+        arguments: u64,
+        kind: u32,
+    ) -> Option<(ID3D12Resource, u64)> {
+        const BATCH_USE: usize = usize::MAX - 0x78;
+        const DISPATCH: u32 = 2;
+        // Another host list, or this one after its reset ([`windows`]).
+        if list.first_use(BATCH_USE) {
+            self.batch = None;
+        }
+        // A draw after dispatches waits for them.
+        if kind != DISPATCH {
+            self.synced();
+        }
+        let (id, offset) = (args.id(), args.offset(arguments));
+        if let Some(b) = &mut self.batch
+            && let Some(at) = b.table.place(id, offset, kind)
+        {
+            return Some((b.scratch.clone(), at));
+        }
+        self.batch = None;
+        let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?;
+        self.host_pipeline = 0;
+        self.host_roots[1] = 0;
+        let at = table.place(id, offset, kind)?;
+        self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false });
+        Some((scratch, at))
+    }
+
     /// Indirect execution of a one-argument signature of `kind` (PC
     /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
     /// records `stride` bytes apart at title address `arguments`, and the
@@ -2905,6 +3032,16 @@ impl State {
             why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
             return false;
         }
+        // One record without a count: clamped in a batch (`batches`).
+        let batch = if batches() > 0 && max == 1 && count.is_none() {
+            args.refresh(list, arguments, len);
+            self.batched(list, &args, arguments, kind)
+        } else {
+            None
+        };
+        if batch.is_some() {
+            self.window = None;
+        }
         // A window of records clamped in one pass (`windows`): for single
         // records without a count buffer, drawn by shaders that store to no
         // buffer. Anything else ends the window: it uses the scratch buffer
@@ -2928,7 +3065,7 @@ impl State {
             .filter(|w| same(w) && offset >= w.base)
             .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
             .map(|w| (w.scratch.clone(), offset - w.base));
-        let (bounded, at) = match hit {
+        let (bounded, at) = match batch.or(hit) {
             Some(hit) => hit,
             None => {
                 // A record a short step after the last window's last one
@@ -3018,6 +3155,11 @@ impl State {
         if kind == MESH {
             self.mesh_scissor(list, false);
         }
+        if kind == DISPATCH {
+            self.buffers_written();
+        } else {
+            self.drew(Some(p));
+        }
         // The scratch buffer stays readable as arguments: the next draw of
         // the window reads it with no barrier, and the next clamp moves it
         // back (`crate::indirect`).

+ 46 - 0
crates/victory-gpu/src/host.rs

@@ -767,6 +767,10 @@ mod tests {
     }
 }
 
+/// The batches of clamped records in one scratch buffer
+/// ([`HostList::batch_place`]).
+const BATCHES: u32 = 8;
+
 /// A host command list and its allocator, always used together.
 pub(crate) struct HostList {
     allocator: ID3D12CommandAllocator,
@@ -802,6 +806,9 @@ pub(crate) struct HostList {
     /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
     /// grown to the largest indirect execution recorded on the list.
     indirect_args: Mutex<Option<(ID3D12Resource, u64)>>,
+    /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and
+    /// how many batches of this recording have a place in them.
+    batch_args: Mutex<(Vec<ID3D12Resource>, u32)>,
     /// Counts the list in [`ALIVE`] while it lives.
     _alive: Counted,
     /// The texts of the markers `note_op` set, in order (for device-removed
@@ -3221,6 +3228,7 @@ impl Host {
                 budget: OnceLock::new(),
                 card_budget: OnceLock::new(),
                 indirect_args: Mutex::default(),
+                batch_args: Mutex::default(),
                 _alive: Counted::new(),
                 #[cfg(feature = "diagnostics")]
                 notes: Mutex::default(),
@@ -4873,6 +4881,7 @@ impl HostList {
         if let Some((scratch, _)) = scratch {
             self.indirect_common(&scratch);
         }
+        self.batches_common();
         self.card_budget_out();
         #[cfg(feature = "diagnostics")]
         if let Some((heap, back)) = self.stamps() {
@@ -5594,6 +5603,43 @@ impl HostList {
         Some(buffer)
     }
 
+    /// Where the next batch of clamped records goes: a device-local buffer
+    /// the list keeps from recording to recording, the batch's place in it
+    /// and the state the buffer is in. Every batch of a recording has a place
+    /// of its own: the executions before it may still read theirs.
+    pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> {
+        use crate::indirect::batch::{JOBS, SLOT};
+        let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
+        let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES);
+        if buffer == args.0.len() {
+            let size = u64::from(BATCHES * JOBS * SLOT);
+            let made = host()?.uav_buffer(size)?;
+            name(&made, || format!("indirect batches {size:#x}"));
+            args.0.push(made);
+        }
+        args.1 += 1;
+        // (Its first batch finds it as the recording before left it:
+        // `batches_common`.)
+        let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT };
+        Some((args.0[buffer].clone(), i * JOBS * SLOT, state))
+    }
+
+    /// Before the list closes: the scratch buffers of the batched clamps go
+    /// back to the common state, where the next recording expects them.
+    fn batches_common(&self) {
+        let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner());
+        let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize;
+        let barriers: Vec<D3D12_RESOURCE_BARRIER> = args.0[..used]
+            .iter()
+            .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON))
+            .collect();
+        if !barriers.is_empty() {
+            // SAFETY: an open list and live buffers this recording left in
+            // `INDIRECT_ARGUMENT`.
+            unsafe { self.list.ResourceBarrier(&barriers) };
+        }
+    }
+
     /// Moves `scratch` back to the common state if a clamp left it readable
     /// as indirect arguments ([`HostList::indirect_readable`]): where the
     /// list's first clamp expects it. Done before the list closes and before

+ 382 - 0
crates/victory-gpu/src/indirect.rs

@@ -17,6 +17,10 @@
 //! execution was followed by a move of the scratch buffer back to the
 //! common state, which drivers may treat as a full wait.
 //!
+//! The executions of one record without a count buffer (all the title's)
+//! are clamped in batches ([`batch`], `VICTORY_INDIRECT_BATCH`): the rest of
+//! this is for the others.
+//!
 //! When a count buffer is given, threads at or past `min(max, count)` return
 //! immediately without charging the list's budget or reading uninitialized
 //! tail slots. Each list has a budget (2^27 vertex instances or threads,
@@ -36,6 +40,8 @@ use windows::core::s;
 
 use crate::host::{HostList, host, transition};
 
+pub(crate) mod batch;
+
 const SOURCE: &str = r#"
 #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
 cbuffer Record : register(b0) {
@@ -478,6 +484,70 @@ fn record_clamp_as(
     true
 }
 
+/// The batched clamp's pipeline ([`batch`]).
+fn batch_clamp() -> Option<&'static Clamp> {
+    static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
+    CLAMP
+        .get_or_init(|| {
+            let made = host().ok_or_else(windows::core::Error::empty).and_then(|h| make_from(&h.device, batch::SOURCE));
+            match made {
+                Ok(c) => Some(c),
+                Err(e) => {
+                    tracing::warn!(error = %e, "no batched argument clamp: records are clamped one at a time");
+                    None
+                }
+            }
+        })
+        .as_ref()
+}
+
+/// Opens a batch in `list` ([`batch`]): a pass that clamps the records of
+/// the executions recorded after it, of `source` (a host copy's number and
+/// buffer) and of the `recent` ones after it. The table to add them to,
+/// and the scratch buffer its places are in. Replaces the list's compute
+/// root signature and pipeline (callers bind theirs after). `None` if the
+/// clamp is not available.
+pub(crate) fn open_batch(
+    list: &HostList,
+    source: (u64, &ID3D12Resource),
+    recent: &[(u64, ID3D12Resource)],
+) -> Option<(batch::Table, ID3D12Resource)> {
+    let c = batch_clamp()?;
+    let budget = list.budget()?;
+    let (jobs, at) = list.scratch(batch::TABLE)?;
+    let (dst, base, before) = list.batch_place()?;
+    let gpu = |b: &ID3D12Resource| {
+        // SAFETY: a live buffer.
+        Some(unsafe { b.GetGPUVirtualAddress() }).filter(|at| at.is_multiple_of(4))
+    };
+    // A source there is none of is the first again, which no job names.
+    let mut ids = [0u64; batch::SOURCES];
+    let mut sources = [gpu(source.1)?; batch::SOURCES];
+    ids[0] = source.0;
+    let others = recent.iter().filter(|r| r.0 != source.0).take(batch::SOURCES - 1);
+    for (i, (id, buffer)) in others.enumerate() {
+        if let Some(at) = gpu(buffer) {
+            // Bound, and read only if a job names it: kept alive like the
+            // copies draws read (`Shadow::refresh`).
+            list.keep(buffer);
+            (ids[i + 1], sources[i + 1]) = (*id, at);
+        }
+    }
+    #[cfg(feature = "diagnostics")]
+    crate::copystat::add(crate::copystat::C::IndirectBounded, 1);
+    batch::record(c, &list.list, (&dst, before), budget, sources, jobs);
+    // SAFETY: the list's own upload memory of that many bytes, 256-byte
+    // aligned, until it is reset.
+    Some((unsafe { batch::Table::new(at, base, ids) }, dst))
+}
+
+/// The batched clamp's root signature and pipeline on `device`, for the
+/// replayer.
+#[cfg(feature = "diagnostics")]
+pub(crate) fn batch_for(device: &ID3D12Device) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> {
+    make_from(device, batch::SOURCE).map(|c| (c.root, c.pso))
+}
+
 fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
     D3D12_RESOURCE_BARRIER {
         Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
@@ -1716,6 +1786,318 @@ void main() {
             assert_eq!(hits, expected, "every record of both windows runs once");
         }
     }
+
+    /// A command signature of one argument of `kind` on `device`.
+    fn one_argument(device: &ID3D12Device, kind: u32, stride: u32) -> ID3D12CommandSignature {
+        let arg = D3D12_INDIRECT_ARGUMENT_DESC {
+            Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
+            ..Default::default()
+        };
+        let desc = D3D12_COMMAND_SIGNATURE_DESC {
+            ByteStride: stride,
+            NumArgumentDescs: 1,
+            pArgumentDescs: &arg,
+            NodeMask: 0,
+        };
+        let mut sig: Option<ID3D12CommandSignature> = None;
+        // SAFETY: a valid single-argument command signature description.
+        unsafe {
+            device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap();
+        }
+        sig.unwrap()
+    }
+
+    /// What a batch's table says of records added to it: one job per
+    /// record, charged for every execution that reads it, and none for what
+    /// the pass cannot read.
+    #[test]
+    fn batch_tables() {
+        use batch::{JOBS, SLOT, TABLE, TIMES, Table, job};
+        let mut memory = vec![0xffff_ffffu32; TABLE as usize / 4 + 1];
+        // SAFETY: the vector holds the table and outlives its use.
+        let mut t = unsafe { Table::new(memory.as_mut_ptr().cast(), 4096, [7, 9, 0, 0]) };
+        assert_eq!(t.place(7, 64, 10), Some(4096));
+        assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
+        assert_eq!(t.place(7, 64, 2), Some(4096 + 2 * u64::from(SLOT)), "another kind is another record");
+        // The same record again: the same place, charged twice.
+        assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT)));
+        assert_eq!(&memory[..4], [3, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff]);
+        assert_eq!(memory[4..8], [job(0, 10, 1), 64, 4096, 0]);
+        assert_eq!(memory[8..12], [job(1, 10, 2), 64, 4096 + SLOT, 0]);
+        assert_eq!(job(1, 10, 2), 1 | 10 << 4 | 3 << 8 | 2 << 16);
+        // Not a copy of the pass, not on 4 bytes, past 32 bits, not a kind.
+        for (id, offset, kind) in [(8, 64, 10), (7, 66, 10), (7, 1 << 32, 10), (7, u64::from(u32::MAX) & !3, 10), (7, 64, 3)] {
+            assert_eq!(t.place(id, offset, kind), None);
+        }
+        // Read more often than one job may be charged for: another job.
+        for _ in 1..TIMES {
+            assert_eq!(t.place(7, 64, 10), Some(4096));
+        }
+        assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
+        assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT)));
+        for i in 4..u64::from(JOBS) {
+            assert_eq!(t.place(7, 1024 + 16 * i, 0), Some(4096 + i * u64::from(SLOT)));
+        }
+        assert_eq!(t.place(7, 1024, 1), None, "full");
+        assert_eq!(t.place(7, 1024 + 16 * 5, 0), Some(4096 + 5 * u64::from(SLOT)));
+        assert_eq!((memory[0], memory[TABLE as usize / 4]), (JOBS, 0xffff_ffff));
+    }
+
+    /// A batch clamps records exactly as the clamp of one execution does, of
+    /// any kind, sensible or not; they are added to its table after the pass
+    /// was recorded; it charges each as often as it is read.
+    #[test]
+    fn warp_batch_clamps_as_the_clamp_of_one_does() {
+        let Some(mut warp) = WarpHarness::new() else {
+            return;
+        };
+        let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
+        let kinds = [0u32, 1, 2, 10];
+        let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX];
+        // Every kind with many records, in two sources.
+        let mut records: Vec<(u32, [u32; 5])> = Vec::new();
+        for kind in kinds {
+            for (i, a) in values.into_iter().enumerate() {
+                for (k, b) in values.into_iter().enumerate() {
+                    records.push((kind, [a, b, values[(i * 3 + k) % 4], 77, 0xABCD]));
+                }
+            }
+        }
+        // In passes of so few that the budget holds whatever one asks for,
+        // and one pass of them all, which it does not.
+        let (src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
+        let (_other, other_ptr, other_gpu) = warp.shared_buffer(64 << 10);
+        for (i, (_, words)) in records.iter().enumerate() {
+            for (w, word) in words.iter().enumerate() {
+                // SAFETY: 400 records of 32 bytes in 64 KiB.
+                unsafe {
+                    src_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
+                    other_ptr.cast::<u32>().add(i * 8 + w).write_volatile(*word);
+                }
+            }
+        }
+        let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
+        let (back, back_ptr, _) = warp.shared_buffer(64 << 10);
+        let dst = warp.default_uav(64 << 10);
+        let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
+        for (i, (kind, _)) in records.iter().enumerate().step_by(3) {
+            let offset = i as u64 * 32;
+            let words = batch::words(*kind).unwrap();
+            let stride = words * 4;
+            let read = |p: *mut u8| -> Vec<u32> {
+                // SAFETY: the mapping holds more.
+                (0..words as usize).map(|w| unsafe { p.cast::<u32>().add(w).read_volatile() }).collect()
+            };
+            let mut seen = Vec::new();
+            for batched in [false, true] {
+                // SAFETY: mapped buffers; nothing runs.
+                unsafe { std::ptr::write_bytes(budget_ptr, 0, 256) };
+                if batched {
+                    batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu, other_gpu, src_gpu, src_gpu], table_gpu);
+                    // SAFETY: the mapped table; the list has not run.
+                    let mut table = unsafe { batch::Table::new(table_ptr, 0, [1, 2, 0, 0]) };
+                    assert_eq!(table.place(1 + i as u64 % 2, offset, *kind), Some(0));
+                } else {
+                    assert!(record_clamp_as(
+                        &warp.clamp,
+                        &warp.list,
+                        (&dst, D3D12_RESOURCE_STATE_COMMON),
+                        budget_gpu,
+                        (&src, offset),
+                        None,
+                        (*kind, stride, 1),
+                        false,
+                    ));
+                }
+                // SAFETY: an open list; the records are readable as arguments.
+                unsafe {
+                    warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
+                    warp.list.CopyBufferRegion(&back, 0, &dst, 0, u64::from(stride));
+                    warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]);
+                }
+                warp.submit_and_wait();
+                // SAFETY: the list has run; mapped words.
+                let budget: Vec<u32> = (0..3).map(|k| unsafe { budget_ptr.cast::<u32>().add(k).read_volatile() }).collect();
+                seen.push((read(back_ptr), budget));
+            }
+            // (A mesh record that asks for nothing notes nothing.)
+            assert_eq!(seen[0], seen[1], "record {i} of kind {kind}: {:?}", records[i].1);
+        }
+    }
+
+    /// Records past the list's budget come out empty, and one read by many
+    /// executions is charged for each.
+    #[test]
+    fn warp_batch_charges_every_execution() {
+        let Some(mut warp) = WarpHarness::new() else {
+            return;
+        };
+        let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
+        const BUDGET: u32 = 1 << 27;
+        // 2^26 vertices each, as much as a draw is let run: two fill it.
+        for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] {
+            let (_src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10);
+            let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256);
+            let (back, back_ptr, _) = warp.shared_buffer(1024);
+            let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE);
+            let dst = warp.default_uav(64 << 10);
+            batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu);
+            // SAFETY: mapped buffers, which the list has not read yet.
+            let mut table = unsafe {
+                std::ptr::write_bytes(budget_ptr, 0, 256);
+                for r in 0..records {
+                    for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() {
+                        src_ptr.cast::<u32>().add(r as usize * 4 + w).write_volatile(word);
+                    }
+                }
+                batch::Table::new(table_ptr, 0, [1, 0, 0, 0])
+            };
+            for _ in 0..times {
+                for r in 0..records {
+                    assert_eq!(table.place(1, r * 16, 0), Some(r * u64::from(batch::SLOT)));
+                }
+            }
+            // SAFETY: an open list; the records are readable as arguments.
+            unsafe {
+                warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
+                warp.list.CopyBufferRegion(&back, 0, &dst, 0, 256);
+            }
+            warp.submit_and_wait();
+            // SAFETY: the list has run; mapped words.
+            let (spent, out): (u32, Vec<u32>) = unsafe {
+                (
+                    budget_ptr.cast::<u32>().read_volatile(),
+                    (0..records as usize).map(|r| back_ptr.cast::<u32>().add(r * batch::SLOT as usize / 4).read_volatile()).collect(),
+                )
+            };
+            assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}");
+            assert!(out.iter().all(|&v| v == 0 || v == 1 << 24));
+            assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32));
+        }
+    }
+
+    /// Two batches through a host list, twice (the second recording finds
+    /// the scratch buffer as the first one's end left it): executions with
+    /// nothing between them read what they asked for, of two source buffers,
+    /// the second batch while the first one's places are still read. With
+    /// the debug layer on no barrier names a state the buffer is not in.
+    #[test]
+    fn host_list_batches() {
+        let Some(host) = super::host() else {
+            return;
+        };
+        let _ = host.log_messages();
+        let Ok(list) = host.new_list() else {
+            return;
+        };
+        let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile");
+        let signature = one_argument(&host.device, 2, 12);
+        let mut sources = Vec::new();
+        for first in [1u32, 100] {
+            let Some((buffer, ptr)) = host.shared_buffer(1024) else {
+                return;
+            };
+            for i in 0..16u32 {
+                for (w, word) in [first + i, 1, 1].into_iter().enumerate() {
+                    // SAFETY: inside the mapping.
+                    unsafe { ptr.cast::<u32>().add(i as usize * 8 + w).write_volatile(word) };
+                }
+            }
+            sources.push(buffer);
+        }
+        let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else {
+            return;
+        };
+        // SAFETY: a live buffer.
+        let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() };
+        for _ in 0..2 {
+            // SAFETY: the mapping holds 256 bytes; nothing runs.
+            unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) };
+            let mut expected = 0;
+            // More batches than one scratch buffer holds.
+            for k in 0..12u32 {
+                let (mut table, scratch) =
+                    open_batch(&list, (1, &sources[0]), &[(1, sources[0].clone()), (2, sources[1].clone())]).unwrap();
+                // SAFETY: an open list; the worker's root signature and
+                // pipeline; buffers the test holds until the list has run.
+                unsafe {
+                    list.list.SetComputeRootSignature(&worker.root);
+                    list.list.SetPipelineState(&worker.pso);
+                    list.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
+                }
+                for (id, record) in [(1u64, 3 + k % 4), (2, 5), (1, 0), (2, 5)] {
+                    let at = table.place(id, u64::from(record) * 32, 2).unwrap();
+                    // SAFETY: as above.
+                    unsafe { list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0) };
+                    expected += record + if id == 1 { 1 } else { 100 };
+                }
+            }
+            list.close();
+            assert_eq!(host.log_messages(), None, "the debug layer found an error");
+            host.execute(&[&list]);
+            list.reset();
+            // SAFETY: the list has run; a mapped buffer.
+            let hits = unsafe { (hits_ptr as *const u32).read_volatile() };
+            assert_eq!(hits, expected, "every execution runs what it asked for");
+        }
+    }
+
+    /// What clamps of a frame cost on the card one by one and in batches
+    /// (ignored: a measurement): 2,355 executions of an empty dispatch, in
+    /// 49 lists' worth of runs, as in the captured frame.
+    #[test]
+    #[ignore]
+    fn batch_costs() {
+        let Some(mut gpu) = WarpHarness::on(false) else {
+            return;
+        };
+        const EXECUTIONS: u32 = 2355;
+        let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
+        let sig = gpu.signature(2, 12);
+        let groups: Vec<u32> = vec![1; 2048];
+        let src = dispatch_records(&gpu, &groups, 32);
+        // SAFETY: a live buffer.
+        let src_gpu = unsafe { src.GetGPUVirtualAddress() };
+        let budget = gpu.default_uav(256);
+        let hits = gpu.default_uav(256);
+        // SAFETY: live buffers.
+        let (budget_gpu, hits_gpu) = unsafe { (budget.GetGPUVirtualAddress(), hits.GetGPUVirtualAddress()) };
+        let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400);
+        let dst = gpu.default_uav(4 << 20);
+        for run in [0u32, 2355 / 49, 5, 1] {
+            let mut best = f64::MAX;
+            for _ in 0..6 {
+                let mut state = D3D12_RESOURCE_STATE_COMMON;
+                let mut table = batch::Table::default();
+                for i in 0..EXECUTIONS {
+                    if run == 0 {
+                        assert!(record_clamp_as(&gpu.clamp, &gpu.list, (&dst, state), budget_gpu, (&src, u64::from(i % 2048) * 32), None, (2, 12, 1), false));
+                    } else if i % run == 0 {
+                        let k = u64::from(i / run) * batch::TABLE;
+                        batch::record(&pass, &gpu.list, (&dst, state), budget_gpu, [src_gpu; 4], tables_gpu + k);
+                        // SAFETY: the mapped table; the list has not run.
+                        table = unsafe { batch::Table::new(tables_ptr.add(k as usize), 0, [1, 0, 0, 0]) };
+                    }
+                    state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
+                    let at = if run == 0 { 0 } else { table.place(1, u64::from(i % 2048) * 32, 2).unwrap() };
+                    // SAFETY: an open list; live buffers.
+                    unsafe {
+                        if run == 0 || i % run == 0 {
+                            gpu.list.SetComputeRootSignature(&gpu.worker.root);
+                            gpu.list.SetPipelineState(&gpu.worker.pso);
+                            gpu.list.SetComputeRootUnorderedAccessView(0, hits_gpu);
+                        }
+                        gpu.list.ExecuteIndirect(&sig, 1, &dst, at, None, 0);
+                    }
+                }
+                let t = std::time::Instant::now();
+                gpu.submit_and_wait();
+                best = best.min(t.elapsed().as_secs_f64() * 1e3);
+            }
+            let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") };
+            println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms");
+        }
+    }
 }
 
 /// The benchmark of the clamp and its barriers (ignored by default).

+ 276 - 0
crates/victory-gpu/src/indirect/batch.rs

@@ -0,0 +1,276 @@
+//! Clamps of many executions in one pass: the arguments of every indirect
+//! execution between two points where they may change are bounded together,
+//! at the first of them.
+//!
+//! The executions that come after it are not known yet when the pass is
+//! recorded, so it reads what to clamp from a table of jobs in upload
+//! memory, which the CPU goes on filling while the list is recorded: the
+//! pass is as wide as the table and its threads past the count do nothing.
+//! An execution that asks for a record already in the table (the title's
+//! tile classes) reads the same clamped one.
+//!
+//! What the records charge the list's budget is as for records clamped
+//! alone, times the executions that read them.
+
+use windows::Win32::Graphics::Direct3D12::*;
+
+use super::{Clamp, uav_barrier};
+use crate::host::transition;
+
+/// The jobs of one pass.
+pub(crate) const JOBS: u32 = 256;
+/// The bytes of its table in upload memory: the count, then the jobs.
+pub(crate) const TABLE: u64 = 16 + 16 * JOBS as u64;
+/// The bytes of a clamped record's place in the scratch buffer.
+pub(crate) const SLOT: u32 = 32;
+/// The source buffers a pass can read.
+pub(crate) const SOURCES: usize = 4;
+/// The most executions charged by one job: the most a record costs (2^26)
+/// as often still fits 32 bits.
+pub(crate) const TIMES: u32 = 31;
+
+pub(crate) const SOURCE: &str = r#"
+#define RS "SRV(t0), SRV(t1), SRV(t2), SRV(t3), SRV(t4), UAV(u0), UAV(u1)"
+ByteAddressBuffer src0 : register(t0);
+ByteAddressBuffer src1 : register(t1);
+ByteAddressBuffer src2 : register(t2);
+ByteAddressBuffer src3 : register(t3);
+// The count, 12 bytes of nothing, then per job: source (bits 0-1), kind
+// (4-7), words (8-11) and the executions that read it (16-31); the
+// record's offset in the source; its place in the scratch buffer; nothing.
+ByteAddressBuffer jobs : register(t4);
+RWByteAddressBuffer dst_args : register(u0);
+RWByteAddressBuffer budget : register(u1);
+static const uint BUDGET = 1u << 27;
+static const uint GROUPS = 1u << 20;
+groupshared uint costs[64];
+groupshared uint fits[64];
+groupshared uint largest_asked;
+groupshared uint all_asked;
+uint load(uint source, uint at) {
+    if (source == 0) return src0.Load(at);
+    if (source == 1) return src1.Load(at);
+    if (source == 2) return src2.Load(at);
+    return src3.Load(at);
+}
+[RootSignature(RS)]
+[numthreads(64, 1, 1)]
+void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
+    uint count = jobs.Load(0);
+    bool active = id.x < count;
+    uint4 job = uint4(0, 0, 0, 0);
+    uint record[5] = {0, 0, 0, 0, 0};
+    uint cost = 0;
+    uint asked = 0;
+    uint kind = 0;
+    uint words = 0;
+    if (gi == 0) {
+        largest_asked = 0;
+        all_asked = 0;
+    }
+    // As the clamp of one execution (`super::SOURCE`) bounds them.
+    if (active) {
+        job = jobs.Load4(16 + id.x * 16);
+        kind = (job.x >> 4) & 15;
+        words = min((job.x >> 8) & 15, 5);
+        for (uint w = 0; w < words; w++) {
+            record[w] = load(job.x & 3, job.y + w * 4);
+        }
+        if (kind <= 1) {
+            record[0] = min(record[0], 1u << 24);
+            record[1] = min(record[1], (1u << 26) / max(record[0], 1u));
+            cost = record[0] * record[1];
+        } else if (kind == 2) {
+            uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u));
+            if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
+                g = uint3(0, 0, 0);
+            }
+            cost = g.x * g.y * g.z * 64u;
+            record[0] = g.x;
+            record[1] = g.y;
+            record[2] = g.z;
+        } else {
+            asked = record[0];
+            record[0] = min(record[0], 65535u);
+            record[1] = min(record[1], 1u);
+            record[2] = min(record[2], 1u);
+            cost = record[0] * record[1] * record[2] * 128u;
+        }
+        cost *= job.x >> 16;
+    }
+    costs[gi] = cost;
+    GroupMemoryBarrierWithGroupSync();
+    if (active && kind > 2) {
+        uint was;
+        InterlockedMax(largest_asked, asked, was);
+        InterlockedAdd(all_asked, min(asked, 1u << 24), was);
+    }
+    uint first = id.x - gi;
+    uint n = count > first ? min(64u, count - first) : 0u;
+    if (gi == 0 && n > 0) {
+        uint before;
+        budget.InterlockedOr(0, 0, before);
+        [allow_uav_condition]
+        while (before < BUDGET) {
+            uint next = before;
+            for (uint j = 0; j < n; j++) {
+                uint c = costs[j];
+                if (c > 0 && next < BUDGET) {
+                    next = (BUDGET - next <= c) ? BUDGET : (next + c);
+                }
+            }
+            if (next == before) break;
+            uint prev;
+            budget.InterlockedCompareExchange(0, before, next, prev);
+            if (prev == before) break;
+            before = prev;
+        }
+        uint at = before;
+        for (uint k = 0; k < n; k++) {
+            uint c = costs[k];
+            uint fit = 1;
+            if (c > 0) {
+                fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u;
+                at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c);
+            }
+            fits[k] = fit;
+        }
+    }
+    GroupMemoryBarrierWithGroupSync();
+    if (gi == 0 && n > 0 && all_asked > 0) {
+        uint was;
+        budget.InterlockedMax(4, largest_asked, was);
+        budget.InterlockedAdd(8, all_asked, was);
+    }
+    if (!active) {
+        return;
+    }
+    if (fits[gi] == 0) {
+        record[0] = 0;
+        record[1] = 0;
+        if (kind > 1) {
+            record[2] = 0;
+        }
+    }
+    for (uint s = 0; s < words; s++) {
+        dst_args.Store(job.z + s * 4, record[s]);
+    }
+}
+"#;
+
+/// The words of a record of `kind` (PC argument numbering).
+pub(crate) fn words(kind: u32) -> Option<u32> {
+    super::min_stride(kind).map(|bytes| bytes / 4)
+}
+
+/// A job's first word.
+pub(crate) fn job(source: u32, kind: u32, times: u32) -> u32 {
+    source | (kind << 4) | (words(kind).unwrap_or(0) << 8) | (times << 16)
+}
+
+/// The jobs of a pass as the CPU fills them ([`SOURCE`]), and where it
+/// keeps which record is where.
+#[derive(Default)]
+pub(crate) struct Table {
+    /// The table in upload memory ([`TABLE`] bytes).
+    at: usize,
+    /// The place of the first clamped record in the scratch buffer.
+    base: u32,
+    /// The host copies it can read, by number ([`crate::shadow::Shadow::id`];
+    /// 0: none).
+    sources: [u64; SOURCES],
+    /// How many executions each job is charged for so far.
+    times: Vec<u32>,
+    /// The job of a record (source, offset, kind).
+    known: std::collections::HashMap<(u32, u32, u32), u32>,
+}
+
+impl Table {
+    /// A table at `at`, with no job yet.
+    ///
+    /// # Safety
+    /// `at` is [`TABLE`] bytes of mapped upload memory, 4-byte aligned, that
+    /// live until the list that reads them is recorded and is not run
+    /// before.
+    pub(crate) unsafe fn new(at: *mut u8, base: u32, sources: [u64; SOURCES]) -> Table {
+        // SAFETY: the caller's.
+        unsafe { at.cast::<u32>().write_volatile(0) };
+        Table { at: at as usize, base, sources, ..Table::default() }
+    }
+
+    /// The place in the scratch buffer of the record of `kind` at `offset`
+    /// of the host copy `id`, once the pass has run: a job of it is added if
+    /// there is none. `None` if the pass cannot read that copy or has no
+    /// room for another job.
+    pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option<u64> {
+        let source = self.sources.iter().position(|&s| s == id)? as u32;
+        let offset = u32::try_from(offset).ok().filter(|o| o.is_multiple_of(4))?;
+        offset.checked_add(words(kind)? * 4)?;
+        let key = (source, offset, kind);
+        let table = self.at as *mut u32;
+        let place = |i: u32| u64::from(self.base + i * SLOT);
+        if let Some(&i) = self.known.get(&key)
+            && self.times[i as usize] < TIMES
+        {
+            self.times[i as usize] += 1;
+            // SAFETY: the job's own word of the table ([`Table::new`]).
+            unsafe { table.add(4 + 4 * i as usize).write_volatile(job(source, kind, self.times[i as usize])) };
+            return Some(place(i));
+        }
+        let i = self.times.len() as u32;
+        if i == JOBS {
+            return None;
+        }
+        self.times.push(1);
+        self.known.insert(key, i);
+        // SAFETY: inside the table: fewer than [`JOBS`] jobs before it.
+        unsafe {
+            let to = table.add(4 + 4 * i as usize);
+            to.write_volatile(job(source, kind, 1));
+            to.add(1).write_volatile(offset);
+            to.add(2).write_volatile(self.base + i * SLOT);
+            to.add(3).write_volatile(0);
+            table.write_volatile(i + 1);
+        }
+        Some(place(i))
+    }
+}
+
+/// Records the pass over the table at `jobs` (a host address) into `dst`,
+/// which is in state `before` and left in `INDIRECT_ARGUMENT`: after every
+/// earlier shader write (the title's argument passes), before what reads
+/// the clamped records.
+pub(super) fn record(
+    c: &Clamp,
+    l: &ID3D12GraphicsCommandList,
+    (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
+    budget: u64,
+    sources: [u64; SOURCES],
+    jobs: u64,
+) {
+    let after = transition(
+        dst,
+        D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+        D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
+    );
+    // SAFETY: an open list; our root signature and pipeline; live buffers:
+    // the sources and the table are read in the common state (promoted).
+    unsafe {
+        l.ResourceBarrier(&[
+            uav_barrier(),
+            transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
+        ]);
+        l.SetComputeRootSignature(&c.root);
+        l.SetPipelineState(&c.pso);
+        for (i, source) in sources.into_iter().enumerate() {
+            l.SetComputeRootShaderResourceView(i as u32, source);
+        }
+        l.SetComputeRootShaderResourceView(SOURCES as u32, jobs);
+        l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 1, dst.GetGPUVirtualAddress());
+        l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 2, budget);
+        l.Dispatch(JOBS.div_ceil(64), 1, 1);
+        // Nothing else the pass writes is read before the next full wait
+        // (the budget, by the next pass): only the records have to be there.
+        l.ResourceBarrier(&[after]);
+    }
+}

+ 12 - 1
crates/victory-gpu/src/list.rs

@@ -742,6 +742,9 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
     if let Some(list) = host_list(this)
         && !barriers.is_null()
     {
+        if count > 0 {
+            with_state(this, |_, state| state.synced());
+        }
         // SAFETY: the title passes `count` barriers.
         let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
         let mut host: Vec<Barrier> = barriers
@@ -1396,7 +1399,14 @@ extern "system" fn set_pipeline(this: This, pipeline: This) {
 /// 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.
-extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
+/// (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) {
+    #[cfg(windows)]
+    with_state(this, |_, state| state.synced());
+    #[cfg(not(windows))]
+    let _ = this;
+}
 
 /// Reset with console flags `(allocator, pipeline, flags)`; the flags only
 /// tune the console's command memory.
@@ -1943,6 +1953,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
         && let Some(list) = host_list(this)
     {
         use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
+        with_state(this, |_, state| state.synced());
         // SAFETY: the same layout; no resource named.
         let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
         // SAFETY: an open list.

+ 378 - 1
crates/victory-gpu/src/replay/edit.rs

@@ -3,7 +3,7 @@
 
 use std::collections::{HashMap, HashSet};
 
-use super::wire::{ALL, Barrier, Cmd, NONE, Va};
+use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot};
 
 /// The buffer the clamped arguments of all clamp passes lie in, in lists
 /// edited by [`clamps`].
@@ -298,6 +298,276 @@ pub fn skip_clamps(cmds: Vec<Cmd>, clamps: &[Clamp]) -> Vec<Cmd> {
     out
 }
 
+/// The root signature, pipeline and table of the batched clamp
+/// (`crate::indirect::batch`), and the scratch buffer it writes in the
+/// first list of the frame (the next lists' are the ids before it), in lists
+/// edited by [`batch_clamps`].
+pub const BATCH_ROOT: u32 = u32::MAX - 2;
+pub const BATCH: u32 = u32::MAX - 3;
+pub const BATCH_JOBS: u32 = u32::MAX - 4;
+pub const BATCH_SCRATCH: u32 = u32::MAX - 16;
+
+/// What [`batch_clamps`] did to a list.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Batched {
+    /// Clamp passes before; after; the records the latter clamp.
+    pub clamps: u32,
+    pub batches: u32,
+    pub jobs: u32,
+    /// The bytes of the scratch buffer.
+    pub scratch: u64,
+}
+
+/// A clamp batch being filled by [`batch_clamps`].
+struct Batch {
+    /// Where its table is in the jobs, and its root views in the list.
+    table: usize,
+    at: usize,
+    sources: Vec<u32>,
+    /// By source, offset and kind: the job, and how often it is read.
+    known: HashMap<(u32, u64, u32), (u32, u32)>,
+    n: u32,
+    base: u64,
+}
+
+/// The list with its clamps done in batches, as `crate::draw` does with
+/// `VICTORY_INDIRECT_BATCH`: one pass at the first execution after a
+/// point where arguments may have changed (a wait for shader writes, with
+/// dispatches since the batch before it; or a draw, with dispatches since
+/// the last wait). `careful`: before indirect dispatches too, with
+/// dispatches since the last wait. `compute`: the pipelines that are compute
+/// ones. The tables go to `jobs` (the contents of [`BATCH_JOBS`]).
+pub fn batch_clamps(
+    cmds: Vec<Cmd>,
+    psos: &HashSet<u32>,
+    compute: &HashSet<u32>,
+    scratch: u32,
+    careful: bool,
+    jobs: &mut Vec<u8>,
+) -> (Vec<Cmd>, Batched) {
+    use crate::indirect::batch::{JOBS, SLOT, SOURCES, TIMES, job};
+    const DISPATCH: u32 = 2;
+    let mut done = Batched::default();
+    let scratches: HashSet<u32> = {
+        let mut next = 0;
+        let found = find_clamps(&cmds, psos, &mut next);
+        found.iter().map(|c| c.scratch).collect()
+    };
+    if scratches.is_empty() {
+        return (cmds, done);
+    }
+    let of_clamp =
+        |b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res));
+    let moved = |before, after| Barrier::Transition {
+        flags: 0,
+        res: scratch,
+        sub: ALL,
+        before,
+        after,
+    };
+    // What the last clamp into a scratch buffer clamped: source, offset,
+    // kind.
+    let mut clamps: HashMap<u32, (u32, u64, u32)> = HashMap::new();
+    let (mut bound, mut constants, mut views) = (NONE, [0u32; 6], [(NONE, 0u64); 5]);
+    let mut out: Vec<Cmd> = Vec::with_capacity(cmds.len());
+    let mut open: Option<Batch> = None;
+    let (mut written, mut dirty, mut readable) = (true, true, false);
+    let mut cmds = cmds.into_iter().peekable();
+    while let Some(c) = cmds.next() {
+        match &c {
+            // A clamp's own commands: its root signature and all it sets.
+            Cmd::RootSignature {
+                graphics: false, ..
+            } if matches!(cmds.peek(), Some(Cmd::Pipeline { pso }) if psos.contains(pso)) => {}
+            Cmd::Pipeline { pso } => {
+                bound = *pso;
+                if !psos.contains(pso) {
+                    out.push(c);
+                }
+            }
+            Cmd::Constants {
+                graphics: false,
+                values,
+                offset,
+                ..
+            } if psos.contains(&bound) => {
+                for (i, v) in values.iter().enumerate() {
+                    if let Some(c) = constants.get_mut(*offset as usize + i) {
+                        *c = *v;
+                    }
+                }
+            }
+            Cmd::RootView {
+                graphics: false,
+                param,
+                va: Va::At { res, offset },
+                ..
+            } if psos.contains(&bound) => {
+                if let Some(v) = views.get_mut(*param as usize) {
+                    *v = (*res, *offset);
+                }
+            }
+            Cmd::Dispatch { .. } if psos.contains(&bound) => {
+                done.clamps += 1;
+                let (source, offset) = views[1];
+                clamps.insert(
+                    views[3].0,
+                    (source, offset + u64::from(constants[3]), constants[0]),
+                );
+                // What it was clamped for follows: a batch is open by then.
+                let full =
+                    |o: &Batch| !o.sources.contains(&source) && o.sources.len() == SOURCES;
+                if dirty && (constants[0] != DISPATCH || careful) || open.as_ref().is_some_and(full)
+                {
+                    open = None;
+                }
+                if open.is_some() {
+                    continue;
+                }
+                done.batches += 1;
+                let table = jobs.len();
+                jobs.resize(table + 16 + 16 * 2048, 0);
+                out.push(Cmd::Barriers {
+                    all: vec![
+                        Barrier::Uav {
+                            flags: 0,
+                            res: NONE,
+                        },
+                        moved(if readable { INDIRECT_ARGUMENT } else { 0 }, UNORDERED_ACCESS),
+                    ],
+                });
+                readable = true;
+                out.push(Cmd::RootSignature {
+                    graphics: false,
+                    root: BATCH_ROOT,
+                });
+                out.push(Cmd::Pipeline { pso: BATCH });
+                let at = out.len();
+                let mut view = |kind, param: usize, res, offset| {
+                    out.push(Cmd::RootView {
+                        graphics: false,
+                        kind,
+                        param: param as u32,
+                        va: Va::At { res, offset },
+                    });
+                };
+                for i in 0..SOURCES {
+                    view(slot::SRV, i, source, 0);
+                }
+                view(slot::SRV, SOURCES, BATCH_JOBS, table as u64);
+                view(slot::UAV, SOURCES + 1, scratch, 0);
+                view(slot::UAV, SOURCES + 2, views[4].0, views[4].1);
+                out.push(Cmd::Dispatch {
+                    groups: [JOBS.div_ceil(64), 1, 1],
+                });
+                out.push(Cmd::Barriers {
+                    all: vec![moved(UNORDERED_ACCESS, INDIRECT_ARGUMENT)],
+                });
+                open = Some(Batch {
+                    table,
+                    at,
+                    sources: Vec::new(),
+                    known: HashMap::new(),
+                    n: 0,
+                    base: done.scratch,
+                });
+                (written, dirty) = (false, false);
+            }
+            Cmd::Barriers { all } => {
+                if all.iter().any(of_clamp) {
+                    continue;
+                }
+                let waits = |b: &Barrier| matches!(b, Barrier::Uav { res: NONE, .. });
+                if all.iter().any(waits) {
+                    if written {
+                        open = None;
+                    }
+                    dirty = false;
+                }
+                out.push(c);
+            }
+            Cmd::Indirect {
+                signature,
+                most,
+                args,
+                at,
+                count,
+                count_at,
+            } if clamps.contains_key(args) => {
+                let (source, offset, kind) = clamps.get(args).copied().unwrap_or_default();
+                let Some(o) = &mut open else {
+                    // Not clamped by any batch: left out, which shows.
+                    continue;
+                };
+                let slot = match o.sources.iter().position(|&s| s == source) {
+                    Some(i) => i,
+                    None => {
+                        o.sources.push(source);
+                        let i = o.sources.len() - 1;
+                        if let Some(Cmd::RootView {
+                            va: Va::At { res, .. },
+                            ..
+                        }) = out.get_mut(o.at + i)
+                        {
+                            *res = source;
+                        }
+                        i
+                    }
+                };
+                let offset = offset + at;
+                let entry = o.known.entry((source, offset, kind)).or_insert((o.n, 0));
+                entry.1 += 1;
+                let (i, times) = *entry;
+                if i == o.n {
+                    o.n += 1;
+                    done.jobs += 1;
+                    done.scratch = o.base + u64::from(o.n * SLOT);
+                    // Wider than the live pass where its table is longer.
+                    if let Some(Cmd::Dispatch { groups }) = out.get_mut(o.at + SOURCES + 3) {
+                        groups[0] = groups[0].max(o.n.div_ceil(64));
+                    }
+                }
+                let place = o.base + u64::from(i * SLOT);
+                let words = [
+                    job(slot as u32, kind, times.min(TIMES)),
+                    offset as u32,
+                    place as u32,
+                    0,
+                ];
+                let mut put = |at: usize, w: u32| {
+                    jobs[o.table + at..o.table + at + 4].copy_from_slice(&w.to_le_bytes());
+                };
+                for (k, w) in words.into_iter().enumerate() {
+                    put(16 + 16 * i as usize + 4 * k, w);
+                }
+                put(0, o.n);
+                out.push(Cmd::Indirect {
+                    signature: *signature,
+                    most: *most,
+                    args: scratch,
+                    at: place,
+                    count: *count,
+                    count_at: *count_at,
+                });
+                if compute.contains(&bound) {
+                    (written, dirty) = (true, true);
+                }
+            }
+            Cmd::Dispatch { .. } => {
+                (written, dirty) = (true, true);
+                out.push(c);
+            }
+            _ => out.push(c),
+        }
+    }
+    if readable {
+        out.push(Cmd::Barriers {
+            all: vec![moved(INDIRECT_ARGUMENT, 0)],
+        });
+    }
+    (out, done)
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -501,4 +771,111 @@ mod tests {
             [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]
         );
     }
+
+    #[test]
+    fn clamps_are_batched() {
+        use crate::indirect::batch::job;
+        let clamp = |kind, offset, records, source| {
+            let view = |param, res| Cmd::RootView {
+                graphics: false,
+                kind: 2,
+                param,
+                va: Va::At { res, offset: 0 },
+            };
+            vec![
+                barriers(&[uav(0), moved(5, 0x200, 8)]),
+                Cmd::RootSignature {
+                    graphics: false,
+                    root: 8,
+                },
+                pso(9),
+                Cmd::Constants {
+                    graphics: false,
+                    param: 0,
+                    offset: 0,
+                    values: vec![kind, 32, records, offset, 0, 0],
+                },
+                view(1, source),
+                view(2, source),
+                view(3, 5),
+                view(4, 6),
+                go(),
+                barriers(&[uav(0), moved(5, 8, 0x200)]),
+            ]
+        };
+        let run = |at| Cmd::Indirect {
+            signature: 1,
+            most: 1,
+            args: 5,
+            at,
+            count: 0,
+            count_at: 0,
+        };
+        // A dispatch, two indirect ones with a wait of the title's between
+        // them, then draws: a window of two and another buffer's.
+        let mut list = vec![pso(1), go()];
+        list.extend(clamp(2, 0, 1, 70));
+        list.extend([pso(1), run(0)]);
+        list.extend(clamp(2, 64, 1, 70));
+        list.extend([pso(1), run(0), barriers(&[uav(0)])]);
+        list.extend(clamp(2, 64, 1, 70));
+        list.extend([pso(1), run(0)]);
+        list.extend(clamp(10, 128, 2, 70));
+        list.extend([pso(2), run(0), run(32), run(32)]);
+        list.extend(clamp(10, 256, 1, 71));
+        list.extend([pso(2), run(0)]);
+        let (clamps, compute) = (HashSet::from([9]), HashSet::from([1]));
+        let table = 16 + 16 * 2048;
+        for (careful, batches) in [(false, 3), (true, 4)] {
+            let mut jobs = Vec::new();
+            let (out, done) = batch_clamps(list.clone(), &clamps, &compute, 99, careful, &mut jobs);
+            assert_eq!((done.clamps, done.batches, done.jobs), (5, batches, 6), "careful {careful}");
+            assert_eq!(jobs.len(), table * batches as usize);
+            let passes = out.iter().filter(|c| matches!(c, Cmd::Pipeline { pso: BATCH })).count();
+            assert_eq!(passes, batches as usize);
+            // Nothing of the clamps is left; the title's wait is.
+            assert!(!out.contains(&pso(9)) && out.contains(&barriers(&[uav(0)])));
+            let names_5 = |c: &Cmd| matches!(c, Cmd::Barriers { all } if all.iter().any(|b| matches!(b, Barrier::Transition { res: 5, .. })));
+            assert!(!out.iter().any(names_5));
+            let places: Vec<u64> = out
+                .iter()
+                .filter_map(|c| match c {
+                    Cmd::Indirect { args: 99, at, .. } => Some(*at),
+                    _ => None,
+                })
+                .collect();
+            assert_eq!(places, [0, 32, 64, 96, 128, 128, 160]);
+            // The last table: two records, one read twice, then one of the
+            // other buffer.
+            let word = |i: usize| {
+                let at = jobs.len() - table + 4 * i;
+                u32::from_le_bytes(jobs[at..at + 4].try_into().unwrap())
+            };
+            assert_eq!(word(0), 3);
+            let all: Vec<u32> = (4..16).map(word).collect();
+            assert_eq!(
+                all,
+                [
+                    [job(0, 10, 1), 128, 96, 0],
+                    [job(0, 10, 2), 160, 128, 0],
+                    [job(1, 10, 1), 256, 160, 0]
+                ]
+                .concat()
+            );
+            let sources: Vec<u32> = out
+                .iter()
+                .filter_map(|c| match c {
+                    Cmd::RootView { param: 1, va: Va::At { res, .. }, .. } => Some(*res),
+                    _ => None,
+                })
+                .collect();
+            assert_eq!(sources.last(), Some(&71));
+            // It ends common, as it began.
+            assert_eq!(out.last(), Some(&barriers(&[moved(99, 0x200, 0)])));
+        }
+        // A list without clamps is left as it is.
+        let plain = vec![pso(1), go(), barriers(&[uav(0)])];
+        let (out, done) = batch_clamps(plain.clone(), &clamps, &compute, 99, false, &mut Vec::new());
+        assert_eq!((out, done), (plain, Batched::default()));
+    }
 }

+ 233 - 49
crates/victory-gpu/src/replay/play.rs

@@ -65,9 +65,13 @@ pub struct Options {
     /// Where the picture goes (default: `replay.png` in the capture).
     pub image: Option<PathBuf>,
     pub buffers: Buffers,
+    /// Of those, only the ones all of these match ([`chosen`]).
+    pub only_buffers: Vec<String>,
     pub no_barriers: bool,
     pub merge_barriers: bool,
     pub skip_clamps: bool,
+    /// The clamps in batches (`edit::batch_clamps`); 2: carefully.
+    pub batch_clamps: u32,
     pub skip_hash_passes: bool,
     pub one_submit: bool,
     /// Copies of what the CPU wrote leave alone what the card wrote in this
@@ -97,9 +101,11 @@ impl Default for Options {
             top: 20,
             image: None,
             buffers: Buffers::AsRecorded,
+            only_buffers: Vec::new(),
             no_barriers: false,
             merge_barriers: false,
             skip_clamps: false,
+            batch_clamps: 0,
             skip_hash_passes: false,
             one_submit: false,
             merge: true,
@@ -118,6 +124,7 @@ impl Options {
         self.no_barriers
             || self.merge_barriers
             || self.skip_clamps
+            || self.batch_clamps > 0
             || self.skip_hash_passes
             || self.one_submit
             || self.wait_all
@@ -132,6 +139,7 @@ impl Options {
             no_barriers: false,
             merge_barriers: false,
             skip_clamps: false,
+            batch_clamps: 0,
             skip_hash_passes: false,
             one_submit: false,
             wait_all: false,
@@ -245,6 +253,32 @@ impl Report {
     }
 }
 
+/// Whether `--only-buffers` means a buffer: all of `only` match it.
+/// `name=<text in its name>`, `min=<bytes>`, `max=<bytes>`,
+/// `seen=<how the CPU saw it>`, `id=<a>..<b>`; with `!` in front: that does not.
+fn chosen(r: &wire::Resource, only: &[String]) -> bool {
+    only.iter().all(|f| {
+        let (no, f) = match f.strip_prefix('!') {
+            Some(f) => (true, f),
+            None => (false, f.as_str()),
+        };
+        let (key, value) = f.split_once('=').unwrap_or(("name", f));
+        let number = value.parse().unwrap_or(0u64);
+        let is = match key {
+            "min" => r.desc.width >= number,
+            "max" => r.desc.width <= number,
+            "seen" => {
+                matches!(&r.place, Place::Committed { props, .. } if format!("{:?}", gpu::seen(props)).eq_ignore_ascii_case(value))
+            }
+            "id" => value.split_once("..").is_some_and(|(a, b)| {
+                (a.parse().unwrap_or(0)..b.parse().unwrap_or(u32::MAX)).contains(&r.id)
+            }),
+            _ => r.name.contains(value),
+        };
+        is != no
+    })
+}
+
 fn median(v: &[f64]) -> f64 {
     let mut v = v.to_vec();
     v.sort_by(f64::total_cmp);
@@ -311,20 +345,65 @@ pub fn dump(folder: &Path, text: &str) -> Result<Vec<String>> {
     Ok(out)
 }
 
+/// Writes, one line each, the commands of lists (by their place in the
+/// frame), and before them the frame's buffers: `--listing`.
+pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> Result<()> {
+    let frame = Frame::read(&find(folder)?.join("frame.bin"))?;
+    let pipelines: HashMap<u32, &str> =
+        frame.pipelines.iter().map(|p| (p.id, p.name.as_str())).collect();
+    for r in &frame.resources {
+        if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
+            let place = match &r.place {
+                Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)),
+                other => format!("{other:?}"),
+            };
+            line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name));
+        }
+    }
+    let mut place = 0;
+    for (i, s) in frame.submits.iter().enumerate() {
+        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}"));
+            for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() {
+                match c {
+                    Cmd::Pipeline { pso } => {
+                        line(&format!("{n} Pipeline {pso} {}", pipelines.get(pso).copied().unwrap_or_default()));
+                    }
+                    c => line(&format!("{n} {c:?}")),
+                }
+            }
+        }
+    }
+    Ok(())
+}
+
 /// Loads a capture and runs it: the whole of `victory replay`. The reports,
 /// with what each is of.
 pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>> {
     let mut player = Player::load(folder, options)?;
     let mut out = Vec::new();
     if options.compare && options.edited() {
+        // Turn by turn: what else the machine does falls on both.
         let image = Some(player.folder.join("replay-unchanged.png"));
-        out.push((
-            "unchanged".into(),
-            player.run(&Options {
-                image,
-                ..options.plain()
-            })?,
-        ));
+        let plain = Options {
+            image,
+            ..options.plain()
+        };
+        let mut a = player.prepare(&plain)?;
+        let mut b = player.prepare(options)?;
+        let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new());
+        for _ in 0..options.loops.max(1) {
+            stamps_a = player.once(&plain, &mut a)?;
+            stamps_b = player.once(options, &mut b)?;
+        }
+        out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?));
+        out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?));
+        return Ok(out);
     }
     let what = if options.edited() {
         "with the experiments"
@@ -468,7 +547,7 @@ impl Player {
             *at = Instant::now();
         };
         let mut at = Instant::now();
-        player.make_resources(options.buffers)?;
+        player.make_resources(options.buffers, &options.only_buffers)?;
         step("resources", &mut at);
         player.make_pipelines()?;
         step("pipelines", &mut at);
@@ -558,7 +637,7 @@ impl Player {
         }
     }
 
-    fn make_resources(&mut self, buffers: Buffers) -> Result<()> {
+    fn make_resources(&mut self, buffers: Buffers, only: &[String]) -> Result<()> {
         // A heap of memory the CPU sees becomes one the card may write too:
         // what the CPU wrote is put back by the card.
         let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES {
@@ -602,7 +681,7 @@ impl Player {
         for h in &self.frame.heaps {
             let desc = D3D12_HEAP_DESC {
                 SizeInBytes: h.size,
-                Properties: props(&h.props, used_by_buffers_only.contains(&h.id)),
+                Properties: props(&h.props, only.is_empty() && used_by_buffers_only.contains(&h.id)),
                 Alignment: h.alignment,
                 Flags: D3D12_HEAP_FLAGS(h.flags & !DROP),
             };
@@ -613,8 +692,15 @@ impl Player {
             self._heaps.extend(heap.map(|heap| (h.id, heap)));
         }
         let mut failed = 0;
+        let mut moves: BTreeMap<String, (u32, u64)> = BTreeMap::new();
         for (index, r) in self.frame.resources.iter().enumerate() {
             let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
+            let moved = is_buffer && chosen(r, only);
+            if moved && let Place::Committed { props, .. } = &r.place {
+                let seen = gpu::seen(props);
+                let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64));
+                *m = (m.0 + 1, m.1 + r.desc.width);
+            }
             let desc = gpu::to_desc(&r.desc);
             let mut made: Option<ID3D12Resource> = None;
             let clear: Option<D3D12_CLEAR_VALUE> = r.clear.map(|c| {
@@ -637,7 +723,7 @@ impl Player {
                         None => Err(windows::core::Error::empty()),
                     },
                     Place::Committed { props: p, flags } => {
-                        let p = props(p, is_buffer);
+                        let p = props(p, moved);
                         let state = if p.Type == D3D12_HEAP_TYPE_READBACK {
                             D3D12_RESOURCE_STATE_COPY_DEST
                         } else {
@@ -700,6 +786,11 @@ impl Player {
         if failed > 0 {
             self.note(format!("{failed} resources could not be made again"));
         }
+        if buffers != Buffers::AsRecorded {
+            self.notes.push(format!(
+                "--buffers is of, by how the CPU saw them (buffers, bytes): {moves:?}"
+            ));
+        }
         Ok(())
     }
 
@@ -1800,6 +1891,17 @@ impl Player {
                 .push(format!("{} pipelines match --skip-shader", skip.len()));
         }
         let hash = self.pipelines_named(COMPARE);
+        let clamp = self.pipelines_named(CLAMP);
+        let compute: HashSet<u32> = self
+            .frame
+            .pipelines
+            .iter()
+            .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0)))
+            .map(|p| p.id)
+            .collect();
+        let mut batched = edit::Batched::default();
+        let mut jobs = Vec::new();
+        let mut scratches = Vec::new();
         let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0);
         let mut place = 0;
         let mut out = Vec::new();
@@ -1818,6 +1920,24 @@ impl Player {
                 {
                     cmds = edit::skip_clamps(cmds, c);
                 }
+                if o.batch_clamps > 0 {
+                    let scratch = edit::BATCH_SCRATCH - here;
+                    let done;
+                    (cmds, done) = edit::batch_clamps(
+                        cmds,
+                        &clamp,
+                        &compute,
+                        scratch,
+                        o.batch_clamps > 1,
+                        &mut jobs,
+                    );
+                    batched.clamps += done.clamps;
+                    batched.batches += done.batches;
+                    batched.jobs += done.jobs;
+                    if done.scratch > 0 {
+                        scratches.push((scratch, done.scratch));
+                    }
+                }
                 let mut n;
                 if !skip.is_empty() {
                     (cmds, n) = edit::skip_pipelines(cmds, &skip);
@@ -1839,6 +1959,15 @@ impl Player {
             }
             out.push(lists);
         }
+        if o.batch_clamps > 0 {
+            report.notes.push(format!(
+                "--batch-clamps: {} clamp passes became {}, of {} records",
+                batched.clamps, batched.batches, batched.jobs
+            ));
+            if let Err(e) = self.make_batches(&jobs, &scratches) {
+                report.notes.push(format!("--batch-clamps failed: {e:#}"));
+            }
+        }
         if !skip.is_empty() {
             report
                 .notes
@@ -1862,6 +1991,44 @@ impl Player {
         out
     }
 
+    /// What lists edited by [`edit::batch_clamps`] name: the pass, its
+    /// tables and scratch buffers.
+    fn make_batches(&mut self, jobs: &[u8], scratches: &[(u32, u64)]) -> Result<()> {
+        let (root, pso) = crate::indirect::batch_for(&self.device)?;
+        self.roots.insert(edit::BATCH_ROOT, root);
+        self.pipelines.insert(edit::BATCH, pso);
+        let (table, data) = gpu::buffer(
+            &self.device,
+            D3D12_HEAP_TYPE_UPLOAD,
+            jobs.len().max(4) as u64,
+            D3D12_RESOURCE_FLAG_NONE,
+        )?;
+        // SAFETY: a mapping of as many bytes.
+        unsafe { std::ptr::copy_nonoverlapping(jobs.as_ptr(), data.cast(), jobs.len()) };
+        let mut all = vec![(edit::BATCH_JOBS, table)];
+        for &(id, bytes) in scratches {
+            let (scratch, _) = gpu::buffer(
+                &self.device,
+                D3D12_HEAP_TYPE_DEFAULT,
+                bytes.next_multiple_of(64 << 10),
+                D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
+            )?;
+            all.push((id, scratch));
+        }
+        for (id, res) in all {
+            // SAFETY: a live buffer.
+            let va = unsafe { res.GetGPUVirtualAddress() };
+            let object = Object {
+                res,
+                va,
+                index: 0,
+                subs: 1,
+            };
+            self.objects.insert(id, object);
+        }
+        Ok(())
+    }
+
     /// The clamp passes of each list of the frame, in order, and their
     /// results in [`RESULTS`] (by a run that keeps them).
     fn clamp_results(&mut self, report: &mut Report) -> Result<Vec<Vec<Clamp>>> {
@@ -2126,7 +2293,8 @@ impl Player {
         wait: bool,
     ) -> Vec<Stamp> {
         let version = self.version_of.get(submit).copied().unwrap_or(0);
-        let clamps = self.pipelines_named(CLAMP);
+        let mut clamps = self.pipelines_named(CLAMP);
+        clamps.insert(edit::BATCH);
         let compares = self.pipelines_named(COMPARE);
         let mesh: HashSet<u32> = self
             .frame
@@ -2713,6 +2881,16 @@ impl Player {
 
     /// Runs the frame as the options say.
     pub fn run(&mut self, o: &Options) -> Result<Report> {
+        let mut made = self.prepare(o)?;
+        let mut stamps = Vec::new();
+        for _ in 0..o.loops.max(1) {
+            stamps = self.once(o, &mut made)?;
+        }
+        self.finish(o, made, &stamps)
+    }
+
+    /// The lists for a run as the options say.
+    fn prepare(&mut self, o: &Options) -> Result<(Sends, Report)> {
         let mut report = Report {
             notes: self.notes.clone(),
             ..Default::default()
@@ -2724,45 +2902,51 @@ impl Player {
             Vec::new()
         };
         let submits = self.edited(o, &mut report, &clamps);
-        let built = self.build(&submits, o)?;
-        let mut stamps = Vec::new();
-        for _ in 0..o.loops.max(1) {
-            self.restore(o.restore)?;
-            self.fresh = false;
-            stamps = self.send(&built, o)?;
-            if let Some((db, _, hash, _)) = self.picture_now()? {
-                report.pictures.push((db, hash));
-            }
-            let ms = |a: u32, b: u32| {
-                stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
-            };
-            let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
-            let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
-                bail!("no lists to run");
-            };
-            let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
-            report.delta_ms.push(
-                delta
-                    .filter(|d| d.first > first.first)
-                    .map(|d| ms(d.first, d.last))
-                    .sum(),
-            );
-            report.frame_ms.push(ms(first.first, last.last));
-            let each = |l: &[Built]| match (l.first(), l.last()) {
-                (Some(a), Some(b)) => ms(a.first, b.last),
-                _ => 0.0,
-            };
-            report.submits = built
-                .steps
-                .iter()
-                .map(|(_, l)| (l.len(), each(l)))
-                .collect();
-            report
-                .busy_ms
-                .push(report.submits.iter().map(|s| s.1).sum());
+        Ok((self.build(&submits, o)?, report))
+    }
+
+    /// One run of the frame, noted in the report; its timestamps.
+    fn once(&mut self, o: &Options, (built, report): &mut (Sends, Report)) -> Result<Vec<u64>> {
+        self.restore(o.restore)?;
+        self.fresh = false;
+        let stamps = self.send(built, o)?;
+        if let Some((db, _, hash, _)) = self.picture_now()? {
+            report.pictures.push((db, hash));
         }
+        let ms = |a: u32, b: u32| {
+            stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
+        };
+        let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
+        let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
+            bail!("no lists to run");
+        };
+        let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
+        report.delta_ms.push(
+            delta
+                .filter(|d| d.first > first.first)
+                .map(|d| ms(d.first, d.last))
+                .sum(),
+        );
+        report.frame_ms.push(ms(first.first, last.last));
+        let each = |l: &[Built]| match (l.first(), l.last()) {
+            (Some(a), Some(b)) => ms(a.first, b.last),
+            _ => 0.0,
+        };
+        report.submits = built
+            .steps
+            .iter()
+            .map(|(_, l)| (l.len(), each(l)))
+            .collect();
+        report
+            .busy_ms
+            .push(report.submits.iter().map(|s| s.1).sum());
+        Ok(stamps)
+    }
+
+    /// The report after the last run.
+    fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result<Report> {
         if o.detailed {
-            self.detail(&built, &stamps, o, &mut report);
+            self.detail(&built, stamps, o, &mut report);
         }
         if self.merging {
             let notes = self.merge_notes(o.loops)?;

+ 4 - 1
docs/replay.md

@@ -56,12 +56,15 @@ with the presented one.
 
 | switch | does |
 |---|---|
-| `--compare` | runs the frame unchanged first and prints the difference |
+| `--compare` | runs the frame unchanged and with the experiments turn by turn, and prints the difference |
 | `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run |
+| `--batch-clamps` / `--batch-clamps 2` | argument clamps in batches, as `VICTORY_INDIRECT_BATCH=2` / `=1` does |
 | `--skip-hash-passes` | no compare/rehash passes over card buffers |
 | `--no-barriers` | no unordered-access barriers |
 | `--merge-barriers` | joins barrier calls with no work between them |
 | `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory |
+| `--only-buffers <what>` | with `--buffers`: only the buffers all of these match: `name=<text>`, `min=<bytes>`, `max=<bytes>`, `seen=No`, `Cached` or `Combined`, `id=<a>..<b>`, or `!` and one of them (repeatable) |
+| `--listing 3..7` | only writes the frame's buffers and those lists' commands |
 | `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones |
 | `--only 3..7` | runs these lists; of the others only barriers |
 | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |