Flecs v3.2
A fast entity component system (ECS) for C & C++
Loading...
Searching...
No Matches
component.hpp
Go to the documentation of this file.
1
6#pragma once
7
8#include <ctype.h>
9#include <stdio.h>
10
19namespace flecs {
20
21namespace _ {
22
23// Trick to obtain typename from type, as described here
24// https://blog.molecular-matters.com/2015/12/11/getting-the-type-of-a-template-argument-as-string-without-rtti/
25//
26// The code from the link has been modified to work with more types, and across
27// multiple compilers. The resulting string should be the same on all platforms
28// for all compilers.
29//
30
31#if defined(__GNUC__) || defined(_WIN32)
32template <typename T>
33inline static const char* type_name() {
34 static const size_t len = ECS_FUNC_TYPE_LEN(const char*, type_name, ECS_FUNC_NAME);
35 static char result[len + 1] = {};
36 static const size_t front_len = ECS_FUNC_NAME_FRONT(const char*, type_name);
37 return ecs_cpp_get_type_name(result, ECS_FUNC_NAME, len, front_len);
38}
39#else
40#error "implicit component registration not supported"
41#endif
42
43// Translate a typename into a language-agnostic identifier. This allows for
44// registration of components/modules across language boundaries.
45template <typename T>
46inline static const char* symbol_name() {
47 static const size_t len = ECS_FUNC_TYPE_LEN(const char*, symbol_name, ECS_FUNC_NAME);
48 static char result[len + 1] = {};
49 return ecs_cpp_get_symbol_name(result, type_name<T>(), len);
50}
51
52template <> inline const char* symbol_name<uint8_t>() {
53 return "u8";
54}
55template <> inline const char* symbol_name<uint16_t>() {
56 return "u16";
57}
58template <> inline const char* symbol_name<uint32_t>() {
59 return "u32";
60}
61template <> inline const char* symbol_name<uint64_t>() {
62 return "u64";
63}
64template <> inline const char* symbol_name<int8_t>() {
65 return "i8";
66}
67template <> inline const char* symbol_name<int16_t>() {
68 return "i16";
69}
70template <> inline const char* symbol_name<int32_t>() {
71 return "i32";
72}
73template <> inline const char* symbol_name<int64_t>() {
74 return "i64";
75}
76template <> inline const char* symbol_name<float>() {
77 return "f32";
78}
79template <> inline const char* symbol_name<double>() {
80 return "f64";
81}
82
83// If type is trivial, don't register lifecycle actions. While the functions
84// that obtain the lifecycle callback do detect whether the callback is required
85// adding a special case for trivial types eases the burden a bit on the
86// compiler as it reduces the number of templates to evaluate.
87template<typename T, enable_if_t<
88 std::is_trivial<T>::value == true
89 >* = nullptr>
90void register_lifecycle_actions(ecs_world_t*, ecs_entity_t) { }
91
92// If the component is non-trivial, register component lifecycle actions.
93// Depending on the type not all callbacks may be available.
94template<typename T, enable_if_t<
95 std::is_trivial<T>::value == false
96 >* = nullptr>
97void register_lifecycle_actions(
100{
101 ecs_type_hooks_t cl{};
102 cl.ctor = ctor<T>();
103 cl.dtor = dtor<T>();
104
105 cl.copy = copy<T>();
106 cl.copy_ctor = copy_ctor<T>();
107 cl.move = move<T>();
108 cl.move_ctor = move_ctor<T>();
109
110 cl.ctor_move_dtor = ctor_move_dtor<T>();
111 cl.move_dtor = move_dtor<T>();
112
114}
115
116// Class that manages component ids across worlds & binaries.
117// The cpp_type class stores the component id for a C++ type in a static global
118// variable that is shared between worlds. Whenever a component is used this
119// class will check if it already has been registered (has the global id been
120// set), and if not, register the component with the world.
121//
122// If the id has been set, the class will ensure it is known by the world. If it
123// is not known the component has been registered by another world and will be
124// registered with the world using the same id. If the id does exist, the class
125// will register it as a component, and verify whether the input is consistent.
126template <typename T>
128 // Initialize component identifier
129 static void init(
130 entity_t entity,
131 bool allow_tag = true)
132 {
133 if (s_reset_count != ecs_cpp_reset_count_get()) {
134 reset();
135 }
136
137 // If an identifier was already set, check for consistency
138 if (s_id) {
139 ecs_assert(s_id == entity, ECS_INCONSISTENT_COMPONENT_ID,
140 type_name<T>());
141 ecs_assert(allow_tag == s_allow_tag, ECS_INVALID_PARAMETER, NULL);
142
143 // Component was already registered and data is consistent with new
144 // identifier, so nothing else to be done.
145 return;
146 }
147
148 // Component wasn't registered yet, set the values. Register component
149 // name as the fully qualified flecs path.
150 s_id = entity;
151 s_allow_tag = allow_tag;
152 s_size = sizeof(T);
153 s_alignment = alignof(T);
154 if (is_empty<T>::value && allow_tag) {
155 s_size = 0;
156 s_alignment = 0;
157 }
158
159 s_reset_count = ecs_cpp_reset_count_get();
160 }
161
162 // Obtain a component identifier for explicit component registration.
163 static entity_t id_explicit(world_t *world = nullptr,
164 const char *name = nullptr, bool allow_tag = true, flecs::id_t id = 0,
165 bool is_component = true, bool *existing = nullptr)
166 {
167 if (!s_id) {
168 // If no world was provided the component cannot be registered
169 ecs_assert(world != nullptr, ECS_COMPONENT_NOT_REGISTERED, name);
170 } else {
171 ecs_assert(!id || s_id == id, ECS_INCONSISTENT_COMPONENT_ID, NULL);
172 }
173
174 // If no id has been registered yet for the component (indicating the
175 // component has not yet been registered, or the component is used
176 // across more than one binary), or if the id does not exists in the
177 // world (indicating a multi-world application), register it. */
178 if (!s_id || (world && !ecs_exists(world, s_id))) {
179 init(s_id ? s_id : id, allow_tag);
180
181 ecs_assert(!id || s_id == id, ECS_INTERNAL_ERROR, NULL);
182
183 const char *symbol = nullptr;
184 if (id) {
185 symbol = ecs_get_symbol(world, id);
186 }
187 if (!symbol) {
188 symbol = symbol_name<T>();
189 }
190
191 entity_t entity = ecs_cpp_component_register_explicit(
192 world, s_id, id, name, type_name<T>(), symbol,
193 s_size, s_alignment, is_component, existing);
194
195 s_id = entity;
196
197 // If component is enum type, register constants
198 #if FLECS_CPP_ENUM_REFLECTION_SUPPORT
199 _::init_enum<T>(world, entity);
200 #endif
201 }
202
203 // By now the identifier must be valid and known with the world.
204 ecs_assert(s_id != 0 && ecs_exists(world, s_id),
205 ECS_INTERNAL_ERROR, NULL);
206
207 return s_id;
208 }
209
210 // Obtain a component identifier for implicit component registration. This
211 // is almost the same as id_explicit, except that this operation
212 // automatically registers lifecycle callbacks.
213 // Additionally, implicit registration temporarily resets the scope & with
214 // state of the world, so that the component is not implicitly created with
215 // the scope/with of the code it happens to be first used by.
216 static id_t id(world_t *world = nullptr, const char *name = nullptr,
217 bool allow_tag = true)
218 {
219 // If no id has been registered yet, do it now.
220 if (!registered(world)) {
221 ecs_entity_t prev_scope = 0;
222 ecs_id_t prev_with = 0;
223
224 if (world) {
225 prev_scope = ecs_set_scope(world, 0);
226 prev_with = ecs_set_with(world, 0);
227 }
228
229 // This will register a component id, but will not register
230 // lifecycle callbacks.
231 bool existing;
232 id_explicit(world, name, allow_tag, 0, true, &existing);
233
234 // Register lifecycle callbacks, but only if the component has a
235 // size. Components that don't have a size are tags, and tags don't
236 // require construction/destruction/copy/move's. */
237 if (size() && !existing) {
238 register_lifecycle_actions<T>(world, s_id);
239 }
240
241 if (prev_with) {
242 ecs_set_with(world, prev_with);
243 }
244 if (prev_scope) {
245 ecs_set_scope(world, prev_scope);
246 }
247 }
248
249 // By now we should have a valid identifier
250 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
251
252 return s_id;
253 }
254
255 // Return the size of a component.
256 static size_t size() {
257 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
258 return s_size;
259 }
260
261 // Return the alignment of a component.
262 static size_t alignment() {
263 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
264 return s_alignment;
265 }
266
267 // Was the component already registered.
268 static bool registered(flecs::world_t *world) {
269 if (s_reset_count != ecs_cpp_reset_count_get()) {
270 reset();
271 }
272 if (s_id == 0) {
273 return false;
274 }
275 if (world && !ecs_exists(world, s_id)) {
276 return false;
277 }
278 return true;
279 }
280
281 // This function is only used to test cross-translation unit features. No
282 // code other than test cases should invoke this function.
283 static void reset() {
284 s_id = 0;
285 s_size = 0;
286 s_alignment = 0;
287 s_allow_tag = true;
288 }
289
290 static entity_t s_id;
291 static size_t s_size;
292 static size_t s_alignment;
293 static bool s_allow_tag;
294 static int32_t s_reset_count;
295};
296
297// Global templated variables that hold component identifier and other info
298template <typename T> entity_t cpp_type_impl<T>::s_id;
299template <typename T> size_t cpp_type_impl<T>::s_size;
300template <typename T> size_t cpp_type_impl<T>::s_alignment;
301template <typename T> bool cpp_type_impl<T>::s_allow_tag( true );
302template <typename T> int32_t cpp_type_impl<T>::s_reset_count;
303
304// Front facing class for implicitly registering a component & obtaining
305// static component data
306
307// Regular type
308template <typename T>
309struct cpp_type<T, if_not_t< is_pair<T>::value >>
310 : cpp_type_impl<base_type_t<T>> { };
311
312// Pair type
313template <typename T>
314struct cpp_type<T, if_t< is_pair<T>::value >>
315{
316 // Override id method to return id of pair
317 static id_t id(world_t *world = nullptr) {
318 return ecs_pair(
321 }
322};
323
324} // namespace _
325
332 using entity::entity;
333
334# ifdef FLECS_META
336# endif
337# ifdef FLECS_METRICS
338# include "mixins/metrics/untyped_component.inl"
339# endif
340};
341
347template <typename T>
359 flecs::world_t *world,
360 const char *name = nullptr,
361 bool allow_tag = true,
362 flecs::id_t id = 0)
363 {
364 const char *n = name;
365 bool implicit_name = false;
366 if (!n) {
367 n = _::type_name<T>();
368
369 /* Keep track of whether name was explicitly set. If not, and the
370 * component was already registered, just use the registered name.
371 *
372 * The registered name may differ from the typename as the registered
373 * name includes the flecs scope. This can in theory be different from
374 * the C++ namespace though it is good practice to keep them the same */
375 implicit_name = true;
376 }
377
379 /* Obtain component id. Because the component is already registered,
380 * this operation does nothing besides returning the existing id */
381 id = _::cpp_type<T>::id_explicit(world, name, allow_tag, id);
382
383 ecs_cpp_component_validate(world, id, n, _::symbol_name<T>(),
386 implicit_name);
387 } else {
388 /* If component is registered from an existing scope, ignore the
389 * namespace in the name of the component. */
390 if (implicit_name && (ecs_get_scope(world) != 0)) {
391 /* If the type is a template type, make sure to ignore ':'
392 * inside the template parameter list. */
393 const char *start = strchr(n, '<'), *last_elem = NULL;
394 if (start) {
395 const char *ptr = start;
396 while (ptr[0] && (ptr[0] != ':') && (ptr > n)) {
397 ptr --;
398 }
399 if (ptr[0] == ':') {
400 last_elem = ptr;
401 }
402 } else {
403 last_elem = strrchr(n, ':');
404 }
405 if (last_elem) {
406 name = last_elem + 1;
407 }
408 }
409
410 /* Find or register component */
411 bool existing;
412 id = ecs_cpp_component_register(world, id, n, _::symbol_name<T>(),
413 ECS_SIZEOF(T), ECS_ALIGNOF(T), implicit_name, &existing);
414
415 /* Initialize static component data */
416 id = _::cpp_type<T>::id_explicit(world, name, allow_tag, id);
417
418 /* Initialize lifecycle actions (ctor, dtor, copy, move) */
419 if (_::cpp_type<T>::size() && !existing) {
420 _::register_lifecycle_actions<T>(world, id);
421 }
422 }
423
424 m_world = world;
425 m_id = id;
426 }
427
429 template <typename Func>
430 component<T>& on_add(Func&& func) {
431 using Invoker = typename _::each_invoker<
432 typename std::decay<Func>::type, T>;
433 flecs::type_hooks_t h = get_hooks();
434 ecs_assert(h.on_add == nullptr, ECS_INVALID_OPERATION,
435 "on_add hook is already set");
436 BindingCtx *ctx = get_binding_ctx(h);
437 h.on_add = Invoker::run_add;
438 ctx->on_add = FLECS_NEW(Invoker)(FLECS_FWD(func));
439 ctx->free_on_add = reinterpret_cast<ecs_ctx_free_t>(
440 _::free_obj<Invoker>);
441 ecs_set_hooks_id(m_world, m_id, &h);
442 return *this;
443 }
444
446 template <typename Func>
447 component<T>& on_remove(Func&& func) {
448 using Invoker = typename _::each_invoker<
449 typename std::decay<Func>::type, T>;
450 flecs::type_hooks_t h = get_hooks();
451 ecs_assert(h.on_remove == nullptr, ECS_INVALID_OPERATION,
452 "on_remove hook is already set");
453 BindingCtx *ctx = get_binding_ctx(h);
454 h.on_remove = Invoker::run_remove;
455 ctx->on_remove = FLECS_NEW(Invoker)(FLECS_FWD(func));
456 ctx->free_on_remove = reinterpret_cast<ecs_ctx_free_t>(
457 _::free_obj<Invoker>);
458 ecs_set_hooks_id(m_world, m_id, &h);
459 return *this;
460 }
461
463 template <typename Func>
464 component<T>& on_set(Func&& func) {
465 using Invoker = typename _::each_invoker<
466 typename std::decay<Func>::type, T>;
467 flecs::type_hooks_t h = get_hooks();
468 ecs_assert(h.on_set == nullptr, ECS_INVALID_OPERATION,
469 "on_set hook is already set");
470 BindingCtx *ctx = get_binding_ctx(h);
471 h.on_set = Invoker::run_set;
472 ctx->on_set = FLECS_NEW(Invoker)(FLECS_FWD(func));
473 ctx->free_on_set = reinterpret_cast<ecs_ctx_free_t>(
474 _::free_obj<Invoker>);
475 ecs_set_hooks_id(m_world, m_id, &h);
476 return *this;
477 }
478
479# ifdef FLECS_META
480# include "mixins/meta/component.inl"
481# endif
482
483private:
484 using BindingCtx = _::component_binding_ctx;
485
486 BindingCtx* get_binding_ctx(flecs::type_hooks_t& h){
487 BindingCtx *result = static_cast<BindingCtx*>(h.binding_ctx);
488 if (!result) {
489 result = FLECS_NEW(BindingCtx);
490 h.binding_ctx = result;
491 h.binding_ctx_free = reinterpret_cast<ecs_ctx_free_t>(
492 _::free_obj<BindingCtx>);
493 }
494 return result;
495 }
496
497 flecs::type_hooks_t get_hooks() {
498 const flecs::type_hooks_t* h = ecs_get_hooks_id(m_world, m_id);
499 if (h) {
500 return *h;
501 } else {
502 return {};
503 }
504 }
505};
506
509template <typename T>
510flecs::entity_t type_id() {
511 if (_::cpp_type<T>::s_reset_count == ecs_cpp_reset_count_get()) {
513 } else {
514 return 0;
515 }
516}
517
540inline void reset() {
541 ecs_cpp_reset_count_inc();
542}
543
544}
545
flecs::entity_t type_id()
Get id currently assigned to component.
Definition: component.hpp:510
ecs_entity_t ecs_set_with(ecs_world_t *world, ecs_id_t id)
Set current with id.
#define ecs_assert(condition, error_code,...)
Assert.
Definition: log.h:352
const ecs_type_hooks_t * ecs_get_hooks_id(ecs_world_t *world, ecs_entity_t id)
Get hooks for component.
void ecs_set_hooks_id(ecs_world_t *world, ecs_entity_t id, const ecs_type_hooks_t *hooks)
Register hooks for component.
ecs_id_t ecs_entity_t
An entity identifier.
Definition: flecs.h:286
struct ecs_world_t ecs_world_t
A world is the container for all ECS data and supporting features.
Definition: flecs.h:330
uint64_t ecs_id_t
Ids are the things that can be added to an entity.
Definition: flecs.h:279
void reset()
Reset static component ids.
Definition: component.hpp:540
transcribe_cv_t< remove_reference_t< P >, typename remove_reference_t< P >::second > pair_second_t
Get pair::second from pair while preserving cv qualifiers.
Definition: pair.hpp:91
transcribe_cv_t< remove_reference_t< P >, typename remove_reference_t< P >::first > pair_first_t
Get pair::first from pair while preserving cv qualifiers.
Definition: pair.hpp:87
void(* ecs_ctx_free_t)(void *ctx)
Function to cleanup context data.
Definition: flecs.h:590
bool ecs_exists(const ecs_world_t *world, ecs_entity_t entity)
Test whether an entity exists.
ecs_entity_t ecs_get_scope(const ecs_world_t *world)
Get the current scope.
const char * ecs_get_symbol(const ecs_world_t *world, ecs_entity_t entity)
Get the symbol of an entity.
ecs_entity_t ecs_set_scope(ecs_world_t *world, ecs_entity_t scope)
Set the current scope.
Meta component mixin.
Type that contains component lifecycle callbacks.
Definition: flecs.h:810
ecs_iter_action_t on_remove
Callback that is invoked when an instance of the component is removed.
Definition: flecs.h:846
void * binding_ctx
Language binding context.
Definition: flecs.h:849
ecs_iter_action_t on_set
Callback that is invoked when an instance of the component is set.
Definition: flecs.h:841
ecs_xtor_t ctor
ctor
Definition: flecs.h:811
ecs_iter_action_t on_add
Callback that is invoked when an instance of a component is added.
Definition: flecs.h:836
ecs_ctx_free_t binding_ctx_free
Callback to free binding_ctx.
Definition: flecs.h:852
Component class.
Definition: component.hpp:348
component< T > & on_remove(Func &&func)
Register on_remove hook.
Definition: component.hpp:447
component(flecs::world_t *world, const char *name=nullptr, bool allow_tag=true, flecs::id_t id=0)
Register a component.
Definition: component.hpp:358
component< T > & on_add(Func &&func)
Register on_add hook.
Definition: component.hpp:430
component< T > & on_set(Func &&func)
Register on_set hook.
Definition: component.hpp:464
flecs::string_view name() const
Return the entity name.
Definition: entity_view.hpp:78
Entity.
Definition: entity.hpp:30
Class that wraps around a flecs::id_t.
Definition: decl.hpp:27
Test if type is a pair.
Definition: pair.hpp:80
Untyped component class.
Definition: component.hpp:331
The world.
Definition: world.hpp:132
void start()
Start timer.