@inglorious/engine 24.4.0 → 24.6.0

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
@@ -208,17 +208,16 @@ test that inherits from the one before it can only be run in one order.
208
208
 
209
209
  ### The game under test
210
210
 
211
- | | |
212
- | ---------------------------------------------- | ------------------------------------------------------------------------ |
213
- | `game.entity(id)` | one entity, by the name the game knows it by |
214
- | `game.state()` | the lot, for keys and for `Object.keys` |
215
- | `game.pooled(type?)` | the pooled entities in play — drawn from a pool rather than in the state |
216
- | `game.check(condition, description)` | assert, in a failure that says what it was about |
217
- | `game.playedSounds` | the sounds the game reached for, in order |
218
- | `game.notify(event, ...args)` | the one way anything is said to it |
219
- | `game.step(frames)` | run frames |
220
- | `game.advance(seconds)` | run for a length of time |
221
- | `game.press(code)` / `game.hold(code, frames)` | tap a key / hold it down |
211
+ | | |
212
+ | ---------------------------------------------- | ------------------------------------------------ |
213
+ | `game.entity(id)` | one entity, by the name the game knows it by |
214
+ | `game.state()` | the lot, for keys and for `Object.keys` |
215
+ | `game.check(condition, description)` | assert, in a failure that says what it was about |
216
+ | `game.playedSounds` | the sounds the game reached for, in order |
217
+ | `game.notify(event, ...args)` | the one way anything is said to it |
218
+ | `game.step(frames)` | run frames |
219
+ | `game.advance(seconds)` | run for a length of time |
220
+ | `game.press(code)` / `game.hold(code, frames)` | tap a key / hold it down |
222
221
 
223
222
  `advance` is there because a test that waits something out is waiting for a lifetime, and
224
223
  a lifetime is in seconds. Converting that to frames by hand means assuming how many frames
@@ -357,7 +356,7 @@ This engine is the product of countless hours of coding, smartly paired with AI
357
356
 
358
357
  Now, let's talk performance. The critique often has two parts: garbage collection (GC) pressure from immutability, and cache performance compared to modern engines.
359
358
 
360
- 1. **Garbage Collection**: The concern is that creating new objects on every state change will flood the GC. This is mitigated by **structural sharing** (via Mutative). We don't deep-clone the state; only the changed data paths create new objects. For the most extreme cases (e.g., a bullet hell), the engine provides a dedicated **entity pooling system** as a pragmatic escape hatch, eliminating GC pressure in performance hotspots.
359
+ 1. **Garbage Collection**: The concern is that creating new objects on every state change will flood the GC. This is mitigated by **structural sharing** (via Mutative). We don't deep-clone the state; only the changed data paths create new objects. For the most extreme cases (thousands of particles, a swarm), a crowd is kept in one entity as a pool of typed arrays (`@inglorious/utils/data-structures/pool.js`): nothing is allocated per member, and the engine's particles work this way.
361
360
 
362
361
  2. **Cache Performance & ECS**: The other critique is that modern engines like Unity or Godot use an Entity-Component-System (ECS) architecture to avoid deep object graphs (`player.inventory.getItem()`) and achieve better cache performance. **This is absolutely correct!** Those engines solve this problem very well.
363
362
 
@@ -375,7 +374,7 @@ This is a frequent point of confusion, so let's clarify. The engine uses [Data-D
375
374
 
376
375
  - **Data-Oriented Design (DOD)**: This is a lower-level implementation strategy focused on CPU cache performance, common in ECS architectures. It involves organizing data in contiguous memory blocks (e.g., an array of all positions, an array of all velocities) to minimize cache misses during iteration.
377
376
 
378
- This engine does **not** implement a strict DOD memory layout. However, by centralizing all entities into a single, flat object, we get a pragmatic, "almost-DOD" benefit. We leverage the JavaScript engine's highly optimized internal object layout, which is significantly more cache-friendly than chasing pointers through a deeply nested OOP graph.
377
+ This engine does **not** impose a DOD memory layout on every entity. By centralizing all entities into a single, flat object, we get a pragmatic, "almost-DOD" benefit; and where it really counts, a crowd kept as a pool of typed arrays (one per property) is a true struct-of-arrays layout. We leverage the JavaScript engine's highly optimized internal object layout, which is significantly more cache-friendly than chasing pointers through a deeply nested OOP graph.
379
378
 
380
379
  **"Functional programming is just painful to read and write."**
381
380
 
@@ -410,7 +409,7 @@ True, disciplined developers favor composition in any paradigm. The difference i
410
409
 
411
410
  This critique usually misunderstands how modern immutability works. The engine uses structural sharing (via Mutative), which means we're not deep-copying the entire game state on every change. It's incredibly efficient.
412
411
 
413
- That said, we're pragmatic. For performance-critical scenarios like a bullet hell with thousands of short-lived objects, we provide an **entity pooling** system as an escape hatch. But for 99% of game logic, we believe the massive benefits of a predictable, testable, and debuggable state (hello, time-travel debugging!) are a worthwhile trade-off for a negligible performance cost.
412
+ That said, we're pragmatic. For performance-critical scenarios like thousands of short-lived particles, the crowd is kept in one entity as a pool of typed arrays rather than as thousands of entities. But for 99% of game logic, we believe the massive benefits of a predictable, testable, and debuggable state (hello, time-travel debugging!) are a worthwhile trade-off for a negligible performance cost.
414
413
 
