locum 0.1.6

Captures everything a Direct3D 11 game draws in a frame, to look at, query, change and replay: d3d11.dll and dxgi.dll beside the game that watch every call on its way to the real runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Acceleration structures, armed or not: what each was last built from, so a capture can give replay the builds of
//! those made before its frame. An acceleration structure's bytes are the driver's own (a copy of them is not even
//! allowed), so replay builds it again from the same inputs, on its own device.
//!
//! A build's inputs (vertices, indices and transforms, or AABBs; a top-level build's instance descriptions) are
//! copied right after `BuildRaytracingAccelerationStructure`, in the application's list, into readback memory of
//! locum's: the application cannot change them before its next barrier, so the copy reads what the build read. Each
//! buffer is copied from the state or layout this list's barriers left it in (see [`super::passes::record_ranges`]).
//! The copies belong to the list until it is reset or destroyed; then those that are still some acceleration
//! structure's latest build are kept, the rest freed once the GPU is done with them. A top-level build's instances
//! given as an array of pointers are gathered on the GPU instead, after the list (see [`super::gather`]).
//!
//! Lists execute in the order they are submitted, so that is the order builds take effect: an acceleration
//! structure's latest build is the last one submitted into it. `CopyRaytracingAccelerationStructure` makes the
//! destination a clone (or compaction) of its source's build.
use core::ffi::c_void;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
use std::time::Duration;

use serde_json::Value;
use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
use windows::core::Interface;

use super::states::{Access, Read};

/// Readback memory every kept build's inputs may hold at once.
const BUDGET: u64 = 4 << 30;
static BYTES: AtomicU64 = AtomicU64::new(0);

/// An acceleration structure: the buffer it is in, and its offset there.
pub type Key = (u64, u64);

/// One range of a build's inputs, copied: its part (`vertices`, `indices`, `transform`, `aabbs`, `instances`), the
/// geometry it is of, where the application had it, and where the copy holds it.
#[derive(Clone, Debug)]
pub struct Input {
    pub part: &'static str,
    pub geometry: Option<usize>,
    pub resource: u64,
    pub offset: u64,
    pub bytes: u64,
    at: u64,
}

/// A build as the application recorded it, and its inputs as it read them.
pub struct Build {
    pub dest: Key,
    /// `values::acceleration_structure_build`'s encoding of the build's description.
    pub description: Value,
    pub inputs: Vec<Input>,
    /// Why its inputs were not copied.
    pub error: Option<String>,
    copy: Option<Copy>,
    /// Its instances' gather, where they are given as an array of pointers (`copy` is its readback).
    gather: Option<super::gather::Gather>,
    /// The fence value locum signalled after the latest execution of the list it is in.
    last: Mutex<Option<(ID3D12Fence, u64)>>,
}

struct Copy {
    buffer: ID3D12Resource,
    bytes: u64,
}

impl Drop for Copy {
    fn drop(&mut self) {
        BYTES.fetch_sub(self.bytes, Ordering::AcqRel);
    }
}

impl Build {
    fn done(&self) -> bool {
        self.last
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .as_ref()
            .is_none_or(|(f, v)| unsafe { f.GetCompletedValue() } >= *v)
    }

    /// Its inputs' bytes, in the order of [`Build::inputs`], once the GPU has copied them (waiting up to `patience`).
    pub fn read(&self, patience: Duration) -> Result<Vec<Vec<u8>>, String> {
        if let Some(why) = &self.error {
            return Err(why.clone());
        }
        let copy = self.copy.as_ref().ok_or("its inputs were not copied")?;
        let analysis = match &self.gather {
            Some(g) => {
                let analysis = g.analysis.get().ok_or("its list was never submitted")?.as_ref()?;
                if let Some(why) = g.failed.lock().unwrap_or_else(|e| e.into_inner()).clone() {
                    return Err(format!("its instances' gather was not made: {why}"));
                }
                Some((g.count, analysis))
            }
            None => None,
        };
        let last = self.last.lock().unwrap_or_else(|e| e.into_inner()).clone();
        let Some((fence, value)) = last else {
            return Err("its list was never submitted".into());
        };
        unsafe { wait(&fence, value, patience) }?;
        let mut mapped = core::ptr::null_mut();
        unsafe { copy.buffer.Map(0, None, Some(&mut mapped)) }.map_err(|e| format!("Map: {e}"))?;
        let all = unsafe { core::slice::from_raw_parts(mapped.cast::<u8>(), copy.bytes as usize) };
        let parts = analysis
            .map_or(Ok(()), |(count, a)| super::gather::verdict(all, count, a))
            .map(|()| {
                self.inputs
                    .iter()
                    .map(|i| all[i.at as usize..(i.at + i.bytes) as usize].to_vec())
                    .collect()
            });
        unsafe { copy.buffer.Unmap(0, None) };
        parts
    }
}

