# Crash Course: entity-component system # Table of Contents * [Introduction](#introduction) * [Design decisions](#design-decisions) * [Type-less and bitset-free](#type-less-and-bitset-free) * [Build your own](#build-your-own) * [Pay per use](#pay-per-use) * [All or nothing](#all-or-nothing) * [Vademecum](#vademecum) * [The Registry, the Entity and the Component](#the-registry-the-entity-and-the-component) * [Observe changes](#observe-changes) * [Auto-binding](#auto-binding) * [Entity lifecycle](#entity-lifecycle) * [Listeners disconnection](#listeners-disconnection) * [They call me reactive storage](#they-call-me-reactive-storage) * [Sorting: is it possible?](#sorting-is-it-possible) * [Helpers](#helpers) * [Null entity](#null-entity) * [Tombstone](#tombstone) * [To entity](#to-entity) * [Dependencies](#dependencies) * [Invoke](#invoke) * [Connection helper](#connection-helper) * [Handle](#handle) * [Organizer](#organizer) * [Context variables](#context-variables) * [Aliased properties](#aliased-properties) * [Snapshot: complete vs continuous](#snapshot-complete-vs-continuous) * [Snapshot loader](#snapshot-loader) * [Continuous loader](#continuous-loader) * [Archives](#archives) * [One example to rule them all](#one-example-to-rule-them-all) * [Storage](#storage) * [Component traits](#component-traits) * [Empty type optimization](#empty-type-optimization) * [Void storage](#void-storage) * [Entity storage](#entity-storage) * [Reserved identifiers](#reserved-identifiers) * [One of a kind to the registry](#one-of-a-kind-to-the-registry) * [Pointer stability](#pointer-stability) * [In-place delete](#in-place-delete) * [Hierarchies and the like](#hierarchies-and-the-like) * [Meet the runtime](#meet-the-runtime) * [A base class to rule them all](#a-base-class-to-rule-them-all) * [Beam me up, registry](#beam-me-up-registry) * [Views and Groups](#views-and-groups) * [Views](#views) * [Create once, reuse many times](#create-once-reuse-many-times) * [Exclude-only](#exclude-only) * [View pack](#view-pack) * [Iteration order](#iteration-order) * [Runtime views](#runtime-views) * [Groups](#groups) * [Full-owning groups](#full-owning-groups) * [Partial-owning groups](#partial-owning-groups) * [Non-owning groups](#non-owning-groups) * [Types: const, non-const and all in between](#types-const-non-const-and-all-in-between) * [Give me everything](#give-me-everything) * [What is allowed and what is not](#what-is-allowed-and-what-is-not) * [More performance, more constraints](#more-performance-more-constraints) * [Multithreading](#multithreading) * [Iterators](#iterators) * [Const registry](#const-registry) * [Beyond this document](#beyond-this-document) # Introduction `EnTT` offers a header-only, tiny and easy to use entity-component system module written in modern C++.
The entity-component-system (also known as _ECS_) is an architectural pattern used mostly in game development. # Design decisions ## Type-less and bitset-free The library implements a sparse set based model that does not require users to specify the set of components neither at compile-time nor at runtime.
This is why users can instantiate the core class simply like: ```cpp entt::registry registry; ``` In place of its more annoying and error-prone counterpart: ```cpp entt::registry registry; ``` Furthermore, it is not necessary to announce the existence of a component type. When the time comes, just use it and that is all. ## Build your own The ECS module (as well as the rest of the library) is designed as a set of containers that are used as needed, just like a vector or any other container. It does not attempt in any way to take over on the user codebase, nor to control its main loop or process scheduling.
Unlike other more or less well known models, it also makes use of independent pools that are extended via _static mixins_. The built-in signal support is an example of this flexible design: defined as a mixin, it is easily disabled if not needed. Similarly, the storage class has a specialization that shows how everything is customizable down to the smallest detail. ## Pay per use Everything is designed around the principle that users only have to pay for what they want. When it comes to using an entity-component system, the tradeoff is usually between performance and memory usage. The faster it is, the more memory it uses. Even worse, some approaches tend to heavily affect other functionalities like the construction and destruction of components to favor iterations, even when it is not strictly required. In fact, slightly worse performance along non-critical paths are the right price to pay to reduce memory usage and have overall better performance.
`EnTT` follows a completely different approach. It gets the best out from the basic data structures and gives users the possibility to pay more for higher performance where needed. ## All or nothing As a rule of thumb, a `T **` pointer (or whatever a custom pool returns) is always available to directly access all the instances of a given component type `T`.
This is one of the corner stones of the library. Many of the tools offered are designed around this need and give the possibility to get this information. # Vademecum The `entt::entity` type implements the concept of _entity identifier_. An entity (the _E_ of an _ECS_) is an opaque element to use as-is. Inspecting it is not recommended since its format can change in future.
Components (the _C_ of an _ECS_) are of any type, without any constraints, not even that of being movable. No need to register them nor their types.
Systems (the _S_ of an _ECS_) are plain functions, functors, lambdas and so on. It is not required to announce them in any case and have no requirements. The next sections go into detail on how to use the entity-component system part of the `EnTT` library.
This module is likely larger than what is described below. For more details, please refer to the inline documentation. # The Registry, the Entity and the Component A registry stores and manages entities (or _identifiers_) and components.
The class template `basic_registry` lets users decide what the preferred type to represent an entity is. Because `std::uint32_t` is large enough for almost any case, there also exists the enum class `entt::entity` that _wraps_ it and the alias `entt::registry` for `entt::basic_registry`. Entities are represented by _entity identifiers_. An entity identifier contains information about the entity itself and its version.
User defined identifiers are allowed as enum classes and class types that define an `entity_type` member of type `std::uint32_t` or `std::uint64_t`. A registry is used both to construct and to destroy entities: ```cpp // constructs a naked entity with no components and returns its identifier auto entity = registry.create(); // destroys an entity and all its components registry.destroy(entity); ``` The `create` member function also accepts a hint. Moreover, it has an overload that gets two iterators to use to generate many entities at once efficiently. Similarly, the `destroy` member function also works with a range of entities: ```cpp // destroys all the entities in a range auto view = registry.view(); registry.destroy(view.begin(), view.end()); ``` In addition to offering an overload to force the version upon destruction.
This function removes all components from an entity before releasing it. There also exists a _lighter_ alternative that does not query component pools, for use with orphaned entities: ```cpp // releases an orphaned identifier registry.release(entity); ``` As with the `destroy` function, also in this case entity ranges are supported and it is possible to force a _version_. In both cases, when an identifier is released, the registry can freely reuse it internally. In particular, the version of an entity is increased (unless the overload that forces a version is used instead of the default one).
Users can then _test_ identifiers by means of a registry: ```cpp // returns true if the entity is still valid, false otherwise bool b = registry.valid(entity); // gets the actual version for the given entity auto curr = registry.current(entity); ``` Or _inspect_ them using some functions meant for parsing an identifier as-is, such as: ```cpp // gets the version contained in the entity identifier auto version = entt::to_version(entity); ``` Components are assigned to or removed from entities at any time.
The `emplace` member function template creates, initializes and assigns to an entity the given component. It accepts a variable number of arguments to use to construct the component itself: ```cpp registry.emplace(entity, 0., 0.); // ... auto &vel = registry.emplace(entity); vel.dx = 0.; vel.dy = 0.; ``` The default storage _detects_ aggregate types internally and exploits aggregate initialization when possible.
Therefore, it is not strictly necessary to define a constructor for each type. The `insert` member function works with _ranges_ and is used to: * Assign the same component to all entities at once when a type is specified as a template parameter or an instance is passed as an argument: ```cpp // default initialized type assigned by copy to all entities registry.insert(first, last); // user-defined instance assigned by copy to all entities registry.insert(from, to, position{0., 0.}); ``` * Assign a set of components to the entities when a range is provided (the length of the range of components **must** be the same of that of entities): ```cpp // first and last specify the range of entities, instances points to the first element of the range of components registry.insert(first, last, instances); ``` If an entity already has the given component, the `replace` and `patch` member function templates are used to update it: ```cpp // replaces the component in-place registry.patch(entity, [](auto &pos) { pos.x = pos.y = 0.; }); // constructs a new instance from a list of arguments and replaces the component registry.replace(entity, 0., 0.); ``` When it is unknown whether an entity already owns an instance of a component, `emplace_or_replace` is the function to use instead: ```cpp registry.emplace_or_replace(entity, 0., 0.); ``` This is a slightly faster alternative to the following snippet: ```cpp if(registry.all_of(entity)) { registry.replace(entity, 0., 0.); } else { registry.emplace(entity, 0., 0.); } ``` The `all_of` and `any_of` member functions may also be useful if in doubt about whether or not an entity has all the components in a set or any of them: ```cpp // true if entity has all the given components bool all = registry.all_of(entity); // true if entity has at least one of the given components bool any = registry.any_of(entity); ``` If the goal is to delete a component from an entity that owns it, the `erase` member function template is the way to go: ```cpp registry.erase(entity); ``` When in doubt whether the entity owns the component, use the `remove` member function instead. It behaves similarly to `erase` but it drops the component if and only if it exists, otherwise it returns safely to the caller: ```cpp registry.remove(entity); ``` The `clear` member function works similarly and is used to either: * Erases all instances of the given components from the entities that own them: ```cpp registry.clear(); ``` * Or destroy all entities in a registry at once: ```cpp registry.clear(); ``` Finally, references to components are obtained simply as: ```cpp const auto &cregistry = registry; // const and non-const reference const auto &crenderable = cregistry.get(entity); auto &renderable = registry.get(entity); // const and non-const references const auto [cpos, cvel] = cregistry.get(entity); auto [pos, vel] = registry.get(entity); ``` If the existence of the component is not certain, `try_get` is the more suitable function instead. ## Observe changes By default, each storage comes with a mixin that adds signal support to it.
This allows for fancy things like dependencies and reactive systems. The `on_construct` member function returns a _sink_ (which is an object for connecting and disconnecting listeners) for those interested in notifications when a new instance of a given component type is created: ```cpp // connects a free function registry.on_construct().connect<&my_free_function>(); // connects a member function registry.on_construct().connect<&my_class::member>(instance); // disconnects a free function registry.on_construct().disconnect<&my_free_function>(); // disconnects a member function registry.on_construct().disconnect<&my_class::member>(instance); ``` Similarly, `on_destroy` and `on_update` are used to receive notifications about the destruction and update of an instance, respectively.
Because of how C++ works, listeners attached to `on_update` are only invoked following a call to `replace`, `emplace_or_replace` or `patch`. Runtime pools are also supported by providing an identifier to the functions above: ```cpp registry.on_construct("other"_hs).connect<&my_free_function>(); ``` Refer to the following sections for more information about runtime pools.
In all cases, the function type of a listener is equivalent to the following: ```cpp void(entt::registry &, entt::entity); ``` All listeners are provided with the registry that triggered the notification and the involved entity. Note also that: * Listeners for construction signals are invoked **after** components have been created. * Listeners designed to observe changes are invoked **after** components have been updated. * Listeners for destruction signals are invoked **before** components have been destroyed. There are also some limitations on what a listener can and cannot do: * Connecting and disconnecting other functions from within the body of a listener should be avoided. It can lead to undefined behavior in some cases. * Removing the component from within the body of a listener that observes the construction or update of instances of a given type is not allowed. * Assigning and removing components from within the body of a listener that observes the destruction of instances of a given type should be avoided. It can lead to undefined behavior in some cases. This type of listeners is intended to provide users with an easy way to perform cleanup and nothing more. Please, refer to the documentation of the signal class to know about all the features it offers.
There are many useful but less known functionalities that are not described here, such as the connection objects or the possibility to attach listeners with a list of parameters that is shorter than that of the signal itself. ### Auto-binding Users don't need to create bindings manually each and every time. For managed types, they can have `EnTT` setup listeners automatically.
The library searches the types for functions with specific names and signatures, as in the following example: ```cpp struct my_type { static void on_construct(entt::registry ®istry, const entt::entity entt); static void on_update(entt::registry ®istry, const entt::entity entt); static void on_destroy(entt::registry ®istry, const entt::entity entt); // ... }; ``` As soon as a storage is created for such a defined type, these functions are associated with the respective signals. The function name is self-explanatory of the target signal. ### Entity lifecycle Observing entities is also possible. In this case, the user must use the entity type instead of the component type: ```cpp registry.on_construct().connect<&my_listener>(); ``` Since entity storage is unique within a registry, if a _name_ is provided it is ignored and therefore discarded.
As for the function signature, this is exactly the same as the components. Entities support all types of signals: construct, destroy, and update. The latter is perhaps ambiguous as an entity is not truly _updated_. Rather, its identifier is created and finally released.
Indeed, the update signal is meant to send _general notifications_ regarding an entity. It can be triggered via the `patch` function, as is the case with components: ```cpp registry.patch(entity); ``` Destroying an entity and then updating the version of an identifier **does not** give rise to these types of signals under any circumstances instead.
Finally, note that listeners that _observe_ the destruction of an entity are invoked **after** all components have been removed, not **before**. This is because the entity would be invalidated before deleting its elements otherwise, making it difficult for the user to write component listeners. ### Listeners disconnection The destruction order of the storage classes and therefore the disconnection of the listeners is completely random.
There are no guarantees today, and while the logic is easily discerned, it is not guaranteed that it will remain so in the future. For example, a listener getting disconnected after a component is discarded as a result of pool destruction is most likely a recipe for problems.
Rather, it is advisable to invoke the `clear` function of the registry before destroying it. This forces the deletion of all components and entities without ever discarding the pools.
As a result, a listener that wants to access components, entities, or pools can safely do so against a still valid registry, while checking for the existence of the various elements as appropriate. ## They call me reactive storage Signals are the basic tools to construct reactive systems, even if they are not enough on their own. `EnTT` tries to take another step in that direction with its _reactive mixin_.
In order to explain what reactive systems are, this is a slightly revised quote from the documentation of the library that first introduced this tool, [Entitas](https://github.com/sschmid/Entitas-CSharp): > Imagine you have 100 fighting units on the battlefield, but only 10 of them > changed their positions. Instead of using a normal system and updating all 100 > entities depending on the position, you can use a reactive system which will > only update the 10 changed units. So efficient. In `EnTT`, this means iterating over a reduced set of entities and components than what would otherwise be returned from a view or group.
On these words, however, the similarities with the proposal of `Entitas` also end. The rules of the language and the design of the library obviously impose and allow different things. A reactive mixin can be used on a standalone storage with any value type (perhaps using an alias to simplify its use): ```cpp using reactive_storage = entt::reactive_mixin>; entt::registry registry{}; reactive_storage storage{}; storage.bind(registry); ``` In this case, it must be provided with a reference registry for subsequent operations.
Alternatively, when using the value type provided by `EnTT`, it is also possible to create a reactive storage directly inside a registry: ```cpp entt::registry registry{}; auto &storage = registry.storage("observer"_hs); ``` In the latter case, there is the advantage that, in the event of destruction of an entity, this storage is also automatically cleaned up.
Also note that, unlike all other storage, these classes do not support signals by default (although they can be enabled if necessary). Once it has been created and associated with a registry, the reactive mixin needs to be informed about what it should _observe_.
Here the choice boils down to three main events affecting all elements (entities or components), namely creation, update or destruction: ```cpp storage // observe position component construction .on_construct() // observe velocity component update .on_update() // observe renderable component destruction .on_destroy(); ``` It goes without saying that it is possible to observe multiple events of the same type or of different types with the same storage.
For example, to know which entities have been assigned or updated a component of a certain type: ```cpp storage .on_construct() .on_update(); ``` Note that all configurations are in _or_ and never in _and_. Therefore, to track entities that have been assigned two different components, there are a couple of options: * Create two reactive storage, then combine them in a view: ```cpp first_storage.on_construct(); second_storage.on_construct(); for(auto entity: entt::basic_view{first_storage, second_storage}) { // ... } ``` * Use a reactive storage with a non-`void` value type and a custom tracking function for the purpose: ```cpp using my_reactive_storage = entt::reactive_mixin>; void callback(my_reactive_storage &storage, const entt::registry &, const entt::entity entity) { storage.contains(entity) ? (storage.get(entity) = true) : storage.emplace(entity, false); } // ... my_reactive_storage storage{}; storage .on_construct() .on_construct(); // ... for(auto [entity, both_were_added]: storage.each()) { if(both_were_added) { // ... } } ``` As highlighted in the last example, the reactive mixin tracks the entities that match the given conditions and saves them aside. However, this behavior can be changed.
For example, it is possible to _capture_ all and only the entities for which a certain component has been updated but only if a specific value is within a given range: ```cpp void callback(reactive_storage &storage, const entt::registry ®istry, const entt::entity entity) { storage.remove(entity); if(const auto x = registry.get(entity).x; x >= min_x && x <= max_x) { storage.emplace(entity); } } // ... storage.on_update(); ``` This makes reactive storage extremely flexible and usable in a large number of cases.
Finally, once the entities of interest have been collected, it is possible to _visit_ the storage like any other: ```cpp for(auto entity: storage) { // ... } ``` Wrapping it in a view and combining it with other views is another option: ```cpp for(auto [entity, pos]: (entt:.basic_view{storage} | registry.view(entt::exclude)).each()) { // ... } ``` In order to simplify this last use case, the reactive mixin also provides a specific function that returns a view of the storage already filtered according to the provided requirements: ```cpp for(auto [entity, pos]: storage.view(entt::exclude).each()) { // ... } ``` The registry used in this case is the one associated with the storage and also available via the `registry` function. It should be noted that a reactive storage never deletes its entities (and elements, if any). To process and then discard entities at regular intervals, refer to the `clear` function available by default for each storage type.
Similarly, the reactive mixin does not disconnect itself from observed storages upon destruction. Therefore, users have to do this themselves: ```cpp entt::registry = storage.registry(); registry.on_construct().disconnect(&storage); registry.on_construct().disconnect(&storage); ``` Destroying a reactive storage without disconnecting it from observed pools will result in undefined behavior. ## Sorting: is it possible? Sorting entities and components is possible using an in-place algorithm that does not require memory allocations and is therefore quite convenient.
There are two functions that respond to slightly different needs: * Components are sorted either directly: ```cpp registry.sort([](const renderable &lhs, const renderable &rhs) { return lhs.z < rhs.z; }); ``` Or by accessing their entities: ```cpp registry.sort([](const entt::entity lhs, const entt::entity rhs) { return entt::registry::entity(lhs) < entt::registry::entity(rhs); }); ``` There exists also the possibility to use a custom sort function object for when the usage pattern is known. * Components are sorted according to the order imposed by another component: ```cpp registry.sort(); ``` In this case, instances of `movement` are arranged in memory so that cache misses are minimized when the two components are iterated together. As a side note, the use of groups limits the possibility of sorting pools of components. Refer to the specific documentation for more details. ## Helpers The so-called _helpers_ are small classes and functions mainly designed to offer built-in support for the most basic functionalities. ### Null entity The `entt::null` variable models the concept of a _null entity_.
The library guarantees that the following expression always returns false: ```cpp registry.valid(entt::null); ``` A registry rejects the null entity in all cases because it is not considered valid. It also means that the null entity cannot own components.
The type of the null entity is internal and should not be used for any purpose other than defining the null entity itself. However, there exist implicit conversions from the null entity to identifiers of any allowed type: ```cpp entt::entity null = entt::null; ``` Similarly, the null entity compares to any other identifier: ```cpp const auto entity = registry.create(); const bool null = (entity == entt::null); ``` As for its integral form, the null entity only affects the entity part of an identifier and is instead completely transparent to its version. Be aware that `entt::null` and entity 0 are different. Likewise, a zero initialized entity is not the same as `entt::null`. Therefore, although `entt::entity{}` is in some sense an alias for entity 0, none of them are used to create a null entity. ### Tombstone Similar to the null entity, the `entt::tombstone` variable models the concept of a _tombstone_.
Once created, the integral form of the two values is the same, although they affect different parts of an identifier. In fact, the tombstone only uses the version part of it and is completely transparent to the entity part. Also in this case, the following expression always returns false: ```cpp registry.valid(entt::tombstone); ``` Moreover, users cannot set the tombstone version when releasing an entity: ```cpp registry.destroy(entity, entt::tombstone); ``` In this case, a different version number is implicitly generated.
The type of a tombstone is internal and can change at any time. However, there exist implicit conversions from a tombstone to identifiers of any allowed type: ```cpp entt::entity null = entt::tombstone; ``` Similarly, the tombstone compares to any other identifier: ```cpp const auto entity = registry.create(); const bool tombstone = (entity == entt::tombstone); ``` Be aware that `entt::tombstone` and entity 0 are different. Likewise, a zero initialized entity is not the same as `entt::tombstone`. Therefore, although `entt::entity{}` is in some sense an alias for entity 0, none of them are used to create tombstones. ### To entity This function accepts a storage and an instance of a component of the storage type, then it returns the entity associated with the latter: ```cpp const auto entity = entt::to_entity(registry.storage(), instance); ``` Where `instance` is a component of type `position`. A null entity is returned in case the instance does not belong to the registry. ### Dependencies The `registry` class is designed to create short circuits between its member functions. This greatly simplifies the definition of a _dependency_.
For example, the following adds (or replaces) the component `a_type` whenever `my_type` is assigned to an entity: ```cpp registry.on_construct().connect<&entt::registry::emplace_or_replace>(); ``` Similarly, the code below removes `a_type` from an entity whenever `my_type` is assigned to it: ```cpp registry.on_construct().connect<&entt::registry::remove>(); ``` A dependency is easily _broken_ as follows: ```cpp registry.on_construct().disconnect<&entt::registry::emplace_or_replace>(); ``` There are many other types of _dependencies_. In general, most of the functions that accept an entity as their first argument are good candidates for this purpose. ### Invoke The `invoke` helper allows to _propagate_ a signal to a member function of a component without having to _extend_ it: ```cpp registry.on_construct().connect>(); ``` All it does is pick up the _right_ component for the received entity and invoke the requested method, passing on the arguments if necessary. ### Connection helper Connecting signals can quickly become cumbersome.
This utility aims to simplify the process by grouping the calls: ```cpp entt::sigh_helper{registry} .with() .on_construct<&a_listener>() .on_destroy<&another_listener>() .with("other"_hs) .on_update(); ``` Runtime pools are also supported by providing an identifier when calling `with`, as shown in the previous snippet. Refer to the following sections for more information about runtime pools.
Obviously, this helper does not make the code disappear but it should at least reduce the boilerplate in the most complex cases. ### Handle A handle is a thin wrapper around an entity and a registry. It _replicates_ the API of a registry by offering functions such as `get` or `emplace`. The difference being that the entity is implicitly passed to the registry.
It is default constructible as an invalid handle that contains a null registry and a null entity. When it contains a null registry, calling functions that delegate execution to the registry causes undefined behavior. It is recommended to test for validity with its implicit cast to `bool` if in doubt.
A handle is also non-owning, meaning that it is freely copied and moved around without affecting its entity (in fact, handles happen to be trivially copyable). An implication of this is that mutability becomes part of the type. There are two aliases that use `entt::entity` as their default entity: `entt::handle` and `entt::const_handle`.
Users can also easily create their own aliases for custom identifiers as: ```cpp using my_handle = entt::basic_handle>; using my_const_handle = entt::basic_handle>; ``` Non-const handles are also implicitly convertible to const handles out of the box but not the other way around. This class is intended to simplify function signatures. In case of functions that take a registry and an entity and do most of their work on that entity, users might want to consider using handles, either const or non-const. ### Organizer The `organizer` class template offers support for creating an execution graph from a set of functions and their requirements on resources.
The resulting tasks are not executed in any case. This is not the goal of this tool. Instead, they are returned to the user in the form of a graph that allows for safe execution. All functions are added in order of execution to the organizer: ```cpp entt::organizer organizer; // adds a free function to the organizer organizer.emplace<&free_function>(); // adds a member function and an instance on which to invoke it to the organizer clazz instance; organizer.emplace<&clazz::member_function>(&instance); // adds a decayed lambda directly organizer.emplace(+[](const void *, entt::registry &) { /* ... */ }); ``` These are the parameters that a free function or a member function can accept: * A possibly constant reference to a registry. * An `entt::basic_view` with any possible combination of storage classes. * A possibly constant reference to any type `T` (that is, a context variable). The function type for free functions and decayed lambdas passed as parameters to `emplace` is `void(const void *, entt::registry &)` instead. The first parameter is an optional pointer to user defined data to provide upon registration: ```cpp clazz instance; organizer.emplace(+[](const void *, entt::registry &) { /* ... */ }, &instance); ``` In all cases, it is also possible to associate a name with the task when creating it. For example: ```cpp organizer.emplace<&free_function>("func"); ``` When a function is registered with the organizer, everything it accesses is considered a _resource_ (views are _unpacked_ and their types are treated as resources). The _constness_ of a type also dictates its access mode (RO/RW). In turn, this affects the resulting graph, since it influences the possibility of launching tasks in parallel.
As for the registry, if a function does not explicitly request it or requires a constant reference to it, it is considered a read-only access. Otherwise, it is considered as read-write access. All functions have the registry among their resources. When registering a function, users can also require resources that are not in the list of parameters of the function itself. These are declared as template parameters: ```cpp organizer.emplace<&free_function, position, velocity>("func"); ``` Similarly, users can override the access mode of a type again via template parameters: ```cpp organizer.emplace<&free_function, const renderable>("func"); ``` In this case, even if `renderable` appears among the parameters of the function as not constant, it is treated as constant as regards the generation of the task graph. To generate the task graph, the organizer offers the `graph` member function: ```cpp std::vector graph = organizer.graph(); ``` A graph is returned in the form of an adjacency list. Each vertex offers the following features: * `ro_count` and `rw_count`: the number of resources accessed in read-only or read-write mode. * `ro_dependency` and `rw_dependency`: type info objects associated with the parameters of the underlying function. * `top_level`: true if a node is a top level one (it has no entering edges), false otherwise. * `info`: type info object associated with the underlying function. * `name`: the name associated with the given vertex if any, a null pointer otherwise. * `callback`: a pointer to the function to execute and whose function type is `void(const void *, entt::registry &)`. * `data`: optional data to provide to the callback. * `children`: the vertices reachable from the given node, in the form of indices within the adjacency list. Since the creation of pools and resources within the registry is not necessarily thread safe, each vertex also offers a `prepare` function which is used to setup a registry for execution with the created graph: ```cpp auto graph = organizer.graph(); entt::registry registry; for(auto &&node: graph) { node.prepare(registry); } ``` The actual scheduling of the tasks is the responsibility of the user, who can use the preferred tool. ## Context variables Each registry has a _context_ associated with it, which is an `any` object map accessible by both type and _name_ for convenience. The _name_ is not really a name though. In fact, it is a numeric id of type `id_type` used as a key for the variable. Any value is accepted, even runtime ones.
The context is returned via the `ctx` functions and offers a minimal set of features including the following: ```cpp // creates a new context variable by type and returns it registry.ctx().emplace(42, 'c'); // creates a new named context variable by type and returns it registry.ctx().emplace_as("my_variable"_hs, 42, 'c'); // inserts or assigns a context variable by (deduced) type and returns it registry.ctx().insert_or_assign(my_type{42, 'c'}); // inserts or assigns a named context variable by (deduced) type and returns it registry.ctx().insert_or_assign("my_variable"_hs, my_type{42, 'c'}); // gets the context variable by type as a non-const reference from a non-const registry auto &var = registry.ctx().get(); // gets the context variable by name as a const reference from either a const or a non-const registry const auto &cvar = registry.ctx().get("my_variable"_hs); // resets the context variable by type registry.ctx().erase(); // resets the context variable associated with the given name registry.ctx().erase("my_variable"_hs); ``` A context variable must be both default constructible and movable. If the supplied type does not match that of the variable when using a _name_, the operation fails.
For all users who want to use the context but do not want to create elements, the `contains` and `find` functions are also available: ```cpp const bool contains = registry.ctx().contains(); const my_type *value = registry.ctx().find("my_variable"_hs); ``` Also in this case, both functions support constant types and accept a _name_ for the variable to look up, as does `at`. ### Aliased properties A context also supports creating _aliases_ for existing variables that are not directly managed by the registry. Const and therefore read-only variables are also accepted.
To do that, the type used upon construction must be a reference type and an lvalue is necessarily provided as an argument: ```cpp time clock; registry.ctx().emplace