@margoengine/ecs 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +294 -3
- package/dist/changes.d.ts +39 -0
- package/dist/changes.js +63 -0
- package/dist/coroutines.d.ts +82 -0
- package/dist/coroutines.js +97 -0
- package/dist/engine.d.ts +80 -0
- package/dist/engine.js +164 -0
- package/dist/growable.d.ts +23 -0
- package/dist/growable.js +28 -0
- package/dist/index.d.ts +145 -0
- package/dist/index.js +166 -0
- package/dist/objects.d.ts +30 -0
- package/dist/objects.js +50 -0
- package/dist/parallel-runtime.d.ts +43 -0
- package/dist/parallel.d.ts +102 -0
- package/dist/parallel.js +280 -0
- package/dist/parallel.worker.d.ts +1 -0
- package/dist/query.d.ts +42 -0
- package/dist/query.js +61 -0
- package/dist/reactive.d.ts +59 -0
- package/dist/reactive.js +106 -0
- package/dist/relation-query.d.ts +44 -0
- package/dist/relation-query.js +79 -0
- package/dist/relations.d.ts +70 -0
- package/dist/relations.js +93 -0
- package/dist/schedule.d.ts +82 -0
- package/dist/schedule.js +109 -0
- package/dist/scripts.d.ts +182 -0
- package/dist/scripts.js +278 -0
- package/dist/serialize-codec.d.ts +34 -0
- package/dist/serialize.d.ts +34 -0
- package/dist/serialize.js +355 -0
- package/dist/workers/parallel.js +1 -0
- package/package.json +107 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Scott Campbell
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,294 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @margoengine/ecs
|
|
2
|
+
|
|
3
|
+
Import `margoengine/ecs` from the `margoengine` package, or `@margoengine/ecs` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
+
|
|
5
|
+
A sparse-set ECS with packed Float32, Float64, Int32, Uint32 and Uint8 component fields.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {World} from 'margoengine/ecs';
|
|
9
|
+
const world = new World(1024);
|
|
10
|
+
const position = world.component({x: Float32Array, y: Float32Array});
|
|
11
|
+
const entity = world.create();
|
|
12
|
+
position.add(entity, {x: 10});
|
|
13
|
+
const results = new Uint32Array(world.capacity);
|
|
14
|
+
const count = world.query([position], results);
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Numeric entity IDs include a generation, so destroyed/reused slots reject stale handles. Removal swaps the last dense row into the removed row: call component.index(entity) before using a row index. Queries write into caller-owned storage and reject undersized output. Integer writes reject truncation and overflow. A `World` has a fixed capacity; a `GrowableWorld` grows. This is a sparse-set implementation, not a second archetype storage engine.
|
|
18
|
+
|
|
19
|
+
## Growable worlds
|
|
20
|
+
|
|
21
|
+
`GrowableWorld` (from `margoengine/ecs/growable`) doubles its slots when `create` runs out, so you do not have to guess a capacity. Everything else works as in a `World`.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import {GrowableWorld} from 'margoengine/ecs/growable';
|
|
25
|
+
const world = new GrowableWorld({capacity: 1024});
|
|
26
|
+
const position = world.component({x: Float32Array});
|
|
27
|
+
const {x} = position.fields;
|
|
28
|
+
const results = world.allocate(Uint32Array); // keeps up with the capacity
|
|
29
|
+
for (let i = 0; i < 5000; i++) position.add(world.create(), {x: i});
|
|
30
|
+
console.log(world.capacity, x.length); // 8192 8192
|
|
31
|
+
console.log(world.query([position], results)); // 5000
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
| `new GrowableWorld` option | Default | Meaning |
|
|
35
|
+
| --- | --- | --- |
|
|
36
|
+
| `capacity` | `1024` | Slots at the start |
|
|
37
|
+
| `limit` | `1000000` | Most slots it may grow to, at most 1,000,000; past it `create` throws `RangeError` |
|
|
38
|
+
|
|
39
|
+
Growing moves nothing: arrays sit on resizable buffers, so `component.fields`, arrays taken from them and ids all stay valid, and arrays only get longer. A `Uint32Array` you made yourself stays its size, so make query outputs with `world.allocate(Uint32Array)`. Ids are spaced by `limit`, and an id must fit 32 bits, so a slot retires after about 4,294,967,295 / `limit` reuses (4,294 at the default) and the world grows past it; lower `limit` for a world that churns entities hard. Resizable arrays cost speed: a loop over 100,000 rows took about twice as long as on a plain `World` (0.25 to 0.31 ms against 0.12 to 0.15, Node 26, busy machine, [ecs-growable.mjs](../../examples/package-benchmarks/ecs-growable.mjs)). When a bound is known, use a `World`.
|
|
40
|
+
|
|
41
|
+
## Query filters and tags
|
|
42
|
+
|
|
43
|
+
`world.query` intersects components. `Query` (from `margoengine/ecs`, or `margoengine/ecs/query` alone) adds `without` and `optional` terms, and `world.tag()` makes a component with no fields.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import {Query, World} from 'margoengine/ecs';
|
|
47
|
+
const world = new World(1024);
|
|
48
|
+
const position = world.component({x: Float32Array});
|
|
49
|
+
const health = world.component({value: Float32Array});
|
|
50
|
+
const frozen = world.tag();
|
|
51
|
+
const entity = world.create();
|
|
52
|
+
position.add(entity, {x: 1});
|
|
53
|
+
const stuck = world.create();
|
|
54
|
+
position.add(stuck, {x: 2});
|
|
55
|
+
frozen.add(stuck);
|
|
56
|
+
const moving = new Query(world, {with: [position], without: [frozen], optional: [health]});
|
|
57
|
+
moving.forEach((id, rows) => {
|
|
58
|
+
position.fields.x[rows[0]] += 1;
|
|
59
|
+
if (rows[1] >= 0) health.fields.value[rows[1]] -= 1; // -1: this entity has no health
|
|
60
|
+
});
|
|
61
|
+
const results = new Uint32Array(world.capacity);
|
|
62
|
+
console.log(moving.run(results), frozen.has(stuck)); // 1 true
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
| `new Query` term | Default | Meaning |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `with` | required | An entity must have all of these; at least one |
|
|
68
|
+
| `without` | none | An entity must have none of these |
|
|
69
|
+
| `optional` | none | Never changes the match; `forEach` gives its row, or -1 |
|
|
70
|
+
|
|
71
|
+
`run(output)` writes the ids into your array. `forEach(visit)` passes the `with` rows, then the `optional` rows, in one reused `Int32Array`. It takes the match list first and looks rows up just before each call, so `visit` can add, remove and destroy; entities that stop matching are passed over, and new matches wait for the next call. A `Query` cannot run inside its own `forEach`; use a second one to nest. Tags store no field data, only the 8 bytes per world slot every component uses for its entity index.
|
|
72
|
+
|
|
73
|
+
## Systems and scheduler
|
|
74
|
+
|
|
75
|
+
`Schedule` (from `margoengine/ecs`, or `margoengine/ecs/schedule` alone) runs named systems in a dependable order. Each `update(delta)` runs the fixed phase, then the frame phase. A `fixed: true` system runs once per step the elapsed time pays for, so physics stays deterministic at any frame rate. Everything else runs once per update.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import {Schedule, World} from 'margoengine/ecs';
|
|
79
|
+
const world = new World(1024);
|
|
80
|
+
const position = world.component({x: Float32Array});
|
|
81
|
+
const velocity = world.component({x: Float32Array});
|
|
82
|
+
const entity = world.create();
|
|
83
|
+
position.add(entity, {x: 0});
|
|
84
|
+
velocity.add(entity, {x: 2});
|
|
85
|
+
const moving = new Uint32Array(world.capacity);
|
|
86
|
+
let paused = false;
|
|
87
|
+
const schedule = new Schedule({step: 1 / 60});
|
|
88
|
+
schedule.add('move', (time) => {
|
|
89
|
+
const count = world.query([position, velocity], moving);
|
|
90
|
+
for (let i = 0; i < count; i++) {
|
|
91
|
+
const id = moving[i];
|
|
92
|
+
position.fields.x[position.index(id)] += velocity.fields.x[velocity.index(id)] * time.delta;
|
|
93
|
+
}
|
|
94
|
+
}, {fixed: true, when: () => !paused});
|
|
95
|
+
schedule.add('report', () => console.log(position.fields.x[position.index(entity)]), {after: ['move']});
|
|
96
|
+
schedule.update(1 / 30); // two fixed steps of move, then report once
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
| `new Schedule` option | Default | Meaning |
|
|
100
|
+
| --- | --- | --- |
|
|
101
|
+
| `step` | `1 / 60` | Seconds per fixed step |
|
|
102
|
+
| `maxSteps` | `8` | Most fixed steps in one update; the rest of a long stall is dropped and reported in `schedule.dropped` |
|
|
103
|
+
|
|
104
|
+
| `schedule.add` option | Default | Meaning |
|
|
105
|
+
| --- | --- | --- |
|
|
106
|
+
| `before`, `after` | none | Names of systems this one runs before or after, in the same phase; a frame system may also run `after` a fixed one |
|
|
107
|
+
| `when` | always | Run condition, asked before every run |
|
|
108
|
+
| `fixed` | `false` | Run in the fixed phase |
|
|
109
|
+
|
|
110
|
+
Systems receive `{delta, elapsed, tick, alpha, fixed}`: `delta` is the step in a fixed system and the frame time otherwise, `alpha` is the share of a step left in the accumulator, for blending the last two fixed states when drawing. The object is reused, so read it during the call. Order is `before` and `after`, then the order of `add`. `schedule.order()` lists the result. A missing name, a cycle, or a frame system ordered before a fixed one throws MargoError `'state'` from `order` or the next `update`. Systems are synchronous and run on the calling thread; a `Schedule` holds one step size, so use a second `Schedule` for a second rate.
|
|
111
|
+
|
|
112
|
+
## Script components
|
|
113
|
+
|
|
114
|
+
`Scripts` (from `margoengine/ecs/scripts`) puts behaviour on entities the way the script components of PlayCanvas and Needle do: a script type declares typed attributes and lifecycle hooks, and any number of instances attach to an entity. One registry belongs to one `World`; there are no globals. Hooks run with the instance as `this`, which carries `entity`, `world`, `attributes`, `state` (yours, kept across hot reload) and `enabled`.
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import {Schedule, World} from 'margoengine/ecs';
|
|
118
|
+
import {Scripts, defineScript} from 'margoengine/ecs/scripts';
|
|
119
|
+
const world = new World(64);
|
|
120
|
+
const errors: unknown[] = [];
|
|
121
|
+
const scripts = new Scripts(world, {onError: (error) => errors.push(error)});
|
|
122
|
+
const spin = defineScript({
|
|
123
|
+
name: 'spin',
|
|
124
|
+
attributes: {
|
|
125
|
+
speed: {type: 'number', default: 1, min: 0, max: 10},
|
|
126
|
+
axis: {type: 'vec3', default: [0, 1, 0]},
|
|
127
|
+
tint: {type: 'color', default: '#ff8800'},
|
|
128
|
+
},
|
|
129
|
+
initialize() { this.state.angle = 0; },
|
|
130
|
+
update(dt) { this.state.angle += this.attributes.speed * dt; },
|
|
131
|
+
onAttributeChange(name, value, previous) { console.log(name, previous, '->', value); },
|
|
132
|
+
});
|
|
133
|
+
scripts.register(spin);
|
|
134
|
+
const entity = world.create();
|
|
135
|
+
const instance = scripts.add(entity, spin, {values: {speed: 2}});
|
|
136
|
+
const schedule = new Schedule();
|
|
137
|
+
scripts.install(schedule); // frame system "scripts" and fixed system "scripts.fixed"
|
|
138
|
+
schedule.update(0.5);
|
|
139
|
+
instance.attributes.speed = 4; // validated; logs: speed 2 -> 4
|
|
140
|
+
console.log(instance.state.angle); // 1
|
|
141
|
+
// Hot reload: same instances, attribute values and state, no new initialize.
|
|
142
|
+
scripts.reload(defineScript({
|
|
143
|
+
name: 'spin',
|
|
144
|
+
attributes: {speed: {type: 'number', default: 1}, axis: {type: 'vec3'}},
|
|
145
|
+
update(dt) { this.state.angle += this.attributes.speed * dt * 2; },
|
|
146
|
+
swap(previous) { console.log('swapped from', previous.name); },
|
|
147
|
+
}));
|
|
148
|
+
schedule.update(0.5);
|
|
149
|
+
console.log(instance.state.angle, scripts.schema()[0].attributes.map((a) => a.name)); // 5 [ 'speed', 'axis' ]
|
|
150
|
+
scripts.dispose();
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
| Attribute `type` | Value | Options |
|
|
154
|
+
| --- | --- | --- |
|
|
155
|
+
| `number` | finite number, default 0 | `min`, `max` |
|
|
156
|
+
| `boolean`, `string` | default `false`, `''` | none |
|
|
157
|
+
| `enum` | one of `options`, default the first | `options` (required) |
|
|
158
|
+
| `vec2`, `vec3`, `vec4` | array of that many finite numbers, default zeros | `min`, `max` per element |
|
|
159
|
+
| `color` | `[r, g, b, a]` in 0..1, or `'#rgb'` / `'#rrggbb'`, default white | `min`, `max` (inside 0..1) |
|
|
160
|
+
| `entity`, `asset` | entity id or asset id string, default `null` | `assetKind` hint |
|
|
161
|
+
|
|
162
|
+
Every attribute also takes `default` and `title` (an inspector label). A bad default throws when the script is defined; a bad value throws `RangeError` naming the attribute when it is added or assigned. `scripts.schema()` returns every registered type's attributes as JSON-safe data for an inspector.
|
|
163
|
+
|
|
164
|
+
| Hook | When |
|
|
165
|
+
| --- | --- |
|
|
166
|
+
| `onEnable`, `initialize`, `postInitialize` | First `update`, `fixedUpdate` or `flush` after `add` while enabled: every `initialize` of the batch, then every `postInitialize` |
|
|
167
|
+
| `update(dt)`, `postUpdate(dt)` | Each `scripts.update(dt)`, every `update` before any `postUpdate`, ordered by `priority` then by `add` |
|
|
168
|
+
| `fixedUpdate(step)` | Each `scripts.fixedUpdate(step)` |
|
|
169
|
+
| `onEnable`, `onDisable` | `instance.enabled` changes; a disabled instance gets no update hooks |
|
|
170
|
+
| `onAttributeChange(name, value, previous)` | An attribute is assigned a different value after `initialize` |
|
|
171
|
+
| `destroy` | `scripts.remove`, `world.destroy(entity)` or dispose, after `onDisable` |
|
|
172
|
+
| `swap(previous)` | Hot reload, on the new type |
|
|
173
|
+
|
|
174
|
+
`scripts.reload(newType, {reinitialize})` swaps the implementation registered under that name. Instances stay with their attribute values (kept when the attribute still exists and is valid, else reset to the new default), `state`, enabled flag and order. `initialize` runs again only with `reinitialize: true`, after the old `onDisable` and `destroy`, with `state` cleared. An error thrown by a hook goes to `onError(error, {script, hook})` and the other scripts still run; without `onError` the pass finishes and throws one MargoError `'failed'` whose `cause` is the first error. `scripts.dispose()` (or `using`) destroys every instance.
|
|
175
|
+
|
|
176
|
+
Sources: the feature set follows the public documentation of PlayCanvas script components (attributes, initialize/postInitialize/update/postUpdate, enable/disable, swap for hot reload) and Needle Engine components; the code is written clean room from those feature names.
|
|
177
|
+
|
|
178
|
+
## Coroutines
|
|
179
|
+
|
|
180
|
+
`Coroutines` (from `@margoengine/ecs/coroutines`) runs multi-frame logic written as a generator, so a sequence reads top to bottom instead of as a state machine. `update(dt)` steps every running coroutine once; `install(schedule)` adds a frame system that does it. A bare `yield` waits one update, `yield 0.5` waits half a second, `yield promise` waits for a promise (a rejection is thrown into the generator at that `yield`), and `yield other` waits until another coroutine ends. `start(generator)` returns a `Coroutine` with `cancel()`, `active` and `done`; `run(generator)` is the async form and returns `done`, which resolves when the generator returns and rejects with an AbortError when it is cancelled. Cancelling runs the generator's `finally` blocks. Pass `{signal}` to cancel with an `AbortSignal`.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import {Schedule} from '@margoengine/ecs/schedule';
|
|
184
|
+
import {Coroutines} from '@margoengine/ecs/coroutines';
|
|
185
|
+
|
|
186
|
+
const coroutines = new Coroutines();
|
|
187
|
+
const schedule = new Schedule();
|
|
188
|
+
coroutines.install(schedule);
|
|
189
|
+
const log: string[] = [];
|
|
190
|
+
function* door() {
|
|
191
|
+
log.push('open');
|
|
192
|
+
yield 0.2; // seconds
|
|
193
|
+
log.push('close');
|
|
194
|
+
}
|
|
195
|
+
const sequence = coroutines.run(door());
|
|
196
|
+
for (let i = 0; i < 30; i++) schedule.update(1 / 60);
|
|
197
|
+
await sequence;
|
|
198
|
+
console.log(log); // ['open', 'close']
|
|
199
|
+
const blink = coroutines.start((function* () { while (true) yield; })());
|
|
200
|
+
blink.cancel(); // blink.done rejects with an AbortError
|
|
201
|
+
coroutines.dispose();
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
A coroutine that throws goes to `onError(error, coroutine)` when you pass it, otherwise `update` rethrows a MargoError `'failed'` with the first error as `cause` after stepping the others. `update` throws a RangeError for a negative or non-finite `dt`, and a coroutine that yields a negative number gets one thrown at its `yield`. A script can start coroutines from its hooks and cancel them in `destroy`. The pattern follows the coroutine runners of other engines' public docs; the stepping is plain generator protocol.
|
|
205
|
+
|
|
206
|
+
## Change detection
|
|
207
|
+
|
|
208
|
+
`ChangeTracker` (from `margoengine/ecs`, or `margoengine/ecs/changes` alone) answers which entities gained, changed or lost one component since its last `clear()`.
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import {ChangeTracker, World} from 'margoengine/ecs';
|
|
212
|
+
const world = new World(1024);
|
|
213
|
+
const health = world.component({value: Float32Array});
|
|
214
|
+
const tracker = new ChangeTracker(health);
|
|
215
|
+
const entity = world.create();
|
|
216
|
+
health.add(entity, {value: 100});
|
|
217
|
+
const results = new Uint32Array(world.capacity);
|
|
218
|
+
console.log(tracker.added(results)); // 1, results[0] is the entity
|
|
219
|
+
tracker.clear();
|
|
220
|
+
health.add(entity, {value: 90}); // seen
|
|
221
|
+
health.fields.value[health.index(entity)] = 80; // not seen by itself...
|
|
222
|
+
health.touch(entity); // ...until reported
|
|
223
|
+
console.log(tracker.changed(results)); // 1
|
|
224
|
+
tracker.clear();
|
|
225
|
+
world.destroy(entity);
|
|
226
|
+
console.log(tracker.removed(results)); // 1, results[0] is now a stale id
|
|
227
|
+
tracker.stop();
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
`fields` are plain typed arrays, so a direct write cannot be seen: call `component.touch(entity)` after one, or write through `component.add`. Results are net over the window: added then removed reports nothing, removed then added back is `changed`, added then written stays `added`. Each tracker keeps its own window, so systems can read at their own pace; call `clear()` when one is done, for example in a last system of a `Schedule`. `stop()`, or `using`, detaches a tracker. A tracker costs 24 bytes per world slot. To react at once instead of reading a window, push your own `{onAdd, onChange, onRemove}` onto `component.observers`; do not add or remove rows of that component from inside one.
|
|
231
|
+
|
|
232
|
+
## Relationships
|
|
233
|
+
|
|
234
|
+
`Relation` (from `margoengine/ecs`, or `margoengine/ecs/relations` alone) holds pairs of entities with a meaning you name. A pair goes from a source to a target and reads both ways.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import {Relation, World} from 'margoengine/ecs';
|
|
238
|
+
const world = new World(1024);
|
|
239
|
+
const childOf = new Relation(world, {exclusive: true, cascade: true, acyclic: true});
|
|
240
|
+
const owns = new Relation(world);
|
|
241
|
+
const ship = world.create();
|
|
242
|
+
const turret = world.create();
|
|
243
|
+
const barrel = world.create();
|
|
244
|
+
childOf.add(turret, ship);
|
|
245
|
+
childOf.add(barrel, turret);
|
|
246
|
+
owns.add(ship, barrel);
|
|
247
|
+
owns.add(ship, turret);
|
|
248
|
+
const results = new Uint32Array(world.capacity);
|
|
249
|
+
console.log(childOf.target(barrel) === turret); // true
|
|
250
|
+
console.log(childOf.sources(ship, results)); // 1: the children of ship
|
|
251
|
+
console.log(childOf.descendants(ship, results)); // 2: turret, then barrel
|
|
252
|
+
console.log(owns.targets(ship, results)); // 2
|
|
253
|
+
world.destroy(ship); // turret and barrel go with it; every pair ends
|
|
254
|
+
console.log(world.alive(barrel), owns.size); // false 0
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
| `new Relation` option | Default | Meaning |
|
|
258
|
+
| --- | --- | --- |
|
|
259
|
+
| `exclusive` | `false` | A source has at most one target; a new pair replaces the old one |
|
|
260
|
+
| `cascade` | `false` | Destroying a target destroys its sources, all the way down |
|
|
261
|
+
| `acyclic` | `false` | `add` throws `TypeError` for a pair that would close a loop |
|
|
262
|
+
|
|
263
|
+
`has`, `target`, `targets`, `sources`, `descendants` and `forEach` read pairs directly. Results go into your `Uint32Array`, oldest pair first, and `descendants` is breadth first, so parents come before children. Pairs of a destroyed entity always end. An `acyclic` add walks up from the target, so it costs the depth of the hierarchy. `stop()`, or `using`, ends all pairs and detaches from the world. Pairs live in Maps and Sets, not typed arrays: keep per-frame data in components.
|
|
264
|
+
|
|
265
|
+
## Engine bridge
|
|
266
|
+
|
|
267
|
+
`MeshBridge` (from `margoengine/ecs/engine`) copies a transform component to core meshes in one bulk step a frame, so systems work on packed arrays and never touch a mesh. It writes through `TransformWriter` from `@margoengine/scene/bulk`, an optional peer of this entry: `margoengine` includes it, and with the `@margoengine/*` packages install `@margoengine/scene` beside `@margoengine/ecs`.
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
import {createStage} from 'margoengine';
|
|
271
|
+
import {World} from 'margoengine/ecs';
|
|
272
|
+
import {MeshBridge, transformSchema} from 'margoengine/ecs/engine';
|
|
273
|
+
const stage = await createStage('#app');
|
|
274
|
+
const world = new World(1024);
|
|
275
|
+
const transform = world.component(transformSchema);
|
|
276
|
+
const bridge = new MeshBridge(transform, {disposeMeshes: true});
|
|
277
|
+
const entity = world.create();
|
|
278
|
+
bridge.link(entity, stage.box());
|
|
279
|
+
stage.onTick((delta) => {
|
|
280
|
+
transform.fields.x[transform.index(entity)] += delta;
|
|
281
|
+
bridge.sync();
|
|
282
|
+
});
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
| `new MeshBridge` option | Default | Meaning |
|
|
286
|
+
| --- | --- | --- |
|
|
287
|
+
| `disposeMeshes` | `false` | Dispose a linked mesh when its entity loses the component or is destroyed |
|
|
288
|
+
|
|
289
|
+
`transformSchema` is position `x y z`, quaternion `qx qy qz qw` and scale `sx sy sz`. A component may hold any of those three groups, whole; a mesh keeps its own values for a group the component lacks. `link(entity, mesh)` fills a new row from the mesh, so nothing jumps; a row made by hand needs `qw: 1` and a scale, or `sync` throws the mesh's RangeError. `sync()` takes one pass over the links to find what moved, then makes one `TransformWriter` write per changed group for each run of rows that changed, so a world where everything moves costs three writes and a world where nothing moves costs that pass alone. The checks and the result are those of the mesh's setters, `mesh.rotation` included, and a group the mesh already holds is left alone. The first `sync` after a link or unlink builds the writer again, about one pass over the links. A link ends with `unlink(entity)`, when the entity loses the component or is destroyed, or with `stop()`. A mesh disposed behind the bridge makes `sync` throw MargoError `'disposed'` rather than write to whichever mesh reuses its slot. Transforms are local to the mesh's parent; set hierarchies on the meshes with `setParent`.
|
|
290
|
+
|
|
291
|
+
Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
|
|
292
|
+
|
|
293
|
+
Build and unit tests: npm test --workspace @margoengine/ecs
|
|
294
|
+
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ComponentStore as Component } from './index.js';
|
|
2
|
+
/**
|
|
3
|
+
* What happened to one component since the last {@link ChangeTracker.clear}, as a net result: an entity added and
|
|
4
|
+
* removed again in the window is not reported at all, one removed and added back is `changed`, and one added and then
|
|
5
|
+
* written stays `added`. Each tracker has its own window, so two systems can read the same component at their own pace.
|
|
6
|
+
*
|
|
7
|
+
* Writes through `component.add` are seen; writes straight into `component.fields` are not until `component.touch`
|
|
8
|
+
* reports them.
|
|
9
|
+
*/
|
|
10
|
+
export declare class ChangeTracker {
|
|
11
|
+
readonly component: Component;
|
|
12
|
+
private readonly addedSet;
|
|
13
|
+
private readonly changedSet;
|
|
14
|
+
private readonly removedSet;
|
|
15
|
+
private readonly observer;
|
|
16
|
+
/** Start tracking `component`; changes before this call are not reported. */
|
|
17
|
+
constructor(component: Component);
|
|
18
|
+
/**
|
|
19
|
+
* Write the entities that gained the component into `output`, in no fixed order; returns how many.
|
|
20
|
+
* @throws RangeError when `output` is too small (`world.capacity` entries always fit).
|
|
21
|
+
*/
|
|
22
|
+
added(output: Uint32Array): number;
|
|
23
|
+
/**
|
|
24
|
+
* Write the entities whose row was written and that had the component before the window; returns how many.
|
|
25
|
+
* @throws RangeError when `output` is too small (`world.capacity` entries always fit).
|
|
26
|
+
*/
|
|
27
|
+
changed(output: Uint32Array): number;
|
|
28
|
+
/**
|
|
29
|
+
* Write the entities that lost the component, destroyed ones included (their ids are stale); returns how many.
|
|
30
|
+
* @throws RangeError when `output` is too small (`world.capacity` entries always fit).
|
|
31
|
+
*/
|
|
32
|
+
removed(output: Uint32Array): number;
|
|
33
|
+
/** Start a new window: forget everything reported so far. Costs one step per change held, not per entity. */
|
|
34
|
+
clear(): void;
|
|
35
|
+
/** Stop tracking. What the tracker holds can still be read. Safe to call twice. */
|
|
36
|
+
stop(): void;
|
|
37
|
+
/** `stop()`, for `using` (on runtimes that have `Symbol.dispose`). */
|
|
38
|
+
[Symbol.dispose]: () => void;
|
|
39
|
+
}
|
package/dist/changes.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
//#region src/changes.ts
|
|
2
|
+
var e = class {
|
|
3
|
+
constructor(e) {
|
|
4
|
+
this.size = 0, this.dense = e.allocate(Uint32Array), this.sparse = e.allocate(Int32Array, -1), this.stride = e.stride;
|
|
5
|
+
}
|
|
6
|
+
has(e) {
|
|
7
|
+
let t = this.sparse[e % this.stride];
|
|
8
|
+
return t >= 0 && this.dense[t] === e;
|
|
9
|
+
}
|
|
10
|
+
add(e) {
|
|
11
|
+
this.has(e) || (this.sparse[e % this.stride] = this.size, this.dense[this.size++] = e);
|
|
12
|
+
}
|
|
13
|
+
delete(e) {
|
|
14
|
+
if (!this.has(e)) return;
|
|
15
|
+
let t = e % this.stride, n = this.sparse[t], r = this.dense[--this.size];
|
|
16
|
+
this.sparse[t] = -1, n !== this.size && (this.dense[n] = r, this.sparse[r % this.stride] = n);
|
|
17
|
+
}
|
|
18
|
+
clear() {
|
|
19
|
+
for (let e = 0; e < this.size; e++) this.sparse[this.dense[e] % this.stride] = -1;
|
|
20
|
+
this.size = 0;
|
|
21
|
+
}
|
|
22
|
+
copy(e) {
|
|
23
|
+
if (e.length < this.size) throw RangeError("Change output is too small; pass a Uint32Array at least as long as the entity count (world.capacity always fits)");
|
|
24
|
+
return e.set(this.dense.subarray(0, this.size)), this.size;
|
|
25
|
+
}
|
|
26
|
+
}, t = class {
|
|
27
|
+
constructor(t) {
|
|
28
|
+
this.component = t;
|
|
29
|
+
let { world: n } = t, r = this.addedSet = new e(n), i = this.changedSet = new e(n), a = this.removedSet = new e(n);
|
|
30
|
+
this.observer = {
|
|
31
|
+
onAdd(e) {
|
|
32
|
+
a.has(e) ? (a.delete(e), i.add(e)) : r.add(e);
|
|
33
|
+
},
|
|
34
|
+
onChange(e) {
|
|
35
|
+
r.has(e) || i.add(e);
|
|
36
|
+
},
|
|
37
|
+
onRemove(e) {
|
|
38
|
+
r.has(e) ? r.delete(e) : (i.delete(e), a.add(e));
|
|
39
|
+
}
|
|
40
|
+
}, t.observers.push(this.observer);
|
|
41
|
+
}
|
|
42
|
+
added(e) {
|
|
43
|
+
return this.addedSet.copy(e);
|
|
44
|
+
}
|
|
45
|
+
changed(e) {
|
|
46
|
+
return this.changedSet.copy(e);
|
|
47
|
+
}
|
|
48
|
+
removed(e) {
|
|
49
|
+
return this.removedSet.copy(e);
|
|
50
|
+
}
|
|
51
|
+
clear() {
|
|
52
|
+
this.addedSet.clear(), this.changedSet.clear(), this.removedSet.clear();
|
|
53
|
+
}
|
|
54
|
+
stop() {
|
|
55
|
+
let { observers: e } = this.component, t = e.indexOf(this.observer);
|
|
56
|
+
t >= 0 && e.splice(t, 1);
|
|
57
|
+
}
|
|
58
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
59
|
+
this.stop();
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
//#endregion
|
|
63
|
+
export { t as ChangeTracker };
|