unsafe fn wait(fence: &ID3D12Fence, value: u64, patience: Duration) -> Result<(), String> {
    if unsafe { fence.GetCompletedValue() } >= value {
        return Ok(());
    }
    let event = unsafe { CreateEventW(None, false, false, None) }.map_err(|e| format!("an event: {e}"))?;
    let waited = unsafe { fence.SetEventOnCompletion(value, event) }
        .map_err(|e| format!("SetEventOnCompletion: {e}"))
        .and_then(|()| {
            (unsafe { WaitForSingleObject(event, patience.as_millis() as u32) } == WAIT_OBJECT_0)
                .then_some(())
                .ok_or_else(|| format!("the GPU did not copy its inputs within {} s", patience.as_secs()))
        });
    unsafe { CloseHandle(event) }.ok();
    waited
}

/// What a list did to acceleration structures, in its order.
enum Step {
    Build(Arc<Build>),
    /// `CopyRaytracingAccelerationStructure(dest, source, mode)`.
    Copy(Key, Key, i32),
}

#[derive(Default)]
struct State {
    /// Each list's steps, by list.
    lists: HashMap<u64, Vec<Step>>,
    /// Each acceleration structure's latest build.
    latest: HashMap<Key, Arc<Build>>,
    /// Builds no list holds that the GPU may still copy into.
    leaving: Vec<Arc<Build>>,
}

fn state() -> MutexGuard<'static, State> {
    static STATE: OnceLock<Mutex<State>> = OnceLock::new();
    STATE
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(|e| e.into_inner())
}

/// The acceleration structure at GPU address `address`: its buffer and offset.
fn key(address: u64) -> Option<Key> {
    super::slots::unique_address(address).or_else(|| super::slots::buffers_at(address).first().copied())
}

/// The bytes of `count` elements `stride` apart whose last is `last` bytes.
fn extent(count: u64, stride: u64, last: u64) -> u64 {
    if count == 0 {
        0
    } else {
        (count - 1) * stride + last
    }
}

