diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index dd6ff25de0..975c26cae3 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -21,6 +21,9 @@ - Tile maps: `TMXTileMap` and `TMXTilesetGroup`, for `TileMap` and `TilesetGroup` (the same classes) - Loader: `loader.getTMX`, for `loader.getTileMap` (the same function) +### Performance +- Rendering: sprites take about **45%** less CPU time to update and draw on WebGL and WebGPU (10,000 sprites on WebGL: 8.6 to 4.9 ms a frame), and about **60%** less when they rotate + ### Fixed - TypeScript: an asset's `data` accepts a parsed map object - Tile maps: a floating tile layer disappeared once the camera moved diff --git a/packages/melonjs/skills/melonjs-math/SKILL.md b/packages/melonjs/skills/melonjs-math/SKILL.md index db762f5f62..5290a413a9 100644 --- a/packages/melonjs/skills/melonjs-math/SKILL.md +++ b/packages/melonjs/skills/melonjs-math/SKILL.md @@ -273,7 +273,7 @@ another matrix: ```js m.setTransform(a, b, c, d, e, f, g, h, i, j, k, l, p, q, r, s); -m.copy(other); // Float32Array.set under the hood +m.copy(other); // sixteen plain stores, nothing allocated ``` Both are fine occasionally. In a per-frame loop, prefer writing `val` or diff --git a/packages/melonjs/src/geometries/observablePoint.ts b/packages/melonjs/src/geometries/observablePoint.ts index 61681dcfcc..618e70cf63 100644 --- a/packages/melonjs/src/geometries/observablePoint.ts +++ b/packages/melonjs/src/geometries/observablePoint.ts @@ -1,5 +1,15 @@ import { Point } from "./point.ts"; +/** + * What a revoked ObservablePoint holds instead of its Point: a proxy revoked + * here, so reading or writing the ObservablePoint after {@link ObservablePoint#revoke} + * throws a `TypeError`, as it does on any revoked proxy. A live ObservablePoint + * keeps a plain Point — no proxy on its hot path. + * @ignore + */ +const _revoked = Proxy.revocable(new Point(), {}); +_revoked.revoke(); + /** * Represents a point in a 2D coordinate system that can be observed for changes. */ @@ -11,17 +21,12 @@ export class ObservablePoint { * @ignore * @internal */ - private _callback: () => void; + private _callback: (() => void) | undefined; /** * @ignore * @internal */ private _point: Point; - /** - * @ignore - * @internal - */ - private _revoke: () => void; private callBackEnabled: boolean = true; @@ -34,22 +39,7 @@ export class ObservablePoint { * @param callback - The callback function to be called when the point changes. Default is undefined. */ constructor(x: number = 0, y: number = 0, callback?: () => void) { - const { proxy, revoke } = Proxy.revocable(new Point(x, y), { - set: (target, property, value) => { - if (property === "x" || property === "y") { - Reflect.set(target, property, value); - if (this.callBackEnabled) { - this._callback?.(); - } - return true; - } - return false; - }, - }); - - this.callBackEnabled = true; - this._revoke = revoke; - this._point = proxy; + this._point = new Point(x, y); if (callback) { this.setCallback(callback); @@ -98,6 +88,9 @@ export class ObservablePoint { */ set x(value: number) { this._point.x = value; + if (this.callBackEnabled) { + this._callback?.(); + } } /** @@ -113,6 +106,9 @@ export class ObservablePoint { */ set y(value: number) { this._point.y = value; + if (this.callBackEnabled) { + this._callback?.(); + } } /** @@ -144,9 +140,9 @@ export class ObservablePoint { } /** - * Revokes the proxy object, preventing further access to the ObservablePoint instance. + * Revokes this instance: reading or writing it afterwards throws a `TypeError`. */ revoke() { - this._revoke(); + this._point = _revoked.proxy; } } diff --git a/packages/melonjs/src/math/color.ts b/packages/melonjs/src/math/color.ts index ff08c63639..67cae643eb 100644 --- a/packages/melonjs/src/math/color.ts +++ b/packages/melonjs/src/math/color.ts @@ -531,7 +531,14 @@ export class Color { if (typeof color === "string") { return this.parseCSS(color); } else { - this.normalizedRGBA.set(color.normalizedRGBA); + // by element: `TypedArray#set` is a builtin call, several times + // slower than four stores, and this runs for every save/restore + const a = this.normalizedRGBA; + const b = color.normalizedRGBA; + a[0] = b[0]; + a[1] = b[1]; + a[2] = b[2]; + a[3] = b[3]; return this; } } diff --git a/packages/melonjs/src/math/matrix3d.ts b/packages/melonjs/src/math/matrix3d.ts index 1930bfcacd..a746ed5bb4 100644 --- a/packages/melonjs/src/math/matrix3d.ts +++ b/packages/melonjs/src/math/matrix3d.ts @@ -129,7 +129,31 @@ export class Matrix3d { * @returns Reference to this object for method chaining */ copy(m: Matrix3d) { - this.val.set(m.val); + // by element: `TypedArray#set` is a builtin call, about twice as slow + // as sixteen stores, and this runs for every save/restore + const a = this.val; + const b = m.val; + if (b.length !== 16) { + // not a 4x4 (a Matrix2d passed from JavaScript): as before + a.set(b); + return this; + } + a[0] = b[0]; + a[1] = b[1]; + a[2] = b[2]; + a[3] = b[3]; + a[4] = b[4]; + a[5] = b[5]; + a[6] = b[6]; + a[7] = b[7]; + a[8] = b[8]; + a[9] = b[9]; + a[10] = b[10]; + a[11] = b[11]; + a[12] = b[12]; + a[13] = b[13]; + a[14] = b[14]; + a[15] = b[15]; return this; } diff --git a/packages/melonjs/src/math/observableVector2d.ts b/packages/melonjs/src/math/observableVector2d.ts index 2548e94bb9..4feaf97aa3 100644 --- a/packages/melonjs/src/math/observableVector2d.ts +++ b/packages/melonjs/src/math/observableVector2d.ts @@ -1,21 +1,7 @@ -import { TupleToUnion } from "type-fest"; import { createPool } from "../system/pool.ts"; import { clamp, damp, lerp } from "./math.ts"; import { Vector2d } from "./vector2d.ts"; -const propertiesToObserve = ["x", "y"] as const; -type ObservableProperty = keyof Pick< - Vector2d, - TupleToUnion ->; -const setOfProperties = new Set(propertiesToObserve); - -const isObservableProperty = ( - property: string | symbol, -): property is ObservableProperty => { - return setOfProperties.has(property as any); -}; - /** * Working room for {@link ObservableVector2d.slerp}, which has to arrive at * the whole answer before publishing any of it. @@ -23,6 +9,16 @@ const isObservableProperty = ( */ const _slerpScratch = new Vector2d(); +/** + * What a revoked ObservableVector2d holds instead of its Vector2d: a proxy revoked + * here, so reading or writing the ObservableVector2d after {@link ObservableVector2d#revoke} + * throws a `TypeError`, as it does on any revoked proxy. A live ObservableVector2d + * keeps a plain Vector2d — no proxy on its hot path. + * @ignore + */ +const _revoked = Proxy.revocable(new Vector2d(), {}); +_revoked.revoke(); + /** * Represents a point in a 2D coordinate vector that can be observed for changes. * @category Math @@ -38,11 +34,6 @@ export class ObservableVector2d { * @internal */ private _vector2d: Vector2d; - /** - * @ignore - * @internal - */ - private _revoke: () => void; private callBackEnabled: boolean = true; @@ -53,21 +44,7 @@ export class ObservableVector2d { * @param callback - The callback function to be called when the point changes. Default is undefined. */ constructor(x: number = 0, y: number = 0, callback?: () => void) { - const { proxy, revoke } = Proxy.revocable(new Vector2d(x, y), { - set: (target, property, value) => { - if (isObservableProperty(property)) { - Reflect.set(target, property, value); - if (this.callBackEnabled) { - this._callback?.(); - } - return true; - } - return false; - }, - }); - - this._revoke = revoke; - this._vector2d = proxy; + this._vector2d = new Vector2d(x, y); if (callback) { this.setCallback(callback); @@ -116,6 +93,9 @@ export class ObservableVector2d { */ set x(value: number) { this._vector2d.x = value; + if (this.callBackEnabled) { + this._callback?.(); + } } /** @@ -131,6 +111,9 @@ export class ObservableVector2d { */ set y(value: number) { this._vector2d.y = value; + if (this.callBackEnabled) { + this._callback?.(); + } } /** @@ -555,10 +538,10 @@ export class ObservableVector2d { } /** - * Revokes the proxy object, preventing further access to the ObservablePoint instance. + * Revokes this instance: reading or writing it afterwards throws a `TypeError`. */ revoke() { - this._revoke(); + this._vector2d = _revoked.proxy; } } diff --git a/packages/melonjs/src/math/observableVector3d.ts b/packages/melonjs/src/math/observableVector3d.ts index a74528a8ef..d9262890f5 100644 --- a/packages/melonjs/src/math/observableVector3d.ts +++ b/packages/melonjs/src/math/observableVector3d.ts @@ -1,23 +1,9 @@ -import { TupleToUnion } from "type-fest"; import { Point } from "../geometries/point.ts"; import { createPool } from "../system/pool.ts"; import { clamp, damp, lerp } from "./math.ts"; import { Vector2d } from "./vector2d"; import { Vector3d } from "./vector3d"; -const propertiesToObserve = ["x", "y", "z"] as const; -type ObservableProperty = keyof Pick< - Vector3d, - TupleToUnion ->; -const setOfProperties = new Set(propertiesToObserve); - -const isObservableProperty = ( - property: string | symbol, -): property is ObservableProperty => { - return setOfProperties.has(property as any); -}; - /** * Working room for {@link ObservableVector3d.slerp}, which has to arrive at * the whole answer before publishing any of it. @@ -25,6 +11,16 @@ const isObservableProperty = ( */ const _slerpScratch = new Vector3d(); +/** + * What a revoked ObservableVector3d holds instead of its Vector3d: a proxy revoked + * here, so reading or writing the ObservableVector3d after {@link ObservableVector3d#revoke} + * throws a `TypeError`, as it does on any revoked proxy. A live ObservableVector3d + * keeps a plain Vector3d — no proxy on its hot path. + * @ignore + */ +const _revoked = Proxy.revocable(new Vector3d(), {}); +_revoked.revoke(); + /** * Represents a point in a 3D coordinate vector that can be observed for changes. * @category Math @@ -40,11 +36,6 @@ export class ObservableVector3d { * @internal */ private _vector3d: Vector3d; - /** - * @ignore - * @internal - */ - private _revoke: () => void; private callBackEnabled: boolean = true; @@ -61,21 +52,7 @@ export class ObservableVector3d { z: number = 0, callback?: () => void, ) { - const { proxy, revoke } = Proxy.revocable(new Vector3d(x, y, z), { - set: (target, property, value) => { - if (isObservableProperty(property)) { - Reflect.set(target, property, value); - if (this.callBackEnabled) { - this._callback?.(); - } - return true; - } - return false; - }, - }); - - this._revoke = revoke; - this._vector3d = proxy; + this._vector3d = new Vector3d(x, y, z); if (callback) { this.setCallback(callback); @@ -128,6 +105,9 @@ export class ObservableVector3d { */ set x(value: number) { this._vector3d.x = value; + if (this.callBackEnabled) { + this._callback?.(); + } } /** @@ -143,6 +123,9 @@ export class ObservableVector3d { */ set y(value: number) { this._vector3d.y = value; + if (this.callBackEnabled) { + this._callback?.(); + } } get z() { @@ -151,6 +134,9 @@ export class ObservableVector3d { set z(value: number) { this._vector3d.z = value; + if (this.callBackEnabled) { + this._callback?.(); + } } /** @@ -637,10 +623,10 @@ export class ObservableVector3d { } /** - * Revokes the proxy object, preventing further access to the ObservablePoint instance. + * Revokes this instance: reading or writing it afterwards throws a `TypeError`. */ revoke() { - this._revoke(); + this._vector3d = _revoked.proxy; } } diff --git a/packages/melonjs/src/physics/bounds.ts b/packages/melonjs/src/physics/bounds.ts index 51875e43d3..1ce5785233 100644 --- a/packages/melonjs/src/physics/bounds.ts +++ b/packages/melonjs/src/physics/bounds.ts @@ -347,15 +347,51 @@ export class Bounds { } return; } - // transformed: walk the 4 corners through `m` via `addPoint`. - // Reuse the module-level scratch — `m.apply` mutates in place - // and `addPoint` reads x/y immediately after, so the same Point - // can shuttle through all four corners. - const v = _addFrameScratch; - this.addPoint(v.set(x0, y0), m); - this.addPoint(v.set(x1, y0), m); - this.addPoint(v.set(x0, y1), m); - this.addPoint(v.set(x1, y1), m); + // affine (every Matrix2d, and a Matrix3d with no perspective, whose w + // is 1): each corner gets the same arithmetic `apply` gives a 2D + // point (z = 1), in the same order, without the scratch point, the + // checks for a z and the divide by w + const a = m.val; + let xa: number; + let ya: number; + let xb: number; + let yb: number; + let xc: number; + let yc: number; + let xd: number; + let yd: number; + if (a.length === 9) { + xa = x0 * a[0] + y0 * a[3] + a[6]; + ya = x0 * a[1] + y0 * a[4] + a[7]; + xb = x1 * a[0] + y0 * a[3] + a[6]; + yb = x1 * a[1] + y0 * a[4] + a[7]; + xc = x0 * a[0] + y1 * a[3] + a[6]; + yc = x0 * a[1] + y1 * a[4] + a[7]; + xd = x1 * a[0] + y1 * a[3] + a[6]; + yd = x1 * a[1] + y1 * a[4] + a[7]; + } else if (a[3] === 0 && a[7] === 0 && a[11] === 0 && a[15] === 1) { + xa = a[0] * x0 + a[4] * y0 + a[8] + a[12]; + ya = a[1] * x0 + a[5] * y0 + a[9] + a[13]; + xb = a[0] * x1 + a[4] * y0 + a[8] + a[12]; + yb = a[1] * x1 + a[5] * y0 + a[9] + a[13]; + xc = a[0] * x0 + a[4] * y1 + a[8] + a[12]; + yc = a[1] * x0 + a[5] * y1 + a[9] + a[13]; + xd = a[0] * x1 + a[4] * y1 + a[8] + a[12]; + yd = a[1] * x1 + a[5] * y1 + a[9] + a[13]; + } else { + // perspective: each corner divides by its own w + const v = _addFrameScratch; + this.addPoint(v.set(x0, y0), m); + this.addPoint(v.set(x1, y0), m); + this.addPoint(v.set(x0, y1), m); + this.addPoint(v.set(x1, y1), m); + return; + } + // Math.min/max, as `addPoint` folds them: a NaN corner spreads + this.min.x = Math.min(this.min.x, xa, xb, xc, xd); + this.max.x = Math.max(this.max.x, xa, xb, xc, xd); + this.min.y = Math.min(this.min.y, ya, yb, yc, yd); + this.max.y = Math.max(this.max.y, ya, yb, yc, yd); } /** diff --git a/packages/melonjs/src/renderable/container.js b/packages/melonjs/src/renderable/container.js index 3190029550..ed1b558d48 100644 --- a/packages/melonjs/src/renderable/container.js +++ b/packages/melonjs/src/renderable/container.js @@ -70,6 +70,28 @@ function isPerspective(renderer) { return renderer._orthographic3d === true && !(renderer._screenSpaceDepth > 0); } +/** + * Whether `obj` is visible: {@link Camera2d#isVisible} asked of the stage's + * cameras in the order they were added, and settled by the first one that + * sees it. Its answer is {@link Renderable#inViewport}, whose changes fire + * {@link Renderable#onVisibilityChange}. A plain loop, not a `forEach` + * callback: this runs for every child of every container, every frame. + * @param {Map} cameras - the stage's cameras + * @param {Renderable} obj - the child to test + * @param {boolean} floating - whether it draws in screen space + * @returns {boolean} true if a camera sees it + * @ignore + * @internal + */ +function isVisible(cameras, obj, floating) { + for (const camera of cameras.values()) { + if (camera.isVisible(obj, floating)) { + return true; + } + } + return false; +} + /** * Send `onActivateEvent` to a child that has not had one yet. * @ignore @@ -1706,7 +1728,6 @@ export default class Container extends Renderable { * @returns {boolean} true if the Container is dirty */ update(dt) { - let isFloating = false; const isPaused = state.isPaused(); // The frame boundary, and the reason the counter below cannot strand // the world. Saving and restoring it around a child is idempotent but @@ -1734,8 +1755,8 @@ export default class Container extends Renderable { // its animation, physics and timers. // // Iterating a snapshot fixes that at the cost of one array copy per - // container per frame, which is nothing beside the per-child closure - // the camera-visibility loop below already allocates. Children added + // container per frame, which is nothing beside the per-child work + // the camera-visibility check below already does. Children added // during the pass are still not visited until the next frame, matching // the previous behaviour (the loop started from a captured length). const pass = children.slice(); @@ -1766,7 +1787,7 @@ export default class Container extends Renderable { continue; } - isFloating = globalFloatingCounter > 0 || obj.floating; + const isFloating = globalFloatingCounter > 0 || obj.floating; if (isFloating) { globalFloatingCounter++; } @@ -1790,13 +1811,7 @@ export default class Container extends Renderable { // local and assign ONCE: assigning `false` then `true` through // the setter would fire `onVisibilityChange` (a change-detecting // setter) twice per frame for every continuously-visible object - let inViewport = false; - // iterate through all cameras - cameras.forEach((camera) => { - if (camera.isVisible(obj, isFloating)) { - inViewport = true; - } - }); + let inViewport = isVisible(cameras, obj, isFloating); // A container measured from its children re-measures itself at // the end of its own update (below), and only runs that update // while it is in view. Culled, it would keep the bounds of where @@ -1810,11 +1825,7 @@ export default class Container extends Renderable { typeof obj.updateBounds === "function" ) { obj.updateBounds(); - cameras.forEach((camera) => { - if (camera.isVisible(obj, isFloating)) { - inViewport = true; - } - }); + inViewport = isVisible(cameras, obj, isFloating); } obj.inViewport = inViewport; diff --git a/packages/melonjs/src/renderable/renderable.js b/packages/melonjs/src/renderable/renderable.js index b6821ff041..450c59494e 100644 --- a/packages/melonjs/src/renderable/renderable.js +++ b/packages/melonjs/src/renderable/renderable.js @@ -762,8 +762,8 @@ export default class Renderable extends Rect { * camera.setPosition(0, 0, -300).lookAt(player); */ setPosition(x, y, z) { - // ONE batched write, not three component assignments. `pos` is a - // proxied observable: every component write fires its callback, which + // ONE batched write, not three component assignments. `pos` is an + // observable: every component write fires its callback, which // runs `updateBounds()`. `set` mutes that and fires once, so this // costs one bounds recompute where assigning `pos.x`, `pos.y` and // `depth` in turn costs three. That matters because the paths this diff --git a/packages/melonjs/src/video/gpu/quadcorners.ts b/packages/melonjs/src/video/gpu/quadcorners.ts index f00550fe8f..fbc0eac2b2 100644 --- a/packages/melonjs/src/video/gpu/quadcorners.ts +++ b/packages/melonjs/src/video/gpu/quadcorners.ts @@ -41,6 +41,37 @@ export function transformQuadCorners( h: number, z: number, ): Vector3d[] { + if (m && !m.isIdentity()) { + const a = m.val; + if (a[3] === 0 && a[7] === 0 && a[11] === 0 && a[15] === 1) { + // affine (every 2D transform, and a Camera3d view), so w is 1: + // each corner gets the same arithmetic `apply` gives it, in the + // same order, without its checks and its divide by w + const x1 = x + w; + const y1 = y + h; + corners[0].set( + a[0] * x + a[4] * y + a[8] * z + a[12], + a[1] * x + a[5] * y + a[9] * z + a[13], + a[2] * x + a[6] * y + a[10] * z + a[14], + ); + corners[1].set( + a[0] * x1 + a[4] * y + a[8] * z + a[12], + a[1] * x1 + a[5] * y + a[9] * z + a[13], + a[2] * x1 + a[6] * y + a[10] * z + a[14], + ); + corners[2].set( + a[0] * x + a[4] * y1 + a[8] * z + a[12], + a[1] * x + a[5] * y1 + a[9] * z + a[13], + a[2] * x + a[6] * y1 + a[10] * z + a[14], + ); + corners[3].set( + a[0] * x1 + a[4] * y1 + a[8] * z + a[12], + a[1] * x1 + a[5] * y1 + a[9] * z + a[13], + a[2] * x1 + a[6] * y1 + a[10] * z + a[14], + ); + return corners; + } + } corners[0].set(x, y, z); corners[1].set(x + w, y, z); corners[2].set(x, y + h, z); diff --git a/packages/melonjs/src/video/renderer.js b/packages/melonjs/src/video/renderer.js index 41d5ab426d..47b21029ad 100644 --- a/packages/melonjs/src/video/renderer.js +++ b/packages/melonjs/src/video/renderer.js @@ -47,6 +47,14 @@ const drawnTransform = new Float64Array(6); */ const _savedView = new Matrix3d(); +/** + * The effect chain of a renderable that has none, shared rather than built + * for each one drawn; frozen, as it is handed out to every caller. + * @ignore + * @internal + */ +const NO_EFFECTS = Object.freeze([]); + /** * a base renderer object * @category Rendering @@ -1650,6 +1658,10 @@ export default class Renderer { * @internal */ beginPostEffect(renderable) { + if (renderable.postEffects.length === 0) { + this.customShader = undefined; + return false; + } // on Canvas, only set customShader for single-effect fast path const effects = renderable.postEffects.filter((fx) => { return fx.enabled !== false; @@ -2139,6 +2151,11 @@ export default class Renderer { * @internal */ _effectChainFor(renderable) { + // nearly every renderable has none: nothing to build for it, and + // this runs twice for every one drawn (as it starts and as it ends) + if (renderable.postEffects.length === 0) { + return NO_EFFECTS; + } const effects = renderable.postEffects.filter((fx) => { return fx.enabled !== false; }); diff --git a/packages/melonjs/tests/affine-corners-exact.spec.js b/packages/melonjs/tests/affine-corners-exact.spec.js new file mode 100644 index 0000000000..48ebded3fe --- /dev/null +++ b/packages/melonjs/tests/affine-corners-exact.spec.js @@ -0,0 +1,103 @@ +import { describe, expect, it } from "vitest"; +import { Bounds, Matrix2d, Matrix3d, Point, Vector3d } from "../src/index.js"; +import { transformQuadCorners } from "../src/video/gpu/quadcorners.ts"; + +// a seeded generator, so a failure can be replayed +let seed = 12345; +const rnd = () => { + seed = (seed * 16807) % 2147483647; + return seed / 2147483647; +}; +const pick = () => { + const r = rnd(); + // mostly ordinary values, some awkward ones + if (r < 0.05) { + return 0; + } + if (r < 0.08) { + return -0; + } + if (r < 0.1) { + return 0.1; + } + return (rnd() - 0.5) * 2000; +}; + +const affine3d = () => { + const m = new Matrix3d(); + m.translate(pick(), pick(), pick()); + m.rotate(rnd() * 7); + m.scale(pick() / 100 || 1, pick() / 100 || 1, 1); + if (rnd() < 0.3) { + // a 3D turn, as a Camera3d view has + m.rotate(rnd() * 7, new Vector3d(rnd(), rnd(), rnd()).normalize()); + } + return m; +}; + +const affine2d = () => { + const m = new Matrix2d(); + m.translate(pick(), pick()); + m.rotate(rnd() * 7); + m.scale(pick() / 100 || 1, pick() / 100 || 1); + return m; +}; + +// what the corners were before: four `apply` calls +const referenceCorners = (m, x, y, w, h, z) => { + const c = [ + new Vector3d(x, y, z), + new Vector3d(x + w, y, z), + new Vector3d(x, y + h, z), + new Vector3d(x + w, y + h, z), + ]; + if (m && !m.isIdentity()) { + for (const v of c) { + m.apply(v); + } + } + return c; +}; + +// what addFrame did before for a transform: four `addPoint` calls +const referenceFrame = (m, x0, y0, x1, y1) => { + const b = new Bounds(); + b.clear(); + const p = new Point(); + b.addPoint(p.set(x0, y0), m); + b.addPoint(p.set(x1, y0), m); + b.addPoint(p.set(x0, y1), m); + b.addPoint(p.set(x1, y1), m); + return [b.min.x, b.min.y, b.max.x, b.max.y]; +}; + +describe("affine fast paths give the same bits as apply", () => { + it("transformQuadCorners matches four Matrix3d#apply", () => { + for (let i = 0; i < 20000; i++) { + const m = affine3d(); + const args = [pick(), pick(), pick(), pick(), pick()]; + const want = referenceCorners(m, ...args); + const got = transformQuadCorners(m, ...args); + for (let k = 0; k < 4; k++) { + expect(Object.is(got[k].x, want[k].x)).toBe(true); + expect(Object.is(got[k].y, want[k].y)).toBe(true); + expect(Object.is(got[k].z, want[k].z)).toBe(true); + } + } + }); + + it("Bounds#addFrame matches four addPoint, for a Matrix3d and a Matrix2d", () => { + for (let i = 0; i < 20000; i++) { + const m = i % 2 === 0 ? affine3d() : affine2d(); + const f = [pick(), pick(), pick(), pick()]; + const want = referenceFrame(m, ...f); + const b = new Bounds(); + b.clear(); + b.addFrame(...f, m); + const got = [b.min.x, b.min.y, b.max.x, b.max.y]; + for (let k = 0; k < 4; k++) { + expect(Object.is(got[k], want[k])).toBe(true); + } + } + }); +}); diff --git a/packages/melonjs/tests/camera-minimap-coords.spec.js b/packages/melonjs/tests/camera-minimap-coords.spec.js index 9e20708860..4819bc632d 100644 --- a/packages/melonjs/tests/camera-minimap-coords.spec.js +++ b/packages/melonjs/tests/camera-minimap-coords.spec.js @@ -81,7 +81,7 @@ describe("Camera2d coordinate conversion with an offset world", () => { * draw a 20px square at (10, 10) to (30, 30) in a world offset by * `worldX`, through the main camera and, if given, a minimap */ - const drawScene = ({ worldX = 20, minimap } = {}) => { + const drawScene = ({ worldX = 20, minimap, squareY = 10 } = {}) => { camera.setBounds(0, 0, 1000, 1000); camera.moveTo(0, 0); let view; @@ -97,7 +97,7 @@ describe("Camera2d coordinate conversion with an offset world", () => { stage.cameras.set("minimap", view); } app.world.pos.set(worldX, 0, 0); - app.world.addChild(new Square(10, 10, 20, "#0000ff"), 1); + app.world.addChild(new Square(10, squareY, 20, "#0000ff"), 1); app.world.sortNow(); app.world.update(0); app.repaint(); @@ -175,6 +175,17 @@ describe("Camera2d coordinate conversion with an offset world", () => { }); }); + it("a minimap draws only inside its own corner", () => { + // the square crosses the minimap's bottom edge, so it is drawn, and + // what lies past that edge is cut off: below the corner is the main + // view's, where there is nothing + drawScene({ minimap: {}, squareY: 30 }); + const empty = at({ x: 5, y: 95 }); + expect(empty).not.toBe(BLUE); + expect(at({ x: 80, y: 35 })).toBe(BLUE); + expect(at({ x: 80, y: 45 })).toBe(empty); + }); + it("without a world offset, every camera is unchanged", () => { const view = drawScene({ worldX: 0, minimap: { zoom: 0.5 } }); const main = camera.worldToLocal(...CENTRE, new Vector2d()); diff --git a/packages/melonjs/tests/container-camera-visibility.spec.js b/packages/melonjs/tests/container-camera-visibility.spec.js new file mode 100644 index 0000000000..485ec40884 --- /dev/null +++ b/packages/melonjs/tests/container-camera-visibility.spec.js @@ -0,0 +1,167 @@ +/** + * Container#update steps a child only while a camera sees it: it asks the + * stage's cameras in the order they were added, marks the child `inViewport` + * as soon as one says yes, and skips the update of one that none of them sees. + * + * Games add cameras (a minimap, a radar, a split screen) and may override + * `isVisible` on one, so these cases update a world seen through two cameras, + * the second of which marks what it sees, and check for each child whether + * it was stepped and which camera was asked about it. + */ +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { + Application, + boot, + Camera2d, + Container, + Renderable, + state, + video, +} from "../src/index.js"; + +/** a 20 x 20 enemy that counts the frames it was stepped */ +class Enemy extends Renderable { + constructor(name, x, y) { + super(x, y, 20, 20); + this.anchorPoint.set(0, 0); + this.name = name; + this.steps = 0; + } + update(dt) { + this.steps++; + return super.update(dt); + } +} + +/** a second camera that marks every renderable it sees, as a radar would */ +class Radar extends Camera2d { + constructor() { + super(0, 0, 100, 100); + this.name = "radar"; + this.autoResize = false; + this.marked = new Set(); + } + isVisible(obj, floating) { + const seen = super.isVisible(obj, floating); + if (seen) { + this.marked.add(obj.name); + } + return seen; + } +} + +describe("a child is updated while any camera sees it", () => { + let app; + let stage; + let camera; + + beforeAll(async () => { + boot(); + app = new Application(100, 100, { + parent: "screen", + renderer: video.CANVAS, + scale: "1.0", + consoleHeader: false, + }); + await app.init(); + stage = state.current(); + camera = stage.cameras.get("default"); + }); + + afterEach(() => { + stage.cameras.delete("radar"); + app.world.reset(); + }); + + afterAll(() => { + return app?.destroy(); + }); + + /** + * the main camera on world x 0 to 100, a radar on x 50 to 150, and an + * enemy seen by both, by each alone, and by neither + */ + const scene = () => { + camera.setBounds(0, 0, 5000, 5000); + camera.moveTo(0, 0); + const radar = new Radar(); + radar.setBounds(0, 0, 5000, 5000); + radar.moveTo(50, 0); + stage.cameras.set("radar", radar); + const enemies = { + both: new Enemy("both", 60, 40), + main: new Enemy("main", 10, 40), + radar: new Enemy("radar", 120, 40), + neither: new Enemy("neither", 400, 400), + }; + for (const enemy of Object.values(enemies)) { + app.world.addChild(enemy); + } + return { radar, enemies }; + }; + + const stepsOf = (enemies) => { + return Object.fromEntries( + Object.entries(enemies).map(([name, e]) => { + return [name, e.steps]; + }), + ); + }; + + it("one seen by either camera is updated, one seen by neither is not", () => { + const { enemies } = scene(); + app.world.update(16); + expect(stepsOf(enemies)).toEqual({ + both: 1, + main: 1, + radar: 1, + neither: 0, + }); + expect(enemies.main.inViewport).toBe(true); + expect(enemies.radar.inViewport).toBe(true); + expect(enemies.neither.inViewport).toBe(false); + }); + + it("the first camera that sees a child settles it", () => { + const { radar } = scene(); + app.world.update(16); + // the main camera, asked first, saw "both" and "main": the radar is + // asked only about the others, and of those it sees "radar" + expect([...radar.marked]).toEqual(["radar"]); + }); + + it("frame after frame, an enemy is stepped only while a camera sees it", () => { + const { enemies } = scene(); + const walker = enemies.neither; + // out of view, into the radar's, into the main view, then out again + const path = [ + [400, 400], + [120, 40], + [10, 40], + [400, 40], + ]; + const stepped = []; + for (const [x, y] of path) { + walker.pos.set(x, y, walker.pos.z); + const before = walker.steps; + app.world.update(16); + stepped.push(walker.steps - before); + } + expect(stepped).toEqual([0, 1, 1, 0]); + }); + + it("a HUD's children are tested on screen, wherever the cameras look", () => { + // a floating HUD draws in screen space, so its labels are seen at + // any camera position, here far from the world origin + camera.setBounds(0, 0, 5000, 5000); + camera.moveTo(3000, 3000); + const hud = new Container(0, 0, 100, 100); + hud.floating = true; + const label = new Enemy("label", 10, 10); + hud.addChild(label); + app.world.addChild(hud); + app.world.update(16); + expect(label.inViewport).toBe(true); + expect(label.steps).toBe(1); + }); +}); diff --git a/packages/melonjs/tests/mat3d.spec.ts b/packages/melonjs/tests/mat3d.spec.ts index 4ffbf1377c..6f9ea45d18 100644 --- a/packages/melonjs/tests/mat3d.spec.ts +++ b/packages/melonjs/tests/mat3d.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { Matrix3d, Vector2d, Vector3d } from "../src/index.js"; +import { Matrix2d, Matrix3d, Vector2d, Vector3d } from "../src/index.js"; describe("Matrix3d", () => { it("should be initialized to a 4x4 identity matrix", () => { @@ -247,4 +247,19 @@ describe("Matrix3d", () => { // and we should have back the original vector values expect(matA.equals(matB)).toEqual(true); }); + + it("copy, given a 3x3 Matrix2d from JavaScript, takes its nine values", () => { + // typed to take a Matrix3d, but plain JavaScript can pass anything: a + // Matrix2d fills the first nine entries and leaves the other seven + const mat2 = new Matrix2d(); + for (let i = 0; i < 9; i++) { + mat2.val[i] = i + 2; + } + // @ts-expect-error a Matrix2d is not a Matrix3d + const matB = new Matrix3d().copy(mat2); + + expect(Array.from(matB.val)).toEqual([ + 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 0, 0, 0, 1, + ]); + }); }); diff --git a/packages/melonjs/tests/renderable-position-updates.spec.js b/packages/melonjs/tests/renderable-position-updates.spec.js new file mode 100644 index 0000000000..ea7ccbc597 --- /dev/null +++ b/packages/melonjs/tests/renderable-position-updates.spec.js @@ -0,0 +1,161 @@ +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { + Application, + boot, + Container, + Renderable, + Vector2d, + video, +} from "../src/index.js"; + +/** + * Moving a renderable the ways games do, and what each move does to its + * bounds. + * + * `pos` and `anchorPoint` report every write to their renderable, which runs + * `updateBounds()`: that is how the bounds keep up with a moving object. These + * cases move one the ways the examples do (`pos.x =`, `pos.x +=`, `pos.set`, + * `setPosition`, `add`, `setMuted`, `anchorPoint.set`), inside a container that + * is itself offset, and check after each move both where the bounds are and + * how many times they were recomputed: once per write, once per batched call, + * never for `setMuted`. + * + * Each catches a different mistake in how a write is reported: a report that + * goes missing (the bounds stay behind), one sent before the value is stored + * (the bounds trail by one move), one sent twice, or one sent per coordinate + * (a `set` recomputing three or four times). + */ +describe("moving a renderable keeps its bounds up to date", () => { + let app; + + beforeAll(async () => { + boot(); + app = new Application(800, 600, { + parent: "screen", + scale: "auto", + renderer: video.CANVAS, + }); + await app.init(); + }); + + // a 32 x 16 renderable at (10, 20), centred anchor, in a container at (100, 50) + const setup = () => { + const parent = new Container(100, 50, 400, 300); + const child = new Renderable(10, 20, 32, 16); + parent.addChild(child); + child.updateBounds(); + const updates = vi.spyOn(child, "updateBounds"); + return { child, updates }; + }; + + // the absolute position, less the anchor offset + const expectBoundsAt = (child, x, y) => { + const b = child.getBounds(); + expect(b.left).toBe(100 + x - 32 * child.anchorPoint.x); + expect(b.top).toBe(50 + y - 16 * child.anchorPoint.y); + expect(b.width).toBe(32); + expect(b.height).toBe(16); + }; + + it("a write to one coordinate moves the bounds at once, with one recompute", () => { + const { child, updates } = setup(); + + child.pos.x = 30; + expect(updates).toHaveBeenCalledTimes(1); + expectBoundsAt(child, 30, 20); + + child.pos.y = 45; + expect(updates).toHaveBeenCalledTimes(2); + expectBoundsAt(child, 30, 45); + }); + + it("moving by a speed every frame keeps the bounds with the object", () => { + const { child, updates } = setup(); + + for (let frame = 1; frame <= 60; frame++) { + child.pos.x += 2; + child.pos.y -= 1; + expectBoundsAt(child, 10 + 2 * frame, 20 - frame); + } + expect(updates).toHaveBeenCalledTimes(120); + }); + + it("set, setPosition and add move every coordinate with one recompute", () => { + const { child, updates } = setup(); + + child.pos.set(40, 60, 0); + expect(updates).toHaveBeenCalledTimes(1); + expectBoundsAt(child, 40, 60); + + child.setPosition(70, 80); + expect(updates).toHaveBeenCalledTimes(2); + expectBoundsAt(child, 70, 80); + + child.pos.add(new Vector2d(5, -5)); + expect(updates).toHaveBeenCalledTimes(3); + expectBoundsAt(child, 75, 75); + }); + + it("setMuted moves the object without a recompute, until one is asked for", () => { + const { child, updates } = setup(); + + child.pos.setMuted(200, 100, 0); + expect(updates).not.toHaveBeenCalled(); + expectBoundsAt(child, 10, 20); + + child.updateBounds(); + expectBoundsAt(child, 200, 100); + }); + + it("anchorPoint.set moves the bounds around the same position, with one recompute", () => { + const { child, updates } = setup(); + + child.anchorPoint.set(0, 0); + expect(updates).toHaveBeenCalledTimes(1); + expect(child.getBounds().left).toBe(110); + expect(child.getBounds().top).toBe(70); + + child.anchorPoint.x = 1; + expect(updates).toHaveBeenCalledTimes(2); + expect(child.getBounds().left).toBe(78); + }); + + it("an object that moves itself in update() keeps its bounds through the game loop", () => { + class Walker extends Renderable { + constructor() { + super(100, 100, 32, 16); + } + update() { + this.pos.x += 2; + return true; + } + } + const walker = new Walker(); + app.world.addChild(walker); + + for (let frame = 0; frame < 30; frame++) { + app.world.update(16); + } + expect(walker.pos.x).toBe(160); + expect(walker.getBounds().left).toBe(160 - 16); + expect(walker.getBounds().top).toBe(100 - 8); + + app.world.removeChildNow(walker); + }); + + it("an anchorPoint kept after destroy() refuses to be used", () => { + const renderable = new Renderable(0, 0, 8, 8); + const anchor = renderable.anchorPoint; + renderable.destroy(); + + expect(() => { + return anchor.x; + }).toThrow(TypeError); + expect(() => { + anchor.x = 1; + }).toThrow(TypeError); + expect(() => { + anchor.set(1, 1); + }).toThrow(TypeError); + }); +}); diff --git a/packages/melonjs/tests/renderable.spec.js b/packages/melonjs/tests/renderable.spec.js index bc7c86d4ec..7e83045843 100644 --- a/packages/melonjs/tests/renderable.spec.js +++ b/packages/melonjs/tests/renderable.spec.js @@ -334,6 +334,30 @@ describe("Renderable", () => { expect(renderer.customShader).toBeUndefined(); }); + it("a child with no effects of its own drops its container's shader", () => { + // in the order Container#draw calls them: the child draws inside + // its container's preDraw/postDraw, and starts without its shader + const renderer = app.renderer; + const group = new Container(0, 0, 100, 100); + const effect = { enabled: true }; + group.addPostEffect(effect); + const child = new Renderable(10, 10, 10, 10); + + // recorded, and checked once every save has its restore, so a + // failure here leaves the renderer as the next test expects it + const seen = []; + group.preDraw(renderer); + seen.push(renderer.customShader); + child.preDraw(renderer); + seen.push(renderer.customShader); + child.postDraw(renderer); + seen.push(renderer.customShader); + group.postDraw(renderer); + seen.push(renderer.customShader); + + expect(seen).toEqual([effect, undefined, effect, undefined]); + }); + it("disabled single effect should not be set as customShader", () => { const renderer = app.renderer; const renderable = new Renderable(0, 0, 100, 100); diff --git a/packages/melonjs/tests/renderer-state-between-sprites.spec.js b/packages/melonjs/tests/renderer-state-between-sprites.spec.js new file mode 100644 index 0000000000..eee843159f --- /dev/null +++ b/packages/melonjs/tests/renderer-state-between-sprites.spec.js @@ -0,0 +1,192 @@ +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { + Application, + boot, + Container, + Matrix3d, + Renderable, + Vector3d, + video, +} from "../src/index.js"; + +/** + * Every renderable draws from the settings its parent left on the renderer, + * never from what the one drawn before it changed. + * + * `preDraw()` saves the renderer's color, tint, opacity and transform, and + * `postDraw()` copies them back. These cases draw a renderable that changes + * all of them the ways games do (a tinted, faded card turned in 3D, whose + * `draw()` sets its own color and opacity and transforms the renderer) between + * two plain ones, then check that the second plain one sees exactly what the + * first one saw, every number of it. The card's last transform has all + * sixteen entries set, and the case checks that the card really changed every + * value, so a copy that misses one of them cannot go unseen. + */ +describe("a renderable leaves the renderer as it found it", () => { + let app; + let order; + + beforeAll(async () => { + boot(); + app = new Application(200, 150, { + parent: "screen", + renderer: video.WEBGL, + scale: "1.0", + failIfMajorPerformanceCaveat: false, + }); + await app.init(); + }); + afterEach(() => { + app.world.reset(); + }); + afterAll(() => { + return app?.destroy(); + }); + + /** everything the renderer would hand the next draw, copied out */ + const settings = (renderer) => { + return { + transform: Array.from(renderer.currentTransform.val), + color: Array.from(renderer.getColor().toArray()), + tint: Array.from(renderer.currentTint.toArray()), + alpha: renderer.globalAlpha(), + }; + }; + + /** draws nothing, records what it was given */ + class Probe extends Renderable { + constructor(name) { + super(20, 20, 16, 16); + this.name = name; + this.seen = null; + } + draw(renderer) { + order.push(this.name); + this.seen = settings(renderer); + } + } + + // every entry set, the perspective row included + const everyEntry = new Matrix3d( + 1.1, + 0.2, + 0.3, + 0.004, + 0.5, + 1.2, + 0.6, + 0.007, + 0.8, + 0.9, + 1.3, + 0.01, + 4, + 5, + 6, + 1.02, + ); + + /** a tinted, faded card, turned around its vertical axis */ + class Card extends Renderable { + constructor() { + super(60, 40, 20, 30); + this.tint.setColor(200, 64, 32); + this.alpha = 0.5; + this.rotate(0.6, new Vector3d(0, 1, 0)); + this.leftBehind = null; + } + draw(renderer) { + order.push("card"); + renderer.setColor("rgba(10, 200, 90, 0.25)"); + renderer.fillRect(0, 0, this.width, this.height); + renderer.setGlobalAlpha(0.2); + renderer.translate(5, 7); + renderer.rotate(0.3); + renderer.scale(2, 3); + renderer.transform(everyEntry); + this.leftBehind = settings(renderer); + } + } + + // one game frame: the children in depth order, updated, then drawn + const frame = () => { + order = []; + app.world.sortNow(true); + app.world.update(16); + app.repaint(); + app.draw(); + }; + + // the card changed each number, or a missed copy of it could not show + const expectChangedEverything = (card, before) => { + for (const key of ["transform", "color", "tint"]) { + card[key].forEach((value, i) => { + expect(value, `${key}[${i}]`).not.toBe(before[key][i]); + }); + } + expect(card.alpha).not.toBe(before.alpha); + }; + + it("the sprite drawn after the card sees what the one before it saw", () => { + const before = new Probe("before"); + const card = new Card(); + const after = new Probe("after"); + app.world.addChild(before, 1); + app.world.addChild(card, 2); + app.world.addChild(after, 3); + + frame(); + + expect(order).toEqual(["before", "card", "after"]); + expectChangedEverything(card.leftBehind, before.seen); + expect(after.seen).toEqual(before.seen); + }); + + it("inside a faded, tinted group, and after it", () => { + const group = new Container(10, 10, 150, 100); + group.alpha = 0.6; + group.tint.setColor(128, 255, 200); + const first = new Probe("first"); + const card = new Card(); + const second = new Probe("second"); + group.addChild(first, 1); + group.addChild(card, 2); + group.addChild(second, 3); + const outside = new Probe("outside before"); + const outsideAfter = new Probe("outside after"); + app.world.addChild(outside, 1); + app.world.addChild(group, 2); + app.world.addChild(outsideAfter, 3); + + frame(); + + expect(order).toEqual([ + "outside before", + "first", + "card", + "second", + "outside after", + ]); + expectChangedEverything(card.leftBehind, first.seen); + expect(second.seen).toEqual(first.seen); + expect(outsideAfter.seen).toEqual(outside.seen); + }); + + it("frame after frame, the same settings every time", () => { + const before = new Probe("before"); + const card = new Card(); + const after = new Probe("after"); + app.world.addChild(before, 1); + app.world.addChild(card, 2); + app.world.addChild(after, 3); + + frame(); + const first = before.seen; + for (let n = 0; n < 10; n++) { + card.rotate(0.1, new Vector3d(0, 1, 0)); + frame(); + expect(before.seen).toEqual(first); + expect(after.seen).toEqual(first); + } + }); +});