@inglorious/engine 23.0.2 → 23.0.4

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.
Files changed (70) hide show
  1. package/README.md +223 -0
  2. package/package.json +9 -5
  3. package/src/ai/movement/dynamic/align.js +1 -1
  4. package/src/ai/movement/dynamic/arrive.js +1 -1
  5. package/src/ai/movement/dynamic/evade.js +1 -1
  6. package/src/ai/movement/dynamic/face.js +1 -1
  7. package/src/ai/movement/dynamic/flee.js +1 -1
  8. package/src/ai/movement/dynamic/look-where-youre-going.js +1 -1
  9. package/src/ai/movement/dynamic/match-velocity.js +1 -1
  10. package/src/ai/movement/dynamic/pursue.js +1 -1
  11. package/src/ai/movement/dynamic/seek.js +1 -1
  12. package/src/ai/movement/dynamic/wander.js +1 -1
  13. package/src/ai/movement/kinematic/align.js +1 -1
  14. package/src/ai/movement/kinematic/arrive.js +1 -1
  15. package/src/ai/movement/kinematic/face.js +1 -1
  16. package/src/ai/movement/kinematic/flee.js +1 -1
  17. package/src/ai/movement/kinematic/seek.js +1 -1
  18. package/src/ai/movement/kinematic/wander-as-seek.js +1 -1
  19. package/src/ai/movement/kinematic/wander.js +1 -1
  20. package/src/animation/due.js +36 -0
  21. package/src/animation/sprite.js +1 -1
  22. package/src/behaviors/at-fps.js +49 -0
  23. package/src/behaviors/audio.js +82 -18
  24. package/src/behaviors/camera.js +1 -1
  25. package/src/behaviors/controls/dynamic/modern.js +2 -2
  26. package/src/behaviors/controls/dynamic/shooter.js +2 -2
  27. package/src/behaviors/controls/dynamic/tank.js +2 -2
  28. package/src/behaviors/controls/event-handlers.js +19 -16
  29. package/src/behaviors/controls/kinematic/modern.js +2 -2
  30. package/src/behaviors/controls/kinematic/shooter.js +2 -2
  31. package/src/behaviors/controls/kinematic/tank.js +2 -2
  32. package/src/behaviors/debug/collision.js +18 -4
  33. package/src/behaviors/fps.js +1 -1
  34. package/src/behaviors/game.js +14 -0
  35. package/src/behaviors/infinite-scroll.js +5 -2
  36. package/src/behaviors/input/controls.js +45 -12
  37. package/src/behaviors/input/gamepad.js +30 -29
  38. package/src/behaviors/input/hover.js +57 -0
  39. package/src/behaviors/input/input.js +22 -14
  40. package/src/behaviors/input/keyboard.js +79 -12
  41. package/src/behaviors/input/mouse.js +76 -11
  42. package/src/behaviors/input/pointer.js +39 -0
  43. package/src/behaviors/input/touch.js +2 -2
  44. package/src/behaviors/particles.js +124 -0
  45. package/src/behaviors/physics/bouncy.js +1 -1
  46. package/src/behaviors/physics/clamped.js +1 -1
  47. package/src/behaviors/physics/jumpable.js +7 -5
  48. package/src/behaviors/state-machine/fsm.js +55 -0
  49. package/src/behaviors/state-machine/mappings.js +59 -0
  50. package/src/behaviors/state-machine/scenes.js +89 -0
  51. package/src/behaviors/ui/button.js +26 -11
  52. package/src/behaviors/ui/slider.js +114 -0
  53. package/src/collision/detection.js +37 -6
  54. package/src/core/core-events.js +3 -0
  55. package/src/core/engine.js +70 -7
  56. package/src/core/loops/fixed.js +6 -1
  57. package/src/core/loops/index.js +23 -3
  58. package/src/core/middlewares/entity-pool/entity-pool-middleware.js +20 -2
  59. package/src/core/middlewares/entity-pool/entity-pools.js +4 -0
  60. package/src/core/types.js +50 -0
  61. package/src/movement/dynamic/modern.js +1 -1
  62. package/src/movement/dynamic/tank.js +1 -1
  63. package/src/movement/kinematic/modern.js +1 -1
  64. package/src/movement/kinematic/tank.js +1 -1
  65. package/src/physics/anchor.js +115 -0
  66. package/src/physics/bounds.js +34 -27
  67. package/src/physics/position.js +29 -11
  68. package/src/storage.js +53 -0
  69. package/src/test.js +185 -0
  70. package/src/behaviors/fsm.js +0 -31