/// A range a build reads: its part, the geometry it is of, its address and its bytes.
type Range = (&'static str, Option<usize>, u64, u64);

/// The ranges a build reads (a top-level build's instances in an array: an array of pointers is gathered).
unsafe fn ranges(i: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS) -> Result<Vec<Range>, String> {
    let n = i.NumDescs as usize;
    if i.Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL {
        let bytes = n as u64 * size_of::<D3D12_RAYTRACING_INSTANCE_DESC>() as u64;
        return Ok(vec![(
            "instances",
            None,
            unsafe { i.Anonymous.InstanceDescs },
            bytes,
        )]);
    }
    let geometry: Vec<&D3D12_RAYTRACING_GEOMETRY_DESC> = if i.DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY {
        unsafe { super::values::slice(i.Anonymous.pGeometryDescs, n) }
            .iter()
            .collect()
    } else {
        unsafe { super::values::slice(i.Anonymous.ppGeometryDescs, n) }
            .iter()
            .map(|g| unsafe { g.as_ref() }.ok_or("a null geometry description"))
            .collect::<Result<_, _>>()?
    };
    let mut out = Vec::new();
    for (k, g) in geometry.into_iter().enumerate() {
        if g.Type == D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES {
            let t = unsafe { &g.Anonymous.Triangles };
            let vertex = locum_capture::format::layout(t.VertexFormat.0 as u32)
                .map(|f| u64::from(f.block_bytes))
                .ok_or_else(|| format!("vertex format {} has no size locum knows", t.VertexFormat.0))?;
            out.push((
                "vertices",
                Some(k),
                t.VertexBuffer.StartAddress,
                extent(u64::from(t.VertexCount), t.VertexBuffer.StrideInBytes, vertex),
            ));
            if t.IndexBuffer != 0 && t.IndexCount > 0 {
                let index = if t.IndexFormat == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT {
                    2
                } else {
                    4
                };
                out.push(("indices", Some(k), t.IndexBuffer, u64::from(t.IndexCount) * index));
            }
            if t.Transform3x4 != 0 {
                out.push(("transform", Some(k), t.Transform3x4, 48));
            }
        } else if g.Type == D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS {
            let a = unsafe { &g.Anonymous.AABBs };
            out.push((
                "aabbs",
                Some(k),
                a.AABBs.StartAddress,
                extent(
                    a.AABBCount,
                    a.AABBs.StrideInBytes,
                    size_of::<D3D12_RAYTRACING_AABB>() as u64,
                ),
            ));
        } else {
            return Err(format!("geometry type {} is not represented", g.Type.0));
        }
    }
    Ok(out)
}

/// How a copy reads buffer `id` at this point of a list whose commands are `commands` (see [`Read::of`]), from
/// what the list's own transitions left it in.
fn access(commands: &[locum_capture::d3d12::Command], id: u64, real: &ID3D12Resource) -> Read {
    let mut known = None;
    let mut enhanced = false;
    for c in commands {
        match c.call {
            "ResourceBarrier" => {
                for b in c.args[0].as_array().into_iter().flatten() {
                    let p = &b["payload"];
                    // A transition, not the first half of a split one.
                    if b["type"] == 0 && b["flags"] != 1 && p["resource"].as_u64() == Some(id) {
                        known = p["after"].as_i64().map(|s| Access::State(s as i32));
                    }
                }
            }
            "Barrier" => enhanced = true,
            _ => {}
        }
    }
    Read::of(known, enhanced, real)
}

/// The predication the list's commands leave set: (buffer, offset, operation).
fn predication(commands: &[locum_capture::d3d12::Command]) -> Option<(u64, u64, i32)> {
    let last = commands.iter().rev().find(|c| c.call == "SetPredication")?;
    let a = &last.args;
    a[0].as_u64()
        .filter(|r| *r != 0)
        .map(|r| (r, a[1].as_u64().unwrap_or(0), a[2].as_i64().unwrap_or(0) as i32))
}

/// After `BuildRaytracingAccelerationStructure(p)` was recorded into the real list `real` (list `data`): its inputs
/// are copied after it (see the module's documentation).
///
/// # Safety
/// `real` is the application's real list, `p` the description it gave.
pub unsafe fn built(
    data: &super::journal::Data,
    real: *mut c_void,
    p: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC,
) {
    if !super::journal::enabled() {
        return;
    }
    let Some(d) = (unsafe { p.as_ref() }) else {
        return;
    };
    let Some(dest) = key(d.DestAccelerationStructureData) else {
        return;
    };
    let description = unsafe { super::values::acceleration_structure_build(p) };
    let (inputs, copy, gather, error) = match unsafe { copy_inputs(data, real, &d.Inputs) } {
        Ok((inputs, copy, gather)) => (inputs, copy, gather, None),
        Err(why) => (Vec::new(), None, None, Some(why)),
    };
    let build = Arc::new(Build {
        dest,
        description,
        inputs,
        error,
        copy,
        gather,
        last: Mutex::new(None),
    });
    state().lists.entry(data.id).or_default().push(Step::Build(build));
}

/// A build's inputs, the copy holding them, and its instances' gather where they are given as an array of pointers.
type Copied = (Vec<Input>, Option<Copy>, Option<super::gather::Gather>);

/// Readback memory of `bytes` for a build's inputs, on the real device of the real list `list`, counted against
/// [`BUDGET`].
unsafe fn readback(list: &ID3D12GraphicsCommandList, bytes: u64) -> Result<(ID3D12Device, Copy), String> {
    if BYTES.fetch_add(bytes, Ordering::AcqRel) + bytes > BUDGET {
        BYTES.fetch_sub(bytes, Ordering::AcqRel);
        return Err(format!(
            "the {} GiB kept of builds' inputs are spent",
            BUDGET >> 30
        ));
    }
    let mut device: Option<ID3D12Device> = None;
    let made = unsafe { list.GetDevice(&mut device) }
        .map_err(|e| e.to_string())
        .and_then(|()| device.ok_or_else(|| "no device".to_string()))
        .and_then(|d| unsafe { super::passes::readback_resource(&d, bytes) }.map(|b| (d, b)));
    match made {
        Ok((device, buffer)) => Ok((device, Copy { buffer, bytes })),
        Err(why) => {
            BYTES.fetch_sub(bytes, Ordering::AcqRel);
            Err(why)
        }
    }
}

unsafe fn copy_inputs(
    data: &super::journal::Data,
    real: *mut c_void,
    i: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
) -> Result<Copied, String> {
    let list = unsafe { ID3D12GraphicsCommandList::from_raw_borrowed(&real) }.ok_or("no list")?;
    let commands = data
        .recording
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .as_ref()
        .map(|r| r.snapshot())
        .ok_or("its list is not recorded")?;
    let commands = &commands.commands;
    if i.Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL
        && i.DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS
    {
        return unsafe { gathered(data, list, commands, i) };
    }
    let ranges = unsafe { ranges(i) }?;
    let mut inputs = Vec::new();
    let mut copies = Vec::new();
    let mut at = 0;
    for (part, geometry, address, bytes) in ranges {
        let (resource, offset) =
            key(address).ok_or_else(|| format!("its {part} are in no live buffer locum knows"))?;
        let real = super::real::<ID3D12Resource>(resource).ok_or("an input buffer was destroyed")?;
        copies.push(super::passes::Source {
            resource,
            read: access(commands, resource, &real),
            real,
            offset,
            bytes,
        });
        inputs.push(Input {
            part,
            geometry,
            resource,
            offset,
            bytes,
            at,
        });
        at += bytes;
    }
    if at == 0 {
        return Ok((inputs, None, None));
    }
    let (_, copy) = unsafe { readback(list, at) }?;
    let predicate = predication(commands)
        .and_then(|(r, offset, op)| super::real::<ID3D12Resource>(r).map(|r| (r, offset, op)));
    let promoted = unsafe {
        super::passes::record_ranges(
            list,
            &copies,
            D3D12_BARRIER_ACCESS_SHADER_RESOURCE,
            predicate,
            &copy.buffer,
        )
    }?;
    promote(data, promoted);
    Ok((inputs, Some(copy), None))
}

/// The buffers a copy of locum's in the list of `data` read by promotion (see [`super::promoted`]).
fn promote(data: &super::journal::Data, promoted: Vec<u64>) {
    if let Some(r) = data.recording.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
        for resource in promoted {
            r.promote(resource);
        }
    }
}

