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
2338 lines (2014 loc) · 84.9 KB
/
application.js
File metadata and controls
2338 lines (2014 loc) · 84.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
import { version, revision } from '../core/core.js';
import { now } from '../core/time.js';
import { path } from '../core/path.js';
import { EventHandler } from '../core/event-handler.js';
import { math } from '../math/math.js';
import { Color } from '../math/color.js';
import { Vec3 } from '../math/vec3.js';
import { Mat4 } from '../math/mat4.js';
import { Quat } from '../math/quat.js';
import { http } from '../net/http.js';
import {
ADDRESS_CLAMP_TO_EDGE,
CLEARFLAG_COLOR, CLEARFLAG_DEPTH,
FILTER_NEAREST,
PIXELFORMAT_DEPTHSTENCIL, PIXELFORMAT_R8_G8_B8_A8,
PRIMITIVE_TRIANGLES, PRIMITIVE_TRIFAN, PRIMITIVE_TRISTRIP
} from '../graphics/constants.js';
import { destroyPostEffectQuad } from '../graphics/simple-post-effect.js';
import { GraphicsDevice } from '../graphics/graphics-device.js';
import { RenderTarget } from '../graphics/render-target.js';
import { Texture } from '../graphics/texture.js';
import {
LAYERID_DEPTH, LAYERID_IMMEDIATE, LAYERID_SKYBOX, LAYERID_UI, LAYERID_WORLD,
LINEBATCH_OVERLAY,
SHADER_DEPTH,
SORTMODE_NONE, SORTMODE_MANUAL
} from '../scene/constants.js';
import { BatchManager } from '../scene/batching/batch-manager.js';
import { ForwardRenderer } from '../scene/forward-renderer.js';
import { ImmediateData } from '../scene/immediate.js';
import { Layer } from '../scene/layer.js';
import { LayerComposition } from '../scene/layer-composition.js';
import { Lightmapper } from '../scene/lightmapper.js';
import { ParticleEmitter } from '../scene/particle-system/particle-emitter.js';
import { Scene } from '../scene/scene.js';
import { Material } from '../scene/materials/material.js';
import { WorldClusters } from '../scene/world-clusters.js';
import { SoundManager } from '../sound/manager.js';
import { AnimationHandler } from '../resources/animation.js';
import { AnimClipHandler } from '../resources/anim-clip.js';
import { AnimStateGraphHandler } from '../resources/anim-state-graph.js';
import { AudioHandler } from '../resources/audio.js';
import { BinaryHandler } from '../resources/binary.js';
import { BundleHandler } from '../resources/bundle.js';
import { ContainerHandler } from '../resources/container.js';
import { CssHandler } from '../resources/css.js';
import { CubemapHandler } from '../resources/cubemap.js';
import { FolderHandler } from '../resources/folder.js';
import { FontHandler } from '../resources/font.js';
import { HierarchyHandler } from '../resources/hierarchy.js';
import { HtmlHandler } from '../resources/html.js';
import { JsonHandler } from '../resources/json.js';
import { MaterialHandler } from '../resources/material.js';
import { ModelHandler } from '../resources/model.js';
import { RenderHandler } from '../resources/render.js';
import { ResourceLoader } from '../resources/loader.js';
import { SceneHandler } from '../resources/scene.js';
import { ScriptHandler } from '../resources/script.js';
import { ShaderHandler } from '../resources/shader.js';
import { SpriteHandler } from '../resources/sprite.js';
import { TemplateHandler } from '../resources/template.js';
import { TextHandler } from '../resources/text.js';
import { TextureAtlasHandler } from '../resources/texture-atlas.js';
import { TextureHandler } from '../resources/texture.js';
import { Asset } from '../asset/asset.js';
import { AssetRegistry } from '../asset/asset-registry.js';
import { BundleRegistry } from '../bundles/bundle-registry.js';
import { ScriptRegistry } from '../script/script-registry.js';
import { I18n } from '../i18n/i18n.js';
import { VrManager } from '../vr/vr-manager.js';
import { XrManager } from '../xr/xr-manager.js';
import { AnimationComponentSystem } from './components/animation/system.js';
import { AnimComponentSystem } from './components/anim/system.js';
import { AudioListenerComponentSystem } from './components/audio-listener/system.js';
import { AudioSourceComponentSystem } from './components/audio-source/system.js';
import { ButtonComponentSystem } from './components/button/system.js';
import { CameraComponentSystem } from './components/camera/system.js';
import { CollisionComponentSystem } from './components/collision/system.js';
import { ComponentSystemRegistry } from './components/registry.js';
import { ComponentSystem } from './components/system.js';
import { ElementComponentSystem } from './components/element/system.js';
import { JointComponentSystem } from './components/joint/system.js';
import { LayoutChildComponentSystem } from './components/layout-child/system.js';
import { LayoutGroupComponentSystem } from './components/layout-group/system.js';
import { LightComponentSystem } from './components/light/system.js';
import { ModelComponentSystem } from './components/model/system.js';
import { RenderComponentSystem } from './components/render/system.js';
import { ParticleSystemComponentSystem } from './components/particle-system/system.js';
import { RigidBodyComponentSystem } from './components/rigid-body/system.js';
import { ScreenComponentSystem } from './components/screen/system.js';
import { ScriptComponentSystem } from './components/script/system.js';
import { ScriptLegacyComponentSystem } from './components/script-legacy/system.js';
import { ScrollViewComponentSystem } from './components/scroll-view/system.js';
import { ScrollbarComponentSystem } from './components/scrollbar/system.js';
import { SoundComponentSystem } from './components/sound/system.js';
import { SpriteComponentSystem } from './components/sprite/system.js';
import { ZoneComponentSystem } from './components/zone/system.js';
import { script } from './script.js';
import { ApplicationStats } from './stats.js';
import { Entity } from './entity.js';
import { SceneRegistry } from './scene-registry.js';
import {
FILLMODE_FILL_WINDOW, FILLMODE_KEEP_ASPECT,
RESOLUTION_AUTO, RESOLUTION_FIXED
} from './constants.js';
import {
getApplication,
setApplication
} from './globals.js';
// Mini-object used to measure progress of loading sets
class Progress {
constructor(length) {
this.length = length;
this.count = 0;
}
inc() {
this.count++;
}
done() {
return (this.count === this.length);
}
}
var _deprecationWarning = false;
/**
* @class
* @name Application
* @augments EventHandler
* @classdesc An Application represents and manages your PlayCanvas application.
* If you are developing using the PlayCanvas Editor, the Application is created
* for you. You can access your 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 {ElementInput} [options.elementInput] - Input handler for {@link ElementComponent}s.
* @param {Keyboard} [options.keyboard] - Keyboard handler for input.
* @param {Mouse} [options.mouse] - Mouse handler for input.
* @param {TouchDevice} [options.touch] - TouchDevice handler for input.
* @param {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 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 Application#scene
* @type {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 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 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 Application#scenes
* @type {SceneRegistry}
* @description The scene registry managed by the application.
* @example
* // Search the scene registry for a item with the name 'racetrack1'
* var sceneItem = this.app.scenes.find('racetrack1');
*
* // Load the scene using the item's url
* this.app.scenes.loadScene(sceneItem.url);
*/
/**
* @name Application#assets
* @type {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 Application#graphicsDevice
* @type {GraphicsDevice}
* @description The graphics device used by the application.
*/
/**
* @name Application#systems
* @type {ComponentSystemRegistry}
* @description The application's component system registry. The Application
* constructor adds the following component systems to its component system registry:
*
* * anim ({@link AnimComponentSystem})
* * animation ({@link AnimationComponentSystem})
* * audiolistener ({@link AudioListenerComponentSystem})
* * button ({@link ButtonComponentSystem})
* * camera ({@link CameraComponentSystem})
* * collision ({@link CollisionComponentSystem})
* * element ({@link ElementComponentSystem})
* * layoutchild ({@link LayoutChildComponentSystem})
* * layoutgroup ({@link LayoutGroupComponentSystem})
* * light ({@link LightComponentSystem})
* * model ({@link ModelComponentSystem})
* * particlesystem ({@link ParticleSystemComponentSystem})
* * rigidbody ({@link RigidBodyComponentSystem})
* * render ({@link RenderComponentSystem})
* * screen ({@link ScreenComponentSystem})
* * script ({@link ScriptComponentSystem})
* * scrollbar ({@link ScrollbarComponentSystem})
* * scrollview ({@link ScrollViewComponentSystem})
* * sound ({@link SoundComponentSystem})
* * sprite ({@link 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 Application#xr
* @type {XrManager}
* @description The XR Manager that provides ability to start VR/AR sessions.
* @example
* // check if VR is available
* if (app.xr.isAvailable(pc.XRTYPE_VR)) {
* // VR is available
* }
*/
/**
* @name Application#lightmapper
* @type {Lightmapper}
* @description The run-time lightmapper.
*/
/**
* @name Application#loader
* @type {ResourceLoader}
* @description The resource loader.
*/
/**
* @name Application#root
* @type {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 Application#keyboard
* @type {Keyboard}
* @description The keyboard device.
*/
/**
* @name Application#mouse
* @type {Mouse}
* @description The mouse device.
*/
/**
* @name Application#touch
* @type {TouchDevice}
* @description Used to get touch events input.
*/
/**
* @name Application#gamepads
* @type {GamePads}
* @description Used to access GamePad input.
*/
/**
* @name Application#elementInput
* @type {ElementInput}
* @description Used to handle input for {@link ElementComponent}s.
*/
/**
* @name Application#scripts
* @type {ScriptRegistry}
* @description The application's script registry.
*/
/**
* @name Application#batcher
* @type {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 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 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 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 Application#i18n
* @type {I18n}
* @description Handles localization.
*/
/**
* @private
* @static
* @name app
* @type {Application|undefined}
* @description Gets the current application, if any.
*/
var app = null;
class Application extends EventHandler {
constructor(canvas, options = {}) {
super();
console.log("Powered by PlayCanvas " + version + " " + revision);
// Store application instance
Application._applications[canvas.id] = this;
setApplication(this);
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 = script.legacy;
this._librariesLoaded = false;
this._fillMode = FILLMODE_KEEP_ASPECT;
this._resolutionMode = RESOLUTION_FIXED;
this._allowResize = true;
// for compatibility
this.context = this;
if (! options.graphicsDeviceOptions)
options.graphicsDeviceOptions = { };
options.graphicsDeviceOptions.xrCompatible = true;
options.graphicsDeviceOptions.alpha = options.graphicsDeviceOptions.alpha || false;
this.graphicsDevice = new GraphicsDevice(canvas, options.graphicsDeviceOptions);
this.stats = new ApplicationStats(this.graphicsDevice);
this._soundManager = new SoundManager(options);
this.loader = new ResourceLoader(this);
WorldClusters.init(this.graphicsDevice);
// stores all entities that have been created
// for this app by guid
this._entityIndex = {};
this.scene = new Scene();
this.root = new Entity(this);
this.root._enabledInHierarchy = true;
this._enableList = [];
this._enableList.size = 0;
this.assets = new AssetRegistry(this.loader);
if (options.assetPrefix) this.assets.prefix = options.assetPrefix;
this.bundles = new 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 ScriptRegistry(this);
this.i18n = new I18n(this);
this.scenes = new SceneRegistry(this);
var self = this;
this.defaultLayerWorld = new Layer({
name: "World",
id: LAYERID_WORLD
});
if (this.graphicsDevice.webgl2) {
// WebGL 2 depth layer just copies existing depth
this.defaultLayerDepth = new Layer({
enabled: false,
name: "Depth",
id: LAYERID_DEPTH,
onEnable: function () {
if (this.renderTarget) return;
var depthBuffer = new Texture(self.graphicsDevice, {
format: PIXELFORMAT_DEPTHSTENCIL,
width: self.graphicsDevice.width,
height: self.graphicsDevice.height,
mipmaps: false
});
depthBuffer.name = 'rt-depth2';
depthBuffer.minFilter = FILTER_NEAREST;
depthBuffer.magFilter = FILTER_NEAREST;
depthBuffer.addressU = ADDRESS_CLAMP_TO_EDGE;
depthBuffer.addressV = ADDRESS_CLAMP_TO_EDGE;
this.renderTarget = new 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 Layer({
enabled: false,
name: "Depth",
id: LAYERID_DEPTH,
shaderPass: SHADER_DEPTH,
onEnable: function () {
if (this.renderTarget) return;
var colorBuffer = new Texture(self.graphicsDevice, {
format: PIXELFORMAT_R8_G8_B8_A8,
width: self.graphicsDevice.width,
height: self.graphicsDevice.height,
mipmaps: false
});
colorBuffer.name = 'rt-depth1';
colorBuffer.minFilter = FILTER_NEAREST;
colorBuffer.magFilter = FILTER_NEAREST;
colorBuffer.addressU = ADDRESS_CLAMP_TO_EDGE;
colorBuffer.addressV = ADDRESS_CLAMP_TO_EDGE;
this.renderTarget = new 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;
// can't use self.defaultLayerWorld.renderTarget because projects that use the editor override default layers
var rt = self.scene.layers.getLayerById(LAYERID_WORLD).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: CLEARFLAG_COLOR | CLEARFLAG_DEPTH
};
}
this.defaultLayerSkybox = new Layer({
enabled: false,
name: "Skybox",
id: LAYERID_SKYBOX,
opaqueSortMode: SORTMODE_NONE
});
this.defaultLayerUi = new Layer({
enabled: true,
name: "UI",
id: LAYERID_UI,
transparentSortMode: SORTMODE_MANUAL,
passThrough: false
});
this.defaultLayerImmediate = new Layer({
enabled: true,
name: "Immediate",
id: LAYERID_IMMEDIATE,
opaqueSortMode: SORTMODE_NONE,
passThrough: true
});
const defaultLayerComposition = new LayerComposition(this.graphicsDevice, "default");
defaultLayerComposition.pushOpaque(this.defaultLayerWorld);
defaultLayerComposition.pushOpaque(this.defaultLayerDepth);
defaultLayerComposition.pushOpaque(this.defaultLayerSkybox);
defaultLayerComposition.pushTransparent(this.defaultLayerWorld);
defaultLayerComposition.pushOpaque(this.defaultLayerImmediate);
defaultLayerComposition.pushTransparent(this.defaultLayerImmediate);
defaultLayerComposition.pushTransparent(this.defaultLayerUi);
this.scene.layers = 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 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 LAYERID_UI:
layer.passThrough = self.defaultLayerUi.passThrough;
break;
case LAYERID_IMMEDIATE:
layer.passThrough = self.defaultLayerImmediate.passThrough;
break;
}
}
});
this.renderer = new ForwardRenderer(this.graphicsDevice);
this.renderer.scene = this.scene;
this.lightmapper = new Lightmapper(this.graphicsDevice, this.root, this.scene, this.renderer, this.assets);
this.once('prerender', this._firstBake, this);
this.batcher = new 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.vr = null;
this.xr = new XrManager(this);
if (this.elementInput)
this.elementInput.attachSelectEvents();
this._inTools = false;
this._skyboxLast = 0;
this._scriptPrefix = options.scriptPrefix || '';
if (this.enableBundles) {
this.loader.addHandler("bundle", new BundleHandler(this.assets));
}
this.loader.addHandler("animation", new AnimationHandler());
this.loader.addHandler("animclip", new AnimClipHandler());
this.loader.addHandler("animstategraph", new AnimStateGraphHandler());
this.loader.addHandler("model", new ModelHandler(this.graphicsDevice, this.scene.defaultMaterial));
this.loader.addHandler("render", new RenderHandler(this.assets));
this.loader.addHandler("material", new MaterialHandler(this));
this.loader.addHandler("texture", new TextureHandler(this.graphicsDevice, this.assets, this.loader));
this.loader.addHandler("text", new TextHandler());
this.loader.addHandler("json", new JsonHandler());
this.loader.addHandler("audio", new AudioHandler(this._soundManager));
this.loader.addHandler("script", new ScriptHandler(this));
this.loader.addHandler("scene", new SceneHandler(this));
this.loader.addHandler("cubemap", new CubemapHandler(this.graphicsDevice, this.assets, this.loader));
this.loader.addHandler("html", new HtmlHandler());
this.loader.addHandler("css", new CssHandler());
this.loader.addHandler("shader", new ShaderHandler());
this.loader.addHandler("hierarchy", new HierarchyHandler(this));
this.loader.addHandler("folder", new FolderHandler());
this.loader.addHandler("font", new FontHandler(this.loader));
this.loader.addHandler("binary", new BinaryHandler());
this.loader.addHandler("textureatlas", new TextureAtlasHandler(this.loader));
this.loader.addHandler("sprite", new SpriteHandler(this.assets, this.graphicsDevice));
this.loader.addHandler("template", new TemplateHandler(this));
this.loader.addHandler("container", new ContainerHandler(this.graphicsDevice, this.scene.defaultMaterial));
this.systems = new ComponentSystemRegistry();
this.systems.add(new RigidBodyComponentSystem(this));
this.systems.add(new CollisionComponentSystem(this));
this.systems.add(new JointComponentSystem(this));
this.systems.add(new AnimationComponentSystem(this));
this.systems.add(new AnimComponentSystem(this));
this.systems.add(new ModelComponentSystem(this));
this.systems.add(new RenderComponentSystem(this));
this.systems.add(new CameraComponentSystem(this));
this.systems.add(new LightComponentSystem(this));
if (script.legacy) {
this.systems.add(new ScriptLegacyComponentSystem(this));
} else {
this.systems.add(new ScriptComponentSystem(this));
}
this.systems.add(new AudioSourceComponentSystem(this, this._soundManager));
this.systems.add(new SoundComponentSystem(this, this._soundManager));
this.systems.add(new AudioListenerComponentSystem(this, this._soundManager));
this.systems.add(new ParticleSystemComponentSystem(this));
this.systems.add(new ScreenComponentSystem(this));
this.systems.add(new ElementComponentSystem(this));
this.systems.add(new ButtonComponentSystem(this));
this.systems.add(new ScrollViewComponentSystem(this));
this.systems.add(new ScrollbarComponentSystem(this));
this.systems.add(new SpriteComponentSystem(this));
this.systems.add(new LayoutGroupComponentSystem(this));
this.systems.add(new LayoutChildComponentSystem(this));
this.systems.add(new 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
}
static _applications = {};
/**
* @static
* @function
* @name 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 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 {Application|undefined} The running application, if any.
* @example
* var app = pc.Application.getApplication();
*/
static getApplication(id) {
return id ? Application._applications[id] : getApplication();
}
/**
* @readonly
* @name Application#fillMode
* @type {string}
* @description The current fill mode of the canvas. Can be:
*
* * {@link FILLMODE_NONE}: the canvas will always match the size provided.
* * {@link FILLMODE_FILL_WINDOW}: the canvas will simply fill the window, changing aspect ratio.
* * {@link FILLMODE_KEEP_ASPECT}: the canvas will grow to fill the window as best it can while maintaining the aspect ratio.
*/
get fillMode() {
return this._fillMode;
}
/**
* @readonly
* @name Application#resolutionMode
* @type {string}
* @description The current resolution mode of the canvas, Can be:
*
* * {@link RESOLUTION_AUTO}: if width and height are not provided, canvas will be resized to match canvas client size.
* * {@link RESOLUTION_FIXED}: resolution of canvas will be fixed.
*/
get resolutionMode() {
return this._resolutionMode;
}
/**
* @function
* @name 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 {callbacks.ConfigureApp} callback - The Function called when the configuration file is loaded and parsed (or an error occurs).
*/
configure(url, callback) {
var self = this;
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 Application#preload
* @description Load all assets in the asset registry that are marked as 'preload'.
* @param {callbacks.PreloadApp} callback - Function called when all assets are loaded.
*/
preload(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();
}
}
_preloadScripts(sceneData, callback) {
if (!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();
}
};