🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1552 lines
63 KiB

  1. # Crash Course: entity-component system
  2. <!--
  3. @cond TURN_OFF_DOXYGEN
  4. -->
  5. # Table of Contents
  6. * [Introduction](#introduction)
  7. * [Design decisions](#design-decisions)
  8. * [A bitset-free entity-component system](#a-bitset-free-entity-component-system)
  9. * [Pay per use](#pay-per-use)
  10. * [All or nothing](#all-or-nothing)
  11. * [Stateless systems](#stateless-systems)
  12. * [Vademecum](#vademecum)
  13. * [The Registry, the Entity and the Component](#the-registry-the-entity-and-the-component)
  14. * [Observe changes](#observe-changes)
  15. * [Runtime components](#runtime-components)
  16. * [A journey through a plugin](#a-journey-through-a-plugin)
  17. * [Sorting: is it possible?](#sorting-is-it-possible)
  18. * [Snapshot: complete vs continuous](#snapshot-complete-vs-continuous)
  19. * [Snapshot loader](#snapshot-loader)
  20. * [Continuous loader](#continuous-loader)
  21. * [Archives](#archives)
  22. * [One example to rule them all](#one-example-to-rule-them-all)
  23. * [Prototype](#prototype)
  24. * [Helpers](#helpers)
  25. * [Dependency function](#dependency-function)
  26. * [Tags](#tags)
  27. * [Null entity](#null-entity)
  28. * [Context variables](#context-variables)
  29. * [Views and Groups](#views-and-groups)
  30. * [Views](#views)
  31. * [Runtime views](#runtime-views)
  32. * [Groups](#groups)
  33. * [Full-owning groups](#full-owning-groups)
  34. * [Partial-owning groups](#partial-owning-groups)
  35. * [Non-owning groups](#non-owning-groups)
  36. * [Types: const, non-const and all in between](#types-const-non-const-and-all-in-between)
  37. * [Give me everything](#give-me-everything)
  38. * [What is allowed and what is not](#what-is-allowed-and-what-is-not)
  39. * [More performance, more constraints](#more-performance-more-constraints)
  40. * [Empty type optimization](#empty-type-optimization)
  41. * [Multithreading](#multithreading)
  42. * [Iterators](#iterators)
  43. <!--
  44. @endcond TURN_OFF_DOXYGEN
  45. -->
  46. # Introduction
  47. `EnTT` is a header-only, tiny and easy to use entity-component system (and much
  48. more) written in modern C++.<br/>
  49. The entity-component-system (also known as _ECS_) is an architectural pattern
  50. used mostly in game development.
  51. # Design decisions
  52. ## A bitset-free entity-component system
  53. `EnTT` is a _bitset-free_ entity-component system that doesn't require users to
  54. specify the component set at compile-time.<br/>
  55. This is why users can instantiate the core class simply like:
  56. ```cpp
  57. entt::registry registry;
  58. ```
  59. In place of its more annoying and error-prone counterpart:
  60. ```cpp
  61. entt::registry<comp_0, comp_1, ..., comp_n> registry;
  62. ```
  63. ## Pay per use
  64. `EnTT` is entirely designed around the principle that users have to pay only for
  65. what they want.
  66. When it comes to using an entity-component system, the tradeoff is usually
  67. between performance and memory usage. The faster it is, the more memory it uses.
  68. Even worse, some approaches tend to heavily affect other functionalities like
  69. the construction and destruction of components to favor iterations, even when it
  70. isn't strictly required. In fact, slightly worse performance along non-critical
  71. paths are the right price to pay to reduce memory usage and have overall better
  72. perfomance sometimes and I've always wondered why this kind of tools do not
  73. leave me the choice.<br/>
  74. `EnTT` follows a completely different approach. It gets the best out from the
  75. basic data structures and gives users the possibility to pay more for higher
  76. performance where needed.<br/>
  77. The disadvantage of this approach is that users need to know the systems they
  78. are working on and the tools they are using. Otherwise, the risk to ruin the
  79. performance along critical paths is high.
  80. So far, this choice has proven to be a good one and I really hope it can be for
  81. many others besides me.
  82. ## All or nothing
  83. `EnTT` is such that at every moment a pair `(T *, size)` is available to
  84. directly access all the instances of a given component type `T`.<br/>
  85. This was a guideline and a design decision that influenced many choices, for
  86. better and for worse. I cannot say whether it will be useful or not to the
  87. reader, but it's worth to mention it, because it's one of the corner stones of
  88. this library.
  89. Many of the tools described below, from the registry to the views and up to the
  90. groups give the possibility to get this information and have been designed
  91. around this need, which was and remains one of my main requirements during the
  92. development.<br/>
  93. The rest is experimentation and the desire to invent something new, hoping to
  94. have succeeded.
  95. ## Stateless systems
  96. `EnTT` is designed so that it can work with _stateless systems_. In other words,
  97. all systems can be free functions and there is no need to define them as classes
  98. (although nothing prevents users from doing so).<br/>
  99. This is possible because the main class with which the users will work provides
  100. all what is needed to act as the sole _source of truth_ of an application.
  101. To be honest, this point became part of the design principles at a later date,
  102. but has also become one of the cornerstones of the library to date, as stateless
  103. systems are widely used and appreciated in general.
  104. # Vademecum
  105. The registry to store, the views and the groups to iterate. That's all.
  106. An entity (the _E_ of an _ECS_) is an opaque identifier that users should just
  107. use as-is and store around if needed. Do not try to inspect an entity
  108. identifier, its format can change in future and a registry offers all the
  109. functionalities to query them out-of-the-box. The underlying type of an entity
  110. (either `std::uint16_t`, `std::uint32_t` or `std::uint64_t`) can be specified
  111. when defining a registry (actually `entt::registry` is nothing more than an
  112. alias for `entt::basic_registry<entt::entity>` and `entt::entity` is an alias
  113. for `std::uint32_t`).<br/>
  114. Components (the _C_ of an _ECS_) should be plain old data structures or more
  115. complex and movable data structures with a proper constructor. Actually, the
  116. sole requirement of a component type is that it must be both move constructible
  117. and move assignable. They are list initialized by using the parameters provided
  118. to construct the component itself. No need to register components or their types
  119. neither with the registry nor with the entity-component system at all.<br/>
  120. Systems (the _S_ of an _ECS_) are just plain functions, functors, lambdas or
  121. whatever users want. They can accept a registry, a view or a group of any type
  122. and use them the way they prefer. No need to register systems or their types
  123. neither with the registry nor with the entity-component system at all.
  124. The following sections will explain in short how to use the entity-component
  125. system, the core part of the whole library.<br/>
  126. In fact, the project is composed of many other classes in addition to those
  127. describe below. For more details, please refer to the inline documentation.
  128. # The Registry, the Entity and the Component
  129. A registry can store and manage entities, as well as create views and groups to
  130. iterate the underlying data structures.<br/>
  131. The class template `basic_registry` lets users decide what's the preferred type
  132. to represent an entity. Because `std::uint32_t` is large enough for almost all
  133. the cases, there exists also the alias `entt::entity` for it, as well as the
  134. alias `entt::registry` for `entt::basic_registry<entt::entity>`.
  135. Entities are represented by _entity identifiers_. An entity identifier is an
  136. opaque type that users should not inspect or modify in any way. It carries
  137. information about the entity itself and its version.
  138. A registry can be used both to construct and to destroy entities:
  139. ```cpp
  140. // constructs a naked entity with no components and returns its identifier
  141. auto entity = registry.create();
  142. // destroys an entity and all its components
  143. registry.destroy(entity);
  144. ```
  145. There exists also an overload of the `create` and `destroy` member functions
  146. that accepts two iterators, that is a range to assign or to destroy. It can be
  147. used to create or destroy multiple entities at once:
  148. ```cpp
  149. // destroys all the entities in a range
  150. auto view = registry.view<a_component, another_component>();
  151. registry.destroy(view.begin(), view.end());
  152. ```
  153. In both cases, the `create` member function accepts also a list of default
  154. constructible types of components to assign to the entities before to return.
  155. It's a faster alternative to the creation and subsequent assignment of
  156. components in separate steps.
  157. When an entity is destroyed, the registry can freely reuse it internally with a
  158. slightly different identifier. In particular, the version of an entity is
  159. increased each and every time it's discarded.<br/>
  160. In case entity identifiers are stored around, the registry offers all the
  161. functionalities required to test them and to get out of them the information
  162. they carry:
  163. ```cpp
  164. // returns true if the entity is still valid, false otherwise
  165. bool b = registry.valid(entity);
  166. // gets the version contained in the entity identifier
  167. auto version = registry.version(entity);
  168. // gets the actual version for the given entity
  169. auto curr = registry.current(entity);
  170. ```
  171. Components can be assigned to or removed from entities at any time with a few
  172. calls to member functions of the registry. As for the entities, the registry
  173. offers also a set of functionalities users can use to work with the components.
  174. The `assign` member function template creates, initializes and assigns to an
  175. entity the given component. It accepts a variable number of arguments to
  176. construct the component itself if present:
  177. ```cpp
  178. registry.assign<position>(entity, 0., 0.);
  179. // ...
  180. auto &velocity = registry.assign<velocity>(entity);
  181. vel.dx = 0.;
  182. vel.dy = 0.;
  183. ```
  184. If an entity already has the given component, the `replace` member function
  185. template can be used to replace it:
  186. ```cpp
  187. registry.replace<position>(entity, 0., 0.);
  188. // ...
  189. auto &velocity = registry.replace<velocity>(entity);
  190. vel.dx = 0.;
  191. vel.dy = 0.;
  192. ```
  193. In case users want to assign a component to an entity, but it's unknown whether
  194. the entity already has it or not, `assign_or_replace` does the work in a single
  195. call (there is a performance penalty to pay for this mainly due to the fact that
  196. it has to check if the entity already has the given component or not):
  197. ```cpp
  198. registry.assign_or_replace<position>(entity, 0., 0.);
  199. // ...
  200. auto &velocity = registry.assign_or_replace<velocity>(entity);
  201. vel.dx = 0.;
  202. vel.dy = 0.;
  203. ```
  204. Note that `assign_or_replace` is a slightly faster alternative for the following
  205. `if/else` statement and nothing more:
  206. ```cpp
  207. if(registry.has<comp>(entity)) {
  208. registry.replace<comp>(entity, arg1, argN);
  209. } else {
  210. registry.assign<comp>(entity, arg1, argN);
  211. }
  212. ```
  213. As already shown, if in doubt about whether or not an entity has one or more
  214. components, the `has` member function template may be useful:
  215. ```cpp
  216. bool b = registry.has<position, velocity>(entity);
  217. ```
  218. On the other side, if the goal is to delete a single component, the `remove`
  219. member function template is the way to go when it's certain that the entity owns
  220. a copy of the component:
  221. ```cpp
  222. registry.remove<position>(entity);
  223. ```
  224. Otherwise consider to use the `reset` member function. It behaves similarly to
  225. `remove` but with a strictly defined behavior (and a performance penalty is the
  226. price to pay for this). In particular it removes the component if and only if it
  227. exists, otherwise it returns safely to the caller:
  228. ```cpp
  229. registry.reset<position>(entity);
  230. ```
  231. There exist also two other _versions_ of the `reset` member function:
  232. * If no entity is passed to it, `reset` will remove the given component from
  233. each entity that has it:
  234. ```cpp
  235. registry.reset<position>();
  236. ```
  237. * If neither the entity nor the component are specified, all the entities still
  238. in use and their components are destroyed:
  239. ```cpp
  240. registry.reset();
  241. ```
  242. Finally, references to components can be retrieved simply by doing this:
  243. ```cpp
  244. const auto &cregistry = registry;
  245. // const and non-const reference
  246. const auto &crenderable = cregistry.get<renderable>(entity);
  247. auto &renderable = registry.get<renderable>(entity);
  248. // const and non-const references
  249. const auto &[cpos, cvel] = cregistry.get<position, velocity>(entity);
  250. auto &[pos, vel] = registry.get<position, velocity>(entity);
  251. ```
  252. The `get` member function template gives direct access to the component of an
  253. entity stored in the underlying data structures of the registry. There exists
  254. also an alternative member function named `try_get` that returns a pointer to
  255. the component owned by an entity if any, a null pointer otherwise.
  256. ## Observe changes
  257. Because of how the registry works internally, it stores a bunch of signal
  258. handlers for each pool in order to notify some of its data structures on the
  259. construction and destruction of components or when an instance of a component is
  260. explicitly replaced by the user.<br/>
  261. These signal handlers are also exposed and made available to users. These are
  262. the basic bricks to build fancy things like dependencies and reactive systems.
  263. To get a sink to be used to connect and disconnect listeners so as to be
  264. notified on the creation of a component, use the `on_construct` member function:
  265. ```cpp
  266. // connects a free function
  267. registry.on_construct<position>().connect<&my_free_function>();
  268. // connects a member function
  269. registry.on_construct<position>().connect<&my_class::member>(&instance);
  270. // disconnects a free function
  271. registry.on_construct<position>().disconnect<&my_free_function>();
  272. // disconnects a member function
  273. registry.on_construct<position>().disconnect<&my_class::member>(&instance);
  274. ```
  275. To be notified when components are destroyed, use the `on_destroy` member
  276. function instead. Finally, the `on_replace` member function will return a sink
  277. to which to connect listeners to observe changes on components.
  278. The function type of a listener for the construction signal should be equivalent
  279. to the following:
  280. ```cpp
  281. void(entt::registry &, entt::entity, Component &);
  282. ```
  283. Where `Component` is intuitively the type of component of interest. In other
  284. words, a listener is provided with the registry that triggered the notification
  285. and the entity affected by the change, in addition to the newly created
  286. instance.<br/>
  287. The sink returned by the `on_replace` member function accepts listeners the
  288. signature of which is the same of that of the construction signal. The one of
  289. the destruction signal is also similar, except for the `Component` parameter:
  290. ```cpp
  291. void(entt::registry &, entt::entity);
  292. ```
  293. This is mainly due to performance reasons. While the component is made available
  294. after the construction, it is not when destroyed. Because of that, there are no
  295. reasons to get it from the underlying storage unless the user requires so. In
  296. this case, the registry is made available for the purpose.
  297. Note also that:
  298. * Listeners for the construction signal are invoked **after** components have
  299. been assigned to entities.
  300. * Listeners designed to observe changes are invoked **before** components have
  301. been replaced and therefore before newly created instances have been assigned
  302. to entities.
  303. * Listeners for the destruction signal are invoked **before** components have
  304. been removed from entities.
  305. * The order of invocation of the listeners isn't guaranteed in any case.
  306. There are also some limitations on what a listener can and cannot do. In
  307. particular:
  308. * Connecting and disconnecting other functions from within the body of a
  309. listener should be avoided. It can lead to undefined behavior in some cases.
  310. * Assigning and removing components from within the body of a listener that
  311. observes the destruction of instances of a given type should be avoided. It
  312. can lead to undefined behavior in some cases. This type of listeners is
  313. intended to provide users with an easy way to perform cleanup and nothing
  314. more.
  315. To a certain extent, these limitations don't apply. However, it's risky to try
  316. to force them and users should respect the limitations unless they know exactly
  317. what they are doing. Subtle bugs are the price to pay in case of errors
  318. otherwise.
  319. In general, events and therefore listeners must not be used as replacements for
  320. systems. They should not contain much logic and interactions with a registry
  321. should be kept to a minimum, if possible. Note also that the greater the number
  322. of listeners, the greater the performance hit when components are created or
  323. destroyed.
  324. ## Runtime components
  325. Defining components at runtime is useful to support plugin systems and mods in
  326. general. However, it seems impossible with a tool designed around a bunch of
  327. templates. Indeed it's not that difficult.<br/>
  328. Of course, some features cannot be easily exported into a runtime
  329. environment. As an example, sorting a group of components defined at runtime
  330. isn't for free if compared to most of the other operations. However, the basic
  331. functionalities of an entity-component system such as `EnTT` fit the problem
  332. perfectly and can also be used to manage runtime components if required.<br/>
  333. All that is necessary to do it is to know the identifiers of the components. An
  334. identifier is nothing more than a number or similar that can be used at runtime
  335. to work with the type system.
  336. In `EnTT`, identifiers are easily accessible:
  337. ```cpp
  338. entt::registry registry;
  339. // component identifier
  340. auto type = registry.type<position>();
  341. ```
  342. Once the identifiers are made available, almost everything becomes pretty
  343. simple.
  344. ### A journey through a plugin
  345. `EnTT` comes with an example (actually a test) that shows how to integrate
  346. compile-time and runtime components in a stack based JavaScript environment. It
  347. uses [`Duktape`](https://github.com/svaarala/duktape) under the hood, mainly
  348. because I wanted to learn how it works at the time I was writing the code.
  349. The code is not production-ready and overall performance can be highly improved.
  350. However, I sacrificed optimizations in favor of a more readable piece of code. I
  351. hope I succeeded.<br/>
  352. Note also that this isn't neither the only nor (probably) the best way to do it.
  353. In fact, the right way depends on the scripting language and the problem one is
  354. facing in general.<br/>
  355. That being said, feel free to use it at your own risk.
  356. The basic idea is that of creating a compile-time component aimed to map all the
  357. runtime components assigned to an entity.<br/>
  358. Identifiers come in use to address the right function from a map when invoked
  359. from the runtime environment and to filter entities when iterating.<br/>
  360. With a bit of gymnastic, one can narrow views and improve the performance to
  361. some extent but it was not the goal of the example.
  362. ## Sorting: is it possible?
  363. It goes without saying that sorting entities and components is possible with
  364. `EnTT`.<br/>
  365. In fact, there are two functions that respond to slightly different needs:
  366. * Components can be sorted either directly:
  367. ```cpp
  368. registry.sort<renderable>([](const auto &lhs, const auto &rhs) {
  369. return lhs.z < rhs.z;
  370. });
  371. ```
  372. Or by accessing their entities:
  373. ```cpp
  374. registry.sort<renderable>([](const entt::entity lhs, const entt::entity rhs) {
  375. return entt::registry::entity(lhs) < entt::registry::entity(rhs);
  376. });
  377. ```
  378. There exists also the possibility to use a custom sort function object, as
  379. long as it adheres to the requirements described in the inline
  380. documentation.<br/>
  381. This is possible mainly because users can get much more with a custom sort
  382. function object if the usage pattern is known. As an example, in case of an
  383. almost sorted pool, quick sort could be much, much slower than insertion sort.
  384. * Components can be sorted according to the order imposed by another component:
  385. ```cpp
  386. registry.sort<movement, physics>();
  387. ```
  388. In this case, instances of `movement` are arranged in memory so that cache
  389. misses are minimized when the two components are iterated together.
  390. ## Snapshot: complete vs continuous
  391. The `registry` class offers basic support to serialization.<br/>
  392. It doesn't convert components to bytes directly, there wasn't the need of
  393. another tool for serialization out there. Instead, it accepts an opaque object
  394. with a suitable interface (namely an _archive_) to serialize its internal data
  395. structures and restore them later. The way types and instances are converted to
  396. a bunch of bytes is completely in charge to the archive and thus to final users.
  397. The goal of the serialization part is to allow users to make both a dump of the
  398. entire registry or a narrower snapshot, that is to select only the components in
  399. which they are interested.<br/>
  400. Intuitively, the use cases are different. As an example, the first approach is
  401. suitable for local save/restore functionalities while the latter is suitable for
  402. creating client-server applications and for transferring somehow parts of the
  403. representation side to side.
  404. To take a snapshot of the registry, use the `snapshot` member function. It
  405. returns a temporary object properly initialized to _save_ the whole registry or
  406. parts of it.
  407. Example of use:
  408. ```cpp
  409. output_archive output;
  410. registry.snapshot()
  411. .entities(output)
  412. .destroyed(output)
  413. .component<a_component, another_component>(output);
  414. ```
  415. It isn't necessary to invoke all these functions each and every time. What
  416. functions to use in which case mostly depends on the goal and there is not a
  417. golden rule to do that.
  418. The `entities` member function asks the registry to serialize all the entities
  419. that are still in use along with their versions. On the other side, the
  420. `destroyed` member function tells to the registry to serialize the entities that
  421. have been destroyed and are no longer in use.<br/>
  422. These two functions can be used to save and restore the whole set of entities
  423. with the versions they had during serialization.
  424. The `component` member function is a function template the aim of which is to
  425. store aside components. The presence of a template parameter list is a
  426. consequence of a couple of design choices from the past and in the present:
  427. * First of all, there is no reason to force a user to serialize all the
  428. components at once and most of the times it isn't desiderable. As an example,
  429. in case the stuff for the HUD in a game is put into the registry for some
  430. reasons, its components can be freely discarded during a serialization step
  431. because probably the software already knows how to reconstruct the HUD
  432. correctly from scratch.
  433. * Furthermore, the registry makes heavy use of _type-erasure_ techniques
  434. internally and doesn't know at any time what types of components it contains.
  435. Therefore being explicit at the call point is mandatory.
  436. There exists also another version of the `component` member function that
  437. accepts a range of entities to serialize. This version is a bit slower than the
  438. other one, mainly because it iterates the range of entities more than once for
  439. internal purposes. However, it can be used to filter out those entities that
  440. shouldn't be serialized for some reasons.<br/>
  441. As an example:
  442. ```cpp
  443. const auto view = registry.view<serialize>();
  444. output_archive output;
  445. registry.snapshot().component<a_component, another_component>(output, view.cbegin(), view.cend());
  446. ```
  447. Note that `component` stores items along with entities. It means that it works
  448. properly without a call to the `entities` member function.
  449. Once a snapshot is created, there exist mainly two _ways_ to load it: as a whole
  450. and in a kind of _continuous mode_.<br/>
  451. The following sections describe both loaders and archives in details.
  452. ### Snapshot loader
  453. A snapshot loader requires that the destination registry be empty and loads all
  454. the data at once while keeping intact the identifiers that the entities
  455. originally had.<br/>
  456. To do that, the registry offers a member function named `loader` that returns a
  457. temporary object properly initialized to _restore_ a snapshot.
  458. Example of use:
  459. ```cpp
  460. input_archive input;
  461. registry.loader()
  462. .entities(input)
  463. .destroyed(input)
  464. .component<a_component, another_component>(input)
  465. .orphans();
  466. ```
  467. It isn't necessary to invoke all these functions each and every time. What
  468. functions to use in which case mostly depends on the goal and there is not a
  469. golden rule to do that. For obvious reasons, what is important is that the data
  470. are restored in exactly the same order in which they were serialized.
  471. The `entities` and `destroyed` member functions restore the sets of entities and
  472. the versions that the entities originally had at the source.
  473. The `component` member function restores all and only the components specified
  474. and assigns them to the right entities. Note that the template parameter list
  475. must be exactly the same used during the serialization.
  476. The `orphans` member function literally destroys those entities that have no
  477. components attached. It's usually useless if the snapshot is a full dump of the
  478. source. However, in case all the entities are serialized but only few components
  479. are saved, it could happen that some of the entities have no components once
  480. restored. The best users can do to deal with them is to destroy those entities
  481. and thus update their versions.
  482. ### Continuous loader
  483. A continuous loader is designed to load data from a source registry to a
  484. (possibly) non-empty destination. The loader can accommodate in a registry more
  485. than one snapshot in a sort of _continuous loading_ that updates the
  486. destination one step at a time.<br/>
  487. Identifiers that entities originally had are not transferred to the target.
  488. Instead, the loader maps remote identifiers to local ones while restoring a
  489. snapshot. Because of that, this kind of loader offers a way to update
  490. automatically identifiers that are part of components (as an example, as data
  491. members or gathered in a container).<br/>
  492. Another difference with the snapshot loader is that the continuous loader does
  493. not need to work with the private data structures of a registry. Furthermore, it
  494. has an internal state that must persist over time. Therefore, there is no reason
  495. to create it by means of a registry, or to limit its lifetime to that of a
  496. temporary object.
  497. Example of use:
  498. ```cpp
  499. entt::continuous_loader<entt::entity> loader{registry};
  500. input_archive input;
  501. loader.entities(input)
  502. .destroyed(input)
  503. .component<a_component, another_component, dirty_component>(input, &dirty_component::parent, &dirty_component::child)
  504. .orphans()
  505. .shrink();
  506. ```
  507. It isn't necessary to invoke all these functions each and every time. What
  508. functions to use in which case mostly depends on the goal and there is not a
  509. golden rule to do that. For obvious reasons, what is important is that the data
  510. are restored in exactly the same order in which they were serialized.
  511. The `entities` and `destroyed` member functions restore groups of entities and
  512. map each entity to a local counterpart when required. In other terms, for each
  513. remote entity identifier not yet registered by the loader, the latter creates a
  514. local identifier so that it can keep the local entity in sync with the remote
  515. one.
  516. The `component` member function restores all and only the components specified
  517. and assigns them to the right entities.<br/>
  518. In case the component contains entities itself (either as data members of type
  519. `entt::entity` or as containers of entities), the loader can update them
  520. automatically. To do that, it's enough to specify the data members to update as
  521. shown in the example.
  522. The `orphans` member function literally destroys those entities that have no
  523. components after a restore. It has exactly the same purpose described in the
  524. previous section and works the same way.
  525. Finally, `shrink` helps to purge local entities that no longer have a remote
  526. conterpart. Users should invoke this member function after restoring each
  527. snapshot, unless they know exactly what they are doing.
  528. ### Archives
  529. Archives must publicly expose a predefined set of member functions. The API is
  530. straightforward and consists only of a group of function call operators that
  531. are invoked by the snapshot class and the loaders.
  532. In particular:
  533. * An output archive, the one used when creating a snapshot, must expose a
  534. function call operator with the following signature to store entities:
  535. ```cpp
  536. void operator()(entt::entity);
  537. ```
  538. Where `entt::entity` is the type of the entities used by the registry. Note
  539. that all the member functions of the snapshot class make also an initial call
  540. to this endpoint to save the _size_ of the set they are going to store.<br/>
  541. In addition, an archive must accept a pair of entity and component for each
  542. type to be serialized. Therefore, given a type `T`, the archive must contain a
  543. function call operator with the following signature:
  544. ```cpp
  545. void operator()(entt::entity, const T &);
  546. ```
  547. The output archive can freely decide how to serialize the data. The register
  548. is not affected at all by the decision.
  549. * An input archive, the one used when restoring a snapshot, must expose a
  550. function call operator with the following signature to load entities:
  551. ```cpp
  552. void operator()(entt::entity &);
  553. ```
  554. Where `entt::entity` is the type of the entities used by the registry. Each
  555. time the function is invoked, the archive must read the next element from the
  556. underlying storage and copy it in the given variable. Note that all the member
  557. functions of a loader class make also an initial call to this endpoint to read
  558. the _size_ of the set they are going to load.<br/>
  559. In addition, the archive must accept a pair of entity and component for each
  560. type to be restored. Therefore, given a type `T`, the archive must contain a
  561. function call operator with the following signature:
  562. ```cpp
  563. void operator()(entt::entity &, T &);
  564. ```
  565. Every time such an operator is invoked, the archive must read the next
  566. elements from the underlying storage and copy them in the given variables.
  567. ### One example to rule them all
  568. `EnTT` comes with some examples (actually some tests) that show how to integrate
  569. a well known library for serialization as an archive. It uses
  570. [`Cereal C++`](https://uscilab.github.io/cereal/) under the hood, mainly
  571. because I wanted to learn how it works at the time I was writing the code.
  572. The code is not production-ready and it isn't neither the only nor (probably)
  573. the best way to do it. However, feel free to use it at your own risk.
  574. The basic idea is to store everything in a group of queues in memory, then bring
  575. everything back to the registry with different loaders.
  576. ## Prototype
  577. A prototype defines a type of an application in terms of its parts. They can be
  578. used to assign components to entities of a registry at once.<br/>
  579. Roughly speaking, in most cases prototypes can be considered just as templates
  580. to use to initialize entities according to _concepts_. In fact, users can create
  581. how many prototypes they want, each one initialized differently from the others.
  582. The following is an example of use of a prototype:
  583. ```cpp
  584. entt::registry registry;
  585. entt::prototype prototype{registry};
  586. prototype.set<position>(100.f, 100.f);
  587. prototype.set<velocity>(0.f, 0.f);
  588. // ...
  589. const auto entity = prototype();
  590. ```
  591. To assign and remove components from a prototype, it offers two dedicated member
  592. functions named `set` and `unset`. The `has` member function can be used to know
  593. if a given prototype contains one or more components and the `get` member
  594. function can be used to retrieve the components.
  595. Creating an entity from a prototype is straightforward:
  596. * To create a new entity from scratch and assign it a prototype, this is the way
  597. to go:
  598. ```cpp
  599. const auto entity = prototype();
  600. ```
  601. It is equivalent to the following invokation:
  602. ```cpp
  603. const auto entity = prototype.create();
  604. ```
  605. * In case we want to initialize an already existing entity, we can provide the
  606. `operator()` directly with the entity identifier:
  607. ```cpp
  608. prototype(entity);
  609. ```
  610. It is equivalent to the following invokation:
  611. ```cpp
  612. prototype.assign(entity);
  613. ```
  614. Note that existing components aren't overwritten in this case. Only those
  615. components that the entity doesn't own yet are copied over. All the other
  616. components remain unchanged.
  617. * Finally, to assign or replace all the components for an entity, thus
  618. overwriting existing ones:
  619. ```cpp
  620. prototype.assign_or_replace(entity);
  621. ```
  622. In the examples above, the prototype uses its underlying registry to create
  623. entities and components both for its purposes and when it's cloned. To use a
  624. different repository to clone a prototype, all the member functions accept also
  625. a reference to a valid registry as a first argument.
  626. Prototypes are a very useful tool that can save a lot of typing sometimes.
  627. Furthermore, the codebase may be easier to maintain, since updating a prototype
  628. is much less error prone than jumping around in the codebase to update all the
  629. snippets copied and pasted around to initialize entities and components.
  630. ## Helpers
  631. The so called _helpers_ are small classes and functions mainly designed to offer
  632. built-in support for the most basic functionalities.<br/>
  633. The list of helpers will grow longer as time passes and new ideas come out.
  634. ### Dependency function
  635. A _dependency function_ is a predefined listener, actually a function template
  636. to use to automatically assign components to an entity when a type has a
  637. dependency on some other types.<br/>
  638. The following adds components `a_type` and `another_type` whenever `my_type` is
  639. assigned to an entity:
  640. ```cpp
  641. entt::connnect<a_type, another_type>(registry.on_construct<my_type>());
  642. ```
  643. A component is assigned to an entity and thus default initialized only in case
  644. the entity itself hasn't it yet. It means that already existent components won't
  645. be overriden.<br/>
  646. A dependency can easily be broken by means of the following function template:
  647. ```cpp
  648. entt::disconnect<a_type, another_type>(registry.on_construct<my_type>());
  649. ```
  650. ### Tags
  651. There's nothing magical about the way tags can be assigned to entities while
  652. avoiding a performance hit at runtime. Nonetheless, the syntax can be annoying
  653. and that's why a more user-friendly shortcut is provided to do it.<br/>
  654. This shortcut is the alias template `entt::tag`.
  655. If used in combination with hashed strings, it helps to use tags where types
  656. would be required otherwise. As an example:
  657. ```cpp
  658. registry.assign<entt::tag<"enemy"_hs>>(entity);
  659. ```
  660. ## Null entity
  661. In `EnTT`, there exists a sort of _null entity_ made available to users that is
  662. accessible via the `entt::null` variable.<br/>
  663. The library guarantees that the following expression always returns false:
  664. ```cpp
  665. registry.valid(entt::null);
  666. ```
  667. In other terms, a registry will reject the null entity in all cases because it
  668. isn't considered valid. It means that the null entity cannot own components for
  669. obvious reasons.<br/>
  670. The type of the null entity is internal and should not be used for any purpose
  671. other than defining the null entity itself. However, there exist implicit
  672. conversions from the null entity to identifiers of any allowed type:
  673. ```cpp
  674. entt::entity null = entt::null;
  675. ```
  676. Similarly, the null entity can be compared to any other identifier:
  677. ```cpp
  678. const auto entity = registry.create();
  679. const bool null = (entity == entt::null);
  680. ```
  681. ## Context variables
  682. It is often convenient to assign context variables to a registry, so as to make
  683. it the only _source of truth_ of an application.<br/>
  684. This is possible by means of a member function named `set` to use to create a
  685. context variable from a given type. Later on, either `ctx` or `try_ctx` can be
  686. used to retrieve the newly created instance and `unset` is there to literally
  687. reset it if needed.
  688. Example of use:
  689. ```cpp
  690. // creates a new context variable initialized with the given values
  691. registry.set<my_type>(42, 'c');
  692. // gets the context variable
  693. const auto &var = registry.ctx<my_type>();
  694. // if in doubts, probe the registry to avoid assertions in case of errors
  695. if(auto *ptr = registry.try_ctx<my_type>(); ptr) {
  696. // uses the context variable associated with the registry, if any
  697. }
  698. // unsets the context variable
  699. registry.unset<my_type>();
  700. ```
  701. The type of a context variable must be such that it's default constructible and
  702. can be moved. The `set` member function either creates a new instance of the
  703. context variable or overwrites an already existing one if any. The `try_ctx`
  704. member function returns a pointer to the context variable if it exists,
  705. otherwise it returns a null pointer. This fits well with the `if` statement with
  706. initializer.
  707. # Views and Groups
  708. First of all, it is worth answering an obvious question: why views and
  709. groups?<br/>
  710. Briefly, they are a good tool to enforce single responsibility. A system that
  711. has access to a registry can create and destroy entities, as well as assign and
  712. remove components. On the other side, a system that has access to a view or a
  713. group can only iterate entities and their components, then read or update the
  714. data members of the latter.<br/>
  715. It is a subtle difference that can help designing a better software sometimes.
  716. More in details, views are a non-intrusive tool to access entities and
  717. components without affecting other functionalities or increasing the memory
  718. consumption. On the other side, groups are an intrusive tool that allows to
  719. reach higher performance along critical paths but has also a price to pay for
  720. that.
  721. There are mainly two kinds of views: _compile-time_ (also known as `view`) and
  722. runtime (also known as `runtime_view`).<br/>
  723. The former require that users indicate at compile-time what are the components
  724. involved and can make several optimizations because of that. The latter can be
  725. constructed at runtime instead and are a bit slower to iterate entities and
  726. components.<br/>
  727. In both cases, creating and destroying a view isn't expensive at all because
  728. views don't have any type of initialization. Moreover, views don't affect any
  729. other functionality of the registry and keep memory usage at a minimum.
  730. Groups come in three different flavors: _full-owning groups_, _partial-owning
  731. groups_ and _non-owning groups_. The main difference between them is in terms of
  732. performance.<br/>
  733. Groups can literally _own_ one or more types of components. It means that they
  734. will be allowed to rearrange pools so as to speed up iterations. Roughly
  735. speaking: the more components a group owns, the faster it is to iterate them.
  736. On the other side, a given component can belong only to one group, so users have
  737. to define groups carefully to get the best out of them.
  738. Continue reading for more details or refer to the inline documentation.
  739. ## Views
  740. A view behaves differently if it's constructed for a single component or if it
  741. has been created to iterate multiple components. Even the API is slightly
  742. different in the two cases.
  743. Single component views are specialized in order to give a boost in terms of
  744. performance in all the situations. This kind of views can access the underlying
  745. data structures directly and avoid superfluous checks. There is nothing as fast
  746. as a single component view. In fact, they walk through a packed array of
  747. components and return them one at a time.<br/>
  748. Single component views offer a bunch of functionalities to get the number of
  749. entities they are going to return and a raw access to the entity list as well as
  750. to the component list. It's also possible to ask a view if it contains a
  751. given entity.<br/>
  752. Refer to the inline documentation for all the details.
  753. Multi component views iterate entities that have at least all the given
  754. components in their bags. During construction, these views look at the number of
  755. entities available for each component and pick up a reference to the smallest
  756. set of candidates in order to speed up iterations.<br/>
  757. They offer fewer functionalities than their companion views for single
  758. component. In particular, a multi component view exposes utility functions to
  759. get the estimated number of entities it is going to return and to know whether
  760. it's empty or not. It's also possible to ask a view if it contains a given
  761. entity.<br/>
  762. Refer to the inline documentation for all the details.
  763. There is no need to store views around for they are extremely cheap to
  764. construct, even though they can be copied without problems and reused freely.
  765. Views also return newly created and correctly initialized iterators whenever
  766. `begin` or `end` are invoked.
  767. Views share the way they are created by means of a registry:
  768. ```cpp
  769. // single component view
  770. auto single = registry.view<position>();
  771. // multi component view
  772. auto multi = registry.view<position, velocity>();
  773. ```
  774. To iterate a view, either use it in a range-for loop:
  775. ```cpp
  776. auto view = registry.view<position, velocity>();
  777. for(auto entity: view) {
  778. // a component at a time ...
  779. auto &position = view.get<position>(entity);
  780. auto &velocity = view.get<velocity>(entity);
  781. // ... or multiple components at once
  782. auto &[pos, vel] = view.get<position, velocity>(entity);
  783. // ...
  784. }
  785. ```
  786. Or rely on the `each` member function to iterate entities and get all their
  787. components at once:
  788. ```cpp
  789. registry.view<position, velocity>().each([](auto entity, auto &pos, auto &vel) {
  790. // ...
  791. });
  792. ```
  793. The `each` member function is highly optimized. Unless users want to iterate
  794. only entities or get only some of the components, this should be the preferred
  795. approach. Note that the entity can also be excluded from the parameter list if
  796. not required, but this won't improve performance for multi component views.<br/>
  797. There exists also an alternative version of `each` named `less` that works
  798. exactly as its counterpart but for the fact that it doesn't return empty
  799. components to the caller.
  800. As a side note, when using a single component view, the most common error is to
  801. invoke `get` with the type of the component as a template parameter. This is
  802. probably due to the fact that it's required for multi component views:
  803. ```cpp
  804. auto view = registry.view<position, const velocity>();
  805. for(auto entity: view) {
  806. const auto &vel = view.get<const velocity>(entity);
  807. // ...
  808. }
  809. ```
  810. However, in case of a single component view, `get` doesn't accept a template
  811. parameter, since it's implicitly defined by the view itself:
  812. ```cpp
  813. auto view = registry.view<const renderable>();
  814. for(auto entity: view) {
  815. const auto &renderable = view.get(entity);
  816. // ...
  817. }
  818. ```
  819. **Note**: prefer the `get` member function of a view instead of the `get` member
  820. function template of a registry during iterations, if possible. However, keep in
  821. mind that it works only with the components of the view itself.
  822. ## Runtime views
  823. Runtime views iterate entities that have at least all the given components in
  824. their bags. During construction, these views look at the number of entities
  825. available for each component and pick up a reference to the smallest
  826. set of candidates in order to speed up iterations.<br/>
  827. They offer more or less the same functionalities of a multi component view.
  828. However, they don't expose a `get` member function and users should refer to the
  829. registry that generated the view to access components. In particular, a runtime
  830. view exposes utility functions to get the estimated number of entities it is
  831. going to return and to know whether it's empty or not. It's also possible to ask
  832. a runtime view if it contains a given entity.<br/>
  833. Refer to the inline documentation for all the details.
  834. Runtime view are extremely cheap to construct and should not be stored around in
  835. any case. They should be used immediately after creation and then they should be
  836. thrown away. The reasons for this go far beyond the scope of this document.<br/>
  837. To iterate a runtime view, either use it in a range-for loop:
  838. ```cpp
  839. using component_type = typename decltype(registry)::component_type;
  840. component_type types[] = { registry.type<position>(), registry.type<velocity>() };
  841. auto view = registry.runtime_view(std::cbegin(types), std::cend(types));
  842. for(auto entity: view) {
  843. // a component at a time ...
  844. auto &position = registry.get<position>(entity);
  845. auto &velocity = registry.get<velocity>(entity);
  846. // ... or multiple components at once
  847. auto &[pos, vel] = registry.get<position, velocity>(entity);
  848. // ...
  849. }
  850. ```
  851. Or rely on the `each` member function to iterate entities:
  852. ```cpp
  853. using component_type = typename decltype(registry)::component_type;
  854. component_type types[] = { registry.type<position>(), registry.type<velocity>() };
  855. auto view = registry.runtime_view(std::cbegin(types), std::cend(types)).each([](auto entity) {
  856. // ...
  857. });
  858. ```
  859. Performance are exactly the same in both cases.
  860. **Note**: runtime views are meant for all those cases where users don't know at
  861. compile-time what components to use to iterate entities. This is particularly
  862. well suited to plugin systems and mods in general. Where possible, don't use
  863. runtime views, as their performance are slightly inferior to those of the other
  864. views.
  865. ## Groups
  866. Groups are meant to iterate multiple components at once and offer a faster
  867. alternative to views. Roughly speaking, they just play in another league when
  868. compared to views.<br/>
  869. Groups overcome the performance of the other tools available but require to get
  870. the ownership of components and this sets some constraints on pools. On the
  871. other side, groups aren't an automatism that increases memory consumption,
  872. affects functionalities and tries to optimize iterations for all the possible
  873. combinations of components. Users can decide when to pay for groups and to what
  874. extent.<br/>
  875. The most interesting aspect of groups is that they fit _usage patterns_. Other
  876. solutions around usually try to optimize everything, because it is known that
  877. somewhere within the _everything_ there are also our usage patterns. However
  878. this has a cost that isn't negligible, both in terms of performance and memory
  879. usage. Ironically, users pay the price also for things they don't want and this
  880. isn't something I like much. Even worse, one cannot easily disable such a
  881. behavior. Groups work differently instead and are designed to optimize only the
  882. real use cases when users find they need to.<br/>
  883. Another nice-to-have feature of groups is that they have no impact on memory
  884. consumption, put aside full non-owning groups that are pretty rare and should be
  885. avoided as long as possible.
  886. All groups affect to an extent the creation and destruction of their components.
  887. This is due to the fact that they must _observe_ changes in the pools of
  888. interest and arrange data _correctly_ when needed for the types they own.<br/>
  889. That being said, the way groups operate is beyond the scope of this document.
  890. However, it's unlikely that users will be able to appreciate the impact of
  891. groups on other functionalities of the registry.
  892. Groups offer a bunch of functionalities to get the number of entities they are
  893. going to return and a raw access to the entity list as well as to the component
  894. list for owned components. It's also possible to ask a group if it contains a
  895. given entity.<br/>
  896. Refer to the inline documentation for all the details.
  897. There is no need to store groups around for they are extremely cheap to
  898. construct, even though they can be copied without problems and reused freely.
  899. A group performs an initialization step the very first time it's requested and
  900. this could be quite costly. To avoid it, consider creating the group when no
  901. components have been assigned yet. If the registry is empty, preparation is
  902. extremely fast. Groups also return newly created and correctly initialized
  903. iterators whenever `begin` or `end` are invoked.
  904. To iterate groups, either use them in a range-for loop:
  905. ```cpp
  906. auto group = registry.group<position>(entt::get<velocity>);
  907. for(auto entity: group) {
  908. // a component at a time ...
  909. auto &position = group.get<position>(entity);
  910. auto &velocity = group.get<velocity>(entity);
  911. // ... or multiple components at once
  912. auto &[pos, vel] = group.get<position, velocity>(entity);
  913. // ...
  914. }
  915. ```
  916. Or rely on the `each` member function to iterate entities and get all their
  917. components at once:
  918. ```cpp
  919. registry.group<position>(entt::get<velocity>).each([](auto entity, auto &pos, auto &vel) {
  920. // ...
  921. });
  922. ```
  923. The `each` member function is highly optimized. Unless users want to iterate
  924. only entities, this should be the preferred approach. Note that the entity can
  925. also be excluded from the parameter list if not required and it can improve even
  926. further the performance during iterations.
  927. **Note**: prefer the `get` member function of a group instead of the `get`
  928. member function template of a registry during iterations, if possible. However,
  929. keep in mind that it works only with the components of the group itself.
  930. Let's go a bit deeper into the different types of groups made available by this
  931. library to know how they are constructed and what are the differences between
  932. them.
  933. ### Full-owning groups
  934. A full-owning group is the fastest tool an user can expect to use to iterate
  935. multiple components at once. It iterates all the components directly, no
  936. indirection required. This type of groups performs more or less as if users are
  937. accessing sequentially a bunch of packed arrays of components all sorted
  938. identically.
  939. A full-owning group is created as:
  940. ```cpp
  941. auto group = registry.group<position, velocity>();
  942. ```
  943. Filtering entities by components is also supported:
  944. ```cpp
  945. auto group = registry.group<position, velocity>(entt::exclude<renderable>);
  946. ```
  947. Once created, the group gets the ownership of all the components specified in
  948. the template parameter list and arranges their pools so as to iterate all of
  949. them as fast as possible.
  950. Sorting owned components is no longer allowed once the group has been created.
  951. However, full-owning groups can be sorted by means of their `sort` member
  952. functions, if required. Sorting a full-owning group affects all the instance of
  953. the same group (it means that users don't have to call `sort` on each instance
  954. to sort all of them because they share the underlying data structure).
  955. ### Partial-owning groups
  956. A partial-owning group works similarly to a full-owning group for the components
  957. it owns, but relies on indirection to get components owned by other groups. This
  958. isn't as fast as a full-owning group, but it's already much faster than views
  959. when there are only one or two free components to retrieve (the most common
  960. cases likely). In the worst case, it's not slower than views anyway.
  961. A partial-owning group is created as:
  962. ```cpp
  963. auto group = registry.group<position>(entt::get<velocity>);
  964. ```
  965. Filtering entities by components is also supported:
  966. ```cpp
  967. auto group = registry.group<position>(entt::get<velocity>, entt::exclude<renderable>);
  968. ```
  969. Once created, the group gets the ownership of all the components specified in
  970. the template parameter list and arranges their pools so as to iterate all of
  971. them as fast as possible. The ownership of the types provided via `entt::get`
  972. doesn't pass to the group instead.
  973. Sorting owned components is no longer allowed once the group has been created.
  974. However, partial-owning groups can be sorted by means of their `sort` member
  975. functions, if required. Sorting a partial-owning group affects all the instance
  976. of the same group (it means that users don't have to call `sort` on each
  977. instance to sort all of them because they share the underlying data structure).
  978. ### Non-owning groups
  979. Non-owning groups are usually fast enough, for sure faster than views and well
  980. suited for most of the cases. However, they require custom data structures to
  981. work properly and they increase memory consumption. As a rule of thumb, users
  982. should avoid using non-owning groups, if possible.
  983. A non-owning group is created as:
  984. ```cpp
  985. auto group = registry.group<>(entt::get<position, velocity>);
  986. ```
  987. Filtering entities by components is also supported:
  988. ```cpp
  989. auto group = registry.group<>(entt::get<position, velocity>, entt::exclude<renderable>);
  990. ```
  991. The group doesn't receive the ownership of any type of component in this
  992. case. This type of groups is therefore the least performing in general, but also
  993. the only one that can be used in any situation to improve a performance where
  994. necessary.
  995. Non-owning groups can be sorted by means of their `sort` member functions, if
  996. required. Sorting a non-owning group affects all the instance of the same group
  997. (it means that users don't have to call `sort` on each instance to sort all of
  998. them because they share the set of entities).
  999. # Types: const, non-const and all in between
  1000. The `registry` class offers two overloads when it comes to constructing views
  1001. and groups: a const version and a non-const one. The former accepts both const
  1002. and non-const types as template parameters, the latter accepts only const types
  1003. instead.<br/>
  1004. It means that views and groups can be constructed also from a const registry and
  1005. they propagate the constness of the registry to the types involved. As an
  1006. example:
  1007. ```cpp
  1008. entt::view<const position, const velocity> view = std::as_const(registry).view<const position, const velocity>();
  1009. ```
  1010. Consider the following definition for a non-const view instead:
  1011. ```cpp
  1012. entt::view<position, const velocity> view = registry.view<position, const velocity>();
  1013. ```
  1014. In the example above, `view` can be used to access either read-only or writable
  1015. `position` components while `velocity` components are read-only in all
  1016. cases.<br/>
  1017. In other terms, these statements are all valid:
  1018. ```cpp
  1019. position &pos = view.get<position>(entity);
  1020. const position &cpos = view.get<const position>(entity);
  1021. const velocity &cpos = view.get<const velocity>(entity);
  1022. std::tuple<position &, const velocity &> tup = view.get<position, const velocity>(entity);
  1023. std::tuple<const position &, const velocity &> ctup = view.get<const position, const velocity>(entity);
  1024. ```
  1025. It's not possible to get non-const references to `velocity` components from the
  1026. same view instead and these will result in compilation errors:
  1027. ```cpp
  1028. velocity &cpos = view.get<velocity>(entity);
  1029. std::tuple<position &, velocity &> tup = view.get<position, velocity>(entity);
  1030. std::tuple<const position &, velocity &> ctup = view.get<const position, velocity>(entity);
  1031. ```
  1032. Similarly, the `each` member functions will propagate constness to the type of
  1033. the components returned during iterations:
  1034. ```cpp
  1035. view.each([](auto entity, position &pos, const velocity &vel) {
  1036. // ...
  1037. });
  1038. ```
  1039. Obviously, a caller can still refer to the `position` components through a const
  1040. reference because of the rules of the language that fortunately already allow
  1041. it.
  1042. The same concepts apply to groups as well.
  1043. ## Give me everything
  1044. Views and groups are narrow windows on the entire list of entities. They work by
  1045. filtering entities according to their components.<br/>
  1046. In some cases there may be the need to iterate all the entities still in use
  1047. regardless of their components. The registry offers a specific member function
  1048. to do that:
  1049. ```cpp
  1050. registry.each([](auto entity) {
  1051. // ...
  1052. });
  1053. ```
  1054. It returns to the caller all the entities that are still in use by means of the
  1055. given function.<br/>
  1056. As a rule of thumb, consider using a view or a group if the goal is to iterate
  1057. entities that have a determinate set of components. These tools are usually much
  1058. faster than combining this function with a bunch of custom tests.<br/>
  1059. In all the other cases, this is the way to go.
  1060. There exists also another member function to use to retrieve orphans. An orphan
  1061. is an entity that is still in use and has no assigned components.<br/>
  1062. The signature of the function is the same of `each`:
  1063. ```cpp
  1064. registry.orphans([](auto entity) {
  1065. // ...
  1066. });
  1067. ```
  1068. To test the _orphanity_ of a single entity, use the member function `orphan`
  1069. instead. It accepts a valid entity identifer as an argument and returns true in
  1070. case the entity is an orphan, false otherwise.
  1071. In general, all these functions can result in poor performance.<br/>
  1072. `each` is fairly slow because of some checks it performs on each and every
  1073. entity. For similar reasons, `orphans` can be even slower. Both functions should
  1074. not be used frequently to avoid the risk of a performance hit.
  1075. ## What is allowed and what is not
  1076. Most of the _ECS_ available out there don't allow to create and destroy entities
  1077. and components during iterations.<br/>
  1078. `EnTT` partially solves the problem with a few limitations:
  1079. * Creating entities and components is allowed during iterations in almost all
  1080. cases.
  1081. * Deleting the current entity or removing its components is allowed during
  1082. iterations. For all the other entities, destroying them or removing their
  1083. components isn't allowed and can result in undefined behavior.
  1084. In these cases, iterators aren't invalidated. To be clear, it doesn't mean that
  1085. also references will continue to be valid.<br/>
  1086. Consider the following example:
  1087. ```cpp
  1088. registry.view<position>([&](const auto entity, auto &pos) {
  1089. registry.assign<position>(registry.create(), 0., 0.);
  1090. pos.x = 0.; // warning: dangling pointer
  1091. });
  1092. ```
  1093. The `each` member function won't break (because iterators aren't invalidated)
  1094. but there are no guarantees on references. Use a common range-for loop and get
  1095. components directly from the view or move the creation of components at the end
  1096. of the function to avoid dangling pointers.
  1097. Iterators are invalidated instead and the behavior is undefined if an entity is
  1098. modified or destroyed and it's not the one currently returned by the iterator
  1099. nor a newly created one.<br/>
  1100. To work around it, possible approaches are:
  1101. * Store aside the entities and the components to be removed and perform the
  1102. operations at the end of the iteration.
  1103. * Mark entities and components with a proper tag component that indicates they
  1104. must be purged, then perform a second iteration to clean them up one by one.
  1105. A notable side effect of this feature is that the number of required allocations
  1106. is further reduced in most of the cases.
  1107. ### More performance, more constraints
  1108. Groups are a (much) faster alternative to views. However, the higher the
  1109. performance, the greater the constraints on what is allowed and what is
  1110. not.<br/>
  1111. In particular, groups add in some rare cases a limitation on the creation of
  1112. components during iterations. It happens in quite particular cases. Given the
  1113. nature and the scope of the groups, it isn't something in which it will happen
  1114. to come across probably, but it's good to know it anyway.
  1115. First of all, it must be said that creating components while iterating a group
  1116. isn't a problem at all and can be done freely as it happens with the views. The
  1117. same applies to the destruction of components and entities, for which the rules
  1118. mentioned above apply.
  1119. The additional limitation pops out instead when a given component that is owned
  1120. by a group is iterated outside of it. In this case, adding components that are
  1121. part of the group itself may invalidate the iterators. There are no further
  1122. limitations to the destruction of components and entities.<br/>
  1123. Fortunately, this isn't always true. In fact, it almost never is and this
  1124. happens only under certain conditions. In particular:
  1125. * Iterating a type of component that is part of a group with a single component
  1126. view and adding to an entity all the components required to get it into the
  1127. group may invalidate the iterators.
  1128. * Iterating a type of component that is part of a group with a multi component
  1129. view and adding to an entity all the components required to get it into the
  1130. group can invalidate the iterators, unless users specify another type of
  1131. component to use to induce the order of iteration of the view (in this case,
  1132. the former is treated as a free type and isn't affected by the limitation).
  1133. In other words, the limitation doesn't exist as long as a type is treated as a
  1134. free type (as an example with multi component views and partial- or non-owning
  1135. groups) or iterated with its own group, but it can occur if the type is used as
  1136. a main type to rule on an iteration.<br/>
  1137. This happens because groups own the pools of their components and organize the
  1138. data internally to maximize performance. Because of that, full consistency for
  1139. owned components is guaranteed only when they are iterated as part of their
  1140. groups or as free types with multi component views and groups in general.
  1141. # Empty type optimization
  1142. An empty type `T` is such that `std::is_empty_v<T>` returns true. They are also
  1143. the same types for which _empty base optimization_ (EBO) is possibile.<br/>
  1144. `EnTT` handles these types in a special way, optimizing both in terms of
  1145. performance and memory usage. However, this also has consequences that are worth
  1146. mentioning.
  1147. When an empty type is detected, it's not instantiated in any case. Therefore,
  1148. only the entities to which it's assigned are made available. All the iterators
  1149. as well as the `get` member functions of the registry, the views and the groups
  1150. will return temporary objects. Similarly, some functions such as `try_get` or
  1151. the raw access to the list of components aren't available for this kind of
  1152. types.<br/>
  1153. On the other hand, iterations are faster because only the entities to which the
  1154. type is assigned are considered. Moreover, less memory is used, since there
  1155. doesn't exist any instance of the component, no matter how many entities it is
  1156. assigned to.
  1157. For similar reasons, wherever a function type of a listener accepts a component,
  1158. it cannot be caught by a non-const reference. Capture it by copy or by const
  1159. reference instead.
  1160. More in general, none of the features offered by the library is affected, but
  1161. for the ones that require to return actual instances.
  1162. # Multithreading
  1163. In general, the entire registry isn't thread safe as it is. Thread safety isn't
  1164. something that users should want out of the box for several reasons. Just to
  1165. mention one of them: performance.<br/>
  1166. Views, groups and consequently the approach adopted by `EnTT` are the great
  1167. exception to the rule. It's true that views, groups and iterators in general
  1168. aren't thread safe by themselves. Because of this users shouldn't try to iterate
  1169. a set of components and modify the same set concurrently. However:
  1170. * As long as a thread iterates the entities that have the component `X` or
  1171. assign and removes that component from a set of entities, another thread can
  1172. safely do the same with components `Y` and `Z` and everything will work like a
  1173. charm. As a trivial example, users can freely execute the rendering system and
  1174. iterate the renderable entities while updating a physic component concurrently
  1175. on a separate thread.
  1176. * Similarly, a single set of components can be iterated by multiple threads as
  1177. long as the components are neither assigned nor removed in the meantime. In
  1178. other words, a hypothetical movement system can start multiple threads, each
  1179. of which will access the components that carry information about velocity and
  1180. position for its entities.
  1181. This kind of entity-component systems can be used in single threaded
  1182. applications as well as along with async stuff or multiple threads. Moreover,
  1183. typical thread based models for _ECS_ don't require a fully thread safe registry
  1184. to work. Actually, users can reach the goal with the registry as it is while
  1185. working with most of the common models.
  1186. Because of the few reasons mentioned above and many others not mentioned, users
  1187. are completely responsible for synchronization whether required. On the other
  1188. hand, they could get away with it without having to resort to particular
  1189. expedients.
  1190. ## Iterators
  1191. A special mention is needed for the iterators returned by the views and the
  1192. groups. Most of the time they meet the requirements of random access iterators,
  1193. in all cases they meet at least the requirements of forward iterators.<br/>
  1194. In other terms, they are suitable for use with the parallel algorithms of the
  1195. standard library. If it's not clear, this is a great thing.
  1196. As an example, this kind of iterators can be used in combination with
  1197. `std::for_each` and `std::execution::par` to parallelize the visit and therefore
  1198. the update of the components returned by a view or a group, as long as the
  1199. constraints previously discussed are respected:
  1200. ```cpp
  1201. auto view = registry.view<position, const velocity>();
  1202. std::for_each(std::execution::par_unseq, view.begin(), view.end(), [&view](auto entity) {
  1203. // ...
  1204. });
  1205. ```
  1206. This can increase the throughput considerably, even without resorting to who
  1207. knows what artifacts that are difficult to maintain over time.
  1208. Unfortunately, because of the limitations of the current revision of the
  1209. standard, the parallel `std::for_each` accepts only forward iterators. This
  1210. means that the iterators provided by the library cannot return proxy objects as
  1211. references and **must** return actual reference types instead.<br/>
  1212. This may change in the future and the iterators will almost certainly return
  1213. both the entities and a list of references to their components sooner or later.
  1214. Multi-pass guarantee won't break in any case and the performance should even
  1215. benefit from it further.