/// A top-level build whose instances are an array of pointers, just recorded into the real list `list` (whose
/// commands so far are `commands`): its pointers copied and its gather made (see [`super::gather`]). Its inputs are
/// the instances, gathered into an array, and the pointers.
unsafe fn gathered(
    data: &super::journal::Data,
    list: &ID3D12GraphicsCommandList,
    commands: &[locum_capture::d3d12::Command],
    i: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
) -> Result<Copied, String> {
    let count = u64::from(i.NumDescs);
    if count == 0 {
        return Ok((Vec::new(), None, None));
    }
    if predication(commands).is_some() {
        return Err(
            "its build is predicated (SetPredication), so locum does not know whether it ran, nor gathers its \
             instances, which are given as an array of pointers"
                .into(),
        );
    }
    let address = unsafe { i.Anonymous.InstanceDescs };
    let (resource, offset) = key(address).ok_or("its instance pointers are in no live buffer locum knows")?;
    let real =
        super::real::<ID3D12Resource>(resource).ok_or("its instance pointers' buffer was destroyed")?;
    let source = super::passes::Source {
        resource,
        read: access(commands, resource, &real),
        real,
        offset,
        bytes: count * 8,
    };
    let (device, copy) = unsafe { readback(list, super::gather::bytes(count)) }?;
    let instances = count * size_of::<D3D12_RAYTRACING_INSTANCE_DESC>() as u64;
    let inputs = vec![
        Input {
            part: "instances",
            geometry: None,
            resource,
            offset,
            bytes: instances,
            at: 0,
        },
        Input {
            part: "pointers",
            geometry: None,
            resource,
            offset,
            bytes: count * 8,
            at: instances,
        },
    ];
    let (gather, promoted) = unsafe {
        super::gather::prepare(
            &device,
            list,
            source,
            i.NumDescs,
            commands.len().saturating_sub(1),
        )
    }?;
    promote(data, promoted);
    Ok((inputs, Some(copy), Some(gather)))
}

