@inglorious/engine 24.11.0 → 24.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -136,12 +136,12 @@ both at once, which is the difference between moving the thing and moving its ou
136
136
 
137
137
  ### Pausing
138
138
 
139
- `api.notify("pause")` stops the store handing out `update` events, and `notify("resume")` starts it again:
139
+ `api.notify("pause")` stops the store handing out `update` events, and `notify("resume")` starts it again. `pauseToggle` sends whichever of the two is due, for a single key or button (`Space: "pauseToggle"`); a state that does more on it, such as playing a sound, answers it itself:
140
140
 
141
141
  ```javascript
142
142
  fsm({
143
143
  play: {
144
- togglePause(entity, _, api) {
144
+ pauseToggle(entity, _, api) {
145
145
  api.notify("soundPlay", "pause")
146
146
  api.notify(entity.paused ? "resume" : "pause")
147
147
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "24.11.0",
3
+ "version": "24.12.1",
4
4
  "description": "A JavaScript game engine written with global state, immutability, and pure functions in mind. Have fun(ctional programming) with it!",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -9,6 +9,8 @@ export function audio() {
9
9
  // imported -- and a module that reaches for `window` on the way in cannot be imported
10
10
  // where there is no window, which is anywhere a test runs.
11
11
  let audioContext
12
+ // Whether the sound was quieted because the page was hidden, to bring it back.
13
+ let hushed = false
12
14
 
13
15
  function context() {
14
16
  audioContext ??= new (window.AudioContext || window.webkitAudioContext)()
@@ -80,6 +82,24 @@ export function audio() {
80
82
  activeSources.delete(name)
81
83
  },
82
84
 
85
+ // A hidden page goes quiet, and its sound comes back with it. Browsers keep
86
+ // playing Web Audio in a background tab, so a game would go on sounding from a
87
+ // tab the player has left. Suspending the context rather than stopping the
88
+ // sources keeps every sound where it was, music included. A context still
89
+ // waiting for the user's first gesture is left waiting: resuming it without one
90
+ // is refused by autoplay policy (https://developer.chrome.com/blog/autoplay).
91
+ visibilityChange(entity, state) {
92
+ if (state === "hidden") {
93
+ if (audioContext?.state !== "running") return
94
+ audioContext.suspend()
95
+ hushed = true
96
+ return
97
+ }
98
+ if (!hushed) return
99
+ hushed = false
100
+ audioContext.resume()
101
+ },
102
+
83
103
  stop: release,
84
104
 
85
105
  destroy: release,
@@ -8,6 +8,11 @@ export function game() {
8
8
  entity.paused = false
9
9
  },
10
10
 
11
+ // one key or button for both: pauses a running world, resumes a paused one
12
+ pauseToggle(entity, payload, api) {
13
+ api.notify(entity.paused ? "resume" : "pause")
14
+ },
15
+
11
16
  quit(entity) {
12
17
  entity.quit = true
13
18
  },
@@ -40,7 +40,7 @@ const storedAt = new Map()
40
40
  * new seed); the one before ends where it was. Ignored while replaying, so a replay
41
41
  * is not knocked off its runs. `create` always starts one.
42
42
  *
43
- * It handles `saveRecording` (the session so far, downloaded as a JSON file),
43
+ * It handles `recordingSave` (the session so far, downloaded as a JSON file),
44
44
  * `replayLoad` (a session to play back, typically a file dropped on the page: see
45
45
  * `onDroppedJSON` and `engine.notify`; on success it notifies `replayStart`, for the
46
46
  * game to leave its menus) and `replayStop`. While replaying, `entity.replay` is
@@ -188,8 +188,8 @@ export function recorded({
188
188
  else entity.replay = { ...recorder.progress(), over: true }
189
189
  },
190
190
 
191
- saveRecording(entity, payload, api) {
192
- type.saveRecording?.(entity, payload, api)
191
+ recordingSave(entity, payload, api) {
192
+ type.recordingSave?.(entity, payload, api)
193
193
  const session = recorderOf(entity).session(
194
194
  turn(entity) ?? NO_TURNS,
195
195
  state(entity),
@@ -48,19 +48,22 @@ function release(entity, id) {
48
48
  }
49
49
 
50
50
  /**
51
- * What a button is for: notifies its `action` when it is pressed. A behaviour next to
52
- * `button()`, which only knows how a button looks.
51
+ * What a button is for: notifies its `event`, with its `payload` if it has one, when
52
+ * it is pressed. A behaviour next to `button()`, which only knows how a button looks.
53
+ * The payload lets buttons that differ by one value share an event: a level picker's
54
+ * buttons all notify `levelPlay`, each with its own level.
53
55
  *
54
56
  * @example
55
57
  * ```js
