@inglorious/engine 23.0.2 → 23.0.3

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
@@ -1,4 +1,10 @@
1
- import { abs } from "@inglorious/utils/math/numbers.js"
1
+ import {
2
+ anchorMargins,
3
+ entityAnchor,
4
+ shapeAnchor,
5
+ } from "@inglorious/engine/physics/anchor.js"
6
+ import { abs } from "@inglorious/utils/math/number.js"
7
+ import { v } from "@inglorious/utils/v.js"
2
8
  import {
3
9
  angle,
4
10
  clamp,
@@ -7,12 +13,12 @@ import {
7
13
  multiply,
8
14
  sum,
9
15
  zero,
10
- } from "@inglorious/utils/vectors"
16
+ } from "@inglorious/utils/vector.js"
11
17
 
12
18
  const ORIGIN = 0
13
19
  const DOUBLE = 2
14
- const HALF = 2
15
20
  const X = 0
21
+ const Y = 1
16
22
  const Z = 2
17
23
 
18
24
  export function bounce(entity, dt, [maxX, maxZ]) {
@@ -35,17 +41,20 @@ export function bounce(entity, dt, [maxX, maxZ]) {
35
41
 
36
42
  const ClampToBoundsByShape = {
37
43
  rectangle(entity, [maxX, maxZ], collisionGroup) {
38
- const [width, height, depth] =
39
- entity.collisions[collisionGroup].size ?? entity.size
40
-
41
- const halfWidth = width / HALF
42
- const halfHeight = height / HALF
43
- const halfDepth = depth / HALF
44
+ const collision = entity.collisions[collisionGroup]
45
+ const size = collision.size ?? entity.size
46
+
47
+ // An anchored box leaves uneven room on either side of its position, so the
48
+ // anchor itself decides how close to the bounds it may get.
49
+ const { before: low, after: high } = anchorMargins(
50
+ shapeAnchor(entity, collision),
51
+ size,
52
+ )
44
53
 
45
54
  return clamp(
46
55
  entity.position,
47
- [halfWidth, halfHeight, halfDepth],
48
- [maxX - halfWidth, maxZ - halfHeight, maxZ - halfDepth],
56
+ [low[ORIGIN], low[Y], low[Z]],
57
+ [maxX - high[ORIGIN], maxZ - high[Y], maxZ - high[Z]],
49
58
  )
50
59
  },
51
60
 
@@ -84,30 +93,28 @@ export function clampToBounds(
84
93
  }
85
94
 
86
95
  export function flip(entity, [maxX, maxZ]) {
87
- const [x, , z] = entity.position
96
+ const { x, z } = entity.position
88
97
 
89
98
  entity.collisions ??= {}
90
99
  entity.collisions.bounds ??= {}
91
100
  entity.collisions.bounds.shape ??= "rectangle"
92
101
 
93
- let width, height, depth
102
+ let size
94
103
  if (entity.collisions.bounds.shape === "circle") {
95
- width = entity.collisions.bounds.radius * DOUBLE
96
- height = entity.collisions.bounds.radius * DOUBLE
97
- depth = entity.collisions.bounds.radius * DOUBLE
104
+ const radius = entity.collisions.bounds.radius ?? entity.radius
105
+ size = v(radius * DOUBLE, radius * DOUBLE, radius * DOUBLE)
98
106
  } else {
99
- ;[width, height, depth] = entity.collisions.bounds.size ?? entity.size
107
+ size = entity.collisions.bounds.size ?? entity.size
100
108
  }
101
- const halfWidth = width / HALF
102
- const halfHeight = height / HALF
103
- const halfDepth = depth / HALF
104
-
105
- const left = x - halfWidth
106
- const right = x + halfWidth
107
- const bottom = z - halfHeight
108
- const top = z + halfHeight
109
- const back = z - halfDepth
110
- const front = z + halfDepth
109
+
110
+ const { before: low, after: high } = anchorMargins(entityAnchor(entity), size)
111
+
112
+ const left = x - low[X]
113
+ const right = x + high[X]
114
+ const bottom = z - low[Y]
115
+ const top = z + high[Y]
116
+ const back = z - low[Z]
117
+ const front = z + high[Z]
111
118
 
112
119
  const direction = fromAngle(entity.orientation)
113
120
 
@@ -1,5 +1,12 @@
1
- const HALF = 2
1
+ import { anchorMargins, shapeAnchor } from "./anchor.js"
2
2
 
3
+ const Y = 1
4
+
5
+ /**
6
+ * Where an entity's position has to be for it to come to rest on top of a
7
+ * target, given that both are positioned by their anchor rather than their
8
+ * centre.
9
+ */
3
10
  export function calculateLandingPosition(
4
11
  entity,
5
12
  target,
@@ -14,26 +21,37 @@ export function calculateLandingPosition(
14
21
  return calculatePYForPoint(entity, target, collisionGroup)
15
22
  }
16
23
 
24
+ /**
25
+ * How far the top edge of a shape sits above the point it is anchored to.
26
+ */
27
+ function topOf(target, collisionGroup) {
28
+ const collision = target.collisions[collisionGroup]
29
+ const { after } = anchorMargins(
30
+ shapeAnchor(target, collision),
31
+ collision.size ?? target.size,
32
+ )
33
+
34
+ return target.position[Y] + after[Y]
35
+ }
36
+
17
37
  function calculatePYForPoint(entity, target, collisionGroup) {
18
- const [, targetY] = target.position
19
- const [, targetHeight] = target.collisions[collisionGroup].size ?? target.size
20
- return targetY + targetHeight / HALF
38
+ return topOf(target, collisionGroup)
21
39
  }
22
40
 
23
41
  function calculatePYForCircle(entity, target, collisionGroup) {
24
42
  const entityRadius = entity.collisions[collisionGroup].radius ?? entity.radius
25
43
 
26
- const [, targetY] = target.position
27
- const [, targetHeight] = target.collisions[collisionGroup].size ?? target.size
28
- return targetY + targetHeight / HALF + entityRadius
44
+ return topOf(target, collisionGroup) + entityRadius
29
45
  }
30
46
 
31
47
  function calculatePYForRectangle(entity, target, collisionGroup) {
32
- const [, entityHeight] = entity.collisions[collisionGroup].size ?? entity.size
48
+ const collision = entity.collisions[collisionGroup]
49
+ const { before } = anchorMargins(
50
+ shapeAnchor(entity, collision),
51
+ collision.size ?? entity.size,
52
+ )
33
53
 
34
- const [, targetY] = target.position
35
- const [, targetHeight] = target.collisions[collisionGroup].size ?? target.size
36
- return targetY + targetHeight / HALF + entityHeight / HALF
54
+ return topOf(target, collisionGroup) + before[Y]
37
55
  }
38
56
 
39
57
  const CalculatePY = {
package/src/storage.js ADDED
@@ -0,0 +1,53 @@
1
+ const DEFAULT_STORAGE = () => globalThis.localStorage
2
+
3
+ function store(storage) {
4
+ return storage ?? DEFAULT_STORAGE()
5
+ }
6
+
7
+ /**
8
+ * Reads a value back as JSON.
9
+ *
10
+ * Storage that is absent -- a server render, a private window, a test -- reads as the
11
+ * fallback rather than throwing, so a caller does not have to know whether it is running
12
+ * somewhere that has any. A value that cannot be parsed is treated the same way: what is
13
+ * stored is not this function's to defend, and refusing to start over it would be worse
14
+ * than starting again.
15
+ *
16
+ * @param {string} key - Where the value is kept.
17
+ * @param {*} fallback - What to answer when there is nothing usable to read.
18
+ * @param {Storage} [storage] - Where to read from. Defaults to the browser's own.
19
+ * @returns {*} The stored value, or the fallback.
20
+ */
21
+ export function readJSON(key, fallback, storage) {
22
+ const raw = store(storage)?.getItem(key)
23
+
24
+ if (raw === null || raw === undefined) return fallback
25
+
26
+ try {
27
+ return JSON.parse(raw)
28
+ } catch {
29
+ return fallback
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Writes a value down as JSON, and answers whether it took.
35
+ *
36
+ * Storage can be full, absent, or refusing writes for its own reasons, and none of those
37
+ * is worth throwing over: a game that cannot remember a score can still be played. The
38
+ * answer is returned so that a caller which does care -- a test, mostly -- can say so.
39
+ *
40
+ * @param {string} key - Where to keep the value.
41
+ * @param {*} value - The value to keep.
42
+ * @param {Storage} [storage] - Where to write to. Defaults to the browser's own.
43
+ * @returns {boolean} `true` if the value was written.
44
+ */
45
+ export function writeJSON(key, value, storage) {
46
+ try {
47
+ store(storage)?.setItem(key, JSON.stringify(value))
48
+
49
+ return true
50
+ } catch {
51
+ return false
52
+ }
53
+ }
package/src/test.js ADDED
@@ -0,0 +1,185 @@
1
+ import { expect, vi } from "vitest"
2
+
3
+ import { Engine } from "./core/engine.js"
4
+
5
+ const DEFAULT_DT = 0.016
6
+ const DEFAULT_STEP_FRAMES = 1
7
+ const KEY_PRESS_SETTLING_FRAMES = 2
8
+ const DEFAULT_HOLD_FRAMES = 30
9
+ /**
10
+ * A game to drive, with its sounds watched.
11
+ *
12
+ * `notify` is the one way anything is said to it, so there is a single place that goes
13
+ * through the store; `step`, `press` and `hold` are written on top of it rather than
14
+ * beside it. A test that needs a world of its own makes one of these, so nothing is
15
+ * shared and tests can be run in any order.
16
+ *
17
+ * A game with a move of its own adds it rather than editing this: the additions are laid
18
+ * over the top, so they can call everything here.
19
+ *
20
+ * @param {Object} gameConfig - The game's own config, as the browser would be given it.
21
+ * @param {Object} [extendWith] - Methods this game's tests need of their own.
22
+ *
23
+ * @returns {Object} The game under test.
24
+ *
25
+ * @example
26
+ * const game = createGame(gameConfig, {
27
+ * // Breakout: a ball that falls off the bottom costs a life.
28
+ * dropTheBall() {
29
+ * this.entity("ball").position[1] = 0
30
+ * return this.step(1)
31
+ * },
32
+ * })
33
+ */
34
+ export function createGame(gameConfig, extendWith = {}) {
35
+ // Dev mode makes the store freeze what it publishes, which is right for a game being
36
+ // looked at in a browser and wrong for a test that has to put a ball where a brick is.
37
+ // Set here rather than in each test file, where it depends on being done before the
38
+ // first game is made.
39
+ gameConfig.entities.game.devMode = false
40
+
41
+ // What the browser would have given the game, so that a test file has nothing to set up
42
+ // before it makes one. Doing it here rather than leaving it to the caller means a test
43
+ // cannot forget and be met with "AudioContext is not a constructor".
44
+ setupBrowser()
45
+
46
+ const engine = new Engine(gameConfig)
47
+ const playedSounds = []
48
+
49
+ // Sounds are watched where they are handled rather than where they are asked for, so
50
+ // this records what the game actually reached for. Recording the request instead would
51
+ // not catch a sound wired to the wrong state.
52
+ vi.spyOn(engine._store.getType("Audio"), "soundPlay").mockImplementation(
53
+ function soundPlay(_, name) {
54
+ playedSounds.push(name)
55
+ },
56
+ )
57
+
58
+ return {
59
+ playedSounds,
60
+
61
+ /**
62
+ * An assertion that says what it was about.
63
+ *
64
+ * A failing `expect` without a description is one you have to go and find; a game
65
+ * saying it checks something reads as the game checking something.
66
+ *
67
+ * @param {boolean} condition - What is being claimed.
68
+ * @param {string} description - What is claimed, said as a fact about the game.
69
+ * @returns {void}
70
+ */
71
+ check(condition, description) {
72
+ expect(condition, description).toBe(true)
73
+ },
74
+
75
+ /** One entity, by the name the game knows it by. */
76
+ entity: (id) => engine._store.getEntity(id),
77
+ state: () => engine._store.getState(),
78
+
79
+ /**
80
+ * The pooled entities of a type that are in play right now.
81
+ *
82
+ * Pooled entities live outside the store's state -- they are drawn from a pool and put
83
+ * back rather than being added and removed -- so one is not read by looking up an id.
84
+ *
85
+ * @param {string} [typeName] - Which type of pooled entity to answer with.
86
+ * @returns {Object[]} The entities currently in play.
87
+ */
88
+ pooled(typeName) {
89
+ const active = engine._store.extras.getAllActivePoolEntities()
90
+
91
+ return typeName ? active.filter(({ type }) => type === typeName) : active
92
+ },
93
+
94
+ /** The one way anything is said to the game. */
95
+ notify(event, ...args) {
96
+ engine._store.notify(event, ...args)
97
+
98
+ return this
99
+ },
100
+
101
+ /** Run frames. */
102
+ step(frames = DEFAULT_STEP_FRAMES) {
103
+ for (let i = 0; i < frames; i++) engine.update(DEFAULT_DT)
104
+
105
+ return this
106
+ },
107
+
108
+ /**
109
+ * Run the game for a length of time, rather than for a number of frames.
110
+ *
111
+ * A test that waits something out is waiting for a lifetime, and a lifetime is in
112
+ * seconds. Working it out in frames means assuming how many of them there are to a
113
+ * second -- and that assumption is wrong by as much as the step is away from a
114
+ * sixtieth.
115
+ *
116
+ * @param {number} seconds - How long to run for.
117
+ * @returns {Object} The game, to keep a chain going.
118
+ */
119
+ advance(seconds) {
120
+ return this.step(Math.ceil(seconds / DEFAULT_DT))
121
+ },
122
+
123
+ /** Tap a key: down, up, then a short settling period for it to be seen in. */
124
+ press(code) {
125
+ return this.notify("keyboardKeyDown", code)
126
+ .notify("keyboardKeyUp", code)
127
+ .step(KEY_PRESS_SETTLING_FRAMES)
128
+ },
129
+
130
+ /** Hold a key down for a while, then let it up. */
131
+ hold(code, frames = DEFAULT_HOLD_FRAMES) {
132
+ return this.notify("keyboardKeyDown", code)
133
+ .step(frames)
134
+ .notify("keyboardKeyUp", code)
135
+ .step(KEY_PRESS_SETTLING_FRAMES)
136
+ },
137
+
138
+ ...extendWith,
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Mocks what a browser gives a game and a test environment does not.
144
+ *
145
+ * Run this once per test file, from a setup module. Web Audio is the thing jsdom has
146
+ * never had, and the audio behaviour asks for a context as soon as an entity carries
147
+ * sounds; `navigator.getGamepads` is the other, and is defined rather than spied on
148
+ * because jsdom's navigator has no such property to spy on.
149
+ *
150
+ * @returns {void}
151
+ */
152
+ function setupBrowser() {
153
+ // A store grows an audio entity of its own accord, and audio waits for the player to
154
+ // touch the page before it will make a sound -- so stepping any game at all reaches
155
+ // for `window`. Under node there is none, so a stand-in is put up; under jsdom there
156
+ // already is one, and replacing it would take away everything the real one is for.
157
+ if (typeof window === "undefined") {
158
+ vi.stubGlobal("window", {
159
+ addEventListener: vi.fn(),
160
+ removeEventListener: vi.fn(),
161
+ location: { search: "" },
162
+ })
163
+ }
164
+
165
+ vi.stubGlobal(
166
+ "AudioContext",
167
+ class {
168
+ state = "running"
169
+ destination = {}
170
+ resume = () => Promise.resolve()
171
+ createGain = () => ({ gain: { value: 1 }, connect: vi.fn() })
172
+ createBufferSource = () => ({
173
+ connect: vi.fn(),
174
+ start: vi.fn(),
175
+ stop: vi.fn(),
176
+ })
177
+ decodeAudioData = () => Promise.resolve({})
178
+ },
179
+ )
180
+
181
+ Object.defineProperty(navigator, "getGamepads", {
182
+ value: () => [],
183
+ configurable: true,
184
+ })
185
+ }
@@ -1,31 +0,0 @@
1
- const DEFAULT_STATE = "default"
2
-
3
- export function fsm(states) {
4
- const uniqueEventNames = [
5
- ...new Set(Object.values(states).flatMap(Object.keys)),
6
- ]
7
-
8
- return (type) => {
9
- return {
10
- create(entity, payload, api) {
11
- type.create?.(entity, payload, api)
12
-
13
- entity.state ??= DEFAULT_STATE
14
- },
15
-
16
- ...uniqueEventNames.reduce(
17
- (acc, eventName) => ({
18
- ...acc,
19
-
20
- [eventName](entity, event, api) {
21
- type[eventName]?.(entity, event, api)
22
-
23
- const state = states[entity.state]
24
- state?.[eventName]?.(entity, event, api)
25
- },
26
- }),
27
- {},
28
- ),
29
- }
30
- }
31
- }