motion-core 0.1.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
555
556
557
//! Lazy typed assets with explicit bounded project pools and request diagnostics.
//!
//! ```
//! use motion_core::{Asset, Assets, AssetStatus, LoadContext, Source};
//! use std::sync::Arc;
//! struct Label(String);
//! impl Asset for Label {
//!     const KIND: &'static str = "label";
//!     fn decode(bytes: &[u8], _: &LoadContext) -> motion_core::Result<Self> {
//!         Ok(Self(std::str::from_utf8(bytes)?.to_owned()))
//!     }
//!     fn retained_bytes(&self) -> usize {
//!         self.0.len()
//!     }
//! }
//! let assets = Assets::new("assets")?;
//! let handle = assets.load::<Label>(Source::Bytes {
//!     key: "title".into(),
//!     data: Arc::from(&b"Native resources"[..]),
//! });
//! assert_eq!(handle.status(), AssetStatus::Unloaded);
//! assert_eq!(handle.get()?.0, "Native resources");
//! # Ok::<(), motion_core::Error>(())
//! ```

use std::{
    any::{Any, TypeId},
    collections::BTreeMap,
    io::{self, Read},
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex, OnceLock, Weak,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
};

use handle::Entry;

pub mod environment;
mod handle;
mod pool;
#[cfg(test)]
mod tests;

pub use environment::{FontEnvironment, FontIdentity};
pub use handle::{AssetStatus, Handle};
pub use pool::ResourcePool;

const MAX_ENCODED: usize = 64 * 1024 * 1024;

const MAX_CACHE_BYTES: usize = 256 * 1024 * 1024;

const MAX_ENTRIES: usize = 4096;

thread_local! {
    static RESOLVING: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// Explicit request-owned diagnostic sink, safely shared with background tasks.
/// Clones append to the same sink. Assets views and handles carry it explicitly.
#[derive(Clone, Default, Debug)]
pub struct RequestDiagnostics(Arc<Mutex<Vec<Arc<crate::Error>>>>);

impl RequestDiagnostics {
    /// Captures a failure once by Arc identity, not by its text or semantic equality.
    pub fn record(&self, error: Arc<crate::Error>) {
        let mut errors = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if !errors.iter().any(|existing| Arc::ptr_eq(existing, &error)) {
            errors.push(error);
        }
    }

    /// Snapshot of failures belonging to this request only.
    pub fn errors(&self) -> Vec<Arc<crate::Error>> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }
}

struct ResolveGuard;

impl Drop for ResolveGuard {
    fn drop(&mut self) {
        RESOLVING.with(|entries| {
            entries.borrow_mut().pop();
        });
    }
}

/// A custom typed resource decoded once for a shared source and project context.
pub trait Asset: Sized + Send + Sync + 'static {
    /// Human-readable resource category retained by load diagnostics.
    const KIND: &'static str;

    /// Decodes bounded input without requiring a rendering device.
    /// Implementations must be deterministic for these bytes/context; recursive
    /// resource dependency graphs are not a supported decoder contract.
    fn decode(bytes: &[u8], context: &LoadContext) -> crate::Result<Self>;

    /// Logical decoded payload charge; custom heap-owning assets should override.
    /// At least the encoded input length is charged regardless of this value.
    fn retained_bytes(&self) -> usize {
        std::mem::size_of::<Self>()
    }
}

/// Local file or immutable named bytes. Byte identity includes the content,
/// so reusing a name with different bytes cannot return the wrong cached asset.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Source {
    /// Relative to the Assets root, or an explicitly supplied absolute path.
    File(PathBuf),
    /// Embedded bytes with a diagnostic identifier.
    Bytes {
        /// Stable user-facing resource name.
        key: Arc<str>,
        /// Immutable encoded content.
        data: Arc<[u8]>,
    },
}

impl std::fmt::Debug for Source {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::File(path) => formatter.debug_tuple("File").field(path).finish(),
            Self::Bytes { key, data } => formatter
                .debug_struct("Bytes")
                .field("key", key)
                .field("length", &data.len())
                .finish(),
        }
    }
}

