diff --git a/README_8md_source.html b/README_8md_source.html
index 37914cd87..7d188c118 100644
--- a/README_8md_source.html
+++ b/README_8md_source.html
@@ -63,7 +63,7 @@ $(function() {
3 [](https://travis-ci.org/skypjack/entt)
4 [](https://ci.appveyor.com/project/skypjack/entt)
5 [](https://coveralls.io/github/skypjack/entt?branch=master)
6 [](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
10 * [Introduction](#introduction)
11 * [Build Instructions](#build-instructions)
12 * [Crash Course: entity-component system](#crash-course-entity-component-system)
13 * [Design choices](#design-choices)
14 * [A bitset-free entity-component system](#a-bitset-free-entity-component-system)
15 * [Pay per use](#pay-per-use)
16 * [Vademecum](#vademecum)
17 * [The Registry, the Entity and the Component](#the-registry-the-entity-and-the-component)
18 * [Single instance components](#single-instance-components)
19 * [Observe changes](#observe-changes)
20 * [Who let the tags out?](#who-let-the-tags-out)
21 * [Runtime components](#runtime-components)
22 * [A journey through a plugin](#a-journey-through-a-plugin)
23 * [Sorting: is it possible?](#sorting-is-it-possible)
24 * [Snapshot: complete vs continuous](#snapshot-complete-vs-continuous)
25 * [Snapshot loader](#snapshot-loader)
26 * [Continuous loader](#continuous-loader)
27 * [Archives](#archives)
28 * [One example to rule them all](#one-example-to-rule-them-all)
29 * [Prototype](#prototype)
31 * [Dependency function](#dependency-function)
32 * [Null entity](#null-entity)
33 * [View: to persist or not to persist?](#view-to-persist-or-not-to-persist)
34 * [Standard View](#standard-view)
35 * [Single component standard view](#single-component-standard-view)
36 * [Multi component standard view](#multi-component-standard-view)
37 * [Persistent View](#persistent-view)
38 * [Raw View](#raw-view)
39 * [Runtime View](#runtime-view)
40 * [Give me everything](#give-me-everything)
41 * [Iterations: what is allowed and what is not](#iterations-what-is-allowed-and-what-is-not)
42 * [Multithreading](#multithreading)
43 * [Crash Course: core functionalities](#crash-course-core-functionalities)
44 * [Compile-time identifiers](#compile-time-identifiers)
45 * [Runtime identifiers](#runtime-identifiers)
46 * [Hashed strings](#hashed-strings)
47 * [Monostate](#monostate)
48 * [Crash Course: service locator](#crash-course-service-locator)
49 * [Crash Course: cooperative scheduler](#crash-course-cooperative-scheduler)
50 * [The process](#the-process)
51 * [The scheduler](#the-scheduler)
52 * [Crash Course: resource management](#crash-course-resource-management)
53 * [The resource, the loader and the cache](#the-resource-the-loader-and-the-cache)
54 * [Crash Course: events, signals and everything in between](#crash-course-events-signals-and-everything-in-between)
56 * [Delegate](#delegate)
57 * [Event dispatcher](#event-dispatcher)
58 * [Event emitter](#event-emitter)
59 * [Packaging Tools](#packaging-tools)
60 * [EnTT in Action](#entt-in-action)
63 * [Donation](#donation)
68 `EnTT` is a header-only, tiny and easy to use framework written in modern
70 It was originally designed entirely around an architectural pattern called _ECS_
71 that is used mostly in game development. For further details:
73 * [Entity Systems Wiki](http://entity-systems.wikidot.com/)
74 * [Evolve Your Hierarchy](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/)
75 * [ECS on Wikipedia](https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system)
77 A long time ago, the sole entity-component system was part of the project. After
78 a while the codebase has grown and more and more classes have become part of the
80 That's why today it's called _the EnTT Framework_.
82 Currently, `EnTT` is tested on Linux, Microsoft Windows and OS X. It has proven
83 to work also on both Android and iOS.<br/>
84 Most likely it will not be problematic on other systems as well, but has not
85 been sufficiently tested so far.
89 `EnTT` was written initially as a faster alternative to other well known and
90 open source entity-component systems. Nowadays the `EnTT` framework is moving
91 its first steps. Much more will come in the future and hopefully I'm going to
92 work on it for a long time.<br/>
93 Requests for feature, PR, suggestions ad feedback are highly appreciated.
95 If you find you can help me and want to contribute to the `EnTT` framework with
96 your experience or you do want to get part of the project for some other
97 reasons, feel free to contact me directly (you can find the mail in the
98 [profile](https://github.com/skypjack)).<br/>
99 I can't promise that each and every contribution will be accepted, but I can
100 assure that I'll do my best to take them all seriously.
104 Here is a brief list of what it offers today:
106 * Statically generated integer identifiers for types (assigned either at
107 compile-time or at runtime).
108 * A constexpr utility for human readable resource identifiers.
109 * An incredibly fast entity-component system based on sparse sets, with its own
110 views and a _pay for what you use_ policy to adjust performance and memory
111 usage according to users' requirements.
112 * Actor class for those who aren't confident with entity-component systems.
113 * The smallest and most basic implementation of a service locator ever seen.
114 * A cooperative scheduler for processes of any type.
115 * All what is needed for resource management (cache, loaders, handles).
116 * Delegates, signal handlers (with built-in support for collectors) and a tiny
118 * A general purpose event emitter, that is a CRTP idiom based class template.
119 * An event dispatcher for immediate and delayed events to integrate in loops.
121 * Any other business.
123 Consider it a work in progress. For more details and an updated list, please
124 refer to the [online documentation](https://skypjack.github.io/entt/). It
125 probably contains much more. Moreover, the whole API is fully documented in-code
126 for those who are brave enough to read it.<br/>
127 Continue reading to know how the different parts of the project work or follow
128 the link above to take a look at the API reference.
133 #include <entt/entt.hpp>
146 void update(entt::DefaultRegistry ®istry) {
147 auto view = registry.view<Position, Velocity>();
149 for(auto entity: view) {
150 // gets only the components that are going to be used ...
152 auto &velocity = view.get<Velocity>(entity);
161 void update(std::uint64_t dt, entt::DefaultRegistry ®istry) {
162 registry.view<Position, Velocity>().each([dt](auto entity, auto &position, auto &velocity) {
163 // gets all the components of the view at once ...
165 position.x += velocity.dx * dt;
166 position.y += velocity.dy * dt;
173 entt::DefaultRegistry registry;
174 std::uint64_t dt = 16;
176 for(auto i = 0; i < 10; ++i) {
177 auto entity = registry.create();
178 registry.assign<Position>(entity, i * 1.f, i * 1.f);
179 if(i % 2 == 0) { registry.assign<Velocity>(entity, i * .1f, i * .1f); }
182 update(dt, registry);
191 I started working on `EnTT` because of the wrong reason: my goal was to design
192 an entity-component system that beated another well known open source solution
193 in terms of performance and used (possibly) less memory in the average
195 In the end, I did it, but it wasn't much satisfying. Actually it wasn't
196 satisfying at all. The fastest and nothing more, fairly little indeed. When I
197 realized it, I tried hard to keep intact the great performance of `EnTT` and to
198 add all the features I wanted to see in *my own library* at the same time.
200 Today `EnTT` is finally what I was looking for: still faster than its
201 _competitors_, lower memory usage in the average case, a really good API and an
202 amazing set of features. And even more, of course.
206 As it stands right now, `EnTT` is just fast enough for my requirements if
207 compared to my first choice (it was already amazingly fast actually).<br/>
208 Below is a comparison between the two (both of them compiled with GCC 7.3.0 on a
209 Dell XPS 13 out of the mid 2014):
211 | Benchmark | EntityX (compile-time) | EnTT |
212 |-----------|-------------|-------------|
213 | Create 1M entities | 0.0147s | **0.0046s** |
214 | Destroy 1M entities | 0.0053s | **0.0045s** |
215 | 1M entities, one component | 0.0012s | **1.9e-07s** |
216 | 1M entities, two components | 0.0012s | **3.8e-07s** |
217 | 1M entities, two components<br/>Half of the entities have all the components | 0.0009s | **3.8e-07s** |
218 | 1M entities, two components<br/>One of the entities has all the components | 0.0008s | **1.0e-06s** |
219 | 1M entities, five components | 0.0010s | **7.0e-07s** |
220 | 1M entities, ten components | 0.0011s | **1.2e-06s** |
221 | 1M entities, ten components<br/>Half of the entities have all the components | 0.0010s | **1.2e-06s** |
222 | 1M entities, ten components<br/>One of the entities has all the components | 0.0008s | **1.2e-06s** |
223 | Sort 150k entities, one component<br/>Arrays are in reverse order | - | **0.0036s** |
224 | Sort 150k entities, enforce permutation<br/>Arrays are in reverse order | - | **0.0005s** |
225 | Sort 150k entities, one component<br/>Arrays are almost sorted, std::sort | - | **0.0035s** |
226 | Sort 150k entities, one component<br/>Arrays are almost sorted, insertion sort | - | **0.0007s** |
228 Note: The default version of `EntityX` (`master` branch) wasn't added to the
229 comparison because it's already much slower than its compile-time counterpart.
231 Pretty interesting, aren't them? In fact, these benchmarks are the same used by
232 `EntityX` to show _how fast it is_. To be honest, they aren't so good and these
233 results shouldn't be taken much seriously (they are completely unrealistic
235 The proposed entity-component system is incredibly fast to iterate entities,
236 this is a fact. The compiler can make a lot of optimizations because of how
237 `EnTT` works, even more when components aren't used at all. This is exactly the
238 case for these benchmarks. On the other hand and if we consider real world
239 cases, `EnTT` is in the middle between a bit and much faster than the other
240 solutions around when users also access the components and not just the
241 entities, although it is not as fast as reported by these benchmarks.<br/>
242 This is why they are completely wrong and cannot be used to evaluate any of the
243 entity-component systems.
245 If you decide to use `EnTT`, choose it because of its API, features and
246 performance, not because there is a benchmark somewhere that makes it seem the
249 Probably I'll try to get out of `EnTT` more features and even better performance
250 in the future, mainly for fun.<br/>
251 If you want to contribute and/or have any suggestion, feel free to make a PR or
252 open an issue to discuss your idea.
258 To be able to use `EnTT`, users must provide a full-featured compiler that
259 supports at least C++14.<br/>
260 The requirements below are mandatory to compile the tests and to extract the
263 * CMake version 3.2 or later.
264 * Doxygen version 1.8 or later.
268 `EnTT` is a header-only library. This means that including the `entt.hpp`
269 header is enough to include the whole framework and use it. For those who are
270 interested only in the entity-component system, consider to include the sole
271 `entity/registry.hpp` header instead.<br/>
272 It's a matter of adding the following line to the top of a file:
275 #include <entt/entt.hpp>
278 Use the line below to include only the entity-component system instead:
281 #include <entt/entity/registry.hpp>
284 Then pass the proper `-I` argument to the compiler to add the `src` directory to
289 The documentation is based on [doxygen](http://www.stack.nl/~dimitri/doxygen/).
293 $ cmake .. -DBUILD_DOCS=ON
296 The API reference will be created in HTML format within the directory
297 `build/docs/html`. To navigate it with your favorite browser:
300 $ your_favorite_browser docs/html/index.html
302 The API reference is also available [online](https://skypjack.github.io/entt/)
303 for the latest version.
307 To compile and run the tests, `EnTT` requires *googletest*.<br/>
308 `cmake` will download and compile the library before compiling anything else.
309 In order to build without tests set CMake option `BUILD_TESTING=OFF`.
311 To build the most basic set of tests:
318 Note that benchmarks are not part of this set.
320 # Crash Course: entity-component system
324 ### A bitset-free entity-component system
326 `EnTT` is a _bitset-free_ entity-component system that doesn't require users to
327 specify the component set at compile-time.<br/>
328 This is why users can instantiate the core class simply like:
331 entt::DefaultRegistry registry;
334 In place of its more annoying and error-prone counterpart:
337 entt::DefaultRegistry<Comp0, Comp1, ..., CompN> registry;
342 `EnTT` is entirely designed around the principle that users have to pay only for
345 When it comes to using an entity-component system, the tradeoff is usually
346 between performance and memory usage. The faster it is, the more memory it uses.
347 However, slightly worse performance along non-critical paths are the right price
348 to pay to reduce memory usage and I've always wondered why this kind of tools do
349 not leave me the choice.<br/>
350 `EnTT` follows a completely different approach. It squeezes the best from the
351 basic data structures and gives users the possibility to pay more for higher
352 performance where needed.<br/>
353 The disadvantage of this approach is that users need to know the systems they
354 are working on and the tools they are using. Otherwise, the risk to ruin the
355 performance along critical paths is high.
357 So far, this choice has proven to be a good one and I really hope it can be for
358 many others besides me.
362 The `Registry` to store, the views to iterate. That's all.
364 An entity (the _E_ of an _ECS_) is an opaque identifier that users should just
365 use as-is and store around if needed. Do not try to inspect an entity
366 identifier, its format can change in future and a registry offers all the
367 functionalities to query them out-of-the-box. The underlying type of an entity
368 (either `std::uint16_t`, `std::uint32_t` or `std::uint64_t`) can be specified
369 when defining a registry (actually the `DefaultRegistry` is nothing more than a
370 `Registry` where the type of the entities is `std::uint32_t`).<br/>
371 Components (the _C_ of an _ECS_) should be plain old data structures or more
372 complex and movable data structures with a proper constructor. Actually, the
373 sole requirement of a component type is that it must be both move constructible
374 and move assignable. They are list initialized by using the parameters provided
375 to construct the component itself. No need to register components or their types
376 neither with the registry nor with the entity-component system at all.<br/>
377 Systems (the _S_ of an _ECS_) are just plain functions, functors, lambdas or
378 whatever users want. They can accept a `Registry` or a view of any type and use
379 them the way they prefer. No need to register systems or their types neither
380 with the registry nor with the entity-component system at all.
382 The following sections will explain in short how to use the entity-component
383 system, the core part of the whole framework.<br/>
384 In fact, the framework is composed of many other classes in addition to those
385 describe below. For more details, please refer to the inline documentation.
387 ## The Registry, the Entity and the Component
389 A registry can store and manage entities, as well as create views to iterate the
390 underlying data structures.<br/>
391 `Registry` is a class template that lets users decide what's the preferred type
392 to represent an entity. Because `std::uint32_t` is large enough for almost all
393 the cases, there exists also an alias named `DefaultRegistry` for
394 `Registry<std::uint32_t>`.
396 Entities are represented by _entity identifiers_. An entity identifier is an
397 opaque type that users should not inspect or modify in any way. It carries
398 information about the entity itself and its version.
400 A registry can be used both to construct and destroy entities:
403 // constructs a naked entity with no components and returns its identifier
404 auto entity = registry.create();
406 // destroys an entity and all its components
407 registry.destroy(entity);
410 Entities can also be destroyed _by type_, that is by specifying the types of the
411 tags or components that identify them:
414 // destroys the entity that owns the given tag, if any
415 registry.destroy<MyTag>(entt::tag_t{});
417 // destroys the entities that own the given components, if any
418 registry.destroy<AComponent, AnotherComponent>();
421 When an entity is destroyed, the registry can freely reuse it internally with a
422 slightly different identifier. In particular, the version of an entity is
423 increased each and every time it's discarded.<br/>
424 In case entity identifiers are stored around, the registry offers all the
425 functionalities required to test them and get out of the them all the
426 information they carry:
429 // returns true if the entity is still valid, false otherwise
430 bool b = registry.valid(entity);
432 // gets the version contained in the entity identifier
433 auto version = registry.version(entity);
435 // gets the actual version for the given entity
436 auto curr = registry.current(entity);
439 Components can be assigned to or removed from entities at any time with a few
440 calls to member functions of the registry. As for the entities, the registry
441 offers also a set of functionalities users can use to work with the components.
443 The `assign` member function template creates, initializes and assigns to an
444 entity the given component. It accepts a variable number of arguments to
445 construct the component itself if present:
448 registry.assign<Position>(entity, 0., 0.);
452 Velocity &velocity = registry.assign<Velocity>(entity);
457 If an entity already has the given component, the `replace` member function
458 template can be used to replace it:
461 registry.replace<Position>(entity, 0., 0.);
465 Velocity &velocity = registry.replace<Velocity>(entity);
470 In case users want to assign a component to an entity, but it's unknown whether
471 the entity already has it or not, `accommodate` does the work in a single call
472 (there is a performance penalty to pay for this mainly due to the fact that it
473 has to check if the entity already has the given component or not):
476 registry.accommodate<Position>(entity, 0., 0.);
480 Velocity &velocity = registry.accommodate<Velocity>(entity);
485 Note that `accommodate` is a slightly faster alternative for the following
486 `if/else` statement and nothing more:
489 if(registry.has<Comp>(entity)) {
490 registry.replace<Comp>(entity, arg1, argN);
492 registry.assign<Comp>(entity, arg1, argN);
496 As already shown, if in doubt about whether or not an entity has one or more
497 components, the `has` member function template may be useful:
500 bool b = registry.has<Position, Velocity>(entity);
503 On the other side, if the goal is to delete a single component, the `remove`
504 member function template is the way to go when it's certain that the entity owns
505 a copy of the component:
508 registry.remove<Position>(entity);
511 Otherwise consider to use the `reset` member function. It behaves similarly to
512 `remove` but with a strictly defined behavior (and a performance penalty is the
513 price to pay for this). In particular it removes the component if and only if it
514 exists, otherwise it returns safely to the caller:
517 registry.reset<Position>(entity);
520 There exist also two other _versions_ of the `reset` member function:
522 * If no entity is passed to it, `reset` will remove the given component from
523 each entity that has it:
526 registry.reset<Position>();
529 * If neither the entity nor the component are specified, all the entities still
530 in use and their components are destroyed:
536 Finally, references to components can be retrieved simply by doing this:
539 const auto &cregistry = registry;
541 // const and non-const reference
542 const Position &position = cregistry.get<Position>(entity);
543 Position &position = registry.get<Position>(entity);
545 // const and non-const references
546 std::tuple<const Position &, const Velocity &> tup = cregistry.get<Position, Velocity>(entity);
547 std::tuple<Position &, Velocity &> tup = registry.get<Position, Velocity>(entity);
550 The `get` member function template gives direct access to the component of an
551 entity stored in the underlying data structures of the registry.
553 ### Single instance components
555 In those cases where all what is needed is a single instance component, tags are
556 the right tool to achieve the purpose.<br/>
557 Tags undergo the same requirements of components. They can be either plain old
558 data structures or more complex and movable data structures with a proper
560 Actually, the same type can be used both as a tag and as a component and the
561 registry will not complain about it. It is up to users to properly manage their
562 own types. In some cases, the tag `tag_t` must also be used in order to
563 disambiguate overloads of member functions.
565 Attaching tags to entities and removing them is trivial:
568 auto player = registry.create();
569 auto camera = registry.create();
571 // attaches a default-initialized tag to an entity
572 registry.assign<PlayingCharacter>(entt::tag_t{}, player);
574 // attaches a tag to an entity and initializes it
575 registry.assign<Camera>(entt::tag_t{}, camera, player);
577 // removes tags from their owners
578 registry.remove<PlayingCharacter>();
579 registry.remove<Camera>();
582 In case a tag already has an owner, its content can be updated by means of the
583 `replace` member function template and the ownership of the tag can be
584 transferred to another entity using the `move` member function template:
587 // replaces the content of the given tag
588 Point &point = registry.replace<Point>(entt::tag_t{}, 1.f, 1.f);
590 // transfers the ownership of the tag to another entity
591 entity_type prev = registry.move<Point>(next);
594 If in doubt about whether or not a tag already has an owner, the `has` member
595 function template may be useful:
598 bool b = registry.has<PlayingCharacter>();
601 References to tags can be retrieved simply by doing this:
604 const auto &cregistry = registry;
606 // either a non-const reference ...
607 PlayingCharacter &player = registry.get<PlayingCharacter>();
609 // ... or a const one
610 const Camera &camera = cregistry.get<Camera>();
613 The `get` member function template gives direct access to the tag as stored in
614 the underlying data structures of the registry.
616 As shown above, in almost all the cases the entity identifier isn't required.
617 Since a single instance component can have only one associated entity, it
618 doesn't make much sense to mention it explicitly.<br/>
619 To find out who the owner is, just do the following:
622 auto player = registry.attachee<PlayingCharacter>();
625 Note that iterating tags isn't possible for obvious reasons. Tags give direct
626 access to single entities and nothing more.
630 Because of how the registry works internally, it stores a couple of signal
631 handlers for each pool in order to notify some of its data structures on the
632 construction and destruction of components.<br/>
633 These signal handlers are also exposed and made available to users. This is the
634 basic brick to build fancy things like dependencies and reactive systems.
636 To get a sink to be used to connect and disconnect listeners so as to be
637 notified on the creation of a component, use the `construction` member function:
640 // connects a free function
641 registry.construction<Position>().connect<&MyFreeFunction>();
643 // connects a member function
644 registry.construction<Position>().connect<MyClass, &MyClass::member>(&instance);
646 // disconnects a free function
647 registry.construction<Position>().disconnect<&MyFreeFunction>();
649 // disconnects a member function
650 registry.construction<Position>().disconnect<MyClass, &MyClass::member>(&instance);
653 To be notified when components are destroyed, use the `destruction` member
656 The function type of a listener is the same in both cases:
659 void(Registry<Entity> &, Entity);
662 In other terms, a listener is provided with the registry that triggered the
663 notification and the entity affected by the change. Note also that:
665 * Listeners are invoked **after** components have been assigned to entities.
666 * Listeners are invoked **before** components have been removed from entities.
667 * The order of invocation of the listeners isn't guaranteed in any case.
669 There are also some limitations on what a listener can and cannot do. In
672 * Connecting and disconnecting other functions from within the body of a
673 listener should be avoided. It can lead to undefined behavior in some cases.
674 * Assigning and removing components and tags from within the body of a listener
675 that observes the destruction of instances of a given type should be avoided.
676 It can lead to undefined behavior in some cases. This type of listeners is
677 intended to provide users with an easy way to perform cleanup and nothing
680 To a certain extent, these limitations do not apply. However, it is risky to try
681 to force them and users should respect the limitations unless they know exactly
682 what they are doing. Subtle bugs are the price to pay in case of errors
685 In general, events and therefore listeners must not be used as replacements for
686 systems. They should not contain much logic and interactions with a registry
687 should be kept to a minimum, if possible. Note also that the greater the number
688 of listeners, the greater the performance hit when components are created or
691 #### Who let the tags out?
693 As an extension, signals are also provided with tags. Although they are not
694 strictly required internally, it makes sense that a user expects signal support
695 even when it comes to tags actually.<br/>
696 Signals for tags undergo exactly the same requirements of those introduced for
697 components. Also the function type for a listener is the same and it's invoked
698 with the same guarantees discussed above.
700 To get the sinks for a tag just use tag `tag_t` to disambiguate overloads of
701 member functions as in the following example:
704 registry.construction<MyTag>(entt::tag_t{}).connect<&MyFreeFunction>();
705 registry.destruction<MyTag>(entt::tag_t{}).connect<MyClass, &MyClass::member>(&instance);
708 Listeners for tags and components are managed separately and do not influence
709 each other in any case. Therefore, note that the greater the number of listeners
710 for a type, the greater the performance hit when a tag of the given type is
711 created or destroyed.
713 ### Runtime components
715 Defining components at runtime is useful to support plugin systems and mods in
716 general. However, it seems impossible with a tool designed around a bunch of
717 templates. Indeed it's not that difficult.<br/>
718 Of course, some features cannot be easily exported into a runtime
719 environment. As an example, sorting a group of components defined at runtime
720 isn't for free if compared to most of the other operations. However, the basic
721 functionalities of an entity-component system such as `EnTT` fit the problem
722 perfectly and can also be used to manage runtime components if required.<br/>
723 All that is necessary to do it is to know the identifiers of the components. An
724 identifier is nothing more than a number or similar that can be used at runtime
725 to work with the type system.
727 In `EnTT`, identifiers are easily accessible:
730 entt::DefaultRegistry registry;
732 // standard component identifier
733 auto ctype = registry.component<Position>();
735 // single instance component identifier
736 auto ttype = registry.tag<PlayingCharacter>();
739 Once the identifiers are made available, almost everything becomes pretty
742 #### A journey through a plugin
744 `EnTT` comes with an example (actually a test) that shows how to integrate
745 compile-time and runtime components in a stack based JavaScript environment. It
746 uses [`Duktape`](https://github.com/svaarala/duktape) under the hood, mainly
747 because I wanted to learn how it works at the time I was writing the code.
749 The code is not production-ready and overall performance can be highly improved.
750 However, I sacrificed optimizations in favor of a more readable piece of code. I
751 hope I succeeded.<br/>
752 Note also that this isn't neither the only nor (probably) the best way to do it.
753 In fact, the right way depends on the scripting language and the problem one is
754 facing in general.<br/>
755 That being said, feel free to use it at your own risk.
757 The basic idea is that of creating a compile-time component aimed to map all the
758 runtime components assigned to an entity.<br/>
759 Identifiers come in use to address the right function from a map when invoked
760 from the runtime environment and to filter entities when iterating.<br/>
761 With a bit of gymnastic, one can narrow views and improve the performance to
762 some extent but it was not the goal of the example.
764 ### Sorting: is it possible?
766 It goes without saying that sorting entities and components is possible with
768 In fact, there are two functions that respond to slightly different needs:
770 * Components can be sorted directly:
773 registry.sort<Renderable>([](const auto &lhs, const auto &rhs) {
774 return lhs.z < rhs.z;
779 There exists also the possibility to use a custom sort function object, as
780 long as it adheres to the requirements described in the inline
782 This is possible mainly because users can get much more with a custom sort
783 function object if the pattern of usage is known. As an example, in case of an
784 almost sorted pool, quick sort could be much, much slower than insertion sort.
786 * Components can be sorted according to the order imposed by another component:
789 registry.sort<Movement, Physics>();
792 In this case, instances of `Movement` are arranged in memory so that cache
793 misses are minimized when the two components are iterated together.
795 ### Snapshot: complete vs continuous
797 The `Registry` class offers basic support to serialization.<br/>
798 It doesn't convert components and tags to bytes directly, there wasn't the need
799 of another tool for serialization out there. Instead, it accepts an opaque
800 object with a suitable interface (namely an _archive_) to serialize its internal
801 data structures and restore them later. The way types and instances are
802 converted to a bunch of bytes is completely in charge to the archive and thus to
805 The goal of the serialization part is to allow users to make both a dump of the
806 entire registry or a narrower snapshot, that is to select only the components
807 and the tags in which they are interested.<br/>
808 Intuitively, the use cases are different. As an example, the first approach is
809 suitable for local save/restore functionalities while the latter is suitable for
810 creating client-server applications and for transferring somehow parts of the
811 representation side to side.
813 To take a snapshot of the registry, use the `snapshot` member function. It
814 returns a temporary object properly initialized to _save_ the whole registry or
820 OutputArchive output;
825 .component<AComponent, AnotherComponent>(output)
829 It isn't necessary to invoke all these functions each and every time. What
830 functions to use in which case mostly depends on the goal and there is not a
831 golden rule to do that.
833 The `entities` member function asks the registry to serialize all the entities
834 that are still in use along with their versions. On the other side, the
835 `destroyed` member function tells to the registry to serialize the entities that
836 have been destroyed and are no longer in use.<br/>
837 These two functions can be used to save and restore the whole set of entities
838 with the versions they had during serialization.
840 The `component` member function is a function template the aim of which is to
841 store aside components. The presence of a template parameter list is a
842 consequence of a couple of design choices from the past and in the present:
844 * First of all, there is no reason to force a user to serialize all the
845 components at once and most of the times it isn't desiderable. As an example,
846 in case the stuff for the HUD in a game is put into the registry for some
847 reasons, its components can be freely discarded during a serialization step
848 because probably the software already knows how to reconstruct the HUD
849 correctly from scratch.
851 * Furthermore, the registry makes heavy use of _type-erasure_ techniques
852 internally and doesn't know at any time what types of components it contains.
853 Therefore being explicit at the call point is mandatory.
855 There exists also another version of the `component` member function that
856 accepts a range of entities to serialize. This version is a bit slower than the
857 other one, mainly because it iterates the range of entities more than once for
858 internal purposes. However, it can be used to filter out those entities that
859 shouldn't be serialized for some reasons.<br/>
863 const auto view = registry.view<Serialize>();
864 OutputArchive output;
867 .component<AComponent, AnotherComponent>(output, view.cbegin(), view.cend());
870 The `tag` member function is similar to the previous one, apart from the fact
871 that it works with tags and not with components.<br/>
872 Note also that both `component` and `tag` store items along with entities. It
873 means that they work properly without a call to the `entities` member function.
875 Once a snapshot is created, there exist mainly two _ways_ to load it: as a whole
876 and in a kind of _continuous mode_.<br/>
877 The following sections describe both loaders and archives in details.
881 A snapshot loader requires that the destination registry be empty and loads all
882 the data at once while keeping intact the identifiers that the entities
884 To do that, the registry offers a member function named `restore` that returns a
885 temporary object properly initialized to _restore_ a snapshot.
895 .component<AComponent, AnotherComponent>(input)
900 It isn't necessary to invoke all these functions each and every time. What
901 functions to use in which case mostly depends on the goal and there is not a
902 golden rule to do that. For obvious reasons, what is important is that the data
903 are restored in exactly the same order in which they were serialized.
905 The `entities` and `destroyed` member functions restore the sets of entities and
906 the versions that the entities originally had at the source.
908 The `component` member function restores all and only the components specified
909 and assigns them to the right entities. Note that the template parameter list
910 must be exactly the same used during the serialization. The same applies to the
911 `tag` member function.
913 The `orphans` member function literally destroys those entities that have
914 neither components nor tags. It's usually useless if the snapshot is a full dump
915 of the source. However, in case all the entities are serialized but only few
916 components and tags are saved, it could happen that some of the entities have
917 neither components nor tags once restored. The best users can do to deal with
918 them is to destroy those entities and thus update their versions.
920 #### Continuous loader
922 A continuous loader is designed to load data from a source registry to a
923 (possibly) non-empty destination. The loader can accommodate in a registry more
924 than one snapshot in a sort of _continuous loading_ that updates the
925 destination one step at a time.<br/>
926 Identifiers that entities originally had are not transferred to the target.
927 Instead, the loader maps remote identifiers to local ones while restoring a
928 snapshot. Because of that, this kind of loader offers a way to update
929 automatically identifiers that are part of components or tags (as an example, as
930 data members or gathered in a container).<br/>
931 Another difference with the snapshot loader is that the continuous loader does
932 not need to work with the private data structures of a registry. Furthermore, it
933 has an internal state that must persist over time. Therefore, there is no reason
934 to create it by means of a registry, or to limit its lifetime to that of a
940 entt::ContinuousLoader<entity_type> loader{registry};
943 loader.entities(input)
945 .component<AComponent, AnotherComponent, DirtyComponent>(input, &DirtyComponent::parent, &DirtyComponent::child)
946 .tag<MyTag, DirtyTag>(input, &DirtyTag::container)
951 It isn't necessary to invoke all these functions each and every time. What
952 functions to use in which case mostly depends on the goal and there is not a
953 golden rule to do that. For obvious reasons, what is important is that the data
954 are restored in exactly the same order in which they were serialized.
956 The `entities` and `destroyed` member functions restore groups of entities and
957 map each entity to a local counterpart when required. In other terms, for each
958 remote entity identifier not yet registered by the loader, the latter creates a
959 local identifier so that it can keep the local entity in sync with the remote
962 The `component` and `tag` member functions restore all and only the components
963 and the tags specified and assign them to the right entities.<br/>
964 In case the component or the tag contains entities itself (either as data
965 members of type `entity_type` or as containers of entities), the loader can
966 update them automatically. To do that, it's enough to specify the data members
967 to update as shown in the example.
969 The `orphans` member function literally destroys those entities that have
970 neither components nor tags after a restore. It has exactly the same purpose
971 described in the previous section and works the same way.
973 Finally, `shrink` helps to purge local entities that no longer have a remote
974 conterpart. Users should invoke this member function after restoring each
975 snapshot, unless they know exactly what they are doing.
979 Archives must publicly expose a predefined set of member functions. The API is
980 straightforward and consists only of a group of function call operators that
981 are invoked by the snapshot class and the loaders.
985 * An output archive, the one used when creating a snapshot, must expose a
986 function call operator with the following signature to store entities:
989 void operator()(Entity);
992 Where `Entity` is the type of the entities used by the registry. Note that all
993 the member functions of the snapshot class make also an initial call to this
994 endpoint to save the _size_ of the set they are going to store.<br/>
995 In addition, an archive must accept a pair of entity and either component or
996 tag for each type to be serialized. Therefore, given a type `T`, the archive
997 must contain a function call operator with the following signature:
1000 void operator()(Entity, const T &);
1003 The output archive can freely decide how to serialize the data. The register
1004 is not affected at all by the decision.
1006 * An input archive, the one used when restoring a snapshot, must expose a
1007 function call operator with the following signature to load entities:
1010 void operator()(Entity &);
1013 Where `Entity` is the type of the entities used by the registry. Each time the
1014 function is invoked, the archive must read the next element from the
1015 underlying storage and copy it in the given variable. Note that all the member
1016 functions of a loader class make also an initial call to this endpoint to read
1017 the _size_ of the set they are going to load.<br/>
1018 In addition, the archive must accept a pair of entity and either component or
1019 tag for each type to be restored. Therefore, given a type `T`, the archive
1020 must contain a function call operator with the following signature:
1023 void operator()(Entity &, T &);
1026 Every time such an operator is invoked, the archive must read the next
1027 elements from the underlying storage and copy them in the given variables.
1029 #### One example to rule them all
1031 `EnTT` comes with some examples (actually some tests) that show how to integrate
1032 a well known library for serialization as an archive. It uses
1033 [`Cereal C++`](https://uscilab.github.io/cereal/) under the hood, mainly
1034 because I wanted to learn how it works at the time I was writing the code.
1036 The code is not production-ready and it isn't neither the only nor (probably)
1037 the best way to do it. However, feel free to use it at your own risk.
1039 The basic idea is to store everything in a group of queues in memory, then bring
1040 everything back to the registry with different loaders.
1044 A prototype defines a type of an application in terms of its parts. They can be
1045 used to assign components to entities of a registry at once.<br/>
1046 Roughly speaking, in most cases prototypes can be considered just as templates
1047 to use to initialize entities according to _concepts_. In fact, users can create
1048 how many prototypes they want, each one initialized differently from the others.
1050 The following is an example of use of a prototype:
1053 entt::DefaultRegistry registry;
1054 entt::DefaultPrototype prototype{registry};
1056 prototype.set<Position>(100.f, 100.f);
1057 prototype.set<Velocity>(0.f, 0.f);
1061 const auto entity = prototype();
1064 To assign and remove components from a prototype, it offers two dedicated member
1065 functions named `set` and `unset`. The `has` member function can be used to know
1066 if a given prototype contains one or more components and the `get` member
1067 function can be used to retrieve the components.
1069 Creating an entity from a prototype is straightforward:
1071 * To create a new entity from scratch and assign it a prototype, this is the way
1074 const auto entity = prototype();
1076 It is equivalent to the following invokation:
1078 const auto entity = prototype.create();
1081 * In case we want to initialize an already existing entity, we can provide the
1082 `operator()` directly with the entity identifier:
1086 It is equivalent to the following invokation:
1088 prototype.assign(entity);
1090 Note that existing components aren't overwritten in this case. Only those
1091 components that the entity doesn't own yet are copied over. All the other
1092 components remain unchanged.
1094 * Finally, to assign or replace all the components for an entity, thus
1095 overwriting existing ones:
1097 prototype.accommodate(entity);
1100 In the examples above, the prototype uses its underlying registry to create
1101 entities and components both for its purposes and when it's cloned. To use a
1102 different repository to clone a prototype, all the member functions accept also
1103 a reference to a valid registry as a first argument.
1105 Prototypes are a very useful tool that can save a lot of typing sometimes.
1106 Furthermore, the codebase may be easier to maintain, since updating a prototype
1107 is much less error prone than jumping around in the codebase to update all the
1108 snippets copied and pasted around to initialize entities and components.
1112 The so called _helpers_ are small classes and functions mainly designed to offer
1113 built-in support for the most basic functionalities.<br/>
1114 The list of helpers will grow longer as time passes and new ideas come out.
1116 #### Dependency function
1118 A _dependency function_ is a predefined listener, actually a function template
1119 to use to automatically assign components to an entity when a type has a
1120 dependency on some other types.<br/>
1121 The following adds components `AType` and `AnotherType` whenever `MyType` is
1122 assigned to an entity:
1125 entt::dependency<AType, AnotherType>(registry.construction<MyType>());
1128 A component is assigned to an entity and thus default initialized only in case
1129 the entity itself hasn't it yet. It means that already existent components won't
1131 A dependency can easily be broken by means of the same function template:
1134 entt::dependency<AType, AnotherType>(entt::break_t{}, registry.construction<MyType>());
1139 In `EnTT`, there exists a sort of _null entity_ made available to users that is
1140 accessible via the `entt::null` variable.<br/>
1141 The framework guarantees that the following expression always returns false:
1144 registry.valid(entt::null);
1147 In other terms, a registry will reject the null entity in all cases because it
1148 isn't considered valid. It means that the null entity cannot own components or
1149 tags for obvious reasons.<br/>
1150 The type of the null entity is internal and should not be used for any purpose
1151 other than defining the null entity itself. However, there exist implicit
1152 conversions from the null entity to identifiers of any allowed type:
1155 typename entt::DefaultRegistry::entity_type null = entt::null;
1158 Similarly, the null entity can be compared to any other identifier:
1161 const auto entity = registry.create();
1162 const bool null = (entity == entt::null);
1165 ## View: to persist or not to persist?
1167 First of all, it is worth answering an obvious question: why views?<br/>
1168 Roughly speaking, they are a good tool to enforce single responsibility. A
1169 system that has access to a registry can create and destroy entities, as well as
1170 assign and remove components. On the other side, a system that has access to a
1171 view can only iterate entities and their components, then read or update the
1172 data members of the latter.<br/>
1173 It is a subtle difference that can help designing a better software sometimes.
1175 There are mainly four kinds of views: standard (also known as `View`),
1176 persistent (also known as `PersistentView`), raw (also known as `RawView`) and
1177 runtime (also known as `RuntimeView`).<br/>
1178 All of them have pros and cons to take in consideration. In particular:
1184 * They work out-of-the-box and don't require any dedicated data structure.
1185 * Creating and destroying them isn't expensive at all because they don't have
1186 any type of initialization.
1187 * They are the best tool for iterating entities for a single component.
1188 * They are the best tool for iterating entities for multiple components when
1189 one of the components is assigned to a significantly low number of entities.
1190 * They don't affect any other operations of the registry.
1194 * Their performance tend to degenerate when the number of components to
1195 iterate grows up and the most of the entities have all of them.
1201 * Once prepared, creating and destroying them isn't expensive at all because
1202 they don't have any type of initialization.
1203 * They are the best tool for iterating entities for multiple components when
1204 most entities have them all.
1208 * They have dedicated data structures and thus affect the memory usage to a
1210 * If not previously prepared, the first time they are used they go through an
1211 initialization step that could take a while.
1212 * They affect to a minimum the creation and destruction of entities and
1213 components. In other terms: the more persistent views there will be, the
1214 less performing will be creating and destroying entities and components.
1220 * They work out-of-the-box and don't require any dedicated data structure.
1221 * Creating and destroying them isn't expensive at all because they don't have
1222 any type of initialization.
1223 * They are the best tool for iterating components when it is not necessary to
1224 know which entities they belong to.
1225 * They don't affect any other operations of the registry.
1229 * They can be used to iterate only one type of component at a time.
1230 * They don't return the entity to which a component belongs to the caller.
1236 * Their lists of components are defined at runtime and not at compile-time.
1237 * Creating and destroying them isn't expensive at all because they don't have
1238 any type of initialization.
1239 * They are the best tool for things like plugin systems and mods in general.
1240 * They don't affect any other operations of the registry.
1244 * Their performances are definitely lower than those of all the other views,
1245 although they are still usable and sufficient for most of the purposes.
1247 To sum up and as a rule of thumb:
1249 * Use a raw view to iterate components only (no entities) for a given type.
1250 * Use a standard view to iterate entities and components for a single type.
1251 * Use a standard view to iterate entities and components for multiple types when
1252 the number of types is low. Standard views are really optimized and persistent
1253 views won't add much in this case.
1254 * Use a standard view to iterate entities and components for multiple types when
1255 a significantly low number of entities have one of the components.
1256 * Use a standard view in all those cases where a persistent view would give a
1257 boost to performance but the iteration isn't performed frequently.
1258 * Prepare and use a persistent view when you want to iterate only entities for
1259 multiple components.
1260 * Prepare and use a persistent view when you want to iterate entities for
1261 multiple components and each component is assigned to a great number of
1262 entities but the intersection between the sets of entities is small.
1263 * Prepare and use a persistent view in all the cases where a standard view
1264 wouldn't fit well otherwise.
1265 * Finally, in case you don't know at compile-time what are the components to
1266 use, choose a runtime view and set them during execution.
1268 To easily iterate entities and components, all the views offer the common
1269 `begin` and `end` member functions that allow users to use a view in a typical
1270 range-for loop. Almost all the views offer also a *more functional* `each`
1271 member function that accepts a callback for convenience.<br/>
1272 Continue reading for more details or refer to the inline documentation.
1276 A standard view behaves differently if it's constructed for a single component
1277 or if it has been requested to iterate multiple components. Even the API is
1278 different in the two cases.<br/>
1279 All that they share is the way they are created by means of a registry:
1282 // single component standard view
1283 auto single = registry.view<Position>();
1285 // multi component standard view
1286 auto multi = registry.view<Position, Velocity>();
1289 For all that remains, it's worth discussing them separately.<br/>
1291 #### Single component standard view
1293 Single component standard views are specialized in order to give a boost in
1294 terms of performance in all the situation. This kind of views can access the
1295 underlying data structures directly and avoid superfluous checks.<br/>
1296 They offer a bunch of functionalities to get the number of entities they are
1297 going to return and a raw access to the entity list as well as to the component
1298 list. It's also possible to ask a view if it contains a given entity.<br/>
1299 Refer to the inline documentation for all the details.
1301 There is no need to store views around for they are extremely cheap to
1302 construct, even though they can be copied without problems and reused freely. In
1303 fact, they return newly created and correctly initialized iterators whenever
1304 `begin` or `end` are invoked.<br/>
1305 To iterate a single component standard view, either use it in a range-for loop:
1308 auto view = registry.view<Renderable>();
1310 for(auto entity: view) {
1311 Renderable &renderable = view.get(entity);
1317 Or rely on the `each` member function to iterate entities and get all their
1321 registry.view<Renderable>().each([](auto entity, auto &renderable) {
1326 The `each` member function is highly optimized. Unless users want to iterate
1327 only entities, using `each` should be the preferred approach.
1329 **Note**: prefer the `get` member function of a view instead of the `get` member
1330 function template of a registry during iterations, if possible. However, keep in
1331 mind that it works only with the components of the view itself.
1333 #### Multi component standard view
1335 Multi component standard views iterate entities that have at least all the given
1336 components in their bags. During construction, these views look at the number of
1337 entities available for each component and pick up a reference to the smallest
1338 set of candidates in order to speed up iterations.<br/>
1339 They offer fewer functionalities than their companion views for single
1340 component. In particular, a multi component standard view exposes utility
1341 functions to get the estimated number of entities it is going to return and to
1342 know whether it's empty or not. It's also possible to ask a view if it contains
1343 a given entity.<br/>
1344 Refer to the inline documentation for all the details.
1346 There is no need to store views around for they are extremely cheap to
1347 construct, even though they can be copied without problems and reused freely. In
1348 fact, they return newly created and correctly initialized iterators whenever
1349 `begin` or `end` are invoked.<br/>
1350 To iterate a multi component standard view, either use it in a range-for loop:
1353 auto view = registry.view<Position, Velocity>();
1355 for(auto entity: view) {
1356 // a component at a time ...
1357 Position &position = view.get<Position>(entity);
1358 Velocity &velocity = view.get<Velocity>(entity);
1360 // ... or multiple components at once
1361 std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1367 Or rely on the `each` member function to iterate entities and get all their
1371 registry.view<Position, Velocity>().each([](auto entity, auto &position, auto &velocity) {
1376 The `each` member function is highly optimized. Unless users want to iterate
1377 only entities or get only some of the components, using `each` should be the
1380 **Note**: prefer the `get` member function of a view instead of the `get` member
1381 function template of a registry during iterations, if possible. However, keep in
1382 mind that it works only with the components of the view itself.
1386 A persistent view returns all the entities and only the entities that have at
1387 least the given components. Moreover, it's guaranteed that the entity list is
1388 tightly packed in memory for fast iterations.<br/>
1389 In general, persistent views don't stay true to the order of any set of
1390 components unless users explicitly sort them.
1392 Persistent views can be used only to iterate multiple components. To create this
1393 kind of views, the tag `persistent_t` must also be used in order to disambiguate
1394 overloads of the `view` member function:
1397 auto view = registry.view<Position, Velocity>(entt::persistent_t{});
1400 There is no need to store views around for they are extremely cheap to
1401 construct, even though they can be copied without problems and reused freely. In
1402 fact, they return newly created and correctly initialized iterators whenever
1403 `begin` or `end` are invoked.<br/>
1404 That being said, persistent views perform an initialization step the very first
1405 time they are constructed and this could be quite costly. To avoid it, consider
1406 asking to the registry to _prepare_ them when no entities have been created yet:
1409 registry.prepare<Position, Velocity>();
1412 If the registry is empty, preparation is extremely fast. Moreover the `prepare`
1413 member function template is idempotent. Feel free to invoke it even more than
1414 once: if the view has been already prepared before, the function returns
1415 immediately and does nothing.
1417 A persistent view offers a bunch of functionalities to get the number of
1418 entities it's going to return, a raw access to the entity list and the
1419 possibility to sort the underlying data structures according to the order of one
1420 of the components for which it has been constructed. It's also possible to ask a
1421 view if it contains a given entity.<br/>
1422 Refer to the inline documentation for all the details.
1424 To iterate a persistent view, either use it in a range-for loop:
1427 auto view = registry.view<Position, Velocity>(entt::persistent_t{});
1429 for(auto entity: view) {
1430 // a component at a time ...
1431 Position &position = view.get<Position>(entity);
1432 Velocity &velocity = view.get<Velocity>(entity);
1434 // ... or multiple components at once
1435 std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1441 Or rely on the `each` member function to iterate entities and get all their
1445 registry.view<Position, Velocity>(entt::persistent_t{}).each([](auto entity, auto &position, auto &velocity) {
1450 Performance are more or less the same. The best approach depends mainly on
1451 whether all the components have to be accessed or not.
1453 **Note**: prefer the `get` member function of a view instead of the `get` member
1454 function template of a registry during iterations, if possible. However, keep in
1455 mind that it works only with the components of the view itself.
1459 Raw views return all the components of a given type. This kind of views can
1460 access components directly and avoid extra indirections like when components are
1461 accessed via an entity identifier.<br/>
1462 They offer a bunch of functionalities to get the number of instances they are
1463 going to return and a raw access to the entity list as well as to the component
1465 Refer to the inline documentation for all the details.
1467 Raw views can be used only to iterate components for a single type. To create
1468 this kind of views, the tag `raw_t` must also be used in order to disambiguate
1469 overloads of the `view` member function:
1472 auto view = registry.view<Renderable>(entt::raw_t{});
1475 There is no need to store views around for they are extremely cheap to
1476 construct, even though they can be copied without problems and reused freely. In
1477 fact, they return newly created and correctly initialized iterators whenever
1478 `begin` or `end` are invoked.<br/>
1479 To iterate a raw view, use it in a range-for loop:
1482 auto view = registry.view<Renderable>(entt::raw_t{});
1484 for(auto &&component: raw) {
1489 Or rely on the `each` member function:
1492 registry.view<Renderable>(entt::raw_t{}).each([](auto &renderable) {
1497 Performance are exactly the same in both cases.
1499 **Note**: raw views don't have a `get` member function for obvious reasons.
1503 Runtime views iterate entities that have at least all the given components in
1504 their bags. During construction, these views look at the number of entities
1505 available for each component and pick up a reference to the smallest
1506 set of candidates in order to speed up iterations.<br/>
1507 They offer more or less the same functionalities of a multi component standard
1508 view. However, they don't expose a `get` member function and users should refer
1509 to the registry that generated the view to access components. In particular, a
1510 runtime view exposes utility functions to get the estimated number of entities
1511 it is going to return and to know whether it's empty or not. It's also possible
1512 to ask a view if it contains a given entity.<br/>
1513 Refer to the inline documentation for all the details.
1515 Runtime view are extremely cheap to construct and should not be stored around in
1516 any case. They should be used immediately after creation and then they should be
1517 thrown away. The reasons for this go far beyond the scope of this document.<br/>
1518 To iterate a runtime view, either use it in a range-for loop:
1521 using component_type = typename decltype(registry)::component_type;
1522 component_type types[] = { registry.type<Position>(), registry.type<Velocity>() };
1524 auto view = registry.view(std::cbegin(types), std::cend(types));
1526 for(auto entity: view) {
1527 // a component at a time ...
1528 Position &position = registry.get<Position>(entity);
1529 Velocity &velocity = registry.get<Velocity>(entity);
1531 // ... or multiple components at once
1532 std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1538 Or rely on the `each` member function to iterate entities:
1541 using component_type = typename decltype(registry)::component_type;
1542 component_type types[] = { registry.type<Position>(), registry.type<Velocity>() };
1544 auto view = registry.view(std::cbegin(types), std::cend(types)).each([](auto entity) {
1549 Performance are exactly the same in both cases.
1551 **Note**: runtime views are meant for all those cases where users don't know at
1552 compile-time what components to use to iterate entities. This is particularly
1553 well suited to plugin systems and mods in general. Where possible, don't use
1554 runtime views, as their performance are slightly inferior to those of the other
1558 ### Give me everything
1560 Views are narrow windows on the entire list of entities. They work by filtering
1561 entities according to their components.<br/>
1562 In some cases there may be the need to iterate all the entities still in use
1563 regardless of their components. The registry offers a specific member function
1567 registry.each([](auto entity) {
1572 It returns to the caller all the entities that are still in use by means of the
1573 given function.<br/>
1574 As a rule of thumb, consider using a view if the goal is to iterate entities
1575 that have a determinate set of components. A view is usually much faster than
1576 combining this function with a bunch of custom tests.<br/>
1577 In all the other cases, this is the way to go.
1579 There exists also another member function to use to retrieve orphans. An orphan
1580 is an entity that is still in use and has neither assigned components nor
1582 The signature of the function is the same of `each`:
1585 registry.orphans([](auto entity) {
1590 To test the _orphanity_ of a single entity, use the member function `orphan`
1591 instead. It accepts a valid entity identifer as an argument and returns true in
1592 case the entity is an orphan, false otherwise.
1594 In general, all these functions can result in poor performance.<br/>
1595 `each` is fairly slow because of some checks it performs on each and every
1596 entity. For similar reasons, `orphans` can be even slower. Both functions should
1597 not be used frequently to avoid the risk of a performance hit.
1599 ## Iterations: what is allowed and what is not
1601 Most of the _ECS_ available out there have some annoying limitations (at least
1602 from my point of view): entities and components cannot be created nor destroyed
1603 during iterations.<br/>
1604 `EnTT` partially solves the problem with a few limitations:
1606 * Creating entities and components is allowed during iterations.
1607 * Deleting an entity or removing its components is allowed during iterations if
1608 it's the one currently returned by the view. For all the other entities,
1609 destroying them or removing their components isn't allowed and it can result
1610 in undefined behavior.
1612 Iterators are invalidated and the behavior is undefined if an entity is modified
1613 or destroyed and it's not the one currently returned by the view nor a newly
1615 To work around it, possible approaches are:
1617 * Store aside the entities and the components to be removed and perform the
1618 operations at the end of the iteration.
1619 * Mark entities and components with a proper tag component that indicates they
1620 must be purged, then perform a second iteration to clean them up one by one.
1622 A notable side effect of this feature is that the number of required allocations
1623 is further reduced in most of the cases.
1627 In general, the entire registry isn't thread safe as it is. Thread safety isn't
1628 something that users should want out of the box for several reasons. Just to
1629 mention one of them: performance.<br/>
1630 Views and consequently the approach adopted by `EnTT` are the great exception to
1631 the rule. It's true that views and thus their iterators aren't thread safe by
1632 themselves. Because of this users shouldn't try to iterate a set of components
1633 and modify the same set concurrently. However:
1635 * As long as a thread iterates the entities that have the component `X` or
1636 assign and removes that component from a set of entities, another thread can
1637 safely do the same with components `Y` and `Z` and everything will work like a
1638 charm. As a trivial example, users can freely execute the rendering system and
1639 iterate the renderable entities while updating a physic component concurrently
1640 on a separate thread.
1642 * Similarly, a single set of components can be iterated by multiple threads as
1643 long as the components are neither assigned nor removed in the meantime. In
1644 other words, a hypothetical movement system can start multiple threads, each
1645 of which will access the components that carry information about velocity and
1646 position for its entities.
1648 This kind of entity-component systems can be used in single threaded
1649 applications as well as along with async stuff or multiple threads. Moreover,
1650 typical thread based models for _ECS_ don't require a fully thread safe registry
1651 to work. Actually, users can reach the goal with the registry as it is while
1652 working with most of the common models.
1654 Because of the few reasons mentioned above and many others not mentioned, users
1655 are completely responsible for synchronization whether required. On the other
1656 hand, they could get away with it without having to resort to particular
1659 # Crash Course: core functionalities
1661 The `EnTT` framework comes with a bunch of core functionalities mostly used by
1662 the other parts of the library itself.<br/>
1663 Hardly users of the framework will include these features in their code, but
1664 it's worth describing what `EnTT` offers so as not to reinvent the wheel in case
1667 ## Compile-time identifiers
1669 Sometimes it's useful to be able to give unique identifiers to types at
1671 There are plenty of different solutions out there and I could have used one of
1672 them. However, I decided to spend my time to define a compact and versatile tool
1673 that fully embraces what the modern C++ has to offer.
1675 The _result of my efforts_ is the `Identifier` class template:
1678 #include <ident.hpp>
1680 // defines the identifiers for the given types
1681 using ID = entt::Identifier<AType, AnotherType>;
1685 switch(aTypeIdentifier) {
1686 case ID::get<AType>():
1689 case ID::get<AnotherType>():
1697 This is all what the class template has to offer: a static `get` member function
1698 that returns a numerical identifier for the given type. It can be used in any
1699 context where constant expressions are required.
1701 As long as the list remains unchanged, identifiers are also guaranteed to be the
1702 same for every run. In case they have been used in a production environment and
1703 a type has to be removed, one can just use a placeholder to left the other
1704 identifiers unchanged:
1707 template<typename> struct IgnoreType {};
1709 using ID = entt::Identifier<
1711 IgnoreType<ATypeNoLongerValid>,
1712 AnotherTypeStillValid
1716 A bit ugly to see, but it works at least.
1718 ## Runtime identifiers
1720 Sometimes it's useful to be able to give unique identifiers to types at
1722 There are plenty of different solutions out there and I could have used one of
1723 them. In fact, I adapted the most common one to my requirements and used it
1724 extensively within the entire framework.
1726 It's the `Family` class. Here is an example of use directly from the
1727 entity-component system:
1730 using component_family = entt::Family<struct InternalRegistryComponentFamily>;
1734 template<typename Component>
1735 component_type component() const noexcept {
1736 return component_family::type<Component>();
1740 This is all what a _family_ has to offer: a `type` member function that returns
1741 a numerical identifier for the given type.
1743 Please, note that identifiers aren't guaranteed to be the same for every run.
1744 Indeed it mostly depends on the flow of execution.
1748 A hashed string is a zero overhead resource identifier. Users can use
1749 human-readable identifiers in the codebase while using their numeric
1750 counterparts at runtime, thus without affecting performance.<br/>
1751 The class has an implicit `constexpr` constructor that chews a bunch of
1752 characters. Once created, all what one can do with it is getting back the
1753 original string or converting it into a number.<br/>
1754 The good part is that a hashed string can be used wherever a constant expression
1755 is required and no _string-to-number_ conversion will take place at runtime if
1761 auto load(entt::HashedString::hash_type resource) {
1762 // uses the numeric representation of the resource to load and return it
1765 auto resource = load(entt::HashedString{"gui/background"});
1770 The hashed string class uses internally FNV-1a to compute the numeric
1771 counterpart of a string. Because of the _pigeonhole principle_, conflicts are
1772 possible. This is a fact.<br/>
1773 There is no silver bullet to solve the problem of conflicts when dealing with
1774 hashing functions. In this case, the best solution seemed to be to give up.
1776 After all, human-readable resource identifiers aren't something strictly defined
1777 and over which users have not the control. Choosing a slightly different
1778 identifier is probably the best solution to make the conflict disappear in this
1783 The monostate pattern is often presented as an alternative to a singleton based
1784 configuration system. This is exactly its purpose in `EnTT`. Moreover, this
1785 implementation is thread safe by design (hopefully).<br/>
1786 Keys are represented by hashed strings, values are basic types like `int`s or
1787 `bool`s. Values of different types can be associated to each key, even more than
1788 one at a time. Because of this, users must pay attention to use the same type
1789 both during an assignment and when they try to read back their data. Otherwise,
1790 they will probably incur in unexpected results.
1795 entt::Monostate<entt::HashedString{"mykey"}>{} = true;
1796 entt::Monostate<"mykey"_hs>{} = 42;
1800 const bool b = entt::Monostate<"mykey"_hs>{};
1801 const int i = entt::Monostate<entt::HashedString{"mykey"}>{};
1804 # Crash Course: service locator
1806 Usually service locators are tightly bound to the services they expose and it's
1807 hard to define a general purpose solution. This template based implementation
1808 tries to fill the gap and to get rid of the burden of defining a different
1809 specific locator for each application.<br/>
1810 This class is tiny, partially unsafe and thus risky to use. Moreover it doesn't
1811 fit probably most of the scenarios in which a service locator is required. Look
1812 at it as a small tool that can sometimes be useful if the user knows how to
1815 The API is straightforward. The basic idea is that services are implemented by
1816 means of interfaces and rely on polymorphism.<br/>
1817 The locator is instantiated with the base type of the service if any and a
1818 concrete implementation is provided along with all the parameters required to
1819 initialize it. As an example:
1822 // the service has no base type, a locator is used to treat it as a kind of singleton
1823 entt::ServiceLocator<MyService>::set(params...);
1825 // sets up an opaque service
1826 entt::ServiceLocator<AudioInterface>::set<AudioImplementation>(params...);
1828 // resets (destroys) the service
1829 entt::ServiceLocator<AudioInterface>::reset();
1832 The locator can also be queried to know if an active service is currently set
1833 and to retrieve it if necessary (either as a pointer or as a reference):
1836 // no service currently set
1837 auto empty = entt::ServiceLocator<AudioInterface>::empty();
1839 // gets a (possibly empty) shared pointer to the service ...
1840 std::shared_ptr<AudioInterface> ptr = entt::ServiceLocator<AudioInterface>::get();
1842 // ... or a reference, but it's undefined behaviour if the service isn't set yet
1843 AudioInterface &ref = entt::ServiceLocator<AudioInterface>::ref();
1846 A common use is to wrap the different locators in a container class, creating
1847 aliases for the various services:
1851 using Camera = entt::ServiceLocator<CameraInterface>;
1852 using Audio = entt::ServiceLocator<AudioInterface>;
1859 Locator::Camera::set<CameraNull>();
1860 Locator::Audio::set<AudioImplementation>(params...);
1865 # Crash Course: cooperative scheduler
1867 Sometimes processes are a useful tool to work around the strict definition of a
1868 system and introduce logic in a different way, usually without resorting to the
1869 introduction of other components.
1871 The `EnTT` framework offers a minimal support to this paradigm by introducing a
1872 few classes that users can use to define and execute cooperative processes.
1876 A typical process must inherit from the `Process` class template that stays true
1877 to the CRTP idiom. Moreover, derived classes must specify what's the intended
1878 type for elapsed times.
1880 A process should expose publicly the following member functions whether
1881 required (note that it isn't required to define a function unless the derived
1882 class wants to _override_ the default behavior):
1884 * `void update(Delta, void *);`
1886 It's invoked once per tick until a process is explicitly aborted or it
1887 terminates either with or without errors. Even though it's not mandatory to
1888 declare this member function, as a rule of thumb each process should at
1889 least define it to work properly. The `void *` parameter is an opaque pointer
1890 to user data (if any) forwarded directly to the process during an update.
1892 * `void init(void *);`
1894 It's invoked at the first tick, immediately before an update. The `void *`
1895 parameter is an opaque pointer to user data (if any) forwarded directly to the
1896 process during an update.
1898 * `void succeeded();`
1900 It's invoked in case of success, immediately after an update and during the
1905 It's invoked in case of errors, immediately after an update and during the
1910 It's invoked only if a process is explicitly aborted. There is no guarantee
1911 that it executes in the same tick, this depends solely on whether the
1912 process is aborted immediately or not.
1914 Derived classes can also change the internal state of a process by invoking
1915 `succeed` and `fail`, as well as `pause` and `unpause` the process itself. All
1916 these are protected member functions made available to be able to manage the
1917 life cycle of a process from a derived class.
1919 Here is a minimal example for the sake of curiosity:
1922 struct MyProcess: entt::Process<MyProcess, std::uint32_t> {
1923 using delta_type = std::uint32_t;
1925 void update(delta_type delta, void *) {
1926 remaining = delta > remaining ? delta_type{] : (remaining - delta);
1935 void init(void *data) {
1936 remaining = *static_cast<delta_type *>(data);
1940 delta_type remaining;
1946 Lambdas and functors can't be used directly with a scheduler for they are not
1947 properly defined processes with managed life cycles.<br/>
1948 This class helps in filling the gap and turning lambdas and functors into
1949 full featured processes usable by a scheduler.
1951 The function call operator has a signature similar to the one of the `update`
1952 function of a process but for the fact that it receives two extra arguments to
1953 call whenever a process is terminated with success or with an error:
1956 void(Delta delta, void *data, auto succeed, auto fail);
1959 Parameters have the following meaning:
1961 * `delta` is the elapsed time.
1962 * `data` is an opaque pointer to user data if any, `nullptr` otherwise.
1963 * `succeed` is a function to call when a process terminates with success.
1964 * `fail` is a function to call when a process terminates with errors.
1966 Both `succeed` and `fail` accept no parameters at all.
1968 Note that usually users shouldn't worry about creating adaptors at all. A
1969 scheduler creates them internally each and every time a lambda or a functor is
1974 A cooperative scheduler runs different processes and helps managing their life
1977 Each process is invoked once per tick. If it terminates, it's removed
1978 automatically from the scheduler and it's never invoked again. Otherwise it's
1979 a good candidate to run once more the next tick.<br/>
1980 A process can also have a child. In this case, the process is replaced with
1981 its child when it terminates if it returns with success. In case of errors,
1982 both the process and its child are discarded. This way, it's easy to create
1983 chain of processes to run sequentially.
1985 Using a scheduler is straightforward. To create it, users must provide only the
1986 type for the elapsed times and no arguments at all:
1989 Scheduler<std::uint32_t> scheduler;
1992 It has member functions to query its internal data structures, like `empty` or
1993 `size`, as well as a `clear` utility to reset it to a clean state:
1996 // checks if there are processes still running
1997 const auto empty = scheduler.empty();
1999 // gets the number of processes still running
2000 Scheduler<std::uint32_t>::size_type size = scheduler.size();
2002 // resets the scheduler to its initial state and discards all the processes
2006 To attach a process to a scheduler there are mainly two ways:
2008 * If the process inherits from the `Process` class template, it's enough to
2009 indicate its type and submit all the parameters required to construct it to
2010 the `attach` member function:
2013 scheduler.attach<MyProcess>("foobar");
2016 * Otherwise, in case of a lambda or a functor, it's enough to provide an
2017 instance of the class to the `attach` member function:
2020 scheduler.attach([](auto...){ /* ... */ });
2023 In both cases, the return value is an opaque object that offers a `then` member
2024 function to use to create chains of processes to run sequentially.<br/>
2025 As a minimal example of use:
2028 // schedules a task in the form of a lambda function
2029 scheduler.attach([](auto delta, void *, auto succeed, auto fail) {
2032 // appends a child in the form of another lambda function
2033 .then([](auto delta, void *, auto succeed, auto fail) {
2036 // appends a child in the form of a process class
2040 To update a scheduler and thus all its processes, the `update` member function
2044 // updates all the processes, no user data are provided
2045 scheduler.update(delta);
2047 // updates all the processes and provides them with custom data
2048 scheduler.update(delta, &data);
2051 In addition to these functions, the scheduler offers an `abort` member function
2052 that can be used to discard all the running processes at once:
2055 // aborts all the processes abruptly ...
2056 scheduler.abort(true);
2058 // ... or gracefully during the next tick
2062 # Crash Course: resource management
2064 Resource management is usually one of the most critical part of a software like
2065 a game. Solutions are often tuned to the particular application. There exist
2066 several approaches and all of them are perfectly fine as long as they fit the
2067 requirements of the piece of software in which they are used.<br/>
2068 Examples are loading everything on start, loading on request, predictive
2071 The `EnTT` framework doesn't pretend to offer a _one-fits-all_ solution for the
2072 different cases. Instead, it offers a minimal and perhaps trivial cache that can
2073 be useful most of the time during prototyping and sometimes even in a production
2075 For those interested in the subject, the plan is to improve it considerably over
2076 time in terms of performance, memory usage and functionalities. Hoping to make
2077 it, of course, one step at a time.
2079 ## The resource, the loader and the cache
2081 There are three main actors in the model: the resource, the loader and the
2084 The _resource_ is whatever the user wants it to be. An image, a video, an audio,
2085 whatever. There are no limits.<br/>
2086 As a minimal example:
2089 struct MyResource { const int value; };
2092 A _loader_ is a class the aim of which is to load a specific resource. It has to
2093 inherit directly from the dedicated base class as in the following example:
2096 struct MyLoader final: entt::ResourceLoader<MyLoader, MyResource> {
2101 Where `MyResource` is the type of resources it creates.<br/>
2102 A resource loader must also expose a public const member function named `load`
2103 that accepts a variable number of arguments and returns a shared pointer to a
2108 struct MyLoader: entt::ResourceLoader<MyLoader, MyResource> {
2109 std::shared_ptr<MyResource> load(int value) const {
2111 return std::shared_ptr<MyResource>(new MyResource{ value });
2116 In general, resource loaders should not have a state or retain data of any type.
2117 They should let the cache manage their resources instead.<br/>
2118 As a side note, base class and CRTP idiom aren't strictly required with the
2119 current implementation. One could argue that a cache can easily work with
2120 loaders of any type. However, future changes won't be breaking ones by forcing
2121 the use of a base class today and that's why the model is already in its place.
2123 Finally, a cache is a specialization of a class template tailored to a specific
2127 using MyResourceCache = entt::ResourceCache<MyResource>;
2131 MyResourceCache cache{};
2134 The idea is to create different caches for different types of resources and to
2135 manage each one independently and in the most appropriate way.<br/>
2136 As a (very) trivial example, audio tracks can survive in most of the scenes of
2137 an application while meshes can be associated with a single scene and then
2138 discarded when the user leaves it.
2140 A cache offers a set of basic functionalities to query its internal state and to
2144 // gets the number of resources managed by a cache
2145 const auto size = cache.size();
2147 // checks if a cache contains at least a valid resource
2148 const auto empty = cache.empty();
2150 // clears a cache and discards its content
2154 Besides these member functions, it contains what is needed to load, use and
2155 discard resources of the given type.<br/>
2156 Before to explore this part of the interface, it makes sense to mention how
2157 resources are identified. The type of the identifiers to use is defined as:
2160 entt::ResourceCache<Resource>::resource_type
2163 Where `resource_type` is an alias for `entt::HashedString`. Therefore, resource
2164 identifiers are created explicitly as in the following example:
2167 constexpr auto identifier = entt::ResourceCache<Resource>::resource_type{"my/resource/identifier"};
2168 // this is equivalent to the following
2169 constexpr auto hs = entt::HashedString{"my/resource/identifier"};
2172 The class `HashedString` is described in a dedicated section, so I won't do in
2175 Resources are loaded and thus stored in a cache through the `load` member
2176 function. It accepts the loader to use as a template parameter, the resource
2177 identifier and the parameters used to construct the resource as arguments:
2180 // uses the identifier declared above
2181 cache.load<MyLoader>(identifier, 0);
2183 // uses a const char * directly as an identifier
2184 cache.load<MyLoader>("another/identifier", 42);
2187 The return value can be used to know if the resource has been loaded correctly.
2188 In case the loader returns an invalid pointer or the resource already exists in
2189 the cache, a false value is returned:
2192 if(!cache.load<MyLoader>("another/identifier", 42)) {
2197 Unfortunately, in this case there is no way to know what was the problem
2198 exactly. However, before trying to load a resource or after an error, one can
2199 use the `contains` member function to know if a cache already contains a
2203 auto exists = cache.contains("my/identifier");
2206 There exists also a member function to use to force a reload of an already
2207 existing resource if needed:
2210 auto result = cache.reload<MyLoader>("another/identifier", 42);
2213 As above, the function returns true in case of success, false otherwise. The
2214 sole difference in this case is that an error necessarily means that the loader
2215 has failed for some reasons to load the resource.<br/>
2216 Note that the `reload` member function is a kind of alias of the following
2220 cache.discard(identifier);
2221 cache.load<MyLoader>(identifier, 42);
2224 Where the `discard` member function is used to get rid of a resource if loaded.
2225 In case the cache doesn't contain a resource for the given identifier, the
2226 function does nothing and returns immediately.
2228 So far, so good. Resources are finally loaded and stored within the cache.<br/>
2229 They are returned to users in the form of handles. To get one of them:
2232 auto handle = cache.handle("my/identifier");
2235 The idea behind a handle is the same of the flyweight pattern. In other terms,
2236 resources aren't copied around. Instead, instances are shared between handles.
2237 Users of a resource owns a handle and it guarantees that a resource isn't
2238 destroyed until all the handles are destroyed, even if the resource itself is
2239 removed from the cache.<br/>
2240 Handles are tiny objects both movable and copyable. They returns the contained
2241 resource as a const reference on request:
2243 * By means of the `get` member function:
2246 const auto &resource = handle.get();
2249 * Using the proper cast operator:
2252 const auto &resource = handle;
2255 * Through the dereference operator:
2258 const auto &resource = *handle;
2261 The resource can also be accessed directly using the arrow operator if required:
2264 auto value = handle->value;
2267 To test if a handle is still valid, the cast operator to `bool` allows users to
2276 Finally, in case there is the need to load a resource and thus to get a handle
2277 without storing the resource itself in the cache, users can rely on the `temp`
2278 member function template.<br/>
2279 The declaration is similar to the one of `load` but for the fact that it doesn't
2280 return a boolean value. Instead, it returns a (possibly invalid) handle for the
2284 auto handle = cache.temp<MyLoader>("another/identifier", 42);
2287 Do not forget to test the handle for validity. Otherwise, getting the reference
2288 to the resource it points may result in undefined behavior.
2290 # Crash Course: events, signals and everything in between
2292 Signals are usually a core part of games and software architectures in
2294 Roughly speaking, they help to decouple the various parts of a system while
2295 allowing them to communicate with each other somehow.
2297 The so called _modern C++_ comes with a tool that can be useful in these terms,
2298 the `std::function`. As an example, it can be used to create delegates.<br/>
2299 However, there is no guarantee that an `std::function` does not perform
2300 allocations under the hood and this could be problematic sometimes. Furthermore,
2301 it solves a problem but may not adapt well to other requirements that may arise
2304 In case that the flexibility and potential of an `std::function` are not
2305 required or where you are looking for something different, the `EnTT` framework
2306 offers a full set of classes to solve completely different problems.
2310 Signal handlers work with naked pointers, function pointers and pointers to
2311 member functions. Listeners can be any kind of objects and the user is in charge
2312 of connecting and disconnecting them from a signal to avoid crashes due to
2313 different lifetimes. On the other side, performance shouldn't be affected that
2314 much by the presence of such a signal handler.<br/>
2315 A signal handler can be used as a private data member without exposing any
2316 _publish_ functionality to the clients of a class. The basic idea is to impose a
2317 clear separation between the signal itself and its _sink_ class, that is a tool
2318 to be used to connect and disconnect listeners on the fly.
2320 The API of a signal handler is straightforward. The most important thing is that
2321 it comes in two forms: with and without a collector. In case a signal is
2322 associated with a collector, all the values returned by the listeners can be
2323 literally _collected_ and used later by the caller. Otherwise it works just like
2324 a plain signal that emits events from time to time.<br/>
2326 **Note**: collectors are allowed only in case of function types whose the return
2327 type isn't `void` for obvious reasons.
2329 To create instances of signal handlers there exist mainly two ways:
2332 // no collector type
2333 entt::SigH<void(int, char)> signal;
2335 // explicit collector type
2336 entt::SigH<void(int, char), MyCollector<bool>> collector;
2339 As expected, they offer all the basic functionalities required to know how many
2340 listeners they contain (`size`) or if they contain at least a listener (`empty`)
2341 and even to swap two signal handlers (`swap`).
2343 Besides them, there are member functions to use both to connect and disconnect
2344 listeners in all their forms by means of a sink:
2347 void foo(int, char) { /* ... */ }
2350 void bar(int, char) { /* ... */ }
2357 signal.sink().connect<&foo>();
2358 signal.sink().connect<S, &S::bar>(&instance);
2362 // disconnects a free function
2363 signal.sink().disconnect<&foo>();
2365 // disconnect a specific member function of an instance ...
2366 signal.sink().disconnect<S, &S::bar>(&instance);
2368 // ... or an instance as a whole
2369 signal.sink().disconnect(&instance);
2371 // discards all the listeners at once
2372 signal.sink().disconnect();
2375 Once listeners are attached (or even if there are no listeners at all), events
2376 and data in general can be published through a signal by means of the `publish`
2380 signal.publish(42, 'c');
2383 To collect data, the `collect` member function should be used instead. Below is
2384 a minimal example to show how to use it:
2387 struct MyCollector {
2388 std::vector<int> vec{};
2390 bool operator()(int v) noexcept {
2396 int f() { return 0; }
2397 int g() { return 1; }
2401 entt::SigH<int(), MyCollector<int>> signal;
2403 signal.sink().connect<&f>();
2404 signal.sink().connect<&g>();
2406 MyCollector collector = signal.collect();
2408 assert(collector.vec[0] == 0);
2409 assert(collector.vec[1] == 1);
2412 As shown above, a collector must expose a function operator that accepts as an
2413 argument a type to which the return type of the listeners can be converted.
2414 Moreover, it has to return a boolean value that is false to stop collecting
2415 data, true otherwise. This way one can avoid calling all the listeners in case
2420 A delegate can be used as general purpose invoker with no memory overhead for
2421 free functions and member functions provided along with an instance on which
2422 to invoke them.<br/>
2423 It does not claim to be a drop-in replacement for an `std::function`, so do not
2424 expect to use it whenever an `std::function` fits well. However, it can be used
2425 to send opaque delegates around to be used to invoke functions as needed.
2427 The interface is trivial. It offers a default constructor to create empty
2431 entt::Delegate<int(int)> delegate{};
2434 All what is needed to create an instance is to specify the type of the function
2435 the delegate will _contain_, that is the signature of the free function or the
2436 member function one wants to assign to it.
2438 Attempting to use an empty delegate by invoking its function call operator
2439 results in undefined behavior, most likely a crash actually. Before to use a
2440 delegate, it must be initialized.<br/>
2441 There exist two functions to do that, both named `connect`:
2444 int f(int i) { return i; }
2447 int f(int i) { return i }
2450 // bind a free function to the delegate
2451 delegate.connect<&f>();
2453 // bind a member function to the delegate
2455 delegate.connect<MyStruct, &MyStruct::f>(&instance);
2458 It hasn't a `disconnect` counterpart. Instead, there exists a `reset` member
2459 function to clear it.<br/>
2460 The `empty` member function can be used to know if a delegate is empty:
2463 const auto empty = delegate.empty();
2466 Finally, to invoke a delegate, the function call operator is the way to go as
2470 auto ret = delegate(42);
2473 Probably too much small and pretty poor of functionalities, but the delegate
2474 class can help in a lot of cases and it has shown that it is worth keeping it
2475 within the framework.
2479 The event dispatcher class is designed so as to be used in a loop. It allows
2480 users both to trigger immediate events or to queue events to be published all
2481 together once per tick.<br/>
2482 This class shares part of its API with the one of the signal handler, but it
2483 doesn't require that all the types of events are specified when declared:
2486 // define a general purpose dispatcher that works with naked pointers
2487 entt::Dispatcher dispatcher{};
2490 In order to register an instance of a class to a dispatcher, its type must
2491 expose one or more member functions of which the return types are `void` and the
2492 argument lists are `const E &`, for each type of event `E`.<br/>
2493 To ease the development, member functions that are named `receive` are
2494 automatically detected and have not to be explicitly specified when registered.
2495 In all the other cases, the name of the member function aimed to receive the
2496 event must be provided to the `connect` member function of the sink bound to the
2500 struct AnEvent { int value; };
2501 struct AnotherEvent {};
2505 void receive(const AnEvent &) { /* ... */ }
2506 void method(const AnotherEvent &) { /* ... */ }
2512 dispatcher.sink<AnEvent>().connect(&listener);
2513 dispatcher.sink<AnotherEvent>().connect<Listener, &Listener::method>(&listener);
2516 The `disconnect` member function follows the same pattern and can be used to
2517 selectively remove listeners:
2520 dispatcher.sink<AnEvent>().disconnect(&listener);
2521 dispatcher.sink<AnotherEvent>().disconnect<Listener, &Listener::method>(&listener);
2524 The `trigger` member function serves the purpose of sending an immediate event
2525 to all the listeners registered so far. It offers a convenient approach that
2526 relieves the user from having to create the event itself. Instead, it's enough
2527 to specify the type of event and provide all the parameters required to
2532 dispatcher.trigger<AnEvent>(42);
2533 dispatcher.trigger<AnotherEvent>();
2536 Listeners are invoked immediately, order of execution isn't guaranteed. This
2537 method can be used to push around urgent messages like an _is terminating_
2538 notification on a mobile app.
2540 On the other hand, the `enqueue` member function queues messages together and
2541 allows to maintain control over the moment they are sent to listeners. The
2542 signature of this method is more or less the same of `trigger`:
2545 dispatcher.enqueue<AnEvent>(42);
2546 dispatcher.enqueue<AnotherEvent>();
2549 Events are stored aside until the `update` member function is invoked, then all
2550 the messages that are still pending are sent to the listeners at once:
2553 // emits all the events of the given type at once
2554 dispatcher.update<MyEvent>();
2556 // emits all the events queued so far at once
2557 dispatcher.update();
2560 This way users can embed the dispatcher in a loop and literally dispatch events
2561 once per tick to their systems.
2565 A general purpose event emitter thought mainly for those cases where it comes to
2566 working with asynchronous stuff.<br/>
2567 Originally designed to fit the requirements of
2568 [`uvw`](https://github.com/skypjack/uvw) (a wrapper for `libuv` written in
2569 modern C++), it was adapted later to be included in this library.
2571 To create a custom emitter type, derived classes must inherit directly from the
2575 struct MyEmitter: Emitter<MyEmitter> {
2580 The full list of accepted types of events isn't required. Handlers are created
2581 internally on the fly and thus each type of event is accepted by default.
2583 Whenever an event is published, an emitter provides the listeners with a
2584 reference to itself along with a const reference to the event. Therefore
2585 listeners have an handy way to work with it without incurring in the need of
2586 capturing a reference to the emitter itself.<br/>
2587 In addition, an opaque object is returned each time a connection is established
2588 between an emitter and a listener, allowing the caller to disconnect them at a
2590 The opaque object used to handle connections is both movable and copyable. On
2591 the other side, an event emitter is movable but not copyable by default.
2593 To create new instances of an emitter, no arguments are required:
2596 MyEmitter emitter{};
2599 Listeners must be movable and callable objects (free functions, lambdas,
2600 functors, `std::function`s, whatever) whose function type is:
2603 void(const Event &, MyEmitter &)
2606 Where `Event` is the type of event they want to listen.<br/>
2607 There are two ways to attach a listener to an event emitter that differ
2608 slightly from each other:
2610 * To register a long-lived listener, use the `on` member function. It is meant
2611 to register a listener designed to be invoked more than once for the given
2616 auto conn = emitter.on<MyEvent>([](const MyEvent &event, MyEmitter &emitter) {
2621 The connection object can be freely discarded. Otherwise, it can be used later
2622 to disconnect the listener if required.
2624 * To register a short-lived listener, use the `once` member function. It is
2625 meant to register a listener designed to be invoked only once for the given
2626 event type. The listener is automatically disconnected after the first
2631 auto conn = emitter.once<MyEvent>([](const MyEvent &event, MyEmitter &emitter) {
2636 The connection object can be freely discarded. Otherwise, it can be used later
2637 to disconnect the listener if required.
2639 In both cases, the connection object can be used with the `erase` member
2643 emitter.erase(conn);
2646 There are also two member functions to use either to disconnect all the
2647 listeners for a given type of event or to clear the emitter:
2650 // removes all the listener for the specific event
2651 emitter.clear<MyEvent>();
2653 // removes all the listeners registered so far
2657 To send an event to all the listeners that are interested in it, the `publish`
2658 member function offers a convenient approach that relieves the user from having
2659 to create the event:
2662 struct MyEvent { int i; };
2666 emitter.publish<MyEvent>(42);
2669 Finally, the `empty` member function tests if there exists at least either a
2670 listener registered with the event emitter or to a given type of event:
2675 // checks if there is any listener registered for the specific event
2676 empty = emitter.empty<MyEvent>();
2678 // checks it there are listeners registered with the event emitter
2679 empty = emitter.empty();
2682 In general, the event emitter is a handy tool when the derived classes _wrap_
2683 asynchronous operations, because it introduces a _nice-to-have_ model based on
2684 events and listeners that kindly hides the complexity behind the scenes. However
2685 it is not limited to such uses.
2689 `EnTT` is available for some of the most known packaging tools. In particular:
2691 * [`vcpkg`](https://github.com/Microsoft/vcpkg/tree/master/ports/entt),
2692 Microsoft VC++ Packaging Tool.
2693 * [`Homebrew`](https://github.com/skypjack/homebrew-entt), the missing package
2694 manager for macOS.<br/>
2695 Available as a homebrew formula. Just type the following to install it:
2697 brew install skypjack/entt/entt
2700 Consider this list a work in progress and help me to make it longer.
2704 `EnTT` is widely used in private and commercial applications. I cannot even
2705 mention most of them because of some signatures I put on some documents time
2707 Fortunately, there are also people who took the time to implement open source
2708 projects based on EnTT and did not hold back when it came to documenting them.
2710 Below an incomplete list of projects and articles:
2712 * [EnttPong](https://github.com/reworks/EnttPong): example game for `EnTT`
2714 * [Space Battle: Huge edition](http://victor.madtriangles.com/code%20experiment/2018/06/11/post-ecs-battle-huge.html):
2715 huge space battle built entirely from scratch.
2716 * [Space Battle](https://github.com/vblanco20-1/ECS_SpaceBattle): huge space
2717 battle built on `UE4`.
2718 * [Experimenting with ECS in UE4](http://victor.madtriangles.com/code%20experiment/2018/03/25/post-ue4-ecs-battle.html):
2719 interesting article about `UE4` and `EnTT`.
2720 * [Implementing ECS architecture in UE4](https://forums.unrealengine.com/development-discussion/c-gameplay-programming/1449913-implementing-ecs-architecture-in-ue4-giant-space-battle):
2722 * [MatchOneEntt](https://github.com/mhaemmerle/MatchOneEntt): port of
2723 [Match One](https://github.com/sschmid/Match-One) for `Entitas-CSharp`.
2724 * [Randballs](https://github.com/gale93/randballs): simple `SFML` and `EnTT`
2728 If you know of other resources out there that are about `EnTT`, feel free to
2729 open an issue or a PR and I'll be glad to add them to the list.
2733 If you want to participate, please see the guidelines for
2734 [contributing](https://github.com/skypjack/entt/blob/master/CONTRIBUTING)
2735 before to create issues or pull requests.<br/>
2736 Take also a look at the
2737 [contributors list](https://github.com/skypjack/entt/blob/master/AUTHORS) to
2738 know who has participated so far.
2742 Code and documentation Copyright (c) 2018 Michele Caini.<br/>
2744 [the MIT license](https://github.com/skypjack/entt/blob/master/LICENSE).
2746 [Creative Commons](https://github.com/skypjack/entt/blob/master/docs/LICENSE).
2752 Developing and maintaining `EnTT` takes some time and lots of coffee. I'd like
2753 to add more and more functionalities in future and turn it in a full-featured
2755 If you want to support this project, you can offer me an espresso. I'm from
2756 Italy, we're used to turning the best coffee ever in code. If you find that
2757 it's not enough, feel free to support me the way you prefer.<br/>
2758 Take a look at the donation button at the top of the page for more details or
2759 just click [here](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted).
2763 If you start using `EnTT` and need help, if you want a new feature and want me
2764 to give it the highest priority, if you have any other reason to contact me:
2765 do not hesitate. I'm available for hiring.<br/>
2766 Feel free to take a look at my [profile](https://github.com/skypjack) and