1use 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 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 pub has_previous: Cell<bool>,
32 pub transition: RefCell<Option<Recorded>>,
34 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
64pub(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
88pub fn frame() -> u32 {
90 with(|rt| rt.frame.get())
91}
92
93pub fn fps() -> f64 {
95 with(|rt| rt.fps)
96}
97
98pub fn dt() -> f64 {
100 with(|rt| 1.0 / rt.fps)
101}
102
103pub fn now() -> f64 {
105 with(|rt| rt.now())
106}
107
108pub fn has_previous() -> bool {
110 with(|rt| rt.has_previous.get())
111}
112
113pub 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
142pub fn time() -> f64 {
144 with(|rt| rt.task_time.get())
145}
146
147pub 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
161pub 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
176pub(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
191pub fn meta_snapshot() -> Meta {
193 with(|rt| rt.meta.borrow().clone())
194}
195
196pub fn with_rng<R>(f: impl FnOnce(&mut ChaCha8Rng) -> R) -> R {
200 with(|rt| f(&mut rt.rng.borrow_mut()))
201}
202
203pub fn random() -> f64 {
205 use rand::RngExt;
206 with_rng(|r| r.random::<f64>())
207}
208
209pub fn random_range(min: f64, max: f64) -> f64 {
211 min + (max - min) * random()
212}
213
214#[derive(Clone)]
218pub struct SeededRng(ChaCha8Rng);
219
220impl SeededRng {
221 pub fn new(seed: u64) -> Self {
223 Self(ChaCha8Rng::seed_from_u64(seed))
224 }
225
226 pub fn next_f64(&mut self) -> f64 {
228 use rand::RngExt;
229 self.0.random::<f64>()
230 }
231
232 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}