package/README.md CHANGED
@@ -26,6 +26,229 @@ This will set up a complete project with a development server ready to go.
26
26
  - **Composable by Design**: Build complex behaviors by composing pure functions and decorators, offering a powerful alternative to inheritance.
27
27
  - **Renderer Agnostic**: The engine is headless. You can use any rendering technology you like, from Canvas2D and HTML to React components.
28
28
  - **Zero Build Step Option**: Write plain JavaScript and run it directly in the browser. No complex build configurations required.
29
+ - **Pausing without permission checks**: `notify("pause")` halts the world, so nothing that moves has to ask whether it is allowed to.
30
+ - **A way out that works anywhere**: `notify("quit")` ends the game, from any state, without a handler of its own.
31
+ - **Sprites in one call**: `crop()` points an entity at a frame of a sheet without you having to remember which half of the crop lives where. See [renderer-2d](https://github.com/iceonfire/inglorious-forge/tree/main/packages/renderer-2d).
32
+ - **Screens that share a world**: `scenes()` puts a state's entities up and takes the last state's down, leaving whatever the two have in common standing.
33
+ - **A mistyped type is an error**: the engine refuses a configuration whose entity names a type nothing declared, and says which type was nearly meant.
34
+
35
+ ### Scenes
36
+
37
+ A state machine says when it moves; `scenes()` says what each state is made of. Pair them
38
+ and each screen is a description of what should be standing there:
39
+
40
+ ```javascript
41
+ import { fsm } from "@inglorious/engine/behaviors/fsm.js"
42
+ import { scenes } from "@inglorious/engine/behaviors/scenes.js"
43
+
44
+ const SCENES = {
45
+ title: () => [createTitleEntity(), createMenuEntity()],
46
+ play: () => [createPaddleEntity(), createBallEntity()],
47
+ }
48
+
49
+ const types = {
50
+ Game: [
51
+ scenes(SCENES),
52
+ fsm({
53
+ title: {
54
+ start(entity) {
55
+ entity.state = "play"
56
+ },
57
+ },
58
+ }),
59
+ ],
60
+ }
61
+
62
+ const entities = { game: { type: "Game", state: "title" } }
63
+ ```
64
+
65
+ Only the difference between two states is touched. Anything they share stays standing as it
66
+ is — which is what carries a paddle, a ball and a level from the serve into the play without
67
+ rebuilding them, and so without losing where the paddle had slid to or what had already been
68
+ knocked out. Without it, every move between two states that share a world rebuilds it.
69
+
70
+ A state is also handed the entity asking for it, so anything worth making only once — a
71
+ level, say — can be held on the entity and left alone the second time round.
72
+
73
+ ### Collision
74
+
75
+ Give an entity a `collisions` block and it is solid:
76
+
77
+ ```javascript
78
+ entities: {
79
+ brick: {
80
+ type: "Brick",
81
+ size: [32, 16, 0],
82
+ collisions: { hitbox: { shape: "rectangle" } },
83
+ },
84
+ }
85
+ ```
86
+
87
+ Or, for the shape almost everything solid wants, say so in one word:
88
+
89
+ ```javascript
90
+ entities: {
91
+ brick: { type: "Brick", size: [32, 16, 0], solid: true },
92
+ }
93
+ ```
94
+
95
+ `solid: true` means "collide with a rectangle the size of `size`". It is asked for rather
96
+ than assumed from the presence of a `size`, because plenty of things have a size and are
97
+ not in the way: a line of text, a frame counter, anything measured in pixels rather than
98
+ in space. Making `size` imply solidity would quietly turn all of those into walls.
99
+
100
+ A declared `collisions` block still wins, so an entity can be solid and still have a hit
101
+ box smaller than itself, or shaped like a point or a circle.
102
+
103
+ A block may also carry its own `size` and `offset`, so the shape can be measured from a
104
+ different place than the sprite is drawn from:
105
+
106
+ All nine anchors are exported by name from `@inglorious/engine/physics/anchor.js` --
107
+ `TOP_LEFT`, `TOP_CENTER`, `TOP_RIGHT`, `LEFT`, `CENTER`, `RIGHT`, `BOTTOM_LEFT`,
108
+ `BOTTOM_CENTER` and `BOTTOM_RIGHT`. Write those rather than the numbers: an anchor
109
+ counts from the low end of every axis, so `[0, 1]` is `TOP_LEFT` and not
110
+ `BOTTOM_LEFT`, and getting it backwards changes where things are drawn _and_ where
111
+ they collide.
112
+
113
+ ```javascript
114
+ import { TOP_LEFT } from "@inglorious/engine/physics/anchor.js"
115
+
116
+ ball: {
117
+ type: "Ball",
118
+ position: v(100, 100, 0),
119
+ size: v(16, 16, 0),
120
+ anchor: TOP_LEFT, // the sprite is drawn from its top left corner
121
+ collisions: {
122
+ // ...but the circle is measured from its middle, so it is pushed there
123
+ hitbox: { shape: "circle", radius: 8, offset: v(8, 8, 0) },
124
+ },
125
+ }
126
+ ```
127
+
128
+ Useful whenever the two shapes disagree about where they are measured from — a square
129
+ sprite from a corner against a circle collision from its centre. `entity.offset` shifts
130
+ both at once, which is the difference between moving the thing and moving its outline.
131
+
132
+ ### Pausing
133
+
134
+ `api.notify("pause")` stops the store handing out `update` events, and `notify("resume")` starts it again:
135
+
136
+ ```javascript
137
+ fsm({
138
+ play: {
139
+ togglePause(entity, _, api) {
140
+ api.notify("soundPlay", "pause")
141
+ api.notify(entity.paused ? "resume" : "pause")
142
+ },
143
+ },
144
+ })
145
+ ```
146
+
147
+ The game entity already keeps a readable `paused` flag, which is what that handler reads. Because `update` is never called while halted, a moving entity needs no pause check of its own:
148
+
149
+ ```javascript
150
+ update(entity, dt) {
151
+ // Never runs while paused, so nothing here has to know about pausing.
152
+ entity.position[0] += entity.velocity[0] * dt
153
+ }
154
+ ```
155
+
156
+ Everything else keeps flowing, so the thing that takes the pause back off still receives its events. A type that must keep updating declares it, which is for overlays and pause menus rather than gameplay:
157
+
158
+ ```javascript
159
+ const Paused = [
160
+ { updatesWhilePaused: true },
161
+ { render: renderText },
162
+ { update },
163
+ ]
164
+ ```
165
+
166
+ The default is to **stop**. Anything that keeps going has to say so, so forgetting a flag pauses the thing you meant to pause rather than freezing the menu. See the [store's built-in events](https://github.com/iceonfire/inglorious-forge/tree/main/packages/store#built-in-events) for the full behaviour.
167
+
168
+ ## Testing a game
169
+
170
+ `@inglorious/engine/test` is the harness for testing a game against its own store: no
171
+ canvas, no browser, no loop.
172
+
173
+ ```javascript
174
+ // test/game.test.js
175
+ import { beforeEach, describe, expect, test } from "vitest"
176
+
177
+ import { createGame } from "@inglorious/engine/test"
178
+
179
+ import gameConfig from "../src/game.ijs"
180
+
181
+ describe("Pong", () => {
182
+ let game
183
+
184
+ beforeEach(() => {
185
+ game = createGame(gameConfig)
186
+ })
187
+
188
+ test("begins the serve on space", () => {
189
+ // given
190
+ game.step(4)
191
+
192
+ // when
193
+ game.press("Space")
194
+
195
+ // then
196
+ expect(game.entity("game").state).toBe("serve")
197
+ })
198
+ })
199
+ ```
200
+
201
+ Each test makes its own game in `beforeEach`, and states what it needs in its `given`. A
202
+ test that inherits from the one before it can only be run in one order.
203
+
204
+ ### The game under test
205
+
206
+ | | |
207
+ | ---------------------------------------------- | ------------------------------------------------------------------------ |
208
+ | `game.entity(id)` | one entity, by the name the game knows it by |
209
+ | `game.state()` | the lot, for keys and for `Object.keys` |
210
+ | `game.pooled(type?)` | the pooled entities in play — drawn from a pool rather than in the state |
211
+ | `game.check(condition, description)` | assert, in a failure that says what it was about |
212
+ | `game.playedSounds` | the sounds the game reached for, in order |
213
+ | `game.notify(event, ...args)` | the one way anything is said to it |
214
+ | `game.step(frames)` | run frames |
215
+ | `game.advance(seconds)` | run for a length of time |
216
+ | `game.press(code)` / `game.hold(code, frames)` | tap a key / hold it down |
217
+
218
+ `advance` is there because a test that waits something out is waiting for a lifetime, and
219
+ a lifetime is in seconds. Converting that to frames by hand means assuming how many frames
220
+ there are to a second — and that assumption is wrong by however far the step is from a
221
+ sixtieth, which shows up as flakiness rather than as a failure.
222
+
223
+ ### Testing a game of your own
224
+
225
+ `createGame` takes additions, so a game with a move of its own adds it rather than editing
226
+ the harness:
227
+
228
+ ```javascript
229
+ game = createGame(gameConfig, {
230
+ dropTheBall() {
231
+ this.entity("ball").position[1] = 0
232
+ return this.step(1)
233
+ },
234
+ })
235
+ ```
236
+
237
+ ### Watching and saying
238
+
239
+ `check` is `expect(condition, description)` — the message is what turns a failure into one
240
+ you can read, and the game saying it checks something reads as the game checking something.
241
+
242
+ `playedSounds` is a spy on where sounds are _handled_ rather than where they are asked for, so a
243
+ sound wired to the wrong state is caught.
244
+
245
+ `notify` is the single door into the store, so a test never reaches for `engine._store` —
246
+ which is private, and whose `extras` are the engine's own.
247
+
248
+ ### Two things worth knowing
249
+
250
+ **Dev mode freezes what the store publishes**, which is right for a game in a browser and
251
+ wrong for a test that has to put a ball where a brick is. `createGame` turns it off.
29
252
 
30
253
  ## Documentation
31
254
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "23.0.2",
3
+ "version": "23.0.4",
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",
@@ -33,12 +33,11 @@
33
33
  },
34
34
  "sideEffects": false,
35
35
  "dependencies": {
36
- "@inglorious/store": "11.0.2",
37
- "@inglorious/utils": "4.0.0"
36
+ "@inglorious/store": "11.0.4",
37
+ "@inglorious/utils": "5.0.0"
38
38
  },
39
39
  "peerDependencies": {
40
- "@inglorious/store": "11.0.2",
41
- "@inglorious/utils": "4.0.0"
40
+ "vitest": "^5.0.0"
42
41
  },
43
42
  "devDependencies": {
44
43
  "@inglorious/eslint-config": "1.1.2",
@@ -49,6 +48,11 @@
49
48
  "engines": {
50
49
  "node": ">= 22"
51
50
  },
51
+ "peerDependenciesMeta": {
52
+ "vitest": {
53
+ "optional": true
54
+ }
55
+ },
52
56
  "scripts": {
53
57
  "format": "prettier --write .",
54
58
  "lint": "eslint .",
@@ -1,4 +1,4 @@
1
- import { abs, clamp } from "@inglorious/utils/math/numbers.js"
1
+ import { abs, clamp } from "@inglorious/utils/math/number.js"
2
2
  import { toRange } from "@inglorious/utils/math/trigonometry.js"
3
3
 
4
4
  export const DEFAULT_TARGET_RADIUS = 0.1
@@ -1,5 +1,5 @@
1
1
  import { matchVelocity } from "@inglorious/engine/ai/movement/dynamic/match-velocity.js"
2
- import { magnitude, setMagnitude, subtract } from "@inglorious/utils/vectors"
2
+ import { magnitude, setMagnitude, subtract } from "@inglorious/utils/vector.js"
3
3
 
4
4
  export const DEFAULT_TARGET_RADIUS = 1
5
5
  export const DEFAULT_SLOW_RADIUS = 100
@@ -5,7 +5,7 @@ import {
5
5
  subtract,
6
6
  sum,
7
7
  zero,
8
- } from "@inglorious/utils/vectors"
8
+ } from "@inglorious/utils/vector.js"
9
9
 
10
10
  export const DEFAULT_MAX_PREDICTION = 10
11
11
 
@@ -1,5 +1,5 @@
1
1
  import { align } from "@inglorious/engine/ai/movement/dynamic/align.js"
2
- import { angle, magnitude, subtract } from "@inglorious/utils/vectors"
2
+ import { angle, magnitude, subtract } from "@inglorious/utils/vector.js"
3
3
 
4
4
  export function face(entity, target, dt, options) {
5
5
  const direction = subtract(target.position, entity.position)
@@ -7,7 +7,7 @@ import {
7
7
  subtract,
8
8
  sum,
9
9
  zero,
10
- } from "@inglorious/utils/vectors"
10
+ } from "@inglorious/utils/vector.js"
11
11
 
12
12
  const DEFAULT_MAX_ACCELERATION = 0
13
13
  const DEFAULT_MAX_SPEED = 0
@@ -1,5 +1,5 @@
1
1
  import { align } from "@inglorious/engine/ai/movement/dynamic/align.js"
2
- import { angle, magnitude, zero } from "@inglorious/utils/vectors"
2
+ import { angle, magnitude, zero } from "@inglorious/utils/vector.js"
3
3
 
4
4
  export function lookWhereYoureGoing(entity, dt, options) {
5
5
  const velocity = entity.velocity ?? zero()
@@ -7,7 +7,7 @@ import {
7
7
  subtract,
8
8
  sum,
9
9
  zero,
10
- } from "@inglorious/utils/vectors"
10
+ } from "@inglorious/utils/vector.js"
11
11
 
12
12
  export const DEFAULT_TIME_TO_TARGET = 0.1
13
13
 
@@ -5,7 +5,7 @@ import {
5
5
  subtract,
6
6
  sum,
7
7
  zero,
8
- } from "@inglorious/utils/vectors"
8
+ } from "@inglorious/utils/vector.js"
9
9
 
10
10
  export const DEFAULT_MAX_PREDICTION = 10
11
11
 
@@ -7,7 +7,7 @@ import {
7
7
  subtract,
8
8
  sum,
9
9
  zero,
10
- } from "@inglorious/utils/vectors"
10
+ } from "@inglorious/utils/vector.js"
11
11
 
