furmint-resources 0.1.0

Resources abstractions for `furmint`
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
use crate::loader::{Asset, ErasedAssetLoader};
use crate::{ResourceError, ResourceResult};
use log::debug;
use specs::Component;
use specs::VecStorage;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::marker::PhantomData;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};

/// Asset server struct
#[derive(Debug, Default)]
pub struct AssetServer {
    root: Option<PathBuf>,
    /// loaders for assets, asset  typeid -> loader
    loaders: HashMap<TypeId, Box<dyn ErasedAssetLoader>>,
    /// caches for assets, asset  typeid -> cache (which is an `Any`, but internally downcasted to a hashmap of assets of that type)
    caches: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
    /// metadat for assets, asset typeid -> metadata
    metas: HashMap<UntypedAssetId, Metadata>,
}

/// Resource read-only handle
#[derive(Clone, Component, Debug)]
#[storage(VecStorage)]
pub struct Handle<A: Asset + ?Sized> {
    id: AssetId<A>,
    inner: Arc<RwLock<A>>,
}

/// Asset ID
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct AssetId<A: Asset + ?Sized> {
    // honey look!!!! somebody's def gonna insert fucking u32::MAX assets and cause the funny thing
    raw: u32,
    generation: u32,
    _marker: PhantomData<fn() -> A>,
}

impl<A: Asset + ?Sized> Copy for AssetId<A> {}

impl<A: Asset + ?Sized> Clone for AssetId<A> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<A: Asset + ?Sized> AssetId<A> {
    pub(crate) fn new(raw: u32, generation: u32) -> Self {
        Self {
            raw,
            generation,
            _marker: PhantomData,
        }
    }

    pub(crate) fn index(&self) -> usize {
        self.raw as usize
    }

    #[allow(unused)]
    pub(crate) fn raw(&self) -> u32 {
        self.raw
    }

    pub(crate) fn generation(&self) -> u32 {
        self.generation
    }
}

impl<A: Asset> AssetId<A> {
    pub(crate) fn untyped(self) -> UntypedAssetId {
        UntypedAssetId {
            type_id: TypeId::of::<A>(),
            raw: self.raw,
            generation: self.generation,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct UntypedAssetId {
    type_id: TypeId,
    raw: u32,
    generation: u32,
}

#[derive(Debug, Clone)]
pub(crate) struct Metadata {
    source: AssetSource,
    _type_id: TypeId,
}

#[derive(Debug, Clone)]
#[allow(unused)]
pub(crate) enum AssetSource {
    File {
        path: PathBuf,
        modified: std::time::SystemTime,
    },
    Reader,
    Internal,
}

#[derive(Debug)]
struct AssetSlot<A: Asset> {
    generation: u32,
    asset: Option<Arc<RwLock<A>>>,
}

#[derive(Debug)]
struct AssetCache<A: Asset> {
    assets: Vec<AssetSlot<A>>,
    names: HashMap<String, AssetId<A>>,
}

impl<A: Asset> AssetCache<A> {
    fn new() -> Self {
        Self {
            assets: Vec::new(),
            names: HashMap::new(),
        }
    }

    fn insert(&mut self, asset: A) -> Handle<A> {
        let raw = self.assets.len() as u32;
        let generation = 0;
        let id = AssetId::new(raw, generation);

        let handle = Handle::new(id, asset);

        self.assets.push(AssetSlot {
            generation,
            asset: Some(handle.inner()),
        });

        handle
    }

    fn insert_named(&mut self, name: String, asset: A) -> Handle<A> {
        let handle = self.insert(asset);
        self.names.insert(name, handle.id());
        handle
    }

    fn get(&self, id: AssetId<A>) -> Option<Handle<A>> {
        let slot = self.assets.get(id.index())?;

        if slot.generation != id.generation() {
            return None;
        }

        let inner = slot.asset.as_ref()?.clone();

        Some(Handle::from_inner(id, inner))
    }

    fn get_named(&self, name: &str) -> Option<Handle<A>> {
        let id = self.names.get(name)?;
        self.get(*id)
    }

    fn id_named(&self, name: &str) -> Option<AssetId<A>> {
        self.names.get(name).copied()
    }

    fn reload(&mut self, id: AssetId<A>, new_asset: A) -> ResourceResult<()> {
        let slot = self
            .assets
            .get_mut(id.index())
            .ok_or(ResourceError::ResourceDoesNotExist)?;

        if slot.generation != id.generation() {
            return Err(ResourceError::ResourceDoesNotExist);
        }

        let existing = slot
            .asset
            .as_ref()
            .ok_or(ResourceError::ResourceDoesNotExist)?;

        *existing.write().expect("asset lock poisoned") = new_asset;

        Ok(())
    }
}

impl<A: Asset> Handle<A> {
    /// Get [`AssetId`] of this handle
    pub fn id(&self) -> AssetId<A> {
        self.id
    }

    pub(crate) fn new(id: AssetId<A>, asset: A) -> Self {
        Self {
            id,
            inner: Arc::new(RwLock::new(asset)),
        }
    }

    pub(crate) fn from_inner(id: AssetId<A>, inner: Arc<RwLock<A>>) -> Self {
        Self { id, inner }
    }

    pub(crate) fn inner(&self) -> Arc<RwLock<A>> {
        self.inner.clone()
    }

    /// Get a reading lock from the asset
    pub fn read(&self) -> AssetRead<'_, A> {
        AssetRead {
            guard: self.inner.read().expect("asset lock poisoned"),
        }
    }

    /// Get a writing lock into the asset
    pub fn write(&self) -> AssetWrite<'_, A> {
        AssetWrite {
            guard: self.inner.write().expect("asset lock poisoned"),
        }
    }
}

impl AssetServer {
    /// Create a new instance of [`AssetServer`]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create an [`AssetServer`] that can load assets from the filesystem
    pub fn with_root(root: impl Into<PathBuf>) -> Self {
        Self {
            root: Some(root.into()),
            ..Self::default()
        }
    }

