BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / scene.js

scene.js

engine optimisations
timfa Tim Falken · pushed by timfa · 3 months ago
74d8cdb3 History
scene.js 9.7 KiB Download Raw
1class Scene
2{
3 static idCount = 0;
4 id = null;
5 activeObjects = [];
6 position = null;
7 size = null;
8 real_position = null;
9 px = 0; py = 0;
10 real_size = null;
11 cameraPosition = null;
12 parentScene = null;
13 renderBackground = true;
14 quadTree = null;
15
16 pendingRemoval = [];
17 _sortedActiveObjects = null;
18 _sortDirty = true;
19
20 g_primary = false;
21
22 static DisplayModes = { absolute: 0, relativeToParent: 1 };
23
24 displayMode = Scene.DisplayModes.absolute;
25
26 cv_canvas = null;
27 glContext = null;
28 destroyed = false;
29
30 // Legacy: posts applied to the "default" layer when that layer has none of its own.
31 postShaders = [];
32 postTime = 0;
33
34 // Ordered list of RenderLayer. Index 0 is drawn first (back).
35 renderLayers = null;
36
37 game = null;
38
39 get primary ()
40 {
41 return this.g_primary;
42 }
43
44 constructor (x, y, width, height, displayMode = 0)
45 {
46 Scene.idCount++;
47 this.id = 'canvas_' + Scene.idCount;
48
49 this.position = new vector(x, y);
50 this.size = new vector(width, height);
51 this.real_position = new vector(x, y);
52 this.real_size = new vector(width, height);
53 this.cameraPosition = new vector(0, 0);
54 this.displayMode = displayMode;
55
56
57 const body = document.body;
58
59 body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');
60
61 this.cv_canvas = document.getElementById(this.id);
62 this.glContext = new GLContext(this.cv_canvas);
63 this.postShaders = [];
64 this.postTime = 0;
65 this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];
66
67 this.g_fixSize();
68 this.quadTree = new QuadTree(this.real_size.x, this.real_size.y);
69 }
70
71 /**
72 * Replace the layer stack. Order in the array is draw order (first = back).
73 * Each entry: RenderLayer, or { name, postShaders?, composite? }.
74 */
75 setLayers (layerConfigs)
76 {
77 if (!layerConfigs || !layerConfigs.length)
78 {
79 this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];
80 return this.renderLayers;
81 }
82
83 const layers = [];
84 for (let i = 0; i < layerConfigs.length; i++)
85 {
86 const cfg = layerConfigs[i];
87 if (!cfg)
88 { continue; }
89
90 if (cfg instanceof RenderLayer)
91 { layers.push(cfg); }
92 else
93 { layers.push(new RenderLayer(cfg.name, cfg)); }
94 }
95
96 if (!layers.length)
97 { layers.push(new RenderLayer(RenderLayer.DEFAULT_NAME)); }
98
99 this.renderLayers = layers;
100 return this.renderLayers;
101 }
102
103 getLayer (name)
104 {
105 const layers = this.renderLayers || [];
106 for (let i = 0; i < layers.length; i++)
107 {
108 if (layers[i].name === name)
109 { return layers[i]; }
110 }
111
112 return null;
113 }
114
115 setPrimary ()
116 {
117 this.game.setPrimaryScene(this);
118 }
119
120 onLoad ()
121 {
122
123 }
124
125 loadChildScene (scene)
126 {
127 scene.parentScene = this;
128 this.game.loadScene(scene);
129 }
130
131 destroy ()
132 {
133 if (this.destroyed)
134 { return; }
135
136 for (var i = 0; i < this.activeObjects.length; i++)
137 {
138 this.activeObjects[i].destroy();
139 }
140
141 this.destroyed = true;
142
143 if (this.game)
144 { this.game.removeScene(this); }
145
146 this.removeCanvas();
147
148 if (this.primary)
149 {
150 if (this.parentScene && !this.parentScene.destroyed)
151 {
152 this.parentScene.setPrimary();
153 }
154 else if (this.game)
155 {
156 let promoted = null;
157 for (let i = 0; i < this.game.activeScenes.length; i++)
158 {
159 const candidate = this.game.activeScenes[i];
160 if (candidate !== this && !candidate.destroyed)
161 {
162 promoted = candidate;
163 break;
164 }
165 }
166
167 if (promoted)
168 { this.game.setPrimaryScene(promoted); }
169 else
170 { this.g_primary = false; }
171 }
172 else
173 {
174 this.g_primary = false;
175 }
176 }
177 }
178
179 removeCanvas ()
180 {
181 var elem = this.cv_canvas || document.getElementById(this.id);
182 if (elem && elem.parentNode)
183 {
184 elem.parentNode.removeChild(elem);
185 }
186
187 this.cv_canvas = null;
188 this.glContext = null;
189 }
190
191 backgroundColor =
192 {
193 r: 255,
194 g: 255,
195 b: 255
196 };
197
198 get canvas ()
199 {
200 return this.cv_canvas;
201 }
202
203 get context ()
204 {
205 return this.glContext ? this.glContext.gl : null;
206 }
207
208 addObject (obj)
209 {
210 if (this.destroyed)
211 { return; }
212
213 this.activeObjects.push(obj);
214 this._sortDirty = true;
215 obj.scene = this;
216 obj.initQuadtree(this.quadTree);
217 obj.checkQuadtree();
218
219 obj.addedToScene && obj.addedToScene();
220
221 return obj;
222 }
223
224 removeObject (obj)
225 {
226 if (this.activeObjects.indexOf(obj) >= 0)
227 {
228 if (!this.pendingRemoval.contains(obj))
229 { this.pendingRemoval.push(obj); }
230
231 this._sortDirty = true;
232 }
233
234 if (this.quadTree === obj.quadTree)
235 { this.quadTree.remove(obj); }
236 }
237
238 update (deltaTime)
239 {
240 if (this.destroyed)
241 { return; }
242
243 this.postTime += deltaTime;
244
245 for (let i = 0; i < this.activeObjects.length; i++)
246 {
247 this.activeObjects[i].update(deltaTime);
248 }
249
250 if (this.pendingRemoval.length)
251 {
252 for (let i = 0; i < this.pendingRemoval.length; i++)
253 {
254 const obj = this.pendingRemoval[i];
255 const index = this.activeObjects.indexOf(obj);
256 if (index >= 0 && obj.destroyed)
257 { this.activeObjects.removeAt(index); }
258 }
259
260 this.pendingRemoval.length = 0;
261 }
262
263 this.quadTree.update(deltaTime);
264 }
265
266 g_fixSize ()
267 {
268 if (this.displayMode == Scene.DisplayModes.relativeToParent)
269 {
270 if (this.parentScene)
271 {
272 this.real_position.x = this.parentScene.real_position.x + (this.position.x * this.parentScene.real_size.x);
273 this.real_position.y = this.parentScene.real_position.y + (this.position.y * this.parentScene.real_size.y);
274
275 this.real_size.x = this.parentScene.real_size.x * this.size.x;
276 this.real_size.y = this.parentScene.real_size.y * this.size.y;
277 }
278 else
279 {
280 this.real_position.x = window.innerWidth * this.position.x;
281 this.real_position.y = window.innerHeight * this.position.y;
282
283 this.real_size.x = window.innerWidth * this.size.x;
284 this.real_size.y = window.innerHeight * this.size.y;
285 }
286 }
287 else if (this.displayMode == Scene.DisplayModes.absolute)
288 {
289 this.real_position.x = this.position.x;
290 this.real_position.y = this.position.y;
291
292 this.real_size.x = this.size.x;
293 this.real_size.y = this.size.y;
294 }
295
296 const canvasW = Math.max(1, Math.round(this.real_size.x));
297 const canvasH = Math.max(1, Math.round(this.real_size.y));
298 let resized = false;
299
300 if (this.canvas.width != canvasW)
301 {
302 this.canvas.width = canvasW;
303 resized = true;
304 }
305
306 if (this.canvas.height != canvasH)
307 {
308 this.canvas.height = canvasH;
309 resized = true;
310 }
311
312 // Changing canvas dimensions resets WebGL — rebuild helper/buffers/programs.
313 if (resized || !this.glContext)
314 { this.glContext = new GLContext(this.cv_canvas); }
315 else
316 { this.glContext.setSize(this.canvas.width, this.canvas.height); }
317
318 if (this.px != this.real_position.x)
319 {
320 this.px = this.real_position.x;
321 this.canvas.style.left = this.real_position.x + "px";
322 }
323
324 if (this.py != this.real_position.y)
325 {
326 this.py = this.real_position.y;
327 this.canvas.style.top = this.real_position.y + "px";
328 }
329 }
330
331 normalizePostShaderList (list)
332 {
333 if (!list || !list.length)
334 { return []; }
335
336 const passes = [];
337 for (let i = 0; i < list.length; i++)
338 {
339 const entry = list[i];
340 if (!entry)
341 { continue; }
342
343 if (entry instanceof Shader || (entry.vertSource && entry.fragSource && entry.getProgramInfo))
344 {
345 passes.push({ shader: entry, uniforms: null });
346 }
347 else if (entry.shader)
348 {
349 const pass = { shader: entry.shader, uniforms: entry.uniforms || null };
350 if (entry.scale != null)
351 { pass.scale = entry.scale; }
352 passes.push(pass);
353 }
354 }
355
356 return passes;
357 }
358
359 normalizePostShaders ()
360 {
361 return this.normalizePostShaderList(this.postShaders);
362 }
363
364 getPostPassesForLayer (layer)
365 {
366 const fromLayer = this.normalizePostShaderList(layer.postShaders);
367 if (fromLayer.length)
368 { return fromLayer; }
369
370 // Back-compat: scene.postShaders apply to the default layer only.
371 if (layer.name === RenderLayer.DEFAULT_NAME)
372 { return this.normalizePostShaders(); }
373
374 return [];
375 }
376
377 draw ()
378 {
379 if (this.destroyed || !this.glContext)
380 { return; }
381
382 this.g_fixSize();
383
384 const gl = this.glContext;
385 const layers = this.renderLayers && this.renderLayers.length
386 ? this.renderLayers
387 : [new RenderLayer(RenderLayer.DEFAULT_NAME)];
388
389 // Canvas clear (background behind all layers).
390 gl.endOffscreenPass();
391 if (this.renderBackground)
392 {
393 gl.clear(
394 this.backgroundColor.r,
395 this.backgroundColor.g,
396 this.backgroundColor.b,
397 1
398 );
399 }
400 else
401 {
402 gl.clearTransparent();
403 }
404
405 if (this._sortDirty || !this._sortedActiveObjects)
406 {
407 this._sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);
408 this._sortDirty = false;
409 }
410
411 const sortedActiveObjects = this._sortedActiveObjects;
412
413 // Bucket visible objects once so empty bloom layers can be skipped entirely.
414 const byLayer = Object.create(null);
415 for (let i = 0; i < sortedActiveObjects.length; i++)
416 {
417 const obj = sortedActiveObjects[i];
418 if (obj.destroyed || !obj.renderer || !obj.renderer.visible)
419 { continue; }
420
421 const name = obj.renderer.layerName;
422 let bucket = byLayer[name];
423 if (!bucket)
424 {
425 bucket = [];
426 byLayer[name] = bucket;
427 }
428
429 bucket.push(obj);
430 }
431
432 const builtins = {
433 u_resolution: [gl._lastWidth, gl._lastHeight],
434 u_time: this.postTime
435 };
436
437 for (let li = 0; li < layers.length; li++)
438 {
439 const renderLayer = layers[li];
440 const layerObjects = byLayer[renderLayer.name];
441 if (!layerObjects || !layerObjects.length)
442 { continue; }
443
444 gl.beginOffscreenPass();
445 gl.clearTransparent();
446
447 for (let i = 0; i < layerObjects.length; i++)
448 { layerObjects[i].draw(this.context); }
449
450 const postPasses = this.getPostPassesForLayer(renderLayer);
451 let texture = gl.colorTextures[0];
452
453 if (postPasses.length)
454 {
455 texture = gl.applyPostShaders(postPasses, builtins, { toCanvas: false });
456 }
457 else
458 {
459 gl.endOffscreenPass();
460 }
461
462 gl.blitToCanvas(texture, renderLayer.composite || "alpha");
463 }
464 }
465}