Files
ecs/README.md
T
2026-11-11 11:50:17 -06:00

127 lines
15 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ecs
Entities, the components each has, and the systems that pass over them: a `world` keeping entities with the same set of components together, a column for each component, so a pass over those having some components is a walk along arrays, as fast as a loop over arrays of one's own. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), and reads only std.
```sakura
import malunal::ecs;
struct position { var x: f32; var y: f32; }
struct velocity { var x: f32; var y: f32; }
struct asleep {} # a tag: a component holding nothing
var w := world::new();
val ball := w.spawn_with(position{}, velocity{ x = 1 });
w.add::<asleep>(w.spawn_with(position{ x = 5 }));
# Each entity having what the function takes, `&T` to read, `&mut T` to write.
w.each(def(p: &mut position, v: &velocity) {
p.x += v.x;
p.y += v.y;
});
# A filter says what the function doesn't take.
w.query(without::<asleep>()).each(def(e: entity, p: &position) { ... });
# Chunks: a table's entities at once, each component a column, for loops of one's own.
for c in w.query(with::<position>().with::<velocity>()).chunks() {
val ps := c.write::<position>();
val vs := c.read::<velocity>();
for i in 0..c.length { ps[i].x += vs[i].x; }
}
# On every processor.
w.par_each(def(p: &mut position, v: &velocity) { p.x += v.x; });
if w.get::<position>(ball) is some(&mut p) { p.y = 10; }
w.set(ball, velocity{ y = -1 }); # replaces the one it has
_ = w.remove::<velocity>(ball);
# What changed of each entity since the query last passed.
var moved := w.query(changed::<position>());
moved.each(def(e: entity, p: &position) { ... });
# Run as an entity is given a component, or loses one.
_ = w.observe::<asleep>(change::added, def(at, e) { ... });
# Children, despawned with their parents.
val shadow := w.spawn_with(position{});
w.set_parent(shadow, ball);
_ = w.despawn(ball); # and `shadow`
```
`tests/ecs.sakura` drives all of it, and `tools/bench.sakura` times it.
A project reads it by requiring this folder, or its remote, and naming `malunal.ecs`, whose module is `malunal::ecs`, among a target's `deps`:
```yaml
requires:
- ../ecs
targets:
- name: game
type: program
deps: [malunal.ecs]
```
## Layout
| Path | Holds |
|---|---|
| `ecs/ecs.sakura` | `entity`, and `component_info`, what a world knows of a type of component |
| `ecs/world.sakura` | `world`: spawning and despawning, giving, replacing, taking, and getting components, deferring, `apply`, and resources |
| `ecs/table.sakura` | Tables: the entities having one set of components, a column of each component's values |
| `ecs/ticks.sakura` | When each entity was given a component, and its value last written, kept of the components queries ask of, and what a pass asks of each entity |
| `ecs/query.sakura` | Filters, by type and by path, queries, the parameters `each` reads, and chunks |
| `ecs/each.sakura` | The passes `each` and `par_each` make, one for each number of parameters a function takes, up to 8 |
| `ecs/observers.sakura` | `observe`: functions run as an entity is given a component, or loses one |
| `ecs/relations.sakura` | Parents and children: `child_of`, `children`, `set_parent`, and the rest |
| `ecs/workers.sakura` | The threads `par_each` calls functions on |
| `ecs/sharing.sakura` | A world shared by threads, each passing over it at once |
| `ecs/commands.sakura` | `commands`: changes to what entities have, and entities spawned, made later |
| `ecs/schedule.sakura` | `schedule`: systems run in order, each timed, and taken out by name |
| `ecs/keys.sakura` | Components and resources reached by their types' keys, and the key of a type's path |
| `ecs/serial.sakura` | How `std::serial` writes and reads an `entity`, and `entity_numbering`, the numbers a program writes entities as in data of its own |
| `ecs/idmap.sakura` | The table of numbers by 64-bit keys a world looks things up in |
## How it works
- **Tables**: a world keeps its entities in tables, one for each set of components an entity has had, its archetype, each component a column of values in the entities' order, and a tag, a component of no size, no column at all. Despawning an entity, or moving it to another table, moves the table's last entity into its place, so the rows stay side by side. An entity gaining or losing a component moves to the table having its new set, which each table remembers by the component, so the move is found once, and `spawn_with` moves an entity into the table of all its components at once, which it remembers by their types.
- **Components** are values of any type. What closes, as a `string`, is closed as its entity loses it, is despawned, or the world closes, and moved byte for byte between tables otherwise. Each type is known by a hash of its `path_of`, its name with the module of each type it names, made while compiling, the same in every program, so `game::position` and `ai::position` are two components.
- **`each`** calls a function for each entity having the components it takes. Its parameters say what it passes over: `&T` reads a component, and `&mut T` writes one, which the entity must have; `maybe<&T>` and `maybe<&mut T>` take one it may lack; and `entity` takes the entity; in any order, up to 8. Its lambda is written with its parameters' types.
- **Queries**: `w.query(filter)` is a pass over the entities a filter passes, by components they have, `with`, or lack, `without`, besides those its function takes. A program knowing a type only by its path names it so, as `with_path("game::player")`, `without_path`, and `changed_path`, as an engine reading what a system takes from its type's spelling does; no entity has a type the world hasn't met, and every one lacks it, until it's met. What a pass asks the world works out once and keeps, with the tables it matches, which it brings up to date as tables are made, so a pass walks straight to the columns.
- **What changed**: a filter's `changed::<T>()` passes the entities whose `T` was written since its query last passed, as a pass taking `&mut T`, a chunk's `write`, or `set`, writes them, or as they were given it; `added::<T>()` passes those given `T` since, spawned with it or given it as they lacked it, a tag as well as a value. A value written through `get` isn't known as written. A query remembers when it last passed, so a system keeps its query from one run to the next; a new one finds every entity changed and given. The world keeps when each entity was given a component, and its value last written, only once some query asks of it, so passes over the rest cost nothing more. Of those asked of, a pass writing them stamps each entity it passes, and a pass asking walks the tables written since, and of those, the entities. A chunk's `passes` says which of its entities do; `count` counts those that do, without moving the query on.
- **Deferring**: while a pass goes over the world, what would move an entity, a component given that it lacks or taken, a spawn, or a despawn, is kept, and made as the outermost pass ends, so the tables a pass walks stay as they are. A component an entity has already is replaced where it is, at once. `commands` keep changes the same way, for a program to `apply` when it's ready; a change to an entity despawned first is dropped, its value closed. Those a world makes, by `world::commands`, spawn entities too, by `spawn` and `spawn_with`, whose numbers are known at once, which the commands and the world give components, despawn, and make children till they're applied; applied, an entity is put in the table of the components the commands gave it at once, as `spawn_with` puts it.
- **Observers**: `observe::<T>(change::added, f)` runs `f`, given the world and the entity, each time an entity is given a `T` it lacked, once the value is there, and `change::removed` each time one loses it, as it's taken or the entity despawned, while the value still is, so `f` reads it. A component replaced, or written, runs none. What an observer changes that would move an entity is made once the change it observed is done, which runs observers in turn. Observers run on the world's thread: those of changes made while a pass or threads went over the world run as they're made. `unobserve` takes one out.
- **Parents and children**: `set_parent(child, parent)` makes an entity a child of another, giving it `child_of` and the parent's `children` it, in order, refusing to make an entity within itself; `remove_parent` takes it from its parent, and `parent_of` and `children_of` read them. Despawning an entity despawns each entity within it, the deepest first, and takes it from its parent's `children`; taking an entity's `children` leaves its children of the world itself. Where a pass goes over the world, a parent given or taken is made as it ends, and commands give and take them too.
- **`par_each`** calls its function from several threads at once: the world's, and workers, one for each processor more, started as it's first called and waiting until the world closes. The rows of the tables it matches are cut into pieces, several for each thread, which each takes in turn, so those finishing first take more; a pass of fewer than 4,096 entities stays on the world's thread. The function writes only what it's given; it may replace components an entity has, spawn, and defer what would move one, but not query or pass over the world itself, which fault. `world::threads` says how many threads it uses.
- **Sharing**: from `begin_sharing` to `end_sharing`, several threads pass over the world at once, as an engine runs systems reaching different components on threads of its own. Each passes by `each`, queries, and chunks, gets and replaces the components entities have, reads resources, and spawns, and what would move an entity is deferred, as within a pass, until the sharing ends. An entity spawned is alive once the sharing ends, and given components, despawned, and made a child till then. Threads may read a component at once, but one writing it must be the only thread reaching it, which the world leaves to its caller. While shared, the world can't meet types it hasn't, be given resources or observers or have them taken, or `apply` commands, which fault, and `par_each` calls its function on its own thread, as the sharing threads are the workers. A thread finding a query, or spawning, takes a lock, which no world not shared takes; a query first asking what changed of a component the world doesn't track yet asks of its tables alone till the sharing ends.
- **Resources** are values of a type a world holds one of, apart from any entity, as a clock: `set_resource`, `resource`, and `remove_resource`. A world closes them the last given first, so one made of another, as a renderer of the window it draws into, closes before it.
- **Schedules** run systems, functions of the world or types of one's own with an `invoke` taking it, in the order they were added, timing each, which `timings` tells; `remove` takes out those of a name.
- **Keys**: `get_by_key`, `has_by_key`, `set_by_info`, `remove_by_key`, `resource_by_key`, `set_resource_by_info`, and `entities_by_key` reach components and resources by their types' keys, `component_key::<T>()`, or `key_of_path` of a type's path, rather than their types, as an engine does for the scripts it runs, which declare types it doesn't: a key, and the bytes of a value, laid out as both sides build the type from one declaration. `component_info::plain` makes what a world knows of a type of plain data as the program runs, which must outlast every world meeting it.
- **Written and read**: an `entity` is `std::serial`'s to write and read, as a component naming one is. Its bits name it only in its own world while the program runs, so a program writing a world as data of its own, as a scene file, gives each entity a number there in an `entity_numbering`, and `apply` writes and reads every entity by it until what it gives closes: an entity as its number, or as nothing where it has none, as one despawned, and a number read as the entity it names, which must name one. With none applied, an entity is written as its bits. `entity::none` is nothing either way.
## Speed
`blossom run malunal.ecs.bench` over a million entities of two components, built with `-O2`, on a Ryzen 9 9950X3D of 16 cores and 32 threads, its passes each over 36 MB, which its 128 MB of L3 holds:
| What | Time for each entity |
|---|---|
| A loop over plain vectors | 0.78 ns |
| A loop over a query's chunks | 0.85 ns |
| `each`, given a type of one's own with an `invoke` | 0.90 ns |
| `each`, given a lambda | 2.0 ns |
| `each`, over 67 tables | 1.95 ns |
| `par_each`, on 32 threads | 0.29–0.37 ns |
| `spawn_with` of two components | 30–32 ns |
| `spawn_with` of two components by commands, recorded and applied | 84 ns |
| `get`, in the order they were spawned | 8 ns |
| `get`, in no order | 28–33 ns |
| `set` of a component the entity has | 16.5 ns |
| A move to another table, as a tag is added or removed | 52–54 ns |
| `despawn`, from 67 tables | 31–35 ns |
| `each` asking what changed, of a million, 10,000 written since | 0.5 ns |
`each` adds next to nothing to the loop it makes: given a type of its own, it's within a tenth of a nanosecond of chunks. A lambda costs a call through its address for each entity, about a nanosecond here, as Sakura calls a lambda given to generic code, where a type's `invoke` is inlined; a hot pass gives a type, or walks chunks. A pass this light is bound by memory, which `par_each`'s threads share, so heavier work gains more from them.
Knowing what changed of each entity costs nothing where no query asks: passes are as fast as they were without it, and spawning, moving, and despawning cost a few nanoseconds more than before observers and parents were the world's, for asking whether an entity has either, about 2 ns a spawn, 5 a move, and 6 a despawn. Of a component a query asks of, a pass writing it stamps each entity it passes, and moving an entity copies its ticks; a pass asking walks only the tables written since it last passed. Commands record each component's bytes and apply them as `spawn_with` would, the rest of their cost.
## Testing
`blossom test` runs `tests/ecs.sakura`: entities and their generations, components given, replaced, taken, and moved between tables, what closes closed once, passes of every kind of parameter, filters, by type and by path, deferring, chunks, what changed, passes on four threads, a world four threads share, each passing over it, finding queries it hadn't, and deferring changes, resources, closed the last given first, commands, schedules, components of one name in two modules, components reached by their types' keys, entities written and read by a numbering, what was written and given of each entity, by passes, `set`, moves, and chunks, observers, parents and children, given and taken, despawned together, by the world and by commands, entities spawned by two threads sharing a world, and by their commands, and what a query first asks while threads share a world. `sakurac run --checks` runs them with every read and write checked, and reports nothing left unreleased.
## Not yet
The tables a world no longer uses given back; observers of a component replaced; relationships besides parents and children; and saving a world whole, which each type's `key` was made for, and its entities' numbering is the start of.