impl From<PathBuf> for Source {
    fn from(path: PathBuf) -> Self {
        Self::File(path)
    }
}

impl From<&Path> for Source {
    fn from(path: &Path) -> Self {
        Self::File(path.to_path_buf())
    }
}

impl From<&str> for Source {
    fn from(path: &str) -> Self {
        Self::File(path.into())
    }
}

impl From<String> for Source {
    fn from(path: String) -> Self {
        Self::File(path.into())
    }
}

/// Immutable loader configuration; no font discovery, GPU or encoder is created.
#[derive(Clone, Debug)]
pub struct LoadContext {
    root: Arc<PathBuf>,
    fonts: Option<crate::asset::environment::FontEnvironment>,
    namespace: u64,
}

impl LoadContext {
    /// Immutable font environment supplied by this resource owner, if any.
    pub fn fonts(&self) -> Option<&crate::asset::environment::FontEnvironment> {
        self.fonts.as_ref()
    }

    /// Absolute project asset directory captured when Assets is created.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Maximum encoded bytes accepted by a single resource.
    pub fn max_encoded_bytes(&self) -> usize {
        MAX_ENCODED
    }
}

type CacheKey = (TypeId, PathBuf, u64, u64, Source);

type Erased = dyn Any + Send + Sync;

struct OwnedEntry {
    value: Arc<Erased>,
    initialized: Box<dyn Fn() -> bool + Send + Sync>,
}

impl OwnedEntry {
    fn new<AssetValue: Asset>(entry: Arc<Entry<AssetValue>>) -> Arc<Self> {
        let weak = Arc::downgrade(&entry);
        Arc::new(Self {
            value: entry,
            initialized: Box::new(move || {
                weak.upgrade()
                    .is_some_and(|entry| entry.result.get().is_some())
            }),
        })
    }
}

/// Bounded project resource owner. Owners/handles retain project weak cache
/// entries; dropping them releases cache payload charges. This is not a hard
/// process-memory cap or an automatic file-change watcher.
#[derive(Clone)]
pub struct Assets {
    context: LoadContext,
    entries: Arc<Mutex<BTreeMap<CacheKey, Arc<OwnedEntry>>>>,
    pool: ResourcePool,
    diagnostics: Option<RequestDiagnostics>,
}

impl std::fmt::Debug for Assets {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Assets")
            .field("root", &self.context.root)
            .finish_non_exhaustive()
    }
}

impl Default for Assets {
    fn default() -> Self {
        Self {
            context: LoadContext {
                root: Arc::new(PathBuf::new()),
                fonts: None,
                namespace: 0,
            },
            entries: Arc::new(Mutex::new(BTreeMap::new())),
            pool: ResourcePool::new(),
            diagnostics: None,
        }
    }
}

impl Assets {
    /// Derives a request-local view without changing resource identity or ownership.
    /// Handles created from this view keep the explicit sink across threads.
    pub fn with_diagnostics(mut self, diagnostics: RequestDiagnostics) -> Self {
        self.diagnostics = Some(diagnostics);
        self
    }

    /// Freezes existing entries while isolating future registrations from old clones.
    /// Snapshot versions still share project accounting and existing decoded payloads.
    pub fn snapshot(&self) -> Self {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
        let mut snapshot = self.clone();
        snapshot.context.namespace = NEXT.fetch_add(1, Ordering::Relaxed);
        let entries = self
            .entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .iter()
            .filter(|(_, entry)| (entry.initialized)())
            .map(|(key, entry)| {
                let mut key = key.clone();
                key.3 = snapshot.context.namespace;
                (key, entry.clone())
            })
            .collect();
        snapshot.entries = Arc::new(Mutex::new(entries));
        snapshot
    }

