oxframe 0.5.0

Procedural animation in Rust: scenes are coroutines, frames are await points
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
use std::fmt;
use std::path::PathBuf;
use std::rc::Rc;

use oxframe_2d::{SceneGraph, View};
use oxframe_core::Executor;
use oxframe_protocol::{MarkerInfo, Meta, MetaError, SceneInfo};
use oxframe_render::{Image, RenderOptions, Renderer};

use crate::{Project, SceneDef};

/// Why a project could not be loaded.
#[derive(Debug)]
pub enum EngineError {
    /// A `meta.json` file is invalid.
    Meta {
        /// The file.
        path: PathBuf,
        /// What is wrong with it.
        error: MetaError,
    },
    /// A file could not be read or written.
    Io {
        /// The file.
        path: PathBuf,
        /// The I/O error.
        error: std::io::Error,
    },
    /// `Project::scene` was never called.
    NoScenes,
}

impl fmt::Display for EngineError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Meta { path, error } => write!(f, "{}: {error}", path.display()),
            Self::Io { path, error } => write!(f, "{}: {error}", path.display()),
            Self::NoScenes => write!(f, "the project has no scenes"),
        }
    }
}

impl std::error::Error for EngineError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Meta { error, .. } => Some(error),
            Self::Io { error, .. } => Some(error),
            Self::NoScenes => None,
        }
    }
}

/// A section of `meta.json`, for [`Engine::edit_meta`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetaSection {
    /// `markers`.
    Markers,
    /// `eases`.
    Eases,
    /// `tunables`.
    Tunables,
}

impl MetaSection {
    fn singular(self) -> &'static str {
        match self {
            Self::Markers => "marker",
            Self::Eases => "ease",
            Self::Tunables => "tunable",
        }
    }
}

/// One execution of a scene: its graph and executor.
struct SceneRun {
    graph: Rc<SceneGraph>,
    exec: Executor,
    theme: oxframe_2d::Theme,
}

impl SceneRun {
    fn new(def: &SceneDef, project: &Project, meta: Meta) -> Self {
        let graph = SceneGraph::new(project.size.0, project.size.1);
        let fut = (def.factory)(View::current());
        Self {
            graph,
            exec: Executor::new(
                f64::from(project.fps),
                meta,
                scene_seed(project.seed, def.name),
                fut,
            ),
            theme: project.theme.clone(),
        }
    }

    fn step(&mut self) -> bool {
        let theme = self.theme.clone();
        oxframe_2d::enter_theme(&theme, || {
            let Self { graph, exec, .. } = self;
            graph.enter(|| exec.step())
        })
    }

    /// Index of the last computed frame, if any.
    fn last_frame(&self) -> Option<u32> {
        self.exec.frames_done().checked_sub(1)
    }
}

struct SceneState {
    def: SceneDef,
    meta: Meta,
    meta_path: PathBuf,
    start: u32,
    frames: u32,
    run: Option<SceneRun>,
}

/// Runs a [`Project`]: knows the length of every scene and produces the
/// state of any global frame.
///
/// Seeking backwards re-simulates the scene from frame 0 without rendering;
/// seeking forwards continues from the current state.
pub struct Engine {
    project: Project,
    scenes: Vec<SceneState>,
}

impl Engine {
    /// Loads the metas and runs every scene once to find its length.
    ///
    /// # Errors
    ///
    /// If a `meta.json` cannot be read or is invalid, or there are no scenes.
    pub fn new(project: Project) -> Result<Self, EngineError> {
        if project.scenes.is_empty() {
            return Err(EngineError::NoScenes);
        }
        let mut scenes = Vec::with_capacity(project.scenes.len());
        for def in &project.scenes {
            let meta_path = match &project.meta_dir {
                Some(dir) => dir.join(format!("{}.meta.json", def.name)),
                None => def.meta_path(),
            };
            let meta = match &project.inline_meta {
                Some(m) => m.get(def.name).cloned().unwrap_or_default(),
                None => load_meta(&meta_path)?,
            };
            scenes.push(SceneState {
                def: *def,
                meta,
                meta_path,
                start: 0,
                frames: 0,
                run: None,
            });
        }
        // The soundtrack is project-wide; its offset lives in the first
        // scene's meta.
        if let Some(file) = &project.audio
            && let Some(first) = scenes.first_mut()
            && first.meta.audio.as_ref().is_none_or(|a| &a.file != file)
        {
            let offset = first.meta.audio.as_ref().map_or(0.0, |a| a.offset);
            first.meta.audio = Some(oxframe_protocol::AudioMeta {
                file: file.clone(),
                offset,
                extra: Default::default(),
            });
            if project.write_meta && project.inline_meta.is_none() {
                save_meta(&first.meta_path, &first.meta)?;
            }
        }
        let mut engine = Self { project, scenes };
        for i in 0..engine.scenes.len() {
            engine.measure(i)?;
        }
        engine.layout();
        Ok(engine)
    }

