@inglorious/engine 24.5.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 +13 -14
- package/package.json +5 -5
- package/src/behaviors/particles.js +179 -66
- package/src/core/engine.js +0 -3
- package/src/test.js +0 -15
- package/types/behaviors/particles.d.ts +69 -24
- package/types/index.d.ts +3 -17
- package/types/test.d.ts +0 -4
- package/src/core/middlewares/entity-pool/entity-pool-middleware.js +0 -68
- package/src/core/middlewares/entity-pool/entity-pool.js +0 -40
- package/src/core/middlewares/entity-pool/entity-pools.js +0 -46
- package/types/core/middlewares/entity-pool/entity-pool-middleware.d.ts +0 -4
- package/types/core/middlewares/entity-pool/entity-pool.d.ts +0 -9
- package/types/core/middlewares/entity-pool/entity-pools.d.ts +0 -12
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.
|
|
216
|
-
| `game.
|
|
217
|
-
| `game.
|
|
218
|
-
| `game.
|
|
219
|
-
| `game.
|
|
220
|
-
| `game.
|
|
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 (
|
|
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**
|
|
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
|
|
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.
|
|
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.
|
|
44
|
+
"@inglorious/utils": "^5.7.0"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
|
-
"@inglorious/store": "^12.9.
|
|
48
|
-
"vitest": "^5.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.
|
|
55
|
+
"vitest": "^5.1.2"
|
|
56
56
|
},
|
|
57
57
|
"engines": {
|
|
58
58
|
"node": ">= 26"
|
|
@@ -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
|
|
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
|
|
19
|
-
const
|
|
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
|
-
|
|
22
|
-
|
|
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
|
-
*
|
|
26
|
-
*
|
|
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
|
-
*
|
|
29
|
-
*
|
|
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: {
|
|
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
|
|
75
|
+
export function createParticles({
|
|
76
|
+
id = DEFAULT_ID,
|
|
77
|
+
capacity = DEFAULT_CAPACITY,
|
|
78
|
+
...rest
|
|
79
|
+
} = {}) {
|
|
37
80
|
return {
|
|
38
|
-
|
|
39
|
-
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
-
|
|
47
|
-
|
|
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
|
-
|
|
50
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
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
|
|
179
|
+
spread,
|
|
90
180
|
velocity,
|
|
91
181
|
opacity = OPAQUE,
|
|
92
|
-
layer = NO_LAYER,
|
|
93
|
-
image,
|
|
94
182
|
tint,
|
|
95
|
-
position
|
|
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
|
-
|
|
192
|
+
for (let emitted = 0; emitted < count; emitted++) {
|
|
193
|
+
const index = addTo(pool)
|
|
194
|
+
if (index === NOT_FOUND) return
|
|
99
195
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
|
|
119
|
-
|
|
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
|
}
|
package/src/core/engine.js
CHANGED
|
@@ -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
|
|
4
|
+
import type { Entity, GameApi } from "../index"
|
|
4
5
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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:
|
|
18
|
+
age: Float64ArrayConstructor
|
|
11
19
|
/** Seconds it lasts. */
|
|
12
|
-
life:
|
|
13
|
-
|
|
14
|
-
opacity:
|
|
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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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 [
|
|
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
|
-
/**
|
|
44
|
-
export function emitBurst(
|
|
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
|
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
|
|
78
|
-
export
|
|
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
|
-
>
|
|
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,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
|
-
}
|