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
use std::sync::{Arc, Mutex, MutexGuard};
use std::sync::mpsc::{channel, Receiver};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::atomic::{AtomicUsize, Ordering};

use hibitset::{BitSet, BitSetLike};
use futures::{Future, Stream};
use futures::future::Executor;
use futures::sync::mpsc;
use futures::sync::oneshot;

use super::{Asset, AssetEvent, AssetFormat, Handle, Loader, Storage};

pub struct AssetManager<A, L>
where
    A: Asset,
    A::Data: AssetFormat<Input = L::Output>,
    L: Loader,
{
    id: AtomicUsize,
    event_sender: mpsc::UnboundedSender<AssetEvent<A, L>>,
    receiver: Receiver<AssetEvent<A, L>>,
    storage: Arc<Storage<A::Data>>,
    loading: Arc<Mutex<BitSet>>,
    loaded: Arc<Mutex<BitSet>>,
    data: HashMap<Handle<A>, (L::Path, L::Options, <A::Data as AssetFormat>::Options)>,
    futures: Arc<Mutex<HashMap<u32, oneshot::Sender<()>>>>,
    loader: Arc<L>,
    executor: Arc<Executor<Box<Future<Item = (), Error = ()> + Send>>>,
}

unsafe impl<A, L> Send for AssetManager<A, L>
where
    A: Asset,
    A::Data: AssetFormat<Input = L::Output>,
    L: Loader,
{
}
unsafe impl<A, L> Sync for AssetManager<A, L>
where
    A: Asset,
    A::Data: AssetFormat<Input = L::Output>,
    L: Loader,
{
}