12
12
  const DEFAULT_MAX_ACCELERATION = 0
13
13
  const DEFAULT_MAX_SPEED = 0
@@ -1,6 +1,6 @@
1
1
  import { seek } from "@inglorious/engine/ai/movement/dynamic/seek.js"
2
2
  import { randomBinomial } from "@inglorious/utils/math/rng.js"
3
- import { createVector, sum } from "@inglorious/utils/vectors"
3
+ import { createVector, sum } from "@inglorious/utils/vector.js"
4
4
 
5
5
  export const DEFAULT_WANDER_OFFSET = 100
6
6
  export const DEFAULT_WANDER_RADIUS = 100
@@ -1,4 +1,4 @@
1
- import { abs, clamp } from "@inglorious/utils/math/numbers.js"
1
+ import { abs, clamp } from "@inglorious/utils/math/number.js"
2
2
  import { toRange } from "@inglorious/utils/math/trigonometry.js"
3
3
 
4
4
  export const DEFAULT_TARGET_RADIUS = 0.1
@@ -6,7 +6,7 @@ import {
6
6
  multiply,
7
7
  subtract,
8
8
  sum,
9
- } from "@inglorious/utils/vectors"
9
+ } from "@inglorious/utils/vector.js"
10
10
 
11
11
  export const DEFAULT_TARGET_RADIUS = 1