/// After `CopyRaytracingAccelerationStructure(dest, source, mode)` was recorded into list `list`.
pub fn copied(list: u64, dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE) {
    if !super::journal::enabled() {
        return;
    }
    if let (Some(dest), Some(source)) = (key(dest), key(source)) {
        state()
            .lists
            .entry(list)
            .or_default()
            .push(Step::Copy(dest, source, mode.0));
    }
}

/// List `list` was reset or destroyed: its builds no longer run again.
pub fn retire(list: u64) {
    let mut s = state();
    if let Some(steps) = s.lists.remove(&list) {
        for step in steps {
            if let Step::Build(b) = step {
                s.leaving.push(b);
            }
        }
    }
    sweep(&mut s);
}

/// Frees the copies no acceleration structure's latest build and no list holds, once the GPU is done with them.
fn sweep(s: &mut State) {
    s.leaving.retain(|b| Arc::strong_count(b) > 1 || !b.done());
}

/// Resource `id` was destroyed: the acceleration structures in it go.
pub fn destroyed(id: u64) {
    let mut s = state();
    let gone: Vec<Key> = s.latest.keys().filter(|k| k.0 == id).copied().collect();
    for k in gone {
        if let Some(b) = s.latest.remove(&k) {
            s.leaving.push(b);
        }
    }
}

/// Lists `lists` are being executed, in this order: their builds and copies take effect. The builds they hold,
/// which [`submitted`] marks with locum's fence.
pub fn executing(lists: &[u64]) -> Vec<Arc<Build>> {
    let mut guard = state();
    let State {
        lists: steps,
        latest,
        leaving,
    } = &mut *guard;
    let mut builds = Vec::new();
    for step in lists.iter().flat_map(|l| steps.get(l)).flatten() {
        let (dest, now) = match step {
            Step::Build(b) => {
                builds.push(b.clone());
                (b.dest, Some(b.clone()))
            }
            // A clone or compaction is its source as built.
            Step::Copy(dest, source, mode)
                if *mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE.0
                    || *mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT.0 =>
            {
                (*dest, latest.get(source).cloned())
            }
            // Deserialized from bytes, or not an acceleration structure (serialized, visualized): no build of it.
            Step::Copy(dest, ..) => (*dest, None),
        };
        let replaced = match now {
            Some(b) => latest.insert(dest, b),
            None => latest.remove(&dest),
        };
        leaving.extend(replaced);
    }
    sweep(&mut guard);
    builds
}

