/* * AUTO-GENERATED FILE — DO NOT EDIT BY HAND. * * Built by glbuild.sh from the modular sources in this repository. * Make changes in the framework/ source tree, then rebuild. * Upstream: https://gitlab.com/Timfa/frameworkv3 */ /* * Start File: * framework/extensions/polyfills.js */ if (!Math.sign) { Math.sign = function (x) { x = +x; // convert to a number if (x === 0 || isNaN(x)) { return Number(x); } return x > 0 ? 1 : -1; }; } (function (e) { var t = function () { try { return !!Symbol.iterator; } catch (e) { return false; } }; var n = t(); var r = function (e) { var t = { next: function () { var t = e.shift(); return { done: t === void 0, value: t }; } }; if (n) { t[Symbol.iterator] = function () { return t; }; } return t; }; var i = function (e) { return encodeURIComponent(e).replace(/%20/g, "+"); }; var o = function (e) { return decodeURIComponent(e).replace(/\+/g, " "); }; var a = function () { var t = function (e) { Object.defineProperty(this, "_entries", { value: {} }); if (typeof e === "string") { if (e !== "") { e = e.replace(/^\?/, ""); var n = e.split("&"); var r; for (var i = 0; i < n.length; i++) { r = n[i].split("="); this.append(o(r[0]), r.length > 1 ? o(r[1]) : ""); } } } else if (e instanceof t) { var a = this; e.forEach(function (e, t) { a.append(e, t); }); } }; var a = t.prototype; a.append = function (e, t) { if (e in this._entries) { this._entries[e].push(t.toString()); } else { this._entries[e] = [t.toString()]; } }; a.delete = function (e) { delete this._entries[e]; }; a.get = function (e) { return e in this._entries ? this._entries[e][0] : null; }; a.getAll = function (e) { return e in this._entries ? this._entries[e].slice(0) : []; }; a.has = function (e) { return e in this._entries; }; a.set = function (e, t) { this._entries[e] = [t.toString()]; }; a.forEach = function (e, t) { var n; for (var r in this._entries) { if (this._entries.hasOwnProperty(r)) { n = this._entries[r]; for (var i = 0; i < n.length; i++) { e.call(t, n[i], r, this); } } } }; a.keys = function () { var e = []; this.forEach(function (t, n) { e.push(n); }); return r(e); }; a.values = function () { var e = []; this.forEach(function (t) { e.push(t); }); return r(e); }; a.entries = function () { var e = []; this.forEach(function (t, n) { e.push([n, t]); }); return r(e); }; if (n) { a[Symbol.iterator] = a.entries; } a.toString = function () { var e = []; this.forEach(function (t, n) { e.push(i(n) + "=" + i(t)); }); return e.join("&"); }; e.URLSearchParams = t; }; if (!("URLSearchParams" in e) || new URLSearchParams("?a=1").toString() !== "a=1") { a(); } })(typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : this); (function (e) { var t = function () { try { var e = new URL("b", "http://a"); e.pathname = "c%20d"; return e.href === "http://a/c%20d" && e.searchParams; } catch (e) { return false; } }; var n = function () { var t = e.URL; var n = function (e, t) { if (typeof e !== "string") {e = String(e);} var n = document.implementation.createHTMLDocument(""); window.doc = n; if (t) { var r = n.createElement("base"); r.href = t; n.head.appendChild(r); } var i = n.createElement("a"); i.href = e; n.body.appendChild(i); i.href = i.href; if (i.protocol === ":" || !/:/.test(i.href)) { throw new TypeError("Invalid URL"); } Object.defineProperty(this, "_anchorElement", { value: i }); }; var r = n.prototype; var i = function (e) { Object.defineProperty(r, e, { get: function () { return this._anchorElement[e]; }, set: function (t) { this._anchorElement[e] = t; }, enumerable: true }); };["hash", "host", "hostname", "port", "protocol", "search"].forEach(function (e) { i(e); }); Object.defineProperties(r, { toString: { get: function () { var e = this; return function () { return e.href; }; } }, href: { get: function () { return this._anchorElement.href.replace(/\?$/, ""); }, set: function (e) { this._anchorElement.href = e; }, enumerable: true }, pathname: { get: function () { return this._anchorElement.pathname.replace(/(^\/?)/, "/"); }, set: function (e) { this._anchorElement.pathname = e; }, enumerable: true }, origin: { get: function () { var e = { "http:": 80, "https:": 443, "ftp:": 21 }[this._anchorElement.protocol]; var t = this._anchorElement.port != e && this._anchorElement.port !== ""; return this._anchorElement.protocol + "//" + this._anchorElement.hostname + (t ? ":" + this._anchorElement.port : ""); }, enumerable: true }, password: { get: function () { return ""; }, set: function (e) { }, enumerable: true }, username: { get: function () { return ""; }, set: function (e) { }, enumerable: true }, searchParams: { get: function () { var e = new URLSearchParams(this.search); var t = this;["append", "delete", "set"].forEach(function (n) { var r = e[n]; e[n] = function () { r.apply(e, arguments); t.search = e.toString(); }; }); return e; }, enumerable: true } }); n.createObjectURL = function (e) { return t.createObjectURL.apply(t, arguments); }; n.revokeObjectURL = function (e) { return t.revokeObjectURL.apply(t, arguments); }; e.URL = n; }; if (!t()) { n(); } if (e.location !== void 0 && !("origin" in e.location)) { var r = function () { return e.location.protocol + "//" + e.location.hostname + (e.location.port ? ":" + e.location.port : ""); }; try { Object.defineProperty(e.location, "origin", { get: r, enumerable: true }); } catch (t) { setInterval(function () { e.location.origin = r(); }, 100); } } })(typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : this); /* * End File: * framework/extensions/polyfills.js */ /* * Start File: * framework/extensions/extentions.js */ /** * Extending exising functionality */ Array.prototype.remove = function (element) { var index = this.indexOf(element); if (index > -1) { this.splice(index, 1); } else { console.error("Element not part of array!", this, element); } }; Array.prototype.removeAt = function (index) { if (index > -1) { this.splice(index, 1); } }; Array.prototype.contains = function (element) { var index = this.indexOf(element); return index > -1; }; Math.clamp = function (number, min, max) { return Math.min(max, Math.max(min, number)); }; Math.randomRange = function (min, max) { return min + (Math.random() * (max - min)); }; Math.lerp = function (a, b, t) { return a + (b - a) * t; }; Array.prototype.random = function () { return this[Math.floor((Math.random() * this.length))]; }; /* * End File: * framework/extensions/extentions.js */ /* * Start File: * framework/extensions/thirdparty.js */ //TWEENJS var TWEEN = TWEEN || function () { var n = []; return { getAll: function () { return n; }, removeAll: function () { n = []; }, add: function (t) { n.push(t); }, remove: function (t) { var r = n.indexOf(t); -1 !== r && n.splice(r, 1); }, update: function (t, r) { if (0 === n.length) {return !1;} var i = 0; for (t = void 0 !== t ? t : TWEEN.now(); i < n.length;){n[i].update(t) || r ? i++ : n.splice(i, 1);} return !0; } }; }(); !function () { void 0 === this.window && void 0 !== this.process ? TWEEN.now = function () { var n = process.hrtime(); return 1e3 * n[0] + n[1] / 1e3; } : void 0 !== this.window && void 0 !== window.performance && void 0 !== window.performance.now ? TWEEN.now = window.performance.now.bind(window.performance) : void 0 !== Date.now ? TWEEN.now = Date.now : TWEEN.now = function () { return (new Date).getTime(); }; }(), TWEEN.Tween = function (n) { var t = n, r = {}, i = {}, o = {}, u = 1e3, e = 0, a = !1, f = !1, c = !1, s = 0, h = null, l = TWEEN.Easing.Linear.None, E = TWEEN.Interpolation.Linear, p = [], d = null, v = !1, w = null, I = null, M = null, C = null, S = null, ST = null; for (var T in n) {r[T] = parseFloat(n[T], 10);} this.to = function (n, t) { return void 0 !== t && (u = t), i = n, this; }, this.start = function (n) { TWEEN.add(this), f = !0, v = !1, h = void 0 !== n ? n : TWEEN.now(), h += s; for (var u in i) { if (i[u] instanceof Array) { if (0 === i[u].length) {continue;} i[u] = [t[u]].concat(i[u]); } void 0 !== r[u] && (r[u] = t[u], r[u] instanceof Array == !1 && (r[u] *= 1), o[u] = r[u] || 0); } return this; }, this.stop = function () { return f ? (TWEEN.remove(this), f = !1, null !== M && M.call(S), this.stopChainedTweens(), this) : this; }, this.stopChainedTweens = function () { for (var n = 0, t = p.length; t > n; n++){p[n].stop();} }, this.delay = function (n) { return s = n, this; }, this.repeat = function (n) { return e = n, this; }, this.yoyo = function (n) { return a = n, this; }, this.easing = function (n) { return l = n, this; }, this.interpolation = function (n) { return E = n, this; }, this.chain = function () { return p = arguments, this; }, this.onStart = function (n, c) { return d = n, ST = c, this; }, this.onUpdate = function (n) { return w = n, this; }, this.onComplete = function (n, c) { return I = n, C = c, this; }, this.onStop = function (n, c) { return M = n, S = c, this; }, this.update = function (n) { var f, M, T; if (h > n) {return !0;} v === !1 && (null !== d && d.call(ST), v = !0), M = (n - h) / u, M = M > 1 ? 1 : M, T = l(M); for (f in i) {if (void 0 !== r[f]) { var N = r[f] || 0, W = i[f]; W instanceof Array ? t[f] = E(W, T) : ("string" == typeof W && (W = "+" === W.charAt(0) || "-" === W.charAt(0) ? N + parseFloat(W, 10) : parseFloat(W, 10)), "number" == typeof W && (t[f] = N + (W - N) * T)); }} if (null !== w && w.call(t, T), 1 === M) { if (e > 0) { isFinite(e) && e--; for (f in o) { if ("string" == typeof i[f] && (o[f] = o[f] + parseFloat(i[f], 10)), a) { var O = o[f]; o[f] = i[f], i[f] = O; } r[f] = o[f]; } return a && (c = !c), h = n + s, !0; } null !== I && I.call(C); for (var m = 0, g = p.length; g > m; m++){p[m].start(h + u);} return !1; } return !0; }; }, TWEEN.Easing = { Linear: { None: function (n) { return n; } }, Quadratic: { In: function (n) { return n * n; }, Out: function (n) { return n * (2 - n); }, InOut: function (n) { return (n *= 2) < 1 ? .5 * n * n : -.5 * (--n * (n - 2) - 1); } }, Cubic: { In: function (n) { return n * n * n; }, Out: function (n) { return --n * n * n + 1; }, InOut: function (n) { return (n *= 2) < 1 ? .5 * n * n * n : .5 * ((n -= 2) * n * n + 2); } }, Quartic: { In: function (n) { return n * n * n * n; }, Out: function (n) { return 1 - --n * n * n * n; }, InOut: function (n) { return (n *= 2) < 1 ? .5 * n * n * n * n : -.5 * ((n -= 2) * n * n * n - 2); } }, Quintic: { In: function (n) { return n * n * n * n * n; }, Out: function (n) { return --n * n * n * n * n + 1; }, InOut: function (n) { return (n *= 2) < 1 ? .5 * n * n * n * n * n : .5 * ((n -= 2) * n * n * n * n + 2); } }, Sinusoidal: { In: function (n) { return 1 - Math.cos(n * Math.PI / 2); }, Out: function (n) { return Math.sin(n * Math.PI / 2); }, InOut: function (n) { return .5 * (1 - Math.cos(Math.PI * n)); } }, Exponential: { In: function (n) { return 0 === n ? 0 : Math.pow(1024, n - 1); }, Out: function (n) { return 1 === n ? 1 : 1 - Math.pow(2, -10 * n); }, InOut: function (n) { return 0 === n ? 0 : 1 === n ? 1 : (n *= 2) < 1 ? .5 * Math.pow(1024, n - 1) : .5 * (-Math.pow(2, -10 * (n - 1)) + 2); } }, Circular: { In: function (n) { return 1 - Math.sqrt(1 - n * n); }, Out: function (n) { return Math.sqrt(1 - --n * n); }, InOut: function (n) { return (n *= 2) < 1 ? -.5 * (Math.sqrt(1 - n * n) - 1) : .5 * (Math.sqrt(1 - (n -= 2) * n) + 1); } }, Elastic: { In: function (n) { return 0 === n ? 0 : 1 === n ? 1 : -Math.pow(2, 10 * (n - 1)) * Math.sin(5 * (n - 1.1) * Math.PI); }, Out: function (n) { return 0 === n ? 0 : 1 === n ? 1 : Math.pow(2, -10 * n) * Math.sin(5 * (n - .1) * Math.PI) + 1; }, InOut: function (n) { return 0 === n ? 0 : 1 === n ? 1 : (n *= 2, 1 > n ? -.5 * Math.pow(2, 10 * (n - 1)) * Math.sin(5 * (n - 1.1) * Math.PI) : .5 * Math.pow(2, -10 * (n - 1)) * Math.sin(5 * (n - 1.1) * Math.PI) + 1); } }, Back: { In: function (n) { var t = 1.70158; return n * n * ((t + 1) * n - t); }, Out: function (n) { var t = 1.70158; return --n * n * ((t + 1) * n + t) + 1; }, InOut: function (n) { var t = 2.5949095; return (n *= 2) < 1 ? .5 * (n * n * ((t + 1) * n - t)) : .5 * ((n -= 2) * n * ((t + 1) * n + t) + 2); } }, Bounce: { In: function (n) { return 1 - TWEEN.Easing.Bounce.Out(1 - n); }, Out: function (n) { return 1 / 2.75 > n ? 7.5625 * n * n : 2 / 2.75 > n ? 7.5625 * (n -= 1.5 / 2.75) * n + .75 : 2.5 / 2.75 > n ? 7.5625 * (n -= 2.25 / 2.75) * n + .9375 : 7.5625 * (n -= 2.625 / 2.75) * n + .984375; }, InOut: function (n) { return .5 > n ? .5 * TWEEN.Easing.Bounce.In(2 * n) : .5 * TWEEN.Easing.Bounce.Out(2 * n - 1) + .5; } } }, TWEEN.Interpolation = { Linear: function (n, t) { var r = n.length - 1, i = r * t, o = Math.floor(i), u = TWEEN.Interpolation.Utils.Linear; return 0 > t ? u(n[0], n[1], i) : t > 1 ? u(n[r], n[r - 1], r - i) : u(n[o], n[o + 1 > r ? r : o + 1], i - o); }, Bezier: function (n, t) { for (var r = 0, i = n.length - 1, o = Math.pow, u = TWEEN.Interpolation.Utils.Bernstein, e = 0; i >= e; e++){r += o(1 - t, i - e) * o(t, e) * n[e] * u(i, e);} return r; }, CatmullRom: function (n, t) { var r = n.length - 1, i = r * t, o = Math.floor(i), u = TWEEN.Interpolation.Utils.CatmullRom; return n[0] === n[r] ? (0 > t && (o = Math.floor(i = r * (1 + t))), u(n[(o - 1 + r) % r], n[o], n[(o + 1) % r], n[(o + 2) % r], i - o)) : 0 > t ? n[0] - (u(n[0], n[0], n[1], n[1], -i) - n[0]) : t > 1 ? n[r] - (u(n[r], n[r], n[r - 1], n[r - 1], i - r) - n[r]) : u(n[o ? o - 1 : 0], n[o], n[o + 1 > r ? r : o + 1], n[o + 2 > r ? r : o + 2], i - o); }, Utils: { Linear: function (n, t, r) { return (t - n) * r + n; }, Bernstein: function (n, t) { var r = TWEEN.Interpolation.Utils.Factorial; return r(n) / r(t) / r(n - t); }, Factorial: function () { var n = [1]; return function (t) { var r = 1; if (n[t]) {return n[t];} for (var i = t; i > 1; i--){r *= i;} return n[t] = r, r; }; }(), CatmullRom: function (n, t, r, i, o) { var u = .5 * (r - n), e = .5 * (i - t), a = o * o, f = o * a; return (2 * t - 2 * r + u + e) * f + (-3 * t + 3 * r - 2 * u - e) * a + u * o + t; } } }, function (n) { "function" == typeof define && define.amd ? define([], function () { return TWEEN; }) : "undefined" != typeof module && "object" == typeof exports ? module.exports = TWEEN : void 0 !== n && (n.TWEEN = TWEEN); }(this); /* * End File: * framework/extensions/thirdparty.js */ /* * Start File: * framework/util/vector.js */ class vector { x = 0; y = 0; constructor (x, y) { this.x = x; this.y = y; } get length () { return Math.sqrt((this.x * this.x) + (this.y * this.y)); } get lengthSq () { return (this.x * this.x) + (this.y * this.y); } getLength () { return Math.sqrt((this.x * this.x) + (this.y * this.y)); } toAngle () { let angle = (Math.atan2(this.y, this.x) * 180 / Math.PI) + 90; if (angle < 0) {angle += 360;} return angle; } static fromAngle (angle) { angle = 360 - ((angle + 180) % 360); angle = (angle / 180) * Math.PI; return new vector(Math.sin(angle), Math.cos(angle)); } normalize () { var newVector = this.getCopy(); var length = newVector.length; if (length != 0) { newVector.x /= length; newVector.y /= length; } return newVector; } lerpTo (otherVector, t) { var delta = otherVector.subtract(this); return this.add(delta.stretch(t)); } lerpToInto (otherVector, t, out) { out.x = this.x + (otherVector.x - this.x) * t; out.y = this.y + (otherVector.y - this.y) * t; return out; } distanceToSq (otherVector) { var dX = this.x - otherVector.x; var dY = this.y - otherVector.y; return (dX * dX) + (dY * dY); } distanceTo (otherVector) { return Math.sqrt(this.distanceToSq(otherVector)); } add (otherVector) { var newVector = this.getCopy(); newVector.x += otherVector.x; newVector.y += otherVector.y; return newVector; } subtract (otherVector) { var newVector = this.getCopy(); newVector.x -= otherVector.x; newVector.y -= otherVector.y; return newVector; } multiply (otherVector) { var newVector = this.getCopy(); newVector.x *= otherVector.x; newVector.y *= otherVector.y; return newVector; } divide (otherVector) { var newVector = this.getCopy(); newVector.x /= otherVector.x; newVector.y /= otherVector.y; return newVector; } stretch (length) { var newVector = this.getCopy(); newVector.x *= length; newVector.y *= length; return newVector; } rotate (degrees) { var ca = Math.cos(degrees * (Math.PI / 180)); var sa = Math.sin(degrees * (Math.PI / 180)); return new vector(ca * this.x - sa * this.y, sa * this.x + ca * this.y); } deltaAngle (otherVector) { var a = this.toAngle() * (Math.PI / 180); var b = otherVector.toAngle() * (Math.PI / 180); return Math.atan2(Math.sin(a - b), Math.cos(a - b)) * (180 / Math.PI); } cross (otherVector) { return this.x * otherVector.y - this.y * otherVector.x; } getCopy () { return new vector(this.x, this.y); } }; /* * End File: * framework/util/vector.js */ /* * Start File: * framework/util/ease.js */ //ease functions var ease = { // // Basic ease functions // easeConstant: function (time, begin, change, duration) { "use strict"; return begin; }, easeLinear: function (time, begin, change, duration) { "use strict"; var val = time / duration; return begin + change * val; }, easeInPower: function (time, begin, change, duration, power) { "use strict"; var val; if (power === undefined) { power = 3; } val = Math.pow(time / duration, power); return begin + change * val; }, easeOutPower: function (time, begin, change, duration, power) { "use strict"; var val = tbEase.easeInPower(duration - time, 1, -1, duration, power); return begin + change * val; }, easeInOutPower: function (time, begin, change, duration, power) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInPower(time, 0, 0.5, duration / 2, power); } else { val = tbEase.easeInPower(duration - time, 1, -0.5, duration / 2, power); } return begin + change * val; }, easeOutInPower: function (time, begin, change, duration, power) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInPower(duration / 2 - time, 0.5, -0.5, duration / 2, power); } else { val = tbEase.easeInPower(time - duration / 2, 0.5, 0.5, duration / 2, power); } return begin + change * val; }, easeInQuadratic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInPower(time, begin, change, duration, 2); }, easeOutQuadratic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutPower(time, begin, change, duration, 2); }, easeInOutQuadratic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInOutPower(time, begin, change, duration, 2); }, easeOutInQuadratic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutInPower(time, begin, change, duration, 2); }, easeInCubic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInPower(time, begin, change, duration, 3); }, easeOutCubic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutPower(time, begin, change, duration, 3); }, easeInOutCubic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInOutPower(time, begin, change, duration, 3); }, easeOutInCubic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutInPower(time, begin, change, duration, 3); }, easeInQuartic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInPower(time, begin, change, duration, 4); }, easeOutQuartic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutPower(time, begin, change, duration, 4); }, easeInOutQuartic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInOutPower(time, begin, change, duration, 4); }, easeOutInQuartic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutInPower(time, begin, change, duration, 4); }, easeInQuintic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInPower(time, begin, change, duration, 5); }, easeOutQuintic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutPower(time, begin, change, duration, 5); }, easeInOutQuintic: function (time, begin, change, duration) { "use strict"; return tbEase.easeInOutPower(time, begin, change, duration, 5); }, easeOutInQuintic: function (time, begin, change, duration) { "use strict"; return tbEase.easeOutInPower(time, begin, change, duration, 5); }, easeInExponential: function (time, begin, change, duration, power) { "use strict"; var val, base; if (power === undefined) { power = 8; } base = Math.pow(2, -power); // The exponential function will not cover the whole range from 0-1 so we must correct it val = (Math.pow(2, power * time / duration - power) - base) / (1 - base); return begin + change * val; }, easeOutExponential: function (time, begin, change, duration, power) { "use strict"; var val = tbEase.easeInExponential(duration - time, 1, -1, duration, power); return begin + change * val; }, easeInOutExponential: function (time, begin, change, duration, power) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInExponential(time, 0, 0.5, duration / 2, power); } else { val = tbEase.easeInExponential(duration - time, 1, -0.5, duration / 2, power); } return begin + change * val; }, easeOutInExponential: function (time, begin, change, duration, power) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInExponential(duration / 2 - time, 0.5, -0.5, duration / 2, power); } else { val = tbEase.easeInExponential(time - duration / 2, 0.5, 0.5, duration / 2, power); } return begin + change * val; }, easeInSine: function (time, begin, change, duration) { "use strict"; var val = 1 - Math.cos(time / duration * Math.PI / 2); return begin + change * val; }, easeOutSine: function (time, begin, change, duration) { "use strict"; var val = tbEase.easeInSine(duration - time, 1, -1, duration); return begin + change * val; }, easeInOutSine: function (time, begin, change, duration) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInSine(time, 0, 0.5, duration / 2); } else { val = tbEase.easeInSine(duration - time, 1, -0.5, duration / 2); } return begin + change * val; }, easeOutInSine: function (time, begin, change, duration) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInSine(duration / 2 - time, 0.5, -0.5, duration / 2); } else { val = tbEase.easeInSine(time - duration / 2, 0.5, 0.5, duration / 2); } return begin + change * val; }, easeInCircular: function (time, begin, change, duration) { "use strict"; var val = 1 - Math.sqrt(1 - Math.pow(time / duration, 2)); return begin + change * val; }, easeOutCircular: function (time, begin, change, duration) { "use strict"; var val = tbEase.easeInCircular(duration - time, 1, -1, duration); return begin + change * val; }, easeInOutCircular: function (time, begin, change, duration) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInCircular(time, 0, 0.5, duration / 2); } else { val = tbEase.easeInCircular(duration - time, 1, -0.5, duration / 2); } return begin + change * val; }, easeOutInCircular: function (time, begin, change, duration) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInCircular(duration / 2 - time, 0.5, -0.5, duration / 2); } else { val = tbEase.easeInCircular(time - duration / 2, 0.5, 0.5, duration / 2); } return begin + change * val; }, easeInElastic: function (time, begin, change, duration, oscillations, stiffness) { "use strict"; var val; if (oscillations === undefined) { oscillations = 3; } if (stiffness === undefined) { stiffness = 8; } val = Math.sin((1 - time / duration) * 2 * Math.PI * oscillations + Math.PI / 2); // Create the correct sign val *= tbEase.easeInExponential(time, 0, 1, duration, stiffness); // Multiply with an exponential ease in return begin + change * val; }, easeOutElastic: function (time, begin, change, duration, oscillations, stiffness) { "use strict"; var val = tbEase.easeInElastic(duration - time, 1, -1, duration, oscillations, stiffness); return begin + change * val; }, easeInOutElastic: function (time, begin, change, duration, oscillations, stiffness) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInElastic(time, 0, 0.5, duration / 2, oscillations, stiffness); } else { val = tbEase.easeInElastic(duration - time, 1, -0.5, duration / 2, oscillations, stiffness); } return begin + change * val; }, easeOutInElastic: function (time, begin, change, duration, oscillations, stiffness) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInElastic(duration / 2 - time, 0.5, -0.5, duration / 2, oscillations, stiffness); } else { val = tbEase.easeInElastic(time - duration / 2, 0.5, 0.5, duration / 2, oscillations, stiffness); } return begin + change * val; }, easeInOvershoot: function (time, begin, change, duration, overshoot) { "use strict"; var val; if (overshoot === undefined) { overshoot = 1.70158; } val = (1 + overshoot) * Math.pow(time / duration, 3) - overshoot * Math.pow(time / duration, 2); return begin + change * val; }, easeOutOvershoot: function (time, begin, change, duration, overshoot) { "use strict"; var val = tbEase.easeInOvershoot(duration - time, 1, -1, duration, overshoot); return begin + change * val; }, easeInOutOvershoot: function (time, begin, change, duration, overshoot) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInOvershoot(time, 0, 0.5, duration / 2, overshoot); } else { val = tbEase.easeInOvershoot(duration - time, 1, -0.5, duration / 2, overshoot); } return begin + change * val; }, easeOutInOvershoot: function (time, begin, change, duration, overshoot) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInOvershoot(duration / 2 - time, 0.5, -0.5, duration / 2, overshoot); } else { val = tbEase.easeInOvershoot(time - duration / 2, 0.5, 0.5, duration / 2, overshoot); } return begin + change * val; }, easeInBounce: function (time, begin, change, duration, number, factor) { "use strict"; var bounces, i, w, width, height, val; // Correct the arguments if (number === undefined) { number = 4; } if (factor === undefined) { factor = 2; } else { factor = Math.sqrt(factor); } // Create the list of bounces bounces = [1]; width = 1; for (i = 1; i < number; i += 1) { bounces.push(bounces[i - 1] * factor); width += bounces[i]; } // Compute total size width -= bounces[number - 1] / 2; // We don't use the last half bounce height = Math.pow(bounces[number - 1], 2); time = time / duration * width; // Find the correct bounce w = 0; for (i = 0; i < number; i += 1) { if (time > bounces[i]) { time -= bounces[i]; } else { w = bounces[i]; break; } } // Now compute the value val = -4 * Math.pow(time - w / 2, 2) + w * w; return begin + change * val / height; }, easeOutBounce: function (time, begin, change, duration, number, factor) { "use strict"; var val = tbEase.easeInBounce(duration - time, 1, -1, duration, number, factor); return begin + change * val; }, easeInOutBounce: function (time, begin, change, duration, number, factor) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInBounce(time, 0, 0.5, duration / 2, number, factor); } else { val = tbEase.easeInBounce(duration - time, 1, -0.5, duration / 2, number, factor); } return begin + change * val; }, easeOutInBounce: function (time, begin, change, duration, number, factor) { "use strict"; var val; if (time < duration / 2) { val = tbEase.easeInBounce(duration / 2 - time, 0.5, -0.5, duration / 2, number, factor); } else { val = tbEase.easeInBounce(time - duration / 2, 0.5, 0.5, duration / 2, number, factor); } return begin + change * val; } }; // Methods above call tbEase.*; alias so composed easings resolve at runtime. var tbEase = ease; /* * End File: * framework/util/ease.js */ /* * Start File: * framework/util/timingUtil.js */ /** /* Timing utility /*/ var timingUtil = { delayUntilCondition: function (conditionFunction, conditionContext, callback, context, interval) { interval = interval || 1; if (conditionFunction.call(conditionContext)) { callback.call(context); } else { setTimeout(function () { timingUtil.delayUntilCondition(conditionFunction, conditionContext, callback, context, interval); }, interval); } }, delayUntilNextFrame: function (callback, context) { requestAnimationFrame(function () { callback.call(context); }); }, delay: function (milliseconds, callback, context) { return setTimeout(function () { callback.call(context); }, milliseconds); }, stop: function (timer) { clearTimeout(timer); }, repeat: function (milliseconds, callback, context) { return setInterval(function () { callback.call(context); }, milliseconds); } }; // Historical alias — some call sites used TimingUtil casing. var TimingUtil = timingUtil; /* * End File: * framework/util/timingUtil.js */ /* * Start File: * framework/util/signal.js */ // Basic event listeners, modeled after Phaser Signals class Signal { listeners = []; dispatch () { for (var i = 0; i < this.listeners.length; i++) { this.listeners[i].callback.apply(this.listeners[i].context, arguments); } for (var i = this.listeners.length - 1; i >= 0; i--) { if (this.listeners[i].once) { this.listeners.splice(i, 1); } } } add (callback, context, once) { if (!this.contains(callback, context)) { this.listeners.push({ callback: callback, context: context, once: once }); } } addOnce (callback, context) { this.add(callback, context, true); } contains (callback, context) { for (var i = this.listeners.length - 1; i >= 0; i--) { if (this.listeners[i].callback === callback && this.listeners[i].context === context) { return true; } } return false; } remove (callback, context) { for (var i = this.listeners.length - 1; i >= 0; i--) { if (this.listeners[i].callback === callback && this.listeners[i].context === context) { this.listeners.splice(i, 1); break; } } } removeAll () { this.listeners = []; } } /* * End File: * framework/util/signal.js */ /* * Start File: * framework/util/cookie.js */ var CookieManager = { setCookie: function (cname, cvalue, exdays = 365) { const d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); const expires = "expires=" + d.toUTCString(); const name = encodeURIComponent(cname); const value = encodeURIComponent(cvalue); document.cookie = name + "=" + value + ";" + expires + ";path=/;SameSite=Lax"; }, getCookie: function (cname) { const name = encodeURIComponent(cname) + "="; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return decodeURIComponent(c.substring(name.length, c.length)); } } return ""; }, deleteCookie: function (cname) { document.cookie = encodeURIComponent(cname) + "=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;SameSite=Lax"; } }; /* * End File: * framework/util/cookie.js */ /* * Start File: * framework/util/urlParams.js */ var UrlParams = { get: function (key) { var url_string = window.location.href; var url = new URL(url_string); var c = url.searchParams.get(key); return c; }, set: function (key, value) { var url_string = window.location.href; var url = new URL(url_string); url.searchParams.set(key, value); // replaceState avoids flooding history when params change often. window.history.replaceState(null, "", url); } }; /* * End File: * framework/util/urlParams.js */ /* * Start File: * framework/util/input.js */ var GameInput = { keys: {}, g_keyStatus: [], g_pKeyStatus: [], g_pressKeyStatus: [], g_ppressKeyStatus: [], g_pressBlacklist: [], g_mouseDown: false, g_mouseDownThisFrame: false, g_altMouseDown: false, g_altMouseDownThisFrame: false, g_middleMouseDown: false, g_middleMouseDownThisFrame: false, trueMousePosition: null, mousePosition: null, MouseButtons: { Left: 0, Middle: 1, Right: 2 }, g_init: function () { GameInput.trueMousePosition = new vector(0, 0); GameInput.mousePosition = new vector(0, 0); document.onkeydown = GameInput.g_setKeyStatus; document.onkeyup = GameInput.g_setKeyStatus; document.oncontextmenu = function () { return false; }; document.onmousedown = function (e) { switch (e.button) { case GameInput.MouseButtons.Left: GameInput.g_mouseDownThisFrame = true; break; case GameInput.MouseButtons.Middle: GameInput.g_middleMouseDownThisFrame = true; break; case GameInput.MouseButtons.Right: GameInput.g_altMouseDownThisFrame = true; break; } }; document.onmouseup = function (e) { switch (e.button) { case GameInput.MouseButtons.Left: GameInput.g_mouseDownThisFrame = false; GameInput.g_mouseDown = false; break; case GameInput.MouseButtons.Middle: GameInput.g_middleMouseDownThisFrame = false; GameInput.g_middleMouseDown = false; break; case GameInput.MouseButtons.Right: GameInput.g_altMouseDownThisFrame = false; GameInput.g_altMouseDown = false; break; } }; document.onmousemove = function (e) { if (!GameInput.trueMousePosition) { GameInput.trueMousePosition = new vector(); } GameInput.trueMousePosition.x = e.x; GameInput.trueMousePosition.y = e.y; }; var el = document.getElementsByTagName("body")[0]; el.addEventListener("touchstart", function () { GameInput.g_mouseDownThisFrame = true; }, false); el.addEventListener("touchend", function () { GameInput.g_mouseDownThisFrame = false; GameInput.g_mouseDown = false; }, false); el.addEventListener("touchcancel", function () { GameInput.g_mouseDownThisFrame = false; GameInput.g_mouseDown = false; }, false); el.addEventListener("touchmove", function () { return false; }, false); }, g_setKeyStatus: function (e) { GameInput.keys[e.key] = e.which; GameInput.g_keyStatus[e.which] = (e.type == "keydown"); if (!GameInput.g_pressBlacklist[e.which]) { GameInput.g_pressKeyStatus[e.which] = (e.type == "keydown"); } GameInput.g_pressBlacklist[e.which] = (e.type == "keydown"); //only allow single presses if key has been released once }, g_updateKeys: function () { GameInput.mousePosition = GameInput.trueMousePosition; // Snapshot previous frame — a bare assignment aliases the live array. GameInput.g_pKeyStatus = GameInput.g_keyStatus.slice(); GameInput.g_ppressKeyStatus = GameInput.g_pressKeyStatus; GameInput.g_pressKeyStatus = []; if (GameInput.g_mouseDown && GameInput.g_mouseDownThisFrame) { GameInput.g_mouseDownThisFrame = false; } if (GameInput.g_mouseDownThisFrame && !GameInput.g_mouseDown) { GameInput.g_mouseDown = true; } if (GameInput.g_altMouseDown && GameInput.g_altMouseDownThisFrame) { GameInput.g_altMouseDownThisFrame = false; } if (GameInput.g_altMouseDownThisFrame && !GameInput.g_altMouseDown) { GameInput.g_altMouseDown = true; } if (GameInput.g_middleMouseDown && GameInput.g_middleMouseDownThisFrame) { GameInput.g_middleMouseDownThisFrame = false; } if (GameInput.g_middleMouseDownThisFrame && !GameInput.g_middleMouseDown) { GameInput.g_middleMouseDown = true; } }, isPressed: function (keyCode) { if (GameInput.g_ppressKeyStatus[keyCode] == null) { return false; } else { return GameInput.g_ppressKeyStatus[keyCode]; } }, isHeld: function (keyCode) { if (GameInput.g_pKeyStatus[keyCode] == null) { return false; } else { return GameInput.g_pKeyStatus[keyCode]; } }, _pressedState: { left: false, middle: false, right: false }, _heldState: { left: false, middle: false, right: false }, mousePressed: function (btn) { switch (btn) { case GameInput.MouseButtons.Left: return GameInput.g_mouseDownThisFrame; case GameInput.MouseButtons.Middle: return GameInput.g_middleMouseDownThisFrame; case GameInput.MouseButtons.Right: return GameInput.g_altMouseDownThisFrame; } const state = GameInput._pressedState; state.left = GameInput.g_mouseDownThisFrame; state.middle = GameInput.g_middleMouseDownThisFrame; state.right = GameInput.g_altMouseDownThisFrame; return state; }, mouseHeld: function (btn) { switch (btn) { case GameInput.MouseButtons.Left: return GameInput.g_mouseDown; case GameInput.MouseButtons.Middle: return GameInput.g_middleMouseDown; case GameInput.MouseButtons.Right: return GameInput.g_altMouseDown; } const state = GameInput._heldState; state.left = GameInput.g_mouseDown; state.middle = GameInput.g_middleMouseDown; state.right = GameInput.g_altMouseDown; return state; } };// /* * End File: * framework/util/input.js */ /* * Start File: * framework/util/audio.js */ var GameAudio = { active: false, sounds: {}, path: "", volume: 1, multiplay: true, supported: ["mp3", "ogg", "wav", "mp4", "aac"], init: function (collection, containingFolder) { console.log("GAME: Loading sounds. (Note: Only supported from online-source, will fail when executed on local files.)"); try { if (typeof Audio !== "function" && typeof Audio !== "object") { throw new Error("HTML5 Audio is not supported in this browser"); } if (containingFolder == null) { containingFolder = ""; } if (containingFolder != "") { containingFolder += "/"; } this.path = containingFolder; this.sounds = {}; for (var i = 0; i < collection.length; i++) { var entry = collection[i]; var name = entry.name; if (!name) { continue; } var audio = new Audio(); audio.preload = "auto"; audio.volume = entry.volume != null ? entry.volume : this.volume; audio.src = this.resolveUrl(entry); // Kick off preload without blocking init. audio.load(); this.sounds[name] = audio; } this.active = true; } catch (err) { this.active = false; console.log("GAME: ERROR: Sounds could not be loaded. Sound will not be available."); } }, resolveUrl: function (entry) { if (entry.url) { return entry.url; } var ext = entry.ext || this.pickExtension(); if (ext.charAt(0) === ".") { ext = ext.substring(1); } return this.path + entry.name + "." + ext; }, pickExtension: function () { var probe = new Audio(); for (var i = 0; i < this.supported.length; i++) { var ext = this.supported[i]; var mime = this.mimeFor(ext); if (mime && probe.canPlayType(mime)) { return ext; } } return "mp3"; }, mimeFor: function (ext) { switch (ext) { case "mp3": return "audio/mpeg"; case "ogg": return "audio/ogg"; case "wav": return "audio/wav"; case "mp4": case "aac": return 'audio/mp4; codecs="mp4a.40.2"'; default: return ""; } }, play: function (name) { if (!this.active) { return; } var source = this.sounds[name]; if (!source) { console.warn("GAME: Sound '" + name + "' was not loaded."); return; } var clip = this.multiplay ? source.cloneNode() : source; clip.volume = source.volume; if (!this.multiplay) { try { clip.currentTime = 0; } catch (err) { /* ignore seek errors before load */ } } var playPromise = clip.play(); if (playPromise && typeof playPromise.catch === "function") { playPromise.catch(function () { // Autoplay policies can reject until a user gesture; ignore. }); } } }; /* * End File: * framework/util/audio.js */ /* * Start File: * framework/util/ray.js */ class Ray { static Cast (scene, origin, direction, maxLength = -1) { direction = direction.normalize(); const hits = []; // {hitObj, hitPoint} for (var i = 0; i < scene.activeObjects.length; i++) { let castAngle = direction.toAngle(); if (scene.activeObjects[i] != this && scene.activeObjects[i].collider.enabled) { var hw = scene.activeObjects[i].transform.size.x / 2; var hh = scene.activeObjects[i].transform.size.y / 2; const points = [ new vector(scene.activeObjects[i].transform.position.x - hw, scene.activeObjects[i].transform.position.y - hh), new vector(scene.activeObjects[i].transform.position.x + hw, scene.activeObjects[i].transform.position.y - hh), new vector(scene.activeObjects[i].transform.position.x - hw, scene.activeObjects[i].transform.position.y + hh), new vector(scene.activeObjects[i].transform.position.x + hw, scene.activeObjects[i].transform.position.y + hh) ]; points.sort((p1, p2) => p1.subtract(origin).length - p2.subtract(origin).length).pop(); for (let p = 0; p < points.length; p++) { const point = points[p]; const deltaDistance = point.subtract(origin).length; if (deltaDistance > maxLength && maxLength > 0) { continue; } const stretched = direction.stretch(Math.min(deltaDistance, maxLength > 0 ? maxLength : deltaDistance)); const calcPoint = origin.add(stretched); if (scene.activeObjects[i].collider.isInBounds(calcPoint)) { //determine in between which vector angles ray is var angles = points.map(p => Ray.mapPointToPointAndAngle(p, origin)); pointLoop: for (let pa = 0; pa < angles.length; pa++) { for (let pb = 0; pb < angles.length; pb++) { if (angles[pa].angle - angles[pb].angle > 270 || angles[pb].angle - angles[pa].angle > 270) { castAngle = (castAngle + 180) % 360; angles.forEach(pIn => pIn.angle = (pIn.angle + 180) % 360); break pointLoop; } } } angles = angles.sort((a, b) => b.angle - a.angle); if (angles[1].length > angles[0].length && angles[1].length > angles[2].length) { //only one face can be hit at this time, which is between angles[0] and angles[2] angles.removeAt(1); //remove the center, connecting to the un-hittable face } else { //one of two faces can be hit at this time, either angles[0]-angles[1] or angles[1]-angles[2] (castAngle > angles[1].angle) ? angles.pop() : angles.shift(); //figure out on which side we are, and remove the furthest } //calc % of angle in relation to the angles it is between const smallAngle = Math.min(angles[1].angle, angles[0].angle); const percent = (castAngle - smallAngle) / (Math.max(angles[1].angle, angles[0].angle) - smallAngle); const hitPoint = angles[1].point.lerpTo(angles[0].point, percent); hits.push({ hitObj: scene.activeObjects[i], hitPoint: hitPoint, length: hitPoint.subtract(origin).length }); break; } } } } if (hits.length === 0) { return undefined; } let shortest = hits[0]; for (let i = 1; i < hits.length; i++) { if (hits[i].length < shortest.length) { shortest = hits[i]; } } return shortest; } static mapPointToPointAndAngle (point, origin) { const delta = point.subtract(origin); return { point: point, angle: delta.toAngle(), length: delta.length }; } } /* * End File: * framework/util/ray.js */ /* * Start File: * framework/util/quadTree.js */ /** * Quadtree is a data-structure that contains a root node, and child nodes up to a defined depth. These nodes can be considered 'buckets' that can hold up to X objects. * When that number is exceeded (and the maximum depth is not yet reached), the node will split up into 4 separate nodes * (top left, top right, bottom left, bottom right), * dividing up the objects into the correct quadrant based on their location. * */ class QuadTree { constructor (width, height, maxDepth = 7, bucketSize = 30) { this.root = new Node(0, 0, width, height, 0, null, "", this); this.maxDepth = maxDepth; this.bucketSize = bucketSize; this.width = width; this.height = height; // Reused across queries (results are valid until the next query). this._queryNodes = []; this._queryResult = []; this._queryScored = []; } /** * Adds object to the quadtree. if the amount of objects in the target node is higher than * the permitted size, it divides up into 4 new nodes. Contents of this node is then divided up. * @param {GameObject} object * @returns {void} */ add (object) { let dirOfOob = this.outOfBounds(object); while (dirOfOob) { this.embiggen(dirOfOob); dirOfOob = this.outOfBounds(object); } // Node.add may split and move the object into a descendant leaf // (divide sets object.node). Otherwise assign the leaf we inserted into. const node = this.findNodeFromRoot(object); node.add(object); if (!object.node) { object.node = node; } } /** * Removes object from quadtree. If the total amount of objects held by siblings is lower than the maximum size, * a cleanup phase is triggered to remove the objects from siblings, moved up to parent node * @param {GameObject} object * @returns {void} */ remove (object) { const node = object.node || (!this.root.hasChildren ? this.root : null); if (node && node.remove(object)) { object.node = null; } } /** * Retrieves objects within range of a given position. Sorted by distance from position * * @param {vector} position * @param {number} range (radius) * @returns {GameObject[]} result */ getObjectsInRange (position, range) { return this.getObjectsOfTypesInRange(position, range, null); } /** * Retrieves objects within range of a given position matching a type. Sorted by distance from position * * @param {vector} position * @param {number} range (radius) * @param {class[]} types * @returns {GameObject[]} result */ getObjectsOfTypesInRange (position, range, types, options) { const typeFilter = Array.isArray(types) ? types.filter(t => t != null) : (types != null ? [types] : []); return this.collectInRange(position, range, (obj) => { if (typeFilter.length === 0) { return true; } for (let i = 0, len = typeFilter.length; i < len; i++) { if (obj instanceof typeFilter[i]) { return true; } } return false; }, options); } getObjectsWithTagInRange (position, range, tags, options) { const tagFilter = Array.isArray(tags) ? tags.filter(t => t != null) : (tags != null ? [tags] : []); return this.collectInRange(position, range, (obj) => { if (tagFilter.length === 0) { return true; } const objTags = obj.tags; if (!objTags || objTags.length === 0) { return false; } for (let i = 0, len = tagFilter.length; i < len; i++) { const want = tagFilter[i]; for (let j = 0, jl = objTags.length; j < jl; j++) { if (objTags[j] == want) { return true; } } } return false; }, options); } getClosestObjectWithTagInRange (position, range, tags) { const tagFilter = Array.isArray(tags) ? tags.filter(t => t != null) : (tags != null ? [tags] : []); return this.getClosestObjectInRange(position, range, (obj) => { if (tagFilter.length === 0) { return true; } const objTags = obj.tags; if (!objTags || objTags.length === 0) { return false; } for (let i = 0, len = tagFilter.length; i < len; i++) { const want = tagFilter[i]; for (let j = 0, jl = objTags.length; j < jl; j++) { if (objTags[j] == want) { return true; } } } return false; }); } /** * @param {vector} position * @param {number} range * @param {Function} predicate * @param {{ sort?: boolean }} [options] - sort defaults true (closest first) * @returns {GameObject[]} reused buffer — consume before the next query */ collectInRange (position, range, predicate, options) { const sort = !options || options.sort !== false; const rangeSq = range * range; const result = this._queryResult; result.length = 0; const nodes = this._queryNodes; nodes.length = 0; nodes.push(this.root); if (!sort) { while (nodes.length > 0) { const node = nodes.pop(); if (!this.isInRange(position, range, node)) { continue; } if (node.hasChildren) { nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright); continue; } const objects = node.objects; for (let i = 0, len = objects.length; i < len; i++) { const obj = objects[i]; const distSq = obj.transform.position.distanceToSq(position); if (distSq > 0 && distSq < rangeSq && predicate(obj)) { result.push(obj); } } } return result; } const scored = this._queryScored; scored.length = 0; while (nodes.length > 0) { const node = nodes.pop(); if (!this.isInRange(position, range, node)) { continue; } if (node.hasChildren) { nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright); continue; } const objects = node.objects; for (let i = 0, len = objects.length; i < len; i++) { const obj = objects[i]; const distSq = obj.transform.position.distanceToSq(position); if (distSq > 0 && distSq < rangeSq && predicate(obj)) { scored.push({ obj, dist: distSq }); } } } if (scored.length > 1) { scored.sort((a, b) => a.dist - b.dist); } for (let i = 0, len = scored.length; i < len; i++) { result.push(scored[i].obj); } return result; } getClosestObjectInRange (position, range, predicate) { const rangeSq = range * range; const nodes = this._queryNodes; nodes.length = 0; nodes.push(this.root); let closest = null; let closestDistSq = rangeSq; while (nodes.length > 0) { const node = nodes.pop(); if (!this.isInRange(position, range, node)) { continue; } if (node.hasChildren) { nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright); continue; } const objects = node.objects; for (let i = 0, len = objects.length; i < len; i++) { const obj = objects[i]; const distSq = obj.transform.position.distanceToSq(position); if (distSq > 0 && distSq < closestDistSq && predicate(obj)) { closestDistSq = distSq; closest = obj; } } } return closest; } isInRange (vector, range, node) { var points = [ vector.x - range, vector.x + range, vector.y - range, vector.y + range ]; if (points[1] >= node.x1 && points[0] <= node.x2) { if (points[3] >= node.y1 && points[2] <= node.y2) { return true; } } return false; } embiggen (dirOfOob) { // Place the current root as a child of a 2x parent that grows into the // out-of-bounds direction (L←, R→, U↑, D↓). if (dirOfOob == "L") { this.root = this.root.createParent("topright"); } else if (dirOfOob == "R") { this.root = this.root.createParent("topleft"); } else if (dirOfOob == "U") { this.root = this.root.createParent("bottomleft"); } else if (dirOfOob == "D") { this.root = this.root.createParent("topleft"); } this.width = this.root.lengthX; this.height = this.root.lengthY; } traverseTo (path) { let node = this.root; for (let i = 0, len = path.length; i < len; i++) { if (!node.hasChildren) { return node; } node = node.getChildren()[path[i]]; } return node; } findNodeFromRoot (object) { return this.findNodeFromRootAtPosition(object.transform.position); } findNodeFromRootAtPosition (position) { let node = this.root; while (node && node.hasChildren) { node = node.findChildNode(position) || node.topleft; } return node || this.root; } show (ctx) { this.showAll(this.root, ctx); } showAll (node, ctx) { node.show(ctx); if (node.hasChildren) { node.getChildren().forEach((element) => this.showAll(element, ctx)); } } update (/* deltaTime */) { // Merge/split happen eagerly on add/remove; nothing to tick per frame. } outOfBounds (object) { const pos = object.transform.position; if (pos.x < this.root.x1) { return "L"; } if (pos.x > this.root.x2) { return "R"; } if (pos.y < this.root.y1) { return "U"; } if (pos.y > this.root.y2) { return "D"; } return false; } } class Node { get canBeMerged () { // Leaf siblings may collapse into their parent when the parent's // whole subtree fits in one bucket again. return !this.hasChildren && this.parent && this.parent.recursiveCount <= this.quadTree.bucketSize; } get shouldSplit () { return !this.hasChildren && this.recursiveCount > this.quadTree.bucketSize && this.depth < this.quadTree.maxDepth; } get hasChildren () { return this.bottomright != null; //assume the rest is there too } constructor (x1, y1, x2, y2, depth, parent, name, quadTree) { this.name = name; this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; this.objects = []; this.topleft = null; this.topright = null; this.bottomleft = null; this.bottomright = null; this.parent = parent; this.depth = depth; this.recursiveCount = 0; this.lengthX = this.x2 - this.x1; this.lengthY = this.y2 - this.y1; this.halfLengthX = this.lengthX / 2; this.halfLengthY = this.lengthY / 2; this.quadTree = quadTree; } addCount () { this.recursiveCount++; this.parent && this.parent.addCount(); if (this.shouldSplit) { this.divide(); } } removeCount () { this.recursiveCount--; // Merge before notifying the parent. If the parent is checked first, // it still sees this node as a branch and skips the collapse; after // this node merges into a leaf the parent never re-checks. if (this.hasChildren) { let merge = true; const children = this.getChildren(); for (let i = 0, l = children.length; i < l; i++) { if (!children[i].canBeMerged) { merge = false; } } if (merge) { this.merge(); } } this.parent && this.parent.removeCount(); } remove (obj) { const index = this.objects ? this.objects.indexOf(obj) : -1; if (index >= 0) { this.objects.splice(index, 1); this.removeCount(); return true; } return false; } add (obj, ignoreCount) { if (this.objects.indexOf(obj) < 0) { this.objects.push(obj); if (!ignoreCount) { this.addCount(); } } } divide () { this.createNodes(); const center = new vector((this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2); this.objects.forEach(object => { if (object.transform.position.y > center.y) { if (object.transform.position.x > center.x) { object.node = this.bottomright; this.bottomright.add(object, true); } else { object.node = this.bottomleft; this.bottomleft.add(object, true); } } else { if (object.transform.position.x > center.x) { object.node = this.topright; this.topright.add(object, true); } else { object.node = this.topleft; this.topleft.add(object, true); } } }); this.objects = []; // add(..., true) skips counting so the parent is not double-counted. // Children still need a correct local recursiveCount, and may themselves // need to split when this redistribute dumps more than bucketSize in one cell. this.getChildren().forEach(child => { child.recursiveCount = child.objects.length; if (child.shouldSplit) { child.divide(); } }); } merge () { this.getChildren().forEach(child => { child.getObjects().forEach(object => { this.add(object, true); object.node = this; }); }); this.removeNodes(); } size () { if (this.objects != null) { return this.objects.length; } return 0; } getObjects () { return this.objects; } getChildren () { if (!this.hasChildren) { return []; } return [this.topleft, this.topright, this.bottomleft, this.bottomright]; } findChildNode (position) { if (!this.hasChildren) { return this; } // Same midpoint rule as divide() so add/remove/query stay consistent, // and we never return undefined on shared edges. const midX = this.x1 + this.halfLengthX; const midY = this.y1 + this.halfLengthY; if (position.y > midY) { return position.x > midX ? this.bottomright : this.bottomleft; } return position.x > midX ? this.topright : this.topleft; } createNodes () { if (this.hasChildren) { return; } const depth = this.depth + 1; this.topleft = new Node(this.x1, this.y1, this.x1 + this.halfLengthX, this.y1 + this.halfLengthY, depth, this, this.name + 0, this.quadTree); this.topright = new Node(this.x1 + this.halfLengthX, this.y1, this.x2, this.y1 + this.halfLengthY, depth, this, this.name + 1, this.quadTree); this.bottomleft = new Node(this.x1, this.y1 + this.halfLengthY, this.x1 + this.halfLengthX, this.y2, depth, this, this.name + 2, this.quadTree); this.bottomright = new Node(this.x1 + this.halfLengthX, this.y1 + this.halfLengthY, this.x2, this.y2, depth, this, this.name + 3, this.quadTree); return this.getChildren(); } createParent (nodePosition) { let parentNode; if (nodePosition == "topleft") { parentNode = new Node(this.x1, this.y1, this.x1 + (this.lengthX * 2), this.y1 + (this.lengthY * 2), this.depth - 1, null, "", this.quadTree); parentNode.topleft = this; } if (nodePosition == "topright") { parentNode = new Node(this.x1 - this.lengthX, this.y1, this.x1 + this.lengthX, this.y1 + (this.lengthY * 2), this.depth - 1, null, "", this.quadTree); parentNode.topright = this; } if (nodePosition == "bottomleft") { parentNode = new Node(this.x1, this.y1 - this.lengthY, this.x1 + (this.lengthX * 2), this.y1 + this.lengthY, this.depth - 1, null, "", this.quadTree); parentNode.bottomleft = this; } if (nodePosition == "bottomright") { parentNode = new Node(this.x1 - this.lengthX, this.y1 - this.lengthY, this.x1 + this.lengthX, this.y1 + this.lengthY, this.depth - 1, null, "", this.quadTree); parentNode.bottomright = this; } this.parent = parentNode; parentNode.recursiveCount = this.recursiveCount; if (!parentNode.topleft) { parentNode.topleft = new Node(parentNode.x1, parentNode.y1, parentNode.x1 + parentNode.halfLengthX, parentNode.y1 + parentNode.halfLengthY, this.depth, parentNode, parentNode.name + 0, this.quadTree); } if (!parentNode.topright) { parentNode.topright = new Node(parentNode.x1 + parentNode.halfLengthX, parentNode.y1, parentNode.x2, parentNode.y1 + parentNode.halfLengthY, this.depth, parentNode, parentNode.name + 1, this.quadTree); } if (!parentNode.bottomleft) { parentNode.bottomleft = new Node(parentNode.x1, parentNode.y1 + parentNode.halfLengthY, parentNode.x1 + parentNode.halfLengthX, parentNode.y2, this.depth, parentNode, parentNode.name + 2, this.quadTree); } if (!parentNode.bottomright) { parentNode.bottomright = new Node(parentNode.x1 + parentNode.halfLengthX, parentNode.y1 + parentNode.halfLengthY, parentNode.x2, parentNode.y2, this.depth, parentNode, parentNode.name + 3, this.quadTree); } parentNode.reconfigureNames(""); return parentNode; } startReconfigureNames () { let parent = this; while (parent.parent) { parent = parent.parent; } parent.reconfigureNames(""); } reconfigureNames (name) { this.name = name; const children = this.getChildren(); for (let i = 0, l = children.length; i < l; i++) { children[i].reconfigureNames(name + i); } } removeNodes () { this.topleft = null; this.topright = null; this.bottomleft = null; this.bottomright = null; } show (ctx) { ctx.strokeStyle = "white"; ctx.strokeRect(this.x1, this.y1, this.lengthX, this.lengthY); } } /* * End File: * framework/util/quadTree.js */ /* * Start File: * framework/util/particleEmitter.js */ class ParticleEmitter { static pool = []; enabled = false; mine = []; position = null; emissionRate = 0; emissionTimer = 0; emissionAngle = 0; startRotation = 0; startVelocity = 0; startAngularVelocity = 0; acceleration = null; angularAcceleration = 0; sprite = null; startSize = null; endSize = null; lifetimeMin = 0; lifetimeMax = 0; fadeIn = 0; fadeOut = 0; animationSpeed = 0; startFrame = 0; friction = null; angularFriction = 0; constructor (position, sprite, emissionRate, emissionAngle, startRotation, startVelocity, startAngularVelocity, acceleration, angularAcceleration, startSize, endSize, lifetimeMin, lifetimeMax = -1, fadeIn = 0, fadeOut = 0, startFrame = 0, animationSpeed = 0) { if (lifetimeMax < 0) { lifetimeMax = lifetimeMin; } this.position = position; this.sprite = sprite; this.emissionRate = emissionRate; this.emissionTimer = emissionRate; this.emissionAngle = emissionAngle; this.startRotation = startRotation; this.startVelocity = startVelocity * 10; this.startAngularVelocity = startAngularVelocity * 10; this.acceleration = acceleration.stretch(10); this.angularAcceleration = angularAcceleration * 10; this.startSize = startSize; this.endSize = endSize; this.lifetimeMin = lifetimeMin; this.lifetimeMax = lifetimeMax; this.fadeIn = fadeIn; this.fadeOut = fadeOut; this.startFrame = startFrame; this.animationSpeed = animationSpeed; this.friction = new vector(0, 0); } start () { this.enabled = true; } stop () { this.enabled = false; } emit (amount = 1) { for (let i = 0; i < amount; i++) { const newParticle = ParticleEmitter.unPool(); this.mine.push(newParticle); const velocity = vector.fromAngle(this.emissionAngle).stretch(this.startVelocity); newParticle.emit(this, this.position.x, this.position.y, this.startRotation, velocity.x, velocity.y, this.startAngularVelocity, this.acceleration.x, this.acceleration.y, this.angularAcceleration, this.sprite, this.startSize.x, this.startSize.y, this.endSize.x, this.endSize.y, this.lifetimeMin, this.lifetimeMax, this.fadeIn, this.fadeOut, this.startFrame, this.animationSpeed, this.friction.getCopy(), this.angularFriction); } } update (deltaTime) { if (this.enabled) { this.emissionTimer -= deltaTime; } if (this.emissionTimer <= 0) { this.emissionTimer = this.emissionRate; this.emit(); } // Backwards so dispose()/remove during update cannot skip particles. for (let i = this.mine.length - 1; i >= 0; i--) { this.mine[i].update(deltaTime); } } draw (scene) { for (let i = 0; i < this.mine.length; i++) { this.mine[i].draw(scene); } } dispose (particle) { this.mine.remove(particle); ParticleEmitter.returnToPool(particle); } static unPool () //get a particle from the static pool { if (ParticleEmitter.pool.length > 0) { return ParticleEmitter.pool.pop(); } return new Particle(); } static returnToPool (particle) { if (!ParticleEmitter.pool.contains(particle)) { ParticleEmitter.pool.push(particle); } } } class Particle { parent = null; position = null; rotation = 0; velocity = null; angularVelocity = 0; acceleration = null; angularAcceleration = 0; sprite = null; animTimer = 0; animationSpeed = 0; subImage = 0; startSize = null; endSize = null; fadeInTime = 0; fadeInStart = 0; fadeOutTime = 0; lifeTime = 0; lifeTimeStart = 0; friction = null; angularfriction = 0; constructor () { this.position = new vector(0, 0); this.velocity = new vector(0, 0); this.acceleration = new vector(0, 0); this.startSize = new vector(0, 0); this.endSize = new vector(0, 0); } emit (parent, x, y, r, vx, vy, va, ax, ay, ar, spr, ssx, ssy, esx, esy, lmin, lmax, fi = 0, fo = 0, sf = 0, as = 0, fric, anfric) { this.parent = parent; this.position.x = x; this.position.y = y; this.rotation = r; this.velocity.x = vx; this.velocity.y = vy; this.angularVelocity = va; this.acceleration.x = ax; this.acceleration.y = ay; this.angularAcceleration = ar; this.sprite = spr; this.startSize.x = ssx; this.startSize.y = ssy; this.endSize.x = esx; this.endSize.y = esy; this.lifeTime = Math.randomRange(lmin, lmax); this.lifeTimeStart = this.lifeTime; this.fadeInTime = fi; this.fadeInStart = fi; this.fadeOutTime = fo; this.animationSpeed = as; this.animTimer = as; this.subImage = sf; this.friction = fric ? fric.getCopy() : new vector(0, 0); this.angularFriction = anfric; } update (deltaTime) { this.position.x += this.velocity.x * deltaTime; this.position.y += this.velocity.y * deltaTime; this.velocity.x += this.acceleration.x * deltaTime; this.velocity.y += this.acceleration.y * deltaTime; this.velocity.x += this.friction.x * deltaTime * -Math.sign(this.velocity.x * 10); this.velocity.y += this.friction.y * deltaTime * -Math.sign(this.velocity.y * 10); this.rotation += this.angularVelocity * deltaTime; this.angularVelocity += this.angularAcceleration * deltaTime; this.angularVelocity += this.angularFriction * deltaTime * -Math.sign(this.angularVelocity * 10); this.lifeTime -= deltaTime; if (this.fadeInTime > 0) { this.fadeInTime -= deltaTime; } if (this.animationSpeed > 0) { this.animTimer -= deltaTime; if (this.animTimer <= 0) { this.animTimer = this.animationSpeed; this.subImage = (this.subImage + 1) % this.sprite.subImages; } } if (this.lifeTime <= 0) { this.parent.dispose(this); } } draw (scene) { const foAlpha = this.fadeOutTime > 0 ? Math.min(1, this.lifeTime / this.fadeOutTime) : 1; const fiAlpha = this.fadeInStart > 0 ? 1 - (this.fadeInTime / this.fadeInStart) : 1; this.sprite.draw( scene, Math.round(this.position.x), Math.round(this.position.y), Math.lerp(this.endSize.x, this.startSize.x, this.lifeTime / this.lifeTimeStart), Math.lerp(this.endSize.y, this.startSize.y, this.lifeTime / this.lifeTimeStart), this.rotation, false, false, Math.min(fiAlpha, foAlpha), this.subImage ); } } /* * End File: * framework/util/particleEmitter.js */ /* * Start File: * framework/engine/gl/shader.js */ class Shader { static DEFAULT_VERT = [ "attribute vec2 a_position;", "attribute vec2 a_texCoord;", "uniform mat4 u_matrix;", "varying vec2 v_texCoord;", "void main() {", " gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);", " v_texCoord = a_texCoord;", "}" ].join("\n"); static DEFAULT_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "varying vec2 v_texCoord;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " gl_FragColor = vec4(color.rgb, color.a * u_alpha);", "}" ].join("\n"); // Fullscreen NDC quad for screen-space / post-process passes. static SCREEN_VERT = [ "attribute vec2 a_position;", "attribute vec2 a_texCoord;", "varying vec2 v_texCoord;", "void main() {", " gl_Position = vec4(a_position, 0.0, 1.0);", " v_texCoord = a_texCoord;", "}" ].join("\n"); static SCREEN_COPY_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "varying vec2 v_texCoord;", "void main() {", " gl_FragColor = texture2D(u_texture, v_texCoord);", "}" ].join("\n"); constructor (vertSource, fragSource) { this.vertSource = vertSource || Shader.DEFAULT_VERT; this.fragSource = fragSource || Shader.DEFAULT_FRAG; this._programs = new WeakMap(); } static fragment (fragSource) { return new Shader(Shader.DEFAULT_VERT, fragSource); } static screenFragment (fragSource) { return new Shader(Shader.SCREEN_VERT, fragSource); } getProgramInfo (gl) { let info = this._programs.get(gl); if (info) { return info; } const program = Shader._createProgram(gl, this.vertSource, this.fragSource); if (!program) { return null; } info = { program: program, attribs: { position: gl.getAttribLocation(program, "a_position"), texCoord: gl.getAttribLocation(program, "a_texCoord") }, uniforms: {} }; const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (let i = 0; i < numUniforms; i++) { const uniformInfo = gl.getActiveUniform(program, i); if (!uniformInfo) { continue; } info.uniforms[uniformInfo.name] = { location: gl.getUniformLocation(program, uniformInfo.name), type: uniformInfo.type, size: uniformInfo.size }; } this._programs.set(gl, info); return info; } static _createShader (gl, type, source) { const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.error("Shader compile error:", gl.getShaderInfoLog(shader)); console.error(source); gl.deleteShader(shader); return null; } return shader; } static _createProgram (gl, vertSource, fragSource) { const vertexShader = Shader._createShader(gl, gl.VERTEX_SHADER, vertSource); const fragmentShader = Shader._createShader(gl, gl.FRAGMENT_SHADER, fragSource); if (!vertexShader || !fragmentShader) { return null; } const program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { console.error("Shader link error:", gl.getProgramInfoLog(program)); gl.deleteProgram(program); return null; } return program; } } /* * End File: * framework/engine/gl/shader.js */ /* * Start File: * framework/engine/gl/builtinShaders.js */ // Built-in screen-space / effect shaders. Games can use these without fetching files. // Expand this set over time into the default framework shader bundle. Shader.Builtin = Shader.Builtin || {}; Shader.Builtin.BLOOM_BRIGHT_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform float u_threshold;", "uniform float u_softKnee;", "varying vec2 v_texCoord;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", // Peak channel (not Rec.709 luma) so reds are not weaker than greens/blues. " float peak = max(color.r, max(color.g, color.b)) * color.a;", " float knee = max(u_softKnee, 0.001);", " float soft = smoothstep(u_threshold, u_threshold + knee, peak);", // Normalize by peak so saturated colors contribute similar bloom energy. " float invPeak = 1.0 / max(peak, 0.001);", " vec3 balanced = color.rgb * invPeak * soft;", " gl_FragColor = vec4(balanced, 1.0);", "}" ].join("\n"); // Max-filter dilate: fattens 1–4px hotspots so later blur has something to spread. Shader.Builtin.BLOOM_DILATE_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform vec2 u_resolution;", "uniform float u_radius;", "varying vec2 v_texCoord;", "void main() {", " vec2 px = u_radius / max(u_resolution, vec2(1.0));", " vec4 c = texture2D(u_texture, v_texCoord);", " c = max(c, texture2D(u_texture, v_texCoord + vec2(px.x, 0.0)));", " c = max(c, texture2D(u_texture, v_texCoord - vec2(px.x, 0.0)));", " c = max(c, texture2D(u_texture, v_texCoord + vec2(0.0, px.y)));", " c = max(c, texture2D(u_texture, v_texCoord - vec2(0.0, px.y)));", " c = max(c, texture2D(u_texture, v_texCoord + px));", " c = max(c, texture2D(u_texture, v_texCoord - px));", " c = max(c, texture2D(u_texture, v_texCoord + vec2(px.x, -px.y)));", " c = max(c, texture2D(u_texture, v_texCoord + vec2(-px.x, px.y)));", " vec2 px2 = px * 2.0;", " c = max(c, texture2D(u_texture, v_texCoord + vec2(px2.x, 0.0)));", " c = max(c, texture2D(u_texture, v_texCoord - vec2(px2.x, 0.0)));", " c = max(c, texture2D(u_texture, v_texCoord + vec2(0.0, px2.y)));", " c = max(c, texture2D(u_texture, v_texCoord - vec2(0.0, px2.y)));", " gl_FragColor = c;", "}" ].join("\n"); // Wider separable blur (13-tap). u_direction (1,0)/(0,1); u_blurSize in texels. Shader.Builtin.BLOOM_BLUR_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform vec2 u_resolution;", "uniform vec2 u_direction;", "uniform float u_blurSize;", "varying vec2 v_texCoord;", "void main() {", " vec2 step = u_direction * u_blurSize / max(u_resolution, vec2(1.0));", " vec4 c = vec4(0.0);", " c += texture2D(u_texture, v_texCoord - step * 6.0) * 0.009;", " c += texture2D(u_texture, v_texCoord - step * 5.0) * 0.019;", " c += texture2D(u_texture, v_texCoord - step * 4.0) * 0.038;", " c += texture2D(u_texture, v_texCoord - step * 3.0) * 0.071;", " c += texture2D(u_texture, v_texCoord - step * 2.0) * 0.111;", " c += texture2D(u_texture, v_texCoord - step) * 0.147;", " c += texture2D(u_texture, v_texCoord) * 0.160;", " c += texture2D(u_texture, v_texCoord + step) * 0.147;", " c += texture2D(u_texture, v_texCoord + step * 2.0) * 0.111;", " c += texture2D(u_texture, v_texCoord + step * 3.0) * 0.071;", " c += texture2D(u_texture, v_texCoord + step * 4.0) * 0.038;", " c += texture2D(u_texture, v_texCoord + step * 5.0) * 0.019;", " c += texture2D(u_texture, v_texCoord + step * 6.0) * 0.009;", " gl_FragColor = c;", "}" ].join("\n"); // Combine: add bloom while keeping / boosting chroma (avoids gray wash at high intensity). Shader.Builtin.BLOOM_COMBINE_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform sampler2D u_scene;", "uniform float u_intensity;", "uniform float u_saturation;", "uniform float u_colorPreserve;", "varying vec2 v_texCoord;", "void main() {", " vec4 scene = texture2D(u_scene, v_texCoord);", " vec4 bloom = texture2D(u_texture, v_texCoord);", " vec3 bloomCol = bloom.rgb;", " float bloomPeak = max(bloomCol.r, max(bloomCol.g, bloomCol.b));", " bloomCol = mix(vec3(bloomPeak), bloomCol, u_saturation);", // Hue from scene peak (not luma) so red bullets keep chroma under colorPreserve. " float scenePeak = max(scene.r, max(scene.g, scene.b));", " vec3 sceneHue = scene.rgb / max(scenePeak, 0.04);", " bloomCol *= mix(vec3(1.0), sceneHue, clamp(u_colorPreserve, 0.0, 1.0));", " bloomCol *= u_intensity;", // Soft add: keeps punchy color instead of clipping hard to white/gray. " vec3 rgb = scene.rgb + bloomCol * (1.0 - scene.rgb * 0.35);", " float bloomA = max(bloomCol.r, max(bloomCol.g, bloomCol.b));", " float a = max(scene.a, min(bloomA, 1.0));", " gl_FragColor = vec4(rgb, a);", "}" ].join("\n"); /** * Multi-pass bloom for a RenderLayer / scene.postShaders. * * options: * - threshold, softKnee, intensity, blurSize * - saturation: bloom chroma boost (1 = neutral, >1 = juicier) * - colorPreserve: 0–1 tint bloom with the original sprite hue * - smallSources: dilate tiny bright pixels before blur (good for 3–4px bullets) * - dilate: explicit dilate radius in texels (overrides smallSources default) * - scales: number of H/V blur scale pairs (default 2 with smallSources, else 1) * - halfRes: run dilate + blur at half resolution when true (default true) */ Shader.getBloomPostChain = function (options) { options = options || {}; const threshold = options.threshold != null ? options.threshold : 0.4; const softKnee = options.softKnee != null ? options.softKnee : 0.3; const intensity = options.intensity != null ? options.intensity : 1.25; const blurSize = options.blurSize != null ? options.blurSize : 3.0; const saturation = options.saturation != null ? options.saturation : 1.0; const colorPreserve = options.colorPreserve != null ? options.colorPreserve : 0.0; const smallSources = !!options.smallSources; let dilateRadius = 0; if (options.dilate != null) { dilateRadius = options.dilate; } else if (smallSources) { dilateRadius = 4.5; } // fatter hotspots so tiny bullets bloom closer to large ones const scales = options.scales != null ? options.scales : (smallSources ? 2 : 1); // Dilate + blur at half-res (~4× less fill). Bright extract + combine stay full-res. const halfResBlur = options.halfRes !== false; const halfPass = halfResBlur ? { scale: 0.5 } : {}; // At half-res, texel-sized kernels cover ~2× world space — keep visual width similar. const resScale = halfResBlur ? 0.5 : 1; if (!Shader._bloomBright || Shader._bloomBright.fragSource !== Shader.Builtin.BLOOM_BRIGHT_FRAG) { Shader._bloomBright = Shader.screenFragment(Shader.Builtin.BLOOM_BRIGHT_FRAG); Shader._bloomDilate = Shader.screenFragment(Shader.Builtin.BLOOM_DILATE_FRAG); Shader._bloomBlur = Shader.screenFragment(Shader.Builtin.BLOOM_BLUR_FRAG); Shader._bloomCombine = Shader.screenFragment(Shader.Builtin.BLOOM_COMBINE_FRAG); } const chain = [ { shader: Shader._bloomBright, uniforms: { u_threshold: threshold, u_softKnee: softKnee } } ]; if (dilateRadius > 0) { chain.push(Object.assign({ shader: Shader._bloomDilate, uniforms: { u_radius: dilateRadius * resScale } }, halfPass)); } const scaleFactors = [1, 2.2, 4.5, 8]; for (let i = 0; i < scales; i++) { const size = blurSize * scaleFactors[Math.min(i, scaleFactors.length - 1)] * resScale; chain.push(Object.assign({ shader: Shader._bloomBlur, uniforms: { u_direction: [1, 0], u_blurSize: size } }, halfPass)); chain.push(Object.assign({ shader: Shader._bloomBlur, uniforms: { u_direction: [0, 1], u_blurSize: size } }, halfPass)); } chain.push({ shader: Shader._bloomCombine, uniforms: { u_intensity: intensity, u_saturation: saturation, u_colorPreserve: colorPreserve } }); return chain; }; // --- Sprite effect builtins ------------------------------------------------- Shader.Builtin.BUMPMAP_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform sampler2D u_bump;", "uniform float u_alpha;", "uniform vec2 u_worldCenter;", "uniform vec2 u_worldSize;", "uniform float u_rotationRad;", "uniform int u_lightCount;", "uniform vec2 u_lightPos[16];", "uniform vec3 u_lightColor[16];", "uniform float u_ambient;", "uniform float u_specular;", // 0 = height map (R), 1 = tangent-space normal map (RGB) "uniform float u_bumpMode;", "varying vec2 v_texCoord;", "void main() {", " vec4 albedo = texture2D(u_texture, v_texCoord);", " vec3 normal;", " if (u_bumpMode < 0.5) {", " float hL = texture2D(u_bump, v_texCoord + vec2(-0.01, 0.0)).r;", " float hR = texture2D(u_bump, v_texCoord + vec2(0.01, 0.0)).r;", " float hU = texture2D(u_bump, v_texCoord + vec2(0.0, -0.01)).r;", " float hD = texture2D(u_bump, v_texCoord + vec2(0.0, 0.01)).r;", " normal = normalize(vec3(hL - hR, hU - hD, 0.35));", " } else {", " vec3 nSample = texture2D(u_bump, v_texCoord).xyz * 2.0 - 1.0;", " normal = normalize(nSample);", " }", " float c = cos(u_rotationRad);", " float s = sin(u_rotationRad);", " normal = normalize(vec3(c * normal.x - s * normal.y, s * normal.x + c * normal.y, normal.z));", " vec2 local = (v_texCoord - vec2(0.5)) * u_worldSize;", " vec2 world = u_worldCenter + vec2(c * local.x - s * local.y, s * local.x + c * local.y);", " vec3 lighting = vec3(u_ambient);", " for (int i = 0; i < 16; i++) {", " if (i >= u_lightCount) { break; }", " vec2 toLight = u_lightPos[i] - world;", " float dist = max(length(toLight), 0.001);", " vec3 lightDir = normalize(vec3(toLight / dist, 0.75));", " float diff = max(dot(normal, lightDir), 0.0);", " float atten = 1.0 / (1.0 + dist * 0.006 + dist * dist * 0.00004);", " float spec = pow(diff, 24.0) * u_specular;", " lighting += u_lightColor[i] * (diff + spec) * atten;", " }", " gl_FragColor = vec4(albedo.rgb * lighting, albedo.a * u_alpha);", "}" ].join("\n"); // Replace pure R/G/B paint channel with u_replaceColor. Shader.Builtin.COLOUR_REPLACE_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "uniform float u_channel;", "uniform vec3 u_replaceColor;", "varying vec2 v_texCoord;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " float ch = color.r;", " float other = max(color.g, color.b);", " if (u_channel > 0.5 && u_channel < 1.5) { ch = color.g; other = max(color.r, color.b); }", " if (u_channel >= 1.5) { ch = color.b; other = max(color.r, color.g); }", " float mask = clamp((ch - other) * 1.75, 0.0, 1.0);", " vec3 rgb = mix(color.rgb, u_replaceColor, mask);", " gl_FragColor = vec4(rgb, color.a * u_alpha);", "}" ].join("\n"); // Clip sprite where secondary map luminance < u_amount (0 = full, 1 = gone). Shader.Builtin.DISINTEGRATE_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform sampler2D u_secondary;", "uniform float u_alpha;", "uniform float u_amount;", "varying vec2 v_texCoord;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " float ref = texture2D(u_secondary, v_texCoord).r;", " if (ref < u_amount) { discard; }", " float edge = smoothstep(u_amount, u_amount + 0.08, ref);", " gl_FragColor = vec4(color.rgb, color.a * u_alpha * edge);", "}" ].join("\n"); Shader.getBumpmapShader = function () { if (!Shader._bumpmap || Shader._bumpmap.fragSource !== Shader.Builtin.BUMPMAP_FRAG) { Shader._bumpmap = Shader.fragment(Shader.Builtin.BUMPMAP_FRAG); } return Shader._bumpmap; }; Shader.getColourReplaceShader = function () { if (!Shader._colourReplace) { Shader._colourReplace = Shader.fragment(Shader.Builtin.COLOUR_REPLACE_FRAG); } return Shader._colourReplace; }; Shader.getDisintegrateShader = function () { if (!Shader._disintegrate) { Shader._disintegrate = Shader.fragment(Shader.Builtin.DISINTEGRATE_FRAG); } return Shader._disintegrate; }; // --- Screen-space effect builtins ------------------------------------------ Shader.Builtin.DIRECTIONAL_BLUR_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform vec2 u_resolution;", "uniform vec2 u_direction;", "uniform float u_length;", "varying vec2 v_texCoord;", "void main() {", " vec2 dir = u_direction;", " float len = length(dir);", " if (len > 0.0001) { dir /= len; } else { dir = vec2(1.0, 0.0); }", " vec2 step = dir * u_length / max(u_resolution, vec2(1.0));", " vec4 c = vec4(0.0);", " c += texture2D(u_texture, v_texCoord - step * 2.0) * 0.12;", " c += texture2D(u_texture, v_texCoord - step) * 0.23;", " c += texture2D(u_texture, v_texCoord) * 0.30;", " c += texture2D(u_texture, v_texCoord + step) * 0.23;", " c += texture2D(u_texture, v_texCoord + step * 2.0) * 0.12;", " gl_FragColor = c;", "}" ].join("\n"); Shader.Builtin.RADIAL_BLUR_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform vec2 u_center;", "uniform float u_amount;", "varying vec2 v_texCoord;", "void main() {", " vec2 toCenter = u_center - v_texCoord;", " vec4 c = vec4(0.0);", " for (int i = 0; i < 8; i++) {", " float t = float(i) / 7.0;", " vec2 uv = v_texCoord + toCenter * t * u_amount;", " c += texture2D(u_texture, uv);", " }", " gl_FragColor = c / 8.0;", "}" ].join("\n"); Shader.Builtin.COLOR_ADJUST_FRAG = [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform float u_saturation;", "uniform float u_contrast;", "uniform float u_brightness;", "varying vec2 v_texCoord;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));", " vec3 rgb = mix(vec3(lum), color.rgb, u_saturation);", " rgb = (rgb - 0.5) * u_contrast + 0.5 + u_brightness;", " gl_FragColor = vec4(rgb, color.a);", "}" ].join("\n"); Shader.getDirectionalBlurPostChain = function (options) { options = options || {}; const direction = options.direction || [1, 0]; const length = options.length != null ? options.length : 8; if (!Shader._directionalBlur) { Shader._directionalBlur = Shader.screenFragment(Shader.Builtin.DIRECTIONAL_BLUR_FRAG); } return [{ shader: Shader._directionalBlur, uniforms: { u_direction: [direction[0], direction[1]], u_length: length } }]; }; Shader.getRadialBlurPostChain = function (options) { options = options || {}; const amount = options.amount != null ? options.amount : 0.15; const center = options.center || [0.5, 0.5]; if (!Shader._radialBlur) { Shader._radialBlur = Shader.screenFragment(Shader.Builtin.RADIAL_BLUR_FRAG); } return [{ shader: Shader._radialBlur, uniforms: { u_amount: amount, u_center: [center[0], center[1]] } }]; }; Shader.getColorAdjustPostChain = function (options) { options = options || {}; const saturation = options.saturation != null ? options.saturation : 1.0; const contrast = options.contrast != null ? options.contrast : 1.0; const brightness = options.brightness != null ? options.brightness : 0.0; if (!Shader._colorAdjust) { Shader._colorAdjust = Shader.screenFragment(Shader.Builtin.COLOR_ADJUST_FRAG); } return [{ shader: Shader._colorAdjust, uniforms: { u_saturation: saturation, u_contrast: contrast, u_brightness: brightness } }]; }; /* * End File: * framework/engine/gl/builtinShaders.js */ /* * Start File: * framework/engine/gl/glContext.js */ class GLContext { static MAX_LIGHTS = 16; constructor (canvas) { this.canvas = canvas; // 2D sprites do not benefit from MSAA; disabling avoids extra GPU cost. const attrs = { alpha: true, premultipliedAlpha: false, antialias: false }; this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs); if (!this.gl) { throw new Error("WebGL is not supported in this browser."); } const gl = this.gl; gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.disable(gl.DEPTH_TEST); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG); this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG); this.textures = new WeakMap(); // Defaults for getTexture uploads. Games can switch to NEAREST for pixel art. this.textureMinFilter = gl.LINEAR; this.textureMagFilter = gl.LINEAR; // Reused per-sprite uploads (avoid allocating Float32Array every draw). this._uvData = new Float32Array(8); this._matrixData = new Float32Array(16); this.positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5 ]), gl.STATIC_DRAW); this.texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._uvData, gl.DYNAMIC_DRAW); // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling). this.screenPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -1, -1, 1, -1, -1, 1, 1, 1 ]), gl.STATIC_DRAW); this.screenTexCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, 1, 0, 0, 1, 1, 1 ]), gl.STATIC_DRAW); // [0] = scene (stable during post), [1]/[2] = full-res ping-pong, // [3]/[4] = half-res ping-pong for pass.scale < 1 blur. this.framebuffers = [null, null, null, null, null]; this.colorTextures = [null, null, null, null, null]; this._offscreenIndex = 0; this._lastWidth = 0; this._lastHeight = 0; this._halfWidth = 0; this._halfHeight = 0; this._postUniforms = {}; this._resUniform = [0, 0]; this.setSize(canvas.width, canvas.height); } setSize (width, height) { const gl = this.gl; width = Math.max(1, width | 0); height = Math.max(1, height | 0); if (width !== this._lastWidth || height !== this._lastHeight) { this._lastWidth = width; this._lastHeight = height; this._halfWidth = Math.max(1, width >> 1); this._halfHeight = Math.max(1, height >> 1); gl.viewport(0, 0, width, height); this._rebuildFramebuffers(width, height); } } _destroyFramebuffers () { const gl = this.gl; for (let i = 0; i < this.framebuffers.length; i++) { if (this.framebuffers[i]) { gl.deleteFramebuffer(this.framebuffers[i]); this.framebuffers[i] = null; } if (this.colorTextures[i]) { gl.deleteTexture(this.colorTextures[i]); this.colorTextures[i] = null; } } } _rebuildFramebuffers (width, height) { const gl = this.gl; this._destroyFramebuffers(); this._halfWidth = Math.max(1, width >> 1); this._halfHeight = Math.max(1, height >> 1); for (let i = 0; i < 5; i++) { const texW = i < 3 ? width : this._halfWidth; const texH = i < 3 ? height : this._halfHeight; const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texW, texH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status !== gl.FRAMEBUFFER_COMPLETE) { console.error("Framebuffer incomplete:", status); } this.framebuffers[i] = fb; this.colorTextures[i] = texture; } gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindTexture(gl.TEXTURE_2D, null); } clear (r, g, b, a = 1) { const gl = this.gl; gl.clearColor(r / 255, g / 255, b / 255, a); gl.clear(gl.COLOR_BUFFER_BIT); } clearTransparent () { const gl = this.gl; gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); } beginOffscreenPass () { const gl = this.gl; this._offscreenIndex = 0; gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]); gl.viewport(0, 0, this._lastWidth, this._lastHeight); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } endOffscreenPass () { const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); } /** * @param {Array} passes * @param {Object} builtins * @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas. * @returns {WebGLTexture|null} final color texture when not drawing to canvas */ applyPostShaders (passes, builtins = {}, options = {}) { if (!passes || !passes.length) { return this.colorTextures[0]; } const gl = this.gl; const toCanvas = !!options.toCanvas; const sceneTexture = this.colorTextures[0]; let read = 0; let readIsHalf = false; gl.disable(gl.BLEND); for (let i = 0; i < passes.length; i++) { const pass = passes[i]; const isLast = i === passes.length - 1; const wantHalf = pass.scale != null && pass.scale < 1; let write; let writeW; let writeH; if (wantHalf) { // Half-res ping-pong on indices 3/4. if (readIsHalf) { write = (read === 3) ? 4 : 3; } else { write = 3; } writeW = this._halfWidth; writeH = this._halfHeight; } else { // Full-res ping-pong on 1/2 (never overwrite scene buffer 0). // When leaving half-res, read half texture into a full write target. if (read === 1) { write = 2; } else if (read === 2) { write = 1; } else { write = 1; } writeW = this._lastWidth; writeH = this._lastHeight; } if (isLast && toCanvas) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); writeW = this._lastWidth; writeH = this._lastHeight; } else { gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]); } gl.viewport(0, 0, writeW, writeH); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); const uniforms = this._postUniforms; for (const key in uniforms) { if (Object.prototype.hasOwnProperty.call(uniforms, key)) { delete uniforms[key]; } } if (builtins) { for (const key in builtins) { if (Object.prototype.hasOwnProperty.call(builtins, key)) { uniforms[key] = builtins[key]; } } } const passUniforms = pass.uniforms; if (passUniforms) { for (const key in passUniforms) { if (Object.prototype.hasOwnProperty.call(passUniforms, key)) { uniforms[key] = passUniforms[key]; } } } this._resUniform[0] = writeW; this._resUniform[1] = writeH; uniforms.u_resolution = this._resUniform; this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture); if (!isLast || !toCanvas) { read = write; readIsHalf = wantHalf && !(isLast && toCanvas); } } this._offscreenIndex = read; gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.bindFramebuffer(gl.FRAMEBUFFER, null); return toCanvas ? null : this.colorTextures[read]; } blitToCanvas (texture, composite = "alpha") { if (!texture) { return; } const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, this._lastWidth, this._lastHeight); gl.enable(gl.BLEND); if (composite === "add") { gl.blendFunc(gl.ONE, gl.ONE); } else { gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } this.drawFullscreen(this.screenCopyShader, texture, null, null); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } drawFullscreen (shader, texture, uniforms, sceneTexture) { const gl = this.gl; const info = shader.getProgramInfo(gl); if (!info || !texture) { return; } gl.useProgram(info.program); gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer); if (info.attribs.position >= 0) { gl.enableVertexAttribArray(info.attribs.position); gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0); } gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer); if (info.attribs.texCoord >= 0) { gl.enableVertexAttribArray(info.attribs.texCoord); gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0); } gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); this._setUniform(info, "u_texture", 0); this._setUniform(info, "u_alpha", 1); if (sceneTexture && info.uniforms.u_scene) { gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, sceneTexture); this._setUniform(info, "u_scene", 1); } if (uniforms) { for (const name in uniforms) { if (!Object.prototype.hasOwnProperty.call(uniforms, name)) { continue; } this._setUniform(info, name, uniforms[name]); } } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } /** * Default min/mag filter applied when creating textures in {@link getTexture}. * Does not rewrite textures that were already uploaded. */ setDefaultTextureFilter (minFilter, magFilter) { const gl = this.gl; this.textureMinFilter = minFilter ?? gl.LINEAR; this.textureMagFilter = magFilter ?? gl.LINEAR; } getTexture (htmlImage) { if (!htmlImage) { return null; } let texture = this.textures.get(htmlImage); if (texture) { return texture; } const gl = this.gl; texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.textureMinFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.textureMagFilter); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImage); this.textures.set(htmlImage, texture); return texture; } drawSprite (options) { const gl = this.gl; const width = this._lastWidth; const height = this._lastHeight; if (width <= 0 || height <= 0) { return; } const shader = options.shader || this.defaultShader; const info = shader.getProgramInfo(gl); if (!info) { return; } const texture = options.texture; if (!texture) { return; } gl.useProgram(info.program); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer); if (info.attribs.position >= 0) { gl.enableVertexAttribArray(info.attribs.position); gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0); } const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 }; const uvData = this._uvData; uvData[0] = uv.u0; uvData[1] = uv.v0; uvData[2] = uv.u1; uvData[3] = uv.v0; uvData[4] = uv.u0; uvData[5] = uv.v1; uvData[6] = uv.u1; uvData[7] = uv.v1; gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, uvData); if (info.attribs.texCoord >= 0) { gl.enableVertexAttribArray(info.attribs.texCoord); gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0); } const matrix = GLContext._buildSpriteMatrix( options.x, options.y, options.w, options.h, options.rotationDeg || 0, options.mirrorX, options.mirrorY, width, height, this._matrixData ); this._setUniform(info, "u_matrix", matrix); this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha); this._setUniform(info, "u_worldCenter", [options.x, options.y]); this._setUniform(info, "u_worldSize", [options.w, options.h]); this._setUniform(info, "u_rotationRad", (options.rotationDeg || 0) * Math.PI / 180); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); this._setUniform(info, "u_texture", 0); let nextUnit = 1; if (options.textures) { for (const name in options.textures) { if (!Object.prototype.hasOwnProperty.call(options.textures, name)) { continue; } const extra = options.textures[name]; if (!extra) { continue; } gl.activeTexture(gl.TEXTURE0 + nextUnit); gl.bindTexture(gl.TEXTURE_2D, extra); this._setUniform(info, name, nextUnit); nextUnit++; } } if (options.lights) { this._setLights(info, options.lights); } else if (info.uniforms.u_lightCount) { this._setUniform(info, "u_lightCount", 0); } // Sensible bump defaults when the shader asks for them. if (info.uniforms.u_ambient && (!options.uniforms || options.uniforms.u_ambient == null)) { this._setUniform(info, "u_ambient", 0.35); } if (info.uniforms.u_specular && (!options.uniforms || options.uniforms.u_specular == null)) { this._setUniform(info, "u_specular", 0.25); } if (info.uniforms.u_bumpMode && (!options.uniforms || options.uniforms.u_bumpMode == null)) { this._setUniform(info, "u_bumpMode", 1); } if (options.uniforms) { for (const name in options.uniforms) { if (!Object.prototype.hasOwnProperty.call(options.uniforms, name)) { continue; } this._setUniform(info, name, options.uniforms[name]); } } gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } _setLights (info, lights) { const gl = this.gl; const max = GLContext.MAX_LIGHTS; const count = Math.max(0, Math.min(lights.length, max)); this._setUniform(info, "u_lightCount", count); const posEntry = info.uniforms["u_lightPos[0]"] || info.uniforms.u_lightPos; const colEntry = info.uniforms["u_lightColor[0]"] || info.uniforms.u_lightColor; if (!posEntry || !colEntry || count === 0) { if (count === 0) { this._setUniform(info, "u_lightCount", 0); } return; } const pos = new Float32Array(max * 2); const col = new Float32Array(max * 3); for (let i = 0; i < count; i++) { const light = lights[i] || {}; pos[i * 2] = light.x != null ? light.x : (light.position ? light.position.x : 0); pos[i * 2 + 1] = light.y != null ? light.y : (light.position ? light.position.y : 0); const c = light.color != null ? light.color : [1, 1, 1]; if (Array.isArray(c)) { col[i * 3] = c[0] != null ? c[0] : 0; col[i * 3 + 1] = c[1] != null ? c[1] : 0; col[i * 3 + 2] = c[2] != null ? c[2] : 0; } else { col[i * 3] = (c.r != null ? c.r : 1); col[i * 3 + 1] = (c.g != null ? c.g : 1); col[i * 3 + 2] = (c.b != null ? c.b : 1); } // Allow 0–255 style colors. if (col[i * 3] > 1 || col[i * 3 + 1] > 1 || col[i * 3 + 2] > 1) { col[i * 3] /= 255; col[i * 3 + 1] /= 255; col[i * 3 + 2] /= 255; } } gl.uniform2fv(posEntry.location, pos); gl.uniform3fv(colEntry.location, col); } _setUniform (info, name, value) { const entry = info.uniforms[name]; if (!entry || entry.location == null) { return; } const gl = this.gl; const loc = entry.location; if (typeof value === "number") { if (entry.type === gl.INT || entry.type === gl.SAMPLER_2D) { gl.uniform1i(loc, value); } else { gl.uniform1f(loc, value); } return; } if (value instanceof Float32Array) { if (value.length === 16) { gl.uniformMatrix4fv(loc, false, value); } else if (value.length === 9) { gl.uniformMatrix3fv(loc, false, value); } else if (value.length === 4) { gl.uniform4fv(loc, value); } else if (value.length === 3) { gl.uniform3fv(loc, value); } else if (value.length === 2) { gl.uniform2fv(loc, value); } return; } if (Array.isArray(value)) { if (value.length === 4) { gl.uniform4fv(loc, value); } else if (value.length === 3) { gl.uniform3fv(loc, value); } else if (value.length === 2) { gl.uniform2fv(loc, value); } else if (value.length === 1) { gl.uniform1f(loc, value[0]); } } } // Column-major mat4: projection (canvas Y-down) * T * R * S static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH, out) { const sx = (mirrorX ? -1 : 1) * w; const sy = (mirrorY ? -1 : 1) * h; const rad = rotationDeg * Math.PI / 180; const c = Math.cos(rad); const s = Math.sin(rad); // Model maps unit quad [-0.5,0.5] into pixel space. const m00 = c * sx; const m01 = -s * sy; const m10 = s * sx; const m11 = c * sy; const m30 = x; const m31 = y; const pr0 = 2 / canvasW; const pr5 = -2 / canvasH; const pr12 = -1; const pr13 = 1; const matrix = out || new Float32Array(16); // P * M (only 2D affine terms matter) matrix[0] = pr0 * m00; matrix[1] = pr5 * m10; matrix[2] = 0; matrix[3] = 0; matrix[4] = pr0 * m01; matrix[5] = pr5 * m11; matrix[6] = 0; matrix[7] = 0; matrix[8] = 0; matrix[9] = 0; matrix[10] = -1; matrix[11] = 0; matrix[12] = pr0 * m30 + pr12; matrix[13] = pr5 * m31 + pr13; matrix[14] = 0; matrix[15] = 1; return matrix; } } /* * End File: * framework/engine/gl/glContext.js */ /* * Start File: * framework/engine/renderLayer.js */ class RenderLayer { static DEFAULT_NAME = "default"; constructor (name, options) { options = options || {}; this.name = name || RenderLayer.DEFAULT_NAME; this.postShaders = options.postShaders || []; // "alpha" (source-over) or "add" (additive) this.composite = options.composite || "alpha"; } } /* * End File: * framework/engine/renderLayer.js */ /* * Start File: * framework/engine/objectComponents/transform.js */ class Transform { get position () { if (!this.g_position) {this.g_position = new vector(0, 0);} return this.g_position; } set position (v) { if (!this.g_position) {this.g_position = new vector(v.x, v.y);} this.g_position.x = v.x; this.g_position.y = v.y; } get scale () { if (!this.g_scale) {this.g_scale = new vector(0, 0);} return this.g_scale; } set scale (v) { if (!this.g_scale) {this.g_scale = new vector(v.x, v.y);} this.g_scale.x = v.x; this.g_scale.y = v.y; } get velocity () { if (!this.g_velocity) {this.g_velocity = new vector(0, 0);} return this.g_velocity; } set velocity (v) { if (!this.g_velocity) {this.g_velocity = new vector(v.x, v.y);} this.g_velocity.x = v.x; this.g_velocity.y = v.y; } g_position = null; g_scale = null; rotation = 0; gameObject = null; g_velocity = null; angularVelocity = 0; get size () { const sprite = this.gameObject.renderer && this.gameObject.renderer.sprite; const width = sprite ? sprite.width : 0; const height = sprite ? sprite.height : 0; if (!this.g_size) { this.g_size = new vector(0, 0); } this.g_size.x = this.scale.x * width; this.g_size.y = this.scale.y * height; return this.g_size; } set size (v) { const sprite = this.gameObject.renderer && this.gameObject.renderer.sprite; const width = sprite && sprite.width ? sprite.width : 1; const height = sprite && sprite.height ? sprite.height : 1; this.scale.x = v.x / width; this.scale.y = v.y / height; } constructor (gameObject, x, y, w, h, r) { this.gameObject = gameObject; this.position = new vector(x, y); this.scale = new vector(w, h); this.rotation = r; this.velocity = new vector(0, 0); } update (deltaTime) { const vel = this.velocity; if (vel.x !== 0 || vel.y !== 0) { this.position.x += vel.x * deltaTime; this.position.y += vel.y * deltaTime; } if (this.angularVelocity !== 0) { this.rotation += this.angularVelocity * deltaTime; } } pointTowards (point) { var delta = point.subtract(this.position); this.rotation = delta.toAngle(); } get left () { return this.g_dir(0); } get right () { return this.g_dir(180); } get forward () { return this.g_dir(90); } get back () { return this.g_dir(270); } g_dir (offset) { var myAngleInRadians = (this.rotation + offset) * (Math.PI / 180); return new vector(-Math.cos(myAngleInRadians), -Math.sin(myAngleInRadians)); } } /* * End File: * framework/engine/objectComponents/transform.js */ /* * Start File: * framework/engine/objectComponents/collider.js */ class Collider { gameObject = null; enabled = false; constructor (gameObject) { this.gameObject = gameObject; } get widestDiagonal () { return Math.sqrt((this.gameObject.transform.size.x * this.gameObject.transform.size.x) + (this.gameObject.transform.size.y * this.gameObject.transform.size.y)); } update (deltaTime) { if (this.enabled) { this.checkCollisions(); } // Bullets/FX have no click handlers — skip per-object mouse work entirely. const obj = this.gameObject; if (!obj.onClick && !obj.onMouseHeld) { return; } const pressed = GameInput.mousePressed(); const held = GameInput.mouseHeld(); if (pressed.left || pressed.middle || pressed.right) { this.checkClick(true, pressed); } if (held.left || held.middle || held.right) { this.checkClick(false, held); } } checkClick (thisFrame, btns) { if (!GameInput.mousePosition || !this.gameObject.scene) { return; } var hit = false; var clickPos = GameInput.mousePosition .subtract(this.gameObject.scene.real_position) .subtract(this.gameObject.scene.cameraPosition); var hw = this.gameObject.transform.size.x / 2; var hh = this.gameObject.transform.size.y / 2; if (clickPos.x > this.gameObject.transform.position.x - hw && clickPos.x < this.gameObject.transform.position.x + hw) { if (clickPos.y > this.gameObject.transform.position.y - hh && clickPos.y < this.gameObject.transform.position.y + hh) { hit = true; } } if (hit) { if (thisFrame) { this.gameObject.onClick && this.gameObject.onClick(btns); } else { this.gameObject.onMouseHeld && this.gameObject.onMouseHeld(btns); } } } isInBounds (point) { var hw = this.gameObject.transform.size.x / 2; var hh = this.gameObject.transform.size.y / 2; if (point.x > this.gameObject.transform.position.x - hw && point.x < this.gameObject.transform.position.x + hw) { if (point.y > this.gameObject.transform.position.y - hh && point.y < this.gameObject.transform.position.y + hh) { return true; } } return false; } checkCollisions () { if (this.enabled && !this.gameObject.destroyed) { const activeObjects = this.gameObject.scene.activeObjects; const offset = activeObjects.indexOf(this.gameObject) + 1; for (var i = offset; i < activeObjects.length; i++) { var o2 = activeObjects[i]; if (o2 === this.gameObject || !o2.collider.enabled || o2.destroyed) { continue; } if (this.widestDiagonal + o2.collider.widestDiagonal < this.gameObject.transform.position.distanceTo(o2.transform.position)) { continue; } var hit = false; //hw = halfWidth, hh = halfHeight var hw = this.gameObject.transform.size.x / 2; var hh = this.gameObject.transform.size.y / 2; var ohw = o2.transform.size.x / 2; var ohh = o2.transform.size.y / 2; //CHECK FROM OBJ PERSPECTIVE var points = [ this.gameObject.transform.position.x - hw, this.gameObject.transform.position.x + hw, this.gameObject.transform.position.y - hh, this.gameObject.transform.position.y + hh ]; if (points[1] >= o2.transform.position.x - ohw && points[0] <= o2.transform.position.x + ohw) { if (points[3] >= o2.transform.position.y - ohh && points[2] <= o2.transform.position.y + ohh) { hit = true; } } if (hit) { if (!this.gameObject.destroyed && typeof this.gameObject.onCollision == 'function') { this.gameObject.onCollision(o2); } if (!o2.destroyed && typeof o2.onCollision == 'function') { o2.onCollision(this.gameObject); } } } } } } /* * End File: * framework/engine/objectComponents/collider.js */ /* * Start File: * framework/engine/objectComponents/renderer.js */ class Renderer { sprite = null; gameObject = null; subImage = 0; alpha = 1; mirrorX = false; mirrorY = false; defaultAnimationSpeed = 1; cycle = null; visible = true; shader = null; shaderUniforms = null; // Optional maps for builtin sprite effects (framework `image` instances). bumpMap = null; secondaryMap = null; // Dynamic lights for bumpmap: [{ x, y, color: [r,g,b]|{r,g,b} }, ...] lights = null; // RenderLayer name; null uses RenderLayer.DEFAULT_NAME ("default"). layer = null; constructor (parentObject, sprite) { this.gameObject = parentObject; this.sprite = sprite; this.shader = null; this.shaderUniforms = null; this.bumpMap = null; this.secondaryMap = null; this.lights = null; this.layer = null; } get layerName () { return this.layer || RenderLayer.DEFAULT_NAME; } update (deltaTime) { if (this.cycle) { if (!this.cycle.cycleSpeed || this.cycle.cycleSpeed == -1) { this.subImage = this.cycle.cycleArray[this.cycle.default]; this.cycle.current = this.cycle.default; return; } this.cycle.timer += deltaTime; if (this.cycle.timer > this.cycle.cycleSpeed) { this.cycle.timer -= this.cycle.cycleSpeed; let next; if (this.cycle.loop) { next = (this.cycle.current + 1) % this.cycle.cycleArray.length; } else { if (this.cycle.current + 1 >= this.cycle.cycleArray.length) { if (this.cycle.chain) { this.cycle.chainDefaultIndex = this.cycle.chainDefaultIndex || this.cycle.default; this.cycle.chainSpeed = this.cycle.chainSpeed || this.cycle.cycleSpeed; this.setAnimation(this.cycle.chain, this.cycle.chainDefaultIndex, this.cycle.chainSpeed); } return; } else { next = this.cycle.current + 1; } } this.updateCycleSprite(next); } } } updateCycleSprite (index) { this.subImage = this.cycle.cycleArray[index]; this.cycle.current = index; } draw () { if (this.sprite) { var offX = this.gameObject.scene.cameraPosition.x; var offY = this.gameObject.scene.cameraPosition.y; this.drawSprite(this.gameObject.transform.position.x + offX, this.gameObject.transform.position.y + offY, this.gameObject.transform.size.x, this.gameObject.transform.size.y, this.gameObject.transform.rotation); } } drawSprite (dx, dy, dw, dh, rotation) { if (isNaN(this.subImage)) { this.subImage = this.g_subImgOld; } else { this.g_subImgOld = this.subImage; } let textures = null; if (this.bumpMap || this.secondaryMap) { textures = {}; if (this.bumpMap) { textures.u_bump = this.bumpMap; } if (this.secondaryMap) { textures.u_secondary = this.secondaryMap; } } this.sprite.draw( this.gameObject.scene, Math.round(dx), Math.round(dy), dw, dh, rotation, this.mirrorX, this.mirrorY, this.alpha, this.subImage, this.shader, this.shaderUniforms, textures, this.lights ); } get currentAnimationName () { return this.cycle ? this.cycle.label : null; } setAnimation (label, defaultIndex = 0, cycleSpeed = -1) { if (cycleSpeed < 0) { cycleSpeed = this.defaultAnimationSpeed; } if (!this.sprite || !this.sprite.animationCycles || !this.sprite.animationCycles[label]) { console.warn("Renderer.setAnimation: unknown animation '" + label + "'"); return; } if (this.cycle) { if (this.cycle.label == label) { this.cycle.default = defaultIndex; this.cycle.cycleSpeed = cycleSpeed; return; } } const cycleData = this.sprite.animationCycles[label]; this.cycle = { label: label, cycleArray: cycleData.frames, default: defaultIndex, current: defaultIndex, cycleSpeed: cycleSpeed, loop: cycleData.loop, chain: cycleData.chain, chainDefaultIndex: cycleData.chainDefaultIndex, chainSpeed: cycleData.chainSpeed, timer: 0 }; this.subImage = this.cycle.cycleArray[this.cycle.current]; } setAnimationCycleSpeed (cycleSpeed) { if (this.cycle) { this.cycle.cycleSpeed = cycleSpeed; } } setSubImage (subImage) { this.subImage = subImage; this.cycle = null; } } /* * End File: * framework/engine/objectComponents/renderer.js */ /* * Start File: * framework/engine/image.js */ class image { subImages = null; subImagesPerRow = null; loop = false; chain = null; g_image = null; animationCycles = {}; constructor (image, subImgTotal = 1, perRow = 1, loop = false, chain = null) { subImgTotal = subImgTotal || 1; perRow = perRow || 1; this.subImages = subImgTotal; this.subImagesPerRow = perRow; this.g_image = image; this.loop = loop; this.chain = chain; this.cacheWidth = -1; this.cacheHeight = -1; // Keep the Image out of the DOM — canvas can draw from it directly. if (image && image.style) { image.style.display = "none"; } } draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage, shader, uniforms, textures, lights) { if (!scene.glContext || !this.g_image) { return; } // One hypot for frustum pad (was computed 4× per sprite). const pad = Math.sqrt(dw * dw + dh * dh); if (dx < -pad || dy < -pad || dx > scene.real_size.x + pad || dy > scene.real_size.y + pad) { return; } let glTextures = null; if (textures) { for (const name in textures) { if (!Object.prototype.hasOwnProperty.call(textures, name)) { continue; } const src = textures[name]; if (!src) { continue; } if (!glTextures) { glTextures = {}; } const htmlImage = src.g_image || src; glTextures[name] = scene.glContext.getTexture(htmlImage); } } const opts = this._drawOpts || (this._drawOpts = {}); opts.texture = scene.glContext.getTexture(this.g_image); opts.x = dx; opts.y = dy; opts.w = dw; opts.h = dh; opts.rotationDeg = rotation; opts.mirrorX = mirrorX; opts.mirrorY = mirrorY; opts.alpha = alpha; opts.uvRect = this.getUvRect(subImage); opts.shader = shader || scene.glContext.defaultShader; opts.uniforms = uniforms; opts.textures = glTextures; opts.lights = lights; scene.glContext.drawSprite(opts); } getUvRect (subImage) { if (!this._uvRects) { this._uvRects = []; } const index = subImage | 0; let rect = this._uvRects[index]; if (rect) { return rect; } const subImageData = this.getSubImage(index); const imgW = this.g_image.width; const imgH = this.g_image.height; rect = { u0: subImageData.sx / imgW, v0: subImageData.sy / imgH, u1: (subImageData.sx + subImageData.sw) / imgW, v1: (subImageData.sy + subImageData.sh) / imgH }; this._uvRects[index] = rect; return rect; } hasAnimationCycle (label) { return this.animationCycles[label] != null; } addAnimationCycle (label, cycle, loop, chain, chainDefaultIndex, chainSpeed) { this.animationCycles[label] = { frames: cycle, loop: loop, chain: chain, chainDefaultIndex: chainDefaultIndex, chainSpeed: chainSpeed }; } get width () { if (this.cacheWidth < 0) { this.cacheWidth = this.g_image.width / this.subImagesPerRow; } return this.cacheWidth; } get height () { if (this.cacheHeight < 0) { this.cacheHeight = this.g_image.height / (Math.ceil(this.subImages / this.subImagesPerRow) + 0); } return this.cacheHeight; } cacheWidth = -1; cacheHeight = -1; getSubImage (subImageIndex) { var subImage = Math.round(subImageIndex); subImage %= this.subImages; var c = subImage % this.subImagesPerRow; var r = Math.floor(subImage / this.subImagesPerRow); var sw = (this.g_image.width / this.subImagesPerRow); var sh = (this.g_image.height / Math.ceil(this.subImages / this.subImagesPerRow)); var sx = sw * c; var sy = sh * r; return { sw: sw, sh: sh, sx: sx, sy: sy }; } } /* * End File: * framework/engine/image.js */ /* * Start File: * framework/engine/gameobject.js */ class GameObject { transform = null; renderer = null; collider = null; scene = null; _layer = 0; tags = []; destroyed = false; constructor (x, y, sprite, layer = 0) { this.transform = new Transform(this, x, y, 1, 1, 0); this.renderer = new Renderer(this, sprite); this.collider = new Collider(this); this._layer = layer; } get layer () { return this._layer; } set layer (value) { if (this._layer === value) { return; } this._layer = value; if (this.scene) { this.scene.objectLayerChanged(this); } } initQuadtree (quadTree) { this.quadTree = quadTree; } checkQuadtree () { if (!this.quadTree) { return; } const x = this.transform.position.x; const y = this.transform.position.y; // Skip reinsert when the object has not moved since the last check. if (this.node && this._qtX === x && this._qtY === y) { return; } this._qtX = x; this._qtY = y; if (this.node) { if (x < this.node.x1 || x > this.node.x2 || y < this.node.y1 || y > this.node.y2) { this.quadTree.remove(this); this.quadTree.add(this); } } else { this.quadTree.add(this); } } update (deltaTime) { if (this.destroyed) { return; } this.transform.update(deltaTime); this.collider.update(deltaTime); this.renderer.update(deltaTime); this.checkQuadtree(); } destroy () { if (!this.destroyed) { this.onDestroy && this.onDestroy(); this.quadTree && this.quadTree.remove(this); this.scene && this.scene.removeObject(this); this.destroyed = true; } } draw () { if (this.destroyed) { return; } this.renderer.draw(); } } /* * End File: * framework/engine/gameobject.js */ /* * Start File: * framework/engine/scene.js */ class Scene { static idCount = 0; id = null; activeObjects = []; position = null; size = null; real_position = null; px = 0; py = 0; real_size = null; cameraPosition = null; parentScene = null; renderBackground = true; quadTree = null; pendingRemoval = []; _sortedActiveObjects = null; _sortDirty = true; /** Objects whose `layer` changed since the last draw-order rebuild. */ _layerChanged = []; /** * If more than this many objects change layer between draws, fall back to a * full in-place sort (cheaper than many splice reinserts on large lists). */ _layerChangeFullSortThreshold = 64; /** Reused per-draw-layer object lists (cleared + refilled each draw). */ _byLayer = null; _byLayerNames = null; g_primary = false; static DisplayModes = { absolute: 0, relativeToParent: 1 }; displayMode = Scene.DisplayModes.absolute; cv_canvas = null; glContext = null; destroyed = false; // Legacy: posts applied to the "default" layer when that layer has none of its own. postShaders = []; postTime = 0; // Ordered list of RenderLayer. Index 0 is drawn first (back). renderLayers = null; game = null; get primary () { return this.g_primary; } constructor (x, y, width, height, displayMode = 0) { Scene.idCount++; this.id = 'canvas_' + Scene.idCount; this.position = new vector(x, y); this.size = new vector(width, height); this.real_position = new vector(x, y); this.real_size = new vector(width, height); this.cameraPosition = new vector(0, 0); this.displayMode = displayMode; const body = document.body; body.insertAdjacentHTML('beforeend', ''); this.cv_canvas = document.getElementById(this.id); this.glContext = new GLContext(this.cv_canvas); this.postShaders = []; this.postTime = 0; this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)]; this.g_fixSize(); this.quadTree = new QuadTree(this.real_size.x, this.real_size.y); } /** * Replace the layer stack. Order in the array is draw order (first = back). * Each entry: RenderLayer, or { name, postShaders?, composite? }. */ setLayers (layerConfigs) { if (!layerConfigs || !layerConfigs.length) { this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)]; return this.renderLayers; } const layers = []; for (let i = 0; i < layerConfigs.length; i++) { const cfg = layerConfigs[i]; if (!cfg) { continue; } if (cfg instanceof RenderLayer) { layers.push(cfg); } else { layers.push(new RenderLayer(cfg.name, cfg)); } } if (!layers.length) { layers.push(new RenderLayer(RenderLayer.DEFAULT_NAME)); } this.renderLayers = layers; return this.renderLayers; } getLayer (name) { const layers = this.renderLayers || []; for (let i = 0; i < layers.length; i++) { if (layers[i].name === name) { return layers[i]; } } return null; } setPrimary () { this.game.setPrimaryScene(this); } onLoad () { } loadChildScene (scene) { scene.parentScene = this; this.game.loadScene(scene); } destroy () { if (this.destroyed) { return; } for (var i = 0; i < this.activeObjects.length; i++) { this.activeObjects[i].destroy(); } this.destroyed = true; if (this.game) { this.game.removeScene(this); } this.removeCanvas(); if (this.primary) { if (this.parentScene && !this.parentScene.destroyed) { this.parentScene.setPrimary(); } else if (this.game) { let promoted = null; for (let i = 0; i < this.game.activeScenes.length; i++) { const candidate = this.game.activeScenes[i]; if (candidate !== this && !candidate.destroyed) { promoted = candidate; break; } } if (promoted) { this.game.setPrimaryScene(promoted); } else { this.g_primary = false; } } else { this.g_primary = false; } } } removeCanvas () { var elem = this.cv_canvas || document.getElementById(this.id); if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } this.cv_canvas = null; this.glContext = null; } backgroundColor = { r: 255, g: 255, b: 255 }; get canvas () { return this.cv_canvas; } get context () { return this.glContext ? this.glContext.gl : null; } addObject (obj) { if (this.destroyed) { return; } this.activeObjects.push(obj); obj.scene = this; obj.initQuadtree(this.quadTree); obj.checkQuadtree(); if (this._sortedActiveObjects && !this._sortDirty && !this._layerChanged.length) { this.#insertSortedByLayer(this._sortedActiveObjects, obj); } else { this._sortDirty = true; } obj.addedToScene && obj.addedToScene(); return obj; } removeObject (obj) { if (this.activeObjects.indexOf(obj) >= 0) { if (!this.pendingRemoval.contains(obj)) { this.pendingRemoval.push(obj); } this._sortDirty = true; } if (this.quadTree === obj.quadTree) { this.quadTree.remove(obj); } } /** * Called when an object's draw-priority `layer` changes. * Batches small moves for splice-reinsert; floods into a full sort when many change. */ objectLayerChanged (obj) { if (!obj || this._sortDirty) { this._sortDirty = true; return; } this._layerChanged.push(obj); if (this._layerChanged.length > this._layerChangeFullSortThreshold) { this._sortDirty = true; this._layerChanged.length = 0; } } /** Force a full draw-order rebuild on the next draw (e.g. bulk external edits). */ markSortDirty () { this._sortDirty = true; this._layerChanged.length = 0; } /** First index with layer strictly greater than `layer` (insert after equal layers). */ #upperBoundByLayer (sorted, layer) { let lo = 0; let hi = sorted.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (sorted[mid].layer <= layer) { lo = mid + 1; } else { hi = mid; } } return lo; } #insertSortedByLayer (sorted, obj) { // New objects and layer moves land after existing equal layers so a // recently updated sprite draws on top of older ties (stable-with-recency). const at = this.#upperBoundByLayer(sorted, obj.layer); sorted.splice(at, 0, obj); } #reinsertSortedByLayer (sorted, obj) { const from = sorted.indexOf(obj); if (from >= 0) { sorted.splice(from, 1); } this.#insertSortedByLayer(sorted, obj); } /** * Ensure `_sortedActiveObjects` matches `activeObjects` ordered by `layer`. * Avoids allocating a fresh array every frame (no `slice().sort()`). */ #ensureDrawOrder () { const active = this.activeObjects; if (this._sortDirty || !this._sortedActiveObjects) { let sorted = this._sortedActiveObjects; if (!sorted) { sorted = new Array(active.length); this._sortedActiveObjects = sorted; } else if (sorted.length !== active.length) { sorted.length = active.length; } for (let i = 0; i < active.length; i++) { sorted[i] = active[i]; } sorted.sort((a, b) => a.layer - b.layer); this._sortDirty = false; this._layerChanged.length = 0; return; } if (!this._layerChanged.length) { return; } const changed = this._layerChanged; const sorted = this._sortedActiveObjects; for (let i = 0; i < changed.length; i++) { this.#reinsertSortedByLayer(sorted, changed[i]); } changed.length = 0; } update (deltaTime) { if (this.destroyed) { return; } this.postTime += deltaTime; for (let i = 0; i < this.activeObjects.length; i++) { this.activeObjects[i].update(deltaTime); } if (this.pendingRemoval.length) { for (let i = 0; i < this.pendingRemoval.length; i++) { const obj = this.pendingRemoval[i]; const index = this.activeObjects.indexOf(obj); if (index >= 0 && obj.destroyed) { this.activeObjects.removeAt(index); } } this.pendingRemoval.length = 0; this._sortDirty = true; this._layerChanged.length = 0; } this.quadTree.update(deltaTime); } g_fixSize () { if (this.displayMode == Scene.DisplayModes.relativeToParent) { if (this.parentScene) { this.real_position.x = this.parentScene.real_position.x + (this.position.x * this.parentScene.real_size.x); this.real_position.y = this.parentScene.real_position.y + (this.position.y * this.parentScene.real_size.y); this.real_size.x = this.parentScene.real_size.x * this.size.x; this.real_size.y = this.parentScene.real_size.y * this.size.y; } else { this.real_position.x = window.innerWidth * this.position.x; this.real_position.y = window.innerHeight * this.position.y; this.real_size.x = window.innerWidth * this.size.x; this.real_size.y = window.innerHeight * this.size.y; } } else if (this.displayMode == Scene.DisplayModes.absolute) { this.real_position.x = this.position.x; this.real_position.y = this.position.y; this.real_size.x = this.size.x; this.real_size.y = this.size.y; } const canvasW = Math.max(1, Math.round(this.real_size.x)); const canvasH = Math.max(1, Math.round(this.real_size.y)); let resized = false; if (this.canvas.width != canvasW) { this.canvas.width = canvasW; resized = true; } if (this.canvas.height != canvasH) { this.canvas.height = canvasH; resized = true; } // Changing canvas dimensions resets WebGL — rebuild helper/buffers/programs. if (resized || !this.glContext) { this.glContext = new GLContext(this.cv_canvas); } else { this.glContext.setSize(this.canvas.width, this.canvas.height); } if (this.px != this.real_position.x) { this.px = this.real_position.x; this.canvas.style.left = this.real_position.x + "px"; } if (this.py != this.real_position.y) { this.py = this.real_position.y; this.canvas.style.top = this.real_position.y + "px"; } } normalizePostShaderList (list) { if (!list || !list.length) { return []; } const passes = []; for (let i = 0; i < list.length; i++) { const entry = list[i]; if (!entry) { continue; } if (entry instanceof Shader || (entry.vertSource && entry.fragSource && entry.getProgramInfo)) { passes.push({ shader: entry, uniforms: null }); } else if (entry.shader) { const pass = { shader: entry.shader, uniforms: entry.uniforms || null }; if (entry.scale != null) { pass.scale = entry.scale; } passes.push(pass); } } return passes; } normalizePostShaders () { return this.normalizePostShaderList(this.postShaders); } getPostPassesForLayer (layer) { const fromLayer = this.normalizePostShaderList(layer.postShaders); if (fromLayer.length) { return fromLayer; } // Back-compat: scene.postShaders apply to the default layer only. if (layer.name === RenderLayer.DEFAULT_NAME) { return this.normalizePostShaders(); } return []; } draw () { if (this.destroyed || !this.glContext) { return; } this.g_fixSize(); const gl = this.glContext; const layers = this.renderLayers && this.renderLayers.length ? this.renderLayers : [new RenderLayer(RenderLayer.DEFAULT_NAME)]; // Canvas clear (background behind all layers). gl.endOffscreenPass(); if (this.renderBackground) { gl.clear( this.backgroundColor.r, this.backgroundColor.g, this.backgroundColor.b, 1 ); } else { gl.clearTransparent(); } this.#ensureDrawOrder(); const sortedActiveObjects = this._sortedActiveObjects; // Reuse per-layer buckets so we do not allocate new arrays every frame. const byLayer = this._byLayer || (this._byLayer = Object.create(null)); const byLayerNames = this._byLayerNames || (this._byLayerNames = []); for (let i = 0; i < byLayerNames.length; i++) { byLayer[byLayerNames[i]].length = 0; } byLayerNames.length = 0; for (let i = 0; i < sortedActiveObjects.length; i++) { const obj = sortedActiveObjects[i]; if (obj.destroyed || !obj.renderer || !obj.renderer.visible) { continue; } const name = obj.renderer.layerName; let bucket = byLayer[name]; if (!bucket) { bucket = []; byLayer[name] = bucket; } if (bucket.length === 0) { byLayerNames.push(name); } bucket.push(obj); } const builtins = { u_resolution: [gl._lastWidth, gl._lastHeight], u_time: this.postTime }; for (let li = 0; li < layers.length; li++) { const renderLayer = layers[li]; const layerObjects = byLayer[renderLayer.name]; if (!layerObjects || !layerObjects.length) { continue; } gl.beginOffscreenPass(); gl.clearTransparent(); for (let i = 0; i < layerObjects.length; i++) { layerObjects[i].draw(this.context); } const postPasses = this.getPostPassesForLayer(renderLayer); let texture = gl.colorTextures[0]; if (postPasses.length) { texture = gl.applyPostShaders(postPasses, builtins, { toCanvas: false }); } else { gl.endOffscreenPass(); } gl.blitToCanvas(texture, renderLayer.composite || "alpha"); } } } /* * End File: * framework/engine/scene.js */ /* * Start File: * framework/engine/game.js */ class Game { activeScenes = []; pendingRemoval = []; previousStep = 0; //used for calculating deltaTime isRunning = false; rafId = null; images = {}; shaders = {}; constructor () { this.previousStep = 0; this.activeScenes = []; this.isRunning = false; this.rafId = null; this.shaders = {}; this.update = this.update.bind(this); } startGame () { GameInput.g_init(); if (this.isRunning) { return; } this.isRunning = true; this.previousStep = Date.now(); this.update(); } stopGame () { this.isRunning = false; if (this.rafId != null) { cancelAnimationFrame(this.rafId); this.rafId = null; } } preloadImagesThenStart (imageData, onComplete, onError) { const cont = async () => { try { await this.preloadImages( imageData ); this.startGame(); onComplete && onComplete(); } catch (err) { console.error("GAME: Image preload failed.", err); onError && onError(err); } }; cont(); } setPrimaryScene (scene) { if (this.activeScenes.contains(scene)) { for (let i = 0; i < this.activeScenes.length; i++) { this.activeScenes[i].g_primary = false; } scene.g_primary = true; } } async preloadImages (imagesData) { const promises = []; const context = this; for (var imageData of imagesData) { if (context.images[imageData.name]) { console.warn("Image '" + imageData.name + "' is already loaded! (overwriting anyway)"); } promises.push(new Promise((resolve, reject) => { var img = new Image(); var imageContext = { name: imageData.name, subImgTotal: imageData.subImgTotal, perRow: imageData.perRow, loop: imageData.loop, chain: imageData.chain }; img.onload = function () { var finalImage = new image(img, imageContext.subImgTotal, imageContext.perRow, imageContext.loop, imageContext.chain); finalImage.name = imageContext.name; context.images[imageContext.name] = finalImage; resolve(); }; img.onerror = function () { reject(new Error("Failed to load image '" + imageContext.name + "' from " + imageData.url)); }; img.src = imageData.url; img.setAttribute("style", "display:none"); })); } await Promise.all(promises); console.log("all images loaded ", this.images); return this.images; } async preloadShaders (shadersData) { const context = this; const promises = []; for (const shaderData of shadersData) { if (!shaderData || !shaderData.name) { throw new Error("preloadShaders: each entry needs a name"); } if (!shaderData.frag) { throw new Error("preloadShaders: '" + shaderData.name + "' needs a frag path"); } if (context.shaders[shaderData.name]) { console.warn("Shader '" + shaderData.name + "' is already loaded! (overwriting anyway)"); } promises.push((async () => { let vertSource = shaderData.screen ? Shader.SCREEN_VERT : Shader.DEFAULT_VERT; if (shaderData.vert) { const vertResponse = await fetch(shaderData.vert); if (!vertResponse.ok) { throw new Error("Failed to load vertex shader '" + shaderData.name + "' from " + shaderData.vert); } vertSource = await vertResponse.text(); } const fragResponse = await fetch(shaderData.frag); if (!fragResponse.ok) { throw new Error("Failed to load fragment shader '" + shaderData.name + "' from " + shaderData.frag); } const fragSource = await fragResponse.text(); const shader = new Shader(vertSource, fragSource); shader.name = shaderData.name; shader.screen = !!shaderData.screen || vertSource === Shader.SCREEN_VERT; context.shaders[shaderData.name] = shader; })()); } await Promise.all(promises); console.log("all shaders loaded ", this.shaders); return this.shaders; } loadScene (scene) { if (this.activeScenes.length == 0) { scene.g_primary = true; } this.activeScenes.push(scene); scene.game = this; scene.onLoad(); } removeScene (scene) { if (this.activeScenes.indexOf(scene) >= 0) { if (!this.pendingRemoval.contains(scene)) { this.pendingRemoval.push(scene); } } } update () { this.previousStep = this.previousStep || 0; const stepTime = Date.now(); let stepTimeCurr = (stepTime - this.previousStep) * 0.001; stepTimeCurr = Math.min(stepTimeCurr, 0.1); if (isNaN(stepTimeCurr)) { stepTimeCurr = 0; } GameInput.g_updateKeys(); for (let i = 0; i < this.activeScenes.length; i++) { this.activeScenes[i].update(stepTimeCurr); this.activeScenes[i].draw(); } this.cleanActiveScenes(); this.previousStep = stepTime; TWEEN.update(); if (this.isRunning) { this.rafId = requestAnimationFrame(this.update); } } cleanActiveScenes () { if (this.pendingRemoval.length > 0) { for (let i = 0; i < this.pendingRemoval.length; i++) { const scene = this.pendingRemoval[i]; const index = this.activeScenes.indexOf(scene); if (index >= 0 && scene.destroyed) { this.activeScenes.removeAt(index); } } this.pendingRemoval.length = 0; } } } /* * End File: * framework/engine/game.js */