12
12
  export const DEFAULT_TIME_TO_TARGET = 0.1
@@ -1,5 +1,5 @@
1
1
  import { align } from "@inglorious/engine/ai/movement/kinematic/align.js"
2
- import { angle, magnitude, subtract } from "@inglorious/utils/vectors"
2
+ import { angle, magnitude, subtract } from "@inglorious/utils/vector.js"
3
3
 
4
4
  export function face(entity, target, dt, options) {
5
5
  const direction = subtract(target.position, entity.position)
@@ -5,7 +5,7 @@ import {
5
5
  setMagnitude,
6
6
  subtract,
7
7
  sum,
8
- } from "@inglorious/utils/vectors"
8
+ } from "@inglorious/utils/vector.js"
9
9
 
10
10
  const DEFAULT_MAX_SPEED = 0
11
11
 
@@ -5,7 +5,7 @@ import {
5
5
  setMagnitude,
6
6
  subtract,
7
7
  sum,
8
- } from "@inglorious/utils/vectors"
8
+ } from "@inglorious/utils/vector.js"
9
9
 
10
10
  const DEFAULT_MAX_SPEED = 0
11
11
 
@@ -1,6 +1,6 @@
1
1
  import { seek } from "@inglorious/engine/ai/movement/kinematic/seek.js"
