@daneren2005/shared-memory-ecs 1.10.3 → 1.10.5

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/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- import { _ as e, a as t, c as n, d as r, f as i, g as a, h as o, i as s, l as c, m as l, n as u, o as d, p as f, r as p, s as m, t as h, u as ee, v as g, y as _ } from "./create-system-worker-BU5CnyVh.js";
2
- import te from "@daneren2005/shared-memory-objects/memory-heap";
3
- import { MAX_BYTE_OFFSET_LENGTH as v } from "@daneren2005/shared-memory-objects/utils/pointer";
4
- //#region \0rolldown/runtime.js
5
- var y = Object.create, b = Object.defineProperty, ne = Object.getOwnPropertyDescriptor, re = Object.getOwnPropertyNames, ie = Object.getPrototypeOf, x = Object.prototype.hasOwnProperty, ae = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), oe = (e, t, n, r) => {
6
- if (t && typeof t == "object" || typeof t == "function") for (var i = re(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !x.call(e, s) && s !== n && b(e, s, {
1
+ import { _ as e, a as t, b as n, c as r, d as i, f as a, g as o, h as s, i as c, l, m as u, n as d, o as f, p, r as ee, s as te, t as ne, u as re, v as ie, x as m, y as h } from "./create-system-worker-CkPwxmmr.js";
2
+ import ae from "@daneren2005/shared-memory-objects/memory-heap";
3
+ import { MAX_BYTE_OFFSET_LENGTH as g } from "@daneren2005/shared-memory-objects/utils/pointer";
4
+ // \0rolldown/runtime.js
5
+ var oe = Object.create, _ = Object.defineProperty, v = Object.getOwnPropertyDescriptor, y = Object.getOwnPropertyNames, se = Object.getPrototypeOf, ce = Object.prototype.hasOwnProperty, le = (e, t) => () => (t || (e((t = { exports: {} }).exports, t, t.exports), e = null), t.exports), ue = (e, t, n, r) => {
6
+ if (t && typeof t == "object" || typeof t == "function") for (var i = y(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !ce.call(e, s) && s !== n && _(e, s, {
7
7
  get: ((e) => t[e]).bind(null, s),
8
- enumerable: !(r = ne(t, s)) || r.enumerable
8
+ enumerable: !(r = v(t, s)) || r.enumerable
9
9
  });
10
10
  return e;
11
- }, S = /* @__PURE__ */ ((e, t, n) => (n = e == null ? {} : y(ie(e)), oe(t || !e || !e.__esModule || !x.call(e, "default") ? b(n, "default", {
11
+ }, b = /* @__PURE__ */ ((e, t, n) => (n = e == null ? {} : oe(se(e)), ue(_(n, "default", {
12
12
  value: e,
13
13
  enumerable: !0
14
- }) : n, e)))((/* @__PURE__ */ ae(((e, t) => {
14
+ }), e)))((/* @__PURE__ */ le(((e, t) => {
15
15
  var n = Object.prototype.hasOwnProperty, r = "~";
16
16
  function i() {}
17
17
  Object.create && (i.prototype = Object.create(null), new i().__proto__ || (r = !1));
@@ -88,7 +88,7 @@ var y = Object.create, b = Object.defineProperty, ne = Object.getOwnPropertyDesc
88
88
  if (!this._events[a]) return this;
89
89
  if (!t) return s(this, a), this;
90
90
  var o = this._events[a];
91
- if (o.fn) o.fn === t && (!i || o.once) && (!n || o.context === n) && s(this, a);
91
+ if (o.fn) o.fn !== t || i && !o.once || n && o.context !== n || s(this, a);
92
92
  else {
93
93
  for (var c = 0, l = [], u = o.length; c < u; c++) (o[c].fn !== t || i && !o[c].once || n && o[c].context !== n) && l.push(o[c]);
94
94
  l.length ? this._events[a] = l.length === 1 ? l[0] : l : s(this, a);
@@ -98,7 +98,38 @@ var y = Object.create, b = Object.defineProperty, ne = Object.getOwnPropertyDesc
98
98
  var t;
99
99
  return e ? (t = r ? r + e : e, this._events[t] && s(this, t)) : (this._events = new i(), this._eventsCount = 0), this;
100
100
  }, c.prototype.off = c.prototype.removeListener, c.prototype.addListener = c.prototype.on, c.prefixed = r, c.EventEmitter = c, t !== void 0 && (t.exports = c);
101
- })))(), 1), C = class extends S.default {
101
+ })))(), 1), de = [], fe = (e, t) => e.order - t.order, pe = class {
102
+ immediate = /* @__PURE__ */ new Map();
103
+ deferred = /* @__PURE__ */ new Map();
104
+ constructor(e) {
105
+ Object.keys(e).forEach((t, n) => {
106
+ if (t === "entity") return;
107
+ let r = e[t], i = r.loadInFinishLoading ? this.deferred : this.immediate, a = {
108
+ name: t,
109
+ order: n
110
+ };
111
+ for (let e of r.loadProperties) {
112
+ let t = i.get(e);
113
+ t ? t.push(a) : i.set(e, [a]);
114
+ }
115
+ });
116
+ }
117
+ forLoad(e) {
118
+ return this.find(this.immediate, e);
119
+ }
120
+ forFinishLoading(e) {
121
+ return this.find(this.deferred, e);
122
+ }
123
+ find(e, t) {
124
+ if (e.size === 0) return de;
125
+ let n = [];
126
+ for (let r in t) {
127
+ let t = e.get(r);
128
+ if (t) for (let e of t) n.includes(e) || n.push(e);
129
+ }
130
+ return n.sort(fe);
131
+ }
132
+ }, x = class extends b.default {
102
133
  world;
103
134
  name;
104
135
  currentDelta = 0;
@@ -174,13 +205,12 @@ var y = Object.create, b = Object.defineProperty, ne = Object.getOwnPropertyDesc
174
205
  this.removeAllListeners();
175
206
  }
176
207
  };
177
- function w(e, t, n) {
208
+ function S(e, t, n) {
178
209
  let r = e.groups.map(t);
179
210
  for (let t = 0; t < e.entities.length; t++) r[e.groupIndexes[t]] && n(e.entities[t]);
180
211
  }
181
- //#endregion
182
- //#region src/systems/iterable-system.ts
183
- var T = class extends C {
212
+ // src/systems/iterable-system.ts
213
+ var C = class extends x {
184
214
  remainingInstancesToRun = [];
185
215
  remainingInstancesStartTime = null;
186
216
  iterationsPerCheck;
@@ -230,7 +260,7 @@ var T = class extends C {
230
260
  }
231
261
  beforeRunIterables() {}
232
262
  getIterableEntityId(e) {}
233
- }, E = class e extends T {
263
+ }, w = class e extends C {
234
264
  entities = /* @__PURE__ */ new Map();
235
265
  options;
236
266
  constructor(e, t = { name: "EntitySystem" }) {
@@ -264,13 +294,9 @@ var T = class extends C {
264
294
  this.checkAddEntity(e) && this.options.updateEntityOnAdd && this.updateEntity(e, 0);
265
295
  }
266
296
  addEntities(t) {
267
- if (this.checkAddEntity !== e.prototype.checkAddEntity) {
268
- t.entities.forEach((e) => this.onEntityAdded(e));
269
- return;
270
- }
271
- w(t, (e) => this.hasComponents(e), (e) => {
297
+ this.checkAddEntity === e.prototype.checkAddEntity ? S(t, (e) => this.hasComponents(e), (e) => {
272
298
  this.filterEntity(e) && (this.entities.set(e.eid, e), this.options.updateEntityOnAdd && this.updateEntity(e, 0));
273
- });
299
+ }) : t.entities.forEach((e) => this.onEntityAdded(e));
274
300
  }
275
301
  hasComponents(e) {
276
302
  return !this.options.components || this.options.components.every((t) => !!e.components[t]);
@@ -300,12 +326,12 @@ var T = class extends C {
300
326
  ...this.reads ?? []
301
327
  ] : void 0;
302
328
  }
303
- }, D = class {
329
+ }, T = class {
304
330
  onmessage(e, t = []) {}
305
- }, O = class extends D {
331
+ }, E = class extends T {
306
332
  updateFunction;
307
- entities = new e();
308
- workState = new a();
333
+ entities = new h();
334
+ workState = new ie();
309
335
  queryEntities = {};
310
336
  worldExtension;
311
337
  world;
@@ -321,69 +347,69 @@ var T = class extends C {
321
347
  };
322
348
  }
323
349
  getString = (e) => this.world.constantStrings.getString(e) ?? "";
324
- postMessage(e) {
325
- if (e.type === "init") this.onMessageTyped({ type: "init-complete" });
326
- else if (e.type === "load") {
327
- this.entities.apply(e.entities);
328
- let t = this.applyQueryDeltas(e.queries), n = {
329
- gameTime: e.gameTime,
350
+ postMessage(t) {
351
+ if (t.type === "init") this.onMessageTyped({ type: "init-complete" });
352
+ else if (t.type === "load") {
353
+ this.entities.apply(t.entities);
354
+ let e = this.applyQueryDeltas(t.queries), n = {
355
+ gameTime: t.gameTime,
330
356
  getString: this.getString,
331
357
  heap: this.world.heap
332
358
  };
333
- this.worldExtension = this.updateFunction.init?.(n, e.data, this.entities.entries, t) ?? void 0, this.onMessageTyped({ type: "loaded" });
334
- } else if (e.type === "reset") this.workState.clear(), this.entities.clear(), this.queryEntities = {};
335
- else if (e.type === "run") {
336
- if (e.world = this.workState.getWorld(e.world, e.workBatch), this.worldExtension && Object.assign(e.world, this.worldExtension), e.world.getString = this.getString, e.world.heap = this.world.heap, e.world.allocate = this.allocator, this.createsEntities) {
337
- let t = this.world.registry;
338
- e.world.buildEntityDescriptor = (e) => o(e, this.world.factory.configs, t, this.allocator, this.world.factory.getWorkerClasses());
359
+ this.worldExtension = this.updateFunction.init?.(n, t.data, this.entities.entries, e) ?? void 0, this.onMessageTyped({ type: "loaded" });
360
+ } else if (t.type === "reset") this.workState.clear(), this.entities.clear(), this.queryEntities = {};
361
+ else if (t.type === "run") {
362
+ if (t.world = this.workState.getWorld(t.world, t.workBatch), this.worldExtension && Object.assign(t.world, this.worldExtension), t.world.getString = this.getString, t.world.heap = this.world.heap, t.world.allocate = this.allocator, this.createsEntities) {
363
+ let n = this.world.registry;
364
+ t.world.buildEntityDescriptor = (t) => e(t, this.world.factory.configs, n, this.allocator, this.world.factory.getWorkerClasses());
339
365
  }
340
366
  if (this.addsComponents) {
341
- let t = this.world.registry;
342
- e.world.buildComponentDescriptor = (e, n) => l(e, n, t, this.allocator);
367
+ let e = this.world.registry;
368
+ t.world.buildComponentDescriptor = (t, n) => o(t, n, e, this.allocator);
343
369
  }
344
- let t = performance.now(), n = [], r = {}, i = [], a = [], s = [];
345
- this.entities.apply(e.entities);
346
- let c = this.workState.getEntities(this.entities.entries, e.entities, e.workBatch), u = this.applyQueryDeltas(e.queries), d = {
347
- entityComponentChanged(e, t, r, i) {
348
- n.push({
370
+ let n = performance.now(), r = [], i = {}, a = [], s = [], c = [];
371
+ this.entities.apply(t.entities);
372
+ let l = this.workState.getEntities(this.entities.entries, t.entities, t.workBatch), u = this.applyQueryDeltas(t.queries), d = {
373
+ entityComponentChanged(e, t, n, i) {
374
+ r.push({
349
375
  entityId: e,
350
376
  event: "component-property-updated",
351
377
  args: [
352
378
  t,
353
- r,
379
+ n,
354
380
  i
355
381
  ]
356
382
  });
357
383
  },
358
- emitEntityEvent(e, t, ...r) {
359
- n.push({
384
+ emitEntityEvent(e, t, ...n) {
385
+ r.push({
360
386
  entityId: e,
361
387
  event: t,
362
- args: r
388
+ args: n
363
389
  });
364
390
  },
365
391
  emitSystemEvent(e, t) {
366
- (r[e] ?? (r[e] = [])).push(t);
392
+ (i[e] ?? (i[e] = [])).push(t);
367
393
  },
368
394
  entityDied(e) {
369
- n.push({
395
+ r.push({
370
396
  entityId: e,
371
397
  event: "death",
372
398
  args: []
373
399
  });
374
400
  },
375
401
  createEntity(e) {
376
- i.push(e);
402
+ a.push(e);
377
403
  },
378
404
  addComponent(e, t) {
379
- a.push({
405
+ s.push({
380
406
  type: "add",
381
407
  entityId: e,
382
408
  component: t
383
409
  });
384
410
  },
385
411
  removeComponent(e, t) {
386
- a.push({
412
+ s.push({
387
413
  type: "remove",
388
414
  entityId: e,
389
415
  componentName: String(t)
@@ -391,77 +417,77 @@ var T = class extends C {
391
417
  }
392
418
  };
393
419
  if (this.updateFunction.queryChanged) {
394
- for (let [t, n] of Object.entries(e.queries)) if (n.added.length || n.removed.length) try {
395
- this.updateFunction.queryChanged(e.world, t, n, d);
420
+ for (let [e, n] of Object.entries(t.queries)) if (n.added.length || n.removed.length) try {
421
+ this.updateFunction.queryChanged(t.world, e, n, d);
396
422
  } catch (e) {
397
- s.push({
423
+ c.push({
398
424
  error: e,
399
425
  phase: "queryChanged"
400
426
  });
401
427
  }
402
428
  }
403
429
  let f = !1;
404
- if (this.updateFunction.preRun && (!e.workBatch || e.workBatch.first)) try {
405
- this.updateFunction.preRun(e.world, this.entities.entries, u, d);
430
+ if (this.updateFunction.preRun && (!t.workBatch || t.workBatch.first)) try {
431
+ this.updateFunction.preRun(t.world, this.entities.entries, u, d);
406
432
  } catch (e) {
407
- f = !0, s.push({
433
+ f = !0, c.push({
408
434
  error: e,
409
435
  phase: "preRun"
410
436
  });
411
437
  }
412
438
  if (!f && this.updateFunction.preBatch) try {
413
- this.updateFunction.preBatch(e.world, c, u, d);
439
+ this.updateFunction.preBatch(t.world, l, u, d);
414
440
  } catch (e) {
415
- f = !0, s.push({
441
+ f = !0, c.push({
416
442
  error: e,
417
443
  phase: "preBatch"
418
444
  });
419
445
  }
420
- if (f || c.forEach((t) => {
446
+ if (f || l.forEach((e) => {
421
447
  try {
422
- this.updateFunction(e.world, t.entityId, t.components, u, d);
423
- } catch (e) {
424
- s.push({
425
- error: e,
448
+ this.updateFunction(t.world, e.entityId, e.components, u, d);
449
+ } catch (t) {
450
+ c.push({
451
+ error: t,
426
452
  phase: "update",
427
- entityId: t.entityId
453
+ entityId: e.entityId
428
454
  });
429
455
  }
430
- }), this.updateFunction.entityRemoved) for (let t of e.entities.removed) try {
431
- this.updateFunction.entityRemoved(e.world, t, d);
432
- } catch (e) {
433
- s.push({
434
- error: e,
456
+ }), this.updateFunction.entityRemoved) for (let e of t.entities.removed) try {
457
+ this.updateFunction.entityRemoved(t.world, e, d);
458
+ } catch (t) {
459
+ c.push({
460
+ error: t,
435
461
  phase: "entityRemoved",
436
- entityId: t
462
+ entityId: e
437
463
  });
438
464
  }
439
- let p = performance.now() - t;
440
- this.workState.finish(e.workBatch, f), this.onMessageTyped({
465
+ let p = performance.now() - n;
466
+ this.workState.finish(t.workBatch, f), this.onMessageTyped({
441
467
  type: "run-complete",
442
- generation: e.generation,
468
+ generation: t.generation,
443
469
  runTime: p,
444
- events: n,
445
- systemEvents: r,
446
- created: i,
447
- componentChanges: a,
448
- errors: s,
470
+ events: r,
471
+ systemEvents: i,
472
+ created: a,
473
+ componentChanges: s,
474
+ errors: c,
449
475
  workFailed: f
450
476
  });
451
477
  }
452
478
  }
453
- applyQueryDeltas(t) {
454
- let n = {};
455
- for (let [r, i] of Object.entries(t)) {
456
- let t = this.queryEntities[r] ??= new e();
457
- t.apply(i), n[r] = t.entries;
479
+ applyQueryDeltas(e) {
480
+ let t = {};
481
+ for (let [n, r] of Object.entries(e)) {
482
+ let e = this.queryEntities[n] ??= new h();
483
+ e.apply(r), t[n] = e.entries;
458
484
  }
459
- return n;
485
+ return t;
460
486
  }
461
487
  onMessageTyped(e) {
462
488
  this.onmessage({ data: e });
463
489
  }
464
- }, k = "___main", A = class e extends C {
490
+ }, D = "___main", O = class e extends x {
465
491
  entities = /* @__PURE__ */ new Map();
466
492
  options;
467
493
  worker;
@@ -479,6 +505,7 @@ var T = class extends C {
479
505
  generation = 0;
480
506
  queryEntities = {};
481
507
  queryDeltas = {};
508
+ bulkMembershipPending = !1;
482
509
  constructor(e, t) {
483
510
  if (super(e, t), t.workBatchSize !== void 0 && (!Number.isSafeInteger(t.workBatchSize) || t.workBatchSize <= 0)) throw Error("workBatchSize must be a positive safe integer");
484
511
  this.options = t, Object.keys(this.options.queries ?? {}).forEach((e) => {
@@ -494,13 +521,13 @@ var T = class extends C {
494
521
  type: "grow-buffer",
495
522
  buffer: e
496
523
  });
497
- })) : (this.worker = new O(t.updateFunction, e, !!t.createsEntities, !!t.addsComponents), this.isWorkerThread = !1), this.initWorker();
524
+ })) : (this.worker = new E(t.updateFunction, e, !!t.createsEntities, !!t.addsComponents), this.isWorkerThread = !1), this.initWorker();
498
525
  }
499
526
  initWorker() {
500
527
  let e = (e) => {
501
528
  console.error(e, e.cause), this.initialized || (this.initError = e, this.initPromise?.reject(e));
502
529
  };
503
- if (!(this.worker instanceof O)) {
530
+ if (!(this.worker instanceof E)) {
504
531
  let t = (t) => {
505
532
  e(Error(`Worker ${this.name} failed to load`, { cause: t }));
506
533
  };
@@ -531,17 +558,16 @@ var T = class extends C {
531
558
  }, a = {
532
559
  apply: () => {
533
560
  if (!r) {
534
- if (t !== this.generation) {
535
- a.discard();
536
- return;
537
- }
538
- r = !0, this.pendingEffects = void 0;
539
- try {
540
- this.applyWorkerEffects(n, !1, e);
541
- } catch (e) {
542
- this.onError(e, { phase: "run" }), this.world.notifySystemRunCompleted(this);
543
- } finally {
544
- i();
561
+ if (t !== this.generation) a.discard();
562
+ else {
563
+ r = !0, this.pendingEffects = void 0;
564
+ try {
565
+ this.applyWorkerEffects(n, !1, e);
566
+ } catch (e) {
567
+ this.onError(e, { phase: "run" }), this.world.notifySystemRunCompleted(this);
568
+ } finally {
569
+ i();
570
+ }
545
571
  }
546
572
  }
547
573
  },
@@ -574,11 +600,7 @@ var T = class extends C {
574
600
  for (let t of Object.keys(e.systemEvents)) this.emit(t, e.systemEvents[t]);
575
601
  e.events.forEach((e) => {
576
602
  let t = this.world.getEntityByEid(e.entityId);
577
- if (!t) {
578
- console.warn(`${this.name}-event ${e.event}: Could not find entity with id ${e.entityId}`);
579
- return;
580
- }
581
- t.emit(e.event, ...e.args);
603
+ t ? t.emit(e.event, ...e.args) : console.warn(`${this.name}-event ${e.event}: Could not find entity with id ${e.entityId}`);
582
604
  }), e.created.forEach((e) => {
583
605
  this.world.adoptEntity(e);
584
606
  }), this.world.emit(`system-${this.name}-worker-events-finished`, e.runTime, n), this.world.notifySystemRunCompleted(this), this.runCompletePromise &&= (this.runCompletePromise.resolve(), null);
@@ -597,23 +619,25 @@ var T = class extends C {
597
619
  promise: e,
598
620
  resolve: t
599
621
  };
600
- let n = {};
622
+ let n = [], r = {};
601
623
  Object.entries(this.options.queries ?? {}).forEach(([e, t]) => {
602
- n[e] = this.buildQueryDelta(e, t);
624
+ r[e] = this.buildLoadDelta(e, t, this.queryEntities[e], n);
603
625
  });
604
- let r = {
626
+ let i = this.buildLoadDelta(D, this.options, this.entities, n);
627
+ this.bulkMembershipPending = !1;
628
+ let a = {
605
629
  type: "load",
606
630
  data: this.options.getInitData?.(),
607
631
  gameTime: this.gameTime,
608
- entities: this.buildQueryDelta(k, this.options),
609
- queries: n,
632
+ entities: i,
633
+ queries: r,
610
634
  heap: this.isWorkerThread ? this.world.heap.getSharedMemory() : void 0,
611
635
  sharedMemory: this.isWorkerThread ? this.world.getSharedComponentMemory() : void 0,
612
636
  factoryConfigs: this.isWorkerThread && this.options.createsEntities ? this.world.factory.configs : void 0,
613
637
  factoryClasses: this.isWorkerThread && this.options.createsEntities ? this.world.factory.getWorkerClasses() : void 0,
614
638
  addsComponents: !!this.options.addsComponents
615
639
  };
616
- return this.worker.postMessage(r), e;
640
+ return this.worker instanceof E ? this.worker.postMessage(a) : this.worker.postMessage(a, n), e;
617
641
  }
618
642
  clear() {
619
643
  if (super.clear(), this.pendingEffects?.discard(), this.isRunning && !this.runCompletePromise) {
@@ -623,7 +647,7 @@ var T = class extends C {
623
647
  resolve: t
624
648
  };
625
649
  }
626
- this.isRunning = !1, this.generation++, this.entities.clear(), Object.values(this.queryEntities).forEach((e) => e.clear()), this.queryDeltas = {}, this.workPass = void 0, this.timingBatch = void 0, this.worker.postMessage({ type: "reset" });
650
+ this.isRunning = !1, this.generation++, this.entities.clear(), Object.values(this.queryEntities).forEach((e) => e.clear()), this.queryDeltas = {}, this.bulkMembershipPending = !1, this.workPass = void 0, this.timingBatch = void 0, this.worker.postMessage({ type: "reset" });
627
651
  }
628
652
  update(e) {
629
653
  return this.isRunning ? (this.currentDelta += e, !1) : this.workPass ? (this.currentDelta += e, this.run(this.workPass.elapsedTime), !0) : super.update(e);
@@ -705,7 +729,7 @@ var T = class extends C {
705
729
  first: t.first,
706
730
  last: t.last
707
731
  }, this.isRunning = !0, this.completeEffects = this.world.scheduler.prepareEffects?.(this.world, this);
708
- let i = this.buildQueryDelta(k, this.options), a = {};
732
+ let i = this.buildQueryDelta(D, this.options), a = {};
709
733
  Object.entries(this.options.queries ?? {}).forEach(([e, t]) => {
710
734
  a[e] = this.buildQueryDelta(e, t);
711
735
  });
@@ -719,21 +743,28 @@ var T = class extends C {
719
743
  };
720
744
  this.worker.postMessage(o);
721
745
  }
722
- buildQueryDelta(e, t) {
723
- let n = this.getQueryDelta(e), r = [];
724
- n.added.forEach((e) => {
725
- r.push({
726
- entityId: e.eid,
727
- components: this.buildComponents(e, t)
728
- });
746
+ buildQueryDelta(e, t, n) {
747
+ let r = this.getQueryDelta(e), i = [];
748
+ for (let e of (n ?? r.added).values()) i.push({
749
+ entityId: e.eid,
750
+ components: this.buildComponents(e, t)
729
751
  });
730
- let i = Array.from(n.removed);
752
+ let a = Array.from(r.removed);
731
753
  return this.queryDeltas[e] = {
732
754
  added: /* @__PURE__ */ new Set(),
733
755
  removed: /* @__PURE__ */ new Set()
734
756
  }, {
735
- added: r,
736
- removed: i
757
+ added: i,
758
+ removed: a
759
+ };
760
+ }
761
+ buildLoadDelta(e, t, n, r) {
762
+ let i = this.bulkMembershipPending ? n : this.getQueryDelta(e).added;
763
+ if (!this.isWorkerThread) return this.buildQueryDelta(e, t, i);
764
+ let a = s(i, [...t.required, ...t.optional ?? []]);
765
+ return r.push(...u(a)), {
766
+ ...this.buildQueryDelta(e, t, /* @__PURE__ */ new Set()),
767
+ packedAdded: a
737
768
  };
738
769
  }
739
770
  buildComponents(e, t) {
@@ -774,29 +805,24 @@ var T = class extends C {
774
805
  }
775
806
  checkAddEntity(e) {
776
807
  let t = this.tracksMainQuery && this.matchesQuery(e, this.options);
777
- return this.updateEntityList(k, this.entities, e, t), Object.entries(this.options.queries ?? {}).forEach(([t, n]) => {
808
+ return this.updateEntityList(D, this.entities, e, t), Object.entries(this.options.queries ?? {}).forEach(([t, n]) => {
778
809
  let r = this.queryEntities[t] ?? (this.queryEntities[t] = /* @__PURE__ */ new Map());
779
810
  this.updateEntityList(t, r, e, this.matchesQuery(e, n));
780
811
  }), t;
781
812
  }
782
813
  addEntities(t) {
783
- if (this.checkAddEntity !== e.prototype.checkAddEntity || this.matchesQuery !== e.prototype.matchesQuery) {
784
- t.entities.forEach((e) => this.checkAddEntity(e));
785
- return;
786
- }
787
- this.tracksMainQuery && this.addBatchToQuery(k, this.entities, this.options, t), Object.entries(this.options.queries ?? {}).forEach(([e, n]) => {
814
+ this.checkAddEntity !== e.prototype.checkAddEntity || this.matchesQuery !== e.prototype.matchesQuery ? t.entities.forEach((e) => this.checkAddEntity(e)) : (this.bulkMembershipPending = !0, this.tracksMainQuery && this.addBatchToQuery(this.entities, this.options, t), Object.entries(this.options.queries ?? {}).forEach(([e, n]) => {
788
815
  let r = this.queryEntities[e] ?? (this.queryEntities[e] = /* @__PURE__ */ new Map());
789
- this.addBatchToQuery(e, r, n, t);
790
- });
816
+ this.addBatchToQuery(r, n, t);
817
+ }));
791
818
  }
792
- addBatchToQuery(e, t, n, r) {
793
- let i = this.getQueryDelta(e);
794
- w(r, (e) => this.matchesComponents(e, n), (e) => {
795
- e.components.entity.dead || n.filter && !n.filter(e) || (t.set(e.eid, e), this.markAdded(i, e));
819
+ addBatchToQuery(e, t, n) {
820
+ S(n, (e) => this.matchesComponents(e, t), (n) => {
821
+ n.components.entity.dead || t.filter && !t.filter(n) || e.set(n.eid, n);
796
822
  });
797
823
  }
798
824
  removeEntity(e) {
799
- this.updateEntityList(k, this.entities, e, !1), Object.entries(this.queryEntities).forEach(([t, n]) => {
825
+ this.updateEntityList(D, this.entities, e, !1), Object.entries(this.queryEntities).forEach(([t, n]) => {
800
826
  this.updateEntityList(t, n, e, !1);
801
827
  });
802
828
  }
@@ -811,7 +837,7 @@ var T = class extends C {
811
837
  destroy() {
812
838
  super.destroy(), this.pendingEffects?.discard(), "terminate" in this.worker && this.worker.terminate();
813
839
  }
814
- }, j = class extends S.default {
840
+ }, k = class extends b.default {
815
841
  eid;
816
842
  config;
817
843
  world;
@@ -873,12 +899,7 @@ var T = class extends C {
873
899
  }
874
900
  }
875
901
  load(e) {
876
- let t = e, n = this.world.registry;
877
- for (let r of Object.keys(n)) {
878
- if (r === "entity" || !this.isComponentAllowed(r)) continue;
879
- let i = n[r];
880
- i.loadInFinishLoading || i.loadProperties.some((e) => e in t) && this.loadComponent(r, e, !1);
881
- }
902
+ for (let { name: t } of this.world.componentTriggers.forLoad(e)) this.isComponentAllowed(t) && this.loadComponent(t, e, !1);
882
903
  this.config = e;
883
904
  }
884
905
  save() {
@@ -891,13 +912,7 @@ var T = class extends C {
891
912
  }
892
913
  finishLoading() {
893
914
  let e = this.config;
894
- if (!e) return;
895
- let t = e, n = this.world.registry;
896
- for (let r of Object.keys(n)) {
897
- if (r === "entity" || !this.isComponentAllowed(r)) continue;
898
- let i = n[r];
899
- i.loadInFinishLoading && i.loadProperties.some((e) => e in t) && this.loadComponent(r, e, !1);
900
- }
915
+ if (e) for (let { name: t } of this.world.componentTriggers.forFinishLoading(e)) this.isComponentAllowed(t) && this.loadComponent(t, e, !1);
901
916
  }
902
917
  isComponentAllowed(e) {
903
918
  return e === "entity" || !this.allowedComponents || this.allowedComponents.has(String(e));
@@ -912,7 +927,7 @@ var T = class extends C {
912
927
  assertComponentPropertyMutable(e, t) {
913
928
  if (e === "entity" && (t === "type" || t === "class")) throw Error(`Entity ${t} is immutable`);
914
929
  }
915
- }, M = class e {
930
+ }, A = class e {
916
931
  world;
917
932
  configs;
918
933
  classes;
@@ -929,7 +944,7 @@ var T = class extends C {
929
944
  this.world = e, this.forbiddenProperties.clear();
930
945
  for (let t of Object.keys(this.classes)) {
931
946
  let n = this.classes[t].entity;
932
- if (n !== j && !(n.prototype instanceof j)) throw Error(`Entity class ${t} must extend BaseEntity`);
947
+ if (n !== k && !(n.prototype instanceof k)) throw Error(`Entity class ${t} must extend BaseEntity`);
933
948
  for (let n of this.classes[t].components) if (n === "entity" || !(n in e.registry)) throw Error(`Entity class ${t} contains unknown or reserved component ${n}`);
934
949
  }
935
950
  for (let e of Object.keys(this.configs)) this.validateTemplate(e, this.configs[e]);
@@ -955,7 +970,7 @@ var T = class extends C {
955
970
  createAdoptedEntity(e, t, n) {
956
971
  if (!t) {
957
972
  if (this.hasClasses) throw Error(`Entity type ${e} has no class`);
958
- return new j(this.world, void 0, n);
973
+ return new k(this.world, void 0, n);
959
974
  }
960
975
  let r = this.classes[t];
961
976
  if (!r) throw Error(`Unknown entity class: ${t}`);
@@ -981,7 +996,7 @@ var T = class extends C {
981
996
  return e ? this.getAllowedComponents(e) : void 0;
982
997
  }
983
998
  createEntity(e) {
984
- return new j(this.world, e);
999
+ return new k(this.world, e);
985
1000
  }
986
1001
  get hasClasses() {
987
1002
  return this.allowedComponents.size > 0;
@@ -1046,48 +1061,48 @@ var T = class extends C {
1046
1061
  }
1047
1062
  throw Error(`Entity type ${e} class ${t} loads a component outside its class`);
1048
1063
  }
1049
- }, N = 45, P = "!", F = "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO", I = "PQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}", L = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
1050
- for (let e = 0; e < N; e++) L[F.charCodeAt(e)] = e, L[I.charCodeAt(e)] = e + N;
1051
- function R(e) {
1064
+ }, j = 45, M = "!", N = "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO", P = "PQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}", F = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
1065
+ for (let e = 0; e < j; e++) F[N.charCodeAt(e)] = e, F[P.charCodeAt(e)] = e + j;
1066
+ function I(e) {
1052
1067
  let t = "";
1053
- for (; e >= N;) t += I[e % N], e = Math.floor(e / N);
1054
- return t + F[e];
1068
+ for (; e >= j;) t += P[e % j], e = Math.floor(e / j);
1069
+ return t + N[e];
1055
1070
  }
1056
- var z = /* @__PURE__ */ new Float32Array(1), B = new Uint32Array(z.buffer);
1057
- function se(e, t) {
1071
+ var L = /* @__PURE__ */ new Float32Array(1), R = new Uint32Array(L.buffer);
1072
+ function z(e, t) {
1058
1073
  switch (e.type) {
1059
- case "boolean": return typeof t == "boolean" ? F[Number(t)] : void 0;
1060
- case "string": return t === null ? F[0] : typeof t == "string" && t.length ? R(t.length) + t : void 0;
1061
- case "float32": return typeof t != "number" || !Number.isFinite(t) || Math.fround(t) !== t ? void 0 : (z[0] = t, R(B[0]));
1074
+ case "boolean": return typeof t == "boolean" ? N[Number(t)] : void 0;
1075
+ case "string": return t === null ? N[0] : typeof t == "string" && t.length ? I(t.length) + t : void 0;
1076
+ case "float32": return typeof t != "number" || !Number.isFinite(t) || Math.fround(t) !== t ? void 0 : (L[0] = t, I(R[0]));
1062
1077
  default: {
1063
- let n = V(e, t);
1064
- return n === void 0 ? void 0 : R(n);
1078
+ let n = B(e, t);
1079
+ return n === void 0 ? void 0 : I(n);
1065
1080
  }
1066
1081
  }
1067
1082
  }
1068
- function V(e, t) {
1083
+ function B(e, t) {
1069
1084
  if (typeof t != "number") return;
1070
1085
  let n = Math.round((t - (e.offset ?? 0)) * 10 ** (e.decimals ?? 0) / (e.step ?? 1));
1071
- if (!Number.isSafeInteger(n) || H(e, n) !== t) return;
1086
+ if (!Number.isSafeInteger(n) || V(e, n) !== t) return;
1072
1087
  if (e.type === "uint") return n >= 0 ? n : void 0;
1073
1088
  let r = n >= 0 ? n * 2 : -n * 2 - 1;
1074
1089
  return Number.isSafeInteger(r) ? r : void 0;
1075
1090
  }
1076
- function H(e, t) {
1091
+ function V(e, t) {
1077
1092
  return t * (e.step ?? 1) / 10 ** (e.decimals ?? 0) + (e.offset ?? 0);
1078
1093
  }
1079
- function U(e, t) {
1094
+ function me(e, t) {
1080
1095
  switch (e.type) {
1081
1096
  case "boolean": return t !== 0;
1082
- case "float32": return B[0] = t, z[0];
1083
- case "uint": return H(e, t);
1084
- default: return H(e, t % 2 == 0 ? t / 2 : -(t + 1) / 2);
1097
+ case "float32": return R[0] = t, L[0];
1098
+ case "uint": return V(e, t);
1099
+ default: return V(e, t % 2 == 0 ? t / 2 : -(t + 1) / 2);
1085
1100
  }
1086
1101
  }
1087
- function W(e) {
1102
+ function H(e) {
1088
1103
  return e.types === void 0 ? [e.type] : e.types;
1089
1104
  }
1090
- var G = class {
1105
+ var U = class {
1091
1106
  encoders = /* @__PURE__ */ new Map();
1092
1107
  used = /* @__PURE__ */ new Set();
1093
1108
  constructor(e) {
@@ -1098,10 +1113,10 @@ var G = class {
1098
1113
  definition: n,
1099
1114
  indices: new Map(n.properties.map((e, t) => [e.name, t]))
1100
1115
  };
1101
- for (let r of W(n)) {
1116
+ for (let r of H(n)) {
1102
1117
  if (this.encoders.has(r)) throw Error(`Duplicate compressed entity definition for ${r}`);
1103
1118
  this.encoders.set(r, {
1104
- prefix: R(t++),
1119
+ prefix: I(t++),
1105
1120
  group: e
1106
1121
  });
1107
1122
  }
@@ -1129,25 +1144,25 @@ var G = class {
1129
1144
  if (r === "type" || i === void 0) continue;
1130
1145
  let t = e.group.indices.get(r);
1131
1146
  if (t === void 0) return;
1132
- let a = se(e.group.definition.properties[t], i);
1147
+ let a = z(e.group.definition.properties[t], i);
1133
1148
  if (a === void 0) return;
1134
1149
  n[t] = a;
1135
1150
  }
1136
1151
  let r = e.prefix;
1137
- for (let e = 0; e < n.length; e++) r += n[e] ?? P;
1152
+ for (let e = 0; e < n.length; e++) r += n[e] ?? M;
1138
1153
  return r;
1139
1154
  }
1140
1155
  };
1141
- function ce(e, t) {
1142
- return new G(t).compressAll(e);
1156
+ function he(e, t) {
1157
+ return new U(t).compressAll(e);
1143
1158
  }
1144
- var K = /* @__PURE__ */ new WeakMap();
1145
- function le(e) {
1146
- let t = K.get(e);
1159
+ var W = /* @__PURE__ */ new WeakMap();
1160
+ function ge(e) {
1161
+ let t = W.get(e);
1147
1162
  if (t) return t;
1148
1163
  t = /* @__PURE__ */ new Map();
1149
1164
  for (let [n, r] of Object.entries(e)) {
1150
- let e = W(r);
1165
+ let e = H(r);
1151
1166
  for (let i = 0; i < e.length; i++) {
1152
1167
  if (t.has(Number(n) + i)) throw Error(`Compressed entity definitions overlap at key ${Number(n) + i}`);
1153
1168
  t.set(Number(n) + i, {
@@ -1156,23 +1171,23 @@ function le(e) {
1156
1171
  });
1157
1172
  }
1158
1173
  }
1159
- return K.set(e, t), t;
1174
+ return W.set(e, t), t;
1160
1175
  }
1161
- function q(e, t) {
1176
+ function G(e, t) {
1162
1177
  let n = 0, r = () => {
1163
- if (e[n] === P) {
1178
+ if (e[n] === M) {
1164
1179
  n++;
1165
1180
  return;
1166
1181
  }
1167
1182
  let t = 0, r = 1;
1168
1183
  for (; n < e.length;) {
1169
- let i = e.charCodeAt(n++), a = i < 128 ? L[i] : -1;
1184
+ let i = e.charCodeAt(n++), a = i < 128 ? F[i] : -1;
1170
1185
  if (a < 0) throw Error(`Invalid compressed entity ${e}`);
1171
- if (a < N) return t + a * r;
1172
- t += (a - N) * r, r *= N;
1186
+ if (a < j) return t + a * r;
1187
+ t += (a - j) * r, r *= j;
1173
1188
  }
1174
1189
  throw Error(`Truncated compressed entity ${e}`);
1175
- }, i = r(), a = i === void 0 ? void 0 : le(t).get(i);
1190
+ }, i = r(), a = i === void 0 ? void 0 : ge(t).get(i);
1176
1191
  if (!a) throw Error(`No compressed entity definition for ${e}`);
1177
1192
  let o = { type: a.type };
1178
1193
  for (let t = 0; n < e.length; t++) {
@@ -1180,7 +1195,7 @@ function q(e, t) {
1180
1195
  if (!i) throw Error(`Compressed entity ${e} has more values than ${a.type} defines`);
1181
1196
  let s = r();
1182
1197
  if (s !== void 0) {
1183
- if (i.type !== "string") o[i.name] = U(i, s);
1198
+ if (i.type !== "string") o[i.name] = me(i, s);
1184
1199
  else if (s === 0) o[i.name] = null;
1185
1200
  else {
1186
1201
  if (n + s > e.length) throw Error(`Truncated compressed entity ${e}`);
@@ -1190,16 +1205,16 @@ function q(e, t) {
1190
1205
  }
1191
1206
  return o;
1192
1207
  }
1193
- function J(e, t) {
1194
- return e.map((e) => {
1195
- if (typeof e != "string") return e;
1196
- if (!t) throw Error("Compressed entities need entityDefinitions to load");
1197
- return q(e, t);
1198
- });
1208
+ function _e(e, t) {
1209
+ return e.map((e) => K(e, t));
1199
1210
  }
1200
- //#endregion
1201
- //#region src/scheduling/default-scheduler.ts
1202
- var Y = class {
1211
+ function K(e, t) {
1212
+ if (typeof e != "string") return e;
1213
+ if (!t) throw Error("Compressed entities need entityDefinitions to load");
1214
+ return G(e, t);
1215
+ }
1216
+ // src/scheduling/default-scheduler.ts
1217
+ var q = class {
1203
1218
  update(e, t) {
1204
1219
  let n = null;
1205
1220
  return e.systems.forEach((r) => {
@@ -1222,11 +1237,29 @@ var Y = class {
1222
1237
  });
1223
1238
  }), { lastSystemError: n };
1224
1239
  }
1225
- }, ue = v, X = 1e4, de = class extends S.default {
1240
+ }, ve = g, J = 1e4, ye = {
1241
+ entities: {
1242
+ start: 0,
1243
+ weight: .6
1244
+ },
1245
+ linking: {
1246
+ start: .6,
1247
+ weight: .1
1248
+ },
1249
+ systems: {
1250
+ start: .7,
1251
+ weight: .1
1252
+ },
1253
+ workers: {
1254
+ start: .8,
1255
+ weight: .2
1256
+ }
1257
+ }, Y = 256, be = class extends b.default {
1226
1258
  heap;
1227
1259
  constantStrings;
1228
1260
  eidCounter;
1229
1261
  registry;
1262
+ componentTriggers;
1230
1263
  factory;
1231
1264
  entities = /* @__PURE__ */ new Map();
1232
1265
  systems = [];
@@ -1238,6 +1271,8 @@ var Y = class {
1238
1271
  destroyed = !1;
1239
1272
  pristine = !0;
1240
1273
  isBulkLoading = !1;
1274
+ isLoading = !1;
1275
+ activeLoad;
1241
1276
  activeFreeBuffer = {
1242
1277
  frees: [],
1243
1278
  waitingSystems: /* @__PURE__ */ new Set(),
@@ -1250,19 +1285,19 @@ var Y = class {
1250
1285
  };
1251
1286
  clearing = !1;
1252
1287
  constructor(e, t = {}) {
1253
- super(), this.scheduler = t.scheduler ?? new Y(), this.heap = new te({ bufferSize: t.heapSize ?? ue }), this.constantStrings = new g(this.heap), this.eidCounter = this.heap.allocUI32(1), this.heap.addOnGrowBufferHandlers((e) => this.emit("grow-buffer", e));
1254
- let n = {
1288
+ super(), this.scheduler = t.scheduler ?? new q(), this.heap = new ae({ bufferSize: t.heapSize ?? ve }), this.constantStrings = new n(this.heap), this.eidCounter = this.heap.allocUI32(1), this.heap.addOnGrowBufferHandlers((e) => this.emit("grow-buffer", e));
1289
+ let r = {
1255
1290
  ...e,
1256
- entity: i
1257
- }, r = {};
1258
- for (let e of Object.keys(n)) {
1259
- let t = n[e];
1260
- r[e] = {
1291
+ entity: a
1292
+ }, i = {};
1293
+ for (let e of Object.keys(r)) {
1294
+ let t = r[e];
1295
+ i[e] = {
1261
1296
  ...t,
1262
- memoryComponent: new _(this.heap, t.type, t.size)
1297
+ memoryComponent: new m(this.heap, t.type, t.size)
1263
1298
  };
1264
1299
  }
1265
- this.registry = r, this.factory = t.factory ?? new M(), this.factory.setWorld(this);
1300
+ this.registry = i, this.componentTriggers = new pe(this.registry), this.factory = t.factory ?? new A(), this.factory.setWorld(this);
1266
1301
  }
1267
1302
  allocateEid() {
1268
1303
  return Atomics.add(this.eidCounter.data, 0, 1) + 1;
@@ -1279,14 +1314,11 @@ var Y = class {
1279
1314
  this.heap.buffers[e.bufferPosition] === void 0 && this.heap.addSharedBuffer(e), this.emit("grow-buffer", e);
1280
1315
  }
1281
1316
  get needsSpareBuffer() {
1282
- return this.systems.some((e) => e instanceof A && e.isWorkerThread && (!!e.options.createsEntities || !!e.options.addsComponents));
1317
+ return this.systems.some((e) => e instanceof O && e.isWorkerThread && (!!e.options.createsEntities || !!e.options.addsComponents));
1283
1318
  }
1284
1319
  async init() {
1285
1320
  await Promise.all(this.systems.map((e) => e.init()).filter((e) => e instanceof Promise));
1286
1321
  }
1287
- async finishLoadingSystems() {
1288
- await Promise.all(this.systems.map((e) => e.finishLoading()).filter((e) => e instanceof Promise));
1289
- }
1290
1322
  addEntity(e, t = !0) {
1291
1323
  return this.entities.set(e.eid, e), e.world = this, this.pristine = !1, e.on("component-added", (t) => {
1292
1324
  this.addEntityToEntityWorkerSystem(e, t);
@@ -1319,28 +1351,81 @@ var Y = class {
1319
1351
  throw r;
1320
1352
  }
1321
1353
  }
1322
- load(e) {
1323
- if (!this.pristine || this.scheduler.prepareEffects && this.systems.some((e) => e.isCurrentlyRunning())) {
1354
+ load(e, t = {}) {
1355
+ if (this.abortActiveLoad(), !this.pristine || this.scheduler.prepareEffects && this.systems.some((e) => e.isCurrentlyRunning())) {
1324
1356
  let e = this.systems.filter((e) => e.isCurrentlyRunning());
1325
1357
  for (let e of Array.from(this.entities.values())) this.removeEntity(e);
1326
1358
  this.systems.forEach((e) => e.clear()), this.scheduler.reset?.(this), this.consolidateFreeBuffersForReload(e);
1327
1359
  }
1328
1360
  for (let e of Object.keys(this.factory.configs)) this.constantStrings.getOrCreate(e);
1329
1361
  for (let e of Object.keys(this.factory.classes)) this.constantStrings.getOrCreate(e);
1362
+ this.isLoading = !0;
1363
+ let n = this.loadSteps(e);
1364
+ if (t.sliceMs === void 0) {
1365
+ let e;
1366
+ try {
1367
+ for (; !(e = n.next()).done;) t.onProgress?.(e.value);
1368
+ } finally {
1369
+ this.isLoading = !1;
1370
+ }
1371
+ return t.onEntitiesReady?.(), this.awaitWorkers(e.value, t.onProgress, t.signal);
1372
+ }
1373
+ let r = new AbortController();
1374
+ this.activeLoad = r;
1375
+ let i = t.signal ? AbortSignal.any([r.signal, t.signal]) : r.signal;
1376
+ return this.loadSliced(n, t.sliceMs, r, i, t);
1377
+ }
1378
+ async loadSliced(e, t, n, r, i) {
1379
+ let a = i.yieldTo ?? xe;
1380
+ try {
1381
+ r.throwIfAborted();
1382
+ let n = performance.now(), o = e.next();
1383
+ for (; !o.done;) i.onProgress?.(o.value), performance.now() - n >= t && (await a(), r.throwIfAborted(), n = performance.now()), o = e.next();
1384
+ this.isLoading = !1, i.onEntitiesReady?.(), await this.awaitWorkers(o.value, i.onProgress, r);
1385
+ } catch (e) {
1386
+ throw this.activeLoad === n && (this.activeLoad = void 0, this.isBulkLoading = !1, this.isLoading = !1), e;
1387
+ }
1388
+ this.activeLoad === n && (this.activeLoad = void 0);
1389
+ }
1390
+ *loadSteps(e) {
1391
+ let t = "entityDefinitions" in e ? e.entityDefinitions : void 0, n = e.entities, r = [];
1330
1392
  this.isBulkLoading = !0;
1331
1393
  try {
1332
- let t = ("entityDefinitions" in e ? J(e.entities, e.entityDefinitions) : e.entities).map((e) => this.loadEntity(e, !1));
1333
- for (let e of t) e.finishLoading(), this.emit("entity-added", e), e.on("death", () => {
1334
- this.onEntityDied(e);
1335
- });
1394
+ for (let e = 0; e < n.length; e++) r.push(this.loadEntity(K(n[e], t), !1)), (e + 1) % Y === 0 && (yield X("entities", e + 1, n.length));
1395
+ yield X("entities", n.length, n.length);
1396
+ for (let e = 0; e < r.length; e++) {
1397
+ let t = r[e];
1398
+ t.finishLoading(), this.emit("entity-added", t), t.on("death", () => {
1399
+ this.onEntityDied(t);
1400
+ }), (e + 1) % Y === 0 && (yield X("linking", e + 1, r.length));
1401
+ }
1402
+ yield X("linking", r.length, r.length);
1336
1403
  } finally {
1337
1404
  this.isBulkLoading = !1;
1338
1405
  }
1339
- let t = fe(this.entities.values());
1340
- return this.systems.forEach((e) => e.addEntities(t)), this.gameTime = e.gameTime ?? 0, this.playerTime = e.playerTime ?? 0, this.timeScale = e.timeScale ?? 1, this.finishLoadingSystems();
1406
+ let i = Ce(this.entities.values()), a = this.systems.slice(), o = a.length * 2;
1407
+ for (let e = 0; e < a.length; e++) a[e].addEntities(i), yield X("systems", e + 1, o);
1408
+ this.gameTime = e.gameTime ?? 0, this.playerTime = e.playerTime ?? 0, this.timeScale = e.timeScale ?? 1;
1409
+ let s = [];
1410
+ for (let e = 0; e < a.length; e++) {
1411
+ let t = a[e].finishLoading();
1412
+ t instanceof Promise && s.push(t), yield X("systems", a.length + e + 1, o);
1413
+ }
1414
+ return s;
1415
+ }
1416
+ async awaitWorkers(e, t, n) {
1417
+ let r = 0;
1418
+ t?.(X("workers", 0, e.length));
1419
+ let i = Promise.all(e.map(async (n) => {
1420
+ await n, t?.(X("workers", ++r, e.length));
1421
+ }));
1422
+ n ? await Promise.race([i, Se(n)]) : await i;
1423
+ }
1424
+ abortActiveLoad() {
1425
+ this.activeLoad && (this.activeLoad.abort(), this.activeLoad = void 0, this.isBulkLoading = !1, this.isLoading = !1);
1341
1426
  }
1342
1427
  async clear() {
1343
- if (!this.pristine || this.scheduler.beforeClear) {
1428
+ if (this.abortActiveLoad(), !this.pristine || this.scheduler.beforeClear) {
1344
1429
  this.clearing = !0;
1345
1430
  try {
1346
1431
  this.scheduler.beforeClear?.(this), await Promise.all(this.systems.map((e) => e.waitForRunToComplete()).filter((e) => e instanceof Promise));
@@ -1412,9 +1497,9 @@ var Y = class {
1412
1497
  }
1413
1498
  checkFreeBufferTimeout(e) {
1414
1499
  let t = this.activeFreeBuffer;
1415
- if (t.waitingSystems.size !== 0 && (t.waitElapsed += e, t.waitElapsed >= X)) {
1500
+ if (t.waitingSystems.size !== 0 && (t.waitElapsed += e, t.waitElapsed >= J)) {
1416
1501
  let e = Array.from(t.waitingSystems).map((e) => e.name).join(", ");
1417
- console.warn(`shared-memory-ecs: deferred component free waited over ${X}ms on system(s): ${e}; freeing anyway`), t.waitingSystems.clear(), this.processFreeBuffers();
1502
+ console.warn(`shared-memory-ecs: deferred component free waited over ${J}ms on system(s): ${e}; freeing anyway`), t.waitingSystems.clear(), this.processFreeBuffers();
1418
1503
  }
1419
1504
  }
1420
1505
  addSystem(e) {
@@ -1431,6 +1516,7 @@ var Y = class {
1431
1516
  }
1432
1517
  }
1433
1518
  update(e) {
1519
+ if (this.isLoading) return {};
1434
1520
  this.emit("update-started", e);
1435
1521
  let t = this.runUpdate(e);
1436
1522
  return this.emit("update-finished", e), t;
@@ -1462,12 +1548,12 @@ var Y = class {
1462
1548
  }
1463
1549
  addEntityToEntityWorkerSystem(e, t) {
1464
1550
  this.isBulkLoading || this.systems.forEach((n) => {
1465
- (n instanceof E && n.options.components?.includes(t) || n instanceof A && this.queriesReferenceComponent(n.options, t)) && n.checkAddEntity(e);
1551
+ (n instanceof w && n.options.components?.includes(t) || n instanceof O && this.queriesReferenceComponent(n.options, t)) && n.checkAddEntity(e);
1466
1552
  });
1467
1553
  }
1468
1554
  removeEntityFromEntityWorkerSystem(e, t) {
1469
1555
  this.isBulkLoading || this.systems.forEach((n) => {
1470
- n instanceof E && n.options.components?.includes(t) ? n.removeEntity(e) : n instanceof A && this.queriesReferenceComponent(n.options, t) && n.checkAddEntity(e);
1556
+ n instanceof w && n.options.components?.includes(t) ? n.removeEntity(e) : n instanceof O && this.queriesReferenceComponent(n.options, t) && n.checkAddEntity(e);
1471
1557
  });
1472
1558
  }
1473
1559
  queriesReferenceComponent(e, t) {
@@ -1475,12 +1561,30 @@ var Y = class {
1475
1561
  return n || r;
1476
1562
  }
1477
1563
  destroy() {
1478
- this.destroyed ||= (this.systems.forEach((e) => {
1564
+ this.destroyed ||= (this.abortActiveLoad(), this.systems.forEach((e) => {
1479
1565
  e.destroy();
1480
1566
  }), this.scheduler.destroy?.(this), !0);
1481
1567
  }
1482
1568
  };
1483
- function fe(e) {
1569
+ function X(e, t, n) {
1570
+ let { start: r, weight: i } = ye[e];
1571
+ return {
1572
+ phase: e,
1573
+ done: t,
1574
+ total: n,
1575
+ fraction: r + i * (n === 0 ? 1 : t / n)
1576
+ };
1577
+ }
1578
+ function xe() {
1579
+ let e = globalThis.scheduler;
1580
+ return e?.yield ? e.yield() : new Promise((e) => setTimeout(e, 0));
1581
+ }
1582
+ function Se(e) {
1583
+ return new Promise((t, n) => {
1584
+ e.aborted ? n(e.reason) : e.addEventListener("abort", () => n(e.reason), { once: !0 });
1585
+ });
1586
+ }
1587
+ function Ce(e) {
1484
1588
  let t = {
1485
1589
  entities: [],
1486
1590
  groupIndexes: [],
@@ -1492,9 +1596,8 @@ function fe(e) {
1492
1596
  }
1493
1597
  return t;
1494
1598
  }
1495
- //#endregion
1496
- //#region src/scheduling/conflict-scheduler.ts
1497
- var pe = class {
1599
+ // src/scheduling/conflict-scheduler.ts
1600
+ var we = class {
1498
1601
  compiled = Object.freeze({
1499
1602
  order: Object.freeze([]),
1500
1603
  batches: Object.freeze([])
@@ -1577,7 +1680,7 @@ var pe = class {
1577
1680
  }, 0);
1578
1681
  }
1579
1682
  isSliced(e) {
1580
- return e.system instanceof T && e.system.remainingInstancesToRun.length > 0;
1683
+ return e.system instanceof C && e.system.remainingInstancesToRun.length > 0;
1581
1684
  }
1582
1685
  reset() {
1583
1686
  this.continuationTimer !== void 0 && (clearTimeout(this.continuationTimer), this.continuationTimer = void 0);
@@ -1590,11 +1693,7 @@ var pe = class {
1590
1693
  prepareEffects(e, t) {
1591
1694
  let n = this.running.get(t), r = this.generation;
1592
1695
  return (e) => {
1593
- if (!n || r !== this.generation || !this.nodes.has(n)) {
1594
- e.discard();
1595
- return;
1596
- }
1597
- n.effects = e, this.publications.add(n), n.publicationDependencies === 0 && this.publicationReady.push(n), this.publish();
1696
+ r !== this.generation || n && !this.nodes.has(n) ? e.discard() : n ? (n.effects = e, this.publications.add(n), n.publicationDependencies === 0 && this.publicationReady.push(n), this.publish()) : e.apply();
1598
1697
  };
1599
1698
  }
1600
1699
  publish() {
@@ -1743,29 +1842,26 @@ var pe = class {
1743
1842
  return e.creates.size > 0 && this.observesCreation(e, t);
1744
1843
  }
1745
1844
  };
1746
- //#endregion
1747
- //#region src/entity-class.ts
1748
- function me(e, t) {
1845
+ // src/entity-class.ts
1846
+ function Te(e, t) {
1749
1847
  return t;
1750
1848
  }
1751
- function Z(e, t) {
1849
+ function Ee(e, t) {
1752
1850
  return t;
1753
1851
  }
1754
- //#endregion
1755
- //#region src/actions/kill-entity.ts
1756
- function he(e) {
1852
+ // src/actions/kill-entity.ts
1853
+ function De(e) {
1757
1854
  e.components.entity.dead = !0, e.emit("death");
1758
1855
  }
1759
- //#endregion
1760
- //#region src/performance-timing.ts
1761
- var ge = 1e3, Q = {
1856
+ // src/performance-timing.ts
1857
+ var Oe = 1e3, Z = {
1762
1858
  avg: 0,
1763
1859
  min: 0,
1764
1860
  max: 0,
1765
1861
  samples: 0
1766
1862
  };
1767
- function $(e) {
1768
- if (!e.length) return { ...Q };
1863
+ function Q(e) {
1864
+ if (!e.length) return { ...Z };
1769
1865
  let t = 0, n = Infinity, r = 0;
1770
1866
  for (let i of e) t += i, i < n && (n = i), i > r && (r = i);
1771
1867
  return {
@@ -1775,13 +1871,13 @@ function $(e) {
1775
1871
  samples: e.length
1776
1872
  };
1777
1873
  }
1778
- var _e = class extends S.default {
1874
+ var ke = class extends b.default {
1779
1875
  world;
1780
1876
  ticksBetweenUpdates;
1781
1877
  stats = {
1782
- update: { ...Q },
1878
+ update: { ...Z },
1783
1879
  systems: [],
1784
- events: { ...Q }
1880
+ events: { ...Z }
1785
1881
  };
1786
1882
  autoUpdate;
1787
1883
  ticks = 0;
@@ -1799,9 +1895,9 @@ var _e = class extends S.default {
1799
1895
  this.ticks = 0, this.updateTimes = [], this.systemTimings.forEach((e) => {
1800
1896
  e.run = [], e.events = [], e.eventStart = -1, e.pendingRun = 0, e.pendingEvents = 0;
1801
1897
  }), this.stats = {
1802
- update: { ...Q },
1898
+ update: { ...Z },
1803
1899
  systems: [],
1804
- events: { ...Q }
1900
+ events: { ...Z }
1805
1901
  };
1806
1902
  }
1807
1903
  destroy() {
@@ -1846,26 +1942,26 @@ var _e = class extends S.default {
1846
1942
  let t = this.systemTimings.get(e.name);
1847
1943
  return {
1848
1944
  name: e.name,
1849
- run: $(t?.run ?? []),
1850
- events: $(t?.events ?? [])
1945
+ run: Q(t?.run ?? []),
1946
+ events: Q(t?.events ?? [])
1851
1947
  };
1852
- }), t = { ...Q };
1948
+ }), t = { ...Z };
1853
1949
  return e.forEach((e) => {
1854
1950
  t.avg += e.events.avg, t.min += e.events.min, t.max += e.events.max, t.samples += e.events.samples;
1855
1951
  }), this.stats = {
1856
- update: $(this.updateTimes),
1952
+ update: Q(this.updateTimes),
1857
1953
  systems: e,
1858
1954
  events: t
1859
1955
  }, this.ticks = 0, this.updateTimes = [], this.systemTimings.forEach((e) => {
1860
1956
  e.run = [], e.events = [];
1861
1957
  }), this.emit("stats-updated", this.stats), this.stats;
1862
1958
  }
1863
- }, ve = class extends A {
1959
+ }, $ = class extends O {
1864
1960
  constructor(e, t) {
1865
1961
  super(e, {
1866
1962
  ...t,
1867
1963
  required: [],
1868
- updateFunction: u(t.updateFunction)
1964
+ updateFunction: d(t.updateFunction)
1869
1965
  });
1870
1966
  }
1871
1967
  get tracksMainQuery() {
@@ -1875,7 +1971,6 @@ var _e = class extends S.default {
1875
1971
  return !0;
1876
1972
  }
1877
1973
  };
1878
- //#endregion
1879
- export { j as BaseEntity, de as BaseWorld, n as CLASS_INDEX, f as Component, pe as ConflictScheduler, g as ConstantStringCache, c as DEAD_INDEX, ge as DEFAULT_TICKS_BETWEEN_UPDATES, Y as DefaultScheduler, G as EntityCompressor, M as EntityFactory, E as EntitySystem, O as EntitySystemWebWorker, A as EntityWorkerSystem, T as IterableSystem, _ as MemoryComponent, _e as PerformanceTiming, ee as STATIC_INDEX, C as System, r as TYPE_INDEX, D as WebWorker, ve as WorkerSystem, t as addComponentWorker, ce as compressEntities, p as createEntitySystemWorker, d as createEntityWorker, h as createSystemWorker, J as decompressEntities, q as decompressEntity, me as defineEntityClasses, Z as defineEntityConfigs, i as entityDefinition, he as killEntity, m as killEntityWorker, s as removeComponentWorker };
1974
+ export { k as BaseEntity, be as BaseWorld, r as CLASS_INDEX, p as Component, we as ConflictScheduler, n as ConstantStringCache, l as DEAD_INDEX, Oe as DEFAULT_TICKS_BETWEEN_UPDATES, q as DefaultScheduler, U as EntityCompressor, A as EntityFactory, w as EntitySystem, E as EntitySystemWebWorker, O as EntityWorkerSystem, C as IterableSystem, m as MemoryComponent, ke as PerformanceTiming, re as STATIC_INDEX, x as System, i as TYPE_INDEX, T as WebWorker, $ as WorkerSystem, t as addComponentWorker, he as compressEntities, ee as createEntitySystemWorker, f as createEntityWorker, ne as createSystemWorker, _e as decompressEntities, G as decompressEntity, Te as defineEntityClasses, Ee as defineEntityConfigs, a as entityDefinition, De as killEntity, te as killEntityWorker, c as removeComponentWorker };
1880
1975
 
1881
1976
  //# sourceMappingURL=index.js.map