56
58
  * types: { Button: [button(), pressable(), { render: renderButton }] }
57
- * entities: { pause: { type: "Button", action: "togglePause", label: "Pause" } }
59
+ * entities: { pause: { type: "Button", event: "pauseToggle", label: "Pause" } }
58
60
  * ```
59
61
  */
60
62
  export function pressable() {
61
63
  return {
62
64
  stateChange(entity, { entityId, to }, api) {
63
- if (entityId === entity.id && to === "pressed") api.notify(entity.action)
65
+ if (entityId === entity.id && to === "pressed")
66
+ api.notify(entity.event, entity.payload)
64
67
  },
65
68
  }
66
69
  }
@@ -13,6 +13,7 @@ export const coreEvents = [
13
13
  "mouseMove",
14
14
  "mouseClick",
15
15
  "quit",
16
+ "visibilityChange",
16
17
  "touchStart",
17
18
  "touchMove",
18
19
  "touchEnd",
@@ -103,6 +103,10 @@ export class Engine {
103
103
  */
104
104
  start() {
105
105
  this._store.notify("start")
106
+ globalThis.document?.addEventListener?.(
107
+ "visibilitychange",
108
+ this._onVisibilityChange,
109
+ )
106
110
  this._loop.start(this, ONE_SECOND / this._config.loop.fps)
107
111
  }
108
112
 
@@ -111,11 +115,48 @@ export class Engine {
111
115
  * this by notifying `quit`, which sets the flag the engine reads after each frame.
112
116
  */
113
117
  stop() {
118
+ globalThis.document?.removeEventListener?.(
119
+ "visibilitychange",
120
+ this._onVisibilityChange,
121
+ )
114
122
  this._store.notify("stop")
115
123
  this._store.update()
116
124
  this._loop.stop()
117
125
  }
118
126
 
127
+ /**
128
+ * The page was hidden (another tab, a minimised window) or shown again: the game
129
+ * hears `visibilityChange` with the document's `visibilityState`, "hidden" or
130
+ * "visible", named after the DOM event it comes from.
131
+ *
132
+ * Hidden, it is heard at once rather than queued for the next frame, because
133
+ * browsers stop animation frames in a hidden page and throttle its timers, so the
134
+ * next frame may come only when the page is shown again: too late to quiet the
135
+ * sound. See MDN, Page Visibility API
136
+ * (https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API), and
137
+ * `requestAnimationFrame` ("paused in most browsers when running in background
138
+ * tabs").
139
+ *
140
+ * Shown, the loop leaves out the time it was away (`skipGap`), so the game carries
141
+ * on where it was rather than playing minutes in one frame; the cap on a frame's
142
+ * time (`loops/max-dt.js`) stays for the gaps no event reports. It is heard in the
143
+ * next frame, as any event.
144
+ *
145
+ * Nothing pauses by itself: whether to pause, open a menu or carry on is the
146
+ * game's to decide, and pausing here would unpause, on return, a game the player
147
+ * had paused.
148
+ */
149
+ _onVisibilityChange = () => {
150
+ const state = document.visibilityState
151
+ if (state === "hidden") {
152
+ this._store.notify("visibilityChange", state)
153
+ this._store.update()
154
+ return
155
+ }
156
+ this._loop.skipGap()
157
+ this._store.notify("visibilityChange", state)
158
+ }
159
+
119
160
  /**
120
161
  * Returns the current game state.
121
162
  * @returns {Entities} The entities of the current state.
@@ -1,13 +1,17 @@
1
- const ONE_SECOND = 1000
1
+ import { cappedDt } from "./max-dt.js"
2
2
 
3
3
  export class AnimationFrameLoop {
4
- _id = null
5
- _previousTime = new Date()
6
-
7
- start(engine) {
4
+ start(engine, msPerUpdate) {
5
+ this._msPerUpdate = msPerUpdate
6
+ this._previousTime = new Date()
8
7
  this._tick(engine)
9
8
  }
10
9
 
10
+ /** Measures the next frame from now: the time since the last one is not played. */
11
+ skipGap() {
12
+ this._previousTime = new Date()
13
+ }
14
+
11
15
  stop() {
12
16
  window.cancelAnimationFrame(this._id)
13
17
  this._id = null
@@ -18,7 +22,7 @@ export class AnimationFrameLoop {
18
22
  this._id = window.requestAnimationFrame(() => this._tick(engine))
19
23
  const dt = currentTime - this._previousTime
20
24
 
21
- engine.update(dt / ONE_SECOND)
25
+ engine.update(cappedDt(dt, this._msPerUpdate))
22
26
 
23
27
  this._previousTime = currentTime
24
28
  }
@@ -1,24 +1,30 @@
1
- const ONE_SECOND = 1000
1
+ import { cappedDt } from "./max-dt.js"
2
+
2
3
  const NO_WAIT = 0
3
4
 
4
5
  export class FixedLoop {
5
6
  _shouldStop = false
6
7
 
7
8
  async start(engine, msPerUpdate) {
8
- let previousTime = Date.now()
9
+ this._previousTime = Date.now()
9
10
 
10
11
  while (!this._shouldStop) {
11
12
  const currentTime = Date.now()
12
- const dt = currentTime - previousTime
13
+ const dt = currentTime - this._previousTime
13
14
 
14
- engine.update(dt / ONE_SECOND)
15
+ engine.update(cappedDt(dt, msPerUpdate))
15
16
 
16
- previousTime = currentTime
17
+ this._previousTime = currentTime
17
18
 
18
19
  await sleep(Math.max(NO_WAIT, msPerUpdate - (Date.now() - currentTime)))
19
20
  }
20
21
  }
21
22
 
23
+ /** Measures the next frame from now: the time since the last one is not played. */
24
+ skipGap() {
25
+ this._previousTime = Date.now()
26
+ }
27
+
22
28
  stop() {
23
29
  this._shouldStop = true
24
30
  }
@@ -0,0 +1,26 @@
1
+ const ONE_SECOND = 1000
2
+ // The longest frame a loop reports, in milliseconds. A quarter of a second, as in
3
+ // Glenn Fiedler's "Fix Your Timestep!"
4
+ // (https://gafferongames.com/post/fix_your_timestep/), where it keeps a fixed-step
5
+ // world from the "spiral of death": a long frame owes many steps, those steps make
6
+ // the next frame long, and so on. It is well above any frame a working game makes
7
+ // (it allows down to 4 frames a second), so it never slows a slow device; a much
8
+ // lower cap, such as 1/60 s, would: at 30 frames a second the game would run at half
9
+ // speed, and a world turned faster than real time could never keep up.
10
+ const MAX_FRAME = 250
11
+ const NO_RATE = 0
12
+
13
+ /**
14
+ * The milliseconds a frame may cover: `elapsed` as measured, but at most a quarter
15
+ * of a second, or one interval when the loop's own rate is slower than that. A tab
16
+ * left in the background stops its animation frames and slows its timers (Chrome
17
+ * wakes chained timers at most once a minute after five minutes hidden:
18
+ * https://developer.chrome.com/blog/timer-throttling-in-chrome-88), so the first
19
+ * frame back can measure minutes: passed on whole, it would jump the world that far
20
+ * ahead in one step. The engine leaves out the time a page was hidden anyway
21
+ * (`skipGap`); the cap is for the gaps no event reports: a debugger's breakpoint, a
22
+ * computer waking from sleep, a long freeze, and Node, where there is no page.
23
+ */
24
+ export function cappedDt(elapsed, msPerUpdate = NO_RATE) {
25
+ return Math.min(elapsed, Math.max(MAX_FRAME, msPerUpdate)) / ONE_SECOND
26
+ }
@@ -1,9 +1,10 @@
1
1
  import type { GameEntity, Handler } from "../index"
2
2
 
3
- /** The `game` entity's own handlers: pause, resume, quit, and `C` and `D` for debug and dev mode. */
3
+ /** The `game` entity's own handlers: pause, resume, pause toggle, quit, and `C` and `D` for debug and dev mode. */
4
4
  export function game(): {
5
5
  pause: Handler<GameEntity>
6
6
  resume: Handler<GameEntity>
7
+ pauseToggle: Handler<GameEntity>
7
8
  quit: Handler<GameEntity>
8
9
  keyboardKeyUp: Handler<GameEntity, string>
9
10
  }
@@ -50,7 +50,7 @@ export function recorded<
50
50
  Record<string, Handler<TEntity, unknown>> & {
51
51
  create: Handler<TEntity, unknown>
52
52
  tick: Handler<TEntity, number>
53
- saveRecording: Handler<TEntity, unknown>
53
+ recordingSave: Handler<TEntity, unknown>
54
54
  replayLoad: Handler<TEntity, RecordedSession<About, Input>>
55
55
  replayStop: Handler<TEntity, unknown>
56
56
  }
@@ -4,12 +4,14 @@ export interface ButtonEntity extends Entity {
4
4
  state?: "default" | "pressed"
5
5
  /** True while the pointer is over it. */
6
6
  hovered?: boolean
7
- /** What `pressable()` notifies when it is pressed. */
8
- action?: string
7
+ /** The event `pressable()` notifies when it is pressed. */
8
+ event?: string
9
+ /** What that event carries, if anything. */
10
+ payload?: unknown
9
11
  }
10
12
 
11
13
  /** Looks pressed from `entityPress` to `entityRelease` (or `entityTouchStart` to `entityTouchEnd`), and announces it through `stateChange`. */
12
14
  export function button(): Decorator<GameType<ButtonEntity>>
13
15
 
14
- /** Notifies the button's `action` when it is pressed. */
16
+ /** Notifies the button's `event`, with its `payload`, when it is pressed. */
15
17
  export function pressable(): GameType<ButtonEntity>
@@ -1,7 +1,12 @@
1
1
  import type { Updatable } from "./index"
2
2
 
3
- /** Updates once per animation frame, as fast as the screen takes it. */
3
+ /**
4
+ * Updates once per animation frame, as fast as the screen takes it. A frame covers
5
+ * at most a quarter of a second, so a tab back from the background does not jump.
6
+ */
4
7
  export class AnimationFrameLoop {
5
- start(engine: Updatable): void
8
+ start(engine: Updatable, msPerUpdate?: number): void
9
+ /** Measures the next frame from now: the time since the last one is not played. */
10
+ skipGap(): void
6
11
  stop(): void
7
12
  }
@@ -1,7 +1,13 @@
1
1
  import type { Updatable } from "./index"
2
2
 
3
- /** Updates every `msPerUpdate` milliseconds. */
3
+ /**
4
+ * Updates every `msPerUpdate` milliseconds. A frame covers at most a quarter of a
5
+ * second, or one interval if that is longer, so a tab back from the background
6
+ * does not jump.
7
+ */
4
8
  export class FixedLoop {
5
9
  start(engine: Updatable, msPerUpdate: number): Promise<void>
10
+ /** Measures the next frame from now: the time since the last one is not played. */
11
+ skipGap(): void
6
12
  stop(): void
7
13
  }