impl<A, L> AssetManager<A, L>
where
    A: Asset,
    A::Data: AssetFormat<Input = L::Output>,
    L: Loader,
{
    #[inline]
    pub fn new(
        loader: Arc<L>,
        executor: Arc<Executor<Box<Future<Item = (), Error = ()> + Send>>>,
    ) -> Self {
        let (sender, receiver) = channel();
        let (event_sender, event_receiver) = mpsc::unbounded();
        let future_receiver = event_receiver.map_err(|_| ()).for_each(move |event| {
            sender.send(event).unwrap();
            Ok(())
        });

        executor.execute(Box::new(future_receiver)).unwrap();

        AssetManager {
            id: AtomicUsize::new(0),
            event_sender: event_sender,
            receiver: receiver,
            storage: Arc::new(Storage::new()),
            loading: Arc::new(Mutex::new(BitSet::new())),
            loaded: Arc::new(Mutex::new(BitSet::new())),
            data: HashMap::new(),
            futures: Arc::new(Mutex::new(HashMap::new())),
            loader: loader,
            executor: executor.clone(),
        }
    }

    #[inline]
    pub fn future(&mut self, handle: &Handle<A>) -> Option<oneshot::Receiver<()>> {
        match self.futures
            .lock()
            .expect("failed to acquire futures lock")
            .entry(handle.id())
        {
            Entry::Occupied(_) => None,
            Entry::Vacant(vacant) => {
                let (sender, receiver) = oneshot::channel();
                vacant.insert(sender);
                Some(receiver)
            }
        }
    }

    #[inline]
    pub fn wait_event(&self) -> Option<AssetEvent<A, L>> {
        match self.receiver.recv() {
            Ok(event) => Some(event),
            Err(_) => None,
        }
    }

    #[inline]
    pub fn poll_event(&self) -> Option<AssetEvent<A, L>> {
        match self.receiver.try_recv() {
            Ok(event) => Some(event),
            Err(_) => None,
        }
    }

    #[inline]
    pub fn poll_events(&self) -> Vec<AssetEvent<A, L>> {
        let mut events = Vec::new();

        while let Ok(event) = self.receiver.try_recv() {
            events.push(event);
        }

        events
    }

    #[inline]
    fn next_id(&self) -> u32 {
        self.id.fetch_add(1, Ordering::Relaxed) as u32
    }

    #[inline]
    fn loading(&self) -> MutexGuard<BitSet> {
        self.loading.lock().expect("failed to acquire loading lock")
    }
    #[inline]
    fn loaded(&self) -> MutexGuard<BitSet> {
        self.loaded.lock().expect("failed to acquire loaded lock")
    }
    #[inline(always)]
    pub fn data(
        &self,
    ) -> &HashMap<Handle<A>, (L::Path, L::Options, <A::Data as AssetFormat>::Options)> {
        &self.data
    }

    #[inline]
    pub fn is_loaded(&self, handle: &Handle<A>) -> bool {
        self.loaded().contains(handle.id())
    }
    #[inline]
    pub fn is_loading(&self, handle: &Handle<A>) -> bool {
        self.loading().contains(handle.id())
    }

    #[inline]
    pub fn asset_count(&self) -> usize {
        self.data.len()
    }
    #[inline]
    pub fn loaded_count(&self) -> usize {
        let loaded = self.loaded();
        (&*loaded).iter().count()
    }
    #[inline]
    pub fn loading_count(&self) -> usize {
        let loading = self.loading();
        (&*loading).iter().count()
    }

    #[inline]
    pub fn add(
        &mut self,
        path: L::Path,
        loader_options: L::Options,
        format_options: <A::Data as AssetFormat>::Options,
        preload: bool,
    ) -> Handle<A> {
        let next_id = self.next_id();
        let handle = Handle::new(self.next_id());

        unsafe {
            self.storage.reserve(next_id as usize);
        }

        self.data
            .insert(handle.clone(), (path, loader_options, format_options));

        if preload {
            self.load(&handle);
        }

        handle
    }

    #[inline]
    pub fn remove(&mut self, handle: Handle<A>) -> bool {
        let id = handle.id();

        if self.loaded().remove(id) {
            let data = unsafe { self.storage.remove(id) };

            self.event_sender
                .unbounded_send(AssetEvent::Remove(handle, data))
                .expect("failed to send asset event");

            true
        } else {
            false
        }
    }

    #[inline]
    pub fn get(&self, handle: &Handle<A>) -> Option<&A::Data> {
        let id = handle.id();

        if self.loaded().contains(id) {
            self.storage.get(id)
        } else {
            if !self.loading().contains(id) {
                self.load(handle);
            }
            None
        }
    }

    #[inline]
    pub fn get_mut(&mut self, handle: &Handle<A>) -> Option<&mut A::Data> {
        let id = handle.id();

        if self.loaded().contains(id) {
            self.storage.get_mut(id)
        } else {
            if !self.loading().contains(id) {
                self.load(handle);
            }
            None
        }
    }

    #[inline]
    fn load(&self, handle: &Handle<A>) {
        let &(ref p, ref lo, ref fo) = self.data.get(handle).expect("load called with invalid id");
        let path = p.clone();
        let loader_options = lo.clone();
        let format_options = fo.clone();
        let id = handle.id();

        self.loading().add(id);

        let storage = self.storage.clone();
        let loading = self.loading.clone();
        let loaded = self.loaded.clone();
        let futures = self.futures.clone();

        let load_handle = handle.clone();
        let load_error_handle = handle.clone();
        let format_error_handle = handle.clone();

        let format_error_sender = self.event_sender.clone();
        let loader_error_sender = self.event_sender.clone();

        let f = self.loader
            .load(path, loader_options)
            .map(
                move |output| match <A::Data as AssetFormat>::format(output, format_options) {
                    Ok(a) => unsafe {
                        loading
                            .lock()
                            .expect("failed to acquire loading lock")
                            .remove(id);
                        loaded
                            .lock()
                            .expect("failed to acquire loaded lock")
                            .add(id);

                        storage.insert(id, a);

                        format_error_sender
                            .unbounded_send(AssetEvent::Load(load_handle))
                            .expect("failed to send asset event");

                        if let Some(sender) = futures
                            .lock()
                            .expect("failed to acquire futures lock")
                            .remove(&id)
                        {
                            sender.send(()).expect("failed to send future");
                        }
                    },
                    Err(e) => format_error_sender
                        .unbounded_send(AssetEvent::FormatError(format_error_handle, e))
                        .expect("failed to send asset event"),
                },
            )
            .map_err(move |e| {
                loader_error_sender
                    .unbounded_send(AssetEvent::LoadError(load_error_handle, e))
                    .expect("failed to send asset event")
            });

        self.executor.execute(Box::new(f)).unwrap();
    }
}

impl<A, L> Drop for AssetManager<A, L>
where
    A: Asset,
    A::Data: AssetFormat<Input = L::Output>,
    L: Loader,
{
    #[inline]
    fn drop(&mut self) {
        unsafe {
            self.storage.clean(&*self.loaded());
        }
    }
}