libbhoo 0.2.0

Minimal UI foundations for SpectreOS
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
//! Bounded, deterministic motion state. No threads, timers, dependencies or disk caches.
//!
//! Standard effects spring parameters are taken from AndroidX StandardMotionTokens,
//! Copyright 2024 The Android Open Source Project, Apache-2.0. See
//! docs/implementation-progress.md and reference-licenses/compose-material3/LICENSE.txt.
//! The analytic oscillator implementation below is independently written for Bhoo.
use std::collections::HashMap;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MotionPreference {
    #[default]
    Full,
    Reduced,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MotionScheme {
    #[default]
    Standard,
    Expressive,
}
impl MotionScheme {
    pub fn spatial(self) -> Spring {
        match self {
            Self::Standard => Spring::SPATIAL,
            Self::Expressive => Spring {
                stiffness: 380.0,
                damping: 0.8,
            },
        }
    }
    pub fn fast_spatial(self) -> Spring {
        match self {
            Self::Standard => Spring {
                stiffness: 1400.0,
                damping: 0.9,
            },
            Self::Expressive => Spring {
                stiffness: 800.0,
                damping: 0.6,
            },
        }
    }
    pub fn slow_spatial(self) -> Spring {
        match self {
            Self::Standard => Spring {
                stiffness: 300.0,
                damping: 0.9,
            },
            Self::Expressive => Spring {
                stiffness: 200.0,
                damping: 0.8,
            },
        }
    }
}

/// Standard Material springs: critical effects and slightly underdamped spatial motion.
#[derive(Clone, Copy, Debug)]
pub struct Spring {
    stiffness: f64,
    damping: f64,
}

impl Spring {
    pub const PROGRESS: Self = Self {
        stiffness: 50.0,
        damping: 1.0,
    };
    pub const EFFECTS: Self = Self {
        stiffness: 1600.0,
        damping: 1.0,
    };
    /// AndroidX StandardMotionTokens default spatial profile.
    pub const SPATIAL: Self = Self {
        stiffness: 700.0,
        damping: 0.9,
    };
    pub const FAST_EFFECTS: Self = Self {
        stiffness: 3800.0,
        damping: 1.0,
    };
}

#[derive(Clone, Copy, Debug)]
struct Track {
    value: f64,
    velocity: f64,
    target: f64,
    time: f64,
    seen: u64,
    spring: Spring,
}

impl Track {
    fn advance(&mut self, time: f64, spring: Spring) {
        let dt = (time - self.time).max(0.0);
        self.time = time;
        if dt == 0.0 {
            return;
        }
        // Effects are critically damped. Exact solution avoids frame-rate-dependent
        // Euler instability and catches up after long suspension without stepping a backlog.
        let omega = spring.stiffness.max(1.0).sqrt();
        let displacement = self.value - self.target;
        if spring.damping < 1.0 {
            let rate = spring.damping * omega;
            let frequency = omega * (1.0 - spring.damping * spring.damping).sqrt();
            let c = (self.velocity + rate * displacement) / frequency;
            let phase = frequency * dt;
            let wave = displacement * phase.cos() + c * phase.sin();
            let decay = (-rate * dt).exp();
            self.value = self.target + wave * decay;
            self.velocity =
                (frequency * (-displacement * phase.sin() + c * phase.cos()) - rate * wave) * decay;
        } else {
            let c = self.velocity + omega * displacement;
            let decay = (-omega * dt).exp();
            self.value = self.target + (displacement + c * dt) * decay;
            self.velocity = (self.velocity - omega * c * dt) * decay;
        }
        if (self.value - self.target).abs() < 0.0005 && self.velocity.abs() < 0.01 {
            self.value = self.target;
            self.velocity = 0.0;
        }
    }
    fn moving(self) -> bool {
        self.value != self.target || self.velocity != 0.0
    }
}

/// Retains only properties referenced during the current frame, up to `capacity`.
/// Targets are normalized [0,1] effects, not arbitrary geometry.
pub struct Motion {
    tracks: HashMap<(u64, u8), Track>,
    tweens: HashMap<(u64, u8), (crate::timing::Tween, u64)>,
    clocks: HashMap<(u64, u8), (f64, u64)>,
    capacity: usize,
    epoch: u64,
    time: f64,
    preference: MotionPreference,
}

impl Default for Motion {
    fn default() -> Self {
        Self::new(4096)
    }
}

impl Motion {
    pub fn new(capacity: usize) -> Self {
        Self {
            tracks: HashMap::new(),
            tweens: HashMap::new(),
            clocks: HashMap::new(),
            capacity,
            epoch: 0,
            time: 0.0,
            preference: MotionPreference::Full,
        }
    }
    pub fn begin(&mut self, time: f64, preference: MotionPreference) {
        if time.is_finite() {
            self.time = time.max(self.time);
        }
        self.preference = preference;
        self.epoch = self.epoch.wrapping_add(1);
    }
    /// First encounter initializes at `initial`; use target for no entrance effect.
    /// Retargeting preserves the sampled presentation and velocity.
    pub fn effect(
        &mut self,
        id: u64,
        property: u8,
        target: f32,
        initial: f32,
        spring: Spring,
    ) -> f32 {
        let target = if target.is_finite() {
            target.clamp(0.0, 1.0) as f64
        } else {
            0.0
        };
        let initial = if initial.is_finite() {
            initial.clamp(0.0, 1.0) as f64
        } else {
            target
        };
        let key = (id, property);
        if !self.tracks.contains_key(&key)
            && self.tracks.len() + self.tweens.len() + self.clocks.len() >= self.capacity
        {
            return target as f32;
        }
        let track = self.tracks.entry(key).or_insert(Track {
            value: initial,
            velocity: 0.0,
            target: initial,
            time: self.time,
            seen: self.epoch,
            spring,
        });
        track.advance(self.time, track.spring);
        track.spring = spring;
        track.target = target;
        track.seen = self.epoch;
        // Effects are critical; standard spatial geometry is slightly underdamped.
        // Bound normalized presentation values; reduced motion reconciles immediately.
        if self.preference == MotionPreference::Reduced {
            track.value = target;
            track.velocity = 0.0;
        }
        track.value.clamp(0.0, 1.0) as f32
    }
    #[allow(clippy::too_many_arguments)]
    pub fn tween(
        &mut self,
        id: u64,
        property: u8,
        target: f32,
        initial: f32,
        enter: crate::timing::TweenSpec,
        exit: crate::timing::TweenSpec,
    ) -> f32 {
        self.tween_inner(id, property, target, initial, enter, exit, false)
    }
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn css_tween(
        &mut self,
        id: u64,
        property: u8,
        target: f32,
        initial: f32,
        enter: crate::timing::TweenSpec,
        exit: crate::timing::TweenSpec,
    ) -> f32 {
        self.tween_inner(id, property, target, initial, enter, exit, true)
    }
    #[allow(clippy::too_many_arguments)]
    fn tween_inner(
        &mut self,
        id: u64,
        property: u8,
        target: f32,
        initial: f32,
        enter: crate::timing::TweenSpec,
        exit: crate::timing::TweenSpec,
        css: bool,
    ) -> f32 {
        let key = (id, property);
        let target = if target.is_finite() {
            target.clamp(0.0, 1.0)
        } else {
            0.0
        };
        if !self.tweens.contains_key(&key)
            && self.tracks.len() + self.tweens.len() + self.clocks.len() >= self.capacity
        {
            return target;
        }
        let (track, seen) = self.tweens.entry(key).or_insert((
            crate::timing::Tween::at(if initial.is_finite() {
                initial.clamp(0.0, 1.0)
            } else {
                target
            }),
            self.epoch,
        ));
        *seen = self.epoch;
        let sample = if css {
            crate::timing::Tween::sample_css
        } else {
            crate::timing::Tween::sample
        };
        sample(
            track,
            self.time,
            target,
            enter,
            exit,
            self.preference == MotionPreference::Reduced,
        )
    }
    pub fn elapsed(&mut self, id: u64, property: u8) -> f64 {
        let key = (id, property);
        if !self.clocks.contains_key(&key) && self.retained_properties() >= self.capacity {
            return self.time;
        }
        let (start, seen) = self.clocks.entry(key).or_insert((self.time, self.epoch));
        *seen = self.epoch;
        (self.time - *start).max(0.0)
    }
    pub fn pause_clocks(&mut self) {
        self.clocks.clear();
    }
    pub fn finish(&mut self) {
        let epoch = self.epoch;
        self.tracks.retain(|_, track| track.seen == epoch);
        self.tweens.retain(|_, (_, seen)| *seen == epoch);
        self.clocks.retain(|_, (_, seen)| *seen == epoch);
    }
    pub fn is_animating(&self) -> bool {
        self.tracks.values().any(|track| track.moving())
            || self.tweens.values().any(|(track, _)| track.moving())
    }
    pub fn retained_properties(&self) -> usize {
        self.tracks.len() + self.tweens.len() + self.clocks.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn standard_spatial_spring_is_animated_stable_and_frame_independent() {
        fn run(times: &[f64]) -> f32 {
            let mut m = Motion::default();
            m.begin(0.0, MotionPreference::Full);
            m.effect(1, 0, 1.0, 0.0, Spring::SPATIAL);
            let mut value = 0.0;
            for &time in times {
                m.begin(time, MotionPreference::Full);
                value = m.effect(1, 0, 1.0, 0.0, Spring::SPATIAL);
            }
            value
        }
        let a = run(&[0.1]);
        let b = run(&[0.02, 0.04, 0.06, 0.08, 0.1]);
        assert!(a > 0.0 && a < 1.0);
        assert!((a - b).abs() < 0.00001);
        assert_eq!(run(&[3.0]), 1.0);
    }
    #[test]
    fn springs_tweens_and_clocks_share_one_bound_and_removed_tracks_are_pruned() {
        let mut m = Motion::new(4);
        m.begin(0.0, MotionPreference::Full);
        let s = crate::timing::TweenSpec::new(0.5, crate::timing::Easing::Linear);
        for i in 0..20 {
            m.tween(i, 1, 1.0, 0.0, s, s);
            m.elapsed(i, 2);
            m.effect(i, 3, 1.0, 0.0, Spring::EFFECTS);
        }
        assert_eq!(m.retained_properties(), 4);
        m.finish();
        m.begin(1.0, MotionPreference::Full);
        m.finish();
        assert_eq!(m.retained_properties(), 0);
        assert!(!m.is_animating());
    }
    fn sample(motion: &mut Motion, time: f64, target: f32, preference: MotionPreference) -> f32 {
        motion.begin(time, preference);
        let value = motion.effect(1, 0, target, 0.0, Spring::EFFECTS);
        motion.finish();
        value
    }
    #[test]
    fn settles_exactly_and_stops_scheduling() {
        let mut motion = Motion::default();
        assert_eq!(sample(&mut motion, 0.0, 1.0, MotionPreference::Full), 0.0);
        assert!(motion.is_animating());
        let mid = sample(&mut motion, 0.05, 1.0, MotionPreference::Full);
        assert!(mid > 0.0 && mid < 1.0);
        assert_eq!(sample(&mut motion, 2.0, 1.0, MotionPreference::Full), 1.0);
        assert!(!motion.is_animating());
    }
    #[test]
    fn reversal_has_no_position_jump_and_eventually_settles() {
        let mut m = Motion::default();
        sample(&mut m, 0.0, 1.0, MotionPreference::Full);
        let before = sample(&mut m, 0.06, 1.0, MotionPreference::Full);
        assert_eq!(sample(&mut m, 0.06, 0.0, MotionPreference::Full), before);
        assert_eq!(sample(&mut m, 2.0, 0.0, MotionPreference::Full), 0.0);
        assert!(!m.is_animating());
    }
    #[test]
    fn analytic_sampling_is_independent_of_frame_count() {
        let mut a = Motion::default();
        let mut b = Motion::default();
        sample(&mut a, 0.0, 1.0, MotionPreference::Full);
        sample(&mut b, 0.0, 1.0, MotionPreference::Full);
        for i in 1..6 {
            sample(&mut a, i as f64 * 0.01, 1.0, MotionPreference::Full);
        }
        assert!(
            (sample(&mut a, 0.06, 1.0, MotionPreference::Full)
                - sample(&mut b, 0.06, 1.0, MotionPreference::Full))
            .abs()
                < 0.00001
        );
    }
    #[test]
    fn reduced_motion_finishes_in_flight_effects() {
        let mut m = Motion::default();
        sample(&mut m, 0.0, 1.0, MotionPreference::Full);
        assert_eq!(sample(&mut m, 0.01, 1.0, MotionPreference::Reduced), 1.0);
        assert!(!m.is_animating());
    }
    #[test]
    fn removed_properties_are_reclaimed_and_cache_is_bounded() {
        let mut m = Motion::new(2);
        m.begin(0.0, MotionPreference::Full);
        for id in 0..100 {
            m.effect(id, 0, 1.0, 0.0, Spring::EFFECTS);
        }
        m.finish();
        assert_eq!(m.retained_properties(), 2);
        m.begin(1.0, MotionPreference::Full);
        m.finish();
        assert_eq!(m.retained_properties(), 0);
        assert!(!m.is_animating());
    }
    #[test]
    fn nonfinite_and_backwards_time_does_not_corrupt_values() {
        let mut m = Motion::default();
        sample(&mut m, 1.0, 1.0, MotionPreference::Full);
        for t in [f64::NAN, -1.0, f64::INFINITY, 1e20] {
            let value = sample(&mut m, t, 1.0, MotionPreference::Full);
            assert!(value.is_finite() && (0.0..=1.0).contains(&value));
        }
    }
}