    /// The project definition.
    pub fn project(&self) -> &Project {
        &self.project
    }

    /// Runs scene `i` to completion to learn its length and to record
    /// defaults (markers, eases, tunables) into its meta.
    fn measure(&mut self, i: usize) -> Result<(), EngineError> {
        let max = (self.project.max_scene_seconds * f64::from(self.project.fps)).ceil() as u32;
        let scene = &mut self.scenes[i];
        let mut run = SceneRun::new(&scene.def, &self.project, scene.meta.clone());
        while !run.step() && run.exec.frames_done() < max.max(1) {}
        scene.frames = run.exec.frames_done();
        if run.exec.take_meta_changed() {
            scene.meta = run.exec.meta();
            if self.project.write_meta && self.project.inline_meta.is_none() {
                save_meta(&scene.meta_path, &scene.meta)?;
            }
        }
        // Reuse the run: it is positioned at the last frame.
        scene.run = Some(run);
        Ok(())
    }

    fn layout(&mut self) {
        let mut start = 0;
        for s in &mut self.scenes {
            s.start = start;
            start += s.frames;
        }
    }

    /// Frames per second.
    pub fn fps(&self) -> u32 {
        self.project.fps
    }

    /// Project size in pixels.
    pub fn size(&self) -> (u32, u32) {
        self.project.size
    }

    /// Length of all scenes together, in frames.
    pub fn total_frames(&self) -> u32 {
        self.scenes.last().map_or(0, |s| s.start + s.frames)
    }

    /// Scenes with their first frame and length.
    pub fn scenes(&self) -> Vec<SceneInfo> {
        self.scenes
            .iter()
            .map(|s| SceneInfo {
                name: s.def.name.to_owned(),
                start: s.start,
                frames: s.frames,
            })
            .collect()
    }

    /// Markers of all scenes.
    pub fn markers(&self) -> Vec<MarkerInfo> {
        self.scenes
            .iter()
            .flat_map(|s| {
                s.meta.markers.iter().map(|(name, &time)| MarkerInfo {
                    scene: s.def.name.to_owned(),
                    name: name.clone(),
                    time,
                })
            })
            .collect()
    }

    /// Soundtrack file and offset (seconds), if the project has one.
    pub fn audio(&self) -> Option<(String, f64)> {
        let a = self.scenes.first()?.meta.audio.as_ref()?;
        Some((a.file.clone(), a.offset))
    }

    /// Meta of every scene, as `(scene, meta)`.
    pub fn metas(&self) -> Vec<(String, Meta)> {
        self.scenes
            .iter()
            .map(|s| (s.def.name.to_owned(), s.meta.clone()))
            .collect()
    }

    /// Meta of one scene.
    pub fn meta(&self, scene: &str) -> Option<&Meta> {
        self.scenes
            .iter()
            .find(|s| s.def.name == scene)
            .map(|s| &s.meta)
    }

    /// Scene index and local frame of a global frame (clamped to the end).
    pub fn locate(&self, frame: u32) -> (usize, u32) {
        let total = self.total_frames();
        let frame = frame.min(total.saturating_sub(1));
        let i = self
            .scenes
            .iter()
            .rposition(|s| s.start <= frame)
            .unwrap_or(0);
        (i, frame - self.scenes[i].start)
    }