415
414
  **"My favorite OOP engine can do all this too!"**
416
415
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/engine",
3
- "version": "24.4.0",
3
+ "version": "24.6.0",
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",
@@ -41,18 +41,18 @@
41
41
  },
42
42
  "sideEffects": false,
43
43
  "dependencies": {
44
- "@inglorious/utils": "^5.6.0"
44
+ "@inglorious/utils": "^5.7.0"
45
45
  },
46
46
  "peerDependencies": {
47
- "@inglorious/store": "^12.9.5",
48
- "vitest": "^5.1.1"
47
+ "@inglorious/store": "^12.9.6",
48
+ "vitest": "^5.1.2"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@inglorious/eslint-config": "1.2.2",
52
52
  "prettier": "^3.10.1",
53
53
  "typescript": "~7.0.2",
54
54
  "vite": "^8.3.8",
55
- "vitest": "^5.1.1"
55
+ "vitest": "^5.1.2"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">= 26"
@@ -6,8 +6,10 @@ const DEFAULT_CURSOR = "arrow"
6
6
  /**
7
7
  * A pointer that turns into a hand over anything there is room to press.
8
8
  *
9
- * Anything with a hitbox is something a press would land on, so the pointer going
10
- * over one of those is the game saying "this does something" the way a desktop does.
9
+ * Anything with a hitbox that answers `entityPress` is something a press would do
10
+ * something to, so the pointer going over one of those is the game saying "this does
11
+ * something" the way a desktop does. A hitbox that only blocks, like a veil behind a
12
+ * dialog, keeps the arrow.
11
13
  * Written as a decorator rather than as part of the mouse itself, so a game that has
12
14
  * nothing to press -- or a mouse that is meant to stay a crosshair whatever it is
13
15
  * over -- simply leaves it out.
@@ -44,7 +46,9 @@ export function hover({ off = DEFAULT_CURSOR } = {}) {
44
46
  }
45
47
 
46
48
  /**
47
- * Puts the hand up or takes it down again.
49
+ * Puts the hand up or takes it down again, and tells what it went over and off:
50
+ * `entityHoverStart` and `entityHoverEnd` with the entity's id, which `button()` turns
51
+ * into `hovered` so it can light up.
48
52
  *
49
53
  * Something pressable under the pointer, or something pressed whatever the pointer has
50
54
  * wandered off to since: a drag that started on a control should not flicker back
@@ -53,5 +57,21 @@ export function hover({ off = DEFAULT_CURSOR } = {}) {
53
57
  function point(entity, api, off) {
54
58
  const held = entity.pressedId ?? findCollision(entity, api.getEntities())?.id
55
59
 
56
- entity.cursor = held ? HAND : off
60
+ entity.cursor = held && answersPresses(held, api) ? HAND : off
61
+
62
+ if (held === entity.hoveredId) return
63
+ if (entity.hoveredId) api.notify("entityHoverEnd", entity.hoveredId)
64
+ if (held) api.notify("entityHoverStart", held)
65
+ entity.hoveredId = held
66
+ }
67
+
68
+ /**
69
+ * Whether pressing an entity does anything: its type answers `entityPress`. Something
70
+ * can be in the way of the pointer without being pressable, such as a veil behind a
71
+ * dialog that stops clicks reaching the scene, and a hand over it would promise a press
72
+ * that does nothing.
73
+ */
74
+ function answersPresses(id, api) {
75
+ const entity = api.getEntity(id)
76
+ return Boolean(entity && api.getType(entity.type)?.entityPress)
57
77
  }
@@ -1,120 +1,233 @@
1
+ import {
2
+ addTo,
3
+ createPool,
4
+ removeFrom,
5
+ } from "@inglorious/utils/data-structures/pool.js"
1
6
  import { random } from "@inglorious/utils/math/rng.js"
2
7
  import { v } from "@inglorious/utils/v.js"
3
- import {
4
- multiply,
5
- negate,
6
- randomVector,
7
- sum,
8
- } from "@inglorious/utils/vector.js"
9
8
 
10
- const FIRST_INDEX = 0
9
+ const DEFAULT_ID = "particles"
10
+ const DEFAULT_CAPACITY = 1024
11
+ const PARTICLES_TYPE = "Particles"
11
12
  const SINGLE = 1
12
13
  const OPAQUE = 1
13
- const NO_LAYER = 0
14
- const NO_SPREAD = 0
15
- const NO_DEPTH = 0
16
- const NO_TIME = 0
17
14
  const WHOLE = 1
18
- const DEFAULT_SIZE = 1
19
- const PARTICLE_TYPE = "Particle"
15
+ const NO_TIME = 0
16
+ const NOTHING = 0
17
+ const NOT_FOUND = -1
18
+ const FIRST = 0
19
+ const AXIS_X = 0
20
+ const AXIS_Y = 1
21
+ const AXIS_Z = 2
20
22
 
21
- const DEFAULT_SIZE_VECTOR = () => v(DEFAULT_SIZE, DEFAULT_SIZE, NO_DEPTH)
22
- const NO_SPREAD_VECTOR = () => v(NO_SPREAD, NO_SPREAD, NO_SPREAD)
23
+ /**
24
+ * What each particle holds: where it is, how it moves, how long it lives and how it
25
+ * looks. One typed array per property, so a frame walks a few arrays instead of
26
+ * thousands of entities. `tint` is the index of the particle's colour in the entity's
27
+ * `tints`.
28
+ */
29
+ const SCHEMA = {
30
+ x: Float64Array,
31
+ y: Float64Array,
32
+ z: Float64Array,
33
+ vx: Float64Array,
34
+ vy: Float64Array,
35
+ vz: Float64Array,
36
+ ax: Float64Array,
37
+ ay: Float64Array,
38
+ az: Float64Array,
39
+ age: Float64Array,
40
+ life: Float64Array,
41
+ opacity: Float64Array,
42
+ tint: Uint16Array,
43
+ }
23
44
 
24
45
  /**
25
- * A single particle: it drifts under an acceleration and fades out over its
26
- * lifetime, then hands itself back to the pool.
46
+ * An entity holding a crowd of particles: debris, sparks, smoke. The particles are not
47
+ * entities of their own but a pool (`@inglorious/utils/data-structures/pool.js`) in
48
+ * `entity.particles`, read as `entity.particles.x[i]` for `i` up to
49
+ * `entity.particles.count`.
27
50
  *
28
- * Pair it with whatever draws the particle, which is usually `renderImage` or
29
- * `renderRectangle`:
51
+ * What every particle shares -- `image`, `size`, `layer` -- is said once, on the
52
+ * entity. A burst says where its particles start, how they move, how long they last
53
+ * and their colour. A different look is a different particles entity, with its own id.
30
54
  *
31
55
  * @example
32
56
  * ```js
33
- * types: { Particle: [{ render: renderImage }, particle()] }
57
+ * types: { Particles: [{ render: renderParticles }, particles()] },
58
+ * entities: {
59
+ * debris: createParticles({
60
+ * id: "debris",
61
+ * size: v(8, 8, 0),
62
+ * layer: 0.5,
63
+ * image: { id: "particle", imageSize: [8, 8] },
64
+ * }),
65
+ * }
34
66
  * ```
67
+ *
68
+ * @param {Object} [options]
69
+ * @param {string} [options.id="particles"] - Where bursts are sent.
70
+ * @param {number} [options.capacity=1024] - The most particles alive at once: a burst
71
+ * past it emits only those that fit.
72
+ * @returns {Object} The entity, of type `Particles` unless `type` says otherwise. Any
73
+ * other option (`image`, `size`, `layer`...) is kept on it for the renderer.
35
74
  */
36
- export function particle() {
75
+ export function createParticles({
76
+ id = DEFAULT_ID,
77
+ capacity = DEFAULT_CAPACITY,
78
+ ...rest
79
+ } = {}) {
37
80
  return {
38
- update(entity, dt, api) {
39
- entity.age += dt
81
+ id,
82
+ type: PARTICLES_TYPE,
83
+ position: v(NOTHING, NOTHING, NOTHING),
84
+ particles: createPool(capacity, SCHEMA),
85
+ tints: [],
86
+ ...rest,
87
+ }
88
+ }
40
89
 
41
- if (entity.age >= entity.life) {
42
- api.notify("despawn", entity)
43
- return
44
- }
90
+ /**
91
+ * The behaviour of a particles entity: each particle drifts under its acceleration and
92
+ * fades out over its lifetime, then leaves the pool; a `particlesBurst` event adds new
93
+ * ones (see `emitBurst`).
94
+ *
95
+ * Pair it with `renderParticles` from `@inglorious/renderer-2d/particles.js`.
96
+ */
97
+ export function particles() {
98
+ return {
99
+ update(entity, dt) {
100
+ const pool = entity.particles
45
101
 
46
- entity.velocity = sum(entity.velocity, multiply(entity.acceleration, dt))
47
- entity.position = sum(entity.position, multiply(entity.velocity, dt))
102
+ // From last to first: a removed particle's place is taken by the last one,
103
+ // which has already moved this frame.
104
+ for (let index = pool.count - SINGLE; index >= FIRST; index--) {
105
+ pool.age[index] += dt
106
+ if (pool.age[index] >= pool.life[index]) {
107
+ removeFrom(pool, index)
108
+ continue
109
+ }
48
110
 
49
- const spent = entity.age / entity.life
50
- entity.opacity = entity.startOpacity * (WHOLE - spent)
111
+ pool.vx[index] += pool.ax[index] * dt
112
+ pool.vy[index] += pool.ay[index] * dt
113
+ pool.vz[index] += pool.az[index] * dt
114
+ pool.x[index] += pool.vx[index] * dt
115
+ pool.y[index] += pool.vy[index] * dt
116
+ pool.z[index] += pool.vz[index] * dt
117
+ }
118
+ },
119
+
120
+ particlesBurst(entity, params) {
121
+ burst(entity, params)
51
122
  },
52
123
  }
53
124
  }
54
125
 
55
126
  /**
56
- * Emits a burst of particles, pooled like any other entity.
127
+ * Sends a burst of particles to a particles entity.
57
128
  *
58
- * Each particle picks its own lifetime, its own acceleration and its own place
59
- * in the emission box, so one call reads as a burst rather than a grid.
129
+ * Each particle picks its own lifetime, its own acceleration and its own place in the
130
+ * emission box, so one call reads as a burst rather than a grid.
60
131
  *
61
- * `acceleration` is a pair of vectors, and each particle's acceleration is drawn
62
- * per axis between them: the low end is where a component starts, the high end
63
- * where it can reach. `spread` is the half-extent of the box particles are
64
- * emitted in, so `[5, 5, 0]` emits within five of the position on each axis.
132
+ * `acceleration` is a pair of vectors, and each particle's acceleration is drawn per
133
+ * axis between them: the low end is where a component starts, the high end where it
134
+ * can reach. `spread` is the half-extent of the box particles are emitted in, so
135
+ * `[5, 5, 0]` emits within five of the position on each axis.
65
136
  *
66
137
  * @example
67
138
  * ```js
68
139
  * // Debris falling away from something that was hit.
69
140
  * emitBurst(api, {
141
+ * into: "debris",
70
142
  * count: 64,
71
143
  * position: v(100, 100, 0),
72
- * size: v(2, 2, 0),
73
144
  * lifetime: [0.5, 1],
74
145
  * tint: "rgb(99, 155, 255)",
75
146
  * acceleration: [v(-15, -80, 0), v(15, 0, 0)],
76
147
  * spread: v(5, 5, 0),
77
- * layer: LAYER_PARTICLES,
78
- * image: { id: "particle", imageSize: [2, 2] },
79
148
  * })
80
149
  * ```
150
+ *
151
+ * @param {Object} api
152
+ * @param {Object} params - `into` is the id of the particles entity ("particles"); the
153
+ * rest is as for `burst`.
81
154
  */
82
- export function emitBurst(api, params) {
155
+ export function emitBurst(api, { into = DEFAULT_ID, ...params }) {
156
+ api.notify(`#${into}:particlesBurst`, params)
157
+ }
158
+
159
+ /**
160
+ * Adds a burst's particles to the pool, as many as fit: what `particlesBurst` does,
161
+ * for whoever holds the entity already.
162
+ *
163
+ * @param {Object} entity - A particles entity, from `createParticles`.
164
+ * @param {Object} params
165
+ * @param {number} [params.count=1]
166
+ * @param {number[]} [params.position] - Where the burst is centred.
167
+ * @param {number[]} [params.spread] - The half-extent of the box particles start in.
168
+ * @param {number[]} [params.velocity] - Every particle's starting velocity (at rest).
169
+ * @param {number[][]} [params.acceleration] - Low and high ends, drawn per axis.
170
+ * @param {number[]} [params.lifetime=[1, 1]] - The shortest and longest life, in seconds.
171
+ * @param {number} [params.opacity=1] - How opaque particles start.
172
+ * @param {string} [params.tint] - Their colour.
173
+ */
174
+ export function burst(entity, params) {
83
175
  const {
84
176
  count = SINGLE,
85
- type = PARTICLE_TYPE,
86
- size = DEFAULT_SIZE_VECTOR(),
87
177
  lifetime = [WHOLE, WHOLE],
88
178
  acceleration,
89
- spread = NO_SPREAD_VECTOR(),
179
+ spread,
90
180
  velocity,
91
181
  opacity = OPAQUE,
92
- layer = NO_LAYER,
93
- image,
94
182
  tint,
95
- position = v(NO_SPREAD, NO_SPREAD, NO_DEPTH),
183
+ position,
96
184
  } = params
185
+ const pool = entity.particles
186
+ const [x = NOTHING, y = NOTHING, z = NOTHING] = position ?? []
187
+ const [spreadX = NOTHING, spreadY = NOTHING, spreadZ = NOTHING] = spread ?? []
188
+ const [vx = NOTHING, vy = NOTHING, vz = NOTHING] = velocity ?? []
189
+ const [low = [], high = []] = acceleration ?? []
190
+ const tintIndex = tintOf(entity, tint)
97
191
 
98
- const [low, high] = acceleration ?? []
192
+ for (let emitted = 0; emitted < count; emitted++) {
193
+ const index = addTo(pool)
194
+ if (index === NOT_FOUND) return
99
195
 
100
- for (let index = FIRST_INDEX; index < count; index++) {
101
- api.notify("spawn", {
102
- type,
103
- layer,
104
- size,
105
- image,
106
- tint,
107
- age: NO_TIME,
108
- life: random(...lifetime),
109
- startOpacity: opacity,
110
- opacity,
111
- position: within(position, spread),
112
- velocity: velocity ?? v(NO_SPREAD, NO_SPREAD, NO_DEPTH),
113
- acceleration: randomVector(low, high),
114
- })
196
+ pool.x[index] = x + random(-spreadX, spreadX)
197
+ pool.y[index] = y + random(-spreadY, spreadY)
198
+ pool.z[index] = z + random(-spreadZ, spreadZ)
199
+ pool.vx[index] = vx
200
+ pool.vy[index] = vy
201
+ pool.vz[index] = vz
202
+ pool.ax[index] = between(low, high, AXIS_X)
203
+ pool.ay[index] = between(low, high, AXIS_Y)
204
+ pool.az[index] = between(low, high, AXIS_Z)
205
+ pool.age[index] = NO_TIME
206
+ pool.life[index] = random(...lifetime)
207
+ pool.opacity[index] = opacity
208
+ pool.tint[index] = tintIndex
115
209
  }
116
210
  }
117
211
 
118
- function within(centre, spread) {
119
- return sum(centre, randomVector(negate(spread), spread))
212
+ /**
213
+ * How opaque a particle is now: it fades from the opacity it was emitted at to nothing
214
+ * over its lifetime.
215
+ * @param {Object} pool - `entity.particles`.
216
+ * @param {number} index
217
+ * @returns {number}
218
+ */
219
+ export function particleOpacity(pool, index) {
220
+ return pool.opacity[index] * (WHOLE - pool.age[index] / pool.life[index])
221
+ }
222
+
223
+ function between(low, high, axis) {
224
+ return random(low[axis] ?? NOTHING, high[axis] ?? NOTHING)
225
+ }
226
+
227
+ /** Where a colour sits in the entity's `tints`, added the first time it is used. */
228
+ function tintOf(entity, tint) {
229
+ const found = entity.tints.indexOf(tint)
230
+ if (found !== NOT_FOUND) return found
231
+ entity.tints.push(tint)
232
+ return entity.tints.length - SINGLE
120
233
  }
@@ -10,23 +10,67 @@ import { fsm } from "@inglorious/store/behaviors/state-machine/fsm.js"
10
10
  * It announces that it was pressed the way any state machine does -- through
11
11
  * `stateChange` -- so whatever the button is *for* is said elsewhere rather than here:
12
12
  * a button knows how it looks, not what it does.
13
+ *
14
+ * While the pointer is over it, `hovered` is true (from `hover()` on the mouse), so it
15
+ * can light up.
16
+ *
17
+ * A finger presses it too, from `entityTouchStart` to `entityTouchEnd`: give it a
18
+ * `touch` collision as well as its `hitbox`, since that is what the touch looks for.
13
19
  */
14
20
  export function button() {
15
21
  return fsm({
16
22
  default: {
17
- entityPress(entity, id) {
18
- if (id !== entity.id) return
19
-
20
- entity.state = "pressed"
21
- },
23
+ entityPress: press,
24
+ entityTouchStart: press,
25
+ ...HOVER,
22
26
  },
23
27
 
24
28
  pressed: {
25
- entityRelease(entity, id) {
26
- if (id !== entity.id) return
27
-
28
- entity.state = "default"
29
+ ...HOVER,
30
+ entityRelease: release,
31
+ entityTouchEnd(entity, { targetId }) {
32
+ release(entity, targetId)
29
33
  },
30
34
  },
31
35
  })
32
36
  }
37
+
38
+ function press(entity, id) {
39
+ if (id !== entity.id) return
40
+
41
+ entity.state = "pressed"
42
+ }
43
+
44
+ function release(entity, id) {
45
+ if (id !== entity.id) return
46
+
47
+ entity.state = "default"
48
+ }
49
+
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.
53
+ *
54
+ * @example
55
+ * ```js
56
+ * types: { Button: [button(), pressable(), { render: renderButton }] }
57
+ * entities: { pause: { type: "Button", action: "togglePause", label: "Pause" } }
58
+ * ```
59
+ */
60
+ export function pressable() {
61
+ return {
62
+ stateChange(entity, { entityId, to }, api) {
63
+ if (entityId === entity.id && to === "pressed") api.notify(entity.action)
64
+ },
65
+ }
66
+ }
67
+
68
+ const HOVER = {
69
+ entityHoverStart(entity, id) {
70
+ if (id === entity.id) entity.hovered = true
71
+ },
72
+
73
+ entityHoverEnd(entity, id) {
74
+ if (id === entity.id) entity.hovered = false
75
+ },
76
+ }
@@ -7,9 +7,9 @@ import * as segment from "@inglorious/utils/math/segment.js"
7
7
  import { filter } from "@inglorious/utils/object.js"
8
8
  import { add, zero } from "@inglorious/utils/vector.js"
9
9
 
10
+ import { drawOrder } from "../core/draw-order.js"
10
11
  import { anchorOffset, shapeAnchor } from "../physics/anchor.js"
11
12
 
12
- const Z = 2
13
13
  const RECTANGLE = "rectangle"
14
14
 
15
15
  const Shape = {
@@ -22,7 +22,8 @@ const Shape = {
22
22
  }
23
23
 
24
24
  /**
25
- * Finds the first collision between a point and a list of entities.
25
+ * Finds the first collision between a point and a list of entities: the one drawn on
26
+ * top, when several overlap (the reverse of `drawOrder`).
26
27
  *
27
28
  * @param {Point} entity - The point to check for collisions.
28
29
  * @param {Options} options - Options for collision detection.
@@ -35,7 +36,7 @@ export function findCollision(entity, entities, collisionGroup = "hitbox") {
35
36
  )
36
37
 
37
38
  return Object.values(otherEntities)
38
- .toSorted((a, b) => a.position[Z] - b.position[Z])
39
+ .toSorted((a, b) => drawOrder(b, a))
39
40
  .find((target) => collidesWith(entity, target, collisionGroup))
40
41
  }
41
42
 
@@ -0,0 +1,22 @@
1
+ const DEFAULT_LAYER = 0
2
+ const Y = 1
3
+ const Z = 2
4
+
5
+ /**
6
+ * The order things are drawn in, as a comparator: by `layer`, then from low to high
7
+ * (`y`), then from the back of the scene to the front (high `z` first).
8
+ *
9
+ * Shared by the renderers, which draw in this order, and by hit testing, which looks in
10
+ * the reverse one: what the pointer lands on is what is drawn on top.
11
+ *
12
+ * @param {{ layer?: number, position: number[] }} a
13
+ * @param {{ layer?: number, position: number[] }} b
14
+ * @returns {number}
15
+ */
16
+ export function drawOrder(a, b) {
17
+ return (
18
+ (a.layer ?? DEFAULT_LAYER) - (b.layer ?? DEFAULT_LAYER) ||
19
+ a.position[Y] - b.position[Y] ||
20
+ b.position[Z] - a.position[Z]
21
+ )
22
+ }
@@ -17,7 +17,6 @@ import { game } from "../behaviors/game.js"
17
17
  import { images } from "../behaviors/images.js"
18
18
  import { coreEvents } from "./core-events.js"
19
19
  import { Loop } from "./loops/index.js"
20
- import { entityPoolMiddleware } from "./middlewares/entity-pool/entity-pool-middleware.js"
21
20
  import { assertTypesAreDeclared } from "./types.js"
22
21
 
23
22
  /**
@@ -64,8 +63,6 @@ export class Engine {
64
63
 
65
64
  const middlewares = []
66
65
 
67
- middlewares.push(entityPoolMiddleware())
68
-
69
66
  const multiplayer = this._config.entities.game?.multiplayer
70
67
  if (multiplayer) {
71
68
  middlewares.push(
package/src/test.js CHANGED
@@ -66,21 +66,6 @@ export function createGame(gameConfig, extendWith = {}) {
66
66
  entity: (id) => engine._store.getEntity(id),
67
67
  state: () => engine._store.getState(),
68
68
 
69
- /**
70
- * The pooled entities of a type that are in play right now.
71
- *
72
- * Pooled entities live outside the store's state -- they are drawn from a pool and put
73
- * back rather than being added and removed -- so one is not read by looking up an id.
74
- *
75
- * @param {string} [typeName] - Which type of pooled entity to answer with.
76
- * @returns {Object[]} The entities currently in play.
77
- */
78
- pooled(typeName) {
79
- const active = engine._store.extras.getAllActivePoolEntities()
80
-
81
- return typeName ? active.filter(({ type }) => type === typeName) : active
82
- },
83
-
84
69
  /** The one way anything is said to the game. */
85
70
  notify(event, ...args) {
86
71
  engine._store.notify(event, ...args)
@@ -1,44 +1,89 @@
1
+ import type { Pool } from "@inglorious/utils/data-structures/pool.js"
1
2
  import type { Vector3 } from "@inglorious/utils/vector.js"
2
3
 
3
- import type { Entity, GameApi, UpdateHandler } from "../index"
4
+ import type { Entity, GameApi } from "../index"
4
5
 
5
- export interface ParticleEntity extends Entity {
6
- position: Vector3
7
- velocity: Vector3
8
- acceleration: Vector3
6
+ /** Each particle's properties, one typed array each, in `entity.particles`. */
7
+ export type ParticlesPool = Pool<{
8
+ x: Float64ArrayConstructor
9
+ y: Float64ArrayConstructor
10
+ z: Float64ArrayConstructor
11
+ vx: Float64ArrayConstructor
12
+ vy: Float64ArrayConstructor
13
+ vz: Float64ArrayConstructor
14
+ ax: Float64ArrayConstructor
15
+ ay: Float64ArrayConstructor
16
+ az: Float64ArrayConstructor
9
17
  /** Seconds since it was emitted. */
10
- age: number
18
+ age: Float64ArrayConstructor
11
19
  /** Seconds it lasts. */
12
- life: number
13
- startOpacity: number
14
- opacity: number
20
+ life: Float64ArrayConstructor
21
+ /** How opaque it was emitted. */
22
+ opacity: Float64ArrayConstructor
23
+ /** Its colour's place in the entity's `tints`. */
24
+ tint: Uint16ArrayConstructor
25
+ }>
26
+
27
+ /** An entity holding a crowd of particles that share its look. */
28
+ export interface ParticlesEntity extends Entity {
29
+ position: Vector3
30
+ particles: ParticlesPool
31
+ /** The colours bursts used, each once. */
32
+ tints: (string | undefined)[]
33
+ /** Drawn for each particle, tinted; a square of `size` without one. */
34
+ image?: unknown
35
+ size?: Vector3
36
+ layer?: number
15
37
  }
16
38
 
17
- /** Drifts and fades over its life, then despawns. */
18
- export function particle(): {
19
- update: UpdateHandler<ParticleEntity>
39
+ export interface ParticlesOptions {
40
+ /** Where bursts are sent. Defaults to `"particles"`. */
41
+ id?: string
42
+ /** The most particles alive at once. Defaults to 1024. */
43
+ capacity?: number
44
+ type?: string
45
+ image?: unknown
46
+ size?: Vector3
47
+ layer?: number
48
+ [key: string]: unknown
20
49
  }
21
50
 
51
+ /** A particles entity with an empty pool. */
52
+ export function createParticles(options?: ParticlesOptions): ParticlesEntity
53
+
22
54
  export interface BurstParams {
23
55
  /** Defaults to 1. */
24
56
  count?: number
25
- /** Defaults to `"Particle"`. */
26
- type?: string
27
- size?: Vector3
28
57
  /** The shortest and longest a particle lasts, in seconds. Defaults to 1. */
29
58
  lifetime?: readonly [number, number]
30
59
  /** Each particle's acceleration is drawn between these, axis by axis. */
31
- acceleration?: readonly [Vector3, Vector3]
60
+ acceleration?: readonly [
61
+ Vector3 | readonly number[],
62
+ Vector3 | readonly number[],
63
+ ]
32
64
  /** The half-extent of the box particles are emitted in. */
33
- spread?: Vector3
34
- velocity?: Vector3
35
- /** Defaults to 1. */
65
+ spread?: Vector3 | readonly number[]
66
+ velocity?: Vector3 | readonly number[]
67
+ /** How opaque particles start. Defaults to 1. */
36
68
  opacity?: number
37
- layer?: number
38
- image?: unknown
39
69
  tint?: string
40
- position?: Vector3
70
+ position?: Vector3 | readonly number[]
71
+ }
72
+
73
+ /** Moves and fades the particles, and adds those of a `particlesBurst`. */
74
+ export function particles(): {
75
+ update: (entity: ParticlesEntity, dt: number) => void
76
+ particlesBurst: (entity: ParticlesEntity, params: BurstParams) => void
41
77
  }
42
78
 
43
- /** Spawns a burst of pooled particles. */
44
- export function emitBurst(api: GameApi, params: BurstParams): void
79
+ /** Sends a burst to the particles entity `into` names (`"particles"`). */
80
+ export function emitBurst(
81
+ api: GameApi,
82
+ params: BurstParams & { into?: string },
83
+ ): void
84
+
85
+ /** Adds a burst's particles to an entity's pool, as many as fit. */
86
+ export function burst(entity: ParticlesEntity, params: BurstParams): void
87
+
88
+ /** How opaque a particle is now, fading over its life. */
89
+ export function particleOpacity(pool: ParticlesPool, index: number): number
@@ -2,7 +2,14 @@ import type { Decorator, Entity, GameType } from "../../index"
2
2
 
3
3
  export interface ButtonEntity extends Entity {
4
4
  state?: "default" | "pressed"
5
+ /** True while the pointer is over it. */
6
+ hovered?: boolean
7
+ /** What `pressable()` notifies when it is pressed. */
8
+ action?: string
5
9
  }
6
10
 
7
- /** Looks pressed from `entityPress` to `entityRelease`, and announces it through `stateChange`. */
11
+ /** Looks pressed from `entityPress` to `entityRelease` (or `entityTouchStart` to `entityTouchEnd`), and announces it through `stateChange`. */
8
12
  export function button(): Decorator<GameType<ButtonEntity>>
13
+
14
+ /** Notifies the button's `action` when it is pressed. */
15
+ export function pressable(): GameType<ButtonEntity>
@@ -0,0 +1,5 @@
1
+ /** The order things are drawn in: by `layer`, then by `y`, then back (high `z`) to front. */
2
+ export function drawOrder(
3
+ a: { layer?: number; position: readonly number[] },
4
+ b: { layer?: number; position: readonly number[] },
5
+ ): number
package/types/index.d.ts CHANGED
@@ -74,25 +74,11 @@ export interface GameEntity extends BaseEntity {
74
74
  multiplayer?: MultiplayerMiddlewareConfig
75
75
  }
76
76
 
77
- /** The api the engine hands every handler: the store's, and the entity pools'. */
78
- export interface GameApi<
77
+ /** The api the engine hands every handler: the store's. */
78
+ export type GameApi<
79
79
  TEntity extends BaseEntity = BaseEntity,
80
80
  TState extends EntitiesState<TEntity> = EntitiesState<TEntity>,
81
- > extends Api<TEntity, TState> {
82
- /** The pooled entities in play, from `spawn`. */
83
- getAllActivePoolEntities: () => Stored<Entity>[]
84
- /** The first entity that collides with `entity`, pooled ones included. */
85
- findCollision: (
86
- entity: Entity,
87
- entities?: Record<string, Entity>,
88
- collisionGroup?: string,
89
- ) => Stored<Entity> | undefined
90
- /** How many entities each pool holds, in `devMode`. */
91
- getEntityPoolsStats?: () => Record<
92
- string,
93
- { active: number; inactive: number }
94
- >
95
- }
81
+ > = Api<TEntity, TState>
96
82
 
97
83
  /** An event handler: the entity, the event's payload and the api. */
98
84
  export type EventHandler<
package/types/test.d.ts CHANGED
@@ -11,10 +11,6 @@ export interface TestGame {
11
11
  /** One entity, by id, typed as `TEntity`. */
12
12
  entity<TEntity extends BaseEntity = Entity>(id: string): Stored<TEntity>
13
13
  state(): EntitiesState
14
- /** The pooled entities in play, of one type or all. */
15
- pooled<TEntity extends BaseEntity = Entity>(
16
- typeName?: string,
17
- ): Stored<TEntity>[]
18
14
  notify(event: string, payload?: unknown): this
19
15
  /** Runs frames. Defaults to one. */
20
16
  step(frames?: number): this
@@ -1,68 +0,0 @@
1
- import { createApi } from "@inglorious/store/api.js"
2
- import { EventMap } from "@inglorious/store/event-map.js"
3
-
4
- import { findCollision } from "../../../collision/detection.js"
5
- import { EntityPools } from "./entity-pools.js"
6
-
7
- export function entityPoolMiddleware() {
8
- return (store) => {
9
- const pools = new EntityPools()
10
- const eventMap = new EventMap()
11
-
12
- store.extras ??= {}
13
- store.extras.getAllActivePoolEntities = () => pools.getAllActiveEntities()
14
-
15
- store.extras.findCollision = (
16
- entity,
17
- entities = store.getState(),
18
- collisionGroup,
19
- ) =>
20
- findCollision(
21
- entity,
22
- { ...entities, ...pools.getAllActiveEntitiesById() },
23
- collisionGroup,
24
- )
25
-
26
- const game = store.getState().game
27
- if (game.devMode) {
28
- store.extras.getEntityPoolsStats = () => pools.getStats()
29
- }
30
-
31
- const api = createApi(store)
32
-
33
- const next = store.dispatch
34
- store.dispatch = (event) => {
35
- switch (event.type) {
36
- case "spawn": {
37
- const entity = pools.acquire(event.payload)
38
- const type = store.getType(entity.type)
39
- eventMap.addEntity(entity.id, type, entity.type)
40
- break
41
- }
42
-
43
- case "despawn": {
44
- const entity = pools.recycle(event.payload)
45
- const type = store.getType(entity.type)
46
- eventMap.removeEntity(entity.id, type, entity.type)
47
- break
48
- }
49
-
50
- default: {
51
- const entityIds = eventMap.getEntitiesForEvent(event.type)
52
- for (const id of entityIds) {
53
- const entity = pools.activeEntitiesById.get(id)
54
- if (!entity) continue
55
-
56
- const type = store.getType(entity.type)
57
- const handle = type[event.type]
58
- handle?.(entity, event.payload, api)
59
- }
60
- }
61
- }
62
-
63
- return next(event)
64
- }
65
-
66
- return store
67
- }
68
- }
@@ -1,40 +0,0 @@
1
- const INITIAL_ID = 0
2
- const NOT_FOUND = -1
3
- const ITEMS_TO_REMOVE = 1
4
-
5
- export class EntityPool {
6
- _activeEntities = []
7
- _inactiveEntities = []
8
- _nextId = INITIAL_ID
9
-
10
- populate(factory, count) {
11
- for (let i = 0; i < count; i++) {
12
- this._activeEntities.push(factory())
13
- }
14
- }
15
-
16
- acquire(props) {
17
- const entity = this._inactiveEntities.pop() || {
18
- id: `entity-${this._nextId++}`,
19
- }
20
- Object.assign(entity, props)
21
- this._activeEntities.push(entity)
22
- return entity
23
- }
24
-
25
- recycle(entity) {
26
- const index = this._activeEntities.indexOf(entity)
27
- if (index !== NOT_FOUND) {
28
- const [entity] = this._activeEntities.splice(index, ITEMS_TO_REMOVE)
29
- this._inactiveEntities.push(entity)
30
- }
31
- return entity
32
- }
33
-
34
- getStats() {
35
- return {
36
- active: this._activeEntities.length,
37
- inactive: this._inactiveEntities.length,
38
- }
39
- }
40
- }
@@ -1,46 +0,0 @@
1
- import { EntityPool } from "./entity-pool.js"
2
-
3
- export class EntityPools {
4
- _pools = new Map()
5
- _activeEntitiesById = new Map()
6
-
7
- get activeEntitiesById() {
8
- return this._activeEntitiesById
9
- }
10
-
11
- getAllActiveEntitiesById() {
12
- return Object.fromEntries(this._activeEntitiesById)
13
- }
14
-
15
- acquire(props) {
16
- this.lazyInit(props)
17
- const entity = this._pools.get(props.type).acquire(props)
18
- this._activeEntitiesById.set(entity.id, entity)
19
- return entity
20
- }
21
-
22
- recycle(props) {
23
- this.lazyInit(props)
24
- const entity = this._pools.get(props.type).recycle(props)
25
- this._activeEntitiesById.delete(entity.id)
26
- return entity
27
- }
28
-
29
- getStats() {
30
- const stats = {}
31
- for (const [type, pool] of this._pools.entries()) {
32
- stats[type] = pool.getStats()
33
- }
34
- return stats
35
- }
36
-
37
- lazyInit(entity) {
38
- if (!this._pools.get(entity.type)) {
39
- this._pools.set(entity.type, new EntityPool())
40
- }
41
- }
42
-
43
- getAllActiveEntities() {
44
- return Array.from(this._activeEntitiesById.values())
45
- }
46
- }
@@ -1,4 +0,0 @@
1
- import type { Middleware } from "@inglorious/store"
2
-
3
- /** Handles `spawn` and `despawn` with entity pools, and adds them to the api. */
4
- export function entityPoolMiddleware(): Middleware
@@ -1,9 +0,0 @@
1
- import type { BaseEntity } from "@inglorious/store"
2
-
3
- /** Recycles entities of one type rather than making new ones. */
4
- export class EntityPool<TEntity extends BaseEntity = BaseEntity> {
5
- populate(factory: () => TEntity, count: number): void
6
- acquire(props: TEntity): TEntity & { id: string }
7
- recycle(entity: TEntity): TEntity
8
- getStats(): { active: number; inactive: number }
9
- }
@@ -1,12 +0,0 @@
1
- import type { BaseEntity } from "@inglorious/store"
2
-
3
- /** An entity pool per type. */
4
- export class EntityPools<TEntity extends BaseEntity = BaseEntity> {
5
- readonly activeEntitiesById: Map<string, TEntity & { id: string }>
6
- getAllActiveEntitiesById(): Record<string, TEntity & { id: string }>
7
- acquire(props: TEntity): TEntity & { id: string }
8
- recycle(props: TEntity): TEntity
9
- getStats(): Record<string, { active: number; inactive: number }>
10
- lazyInit(entity: TEntity): void
11
- getAllActiveEntities(): (TEntity & { id: string })[]
12
- }