nsi_intermediate/recorder/mod.rs
1//! The ɴsɪ recorder.
2//!
3//! `Nsi` takes `&self` everywhere, so the scene lives behind a
4//! `parking_lot::Mutex` -- which has no poisoning, so reading the scene
5//! back after a panic in one of these methods is not a `Result`.
6
7use crate::{OwnedArgument, OwnedData, RecordError, Scene};
8use nsi_ffi_wrap::Arg;
9use nsi_trait::{Action, Nsi};
10use parking_lot::{Mutex, MutexGuard};
11
12/// Where the render is in its lifecycle.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14pub enum RenderState {
15 /// Not rendering. The state before `Start` and after `Stop`.
16 #[default]
17 Idle,
18 /// Rendering.
19 Running,
20 /// Started, then suspended. `Resume` returns it to
21 /// [`RenderState::Running`].
22 Suspended,
23}
24
25/// Records an ɴsɪ scene without rendering it.
26///
27/// # Why there is no context lifetime
28///
29/// [`nsi_ffi_wrap::Context`] carries a `'a` bounding the borrowed data
30/// handed to it through `Reference`, `ReferenceSlice` and `Callback`.
31/// The recorder does not, and the difference is real rather than an
32/// oversight: `Context` stores no pointers -- its `'a` is a `PhantomData`
33/// marker and the renderer holds the data -- whereas the recorder
34/// *retains* those addresses so they survive to replay.
35///
36/// Retaining them while also being `Send + Sync`, which [`Nsi`]
37/// requires, is only sound if the pointees outlive every thread that
38/// could see them. So the `Arg` GAT is pinned to `'static` and a
39/// lifetime parameter would be vestigial: it could only ever be
40/// `'static`. This matches `nsi-ffi-wrap`, where `Reference`,
41/// `Callback` and `ReferenceSlice` are `Send`/`Sync` at `'static` and
42/// nowhere else.
43///
44/// In practice this costs nothing. ɴsɪ `Reference` carries output-driver
45/// callbacks and similar host state, which is long-lived by nature.
46#[derive(Debug, Default)]
47pub struct Recorder {
48 scene: Mutex<Scene>,
49 state: Mutex<RenderState>,
50}
51
52impl Recorder {
53 /// An empty recorder.
54 pub fn new() -> Self {
55 Self::default()
56 }
57
58 /// Borrow the recorded scene.
59 ///
60 /// # Deadlock
61 ///
62 /// The guard holds the only lock every [`Nsi`] method takes. Calling
63 /// one on the same recorder while a guard is alive deadlocks the
64 /// calling thread. Drop the guard, or scope it, before recording
65 /// again.
66 pub fn scene(&self) -> MutexGuard<'_, Scene> {
67 self.scene.lock()
68 }
69
70 /// Take the recorded scene, consuming the recorder.
71 ///
72 /// The alternative is `scene().clone()`, which deep-copies every
73 /// vertex buffer in the scene. A backend that is done recording
74 /// wants this one.
75 ///
76 /// # Panics
77 ///
78 /// If the scene mutex was poisoned by a panic while recording.
79 pub fn into_scene(self) -> Scene {
80 self.scene.into_inner()
81 }
82
83 /// The current render state.
84 pub fn render_state(&self) -> RenderState {
85 *self.state.lock()
86 }
87
88 fn own(args: &[Arg<'_, 'static>]) -> Vec<OwnedArgument> {
89 args.iter().map(OwnedArgument::from_param).collect()
90 }
91}
92
93impl Nsi for Recorder {
94 /// `'call` is the transient borrow. The context-bound lifetime is
95 /// `'static`; see the type's documentation for why.
96 type Arg<'call> = Arg<'call, 'static>;
97 type Error = RecordError;
98
99 fn create(
100 &self,
101 handle: &str,
102 node_type: &str,
103 _args: Option<&[Self::Arg<'_>]>,
104 ) -> Result<(), Self::Error> {
105 self.scene().create(handle, node_type)
106 }
107
108 /// `args` is read for ɴsɪ's `"recursive"`.
109 fn delete(
110 &self,
111 handle: &str,
112 args: Option<&[Self::Arg<'_>]>,
113 ) -> Result<(), Self::Error> {
114 let recursive = args
115 .unwrap_or_default()
116 .iter()
117 .map(OwnedArgument::from_param)
118 .find(|arg| arg.name == "recursive")
119 .is_some_and(|arg| match &arg.data {
120 OwnedData::I32(values) => {
121 values.first().is_some_and(|v| *v != 0)
122 }
123 _ => false,
124 });
125
126 if recursive {
127 self.scene().delete_recursive(handle)
128 } else {
129 self.scene().delete(handle)
130 }
131 }
132
133 fn set_attribute(
134 &self,
135 handle: &str,
136 args: &[Self::Arg<'_>],
137 ) -> Result<(), Self::Error> {
138 let owned = Self::own(args);
139 self.scene().set_attribute(handle, owned)
140 }
141
142 fn set_attribute_at_time(
143 &self,
144 handle: &str,
145 time: f64,
146 args: &[Self::Arg<'_>],
147 ) -> Result<(), Self::Error> {
148 let owned = Self::own(args);
149 self.scene().set_attribute_at_time(handle, time, owned)
150 }
151
152 fn delete_attribute(
153 &self,
154 handle: &str,
155 name: &str,
156 ) -> Result<(), Self::Error> {
157 self.scene().delete_attribute(handle, name);
158 Ok(())
159 }
160
161 /// Every connection argument is recorded. Resolution reads only
162 /// `"priority"`, but `"strength"` and `"value"` survive for a
163 /// backend that wants them, and for replay.
164 fn connect(
165 &self,
166 from: &str,
167 from_attribute: Option<&str>,
168 to: &str,
169 to_attribute: &str,
170 args: Option<&[Self::Arg<'_>]>,
171 ) -> Result<(), Self::Error> {
172 let args = args.map(Self::own).unwrap_or_default();
173 self.scene().connect_with_arguments(
174 from,
175 from_attribute,
176 to,
177 to_attribute,
178 args,
179 )
180 }
181
182 fn disconnect(
183 &self,
184 from: &str,
185 from_attribute: Option<&str>,
186 to: &str,
187 to_attribute: &str,
188 ) -> Result<(), Self::Error> {
189 self.scene()
190 .disconnect(from, from_attribute, to, to_attribute)
191 }
192
193 fn evaluate(&self, args: &[Self::Arg<'_>]) -> Result<(), Self::Error> {
194 // Not executed -- an archive, Lua script or compiled procedural
195 // implies an execution model this crate does not define -- but
196 // recorded. Dropping it meant a stream carrying `Evaluate` came
197 // back as a scene missing whatever it would have produced, with
198 // no error and nothing to show that anything had been asked
199 // for. `Scene::evaluations` hands the call to a backend that
200 // wants to run it.
201 self.scene().evaluate(Self::own(args));
202 Ok(())
203 }
204
205 fn render_control(
206 &self,
207 action: Action,
208 _args: Option<&[Self::Arg<'_>]>,
209 ) -> Result<(), Self::Error> {
210 let mut state = self.state.lock();
211 *state = match (action, *state) {
212 (Action::Start, _) => RenderState::Running,
213 (Action::Suspend, RenderState::Running) => RenderState::Suspended,
214 (Action::Resume, RenderState::Suspended) => RenderState::Running,
215 (Action::Stop, _) => RenderState::Idle,
216 // Wait and Synchronize are not transitions: a recorder has
217 // nothing to wait for, and synchronising an unrendered scene
218 // is a no-op.
219 (_, current) => current,
220 };
221 Ok(())
222 }
223}
224
225#[cfg(test)]
226mod tests;