forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.js
More file actions
1879 lines (1617 loc) · 72.9 KB
/
application.js
File metadata and controls
1879 lines (1617 loc) · 72.9 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
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
Object.assign(pc, function () {
/**
* @class
* @name pc.Application
* @augments pc.EventHandler
* @classdesc A pc.Application represents and manages your PlayCanvas application.
* If you are developing using the PlayCanvas Editor, the pc.Application is created
* for you. You can access your pc.Application instance in your scripts. Below is a
* skeleton script which shows how you can access the application 'app' property inside
* the initialize and update functions:
*
* ```javascript
* // Editor example: accessing the pc.Application from a script
* var MyScript = pc.createScript('myScript');
*
* MyScript.prototype.initialize = function() {
* // Every script instance has a property 'this.app' accessible in the initialize...
* var app = this.app;
* };
*
* MyScript.prototype.update = function(dt) {
* // ...and update functions.
* var app = this.app;
* };
* ```
*
* If you are using the Engine without the Editor, you have to create the application
* instance manually.
* @description Create a new Application.
* @param {Element} canvas - The canvas element.
* @param {object} options
* @param {pc.ElementInput} [options.elementInput] - Input handler for {@link pc.ElementComponent}s.
* @param {pc.Keyboard} [options.keyboard] - Keyboard handler for input.
* @param {pc.Mouse} [options.mouse] - Mouse handler for input.
* @param {pc.TouchDevice} [options.touch] - TouchDevice handler for input.
* @param {pc.GamePads} [options.gamepads] - Gamepad handler for input.
* @param {string} [options.scriptPrefix] - Prefix to apply to script urls before loading.
* @param {string} [options.assetPrefix] - Prefix to apply to asset urls before loading.
* @param {object} [options.graphicsDeviceOptions] - Options object that is passed into the {@link pc.GraphicsDevice} constructor.
* @param {string[]} [options.scriptsOrder] - Scripts in order of loading first.
* @example
* // Engine-only example: create the application manually
* var app = new pc.Application(canvas, options);
*
* // Start the application's main loop
* app.start();
*/
// PROPERTIES
/**
* @name pc.Application#scene
* @type {pc.Scene}
* @description The scene managed by the application.
* @example
* // Set the tone mapping property of the application's scene
* this.app.scene.toneMapping = pc.TONEMAP_FILMIC;
*/
/**
* @name pc.Application#timeScale
* @type {number}
* @description Scales the global time delta. Defaults to 1.
* @example
* // Set the app to run at half speed
* this.app.timeScale = 0.5;
*/
/**
* @name pc.Application#maxDeltaTime
* @type {number}
* @description Clamps per-frame delta time to an upper bound. Useful since returning from a tab
* deactivation can generate huge values for dt, which can adversely affect game state. Defaults
* to 0.1 (seconds).
* @example
* // Don't clamp inter-frame times of 200ms or less
* this.app.maxDeltaTime = 0.2;
*/
/**
* @name pc.Application#assets
* @type {pc.AssetRegistry}
* @description The asset registry managed by the application.
* @example
* // Search the asset registry for all assets with the tag 'vehicle'
* var vehicleAssets = this.app.assets.findByTag('vehicle');
*/
/**
* @name pc.Application#graphicsDevice
* @type {pc.GraphicsDevice}
* @description The graphics device used by the application.
*/
/**
* @name pc.Application#systems
* @type {pc.ComponentSystemRegistry}
* @description The application's component system registry. The pc.Application
* constructor adds the following component systems to its component system registry:
*
* * animation ({@link pc.AnimationComponentSystem})
* * audiolistener ({@link pc.AudioListenerComponentSystem})
* * button ({@link pc.ButtonComponentSystem})
* * camera ({@link pc.CameraComponentSystem})
* * collision ({@link pc.CollisionComponentSystem})
* * element ({@link pc.ElementComponentSystem})
* * layoutchild ({@link pc.LayoutChildComponentSystem})
* * layoutgroup ({@link pc.LayoutGroupComponentSystem})
* * light ({@link pc.LightComponentSystem})
* * model ({@link pc.ModelComponentSystem})
* * particlesystem ({@link pc.ParticleSystemComponentSystem})
* * rigidbody ({@link pc.RigidBodyComponentSystem})
* * screen ({@link pc.ScreenComponentSystem})
* * script ({@link pc.ScriptComponentSystem})
* * scrollbar ({@link pc.ScrollbarComponentSystem})
* * scrollview ({@link pc.ScrollViewComponentSystem})
* * sound ({@link pc.SoundComponentSystem})
* * sprite ({@link pc.SpriteComponentSystem})
* @example
* // Set global gravity to zero
* this.app.systems.rigidbody.gravity.set(0, 0, 0);
* @example
* // Set the global sound volume to 50%
* this.app.systems.sound.volume = 0.5;
*/
/**
* @name pc.Application#xr
* @type {pc.XrManager}
* @description The XR Manager that provides ability to start VR/AR sessions.
* @example
* // check if VR is available
* if (app.xr.isAvailable(pc.XR_TYPE_IMMERSIVE_VR)) {
* // VR is available
* }
*/
/**
* @name pc.Application#loader
* @type {pc.ResourceLoader}
* @description The resource loader.
*/
/**
* @name pc.Application#root
* @type {pc.Entity}
* @description The root entity of the application.
* @example
* // Return the first entity called 'Camera' in a depth-first search of the scene hierarchy
* var camera = this.app.root.findByName('Camera');
*/
/**
* @name pc.Application#keyboard
* @type {pc.Keyboard}
* @description The keyboard device.
*/
/**
* @name pc.Application#mouse
* @type {pc.Mouse}
* @description The mouse device.
*/
/**
* @name pc.Application#touch
* @type {pc.TouchDevice}
* @description Used to get touch events input.
*/
/**
* @name pc.Application#gamepads
* @type {pc.GamePads}
* @description Used to access GamePad input.
*/
/**
* @name pc.Application#elementInput
* @type {pc.ElementInput}
* @description Used to handle input for {@link pc.ElementComponent}s.
*/
/**
* @name pc.Application#scripts
* @type {pc.ScriptRegistry}
* @description The application's script registry.
*/
/**
* @name pc.Application#batcher
* @type {pc.BatchManager}
* @description The application's batch manager. The batch manager is used to
* merge mesh instances in the scene, which reduces the overall number of draw
* calls, thereby boosting performance.
*/
/**
* @name pc.Application#autoRender
* @type {boolean}
* @description When true, the application's render function is called every frame.
* Setting autoRender to false is useful to applications where the rendered image
* may often be unchanged over time. This can heavily reduce the application's
* load on the CPU and GPU. Defaults to true.
* @example
* // Disable rendering every frame and only render on a keydown event
* this.app.autoRender = false;
* this.app.keyboard.on('keydown', function (event) {
* this.app.renderNextFrame = true;
* }, this);
*/
/**
* @name pc.Application#renderNextFrame
* @type {boolean}
* @description Set to true to render the scene on the next iteration of the main loop.
* This only has an effect if {@link pc.Application#autoRender} is set to false. The
* value of renderNextFrame is set back to false again as soon as the scene has been
* rendered.
* @example
* // Render the scene only while space key is pressed
* if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
* this.app.renderNextFrame = true;
* }
*/
/**
* @name pc.Application#i18n
* @type {pc.I18n}
* @description Handles localization.
*/
var Application = function (canvas, options) {
pc.EventHandler.call(this);
options = options || {};
// Open the log
pc.log.open();
// Store application instance
Application._applications[canvas.id] = this;
Application._currentApplication = this;
/**
* @private
* @static
* @name pc.app
* @type {pc.Application|undefined}
* @description Gets the current application, if any.
*/
pc.app = this;
this._time = 0;
this.timeScale = 1;
this.maxDeltaTime = 0.1; // Maximum delta is 0.1s or 10 fps.
this.frame = 0; // the total number of frames the application has updated since start() was called
this.autoRender = true;
this.renderNextFrame = false;
// enable if you want entity type script attributes
// to not be re-mapped when an entity is cloned
this.useLegacyScriptAttributeCloning = pc.script.legacy;
this._librariesLoaded = false;
this._fillMode = pc.FILLMODE_KEEP_ASPECT;
this._resolutionMode = pc.RESOLUTION_FIXED;
// for compatibility
this.context = this;
options.graphicsDeviceOptions.xrCompatible = true;
this.graphicsDevice = new pc.GraphicsDevice(canvas, options.graphicsDeviceOptions);
this.stats = new pc.ApplicationStats(this.graphicsDevice);
this._audioManager = new pc.SoundManager(options);
this.loader = new pc.ResourceLoader(this);
// stores all entities that have been created
// for this app by guid
this._entityIndex = {};
this.scene = new pc.Scene();
this.root = new pc.Entity(this);
this.root._enabledInHierarchy = true;
this._enableList = [];
this._enableList.size = 0;
this.assets = new pc.AssetRegistry(this.loader);
if (options.assetPrefix) this.assets.prefix = options.assetPrefix;
this.bundles = new pc.BundleRegistry(this.assets);
// set this to false if you want to run without using bundles
// We set it to true only if TextDecoder is available because we currently
// rely on it for untarring.
this.enableBundles = (typeof TextDecoder !== 'undefined');
this.scriptsOrder = options.scriptsOrder || [];
this.scripts = new pc.ScriptRegistry(this);
this.i18n = new pc.I18n(this);
this._sceneRegistry = new pc.SceneRegistry(this);
var self = this;
this.defaultLayerWorld = new pc.Layer({
name: "World",
id: pc.LAYERID_WORLD
});
if (this.graphicsDevice.webgl2) {
// WebGL 2 depth layer just copies existing depth
this.defaultLayerDepth = new pc.Layer({
enabled: false,
name: "Depth",
id: pc.LAYERID_DEPTH,
onEnable: function () {
if (this.renderTarget) return;
var depthBuffer = new pc.Texture(self.graphicsDevice, {
format: pc.PIXELFORMAT_DEPTHSTENCIL,
width: self.graphicsDevice.width,
height: self.graphicsDevice.height
});
depthBuffer.name = 'rt-depth2';
depthBuffer.minFilter = pc.FILTER_NEAREST;
depthBuffer.magFilter = pc.FILTER_NEAREST;
depthBuffer.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
depthBuffer.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
this.renderTarget = new pc.RenderTarget({
colorBuffer: null,
depthBuffer: depthBuffer,
autoResolve: false
});
self.graphicsDevice.scope.resolve("uDepthMap").setValue(depthBuffer);
},
onDisable: function () {
if (!this.renderTarget) return;
this.renderTarget._depthBuffer.destroy();
this.renderTarget.destroy();
this.renderTarget = null;
},
onPreRenderOpaque: function (cameraPass) { // resize depth map if needed
var gl = self.graphicsDevice.gl;
this.srcFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING);
if (!this.renderTarget || (this.renderTarget.width !== self.graphicsDevice.width || this.renderTarget.height !== self.graphicsDevice.height)) {
this.onDisable();
this.onEnable();
}
// disable clearing
this.oldClear = this.cameras[cameraPass].camera._clearOptions;
this.cameras[cameraPass].camera._clearOptions = this.depthClearOptions;
},
onPostRenderOpaque: function (cameraPass) { // copy depth
if (!this.renderTarget) return;
this.cameras[cameraPass].camera._clearOptions = this.oldClear;
var gl = self.graphicsDevice.gl;
self.graphicsDevice.setRenderTarget(this.renderTarget);
self.graphicsDevice.updateBegin();
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, this.srcFbo);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, this.renderTarget._glFrameBuffer);
gl.blitFramebuffer( 0, 0, this.renderTarget.width, this.renderTarget.height,
0, 0, this.renderTarget.width, this.renderTarget.height,
gl.DEPTH_BUFFER_BIT,
gl.NEAREST);
}
});
this.defaultLayerDepth.depthClearOptions = {
flags: 0
};
} else {
// WebGL 1 depth layer just renders same objects as in World, but with RGBA-encoded depth shader
this.defaultLayerDepth = new pc.Layer({
enabled: false,
name: "Depth",
id: pc.LAYERID_DEPTH,
shaderPass: pc.SHADER_DEPTH,
onEnable: function () {
if (this.renderTarget) return;
var colorBuffer = new pc.Texture(self.graphicsDevice, {
format: pc.PIXELFORMAT_R8_G8_B8_A8,
width: self.graphicsDevice.width,
height: self.graphicsDevice.height
});
colorBuffer.name = 'rt-depth1';
colorBuffer.minFilter = pc.FILTER_NEAREST;
colorBuffer.magFilter = pc.FILTER_NEAREST;
colorBuffer.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
colorBuffer.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
this.renderTarget = new pc.RenderTarget(self.graphicsDevice, colorBuffer, {
depth: true,
stencil: self.graphicsDevice.supportsStencil
});
self.graphicsDevice.scope.resolve("uDepthMap").setValue(colorBuffer);
},
onDisable: function () {
if (!this.renderTarget) return;
this.renderTarget._colorBuffer.destroy();
this.renderTarget.destroy();
this.renderTarget = null;
},
onPostCull: function (cameraPass) {
// Collect all rendered mesh instances with the same render target as World has, depthWrite == true and prior to this layer to replicate blitFramebuffer on WebGL2
var visibleObjects = this.instances.visibleOpaque[cameraPass];
var visibleList = visibleObjects.list;
var visibleLength = 0;
var layers = self.scene.layers.layerList;
var subLayerEnabled = self.scene.layers.subLayerEnabled;
var isTransparent = self.scene.layers.subLayerList;
var rt = self.defaultLayerWorld.renderTarget;
var cam = this.cameras[cameraPass];
var layer;
var j;
var layerVisibleList, layerCamId, layerVisibleListLength, drawCall, transparent;
for (var i = 0; i < layers.length; i++) {
layer = layers[i];
if (layer === this) break;
if (layer.renderTarget !== rt || !layer.enabled || !subLayerEnabled[i]) continue;
layerCamId = layer.cameras.indexOf(cam);
if (layerCamId < 0) continue;
transparent = isTransparent[i];
layerVisibleList = transparent ? layer.instances.visibleTransparent[layerCamId] : layer.instances.visibleOpaque[layerCamId];
layerVisibleListLength = layerVisibleList.length;
layerVisibleList = layerVisibleList.list;
for (j = 0; j < layerVisibleListLength; j++) {
drawCall = layerVisibleList[j];
if (drawCall.material && drawCall.material.depthWrite && !drawCall._noDepthDrawGl1) {
visibleList[visibleLength] = drawCall;
visibleLength++;
}
}
}
visibleObjects.length = visibleLength;
},
onPreRenderOpaque: function (cameraPass) { // resize depth map if needed
if (!this.renderTarget || (this.renderTarget.width !== self.graphicsDevice.width || this.renderTarget.height !== self.graphicsDevice.height)) {
this.onDisable();
this.onEnable();
}
this.oldClear = this.cameras[cameraPass].camera._clearOptions;
this.cameras[cameraPass].camera._clearOptions = this.rgbaDepthClearOptions;
},
onDrawCall: function () {
self.graphicsDevice.setColorWrite(true, true, true, true);
},
onPostRenderOpaque: function (cameraPass) {
if (!this.renderTarget) return;
this.cameras[cameraPass].camera._clearOptions = this.oldClear;
}
});
this.defaultLayerDepth.rgbaDepthClearOptions = {
color: [254.0 / 255, 254.0 / 255, 254.0 / 255, 254.0 / 255],
depth: 1.0,
flags: pc.CLEARFLAG_COLOR | pc.CLEARFLAG_DEPTH
};
}
this.defaultLayerSkybox = new pc.Layer({
enabled: false,
name: "Skybox",
id: pc.LAYERID_SKYBOX,
opaqueSortMode: pc.SORTMODE_NONE
});
this.defaultLayerUi = new pc.Layer({
enabled: true,
name: "UI",
id: pc.LAYERID_UI,
transparentSortMode: pc.SORTMODE_MANUAL,
passThrough: false
});
this.defaultLayerImmediate = new pc.Layer({
enabled: true,
name: "Immediate",
id: pc.LAYERID_IMMEDIATE,
opaqueSortMode: pc.SORTMODE_NONE,
passThrough: true
});
this.defaultLayerComposition = new pc.LayerComposition();
this.defaultLayerComposition.pushOpaque(this.defaultLayerWorld);
this.defaultLayerComposition.pushOpaque(this.defaultLayerDepth);
this.defaultLayerComposition.pushOpaque(this.defaultLayerSkybox);
this.defaultLayerComposition.pushTransparent(this.defaultLayerWorld);
this.defaultLayerComposition.pushOpaque(this.defaultLayerImmediate);
this.defaultLayerComposition.pushTransparent(this.defaultLayerImmediate);
this.defaultLayerComposition.pushTransparent(this.defaultLayerUi);
this.scene.layers = this.defaultLayerComposition;
this._immediateLayer = this.defaultLayerImmediate;
// Default layers patch
this.scene.on('set:layers', function (oldComp, newComp) {
var list = newComp.layerList;
var layer;
for (var i = 0; i < list.length; i++) {
layer = list[i];
switch (layer.id) {
case pc.LAYERID_DEPTH:
layer.onEnable = self.defaultLayerDepth.onEnable;
layer.onDisable = self.defaultLayerDepth.onDisable;
layer.onPreRenderOpaque = self.defaultLayerDepth.onPreRenderOpaque;
layer.onPostRenderOpaque = self.defaultLayerDepth.onPostRenderOpaque;
layer.depthClearOptions = self.defaultLayerDepth.depthClearOptions;
layer.rgbaDepthClearOptions = self.defaultLayerDepth.rgbaDepthClearOptions;
layer.shaderPass = self.defaultLayerDepth.shaderPass;
layer.onPostCull = self.defaultLayerDepth.onPostCull;
layer.onDrawCall = self.defaultLayerDepth.onDrawCall;
break;
case pc.LAYERID_UI:
layer.passThrough = self.defaultLayerUi.passThrough;
break;
case pc.LAYERID_IMMEDIATE:
layer.passThrough = self.defaultLayerImmediate.passThrough;
break;
}
}
});
this.renderer = new pc.ForwardRenderer(this.graphicsDevice);
this.renderer.scene = this.scene;
this.lightmapper = new pc.Lightmapper(this.graphicsDevice, this.root, this.scene, this.renderer, this.assets);
this.once('prerender', this._firstBake, this);
this.batcher = new pc.BatchManager(this.graphicsDevice, this.root, this.scene);
this.once('prerender', this._firstBatch, this);
this.keyboard = options.keyboard || null;
this.mouse = options.mouse || null;
this.touch = options.touch || null;
this.gamepads = options.gamepads || null;
this.elementInput = options.elementInput || null;
if (this.elementInput)
this.elementInput.app = this;
this.xr = new pc.XrManager(this);
this._inTools = false;
this._skyboxLast = 0;
this._scriptPrefix = options.scriptPrefix || '';
if (this.enableBundles) {
this.loader.addHandler("bundle", new pc.BundleHandler(this.assets));
}
this.loader.addHandler("animation", new pc.AnimationHandler());
this.loader.addHandler("model", new pc.ModelHandler(this.graphicsDevice, this.scene.defaultMaterial));
this.loader.addHandler("material", new pc.MaterialHandler(this));
this.loader.addHandler("texture", new pc.TextureHandler(this.graphicsDevice, this.assets, this.loader));
this.loader.addHandler("text", new pc.TextHandler());
this.loader.addHandler("json", new pc.JsonHandler());
this.loader.addHandler("audio", new pc.AudioHandler(this._audioManager));
this.loader.addHandler("script", new pc.ScriptHandler(this));
this.loader.addHandler("scene", new pc.SceneHandler(this));
this.loader.addHandler("cubemap", new pc.CubemapHandler(this.graphicsDevice, this.assets, this.loader));
this.loader.addHandler("html", new pc.HtmlHandler());
this.loader.addHandler("css", new pc.CssHandler());
this.loader.addHandler("shader", new pc.ShaderHandler());
this.loader.addHandler("hierarchy", new pc.HierarchyHandler(this));
this.loader.addHandler("scenesettings", new pc.SceneSettingsHandler(this));
this.loader.addHandler("folder", new pc.FolderHandler());
this.loader.addHandler("font", new pc.FontHandler(this.loader));
this.loader.addHandler("binary", new pc.BinaryHandler());
this.loader.addHandler("textureatlas", new pc.TextureAtlasHandler(this.loader));
this.loader.addHandler("sprite", new pc.SpriteHandler(this.assets, this.graphicsDevice));
this.loader.addHandler("template", new pc.TemplateHandler(this));
this.systems = new pc.ComponentSystemRegistry();
this.systems.add(new pc.RigidBodyComponentSystem(this));
this.systems.add(new pc.CollisionComponentSystem(this));
this.systems.add(new pc.AnimationComponentSystem(this));
this.systems.add(new pc.ModelComponentSystem(this));
this.systems.add(new pc.CameraComponentSystem(this));
this.systems.add(new pc.LightComponentSystem(this));
if (pc.script.legacy) {
this.systems.add(new pc.ScriptLegacyComponentSystem(this));
} else {
this.systems.add(new pc.ScriptComponentSystem(this));
}
this.systems.add(new pc.AudioSourceComponentSystem(this, this._audioManager));
this.systems.add(new pc.SoundComponentSystem(this, this._audioManager));
this.systems.add(new pc.AudioListenerComponentSystem(this, this._audioManager));
this.systems.add(new pc.ParticleSystemComponentSystem(this));
this.systems.add(new pc.ScreenComponentSystem(this));
this.systems.add(new pc.ElementComponentSystem(this));
this.systems.add(new pc.ButtonComponentSystem(this));
this.systems.add(new pc.ScrollViewComponentSystem(this));
this.systems.add(new pc.ScrollbarComponentSystem(this));
this.systems.add(new pc.SpriteComponentSystem(this));
this.systems.add(new pc.LayoutGroupComponentSystem(this));
this.systems.add(new pc.LayoutChildComponentSystem(this));
this.systems.add(new pc.ZoneComponentSystem(this));
this._visibilityChangeHandler = this.onVisibilityChange.bind(this);
// Depending on browser add the correct visibiltychange event and store the name of the hidden attribute
// in this._hiddenAttr.
if (typeof document !== 'undefined') {
if (document.hidden !== undefined) {
this._hiddenAttr = 'hidden';
document.addEventListener('visibilitychange', this._visibilityChangeHandler, false);
} else if (document.mozHidden !== undefined) {
this._hiddenAttr = 'mozHidden';
document.addEventListener('mozvisibilitychange', this._visibilityChangeHandler, false);
} else if (document.msHidden !== undefined) {
this._hiddenAttr = 'msHidden';
document.addEventListener('msvisibilitychange', this._visibilityChangeHandler, false);
} else if (document.webkitHidden !== undefined) {
this._hiddenAttr = 'webkitHidden';
document.addEventListener('webkitvisibilitychange', this._visibilityChangeHandler, false);
}
}
// bind tick function to current scope
/* eslint-disable-next-line no-use-before-define */
this.tick = makeTick(this); // Circular linting issue as makeTick and Application reference each other
};
Application.prototype = Object.create(pc.EventHandler.prototype);
Application.prototype.constructor = Application;
Application._currentApplication = null;
Application._applications = {};
/**
* @static
* @function
* @name pc.Application.getApplication
* @description Get the current application. In the case where there are multiple running
* applications, the function can get an application based on a supplied canvas id. This
* function is particularly useful when the current pc.Application is not readily available.
* For example, in the JavaScript console of the browser's developer tools.
* @param {string} [id] - If defined, the returned application should use the canvas which has this id. Otherwise current application will be returned.
* @returns {pc.Application|undefined} The running application, if any.
* @example
* var app = pc.Application.getApplication();
*/
Application.getApplication = function (id) {
return id ? Application._applications[id] : Application._currentApplication;
};
// Mini-object used to measure progress of loading sets
var Progress = function (length) {
this.length = length;
this.count = 0;
this.inc = function () {
this.count++;
};
this.done = function () {
return (this.count === this.length);
};
};
Object.assign(Application.prototype, {
/**
* @function
* @name pc.Application#configure
* @description Load the application configuration file and apply application properties and fill the asset registry.
* @param {string} url - The URL of the configuration file to load.
* @param {pc.callbacks.ConfigureApp} callback - The Function called when the configuration file is loaded and parsed (or an error occurs).
*/
configure: function (url, callback) {
var self = this;
pc.http.get(url, function (err, response) {
if (err) {
callback(err);
return;
}
var props = response.application_properties;
var scenes = response.scenes;
var assets = response.assets;
self._parseApplicationProperties(props, function (err) {
self._parseScenes(scenes);
self._parseAssets(assets);
if (!err) {
callback(null);
} else {
callback(err);
}
});
});
},
/**
* @function
* @name pc.Application#preload
* @description Load all assets in the asset registry that are marked as 'preload'.
* @param {pc.callbacks.PreloadApp} callback - Function called when all assets are loaded.
*/
preload: function (callback) {
var self = this;
var i, total;
self.fire("preload:start");
// get list of assets to preload
var assets = this.assets.list({
preload: true
});
var _assets = new Progress(assets.length);
var _done = false;
// check if all loading is done
var done = function () {
// do not proceed if application destroyed
if (!self.graphicsDevice) {
return;
}
if (!_done && _assets.done()) {
_done = true;
self.fire("preload:end");
callback();
}
};
// totals loading progress of assets
total = assets.length;
var count = function () {
return _assets.count;
};
if (_assets.length) {
var onAssetLoad = function (asset) {
_assets.inc();
self.fire('preload:progress', count() / total);
if (_assets.done())
done();
};
var onAssetError = function (err, asset) {
_assets.inc();
self.fire('preload:progress', count() / total);
if (_assets.done())
done();
};
// for each asset
for (i = 0; i < assets.length; i++) {
if (!assets[i].loaded) {
assets[i].once('load', onAssetLoad);
assets[i].once('error', onAssetError);
this.assets.load(assets[i]);
} else {
_assets.inc();
self.fire("preload:progress", count() / total);
if (_assets.done())
done();
}
}
} else {
done();
}
},
/**
* @function
* @name pc.Application#getSceneUrl
* @description Look up the URL of the scene hierarchy file via the name given to the scene in the editor. Use this to in {@link pc.Application#loadSceneHierarchy}.
* @param {string} name - The name of the scene file given in the Editor.
* @returns {string} The URL of the scene file.
*/
getSceneUrl: function (name) {
var entry = this._sceneRegistry.find(name);
if (entry) {
return entry.url;
}
return null;
},
/**
* @function
* @name pc.Application#loadSceneHierarchy
* @description Load a scene file, create and initialize the Entity hierarchy
* and add the hierarchy to the application root Entity.
* @param {string} url - The URL of the scene file. Usually this will be "scene_id.json".
* @param {pc.callbacks.LoadHierarchy} callback - The function to call after loading, passed (err, entity) where err is null if no errors occurred.
* @example
*
* app.loadSceneHierarchy("1000.json", function (err, entity) {
* if (!err) {
* var e = app.root.find("My New Entity");
* } else {
* // error
* }
* });
*/
loadSceneHierarchy: function (url, callback) {
this._sceneRegistry.loadSceneHierarchy(url, callback);
},
/**
* @function
* @name pc.Application#loadSceneSettings
* @description Load a scene file and automatically apply the scene settings to the current scene.
* @param {string} url - The URL of the scene file. Usually this will be "scene_id.json".
* @param {pc.callbacks.LoadSettings} callback - The function called after the settings are applied. Passed (err) where err is null if no error occurred.
* @example
* app.loadSceneSettings("1000.json", function (err) {
* if (!err) {
* // success
* } else {
* // error
* }
* });
*/
loadSceneSettings: function (url, callback) {
this._sceneRegistry.loadSceneSettings(url, callback);
},
/**
* @private
* @function
* @name pc.Application#loadScene
* @description Load a scene file.
* @param {string} url - The URL of the scene file. Usually this will be "scene_id.json".
* @param {pc.callbacks.LoadScene} callback - The function to call after loading, passed (err, entity) where err is null if no errors occurred.
* @example
*
* app.loadScene("1000.json", function (err, entity) {
* if (!err) {
* var e = app.root.find("My New Entity");
* } else {
* // error
* }
* });
*/
loadScene: function (url, callback) {
this._sceneRegistry.loadScene(url, callback);
},
_preloadScripts: function (sceneData, callback) {
if (!pc.script.legacy) {
callback();
return;
}
var self = this;
self.systems.script.preloading = true;
var scripts = this._getScriptReferences(sceneData);
var i = 0, l = scripts.length;
var progress = new Progress(l);
var scriptUrl;
var regex = /^http(s)?:\/\//;
if (l) {
var onLoad = function (err, ScriptType) {
if (err)
console.error(err);
progress.inc();
if (progress.done()) {
self.systems.script.preloading = false;
callback();
}
};
for (i = 0; i < l; i++) {
scriptUrl = scripts[i];
// support absolute URLs (for now)
if (!regex.test(scriptUrl.toLowerCase()) && self._scriptPrefix)
scriptUrl = pc.path.join(self._scriptPrefix, scripts[i]);
this.loader.load(scriptUrl, 'script', onLoad);
}
} else {
self.systems.script.preloading = false;
callback();
}
},
// set application properties from data file
_parseApplicationProperties: function (props, callback) {
var i;
var len;
// TODO: remove this temporary block after migrating properties
if (!props.useDevicePixelRatio)
props.useDevicePixelRatio = props.use_device_pixel_ratio;
if (!props.resolutionMode)
props.resolutionMode = props.resolution_mode;
if (!props.fillMode)
props.fillMode = props.fill_mode;
this._width = props.width;
this._height = props.height;
if (props.useDevicePixelRatio) {
this.graphicsDevice.maxPixelRatio = window.devicePixelRatio;
}
this.setCanvasResolution(props.resolutionMode, this._width, this._height);
this.setCanvasFillMode(props.fillMode, this._width, this._height);
// set up layers
if (props.layers && props.layerOrder) {
var composition = new pc.LayerComposition();
var layers = {};
for (var key in props.layers) {
var data = props.layers[key];
data.id = parseInt(key, 10);
// depth layer should only be enabled when needed
// by incrementing its ref counter
data.enabled = data.id !== pc.LAYERID_DEPTH;
layers[key] = new pc.Layer(data);
}
for (i = 0, len = props.layerOrder.length; i < len; i++) {
var sublayer = props.layerOrder[i];
var layer = layers[sublayer.layer];
if (!layer) continue;
if (sublayer.transparent) {
composition.pushTransparent(layer);
} else {
composition.pushOpaque(layer);
}
composition.subLayerEnabled[i] = sublayer.enabled;
}
this.scene.layers = composition;
}
// add batch groups
if (props.batchGroups) {
for (i = 0, len = props.batchGroups.length; i < len; i++) {
var grp = props.batchGroups[i];
this.batcher.addGroup(grp.name, grp.dynamic, grp.maxAabbSize, grp.id, grp.layers);
}
}
// set localization assets
if (props.i18nAssets) {
this.i18n.assets = props.i18nAssets;
}
this._loadLibraries(props.libraries, callback);
},
_loadLibraries: function (urls, callback) {
var len = urls.length;
var count = len;
var self = this;
var regex = /^http(s)?:\/\//;
if (len) {
var onLoad = function (err, script) {
count--;
if (err) {
callback(err);
} else if (count === 0) {
self.onLibrariesLoaded();
callback(null);
}
};
for (var i = 0; i < len; ++i) {
var url = urls[i];
if (!regex.test(url.toLowerCase()) && self._scriptPrefix)
url = pc.path.join(self._scriptPrefix, url);
this.loader.load(url, 'script', onLoad);
}
} else {
self.onLibrariesLoaded();
callback(null);