    /// Register an asset type without registering a loader
    ///
    /// Useful for internal/generated assets
    pub fn register_asset_type<A: Asset>(&mut self) {
        self.caches
            .entry(TypeId::of::<A>())
            .or_insert_with(|| Box::new(AssetCache::<A>::new()));
    }

    /// Register an asset loader
    pub fn register_loader<A: Asset>(&mut self, loader: Box<dyn ErasedAssetLoader>) {
        self.register_asset_type::<A>();
        self.loaders.insert(TypeId::of::<A>(), loader);
    }

    /// Load asset into cache from a reader
    ///
    /// # Warning
    /// Assets loaded with this function won't be hot-reloadable
    pub fn load_reader<A: Asset>(
        &mut self,
        name: &str,
        reader: &mut dyn Read,
    ) -> ResourceResult<Handle<A>> {
        let asset = self.load_asset_from_reader::<A>(reader)?;

        let handle = self
            .cache_mut::<A>()
            .expect("asset cache was not registered")
            .insert_named(name.to_string(), asset);

        self.metas.insert(
            handle.id().untyped(),
            Metadata {
                source: AssetSource::Reader,
                _type_id: TypeId::of::<A>(),
            },
        );

        Ok(handle)
    }

    /// Insert an internal/generated asset into the cache
    pub fn insert<A: Asset>(&mut self, asset: A) -> ResourceResult<Handle<A>> {
        let handle = self
            .cache_mut::<A>()
            .expect("asset cache was not registered")
            .insert(asset);

        self.metas.insert(
            handle.id().untyped(),
            Metadata {
                source: AssetSource::Internal,
                _type_id: TypeId::of::<A>(),
            },
        );

        Ok(handle)
    }

    /// Insert an internal/generated asset with a name alias
    pub fn insert_named<A: Asset>(
        &mut self,
        name: impl Into<String>,
        asset: A,
    ) -> ResourceResult<Handle<A>> {
        let handle = self
            .cache_mut::<A>()
            .expect("asset cache was not registered")
            .insert_named(name.into(), asset);

        self.metas.insert(
            handle.id().untyped(),
            Metadata {
                source: AssetSource::Internal,
                _type_id: TypeId::of::<A>(),
            },
        );

        Ok(handle)
    }

