diff --git a/packages/examples/src/examples/afterBurner/HUD.ts b/packages/examples/src/examples/afterBurner/HUD.ts index 9ff7ed7ea0..84db42d7a8 100644 --- a/packages/examples/src/examples/afterBurner/HUD.ts +++ b/packages/examples/src/examples/afterBurner/HUD.ts @@ -345,7 +345,7 @@ export class HUD { this.flashTween?.stop(); this.flashTween = undefined; this.flashDriver.k = 0; - this.deathFlash.setUniform("uFlashIntensity", 0); + this.deathFlash.setIntensity(0); } /** @@ -360,7 +360,7 @@ export class HUD { flashDeath(): void { this.flashTween?.stop(); this.flashDriver.k = 1; - this.deathFlash.setUniform("uFlashIntensity", DEATH_FLASH_ALPHA); + this.deathFlash.setIntensity(DEATH_FLASH_ALPHA); const tween = new Tween(this.flashDriver); // the wash has to finish even though the run is over tween.updateWhenPaused = true; @@ -368,10 +368,7 @@ export class HUD { .to({ k: 0 }, { duration: DEATH_FLASH_FADE_MS }) .easing(Tween.Easing.Quadratic.Out) .onUpdate(() => { - this.deathFlash.setUniform( - "uFlashIntensity", - this.flashDriver.k * DEATH_FLASH_ALPHA, - ); + this.deathFlash.setIntensity(this.flashDriver.k * DEATH_FLASH_ALPHA); }) .onComplete(() => { this.flashTween = undefined; diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 27237bb442..403c5e6d8e 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -1,42 +1,42 @@ # Changelog -## [20.17.0] (melonJS 2) - _unreleased_ +## [20.17.0] (melonJS 2) - _2026-11-22_ + +**Highlights:** isometric, staggered and hexagonal Tiled maps are now drawn by the GPU, as orthogonal ones are: up to **98%** less of the main thread's time per tile layer, with nothing to enable. Also new: mask transitions shaped like an image or a sprite that close on the player, and two effects, `GradientMapEffect` (palette swaps, duotones) and `DitherEffect` (a retro limited-color look). A map with layer offsets now looks as it does in Tiled: the offsets were ignored before. ### Added -- Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) -- Tiled: isometric maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are, and so are staggered and hexagonal maps. Nothing to enable: a tile layer whose tiles come from one tileset takes it by itself, and any other is drawn as before, the console saying why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) -- Effects: `GradientMapEffect` recolors a sprite or a whole scene from its brightness, through a list of two to eight colors, the darkest pixels taking the first and the brightest the last: one sprite in a palette per team, a duotone, a night scene. With `smooth: false` each color takes a band of its own, a palette swap for art drawn in flat shades -- Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: on the camera, so many `levels` of each channel, so everything keeps its own hue, or a `palette` of two to sixteen colors of your own, in pixels `size` pixels wide. Only what falls between two colors is patterned (shading, soft shadows, gradients); a flat color that is one of them stays flat -- Skills: the entry skill now says what melonJS is the right engine for and what it is not, turns a kind of game (a platformer, a puzzle, a shooter) into the skills to read and the example to start from, and maps the usual engine vocabulary to the names used here. It also answers a request for a browser game that names no engine -- Skills: a new `melonjs-testing` skill is how an agent checks its own work: the game run in a headless browser, every console line read (the header names the renderer the run got), the controls driven, the game's state read from outside, a frame looked at +- Transitions: a mask transition can take the shape of an image or a `Sprite`, close on the player (`center`) and fill the shape (`invert`), on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) +- Tiled: isometric, staggered and hexagonal maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are. Nothing to enable: a tile layer drawn from a single tileset uses it by itself ([#1897](https://github.com/melonjs/melonJS/issues/1897)) +- Effects: `GradientMapEffect` recolors a sprite or a scene from its brightness, through two to eight colors: a palette per team, a duotone, a night scene, or a hard palette swap with `smooth: false` +- Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: `levels` of each channel or a `palette` of two to sixteen colors, in pixels `size` pixels wide ### Performance -- Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same +- Tiled: on the GPU, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms). Staggered and hexagonal maps gain the same - Tiled: for reference, orthogonal tile layers, on the GPU since 19.4, measure about **85%** less with 1000 tiles in view (0.62 to 0.09 ms) and about **97%** less with 3600 (1.9 to 0.06 ms) -- Size: the engine is about **8%** smaller to download: 323 kB minified and gzipped, from 350 kB (1,073 kB minified, from 1,159 kB). The comments in its shaders are no longer published; a shader is bundled as text, which a game's minifier does not touch, so they reached every game. Nothing to change in a game +- Effects: `FlashEffect` and `TintPulseEffect` are drawn by the `ColorMatrixEffect` shader, as `SepiaEffect`, `DesaturateEffect` and `InvertEffect` are: two fewer shaders to compile, and the pulse is computed once a frame rather than for every pixel. Nothing to change in a game ### Fixed -- Tiled: layers follow their offset in Tiled. A tile layer is drawn there, and where its own `pos` moves it, and `getTile()` finds its tiles there; an object layer's objects are created there; a group layer's offset moves the tile layers inside it. All were ignored, so a map with layer offsets now looks as it does in Tiled -- Tiled: tiles larger than a cell are drawn wherever they are in view. They were cut off or left out along the edges of the view, above and right of the map, on a map centred in the screen, and once the map itself had scrolled out of view +- Tiled: a layer's offset in Tiled is applied: to a tile layer (where it is drawn and where `getTile()` looks), to the objects of an object layer, and to the tile layers inside a group. It was ignored +- Tiled: tiles larger than a cell are drawn wherever they are in view; they were cut off or left out along the edges of the view and of the map - Tiled: staggered and hexagonal maps are drawn where Tiled draws them: a tile larger than its cell stands on it, a tileset's `tileoffset` moves its tiles, and maps of odd sizes stay on whole pixels - Tiled: orthogonal layers drawn by the GPU show the soft edges of large tiles over the tiles behind them, lay large tiles over each other in the map's order, and read a tileset with a `margin` right - Tiled: an isometric, staggered or hexagonal layer with an `opacity` below 1 fades as one picture on WebGL and WebGPU; each tile showed through the one in front of it - Tiled: a tile layer removed from its container and added again, and a tile missing from its tileset's image, no longer throw - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it -- Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where Helvetica's hanging metrics made the ink padding exactly as tall as the ink, shearing its first row off the canvas ([#1870](https://github.com/melonjs/melonJS/issues/1870)) -- glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it -- Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw -- Sprites: an atlas frame the packer stored rotated is drawn where the sprite is. It was drawn off the screen unless the sprite stood at (0, 0), so an animation with such frames blinked, on every renderer. A `NineSliceSprite` made from a rotated frame is stretched along the right axes, with its corners the right way round -- WebGL: with `antiAlias` on, a frame that captures the canvas and then draws over it (`renderer.toFrameTexture()`, a `screen_texture` effect, an advanced blend mode) is no longer shown black. Chromium loses such a frame, more often the longer it takes: the Aquarium example showed 114 black frames in 125 on its software renderer, none now -- Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when a later change finds that sprite gone with its level and closes a plain iris instead; nothing was said. A mask transition given no shape also says so once, not on every change -- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle too, so a bundler keeps a `melonjs` imported only for its polyfills -- Skills and README: the engine's size was given as 250 KB; it is about 320 kB minified and gzipped (the README now says ~300 KB) -- Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc. Rounding could push the cosine of its sweep angle just past -1, `Math.acos` returned `NaN`, and the arc became a straight line between its endpoints (thanks @SwastikTripathi) +- Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where its first row was cut off ([#1870](https://github.com/melonjs/melonJS/issues/1870)) (thanks @Goldloli) +- glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an unrelated accessor error +- Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, and a raycast passes over an object whose body is not the adapter's; both threw +- Sprites: an atlas frame the packer stored rotated is drawn where the sprite is; it was drawn off the screen unless the sprite stood at (0, 0), so its animation blinked. A `NineSliceSprite` made from such a frame is no longer stretched along the wrong axes +- WebGL: with `antiAlias` on, a frame that captures the canvas and then draws over it (`renderer.toFrameTexture()`, a `screen_texture` effect, an advanced blend mode) is no longer shown black at times in Chromium +- Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when that sprite is gone with its level and a plain iris is used instead. A mask transition given no shape also says so once, not on every change +- Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc; rounding could turn it into a straight line between its endpoints (thanks @SwastikTripathi) ### Chore - Dependencies: update the development tools, clearing the 46 vulnerabilities reported by the security audit - Lint: lint each package on its own and cache the result, so `pnpm lint` skips what has not changed - CI: fix the test job losing its browser page at random, and run the test suite in about half the time +- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle +- Size: the engine is about 8% smaller to download (323 kB minified and gzipped, from 350 kB), as the comments in its shaders are no longer published ## [20.16.0] (melonJS 2) - _2026-11-17_ diff --git a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md index 1efd988f5a..00149fb560 100644 --- a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md +++ b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md @@ -121,6 +121,11 @@ GPU backend: `VignetteEffect`, `ScanlineEffect` (optional CRT curvature), `HologramEffect`, `ShineEffect`, `RadialGradientEffect`, `SquishEffect`, `ToneMappingEffect`, `GradientMapEffect`, `DitherEffect`. +Five of them are a `ColorMatrixEffect` with a matrix set for you, and share +its one shader: `SepiaEffect`, `DesaturateEffect`, `InvertEffect`, +`FlashEffect` and `TintPulseEffect` (the last two since 20.17). Drive them +through their own setters (`setIntensity`, `setColor`, `setTime`). + **Colors take an alpha.** Every color option and `setColor` takes `[r, g, b]` or `[r, g, b, a]`, each 0.0 to 1.0, and the alpha is the color's own opacity: a half-transparent outline, a glow at half strength, a flash that only half diff --git a/packages/melonjs/src/video/effects/colorMatrix.js b/packages/melonjs/src/video/effects/colorMatrix.js index 2b666b8f5e..bf44003379 100644 --- a/packages/melonjs/src/video/effects/colorMatrix.js +++ b/packages/melonjs/src/video/effects/colorMatrix.js @@ -71,6 +71,44 @@ export default class ColorMatrixEffect extends ShaderEffect { this.setUniform("uColorMatrix", this._matrix.val); } + /** + * Set the matrix to a blend of every pixel toward one color: `amount` of + * the way, scaled by the color's own alpha. What a flash or a tint is. + * + * Colors reach an effect premultiplied, so "this color, as opaque as the + * pixel" is the color times the pixel's alpha: the matrix's alpha column. + * @param {ArrayLike} color - the color to blend toward, as [r, g, b, a] (0.0–1.0) + * @param {number} amount - how far (0.0 = the pixel's own color, 1.0 = the color) + * @ignore + * @internal + */ + _blendToward(color, amount) { + const k = amount * color[3]; + const keep = 1 - k; + // column-major: what red, green, blue and alpha each add to the result + this._matrix + .identity() + .transform( + keep, + 0, + 0, + 0, + 0, + keep, + 0, + 0, + 0, + 0, + keep, + 0, + k * color[0], + k * color[1], + k * color[2], + 1, + ); + this._syncUniform(); + } + /** * Reset the color matrix to identity (no color change). * @returns {this} this instance for chaining diff --git a/packages/melonjs/src/video/effects/flash.js b/packages/melonjs/src/video/effects/flash.js index 40dccc8530..9ee8ff647e 100644 --- a/packages/melonjs/src/video/effects/flash.js +++ b/packages/melonjs/src/video/effects/flash.js @@ -1,5 +1,5 @@ +import ColorMatrixEffect from "./colorMatrix.js"; import { rgba } from "./rgba.js"; -import ShaderEffect from "./shadereffect.js"; /** * additional import for TypeScript @@ -8,26 +8,15 @@ import ShaderEffect from "./shadereffect.js"; * @import WebGPURenderer from "../webgpu/webgpu_renderer.js"; * @import Renderer from "../renderer.js"; */ -// the WGSL twin of the GLSL body below — same logic, same uniform -// names, picked by the ShaderEffect base per renderer.shaderLanguage -const wgslFragment = ` -struct FlashUniforms { - uFlashColor : vec4f, - uFlashIntensity : f32, -}; -@group(3) @binding(0) var fx : FlashUniforms; - -fn apply(color : vec4f, uv : vec2f) -> vec4f { - // the color's alpha scales how far the flash covers the sprite - return vec4f(mix(color.rgb, fx.uFlashColor.rgb * color.a, fx.uFlashIntensity * fx.uFlashColor.a), color.a); -} -`; /** * A shader effect that flashes the sprite with a solid color. * Commonly used for hit feedback — flash white when the player takes damage. - * The `intensity` uniform controls how much of the flash color is mixed in + * The `intensity` controls how much of the flash color is mixed in * (0.0 = original sprite, 1.0 = fully colored). + * + * A flash is a color matrix: it is drawn by the shader of + * {@link ColorMatrixEffect}, which every flash shares. * @category Effects * @see {@link Renderable#addPostEffect} for usage * @example @@ -48,7 +37,7 @@ fn apply(color : vec4f, uv : vec2f) -> vec4f { * const hit = new FlashEffect(renderer, { color: [1.0, 1.0, 1.0, 0.5] }); * hit.setIntensity(1.0); */ -export default class FlashEffect extends ShaderEffect { +export default class FlashEffect extends ColorMatrixEffect { /** * @param {Renderer} renderer - the current renderer instance * @param {object} [options] - effect options @@ -56,23 +45,22 @@ export default class FlashEffect extends ShaderEffect { * @param {number} [options.intensity=0.0] - initial flash intensity (0.0–1.0) */ constructor(renderer, options = {}) { - super(renderer, { - glsl: ` - uniform vec4 uFlashColor; - uniform float uFlashIntensity; - vec4 apply(vec4 color, vec2 uv) { - // the color's alpha scales how far the flash covers the sprite - return vec4(mix(color.rgb, uFlashColor.rgb * color.a, uFlashIntensity * uFlashColor.a), color.a); - } - `, - wgsl: wgslFragment, - }); + super(renderer); + + /** + * the flash color, as [r, g, b, a] + * @ignore + * @internal + */ + this._color = rgba(options.color ?? [1.0, 1.0, 1.0]); - const color = options.color ?? [1.0, 1.0, 1.0]; + /** + * how much of the flash color is mixed in (0.0–1.0) + * @type {number} + */ this.intensity = options.intensity ?? 0.0; - this.setUniform("uFlashColor", rgba(color)); - this.setUniform("uFlashIntensity", this.intensity); + this._blendToward(this._color, this.intensity); } /** @@ -81,7 +69,7 @@ export default class FlashEffect extends ShaderEffect { */ setIntensity(value) { this.intensity = Math.max(0, Math.min(1, value)); - this.setUniform("uFlashIntensity", this.intensity); + this._blendToward(this._color, this.intensity); } /** @@ -89,6 +77,26 @@ export default class FlashEffect extends ShaderEffect { * @param {number[]} color - flash color as [r, g, b] or [r, g, b, a] (0.0–1.0); the alpha scales the intensity */ setColor(color) { - this.setUniform("uFlashColor", rgba(color)); + this._color = rgba(color); + this._blendToward(this._color, this.intensity); + } + + /** + * The flash had a shader of its own, with these two uniforms: a game that + * set them by name keeps working. + * @param {string} name - the uniform's name + * @param {*} value - its value + * @ignore + */ + setUniform(name, value) { + if (name === "uFlashIntensity") { + // as given, not clamped: that is what the uniform did + this.intensity = value; + this._blendToward(this._color, this.intensity); + } else if (name === "uFlashColor") { + this.setColor(value); + } else { + super.setUniform(name, value); + } } } diff --git a/packages/melonjs/src/video/effects/tintPulse.js b/packages/melonjs/src/video/effects/tintPulse.js index 9d67ed3b54..e329031ed3 100644 --- a/packages/melonjs/src/video/effects/tintPulse.js +++ b/packages/melonjs/src/video/effects/tintPulse.js @@ -1,5 +1,5 @@ +import ColorMatrixEffect from "./colorMatrix.js"; import { rgba } from "./rgba.js"; -import ShaderEffect from "./shadereffect.js"; /** * additional import for TypeScript @@ -8,28 +8,15 @@ import ShaderEffect from "./shadereffect.js"; * @import WebGPURenderer from "../webgpu/webgpu_renderer.js"; * @import Renderer from "../renderer.js"; */ -// the WGSL twin of the GLSL body below — same logic, same uniform -// names, picked by the ShaderEffect base per renderer.shaderLanguage -const wgslFragment = ` -struct TintPulseUniforms { - uPulseColor : vec4f, - uPulseSpeed : f32, - uPulseIntensity : f32, - uTime : f32, -}; -@group(3) @binding(0) var fx : TintPulseUniforms; - -fn apply(color : vec4f, uv : vec2f) -> vec4f { - let pulse = (sin(fx.uTime * fx.uPulseSpeed * 6.2832) * 0.5 + 0.5) * fx.uPulseIntensity; - // the color's alpha scales how far the pulse tints the sprite - return vec4f(mix(color.rgb, fx.uPulseColor.rgb * color.a, pulse * fx.uPulseColor.a), color.a); -} -`; /** * A shader effect that pulses a color overlay on the sprite. * Commonly used for status effects — poison green, freeze blue, fire red. - * The `time` uniform should be updated each frame for the pulse animation. + * The time should be updated each frame, with `setTime()`, for the pulse + * animation. + * + * A tint is a color matrix, here one that follows the time: it is drawn by + * the shader of {@link ColorMatrixEffect}, which every pulse shares. * @category Effects * @see {@link Renderable#addPostEffect} for usage * @example @@ -46,7 +33,7 @@ fn apply(color : vec4f, uv : vec2f) -> vec4f { * // a subtle pulse: the color's alpha caps how far it tints * mySprite.addPostEffect(new TintPulseEffect(renderer, { color: [1.0, 0.8, 0.0, 0.35] })); */ -export default class TintPulseEffect extends ShaderEffect { +export default class TintPulseEffect extends ColorMatrixEffect { /** * @param {Renderer} renderer - the current renderer instance * @param {object} [options] - effect options @@ -55,26 +42,35 @@ export default class TintPulseEffect extends ShaderEffect { * @param {number} [options.intensity=0.3] - maximum tint strength (0.0–1.0) */ constructor(renderer, options = {}) { - super(renderer, { - glsl: ` - uniform vec4 uPulseColor; - uniform float uPulseSpeed; - uniform float uPulseIntensity; - uniform float uTime; - vec4 apply(vec4 color, vec2 uv) { - float pulse = (sin(uTime * uPulseSpeed * 6.2832) * 0.5 + 0.5) * uPulseIntensity; - // the color's alpha scales how far the pulse tints the sprite - return vec4(mix(color.rgb, uPulseColor.rgb * color.a, pulse * uPulseColor.a), color.a); - } - `, - wgsl: wgslFragment, - }); + super(renderer); + + /** + * the pulse color, as [r, g, b, a] + * @ignore + * @internal + */ + this._color = rgba(options.color ?? [1.0, 0.0, 0.0]); + + /** + * pulse speed, in oscillations per second + * @type {number} + */ + this.speed = options.speed ?? 2.0; - const color = options.color ?? [1.0, 0.0, 0.0]; - this.setUniform("uPulseColor", rgba(color)); - this.setUniform("uPulseSpeed", options.speed ?? 2.0); - this.setUniform("uPulseIntensity", options.intensity ?? 0.3); - this.setUniform("uTime", 0.0); + /** + * maximum tint strength (0.0–1.0) + * @type {number} + */ + this.intensity = options.intensity ?? 0.3; + + /** + * the time the pulse is drawn at, in seconds + * @ignore + * @internal + */ + this._time = 0; + + this._pulse(); } /** @@ -82,6 +78,50 @@ export default class TintPulseEffect extends ShaderEffect { * @param {number[]} color - pulse color as [r, g, b] or [r, g, b, a] (0.0–1.0); the alpha scales the intensity */ setColor(color) { - this.setUniform("uPulseColor", rgba(color)); + this._color = rgba(color); + this._pulse(); + } + + /** + * Set the time the pulse is drawn at: call it once per frame. + * @param {number} seconds - elapsed time, in seconds + */ + setTime(seconds) { + this._time = seconds; + this._pulse(); + } + + /** + * The pulse had a shader of its own, with these four uniforms: a game + * that set them by name keeps working. + * @param {string} name - the uniform's name + * @param {*} value - its value + * @ignore + */ + setUniform(name, value) { + if (name === "uTime") { + this.setTime(value); + } else if (name === "uPulseColor") { + this.setColor(value); + } else if (name === "uPulseSpeed") { + this.speed = value; + this._pulse(); + } else if (name === "uPulseIntensity") { + this.intensity = value; + this._pulse(); + } else { + super.setUniform(name, value); + } + } + + /** + * the matrix of the tint at the current time: from none to `intensity` + * and back, `speed` times a second + * @ignore + * @internal + */ + _pulse() { + const wave = Math.sin(this._time * this.speed * Math.PI * 2) * 0.5 + 0.5; + this._blendToward(this._color, wave * this.intensity); } } diff --git a/packages/melonjs/tests/effect-color-blend.spec.js b/packages/melonjs/tests/effect-color-blend.spec.js new file mode 100644 index 0000000000..03eb81a30d --- /dev/null +++ b/packages/melonjs/tests/effect-color-blend.spec.js @@ -0,0 +1,388 @@ +import "./helpers/webgpu-globals.js"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + boot, + ColorMatrixEffect, + FlashEffect, + ShaderEffect, + TintPulseEffect, +} from "../src/index.js"; +import Renderer from "../src/video/renderer.js"; +import { + getWebGLRenderer, + releaseWebGLRenderer, +} from "./helpers/webgl-context.js"; + +/** + * A flash and a tint pulse blend every pixel toward one color. On the + * premultiplied colors an effect is given, that is a color matrix, so both + * are a `ColorMatrixEffect` and share its shader, where each had one of its + * own. + * + * What has to hold: the picture is the one the old shaders drew, the colors + * and options mean what they did, and a game that set the old uniforms by + * name still works. + */ + +/** the sixteen floats of an effect's matrix, column-major */ +const matrixOf = (effect) => { + return Array.from(effect._matrix.val).map((v) => { + return Math.round(v * 1e6) / 1e6; + }); +}; + +/** the matrix of a blend toward [r, g, b], `k` of the way */ +const blend = ([r, g, b], k) => { + const keep = Math.round((1 - k) * 1e6) / 1e6; + const part = (v) => { + return Math.round(v * k * 1e6) / 1e6; + }; + return [ + keep, + 0, + 0, + 0, + 0, + keep, + 0, + 0, + 0, + 0, + keep, + 0, + part(r), + part(g), + part(b), + 1, + ]; +}; + +const IDENTITY = blend([0, 0, 0], 0); + +const wgslRenderer = { shaderLanguage: "wgsl", width: 64, height: 64 }; + +/** an effect on a WGSL renderer, with no device needed to check its matrix */ +const make = (Effect, options) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const effect = new Effect(wgslRenderer, options); + warn.mockRestore(); + return effect; +}; + +describe("a flash and a tint pulse, as color matrices", () => { + describe("FlashEffect", () => { + it("is a ColorMatrixEffect, and still a ShaderEffect", () => { + const flash = make(FlashEffect); + expect(flash).toBeInstanceOf(ColorMatrixEffect); + expect(flash).toBeInstanceOf(ShaderEffect); + expect(flash.wgslRealization.valid).toBe(true); + flash.destroy(); + }); + + it("shares the color matrix shader, with a matrix as its only uniform", () => { + const flash = make(FlashEffect); + const matrix = make(ColorMatrixEffect); + expect([...flash.wgslRealization.layout.keys()]).toEqual([ + ...matrix.wgslRealization.layout.keys(), + ]); + expect([...flash.wgslRealization.layout.keys()]).toEqual([ + "uColorMatrix", + ]); + flash.destroy(); + matrix.destroy(); + }); + + it("leaves the sprite as it is by default: white, at no intensity", () => { + const flash = make(FlashEffect); + expect(flash.intensity).toBe(0); + expect(matrixOf(flash)).toEqual(IDENTITY); + flash.destroy(); + }); + + it("blends toward its color by its intensity", () => { + const flash = make(FlashEffect, { color: [1, 0.5, 0], intensity: 0.25 }); + expect(matrixOf(flash)).toEqual(blend([1, 0.5, 0], 0.25)); + flash.setIntensity(1); + expect(flash.intensity).toBe(1); + expect(matrixOf(flash)).toEqual(blend([1, 0.5, 0], 1)); + flash.destroy(); + }); + + it("scales the intensity by the color's alpha", () => { + const flash = make(FlashEffect, { color: [1, 1, 1, 0.5], intensity: 1 }); + expect(matrixOf(flash)).toEqual(blend([1, 1, 1], 0.5)); + flash.destroy(); + }); + + it("setIntensity keeps the intensity between 0 and 1", () => { + const flash = make(FlashEffect, { color: [1, 0, 0] }); + flash.setIntensity(3); + expect(flash.intensity).toBe(1); + flash.setIntensity(-1); + expect(flash.intensity).toBe(0); + expect(matrixOf(flash)).toEqual(IDENTITY); + flash.destroy(); + }); + + it("setColor changes the color, at the intensity it had", () => { + const flash = make(FlashEffect, { intensity: 0.5 }); + flash.setColor([0, 0, 1]); + expect(matrixOf(flash)).toEqual(blend([0, 0, 1], 0.5)); + flash.setColor([0, 0, 1, 0.5]); + expect(matrixOf(flash)).toEqual(blend([0, 0, 1], 0.25)); + expect(() => { + flash.setColor([1, 0]); + }).toThrow(TypeError); + flash.destroy(); + }); + + it("the uniforms its own shader had still set it, by name", () => { + const flash = make(FlashEffect); + flash.setUniform("uFlashIntensity", 0.75); + expect(flash.intensity).toBe(0.75); + expect(matrixOf(flash)).toEqual(blend([1, 1, 1], 0.75)); + flash.setUniform("uFlashColor", [1, 0, 0, 1]); + expect(matrixOf(flash)).toEqual(blend([1, 0, 0], 0.75)); + flash.setUniform("uFlashIntensity", 0); + expect(matrixOf(flash)).toEqual(IDENTITY); + flash.destroy(); + }); + }); + + describe("TintPulseEffect", () => { + it("is a ColorMatrixEffect, sharing its shader", () => { + const pulse = make(TintPulseEffect); + expect(pulse).toBeInstanceOf(ColorMatrixEffect); + expect(pulse.wgslRealization.valid).toBe(true); + expect([...pulse.wgslRealization.layout.keys()]).toEqual([ + "uColorMatrix", + ]); + pulse.destroy(); + }); + + it("takes its defaults: red, twice a second, up to 0.3", () => { + const pulse = make(TintPulseEffect); + expect(pulse.speed).toBe(2); + expect(pulse.intensity).toBe(0.3); + // at time 0 the wave is half way up + expect(matrixOf(pulse)).toEqual(blend([1, 0, 0], 0.15)); + pulse.destroy(); + }); + + it("goes from none to its intensity and back, `speed` times a second", () => { + const pulse = make(TintPulseEffect, { + color: [0, 1, 0], + speed: 1, + intensity: 0.8, + }); + // a quarter of a cycle in: the peak + pulse.setTime(0.25); + expect(matrixOf(pulse)).toEqual(blend([0, 1, 0], 0.8)); + // three quarters in: none + pulse.setTime(0.75); + expect(matrixOf(pulse)).toEqual(IDENTITY); + // a whole cycle later, the same as at the start + pulse.setTime(1); + expect(matrixOf(pulse)).toEqual(blend([0, 1, 0], 0.4)); + // twice as fast, the peak comes at an eighth of a second + const fast = make(TintPulseEffect, { + color: [0, 1, 0], + speed: 2, + intensity: 0.8, + }); + fast.setTime(0.125); + expect(matrixOf(fast)).toEqual(blend([0, 1, 0], 0.8)); + pulse.destroy(); + fast.destroy(); + }); + + it("scales the tint by the color's alpha, and takes a new color", () => { + const pulse = make(TintPulseEffect, { + color: [0, 1, 0, 0.5], + speed: 1, + intensity: 1, + }); + pulse.setTime(0.25); + expect(matrixOf(pulse)).toEqual(blend([0, 1, 0], 0.5)); + pulse.setColor([0, 0, 1]); + expect(matrixOf(pulse)).toEqual(blend([0, 0, 1], 1)); + expect(() => { + pulse.setColor([1, 0, 0, 1, 1]); + }).toThrow(TypeError); + pulse.destroy(); + }); + + it("the uniforms its own shader had still set it, by name", () => { + const pulse = make(TintPulseEffect, { color: [1, 0, 0], intensity: 1 }); + pulse.setUniform("uPulseSpeed", 1); + pulse.setUniform("uTime", 0.25); + expect(pulse.speed).toBe(1); + expect(matrixOf(pulse)).toEqual(blend([1, 0, 0], 1)); + pulse.setUniform("uPulseIntensity", 0.5); + expect(pulse.intensity).toBe(0.5); + expect(matrixOf(pulse)).toEqual(blend([1, 0, 0], 0.5)); + pulse.setUniform("uPulseColor", [0, 0, 1, 1]); + expect(matrixOf(pulse)).toEqual(blend([0, 0, 1], 0.5)); + pulse.destroy(); + }); + }); + + describe("on WebGL, against the shaders they had", () => { + const SIZE = 64; + let renderer; + let sprite; + + // the bodies the two effects were drawn with, before + const OLD_FLASH = ` + uniform vec4 uFlashColor; + uniform float uFlashIntensity; + vec4 apply(vec4 color, vec2 uv) { + return vec4(mix(color.rgb, uFlashColor.rgb * color.a, uFlashIntensity * uFlashColor.a), color.a); + } + `; + const OLD_PULSE = ` + uniform vec4 uPulseColor; + uniform float uPulseSpeed; + uniform float uPulseIntensity; + uniform float uTime; + vec4 apply(vec4 color, vec2 uv) { + float pulse = (sin(uTime * uPulseSpeed * 6.2832) * 0.5 + 0.5) * uPulseIntensity; + return vec4(mix(color.rgb, uPulseColor.rgb * color.a, pulse * uPulseColor.a), color.a); + } + `; + + beforeAll(async () => { + await boot(); + try { + renderer = await getWebGLRenderer(SIZE, SIZE); + } catch { + // WebGL genuinely unavailable: the tests skip below + } + if (renderer) { + renderer.projectionMatrix.ortho(0, SIZE, SIZE, 0, -1000, 1000); + renderer.currentBatcher.setProjection(renderer.projectionMatrix); + } + // 32x32, every kind of pixel a sprite has: opaque colors, a + // gradient, and half and quarter transparent ones over nothing + sprite = Renderer.createCanvas(32, 32); + const ctx = sprite.getContext("2d"); + const ramp = ctx.createLinearGradient(0, 0, 32, 0); + ramp.addColorStop(0, "#102080"); + ramp.addColorStop(1, "#f0c020"); + ctx.fillStyle = ramp; + ctx.fillRect(0, 0, 32, 12); + ctx.fillStyle = "rgba(255, 0, 0, 0.5)"; + ctx.fillRect(0, 12, 16, 10); + ctx.fillStyle = "rgba(0, 255, 64, 0.25)"; + ctx.fillRect(16, 12, 16, 10); + ctx.fillStyle = "#ffffff"; + ctx.fillRect(4, 24, 24, 6); + }); + + afterAll(() => { + releaseWebGLRenderer(); + }); + + const requireWebGL = (ctx) => { + if (renderer === undefined) { + ctx.skip("WebGL renderer not available in this environment"); + } + }; + + /** the sprite drawn with an effect over a mid grey, as its pixels */ + const drawn = (effect) => { + renderer.clearColor("#404040ff"); + renderer.save(); + renderer.customShader = effect; + renderer.drawImage(sprite, 0, 0, 32, 32, 16, 16, 32, 32); + renderer.flush(); + renderer.customShader = undefined; + renderer.restore(); + effect.destroy(); + const gl = renderer.gl; + const out = new Uint8Array(SIZE * SIZE * 4); + gl.readPixels(0, 0, SIZE, SIZE, gl.RGBA, gl.UNSIGNED_BYTE, out); + return out; + }; + + /** the largest difference between two frames, in 8-bit steps */ + const furthest = (a, b) => { + let most = 0; + for (let i = 0; i < a.length; i++) { + most = Math.max(most, Math.abs(a[i] - b[i])); + } + return most; + }; + + const oldFlash = (color, intensity) => { + const effect = new ShaderEffect(renderer, OLD_FLASH); + effect.setUniform("uFlashColor", new Float32Array(color)); + effect.setUniform("uFlashIntensity", intensity); + return effect; + }; + + const oldPulse = (color, speed, intensity, time) => { + const effect = new ShaderEffect(renderer, OLD_PULSE); + effect.setUniform("uPulseColor", new Float32Array(color)); + effect.setUniform("uPulseSpeed", speed); + effect.setUniform("uPulseIntensity", intensity); + effect.setUniform("uTime", time); + return effect; + }; + + it("the test sprite is drawn, and a flash changes it", (ctx) => { + requireWebGL(ctx); + const plain = drawn(new FlashEffect(renderer, { intensity: 0 })); + const white = drawn(new FlashEffect(renderer, { intensity: 1 })); + expect(furthest(plain, white)).toBeGreaterThan(100); + }); + + it.for([ + { color: [1, 1, 1, 1], intensity: 0 }, + { color: [1, 1, 1, 1], intensity: 0.3 }, + { color: [1, 1, 1, 1], intensity: 1 }, + { color: [1, 0, 0, 1], intensity: 0.6 }, + { color: [0.2, 0.9, 0.4, 0.5], intensity: 1 }, + { color: [0, 0, 0, 1], intensity: 0.8 }, + { color: [1, 1, 1, 0], intensity: 1 }, + ])( + "a flash of $color at $intensity is the picture its own shader drew", + (flash, ctx) => { + requireWebGL(ctx); + const now = drawn( + new FlashEffect(renderer, { + color: flash.color, + intensity: flash.intensity, + }), + ); + const before = drawn(oldFlash(flash.color, flash.intensity)); + // the same arithmetic in another order: a rounding step at most + expect(furthest(now, before)).toBeLessThanOrEqual(1); + }, + ); + + it.for([ + { color: [1, 0, 0, 1], speed: 2, intensity: 0.3, time: 0 }, + { color: [0, 1, 0, 1], speed: 1, intensity: 1, time: 0.25 }, + { color: [0, 1, 0, 1], speed: 1, intensity: 1, time: 0.75 }, + { color: [0.1, 0.4, 1, 0.5], speed: 3, intensity: 0.8, time: 1.37 }, + { color: [1, 0.8, 0, 0.35], speed: 2, intensity: 0.3, time: 12.4 }, + ])( + "a pulse of $color at $time s is the picture its own shader drew", + (pulse, ctx) => { + requireWebGL(ctx); + const effect = new TintPulseEffect(renderer, { + color: pulse.color, + speed: pulse.speed, + intensity: pulse.intensity, + }); + effect.setTime(pulse.time); + const now = drawn(effect); + const before = drawn( + oldPulse(pulse.color, pulse.speed, pulse.intensity, pulse.time), + ); + expect(furthest(now, before)).toBeLessThanOrEqual(1); + }, + ); + }); +}); diff --git a/packages/melonjs/tests/effect-colors.spec.js b/packages/melonjs/tests/effect-colors.spec.js index 00c2ed77c9..9a0fc04f66 100644 --- a/packages/melonjs/tests/effect-colors.spec.js +++ b/packages/melonjs/tests/effect-colors.spec.js @@ -32,12 +32,12 @@ import { */ // [effect, its color uniform, the constructor option, the setter] +// (a flash and a tint pulse take a color too, in a color matrix rather than a +// uniform of their own: effect-color-blend.spec.js) const COLORED = [ [OutlineEffect, "uOutlineColor", "color", "setColor"], [GlowEffect, "uGlowColor", "color", "setColor"], [DropShadowEffect, "uShadowColor", "color", "setColor"], - [FlashEffect, "uFlashColor", "color", "setColor"], - [TintPulseEffect, "uPulseColor", "color", "setColor"], [HologramEffect, "uHoloColor", "color", "setColor"], [ShineEffect, "uShineColor", "color", "setColor"], [DissolveEffect, "uEdgeColor", "edgeColor", "setEdgeColor"],