# 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 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::(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::()).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::().with::()).chunks() { val ps := c.write::(); val vs := c.read::(); 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::(ball) is some(&mut p) { p.y = 10; } w.set(ball, velocity{ y = -1 }); # replaces the one it has _ = w.remove::(ball); _ = w.despawn(ball); ``` `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 `ecs` among a target's `deps`: ```yaml requires: - ../ecs targets: - name: game type: program deps: [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/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/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, 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::()` passes the tables whose `T` was written since its query last passed, as a pass taking `&mut T`, a chunk's `write`, or `set`, writes them: a table passes whole where any of its entities was 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 table changed, those entities moved into among them. - **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. - **`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, and defer what would move one, but not spawn, 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, and reads resources, and what would move an entity is deferred, as within a pass, until the sharing ends. 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 spawn, meet types it hasn't, be given resources 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 takes a lock, which no world not shared takes. - **Resources** are values of a type a world holds one of, apart from any entity, as a clock: `set_resource`, `resource`, and `remove_resource`. - **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::()`, 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 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 | 1.63 ns | | A loop over a query's chunks | 1.20 ns | | `each`, given a type of one's own with an `invoke` | 1.20 ns | | `each`, given a lambda | 1.95 ns | | `each`, over 67 tables | 1.95 ns | | `par_each`, on 32 threads | 0.28 ns | | `spawn_with` of two components | 27 ns | | `get`, in the order they were spawned | 5.9 ns | | `get`, in no order | 20 ns | | `set` of a component the entity has | 16 ns | | A move to another table, as a tag is added or removed | 50 ns | | `despawn` | 25 ns | `each` adds nothing to the loop it makes: given a type of its own, it's as fast as chunks. A lambda costs a call through its address for each entity, 0.75 ns 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. ## 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, commands, schedules, components of one name in two modules, components reached by their types' keys, and entities written and read by a numbering. `sakurac run --checks` runs them with every read and write checked, and reports nothing left unreleased. ## Not yet Relationships between entities, which a program keeps of its own, as hearth's scenes keep parents and children; hooks run as a component is given or taken; the tables a world no longer uses given back; what changed known of each entity rather than each table; spawning, by commands or while threads share a world; and saving a world whole, which each type's `key` was made for, and its entities' numbering is the start of.