diff --git a/README_8md_source.html b/README_8md_source.html index 4acb6f77b..6a25fdc61 100644 --- a/README_8md_source.html +++ b/README_8md_source.html @@ -22,7 +22,7 @@
entt -  2.2.0 +  2.3.0
@@ -63,7 +63,7 @@ $(function() {
README.md
-
1 # EnTT Framework
2 
3 [![Build Status](https://travis-ci.org/skypjack/entt.svg?branch=master)](https://travis-ci.org/skypjack/entt)
4 [![Build status](https://ci.appveyor.com/api/projects/status/rvhaabjmghg715ck?svg=true)](https://ci.appveyor.com/project/skypjack/entt)
5 [![Coverage Status](https://coveralls.io/repos/github/skypjack/entt/badge.svg?branch=master)](https://coveralls.io/github/skypjack/entt?branch=master)
6 [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
7 
8 # Introduction
9 
10 `EnTT` is a header-only, tiny and easy to use framework written in modern
11 C++.<br/>
12 It was originally designed entirely around an architectural pattern called _ECS_
13 that is used mostly in game development. For further details:
14 
15 * [Entity Systems Wiki](http://entity-systems.wikidot.com/)
16 * [Evolve Your Hierarchy](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/)
17 * [ECS on Wikipedia](https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system)
18 
19 A long time ago, the sole entity-component system was part of the project. After
20 a while the codebase has grown and more and more classes have become part
21 of the repository.<br/>
22 That's why today it's called _the EnTT Framework_.
23 
24 Currently, `EnTT` is tested on Linux, Microsoft Windows and OS X. It has proven
25 to work also on both Android and iOS.<br/>
26 Most likely it will not be problematic on other systems as well, but has not
27 been sufficiently tested so far.
28 
29 ## The framework
30 
31 `EnTT` was written initially as a faster alternative to other well known and
32 open source entity-component systems. Nowadays the `EnTT` framework is moving
33 its first steps. Much more will come in the future and hopefully I'm going to
34 work on it for a long time.<br/>
35 Requests for feature, PR, suggestions ad feedback are highly appreciated.
36 
37 If you find you can help me and want to contribute to the `EnTT` framework with
38 your experience or you do want to get part of the project for some other
39 reason, feel free to contact me directly (you can find the mail in the
40 [profile](https://github.com/skypjack)).<br/>
41 I can't promise that each and every contribution will be accepted, but I can
42 assure that I'll do my best to take them all seriously.
43 
44 ### State of the art
45 
46 Here is a brief list of what it offers today:
47 
48 * Statically generated integer identifiers for types (assigned either at
49 compile-time or at runtime).
50 * A constexpr utility for human readable resource identifiers.
51 * An incredibly fast entity-component system based on sparse sets, with its own
52 views and a _pay for what you use_ policy to adjust performance and memory
53 pressure according to the users' requirements.
54 * Actor class for those who aren't confident with entity-component systems.
55 * The smallest and most basic implementation of a service locator ever seen.
56 * A cooperative scheduler for processes of any type.
57 * All what is needed for resource management (cache, loaders, handles).
58 * Signal handlers of any type, delegates and an event bus.
59 * A general purpose event emitter, that is a CRTP idiom based class template.
60 * An event dispatcher for immediate and delayed events to integrate in loops.
61 * ...
62 * Any other business.
63 
64 Consider it a work in progress. For more details and an updated list, please
65 refer to the [online documentation](https://skypjack.github.io/entt/).
66 
67 ### A note about the README
68 
69 The README file stays true to the original project and it describes only the
70 entity-component system. However, the whole API is fully documented in-code and
71 the [online documentation](https://skypjack.github.io/entt/) contains much
72 more.<br/>
73 Continue reading to know how the core part of the project works or follow the
74 link above to take a look at the API reference for all other available classes.
75 
76 ## Code Example
77 
78 ```cpp
79 #include <entt/entt.hpp>
80 #include <cstdint>
81 
82 struct Position {
83  float x;
84  float y;
85 };
86 
87 struct Velocity {
88  float dx;
89  float dy;
90 };
91 
92 void update(entt::DefaultRegistry &registry) {
93  auto view = registry.view<Position, Velocity>();
94 
95  for(auto entity: view) {
96  // gets only the components that are going to be used ...
97 
98  auto &velocity = view.get<Velocity>(entity);
99 
100  velocity.dx = 0.;
101  velocity.dy = 0.;
102 
103  // ...
104  }
105 }
106 
107 void update(std::uint64_t dt, entt::DefaultRegistry &registry) {
108  registry.view<Position, Velocity>().each([dt](auto entity, auto &position, auto &velocity) {
109  // gets all the components of the view at once ...
110 
111  position.x += velocity.dx * dt;
112  position.y += velocity.dy * dt;
113 
114  // ...
115  });
116 }
117 
118 int main() {
119  entt::DefaultRegistry registry;
120  std::uint64_t dt = 16;
121 
122  for(auto i = 0; i < 10; ++i) {
123  auto entity = registry.create(Position{i * 1.f, i * 1.f});
124  if(i % 2 == 0) { registry.assign<Velocity>(entity, i * .1f, i * .1f); }
125  }
126 
127  update(dt, registry);
128  update(registry);
129 
130  // ...
131 }
132 ```
133 
134 ## Motivation
135 
136 I started working on `EnTT` because of the wrong reason: my goal was to design
137 an entity-component system that beated another well known open source solution
138 in terms of performance.<br/>
139 I did it, of course, but it wasn't much satisfying. Actually it wasn't
140 satisfying at all. The fastest and nothing more, fairly little indeed. When I
141 realized it, I tried hard to keep intact the great performance of `EnTT` and to
142 add all the features I wanted to see in *my* entity-component system at the same
143 time.
144 
145 Today `EnTT` is finally what I was looking for: still faster than its
146 _competitors_, a really good API and an amazing set of features. And even more,
147 of course.
148 
149 ## Performance
150 
151 As it stands right now, `EnTT` is just fast enough for my requirements if
152 compared to my first choice (that was already amazingly fast indeed).<br/>
153 Here is a comparision between the two (both of them compiled with GCC 7.2.0 on a
154 Dell XPS 13 out of the mid 2014):
155 
156 | Benchmark | EntityX (compile-time) | EnTT |
157 |-----------|-------------|-------------|
158 | Create 10M entities | 0.1289s | **0.0409s** |
159 | Destroy 10M entities | **0.0531s** | 0.0546s |
160 | Standard view, 10M entities, one component | 0.0107s | **1.6e-07s** |
161 | Standard view, 10M entities, two components | **0.0113s** | 0.0295s |
162 | Standard view, 10M entities, two components<br/>Half of the entities have all the components | **0.0078s** | 0.0150s |
163 | Standard view, 10M entities, two components<br/>One of the entities has all the components | 0.0071s | **8.8e-07s** |
164 | Persistent view, 10M entities, two components | 0.0113s | **5.7e-07s** |
165 | Standard view, 10M entities, five components | **0.0091s** | 0.0688s |
166 | Persistent view, 10M entities, five components | 0.0091s | **2.9e-07s** |
167 | Standard view, 10M entities, ten components | **0.0105s** | 0.1403s |
168 | Standard view, 10M entities, ten components<br/>Half of the entities have all the components | **0.0090s** | 0.0620s |
169 | Standard view, 10M entities, ten components<br/>One of the entities has all the components | 0.0070s | **1.3e-06s** |
170 | Persistent view, 10M entities, ten components | 0.0105s | **6.2e-07s** |
171 | Sort 150k entities, one component | - | **0.0084s** |
172 | Sort 150k entities, enforce permutation | - | **0.0067s** |
173 
174 `EnTT` includes its own tests and benchmarks. See
175 [benchmark.cpp](https://github.com/skypjack/entt/blob/master/test/benchmark.cpp)
176 for further details.<br/>
177 On Github users can find also a
178 [benchmark suite](https://github.com/abeimler/ecs_benchmark) that compares a
179 bunch of different projects, one of which is `EnTT`.
180 
181 Of course, probably I'll try to get out of `EnTT` more features and better
182 performance in the future, mainly for fun.<br/>
183 If you want to contribute and/or have any suggestion, feel free to make a PR or
184 open an issue to discuss your idea.
185 
186 # Build Instructions
187 
188 ## Requirements
189 
190 To be able to use `EnTT`, users must provide a full-featured compiler that
191 supports at least C++14.<br/>
192 The requirements below are mandatory to compile the tests and to extract the
193 documentation:
194 
195 * CMake version 3.2 or later.
196 * Doxygen version 1.8 or later.
197 
198 ## Library
199 
200 `EnTT` is a header-only library. This means that including the `entt.hpp`
201 header is enough to include the whole framework and use it. For those who are
202 interested only in the entity-component system, consider to include the sole
203 `entity/registry.hpp` header instead.<br/>
204 It's a matter of adding the following line to the top of a file:
205 
206 ```cpp
207 #include <entt/entt.hpp>
208 ```
209 
210 Use the line below to include only the entity-component system instead:
211 
212 ```cpp
213 #include <entt/entity/registry.hpp>
214 ```
215 
216 Then pass the proper `-I` argument to the compiler to add the `src` directory to
217 the include paths.
218 
219 ## Documentation
220 
221 The documentation is based on [doxygen](http://www.stack.nl/~dimitri/doxygen/).
222 To build it:
223 
224  $ cd build
225  $ cmake ..
226  $ make docs
227 
228 The API reference will be created in HTML format within the directory
229 `build/docs/html`. To navigate it with your favorite browser:
230 
231  $ cd build
232  $ your_favorite_browser docs/html/index.html
233 
234 The API reference is also available [online](https://skypjack.github.io/entt/)
235 for the latest version.
236 
237 ## Tests
238 
239 To compile and run the tests, `EnTT` requires *googletest*.<br/>
240 `cmake` will download and compile the library before to compile anything else.
241 
242 To build the tests:
243 
244 * `$ cd build`
245 * `$ cmake ..`
246 * `$ make`
247 * `$ make test`
248 
249 To build the benchmarks, use the following line instead:
250 
251 * `$ cmake -DCMAKE_BUILD_TYPE=Release ..`
252 
253 Benchmarks are compiled only in release mode currently.
254 
255 # Crash Course
256 
257 ## Design choices
258 
259 ### A bitset-free entity-component system
260 
261 `EnTT` is a _bitset-free_ entity-component system that doesn't require users to
262 specify the component set at compile-time.<br/>
263 That's the reason for which users can instantiate the core class simply as:
264 
265 ```cpp
266 entt::DefaultRegistry registry;
267 ```
268 
269 In place of its more annoying and error-prone counterpart:
270 
271 ```cpp
272 entt::DefaultRegistry<Comp0, Comp1, ..., CompN> registry;
273 ```
274 
275 ### Pay per use
276 
277 `EnTT` is entirely designed around the principle that users have to pay only for
278 what they want.
279 
280 When it comes to use an entity-componet system, the tradeoff is usually between
281 performance and memory usage. The faster it is, the more memory it uses.
282 However, slightly worse performance along non-critical paths are the right price
283 to pay to reduce memory usage and I've always wondered why this kind of tools do
284 not leave me the choice.<br/>
285 `EnTT` follows a completely different approach. It squezees the best from the
286 basic data structures and gives users the possibility to pay more for higher
287 performance where needed.<br/>
288 The disadvantage of this approach is that users need to know the systems they
289 are working on and the tools they are using. Otherwise, the risk to ruin the
290 performance along critical paths is high.
291 
292 So far, this choice has proven to be a good one and I really hope it can be for
293 many others besides me.
294 
295 ## Vademecum
296 
297 The `Registry` to store, the `View`s to iterate. That's all.
298 
299 An entity (the _E_ of an _ECS_) is an opaque identifier that users should just
300 use as-is and store around if needed. Do not try to inspect an entity
301 identifier, its type can change in future and a registry offers all the
302 functionalities to query them out-of-the-box. The underlying type of an entity
303 (either `std::uint16_t`, `std::uint32_t` or `std::uint64_t`) can be specified
304 when defining a registry (actually the DefaultRegistry is nothing more than a
305 Registry where the type of the entities is `std::uint32_t`).<br/>
306 Components (the _C_ of an _ECS_) should be plain old data structures or more
307 complex and moveable data structures with a proper constructor. Actually, the
308 sole requirement of a component type is that it must be both move constructible
309 and move assignable. They are list initialized by using the parameters provided
310 to construct the component itself. No need to register components or their types
311 neither with the registry nor with the entity-component system at all.<br/>
312 Systems (the _S_ of an _ECS_) are just plain functions, functors, lambdas or
313 whatever the users want. They can accept a Registry, a View or a PersistentView
314 and use them the way they prefer. No need to register systems or their types
315 neither with the registry nor with the entity-component system at all.
316 
317 The following sections will explain in short how to use the entity-component
318 system, the core part of the whole framework.<br/>
319 In fact, the framework is composed of many other classes in addition to those
320 describe below. For more details, please refer to the
321 [online documentation](https://skypjack.github.io/entt/).
322 
323 ## The Registry, the Entity and the Component
324 
325 A registry is used to store and manage entities as well as to create views to
326 iterate the underlying data structures.<br/>
327 Registry is a class template that lets the users decide what's the preferred
328 type to represent an entity. Because `std::uint32_t` is large enough for almost
329 all the cases, there exists also an alias named DefaultRegistry for
330 `Registry<std::uint32_t>`.
331 
332 Entities are represented by _entitiy identifiers_. An entity identifier is an
333 opaque type that users should not inspect or modify in any way. It carries
334 information about the entity itself and its version.
335 
336 A registry can be used both to construct and to destroy entities:
337 
338 ```cpp
339 // constructs a naked entity with no components ad returns its identifier
340 auto entity = registry.create();
341 
342 // constructs an entity and assigns it default-initialized components
343 auto another = registry.create<Position, Velocity>();
344 
345 // destroys an entity and all its components
346 registry.destroy(entity);
347 ```
348 
349 Once an entity is deleted, the registry can freely reuse it internally with a
350 slightly different identifier. In particular, the version of an entity is
351 increased each and every time it's destroyed.<br/>
352 In case entity identifiers are stored around, the registry offers all the
353 functionalities required to test them and get out of the them all the
354 information they carry:
355 
356 ```cpp
357 // returns true if the entity is still valid, false otherwise
358 bool b = registry.valid(entity);
359 
360 // gets the version contained in the entity identifier
361 auto version = registry.version(entity);
362 
363 // gets the actual version for the given entity
364 auto curr = registry.current(entity);
365 ```
366 
367 Components can be assigned to or removed from entities at any time with a few
368 calls to member functions of the registry. As for the entities, the registry
369 offers also a set of functionalities users can use to work with the components.
370 
371 The `assign` member function template creates, initializes and assigns to an
372 entity the given component. It accepts a variable number of arguments that are
373 used to construct the component itself if present:
374 
375 ```cpp
376 registry.assign<Position>(entity, 0., 0.);
377 
378 // ...
379 
380 auto &velocity = registry.assign<Velocity>(entity);
381 velocity.dx = 0.;
382 velocity.dy = 0.;
383 ```
384 
385 If the entity already has the given component, the `replace` member function
386 template can be used to replace it:
387 
388 ```cpp
389 registry.replace<Position>(entity, 0., 0.);
390 
391 // ...
392 
393 auto &velocity = registry.replace<Velocity>(entity);
394 velocity.dx = 0.;
395 velocity.dy = 0.;
396 ```
397 
398 In case users want to assign a component to an entity, but it's unknown whether
399 the entity already has it or not, `accomodate` does the work in a single call
400 (there is a performance penalty to pay for that mainly due to the fact that it
401 must check if `entity` already has the given component or not):
402 
403 ```cpp
404 registry.accomodate<Position>(entity, 0., 0.);
405 
406 // ...
407 
408 auto &velocity = registry.accomodate<Velocity>(entity);
409 velocity.dx = 0.;
410 velocity.dy = 0.;
411 ```
412 
413 Note that `accomodate` is a sliglhty faster alternative for the following
414 `if`/`else` statement and nothing more:
415 
416 ```cpp
417 if(registry.has<Comp>(entity)) {
418  registry.replace<Comp>(entity, arg1, argN);
419 } else {
420  registry.assign<Comp>(entity, arg1, argN);
421 }
422 ```
423 
424 As already shown, if in doubt about whether or not an entity has one or more
425 components, the `has` member function template may be useful:
426 
427 ```cpp
428 bool b = registry.has<Position, Velocity>(entity);
429 ```
430 
431 On the other side, if the goal is to delete a single component, the `remove`
432 member function template is the way to go when it's certain that the entity owns
433 a copy of the component:
434 
435 ```cpp
436 registry.remove<Position>(entity);
437 ```
438 
439 Otherwise consider to use the `reset` member function. It behaves similarly to
440 `remove` but with a strictly defined behaviour (and a performance penalty is the
441 price to pay for that). In particular it removes the component if and only if it
442 exists, otherwise it returns safely to the caller:
443 
444 ```cpp
445 registry.reset<Position>(entity);
446 ```
447 
448 There exist also two other _versions_ of the `reset` member function:
449 
450 * If no entity is passed to it, `reset` will remove the given component from
451 each entity that has it:
452 
453  ```cpp
454  registry.reset<Position>();
455  ```
456 
457 * If neither the entity nor the component are specified, all the entities and
458 their components are destroyed:
459 
460  ```cpp
461  registry.reset();
462  ```
463 
464 Finally, references to components can be retrieved simply by doing this:
465 
466 ```cpp
467 // either a non-const reference ...
468 entt::DefaultRegistry registry;
469 auto &position = registry.get<Position>(entity);
470 
471 // ... or a const one
472 const auto &cregistry = registry;
473 const auto &position = cregistry.get<Position>(entity);
474 ```
475 
476 The `get` member function template gives direct access to the component of an
477 entity stored in the underlying data structures of the registry.
478 
479 ### Single instance components
480 
481 In those cases where all what is needed is a single instance component, tags are
482 the right tool to achieve the purpose.<br/>
483 Tags undergo the same requirements of components. They can be either plain old
484 data structures or more complex and moveable data structures with a proper
485 constructor.<br/>
486 Actually, the same type can be used both as a tag and as a component and the
487 registry will not complain about it. It is up to the users to properly manage
488 their own types.
489 
490 Attaching tags to entities and removing them is trivial:
491 
492 ```cpp
493 auto player = registry.create();
494 auto camera = registry.create();
495 
496 // attaches a default-initialized tag to an entity
497 registry.attach<PlayingCharacter>(player);
498 
499 // attaches a tag to an entity and initializes it
500 registry.attach<Camera>(camera, player);
501 
502 // removes tags from their owners
503 registry.remove<PlayingCharacter>();
504 registry.remove<Camera>();
505 ```
506 
507 If in doubt about whether or not a tag has already an owner, the `has` member
508 function template may be useful:
509 
510 ```cpp
511 bool b = registry.has<PlayingCharacter>();
512 ```
513 
514 References to tags can be retrieved simply by doing this:
515 
516 ```cpp
517 // either a non-const reference ...
518 entt::DefaultRegistry registry;
519 auto &player = registry.get<PlayingCharacter>();
520 
521 // ... or a const one
522 const auto &cregistry = registry;
523 const auto &camera = cregistry.get<Camera>();
524 ```
525 
526 The `get` member function template gives direct access to the tag as stored in
527 the underlying data structures of the registry.
528 
529 As shown above, in almost all the cases the entity identifier isn't required,
530 since a single instance component can have only one associated entity and
531 therefore it doesn't make much sense to mention it explicitly.<br/>
532 To find out who the owner is, just do the following:
533 
534 ```cpp
535 auto player = registry.attachee<PlayingCharacter>();
536 ```
537 
538 Note that iterating tags isn't possible for obvious reasons. Tags give direct
539 access to single entities and nothing more.
540 
541 ### Sorting: is it possible?
542 
543 It goes without saying that sorting entities and components is possible with
544 `EnTT`.<br/>
545 In fact, there are two functions that respond to slightly different needs:
546 
547 * Components can be sorted directly:
548 
549  ```cpp
550  registry.sort<Renderable>([](const auto &lhs, const auto &rhs) {
551  return lhs.z < rhs.z;
552  });
553  ```
554 
555 * Components can be sorted according to the order imposed by another component:
556 
557  ```cpp
558  registry.sort<Movement, Physics>();
559  ```
560 
561  In this case, instances of `Movement` are arranged in memory so that cache
562  misses are minimized when the two components are iterated together.
563 
564 ## View: to persist or not to persist?
565 
566 There are mainly two kinds of views: standard (also known as View) and
567 persistent (alsa known as PersistentView).<br/>
568 Both of them have pros and cons to take in consideration. In particular:
569 
570 * Standard views:
571 
572  Pros:
573  * They work out-of-the-box and don't require any dedicated data
574  structure.
575  * Creating and destroying them isn't expensive at all because they don't
576  have any type of initialization.
577  * They are the best tool to iterate single components.
578  * They are the best tool to iterate multiple components at once when
579  tags are involved or one of the component is assigned to a
580  significantly low number of entities.
581  * They don't affect any other operations of the registry.
582 
583  Cons:
584  * Their performance tend to degenerate when the number of components
585  to iterate grows up and the most of the entities have all of them.
586 
587 * Persistent views:
588 
589  Pros:
590  * Once prepared, creating and destroying them isn't expensive at all
591  because they don't have any type of initialization.
592  * They are the best tool to iterate multiple components at once when
593  the most of the entities have all of them.
594 
595  Cons:
596  * They have dedicated data structures and thus affect the memory
597  pressure to a minimal extent.
598  * If not previously prepared, the first time they are used they go
599  through an initialization step that could take a while.
600  * They affect to a minimum the creation and destruction of entities and
601  components. In other terms: the more persistent views there will be,
602  the less performing will be creating and destroying entities and
603  components.
604 
605 To sum up and as a rule of thumb, use a standard view:
606 * To iterate entities for a single component.
607 * To iterate entities for multiple components when a significantly low
608  number of entities have one of the components.
609 * In all those cases where a persistent view would give a boost to
610  performance but the iteration isn't performed frequently.
611 
612 Use a persistent view in all the other cases.
613 
614 To easily iterate entities, all the views offer the common `begin` and `end`
615 member functions that allow users to use a view in a typical range-for
616 loop.<br/>
617 Continue reading for more details or refer to the
618 [official documentation](https://skypjack.github.io/entt/).
619 
620 ### Standard View
621 
622 A standard view behaves differently if it's constructed for a single component
623 or if it has been requested to iterate multiple components. Even the API is
624 different in the two cases.<br/>
625 All that they share is the way they are created by means of a registry:
626 
627 ```cpp
628 // single component standard view
629 auto single = registry.view<Position>();
630 
631 // multi component standard view
632 auto multi = registry.view<Position, Velocity>();
633 ```
634 
635 For all that remains, it's worth discussing them separately.<br/>
636 
637 #### Single component standard view
638 
639 Single component standard views are specialized in order to give a boost in
640 terms of performance in all the situation. This kind of views can access the
641 underlying data structures directly and avoid superflous checks.<br/>
642 They offer a bunch of functionalities to get the number of entities they are
643 going to return and a raw access to the entity list as well as to the component
644 list.<br/>
645 Refer to the [official documentation](https://skypjack.github.io/entt/) for all
646 the details.
647 
648 There is no need to store views around for they are extremely cheap to
649 construct, even though they can be copied without problems and reused
650 freely. In fact, they return newly created and correctly initialized iterators
651 whenever `begin` or `end` are invoked.<br/>
652 To iterate a single component standard view, either use it in range-for loop:
653 
654 ```cpp
655 auto view = registry.view<Renderable>();
656 
657 for(auto entity: view) {
658  auto &renderable = view.get(entity);
659 
660  // ...
661 }
662 ```
663 
664 Or rely on the `each` member function to iterate entities and get all their
665 components at once:
666 
667 ```cpp
668 registry.view<Renderable>().each([](auto entity, auto &renderable) {
669  // ...
670 });
671 ```
672 
673 Performance are more or less the same. The best approach depends mainly on
674 whether all the components have to be accessed or not.
675 
676 **Note**: prefer the `get` member function of a view instead of the `get` member
677 function template of a registry during iterations, if possible. However, keep in
678 mind that it works only with the components of the view itself.
679 
680 #### Multi component standard view
681 
682 Multi component standard views iterate entities that have at least all the given
683 components in their bags. During construction, these views look at the number
684 of entities available for each component and pick up a reference to the smallest
685 set of candidates in order to speed up iterations.<br/>
686 They offer fewer functionalities than their companion views for single
687 component, the most important of which can be used to reset the view and refresh
688 the reference to the set of candidate entities to iterate.<br/>
689 Refer to the [official documentation](https://skypjack.github.io/entt/) for all
690 the details.
691 
692 There is no need to store views around for they are extremely cheap to
693 construct, even though they can be copied without problems and reused
694 freely. In fact, they return newly created and correctly initialized iterators
695 whenever `begin` or `end` are invoked.<br/>
696 To iterate a multi component standard view, either use it in range-for loop:
697 
698 ```cpp
699 auto view = registry.view<Position, Velocity>();
700 
701 for(auto entity: view) {
702  auto &position = view.get<Position>(entity);
703  auto &velocity = view.get<Velocity>(entity);
704 
705  // ...
706 }
707 ```
708 
709 Or rely on the `each` member function to iterate entities and get all their
710 components at once:
711 
712 ```cpp
713 registry.view<Position, Velocity>().each([](auto entity, auto &position, auto &velocity) {
714  // ...
715 });
716 ```
717 
718 Performance are more or less the same. The best approach depends mainly on
719 whether all the components have to be accessed or not.
720 
721 **Note**: prefer the `get` member function of a view instead of the `get` member
722 function template of a registry during iterations, if possible. However, keep in
723 mind that it works only with the components of the view itself.
724 
725 ### Persistent View
726 
727 A persistent view returns all the entities and only the entities that have at
728 least the given components. Moreover, it's guaranteed that the entity list is
729 thightly packed in memory for fast iterations.<br/>
730 In general, persistent views don't stay true to the order of any set of
731 components unless users explicitly sort them.
732 
733 Persistent views can be used only to iterate multiple components. Create them
734 as it follows:
735 
736 ```cpp
737 auto view = registry.persistent<Position, Velocity>();
738 ```
739 
740 There is no need to store views around for they are extremely cheap to
741 construct, even though they can be copied without problems and reused
742 freely. In fact, they return newly created and correctly initialized iterators
743 whenever `begin` or `end` are invoked.<br/>
744 That being said, persistent views perform an initialization step the very first
745 time they are constructed and this could be quite costly. To avoid it, consider
746 asking to the registry to _prepare_ them when no entities have been created yet:
747 
748 ```cpp
749 registry.prepare<Position, Velocity>();
750 ```
751 
752 If the registry is empty, preparation is extremely fast. Moreover the `prepare`
753 member function template is idempotent. Feel free to invoke it even more than
754 once: if the view has been alreadt prepared before, the function returns
755 immediately and does nothing.
756 
757 A persistent view offers a bunch of functionalities to get the number of
758 entities it's going to return, a raw access to the entity list and the
759 possibility to sort the underlying data structures according to the order of one
760 of the components for which it has been constructed.<br/>
761 Refer to the [official documentation](https://skypjack.github.io/entt/) for all
762 the details.
763 
764 To iterate a persistent view, either use it in range-for loop:
765 
766 ```cpp
767 auto view = registry.persistent<Position, Velocity>();
768 
769 for(auto entity: view) {
770  auto &position = view.get<Position>(entity);
771  auto &velocity = view.get<Velocity>(entity);
772 
773  // ...
774 }
775 ```
776 
777 Or rely on the `each` member function to iterate entities and get all their
778 components at once:
779 
780 ```cpp
781 registry.persistent<Position, Velocity>().each([](auto entity, auto &position, auto &velocity) {
782  // ...
783 });
784 ```
785 
786 Performance are more or less the same. The best approach depends mainly on
787 whether all the components have to be accessed or not.
788 
789 **Note**: prefer the `get` member function of a view instead of the `get` member
790 function template of a registry during iterations, if possible. However, keep in
791 mind that it works only with the components of the view itself.
792 
793 ## Side notes
794 
795 * Entity identifiers are numbers and nothing more. They are not classes and they
796  have no member functions at all. As already mentioned, do no try to inspect or
797  modify an entity descriptor in any way.
798 
799 * As shown in the examples above, the preferred way to get references to the
800  components while iterating a view is by using the view itself. It's a faster
801  alternative to the `get` member function template that is part of the API of
802  the Registry. That's because the registry must ensure that a pool for the
803  given component exists before to use it; on the other side, views force the
804  construction of the pools for all their components and access them directly,
805  thus avoiding all the checks.
806 
807 * Most of the _ECS_ available out there have an annoying limitation (at least
808  from my point of view): entities and components cannot be created and/or
809  deleted during iterations.<br/>
810  `EnTT` partially solves the problem with a few limitations:
811 
812  * Creating entities and components is allowed during iterations.
813  * Deleting an entity or removing its components is allowed during
814  iterations if it's the one currently returned by a view. For all the
815  other entities, destroying them or removing their components isn't
816  allowed and it can result in undefined behavior.
817 
818  Iterators are invalidated and the behaviour is undefined if an entity is
819  modified or destroyed and it's not the one currently returned by the
820  view.<br/>
821  To work around it, possible approaches are:
822 
823  * Store aside the entities and the components to be removed and perform the
824  operations at the end of the iteration.
825  * Mark entities and components with a proper tag component that indicates
826  they must be purged, then perform a second iteration to clean them up one
827  by one.
828 
829 * Views and thus their iterators aren't thread safe. Do no try to iterate a set
830  of components and modify the same set concurrently.<br/>
831  That being said, as long as a thread iterates the entities that have the
832  component `X` or assign and removes that component from a set of entities,
833  another thread can safely do the same with components `Y` and `Z` and
834  everything will work like a charm.<br/>
835  As an example, users can freely execute the rendering system and iterate the
836  renderable entities while updating a physic component concurrently on a
837  separate thread if needed.
838 
839 # Contributors
840 
841 If you want to contribute, please send patches as pull requests against the
842 branch `master`.<br/>
843 Check the
844 [contributors list](https://github.com/skypjack/entt/blob/master/AUTHORS) to see
845 who has partecipated so far.
846 
847 # License
848 
849 Code and documentation Copyright (c) 2017 Michele Caini.<br/>
850 Code released under
851 [the MIT license](https://github.com/skypjack/entt/blob/master/LICENSE).
852 Docs released under
853 [Creative Commons](https://github.com/skypjack/entt/blob/master/docs/LICENSE).
854 
855 # Donation
856 
857 Developing and maintaining `EnTT` takes some time and lots of coffee. I'd like
858 to add more and more functionalities in future and turn it in a full-featured
859 framework.<br/>
860 If you want to support this project, you can offer me an espresso. I'm from
861 Italy, we're used to turning the best coffee ever in code. If you find that
862 it's not enough, feel free to support me the way you prefer.<br/>
863 Take a look at the donation button at the top of the page for more details or
864 just click [here](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted).
+
1 # EnTT Framework
2 
3 [![Build Status](https://travis-ci.org/skypjack/entt.svg?branch=master)](https://travis-ci.org/skypjack/entt)
4 [![Build status](https://ci.appveyor.com/api/projects/status/rvhaabjmghg715ck?svg=true)](https://ci.appveyor.com/project/skypjack/entt)
5 [![Coverage Status](https://coveralls.io/repos/github/skypjack/entt/badge.svg?branch=master)](https://coveralls.io/github/skypjack/entt?branch=master)
6 [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
7 
8 # Introduction
9 
10 `EnTT` is a header-only, tiny and easy to use framework written in modern
11 C++.<br/>
12 It was originally designed entirely around an architectural pattern called _ECS_
13 that is used mostly in game development. For further details:
14 
15 * [Entity Systems Wiki](http://entity-systems.wikidot.com/)
16 * [Evolve Your Hierarchy](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/)
17 * [ECS on Wikipedia](https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system)
18 
19 A long time ago, the sole entity-component system was part of the project. After
20 a while the codebase has grown and more and more classes have become part
21 of the repository.<br/>
22 That's why today it's called _the EnTT Framework_.
23 
24 Currently, `EnTT` is tested on Linux, Microsoft Windows and OS X. It has proven
25 to work also on both Android and iOS.<br/>
26 Most likely it will not be problematic on other systems as well, but has not
27 been sufficiently tested so far.
28 
29 ## The framework
30 
31 `EnTT` was written initially as a faster alternative to other well known and
32 open source entity-component systems. Nowadays the `EnTT` framework is moving
33 its first steps. Much more will come in the future and hopefully I'm going to
34 work on it for a long time.<br/>
35 Requests for feature, PR, suggestions ad feedback are highly appreciated.
36 
37 If you find you can help me and want to contribute to the `EnTT` framework with
38 your experience or you do want to get part of the project for some other
39 reason, feel free to contact me directly (you can find the mail in the
40 [profile](https://github.com/skypjack)).<br/>
41 I can't promise that each and every contribution will be accepted, but I can
42 assure that I'll do my best to take them all seriously.
43 
44 ### State of the art
45 
46 Here is a brief list of what it offers today:
47 
48 * Statically generated integer identifiers for types (assigned either at
49 compile-time or at runtime).
50 * A constexpr utility for human readable resource identifiers.
51 * An incredibly fast entity-component system based on sparse sets, with its own
52 views and a _pay for what you use_ policy to adjust performance and memory
53 pressure according to the users' requirements.
54 * Actor class for those who aren't confident with entity-component systems.
55 * The smallest and most basic implementation of a service locator ever seen.
56 * A cooperative scheduler for processes of any type.
57 * All what is needed for resource management (cache, loaders, handles).
58 * Signal handlers of any type, delegates and an event bus.
59 * A general purpose event emitter, that is a CRTP idiom based class template.
60 * An event dispatcher for immediate and delayed events to integrate in loops.
61 * ...
62 * Any other business.
63 
64 Consider it a work in progress. For more details and an updated list, please
65 refer to the [online documentation](https://skypjack.github.io/entt/).
66 
67 ### A note about the README
68 
69 The README file stays true to the original project and it describes only the
70 entity-component system. However, the whole API is fully documented in-code and
71 the [online documentation](https://skypjack.github.io/entt/) contains much
72 more.<br/>
73 Continue reading to know how the core part of the project works or follow the
74 link above to take a look at the API reference for all other available classes.
75 
76 ## Code Example
77 
78 ```cpp
79 #include <entt/entt.hpp>
80 #include <cstdint>
81 
82 struct Position {
83  float x;
84  float y;
85 };
86 
87 struct Velocity {
88  float dx;
89  float dy;
90 };
91 
92 void update(entt::DefaultRegistry &registry) {
93  auto view = registry.view<Position, Velocity>();
94 
95  for(auto entity: view) {
96  // gets only the components that are going to be used ...
97 
98  auto &velocity = view.get<Velocity>(entity);
99 
100  velocity.dx = 0.;
101  velocity.dy = 0.;
102 
103  // ...
104  }
105 }
106 
107 void update(std::uint64_t dt, entt::DefaultRegistry &registry) {
108  registry.view<Position, Velocity>().each([dt](auto entity, auto &position, auto &velocity) {
109  // gets all the components of the view at once ...
110 
111  position.x += velocity.dx * dt;
112  position.y += velocity.dy * dt;
113 
114  // ...
115  });
116 }
117 
118 int main() {
119  entt::DefaultRegistry registry;
120  std::uint64_t dt = 16;
121 
122  for(auto i = 0; i < 10; ++i) {
123  auto entity = registry.create(Position{i * 1.f, i * 1.f});
124  if(i % 2 == 0) { registry.assign<Velocity>(entity, i * .1f, i * .1f); }
125  }
126 
127  update(dt, registry);
128  update(registry);
129 
130  // ...
131 }
132 ```
133 
134 ## Motivation
135 
136 I started working on `EnTT` because of the wrong reason: my goal was to design
137 an entity-component system that beated another well known open source solution
138 in terms of performance.<br/>
139 In the end, I did it, but it wasn't much satisfying. Actually it wasn't
140 satisfying at all. The fastest and nothing more, fairly little indeed. When I
141 realized it, I tried hard to keep intact the great performance of `EnTT` and to
142 add all the features I wanted to see in *my* entity-component system at the same
143 time.
144 
145 Today `EnTT` is finally what I was looking for: still faster than its
146 _competitors_, a really good API and an amazing set of features. And even more,
147 of course.
148 
149 ## Performance
150 
151 As it stands right now, `EnTT` is just fast enough for my requirements if
152 compared to my first choice (it was already amazingly fast actually).<br/>
153 Here is a comparision between the two (both of them compiled with GCC 7.2.0 on a
154 Dell XPS 13 out of the mid 2014):
155 
156 | Benchmark | EntityX (compile-time) | EnTT |
157 |-----------|-------------|-------------|
158 | Create 10M entities | 0.1289s | **0.0409s** |
159 | Destroy 10M entities | **0.0531s** | 0.0546s |
160 | Standard view, 10M entities, one component | 0.0107s | **1.6e-07s** |
161 | Standard view, 10M entities, two components | **0.0113s** | 0.0295s |
162 | Standard view, 10M entities, two components<br/>Half of the entities have all the components | **0.0078s** | 0.0150s |
163 | Standard view, 10M entities, two components<br/>One of the entities has all the components | 0.0071s | **8.8e-07s** |
164 | Persistent view, 10M entities, two components | 0.0113s | **5.7e-07s** |
165 | Standard view, 10M entities, five components | **0.0091s** | 0.0688s |
166 | Persistent view, 10M entities, five components | 0.0091s | **2.9e-07s** |
167 | Standard view, 10M entities, ten components | **0.0105s** | 0.1403s |
168 | Standard view, 10M entities, ten components<br/>Half of the entities have all the components | **0.0090s** | 0.0620s |
169 | Standard view, 10M entities, ten components<br/>One of the entities has all the components | 0.0070s | **1.3e-06s** |
170 | Persistent view, 10M entities, ten components | 0.0105s | **6.2e-07s** |
171 | Sort 150k entities, one component<br/>Arrays are in reverse order | - | **0.0043s** |
172 | Sort 150k entities, enforce permutation<br/>Arrays are in reverse order | - | **0.0006s** |
173 
174 `EnTT` includes its own tests and benchmarks. See
175 [benchmark.cpp](https://github.com/skypjack/entt/blob/master/test/benchmark.cpp)
176 for further details.<br/>
177 On Github users can find also a
178 [benchmark suite](https://github.com/abeimler/ecs_benchmark) that compares a
179 bunch of different projects, one of which is `EnTT`.
180 
181 Probably I'll try to get out of `EnTT` more features and better performance in
182 the future, mainly for fun.<br/>
183 If you want to contribute and/or have any suggestion, feel free to make a PR or
184 open an issue to discuss your idea.
185 
186 # Build Instructions
187 
188 ## Requirements
189 
190 To be able to use `EnTT`, users must provide a full-featured compiler that
191 supports at least C++14.<br/>
192 The requirements below are mandatory to compile the tests and to extract the
193 documentation:
194 
195 * CMake version 3.2 or later.
196 * Doxygen version 1.8 or later.
197 
198 ## Library
199 
200 `EnTT` is a header-only library. This means that including the `entt.hpp`
201 header is enough to include the whole framework and use it. For those who are
202 interested only in the entity-component system, consider to include the sole
203 `entity/registry.hpp` header instead.<br/>
204 It's a matter of adding the following line to the top of a file:
205 
206 ```cpp
207 #include <entt/entt.hpp>
208 ```
209 
210 Use the line below to include only the entity-component system instead:
211 
212 ```cpp
213 #include <entt/entity/registry.hpp>
214 ```
215 
216 Then pass the proper `-I` argument to the compiler to add the `src` directory to
217 the include paths.
218 
219 ## Documentation
220 
221 The documentation is based on [doxygen](http://www.stack.nl/~dimitri/doxygen/).
222 To build it:
223 
224  $ cd build
225  $ cmake ..
226  $ make docs
227 
228 The API reference will be created in HTML format within the directory
229 `build/docs/html`. To navigate it with your favorite browser:
230 
231  $ cd build
232  $ your_favorite_browser docs/html/index.html
233 
234 The API reference is also available [online](https://skypjack.github.io/entt/)
235 for the latest version.
236 
237 ## Tests
238 
239 To compile and run the tests, `EnTT` requires *googletest*.<br/>
240 `cmake` will download and compile the library before to compile anything else.
241 
242 To build the tests:
243 
244 * `$ cd build`
245 * `$ cmake ..`
246 * `$ make`
247 * `$ make test`
248 
249 To build the benchmarks, use the following line instead:
250 
251 * `$ cmake -DCMAKE_BUILD_TYPE=Release ..`
252 
253 Benchmarks are compiled only in release mode currently.
254 
255 # Crash Course
256 
257 ## Design choices
258 
259 ### A bitset-free entity-component system
260 
261 `EnTT` is a _bitset-free_ entity-component system that doesn't require users to
262 specify the component set at compile-time.<br/>
263 This is why users can instantiate the core class simply like:
264 
265 ```cpp
266 entt::DefaultRegistry registry;
267 ```
268 
269 In place of its more annoying and error-prone counterpart:
270 
271 ```cpp
272 entt::DefaultRegistry<Comp0, Comp1, ..., CompN> registry;
273 ```
274 
275 ### Pay per use
276 
277 `EnTT` is entirely designed around the principle that users have to pay only for
278 what they want.
279 
280 When it comes to using an entity-componet system, the tradeoff is usually
281 between performance and memory usage. The faster it is, the more memory it uses.
282 However, slightly worse performance along non-critical paths are the right price
283 to pay to reduce memory usage and I've always wondered why this kind of tools do
284 not leave me the choice.<br/>
285 `EnTT` follows a completely different approach. It squezees the best from the
286 basic data structures and gives users the possibility to pay more for higher
287 performance where needed.<br/>
288 The disadvantage of this approach is that users need to know the systems they
289 are working on and the tools they are using. Otherwise, the risk to ruin the
290 performance along critical paths is high.
291 
292 So far, this choice has proven to be a good one and I really hope it can be for
293 many others besides me.
294 
295 ## Vademecum
296 
297 The `Registry` to store, the `View`s to iterate. That's all.
298 
299 An entity (the _E_ of an _ECS_) is an opaque identifier that users should just
300 use as-is and store around if needed. Do not try to inspect an entity
301 identifier, its type can change in future and a registry offers all the
302 functionalities to query them out-of-the-box. The underlying type of an entity
303 (either `std::uint16_t`, `std::uint32_t` or `std::uint64_t`) can be specified
304 when defining a registry (actually the DefaultRegistry is nothing more than a
305 Registry where the type of the entities is `std::uint32_t`).<br/>
306 Components (the _C_ of an _ECS_) should be plain old data structures or more
307 complex and moveable data structures with a proper constructor. Actually, the
308 sole requirement of a component type is that it must be both move constructible
309 and move assignable. They are list initialized by using the parameters provided
310 to construct the component itself. No need to register components or their types
311 neither with the registry nor with the entity-component system at all.<br/>
312 Systems (the _S_ of an _ECS_) are just plain functions, functors, lambdas or
313 whatever the users want. They can accept a Registry, a View or a PersistentView
314 and use them the way they prefer. No need to register systems or their types
315 neither with the registry nor with the entity-component system at all.
316 
317 The following sections will explain in short how to use the entity-component
318 system, the core part of the whole framework.<br/>
319 In fact, the framework is composed of many other classes in addition to those
320 describe below. For more details, please refer to the
321 [online documentation](https://skypjack.github.io/entt/).
322 
323 ## The Registry, the Entity and the Component
324 
325 A registry is used to store and manage entities as well as to create views to
326 iterate the underlying data structures.<br/>
327 Registry is a class template that lets the users decide what's the preferred
328 type to represent an entity. Because `std::uint32_t` is large enough for almost
329 all the cases, there exists also an alias named DefaultRegistry for
330 `Registry<std::uint32_t>`.
331 
332 Entities are represented by _entitiy identifiers_. An entity identifier is an
333 opaque type that users should not inspect or modify in any way. It carries
334 information about the entity itself and its version.
335 
336 A registry can be used both to construct and to destroy entities:
337 
338 ```cpp
339 // constructs a naked entity with no components ad returns its identifier
340 auto entity = registry.create();
341 
342 // constructs an entity and assigns it default-initialized components
343 auto another = registry.create<Position, Velocity>();
344 
345 // destroys an entity and all its components
346 registry.destroy(entity);
347 ```
348 
349 Once an entity is deleted, the registry can freely reuse it internally with a
350 slightly different identifier. In particular, the version of an entity is
351 increased each and every time it's destroyed.<br/>
352 In case entity identifiers are stored around, the registry offers all the
353 functionalities required to test them and get out of the them all the
354 information they carry:
355 
356 ```cpp
357 // returns true if the entity is still valid, false otherwise
358 bool b = registry.valid(entity);
359 
360 // gets the version contained in the entity identifier
361 auto version = registry.version(entity);
362 
363 // gets the actual version for the given entity
364 auto curr = registry.current(entity);
365 ```
366 
367 Components can be assigned to or removed from entities at any time with a few
368 calls to member functions of the registry. As for the entities, the registry
369 offers also a set of functionalities users can use to work with the components.
370 
371 The `assign` member function template creates, initializes and assigns to an
372 entity the given component. It accepts a variable number of arguments that are
373 used to construct the component itself if present:
374 
375 ```cpp
376 registry.assign<Position>(entity, 0., 0.);
377 
378 // ...
379 
380 auto &velocity = registry.assign<Velocity>(entity);
381 velocity.dx = 0.;
382 velocity.dy = 0.;
383 ```
384 
385 If the entity already has the given component, the `replace` member function
386 template can be used to replace it:
387 
388 ```cpp
389 registry.replace<Position>(entity, 0., 0.);
390 
391 // ...
392 
393 auto &velocity = registry.replace<Velocity>(entity);
394 velocity.dx = 0.;
395 velocity.dy = 0.;
396 ```
397 
398 In case users want to assign a component to an entity, but it's unknown whether
399 the entity already has it or not, `accomodate` does the work in a single call
400 (there is a performance penalty to pay for this mainly due to the fact that it
401 has to check if `entity` already has the given component or not):
402 
403 ```cpp
404 registry.accomodate<Position>(entity, 0., 0.);
405 
406 // ...
407 
408 auto &velocity = registry.accomodate<Velocity>(entity);
409 velocity.dx = 0.;
410 velocity.dy = 0.;
411 ```
412 
413 Note that `accomodate` is a sliglhty faster alternative for the following
414 `if`/`else` statement and nothing more:
415 
416 ```cpp
417 if(registry.has<Comp>(entity)) {
418  registry.replace<Comp>(entity, arg1, argN);
419 } else {
420  registry.assign<Comp>(entity, arg1, argN);
421 }
422 ```
423 
424 As already shown, if in doubt about whether or not an entity has one or more
425 components, the `has` member function template may be useful:
426 
427 ```cpp
428 bool b = registry.has<Position, Velocity>(entity);
429 ```
430 
431 On the other side, if the goal is to delete a single component, the `remove`
432 member function template is the way to go when it's certain that the entity owns
433 a copy of the component:
434 
435 ```cpp
436 registry.remove<Position>(entity);
437 ```
438 
439 Otherwise consider to use the `reset` member function. It behaves similarly to
440 `remove` but with a strictly defined behaviour (and a performance penalty is the
441 price to pay for this). In particular it removes the component if and only if it
442 exists, otherwise it returns safely to the caller:
443 
444 ```cpp
445 registry.reset<Position>(entity);
446 ```
447 
448 There exist also two other _versions_ of the `reset` member function:
449 
450 * If no entity is passed to it, `reset` will remove the given component from
451 each entity that has it:
452 
453  ```cpp
454  registry.reset<Position>();
455  ```
456 
457 * If neither the entity nor the component are specified, all the entities and
458 their components are destroyed:
459 
460  ```cpp
461  registry.reset();
462  ```
463 
464 Finally, references to components can be retrieved simply by doing this:
465 
466 ```cpp
467 // either a non-const reference ...
468 entt::DefaultRegistry registry;
469 auto &position = registry.get<Position>(entity);
470 
471 // ... or a const one
472 const auto &cregistry = registry;
473 const auto &position = cregistry.get<Position>(entity);
474 ```
475 
476 The `get` member function template gives direct access to the component of an
477 entity stored in the underlying data structures of the registry.
478 
479 ### Single instance components
480 
481 In those cases where all what is needed is a single instance component, tags are
482 the right tool to achieve the purpose.<br/>
483 Tags undergo the same requirements of components. They can be either plain old
484 data structures or more complex and moveable data structures with a proper
485 constructor.<br/>
486 Actually, the same type can be used both as a tag and as a component and the
487 registry will not complain about it. It is up to the users to properly manage
488 their own types.
489 
490 Attaching tags to entities and removing them is trivial:
491 
492 ```cpp
493 auto player = registry.create();
494 auto camera = registry.create();
495 
496 // attaches a default-initialized tag to an entity
497 registry.attach<PlayingCharacter>(player);
498 
499 // attaches a tag to an entity and initializes it
500 registry.attach<Camera>(camera, player);
501 
502 // removes tags from their owners
503 registry.remove<PlayingCharacter>();
504 registry.remove<Camera>();
505 ```
506 
507 If in doubt about whether or not a tag has already an owner, the `has` member
508 function template may be useful:
509 
510 ```cpp
511 bool b = registry.has<PlayingCharacter>();
512 ```
513 
514 References to tags can be retrieved simply by doing this:
515 
516 ```cpp
517 // either a non-const reference ...
518 entt::DefaultRegistry registry;
519 auto &player = registry.get<PlayingCharacter>();
520 
521 // ... or a const one
522 const auto &cregistry = registry;
523 const auto &camera = cregistry.get<Camera>();
524 ```
525 
526 The `get` member function template gives direct access to the tag as stored in
527 the underlying data structures of the registry.
528 
529 As shown above, in almost all the cases the entity identifier isn't required,
530 since a single instance component can have only one associated entity and
531 therefore it doesn't make much sense to mention it explicitly.<br/>
532 To find out who the owner is, just do the following:
533 
534 ```cpp
535 auto player = registry.attachee<PlayingCharacter>();
536 ```
537 
538 Note that iterating tags isn't possible for obvious reasons. Tags give direct
539 access to single entities and nothing more.
540 
541 ### Runtime components
542 
543 Defining components at runtime is useful to support plugins and mods in general.
544 However, it seems impossible with a tool designed around a bunch of templates.
545 Indeed it's not that difficult.<br/>
546 Of course, some features cannot be easily exported into a runtime
547 environment. As an example, sorting a group of components defined at runtime
548 isn't for free if compared to most of the other operations. However, the basic
549 functionalities of an entity-component system such as `EnTT` fit the problem
550 perfectly and can also be used to manage runtime components if required.<br/>
551 All that is necessary to do it is to know the identifiers of the components. An
552 identifier is nothing more than a number or similar that can be used at runtime
553 to work with the type system.
554 
555 In `EnTT`, identifiers are easily accessible:
556 
557 ```cpp
558 entt::DefaultRegistry registry;
559 
560 // standard component identifier
561 auto ctype = registry.component<Position>();
562 
563 // single instance component identifier
564 auto ttype = registry.tag<PlayingCharacter>();
565 ```
566 
567 Once the identifiers are made available, almost everything becomes pretty
568 simple.
569 
570 #### A journey through a plugin
571 
572 `EnTT` comes with an example (actually a test) that shows how to integrate
573 compile-time and runtime components in a stack based JavaScript environment. It
574 uses [`duktape`](https://github.com/svaarala/duktape) under the hood, mainly
575 because I wanted to learn how it works at the time I was writing the code.
576 
577 It's not production-ready and overall performance can be highly improved.
578 However, I sacrificed optimizations in favor of a more readable piece of
579 code. I hope I succeeded.<br/>
580 Note also that this isn't neither the only nor (probably) the best way to do it.
581 In fact, the right way depends on the scripting language and the problem one is
582 facing in general.
583 
584 The basic idea is that of creating a compile-time component aimed to map all the
585 runtime components assigned to an entity.<br/>
586 Identifiers come in use to address the right function from a map when invoked
587 from the runtime environment and to filter entities when iterating.<br/>
588 With a bit of gymnastic, one can narrow views and improve the performance to
589 some extent but it was not the goal of the example.
590 
591 ### Sorting: is it possible?
592 
593 It goes without saying that sorting entities and components is possible with
594 `EnTT`.<br/>
595 In fact, there are two functions that respond to slightly different needs:
596 
597 * Components can be sorted directly:
598 
599  ```cpp
600  registry.sort<Renderable>([](const auto &lhs, const auto &rhs) {
601  return lhs.z < rhs.z;
602  });
603  ```
604 
605 * Components can be sorted according to the order imposed by another component:
606 
607  ```cpp
608  registry.sort<Movement, Physics>();
609  ```
610 
611  In this case, instances of `Movement` are arranged in memory so that cache
612  misses are minimized when the two components are iterated together.
613 
614 ## View: to persist or not to persist?
615 
616 There are mainly two kinds of views: standard (also known as View) and
617 persistent (alsa known as PersistentView).<br/>
618 Both of them have pros and cons to take in consideration. In particular:
619 
620 * Standard views:
621 
622  Pros:
623  * They work out-of-the-box and don't require any dedicated data
624  structure.
625  * Creating and destroying them isn't expensive at all because they don't
626  have any type of initialization.
627  * They are the best tool to iterate single components.
628  * They are the best tool to iterate multiple components at once when
629  tags are involved or one of the component is assigned to a
630  significantly low number of entities.
631  * They don't affect any other operations of the registry.
632 
633  Cons:
634  * Their performance tend to degenerate when the number of components
635  to iterate grows up and the most of the entities have all of them.
636 
637 * Persistent views:
638 
639  Pros:
640  * Once prepared, creating and destroying them isn't expensive at all
641  because they don't have any type of initialization.
642  * They are the best tool to iterate multiple components at once when
643  the most of the entities have all of them.
644 
645  Cons:
646  * They have dedicated data structures and thus affect the memory
647  pressure to a minimal extent.
648  * If not previously prepared, the first time they are used they go
649  through an initialization step that could take a while.
650  * They affect to a minimum the creation and destruction of entities and
651  components. In other terms: the more persistent views there will be,
652  the less performing will be creating and destroying entities and
653  components.
654 
655 To sum up and as a rule of thumb, use a standard view:
656 * To iterate entities for a single component.
657 * To iterate entities for multiple components when a significantly low
658  number of entities have one of the components.
659 * In all those cases where a persistent view would give a boost to
660  performance but the iteration isn't performed frequently.
661 
662 Use a persistent view in all the other cases.
663 
664 To easily iterate entities, all the views offer the common `begin` and `end`
665 member functions that allow users to use a view in a typical range-for
666 loop.<br/>
667 Continue reading for more details or refer to the
668 [official documentation](https://skypjack.github.io/entt/).
669 
670 ### Standard View
671 
672 A standard view behaves differently if it's constructed for a single component
673 or if it has been requested to iterate multiple components. Even the API is
674 different in the two cases.<br/>
675 All that they share is the way they are created by means of a registry:
676 
677 ```cpp
678 // single component standard view
679 auto single = registry.view<Position>();
680 
681 // multi component standard view
682 auto multi = registry.view<Position, Velocity>();
683 ```
684 
685 For all that remains, it's worth discussing them separately.<br/>
686 
687 #### Single component standard view
688 
689 Single component standard views are specialized in order to give a boost in
690 terms of performance in all the situation. This kind of views can access the
691 underlying data structures directly and avoid superflous checks.<br/>
692 They offer a bunch of functionalities to get the number of entities they are
693 going to return and a raw access to the entity list as well as to the component
694 list.<br/>
695 Refer to the [official documentation](https://skypjack.github.io/entt/) for all
696 the details.
697 
698 There is no need to store views around for they are extremely cheap to
699 construct, even though they can be copied without problems and reused
700 freely. In fact, they return newly created and correctly initialized iterators
701 whenever `begin` or `end` are invoked.<br/>
702 To iterate a single component standard view, either use it in range-for loop:
703 
704 ```cpp
705 auto view = registry.view<Renderable>();
706 
707 for(auto entity: view) {
708  auto &renderable = view.get(entity);
709 
710  // ...
711 }
712 ```
713 
714 Or rely on the `each` member function to iterate entities and get all their
715 components at once:
716 
717 ```cpp
718 registry.view<Renderable>().each([](auto entity, auto &renderable) {
719  // ...
720 });
721 ```
722 
723 Performance are more or less the same. The best approach depends mainly on
724 whether all the components have to be accessed or not.
725 
726 **Note**: prefer the `get` member function of a view instead of the `get` member
727 function template of a registry during iterations, if possible. However, keep in
728 mind that it works only with the components of the view itself.
729 
730 #### Multi component standard view
731 
732 Multi component standard views iterate entities that have at least all the given
733 components in their bags. During construction, these views look at the number
734 of entities available for each component and pick up a reference to the smallest
735 set of candidates in order to speed up iterations.<br/>
736 They offer fewer functionalities than their companion views for single
737 component, the most important of which can be used to reset the view and refresh
738 the reference to the set of candidate entities to iterate.<br/>
739 Refer to the [official documentation](https://skypjack.github.io/entt/) for all
740 the details.
741 
742 There is no need to store views around for they are extremely cheap to
743 construct, even though they can be copied without problems and reused
744 freely. In fact, they return newly created and correctly initialized iterators
745 whenever `begin` or `end` are invoked.<br/>
746 To iterate a multi component standard view, either use it in range-for loop:
747 
748 ```cpp
749 auto view = registry.view<Position, Velocity>();
750 
751 for(auto entity: view) {
752  auto &position = view.get<Position>(entity);
753  auto &velocity = view.get<Velocity>(entity);
754 
755  // ...
756 }
757 ```
758 
759 Or rely on the `each` member function to iterate entities and get all their
760 components at once:
761 
762 ```cpp
763 registry.view<Position, Velocity>().each([](auto entity, auto &position, auto &velocity) {
764  // ...
765 });
766 ```
767 
768 Performance are more or less the same. The best approach depends mainly on
769 whether all the components have to be accessed or not.
770 
771 **Note**: prefer the `get` member function of a view instead of the `get` member
772 function template of a registry during iterations, if possible. However, keep in
773 mind that it works only with the components of the view itself.
774 
775 ### Persistent View
776 
777 A persistent view returns all the entities and only the entities that have at
778 least the given components. Moreover, it's guaranteed that the entity list is
779 thightly packed in memory for fast iterations.<br/>
780 In general, persistent views don't stay true to the order of any set of
781 components unless users explicitly sort them.
782 
783 Persistent views can be used only to iterate multiple components. Create them
784 as it follows:
785 
786 ```cpp
787 auto view = registry.persistent<Position, Velocity>();
788 ```
789 
790 There is no need to store views around for they are extremely cheap to
791 construct, even though they can be copied without problems and reused
792 freely. In fact, they return newly created and correctly initialized iterators
793 whenever `begin` or `end` are invoked.<br/>
794 That being said, persistent views perform an initialization step the very first
795 time they are constructed and this could be quite costly. To avoid it, consider
796 asking to the registry to _prepare_ them when no entities have been created yet:
797 
798 ```cpp
799 registry.prepare<Position, Velocity>();
800 ```
801 
802 If the registry is empty, preparation is extremely fast. Moreover the `prepare`
803 member function template is idempotent. Feel free to invoke it even more than
804 once: if the view has been alreadt prepared before, the function returns
805 immediately and does nothing.
806 
807 A persistent view offers a bunch of functionalities to get the number of
808 entities it's going to return, a raw access to the entity list and the
809 possibility to sort the underlying data structures according to the order of one
810 of the components for which it has been constructed.<br/>
811 Refer to the [official documentation](https://skypjack.github.io/entt/) for all
812 the details.
813 
814 To iterate a persistent view, either use it in range-for loop:
815 
816 ```cpp
817 auto view = registry.persistent<Position, Velocity>();
818 
819 for(auto entity: view) {
820  auto &position = view.get<Position>(entity);
821  auto &velocity = view.get<Velocity>(entity);
822 
823  // ...
824 }
825 ```
826 
827 Or rely on the `each` member function to iterate entities and get all their
828 components at once:
829 
830 ```cpp
831 registry.persistent<Position, Velocity>().each([](auto entity, auto &position, auto &velocity) {
832  // ...
833 });
834 ```
835 
836 Performance are more or less the same. The best approach depends mainly on
837 whether all the components have to be accessed or not.
838 
839 **Note**: prefer the `get` member function of a view instead of the `get` member
840 function template of a registry during iterations, if possible. However, keep in
841 mind that it works only with the components of the view itself.
842 
843 ## Side notes
844 
845 * Entity identifiers are numbers and nothing more. They are not classes and they
846  have no member functions at all. As already mentioned, do no try to inspect or
847  modify an entity descriptor in any way.
848 
849 * As shown in the examples above, the preferred way to get references to the
850  components while iterating a view is by using the view itself. It's a faster
851  alternative to the `get` member function template that is part of the API of
852  the Registry. This is because the registry must ensure that a pool for the
853  given component exists before to use it; on the other side, views force the
854  construction of the pools for all their components and access them directly,
855  thus avoiding all the checks.
856 
857 * Most of the _ECS_ available out there have an annoying limitation (at least
858  from my point of view): entities and components cannot be created and/or
859  deleted during iterations.<br/>
860  `EnTT` partially solves the problem with a few limitations:
861 
862  * Creating entities and components is allowed during iterations.
863  * Deleting an entity or removing its components is allowed during
864  iterations if it's the one currently returned by a view. For all the
865  other entities, destroying them or removing their components isn't
866  allowed and it can result in undefined behavior.
867 
868  Iterators are invalidated and the behaviour is undefined if an entity is
869  modified or destroyed and it's not the one currently returned by the
870  view.<br/>
871  To work around it, possible approaches are:
872 
873  * Store aside the entities and the components to be removed and perform the
874  operations at the end of the iteration.
875  * Mark entities and components with a proper tag component that indicates
876  they must be purged, then perform a second iteration to clean them up one
877  by one.
878 
879 * Views and thus their iterators aren't thread safe. Do no try to iterate a set
880  of components and modify the same set concurrently.<br/>
881  That being said, as long as a thread iterates the entities that have the
882  component `X` or assign and removes that component from a set of entities,
883  another thread can safely do the same with components `Y` and `Z` and
884  everything will work like a charm.<br/>
885  As an example, users can freely execute the rendering system and iterate the
886  renderable entities while updating a physic component concurrently on a
887  separate thread if needed.
888 
889 # Contributors
890 
891 If you want to contribute, please send patches as pull requests against the
892 branch `master`.<br/>
893 Check the
894 [contributors list](https://github.com/skypjack/entt/blob/master/AUTHORS) to see
895 who has partecipated so far.
896 
897 # License
898 
899 Code and documentation Copyright (c) 2017 Michele Caini.<br/>
900 Code released under
901 [the MIT license](https://github.com/skypjack/entt/blob/master/LICENSE).
902 Docs released under
903 [Creative Commons](https://github.com/skypjack/entt/blob/master/docs/LICENSE).
904 
905 # Donation
906 
907 Developing and maintaining `EnTT` takes some time and lots of coffee. I'd like
908 to add more and more functionalities in future and turn it in a full-featured
909 framework.<br/>
910 If you want to support this project, you can offer me an espresso. I'm from
911 Italy, we're used to turning the best coffee ever in code. If you find that
912 it's not enough, feel free to support me the way you prefer.<br/>
913 Take a look at the donation button at the top of the page for more details or
914 just click [here](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted).