Skip to main content

mln_engine/render/
update_slot.rs

1//! The map's latest update for the renderer that draws it.
2//!
3//! The map publishes an [`UpdateParameters`] after each change that a frame
4//! shows, and a renderer, on the map's thread or another, draws the latest
5//! one it finds. An update replaces the one before it, whether or not a
6//! renderer drew that one, and the slot keeps the latest while no renderer
7//! reads it.
8//!
9//! A command group holds the updates back: while one is open, what the map
10//! publishes waits, and the latest of it shows when the outermost group ends.
11//! A hold, which the map's owner sets apart from the groups, does the same.
12
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU64, Ordering};
15
16use mln_style::error::Error;
17use parking_lot::Mutex;
18
19use crate::exec::event_queue::Waker;
20use crate::render::update_parameters::UpdateParameters;
21
22/// An update that a slot published.
23#[derive(Clone)]
24pub struct Update {
25    /// Counts the updates that the slot published, this one included.
26    pub generation: u64,
27    pub parameters: Arc<UpdateParameters>,
28}
29
30#[derive(Default)]
31struct State {
32    generation: u64,
33    latest: Option<Arc<UpdateParameters>>,
34    /// The latest update published while a group or the hold was open.
35    held: Option<Arc<UpdateParameters>>,
36    group_depth: u32,
37    hold: bool,
38    closed: bool,
39}
40
41#[derive(Default)]
42struct Shared {
43    state: Mutex<State>,
44    /// The readers' wakers, by reader.
45    wakers: Mutex<Vec<(u64, Waker)>>,
46    next_reader: AtomicU64,
47}
48
49impl Shared {
50    fn reader(self: &Arc<Self>) -> UpdateReader {
51        UpdateReader { shared: Arc::clone(self), id: self.next_reader.fetch_add(1, Ordering::Relaxed) }
52    }
53
54    /// Runs the wakers, with nothing locked.
55    fn wake(&self) {
56        let wakers: Vec<Waker> = self.wakers.lock().iter().map(|(_, waker)| Arc::clone(waker)).collect();
57        for waker in wakers {
58            waker();
59        }
60    }
61}
62
63/// The writing side, which the map owns. Dropping it closes the slot: its
64/// readers see no update from then on.
65#[derive(Default)]
66pub struct UpdateSlot {
67    shared: Arc<Shared>,
68}
69
70// The map and a renderer on another thread share the slot.
71const _: () = {
72    const fn assert_send_sync<T: Send + Sync>() {}
73    assert_send_sync::<UpdateSlot>();
74    assert_send_sync::<UpdateReader>();
75};
76
77impl UpdateSlot {
78    #[must_use]
79    pub(crate) fn new() -> Self {
80        Self::default()
81    }
82
83    /// A reader of this slot's updates.
84    #[must_use]
85    pub(crate) fn reader(&self) -> UpdateReader {
86        self.shared.reader()
87    }
88
89    /// Makes `parameters` the latest update, or, while a group or the hold
90    /// is open, the update that shows when the last of them ends.
91    pub(crate) fn publish(&self, parameters: Arc<UpdateParameters>) {
92        {
93            let mut state = self.shared.state.lock();
94            if state.group_depth > 0 || state.hold {
95                state.held = Some(parameters);
96                return;
97            }
98            Self::show(&mut state, parameters);
99        }
100        self.shared.wake();
101    }
102
103    fn show(state: &mut State, parameters: Arc<UpdateParameters>) {
104        state.generation += 1;
105        state.latest = Some(parameters);
106    }
107
108    /// Counts the updates that readers could see.
109    #[must_use]
110    pub(crate) fn generation(&self) -> u64 {
111        self.shared.state.lock().generation
112    }
113
114    /// The generation of the update that shows what was published last:
115    /// the current one, or while a group holds an update back, the one its
116    /// end shows.
117    #[must_use]
118    pub(crate) fn pending_generation(&self) -> u64 {
119        let state = self.shared.state.lock();
120        state.generation + u64::from(state.held.is_some())
121    }
122
123    /// Opens a command group. Groups nest.
124    pub(crate) fn begin_group(&self) {
125        self.shared.state.lock().group_depth += 1;
126    }
127
128    /// Closes the innermost command group. When it was the outermost, the
129    /// latest update published inside it shows. Fails with
130    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when no group is
131    /// open.
132    pub(crate) fn end_group(&self) -> Result<(), Error> {
133        let shown = {
134            let mut state = self.shared.state.lock();
135            if state.group_depth == 0 {
136                return Err(Error::invalid_state("the map has no open command group"));
137            }
138            state.group_depth -= 1;
139            Self::show_held(&mut state)
140        };
141        if shown {
142            self.shared.wake();
143        }
144        Ok(())
145    }
146
147    /// Shows the held update once neither a group nor the hold keeps it.
148    fn show_held(state: &mut State) -> bool {
149        if state.group_depth > 0 || state.hold {
150            return false;
151        }
152        let Some(parameters) = state.held.take() else { return false };
153        Self::show(state, parameters);
154        true
155    }
156
157    /// Holds the updates back, as a group does, until
158    /// [`release`](Self::release). It doesn't nest, and it doesn't count
159    /// as a group.
160    pub(crate) fn hold(&self) {
161        self.shared.state.lock().hold = true;
162    }
163
164    /// Ends the hold: the latest update published during it shows, unless
165    /// a group still holds it.
166    pub(crate) fn release(&self) {
167        let shown = {
168            let mut state = self.shared.state.lock();
169            state.hold = false;
170            Self::show_held(&mut state)
171        };
172        if shown {
173            self.shared.wake();
174        }
175    }
176
177    /// How many command groups are open.
178    #[must_use]
179    pub(crate) fn group_depth(&self) -> u32 {
180        self.shared.state.lock().group_depth
181    }
182}
183
184impl Drop for UpdateSlot {
185    fn drop(&mut self) {
186        {
187            let mut state = self.shared.state.lock();
188            state.closed = true;
189            state.latest = None;
190            state.held = None;
191        }
192        self.shared.wake();
193    }
194}
195
196/// The reading side of an [`UpdateSlot`], for the renderer that draws the
197/// map. Clones read the same slot, each with a waker of its own.
198pub struct UpdateReader {
199    shared: Arc<Shared>,
200    id: u64,
201}
202
203impl Clone for UpdateReader {
204    /// Another reader of the same slot, without a waker.
205    fn clone(&self) -> Self {
206        self.shared.reader()
207    }
208}
209
210impl Drop for UpdateReader {
211    fn drop(&mut self) {
212        self.set_waker(None);
213    }
214}
215
216impl UpdateReader {
217    /// The latest update, if the map published one and is still there.
218    #[must_use]
219    pub fn latest(&self) -> Option<Update> {
220        let state = self.shared.state.lock();
221        let parameters = state.latest.clone()?;
222        Some(Update { generation: state.generation, parameters })
223    }
224
225    /// The generation of the latest update, or 0 before the first.
226    #[must_use]
227    pub fn generation(&self) -> u64 {
228        self.shared.state.lock().generation
229    }
230
231    /// Whether the map that published to the slot is gone.
232    #[must_use]
233    pub fn is_closed(&self) -> bool {
234        self.shared.state.lock().closed
235    }
236
237    /// Sets the waker that runs when an update shows or the slot closes,
238    /// until the reader drops. It runs on the map's thread, with the slot
239    /// unlocked, and schedules the reader's work rather than drawing there.
240    pub fn set_waker(&self, waker: Option<Waker>) {
241        let mut wakers = self.shared.wakers.lock();
242        wakers.retain(|(id, _)| *id != self.id);
243        if let Some(waker) = waker {
244            wakers.push((self.id, waker));
245        }
246    }
247
248    /// Whether both read the same slot.
249    #[must_use]
250    pub fn ptr_eq(&self, other: &UpdateReader) -> bool {
251        Arc::ptr_eq(&self.shared, &other.shared)
252    }
253}