motion-core 0.2.0

Backend-independent motion engine primitives
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Stateless authoring time, design coordinates and optional shared computation.

use std::hash::Hash;
use std::sync::Arc;

use crate::{
    Duration, FrameRate, Interval, Node, Point, Random, Rect, Signal, Size, Time, TimeOffset,
};

mod cache;
mod partition;
#[cfg(test)]
mod tests;

pub use cache::SceneCache;
pub use partition::{CacheLimits, CachePartition, RenderCache};

/// Immutable scene evaluation inputs in signed ticks and logical coordinates.
///
/// The caller supplies time explicitly and can reuse one [`SceneCache`] across
/// arbitrary frame orders and threads, without initializing rendering resources
/// or interpreting design dimensions as output pixels.
///
/// ```
/// use motion_core::prelude::*;
/// use motion_core::{
///     DisplayList, RasterLimits, ResourceStore, ValidatedDisplayList, MAX_PATH_VERBS,
///     MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
/// };
/// use std::sync::Arc;
///
/// let cache = SceneCache::new(32);
/// let tween = Tween::new(0.0, 100.0, 1.seconds());
/// let evaluate = |time| {
///     let context = SceneContext::new(time, fps!(30), Size::new(640.0, 360.0), &cache)
///         .with_clip_duration(2.seconds());
///     let positions = context.cache(("dots", 8_u32), || {
///         (0..8_u32)
///             .map(|index| Point::new(context.random(("x", index)) * 640.0, 180.0))
///             .collect::<Vec<_>>()
///     });
///     let local = context.shifted(500.milliseconds().offset());
///     assert_eq!(local.global_time(), time);
///     (local.sample(&tween), positions)
/// };
/// let (late, first) = evaluate(1500.milliseconds().after_origin());
/// let (early, second) = evaluate(500.milliseconds().after_origin());
/// let (again, third) = evaluate(1500.milliseconds().after_origin());
/// assert_eq!((late, early, again), (100.0, 0.0, 100.0));
/// assert!(Arc::ptr_eq(&first, &second) && Arc::ptr_eq(&first, &third));
/// ```
#[derive(Clone)]
pub struct SceneContext<'a> {
    evaluation: Arc<crate::Evaluation>,
    time: Time,
    global_time: Time,
    clip_duration: Option<Duration>,
    frame_rate: FrameRate,
    size: Size,
    nested_scene: bool,

    cache: &'a SceneCache,
}

impl<'a> SceneContext<'a> {
    /// Creates root evaluation inputs with matching local/global time.
    ///
    /// Panics unless both design dimensions are finite and strictly positive.
    pub fn new(time: Time, frame_rate: FrameRate, size: Size, cache: &'a SceneCache) -> Self {
        Self::try_new(time, frame_rate, size, cache)
            .unwrap_or_else(|error| panic!("{}", error.message))
    }

    /// Creates evaluation inputs with recoverable design-size validation.
    pub fn try_new(
        time: Time,
        frame_rate: FrameRate,
        size: Size,
        cache: &'a SceneCache,
    ) -> Result<Self, crate::ValidationError> {
        if !size.width.is_finite()
            || size.width <= 0.0
            || !size.height.is_finite()
            || size.height <= 0.0
        {
            return Err(crate::ValidationError::invalid(
                "scene_context",
                "size",
                "scene design dimensions must be finite and positive",
            ));
        }
        Ok(Self {
            evaluation: Arc::default(),
            time,
            global_time: time,
            clip_duration: None,
            frame_rate,
            size,
            nested_scene: false,
            cache,
        })
    }

    /// Shares an evaluation environment; its own time is ignored in favor of local time.
    pub fn with_evaluation(mut self, evaluation: Arc<crate::Evaluation>) -> Self {
        self.evaluation = evaluation;
        self
    }

    /// Shared quality, resources, diagnostics and caches, retained by shifted, sampled and
    /// nested contexts.
    pub fn evaluation(&self) -> &Arc<crate::Evaluation> {
        &self.evaluation
    }

