-
Notifications
You must be signed in to change notification settings - Fork 8
/
ecs.js
741 lines (618 loc) · 22.6 KB
/
ecs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
import * as ComponentSet from './component-set.js'
import removeItems from 'remove-array-items'
/**
* @typedef { 'added' | 'removed' } ListenerType
*/
/**
* @typedef { Entity[] } ListenerResult
*/
/**
* @typedef { any } Component
*/
/**
* @typedef {{
* [ key: string ]: Component
* }} Entity
*/
/**
* @typedef { Entity[] } FilteredEntityList
*/
/**
* @typedef { (dt: number) => void } SystemUpdateFunction
*/
/**
* @typedef { Object } System
* @prop {SystemUpdateFunction} [onPreFixedUpdate]
* @prop {SystemUpdateFunction} [onFixedUpdate]
* @prop {SystemUpdateFunction} [onPostFixedUpdate]
* @prop {SystemUpdateFunction} [onPreUpdate]
* @prop {SystemUpdateFunction} [onUpdate]
* @prop {SystemUpdateFunction} [onPostUpdate]
*/
/**
* @typedef {{
* (world: World) => System
* }} SystemFunction
* @prop {string} [name] Name of the function. Defaults to "anonymousSystem"
*/
/**
* @typedef { Object } Listener
*/
/**
* @typedef {{ [ key: string ]: Listener }} ListenerMap
*/
/**
* @typedef { Object } ListenerChangeMap
* @prop {ListenerMap} added
* @prop {ListenerMap} removed
*/
/**
* @typedef {{ [ filterId: string ]: FilteredEntityList }} FilterMap
*/
/**
* @typedef { Object } DeferredRemovalMap
* @prop {number[]} entities
* @prop {string[]} components [ entity, component name ]
*/
/**
* @typedef { Object } WorldStats
* @prop {number} entityCount
* @prop {{ [ key: number ]: number }} componentCount key is component id, value is instance count
* @prop {{ [ key: number ]: number }} filterInvocationCount key is filter id, value is number of times this filter was run this frame
* @prop {{
* name: string;
* timeElapsed: number;
* filters: {
* [ key: string ]: number;
* };
* }[]} systems
* @prop {number} currentSystem the array index of the currently processed system
* used to determine which systems invoke queries
* @prop {number} lastSendTime time stats were last sent (used to throttle send)
*/
/**
* @typedef { Object } World
* @prop {Entity[]} entities
* @prop {FilterMap} filters
* @prop {System[]} systems
* @prop {ListenerChangeMap} listeners
* @prop {DeferredRemovalMap} deferredRemovals
* @prop {WorldStats} stats
*/
/**
* Creates a world and sends window post message with id `mreinstein/ecs-source`
* and method `worldCreated`
*
* @param {number} worldId ID of the world to create
* @returns {World} created world
*/
export function createWorld (worldId=Math.ceil(Math.random() * 999999999) ) {
/**
* @type {World}
*/
const world = {
entityIds: new Map(), // maps both entityId -> entity, and entity -> entityId
nextId: 1, // id of the next entity to be created
entities: [ ],
filters: { },
systems: [ ],
listeners: {
added: new Set(), // entities added last frame
removed: new Set(), // entities removed last frame
// Buffer all entities added/removed this frame and report them as added/removed in the
// next frame. Fixes https://github.com/mreinstein/ecs/issues/35 where some events can
// be missed depending on system order.
_added: new Set(),
_removed: new Set()
},
deferredRemovals: {
entities: new Set(),
components: ComponentSet.create() // [ entity, componentName ] pairs
},
stats: {
// TODO: send world id to support multiple ecs worlds per page
/*worldId, */
entityCount: 0,
componentCount: { }, // key is component id, value is instance count
filterInvocationCount: { }, // key is filter id, value is number of times this filter was run this frame
systems: [
/*
example format:
{
name: 'systemname',
timeElapsed: 0, // milliseconds spent in this system this frame
filters: {
filterId1: 0, // number of entities that matched the filter
filterId2: 0,
}
}
*/
],
// the array index of the currently processed system
// used to determine which systems invoke queries
currentSystem: 0,
lastSendTime: 0, // time stats were last sent (used to throttle send)
}
}
if ((typeof window !== 'undefined') && window.__MREINSTEIN_ECS_DEVTOOLS) {
window.postMessage({
id: 'mreinstein/ecs-source',
method: 'worldCreated',
data: world.stats,
}, '*');
}
return world
}
/**
* Creates an entity and adds it to the world, incrementing the entity count
* @param {World} world world where entity will be added
* @returns {Entity} the created entity
*/
export function createEntity (world) {
const entity = { }
world.entities.push(entity)
world.stats.entityCount++
world.entityIds.set(world.nextId, entity)
world.entityIds.set(entity, world.nextId)
world.nextId++
world.listeners._added.add(entity)
return entity
}
export function getEntityId (world, entity) {
return world.entityIds.get(entity)
}
export function getEntityById (world, entityId) {
return world.entityIds.get(entityId)
}
/**
* Adds a component to the entity
* @param {World} world world where listener will be invoked
* @param {Entity} entity
* @param {string} componentName
* @param {Component} [componentData]
* @returns {void} returns early if this is a duplicate componentName
*/
export function addComponentToEntity (world, entity, componentName, componentData={}) {
// ignore duplicate adds
if (entity[componentName])
return
if (!Number.isInteger(world.stats.componentCount[componentName]))
world.stats.componentCount[componentName] = 0
if (!entity[componentName])
world.stats.componentCount[componentName] += 1
entity[componentName] = componentData
// add this entity to any filters that match
for (const filterId in world.filters) {
const matches = _matchesFilter(filterId, entity)
const filter = world.filters[filterId]
const idx = filter.indexOf(entity)
if (idx >= 0) {
// filter already contains entity and the filter doesn't match the entity, remove it
if (!matches)
removeItems(filter, idx, 1)
} else if (matches) {
// filter doesn't contain the entity yet, and it's not included yet, add it
filter.push(entity)
}
}
}
/**
* Removes a component from the entity, optionally deferring removal
* @param {World} world world where listener will be invoked
* @param {Entity} entity entity to remove component from
* @param {string} componentName name of the component to remove
* @param {boolean} [deferredRemoval] Default is true, optionally defer removal
* @returns {void} returns early if componentName does not exist on entity
*/
export function removeComponentFromEntity (world, entity, componentName, deferredRemoval=true) {
// ignore removals when the component isn't present
if (!entity[componentName])
return
if (deferredRemoval) {
// add the component to the list of components to remove when the cleanup function is invoked
if (!ComponentSet.includes(world.deferredRemovals.components, entity, componentName))
ComponentSet.add(world.deferredRemovals.components, entity, componentName)
} else {
_removeComponent(world, entity, componentName)
}
}
/**
* Remove an entity from the world
* @param {World} world world to remove entity from and emit listeners
* @param {Entity} entity entity to remove
* @param {boolean} [deferredRemoval] Default is true, optionally defer removal
* @returns {void} returns early if entity does not exist in world
*/
export function removeEntity (world, entity, deferredRemoval=true) {
const idx = world.entities.indexOf(entity)
if (idx < 0)
return
world.listeners._removed.add(entity)
if (deferredRemoval) {
// add the entity to the list of entities to remove when the cleanup function is invoked
if (!world.deferredRemovals.entities.has(entity)) {
world.deferredRemovals.entities.add(entity)
world.stats.entityCount--
}
} else {
_removeEntity(world, entity)
}
}
/**
* Remove entities from the world that match the given component criteria.
* @param {World} world - The world containing the entities.
* @param {string[]} componentNames - Array of component names to filter by.
* Supports 'not' filters by prefixing component names with '!'.
*/
export function removeEntities(world, componentNames) {
const entitiesToRemove = world.entities.filter((entity) => {
for (const componentName of componentNames) {
const isNotFilter = componentName.startsWith('!');
const actualComponentName = isNotFilter
? componentName.slice(1)
: componentName;
if (isNotFilter) {
// If it's a 'not' filter (prefixed with '!'), the entity should NOT have the component
if (entity[actualComponentName]) {
return false;
}
} else {
// If it's a regular filter, the entity MUST have the component
if (!entity[actualComponentName]) {
return false;
}
}
}
return true;
});
// Remove each matched entity
for (const entity of entitiesToRemove) {
removeEntity(world, entity, false); // remove immediately
}
}
/**
* Get entities from the world with all provided components. Optionally,
* @param {World} world
* @param {string[]} componentNames A component filter used to match entities.
* Must match all of the components in the filter.
* Can add an exclamation mark at the beginning to query by components that are not present. For example:
* `const entities = ECS.getEntities(world, [ 'transform', '!hero' ])`
*
* @param {ListenerType} [listenerType] Optional. Can be "added" or "removed". Provides a list of entities
* that match were "added" or "removed" since the last system call which matched the filter.
* * @param {ListenerResult} [listenerEntities] Optional. Provides the resulting entities that match the added/removed event.
* must be present whenever ListenerType is present.
* @returns {Entity[]} an array of entities that match the given filters
*/
export function getEntities (world, componentNames, listenerType, listenerEntities) {
const filterId = componentNames.join(',')
if (!world.filters[filterId])
world.filters[filterId] = world.entities.filter((e) => _matchesFilter(filterId, e))
if (!world.stats.filterInvocationCount[filterId])
world.stats.filterInvocationCount[filterId] = 0
world.stats.filterInvocationCount[filterId] += 1;
const systemIdx = world.stats.currentSystem
if (world.stats.systems[systemIdx]) {
if (!world.stats.systems[systemIdx].filters[filterId])
world.stats.systems[systemIdx].filters[filterId] = 0
world.stats.systems[systemIdx].filters[filterId] += world.filters[filterId].length
}
if (listenerType === 'added' || listenerType === 'removed') {
if (listenerEntities) {
listenerEntities.count = 0
for (const entity of world.listeners[listenerType]) {
if (_matchesFilter(filterId, entity)) {
listenerEntities.entries[listenerEntities.count] = entity
listenerEntities.count++
}
}
return listenerEntities
}
} else if (listenerType) {
throw new Error(`Invalid listenerType '${listenerType}'. Should be 'removed' or 'added'.`)
}
return world.filters[filterId]
}
/**
* Get one entity from the world with all provided components. Optionally,
* @param {World} world
* @param {string[]} componentNames A component filter used to match entities.
* Must match all of the components in the filter.
* Can add an exclamation mark at the beginning to query by components that are not present. For example:
* `const e = ECS.getEntity(world, [ 'transform', '!hero' ])`
*
* @returns {Entity|void} one entity that matches the given filters or undefined if none match
*/
export function getEntity (world, componentNames) {
return getEntities(world, componentNames)[0]
}
/**
* returns true if an entity contains all the components that match the filter
* all entities having at least one component in the ignore list are excluded.
* @param {string} filterId
* @param {Entity} entity
* @param {string[]} componentIgnoreList
* @returns
*/
function _matchesFilter (filterId, entity, componentIgnoreList=[]) {
const componentIds = filterId.split(',')
// if the entity lacks any components in the filter, it's not in the filter
for (const componentId of componentIds) {
const isIgnored = componentIgnoreList.includes(componentId)
if (isIgnored)
return false
if (componentId.startsWith('!') && entity[componentId.slice(1)])
return false
if (!componentId.startsWith('!') && !entity[componentId])
return false
}
return true
}
/**
* Adds a system to the world.
* @param {World} world
* @param {SystemFunction} fn
*/
export function addSystem (world, fn) {
const system = fn(world)
world.stats.systems.push({
name: fn.name || 'anonymousSystem',
timeElapsed: 0, // milliseconds spent in this system this frame
// key is filterId, value is number of entities that matched the filter
filters: { }
})
if (!system.onPreFixedUpdate)
system.onPreFixedUpdate = function () { }
if (!system.onFixedUpdate)
system.onFixedUpdate = function () { }
if (!system.onPostFixedUpdate)
system.onPostFixedUpdate = function () { }
if (!system.onPreUpdate)
system.onPreUpdate = function () { }
if (!system.onUpdate)
system.onUpdate = function () { }
if (!system.onPostUpdate)
system.onPostUpdate = function () { }
world.systems.push(system)
}
/**
*
* @param {World} world
* @param {number} dt Change in time since last update, in milliseconds
*/
export function preFixedUpdate (world, dt) {
for (let i=0; i < world.systems.length; i++) {
world.stats.currentSystem = i
const system = world.systems[i]
const start = performance.now()
system.onPreFixedUpdate(dt)
world.stats.systems[i].timeElapsed += (performance.now() - start)
}
}
/**
*
* @param {World} world
* @param {number} dt Change in time since last update, in milliseconds
*/
export function fixedUpdate (world, dt) {
for (let i=0; i < world.systems.length; i++) {
world.stats.currentSystem = i
const system = world.systems[i]
const start = performance.now()
system.onFixedUpdate(dt)
world.stats.systems[i].timeElapsed += (performance.now() - start)
}
}
/**
*
* @param {World} world
* @param {number} dt Change in time since last update, in milliseconds
*/
export function postFixedUpdate (world, dt) {
for (let i=0; i < world.systems.length; i++) {
world.stats.currentSystem = i
const system = world.systems[i]
const start = performance.now()
system.onPostFixedUpdate(dt)
world.stats.systems[i].timeElapsed += (performance.now() - start)
}
}
/**
*
* @param {World} world
* @param {number} dt Change in time since last update, in milliseconds
*/
export function preUpdate (world, dt) {
for (let i=0; i < world.systems.length; i++) {
world.stats.currentSystem = i
const system = world.systems[i]
const start = performance.now()
system.onPreUpdate(dt)
world.stats.systems[i].timeElapsed += (performance.now() - start)
}
}
/**
*
* @param {World} world
* @param {number} dt Change in time since last update, in milliseconds
*/
export function update (world, dt) {
for (let i=0; i < world.systems.length; i++) {
world.stats.currentSystem = i
const system = world.systems[i]
const start = performance.now()
system.onUpdate(dt)
world.stats.systems[i].timeElapsed += (performance.now() - start)
}
}
/**
*
* @param {World} world
* @param {number} dt Change in time since last update, in milliseconds
*/
export function postUpdate (world, dt) {
for (let i=0; i < world.systems.length; i++) {
world.stats.currentSystem = i
const system = world.systems[i]
const start = performance.now()
system.onPostUpdate(dt)
world.stats.systems[i].timeElapsed += (performance.now() - start)
}
}
/**
*
* @param {World} world
*/
function _resetStats (world) {
for (const filterId in world.stats.filterInvocationCount)
world.stats.filterInvocationCount[filterId] = 0
for (const system of world.stats.systems) {
system.timeElapsed = 0
for (const filterId in system.filters)
system.filters[filterId] = 0
}
world.stats.currentSystem = 0
}
/**
*
* @param {World} world
* @param {Entity} entity
* @param {string} componentName
*/
function _removeComponent (world, entity, componentName) {
if (entity[componentName])
world.stats.componentCount[componentName] -= 1
delete entity[componentName]
// remove this entity from any filters that no longer match
for (const filterId in world.filters) {
const filter = world.filters[filterId]
if (_matchesFilter(filterId, entity) && !filter.includes(entity)) {
// entity matches filter and it's not in the filter add it
filter.push(entity)
} else if (_hasComponent(filterId, componentName)) {
// entity doesn't match filter and it's in the filter remove it
// this filter contains the removed component
const filterIdx = filter.indexOf(entity)
if (filterIdx >= 0)
removeItems(filter, filterIdx, 1)
}
}
}
/**
*
* @param {World} world
* @param {Entity} entity
*/
function _removeEntity (world, entity) {
for (const componentName in entity)
if (entity[componentName])
world.stats.componentCount[componentName] -= 1
const entityToRemoveIdx = world.entities.indexOf(entity)
const entityId = world.entityIds.get(entity)
if (entityId !== undefined) {
world.entityIds.delete(entity)
world.entityIds.delete(entityId)
}
removeItems(world.entities, entityToRemoveIdx, 1)
// if this entity was defer removed, but then insta-removed, we can remove
// this entity from the deferred removal list. e.g.,
//
// ECS.removeEntity(w, e, true) // deferred removal
// ECS.removeEntity(w, e, false) // instant removal
// <-- at this point, there shouldnt be anything in the deferred removal list for the cleanup step to run
// ECS.cleanup()
world.deferredRemovals.entities.delete(entity)
for (let i=world.deferredRemovals.components.length-1; i >= 0; i--) {
const [ e ] = world.deferredRemovals.components[i]
if (e === entity) {
// remove this component from the deferred list since the entity it belongs to has already been removed
removeItems(world.deferredRemovals.components, i, 1)
}
}
// update all filters that match this
for (const filterId in world.filters) {
const filter = world.filters[filterId]
const idx = filter.indexOf(entity)
if (idx >= 0)
removeItems(filter, idx, 1)
}
}
/**
* purpose: by given filterId and component determine if component is referred in that filter.
* @param {string} filterId a string in the form "component1,component2,...,componentN", component is a string
* @param {string} component
* @returns {boolean}
*/
function _hasComponent (filterId, component) {
return (filterId === component) ||
filterId.startsWith(`${component},`) ||
filterId.endsWith(`,${component}`) ||
filterId.includes(`,${component},`)
}
/**
* necessary cleanup step at the end of each frame loop
* @param {World} world
*/
export function cleanup (world) {
// move all of the entities that were added/removed this frame into the list to report
// next frame. This ensures that events aren't missed when systems add entities after another
// system listening for those entities has already run this frame.
world.listeners.added.clear()
world.listeners.removed.clear()
for (const e of world.listeners._added)
world.listeners.added.add(e)
for (const e of world.listeners._removed)
world.listeners.removed.add(e)
world.listeners._added.clear()
world.listeners._removed.clear()
// process all entity components marked for deferred removal
for (let i=0; i < world.deferredRemovals.components.length; i++) {
const [ entity, componentName ] = world.deferredRemovals.components[i]
_removeComponent(world, entity, componentName)
}
world.deferredRemovals.components.length = 0
// process all entities marked for deferred removal
for (const entity of world.deferredRemovals.entities)
_removeEntity(world, entity)
world.deferredRemovals.entities.clear()
if ((typeof window !== 'undefined') && window.__MREINSTEIN_ECS_DEVTOOLS) {
// running at 60fps seems to queue up a lot of messages. I'm thinking it might just be more
// data than postMessage can send. capping it at some lower update rate seems to work better.
// for now capping this at 4fps. later we might investigate if sending deltas over postmessage
// solves the message piling up problem.
if (performance.now() - world.stats.lastSendTime > 250) {
world.stats.lastSendTime = performance.now();
window.postMessage({
id: 'mreinstein/ecs-source',
method: 'refreshData',
data: world.stats,
}, '*');
}
}
setTimeout(_resetStats, 0, world) // defer reset until next frame
}
export default {
createWorld,
createEntity,
getEntityId,
getEntityById,
addComponentToEntity,
removeComponentFromEntity,
getEntities,
getEntity,
removeEntity,
removeEntities,
addSystem,
preFixedUpdate,
fixedUpdate,
postFixedUpdate,
update,
preUpdate,
postUpdate,
cleanup,
// aliases. shorter == nicer :)
addWorld: createWorld,
addEntity: createEntity,
addComponent: addComponentToEntity,
removeComponent: removeComponentFromEntity
}