Flecs: include/flecs/addons/cpp/delegate.hpp Source File
Description: A fast entity component system (ECS) for C & C++

| Flecs v4.0 A fast entity component system (ECS) for C & C++

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