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}
35
36impl Runtime {
37 pub fn new(fps: f64, meta: Meta, seed: u64) -> Rc<Self> {
38 assert!(fps > 0.0 && fps.is_finite(), "fps must be positive");
39 Rc::new(Self {
40 fps,
41 frame: Cell::new(0),
42 task_time: Cell::new(0.0),
43 spawned: RefCell::new(Vec::new()),
44 meta: RefCell::new(meta),
45 meta_changed: Cell::new(false),
46 rng: RefCell::new(ChaCha8Rng::seed_from_u64(seed)),
47 has_previous: Cell::new(false),
48 transition: RefCell::new(None),
49 })
50 }
51
52 pub fn now(&self) -> f64 {
53 f64::from(self.frame.get()) / self.fps
54 }
55}
56
57thread_local! {
58 static CURRENT: RefCell<Option<Rc<Runtime>>> = const { RefCell::new(None) };
59}
60
61pub(crate) struct Installed(Option<Rc<Runtime>>);
63
64pub(crate) fn install(rt: &Rc<Runtime>) -> Installed {
65 Installed(CURRENT.with(|c| c.borrow_mut().replace(rt.clone())))
66}
67
68impl Drop for Installed {
69 fn drop(&mut self) {
70 let prev = self.0.take();
71 CURRENT.with(|c| *c.borrow_mut() = prev);
72 }
73}
74
75pub(crate) fn with<R>(f: impl FnOnce(&Runtime) -> R) -> R {
76 CURRENT.with(|c| {
77 let c = c.borrow();
78 let rt = c
79 .as_ref()
80 .expect("oxframe: this function can only be called while a scene is running");
81 f(rt)
82 })
83}
84
85pub fn frame() -> u32 {
87 with(|rt| rt.frame.get())
88}
89
90pub fn fps() -> f64 {
92 with(|rt| rt.fps)
93}
94
95pub fn dt() -> f64 {
97 with(|rt| 1.0 / rt.fps)
98}
99
100pub fn now() -> f64 {
102 with(|rt| rt.now())
103}
104
105pub fn has_previous() -> bool {
107 with(|rt| rt.has_previous.get())
108}
109
110pub fn begin_transition(mut spec: Recorded) -> f64 {
113 with(|rt| {
114 if rt.transition.borrow().is_some() {
115 panic!("oxframe: a scene can declare only one transition; call it once, at the start");
116 }
117 let stored = rt.meta.borrow().transition.as_ref().map(|t| t.seconds);
118 if let Some(seconds) = stored {
119 spec.seconds = if seconds.is_finite() {
120 seconds.max(0.0)
121 } else {
122 0.0
123 };
124 } else if spec.seconds.is_finite() && spec.seconds > 0.0 {
125 let seconds = spec.seconds;
126 rt.meta.borrow_mut().transition = Some(oxframe_protocol::TransitionMeta { seconds });
127 rt.meta_changed.set(true);
128 } else {
129 spec.seconds = 0.0;
130 }
131 let seconds = spec.seconds;
132 if seconds > 0.0 {
133 *rt.transition.borrow_mut() = Some(spec);
134 }
135 seconds
136 })
137}
138
139pub fn time() -> f64 {
141 with(|rt| rt.task_time.get())
142}
143
144pub fn tunable(name: &str, default: f64) -> f64 {
147 with(|rt| {
148 let mut meta = rt.meta.borrow_mut();
149 if let Some(v) = meta.tunables.get(name) {
150 return *v;
151 }
152 meta.tunables.insert(name.to_owned(), default);
153 rt.meta_changed.set(true);
154 default
155 })
156}
157
158pub fn ease_named(name: &str, default: Option<CubicBezier>) -> CubicBezier {
161 with(|rt| {
162 let mut meta = rt.meta.borrow_mut();
163 if let Some(v) = meta.eases.get(name) {
164 return CubicBezier::from_array(*v);
165 }
166 let default = default.unwrap_or(presets::DEFAULT);
167 meta.eases.insert(name.to_owned(), default.to_array());
168 rt.meta_changed.set(true);
169 default
170 })
171}
172
173pub(crate) fn marker(name: &str) -> f64 {
176 with(|rt| {
177 let mut meta = rt.meta.borrow_mut();
178 if let Some(v) = meta.markers.get(name) {
179 return *v;
180 }
181 let t = rt.task_time.get();
182 meta.markers.insert(name.to_owned(), t);
183 rt.meta_changed.set(true);
184 t
185 })
186}
187
188pub fn meta_snapshot() -> Meta {
190 with(|rt| rt.meta.borrow().clone())
191}
192
193pub fn with_rng<R>(f: impl FnOnce(&mut ChaCha8Rng) -> R) -> R {
197 with(|rt| f(&mut rt.rng.borrow_mut()))
198}
199
200pub fn random() -> f64 {
202 use rand::RngExt;
203 with_rng(|r| r.random::<f64>())
204}
205
206pub fn random_range(min: f64, max: f64) -> f64 {
208 min + (max - min) * random()
209}
210
211#[derive(Clone)]
215pub struct SeededRng(ChaCha8Rng);
216
217impl SeededRng {
218 pub fn new(seed: u64) -> Self {
220 Self(ChaCha8Rng::seed_from_u64(seed))
221 }
222
223 pub fn next_f64(&mut self) -> f64 {
225 use rand::RngExt;
226 self.0.random::<f64>()
227 }
228
229 pub fn range(&mut self, span: std::ops::Range<f64>) -> f64 {
231 let w = span.end - span.start;
232 span.start + w * self.next_f64()
233 }
234}