Flecs v4.1
A fast entity component system (ECS) for C & C++
Loading...
Searching...
No Matches
delegate.hpp
Go to the documentation of this file.
1
6#pragma once
7
8#include <utility> // std::declval
9
10namespace flecs
11{
12
13namespace _
14{
15
16// Binding ctx for component hooks
18 void *on_add = nullptr;
19 void *on_remove = nullptr;
20 void *on_set = nullptr;
21 void *on_replace = nullptr;
22 ecs_ctx_free_t free_on_add = nullptr;
23 ecs_ctx_free_t free_on_remove = nullptr;
24 ecs_ctx_free_t free_on_set = nullptr;
25 ecs_ctx_free_t free_on_replace = nullptr;
26
28 if (on_add && free_on_add) {
29 free_on_add(on_add);
30 }
31 if (on_remove && free_on_remove) {
32 free_on_remove(on_remove);
33 }
34 if (on_set && free_on_set) {
35 free_on_set(on_set);
36 }
37 if (on_replace && free_on_replace) {
38 free_on_replace(on_replace);
39 }
40 }
41};
42
43// Utility to convert template argument pack to array of term ptrs
44struct field_ptr {
45 void *ptr = nullptr;
46 int8_t index = 0;
47 bool is_ref = false;
48 bool is_row = false;
49};
50
51template <typename ... Components>
52struct field_ptrs {
53 using array = flecs::array<_::field_ptr, sizeof...(Components)>;
54
55 void populate(const ecs_iter_t *iter) {
56 populate_impl(iter, std::index_sequence_for<Components...>{});
57 }
58
59 void populate_self(const ecs_iter_t *iter) {
60 populate_self_impl(iter, std::index_sequence_for<Components...>{});
61 }
62
63 array fields_;
64
65private:
66 template <typename T>
67 void populate_field(const ecs_iter_t *iter, size_t index) {
68 using A = remove_pointer_t<actual_type_t<T>>;
69 if constexpr (!is_empty_v<A>) {
70 if (iter->row_fields & (1llu << index)) {
71 /* Need to fetch the value with ecs_field_at() */
72 fields_[index].is_row = true;
73 fields_[index].is_ref = true;
74 fields_[index].index = static_cast<int8_t>(index);
75 } else {
76 fields_[index].ptr = ecs_field_w_size(iter, sizeof(A),
77 static_cast<int8_t>(index));
78 fields_[index].is_ref = iter->sources[index] != 0;
79 }
80 }
81 }
82
83 template <typename T>
84 void populate_self_field(const ecs_iter_t *iter, size_t index) {
85 (void)iter; (void)index;
86
87 using A = remove_pointer_t<actual_type_t<T>>;
88 if constexpr (!is_empty_v<A>) {
89 fields_[index].ptr = ecs_field_w_size(iter, sizeof(A),
90 static_cast<int8_t>(index));
91 fields_[index].is_ref = false;
92 }
93 }
94
95 template <size_t... Is>
96 void populate_impl(const ecs_iter_t *iter, std::index_sequence<Is...>) {
97 (void)iter;
98 (populate_field<Components>(iter, Is), ...);
99 }
100
101 template <size_t... Is>
102 void populate_self_impl(const ecs_iter_t *iter, std::index_sequence<Is...>) {
103 (void)iter;
104 (populate_self_field<Components>(iter, Is), ...);
105 }
106};
107
108struct delegate { };
109
110// Template that figures out from the template parameters of a query/system
111// how to pass the value to the each callback
112template <typename T, typename = int>
113struct each_field { };
114
115// Base class
117 each_column_base(const _::field_ptr& field, size_t row)
118 : field_(field), row_(row) {
119 }
120
121protected:
122 const _::field_ptr& field_;
123 size_t row_;
124};
125
126// If type is not a pointer, return a reference to the type (default case)
127template <typename T>
128struct each_field<T, if_t< !is_pointer<T>::value &&
129 !is_empty<actual_type_t<T>>::value && is_actual<T>::value > >
131{
132 each_field(const flecs::iter_t*, _::field_ptr& field, size_t row)
133 : each_column_base(field, row) { }
134
135 T& get_row() {
136 return static_cast<T*>(this->field_.ptr)[this->row_];
137 }
138};
139
140// If argument type is not the same as actual component type, return by value.
141// This requires that the actual type can be converted to the type.
142// A typical scenario where this happens is when using flecs::pair types.
143template <typename T>
144struct each_field<T, if_t< !is_pointer<T>::value &&
145 !is_empty<actual_type_t<T>>::value && !is_actual<T>::value> >
147{
148 each_field(const flecs::iter_t*, _::field_ptr& field, size_t row)
149 : each_column_base(field, row) { }
150
151 T get_row() {
152 return static_cast<actual_type_t<T>*>(this->field_.ptr)[this->row_];
153 }
154};
155
156// If type is empty (indicating a tag) the query will pass a nullptr. To avoid
157// returning nullptr to reference arguments, return a temporary value.
158template <typename T>
159struct each_field<T, if_t< is_empty<actual_type_t<T>>::value &&
160 !is_pointer<T>::value > >
162{
163 each_field(const flecs::iter_t*, _::field_ptr& field, size_t row)
164 : each_column_base(field, row) { }
165
166 T get_row() {
167 return actual_type_t<T>();
168 }
169};
170
171// If type is a pointer (indicating an optional value) don't index with row if
172// the field is not set.
173template <typename T>
174struct each_field<T, if_t< is_pointer<T>::value &&
175 !is_empty<actual_type_t<T>>::value > >
177{
178 each_field(const flecs::iter_t*, _::field_ptr& field, size_t row)
179 : each_column_base(field, row) { }
180
181 actual_type_t<T> get_row() {
182 if (this->field_.ptr) {
183 return &static_cast<actual_type_t<T>>(this->field_.ptr)[this->row_];
184 } else {
185 // optional argument doesn't have a value
186 return nullptr;
187 }
188 }
189};
190
191// If the query contains component references to other entities, check if the
192// current argument is one.
193template <typename T, typename = int>
194struct each_ref_field : public each_field<T> {
196 : each_field<T>(iter, field, row) {
197
198 if (field.is_ref) {
199 // If this is a reference, set the row to 0 as a ref always is a
200 // single value, not an array. This prevents the application from
201 // having to do an if-check on whether the column is owned.
202 //
203 // This check only happens when the current table being iterated
204 // over caused the query to match a reference. The check is
205 // performed once per iterated table.
206 this->row_ = 0;
207 }
208
209 if (field.is_row) {
210 field.ptr = ecs_field_at_w_size(iter, sizeof(T), field.index,
211 static_cast<int32_t>(row));
212 }
213 }
214};
215
216// Type that handles passing components to each callbacks
217template <typename Func, typename ... Components>
218struct each_delegate : public delegate {
219 using Terms = typename field_ptrs<Components ...>::array;
220
221 template < if_not_t< is_same< decay_t<Func>, decay_t<Func>& >::value > = 0>
222 explicit each_delegate(Func&& func) noexcept
223 : func_(FLECS_MOV(func)) { }
224
225 explicit each_delegate(const Func& func) noexcept
226 : func_(func) { }
227
228 // Invoke object directly. This operation is useful when the calling
229 // function has just constructed the delegate, such as what happens when
230 // iterating a query.
231 void invoke(ecs_iter_t *iter) const {
232 field_ptrs<Components...> terms;
233
234 iter->flags |= EcsIterCppEach;
235
236 if (iter->ref_fields | iter->up_fields) {
237 terms.populate(iter);
238 invoke_unpack< each_ref_field >(iter, func_, 0, terms.fields_);
239 } else {
240 terms.populate_self(iter);
241 invoke_unpack< each_field >(iter, func_, 0, terms.fields_);
242 }
243 }
244
245 // Static function that can be used as callback for systems/triggers
246 static void run(ecs_iter_t *iter) {
247 auto self = static_cast<const each_delegate*>(iter->callback_ctx);
248 ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL);
249 self->invoke(iter);
250 }
251
252 // Static function that can be used as callback for systems/triggers.
253 // Different from run() in that it loops the iterator.
254 static void run_each(ecs_iter_t *iter) {
255 auto self = static_cast<const each_delegate*>(iter->run_ctx);
256 ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL);
257 while (iter->next(iter)) {
258 self->invoke(iter);
259 }
260 }
261
262 // Create instance of delegate
263 static each_delegate* make(const Func& func) {
264 return FLECS_NEW(each_delegate)(func);
265 }
266
267 // Function that can be used as callback to free delegate
268 static void destruct(void *obj) {
269 _::free_obj<each_delegate>(obj);
270 }
271
272 // Static function to call for component on_add hook
273 static void run_add(ecs_iter_t *iter) {
274 component_binding_ctx *ctx = reinterpret_cast<component_binding_ctx*>(
275 iter->callback_ctx);
276 iter->callback_ctx = ctx->on_add;
277 run(iter);
278 }
279
280 // Static function to call for component on_remove hook
281 static void run_remove(ecs_iter_t *iter) {
282 component_binding_ctx *ctx = reinterpret_cast<component_binding_ctx*>(
283 iter->callback_ctx);
284 iter->callback_ctx = ctx->on_remove;
285 run(iter);
286 }
287
288 // Static function to call for component on_set hook
289 static void run_set(ecs_iter_t *iter) {
290 component_binding_ctx *ctx = reinterpret_cast<component_binding_ctx*>(
291 iter->callback_ctx);
292 iter->callback_ctx = ctx->on_set;
293 run(iter);
294 }
295
296 // Static function to call for component on_replace hook
297 static void run_replace(ecs_iter_t *iter) {
298 component_binding_ctx *ctx = reinterpret_cast<component_binding_ctx*>(
299 iter->callback_ctx);
300 iter->callback_ctx = ctx->on_replace;
301 run(iter);
302 }
303
304private:
305 // func(flecs::entity, Components...)
306 template <template<typename X, typename = int> class ColumnType,
307 typename... Args,
308 typename Fn = Func,
309 decltype(std::declval<const Fn&>()(
310 std::declval<flecs::entity>(),
311 std::declval<ColumnType< remove_reference_t<Components> > >().get_row()...), 0) = 0>
312 static void invoke_callback(
313 ecs_iter_t *iter, const Func& func, size_t i, Args... comps)
314 {
315 ecs_assert(iter->entities != nullptr, ECS_INVALID_PARAMETER,
316 "query does not return entities ($this variable is not populated)");
317 func(flecs::entity(iter->world, iter->entities[i]),
318 (ColumnType< remove_reference_t<Components> >(iter, comps, i)
319 .get_row())...);
320 }
321
322 // func(flecs::iter&, size_t row, Components...)
323 template <template<typename X, typename = int> class ColumnType,
324 typename... Args,
325 typename Fn = Func,
326 decltype(std::declval<const Fn&>()(
327 std::declval<flecs::iter&>(),
328 std::declval<size_t&>(),
329 std::declval<ColumnType< remove_reference_t<Components> > >().get_row()...), 0) = 0>
330 static void invoke_callback(
331 ecs_iter_t *iter, const Func& func, size_t i, Args... comps)
332 {
333 flecs::iter it(iter);
334 func(it, i, (ColumnType< remove_reference_t<Components> >(iter, comps, i)
335 .get_row())...);
336 }
337
338 // func(Components...)
339 template <template<typename X, typename = int> class ColumnType,
340 typename... Args,
341 typename Fn = Func,
342 decltype(std::declval<const Fn&>()(
343 std::declval<ColumnType< remove_reference_t<Components> > >().get_row()...), 0) = 0>
344 static void invoke_callback(
345 ecs_iter_t *iter, const Func& func, size_t i, Args... comps)
346 {
347 func((ColumnType< remove_reference_t<Components> >(iter, comps, i)
348 .get_row())...);
349 }
350
351 template <template<typename X, typename = int> class ColumnType,
352 typename... Args, if_t<
353 sizeof...(Components) == sizeof...(Args)> = 0>
354 static void invoke_unpack(
355 ecs_iter_t *iter, const Func& func, size_t, Terms&, Args... comps)
356 {
357 ECS_TABLE_LOCK(iter->world, iter->table);
358
359 size_t count = static_cast<size_t>(iter->count);
360 if (count == 0 && !iter->table) {
361 // If query has no This terms, count can be 0. Since each does not
362 // have an entity parameter, just pass through components
363 count = 1;
364 }
365
366 for (size_t i = 0; i < count; i ++) {
367 invoke_callback<ColumnType>(iter, func, i, comps...);
368 }
369
370 ECS_TABLE_UNLOCK(iter->world, iter->table);
371 }
372
373 template <template<typename X, typename = int> class ColumnType,
374 typename... Args, if_t< sizeof...(Components) != sizeof...(Args) > = 0>
375 static void invoke_unpack(ecs_iter_t *iter, const Func& func,
376 size_t index, Terms& columns, Args... comps)
377 {
378 invoke_unpack<ColumnType>(
379 iter, func, index + 1, columns, comps..., columns[index]);
380 }
381
382public:
383 Func func_;
384};
385
386template <typename Func, typename ... Components>
387struct find_delegate : public delegate {
388 using Terms = typename field_ptrs<Components ...>::array;
389
390 template < if_not_t< is_same< decay_t<Func>, decay_t<Func>& >::value > = 0>
391 explicit find_delegate(Func&& func) noexcept
392 : func_(FLECS_MOV(func)) { }
393
394 explicit find_delegate(const Func& func) noexcept
395 : func_(func) { }
396
397 // Invoke object directly. This operation is useful when the calling
398 // function has just constructed the delegate, such as what happens when
399 // iterating a query.
400 flecs::entity invoke(ecs_iter_t *iter) const {
401 field_ptrs<Components...> terms;
402
403 iter->flags |= EcsIterCppEach;
404
405 if (iter->ref_fields | iter->up_fields) {
406 terms.populate(iter);
407 return invoke_callback< each_ref_field >(iter, func_, 0, terms.fields_);
408 } else {
409 terms.populate_self(iter);
410 return invoke_callback< each_field >(iter, func_, 0, terms.fields_);
411 }
412 }
413
414private:
415 // Number of function arguments is one more than number of components, pass
416 // entity as argument.
417 template <template<typename X, typename = int> class ColumnType,
418 typename... Args,
419 typename Fn = Func,
420 if_t<sizeof...(Components) == sizeof...(Args)> = 0,
421 decltype(bool(std::declval<const Fn&>()(
422 std::declval<flecs::entity>(),
423 std::declval<ColumnType< remove_reference_t<Components> > >().get_row()...))) = true>
424 static flecs::entity invoke_callback(
425 ecs_iter_t *iter, const Func& func, size_t, Terms&, Args... comps)
426 {
427 ECS_TABLE_LOCK(iter->world, iter->table);
428
429 ecs_world_t *world = iter->world;
430 size_t count = static_cast<size_t>(iter->count);
431 flecs::entity result;
432
433 for (size_t i = 0; i < count; i ++) {
434 if (func(flecs::entity(world, iter->entities[i]),
435 (ColumnType< remove_reference_t<Components> >(iter, comps, i)
436 .get_row())...))
437 {
438 result = flecs::entity(world, iter->entities[i]);
439 break;
440 }
441 }
442
443 ECS_TABLE_UNLOCK(iter->world, iter->table);
444
445 return result;
446 }
447
448 // Number of function arguments is two more than number of components, pass
449 // iter + index as argument.
450 template <template<typename X, typename = int> class ColumnType,
451 typename... Args,
452 typename Fn = Func,
453 if_t<sizeof...(Components) == sizeof...(Args)> = 0,
454 decltype(bool(std::declval<const Fn&>()(
455 std::declval<flecs::iter&>(),
456 std::declval<size_t&>(),
457 std::declval<ColumnType< remove_reference_t<Components> > >().get_row()...))) = true>
458 static flecs::entity invoke_callback(
459 ecs_iter_t *iter, const Func& func, size_t, Terms&, Args... comps)
460 {
461 size_t count = static_cast<size_t>(iter->count);
462 if (count == 0) {
463 // If query has no This terms, count can be 0. Since each does not
464 // have an entity parameter, just pass through components
465 count = 1;
466 }
467
468 flecs::iter it(iter);
469 flecs::entity result;
470
471 ECS_TABLE_LOCK(iter->world, iter->table);
472
473 for (size_t i = 0; i < count; i ++) {
474 if (func(it, i,
475 (ColumnType< remove_reference_t<Components> >(iter, comps, i)
476 .get_row())...))
477 {
478 result = flecs::entity(iter->world, iter->entities[i]);
479 break;
480 }
481 }
482
483 ECS_TABLE_UNLOCK(iter->world, iter->table);
484
485 return result;
486 }
487
488 // Number of function arguments is equal to number of components, no entity
489 template <template<typename X, typename = int> class ColumnType,
490 typename... Args,
491 typename Fn = Func,
492 if_t<sizeof...(Components) == sizeof...(Args)> = 0,
493 decltype(bool(std::declval<const Fn&>()(
494 std::declval<ColumnType< remove_reference_t<Components> > >().get_row()...))) = true>
495 static flecs::entity invoke_callback(
496 ecs_iter_t *iter, const Func& func, size_t, Terms&, Args... comps)
497 {
498 size_t count = static_cast<size_t>(iter->count);
499 if (count == 0) {
500 // If query has no This terms, count can be 0. Since each does not
501 // have an entity parameter, just pass through components
502 count = 1;
503 }
504
505 flecs::iter it(iter);
506 flecs::entity result;
507
508 ECS_TABLE_LOCK(iter->world, iter->table);
509
510 for (size_t i = 0; i < count; i ++) {
511 if (func(
512 (ColumnType< remove_reference_t<Components> >(iter, comps, i)
513 .get_row())...))
514 {
515 result = flecs::entity(iter->world, iter->entities[i]);
516 break;
517 }
518 }
519
520 ECS_TABLE_UNLOCK(iter->world, iter->table);
521
522 return result;
523 }
524
525 template <template<typename X, typename = int> class ColumnType,
526 typename... Args, if_t< sizeof...(Components) != sizeof...(Args) > = 0>
527 static flecs::entity invoke_callback(ecs_iter_t *iter, const Func& func,
528 size_t index, Terms& columns, Args... comps)
529 {
530 return invoke_callback<ColumnType>(
531 iter, func, index + 1, columns, comps..., columns[index]);
532 }
533
534 Func func_;
535};
536
540
541template <typename Func>
543 template < if_not_t< is_same< decay_t<Func>, decay_t<Func>& >::value > = 0>
544 explicit run_delegate(Func&& func) noexcept
545 : func_(FLECS_MOV(func)) { }
546
547 explicit run_delegate(const Func& func) noexcept
548 : func_(func) { }
549
550 // Invoke object directly. This operation is useful when the calling
551 // function has just constructed the delegate, such as what happens when
552 // iterating a query.
553 void invoke(ecs_iter_t *iter) const {
554 flecs::iter it(iter);
555 iter->flags &= ~EcsIterIsValid;
556 func_(it);
557 }
558
559 // Static function that can be used as callback for systems/triggers
560 static void run(ecs_iter_t *iter) {
561 auto self = static_cast<const run_delegate*>(iter->run_ctx);
562 ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL);
563 self->invoke(iter);
564 }
565
566 Func func_;
567};
568
569
573
574template <typename Func>
576 explicit entity_observer_delegate(Func&& func) noexcept
577 : func_(FLECS_MOV(func)) { }
578
579 // Static function that can be used as callback for systems/triggers
580 static void run(ecs_iter_t *iter) {
581 invoke<Func>(iter);
582 }
583
584private:
585 template <typename F,
586 decltype(std::declval<const F&>()(std::declval<flecs::entity>()), 0) = 0>
587 static void invoke(ecs_iter_t *iter) {
588 auto self = static_cast<const entity_observer_delegate*>(iter->callback_ctx);
589 ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL);
590 self->func_(flecs::entity(iter->world, ecs_field_src(iter, 0)));
591 }
592
593 template <typename F,
594 decltype(std::declval<const F&>()(), 0) = 0>
595 static void invoke(ecs_iter_t *iter) {
596 auto self = static_cast<const entity_observer_delegate*>(iter->callback_ctx);
597 ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL);
598 self->func_();
599 }
600
601 Func func_;
602};
603
604template <typename Func, typename Event>
606 explicit entity_payload_observer_delegate(Func&& func) noexcept
607 : func_(FLECS_MOV(func)) { }
608
609 // Static function that can be used as callback for systems/triggers
610 static void run(ecs_iter_t *iter) {
611 invoke<Func>(iter);
612 }
613
614private:
615 template <typename F,
616 decltype(std::declval<const F&>()(
617 std::declval<Event&>()), 0) = 0>
618 static void invoke(ecs_iter_t *iter) {
619 auto self = static_cast<const entity_payload_observer_delegate*>(
620 iter->callback_ctx);
621 ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL);
622 ecs_assert(iter->param != nullptr, ECS_INVALID_OPERATION,
623 "entity observer invoked without payload");
624
625 Event *data = static_cast<Event*>(iter->param);
626 self->func_(*data);
627 }
628
629 template <typename F,
630 decltype(std::declval<const F&>()(
631 std::declval<flecs::entity>(),
632 std::declval<Event&>()), 0) = 0>
633 static void invoke(ecs_iter_t *iter) {
634 auto self = static_cast<const entity_payload_observer_delegate*>(
635 iter->callback_ctx);
636 ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL);
637 ecs_assert(iter->param != nullptr, ECS_INVALID_OPERATION,
638 "entity observer invoked without payload");
639
640 Event *data = static_cast<Event*>(iter->param);
641 self->func_(flecs::entity(iter->world, ecs_field_src(iter, 0)), *data);
642 }
643
644 Func func_;
645};
646
647
651
652template<typename ... Args>
654
655template<typename ... Args>
657 using ColumnArray = flecs::array<int32_t, sizeof...(Args)>;
658 using ArrayType = flecs::array<void*, sizeof...(Args)>;
659 using DummyArray = flecs::array<int, sizeof...(Args)>;
660 using IdArray = flecs::array<id_t, sizeof...(Args)>;
661
662 static constexpr bool const_args() {
663 return (is_const_v<remove_reference_t<Args>> && ...);
664 }
665
666 static
667 bool get_ptrs(world_t *world, flecs::entity_t e, const ecs_record_t *r, ecs_table_t *table,
668 ArrayType& ptrs)
669 {
670 ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL);
671
672 /* table_index_of needs real world */
673 const flecs::world_t *real_world = ecs_get_world(world);
674
675 IdArray ids ({
676 _::type<Args>().id(world)...
677 });
678
679 /* Get column indices for components */
680 ColumnArray columns ({
682 _::type<Args>().id(world))...
683 });
684
685 /* Get pointers for columns for entity */
686 size_t i = 0;
687 for (int32_t column : columns) {
688 if (column == -1) {
689 /* Component could be sparse */
690 void *ptr = ecs_get_mut_id(world, e, ids[i]);
691 if (!ptr) {
692 return false;
693 }
694
695 ptrs[i ++] = ptr;
696 continue;
697 }
698
699 ptrs[i ++] = ecs_record_get_by_column(r, column, 0);
700 }
701
702 return true;
703 }
704
705 static bool ensure_ptrs(world_t *world, ecs_entity_t e, ArrayType& ptrs) {
706 /* Get pointers w/ensure */
707 size_t i = 0;
708 DummyArray dummy ({
709 (ptrs[i ++] = ecs_ensure_id(world, e,
710 _::type<Args>().id(world), sizeof(Args)), 0)...
711 });
712
713 return true;
714 }
715
716 template <typename Func>
717 static bool invoke_read(world_t *world, entity_t e, const Func& func) {
718 const ecs_record_t *r = ecs_read_begin(world, e);
719 if (!r) {
720 return false;
721 }
722
723 ecs_table_t *table = r->table;
724 if (!table) {
725 return false;
726 }
727
728 ArrayType ptrs;
729 bool has_components = get_ptrs(world, e, r, table, ptrs);
730 if (has_components) {
731 invoke_callback(func, 0, ptrs);
732 }
733
734 ecs_read_end(r);
735
736 return has_components;
737 }
738
739 template <typename Func>
740 static bool invoke_write(world_t *world, entity_t e, const Func& func) {
741 ecs_record_t *r = ecs_write_begin(world, e);
742 if (!r) {
743 return false;
744 }
745
746 ecs_table_t *table = r->table;
747 if (!table) {
748 return false;
749 }
750
751 ArrayType ptrs;
752 bool has_components = get_ptrs(world, e, r, table, ptrs);
753 if (has_components) {
754 invoke_callback(func, 0, ptrs);
755 }
756
757 ecs_write_end(r);
758
759 return has_components;
760 }
761
762 template <typename Func>
763 static bool invoke_get(world_t *world, entity_t e, const Func& func) {
764 if constexpr (const_args()) {
765 return invoke_read(world, e, func);
766 } else {
767 return invoke_write(world, e, func);
768 }
769 }
770
771 // Utility for storing id in array in pack expansion
772 static size_t store_added(IdArray& added, size_t elem, ecs_table_t *prev,
773 ecs_table_t *next, id_t id)
774 {
775 // Array should only contain ids for components that are actually added,
776 // so check if the prev and next tables are different.
777 if (prev != next) {
778 added[elem] = id;
779 elem ++;
780 }
781 return elem;
782 }
783
784 struct InvokeCtx {
785 InvokeCtx(flecs::table_t *table_arg) : table(table_arg) { }
786 flecs::table_t *table;
787 size_t component_count = 0;
788 IdArray added = {};
789 };
790
791 static int invoke_add(
792 flecs::world& w,
793 flecs::entity_t entity,
794 flecs::id_t component_id,
795 InvokeCtx& ctx)
796 {
797 ecs_table_diff_t diff;
798 flecs::table_t *next = flecs_table_traverse_add(
799 w, ctx.table, &component_id, &diff);
800 if (next != ctx.table) {
801 ctx.added[ctx.component_count] = component_id;
802 ctx.component_count ++;
803 } else {
804 if (diff.added_flags & EcsTableHasDontFragment) {
805 w.entity(entity).add(component_id);
806
807 ctx.added[ctx.component_count] = component_id;
808 ctx.component_count ++;
809 }
810 }
811
812 ctx.table = next;
813
814 return 0;
815 }
816
817 template <typename Func>
818 static bool invoke_ensure(
819 world_t *world,
820 entity_t id,
821 const Func& func)
822 {
823 flecs::world w(world);
824
825 ArrayType ptrs;
826 ecs_table_t *table = NULL;
827
828 // When not deferred take the fast path.
829 if (!w.is_deferred()) {
830 // Bit of low level code so we only do at most one table move & one
831 // entity lookup for the entire operation.
832
833 // Make sure the object is not a stage. Operations on a stage are
834 // only allowed when the stage is in deferred mode, which is when
835 // the world is in readonly mode.
836 ecs_assert(!w.is_stage(), ECS_INVALID_PARAMETER, NULL);
837
838 // Find table for entity
839 ecs_record_t *r = ecs_record_find(world, id);
840 if (r) {
841 table = r->table;
842 }
843
844 // Iterate components, only store added component ids in added array
845 InvokeCtx ctx(table);
846 DummyArray dummy_before ({ (
847 invoke_add(w, id, w.id<Args>(), ctx)
848 )... });
849
850 (void)dummy_before;
851
852 // If table is different, move entity straight to it
853 if (table != ctx.table) {
854 ecs_type_t ids;
855 ids.array = ctx.added.ptr();
856 ids.count = static_cast<ecs_size_t>(ctx.component_count);
857 ecs_commit(world, id, r, ctx.table, &ids, NULL);
858 table = ctx.table;
859 }
860
861 if (!get_ptrs(w, id, r, table, ptrs)) {
862 ecs_abort(ECS_INTERNAL_ERROR, NULL);
863 }
864
865 ECS_TABLE_LOCK(world, table);
866
867 // When deferred, obtain pointers with regular ensure
868 } else {
869 ensure_ptrs(world, id, ptrs);
870 }
871
872 invoke_callback(func, 0, ptrs);
873
874 if (!w.is_deferred()) {
875 ECS_TABLE_UNLOCK(world, table);
876 }
877
878 // Call modified on each component
879 DummyArray dummy_after ({
880 ( ecs_modified_id(world, id, w.id<Args>()), 0)...
881 });
882 (void)dummy_after;
883
884 return true;
885 }
886
887private:
888 template <typename Func, typename ... TArgs,
889 if_t<sizeof...(TArgs) == sizeof...(Args)> = 0>
890 static void invoke_callback(
891 const Func& f, size_t, ArrayType&, TArgs&& ... comps)
892 {
893 f(*static_cast<typename base_arg_type<Args>::type*>(comps)...);
894 }
895
896 template <typename Func, typename ... TArgs,
897 if_t<sizeof...(TArgs) != sizeof...(Args)> = 0>
898 static void invoke_callback(const Func& f, size_t arg, ArrayType& ptrs,
899 TArgs&& ... comps)
900 {
901 invoke_callback(f, arg + 1, ptrs, comps..., ptrs[arg]);
902 }
903};
904
905template <typename Func, typename U = int>
907 static_assert(function_traits<Func>::value, "type is not callable");
908};
909
910template <typename Func>
911struct entity_with_delegate<Func, if_t< is_callable<Func>::value > >
912 : entity_with_delegate_impl< arg_list_t<Func> >
913{
914 static_assert(function_traits<Func>::arity > 0,
915 "function must have at least one argument");
916};
917
918} // namespace _
919
920// Experimental: allows using the each delegate for use cases outside of flecs
921template <typename Func, typename ... Args>
923
924} // namespace flecs
#define ecs_assert(condition, error_code,...)
Assert.
Definition log.h:368
#define ecs_abort(error_code,...)
Abort.
Definition log.h:359
ecs_id_t ecs_entity_t
An entity identifier.
Definition flecs.h:381
struct ecs_world_t ecs_world_t
A world is the container for all ECS data and supporting features.
Definition flecs.h:425
struct ecs_record_t ecs_record_t
Information about an entity, like its table and row.
Definition flecs.h:490
struct ecs_table_t ecs_table_t
A table stores entities and components for a specific type.
Definition flecs.h:431
flecs::entity entity(Args &&... args) const
Create an entity.
flecs::id id(E value) const
Convert enum constant to entity.
void(* ecs_ctx_free_t)(void *ctx)
Function to cleanup context data.
Definition flecs.h:645
void ecs_modified_id(ecs_world_t *world, ecs_entity_t entity, ecs_id_t component)
Signal that a component has been modified.
void * ecs_get_mut_id(const ecs_world_t *world, ecs_entity_t entity, ecs_id_t component)
Get a mutable pointer to a component.
void * ecs_ensure_id(ecs_world_t *world, ecs_entity_t entity, ecs_id_t component, size_t size)
Ensure entity has component, return pointer.
ecs_entity_t ecs_field_src(const ecs_iter_t *it, int8_t index)
Return field source.
void * ecs_field_at_w_size(const ecs_iter_t *it, size_t size, int8_t index, int32_t row)
Get data for field at specified row.
void * ecs_field_w_size(const ecs_iter_t *it, size_t size, int8_t index)
Get data for field.
int32_t ecs_table_get_column_index(const ecs_world_t *world, const ecs_table_t *table, ecs_id_t component)
Get column index for component.
bool ecs_commit(ecs_world_t *world, ecs_entity_t entity, ecs_record_t *record, ecs_table_t *table, const ecs_type_t *added, const ecs_type_t *removed)
Commit (move) entity to a table.
const ecs_world_t * ecs_get_world(const ecs_poly_t *poly)
Get world from poly.
Iterator.
Definition flecs.h:1162
A type is a list of (component) ids.
Definition flecs.h:398
ecs_id_t * array
Array with ids.
Definition flecs.h:399
int32_t count
Number of elements in array.
Definition flecs.h:400
const Self & add() const
Add a component to an entity.
Definition builder.hpp:25
Entity.
Definition entity.hpp:30
Wrapper class around a field.
Definition field.hpp:61
Class that wraps around a flecs::id_t.
Definition decl.hpp:27
Class for iterating over query results.
Definition iter.hpp:68
void * param()
Access param.
Definition iter.hpp:142
flecs::field< const flecs::entity_t > entities() const
Get readonly access to entity ids.
Definition iter.hpp:327
bool next()
Progress iterator.
Definition iter.hpp:370
The world.
Definition world.hpp:174
bool is_stage() const
Test if is a stage.
Definition world.hpp:477
bool is_deferred() const
Test whether deferring is enabled.
Definition world.hpp:410