    fn edit(mut self, edit: impl FnOnce(crate::Evaluation) -> crate::Evaluation) -> Self {
        let current = Arc::try_unwrap(std::mem::take(&mut self.evaluation))
            .unwrap_or_else(|shared| crate::Evaluation::clone(&shared));
        self.evaluation = Arc::new(edit(current));
        self
    }

    /// Selects preview approximations, preserved by nested and sampled contexts.
    pub fn with_quality(self, quality: crate::RenderQuality) -> Self {
        self.edit(|evaluation| evaluation.with_quality(quality))
    }

    /// Explicit rendering quality; manually constructed contexts default to Final.
    pub fn render_quality(&self) -> crate::RenderQuality {
        self.evaluation.quality()
    }

    /// Always available resources; an unconfigured context uses an empty owner.
    pub fn assets(&self) -> &crate::Assets {
        self.evaluation.assets()
    }

    /// Attaches the common resource owner without reading or decoding.
    pub fn with_assets(self, assets: &crate::Assets) -> Self {
        self.edit(|evaluation| evaluation.with_assets(assets))
    }

    /// Attaches a request-owned sink suitable for explicit background resource reads.
    pub fn with_diagnostics(self, diagnostics: &crate::RequestDiagnostics) -> Self {
        self.edit(|evaluation| evaluation.with_diagnostics(diagnostics.clone()))
    }

    /// Diagnostic scope retained by shifted, sampled and nested contexts.
    pub fn diagnostics(&self) -> &crate::RequestDiagnostics {
        self.evaluation.diagnostics()
    }

    /// Sets finite clip metadata; zero denotes an instantaneous clip.
    ///
    /// Sampling time is not clamped to the clip.
    pub fn with_clip_duration(mut self, duration: Duration) -> Self {
        self.clip_duration = Some(duration);
        self
    }

    /// Signed clip-local time.
    pub fn time(&self) -> Time {
        self.time
    }

    /// Clip-local time in floating-point seconds, for animation mathematics.
    pub fn seconds(&self) -> f64 {
        self.time.as_seconds()
    }

    /// Root evaluation time, unaffected by local shifts.
    pub fn global_time(&self) -> Time {
        self.global_time
    }

    /// Explicit clip duration, absent for an unconstrained scene.
    pub fn clip_duration(&self) -> Option<Duration> {
        self.clip_duration
    }

    /// Clip-local time as a duration since the clip start; zero before the start.
    pub fn elapsed(&self) -> Duration {
        self.time
            .duration_since(Time::ZERO)
            .unwrap_or(Duration::ZERO)
    }

    /// Clamped local progress; unconstrained scenes return zero.
    ///
    /// A zero-duration clip jumps from zero to one at local time zero.
    pub fn progress(&self) -> f64 {
        self.clip_duration
            .map_or(0.0, |duration| self.progress_in(Time::ZERO, duration))
    }

    /// Clamped progress in a local interval, using integer boundary comparisons.
    ///
    /// Zero duration jumps at start. Wide integer
    /// differences allow queries across opposite signed tick extremes.
    pub fn progress_in(&self, start: Time, duration: Duration) -> f64 {
        Interval::new(start, duration).progress(self.time)
    }

    /// Eased local interval progress, with the same clamping as progress_in.
    pub fn ease_in(&self, start: Time, duration: Duration, easing: crate::Easing) -> f64 {
        Interval::new(start, duration).ease(self.time, easing)
    }

    /// Exact rational authoring frame rate shared by still, preview and export clocks.
    pub fn frame_rate(&self) -> FrameRate {
        self.frame_rate
    }

    pub(crate) fn for_timeline(&self, size: Size, frame_rate: FrameRate) -> Self {
        Self {
            frame_rate,
            size,
            nested_scene: true,
            ..self.clone()
        }
    }

    pub(crate) fn is_nested_scene(&self) -> bool {
        self.nested_scene
    }

