-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassets.js
More file actions
93 lines (74 loc) · 1.97 KB
/
assets.js
File metadata and controls
93 lines (74 loc) · 1.97 KB
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
// assets that need to load before we can start
const expectedAssets = [ "storyfile" ];
// functions that are called when all assets have loaded
const callbacks = [];
// the callback that's called the very last
let lastCallback;
/**
* When all assets are ready, run the callbacks.
*/
async function done() {
for( let i = 0; i < callbacks.length; ++i ) {
await callbacks[ i ]();
}
if( lastCallback ) {
await lastCallback();
}
}
/**
* Adds a callback that's run when all assets are ready.
* If all assets have already loaded, call the callback immediately.
*
* The first parameter of the callback function must be a function that
* itself calls as a callback when it has finished.
*
* @param cb
*/
export function addCallback( cb ) {
if( expectedAssets.length === 0 ) {
// make the function consistently asynchronous
setTimeout( cb, 0 );
}
callbacks.push( cb );
}
/**
* Add an expected asset to the list.
*
* @param {function} asset
*/
export function expect( asset ) {
if( expectedAssets.length === 0 ) {
console.warn( "An expected asset \"" + asset + "\" was added "
+ "but all previous assets have already finished loading" );
return;
}
expectedAssets.push( asset );
}
/**
* As a bit of a hack this ensures the game starting callback is always
* the last one.
*
* @param cb
*/
export function finalCallback( cb ) {
lastCallback = cb;
}
/**
* When an asset has finished loading, this method should be called.
*
* @param asset The name of the asset that's ready
* @returns {boolean} true if asset was expected
*/
export function finished( asset ) {
const index = expectedAssets.indexOf( asset );
if( index === -1 ) {
return false;
}
// remove from the list of expected assets
expectedAssets.splice( index, 1 );
// if everything's ready, run the callbacks
if( expectedAssets.length === 0 ) {
done();
}
return true;
}