limnus_assets_loader/
lib.rs

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
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/limnus
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */
use limnus_app::prelude::{App, Plugin};
use limnus_assets::prelude::{Asset, RawWeakId};
use limnus_resource::prelude::Resource;
pub use limnus_resource::ResourceStorage;
use std::any::{type_name, TypeId};
use std::collections::HashMap;
use std::fmt::Debug;
use std::io;
use std::io::Error;
use std::sync::{Arc, Mutex};
use tracing::debug;

#[derive(Debug)]
pub enum LoadError {
    MissingLoader(RawWeakId),
    ConversionError(ConversionError),
    Downcast,
}

#[derive(Debug)]
pub enum ConversionError {
    WrongFormat,
    IoError(io::Error),
}

impl From<ConversionError> for LoadError {
    fn from(err: ConversionError) -> Self {
        Self::ConversionError(err)
    }
}

impl From<io::Error> for ConversionError {
    fn from(value: Error) -> Self {
        Self::IoError(value)
    }
}

pub trait AssetLoader: Send + Sync {
    type AssetType: Asset + 'static;

    /// # Errors
    /// TODO: Add more here
    fn convert_and_insert(
        &self,
        id: RawWeakId,
        octets: &[u8],
        world: &mut ResourceStorage,
    ) -> Result<(), ConversionError>;
}

type TypeIdMap<T> = HashMap<TypeId, T>;

pub trait AnyAssetLoader: Send + Sync {
    /// # Errors
    /// TODO: Add more here
    fn convert_and_insert_erased(
        &self,
        id: RawWeakId,
        octets: &[u8],
        resources: &mut ResourceStorage,
    ) -> Result<(), LoadError>;

    fn asset_type_id(&self) -> TypeId;
}

impl<T> AnyAssetLoader for T
where
    T: AssetLoader + 'static,
{
    fn convert_and_insert_erased(
        &self,
        id: RawWeakId,
        octets: &[u8],
        resources: &mut ResourceStorage,
    ) -> Result<(), LoadError> {
        self.convert_and_insert(id, octets, resources)
            .map_err(LoadError::from)
    }

    fn asset_type_id(&self) -> TypeId {
        TypeId::of::<T::AssetType>()
    }
}

#[derive(Resource)]
pub struct WrappedAssetLoaderRegistry {
    pub value: Arc<Mutex<AssetLoaderRegistry>>,
}

impl Debug for WrappedAssetLoaderRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "WrappedAssetLoaderRegistry")
    }
}

#[derive(Default)]
pub struct AssetLoaderRegistry {
    loaders: TypeIdMap<Box<dyn AnyAssetLoader>>,
}

impl Debug for AssetLoaderRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "AssetLoaderRegistry")
    }
}

impl AssetLoaderRegistry {
    #[must_use]
    pub fn new() -> Self {
        Self {
            loaders: TypeIdMap::new(),
        }
    }

    pub fn register_loader<T>(&mut self, loader: T)
    where
        T: AssetLoader + 'static,
    {
        debug!(
            asset_type = type_name::<T::AssetType>(),
            loader = type_name::<T>(),
            "registering asset loader",
        );
        self.loaders
            .insert(loader.asset_type_id(), Box::new(loader));
    }

    /// # Errors
    /// If missing or conversion failed
    pub fn convert_and_insert(
        &self,
        id: RawWeakId,
        octets: &[u8],
        resources: &mut ResourceStorage,
    ) -> Result<(), LoadError> {
        let loader = self
            .loaders
            .get(&id.type_id())
            .ok_or(LoadError::MissingLoader(id))?;

        loader.convert_and_insert_erased(id, octets, resources)
    }
}

pub struct AssetLoaderRegistryPlugin;

impl Plugin for AssetLoaderRegistryPlugin {
    fn build(&self, app: &mut App) {
        let loader_registry = WrappedAssetLoaderRegistry {
            value: Arc::new(Mutex::new(AssetLoaderRegistry::new())),
        };
        app.insert_resource(loader_registry);
    }
}