Flecs v4.0
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 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 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 if (cl.move == ecs_move_illegal || cl.move_ctor == ecs_move_ctor_illegal) {
116 ecs_add_id(world, component, flecs::Sparse);
117 }
118}
119
120// Class that manages component ids across worlds & binaries.
121// The type class stores the component id for a C++ type in a static global
122// variable that is shared between worlds. Whenever a component is used this
123// class will check if it already has been registered (has the global id been
124// set), and if not, register the component with the world.
125//
126// If the id has been set, the class will ensure it is known by the world. If it
127// is not known the component has been registered by another world and will be
128// registered with the world using the same id. If the id does exist, the class
129// will register it as a component, and verify whether the input is consistent.
130template <typename T>
131struct type_impl {
132 static_assert(is_pointer<T>::value == false,
133 "pointer types are not allowed for components");
134
135 // Initialize component identifier
136 static void init(
137 entity_t entity,
138 bool allow_tag = true)
139 {
140 if (s_reset_count != ecs_cpp_reset_count_get()) {
141 reset();
142 }
143
144 // If an identifier was already set, check for consistency
145 if (s_id) {
146 ecs_assert(s_id == entity, ECS_INCONSISTENT_COMPONENT_ID,
147 type_name<T>());
148 ecs_assert(allow_tag == s_allow_tag, ECS_INVALID_PARAMETER, NULL);
149
150 // Component was already registered and data is consistent with new
151 // identifier, so nothing else to be done.
152 return;
153 }
154
155 // Component wasn't registered yet, set the values. Register component
156 // name as the fully qualified flecs path.
157 s_id = entity;
158 s_allow_tag = allow_tag;
159 s_size = sizeof(T);
160 s_alignment = alignof(T);
161 if (is_empty<T>::value && allow_tag) {
162 s_size = 0;
163 s_alignment = 0;
164 }
165
166 s_reset_count = ecs_cpp_reset_count_get();
167 }
168
169 // Obtain a component identifier for explicit component registration.
170 static entity_t id_explicit(world_t *world = nullptr,
171 const char *name = nullptr, bool allow_tag = true, flecs::id_t id = 0,
172 bool is_component = true, bool *existing = nullptr)
173 {
174 if (!s_id) {
175 // If no world was provided the component cannot be registered
176 ecs_assert(world != nullptr, ECS_COMPONENT_NOT_REGISTERED, name);
177 } else {
178 ecs_assert(!id || s_id == id, ECS_INCONSISTENT_COMPONENT_ID, NULL);
179 }
180
181 // If no id has been registered yet for the component (indicating the
182 // component has not yet been registered, or the component is used
183 // across more than one binary), or if the id does not exists in the
184 // world (indicating a multi-world application), register it.
185 if (!s_id || (world && !ecs_exists(world, s_id))) {
186 init(s_id ? s_id : id, allow_tag);
187
188 ecs_assert(!id || s_id == id, ECS_INTERNAL_ERROR, NULL);
189
190 const char *symbol = nullptr;
191 if (id) {
192 symbol = ecs_get_symbol(world, id);
193 }
194 if (!symbol) {
195 symbol = symbol_name<T>();
196 }
197
198 entity_t entity = ecs_cpp_component_register_explicit(
199 world, s_id, id, name, type_name<T>(), symbol,
200 s_size, s_alignment, is_component, existing);
201
202 s_id = entity;
203
204 // If component is enum type, register constants
205 #if FLECS_CPP_ENUM_REFLECTION_SUPPORT
206 _::init_enum<T>(world, entity);
207 #endif
208 }
209
210 // By now the identifier must be valid and known with the world.
211 ecs_assert(s_id != 0 && ecs_exists(world, s_id),
212 ECS_INTERNAL_ERROR, NULL);
213
214 return s_id;
215 }
216
217 // Obtain a component identifier for implicit component registration. This
218 // is almost the same as id_explicit, except that this operation
219 // automatically registers lifecycle callbacks.
220 // Additionally, implicit registration temporarily resets the scope & with
221 // state of the world, so that the component is not implicitly created with
222 // the scope/with of the code it happens to be first used by.
223 static id_t id(world_t *world = nullptr, const char *name = nullptr,
224 bool allow_tag = true)
225 {
226 // If no id has been registered yet, do it now.
227#ifndef FLECS_CPP_NO_AUTO_REGISTRATION
228 if (!registered(world)) {
229 ecs_entity_t prev_scope = 0;
230 ecs_id_t prev_with = 0;
231
232 if (world) {
233 prev_scope = ecs_set_scope(world, 0);
234 prev_with = ecs_set_with(world, 0);
235 }
236
237 // This will register a component id, but will not register
238 // lifecycle callbacks.
239 bool existing;
240 id_explicit(world, name, allow_tag, 0, true, &existing);
241
242 // Register lifecycle callbacks, but only if the component has a
243 // size. Components that don't have a size are tags, and tags don't
244 // require construction/destruction/copy/move's.
245 if (size() && !existing) {
246 register_lifecycle_actions<T>(world, s_id);
247 }
248
249 if (prev_with) {
250 ecs_set_with(world, prev_with);
251 }
252 if (prev_scope) {
253 ecs_set_scope(world, prev_scope);
254 }
255 }
256#else
257 (void)world;
258 (void)name;
259 (void)allow_tag;
260
261 ecs_assert(registered(world), ECS_INVALID_OPERATION,
262 "component '%s' was not registered before use",
263 type_name<T>());
264#endif
265
266 // By now we should have a valid identifier
267 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
268
269 return s_id;
270 }
271
272 // Return the size of a component.
273 static size_t size() {
274 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
275 return s_size;
276 }
277
278 // Return the alignment of a component.
279 static size_t alignment() {
280 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
281 return s_alignment;
282 }
283
284 // Was the component already registered.
285 static bool registered(flecs::world_t *world) {
286 if (s_reset_count != ecs_cpp_reset_count_get()) {
287 reset();
288 }
289 if (s_id == 0) {
290 return false;
291 }
292 if (world && !ecs_exists(world, s_id)) {
293 return false;
294 }
295 return true;
296 }
297
298 // This function is only used to test cross-translation unit features. No
299 // code other than test cases should invoke this function.
300 static void reset() {
301 s_id = 0;
302 s_size = 0;
303 s_alignment = 0;
304 s_allow_tag = true;
305 }
306
307 static entity_t s_id;
308 static size_t s_size;
309 static size_t s_alignment;
310 static bool s_allow_tag;
311 static int32_t s_reset_count;
312};
313
314// Global templated variables that hold component identifier and other info
315template <typename T> entity_t type_impl<T>::s_id;
316template <typename T> size_t type_impl<T>::s_size;
317template <typename T> size_t type_impl<T>::s_alignment;
318template <typename T> bool type_impl<T>::s_allow_tag( true );
319template <typename T> int32_t type_impl<T>::s_reset_count;
320
321// Front facing class for implicitly registering a component & obtaining
322// static component data
323
324// Regular type
325template <typename T>
326struct type<T, if_not_t< is_pair<T>::value >>
327 : type_impl<base_type_t<T>> { };
328
329// Pair type
330template <typename T>
331struct type<T, if_t< is_pair<T>::value >>
332{
333 // Override id method to return id of pair
334 static id_t id(world_t *world = nullptr) {
335 return ecs_pair(
336 type< pair_first_t<T> >::id(world),
337 type< pair_second_t<T> >::id(world));
338 }
339};
340
341} // namespace _
342
349 using entity::entity;
350
351# ifdef FLECS_META
353# endif
354# ifdef FLECS_METRICS
355# include "mixins/metrics/untyped_component.inl"
356# endif
357};
358
364template <typename T>
376 flecs::world_t *world,
377 const char *name = nullptr,
378 bool allow_tag = true,
379 flecs::id_t id = 0)
380 {
381 const char *n = name;
382 bool implicit_name = false;
383 if (!n) {
384 n = _::type_name<T>();
385
386 /* Keep track of whether name was explicitly set. If not, and the
387 * component was already registered, just use the registered name.
388 *
389 * The registered name may differ from the typename as the registered
390 * name includes the flecs scope. This can in theory be different from
391 * the C++ namespace though it is good practice to keep them the same */
392 implicit_name = true;
393 }
394
396 /* Obtain component id. Because the component is already registered,
397 * this operation does nothing besides returning the existing id */
398 id = _::type<T>::id_explicit(world, name, allow_tag, id);
399
400 ecs_cpp_component_validate(world, id, n, _::symbol_name<T>(),
403 implicit_name);
404 } else {
405 /* If component is registered from an existing scope, ignore the
406 * namespace in the name of the component. */
407 if (implicit_name && (ecs_get_scope(world) != 0)) {
408 /* If the type is a template type, make sure to ignore ':'
409 * inside the template parameter list. */
410 const char *start = strchr(n, '<'), *last_elem = NULL;
411 if (start) {
412 const char *ptr = start;
413 while (ptr[0] && (ptr[0] != ':') && (ptr > n)) {
414 ptr --;
415 }
416 if (ptr[0] == ':') {
417 last_elem = ptr;
418 }
419 }
420
421 if (last_elem) {
422 name = last_elem + 1;
423 }
424 }
425
426 /* Find or register component */
427 bool existing;
428 id = ecs_cpp_component_register(world, id, n, _::symbol_name<T>(),
429 ECS_SIZEOF(T), ECS_ALIGNOF(T), implicit_name, &existing);
430
431 /* Initialize static component data */
432 id = _::type<T>::id_explicit(world, name, allow_tag, id);
433
434 /* Initialize lifecycle actions (ctor, dtor, copy, move) */
435 if (_::type<T>::size() && !existing) {
436 _::register_lifecycle_actions<T>(world, id);
437 }
438 }
439
440 world_ = world;
441 id_ = id;
442 }
443
445 template <typename Func>
446 component<T>& on_add(Func&& func) {
447 using Delegate = typename _::each_delegate<typename std::decay<Func>::type, T>;
448 flecs::type_hooks_t h = get_hooks();
449 ecs_assert(h.on_add == nullptr, ECS_INVALID_OPERATION,
450 "on_add hook is already set");
451 BindingCtx *ctx = get_binding_ctx(h);
452 h.on_add = Delegate::run_add;
453 ctx->on_add = FLECS_NEW(Delegate)(FLECS_FWD(func));
454 ctx->free_on_add = reinterpret_cast<ecs_ctx_free_t>(
455 _::free_obj<Delegate>);
456 ecs_set_hooks_id(world_, id_, &h);
457 return *this;
458 }
459
461 template <typename Func>
462 component<T>& on_remove(Func&& func) {
463 using Delegate = typename _::each_delegate<
464 typename std::decay<Func>::type, T>;
465 flecs::type_hooks_t h = get_hooks();
466 ecs_assert(h.on_remove == nullptr, ECS_INVALID_OPERATION,
467 "on_remove hook is already set");
468 BindingCtx *ctx = get_binding_ctx(h);
469 h.on_remove = Delegate::run_remove;
470 ctx->on_remove = FLECS_NEW(Delegate)(FLECS_FWD(func));
471 ctx->free_on_remove = reinterpret_cast<ecs_ctx_free_t>(
472 _::free_obj<Delegate>);
473 ecs_set_hooks_id(world_, id_, &h);
474 return *this;
475 }
476
478 template <typename Func>
479 component<T>& on_set(Func&& func) {
480 using Delegate = typename _::each_delegate<
481 typename std::decay<Func>::type, T>;
482 flecs::type_hooks_t h = get_hooks();
483 ecs_assert(h.on_set == nullptr, ECS_INVALID_OPERATION,
484 "on_set hook is already set");
485 BindingCtx *ctx = get_binding_ctx(h);
486 h.on_set = Delegate::run_set;
487 ctx->on_set = FLECS_NEW(Delegate)(FLECS_FWD(func));
488 ctx->free_on_set = reinterpret_cast<ecs_ctx_free_t>(
489 _::free_obj<Delegate>);
490 ecs_set_hooks_id(world_, id_, &h);
491 return *this;
492 }
493
494# ifdef FLECS_META
495# include "mixins/meta/component.inl"
496# endif
497
498private:
499 using BindingCtx = _::component_binding_ctx;
500
501 BindingCtx* get_binding_ctx(flecs::type_hooks_t& h){
502 BindingCtx *result = static_cast<BindingCtx*>(h.binding_ctx);
503 if (!result) {
504 result = FLECS_NEW(BindingCtx);
505 h.binding_ctx = result;
506 h.binding_ctx_free = reinterpret_cast<ecs_ctx_free_t>(
507 _::free_obj<BindingCtx>);
508 }
509 return result;
510 }
511
512 flecs::type_hooks_t get_hooks() {
513 const flecs::type_hooks_t* h = ecs_get_hooks_id(world_, id_);
514 if (h) {
515 return *h;
516 } else {
517 return {};
518 }
519 }
520};
521
524template <typename T>
525flecs::entity_t type_id() {
526 if (_::type<T>::s_reset_count == ecs_cpp_reset_count_get()) {
527 return _::type<T>::s_id;
528 } else {
529 return 0;
530 }
531}
532
555inline void reset() {
556 ecs_cpp_reset_count_inc();
557}
558
559}
560
flecs::entity_t type_id()
Get id currently assigned to component.
ecs_entity_t ecs_set_with(ecs_world_t *world, ecs_id_t id)
Set current with id.
void ecs_add_id(ecs_world_t *world, ecs_entity_t entity, ecs_id_t id)
Add a (component) id to an entity.
#define ecs_assert(condition, error_code,...)
Assert.
Definition log.h:352
void ecs_set_hooks_id(ecs_world_t *world, ecs_entity_t id, const ecs_type_hooks_t *hooks)
Register hooks for component.
const ecs_type_hooks_t * ecs_get_hooks_id(const ecs_world_t *world, ecs_entity_t id)
Get hooks for component.
ecs_id_t ecs_entity_t
An entity identifier.
Definition flecs.h:339
struct ecs_world_t ecs_world_t
A world is the container for all ECS data and supporting features.
Definition flecs.h:383
uint64_t ecs_id_t
Ids are the things that can be added to an entity.
Definition flecs.h:332
void reset()
Reset static component ids.
transcribe_cv_t< remove_reference_t< P >, typename raw_type_t< P >::second > pair_second_t
Get pair::second from pair while preserving cv qualifiers.
Definition pair.hpp:92
transcribe_cv_t< remove_reference_t< P >, typename raw_type_t< P >::first > pair_first_t
Get pair::first from pair while preserving cv qualifiers.
Definition pair.hpp:88
void(* ecs_ctx_free_t)(void *ctx)
Function to cleanup context data.
Definition flecs.h:584
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:830
ecs_iter_action_t on_remove
Callback that is invoked when an instance of the component is removed.
Definition flecs.h:866
void * binding_ctx
Language binding context.
Definition flecs.h:869
ecs_iter_action_t on_set
Callback that is invoked when an instance of the component is set.
Definition flecs.h:861
ecs_xtor_t ctor
ctor
Definition flecs.h:831
ecs_iter_action_t on_add
Callback that is invoked when an instance of a component is added.
Definition flecs.h:856
ecs_ctx_free_t binding_ctx_free
Callback to free binding_ctx.
Definition flecs.h:872
Component class.
component< T > & on_remove(Func &&func)
Register on_remove hook.
component(flecs::world_t *world, const char *name=nullptr, bool allow_tag=true, flecs::id_t id=0)
Register a component.
component< T > & on_add(Func &&func)
Register on_add hook.
component< T > & on_set(Func &&func)
Register on_set hook.
flecs::string_view name() const
Return the entity name.
entity_t id() const
Get entity id.
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:82
Untyped component class.
The world.
Definition world.hpp:137