This repository was archived by the owner on May 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathResourceLoader.js
104 lines (93 loc) · 2.79 KB
/
ResourceLoader.js
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
var io = require('pex-io');
/**
* ResourceLoader class
* @class
*/
var ResourceLoader = {
}
/**
* Load provided resources
* @param {Object} resources - map of resources, see example
* @param {Function} callback function(err, resources), see example
* @returns {Object} - with same properties are resource list but resolved to the actual data
*
* @example
* var glslify = require('glslify-promise');
* var resources = {
* vert : { glsl: glslify(__dirname + '/shader.vert') },
* frag : { glsl: glslify(__dirname + '/shader.frag') },
* img : { image: __dirname + '/tex.jpg', crossOrigin: true/false},
* hdrImg : { binary: __dirname + '/tex.hdr'}
* data : { json: __dirname + '/data.json'},
* hello : { text: __dirname + '/hello.txt'}
* };
* Resource.load(resources, function(err, res) {
* res.vert //{Promise}
* res.frag //{Promise}
* res.img //{Image} in a Browser or {SkCanvas} in Plask
* res.hdrImg //{ArrayBuffer}
* res.data //{JSON}
* res.hello //{String}
* })
*/
ResourceLoader.load = function(resources, callback) {
var results = {};
var errors = {};
var hadErrors = false;
//TODO: use `async` module instead?
var loadedResources = 0;
var resourceNames = Object.keys(resources);
var numResources = resourceNames.length;
function onFinish() {
if (hadErrors) {
callback(errors, null);
}
else {
callback(null, resources);
}
}
resourceNames.forEach(function(name) {
function onLoaded(err, data) {
if (err) {
hadErrors = true;
errors[name] = err;
}
else {
resources[name] = data;
}
if (++loadedResources == numResources) {
onFinish();
}
}
var res = resources[name];
if (res.image) {
io.loadImage(res.image, onLoaded, res.crossOrigin);
}
else if (res.text) {
io.loadText(res.text, onLoaded);
}
else if (res.json) {
io.loadJSON(res.json, onLoaded);
}
else if (res.binary) {
io.loadBinary(res.binary, onLoaded);
}
else if (res.glsl) {
res.glsl.then(function(glslString) {
//Escape promise catch-all-errors sinkhole
setTimeout(function() {
onLoaded(null, glslString);
}, 1);
}).catch(function(e) {
onLoaded(e, null);
})
}
else {
onLoaded('ResourceLoader.load unknown resource type ' + Object.keys(res), null);
}
});
if (resourceNames.length == 0) {
onFinish();
}
}
module.exports = ResourceLoader;