/// The gathers the application lists `lists` (each with its place in the application's array) make once
/// submitted, by that place: their builds whose instances are an array of pointers, each with what its list does
/// after it (see [`super::gather::analyse`]), decided at its first submission. Builds no gather can read for are left
/// out: their reads say why.
pub fn gathers(lists: &[(usize, &locum_capture::d3d12::List)]) -> Vec<(usize, Vec<Arc<Build>>)> {
    let s = state();
    let mut out = Vec::new();
    for &(at, list) in lists {
        let builds: Vec<Arc<Build>> = s
            .lists
            .get(&list.id)
            .into_iter()
            .flatten()
            .filter_map(|step| match step {
                Step::Build(b) => b.gather.as_ref().map(|g| (b, g)),
                Step::Copy(..) => None,
            })
            .filter(|(_, g)| {
                g.analysis
                    .get_or_init(|| super::gather::analyse(&list.commands, g.at, &super::slots::buffer_range))
                    .is_ok()
            })
            .map(|(b, _)| b.clone())
            .collect();
        if !builds.is_empty() {
            out.push((at, builds));
        }
    }
    out
}

/// Records into locum's list `list` the gathers of `builds` (of one application list, from [`gathers`]).
///
/// # Safety
/// `list` is a real list of locum's open for recording, on the builds' device, submitted right after their list.
pub unsafe fn record_gathers(list: &ID3D12GraphicsCommandList, builds: &[Arc<Build>]) {
    let gathers: Vec<_> = builds
        .iter()
        .filter_map(|b| {
            let g = b.gather.as_ref()?;
            let analysis = g.analysis.get()?.as_ref().ok()?;
            Some((g, analysis, &b.copy.as_ref()?.buffer))
        })
        .collect();
    unsafe { super::gather::record(list, &gathers) };
}

/// The latest submission of `builds` made their gathers, or did not, for `why`.
pub fn gathered_at_submission(builds: &[Arc<Build>], why: Option<&str>) {
    for b in builds {
        if let Some(g) = &b.gather {
            *g.failed.lock().unwrap_or_else(|e| e.into_inner()) = why.map(str::to_string);
        }
    }
}

/// After the lists holding `builds` were submitted to the real queue `queue` (number `queue_id`): locum's fence
/// marks when their copies are made.
///
/// # Safety
/// `queue` is the real queue, called right after the application's ExecuteCommandLists on it.
pub unsafe fn submitted(queue_id: u64, queue: *mut c_void, builds: Vec<Arc<Build>>) {
    if builds.is_empty() {
        return;
    }
    match unsafe { super::passes::mark(queue_id, queue) } {
        Ok(marked) => {
            for b in builds {
                *b.last.lock().unwrap_or_else(|e| e.into_inner()) = Some(marked.clone());
            }
        }
        Err(why) => crate::log::log!("D3D12 acceleration structures: {why} on queue {queue_id}"),
    }
}

/// Every acceleration structure's latest build, as a frame begins: a clone's or compaction's is its source's.
pub fn latest() -> Vec<(Key, Arc<Build>)> {
    let s = state();
    let mut all: Vec<_> = s.latest.iter().map(|(k, b)| (*k, b.clone())).collect();
    all.sort_by_key(|(k, _)| *k);
    all
}

/// How long a capture waits for the GPU to have copied a build's inputs.
const PATIENCE: Duration = Duration::from_secs(10);

/// The acceleration structure at `key`, built (or cloned from one built) by `b`, as a capture records it: its
/// inputs' bytes into the blob store.
pub fn record(key: Key, b: &Build) -> locum_capture::d3d12::AccelerationStructure {
    let inputs = b.read(PATIENCE).map(|parts| {
        let blobs = &crate::settings::settings().blobs;
        Value::Array(
            b.inputs
                .iter()
                .zip(parts)
                .map(|(i, bytes)| {
                    let hash = locum_capture::hash::key(&bytes);
                    locum_capture::writer::blob(blobs, hash.clone(), bytes, true);
                    serde_json::json!({"part":i.part,"geometry":i.geometry,"resource":i.resource,"offset":i.offset,
                        "bytes":i.bytes,"blob":hash})
                })
                .collect(),
        )
    });
    locum_capture::d3d12::AccelerationStructure {
        resource: key.0,
        offset: key.1,
        build: b.description.clone(),
        inputs,
    }
}