    /// Simulates up to global `frame` and returns the scene graph in that
    /// state. Does not render.
    pub fn seek(&mut self, frame: u32) -> &SceneGraph {
        let (i, local) = self.locate(frame);
        let project = &self.project;
        let scene = &mut self.scenes[i];
        let reusable = scene
            .run
            .as_ref()
            .is_some_and(|r| r.last_frame().is_some_and(|last| last <= local));
        if !reusable {
            scene.run = Some(SceneRun::new(&scene.def, project, scene.meta.clone()));
        }
        let run = scene.run.as_mut().expect("run was just ensured");
        while run.last_frame().is_none_or(|last| last < local) {
            if run.step() {
                break;
            }
        }
        // Drop runs of other scenes; only one graph is alive at a time.
        for (j, s) in self.scenes.iter_mut().enumerate() {
            if j != i {
                s.run = None;
            }
        }
        &self.scenes[i].run.as_ref().expect("run exists").graph
    }

    /// Applies a meta edit to the scene that owns `name` (markers, eases and
    /// tunables are looked up across scenes), re-measures it and saves the
    /// meta. Returns the scene name and its new meta.
    ///
    /// # Errors
    ///
    /// If the scene or name is unknown, the name is invalid, or the meta
    /// cannot be saved.
    pub fn edit_meta(
        &mut self,
        section: MetaSection,
        name: &str,
        scene: Option<&str>,
        apply: impl FnOnce(&mut Meta),
    ) -> Result<(String, Meta), String> {
        let i = match scene {
            Some(scene) => self
                .scenes
                .iter()
                .position(|s| s.def.name == scene)
                .ok_or_else(|| format!("no scene named `{scene}`"))?,
            None => self
                .scenes
                .iter()
                .position(|s| match section {
                    MetaSection::Markers => s.meta.markers.contains_key(name),
                    MetaSection::Eases => s.meta.eases.contains_key(name),
                    MetaSection::Tunables => s.meta.tunables.contains_key(name),
                })
                .ok_or_else(|| format!("no {} named `{name}` in any scene", section.singular()))?,
        };
        let scene = &mut self.scenes[i];
        let mut meta = scene.meta.clone();
        apply(&mut meta);
        meta.validate().map_err(|e| e.to_string())?;
        scene.meta = meta;
        if self.project.write_meta && self.project.inline_meta.is_none() {
            save_meta(&scene.meta_path, &scene.meta).map_err(|e| e.to_string())?;
        }
        scene.run = None;
        self.measure(i).map_err(|e| e.to_string())?;
        self.layout();
        let s = &self.scenes[i];
        Ok((s.def.name.to_owned(), s.meta.clone()))
    }

    /// Converts frame pixels (top-left origin) to scene coordinates.
    pub fn pixels_to_scene(&self, x: f64, y: f64) -> oxframe_core::Point {
        let (w, h) = self.project.size;
        oxframe_core::Point::new(x - f64::from(w) / 2.0, y - f64::from(h) / 2.0)
    }

    /// Simulates up to `frame` and draws it at `size` pixels.
    pub fn render(&mut self, frame: u32, renderer: &mut dyn Renderer, size: (u32, u32)) -> Image {
        let background = self.project.background;
        let graph = self.seek(frame);
        renderer.render(
            graph,
            &RenderOptions {
                width: size.0,
                height: size.1,
                background,
            },
        )
    }
}

/// Per-scene seed: the project seed mixed with an FNV-1a hash of the name,
/// so scenes get independent but reproducible streams.
fn scene_seed(seed: u64, name: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in name.bytes() {
        h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
    }
    seed ^ h
}

fn load_meta(path: &PathBuf) -> Result<Meta, EngineError> {
    match std::fs::read_to_string(path) {
        Ok(text) => Meta::parse(&text).map_err(|error| EngineError::Meta {
            path: path.clone(),
            error,
        }),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Meta::default()),
        Err(error) => Err(EngineError::Io {
            path: path.clone(),
            error,
        }),
    }
}

fn save_meta(path: &PathBuf, meta: &Meta) -> Result<(), EngineError> {
    let text = meta.to_pretty_string();
    if std::fs::read_to_string(path).is_ok_and(|old| old == text) {
        return Ok(());
    }
    // Write through a temp file so an interrupted write never leaves a
    // truncated meta.json behind.
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, &text)
        .and_then(|()| std::fs::rename(&tmp, path))
        .map_err(|error| EngineError::Io {
            path: path.clone(),
            error,
        })
}