    /// Registers decoded data in the same bounded entry used by lazy handles.
    /// Performs no file read; an already resolved source is never replaced.
    pub fn preload<A: Asset>(
        &self,
        source: impl Into<Source>,
        value: Arc<A>,
    ) -> crate::Result<Handle<A>> {
        let handle = self.load::<A>(source);
        let inserted = std::cell::Cell::new(false);
        let result = handle.entry.result.get_or_init(|| {
            inserted.set(true);
            let charge = value
                .retained_bytes()
                .checked_add(handle.entry.charged.load(Ordering::Acquire));
            let result = charge
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::OutOfMemory,
                        "Asset payload accounting overflow",
                    )
                })
                .and_then(|charge| {
                    let additional = charge - handle.entry.charged.load(Ordering::Acquire);
                    self.pool
                        .0
                        .bytes
                        .try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                            current
                                .checked_add(additional)
                                .filter(|total| *total <= self.pool.0.max_bytes)
                        })
                        .map_err(|_| {
                            io::Error::new(
                                io::ErrorKind::OutOfMemory,
                                "Shared asset-cache logical payload exceeds its allowance",
                            )
                        })?;
                    handle.entry.charged.store(charge, Ordering::Release);
                    Ok(value)
                });
            result.map_err(|error| {
                Arc::new(crate::Error::asset(A::KIND, handle.source_name(), error))
            })
        });
        if let Err(error) = result {
            return Err(crate::Error::asset(
                A::KIND,
                handle.source_name(),
                error.clone(),
            ));
        }
        if !inserted.get() {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "Asset source is already resolved",
            )
            .into());
        }
        Ok(handle)
    }

    /// Uses an explicit project pool and drops this value's retained entry table.
    /// Existing owner clones, handles and decoded values keep their original ownership.
    pub fn with_pool(mut self, pool: ResourcePool) -> Self {
        self.pool = pool;
        self.entries = Arc::new(Mutex::new(BTreeMap::new()));
        self
    }

    /// Project cache identity and accounting shared by this owner's clones.
    pub fn pool(&self) -> &ResourcePool {
        &self.pool
    }

    /// Unregisters one typed source from this owner without invalidating handles.
    /// Clones share registrations; use snapshot() before independent edits.
    /// Retained snapshots and handles keep their payload charged until dropped.
    pub fn remove<A: Asset>(&self, source: impl Into<Source>) -> bool {
        let mut source = source.into();
        if let Source::File(path) = &mut source
            && !path.is_absolute()
        {
            *path = self.context.root.join(&*path);
        }
        let key = (
            TypeId::of::<A>(),
            self.context.root.as_ref().clone(),
            self.context
                .fonts
                .as_ref()
                .map_or(0, crate::asset::environment::FontEnvironment::snapshot_id),
            self.context.namespace,
            source,
        );
        let mut entries = self
            .entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let Some(entry) = entries.remove(&key) else {
            return false;
        };
        let mut global = self
            .pool
            .0
            .entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if global
            .get(&key)
            .and_then(Weak::upgrade)
            .is_some_and(|value| Arc::ptr_eq(&value, &entry.value))
        {
            global.remove(&key);
        }
        true
    }

    /// Derives an independent resource view with an immutable font environment.
    /// Cache identity includes its snapshot; existing owners/handles stay valid.
    pub fn with_fonts(
        mut self,
        fonts: impl Into<crate::asset::environment::FontEnvironment>,
    ) -> Self {
        self.context.fonts = Some(fonts.into());
        self.entries = Arc::new(Mutex::new(BTreeMap::new()));
        self
    }

    /// Font snapshot shared by layout and explicit SVG parsing.
    pub fn fonts(&self) -> Option<&crate::asset::environment::FontEnvironment> {
        self.context.fonts()
    }

    /// Captures a project asset directory without reading/decode/device work.
    pub fn new(root: impl AsRef<Path>) -> crate::Result<Self> {
        Ok(Self {
            context: LoadContext {
                root: Arc::new(std::path::absolute(root)?),
                fonts: None,
                namespace: 0,
            },
            entries: Arc::new(Mutex::new(BTreeMap::new())),
            pool: ResourcePool::new(),
            diagnostics: None,
        })
    }

    /// Requests a lazy typed handle. Matching type/root/font snapshot/source shares
    /// one entry only among owners attached to the same ResourcePool. Creating a
    /// handle performs no file decode. Relative parent traversal is rejected.
    pub fn load<A: Asset>(&self, source: impl Into<Source>) -> Handle<A> {
        let mut source = source.into();
        let failure = if let Source::File(path) = &mut source {
            if self.context.root.as_os_str().is_empty() && !path.is_absolute() {
                Some("Relative file assets require an explicit project root")
            } else if path
                .components()
                .any(|component| component == std::path::Component::ParentDir)
            {
                Some("Asset paths must not contain parent traversal")
            } else {
                if !path.is_absolute() {
                    *path = self.context.root.join(&*path);
                }
                None
            }
        } else if let Source::Bytes { key, data } = &source {
            if data.len() > MAX_ENCODED {
                Some("Asset source exceeds 64 MiB")
            } else if key.is_empty() || key.len() > 1024 || key.chars().any(char::is_control) {
                Some("Asset byte keys require 1..=1024 bytes without control characters")
            } else {
                None
            }
        } else {
            None
        };
        let key = (
            TypeId::of::<A>(),
            self.context.root.as_ref().clone(),
            self.context
                .fonts
                .as_ref()
                .map_or(0, crate::asset::environment::FontEnvironment::snapshot_id),
            self.context.namespace,
            source.clone(),
        );
        let mut entries = self
            .entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if failure.is_none()
            && let Some(entry) = entries.get(&key)
        {
            return Handle {
                entry: entry
                    .value
                    .clone()
                    .downcast::<Entry<A>>()
                    .expect("typed resource key"),
                diagnostics: self.diagnostics.clone(),
            };
        }
        let mut global = self
            .pool
            .0
            .entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        global.retain(|_, entry| entry.strong_count() > 0);
        let failure = failure.or_else(|| {
            (entries.len() >= self.pool.0.max_entries)
                .then_some("Resource cache exceeds its entry allowance")
        });
        if failure.is_none()
            && let Some(entry) = global.get(&key).and_then(Weak::upgrade)
        {
            let entry = entry.downcast::<Entry<A>>().expect("typed global key");
            entries.insert(key, OwnedEntry::new(entry.clone()));
            return Handle {
                entry,
                diagnostics: self.diagnostics.clone(),
            };
        }
        let mut failure = failure.or_else(|| {
            (global.len() >= self.pool.0.max_entries)
                .then_some("Resource cache exceeds its entry allowance")
        });
        let mut charged = 0;
        if failure.is_none()
            && let Source::Bytes { data, .. } = &source
        {
            if self
                .pool
                .0
                .bytes
                .try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                    current
                        .checked_add(data.len())
                        .filter(|total| *total <= self.pool.0.max_bytes)
                })
                .is_ok()
            {
                charged = data.len();
            } else {
                failure = Some("Shared asset-cache logical payload exceeds its allowance");
            }
        }
        if failure.is_some()
            && let Source::Bytes { data, .. } = &mut source
        {
            *data = Arc::from([]);
        }
        let entry = Arc::new(Entry {
            pool: self.pool.clone(),
            source,
            context: self.context.clone(),
            result: OnceLock::new(),
            loading: AtomicBool::new(false),
            charged: AtomicUsize::new(charged),
        });
        if let Some(message) = failure {
            let source_name = match &entry.source {
                Source::File(path) => path.display().to_string(),
                Source::Bytes { key, .. } => key.to_string(),
            };
            let _result = entry.result.set(Err(Arc::new(crate::Error::asset(
                A::KIND,
                source_name,
                io::Error::new(io::ErrorKind::InvalidInput, message),
            ))));
        } else {
            let erased: Arc<Erased> = entry.clone();
            global.insert(key.clone(), Arc::downgrade(&erased));
            entries.insert(key, OwnedEntry::new(entry.clone()));
        }
        Handle {
            entry,
            diagnostics: self.diagnostics.clone(),
        }
    }
}