-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAssetLoader.ts
949 lines (820 loc) · 31 KB
/
AssetLoader.ts
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
// Vendor
// @ts-ignore missing type definition
import FontFaceObserver from 'fontfaceobserver-es';
// Constants
import { ASSET_LOADED, ASSETS_LOADED } from '../constants';
// Events
import { eventEmitter } from '../events/EventEmitter';
// Features
import getBrowserType from '../features/browserFeatures/getBrowserType';
import getWebGLFeatures from '../features/browserFeatures/getWebGLFeatures';
import isImageBitmapSupported from '../features/browserFeatures/isImageBitmapSupported';
import isImageDecodeSupported from '../features/browserFeatures/isImageDecodeSupported';
import isWebAssemblySupported from '../features/browserFeatures/isWebAssemblySupported';
// Utilities
import { assert, convertBlobToArrayBuffer } from '../utilities';
// Types
import { TNullable, TUndefinable, TVoidable } from '../types';
import {
ELoaderKey,
IAssetLoaderOptions,
IByDeviceTypeOptions,
IBySupportedCompressedTextureOptions,
ILoadItem,
} from './types';
/**
* Loader types and the extensions they handle
* Allows the omission of the loader key for some generic extensions used on the web
*/
const LOADER_EXTENSIONS_MAP = new Map([
[ELoaderKey.ArrayBuffer, { extensions: ['bin'] }],
[ELoaderKey.Audio, { extensions: ['mp3', 'm4a', 'ogg', 'wav', 'flac'] }],
[ELoaderKey.Audiopack, { extensions: ['audiopack'] }],
[ELoaderKey.Binpack, { extensions: ['binpack'] }],
[ELoaderKey.Font, { extensions: ['woff2', 'woff', 'ttf', 'otf', 'eot'] }],
[ELoaderKey.Image, { extensions: ['jpeg', 'jpg', 'gif', 'png', 'webp'] }],
[ELoaderKey.ImageBitmap, { extensions: ['jpeg', 'jpg', 'gif', 'png', 'webp'] }],
[ELoaderKey.ImageCompressed, { extensions: ['ktx'] }],
[ELoaderKey.JSON, { extensions: ['json'] }],
[ELoaderKey.Text, { extensions: ['txt', 'm3u8'] }],
[ELoaderKey.Video, { extensions: ['webm', 'ogg', 'mp4'] }],
[ELoaderKey.WebAssembly, { extensions: ['wasm', 'wat'] }],
[
ELoaderKey.XML,
{
defaultMimeType: 'text/xml',
extensions: ['xml', 'svg', 'html'],
mimeType: {
html: 'text/html',
svg: 'image/svg+xml',
xml: 'text/xml',
},
},
],
]);
// Safari does not fire `canplaythrough` preventing it from resolving naturally
// A workaround is to not wait for the `canplaythrough` event but rather resolve early and hope for the best
const IS_MEDIA_PRELOAD_SUPPORTED = !getBrowserType.isSafari;
/**
* Asynchronous asset preloader
*/
export class AssetLoader {
public assets: Map<string, Promise<Response>> = new Map();
private options: IAssetLoaderOptions;
private domParser = new DOMParser();
constructor(options: IAssetLoaderOptions) {
this.options = options;
}
/**
* Load conditionally based on device type
*/
public byDeviceType = (data: IByDeviceTypeOptions): TUndefinable<string> =>
data.DESKTOP && getBrowserType.isDesktop
? data.DESKTOP
: data.TABLET && getBrowserType.isTablet
? data.TABLET
: data.MOBILE;
/**
* Load conditionally based on supported compressed texture
*/
public bySupportedCompressedTexture = (
data: IBySupportedCompressedTextureOptions
): TUndefinable<string> => {
if (getWebGLFeatures) {
return data.ASTC && getWebGLFeatures.extensions.compressedTextureASTCExtension
? data.ASTC
: data.ETC && getWebGLFeatures.extensions.compressedTextureETCExtension
? data.ETC
: data.PVRTC && getWebGLFeatures.extensions.compressedTexturePVRTCExtension
? data.PVRTC
: data.S3TC && getWebGLFeatures.extensions.compressedTextureS3TCExtension
? data.S3TC
: data.FALLBACK;
} else {
return data.FALLBACK;
}
};
/**
* Load the specified manifest (array of items)
*
* @param items Items to load
*/
public loadAssets = (items: ILoadItem[]): Promise<any> => {
const loadingAssets = items
.filter(item => item)
.map(item => {
const startTime = window.performance.now();
return new Promise((resolve): void => {
const cacheHit = this.assets.get(item.src);
if (cacheHit) {
resolve({
fromCache: true,
id: item.id || item.src,
item: cacheHit,
timeToLoad: window.performance.now() - startTime,
});
}
const loaderType = item.loader || this.getLoaderByFileExtension(item.src);
let loadedItem;
switch (loaderType) {
case ELoaderKey.ArrayBuffer:
loadedItem = this.loadArrayBuffer(item);
break;
case ELoaderKey.Audio:
loadedItem = this.loadAudio(item);
break;
case ELoaderKey.Audiopack:
loadedItem = this.loadAudiopack(item);
break;
case ELoaderKey.Binpack:
loadedItem = this.loadBinpack(item);
break;
case ELoaderKey.Blob:
loadedItem = this.loadBlob(item);
break;
case ELoaderKey.Font:
loadedItem = this.loadFont(item);
break;
case ELoaderKey.Image:
loadedItem = this.loadImage(item);
break;
case ELoaderKey.ImageBitmap:
loadedItem = this.loadImageBitmap(item);
break;
case ELoaderKey.ImageCompressed:
loadedItem = this.loadImageCompressed(item);
break;
case ELoaderKey.JSON:
loadedItem = this.loadJSON(item);
break;
case ELoaderKey.Text:
loadedItem = this.loadText(item);
break;
case ELoaderKey.Video:
loadedItem = this.loadVideo(item);
break;
case ELoaderKey.WebAssembly:
loadedItem = this.loadWebAssembly(item);
break;
case ELoaderKey.XML:
loadedItem = this.loadXML(item);
break;
default:
console.warn('AssetLoader -> Missing loader, falling back to loading as ArrayBuffer');
loadedItem = this.loadArrayBuffer(item);
break;
}
loadedItem.then((asset: any) => {
this.assets.set(item.src, asset);
resolve({
fromCache: false,
id: item.id || item.src,
item: asset,
loaderType,
persistent: item.persistent,
timeToLoad: window.performance.now() - startTime,
});
});
});
});
const loadedAssets = Promise.all(loadingAssets);
let progress = 0;
loadingAssets.forEach((promise: Promise<any>) =>
promise.then(asset => {
progress++;
if (asset.persistent && (!this.options || !this.options.persistentCache)) {
console.warn(
'AssetLoader -> Persistent caching requires an instance of a PersistentCache to be passed to the AssetLoader constructor'
);
}
if (this.options && this.options.persistentCache && asset.persistent) {
switch (asset.loaderType) {
case ELoaderKey.ArrayBuffer:
this.options.persistentCache.set(asset.id, asset.item);
break;
case ELoaderKey.Blob:
// Safari iOS does not permit storing file blobs and must be converted to ArrayBuffers
// SEE: https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/indexeddb-best-practices
convertBlobToArrayBuffer(asset.item).then(buffer => {
if (this.options && this.options.persistentCache) {
this.options.persistentCache.set(asset.id, buffer);
}
});
break;
default:
console.warn(
'AssetLoader -> Persistent caching is currently only possible with ArrayBuffer and Blob loaders'
);
}
}
eventEmitter.emit(ASSET_LOADED, {
id: asset.id,
progress: `${(progress / loadingAssets.length).toFixed(2)}`,
timeToLoad: `${asset.timeToLoad.toFixed(2)}ms`,
});
})
);
return loadedAssets.then(assets => {
const assetMap = new Map();
assets.forEach((asset: any) => {
if (assetMap.get(asset.id)) {
console.warn("AssetLoader -> Detected duplicate id, please use unique id's");
}
assetMap.set(asset.id, asset.item);
});
eventEmitter.emit(ASSETS_LOADED, {
assetMap,
});
return assetMap;
});
};
/**
* Get a file extension from a full asset path
*
* @param path Path to asset
*/
private getFileExtension = (path: string): string => {
const basename = path.split(/[\\/]/).pop();
if (!basename) {
return '';
}
const seperator = basename.lastIndexOf('.');
if (seperator < 1) {
return '';
}
return basename.slice(seperator + 1);
};
/**
* Retrieve mime type from extension
*
* @param loaderKey Loader key
* @param extension extension
*/
private getMimeType = (loaderKey: ELoaderKey, extension: string): string => {
const loader: any = LOADER_EXTENSIONS_MAP.get(loaderKey);
return loader.mimeType[extension] || loader.defaultMimeType;
};
/**
* Retrieve loader key from extension (when the loader option isn't specified)
*
* @param path File path
*/
private getLoaderByFileExtension = (path: string): string => {
const fileExtension = this.getFileExtension(path);
const loader = Array.from(LOADER_EXTENSIONS_MAP).find(type =>
type[1].extensions.includes(fileExtension)
);
return loader ? loader[0] : ELoaderKey.ArrayBuffer;
};
/**
* Fetch wrapper for loading an item, to be processed by a specific loader afterwards
*
* @param item Item to fetch
*/
private fetchItem = (item: ILoadItem): Promise<Response> => fetch(item.src, item.options || {});
/**
* Load an item and parse the Response as arrayBuffer
*
* @param item Item to load
*/
private loadArrayBuffer = (item: ILoadItem): Promise<ArrayBuffer | void> =>
this.fetchItem(item)
.then(response => response.arrayBuffer())
.catch(err => {
console.warn(err.message);
});
/**
* Load an item and parse the Response as <audio> element
*
* @param item Item to load
*/
private loadAudio = (item: ILoadItem): Promise<any> =>
this.fetchItem(item)
.then(response => response.blob())
.then(
blob =>
new Promise((resolve, reject): void => {
const audio = document.createElement('audio');
if (item.loaderOptions && item.loaderOptions.crossOrigin) {
audio.crossOrigin = 'anonymous';
}
audio.preload = 'auto';
audio.autoplay = false;
if (IS_MEDIA_PRELOAD_SUPPORTED) {
audio.addEventListener('canplaythrough', function handler(): void {
audio.removeEventListener('canplaythrough', handler);
URL.revokeObjectURL(audio.src);
resolve(audio);
});
audio.addEventListener('error', function handler(): void {
audio.removeEventListener('error', handler);
URL.revokeObjectURL(audio.src);
reject(audio);
});
}
audio.src = URL.createObjectURL(blob);
if (!IS_MEDIA_PRELOAD_SUPPORTED) {
// Force the audio to load but resolve immediately as `canplaythrough` event will never be fired
audio.load();
resolve(audio);
}
})
)
.catch(err => {
console.error(err);
});
/**
* Load an item and parse the Response as Audiopack
*
* @param item Item to load
*/
private loadAudiopack = (item: ILoadItem): Promise<any> =>
this.loadArrayBuffer(item).then((data: TVoidable<ArrayBuffer>): any => {
if (data) {
let content: TNullable<string> = null;
let contentArray: TNullable<Uint8Array> = null;
let binaryChunk: TNullable<ArrayBuffer> = null;
let byteOffset: number = 0;
let chunkIndex: number = 0;
let chunkLength: number = 0;
let chunkType: TNullable<number> = null;
const headerMagic = new Uint8Array(data, 0, 4).reduce(
(magic, char) => (magic += String.fromCharCode(char)),
''
);
assert(headerMagic === 'AUDP', 'AssetLoader -> Unsupported Audiopacker header');
const chunkView = new DataView(data, 12);
while (chunkIndex < chunkView.byteLength) {
chunkLength = chunkView.getUint32(chunkIndex, true);
chunkIndex += 4;
chunkType = chunkView.getUint32(chunkIndex, true);
chunkIndex += 4;
if (chunkType === 0x4e4f534a) {
contentArray = new Uint8Array(data, 12 + chunkIndex, chunkLength);
content = contentArray.reduce((str, char) => (str += String.fromCharCode(char)), '');
} else if (chunkType === 0x004e4942) {
byteOffset = 12 + chunkIndex;
binaryChunk = data.slice(byteOffset, byteOffset + chunkLength);
}
chunkIndex += chunkLength;
}
assert(content !== null, 'AssetLoader -> JSON content chunk not found');
if (content) {
const jsonChunk = JSON.parse(content);
const binary =
binaryChunk && binaryChunk.slice(jsonChunk.bufferStart, jsonChunk.bufferEnd);
assert(binary !== null, 'AssetLoader -> Binary content chunk not found');
const blob =
binary &&
new Blob([new Uint8Array(binary)], {
type: jsonChunk.mimeType,
});
if (blob) {
return Promise.resolve(
this.loadAudio({ src: URL.createObjectURL(blob), id: item.src })
).then(audio => {
return {
audio,
data: jsonChunk.data,
mimeType: jsonChunk.mimeType,
};
});
}
}
}
});
/**
* Load an item and parse the Response as Binpack
*
* @param item Item to load
*/
private loadBinpack = (item: ILoadItem): Promise<any> =>
this.loadArrayBuffer(item).then((data: TVoidable<ArrayBuffer>): any => {
if (data) {
let content: TNullable<string> = null;
let contentArray: TNullable<Uint8Array> = null;
let binaryChunk: TNullable<ArrayBuffer> = null;
let byteOffset: number = 0;
let chunkIndex: number = 0;
let chunkLength: number = 0;
let chunkType: TNullable<number> = null;
const headerMagic = new Uint8Array(data, 0, 4).reduce(
(magic, char) => (magic += String.fromCharCode(char)),
''
);
assert(headerMagic === 'BINP', 'AssetLoader -> Unsupported Binpacker header');
const chunkView = new DataView(data, 12);
while (chunkIndex < chunkView.byteLength) {
chunkLength = chunkView.getUint32(chunkIndex, true);
chunkIndex += 4;
chunkType = chunkView.getUint32(chunkIndex, true);
chunkIndex += 4;
if (chunkType === 0x4e4f534a) {
contentArray = new Uint8Array(data, 12 + chunkIndex, chunkLength);
content = contentArray.reduce((str, char) => (str += String.fromCharCode(char)), '');
} else if (chunkType === 0x004e4942) {
byteOffset = 12 + chunkIndex;
binaryChunk = data.slice(byteOffset, byteOffset + chunkLength);
}
chunkIndex += chunkLength;
}
assert(content !== null, 'AssetLoader -> JSON content chunk not found');
if (content && binaryChunk) {
const jsonChunk = JSON.parse(content);
return Promise.all(
jsonChunk.map(
(entry: {
name: string;
mimeType: string;
bufferStart: number;
bufferEnd: number;
}) => {
const { name, mimeType } = entry;
const binary = binaryChunk && binaryChunk.slice(entry.bufferStart, entry.bufferEnd);
assert(binary !== null, 'AssetLoader -> Binary content chunk not found');
const blob =
binary &&
new Blob([new Uint8Array(binary)], {
type: mimeType,
});
const loaderType = this.getLoaderByFileExtension(name);
const url = URL.createObjectURL(blob);
switch (loaderType) {
case ELoaderKey.Image:
return this.loadImage({ src: url, id: name });
case ELoaderKey.JSON:
return this.loadJSON({ src: url, id: name });
case ELoaderKey.Text:
return this.loadText({ src: url, id: name });
case ELoaderKey.XML:
return this.loadXML({ src: url, id: name });
default:
throw new Error(
'AssetLoader -> Binpack currently only supports images, JSON, plain text and XML (SVG)'
);
}
}
)
).then((assets: any[]) => {
return Object.assign(
{},
...jsonChunk.map((entry: any, index: number) => {
return { [entry.name]: assets[index] };
})
);
});
}
}
});
/**
* Load an item and parse the Response as blob
*
* @param item Item to load
*/
private loadBlob = (item: ILoadItem): Promise<Blob | void> =>
this.fetchItem(item)
.then(response => response.blob())
.catch(err => {
console.error(err);
});
/**
* Load an item and parse the Response as a FontFace
*
* @param item Item to load
*/
private loadFont = (item: ILoadItem): Promise<any> =>
new FontFaceObserver(item.id, item.options || {}).load();
/**
* Load an item and parse the Response as <image> element
*
* @param item Item to load
*/
private loadImage = (item: ILoadItem): Promise<HTMLImageElement> =>
new Promise((resolve, reject): void => {
const image = new Image();
if (item.loaderOptions && item.loaderOptions.crossOrigin) {
image.crossOrigin = 'anonymous';
}
// Check if we can decode non-blocking by loading the image asynchronously using image.decode().then(() => ...)
// SEE: https://www.chromestatus.com/feature/5637156160667648 (Chrome | Safari | Safari iOS)
if (isImageDecodeSupported) {
image.src = item.src;
image
.decode()
.then(() => {
resolve(image);
})
.catch(err => {
reject(err);
});
} else {
// Fallback solution
// Decode as synchronous blocking on the main thread
// This is the least favorable method and should preferably only be used in old browsers (Edge | Firefox)
image.onload = (): void => {
resolve(image);
};
image.onerror = (err): void => {
reject(err);
};
image.src = item.src;
}
});
/**
* Load an item and parse the Response as ImageBitmap element
*
* NOTE: Please be cautious when using loadImageBitmap as browser support is still spotty and unreliable
*
* SEE:
* - https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-createimagebitmap
* - https://caniuse.com/createimagebitmap
* - https://bugzilla.mozilla.org/show_bug.cgi?id=1335594
* - https://bugzilla.mozilla.org/show_bug.cgi?id=1363861
*
* @param item Item to load
*/
private loadImageBitmap = (item: ILoadItem): Promise<ImageBitmap | HTMLImageElement> => {
if (isImageBitmapSupported) {
return this.loadBlob(item).then(data => {
if (data) {
if (item.loaderOptions) {
const { sx, sy, sw, sh, options } = item.loaderOptions;
if (sx !== undefined && sy !== undefined && sw !== undefined && sh !== undefined) {
if (options !== undefined) {
// NOTE: Firefox does not yet support passing options (at least as second parameter) to createImageBitmap and throws
// SEE: https://bugzilla.mozilla.org/show_bug.cgi?id=1335594
// SEE: https://www.khronos.org/registry/webgl/specs/latest/1.0/#PIXEL_STORAGE_PARAMETERS
// @ts-ignore createImageBitmap expects 1 or 5 parameters but now optionally supports 6
return createImageBitmap(data, sx, sy, sw, sh, options);
} else {
return createImageBitmap(data, sx, sy, sw, sh);
}
} else if (options !== undefined) {
// NOTE: Firefox does not yet support passing options (at least as second parameter) to createImageBitmap and throws
// SEE: https://bugzilla.mozilla.org/show_bug.cgi?id=1335594
// SEE: https://www.khronos.org/registry/webgl/specs/latest/1.0/#PIXEL_STORAGE_PARAMETERS
// @ts-ignore createImageBitmap expects 1 or 5 parameters but now optionally supports 2
return createImageBitmap(data, options);
} else {
return createImageBitmap(data);
}
} else {
return createImageBitmap(data);
}
} else {
// In case something went wrong with loading the blob or corrupted data
// Fallback to default image loader
console.warn(
'AssetLoader -> Received no or corrupt data, falling back to default image loader'
);
return this.loadImage(item);
}
});
} else {
// Fallback to default image loader
return this.loadImage(item);
}
};
/**
* Load an item and parse the Response as compressed image (KTX container)
*
* @param item Item to load
*/
private loadImageCompressed = (
item: ILoadItem
): Promise<
TUndefinable<{
baseInternalFormat: GLenum;
height: number;
internalFormat: GLenum;
isCompressed: boolean;
isCubemap: boolean;
mipmapCount: number;
mipmaps: any;
width: number;
}>
> =>
this.loadArrayBuffer(item).then(data => {
if (data) {
// Switch endianness of value
const switchEndianness = (value: number): number =>
((value & 0xff) << 24) |
((value & 0xff00) << 8) |
((value >> 8) & 0xff00) |
((value >> 24) & 0xff);
// Test that it is a ktx formatted file, based on the first 12 bytes:
// '´', 'K', 'T', 'X', ' ', '1', '1', 'ª', '\r', '\n', '\x1A', '\n'
// 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
const identifier = new Uint8Array(data, 0, 12);
assert(
identifier[0] === 0xab &&
identifier[1] === 0x4b &&
identifier[2] === 0x54 &&
identifier[3] === 0x58 &&
identifier[4] === 0x20 &&
identifier[5] === 0x31 &&
identifier[6] === 0x31 &&
identifier[7] === 0xbb &&
identifier[8] === 0x0d &&
identifier[9] === 0x0a &&
identifier[10] === 0x1a &&
identifier[11] === 0x0a,
'AssetLoader -> Texture missing KTX identifier, currently only supporting KTX containers'
);
// Load the rest of the header in 32 bit int
const header = new Int32Array(data, 12, 13);
// Determine of the remaining header values are recorded
// in the opposite endianness and require conversion
const isBigEndian = header[0] === 0x01020304;
// Must be 0 for compressed textures
const glType = isBigEndian ? switchEndianness(header[1]) : header[1];
// Must be 1 for compressed textures
// const glTypeSize = isBigEndian ? switchEndianness(header[2]) : header[2];
// Must be 0 for compressed textures
// const glFormat = isBigEndian ? switchEndianness(header[3]) : header[3];
// The value to be passed to gl.compressedTexImage2D(,,x,,,,)
const glInternalFormat = isBigEndian ? switchEndianness(header[4]) : header[4];
// Specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
const glBaseInternalFormat = isBigEndian ? switchEndianness(header[5]) : header[5];
// Level 0 value to be passed to gl.compressedTexImage2D(,,,x,,,)
const pixelWidth = isBigEndian ? switchEndianness(header[6]) : header[6];
// Level 0 value to be passed to gl.compressedTexImage2D(,,,,x,,)
const pixelHeight = isBigEndian ? switchEndianness(header[7]) : header[7];
// Level 0 value to be passed to gl.compressedTexImage3D(,,,,,x,,)
const pixelDepth = isBigEndian ? switchEndianness(header[8]) : header[8];
// Used for texture arrays
const numberOfArrayElements = isBigEndian ? switchEndianness(header[9]) : header[9];
// Used for cubemap textures, should either be 1 or 6
const numberOfFaces = isBigEndian ? switchEndianness(header[10]) : header[10];
// Number of levels; disregard possibility of 0 for compressed textures
let numberOfMipmapLevels = isBigEndian ? switchEndianness(header[11]) : header[11];
// The amount of space after the header for meta-data
const bytesOfKeyValueData = isBigEndian ? switchEndianness(header[12]) : header[12];
// Value of zero is an indication to generate mipmaps at runtime.
// Not usually allowed for compressed, so disregard.
numberOfMipmapLevels = Math.max(1, numberOfMipmapLevels);
// Check for 2D texture
assert(
pixelHeight !== 0 && pixelDepth === 0,
'AssetLoader -> Only 2D textures currently supported'
);
// Check for texture arrays, currently not supported
assert(
numberOfArrayElements === 0,
'AssetLoader -> Texture arrays not currently supported'
);
const mipmaps = [];
// Identifier + header elements (not including key value meta-data pairs)
let dataOffset = 64 + bytesOfKeyValueData;
let width = pixelWidth;
let height = pixelHeight;
const mipmapCount = numberOfMipmapLevels || 1;
for (let level = 0; level < mipmapCount; level++) {
// Size per face, since not supporting array cubemaps
const imageSize = new Int32Array(data, dataOffset, 1)[0];
// Image data starts from next multiple of 4 offset
// Each face refers to same imagesize field above
dataOffset += 4;
for (let face = 0; face < numberOfFaces; face++) {
const byteArray = new Uint8Array(data, dataOffset, imageSize);
mipmaps.push({
data: byteArray,
height,
width,
});
// Add size of the image for the next face & mipmap
dataOffset += imageSize;
// Add padding for odd sized image
dataOffset += 3 - ((imageSize + 3) % 4);
}
width = Math.max(1.0, width * 0.5);
height = Math.max(1.0, height * 0.5);
}
return {
baseInternalFormat: glBaseInternalFormat,
height: pixelHeight,
internalFormat: glInternalFormat,
isCompressed: !glType,
isCubemap: numberOfFaces === 6,
mipmapCount: numberOfMipmapLevels,
mipmaps,
width: pixelWidth,
};
}
});
/**
* Load an item and parse the Response as JSON
*
* @param item Item to load
*/
private loadJSON = (item: ILoadItem): Promise<JSON> =>
this.fetchItem(item)
.then(response => response.json())
.catch(err => {
console.error(err);
});
/**
* Load an item and parse the Response as plain text
*
* @param item Item to load
*/
private loadText = (item: ILoadItem): Promise<string | void> =>
this.fetchItem(item)
.then(response => response.text())
.catch(err => {
console.error(err);
});
/**
* Load an item and parse the Response as <video> element
*
* @param item Item to load
*/
private loadVideo = (item: ILoadItem): Promise<any> =>
this.fetchItem(item)
.then(response => response.blob())
.then(
blob =>
new Promise((resolve, reject): void => {
const video = document.createElement('video');
if (item.loaderOptions && item.loaderOptions.crossOrigin) {
video.crossOrigin = 'anonymous';
}
video.preload = 'auto';
video.autoplay = false;
// @ts-ignore playsInline is not recognized as a valid type but it is valid syntax
video.playsInline = true;
if (IS_MEDIA_PRELOAD_SUPPORTED) {
video.addEventListener('canplaythrough', function handler(): void {
video.removeEventListener('canplaythrough', handler);
URL.revokeObjectURL(video.src);
resolve(video);
});
video.addEventListener('error', function handler(): void {
video.removeEventListener('error', handler);
URL.revokeObjectURL(video.src);
reject(video);
});
}
video.src = URL.createObjectURL(blob);
if (!IS_MEDIA_PRELOAD_SUPPORTED) {
// Force the audio to load but resolve immediately as `canplaythrough` event will never be fired
video.load();
resolve(video);
}
})
)
.catch(err => {
console.error(err);
});
/**
* Load an item and parse the Response as ArrayBuffer (ready to instantiate)
*
* @param item Item to load
*/
private loadWebAssembly = (item: ILoadItem): Promise<TVoidable<WebAssembly.Instance>> => {
if (isWebAssemblySupported) {
if ((window as any).WebAssembly.instantiateStreaming) {
return (window as any).WebAssembly.instantiateStreaming(
this.fetchItem(item),
item.loaderOptions.importObject
);
} else {
return this.fetchItem(item)
.then(response => response.arrayBuffer())
.then(data =>
(window as any).WebAssembly.instantiate(data, item.loaderOptions.importObject)
)
.catch(err => {
console.error(err);
});
}
} else {
console.warn('AssetLoader -> WebAssembly is not supported');
return Promise.resolve();
}
};
/**
* Load an item and parse the Response as XML
*
* @param item Item to load
*/
private loadXML = (item: ILoadItem): Promise<any> => {
if (!item.mimeType) {
const extension: string = this.getFileExtension(item.src);
item = {
...item,
mimeType: this.getMimeType(ELoaderKey.XML, extension) as SupportedType,
};
}
return this.fetchItem(item)
.then(response => response.text())
.then(data => {
if (item.mimeType) {
return this.domParser.parseFromString(data, item.mimeType);
}
})
.catch(err => {
console.error(err);
});
};
}