Skip to main content

mln_engine/draw/
after_gpu.rs

1//! Work that waits for the GPU to finish what the renderer gave it.
2
3use std::cell::Cell;
4use std::rc::{Rc, Weak};
5
6use mln_gfx::gpu::Gpu;
7
8use crate::log_target;
9
10/// Where a layer queues work that waits for the GPU: what runs once the GPU
11/// finished the work that the renderer gave it so far, or once the
12/// renderer's graphics objects are lost, such as the freeing of what a
13/// layer made with the commands a frame lent it ([`Lent`](super::Lent)).
14///
15/// A layer keeps a clone and pushes to it, typically as it drops, which is
16/// when it leaves the renderer. The renderer runs what was pushed at the end
17/// of its next update, after waiting for the GPU, or as it clears its data,
18/// is torn down or loses its graphics objects.
19#[derive(Clone)]
20pub struct AfterGpu(Weak<Cell<Vec<Work>>>);
21
22/// How the GPU's work that a piece of work after it waited for ended.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum GpuEnd {
25    /// The GPU finished it: what it used can go.
26    Finished,
27    /// The renderer's graphics objects are lost, or may be: what the work
28    /// used is to be forgotten, not destroyed.
29    Lost,
30}
31
32/// A piece of work after the GPU.
33type Work = Box<dyn FnOnce(GpuEnd)>;
34
35impl AfterGpu {
36    /// Runs `work` once the GPU finished the renderer's work so far, or its
37    /// graphics objects are lost, as its argument says; at once, as lost,
38    /// once the renderer went.
39    pub fn push(&self, work: impl FnOnce(GpuEnd) + 'static) {
40        match self.0.upgrade() {
41            Some(queue) => {
42                let mut waiting = queue.take();
43                waiting.push(Box::new(work));
44                queue.set(waiting);
45            }
46            None => work(GpuEnd::Lost),
47        }
48    }
49}
50
51/// The work pushed to the [`AfterGpu`]s of a renderer and not run yet,
52/// which runs as [`GpuEnd::Lost`] if the queue drops first.
53pub(crate) struct AfterGpuQueue {
54    work: Rc<Cell<Vec<Work>>>,
55    handle: AfterGpu,
56}
57
58impl AfterGpuQueue {
59    pub(crate) fn new() -> Self {
60        let work = Rc::default();
61        let handle = AfterGpu(Rc::downgrade(&work));
62        AfterGpuQueue { work, handle }
63    }
64
65    /// A handle that pushes to the queue.
66    pub(crate) fn handle(&self) -> &AfterGpu {
67        &self.handle
68    }
69
70    /// Takes the work that waits, in the order it was pushed. Work that it
71    /// pushes as it runs waits for the next run.
72    fn take(&self) -> Vec<Work> {
73        self.work.take()
74    }
75
76    /// Runs the work that waits, in the order it was pushed, once `gpu`
77    /// finished what the renderer gave it, if any work waits.
78    pub(crate) fn finish(&self, gpu: &mut dyn Gpu) {
79        let work = self.take();
80        if work.is_empty() {
81            return;
82        }
83        if let Err(error) = gpu.flush(true) {
84            log::error!(target: log_target::RENDER, "Waiting for the GPU before the work after it failed: {error}");
85        }
86        for work in work {
87            work(GpuEnd::Finished);
88        }
89    }
90
91    /// Runs the work that waits, in the order it was pushed, as lost, and
92    /// the work that it pushes.
93    pub(crate) fn lose(&self) {
94        loop {
95            let work = self.take();
96            if work.is_empty() {
97                return;
98            }
99            for work in work {
100                work(GpuEnd::Lost);
101            }
102        }
103    }
104}
105
106impl Drop for AfterGpuQueue {
107    fn drop(&mut self) {
108        self.lose();
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use std::cell::RefCell;
115    use std::rc::Rc;
116
117    use super::{AfterGpu, AfterGpuQueue, GpuEnd};
118
119    type Ends = Rc<RefCell<Vec<(&'static str, GpuEnd)>>>;
120
121    /// Pushes to `after` work that records its end as `name`'s in `ends`.
122    fn record(after: &AfterGpu, ends: &Ends, name: &'static str) {
123        let ends = Rc::clone(ends);
124        after.push(move |end| ends.borrow_mut().push((name, end)));
125    }
126
127    #[test]
128    fn work_runs_once_in_order_and_as_lost_once_the_queue_goes() {
129        let ends = Ends::default();
130        let queue = AfterGpuQueue::new();
131        let after = queue.handle().clone();
132        record(&after, &ends, "first");
133        record(&after, &ends, "second");
134        queue.lose();
135        queue.lose();
136        assert_eq!(ends.take(), [("first", GpuEnd::Lost), ("second", GpuEnd::Lost)]);
137
138        record(&after, &ends, "waiting");
139        drop(queue);
140        record(&after, &ends, "late");
141        assert_eq!(ends.take(), [("waiting", GpuEnd::Lost), ("late", GpuEnd::Lost)]);
142    }
143}