-
Notifications
You must be signed in to change notification settings - Fork 490
/
Copy pathLoader.js
3307 lines (2822 loc) · 120 KB
/
Loader.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
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* jshint wsh:true */
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
*
* The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks.
*
* Parallel loading (see {@link #enableParallel}) is supported and enabled by default.
* Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}.
*
* Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and
* [Shoebox](http://renderhjs.net/shoebox/)
*
* @class Phaser.Loader
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Loader = function (game)
{
/**
* Local reference to game.
* @property {Phaser.Game} game
* @protected
*/
this.game = game;
/**
* Local reference to the Phaser.Cache.
* @property {Phaser.Cache} cache
* @protected
*/
this.cache = game.cache;
/**
* If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state.
* @property {boolean} resetLocked
* @default
*/
this.resetLocked = false;
/**
* True if the Loader is in the process of loading the queue.
* @property {boolean} isLoading
* @default
*/
this.isLoading = false;
/**
* True if all assets in the queue have finished loading.
* @property {boolean} hasLoaded
* @default
*/
this.hasLoaded = false;
/**
* You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}.
*
* This property is an object containing: sprite, rect, direction, width and height
*
* @property {?object} preloadSprite
* @protected
*/
this.preloadSprite = null;
/**
* The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'.
* @property {boolean|string} crossOrigin
* @default
*/
this.crossOrigin = false;
/**
* If you want to append a URL before the path of any asset you can set this here.
* Useful if allowing the asset base url to be configured outside of the game code.
* The string _must_ end with a "/".
*
* @property {string} baseURL
*/
this.baseURL = '';
/**
* The value of `path`, if set, is placed before any _relative_ file path given. For example:
*
* ```javascript
* load.path = "images/sprites/";
* load.image("ball", "ball.png");
* load.image("tree", "level1/oaktree.png");
* load.image("boom", "http://server.com/explode.png");
* ```
*
* Would load the `ball` file from `images/sprites/ball.png` and the tree from
* `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL
* given as it's an absolute URL.
*
* Please note that the path is added before the filename but *after* the baseURL (if set.)
*
* The string _must_ end with a "/".
*
* @property {string} path
*/
this.path = '';
/**
* Used to map the application mime-types to to the Accept header in XHR requests.
* If you don't require these mappings, or they cause problems on your server, then
* remove them from the headers object and the XHR request will not try to use them.
*
* This object can also be used to set the `X-Requested-With` header to
* `XMLHttpRequest` (or any other value you need). To enable this do:
*
* ```javascript
* this.load.headers.requestedWith = 'XMLHttpRequest'
* ```
*
* before adding anything to the Loader. The XHR loader will then call:
*
* ```javascript
* setRequestHeader('X-Requested-With', this.headers['requestedWith'])
* ```
*
* @property {object} headers
* @default
*/
this.headers = {
requestedWith: false,
json: 'application/json',
xml: 'application/xml'
};
/**
* This event is dispatched when the loading process starts: before the first file has been requested,
* but after all the initial packs have been loaded.
*
* @property {Phaser.Signal} onLoadStart
*/
this.onLoadStart = new Phaser.Signal();
/**
* This event is dispatched when the final file in the load queue has either loaded or failed,
* before {@link #onLoadComplete} and before the loader is {@link #reset}.
*
* @property {Phaser.Signal} onBeforeLoadComplete
*/
this.onBeforeLoadComplete = new Phaser.Signal();
/**
* This event is dispatched when the final file in the load queue has either loaded or failed,
* after the loader is {@link #reset}.
*
* @property {Phaser.Signal} onLoadComplete
*/
this.onLoadComplete = new Phaser.Signal();
/**
* This event is dispatched when an asset pack has either loaded or failed to load.
*
* This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue.
*
* Params: `(pack key, success?, total packs loaded, total packs)`
*
* @property {Phaser.Signal} onPackComplete
*/
this.onPackComplete = new Phaser.Signal();
/**
* This event is dispatched immediately before a file starts loading.
* It's possible the file may fail (eg. download error, invalid format) after this event is sent.
*
* Params: `(progress, file key, file url)`
*
* @property {Phaser.Signal} onFileStart
*/
this.onFileStart = new Phaser.Signal();
/**
* This event is dispatched when a file has either loaded or failed to load.
*
* Any function bound to this will receive the following parameters:
*
* progress, file key, success?, total loaded files, total files
*
* Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load.
*
* @property {Phaser.Signal} onFileComplete
*/
this.onFileComplete = new Phaser.Signal();
/**
* This event is dispatched when a file (or pack) errors as a result of the load request.
*
* For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`.
*
* Params: `(file key, file)`
*
* @property {Phaser.Signal} onFileError
*/
this.onFileError = new Phaser.Signal();
/**
* If true (the default) then parallel downloading will be enabled.
*
* To disable all parallel downloads this must be set to false prior to any resource being loaded.
*
* @property {boolean} enableParallel
*/
this.enableParallel = true;
/**
* The number of concurrent / parallel resources to try and fetch at once.
*
* Many current browsers limit 6 requests per domain; this is slightly conservative.
*
* This should generally be left at the default, but can be set to a higher limit for specific use-cases. Just be careful when setting large values as different browsers could behave differently.
*
* @property {integer} maxParallelDownloads
*/
this.maxParallelDownloads = 4;
/**
* A counter: if more than zero, files will be automatically added as a synchronization point.
* @property {integer} _withSyncPointDepth;
*/
this._withSyncPointDepth = 0;
/**
* Contains all the information for asset files (including packs) to load.
*
* File/assets are only removed from the list after all loading completes.
*
* @property {file[]} _fileList
* @private
*/
this._fileList = [];
/**
* Inflight files (or packs) that are being fetched/processed.
*
* This means that if there are any files in the flight queue there should still be processing
* going on; it should only be empty before or after loading.
*
* The files in the queue may have additional properties added to them,
* including `requestObject` which is normally the associated XHR.
*
* @property {file[]} _flightQueue
* @private
*/
this._flightQueue = [];
/**
* The offset into the fileList past all the complete (loaded or error) entries.
*
* @property {integer} _processingHead
* @private
*/
this._processingHead = 0;
/**
* True when the first file (not pack) has loading started.
* This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded.
*
* @property {boolean} _initialPacksLoaded
* @private
*/
this._fileLoadStarted = false;
/**
* Total packs seen - adjusted when a pack is added.
* @property {integer} _totalPackCount
* @private
*/
this._totalPackCount = 0;
/**
* Total files seen - adjusted when a file is added.
* @property {integer} _totalFileCount
* @private
*/
this._totalFileCount = 0;
/**
* Total packs loaded - adjusted just prior to `onPackComplete`.
* @property {integer} _loadedPackCount
* @private
*/
this._loadedPackCount = 0;
/**
* Total files loaded - adjusted just prior to `onFileComplete`.
* @property {integer} _loadedFileCount
* @private
*/
this._loadedFileCount = 0;
};
/**
* @constant
* @type {number}
*/
Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
/**
* @constant
* @type {number}
*/
Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1;
/**
* @constant
* @type {number}
*/
Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2;
/**
* @constant
* @type {number}
*/
Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3;
/**
* @constant
* @type {number}
*/
Phaser.Loader.PHYSICS_PHASER_JSON = 4;
/**
* @constant
* @type {number}
*/
Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5;
Phaser.Loader.prototype = {
/**
* Set a Sprite to be a "preload" sprite by passing it to this method.
*
* A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time.
* This allows you to easily make loading bars for games.
*
* The sprite will automatically be made visible when calling this.
*
* @method Phaser.Loader#setPreloadSprite
* @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load.
* @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically.
*/
setPreloadSprite: function (sprite, direction)
{
direction = direction || 0;
this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null };
if (direction === 0)
{
// Horizontal rect
this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height);
}
else
{
// Vertical rect
this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1);
}
sprite.crop(this.preloadSprite.rect);
sprite.visible = true;
},
/**
* Called automatically by ScaleManager when the game resizes in RESIZE scalemode.
*
* This can be used to adjust the preloading sprite size, eg.
*
* @method Phaser.Loader#resize
* @protected
*/
resize: function ()
{
if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height)
{
this.preloadSprite.rect.height = this.preloadSprite.sprite.height;
}
},
/**
* Check whether a file/asset with a specific key is queued to be loaded.
*
* To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey}
*
* @method Phaser.Loader#checkKeyExists
* @param {string} type - The type asset you want to check.
* @param {string} key - Key of the asset you want to check.
* @return {boolean} Return true if exists, otherwise return false.
*/
checkKeyExists: function (type, key)
{
return this.getAssetIndex(type, key) > -1;
},
/**
* Get the queue-index of the file/asset with a specific key.
*
* Only assets in the download file queue will be found.
*
* @method Phaser.Loader#getAssetIndex
* @param {string} type - The type asset you want to check.
* @param {string} key - Key of the asset you want to check.
* @return {number} The index of this key in the filelist, or -1 if not found.
* The index may change and should only be used immediately following this call
*/
getAssetIndex: function (type, key)
{
var bestFound = -1;
for (var i = 0; i < this._fileList.length; i++)
{
var file = this._fileList[i];
if (file.type === type && file.key === key)
{
bestFound = i;
// An already loaded/loading file may be superceded.
if (!file.loaded && !file.loading)
{
break;
}
}
}
return bestFound;
},
/**
* Find a file/asset with a specific key.
*
* Only assets in the download file queue will be found.
*
* @method Phaser.Loader#getAsset
* @param {string} type - The type asset you want to check.
* @param {string} key - Key of the asset you want to check.
* @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned.
* The index may change and should only be used immediately following this call.
*/
getAsset: function (type, key)
{
var fileIndex = this.getAssetIndex(type, key);
if (fileIndex > -1)
{
return { index: fileIndex, file: this._fileList[fileIndex] };
}
return false;
},
/**
* Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort.
*
* This will abort any loading and clear any queued assets.
*
* Optionally you can clear any associated events.
*
* @method Phaser.Loader#reset
* @protected
* @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared.
* @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them.
*/
reset: function (hard, clearEvents)
{
if (clearEvents === undefined) { clearEvents = false; }
if (this.resetLocked)
{
return;
}
if (hard)
{
this.preloadSprite = null;
}
this.isLoading = false;
this._processingHead = 0;
this._fileList.length = 0;
this._flightQueue.length = 0;
this._fileLoadStarted = false;
this._totalFileCount = 0;
this._totalPackCount = 0;
this._loadedPackCount = 0;
this._loadedFileCount = 0;
if (clearEvents)
{
this.onLoadStart.removeAll();
this.onLoadComplete.removeAll();
this.onPackComplete.removeAll();
this.onFileStart.removeAll();
this.onFileComplete.removeAll();
this.onFileError.removeAll();
}
},
/**
* Internal function that adds a new entry to the file list. Do not call directly.
*
* @method Phaser.Loader#addToFileList
* @protected
* @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
* @param {string} key - The unique Cache ID key of this resource.
* @param {string} [url] - The URL the asset will be loaded from.
* @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults.
* @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead.
* @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension.
* @return {Phaser.Loader} This instance of the Phaser Loader.
*/
addToFileList: function (type, key, url, properties, overwrite, extension)
{
if (overwrite === undefined) { overwrite = false; }
if (key === undefined || key === '')
{
console.warn('Phaser.Loader: Invalid or no key given of type ' + type);
return this;
}
if (url === undefined || url === null)
{
if (extension)
{
url = key + extension;
}
else
{
console.warn('Phaser.Loader: No URL given for file type: ' + type + ' key: ' + key);
return this;
}
}
var file = {
type: type,
key: key,
path: this.path,
url: url,
syncPoint: this._withSyncPointDepth > 0,
data: null,
loading: false,
loaded: false,
error: false
};
if (properties)
{
for (var prop in properties)
{
file[prop] = properties[prop];
}
}
var fileIndex = this.getAssetIndex(type, key);
if (overwrite && fileIndex > -1)
{
var currentFile = this._fileList[fileIndex];
if (!currentFile.loading && !currentFile.loaded)
{
this._fileList[fileIndex] = file;
}
else
{
this._fileList.push(file);
this._totalFileCount++;
}
}
else if (fileIndex === -1)
{
this._fileList.push(file);
this._totalFileCount++;
}
return this;
},
/**
* Internal function that replaces an existing entry in the file list with a new one. Do not call directly.
*
* @method Phaser.Loader#replaceInFileList
* @protected
* @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
* @param {string} key - The unique Cache ID key of this resource.
* @param {string} url - The URL the asset will be loaded from.
* @param {object} properties - Any additional properties needed to load the file.
*/
replaceInFileList: function (type, key, url, properties)
{
return this.addToFileList(type, key, url, properties, true);
},
/**
* Add a JSON resource pack ('packfile') to the Loader.
*
* A packfile is a JSON file that contains a list of assets to the be loaded.
* Please see the example 'loader/asset pack' in the Phaser Examples repository.
*
* Packs are always put before the first non-pack file that is not loaded / loading.
*
* This means that all packs added before any loading has started are added to the front
* of the file queue, in the order added.
*
* The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
*
* The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* @method Phaser.Loader#pack
* @param {string} key - Unique asset key of this resource pack.
* @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter.
* @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO
* @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here.
* @return {Phaser.Loader} This Loader instance.
*/
pack: function (key, url, data, callbackContext)
{
if (url === undefined) { url = null; }
if (data === undefined) { data = null; }
if (callbackContext === undefined) { callbackContext = null; }
if (!url && !data)
{
console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.');
return this;
}
var pack = {
type: 'packfile',
key: key,
url: url,
path: this.path,
syncPoint: true,
data: null,
loading: false,
loaded: false,
error: false,
callbackContext: callbackContext
};
// A data object has been given
if (data)
{
if (typeof data === 'string')
{
data = JSON.parse(data);
}
pack.data = data || {};
// Already consider 'loaded'
pack.loaded = true;
}
// Add before first non-pack/no-loaded ~ last pack from start prior to loading
// (Read one past for splice-to-end)
for (var i = 0; i < this._fileList.length + 1; i++)
{
var file = this._fileList[i];
if (!file || (!file.loaded && !file.loading && file.type !== 'packfile'))
{
this._fileList.splice(i, 0, pack);
this._totalPackCount++;
break;
}
}
return this;
},
/**
* Adds an Image to the current load queue.
*
* The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
*
* Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
*
* The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
*
* Retrieve the image via `Cache.getImage(key)`
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
* If you do not desire this action then provide a URL.
*
* This method also supports passing in a texture object as the `url` argument. This allows you to load
* compressed textures into Phaser. You can also use `Loader.texture` to do this.
*
* Compressed Textures are a WebGL only feature, and require 3rd party tools to create.
* Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool.
*
* Supported texture compression formats are: PVRTC, S3TC and ETC1.
* Supported file formats are: PVR, DDS, KTX and PKM.
*
* The formats that support all 3 compression algorithms are PVR and KTX.
* PKM only supports ETC1, and DDS only S3TC for now.
*
* The texture path object looks like this:
*
* ```javascript
* load.image('factory', {
* etc1: 'assets/factory_etc1.pkm',
* s3tc: 'assets/factory_dxt1.pvr',
* pvrtc: 'assets/factory_pvrtc.pvr',
* truecolor: 'assets/factory.png'
* });
* ```
*
* The `truecolor` property points to a standard PNG file, that will be used if none of the
* compressed formats are supported by the browser / GPU.
*
* @method Phaser.Loader#image
* @param {string} key - Unique asset key of this image file.
* @param {string|object} [url] - URL of an image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". Can also be a texture data object.
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
image: function (key, url, overwrite)
{
if (typeof url === 'object')
{
return this.texture(key, url, overwrite);
}
else
{
return this.addToFileList('image', key, url, undefined, overwrite, '.png');
}
},
/**
* Generate an image from a BitmapData object and add it to the current load queue.
*
* @method Phaser.Loader#imageFromBitmapData
* @param {string} key - Unique asset key for the generated image.
* @param {Phaser.BitmapData} bitmapData
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
imageFromBitmapData: function (key, bitmapData, overwrite)
{
return this.image(key, bitmapData.canvas.toDataURL('image/png'), overwrite);
},
/**
* Generate a grid image and add it to the current load queue.
*
* @method Phaser.Loader#imageFromGrid
* @see Phaser.Create#grid
*/
imageFromGrid: function (key, width, height, cellWidth, cellHeight, color)
{
return this.imageFromBitmapData(key, this.game.create.grid(key, width, height, cellWidth, cellHeight, color, false));
},
/**
* Generate a texture image and add it to the current load queue.
*
* @method Phaser.Loader#imageFromTexture
* @see Phaser.Create#texture
*/
imageFromTexture: function (key, data, pixelWidth, pixelHeight, palette)
{
return this.imageFromBitmapData(key, this.game.create.texture(key, data, pixelWidth, pixelHeight, palette, false));
},
/**
* Adds a Compressed Texture Image to the current load queue.
*
* Compressed Textures are a WebGL only feature, and require 3rd party tools to create.
* Available tools include Texture Packer, PVRTexTool, DirectX Texture Tool and Mali Texture Compression Tool.
*
* Supported texture compression formats are: PVRTC, S3TC and ETC1.
* Supported file formats are: PVR, DDS, KTX and PKM.
*
* The formats that support all 3 compression algorithms are PVR and KTX.
* PKM only supports ETC1, and DDS only S3TC for now.
*
* The texture path object looks like this:
*
* ```javascript
* load.texture('factory', {
* etc1: 'assets/factory_etc1.pkm',
* s3tc: 'assets/factory_dxt1.pvr',
* pvrtc: 'assets/factory_pvrtc.pvr',
* truecolor: 'assets/factory.png'
* });
* ```
*
* The `truecolor` property points to a standard PNG file, that will be used if none of the
* compressed formats are supported by the browser / GPU.
*
* The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
*
* The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
*
* Retrieve the image via `Cache.getImage(key)`
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.pvr". It will always add `.pvr` as the extension.
* If you do not desire this action then provide a URL.
*
* @method Phaser.Loader#texture
* @param {string} key - Unique asset key of this image file.
* @param {object} object - The texture path data object.
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
texture: function (key, object, overwrite)
{
if (this.game.renderType === Phaser.WEBGL)
{
var compression = this.game.renderer.extensions.compression;
var exkey;
for (exkey in object)
{
if (exkey.toUpperCase() in compression)
{
return this.addToFileList('texture', key, object[exkey], undefined, overwrite, '.pvr');
}
}
}
// Check if we have a truecolor texture to fallback.
// Also catches calls to this function that are from a Canvas renderer
if (object.truecolor)
{
this.addToFileList('image', key, object.truecolor, undefined, overwrite, '.png');
}
return this;
},
/**
* Adds an array of images to the current load queue.
*
* It works by passing each element of the array to the Loader.image method.
*
* The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts.
*
* Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
*
* The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load.
*
* Retrieve the images via `Cache.getImage(key)`
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
* If you do not desire this action then provide a URL.
*
* @method Phaser.Loader#images
* @param {array} keys - An array of unique asset keys of the image files.
* @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length.
* @return {Phaser.Loader} This Loader instance.
*/
images: function (keys, urls)
{
if (Array.isArray(urls))
{
for (var i = 0; i < keys.length; i++)
{
this.image(keys[i], urls[i]);
}
}
else
{
for (var i = 0; i < keys.length; i++)
{
this.image(keys[i]);
}
}
return this;
},
/**
* Adds a Text file to the current load queue.
*
* The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
*
* The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
*
* Retrieve the file via `Cache.getText(key)`
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension.
* If you do not desire this action then provide a URL.
*
* @method Phaser.Loader#text
* @param {string} key - Unique asset key of the text file.
* @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
text: function (key, url, overwrite)
{
return this.addToFileList('text', key, url, undefined, overwrite, '.txt');
},
/**
* Adds a JSON file to the current load queue.
*
* The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
*
* The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
*
* Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load.
* If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension.
* If you do not desire this action then provide a URL.
*
* @method Phaser.Loader#json
* @param {string} key - Unique asset key of the json file.
* @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
* @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
* @return {Phaser.Loader} This Loader instance.
*/
json: function (key, url, overwrite)
{
return this.addToFileList('json', key, url, undefined, overwrite, '.json');
},
/**
* Adds a fragment shader file to the current load queue.
*
* The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
*
* The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
*
* Retrieve the file via `Cache.getShader(key)`.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur"
* and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension.
* If you do not desire this action then provide a URL.
*
* @method Phaser.Loader#shader
* @param {string} key - Unique asset key of the fragment file.