BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / scene.js

scene.js

scene.js 12.3 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 /** Objects whose `layer` changed since the last draw-order rebuild. */
20 _layerChanged = [];
21 /**
22 * If more than this many objects change layer between draws, fall back to a
23 * full in-place sort (cheaper than many splice reinserts on large lists).
24 */
25 _layerChangeFullSortThreshold = 64;
26
27 g_primary = false;
28
29 static DisplayModes = { absolute: 0, relativeToParent: 1 };
30
31 displayMode = Scene.DisplayModes.absolute;
32
33 cv_canvas = null;
34 glContext = null;
35 destroyed = false;
36
37 // Legacy: posts applied to the "default" layer when that layer has none of its own.
38 postShaders = [];
39 postTime = 0;
40
41 // Ordered list of RenderLayer. Index 0 is drawn first (back).
42 renderLayers = null;
43
44 game = null;
45
46 get primary ()
47 {
48 return this.g_primary;
49 }
50
51 constructor (x, y, width, height, displayMode = 0)
52 {
53 Scene.idCount++;
54 this.id = 'canvas_' + Scene.idCount;
55
56 this.position = new vector(x, y);
57 this.size = new vector(width, height);
58 this.real_position = new vector(x, y);
59 this.real_size = new vector(width, height);
60 this.cameraPosition = new vector(0, 0);
61 this.displayMode = displayMode;
62
63
64 const body = document.body;
65
66 body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');
67
68 this.cv_canvas = document.getElementById(this.id);
69 this.glContext = new GLContext(this.cv_canvas);
70 this.postShaders = [];
71 this.postTime = 0;
72 this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];
73
74 this.g_fixSize();
75 this.quadTree = new QuadTree(this.real_size.x, this.real_size.y);
76 }
77
78 /**
79 * Replace the layer stack. Order in the array is draw order (first = back).
80 * Each entry: RenderLayer, or { name, postShaders?, composite? }.
81 */
82 setLayers (layerConfigs)
83 {
84 if (!layerConfigs || !layerConfigs.length)
85 {
86 this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];
87 return this.renderLayers;
88 }
89
90 const layers = [];
91 for (let i = 0; i < layerConfigs.length; i++)
92 {
93 const cfg = layerConfigs[i];
94 if (!cfg)
95 { continue; }
96
97 if (cfg instanceof RenderLayer)
98 { layers.push(cfg); }
99 else
100 { layers.push(new RenderLayer(cfg.name, cfg)); }
101 }
102
103 if (!layers.length)
104 { layers.push(new RenderLayer(RenderLayer.DEFAULT_NAME)); }
105
106 this.renderLayers = layers;
107 return this.renderLayers;
108 }
109
110 getLayer (name)
111 {
112 const layers = this.renderLayers || [];
113 for (let i = 0; i < layers.length; i++)
114 {
115 if (layers[i].name === name)
116 { return layers[i]; }
117 }
118
119 return null;
120 }
121
122 setPrimary ()
123 {
124 this.game.setPrimaryScene(this);
125 }
126
127 onLoad ()
128 {
129
130 }
131
132 loadChildScene (scene)
133 {
134 scene.parentScene = this;
135 this.game.loadScene(scene);
136 }
137
138 destroy ()
139 {
140 if (this.destroyed)
141 { return; }
142
143 for (var i = 0; i < this.activeObjects.length; i++)
144 {
145 this.activeObjects[i].destroy();
146 }
147
148 this.destroyed = true;
149
150 if (this.game)
151 { this.game.removeScene(this); }
152
153 this.removeCanvas();
154
155 if (this.primary)
156 {
157 if (this.parentScene && !this.parentScene.destroyed)
158 {
159 this.parentScene.setPrimary();
160 }
161 else if (this.game)
162 {
163 let promoted = null;
164 for (let i = 0; i < this.game.activeScenes.length; i++)
165 {
166 const candidate = this.game.activeScenes[i];
167 if (candidate !== this && !candidate.destroyed)
168 {
169 promoted = candidate;
170 break;
171 }
172 }
173
174 if (promoted)
175 { this.game.setPrimaryScene(promoted); }
176 else
177 { this.g_primary = false; }
178 }
179 else
180 {
181 this.g_primary = false;
182 }
183 }
184 }
185
186 removeCanvas ()
187 {
188 var elem = this.cv_canvas || document.getElementById(this.id);
189 if (elem && elem.parentNode)
190 {
191 elem.parentNode.removeChild(elem);
192 }
193
194 this.cv_canvas = null;
195 this.glContext = null;
196 }
197
198 backgroundColor =
199 {
200 r: 255,
201 g: 255,
202 b: 255
203 };
204
205 get canvas ()
206 {
207 return this.cv_canvas;
208 }
209
210 get context ()
211 {
212 return this.glContext ? this.glContext.gl : null;
213 }
214
215 addObject (obj)
216 {
217 if (this.destroyed)
218 { return; }
219
220 this.activeObjects.push(obj);
221 obj.scene = this;
222 obj.initQuadtree(this.quadTree);
223 obj.checkQuadtree();
224
225 if (this._sortedActiveObjects && !this._sortDirty && !this._layerChanged.length)
226 { this.#insertSortedByLayer(this._sortedActiveObjects, obj); }
227 else
228 { this._sortDirty = true; }
229
230 obj.addedToScene && obj.addedToScene();
231
232 return obj;
233 }
234
235 removeObject (obj)
236 {
237 if (this.activeObjects.indexOf(obj) >= 0)
238 {
239 if (!this.pendingRemoval.contains(obj))
240 { this.pendingRemoval.push(obj); }
241
242 this._sortDirty = true;
243 }
244
245 if (this.quadTree === obj.quadTree)
246 { this.quadTree.remove(obj); }
247 }
248
249 /**
250 * Called when an object's draw-priority `layer` changes.
251 * Batches small moves for splice-reinsert; floods into a full sort when many change.
252 */
253 objectLayerChanged (obj)
254 {
255 if (!obj || this._sortDirty)
256 {
257 this._sortDirty = true;
258 return;
259 }
260 this._layerChanged.push(obj);
261 if (this._layerChanged.length > this._layerChangeFullSortThreshold)
262 {
263 this._sortDirty = true;
264 this._layerChanged.length = 0;
265 }
266 }
267
268 /** Force a full draw-order rebuild on the next draw (e.g. bulk external edits). */
269 markSortDirty ()
270 {
271 this._sortDirty = true;
272 this._layerChanged.length = 0;
273 }
274
275 /** First index with layer strictly greater than `layer` (insert after equal layers). */
276 #upperBoundByLayer (sorted, layer)
277 {
278 let lo = 0;
279 let hi = sorted.length;
280 while (lo < hi)
281 {
282 const mid = (lo + hi) >> 1;
283 if (sorted[mid].layer <= layer)
284 { lo = mid + 1; }
285 else
286 { hi = mid; }
287 }
288 return lo;
289 }
290
291 #insertSortedByLayer (sorted, obj)
292 {
293 // New objects and layer moves land after existing equal layers so a
294 // recently updated sprite draws on top of older ties (stable-with-recency).
295 const at = this.#upperBoundByLayer(sorted, obj.layer);
296 sorted.splice(at, 0, obj);
297 }
298
299 #reinsertSortedByLayer (sorted, obj)
300 {
301 const from = sorted.indexOf(obj);
302 if (from >= 0)
303 { sorted.splice(from, 1); }
304 this.#insertSortedByLayer(sorted, obj);
305 }
306
307 /**
308 * Ensure `_sortedActiveObjects` matches `activeObjects` ordered by `layer`.
309 * Avoids allocating a fresh array every frame (no `slice().sort()`).
310 */
311 #ensureDrawOrder ()
312 {
313 const active = this.activeObjects;
314 if (this._sortDirty || !this._sortedActiveObjects)
315 {
316 let sorted = this._sortedActiveObjects;
317 if (!sorted)
318 {
319 sorted = new Array(active.length);
320 this._sortedActiveObjects = sorted;
321 }
322 else if (sorted.length !== active.length)
323 { sorted.length = active.length; }
324
325 for (let i = 0; i < active.length; i++)
326 { sorted[i] = active[i]; }
327
328 sorted.sort((a, b) => a.layer - b.layer);
329 this._sortDirty = false;
330 this._layerChanged.length = 0;
331 return;
332 }
333
334 if (!this._layerChanged.length)
335 { return; }
336
337 const changed = this._layerChanged;
338 const sorted = this._sortedActiveObjects;
339 for (let i = 0; i < changed.length; i++)
340 { this.#reinsertSortedByLayer(sorted, changed[i]); }
341 changed.length = 0;
342 }
343
344 update (deltaTime)
345 {
346 if (this.destroyed)
347 { return; }
348
349 this.postTime += deltaTime;
350
351 for (let i = 0; i < this.activeObjects.length; i++)
352 {
353 this.activeObjects[i].update(deltaTime);
354 }
355
356 if (this.pendingRemoval.length)
357 {
358 for (let i = 0; i < this.pendingRemoval.length; i++)
359 {
360 const obj = this.pendingRemoval[i];
361 const index = this.activeObjects.indexOf(obj);
362 if (index >= 0 && obj.destroyed)
363 { this.activeObjects.removeAt(index); }
364 }
365
366 this.pendingRemoval.length = 0;
367 this._sortDirty = true;
368 this._layerChanged.length = 0;
369 }
370
371 this.quadTree.update(deltaTime);
372 }
373
374 g_fixSize ()
375 {
376 if (this.displayMode == Scene.DisplayModes.relativeToParent)
377 {
378 if (this.parentScene)
379 {
380 this.real_position.x = this.parentScene.real_position.x + (this.position.x * this.parentScene.real_size.x);
381 this.real_position.y = this.parentScene.real_position.y + (this.position.y * this.parentScene.real_size.y);
382
383 this.real_size.x = this.parentScene.real_size.x * this.size.x;
384 this.real_size.y = this.parentScene.real_size.y * this.size.y;
385 }
386 else
387 {
388 this.real_position.x = window.innerWidth * this.position.x;
389 this.real_position.y = window.innerHeight * this.position.y;
390
391 this.real_size.x = window.innerWidth * this.size.x;
392 this.real_size.y = window.innerHeight * this.size.y;
393 }
394 }
395 else if (this.displayMode == Scene.DisplayModes.absolute)
396 {
397 this.real_position.x = this.position.x;
398 this.real_position.y = this.position.y;
399
400 this.real_size.x = this.size.x;
401 this.real_size.y = this.size.y;
402 }
403
404 const canvasW = Math.max(1, Math.round(this.real_size.x));
405 const canvasH = Math.max(1, Math.round(this.real_size.y));
406 let resized = false;
407
408 if (this.canvas.width != canvasW)
409 {
410 this.canvas.width = canvasW;
411 resized = true;
412 }
413
414 if (this.canvas.height != canvasH)
415 {
416 this.canvas.height = canvasH;
417 resized = true;
418 }
419
420 // Changing canvas dimensions resets WebGL — rebuild helper/buffers/programs.
421 if (resized || !this.glContext)
422 { this.glContext = new GLContext(this.cv_canvas); }
423 else
424 { this.glContext.setSize(this.canvas.width, this.canvas.height); }
425
426 if (this.px != this.real_position.x)
427 {
428 this.px = this.real_position.x;
429 this.canvas.style.left = this.real_position.x + "px";
430 }
431
432 if (this.py != this.real_position.y)
433 {
434 this.py = this.real_position.y;
435 this.canvas.style.top = this.real_position.y + "px";
436 }
437 }
438
439 normalizePostShaderList (list)
440 {
441 if (!list || !list.length)
442 { return []; }
443
444 const passes = [];
445 for (let i = 0; i < list.length; i++)
446 {
447 const entry = list[i];
448 if (!entry)
449 { continue; }
450
451 if (entry instanceof Shader || (entry.vertSource && entry.fragSource && entry.getProgramInfo))
452 {
453 passes.push({ shader: entry, uniforms: null });
454 }
455 else if (entry.shader)
456 {
457 const pass = { shader: entry.shader, uniforms: entry.uniforms || null };
458 if (entry.scale != null)
459 { pass.scale = entry.scale; }
460 passes.push(pass);
461 }
462 }
463
464 return passes;
465 }
466
467 normalizePostShaders ()
468 {
469 return this.normalizePostShaderList(this.postShaders);
470 }
471
472 getPostPassesForLayer (layer)
473 {
474 const fromLayer = this.normalizePostShaderList(layer.postShaders);
475 if (fromLayer.length)
476 { return fromLayer; }
477
478 // Back-compat: scene.postShaders apply to the default layer only.
479 if (layer.name === RenderLayer.DEFAULT_NAME)
480 { return this.normalizePostShaders(); }
481
482 return [];
483 }
484
485 draw ()
486 {
487 if (this.destroyed || !this.glContext)
488 { return; }
489
490 this.g_fixSize();
491
492 const gl = this.glContext;
493 const layers = this.renderLayers && this.renderLayers.length
494 ? this.renderLayers
495 : [new RenderLayer(RenderLayer.DEFAULT_NAME)];
496
497 // Canvas clear (background behind all layers).
498 gl.endOffscreenPass();
499 if (this.renderBackground)
500 {
501 gl.clear(
502 this.backgroundColor.r,
503 this.backgroundColor.g,
504 this.backgroundColor.b,
505 1
506 );
507 }
508 else
509 {
510 gl.clearTransparent();
511 }
512
513 this.#ensureDrawOrder();
514 const sortedActiveObjects = this._sortedActiveObjects;
515
516 // Bucket visible objects once so empty bloom layers can be skipped entirely.
517 const byLayer = Object.create(null);
518 for (let i = 0; i < sortedActiveObjects.length; i++)
519 {
520 const obj = sortedActiveObjects[i];
521 if (obj.destroyed || !obj.renderer || !obj.renderer.visible)
522 { continue; }
523
524 const name = obj.renderer.layerName;
525 let bucket = byLayer[name];
526 if (!bucket)
527 {
528 bucket = [];
529 byLayer[name] = bucket;
530 }
531
532 bucket.push(obj);
533 }
534
535 const builtins = {
536 u_resolution: [gl._lastWidth, gl._lastHeight],
537 u_time: this.postTime
538 };
539
540 for (let li = 0; li < layers.length; li++)
541 {
542 const renderLayer = layers[li];
543 const layerObjects = byLayer[renderLayer.name];
544 if (!layerObjects || !layerObjects.length)
545 { continue; }
546
547 gl.beginOffscreenPass();
548 gl.clearTransparent();
549
550 for (let i = 0; i < layerObjects.length; i++)
551 { layerObjects[i].draw(this.context); }
552
553 const postPasses = this.getPostPassesForLayer(renderLayer);
554 let texture = gl.colorTextures[0];
555
556 if (postPasses.length)
557 {
558 texture = gl.applyPostShaders(postPasses, builtins, { toCanvas: false });
559 }
560 else
561 {
562 gl.endOffscreenPass();
563 }
564
565 gl.blitToCanvas(texture, renderLayer.composite || "alpha");
566 }
567 }
568}