2
2
  import { randomBinomial } from "@inglorious/utils/math/rng.js"
3
- import { fromAngle, multiply, sum } from "@inglorious/utils/vectors"
3
+ import { fromAngle, multiply, sum } from "@inglorious/utils/vector.js"
4
4
 
5
5
  export const DEFAULT_WANDER_RADIUS = 10
6
6
 
@@ -1,5 +1,5 @@
1
1
  import { randomBinomial } from "@inglorious/utils/math/rng.js"
2
- import { angle, createVector, multiply, sum } from "@inglorious/utils/vectors"
2
+ import { angle, createVector, multiply, sum } from "@inglorious/utils/vector.js"
3
3
 
4
4
  const DEFAULT_MAX_SPEED = 0
5
5
  const DEFAULT_MAX_ANGULAR_SPEED = 0
@@ -0,0 +1,36 @@
1
+ const NO_TIME_PASSED = 0
2
+ // How far short of a rate still counts as reaching it.
3
+ const WITHIN = 1e-9
4
+
5
+ /**
6
+ * Asks whether enough time has passed for something that moves at a rate.
7
+ *
8
+ * Made for the two things that hold themselves back from the loop's pace -- an entity
9
+ * with `atFps`, and a system that keeps its own clock -- so that "has the interval
10
+ * arrived" is written down once rather than twice.
11
+ *
12
+ * It hands back the time to account for on this turn and the time still to come, rather
13
+ * than only saying yes: an entity held to ten frames a second is told how long it has
14
+ * been since its last move, because six frames of a sixtieth of a second have to come
15
+ * to a tenth of a second for a game moving by velocity times dt.
16
+ *
17
+ * This is not the engine's `Ticker`, which answers the same question and then forgets
18
+ * how long it took: it resets its counter to zero as it fires, so by the time the
19
+ * handler ran, the time it had just measured was gone.
20
+ *
21
+ * @param {number} interval - How long between turns, in seconds.
22
+ * @returns {Function} Given the time already waited and the time just passed.
23
+ */
24
+ export function dueAt(interval) {
25
+ return function isDue(clock, dt) {
26
+ const since = clock + dt
27
+
28
+ // A shade short of the interval counts as reaching it. Frame times are added up, and
29
+ // six of a sixtieth of a second come to a hair under a tenth of one, which would
30
+ // otherwise leave something moving ten times a second moving at nine. An interval of
31
+ // nothing is never short of anything, so that moves every time it is asked.
32
+ if (since + interval * WITHIN < interval) return { since }
33
+
34
+ return { elapsed: since, since: NO_TIME_PASSED }
35
+ }
36
+ }
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable no-magic-numbers */
2
2
  import { Ticker } from "@inglorious/engine/animation/ticker.js"
