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
use std::{borrow::Borrow, hash::Hash, path::PathBuf, sync::Arc};

use fnv::FnvHashMap;
use log::debug;
use rayon::ThreadPool;

use amethyst_error::ResultExt;
#[cfg(feature = "profiler")]
use thread_profiler::profile_scope;

use crate::{
    error::Error,
    storage::{AssetStorage, Handle, Processed},
    Asset, Directory, Format, FormatValue, Progress, Source,
};

/// The asset loader, holding the sources and a reference to the `ThreadPool`.
pub struct Loader {
    hot_reload: bool,
    pool: Arc<ThreadPool>,
    sources: FnvHashMap<String, Arc<dyn Source>>,
}

impl Loader {
    /// Creates a new asset loader, initializing the directory store with the
    /// given path.
    pub fn new<P>(directory: P, pool: Arc<ThreadPool>) -> Self
    where
        P: Into<PathBuf>,
    {
        Self::with_default_source(Directory::new(directory), pool)
    }

    /// Creates a new asset loader, using the provided source
    pub fn with_default_source<S>(source: S, pool: Arc<ThreadPool>) -> Self
    where
        S: Source,
    {
        let mut loader = Loader {
            hot_reload: true,
            pool,
            sources: Default::default(),
        };

        loader.set_default_source(source);
        loader
    }

    /// Add a source to the `Loader`, given an id and the source.
    pub fn add_source<I, S>(&mut self, id: I, source: S)
    where
        I: Into<String>,
        S: Source,
    {
        self.sources
            .insert(id.into(), Arc::new(source) as Arc<dyn Source>);
    }

    /// Set the default source of the `Loader`.
    pub fn set_default_source<S>(&mut self, source: S)
    where
        S: Source,
    {
        self.add_source(String::new(), source);
    }

    /// If set to `true`, this `Loader` will ask formats to
    /// generate "reload instructions" which *allow* reloading.
    /// Calling `set_hot_reload(true)` does not actually enable
    /// hot reloading; this is controlled by the `HotReloadStrategy`
    /// resource.
    pub fn set_hot_reload(&mut self, value: bool) {
        self.hot_reload = value;
    }

    /// Loads an asset with a given format from the default (directory) source.
    /// If you want to load from a custom source instead, use `load_from`.
    ///
    /// See `load_from` for more information.
    pub fn load<A, F, N, P>(
        &self,
        name: N,
        format: F,
        progress: P,
        storage: &AssetStorage<A>,
    ) -> Handle<A>
    where
        A: Asset,
        F: Format<A::Data>,
        N: Into<String>,
        P: Progress,
    {
        #[cfg(feature = "profiler")]
        profile_scope!("initialise_loading_assets");
        self.load_from::<A, F, _, _, _>(name, format, "", progress, storage)
    }

    /// Loads an asset with a given id and format from a custom source.
    /// The actual work is done in a worker thread, thus this method immediately returns a handle.
    ///
    /// ## Parameters
    ///
    /// * `name`: this is just an identifier for the asset, most likely a file name e.g.
    ///   `"meshes/a.obj"`
    /// * `format`: A format struct which loads bytes from a `source` and produces `Asset::Data`
    ///   with them
    /// * `source`: An identifier for a source which has previously been added using `with_source`
    /// * `progress`: A tracker which will be notified of assets which have been imported
    /// * `storage`: The asset storage which can be fetched from the ECS `World` using
    ///   `read_resource`.
    pub fn load_from<A, F, N, P, S>(
        &self,
        name: N,
        format: F,
        source: &S,
        mut progress: P,
        storage: &AssetStorage<A>,
    ) -> Handle<A>
    where
        A: Asset,
        F: Format<A::Data>,
        N: Into<String>,
        P: Progress,
        S: AsRef<str> + Eq + Hash + ?Sized,
        String: Borrow<S>,
    {
        #[cfg(feature = "profiler")]
        profile_scope!("load_asset_from");
        use crate::progress::Tracker;

        let name = name.into();
        let source = source.as_ref();

        let format_name = format.name();
        let source_name = match source {
            "" => "[default source]",
            other => other,
        };

        let handle = storage.allocate();

        debug!(
            "{:?}: Loading asset {:?} with format {:?} from source {:?} (handle id: {:?})",
            A::NAME,
            name,
            format_name,
            source_name,
            handle,
        );

        progress.add_assets(1);
        let tracker = progress.create_tracker();

        let source = self.source(source);
        let handle_clone = handle.clone();
        let processed = storage.processed.clone();

        let hot_reload = if self.hot_reload {
            Some(objekt::clone_box(&format) as Box<dyn Format<A::Data>>)
        } else {
            None
        };

        let cl = move || {
            #[cfg(feature = "profiler")]
            profile_scope!("load_asset_from_worker");
            let data = format
                .import(name.clone(), source, hot_reload)
                .with_context(|_| Error::Format(format_name));
            let tracker = Box::new(tracker) as Box<dyn Tracker>;

            processed.push(Processed::NewAsset {
                data,
                handle,
                name,
                tracker,
            });
        };
        self.pool.spawn(cl);

        handle_clone
    }

    /// Load an asset from data and return a handle.
    pub fn load_from_data<A, P>(
        &self,
        data: A::Data,
        mut progress: P,
        storage: &AssetStorage<A>,
    ) -> Handle<A>
    where
        A: Asset,
        P: Progress,
    {
        progress.add_assets(1);
        let tracker = progress.create_tracker();
        let tracker = Box::new(tracker);
        let handle = storage.allocate();
        storage.processed.push(Processed::NewAsset {
            data: Ok(FormatValue::data(data)),
            handle: handle.clone(),
            name: "<Data>".into(),
            tracker,
        });

        handle
    }

    /// Asynchronously load an asset from data and return a handle.
    pub fn load_from_data_async<A, P, F>(
        &self,
        data: F,
        mut progress: P,
        storage: &AssetStorage<A>,
    ) -> Handle<A>
    where
        A: Asset,
        P: Progress,
        F: FnOnce() -> A::Data + Send + Sync + 'static,
    {
        progress.add_assets(1);
        let tracker = progress.create_tracker();
        let tracker = Box::new(tracker);
        let handle = storage.allocate();
        let processed = storage.processed.clone();

        self.pool.spawn({
            let handle = handle.clone();
            move || {
                processed.push(Processed::NewAsset {
                    data: Ok(FormatValue::data(data())),
                    handle: handle.clone(),
                    name: "<Data>".into(),
                    tracker,
                });
            }
        });

        handle
    }

    fn source(&self, source: &str) -> Arc<dyn Source> {
        self.sources
            .get(source)
            .expect("No such source. Maybe you forgot to add it with `Loader::add_source`?")
            .clone()
    }
}