    /// Converts a frame count directly to ticks without cumulative rounding.
    pub fn frames(&self, count: u64) -> Duration {
        Duration::from_frame(count, self.frame_rate)
    }

    /// Samples an animation using local, not global, time.
    pub fn sample<Value>(&self, animation: &(impl Signal<Value> + ?Sized)) -> Value {
        animation.sample(self.time)
    }

    /// Subtracts an offset from local time, preserving global time and clip metadata.
    ///
    /// Offsets can be negative. Panics if the resulting local ticks overflow.
    pub fn shifted(&self, offset: TimeOffset) -> Self {
        Self {
            time: self.time - offset,
            ..self.clone()
        }
    }

    /// Subtracts a local offset without panicking on tick overflow.
    pub fn try_shifted(&self, offset: TimeOffset) -> Result<Self, crate::ValidationError> {
        let ticks = self
            .time
            .ticks()
            .checked_sub(offset.ticks())
            .ok_or_else(|| {
                crate::ValidationError::invalid(
                    "scene_context",
                    "time",
                    "Shifted local ticks overflow",
                )
            })?;
        Ok(Self {
            time: Time::from_ticks(ticks),
            ..self.clone()
        })
    }

    pub(crate) fn resampled(&self, offset: TimeOffset) -> Result<Self, crate::ValidationError> {
        let shift = |time: Time| {
            time.ticks()
                .checked_add(offset.ticks())
                .map(Time::from_ticks)
                .ok_or_else(|| {
                    crate::ValidationError::invalid(
                        "motion_blur",
                        "time",
                        "Subframe local/global ticks overflow",
                    )
                })
        };
        Ok(Self {
            time: shift(self.time)?,
            global_time: shift(self.global_time)?,
            ..self.clone()
        })
    }