    /// Load asset into cache from file
    ///
    /// The extension will be stripped and the asset inserted under that name.
    /// For example, `music.ogg` is inserted as `music`
    pub fn load<A: Asset>(&mut self, path: impl Into<PathBuf>) -> ResourceResult<Handle<A>> {
        let root = self
            .root
            .as_ref()
            .ok_or(ResourceError::AssetServerUnsupported)?;

        let path = path.into();
        let name = asset_name(&path)?;
        let full_path = root.join(&path);

        debug!("loading asset from {:?}", full_path);

        let modified = std::fs::metadata(&full_path)?.modified()?;

        let mut reader = File::open(&full_path)?;
        let asset = self.load_asset_from_reader::<A>(&mut reader)?;

        let handle = self
            .cache_mut::<A>()
            .expect("asset cache was not registered")
            .insert_named(name, asset);

        self.metas.insert(
            handle.id().untyped(),
            Metadata {
                source: AssetSource::File {
                    path: full_path,
                    modified,
                },
                _type_id: TypeId::of::<A>(),
            },
        );

        Ok(handle)
    }

    /// Get asset handle from server by ID
    pub fn get<A: Asset>(&self, id: AssetId<A>) -> Option<Handle<A>> {
        self.cache::<A>()?.get(id)
    }

    /// Get asset handle from server by name
    pub fn get_named<A: Asset>(&self, name: &str) -> Option<Handle<A>> {
        self.cache::<A>()?.get_named(name)
    }

    /// Get asset ID from name
    pub fn id_named<A: Asset>(&self, name: &str) -> Option<AssetId<A>> {
        self.cache::<A>()?.id_named(name)
    }

    /// Hot-reload an asset by ID
    pub fn reload<A: Asset>(&mut self, id: AssetId<A>) -> ResourceResult<()> {
        self.root
            .as_ref()
            .ok_or(ResourceError::AssetServerUnsupported)?;

        let source = self
            .metas
            .get(&id.untyped())
            .ok_or(ResourceError::ResourceDoesNotExist)?
            .source
            .clone();

        let AssetSource::File { path, .. } = source else {
            return Err(ResourceError::ResourceDoesNotExist);
        };

        let mut reader = File::open(&path)?;
        let new_asset = self.load_asset_from_reader::<A>(&mut reader)?;

        self.cache_mut::<A>()
            .expect("asset cache was not registered")
            .reload(id, new_asset)?;

        Ok(())
    }

    /// Hot-reload an asset by name
    pub fn reload_named<A: Asset>(&mut self, name: &str) -> ResourceResult<()> {
        let id = self
            .id_named::<A>(name)
            .ok_or(ResourceError::ResourceDoesNotExist)?;

        self.reload(id)
    }

    fn load_asset_from_reader<A: Asset>(&self, reader: &mut dyn Read) -> ResourceResult<A> {
        let loader = self
            .loaders
            .get(&TypeId::of::<A>())
            .ok_or(ResourceError::LoaderNotFound)?;

        loader
            .load_erased(reader)?
            .downcast::<A>()
            .map(|asset| *asset)
            .map_err(|_| ResourceError::LoaderReturnedWrongType)
    }

    fn cache<A: Asset>(&self) -> Option<&AssetCache<A>> {
        self.caches
            .get(&TypeId::of::<A>())?
            .downcast_ref::<AssetCache<A>>()
    }

    fn cache_mut<A: Asset>(&mut self) -> Option<&mut AssetCache<A>> {
        self.caches
            .get_mut(&TypeId::of::<A>())?
            .downcast_mut::<AssetCache<A>>()
    }
}

fn asset_name(path: &Path) -> ResourceResult<String> {
    path.with_extension("")
        .to_str()
        .map(ToOwned::to_owned)
        .ok_or(ResourceError::NotFound(path.to_path_buf()))
}

/// Wrapper for reading from the asset
pub struct AssetRead<'a, A> {
    guard: RwLockReadGuard<'a, A>,
}

impl<A> Deref for AssetRead<'_, A> {
    type Target = A;

    fn deref(&self) -> &Self::Target {
        &self.guard
    }
}

/// Wrapper for writing into the asset
pub struct AssetWrite<'a, A> {
    guard: RwLockWriteGuard<'a, A>,
}

impl<A> Deref for AssetWrite<'_, A> {
    type Target = A;

    fn deref(&self) -> &Self::Target {
        &self.guard
    }
}

impl<A> std::ops::DerefMut for AssetWrite<'_, A> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.guard
    }
}