3
- import { mod } from "@inglorious/utils/math/numbers.js"
3
+ import { mod } from "@inglorious/utils/math/number.js"
4
4
  import { pi, toRange } from "@inglorious/utils/math/trigonometry.js"
5
5
 
6
6
  export const Sprite = {
@@ -0,0 +1,49 @@
1
+ import { dueAt } from "@inglorious/engine/animation/due.js"
2
+
3
+ const ONE_SECOND = 1
4
+
5
+ /**
6
+ * An entity that moves at its own rate rather than at the loop's.
7
+ *
8
+ * This is how a game says "this one moves every frame, that one moves ten times a
9
+ * second": the loop stays as fast as the browser will take it -- which is what keeps
10
+ * input and the screen smooth -- and each entity that wants to be slower keeps its own
11
+ * time and is only updated when that time has run out.
12
+ *
13
+ * The rate is a ceiling and not a floor: a frame that leaves more time than the rate
14
+ * allows carries all of it into the next update, so the entity still accounts for every
15
+ * second that really went by.
16
+ *
17
+ * Put it **last** in a type's behaviors. Each one wraps the ones before it and calls on
18
+ * to them, so the last one is the one the store reaches first; anywhere else it is
19
+ * wrapped in turn and never gets a say.
20
+ *
21
+ * @param {number} fps - How many times a second this entity is updated. `Infinity` for
22
+ * every frame, which is also what the engine's default is.
23
+ * @returns {Function} A behavior wrapping whatever it is put in front of.
24
+ */
25
+ export function atFps(fps) {
26
+ const isDue = dueAt(ONE_SECOND / fps)
27
+
28
+ return (type) => ({
29
+ create(entity, payload, api) {
30
+ type.create?.(entity, payload, api)
31
+
32
+ entity.fpsClock = 0
33
+ },
34
+
35
+ update(entity, dt, api) {
36
+ const { elapsed, since } = isDue(entity.fpsClock, dt)
37
+
38
+ entity.fpsClock = since
39
+
40
+ if (elapsed === undefined) return
41
+
42
+ // The whole of the time this entity's turn covers, rather than the length of the
43
+ // frame that happened to land on it: six frames of a sixtieth of a second are a
44
+ // tenth of a second, and a game moving by velocity times dt has to move by all of
45
+ // it or it runs six times too slowly for asking to move ten times a second.
46
+ type.update?.(entity, elapsed, api)
47
+ },
48
+ })
49
+ }
@@ -1,37 +1,102 @@
1
1
  const DEFAULT_VOLUME = 1
2
2
 
3
- export function audio() {
4
- const audioContext = new (window.AudioContext || window.webkitAudioContext)()
3
+ /**
4
+ * Fetches and decodes one sound. A sound that is missing, or that the browser
5
+ * cannot decode, is reported and skipped: losing one effect is not worth refusing
6
+ * to start.
7
+ */
8
+ async function load(context, cache, name, url) {
9
+ try {
10
+ const response = await fetch(url)
11
+
12
+ if (!response.ok) {
13
+ console.warn(`Sound '${name}' could not be fetched from ${url}`)
14
+ return
15
+ }
16
+
17
+ const audioBuffer = await context.decodeAudioData(
18
+ await response.arrayBuffer(),
19
+ )
20
+
21
+ cache.set(name, audioBuffer)
22
+ } catch (error) {
23
+ console.warn(`Sound '${name}' could not be loaded from ${url}`, error)
24
+ }
25
+ }
5
26
 
27
+ export function audio() {
6
28
  const audioBufferCache = new Map()
7
29
  const activeSources = new Map()
8
30
 
31
+ // The context is made when something first asks for sound rather than when this is
32
+ // called, because the engine's own default configuration builds every behaviour as it is
33
+ // imported -- and a module that reaches for `window` on the way in cannot be imported
34
+ // where there is no window, which is anywhere a test runs.
35
+ let audioContext
36
+
37
+ function context() {
38
+ audioContext ??= new (window.AudioContext || window.webkitAudioContext)()
39
+
40
+ return audioContext
41
+ }
42
+
43
+ function resume() {
44
+ window.removeEventListener("pointerdown", resume)
45
+ window.removeEventListener("keydown", resume)
46
+ context().resume()
47
+ }
48
+
49
+ // Both stopping the game and being taken off the world have to let go of the window and
50
+ // of anything still sounding over it. One function, because the two differ only in when
51
+ // they happen -- and a listener an entity that is no longer in the world forgot to take
52
+ // off would stay on the page for as long as the page is open.
53
+ function release() {
54
+ window.removeEventListener("pointerdown", resume)
55
+ window.removeEventListener("keydown", resume)
56
+
57
+ for (const source of activeSources.values()) {
58
+ source.stop()
59
+ }
60
+
61
+ activeSources.clear()
62
+ }
63
+
9
64
  return {
65
+ create() {
66
+ // Browsers keep an AudioContext suspended until the user interacts with
67
+ // the page, so playback would be silently dropped until then.
68
+ window.addEventListener("pointerdown", resume)
69
+ window.addEventListener("keydown", resume)
70
+ },
71
+
10
72
  async init(entity) {
11
73
  const sounds = entity.sounds || {}
12
74
 
13
75
  await Promise.all(
14
- Object.entries(sounds).map(async ([name, { url }]) => {
15
- const response = await fetch(url)
16
- const arrayBuffer = await response.arrayBuffer()
17
- const audioBuffer = await audioContext.decodeAudioData(arrayBuffer)
18
- audioBufferCache.set(name, audioBuffer)
19
- }),
76
+ Object.entries(sounds).map(([name, { url }]) =>
77
+ load(context(), audioBufferCache, name, url),
78
+ ),
20
79
  )
21
80
  },
22
81
 
23
82
  soundPlay(entity, name) {
24
- const { volume = DEFAULT_VOLUME, loop } = entity.sounds[name]
83
+ const { volume = DEFAULT_VOLUME, loop } = entity.sounds[name] || {}
25
84
  const audioBuffer = audioBufferCache.get(name)
26
85
 
27
- const source = audioContext.createBufferSource()
28
- const gainNode = audioContext.createGain()
86
+ if (!audioBuffer) return
87
+
88
+ // Only one source per sound can be tracked, so playing a sound again
89
+ // replaces the previous one instead of stacking a new copy on top of it.
90
+ activeSources.get(name)?.stop()
91
+
92
+ const source = context().createBufferSource()
93
+ const gainNode = context().createGain()
29
94
 
30
95
  source.buffer = audioBuffer
31
96
  gainNode.gain.value = volume
32
97
 
33
98
  source.connect(gainNode)
34
- gainNode.connect(audioContext.destination)
99
+ gainNode.connect(context().destination)
35
100
 
36
101
  source.loop = loop
37
102
  source.start()
@@ -45,11 +110,10 @@ export function audio() {
45
110
  activeSources.delete(name)
46
111
  },
47
112
 
48
- stop() {
49
- for (const source of activeSources.values()) {
50
- source.stop()
51
- }
52
- activeSources.clear()
53
- },
113
+ stop: release,
114
+
115
+ // Taken off the world rather than the game stopping: the same letting go, because
116
+ // there is nothing left for anything still sounding to be sound over.
117
+ destroy: release,
54
118
  }
55
119
  }
@@ -1,6 +1,6 @@
1
1
  import { arrive } from "@inglorious/engine/ai/movement/dynamic/arrive.js"
2
2
  import { lerp } from "@inglorious/utils/math/linear-interpolation.js"
3
- import { defaults, extend, merge } from "@inglorious/utils/objects"
3
+ import { defaults, extend, merge } from "@inglorious/utils/object.js"
4
4
 
5
5
  const DEFAULT_PARAMS = {
6
6
  zoom: 1,
@@ -1,6 +1,6 @@
1
1
  import { modernMove } from "@inglorious/engine/movement/dynamic/modern.js"
2
- import { extend, merge } from "@inglorious/utils/objects"
3
- import { zero } from "@inglorious/utils/vectors"
2
+ import { extend, merge } from "@inglorious/utils/object.js"
3
+ import { zero } from "@inglorious/utils/vector.js"
4
4
 
5
5
  import { createMovementEventHandlers } from "../event-handlers.js"
6
6