    /// Resamples a local subtree at 1..=64 centered integer shutter midpoints.
    /// Both local/global clocks move; clip metadata, resources and cache persist.
    /// Signed samples outside a clip are supplied unchanged for caller-owned gating.
    pub fn try_motion_blur(
        &self,
        shutter: Duration,
        samples: u32,
        build: impl FnMut(&SceneContext<'_>) -> Node,
    ) -> Result<Node, crate::ValidationError> {
        crate::authoring::sampling::capture(self, shutter, samples, build)
    }

    /// Captures shutter samples, deferring invalid sampling parameters to compilation.
    pub fn motion_blur(
        &self,
        shutter: Duration,
        samples: u32,
        build: impl FnMut(&SceneContext<'_>) -> Node,
    ) -> Node {
        self.try_motion_blur(shutter, samples, build)
            .unwrap_or_else(super::scene::failure)
    }

    /// Builds only in [start, start + duration), with shifted local clip inputs.
    ///
    /// Outside the interval, including zero duration, returns an empty node and
    /// does not call build. Global time stays unchanged. Integer differences avoid
    /// overflowing the endpoint sum.
    pub fn during(
        &self,
        start: Time,
        duration: Duration,
        build: impl FnOnce(&SceneContext<'a>) -> Node,
    ) -> Node {
        let interval = Interval::new(start, duration);
        if !interval.contains(self.time) {
            Node::empty()
        } else {
            build(&Self {
                nested_scene: true,
                ..self
                    .shifted(start.since_origin())
                    .with_clip_duration(duration)
            })
            .with_scene_time(Time::from_ticks(
                (i128::from(self.time.ticks()) - i128::from(start.ticks())) as i64,
            ))
        }
    }

    /// Evaluates a child scene starting at a parent-local offset.
    ///
    /// Finite children use their half-open duration. Infinite children are active
    /// from offset onward and clear inherited clip-duration metadata. The parent
    /// context itself is never clamped; its caller controls the parent interval.
    /// Panics for unrepresentable shifted local ticks.
    /// Timeline children clip and contain their own design viewport;
    /// changing the child frame grid never quantizes the elapsed parent ticks.
    pub fn embed(&self, scene: &dyn crate::authoring::Scene, offset: Time) -> Node {
        match scene.duration() {
            Some(duration) => self.during(offset, duration, |context| scene.render(context)),
            None if self.time < offset => Node::empty(),
            None => scene.render(&Self {
                clip_duration: None,
                nested_scene: true,
                ..self.shifted(offset.since_origin())
            }),
        }
    }

    /// Logical design dimensions, not device pixels.
    pub fn size(&self) -> Size {
        self.size
    }

    /// Opposite-corner logical bounds at the origin.
    pub fn bounds(&self) -> Rect {
        self.size.to_rect()
    }

    /// Center of the logical design bounds.
    pub fn center(&self) -> Point {
        self.bounds().center()
    }

    /// Measures content or declared layout in parent coordinates.
    ///
    /// Deferred content sees this context's local time, quality, assets and
    /// diagnostics. Uses default structural limits without rendering or f32 pixel
    /// conversion.
    /// For explicit budgets use [`Node::measure`]. Leaves supply their own bounds
    /// with the shared explicit font environment. This does not invoke drawing
    /// or infer filter extents; command validation occurs during compilation.
    pub fn measure(&self, node: &Node) -> Result<Rect, crate::ValidationError> {
        let drawing = crate::DrawContext::default()
            .with_evaluation(self.evaluation.clone())
            .with_time(self.time);
        node.measure_with(&drawing, crate::ValidationLimits::default())
    }

    /// Measures like [`measure`](Self::measure) but substitutes `fallback` when measurement fails,
    /// for example `context.measure_or(&label, Rect::default())`. The failure still surfaces
    /// when the node is compiled.
    pub fn measure_or(&self, node: &Node, fallback: Rect) -> Rect {
        self.measure(node).unwrap_or(fallback)
    }

    /// Places a measured snapshot next to a reference in parent coordinates.
    ///
    /// Vertical sides center horizontally; horizontal sides center vertically.
    /// Finite negative gaps intentionally overlap. Returns errors for unknown
    /// geometry, invalid gaps or unrepresentable offsets; inputs stay unchanged.
    /// This is immediate snapshot positioning, not a live constraint to reference.
    ///
    /// ```
    /// use motion_core::prelude::*;
    /// use motion_core::{
    ///     DisplayList, RasterLimits, ResourceStore, ValidatedDisplayList, MAX_PATH_VERBS,
    ///     MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
    /// };
    /// let cache = SceneCache::new(0);
    /// let context = SceneContext::new(
    ///     Time::ZERO,
    ///     fps!(30),
    ///     Size::new(200.0, 100.0),
    ///     &cache,
    /// );
    /// let reference = Node::from(Rect::new(10.0, 10.0, 50.0, 30.0).fill(Color::WHITE));
    /// let card = Node::from(Rect::new(0.0, 0.0, 8.0, 4.0).fill(Color::WHITE));
    /// let card = context.next_to(card, &reference, Side::Right, 6.0);
    /// assert_eq!(context.measure(&card)?, Rect::new(56.0, 18.0, 64.0, 22.0));
    /// let card = context.align_to(card, &reference, Side::Bottom);
    /// assert_eq!(context.measure(&card)?, Rect::new(56.0, 26.0, 64.0, 30.0));
    /// # Ok::<(), motion_core::ValidationError>(())
    /// ```
    pub fn try_next_to(
        &self,
        node: impl Into<Node>,
        reference: &Node,
        side: crate::authoring::Side,
        gap: f64,
    ) -> Result<Node, crate::ValidationError> {
        if !gap.is_finite() {
            return Err(crate::ValidationError::invalid(
                "layout",
                "gap",
                "Relative layout gap must be finite",
            ));
        }
        let node = node.into();
        let offset = side.adjacent(self.measure(&node)?, self.measure(reference)?, gap);
        self.translated_layout(node, offset)
    }

    /// Aligns one measured edge with a reference, preserving the other axis.
    ///
    /// Uses the already transformed parent-space AABBs. Existing position,
    /// rotation, scale and pivot remain intact; only translation is added.
    pub fn try_align_to(
        &self,
        node: impl Into<Node>,
        reference: &Node,
        edge: crate::authoring::Side,
    ) -> Result<Node, crate::ValidationError> {
        let node = node.into();
        let offset = edge.aligned(self.measure(&node)?, self.measure(reference)?);
        self.translated_layout(node, offset)
    }

    /// Measures and places the snapshot next to its reference during compilation.
    pub fn next_to(
        &self,
        node: impl Into<Node>,
        reference: &Node,
        side: super::Side,
        gap: f64,
    ) -> Node {
        node.into().next_to(reference, side, gap)
    }

    /// Aligns one edge using the current compile-time font and drawing environment.
    pub fn align_to(&self, node: impl Into<Node>, reference: &Node, edge: super::Side) -> Node {
        node.into().align_to(reference, edge)
    }

    fn translated_layout(
        &self,
        node: Node,
        offset: crate::Vector2,
    ) -> Result<Node, crate::ValidationError> {
        use crate::NodeModifiers;
        if !offset.x.is_finite() || !offset.y.is_finite() {
            return Err(crate::ValidationError::invalid(
                "layout",
                "translation",
                "Relative layout offset must remain finite",
            ));
        }
        let node = node.translate(offset.x, offset.y);
        self.measure(&node)?;
        Ok(node)
    }

    /// Returns a key-derived value in [0, 1), independent of time and cache state.
    pub fn random(&self, key: impl Hash) -> f64 {
        self.random_generator(key).next_float()
    }

    /// Starts a fresh key-derived stream, independent of all other evaluations.
    pub fn random_generator(&self, key: impl Hash) -> Random {
        Random::from_key(key)
    }

    /// Reuses a pure value by calling location, value type and an equal typed key.
    ///
    /// Keys must distinguish all inputs, including resource revisions. Keys are
    /// retained, so use owned data or static references rather than borrowed locals.
    /// Hash collisions are resolved by key type and equality.
    /// Builders may be rerun after eviction, clear, disabled caching or races.
    #[track_caller]
    pub fn cache<Key: Eq + Hash + Send + Sync + 'static, Value: Send + Sync + 'static>(
        &self,
        key: Key,
        build: impl FnOnce() -> Value,
    ) -> Arc<Value> {
        self.cache.get(key, build)
    }

    /// Like [`cache`](Self::cache) for a fallible builder, for example a validated
    /// `build()`. A failure is returned and not retained, so the next call tries again.
    #[track_caller]
    pub fn try_cache<
        Key: Eq + Hash + Send + Sync + 'static,
        Value: Send + Sync + 'static,
        Error,
    >(
        &self,
        key: Key,
        build: impl FnOnce() -> Result<Value, Error>,
    ) -> Result<Arc<Value>, Error> {
        self.cache.try_get(key, build)
    }

    /// Reuses a pure static subtree without exposing its shared Arc handle.
    #[track_caller]
    pub fn memo<Key: Eq + Hash + Send + Sync + 'static, Output: Into<Node>>(
        &self,
        key: Key,
        build: impl FnOnce() -> Output,
    ) -> Node {
        self.cache(key, || build().into()).as_ref().clone()
    }

    /// Caches a pure value with an explicit logical retained-byte estimate.
    /// Cost includes the key, value and their owned heap payloads, with a minimum
    /// of their combined inline sizes. Entry metadata, allocator overhead and
    /// shared external pins are excluded.
    /// Oversized values are returned without retention; cost runs outside the lock.
    /// Keys retain the same equality-checked, callsite-scoped contract as cache().
    #[track_caller]
    pub fn cache_with_cost<Key: Eq + Hash + Send + Sync + 'static, Value: Send + Sync + 'static>(
        &self,
        key: Key,
        build: impl FnOnce() -> Value,
        cost: impl FnOnce(&Value) -> usize,
    ) -> Arc<Value> {
        self.cache.get_with_cost(key, build, cost)
    }
}