diff --git a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md index 00662de9d..66f387f54 100644 --- a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md +++ b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md @@ -162,11 +162,26 @@ scene uncovered. A sprite or renderable given here is read when the transition starts, and the reveal reuses what the hide read, so the old stage destroying the player -in between is fine. It is then let go: the transition is sticky, but one -level's player is not the next one's, so later changes are an iris on the -centre of the screen until you set it again. Give it this level's player -right before each `state.change`. The -`"pixelate"` form breaks the screen up into blocks (its fourth argument is the +in between is fine. Whether it is kept depends on whose it is: + +- **a sprite the game keeps for itself** (never added to a level, such as + `atlas.createSpriteFromName("logo")`, or a persistent one in the world): set + it once, it shapes every change, with the frame it shows by then. +- **a sprite that is part of the level** (the player): the change destroys it, + so it is let go after that one transition, and later changes are an iris on + the centre of the screen until you set it again. Give it this level's + player right before each `state.change`. + +```js +// once, at startup: every change wears the logo +state.transition("mask", "#000", 500, atlas.createSpriteFromName("logo")); + +// before each change: this level's player +state.transition("mask", "#000", 500, player, { center: player }); +state.change(state.GAME_END); +``` + +The `"pixelate"` form breaks the screen up into blocks (its fourth argument is the largest block size in pixels; the color is not used). It is a shader effect, so on Canvas it does nothing and the state changes directly. @@ -596,7 +611,7 @@ When `setStorage()` switches storage: | `Undefined Stage for state 'N'` thrown | no `state.set` for that id first | | `state.change(state.PLAY)` from `PLAY` does nothing ("Retry" ignored) | a change to the current state is a no-op — `state.reload()` (20.16), `level.reload()` for the map alone | | a mask transition closes on the middle of the screen, not on the player | pass `{ center: player }` as the fifth argument; on a `Trigger`, `center: "touching"` | -| the first mask transition is the player's shape, later ones a plain iris on the middle of the screen | a sprite or renderable given to `state.transition` is used by one transition, then let go: set it again, with this level's player, right before each `state.change` | +| the first mask transition is the player's shape, later ones a plain iris on the middle of the screen | a sprite that is part of the level is destroyed by the change, so `state.transition` lets it go after one transition: set it again, with this level's player, right before each `state.change`. A sprite kept outside any level (or a persistent one) is set once and shapes every change | | a level change through a `Trigger` ignores `state.transition` | it is a level change, not a state change: set `color` and `duration` (and `transition`) on the trigger | | the game stops updating for good after one very slow update, such as a heavy first frame (20.12 and 20.13) | the loop could no longer save enough time to step the world: update | | the game resumes under its own pause menu after a tab switch (before 20.9) | focus undid any pause; update, only the blur pause is undone | diff --git a/packages/melonjs/src/state/state.ts b/packages/melonjs/src/state/state.ts index 70da3747b..5280ec701 100644 --- a/packages/melonjs/src/state/state.ts +++ b/packages/melonjs/src/state/state.ts @@ -10,6 +10,7 @@ import MaskEffect, { } from "../camera/effects/mask_effect.ts"; import PixelateTransitionEffect from "../camera/effects/pixelate_transition_effect.ts"; import DefaultLoadingScreen from "./../loader/loadingscreen.js"; +import type Renderable from "./../renderable/renderable.js"; import Stage from "./../state/stage.ts"; import { BLUR, @@ -56,8 +57,8 @@ const _transitionConfig: { // where a mask transition closes and opens, and whether it is inverted center?: MaskCenter | undefined; invert?: boolean | undefined; - // a sprite shape or a renderable center was used, and let go: later - // changes are an iris on the centre of the screen until it is set again + // a sprite shape the change took with its level was used, and let go: + // later changes are an iris until it is set again released?: boolean | undefined; // the largest blocks of a pixelate transition, in screen pixels size?: number | undefined; @@ -66,6 +67,33 @@ const _transitionConfig: { duration: 0, }; +/** + * Whether a state change takes this away: a renderable in the world, unless + * the child of the world it is, or is under, is persistent. The world is + * reset with its stage, and spares its persistent children with all they + * hold; a renderable in no world (one the game made and keeps for itself) is + * not its to destroy. + * @param value - the shape or the center of a mask transition + * @returns true for a renderable the next state change takes away + */ +function goesWithTheStage(value: unknown): boolean { + if (!isRenderable(value)) { + return false; + } + let node: Renderable = value; + let kept = false; + // `ancestor` is undefined on a renderable that is in no container + let parent = node.ancestor as Renderable | undefined; + while (parent !== undefined) { + // persistent is a word to the container a renderable is a child of: + // only the world's own children are asked + kept = node.isPersistent; + node = parent; + parent = node.ancestor; + } + return node === _app.world && !kept; +} + // callback when state switch is done /** * @ignore @@ -725,14 +753,18 @@ const state = { * @param [shape] - for "mask" (required) the mask shape: an `Ellipse` or * `Polygon` (unit-sized, centred on the origin), an image or the name of a * preloaded one (its silhouette), or a `Sprite` (the silhouette of the - * frame it shows when the transition starts); see {@link MaskEffect}. For - * "pixelate", the size of the largest blocks, in screen pixels (32 by - * default) + * frame it shows when the transition starts); see {@link MaskEffect}. A + * sprite the game keeps for itself (in no level, or persistent) is kept + * with the transition, and shapes every change. One that is part of the + * level shapes the next change, which destroys it, and is then let go: + * later changes are an iris until it is set again. For "pixelate", the + * size of the largest blocks, in screen pixels (32 by default) * @param [options] - for "mask" only * @param [options.center] - where the shape closes and opens: a * renderable, such as the player, at the place it is drawn when the * transition starts, or a point on screen. The centre of the screen by - * default. The reveal opens from the same place + * default. The reveal opens from the same place. A renderable is kept or + * let go as a sprite `shape` is * @param [options.invert=false] - make the shape the cover rather than * the window: filled with the color, it grows out of `center` until it * covers the screen, and shrinks away to reveal it @@ -757,6 +789,10 @@ const state = { * state.transition("mask", "#000", 500, player, { center: player }); * state.change(state.GAME_END); * @example + * // a sprite of the game's own, in no level: set once, for every change + * const logo = atlas.createSpriteFromName("logo"); + * state.transition("mask", "#000", 500, logo); + * @example * // a black circle growing out of the player until it covers the screen * state.transition("mask", "#000", 400, new Ellipse(0, 0, 1, 1), { * center: player, @@ -940,15 +976,16 @@ const state = { invert: _transitionConfig.invert, onComplete, }); - // The transition is set once and kept, but a sprite or a - // renderable is one level's player: read now, it is let - // go, rather than held (and read again, destroyed or - // recycled into something else) by every later change - if (isRenderable(_transitionConfig.shape)) { + // The transition is set once and kept, and so is a sprite + // the game keeps for itself. One this change destroys, + // one level's player, is read now and let go, rather + // than held (and read again, destroyed or recycled into + // something else) by every later change + if (goesWithTheStage(_transitionConfig.shape)) { _transitionConfig.shape = undefined; _transitionConfig.released = true; } - if (isRenderable(_transitionConfig.center)) { + if (goesWithTheStage(_transitionConfig.center)) { _transitionConfig.center = undefined; } // see the note in the fade case: persistent is what diff --git a/packages/melonjs/tests/mask-transition-sprite.spec.js b/packages/melonjs/tests/mask-transition-sprite.spec.js index f66506fee..b8fd3c04c 100644 --- a/packages/melonjs/tests/mask-transition-sprite.spec.js +++ b/packages/melonjs/tests/mask-transition-sprite.spec.js @@ -1,11 +1,23 @@ -import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; import { Application, boot, + Container, + FadeEffect, MaskEffect, Sprite, Stage, state, + TextureAtlas, video, } from "../src/index.js"; import { readPixel } from "./helpers/pixels.js"; @@ -15,6 +27,13 @@ import { readPixel } from "./helpers/pixels.js"; * hide closes on the player with the player's own silhouette, and the reveal * opens from the same place with the same silhouette, though the state * change has destroyed the player in between. + * + * And the way to use one for a single change: set it, call `state.change()`, + * set the usual transition back on the next line. + * + * A sprite is let go after one transition only when the change takes it: one + * the game keeps for itself, outside any level, or a persistent one, is set + * once and shapes every change. */ const DURATION = 60; @@ -59,6 +78,58 @@ const leftHalf = () => { return canvas; }; +/** what is on the camera now, as `Class:direction` */ +const effectsOn = (app) => { + return app.viewport.cameraEffects.map((fx) => { + return `${fx.constructor.name}:${fx.direction}`; + }); +}; + +/** the side of a silhouette that holds more of the shape, "left" or "right" */ +const heavierSide = (silhouette) => { + const canvas = silhouette.target.canvas; + const { width, height } = canvas; + const { data } = canvas.getContext("2d").getImageData(0, 0, width, height); + let left = 0; + let right = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const alpha = data[(y * width + x) * 4 + 3]; + if (x < width / 2) { + left += alpha; + } else { + right += alpha; + } + } + } + return left > right ? "left" : "right"; +}; + +/** a sprite from an atlas, as `atlas.createSpriteFromName()` makes one */ +const atlasSprite = () => { + const atlas = new TextureAtlas( + { + frames: [ + { + filename: "eat_0000", + frame: { x: 0, y: 0, w: 20, h: 30 }, + rotated: false, + trimmed: false, + spriteSourceSize: { x: 0, y: 0, w: 20, h: 30 }, + sourceSize: { w: 20, h: 30 }, + }, + ], + meta: { + app: "texturepacker", + image: "eat-sheet.png", + size: { w: 20, h: 30 }, + }, + }, + leftHalf(), + ); + return atlas.createSpriteFromName("eat_0000"); +}; + describe("a mask transition shaped like, and closing on, a sprite", () => { let app; beforeAll(async () => { @@ -179,4 +250,290 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { expect(app.viewport.cameraEffects).toHaveLength(0); }); }); + + it("set for one change, then set back at once: that change is the mask, the next one the usual fade", async () => { + let player; + const start = state.USER + 92; + const next = state.USER + 93; + const last = state.USER + 94; + state.set( + start, + new Stage({ + onResetEvent(game) { + player = new Sprite(200, 50, { image: leftHalf() }); + game.world.addChild(player); + }, + }), + ); + state.set(next, new Stage()); + state.set(last, new Stage()); + state.setTransition(start, false); + state.change(start, true); + await runUntil(() => { + expect(state.isCurrent(start)).toBe(true); + expect(player?.ancestor).toBeDefined(); + }); + + // the game's usual transition + state.transition("fade", "#000", DURATION); + + // the player's silhouette, for this change only: the usual one is + // set back before a single frame of the mask has run + state.transition("mask", "#000", DURATION, player); + state.change(next); + state.transition("fade", "#000", DURATION); + + // the hide was built when the change was asked for, from the mask + expect(effectsOn(app)).toEqual(["MaskEffect:hide"]); + const hide = app.viewport.getCameraEffect(MaskEffect); + expect(hide._silhouette).toBeDefined(); + const silhouette = hide._silhouette.target.canvas; + + // the reveal comes from the hide, not from the settings, which are + // the fade's by now: the same mask, the same silhouette + const seen = new Set(); + let reveal; + await runUntil(() => { + for (const name of effectsOn(app)) { + seen.add(name); + } + expect(state.isCurrent(next)).toBe(true); + reveal = app.viewport.cameraEffects.find((fx) => { + return fx instanceof MaskEffect && fx.direction === "reveal"; + }); + expect(reveal).toBeDefined(); + }); + expect(reveal._silhouette.target.canvas).toBe(silhouette); + await runUntil(() => { + for (const name of effectsOn(app)) { + seen.add(name); + } + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + // on no frame of that transition was a fade on the camera + expect([...seen].sort()).toEqual(["MaskEffect:hide", "MaskEffect:reveal"]); + + // the next change is the usual fade, both ways, and never a mask + state.change(last); + expect(app.viewport.getCameraEffect(FadeEffect)).toBeDefined(); + const seenNext = new Set(); + await runUntil(() => { + for (const name of effectsOn(app)) { + seenNext.add(name); + } + expect(state.isCurrent(last)).toBe(true); + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + expect(seenNext.size).toBeGreaterThan(0); + for (const name of seenNext) { + expect(name.startsWith("FadeEffect")).toBe(true); + } + }); + + describe("set once, for every change", () => { + // two empty stages to go back and forth between + const here = state.USER + 95; + const there = state.USER + 96; + let warn; + let current; + + /** change to the other stage, and hand back the hide it starts */ + const change = () => { + current = current === here ? there : here; + state.change(current); + return app.viewport.getCameraEffect(MaskEffect); + }; + /** let the change land and its reveal end */ + const settle = async () => { + await runUntil(() => { + expect(state.isCurrent(current)).toBe(true); + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + }; + const isIris = (effect) => { + return ( + effect._silhouette === undefined && + effect._maskShape?.type === "Ellipse" + ); + }; + + beforeAll(async () => { + state.set(here, new Stage()); + state.set(there, new Stage()); + state.transition("fade", "#000", 0); + current = here; + state.change(here, true); + await runUntil(() => { + expect(state.isCurrent(here)).toBe(true); + }); + }); + beforeEach(() => { + warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + }); + afterEach(async () => { + warn.mockRestore(); + await settle(); + }); + + it("a sprite the game keeps for itself, never in a level, shapes every change", async () => { + // what `atlas.createSpriteFromName()` gives, set once at startup + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + + for (let i = 0; i < 4; i++) { + const hide = change(); + expect(hide.direction).toBe("hide"); + expect(hide._silhouette, `change ${i + 1}`).toBeDefined(); + await settle(); + // no change destroyed it + expect(sprite.offset).toBeDefined(); + } + expect(warn).not.toHaveBeenCalled(); + }); + + it("each change draws the frame the sprite shows by then", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + + // the image's left half is the opaque one + expect(heavierSide(change()._silhouette)).toBe("left"); + await settle(); + + // the game turns its sprite around: the next change is not the + // picture of the first one, kept, but the sprite read again + sprite.flipX(true); + expect(heavierSide(change()._silhouette)).toBe("right"); + await settle(); + + sprite.flipX(false); + expect(heavierSide(change()._silhouette)).toBe("left"); + }); + + it("a persistent sprite in the world, and one in a persistent container, are kept", async () => { + const lone = new Sprite(40, 40, { image: leftHalf() }); + lone.isPersistent = true; + app.world.addChild(lone); + + const hud = new Container(0, 0, 320, 240); + hud.isPersistent = true; + const inHud = new Sprite(100, 100, { image: leftHalf() }); + hud.addChild(inHud); + app.world.addChild(hud); + + for (const sprite of [lone, inHud]) { + state.transition("mask", "#000", DURATION, sprite, { center: sprite }); + for (let i = 0; i < 3; i++) { + const hide = change(); + expect(hide._silhouette, `change ${i + 1}`).toBeDefined(); + expect(hide.center, `change ${i + 1}`).toBeDefined(); + await settle(); + // the change left it in the world + expect(sprite.ancestor).toBeDefined(); + } + } + expect(warn).not.toHaveBeenCalled(); + + app.world.removeChildNow(lone); + app.world.removeChildNow(hud); + }); + + it("a sprite inside a container of the level goes with it, and is let go", async () => { + const room = new Container(0, 0, 320, 240); + const inRoom = new Sprite(100, 100, { image: leftHalf() }); + room.addChild(inRoom); + app.world.addChild(room); + state.transition("mask", "#000", DURATION, inRoom, { center: inRoom }); + + const first = change(); + expect(first._silhouette).toBeDefined(); + expect(first.center).toBeDefined(); + await settle(); + // the change destroyed it + expect(inRoom.offset).toBeUndefined(); + + const second = change(); + expect(isIris(second)).toBe(true); + expect(second.center).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); + + it("a persistent sprite inside a container of the level is let go with it", async () => { + // Persistent is a word to the container a renderable is a child + // of, and the world only asks its own children: the room goes, + // and what it held is left in a container that is no more. + // Nothing to keep reading a place on screen from + const room = new Container(0, 0, 320, 240); + const inRoom = new Sprite(100, 100, { image: leftHalf() }); + inRoom.isPersistent = true; + room.addChild(inRoom); + app.world.addChild(room); + state.transition("mask", "#000", DURATION, inRoom, { center: inRoom }); + + const first = change(); + expect(first._silhouette).toBeDefined(); + expect(first.center).toBeDefined(); + await settle(); + expect(room.ancestor).toBeUndefined(); + + const second = change(); + expect(isIris(second)).toBe(true); + expect(second.center).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); + + it("kept while it is the game's own, let go by the change that finds it in a level", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + expect(change()._silhouette).toBeDefined(); + await settle(); + expect(change()._silhouette).toBeDefined(); + await settle(); + + // now it joins a level: this change still wears it, and takes it + app.world.addChild(sprite); + expect(change()._silhouette).toBeDefined(); + await settle(); + expect(sprite.offset).toBeUndefined(); + + expect(isIris(change())).toBe(true); + expect(warn).not.toHaveBeenCalled(); + }); + + it("a sprite in a container that is in no world is kept", async () => { + const shelf = new Container(0, 0, 100, 100); + const sprite = new Sprite(10, 10, { image: leftHalf() }); + shelf.addChild(sprite); + state.transition("mask", "#000", DURATION, sprite); + for (let i = 0; i < 3; i++) { + expect(change()._silhouette, `change ${i + 1}`).toBeDefined(); + await settle(); + } + expect(warn).not.toHaveBeenCalled(); + }); + + it("a kept sprite the game destroys later: an iris from then on, not an error", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite, { center: sprite }); + expect(change()._silhouette).toBeDefined(); + await settle(); + + sprite.destroy(); + const hide = change(); + expect(isIris(hide)).toBe(true); + await settle(); + expect(isIris(change())).toBe(true); + }); + + it("setting another transition forgets a kept sprite", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + expect(change()._silhouette).toBeDefined(); + await settle(); + + state.transition("fade", "#000", DURATION); + state.change((current = current === here ? there : here)); + expect(app.viewport.getCameraEffect(MaskEffect)).toBeUndefined(); + expect(app.viewport.getCameraEffect(FadeEffect)).toBeDefined(); + }); + }); });