Skip to main content

oxframe_core/
runtime.rs

1//! Per-thread context of the scene being executed.
2//!
3//! The [`Executor`](crate::Executor) installs its runtime for the duration
4//! of each step, so free functions like [`now`] and [`wait_until`]
5//! (crate::wait_until) work inside scene code without passing handles.
6
7use std::cell::{Cell, RefCell};
8use std::rc::Rc;
9
10use oxframe_protocol::Meta;
11use rand::SeedableRng;
12use rand_chacha::ChaCha8Rng;
13
14use crate::CubicBezier;
15use crate::ease::presets;
16use crate::flow::Task;
17use crate::transition::Recorded;
18
19pub(crate) struct Runtime {
20    pub fps: f64,
21    pub frame: Cell<u32>,
22    /// Virtual time of the task being polled. It can lag behind the frame
23    /// time by a fraction of a frame: when a tween ends between frames, the
24    /// next tween starts at the exact end time, so timings do not drift.
25    pub task_time: Cell<f64>,
26    pub spawned: RefCell<Vec<Task>>,
27    pub meta: RefCell<Meta>,
28    pub meta_changed: Cell<bool>,
29    pub rng: RefCell<ChaCha8Rng>,
30    /// Set by the engine: this scene has one before it, so a transition blends.
31    pub has_previous: Cell<bool>,
32    /// The transition declared by the scene, if it starts one.
33    pub transition: RefCell<Option<Recorded>>,
34    /// Sound effects scheduled by `sound()`, in scene time.
35    pub sounds: RefCell<Vec<crate::SoundClip>>,
36}
37
38impl Runtime {
39    pub fn new(fps: f64, meta: Meta, seed: u64) -> Rc<Self> {
40        assert!(fps > 0.0 && fps.is_finite(), "fps must be positive");
41        Rc::new(Self {
42            fps,
43            frame: Cell::new(0),
44            task_time: Cell::new(0.0),
45            spawned: RefCell::new(Vec::new()),
46            meta: RefCell::new(meta),
47            meta_changed: Cell::new(false),
48            rng: RefCell::new(ChaCha8Rng::seed_from_u64(seed)),
49            has_previous: Cell::new(false),
50            transition: RefCell::new(None),
51            sounds: RefCell::new(Vec::new()),
52        })
53    }
54
55    pub fn now(&self) -> f64 {
56        f64::from(self.frame.get()) / self.fps
57    }
58}
59
60thread_local! {
61    static CURRENT: RefCell<Option<Rc<Runtime>>> = const { RefCell::new(None) };
62}
63
64/// Restores the previously installed runtime on drop.
65pub(crate) struct Installed(Option<Rc<Runtime>>);
66
67pub(crate) fn install(rt: &Rc<Runtime>) -> Installed {
68    Installed(CURRENT.with(|c| c.borrow_mut().replace(rt.clone())))
69}
70
71impl Drop for Installed {
72    fn drop(&mut self) {
73        let prev = self.0.take();
74        CURRENT.with(|c| *c.borrow_mut() = prev);
75    }
76}
77
78pub(crate) fn with<R>(f: impl FnOnce(&Runtime) -> R) -> R {
79    CURRENT.with(|c| {
80        let c = c.borrow();
81        let rt = c
82            .as_ref()
83            .expect("oxframe: this function can only be called while a scene is running");
84        f(rt)
85    })
86}
87
88/// Index of the frame being computed.
89pub fn frame() -> u32 {
90    with(|rt| rt.frame.get())
91}
92
93/// Frames per second of the running project.
94pub fn fps() -> f64 {
95    with(|rt| rt.fps)
96}
97
98/// Duration of one frame in seconds, `1 / fps`.
99pub fn dt() -> f64 {
100    with(|rt| 1.0 / rt.fps)
101}
102
103/// Time of the current frame, `frame / fps` seconds.
104pub fn now() -> f64 {
105    with(|rt| rt.now())
106}
107
108/// Whether the running scene has a scene before it.
109pub fn has_previous() -> bool {
110    with(|rt| rt.has_previous.get())
111}
112
113/// Records `spec`, letting `meta.json` override its duration the way markers
114/// do. Returns the duration to wait. Panics if the scene already started one.
115pub fn begin_transition(mut spec: Recorded) -> f64 {
116    with(|rt| {
117        if rt.transition.borrow().is_some() {
118            panic!("oxframe: a scene can declare only one transition; call it once, at the start");
119        }
120        let stored = rt.meta.borrow().transition.as_ref().map(|t| t.seconds);
121        if let Some(seconds) = stored {
122            spec.seconds = if seconds.is_finite() {
123                seconds.max(0.0)
124            } else {
125                0.0
126            };
127        } else if spec.seconds.is_finite() && spec.seconds > 0.0 {
128            let seconds = spec.seconds;
129            rt.meta.borrow_mut().transition = Some(oxframe_protocol::TransitionMeta { seconds });
130            rt.meta_changed.set(true);
131        } else {
132            spec.seconds = 0.0;
133        }
134        let seconds = spec.seconds;
135        if seconds > 0.0 {
136            *rt.transition.borrow_mut() = Some(spec);
137        }
138        seconds
139    })
140}
141
142/// Virtual time of the current task — where the next animation starts.
143pub fn time() -> f64 {
144    with(|rt| rt.task_time.get())
145}
146
147/// Value of tunable `name` from `meta.json`; `default` is recorded there on
148/// first use. Use through the `tune!` macro.
149pub fn tunable(name: &str, default: f64) -> f64 {
150    with(|rt| {
151        let mut meta = rt.meta.borrow_mut();
152        if let Some(v) = meta.tunables.get(name) {
153            return *v;
154        }
155        meta.tunables.insert(name.to_owned(), default);
156        rt.meta_changed.set(true);
157        default
158    })
159}
160
161/// Named easing from `meta.json`; `default` is recorded there on first use.
162/// Use through the `ease!` macro.
163pub fn ease_named(name: &str, default: Option<CubicBezier>) -> CubicBezier {
164    with(|rt| {
165        let mut meta = rt.meta.borrow_mut();
166        if let Some(v) = meta.eases.get(name) {
167            return CubicBezier::from_array(*v);
168        }
169        let default = default.unwrap_or(presets::DEFAULT);
170        meta.eases.insert(name.to_owned(), default.to_array());
171        rt.meta_changed.set(true);
172        default
173    })
174}
175
176/// Marker time from `meta.json`; the current task time is recorded on first
177/// encounter.
178pub(crate) fn marker(name: &str) -> f64 {
179    with(|rt| {
180        let mut meta = rt.meta.borrow_mut();
181        if let Some(v) = meta.markers.get(name) {
182            return *v;
183        }
184        let t = rt.task_time.get();
185        meta.markers.insert(name.to_owned(), t);
186        rt.meta_changed.set(true);
187        t
188    })
189}
190
191/// Copy of the running scene's markers, eases and tunables.
192pub fn meta_snapshot() -> Meta {
193    with(|rt| rt.meta.borrow().clone())
194}
195
196/// Runs `f` with the scene's random generator. It is seeded from the
197/// project seed and the scene name, so results are reproducible; never use
198/// `rand::rng()` or other entropy sources in scenes.
199pub fn with_rng<R>(f: impl FnOnce(&mut ChaCha8Rng) -> R) -> R {
200    with(|rt| f(&mut rt.rng.borrow_mut()))
201}
202
203/// Uniform random number in `[0, 1)` from the scene's seeded generator.
204pub fn random() -> f64 {
205    use rand::RngExt;
206    with_rng(|r| r.random::<f64>())
207}
208
209/// Uniform random number in `[min, max)` from the scene's seeded generator.
210pub fn random_range(min: f64, max: f64) -> f64 {
211    min + (max - min) * random()
212}
213
214/// A generator seeded by the caller. Drawing with this does not advance the
215/// scene's [`random`] generator, and the same seed always yields the same
216/// sequence, including after a seek.
217#[derive(Clone)]
218pub struct SeededRng(ChaCha8Rng);
219
220impl SeededRng {
221    /// Generator for `seed`. The same seed is the same sequence.
222    pub fn new(seed: u64) -> Self {
223        Self(ChaCha8Rng::seed_from_u64(seed))
224    }
225
226    /// Uniform number in `[0, 1)`.
227    pub fn next_f64(&mut self) -> f64 {
228        use rand::RngExt;
229        self.0.random::<f64>()
230    }
231
232    /// Uniform number in `span` (`end` is excluded).
233    pub fn range(&mut self, span: std::ops::Range<f64>) -> f64 {
234        let w = span.end - span.start;
235        span.start + w * self.next_f64()
236    }
237}