diff --git a/README.md b/README.md index 93efd51..719b7e4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # [zflecs](https://github.com/zig-gamedev/zflecs) -Zig build package and bindings for [flecs](https://github.com/SanderMertens/flecs) ECS v4.1.4 +Zig build package and bindings for [flecs](https://github.com/SanderMertens/flecs) ECS v4.1.5 ## Getting started diff --git a/libs/flecs/flecs.c b/libs/flecs/flecs.c index d6a1b71..9f73073 100644 --- a/libs/flecs/flecs.c +++ b/libs/flecs/flecs.c @@ -49,59 +49,97 @@ extern "C" { #endif +/** A bitset data structure for compact boolean storage. */ typedef struct ecs_bitset_t { - uint64_t *data; - int32_t count; - ecs_size_t size; + uint64_t *data; /**< Array of 64-bit words storing the bits. */ + int32_t count; /**< Number of bits in the bitset. */ + ecs_size_t size; /**< Allocated capacity in 64-bit words. */ } ecs_bitset_t; -/** Initialize bitset. */ +/** Initialize a bitset. + * + * @param bs The bitset to initialize. + */ FLECS_DBG_API void flecs_bitset_init( ecs_bitset_t *bs); -/** Deinitialize bitset. */ +/** Deinitialize a bitset. + * + * @param bs The bitset to deinitialize. + */ FLECS_DBG_API void flecs_bitset_fini( ecs_bitset_t *bs); -/** Add n elements to bitset. */ +/** Add n elements to a bitset. + * + * @param bs The bitset to add to. + * @param count Number of bits to add. + */ FLECS_DBG_API void flecs_bitset_addn( ecs_bitset_t *bs, int32_t count); -/** Ensure element exists. */ +/** Ensure an element exists. + * + * @param bs The bitset to ensure capacity for. + * @param count Minimum number of bits the bitset must hold. + */ FLECS_DBG_API void flecs_bitset_ensure( ecs_bitset_t *bs, int32_t count); -/** Set element. */ +/** Set an element. + * + * @param bs The bitset to modify. + * @param elem Index of the bit to set. + * @param value The boolean value to set. + */ FLECS_DBG_API void flecs_bitset_set( ecs_bitset_t *bs, int32_t elem, bool value); -/** Get element. */ +/** Get an element. + * + * @param bs The bitset to read from. + * @param elem Index of the bit to get. + * @return The boolean value of the bit. + */ FLECS_DBG_API bool flecs_bitset_get( const ecs_bitset_t *bs, int32_t elem); -/** Return number of elements. */ +/** Return the number of elements. + * + * @param bs The bitset. + * @return The number of bits in the bitset. + */ FLECS_DBG_API int32_t flecs_bitset_count( const ecs_bitset_t *bs); -/** Remove from bitset. */ +/** Remove from a bitset. + * + * @param bs The bitset to remove from. + * @param elem Index of the bit to remove. + */ FLECS_DBG_API void flecs_bitset_remove( ecs_bitset_t *bs, int32_t elem); -/** Swap values in bitset. */ +/** Swap values in a bitset. + * + * @param bs The bitset. + * @param elem_a Index of the first bit to swap. + * @param elem_b Index of the second bit to swap. + */ FLECS_DBG_API void flecs_bitset_swap( ecs_bitset_t *bs, @@ -447,6 +485,20 @@ typedef struct ecs_pair_record_t { /* Vector with ordered children */ ecs_vec_t ordered_children; + /* Tables with non-fragmenting children */ + ecs_map_t children_tables; /* mapis.op_kind) +void flecs_query_op_ctx_fini( + ecs_iter_t *it, + const ecs_query_op_t *op, + ecs_query_op_ctx_t *ctx); + void flecs_reset_source_set_flag( ecs_iter_t *it, int32_t field_index); @@ -2001,11 +2228,14 @@ void flecs_query_var_set_range( int32_t count, const ecs_query_run_ctx_t *ctx); -void flecs_query_var_narrow_range( - ecs_var_id_t var_id, - ecs_table_t *table, - int32_t offset, - int32_t count, +void flecs_query_src_set_single( + const ecs_query_op_t *op, + int32_t row, + const ecs_query_run_ctx_t *ctx); + +void flecs_query_src_set_range( + const ecs_query_op_t *op, + const ecs_table_range_t *range, const ecs_query_run_ctx_t *ctx); void flecs_query_var_set_entity( @@ -2086,6 +2316,18 @@ bool flecs_query_run_until( int32_t last); +/* And evaluation */ + +bool flecs_query_and( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + +bool flecs_query_and_any( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + /* Select evaluation */ bool flecs_query_select( @@ -2147,6 +2389,54 @@ bool flecs_query_sparse_self_up( const ecs_query_run_ctx_t *ctx); +/* Hierarchy evaluation */ + +const EcsParent* flecs_query_tree_get_parents( + ecs_table_range_t range); + +bool flecs_query_tree_and( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + +bool flecs_query_tree_and_wildcard( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + bool bulk_return); + +bool flecs_query_tree_pre( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + +bool flecs_query_tree_post( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + +bool flecs_query_tree_up_pre( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + bool self); + +bool flecs_query_tree_up_post( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + bool self); + +bool flecs_query_tree_with( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + +bool flecs_query_children( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + /* Toggle evaluation*/ bool flecs_query_toggle( @@ -2225,6 +2515,16 @@ typedef enum ecs_query_up_select_kind_t { FlecsQueryUpSelectSparse } ecs_query_up_select_kind_t; +bool flecs_query_up( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + +bool flecs_query_self_up( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx); + bool flecs_query_up_select( const ecs_query_op_t *op, bool redo, @@ -2240,8 +2540,7 @@ bool flecs_query_up_with( bool flecs_query_self_up_with( const ecs_query_op_t *op, bool redo, - const ecs_query_run_ctx_t *ctx, - bool id_only); + const ecs_query_run_ctx_t *ctx); /* Transitive relationship traversal */ @@ -2344,6 +2643,12 @@ void flecs_query_apply_iter_flags( ecs_iter_t *it, const ecs_query_t *query); +ecs_id_t flecs_query_iter_set_id( + ecs_iter_t *it, + int8_t field, + ecs_id_t id); + + #ifdef FLECS_DEBUG #define flecs_set_var_label(var, lbl) (var)->label = lbl @@ -2438,8 +2743,35 @@ bool flecs_sparse_on_add_cr( bool construct, void **ptr_out); -/* Run add actions for components added to entity. */ -void flecs_notify_on_add( +/* Run actions for creating new entity in table. */ +void flecs_actions_new( + ecs_world_t *world, + ecs_table_t *table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff, + ecs_flags32_t flags, + bool construct, + bool sparse); + +/* Run actions for deleting an entity. */ +void flecs_actions_delete( + ecs_world_t *world, + ecs_table_t *table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff); + +/* Same as flecs_actions_delete, but for entities whose parent is also deleted */ +void flecs_actions_delete_tree( + ecs_world_t *world, + ecs_table_t *table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff); + +/* Run actions for added components in table move */ +void flecs_actions_move_add( ecs_world_t *world, ecs_table_t *table, ecs_table_t *other_table, @@ -2450,8 +2782,8 @@ void flecs_notify_on_add( bool construct, bool sparse); -/* Run remove actions for components removed from entity. */ -void flecs_notify_on_remove( +/* Run actions for removed components in table move */ +void flecs_actions_move_remove( ecs_world_t *world, ecs_table_t *table, ecs_table_t *other_table, @@ -2481,15 +2813,15 @@ void flecs_notify_on_set_ids( */ -/* Called during bootstrap to register entity name logic with world. */ +/* Called during bootstrap to register entity name entities with world. */ void flecs_bootstrap_entity_name( ecs_world_t *world); /* Update lookup index for entity names. */ void flecs_reparent_name_index( ecs_world_t *world, + ecs_table_t *dst, ecs_table_t *src, - ecs_table_t *dst, int32_t offset, int32_t count); @@ -2519,6 +2851,7 @@ typedef enum ecs_cmd_kind_t { EcsCmdAdd, EcsCmdRemove, EcsCmdSet, + EcsCmdSetDontFragment, EcsCmdEmplace, EcsCmdEnsure, EcsCmdModified, @@ -2591,11 +2924,6 @@ bool flecs_defer_begin( ecs_world_t *world, ecs_stage_t *stage); -/* End deferred mode (executes commands when stage->deref becomes 0). */ -bool flecs_defer_end( - ecs_world_t *world, - ecs_stage_t *stage); - /* Purge command queue without executing commands. */ bool flecs_defer_purge( ecs_world_t *world, @@ -2865,7 +3193,8 @@ void flecs_on_delete( ecs_world_t *world, ecs_id_t id, ecs_entity_t action, - bool delete_id); + bool delete_id, + bool force_delete); /* Remove non-fragmenting components from entity */ void flecs_entity_remove_non_fragmenting( @@ -2881,6 +3210,13 @@ ecs_table_range_t flecs_range_from_entity( const ecs_world_t *world, ecs_entity_t e); +ecs_entity_t flecs_set_identifier( + ecs_world_t *world, + ecs_stage_t *stage, + ecs_entity_t entity, + ecs_entity_t tag, + const char *name); + #endif /** @@ -2896,12 +3232,25 @@ typedef struct ecs_instantiate_ctx_t { ecs_entity_t root_instance; } ecs_instantiate_ctx_t; -/* Instantiate prefab for entity. Called when adding (IsA, prefab). */ void flecs_instantiate( ecs_world_t *world, ecs_entity_t base, ecs_entity_t instance, - const ecs_instantiate_ctx_t *ctx); + const ecs_instantiate_ctx_t *ctx, + int32_t depth); + +void flecs_instantiate_dont_fragment( + ecs_world_t *world, + ecs_entity_t base, + ecs_entity_t instance); + +void flecs_instantiate_sparse( + ecs_world_t *world, + const ecs_table_range_t *base_child_range, + const ecs_entity_t *base_children, + ecs_table_t *instance_table, + const ecs_entity_t *instance_children, + int32_t row_offset); #endif @@ -3180,7 +3529,7 @@ ecs_poly_t* flecs_poly_get_( ecs_assert(object != NULL, ECS_INVALID_PARAMETER, NULL);\ const ecs_header_t *hdr = (const ecs_header_t *)object;\ const char *type_name = hdr->mixins->type_name;\ - ecs_assert(hdr->type == ty##_magic, ECS_INVALID_PARAMETER, type_name);\ + ecs_assert(hdr->type == ty##_magic, ECS_INVALID_PARAMETER, "%s", type_name);\ } while (0) #else #define flecs_poly_assert(object, ty) @@ -3196,6 +3545,29 @@ flecs_poly_dtor_t* flecs_get_dtor( #endif +/** + * @file tree_spawner.h + * @brief Data structure used to speed up the creation of hierarchies. + */ + +#ifndef FLECS_SPAWNER_H +#define FLECS_SPAWNER_H + +/* Called during bootstrap to register spawner entities with world. */ +void flecs_bootstrap_spawner( + ecs_world_t *world); + +EcsTreeSpawner* flecs_prefab_spawner_build( + ecs_world_t *world, + ecs_entity_t base); + +void flecs_spawner_instantiate( + ecs_world_t *world, + EcsTreeSpawner *spawner, + ecs_entity_t instance); + +#endif + /** * @file stage.h * @brief Stage functions. @@ -3316,6 +3688,9 @@ typedef struct ecs_world_allocators_t { /* Temporary vectors used for creating table diff id sequences */ ecs_table_diff_builder_t diff_builder; + + /* Temporary vector for tree spawner */ + ecs_vec_t tree_spawner; } ecs_world_allocators_t; /* Component monitor */ @@ -3414,19 +3789,12 @@ struct ecs_world_t { * cached pointer is still valid. */ uint32_t table_version[ECS_TABLE_VERSION_ARRAY_SIZE]; - /* Same as table_version, but only increases after the column pointers of - * a table change. */ - uint32_t table_column_version[ECS_TABLE_VERSION_ARRAY_SIZE]; - /* Array for checking if components can be looked up trivially */ ecs_flags8_t non_trivial_lookup[FLECS_HI_COMPONENT_ID]; /* Array for checking if components can be set trivially */ ecs_flags8_t non_trivial_set[FLECS_HI_COMPONENT_ID]; - /* Is entity range checking enabled? */ - bool range_check_enabled; - /* -- Data storage -- */ ecs_store_t store; @@ -3447,6 +3815,12 @@ struct ecs_world_t { /* -- Component ids -- */ ecs_vec_t component_ids; /* World local component ids */ + /* Index of prefab children in ordered children vector. Used by ecs_get_target. */ + ecs_map_t prefab_child_indices; + + /* Is entity range checking enabled? */ + bool range_check_enabled; + /* Internal callback for command inspection. Only one callback can be set at * a time. After assignment the action will become active at the start of * the next frame, set by ecs_frame_begin, and will be reset by @@ -3568,21 +3942,11 @@ void flecs_increment_table_version( ecs_world_t *world, ecs_table_t *table); -/* Same as flecs_increment_table_version, but for column version. */ -void flecs_increment_table_column_version( - ecs_world_t *world, - ecs_table_t *table); - /* Get table version. */ uint32_t flecs_get_table_version_fast( const ecs_world_t *world, const uint64_t table_id); -/* Get table version for column pointer validation. */ -uint32_t flecs_get_table_column_version( - const ecs_world_t *world, - const uint64_t table_id); - /* Throws error when (OnDelete*, Panic) constraint is violated. */ void flecs_throw_invalid_delete( ecs_world_t *world, @@ -3718,6 +4082,7 @@ typedef enum ecs_journal_kind_t { EcsJournalMove, EcsJournalClear, EcsJournalDelete, + EcsJournalSetParent, EcsJournalDeleteWith, EcsJournalRemoveAll, EcsJournalTableEvents @@ -3754,9 +4119,6 @@ void flecs_journal_end(void); /* Used in id records to keep track of entities used with id flags */ extern const ecs_entity_t EcsFlag; -/* Scope for flecs internals, like observers used for builtin features */ -extern const ecs_entity_t EcsFlecsInternals; - //////////////////////////////////////////////////////////////////////////////// //// Bootstrap API //////////////////////////////////////////////////////////////////////////////// @@ -3774,10 +4136,8 @@ void flecs_bootstrap( #define flecs_bootstrap_tag(world, name)\ ecs_make_alive(world, name);\ - ecs_add_id(world, name, EcsFinal);\ ecs_add_pair(world, name, EcsChildOf, ecs_get_scope(world));\ - ecs_set_name(world, name, (const char*)&#name[ecs_os_strlen(world->info.name_prefix)]);\ - ecs_set_symbol(world, name, #name); + ecs_set_name(world, name, (const char*)&#name[ecs_os_strlen(world->info.name_prefix)]); #define flecs_bootstrap_trait(world, name)\ flecs_bootstrap_tag(world, name)\ @@ -3912,6 +4272,10 @@ const ecs_type_info_t* flecs_determine_type_info_for_component( const ecs_world_t *world, ecs_id_t component); +ecs_size_t flecs_type_size( + ecs_world_t *world, + ecs_entity_t type); + /* Utility for using allocated strings in assert/error messages */ const char* flecs_errstr( char *str); @@ -4389,9 +4753,16 @@ void flecs_on_component(ecs_iter_t *it) { (void)component_id; if (it->event != EcsOnRemove) { - ecs_entity_t parent = ecs_get_target(world, e, EcsChildOf, 0); + ecs_entity_t parent = ecs_get_parent(world, e); if (parent) { - ecs_add_id(world, parent, EcsModule); + ecs_record_t *parent_record = flecs_entities_get(world, parent); + ecs_table_t *parent_table = parent_record->table; + if (!ecs_table_has_id(world, parent_table, EcsModule)) { + if (!ecs_table_has_id(world, parent_table, ecs_id(EcsComponent))) { + ecs_add_id(world, parent, EcsModule); + } + } + } } @@ -4489,6 +4860,22 @@ void flecs_disable_module(ecs_iter_t *it) { } } +static +void flecs_on_add_prefab(ecs_iter_t *it) { + ecs_world_t *world = it->world; + + for (int32_t i = 0; i < it->count; i ++) { + ecs_entity_t p = it->entities[i]; + + ecs_iter_t cit = ecs_children(world, p); + while (ecs_children_next(&cit)) { + for (int32_t j = 0; j < cit.count; j ++) { + ecs_add_id(world, cit.entities[j], EcsPrefab); + } + } + } +} + static void flecs_register_ordered_children(ecs_iter_t *it) { int32_t i; @@ -4498,11 +4885,12 @@ void flecs_register_ordered_children(ecs_iter_t *it) { ecs_component_record_t *cr = flecs_components_ensure( it->world, ecs_childof(parent)); if (!(cr->flags & EcsIdOrderedChildren)) { + flecs_ordered_children_init(it->world, cr); flecs_ordered_children_populate(it->world, cr); cr->flags |= EcsIdOrderedChildren; } } - } else { + } else if (!(it->real_world->flags & EcsWorldFini) && it->other_table) { ecs_assert(it->event == EcsOnRemove, ECS_INTERNAL_ERROR, NULL); for (i = 0; i < it->count; i ++) { ecs_entity_t parent = it->entities[i]; @@ -4542,12 +4930,13 @@ void flecs_bootstrap_builtin( world, &world->store.root, ECS_RECORD_TO_ROW(record->row), false); record->table = table; - int32_t index = flecs_table_append(world, table, entity, false, false); - record->row = ECS_ROW_TO_RECORD(index, 0); + int32_t row = ecs_table_count(table); + flecs_table_append(world, table, entity, false, false); + record->row = ECS_ROW_TO_RECORD(row, 0); EcsComponent *component = columns[0].data; - component[index].size = size; - component[index].alignment = alignment; + component[row].size = size; + component[row].alignment = alignment; const char *name = &symbol[3]; /* Strip 'Ecs' */ ecs_size_t symbol_length = ecs_os_strlen(symbol); @@ -4555,21 +4944,21 @@ void flecs_bootstrap_builtin( EcsIdentifier *name_col = columns[1].data; uint64_t name_hash = flecs_hash(name, name_length); - name_col[index].value = ecs_os_strdup(name); - name_col[index].length = name_length; - name_col[index].hash = name_hash; - name_col[index].index_hash = 0; + name_col[row].value = ecs_os_strdup(name); + name_col[row].length = name_length; + name_col[row].hash = name_hash; + name_col[row].index_hash = 0; - ecs_hashmap_t *name_index = table->_->childof_r->name_index; - name_col[index].index = name_index; + ecs_hashmap_t *name_index = flecs_table_get_name_index(world, table); + name_col[row].index = name_index; flecs_name_index_ensure(name_index, entity, name, name_length, name_hash); EcsIdentifier *symbol_col = columns[2].data; - symbol_col[index].value = ecs_os_strdup(symbol); - symbol_col[index].length = symbol_length; - symbol_col[index].hash = flecs_hash(symbol, symbol_length); - symbol_col[index].index_hash = 0; - symbol_col[index].index = NULL; + symbol_col[row].value = ecs_os_strdup(symbol); + symbol_col[row].length = symbol_length; + symbol_col[row].hash = flecs_hash(symbol, symbol_length); + symbol_col[row].index_hash = 0; + symbol_col[row].index = NULL; } /** Initialize component table. This table is manually constructed to bootstrap @@ -4605,29 +4994,26 @@ ecs_table_t* flecs_bootstrap_component_table( ecs_id_t ids[] = { ecs_id(EcsComponent), - EcsFinal, ecs_pair_t(EcsIdentifier, EcsName), ecs_pair_t(EcsIdentifier, EcsSymbol), ecs_pair(EcsChildOf, EcsFlecsCore), - ecs_pair(EcsOnDelete, EcsPanic) }; ecs_type_t array = { .array = ids, - .count = 6 + .count = 4 }; ecs_table_t *result = flecs_table_find_or_create(world, &array); /* Preallocate enough memory for initial components */ - ecs_allocator_t *a = &world->allocator; ecs_vec_t v_entities = ecs_vec_from_entities(result); - ecs_vec_init_t(a, &v_entities, ecs_entity_t, EcsFirstUserComponentId); + ecs_vec_init_t(NULL, &v_entities, ecs_entity_t, EcsFirstUserComponentId); { ecs_column_t *column = &result->data.columns[0]; ecs_vec_t v = ecs_vec_from_column_t(column, result, EcsComponent); - ecs_vec_init_t(a, &v, EcsComponent, EcsFirstUserComponentId); + ecs_vec_init_t(NULL, &v, EcsComponent, EcsFirstUserComponentId); ecs_assert(v.count == v_entities.count, ECS_INTERNAL_ERROR, NULL); ecs_assert(v.size == v_entities.size, ECS_INTERNAL_ERROR, NULL); column->data = v.array; @@ -4635,7 +5021,7 @@ ecs_table_t* flecs_bootstrap_component_table( { ecs_column_t *column = &result->data.columns[1]; ecs_vec_t v = ecs_vec_from_column_t(column, result, EcsIdentifier); - ecs_vec_init_t(a, &v, EcsIdentifier, EcsFirstUserComponentId); + ecs_vec_init_t(NULL, &v, EcsIdentifier, EcsFirstUserComponentId); ecs_assert(v.count == v_entities.count, ECS_INTERNAL_ERROR, NULL); ecs_assert(v.size == v_entities.size, ECS_INTERNAL_ERROR, NULL); column->data = v.array; @@ -4643,7 +5029,7 @@ ecs_table_t* flecs_bootstrap_component_table( { ecs_column_t *column = &result->data.columns[2]; ecs_vec_t v = ecs_vec_from_column_t(column, result, EcsIdentifier); - ecs_vec_init_t(a, &v, EcsIdentifier, EcsFirstUserComponentId); + ecs_vec_init_t(NULL, &v, EcsIdentifier, EcsFirstUserComponentId); ecs_assert(v.count == v_entities.count, ECS_INTERNAL_ERROR, NULL); ecs_assert(v.size == v_entities.size, ECS_INTERNAL_ERROR, NULL); column->data = v.array; @@ -4674,8 +5060,7 @@ void flecs_bootstrap_make_alive( r->row = flecs_ito(uint32_t, root->data.count); ecs_vec_t v_entities = ecs_vec_from_entities(root); - ecs_entity_t *array = ecs_vec_append_t(&world->allocator, - &v_entities, ecs_entity_t); + ecs_entity_t *array = ecs_vec_append_t(NULL, &v_entities, ecs_entity_t); array[0] = e; root->data.entities = v_entities.array; @@ -4690,15 +5075,10 @@ void flecs_bootstrap_entity( ecs_entity_t id, const char *name, ecs_entity_t parent) -{ - char symbol[256]; - ecs_os_strcpy(symbol, "flecs.core."); - ecs_os_strcat(symbol, name); - +{ flecs_bootstrap_make_alive(world, id); ecs_add_pair(world, id, EcsChildOf, parent); ecs_set_name(world, id, name); - ecs_set_symbol(world, id, symbol); ecs_assert(ecs_get_name(world, id) != NULL, ECS_INTERNAL_ERROR, NULL); @@ -4763,6 +5143,8 @@ void flecs_bootstrap( flecs_bootstrap_make_alive(world, ecs_id(EcsComponent)); flecs_bootstrap_make_alive(world, ecs_id(EcsIdentifier)); flecs_bootstrap_make_alive(world, ecs_id(EcsPoly)); + flecs_bootstrap_make_alive(world, ecs_id(EcsParent)); + flecs_bootstrap_make_alive(world, ecs_id(EcsTreeSpawner)); flecs_bootstrap_make_alive(world, ecs_id(EcsDefaultChildComponent)); flecs_bootstrap_make_alive(world, EcsFinal); flecs_bootstrap_make_alive(world, EcsName); @@ -4771,7 +5153,6 @@ void flecs_bootstrap( flecs_bootstrap_make_alive(world, EcsChildOf); flecs_bootstrap_make_alive(world, EcsFlecs); flecs_bootstrap_make_alive(world, EcsFlecsCore); - flecs_bootstrap_make_alive(world, EcsFlecsInternals); flecs_bootstrap_make_alive(world, EcsOnAdd); flecs_bootstrap_make_alive(world, EcsOnRemove); flecs_bootstrap_make_alive(world, EcsOnSet); @@ -4813,6 +5194,10 @@ void flecs_bootstrap( .dtor = ecs_dtor(EcsPoly) }); + flecs_type_info_init(world, EcsParent, { + .ctor = flecs_default_ctor + }); + flecs_type_info_init(world, EcsDefaultChildComponent, { .ctor = flecs_default_ctor, }); @@ -4830,6 +5215,8 @@ void flecs_bootstrap( flecs_bootstrap_builtin_t(world, table, EcsIdentifier); flecs_bootstrap_builtin_t(world, table, EcsComponent); flecs_bootstrap_builtin_t(world, table, EcsPoly); + flecs_bootstrap_builtin_t(world, table, EcsParent); + flecs_bootstrap_builtin_t(world, table, EcsTreeSpawner); flecs_bootstrap_builtin_t(world, table, EcsDefaultChildComponent); /* Initialize default entity id range */ @@ -4840,11 +5227,11 @@ void flecs_bootstrap( /* Register observer for trait before adding EcsPairIsTag */ ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = EcsPairIsTag }, .events = {EcsOnAdd, EcsOnRemove}, .callback = flecs_register_tag, - .yield_existing = true + .yield_existing = true, + .global_observer = true }); /* Populate core module */ @@ -4854,11 +5241,11 @@ void flecs_bootstrap( flecs_bootstrap_tag(world, EcsSymbol); flecs_bootstrap_tag(world, EcsAlias); + flecs_bootstrap_tag(world, EcsParentDepth); flecs_bootstrap_tag(world, EcsQuery); flecs_bootstrap_tag(world, EcsObserver); flecs_bootstrap_tag(world, EcsModule); - flecs_bootstrap_tag(world, EcsPrivate); flecs_bootstrap_tag(world, EcsPrefab); flecs_bootstrap_tag(world, EcsSlotOf); flecs_bootstrap_tag(world, EcsDisabled); @@ -4874,10 +5261,6 @@ void flecs_bootstrap( ecs_set_name(world, EcsFlecsCore, "core"); ecs_add_id(world, EcsFlecsCore, EcsModule); - ecs_add_pair(world, EcsFlecsInternals, EcsChildOf, EcsFlecsCore); - ecs_set_name(world, EcsFlecsInternals, "internals"); - ecs_add_id(world, EcsFlecsInternals, EcsModule); - /* Self check */ ecs_record_t *r = flecs_entities_get(world, EcsFlecs); ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); @@ -4946,17 +5329,18 @@ void flecs_bootstrap( flecs_bootstrap_entity(world, EcsOnTableCreate, "OnTableCreate", EcsFlecsCore); flecs_bootstrap_entity(world, EcsOnTableDelete, "OnTableDelete", EcsFlecsCore); + /* Constant tag */ + flecs_bootstrap_entity(world, EcsConstant, "constant", EcsFlecsCore); + /* Sync properties of ChildOf and Identifier with bootstrapped flags */ ecs_add_pair(world, EcsChildOf, EcsOnDeleteTarget, EcsDelete); ecs_add_id(world, EcsChildOf, EcsTrait); + ecs_add_id(world, EcsIsA, EcsTrait); ecs_add_id(world, EcsChildOf, EcsAcyclic); ecs_add_id(world, EcsChildOf, EcsTraversable); ecs_add_pair(world, EcsChildOf, EcsOnInstantiate, EcsDontInherit); ecs_add_pair(world, ecs_id(EcsIdentifier), EcsOnInstantiate, EcsDontInherit); - /* Create triggers in internals scope */ - ecs_set_scope(world, EcsFlecsInternals); - /* Register observers for components/relationship properties. Most observers * set flags on an component record when a trait is added to a component, which * allows for quick trait testing in various operations. */ @@ -4964,7 +5348,8 @@ void flecs_bootstrap( .query.terms = {{ .id = EcsFinal }}, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, - .callback = flecs_register_final + .callback = flecs_register_final, + .global_observer = true }); static ecs_on_trait_ctx_t inheritable_trait = { EcsIdInheritable, 0 }; @@ -4973,7 +5358,8 @@ void flecs_bootstrap( .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, .callback = flecs_register_trait, - .ctx = &inheritable_trait + .ctx = &inheritable_trait, + .global_observer = true }); ecs_observer(world, { @@ -4982,7 +5368,8 @@ void flecs_bootstrap( }, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd, EcsOnRemove}, - .callback = flecs_register_on_delete + .callback = flecs_register_on_delete, + .global_observer = true }); ecs_observer(world, { @@ -4991,7 +5378,8 @@ void flecs_bootstrap( }, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd, EcsOnRemove}, - .callback = flecs_register_on_delete_object + .callback = flecs_register_on_delete_object, + .global_observer = true }); ecs_observer(world, { @@ -5000,21 +5388,24 @@ void flecs_bootstrap( }, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, - .callback = flecs_register_on_instantiate + .callback = flecs_register_on_instantiate, + .global_observer = true }); ecs_observer(world, { .query.terms = {{ .id = EcsSymmetric }}, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, - .callback = flecs_register_symmetric + .callback = flecs_register_symmetric, + .global_observer = true }); ecs_observer(world, { .query.terms = {{ .id = EcsSingleton }}, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, - .callback = flecs_register_singleton + .callback = flecs_register_singleton, + .global_observer = true }); static ecs_on_trait_ctx_t traversable_trait = { EcsIdTraversable, EcsIdTraversable }; @@ -5023,7 +5414,8 @@ void flecs_bootstrap( .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd, EcsOnRemove}, .callback = flecs_register_trait, - .ctx = &traversable_trait + .ctx = &traversable_trait, + .global_observer = true }); static ecs_on_trait_ctx_t exclusive_trait = { EcsIdExclusive, 0 }; @@ -5032,7 +5424,8 @@ void flecs_bootstrap( .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd, EcsOnRemove}, .callback = flecs_register_trait, - .ctx = &exclusive_trait + .ctx = &exclusive_trait, + .global_observer = true }); static ecs_on_trait_ctx_t toggle_trait = { EcsIdCanToggle, 0 }; @@ -5041,7 +5434,8 @@ void flecs_bootstrap( .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, .callback = flecs_register_trait, - .ctx = &toggle_trait + .ctx = &toggle_trait, + .global_observer = true }); static ecs_on_trait_ctx_t with_trait = { EcsIdWith, 0 }; @@ -5052,7 +5446,8 @@ void flecs_bootstrap( .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, .callback = flecs_register_trait_pair, - .ctx = &with_trait + .ctx = &with_trait, + .global_observer = true }); static ecs_on_trait_ctx_t sparse_trait = { EcsIdSparse, 0 }; @@ -5061,7 +5456,8 @@ void flecs_bootstrap( .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, .callback = flecs_register_trait, - .ctx = &sparse_trait + .ctx = &sparse_trait, + .global_observer = true }); static ecs_on_trait_ctx_t dont_fragment_trait = { EcsIdDontFragment, 0 }; @@ -5070,14 +5466,16 @@ void flecs_bootstrap( .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, .callback = flecs_register_trait, - .ctx = &dont_fragment_trait + .ctx = &dont_fragment_trait, + .global_observer = true }); ecs_observer(world, { .query.terms = {{ .id = EcsOrderedChildren }}, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd, EcsOnRemove}, - .callback = flecs_register_ordered_children + .callback = flecs_register_ordered_children, + .global_observer = true }); /* Entities used as slot are marked as exclusive to ensure a slot can always @@ -5088,7 +5486,8 @@ void flecs_bootstrap( }, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, - .callback = flecs_register_slot_of + .callback = flecs_register_slot_of, + .global_observer = true }); /* Define observer to make sure that adding a module to a child entity also @@ -5097,7 +5496,8 @@ void flecs_bootstrap( .query.terms = {{ .id = EcsModule } }, .query.flags = EcsQueryMatchPrefab|EcsQueryMatchDisabled, .events = {EcsOnAdd}, - .callback = flecs_ensure_module_tag + .callback = flecs_ensure_module_tag, + .global_observer = true }); /* Observer that tracks whether observers are disabled */ @@ -5107,7 +5507,8 @@ void flecs_bootstrap( { .id = EcsDisabled }, }, .events = {EcsOnAdd, EcsOnRemove}, - .callback = flecs_disable_observer + .callback = flecs_disable_observer, + .global_observer = true }); /* Observer that tracks whether modules are disabled */ @@ -5117,17 +5518,26 @@ void flecs_bootstrap( { .id = EcsDisabled }, }, .events = {EcsOnAdd, EcsOnRemove}, - .callback = flecs_disable_module + .callback = flecs_disable_module, + .global_observer = true }); - /* Set scope back to flecs core */ - ecs_set_scope(world, EcsFlecsCore); + /* Observer that ensures children of a prefab are also prefabs */ + ecs_observer(world, { + .query.terms = { + { .id = EcsPrefab }, + }, + .events = {EcsOnAdd}, + .callback = flecs_on_add_prefab, + .global_observer = true + }); /* Exclusive properties */ ecs_add_id(world, EcsChildOf, EcsExclusive); ecs_add_id(world, EcsOnDelete, EcsExclusive); ecs_add_id(world, EcsOnDeleteTarget, EcsExclusive); ecs_add_id(world, EcsOnInstantiate, EcsExclusive); + ecs_add_id(world, EcsParentDepth, EcsExclusive); /* Unqueryable entities */ ecs_add_id(world, EcsThis, EcsNotQueryable); @@ -5167,6 +5577,9 @@ void flecs_bootstrap( /* DontFragment components are always sparse */ ecs_add_pair(world, EcsDontFragment, EcsWith, EcsSparse); + + /* Modules are singletons */ + ecs_add_pair(world, EcsModule, EcsWith, EcsSingleton); /* DontInherit components */ ecs_add_pair(world, EcsPrefab, EcsOnInstantiate, EcsDontInherit); @@ -5188,24 +5601,14 @@ void flecs_bootstrap( ecs_add_id(world, EcsSlotOf, EcsExclusive); ecs_add_id(world, EcsOneOf, EcsExclusive); - /* Private properties */ - ecs_add_id(world, ecs_id(EcsPoly), EcsPrivate); - ecs_add_id(world, ecs_id(EcsIdentifier), EcsPrivate); - /* Inherited components */ ecs_add_pair(world, EcsIsA, EcsOnInstantiate, EcsInherit); ecs_add_pair(world, EcsDependsOn, EcsOnInstantiate, EcsInherit); /* Run bootstrap functions for other parts of the code */ flecs_bootstrap_entity_name(world); - - /* Register constant tag */ - ecs_component(world, { - .entity = ecs_entity(world, { .id = EcsConstant, - .name = "constant", .symbol = "EcsConstant", - .add = ecs_ids(ecs_pair(EcsOnInstantiate, EcsDontInherit)) - }) - }); + flecs_bootstrap_parent_component(world); + flecs_bootstrap_spawner(world); ecs_set_scope(world, 0); ecs_set_name_prefix(world, NULL); @@ -5492,6 +5895,40 @@ bool flecs_defer_remove( cmd->kind = EcsCmdRemove; cmd->id = id; cmd->entity = entity; + + /* If an override is removed, restore to the component to the value of + * the overridden component. This serves to purposes: + * + * - the application immediately sees the correct component value + * - if a remove command is followed up by an add command, the override + * will still be applied vs. getting cancelled out because of + * command batching. + */ + ecs_world_t *world = stage->world; + ecs_record_t *r = flecs_entities_get(world, entity); + ecs_table_t *table = r->table; + ecs_table_overrides_t *o = table->data.overrides; + if (o) { + ecs_component_record_t *cr = flecs_components_get(world, id); + const ecs_type_info_t *ti; + if (cr && (ti = cr->type_info)) { + const ecs_table_record_t *tr = flecs_component_get_table( + cr, table); + if (tr) { + ecs_assert(tr->column != -1, ECS_INTERNAL_ERROR, NULL); + ecs_ref_t *ref = &o->refs[tr->column]; + if (ref->entity) { + void *dst = ECS_OFFSET( + table->data.columns[tr->column].data, + ti->size * ECS_RECORD_TO_ROW(r->row)); + const void *src = ecs_ref_get_id( + world, &o->refs[tr->column], id); + flecs_type_info_copy(dst, src, 1, ti); + } + } + } + } + return true; } return false; @@ -5617,18 +6054,10 @@ void* flecs_defer_ensure( if (!base) { /* Normal ctor */ - ecs_xtor_t ctor = ti->hooks.ctor; - if (ctor) { - ctor(ptr.ptr, 1, ti); - } + flecs_type_info_ctor(ptr.ptr, 1, ti); } else { /* Override */ - ecs_copy_t copy = ti->hooks.copy_ctor; - if (copy) { - copy(ptr.ptr, base, 1, ti); - } else { - ecs_os_memcpy(ptr.ptr, base, size); - } + flecs_type_info_copy_ctor(ptr.ptr, base, 1, ti); } } else { cmd->kind = EcsCmdAdd; @@ -5659,11 +6088,19 @@ void* flecs_defer_set( flecs_component_ptr_t ptr = flecs_defer_get_existing( world, entity, r, id, size); + if (world->stage_count != 1) { + /* If world has multiple stages we need to insert a set command + * with temporary storage, as the value could be lost otherwise + * by a command in another stage. */ + ptr.ptr = NULL; + } + const ecs_type_info_t *ti = ptr.ti; ecs_check(ti != NULL, ECS_INVALID_PARAMETER, "provided component is not a type"); ecs_assert(size == ti->size, ECS_INVALID_PARAMETER, - "mismatching size specified for component in ensure/emplace/set"); + "mismatching size specified for component in ensure/emplace/set (%u vs %u)", + size, ti->size); /* Handle trivial set command (no hooks, OnSet observers) */ if (id < FLECS_HI_COMPONENT_ID) { @@ -5678,8 +6115,8 @@ void* flecs_defer_set( cmd->is._1.value = ptr.ptr; } else { /* No OnSet observers, so only thing we need to do is make sure - * that a preceding remove command doesn't cause the entity to - * end up without the component. */ + * that a preceding remove command doesn't cause the entity to + * end up without the component. */ cmd->kind = EcsCmdAdd; } @@ -5688,13 +6125,14 @@ void* flecs_defer_set( } } - ecs_copy_t copy; if (!ptr.ptr) { - cmd->kind = EcsCmdSet; + bool is_dont_fragment = + flecs_component_get_flags(world, id) & EcsIdDontFragment; + cmd->kind = is_dont_fragment ? EcsCmdSetDontFragment : EcsCmdSet; cmd->is._1.size = size; ptr.ptr = cmd->is._1.value = flecs_stack_alloc(&stage->cmd->stack, size, ti->alignment); - copy = ti->hooks.copy_ctor; + flecs_type_info_copy_ctor(ptr.ptr, value, 1, ti); } else { cmd->kind = EcsCmdAddModified; @@ -5704,13 +6142,7 @@ void* flecs_defer_set( world, r->table, entity, id, ptr.ptr, value, ti); } - copy = ti->hooks.copy; - } - - if (copy) { - copy(ptr.ptr, value, 1, ti); - } else { - ecs_os_memcpy(ptr.ptr, value, size); + flecs_type_info_copy(ptr.ptr, value, 1, ti); } return ptr.ptr; @@ -5769,15 +6201,14 @@ void* flecs_defer_cpp_set( } if (!ptr.ptr) { - cmd->kind = EcsCmdSet; + bool is_dont_fragment = + flecs_component_get_flags(world, id) & EcsIdDontFragment; + cmd->kind = is_dont_fragment ? EcsCmdSetDontFragment : EcsCmdSet; cmd->is._1.size = size; ptr.ptr = cmd->is._1.value = flecs_stack_alloc(&stage->cmd->stack, size, ti->alignment); - ecs_xtor_t ctor = ti->hooks.ctor; - if (ctor) { - ctor(ptr.ptr, 1, ti); - } + flecs_type_info_ctor(ptr.ptr, 1, ti); } else { cmd->kind = EcsCmdAddModified; @@ -5867,17 +6298,9 @@ void flecs_enqueue( void *param_cmd = flecs_stack_alloc(stack, ti->size, ti->alignment); ecs_assert(param_cmd != NULL, ECS_INTERNAL_ERROR, NULL); if (desc->param) { - if (ti->hooks.move_ctor) { - ti->hooks.move_ctor(param_cmd, desc->param, 1, ti); - } else { - ecs_os_memcpy(param_cmd, desc->param, ti->size); - } + flecs_type_info_move_ctor(param_cmd, desc->param, 1, ti); } else { - if (ti->hooks.copy_ctor) { - ti->hooks.copy_ctor(param_cmd, desc->const_param, 1, ti); - } else { - ecs_os_memcpy(param_cmd, desc->const_param, ti->size); - } + flecs_type_info_copy_ctor(param_cmd, desc->const_param, 1, ti); } desc_cmd->param = param_cmd; @@ -5914,10 +6337,7 @@ void flecs_dtor_value( { const ecs_type_info_t *ti = ecs_get_type_info(world, id); ecs_assert(ti != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_xtor_t dtor = ti->hooks.dtor; - if (dtor) { - dtor(value, 1, ti); - } + flecs_type_info_dtor(value, 1, ti); } static @@ -6055,6 +6475,9 @@ void flecs_cmd_batch_for_entity( if (cr && cr->flags & EcsIdDontFragment) { /* Nothing to batch for non-fragmenting components */ + if (cmd->kind == EcsCmdSet) { + cmd->kind = EcsCmdSetDontFragment; + } continue; } @@ -6099,22 +6522,7 @@ void flecs_cmd_batch_for_entity( * the constructor is not invoked for the component */ break; case EcsCmdRemove: { - ecs_table_t *next = - flecs_find_table_remove(world, table, id, diff); - if ((table != next) && (table->flags & EcsTableHasIsA)) { - /* Abort batch. It's possible that we removed an override, and - * if we're reading the component in the same batch we need to - * reapply the override. If we do nothing here, an add for the - * same component would cancel out the remove and we'd won't get - * the override for the component. */ - next_for_entity = 0; - - /* Make sure that if we have to do any processing we don't go - * beyond the current command. */ - cmd->next_for_entity = 0; - } - - table = next; + table = flecs_find_table_remove(world, table, id, diff); world->info.cmd.batched_command_count ++; cmd->kind = EcsCmdSkip; break; @@ -6143,6 +6551,7 @@ void flecs_cmd_batch_for_entity( case EcsCmdSkip: case EcsCmdModifiedNoHook: case EcsCmdModified: + case EcsCmdSetDontFragment: break; } } while ((cur = next_for_entity)); @@ -6165,8 +6574,11 @@ void flecs_cmd_batch_for_entity( /* If destination table has new sparse components, make sure they're created * for the entity. */ if ((table_diff.added_flags & (EcsTableHasSparse|EcsTableHasDontFragment)) && added.count) { - flecs_sparse_on_add( - world, table, ECS_RECORD_TO_ROW(r->row), 1, &added, true); + if (flecs_sparse_on_add( + world, table, ECS_RECORD_TO_ROW(r->row), 1, &added, true)) + { + table_diff.added_flags |= EcsTableHasOnAdd; + } } /* If the batch contains set commands, copy the component value from the @@ -6199,19 +6611,23 @@ void flecs_cmd_batch_for_entity( void *ptr = cmd->is._1.value; const ecs_type_info_t *ti = dst.ti; if (ti->hooks.on_replace) { - flecs_invoke_replace_hook(world, r->table, entity, + ecs_table_t *prev_table = r->table; + flecs_invoke_replace_hook(world, prev_table, entity, cmd->id, dst.ptr, ptr, ti); + if (prev_table != r->table) { + if (!r->table) { + /* Entity was deleted */ + goto done; + } + dst = flecs_get_mut( + world, entity, cmd->id, r, cmd->is._1.size); + } } - ecs_move_t move = ti->hooks.move; - if (move) { - move(dst.ptr, ptr, 1, ti); - ecs_xtor_t dtor = ti->hooks.dtor; - if (dtor) { - dtor(ptr, 1, ti); - } - } else { - ecs_os_memcpy(dst.ptr, ptr, ti->size); + bool move_hook = ti->hooks.move != NULL; + flecs_type_info_move(dst.ptr, ptr, 1, ti); + if (move_hook) { + flecs_type_info_dtor(ptr, 1, ti); } flecs_stack_free(ptr, cmd->is._1.size); @@ -6243,6 +6659,7 @@ void flecs_cmd_batch_for_entity( case EcsCmdModified: case EcsCmdModifiedNoHook: case EcsCmdAddModified: + case EcsCmdSetDontFragment: case EcsCmdPath: case EcsCmdDelete: case EcsCmdClear: @@ -6261,11 +6678,11 @@ void flecs_cmd_batch_for_entity( if (added.count) { ecs_table_diff_t add_diff = ECS_TABLE_DIFF_INIT; add_diff.added = added; - add_diff.added_flags = diff->added_flags; + add_diff.added_flags = table_diff.added_flags; if (r->row & EcsEntityIsTraversable) { /* Update monitors since we didn't do this in flecs_commit. Do this - * before calling flecs_notify_on_add() since this can trigger + * before calling flecs_actions_move_add() since this can trigger * prefab instantiation logic. When that happens, prefab children * can be created for this instance which would mean that the table * count of r->cr would always be >0. @@ -6273,21 +6690,20 @@ void flecs_cmd_batch_for_entity( * monitors since queries will have correctly matched them. */ ecs_component_record_t *cr = flecs_components_get( world, ecs_pair(EcsWildcard, entity)); - ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); - if (ecs_map_count(&cr->cache.index)) { + if (cr && ecs_map_count(&cr->cache.index)) { flecs_update_component_monitors(world, &added, NULL); } } flecs_defer_begin(world, world->stages[0]); - flecs_notify_on_add(world, r->table, start_table, + flecs_actions_move_add(world, r->table, start_table, ECS_RECORD_TO_ROW(r->row), 1, &add_diff, 0, true, false); flecs_defer_end(world, world->stages[0]); } +done: diff->added.array = added.array; diff->added.count = added.count; - flecs_table_diff_builder_clear(diff); } @@ -6345,8 +6761,8 @@ bool flecs_defer_end( ecs_cmd_t *cmds = ecs_vec_first(queue); int32_t i, count = ecs_vec_count(queue); - ecs_table_diff_builder_t diff; - flecs_table_diff_builder_init(world, &diff); + ecs_table_diff_builder_t diff = {0}; + bool diff_builder_used = false; for (i = 0; i < count; i ++) { ecs_cmd_t *cmd = &cmds[i]; @@ -6360,6 +6776,11 @@ bool flecs_defer_end( /* Batch commands for entity to limit archetype moves */ if (is_alive) { + if (!diff_builder_used) { + flecs_table_diff_builder_init(world, &diff); + diff_builder_used = true; + } + flecs_cmd_batch_for_entity(world, &diff, e, cmds, i); } else { world->info.cmd.discard_count ++; @@ -6407,6 +6828,7 @@ bool flecs_defer_end( world->info.cmd.other_count ++; break; case EcsCmdSet: + case EcsCmdSetDontFragment: flecs_set_id_move(world, dst_stage, e, cmd->id, flecs_itosize(cmd->is._1.size), cmd->is._1.value, kind); @@ -6456,7 +6878,7 @@ bool flecs_defer_end( break; case EcsCmdOnDeleteAction: ecs_defer_begin(world); - flecs_on_delete(world, id, e, false); + flecs_on_delete(world, id, e, false, false); ecs_defer_end(world); world->info.cmd.other_count ++; break; @@ -6512,7 +6934,10 @@ bool flecs_defer_end( flecs_stack_reset(&commands->stack); ecs_vec_clear(queue); - flecs_table_diff_builder_fini(world, &diff); + + if (diff_builder_used) { + flecs_table_diff_builder_fini(world, &diff); + } /* Internal callback for capturing commands, signal queue is done */ if (world->on_commands_active) { @@ -6751,9 +7176,10 @@ void flecs_on_reparent( ecs_table_t *other_table, int32_t row, int32_t count) -{ - flecs_reparent_name_index(world, other_table, table, row, count); - flecs_ordered_children_reparent(world, other_table, table, row, count); +{ + flecs_reparent_name_index(world, table, other_table, row, count); + flecs_ordered_children_reparent(world, table, other_table, row, count); + flecs_non_fragmenting_childof_reparent(world, table, other_table, row, count); } static @@ -6768,6 +7194,7 @@ void flecs_on_unparent( flecs_unparent_name_index(world, table, other_table, row, count); } flecs_ordered_children_unparent(world, table, row, count); + flecs_non_fragmenting_childof_unparent(world, other_table, table, row, count); } bool flecs_sparse_on_add_cr( @@ -6920,7 +7347,8 @@ void flecs_entity_remove_non_fragmenting( r->row &= ~EcsEntityHasDontFragment; } -void flecs_notify_on_add( +static +void flecs_actions_on_add_intern( ecs_world_t *world, ecs_table_t *table, ecs_table_t *other_table, @@ -6931,42 +7359,78 @@ void flecs_notify_on_add( bool construct, bool sparse) { - ecs_assert(diff != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_flags32_t diff_flags = diff->added_flags; + if (!diff_flags) { + return; + } + const ecs_type_t *added = &diff->added; - if (added->count) { - ecs_flags32_t diff_flags = - diff->added_flags|(table->flags & EcsTableHasTraversable); - if (!diff_flags) { - return; - } + if (diff_flags & EcsTableEdgeReparent) { + flecs_on_reparent(world, table, other_table, row, count); + } - if (diff_flags & EcsTableEdgeReparent) { - flecs_on_reparent(world, table, other_table, row, count); + if (sparse && (diff_flags & EcsTableHasSparse)) { + if (flecs_sparse_on_add(world, table, row, count, added, construct)) { + diff_flags |= EcsTableHasOnAdd; } + } - if (sparse && (diff_flags & EcsTableHasSparse)) { - if (flecs_sparse_on_add(world, table, row, count, added, construct)) { - diff_flags |= EcsTableHasOnAdd; - } - } + if (diff_flags & (EcsTableHasOnAdd|EcsTableHasTraversable)) { + flecs_emit(world, world, &(ecs_event_desc_t){ + .event = EcsOnAdd, + .ids = added, + .table = table, + .other_table = other_table, + .offset = row, + .count = count, + .observable = world, + .flags = flags + }); + } +} - if (diff_flags & (EcsTableHasOnAdd|EcsTableHasTraversable)) { - flecs_emit(world, world, &(ecs_event_desc_t){ - .event = EcsOnAdd, - .ids = added, - .table = table, - .other_table = other_table, - .offset = row, - .count = count, - .observable = world, - .flags = flags - }); +static +void flecs_actions_on_remove_intern( + ecs_world_t *world, + ecs_table_t *table, + ecs_table_t *other_table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff, + ecs_flags32_t diff_flags) +{ + const ecs_type_t *removed = &diff->removed; + + ecs_assert(diff_flags != 0, ECS_INTERNAL_ERROR, NULL); + + if (diff_flags & EcsTableHasDontFragment) { + if (flecs_dont_fragment_on_remove( + world, table, row, count, removed)) + { + diff_flags |= EcsTableHasOnRemove; } } + + if (diff_flags & EcsTableHasOnRemove) { + flecs_emit(world, world, &(ecs_event_desc_t) { + .event = EcsOnRemove, + .ids = removed, + .table = table, + .other_table = other_table, + .offset = row, + .count = count, + .observable = world + }); + } + + if (diff_flags & EcsTableHasSparse) { + flecs_sparse_on_remove(world, table, row, count, removed); + } } -void flecs_notify_on_remove( +static +void flecs_actions_on_remove_intern_w_reparent( ecs_world_t *world, ecs_table_t *table, ecs_table_t *other_table, @@ -6974,53 +7438,136 @@ void flecs_notify_on_remove( int32_t count, const ecs_table_diff_t *diff) { - ecs_assert(diff != NULL, ECS_INTERNAL_ERROR, NULL); - const ecs_type_t *removed = &diff->removed; - ecs_assert(count != 0, ECS_INTERNAL_ERROR, NULL); + if (!(world->flags & EcsWorldFini)) { + ecs_check(!(table->flags & EcsTableHasBuiltins), + ECS_INVALID_OPERATION, + "removing components from builtin entities is not allowed"); + } - if (removed->count) { - if (!(world->flags & EcsWorldFini)) { - ecs_check(!(table->flags & EcsTableHasBuiltins), - ECS_INVALID_OPERATION, - "removing components from builtin entities is not allowed"); + ecs_flags32_t diff_flags = diff->removed_flags; + if (!diff_flags) { + return; + } + + if (diff_flags & (EcsTableEdgeReparent|EcsTableHasOrderedChildren)) { + if (!other_table || !(other_table->flags & EcsTableHasChildOf)) { + flecs_on_unparent(world, table, other_table, row, count); } + } + + flecs_actions_on_remove_intern( + world, table, other_table, row, count, diff, diff_flags); + +error: + return; +} + +void flecs_actions_new( + ecs_world_t *world, + ecs_table_t *table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff, + ecs_flags32_t flags, + bool construct, + bool sparse) +{ + flecs_actions_on_add_intern( + world, table, NULL, row, count, diff, flags, construct, sparse); +} + +void flecs_actions_delete( + ecs_world_t *world, + ecs_table_t *table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff) +{ + if (diff->removed.count) { + flecs_actions_on_remove_intern_w_reparent( + world, table, NULL, row, count, diff); + } +} - ecs_flags32_t diff_flags = - diff->removed_flags|(table->flags & EcsTableHasTraversable); +void flecs_actions_delete_tree( + ecs_world_t *world, + ecs_table_t *table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff) +{ + if (diff->removed.count) { + ecs_flags32_t diff_flags = diff->removed_flags; if (!diff_flags) { return; } - if (diff_flags & (EcsTableEdgeReparent|EcsTableHasOrderedChildren)) { - flecs_on_unparent(world, table, other_table, row, count); + flecs_actions_on_remove_intern( + world, table, NULL, row, count, diff, diff_flags); + } +} + +void flecs_actions_move_add( + ecs_world_t *world, + ecs_table_t *table, + ecs_table_t *other_table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff, + ecs_flags32_t flags, + bool construct, + bool sparse) +{ + ecs_assert(diff != NULL, ECS_INTERNAL_ERROR, NULL); + const ecs_type_t *added = &diff->added; + + if (added->count) { + ecs_flags32_t table_flags = table->flags; + + if (table_flags & EcsTableHasTraversable) { + flecs_emit_propagate_invalidate(world, table, row, count); } - if (diff_flags & EcsTableHasDontFragment) { - if (flecs_dont_fragment_on_remove( - world, table, row, count, removed)) - { - diff_flags |= EcsTableHasOnRemove; - } + if (table_flags & EcsTableHasParent) { + flecs_on_non_fragmenting_child_move_add( + world, table, other_table, row, count); } - if (diff_flags & (EcsTableHasOnRemove|EcsTableHasTraversable)) { - flecs_emit(world, world, &(ecs_event_desc_t) { - .event = EcsOnRemove, - .ids = removed, - .table = table, - .other_table = other_table, - .offset = row, - .count = count, - .observable = world - }); + flecs_actions_on_add_intern(world, table, other_table, row, count, diff, + flags, construct, sparse); + } +} + +void flecs_actions_move_remove( + ecs_world_t *world, + ecs_table_t *table, + ecs_table_t *other_table, + int32_t row, + int32_t count, + const ecs_table_diff_t *diff) +{ + ecs_assert(diff != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(count != 0, ECS_INTERNAL_ERROR, NULL); + + if (diff->removed.count) { + ecs_flags32_t table_flags = table->flags; + if (table_flags & EcsTableHasTraversable) { + flecs_emit_propagate_invalidate(world, table, row, count); } - if (diff_flags & EcsTableHasSparse) { - flecs_sparse_on_remove(world, table, row, count, removed); + if (table_flags & EcsTableHasParent) { + bool update_parent_records = true; + if (diff->added.count && (table->flags & EcsTableHasParent)) { + update_parent_records = false; + } + + flecs_on_non_fragmenting_child_move_remove( + world, other_table, table, row, count, update_parent_records); } + + flecs_actions_on_remove_intern_w_reparent( + world, table, other_table, row, count, diff); } -error: - return; } void flecs_notify_on_set_ids( @@ -7105,6 +7652,7 @@ void flecs_notify_on_set( ecs_component_record_t *cr = flecs_components_get(world, id); ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr->type_info != NULL, ECS_INTERNAL_ERROR, NULL); bool dont_fragment = (cr->flags & EcsIdDontFragment) != 0; if (invoke_hook) { @@ -7112,8 +7660,7 @@ void flecs_notify_on_set( ecs_iter_action_t on_set = ti->hooks.on_set; if (on_set) { ecs_table_record_t dummy_tr; - const ecs_table_record_t *tr = - flecs_component_get_table(cr, table); + const ecs_table_record_t *tr = flecs_component_get_table(cr, table); if (!tr) { dummy_tr.hdr.cr = cr; dummy_tr.hdr.table = table; @@ -7137,7 +7684,6 @@ void flecs_notify_on_set( } } - /* Run OnSet notifications */ if ((dont_fragment || table->flags & EcsTableHasOnSet)) { ecs_type_t ids = { .array = &id, .count = 1 }; flecs_emit(world, world, &(ecs_event_desc_t) { @@ -7538,22 +8084,23 @@ static ecs_record_t* flecs_new_entity( ecs_world_t *world, ecs_entity_t entity, - ecs_record_t *record, + ecs_record_t *r, ecs_table_t *table, ecs_table_diff_t *diff, bool ctor, ecs_flags32_t evt_flags) { - ecs_assert(record != NULL, ECS_INTERNAL_ERROR, NULL); - int32_t row = flecs_table_append(world, table, entity, ctor, true); - record->table = table; - record->row = ECS_ROW_TO_RECORD(row, record->row & ECS_ROW_FLAGS_MASK); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + int32_t row = ecs_table_count(table); + r->table = table; + r->row = ECS_ROW_TO_RECORD(row, r->row & ECS_ROW_FLAGS_MASK); + flecs_table_append(world, table, entity, ctor, true); ecs_assert(ecs_table_count(table) > row, ECS_INTERNAL_ERROR, NULL); - flecs_notify_on_add(world, table, NULL, row, 1, diff, evt_flags, ctor, true); - ecs_assert(table == record->table, ECS_INTERNAL_ERROR, NULL); + flecs_actions_new(world, table, row, 1, diff, evt_flags, ctor, true); + ecs_assert(table == r->table, ECS_INTERNAL_ERROR, NULL); - return record; + return r; } static @@ -7580,24 +8127,23 @@ void flecs_move_entity( ecs_assert(record->table == src_table, ECS_INTERNAL_ERROR, NULL); /* Append new row to destination table */ - int32_t dst_row = flecs_table_append(world, dst_table, entity, - false, false); + int32_t dst_row = ecs_table_count(dst_table); + flecs_table_append(world, dst_table, entity, false, false); /* Invoke remove actions for removed components */ - flecs_notify_on_remove(world, src_table, dst_table, src_row, 1, diff); + flecs_actions_move_remove(world, src_table, dst_table, src_row, 1, diff); + + record->table = dst_table; + record->row = ECS_ROW_TO_RECORD(dst_row, record->row & ECS_ROW_FLAGS_MASK); /* Copy entity & components from src_table to dst_table */ flecs_table_move(world, entity, entity, dst_table, dst_row, src_table, src_row, ctor); - ecs_assert(record->table == src_table, ECS_INTERNAL_ERROR, NULL); - - /* Update entity index & delete old data after running remove actions */ - record->table = dst_table; - record->row = ECS_ROW_TO_RECORD(dst_row, record->row & ECS_ROW_FLAGS_MASK); + ecs_assert(record->table == dst_table, ECS_INTERNAL_ERROR, NULL); flecs_table_delete(world, src_table, src_row, false); - flecs_notify_on_add(world, dst_table, src_table, dst_row, 1, diff, + flecs_actions_move_add(world, dst_table, src_table, dst_row, 1, diff, evt_flags, ctor, true); ecs_assert(record->table == dst_table, ECS_INTERNAL_ERROR, NULL); @@ -7632,11 +8178,11 @@ void flecs_commit( diff->added_flags |= non_fragment_flags; diff->removed_flags |= non_fragment_flags; - flecs_notify_on_add(world, src_table, src_table, + flecs_actions_move_add(world, src_table, src_table, ECS_RECORD_TO_ROW(record->row), 1, diff, evt_flags, construct, true); - flecs_notify_on_remove(world, src_table, src_table, + flecs_actions_move_remove(world, src_table, src_table, ECS_RECORD_TO_ROW(record->row), 1, diff); } flecs_journal_end(); @@ -7712,7 +8258,7 @@ const ecs_entity_t* flecs_bulk_new( component_array.count = type.count; } - flecs_notify_on_add(world, table, NULL, row, count, diff, + flecs_actions_move_add(world, table, NULL, row, count, diff, (component_data == NULL) ? 0 : EcsEventNoOnSet, true, true); if (component_data) { @@ -7744,14 +8290,10 @@ const ecs_entity_t* flecs_bulk_new( ptr = flecs_component_sparse_get( world, cr, table, entities[e]); - ecs_copy_t copy; - ecs_move_t move; - if (is_move && (move = ti->hooks.move)) { - move(ptr, src_ptr, 1, ti); - } else if (!is_move && (copy = ti->hooks.copy)) { - copy(ptr, src_ptr, 1, ti); + if (is_move) { + flecs_type_info_move(ptr, src_ptr, 1, ti); } else { - ecs_os_memcpy(ptr, src_ptr, size); + flecs_type_info_copy(ptr, src_ptr, 1, ti); } flecs_notify_on_set(world, table, row + e, id, true); @@ -7777,14 +8319,10 @@ const ecs_entity_t* flecs_bulk_new( ecs_assert(size != 0, ECS_INTERNAL_ERROR, NULL); ptr = ECS_ELEM(column->data, size, row); - ecs_copy_t copy; - ecs_move_t move; - if (is_move && (move = ti->hooks.move)) { - move(ptr, src_ptr, count, ti); - } else if (!is_move && (copy = ti->hooks.copy)) { - copy(ptr, src_ptr, count, ti); + if (is_move) { + flecs_type_info_move(ptr, src_ptr, count, ti); } else { - ecs_os_memcpy(ptr, src_ptr, size * count); + flecs_type_info_copy(ptr, src_ptr, count, ti); } } }; @@ -8046,7 +8584,8 @@ void flecs_add_to_root_table( ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(r->table == NULL, ECS_INTERNAL_ERROR, NULL); - int32_t row = flecs_table_append(world, &world->store.root, e, false, false); + int32_t row = ecs_table_count(&world->store.root); + flecs_table_append(world, &world->store.root, e, false, false); r->table = &world->store.root; r->row = ECS_ROW_TO_RECORD(row, r->row & ECS_ROW_FLAGS_MASK); @@ -8257,18 +8796,14 @@ void flecs_copy_id( { ecs_assert(dst_ptr != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(src_ptr != NULL, ECS_INTERNAL_ERROR, NULL); + (void)size; if (ti->hooks.on_replace) { flecs_invoke_replace_hook( world, r->table, entity, component, dst_ptr, src_ptr, ti); } - ecs_copy_t copy = ti->hooks.copy; - if (copy) { - copy(dst_ptr, src_ptr, 1, ti); - } else { - ecs_os_memcpy(dst_ptr, src_ptr, flecs_utosize(size)); - } + flecs_type_info_copy(dst_ptr, src_ptr, 1, ti); flecs_table_mark_dirty(world, r->table, component); @@ -8910,12 +9445,12 @@ void flecs_check_component( { if (ptr->size != size) { char *path = ecs_get_path(world, result); - ecs_abort(ECS_INVALID_COMPONENT_SIZE, path); + ecs_abort(ECS_INVALID_COMPONENT_SIZE, "%s", path); ecs_os_free(path); } if (ptr->alignment != alignment) { char *path = ecs_get_path(world, result); - ecs_abort(ECS_INVALID_COMPONENT_ALIGNMENT, path); + ecs_abort(ECS_INVALID_COMPONENT_ALIGNMENT, "%s", path); ecs_os_free(path); } } @@ -9062,17 +9597,13 @@ void ecs_delete( ecs_table_t *table; if (row_flags) { if (row_flags & EcsEntityIsTarget) { - flecs_on_delete(world, ecs_pair(EcsFlag, entity), 0, true); - flecs_on_delete(world, ecs_pair(EcsWildcard, entity), 0, true); + flecs_on_delete(world, ecs_pair(EcsFlag, entity), 0, true, true); + flecs_on_delete(world, ecs_pair(EcsWildcard, entity), 0, true, true); } if (row_flags & EcsEntityIsId) { - flecs_on_delete(world, entity, 0, true); - flecs_on_delete(world, ecs_pair(entity, EcsWildcard), 0, true); - } - - if (row_flags & EcsEntityIsTraversable) { - flecs_table_traversable_add(r->table, -1); + flecs_on_delete(world, entity, 0, true, true); + flecs_on_delete(world, ecs_pair(entity, EcsWildcard), 0, true, true); } /* Merge operations before deleting entity */ @@ -9096,10 +9627,14 @@ void ecs_delete( }; int32_t row = ECS_RECORD_TO_ROW(r->row); - flecs_notify_on_remove( + flecs_actions_move_remove( world, table, &world->store.root, row, 1, &diff); flecs_entity_remove_non_fragmenting(world, entity, r); flecs_table_delete(world, table, row, true); + + if (row_flags & EcsEntityIsTraversable) { + flecs_table_traversable_add(table, -1); + } } flecs_entities_remove(world, entity); @@ -9189,6 +9724,8 @@ ecs_entity_t ecs_clone( if (src_table->flags & EcsTableHasName) { dst_table = ecs_table_remove_id(world, src_table, ecs_pair_t(EcsIdentifier, EcsName)); + dst_table = ecs_table_remove_id(world, dst_table, + ecs_pair_t(EcsIdentifier, EcsSymbol)); } ecs_type_t dst_type = dst_table->type; @@ -9205,10 +9742,10 @@ ecs_entity_t ecs_clone( if (copy_value) { int32_t row = ECS_RECORD_TO_ROW(dst_r->row); - int32_t i, count = src_table->column_count; + int32_t i, count = dst_table->column_count; for (i = 0; i < count; i ++) { - int32_t type_id = ecs_table_column_to_type_index(src_table, i); - ecs_id_t component = src_table->type.array[type_id]; + int32_t index = ecs_table_column_to_type_index(dst_table, i); + ecs_id_t component = dst_table->type.array[index]; void *dst_ptr = ecs_get_mut_id(world, dst, component); if (!dst_ptr) { @@ -9217,11 +9754,7 @@ ecs_entity_t ecs_clone( const void *src_ptr = ecs_get_id(world, src, component); const ecs_type_info_t *ti = src_table->data.columns[i].ti; - if (ti->hooks.copy) { - ti->hooks.copy(dst_ptr, src_ptr, 1, ti); - } else { - ecs_os_memcpy(dst_ptr, src_ptr, ti->size); - } + flecs_type_info_copy(dst_ptr, src_ptr, 1, ti); flecs_notify_on_set(world, dst_table, row, component, true); } @@ -9626,13 +10159,13 @@ void flecs_modified_id_if( ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); ecs_component_record_t *cr = flecs_components_get(world, component); - if (!cr || !flecs_component_get_table(cr, table)) { + int32_t row = ECS_RECORD_TO_ROW(r->row); + if (!cr || !flecs_get_component(world, table, row, cr)) { flecs_defer_end(world, stage); return; } - flecs_notify_on_set( - world, table, ECS_RECORD_TO_ROW(r->row), component, invoke_hook); + flecs_notify_on_set(world, table, row, component, invoke_hook); flecs_table_mark_dirty(world, table, component); flecs_defer_end(world, stage); @@ -9710,17 +10243,11 @@ void flecs_set_id_move( world, r->table, entity, component, dst.ptr, ptr, ti); } - ecs_move_t move; if (cmd_kind != EcsCmdEmplace) { /* ctor will have happened by ensure */ - move = ti->hooks.move_dtor; + flecs_type_info_move_dtor(dst.ptr, ptr, 1, ti); } else { - move = ti->hooks.ctor_move_dtor; - } - if (move) { - move(dst.ptr, ptr, 1, ti); - } else { - ecs_os_memcpy(dst.ptr, ptr, flecs_utosize(size)); + flecs_type_info_ctor_move_dtor(dst.ptr, ptr, 1, ti); } flecs_table_mark_dirty(world, r->table, component); @@ -9732,6 +10259,9 @@ void flecs_set_id_move( flecs_notify_on_set_ids( world, table, ECS_RECORD_TO_ROW(r->row), 1, &ids); } + } else if (cmd_kind == EcsCmdSetDontFragment) { + flecs_notify_on_set( + world, r->table, ECS_RECORD_TO_ROW(r->row), component, true); } flecs_defer_end(world, stage); @@ -9791,7 +10321,7 @@ bool flecs_can_toggle( { ecs_component_record_t *cr = flecs_components_get(world, component); if (!cr) { - return false; + return ecs_has_id(world, component, EcsCanToggle); } return (cr->flags & EcsIdCanToggle) != 0; @@ -9975,6 +10505,19 @@ bool ecs_has_id( } } + if (ECS_PAIR_FIRST(component) == EcsChildOf) { + if (table->flags & EcsTableHasParent) { + if (ECS_PAIR_SECOND(component) == EcsWildcard) { + return true; + } + + int32_t column = table->component_map[ecs_id(EcsParent)]; + EcsParent *p = flecs_table_get_component( + table, column - 1, ECS_RECORD_TO_ROW(r->row)).ptr; + return (uint32_t)p->value == ECS_PAIR_SECOND(component); + } + } + can_inherit = cr->flags & EcsIdOnInstantiateInherit; } @@ -10018,7 +10561,7 @@ bool ecs_owns_id( if (component < FLECS_HI_COMPONENT_ID) { if (!world->non_trivial_lookup[component]) { - return table->component_map[component]; + return table->component_map[component] != 0; } } @@ -10032,12 +10575,90 @@ bool ecs_owns_id( if (cr->flags & (EcsIdDontFragment|EcsIdMatchDontFragment)) { return flecs_component_sparse_has(cr, entity); } + + if (ECS_PAIR_FIRST(component) == EcsChildOf) { + if (table->flags & EcsTableHasParent) { + if (ECS_PAIR_SECOND(component) == EcsWildcard) { + return true; + } + + int32_t column = table->component_map[ecs_id(EcsParent)]; + EcsParent *p = flecs_table_get_component( + table, column - 1, ECS_RECORD_TO_ROW(r->row)).ptr; + return (uint32_t)p->value == ECS_PAIR_SECOND(component); + } + } } error: return false; } +static +ecs_entity_t flecs_get_prefab_instance_child( + const ecs_world_t *world, + ecs_entity_t entity, + ecs_entity_t prefab_child) +{ + ecs_map_val_t *index_ptr = ecs_map_get( + &world->prefab_child_indices, prefab_child); + if (!index_ptr) { + return 0; + } + + flecs_assert_entity_valid(world, prefab_child, "get_target"); + ecs_check(ecs_owns_id(world, prefab_child, EcsPrefab), + ECS_INVALID_OPERATION, + "cannot get target for '%s': entity is not/no longer a prefab", + flecs_errstr(ecs_id_str(world, prefab_child))); + +#ifdef FLECS_DEBUG + ecs_entity_t prefab = ecs_get_parent(world, prefab_child); + ecs_check(prefab != 0, ECS_INVALID_OPERATION, + "cannot get target for '%s': entity has no parent", + flecs_errstr(ecs_id_str(world, prefab_child))); + + ecs_check(ecs_owns_id(world, prefab, EcsPrefab), ECS_INVALID_OPERATION, + "cannot get target for '%s': parent is not/no longer a prefab", + flecs_errstr(ecs_id_str(world, prefab)), + flecs_errstr_1(ecs_id_str(world, prefab_child))); + + ecs_check(ecs_has_pair(world, entity, EcsIsA, prefab), + ECS_INVALID_OPERATION, + "cannot get target for '%s': entity '%s' is not an instance of prefab '%s'", + flecs_errstr(ecs_id_str(world, prefab_child)), + flecs_errstr_1(ecs_id_str(world, entity)), + flecs_errstr_2(ecs_id_str(world, prefab))); +#endif + + ecs_component_record_t *childof_cr = flecs_components_get( + world, ecs_childof(entity)); + ecs_check(childof_cr != NULL, ECS_INVALID_OPERATION, + "cannot get target for '%s': children of '%s' have changed since " + "prefab instantiation", + flecs_errstr(ecs_id_str(world, prefab_child)), + flecs_errstr_1(ecs_id_str(world, entity))); + + ecs_vec_t *v = &childof_cr->pair->ordered_children; + int32_t index = flecs_uto(int32_t, *index_ptr); + ecs_check(ecs_vec_count(v) >= index, ECS_INVALID_OPERATION, + "cannot get target for '%s': children of '%s' have changed since " + "prefab instantiation", + flecs_errstr(ecs_id_str(world, prefab_child)), + flecs_errstr_1(ecs_id_str(world, entity))); + + ecs_entity_t tgt = ecs_vec_get_t(v, ecs_entity_t, index)[0]; + ecs_check(ecs_has_pair(world, tgt, EcsIsA, prefab_child), ECS_INVALID_OPERATION, + "cannot get target for '%s': children of '%s' have changed since " + "prefab instantiation", + flecs_errstr(ecs_id_str(world, prefab_child)), + flecs_errstr_1(ecs_id_str(world, entity))); + + return tgt; +error: + return 0; +} + ecs_entity_t ecs_get_target( const ecs_world_t *world, ecs_entity_t entity, @@ -10047,6 +10668,16 @@ ecs_entity_t ecs_get_target( ecs_check(world != NULL, ECS_INVALID_PARAMETER, NULL); flecs_assert_entity_valid(world, entity, "get_target"); ecs_check(rel != 0, ECS_INVALID_PARAMETER, NULL); + if (index < 0) { + return 0; + } + + if (rel == EcsChildOf) { + if (index > 0) { + return 0; + } + return ecs_get_parent(world, entity); + } world = ecs_get_world(world); @@ -10058,6 +10689,9 @@ ecs_entity_t ecs_get_target( ecs_id_t wc = ecs_pair(rel, EcsWildcard); ecs_component_record_t *cr = flecs_components_get(world, wc); if (!cr) { + if (!index) { + return flecs_get_prefab_instance_child(world, entity, rel); + } return 0; } @@ -10093,7 +10727,13 @@ ecs_entity_t ecs_get_target( goto look_in_base; } - return ecs_pair_second(world, table->type.array[tr->index + index]); + ecs_id_t pair_id = table->type.array[tr->index + index]; + if (!ECS_IS_VALUE_PAIR(pair_id)) { + return flecs_entities_get_alive(world, pair_id); + } else { + return ECS_PAIR_SECOND(pair_id); + } + look_in_base: if (table->flags & EcsTableHasIsA) { const ecs_table_record_t *tr_isa = flecs_component_get_table( @@ -10131,6 +10771,17 @@ ecs_entity_t ecs_get_parent( ecs_table_t *table = r->table; ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + if (table->flags & EcsTableHasParent) { + int32_t column = table->component_map[ecs_id(EcsParent)]; + ecs_assert(column > 0, ECS_INTERNAL_ERROR, NULL); + EcsParent *p = ecs_table_get_column( + table, column - 1, ECS_RECORD_TO_ROW(r->row)); + ecs_assert(ecs_is_valid(world, p->value), ECS_INVALID_OPERATION, + "Parent component points to invalid parent %u", + p->value, entity); + return p->value; + } + ecs_component_record_t *cr = world->cr_childof_wildcard; ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); @@ -10145,6 +10796,74 @@ ecs_entity_t ecs_get_parent( return 0; } +ecs_entity_t ecs_new_w_parent( + ecs_world_t *world, + ecs_entity_t parent, + const char *name) +{ + ecs_stage_t *stage = flecs_stage_from_world(&world); + flecs_poly_assert(world, ecs_world_t); + ecs_assert(!(world->flags & EcsWorldMultiThreaded), ECS_INVALID_OPERATION, + "cannot create new entity while world is multithreaded"); + + ecs_component_record_t *cr = flecs_components_ensure( + world, ecs_childof(parent)); + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_pair_record_t *pr = cr->pair; + ecs_assert(pr != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_entity_t entity = 0; + if (name) { + ecs_hashmap_t *name_index = pr->name_index; + if (name_index) { + entity = flecs_name_index_find(name_index, name, 0, 0); + if (entity) { + return entity; + } + } + } + + ecs_id_t type_ids[] = { + ecs_id(EcsParent), ecs_value_pair(EcsParentDepth, pr->depth)}; + + ecs_type_t type = { .count = 2, .array = type_ids }; + ecs_table_t *table = flecs_table_find_or_create(world, &type); + + ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + + entity = flecs_new_id(world); + ecs_record_t *r = flecs_entities_get(world, entity); + ecs_flags32_t flags = table->flags & EcsTableAddEdgeFlags; + + ecs_table_diff_t table_diff = { + .added = table->type, + .added_flags = flags + }; + + int32_t row = ecs_table_count(table); + flecs_table_append(world, table, entity, false, false); + r->table = table; + r->row = (uint32_t)row; + + flecs_actions_new(world, table, row, 1, &table_diff, 0, false, true); + + EcsParent *parent_ptr = table->data.columns[0].data; + parent_ptr = &parent_ptr[row]; + parent_ptr->value = parent; + + if (name) { + bool is_deferred = ecs_is_deferred(world); + if (is_deferred) ecs_defer_suspend(world); + flecs_set_identifier(world, stage, entity, EcsName, name); + if (is_deferred) ecs_defer_resume(world); + } + + flecs_add_non_fragmenting_child_w_records(world, parent, entity, cr, r); + + return entity; +} + ecs_entity_t ecs_get_target_for_id( const ecs_world_t *world, ecs_entity_t entity, @@ -10161,17 +10880,20 @@ ecs_entity_t ecs_get_target_for_id( world = ecs_get_world(world); ecs_table_t *table = ecs_get_table(world, entity); - ecs_entity_t subject = 0; + ecs_entity_t src = 0; if (rel) { - int32_t column = ecs_search_relation( - world, table, 0, component, rel, 0, &subject, 0, 0); + ecs_component_record_t *cr = flecs_components_get(world, component); + if (!cr) { + return 0; + } + + int32_t column = ecs_search_relation_for_entity( + world, entity, component, ecs_pair(rel, EcsWildcard), true, cr, &src, 0, 0); if (column == -1) { return 0; } } else { - entity = 0; /* Don't return entity if id was not found */ - if (table) { ecs_id_t *ids = table->type.array; int32_t i, count = table->type.count; @@ -10184,18 +10906,14 @@ ecs_entity_t ecs_get_target_for_id( } if (ecs_has_id(world, ent, component)) { - subject = ent; + src = ent; break; } } } } - if (subject == 0) { - return entity; - } else { - return subject; - } + return src; error: return 0; } @@ -10365,8 +11083,8 @@ void ecs_make_alive( ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(r->table == NULL, ECS_INTERNAL_ERROR, NULL); - int32_t row = flecs_table_append( - world, &world->store.root, entity, false, false); + int32_t row = ecs_table_count(&world->store.root); + flecs_table_append(world, &world->store.root, entity, false, false); r->table = &world->store.root; r->row = ECS_ROW_TO_RECORD(row, r->row & ECS_ROW_FLAGS_MASK); error: @@ -10391,10 +11109,13 @@ void ecs_make_alive_id( "first element of pair is not alive"); ecs_make_alive(world, r); } - if (flecs_entities_get_alive(world, t) == 0) { - ecs_assert(!ecs_exists(world, t), ECS_INVALID_PARAMETER, - "second element of pair is not alive"); - ecs_make_alive(world, t); + + if (!ECS_IS_VALUE_PAIR(component)) { + if (flecs_entities_get_alive(world, t) == 0) { + ecs_assert(!ecs_exists(world, t), ECS_INVALID_PARAMETER, + "second element of pair is not alive"); + ecs_make_alive(world, t); + } } } else { ecs_make_alive(world, component & ECS_COMPONENT_MASK); @@ -10780,26 +11501,28 @@ const char* flecs_path_elem( ecs_size_t size = size_out ? *size_out : 0; for (ptr = path; (ch = *ptr); ptr ++) { + bool escaped = false; if (ch == '<') { template_nesting ++; } else if (ch == '>') { template_nesting --; } else if (ch == '\\') { ptr ++; - if (buffer) { - buffer[pos] = ptr[0]; + ch = ptr[0]; + if (!ch) { + break; } - pos ++; - continue; + escaped = true; } - ecs_check(template_nesting >= 0, ECS_INVALID_PARAMETER, path); + ecs_check(template_nesting >= 0, ECS_INVALID_PARAMETER, "%s", path); - if (!template_nesting && flecs_is_sep(&ptr, sep)) { + if (!escaped && !template_nesting && flecs_is_sep(&ptr, sep)) { break; } if (buffer) { + ecs_assert(size > 0, ECS_INTERNAL_ERROR, NULL); if (pos >= (size - 1)) { if (size == ECS_NAME_BUFFER_LENGTH) { /* stack buffer */ char *new_buffer = ecs_os_malloc(size * 2 + 1); @@ -10915,13 +11638,13 @@ void flecs_bootstrap_entity_name( ecs_world_t *world) { ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_pair(ecs_id(EcsIdentifier), EcsSymbol) }, .callback = flecs_on_set_symbol, .events = {EcsOnSet}, - .yield_existing = true + .yield_existing = true, + .global_observer = true }); } @@ -10938,6 +11661,8 @@ void ecs_on_set(EcsIdentifier)( ecs_entity_t kind = ECS_PAIR_SECOND(evt_id); /* Name, Symbol, Alias */ ecs_id_t pair = ecs_childof(0); ecs_hashmap_t *index = NULL; + bool has_parent = false; + EcsParent *parents = NULL; if (kind == EcsSymbol) { index = &world->symbols; @@ -10945,14 +11670,20 @@ void ecs_on_set(EcsIdentifier)( index = &world->aliases; } else if (kind == EcsName) { ecs_assert(it->table != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_search(world, it->table, ecs_childof(EcsWildcard), &pair); - ecs_assert(pair != 0, ECS_INTERNAL_ERROR, NULL); - ecs_component_record_t *cr = flecs_components_get(world, pair); - if (evt == EcsOnSet) { - index = flecs_component_name_index_ensure(world, cr); + if (it->table->flags & EcsTableHasParent) { + has_parent = true; + parents = ecs_table_get(world, it->table, EcsParent, it->offset); } else { - index = flecs_component_name_index_get(world, cr); + ecs_search(world, it->table, ecs_childof(EcsWildcard), &pair); + ecs_assert(pair != 0, ECS_INTERNAL_ERROR, NULL); + + ecs_component_record_t *cr = flecs_components_get(world, pair); + if (evt == EcsOnSet) { + index = flecs_component_name_index_ensure(world, cr); + } else { + index = flecs_component_name_index_get(world, cr); + } } } @@ -10978,6 +11709,13 @@ void ecs_on_set(EcsIdentifier)( (it->entities[i] != EcsFlecsCore), ECS_INVALID_OPERATION, "cannot rename flecs.core module"); + + if (has_parent) { + ecs_component_record_t *cr = flecs_components_get( + world, ecs_childof(parents[i].value)); + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + index = flecs_component_name_index_ensure(world, cr); + } } if (cur->index && cur->index != index) { @@ -11061,8 +11799,8 @@ void flecs_reparent_name_index_intern( void flecs_reparent_name_index( ecs_world_t *world, + ecs_table_t *dst, ecs_table_t *src, - ecs_table_t *dst, int32_t offset, int32_t count) { @@ -11078,18 +11816,9 @@ void flecs_reparent_name_index( src = &world->store.root; } - ecs_pair_record_t *src_pair = src->_->childof_r; - ecs_pair_record_t *dst_pair = dst->_->childof_r; - - /* Reparenting should only get triggered when an entity changed parent */ - ecs_assert(src_pair != dst_pair, ECS_INTERNAL_ERROR, NULL); - - /* Even when an entity has no parent, it's still in the root scope */ - ecs_assert(src_pair != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(dst_pair != NULL, ECS_INTERNAL_ERROR, NULL); - - ecs_hashmap_t *src_index = src_pair->name_index; - ecs_hashmap_t *dst_index = dst_pair->name_index; + ecs_hashmap_t *src_index = flecs_table_get_name_index(world, src); + ecs_hashmap_t *dst_index = flecs_table_get_name_index(world, dst); + ecs_assert(src_index != dst_index, ECS_INTERNAL_ERROR, NULL); if ((!src_index && !dst_index)) { return; } @@ -11121,9 +11850,9 @@ void flecs_unparent_name_index( return; } - ecs_assert(src->_->childof_r != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_hashmap_t *src_index = src->_->childof_r->name_index; - ecs_hashmap_t *dst_index = dst ? dst->_->childof_r->name_index : NULL; + ecs_hashmap_t *src_index = flecs_table_get_name_index(world, src); + ecs_hashmap_t *dst_index = dst ? flecs_table_get_name_index(world, dst) : NULL; + ecs_assert(src_index != NULL, ECS_INTERNAL_ERROR, NULL); EcsIdentifier *names = ecs_table_get_pair(world, src, EcsIdentifier, EcsName, offset); @@ -11435,9 +12164,6 @@ void flecs_add_path( ecs_add_pair(world, entity, EcsChildOf, parent); } - ecs_assert(name[0] != '#', ECS_INVALID_PARAMETER, - "path should not contain identifier with #"); - ecs_set_name(world, entity, name); if (defer_suspend) { @@ -11610,7 +12336,6 @@ const char* ecs_get_symbol( } } -static ecs_entity_t flecs_set_identifier( ecs_world_t *world, ecs_stage_t *stage, @@ -11723,9 +12448,20 @@ bool ecs_id_match( "first element of pair cannot be 0"); ecs_check(pattern_second != 0, ECS_INVALID_PARAMETER, "second element of pair cannot be 0"); + + bool pattern_first_wildcard = pattern_first == EcsWildcard; + bool pattern_second_wc = pattern_second == EcsWildcard; + if (ECS_IS_VALUE_PAIR(pattern)) { + if (!ECS_IS_VALUE_PAIR(id)) { + return false; + } + + pattern_first_wildcard = false; + pattern_second_wc = false; + } - if (pattern_first == EcsWildcard) { - if (pattern_second == EcsWildcard || pattern_second == id_second) { + if (pattern_first_wildcard) { + if (pattern_second_wc || pattern_second == id_second) { return true; } } else if (pattern_first == EcsFlag) { @@ -11777,6 +12513,10 @@ bool ecs_id_is_wildcard( } ecs_entity_t first = ECS_PAIR_FIRST(id); + if (ECS_IS_VALUE_PAIR(id)) { + return (first == EcsWildcard) || (first == EcsAny); + } + ecs_entity_t second = ECS_PAIR_SECOND(id); return (first == EcsWildcard) || (second == EcsWildcard) || @@ -11822,6 +12562,10 @@ const char* flecs_id_invalid_reason( if (!ECS_PAIR_SECOND(id)) { return "invalid pair: second element is 0"; } + } else if (ECS_HAS_ID_FLAG(id, VALUE_PAIR)) { + if (!ECS_PAIR_FIRST(id)) { + return "invalid value pair: first element is 0 (is the relationship registered?)"; + } } else if (id & ECS_ID_FLAGS_MASK) { if (!ecs_is_valid(world, id & ECS_COMPONENT_MASK)) { ecs_abort(ECS_INTERNAL_ERROR, NULL); @@ -11875,8 +12619,11 @@ ecs_id_t ecs_id_from_str( } const char* ecs_id_flag_str( - ecs_entity_t entity) + uint64_t entity) { + if (ECS_IS_VALUE_PAIR(entity)) { + return "VALUE_PAIR"; + } else if (ECS_HAS_ID_FLAG(entity, PAIR)) { return "PAIR"; } else @@ -11911,20 +12658,27 @@ void ecs_id_str_buf( if (ECS_HAS_ID_FLAG(id, PAIR)) { ecs_entity_t rel = ECS_PAIR_FIRST(id); - ecs_entity_t obj = ECS_PAIR_SECOND(id); + ecs_entity_t tgt = ECS_PAIR_SECOND(id); ecs_entity_t e; if ((e = ecs_get_alive(world, rel))) { rel = e; } - if ((e = ecs_get_alive(world, obj))) { - obj = e; - } ecs_strbuf_appendch(buf, '('); ecs_get_path_w_sep_buf(world, 0, rel, NULL, NULL, buf, false); ecs_strbuf_appendch(buf, ','); - ecs_get_path_w_sep_buf(world, 0, obj, NULL, NULL, buf, false); + + if (ECS_IS_VALUE_PAIR(id)) { + ecs_strbuf_appendlit(buf, "@"); + ecs_strbuf_appendint(buf, (uint32_t)tgt); + } else { + if ((e = ecs_get_alive(world, tgt))) { + tgt = e; + } + ecs_get_path_w_sep_buf(world, 0, tgt, NULL, NULL, buf, false); + } + ecs_strbuf_appendch(buf, ')'); } else { ecs_entity_t e = id & ECS_COMPONENT_MASK; @@ -11959,9 +12713,10 @@ bool ecs_id_is_tag( { if (ecs_id_is_wildcard(id)) { /* If id is a wildcard, we can't tell if it's a tag or not, except - * when the relationship part of a pair has the Tag property */ + * when the relationship part of a pair has the PairIsTag property */ if (ECS_HAS_ID_FLAG(id, PAIR)) { - if (ECS_PAIR_FIRST(id) != EcsWildcard) { + ecs_entity_t first = ECS_PAIR_FIRST(id); + if (first != EcsWildcard && first != EcsAny) { ecs_entity_t rel = ecs_pair_first(world, id); if (ecs_is_valid(world, rel)) { if (ecs_has_id(world, rel, EcsPairIsTag)) { @@ -11990,7 +12745,6 @@ bool ecs_id_is_tag( return false; } - ecs_entity_t ecs_get_typeid( const ecs_world_t *world, ecs_id_t id) @@ -12145,13 +12899,62 @@ int32_t flecs_child_type_insert( return i; } +void flecs_instantiate_sparse( + ecs_world_t *world, + const ecs_table_range_t *base_child_range, + const ecs_entity_t *base_children, + ecs_table_t *instance_table, + const ecs_entity_t *instance_children, + int32_t row_offset) +{ + ecs_table_t *base_child_table = base_child_range->table; + if (!(base_child_table->flags & EcsTableHasSparse)) { + return; + } + + ecs_table_record_t *trs = base_child_table->_->records; + int32_t i, count = base_child_table->type.count; + for (i = 0; i < count; i ++) { + ecs_table_record_t *tr = &trs[i]; + ecs_component_record_t *cr = tr->hdr.cr; + + if (!(cr->flags & EcsIdSparse)) { + continue; + } + + const ecs_type_info_t *ti = cr->type_info; + if (!ti) { + continue; + } + + ecs_id_t id = base_child_table->type.array[i]; + + for (int32_t j = 0; j < base_child_range->count; j ++) { + ecs_entity_t child = base_children[j + base_child_range->offset]; + ecs_entity_t instance_child = instance_children[j]; + + void *src_ptr = flecs_sparse_get(cr->sparse, ti->size, child); + ecs_assert(src_ptr != NULL, ECS_INTERNAL_ERROR, NULL); + + void *dst_ptr = flecs_sparse_get(cr->sparse, ti->size, instance_child); + ecs_assert(dst_ptr != NULL, ECS_INTERNAL_ERROR, NULL); + + flecs_type_info_copy(dst_ptr, src_ptr, 1, ti); + + flecs_notify_on_set( + world, instance_table, row_offset + j, id, true); + } + } +} + static void flecs_instantiate_children( ecs_world_t *world, ecs_entity_t base, ecs_entity_t instance, ecs_table_range_t child_range, - const ecs_instantiate_ctx_t *ctx) + const ecs_instantiate_ctx_t *ctx, + int32_t depth) { if (!child_range.count) { return; @@ -12327,6 +13130,9 @@ void flecs_instantiate_children( const ecs_entity_t *i_children = flecs_bulk_new(world, i_table, child_ids, &diff.added, child_range.count, component_data, false, &child_row, &diff); + flecs_instantiate_sparse( + world, &child_range, children, i_table, i_children, child_row); + /* If children are slots, add slot relationships to parent */ if (slot_of) { for (j = 0; j < child_range.count; j ++) { @@ -12340,7 +13146,7 @@ void flecs_instantiate_children( /* If prefab child table has children itself, recursively instantiate */ for (j = 0; j < child_range.count; j ++) { ecs_entity_t child = children[j + child_range.offset]; - flecs_instantiate(world, child, i_children[j], &ctx_cur); + flecs_instantiate(world, child, i_children[j], &ctx_cur, depth + 1); } flecs_wfree_n(world, ecs_entity_t, child_range.count, child_ids); @@ -12348,7 +13154,6 @@ void flecs_instantiate_children( return; } -static void flecs_instantiate_dont_fragment( ecs_world_t *world, ecs_entity_t base, @@ -12374,11 +13179,13 @@ void flecs_instantiate_dont_fragment( if (ti) { ecs_assert(ptr != NULL, ECS_INTERNAL_ERROR, NULL); - if (ti->hooks.copy) { - ti->hooks.copy(ptr, base_ptr, 1, ti); - } else { - ecs_os_memcpy(ptr, base_ptr, ti->size); - } + flecs_type_info_copy(ptr, base_ptr, 1, ti); + } + + if (ti) { + flecs_notify_on_set( + world, r->table, ECS_RECORD_TO_ROW(r->row), + cur->id, true); } } } @@ -12415,11 +13222,15 @@ void flecs_instantiate( ecs_world_t *world, ecs_entity_t base, ecs_entity_t instance, - const ecs_instantiate_ctx_t *ctx) + const ecs_instantiate_ctx_t *ctx, + int32_t depth) { ecs_record_t *record = flecs_entities_get_any(world, base); ecs_table_t *base_table = record->table; ecs_assert(base_table != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_check(depth < FLECS_DAG_DEPTH_MAX, ECS_CYCLE_DETECTED, + "likely cycle detected during instantiation of base %s", + flecs_errstr(ecs_get_path(world, base))); if (base_table->flags & EcsTableOverrideDontFragment) { flecs_instantiate_override_dont_fragment( @@ -12437,34 +13248,61 @@ void flecs_instantiate( } ecs_component_record_t *cr = flecs_components_get(world, ecs_childof(base)); - ecs_table_cache_iter_t it; - if (cr && flecs_table_cache_all_iter((ecs_table_cache_t*)cr, &it)) { + if (cr) { ecs_os_perf_trace_push("flecs.instantiate"); + if (cr->flags & EcsIdOrderedChildren) { + if (flecs_component_has_non_fragmenting_childof(cr)) { + EcsTreeSpawner *ts = flecs_get_mut( + world, base, ecs_id(EcsTreeSpawner), record, + sizeof(EcsTreeSpawner)).ptr; + if (!ts) { + ts = flecs_prefab_spawner_build(world, base); + } + + if (ts) { + flecs_spawner_instantiate(world, ts, instance); + } + + ecs_os_perf_trace_pop("flecs.instantiate"); + return; + } + ecs_vec_t *children_vec = &cr->pair->ordered_children; int32_t i, count = ecs_vec_count(children_vec); ecs_entity_t *children = ecs_vec_first(children_vec); for (i = 0; i < count; i ++) { ecs_entity_t child = children[i]; ecs_table_range_t range = flecs_range_from_entity(world, child); + + if (!(range.table->flags & EcsTableHasChildOf)) { + continue; + } + flecs_instantiate_children( - world, base, instance, range, ctx); + world, base, instance, range, ctx, depth); } } else { - const ecs_table_record_t *tr; - while ((tr = flecs_table_cache_next(&it, ecs_table_record_t))) { - ecs_table_range_t range = { - tr->hdr.table, - 0, - ecs_table_count(tr->hdr.table) - }; - - flecs_instantiate_children( - world, base, instance, range, ctx); + ecs_table_cache_iter_t it; + if (flecs_table_cache_all_iter((ecs_table_cache_t*)cr, &it)) { + const ecs_table_record_t *tr; + while ((tr = flecs_table_cache_next(&it, ecs_table_record_t))) { + ecs_table_range_t range = { + tr->hdr.table, + 0, + ecs_table_count(tr->hdr.table) + }; + + flecs_instantiate_children( + world, base, instance, range, ctx, depth); + } } } + ecs_os_perf_trace_pop("flecs.instantiate"); } +error: + return; } /** @@ -12573,29 +13411,14 @@ void* ecs_field_w_size( "missing size for field %d", index); ecs_check(ecs_field_size(it, index) == size || !ecs_field_size(it, index), - ECS_INVALID_PARAMETER, "mismatching size for field %d", index); + ECS_INVALID_PARAMETER, + "mismatching size for field %d (expected '%s')", + index, + flecs_errstr(ecs_id_str(it->world, it->ids[index]))); (void)size; - if (it->ptrs && !it->offset) { - void *ptr = it->ptrs[index]; - if (ptr) { -#ifdef FLECS_DEBUG - if (it->trs[index]) { - /* Make sure that address in ptrs array is the same as what this - * function would have returned if no ptrs array was set. */ - void **temp_ptrs = it->ptrs; - ECS_CONST_CAST(ecs_iter_t*, it)->ptrs = NULL; - ecs_assert(ptr == ecs_field_w_size(it, size, index), - ECS_INTERNAL_ERROR, NULL); - ECS_CONST_CAST(ecs_iter_t*, it)->ptrs = temp_ptrs; - } else { - /* We're just passing in a pointer to a value that may not be - * a component on the entity (such as a pointer to a new value - * in an on_replace hook). */ - } -#endif - return ptr; - } + if (it->ptrs) { + return it->ptrs[index]; } const ecs_table_record_t *tr = it->trs[index]; @@ -13510,11 +14333,11 @@ uint64_t flecs_ito_( v.u = u; if (is_signed) { - ecs_assert(v.s >= flecs_s_min[size], ECS_INVALID_CONVERSION, err); - ecs_assert(v.s <= flecs_s_max[size], ECS_INVALID_CONVERSION, err); + ecs_assert(v.s >= flecs_s_min[size], ECS_INVALID_CONVERSION, "%s", err); + ecs_assert(v.s <= flecs_s_max[size], ECS_INVALID_CONVERSION, "%s", err); } else { - ecs_assert(lt_zero == false, ECS_INVALID_CONVERSION, err); - ecs_assert(u <= flecs_u_max[size], ECS_INVALID_CONVERSION, err); + ecs_assert(lt_zero == false, ECS_INVALID_CONVERSION, "%s", err); + ecs_assert(u <= flecs_u_max[size], ECS_INVALID_CONVERSION, "%s", err); } return u; @@ -13901,6 +14724,13 @@ char* flecs_astresc( return out; } +static +bool flecs_parse_is_e( + char e) +{ + return e == 'e' || e == 'E'; +} + const char* flecs_parse_digit( const char *ptr, char *token) @@ -13918,8 +14748,10 @@ const char* flecs_parse_digit( ptr ++; for (; (ch = *ptr); ptr ++) { - if (!isdigit(ch) && (ch != '.') && (ch != 'e')) { - break; + if (!isdigit(ch) && (ch != '.') && !flecs_parse_is_e(ch)) { + if (ch != '-' || !flecs_parse_is_e(ptr[-1])) { + break; + } } tptr[0] = ch; @@ -14012,6 +14844,7 @@ void flecs_observable_init( ecs_observable_t *observable) { flecs_sparse_init_t(&observable->events, NULL, NULL, ecs_event_record_t); + ecs_vec_init_t(NULL, &observable->global_observers, ecs_observer_t*, 0); observable->on_add.event = EcsOnAdd; observable->on_remove.event = EcsOnRemove; observable->on_set.event = EcsOnSet; @@ -14020,6 +14853,12 @@ void flecs_observable_init( void flecs_observable_fini( ecs_observable_t *observable) { + int32_t i, count = ecs_vec_count(&observable->global_observers); + ecs_observer_t **observers = ecs_vec_first(&observable->global_observers); + for (i = 0; i < count; i ++) { + flecs_observer_fini(observers[i]); + } + ecs_assert(!ecs_map_is_init(&observable->on_add.event_ids), ECS_INTERNAL_ERROR, NULL); ecs_assert(!ecs_map_is_init(&observable->on_remove.event_ids), @@ -14028,7 +14867,7 @@ void flecs_observable_fini( ECS_INTERNAL_ERROR, NULL); ecs_sparse_t *events = &observable->events; - int32_t i, count = flecs_sparse_count(events); + count = flecs_sparse_count(events); for (i = 0; i < count; i ++) { ecs_event_record_t *er = flecs_sparse_get_dense_t(events, ecs_event_record_t, i); @@ -14040,6 +14879,7 @@ void flecs_observable_fini( ECS_INTERNAL_ERROR, NULL); } + ecs_vec_fini_t(NULL, &observable->global_observers, ecs_observer_t*); flecs_sparse_fini(&observable->events); } @@ -14252,6 +15092,60 @@ void flecs_emit_propagate( ecs_event_id_record_t **iders, int32_t ider_count); +static +void flecs_emit_propagate_id_for_range( + ecs_world_t *world, + ecs_iter_t *it, + ecs_component_record_t *cr, + ecs_entity_t trav, + ecs_event_id_record_t **iders, + int32_t ider_count, + ecs_table_range_t *range) +{ + ecs_table_t *table = range->table; + int32_t count = range->count; + int32_t offset = range->offset; + + bool owned = flecs_component_get_table(cr, table) != NULL; + + int32_t e; + it->table = table; + it->other_table = NULL; + it->offset = 0; + it->count = count; + it->up_fields = 1; + if (count) { + it->entities = &ecs_table_entities(table)[offset]; + } + + int32_t ider_i; + for (ider_i = 0; ider_i < ider_count; ider_i ++) { + ecs_event_id_record_t *ider = iders[ider_i]; + flecs_observers_invoke(world, &ider->up, it, table, trav); + + if (!owned) { + /* Owned takes precedence */ + flecs_observers_invoke(world, &ider->self_up, it, table, trav); + } + } + + if (!table->_->traversable_count) { + return; + } + + const ecs_entity_t *entities = it->entities; + for (e = 0; e < count; e ++) { + ecs_component_record_t *cr_t = flecs_components_get( + world, ecs_pair(EcsWildcard, entities[e])); + if (cr_t) { + /* Only notify for entities that are used in pairs with + * traversable relationships */ + flecs_emit_propagate(world, it, cr, cr_t, trav, + iders, ider_count); + } + } +} + static void flecs_emit_propagate_id( ecs_world_t *world, @@ -14263,6 +15157,30 @@ void flecs_emit_propagate_id( int32_t ider_count) { ecs_table_cache_iter_t idt; + + if ((trav == EcsChildOf) && (flecs_component_has_non_fragmenting_childof(cur))) { + ecs_assert(ECS_PAIR_FIRST(cur->id) == EcsChildOf, ECS_INTERNAL_ERROR, NULL); + + if (!(cur->flags & EcsIdMarkedForDelete)) { + int32_t i, count = ecs_vec_count(&cur->pair->ordered_children); + ecs_entity_t *children = ecs_vec_first(&cur->pair->ordered_children); + for (i = 0; i < count; i ++) { + ecs_record_t *r = flecs_entities_get(world, children[i]); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + + flecs_emit_propagate_id_for_range( + world, it, cr, trav, iders, ider_count, + &(ecs_table_range_t){ + .table = r->table, + .offset = ECS_RECORD_TO_ROW(r->row), + .count = 1 + }); + } + } + + return; + } + if (!flecs_table_cache_all_iter(&cur->cache, &idt)) { return; } @@ -14275,44 +15193,12 @@ void flecs_emit_propagate_id( continue; } - bool owned = flecs_component_get_table(cr, table) != NULL; - - int32_t e, entity_count = ecs_table_count(table); - it->table = table; - it->other_table = NULL; - it->offset = 0; - it->count = entity_count; - it->up_fields = 1; - if (entity_count) { - it->entities = ecs_table_entities(table); - } - - int32_t ider_i; - for (ider_i = 0; ider_i < ider_count; ider_i ++) { - ecs_event_id_record_t *ider = iders[ider_i]; - flecs_observers_invoke(world, &ider->up, it, table, trav); - - if (!owned) { - /* Owned takes precedence */ - flecs_observers_invoke(world, &ider->self_up, it, table, trav); - } - } - - if (!table->_->traversable_count) { - continue; - } - - const ecs_entity_t *entities = ecs_table_entities(table); - for (e = 0; e < entity_count; e ++) { - ecs_component_record_t *cr_t = flecs_components_get( - world, ecs_pair(EcsWildcard, entities[e])); - if (cr_t) { - /* Only notify for entities that are used in pairs with - * traversable relationships */ - flecs_emit_propagate(world, it, cr, cr_t, trav, - iders, ider_count); - } - } + flecs_emit_propagate_id_for_range( + world, it, cr, trav, iders, ider_count, + &(ecs_table_range_t){ + .table = table, + .count = ecs_table_count(table), + }); } it->event_cur = event_cur; @@ -14383,6 +15269,19 @@ void flecs_emit_propagate_invalidate_tables( rc->generation ++; + if (flecs_component_has_non_fragmenting_childof(cur)) { + int32_t i, count = ecs_vec_count(&cur->pair->ordered_children); + ecs_entity_t *children = ecs_vec_first(&cur->pair->ordered_children); + + for (i = 0; i < count; i ++) { + ecs_component_record_t *cr_t = flecs_components_get( + world, ecs_pair(EcsWildcard, children[i])); + if (cr_t) { + flecs_emit_propagate_invalidate_tables(world, cr_t); + } + } + } + ecs_table_cache_iter_t idt; if (!flecs_table_cache_all_iter(&cur->cache, &idt)) { continue; @@ -14402,8 +15301,6 @@ void flecs_emit_propagate_invalidate_tables( ecs_component_record_t *cr_t = flecs_components_get( world, ecs_pair(EcsWildcard, entities[e])); if (cr_t) { - /* Only notify for entities that are used in pairs with - * traversable relationships */ flecs_emit_propagate_invalidate_tables(world, cr_t); } } @@ -14753,17 +15650,28 @@ void flecs_emit_forward_table_up( if (cr == tgt_cr) { char *idstr = ecs_id_str(world, cr->id); - ecs_assert(cr != tgt_cr, ECS_CYCLE_DETECTED, idstr); + ecs_assert(cr != tgt_cr, ECS_CYCLE_DETECTED, "%s", idstr); ecs_os_free(idstr); return; } /* Id has the same relationship, traverse to find ids for forwarding */ - if (ECS_PAIR_FIRST(id) == trav || ECS_PAIR_FIRST(id) == EcsIsA) { + if (ECS_PAIR_FIRST(id) == trav || ECS_PAIR_FIRST(id) == EcsIsA || ( + (trav == EcsChildOf) && id == ecs_id(EcsParent))) + { ecs_table_t **t = ecs_vec_append_t(&world->allocator, stack, ecs_table_t*); t[0] = tgt_table; + if (id == ecs_id(EcsParent)) { + const EcsParent *parent = ecs_get(world, tgt, EcsParent); + ecs_assert(parent != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(parent->value != 0, ECS_INTERNAL_ERROR, NULL); + + cr = flecs_components_get(world, ecs_childof(parent->value)); + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + } + ecs_assert(cr->pair != NULL, ECS_INTERNAL_ERROR, NULL); ecs_reachable_cache_t *cr_rc = &cr->pair->reachable; if (cr_rc->current == cr_rc->generation) { @@ -14870,7 +15778,7 @@ void flecs_emit_forward_up( { if (depth >= FLECS_DAG_DEPTH_MAX) { char *idstr = ecs_id_str(world, cr->id); - ecs_assert(depth < FLECS_DAG_DEPTH_MAX, ECS_CYCLE_DETECTED, idstr); + ecs_assert(depth < FLECS_DAG_DEPTH_MAX, ECS_CYCLE_DETECTED, "%s", idstr); ecs_os_free(idstr); return; } @@ -15254,7 +16162,7 @@ void flecs_emit( * event) this will cause the components of the target entity to be * propagated to the source entity. This makes it possible for observers to * get notified of any new reachable components though the relationship. */ - bool can_forward = event != EcsOnSet; + bool can_forward = true; /* Does table has observed entities */ bool has_observed = table_flags & EcsTableHasTraversable; @@ -15262,10 +16170,6 @@ void flecs_emit( ecs_event_id_record_t *iders[5] = {0}; ecs_table_record_t dummy_tr; - if (count && can_forward && has_observed) { - flecs_emit_propagate_invalidate(world, table, offset, count); - } - repeat_event: /* This is the core event logic, which is executed for each event. By * default this is just the event kind from the ecs_event_desc_t struct, but @@ -15290,14 +16194,45 @@ void flecs_emit( continue; } + /* Forward events for Parent component as ChildOf pairs. */ + if (id == ecs_id(EcsParent) && !table_event && + (table->flags & EcsTableHasParent)) + { + ecs_event_desc_t pdesc = *desc; + + pdesc.event = event; + if (event == EcsOnSet) { + /* If the Parent component is set, forward it as an OnAdd event + * for a ChildOf pair. */ + pdesc.event = EcsOnAdd; + } + + /* Iterate over entities, forward for their specific parent. */ + const EcsParent *parents = ecs_table_get_column(table, + table->component_map[ecs_id(EcsParent)] - 1, it.offset); + int32_t p, parent_count = pdesc.count; + + for (p = 0; p < parent_count; p ++) { + ecs_entity_t parent = parents[p].value; + if (parent && flecs_entities_is_alive(world, parent)) { + ecs_id_t pair = ecs_childof(parent); + ecs_type_t type = { .count = 1, .array = &pair }; + pdesc.ids = &type; + flecs_emit(world, stage, &pdesc); + } + } + } + int32_t ider_i, ider_count = 0; ecs_component_record_t *cr = flecs_components_get(world, id); - ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + if (!cr) { + continue; + } ecs_flags32_t cr_flags = cr->flags; /* Check if this id is a pair of an traversable relationship. If so, we * may have to forward ids from the pair's target. */ - if (can_forward && (cr_flags & EcsIdTraversable)) { + if (can_forward && ECS_IS_PAIR(id) && (cr_flags & EcsIdTraversable)) { const ecs_event_record_t *er_fwd = NULL; if (ECS_PAIR_FIRST(id) == EcsIsA) { if (event == EcsOnAdd) { @@ -15318,7 +16253,7 @@ void flecs_emit( for (e = 0; e < count; e ++) { flecs_instantiate( - world, tgt, instances[offset + e], NULL); + world, tgt, instances[offset + e], NULL, 0); } world->stages[0]->base = 0; @@ -15332,6 +16267,7 @@ void flecs_emit( /* Forward events for components from pair target */ flecs_emit_forward(world, er, er_fwd, ids, &it, table, cr); + ecs_assert(it.event_cur == evtx, ECS_INTERNAL_ERROR, NULL); } @@ -15359,7 +16295,7 @@ void flecs_emit( }; bool dont_fragment = cr_flags & EcsIdDontFragment; - if (!dont_fragment && id != EcsAny) { + if (!dont_fragment && id != EcsAny && (ECS_PAIR_FIRST(id) != EcsChildOf)) { if (tr == NULL) { /* When a single batch contains multiple add's for an exclusive * relationship, it's possible that an id was in the added list @@ -15425,7 +16361,9 @@ void flecs_emit( if (non_trivial_set) { ecs_component_record_t *cr = flecs_components_get(world, id); - ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + if (!cr) { + continue; + } const ecs_type_info_t *ti = cr->type_info;; ecs_flags32_t cr_flags = cr->flags; @@ -15606,7 +16544,9 @@ void flecs_inc_observer_count( if (event == EcsOnSet || event == EcsWildcard) { if (id < FLECS_HI_COMPONENT_ID) { world->non_trivial_set[id] = true; - } else if (id == EcsWildcard || id == EcsAny) { + } + + if (id == EcsWildcard || id == EcsAny) { ecs_os_memset_n(world->non_trivial_set, true, bool, FLECS_HI_COMPONENT_ID); } @@ -15630,6 +16570,19 @@ void flecs_inc_observer_count( flecs_event_id_record_remove(evt, id); ecs_os_free(idt); } + + if (ECS_PAIR_FIRST(id) == EcsChildOf) { + ecs_observable_t *observable = &world->observable; + if (event == EcsOnAdd) { + ecs_event_record_t *er_onset = + flecs_event_record_ensure(observable, EcsOnSet); + flecs_inc_observer_count( + world, EcsOnSet, er_onset, ecs_id(EcsParent), value); + } else { + flecs_inc_observer_count( + world, event, evt, ecs_id(EcsParent), value); + } + } } static @@ -15649,21 +16602,53 @@ ecs_id_t flecs_observer_id( } static -void flecs_register_observer_for_id( +void flecs_register_observer_for_event_and_id( ecs_world_t *world, ecs_observable_t *observable, ecs_observer_t *o, - size_t offset) + size_t offset, + const ecs_term_t *term, + ecs_entity_t event, + ecs_id_t term_id) { ecs_observer_impl_t *impl = flecs_observer_impl(o); - ecs_id_t term_id = flecs_observer_id(impl->register_id); - ecs_term_t *term = o->query ? &o->query->terms[0] : NULL; ecs_entity_t trav = term ? term->trav : 0; + /* Get observers for event */ + ecs_event_record_t *er = flecs_event_record_ensure(observable, event); + ecs_assert(er != NULL, ECS_INTERNAL_ERROR, NULL); + + /* Get observers for (component) id for event */ + ecs_event_id_record_t *idt = flecs_event_id_record_ensure( + world, er, term_id); + ecs_assert(idt != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_map_t *observers = ECS_OFFSET(idt, offset); + ecs_map_init_if(observers, &world->allocator); + ecs_map_insert_ptr(observers, impl->id, o); + + flecs_inc_observer_count(world, event, er, term_id, 1); + if (trav && (term_id != ecs_id(EcsParent))) { + flecs_inc_observer_count(world, event, er, + ecs_pair(trav, EcsWildcard), 1); + } +} + +static +void flecs_register_observer_for_id( + ecs_world_t *world, + ecs_observable_t *observable, + ecs_observer_t *o, + size_t offset, + ecs_id_t term_id) +{ + ecs_term_t *term = o->query ? &o->query->terms[0] : NULL; + int i, j; for (i = 0; i < o->event_count; i ++) { ecs_entity_t event = flecs_get_observer_event( term, o->events[i]); + for (j = 0; j < i; j ++) { if (event == flecs_get_observer_event(term, o->events[j])) { break; @@ -15674,24 +16659,8 @@ void flecs_register_observer_for_id( continue; } - /* Get observers for event */ - ecs_event_record_t *er = flecs_event_record_ensure(observable, event); - ecs_assert(er != NULL, ECS_INTERNAL_ERROR, NULL); - - /* Get observers for (component) id for event */ - ecs_event_id_record_t *idt = flecs_event_id_record_ensure( - world, er, term_id); - ecs_assert(idt != NULL, ECS_INTERNAL_ERROR, NULL); - - ecs_map_t *observers = ECS_OFFSET(idt, offset); - ecs_map_init_if(observers, &world->allocator); - ecs_map_insert_ptr(observers, impl->id, o); - - flecs_inc_observer_count(world, event, er, term_id, 1); - if (trav) { - flecs_inc_observer_count(world, event, er, - ecs_pair(trav, EcsWildcard), 1); - } + flecs_register_observer_for_event_and_id( + world, observable, o, offset, term, event, term_id); } } @@ -15704,16 +16673,27 @@ void flecs_uni_observer_register( ecs_term_t *term = o->query ? &o->query->terms[0] : NULL; ecs_flags64_t flags = term ? ECS_TERM_REF_FLAGS(&term->src) : EcsSelf; + ecs_observer_impl_t *impl = flecs_observer_impl(o); + ecs_id_t term_id = flecs_observer_id(impl->register_id); + if ((flags & (EcsSelf|EcsUp)) == (EcsSelf|EcsUp)) { flecs_register_observer_for_id(world, observable, o, - offsetof(ecs_event_id_record_t, self_up)); + offsetof(ecs_event_id_record_t, self_up), term_id); } else if (flags & EcsSelf) { flecs_register_observer_for_id(world, observable, o, - offsetof(ecs_event_id_record_t, self)); + offsetof(ecs_event_id_record_t, self), term_id); } else if (flags & EcsUp) { ecs_assert(term->trav != 0, ECS_INTERNAL_ERROR, NULL); flecs_register_observer_for_id(world, observable, o, - offsetof(ecs_event_id_record_t, up)); + offsetof(ecs_event_id_record_t, up), term_id); + } + + if (term && (term->trav == EcsChildOf)) { + ecs_assert(o->query != NULL, ECS_INTERNAL_ERROR, NULL); + if (o->query->flags & EcsQueryTableOnly) { + flecs_register_observer_for_id(world, observable, o, + offsetof(ecs_event_id_record_t, self), ecs_id(EcsParent)); + } } } @@ -15722,10 +16702,10 @@ void flecs_unregister_observer_for_id( ecs_world_t *world, ecs_observable_t *observable, ecs_observer_t *o, - size_t offset) + size_t offset, + ecs_id_t term_id) { ecs_observer_impl_t *impl = flecs_observer_impl(o); - ecs_id_t term_id = flecs_observer_id(impl->register_id); ecs_term_t *term = o->query ? &o->query->terms[0] : NULL; ecs_entity_t trav = term ? term->trav : 0; @@ -15758,7 +16738,7 @@ void flecs_unregister_observer_for_id( } flecs_inc_observer_count(world, event, er, term_id, -1); - if (trav) { + if (trav && (term_id != ecs_id(EcsParent))) { flecs_inc_observer_count(world, event, er, ecs_pair(trav, EcsWildcard), -1); } @@ -15780,15 +16760,25 @@ void flecs_unregister_observer( ecs_term_t *term = q ? &q->terms[0] : NULL; ecs_flags64_t flags = term ? ECS_TERM_REF_FLAGS(&term->src) : EcsSelf; + ecs_observer_impl_t *impl = flecs_observer_impl(o); + ecs_id_t term_id = flecs_observer_id(impl->register_id); + if ((flags & (EcsSelf|EcsUp)) == (EcsSelf|EcsUp)) { flecs_unregister_observer_for_id(world, observable, o, - offsetof(ecs_event_id_record_t, self_up)); + offsetof(ecs_event_id_record_t, self_up), term_id); } else if (flags & EcsSelf) { flecs_unregister_observer_for_id(world, observable, o, - offsetof(ecs_event_id_record_t, self)); + offsetof(ecs_event_id_record_t, self), term_id); } else if (flags & EcsUp) { flecs_unregister_observer_for_id(world, observable, o, - offsetof(ecs_event_id_record_t, up)); + offsetof(ecs_event_id_record_t, up), term_id); + } + + if (term && (term->trav == EcsChildOf)) { + if (o->query->flags & EcsQueryTableOnly) { + flecs_unregister_observer_for_id(world, observable, o, + offsetof(ecs_event_id_record_t, self), ecs_id(EcsParent)); + } } } @@ -16078,6 +17068,7 @@ void flecs_multi_observer_invoke( ecs_assert(pivot_field < user_it.field_count, ECS_INTERNAL_ERROR, NULL); user_it.ids[pivot_field] = it->event_id; user_it.trs[pivot_field] = it->trs[0]; + user_it.sources[pivot_field] = it->sources[0]; user_it.term_index = pivot_term; user_it.ctx = o->ctx; @@ -16561,8 +17552,10 @@ ecs_observer_t* flecs_observer_init( (dummy_query.flags & EcsQueryMatchOnlySelf) && !dummy_query.row_fields; if (trivial_observer) { - dummy_query.flags |= desc->query.flags; - query = &dummy_query; + if (ECS_PAIR_FIRST(dummy_query.terms[0].id) != EcsChildOf) { + dummy_query.flags |= desc->query.flags; + query = &dummy_query; + } } else { /* We're going to create an actual query, so undo the keep_alive * increment of the dummy_query. */ @@ -16713,90 +17706,102 @@ ecs_entity_t ecs_observer_init( "cannot create observer while world is being deleted"); entity = desc->entity; - if (!entity) { + if (!entity && !desc->global_observer) { entity = ecs_entity(world, {0}); } - EcsPoly *poly = flecs_poly_bind(world, entity, ecs_observer_t); - if (!poly->poly) { + EcsPoly *poly = NULL; + if (!entity) { ecs_observer_t *o = flecs_observer_init(world, entity, desc);\ if (!o) { goto error; } - ecs_assert(o->entity == entity, ECS_INTERNAL_ERROR, NULL); - poly->poly = o; - - if (ecs_get_name(world, entity)) { - ecs_trace("#[green]observer#[reset] %s created", - ecs_get_name(world, entity)); - } + ecs_vec_append_t(NULL, &world->observable.global_observers, + ecs_observer_t*)[0] = o; } else { - flecs_poly_assert(poly->poly, ecs_observer_t); - ecs_observer_t *o = (ecs_observer_t*)poly->poly; + poly = flecs_poly_bind(world, entity, ecs_observer_t); - if (o->ctx_free) { - if (o->ctx && o->ctx != desc->ctx) { - o->ctx_free(o->ctx); + if (!poly->poly) { + ecs_observer_t *o = flecs_observer_init(world, entity, desc);\ + if (!o) { + goto error; } - } - if (o->callback_ctx_free) { - if (o->callback_ctx && o->callback_ctx != desc->callback_ctx) { - o->callback_ctx_free(o->callback_ctx); - o->callback_ctx_free = NULL; - o->callback_ctx = NULL; + ecs_assert(o->entity == entity, ECS_INTERNAL_ERROR, NULL); + poly->poly = o; + + if (ecs_get_name(world, entity)) { + ecs_trace("#[green]observer#[reset] %s created", + ecs_get_name(world, entity)); } - } + } else { + flecs_poly_assert(poly->poly, ecs_observer_t); + ecs_observer_t *o = (ecs_observer_t*)poly->poly; - if (o->run_ctx_free) { - if (o->run_ctx && o->run_ctx != desc->run_ctx) { - o->run_ctx_free(o->run_ctx); - o->run_ctx_free = NULL; - o->run_ctx = NULL; + if (o->ctx_free) { + if (o->ctx && o->ctx != desc->ctx) { + o->ctx_free(o->ctx); + } } - } - if (desc->run) { - o->run = desc->run; - if (!desc->callback) { - o->callback = NULL; + if (o->callback_ctx_free) { + if (o->callback_ctx && o->callback_ctx != desc->callback_ctx) { + o->callback_ctx_free(o->callback_ctx); + o->callback_ctx_free = NULL; + o->callback_ctx = NULL; + } } - } - if (desc->callback) { - o->callback = desc->callback; - if (!desc->run) { - o->run = NULL; + if (o->run_ctx_free) { + if (o->run_ctx && o->run_ctx != desc->run_ctx) { + o->run_ctx_free(o->run_ctx); + o->run_ctx_free = NULL; + o->run_ctx = NULL; + } } - } - if (desc->ctx) { - o->ctx = desc->ctx; - } + if (desc->run) { + o->run = desc->run; + if (!desc->callback) { + o->callback = NULL; + } + } - if (desc->callback_ctx) { - o->callback_ctx = desc->callback_ctx; - } + if (desc->callback) { + o->callback = desc->callback; + if (!desc->run) { + o->run = NULL; + } + } - if (desc->run_ctx) { - o->run_ctx = desc->run_ctx; - } + if (desc->ctx) { + o->ctx = desc->ctx; + } - if (desc->ctx_free) { - o->ctx_free = desc->ctx_free; - } + if (desc->callback_ctx) { + o->callback_ctx = desc->callback_ctx; + } - if (desc->callback_ctx_free) { - o->callback_ctx_free = desc->callback_ctx_free; - } + if (desc->run_ctx) { + o->run_ctx = desc->run_ctx; + } - if (desc->run_ctx_free) { - o->run_ctx_free = desc->run_ctx_free; + if (desc->ctx_free) { + o->ctx_free = desc->ctx_free; + } + + if (desc->callback_ctx_free) { + o->callback_ctx_free = desc->callback_ctx_free; + } + + if (desc->run_ctx_free) { + o->run_ctx_free = desc->run_ctx_free; + } } - } - flecs_poly_modified(world, entity, ecs_observer_t); + flecs_poly_modified(world, entity, ecs_observer_t); + } return entity; error: @@ -16917,61 +17922,68 @@ void flecs_marked_id_push( m->action = action; m->delete_id = delete_id; + cr->flags |= EcsIdMarkedForDelete; + flecs_component_claim(world, cr); } static -void flecs_id_mark_for_delete( +void flecs_component_mark_for_delete( ecs_world_t *world, ecs_component_record_t *cr, ecs_entity_t action, bool delete_id); static -void flecs_targets_mark_for_delete( +void flecs_target_mark_for_delete( ecs_world_t *world, - ecs_table_t *table) + ecs_entity_t e) { ecs_component_record_t *cr; - const ecs_entity_t *entities = ecs_table_entities(table); - int32_t i, count = ecs_table_count(table); - for (i = 0; i < count; i ++) { - ecs_record_t *r = flecs_entities_get(world, entities[i]); - if (!r) { - continue; - } + ecs_record_t *r = flecs_entities_get(world, e); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); - /* If entity is not used as id or as relationship target, there won't - * be any tables with a reference to it. */ - ecs_flags32_t flags = r->row & ECS_ROW_FLAGS_MASK; - if (!(flags & (EcsEntityIsId|EcsEntityIsTarget))) { - continue; - } + /* If entity is not used as id or as relationship target, there won't + * be any tables with a reference to it. */ + ecs_flags32_t flags = r->row & ECS_ROW_FLAGS_MASK; + if (!(flags & (EcsEntityIsId|EcsEntityIsTarget))) { + return; + } - ecs_entity_t e = entities[i]; - if (flags & EcsEntityIsId) { - if ((cr = flecs_components_get(world, e))) { - flecs_id_mark_for_delete(world, cr, - ECS_ID_ON_DELETE(cr->flags), true); - } - if ((cr = flecs_components_get(world, ecs_pair(e, EcsWildcard)))) { - flecs_id_mark_for_delete(world, cr, - ECS_ID_ON_DELETE(cr->flags), true); - } + if (flags & EcsEntityIsId) { + if ((cr = flecs_components_get(world, e))) { + flecs_component_mark_for_delete(world, cr, + ECS_ID_ON_DELETE(cr->flags), true); } - if (flags & EcsEntityIsTarget) { - if ((cr = flecs_components_get(world, ecs_pair(EcsWildcard, e)))) { - flecs_id_mark_for_delete(world, cr, - ECS_ID_ON_DELETE_TARGET(cr->flags), true); - } - if ((cr = flecs_components_get(world, ecs_pair(EcsFlag, e)))) { - flecs_id_mark_for_delete(world, cr, - ECS_ID_ON_DELETE_TARGET(cr->flags), true); - } + if ((cr = flecs_components_get(world, ecs_pair(e, EcsWildcard)))) { + flecs_component_mark_for_delete(world, cr, + ECS_ID_ON_DELETE(cr->flags), true); + } + } + if (flags & EcsEntityIsTarget) { + if ((cr = flecs_components_get(world, ecs_pair(EcsWildcard, e)))) { + flecs_component_mark_for_delete(world, cr, + ECS_ID_ON_DELETE_TARGET(cr->flags), true); + } + if ((cr = flecs_components_get(world, ecs_pair(EcsFlag, e)))) { + flecs_component_mark_for_delete(world, cr, + ECS_ID_ON_DELETE_TARGET(cr->flags), true); } } } +static +void flecs_targets_mark_for_delete( + ecs_world_t *world, + ecs_table_t *table) +{ + const ecs_entity_t *entities = ecs_table_entities(table); + int32_t i, count = ecs_table_count(table); + for (i = 0; i < count; i ++) { + flecs_target_mark_for_delete(world, entities[i]); + } +} + static bool flecs_id_is_delete_target( ecs_id_t id, @@ -17030,7 +18042,169 @@ ecs_entity_t flecs_get_delete_action( } static -void flecs_id_mark_for_delete( +void flecs_simple_delete( + ecs_world_t *world, + ecs_entity_t entity, + ecs_record_t *r) +{ + ecs_check(world != NULL, ECS_INVALID_PARAMETER, NULL); + ecs_check(entity != 0, ECS_INVALID_PARAMETER, NULL); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_check(!ecs_has_pair(world, entity, EcsOnDelete, EcsPanic), + ECS_CONSTRAINT_VIOLATED, + "cannot delete entity '%s' with (OnDelete, Panic) trait", + flecs_errstr(ecs_get_path(world, entity))); + + flecs_journal_begin(world, EcsJournalDelete, entity, NULL, NULL); + + /* Entity is still in use by a query */ + ecs_assert((world->flags & EcsWorldQuit) || + !flecs_component_is_delete_locked(world, entity), + ECS_INVALID_OPERATION, + "cannot delete '%s' as it is still in use by queries", + flecs_errstr(ecs_id_str(world, entity))); + + ecs_table_t *table = r->table; + ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_table_diff_t diff = { + .removed = table->type, + .removed_flags = table->flags & EcsTableRemoveEdgeFlags + }; + + int32_t row = ECS_RECORD_TO_ROW(r->row); + flecs_actions_delete_tree(world, table, row, 1, &diff); + flecs_entity_remove_non_fragmenting(world, entity, r); + flecs_table_delete(world, table, row, true); + + flecs_entities_remove(world, entity); + + flecs_journal_end(); +error: + return; +} + +static +bool flecs_is_childof_tgt_only( + const ecs_component_record_t *cr) +{ + ecs_pair_record_t *pr = cr->pair; + if (pr->second.next) { + return false; + } + + if (ECS_PAIR_FIRST(pr->second.prev->id) != EcsWildcard) { + return false; + } + + return true; +} + +static +void flecs_component_delete_non_fragmenting_childof( + ecs_world_t *world, + ecs_component_record_t *cr) +{ + cr->flags |= EcsIdMarkedForDelete; + + ecs_pair_record_t *pr = cr->pair; + int32_t i, count = ecs_vec_count(&pr->ordered_children); + ecs_entity_t *children = ecs_vec_first(&pr->ordered_children); + + for (i = 0; i < count; i ++) { + ecs_entity_t e = children[i]; + ecs_assert(ecs_is_alive(world, e), ECS_INTERNAL_ERROR, NULL); + + ecs_record_t *r = flecs_entities_get_any(world, e); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + + if ((r->row & EcsEntityIsTarget)) { + ecs_component_record_t *child_cr = flecs_components_get( + world, ecs_childof(e)); + if (child_cr && + !(child_cr->flags & EcsIdMarkedForDelete) && + flecs_component_has_non_fragmenting_childof(child_cr)) + { + if (!flecs_is_childof_tgt_only(child_cr)) { + /* Entity is used as target with other relationships, go + * through regular cleanup path. */ + flecs_target_mark_for_delete(world, e); + } else { + flecs_component_delete_non_fragmenting_childof( + world, child_cr); + } + } else { + /* Entity is a target but is not a (non-fragmenting) ChildOf + * target. Go through regular cleanup path. */ + flecs_target_mark_for_delete(world, e); + } + } + + flecs_simple_delete(world, e, r); + } + + ecs_component_record_t *tgt_wc = pr->second.prev; + ecs_assert(ECS_PAIR_FIRST(tgt_wc->id) == EcsWildcard, ECS_INTERNAL_ERROR, NULL); + flecs_component_release(world, tgt_wc); +} + +static +bool flecs_component_mark_non_fragmenting_childof( + ecs_world_t *world, + ecs_component_record_t *cr) +{ + ecs_entity_t tgt = ECS_PAIR_SECOND(cr->id); + + ecs_component_record_t *childof_cr = flecs_components_get( + world, ecs_childof(tgt)); + if (!childof_cr) { + return false; + } + + ecs_flags32_t flags = childof_cr->flags; + + if (flags & EcsIdMarkedForDelete) { + return false; + } + + childof_cr->flags |= EcsIdMarkedForDelete; + + if (!flecs_component_has_non_fragmenting_childof(childof_cr)) { + return false; + } + + ecs_pair_record_t *pr = childof_cr->pair; + + if (!pr->second.next) { + if (ECS_PAIR_FIRST(pr->second.prev->id) == EcsWildcard) { + /* Entity is only used as ChildOf target */ + flecs_component_delete_non_fragmenting_childof(world, childof_cr); + return true; + } + } + + flecs_marked_id_push(world, childof_cr, EcsDelete, true); + + int32_t i, count = ecs_vec_count(&pr->ordered_children); + ecs_entity_t *children = ecs_vec_first(&pr->ordered_children); + for (i = 0; i < count; i ++) { + ecs_entity_t e = children[i]; + + ecs_component_record_t *tgt_cr = flecs_components_get( + world, ecs_pair(EcsWildcard, e)); + if (!tgt_cr) { + continue; + } + + flecs_component_mark_for_delete(world, tgt_cr, 0, true); + } + + return false; +} + +static +void flecs_component_mark_for_delete( ecs_world_t *world, ecs_component_record_t *cr, ecs_entity_t action, @@ -17040,12 +18214,16 @@ void flecs_id_mark_for_delete( return; } - cr->flags |= EcsIdMarkedForDelete; flecs_marked_id_push(world, cr, action, delete_id); ecs_id_t id = cr->id; bool delete_target = flecs_id_is_delete_target(id, action); + if (delete_target) { + if (flecs_component_mark_non_fragmenting_childof(world, cr)) { + return; + } + } /* Mark all tables with the id for delete */ ecs_table_cache_iter_t it; @@ -17149,7 +18327,7 @@ bool flecs_on_delete_mark( return false; } - flecs_id_mark_for_delete(world, cr, action, delete_id); + flecs_component_mark_for_delete(world, cr, action, delete_id); return true; } @@ -17206,7 +18384,7 @@ void flecs_remove_from_table( } } - flecs_notify_on_remove(world, table, NULL, 0, table_count, &td); + flecs_actions_move_remove(world, table, dst_table, 0, table_count, &td); ecs_log_pop_3(); } @@ -17217,12 +18395,14 @@ void flecs_remove_from_table( } static -bool flecs_on_delete_clear_tables( - ecs_world_t *world) +bool flecs_on_delete_clear_entities( + ecs_world_t *world, + bool force_delete) { /* Iterate in reverse order so that DAGs get deleted bottom to top */ int32_t i, last = ecs_vec_count(&world->store.marked_ids), first = 0; ecs_marked_id_t *ids = ecs_vec_first(&world->store.marked_ids); + do { for (i = last - 1; i >= first; i --) { ecs_component_record_t *cr = ids[i].cr; @@ -17235,6 +18415,18 @@ bool flecs_on_delete_clear_tables( while ((tr = flecs_table_cache_next(&it, ecs_table_record_t))) { ecs_table_t *table = tr->hdr.table; + /* If table contains prefabs and we're not deleting the + * prefab entity itself (!force_delete), don't delete table. + * This means that delete_with/remove_all can be used safely + * for game entities without risking modifying prefabs. + * If force_delete is true, it means that one of the + * components, relationships or relationship targets is + * being deleted in which case the table must go too. */ + if ((table->flags & EcsTableIsPrefab) && !force_delete) { + table->flags &= ~EcsTableMarkedForDelete; + continue; + } + if ((action == EcsRemove) || !(table->flags & EcsTableMarkedForDelete)) { @@ -17243,15 +18435,22 @@ bool flecs_on_delete_clear_tables( ecs_dbg_3( "#[red]delete#[reset] entities from table %u", (uint32_t)table->id); - flecs_table_delete_entities(world, table); + ecs_table_clear_entities(world, table); } } } - /* Run commands so children get notified before parent is deleted */ - if (world->stages[0]->defer) { - flecs_defer_end(world, world->stages[0]); - flecs_defer_begin(world, world->stages[0]); + /* If component record contains children with Parent components, + * delete them. */ + if (flecs_component_has_non_fragmenting_childof(cr)) { + int32_t c, count = ecs_vec_count(&cr->pair->ordered_children); + ecs_entity_t *children = ecs_vec_first(&cr->pair->ordered_children); + + ecs_defer_suspend(world); + for (c = count - 1; c >= 0; c --) { + ecs_delete(world, children[c]); + } + ecs_defer_resume(world); } /* User code (from triggers) could have enqueued more ids to delete, @@ -17295,12 +18494,15 @@ void flecs_on_delete_clear_sparse( static bool flecs_on_delete_clear_ids( - ecs_world_t *world) + ecs_world_t *world, + bool force_delete) { int32_t i, count = ecs_vec_count(&world->store.marked_ids); ecs_marked_id_t *ids = ecs_vec_first(&world->store.marked_ids); int twice = 2; + (void)force_delete; + do { for (i = 0; i < count; i ++) { /* Release normal ids before wildcard ids */ @@ -17333,26 +18535,36 @@ bool flecs_on_delete_clear_ids( } } - flecs_component_release_tables(world, cr); - - /* Release the claim taken by flecs_marked_id_push. This may delete the - * component record as all other claims may have been released. */ - int32_t rc = flecs_component_release(world, cr); - ecs_assert(rc >= 0, ECS_INTERNAL_ERROR, NULL); - (void)rc; + if (flecs_component_release_tables(world, cr)) { + ecs_assert(!force_delete, ECS_INVALID_OPERATION, + "cannot delete component '%s': tables are keeping it alive", + flecs_errstr(ecs_id_str(world, cr->id))); - /* If rc is 0, the id was likely deleted by a nested delete_with call - * made by an on_remove handler/OnRemove observer */ - if (rc) { - if (delete_id) { - /* If id should be deleted, release initial claim. This happens when - * a component, tag, or part of a pair is deleted. */ - flecs_component_release(world, cr); - } else { - /* If id should not be deleted, unmark component record for deletion. This - * happens when all instances *of* an id are deleted, for example - * when calling ecs_remove_all or ecs_delete_with. */ - cr->flags &= ~EcsIdMarkedForDelete; + /* There are still tables remaining. This can happen when + * flecs_table_keep has been called for a table, which is used + * whenever code doesn't want a table to get deleted. */ + cr->flags &= ~EcsIdMarkedForDelete; + flecs_component_release(world, cr); + } else { + /* Release the claim taken by flecs_marked_id_push. This may delete the + * component record as all other claims may have been released. */ + int32_t rc = flecs_component_release(world, cr); + ecs_assert(rc >= 0, ECS_INTERNAL_ERROR, NULL); + (void)rc; + + /* If rc is 0, the id was likely deleted by a nested delete_with call + * made by an on_remove handler/OnRemove observer */ + if (rc) { + if (delete_id) { + /* If id should be deleted, release initial claim. This happens when + * a component, tag, or part of a pair is deleted. */ + flecs_component_release(world, cr); + } else { + /* If id should not be deleted, unmark component record for deletion. This + * happens when all instances *of* an id are deleted, for example + * when calling ecs_remove_all or ecs_delete_with. */ + cr->flags &= ~EcsIdMarkedForDelete; + } } } } @@ -17380,7 +18592,8 @@ void flecs_on_delete( ecs_world_t *world, ecs_id_t id, ecs_entity_t action, - bool delete_id) + bool delete_id, + bool force_delete) { /* Cleanup can happen recursively. If a cleanup action is already in * progress, only append ids to the marked_ids. The topmost cleanup @@ -17395,22 +18608,11 @@ void flecs_on_delete( ecs_dbg_2("#[red]delete#[reset]"); ecs_log_push_2(); - /* Empty tables with all the to be deleted ids */ - flecs_on_delete_clear_tables(world); + /* Delete all the entities from the to be deleted tables/components */ + flecs_on_delete_clear_entities(world, force_delete); /* Release remaining references to the ids */ - flecs_on_delete_clear_ids(world); - - /* Verify deleted ids are no longer in use */ -#ifdef FLECS_DEBUG - ecs_marked_id_t *ids = ecs_vec_first(&world->store.marked_ids); - count = ecs_vec_count(&world->store.marked_ids); - for (i = 0; i < count; i ++) { - ecs_assert(!ecs_id_in_use(world, ids[i].id), - ECS_INTERNAL_ERROR, NULL); - } -#endif - ecs_assert(!ecs_id_in_use(world, id), ECS_INTERNAL_ERROR, NULL); + flecs_on_delete_clear_ids(world, force_delete); /* Ids are deleted, clear stack */ ecs_vec_clear(&world->store.marked_ids); @@ -17440,7 +18642,7 @@ void ecs_delete_with( return; } - flecs_on_delete(world, id, EcsDelete, false); + flecs_on_delete(world, id, EcsDelete, false, false); flecs_defer_end(world, stage); flecs_journal_end(); @@ -17457,7 +18659,7 @@ void ecs_remove_all( return; } - flecs_on_delete(world, id, EcsRemove, false); + flecs_on_delete(world, id, EcsRemove, false, false); flecs_defer_end(world, stage); flecs_journal_end(); @@ -17560,20 +18762,26 @@ void flecs_dump_backtrace( SYMBOL_INFO *symbol; HANDLE hProcess = GetCurrentProcess(); - SymInitialize(hProcess, NULL, TRUE); + if (!SymInitialize(hProcess, NULL, TRUE)) { + return; + } frames = CaptureStackBackTrace(0, ECS_BT_BUF_SIZE, stack, NULL); - symbol = (SYMBOL_INFO*)ecs_os_malloc( + symbol = (SYMBOL_INFO*)ecs_os_calloc( sizeof(SYMBOL_INFO) + 256 * sizeof(char)); symbol->MaxNameLen = 255; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); for (int i = 0; i < frames; i++) { - SymFromAddr(hProcess, (DWORD)(uintptr_t)stack[i], NULL, symbol); - fprintf(stream, "%s\n", symbol->Name); + if (SymFromAddr(hProcess, (DWORD64)(uintptr_t)stack[i], NULL, symbol)) { + fprintf(stream, "%s\n", symbol->Name); + } else { + fprintf(stream, "%p\n", stack[i]); + } } ecs_os_free(symbol); + SymCleanup(hProcess); } #elif HAVE_EXECINFO @@ -18425,7 +19633,13 @@ void ecs_ref_update( return; } - ecs_check(ecs_is_alive(world, ref->entity), ECS_INVALID_PARAMETER, NULL); + if (!ecs_is_alive(world, ref->entity)) { + ref->table_id = 0; + ref->table_version_fast = 0; + ref->table_version = 0; + ref->ptr = NULL; + return; + } if (ref->table_id == table->id && ref->table_version == table->version) { ref->table_version_fast = flecs_get_table_version_fast(world, ref->table_id); @@ -18474,10 +19688,24 @@ void* ecs_ref_get_id( static -int32_t flecs_type_search( +int32_t flecs_table_search_relation( + const ecs_world_t *world, + const ecs_record_t *record, + const ecs_table_t *table, + int32_t offset, + ecs_id_t id, + ecs_component_record_t *cr, + ecs_id_t rel, + ecs_component_record_t *cr_r, + bool self, + ecs_entity_t *tgt_out, + ecs_id_t *id_out, + ecs_table_record_t **tr_out); + +static +int32_t flecs_table_search( const ecs_table_t *table, ecs_component_record_t *cr, - ecs_id_t *ids, ecs_id_t *id_out, ecs_table_record_t **tr_out) { @@ -18486,7 +19714,7 @@ int32_t flecs_type_search( int32_t r = tr->index; if (tr_out) tr_out[0] = tr; if (id_out) { - id_out[0] = ids[r]; + id_out[0] = table->type.array[r]; } return r; } @@ -18495,18 +19723,16 @@ int32_t flecs_type_search( } static -int32_t flecs_type_offset_search( +int32_t flecs_table_offset_search( + const ecs_table_t *table, int32_t offset, ecs_id_t id, - ecs_id_t *ids, - int32_t count, ecs_id_t *id_out) { - ecs_assert(ids != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(count > 0, ECS_INTERNAL_ERROR, NULL); - ecs_assert(offset > 0, ECS_INTERNAL_ERROR, NULL); ecs_assert(id != 0, ECS_INVALID_PARAMETER, NULL); + ecs_id_t *ids = table->type.array; + int32_t count = table->type.count; while (offset < count) { ecs_id_t type_id = ids[offset ++]; if (ecs_id_match(type_id, id)) { @@ -18546,8 +19772,94 @@ bool flecs_type_can_inherit_id( } static -int32_t flecs_type_search_relation( +int32_t flecs_table_search_relation_for_tgt( + const ecs_world_t *world, + ecs_entity_t tgt, + ecs_id_t id, + ecs_component_record_t *cr, + ecs_id_t rel, + ecs_component_record_t *cr_r, + ecs_entity_t *tgt_out, + ecs_id_t *id_out, + ecs_table_record_t **tr_out) +{ + ecs_record_t *r = flecs_entities_get_any(world, tgt); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_table_t *tgt_table = r->table; + ecs_assert(tgt_table != NULL, ECS_INTERNAL_ERROR, NULL); + + int32_t result = -1; + + if (cr->flags & EcsIdDontFragment) { + if (flecs_sparse_get(cr->sparse, 0, tgt) != NULL) { + result = -2; + goto found; + } + } else { + result = flecs_table_search_relation(world, r, tgt_table, 0, id, cr, + rel, cr_r, true, tgt_out, id_out, tr_out); + if (result != -1) { + goto found; + } + } + + return -1; +found: + if (tgt_out && !tgt_out[0]) { + tgt_out[0] = ecs_get_alive(world, tgt); + } + + return result; +} + +static +int32_t flecs_table_search_relation_pairs( + const ecs_world_t *world, + const ecs_table_t *table, + int32_t offset, + ecs_id_t id, + ecs_component_record_t *cr, + ecs_id_t rel, + ecs_component_record_t *cr_r, + ecs_entity_t *tgt_out, + ecs_id_t *id_out, + ecs_table_record_t **tr_out) +{ + bool exclusive = cr_r->flags & EcsIdExclusive; + + int32_t column; + ecs_id_t id_r; + if (offset) { + column = flecs_table_offset_search(table, offset, rel, &id_r); + } else { + column = flecs_table_search(table, cr_r, &id_r, 0); + } + + while (column != -1) { + ecs_entity_t tgt = ECS_PAIR_SECOND(id_r); + ecs_assert(tgt != 0, ECS_INTERNAL_ERROR, NULL); + + if (flecs_table_search_relation_for_tgt( + world, tgt, id, cr, rel, cr_r, tgt_out, id_out, tr_out) != -1) + { + return column; + } + + if (exclusive) { + break; + } + + column = flecs_table_offset_search(table, column + 1, rel, &id_r); + } + + return -1; +} + +static +int32_t flecs_table_search_relation( const ecs_world_t *world, + const ecs_record_t *record, const ecs_table_t *table, int32_t offset, ecs_id_t id, @@ -18555,23 +19867,20 @@ int32_t flecs_type_search_relation( ecs_id_t rel, ecs_component_record_t *cr_r, bool self, - ecs_entity_t *subject_out, + ecs_entity_t *tgt_out, ecs_id_t *id_out, ecs_table_record_t **tr_out) { - ecs_type_t type = table->type; - ecs_id_t *ids = type.array; - int32_t count = type.count; bool dont_fragment = cr->flags & EcsIdDontFragment; if (self && !dont_fragment) { if (offset) { - int32_t r = flecs_type_offset_search(offset, id, ids, count, id_out); + int32_t r = flecs_table_offset_search(table, offset, id, id_out); if (r != -1) { return r; } } else { - int32_t r = flecs_type_search(table, cr, ids, id_out, tr_out); + int32_t r = flecs_table_search(table, cr, id_out, tr_out); if (r != -1) { return r; } @@ -18579,78 +19888,85 @@ int32_t flecs_type_search_relation( } ecs_flags32_t flags = table->flags; - if ((flags & EcsTableHasPairs) && rel) { - bool is_a = rel == ecs_pair(EcsIsA, EcsWildcard); - if (is_a) { - if (!(flags & EcsTableHasIsA)) { - return -1; - } - cr_r = world->cr_isa_wildcard; - if (!flecs_type_can_inherit_id(world, table, cr, id)) { - return -1; - } - } + if (!(flags & EcsTableHasPairs) || !rel) { + return -1; + } - if (!cr_r) { - cr_r = flecs_components_get(world, rel); - if (!cr_r) { - return -1; + if (flags & EcsTableHasIsA) { + if (flecs_type_can_inherit_id(world, table, cr, id)) { + int32_t column = flecs_table_search_relation_pairs( + world, table, offset, id, cr, rel, world->cr_isa_wildcard, + tgt_out, id_out, tr_out); + if (column != -1) { + return column; } } + if (rel == ecs_isa(EcsWildcard)) { + return -1; + } + } - ecs_id_t id_r; - int32_t r, r_column; - if (offset) { - r_column = flecs_type_offset_search(offset, rel, ids, count, &id_r); - } else { - r_column = flecs_type_search(table, cr_r, ids, &id_r, 0); + if (rel == ecs_childof(EcsWildcard)) { + cr_r = world->cr_childof_wildcard; + + if (table->flags & EcsTableHasParent) { + /* Can't resolve parent on */ + ecs_assert(record != NULL, ECS_INVALID_PARAMETER, + "cannot traverse ChildOf on table with Parent component, " + "search on entity instead"); + + int32_t column = table->component_map[ecs_id(EcsParent)]; + ecs_assert(column > 0, ECS_INTERNAL_ERROR, NULL); + + const EcsParent *parents = table->data.columns[column - 1].data; + ecs_entity_t parent = + parents[ECS_RECORD_TO_ROW(record->row)].value; + + return flecs_table_search_relation_for_tgt(world, parent, id, cr, + rel, cr_r, tgt_out, id_out, tr_out); } - while (r_column != -1) { - ecs_entity_t obj = ECS_PAIR_SECOND(id_r); - ecs_assert(obj != 0, ECS_INTERNAL_ERROR, NULL); + } - ecs_record_t *rec = flecs_entities_get_any(world, obj); - ecs_assert(rec != NULL, ECS_INTERNAL_ERROR, NULL); + if (!cr_r) { + cr_r = flecs_components_get(world, rel); + if (!cr_r) { + return -1; + } + } - ecs_table_t *tgt_table = rec->table; - ecs_assert(tgt_table != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(tgt_table != table, ECS_CYCLE_DETECTED, NULL); + return flecs_table_search_relation_pairs(world, table, offset, id, cr, rel, + cr_r, tgt_out, id_out, tr_out); +} - if (dont_fragment) { - r = -1; - if (flecs_sparse_get(cr->sparse, 0, obj) != NULL) { - r = -2; - } - } else { - r = flecs_type_search_relation(world, tgt_table, 0, id, cr, - rel, cr_r, true, subject_out, id_out, tr_out); - } - if (r != -1) { - if (subject_out && !subject_out[0]) { - subject_out[0] = ecs_get_alive(world, obj); - } - return r_column; - } +int32_t ecs_search_relation_for_entity( + const ecs_world_t *world, + ecs_entity_t entity, + ecs_id_t id, + ecs_entity_t rel, + bool self, + ecs_component_record_t *cr, + ecs_entity_t *tgt_out, + ecs_id_t *id_out, + struct ecs_table_record_t **tr_out) +{ + ecs_record_t *r = flecs_entities_get(world, entity); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); - if (!is_a) { - r = flecs_type_search_relation(world, tgt_table, 0, id, cr, - ecs_pair(EcsIsA, EcsWildcard), world->cr_isa_wildcard, - true, subject_out, id_out, tr_out); - if (r != -1) { - if (subject_out && !subject_out[0]) { - subject_out[0] = ecs_get_alive(world, obj); - } - return r_column; - } - } + if (tgt_out) tgt_out[0] = 0; + if (!cr) { + cr = flecs_components_get(world, id); + } - r_column = flecs_type_offset_search( - r_column + 1, rel, ids, count, &id_r); + int32_t result = flecs_table_search_relation(world, r, r->table, 0, id, cr, + rel, NULL, self, tgt_out, id_out, tr_out); + if (result != -1) { + if (tgt_out && !tgt_out[0]) { + tgt_out[0] = entity; } } - return -1; + return result; } int32_t ecs_search_relation( @@ -18660,7 +19976,7 @@ int32_t ecs_search_relation( ecs_id_t id, ecs_entity_t rel, ecs_flags64_t flags, - ecs_entity_t *subject_out, + ecs_entity_t *tgt_out, ecs_id_t *id_out, struct ecs_table_record_t **tr_out) { @@ -18669,7 +19985,7 @@ int32_t ecs_search_relation( flags = flags ? flags : (EcsSelf|EcsUp); - if (subject_out) subject_out[0] = 0; + if (tgt_out) tgt_out[0] = 0; if (!(flags & EcsUp)) { return ecs_search_offset(world, table, offset, id, id_out); } @@ -18679,8 +19995,8 @@ int32_t ecs_search_relation( return -1; } - int32_t result = flecs_type_search_relation(world, table, offset, id, cr, - ecs_pair(rel, EcsWildcard), NULL, flags & EcsSelf, subject_out, + int32_t result = flecs_table_search_relation(world, NULL, table, offset, id, + cr, ecs_pair(rel, EcsWildcard), NULL, flags & EcsSelf, tgt_out, id_out, tr_out); return result; @@ -18700,9 +20016,7 @@ int32_t ecs_search( return -1; } - ecs_type_t type = table->type; - ecs_id_t *ids = type.array; - return flecs_type_search(table, cr, ids, id_out, 0); + return flecs_table_search(table, cr, id_out, 0); } int32_t ecs_search_offset( @@ -18717,10 +20031,7 @@ int32_t ecs_search_offset( return ecs_search(world, table, id, id_out); } - ecs_type_t type = table->type; - ecs_id_t *ids = type.array; - int32_t count = type.count; - return flecs_type_offset_search(offset, id, ids, count, id_out); + return flecs_table_offset_search(table, offset, id, id_out); } static @@ -18769,7 +20080,41 @@ int32_t flecs_relation_depth( ecs_entity_t r, const ecs_table_t *table) { - ecs_component_record_t *cr = flecs_components_get(world, ecs_pair(r, EcsWildcard)); + if (r == EcsChildOf) { + if (table->flags & EcsTableHasChildOf) { + ecs_component_record_t *cr_wc = world->cr_childof_wildcard; + const ecs_table_record_t *tr_wc = + flecs_component_get_table(cr_wc, table); + ecs_assert(tr_wc != NULL, ECS_INTERNAL_ERROR, NULL); + const ecs_table_record_t *tr = &table->_->records[tr_wc->index]; + ecs_component_record_t *cr = tr->hdr.cr; + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr->pair != NULL, ECS_INTERNAL_ERROR, NULL); + return cr->pair->depth; + } else if (table->flags & EcsTableHasParent) { + ecs_component_record_t *cr_wc = flecs_components_get( + world, ecs_pair(EcsParentDepth, EcsWildcard)); + if (!cr_wc) { + return 0; + } + + const ecs_table_record_t *tr_wc = flecs_component_get_table( + cr_wc, table); + if (!tr_wc) { + return 0; + } + + ecs_id_t depth_pair = table->type.array[tr_wc->index]; + ecs_assert(ECS_PAIR_FIRST(depth_pair) == EcsParentDepth, + ECS_INTERNAL_ERROR, NULL); + return flecs_uto(int32_t, ECS_PAIR_SECOND(depth_pair)); + } else { + return 0; + } + } + + ecs_component_record_t *cr = flecs_components_get( + world, ecs_pair(r, EcsWildcard)); if (!cr) { return 0; } @@ -19266,12 +20611,369 @@ bool ecs_is_defer_suspended( return false; } +/** + * @file tree_spawner.c + * @brief Data structure used to speed up the creation of hierarchies. + */ + + +static +void flecs_tree_spawner_release_tables( + ecs_vec_t *v) +{ + int32_t i, count = ecs_vec_count(v); + ecs_tree_spawner_child_t *elems = ecs_vec_first(v); + for (i = 0; i < count; i ++) { + ecs_tree_spawner_child_t *elem = &elems[i]; + flecs_table_release(elem->table); + } +} + +static +void EcsTreeSpawner_free(EcsTreeSpawner *ptr) { + int32_t i; + for (i = 0; i < FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE; i ++) { + flecs_tree_spawner_release_tables(&ptr->data[i].children); + ecs_vec_fini_t(NULL, &ptr->data[i].children, ecs_tree_spawner_child_t); + } +} + +static ECS_COPY(EcsTreeSpawner, dst, src, { + (void)dst; + (void)src; + ecs_abort(ECS_INVALID_OPERATION, "TreeSpawner component cannot be copied"); +}) + +static ECS_MOVE(EcsTreeSpawner, dst, src, { + EcsTreeSpawner_free(dst); + *dst = *src; + ecs_os_zeromem(src); +}) + +static ECS_DTOR(EcsTreeSpawner, ptr, { + EcsTreeSpawner_free(ptr); +}) + +static +ecs_type_t flecs_prefab_spawner_build_type( + ecs_world_t *world, + ecs_entity_t child, + ecs_table_t *table, + int32_t depth) +{ + ecs_type_t dst = {0}; + ecs_type_t *src = &table->type; + + flecs_type_add(world, &dst, ecs_id(EcsParent)); + + int32_t i, count = src->count; + for (i = 0; i < count; i ++) { + ecs_id_t id = src->array[i]; + ecs_table_record_t *tr = &table->_->records[i]; + ecs_component_record_t *cr = tr->hdr.cr; + + if (cr->flags & + (EcsIdOnInstantiateDontInherit|EcsIdOnInstantiateInherit)) + { + continue; + } + + if (id & ECS_AUTO_OVERRIDE) { + /* If AUTO_OVERRIDE flag is set, add component to instances. This + * allows instances to end up with an owned component, even if the + * component has the (OnInstantiate, Inherit) trait. + * Additionally, this also allows for adding components to instances + * that aren't copyable, since a prefab can have a component with + * AUTO_OVERRIDE flag, but not have the actual component (which then + * isn't copied). */ + flecs_type_add(world, &dst, id & ~ECS_AUTO_OVERRIDE); + continue; + } + + ecs_entity_t rel = ECS_PAIR_FIRST(id); + if (rel == EcsIsA) { + /* If prefab child has IsA relationships, they will be inherited + * through the (IsA, prefab_child) relationship (added below). */ + continue; + } + + if (rel == EcsParentDepth) { + /* Replace depth value with the normalized depth for spawner. */ + id = ecs_value_pair(EcsParentDepth, depth); + } + + flecs_type_add(world, &dst, id); + } + + flecs_type_add(world, &dst, ecs_isa(child)); + + return dst; +} + +static +void flecs_prefab_spawner_build_from_cr( + ecs_world_t *world, + ecs_component_record_t *cr, + ecs_vec_t *spawner, + int32_t parent_index, + int32_t depth) +{ + ecs_vec_t *children_vec = &cr->pair->ordered_children; + int32_t i, count = ecs_vec_count(children_vec); + ecs_entity_t *children = ecs_vec_first(children_vec); + for (i = 0; i < count; i ++) { + ecs_entity_t child = children[i]; + ecs_record_t *r = flecs_entities_get(world, child); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_table_t *table = r->table; + ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + + if (!(table->flags & EcsTableHasParent)) { + continue; + } + + ecs_tree_spawner_child_t *elem = ecs_vec_append_t( + NULL, spawner, ecs_tree_spawner_child_t); + elem->parent_index = parent_index; + elem->child_name = NULL; + elem->child = (uint32_t)child; + + if (table->flags & EcsTableHasName) { + elem->child_name = ecs_get_name(world, child); + } + + ecs_type_t type = flecs_prefab_spawner_build_type( + world, child, table, depth); + elem->table = flecs_table_find_or_create(world, &type); + ecs_assert(elem->table != NULL, ECS_INTERNAL_ERROR, NULL); + flecs_type_free(world, &type); + + /* Make sure table doesn't get freed by shrink() */ + flecs_table_keep(elem->table); + + if (!(r->row & EcsEntityIsTraversable)) { + continue; + } + + ecs_component_record_t *child_cr = flecs_components_get( + world, ecs_childof(child)); + if (!child_cr) { + continue; + } + + flecs_prefab_spawner_build_from_cr( + world, child_cr, spawner, ecs_vec_count(spawner), depth + 1); + } +} + +static +void flecs_spawner_transpose_depth( + ecs_world_t *world, + EcsTreeSpawner *spawner, + ecs_vec_t *dst, + int32_t depth) +{ + ecs_vec_t *src = &spawner->data[0].children; + + int32_t i, count = ecs_vec_count(src); + ecs_vec_set_count_t(NULL, dst, ecs_tree_spawner_child_t, count); + + for (i = 0; i < count; i ++) { + ecs_tree_spawner_child_t *src_elem = ecs_vec_get_t( + src, ecs_tree_spawner_child_t, i); + ecs_tree_spawner_child_t *dst_elem = ecs_vec_get_t( + dst, ecs_tree_spawner_child_t, i); + + dst_elem->child_name = src_elem->child_name; + dst_elem->parent_index = src_elem->parent_index; + dst_elem->child = src_elem->child; + + /* Get depth for source element at depth 0 */ + int32_t src_depth = flecs_relation_depth( + world, EcsChildOf, src_elem->table); + + /* Get table for correct depth */ + ecs_id_t depth_pair = ecs_value_pair(EcsParentDepth, src_depth + depth); + ecs_table_diff_t diff = ECS_TABLE_DIFF_INIT; + + dst_elem->table = flecs_table_traverse_add( + world, src_elem->table, &depth_pair, &diff); + + flecs_table_keep(dst_elem->table); + } +} + +EcsTreeSpawner* flecs_prefab_spawner_build( + ecs_world_t *world, + ecs_entity_t base) +{ + ecs_component_record_t *cr = flecs_components_get(world, ecs_childof(base)); + if (!cr) { + return NULL; + } + + ecs_vec_t spawner; + ecs_vec_init_t(NULL, &spawner, ecs_tree_spawner_child_t, 0); + flecs_prefab_spawner_build_from_cr(world, cr, &spawner, 0, 1); + + base = flecs_entities_get_alive(world, base); + EcsTreeSpawner *ts = ecs_ensure(world, base, EcsTreeSpawner); + ts->data[0].children = spawner; + + /* Initialize remaining vectors */ + int32_t i; + for (i = 1; i < FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE; i ++) { + ecs_vec_init_t( + NULL, &ts->data[i].children, ecs_tree_spawner_child_t, 0); + } + + return ts; +} + +void flecs_spawner_instantiate( + ecs_world_t *world, + EcsTreeSpawner *spawner, + ecs_entity_t instance) +{ + ecs_record_t *r_instance = flecs_entities_get(world, instance); + int32_t depth = flecs_relation_depth(world, EcsChildOf, r_instance->table); + int32_t i, child_count = ecs_vec_count(&spawner->data[0].children); + + bool is_prefab = r_instance->table->flags & EcsTableIsPrefab; + + /* Use cached spawner for depth if available. */ + ecs_vec_t *vec, tmp_vec; + if (depth < FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE) { + vec = &spawner->data[depth].children; + } else { + vec = &tmp_vec; + ecs_vec_init_t(NULL, vec, ecs_tree_spawner_child_t, 0); + } + + if (depth && ecs_vec_count(vec) != child_count) { + /* Vector for depth is not yet initialized, create it. */ + flecs_spawner_transpose_depth(world, spawner, vec, depth); + } + + ecs_tree_spawner_child_t *spawn_children = ecs_vec_first(vec); + ecs_vec_set_min_count_t(&world->allocator, &world->allocators.tree_spawner, + ecs_entity_t, child_count + 1); + ecs_entity_t *parents = ecs_vec_first(&world->allocators.tree_spawner); + parents[0] = instance; + + ecs_component_record_t *cr = NULL; + ecs_entity_t old_parent = 0; + + ecs_assert(ecs_vec_count(vec) == child_count, ECS_INTERNAL_ERROR, NULL); + + for (i = 0; i < child_count; i ++) { + ecs_entity_t entity = parents[i + 1] = flecs_new_id(world); + ecs_tree_spawner_child_t *spawn_child = &spawn_children[i]; + ecs_table_t *table = spawn_child->table; + ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + + if (is_prefab) { + ecs_table_diff_t diff = ECS_TABLE_DIFF_INIT; + ecs_id_t id = EcsPrefab; + table = flecs_table_traverse_add(world, table, &id, &diff); + + if (spawn_child->child_name) { + id = ecs_pair_t(EcsIdentifier, EcsName); + table = flecs_table_traverse_add(world, table, &id, &diff); + } + } + + ecs_record_t *r = flecs_entities_get(world, entity); + ecs_flags32_t flags = table->flags & EcsTableAddEdgeFlags; + + ecs_table_diff_t table_diff = { + .added = table->type, + .added_flags = flags + }; + + ecs_entity_t parent = parents[spawn_child->parent_index]; + ecs_assert(parent != 0, ECS_INTERNAL_ERROR, NULL); + if (parent != old_parent) { + cr = flecs_components_ensure(world, ecs_childof(parent)); + old_parent = parent; + } + + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + + int32_t row = ecs_table_count(table); + r->table = table; + r->row = (uint32_t)row; + flecs_table_append(world, table, entity, true, true); + + int32_t parent_column = table->component_map[ecs_id(EcsParent)]; + ecs_assert(parent_column != 0, ECS_INTERNAL_ERROR, NULL); + EcsParent *parent_ptr = table->data.columns[parent_column - 1].data; + parent_ptr = &parent_ptr[row]; + parent_ptr->value = parent; + + flecs_actions_new(world, table, row, 1, &table_diff, 0, false, true); + + if (is_prefab && spawn_child->child_name) { + ecs_set_name(world, entity, spawn_child->child_name); + } + + flecs_add_non_fragmenting_child_w_records(world, parent, entity, cr, r); + + ecs_entity_t base_child = spawn_child->child; + ecs_record_t *spawn_r = flecs_entities_get_any( + world, spawn_child->child); + ecs_assert(spawn_r != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_table_range_t base_range = { + .table = spawn_r->table, + .offset = 0, + .count = 1 }; + flecs_instantiate_sparse(world, &base_range, &base_child, + r->table, &entity, ECS_RECORD_TO_ROW(r->row)); + + if (spawn_r->row & EcsEntityHasDontFragment) { + flecs_instantiate_dont_fragment( + world, spawn_child->child, entity); + } + } + + if (vec == &tmp_vec) { + ecs_vec_fini_t(NULL, vec, ecs_tree_spawner_child_t); + } +} + +void flecs_bootstrap_spawner( + ecs_world_t *world) +{ + flecs_type_info_init(world, EcsTreeSpawner, { + .ctor = flecs_default_ctor, + .copy = ecs_copy(EcsTreeSpawner), + .move = ecs_move(EcsTreeSpawner), + .dtor = ecs_dtor(EcsTreeSpawner) + }); + + ecs_add_pair(world, ecs_id(EcsTreeSpawner), + EcsOnInstantiate, EcsDontInherit); +} + /** * @file type_info.c * @brief Component metadata and lifecycle hooks. */ +#ifdef FLECS_DEBUG +static +void flecs_type_info_mark_in_use( + const ecs_type_info_t *ti) +{ + ecs_type_info_t *ti_mut = ECS_CONST_CAST(ecs_type_info_t*, ti); + ti_mut->hooks.flags |= ECS_TYPE_HOOK_IN_USE; +} +#else +#define flecs_type_info_mark_in_use(ti) ((void)ti) +#endif + void flecs_default_ctor( void *ptr, int32_t count, @@ -19280,6 +20982,166 @@ void flecs_default_ctor( ecs_os_memset(ptr, 0, ti->size * count); } +bool flecs_type_info_ctor( + void *ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_CTOR_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_xtor_t ctor = ti->hooks.ctor; + if (ctor) { + ctor(ptr, count, ti); + return true; + } + return false; +} + +bool flecs_type_info_dtor( + void *ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_DTOR_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_xtor_t dtor = ti->hooks.dtor; + if (dtor) { + dtor(ptr, count, ti); + return true; + } + return false; +} + +void flecs_type_info_copy( + void *dst_ptr, + const void *src_ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_COPY_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_copy_t copy = ti->hooks.copy; + if (copy) { + copy(dst_ptr, src_ptr, count, ti); + } else { + ecs_os_memcpy(dst_ptr, src_ptr, flecs_uto(ecs_size_t, ti->size) * count); + } +} + +void flecs_type_info_move( + void *dst_ptr, + void *src_ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_MOVE_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_move_t move = ti->hooks.move; + if (move) { + move(dst_ptr, src_ptr, count, ti); + } else { + ecs_os_memcpy(dst_ptr, src_ptr, flecs_uto(ecs_size_t, ti->size) * count); + } +} + +void flecs_type_info_copy_ctor( + void *dst_ptr, + const void *src_ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_COPY_CTOR_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_copy_t copy = ti->hooks.copy_ctor; + if (copy) { + copy(dst_ptr, src_ptr, count, ti); + } else { + ecs_os_memcpy(dst_ptr, src_ptr, flecs_uto(ecs_size_t, ti->size) * count); + } +} + +void flecs_type_info_move_ctor( + void *dst_ptr, + void *src_ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_MOVE_CTOR_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_move_t move = ti->hooks.move_ctor; + if (move) { + move(dst_ptr, src_ptr, count, ti); + } else { + ecs_os_memcpy(dst_ptr, src_ptr, flecs_uto(ecs_size_t, ti->size) * count); + } +} + +void flecs_type_info_ctor_move_dtor( + void *dst_ptr, + void *src_ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_CTOR_MOVE_DTOR_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_move_t move = ti->hooks.ctor_move_dtor; + if (move) { + move(dst_ptr, src_ptr, count, ti); + } else { + ecs_os_memcpy(dst_ptr, src_ptr, flecs_uto(ecs_size_t, ti->size) * count); + } +} + +void flecs_type_info_move_dtor( + void *dst_ptr, + void *src_ptr, + int32_t count, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_MOVE_DTOR_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_move_t move = ti->hooks.move_dtor; + if (move) { + move(dst_ptr, src_ptr, count, ti); + } else { + ecs_os_memcpy(dst_ptr, src_ptr, flecs_uto(ecs_size_t, ti->size) * count); + } +} + +int flecs_type_info_cmp( + const void *a_ptr, + const void *b_ptr, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_CMP_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_cmp_t cmp = ti->hooks.cmp; + ecs_assert(cmp != NULL, ECS_INTERNAL_ERROR, NULL); + return cmp(a_ptr, b_ptr, ti); +} + +bool flecs_type_info_equals( + const void *a_ptr, + const void *b_ptr, + const ecs_type_info_t *ti) +{ + ecs_assert(!(ti->hooks.flags & ECS_TYPE_HOOK_EQUALS_ILLEGAL), + ECS_INVALID_OPERATION, "%s", ti->name); + flecs_type_info_mark_in_use(ti); + ecs_equals_t equals = ti->hooks.equals; + ecs_assert(equals != NULL, ECS_INTERNAL_ERROR, NULL); + return equals(a_ptr, b_ptr, ti); +} + static void flecs_default_copy_ctor(void *dst_ptr, const void *src_ptr, int32_t count, const ecs_type_info_t *ti) @@ -19845,7 +21707,7 @@ bool flecs_type_info_init_id( /* All id records with component as relationship inherit type info */ cr = flecs_components_get(world, ecs_pair(component, EcsWildcard)); if (cr) { - do { + while ((cr = flecs_component_first_next(cr))) { if (is_tag) { changed |= flecs_component_set_type_info(world, cr, NULL); } else if (ti) { @@ -19855,24 +21717,20 @@ bool flecs_type_info_init_id( { changed |= flecs_component_set_type_info(world, cr, NULL); } - } while ((cr = flecs_component_first_next(cr))); + } } /* All non-tag id records with component as object inherit type info, * if relationship doesn't have type info */ cr = flecs_components_get(world, ecs_pair(EcsWildcard, component)); if (cr) { - do { + while ((cr = flecs_component_second_next(cr))) { if (!(cr->flags & EcsIdPairIsTag) && !cr->type_info) { changed |= flecs_component_set_type_info(world, cr, ti); } - } while ((cr = flecs_component_first_next(cr))); + } } - /* Type info of (*, component) should always point to component */ - // ecs_assert(flecs_components_get(world, ecs_pair(EcsWildcard, component))-> - // type_info == ti, ECS_INTERNAL_ERROR, NULL); - return changed; } @@ -19898,6 +21756,15 @@ void flecs_type_info_free( } } +ecs_size_t flecs_type_size( + ecs_world_t *world, + ecs_entity_t type) +{ + const EcsComponent *comp = ecs_get(world, type, EcsComponent); + ecs_assert(comp != NULL, ECS_INTERNAL_ERROR, NULL); + return comp->size; +} + const ecs_type_hooks_t* ecs_get_hooks_id( const ecs_world_t *world, ecs_entity_t id) @@ -19918,21 +21785,24 @@ const ecs_type_info_t* flecs_determine_type_info_for_component( return flecs_type_info_get(world, id); } } else { - ecs_entity_t rel = ecs_pair_first(world, id); - if (rel) { - if (ecs_has_id(world, rel, EcsPairIsTag)) { - return NULL; - } + ecs_entity_t rel = ECS_PAIR_FIRST(id); + rel = flecs_entities_get_alive(world, rel); + ecs_assert(ecs_is_alive(world, rel), ECS_INTERNAL_ERROR, NULL); - const ecs_type_info_t *ti = flecs_type_info_get(world, rel); - if (ti) { - return ti; - } + if (ecs_owns_id(world, rel, EcsPairIsTag)) { + return NULL; } - ecs_entity_t tgt = ecs_pair_second(world, id); - if (tgt) { - return flecs_type_info_get(world, tgt); + const ecs_type_info_t *ti = flecs_type_info_get(world, rel); + if (ti) { + return ti; + } + + if (!ECS_IS_VALUE_PAIR(id)) { + ecs_entity_t tgt = ecs_pair_second(world, id); + if (tgt) { + return flecs_type_info_get(world, tgt); + } } } @@ -19973,10 +21843,7 @@ int ecs_value_init_w_type_info( ecs_check(ti != NULL, ECS_INVALID_PARAMETER, NULL); (void)world; - ecs_xtor_t ctor; - if ((ctor = ti->hooks.ctor)) { - ctor(ptr, 1, ti); - } else { + if (!flecs_type_info_ctor(ptr, 1, ti)) { ecs_os_memset(ptr, 0, ti->size); } @@ -20041,10 +21908,7 @@ int ecs_value_fini_w_type_info( ecs_check(ti != NULL, ECS_INVALID_PARAMETER, NULL); (void)world; - ecs_xtor_t dtor; - if ((dtor = ti->hooks.dtor)) { - dtor(ptr, 1, ti); - } + flecs_type_info_dtor(ptr, 1, ti); return 0; error: @@ -20094,12 +21958,7 @@ int ecs_value_copy_w_type_info( ecs_check(ti != NULL, ECS_INVALID_PARAMETER, NULL); (void)world; - ecs_copy_t copy; - if ((copy = ti->hooks.copy)) { - copy(dst, src, 1, ti); - } else { - ecs_os_memcpy(dst, src, ti->size); - } + flecs_type_info_copy(dst, src, 1, ti); return 0; error: @@ -20130,12 +21989,7 @@ int ecs_value_move_w_type_info( ecs_check(ti != NULL, ECS_INVALID_PARAMETER, NULL); (void)world; - ecs_move_t move; - if ((move = ti->hooks.move)) { - move(dst, src, 1, ti); - } else { - ecs_os_memcpy(dst, src, ti->size); - } + flecs_type_info_move(dst, src, 1, ti); return 0; error: @@ -20166,12 +22020,7 @@ int ecs_value_move_ctor_w_type_info( ecs_check(ti != NULL, ECS_INVALID_PARAMETER, NULL); (void)world; - ecs_move_t move; - if ((move = ti->hooks.move_ctor)) { - move(dst, src, 1, ti); - } else { - ecs_os_memcpy(dst, src, ti->size); - } + flecs_type_info_move_ctor(dst, src, 1, ti); return 0; error: @@ -20203,11 +22052,15 @@ int ecs_value_move_ctor( const ecs_id_t ECS_PAIR = (1ull << 63); const ecs_id_t ECS_AUTO_OVERRIDE = (1ull << 62); const ecs_id_t ECS_TOGGLE = (1ull << 61); +const ecs_id_t ECS_VALUE_PAIR = ((1ull << 60) | (1ull << 63)); /** Builtin component ids */ const ecs_entity_t ecs_id(EcsComponent) = 1; const ecs_entity_t ecs_id(EcsIdentifier) = 2; const ecs_entity_t ecs_id(EcsPoly) = 3; +const ecs_entity_t ecs_id(EcsParent) = 4; +const ecs_entity_t ecs_id(EcsTreeSpawner) = 5; +const ecs_entity_t EcsParentDepth = 6; /* Poly target components */ const ecs_entity_t EcsQuery = FLECS_HI_COMPONENT_ID + 0; @@ -20218,9 +22071,7 @@ const ecs_entity_t EcsSystem = FLECS_HI_COMPONENT_ID + 2; const ecs_entity_t EcsWorld = FLECS_HI_COMPONENT_ID + 3; const ecs_entity_t EcsFlecs = FLECS_HI_COMPONENT_ID + 4; const ecs_entity_t EcsFlecsCore = FLECS_HI_COMPONENT_ID + 5; -const ecs_entity_t EcsFlecsInternals = FLECS_HI_COMPONENT_ID + 6; const ecs_entity_t EcsModule = FLECS_HI_COMPONENT_ID + 7; -const ecs_entity_t EcsPrivate = FLECS_HI_COMPONENT_ID + 8; const ecs_entity_t EcsPrefab = FLECS_HI_COMPONENT_ID + 9; const ecs_entity_t EcsDisabled = FLECS_HI_COMPONENT_ID + 10; const ecs_entity_t EcsNotQueryable = FLECS_HI_COMPONENT_ID + 11; @@ -20257,7 +22108,6 @@ const ecs_entity_t EcsTrait = FLECS_HI_COMPONENT_ID + 35; const ecs_entity_t EcsRelationship = FLECS_HI_COMPONENT_ID + 36; const ecs_entity_t EcsTarget = FLECS_HI_COMPONENT_ID + 37; - /* Builtin relationships */ const ecs_entity_t EcsChildOf = FLECS_HI_COMPONENT_ID + 38; const ecs_entity_t EcsIsA = FLECS_HI_COMPONENT_ID + 39; @@ -20341,18 +22191,19 @@ const ecs_entity_t ecs_id(ecs_entity_t) = FLECS_HI_COMPONENT_ID + 97; const ecs_entity_t ecs_id(ecs_id_t) = FLECS_HI_COMPONENT_ID + 98; /** Meta module component ids */ -const ecs_entity_t ecs_id(EcsType) = FLECS_HI_COMPONENT_ID + 99; -const ecs_entity_t ecs_id(EcsTypeSerializer) = FLECS_HI_COMPONENT_ID + 100; -const ecs_entity_t ecs_id(EcsPrimitive) = FLECS_HI_COMPONENT_ID + 101; -const ecs_entity_t ecs_id(EcsEnum) = FLECS_HI_COMPONENT_ID + 102; -const ecs_entity_t ecs_id(EcsBitmask) = FLECS_HI_COMPONENT_ID + 103; -const ecs_entity_t ecs_id(EcsConstants) = FLECS_HI_COMPONENT_ID + 104; -const ecs_entity_t ecs_id(EcsMember) = FLECS_HI_COMPONENT_ID + 105; -const ecs_entity_t ecs_id(EcsMemberRanges) = FLECS_HI_COMPONENT_ID + 106; -const ecs_entity_t ecs_id(EcsStruct) = FLECS_HI_COMPONENT_ID + 107; -const ecs_entity_t ecs_id(EcsArray) = FLECS_HI_COMPONENT_ID + 108; -const ecs_entity_t ecs_id(EcsVector) = FLECS_HI_COMPONENT_ID + 109; -const ecs_entity_t ecs_id(EcsOpaque) = FLECS_HI_COMPONENT_ID + 110; +const ecs_entity_t ecs_id(EcsPrimitive) = FLECS_HI_COMPONENT_ID + 99; +const ecs_entity_t ecs_id(EcsEnum) = FLECS_HI_COMPONENT_ID + 100; +const ecs_entity_t ecs_id(EcsBitmask) = FLECS_HI_COMPONENT_ID + 101; +const ecs_entity_t ecs_id(EcsConstants) = FLECS_HI_COMPONENT_ID + 102; +const ecs_entity_t ecs_id(EcsMember) = FLECS_HI_COMPONENT_ID + 103; +const ecs_entity_t ecs_id(EcsMemberRanges) = FLECS_HI_COMPONENT_ID + 104; +const ecs_entity_t ecs_id(EcsStruct) = FLECS_HI_COMPONENT_ID + 105; +const ecs_entity_t ecs_id(EcsArray) = FLECS_HI_COMPONENT_ID + 106; +const ecs_entity_t ecs_id(EcsVector) = FLECS_HI_COMPONENT_ID + 107; +const ecs_entity_t ecs_id(EcsOpaque) = FLECS_HI_COMPONENT_ID + 108; +const ecs_entity_t ecs_id(EcsTypeSerializer) = FLECS_HI_COMPONENT_ID + 109; +const ecs_entity_t ecs_id(EcsType) = FLECS_HI_COMPONENT_ID + 110; + const ecs_entity_t ecs_id(EcsUnit) = FLECS_HI_COMPONENT_ID + 111; const ecs_entity_t ecs_id(EcsUnitPrefix) = FLECS_HI_COMPONENT_ID + 112; const ecs_entity_t EcsQuantity = FLECS_HI_COMPONENT_ID + 113; @@ -20900,6 +22751,8 @@ void flecs_world_allocators_init( flecs_ballocator_init_t(&a->table_diff, ecs_table_diff_t); flecs_ballocator_init_n(&a->sparse_chunk, int32_t, FLECS_SPARSE_PAGE_SIZE); flecs_table_diff_builder_init(world, &world->allocators.diff_builder); + ecs_vec_init_t(&world->allocator, + &world->allocators.tree_spawner, ecs_entity_t, 0); } static @@ -20915,6 +22768,8 @@ void flecs_world_allocators_fini( flecs_ballocator_fini(&a->table_diff); flecs_ballocator_fini(&a->sparse_chunk); flecs_table_diff_builder_fini(world, &world->allocators.diff_builder); + ecs_vec_fini_t( + &world->allocator, &world->allocators.tree_spawner, ecs_entity_t); flecs_allocator_fini(&world->allocator); } @@ -21124,7 +22979,7 @@ void flecs_log_build_info(void) { const char **addon = bi->addons; do { - ecs_trace(addon[0]); + ecs_trace("%s", addon[0]); } while ((++ addon)[0]); ecs_log_pop(); @@ -21163,6 +23018,8 @@ ecs_world_t *ecs_mini(void) { ecs_assert(ECS_ALIGNOF(ecs_query_triv_cache_match_t) == ECS_ALIGNOF(ecs_query_cache_match_t), ECS_INTERNAL_ERROR, NULL); + ecs_assert(EcsQueryNothing < 256, ECS_INTERNAL_ERROR, NULL); + ecs_trace("#[bold]bootstrapping world"); ecs_log_push(); @@ -21217,6 +23074,8 @@ ecs_world_t *ecs_mini(void) { ecs_os_get_time(&world->world_start_time); } + ecs_map_init(&world->prefab_child_indices, a); + ecs_set_stage_count(world, 1); ecs_default_lookup_path[0] = EcsFlecsCore; ecs_set_lookup_path(world, ecs_default_lookup_path); @@ -21506,6 +23365,7 @@ int ecs_fini( ecs_dbg_1("#[bold]cleanup world data structures"); ecs_log_push_1(); + flecs_observable_fini(&world->observable); flecs_entities_fini(world); flecs_components_fini(world); flecs_fini_type_info(world); @@ -21513,10 +23373,10 @@ int ecs_fini( ecs_map_fini(&world->locked_components); ecs_map_fini(&world->locked_entities); #endif - flecs_observable_fini(&world->observable); flecs_name_index_fini(&world->aliases); flecs_name_index_fini(&world->symbols); ecs_set_stage_count(world, 0); + ecs_map_fini(&world->prefab_child_indices); ecs_vec_fini_t(&world->allocator, &world->component_ids, ecs_id_t); ecs_log_pop_1(); @@ -21703,29 +23563,6 @@ uint32_t flecs_get_table_version_fast( return world->table_version[table_id & ECS_TABLE_VERSION_ARRAY_BITMASK]; } -void flecs_increment_table_column_version( - ecs_world_t *world, - ecs_table_t *table) -{ - flecs_poly_assert(world, ecs_world_t); - ecs_assert(table != NULL, ECS_INVALID_PARAMETER, NULL); - - int32_t index = table->id & ECS_TABLE_VERSION_ARRAY_BITMASK; - world->table_column_version[index] ++; - if (world->table_column_version[index] == UINT32_MAX) { - /* Skip sentinel value */ - world->table_column_version[index] = 0; - } -} - -uint32_t flecs_get_table_column_version( - const ecs_world_t *world, - const uint64_t table_id) -{ - flecs_poly_assert(world, ecs_world_t); - return world->table_column_version[table_id & ECS_TABLE_VERSION_ARRAY_BITMASK]; -} - static int32_t flecs_component_ids_last_index = 0; int32_t flecs_component_ids_index_get(void) { @@ -21923,6 +23760,10 @@ int32_t ecs_delete_empty_tables( ecs_table_t *table = flecs_sparse_get_dense_t(&world->store.tables, ecs_table_t, i); + if (table->keep) { + continue; + } + measure_budget_after --; if (time_budget && !measure_budget_after) { @@ -21983,6 +23824,8 @@ bool flecs_component_record_in_use( { if (cr->flags & EcsIdDontFragment) { return flecs_sparse_count(cr->sparse) != 0; + } else if (cr->flags & EcsIdOrderedChildren) { + return ecs_vec_count(&cr->pair->ordered_children) != 0; } else { return cr->cache.tables.count != 0; } @@ -22003,7 +23846,7 @@ void ecs_shrink( ecs_table_t *table = flecs_sparse_get_dense_t(tables, ecs_table_t, i); if (ecs_table_count(table)) { flecs_table_shrink(world, table); - } else { + } else if (!table->keep) { flecs_table_fini(world, table); } } @@ -22930,9 +24773,6 @@ void FlecsAlertsImport(ecs_world_t *world) { ECS_IMPORT(world, FlecsPipeline); ECS_IMPORT(world, FlecsTimer); ECS_IMPORT(world, FlecsMetrics); -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); -#endif ecs_set_name_prefix(world, "Ecs"); ECS_COMPONENT_DEFINE(world, EcsAlert); @@ -22950,7 +24790,6 @@ void FlecsAlertsImport(ecs_world_t *world) { ecs_add_id(world, ecs_id(EcsAlert), EcsPairIsTag); ecs_add_id(world, ecs_id(EcsAlert), EcsExclusive); - ecs_add_id(world, ecs_id(EcsAlertsActive), EcsPrivate); ecs_struct(world, { .entity = ecs_id(EcsAlertInstance), @@ -23066,7 +24905,7 @@ static ecs_app_frame_action_t frame_action = flecs_default_frame_action; static ecs_app_desc_t ecs_app_desc; /* Serve REST API from wasm image when running in emscripten */ -#ifdef ECS_TARGET_EM +#if defined(ECS_TARGET_EM) && defined(FLECS_REST) #include ecs_http_server_t *flecs_wasm_rest_server = NULL; @@ -23337,93 +25176,6 @@ const char* ecs_doc_get_color( } } -/* Doc definitions for core components */ -static -void flecs_doc_import_core_definitions( - ecs_world_t *world) -{ - ecs_doc_set_brief(world, EcsFlecs, "Flecs root module"); - ecs_doc_set_link(world, EcsFlecs, "https://github.com/SanderMertens/flecs"); - ecs_doc_set_brief(world, EcsFlecsCore, "Module with builtin components"); - ecs_doc_set_brief(world, EcsFlecsInternals, "Module with internal entities"); - - ecs_doc_set_brief(world, EcsWorld, "Entity associated with world"); - - ecs_doc_set_brief(world, ecs_id(EcsComponent), "Component that is added to components"); - ecs_doc_set_brief(world, EcsModule, "Tag that is added to modules"); - ecs_doc_set_brief(world, EcsPrefab, "Tag that is added to prefabs"); - ecs_doc_set_brief(world, EcsDisabled, "Tag that is added to disabled entities"); - ecs_doc_set_brief(world, EcsPrivate, "Tag that is added to private components"); - ecs_doc_set_brief(world, EcsFlag, "Internal tag for tracking ids with special id flags"); - ecs_doc_set_brief(world, ecs_id(EcsPoly), "Internal component that stores pointer to poly objects"); - - ecs_doc_set_brief(world, ecs_id(EcsIdentifier), "Component used for entity names"); - ecs_doc_set_brief(world, EcsName, "Tag used with EcsIdentifier to store entity name"); - ecs_doc_set_brief(world, EcsSymbol, "Tag used with EcsIdentifier to store entity symbol"); - ecs_doc_set_brief(world, EcsAlias, "Tag used with EcsIdentifier to store entity alias"); - - ecs_doc_set_brief(world, EcsQuery, "Tag added to query entities"); - ecs_doc_set_brief(world, EcsObserver, "Tag added to observer entities"); - - ecs_doc_set_brief(world, EcsTransitive, "Trait that enables transitive evaluation of relationships"); - ecs_doc_set_brief(world, EcsReflexive, "Trait that enables reflexive evaluation of relationships"); - ecs_doc_set_brief(world, EcsFinal, "Trait that indicates an entity cannot be inherited from"); - ecs_doc_set_brief(world, EcsDontInherit, "Trait that indicates it should not be inherited"); - ecs_doc_set_brief(world, EcsPairIsTag, "Trait that ensures a pair cannot contain a value"); - ecs_doc_set_brief(world, EcsAcyclic, "Trait that indicates a relationship is acyclic"); - ecs_doc_set_brief(world, EcsTraversable, "Trait that indicates a relationship is traversable"); - ecs_doc_set_brief(world, EcsExclusive, "Trait that ensures a relationship can only have one target"); - ecs_doc_set_brief(world, EcsSymmetric, "Trait that causes a relationship to be two-way"); - ecs_doc_set_brief(world, EcsWith, "Trait for adding additional components when a component is added"); - ecs_doc_set_brief(world, EcsOneOf, "Trait that enforces target of relationship is a child of "); - ecs_doc_set_brief(world, EcsOnDelete, "Cleanup trait for specifying what happens when component is deleted"); - ecs_doc_set_brief(world, EcsOnDeleteTarget, "Cleanup trait for specifying what happens when pair target is deleted"); - ecs_doc_set_brief(world, EcsRemove, "Cleanup action used with OnDelete/OnDeleteTarget"); - ecs_doc_set_brief(world, EcsDelete, "Cleanup action used with OnDelete/OnDeleteTarget"); - ecs_doc_set_brief(world, EcsPanic, "Cleanup action used with OnDelete/OnDeleteTarget"); - ecs_doc_set_brief(world, ecs_id(EcsDefaultChildComponent), "Sets default component hint for children of entity"); - ecs_doc_set_brief(world, EcsIsA, "Relationship used for expressing inheritance"); - ecs_doc_set_brief(world, EcsChildOf, "Relationship used for expressing hierarchies"); - ecs_doc_set_brief(world, EcsDependsOn, "Relationship used for expressing dependencies"); - ecs_doc_set_brief(world, EcsSlotOf, "Relationship used for expressing prefab slots"); - ecs_doc_set_brief(world, EcsOnAdd, "Event emitted when component is added"); - ecs_doc_set_brief(world, EcsOnRemove, "Event emitted when component is removed"); - ecs_doc_set_brief(world, EcsOnSet, "Event emitted when component is set"); - ecs_doc_set_brief(world, EcsMonitor, "Marker used to create monitor observers"); - ecs_doc_set_brief(world, EcsOnTableCreate, "Event emitted when table is created"); - ecs_doc_set_brief(world, EcsOnTableDelete, "Event emitted when table is deleted"); - - ecs_doc_set_brief(world, EcsThis, "Query marker to express $this variable"); - ecs_doc_set_brief(world, EcsWildcard, "Query marker to express match all wildcard"); - ecs_doc_set_brief(world, EcsAny, "Query marker to express match at least one wildcard"); - - ecs_doc_set_brief(world, EcsPredEq, "Query marker to express == operator"); - ecs_doc_set_brief(world, EcsPredMatch, "Query marker to express ~= operator"); - ecs_doc_set_brief(world, EcsPredLookup, "Query marker to express by-name lookup"); - ecs_doc_set_brief(world, EcsScopeOpen, "Query marker to express scope open"); - ecs_doc_set_brief(world, EcsScopeClose, "Query marker to express scope close"); - ecs_doc_set_brief(world, EcsEmpty, "Tag used to indicate a query has no results"); -} - -/* Doc definitions for doc components */ -static -void flecs_doc_import_doc_definitions( - ecs_world_t *world) -{ - ecs_entity_t doc = ecs_lookup(world, "flecs.doc"); - ecs_doc_set_brief(world, doc, "Flecs module with documentation components"); - - ecs_doc_set_brief(world, EcsDocBrief, "Brief description"); - ecs_doc_set_brief(world, EcsDocDetail, "Detailed description"); - ecs_doc_set_brief(world, EcsDocLink, "Link to additional documentation"); - ecs_doc_set_brief(world, EcsDocColor, "Color hint for entity"); - - ecs_doc_set_brief(world, ecs_id(EcsDocDescription), "Component used to add documentation"); - ecs_doc_set_brief(world, EcsDocBrief, "Used as (Description, Brief) to add a brief description"); - ecs_doc_set_brief(world, EcsDocDetail, "Used as (Description, Detail) to add a detailed description"); - ecs_doc_set_brief(world, EcsDocLink, "Used as (Description, Link) to add a link"); -} - void FlecsDocImport( ecs_world_t *world) { @@ -23445,11 +25197,16 @@ void FlecsDocImport( .dtor = ecs_dtor(EcsDocDescription) }); - ecs_add_pair(world, ecs_id(EcsDocDescription), EcsOnInstantiate, EcsDontInherit); - ecs_add_id(world, ecs_id(EcsDocDescription), EcsPrivate); +#ifdef FLECS_META + ecs_struct(world, { + .entity = ecs_id(EcsDocDescription), + .members = { + { .name = "value", .type = ecs_id(ecs_string_t) } + } + }); +#endif - flecs_doc_import_core_definitions(world); - flecs_doc_import_doc_definitions(world); + ecs_add_pair(world, ecs_id(EcsDocDescription), EcsOnInstantiate, EcsDontInherit); } #endif @@ -23552,10 +25309,21 @@ char* ecs_cpp_get_symbol_name( const char *type_name, size_t len) { + ecs_assert(type_name != NULL, ECS_INVALID_PARAMETER, NULL); + + if (!len) { + len = flecs_itosize(ecs_os_strlen(type_name)); + } + + if (!symbol_name) { + symbol_name = ecs_os_malloc_n(char, flecs_uto(int32_t, len + 1)); + ecs_assert(symbol_name != NULL, ECS_OUT_OF_MEMORY, NULL); + } + const char *ptr; size_t i; for (i = 0, ptr = type_name; i < len && *ptr; i ++, ptr ++) { - if (*ptr == ':') { + if (*ptr == ':' && ptr[1] == ':') { symbol_name[i] = '.'; ptr ++; } else { @@ -23606,7 +25374,7 @@ char* ecs_cpp_get_constant_name( func_name, f_len, fb_len, ':')); start = flecs_cpp_func_max(start, flecs_cpp_func_rchr( func_name, f_len, fb_len, ',')); - ecs_assert(start != NULL, ECS_INVALID_PARAMETER, func_name); + ecs_assert(start != NULL, ECS_INVALID_PARAMETER, "%s", func_name); start ++; ecs_size_t len = flecs_uto(ecs_size_t, @@ -23661,38 +25429,39 @@ const char* ecs_cpp_trim_module( ecs_entity_t ecs_cpp_component_register( ecs_world_t *world, - ecs_entity_t id, - int32_t ids_index, - const char *name, - const char *cpp_name, - const char *cpp_symbol, - size_t size, - size_t alignment, - bool is_component, - bool explicit_registration, - bool *registered_out, - bool *existing_out) + const ecs_cpp_component_desc_t *desc) { - ecs_assert(registered_out != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(existing_out != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(desc != NULL, ECS_INVALID_PARAMETER, NULL); + const char *name = desc->name; + const char *cpp_symbol = desc->cpp_symbol; - ecs_entity_t c = flecs_component_ids_get(world, ids_index); + bool existing = false; + ecs_entity_t c = flecs_component_ids_get(world, desc->ids_index); if (!c || !ecs_is_alive(world, c)) { } else { return c; } + ecs_assert(desc->cpp_name != NULL, ECS_INTERNAL_ERROR, NULL); + + if (!desc->cpp_symbol) { + ecs_size_t len = ecs_os_strlen(desc->cpp_name); + char *symbol_name = ecs_os_alloca_n(char, len + 1); + cpp_symbol = ecs_cpp_get_symbol_name( + symbol_name, desc->cpp_name, flecs_itosize(len)); + } + const char *user_name = NULL; bool implicit_name = true; ecs_entity_t module = 0; - if (explicit_registration) { - user_name = name; + if (desc->explicit_registration) { + user_name = desc->name; implicit_name = false; if (!user_name) { - user_name = cpp_name; + user_name = desc->cpp_name; /* Keep track of whether name was explicitly set. If not, and * the component was already registered, just use the registered @@ -23739,11 +25508,11 @@ ecs_entity_t ecs_cpp_component_register( * or entity has been registered with this name. Ensure component is * looked up from root. */ ecs_entity_t prev_scope = ecs_set_scope(world, 0); - if (id) { - c = id; + if (desc->id) { + c = desc->id; } else { c = ecs_lookup_path_w_sep(world, 0, user_name, "::", "::", false); - *existing_out = c != 0 && ecs_has(world, c, EcsComponent); + existing = c != 0 && ecs_has(world, c, EcsComponent); } ecs_set_scope(world, prev_scope); @@ -23782,8 +25551,8 @@ ecs_entity_t ecs_cpp_component_register( ecs_abort(ECS_NAME_IN_USE, NULL); } - if (flecs_itosize(component->size) != size || - flecs_itosize(component->alignment) != alignment) + if (flecs_itosize(component->size) != desc->size || + flecs_itosize(component->alignment) != desc->alignment) { ecs_err( "component with name '%s' is already registered with"\ @@ -23801,8 +25570,8 @@ ecs_entity_t ecs_cpp_component_register( * registered under a different name. */ } else if (!implicit_name) { c = ecs_lookup_symbol(world, cpp_symbol, false, false); - ecs_assert(c == 0 || (c == id), - ECS_INCONSISTENT_COMPONENT_ID, cpp_symbol); + ecs_assert(c == 0 || (c == desc->id), + ECS_INCONSISTENT_COMPONENT_ID, "%s", cpp_symbol); } const char *symbol = NULL; @@ -23833,21 +25602,21 @@ ecs_entity_t ecs_cpp_component_register( if (e) { existing_name = ecs_get_path_w_sep(world, 0, e, "::", "::"); name = existing_name; - *existing_out = true; + existing = true; } else { /* If type is not yet known, derive from type name */ - name = ecs_cpp_trim_module(world, cpp_name); + name = ecs_cpp_trim_module(world, desc->cpp_name); } } } else { /* If an explicit id is provided but it has no name, inherit * the name from the type. */ if (!ecs_is_valid(world, c) || !ecs_get_name(world, c)) { - name = ecs_cpp_trim_module(world, cpp_name); + name = ecs_cpp_trim_module(world, desc->cpp_name); } } - if (is_component || size != 0) { + if (desc->is_component || desc->size != 0) { c = ecs_entity(world, { .id = c, .name = name, @@ -23862,8 +25631,8 @@ ecs_entity_t ecs_cpp_component_register( c = ecs_component_init(world, &(ecs_component_desc_t){ .entity = c, - .type.size = flecs_uto(int32_t, size), - .type.alignment = flecs_uto(int32_t, alignment) + .type.size = flecs_uto(int32_t, desc->size), + .type.alignment = flecs_uto(int32_t, desc->alignment) }); ecs_assert(c != 0, ECS_INVALID_OPERATION, @@ -23886,9 +25655,15 @@ ecs_entity_t ecs_cpp_component_register( ecs_set_scope(world, prev_scope); /* Set world local component id */ - flecs_component_ids_set(world, ids_index, c); + flecs_component_ids_set(world, desc->ids_index, c); + + if (desc->lifecycle_action && desc->size && !existing) { + desc->lifecycle_action(world, c); + } - *registered_out = true; + if (desc->enum_action) { + desc->enum_action(world, c); + } return c; } @@ -23945,7 +25720,7 @@ ecs_entity_t ecs_cpp_enum_constant_register( .id = id, .name = name }); - ecs_assert(id != 0, ECS_INVALID_OPERATION, name); + ecs_assert(id != 0, ECS_INVALID_OPERATION, "%s", name); ecs_set_scope(world, prev); #ifdef FLECS_DEBUG @@ -23974,7 +25749,7 @@ ecs_entity_t ecs_cpp_enum_constant_register( } #ifdef FLECS_META -const ecs_member_t* ecs_cpp_last_member( +ecs_member_t* ecs_cpp_last_member( const ecs_world_t *world, ecs_entity_t type) { @@ -24012,6 +25787,7 @@ ecs_cpp_get_mut_t ecs_cpp_set( flecs_utosize(size), new_ptr); /* Modified command is already inserted */ result.call_modified = false; + result.stage = NULL; return result; } @@ -24020,6 +25796,8 @@ ecs_cpp_get_mut_t ecs_cpp_set( flecs_uto(int32_t, size)); result.ptr = dst.ptr; + result.world = world; + result.stage = stage; if (id < FLECS_HI_COMPONENT_ID) { if (!world->non_trivial_set[id]) { @@ -24036,9 +25814,7 @@ ecs_cpp_get_mut_t ecs_cpp_set( world, r->table, entity, id, dst.ptr, new_ptr, dst.ti); } -done: - flecs_defer_end(world, stage); - +done: return result; error: return (ecs_cpp_get_mut_t){0}; @@ -24062,6 +25838,7 @@ ecs_cpp_get_mut_t ecs_cpp_assign( world, stage, entity, id, flecs_uto(int32_t, size), new_ptr); /* Modified command is already inserted */ result.call_modified = false; + result.stage = NULL; return result; } @@ -24073,6 +25850,8 @@ ecs_cpp_get_mut_t ecs_cpp_assign( "entity does not have component, use set() instead"); result.ptr = dst.ptr; + result.world = world; + result.stage = stage; if (id < FLECS_HI_COMPONENT_ID) { if (!world->non_trivial_set[id]) { @@ -24090,13 +25869,36 @@ ecs_cpp_get_mut_t ecs_cpp_assign( } done: - flecs_defer_end(world, stage); - return result; error: return (ecs_cpp_get_mut_t){0}; } +ecs_entity_t ecs_cpp_new( + ecs_world_t *world, + ecs_entity_t parent, + const char *name, + const char *sep, + const char *root_sep) +{ + ecs_stage_t *stage = flecs_stage_from_world(&world); + + if (!parent && !name) { + if (!stage->scope && !stage->with) { + ecs_entity_t result = flecs_new_id(world); + flecs_add_to_root_table(world, result); + return result; + } + } + + ecs_entity_desc_t desc = {0}; + desc.parent = parent; + desc.name = name; + desc.sep = sep; + desc.root_sep = root_sep; + return ecs_entity_init(world, &desc); +} + #endif /** @@ -24132,7 +25934,14 @@ char* flecs_journal_idstr( ecs_world_t *world, ecs_id_t id) { - if (ECS_IS_PAIR(id)) { + if (ECS_IS_VALUE_PAIR(id)) { + char *first_path = flecs_journal_entitystr(world, + ecs_pair_first(world, id)); + char *result = flecs_asprintf("#[cyan]ecs_value_pair#[normal](%s, %u)", + first_path, ECS_PAIR_SECOND(id)); + ecs_os_free(first_path); + return result; + } else if (ECS_IS_PAIR(id)) { char *first_path = flecs_journal_entitystr(world, ecs_pair_first(world, id)); char *second_path = flecs_journal_entitystr(world, @@ -24149,6 +25958,7 @@ char* flecs_journal_idstr( } } +static int flecs_journal_counter = 0; static int flecs_journal_sp = 0; void flecs_journal_begin( @@ -24159,6 +25969,7 @@ void flecs_journal_begin( ecs_type_t *remove) { flecs_journal_sp ++; + flecs_journal_counter ++; if (ecs_os_api.log_level_ < FLECS_JOURNAL_LOG_LEVEL) { return; @@ -24177,48 +25988,59 @@ void flecs_journal_begin( } if (kind == EcsJournalNew) { - ecs_print(4, "#[magenta]#ifndef #[normal]_var_%s", var_id); - ecs_print(4, "#[magenta]#define #[normal]_var_%s", var_id); - ecs_print(4, "#[green]ecs_entity_t %s;", var_id); - ecs_print(4, "#[magenta]#endif"); - ecs_print(4, "%s = #[cyan]ecs_new_id#[reset](world); " - "#[grey] // %s = new()", var_id, path); - } - if (add) { - for (int i = 0; i < add->count; i ++) { - char *jidstr = flecs_journal_idstr(world, add->array[i]); - char *idstr = ecs_id_str(world, add->array[i]); - ecs_print(4, "#[cyan]ecs_add_id#[reset](world, %s, %s); " - "#[grey] // add(%s, %s)", var_id, jidstr, - path, idstr); - ecs_os_free(idstr); - ecs_os_free(jidstr); + ecs_print(4, "%d: #[magenta]#ifndef #[normal]_var_%s", flecs_journal_counter, var_id); + ecs_print(4, "%d: #[magenta]#define #[normal]_var_%s", flecs_journal_counter, var_id); + ecs_print(4, "%d: #[green]ecs_entity_t %s;", flecs_journal_counter, var_id); + ecs_print(4, "%d: #[magenta]#endif", flecs_journal_counter); + ecs_print(4, "%d: %s = #[cyan]ecs_new#[reset](world); " + "#[grey] // %s = new()", flecs_journal_counter, var_id, path); + } + if (kind == EcsJournalSetParent) { + ecs_entity_t parent = add->array[0]; + char *parentstr = flecs_journal_entitystr(world, parent); + ecs_print(4, "%d: #[cyan]ecs_set#[reset](world, %s, EcsParent, {%s}); " + "#[grey] // set(%s, EcsParent, %s)", flecs_journal_counter, var_id, parentstr, + path, parentstr); + ecs_os_free(parentstr); + } else { + if (add) { + for (int i = 0; i < add->count; i ++) { + char *jidstr = flecs_journal_idstr(world, add->array[i]); + char *idstr = ecs_id_str(world, add->array[i]); + ecs_print(4, "%d: #[cyan]ecs_add_id#[reset](world, %s, %s); " + "#[grey] // add(%s, %s)", flecs_journal_counter, var_id, jidstr, + path, idstr); + ecs_os_free(idstr); + ecs_os_free(jidstr); + } + } + if (remove) { + for (int i = 0; i < remove->count; i ++) { + char *jidstr = flecs_journal_idstr(world, remove->array[i]); + char *idstr = ecs_id_str(world, remove->array[i]); + ecs_print(4, "%d: #[cyan]ecs_remove_id#[reset](world, %s, %s); " + "#[grey] // remove(%s, %s)", flecs_journal_counter, var_id, jidstr, + path, idstr); + ecs_os_free(idstr); + ecs_os_free(jidstr); + } + } + + if (kind == EcsJournalClear) { + ecs_print(4, "%d: #[cyan]ecs_clear#[reset](world, %s); " + "#[grey] // clear(%s)", flecs_journal_counter, var_id, path); + } else if (kind == EcsJournalDelete) { + ecs_print(4, "%d: #[cyan]ecs_delete#[reset](world, %s); " + "#[grey] // delete(%s)", flecs_journal_counter, var_id, path); + } else if (kind == EcsJournalDeleteWith) { + ecs_print(4, "%d: #[cyan]ecs_delete_with#[reset](world, %s); " + "#[grey] // delete_with(%s)", flecs_journal_counter, var_id, path); + } else if (kind == EcsJournalRemoveAll) { + ecs_print(4, "%d: #[cyan]ecs_remove_all#[reset](world, %s); " + "#[grey] // remove_all(%s)", flecs_journal_counter, var_id, path); } } - if (remove) { - for (int i = 0; i < remove->count; i ++) { - char *jidstr = flecs_journal_idstr(world, remove->array[i]); - char *idstr = ecs_id_str(world, remove->array[i]); - ecs_print(4, "#[cyan]ecs_remove_id#[reset](world, %s, %s); " - "#[grey] // remove(%s, %s)", var_id, jidstr, - path, idstr); - ecs_os_free(idstr); - ecs_os_free(jidstr); - } - } - if (kind == EcsJournalClear) { - ecs_print(4, "#[cyan]ecs_clear#[reset](world, %s); " - "#[grey] // clear(%s)", var_id, path); - } else if (kind == EcsJournalDelete) { - ecs_print(4, "#[cyan]ecs_delete#[reset](world, %s); " - "#[grey] // delete(%s)", var_id, path); - } else if (kind == EcsJournalDeleteWith) { - ecs_print(4, "#[cyan]ecs_delete_with#[reset](world, %s); " - "#[grey] // delete_with(%s)", var_id, path); - } else if (kind == EcsJournalRemoveAll) { - ecs_print(4, "#[cyan]ecs_remove_all#[reset](world, %s); " - "#[grey] // remove_all(%s)", var_id, path); - } + ecs_os_free(var_id); ecs_os_free(path); ecs_log_push(); @@ -24230,6 +26052,10 @@ void flecs_journal_end(void) { ecs_log_pop(); } +int flecs_journal_get_counter(void) { + return flecs_journal_counter; +} + #endif /** @@ -25804,10 +27630,6 @@ void FlecsMetricsImport(ecs_world_t *world) { ECS_COMPONENT_DEFINE(world, EcsMetricCountIds); ECS_COMPONENT_DEFINE(world, EcsMetricCountTargets); - ecs_add_id(world, ecs_id(EcsMetricMemberInstance), EcsPrivate); - ecs_add_id(world, ecs_id(EcsMetricIdInstance), EcsPrivate); - ecs_add_id(world, ecs_id(EcsMetricOneOfInstance), EcsPrivate); - ecs_struct(world, { .entity = ecs_id(EcsMetricValue), .members = { @@ -25955,7 +27777,7 @@ ecs_entity_t ecs_import( /* Lookup module entity (must be registered by module) */ e = ecs_lookup(world, module_name); - ecs_check(e != 0, ECS_MODULE_UNDEFINED, module_name); + ecs_check(e != 0, ECS_MODULE_UNDEFINED, "%s", module_name); ecs_log_pop(); } @@ -26114,7 +27936,6 @@ ecs_entity_t ecs_module_init( } ecs_add_id(world, e, EcsModule); - ecs_add_id(world, e, EcsSingleton); ecs_component_desc_t private_desc = *desc; private_desc.entity = e; @@ -26167,7 +27988,6 @@ struct ecs_pipeline_state_t { ecs_vec_t systems; /* Vector with system ids */ ecs_entity_t last_system; /* Last system ran by pipeline */ - ecs_component_record_t *cr_inactive; /* Cached record for quick inactive test */ int32_t match_count; /* Used to track of rebuild is necessary */ int32_t rebuild_count; /* Number of pipeline rebuilds */ ecs_iter_t *iters; /* Iterator for worker(s) */ @@ -26271,11 +28091,14 @@ typedef struct ecs_json_ser_ctx_t { ecs_component_record_t *cr_doc_name; ecs_component_record_t *cr_doc_color; ecs_json_value_ser_ctx_t value_ctx[64]; + ecs_map_t serialized; } ecs_json_ser_ctx_t; typedef struct ecs_json_this_data_t { + const ecs_table_t *table; const ecs_entity_t *ids; const EcsIdentifier *names; + const EcsParent *parents; const EcsDocDescription *label; const EcsDocDescription *brief; const EcsDocDescription *detail; @@ -26474,6 +28297,7 @@ int flecs_json_serialize_iter_result_table( const ecs_iter_t *it, ecs_strbuf_t *buf, const ecs_iter_to_json_desc_t *desc, + ecs_json_ser_ctx_t *ser_ctx, int32_t count, bool has_this, const char *parent_path, @@ -26490,13 +28314,14 @@ int flecs_json_serialize_iter_result_query( const char *parent_path, const ecs_json_this_data_t *this_data); -void flecs_json_serialize_iter_this( +bool flecs_json_serialize_iter_this( const ecs_iter_t *it, const char *parent_path, const ecs_json_this_data_t *this_data, int32_t row, ecs_strbuf_t *buf, - const ecs_iter_to_json_desc_t *desc); + const ecs_iter_to_json_desc_t *desc, + ecs_json_ser_ctx_t *ser_ctx); bool flecs_json_serialize_vars( const ecs_world_t *world, @@ -26523,6 +28348,22 @@ int flecs_json_serialize_alerts( bool flecs_json_is_builtin( ecs_id_t id); +int flecs_entity_to_json_buf( + const ecs_world_t *world, + ecs_entity_t entity, + ecs_strbuf_t *buf, + const ecs_iter_to_json_desc_t *desc, + ecs_json_ser_ctx_t *ser_ctx); + +bool flecs_json_should_serialize( + ecs_entity_t entity, + const ecs_iter_t *it, + const ecs_json_ser_ctx_t *ser_ctx); + +void flecs_json_mark_serialized( + ecs_entity_t entity, + ecs_json_ser_ctx_t *ser_ctx); + #endif #endif /* FLECS_JSON_PRIVATE_H */ @@ -26533,8 +28374,6 @@ bool flecs_json_is_builtin( /* Retain captured commands for one minute at 60 FPS */ #define FLECS_REST_COMMAND_RETAIN_COUNT (60 * 60) -static ECS_TAG_DECLARE(EcsRestPlecs); - typedef struct { char *cmds; ecs_time_t start_time; @@ -26828,6 +28667,32 @@ ecs_entity_t flecs_rest_entity_from_path( return e; } +static +bool flecs_rest_get_type_info( + ecs_world_t *world, + ecs_http_reply_t *reply, + const char *path) +{ + ecs_dbg_2("rest: request type info '%s'", path); + + ecs_entity_t e; + if (!(e = flecs_rest_entity_from_path(world, reply, path))) { + return true; + } + + char *json = ecs_type_info_to_json(world, e); + if (!json) { + flecs_reply_error(reply, "failed to serialize type info for '%s'", path); + reply->code = 500; + return true; + } + + ecs_strbuf_appendstr(&reply->body, json); + ecs_os_free(json); + + return true; +} + static bool flecs_rest_get_component( ecs_world_t *world, @@ -28213,6 +30078,7 @@ const char* flecs_rest_cmd_kind_to_str( case EcsCmdBulkNew: return "BulkNew"; case EcsCmdAdd: return "Add"; case EcsCmdRemove: return "Remove"; + case EcsCmdSetDontFragment: case EcsCmdSet: return "Set"; case EcsCmdEmplace: return "Emplace"; case EcsCmdEnsure: return "Ensure"; @@ -28246,6 +30112,7 @@ bool flecs_rest_cmd_has_id( case EcsCmdAdd: case EcsCmdRemove: case EcsCmdSet: + case EcsCmdSetDontFragment: case EcsCmdEmplace: case EcsCmdEnsure: case EcsCmdModified: @@ -28517,6 +30384,10 @@ bool flecs_rest_reply( } else if (!ecs_os_strncmp(req->path, "component/", 10)) { return flecs_rest_get_component(world, req, reply, &req->path[10]); + /* Type info endpoint */ + } else if (!ecs_os_strncmp(req->path, "type_info/", 10)) { + return flecs_rest_get_type_info(world, reply, &req->path[10]); + /* Query endpoint */ } else if (!ecs_os_strcmp(req->path, "query")) { return flecs_rest_get_query(world, req, reply); @@ -28606,7 +30477,6 @@ ecs_http_server_t* ecs_rest_server_init( srv_ctx->world = world; srv_ctx->srv = srv; srv_ctx->rc = 1; - srv_ctx->srv = srv; /* Set build info on world so clients know which version they're using */ ecs_id_t build_info = ecs_lookup(world, "flecs.core.BuildInfo"); @@ -28716,14 +30586,7 @@ void FlecsRestImport( ECS_MODULE(world, FlecsRest); ECS_IMPORT(world, FlecsPipeline); -#ifdef FLECS_SCRIPT - ECS_IMPORT(world, FlecsScript); -#endif -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); - ecs_doc_set_brief(world, ecs_id(FlecsRest), - "Module that implements Flecs REST API"); -#endif + ECS_IMPORT(world, FlecsMeta); ecs_set_name_prefix(world, "Ecs"); @@ -28738,7 +30601,7 @@ void FlecsRestImport( }); ecs_system(world, { - .entity = ecs_entity(world, {.name = "DequeueRest", .add = ecs_ids( ecs_dependson(EcsPostFrame))}), + .entity = ecs_entity(world, { .name = "DequeueRest", .add = ecs_ids( ecs_dependson(EcsPostFrame)) }), .query.terms = { { .id = ecs_id(EcsRest) }, }, @@ -28751,11 +30614,11 @@ void FlecsRestImport( .terms = {{ .id = EcsDisabled, .src.id = ecs_id(FlecsRest) }} }, .events = {EcsOnAdd, EcsOnRemove}, - .callback = DisableRest + .callback = DisableRest, + .global_observer = true }); ecs_set_name_prefix(world, "EcsRest"); - ECS_TAG_DEFINE(world, EcsRestPlecs); /* Enable frame time measurements so we're guaranteed to have a delta time * value to pass into the HTTP server. */ @@ -29092,11 +30955,6 @@ void FlecsTimerImport( { ECS_MODULE(world, FlecsTimer); ECS_IMPORT(world, FlecsPipeline); -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); - ecs_doc_set_brief(world, ecs_id(FlecsTimer), - "Module that implements system timers (used by .interval)"); -#endif ecs_set_name_prefix(world, "Ecs"); @@ -29158,12 +31016,6 @@ void FlecsUnitsImport( ECS_MODULE(world, FlecsUnits); ECS_IMPORT(world, FlecsMeta); -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); - ecs_doc_set_brief(world, ecs_id(FlecsUnits), - "Module with (amongst others) SI units for annotating component members"); -#endif - ecs_set_name_prefix(world, "Ecs"); EcsUnitPrefixes = ecs_entity(world, { @@ -29192,7 +31044,7 @@ void FlecsUnitsImport( }); EcsFemto = ecs_unit_prefix_init(world, &(ecs_unit_prefix_desc_t){ .entity = ecs_entity(world, { .name = "Femto" }), - .symbol = "a", + .symbol = "f", .translation = { .factor = 10, .power = -15 } }); EcsPico = ecs_unit_prefix_init(world, &(ecs_unit_prefix_desc_t){ @@ -30379,6 +32231,7 @@ void flecs_bitset_set( int32_t elem, bool value) { + ecs_check(elem >= 0, ECS_INVALID_PARAMETER, NULL); ecs_check(elem < bs->count, ECS_INVALID_PARAMETER, NULL); uint32_t hi = ((uint32_t)elem) >> 6; uint32_t lo = ((uint32_t)elem) & 0x3F; @@ -30392,6 +32245,7 @@ bool flecs_bitset_get( const ecs_bitset_t *bs, int32_t elem) { + ecs_check(elem >= 0, ECS_INVALID_PARAMETER, NULL); ecs_check(elem < bs->count, ECS_INVALID_PARAMETER, NULL); return !!(bs->data[elem >> 6] & ((uint64_t)1 << ((uint64_t)elem & 0x3F))); error: @@ -30408,6 +32262,7 @@ void flecs_bitset_remove( ecs_bitset_t *bs, int32_t elem) { + ecs_check(elem >= 0, ECS_INVALID_PARAMETER, NULL); ecs_check(elem < bs->count, ECS_INVALID_PARAMETER, NULL); int32_t last = bs->count - 1; bool last_value = flecs_bitset_get(bs, last); @@ -30423,6 +32278,8 @@ void flecs_bitset_swap( int32_t elem_a, int32_t elem_b) { + ecs_check(elem_a >= 0, ECS_INVALID_PARAMETER, NULL); + ecs_check(elem_b >= 0, ECS_INVALID_PARAMETER, NULL); ecs_check(elem_a < bs->count, ECS_INVALID_PARAMETER, NULL); ecs_check(elem_b < bs->count, ECS_INVALID_PARAMETER, NULL); @@ -32688,6 +34545,7 @@ void* flecs_stack_alloc( ecs_assert(page->data != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(align != 0, ECS_INTERNAL_ERROR, NULL); int16_t sp = flecs_ito(int16_t, ECS_ALIGN(page->sp, align)); int16_t next_sp = flecs_ito(int16_t, sp + size); @@ -32904,23 +34762,26 @@ char* flecs_strbuf_itoa( char *ptr = buf; char * p1; char c; + uint64_t uv; - if (!v) { - *ptr++ = '0'; + if (v < 0) { + ptr[0] = '-'; + ptr ++; + uv = (uint64_t)0 - (uint64_t)v; } else { - if (v < 0) { - ptr[0] = '-'; - ptr ++; - v *= -1; - } + uv = (uint64_t)v; + } + if (!uv) { + *ptr++ = '0'; + } else { char *p = ptr; - while (v) { - int64_t vdiv = v / 10; - int64_t vmod = v - (vdiv * 10); - p[0] = (char)('0' + vmod); + while (uv) { + uint64_t vdiv = uv / 10; + uint64_t vmod = uv - (vdiv * 10); + p[0] = (char)('0' + (char)vmod); p ++; - v = vdiv; + uv = vdiv; } p1 = p; @@ -33288,8 +35149,13 @@ char* ecs_strbuf_get( ecs_strbuf_appendch(b, '\0'); result = b->content; +#ifdef FLECS_SANITIZE + ecs_assert(ecs_os_strlen(result) <= (b->length - 1), + ECS_INTERNAL_ERROR, NULL); +#endif + if (result == b->small_string) { - result = ecs_os_memdup_n(result, char, b->length + 1); + result = ecs_os_memdup_n(result, char, b->length); } b->length = 0; @@ -33692,8 +35558,18 @@ void ecs_vec_set_min_size_w_type_info( int32_t elem_count, const ecs_type_info_t *ti) { + ecs_assert(size != 0, ECS_INVALID_PARAMETER, NULL); + ecs_vec_init_if(vec, size); +#ifdef FLECS_SANITIZE + if (!vec->type_name) { + vec->type_name = ti ? ti->name : NULL; + } +#else + (void)ti; +#endif + if (elem_count > vec->size) { - ecs_vec_set_min_size_w_type_info(allocator, vec, size, elem_count, ti); + ecs_vec_set_size(allocator, vec, size, elem_count); } } @@ -33772,9 +35648,7 @@ void ecs_vec_set_count_w_type_info( return; } - ecs_xtor_t ctor, dtor; - ecs_move_t move = ti->hooks.ctor_move_dtor; - if (!move) { + if (!ti->hooks.ctor_move_dtor) { /* Trivial type, use regular set_count */ ecs_vec_set_count(allocator, v, size, elem_count); return; @@ -33783,17 +35657,13 @@ void ecs_vec_set_count_w_type_info( /* If array is large enough, we don't need to realloc. */ if (v->size > elem_count) { if (elem_count > v->count) { - if ((ctor = ti->hooks.ctor)) { - void *ptr = ECS_ELEM(v->array, size, v->count); - ctor(ptr, elem_count - v->count, ti); - } + void *ptr = ECS_ELEM(v->array, size, v->count); + flecs_type_info_ctor(ptr, elem_count - v->count, ti); } if (elem_count < v->count) { - if ((dtor = ti->hooks.dtor)) { - void *ptr = ECS_ELEM(v->array, size, elem_count); - dtor(ptr, v->count - elem_count, ti); - } + void *ptr = ECS_ELEM(v->array, size, elem_count); + flecs_type_info_dtor(ptr, v->count - elem_count, ti); } v->count = elem_count; @@ -33819,22 +35689,18 @@ void ecs_vec_set_count_w_type_info( } /* Move elements over to new array */ - move(array, v->array, move_count, ti); + flecs_type_info_ctor_move_dtor(array, v->array, move_count, ti); /* Destruct remaining elements in old array, if any */ if (move_count < v->count) { - if ((dtor = ti->hooks.dtor)) { - void *ptr = ECS_ELEM(v->array, size, move_count); - dtor(ptr, v->count - move_count, ti); - } + void *ptr = ECS_ELEM(v->array, size, move_count); + flecs_type_info_dtor(ptr, v->count - move_count, ti); } /* Construct new elements, if any */ if (move_count < elem_count) { - if ((ctor = ti->hooks.ctor)) { - void *ptr = ECS_ELEM(array, size, move_count); - ctor(ptr, elem_count - move_count, ti); - } + void *ptr = ECS_ELEM(array, size, move_count); + flecs_type_info_ctor(ptr, elem_count - move_count, ti); } flecs_vec_free(allocator, size, v->size, v->array); @@ -34092,7 +35958,11 @@ int flecs_query_set_caching_policy( if (impl->pub.flags & EcsQueryIsCacheable) { /* If all terms of the query are cacheable, just set the policy to * All which simplifies work for the compiler. */ - impl->pub.cache_kind = EcsQueryCacheAll; + if (!(impl->pub.flags & EcsQueryCacheWithFilter)) { + impl->pub.cache_kind = EcsQueryCacheAll; + } else { + impl->pub.cache_kind = EcsQueryCacheAuto; + } } else if (!(impl->pub.flags & EcsQueryHasCacheable)) { /* Same for when the query has no cacheable terms */ impl->pub.cache_kind = EcsQueryCacheNone; @@ -34413,7 +36283,7 @@ ecs_query_t* ecs_query_init( } bool ecs_query_has( - ecs_query_t *q, + const ecs_query_t *q, ecs_entity_t entity, ecs_iter_t *it) { @@ -34428,7 +36298,7 @@ bool ecs_query_has( } bool ecs_query_has_table( - ecs_query_t *q, + const ecs_query_t *q, ecs_table_t *table, ecs_iter_t *it) { @@ -34436,7 +36306,8 @@ bool ecs_query_has_table( ecs_check(q->flags & EcsQueryMatchThis, ECS_INVALID_PARAMETER, NULL); if (!flecs_table_bloom_filter_test(table, q->bloom_filter)) { - q->eval_count ++; + /* Safe, only used for statistics */ + ECS_CONST_CAST(ecs_query_t*, q)->eval_count ++; return false; } @@ -34448,7 +36319,7 @@ bool ecs_query_has_table( } bool ecs_query_has_range( - ecs_query_t *q, + const ecs_query_t *q, ecs_table_range_t *range, ecs_iter_t *it) { @@ -34465,7 +36336,8 @@ bool ecs_query_has_range( } if (!flecs_table_bloom_filter_test(table, q->bloom_filter)) { - q->eval_count ++; + /* Safe, only used for statistics */ + ECS_CONST_CAST(ecs_query_t*, q)->eval_count ++; return false; } @@ -34620,12 +36492,102 @@ void* ecs_query_get_group_ctx( } } +const ecs_map_t* ecs_query_get_groups( + const ecs_query_t *query) +{ + flecs_poly_assert(query, ecs_query_t); + ecs_query_impl_t *q = flecs_query_impl(query); + ecs_check(q->cache != NULL, ECS_INVALID_PARAMETER, + "ecs_query_get_groups is not valid for queries that don't use group_by"); + + ecs_query_cache_t *cache = q->cache; + ecs_check(cache->group_by != 0, ECS_INVALID_PARAMETER, + "ecs_query_get_groups is not valid for queries that don't use group_by"); + + return &cache->groups; +error: + return NULL; +} + /** * @file query/util.c * @brief Query utilities. */ +const char* flecs_query_op_str( + uint16_t kind) +{ + switch(kind) { + case EcsQueryAll: return "all "; + case EcsQueryAnd: return "and "; + case EcsQueryAndAny: return "and_any "; + case EcsQueryAndWcTgt: return "and_wct "; + case EcsQueryTriv: return "triv "; + case EcsQueryCache: return "cache "; + case EcsQueryIsCache: return "xcache "; + case EcsQueryUp: return "up "; + case EcsQuerySelfUp: return "selfup "; + case EcsQueryWith: return "with "; + case EcsQueryWithWcTgt: return "with_wct "; + case EcsQueryTrav: return "trav "; + case EcsQueryAndFrom: return "andfrom "; + case EcsQueryOrFrom: return "orfrom "; + case EcsQueryNotFrom: return "notfrom "; + case EcsQueryIds: return "ids "; + case EcsQueryIdsRight: return "idsr "; + case EcsQueryIdsLeft: return "idsl "; + case EcsQueryEach: return "each "; + case EcsQueryStore: return "store "; + case EcsQueryReset: return "reset "; + case EcsQueryOr: return "or "; + case EcsQueryOptional: return "option "; + case EcsQueryIfVar: return "ifvar "; + case EcsQueryIfSet: return "ifset "; + case EcsQueryEnd: return "end "; + case EcsQueryNot: return "not "; + case EcsQueryPredEq: return "eq "; + case EcsQueryPredNeq: return "neq "; + case EcsQueryPredEqName: return "eq_nm "; + case EcsQueryPredNeqName: return "neq_nm "; + case EcsQueryPredEqMatch: return "eq_m "; + case EcsQueryPredNeqMatch: return "neq_m "; + case EcsQueryMemberEq: return "membereq "; + case EcsQueryMemberNeq: return "memberneq "; + case EcsQueryToggle: return "toggle "; + case EcsQueryToggleOption: return "togglopt "; + case EcsQuerySparse: return "sparse "; + case EcsQuerySparseWith: return "sparse_w "; + case EcsQuerySparseNot: return "sparse_not "; + case EcsQuerySparseSelfUp: return "sparse_sup "; + case EcsQuerySparseUp: return "sparse_up "; + case EcsQueryTree: return "tree "; + case EcsQueryTreeWildcard: return "tree_wc "; + case EcsQueryTreePre: return "tree_pre "; + case EcsQueryTreePost: return "tree_post "; + case EcsQueryTreeUpPre: return "treeup_pre "; + case EcsQueryTreeSelfUpPre: return "treesup_pre "; + case EcsQueryTreeUpPost: return "treeup_post "; + case EcsQueryTreeSelfUpPost: return "treesup_post"; + case EcsQueryTreeUp: return "tree_up "; + case EcsQueryTreeSelfUp: return "tree_selfup "; + case EcsQueryTreeWith: return "tree_w "; + case EcsQueryChildren: return "children "; + case EcsQueryChildrenWc: return "children_wc "; + case EcsQueryLookup: return "lookup "; + case EcsQuerySetVars: return "setvars "; + case EcsQuerySetThis: return "setthis "; + case EcsQuerySetFixed: return "setfix "; + case EcsQuerySetIds: return "setids "; + case EcsQuerySetId: return "setid "; + case EcsQueryContain: return "contain "; + case EcsQueryPairEq: return "pair_eq "; + case EcsQueryYield: return "yield "; + case EcsQueryNothing: return "nothing "; + default: return "!invalid "; + } +} + ecs_query_lbl_t flecs_itolbl(int64_t val) { return flecs_ito(int16_t, val); } @@ -34791,66 +36753,6 @@ ecs_allocator_t* flecs_query_get_allocator( } } -const char* flecs_query_op_str( - uint16_t kind) -{ - switch(kind) { - case EcsQueryAll: return "all "; - case EcsQueryAnd: return "and "; - case EcsQueryAndAny: return "and_any "; - case EcsQueryAndWcTgt: return "and_wct "; - case EcsQueryTriv: return "triv "; - case EcsQueryCache: return "cache "; - case EcsQueryIsCache: return "xcache "; - case EcsQueryUp: return "up "; - case EcsQuerySelfUp: return "selfup "; - case EcsQueryWith: return "with "; - case EcsQueryWithWcTgt: return "with_wct "; - case EcsQueryTrav: return "trav "; - case EcsQueryAndFrom: return "andfrom "; - case EcsQueryOrFrom: return "orfrom "; - case EcsQueryNotFrom: return "notfrom "; - case EcsQueryIds: return "ids "; - case EcsQueryIdsRight: return "idsr "; - case EcsQueryIdsLeft: return "idsl "; - case EcsQueryEach: return "each "; - case EcsQueryStore: return "store "; - case EcsQueryReset: return "reset "; - case EcsQueryOr: return "or "; - case EcsQueryOptional: return "option "; - case EcsQueryIfVar: return "ifvar "; - case EcsQueryIfSet: return "ifset "; - case EcsQueryEnd: return "end "; - case EcsQueryNot: return "not "; - case EcsQueryPredEq: return "eq "; - case EcsQueryPredNeq: return "neq "; - case EcsQueryPredEqName: return "eq_nm "; - case EcsQueryPredNeqName: return "neq_nm "; - case EcsQueryPredEqMatch: return "eq_m "; - case EcsQueryPredNeqMatch: return "neq_m "; - case EcsQueryMemberEq: return "membereq "; - case EcsQueryMemberNeq: return "memberneq "; - case EcsQueryToggle: return "toggle "; - case EcsQueryToggleOption: return "togglopt "; - case EcsQuerySparse: return "spars "; - case EcsQuerySparseWith: return "spars_w "; - case EcsQuerySparseNot: return "spars_not "; - case EcsQuerySparseSelfUp: return "spars_sup "; - case EcsQuerySparseUp: return "spars_up "; - case EcsQueryLookup: return "lookup "; - case EcsQuerySetVars: return "setvars "; - case EcsQuerySetThis: return "setthis "; - case EcsQuerySetFixed: return "setfix "; - case EcsQuerySetIds: return "setids "; - case EcsQuerySetId: return "setid "; - case EcsQueryContain: return "contain "; - case EcsQueryPairEq: return "pair_eq "; - case EcsQueryYield: return "yield "; - case EcsQueryNothing: return "nothing "; - default: return "!invalid "; - } -} - static int32_t flecs_query_op_ref_str( const ecs_query_impl_t *query, @@ -35075,6 +36977,29 @@ char* ecs_query_plan( return ecs_query_plan_w_profile(q, NULL); } +char* ecs_query_plans( + const ecs_query_t *q) +{ + flecs_poly_assert(q, ecs_query_t); + ecs_strbuf_t buf = ECS_STRBUF_INIT; + + flecs_query_plan_w_profile(q, NULL, &buf); + + ecs_query_impl_t *impl = flecs_query_impl(q); + if (impl->cache) { + ecs_strbuf_appendstr(&buf, "---\n"); + flecs_query_plan_w_profile(impl->cache->query, NULL, &buf); + } + +#ifdef FLECS_LOG + char *str = ecs_strbuf_get(&buf); + flecs_colorize_buf(str, ecs_os_api.flags_ & EcsOsApiLogWithColors, &buf); + ecs_os_free(str); +#endif + + return ecs_strbuf_get(&buf); +} + static void flecs_query_str_add_id( const ecs_world_t *world, @@ -35327,6 +37252,17 @@ void flecs_query_reclaim( } } +ecs_id_t flecs_query_iter_set_id( + ecs_iter_t *it, + int8_t field, + ecs_id_t id) +{ + ecs_assert(!(it->flags & EcsIterImmutableCacheData), + ECS_INTERNAL_ERROR, NULL); + it->ids[field] = id; + return id; +} + /** * @file query/validator.c * @brief Validate and finalize queries. @@ -35495,6 +37431,10 @@ int flecs_term_ref_lookup( e = ecs_lookup(world, name); } + if (!e) { + e = ecs_lookup_symbol(world, name, false, false); + } + if (!e) { if (ctx->query && (ctx->query->flags & EcsQueryAllowUnresolvedByName)) { ref->id |= EcsIsName; @@ -35923,7 +37863,9 @@ int flecs_term_verify( if ((src->id & mask) == (second->id & mask)) { bool is_same = false; if (src->id & EcsIsEntity) { - is_same = src_id == second_id; + if (src_id) { + is_same = src_id == second_id; + } } else if (src->name && second->name) { is_same = !ecs_os_strcmp(src->name, second->name); } @@ -35985,17 +37927,20 @@ int flecs_term_finalize( if (first->name && (first->id & ~EcsTermRefFlags)) { flecs_query_validator_error(ctx, - "first.name and first.id have competing values"); + "first.name (%s) and first.id have competing values", + first->name); return -1; } if (src->name && (src->id & ~EcsTermRefFlags)) { flecs_query_validator_error(ctx, - "src.name and src.id have competing values"); + "src.name (%s) and src.id have competing values", + src->name); return -1; } if (second->name && (second->id & ~EcsTermRefFlags)) { flecs_query_validator_error(ctx, - "second.name and second.id have competing values"); + "second.name (%s) and second.id have competing values", + second->name); return -1; } @@ -36050,7 +37995,11 @@ int flecs_term_finalize( /* If term queries for !(ChildOf, _), translate it to the builtin * (ChildOf, 0) index which is a cheaper way to find root entities */ - if (term->oper == EcsNot && term->id == ecs_pair(EcsChildOf, EcsAny)) { + if (term->oper == EcsNot && ( + (term->id == ecs_pair(EcsChildOf, EcsAny)) || + (term->id == ecs_pair(EcsChildOf, EcsWildcard)) + )) + { /* Only if the source is not EcsAny */ if (!(ECS_TERM_REF_ID(&term->src) == EcsAny && (term->src.id & EcsIsVariable))) { term->oper = EcsAnd; @@ -36250,6 +38199,16 @@ int flecs_term_finalize( trivial_term = false; } + if (ECS_IS_PAIR(term->id) && (ECS_PAIR_FIRST(term->id) == EcsChildOf)) { + if (term->oper == EcsAnd) { + term->flags_ |= EcsTermNonFragmentingChildOf; + } + + if (ECS_PAIR_SECOND(term->id)) { + trivial_term = false; + } + } + if (ecs_id_is_wildcard(term->id)) { if (ECS_PAIR_FIRST(term->id) == EcsWildcard) { cacheable_term = false; @@ -36445,6 +38404,12 @@ int flecs_query_finalize_terms( bool cacheable = true; bool match_nothing = true; + /* If a query has ChildOf terms we need to prevent it from being marked as + * IsCacheable (meaning the query can be evaluated by just iterating the + * cache). A ChildOf term must be marked as cacheable, but also needs an + * instruction to filter tables that use non-fragmenting relationships. */ + bool has_childof = false; + for (i = 0; i < term_count; i ++) { ecs_term_t *term = &terms[i]; bool prev_is_or = i && term[-1].oper == EcsOr; @@ -36456,6 +38421,25 @@ int flecs_query_finalize_terms( return -1; } + if (term->flags_ & EcsTermNonFragmentingChildOf) { + if (!i) { + /* If the first term is a ChildOf pair, the query result should + * respect the order of parents with the OrderedChildren trait. + * This cannot be cached, so unset the IsCacheable bit. */ + ECS_BIT_CLEAR16(term->flags_, EcsTermIsCacheable); + } + + if (ECS_PAIR_SECOND(term->id) != EcsAny) { + has_childof = true; + } + } + + if (term->trav == EcsChildOf && (term->oper == EcsAnd || term->oper == EcsOptional)) { + if (!(term->flags_ & EcsTermIsOr)) { + has_childof = true; + } + } + if (term->src.id != EcsIsEntity) { /* If term doesn't match 0 entity, query doesn't match nothing */ match_nothing = false; @@ -36800,6 +38784,13 @@ int flecs_query_finalize_terms( ECS_BIT_CLEAR(q->flags, EcsQueryMatchOnlySelf); } + if (ECS_TERM_REF_ID(&term->first) == EcsChildOf) { + if (ECS_TERM_REF_ID(&term->second) != 0) { + is_trivial = false; + continue; + } + } + if (!(term->flags_ & EcsTermIsTrivial)) { is_trivial = false; continue; @@ -36829,7 +38820,10 @@ int flecs_query_finalize_terms( * optimized logic as it doesn't have to deal with order_by edge cases */ ECS_BIT_COND(q->flags, EcsQueryIsCacheable, cacheable && (cacheable_terms == term_count) && - !desc->order_by_callback); + !desc->order_by_callback && + !has_childof); + + ECS_BIT_COND(q->flags, EcsQueryCacheWithFilter, has_childof); /* If none of the terms match a source, the query matches nothing */ ECS_BIT_COND(q->flags, EcsQueryMatchNothing, match_nothing); @@ -37066,11 +39060,30 @@ bool flecs_query_finalize_simple( } if (ECS_IS_PAIR(id)) { + if (first == EcsChildOf) { + if (term->oper == EcsAnd) { + term->flags_ |= EcsTermNonFragmentingChildOf; + } + + ecs_entity_t second = ECS_PAIR_SECOND(id); + if (second) { + trivial = false; + if (ECS_PAIR_SECOND(id) != EcsAny) { + if (!i) { + /* If first query term is ChildOf, return children + * in order if possible, which can't be cached. */ + cacheable = false; + } + } + } + } + if (ecs_has_id(world, first, EcsTransitive)) { term->flags_ |= EcsTermTransitive; trivial = false; cacheable = false; } + if (ecs_has_id(world, first, EcsReflexive)) { term->flags_ |= EcsTermReflexive; trivial = false; @@ -37383,14 +39396,19 @@ ecs_id_t flecs_component_hash( id = ecs_strip_generation(id); if (ECS_IS_PAIR(id)) { ecs_entity_t r = ECS_PAIR_FIRST(id); - ecs_entity_t o = ECS_PAIR_SECOND(id); - if (r == EcsAny) { - r = EcsWildcard; - } - if (o == EcsAny) { - o = EcsWildcard; + ecs_entity_t t = ECS_PAIR_SECOND(id); + + if (ECS_IS_VALUE_PAIR(id)) { + id = ecs_value_pair(r, t); + } else { + if (r == EcsAny) { + r = EcsWildcard; + } + if (t == EcsAny) { + t = EcsWildcard; + } + id = ecs_pair(r, t); } - id = ecs_pair(r, o); } return id; } @@ -37535,9 +39553,18 @@ ecs_flags32_t flecs_component_event_flags( |EcsIdHasOnSet |EcsIdHasOnTableCreate |EcsIdHasOnTableDelete); + return result; } +void flecs_component_ordered_children_init( + ecs_world_t *world, + ecs_component_record_t *cr) +{ + cr->flags |= EcsIdOrderedChildren; + flecs_ordered_children_init(world, cr); +} + static ecs_flags32_t flecs_component_get_flags_intern( const ecs_world_t *world, @@ -37558,93 +39585,27 @@ ecs_flags32_t flecs_component_get_flags_intern( ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); ecs_table_t *table = r->table; - if (ecs_table_has_id(world, table, ecs_pair(EcsWith, EcsWildcard))) { - result |= EcsIdWith; - } - - if (ecs_table_has_id(world, table, EcsCanToggle)) { - result |= EcsIdCanToggle; - } - - if (ecs_table_has_id(world, table, EcsInheritable)) { - result |= EcsIdInheritable; - } - - if (ecs_table_has_id(world, table, EcsSingleton)) { - result |= EcsIdSingleton; - } - - ecs_entity_t on_delete_kind = ecs_table_get_target(world, table, EcsOnDelete, 0); - if (on_delete_kind == EcsRemove) { - result |= EcsIdOnDeleteRemove; - } else if (on_delete_kind == EcsDelete) { - result |= EcsIdOnDeleteDelete; - } else if (on_delete_kind == EcsPanic) { - result |= EcsIdOnDeletePanic; - } - - on_delete_kind = ecs_table_get_target(world, table, EcsOnDeleteTarget, 0); - if (on_delete_kind == EcsRemove) { - result |= EcsIdOnDeleteTargetRemove; - } else if (on_delete_kind == EcsDelete) { - result |= EcsIdOnDeleteTargetDelete; - } else if (on_delete_kind == EcsPanic) { - result |= EcsIdOnDeleteTargetPanic; - } - - ecs_entity_t inherit_kind = ecs_table_get_target(world, table, EcsOnInstantiate, 0); - if (inherit_kind == EcsInherit) { - result |= EcsIdOnInstantiateInherit; - } else if (inherit_kind == EcsDontInherit) { - result |= EcsIdOnInstantiateDontInherit; - } else if (inherit_kind == EcsOverride) { - result |= EcsIdOnInstantiateOverride; - } + result = table->trait_flags; if (tgt) { - if (ecs_table_has_id(world, table, EcsExclusive)) { - result |= EcsIdExclusive; - } - - if (ecs_table_has_id(world, table, EcsTraversable)) { - result |= EcsIdTraversable; - } - - if (ecs_table_has_id(world, table, EcsPairIsTag)) { - result |= EcsIdPairIsTag; - } + if (ti && (ti->component == tgt)) { + /* Target determines the type, so unset storage flags */ + result &= ~EcsIdSparse; + result &= ~EcsIdDontFragment; - if (ecs_table_has_id(world, table, EcsTransitive)) { - result |= EcsIdIsTransitive; - } - - if (rel == EcsChildOf) { - if (ecs_has_id(world, tgt, EcsOrderedChildren)) { - result |= EcsIdOrderedChildren; + if (ecs_owns_id(world, tgt, EcsSparse)) { + result |= EcsIdSparse; } - } - } - if (tgt && ti && (ti->component == tgt)) { - if (ecs_has_id(world, tgt, EcsSparse)) { - result |= EcsIdSparse; - } - - if (ecs_has_id(world, tgt, EcsDontFragment)) { - result |= EcsIdDontFragment; + if (ecs_owns_id(world, tgt, EcsDontFragment)) { + result |= EcsIdDontFragment; + } } } else { - if (ecs_table_has_id(world, table, EcsSparse)) { - result |= EcsIdSparse; - } - - if (ecs_table_has_id(world, table, EcsDontFragment)) { - result |= EcsIdDontFragment; - } + /* Disable flags that only apply to pairs */ + result &= ~(EcsIdExclusive|EcsIdTraversable|EcsIdPairIsTag|EcsIdIsTransitive); } - result |= flecs_component_event_flags(world, id); - return result; } @@ -37687,14 +39648,24 @@ void flecs_component_record_check_constraints( (void)tgt; #ifdef FLECS_DEBUG + if (ECS_HAS_ID_FLAG(cr->id, PAIR) && !ECS_IS_PAIR(cr->id)) { + return; + } + if (ECS_IS_PAIR(cr->id)) { + /* Internal role records use (EcsFlag, X). These should not be + * validated as regular relationship/target pairs. */ + if (rel == EcsFlag) { + return; + } + if (tgt) { ecs_assert(tgt != 0, ECS_INTERNAL_ERROR, NULL); /* Can't use relationship as target */ if (ecs_has_id(world, tgt, EcsRelationship)) { if (!ecs_id_is_wildcard(rel) && - !ecs_has_id(world, rel, EcsTrait)) + !ecs_has_id(world, rel, EcsTrait)) { ecs_throw(ECS_CONSTRAINT_VIOLATED, "cannot use '%s' as target" " in pair '%s': '%s' has the Relationship trait", @@ -37808,101 +39779,151 @@ ecs_component_record_t* flecs_component_new( bool is_wildcard = ecs_id_is_wildcard(id); bool is_pair = ECS_IS_PAIR(id); + bool is_value_pair = ECS_IS_VALUE_PAIR(id); ecs_entity_t rel = 0, tgt = 0; + ecs_table_t *tgt_table = NULL; + ecs_record_t *tgt_r = NULL; + if (is_pair) { cr->pair = flecs_bcalloc_w_dbg_info( &world->allocators.pair_record, "ecs_pair_record_t"); cr->pair->reachable.current = -1; - flecs_ordered_children_init(world, cr); - rel = ECS_PAIR_FIRST(id); - rel = flecs_entities_get_alive(world, rel); - ecs_assert(rel != 0, ECS_INTERNAL_ERROR, NULL); + if (!is_value_pair) { + tgt = ECS_PAIR_SECOND(id); + } + + /* Link with (R, *) record so we can easily find all matching pairs. */ + if (!is_wildcard && (rel != EcsFlag)) { + ecs_id_t parent_id = ecs_pair(rel, EcsWildcard); + ecs_component_record_t *cr_r = flecs_components_ensure( + world, parent_id); + cr->pair->parent = cr_r; + cr->flags = cr_r->flags; + + /* If pair is not a wildcard, append it to wildcard lists. These + * allow for quickly enumerating all relationships for an object, + * or all objects for a relationship. */ + flecs_insert_id_elem(world, cr, parent_id, cr_r); + + if (tgt) { + ecs_id_t wc_tgt = ecs_pair(EcsWildcard, tgt); + cr_t = flecs_components_ensure(world, wc_tgt); + flecs_insert_id_elem(world, cr, wc_tgt, cr_t); + } + } /* Relationship object can be 0, as tables without a ChildOf * relationship are added to the (ChildOf, 0) component record */ - tgt = ECS_PAIR_SECOND(id); if (tgt) { ecs_entity_t alive_tgt = flecs_entities_get_alive(world, tgt); ecs_assert(alive_tgt != 0, ECS_INVALID_PARAMETER, "target '%s' of pair '%s' is not alive", flecs_errstr(ecs_id_str(world, tgt)), flecs_errstr_1(ecs_id_str(world, cr->id))); + tgt = alive_tgt; - } - if (!is_wildcard && (rel != EcsFlag) && is_pair) { - /* Inherit flags from (relationship, *) record */ - ecs_component_record_t *cr_r = flecs_components_ensure( - world, ecs_pair(rel, EcsWildcard)); - cr->pair->parent = cr_r; - cr->flags = cr_r->flags; + if (tgt != EcsWildcard) { + tgt_r = flecs_entities_get(world, tgt); + ecs_assert(tgt_r != NULL, ECS_INTERNAL_ERROR, NULL); + tgt_table = tgt_r->table; + + /* Enable flag that indicates entity is a target. */ + flecs_record_add_flag(tgt_r, EcsEntityIsTarget); + + /* ChildOf records can be created often and since we already know + * the traits a ChildOf record will have, set them directly. */ + if (rel == EcsChildOf) { + /* Add flag to indicate that children are prefab children. + * This is used to determine whether to build the lookup map + * that allows for: + * instance_child = instance.target(prefab_child); + */ + if (tgt_table->flags & EcsTableIsPrefab) { + cr->flags |= EcsIdPrefabChildren; + } - /* If pair is not a wildcard, append it to wildcard lists. These - * allow for quickly enumerating all relationships for an object, - * or all objects for a relationship. */ - flecs_insert_id_elem(world, cr, ecs_pair(rel, EcsWildcard), cr_r); + /* Check if we should keep a list of ordered children for + * parent */ + if (ecs_table_has_id( + world, tgt_table, EcsOrderedChildren)) + { + flecs_component_ordered_children_init(world, cr); + } - if (tgt) { - cr_t = flecs_components_ensure(world, ecs_pair(EcsWildcard, tgt)); - flecs_insert_id_elem(world, cr, ecs_pair(EcsWildcard, tgt), cr_t); + flecs_component_update_childof_depth( + world, cr, tgt, tgt_r); + + cr->flags |= EcsIdOnDeleteTargetDelete | + EcsIdOnInstantiateDontInherit | EcsIdTraversable | + EcsIdPairIsTag | EcsIdExclusive; + + if (tgt && tgt != EcsWildcard) { + /* (ChildOf, tgt) pairs are always traversable. */ + ecs_assert(tgt_r != NULL, ECS_INTERNAL_ERROR, NULL); + flecs_record_add_flag(tgt_r, EcsEntityIsTraversable); + } + } } } } else { rel = id & ECS_COMPONENT_MASK; - ecs_assert(rel != 0, ECS_INTERNAL_ERROR, NULL); - rel = flecs_entities_get_alive(world, rel); + ecs_assert(rel != 0, ECS_INTERNAL_ERROR, NULL); } - cr->type_info = flecs_determine_type_info_for_component(world, id); - - cr->flags |= flecs_component_get_flags_intern( - world, id, rel, tgt, cr->type_info); + /* Wildcards don't need trait flags, ChildOf is already initialized */ + if (rel != EcsWildcard && rel != EcsChildOf) { + rel = flecs_entities_get_alive(world, rel); - flecs_component_record_check_constraints(world, cr, rel, tgt); + cr->type_info = flecs_determine_type_info_for_component(world, id); + cr->flags |= flecs_component_get_flags_intern( + world, id, rel, tgt, cr->type_info); - /* Mark entities that are used as component/pair ids. When a tracked - * entity is deleted, cleanup policies are applied so that the store - * won't contain any tables with deleted ids. */ + /* Set flag that indicates entity is used as component/relationship. */ + flecs_add_flag(world, rel, EcsEntityIsId); - /* Flag for OnDelete policies */ - flecs_add_flag(world, rel, EcsEntityIsId); - if (tgt && tgt != EcsWildcard) { - /* Flag for OnDeleteTarget policies */ - ecs_record_t *tgt_r = flecs_entities_get_any(world, tgt); - ecs_assert(tgt_r != NULL, ECS_INTERNAL_ERROR, NULL); - flecs_record_add_flag(tgt_r, EcsEntityIsTarget); + if (tgt && tgt != EcsWildcard) { + if (cr->flags & EcsIdTraversable) { + /* Flag used to determine if object should be traversed when + * propagating events or with super/subset queries */ + ecs_assert(tgt_r != NULL, ECS_INTERNAL_ERROR, NULL); + flecs_record_add_flag(tgt_r, EcsEntityIsTraversable); + } + } - if (cr->flags & EcsIdTraversable) { - /* Flag used to determine if object should be traversed when - * propagating events or with super/subset queries */ - flecs_record_add_flag(tgt_r, EcsEntityIsTraversable); + /* Initialize Sparse storage */ + if (cr->flags & EcsIdSparse) { + flecs_component_init_sparse(world, cr); } - /* Mark (*, tgt) record with HasDontFragment so that queries can quickly - * detect if there are any non-fragmenting records to consider for a - * (*, tgt) query. */ - if (cr->flags & EcsIdDontFragment && ECS_PAIR_FIRST(id) != EcsFlag) { + /* Initialize DontFragment storage */ + if (cr->flags & EcsIdDontFragment) { + flecs_component_record_init_dont_fragment(world, cr); + if (cr_t) { + /* Mark (*, tgt) record with HasDontFragment so that queries + * can quickly detect if there are any non-fragmenting + * records to consider for a (*, tgt) query. */ cr_t->flags |= EcsIdMatchDontFragment; } } } - /* Initialize storage */ - if (cr->flags & EcsIdSparse) { - flecs_component_init_sparse(world, cr); - } + /* Set flags that indicate whether there are observers for component */ + cr->flags |= flecs_component_event_flags(world, id); - if (cr->flags & EcsIdDontFragment) { - flecs_component_record_init_dont_fragment(world, cr); - } + flecs_component_record_check_constraints(world, cr, rel, tgt); + + /* Mark entities that are used as component/pair ids. When a tracked + * entity is deleted, cleanup policies are applied so that the store + * won't contain any tables with deleted ids. */ if (ecs_should_log_1()) { char *id_str = ecs_id_str(world, id); - ecs_dbg_1("#[green]id#[normal] %s #[green]created", id_str); + ecs_dbg_1("#[green]component record#[normal] %s #[green]created", id_str); ecs_os_free(id_str); } @@ -37946,7 +39967,9 @@ void flecs_component_free( if (ECS_PAIR_FIRST(id) != EcsFlag) { /* If id is not a wildcard, remove it from the wildcard lists */ flecs_remove_id_elem(cr, ecs_pair(rel, EcsWildcard)); - flecs_remove_id_elem(cr, ecs_pair(EcsWildcard, tgt)); + if (!ECS_IS_VALUE_PAIR(id)) { + flecs_remove_id_elem(cr, ecs_pair(EcsWildcard, tgt)); + } } } else { ecs_log_push_2(); @@ -38018,7 +40041,7 @@ void flecs_component_free( if (ecs_should_log_1()) { char *id_str = ecs_id_str(world, id); - ecs_dbg_1("#[green]id#[normal] %s #[red]deleted", id_str); + ecs_dbg_1("#[green]component record#[normal] %s #[red]deleted", id_str); ecs_os_free(id_str); } } @@ -38084,6 +40107,7 @@ int32_t flecs_component_release( ecs_component_record_t *cr) { int32_t rc = -- cr->refcount; + ecs_assert(rc >= 0, ECS_INTERNAL_ERROR, flecs_errstr(ecs_id_str(world, cr->id))); @@ -38094,18 +40118,34 @@ int32_t flecs_component_release( return rc; } -void flecs_component_release_tables( +bool flecs_component_release_tables( ecs_world_t *world, ecs_component_record_t *cr) { + bool remaining = false; + ecs_table_cache_iter_t it; if (flecs_table_cache_all_iter(&cr->cache, &it)) { const ecs_table_record_t *tr; while ((tr = flecs_table_cache_next(&it, ecs_table_record_t))) { + ecs_table_t *table = tr->hdr.table; + + if (table->keep) { + remaining = true; + continue; + } + + if (ecs_table_count(table)) { + remaining = true; + continue; + } + /* Release current table */ flecs_table_fini(world, tr->hdr.table); } } + + return remaining; } bool flecs_component_set_type_info( @@ -38134,6 +40174,13 @@ bool flecs_component_set_type_info( return changed; } +const ecs_type_info_t* flecs_component_get_type_info( + const ecs_component_record_t *cr) +{ + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + return cr->type_info; +} + ecs_hashmap_t* flecs_component_name_index_ensure( ecs_world_t *world, ecs_component_record_t *cr) @@ -38270,10 +40317,19 @@ void flecs_component_delete_sparse( ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(cr->flags & EcsIdSparse, ECS_INTERNAL_ERROR, NULL); int32_t i, count = flecs_sparse_count(cr->sparse); + if (!count) { + return; + } + const uint64_t *entities = flecs_sparse_ids(cr->sparse); + ecs_entity_t *to_delete = ecs_os_malloc_n(ecs_entity_t, count); + ecs_os_memcpy_n(to_delete, entities, ecs_entity_t, count); + for (i = 0; i < count; i ++) { - ecs_delete(world, entities[i]); + ecs_delete(world, to_delete[i]); } + + ecs_os_free(to_delete); } ecs_component_record_t* flecs_component_first_next( @@ -38317,6 +40373,163 @@ ecs_id_t flecs_component_get_id( return cr->id; } +ecs_parent_record_t* flecs_component_get_parent_record( + const ecs_component_record_t *cr, + const ecs_table_t *table) +{ + ecs_assert(cr != NULL, ECS_INVALID_PARAMETER, NULL); + ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_pair_record_t *pair = cr->pair; + + if (!pair) { + return NULL; + } + + if (!ecs_map_is_init(&pair->children_tables)) { + return NULL; + } + + return (ecs_parent_record_t*)ecs_map_get(&pair->children_tables, table->id); +} + +int32_t flecs_component_get_childof_depth( + const ecs_component_record_t *cr) +{ + ecs_assert(ECS_IS_PAIR(cr->id), ECS_INVALID_PARAMETER, NULL); + ecs_assert(ECS_PAIR_FIRST(cr->id) == EcsChildOf, ECS_INVALID_PARAMETER, NULL); + ecs_assert(cr->pair != NULL, ECS_INVALID_PARAMETER, NULL); + return cr->pair->depth; +} + +static +void flecs_entities_update_childof_depth( + ecs_world_t *world, + ecs_component_record_t *cr) +{ + if (cr->flags & EcsIdOrderedChildren) { + ecs_entity_t *entities = ecs_vec_first(&cr->pair->ordered_children); + int32_t i, count = ecs_vec_count(&cr->pair->ordered_children); + for (i = 0; i < count; i ++) { + ecs_entity_t tgt = entities[i]; + ecs_record_t *r = flecs_entities_get(world, tgt); + ecs_table_t *table = r->table; + + if (table->flags & EcsTableHasParent) { + ecs_add_id(world, tgt, + ecs_value_pair(EcsParentDepth, cr->pair->depth)); + } + + if (!(r->row & EcsEntityIsTraversable)) { + continue; + } + + ecs_component_record_t *tgt_cr = flecs_components_get( + world, ecs_childof(tgt)); + if (!tgt_cr) { + continue; + } + + flecs_component_update_childof_depth(world, tgt_cr, tgt, r); + } + return; + } + + /* If the component record doesn't have a children vector, iterate tables. */ + ecs_table_cache_iter_t it; flecs_component_iter(cr, &it); + const ecs_table_record_t *tr; + while ((tr = flecs_component_next(&it))) { + ecs_table_t *table = tr->hdr.table; + if (!(table->flags & EcsTableHasTraversable)) { + continue; + } + + const ecs_entity_t *entities = ecs_table_entities(table); + int32_t i, count = ecs_table_count(table); + for (i = 0; i < count; i ++) { + ecs_entity_t tgt = entities[i]; + ecs_component_record_t *tgt_cr = flecs_components_get( + world, ecs_childof(tgt)); + if (!tgt_cr) { + continue; + } + + ecs_record_t *r = flecs_entities_get(world, tgt); + flecs_component_update_childof_depth(world, tgt_cr, tgt, r); + } + } +} + +void flecs_component_update_childof_w_depth( + ecs_world_t *world, + ecs_component_record_t *cr, + int32_t depth) +{ + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_pair_record_t *pair = cr->pair; + ecs_assert(pair != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(depth < (FLECS_DAG_DEPTH_MAX + 1), ECS_INVALID_OPERATION, + "possible cycle detected in ChildOf/Parent hierarchy"); + + if (cr->flags & EcsIdMarkedForDelete) { + return; + } + + /* If depth changed, propagate downwards */ + if (depth != pair->depth) { + pair->depth = depth; + flecs_entities_update_childof_depth(world, cr); + } +} + +void flecs_component_update_childof_depth( + ecs_world_t *world, + ecs_component_record_t *cr, + ecs_entity_t tgt, + const ecs_record_t *tgt_r) +{ + ecs_assert(world != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr->pair != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(ECS_PAIR_SECOND(cr->id) == (uint32_t)tgt, + ECS_INTERNAL_ERROR, NULL); + + if (cr->flags & EcsIdMarkedForDelete) { + return; + } + + int32_t new_depth; + if (tgt) { + ecs_table_t *tgt_table = tgt_r->table; + if (tgt_table->flags & EcsTableHasChildOf) { + ecs_pair_record_t *tgt_childof_pr = flecs_table_get_childof_pr( + world, tgt_table); + new_depth = tgt_childof_pr->depth + 1; + } else if (tgt_table->flags & EcsTableHasParent) { + int32_t column = tgt_table->component_map[ecs_id(EcsParent)]; + ecs_assert(column > 0, ECS_INTERNAL_ERROR, NULL); + + EcsParent *data = tgt_table->data.columns[column - 1].data; + ecs_entity_t parent = data[ECS_RECORD_TO_ROW(tgt_r->row)].value; + if (!parent) { + new_depth = 0; + } else { + ecs_component_record_t *cr_parent = flecs_components_get(world, + ecs_childof(parent)); + ecs_assert(cr_parent != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr_parent->pair != NULL, ECS_INTERNAL_ERROR, NULL); + + new_depth = cr_parent->pair->depth + 1; + } + } else { + new_depth = 1; + } + } else { + new_depth = 0; + } + + flecs_component_update_childof_w_depth(world, cr, new_depth); +} #include @@ -38729,6 +40942,452 @@ const uint64_t* flecs_entity_index_ids( } +static +void flecs_add_non_fragmenting_child_to_table( + ecs_world_t *world, + ecs_component_record_t *cr, + ecs_entity_t entity, + const ecs_table_t *table) +{ + ecs_map_init_if(&cr->pair->children_tables, &world->allocator); + ecs_parent_record_t *elem = (ecs_parent_record_t*) + ecs_map_ensure(&cr->pair->children_tables, table->id); + ecs_assert(elem != NULL, ECS_INTERNAL_ERROR, NULL); + + /* Encode id of first entity in table + the total number of entities in the + * table for this parent in a single uint64 so everything fits in a map + * element without having to allocate. */ + if (!elem->count) { + elem->entity = (uint32_t)entity; + + if (table->flags & EcsTableIsDisabled) { + cr->pair->disabled_tables ++; + } + if (table->flags & EcsTableIsPrefab) { + cr->pair->prefab_tables ++; + } + } else { + elem->entity = 0; + } + + elem->count ++; +} + +static +void flecs_remove_non_fragmenting_child_from_table( + ecs_component_record_t *cr, + const ecs_table_t *table) +{ + ecs_parent_record_t *elem = flecs_component_get_parent_record(cr, table); + if (!elem) { + return; + } + + elem->count --; + + if (!elem->count) { + ecs_map_remove(&cr->pair->children_tables, table->id); + if (table->flags & EcsTableIsDisabled) { + cr->pair->disabled_tables --; + ecs_assert(cr->pair->disabled_tables >= 0, + ECS_INTERNAL_ERROR, NULL); + } + if (table->flags & EcsTableIsPrefab) { + cr->pair->prefab_tables --; + ecs_assert(cr->pair->prefab_tables >= 0, + ECS_INTERNAL_ERROR, NULL); + } + } +} + +int flecs_add_non_fragmenting_child_w_records( + ecs_world_t *world, + ecs_entity_t parent, + ecs_entity_t entity, + ecs_component_record_t *cr, + const ecs_record_t *r) +{ + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(r->table != NULL, ECS_INTERNAL_ERROR, NULL); + + (void)parent; + + if (!(cr->flags & EcsIdOrderedChildren)) { + flecs_component_ordered_children_init(world, cr); + flecs_ordered_children_populate(world, cr); + } + + ecs_check(parent != 0, ECS_INVALID_OPERATION, + "cannot set Parent component with 0 entity"); + ecs_check(ecs_is_alive(world, parent), ECS_INVALID_OPERATION, + "cannot set Parent component to entity that is not alive"); + + flecs_ordered_entities_append(world, cr, entity); + + flecs_add_non_fragmenting_child_to_table(world, cr, entity, r->table); + + ecs_record_t *r_parent = flecs_entities_get(world, parent); + if (r_parent->table->flags & EcsTableIsPrefab) { + ecs_add_id(world, entity, EcsPrefab); + } + + return 0; +error: + return -1; +} + +static +ecs_component_record_t* flecs_add_non_fragmenting_child( + ecs_world_t *world, + ecs_entity_t parent, + ecs_entity_t entity) +{ + ecs_component_record_t *cr = flecs_components_ensure(world, + ecs_pair(EcsChildOf, parent)); + ecs_record_t *r = flecs_entities_get(world, entity); + + if (flecs_add_non_fragmenting_child_w_records(world, parent, entity, cr, r)) { + return NULL; + } + + return cr; +} + +static +void flecs_remove_non_fragmenting_child( + ecs_world_t *world, + ecs_entity_t parent, + ecs_entity_t entity) +{ + if (!parent) { + return; + } + + ecs_component_record_t *cr = flecs_components_get(world, + ecs_pair(EcsChildOf, parent)); + if (!cr || (cr->flags & EcsIdMarkedForDelete)) { + return; + } + + flecs_ordered_entities_remove(world, cr, entity); + + ecs_record_t *r = flecs_entities_get(world, entity); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_table_t *table = r->table; + ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + + flecs_remove_non_fragmenting_child_from_table(cr, table); +} + +static +void flecs_on_reparent_update_name( + ecs_world_t *world, + ecs_entity_t e, + EcsIdentifier *name, + ecs_entity_t parent_old, + ecs_component_record_t *cr_parent_new) +{ + if (name->value && name->index_hash) { + /* Remove entity from name index of old parent */ + ecs_component_record_t *old_cr = flecs_components_get( + world, ecs_childof(parent_old)); + if (old_cr) { + ecs_hashmap_t *old_index = + flecs_component_name_index_get(world, old_cr); + if (old_index) { + flecs_name_index_remove(old_index, e, name->index_hash); + } + } + + if (cr_parent_new) { + /* Add entity to name index of new parent */ + ecs_hashmap_t *new_index = + flecs_component_name_index_ensure(world, cr_parent_new); + flecs_name_index_ensure( + new_index, e, name->value, name->length, name->hash); + name->index = new_index; + } else { + name->index = NULL; + } + } +} + +static +void flecs_on_replace_parent(ecs_iter_t *it) { + ecs_world_t *world = it->world; + EcsParent *old = ecs_field(it, EcsParent, 0); + EcsParent *new = ecs_field(it, EcsParent, 1); + + ecs_assert(old != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(new != NULL, ECS_INTERNAL_ERROR, NULL); + + EcsIdentifier *names = NULL; + if (it->table->flags & EcsTableHasName) { + names = ecs_table_get_pair( + world, it->table, EcsIdentifier, EcsName, it->offset); + ecs_assert(names != NULL, ECS_INTERNAL_ERROR, NULL); + } + + int32_t i, count = it->count; + for (i = 0; i < count; i ++) { + ecs_entity_t e = it->entities[i]; + ecs_entity_t old_parent = old[i].value; + ecs_entity_t new_parent = new[i].value; + + /* This can happen when a child is parented to a parent that is deleted + * in the same command queue. */ + if (!flecs_entities_is_alive(world, new_parent)) { + /* So cleanup code can see this is child of deleted parent */ + old[i].value = new_parent; + ecs_delete(world, e); + continue; + } + + #ifdef FLECS_DEBUG + ecs_entity_t cur = new_parent; + while (cur) { + ecs_assert(cur != e, ECS_CYCLE_DETECTED, + "cycle detected in Parent hierarchy"); + cur = ecs_get_parent(world, cur); + } + #endif + + flecs_journal_begin(world, EcsJournalSetParent, e, &(ecs_type_t){ + .count = 1, .array = &new_parent + }, NULL); + + flecs_remove_non_fragmenting_child(world, old_parent, e); + + ecs_component_record_t *cr_parent = + flecs_add_non_fragmenting_child(world, new_parent, e); + if (!cr_parent) { + continue; + } + + if (names) { + flecs_on_reparent_update_name( + world, e, &names[i], old_parent, cr_parent); + } + + int32_t depth = cr_parent->pair->depth; + ecs_add_id(world, e, ecs_value_pair(EcsParentDepth, depth)); + + ecs_component_record_t *cr = flecs_components_get(world, ecs_childof(e)); + if (cr) { + flecs_component_update_childof_w_depth(world, cr, depth + 1); + } + + ecs_record_t *r = flecs_entities_get(world, e); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + + if (r->row & EcsEntityIsTraversable) { + ecs_id_t added = ecs_childof(new_parent); + ecs_id_t removed = ecs_childof(old_parent); + + flecs_update_component_monitors(world, + &(ecs_type_t){ .count = 1, .array = &added }, + &(ecs_type_t) { .count = 1, .array = &removed }); + } + + flecs_journal_end(); + } +} + +void flecs_on_non_fragmenting_child_move_add( + ecs_world_t *world, + const ecs_table_t *dst, + const ecs_table_t *src, + int32_t row, + int32_t count) +{ + ecs_assert(dst->flags & EcsTableHasParent, ECS_INTERNAL_ERROR, NULL); + + EcsParent *parents = ecs_table_get(world, dst, EcsParent, 0); + int32_t i = row, end = i + count; + for (; i < end; i ++) { + ecs_entity_t e = ecs_table_entities(dst)[i]; + ecs_entity_t p = parents[i].value; + + ecs_component_record_t *cr = flecs_components_get( + world, ecs_childof(p)); + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + + if (src && (src->flags & EcsTableHasParent)) { + flecs_remove_non_fragmenting_child_from_table(cr, src); + } + + flecs_add_non_fragmenting_child_to_table(world, cr, e, dst); + } +} + +void flecs_on_non_fragmenting_child_move_remove( + ecs_world_t *world, + const ecs_table_t *dst, + const ecs_table_t *src, + int32_t row, + int32_t count, + bool update_parent_records) +{ + EcsIdentifier *names = NULL; + if (src->flags & EcsTableHasName) { + names = ecs_table_get_pair(world, src, EcsIdentifier, EcsName, 0); + } + + EcsParent *parents = ecs_table_get(world, src, EcsParent, 0); + int32_t i = row, end = i + count; + for (; i < end; i ++) { + ecs_entity_t e = ecs_table_entities(src)[i]; + ecs_entity_t p = parents[i].value; + if (!ecs_is_alive(world, p)) { + continue; + } + + ecs_component_record_t *cr = flecs_components_ensure( + world, ecs_childof(p)); + + if (update_parent_records) { + flecs_remove_non_fragmenting_child_from_table(cr, src); + } + + if (dst && (dst->flags & EcsTableHasParent)) { + if (update_parent_records) { + flecs_add_non_fragmenting_child_to_table(world, cr, e, dst); + } + } else { + flecs_ordered_entities_remove(world, cr, e); + + if (names) { + flecs_on_reparent_update_name(world, e, &names[i], p, NULL); + } + + ecs_component_record_t *cr_e = flecs_components_get( + world, ecs_childof(e)); + if (cr_e) { + flecs_component_update_childof_w_depth(world, cr_e, 1); + } + } + } +} + +void flecs_non_fragmenting_childof_reparent( + ecs_world_t *world, + const ecs_table_t *dst, + const ecs_table_t *src, + int32_t row, + int32_t count) +{ + ecs_assert(dst != NULL, ECS_INTERNAL_ERROR, NULL); + + if (!src) { + return; + } + + ecs_pair_record_t *dst_pair = flecs_table_get_childof_pr(world, dst); + ecs_assert(dst_pair != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_pair_record_t *src_pair = flecs_table_get_childof_pr(world, src); + + int32_t dst_depth = dst_pair->depth; + int32_t src_depth = 0; + if (src_pair) { + src_depth = src_pair->depth; + } + + if (dst_depth == src_depth) { + /* If src depth is dst depth, no need to update cached depth values */ + return; + } + + if (!ecs_table_has_traversable(src)) { + /* If table doesn't contain any traversable entities (meaning there + * can't be any parents in the table) there can't be any cached depth + * values to update. */ + return; + } + + const ecs_entity_t *entities = ecs_table_entities(dst); + int32_t i = row, end = i + count; + for (; i < end; i ++) { + ecs_entity_t e = entities[i]; + ecs_component_record_t *cr = flecs_components_get( + world, ecs_childof(e)); + if (!cr) { + continue; + } + + ecs_record_t *r = flecs_entities_get(world, e); + flecs_component_update_childof_depth(world, cr, e, r); + } +} + +void flecs_non_fragmenting_childof_unparent( + ecs_world_t *world, + const ecs_table_t *dst, + const ecs_table_t *src, + int32_t row, + int32_t count) +{ + ecs_assert(src != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_pair_record_t *dst_pair = flecs_table_get_childof_pr(world, dst); + ecs_pair_record_t *src_pair = flecs_table_get_childof_pr(world, src); + + ecs_assert(src_pair != NULL, ECS_INTERNAL_ERROR, NULL); + + int32_t dst_depth = dst_pair ? dst_pair->depth : 0; + int32_t src_depth = src_pair->depth; + + /* If unparent is called there has to be a difference in depth, since the + * parent is removed from an entity. */ + ecs_assert(src_depth != dst_depth, ECS_INTERNAL_ERROR, NULL); + (void)src_depth; + (void)dst_depth; + + if (!ecs_table_has_traversable(src)) { + /* If table doesn't contain any traversable entities (meaning there + * aren't any parents in the table) there can't be any cached depth + * values to update. */ + return; + } + + const ecs_entity_t *entities = ecs_table_entities(src); + int32_t i = row, end = i + count; + for (; i < end; i ++) { + ecs_entity_t e = entities[i]; + ecs_component_record_t *cr = flecs_components_get( + world, ecs_childof(e)); + if (!cr || (cr->flags & EcsIdMarkedForDelete)) { + continue; + } else { + /* Entity is a parent */ + } + + /* Update depth to 1 if parent is removed */ + flecs_component_update_childof_w_depth(world, cr, 1); + } +} + +bool flecs_component_has_non_fragmenting_childof( + ecs_component_record_t *cr) +{ + if (cr->flags & EcsIdOrderedChildren) { + return ecs_map_count(&cr->pair->children_tables) != 0; + } + return false; +} + +void flecs_bootstrap_parent_component( + ecs_world_t *world) +{ + flecs_type_info_init(world, EcsParent, { + .ctor = flecs_default_ctor, + .on_replace = flecs_on_replace_parent + }); + + ecs_add_pair(world, ecs_id(EcsParent), EcsOnInstantiate, EcsDontInherit); +} + + void flecs_ordered_children_init( ecs_world_t *world, ecs_component_record_t *cr) @@ -38743,14 +41402,15 @@ void flecs_ordered_children_fini( { ecs_vec_fini_t( &world->allocator, &cr->pair->ordered_children, ecs_entity_t); + ecs_map_fini(&cr->pair->children_tables); } void flecs_ordered_children_populate( ecs_world_t *world, ecs_component_record_t *cr) { - ecs_vec_t *v = &cr->pair->ordered_children; - ecs_assert(ecs_vec_count(v) == 0, ECS_INTERNAL_ERROR, NULL); + ecs_assert(ecs_vec_count(&cr->pair->ordered_children) == 0, + ECS_INTERNAL_ERROR, NULL); ecs_assert(ECS_IS_PAIR(cr->id), ECS_INTERNAL_ERROR, NULL); ecs_assert(ECS_PAIR_FIRST(cr->id) == EcsChildOf, ECS_INTERNAL_ERROR, NULL); @@ -38759,8 +41419,7 @@ void flecs_ordered_children_populate( while (ecs_each_next(&it)) { int32_t i; for (i = 0; i < it.count; i ++) { - ecs_vec_append_t( - &world->allocator, v, ecs_entity_t)[0] = it.entities[i]; + flecs_ordered_entities_append(world, cr, it.entities[i]); } } } @@ -38773,73 +41432,97 @@ void flecs_ordered_children_clear( ecs_assert(ECS_PAIR_FIRST(cr->id) == EcsChildOf, ECS_INTERNAL_ERROR, NULL); - ecs_vec_clear(v); + if (!(cr->flags & EcsIdMarkedForDelete)) { + ecs_assert(!ecs_map_count(&cr->pair->children_tables), + ECS_UNSUPPORTED, + "cannot remove OrderedChildren trait from parent that has " + "children which use the Parent component"); + + ecs_vec_clear(v); + } } -static void flecs_ordered_entities_append( ecs_world_t *world, - ecs_pair_record_t *pair, + ecs_component_record_t *cr, ecs_entity_t e) { - ecs_assert(pair != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_pair_record_t *pr = cr->pair; + ecs_assert(pr != NULL, ECS_INTERNAL_ERROR, NULL); ecs_vec_append_t( - &world->allocator, &pair->ordered_children, ecs_entity_t)[0] = e; + &world->allocator, &pr->ordered_children, ecs_entity_t)[0] = e; + + if (cr->flags & EcsIdPrefabChildren) { + /* Register index of prefab child so that it can be used to lookup + * corresponding instance child. */ + ecs_map_ensure(&world->prefab_child_indices, e)[0] = + flecs_ito(uint64_t, ecs_vec_count(&pr->ordered_children) - 1); + } else { + ecs_assert( + !ecs_owns_id(world, ecs_pair_second(world, cr->id), EcsPrefab), + ECS_INTERNAL_ERROR, NULL); + } } -static void flecs_ordered_entities_remove( - ecs_pair_record_t *pair, + ecs_world_t *world, + ecs_component_record_t *cr, ecs_entity_t e) { - ecs_assert(pair != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr->pair != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_vec_t *vec = &pair->ordered_children; + ecs_vec_t *vec = &cr->pair->ordered_children; int32_t i, count = ecs_vec_count(vec); ecs_entity_t *entities = ecs_vec_first_t(vec, ecs_entity_t); for (i = 0; i < count; i ++) { if (entities[i] == e) { ecs_vec_remove_ordered_t(vec, ecs_entity_t, i); + if (cr->flags & EcsIdPrefabChildren) { + ecs_map_remove(&world->prefab_child_indices, e); + } + break; } } } static void flecs_ordered_entities_unparent_internal( - const ecs_table_t *table, + ecs_world_t *world, const ecs_table_t *entities_table, + const ecs_table_t *table, int32_t row, int32_t count) { if (table && (table->flags & EcsTableHasOrderedChildren)) { - ecs_pair_record_t *pair = table->_->childof_r; + ecs_component_record_t *cr = flecs_table_get_childof_cr(world, table); const ecs_entity_t *entities = ecs_table_entities(entities_table); int32_t i = row, end = row + count; for (; i < end; i ++) { ecs_entity_t e = entities[i]; - flecs_ordered_entities_remove(pair, e); + flecs_ordered_entities_remove(world, cr, e); } } } void flecs_ordered_children_reparent( ecs_world_t *world, - const ecs_table_t *src, const ecs_table_t *dst, + const ecs_table_t *src, int32_t row, int32_t count) { - flecs_ordered_entities_unparent_internal(src, dst, row, count); + flecs_ordered_entities_unparent_internal(world, dst, src, row, count); if (dst->flags & EcsTableHasOrderedChildren) { - ecs_pair_record_t *pair = dst->_->childof_r; + ecs_component_record_t *cr = flecs_table_get_childof_cr(world, dst); const ecs_entity_t *entities = ecs_table_entities(dst); int32_t i = row, end = row + count; for (; i < end; i ++) { ecs_entity_t e = entities[i]; - flecs_ordered_entities_append(world, pair, e); + flecs_ordered_entities_append(world, cr, e); } } } @@ -38851,7 +41534,7 @@ void flecs_ordered_children_unparent( int32_t count) { (void)world; - flecs_ordered_entities_unparent_internal(src, src, row, count); + flecs_ordered_entities_unparent_internal(world, src, src, row, count); } void flecs_ordered_children_reorder( @@ -39070,10 +41753,7 @@ ecs_entity_t flecs_component_sparse_remove_intern( &entity, cr->id, ti, EcsOnRemove, on_remove); } - ecs_xtor_t dtor = ti->hooks.dtor; - if (dtor) { - dtor(ptr, 1, ti); - } + flecs_type_info_dtor(ptr, 1, ti); flecs_sparse_remove(cr->sparse, 0, entity); @@ -39093,18 +41773,6 @@ void flecs_component_sparse_dont_fragment_pair_remove( return; } - ecs_entity_t tgt = ecs_pair_second(world, cr->id); - if (!tgt) { - /* It's possible that the target entity is cleaned up as part of the - * same entity that holds the relationship. If that's the case, the - * relationship will get cleaned up later anyway so we can exit here. */ - if (!(world->flags & EcsWorldFini)) { - ecs_assert(cr->flags & EcsIdMarkedForDelete, - ECS_INTERNAL_ERROR, NULL); - } - return; - } - ecs_type_t *type = flecs_sparse_get_t( parent->sparse, ecs_type_t, entity); if (!type) { @@ -39114,7 +41782,7 @@ void flecs_component_sparse_dont_fragment_pair_remove( ecs_assert(type->count > 0, ECS_INTERNAL_ERROR, NULL); int32_t old_type_count = type->count; - flecs_type_remove(world, type, tgt); + flecs_type_remove_ignoring_generation(world, type, ECS_PAIR_SECOND(cr->id)); ecs_assert(type->count != old_type_count, ECS_INTERNAL_ERROR, NULL); (void)old_type_count; @@ -39211,7 +41879,7 @@ void flecs_component_sparse_remove_all_id( const ecs_type_info_t *ti = cr->type_info; if (ti) { ecs_iter_action_t on_remove = ti->hooks.on_remove; - ecs_xtor_t dtor = ti->hooks.dtor; + bool dtor = ti->hooks.dtor != NULL; if (on_remove) { for (i = 0; i < count; i ++) { @@ -39226,7 +41894,7 @@ void flecs_component_sparse_remove_all_id( if (dtor) { for (i = 0; i < count; i ++) { void *ptr = flecs_sparse_get_dense(sparse, 0, i); - dtor(ptr, 1, ti); + flecs_type_info_dtor(ptr, 1, ti); } } } @@ -39372,19 +42040,13 @@ void flecs_component_sparse_override( } } - ecs_xtor_t ctor = ti->hooks.ctor; if (!override_ptr) { - if (ctor) { - ctor(ptr, 1, ti); - } + flecs_type_info_ctor(ptr, 1, ti); } else { - ecs_copy_t copy = ti->hooks.copy_ctor; - if (copy) { - copy(ptr, override_ptr, 1, ti); + if (ti->hooks.copy_ctor) { + flecs_type_info_copy_ctor(ptr, override_ptr, 1, ti); } else { - if (ctor) { - ctor(ptr, 1, ti); - } + flecs_type_info_ctor(ptr, 1, ti); ecs_os_memcpy(ptr, override_ptr, ti->size); } } @@ -39717,6 +42379,8 @@ void flecs_table_init_flags( table->_->parent.id = 0; #endif + table->childof_index = -1; + int32_t i; for (i = 0; i < count; i ++) { ecs_id_t id = ids[i]; @@ -39733,60 +42397,109 @@ void flecs_table_init_flags( table->flags |= EcsTableIsDisabled; } else if (id == EcsNotQueryable) { table->flags |= EcsTableNotQueryable; - } else { - if (ECS_IS_PAIR(id)) { - ecs_entity_t r = ECS_PAIR_FIRST(id); - - table->flags |= EcsTableHasPairs; - - if (r == EcsIsA) { - table->flags |= EcsTableHasIsA; - } else if (r == EcsChildOf) { - table->flags |= EcsTableHasChildOf; - ecs_entity_t tgt = ecs_pair_second(world, id); - ecs_assert(tgt != 0, ECS_INTERNAL_ERROR, NULL); + } else if (id == ecs_id(EcsParent)) { + table->flags |= EcsTableHasParent; + table->trait_flags |= EcsIdTraversable; + } else if (ECS_PAIR_FIRST(id) == EcsWith) { + table->trait_flags |= EcsIdWith; + } else if (ECS_PAIR_FIRST(id) == EcsOnDelete) { + ecs_entity_t on_delete_kind = ECS_PAIR_SECOND(id); + if (on_delete_kind == EcsRemove) { + table->trait_flags |= EcsIdOnDeleteRemove; + } else if (on_delete_kind == EcsDelete) { + table->trait_flags |= EcsIdOnDeleteDelete; + } else if (on_delete_kind == EcsPanic) { + table->trait_flags |= EcsIdOnDeletePanic; + } + } else if (ECS_PAIR_FIRST(id) == EcsOnDeleteTarget) { + ecs_entity_t on_delete_kind = ECS_PAIR_SECOND(id); + if (on_delete_kind == EcsRemove) { + table->trait_flags |= EcsIdOnDeleteTargetRemove; + } else if (on_delete_kind == EcsDelete) { + table->trait_flags |= EcsIdOnDeleteTargetDelete; + } else if (on_delete_kind == EcsPanic) { + table->trait_flags |= EcsIdOnDeleteTargetPanic; + } + } else if (ECS_PAIR_FIRST(id) == EcsOnInstantiate) { + ecs_entity_t inherit_kind = ECS_PAIR_SECOND(id); + if (inherit_kind == EcsInherit) { + table->trait_flags |= EcsIdOnInstantiateInherit; + } else if (inherit_kind == EcsDontInherit) { + table->trait_flags |= EcsIdOnInstantiateDontInherit; + } else if (inherit_kind == EcsOverride) { + table->trait_flags |= EcsIdOnInstantiateOverride; + } + } else if (id == EcsCanToggle) { + table->trait_flags |= EcsIdCanToggle; + } else if (id == EcsInheritable) { + table->trait_flags |= EcsIdInheritable; + } else if (id == EcsSingleton) { + table->trait_flags |= EcsIdSingleton; + } else if (id == EcsSparse) { + table->trait_flags |= EcsIdSparse; + } else if (id == EcsDontFragment) { + table->trait_flags |= EcsIdDontFragment; + } else if (id == EcsExclusive) { + table->trait_flags |= EcsIdExclusive; + } else if (id == EcsTraversable) { + table->trait_flags |= EcsIdTraversable; + } else if (id == EcsPairIsTag) { + table->trait_flags |= EcsIdPairIsTag; + } else if (id == EcsTransitive) { + table->trait_flags |= EcsIdIsTransitive; + } else if (ECS_IS_PAIR(id)) { + ecs_entity_t r = ECS_PAIR_FIRST(id); + + table->flags |= EcsTableHasPairs; + + if (r == EcsIsA) { + table->flags |= EcsTableHasIsA; + } else if (r == EcsChildOf) { + table->flags |= EcsTableHasChildOf; + table->childof_index = flecs_ito(int16_t, i); + + ecs_entity_t tgt = ecs_pair_second(world, id); + ecs_assert(tgt != 0, ECS_INTERNAL_ERROR, NULL); - /* If table contains entities that are inside one of the - * builtin modules, it contains builtin entities */ + /* If table contains entities that are inside one of the + * builtin modules, it contains builtin entities */ - if (tgt == EcsFlecsCore || tgt == EcsFlecsInternals) { - table->flags |= EcsTableHasBuiltins; - table->flags |= EcsTableHasModule; - } + if (tgt == EcsFlecsCore) { + table->flags |= EcsTableHasBuiltins; + } - if (ecs_has_id(world, tgt, EcsModule)) { - table->flags |= EcsTableHasModule; - } + if (ecs_has_id(world, tgt, EcsModule)) { + table->flags |= EcsTableHasModule; + } #ifdef FLECS_DEBUG_INFO - table->_->parent.id = tgt; + table->_->parent.id = tgt; #endif - } else if (id == ecs_pair_t(EcsIdentifier, EcsName)) { - table->flags |= EcsTableHasName; + } else if (id == ecs_pair_t(EcsIdentifier, EcsName)) { + table->flags |= EcsTableHasName; #ifdef FLECS_DEBUG_INFO - table->_->name_column = flecs_ito(int16_t, i); + table->_->name_column = flecs_ito(int16_t, i); #endif - } else if (r == ecs_id(EcsPoly)) { - table->flags |= EcsTableHasModule; - } + } else if (r == ecs_id(EcsPoly)) { + table->flags |= EcsTableHasModule; + } #if defined(FLECS_DEBUG_INFO) && defined(FLECS_DOC) - else if (id == ecs_pair_t(EcsDocDescription, EcsName)) { - table->_->doc_name_column = flecs_ito(int16_t, i); - } + else if (id == ecs_pair_t(EcsDocDescription, EcsName)) { + table->_->doc_name_column = flecs_ito(int16_t, i); + } #endif - } else { - if (ECS_HAS_ID_FLAG(id, TOGGLE)) { - ecs_table__t *meta = table->_; - table->flags |= EcsTableHasToggle; + } else { + if (ECS_HAS_ID_FLAG(id, TOGGLE)) { + ecs_table__t *meta = table->_; + table->flags |= EcsTableHasToggle; - if (!meta->bs_count) { - meta->bs_offset = flecs_ito(int16_t, i); - } - meta->bs_count ++; - } - if (ECS_HAS_ID_FLAG(id, AUTO_OVERRIDE)) { - table->flags |= EcsTableHasOverrides; + if (!meta->bs_count) { + meta->bs_offset = flecs_ito(int16_t, i); } + meta->bs_count ++; + } + if (ECS_HAS_ID_FLAG(id, AUTO_OVERRIDE)) { + table->flags |= EcsTableHasOverrides; } } } @@ -40108,7 +42821,7 @@ void flecs_table_init( } int32_t last_pair = -1; - bool has_childof = table->flags & EcsTableHasChildOf; + bool has_childof = !!(table->flags & (EcsTableHasChildOf|EcsTableHasParent)); if (first_pair != -1) { /* Add a (Relationship, *) record for each relationship. */ ecs_entity_t r = 0; @@ -40149,6 +42862,11 @@ void flecs_table_init( * linear scan to find all occurrences for a target. */ for (dst_i = first_pair; dst_i < last_pair; dst_i ++) { ecs_id_t dst_id = dst_ids[dst_i]; + + if (ECS_IS_VALUE_PAIR(dst_id)) { + continue; + } + ecs_id_t tgt_id = ecs_pair(EcsWildcard, ECS_PAIR_SECOND(dst_id)); flecs_table_append_to_records( @@ -40239,30 +42957,24 @@ void flecs_table_init( /* Initialize event flags for any record */ table->flags |= world->cr_any->flags & EcsIdEventMask; - table->component_map = flecs_wcalloc_n( - world, int16_t, FLECS_HI_COMPONENT_ID); + table->component_map = ecs_os_calloc_n(int16_t, FLECS_HI_COMPONENT_ID); if (column_count) { - table->column_map = flecs_walloc_n(world, int16_t, - dst_count + column_count); + table->column_map = ecs_os_calloc_n(int16_t, dst_count + column_count); } table->column_count = flecs_ito(int16_t, column_count); table->version = 1; flecs_table_init_data(world, table); - /* If the table doesn't have an explicit ChildOf pair, it will be in the - * root which is registered with the (ChildOf, 0) index. */ - ecs_assert(childof_cr != NULL, ECS_INTERNAL_ERROR, NULL); - - if (table->flags & EcsTableHasName) { - flecs_component_name_index_ensure(world, childof_cr); - ecs_assert(childof_cr->pair->name_index != NULL, - ECS_INTERNAL_ERROR, NULL); + if (childof_cr) { + if (table->flags & EcsTableHasName) { + flecs_component_name_index_ensure(world, childof_cr); + ecs_assert(childof_cr->pair->name_index != NULL, + ECS_INTERNAL_ERROR, NULL); + } } - table->_->childof_r = childof_cr->pair; - /* If table has IsA pairs, create overrides cache */ if (isa_tr) { flecs_table_init_overrides(world, table, isa_tr); @@ -40348,7 +43060,7 @@ void flecs_table_notify_on_remove( ecs_table_diff_t diff = ECS_TABLE_DIFF_INIT; diff.removed = table->type; diff.removed_flags = table->flags & EcsTableRemoveEdgeFlags; - flecs_notify_on_remove(world, table, NULL, 0, count, &diff); + flecs_actions_move_remove(world, table, &world->store.root, 0, count, &diff); } } @@ -40395,17 +43107,12 @@ void flecs_table_invoke_ctor_for_array( void *base_ptr = ecs_ref_get_id(world, r, r->id); ecs_assert(base_ptr != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_copy_t copy = ti->hooks.copy_ctor; ecs_iter_action_t on_set = ti->hooks.on_set; ecs_size_t size = ti->size; int32_t i; for (i = 0; i < count; i ++) { - if (copy) { - copy(ptr, base_ptr, 1, ti); - } else { - ecs_os_memcpy(ptr, base_ptr, size); - } + flecs_type_info_copy_ctor(ptr, base_ptr, 1, ti); ptr = ECS_OFFSET(ptr, size); } @@ -40425,10 +43132,7 @@ void flecs_table_invoke_ctor_for_array( } } - ecs_xtor_t ctor = ti->hooks.ctor; - if (ctor) { - ctor(ptr, count, ti); - } + flecs_type_info_ctor(ptr, count, ti); } static @@ -40459,11 +43163,8 @@ void flecs_table_invoke_dtor( ecs_assert(column->data != NULL, ECS_INTERNAL_ERROR, NULL); ecs_type_info_t *ti = column->ti; ecs_assert(ti != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_xtor_t dtor = ti->hooks.dtor; - if (dtor) { - void *ptr = ECS_ELEM(column->data, ti->size, row); - dtor(ptr, count, ti); - } + void *ptr = ECS_ELEM(column->data, ti->size, row); + flecs_type_info_dtor(ptr, count, ti); } /* Run hooks that get invoked when component is added to entity */ @@ -40625,7 +43326,7 @@ void flecs_table_fini_data( for (c = 0; c < column_count; c ++) { ecs_column_t *column = &columns[c]; ecs_vec_t v = ecs_vec_from_column(column, table, column->ti->size); - ecs_vec_fini(&world->allocator, &v, column->ti->size); + ecs_vec_fini(NULL, &v, column->ti->size); column->data = NULL; } @@ -40657,7 +43358,7 @@ void flecs_table_fini_data( if (deallocate) { ecs_vec_t v = ecs_vec_from_entities(table); - ecs_vec_fini_t(&world->allocator, &v, ecs_entity_t); + ecs_vec_fini_t(NULL, &v, ecs_entity_t); table->data.entities = NULL; table->data.size = 0; } @@ -40665,6 +43366,8 @@ void flecs_table_fini_data( table->data.count = 0; table->_->traversable_count = 0; table->flags &= ~EcsTableHasTraversable; + + flecs_increment_table_version(world, table); } const ecs_entity_t* ecs_table_entities( @@ -40674,7 +43377,6 @@ const ecs_entity_t* ecs_table_entities( return table->data.entities; } -/* Cleanup, no OnRemove, retain allocations */ void ecs_table_clear_entities( ecs_world_t* world, ecs_table_t* table) @@ -40682,7 +43384,6 @@ void ecs_table_clear_entities( flecs_table_fini_data(world, table, true, false); } -/* Cleanup, run OnRemove, free allocations */ void flecs_table_delete_entities( ecs_world_t *world, ecs_table_t *table) @@ -40710,6 +43411,9 @@ void flecs_table_fini( bool is_root = table == &world->store.root; ecs_assert(!table->_->lock, ECS_LOCKED_STORAGE, FLECS_LOCKED_STORAGE_MSG("table deletion")); + ecs_assert((world->flags & EcsWorldFini) || !table->keep, ECS_INVALID_OPERATION, + "cannot delete table (still in use): '[%s]'", + flecs_errstr(ecs_table_str(world, table))); ecs_assert(is_root || table->id != 0, ECS_INTERNAL_ERROR, NULL); ecs_assert(is_root || flecs_sparse_is_alive(&world->store.tables, table->id), ECS_INTERNAL_ERROR, NULL); @@ -40748,9 +43452,8 @@ void flecs_table_fini( flecs_table_fini_overrides(world, table); flecs_wfree_n(world, int32_t, table->column_count + 1, table->dirty_state); - flecs_wfree_n(world, int16_t, table->column_count + table->type.count, - table->column_map); - flecs_wfree_n(world, int16_t, FLECS_HI_COMPONENT_ID, table->component_map); + ecs_os_free(table->column_map); + ecs_os_free(table->component_map); flecs_table_records_unregister(world, table); /* Update counters */ @@ -40981,21 +43684,19 @@ void flecs_table_grow_column( /* If the array could possibly realloc and the component has a move action * defined, move old elements manually */ - ecs_move_t move_ctor; - if (count && can_realloc && (move_ctor = ti->hooks.ctor_move_dtor)) { + if (count && can_realloc && ti->hooks.ctor_move_dtor) { ecs_assert(ti->hooks.ctor != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(move_ctor != NULL, ECS_INTERNAL_ERROR, NULL); /* Create vector */ ecs_vec_t dst; - ecs_vec_init(&world->allocator, &dst, elem_size, dst_size); + ecs_vec_init(NULL, &dst, elem_size, dst_size); dst.count = dst_count; void *src_buffer = column->array; void *dst_buffer = dst.array; /* Move (and construct) existing elements to new vector */ - move_ctor(dst_buffer, src_buffer, count, ti); + flecs_type_info_ctor_move_dtor(dst_buffer, src_buffer, count, ti); if (construct) { /* Construct new element(s) */ @@ -41004,16 +43705,16 @@ void flecs_table_grow_column( } /* Free old vector */ - ecs_vec_fini(&world->allocator, column, elem_size); + ecs_vec_fini(NULL, column, elem_size); *column = dst; } else { /* If array won't realloc or has no move, simply add new elements */ if (can_realloc) { - ecs_vec_set_size(&world->allocator, column, elem_size, dst_size); + ecs_vec_set_size(NULL, column, elem_size, dst_size); } - ecs_vec_grow(&world->allocator, column, elem_size, to_add); + ecs_vec_grow(NULL, column, elem_size, to_add); if (construct) { flecs_table_invoke_ctor_for_array( @@ -41043,11 +43744,12 @@ int32_t flecs_table_grow_data( /* Add entity to column with entity ids */ ecs_vec_t v_entities = ecs_vec_from_entities(table); - ecs_vec_set_size_t(&world->allocator, &v_entities, ecs_entity_t, size); + ecs_vec_set_size_t(NULL, &v_entities, ecs_entity_t, size); ecs_entity_t *e = NULL; + if (size) { - e = ecs_vec_last_t(&v_entities, ecs_entity_t) + 1; + e = ECS_ELEM_T(v_entities.array, ecs_entity_t, v_entities.count); } v_entities.count += to_add; @@ -41104,9 +43806,6 @@ int32_t flecs_table_grow_data( /* If the table is monitored indicate that there has been a change */ flecs_table_mark_table_dirty(world, table, 0); - /* Mark columns as potentially reallocated */ - flecs_increment_table_column_version(world, table); - /* Return index of first added entity */ return count; } @@ -41114,7 +43813,6 @@ int32_t flecs_table_grow_data( /* Append operation for tables that don't have any complex logic */ static void flecs_table_fast_append( - ecs_world_t *world, ecs_table_t *table) { /* Add elements to each column array */ @@ -41124,13 +43822,13 @@ void flecs_table_fast_append( ecs_column_t *column = &columns[i]; const ecs_type_info_t *ti = column->ti; ecs_vec_t v = ecs_vec_from_column(column, table, ti->size); - ecs_vec_append(&world->allocator, &v, ti->size); + ecs_vec_append(NULL, &v, ti->size); column->data = v.array; } } /* Append entity to table */ -int32_t flecs_table_append( +void flecs_table_append( ecs_world_t *world, ecs_table_t *table, ecs_entity_t entity, @@ -41151,8 +43849,7 @@ int32_t flecs_table_append( /* Grow buffer with entity ids, set new element to new entity */ ecs_vec_t v_entities = ecs_vec_from_entities(table); - ecs_entity_t *e = ecs_vec_append_t(&world->allocator, - &v_entities, ecs_entity_t); + ecs_entity_t *e = ecs_vec_append_t(NULL, &v_entities, ecs_entity_t); ecs_assert(e != NULL, ECS_INTERNAL_ERROR, NULL); ecs_entity_t *entities = table->data.entities = v_entities.array; @@ -41160,15 +43857,14 @@ int32_t flecs_table_append( /* If the table is monitored indicate that there has been a change */ flecs_table_mark_table_dirty(world, table, 0); - flecs_increment_table_column_version(world, table); ecs_assert(count >= 0, ECS_INTERNAL_ERROR, NULL); /* Fast path: no switch columns, no lifecycle actions */ if (!(table->flags & (EcsTableIsComplex|EcsTableHasIsA))) { - flecs_table_fast_append(world, table); + flecs_table_fast_append(table); table->data.count = v_entities.count; table->data.size = v_entities.size; - return count; + return; } flecs_table_update_overrides(world, table); @@ -41218,8 +43914,6 @@ int32_t flecs_table_append( } flecs_table_check_sanity(table); - - return count; } /* Delete operation for tables that don't have any complex logic */ @@ -41323,21 +44017,14 @@ void flecs_table_delete( EcsOnRemove, column, &entity_to_delete, row, 1); } - ecs_move_t move_dtor = ti->hooks.move_dtor; - /* If neither move nor move_ctor are set, this indicates that * non-destructive move semantics are not supported for this - * type. In such cases, we set the move_dtor as ctor_move_dtor, - * which indicates a destructive move operation. This adjustment - * ensures compatibility with different language bindings. */ + * type. In such cases, use ctor_move_dtor for destructive move + * semantics to ensure compatibility with language bindings. */ if (!ti->hooks.move_ctor && ti->hooks.ctor_move_dtor) { - move_dtor = ti->hooks.ctor_move_dtor; - } - - if (move_dtor) { - move_dtor(dst, src, 1, ti); + flecs_type_info_ctor_move_dtor(dst, src, 1, ti); } else { - ecs_os_memcpy(dst, src, size); + flecs_type_info_move_dtor(dst, src, 1, ti); } } } else { @@ -41450,18 +44137,14 @@ void flecs_table_move( void *dst = ECS_ELEM(dst_column->data, size, dst_index); void *src = ECS_ELEM(src_column->data, size, src_index); - ecs_move_t move = ti->hooks.move_ctor; - if (use_move_dtor || !move) { + bool use_ctor_move_dtor = use_move_dtor || !ti->hooks.move_ctor; + if (use_ctor_move_dtor) { /* Also use move_dtor if component doesn't have a move_ctor * registered, to ensure that the dtor gets called to * cleanup resources. */ - move = ti->hooks.ctor_move_dtor; - } - - if (move) { - move(dst, src, 1, ti); + flecs_type_info_ctor_move_dtor(dst, src, 1, ti); } else { - ecs_os_memcpy(dst, src, size); + flecs_type_info_move_ctor(dst, src, 1, ti); } } else { if (dst_id < src_id) { @@ -41532,53 +44215,42 @@ bool flecs_table_shrink( bool has_payload = table->data.entities != NULL; - int32_t old_size = table->data.size; int32_t count = table->data.count; if (count == table->data.size) { return has_payload; } - ecs_allocator_t *a = &world->allocator; ecs_column_t *columns = table->data.columns; ecs_entity_t *entities = table->data.entities; if (count) { ecs_assert(table->data.entities != NULL, ECS_INTERNAL_ERROR, NULL); - table->data.entities = flecs_alloc_n(a, ecs_entity_t, count); + table->data.entities = ecs_os_malloc_n(ecs_entity_t, count); ecs_os_memcpy_n(table->data.entities, entities, ecs_entity_t, count); } else { table->data.entities = NULL; } - flecs_free_n(a, ecs_entity_t, old_size, entities); + ecs_os_free(entities); int32_t i, column_count = table->column_count; for (i = 0; i < column_count; i ++) { const ecs_type_info_t *ti = columns[i].ti; ecs_size_t component_size = ti->size; - ecs_move_t move = ti->hooks.ctor_move_dtor; void *data = columns[i].data; if (count) { - columns[i].data = flecs_alloc(a, component_size * count); - - if (move) { - move(columns[i].data, data, count, ti); - } else { - ecs_assert(columns[i].data != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_os_memcpy(columns[i].data, data, component_size * count); - } + columns[i].data = ecs_os_malloc(component_size * count); + flecs_type_info_ctor_move_dtor(columns[i].data, data, count, ti); } else { columns[i].data = NULL; } - flecs_free(a, component_size * old_size, data); + ecs_os_free(data); } table->data.size = count; - flecs_increment_table_column_version(world, table); - flecs_table_mark_table_dirty(world, table, 0); flecs_table_check_sanity(table); @@ -41677,19 +44349,17 @@ void flecs_table_swap( void *el_1 = ECS_ELEM(ptr, size, row_1); void *el_2 = ECS_ELEM(ptr, size, row_2); - ecs_move_t move = ti->hooks.move; - if (!move) { + bool move_hook = ti->hooks.move != NULL; + if (!move_hook) { ecs_os_memcpy(tmp, el_1, size); ecs_os_memcpy(el_1, el_2, size); ecs_os_memcpy(el_2, tmp, size); } else { - ecs_move_t move_ctor = ti->hooks.move_ctor; - ecs_move_t move_dtor = ti->hooks.move_dtor; - ecs_assert(move_ctor != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(move_dtor != NULL, ECS_INTERNAL_ERROR, NULL); - move_ctor(tmp, el_1, 1, ti); - move(el_1, el_2, 1, ti); - move_dtor(el_2, tmp, 1, ti); + ecs_assert(ti->hooks.move_ctor != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(ti->hooks.move_dtor != NULL, ECS_INTERNAL_ERROR, NULL); + flecs_type_info_move_ctor(tmp, el_1, 1, ti); + flecs_type_info_move(el_1, el_2, 1, ti); + flecs_type_info_move_dtor(el_2, tmp, 1, ti); } } @@ -41698,7 +44368,6 @@ void flecs_table_swap( static void flecs_table_merge_vec( - ecs_world_t *world, ecs_vec_t *dst, ecs_vec_t *src, int32_t size, @@ -41707,7 +44376,7 @@ void flecs_table_merge_vec( int32_t dst_count = dst->count; if (!dst_count) { - ecs_vec_fini(&world->allocator, dst, size); + ecs_vec_fini(NULL, dst, size); *dst = *src; src->array = NULL; src->count = 0; @@ -41716,17 +44385,15 @@ void flecs_table_merge_vec( int32_t src_count = src->count; if (elem_size) { - ecs_vec_set_size(&world->allocator, - dst, size, elem_size); + ecs_vec_set_size(NULL, dst, size, elem_size); } - ecs_vec_set_count(&world->allocator, - dst, size, dst_count + src_count); + ecs_vec_set_count(NULL, dst, size, dst_count + src_count); void *dst_ptr = ECS_ELEM(dst->array, size, dst_count); void *src_ptr = src->array; ecs_os_memcpy(dst_ptr, src_ptr, size * src_count); - ecs_vec_fini(&world->allocator, src, size); + ecs_vec_fini(NULL, src, size); } } @@ -41746,7 +44413,7 @@ void flecs_table_merge_column( int32_t dst_count = ecs_vec_count(dst_vec); if (!dst_count) { - ecs_vec_fini(&world->allocator, dst_vec, elem_size); + ecs_vec_fini(NULL, dst_vec, elem_size); *dst_vec = *src_vec; /* If the new table is not empty, copy the contents from the @@ -41760,14 +44427,9 @@ void flecs_table_merge_column( /* Move values into column */ ecs_assert(ti != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_move_t move = ti->hooks.ctor_move_dtor; - if (move) { - move(dst_ptr, src_ptr, src_count, ti); - } else { - ecs_os_memcpy(dst_ptr, src_ptr, elem_size * src_count); - } + flecs_type_info_ctor_move_dtor(dst_ptr, src_ptr, src_count, ti); - ecs_vec_fini(&world->allocator, src_vec, elem_size); + ecs_vec_fini(NULL, src_vec, elem_size); } dst->data = dst_vec->array; @@ -41797,12 +44459,11 @@ void flecs_table_merge_data( /* Merge entities */ ecs_vec_t dst_entities = ecs_vec_from_entities(dst_table); ecs_vec_t src_entities = ecs_vec_from_entities(src_table); - flecs_table_merge_vec(world, &dst_entities, &src_entities, + flecs_table_merge_vec( &dst_entities, &src_entities, ECS_SIZEOF(ecs_entity_t), 0); ecs_assert(dst_entities.count == src_count + dst_count, ECS_INTERNAL_ERROR, NULL); int32_t column_size = dst_entities.size; - ecs_allocator_t *a = &world->allocator; for (; (i_new < dst_column_count) && (i_old < src_column_count); ) { ecs_column_t *dst_column = &dst_columns[i_new]; @@ -41825,14 +44486,14 @@ void flecs_table_merge_data( i_old ++; } else if (dst_id < src_id) { /* New column, make sure vector is large enough. */ - ecs_vec_set_size(a, &dst_vec, dst_elem_size, column_size); + ecs_vec_set_size(NULL, &dst_vec, dst_elem_size, column_size); dst_column->data = dst_vec.array; flecs_table_invoke_ctor(world, dst_table, i_new, dst_count, src_count); i_new ++; } else if (dst_id > src_id) { /* Old column does not occur in new table, destruct */ flecs_table_invoke_dtor(src_column, 0, src_count); - ecs_vec_fini(a, &src_vec, src_elem_size); + ecs_vec_fini(NULL, &src_vec, src_elem_size); src_column->data = NULL; i_old ++; } @@ -41847,7 +44508,7 @@ void flecs_table_merge_data( int32_t elem_size = column->ti->size; ecs_assert(elem_size != 0, ECS_INTERNAL_ERROR, NULL); ecs_vec_t vec = ecs_vec_from_column(column, dst_table, elem_size); - ecs_vec_set_size(a, &vec, elem_size, column_size); + ecs_vec_set_size(NULL, &vec, elem_size, column_size); column->data = vec.array; flecs_table_invoke_ctor(world, dst_table, i_new, dst_count, src_count); } @@ -41859,16 +44520,13 @@ void flecs_table_merge_data( ecs_assert(elem_size != 0, ECS_INTERNAL_ERROR, NULL); flecs_table_invoke_dtor(column, 0, src_count); ecs_vec_t vec = ecs_vec_from_column(column, src_table, elem_size); - ecs_vec_fini(a, &vec, elem_size); + ecs_vec_fini(NULL, &vec, elem_size); column->data = vec.array; } /* Mark entity column as dirty */ flecs_table_mark_table_dirty(world, dst_table, 0); - /* Mark columns as potentially reallocated */ - flecs_increment_table_column_version(world, dst_table); - dst_table->data.entities = dst_entities.array; dst_table->data.count = dst_entities.count; dst_table->data.size = dst_entities.size; @@ -42069,6 +44727,65 @@ const ecs_ref_t* flecs_table_get_override( return r; } +void flecs_table_keep( + ecs_table_t *table) +{ + table->keep ++; +} + +void flecs_table_release( + ecs_table_t *table) +{ + table->keep --; + ecs_assert(table->keep >= 0, ECS_INTERNAL_ERROR, NULL); +} + +ecs_component_record_t* flecs_table_get_childof_cr( + const ecs_world_t *world, + const ecs_table_t *table) +{ + if (!table) { + return NULL; + } + + int16_t index = table->childof_index; + if (index == -1) { + return world->cr_childof_0; + } else { + return table->_->records[index].hdr.cr; + } +} + +ecs_pair_record_t* flecs_table_get_childof_pr( + const ecs_world_t *world, + const ecs_table_t *table) +{ + if (!table) { + return NULL; + } + + ecs_component_record_t *cr = flecs_table_get_childof_cr(world, table); + if (cr) { + return cr->pair; + } + return NULL; +} + +ecs_hashmap_t* flecs_table_get_name_index( + const ecs_world_t *world, + const ecs_table_t *table) +{ + if (!table) { + return NULL; + } + + ecs_pair_record_t *pr = flecs_table_get_childof_pr(world, table); + if (pr) { + return pr->name_index; + } + return NULL; +} + /* -- Public API -- */ @@ -42298,7 +45015,7 @@ ecs_entity_t ecs_table_get_target( return 0; } - if (index > tr->count) { + if ((index < 0) || (index >= tr->count)) { return 0; } @@ -42720,7 +45437,7 @@ int flecs_type_find( if (ecs_id_match(cur, id)) { return i; } - if (cur > id) { + if (!ECS_IS_PAIR(id) && (cur > id)) { return -1; } } @@ -42728,6 +45445,23 @@ int flecs_type_find( return -1; } +static +int flecs_type_find_ignoring_generation( + const ecs_type_t *type, + ecs_id_t id) +{ + ecs_id_t *array = type->array; + int32_t i, count = type->count; + + for (i = 0; i < count; i ++) { + if ((uint32_t)array[i] == (uint32_t)id) { + return i; + } + } + + return -1; +} + /* Count number of matching ids */ static int flecs_type_count_matches( @@ -42863,6 +45597,9 @@ int flecs_type_new_without( ecs_id_t *dst_array = flecs_walloc_n(world, ecs_id_t, dst_count); dst->array = dst_array; + ecs_assert(dst_array != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(src_array != NULL, ECS_INTERNAL_ERROR, NULL); + if (at) { ecs_os_memcpy_n(dst_array, src_array, ecs_id_t, at); } @@ -42876,6 +45613,51 @@ int flecs_type_new_without( return 0; } +/* Create type from source type without entity id, ignoring generation */ +static +int flecs_type_new_without_ignoring_generation( + ecs_world_t *world, + ecs_type_t *dst, + const ecs_type_t *src, + ecs_id_t without) +{ + ecs_assert(!ecs_id_is_wildcard(without), ECS_INVALID_PARAMETER, NULL); + ecs_assert(!ECS_IS_PAIR(without), ECS_INVALID_PARAMETER, NULL); + + ecs_id_t *src_array = src->array; + int32_t at = flecs_type_find_ignoring_generation(src, without); + if (at == -1) { + return -1; + } + + int32_t src_count = src->count; + if (src_count == 1) { + dst->array = NULL; + dst->count = 0; + return 0; + } + + int32_t dst_count = src_count - 1; + ecs_id_t *dst_array = flecs_walloc_n(world, ecs_id_t, dst_count); + dst->array = dst_array; + dst->count = dst_count; + + ecs_assert(dst_array != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(src_array != NULL, ECS_INTERNAL_ERROR, NULL); + + if (at) { + ecs_os_memcpy_n(dst_array, src_array, ecs_id_t, at); + } + + int32_t remain = dst_count - at; + if (remain) { + ecs_os_memcpy_n( + &dst_array[at], &src_array[at + 1], ecs_id_t, remain); + } + + return 0; +} + /* Copy type */ ecs_type_t flecs_type_copy( ecs_world_t *world, @@ -42935,6 +45717,22 @@ void flecs_type_remove( } } +/* Remove from type while ignoring entity id generation */ +void flecs_type_remove_ignoring_generation( + ecs_world_t *world, + ecs_type_t *type, + ecs_id_t remove) +{ + ecs_type_t new_type; + int res = flecs_type_new_without_ignoring_generation( + world, &new_type, type, remove); + if (res != -1) { + flecs_type_free(world, type); + type->array = new_type.array; + type->count = new_type.count; + } +} + /* Graph edge utilities */ void flecs_table_diff_builder_init( @@ -43528,8 +46326,6 @@ void flecs_add_overrides_for_base( int32_t column = flecs_type_find(dst_type, wc); if (column == -1) { flecs_type_add(world, dst_type, to_add); - } else { - dst_type->array[column] = to_add; } } } @@ -43645,6 +46441,19 @@ ecs_table_t* flecs_find_table_with( flecs_add_with_property(world, cr_with_wildcard, &dst_type, r, o); } + if (with == ecs_id(EcsParent)) { + if (node->flags & EcsTableHasChildOf) { + flecs_type_remove(world, &dst_type, + ecs_pair(EcsChildOf, EcsWildcard)); + } + } else if (ECS_PAIR_FIRST(with) == EcsChildOf) { + if (node->flags & EcsTableHasParent) { + flecs_type_remove(world, &dst_type, ecs_id(EcsParent)); + flecs_type_remove(world, &dst_type, + ecs_pair(EcsParentDepth, EcsWildcard)); + } + } + return flecs_table_ensure(world, &dst_type, true, node); } @@ -43682,6 +46491,11 @@ ecs_table_t* flecs_find_table_without( return node; /* Current table does not have id */ } + if (without == ecs_id(EcsParent)) { + flecs_type_remove(world, &dst_type, + ecs_pair(EcsParentDepth, EcsWildcard)); + } + return flecs_table_ensure(world, &dst_type, true, node); } @@ -44380,8 +47194,8 @@ void http_sock_set_timeout( int r; #ifdef ECS_TARGET_POSIX struct timeval tv; - tv.tv_sec = timeout_ms * 1000; - tv.tv_usec = 0; + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; r = setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); #else DWORD t = (DWORD)timeout_ms; @@ -44548,6 +47362,9 @@ static char http_hex_2_int(char a, char b){ a = (a <= '9') ? (char)(a - '0') : (char)((a & 0x7) + 9); b = (b <= '9') ? (char)(b - '0') : (char)((b & 0x7) + 9); + if (a < 0) { + return 0; + } return (char)((a << 4) + b); } @@ -44557,7 +47374,7 @@ void http_decode_url_str( { char ch, *ptr, *dst = str; for (ptr = str; (ch = *ptr); ptr++) { - if (ch == '%') { + if (ch == '%' && ptr[1]) { dst[0] = http_hex_2_int(ptr[1], ptr[2]); dst ++; ptr += 2; @@ -44607,7 +47424,7 @@ void http_header_buf_append( char ch) { if ((frag->header_buf_ptr - frag->header_buf) < - ECS_SIZEOF(frag->header_buf)) + (ECS_SIZEOF(frag->header_buf) - 1)) { frag->header_buf_ptr[0] = ch; frag->header_buf_ptr ++; @@ -45921,8 +48738,8 @@ static void flecs_from_json_ctx_fini( ecs_from_json_ctx_t *ctx) { - ecs_vec_fini_t(ctx->a, &ctx->table_type, ecs_record_t*); - ecs_vec_fini_t(ctx->a, &ctx->remove_ids, ecs_record_t*); + ecs_vec_fini_t(ctx->a, &ctx->table_type, ecs_id_t); + ecs_vec_fini_t(ctx->a, &ctx->remove_ids, ecs_id_t); ecs_map_fini(&ctx->anonymous_ids); ecs_map_fini(&ctx->missing_reflection); } @@ -46111,7 +48928,7 @@ const char* flecs_json_deser_tags( } while (true); if (token_kind != JsonArrayClose) { - ecs_parser_error(NULL, expr, json - expr, "expected }"); + ecs_parser_error(NULL, expr, json - expr, "expected ]"); goto error; } @@ -46436,13 +49253,13 @@ const char* flecs_entity_from_json( goto error; } - if (!e) { - e = flecs_json_lookup(world, parent, str, desc); - } else { - ecs_set_name(world, e, str); - } - if (str[0] != '#') { + if (!e) { + e = flecs_json_lookup(world, parent, str, desc); + } else { + ecs_set_name(world, e, str); + } + ecs_vec_append_t(ctx->a, &ctx->table_type, ecs_id_t)[0] = ecs_pair_t(EcsIdentifier, EcsName); } @@ -46472,18 +49289,45 @@ const char* flecs_entity_from_json( goto error; } + json = flecs_json_parse_next_member(json, token, &token_kind, desc); + if (!json) { + goto error; + } + + if (!ecs_os_strcmp(token, "version")) { + json = flecs_json_parse(json, &token_kind, token); + if (!json) { + goto error; + } + + uint64_t version; + if (token_kind == JsonNumber || token_kind == JsonLargeInt) { + version = flecs_ito(uint64_t, atoll(token)); + } else { + ecs_parser_error(NULL, expr, json - expr, "expected version"); + goto error; + } + + id |= version << 32; + + json = flecs_json_parse_next_member(json, token, &token_kind, desc); + if (!json) { + goto error; + } + } + if (!e) { - char name[32]; - ecs_os_snprintf(name, 32, "#%u", (uint32_t)id); - e = flecs_json_lookup(world, 0, name, desc); + if (ecs_is_alive(world, id) && !ecs_get_name(world, id)) { + e = id; + } else { + char name[32]; + ecs_os_snprintf(name, 32, "#%u", (uint32_t)id); + e = flecs_json_lookup(world, 0, name, desc); + } } else { /* If we already have an id, ignore explicit id */ } - json = flecs_json_parse_next_member(json, token, &token_kind, desc); - if (!json) { - goto error; - } if (token_kind == JsonObjectClose) { goto end; } @@ -46626,6 +49470,9 @@ const char* ecs_entity_from_json( const char *json, const ecs_from_json_desc_t *desc_arg) { + ecs_assert(!ecs_is_deferred(world), ECS_INVALID_OPERATION, + "cannot deserialize while world is deferred"); + ecs_from_json_desc_t desc = {0}; if (desc_arg) { desc = *desc_arg; @@ -46766,15 +49613,23 @@ const char* ecs_world_from_json_file( typedef struct ecs_script_impl_t ecs_script_impl_t; typedef struct ecs_script_scope_t ecs_script_scope_t; +#ifndef ECS_PARSER_MAX_RECURSION_DEPTH +#define ECS_PARSER_MAX_RECURSION_DEPTH (64) +#endif + typedef struct ecs_parser_t { const char *name; const char *code; const char *pos; char *token_cur; + char *token_end; char *token_keep; bool significant_newline; bool merge_variable_members; + bool function_token; + int16_t scope_depth; + int16_t expr_depth; ecs_world_t *world; @@ -46836,23 +49691,24 @@ typedef enum ecs_token_kind_t { EcsTokShiftLeft = 110, EcsTokShiftRight = 111, EcsTokIdentifier = 112, - EcsTokString = 113, - EcsTokNumber = 114, - EcsTokKeywordModule = 115, - EcsTokKeywordUsing = 116, - EcsTokKeywordWith = 117, - EcsTokKeywordIf = 118, - EcsTokKeywordFor = 119, - EcsTokKeywordIn = 120, - EcsTokKeywordElse = 121, - EcsTokKeywordTemplate = 122, - EcsTokKeywordProp = 130, - EcsTokKeywordConst = 131, - EcsTokKeywordMatch = 132, - EcsTokKeywordNew = 133, - EcsTokKeywordExport = 134, - EcsTokAddAssign = 135, - EcsTokMulAssign = 136, + EcsTokFunction = 113, + EcsTokString = 114, + EcsTokNumber = 115, + EcsTokKeywordModule = 116, + EcsTokKeywordUsing = 117, + EcsTokKeywordWith = 118, + EcsTokKeywordIf = 119, + EcsTokKeywordFor = 120, + EcsTokKeywordIn = 121, + EcsTokKeywordElse = 122, + EcsTokKeywordTemplate = 130, + EcsTokKeywordProp = 131, + EcsTokKeywordConst = 132, + EcsTokKeywordMatch = 133, + EcsTokKeywordNew = 134, + EcsTokKeywordExport = 135, + EcsTokAddAssign = 136, + EcsTokMulAssign = 137, } ecs_token_kind_t; typedef struct ecs_token_t { @@ -46923,7 +49779,11 @@ struct ecs_script_impl_t { typedef struct ecs_function_calldata_t { ecs_entity_t function; - ecs_function_callback_t callback; + struct { + ecs_function_callback_t callback; + ecs_vector_function_callback_t vector_callback; + } is; + int32_t vector_elem_count; void *ctx; } ecs_function_calldata_t; @@ -47026,6 +49886,7 @@ struct ecs_script_entity_t { const char *name; bool name_is_var; bool kind_w_expr; + bool non_fragmenting_parent; ecs_script_scope_t *scope; ecs_expr_node_t *name_expr; @@ -47347,6 +50208,10 @@ typedef struct ecs_expr_binary_t { ecs_expr_node_t *left; ecs_expr_node_t *right; ecs_token_kind_t operator; + + /* For vector operations */ + ecs_entity_t vector_type; + int32_t vector_count; } ecs_expr_binary_t; typedef struct ecs_expr_member_t { @@ -47409,6 +50274,11 @@ ecs_expr_variable_t* flecs_expr_variable_from( ecs_expr_node_t *node, const char *name); +ecs_expr_member_t* flecs_expr_member_from( + ecs_script_t *script, + ecs_expr_node_t *node, + const char *name); + ecs_expr_value_node_t* flecs_expr_bool( ecs_parser_t *parser, bool value); @@ -47577,6 +50447,16 @@ bool flecs_expr_is_type_integer( bool flecs_expr_is_type_number( ecs_entity_t type); +ecs_size_t flecs_expr_storage_size( + ecs_entity_t type); + +int flecs_expr_initializer_validate_assign( + const ecs_script_t *script, + ecs_expr_initializer_t *node, + ecs_expr_initializer_element_t *elem, + ecs_entity_t type, + ecs_size_t value_size); + #endif /** @@ -47593,10 +50473,15 @@ typedef int (*ecs_visit_action_t)( ecs_script_visit_t *visitor, ecs_script_node_t *node); +/* Visitors track both scope nodes and statement nodes on the traversal stack. + * For deeply nested scopes this requires roughly 2x the parser nesting depth, + * plus the root scope node. */ +#define ECS_SCRIPT_VISIT_MAX_DEPTH ((ECS_PARSER_MAX_RECURSION_DEPTH * 2) + 4) + struct ecs_script_visit_t { ecs_script_impl_t *script; ecs_visit_action_t visit; - ecs_script_node_t* nodes[256]; + ecs_script_node_t* nodes[ECS_SCRIPT_VISIT_MAX_DEPTH]; ecs_script_node_t *prev, *next; int32_t depth; }; @@ -47825,6 +50710,12 @@ struct ecs_script_template_t { /* Type info for template component */ const ecs_type_info_t *type_info; + + /* Annotations to apply to template instance */ + ecs_vec_t annot; + + /* Use non-fragmenting hierarchy */ + bool non_fragmenting_parent; }; #define ECS_TEMPLATE_SMALL_SIZE (36) @@ -47914,6 +50805,20 @@ int ecs_script_ast_node_to_buf( void ecs_script_runtime_clear( ecs_script_runtime_t *r); +int flecs_script_apply_annot( + ecs_script_eval_visitor_t *v, + ecs_script_entity_t *node, + ecs_script_annot_t *annot); + +/* Script functions */ +double flecs_lerp( + double a, + double b, + double t); + +void FlecsScriptMathPerlinImport( + ecs_world_t *world); + #endif // FLECS_SCRIPT #endif // FLECS_SCRIPT_PRIVATE_H @@ -48716,7 +51621,12 @@ void flecs_json_id( ecs_strbuf_appendch(buf, '"'); ecs_strbuf_appendch(buf, ','); ecs_strbuf_appendch(buf, '"'); - ecs_get_path_w_sep_buf(world, 0, second, ".", "", buf, true); + if (ECS_IS_VALUE_PAIR(id)) { + ecs_strbuf_appendch(buf, '@'); + ecs_strbuf_appendint(buf, ECS_PAIR_SECOND(id)); + } else { + ecs_get_path_w_sep_buf(world, 0, second, ".", "", buf, true); + } ecs_strbuf_appendch(buf, '"'); } else { ecs_strbuf_appendch(buf, '"'); @@ -48801,6 +51711,40 @@ ecs_primitive_kind_t flecs_json_op_to_primitive_kind( return kind - EcsOpPrimitive; } +bool flecs_json_should_serialize( + ecs_entity_t entity, + const ecs_iter_t *it, + const ecs_json_ser_ctx_t *ser_ctx) +{ + if (!ecs_map_is_init(&ser_ctx->serialized)) { + return true; + } + + if (ecs_map_get(&ser_ctx->serialized, entity) != NULL) { + return false; + } + + if (it->query) { + ecs_iter_t temp_it; + bool result = ecs_query_has(it->query, entity, &temp_it); + if (result) { + ecs_iter_fini(&temp_it); + } else { + return false; + } + } + + return true; +} + +void flecs_json_mark_serialized( + ecs_entity_t entity, + ecs_json_ser_ctx_t *ser_ctx) +{ + if (ecs_map_is_init(&ser_ctx->serialized)) { + ecs_map_ensure(&ser_ctx->serialized, entity); + } +} #endif /** @@ -48846,6 +51790,12 @@ int flecs_expr_ser_primitive( void flecs_rtt_init_default_hooks( ecs_iter_t *it); +const char* flecs_type_kind_str( + ecs_type_kind_t kind); + +const char* flecs_primitive_type_kind_str( + ecs_primitive_kind_t kind); + const char* flecs_meta_op_kind_str( ecs_meta_op_kind_t kind); @@ -48856,28 +51806,13 @@ const char* flecs_meta_op_kind_str( #ifdef FLECS_JSON -int ecs_entity_to_json_buf( - const ecs_world_t *stage, +int flecs_entity_to_json_buf( + const ecs_world_t *world, ecs_entity_t entity, ecs_strbuf_t *buf, - const ecs_entity_to_json_desc_t *desc) + const ecs_iter_to_json_desc_t *desc, + ecs_json_ser_ctx_t *ser_ctx) { - const ecs_world_t *world = ecs_get_world(stage); - - if (!entity || !ecs_is_valid(world, entity)) { - return -1; - } - - /* Cache component record for flecs.doc ids */ - ecs_json_ser_ctx_t ser_ctx; - ecs_os_zeromem(&ser_ctx); -#ifdef FLECS_DOC - ser_ctx.cr_doc_name = flecs_components_get(world, - ecs_pair_t(EcsDocDescription, EcsName)); - ser_ctx.cr_doc_color = flecs_components_get(world, - ecs_pair_t(EcsDocDescription, EcsDocColor)); -#endif - ecs_record_t *r = ecs_record_find(world, entity); if (!r || !r->table) { flecs_json_object_push(buf); @@ -48902,6 +51837,37 @@ int ecs_entity_to_json_buf( .field_count = 0 }; + if (flecs_json_serialize_iter_result( + world, &it, buf, desc, ser_ctx)) + { + return -1; + } + + return 0; +} + +int ecs_entity_to_json_buf( + ecs_world_t *stage, + ecs_entity_t entity, + ecs_strbuf_t *buf, + const ecs_entity_to_json_desc_t *desc) +{ + const ecs_world_t *world = ecs_get_world(stage); + + if (!entity || !ecs_is_valid(world, entity)) { + return -1; + } + + /* Cache component record for flecs.doc ids */ + ecs_json_ser_ctx_t ser_ctx; + ecs_os_zeromem(&ser_ctx); +#ifdef FLECS_DOC + ser_ctx.cr_doc_name = flecs_components_get(world, + ecs_pair_t(EcsDocDescription, EcsName)); + ser_ctx.cr_doc_color = flecs_components_get(world, + ecs_pair_t(EcsDocDescription, EcsDocColor)); +#endif + /* Initialize iterator parameters */ ecs_iter_to_json_desc_t iter_desc = { .serialize_table = true, @@ -48918,17 +51884,14 @@ int ecs_entity_to_json_buf( .component_filter = desc ? desc->component_filter : NULL, }; - if (flecs_json_serialize_iter_result( - world, &it, buf, &iter_desc, &ser_ctx)) - { - return -1; - } + int result = flecs_entity_to_json_buf( + world, entity, buf, &iter_desc, &ser_ctx); - return 0; + return result; } char* ecs_entity_to_json( - const ecs_world_t *world, + ecs_world_t *world, ecs_entity_t entity, const ecs_entity_to_json_desc_t *desc) { @@ -49061,7 +52024,7 @@ void flecs_json_serialize_id_str( ecs_strbuf_appendch(buf, '"'); if (ECS_IS_PAIR(id)) { ecs_entity_t first = ecs_pair_first(world, id); - ecs_entity_t second = ecs_pair_first(world, id); + ecs_entity_t second = ecs_pair_second(world, id); ecs_strbuf_appendch(buf, '('); ecs_get_path_w_sep_buf(world, 0, first, ".", "", buf, true); ecs_strbuf_appendch(buf, ','); @@ -49373,16 +52336,28 @@ int ecs_iter_to_json_buf( ECS_BIT_SET(it->flags, EcsIterNoData); } + /* Keep track of serialized entities. This allows entities to be + * serialized depth first, which avoids weird side effects from children + * being created before parents. */ + if (desc && desc->serialize_parents_before_children) { + ecs_map_init(&ser_ctx.serialized, &world->allocator); + } + ecs_iter_next_action_t next = it->next; while (next(it)) { if (flecs_json_serialize_iter_result(world, it, buf, desc, &ser_ctx)) { ecs_strbuf_reset(buf); flecs_iter_free_ser_ctx(it, &ser_ctx); ecs_iter_fini(it); + ecs_map_fini(&ser_ctx.serialized); return -1; } } + if (desc && desc->serialize_parents_before_children) { + ecs_map_fini(&ser_ctx.serialized); + } + flecs_json_array_pop(buf); } else { ecs_iter_fini(it); @@ -49742,34 +52717,84 @@ bool flecs_json_serialize_get_value_ctx( } } -void flecs_json_serialize_iter_this( +bool flecs_json_serialize_iter_this( const ecs_iter_t *it, const char *parent_path, const ecs_json_this_data_t *this_data, int32_t row, ecs_strbuf_t *buf, - const ecs_iter_to_json_desc_t *desc) + const ecs_iter_to_json_desc_t *desc, + ecs_json_ser_ctx_t *ser_ctx) { ecs_assert(row < it->count, ECS_INTERNAL_ERROR, NULL); + ecs_world_t *world = it->real_world; + + ecs_assert(this_data != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(this_data->ids != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_entity_t e = this_data->ids[row]; + + /* Skip entity if it already has been serialized */ + if (!flecs_json_should_serialize(e, it, ser_ctx)) { + return false; + } + + flecs_json_mark_serialized(e, ser_ctx); + + /* Serialize parent first. Only necessary if this is a table with Parent + * component, as this will have been done at the table level for fragmenting + * relationships. */ + ecs_entity_t parent = 0; + if (this_data->parents) { + parent = this_data->parents[row].value; + ecs_assert(parent != 0, ECS_INTERNAL_ERROR, NULL); + if (ecs_map_is_init(&ser_ctx->serialized)) { + flecs_entity_to_json_buf(world, parent, buf, desc, ser_ctx); + } + } + + flecs_json_next(buf); + flecs_json_object_push(buf); if (parent_path) { flecs_json_memberl(buf, "parent"); flecs_json_string(buf, parent_path); + } else if (parent) { + flecs_json_memberl(buf, "parent"); + char *path = ecs_get_path_w_sep(world, 0, parent, ".", ""); + flecs_json_string(buf, path); + ecs_os_free(path); } flecs_json_memberl(buf, "name"); if (this_data->names) { - flecs_json_string(buf, this_data->names[row].value); + if (this_data->table) { + flecs_json_string(buf, this_data->names[row].value); + } } else { - ecs_strbuf_appendlit(buf, "\"#"); - ecs_strbuf_appendint(buf, flecs_uto(int64_t, - (uint32_t)it->entities[row])); - ecs_strbuf_appendlit(buf, "\""); + bool name_set = false; + if (!this_data->table) { + const char *name = ecs_get_name(world, e); + if (name) { + flecs_json_string(buf, name); + name_set = true; + } + } + + if (!name_set) { + ecs_strbuf_appendlit(buf, "\"#"); + ecs_strbuf_appendint(buf, flecs_uto(int64_t, + (uint32_t)it->entities[row])); + ecs_strbuf_appendlit(buf, "\""); + } } if (desc && desc->serialize_entity_ids) { flecs_json_memberl(buf, "id"); - flecs_json_u32(buf, (uint32_t)this_data->ids[row]); + flecs_json_u32(buf, (uint32_t)e); + if (e != (uint32_t)e) { + flecs_json_memberl(buf, "version"); + flecs_json_u32(buf, (uint32_t)(e >> 32)); + } } #ifdef FLECS_DOC @@ -49819,6 +52844,8 @@ void flecs_json_serialize_iter_this( flecs_json_memberl(buf, "has_alerts"); flecs_json_true(buf); } + + return true; } int flecs_json_serialize_iter_result( @@ -49829,7 +52856,7 @@ int flecs_json_serialize_iter_result( ecs_json_ser_ctx_t *ser_ctx) { char *parent_path = NULL; - ecs_json_this_data_t this_data = {0}; + ecs_json_this_data_t this_data = { .table = it->table }; int32_t count = it->count; bool has_this = true; @@ -49849,6 +52876,22 @@ int flecs_json_serialize_iter_result( ecs_entity_t parent = ecs_pair_second( world, table->type.array[tr->index]); parent_path = ecs_get_path_w_sep(world, 0, parent, ".", ""); + + /* If matching a query check if we need to serialize the parent + * of the table before its children. Don't do this if query + * isn't set, as that means that we're serializing a single + * entity. */ + if (ecs_map_is_init(&ser_ctx->serialized)) { + if (flecs_json_should_serialize(parent, it, ser_ctx)) { + if (flecs_entity_to_json_buf( + world, parent, buf, desc, ser_ctx)) + { + return -1; + } + + flecs_json_mark_serialized(parent, ser_ctx); + } + } } /* Fetch name column once vs. calling ecs_get_name for each row */ @@ -49857,6 +52900,12 @@ int flecs_json_serialize_iter_result( ecs_pair_t(EcsIdentifier, EcsName), it->offset); } + /* Same for Parent column */ + if (table->flags & EcsTableHasParent) { + this_data.parents = ecs_table_get_id(it->world, it->table, + ecs_id(EcsParent), it->offset); + } + /* Get entity labels */ #ifdef FLECS_DOC if (desc && desc->serialize_doc) { @@ -49882,14 +52931,13 @@ int flecs_json_serialize_iter_result( } #endif } else { - /* Very rare case, but could happen if someone's using an iterator - * to return empty entities. */ + this_data.ids = it->entities; } } if (desc && desc->serialize_table) { if (flecs_json_serialize_iter_result_table(world, it, buf, - desc, count, has_this, parent_path, &this_data)) + desc, ser_ctx, count, has_this, parent_path, &this_data)) { goto error; } @@ -50157,12 +53205,15 @@ int flecs_json_serialize_iter_result_query( int32_t i; for (i = 0; i < count; i ++) { - flecs_json_next(buf); - flecs_json_object_push(buf); - if (has_this) { - flecs_json_serialize_iter_this( - it, parent_path, this_data, i, buf, desc); + if (!flecs_json_serialize_iter_this( + it, parent_path, this_data, i, buf, desc, ser_ctx)) + { + continue; + } + } else { + flecs_json_next(buf); + flecs_json_object_push(buf); } if (common_data) { @@ -50395,9 +53446,6 @@ bool flecs_json_serialize_table_pairs( flecs_json_object_push(buf); } - ecs_entity_t second = flecs_entities_get_alive( - world, ECS_PAIR_SECOND(id)); - bool is_last = f == (type_count - 1); bool is_same = !is_last && (ECS_PAIR_FIRST(ids[f + 1]) == ECS_PAIR_FIRST(id)); @@ -50425,8 +53473,18 @@ bool flecs_json_serialize_table_pairs( flecs_json_next(buf); } - flecs_json_path_or_label(buf, world, second, - desc ? desc->serialize_full_paths : true); + if (ECS_IS_VALUE_PAIR(id)) { + ecs_strbuf_appendch(buf, '\"'); + ecs_strbuf_appendch(buf, '@'); + ecs_strbuf_appendint(buf, ECS_PAIR_SECOND(id)); + ecs_strbuf_appendch(buf, '\"'); + } else { + ecs_entity_t second = flecs_entities_get_alive( + world, ECS_PAIR_SECOND(id)); + + flecs_json_path_or_label(buf, world, second, + desc ? desc->serialize_full_paths : true); + } pair_count ++; } @@ -50678,6 +53736,7 @@ int flecs_json_serialize_iter_result_table( const ecs_iter_t *it, ecs_strbuf_t *buf, const ecs_iter_to_json_desc_t *desc, + ecs_json_ser_ctx_t *ser_ctx, int32_t count, bool has_this, const char *parent_path, @@ -50712,13 +53771,16 @@ int flecs_json_serialize_iter_result_table( int32_t i, end = it->offset + count; int result = 0; for (i = it->offset; i < end; i ++) { - flecs_json_next(buf); - flecs_json_object_push(buf); - if (has_this) { ecs_json_this_data_t this_data_cpy = *this_data; - flecs_json_serialize_iter_this( - it, parent_path, &this_data_cpy, i - it->offset, buf, desc); + if (!flecs_json_serialize_iter_this(it, parent_path, + &this_data_cpy, i - it->offset, buf, desc, ser_ctx)) + { + continue; + } + } else { + flecs_json_next(buf); + flecs_json_object_push(buf); } if (tags_pairs_vars) { @@ -51030,6 +54092,8 @@ int flecs_json_typeinfo_ser_primitive( return -1; } + ecs_strbuf_list_next(str); + return 0; } @@ -51292,7 +54356,6 @@ int flecs_json_typeinfo_ser_type_slice( ecs_entity_t unit = m->unit; if (unit || error_range || warning_range || value_range) { - flecs_json_next(str); flecs_json_next(str); flecs_json_object_push(str); @@ -51919,7 +54982,8 @@ int ecs_world_to_json_buf( .serialize_table = true, .serialize_full_paths = true, .serialize_entity_ids = true, - .serialize_values = true + .serialize_values = true, + .serialize_parents_before_children = true }; int ret = ecs_iter_to_json_buf(&it, buf_out, &json_desc); @@ -52640,28 +55704,47 @@ int flecs_meta_utils_parse_struct( .desc = ptr }; - ecs_entity_t old_scope = ecs_set_scope(world, t); + ecs_struct_desc_t struct_desc = { + .entity = t + }; - while ((ptr = flecs_meta_utils_parse_member(ptr, &token, &ctx)) && ptr[0]) { - ecs_entity_t m = ecs_entity(world, { - .name = token.name - }); + int32_t member = 0; + int32_t result = 0; + while ((ptr = flecs_meta_utils_parse_member(ptr, &token, &ctx)) && ptr[0]) { ecs_entity_t type = flecs_meta_utils_lookup( world, &token.type, ptr, 0, &ctx); if (!type) { goto error; } - ecs_set(world, m, EcsMember, { - .type = type, - .count = (ecs_size_t)token.count - }); + if (member == (ECS_MEMBER_DESC_CACHE_SIZE - 1)) { + ecs_err("too many members (%d) defined for struct " + "(increase ECS_MEMBER_DESC_CACHE_SIZE)", + ECS_MEMBER_DESC_CACHE_SIZE); + result = -1; + goto done; + } + + struct_desc.members[member].name = ecs_os_strdup(token.name); + struct_desc.members[member].type = type; + struct_desc.members[member].count = flecs_ito(int32_t, token.count); + member ++; } - ecs_set_scope(world, old_scope); + if (!ecs_struct_init(world, &struct_desc)) { + goto error; + } - return 0; +done: + for (int i = 0; i < ECS_MEMBER_DESC_CACHE_SIZE; i ++) { + if (!struct_desc.members[i].name) { + break; + } + ecs_os_free(ECS_CONST_CAST(char*, struct_desc.members[i].name)); + } + + return result; error: return -1; } @@ -52996,12 +56079,15 @@ void* flecs_meta_cursor_get_ptr( scope->is_empty_scope = false; - void *opaque_ptr = opaque->ensure_element(scope->ptr, - flecs_itosize(parent->elem)); - ecs_assert(opaque_ptr != NULL, ECS_INVALID_OPERATION, - "ensure_element() returned NULL"); + if (scope->ptr) { + void *opaque_ptr = opaque->ensure_element(scope->ptr, + flecs_itosize(parent->elem)); + ecs_assert(opaque_ptr != NULL, ECS_INVALID_OPERATION, + "ensure_element() returned NULL"); + return opaque_ptr; + } - return opaque_ptr; + return NULL; } else if (op->name) { if (!opaque->ensure_member) { char *str = ecs_get_path(world, scope->type); @@ -53225,6 +56311,10 @@ const char* flecs_meta_parse_member( } int32_t len = flecs_ito(int32_t, ptr - start); + if (len >= ECS_MAX_TOKEN_SIZE) { + len = ECS_MAX_TOKEN_SIZE - 1; + } + ecs_os_memcpy(token_out, start, len); token_out[len] = '\0'; if (ch == '.') { @@ -54027,6 +57117,10 @@ int ecs_meta_set_value( ecs_check(value != NULL, ECS_INVALID_PARAMETER, NULL); ecs_entity_t type = value->type; ecs_check(type != 0, ECS_INVALID_PARAMETER, NULL); + if (!value->ptr) { + ecs_err("value pointer is null"); + return -1; + } const EcsType *mt = ecs_get(cursor->world, type, EcsType); if (!mt) { ecs_err("type of value does not have reflection data"); @@ -54052,7 +57146,13 @@ int ecs_meta_set_value( case EcsF64: return ecs_meta_set_float(cursor, *(double*)value->ptr); case EcsUPtr: return ecs_meta_set_uint(cursor, *(uintptr_t*)value->ptr); case EcsIPtr: return ecs_meta_set_int(cursor, *(intptr_t*)value->ptr); - case EcsString: return ecs_meta_set_string(cursor, *(char**)value->ptr); + case EcsString: { + char *str = *(char**)value->ptr; + if (!str) { + return ecs_meta_set_null(cursor); + } + return ecs_meta_set_string(cursor, str); + } case EcsEntity: return ecs_meta_set_entity(cursor, *(ecs_entity_t*)value->ptr); case EcsId: return ecs_meta_set_id(cursor, *(ecs_id_t*)value->ptr); default: @@ -54179,9 +57279,17 @@ int ecs_meta_set_string( ecs_meta_cursor_t *cursor, const char *value) { + if (!value) { + return ecs_meta_set_null(cursor); + } + ecs_meta_scope_t *scope = flecs_cursor_get_scope(cursor); ecs_meta_op_t *op = flecs_cursor_get_op(scope); void *ptr = flecs_meta_cursor_get_ptr(cursor->world, cursor, scope); + if (!ptr) { + ecs_err("no object to assign"); + goto error; + } switch(op->kind) { case EcsOpI8: @@ -54270,7 +57378,9 @@ int ecs_meta_set_string( set_T(ecs_f64_t, ptr, atof(value)); break; case EcsOpString: { - ecs_assert(*(ecs_string_t*)ptr != value, ECS_INVALID_PARAMETER, NULL); + if (*(ecs_string_t*)ptr == value) { + break; + } ecs_os_free(*(ecs_string_t*)ptr); char *result = ecs_os_strdup(value); set_T(ecs_string_t, ptr, result); @@ -54603,6 +57713,10 @@ int ecs_meta_set_null( ecs_meta_scope_t *scope = flecs_cursor_get_scope(cursor); ecs_meta_op_t *op = flecs_cursor_get_op(scope); void *ptr = flecs_meta_cursor_get_ptr(cursor->world, cursor, scope); + if (!ptr) { + ecs_err("no object to assign"); + goto error; + } switch (op->kind) { case EcsOpString: ecs_os_free(*(char**)ptr); @@ -55129,6 +58243,11 @@ int flecs_init_type( ecs_size_t size, ecs_size_t alignment); +void flecs_meta_detect_cycles( + ecs_world_t *world, + ecs_entity_t type, + ecs_entity_t target); + #define flecs_init_type_t(world, type, kind, T) \ flecs_init_type(world, type, kind, ECS_SIZEOF(T), ECS_ALIGNOF(T)) @@ -55209,13 +58328,6 @@ void flecs_meta_import_core_definitions( } }); - ecs_struct(world, { - .entity = ecs_id(EcsDefaultChildComponent), - .members = { - { .name = "component", .type = ecs_id(ecs_entity_t) } - } - }); - ecs_struct(world, { .entity = ecs_id(EcsIdentifier), .members = { @@ -55227,6 +58339,20 @@ void flecs_meta_import_core_definitions( } }); + ecs_struct(world, { + .entity = ecs_id(EcsParent), + .members = { + { .name = "value", .type = ecs_id(ecs_entity_t) } + } + }); + + ecs_struct(world, { + .entity = ecs_id(EcsDefaultChildComponent), + .members = { + { .name = "component", .type = ecs_id(ecs_entity_t) } + } + }); + /* Define const string as an opaque type that maps to string This enables reflection for strings that are in .rodata, (read-only) so that the meta add-on does not try to free them. @@ -55300,22 +58426,6 @@ void flecs_meta_import_core_definitions( }); } -/* Initialize reflection data for doc components */ -static -void flecs_meta_import_doc_definitions( - ecs_world_t *world) -{ - (void)world; -#ifdef FLECS_DOC - ecs_struct(world, { - .entity = ecs_id(EcsDocDescription), - .members = { - { .name = "value", .type = ecs_id(ecs_string_t) } - } - }); -#endif -} - /* Initialize reflection data for meta components */ static void flecs_meta_import_meta_definitions( @@ -55455,47 +58565,12 @@ void flecs_meta_import_meta_definitions( { .name = "translation", .type = ut } } }); - - /* Meta doc definitions */ -#ifdef FLECS_DOC - ecs_entity_t meta = ecs_lookup(world, "flecs.meta"); - ecs_doc_set_brief(world, meta, "Flecs module with reflection components"); - - ecs_doc_set_brief(world, ecs_id(EcsType), "Component added to types"); - ecs_doc_set_brief(world, ecs_id(EcsTypeSerializer), "Component that stores reflection data in an optimized format"); - ecs_doc_set_brief(world, ecs_id(EcsPrimitive), "Component added to primitive types"); - ecs_doc_set_brief(world, ecs_id(EcsEnum), "Component added to enumeration types"); - ecs_doc_set_brief(world, ecs_id(EcsBitmask), "Component added to bitmask types"); - ecs_doc_set_brief(world, ecs_id(EcsMember), "Component added to struct members"); - ecs_doc_set_brief(world, ecs_id(EcsStruct), "Component added to struct types"); - ecs_doc_set_brief(world, ecs_id(EcsArray), "Component added to array types"); - ecs_doc_set_brief(world, ecs_id(EcsVector), "Component added to vector types"); - - ecs_doc_set_brief(world, ecs_id(ecs_bool_t), "bool component"); - ecs_doc_set_brief(world, ecs_id(ecs_char_t), "char component"); - ecs_doc_set_brief(world, ecs_id(ecs_byte_t), "byte component"); - ecs_doc_set_brief(world, ecs_id(ecs_u8_t), "8 bit unsigned int component"); - ecs_doc_set_brief(world, ecs_id(ecs_u16_t), "16 bit unsigned int component"); - ecs_doc_set_brief(world, ecs_id(ecs_u32_t), "32 bit unsigned int component"); - ecs_doc_set_brief(world, ecs_id(ecs_u64_t), "64 bit unsigned int component"); - ecs_doc_set_brief(world, ecs_id(ecs_uptr_t), "word sized unsigned int component"); - ecs_doc_set_brief(world, ecs_id(ecs_i8_t), "8 bit signed int component"); - ecs_doc_set_brief(world, ecs_id(ecs_i16_t), "16 bit signed int component"); - ecs_doc_set_brief(world, ecs_id(ecs_i32_t), "32 bit signed int component"); - ecs_doc_set_brief(world, ecs_id(ecs_i64_t), "64 bit signed int component"); - ecs_doc_set_brief(world, ecs_id(ecs_iptr_t), "word sized signed int component"); - ecs_doc_set_brief(world, ecs_id(ecs_f32_t), "32 bit floating point component"); - ecs_doc_set_brief(world, ecs_id(ecs_f64_t), "64 bit floating point component"); - ecs_doc_set_brief(world, ecs_id(ecs_string_t), "string component"); - ecs_doc_set_brief(world, ecs_id(ecs_entity_t), "entity component"); -#endif } void flecs_meta_import_definitions( ecs_world_t *world) { flecs_meta_import_core_definitions(world); - flecs_meta_import_doc_definitions(world); flecs_meta_import_meta_definitions(world); } @@ -55555,7 +58630,6 @@ static ECS_DTOR(EcsTypeSerializer, ptr, { flecs_type_serializer_dtor(ptr); }) -static const char* flecs_type_kind_str( ecs_type_kind_t kind) { @@ -55571,6 +58645,108 @@ const char* flecs_type_kind_str( } } +const char* flecs_primitive_type_kind_str( + ecs_primitive_kind_t kind) +{ + switch(kind) { + case EcsBool: return "Bool"; + case EcsChar: return "Char"; + case EcsByte: return "Byte"; + case EcsU8: return "U8"; + case EcsU16: return "U16"; + case EcsU32: return "U32"; + case EcsU64: return "U64"; + case EcsI8: return "I8"; + case EcsI16: return "I16"; + case EcsI32: return "I32"; + case EcsI64: return "I64"; + case EcsF32: return "F32"; + case EcsF64: return "F64"; + case EcsUPtr: return "UPtr"; + case EcsIPtr: return "IPtr"; + case EcsString: return "String"; + case EcsEntity: return "Entity"; + case EcsId: return "Id"; + default: return "unknown"; + } +} + +#ifdef FLECS_DEBUG +static +bool flecs_meta_detect_cycles_w_stack( + ecs_world_t *world, + ecs_entity_t type, + ecs_entity_t target, + ecs_vec_t *visited) +{ + if (!type) { + return false; + } + + if (type == target) { + return true; + } + + ecs_entity_t *visited_types = ecs_vec_first_t(visited, ecs_entity_t); + int32_t i, count = ecs_vec_count(visited); + for (i = 0; i < count; i ++) { + if (visited_types[i] == type) { + return false; + } + } + + ecs_vec_append_t(NULL, visited, ecs_entity_t)[0] = type; + + const EcsStruct *struct_info = ecs_get(world, type, EcsStruct); + if (struct_info) { + ecs_member_t *members = ecs_vec_first_t(&struct_info->members, ecs_member_t); + count = ecs_vec_count(&struct_info->members); + for (i = 0; i < count; i ++) { + if (flecs_meta_detect_cycles_w_stack( + world, members[i].type, target, visited)) + { + return true; + } + } + } + + const EcsArray *array_info = ecs_get(world, type, EcsArray); + if (array_info) { + if (flecs_meta_detect_cycles_w_stack( + world, array_info->type, target, visited)) + { + return true; + } + } + + return false; +} +#endif + +void flecs_meta_detect_cycles( + ecs_world_t *world, + ecs_entity_t type, + ecs_entity_t target) +{ + (void)world; + (void)type; + (void)target; +#ifdef FLECS_DEBUG + ecs_vec_t visited; + ecs_vec_init_t(NULL, &visited, ecs_entity_t, 0); + bool cycles_detected = flecs_meta_detect_cycles_w_stack( + world, type, target, &visited); + ecs_vec_fini_t(NULL, &visited, ecs_entity_t); + + ecs_assert( + !cycles_detected, + ECS_CYCLE_DETECTED, + "cyclic type definition: '%s' depends on '%s'", + flecs_errstr(ecs_get_path(world, target)), + flecs_errstr_1(ecs_get_path(world, type))); +#endif +} + int flecs_init_type( ecs_world_t *world, ecs_entity_t type, @@ -55581,11 +58757,28 @@ int flecs_init_type( ecs_assert(world != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(type != 0, ECS_INTERNAL_ERROR, NULL); +#ifdef FLECS_DEBUG + { + const ecs_type_info_t *ti = ecs_get_type_info(world, type); + if (ti && (ti->hooks.flags & ECS_TYPE_HOOK_IN_USE)) { + const EcsType *t = ecs_get(world, type, EcsType); + ecs_assert(!t || t->existing, + ECS_INVALID_OPERATION, + "cannot modify runtime type '%s' after it is in use", + flecs_errstr_1(ecs_get_path(world, type))); + } + } +#endif + EcsType *meta_type = ecs_ensure(world, type, EcsType); if (meta_type->kind == 0) { + meta_type->kind = kind; + + const EcsComponent *cptr = ecs_get(world, type, EcsComponent); + /* Determine if this is an existing type or a reflection-defined type * (runtime type) */ - meta_type->existing = ecs_has(world, type, EcsComponent); + meta_type->existing = (cptr != NULL) && (cptr->size != 0); /* For existing types, ensure that component has a default constructor, * to prevent crashing serializers on uninitialized values. For runtime @@ -55596,6 +58789,7 @@ int flecs_init_type( if(!ti->hooks.ctor) { ti->hooks.ctor = flecs_default_ctor; } + if(kind == EcsEnumType) { /* Generate compare/equals hooks for enums, copying the underlying type's hooks, which should be @@ -55632,30 +58826,31 @@ int flecs_init_type( ecs_modified(world, type, EcsComponent); } else { const EcsComponent *comp = ecs_get(world, type, EcsComponent); - if (comp->size < size) { - ecs_err( - "computed size (%d) for '%s' is larger than actual type (%d)", - size, ecs_get_name(world, type), comp->size); - return -1; - } - if (comp->alignment < alignment) { - ecs_err( - "computed alignment (%d) for '%s' is larger than actual type (%d)", - alignment, ecs_get_name(world, type), comp->alignment); - return -1; - } - if (comp->size == size && comp->alignment != alignment) { + if (comp->size) { + if (comp->size < size) { + ecs_err( + "computed size (%d) for '%s' is larger than actual type (%d)", + size, ecs_get_name(world, type), comp->size); + return -1; + } if (comp->alignment < alignment) { - ecs_err("computed size for '%s' matches with actual type but " - "alignment is different (%d vs. %d)", - ecs_get_name(world, type), alignment, comp->alignment); + ecs_err( + "computed alignment (%d) for '%s' is larger than actual type (%d)", + alignment, ecs_get_name(world, type), comp->alignment); + return -1; + } + if (comp->size == size && comp->alignment != alignment) { + if (comp->alignment < alignment) { + ecs_err("computed size for '%s' matches with actual type but " + "alignment is different (%d vs. %d)", + ecs_get_name(world, type), alignment, comp->alignment); + } } - } - meta_type->partial = comp->size != size; + meta_type->partial = comp->size != size; + } } - meta_type->kind = kind; ecs_modified(world, type, EcsType); return 0; @@ -55665,9 +58860,6 @@ void FlecsMetaImport( ecs_world_t *world) { ECS_MODULE(world, FlecsMeta); -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); -#endif ecs_set_name_prefix(world, "Ecs"); @@ -55692,17 +58884,17 @@ void FlecsMetaImport( }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsType) }, .events = {EcsOnSet}, - .callback = flecs_meta_type_serializer_init + .callback = flecs_meta_type_serializer_init, + .global_observer = true }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsType) }, .events = {EcsOnSet}, - .callback = flecs_rtt_init_default_hooks + .callback = flecs_rtt_init_default_hooks, + .global_observer = true }); /* Import type support for different type kinds */ @@ -56086,6 +59278,9 @@ void flecs_rtt_init_default_hooks_struct( for (i = 0; i < member_count; i++) { ecs_member_t *m = &members[i]; const ecs_type_info_t *member_ti = ecs_get_type_info(world, m->type); + if (!member_ti || member_ti == ti) { + continue; + } ctor_hook_required |= member_ti->hooks.ctor && member_ti->hooks.ctor != flecs_default_ctor; dtor_hook_required |= member_ti->hooks.dtor != NULL; @@ -56121,6 +59316,9 @@ void flecs_rtt_init_default_hooks_struct( for (i = 0; i < member_count; i++) { ecs_member_t *m = &members[i]; const ecs_type_info_t *member_ti = ecs_get_type_info(world, m->type); + if (!member_ti || member_ti == ti) { + continue; + } if (ctor_hook_required) { ecs_rtt_call_data_t *ctor_data = ecs_vec_append_t(NULL, &rtt_ctx->vctor, ecs_rtt_call_data_t); @@ -56213,11 +59411,10 @@ void flecs_rtt_array_ctor( const ecs_type_info_t *type_info) { ecs_rtt_array_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_xtor_t ctor = rtt_ctx->type_info->hooks.ctor; int i; for (i = 0; i < count; i++) { void *arr = ECS_ELEM(ptr, type_info->size, i); - ctor(arr, rtt_ctx->elem_count, rtt_ctx->type_info); + flecs_type_info_ctor(arr, rtt_ctx->elem_count, rtt_ctx->type_info); } } @@ -56231,11 +59428,10 @@ void flecs_rtt_array_dtor( const ecs_type_info_t *type_info) { ecs_rtt_array_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_xtor_t dtor = rtt_ctx->type_info->hooks.dtor; int i; for (i = 0; i < count; i++) { void *arr = ECS_ELEM(ptr, type_info->size, i); - dtor(arr, rtt_ctx->elem_count, rtt_ctx->type_info); + flecs_type_info_dtor(arr, rtt_ctx->elem_count, rtt_ctx->type_info); } } @@ -56250,12 +59446,12 @@ void flecs_rtt_array_move( const ecs_type_info_t *type_info) { ecs_rtt_array_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_move_t move = rtt_ctx->type_info->hooks.move; int i; for (i = 0; i < count; i++) { void *src_arr = ECS_ELEM(src_ptr, type_info->size, i); void *dst_arr = ECS_ELEM(dst_ptr, type_info->size, i); - move(dst_arr, src_arr, rtt_ctx->elem_count, rtt_ctx->type_info); + flecs_type_info_move( + dst_arr, src_arr, rtt_ctx->elem_count, rtt_ctx->type_info); } } @@ -56270,12 +59466,12 @@ void flecs_rtt_array_copy( const ecs_type_info_t *type_info) { ecs_rtt_array_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_copy_t copy = rtt_ctx->type_info->hooks.copy; int i; for (i = 0; i < count; i++) { const void *src_arr = ECS_ELEM(src_ptr, type_info->size, i); void *dst_arr = ECS_ELEM(dst_ptr, type_info->size, i); - copy(dst_arr, src_arr, rtt_ctx->elem_count, rtt_ctx->type_info); + flecs_type_info_copy( + dst_arr, src_arr, rtt_ctx->elem_count, rtt_ctx->type_info); } } @@ -56292,14 +59488,12 @@ int flecs_rtt_array_cmp( } ecs_rtt_array_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_cmp_t cmp = rtt_ctx->type_info->hooks.cmp; - ecs_assert(cmp, ECS_INVALID_PARAMETER, NULL); ecs_size_t element_size = rtt_ctx->type_info->size; int i; for (i = 0; i < rtt_ctx->elem_count; i++) { const void *a_element = ECS_ELEM(a_ptr, element_size, i); const void *b_element = ECS_ELEM(b_ptr, element_size, i); - int c = cmp(a_element, b_element, rtt_ctx->type_info); + int c = flecs_type_info_cmp(a_element, b_element, rtt_ctx->type_info); if(c != 0) { return c; } @@ -56320,14 +59514,13 @@ bool flecs_rtt_array_equals( } ecs_rtt_array_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_equals_t equals = rtt_ctx->type_info->hooks.equals; - ecs_assert(equals, ECS_INVALID_PARAMETER, NULL); ecs_size_t element_size = rtt_ctx->type_info->size; int i; for (i = 0; i < rtt_ctx->elem_count; i++) { const void *a_element = ECS_ELEM(a_ptr, element_size, i); const void *b_element = ECS_ELEM(b_ptr, element_size, i); - bool eq = equals(a_element, b_element, rtt_ctx->type_info); + bool eq = flecs_type_info_equals( + a_element, b_element, rtt_ctx->type_info); if(!eq) { return false; } @@ -56439,13 +59632,13 @@ void flecs_rtt_vector_dtor( const ecs_type_info_t *type_info) { ecs_rtt_vector_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_xtor_t dtor = rtt_ctx->type_info->hooks.dtor; int i; for (i = 0; i < count; i++) { ecs_vec_t *vec = ECS_ELEM(ptr, type_info->size, i); int32_t num_elements = ecs_vec_count(vec); - if (dtor && num_elements) { - dtor(ecs_vec_first(vec), num_elements, rtt_ctx->type_info); + if (rtt_ctx->type_info->hooks.dtor && num_elements) { + flecs_type_info_dtor( + ecs_vec_first(vec), num_elements, rtt_ctx->type_info); } ecs_vec_fini(NULL, vec, rtt_ctx->type_info->size); } @@ -56480,13 +59673,9 @@ void flecs_rtt_vector_copy( { ecs_rtt_vector_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; flecs_rtt_vector_dtor(dst_ptr, count, type_info); - ecs_copy_t copy = rtt_ctx->type_info->hooks.copy - ? rtt_ctx->type_info->hooks.copy - : flecs_rtt_default_copy; - ecs_xtor_t ctor = rtt_ctx->type_info->hooks.ctor - ? rtt_ctx->type_info->hooks.ctor - : flecs_default_ctor; - ecs_xtor_t dtor = rtt_ctx->type_info->hooks.dtor; + bool has_copy = rtt_ctx->type_info->hooks.copy != NULL; + bool has_ctor = rtt_ctx->type_info->hooks.ctor != NULL; + bool has_dtor = rtt_ctx->type_info->hooks.dtor != NULL; int i; for (i = 0; i < count; i++) { const ecs_vec_t *src_vec = ECS_ELEM(src_ptr, type_info->size, i); @@ -56494,16 +59683,31 @@ void flecs_rtt_vector_copy( ecs_vec_init_if(dst_vec, rtt_ctx->type_info->size); int32_t src_count = ecs_vec_count(src_vec); int32_t dst_count = ecs_vec_count(dst_vec); - if (dtor && dst_count) { - dtor(ecs_vec_first(dst_vec), dst_count, rtt_ctx->type_info); + if (has_dtor && dst_count) { + flecs_type_info_dtor( + ecs_vec_first(dst_vec), dst_count, rtt_ctx->type_info); } ecs_vec_set_count(NULL, dst_vec, rtt_ctx->type_info->size, src_count); - ctor(ecs_vec_first(dst_vec), src_count, rtt_ctx->type_info); - copy( - ecs_vec_first(dst_vec), - ecs_vec_first(src_vec), - src_count, - rtt_ctx->type_info); + if (has_ctor) { + flecs_type_info_ctor( + ecs_vec_first(dst_vec), src_count, rtt_ctx->type_info); + } else { + flecs_default_ctor( + ecs_vec_first(dst_vec), src_count, rtt_ctx->type_info); + } + if (has_copy) { + flecs_type_info_copy( + ecs_vec_first(dst_vec), + ecs_vec_first(src_vec), + src_count, + rtt_ctx->type_info); + } else { + flecs_rtt_default_copy( + ecs_vec_first(dst_vec), + ecs_vec_first(src_vec), + src_count, + rtt_ctx->type_info); + } } } @@ -56531,8 +59735,6 @@ int flecs_rtt_vector_cmp( } ecs_rtt_vector_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_cmp_t cmp = rtt_ctx->type_info->hooks.cmp; - ecs_assert(cmp, ECS_INVALID_PARAMETER, NULL); ecs_size_t element_size = rtt_ctx->type_info->size; const void *a = ecs_vec_first(vec_a); @@ -56542,7 +59744,7 @@ int flecs_rtt_vector_cmp( for (i = 0; i < count_a; i++) { const void *a_element = ECS_ELEM(a, element_size, i); const void *b_element = ECS_ELEM(b, element_size, i); - int c = cmp(a_element, b_element, rtt_ctx->type_info); + int c = flecs_type_info_cmp(a_element, b_element, rtt_ctx->type_info); if(c != 0) { return c; } @@ -56574,8 +59776,6 @@ bool flecs_rtt_vector_equals( } ecs_rtt_vector_ctx_t *rtt_ctx = type_info->hooks.lifecycle_ctx; - ecs_equals_t equals = rtt_ctx->type_info->hooks.equals; - ecs_assert(equals, ECS_INVALID_PARAMETER, NULL); ecs_size_t element_size = rtt_ctx->type_info->size; const void *a = ecs_vec_first(vec_a); @@ -56585,7 +59785,8 @@ bool flecs_rtt_vector_equals( for (i = 0; i < count_a; i++) { const void *a_element = ECS_ELEM(a, element_size, i); const void *b_element = ECS_ELEM(b, element_size, i); - int eq = equals(a_element, b_element, rtt_ctx->type_info); + bool eq = flecs_type_info_equals( + a_element, b_element, rtt_ctx->type_info); if(!eq) { return false; } @@ -56604,8 +59805,18 @@ void flecs_rtt_init_default_hooks_vector( { const EcsVector *vector_info = ecs_get(world, component, EcsVector); ecs_assert(vector_info != NULL, ECS_INTERNAL_ERROR, NULL); + if (!ecs_is_alive(world, vector_info->type)) { + ecs_err("vector '%s' has invalid element type", ecs_get_name(world, component)); + return; + } + const ecs_type_info_t *element_ti = ecs_get_type_info(world, vector_info->type); + if (!element_ti) { + ecs_err("vector '%s' has invalid element type", ecs_get_name(world, component)); + return; + } + ecs_rtt_vector_ctx_t *rtt_ctx = ecs_os_malloc_t(ecs_rtt_vector_ctx_t); rtt_ctx->type_info = element_ti; ecs_flags32_t flags = element_ti->hooks.flags; @@ -56868,13 +60079,6 @@ ecs_meta_op_kind_t flecs_meta_primitive_to_op_kind( } } -static -ecs_size_t flecs_meta_type_size(ecs_world_t *world, ecs_entity_t type) { - const EcsComponent *comp = ecs_get(world, type, EcsComponent); - ecs_assert(comp != NULL, ECS_INTERNAL_ERROR, NULL); - return comp->size; -} - static ecs_meta_op_t* flecs_meta_ops_add(ecs_vec_t *ops, ecs_meta_op_kind_t kind) { ecs_meta_op_t *op = ecs_vec_append_t(NULL, ops, ecs_meta_op_t); @@ -57031,7 +60235,7 @@ int flecs_meta_serialize_array_inline( ecs_meta_op_t *op = flecs_meta_ops_add(ops, EcsOpPushArray); op->type = elem_type; op->type_info = NULL; - op->elem_size = flecs_meta_type_size(world, elem_type); + op->elem_size = flecs_type_size(world, elem_type); op->offset = offset; } @@ -57087,7 +60291,7 @@ int flecs_meta_serialize_vector_type( op->type = type; op->type_info = ecs_get_type_info(world, type); ecs_assert(op->type_info != NULL, ECS_INTERNAL_ERROR, NULL); - op->elem_size = flecs_meta_type_size(world, ptr->type); + op->elem_size = flecs_type_size(world, ptr->type); } if (flecs_meta_serialize_type(world, ptr->type, 0, ops) != 0) { @@ -57135,7 +60339,7 @@ int flecs_meta_serialize_opaque_type( const EcsOpaque *o = ecs_get(world, type, EcsOpaque); ecs_assert(o != NULL, ECS_INTERNAL_ERROR, NULL); const EcsType *t = ecs_get(world, o->as_type, EcsType); - ecs_assert(o != NULL, ECS_INTERNAL_ERROR, + ecs_assert(t != NULL, ECS_INTERNAL_ERROR, "missing reflection for Opaque::as_type"); ecs_meta_op_kind_t kind = EcsOpOpaqueValue; @@ -57196,7 +60400,7 @@ int flecs_meta_serialize_struct( op = flecs_meta_ops_get(ops, cur); } else { if (flecs_meta_serialize_type( - world, member->type, member->offset, ops)) + world, member->type, member->offset, ops)) { continue; } @@ -57241,17 +60445,32 @@ int flecs_meta_serialize_type( return -1; } + int ret = 0; switch(ptr->kind) { - case EcsPrimitiveType: return flecs_meta_serialize_primitive(world, type, offset, ops); - case EcsEnumType: return flecs_meta_serialize_enum(world, type, offset, ops); - case EcsBitmaskType: return flecs_meta_serialize_bitmask(world, type, offset, ops); - case EcsStructType: return flecs_meta_serialize_struct(world, type, offset, ops); - case EcsArrayType: return flecs_meta_serialize_forward(world, type, offset, ops); - case EcsVectorType: return flecs_meta_serialize_forward(world, type, offset, ops); - case EcsOpaqueType: return flecs_meta_serialize_opaque_type(world, type, offset, ops); + case EcsPrimitiveType: + ret = flecs_meta_serialize_primitive(world, type, offset, ops); + break; + case EcsEnumType: + ret = flecs_meta_serialize_enum(world, type, offset, ops); + break; + case EcsBitmaskType: + ret = flecs_meta_serialize_bitmask(world, type, offset, ops); + break; + case EcsStructType: + ret = flecs_meta_serialize_struct(world, type, offset, ops); + break; + case EcsArrayType: + ret = flecs_meta_serialize_forward(world, type, offset, ops); + break; + case EcsVectorType: + ret = flecs_meta_serialize_forward(world, type, offset, ops); + break; + case EcsOpaqueType: + ret = flecs_meta_serialize_opaque_type(world, type, offset, ops); + break; } - return 0; + return ret; } void flecs_meta_type_serializer_init( @@ -57273,12 +60492,18 @@ void flecs_meta_type_serializer_init( continue; } + int ret; if (type_ptr->kind == EcsArrayType) { - flecs_meta_serialize_array_type(world, type, &ops); + ret = flecs_meta_serialize_array_type(world, type, &ops); } else if (type_ptr->kind == EcsVectorType) { - flecs_meta_serialize_vector_type(world, type, &ops); + ret = flecs_meta_serialize_vector_type(world, type, &ops); } else { - flecs_meta_serialize_type(world, type, 0, &ops); + ret = flecs_meta_serialize_type(world, type, 0, &ops); + } + + if (ret != 0) { + ecs_vec_fini_t(NULL, &ops, ecs_meta_op_t); + continue; } EcsTypeSerializer *ptr = ecs_ensure(world, type, EcsTypeSerializer); @@ -57984,12 +61209,47 @@ void ecs_set_os_api_impl(void) { #ifdef FLECS_PARSER +static +bool flecs_is_comment( + const char *pos) +{ + return pos[0] == '/' && (pos[1] == '/' || pos[1] == '*'); +} + +static +bool flecs_keyword_boundary( + const char *pos) +{ + if (!pos[0]) { + return true; + } + + if (isspace(pos[0])) { + return true; + } + + if (flecs_is_comment(pos)) { + return true; + } + + return false; +} + +static +bool flecs_keyword_match( + const char *pos, + const char *keyword) +{ + ecs_size_t len = ecs_os_strlen(keyword); + if (ecs_os_strncmp(pos, keyword, len)) { + return false; + } + + return flecs_keyword_boundary(pos + len); +} + #define Keyword(keyword, _kind)\ - } else if (!ecs_os_strncmp(pos, keyword " ", ecs_os_strlen(keyword) + 1)) {\ - out->value = keyword;\ - out->kind = _kind;\ - return pos + ecs_os_strlen(keyword);\ - } else if (!ecs_os_strncmp(pos, keyword "\n", ecs_os_strlen(keyword) + 1)) {\ + } else if (flecs_keyword_match(pos, keyword)) {\ out->value = keyword;\ out->kind = _kind;\ return pos + ecs_os_strlen(keyword); @@ -58006,6 +61266,23 @@ void ecs_set_os_api_impl(void) { out->kind = _kind;\ return pos + 1; +static +char* flecs_tokenizer_write( + ecs_parser_t *parser, + char *dst, + char ch) +{ + ecs_assert(dst != NULL, ECS_INTERNAL_ERROR, NULL); + + if (parser && parser->token_end) { + ecs_assert(dst < parser->token_end, ECS_INVALID_OPERATION, + "out of parser token storage"); + } + + dst[0] = ch; + return dst + 1; +} + const char* flecs_token_kind_str( ecs_token_kind_t kind) { @@ -58063,6 +61340,8 @@ const char* flecs_token_kind_str( return "keyword "; case EcsTokIdentifier: return "identifier "; + case EcsTokFunction: + return "function "; case EcsTokString: return "string "; case EcsTokChar: @@ -58133,6 +61412,7 @@ const char* flecs_token_str( case EcsTokKeywordTemplate: return "template"; case EcsTokKeywordModule: return "module"; case EcsTokIdentifier: return "identifier"; + case EcsTokFunction: return "function"; case EcsTokString: return "string"; case EcsTokChar: return "char"; case EcsTokNumber: return "number"; @@ -58148,7 +61428,7 @@ const char* flecs_scan_whitespace( ecs_parser_t *parser, const char *pos) { - (void)parser; + ecs_assert(pos != NULL, ECS_INTERNAL_ERROR, NULL); if (parser->significant_newline) { while (pos[0] && isspace(pos[0]) && pos[0] != '\n') { @@ -58163,38 +61443,149 @@ const char* flecs_scan_whitespace( return pos; } +static +const char* flecs_scan_line_comment( + const char *pos) +{ + ecs_assert(pos[0] == '/' && pos[1] == '/', ECS_INTERNAL_ERROR, NULL); + + for (pos = pos + 2; pos[0] && pos[0] != '\n'; pos ++) { } + return pos; +} + +static +bool flecs_newline_followed_by_comment( + ecs_parser_t *parser, + const char *newline) +{ + ecs_assert(newline[0] == '\n', ECS_INTERNAL_ERROR, NULL); + const char *next = flecs_scan_whitespace(parser, newline + 1); + return flecs_is_comment(next); +} + +static +const char* flecs_scan_multiline_comment( + ecs_parser_t *parser, + const char *pos) +{ + ecs_assert(pos[0] == '/' && pos[1] == '*', ECS_INTERNAL_ERROR, NULL); + + for (pos = &pos[2]; pos[0] != 0; pos ++) { + if (pos[0] == '*' && pos[1] == '/') { + return pos + 2; + } + } + + ecs_parser_error(parser->name, parser->code, + pos - parser->code, "missing */ for multiline comment"); + return NULL; +} + +static +const char* flecs_scan_significant_line_comment_newline_run( + ecs_parser_t *parser, + const char *comment_newline) +{ + ecs_assert(comment_newline[0] == '\n', ECS_INTERNAL_ERROR, NULL); + + const char *next = comment_newline + 1; + const char *last_newline = comment_newline; + bool collapse = false; + + while (next[0]) { + next = flecs_scan_whitespace(parser, next); + + if (next[0] == '\n') { + collapse = true; + last_newline = next; + next ++; + continue; + } + + if (next[0] == '/' && next[1] == '/') { + collapse = true; + next = flecs_scan_line_comment(next); + if (next[0] == '\n') { + last_newline = next; + next ++; + } + continue; + } + + if (next[0] == '/' && next[1] == '*') { + collapse = true; + const char *ml_end = &next[2]; + while (ml_end[0]) { + if (ml_end[0] == '*' && ml_end[1] == '/') { + next = ml_end + 2; + break; + } + ml_end ++; + } + + if (!ml_end[0]) { + /* Unterminated multiline comments are reported by the regular + * tokenizer path. Keep this pass non-fatal as it is only used + * to decide whether newlines can be collapsed. */ + break; + } + continue; + } + + break; + } + + return collapse ? last_newline : comment_newline; +} + static const char* flecs_scan_whitespace_and_comment( ecs_parser_t *parser, const char *pos) { + if (!pos) { + return NULL; + } + repeat_skip_whitespace_comment: pos = flecs_scan_whitespace(parser, pos); + if (pos[0] == '/') { if (pos[1] == '/') { - for (pos = pos + 2; pos[0] && pos[0] != '\n'; pos ++) { } + pos = flecs_scan_line_comment(pos); if (pos[0] == '\n') { + if (parser->significant_newline) { + return flecs_scan_significant_line_comment_newline_run( + parser, pos); + } pos ++; goto repeat_skip_whitespace_comment; } } else if (pos[1] == '*') { - for (pos = &pos[2]; pos[0] != 0; pos ++) { - if (pos[0] == '*' && pos[1] == '/') { - pos += 2; - goto repeat_skip_whitespace_comment; - } + pos = flecs_scan_multiline_comment(parser, pos); + if (!pos) { + return NULL; } - ecs_parser_error(parser->name, parser->code, - pos - parser->code, "missing */ for multiline comment"); - return NULL; + const char *newline = pos; + if (newline[0] == '\r' && newline[1] == '\n') { + newline ++; + } + + if (parser->significant_newline && newline[0] == '\n' && + flecs_newline_followed_by_comment(parser, newline)) + { + return flecs_scan_significant_line_comment_newline_run( + parser, newline); + } + + goto repeat_skip_whitespace_comment; } } return pos; } -// Identifier token static bool flecs_script_is_identifier( char c) @@ -58234,6 +61625,11 @@ const char* flecs_tokenizer_identifier( do { char c = pos[0]; + + if ((c == '.') && (pos[1] == '.')) { + break; + } + bool is_ident = flecs_script_is_identifier(c) || isdigit(c); if (!is_var) { @@ -58255,6 +61651,9 @@ const char* flecs_tokenizer_identifier( if (!is_ident) { if (c == '\\') { pos ++; + if (!pos[0]) { + goto done; + } } else if (c == '<') { int32_t indent = 0; do { @@ -58271,8 +61670,7 @@ const char* flecs_tokenizer_identifier( } if (outpos) { - *outpos = c; - outpos ++; + outpos = flecs_tokenizer_write(parser, outpos, c); } pos ++; @@ -58281,34 +61679,41 @@ const char* flecs_tokenizer_identifier( } } while (true); - if (outpos && parser) { - *outpos = '\0'; - parser->token_cur = outpos + 1; - } - return pos; + goto done; } else if (c == '>') { ecs_parser_error(name, code, pos - code, "> without < in identifier"); return NULL; } else { - if (outpos && parser) { - *outpos = '\0'; - parser->token_cur = outpos + 1; - } - return pos; + goto done; } } if (outpos) { - *outpos = *pos; - outpos ++; + outpos = flecs_tokenizer_write(parser, outpos, *pos); } pos ++; } while (true); + +done: + if (outpos) { + outpos = flecs_tokenizer_write(parser, outpos, '\0'); + if (parser) { + parser->token_cur = outpos; + } + } + + if (parser && parser->function_token) { + if (pos[0] == '(') { + out->kind = EcsTokFunction; + pos ++; + } + } + + return pos; } -// Number token static static bool flecs_script_is_number( const char *c) @@ -58327,34 +61732,33 @@ const char* flecs_script_number( bool dot_parsed = false; bool e_parsed = false; + bool digit_parsed = false; int base = 10; ecs_assert(flecs_script_is_number(pos), ECS_INTERNAL_ERROR, NULL); char *outpos = parser->token_cur; if (pos[0] == '-') { - outpos[0] = pos[0]; + outpos = flecs_tokenizer_write(parser, outpos, pos[0]); pos ++; - outpos ++; } if (pos[0] == '0' && (pos[1] == 'x' || pos[1] == 'X')) { base = 16; - outpos[0] = pos[0]; - outpos[1] = pos[1]; - outpos += 2; + outpos = flecs_tokenizer_write(parser, outpos, pos[0]); + outpos = flecs_tokenizer_write(parser, outpos, pos[1]); pos += 2; } else if (pos[0] == '0' && (pos[1] == 'b' || pos[1] == 'B')) { base = 2; - outpos[0] = pos[0]; - outpos[1] = pos[1]; - outpos += 2; + outpos = flecs_tokenizer_write(parser, outpos, pos[0]); + outpos = flecs_tokenizer_write(parser, outpos, pos[1]); pos += 2; } do { char c = pos[0]; bool valid_number = false; + bool handled_char = false; if (c == '.') { if (!dot_parsed && !e_parsed) { @@ -58363,30 +61767,48 @@ const char* flecs_script_number( valid_number = true; } } - } else if (c == 'e') { - if (!e_parsed) { + } else if ((c == 'e' || c == 'E') && base == 10) { + if (!e_parsed && digit_parsed) { if (isdigit(pos[1])) { e_parsed = true; valid_number = true; + } else if ((pos[1] == '+' || pos[1] == '-') && isdigit(pos[2])) { + e_parsed = true; + valid_number = true; + handled_char = true; + + outpos = flecs_tokenizer_write(parser, outpos, c); + outpos = flecs_tokenizer_write(parser, outpos, pos[1]); + pos += 2; } } } else if ((base == 10) && isdigit(c)) { + digit_parsed = true; valid_number = true; } else if ((base == 16) && isxdigit(c)) { + digit_parsed = true; valid_number = true; } else if ((base == 2) && (c == '0' || c == '1')) { + digit_parsed = true; valid_number = true; } if (!valid_number) { - *outpos = '\0'; - parser->token_cur = outpos + 1; + if (!digit_parsed && base != 10) { + ecs_parser_error(parser->name, parser->code, + pos - parser->code, "missing digits in number literal"); + return NULL; + } + + outpos = flecs_tokenizer_write(parser, outpos, '\0'); + parser->token_cur = outpos; break; } - outpos[0] = pos[0]; - outpos ++; - pos ++; + if (!handled_char) { + outpos = flecs_tokenizer_write(parser, outpos, pos[0]); + pos ++; + } } while (true); return pos; @@ -58433,18 +61855,22 @@ const char* flecs_script_char( ecs_parser_error(parser->name, parser->code, pos - parser->code, "Empty char"); return NULL; - } else if((len > 2) || (len == 2 && parser->token_cur[0] == '\\')) { + } else if ((len > 1) && !((len == 2) && (pos[1] == '\\'))) { ecs_parser_error(parser->name, parser->code, pos - parser->code, "only one char allowed"); return NULL; } - ecs_os_memcpy(parser->token_cur, pos + 1, len); - parser->token_cur[len] = '\0'; + char *outpos = parser->token_cur; + int32_t i; + for (i = 0; i < len; i ++) { + outpos = flecs_tokenizer_write(parser, outpos, pos[i + 1]); + } + outpos = flecs_tokenizer_write(parser, outpos, '\0'); out->kind = EcsTokChar; out->value = parser->token_cur; - parser->token_cur += len + 1; + parser->token_cur = outpos; return end + 2; } @@ -58463,12 +61889,16 @@ const char* flecs_script_string( end --; int32_t len = flecs_ito(int32_t, end - pos); - ecs_os_memcpy(parser->token_cur, pos + 1, len); - parser->token_cur[len] = '\0'; + char *outpos = parser->token_cur; + int32_t i; + for (i = 0; i < len; i ++) { + outpos = flecs_tokenizer_write(parser, outpos, pos[i + 1]); + } + outpos = flecs_tokenizer_write(parser, outpos, '\0'); out->kind = EcsTokString; out->value = parser->token_cur; - parser->token_cur += len + 1; + parser->token_cur = outpos; return end + 2; } @@ -58488,18 +61918,24 @@ const char* flecs_script_multiline_string( } if (ch != '`') { + ecs_parser_error(parser->name, parser->code, + end - parser->code, "unterminated string"); return NULL; } end --; int32_t len = flecs_ito(int32_t, end - pos); - ecs_os_memcpy(parser->token_cur, pos + 1, len); - parser->token_cur[len] = '\0'; + char *outpos = parser->token_cur; + int32_t i; + for (i = 0; i < len; i ++) { + outpos = flecs_tokenizer_write(parser, outpos, pos[i + 1]); + } + outpos = flecs_tokenizer_write(parser, outpos, '\0'); out->kind = EcsTokString; out->value = parser->token_cur; - parser->token_cur += len + 1; + parser->token_cur = outpos; return end + 2; } @@ -58538,16 +61974,20 @@ const char* flecs_tokenizer_until( } int32_t len = flecs_ito(int32_t, pos - start); - ecs_os_memcpy(parser->token_cur, start, len); + char *token_start = parser->token_cur; + char *outpos = token_start; + int32_t i; + for (i = 0; i < len; i ++) { + outpos = flecs_tokenizer_write(parser, outpos, start[i]); + } out->value = parser->token_cur; - parser->token_cur += len; + parser->token_cur = outpos; - while (isspace(parser->token_cur[-1])) { + while (parser->token_cur != token_start && isspace(parser->token_cur[-1])) { parser->token_cur --; } - parser->token_cur[0] = '\0'; - parser->token_cur ++; + parser->token_cur = flecs_tokenizer_write(parser, parser->token_cur, '\0'); return pos; } @@ -58558,9 +61998,16 @@ const char* flecs_token( ecs_token_t *out, bool is_lookahead) { + if (!pos) { + if (!is_lookahead) { + ecs_parser_error(parser->name, parser->code, 0, + "unexpected end of parser state"); + } + return NULL; + } + parser->pos = pos; - // Skip whitespace and comments pos = flecs_scan_whitespace_and_comment(parser, pos); if (!pos) { return NULL; @@ -58574,12 +62021,16 @@ const char* flecs_token( return pos; } else if (pos[0] == '\n') { out->kind = EcsTokNewline; - - // Parse multiple newlines/whitespaces as a single token + pos = flecs_scan_whitespace_and_comment(parser, pos + 1); + if (!pos) { + return NULL; + } + if (pos[0] == '\n') { pos ++; } + return pos; } else if (flecs_script_is_number(pos)) { @@ -59290,8 +62741,10 @@ bool flecs_pipeline_build( pq->match_count = new_match_count; - ecs_assert(pq->cur_op <= ecs_vec_last_t(&pq->ops, ecs_pipeline_op_t), - ECS_INTERNAL_ERROR, NULL); + if (ecs_vec_count(&pq->ops)) { + ecs_assert((pq->cur_op <= ecs_vec_last_t(&pq->ops, ecs_pipeline_op_t)), + ECS_INTERNAL_ERROR, NULL); + } return true; } @@ -59680,7 +63133,6 @@ ecs_entity_t ecs_pipeline_init( ecs_pipeline_state_t *pq = ecs_os_calloc_t(ecs_pipeline_state_t); pq->query = query; pq->match_count = -1; - pq->cr_inactive = flecs_components_ensure(world, EcsEmpty); ecs_set(world, result, EcsPipeline, { pq }); return result; @@ -59723,11 +63175,7 @@ void FlecsPipelineImport( { ECS_MODULE(world, FlecsPipeline); ECS_IMPORT(world, FlecsSystem); -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); - ecs_doc_set_brief(world, ecs_id(FlecsPipeline), - "Module that schedules and runs systems"); -#endif + ecs_set_name_prefix(world, "Ecs"); flecs_bootstrap_component(world, EcsPipeline); @@ -60136,7 +63584,8 @@ bool ecs_using_task_threads( .name = script_name,\ .code = expr,\ .pos = expr,\ - .token_cur = tokens\ + .token_cur = tokens,\ + .token_end = &(tokens)[tokens_len]\ } /* Definitions for parser functions */ @@ -60320,6 +63769,16 @@ bool ecs_using_task_threads( parser->token_cur = parser->token_keep;\ }\ } else {\ + if (flecs_token(parser, pos, &lookahead_token, false)) {\ + if (lookahead_token.value) {\ + Error("unexpected %s'%s'", \ + flecs_token_kind_str(lookahead_token.kind), \ + lookahead_token.value);\ + } else {\ + Error("unexpected %s", \ + flecs_token_kind_str(lookahead_token.kind));\ + }\ + }\ goto error;\ } @@ -60546,6 +64005,23 @@ const char* flecs_term_parse_arg( // Position(src // ^ Parse( + case '@': { + parser->term->id = ECS_VALUE_PAIR; + Parse( + case '*': + ref->id = EcsWildcard; + break; + case EcsTokIdentifier: + ref->name = Token(1); + break; + case EcsTokNumber: { + char *end; + ref->id = strtoul(Token(1), &end, 10); + break; + } + ); + break; + } case EcsTokTermIdentifier: { ref->name = Token(0); @@ -61002,7 +64478,7 @@ const char* flecs_term_parse( ecs_term_t *term) { ecs_assert(world != NULL, ECS_INVALID_PARAMETER, NULL); - ecs_assert(expr != NULL, ECS_INVALID_PARAMETER, name); + ecs_assert(expr != NULL, ECS_INVALID_PARAMETER, "%s", name); ecs_assert(term != NULL, ECS_INVALID_PARAMETER, NULL); ecs_parser_t parser = { @@ -61031,7 +64507,7 @@ const char* flecs_id_parse( ecs_id_t *id) { ecs_assert(world != NULL, ECS_INVALID_PARAMETER, NULL); - ecs_assert(expr != NULL, ECS_INVALID_PARAMETER, name); + ecs_assert(expr != NULL, ECS_INVALID_PARAMETER, "%s", name); ecs_assert(id != NULL, ECS_INVALID_PARAMETER, NULL); char token_buffer[256]; @@ -61570,26 +65046,79 @@ ecs_script_for_range_t* flecs_script_insert_for_range( static void ecs_script_params_free(ecs_vec_t *params) { - ecs_script_parameter_t *array = ecs_vec_first(params); int32_t i, count = ecs_vec_count(params); - for (i = 0; i < count; i ++) { - /* Safe, component owns string */ - ecs_os_free(ECS_CONST_CAST(char*, array[i].name)); + if (count) { + ecs_script_parameter_t *array = ecs_vec_first(params); + for (i = 0; i < count; i ++) { + /* Safe, component owns string */ + ecs_os_free(ECS_CONST_CAST(char*, array[i].name)); + } } + ecs_vec_fini_t(NULL, params, ecs_script_parameter_t); + ecs_os_zeromem(params); } static -ECS_MOVE(EcsScriptConstVar, dst, src, { - if (dst->value.ptr) { - ecs_assert(dst->type_info != NULL, ECS_INTERNAL_ERROR, NULL); +void ecs_script_params_copy( + ecs_vec_t *dst, + const ecs_vec_t *src) +{ + int32_t i, count = ecs_vec_count(src); + if (!count) { + ecs_os_zeromem(dst); + return; + } - if (dst->type_info->hooks.dtor) { - dst->type_info->hooks.dtor(dst->value.ptr, 1, dst->type_info); - } + const ecs_script_parameter_t *src_array = ecs_vec_first(src); + if (!src_array) { + ecs_os_zeromem(dst); + return; + } + + ecs_vec_init_t(NULL, dst, ecs_script_parameter_t, count); + for (i = 0; i < count; i ++) { + ecs_script_parameter_t *p = ecs_vec_append_t( + NULL, dst, ecs_script_parameter_t); + p->type = src_array[i].type; + p->name = src_array[i].name ? ecs_os_strdup(src_array[i].name) : NULL; + } +} + +static +void ecs_script_const_var_fini( + EcsScriptConstVar *ptr) +{ + if (!ptr->value.ptr) { + return; + } + + ecs_assert(ptr->type_info != NULL, ECS_INTERNAL_ERROR, NULL); + flecs_type_info_dtor(ptr->value.ptr, 1, ptr->type_info); + + ecs_os_free(ptr->value.ptr); + ptr->value.ptr = NULL; + ptr->value.type = 0; + ptr->type_info = NULL; +} - ecs_os_free(dst->value.ptr); +static +ECS_COPY(EcsScriptConstVar, dst, src, { + ecs_script_const_var_fini(dst); + dst->value.type = src->value.type; + dst->type_info = src->type_info; + + if (src->value.ptr) { + ecs_assert(src->type_info != NULL, ECS_INTERNAL_ERROR, NULL); + dst->value.ptr = ecs_os_malloc(src->type_info->size); + flecs_type_info_copy( + dst->value.ptr, src->value.ptr, 1, src->type_info); } +}) + +static +ECS_MOVE(EcsScriptConstVar, dst, src, { + ecs_script_const_var_fini(dst); *dst = *src; @@ -61600,13 +65129,18 @@ ECS_MOVE(EcsScriptConstVar, dst, src, { static ECS_DTOR(EcsScriptConstVar, ptr, { - if (ptr->value.ptr) { - ecs_assert(ptr->type_info != NULL, ECS_INTERNAL_ERROR, NULL); - if (ptr->type_info->hooks.dtor) { - ptr->type_info->hooks.dtor(ptr->value.ptr, 1, ptr->type_info); - } - } - ecs_os_free(ptr->value.ptr); + ecs_script_const_var_fini(ptr); +}) + +static +ECS_COPY(EcsScriptFunction, dst, src, { + ecs_script_params_free(&dst->params); + dst->return_type = src->return_type; + dst->callback = src->callback; + ecs_os_memcpy_n(dst->vector_callbacks, src->vector_callbacks, + ecs_vector_function_callback_t, FLECS_SCRIPT_VECTOR_FUNCTION_COUNT); + dst->ctx = src->ctx; + ecs_script_params_copy(&dst->params, &src->params); }) static @@ -61621,6 +65155,17 @@ ECS_DTOR(EcsScriptFunction, ptr, { ecs_script_params_free(&ptr->params); }) +static +ECS_COPY(EcsScriptMethod, dst, src, { + ecs_script_params_free(&dst->params); + dst->return_type = src->return_type; + dst->callback = src->callback; + ecs_os_memcpy_n(dst->vector_callbacks, src->vector_callbacks, + ecs_vector_function_callback_t, FLECS_SCRIPT_VECTOR_FUNCTION_COUNT); + dst->ctx = src->ctx; + ecs_script_params_copy(&dst->params, &src->params); +}) + static ECS_MOVE(EcsScriptMethod, dst, src, { ecs_script_params_free(&dst->params); @@ -61690,30 +65235,65 @@ ecs_value_t ecs_const_var_get( return (ecs_value_t){0}; } -ecs_entity_t ecs_function_init( - ecs_world_t *world, +#ifdef FLECS_DEBUG +static +bool flecs_script_function_has_vector_args( + const ecs_function_desc_t *desc) +{ + int32_t i; + for (i = 0; i < FLECS_SCRIPT_FUNCTION_ARGS_MAX; i ++) { + if (!desc->params[i].name) { + break; + } + + if (desc->params[i].type == EcsScriptVectorType) { + return true; + } + } + + return false; +} + +static +int flecs_script_function_validate_desc( const ecs_function_desc_t *desc) { - flecs_poly_assert(world, ecs_world_t); ecs_check(desc != NULL, ECS_INVALID_PARAMETER, NULL); ecs_check(desc->name != NULL, ECS_INVALID_PARAMETER, NULL); - ecs_check(desc->callback != NULL, ECS_INVALID_PARAMETER, NULL); ecs_check(desc->return_type != 0, ECS_INVALID_PARAMETER, NULL); - ecs_entity_t result = ecs_entity(world, { - .name = desc->name, - .parent = desc->parent - }); + if (!flecs_script_function_has_vector_args(desc)) { + ecs_check(desc->callback != NULL, ECS_INVALID_PARAMETER, "%s", desc->name); + ecs_check(desc->return_type != EcsScriptVectorType, ECS_INVALID_PARAMETER, + "function '%s' cannot have flecs.script.vector return type unless " + "at least one argument is of type flecs.script.vector", + desc->name); + } else { + int32_t i; + for (i = 0; i < EcsPrimitiveKindLast; i ++) { + if (desc->vector_callbacks[i]) { + break; + } + } - if (!result) { - goto error; + if (i == EcsPrimitiveKindLast) { + ecs_throw(ECS_INVALID_PARAMETER, "function '%s' has vector " + "arguments, must implement at least one element of " + ".vector_callbacks", desc->name); + } } - EcsScriptFunction *f = ecs_ensure(world, result, EcsScriptFunction); - f->return_type = desc->return_type; - f->callback = desc->callback; - f->ctx = desc->ctx; + return 0; +error: + return -1; +} +#endif +static +void flecs_script_function_parse_args( + const ecs_function_desc_t *desc, + ecs_vec_t *params) +{ int32_t i; for (i = 0; i < FLECS_SCRIPT_FUNCTION_ARGS_MAX; i ++) { if (!desc->params[i].name) { @@ -61721,14 +65301,41 @@ ecs_entity_t ecs_function_init( } if (!i) { - ecs_vec_init_t(NULL, &f->params, ecs_script_parameter_t, 0); + ecs_vec_init_t(NULL, params, ecs_script_parameter_t, 0); } ecs_script_parameter_t *p = ecs_vec_append_t( - NULL, &f->params, ecs_script_parameter_t); + NULL, params, ecs_script_parameter_t); p->type = desc->params[i].type; p->name = ecs_os_strdup(desc->params[i].name); } +} + +ecs_entity_t ecs_function_init( + ecs_world_t *world, + const ecs_function_desc_t *desc) +{ + flecs_poly_assert(world, ecs_world_t); + ecs_dbg_assert(!flecs_script_function_validate_desc(desc), + ECS_INVALID_PARAMETER, NULL); + + ecs_entity_t result = ecs_entity(world, { + .name = desc->name, + .parent = desc->parent + }); + + if (!result) { + goto error; + } + + EcsScriptFunction *f = ecs_ensure(world, result, EcsScriptFunction); + f->return_type = desc->return_type; + f->callback = desc->callback; + ecs_os_memcpy_n(f->vector_callbacks, desc->vector_callbacks, + ecs_vector_function_callback_t, FLECS_SCRIPT_VECTOR_FUNCTION_COUNT); + f->ctx = desc->ctx; + + flecs_script_function_parse_args(desc, &f->params); ecs_modified(world, result, EcsScriptFunction); @@ -61742,11 +65349,9 @@ ecs_entity_t ecs_method_init( const ecs_function_desc_t *desc) { flecs_poly_assert(world, ecs_world_t); - ecs_check(desc != NULL, ECS_INVALID_PARAMETER, NULL); - ecs_check(desc->name != NULL, ECS_INVALID_PARAMETER, NULL); - ecs_check(desc->callback != NULL, ECS_INVALID_PARAMETER, NULL); + ecs_dbg_assert(!flecs_script_function_validate_desc(desc), + ECS_INVALID_PARAMETER, NULL); ecs_check(desc->parent != 0, ECS_INVALID_PARAMETER, NULL); - ecs_check(desc->return_type != 0, ECS_INVALID_PARAMETER, NULL); ecs_entity_t result = ecs_entity(world, { .name = desc->name, @@ -61760,23 +65365,11 @@ ecs_entity_t ecs_method_init( EcsScriptMethod *f = ecs_ensure(world, result, EcsScriptMethod); f->return_type = desc->return_type; f->callback = desc->callback; + ecs_os_memcpy_n(f->vector_callbacks, desc->vector_callbacks, + ecs_vector_function_callback_t, FLECS_SCRIPT_VECTOR_FUNCTION_COUNT); f->ctx = desc->ctx; - - int32_t i; - for (i = 0; i < FLECS_SCRIPT_FUNCTION_ARGS_MAX; i ++) { - if (!desc->params[i].name) { - break; - } - - if (!i) { - ecs_vec_init_t(NULL, &f->params, ecs_script_parameter_t, 0); - } - - ecs_script_parameter_t *p = ecs_vec_append_t( - NULL, &f->params, ecs_script_parameter_t); - p->type = desc->params[i].type; - p->name = ecs_os_strdup(desc->params[i].name); - } + + flecs_script_function_parse_args(desc, &f->params); ecs_modified(world, result, EcsScriptMethod); @@ -61810,22 +65403,22 @@ void flecs_function_import( ecs_set_hooks(world, EcsScriptConstVar, { .ctor = flecs_default_ctor, .dtor = ecs_dtor(EcsScriptConstVar), + .copy = ecs_copy(EcsScriptConstVar), .move = ecs_move(EcsScriptConstVar), - .flags = ECS_TYPE_HOOK_COPY_ILLEGAL }); ecs_set_hooks(world, EcsScriptFunction, { .ctor = flecs_default_ctor, .dtor = ecs_dtor(EcsScriptFunction), + .copy = ecs_copy(EcsScriptFunction), .move = ecs_move(EcsScriptFunction), - .flags = ECS_TYPE_HOOK_COPY_ILLEGAL }); ecs_set_hooks(world, EcsScriptMethod, { .ctor = flecs_default_ctor, .dtor = ecs_dtor(EcsScriptMethod), + .copy = ecs_copy(EcsScriptMethod), .move = ecs_move(EcsScriptMethod), - .flags = ECS_TYPE_HOOK_COPY_ILLEGAL }); flecs_script_register_builtin_functions(world); @@ -61951,71 +65544,47 @@ static void flecs_script_register_builtin_doc_functions( ecs_world_t *world) { - { - ecs_entity_t m = ecs_method(world, { - .name = "doc_name", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_doc_name - }); - - ecs_doc_set_brief(world, m, "Returns entity doc name"); - } - - { - ecs_entity_t m = ecs_method(world, { - .name = "doc_uuid", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_doc_uuid - }); - - ecs_doc_set_brief(world, m, "Returns entity doc uuid"); - } - - { - ecs_entity_t m = ecs_method(world, { - .name = "doc_brief", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_doc_brief - }); - - ecs_doc_set_brief(world, m, "Returns entity doc brief description"); - } - - { - ecs_entity_t m = ecs_method(world, { - .name = "doc_detail", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_doc_detail - }); + ecs_method(world, { + .name = "doc_name", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_doc_name + }); - ecs_doc_set_brief(world, m, "Returns entity doc detailed description"); - } + ecs_method(world, { + .name = "doc_uuid", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_doc_uuid + }); - { - ecs_entity_t m = ecs_method(world, { - .name = "doc_link", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_doc_link - }); + ecs_method(world, { + .name = "doc_brief", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_doc_brief + }); - ecs_doc_set_brief(world, m, "Returns entity doc link"); - } + ecs_method(world, { + .name = "doc_detail", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_doc_detail + }); - { - ecs_entity_t m = ecs_method(world, { - .name = "doc_color", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_doc_color - }); + ecs_method(world, { + .name = "doc_link", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_doc_link + }); - ecs_doc_set_brief(world, m, "Returns entity doc color"); - } + ecs_method(world, { + .name = "doc_color", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_doc_color + }); } #else @@ -62032,81 +65601,57 @@ void flecs_script_register_builtin_doc_functions( void flecs_script_register_builtin_functions( ecs_world_t *world) { - { - ecs_entity_t m = ecs_method(world, { - .name = "name", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_name - }); - - ecs_doc_set_brief(world, m, "Returns entity name"); - } - - { - ecs_entity_t m = ecs_method(world, { - .name = "path", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_string_t), - .callback = flecs_meta_entity_path - }); - - ecs_doc_set_brief(world, m, "Returns entity path"); - } - - { - ecs_entity_t m = ecs_method(world, { - .name = "parent", - .parent = ecs_id(ecs_entity_t), - .return_type = ecs_id(ecs_entity_t), - .callback = flecs_meta_entity_parent - }); - - ecs_doc_set_brief(world, m, "Returns entity parent"); - } - - { - ecs_entity_t m = ecs_method(world, { - .name = "has", - .parent = ecs_id(ecs_entity_t), - .params = { - { .name = "component", .type = ecs_id(ecs_id_t) } - }, - .return_type = ecs_id(ecs_bool_t), - .callback = flecs_meta_entity_has - }); + ecs_method(world, { + .name = "name", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_name + }); - ecs_doc_set_brief(world, m, "Returns whether entity has component"); - } + ecs_method(world, { + .name = "path", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_string_t), + .callback = flecs_meta_entity_path + }); - { - ecs_entity_t m = ecs_method(world, { - .name = "lookup", - .parent = ecs_id(ecs_entity_t), - .params = { - { .name = "path", .type = ecs_id(ecs_string_t) } - }, - .return_type = ecs_id(ecs_entity_t), - .callback = flecs_meta_entity_lookup - }); + ecs_method(world, { + .name = "parent", + .parent = ecs_id(ecs_entity_t), + .return_type = ecs_id(ecs_entity_t), + .callback = flecs_meta_entity_parent + }); - ecs_doc_set_brief(world, m, "Lookup child by name"); - } + ecs_method(world, { + .name = "has", + .parent = ecs_id(ecs_entity_t), + .params = { + { .name = "component", .type = ecs_id(ecs_id_t) } + }, + .return_type = ecs_id(ecs_bool_t), + .callback = flecs_meta_entity_has + }); - { - ecs_entity_t m = ecs_function(world, { - .name = "pair", - .parent = ecs_entity(world, { .name = "core" }), - .params = { - { .name = "first", .type = ecs_id(ecs_entity_t) }, - { .name = "second", .type = ecs_id(ecs_entity_t) } - }, - .return_type = ecs_id(ecs_id_t), - .callback = flecs_meta_core_pair - }); + ecs_method(world, { + .name = "lookup", + .parent = ecs_id(ecs_entity_t), + .params = { + { .name = "path", .type = ecs_id(ecs_string_t) } + }, + .return_type = ecs_id(ecs_entity_t), + .callback = flecs_meta_entity_lookup + }); - ecs_doc_set_brief(world, m, "Returns a pair identifier"); - } + ecs_function(world, { + .name = "pair", + .parent = ecs_entity(world, { .name = "core" }), + .params = { + { .name = "first", .type = ecs_id(ecs_entity_t) }, + { .name = "second", .type = ecs_id(ecs_entity_t) } + }, + .return_type = ecs_id(ecs_id_t), + .callback = flecs_meta_core_pair + }); flecs_script_register_builtin_doc_functions(world); } @@ -62250,6 +65795,233 @@ void flecs_script_rng_get_uint( } } +double flecs_lerp( + double a, + double b, + double t) +{ + return a + t * (b - a); +} + +void flecs_script_min( + const ecs_function_ctx_t *ctx, + int32_t argc, + const ecs_value_t *argv, + ecs_value_t *result) +{ + (void)ctx; + (void)argc; + double a = *(double*)argv[0].ptr; + double b = *(double*)argv[1].ptr; + *(double*)result->ptr = (a < b) ? a : b; +} + +void flecs_script_max( + const ecs_function_ctx_t *ctx, + int32_t argc, + const ecs_value_t *argv, + ecs_value_t *result) +{ + (void)ctx; + (void)argc; + double a = *(double*)argv[0].ptr; + double b = *(double*)argv[1].ptr; + *(double*)result->ptr = (a > b) ? a : b; +} + +#define FLECS_SCRIPT_LERP(type)\ + static void flecs_script_lerp_##type(\ + const ecs_function_ctx_t *ctx,\ + int32_t argc,\ + const ecs_value_t *argv,\ + ecs_value_t *result,\ + int32_t elem_count)\ + {\ + (void)ctx; (void)argc;\ + type *a = argv[0].ptr;\ + type *b = argv[1].ptr;\ + type t = (type)*(double*)argv[2].ptr;\ + type *r = result->ptr;\ + for (int i = 0; i < elem_count; i ++) {\ + r[i] = a[i] + t * (b[i] - a[i]);\ + }\ + } + +FLECS_SCRIPT_LERP(float) +FLECS_SCRIPT_LERP(double) + +#define FLECS_SCRIPT_SMOOTHSTEP(type)\ + void flecs_script_smoothstep_##type(\ + const ecs_function_ctx_t *ctx,\ + int32_t argc,\ + const ecs_value_t *argv,\ + ecs_value_t *result,\ + int32_t elem_count)\ + {\ + (void)ctx; (void)argc;\ + type *a = argv[0].ptr;\ + type *b = argv[1].ptr;\ + type t = (type)*(double*)argv[2].ptr;\ + type *r = result->ptr;\ + for (int i = 0; i < elem_count; i ++) {\ + type v = (t - a[i]) / (b[i] - a[i]);\ + type x = (v < (type)0) ? (type)0\ + : (v > (type)1) ? (type)1\ + : v;\ + r[i] = x * x * (3 - 2 * x);\ + }\ + } + +FLECS_SCRIPT_SMOOTHSTEP(float) +FLECS_SCRIPT_SMOOTHSTEP(double) + +#define FLECS_SCRIPT_CLAMP(type)\ + static void flecs_script_clamp_##type(\ + const ecs_function_ctx_t *ctx,\ + int32_t argc,\ + const ecs_value_t *argv,\ + ecs_value_t *result,\ + int32_t elem_count)\ + {\ + (void)ctx; (void)argc;\ + type *v = argv[0].ptr;\ + type min = (type)*(double*)argv[1].ptr;\ + type max = (type)*(double*)argv[2].ptr;\ + type *r = result->ptr;\ + for (int i = 0; i < elem_count; i ++) {\ + r[i] = (v[i] < min) ? min\ + : (v[i] > max) ? max\ + : v[i];\ + }\ + } + +FLECS_SCRIPT_CLAMP(int8_t) +FLECS_SCRIPT_CLAMP(int16_t) +FLECS_SCRIPT_CLAMP(int32_t) +FLECS_SCRIPT_CLAMP(int64_t) +FLECS_SCRIPT_CLAMP(uint8_t) +FLECS_SCRIPT_CLAMP(uint16_t) +FLECS_SCRIPT_CLAMP(uint32_t) +FLECS_SCRIPT_CLAMP(uint64_t) +FLECS_SCRIPT_CLAMP(float) +FLECS_SCRIPT_CLAMP(double) + +#define FLECS_SCRIPT_DOT(type)\ + static void flecs_script_dot_##type(\ + const ecs_function_ctx_t *ctx,\ + int32_t argc,\ + const ecs_value_t *argv,\ + ecs_value_t *result,\ + int32_t elem_count)\ + {\ + (void)ctx; (void)argc;\ + type *a = argv[0].ptr;\ + type *b = argv[1].ptr;\ + double *r = result->ptr;\ + for (int i = 0; i < elem_count; i ++) {\ + double x = (double)a[i], y = (double)b[i];\ + *r += x * y;\ + }\ + } + +FLECS_SCRIPT_DOT(int8_t) +FLECS_SCRIPT_DOT(int16_t) +FLECS_SCRIPT_DOT(int32_t) +FLECS_SCRIPT_DOT(int64_t) +FLECS_SCRIPT_DOT(uint8_t) +FLECS_SCRIPT_DOT(uint16_t) +FLECS_SCRIPT_DOT(uint32_t) +FLECS_SCRIPT_DOT(uint64_t) +FLECS_SCRIPT_DOT(float) +FLECS_SCRIPT_DOT(double) + +#define FLECS_SCRIPT_LENGTH(type)\ + static void flecs_script_length_##type(\ + const ecs_function_ctx_t *ctx,\ + int32_t argc,\ + const ecs_value_t *argv,\ + ecs_value_t *result,\ + int32_t elem_count)\ + {\ + (void)ctx; (void)argc;\ + type *v = argv[0].ptr;\ + double *r = result->ptr;\ + double sum = 0;\ + for (int i = 0; i < elem_count; i ++) {\ + double x = (double)v[i];\ + sum += x * x;\ + }\ + *r = sqrt(sum);\ + } + +FLECS_SCRIPT_LENGTH(int8_t) +FLECS_SCRIPT_LENGTH(int16_t) +FLECS_SCRIPT_LENGTH(int32_t) +FLECS_SCRIPT_LENGTH(int64_t) +FLECS_SCRIPT_LENGTH(uint8_t) +FLECS_SCRIPT_LENGTH(uint16_t) +FLECS_SCRIPT_LENGTH(uint32_t) +FLECS_SCRIPT_LENGTH(uint64_t) +FLECS_SCRIPT_LENGTH(float) +FLECS_SCRIPT_LENGTH(double) + +#define FLECS_SCRIPT_LENGTH_SQ(type)\ + static void flecs_script_length_sq_##type(\ + const ecs_function_ctx_t *ctx,\ + int32_t argc,\ + const ecs_value_t *argv,\ + ecs_value_t *result,\ + int32_t elem_count)\ + {\ + (void)ctx; (void)argc;\ + type *v = argv[0].ptr;\ + double *r = result->ptr;\ + for (int i = 0; i < elem_count; i ++) {\ + double x = (double)v[i];\ + *r += x * x;\ + }\ + } + +FLECS_SCRIPT_LENGTH_SQ(int8_t) +FLECS_SCRIPT_LENGTH_SQ(int16_t) +FLECS_SCRIPT_LENGTH_SQ(int32_t) +FLECS_SCRIPT_LENGTH_SQ(int64_t) +FLECS_SCRIPT_LENGTH_SQ(uint8_t) +FLECS_SCRIPT_LENGTH_SQ(uint16_t) +FLECS_SCRIPT_LENGTH_SQ(uint32_t) +FLECS_SCRIPT_LENGTH_SQ(uint64_t) +FLECS_SCRIPT_LENGTH_SQ(float) +FLECS_SCRIPT_LENGTH_SQ(double) + +#define FLECS_SCRIPT_NORMALIZE(type)\ + static void flecs_script_normalize_##type(\ + const ecs_function_ctx_t *ctx,\ + int32_t argc,\ + const ecs_value_t *argv,\ + ecs_value_t *result,\ + int32_t elem_count)\ + {\ + (void)ctx; (void)argc;\ + const type *v = argv[0].ptr;\ + type *r = result->ptr;\ + double sum_sq = 0.0;\ + for (int i = 0; i < elem_count; i++) {\ + double x = (double)v[i];\ + sum_sq += x * x;\ + }\ + if (ECS_EQZERO(sum_sq)) {\ + for (int i = 0; i < elem_count; i++) r[i] = (type)0;\ + return;\ + }\ + double inv_len = 1.0 / sqrt(sum_sq);\ + for (int i = 0; i < elem_count; i++) {\ + r[i] = (type)((double)v[i] * inv_len);\ + }\ + } + +FLECS_SCRIPT_NORMALIZE(float) +FLECS_SCRIPT_NORMALIZE(double) + #define FLECS_MATH_FUNC_F64(name, ...)\ static\ void flecs_math_##name(\ @@ -62258,8 +66030,7 @@ void flecs_script_rng_get_uint( const ecs_value_t *argv,\ ecs_value_t *result)\ {\ - (void)ctx;\ - (void)argc;\ + (void)ctx; (void)argc;\ ecs_assert(argc == 1, ECS_INTERNAL_ERROR, NULL);\ double x = *(double*)argv[0].ptr;\ *(double*)result->ptr = __VA_ARGS__;\ @@ -62273,8 +66044,7 @@ void flecs_script_rng_get_uint( const ecs_value_t *argv,\ ecs_value_t *result)\ {\ - (void)ctx;\ - (void)argc;\ + (void)ctx; (void)argc;\ ecs_assert(argc == 2, ECS_INTERNAL_ERROR, NULL);\ double x = *(double*)argv[0].ptr;\ double y = *(double*)argv[1].ptr;\ @@ -62289,8 +66059,7 @@ void flecs_script_rng_get_uint( const ecs_value_t *argv,\ ecs_value_t *result)\ {\ - (void)ctx;\ - (void)argc;\ + (void)ctx; (void)argc;\ ecs_assert(argc == 2, ECS_INTERNAL_ERROR, NULL);\ double x = *(double*)argv[0].ptr;\ ecs_i32_t y = *(ecs_i32_t*)argv[1].ptr;\ @@ -62474,6 +66243,301 @@ void FlecsScriptMathImport( }, .callback = flecs_script_rng_get_uint }); + + ecs_function(world, { + .name = "min", + .parent = ecs_id(FlecsScriptMath), + .return_type = ecs_id(ecs_f64_t), + .params = { + { .name = "a", .type = ecs_id(ecs_f64_t) }, + { .name = "b", .type = ecs_id(ecs_f64_t) }, + }, + .callback = flecs_script_min + }); + + ecs_function(world, { + .name = "max", + .parent = ecs_id(FlecsScriptMath), + .return_type = ecs_id(ecs_f64_t), + .params = { + { .name = "a", .type = ecs_id(ecs_f64_t) }, + { .name = "b", .type = ecs_id(ecs_f64_t) }, + }, + .callback = flecs_script_max + }); + + ecs_function(world, { + .name = "dot", + .parent = ecs_id(FlecsScriptMath), + .return_type = ecs_id(ecs_f64_t), + .params = { + { .name = "a", .type = EcsScriptVectorType }, + { .name = "b", .type = EcsScriptVectorType }, + }, + .vector_callbacks = { + [EcsI8] = flecs_script_dot_int8_t, + [EcsI16] = flecs_script_dot_int16_t, + [EcsI32] = flecs_script_dot_int32_t, + [EcsI64] = flecs_script_dot_int64_t, + [EcsU8] = flecs_script_dot_uint8_t, + [EcsU16] = flecs_script_dot_uint16_t, + [EcsU32] = flecs_script_dot_uint32_t, + [EcsU64] = flecs_script_dot_uint64_t, + [EcsF32] = flecs_script_dot_float, + [EcsF64] = flecs_script_dot_double + } + }); + + ecs_function(world, { + .name = "length", + .parent = ecs_id(FlecsScriptMath), + .return_type = ecs_id(ecs_f64_t), + .params = { + { .name = "v", .type = EcsScriptVectorType } + }, + .vector_callbacks = { + [EcsI8] = flecs_script_length_int8_t, + [EcsI16] = flecs_script_length_int16_t, + [EcsI32] = flecs_script_length_int32_t, + [EcsI64] = flecs_script_length_int64_t, + [EcsU8] = flecs_script_length_uint8_t, + [EcsU16] = flecs_script_length_uint16_t, + [EcsU32] = flecs_script_length_uint32_t, + [EcsU64] = flecs_script_length_uint64_t, + [EcsF32] = flecs_script_length_float, + [EcsF64] = flecs_script_length_double + } + }); + + ecs_function(world, { + .name = "length_sq", + .parent = ecs_id(FlecsScriptMath), + .return_type = ecs_id(ecs_f64_t), + .params = { + { .name = "v", .type = EcsScriptVectorType } + }, + .vector_callbacks = { + [EcsI8] = flecs_script_length_sq_int8_t, + [EcsI16] = flecs_script_length_sq_int16_t, + [EcsI32] = flecs_script_length_sq_int32_t, + [EcsI64] = flecs_script_length_sq_int64_t, + [EcsU8] = flecs_script_length_sq_uint8_t, + [EcsU16] = flecs_script_length_sq_uint16_t, + [EcsU32] = flecs_script_length_sq_uint32_t, + [EcsU64] = flecs_script_length_sq_uint64_t, + [EcsF32] = flecs_script_length_sq_float, + [EcsF64] = flecs_script_length_sq_double + } + }); + + ecs_function(world, { + .name = "normalize", + .parent = ecs_id(FlecsScriptMath), + .return_type = EcsScriptVectorType, + .params = { + { .name = "v", .type = EcsScriptVectorType } + }, + .vector_callbacks = { + [EcsF32] = flecs_script_normalize_float, + [EcsF64] = flecs_script_normalize_double + } + }); + + ecs_function(world, { + .name = "lerp", + .parent = ecs_id(FlecsScriptMath), + .return_type = EcsScriptVectorType, + .params = { + { .name = "a", .type = EcsScriptVectorType }, + { .name = "b", .type = EcsScriptVectorType }, + { .name = "t", .type = ecs_id(ecs_f64_t) } + }, + .vector_callbacks = { + [EcsF32] = flecs_script_lerp_float, + [EcsF64] = flecs_script_lerp_double + } + }); + + ecs_function(world, { + .name = "smoothstep", + .parent = ecs_id(FlecsScriptMath), + .return_type = EcsScriptVectorType, + .params = { + { .name = "a", .type = EcsScriptVectorType }, + { .name = "b", .type = EcsScriptVectorType }, + { .name = "t", .type = ecs_id(ecs_f64_t) } + }, + .vector_callbacks = { + [EcsF32] = flecs_script_smoothstep_float, + [EcsF64] = flecs_script_smoothstep_double + } + }); + + ecs_function(world, { + .name = "clamp", + .parent = ecs_id(FlecsScriptMath), + .return_type = EcsScriptVectorType, + .params = { + { .name = "v", .type = EcsScriptVectorType }, + { .name = "min", .type = ecs_id(ecs_f64_t) }, + { .name = "max", .type = ecs_id(ecs_f64_t) } + }, + .vector_callbacks = { + [EcsI8] = flecs_script_clamp_int8_t, + [EcsI16] = flecs_script_clamp_int16_t, + [EcsI32] = flecs_script_clamp_int32_t, + [EcsI64] = flecs_script_clamp_int64_t, + [EcsU8] = flecs_script_clamp_uint8_t, + [EcsU16] = flecs_script_clamp_uint16_t, + [EcsU32] = flecs_script_clamp_uint32_t, + [EcsU64] = flecs_script_clamp_uint64_t, + [EcsF32] = flecs_script_clamp_float, + [EcsF64] = flecs_script_clamp_double + } + }); + + FlecsScriptMathPerlinImport(world); +} + +#endif + +/** + * @file addons/script/functions_math_perlin.c + * @brief Perlin noise functions for flecs script. + * + * - flecs_perlin2(x, y): returns noise in ~[-1, 1] + * - flecs_perlin_seed(seed): initializes permutation table for repeatable noise + */ + + +#ifdef FLECS_SCRIPT_MATH +#include + +static uint8_t flecs_perlin_perm[512]; + +static +uint32_t flecs_perlin_xs32( + uint32_t *state) +{ + uint32_t x = *state; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + *state = x; + return x; +} + +void flecs_perlin_seed( + uint32_t seed) +{ + uint8_t p[256]; + for (int i = 0; i < 256; i++) p[i] = (uint8_t)i; + + uint32_t st = (seed ? seed : 0xA341316Cu); + + for (int i = 255; i > 0; i--) { + uint32_t r = flecs_perlin_xs32(&st); + int j = (int)(r % (uint32_t)(i + 1)); + uint8_t tmp = p[i]; + p[i] = p[j]; + p[j] = tmp; + } + + for (int i = 0; i < 256; i++) { + flecs_perlin_perm[i] = p[i]; + flecs_perlin_perm[i + 256] = p[i]; + } +} + +static +double flecs_perlin_fade( + double t) +{ + return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); +} + +static +double flecs_perlin_grad2( + int hash, + double x, + double y) +{ + switch (hash & 7) { + case 0: return x + y; + case 1: return -x + y; + case 2: return x - y; + case 3: return -x - y; + case 4: return x; + case 5: return -x; + case 6: return y; + default: return -y; + } +} + +static +double flecs_perlin2( + double x, + double y) +{ + int X = (int)floor(x) & 255; + int Y = (int)floor(y) & 255; + + double xf = x - floor(x); + double yf = y - floor(y); + + double u = flecs_perlin_fade(xf); + double v = flecs_perlin_fade(yf); + + int aa = flecs_perlin_perm[flecs_perlin_perm[X] + Y]; + int ab = flecs_perlin_perm[flecs_perlin_perm[X] + Y + 1]; + int ba = flecs_perlin_perm[flecs_perlin_perm[X + 1] + Y]; + int bb = flecs_perlin_perm[flecs_perlin_perm[X + 1] + Y + 1]; + + double x1 = flecs_lerp( + flecs_perlin_grad2(aa, xf, yf), + flecs_perlin_grad2(ba, xf - 1, yf), + u); + + double x2 = flecs_lerp( + flecs_perlin_grad2(ab, xf, yf - 1), + flecs_perlin_grad2(bb, xf - 1, yf - 1), + u); + + return flecs_lerp(x1, x2, v); +} + +static +void flecs_script_perlin2( + const ecs_function_ctx_t *ctx, + int32_t argc, + const ecs_value_t *argv, + ecs_value_t *result) +{ + (void)argc; + (void)ctx; + double x = *(double*)argv[0].ptr; + double y = *(double*)argv[1].ptr; + *(double*)result->ptr = flecs_perlin2(x, y); +} + +void FlecsScriptMathPerlinImport( + ecs_world_t *world) +{ + ecs_entity_t FlecsScriptMath = ecs_lookup(world, "flecs.script.math"); + ecs_assert(FlecsScriptMath != 0, ECS_INTERNAL_ERROR, NULL); + + flecs_perlin_seed(1234); + + ecs_function(world, { + .name = "perlin2", + .parent = FlecsScriptMath, + .return_type = ecs_id(ecs_f64_t), + .params = { + { .name = "x", .type = ecs_id(ecs_f64_t) }, + { .name = "y", .type = ecs_id(ecs_f64_t) }, + }, + .callback = flecs_script_perlin2 + }); } #endif @@ -62504,6 +66568,14 @@ const char* flecs_script_scope( ecs_assert(scope != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(pos[-1] == '{', ECS_INTERNAL_ERROR, NULL); + if (parser->scope_depth >= ECS_PARSER_MAX_RECURSION_DEPTH) { + ecs_parser_error(parser->name, parser->code, pos - parser->code, + "maximum scope nesting depth exceeded"); + return NULL; + } + + parser->scope_depth ++; + ecs_script_scope_t *prev = parser->scope; parser->scope = scope; @@ -62525,11 +66597,16 @@ const char* flecs_script_scope( scope_close: parser->scope = prev; + parser->scope_depth --; ecs_assert(pos[-1] == '}', ECS_INTERNAL_ERROR, NULL); return pos; - ParserEnd; + Error("unexpected end of rule (parser error)"); +error: + parser->scope = prev; + parser->scope_depth --; + return NULL; } /* Parse comma expression (expressions separated by ',') */ @@ -62743,10 +66820,18 @@ const char* flecs_script_if_stmt( // if expr { } else\n if case EcsTokNewline: { - Parse_1(EcsTokKeywordIf, - Scope(stmt->if_false, - return flecs_script_if_stmt(parser, pos); - ) + Parse( + case EcsTokKeywordIf: { + Scope(stmt->if_false, + return flecs_script_if_stmt(parser, pos); + ) + } + + // if expr { } else\n { + case '{': { + return flecs_script_scope( + parser, stmt->if_false, pos); + } ) } @@ -63122,10 +67207,6 @@ paren: { ) ) ) - // // (Likes, Apples) - // Parse_4(EcsTokIdentifier, ',', EcsTokIdentifier, ')', - // goto pair; - // ) } // (Likes, Apples) @@ -63515,6 +67596,7 @@ ecs_script_t* ecs_script_parse( impl->token_buffer = flecs_alloc_w_dbg_info( &impl->allocator, impl->token_buffer_size, "token buffer"); parser.token_cur = impl->token_buffer; + parser.token_end = &impl->token_buffer[impl->token_buffer_size]; /* Start parsing code */ const char *pos = script->code; @@ -63562,6 +67644,7 @@ ECS_COMPONENT_DECLARE(EcsScript); ECS_COMPONENT_DECLARE(EcsScriptConstVar); ECS_COMPONENT_DECLARE(EcsScriptFunction); ECS_COMPONENT_DECLARE(EcsScriptMethod); +ECS_DECLARE(EcsScriptVectorType); static ECS_MOVE(EcsScript, dst, src, { @@ -63634,17 +67717,29 @@ void ecs_script_clear( if (!instance) { ecs_delete_with(world, ecs_pair_t(EcsScript, script)); } else { + ecs_assert(ecs_is_alive(world, instance), ECS_INTERNAL_ERROR, NULL); ecs_vec_t to_delete = {0}; ecs_vec_init_t(&world->allocator, &to_delete, ecs_entity_t, 0); ecs_iter_t it = ecs_children(world, instance); while (ecs_children_next(&it)) { - if (ecs_table_has_id(world, it.table, ecs_pair(EcsScriptTemplate, script))) { + if (it.table) { + if (ecs_table_has_id(world, it.table, ecs_pair(EcsScriptTemplate, script))) { + int32_t i, count = it.count; + for (i = 0; i < count; i ++) { + ecs_vec_append_t( + &world->allocator, &to_delete, ecs_entity_t)[0] = + it.entities[i]; + } + } + } else { int32_t i, count = it.count; for (i = 0; i < count; i ++) { - ecs_vec_append_t( - &world->allocator, &to_delete, ecs_entity_t)[0] = - it.entities[i]; + ecs_entity_t e = it.entities[i]; + if (ecs_has_pair(world, e, EcsScriptTemplate, script)) { + ecs_vec_append_t( + &world->allocator, &to_delete, ecs_entity_t)[0] = e; + } } } } @@ -63759,6 +67854,7 @@ int ecs_script_update( s->script = ecs_script_parse(world, name, code, NULL, &eval_result); if (s->script == NULL) { s->error = eval_result.error; + ecs_log_(-3, NULL, 0, "%s: %s", name ? name : "script", s->error); return -1; } @@ -63774,6 +67870,13 @@ int ecs_script_update( ecs_script_clear(world, e, instance); +#ifdef FLECS_DEBUG + { + ecs_iter_t it = ecs_each_pair_t(world, EcsScript, e); + ecs_assert(!ecs_iter_is_true(&it), ECS_INTERNAL_ERROR, NULL); + } +#endif + ecs_entity_t prev = ecs_set_with(world, flecs_script_tag(e, instance)); if (ecs_script_eval(s->script, NULL, &eval_result)) { @@ -63927,16 +68030,15 @@ int EcsScript_serialize( void FlecsScriptImport( ecs_world_t *world) { + ecs_assert(FLECS_SCRIPT_VECTOR_FUNCTION_COUNT == EcsPrimitiveKindLast, + ECS_INTERNAL_ERROR, NULL); + ECS_MODULE(world, FlecsScript); ECS_IMPORT(world, FlecsMeta); -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); - ecs_doc_set_brief(world, ecs_id(FlecsScript), - "Module with components for managing Flecs scripts"); -#endif ecs_set_name_prefix(world, "Ecs"); ECS_COMPONENT_DEFINE(world, EcsScript); + ECS_TAG_DEFINE(world, EcsScriptVectorType); ecs_set_hooks(world, EcsScript, { .ctor = flecs_default_ctor, @@ -63948,7 +68050,7 @@ void FlecsScriptImport( ECS_COMPONENT(world, ecs_script_t); ecs_entity_t opaque_view = ecs_struct(world, { - .entity = ecs_entity(world, { .name = "ecs_script_view_t"}), + .entity = ecs_entity(world, { .name = "ecs_script_view_t" }), .members = { { .name = "filename", .type = ecs_id(ecs_string_t) }, { .name = "code", .type = ecs_id(ecs_string_t) }, @@ -63964,7 +68066,6 @@ void FlecsScriptImport( }); ecs_add_id(world, ecs_id(EcsScript), EcsPairIsTag); - ecs_add_id(world, ecs_id(EcsScript), EcsPrivate); ecs_add_pair(world, ecs_id(EcsScript), EcsOnInstantiate, EcsDontInherit); flecs_script_template_import(world); @@ -64504,10 +68605,12 @@ void flecs_script_template_ctor( { ecs_world_t *world = ti->hooks.ctx; ecs_entity_t template_entity = ti->component; + + /* Initialize object so copy hooks can safely overwrite members with dtors. */ + flecs_default_ctor(ptr, count, ti); const EcsStruct *st = ecs_get(world, template_entity, EcsStruct); if (!st) { - ecs_os_memset(ptr, 0, count * ti->size); return; } @@ -64611,6 +68714,7 @@ void flecs_script_template_instantiate( ecs_vec_t prev_using = v.r->using; ecs_vec_t prev_with = desc.runtime->with; ecs_vec_t prev_with_type_info = desc.runtime->with_type_info; + v.r->using = template->using_; v.template_entity = template_entity; ecs_vec_init_t(NULL, &desc.runtime->with, ecs_value_t, 0); @@ -64629,13 +68733,20 @@ void flecs_script_template_instantiate( v.entity = &instance_node; - int32_t i, m; + int32_t i, m, a; for (i = 0; i < count; i ++) { v.parent = entities[i]; ecs_assert(ecs_is_alive(world, v.parent), ECS_INTERNAL_ERROR, NULL); instance_node.eval = entities[i]; + /* Apply annotations, if any */ + for (a = 0; a < ecs_vec_count(&template->annot); a ++) { + ecs_script_annot_t *annot = ecs_vec_get_t( + &template->annot, ecs_script_annot_t*, a)[0]; + flecs_script_apply_annot(&v, &instance_node, annot); + } + /* Create variables to hold template properties */ ecs_script_vars_t *vars = flecs_script_vars_push( NULL, &v.r->stack, &v.r->allocator); @@ -64818,9 +68929,7 @@ int flecs_script_template_eval_prop( type = var->value.type = value.type; var->type_info = ti; - if (ti->hooks.ctor) { - ti->hooks.ctor(var->value.ptr, 1, ti); - } + flecs_type_info_ctor(var->value.ptr, 1, ti); ecs_value_copy_w_type_info(v->world, ti, var->value.ptr, value.ptr); ecs_value_fini_w_type_info(v->world, ti, value.ptr); @@ -64948,6 +69057,8 @@ ecs_script_template_t* flecs_script_template_init( ecs_script_template_t *result = flecs_alloc_t(a, ecs_script_template_t); ecs_vec_init_t(NULL, &result->prop_defaults, ecs_script_var_t, 0); ecs_vec_init_t(NULL, &result->using_, ecs_entity_t, 0); + ecs_vec_init_t(NULL, &result->annot, ecs_script_annot_t*, 0); + result->vars = ecs_script_vars_init(script->pub.world); return result; } @@ -64965,7 +69076,7 @@ void flecs_script_template_fini( ecs_script_var_t *value = &values[i]; const ecs_type_info_t *ti = value->type_info; if (ti->hooks.dtor) { - ti->hooks.dtor(value->value.ptr, 1, ti); + flecs_type_info_dtor(value->value.ptr, 1, ti); } flecs_free(a, ti->size, value->value.ptr); } @@ -64973,6 +69084,7 @@ void flecs_script_template_fini( ecs_vec_fini_t(a, &template->prop_defaults, ecs_script_var_t); ecs_vec_fini_t(a, &template->using_, ecs_entity_t); + ecs_vec_fini_t(a, &template->annot, ecs_script_annot_t*); ecs_script_vars_fini(template->vars); flecs_free_t(a, ecs_script_template_t, template); } @@ -65016,6 +69128,17 @@ int flecs_script_eval_template( ecs_set(v->world, template_entity, EcsComponent, {1, 1}); } + /* Consume annotations, if any */ + int32_t i, count = ecs_vec_count(&v->r->annot); + if (count) { + ecs_script_annot_t **annots = ecs_vec_first(&v->r->annot); + for (i = 0; i < count ; i ++) { + ecs_vec_append_t(&v->base.script->allocator, + &template->annot, ecs_script_annot_t*)[0] = annots[i]; + } + ecs_vec_clear(&v->r->annot); + } + template->type_info = ecs_get_type_info(v->world, template_entity); ecs_add_pair(v->world, template_entity, EcsOnInstantiate, EcsOverride); @@ -65174,7 +69297,7 @@ ecs_script_vars_t* ecs_script_vars_pop( continue; } - var->type_info->hooks.dtor(var->value.ptr, 1, var->type_info); + flecs_type_info_dtor(var->value.ptr, 1, var->type_info); } flecs_name_index_fini(&vars->var_index); @@ -65248,9 +69371,7 @@ ecs_script_var_t* ecs_script_vars_define_id( result->value.ptr = flecs_stack_alloc(vars->stack, ti->size, ti->alignment); result->type_info = ti; - if (ti->hooks.ctor) { - ti->hooks.ctor(result->value.ptr, 1, ti); - } + flecs_type_info_ctor(result->value.ptr, 1, ti); return result; error: @@ -65434,6 +69555,20 @@ void ecs_script_vars_from_iter( #ifdef FLECS_SCRIPT +static +int flecs_script_visit_push_checked( + ecs_script_visit_t *v, + ecs_script_node_t *node) +{ + if (v->depth >= ECS_SCRIPT_VISIT_MAX_DEPTH) { + ecs_err("maximum script nesting depth exceeded"); + return -1; + } + + v->nodes[v->depth ++] = node; + return 0; +} + ecs_script_node_t* ecs_script_parent_node_( ecs_script_visit_t *v) { @@ -65509,10 +69644,13 @@ int ecs_script_visit_scope_( ecs_script_visit_t *v, ecs_script_scope_t *scope) { + int32_t depth = v->depth; ecs_script_node_t **nodes = ecs_vec_first_t( &scope->stmts, ecs_script_node_t*); - v->nodes[v->depth ++] = (ecs_script_node_t*)scope; + if (flecs_script_visit_push_checked(v, (ecs_script_node_t*)scope)) { + return -1; + } int32_t i, count = ecs_vec_count(&scope->stmts); for (i = 0; i < count; i ++) { @@ -65528,18 +69666,22 @@ int ecs_script_visit_scope_( v->next = NULL; } - ecs_script_visit_push(v, nodes[i]); + if (flecs_script_visit_push_checked(v, nodes[i])) { + v->depth = depth; + return -1; + } ecs_assert(v->visit != NULL, ECS_INTERNAL_ERROR, NULL); if (v->visit(v, nodes[i])) { + v->depth = depth; return -1; } ecs_script_visit_pop(v, nodes[i]); } - v->depth --; + v->depth = depth; return 0; } @@ -65548,13 +69690,17 @@ int ecs_script_visit_node_( ecs_script_visit_t *v, ecs_script_node_t *node) { - v->nodes[v->depth ++] = node; + int32_t depth = v->depth; + if (flecs_script_visit_push_checked(v, node)) { + return -1; + } if (v->visit(v, node)) { + v->depth = depth; return -1; } - v->depth --; + v->depth = depth; return 0; } @@ -65931,7 +70077,8 @@ int flecs_script_check_using( ecs_script_eval_visitor_t *v, ecs_script_using_t *node) { - return flecs_script_eval_using(v, node); + flecs_script_eval_error(v, node, "using in template is not allowed"); + return -1; } static @@ -66146,6 +70293,26 @@ int flecs_script_check( #ifdef FLECS_SCRIPT +static +bool flecs_script_valid_lookup_path( + const char *path) +{ + int32_t template_nesting = 0; + char ch; + for (; (ch = path[0]); path ++) { + if (ch == '<') { + template_nesting ++; + } else if (ch == '>') { + template_nesting --; + if (template_nesting < 0) { + return false; + } + } + } + + return template_nesting == 0; +} + void flecs_script_eval_error_( ecs_script_eval_visitor_t *v, ecs_script_node_t *node, @@ -66202,7 +70369,7 @@ void flecs_script_with_set_count( &v->r->with_type_info, ecs_type_info_t*, i)[0]; if (ti) { if (ti->hooks.dtor) { - ti->hooks.dtor(val->ptr, 1, ti); + flecs_type_info_dtor(val->ptr, 1, ti); } flecs_stack_free(val->ptr, ti->size); } @@ -66357,17 +70524,19 @@ int flecs_script_find_entity( ecs_entity_t result = 0; if (path[0] != '$') { + bool valid_path = flecs_script_valid_lookup_path(path); + if (name_expr && *name_expr) { result = flecs_script_eval_name_expr(v, NULL, name_expr, true); if (!result) { return -1; } - } else if (from) { + } else if (from && valid_path) { result = ecs_lookup_path_w_sep( v->world, from, path, NULL, NULL, false); } else { int32_t i, using_count = ecs_vec_count(&v->r->using); - if (using_count) { + if (using_count && valid_path) { ecs_entity_t *using = ecs_vec_first(&v->r->using); for (i = using_count - 1; i >= 0; i --) { ecs_entity_t e = ecs_lookup_path_w_sep( @@ -66378,7 +70547,7 @@ int flecs_script_find_entity( } } - if (!result) { + if (!result && valid_path) { result = ecs_lookup_path_w_sep( v->world, v->parent, path, NULL, NULL, true); } @@ -66452,8 +70621,18 @@ ecs_entity_t flecs_script_create_entity( } ecs_entity_desc_t desc = {0}; - desc.name = name; - desc.parent = v->parent; + + if (v->entity && v->entity->non_fragmenting_parent) { + desc.id = ecs_new_w_parent(v->world, v->parent, name); + ecs_id_t world_with = ecs_get_with(v->world); + if (world_with) { + ecs_add_id(v->world, desc.id, world_with); + } + } else { + desc.parent = v->parent; + desc.name = name; + } + desc.set = with; return ecs_entity_init(v->world, &desc); } @@ -66521,9 +70700,13 @@ int flecs_script_eval_id( return 0; } - if (!id->first) { - flecs_script_eval_error(v, node, - "invalid component/tag identifier"); + if (!id->first || !id->first[0]) { + flecs_script_eval_error(v, node, "invalid component identifier"); + return -1; + } + + if (id->second && !id->second[0]) { + flecs_script_eval_error(v, node, "invalid pair identifier"); return -1; } @@ -66709,28 +70892,119 @@ int flecs_script_eval_scope( } static +void flecs_script_apply_non_fragmenting_childof( + ecs_world_t *world, + ecs_script_entity_t *node, + bool enabled); + +static +void flecs_script_apply_non_fragmenting_childof_to_scope( + ecs_world_t *world, + ecs_script_scope_t *scope, + bool enabled) +{ + if (!scope) { + return; + } + + int32_t i, count = ecs_vec_count(&scope->stmts); + ecs_script_node_t **stmts = ecs_vec_first(&scope->stmts); + for (i = 0; i < count; i ++) { + ecs_script_node_t *stmt = stmts[i]; + switch(stmt->kind) { + case EcsAstScope: + flecs_script_apply_non_fragmenting_childof_to_scope( + world, (ecs_script_scope_t*)stmt, enabled); + break; + case EcsAstEntity: + flecs_script_apply_non_fragmenting_childof( + world, (ecs_script_entity_t*)stmt, enabled); + break; + case EcsAstIf: + flecs_script_apply_non_fragmenting_childof_to_scope( + world, ((ecs_script_if_t*)stmt)->if_false, enabled); + flecs_script_apply_non_fragmenting_childof_to_scope( + world, ((ecs_script_if_t*)stmt)->if_true, enabled); + break; + case EcsAstFor: + flecs_script_apply_non_fragmenting_childof_to_scope( + world, ((ecs_script_for_range_t*)stmt)->scope, enabled); + break; + case EcsAstWith: + case EcsAstWithVar: + case EcsAstWithTag: + case EcsAstWithComponent: + flecs_script_apply_non_fragmenting_childof_to_scope( + world, ((ecs_script_with_t*)stmt)->scope, enabled); + break; + case EcsAstPairScope: + flecs_script_apply_non_fragmenting_childof_to_scope( + world, ((ecs_script_pair_scope_t*)stmt)->scope, enabled); + break; + case EcsAstTag: + case EcsAstComponent: + case EcsAstDefaultComponent: + case EcsAstVarComponent: + case EcsAstUsing: + case EcsAstModule: + case EcsAstAnnotation: + case EcsAstTemplate: + case EcsAstProp: + case EcsAstConst: + case EcsAstExportConst: + break; + } + } +} + +static +void flecs_script_apply_non_fragmenting_childof( + ecs_world_t *world, + ecs_script_entity_t *node, + bool enabled) +{ + node->non_fragmenting_parent = enabled; + + flecs_script_apply_non_fragmenting_childof_to_scope( + world, node->scope, enabled); +} + int flecs_script_apply_annot( ecs_script_eval_visitor_t *v, - ecs_entity_t entity, - ecs_script_annot_t *node) + ecs_script_entity_t *node, + ecs_script_annot_t *annot) { - if (!ecs_os_strcmp(node->name, "name")) { - ecs_doc_set_name(v->world, entity, node->expr); + ecs_entity_t e = node->eval; + + if (!ecs_os_strcmp(annot->name, "name")) { + ecs_doc_set_name(v->world, e, annot->expr); } else - if (!ecs_os_strcmp(node->name, "brief")) { - ecs_doc_set_brief(v->world, entity, node->expr); + if (!ecs_os_strcmp(annot->name, "brief")) { + ecs_doc_set_brief(v->world, e, annot->expr); } else - if (!ecs_os_strcmp(node->name, "detail")) { - ecs_doc_set_detail(v->world, entity, node->expr); + if (!ecs_os_strcmp(annot->name, "detail")) { + ecs_doc_set_detail(v->world, e, annot->expr); } else - if (!ecs_os_strcmp(node->name, "link")) { - ecs_doc_set_link(v->world, entity, node->expr); + if (!ecs_os_strcmp(annot->name, "link")) { + ecs_doc_set_link(v->world, e, annot->expr); } else - if (!ecs_os_strcmp(node->name, "color")) { - ecs_doc_set_color(v->world, entity, node->expr); + if (!ecs_os_strcmp(annot->name, "color")) { + ecs_doc_set_color(v->world, e, annot->expr); + } else + if (!ecs_os_strcmp(annot->name, "tree")) { + if (!ecs_os_strcmp(annot->expr, "Parent")) { + flecs_script_apply_non_fragmenting_childof(v->world, node, true); + } else if (!ecs_os_strcmp(annot->expr, "ChildOf")) { + flecs_script_apply_non_fragmenting_childof(v->world, node, false); + } else { + flecs_script_eval_error(v, annot, + "invalid value for tree annotation: '%s' (expected 'Parent' or 'ChildOf')", + annot->expr); + return -1; + } } else { - flecs_script_eval_error(v, node, "unknown annotation '%s'", - node->name); + flecs_script_eval_error(v, annot, "unknown annotation '%s'", + annot->name); return -1; } @@ -66821,12 +71095,11 @@ int flecs_script_eval_entity( if (count) { ecs_script_annot_t **annots = ecs_vec_first(&v->r->annot); for (i = 0; i < count ; i ++) { - flecs_script_apply_annot(v, node->eval, annots[i]); + flecs_script_apply_annot(v, node, annots[i]); } ecs_vec_clear(&v->r->annot); } - bool old_is_with_scope = v->is_with_scope; ecs_entity_t old_template_entity = v->template_entity; v->is_with_scope = false; @@ -66895,6 +71168,13 @@ int flecs_script_eval_tag( return -1; } + if (node->id.eval == ecs_id(EcsParent)) { + flecs_script_eval_error(v, node, + "Parent component cannot be added as tag (set to valid parent)", + node->id.first, node->id.second); + return -1; + } + if (!resolved) { if (!flecs_script_can_default_ctor(v->world, node->id.eval)) { if (node->id.second) { @@ -66989,26 +71269,29 @@ int flecs_script_eval_component( return -1; } + bool needs_set = ti->hooks.on_replace != NULL; ecs_record_t *r = flecs_entities_get(v->world, src); ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); ecs_table_t *table = r->table; ecs_value_t value = { - .ptr = ecs_ensure_id(v->world, src, node->id.eval, - flecs_ito(size_t, ti->size)), + .ptr = needs_set + ? ecs_os_alloca(ti->size) + : ecs_ensure_id(v->world, src, node->id.eval, + flecs_ito(size_t, ti->size)), .type = ti->component }; /* Assign entire value, including members not set by expression. This * prevents uninitialized or unexpected values. */ - if (r->table != table) { + if (needs_set || (r->table != table)) { if (!ti->hooks.ctor) { ecs_os_memset(value.ptr, 0, ti->size); - } else if (ti->hooks.ctor) { - if (ti->hooks.dtor) { - ti->hooks.dtor(value.ptr, 1, ti); + } else { + if (!needs_set && ti->hooks.dtor) { + flecs_type_info_dtor(value.ptr, 1, ti); } - ti->hooks.ctor(value.ptr, 1, ti); + flecs_type_info_ctor(value.ptr, 1, ti); } } @@ -67016,7 +71299,12 @@ int flecs_script_eval_component( return -1; } - ecs_modified_id(v->world, src, node->id.eval); + if (needs_set) { + ecs_set_id(v->world, src, node->id.eval, + flecs_itosize(ti->size), value.ptr); + } else { + ecs_modified_id(v->world, src, node->id.eval); + } } else { ecs_add_id(v->world, src, node->id.eval); } @@ -67038,6 +71326,8 @@ int flecs_script_eval_var_component( if (flecs_script_find_entity( v, 0, node->name, NULL, NULL, &var_entity, NULL)) { + flecs_script_eval_error(v, node, + "unresolved variable '%s'", node->name); return -1; } @@ -67059,6 +71349,11 @@ int flecs_script_eval_var_component( return -1; } + if (!v->entity) { + flecs_script_eval_error(v, node, "missing entity for variable component"); + return -1; + } + ecs_id_t var_id = var_value.type; if (var_value.ptr) { @@ -67202,9 +71497,7 @@ int flecs_script_eval_with_component( value->ptr = flecs_stack_alloc(&v->r->stack, ti->size, ti->alignment); value->type = ti->component; // Expression parser needs actual type - if (ti->hooks.ctor) { - ti->hooks.ctor(value->ptr, 1, ti); - } + flecs_type_info_ctor(value->ptr, 1, ti); if (flecs_script_eval_expr(v, &node->expr, value)) { return -1; @@ -67401,9 +71694,7 @@ int flecs_script_eval_const( result.ptr = flecs_stack_calloc(&v->r->stack, ti->size, ti->alignment); - if (ti->hooks.ctor) { - ti->hooks.ctor(result.ptr, 1, ti); - } + flecs_type_info_ctor(result.ptr, 1, ti); if (flecs_script_eval_expr(v, &node->expr, &result)) { flecs_script_eval_error(v, node, @@ -67430,9 +71721,7 @@ int flecs_script_eval_const( &v->r->stack, ti->size, ti->alignment); result.type = value.type; - if (ti->hooks.ctor) { - ti->hooks.ctor(result.ptr, 1, ti); - } + flecs_type_info_ctor(result.ptr, 1, ti); ecs_value_copy_w_type_info(v->world, ti, result.ptr, value.ptr); ecs_value_fini_w_type_info(v->world, ti, value.ptr); @@ -67457,7 +71746,7 @@ int flecs_script_eval_const( /* Clean up value since it'll have been copied into the const var. */ if (ti->hooks.dtor) { - ti->hooks.dtor(result.ptr, 1, ti); + flecs_type_info_dtor(result.ptr, 1, ti); } flecs_stack_free(result.ptr, ti->size); @@ -67627,10 +71916,12 @@ int flecs_script_eval_annot( return -1; } - if (v->base.next->kind != EcsAstEntity) { - if (v->base.next->kind != EcsAstAnnotation) { + ecs_script_node_kind_t next_kind = v->base.next->kind; + if (next_kind != EcsAstEntity && next_kind != EcsAstTemplate) { + if (next_kind != EcsAstAnnotation) { flecs_script_eval_error(v, node, - "target of @%s annotation must be an entity", node->name); + "target of @%s annotation must be an entity or template", + node->name); return -1; } } @@ -67789,8 +72080,6 @@ int ecs_script_eval( int r = ecs_script_visit(impl, &v, flecs_script_eval_node); flecs_script_eval_visit_fini(&v, &priv_desc); - // printf("%s\n", ecs_script_ast_to_str(script, true)); - if (result) { result->error = ecs_log_stop_capture(); } @@ -68865,11 +73154,13 @@ void ecs_component_record_memory_get( result->bytes_name_index += ECS_SIZEOF(ecs_hashmap_t); result->bytes_name_index += flecs_hashmap_memory_get( pair->name_index); - } result->bytes_ordered_children += ecs_vec_size(&pair->ordered_children) * ECS_SIZEOF(ecs_entity_t); + + result->bytes_children_table_map += flecs_map_memory_get( + &pair->children_tables, 0); const ecs_reachable_cache_t *reachable = &pair->reachable; result->bytes_reachable_cache += @@ -69165,11 +73456,11 @@ void ecs_table_memory_get( result->bytes_overrides += column_count * ECS_SIZEOF(ecs_ref_t); } - result->bytes_columns += column_count * ECS_SIZEOF(ecs_column_t); + result->bytes_type += column_count * ECS_SIZEOF(ecs_column_t); if (table->_) { result->bytes_table += ECS_SIZEOF(ecs_table__t); - result->bytes_table_records += + result->bytes_type += table->_->record_count * ECS_SIZEOF(ecs_table_record_t); } @@ -69303,10 +73594,17 @@ ecs_size_t flecs_observers_memory_get( { ecs_size_t result = 0; + int32_t i, count = ecs_vec_count(&world->observable.global_observers); + for (i = 0; i < count; i ++) { + ecs_observer_t *o = ecs_vec_get_t( + &world->observable.global_observers, ecs_observer_t*, i)[0]; + result += flecs_observer_memory_get(flecs_observer_impl(o)); + } + ecs_iter_t it = ecs_each_pair_t(world, EcsPoly, EcsObserver); while (ecs_each_next(&it)) { EcsPoly *p = ecs_field(&it, EcsPoly, 0); - int32_t i, count = it.count; + count = it.count; for (i = 0; i < count; i ++) { ecs_observer_impl_t *o = p[i].poly; if (!o) { @@ -69588,6 +73886,31 @@ void flecs_rest_memory_get( } #endif +static +void flecs_tree_spawner_memory_get( + const ecs_world_t *world, + ecs_misc_memory_t *result) +{ + ecs_iter_t it = ecs_each(world, EcsTreeSpawner); + while (ecs_each_next(&it)) { + EcsTreeSpawner *t = ecs_field(&it, EcsTreeSpawner, 0); + for (int32_t i = 0; i < it.count; i ++) { + for (int32_t depth = 0; + depth < FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE; + depth ++) + { + result->bytes_tree_spawner += + ecs_vec_count(&t[i].data[depth].children) * + ECS_SIZEOF(ecs_tree_spawner_child_t); + } + } + } + + result->bytes_tree_spawner += + ecs_vec_count(&world->allocators.tree_spawner) * + ECS_SIZEOF(ecs_entity_t); +} + ecs_misc_memory_t ecs_misc_memory_get( const ecs_world_t *world) { @@ -69615,6 +73938,10 @@ ecs_misc_memory_t ecs_misc_memory_get( #ifdef FLECS_REST flecs_rest_memory_get(world, &result); #endif + flecs_tree_spawner_memory_get(world, &result); + + result.bytes_prefab_child_indices = flecs_map_memory_get( + &world->prefab_child_indices, 0); result.bytes_component_ids += ecs_vec_size(&world->component_ids) * ECS_SIZEOF(ecs_entity_t); @@ -69811,6 +74138,7 @@ void flecs_stats_memory_register_reflection( { .name = "bytes_table_cache", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_name_index", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_ordered_children", .type = ecs_id(ecs_i32_t), .unit = unit }, + { .name = "bytes_children_table_map", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_reachable_cache", .type = ecs_id(ecs_i32_t), .unit = unit } } }); @@ -69840,8 +74168,6 @@ void flecs_stats_memory_register_reflection( { .name = "bytes_type", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_entities", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_overrides", .type = ecs_id(ecs_i32_t), .unit = unit }, - { .name = "bytes_columns", .type = ecs_id(ecs_i32_t), .unit = unit }, - { .name = "bytes_table_records", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_column_map", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_component_map", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_dirty_state", .type = ecs_id(ecs_i32_t), .unit = unit }, @@ -69871,6 +74197,8 @@ void flecs_stats_memory_register_reflection( { .name = "bytes_rematch_monitor", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_component_ids", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_reflection", .type = ecs_id(ecs_i32_t), .unit = unit }, + { .name = "bytes_tree_spawner", .type = ecs_id(ecs_i32_t), .unit = unit }, + { .name = "bytes_prefab_child_indices", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_stats", .type = ecs_id(ecs_i32_t), .unit = unit }, { .name = "bytes_rest", .type = ecs_id(ecs_i32_t), .unit = unit }, } @@ -70389,14 +74717,6 @@ void FlecsStatsImport( #ifdef FLECS_META ECS_IMPORT(world, FlecsMeta); #endif -#ifdef FLECS_UNITS - ECS_IMPORT(world, FlecsUnits); -#endif -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); - ecs_doc_set_brief(world, ecs_id(FlecsStats), - "Module that automatically monitors statistics for the world & systems"); -#endif ecs_set_name_prefix(world, "Ecs"); @@ -71063,10 +75383,13 @@ bool ecs_pipeline_stats_get( int32_t sys_count = 0, active_sys_count = 0; + ecs_component_record_t *cr_empty = flecs_components_get( + world, EcsEmpty); + /* Count number of active systems */ ecs_iter_t it = ecs_query_iter(stage, pq->query); while (ecs_query_next(&it)) { - if (flecs_component_get_table(pq->cr_inactive, it.table) != NULL) { + if (cr_empty && flecs_component_get_table(cr_empty, it.table) != NULL) { continue; } active_sys_count += it.count; @@ -71100,7 +75423,9 @@ bool ecs_pipeline_stats_get( int32_t i, i_system = 0, ran_since_merge = 0; while (ecs_query_next(&it)) { - if (flecs_component_get_table(pq->cr_inactive, it.table) != NULL) { + if (cr_empty && + flecs_component_get_table(cr_empty, it.table) != NULL) + { continue; } @@ -71701,12 +76026,10 @@ void FlecsWorldSummaryImport( }); ecs_observer(world, { - .entity = ecs_entity(world, { - .name = "OnSetWorldSummary" - }), .events = { EcsOnSet }, .query.terms = {{ .id = ecs_id(EcsWorldSummary) }}, - .callback = OnSetWorldSummary + .callback = OnSetWorldSummary, + .global_observer = true }); ecs_set(world, EcsWorld, EcsWorldSummary, { @@ -71813,6 +76136,10 @@ ecs_entity_t flecs_run_system( qit.callback_ctx = system_data->callback_ctx; qit.run_ctx = system_data->run_ctx; + if (system_data->group_id_set) { + ecs_iter_set_group(&qit, system_data->group_id); + } + if (stage_count > 1 && system_data->multi_threaded) { wit = ecs_worker_iter(it, stage_index, stage_count); it = &wit; @@ -71992,6 +76319,13 @@ ecs_entity_t ecs_system_init( EcsPoly *poly = flecs_poly_bind(world, entity, ecs_system_t); if (!poly->poly) { + ecs_check(desc->callback != NULL || desc->run != NULL, + ECS_INVALID_PARAMETER, + "missing implementation for system %s (set .callback or .run)", + desc->entity + ? flecs_errstr(ecs_get_path(world, desc->entity)) + : ""); + ecs_system_t *system = flecs_poly_new(ecs_system_t); ecs_assert(system != NULL, ECS_INTERNAL_ERROR, NULL); @@ -72010,6 +76344,11 @@ ecs_entity_t ecs_system_init( /* Prevent the system from moving while we're initializing */ flecs_defer_begin(world, world->stages[0]); + if (desc->phase) { + ecs_add_id(world, entity, desc->phase); + ecs_add_pair(world, entity, EcsDependsOn, desc->phase); + } + system->query = query; system->run = desc->run; @@ -72133,15 +76472,27 @@ const ecs_system_t* ecs_system_get( return flecs_poly_get(world, entity, ecs_system_t); } +void ecs_system_set_group( + ecs_world_t *world, + ecs_entity_t system, + uint64_t group_id) +{ + ecs_check(world != NULL, ECS_INVALID_PARAMETER, NULL); + ecs_check(system != 0, ECS_INVALID_PARAMETER, NULL); + + ecs_system_t *system_data = flecs_poly_get(world, system, ecs_system_t); + ecs_check(system_data != NULL, ECS_INVALID_PARAMETER, NULL); + + system_data->group_id = group_id; + system_data->group_id_set = true; +error: + return; +} + void FlecsSystemImport( ecs_world_t *world) { ECS_MODULE(world, FlecsSystem); -#ifdef FLECS_DOC - ECS_IMPORT(world, FlecsDoc); - ecs_doc_set_brief(world, ecs_id(FlecsSystem), - "Module that implements Flecs systems"); -#endif ecs_set_name_prefix(world, "Ecs"); @@ -72324,7 +76675,11 @@ uint64_t flecs_query_cache_default_group_by( ecs_id_t match; if (ecs_search(world, table, ecs_pair(id, EcsWildcard), &match) != -1) { - return ecs_pair_second(world, match); + if (ECS_IS_VALUE_PAIR(match)) { + return ECS_PAIR_SECOND(match); + } else { + return ecs_pair_second(world, match); + } } return 0; } @@ -72778,13 +77133,15 @@ ecs_query_cache_t* flecs_query_cache_init( } if ((t == count) && (q->flags & EcsQueryMatchOnlySelf) && - !(q->flags & EcsQueryMatchWildcards)) + !(q->flags & EcsQueryMatchWildcards) && + !(q->flags & EcsQueryCacheWithFilter)) { if (!const_desc->order_by && !const_desc->group_by && !const_desc->order_by_callback && !const_desc->group_by_callback && !(const_desc->flags & EcsQueryDetectChanges)) { + q->flags |= EcsQueryTrivialCache; } } @@ -72793,6 +77150,7 @@ ecs_query_cache_t* flecs_query_cache_init( if (const_desc->flags & EcsQueryDetectChanges) { for (int i = 0; i < q->term_count; i ++) { ecs_term_t *term = &q->terms[i]; + /* If query has change detection, flag this on the component record. * This allows code to skip calling modified() if there are no OnSet * hooks/observers, and the component isn't used in any queries that use @@ -72855,6 +77213,7 @@ ecs_query_cache_t* flecs_query_cache_init( ecs_os_memcpy_n(observer_desc.query.terms, q->terms, ecs_term_t, q->term_count); observer_desc.query.expr = NULL; /* Already parsed */ + observer_desc.query.flags |= EcsQueryTableOnly; result->observer = flecs_observer_init(world, entity, &observer_desc); if (!result->observer) { @@ -72952,18 +77311,19 @@ void flecs_query_update_node_up_trs( } ecs_entity_t src = node->_sources[f]; - if (src) { + if (src && src != EcsWildcard) { ecs_record_t *r = flecs_entities_get(ctx->world, src); ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(r->table != NULL, ECS_INTERNAL_ERROR, NULL); if (r->table != node->_tables[f]) { + node->_tables[f] = r->table; + ecs_component_record_t *cr = flecs_components_get( ctx->world, q->ids[f]); const ecs_table_record_t *tr = node->base.trs[f] = flecs_component_get_table(cr, r->table); - ecs_assert(tr != NULL, ECS_INTERNAL_ERROR, NULL); - ctx->it->trs[field_map ? field_map[f] : f] = tr; - node->_tables[f] = r->table; + + ctx->it->trs[field_map ? field_map[f] : f] = tr; } } } @@ -73076,53 +77436,6 @@ ecs_query_cache_match_t* flecs_query_cache_next( } } -/* Update cached pointers. Cached queries store the column pointers of a matched - * table which improves cache locality of fetching component pointers while - * iterating a cache as it avoids having to go through a table record. - * Component pointers only need to be updated when a table column got - * reallocated, in which case the table_column_version will have increased. */ -static -void flecs_query_cache_update_ptrs( - ecs_iter_t *it, - ecs_query_triv_cache_match_t *qm, - ecs_table_t *table) -{ - ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); - - it->ptrs = qm->ptrs; - - uint32_t version = flecs_get_table_column_version( - it->real_world, table->id); - if (qm->table_version == version) { - /* This is the most common case, as table columns pointers only change - * when the table grows in size. */ - return; - } - - qm->table_version = version; - - /* Update the pointers. This can be done safely from multiple threads since - * all the read data is immutable, and thus each thread will arrive at the - * same result. */ - int32_t i, field_count = it->field_count; - for (i = 0; i < field_count; i ++) { - qm->ptrs[i] = NULL; - - const ecs_table_record_t *tr = qm->trs[i]; - if (!tr || tr->column == -1) { - /* Field is not set or is not a component. */ - continue; - } - - if (it->sources[i]) { - /* Field is not matched on table */ - continue; - } - - qm->ptrs[i] = table->data.columns[tr->column].data; - } -} - /* Find next match in trivial cache. A trivial cache doesn't have to handle * wildcards, multiple groups or fields matched through up traversal. */ static @@ -73150,8 +77463,6 @@ ecs_query_cache_match_t* flecs_query_trivial_cache_next( } } - flecs_query_cache_update_ptrs(it, qm, table); - it->entities = ecs_table_entities(table); it->trs = qm->trs; it->set_fields = qm->set_fields; @@ -73256,6 +77567,9 @@ bool flecs_query_is_cache_search( return false; } + ctx->vars[0].range.count = node->_count; + ctx->vars[0].range.offset = node->_offset; + ecs_iter_t *it = ctx->it; it->trs = node->base.trs; it->ids = node->_ids; @@ -73263,9 +77577,11 @@ bool flecs_query_is_cache_search( it->set_fields = node->base.set_fields; it->up_fields = node->_up_fields; - flecs_query_update_node_up_trs(ctx, node); +#ifdef FLECS_DEBUG + it->flags |= EcsIterImmutableCacheData; +#endif - flecs_query_cache_update_ptrs(it, &node->base, node->base.table); + flecs_query_update_node_up_trs(ctx, node); return true; } @@ -73312,6 +77628,10 @@ bool flecs_query_is_cache_test( it->sources = node->_sources; it->set_fields = node->base.set_fields; +#ifdef FLECS_DEBUG + it->flags |= EcsIterImmutableCacheData; +#endif + flecs_query_update_node_up_trs(ctx, node); return true; @@ -74022,6 +78342,23 @@ void ecs_iter_skip( */ +/* Check if group is currently linked in the cache group list. */ +static +bool flecs_query_cache_group_is_linked( + const ecs_query_cache_t *cache, + const ecs_query_cache_group_t *group) +{ + ecs_query_cache_group_t *cur = cache->first_group; + while (cur) { + if (cur == group) { + return true; + } + cur = cur->next; + } + + return false; +} + /* Get group id for table. */ static uint64_t flecs_query_cache_get_group_id( @@ -74061,11 +78398,6 @@ void flecs_query_cache_group_insert( cache->cascade_by - 1].src.id & EcsDesc) != 0; } - if (!group->info.id) { - /* Default group is always inserted */ - return; - } - ecs_query_cache_group_t *cur = cache->first_group, *prev = NULL; do { ecs_assert(cur->info.id != group->info.id, ECS_INTERNAL_ERROR, NULL); @@ -74098,7 +78430,25 @@ ecs_query_cache_group_t* flecs_query_cache_ensure_group( uint64_t group_id) { if (!group_id) { - return &cache->default_group; + ecs_query_cache_group_t *group = &cache->default_group; + if (!group->info.table_count) { + if (ecs_map_is_init(&cache->groups)) { + ecs_query_cache_group_t **group_ptr = ecs_map_ensure_ref( + &cache->groups, ecs_query_cache_group_t, 0); + *group_ptr = group; + } + + if (!flecs_query_cache_group_is_linked(cache, group)) { + flecs_query_cache_group_insert(cache, group); + } + + if (cache->on_group_create) { + group->info.ctx = cache->on_group_create( + cache->query->world, 0, cache->group_by_ctx); + } + } + + return group; } ecs_query_cache_group_t *group = ecs_map_get_deref(&cache->groups, @@ -74120,6 +78470,7 @@ ecs_query_cache_group_t* flecs_query_cache_ensure_group( flecs_query_cache_group_insert(cache, group); + if (cache->on_group_create) { group->info.ctx = cache->on_group_create( cache->query->world, group_id, cache->group_by_ctx); @@ -74135,7 +78486,10 @@ void flecs_query_cache_group_fini( ecs_query_cache_t *cache, ecs_query_cache_group_t *group) { - if (cache->on_group_delete) { + /* Group callbacks are only meaningful for groups that have matched at + * least one table. The default group can exist as list head without ever + * being materialized through on_group_create (group id 0). */ + if (cache->on_group_delete && group->info.table_count) { cache->on_group_delete(cache->query->world, group->info.id, group->info.ctx, cache->group_by_ctx); } @@ -74144,9 +78498,16 @@ void flecs_query_cache_group_fini( ecs_allocator_t *a = &cache->query->real_world->allocator; ecs_vec_fini(a, &group->tables, elem_size); + group->info.table_count = 0; + group->info.match_count = 0; + group->info.ctx = NULL; if (group != &cache->default_group) { ecs_map_remove_free(&cache->groups, group->info.id); + } else { + if (ecs_map_is_init(&cache->groups)) { + ecs_map_remove(&cache->groups, 0); + } } } @@ -74438,9 +78799,6 @@ void flecs_query_cache_match_elem_fini( flecs_bfree(&cache->allocators.pointers, ECS_CONST_CAST(void*, qm->base.trs)); - flecs_bfree(&cache->allocators.pointers, - ECS_CONST_CAST(void*, qm->base.ptrs)); - if (!flecs_query_cache_is_trivial(cache)) { if (qm->_ids != cache->query->ids) { flecs_bfree(&cache->allocators.ids, qm->_ids); @@ -74497,10 +78855,6 @@ void flecs_query_cache_match_set( qm->base.table = it->table; qm->base.set_fields = it->set_fields; - if (!qm->base.ptrs) { - qm->base.ptrs = flecs_balloc(&cache->allocators.pointers); - } - if (!qm->base.trs) { qm->base.trs = flecs_balloc(&cache->allocators.pointers); } @@ -74508,12 +78862,6 @@ void flecs_query_cache_match_set( /* Reset resources in case this is an existing record */ ecs_os_memcpy_n(ECS_CONST_CAST(ecs_table_record_t**, qm->base.trs), it->trs, ecs_table_record_t*, field_count); - - /* Initialize pointers*/ - ecs_os_memset_n(qm->base.ptrs, 0, void*, field_count); - - /* Set table version to sentinel that'll force reevaluation */ - qm->base.table_version = UINT32_MAX; /* Find out whether to store result-specific ids array or fixed array */ ecs_id_t *ids = cache->query->ids; @@ -75379,7 +79727,7 @@ int flecs_query_discover_vars( bool first_is_this = (ECS_TERM_REF_ID(first) == EcsThis) && (first->id & EcsIsVariable); bool second_is_this = - (ECS_TERM_REF_ID(first) == EcsThis) && (first->id & EcsIsVariable); + (ECS_TERM_REF_ID(second) == EcsThis) && (second->id & EcsIsVariable); if (first_is_this || second_is_this) { if (!table_this) { @@ -75742,6 +80090,8 @@ void flecs_query_insert_cache_search( } ecs_query_t *q = &query->pub; + int32_t childof_term = -1; + bool has_childof_trav = false; if (q->cache_kind == EcsQueryCacheAll) { /* If all terms are cacheable, make sure no other terms are compiled */ @@ -75761,6 +80111,16 @@ void flecs_query_insert_cache_search( continue; } + if (term->flags_ & EcsTermNonFragmentingChildOf) { + if (!term->trav) { + childof_term = i; + } + } + + if (term->trav == EcsChildOf) { + has_childof_trav = true; + } + *compiled |= (1ull << i); } } @@ -75777,6 +80137,35 @@ void flecs_query_insert_cache_search( flecs_query_write(0, &op.written); flecs_query_write_ctx(0, ctx, false); flecs_query_op_insert(&op, ctx); + + if (childof_term != -1) { + flecs_query_compile_term( + q->world, query, &q->terms[childof_term], ctx); + } + + if (has_childof_trav) { + ecs_term_t *terms = q->terms; + int32_t i, count = q->term_count; + + for (i = 0; i < count; i ++) { + ecs_term_t *term = &terms[i]; + if (!((*compiled) & (1ull << i))) { + continue; + } + + if (!(term->flags_ & EcsTermIsCacheable)) { + continue; + } + + if (term->trav == EcsChildOf && (term->oper == EcsAnd || term->oper == EcsOptional)) { + ecs_oper_kind_t oper = q->terms[i].oper; + q->terms[i].oper = EcsAnd; + flecs_query_compile_term( + q->world, query, &q->terms[i], ctx); + q->terms[i].oper = (int16_t)oper; + } + } + } } static @@ -75960,7 +80349,9 @@ int flecs_query_compile( if (query->cache) { if (flags & EcsQueryIsCacheable) { - needs_plan = false; + if (!(flags & EcsQueryCacheWithFilter)) { + needs_plan = false; + } } } else { ecs_flags32_t trivial_flags = EcsQueryIsTrivial|EcsQueryMatchOnlySelf; @@ -75989,7 +80380,6 @@ int flecs_query_compile( ctx.ops = &stage->operations; ctx.cur = ctx.ctrlflow; ctx.cur->lbl_begin = -1; - ctx.cur->lbl_begin = -1; ecs_vec_clear(ctx.ops); /* Find all variables defined in query */ @@ -76110,6 +80500,20 @@ int flecs_query_compile( } } while (true); + /* If this is the last term and it's a Tree instruction, replace it + * with Children. If the queried for parent has the OrderedChildren + * trait, the Children instruction will return the array with child + * entities vs. returning children one by one. */ + if (term_count == 1 && ecs_vec_count(ctx.ops)) { + ecs_query_op_t *op = ecs_vec_last_t(ctx.ops, ecs_query_op_t); + ecs_assert(op != NULL, ECS_INTERNAL_ERROR, NULL); + if (op->kind == EcsQueryTree) { + op->kind = EcsQueryChildren; + } else if (op->kind == EcsQueryTreeWildcard) { + op->kind = EcsQueryChildrenWc; + } + } + ecs_var_id_t this_id = flecs_query_find_var_id(query, "this", EcsVarEntity); if (this_id != EcsVarNone) { /* If This variable has been written as entity, insert an operation to @@ -77291,10 +81695,13 @@ void flecs_query_mark_last_or_op( static void flecs_query_set_op_kind( + ecs_query_impl_t *query, ecs_query_op_t *op, ecs_term_t *term, bool src_is_var) { + (void)query; + /* Default instruction for And operators. If the source is fixed (like for * singletons or terms with an entity source), use With, which like And but * just matches against a source (vs. finding a source). */ @@ -77313,8 +81720,11 @@ void flecs_query_set_op_kind( /* If query is transitive, use Trav(ersal) instruction */ } else if (term->flags_ & EcsTermTransitive) { - ecs_assert(ecs_term_ref_is_set(&term->second), ECS_INTERNAL_ERROR, NULL); + ecs_assert(ecs_term_ref_is_set(&term->second), + ECS_INTERNAL_ERROR, NULL); op->kind = EcsQueryTrav; + + /* Handle non-fragmenting components */ } else if (term->flags_ & EcsTermDontFragment) { if (op->kind == EcsQueryAnd) { op->kind = EcsQuerySparse; @@ -77333,8 +81743,22 @@ void flecs_query_set_op_kind( } else { if ((term->src.id & trav_flags) == EcsUp) { op->kind = EcsQueryUp; + if (term->trav == EcsChildOf) { + if (term->flags_ & EcsTermIsCacheable && query->cache) { + op->kind = EcsQueryTreeUpPost; + } else if (query->pub.flags & EcsQueryNested) { + op->kind = EcsQueryTreeUpPre; + } + } } else if ((term->src.id & trav_flags) == (EcsSelf|EcsUp)) { op->kind = EcsQuerySelfUp; + if (term->trav == EcsChildOf) { + if (term->flags_ & EcsTermIsCacheable && query->cache) { + op->kind = EcsQueryTreeSelfUpPost; + } else if (query->pub.flags & EcsQueryNested) { + op->kind = EcsQueryTreeSelfUpPre; + } + } } else if (term->flags_ & (EcsTermMatchAny|EcsTermMatchAnySrc)) { op->kind = EcsQueryAndAny; } else if (ECS_IS_PAIR(term->id) && @@ -77346,6 +81770,43 @@ void flecs_query_set_op_kind( op->kind = EcsQueryWithWcTgt; } } + + /* ChildOf terms need to take into account both ChildOf pairs and the + * Parent component for non-fragmenting hierarchies. */ + if (term->flags_ & EcsTermNonFragmentingChildOf && !term->trav) { + if (query->pub.flags & EcsQueryNested) { + /* If this is a nested query (used to populate a cache), insert + * instruction that matches tables with ChildOf pairs and Parent + * component, without filtering the non-fragmenting parents as + * this cannot be cached. */ + op->kind = EcsQueryTreePre; + } else { + if (!src_is_var) { + op->kind = EcsQueryTreeWith; + } else { + if (op->kind == EcsQueryAnd) { + if (ECS_PAIR_SECOND(term->id) == EcsWildcard) { + op->kind = EcsQueryTreeWildcard; + } else { + op->kind = EcsQueryTree; + } + + if (term->flags_ & EcsTermIsCacheable) { + if (query->cache) { + op->kind = EcsQueryTreePost; + } + } + } else if (op->kind == EcsQueryAndAny) { + if (ECS_PAIR_SECOND(term->id)) { + op->kind = EcsQueryTreeWildcard; + } else { + /* If it's a (ChildOf, 0) query then we don't need to + * evaluate it as a wildcard. */ + } + } + } + } + } } } @@ -77445,7 +81906,7 @@ int flecs_query_compile_term( op.field_index = flecs_ito(int8_t, term->field_index); op.term_index = flecs_ito(int8_t, term - q->terms); - flecs_query_set_op_kind(&op, term, src_is_var); + flecs_query_set_op_kind(query, &op, term, src_is_var); bool is_not = (term->oper == EcsNot) && !builtin_pred; if (op.kind == EcsQuerySparseNot) { @@ -77769,7 +82230,7 @@ bool flecs_query_select_w_id( } repeat: - if (!redo || !op_ctx->remaining) { + if (!redo || (op_ctx->remaining <= 0)) { tr = flecs_table_cache_next(&op_ctx->it, ecs_table_record_t); if (!tr) { return false; @@ -77918,7 +82379,6 @@ bool flecs_query_all( } } -static bool flecs_query_and( const ecs_query_op_t *op, bool redo, @@ -78016,37 +82476,6 @@ bool flecs_query_with_id( return true; } -static -bool flecs_query_up( - const ecs_query_op_t *op, - bool redo, - const ecs_query_run_ctx_t *ctx) -{ - uint64_t written = ctx->written[ctx->op_index]; - if (flecs_ref_is_written(op, &op->src, EcsQuerySrc, written)) { - return flecs_query_up_with(op, redo, ctx); - } else { - return flecs_query_up_select(op, redo, ctx, - FlecsQueryUpSelectUp, FlecsQueryUpSelectDefault); - } -} - -static -bool flecs_query_self_up( - const ecs_query_op_t *op, - bool redo, - const ecs_query_run_ctx_t *ctx) -{ - uint64_t written = ctx->written[ctx->op_index]; - if (flecs_ref_is_written(op, &op->src, EcsQuerySrc, written)) { - return flecs_query_self_up_with(op, redo, ctx, false); - } else { - return flecs_query_up_select(op, redo, ctx, - FlecsQueryUpSelectSelfUp, FlecsQueryUpSelectDefault); - } -} - -static bool flecs_query_and_any( const ecs_query_op_t *op, bool redo, @@ -78402,6 +82831,25 @@ bool flecs_query_or_from( return flecs_query_x_from(op, redo, ctx, EcsOrFrom); } +static +bool flecs_query_ids_check( + ecs_component_record_t *cur) +{ + if (!cur->cache.tables.count) { + if (!(cur->flags & EcsIdOrderedChildren)) { + return false; + } + + ecs_assert(cur->pair != NULL, ECS_INTERNAL_ERROR, NULL); + + if (!ecs_vec_count(&cur->pair->ordered_children)) { + return false; + } + } + + return true; +} + static bool flecs_query_ids( const ecs_query_op_t *op, @@ -78417,7 +82865,11 @@ bool flecs_query_ids( { cur = flecs_components_get(ctx->world, id); - if (!cur || !cur->cache.tables.count) { + if (!cur) { + return false; + } + + if (!flecs_query_ids_check(cur)) { return false; } } @@ -78442,18 +82894,22 @@ bool flecs_query_idsright( { ecs_query_ids_ctx_t *op_ctx = flecs_op_ctx(ctx, ids); ecs_component_record_t *cur; + ecs_iter_t *it = ctx->it; if (!redo) { ecs_id_t id = flecs_query_op_get_id(op, ctx); + cur = op_ctx->cur = flecs_components_get(ctx->world, id); if (!ecs_id_is_wildcard(id)) { /* If id is not a wildcard, we can directly return it. This can * happen if a variable was constrained by an iterator. */ op_ctx->cur = NULL; flecs_query_set_vars(op, id, ctx); - return true; + it->ids[op->field_index] = id; + it->sources[op->field_index] = EcsWildcard; + ECS_TERMSET_SET(it->set_fields, 1u << op->field_index); + return flecs_query_ids_check(cur); } - cur = op_ctx->cur = flecs_components_get(ctx->world, id); if (!cur) { return false; } @@ -78466,7 +82922,7 @@ bool flecs_query_idsright( next: do { cur = op_ctx->cur = flecs_component_first_next(op_ctx->cur); - } while (cur && !cur->cache.tables.count); /* Skip empty ids */ + } while (cur && !flecs_query_ids_check(cur)); /* Skip empty ids */ if (!cur) { return false; @@ -78481,7 +82937,6 @@ bool flecs_query_idsright( flecs_query_set_vars(op, cur->id, ctx); if (op->field_index != -1) { - ecs_iter_t *it = ctx->it; ecs_id_t id = flecs_query_op_get_id_w_written(op, op->written, ctx); it->ids[op->field_index] = id; it->sources[op->field_index] = EcsWildcard; @@ -78995,9 +83450,18 @@ bool flecs_query_select_or( do { ctx->written[prev] = ctx->written[last]; + ecs_query_op_ctx_t *op_ctx_ptr = &ctx->op_ctx[first]; + ecs_query_op_ctx_t tmp_op_ctx = *op_ctx_ptr; + + ecs_os_zeromem(op_ctx_ptr); + flecs_query_run_until(false, ctx, ops, flecs_itolbl(first - 1), prev, cur); + flecs_query_op_ctx_fini(ctx->it, &ops[first], op_ctx_ptr); + + ecs_os_memcpy_t(op_ctx_ptr, &tmp_op_ctx, ecs_query_op_ctx_t); + if (ctx->op_index == last) { /* Duplicate match was found, find next result */ redo = true; @@ -79100,9 +83564,23 @@ bool flecs_query_optional( ecs_query_run_ctx_t *ctx) { bool result = flecs_query_run_block_w_reset(op, redo, ctx); + + ecs_query_optional_ctx_t *op_ctx = flecs_op_ctx(ctx, optional); + if (!redo) { + op_ctx->range = flecs_query_get_range(op, &op->src, EcsQuerySrc, ctx); return true; /* Return at least once */ } else { + if (!result) { + ecs_table_range_t range = flecs_query_get_range( + op, &op->src, EcsQuerySrc, ctx); + if (range.offset != op_ctx->range.offset) { + /* Different range is returned, so yield again. */ + result = true; + op_ctx->range = range; + } + } + return result; } } @@ -79223,6 +83701,17 @@ bool flecs_query_dispatch( case EcsQuerySparseNot: return flecs_query_sparse_with(op, redo, ctx, true); case EcsQuerySparseSelfUp: return flecs_query_sparse_self_up(op, redo, ctx); case EcsQuerySparseUp: return flecs_query_sparse_up(op, redo, ctx); + case EcsQueryTree: return flecs_query_tree_and(op, redo, ctx); + case EcsQueryTreeWildcard: return flecs_query_tree_and_wildcard(op, redo, ctx, false); + case EcsQueryTreePre: return flecs_query_tree_pre(op, redo, ctx); + case EcsQueryTreePost: return flecs_query_tree_post(op, redo, ctx); + case EcsQueryTreeUpPre: return flecs_query_tree_up_pre(op, redo, ctx, false); + case EcsQueryTreeSelfUpPre: return flecs_query_tree_up_pre(op, redo, ctx, true); + case EcsQueryTreeUpPost: return flecs_query_tree_up_post(op, redo, ctx, false); + case EcsQueryTreeSelfUpPost: return flecs_query_tree_up_post(op, redo, ctx, true); + case EcsQueryChildrenWc: return flecs_query_tree_and_wildcard(op, redo, ctx, true); + case EcsQueryTreeWith: return flecs_query_tree_with(op, redo, ctx); + case EcsQueryChildren: return flecs_query_children(op, redo, ctx); case EcsQueryLookup: return flecs_query_lookup(op, redo, ctx); case EcsQuerySetVars: return flecs_query_setvars(op, redo, ctx); case EcsQuerySetThis: return flecs_query_setthis(op, redo, ctx); @@ -79378,17 +83867,19 @@ void flecs_query_iter_constrain( } } } else if (flags & EcsQueryIsCacheable) { - if (!cache->order_by_callback && - (cache->query->flags & EcsQueryTrivialCache && - !(query->pub.flags & EcsQueryHasChangeDetection))) - { - it->flags |= EcsIterTrivialTest|EcsIterTrivialCached| - EcsIterTrivialChangeDetection; - it->ids = cache->query->ids; - it->sources = cache->sources; - it->set_fields = flecs_uto(uint32_t, (1llu << it->field_count) - 1); - } else { - it->flags |= EcsIterTrivialTest|EcsIterCached; + if (!query->ops) { + if (!cache->order_by_callback && + (cache->query->flags & EcsQueryTrivialCache && + !(query->pub.flags & EcsQueryHasChangeDetection))) + { + it->flags |= EcsIterTrivialTest|EcsIterTrivialCached| + EcsIterTrivialChangeDetection; + it->ids = cache->query->ids; + it->sources = cache->sources; + it->set_fields = flecs_uto(uint32_t, (1llu << it->field_count) - 1); + } else { + it->flags |= EcsIterTrivialTest|EcsIterCached; + } } } } else { @@ -79401,17 +83892,19 @@ void flecs_query_iter_constrain( } } } else if (flags & EcsQueryIsCacheable) { - if (!cache->order_by_callback && - (cache->query->flags & EcsQueryTrivialCache && - !(query->pub.flags & EcsQueryHasChangeDetection))) - { - it->flags |= EcsIterTrivialSearch|EcsIterTrivialCached| - EcsIterTrivialChangeDetection; - it->ids = cache->query->ids; - it->sources = cache->sources; - it->set_fields = flecs_uto(uint32_t, (1llu << it->field_count) - 1); - } else { - it->flags |= EcsIterTrivialSearch|EcsIterCached; + if (!query->ops) { + if (!cache->order_by_callback && + (cache->query->flags & EcsQueryTrivialCache && + !(query->pub.flags & EcsQueryHasChangeDetection))) + { + it->flags |= EcsIterTrivialSearch|EcsIterTrivialCached| + EcsIterTrivialChangeDetection; + it->ids = cache->query->ids; + it->sources = cache->sources; + it->set_fields = flecs_uto(uint32_t, (1llu << it->field_count) - 1); + } else { + it->flags |= EcsIterTrivialSearch|EcsIterCached; + } } } } @@ -79608,6 +84101,46 @@ bool flecs_query_trivial_cached_next( return false; } +void flecs_query_op_ctx_fini( + ecs_iter_t *it, + const ecs_query_op_t *op, + ecs_query_op_ctx_t *ctx) +{ + switch(op->kind) { + case EcsQueryTrav: { + ecs_allocator_t *a = flecs_query_get_allocator(it); + flecs_query_trav_cache_fini(a, &ctx->is.trav.cache); + break; + } + case EcsQueryUp: + case EcsQuerySelfUp: + case EcsQueryTreeUp: + case EcsQueryTreeSelfUp: + case EcsQueryTreeUpPre: + case EcsQueryTreeSelfUpPre: + case EcsQueryTreeUpPost: + case EcsQueryTreeSelfUpPost: + case EcsQuerySparseUp: + case EcsQuerySparseSelfUp: { + ecs_allocator_t *a = flecs_query_get_allocator(it); + ecs_query_up_ctx_t *op_ctx = &ctx->is.up; + ecs_query_up_impl_t *impl = op_ctx->impl; + if (impl) { + ecs_trav_up_cache_t *cache = &impl->cache; + if (cache->dir == EcsTravDown) { + flecs_query_down_cache_fini(a, cache); + } else { + flecs_query_up_cache_fini(cache); + } + flecs_free_t(a, ecs_query_up_impl_t, impl); + } + break; + } + default: + break; + } +} + static void flecs_query_iter_fini_ctx( ecs_iter_t *it, @@ -79617,34 +84150,10 @@ void flecs_query_iter_fini_ctx( int32_t i, count = query->op_count; ecs_query_op_t *ops = query->ops; ecs_query_op_ctx_t *ctx = qit->op_ctx; - ecs_allocator_t *a = flecs_query_get_allocator(it); for (i = 0; i < count; i ++) { ecs_query_op_t *op = &ops[i]; - switch(op->kind) { - case EcsQueryTrav: - flecs_query_trav_cache_fini(a, &ctx[i].is.trav.cache); - break; - case EcsQueryUp: - case EcsQuerySelfUp: - case EcsQuerySparseUp: - case EcsQuerySparseSelfUp: { - ecs_query_up_ctx_t *op_ctx = &ctx[i].is.up; - ecs_query_up_impl_t *impl = op_ctx->impl; - if (impl) { - ecs_trav_up_cache_t *cache = &impl->cache; - if (cache->dir == EcsTravDown) { - flecs_query_down_cache_fini(a, cache); - } else { - flecs_query_up_cache_fini(cache); - } - flecs_free_t(a, ecs_query_up_impl_t, impl); - } - break; - } - default: - break; - } + flecs_query_op_ctx_fini(it, op, &ctx[i]); } } @@ -79782,7 +84291,8 @@ ecs_iter_t flecs_query_iter( it.up_fields = 0; flecs_query_apply_iter_flags(&it, q); - flecs_iter_init(it.world, &it, !impl->cache || !(q->flags & EcsQueryIsCacheable)); + bool fully_cached = (q->flags & EcsQueryIsCacheable) && !(q->flags & EcsQueryCacheWithFilter); + flecs_iter_init(it.world, &it, !impl->cache || !fully_cached); qit->query_vars = impl->vars; qit->ops = impl->ops; @@ -80351,10 +84861,7 @@ bool flecs_query_sparse_next_entity( op_ctx->cur ++; if (op_ctx->cur == end) { - if (op->flags & (EcsQueryIsVar << EcsQuerySrc)) { - flecs_query_var_narrow_range(op->src.var, op_ctx->range.table, - op_ctx->range.offset, op_ctx->range.count, ctx); - } + flecs_query_src_set_range(op, &op_ctx->range, ctx); return false; } @@ -80377,10 +84884,7 @@ bool flecs_query_sparse_next_entity( goto next; } - if (op->flags & (EcsQueryIsVar << EcsQuerySrc)) { - flecs_query_var_narrow_range(op->src.var, op_ctx->range.table, - op_ctx->cur, 1, ctx); - } + flecs_query_src_set_single(op, op_ctx->cur, ctx); return true; } @@ -80595,18 +85099,29 @@ bool flecs_query_sparse_with_id( if (!redo) { ecs_component_record_t *cr = flecs_components_get(ctx->world, id); if (!cr) { - return false; + goto no_sparse; } - op_ctx->sparse = cr->sparse; - if (!op_ctx->sparse) { - return false; + ecs_sparse_t *sparse = cr->sparse; + if (!sparse || !flecs_sparse_count(sparse)) { + goto no_sparse; } + op_ctx->sparse = sparse; flecs_query_sparse_init_range(op, ctx, op_ctx); + } else { + if (!op_ctx->range.table) { + return false; + } } return flecs_query_sparse_next_entity(op, ctx, op_ctx, not, ptr_out); +no_sparse: + op_ctx->sparse = NULL; + op_ctx->range.table = NULL; + op_ctx->range.offset = 0; + op_ctx->range.count = 0; + return not; } static @@ -81197,21 +85712,18 @@ bool flecs_query_toggle_cmp( goto done; } - if (op->flags & (EcsQueryIsVar << EcsQuerySrc)) { - flecs_query_var_narrow_range(op->src.var, table, row, cur - row, ctx); - } + flecs_query_src_set_range(op, &(ecs_table_range_t){ + .table = table, .offset = row, .count = cur - row + }, ctx); op_ctx->cur = cur; return true; done: /* Restore range & set fields */ - if (op->flags & (EcsQueryIsVar << EcsQuerySrc)) { - flecs_query_var_narrow_range(op->src.var, - table, op_ctx->range.offset, op_ctx->range.count, ctx); - } - + flecs_query_src_set_range(op, &op_ctx->range, ctx); it->set_fields = op_ctx->prev_set_fields; + return false; } @@ -81559,6 +86071,829 @@ bool flecs_query_trav( } } +/** + * @file query/engine/eval_tree.c + * @brief Hierarchy evaluation (ChildOf pairs/Parent components). + */ + + +const EcsParent* flecs_query_tree_get_parents( + ecs_table_range_t range) +{ + int32_t parent_column = range.table->component_map[ecs_id(EcsParent)]; + ecs_assert(parent_column != -1, ECS_INTERNAL_ERROR, NULL); + return ecs_table_get_column(range.table, parent_column - 1, range.offset); +} + +static +bool flecs_query_tree_select_tgt( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + ecs_query_tree_ctx_t *op_ctx = flecs_op_ctx(ctx, tree); + + if (redo) { + op_ctx->cur ++; + if (op_ctx->cur >= op_ctx->range.count) { + return false; + } + } + + ecs_entity_t child = op_ctx->entities[op_ctx->cur]; + ecs_assert(child != 0, ECS_INTERNAL_ERROR, NULL); + + ecs_table_range_t range = flecs_range_from_entity(ctx->world, child); + flecs_query_var_set_range(op, op->src.var, + range.table, range.offset, range.count, ctx); + + return true; +} + +static +bool flecs_query_tree_with_parent( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + ecs_query_tree_ctx_t *op_ctx = flecs_op_ctx(ctx, tree); + ecs_table_range_t range = op_ctx->range; + +repeat: + if (redo) { + op_ctx->cur ++; + } + + if ((op_ctx->cur - range.offset) >= range.count) { + flecs_query_src_set_range(op, &op_ctx->range, ctx); + return false; + } + + ecs_assert(op_ctx->cur >= range.offset, ECS_INTERNAL_ERROR, NULL); + ecs_assert(op_ctx->cur < (range.offset + range.count), ECS_INTERNAL_ERROR, NULL); + + ecs_entity_t tgt = op_ctx->tgt; + ecs_entity_t parent = op_ctx->parents[op_ctx->cur - range.offset].value; + + ecs_iter_t *it = ctx->it; + flecs_query_iter_set_id(it, op->field_index, ecs_childof(parent)); + + if (tgt != EcsWildcard) { + if (parent != op_ctx->tgt) { + redo = true; + goto repeat; + } + } + + flecs_query_src_set_single(op, op_ctx->cur, ctx); + + return true; +} + +static +bool flecs_query_tree_select( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + ecs_query_tree_ctx_t *op_ctx = flecs_op_ctx(ctx, tree); + + if (!redo) { + ecs_id_t id = flecs_query_op_get_id(op, ctx); + ecs_assert(ECS_PAIR_FIRST(id) == EcsChildOf, + ECS_INTERNAL_ERROR, NULL); + op_ctx->tgt = ECS_PAIR_SECOND(id); + op_ctx->cur = 0; + + ecs_component_record_t *cr = flecs_components_get(ctx->world, id); + if (!cr) { + return false; + } + + if (!(cr->flags & EcsIdOrderedChildren)) { + op_ctx->tgt = 0; + return flecs_query_and(op, redo, ctx); + } + + ecs_assert(op_ctx->tgt != EcsWildcard, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr->pair != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_vec_t *v_children = &cr->pair->ordered_children; + op_ctx->entities = ecs_vec_first_t(v_children, ecs_entity_t); + op_ctx->range.count = ecs_vec_count(v_children); + if (!op_ctx->range.count) { + return false; + } + } else { + if (!op_ctx->tgt) { + return flecs_query_and(op, redo, ctx); + } + } + + return flecs_query_tree_select_tgt(op, redo, ctx); +} + +static +bool flecs_query_tree_select_any( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + ecs_id_t pair) +{ + ecs_query_tree_wildcard_ctx_t *op_ctx = flecs_op_ctx(ctx, tree_wildcard); + ecs_iter_t *it = ctx->it; + int8_t field_index = op->field_index; + ecs_assert(field_index >= 0, ECS_INTERNAL_ERROR, NULL); + + if (!redo) { + op_ctx->cr = ctx->world->cr_childof_wildcard; + ecs_assert(op_ctx->cr != NULL, ECS_INTERNAL_ERROR, NULL); + op_ctx->state = EcsQueryTreeIterEntities; + } + +next: + switch(op_ctx->state) { + case EcsQueryTreeIterEntities: { + bool result = flecs_query_select_w_id( + op, redo, ctx, ecs_id(EcsParent), + (EcsTableNotQueryable|EcsTableIsPrefab|EcsTableIsDisabled)); + if (!result) { + op_ctx->state = EcsQueryTreeIterTables; + redo = false; + goto next; + } + it->ids[field_index] = ecs_pair(EcsChildOf, EcsWildcard); + return true; + } + case EcsQueryTreeIterTables: { + bool result = flecs_query_select_w_id( + op, redo, ctx, pair, + (EcsTableNotQueryable|EcsTableIsPrefab|EcsTableIsDisabled)); + if (!result) { + return false; + } + it->ids[field_index] = pair; + return true; + } + case EcsQueryTreeIterNext: + default: + return false; + } +} + +static +bool flecs_query_tree_select_wildcard( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + bool bulk_return) +{ + ecs_iter_t *it = ctx->it; + int8_t field_index = op->field_index; + ecs_assert(field_index >= 0, ECS_INTERNAL_ERROR, NULL); + + ecs_id_t id = flecs_query_op_get_id(op, ctx); + ecs_assert(ECS_PAIR_FIRST(id) == EcsChildOf, + ECS_INTERNAL_ERROR, NULL); + ecs_entity_t tgt = ECS_PAIR_SECOND(id); + if (tgt != EcsWildcard) { + it->ids[field_index] = id; + + /* Happens when variable has been constrained */ + if (bulk_return) { + return flecs_query_children(op, redo, ctx); + } else { + return flecs_query_tree_select(op, redo, ctx); + } + } + + ecs_query_tree_wildcard_ctx_t *op_ctx = flecs_op_ctx(ctx, tree_wildcard); + + if (!redo) { + op_ctx->cr = ctx->world->cr_childof_wildcard; + ecs_assert(op_ctx->cr != NULL, ECS_INTERNAL_ERROR, NULL); + op_ctx->state = EcsQueryTreeIterNext; + } + +next: + switch(op_ctx->state) { + + /* Select next (ChildOf, parent) pair */ + case EcsQueryTreeIterNext: { + ecs_component_record_t *cr = op_ctx->cr = + flecs_component_first_next(op_ctx->cr); + if (!cr) { + return false; + } + + flecs_query_var_reset(0, ctx); + if (op->match_flags & EcsTermMatchAny) { + it->ids[field_index] = ecs_childof(EcsWildcard); + } else { + it->ids[field_index] = op_ctx->cr->id; + } + + if (cr->flags & EcsIdOrderedChildren) { + ecs_assert(cr->pair != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_vec_t *v_children = &cr->pair->ordered_children; + if (bulk_return) { + op_ctx->state = EcsQueryTreeIterNext; + it->entities = ecs_vec_first_t(v_children, ecs_entity_t); + it->count = ecs_vec_count(v_children); + goto done; + } else { + op_ctx->entities = ecs_vec_first_t(v_children, ecs_entity_t); + op_ctx->count = ecs_vec_count(v_children); + op_ctx->cur = -1; + op_ctx->state = EcsQueryTreeIterEntities; + goto next; + } + } else { + if (!flecs_component_iter(cr, &op_ctx->it)) { + op_ctx->state = EcsQueryTreeIterNext; + } else { + op_ctx->state = EcsQueryTreeIterTables; + } + } + goto next; + } + + /* Iterate tables for (ChildOf, parent) */ + case EcsQueryTreeIterTables: { + const ecs_table_record_t *tr = flecs_component_next(&op_ctx->it); + if (!tr) { + op_ctx->state = EcsQueryTreeIterNext; + goto next; + } else { + ecs_table_t *table = tr->hdr.table; + if (!ecs_table_count(table) || (table->flags & EcsTableNotQueryable)) { + goto next; + } + + it->trs[field_index] = tr; + flecs_query_var_set_range(op, op->src.var, table, 0, 0, ctx); + goto done; + } + } + + /* Return ordered entities for (ChildOf, parent) one by one */ + case EcsQueryTreeIterEntities: { + op_ctx->cur ++; + if (op_ctx->cur >= op_ctx->count) { + op_ctx->state = EcsQueryTreeIterNext; + goto next; + } else { + ecs_entity_t child = op_ctx->entities[op_ctx->cur]; + ecs_assert(child != 0, ECS_INTERNAL_ERROR, NULL); + ecs_table_range_t range = flecs_range_from_entity(ctx->world, child); + flecs_query_var_set_range(op, op->src.var, + range.table, range.offset, range.count, ctx); + goto done; + } + } + } + +done: + flecs_query_set_vars(op, it->ids[field_index], ctx); + return true; +} + +bool flecs_query_tree_with( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + ecs_query_tree_ctx_t *op_ctx = flecs_op_ctx(ctx, tree); + + if (redo) { + if (op_ctx->tgt) { + return flecs_query_tree_with_parent(op, redo, ctx); + } + + flecs_query_src_set_range(op, &op_ctx->range, ctx); + return false; + } + + ecs_table_range_t range = flecs_query_get_range( + op, &op->src, EcsQuerySrc, ctx); + if (!range.count) { + range.count = ecs_table_count(range.table); + } + + op_ctx->range = range; + + ecs_table_t *table = range.table; + ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); + + /* Fragmenting childof */ + if (table->flags & EcsTableHasChildOf) { + if (op->match_flags & EcsTermMatchAny) { + return flecs_query_and_any(op, redo, ctx); + } else { + return flecs_query_with(op, redo, ctx); + } + } + + ecs_iter_t *it = ctx->it; + ecs_id_t id = flecs_query_op_get_id(op, ctx); + ecs_assert(ECS_IS_PAIR(id), ECS_INTERNAL_ERROR, NULL); + ecs_assert(ECS_PAIR_FIRST(id) == EcsChildOf, ECS_INTERNAL_ERROR, NULL); + ecs_entity_t tgt = ECS_PAIR_SECOND(id); + + /* Root */ + if (!(table->flags & EcsTableHasParent)) { + if (!tgt) { + int8_t field_index = op->field_index; + it->set_fields &= ~(1u << field_index); + flecs_query_iter_set_id(it, op->field_index, ecs_childof(EcsWildcard)); + return true; + } + return false; + } + + /* Non-fragmenting childof */ + const EcsParent *parents = flecs_query_tree_get_parents(range); + + /* Evaluating a single entity */ + if (range.count == 1) { + ecs_entity_t parent = parents[0].value; + + /* Wildcard query */ + if (tgt == EcsWildcard) { + if (op->match_flags & EcsTermMatchAny) { + flecs_query_iter_set_id(it, op->field_index, ecs_childof(EcsWildcard)); + } else { + ecs_id_t actual_id = flecs_query_iter_set_id(it, op->field_index, + ecs_childof(parent)); + flecs_query_set_vars(op, actual_id, ctx); + } + + /* Parent query */ + } else { + if ((uint32_t)parent != tgt) { + return false; + } + + ecs_id_t actual_id = flecs_query_iter_set_id(it, op->field_index, + ecs_childof(parent)); + flecs_query_set_vars(op, actual_id, ctx); + } + + /* Evaluating an entity range */ + } else { + /* Wildcard query */ + if (tgt == EcsWildcard) { + if (op->match_flags & EcsTermMatchAny) { + flecs_query_iter_set_id(it, op->field_index, ecs_childof(EcsWildcard)); + } else { + op_ctx->parents = parents; + op_ctx->tgt = tgt; + op_ctx->cur = range.offset; + return flecs_query_tree_with_parent(op, redo, ctx); + } + + /* Parent query */ + } else { + ecs_component_record_t *cr = flecs_components_get( + ctx->world, ecs_pair(EcsChildOf, tgt)); + if (!cr) { + return false; + } + + ecs_parent_record_t *pr = flecs_component_get_parent_record( + cr, range.table); + if (!pr) { + /* Table doesn't have entities with parent */ + return false; + } + + ecs_entity_t child = pr->entity; + if (child) { + ecs_assert(pr->count == 1, ECS_INTERNAL_ERROR, NULL); + ecs_record_t *r = flecs_entities_get_any(ctx->world, child); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(r->table == range.table, ECS_INTERNAL_ERROR, NULL); + int32_t cur = ECS_RECORD_TO_ROW(r->row); + + /* Table contains a single entity for parent */ + if ((range.offset > cur) || ((range.offset + range.count) <= cur)) { + /* Entity does not fall within range */ + return false; + } + + flecs_query_iter_set_id(it, op->field_index, ecs_childof(tgt)); + flecs_query_src_set_single(op, cur, ctx); + return true; + } + + /* Table contains multiple entities for same parent, scan */ + op_ctx->parents = parents; + op_ctx->tgt = tgt; + op_ctx->cur = range.offset; + + return flecs_query_tree_with_parent(op, redo, ctx); + } + } + + return true; +} + +static +bool flecs_query_tree_with_pre( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + if (redo) { + return false; + } + + ecs_table_range_t range = flecs_query_get_range( + op, &op->src, EcsQuerySrc, ctx); + + if (range.table->flags & EcsTableHasChildOf) { + bool result = flecs_query_with(op, redo, ctx); + if (op->match_flags & EcsTermMatchAny) { + flecs_query_iter_set_id( + ctx->it, op->field_index, ecs_childof(EcsWildcard)); + } + return result; + } + + if (range.table->flags & EcsTableHasParent) { + flecs_query_iter_set_id( + ctx->it, op->field_index, ecs_pair(EcsChildOf, EcsWildcard)); + return true; + } + + return false; +} + +static +bool flecs_query_children_select( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + ecs_query_tree_ctx_t *op_ctx = flecs_op_ctx(ctx, tree); + ecs_assert(op_ctx->tgt == 0, ECS_INTERNAL_ERROR, NULL); + ecs_iter_t *it = ctx->it; + + if (!redo) { + ecs_id_t id = flecs_query_op_get_id(op, ctx); + ecs_assert(ECS_PAIR_FIRST(id) == EcsChildOf, + ECS_INTERNAL_ERROR, NULL); + + ecs_entity_t tgt = ECS_PAIR_SECOND(id); + ecs_assert(tgt != EcsWildcard, ECS_INTERNAL_ERROR, NULL); + ecs_assert(tgt != EcsAny, ECS_INTERNAL_ERROR, NULL); + (void)tgt; + + ecs_component_record_t *cr = flecs_components_get(ctx->world, id); + if (!cr) { + return false; + } + + op_ctx->tgt = 0; + if (!(cr->flags & EcsIdOrderedChildren)) { + /* No vector with ordered children, forward to regular search. */ + op_ctx->state = EcsQueryTreeIterTables; + goto next; + } + + ecs_pair_record_t *pr = cr->pair; + ecs_assert(pr != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_vec_t *v_children = &pr->ordered_children; + uint32_t filter = flecs_ito(uint32_t, op->other); + + if ((!pr->disabled_tables || !(filter & EcsTableIsDisabled)) && + (!pr->prefab_tables || !(filter & EcsTableIsPrefab))) + { + it->entities = ecs_vec_first_t(v_children, ecs_entity_t); + it->count = ecs_vec_count(v_children); + return true; + } else { + /* Flags that we're going to iterate each entity separately because we + * need to filter out disabled entities. */ + op_ctx->state = EcsQueryTreeIterEntities; + op_ctx->entities = ecs_vec_first_t(v_children, ecs_entity_t); + op_ctx->cur = -1; + op_ctx->range.count = ecs_vec_count(v_children); + op_ctx->cr = cr; + } + } else { + if (!op_ctx->state) { + return false; + } + } + +next: + if (op_ctx->state == EcsQueryTreeIterEntities) { + int32_t cur = ++ op_ctx->cur; + if (cur >= op_ctx->range.count) { + return false; + } + + ecs_entity_t *e = &op_ctx->entities[cur]; + ecs_record_t *r = flecs_entities_get(ctx->world, *e); + ecs_assert(r != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(r->table != NULL, ECS_INTERNAL_ERROR, NULL); + + if (flecs_query_table_filter(r->table, op->other, + (EcsTableIsDisabled|EcsTableIsPrefab))) + { + /* Skip disabled/prefab entities */ + goto next; + } + + it->entities = e; + it->count = 1; + return true; + } else { + ecs_assert(op_ctx->state == EcsQueryTreeIterTables, + ECS_INTERNAL_ERROR, NULL); + return flecs_query_and(op, redo, ctx); + } +} + +static +bool flecs_query_children_with( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + if (redo) { + return false; + } + + ecs_table_range_t range = flecs_query_get_range( + op, &op->src, EcsQuerySrc, ctx); + if (range.table->flags & EcsTableHasChildOf) { + return flecs_query_and(op, redo, ctx); + } + + if (!(range.table->flags & EcsTableHasParent)) { + /* If table doesn't have ChildOf or Parent its entities don't have + * parents. */ + return false; + } + + ecs_id_t id = flecs_query_op_get_id(op, ctx); + ecs_assert(ECS_PAIR_FIRST(id) == EcsChildOf, ECS_INTERNAL_ERROR, NULL); + + ecs_entity_t tgt = ECS_PAIR_SECOND(id); + if (tgt == EcsWildcard || tgt == EcsAny) { + /* Entities in table have parents, so wildcard will always match. */ + return true; + } + + /* TODO: if a ChildOf query is constrained to a table with Parent component, + * only some entities in the table may match the query. TBD on what the + * behavior should be in this case. For now the query engine only supports + * constraining the query to a single entity or an entire table. */ + ecs_assert(range.count < 2, ECS_UNSUPPORTED, + "can only use set_var() to a single entity for ChildOf($this, parent) terms"); + + if (range.count == 0) { + /* If matching the entire table, return true. Even though not all + * entities in the table may match, this lets us add tables with the + * Parent component to query caches. */ + return true; + } + + if (flecs_query_table_filter(range.table, op->other, + EcsTableIsDisabled|EcsTableIsPrefab)) + { + return false; + } + + const EcsParent *parents = flecs_query_tree_get_parents(range); + if ((uint32_t)parents->value == tgt) { + return true; + } + + return false; +} + +bool flecs_query_children( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + uint64_t written = ctx->written[ctx->op_index]; + if (written & (1ull << op->src.var)) { + return flecs_query_children_with(op, redo, ctx); + } else { + return flecs_query_children_select(op, redo, ctx); + } +} + +bool flecs_query_tree_and( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + uint64_t written = ctx->written[ctx->op_index]; + if (written & (1ull << op->src.var)) { + return flecs_query_tree_with(op, redo, ctx); + } else { + return flecs_query_tree_select(op, redo, ctx); + } +} + +bool flecs_query_tree_and_wildcard( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + bool bulk_return) +{ + uint64_t written = ctx->written[ctx->op_index]; + if (written & (1ull << op->src.var)) { + return flecs_query_tree_with(op, redo, ctx); + } else { + if (op->match_flags & EcsTermMatchAny) { + return flecs_query_tree_select_any( + op, redo, ctx, ecs_pair(EcsChildOf, EcsWildcard)); + } else { + return flecs_query_tree_select_wildcard(op, redo, ctx, bulk_return); + } + } +} + +bool flecs_query_tree_pre( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + uint64_t written = ctx->written[ctx->op_index]; + if (written & (1ull << op->src.var)) { + return flecs_query_tree_with_pre(op, redo, ctx); + } else { + ecs_id_t id = flecs_query_op_get_id(op, ctx); + return flecs_query_tree_select_any(op, redo, ctx, id); + } +} + +bool flecs_query_tree_post( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + /* Source should have been written as this instruction can only be inserted + * after a cache instruction has been evaluated. */ + uint64_t written = ctx->written[ctx->op_index]; + ecs_assert(written & (1ull << op->src.var), ECS_INTERNAL_ERROR, NULL); + (void)written; + + ecs_table_range_t range = flecs_query_get_range( + op, &op->src, EcsQuerySrc, ctx); + + if (range.table->flags & (EcsTableHasChildOf)) { + return !redo; + } + + /* Shouldn't have gotten here if the table has neither ChildOf or Parent */ + ecs_assert(range.table->flags & EcsTableHasParent, ECS_INTERNAL_ERROR, NULL); + + return flecs_query_tree_with(op, redo, ctx); +} + +bool flecs_query_tree_up_pre( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + bool self) +{ + uint64_t written = ctx->written[ctx->op_index]; + if (flecs_ref_is_written(op, &op->src, EcsQuerySrc, written)) { + if (self) { + return flecs_query_self_up(op, redo, ctx); + } else { + return flecs_query_up(op, redo, ctx); + } + } else { + ecs_query_tree_pre_ctx_t *op_ctx = flecs_op_ctx(ctx, tree_pre); + if (!redo) { + op_ctx->state = EcsQueryTreeIterTables; + } + + if (op_ctx->state == EcsQueryTreeIterTables) { + bool result; +retry: + if (self) { + result = flecs_query_self_up(op, redo, ctx); + } else { + result = flecs_query_up(op, redo, ctx); + } + + if (!result) { + op_ctx->state = EcsQueryTreeIterEntities; + redo = false; + } else { + ecs_table_range_t range = flecs_query_get_range( + op, &op->src, EcsQuerySrc, ctx); + ecs_assert(range.table != NULL, ECS_INTERNAL_ERROR, NULL); + if (range.table->flags & EcsTableHasParent) { + /* Skip tables with Parent, since we'll yield all tables + * with Parent in the second phase. */ + redo = true; + goto retry; + } + + return true; + } + } + + bool result = flecs_query_select_w_id(op, redo, ctx, ecs_id(EcsParent), + (EcsTableNotQueryable|EcsTableIsPrefab|EcsTableIsDisabled)); + if (result) { + /* Signal this table needs post processing */ + ctx->it->sources[op->field_index] = EcsWildcard; + } + + return result; + } +} + +bool flecs_query_tree_up_post( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx, + bool self) +{ + ecs_query_tree_ctx_t *op_ctx = flecs_op_ctx(ctx, tree); + + /* Source should have been written as this instruction can only be inserted + * after a cache instruction has been evaluated. */ + uint64_t written = ctx->written[ctx->op_index]; + ecs_assert(written & (1ull << op->src.var), ECS_INTERNAL_ERROR, NULL); + (void)written; + + ecs_table_range_t range = flecs_query_get_range( + op, &op->src, EcsQuerySrc, ctx); + + /* Passthrough tables with ChildOf pair */ + if (!(range.table->flags & EcsTableHasParent)) { + return !redo; + } + + if (!redo) { + op_ctx->tgt = ctx->it->sources[op->field_index]; + } + + /* Passthrough tables that own the component */ + if (op_ctx->tgt != EcsWildcard) { + return !redo; + } + + /* Shouldn't have gotten here if the table has neither ChildOf or Parent */ + ecs_assert(range.table->flags & EcsTableHasParent, ECS_INTERNAL_ERROR, NULL); + + const ecs_term_t *term = &ctx->query->pub.terms[op->term_index]; + + if (term->oper == EcsOptional) { + if (!redo) { + if (!range.count) { + range.count = ecs_table_count(range.table); + } + + op_ctx->range = range; + op_ctx->cur = range.offset - 1; + } + + op_ctx->cur ++; + + if (op_ctx->cur >= op_ctx->range.count) { + flecs_query_src_set_range(op, &op_ctx->range, ctx); + return false; + } + + bool result = false; + + flecs_query_src_set_single(op, op_ctx->cur, ctx); + + if (self) { + result = flecs_query_self_up_with(op, false, ctx); + } else { + result = flecs_query_up_with(op, false, ctx); + } + + uint64_t field_bit = 1llu << op->field_index; + if (!result) { + ctx->it->set_fields &= (ecs_termset_t)~field_bit; + } else { + ctx->it->set_fields |= (ecs_termset_t)field_bit; + } + + return true; + } else { + if (self) { + return flecs_query_self_up_with(op, redo, ctx); + } else { + return flecs_query_up_with(op, redo, ctx); + } + } +} + /** * @file query/engine/eval.c * @brief Query engine implementation. @@ -81583,7 +86918,13 @@ bool flecs_query_up_select_table( do { bool result; - if (kind == FlecsQueryUpSelectId) { + if (ECS_PAIR_FIRST(impl->with) == EcsChildOf) { + if (impl->with == ecs_childof(EcsWildcard)) { + result = flecs_query_tree_and_wildcard(op, redo, ctx, false); + } else { + result = flecs_query_tree_and(op, redo, ctx); + } + } else if (kind == FlecsQueryUpSelectId) { result = flecs_query_select_id(op, redo, ctx, 0); } else if (kind == FlecsQueryUpSelectDefault) { result = flecs_query_select_w_id(op, redo, ctx, @@ -81605,7 +86946,7 @@ bool flecs_query_up_select_table( ecs_assert(range.table != NULL, ECS_INTERNAL_ERROR, NULL); /* Keep searching until we find a table that has the requested component, - * with traversable entities */ + * with traversable entities */ } while (!self && range.table->_->traversable_count == 0); if (!range.count) { @@ -81804,10 +87145,11 @@ bool flecs_query_up_select( ecs_trav_down_elem_t *elem = ecs_vec_get_t( &down->elems, ecs_trav_down_elem_t, impl->cache_elem); - flecs_query_var_set_range(op, op->src.var, elem->table, 0, 0, ctx); + flecs_query_var_set_range(op, op->src.var, elem->range.table, + elem->range.offset, elem->range.count, ctx); flecs_query_set_vars(op, impl->matched, ctx); - if (flecs_query_table_filter(elem->table, op->other, + if (flecs_query_table_filter(elem->range.table, op->other, (EcsTableNotQueryable|EcsTableIsPrefab|EcsTableIsDisabled))) { /* Go to next table if table contains prefabs, disabled entities or @@ -81870,30 +87212,77 @@ bool flecs_query_up_with( return false; } - /* Get entry from up traversal cache. The up traversal cache contains - * the entity on which the component was found, with additional metadata - * on where it is stored. */ - ecs_trav_up_t *up = flecs_query_get_up_cache(ctx, &impl->cache, - range.table, impl->with, impl->trav, impl->cr_with, - impl->cr_trav); + op_ctx->range = range; + if (!op_ctx->range.count) { + op_ctx->range.count = ecs_table_count(op_ctx->range.table); + } + + op_ctx->cur = -1; + + /* Handle tables with non-fragmenting ChildOf */ + if (impl->trav == EcsChildOf) { + if (range.table->flags & EcsTableHasParent) { + if (q->flags & EcsQueryNested) { + /* If this is a nested query (used to populate a cache), + * don't store entries for individual entities in the cache. + * Instead, match the entire table, and figure out from + * which parent the entity gets the component in an uncached + * operation. */ + + /* Signal that the uncached instruction needs to search. + * This helps distinguish between tables with a Parent + * component that own the component vs. those that don't. */ + it->sources[op->field_index] = EcsWildcard; + return true; + } - if (!up) { - /* Component is not reachable from table */ + /* Signals that we need to evaluate individual rows. */ + op_ctx->cur = 0; + flecs_query_src_set_single(op, range.offset, ctx); + } + } + } else { +next_row: + if (op_ctx->cur == -1) { + /* The table either can or can't reach the component, nothing to do + * for a second evaluation of this operation.*/ return false; } - it->sources[op->field_index] = flecs_entities_get_alive( - ctx->world, up->src); - it->trs[op->field_index] = up->tr; - it->ids[op->field_index] = up->id; - flecs_query_set_vars(op, up->id, ctx); - flecs_set_source_set_flag(it, op->field_index); - return true; - } else { - /* The table either can or can't reach the component, nothing to do for - * a second evaluation of this operation.*/ - return false; + /* Evaluate next row. Only necessary for non-fragmenting ChildOf since + * in that case different table rows can have different parents. */ + op_ctx->cur ++; + if (op_ctx->cur >= op_ctx->range.count) { + return false; + } + + flecs_query_src_set_single(op, op_ctx->range.offset + op_ctx->cur, ctx); } + + /* Get entry from up traversal cache. The up traversal cache contains + * the entity on which the component was found, with additional metadata + * on where it is stored. */ + ecs_trav_up_t *up = flecs_query_get_up_cache(ctx, &impl->cache, + op_ctx->range.table, op_ctx->range.offset + op_ctx->cur, impl->with, + impl->trav, impl->cr_with, impl->cr_trav); + + if (!up) { + /* Component is not reachable from table */ + goto next_row; + } + + it->sources[op->field_index] = flecs_entities_get_alive( + ctx->world, up->src); + it->trs[op->field_index] = up->tr; + it->ids[op->field_index] = up->id; + if (op->match_flags & EcsTermMatchAny) { + it->ids[op->field_index] = ecs_pair(impl->trav, EcsWildcard); + } + + flecs_query_set_vars(op, up->id, ctx); + flecs_set_source_set_flag(it, op->field_index); + + return true; } /* Check if a table can reach the target component through the traversal @@ -81901,55 +87290,78 @@ bool flecs_query_up_with( bool flecs_query_self_up_with( const ecs_query_op_t *op, bool redo, - const ecs_query_run_ctx_t *ctx, - bool id_only) + const ecs_query_run_ctx_t *ctx) { - if (!redo) { - bool result; + ecs_query_up_ctx_t *op_ctx = flecs_op_ctx(ctx, up); + ecs_query_up_impl_t *impl = op_ctx->impl; + ecs_iter_t *it = ctx->it; - ecs_iter_t *it = ctx->it; - ecs_allocator_t *a = flecs_query_get_allocator(it); - ecs_query_up_ctx_t *op_ctx = flecs_op_ctx(ctx, up); + if (!redo) { if (!op_ctx->impl) { - op_ctx->impl = flecs_calloc_t(a, ecs_query_up_impl_t); + ecs_allocator_t *a = flecs_query_get_allocator(it); + impl = op_ctx->impl = flecs_calloc_t(a, ecs_query_up_impl_t); } - if (id_only) { - /* Simple id, no wildcards */ - result = flecs_query_with_id(op, redo, ctx); - op_ctx->is.and.remaining = 1; + flecs_reset_source_set_flag(ctx->it, op->field_index); + op_ctx->cur = -1; + impl->trav = 0; + impl->with = flecs_query_op_get_id(op, ctx); + } + + /* First check if table has the component */ + if (op_ctx->impl->trav == 0) { + bool result; + ecs_id_t with = impl->with; + if (ECS_PAIR_FIRST(with) == EcsChildOf) { + if (with == ecs_childof(EcsWildcard)) { + result = flecs_query_tree_and_wildcard(op, redo, ctx, false); + } else { + result = flecs_query_tree_and(op, redo, ctx); + } } else { result = flecs_query_with(op, redo, ctx); } - flecs_reset_source_set_flag(ctx->it, op->field_index); - if (result) { - /* Table has component, no need to traverse*/ - ecs_query_up_impl_t *impl = op_ctx->impl; - ecs_assert(impl != NULL, ECS_INTERNAL_ERROR, NULL); - impl->trav = 0; + /* Table has component, no need to traverse*/ if (flecs_query_ref_flags(op->flags, EcsQuerySrc) & EcsQueryIsVar) { /* Matching self, so set sources to 0 */ it->sources[op->field_index] = 0; } return true; } + } - /* Table doesn't have component, traverse relationship */ + /* Table doesn't have component, traverse relationship */ + return flecs_query_up_with(op, redo, ctx); +} + +bool flecs_query_up( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + uint64_t written = ctx->written[ctx->op_index]; + if (flecs_ref_is_written(op, &op->src, EcsQuerySrc, written)) { return flecs_query_up_with(op, redo, ctx); } else { - ecs_query_up_ctx_t *op_ctx = flecs_op_ctx(ctx, up); - ecs_query_up_impl_t *impl = op_ctx->impl; - ecs_assert(impl != NULL, ECS_INTERNAL_ERROR, NULL); - if (impl->trav == 0) { - /* If matching components without traversing, make sure to still - * match remaining components that match the id (wildcard). */ - return flecs_query_with(op, redo, ctx); - } + return flecs_query_up_select(op, redo, ctx, + FlecsQueryUpSelectUp, FlecsQueryUpSelectDefault); } +} - return false; +bool flecs_query_self_up( + const ecs_query_op_t *op, + bool redo, + const ecs_query_run_ctx_t *ctx) +{ + uint64_t written = ctx->written[ctx->op_index]; + if (flecs_ref_is_written(op, &op->src, EcsQuerySrc, written)) { + return flecs_query_self_up_with(op, redo, ctx); + } else { + return flecs_query_up_select(op, redo, ctx, + FlecsQueryUpSelectSelfUp, FlecsQueryUpSelectDefault); + } } /** @@ -82130,26 +87542,44 @@ void flecs_query_var_set_range( }; } -void flecs_query_var_narrow_range( - ecs_var_id_t var_id, - ecs_table_t *table, - int32_t offset, - int32_t count, +void flecs_query_src_set_single( + const ecs_query_op_t *op, + int32_t row, const ecs_query_run_ctx_t *ctx) -{ - ecs_var_t *var = &ctx->vars[var_id]; +{ + if (!(op->flags & (EcsQueryIsVar << EcsQuerySrc))) { + return; + } + + ecs_var_id_t src = op->src.var; + ecs_var_t *var = &ctx->vars[src]; + + ecs_assert(var->range.table != NULL, ECS_INTERNAL_ERROR, NULL); + var->range.offset = row; + var->range.count = 1; + + var->entity = ecs_table_entities(var->range.table)[row]; +} + +void flecs_query_src_set_range( + const ecs_query_op_t *op, + const ecs_table_range_t *range, + const ecs_query_run_ctx_t *ctx) +{ + if (!(op->flags & (EcsQueryIsVar << EcsQuerySrc))) { + return; + } + + ecs_var_id_t src = op->src.var; + ecs_var_t *var = &ctx->vars[src]; var->entity = 0; - var->range = (ecs_table_range_t){ - .table = table, - .offset = offset, - .count = count - }; + ecs_assert(var->range.table == range->table, ECS_INTERNAL_ERROR, NULL); + var->range = *range; - ecs_assert(var_id < ctx->query->var_count, ECS_INTERNAL_ERROR, NULL); - if (ctx->query_vars[var_id].kind != EcsVarTable) { - ecs_assert(count == 1, ECS_INTERNAL_ERROR, NULL); - var->entity = ecs_table_entities(table)[offset]; + if (ctx->query_vars[src].kind != EcsVarTable) { + ecs_assert(range->count == 1, ECS_INTERNAL_ERROR, NULL); + var->entity = ecs_table_entities(range->table)[range->offset]; } } @@ -82514,7 +87944,7 @@ void flecs_trav_entity_down_isa( bool empty); static -ecs_trav_down_t* flecs_trav_entity_down( +void flecs_trav_entity_down( ecs_world_t *world, ecs_allocator_t *a, ecs_trav_up_cache_t *cache, @@ -82548,11 +87978,12 @@ ecs_trav_down_t* flecs_trav_table_down( ecs_trav_up_cache_t *cache, ecs_trav_down_t *dst, ecs_entity_t trav, - const ecs_table_t *table, + const ecs_table_range_t *range, ecs_component_record_t *cr_with, bool self, bool empty) { + ecs_table_t *table = range->table; ecs_assert(table->id != 0, ECS_INTERNAL_ERROR, NULL); if (!table->_->traversable_count) { @@ -82562,8 +87993,8 @@ ecs_trav_down_t* flecs_trav_table_down( ecs_assert(cr_with != NULL, ECS_INTERNAL_ERROR, NULL); const ecs_entity_t *entities = ecs_table_entities(table); - int32_t i, count = ecs_table_count(table); - for (i = 0; i < count; i ++) { + int32_t i = range->offset, end = i + range->count; + for (; i < end; i ++) { ecs_entity_t entity = entities[i]; ecs_record_t *record = flecs_entities_get(world, entity); if (!record) { @@ -82649,7 +88080,7 @@ void flecs_trav_entity_down_isa( } static -ecs_trav_down_t* flecs_trav_entity_down( +void flecs_trav_entity_down_iter_children( ecs_world_t *world, ecs_allocator_t *a, ecs_trav_up_cache_t *cache, @@ -82660,11 +88091,54 @@ ecs_trav_down_t* flecs_trav_entity_down( bool self, bool empty) { - ecs_assert(dst != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(cr_with != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(cr_trav != NULL, ECS_INTERNAL_ERROR, NULL); + (void)cache; + (void)trav; + (void)empty; - int32_t first = ecs_vec_count(&dst->elems); + ecs_vec_t *children = &cr_trav->pair->ordered_children; + int32_t i, count = ecs_vec_count(children); + ecs_entity_t *elems = ecs_vec_first(children); + + for (i = 0; i < count; i ++) { + ecs_entity_t e = elems[i]; + ecs_record_t *r = flecs_entities_get(world, e); + bool leaf = false; + + /* Check if table has the component*/ + if (flecs_component_get_table(cr_with, r->table) != NULL) { + if (self) { + /* If matching self and the table has the component, entity + * shouldn't be matched through traversal and will instead + * be matched directly.*/ + continue; + } + + leaf = true; + } + + /* Add element to the cache for a single child */ + ecs_trav_down_elem_t *elem = ecs_vec_append_t( + a, &dst->elems, ecs_trav_down_elem_t); + elem->range.table = r->table; + elem->range.offset = ECS_RECORD_TO_ROW(r->row); + elem->range.count = 1; + elem->leaf = leaf; + } +} + +static +void flecs_trav_entity_down_iter_tables( + ecs_world_t *world, + ecs_allocator_t *a, + ecs_trav_up_cache_t *cache, + ecs_trav_down_t *dst, + ecs_entity_t trav, + ecs_component_record_t *cr_trav, + ecs_component_record_t *cr_with, + bool self, + bool empty) +{ + (void)cache; ecs_table_cache_iter_t it; bool result; @@ -82708,10 +88182,39 @@ ecs_trav_down_t* flecs_trav_entity_down( ecs_trav_down_elem_t *elem = ecs_vec_append_t( a, &dst->elems, ecs_trav_down_elem_t); - elem->table = table; + elem->range.table = table; + elem->range.offset = 0; + elem->range.count = ecs_table_count(table); elem->leaf = leaf; } } +} + +static +void flecs_trav_entity_down( + ecs_world_t *world, + ecs_allocator_t *a, + ecs_trav_up_cache_t *cache, + ecs_trav_down_t *dst, + ecs_entity_t trav, + ecs_component_record_t *cr_trav, + ecs_component_record_t *cr_with, + bool self, + bool empty) +{ + ecs_assert(dst != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr_with != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(cr_trav != NULL, ECS_INTERNAL_ERROR, NULL); + + int32_t first = ecs_vec_count(&dst->elems); + + if (cr_trav->flags & EcsIdOrderedChildren) { + flecs_trav_entity_down_iter_children( + world, a, cache, dst, trav, cr_trav, cr_with, self, empty); + } else { + flecs_trav_entity_down_iter_tables( + world, a, cache, dst, trav, cr_trav, cr_with, self, empty); + } /* Breadth first walk */ int32_t t, last = ecs_vec_count(&dst->elems); @@ -82720,11 +88223,9 @@ ecs_trav_down_t* flecs_trav_entity_down( &dst->elems, ecs_trav_down_elem_t, t); if (!elem->leaf) { flecs_trav_table_down(world, a, cache, dst, trav, - elem->table, cr_with, self, empty); + &elem->range, cr_with, self, empty); } } - - return dst; } ecs_trav_down_t* flecs_query_get_down_cache( @@ -82751,8 +88252,11 @@ ecs_trav_down_t* flecs_query_get_down_cache( ecs_component_record_t *cr_trav = flecs_components_get(world, ecs_pair(trav, e)); if (!cr_trav) { if (trav != EcsIsA) { - flecs_trav_entity_down_isa( - world, a, cache, result, trav, e, cr_with, self, empty); + if (cr_with->flags & EcsIdOnInstantiateInherit) { + flecs_trav_entity_down_isa( + world, a, cache, result, trav, e, cr_with, self, empty); + } + } result->ready = true; return result; @@ -82796,10 +88300,10 @@ static ecs_trav_up_t* flecs_trav_up_ensure( const ecs_query_run_ctx_t *ctx, ecs_trav_up_cache_t *cache, - uint64_t table_id) + ecs_entity_t tgt) { ecs_trav_up_t **trav = ecs_map_ensure_ref( - &cache->src, ecs_trav_up_t, table_id); + &cache->src, ecs_trav_up_t, tgt); if (!trav[0]) { trav[0] = flecs_iter_calloc_t(ctx->it, ecs_trav_up_t); } @@ -82882,6 +88386,20 @@ ecs_trav_up_t* flecs_trav_table_up( if (flecs_trav_type_search(up, table, cr_with, &type) >= 0) { up->src = src; goto found; + } else if (ECS_PAIR_FIRST(with) == EcsChildOf) { + if (table->flags & EcsTableHasParent) { + const EcsParent *p = ecs_table_get_id( + world, table, ecs_id(EcsParent), + ECS_RECORD_TO_ROW(src_record->row)); + ecs_assert(p != NULL, ECS_INTERNAL_ERROR, NULL); + + if ((uint32_t)p->value == ECS_PAIR_SECOND(with)) { + up->src = src; + up->tr = NULL; + up->id = cr_with->id; + goto found; + } + } } } @@ -82898,9 +88416,27 @@ ecs_trav_up_t* flecs_trav_table_up( } } + if ((rel == ecs_pair(EcsChildOf, EcsWildcard) && + (flags & EcsTableHasParent))) + { + const EcsParent *p = ecs_table_get_id( + world, table, ecs_id(EcsParent), + ECS_RECORD_TO_ROW(src_record->row)); + ecs_assert(p != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_trav_up_t *up_parent = flecs_trav_table_up(ctx, a, cache, + world, p->value, with, rel, cr_with, cr_trav); + if (up_parent->tr) { + up->src = up_parent->src; + up->tr = up_parent->tr; + up->id = up_parent->id; + goto found; + } + } + ecs_trav_up_t up_pair = {0}; int32_t r_column = flecs_trav_type_search( - &up_pair, table, cr_trav, &type); + &up_pair, table, cr_trav, &type); while (r_column != -1) { ecs_entity_t tgt = ECS_PAIR_SECOND(up_pair.id); @@ -82954,6 +88490,7 @@ ecs_trav_up_t* flecs_query_get_up_cache( const ecs_query_run_ctx_t *ctx, ecs_trav_up_cache_t *cache, ecs_table_t *table, + int32_t row, ecs_id_t with, ecs_entity_t trav, ecs_component_record_t *cr_with, @@ -82973,6 +88510,30 @@ ecs_trav_up_t* flecs_query_get_up_cache( ecs_assert(cr_with != NULL, ECS_INTERNAL_ERROR, NULL); ecs_assert(cr_trav != NULL, ECS_INTERNAL_ERROR, NULL); + + if (trav == EcsChildOf) { + if (table->flags & EcsTableHasParent) { + ecs_assert(row != -1, ECS_INTERNAL_ERROR, NULL); + + const EcsParent *p = flecs_query_tree_get_parents((ecs_table_range_t){ + .table = table, + .offset = row, + .count = 1 + }); + ecs_assert(p != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_entity_t tgt = (uint32_t)p->value; + ecs_trav_up_t *result = flecs_trav_table_up(ctx, a, cache, world, tgt, + with, ecs_pair(trav, EcsWildcard), cr_with, cr_trav); + ecs_assert(result != NULL, ECS_INTERNAL_ERROR, NULL); + if (result->src != 0) { + return result; + } + + return NULL; + } + } + ecs_table_record_t *tr = ecs_table_cache_get(&cr_trav->cache, table); if (!tr) { return NULL; /* Table doesn't have the relationship */ @@ -83259,7 +88820,24 @@ void flecs_set_array(ecs_iter_t *it) { continue; } + if (!ecs_is_alive(world, elem_type)) { + ecs_err("array '%s' has invalid element type", ecs_get_name(world, e)); + continue; + } + + flecs_meta_detect_cycles(world, elem_type, e); + const EcsComponent *elem_ptr = ecs_get(world, elem_type, EcsComponent); + if (!elem_ptr) { + ecs_err("array '%s' has invalid element type", ecs_get_name(world, e)); + continue; + } + + if (!ecs_get_type_info(world, elem_type)) { + ecs_err("array '%s' element type has no type info", ecs_get_name(world, e)); + continue; + } + if (flecs_init_type(world, e, EcsArrayType, elem_ptr->size * elem_count, elem_ptr->alignment)) { @@ -83283,6 +88861,21 @@ void flecs_set_vector(ecs_iter_t *it) { continue; } + if (!ecs_is_alive(world, elem_type)) { + ecs_err("vector '%s' has invalid element type", ecs_get_name(world, e)); + continue; + } + + if (!ecs_get(world, elem_type, EcsComponent)) { + ecs_err("vector '%s' has invalid element type", ecs_get_name(world, e)); + continue; + } + + if (!ecs_get_type_info(world, elem_type)) { + ecs_err("vector '%s' element type has no type info", ecs_get_name(world, e)); + continue; + } + if (flecs_init_type_t(world, e, EcsVectorType, ecs_vec_t)) { continue; } @@ -83354,17 +88947,17 @@ void flecs_meta_array_init( }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsArray) }, .events = {EcsOnSet}, - .callback = flecs_set_array + .callback = flecs_set_array, + .global_observer = true }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsVector) }, .events = {EcsOnSet}, - .callback = flecs_set_vector + .callback = flecs_set_vector, + .global_observer = true }); } @@ -83998,31 +89591,31 @@ void flecs_meta_enum_init( ecs_add_pair(world, ecs_id(EcsBitmask), EcsWith, ecs_id(EcsConstants)); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsEnum) }, .events = {EcsOnSet}, - .callback = flecs_add_enum + .callback = flecs_add_enum, + .global_observer = true }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsBitmask) }, .events = {EcsOnAdd}, - .callback = flecs_add_bitmask + .callback = flecs_add_bitmask, + .global_observer = true }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = EcsConstant }, .events = {EcsOnAdd}, - .callback = flecs_add_constant + .callback = flecs_add_constant, + .global_observer = true }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_pair(EcsConstant, EcsWildcard) }, .events = {EcsOnSet}, - .callback = flecs_add_constant + .callback = flecs_add_constant, + .global_observer = true }); ecs_set(world, ecs_id(EcsEnum), EcsDefaultChildComponent, {EcsConstant}); @@ -84111,10 +89704,10 @@ void flecs_meta_opaque_init( }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsOpaque) }, .events = {EcsOnSet}, - .callback = flecs_set_opaque_type + .callback = flecs_set_opaque_type, + .global_observer = true }); } @@ -84628,24 +90221,29 @@ void flecs_meta_primitives_init( }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsPrimitive) }, .events = {EcsOnSet}, - .callback = flecs_set_primitive + .callback = flecs_set_primitive, + .global_observer = true }); /* Initialize primitive types */ - #define ECS_PRIMITIVE(world, type, primitive_kind)\ - ecs_entity_init(world, &(ecs_entity_desc_t){\ - .id = ecs_id(ecs_##type##_t),\ - .name = #type,\ - .symbol = #type });\ - ecs_set(world, ecs_id(ecs_##type##_t), EcsPrimitive, {\ + #define ECS_PRIMITIVE(world, T, primitive_kind)\ + ecs_component_init(world, &(ecs_component_desc_t){\ + .entity = ecs_entity(world, {\ + .id = ecs_id(ecs_##T##_t),\ + .name = #T,\ + .symbol = #T \ + }),\ + .type.size = ECS_SIZEOF(ecs_##T##_t),\ + .type.alignment = ECS_ALIGNOF(ecs_##T##_t),\ + });\ + ecs_set(world, ecs_id(ecs_##T##_t), EcsPrimitive, {\ .kind = primitive_kind\ });\ - ecs_set_hooks(world, ecs_##type##_t, { \ - .cmp = flecs_compare_##type, \ - .equals = flecs_equals_##type \ + ecs_set_hooks(world, ecs_##T##_t, { \ + .cmp = flecs_compare_##T, \ + .equals = flecs_equals_##T \ }) ECS_PRIMITIVE(world, bool, EcsBool); @@ -84724,70 +90322,63 @@ static void flecs_set_struct_member( ecs_member_t *member, ecs_entity_t entity, - const char *name, - ecs_entity_t type, - int32_t count, - int32_t offset, - ecs_entity_t unit, - EcsMemberRanges *ranges) + ecs_member_t *m, + ecs_entity_t unit) { member->member = entity; - member->type = type; - member->count = count; + member->type = m->type; + member->count = m->count; member->unit = unit; - member->offset = offset; + member->offset = m->offset; - ecs_os_strset(ECS_CONST_CAST(char**, &member->name), name); + ecs_os_strset(ECS_CONST_CAST(char**, &member->name), m->name); - if (ranges) { - member->range = ranges->value; - member->error_range = ranges->error; - member->warning_range = ranges->warning; - } else { - ecs_os_zeromem(&member->range); - ecs_os_zeromem(&member->error_range); - ecs_os_zeromem(&member->warning_range); - } + member->range = m->range; + member->error_range = m->error_range; + member->warning_range = m->warning_range; } static int flecs_add_member_to_struct( ecs_world_t *world, - ecs_entity_t type, - ecs_entity_t member, - EcsMember *m, - EcsMemberRanges *ranges) + ecs_entity_t struct_type, + ecs_entity_t member_entity, + const ecs_member_t *m_ptr) { ecs_assert(world != NULL, ECS_INTERNAL_ERROR, NULL); - ecs_assert(type != 0, ECS_INTERNAL_ERROR, NULL); - ecs_assert(member != 0, ECS_INTERNAL_ERROR, NULL); - ecs_assert(m != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_assert(struct_type != 0, ECS_INTERNAL_ERROR, NULL); + ecs_assert(m_ptr != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_member_t m = *m_ptr; + const char *name = m.name; - const char *name = ecs_get_name(world, member); if (!name) { - char *path = ecs_get_path(world, type); + char *path = ecs_get_path(world, struct_type); ecs_err("member for struct '%s' does not have a name", path); ecs_os_free(path); return -1; } - if (!m->type) { - char *path = ecs_get_path(world, member); - ecs_err("member '%s' does not have a type", path); + if (!m.type) { + char *path = ecs_get_path(world, struct_type); + ecs_err("member '%s.%s' does not have a type", path, name); ecs_os_free(path); return -1; } - if (ecs_get_typeid(world, m->type) == 0) { - char *path = ecs_get_path(world, member); - char *ent_path = ecs_get_path(world, m->type); - ecs_err("member '%s.type' is '%s' which is not a type", path, ent_path); + flecs_meta_detect_cycles(world, m.type, struct_type); + + if (ecs_get_typeid(world, m.type) == 0) { + char *path = ecs_get_path(world, struct_type); + char *ent_path = ecs_get_path(world, m.type); + ecs_err("member '%s.%s.type' is '%s' which is not a type", + path, name, ent_path); ecs_os_free(path); ecs_os_free(ent_path); return -1; } - ecs_entity_t unit = m->unit; + ecs_entity_t unit = m.unit; if (unit) { if (!ecs_has(world, unit, EcsUnit)) { ecs_err("entity '%s' for member '%s' is not a unit", @@ -84795,51 +90386,66 @@ int flecs_add_member_to_struct( return -1; } - if (ecs_has(world, m->type, EcsUnit) && m->type != unit) { + if (ecs_has(world, m.type, EcsUnit) && m.type != unit) { ecs_err("unit mismatch for type '%s' and unit '%s' for member '%s'", - ecs_get_name(world, m->type), ecs_get_name(world, unit), name); + ecs_get_name(world, m.type), ecs_get_name(world, unit), name); return -1; } } else { - if (ecs_has(world, m->type, EcsUnit)) { + if (ecs_has(world, m.type, EcsUnit)) { ecs_entity_t unit_base = ecs_get_target_for( - world, m->type, EcsIsA, EcsUnit); + world, m.type, EcsIsA, EcsUnit); if (unit_base) { - unit = m->unit = unit_base; + unit = m.unit = unit_base; } else { - unit = m->unit = m->type; + unit = m.unit = m.type; + } + + if (member_entity) { + ecs_assert(ecs_owns(world, member_entity, EcsMember), + ECS_INTERNAL_ERROR, NULL); + ecs_get_mut(world, member_entity, EcsMember)->unit = m.type; } } } - EcsStruct *s = ecs_ensure(world, type, EcsStruct); + EcsStruct *s = ecs_ensure(world, struct_type, EcsStruct); ecs_assert(s != NULL, ECS_INTERNAL_ERROR, NULL); /* First check if member is already added to struct */ ecs_member_t *members = ecs_vec_first_t(&s->members, ecs_member_t); int32_t i, count = ecs_vec_count(&s->members); + + bool has_member = false; for (i = 0; i < count; i ++) { - if (members[i].member == member) { - flecs_set_struct_member(&members[i], member, name, m->type, - m->count, m->offset, unit, ranges); - break; + if (member_entity && members[i].member) { + if (members[i].member == member_entity) { + flecs_set_struct_member(&members[i], member_entity, &m, unit); + break; + } + } else { + if (!ecs_os_strcmp(name, members[i].name)) { + flecs_set_struct_member(&members[i], member_entity, &m, unit); + break; + } } } + has_member = i != count; + /* If member wasn't added yet, add a new element to vector */ - if (i == count) { + if (!has_member) { ecs_vec_init_if_t(&s->members, ecs_member_t); ecs_member_t *elem = ecs_vec_append_t(NULL, &s->members, ecs_member_t); elem->name = NULL; - flecs_set_struct_member(elem, member, name, m->type, - m->count, m->offset, unit, ranges); + flecs_set_struct_member(elem, member_entity, &m, unit); /* Reobtain members array in case it was reallocated */ members = ecs_vec_first_t(&s->members, ecs_member_t); count ++; } - bool explicit_offset = m->offset || m->use_offset; + bool explicit_offset = m.offset || m.use_offset; /* Compute member offsets and size & alignment of struct */ ecs_size_t size = 0; @@ -84877,11 +90483,10 @@ int flecs_add_member_to_struct( elem->offset = size; /* Synchronize offset with Member component */ - if (elem->member == member) { - m->offset = elem->offset; - } else { - EcsMember *other = ecs_ensure(world, elem->member, EcsMember); - other->offset = elem->offset; + if (elem->member) { + EcsMember *member_data = ecs_ensure( + world, elem->member, EcsMember); + member_data->offset = elem->offset; } size += member_size; @@ -84925,7 +90530,7 @@ int flecs_add_member_to_struct( elem->size = member_size; size = elem->offset + member_size; - const EcsComponent* comp = ecs_get(world, type, EcsComponent); + const EcsComponent* comp = ecs_get(world, struct_type, EcsComponent); if (comp) { alignment = comp->alignment; } else { @@ -84934,39 +90539,69 @@ int flecs_add_member_to_struct( } if (size == 0) { - ecs_err("struct '%s' has 0 size", ecs_get_name(world, type)); + ecs_err("struct '%s' has 0 size", ecs_get_name(world, struct_type)); return -1; } if (alignment == 0) { - ecs_err("struct '%s' has 0 alignment", ecs_get_name(world, type)); + ecs_err("struct '%s' has 0 alignment", ecs_get_name(world, struct_type)); return -1; } /* Align struct size to struct alignment */ size = ECS_ALIGN(size, alignment); - ecs_modified(world, type, EcsStruct); + ecs_modified(world, struct_type, EcsStruct); /* Do this last as it triggers the update of EcsTypeSerializer */ - if (flecs_init_type(world, type, EcsStructType, size, alignment)) { + if (flecs_init_type(world, struct_type, EcsStructType, size, alignment)) { return -1; } /* If current struct is also a member, assign to itself */ - if (ecs_has(world, type, EcsMember)) { - EcsMember *type_mbr = ecs_ensure(world, type, EcsMember); + if (ecs_has(world, struct_type, EcsMember)) { + EcsMember *type_mbr = ecs_ensure(world, struct_type, EcsMember); ecs_assert(type_mbr != NULL, ECS_INTERNAL_ERROR, NULL); - type_mbr->type = type; + type_mbr->type = struct_type; type_mbr->count = 0; - ecs_modified(world, type, EcsMember); + ecs_modified(world, struct_type, EcsMember); } return 0; } +static +void flecs_set_member_from_component( + ecs_world_t *world, + ecs_entity_t e, + EcsMember *member, + EcsMemberRanges *ranges) +{ + ecs_entity_t struct_type = ecs_get_parent(world, e); + if (!struct_type) { + ecs_err("missing parent for member '%s'", ecs_get_name(world, e)); + return; + } + + ecs_member_t m = { + .name = ecs_get_name(world, e), + .type = member->type, + .count = member->count, + .offset = member->offset, + .unit = member->unit + }; + + if (ranges) { + m.range = ranges->value; + m.error_range = ranges->error; + m.warning_range = ranges->warning; + } + + flecs_add_member_to_struct(world, struct_type, e, &m); +} + static void flecs_set_member(ecs_iter_t *it) { ecs_world_t *world = it->world; @@ -84976,15 +90611,8 @@ void flecs_set_member(ecs_iter_t *it) { int i, count = it->count; for (i = 0; i < count; i ++) { - ecs_entity_t e = it->entities[i]; - ecs_entity_t parent = ecs_get_target(world, e, EcsChildOf, 0); - if (!parent) { - ecs_err("missing parent for member '%s'", ecs_get_name(world, e)); - continue; - } - - flecs_add_member_to_struct(world, parent, e, &member[i], - ranges ? &ranges[i] : NULL); + flecs_set_member_from_component(world, it->entities[i], + &member[i], ranges ? &ranges[i] : NULL); } } @@ -85000,15 +90628,8 @@ void flecs_set_member_ranges(ecs_iter_t *it) { int i, count = it->count; for (i = 0; i < count; i ++) { - ecs_entity_t e = it->entities[i]; - ecs_entity_t parent = ecs_get_target(world, e, EcsChildOf, 0); - if (!parent) { - ecs_err("missing parent for member '%s'", ecs_get_name(world, e)); - continue; - } - - flecs_add_member_to_struct(world, parent, e, &member[i], - &ranges[i]); + flecs_set_member_from_component(world, it->entities[i], + &member[i], &ranges[i]); } } @@ -85071,6 +90692,105 @@ bool flecs_type_is_number( } } +static +int flecs_member_validate_ranges( + ecs_world_t *world, + ecs_entity_t type, + const ecs_member_t *member, + bool *ranges_set_out) +{ + const ecs_member_value_range_t *range = &member->range; + const ecs_member_value_range_t *error = &member->error_range; + const ecs_member_value_range_t *warning = &member->warning_range; + bool ranges_set = false; + + if (ECS_NEQ(range->min, range->max)) { + ranges_set = true; + if (range->min > range->max) { + ecs_err("member '%s.%s' has an invalid value range [%f..%f]", + flecs_errstr(ecs_get_path(world, type)), member->name, + range->min, range->max); + goto error; + } + } + + if (ECS_NEQ(error->min, error->max)) { + ranges_set = true; + if (error->min > error->max) { + ecs_err("member '%s.%s' has an invalid error range [%f..%f]", + flecs_errstr(ecs_get_path(world, type)), member->name, + error->min, error->max); + goto error; + } + + if (flecs_member_range_overlaps(error, range)) { + ecs_err("error range of member '%s.%s' overlaps with value range", + flecs_errstr(ecs_get_path(world, type)), member->name); + goto error; + } + } + + if (ECS_NEQ(warning->min, warning->max)) { + ranges_set = true; + if (warning->min > warning->max) { + ecs_err("member '%s.%s' has an invalid warning range [%f..%f]", + flecs_errstr(ecs_get_path(world, type)), member->name, + warning->min, warning->max); + goto error; + } + + if (flecs_member_range_overlaps(warning, range)) { + ecs_err("warning range of member '%s.%s' overlaps with value range", + flecs_errstr(ecs_get_path(world, type)), member->name); + goto error; + } + + if (flecs_member_range_overlaps(warning, error)) { + ecs_err("warning range of member '%s.%s' overlaps with error range", + flecs_errstr(ecs_get_path(world, type)), member->name); + goto error; + } + } + + if (ranges_set && !flecs_type_is_number(world, member->type)) { + ecs_err("member '%s.%s' has an value/error/warning range, but is " + "not a number", + flecs_errstr(ecs_get_path(world, type)), member->name); + goto error; + } + + *ranges_set_out = ranges_set; + + return 0; +error: + return -1; +} + +static +void flecs_struct_create_member_entity( + ecs_world_t *world, + ecs_entity_t type, + const ecs_member_t *member, + bool set_ranges) +{ + ecs_entity_t member_entity = ecs_new_from_path(world, type, member->name); + + ecs_set(world, member_entity, EcsMember, { + .type = member->type, + .count = member->count, + .offset = member->offset, + .unit = member->unit + }); + + if (set_ranges) { + ecs_set(world, member_entity, EcsMemberRanges, { + .value = member->range, + .error = member->error_range, + .warning = member->warning_range + }); + } +} + ecs_entity_t ecs_struct_init( ecs_world_t *world, const ecs_struct_desc_t *desc) @@ -85078,114 +90798,43 @@ ecs_entity_t ecs_struct_init( ecs_suspend_readonly_state_t rs; world = flecs_suspend_readonly(world, &rs); - ecs_entity_t t = desc->entity; - if (!t) { - t = ecs_new_low_id(world); + ecs_entity_t type = desc->entity; + if (!type) { + type = ecs_new_low_id(world); } - ecs_entity_t old_scope = ecs_set_scope(world, t); + ecs_entity_t old_scope = ecs_set_scope(world, type); int i; for (i = 0; i < ECS_MEMBER_DESC_CACHE_SIZE; i ++) { const ecs_member_t *m_desc = &desc->members[i]; - if (!m_desc->type) { + if (!m_desc->name) { break; } - if (!m_desc->name) { - ecs_err("member %d of struct '%s' does not have a name", i, - ecs_get_name(world, t)); + if (!m_desc->type) { + ecs_err("member '%s' of struct '%s' does not have a type", + m_desc->name, ecs_get_name(world, type)); goto error; } - ecs_entity_t m = ecs_new_from_path(world, t, m_desc->name); - - ecs_set(world, m, EcsMember, { - .type = m_desc->type, - .count = m_desc->count, - .offset = m_desc->offset, - .unit = m_desc->unit, - .use_offset = m_desc->use_offset - }); + ecs_member_t member = *m_desc; + bool ranges_set = false; + bool create_member_entity = desc->create_member_entities; - EcsMemberRanges *ranges = NULL; - const ecs_member_value_range_t *range = &m_desc->range; - const ecs_member_value_range_t *error = &m_desc->error_range; - const ecs_member_value_range_t *warning = &m_desc->warning_range; - if (ECS_NEQ(range->min, range->max)) { - ranges = ecs_ensure(world, m, EcsMemberRanges); - if (range->min > range->max) { - char *member_name = ecs_get_path(world, m); - ecs_err("member '%s' has an invalid value range [%f..%f]", - member_name, range->min, range->max); - ecs_os_free(member_name); - goto error; - } - ranges->value.min = range->min; - ranges->value.max = range->max; - } - if (ECS_NEQ(error->min, error->max)) { - if (error->min > error->max) { - char *member_name = ecs_get_path(world, m); - ecs_err("member '%s' has an invalid error range [%f..%f]", - member_name, error->min, error->max); - ecs_os_free(member_name); - goto error; - } - if (flecs_member_range_overlaps(error, range)) { - char *member_name = ecs_get_path(world, m); - ecs_err("error range of member '%s' overlaps with value range", - member_name); - ecs_os_free(member_name); - goto error; - } - if (!ranges) { - ranges = ecs_ensure(world, m, EcsMemberRanges); - } - ranges->error.min = error->min; - ranges->error.max = error->max; +#ifdef FLECS_CREATE_MEMBER_ENTITIES + create_member_entity = true; +#endif + if (flecs_member_validate_ranges(world, type, &member, &ranges_set)) { + goto error; } - if (ECS_NEQ(warning->min, warning->max)) { - if (warning->min > warning->max) { - char *member_name = ecs_get_path(world, m); - ecs_err("member '%s' has an invalid warning range [%f..%f]", - member_name, warning->min, warning->max); - ecs_os_free(member_name); + if (!create_member_entity) { + if (flecs_add_member_to_struct(world, type, 0, &member)) { goto error; } - if (flecs_member_range_overlaps(warning, range)) { - char *member_name = ecs_get_path(world, m); - ecs_err("warning range of member '%s' overlaps with value " - "range", member_name); - ecs_os_free(member_name); - goto error; - } - if (flecs_member_range_overlaps(warning, error)) { - char *member_name = ecs_get_path(world, m); - ecs_err("warning range of member '%s' overlaps with error " - "range", member_name); - ecs_os_free(member_name); - goto error; - } - - if (!ranges) { - ranges = ecs_ensure(world, m, EcsMemberRanges); - } - ranges->warning.min = warning->min; - ranges->warning.max = warning->max; - } - - if (ranges && !flecs_type_is_number(world, m_desc->type)) { - char *member_name = ecs_get_path(world, m); - ecs_err("member '%s' has an value/error/warning range, but is not a " - "number", member_name); - ecs_os_free(member_name); - goto error; - } - - if (ranges) { - ecs_modified(world, m, EcsMemberRanges); + } else { + flecs_struct_create_member_entity(world, type, &member, ranges_set); } } @@ -85193,21 +90842,87 @@ ecs_entity_t ecs_struct_init( flecs_resume_readonly(world, &rs); if (i == 0) { - ecs_err("struct '%s' has no members", ecs_get_name(world, t)); + EcsStruct *s = ecs_ensure(world, type, EcsStruct); + ecs_assert(s != NULL, ECS_INTERNAL_ERROR, NULL); + ecs_vec_init_t(NULL, &s->members, ecs_member_t, 0); + ecs_modified(world, type, EcsStruct); + } else if (!ecs_has(world, type, EcsStruct)) { goto error; } - if (!ecs_has(world, t, EcsStruct)) { + return type; +error: + flecs_resume_readonly(world, &rs); + if (type) { + ecs_delete(world, type); + } + return 0; +} + +int ecs_struct_add_member( + ecs_world_t *world, + ecs_entity_t type, + const ecs_member_t *member) +{ + flecs_stage_from_world(&world); + + bool ranges_set; + if (flecs_member_validate_ranges(world, type, member, &ranges_set)) { goto error; } - return t; -error: - flecs_resume_readonly(world, &rs); - if (t) { - ecs_delete(world, t); +#ifdef FLECS_CREATE_MEMBER_ENTITIES + flecs_struct_create_member_entity(world, type, member, ranges_set); +#else + if (flecs_add_member_to_struct(world, type, 0, member)) { + goto error; } +#endif + return 0; +error: + return -1; +} + +ecs_member_t* ecs_struct_get_member( + ecs_world_t *world, + ecs_entity_t type, + const char *name) +{ + const EcsStruct *s = ecs_get(world, type, EcsStruct); + if (!s) { + return NULL; + } + + ecs_member_t *members = ecs_vec_first(&s->members); + int32_t i, count = ecs_vec_count(&s->members); + + for (i = 0; i < count; i ++) { + if (!ecs_os_strcmp(members[i].name, name)) { + return &members[i]; + } + } + + return NULL; +} + +ecs_member_t* ecs_struct_get_nth_member( + ecs_world_t *world, + ecs_entity_t type, + int32_t i) +{ + const EcsStruct *s = ecs_get(world, type, EcsStruct); + if (!s) { + return NULL; + } + + ecs_member_t *members = ecs_vec_first(&s->members); + int32_t count = ecs_vec_count(&s->members); + if (i >= count) { + return NULL; + } + + return &members[i]; } void flecs_meta_struct_init( @@ -85256,20 +90971,21 @@ void flecs_meta_struct_init( }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsMember) }, .events = {EcsOnSet}, - .callback = flecs_set_member + .callback = flecs_set_member, + .global_observer = true }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsMemberRanges) }, .events = {EcsOnSet}, - .callback = flecs_set_member_ranges + .callback = flecs_set_member_ranges, + .global_observer = true }); ecs_set(world, ecs_id(EcsStruct), EcsDefaultChildComponent, {ecs_id(EcsMember)}); + ecs_add_pair(world, ecs_id(EcsStruct), EcsWith, ecs_id(EcsComponent)); ecs_set(world, ecs_id(EcsMember), EcsDefaultChildComponent, {ecs_id(EcsMember)}); } @@ -85631,20 +91347,20 @@ void flecs_meta_units_init( ecs_add_id(world, EcsQuantity, EcsPairIsTag); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms[0] = { .id = ecs_id(EcsUnit) }, .events = {EcsOnSet}, - .callback = flecs_set_unit + .callback = flecs_set_unit, + .global_observer = true }); ecs_observer(world, { - .entity = ecs_entity(world, { .parent = EcsFlecsInternals }), .query.terms = { { .id = ecs_id(EcsUnit) }, { .id = EcsQuantity } }, .events = { EcsMonitor }, - .callback = flecs_unit_quantity_monitor + .callback = flecs_unit_quantity_monitor, + .global_observer = true }); @@ -85707,6 +91423,20 @@ ecs_expr_variable_t* flecs_expr_variable_from( return result; } +ecs_expr_member_t* flecs_expr_member_from( + ecs_script_t *script, + ecs_expr_node_t *node, + const char *name) +{ + ecs_expr_member_t *result = flecs_calloc_t( + &flecs_script_impl(script)->allocator, ecs_expr_member_t); + result->node.kind = EcsExprMember; + result->node.pos = node->pos; + result->left = node; + result->member_name =name; + return result; +} + ecs_expr_value_node_t* flecs_expr_bool( ecs_parser_t *parser, bool value) @@ -85731,6 +91461,8 @@ ecs_expr_value_node_t* flecs_expr_char( char ch = 0; const char *ptr = flecs_chrparse(value, &ch); if(!ptr) { + flecs_free_t( + &parser->script->allocator, ecs_expr_value_node_t, result); return NULL; } result->storage.char_ = ch; @@ -85788,6 +91520,7 @@ ecs_expr_value_node_t* flecs_expr_string( result->node.type = ecs_id(ecs_string_t); if (!flecs_string_escape(str)) { + flecs_free_t(&parser->script->allocator, ecs_expr_value_node_t, result); return NULL; } @@ -86289,6 +92022,38 @@ const char* flecs_script_parse_collection_initializer( ParserEnd; } +static +const char* flecs_script_parse_function( + ecs_parser_t *parser, + const char *pos, + ecs_expr_node_t **out) +{ + ecs_expr_function_t *result = flecs_expr_function(parser); + result->left = *out; + + pos = flecs_script_parse_initializer( + parser, pos, ')', &result->args); + if (!pos) { + goto error; + } + + *out = (ecs_expr_node_t*)result; + + if (pos[0] != ')') { + Error("expected end of argument list"); + } + + pos ++; + + return pos; +error: + if (result->args) { + flecs_script_parser_expr_free(parser, (ecs_expr_node_t*)result->args); + } + flecs_free_t(&parser->script->allocator, ecs_expr_function_t, result); + return NULL; +} + static const char* flecs_script_parse_rhs( ecs_parser_t *parser, @@ -86331,7 +92096,6 @@ const char* flecs_script_parse_rhs( case EcsTokShiftRight: case EcsTokBracketOpen: case EcsTokMember: - case EcsTokParenOpen: { ecs_token_kind_t oper = lookahead_token.kind; @@ -86364,34 +92128,25 @@ const char* flecs_script_parse_rhs( } case EcsTokMember: { - Parse_1(EcsTokIdentifier, { - ecs_expr_member_t *result = flecs_expr_member(parser); - result->left = *out; - result->member_name = Token(1); - *out = (ecs_expr_node_t*)result; - break; - }); - - break; - } - - case EcsTokParenOpen: { - ecs_expr_function_t *result = flecs_expr_function(parser); - result->left = *out; - - pos = flecs_script_parse_initializer( - parser, pos, ')', &result->args); - if (!pos) { - goto error; - } - - *out = (ecs_expr_node_t*)result; + Parse( + case EcsTokFunction: + case EcsTokIdentifier: { + ecs_expr_member_t *result = flecs_expr_member(parser); + result->left = *out; + result->member_name = Token(1); + *out = (ecs_expr_node_t*)result; + + if(t->kind == EcsTokFunction) { + pos = flecs_script_parse_function(parser, pos, out); + if (!pos) { + goto error; + } + } - if (pos[0] != ')') { - Error("expected end of argument list"); - } + break; + } + ); - pos ++; break; } @@ -86441,19 +92196,38 @@ const char* flecs_script_parse_lhs( Parse( case EcsTokNumber: { const char *expr = Token(0); - if (strchr(expr, '.') || strchr(expr, 'e')) { - *out = (ecs_expr_node_t*)flecs_expr_float(parser, atof(expr)); - break; - } int base = 10; - if (expr[0] == '0' && (expr[1] == 'x' || expr[1] == 'X')) { + bool is_negative = false; + const char *base_expr = expr; + if (base_expr[0] == '-') { + is_negative = true; + base_expr ++; + } + + if (base_expr[0] == '0' && (base_expr[1] == 'x' || base_expr[1] == 'X')) { base = 16; - expr += 2; - } else if (expr[0] == '0' && (expr[1] == 'b' || expr[1] == 'B')) { + } else if (base_expr[0] == '0' && (base_expr[1] == 'b' || base_expr[1] == 'B')) { base = 2; - expr += 2; } - if (expr[0] == '-') { + + if (base == 10 && + (strchr(expr, '.') || strchr(expr, 'e') || strchr(expr, 'E'))) + { + *out = (ecs_expr_node_t*)flecs_expr_float(parser, atof(expr)); + break; + } + + if (base == 2) { + const char *bin_expr = base_expr + 2; + char *end; + uint64_t v = strtoull(bin_expr, &end, base); + + if (is_negative) { + *out = (ecs_expr_node_t*)flecs_expr_int(parser, -(int64_t)v); + } else { + *out = (ecs_expr_node_t*)flecs_expr_uint(parser, v); + } + } else if (is_negative) { char *end; *out = (ecs_expr_node_t*)flecs_expr_int(parser, strtoll(expr, &end, base)); @@ -86480,7 +92254,8 @@ const char* flecs_script_parse_lhs( break; } - case EcsTokIdentifier: { + case EcsTokIdentifier: + case EcsTokFunction: { const char *expr = Token(0); if (expr[0] == '$') { *out = (ecs_expr_node_t*)flecs_expr_variable(parser, &expr[1]); @@ -86502,6 +92277,14 @@ const char* flecs_script_parse_lhs( *out = (ecs_expr_node_t*)flecs_expr_identifier(parser, expr); } } + + if(t->kind == EcsTokFunction) { + pos = flecs_script_parse_function(parser, pos, out); + if (!pos) { + goto error; + } + } + break; } @@ -86569,14 +92352,21 @@ const char* flecs_script_parse_lhs( int32_t stmt_count = ecs_vec_count(&parser->scope->stmts); + bool old_function_token = parser->function_token; + bool old_significant_newline = parser->significant_newline; + parser->function_token = false; + parser->significant_newline = true; pos = flecs_script_stmt(parser, pos); if (!pos) { + parser->significant_newline = old_significant_newline; goto error; } + parser->function_token = old_function_token; + parser->significant_newline = old_significant_newline; pos = flecs_parse_ws_eol(pos); - if ((stmt_count - ecs_vec_count(&parser->scope->stmts)) > 1) { + if ((ecs_vec_count(&parser->scope->stmts) - stmt_count) != 1) { Error("expected entity statement after new"); } @@ -86622,13 +92412,13 @@ const char* flecs_script_parse_lhs( goto error; } + *out = (ecs_expr_node_t*)node; + Parse_1('}', { break; }) can_have_rhs = false; - - *out = (ecs_expr_node_t*)node; break; } @@ -86641,14 +92431,13 @@ const char* flecs_script_parse_lhs( } node->is_collection = true; + *out = (ecs_expr_node_t*)node; Parse_1(']', { break; }) can_have_rhs = false; - - *out = (ecs_expr_node_t*)node; break; } ) @@ -86673,13 +92462,34 @@ const char* flecs_script_parse_expr( ecs_token_kind_t left_oper, ecs_expr_node_t **out) { - ParserBegin; + if (parser->expr_depth >= ECS_PARSER_MAX_RECURSION_DEPTH) { + ecs_parser_error(parser->name, parser->code, pos - parser->code, + "maximum expression nesting depth exceeded"); + return NULL; + } - pos = flecs_script_parse_lhs(parser, pos, tokenizer, left_oper, out); + parser->expr_depth ++; - EndOfRule; + ecs_tokenizer_t _tokenizer; + ecs_os_zeromem(&_tokenizer); + _tokenizer.tokens = _tokenizer.stack.tokens; + ecs_tokenizer_t *tokenizer = &_tokenizer; - ParserEnd; + bool old_function_token = parser->function_token; + parser->function_token = true; + pos = flecs_script_parse_lhs(parser, pos, tokenizer, left_oper, out); + parser->function_token = old_function_token; + if (!pos) { + parser->expr_depth --; + if (out && *out) { + flecs_script_parser_expr_free(parser, *out); + *out = NULL; + } + return NULL; + } + + parser->expr_depth --; + return pos; } ecs_script_t* ecs_expr_parse( @@ -86704,13 +92514,15 @@ ecs_script_t* ecs_expr_parse( .code = script->code, .script = impl, .scope = impl->root, - .significant_newline = false + .significant_newline = false, + .function_token = true }; impl->token_buffer_size = ecs_os_strlen(expr) * 2 + 1; impl->token_buffer = flecs_alloc_w_dbg_info( &impl->allocator, impl->token_buffer_size, "token buffer"); parser.token_cur = impl->token_buffer; + parser.token_end = &impl->token_buffer[impl->token_buffer_size]; const char *ptr = flecs_script_parse_expr(&parser, expr, 0, &impl->expr); if (!ptr) { @@ -86724,7 +92536,7 @@ ecs_script_t* ecs_expr_parse( goto error; } - //printf("%s\n", ecs_script_ast_to_str(script, true)); + // printf("%s\n", ecs_script_ast_to_str(script, true)); if (!desc || !desc->disable_folding) { if (flecs_expr_visit_fold(script, &impl->expr, &priv_desc)) { @@ -86732,7 +92544,7 @@ ecs_script_t* ecs_expr_parse( } } - //printf("%s\n", ecs_script_ast_to_str(script, true)); + // printf("%s\n", ecs_script_ast_to_str(script, true)); return script; error: @@ -86857,9 +92669,7 @@ void flecs_expr_value_alloc( v->value.type = ti->component; v->value.ptr = flecs_stack_alloc(&stack->stack, ti->size, ti->alignment); - if (ti->hooks.ctor) { - ti->hooks.ctor(v->value.ptr, 1, ti); - } + flecs_type_info_ctor(v->value.ptr, 1, ti); } static @@ -86877,7 +92687,7 @@ void flecs_expr_value_free( if (ti && ti->hooks.dtor) { ecs_assert(v->value.ptr != NULL, ECS_INTERNAL_ERROR, NULL); - ti->hooks.dtor(v->value.ptr, 1, ti); + flecs_type_info_dtor(v->value.ptr, 1, ti); flecs_stack_free(v->value.ptr, ti->size); } @@ -87271,6 +93081,7 @@ int flecs_value_binary( case EcsTokMatch: case EcsTokRange: case EcsTokIdentifier: + case EcsTokFunction: case EcsTokString: case EcsTokChar: case EcsTokNumber: @@ -87485,13 +93296,40 @@ int flecs_expr_initializer_eval( ecs_script_eval_ctx_t *ctx, ecs_expr_initializer_t *node, void *value, - ecs_meta_cursor_t *cur); + ecs_meta_cursor_t *cur, + ecs_size_t value_size); + +int flecs_expr_initializer_validate_assign( + const ecs_script_t *script, + ecs_expr_initializer_t *node, + ecs_expr_initializer_element_t *elem, + ecs_entity_t type, + ecs_size_t value_size) +{ + const ecs_type_info_t *ti = ecs_get_type_info(script->world, type); + ecs_assert(ti != NULL, ECS_INTERNAL_ERROR, NULL); + + uintptr_t offset = elem->offset; + uintptr_t type_size = flecs_uto(uintptr_t, ti->size); + uintptr_t dst_size = flecs_uto(uintptr_t, value_size); + if (offset > dst_size || type_size > (dst_size - offset)) { + flecs_expr_visit_error(script, node, + "initializer of type '%s' writes past end of target value", + flecs_errstr(ecs_get_path(script->world, type))); + goto error; + } + + return 0; +error: + return -1; +} static int flecs_expr_initializer_eval_static( ecs_script_eval_ctx_t *ctx, ecs_expr_initializer_t *node, - void *value) + void *value, + ecs_size_t value_size) { flecs_expr_stack_push(ctx->stack); @@ -87499,10 +93337,11 @@ int flecs_expr_initializer_eval_static( int32_t i, count = ecs_vec_count(&node->elements); for (i = 0; i < count; i ++) { ecs_expr_initializer_element_t *elem = &elems[i]; + ecs_assert(elem->value != NULL, ECS_INTERNAL_ERROR, NULL); if (elem->value->kind == EcsExprInitializer) { if (flecs_expr_initializer_eval(ctx, - (ecs_expr_initializer_t*)elem->value, value, NULL)) + (ecs_expr_initializer_t*)elem->value, value, NULL, value_size)) { goto error; } @@ -87517,6 +93356,11 @@ int flecs_expr_initializer_eval_static( /* Type is guaranteed to be correct, since type visitor will insert * a cast to the type of the initializer element. */ ecs_entity_t type = elem->value->type; + if (flecs_expr_initializer_validate_assign( + ctx->script, node, elem, type, value_size)) + { + goto error; + } if (!elem->operator) { if (expr->owned) { @@ -87558,8 +93402,11 @@ int flecs_expr_initializer_eval_dynamic( ecs_script_eval_ctx_t *ctx, ecs_expr_initializer_t *node, void *value, - ecs_meta_cursor_t *cur) + ecs_meta_cursor_t *cur, + ecs_size_t value_size) { + (void)value_size; + flecs_expr_stack_push(ctx->stack); ecs_meta_cursor_t local_cur; @@ -87577,6 +93424,7 @@ int flecs_expr_initializer_eval_dynamic( ecs_expr_initializer_element_t *elems = ecs_vec_first(&node->elements); for (i = 0; i < count; i ++) { ecs_expr_initializer_element_t *elem = &elems[i]; + ecs_assert(elem->value != NULL, ECS_INTERNAL_ERROR, NULL); if (i) { ecs_meta_next(cur); @@ -87584,7 +93432,7 @@ int flecs_expr_initializer_eval_dynamic( if (elem->value->kind == EcsExprInitializer) { if (flecs_expr_initializer_eval(ctx, - (ecs_expr_initializer_t*)elem->value, value, cur)) + (ecs_expr_initializer_t*)elem->value, value, cur, value_size)) { goto error; } @@ -87626,12 +93474,14 @@ int flecs_expr_initializer_eval( ecs_script_eval_ctx_t *ctx, ecs_expr_initializer_t *node, void *value, - ecs_meta_cursor_t *cur) + ecs_meta_cursor_t *cur, + ecs_size_t value_size) { if (node->is_dynamic) { - return flecs_expr_initializer_eval_dynamic(ctx, node, value, cur); + return flecs_expr_initializer_eval_dynamic( + ctx, node, value, cur, value_size); } else { - return flecs_expr_initializer_eval_static(ctx, node, value); + return flecs_expr_initializer_eval_static(ctx, node, value, value_size); } } @@ -87642,7 +93492,13 @@ int flecs_expr_initializer_visit_eval( ecs_expr_value_t *out) { out->owned = true; - return flecs_expr_initializer_eval(ctx, node, out->value.ptr, NULL); + + const ecs_type_info_t *ti = ecs_get_type_info( + ctx->world, node->node.type); + ecs_assert(ti != NULL, ECS_INTERNAL_ERROR, NULL); + + return flecs_expr_initializer_eval( + ctx, node, out->value.ptr, NULL, ti->size); } static @@ -87714,10 +93570,36 @@ int flecs_expr_binary_visit_eval( goto error; } - if (flecs_value_binary( - ctx->script, &left->value, &right->value, &out->value, node->operator)) - { - goto error; + int32_t i, vector_count = node->vector_count; + if (!vector_count) { + if (flecs_value_binary( + ctx->script, &left->value, &right->value, &out->value, node->operator)) + { + goto error; + } + } else { + ecs_entity_t vector_type = node->vector_type; + ecs_value_t left_value = { .ptr = left->value.ptr, .type = vector_type }; + ecs_value_t right_value = { .ptr = right->value.ptr, .type = vector_type }; + ecs_value_t out_value = { .ptr = out->value.ptr, .type = vector_type }; + ecs_size_t size = flecs_expr_storage_size(vector_type); + ecs_size_t right_offset = 0; + + if (left->value.type == right->value.type) { + right_offset = size; + } + + for (i = 0; i < vector_count; i ++) { + if (flecs_value_binary(ctx->script, &left_value, &right_value, + &out_value, node->operator)) + { + goto error; + } + + left_value.ptr = ECS_OFFSET(left_value.ptr, size); + right_value.ptr = ECS_OFFSET(right_value.ptr, right_offset); + out_value.ptr = ECS_OFFSET(out_value.ptr, size); + } } flecs_expr_stack_pop(ctx->stack); @@ -88012,10 +93894,12 @@ int flecs_expr_function_visit_eval( { flecs_expr_stack_push(ctx->stack); + const ecs_function_calldata_t *calldata = &node->calldata; + ecs_function_ctx_t call_ctx = { .world = ctx->world, - .function = node->calldata.function, - .ctx = node->calldata.ctx + .function = calldata->function, + .ctx = calldata->ctx }; ecs_assert(out->value.ptr != NULL, ECS_INTERNAL_ERROR, NULL); @@ -88029,7 +93913,14 @@ int flecs_expr_function_visit_eval( } } - node->calldata.callback(&call_ctx, argc, argv, &out->value); + int32_t elem_count = calldata->vector_elem_count; + if (elem_count) { + node->calldata.is.vector_callback( + &call_ctx, argc, argv, &out->value, elem_count); + } else { + node->calldata.is.callback(&call_ctx, argc, argv, &out->value); + } + out->owned = true; flecs_expr_stack_pop(ctx->stack); @@ -88053,10 +93944,12 @@ int flecs_expr_method_visit_eval( goto error; } + const ecs_function_calldata_t *calldata = &node->calldata; + ecs_function_ctx_t call_ctx = { .world = ctx->world, - .function = node->calldata.function, - .ctx = node->calldata.ctx + .function = calldata->function, + .ctx = calldata->ctx }; ecs_assert(expr->value.ptr != NULL, ECS_INTERNAL_ERROR, NULL); @@ -88074,7 +93967,14 @@ int flecs_expr_method_visit_eval( } } - node->calldata.callback(&call_ctx, argc, argv, &out->value); + int32_t elem_count = calldata->vector_elem_count; + if (elem_count) { + node->calldata.is.vector_callback( + &call_ctx, argc, argv, &out->value, elem_count); + } else { + node->calldata.is.callback(&call_ctx, argc, argv, &out->value); + } + out->owned = true; } @@ -88768,6 +94668,7 @@ int flecs_expr_initializer_pre_fold( int32_t i, count = ecs_vec_count(&node->elements); for (i = 0; i < count; i ++) { ecs_expr_initializer_element_t *elem = &elems[i]; + ecs_assert(elem->value != NULL, ECS_INTERNAL_ERROR, NULL); /* If this is a nested initializer, don't fold it but instead fold its * values. Because nested initializers are flattened, this ensures that @@ -88808,27 +94709,40 @@ static int flecs_expr_initializer_post_fold( ecs_script_t *script, ecs_expr_initializer_t *node, - void *value) + void *value, + ecs_size_t value_size) { ecs_expr_initializer_element_t *elems = ecs_vec_first(&node->elements); int32_t i, count = ecs_vec_count(&node->elements); for (i = 0; i < count; i ++) { ecs_expr_initializer_element_t *elem = &elems[i]; + ecs_assert(elem->value != NULL, ECS_INTERNAL_ERROR, NULL); if (elem->value->kind == EcsExprInitializer) { if (flecs_expr_initializer_post_fold( - script, (ecs_expr_initializer_t*)elem->value, value)) + script, (ecs_expr_initializer_t*)elem->value, value, value_size)) { goto error; } continue; } + if (elem->value->kind != EcsExprValue) { + flecs_expr_visit_error(script, node, + "expected value for initializer element"); + goto error; + } + ecs_expr_value_node_t *elem_value = (ecs_expr_value_node_t*)elem->value; /* Type is guaranteed to be correct, since type visitor will insert * a cast to the type of the initializer element. */ ecs_entity_t type = elem_value->node.type; + if (flecs_expr_initializer_validate_assign( + script, node, elem, type, value_size)) + { + goto error; + } if (ecs_value_copy(script->world, type, ECS_OFFSET(value, elem->offset), elem_value->ptr)) @@ -88849,6 +94763,7 @@ int flecs_expr_initializer_visit_fold( const ecs_expr_eval_desc_t *desc) { bool can_fold = true; + void *value = NULL; ecs_expr_initializer_t *node = (ecs_expr_initializer_t*)*node_ptr; @@ -88859,21 +94774,30 @@ int flecs_expr_initializer_visit_fold( /* If all elements of initializer fold to literals, initializer itself can * be folded into a literal. */ if (can_fold) { - void *value = ecs_value_new(script->world, node->node.type); + value = ecs_value_new(script->world, node->node.type); + const ecs_type_info_t *type_info = ecs_get_type_info( + script->world, node->node.type); + ecs_assert(type_info != NULL, ECS_INTERNAL_ERROR, NULL); - if (flecs_expr_initializer_post_fold(script, node, value)) { + if (flecs_expr_initializer_post_fold( + script, node, value, type_info->size)) + { goto error; } ecs_expr_value_node_t *result = flecs_expr_value_from( script, (ecs_expr_node_t*)node, node->node.type); result->ptr = value; + value = NULL; flecs_visit_fold_replace(script, node_ptr, (ecs_expr_node_t*)result); } return 0; error: + if (value) { + ecs_value_free(script->world, node->node.type, value); + } return -1; } @@ -89962,6 +95886,37 @@ ecs_size_t flecs_expr_storage_score( else return false; } +/** Returns the storage size for primitive type */ +ecs_size_t flecs_expr_storage_size( + ecs_entity_t type) +{ + if (type == ecs_id(ecs_bool_t)) return ECS_SIZEOF(ecs_bool_t); + else if (type == ecs_id(ecs_char_t)) return ECS_SIZEOF(ecs_char_t); + + /* Unsigned integers have a larger storage size than signed integers, since + * the unsigned range of a signed integer is smaller. */ + else if (type == ecs_id(ecs_u8_t)) return ECS_SIZEOF(ecs_u8_t); + else if (type == ecs_id(ecs_u16_t)) return ECS_SIZEOF(ecs_u16_t); + else if (type == ecs_id(ecs_u32_t)) return ECS_SIZEOF(ecs_u32_t); + else if (type == ecs_id(ecs_uptr_t)) return ECS_SIZEOF(ecs_uptr_t); + else if (type == ecs_id(ecs_u64_t)) return ECS_SIZEOF(ecs_u64_t); + + else if (type == ecs_id(ecs_i8_t)) return ECS_SIZEOF(ecs_i8_t); + else if (type == ecs_id(ecs_i16_t)) return ECS_SIZEOF(ecs_i16_t); + else if (type == ecs_id(ecs_i32_t)) return ECS_SIZEOF(ecs_i32_t); + else if (type == ecs_id(ecs_iptr_t)) return ECS_SIZEOF(ecs_iptr_t); + else if (type == ecs_id(ecs_i64_t)) return ECS_SIZEOF(ecs_i64_t); + + /* Floating points have a smaller storage score, since the largest integer + * that can be represented exactly is lower than the actual storage size. */ + else if (type == ecs_id(ecs_f32_t)) return ECS_SIZEOF(ecs_f32_t); + else if (type == ecs_id(ecs_f64_t)) return ECS_SIZEOF(ecs_f64_t); + + else if (type == ecs_id(ecs_string_t)) return ECS_SIZEOF(ecs_string_t); + else if (type == ecs_id(ecs_entity_t)) return ECS_SIZEOF(ecs_entity_t); + else return false; +} + /* This function returns true if an type can be casted without changing the * precision of the value. It is used to determine a type for operands in a * binary expression in case they are of different types. */ @@ -90120,6 +96075,7 @@ bool flecs_expr_oper_valid_for_type( case EcsTokMatch: case EcsTokRange: case EcsTokIdentifier: + case EcsTokFunction: case EcsTokChar: case EcsTokString: case EcsTokNumber: @@ -90142,6 +96098,40 @@ bool flecs_expr_oper_valid_for_type( } } +static +int32_t flecs_script_get_vector_type_data( + ecs_world_t *world, + ecs_entity_t type, + ecs_entity_t *vector_type_out) +{ + const EcsStruct *stype = ecs_get(world, type, EcsStruct); + if (!stype) { + return 0; + } + + ecs_entity_t vector_type = 0; + ecs_member_t *members = ecs_vec_first(&stype->members); + int32_t i, count = ecs_vec_count(&stype->members); + for (i = 0; i < count; i ++) { + ecs_member_t *member = &members[i]; + if (!i) { + if (!ecs_owns(world, member->type, EcsPrimitive)) { + /* Only primitive types can be used in vector ops */ + return 0; + } + + vector_type = member->type; + } else if (member->type != vector_type) { + /* Only structs with members of the same type can be used as vector */ + return 0; + } + } + + *vector_type_out = vector_type; + + return count; +} + static int flecs_expr_type_for_operator( ecs_script_t *script, @@ -90151,7 +96141,8 @@ int flecs_expr_type_for_operator( ecs_expr_node_t *right, ecs_token_kind_t operator, ecs_entity_t *operand_type, - ecs_entity_t *result_type) + ecs_entity_t *result_type, + int32_t *vector_elem_count) { ecs_world_t *world = script->world; @@ -90232,6 +96223,7 @@ int flecs_expr_type_for_operator( case EcsTokMatch: case EcsTokRange: case EcsTokIdentifier: + case EcsTokFunction: case EcsTokChar: case EcsTokString: case EcsTokNumber: @@ -90261,10 +96253,11 @@ int flecs_expr_type_for_operator( goto done; } - const EcsPrimitive *ltype_ptr = ecs_get(world, left->type, EcsPrimitive); + ecs_entity_t left_type = left->type; + const EcsPrimitive *ltype_ptr = ecs_get(world, left_type, EcsPrimitive); const EcsPrimitive *rtype_ptr = ecs_get(world, right->type, EcsPrimitive); if (!ltype_ptr || !rtype_ptr) { - if (ecs_get(world, left->type, EcsBitmask) != NULL) { + if (ecs_get(world, left_type, EcsBitmask) != NULL) { *operand_type = ecs_id(ecs_u32_t); goto done; } @@ -90275,7 +96268,7 @@ int flecs_expr_type_for_operator( } { - const EcsEnum *ptr = ecs_get(script->world, left->type, EcsEnum); + const EcsEnum *ptr = ecs_get(script->world, left_type, EcsEnum); if (ptr) { *operand_type = ptr->underlying_type; goto done; @@ -90290,25 +96283,59 @@ int flecs_expr_type_for_operator( } } - char *lname = ecs_get_path(world, left->type); - char *rname = ecs_get_path(world, right->type); + if (!ltype_ptr) { + ecs_entity_t vector_type = 0; + int32_t elem_count = flecs_script_get_vector_type_data( + world, left_type, &vector_type); + if (elem_count) { + /* For vector operations the right operand type must be either a + * primitive type or the same type as the left operand. */ + if (!rtype_ptr && (left_type != right->type)) { + flecs_expr_visit_error(script, node, + "invalid types for binary expression (%s, %s)", + flecs_errstr(ecs_get_path(world, left->type)), + flecs_errstr_1(ecs_get_path(world, right->type))); + goto error; + } + + /* This is a binary vector operation, check if it's allowed */ + if (!vector_elem_count) { + flecs_expr_visit_error(script, node, + "binary vector operation is not allowed here (%s, %s)", + flecs_errstr(ecs_get_path(world, left->type)), + flecs_errstr_1(ecs_get_path(world, right->type))); + goto error; + } + + *result_type = left_type; + *operand_type = vector_type; + *vector_elem_count = elem_count; + goto done; + } + } + flecs_expr_visit_error(script, node, - "invalid non-primitive type in expression (%s, %s)", - lname, rname); - ecs_os_free(lname); - ecs_os_free(rname); + "invalid types for binary expression (%s, %s)", + flecs_errstr(ecs_get_path(world, left->type)), + flecs_errstr_1(ecs_get_path(world, right->type))) goto error; } /* If left and right type are the same, do nothing */ - if (left->type == right->type) { + if (left_type == right->type) { *operand_type = left->type; goto done; } /* If types are not the same, find the smallest type for literals that can * represent the value without losing precision. */ - ecs_entity_t ltype = flecs_expr_narrow_type(node_type, left); + ecs_entity_t ltype; + if (left_type == left->type) { /* If this is not a vector type */ + ltype = flecs_expr_narrow_type(node_type, left); + } else { + ltype = left_type; + } + ecs_entity_t rtype = flecs_expr_narrow_type(node_type, right); /* If types are not the same, try to implicitly cast to expression type */ @@ -90422,11 +96449,12 @@ int flecs_expr_type_for_binary_expr( ecs_script_t *script, ecs_expr_binary_t *node, ecs_entity_t *operand_type, - ecs_entity_t *result_type) + ecs_entity_t *result_type, + int32_t *vector_elem_count) { return flecs_expr_type_for_operator(script, (ecs_expr_node_t*)node, node->node.type, node->left, node->right, node->operator, - operand_type, result_type); + operand_type, result_type, vector_elem_count); } static @@ -90485,10 +96513,13 @@ int flecs_expr_interpolated_string_visit_type( ecs_script_impl_t *impl = flecs_script_impl(script); ecs_parser_t parser = { + .name = script->name, + .code = script->code, .script = impl, .scope = impl->root, .significant_newline = false, - .token_cur = impl->token_remaining + .token_cur = impl->token_remaining, + .token_end = &impl->token_buffer[impl->token_buffer_size] }; ptr = ECS_CONST_CAST(char*, flecs_script_parse_expr( @@ -90715,6 +96746,12 @@ int flecs_expr_initializer_visit_type( } ecs_expr_initializer_element_t *elem = &elems[i]; + if (!elem->value) { + flecs_expr_visit_error(script, node, + "missing value for initializer element"); + goto error; + } + if (elem->member) { if (ecs_meta_dotmember(cur, elem->member)) { /* x: */ flecs_expr_visit_error(script, node, "cannot resolve member"); @@ -90828,6 +96865,9 @@ int flecs_expr_binary_visit_type( /* Resulting type of binary expression */ ecs_entity_t result_type = 0; + /* Number of elements in vector, if vector operation */ + int32_t vector_elem_count = 0; + if (cur->valid) { /* Provides a hint to the type visitor. The lvalue type will be used to * reduce the number of casts where possible. */ @@ -90845,39 +96885,65 @@ int flecs_expr_binary_visit_type( goto error; } - if (flecs_expr_visit_type_priv(script, node->right, cur, desc)) { + if (!node->left || !node->right) { + flecs_expr_visit_error(script, node, "invalid binary expression"); goto error; } - if (flecs_expr_type_for_binary_expr( - script, node, &operand_type, &result_type)) - { + ecs_meta_cursor_t right_cur = *cur; + if (node->right->kind == EcsExprIdentifier) { + if (ecs_get(script->world, node->left->type, EcsEnum) != NULL) { + /* If the left hand side is an enum, interpret untyped identifiers + * on the right hand side as enum constants of the same type. */ + right_cur = ecs_meta_cursor(script->world, node->left->type, NULL); + } + } + + if (flecs_expr_visit_type_priv(script, node->right, &right_cur, desc)) { goto error; } - if (!flecs_expr_oper_valid_for_type( - script->world, result_type, node->operator)) + if (flecs_expr_type_for_binary_expr( + script, node, &operand_type, &result_type, &vector_elem_count)) { - char *type_str = ecs_get_path(script->world, result_type); - flecs_expr_visit_error(script, node, "invalid operator %s for type '%s'", - flecs_token_str(node->operator), type_str); - ecs_os_free(type_str); goto error; } - if (operand_type != node->left->type) { - node->left = (ecs_expr_node_t*)flecs_expr_cast( - script, node->left, operand_type); - if (!node->left) { + if (!vector_elem_count) { + if (!flecs_expr_oper_valid_for_type( + script->world, result_type, node->operator)) + { + char *type_str = ecs_get_path(script->world, result_type); + flecs_expr_visit_error(script, node, "invalid operator %s for type '%s'", + flecs_token_str(node->operator), type_str); + ecs_os_free(type_str); goto error; } + + if (operand_type != node->left->type) { + node->left = (ecs_expr_node_t*)flecs_expr_cast( + script, node->left, operand_type); + if (!node->left) { + goto error; + } + } + + node->vector_type = 0; + node->vector_count = 0; + } else { + node->vector_type = operand_type; + node->vector_count = vector_elem_count; } if (operand_type != node->right->type) { - node->right = (ecs_expr_node_t*)flecs_expr_cast( - script, node->right, operand_type); - if (!node->right) { - goto error; + if (!vector_elem_count || (node->right->type != node->left->type)) { + /* If this is a vector operation between the same types, don't try + * to cast the right hand to the vector type. */ + node->right = (ecs_expr_node_t*)flecs_expr_cast( + script, node->right, operand_type); + if (!node->right) { + goto error; + } } } @@ -90911,6 +96977,78 @@ int flecs_expr_constant_identifier_visit_type( return -1; } +static +bool flecs_expr_is_entity_type( + ecs_world_t *world, + ecs_entity_t type, + bool *is_opaque) +{ + *is_opaque = false; + if (type == ecs_id(ecs_entity_t) || type == ecs_id(ecs_id_t)) { + return true; + } + + const EcsPrimitive *p = ecs_get(world, type, EcsPrimitive); + if (p) { + return p->kind == EcsEntity || p->kind == EcsId; + } + + const EcsOpaque *o = ecs_get(world, type, EcsOpaque); + if (o) { + *is_opaque = true; + bool dummy; + return flecs_expr_is_entity_type(world, o->as_type, &dummy); + } + + return false; +} + +static +int flecs_expr_identifier_variable_member_visit_type( + ecs_script_t *script, + ecs_expr_identifier_t *node, + const ecs_expr_eval_desc_t *desc) +{ + char *member_sep = strchr(node->value, '.'); + while (member_sep) { + if (member_sep != node->value && member_sep[-1] == '\\') { + member_sep = strchr(member_sep + 1, '.'); + continue; + } + break; + } + + if (!member_sep) { + return 1; + } + + member_sep[0] = '\0'; + + if (!flecs_script_find_var(desc->vars, node->value, NULL)) { + member_sep[0] = '.'; + return 1; + } + + ecs_expr_variable_t *var_node = flecs_expr_variable_from( + script, (ecs_expr_node_t*)node, node->value); + ecs_expr_member_t *member_node = flecs_expr_member_from( + script, (ecs_expr_node_t*)var_node, &member_sep[1]); + + node->expr = (ecs_expr_node_t*)member_node; + + ecs_meta_cursor_t tmp_cur; ecs_os_zeromem(&tmp_cur); + if (flecs_expr_visit_type_priv(script, node->expr, &tmp_cur, desc)) { + goto error; + } + + node->node.type = node->expr->type; + return 0; +error: + flecs_expr_visit_free(script, node->expr); + node->expr = NULL; + return -1; +} + static int flecs_expr_identifier_visit_type( ecs_script_t *script, @@ -90953,11 +97091,10 @@ int flecs_expr_identifier_visit_type( global = ecs_get(script->world, e, EcsScriptConstVar); } if (!global) { + bool is_opaque = false; if (!type) { type = ecs_id(ecs_entity_t); - } else if (type != ecs_id(ecs_id_t) && - type != ecs_id(ecs_entity_t)) - { + } else if (!flecs_expr_is_entity_type(script->world, type, &is_opaque)) { char *type_str = ecs_get_path(script->world, type); flecs_expr_visit_error(script, node, "cannot cast identifier '%s' to %s", @@ -90968,8 +97105,23 @@ int flecs_expr_identifier_visit_type( ecs_expr_value_node_t *result = flecs_expr_value_from( script, (ecs_expr_node_t*)node, type); - result->storage.entity = e; - result->ptr = &result->storage.entity; + + if (!is_opaque) { + result->storage.entity = e; + result->ptr = &result->storage.entity; + } else { + ecs_size_t size = flecs_type_size(script->world, type); + ecs_assert(size > 0, ECS_INTERNAL_ERROR, NULL); + result->ptr = flecs_walloc(script->world, size); + + ecs_meta_cursor_t expr_cur = ecs_meta_cursor( + script->world, type, result->ptr); + if (ecs_meta_set_entity(&expr_cur, e)) { + flecs_expr_visit_free(script, (ecs_expr_node_t*)result); + goto error; + } + } + node->expr = (ecs_expr_node_t*)result; node->node.type = type; } else { @@ -91009,6 +97161,14 @@ int flecs_expr_identifier_visit_type( return 0; } + int var_member_result = flecs_expr_identifier_variable_member_visit_type( + script, node, desc); + if (var_member_result == 0) { + return 0; + } else if (var_member_result == -1) { + goto error; + } + /* If unresolved identifiers aren't allowed here, throw error */ if (!desc->allow_unresolved_identifiers) { flecs_expr_visit_error(script, node, @@ -91110,43 +97270,217 @@ int flecs_expr_arguments_visit_type( ecs_script_t *script, ecs_expr_initializer_t *node, const ecs_expr_eval_desc_t *desc, - const ecs_vec_t *param_vec) + const struct ecs_script_function_t *func_data, + ecs_entity_t *vector_type_out) { + ecs_script_parameter_t *params = ecs_vec_first(&func_data->params); ecs_expr_initializer_element_t *elems = ecs_vec_first(&node->elements); int32_t i, count = ecs_vec_count(&node->elements); - - if (count != ecs_vec_count(param_vec)) { - flecs_expr_visit_error(script, node, "expected %d arguments, got %d", - ecs_vec_count(param_vec), count); - goto error; - } - - ecs_script_parameter_t *params = ecs_vec_first(param_vec); + ecs_entity_t vector_type = 0; for (i = 0; i < count; i ++) { ecs_expr_initializer_element_t *elem = &elems[i]; + if (!elem->value) { + flecs_expr_visit_error(script, node, + "missing value for function argument"); + goto error; + } - ecs_meta_cursor_t cur = ecs_meta_cursor( - script->world, params[i].type, NULL); + ecs_entity_t argtype = params[i].type; - if (flecs_expr_visit_type_priv(script, elem->value, &cur, desc)){ - goto error; + if (argtype != EcsScriptVectorType) { + ecs_meta_cursor_t cur = ecs_meta_cursor( + script->world, argtype, NULL); + + if (flecs_expr_visit_type_priv(script, elem->value, &cur, desc)){ + goto error; + } + } else { + ecs_meta_cursor_t cur; + ecs_os_zeromem(&cur); + + if (flecs_expr_visit_type_priv(script, elem->value, &cur, desc)){ + goto error; + } + + if (!vector_type) { + vector_type = elem->value->type; + } + + argtype = vector_type; + + /* Check if function provides implementation for type if argument + * is of a primitive type. If it doesn't, try to cast. */ + const EcsPrimitive *p = ecs_get( + script->world, argtype, EcsPrimitive); + if (p) { + if (!func_data->vector_callbacks[p->kind]) { + /* Fallback to types with max expressiveness */ + if (func_data->vector_callbacks[EcsF64]) { + vector_type = argtype = ecs_id(ecs_f64_t); + } else if (func_data->vector_callbacks[EcsI64]) { + vector_type = argtype = ecs_id(ecs_i64_t); + } else if (func_data->vector_callbacks[EcsU64]) { + vector_type = argtype = ecs_id(ecs_u64_t); + } else { + /* No matching implementation. Error will be caught + * later in the code. */ + } + } + } } - if (elem->value->type != params[i].type) { + if (elem->value->type != argtype) { elem->value = (ecs_expr_node_t*)flecs_expr_cast( - script, elem->value, params[i].type); + script, elem->value, argtype); if (!elem->value) { goto error; } } } + *vector_type_out = vector_type; + return 0; error: return -1; } +static +int flecs_expr_populate_primitive_vector_calldata( + ecs_script_t *script, + ecs_expr_function_t *node, + const struct ecs_script_function_t *func_data, + ecs_entity_t vector_type, + ecs_entity_t elem_type, + int32_t count) +{ + ecs_world_t *world = script->world; + const EcsPrimitive *ptype = ecs_get(world, elem_type, EcsPrimitive); + if (!ptype) { + flecs_expr_visit_error(script, node, + "type '%s' cannot be passed to vector argument of " + "function '%s': (member) type '%s' is not a primitive type", + flecs_errstr(ecs_get_path(world, vector_type)), + node->function_name, + flecs_errstr(ecs_get_path(world, elem_type))); + goto error; + } + + ecs_vector_function_callback_t cb = func_data->vector_callbacks[ptype->kind]; + if (!cb) { + flecs_expr_visit_error(script, node, "function '%s' does not implement " + "matching vector operation for type '%s'", + node->function_name, + flecs_errstr(ecs_get_path(script->world, elem_type))); + goto error; + } + + node->calldata.is.vector_callback = cb; + node->calldata.vector_elem_count = count; + + return 0; +error: + return -1; +} + +static +int flecs_expr_populate_struct_vector_calldata( + ecs_script_t *script, + ecs_expr_function_t *node, + const struct ecs_script_function_t *func_data, + ecs_entity_t vector_type) +{ + ecs_world_t *world = script->world; + const EcsStruct *type = ecs_get(world, vector_type, EcsStruct); + ecs_assert(type != NULL, ECS_INTERNAL_ERROR, NULL); + + ecs_entity_t elem_type = 0; + ecs_member_t *members = ecs_vec_first(&type->members); + int32_t i, count = ecs_vec_count(&type->members); + for (i = 0; i < count; i ++) { + ecs_member_t *m = &members[i]; + if (!i) { + elem_type = m->type; + } else { + if (m->type != elem_type) { + flecs_expr_visit_error(script, node, + "type '%s' cannot be passed to vector argument of " + "function '%s': all its members must be of the same type", + flecs_errstr(ecs_get_path(world, vector_type)), + node->function_name); + goto error; + } + } + } + + return flecs_expr_populate_primitive_vector_calldata( + script, node, func_data, vector_type, elem_type, count); +error: + return -1; +} + +static +int flecs_expr_populate_array_vector_calldata( + ecs_script_t *script, + ecs_expr_function_t *node, + const struct ecs_script_function_t *func_data, + ecs_entity_t vector_type) +{ + const EcsArray *type = ecs_get(script->world, vector_type, EcsArray); + ecs_assert(type != NULL, ECS_INTERNAL_ERROR, NULL); + + return flecs_expr_populate_primitive_vector_calldata( + script, node, func_data, vector_type, type->type, type->count); +} + +static +int flecs_expr_populate_vector_vector_calldata( + ecs_script_t *script, + ecs_expr_function_t *node, + const struct ecs_script_function_t *func_data, + ecs_entity_t vector_type) +{ + const EcsVector *type = ecs_get(script->world, vector_type, EcsVector); + ecs_assert(type != NULL, ECS_INTERNAL_ERROR, NULL); + + return flecs_expr_populate_primitive_vector_calldata( + script, node, func_data, vector_type, type->type, -1); +} + +static +int flecs_expr_populate_vector_calldata( + ecs_script_t *script, + ecs_expr_function_t *node, + const struct ecs_script_function_t *func_data, + ecs_entity_t vector_type) +{ + ecs_world_t *world = script->world; + const EcsType *type = ecs_get(world, vector_type, EcsType); + ecs_assert(type != NULL, ECS_INTERNAL_ERROR, NULL); + + if (type->kind == EcsPrimitiveType) { + return flecs_expr_populate_primitive_vector_calldata( + script, node, func_data, vector_type, vector_type, 1); + } else if (type->kind == EcsStructType) { + return flecs_expr_populate_struct_vector_calldata( + script, node, func_data, vector_type); + } else if (type->kind == EcsArrayType) { + return flecs_expr_populate_array_vector_calldata( + script, node, func_data, vector_type); + } else if (type->kind == EcsVectorType) { + return flecs_expr_populate_vector_vector_calldata( + script, node, func_data, vector_type); + } + + flecs_expr_visit_error(script, node, + "type '%s' cannot be passed to vector argument of function '%s'", + flecs_errstr(ecs_get_path(world, vector_type)), + node->function_name); + + return -1; +} + static int flecs_expr_function_visit_type( ecs_script_t *script, @@ -91201,6 +97535,7 @@ int flecs_expr_function_visit_type( ecs_world_t *world = script->world; const ecs_vec_t *params = NULL; + const struct ecs_script_function_t *func_data = NULL; /* If this is a method, lookup function entity in scope of type */ if (is_method) { @@ -91223,8 +97558,7 @@ int flecs_expr_function_visit_type( goto error; } - const EcsScriptMethod *func_data = ecs_get( - world, func, EcsScriptMethod); + func_data = ecs_get(world, func, EcsScriptMethod); if (!func_data) { char *path = ecs_get_path(world, func); flecs_expr_visit_error(script, node, @@ -91236,7 +97570,7 @@ int flecs_expr_function_visit_type( node->node.kind = EcsExprMethod; node->node.type = func_data->return_type; node->calldata.function = func; - node->calldata.callback = func_data->callback; + node->calldata.is.callback = func_data->callback; node->calldata.ctx = func_data->ctx; params = &func_data->params; } @@ -91252,8 +97586,7 @@ int flecs_expr_function_visit_type( goto error; } - const EcsScriptFunction *func_data = ecs_get( - world, func, EcsScriptFunction); + func_data = ecs_get(world, func, EcsScriptFunction); if (!func_data) { char *path = ecs_get_path(world, func); flecs_expr_visit_error(script, node, @@ -91264,15 +97597,41 @@ int flecs_expr_function_visit_type( node->node.type = func_data->return_type; node->calldata.function = func; - node->calldata.callback = func_data->callback; + node->calldata.is.callback = func_data->callback; node->calldata.ctx = func_data->ctx; + node->calldata.vector_elem_count = 0; params = &func_data->params; } - if (flecs_expr_arguments_visit_type(script, node->args, desc, params)) { + int32_t count = ecs_vec_count(&node->args->elements); + if (count != ecs_vec_count(params)) { + flecs_expr_visit_error(script, node, "expected %d arguments, got %d", + ecs_vec_count(params), count); + goto error; + } + + ecs_entity_t vector_type = 0; + if (flecs_expr_arguments_visit_type( + script, node->args, desc, func_data, &vector_type)) + { goto error; } + if (vector_type) { + if (node->node.type == EcsScriptVectorType) { + node->node.type = vector_type; + } + + if (flecs_expr_populate_vector_calldata( + script, node, func_data, vector_type)) + { + goto error; + } + } else { + ecs_assert(node->node.type != EcsScriptVectorType, + ECS_INTERNAL_ERROR, NULL); + } + return 0; error: return -1; @@ -91327,10 +97686,6 @@ int flecs_expr_member_visit_type( ecs_log_set_level(prev_log); node->node.type = ecs_meta_get_type(cur); -#ifdef FLECS_DEBUG - const EcsMember *m = ecs_get(world, ecs_meta_get_member_id(cur), EcsMember); - ecs_assert(m != NULL, ECS_INTERNAL_ERROR, NULL); -#endif node->offset = (uintptr_t)ecs_meta_get_ptr(cur); return 0; @@ -91497,7 +97852,7 @@ int flecs_expr_match_visit_type( if (flecs_expr_type_for_operator(script, (ecs_expr_node_t*)node, 0, (ecs_expr_node_t*)node, elem->expr, EcsTokAdd, /* Use operator that doesn't change types */ - &operand_type, &result_type)) + &operand_type, &result_type, NULL)) { goto error; } diff --git a/libs/flecs/flecs.h b/libs/flecs/flecs.h index 23fa42e..a8bb5bd 100644 --- a/libs/flecs/flecs.h +++ b/libs/flecs/flecs.h @@ -27,7 +27,7 @@ /** * @defgroup options API defines - * Defines for customizing compile time features. + * Defines for customizing compile-time features. * * @{ */ @@ -35,7 +35,7 @@ /* Flecs version macros */ #define FLECS_VERSION_MAJOR 4 /**< Flecs major version. */ #define FLECS_VERSION_MINOR 1 /**< Flecs minor version. */ -#define FLECS_VERSION_PATCH 4 /**< Flecs patch version. */ +#define FLECS_VERSION_PATCH 5 /**< Flecs patch version. */ /** Flecs version. */ #define FLECS_VERSION FLECS_VERSION_IMPL(\ @@ -49,14 +49,14 @@ #endif /** @def ecs_float_t - * Customizable precision for floating point operations */ + * Customizable precision for floating-point operations. */ #ifndef ecs_float_t #define ecs_float_t float #endif /** @def ecs_ftime_t * Customizable precision for scalar time values. Change to double precision for - * processes that can run for a long time (e.g. longer than a day). */ + * processes that can run for a long time (e.g., longer than a day). */ #ifndef ecs_ftime_t #define ecs_ftime_t ecs_float_t #endif @@ -123,7 +123,7 @@ /** @def FLECS_SOFT_ASSERT * Define to not abort for recoverable errors, like invalid parameters. An error * is still thrown to the console. This is recommended for when running inside a - * third party runtime, such as the Unreal editor. + * third-party runtime, such as the Unreal editor. * * Note that internal sanity checks (ECS_INTERNAL_ERROR) will still abort a * process, as this gives more information than a (likely) subsequent crash. @@ -136,7 +136,7 @@ // #define FLECS_SOFT_ASSERT /** @def FLECS_KEEP_ASSERT - * By default asserts are disabled in release mode, when either FLECS_NDEBUG or + * By default, asserts are disabled in release mode, when either FLECS_NDEBUG or * NDEBUG is defined. Defining FLECS_KEEP_ASSERT ensures that asserts are not * disabled. This define can be combined with FLECS_SOFT_ASSERT. */ @@ -145,11 +145,25 @@ /** @def FLECS_DEFAULT_TO_UNCACHED_QUERIES * When set, this will cause queries with the EcsQueryCacheDefault policy * to default to EcsQueryCacheNone. This can reduce the memory footprint of - * applications at the cost of performance. Queries that use features which - * require caching such as group_by and order_by will still use caching. + * applications at the cost of performance. Queries that use features which + * require caching, such as group_by and order_by, will still use caching. */ // #define FLECS_DEFAULT_TO_UNCACHED_QUERIES +/** @def FLECS_CREATE_MEMBER_ENTITIES + * By default, Flecs does not create entities for component members when they + * are registered with reflection. Define this addon if an application relies + * on members being defined as entities. Features that require members to be + * defined as entities are: + * - Member queries + * - Metrics + * - Alerts + * + * Member entities can also be created on a per-type basis by setting + * ecs_struct_desc_t::create_member_entities to true. + */ +// #define FLECS_CREATE_MEMBER_ENTITIES + /** @def FLECS_CPP_NO_AUTO_REGISTRATION * When set, the C++ API will require that components are registered before they * are used. This is useful in multithreaded applications, where components need @@ -164,22 +178,22 @@ * When set, the C++ API will not attempt to discover and register enum * constants for registered enum components. This will cause C++ APIs that * accept enum constants to not work. - * Disabling this feature can significantly improve compile times and reduces + * Disabling this feature can significantly improve compile times and reduce * the RAM footprint of an application. */ // #define FLECS_CPP_NO_ENUM_REFLECTION /** @def FLECS_NO_ALWAYS_INLINE - * When set, this will prevent functions from being annotated with always_inline + * When set, this will prevent functions from being annotated with always_inline, * which can improve performance at the cost of increased binary footprint. */ // #define FLECS_NO_ALWAYS_INLINE /** @def FLECS_CUSTOM_BUILD - * This macro lets you customize which addons to build flecs with. - * Without any addons Flecs is just a minimal ECS storage, but addons add - * features such as systems, scheduling and reflection. If an addon is disabled, - * it is excluded from the build, so that it consumes no resources. By default + * This macro lets you customize which addons to build Flecs with. + * Without any addons, Flecs is just a minimal ECS storage, but addons add + * features such as systems, scheduling, and reflection. If an addon is disabled, + * it is excluded from the build, so that it consumes no resources. By default, * all addons are enabled. * * You can customize a build by either whitelisting or blacklisting addons. To @@ -193,7 +207,7 @@ * blacklisted addon, an error will be thrown during the build. * * Note that addons can have dependencies on each other. Addons will - * automatically enable their dependencies. To see the list of addons that was + * automatically enable their dependencies. To see the list of addons that were * compiled in a build, enable tracing before creating the world by doing: * * @code @@ -205,30 +219,30 @@ // #define FLECS_CUSTOM_BUILD #ifndef FLECS_CUSTOM_BUILD -#define FLECS_ALERTS /**< Monitor conditions for errors */ -#define FLECS_APP /**< Application addon */ -// #define FLECS_C /**< C API convenience macros, always enabled */ -#define FLECS_CPP /**< C++ API */ -#define FLECS_DOC /**< Document entities & components */ -// #define FLECS_JOURNAL /**< Journaling addon */ -#define FLECS_JSON /**< Parsing JSON to/from component values */ -#define FLECS_HTTP /**< Tiny HTTP server for connecting to remote UI */ -#define FLECS_LOG /**< When enabled ECS provides more detailed logs */ -#define FLECS_META /**< Reflection support */ -#define FLECS_METRICS /**< Expose component data as statistics */ -#define FLECS_MODULE /**< Module support */ -#define FLECS_OS_API_IMPL /**< Default implementation for OS API */ -// #define FLECS_PERF_TRACE /**< Enable performance tracing */ -#define FLECS_PIPELINE /**< Pipeline support */ -#define FLECS_REST /**< REST API for querying application data */ -#define FLECS_PARSER /**< Utilities for script and query DSL parsers */ -#define FLECS_QUERY_DSL /**< Flecs query DSL parser */ -#define FLECS_SCRIPT /**< Flecs entity notation language */ -// #define FLECS_SCRIPT_MATH /**< Math functions for flecs script (may require linking with libm) */ -#define FLECS_SYSTEM /**< System support */ -#define FLECS_STATS /**< Track runtime statistics */ -#define FLECS_TIMER /**< Timer support */ -#define FLECS_UNITS /**< Builtin standard units */ +#define FLECS_ALERTS /**< Monitor conditions for errors. */ +#define FLECS_APP /**< Application addon. */ +// #define FLECS_C /**< C API convenience macros, always enabled. */ +#define FLECS_CPP /**< C++ API. */ +#define FLECS_DOC /**< Document entities and components. */ +// #define FLECS_JOURNAL /**< Journaling addon. */ +#define FLECS_JSON /**< Parsing JSON to/from component values. */ +#define FLECS_HTTP /**< Tiny HTTP server for connecting to remote UI. */ +#define FLECS_LOG /**< When enabled, ECS provides more detailed logs. */ +#define FLECS_META /**< Reflection support. */ +#define FLECS_METRICS /**< Expose component data as statistics. */ +#define FLECS_MODULE /**< Module support. */ +#define FLECS_OS_API_IMPL /**< Default implementation for OS API. */ +// #define FLECS_PERF_TRACE /**< Enable performance tracing. */ +#define FLECS_PIPELINE /**< Pipeline support. */ +#define FLECS_REST /**< REST API for querying application data. */ +#define FLECS_PARSER /**< Utilities for script and query DSL parsers. */ +#define FLECS_QUERY_DSL /**< Flecs query DSL parser. */ +#define FLECS_SCRIPT /**< Flecs entity notation language. */ +// #define FLECS_SCRIPT_MATH /**< Math functions for Flecs script (may require linking with libm). */ +#define FLECS_SYSTEM /**< System support. */ +#define FLECS_STATS /**< Track runtime statistics. */ +#define FLECS_TIMER /**< Timer support. */ +#define FLECS_UNITS /**< Built-in standard units. */ #endif // ifndef FLECS_CUSTOM_BUILD /** @def FLECS_LOW_FOOTPRINT @@ -246,16 +260,16 @@ /** @def FLECS_HI_COMPONENT_ID * This constant can be used to balance between performance and memory * utilization. The constant is used in two ways: - * - Entity ids 0..FLECS_HI_COMPONENT_ID are reserved for component ids. - * - Used as lookup array size in table edges. + * - Entity IDs 0..FLECS_HI_COMPONENT_ID are reserved for component IDs. + * - Used as the lookup array size in table edges. * * Increasing this value increases the size of the lookup array, which allows * fast table traversal, which improves performance of ECS add/remove - * operations. Component ids that fall outside of this range use a regular map + * operations. Component IDs that fall outside of this range use a regular map * lookup, which is slower but more memory efficient. * - * This value must be set to a value that is a power of 2. Setting it to a value - * that is not a power of two will degrade performance. + * This value must be set to a power of 2. Setting it to a value that is not a + * power of 2 will degrade performance. */ #ifndef FLECS_HI_COMPONENT_ID #define FLECS_HI_COMPONENT_ID 256 @@ -264,7 +278,7 @@ /** @def FLECS_HI_ID_RECORD_ID * This constant can be used to balance between performance and memory * utilization. The constant is used to determine the size of the component record - * lookup array. Id values that fall outside of this range use a regular map + * lookup array. ID values that fall outside of this range use a regular map * lookup, which is slower but more memory efficient. */ #ifndef FLECS_HI_ID_RECORD_ID @@ -272,7 +286,7 @@ #endif /** @def FLECS_SPARSE_PAGE_BITS - * This constant is used to determine the number of bits of an id that is used + * This constant is used to determine the number of bits of an ID that is used * to determine the page index when used with a sparse set. The number of bits * determines the page size, which is (1 << bits). * Lower values decrease memory utilization, at the cost of more allocations. */ @@ -288,24 +302,24 @@ /** @def FLECS_USE_OS_ALLOC * When enabled, Flecs will use the OS allocator provided in the OS API directly - * instead of the builtin block allocator. This can decrease memory utilization + * instead of the built-in block allocator. This can decrease memory utilization * as memory will be freed more often, at the cost of decreased performance. */ // #define FLECS_USE_OS_ALLOC /** @def FLECS_ID_DESC_MAX - * Maximum number of ids to add ecs_entity_desc_t / ecs_bulk_desc_t */ + * Maximum number of IDs to add in ecs_entity_desc_t / ecs_bulk_desc_t. */ #ifndef FLECS_ID_DESC_MAX #define FLECS_ID_DESC_MAX 32 #endif /** @def FLECS_EVENT_DESC_MAX - * Maximum number of events in ecs_observer_desc_t */ + * Maximum number of events in ecs_observer_desc_t. */ #ifndef FLECS_EVENT_DESC_MAX #define FLECS_EVENT_DESC_MAX 8 #endif /** @def FLECS_VARIABLE_COUNT_MAX - * Maximum number of query variables per query */ + * Maximum number of query variables per query. */ #define FLECS_VARIABLE_COUNT_MAX 64 /** @def FLECS_TERM_COUNT_MAX @@ -327,19 +341,25 @@ #endif /** @def FLECS_QUERY_SCOPE_NESTING_MAX - * Maximum nesting depth of query scopes */ + * Maximum nesting depth of query scopes. */ #ifndef FLECS_QUERY_SCOPE_NESTING_MAX #define FLECS_QUERY_SCOPE_NESTING_MAX 8 #endif /** @def FLECS_DAG_DEPTH_MAX - * Maximum of levels in a DAG (acyclic relationship graph). If a graph with a + * Maximum number of levels in a DAG (acyclic relationship graph). If a graph with a * depth larger than this is encountered, a CYCLE_DETECTED panic is thrown. */ #ifndef FLECS_DAG_DEPTH_MAX #define FLECS_DAG_DEPTH_MAX 128 #endif +/** @def FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE + * Size of the depth cache in the tree spawner component. Higher values speed up prefab + * instantiation for deeper hierarchies, at the cost of slightly more memory. + */ +#define FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE (6) + /** @} */ /** @@ -402,7 +422,7 @@ extern "C" { //////////////////////////////////////////////////////////////////////////////// -//// Id flags (used by ecs_component_record_t::flags) +//// ID flags (used by ecs_component_record_t::flags) //////////////////////////////////////////////////////////////////////////////// #define EcsIdOnDeleteRemove (1u << 0) @@ -433,24 +453,25 @@ extern "C" { #define EcsIdIsTransitive (1u << 14) #define EcsIdInheritable (1u << 15) -#define EcsIdHasOnAdd (1u << 16) /* Same values as table flags */ +#define EcsIdHasOnAdd (1u << 16) /* Same values as table flags. */ #define EcsIdHasOnRemove (1u << 17) #define EcsIdHasOnSet (1u << 18) #define EcsIdHasOnTableCreate (1u << 19) #define EcsIdHasOnTableDelete (1u << 20) #define EcsIdSparse (1u << 21) #define EcsIdDontFragment (1u << 22) -#define EcsIdMatchDontFragment (1u << 23) /* For (*, T) wildcards */ +#define EcsIdMatchDontFragment (1u << 23) /* For (*, T) wildcards. */ #define EcsIdOrderedChildren (1u << 24) #define EcsIdSingleton (1u << 25) #define EcsIdEventMask\ (EcsIdHasOnAdd|EcsIdHasOnRemove|EcsIdHasOnSet|\ EcsIdHasOnTableCreate|EcsIdHasOnTableDelete|EcsIdSparse|\ EcsIdOrderedChildren) +#define EcsIdPrefabChildren (1u << 26) #define EcsIdMarkedForDelete (1u << 30) -/* Utilities for converting from flags to delete policies and vice versa */ +/* Utilities for converting from flags to delete policies and vice versa. */ #define ECS_ID_ON_DELETE(flags) \ ((ecs_entity_t[]){0, EcsRemove, EcsDelete, 0, EcsPanic}\ [((flags) & EcsIdOnDeleteMask)]) @@ -458,7 +479,7 @@ extern "C" { #define ECS_ID_ON_DELETE_FLAG(id) (1u << ((id) - EcsRemove)) #define ECS_ID_ON_DELETE_TARGET_FLAG(id) (1u << (3 + ((id) - EcsRemove))) -/* Utilities for converting from flags to instantiate policies and vice versa */ +/* Utilities for converting from flags to instantiate policies and vice versa. */ #define ECS_ID_ON_INSTANTIATE(flags) \ ((ecs_entity_t[]){EcsOverride, EcsOverride, EcsInherit, 0, EcsDontInherit}\ [(((flags) & EcsIdOnInstantiateMask) >> 6)]) @@ -478,61 +499,63 @@ extern "C" { //// Iterator flags (used by ecs_iter_t::flags) //////////////////////////////////////////////////////////////////////////////// -#define EcsIterIsValid (1u << 0u) /* Does iterator contain valid result */ -#define EcsIterNoData (1u << 1u) /* Does iterator provide (component) data */ -#define EcsIterNoResults (1u << 2u) /* Iterator has no results */ -#define EcsIterMatchEmptyTables (1u << 3u) /* Match empty tables */ -#define EcsIterIgnoreThis (1u << 4u) /* Only evaluate non-this terms */ +#define EcsIterIsValid (1u << 0u) /* Does the iterator contain a valid result. */ +#define EcsIterNoData (1u << 1u) /* Does the iterator provide (component) data. */ +#define EcsIterNoResults (1u << 2u) /* Iterator has no results. */ +#define EcsIterMatchEmptyTables (1u << 3u) /* Match empty tables. */ +#define EcsIterIgnoreThis (1u << 4u) /* Only evaluate non-this terms. */ #define EcsIterTrivialChangeDetection (1u << 5u) -#define EcsIterHasCondSet (1u << 6u) /* Does iterator have conditionally set fields */ -#define EcsIterProfile (1u << 7u) /* Profile iterator performance */ -#define EcsIterTrivialSearch (1u << 8u) /* Trivial iterator mode */ -#define EcsIterTrivialTest (1u << 11u) /* Trivial test mode (constrained $this) */ -#define EcsIterTrivialCached (1u << 14u) /* Trivial search for cached query */ -#define EcsIterCached (1u << 15u) /* Cached query */ -#define EcsIterFixedInChangeComputed (1u << 16u) /* Change detection for fixed in terms is done */ -#define EcsIterFixedInChanged (1u << 17u) /* Fixed in terms changed */ -#define EcsIterSkip (1u << 18u) /* Result was skipped for change detection */ -#define EcsIterCppEach (1u << 19u) /* Uses C++ 'each' iterator */ +#define EcsIterHasCondSet (1u << 6u) /* Does the iterator have conditionally set fields. */ +#define EcsIterProfile (1u << 7u) /* Profile iterator performance. */ +#define EcsIterTrivialSearch (1u << 8u) /* Trivial iterator mode. */ +#define EcsIterTrivialTest (1u << 11u) /* Trivial test mode (constrained $this). */ +#define EcsIterTrivialCached (1u << 14u) /* Trivial search for cached query. */ +#define EcsIterCached (1u << 15u) /* Cached query. */ +#define EcsIterFixedInChangeComputed (1u << 16u) /* Change detection for fixed-in terms is done. */ +#define EcsIterFixedInChanged (1u << 17u) /* Fixed-in terms changed. */ +#define EcsIterSkip (1u << 18u) /* Result was skipped for change detection. */ +#define EcsIterCppEach (1u << 19u) /* Uses C++ 'each' iterator. */ +#define EcsIterImmutableCacheData (1u << 21u) /* Internally used by the engine to indicate immutable arrays from the cache. */ -/* Same as event flags */ -#define EcsIterTableOnly (1u << 20u) /* Result only populates table */ +/* Same as event flags. */ +#define EcsIterTableOnly (1u << 20u) /* Result only populates the table. */ //////////////////////////////////////////////////////////////////////////////// -//// Event flags (used by ecs_event_decs_t::flags) +//// Event flags (used by ecs_event_desc_t::flags) //////////////////////////////////////////////////////////////////////////////// -#define EcsEventTableOnly (1u << 20u) /* Table event (no data, same as iter flags) */ -#define EcsEventNoOnSet (1u << 16u) /* Don't emit OnSet for inherited ids */ +#define EcsEventTableOnly (1u << 20u) /* Table event (no data, same as iter flags). */ +#define EcsEventNoOnSet (1u << 16u) /* Don't emit OnSet for inherited IDs. */ //////////////////////////////////////////////////////////////////////////////// //// Query flags (used by ecs_query_t::flags) //////////////////////////////////////////////////////////////////////////////// -/* Flags that can only be set by the query implementation */ -#define EcsQueryMatchThis (1u << 11u) /* Query has terms with $this source */ -#define EcsQueryMatchOnlyThis (1u << 12u) /* Query only has terms with $this source */ -#define EcsQueryMatchOnlySelf (1u << 13u) /* Query has no terms with up traversal */ -#define EcsQueryMatchWildcards (1u << 14u) /* Query matches wildcards */ -#define EcsQueryMatchNothing (1u << 15u) /* Query matches nothing */ -#define EcsQueryHasCondSet (1u << 16u) /* Query has conditionally set fields */ -#define EcsQueryHasPred (1u << 17u) /* Query has equality predicates */ -#define EcsQueryHasScopes (1u << 18u) /* Query has query scopes */ -#define EcsQueryHasRefs (1u << 19u) /* Query has terms with static source */ -#define EcsQueryHasOutTerms (1u << 20u) /* Query has [out] terms */ -#define EcsQueryHasNonThisOutTerms (1u << 21u) /* Query has [out] terms with no $this source */ -#define EcsQueryHasChangeDetection (1u << 22u) /* Query has monitor for change detection */ -#define EcsQueryIsTrivial (1u << 23u) /* Query can use trivial evaluation function */ -#define EcsQueryHasCacheable (1u << 24u) /* Query has cacheable terms */ -#define EcsQueryIsCacheable (1u << 25u) /* All terms of query are cacheable */ -#define EcsQueryHasTableThisVar (1u << 26u) /* Does query have $this table var */ -#define EcsQueryCacheYieldEmptyTables (1u << 27u) /* Does query cache empty tables */ -#define EcsQueryTrivialCache (1u << 28u) /* Trivial cache (no wildcards, traversal, order_by, group_by, change detection) */ -#define EcsQueryNested (1u << 29u) /* Query created by a query (for observer, cache) */ -#define EcsQueryValid (1u << 30u) +/* Flags that can only be set by the query implementation. */ +#define EcsQueryMatchThis (1u << 11u) /* Query has terms with $this source. */ +#define EcsQueryMatchOnlyThis (1u << 12u) /* Query only has terms with $this source. */ +#define EcsQueryMatchOnlySelf (1u << 13u) /* Query has no terms with up traversal. */ +#define EcsQueryMatchWildcards (1u << 14u) /* Query matches wildcards. */ +#define EcsQueryMatchNothing (1u << 15u) /* Query matches nothing. */ +#define EcsQueryHasCondSet (1u << 16u) /* Query has conditionally set fields. */ +#define EcsQueryHasPred (1u << 17u) /* Query has equality predicates. */ +#define EcsQueryHasScopes (1u << 18u) /* Query has query scopes. */ +#define EcsQueryHasRefs (1u << 19u) /* Query has terms with static source. */ +#define EcsQueryHasOutTerms (1u << 20u) /* Query has [out] terms. */ +#define EcsQueryHasNonThisOutTerms (1u << 21u) /* Query has [out] terms with no $this source. */ +#define EcsQueryHasChangeDetection (1u << 22u) /* Query has a monitor for change detection. */ +#define EcsQueryIsTrivial (1u << 23u) /* Query can use trivial evaluation function. */ +#define EcsQueryHasCacheable (1u << 24u) /* Query has cacheable terms. */ +#define EcsQueryIsCacheable (1u << 25u) /* All terms of the query are cacheable. */ +#define EcsQueryHasTableThisVar (1u << 26u) /* Does the query have $this table var. */ +#define EcsQueryCacheYieldEmptyTables (1u << 27u) /* Does the query cache empty tables. */ +#define EcsQueryTrivialCache (1u << 28u) /* Trivial cache (no wildcards, traversal, order_by, group_by, change detection). */ +#define EcsQueryNested (1u << 29u) /* Query created by a query (for observer, cache). */ +#define EcsQueryCacheWithFilter (1u << 30u) +#define EcsQueryValid (1u << 31u) //////////////////////////////////////////////////////////////////////////////// //// Term flags (used by ecs_term_t::flags_) @@ -544,51 +567,53 @@ extern "C" { #define EcsTermReflexive (1u << 3) #define EcsTermIdInherited (1u << 4) #define EcsTermIsTrivial (1u << 5) -#define EcsTermIsCacheable (1u << 7) -#define EcsTermIsScope (1u << 8) -#define EcsTermIsMember (1u << 9) -#define EcsTermIsToggle (1u << 10) -#define EcsTermIsSparse (1u << 12) -#define EcsTermIsOr (1u << 13) -#define EcsTermDontFragment (1u << 14) +#define EcsTermIsCacheable (1u << 6) +#define EcsTermIsScope (1u << 7) +#define EcsTermIsMember (1u << 8) +#define EcsTermIsToggle (1u << 9) +#define EcsTermIsSparse (1u << 10) +#define EcsTermIsOr (1u << 11) +#define EcsTermDontFragment (1u << 12) +#define EcsTermNonFragmentingChildOf (1u << 13) //////////////////////////////////////////////////////////////////////////////// //// Observer flags (used by ecs_observer_t::flags) //////////////////////////////////////////////////////////////////////////////// -#define EcsObserverMatchPrefab (1u << 1u) /* Same as query*/ -#define EcsObserverMatchDisabled (1u << 2u) /* Same as query*/ -#define EcsObserverIsMulti (1u << 3u) /* Does observer have multiple terms */ -#define EcsObserverIsMonitor (1u << 4u) /* Is observer a monitor */ -#define EcsObserverIsDisabled (1u << 5u) /* Is observer entity disabled */ -#define EcsObserverIsParentDisabled (1u << 6u) /* Is module parent of observer disabled */ -#define EcsObserverBypassQuery (1u << 7u) /* Don't evaluate query for multi-component observer*/ -#define EcsObserverYieldOnCreate (1u << 8u) /* Yield matching entities when creating observer */ -#define EcsObserverYieldOnDelete (1u << 9u) /* Yield matching entities when deleting observer */ -#define EcsObserverKeepAlive (1u << 11u) /* Observer keeps component alive (same value as EcsTermKeepAlive) */ +#define EcsObserverMatchPrefab (1u << 1u) /* Same as query. */ +#define EcsObserverMatchDisabled (1u << 2u) /* Same as query. */ +#define EcsObserverIsMulti (1u << 3u) /* Does the observer have multiple terms. */ +#define EcsObserverIsMonitor (1u << 4u) /* Is the observer a monitor. */ +#define EcsObserverIsDisabled (1u << 5u) /* Is the observer entity disabled. */ +#define EcsObserverIsParentDisabled (1u << 6u) /* Is the module parent of the observer disabled. */ +#define EcsObserverBypassQuery (1u << 7u) /* Don't evaluate query for multi-component observer. */ +#define EcsObserverYieldOnCreate (1u << 8u) /* Yield matching entities when creating observer. */ +#define EcsObserverYieldOnDelete (1u << 9u) /* Yield matching entities when deleting observer. */ +#define EcsObserverKeepAlive (1u << 11u) /* Observer keeps component alive (same value as EcsTermKeepAlive). */ //////////////////////////////////////////////////////////////////////////////// //// Table flags (used by ecs_table_t::flags) //////////////////////////////////////////////////////////////////////////////// -#define EcsTableHasBuiltins (1u << 1u) /* Does table have builtin components */ -#define EcsTableIsPrefab (1u << 2u) /* Does the table store prefabs */ -#define EcsTableHasIsA (1u << 3u) /* Does the table have IsA relationship */ -#define EcsTableHasMultiIsA (1u << 4u) /* Does table have multiple IsA pairs */ -#define EcsTableHasChildOf (1u << 5u) /* Does the table type ChildOf relationship */ -#define EcsTableHasName (1u << 6u) /* Does the table type have (Identifier, Name) */ -#define EcsTableHasPairs (1u << 7u) /* Does the table type have pairs */ -#define EcsTableHasModule (1u << 8u) /* Does the table have module data */ -#define EcsTableIsDisabled (1u << 9u) /* Does the table type has EcsDisabled */ -#define EcsTableNotQueryable (1u << 10u) /* Table should never be returned by queries */ +#define EcsTableHasBuiltins (1u << 0u) /* Does the table have built-in components. */ +#define EcsTableIsPrefab (1u << 1u) /* Does the table store prefabs. */ +#define EcsTableHasIsA (1u << 2u) /* Does the table have IsA relationship. */ +#define EcsTableHasMultiIsA (1u << 3u) /* Does the table have multiple IsA pairs. */ +#define EcsTableHasChildOf (1u << 4u) /* Does the table type have ChildOf relationship. */ +#define EcsTableHasParent (1u << 5u) /* Does the table type have Parent component. */ +#define EcsTableHasName (1u << 6u) /* Does the table type have (Identifier, Name). */ +#define EcsTableHasPairs (1u << 7u) /* Does the table type have pairs. */ +#define EcsTableHasModule (1u << 8u) /* Does the table have module data. */ +#define EcsTableIsDisabled (1u << 9u) /* Does the table type have EcsDisabled. */ +#define EcsTableNotQueryable (1u << 10u) /* Table should never be returned by queries. */ #define EcsTableHasCtors (1u << 11u) #define EcsTableHasDtors (1u << 12u) #define EcsTableHasCopy (1u << 13u) #define EcsTableHasMove (1u << 14u) #define EcsTableHasToggle (1u << 15u) -#define EcsTableHasOnAdd (1u << 16u) /* Same values as id flags */ +#define EcsTableHasOnAdd (1u << 16u) /* Same values as ID flags. */ #define EcsTableHasOnRemove (1u << 17u) #define EcsTableHasOnSet (1u << 18u) #define EcsTableHasOnTableCreate (1u << 19u) @@ -613,11 +638,11 @@ extern "C" { #define EcsTableRemoveEdgeFlags (EcsTableHasOnRemove | EcsTableHasSparse | EcsTableHasOrderedChildren) //////////////////////////////////////////////////////////////////////////////// -//// Aperiodic action flags (used by ecs_run_aperiodic) +//// Aperiodic action flags (used by ecs_run_aperiodic()) //////////////////////////////////////////////////////////////////////////////// -#define EcsAperiodicComponentMonitors (1u << 2u) /* Process component monitors */ -#define EcsAperiodicEmptyQueries (1u << 4u) /* Process empty queries */ +#define EcsAperiodicComponentMonitors (1u << 2u) /* Process component monitors. */ +#define EcsAperiodicEmptyQueries (1u << 4u) /* Process empty queries. */ #ifdef __cplusplus } @@ -665,8 +690,8 @@ extern "C" { #define ECS_TARGET_GNU #endif -/* Map between clang and apple clang versions, as version 13 has a difference in - * the format of __PRETTY_FUNCTION__ which enum reflection depends on. */ +/* Map between clang and Apple clang versions, as version 13 has a difference in + * the format of __PRETTY_FUNCTION__, which enum reflection depends on. */ #if defined(__clang__) #if defined(__APPLE__) #if __clang_major__ == 13 @@ -692,12 +717,12 @@ extern "C" { /* Ignored warnings */ #if defined(ECS_TARGET_CLANG) -/* Ignore unknown options so we don't have to care about the compiler version */ +/* Ignore unknown options so we don't have to care about the compiler version. */ #pragma clang diagnostic ignored "-Wunknown-warning-option" /* Warns for double or redundant semicolons. There are legitimate cases where a - * semicolon after an empty statement is useful, for example after a macro that + * semicolon after an empty statement is useful, for example, after a macro that * is replaced with a code block. With this warning enabled, semicolons would - * only have to be added after macro's that are not code blocks, which in some + * only have to be added after macros that are not code blocks, which in some * cases isn't possible as the implementation of a macro can be different in * debug/release mode. */ #pragma clang diagnostic ignored "-Wextra-semi-stmt" @@ -705,47 +730,47 @@ extern "C" { #pragma clang diagnostic ignored "-Wdeclaration-after-statement" /* Clang attribute to detect fallthrough isn't supported on older versions. * Implicit fallthrough is still detected by gcc and ignored with "fall through" - * comments */ + * comments. */ #pragma clang diagnostic ignored "-Wimplicit-fallthrough" /* This warning prevents adding a default case when all enum constants are part - * of the switch. In C however an enum type can assume any value in the range of + * of the switch. In C, however, an enum type can assume any value in the range of * the type, and this warning makes it harder to catch invalid enum values. */ #pragma clang diagnostic ignored "-Wcovered-switch-default" /* This warning prevents some casts of function results to a different kind of - * type, e.g. casting an int result to double. Not very useful in practice, as + * type, e.g., casting an int result to double. Not very useful in practice, as * it just forces the code to assign to a variable first, then cast. */ #pragma clang diagnostic ignored "-Wbad-function-cast" /* Format strings can be passed down from other functions. */ #pragma clang diagnostic ignored "-Wformat-nonliteral" -/* Useful, but not reliable enough. It can incorrectly flag macro's as unused +/* Useful, but not reliable enough. It can incorrectly flag macros as unused * in standalone builds. */ #pragma clang diagnostic ignored "-Wunused-macros" -/* This warning gets thrown by clang even when a code is handling all case +/* This warning gets thrown by clang even when the code is handling all case * values but not all cases (for example, when the switch contains a LastValue * case). Adding a "default" case fixes the warning, but silences future * warnings about unhandled cases, which is worse. */ #pragma clang diagnostic ignored "-Wswitch-default" #if __clang_major__ == 13 -/* clang 13 can throw this warning for a define in ctype.h */ +/* clang 13 can throw this warning for a macro in ctype.h. */ #pragma clang diagnostic ignored "-Wreserved-identifier" #endif /* Filenames aren't consistent across targets as they can use different casing - * (e.g. WinSock2 vs winsock2). */ + * (e.g., WinSock2 vs. winsock2). */ #pragma clang diagnostic ignored "-Wnonportable-system-include-path" -/* Very difficult to workaround this warning in C, especially for an ECS. */ +/* Very difficult to work around this warning in C, especially for an ECS. */ #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" -/* This warning gets thrown when trying to cast pointer returned from dlproc */ +/* This warning gets thrown when trying to cast a pointer returned from dlproc. */ #pragma clang diagnostic ignored "-Wcast-function-type-strict" /* This warning can get thrown for expressions that evaluate to constants * in debug/release mode. */ #pragma clang diagnostic ignored "-Wconstant-logical-operand" -/* With soft asserts enabled the code won't abort, which in some cases means +/* With soft asserts enabled, the code won't abort, which in some cases means * code paths are reached where values are uninitialized. */ #ifdef FLECS_SOFT_ASSERT #pragma clang diagnostic ignored "-Wsometimes-uninitialized" #endif -/* Allows for enum reflection support on legacy compilers */ +/* Allows for enum reflection support on legacy compilers. */ #if __clang_major__ < 16 #pragma clang diagnostic ignored "-Wenum-constexpr-conversion" #endif @@ -759,24 +784,24 @@ extern "C" { #pragma GCC diagnostic ignored "-Wunused-macros" /* This warning gets thrown *sometimes* when not all members for a struct are * provided in an initializer. Flecs heavily relies on descriptor structs that - * only require partly initialization, so this warning isn't useful. + * only require partial initialization, so this warning isn't useful. * It doesn't introduce any safety issues (fields are guaranteed to be 0 * initialized), and later versions of gcc (>=11) seem to no longer throw this * warning. */ #pragma GCC diagnostic ignored "-Wmissing-field-initializers" /* Produces false positives in addons/cpp/delegate.hpp. */ #pragma GCC diagnostic ignored "-Warray-bounds" -/* Produces false positives in queries/src/cache.c */ +/* Produces false positives in queries/src/cache.c. */ #pragma GCC diagnostic ignored "-Wstringop-overflow" #pragma GCC diagnostic ignored "-Wrestrict" #elif defined(ECS_TARGET_MSVC) -/* recursive on all control paths, function will cause runtime stack overflow +/* Recursive on all control paths, the function will cause runtime stack overflow. * This warning is incorrectly thrown on enum reflection code. */ #pragma warning(disable: 4717) #endif -/* Allows for enum reflection support on legacy compilers */ +/* Allows for enum reflection support on legacy compilers. */ #if defined(__GNUC__) && __GNUC__ <= 10 #pragma GCC diagnostic ignored "-Wconversion" #endif @@ -787,10 +812,10 @@ extern "C" { #include #include -/* Non-standard but required. If not provided by platform, add manually. */ +/* Non-standard but required. If not provided by the platform, add manually. */ #include -/* Contains macros for importing / exporting symbols */ +/* Contains macros for importing and exporting symbols. */ /* ) (.) @@ -840,8 +865,8 @@ extern "C" { #define FLECS_LEGACY #endif -/* Some symbols are only exported when building in debug build, to enable - * white-box testing of internal data structures */ +/* Some symbols are only exported when building in a debug build, to enable + * white-box testing of internal data structures. */ #ifndef FLECS_NDEBUG #define FLECS_DBG_API FLECS_API #else @@ -861,7 +886,7 @@ extern "C" { #define NULL ((void*)0) #endif -/* The API uses the native bool type in C++, or a custom one in C */ +/* The API uses the native bool type in C++, or a custom one in C. */ #if !defined(__cplusplus) && !defined(__bool_true_false_are_defined) #undef bool #undef true @@ -871,30 +896,30 @@ typedef char bool; #define true !false #endif -/* Utility types to indicate usage as bitmask */ +/* Utility types to indicate usage as a bitmask. */ typedef uint8_t ecs_flags8_t; typedef uint16_t ecs_flags16_t; typedef uint32_t ecs_flags32_t; typedef uint64_t ecs_flags64_t; -/* Bitmask type with compile-time defined size */ +/* Bitmask type with compile-time-defined size. */ #define ecs_flagsn_t_(bits) ecs_flags##bits##_t #define ecs_flagsn_t(bits) ecs_flagsn_t_(bits) -/* Bitset type that can store exactly as many bits as there are terms */ +/* Bitset type that can store exactly as many bits as there are terms. */ #define ecs_termset_t ecs_flagsn_t(FLECS_TERM_COUNT_MAX) -/* Utility macro's for setting/clearing termset bits */ +/* Utility macros for setting/clearing termset bits. */ #define ECS_TERMSET_SET(set, flag) ((set) |= (ecs_termset_t)(flag)) #define ECS_TERMSET_CLEAR(set, flag) ((set) &= (ecs_termset_t)~(flag)) #define ECS_TERMSET_COND(set, flag, cond) ((cond) \ ? (ECS_TERMSET_SET(set, flag)) \ : (ECS_TERMSET_CLEAR(set, flag))) -/* Keep unsigned integers out of the codebase as they do more harm than good */ +/* Keep unsigned integers out of the codebase as they do more harm than good. */ typedef int32_t ecs_size_t; -/* Allocator type */ +/* Allocator type. */ typedef struct ecs_allocator_t ecs_allocator_t; #define ECS_SIZEOF(T) ECS_CAST(ecs_size_t, sizeof(T)) @@ -904,12 +929,21 @@ typedef struct ecs_allocator_t ecs_allocator_t; #define ECS_ALIGNOF(T) static_cast(alignof(T)) #elif defined(ECS_TARGET_MSVC) #define ECS_ALIGNOF(T) (int64_t)__alignof(T) -#elif defined(ECS_TARGET_GNU) -#define ECS_ALIGNOF(T) (int64_t)__alignof__(T) -#elif defined(ECS_TARGET_CLANG) -#define ECS_ALIGNOF(T) (int64_t)__alignof__(T) #else -#define ECS_ALIGNOF(T) ((int64_t)&((struct { char c; T d; } *)0)->d) +/* Use the struct trick since on 32-bit platforms __alignof__ can return different + * results than C++'s alignof. This is illustrated when doing: + * + * __alignof__(uint64_t) == 8 on 32-bit platforms + * alignof(uint64_t) == 4 on 32-bit platforms + * + * typedef struct { + * uint64_t value; + * } Foo; + * + * __alignof__(Foo) == 4 on 32-bit platforms + * alignof(Foo) == 4 on 32-bit platforms + */ +#define ECS_ALIGNOF(T) ((int64_t)(size_t)&((struct { char c; T d; } *)0)->d) #endif #ifndef FLECS_NO_ALWAYS_INLINE @@ -938,39 +972,39 @@ typedef struct ecs_allocator_t ecs_allocator_t; #define ECS_ALIGN(size, alignment) (ecs_size_t)((((((size_t)size) - 1) / ((size_t)alignment)) + 1) * ((size_t)alignment)) -/* Simple utility for determining the max of two values */ +/* Simple utility for determining the max of two values. */ #define ECS_MAX(a, b) (((a) > (b)) ? a : b) #define ECS_MIN(a, b) (((a) < (b)) ? a : b) /* Abstraction on top of C-style casts so that C functions can be used in C++ - * code without producing warnings */ + * code without producing warnings. */ #ifndef __cplusplus #define ECS_CAST(T, V) ((T)(V)) #else #define ECS_CAST(T, V) (static_cast(V)) #endif -/* Utility macro for doing const casts without warnings */ +/* Utility macro for doing const casts without warnings. */ #ifndef __cplusplus #define ECS_CONST_CAST(type, value) ((type)(uintptr_t)(value)) #else #define ECS_CONST_CAST(type, value) (const_cast(value)) #endif -/* Utility macro for doing pointer casts without warnings */ +/* Utility macro for doing pointer casts without warnings. */ #ifndef __cplusplus #define ECS_PTR_CAST(type, value) ((type)(uintptr_t)(value)) #else #define ECS_PTR_CAST(type, value) (reinterpret_cast(value)) #endif -/* Utility macro's to do bitwise comparisons between floats without warnings */ +/* Utility macros to do bitwise comparisons between floats without warnings. */ #define ECS_EQ(a, b) (ecs_os_memcmp(&(a), &(b), sizeof(a)) == 0) #define ECS_NEQ(a, b) (!ECS_EQ(a, b)) #define ECS_EQZERO(a) ECS_EQ(a, (uint64_t){0}) #define ECS_NEQZERO(a) ECS_NEQ(a, (uint64_t){0}) -/* Utilities to convert flecs version to string */ +/* Utilities to convert Flecs version to a string. */ #define FLECS_VERSION_IMPLSTR(major, minor, patch) #major "." #minor "." #patch #define FLECS_VERSION_IMPL(major, minor, patch) \ FLECS_VERSION_IMPLSTR(major, minor, patch) @@ -981,7 +1015,7 @@ typedef struct ecs_allocator_t ecs_allocator_t; //// Magic numbers for sanity checking //////////////////////////////////////////////////////////////////////////////// -/* Magic number to identify the type of the object */ +/* Magic number to identify the type of the object. */ #define ecs_world_t_magic (0x65637377) #define ecs_stage_t_magic (0x65637373) #define ecs_query_t_magic (0x65637375) @@ -989,7 +1023,7 @@ typedef struct ecs_allocator_t ecs_allocator_t; //////////////////////////////////////////////////////////////////////////////// -//// Entity id macros +//// Entity ID macros //////////////////////////////////////////////////////////////////////////////// #define ECS_ROW_MASK (0x0FFFFFFFu) @@ -1005,7 +1039,8 @@ typedef struct ecs_allocator_t ecs_allocator_t; #define ECS_GENERATION_INC(e) ((e & ~ECS_GENERATION_MASK) | ((0xFFFF & (ECS_GENERATION(e) + 1)) << 32)) #define ECS_COMPONENT_MASK (~ECS_ID_FLAGS_MASK) #define ECS_HAS_ID_FLAG(e, flag) ((e) & ECS_##flag) -#define ECS_IS_PAIR(id) (((id) & ECS_ID_FLAGS_MASK) == ECS_PAIR) +#define ECS_IS_VALUE_PAIR(id) (((id) & ECS_ID_FLAGS_MASK) == ECS_VALUE_PAIR) +#define ECS_IS_PAIR(id) ((((id) & ECS_ID_FLAGS_MASK) == ECS_PAIR) || ECS_IS_VALUE_PAIR(id)) #define ECS_PAIR_FIRST(e) (ecs_entity_t_hi(e & ECS_COMPONENT_MASK)) #define ECS_PAIR_SECOND(e) (ecs_entity_t_lo(e)) #define ECS_HAS_RELATION(e, rel) (ECS_HAS_ID_FLAG(e, PAIR) && (ECS_PAIR_FIRST(e) == rel)) @@ -1017,7 +1052,7 @@ typedef struct ecs_allocator_t ecs_allocator_t; //// Convert between C typenames and variables //////////////////////////////////////////////////////////////////////////////// -/** Translate C type to id. */ +/** Translate a C type to an ID. */ #define ecs_id(T) FLECS_ID##T##ID_ @@ -1029,13 +1064,15 @@ typedef struct ecs_allocator_t ecs_allocator_t; #define ecs_entity_t_hi(value) ECS_CAST(uint32_t, (value) >> 32) #define ecs_entity_t_comb(lo, hi) ((ECS_CAST(uint64_t, hi) << 32) + ECS_CAST(uint32_t, lo)) -#define ecs_pair(pred, obj) (ECS_PAIR | ecs_entity_t_comb(obj, pred)) -#define ecs_pair_t(pred, obj) (ECS_PAIR | ecs_entity_t_comb(obj, ecs_id(pred))) +#define ecs_pair(rel, tgt) (ECS_PAIR | ecs_entity_t_comb(tgt, rel)) +#define ecs_pair_t(rel, tgt) (ECS_PAIR | ecs_entity_t_comb(tgt, ecs_id(rel))) #define ecs_pair_first(world, pair) ecs_get_alive(world, ECS_PAIR_FIRST(pair)) #define ecs_pair_second(world, pair) ecs_get_alive(world, ECS_PAIR_SECOND(pair)) #define ecs_pair_relation ecs_pair_first #define ecs_pair_target ecs_pair_second +#define ecs_value_pair(rel, val) (ECS_VALUE_PAIR | ecs_entity_t_comb(val, rel)) + #define flecs_poly_id(tag) ecs_pair(ecs_id(EcsPoly), tag) @@ -1053,7 +1090,7 @@ typedef struct ecs_allocator_t ecs_allocator_t; //////////////////////////////////////////////////////////////////////////////// -//// Convenience macros for ctor, dtor, move and copy +//// Convenience macros for ctor, dtor, move, and copy //////////////////////////////////////////////////////////////////////////////// #ifndef FLECS_LEGACY @@ -1146,23 +1183,23 @@ typedef struct ecs_allocator_t ecs_allocator_t; * @{ */ -/** Ids are the things that can be added to an entity. - * An id can be an entity or pair, and can have optional id flags. */ +/** IDs are the things that can be added to an entity. + * An ID can be an entity or pair, and can have optional ID flags. */ typedef uint64_t ecs_id_t; /** An entity identifier. - * Entity ids consist out of a number unique to the entity in the lower 32 bits, + * Entity IDs consist of a number unique to the entity in the lower 32 bits, * and a counter used to track entity liveliness in the upper 32 bits. When an - * id is recycled, its generation count is increased. This causes recycled ids + * ID is recycled, its generation count is increased. This causes recycled IDs * to be very large (>4 billion), which is normal. */ typedef ecs_id_t ecs_entity_t; -/** A type is a list of (component) ids. - * Types are used to communicate the "type" of an entity. In most type systems a - * typeof operation returns a single type. In ECS however, an entity can have - * multiple components, which is why an ECS type consists of a vector of ids. +/** A type is a list of (component) IDs. + * Types are used to communicate the "type" of an entity. In most type systems, a + * typeof operation returns a single type. In ECS, however, an entity can have + * multiple components, which is why an ECS type consists of a vector of IDs. * - * The component ids of a type are sorted, which ensures that it doesn't matter + * The component IDs of a type are sorted, which ensures that it doesn't matter * in which order components are added to an entity. For example, if adding * Position then Velocity would result in type [Position, Velocity], first * adding Velocity then Position would also result in type [Position, Velocity]. @@ -1173,35 +1210,35 @@ typedef ecs_id_t ecs_entity_t; * also referred to as an archetype. */ typedef struct { - ecs_id_t *array; /**< Array with ids. */ + ecs_id_t *array; /**< Array with IDs. */ int32_t count; /**< Number of elements in array. */ } ecs_type_t; /** A world is the container for all ECS data and supporting features. * Applications can have multiple worlds, though in most cases will only need * one. Worlds are isolated from each other, and can have separate sets of - * systems, components, modules etc. + * systems, components, modules, etc. * * If an application has multiple worlds with overlapping components, it is - * common (though not strictly required) to use the same component ids across - * worlds, which can be achieved by declaring a global component id variable. + * common (though not strictly required) to use the same component IDs across + * worlds, which can be achieved by declaring a global component ID variable. * To do this in the C API, see the entities/fwd_component_decl example. The - * C++ API automatically synchronizes component ids between worlds. + * C++ API automatically synchronizes component IDs between worlds. * - * Component id conflicts between worlds can occur when a world has already used - * an id for something else. There are a few ways to avoid this: + * Component ID conflicts between worlds can occur when a world has already used + * an ID for something else. There are a few ways to avoid this: * * - Ensure to register the same components in each world, in the same order. - * - Create a dummy world in which all components are preregistered which - * initializes the global id variables. + * - Create a dummy world in which all components are preregistered, which + * initializes the global ID variables. * * In some use cases, typically when writing tests, multiple worlds are created * and deleted with different components, registered in different order. To * ensure isolation between tests, the C++ API has a `flecs::reset` function - * that forces the API to ignore the old component ids. */ + * that forces the API to ignore the old component IDs. */ typedef struct ecs_world_t ecs_world_t; -/** A stage enables modification while iterating and from multiple threads */ +/** A stage enables modification while iterating and from multiple threads. */ typedef struct ecs_stage_t ecs_stage_t; /** A table stores entities and components for a specific type. */ @@ -1215,7 +1252,7 @@ typedef struct ecs_query_t ecs_query_t; /** An observer is a system that is invoked when an event matches its query. * Observers allow applications to respond to specific events, such as adding or - * removing a component. Observers are created by both specifying a query and + * removing a component. Observers are created by specifying both a query and * a list of event kinds that should be listened for. An example of an observer * that triggers when a Position component is added to an entity (in C++): * @@ -1254,32 +1291,32 @@ typedef struct ecs_iter_t ecs_iter_t; typedef struct ecs_ref_t ecs_ref_t; /** Type hooks are callbacks associated with component lifecycle events. - * Typical examples of lifecycle events are construction, destruction, copying + * Typical examples of lifecycle events are construction, destruction, copying, * and moving of components. */ typedef struct ecs_type_hooks_t ecs_type_hooks_t; /** Type information. - * Contains information about a (component) type, such as its size and - * alignment and type hooks. */ + * Contains information about a (component) type, such as its size, + * alignment, and type hooks. */ typedef struct ecs_type_info_t ecs_type_info_t; /** Information about an entity, like its table and row. */ typedef struct ecs_record_t ecs_record_t; -/** Information about a (component) id, such as type info and tables with the id */ +/** Information about a (component) ID, such as type info and tables with the ID. */ typedef struct ecs_component_record_t ecs_component_record_t; /** A poly object. * A poly (short for polymorph) object is an object that has a variable list of * capabilities, determined by a mixin table. This is the current list of types - * in the flecs API that can be used as an ecs_poly_t: + * in the Flecs API that can be used as an ecs_poly_t: * * - ecs_world_t * - ecs_stage_t * - ecs_query_t * * Functions that accept an ecs_poly_t argument can accept objects of these - * types. If the object does not have the requested mixin the API will throw an + * types. If the object does not have the requested mixin, the API will throw an * assert. * * The poly/mixin framework enables partially overlapping features to be @@ -1290,16 +1327,17 @@ typedef struct ecs_component_record_t ecs_component_record_t; */ typedef void ecs_poly_t; -/** Type that stores poly mixins */ +/** Type that stores poly mixins. */ typedef struct ecs_mixins_t ecs_mixins_t; /** Header for ecs_poly_t objects. */ typedef struct ecs_header_t { - int32_t type; /**< Magic number indicating which type of flecs object */ - int32_t refcount; /**< Refcount, to enable RAII handles */ - ecs_mixins_t *mixins; /**< Table with offsets to (optional) mixins */ + int32_t type; /**< Magic number indicating which type of Flecs object. */ + int32_t refcount; /**< Refcount, to enable RAII handles. */ + ecs_mixins_t *mixins; /**< Table with offsets to (optional) mixins. */ } ecs_header_t; +/** Opaque type for table record. */ typedef struct ecs_table_record_t ecs_table_record_t; /** @} */ @@ -1319,15 +1357,22 @@ extern "C" { /** A component column. */ typedef struct ecs_vec_t { - void *array; - int32_t count; - int32_t size; + void *array; /**< Pointer to the element array. */ + int32_t count; /**< Number of elements in the vector. */ + int32_t size; /**< Allocated capacity in number of elements. */ #ifdef FLECS_SANITIZE - ecs_size_t elem_size; - const char *type_name; + ecs_size_t elem_size; /**< Size of each element in bytes (sanitize only). */ + const char *type_name; /**< Type name string for debugging (sanitize only). */ #endif } ecs_vec_t; +/** Initialize a vector. + * + * @param allocator Allocator to use for memory management. + * @param vec The vector to initialize. + * @param size Size of each element in bytes. + * @param elem_count Initial number of elements to allocate. + */ FLECS_API void ecs_vec_init( struct ecs_allocator_t *allocator, @@ -1335,6 +1380,14 @@ void ecs_vec_init( ecs_size_t size, int32_t elem_count); +/** Initialize a vector with debug info. + * + * @param allocator Allocator to use for memory management. + * @param vec The vector to initialize. + * @param size Size of each element in bytes. + * @param elem_count Initial number of elements to allocate. + * @param type_name Type name string for debugging. + */ FLECS_API void ecs_vec_init_w_dbg_info( struct ecs_allocator_t *allocator, @@ -1343,97 +1396,230 @@ void ecs_vec_init_w_dbg_info( int32_t elem_count, const char *type_name); +/** Type-safe vector initialization. + * + * @param allocator Allocator to use for memory management. + * @param vec The vector to initialize. + * @param T The element type. + * @param elem_count Initial number of elements to allocate. + */ #define ecs_vec_init_t(allocator, vec, T, elem_count) \ ecs_vec_init_w_dbg_info(allocator, vec, ECS_SIZEOF(T), elem_count, "vec<"#T">") +/** Initialize a vector if it is not already initialized. + * + * @param vec The vector to initialize. + * @param size Size of each element in bytes. + */ FLECS_API void ecs_vec_init_if( ecs_vec_t *vec, ecs_size_t size); +/** Type-safe conditional vector initialization. + * + * @param vec The vector to initialize. + * @param T The element type. + */ #define ecs_vec_init_if_t(vec, T) \ ecs_vec_init_if(vec, ECS_SIZEOF(T)) +/** Deinitialize a vector. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to deinitialize. + * @param size Size of each element in bytes. + */ FLECS_API void ecs_vec_fini( struct ecs_allocator_t *allocator, ecs_vec_t *vec, ecs_size_t size); +/** Type-safe vector deinitialization. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to deinitialize. + * @param T The element type. + */ #define ecs_vec_fini_t(allocator, vec, T) \ ecs_vec_fini(allocator, vec, ECS_SIZEOF(T)) +/** Reset a vector. Keeps allocated memory for reuse. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to reset. + * @param size Size of each element in bytes. + * @return Pointer to the reset vector. + */ FLECS_API ecs_vec_t* ecs_vec_reset( struct ecs_allocator_t *allocator, ecs_vec_t *vec, ecs_size_t size); +/** Type-safe vector reset. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to reset. + * @param T The element type. + */ #define ecs_vec_reset_t(allocator, vec, T) \ ecs_vec_reset(allocator, vec, ECS_SIZEOF(T)) +/** Clear a vector. Sets count to zero without freeing memory. + * + * @param vec The vector to clear. + */ FLECS_API void ecs_vec_clear( ecs_vec_t *vec); +/** Append a new element to the vector. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to append to. + * @param size Size of each element in bytes. + * @return Pointer to the newly appended element. + */ FLECS_API void* ecs_vec_append( struct ecs_allocator_t *allocator, ecs_vec_t *vec, ecs_size_t size); +/** Type-safe element append. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to append to. + * @param T The element type. + * @return Typed pointer to the newly appended element. + */ #define ecs_vec_append_t(allocator, vec, T) \ ECS_CAST(T*, ecs_vec_append(allocator, vec, ECS_SIZEOF(T))) +/** Remove an element by swapping with the last element. + * + * @param vec The vector to remove from. + * @param size Size of each element in bytes. + * @param elem Index of the element to remove. + */ FLECS_API void ecs_vec_remove( ecs_vec_t *vec, ecs_size_t size, int32_t elem); +/** Type-safe element removal (swap with last). + * + * @param vec The vector to remove from. + * @param T The element type. + * @param elem Index of the element to remove. + */ #define ecs_vec_remove_t(vec, T, elem) \ ecs_vec_remove(vec, ECS_SIZEOF(T), elem) +/** Remove an element while preserving order. + * + * @param v The vector to remove from. + * @param size Size of each element in bytes. + * @param index Index of the element to remove. + */ FLECS_API void ecs_vec_remove_ordered( ecs_vec_t *v, ecs_size_t size, int32_t index); +/** Type-safe ordered element removal. + * + * @param vec The vector to remove from. + * @param T The element type. + * @param elem Index of the element to remove. + */ #define ecs_vec_remove_ordered_t(vec, T, elem) \ ecs_vec_remove_ordered(vec, ECS_SIZEOF(T), elem) +/** Remove the last element from the vector. + * + * @param vec The vector to remove from. + */ FLECS_API void ecs_vec_remove_last( ecs_vec_t *vec); +/** Copy a vector. + * + * @param allocator Allocator used for memory management. + * @param vec The source vector to copy. + * @param size Size of each element in bytes. + * @return A new vector containing copies of all elements. + */ FLECS_API ecs_vec_t ecs_vec_copy( struct ecs_allocator_t *allocator, const ecs_vec_t *vec, ecs_size_t size); +/** Type-safe vector copy. + * + * @param allocator Allocator used for memory management. + * @param vec The source vector to copy. + * @param T The element type. + */ #define ecs_vec_copy_t(allocator, vec, T) \ ecs_vec_copy(allocator, vec, ECS_SIZEOF(T)) +/** Copy a vector and shrink to fit. + * + * @param allocator Allocator used for memory management. + * @param vec The source vector to copy. + * @param size Size of each element in bytes. + * @return A new vector with capacity shrunk to its count. + */ FLECS_API ecs_vec_t ecs_vec_copy_shrink( struct ecs_allocator_t *allocator, const ecs_vec_t *vec, ecs_size_t size); +/** Type-safe vector copy and shrink. + * + * @param allocator Allocator used for memory management. + * @param vec The source vector to copy. + * @param T The element type. + */ #define ecs_vec_copy_shrink_t(allocator, vec, T) \ ecs_vec_copy_shrink(allocator, vec, ECS_SIZEOF(T)) +/** Reclaim unused memory. Shrinks the vector's allocation to fit its count. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to reclaim memory from. + * @param size Size of each element in bytes. + */ FLECS_API void ecs_vec_reclaim( struct ecs_allocator_t *allocator, ecs_vec_t *vec, ecs_size_t size); +/** Type-safe memory reclaim. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to reclaim memory from. + * @param T The element type. + */ #define ecs_vec_reclaim_t(allocator, vec, T) \ ecs_vec_reclaim(allocator, vec, ECS_SIZEOF(T)) +/** Set the capacity of a vector. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to resize. + * @param size Size of each element in bytes. + * @param elem_count Desired capacity in number of elements. + */ FLECS_API void ecs_vec_set_size( struct ecs_allocator_t *allocator, @@ -1441,9 +1627,23 @@ void ecs_vec_set_size( ecs_size_t size, int32_t elem_count); +/** Type-safe set capacity. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to resize. + * @param T The element type. + * @param elem_count Desired capacity in number of elements. + */ #define ecs_vec_set_size_t(allocator, vec, T, elem_count) \ ecs_vec_set_size(allocator, vec, ECS_SIZEOF(T), elem_count) +/** Set the minimum capacity of a vector. Does not shrink. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to resize. + * @param size Size of each element in bytes. + * @param elem_count Minimum capacity in number of elements. + */ FLECS_API void ecs_vec_set_min_size( struct ecs_allocator_t *allocator, @@ -1451,9 +1651,24 @@ void ecs_vec_set_min_size( ecs_size_t size, int32_t elem_count); +/** Type-safe set minimum capacity. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to resize. + * @param T The element type. + * @param elem_count Minimum capacity in number of elements. + */ #define ecs_vec_set_min_size_t(allocator, vec, T, elem_count) \ ecs_vec_set_min_size(allocator, vec, ECS_SIZEOF(T), elem_count) +/** Set the minimum capacity using type info for lifecycle management. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to resize. + * @param size Size of each element in bytes. + * @param elem_count Minimum capacity in number of elements. + * @param ti Type info for lifecycle callbacks. + */ FLECS_API void ecs_vec_set_min_size_w_type_info( struct ecs_allocator_t *allocator, @@ -1462,6 +1677,13 @@ void ecs_vec_set_min_size_w_type_info( int32_t elem_count, const ecs_type_info_t *ti); +/** Set the minimum count. Increases count if smaller than elem_count. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param size Size of each element in bytes. + * @param elem_count Minimum element count. + */ FLECS_API void ecs_vec_set_min_count( struct ecs_allocator_t *allocator, @@ -1469,9 +1691,23 @@ void ecs_vec_set_min_count( ecs_size_t size, int32_t elem_count); +/** Type-safe set minimum count. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param T The element type. + * @param elem_count Minimum element count. + */ #define ecs_vec_set_min_count_t(allocator, vec, T, elem_count) \ ecs_vec_set_min_count(allocator, vec, ECS_SIZEOF(T), elem_count) +/** Set the minimum count and zero-initialize new elements. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param size Size of each element in bytes. + * @param elem_count Minimum element count. + */ FLECS_API void ecs_vec_set_min_count_zeromem( struct ecs_allocator_t *allocator, @@ -1479,9 +1715,23 @@ void ecs_vec_set_min_count_zeromem( ecs_size_t size, int32_t elem_count); +/** Type-safe set minimum count with zero-initialization. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param T The element type. + * @param elem_count Minimum element count. + */ #define ecs_vec_set_min_count_zeromem_t(allocator, vec, T, elem_count) \ ecs_vec_set_min_count_zeromem(allocator, vec, ECS_SIZEOF(T), elem_count) +/** Set the element count of a vector. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param size Size of each element in bytes. + * @param elem_count Desired element count. + */ FLECS_API void ecs_vec_set_count( struct ecs_allocator_t *allocator, @@ -1489,9 +1739,24 @@ void ecs_vec_set_count( ecs_size_t size, int32_t elem_count); +/** Type-safe set element count. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param T The element type. + * @param elem_count Desired element count. + */ #define ecs_vec_set_count_t(allocator, vec, T, elem_count) \ ecs_vec_set_count(allocator, vec, ECS_SIZEOF(T), elem_count) +/** Set the element count using type info for lifecycle management. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param size Size of each element in bytes. + * @param elem_count Desired element count. + * @param ti Type info for lifecycle callbacks. + */ FLECS_API void ecs_vec_set_count_w_type_info( struct ecs_allocator_t *allocator, @@ -1500,6 +1765,14 @@ void ecs_vec_set_count_w_type_info( int32_t elem_count, const ecs_type_info_t *ti); +/** Set the minimum count using type info for lifecycle management. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to modify. + * @param size Size of each element in bytes. + * @param elem_count Minimum element count. + * @param ti Type info for lifecycle callbacks. + */ FLECS_API void ecs_vec_set_min_count_w_type_info( struct ecs_allocator_t *allocator, @@ -1508,6 +1781,14 @@ void ecs_vec_set_min_count_w_type_info( int32_t elem_count, const ecs_type_info_t *ti); +/** Grow the vector by a number of elements. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to grow. + * @param size Size of each element in bytes. + * @param elem_count Number of elements to grow by. + * @return Pointer to the first newly added element. + */ FLECS_API void* ecs_vec_grow( struct ecs_allocator_t *allocator, @@ -1515,38 +1796,92 @@ void* ecs_vec_grow( ecs_size_t size, int32_t elem_count); +/** Type-safe vector grow. + * + * @param allocator Allocator used for memory management. + * @param vec The vector to grow. + * @param T The element type. + * @param elem_count Number of elements to grow by. + */ #define ecs_vec_grow_t(allocator, vec, T, elem_count) \ ecs_vec_grow(allocator, vec, ECS_SIZEOF(T), elem_count) +/** Return the number of elements in the vector. + * + * @param vec The vector. + * @return The number of elements. + */ FLECS_API int32_t ecs_vec_count( const ecs_vec_t *vec); +/** Return the allocated capacity of the vector. + * + * @param vec The vector. + * @return The allocated capacity in number of elements. + */ FLECS_API int32_t ecs_vec_size( const ecs_vec_t *vec); +/** Get a pointer to an element at the given index. + * + * @param vec The vector. + * @param size Size of each element in bytes. + * @param index Index of the element to retrieve. + * @return Pointer to the element. + */ FLECS_API void* ecs_vec_get( const ecs_vec_t *vec, ecs_size_t size, int32_t index); +/** Type-safe element access by index. + * + * @param vec The vector. + * @param T The element type. + * @param index Index of the element to retrieve. + * @return Typed pointer to the element. + */ #define ecs_vec_get_t(vec, T, index) \ ECS_CAST(T*, ecs_vec_get(vec, ECS_SIZEOF(T), index)) +/** Get a pointer to the first element. + * + * @param vec The vector. + * @return Pointer to the first element, or NULL if empty. + */ FLECS_API void* ecs_vec_first( const ecs_vec_t *vec); +/** Type-safe access to the first element. + * + * @param vec The vector. + * @param T The element type. + * @return Typed pointer to the first element, or NULL if empty. + */ #define ecs_vec_first_t(vec, T) \ ECS_CAST(T*, ecs_vec_first(vec)) +/** Get a pointer to the last element. + * + * @param vec The vector. + * @param size Size of each element in bytes. + * @return Pointer to the last element, or NULL if empty. + */ FLECS_API void* ecs_vec_last( const ecs_vec_t *vec, ecs_size_t size); +/** Type-safe access to the last element. + * + * @param vec The vector. + * @param T The element type. + * @return Typed pointer to the last element, or NULL if empty. + */ #define ecs_vec_last_t(vec, T) \ ECS_CAST(T*, ecs_vec_last(vec, ECS_SIZEOF(T))) @@ -1569,36 +1904,43 @@ void* ecs_vec_last( extern "C" { #endif -/** The number of elements in a single page */ +/** The number of elements in a single page. */ #define FLECS_SPARSE_PAGE_SIZE (1 << FLECS_SPARSE_PAGE_BITS) -/** Compute the page index from an id by stripping the first 12 bits */ +/** Compute the page index from an ID by stripping the first 12 bits. */ #define FLECS_SPARSE_PAGE(index) ((int32_t)((uint32_t)index >> FLECS_SPARSE_PAGE_BITS)) -/** This computes the offset of an index inside a page */ +/** Compute the offset of an index inside a page. */ #define FLECS_SPARSE_OFFSET(index) ((int32_t)index & (FLECS_SPARSE_PAGE_SIZE - 1)) +/** A page in the sparse set containing a sparse-to-dense mapping and data. */ typedef struct ecs_sparse_page_t { - int32_t *sparse; /* Sparse array with indices to dense array */ - void *data; /* Store data in sparse array to reduce - * indirection and provide stable pointers. */ + int32_t *sparse; /**< Sparse array with indices to dense array. */ + void *data; /**< Store data in sparse array to reduce + * indirection and provide stable pointers. */ } ecs_sparse_page_t; +/** A sparse set data structure for O(1) access with stable pointers. */ typedef struct ecs_sparse_t { - ecs_vec_t dense; /* Dense array with indices to sparse array. The - * dense array stores both alive and not alive - * sparse indices. The 'count' member keeps - * track of which indices are alive. */ - - ecs_vec_t pages; /* Chunks with sparse arrays & data */ - ecs_size_t size; /* Element size */ - int32_t count; /* Number of alive entries */ - uint64_t max_id; /* Local max index (if no global is set) */ - struct ecs_allocator_t *allocator; - struct ecs_block_allocator_t *page_allocator; + ecs_vec_t dense; /**< Dense array with indices to sparse array. The + * dense array stores both alive and not alive + * sparse indices. The 'count' member keeps + * track of which indices are alive. */ + ecs_vec_t pages; /**< Chunks with sparse arrays and data. */ + ecs_size_t size; /**< Element size in bytes. */ + int32_t count; /**< Number of alive entries. */ + uint64_t max_id; /**< Local max index (if no global is set). */ + struct ecs_allocator_t *allocator; /**< Allocator for general allocations. */ + struct ecs_block_allocator_t *page_allocator; /**< Allocator for page allocations. */ } ecs_sparse_t; -/** Initialize sparse set */ +/** Initialize a sparse set. + * + * @param result The sparse set to initialize. + * @param allocator Allocator for general memory management. + * @param page_allocator Block allocator for page allocations. + * @param size Size of each element in bytes. + */ FLECS_DBG_API void flecs_sparse_init( ecs_sparse_t *result, @@ -1606,104 +1948,221 @@ void flecs_sparse_init( struct ecs_block_allocator_t *page_allocator, ecs_size_t size); +/** Typed sparse set initialization. + * + * @param result The sparse set to initialize. + * @param allocator Allocator for general memory management. + * @param page_allocator Block allocator for page allocations. + * @param T The element type. + */ #define flecs_sparse_init_t(result, allocator, page_allocator, T)\ flecs_sparse_init(result, allocator, page_allocator, ECS_SIZEOF(T)) +/** Deinitialize a sparse set. + * + * @param sparse The sparse set to deinitialize. + */ FLECS_DBG_API void flecs_sparse_fini( ecs_sparse_t *sparse); -/** Remove all elements from sparse set */ +/** Remove all elements from a sparse set. + * + * @param sparse The sparse set to clear. + */ FLECS_DBG_API void flecs_sparse_clear( ecs_sparse_t *sparse); -/** Add element to sparse set, this generates or recycles an id */ +/** Add an element to a sparse set. This generates or recycles an ID. + * + * @param sparse The sparse set to add to. + * @param elem_size Size of each element in bytes. + * @return Pointer to the newly added element. + */ FLECS_DBG_API void* flecs_sparse_add( ecs_sparse_t *sparse, ecs_size_t elem_size); +/** Typed element add. + * + * @param sparse The sparse set to add to. + * @param T The element type. + * @return Typed pointer to the newly added element. + */ #define flecs_sparse_add_t(sparse, T)\ ECS_CAST(T*, flecs_sparse_add(sparse, ECS_SIZEOF(T))) -/** Get last issued id. */ +/** Get the last issued ID. + * + * @param sparse The sparse set. + * @return The last issued ID. + */ FLECS_DBG_API uint64_t flecs_sparse_last_id( const ecs_sparse_t *sparse); -/** Generate or recycle a new id. */ +/** Generate or recycle a new ID. + * + * @param sparse The sparse set. + * @return A new or recycled ID. + */ FLECS_DBG_API uint64_t flecs_sparse_new_id( ecs_sparse_t *sparse); -/** Remove an element */ +/** Remove an element. + * + * @param sparse The sparse set to remove from. + * @param size Size of each element in bytes. + * @param id The ID of the element to remove. + * @return True if the element was found and removed. + */ FLECS_DBG_API bool flecs_sparse_remove( ecs_sparse_t *sparse, ecs_size_t size, uint64_t id); +/** Typed element removal. + * + * @param sparse The sparse set to remove from. + * @param T The element type. + * @param id The ID of the element to remove. + */ #define flecs_sparse_remove_t(sparse, T, id)\ flecs_sparse_remove(sparse, ECS_SIZEOF(T), id) -/** Remove an element, increase generation */ +/** Remove an element and increase the generation. + * + * @param sparse The sparse set to remove from. + * @param size Size of each element in bytes. + * @param id The ID of the element to remove. + * @return True if the element was found and removed. + */ bool flecs_sparse_remove_w_gen( ecs_sparse_t *sparse, ecs_size_t size, uint64_t id); +/** Typed element removal with generation increase. + * + * @param sparse The sparse set to remove from. + * @param T The element type. + * @param id The ID of the element to remove. + */ #define flecs_sparse_remove_w_gen_t(sparse, T, id)\ flecs_sparse_remove_w_gen(sparse, ECS_SIZEOF(T), id) -/** Test if id is alive, which requires the generation count to match. */ +/** Test if an ID is alive, which requires the generation count to match. + * + * @param sparse The sparse set to check. + * @param id The ID to test for liveness. + * @return True if the ID is alive. + */ FLECS_DBG_API bool flecs_sparse_is_alive( const ecs_sparse_t *sparse, uint64_t id); -/** Get value from sparse set by dense id. This function is useful in - * combination with flecs_sparse_count for iterating all values in the set. */ +/** Get a value from a sparse set by dense ID. This function is useful in + * combination with flecs_sparse_count() for iterating all values in the set. + * + * @param sparse The sparse set to retrieve from. + * @param elem_size Size of each element in bytes. + * @param index Dense index of the element. + * @return Pointer to the element at the given dense index. + */ FLECS_DBG_API void* flecs_sparse_get_dense( const ecs_sparse_t *sparse, ecs_size_t elem_size, int32_t index); +/** Typed get by dense index. + * + * @param sparse The sparse set to retrieve from. + * @param T The element type. + * @param index Dense index of the element. + * @return Typed pointer to the element. + */ #define flecs_sparse_get_dense_t(sparse, T, index)\ ECS_CAST(T*, flecs_sparse_get_dense(sparse, ECS_SIZEOF(T), index)) -/** Get the number of alive elements in the sparse set. */ +/** Get the number of alive elements in the sparse set. + * + * @param sparse The sparse set. + * @return The number of alive elements. + */ FLECS_DBG_API int32_t flecs_sparse_count( const ecs_sparse_t *sparse); -/** Check if sparse set has id */ +/** Check if a sparse set has an ID. + * + * @param sparse The sparse set to check. + * @param id The ID to look for. + * @return True if the sparse set contains the ID. + */ bool flecs_sparse_has( const ecs_sparse_t *sparse, uint64_t id); -/** Like get_sparse, but don't care whether element is alive or not. */ +/** Get element by sparse ID, regardless of whether the element is alive or not. + * + * @param sparse The sparse set to retrieve from. + * @param elem_size Size of each element in bytes. + * @param id The sparse ID of the element. + * @return Pointer to the element, regardless of liveness. + */ FLECS_DBG_API void* flecs_sparse_get( const ecs_sparse_t *sparse, ecs_size_t elem_size, uint64_t id); +/** Typed get by sparse ID. + * + * @param sparse The sparse set to retrieve from. + * @param T The element type. + * @param index The sparse ID of the element. + * @return Typed pointer to the element. + */ #define flecs_sparse_get_t(sparse, T, index)\ ECS_CAST(T*, flecs_sparse_get(sparse, ECS_SIZEOF(T), index)) -/** Create element by (sparse) id. */ +/** Create an element by (sparse) ID. + * + * @param sparse The sparse set to insert into. + * @param elem_size Size of each element in bytes. + * @param id The sparse ID for the new element. + * @return Pointer to the newly created element. + */ FLECS_DBG_API void* flecs_sparse_insert( ecs_sparse_t *sparse, ecs_size_t elem_size, uint64_t id); +/** Typed insert by sparse ID. + * + * @param sparse The sparse set to insert into. + * @param T The element type. + * @param index The sparse ID for the new element. + * @return Typed pointer to the newly created element. + */ #define flecs_sparse_insert_t(sparse, T, index)\ ECS_CAST(T*, flecs_sparse_insert(sparse, ECS_SIZEOF(T), index)) -/** Get or create element by (sparse) id. */ +/** Get or create an element by (sparse) ID. + * + * @param sparse The sparse set. + * @param elem_size Size of each element in bytes. + * @param id The sparse ID to get or create. + * @param is_new Output parameter set to true if a new element was created. + * @return Pointer to the existing or newly created element. + */ FLECS_DBG_API void* flecs_sparse_ensure( ecs_sparse_t *sparse, @@ -1711,71 +2170,160 @@ void* flecs_sparse_ensure( uint64_t id, bool *is_new); +/** Typed get or create by sparse ID. + * + * @param sparse The sparse set. + * @param T The element type. + * @param index The sparse ID to get or create. + * @param is_new Output parameter set to true if a new element was created. + * @return Typed pointer to the element. + */ #define flecs_sparse_ensure_t(sparse, T, index, is_new)\ ECS_CAST(T*, flecs_sparse_ensure(sparse, ECS_SIZEOF(T), index, is_new)) -/** Fast version of ensure, no liveliness checking */ +/** Fast version of ensure with no liveness checking. + * + * @param sparse The sparse set. + * @param elem_size Size of each element in bytes. + * @param id The sparse ID to get or create. + * @return Pointer to the element. + */ FLECS_DBG_API void* flecs_sparse_ensure_fast( ecs_sparse_t *sparse, ecs_size_t elem_size, uint64_t id); +/** Typed fast ensure without liveness checking. + * + * @param sparse The sparse set. + * @param T The element type. + * @param index The sparse ID to get or create. + * @return Typed pointer to the element. + */ #define flecs_sparse_ensure_fast_t(sparse, T, index)\ ECS_CAST(T*, flecs_sparse_ensure_fast(sparse, ECS_SIZEOF(T), index)) -/** Get pointer to ids (alive and not alive). Use with count() or size(). */ +/** Get a pointer to IDs (alive and not alive). Use with flecs_sparse_count(). + * + * @param sparse The sparse set. + * @return Pointer to the dense array of IDs. + */ FLECS_DBG_API const uint64_t* flecs_sparse_ids( const ecs_sparse_t *sparse); +/** Shrink sparse set memory to fit current usage. + * + * @param sparse The sparse set to shrink. + */ FLECS_DBG_API void flecs_sparse_shrink( ecs_sparse_t *sparse); -/* Publicly exposed APIs - * These APIs are not part of the public API and as a result may change without - * notice (though they haven't changed in a long time). */ +/** Exposed but unstable APIs. + * These APIs are visible in the header but not part of the stable public API, + * and as a result may change without notice. */ +/** Initialize a public sparse set. + * + * @param sparse The sparse set to initialize. + * @param elem_size Size of each element in bytes. + */ FLECS_API void ecs_sparse_init( ecs_sparse_t *sparse, ecs_size_t elem_size); +/** Typed public sparse set initialization. + * + * @param sparse The sparse set to initialize. + * @param T The element type. + */ #define ecs_sparse_init_t(sparse, T)\ ecs_sparse_init(sparse, ECS_SIZEOF(T)) +/** Add an element to a public sparse set. + * + * @param sparse The sparse set to add to. + * @param elem_size Size of each element in bytes. + * @return Pointer to the newly added element. + */ FLECS_API void* ecs_sparse_add( ecs_sparse_t *sparse, ecs_size_t elem_size); +/** Typed public sparse set add. + * + * @param sparse The sparse set to add to. + * @param T The element type. + * @return Typed pointer to the newly added element. + */ #define ecs_sparse_add_t(sparse, T)\ ECS_CAST(T*, ecs_sparse_add(sparse, ECS_SIZEOF(T))) +/** Get the last issued ID from a public sparse set. + * + * @param sparse The sparse set. + * @return The last issued ID. + */ FLECS_API uint64_t ecs_sparse_last_id( const ecs_sparse_t *sparse); +/** Get the number of alive elements in a public sparse set. + * + * @param sparse The sparse set. + * @return The number of alive elements. + */ FLECS_API int32_t ecs_sparse_count( const ecs_sparse_t *sparse); +/** Get a value from a public sparse set by dense index. + * + * @param sparse The sparse set. + * @param elem_size Size of each element in bytes. + * @param index Dense index of the element. + * @return Pointer to the element. + */ FLECS_API void* ecs_sparse_get_dense( const ecs_sparse_t *sparse, ecs_size_t elem_size, int32_t index); +/** Typed public get by dense index. + * + * @param sparse The sparse set. + * @param T The element type. + * @param index Dense index of the element. + * @return Typed pointer to the element. + */ #define ecs_sparse_get_dense_t(sparse, T, index)\ ECS_CAST(T*, ecs_sparse_get_dense(sparse, ECS_SIZEOF(T), index)) +/** Get a value from a public sparse set by sparse ID. + * + * @param sparse The sparse set. + * @param elem_size Size of each element in bytes. + * @param id The sparse ID of the element. + * @return Pointer to the element. + */ FLECS_API void* ecs_sparse_get( const ecs_sparse_t *sparse, ecs_size_t elem_size, uint64_t id); +/** Typed public get by sparse ID. + * + * @param sparse The sparse set. + * @param T The element type. + * @param index The sparse ID of the element. + * @return Typed pointer to the element. + */ #define ecs_sparse_get_t(sparse, T, index)\ ECS_CAST(T*, ecs_sparse_get(sparse, ECS_SIZEOF(T), index)) @@ -1794,104 +2342,186 @@ void* ecs_sparse_get( #define FLECS_BLOCK_ALLOCATOR_H +/** Forward declaration of map type. */ typedef struct ecs_map_t ecs_map_t; +/** A block of memory managed by the block allocator. */ typedef struct ecs_block_allocator_block_t { - void *memory; - struct ecs_block_allocator_block_t *next; + void *memory; /**< Pointer to the block memory. */ + struct ecs_block_allocator_block_t *next; /**< Next block in the list. */ } ecs_block_allocator_block_t; +/** Header for a free chunk in the block allocator free list. */ typedef struct ecs_block_allocator_chunk_header_t { - struct ecs_block_allocator_chunk_header_t *next; + struct ecs_block_allocator_chunk_header_t *next; /**< Next free chunk. */ } ecs_block_allocator_chunk_header_t; +/** Block allocator that returns fixed-size memory blocks. */ typedef struct ecs_block_allocator_t { - int32_t data_size; + int32_t data_size; /**< Size of each allocation. */ #ifndef FLECS_USE_OS_ALLOC - int32_t chunk_size; - int32_t chunks_per_block; - int32_t block_size; - ecs_block_allocator_chunk_header_t *head; - ecs_block_allocator_block_t *block_head; + int32_t chunk_size; /**< Aligned chunk size including header. */ + int32_t chunks_per_block; /**< Number of chunks per block. */ + int32_t block_size; /**< Total size of each allocated block. */ + ecs_block_allocator_chunk_header_t *head; /**< Head of the free chunk list. */ + ecs_block_allocator_block_t *block_head; /**< Head of the allocated block list. */ #ifdef FLECS_SANITIZE - int32_t alloc_count; - ecs_map_t *outstanding; + int32_t alloc_count; /**< Number of outstanding allocations (sanitizer only). */ + ecs_map_t *outstanding; /**< Map of outstanding allocations (sanitizer only). */ #endif #endif } ecs_block_allocator_t; +/** Initialize a block allocator. + * + * @param ba The block allocator to initialize. + * @param size The size of each allocation. + */ FLECS_API void flecs_ballocator_init( ecs_block_allocator_t *ba, ecs_size_t size); +/** Initialize a block allocator for type T. */ #define flecs_ballocator_init_t(ba, T)\ flecs_ballocator_init(ba, ECS_SIZEOF(T)) + +/** Initialize a block allocator for count elements of type T. */ #define flecs_ballocator_init_n(ba, T, count)\ flecs_ballocator_init(ba, ECS_SIZEOF(T) * count) +/** Create a new block allocator on the heap. + * + * @param size The size of each allocation. + * @return The new block allocator. + */ FLECS_API ecs_block_allocator_t* flecs_ballocator_new( ecs_size_t size); +/** Create a new block allocator for type T. */ #define flecs_ballocator_new_t(T)\ flecs_ballocator_new(ECS_SIZEOF(T)) + +/** Create a new block allocator for count elements of type T. */ #define flecs_ballocator_new_n(T, count)\ flecs_ballocator_new(ECS_SIZEOF(T) * count) +/** Deinitialize a block allocator. + * + * @param ba The block allocator to deinitialize. + */ FLECS_API void flecs_ballocator_fini( ecs_block_allocator_t *ba); +/** Free a block allocator created with flecs_ballocator_new(). + * + * @param ba The block allocator to free. + */ FLECS_API void flecs_ballocator_free( ecs_block_allocator_t *ba); +/** Allocate a block of memory. + * + * @param allocator The block allocator. + * @return Pointer to the allocated memory. + */ FLECS_API void* flecs_balloc( ecs_block_allocator_t *allocator); +/** Allocate a block of memory with debug type name info. + * + * @param allocator The block allocator. + * @param type_name The type name for debug tracking. + * @return Pointer to the allocated memory. + */ FLECS_API void* flecs_balloc_w_dbg_info( ecs_block_allocator_t *allocator, const char *type_name); +/** Allocate a zeroed block of memory. + * + * @param allocator The block allocator. + * @return Pointer to the zeroed memory. + */ FLECS_API void* flecs_bcalloc( ecs_block_allocator_t *allocator); +/** Allocate a zeroed block of memory with debug type name info. + * + * @param allocator The block allocator. + * @param type_name The type name for debug tracking. + * @return Pointer to the zeroed memory. + */ FLECS_API void* flecs_bcalloc_w_dbg_info( ecs_block_allocator_t *allocator, const char *type_name); +/** Free a block of memory. + * + * @param allocator The block allocator. + * @param memory The memory to free. + */ FLECS_API void flecs_bfree( - ecs_block_allocator_t *allocator, + ecs_block_allocator_t *allocator, void *memory); +/** Free a block of memory with debug type name info. + * + * @param allocator The block allocator. + * @param memory The memory to free. + * @param type_name The type name for debug tracking. + */ FLECS_API void flecs_bfree_w_dbg_info( - ecs_block_allocator_t *allocator, + ecs_block_allocator_t *allocator, void *memory, const char *type_name); +/** Reallocate a block from one block allocator to another. + * + * @param dst The destination block allocator. + * @param src The source block allocator. + * @param memory The memory to reallocate. + * @return Pointer to the reallocated memory. + */ FLECS_API void* flecs_brealloc( - ecs_block_allocator_t *dst, - ecs_block_allocator_t *src, + ecs_block_allocator_t *dst, + ecs_block_allocator_t *src, void *memory); +/** Reallocate a block with debug type name info. + * + * @param dst The destination block allocator. + * @param src The source block allocator. + * @param memory The memory to reallocate. + * @param type_name The type name for debug tracking. + * @return Pointer to the reallocated memory. + */ FLECS_API void* flecs_brealloc_w_dbg_info( - ecs_block_allocator_t *dst, - ecs_block_allocator_t *src, + ecs_block_allocator_t *dst, + ecs_block_allocator_t *src, void *memory, const char *type_name); +/** Duplicate a block of memory. + * + * @param ba The block allocator. + * @param memory The memory to duplicate. + * @return Pointer to the duplicated memory. + */ FLECS_API void* flecs_bdup( - ecs_block_allocator_t *ba, + ecs_block_allocator_t *ba, void *memory); #endif @@ -1904,87 +2534,138 @@ void* flecs_bdup( #ifndef FLECS_STACK_ALLOCATOR_H #define FLECS_STACK_ALLOCATOR_H -/** Stack allocator for quick allocation of small temporary values */ - +/** A page of memory in the stack allocator. */ typedef struct ecs_stack_page_t { - void *data; - struct ecs_stack_page_t *next; - int16_t sp; - uint32_t id; + void *data; /**< Pointer to the page data. */ + struct ecs_stack_page_t *next; /**< Next page in the list. */ + int16_t sp; /**< Current stack pointer within the page. */ + uint32_t id; /**< Page identifier. */ } ecs_stack_page_t; +/** Cursor that marks a position in the stack allocator for later restoration. */ typedef struct ecs_stack_cursor_t { - struct ecs_stack_cursor_t *prev; - struct ecs_stack_page_t *page; - int16_t sp; - bool is_free; + struct ecs_stack_cursor_t *prev; /**< Previous cursor in the stack. */ + struct ecs_stack_page_t *page; /**< Page at the cursor position. */ + int16_t sp; /**< Stack pointer at the cursor position. */ + bool is_free; /**< Whether this cursor has been freed. */ #ifdef FLECS_DEBUG - struct ecs_stack_t *owner; + struct ecs_stack_t *owner; /**< Stack allocator that owns this cursor (debug only). */ #endif } ecs_stack_cursor_t; +/** Stack allocator for quick allocation of small temporary values. */ typedef struct ecs_stack_t { - ecs_stack_page_t *first; - ecs_stack_page_t *tail_page; - ecs_stack_cursor_t *tail_cursor; + ecs_stack_page_t *first; /**< First page in the stack. */ + ecs_stack_page_t *tail_page; /**< Current tail page. */ + ecs_stack_cursor_t *tail_cursor; /**< Current tail cursor. */ #ifdef FLECS_DEBUG - int32_t cursor_count; + int32_t cursor_count; /**< Number of active cursors (debug only). */ #endif } ecs_stack_t; +/** Offset of usable data within a stack page (aligned to 16 bytes). */ #define FLECS_STACK_PAGE_OFFSET ECS_ALIGN(ECS_SIZEOF(ecs_stack_page_t), 16) + +/** Size of usable data within a stack page. */ #define FLECS_STACK_PAGE_SIZE (1024 - FLECS_STACK_PAGE_OFFSET) +/** Initialize a stack allocator. + * + * @param stack The stack allocator to initialize. + */ FLECS_DBG_API void flecs_stack_init( ecs_stack_t *stack); +/** Deinitialize a stack allocator. + * + * @param stack The stack allocator to deinitialize. + */ FLECS_DBG_API void flecs_stack_fini( ecs_stack_t *stack); +/** Allocate memory from the stack. + * + * @param stack The stack allocator. + * @param size The allocation size. + * @param align The required alignment. + * @return Pointer to the allocated memory. + */ FLECS_DBG_API void* flecs_stack_alloc( - ecs_stack_t *stack, + ecs_stack_t *stack, ecs_size_t size, ecs_size_t align); +/** Allocate memory for a single element of type T from the stack. */ #define flecs_stack_alloc_t(stack, T)\ flecs_stack_alloc(stack, ECS_SIZEOF(T), ECS_ALIGNOF(T)) +/** Allocate memory for count elements of type T from the stack. */ #define flecs_stack_alloc_n(stack, T, count)\ flecs_stack_alloc(stack, ECS_SIZEOF(T) * count, ECS_ALIGNOF(T)) +/** Allocate zeroed memory from the stack. + * + * @param stack The stack allocator. + * @param size The allocation size. + * @param align The required alignment. + * @return Pointer to the zeroed memory. + */ FLECS_DBG_API void* flecs_stack_calloc( - ecs_stack_t *stack, + ecs_stack_t *stack, ecs_size_t size, ecs_size_t align); +/** Allocate zeroed memory for a single element of type T from the stack. */ #define flecs_stack_calloc_t(stack, T)\ flecs_stack_calloc(stack, ECS_SIZEOF(T), ECS_ALIGNOF(T)) +/** Allocate zeroed memory for count elements of type T from the stack. */ #define flecs_stack_calloc_n(stack, T, count)\ flecs_stack_calloc(stack, ECS_SIZEOF(T) * count, ECS_ALIGNOF(T)) +/** Free memory allocated from the stack. + * + * @param ptr The pointer to free. + * @param size The size of the allocation. + */ FLECS_DBG_API void flecs_stack_free( void *ptr, ecs_size_t size); +/** Free memory for a single element of type T from the stack. */ #define flecs_stack_free_t(ptr, T)\ flecs_stack_free(ptr, ECS_SIZEOF(T)) +/** Free memory for count elements of type T from the stack. */ #define flecs_stack_free_n(ptr, T, count)\ flecs_stack_free(ptr, ECS_SIZEOF(T) * count) +/** Reset the stack allocator. + * + * @param stack The stack allocator to reset. + */ void flecs_stack_reset( ecs_stack_t *stack); +/** Get a cursor marking the current position in the stack. + * + * @param stack The stack allocator. + * @return A cursor that can be used to restore the stack. + */ FLECS_DBG_API ecs_stack_cursor_t* flecs_stack_get_cursor( ecs_stack_t *stack); +/** Restore the stack to a previously saved cursor position. + * + * @param stack The stack allocator. + * @param cursor The cursor to restore to. + */ FLECS_DBG_API void flecs_stack_restore_cursor( ecs_stack_t *stack, @@ -2005,169 +2686,272 @@ void flecs_stack_restore_cursor( extern "C" { #endif +/** Data type for map key-value storage. */ typedef uint64_t ecs_map_data_t; + +/** Map key type. */ typedef ecs_map_data_t ecs_map_key_t; + +/** Map value type. */ typedef ecs_map_data_t ecs_map_val_t; -/* Map type */ +/** A single entry in a map bucket (linked list node). */ typedef struct ecs_bucket_entry_t { - ecs_map_key_t key; - ecs_map_val_t value; - struct ecs_bucket_entry_t *next; + ecs_map_key_t key; /**< Key of the entry. */ + ecs_map_val_t value; /**< Value of the entry. */ + struct ecs_bucket_entry_t *next; /**< Next entry in the bucket chain. */ } ecs_bucket_entry_t; +/** A bucket in the map hash table. */ typedef struct ecs_bucket_t { - ecs_bucket_entry_t *first; + ecs_bucket_entry_t *first; /**< First entry in this bucket. */ } ecs_bucket_t; +/** A hashmap data structure. */ struct ecs_map_t { - ecs_bucket_t *buckets; - int32_t bucket_count; - unsigned count : 26; - unsigned bucket_shift : 6; - struct ecs_allocator_t *allocator; + ecs_bucket_t *buckets; /**< Array of hash buckets. */ + int32_t bucket_count; /**< Total number of buckets. */ + unsigned count : 26; /**< Number of elements in the map. */ + unsigned bucket_shift : 6; /**< Bit shift for bucket index computation. */ + struct ecs_allocator_t *allocator; /**< Allocator used for memory management. */ #ifdef FLECS_DEBUG - int32_t change_count; /* Track modifications while iterating */ - ecs_map_key_t last_iterated; /* Currently iterated element */ + int32_t change_count; /**< Track modifications while iterating. */ + ecs_map_key_t last_iterated; /**< Currently iterated element. */ #endif }; +/** Iterator for traversing map contents. */ typedef struct ecs_map_iter_t { - const ecs_map_t *map; - ecs_bucket_t *bucket; - ecs_bucket_entry_t *entry; - ecs_map_data_t *res; + const ecs_map_t *map; /**< The map being iterated. */ + ecs_bucket_t *bucket; /**< Current bucket. */ + ecs_bucket_entry_t *entry; /**< Current entry in the bucket. */ + ecs_map_data_t *res; /**< Pointer to current key-value pair. */ #ifdef FLECS_DEBUG - int32_t change_count; + int32_t change_count; /**< Change count at iterator creation for modification detection. */ #endif } ecs_map_iter_t; -/* Function/macro postfixes meaning: - * _ptr: access ecs_map_val_t as void* - * _ref: access ecs_map_val_t* as T** - * _deref: dereferences a _ref - * _alloc: if _ptr is NULL, alloc - * _free: if _ptr is not NULL, free +/** Function and macro postfix meanings: + * - _ptr: Access ecs_map_val_t as void*. + * - _ref: Access ecs_map_val_t* as T**. + * - _deref: Dereference a _ref. + * - _alloc: If _ptr is NULL, alloc. + * - _free: If _ptr is not NULL, free. */ -/** Initialize new map. */ +/** Initialize a new map. + * + * @param map The map to initialize. + * @param allocator Allocator to use for memory management. + */ FLECS_API void ecs_map_init( ecs_map_t *map, struct ecs_allocator_t *allocator); -/** Initialize new map if uninitialized, leave as is otherwise */ +/** Initialize a new map if uninitialized, leave as is otherwise. + * + * @param map The map to initialize. + * @param allocator Allocator to use for memory management. + */ FLECS_API void ecs_map_init_if( ecs_map_t *map, struct ecs_allocator_t *allocator); -/** Reclaim map memory. */ +/** Reclaim map memory. + * + * @param map The map to reclaim memory from. + */ FLECS_API void ecs_map_reclaim( ecs_map_t *map); -/** Deinitialize map. */ +/** Deinitialize a map. + * + * @param map The map to deinitialize. + */ FLECS_API void ecs_map_fini( ecs_map_t *map); -/** Get element for key, returns NULL if they key doesn't exist. */ +/** Get an element for a key. Returns NULL if the key doesn't exist. + * + * @param map The map to search. + * @param key The key to look up. + * @return Pointer to the value, or NULL if the key was not found. + */ FLECS_API ecs_map_val_t* ecs_map_get( const ecs_map_t *map, ecs_map_key_t key); -/* Get element as pointer (auto-dereferences _ptr) */ +/** Get element as pointer (auto-dereferences _ptr). + * + * @param map The map to search. + * @param key The key to look up. + * @return Dereferenced pointer value, or NULL if the key was not found. + */ FLECS_API void* ecs_map_get_deref_( const ecs_map_t *map, ecs_map_key_t key); -/** Get or insert element for key. */ +/** Get or insert an element for a key. + * + * @param map The map to get or insert into. + * @param key The key to look up or insert. + * @return Pointer to the existing or newly inserted value. + */ FLECS_API ecs_map_val_t* ecs_map_ensure( ecs_map_t *map, ecs_map_key_t key); -/** Get or insert pointer element for key, allocate if the pointer is NULL */ +/** Get or insert a pointer element for a key. Allocate if the pointer is NULL. + * + * @param map The map to get or insert into. + * @param elem_size Size of the element to allocate. + * @param key The key to look up or insert. + * @return Pointer to the existing or newly allocated element. + */ FLECS_API void* ecs_map_ensure_alloc( ecs_map_t *map, ecs_size_t elem_size, ecs_map_key_t key); -/** Insert element for key. */ +/** Insert an element for a key. + * + * @param map The map to insert into. + * @param key The key for the new element. + * @param value The value to insert. + */ FLECS_API void ecs_map_insert( ecs_map_t *map, ecs_map_key_t key, ecs_map_val_t value); -/** Insert pointer element for key, populate with new allocation. */ +/** Insert a pointer element for a key, populate with a new allocation. + * + * @param map The map to insert into. + * @param elem_size Size of the element to allocate. + * @param key The key for the new element. + * @return Pointer to the newly allocated element. + */ FLECS_API void* ecs_map_insert_alloc( ecs_map_t *map, ecs_size_t elem_size, ecs_map_key_t key); -/** Remove key from map. */ +/** Remove a key from the map. + * + * @param map The map to remove from. + * @param key The key to remove. + * @return The removed value. + */ FLECS_API ecs_map_val_t ecs_map_remove( ecs_map_t *map, ecs_map_key_t key); -/* Remove pointer element, free if not NULL */ +/** Remove a pointer element. Free if not NULL. + * + * @param map The map to remove from. + * @param key The key to remove and free. + */ FLECS_API void ecs_map_remove_free( ecs_map_t *map, ecs_map_key_t key); -/** Remove all elements from map. */ +/** Remove all elements from the map. + * + * @param map The map to clear. + */ FLECS_API void ecs_map_clear( ecs_map_t *map); -/** Return number of elements in map. */ +/** Return the number of elements in the map. */ #define ecs_map_count(map) ((map) ? (map)->count : 0) -/** Is map initialized */ +/** Is the map initialized? */ #define ecs_map_is_init(map) ((map) ? (map)->bucket_shift != 0 : false) -/** Return iterator to map contents. */ +/** Return an iterator to map contents. + * + * @param map The map to iterate. + * @return A new iterator positioned before the first element. + */ FLECS_API ecs_map_iter_t ecs_map_iter( const ecs_map_t *map); -/** Return whether map iterator is valid. */ +/** Return whether the map iterator is valid. + * + * @param iter The iterator to check. + * @return True if the iterator is valid. + */ FLECS_API bool ecs_map_iter_valid( ecs_map_iter_t *iter); -/** Obtain next element in map from iterator. */ +/** Obtain the next element in the map from the iterator. + * + * @param iter The iterator to advance. + * @return True if a next element was found, false if iteration is done. + */ FLECS_API bool ecs_map_next( ecs_map_iter_t *iter); -/** Copy map. */ +/** Copy a map. + * + * @param dst The destination map. + * @param src The source map to copy from. + */ FLECS_API void ecs_map_copy( ecs_map_t *dst, const ecs_map_t *src); +/** Get value as a typed reference (T**). */ #define ecs_map_get_ref(m, T, k) ECS_CAST(T**, ecs_map_get(m, k)) + +/** Get value as a typed dereferenced pointer (T*). */ #define ecs_map_get_deref(m, T, k) ECS_CAST(T*, ecs_map_get_deref_(m, k)) + +/** Get value as a void pointer. */ #define ecs_map_get_ptr(m, k) ECS_CAST(void*, ecs_map_get_deref_(m, k)) + +/** Ensure a typed reference (T**) for the key. */ #define ecs_map_ensure_ref(m, T, k) ECS_CAST(T**, ecs_map_ensure(m, k)) +/** Insert a pointer value into the map. */ #define ecs_map_insert_ptr(m, k, v) ecs_map_insert(m, k, ECS_CAST(ecs_map_val_t, ECS_PTR_CAST(uintptr_t, v))) + +/** Type-safe insert with allocation. */ #define ecs_map_insert_alloc_t(m, T, k) ECS_CAST(T*, ecs_map_insert_alloc(m, ECS_SIZEOF(T), k)) + +/** Type-safe ensure with allocation. */ #define ecs_map_ensure_alloc_t(m, T, k) ECS_PTR_CAST(T*, (uintptr_t)ecs_map_ensure_alloc(m, ECS_SIZEOF(T), k)) + +/** Remove a pointer element from the map. */ #define ecs_map_remove_ptr(m, k) (ECS_PTR_CAST(void*, ECS_CAST(uintptr_t, (ecs_map_remove(m, k))))) +/** Get the key from an iterator. */ #define ecs_map_key(it) ((it)->res[0]) + +/** Get the value from an iterator. */ #define ecs_map_value(it) ((it)->res[1]) + +/** Get the value from an iterator as a void pointer. */ #define ecs_map_ptr(it) ECS_PTR_CAST(void*, ECS_CAST(uintptr_t, ecs_map_value(it))) + +/** Get the value from an iterator as a typed reference (T**). */ #define ecs_map_ref(it, T) (ECS_CAST(T**, &((it)->res[1]))) #ifdef __cplusplus @@ -2178,50 +2962,83 @@ void ecs_map_copy( /** * @file allocator.h - * @brief Allocator that returns memory objects of any size. + * @brief Allocator that returns memory objects of any size. */ #ifndef FLECS_ALLOCATOR_H #define FLECS_ALLOCATOR_H -FLECS_DBG_API extern int64_t ecs_block_allocator_alloc_count; -FLECS_DBG_API extern int64_t ecs_block_allocator_free_count; -FLECS_DBG_API extern int64_t ecs_stack_allocator_alloc_count; -FLECS_DBG_API extern int64_t ecs_stack_allocator_free_count; +FLECS_DBG_API extern int64_t ecs_block_allocator_alloc_count; /**< Block allocator allocation count. */ +FLECS_DBG_API extern int64_t ecs_block_allocator_free_count; /**< Block allocator free count. */ +FLECS_DBG_API extern int64_t ecs_stack_allocator_alloc_count; /**< Stack allocator allocation count. */ +FLECS_DBG_API extern int64_t ecs_stack_allocator_free_count; /**< Stack allocator free count. */ +/** General purpose allocator that manages block allocators for different sizes. */ struct ecs_allocator_t { #ifndef FLECS_USE_OS_ALLOC - ecs_block_allocator_t chunks; - struct ecs_sparse_t sizes; /* */ + ecs_block_allocator_t chunks; /**< Block allocator for chunk storage. */ + struct ecs_sparse_t sizes; /**< Sparse set mapping size to block allocator. */ #else - bool dummy; + bool dummy; /**< Unused member for OS allocator fallback. */ #endif }; +/** Initialize an allocator. + * + * @param a The allocator to initialize. + */ FLECS_API void flecs_allocator_init( ecs_allocator_t *a); +/** Deinitialize an allocator. + * + * @param a The allocator to deinitialize. + */ FLECS_API void flecs_allocator_fini( ecs_allocator_t *a); +/** Get or create a block allocator for the specified size. + * + * @param a The allocator. + * @param size The allocation size. + * @return The block allocator for the given size. + */ FLECS_API ecs_block_allocator_t* flecs_allocator_get( - ecs_allocator_t *a, + ecs_allocator_t *a, ecs_size_t size); +/** Duplicate a string using the allocator. + * + * @param a The allocator. + * @param str The string to duplicate. + * @return The duplicated string. + */ FLECS_API char* flecs_strdup( - ecs_allocator_t *a, + ecs_allocator_t *a, const char* str); +/** Free a string previously allocated with flecs_strdup(). + * + * @param a The allocator. + * @param str The string to free. + */ FLECS_API void flecs_strfree( - ecs_allocator_t *a, + ecs_allocator_t *a, char* str); +/** Duplicate a memory block using the allocator. + * + * @param a The allocator. + * @param size The size of the memory block. + * @param src The source memory to duplicate. + * @return Pointer to the duplicated memory. + */ FLECS_API void* flecs_dup( ecs_allocator_t *a, @@ -2229,78 +3046,147 @@ void* flecs_dup( const void *src); #ifndef FLECS_USE_OS_ALLOC + +/** Get the dynamic allocator from an object. */ #define flecs_allocator(obj) (&obj->allocators.dyn) +/** Allocate memory of a given size. */ #define flecs_alloc(a, size) flecs_balloc(flecs_allocator_get(a, size)) + +/** Allocate memory with debug type name info. */ #define flecs_alloc_w_dbg_info(a, size, type_name) flecs_balloc_w_dbg_info(flecs_allocator_get(a, size), type_name) + +/** Allocate memory for a single element of type T. */ #define flecs_alloc_t(a, T) flecs_alloc_w_dbg_info(a, ECS_SIZEOF(T), #T) + +/** Allocate memory for count elements of type T. */ #define flecs_alloc_n(a, T, count) flecs_alloc_w_dbg_info(a, ECS_SIZEOF(T) * (count), #T) +/** Allocate zeroed memory of a given size. */ #define flecs_calloc(a, size) flecs_bcalloc(flecs_allocator_get(a, size)) + +/** Allocate zeroed memory with debug type name info. */ #define flecs_calloc_w_dbg_info(a, size, type_name) flecs_bcalloc_w_dbg_info(flecs_allocator_get(a, size), type_name) + +/** Allocate zeroed memory for a single element of type T. */ #define flecs_calloc_t(a, T) flecs_calloc_w_dbg_info(a, ECS_SIZEOF(T), #T) + +/** Allocate zeroed memory for count elements of type T. */ #define flecs_calloc_n(a, T, count) flecs_calloc_w_dbg_info(a, ECS_SIZEOF(T) * (count), #T) +/** Free memory of a given size. */ #define flecs_free(a, size, ptr)\ flecs_bfree((ptr) ? flecs_allocator_get(a, size) : NULL, ptr) + +/** Free memory for a single element of type T. */ #define flecs_free_t(a, T, ptr)\ flecs_bfree_w_dbg_info((ptr) ? flecs_allocator_get(a, ECS_SIZEOF(T)) : NULL, ptr, #T) + +/** Free memory for count elements of type T. */ #define flecs_free_n(a, T, count, ptr)\ flecs_bfree_w_dbg_info((ptr) ? flecs_allocator_get(a, ECS_SIZEOF(T) * (count)) : NULL\ , ptr, #T) +/** Reallocate memory from one size to another. */ #define flecs_realloc(a, size_dst, size_src, ptr)\ flecs_brealloc(flecs_allocator_get(a, size_dst),\ flecs_allocator_get(a, size_src),\ ptr) + +/** Reallocate memory with debug type name info. */ #define flecs_realloc_w_dbg_info(a, size_dst, size_src, ptr, type_name)\ flecs_brealloc_w_dbg_info(flecs_allocator_get(a, size_dst),\ flecs_allocator_get(a, size_src),\ ptr,\ type_name) + +/** Reallocate memory for count elements of type T. */ #define flecs_realloc_n(a, T, count_dst, count_src, ptr)\ flecs_realloc(a, ECS_SIZEOF(T) * (count_dst), ECS_SIZEOF(T) * (count_src), ptr) +/** Duplicate count elements of type T. */ #define flecs_dup_n(a, T, count, ptr) flecs_dup(a, ECS_SIZEOF(T) * (count), ptr) #else +/** Allocate memory of a given size (OS allocator fallback). + * + * @param a The allocator (unused). + * @param size The allocation size. + * @return Pointer to the allocated memory. + */ void* flecs_alloc( - ecs_allocator_t *a, + ecs_allocator_t *a, ecs_size_t size); +/** Allocate zeroed memory of a given size (OS allocator fallback). + * + * @param a The allocator (unused). + * @param size The allocation size. + * @return Pointer to the zeroed memory. + */ void* flecs_calloc( - ecs_allocator_t *a, + ecs_allocator_t *a, ecs_size_t size); +/** Reallocate memory from one size to another (OS allocator fallback). + * + * @param a The allocator (unused). + * @param dst_size The new allocation size. + * @param src_size The old allocation size. + * @param ptr The pointer to reallocate. + * @return Pointer to the reallocated memory. + */ void* flecs_realloc( - ecs_allocator_t *a, - ecs_size_t dst_size, - ecs_size_t src_size, + ecs_allocator_t *a, + ecs_size_t dst_size, + ecs_size_t src_size, void *ptr); +/** Free memory of a given size (OS allocator fallback). + * + * @param a The allocator (unused). + * @param size The allocation size. + * @param ptr The pointer to free. + */ void flecs_free( - ecs_allocator_t *a, + ecs_allocator_t *a, ecs_size_t size, void *ptr); +/** Allocate memory with debug type name info (OS allocator fallback). */ #define flecs_alloc_w_dbg_info(a, size, type_name) flecs_alloc(a, size) + +/** Allocate memory for a single element of type T (OS allocator fallback). */ #define flecs_alloc_t(a, T) flecs_alloc(a, ECS_SIZEOF(T)) + +/** Allocate memory for count elements of type T (OS allocator fallback). */ #define flecs_alloc_n(a, T, count) flecs_alloc(a, ECS_SIZEOF(T) * (count)) +/** Allocate zeroed memory with debug type name info (OS allocator fallback). */ #define flecs_calloc_w_dbg_info(a, size, type_name) flecs_calloc(a, size) + +/** Allocate zeroed memory for a single element of type T (OS allocator fallback). */ #define flecs_calloc_t(a, T) flecs_calloc(a, ECS_SIZEOF(T)) + +/** Allocate zeroed memory for count elements of type T (OS allocator fallback). */ #define flecs_calloc_n(a, T, count) flecs_calloc(a, ECS_SIZEOF(T) * (count)) +/** Free memory for a single element of type T (OS allocator fallback). */ #define flecs_free_t(a, T, ptr) flecs_free(a, ECS_SIZEOF(T), ptr) + +/** Free memory for count elements of type T (OS allocator fallback). */ #define flecs_free_n(a, T, count, ptr) flecs_free(a, ECS_SIZEOF(T) * (count), ptr) +/** Reallocate memory with debug type name info (OS allocator fallback). */ #define flecs_realloc_w_dbg_info(a, size_dst, size_src, ptr, type_name)\ flecs_realloc(a, size_dst, size_src, ptr) +/** Reallocate memory for count elements of type T (OS allocator fallback). */ #define flecs_realloc_n(a, T, count_dst, count_src, ptr)\ flecs_realloc(a, ECS_SIZEOF(T) * count_dst, ECS_SIZEOF(T) * count_src, ptr) +/** Duplicate count elements of type T (OS allocator fallback). */ #define flecs_dup_n(a, T, count, ptr) flecs_dup(a, ECS_SIZEOF(T) * (count), ptr) #endif @@ -2320,6 +3206,7 @@ void flecs_free( extern "C" { #endif +/** Initializer for ecs_strbuf_t. */ #ifdef __cplusplus /* Fixes missing field initializer warning on g++ */ #define ECS_STRBUF_INIT (ecs_strbuf_t){} @@ -2327,158 +3214,236 @@ extern "C" { #define ECS_STRBUF_INIT (ecs_strbuf_t){0} #endif +/** Size of the small string optimization buffer. */ #define ECS_STRBUF_SMALL_STRING_SIZE (512) + +/** Maximum nesting depth for list operations. */ #define ECS_STRBUF_MAX_LIST_DEPTH (32) +/** Element tracking for nested list appends. */ typedef struct ecs_strbuf_list_elem { - int32_t count; - const char *separator; + int32_t count; /**< Number of elements appended to the list. */ + const char *separator; /**< Separator string inserted between elements. */ } ecs_strbuf_list_elem; +/** A string buffer for efficient string construction. */ typedef struct ecs_strbuf_t { - char *content; - ecs_size_t length; - ecs_size_t size; + char *content; /**< Pointer to the heap-allocated string content. */ + ecs_size_t length; /**< Current length of the string in bytes. */ + ecs_size_t size; /**< Allocated capacity of the content buffer. */ - ecs_strbuf_list_elem list_stack[ECS_STRBUF_MAX_LIST_DEPTH]; - int32_t list_sp; + ecs_strbuf_list_elem list_stack[ECS_STRBUF_MAX_LIST_DEPTH]; /**< Stack of nested list states. */ + int32_t list_sp; /**< Current list stack pointer (nesting depth). */ - char small_string[ECS_STRBUF_SMALL_STRING_SIZE]; + char small_string[ECS_STRBUF_SMALL_STRING_SIZE]; /**< Inline buffer for small string optimization. */ } ecs_strbuf_t; -/* Append format string to a buffer. - * Returns false when max is reached, true when there is still space */ +/** Append a format string to a buffer. + * + * @param buffer The buffer to append to. + * @param fmt The format string. + */ FLECS_API void ecs_strbuf_append( ecs_strbuf_t *buffer, const char *fmt, ...); -/* Append format string with argument list to a buffer. - * Returns false when max is reached, true when there is still space */ +/** Append a format string with an argument list to a buffer. + * + * @param buffer The buffer to append to. + * @param fmt The format string. + * @param args The format argument list. + */ FLECS_API void ecs_strbuf_vappend( ecs_strbuf_t *buffer, const char *fmt, va_list args); -/* Append string to buffer. - * Returns false when max is reached, true when there is still space */ +/** Append a string to a buffer. + * + * @param buffer The buffer to append to. + * @param str The string to append. + */ FLECS_API void ecs_strbuf_appendstr( ecs_strbuf_t *buffer, const char *str); -/* Append character to buffer. - * Returns false when max is reached, true when there is still space */ +/** Append a character to a buffer. + * + * @param buffer The buffer to append to. + * @param ch The character to append. + */ FLECS_API void ecs_strbuf_appendch( ecs_strbuf_t *buffer, char ch); -/* Append int to buffer. - * Returns false when max is reached, true when there is still space */ +/** Append an int to a buffer. + * + * @param buffer The buffer to append to. + * @param v The integer value to append. + */ FLECS_API void ecs_strbuf_appendint( ecs_strbuf_t *buffer, int64_t v); -/* Append float to buffer. - * Returns false when max is reached, true when there is still space */ +/** Append a float to a buffer. + * + * @param buffer The buffer to append to. + * @param v The float value to append. + * @param nan_delim The delimiter to use for NaN values. + */ FLECS_API void ecs_strbuf_appendflt( ecs_strbuf_t *buffer, double v, char nan_delim); -/* Append boolean to buffer. - * Returns false when max is reached, true when there is still space */ +/** Append a boolean to a buffer. + * + * @param buffer The buffer to append to. + * @param v The boolean value to append. + */ FLECS_API void ecs_strbuf_appendbool( ecs_strbuf_t *buffer, bool v); -/* Append source buffer to destination buffer. - * Returns false when max is reached, true when there is still space */ +/** Append a source buffer to a destination buffer. + * + * @param dst_buffer The destination buffer. + * @param src_buffer The source buffer to append. + */ FLECS_API void ecs_strbuf_mergebuff( ecs_strbuf_t *dst_buffer, ecs_strbuf_t *src_buffer); -/* Append n characters to buffer. - * Returns false when max is reached, true when there is still space */ +/** Append n characters to a buffer. + * + * @param buffer The buffer to append to. + * @param str The string to append from. + * @param n The number of characters to append. + */ FLECS_API void ecs_strbuf_appendstrn( ecs_strbuf_t *buffer, const char *str, int32_t n); -/* Return result string */ +/** Return the result string. + * + * @param buffer The buffer to get the string from. + * @return The result string, or NULL if empty. + */ FLECS_API char* ecs_strbuf_get( ecs_strbuf_t *buffer); -/* Return small string from first element (appends \0) */ +/** Return the small string from the first element (appends \\0). + * + * @param buffer The buffer to get the string from. + * @return The small string. + */ FLECS_API char* ecs_strbuf_get_small( ecs_strbuf_t *buffer); -/* Reset buffer without returning a string */ +/** Reset a buffer without returning a string. + * + * @param buffer The buffer to reset. + */ FLECS_API void ecs_strbuf_reset( ecs_strbuf_t *buffer); -/* Push a list */ +/** Push a list. + * + * @param buffer The buffer. + * @param list_open The string used to open the list. + * @param separator The separator string inserted between elements. + */ FLECS_API void ecs_strbuf_list_push( ecs_strbuf_t *buffer, const char *list_open, const char *separator); -/* Pop a new list */ +/** Pop a list. + * + * @param buffer The buffer. + * @param list_close The string used to close the list. + */ FLECS_API void ecs_strbuf_list_pop( ecs_strbuf_t *buffer, const char *list_close); -/* Insert a new element in list */ +/** Insert a new element in the list. + * + * @param buffer The buffer. + */ FLECS_API void ecs_strbuf_list_next( ecs_strbuf_t *buffer); -/* Append character to as new element in list. */ +/** Append a character as a new element in the list. + * + * @param buffer The buffer. + * @param ch The character to append. + */ FLECS_API void ecs_strbuf_list_appendch( ecs_strbuf_t *buffer, char ch); -/* Append formatted string as a new element in list */ +/** Append a formatted string as a new element in the list. + * + * @param buffer The buffer. + * @param fmt The format string. + */ FLECS_API void ecs_strbuf_list_append( ecs_strbuf_t *buffer, const char *fmt, ...); -/* Append string as a new element in list */ +/** Append a string as a new element in the list. + * + * @param buffer The buffer. + * @param str The string to append. + */ FLECS_API void ecs_strbuf_list_appendstr( ecs_strbuf_t *buffer, const char *str); -/* Append string as a new element in list */ +/** Append n characters as a new element in the list. + * + * @param buffer The buffer. + * @param str The string to append from. + * @param n The number of characters to append. + */ FLECS_API void ecs_strbuf_list_appendstrn( ecs_strbuf_t *buffer, const char *str, int32_t n); +/** Return the number of bytes written to the buffer. */ FLECS_API int32_t ecs_strbuf_written( const ecs_strbuf_t *buffer); +/** Append a string literal to a buffer. Uses sizeof to determine length. */ #define ecs_strbuf_appendlit(buf, str)\ ecs_strbuf_appendstrn(buf, str, (int32_t)(sizeof(str) - 1)) +/** Append a string literal as a new element in a list. Uses sizeof to determine length. */ #define ecs_strbuf_list_appendlit(buf, str)\ ecs_strbuf_list_appendstrn(buf, str, (int32_t)(sizeof(str) - 1)) @@ -2493,10 +3458,10 @@ int32_t ecs_strbuf_written( * @brief Operating system abstraction API. * * This file contains the operating system abstraction API. The flecs core - * library avoids OS/runtime specific API calls as much as possible. Instead it + * library avoids OS/runtime-specific API calls as much as possible. Instead, it * provides an interface that can be implemented by applications. * - * Examples for how to implement this interface can be found in the + * Examples of how to implement this interface can be found in the * examples/os_api folder. */ @@ -2506,7 +3471,7 @@ int32_t ecs_strbuf_written( /** * @defgroup c_os_api OS API * @ingroup c - * Interface for providing OS specific functionality. + * Interface for providing OS-specific functionality. * * @{ */ @@ -2529,7 +3494,7 @@ typedef struct ecs_time_t { uint32_t nanosec; /**< Nanosecond part. */ } ecs_time_t; -/* Allocation counters */ +/** Allocation counters. */ extern int64_t ecs_os_api_malloc_count; /**< malloc count. */ extern int64_t ecs_os_api_realloc_count; /**< realloc count. */ extern int64_t ecs_os_api_calloc_count; /**< calloc count. */ @@ -2537,20 +3502,20 @@ extern int64_t ecs_os_api_free_count; /**< free count. */ /* Enabling this flag will add a header to each allocation that allows the code * to track exactly how much memory has been allocated. Increases memory - * utilization by 16 bytes per allocation, and is not thread safe. */ + * utilization by 16 bytes per allocation, and is not thread-safe. */ // #define FLECS_TRACK_OS_ALLOC #ifdef FLECS_TRACK_OS_ALLOC FLECS_API extern ecs_size_t ecs_os_allocated_bytes; #endif -/* Use handle types that _at least_ can store pointers */ +/** Use handle types that _at least_ can store pointers. */ typedef uintptr_t ecs_os_thread_t; /**< OS thread. */ typedef uintptr_t ecs_os_cond_t; /**< OS cond. */ typedef uintptr_t ecs_os_mutex_t; /**< OS mutex. */ typedef uintptr_t ecs_os_dl_t; /**< OS dynamic library. */ typedef uintptr_t ecs_os_sock_t; /**< OS socket. */ -/** 64 bit thread id. */ +/** 64-bit thread ID. */ typedef uint64_t ecs_os_thread_id_t; /** Generic function pointer type. */ @@ -2621,7 +3586,7 @@ typedef void* (*ecs_os_api_task_join_t)( ecs_os_thread_t thread); -/* Atomic increment / decrement */ +/** Atomic increment and decrement. */ /** OS API ainc function type. */ typedef int32_t (*ecs_os_api_ainc_t)( @@ -2632,7 +3597,7 @@ typedef int64_t (*ecs_os_api_lainc_t)( int64_t *value); -/* Mutex */ +/** Mutex. */ /** OS API mutex_new function type. */ typedef ecs_os_mutex_t (*ecs_os_api_mutex_new_t)( @@ -2653,7 +3618,7 @@ typedef void (*ecs_os_api_mutex_free_t)( ecs_os_mutex_t mutex); -/* Condition variable */ +/** Condition variable. */ /** OS API cond_new function type. */ typedef ecs_os_cond_t (*ecs_os_api_cond_new_t)( @@ -2700,12 +3665,18 @@ void (*ecs_os_api_get_time_t)( typedef uint64_t (*ecs_os_api_now_t)(void); -/** OS API log function type. */ +/** OS API log function type. + * + * @param level The logging level. + * @param file The file where the message was logged. + * @param line The line where it was logged. + * @param msg The log message. + */ typedef void (*ecs_os_api_log_t)( - int32_t level, /* Logging level */ - const char *file, /* File where message was logged */ - int32_t line, /* Line it was logged */ + int32_t level, + const char *file, + int32_t line, const char *msg); /** OS API abort function type. */ @@ -2734,18 +3705,23 @@ typedef char* (*ecs_os_api_module_to_path_t)( const char *module_id); -/* Performance tracing */ +/** OS API performance tracing function type. + * + * @param filename The source file name. + * @param line The source line number. + * @param name The name of the trace region. + */ typedef void (*ecs_os_api_perf_trace_t)( const char *filename, size_t line, const char *name); -/* Prefix members of struct with 'ecs_' as some system headers may define - * macros for functions like "strdup", "log" or "_free" */ +/* Prefix members of the struct with 'ecs_' as some system headers may define + * macros for functions like "strdup", "log", or "_free". */ /** OS API interface. */ typedef struct ecs_os_api_t { - /* API init / deinit */ + /* API init and deinit */ ecs_os_api_init_t init_; /**< init callback. */ ecs_os_api_fini_t fini_; /**< fini callback. */ @@ -2767,7 +3743,7 @@ typedef struct ecs_os_api_t { ecs_os_api_thread_new_t task_new_; /**< task_new callback. */ ecs_os_api_thread_join_t task_join_; /**< task_join callback. */ - /* Atomic increment / decrement */ + /* Atomic increment and decrement */ ecs_os_api_ainc_t ainc_; /**< ainc callback. */ ecs_os_api_ainc_t adec_; /**< adec callback. */ ecs_os_api_lainc_t lainc_; /**< lainc callback. */ @@ -2795,10 +3771,10 @@ typedef struct ecs_os_api_t { ecs_os_api_log_t log_; /**< log callback. * The level should be interpreted as: * >0: Debug tracing. Only enabled in debug builds. - * 0: Tracing. Enabled in debug/release builds. - * -2: Warning. An issue occurred, but operation was successful. - * -3: Error. An issue occurred, and operation was unsuccessful. - * -4: Fatal. An issue occurred, and application must quit. */ + * 0: Tracing. Enabled in debug and release builds. + * -2: Warning. An issue occurred, but the operation was successful. + * -3: Error. An issue occurred, and the operation was unsuccessful. + * -4: Fatal. An issue occurred, and the application must quit. */ /* Application termination */ ecs_os_api_abort_t abort_; /**< abort callback. */ @@ -2808,36 +3784,34 @@ typedef struct ecs_os_api_t { ecs_os_api_dlproc_t dlproc_; /**< dlproc callback. */ ecs_os_api_dlclose_t dlclose_; /**< dlclose callback. */ - /* Overridable function that translates from a logical module id to a - * shared library filename */ + /* Overridable function that translates from a logical module ID to a + * shared library filename. */ ecs_os_api_module_to_path_t module_to_dl_; /**< module_to_dl callback. */ - /* Overridable function that translates from a logical module id to a - * path that contains module-specif resources or assets */ + /* Overridable function that translates from a logical module ID to a + * path that contains module-specific resources or assets. */ ecs_os_api_module_to_path_t module_to_etc_; /**< module_to_etc callback. */ /* Performance tracing */ - ecs_os_api_perf_trace_t perf_trace_push_; - - /* Performance tracing */ - ecs_os_api_perf_trace_t perf_trace_pop_; + ecs_os_api_perf_trace_t perf_trace_push_; /**< perf_trace_push callback. */ + ecs_os_api_perf_trace_t perf_trace_pop_; /**< perf_trace_pop callback. */ int32_t log_level_; /**< Tracing level. */ int32_t log_indent_; /**< Tracing indentation level. */ int32_t log_last_error_; /**< Last logged error code. */ int64_t log_last_timestamp_; /**< Last logged timestamp. */ - ecs_flags32_t flags_; /**< OS API flags */ + ecs_flags32_t flags_; /**< OS API flags. */ void *log_out_; /**< File used for logging output (type is FILE*) - * (hint, log_ decides where to write) */ + * (hint: log_ decides where to write). */ } ecs_os_api_t; /** Static OS API variable with configured callbacks. */ FLECS_API extern ecs_os_api_t ecs_os_api; -/** Initialize OS API. +/** Initialize the OS API. * This operation is not usually called by an application. To override callbacks * of the OS API, use the following pattern: * @@ -2851,31 +3825,31 @@ extern ecs_os_api_t ecs_os_api; FLECS_API void ecs_os_init(void); -/** Deinitialize OS API. +/** Deinitialize the OS API. * This operation is not usually called by an application. */ FLECS_API void ecs_os_fini(void); -/** Override OS API. +/** Override the OS API. * This overrides the OS API struct with new values for callbacks. See - * ecs_os_init() on how to use the function. + * ecs_os_init() for how to use the function. * - * @param os_api Pointer to struct with values to set. + * @param os_api Pointer to a struct with values to set. */ FLECS_API void ecs_os_set_api( ecs_os_api_t *os_api); -/** Get OS API. +/** Get the OS API. * - * @return A value with the current OS API callbacks + * @return A value with the current OS API callbacks. * @see ecs_os_init() */ FLECS_API ecs_os_api_t ecs_os_get_api(void); -/** Set default values for OS API. +/** Set default values for the OS API. * This initializes the OS API struct with default values for callbacks like * malloc and free. * @@ -2944,7 +3918,6 @@ void ecs_os_set_api_defaults(void); #define ecs_os_memmove_t(ptr1, ptr2, T) ecs_os_memmove(ptr1, ptr2, ECS_SIZEOF(T)) #define ecs_os_memmove_n(ptr1, ptr2, T, count) ecs_os_memmove(ptr1, ptr2, ECS_SIZEOF(T) * (size_t)count) -#define ecs_os_memmove_t(ptr1, ptr2, T) ecs_os_memmove(ptr1, ptr2, ECS_SIZEOF(T)) #define ecs_os_strcmp(str1, str2) strcmp(str1, str2) #define ecs_os_memset_t(ptr, value, T) ecs_os_memset(ptr, value, ECS_SIZEOF(T)) @@ -2987,7 +3960,7 @@ void ecs_os_set_api_defaults(void); #define ecs_os_task_new(callback, param) ecs_os_api.task_new_(callback, param) #define ecs_os_task_join(thread) ecs_os_api.task_join_(thread) -/* Atomic increment / decrement */ +/* Atomic increment and decrement */ #define ecs_os_ainc(value) ecs_os_api.ainc_(value) #define ecs_os_adec(value) ecs_os_api.adec_(value) #define ecs_os_lainc(value) ecs_os_api.lainc_(value) @@ -3032,8 +4005,8 @@ void ecs_os_set_api_defaults(void); #ifdef ECS_TARGET_MINGW -/* mingw bug: without this a conversion error is thrown, but isnan/isinf should - * accept float, double and long double. */ +/* mingw bug: without this, a conversion error is thrown, but isnan/isinf should + * accept float, double, and long double. */ #define ecs_os_isnan(val) (isnan((float)val)) #define ecs_os_isinf(val) (isinf((float)val)) #else @@ -3049,7 +4022,7 @@ void ecs_os_set_api_defaults(void); #define ecs_os_dlproc(lib, procname) ecs_os_api.dlproc_(lib, procname) #define ecs_os_dlclose(lib) ecs_os_api.dlclose_(lib) -/* Module id translation */ +/* Module ID translation */ #define ecs_os_module_to_dl(lib) ecs_os_api.module_to_dl_(lib) #define ecs_os_module_to_etc(lib) ecs_os_api.module_to_etc_(lib) @@ -3062,8 +4035,8 @@ void ecs_os_set_api_defaults(void); /** Log at debug level. * - * @param file The file to log. - * @param line The line to log. + * @param file The source file. + * @param line The source line. * @param msg The message to log. */ FLECS_API @@ -3074,8 +4047,8 @@ void ecs_os_dbg( /** Log at trace level. * - * @param file The file to log. - * @param line The line to log. + * @param file The source file. + * @param line The source line. * @param msg The message to log. */ FLECS_API @@ -3086,8 +4059,8 @@ void ecs_os_trace( /** Log at warning level. * - * @param file The file to log. - * @param line The line to log. + * @param file The source file. + * @param line The source line. * @param msg The message to log. */ FLECS_API @@ -3098,8 +4071,8 @@ void ecs_os_warn( /** Log at error level. * - * @param file The file to log. - * @param line The line to log. + * @param file The source file. + * @param line The source line. * @param msg The message to log. */ FLECS_API @@ -3110,8 +4083,8 @@ void ecs_os_err( /** Log at fatal level. * - * @param file The file to log. - * @param line The line to log. + * @param file The source file. + * @param line The source line. * @param msg The message to log. */ FLECS_API @@ -3120,7 +4093,7 @@ void ecs_os_fatal( int32_t line, const char *msg); -/** Convert errno to string. +/** Convert errno to a string. * * @param err The error number. * @return A string describing the error. @@ -3129,7 +4102,7 @@ FLECS_API const char* ecs_os_strerror( int err); -/** Utility for assigning strings. +/** A utility for assigning strings. * This operation frees an existing string and duplicates the input string. * * @param str Pointer to a string value. @@ -3149,17 +4122,29 @@ void ecs_os_strset( #define ecs_os_perf_trace_pop(name) #endif +/** Push a performance trace region. + * + * @param file The source file name. + * @param line The source line number. + * @param name The name of the trace region. + */ void ecs_os_perf_trace_push_( const char *file, size_t line, const char *name); +/** Pop a performance trace region. + * + * @param file The source file name. + * @param line The source line number. + * @param name The name of the trace region. + */ void ecs_os_perf_trace_pop_( const char *file, size_t line, const char *name); -/** Sleep with floating point time. +/** Sleep with floating-point time. * * @param t The time in seconds. */ @@ -3167,9 +4152,9 @@ FLECS_API void ecs_sleepf( double t); -/** Measure time since provided timestamp. +/** Measure time since the provided timestamp. * Use with a time value initialized to 0 to obtain the number of seconds since - * the epoch. The operation will write the current timestamp in start. + * the epoch. The operation will write the current timestamp into start. * * Usage: * @code @@ -3186,10 +4171,10 @@ FLECS_API double ecs_time_measure( ecs_time_t *start); -/** Calculate difference between two timestamps. +/** Calculate the difference between two timestamps. * * @param t1 The first timestamp. - * @param t2 The first timestamp. + * @param t2 The second timestamp. * @return The difference between timestamps. */ FLECS_API @@ -3197,7 +4182,7 @@ ecs_time_t ecs_time_sub( ecs_time_t t1, ecs_time_t t2); -/** Convert time value to a double. +/** Convert a time value to a double. * * @param t The timestamp. * @return The timestamp converted to a double. @@ -3299,7 +4284,7 @@ typedef void (*ecs_iter_action_t)( * an iterator without needing to know what created it. * * @param it The iterator to iterate. - * @return True if iterator has no more results, false if it does. + * @return True if iterator has more results, false if not. */ typedef bool (*ecs_iter_next_action_t)( ecs_iter_t *it); @@ -3312,14 +4297,14 @@ typedef bool (*ecs_iter_next_action_t)( typedef void (*ecs_iter_fini_action_t)( ecs_iter_t *it); -/** Callback used for comparing components */ +/** Callback used for comparing components. */ typedef int (*ecs_order_by_action_t)( ecs_entity_t e1, const void *ptr1, ecs_entity_t e2, const void *ptr2); -/** Callback used for sorting the entire table of components */ +/** Callback used for sorting the entire table of components. */ typedef void (*ecs_sort_table_action_t)( ecs_world_t* world, ecs_table_t* table, @@ -3330,7 +4315,7 @@ typedef void (*ecs_sort_table_action_t)( int32_t hi, ecs_order_by_action_t order_by); -/** Callback used for grouping tables in a query */ +/** Callback used for grouping tables in a query. */ typedef uint64_t (*ecs_group_by_action_t)( ecs_world_t *world, ecs_table_t *table, @@ -3350,29 +4335,29 @@ typedef void (*ecs_group_delete_action_t)( void *group_ctx, /* return value from ecs_group_create_action_t */ void *group_by_ctx); /* from ecs_query_desc_t */ -/** Initialization action for modules */ +/** Initialization action for modules. */ typedef void (*ecs_module_action_t)( ecs_world_t *world); -/** Action callback on world exit */ +/** Action callback on world exit. */ typedef void (*ecs_fini_action_t)( ecs_world_t *world, void *ctx); -/** Function to cleanup context data */ +/** Function to clean up context data. */ typedef void (*ecs_ctx_free_t)( void *ctx); -/** Callback used for sorting values */ +/** Callback used for sorting values. */ typedef int (*ecs_compare_action_t)( const void *ptr1, const void *ptr2); -/** Callback used for hashing values */ +/** Callback used for hashing values. */ typedef uint64_t (*ecs_hash_value_action_t)( const void *ptr); -/** Constructor/destructor callback */ +/** Constructor/destructor callback. */ typedef void (*ecs_xtor_t)( void *ptr, int32_t count, @@ -3392,13 +4377,13 @@ typedef void (*ecs_move_t)( int32_t count, const ecs_type_info_t *type_info); -/** Compare hook to compare component instances */ +/** Compare hook to compare component instances. */ typedef int (*ecs_cmp_t)( const void *a_ptr, const void *b_ptr, const ecs_type_info_t *type_info); -/** Equals operator hook */ +/** Equals operator hook. */ typedef bool (*ecs_equals_t)( const void *a_ptr, const void *b_ptr, @@ -3417,39 +4402,39 @@ typedef void (*flecs_poly_dtor_t)( * @{ */ -/** Specify read/write access for term */ +/** Specify read/write access for term. */ typedef enum ecs_inout_kind_t { - EcsInOutDefault, /**< InOut for regular terms, In for shared terms */ - EcsInOutNone, /**< Term is neither read nor written */ - EcsInOutFilter, /**< Same as InOutNone + prevents term from triggering observers */ - EcsInOut, /**< Term is both read and written */ - EcsIn, /**< Term is only read */ - EcsOut, /**< Term is only written */ + EcsInOutDefault, /**< InOut for regular terms, In for shared terms. */ + EcsInOutNone, /**< Term is neither read nor written. */ + EcsInOutFilter, /**< Same as InOutNone + prevents term from triggering observers. */ + EcsInOut, /**< Term is both read and written. */ + EcsIn, /**< Term is only read. */ + EcsOut, /**< Term is only written. */ } ecs_inout_kind_t; -/** Specify operator for term */ +/** Specify operator for term. */ typedef enum ecs_oper_kind_t { - EcsAnd, /**< The term must match */ - EcsOr, /**< One of the terms in an or chain must match */ - EcsNot, /**< The term must not match */ - EcsOptional, /**< The term may match */ - EcsAndFrom, /**< Term must match all components from term id */ - EcsOrFrom, /**< Term must match at least one component from term id */ - EcsNotFrom, /**< Term must match none of the components from term id */ + EcsAnd, /**< The term must match. */ + EcsOr, /**< One of the terms in an or chain must match. */ + EcsNot, /**< The term must not match. */ + EcsOptional, /**< The term may match. */ + EcsAndFrom, /**< Term must match all components from term ID. */ + EcsOrFrom, /**< Term must match at least one component from term ID. */ + EcsNotFrom, /**< Term must match none of the components from term ID. */ } ecs_oper_kind_t; -/** Specify cache policy for query */ +/** Specify cache policy for query. */ typedef enum ecs_query_cache_kind_t { - EcsQueryCacheDefault, /**< Behavior determined by query creation context */ - EcsQueryCacheAuto, /**< Cache query terms that are cacheable */ - EcsQueryCacheAll, /**< Require that all query terms can be cached */ - EcsQueryCacheNone, /**< No caching */ + EcsQueryCacheDefault, /**< Behavior determined by query creation context. */ + EcsQueryCacheAuto, /**< Cache query terms that are cacheable. */ + EcsQueryCacheAll, /**< Require that all query terms can be cached. */ + EcsQueryCacheNone, /**< No caching. */ } ecs_query_cache_kind_t; -/* Term id flags */ +/** Term ID flags. */ /** Match on self. - * Can be combined with other term flags on the ecs_term_t::flags_ field. + * Can be combined with other term flags on the ecs_term_ref_t::id field. * \ingroup queries */ #define EcsSelf (1llu << 63) @@ -3466,7 +4451,7 @@ typedef enum ecs_query_cache_kind_t { */ #define EcsTrav (1llu << 61) -/** Sort results breadth first. +/** Sort results breadth-first. * Can be combined with other term flags on the ecs_term_ref_t::id field. * \ingroup queries */ @@ -3478,19 +4463,19 @@ typedef enum ecs_query_cache_kind_t { */ #define EcsDesc (1llu << 59) -/** Term id is a variable. +/** Term ID is a variable. * Can be combined with other term flags on the ecs_term_ref_t::id field. * \ingroup queries */ #define EcsIsVariable (1llu << 58) -/** Term id is an entity. +/** Term ID is an entity. * Can be combined with other term flags on the ecs_term_ref_t::id field. * \ingroup queries */ #define EcsIsEntity (1llu << 57) -/** Term id is a name (don't attempt to lookup as entity). +/** Term ID is a name (don't attempt to look up as an entity). * Can be combined with other term flags on the ecs_term_ref_t::id field. * \ingroup queries */ @@ -3510,10 +4495,10 @@ typedef enum ecs_query_cache_kind_t { /** Type that describes a reference to an entity or variable in a term. */ typedef struct ecs_term_ref_t { - ecs_entity_t id; /**< Entity id. If left to 0 and flags does not - * specify whether id is an entity or a variable - * the id will be initialized to #EcsThis. - * To explicitly set the id to 0, leave the id + ecs_entity_t id; /**< Entity ID. If left to 0 and flags do not + * specify whether the ID is an entity or a variable, + * the ID will be initialized to #EcsThis. + * To explicitly set the ID to 0, leave the ID * member to 0 and set #EcsIsEntity in flags. */ const char *name; /**< Name. This can be either the variable name @@ -3525,94 +4510,94 @@ typedef struct ecs_term_ref_t { /** Type that describes a term (single element in a query). */ struct ecs_term_t { - ecs_id_t id; /**< Component id to be matched by term. Can be + ecs_id_t id; /**< Component ID to be matched by term. Can be * set directly, or will be populated from the * first/second members, which provide more * flexibility. */ - ecs_term_ref_t src; /**< Source of term */ - ecs_term_ref_t first; /**< Component or first element of pair */ - ecs_term_ref_t second; /**< Second element of pair */ + ecs_term_ref_t src; /**< Source of term. */ + ecs_term_ref_t first; /**< Component or first element of pair. */ + ecs_term_ref_t second; /**< Second element of pair. */ ecs_entity_t trav; /**< Relationship to traverse when looking for the * component. The relationship must have * the `Traversable` property. Default is `IsA`. */ - int16_t inout; /**< Access to contents matched by term */ - int16_t oper; /**< Operator of term */ + int16_t inout; /**< Access to contents matched by term. */ + int16_t oper; /**< Operator of term. */ - int8_t field_index; /**< Index of field for term in iterator */ - ecs_flags16_t flags_; /**< Flags that help eval, set by ecs_query_init() */ + int8_t field_index; /**< Index of the field for the term in the iterator. */ + ecs_flags16_t flags_; /**< Flags that help evaluation, set by ecs_query_init(). */ }; /** Queries are lists of constraints (terms) that match entities. * Created with ecs_query_init(). */ struct ecs_query_t { - ecs_header_t hdr; /**< Object header */ - - ecs_term_t *terms; /**< Query terms */ - int32_t *sizes; /**< Component sizes. Indexed by field */ - ecs_id_t *ids; /**< Component ids. Indexed by field */ - - uint64_t bloom_filter; /**< Bitmask used to quickly discard tables */ - ecs_flags32_t flags; /**< Query flags */ - int8_t var_count; /**< Number of query variables */ - int8_t term_count; /**< Number of query terms */ - int8_t field_count; /**< Number of fields returned by query */ - - /* Bitmasks for quick field information lookups */ - ecs_termset_t fixed_fields; /**< Fields with a fixed source */ - ecs_termset_t var_fields; /**< Fields with non-$this variable source */ - ecs_termset_t static_id_fields; /**< Fields with a static (component) id */ - ecs_termset_t data_fields; /**< Fields that have data */ - ecs_termset_t write_fields; /**< Fields that write data */ - ecs_termset_t read_fields; /**< Fields that read data */ - ecs_termset_t row_fields; /**< Fields that must be acquired with field_at */ - ecs_termset_t shared_readonly_fields; /**< Fields that don't write shared data */ - ecs_termset_t set_fields; /**< Fields that will be set */ - - ecs_query_cache_kind_t cache_kind; /**< Caching policy of query */ - - char **vars; /**< Array with variable names for iterator */ + ecs_header_t hdr; /**< Object header. */ + + ecs_term_t *terms; /**< Query terms. */ + int32_t *sizes; /**< Component sizes. Indexed by field. */ + ecs_id_t *ids; /**< Component ids. Indexed by field. */ + + uint64_t bloom_filter; /**< Bitmask used to quickly discard tables. */ + ecs_flags32_t flags; /**< Query flags. */ + int8_t var_count; /**< Number of query variables. */ + int8_t term_count; /**< Number of query terms. */ + int8_t field_count; /**< Number of fields returned by the query. */ + + /** Bitmasks for quick field information lookups. */ + ecs_termset_t fixed_fields; /**< Fields with a fixed source. */ + ecs_termset_t var_fields; /**< Fields with non-$this variable source. */ + ecs_termset_t static_id_fields; /**< Fields with a static (component) id. */ + ecs_termset_t data_fields; /**< Fields that have data. */ + ecs_termset_t write_fields; /**< Fields that write data. */ + ecs_termset_t read_fields; /**< Fields that read data. */ + ecs_termset_t row_fields; /**< Fields that must be acquired with field_at. */ + ecs_termset_t shared_readonly_fields; /**< Fields that don't write shared data. */ + ecs_termset_t set_fields; /**< Fields that will be set. */ - void *ctx; /**< User context to pass to callback */ - void *binding_ctx; /**< Context to be used for language bindings */ + ecs_query_cache_kind_t cache_kind; /**< Caching policy of the query. */ - ecs_entity_t entity; /**< Entity associated with query (optional) */ + char **vars; /**< Array with variable names for the iterator. */ + + void *ctx; /**< User context to pass to callback. */ + void *binding_ctx; /**< Context to be used for language bindings. */ + + ecs_entity_t entity; /**< Entity associated with query (optional). */ ecs_world_t *real_world; /**< Actual world. */ - ecs_world_t *world; /**< World or stage query was created with. */ + ecs_world_t *world; /**< World or stage the query was created with. */ - int32_t eval_count; /**< Number of times query is evaluated */ + int32_t eval_count; /**< Number of times the query is evaluated. */ }; /** An observer reacts to events matching a query. * Created with ecs_observer_init(). */ struct ecs_observer_t { - ecs_header_t hdr; /**< Object header */ - - ecs_query_t *query; /**< Observer query */ + ecs_header_t hdr; /**< Object header. */ + + ecs_query_t *query; /**< Observer query. */ - /** Observer events */ + /** Observer events. */ ecs_entity_t events[FLECS_EVENT_DESC_MAX]; - int32_t event_count; /**< Number of events */ + int32_t event_count; /**< Number of events. */ - ecs_iter_action_t callback; /**< See ecs_observer_desc_t::callback */ - ecs_run_action_t run; /**< See ecs_observer_desc_t::run */ + ecs_iter_action_t callback; /**< See ecs_observer_desc_t::callback. */ + ecs_run_action_t run; /**< See ecs_observer_desc_t::run. */ - void *ctx; /**< Observer context */ - void *callback_ctx; /**< Callback language binding context */ - void *run_ctx; /**< Run language binding context */ + void *ctx; /**< Observer context. */ + void *callback_ctx; /**< Callback language binding context. */ + void *run_ctx; /**< Run language binding context. */ - ecs_ctx_free_t ctx_free; /**< Callback to free ctx */ - ecs_ctx_free_t callback_ctx_free; /**< Callback to free callback_ctx */ - ecs_ctx_free_t run_ctx_free; /**< Callback to free run_ctx */ + ecs_ctx_free_t ctx_free; /**< Callback to free ctx. */ + ecs_ctx_free_t callback_ctx_free; /**< Callback to free callback_ctx. */ + ecs_ctx_free_t run_ctx_free; /**< Callback to free run_ctx. */ - ecs_observable_t *observable; /**< Observable for observer */ + ecs_observable_t *observable; /**< Observable for the observer. */ - ecs_world_t *world; /**< The world */ - ecs_entity_t entity; /**< Entity associated with observer */ + ecs_world_t *world; /**< The world. */ + ecs_entity_t entity; /**< Entity associated with the observer. */ }; /** @} */ @@ -3647,6 +4632,9 @@ struct ecs_observer_t { #define ECS_TYPE_HOOK_CMP_ILLEGAL ECS_CAST(ecs_flags32_t, 1 << 19) #define ECS_TYPE_HOOK_EQUALS_ILLEGAL ECS_CAST(ecs_flags32_t, 1 << 20) +/* Internal debug flag that indicates type hooks have been invoked */ +#define ECS_TYPE_HOOK_IN_USE ECS_CAST(ecs_flags32_t, 1 << 21) + /* All valid hook flags */ #define ECS_TYPE_HOOKS (ECS_TYPE_HOOK_CTOR|ECS_TYPE_HOOK_DTOR|\ @@ -3662,79 +4650,79 @@ struct ecs_observer_t { ECS_TYPE_HOOK_MOVE_DTOR_ILLEGAL|ECS_TYPE_HOOK_CMP_ILLEGAL|\ ECS_TYPE_HOOK_EQUALS_ILLEGAL) struct ecs_type_hooks_t { - ecs_xtor_t ctor; /**< ctor */ - ecs_xtor_t dtor; /**< dtor */ - ecs_copy_t copy; /**< copy assignment */ - ecs_move_t move; /**< move assignment */ + ecs_xtor_t ctor; /**< ctor. */ + ecs_xtor_t dtor; /**< dtor. */ + ecs_copy_t copy; /**< copy assignment. */ + ecs_move_t move; /**< move assignment. */ - /** Ctor + copy */ + /** Ctor + copy. */ ecs_copy_t copy_ctor; - /** Ctor + move */ + /** Ctor + move. */ ecs_move_t move_ctor; /** Ctor + move + dtor (or move_ctor + dtor). * This combination is typically used when a component is moved from one * location to a new location, like when it is moved to a new table. If - * not set explicitly it will be derived from other callbacks. */ + * not set explicitly, it will be derived from other callbacks. */ ecs_move_t ctor_move_dtor; /** Move + dtor. * This combination is typically used when a component is moved from one * location to an existing location, like what happens during a remove. If - * not set explicitly it will be derived from other callbacks. */ + * not set explicitly, it will be derived from other callbacks. */ ecs_move_t move_dtor; - /** Compare hook */ + /** Compare hook. */ ecs_cmp_t cmp; - /** Equals hook */ + /** Equals hook. */ ecs_equals_t equals; /** Hook flags. * Indicates which hooks are set for the type, and which hooks are illegal. - * When an ILLEGAL flag is set when calling ecs_set_hooks() a hook callback + * When an ILLEGAL flag is set when calling ecs_set_hooks(), a hook callback * will be set that panics when called. */ ecs_flags32_t flags; /** Callback that is invoked when an instance of a component is added. This - * callback is invoked before triggers are invoked. */ + * callback is invoked before observers are invoked. */ ecs_iter_action_t on_add; /** Callback that is invoked when an instance of the component is set. This - * callback is invoked before triggers are invoked, and enable the component + * callback is invoked before observers are invoked, and enables the component * to respond to changes on itself before others can. */ ecs_iter_action_t on_set; /** Callback that is invoked when an instance of the component is removed. - * This callback is invoked after the triggers are invoked, and before the + * This callback is invoked after the observers are invoked, and before the * destructor is invoked. */ ecs_iter_action_t on_remove; /** Callback that is invoked with the existing and new value before the * value is assigned. Invoked after on_add and before on_set. Registering * an on_replace hook prevents using operations that return a mutable - * pointer to the component like get_mut, ensure and emplace. */ + * pointer to the component, like get_mut(), ensure(), and emplace(). */ ecs_iter_action_t on_replace; - void *ctx; /**< User defined context */ - void *binding_ctx; /**< Language binding context */ - void *lifecycle_ctx; /**< Component lifecycle context (see meta add-on)*/ + void *ctx; /**< User-defined context. */ + void *binding_ctx; /**< Language binding context. */ + void *lifecycle_ctx; /**< Component lifecycle context (see meta addon). */ - ecs_ctx_free_t ctx_free; /**< Callback to free ctx */ - ecs_ctx_free_t binding_ctx_free; /**< Callback to free binding_ctx */ - ecs_ctx_free_t lifecycle_ctx_free; /**< Callback to free lifecycle_ctx */ + ecs_ctx_free_t ctx_free; /**< Callback to free ctx. */ + ecs_ctx_free_t binding_ctx_free; /**< Callback to free binding_ctx. */ + ecs_ctx_free_t lifecycle_ctx_free; /**< Callback to free lifecycle_ctx. */ }; -/** Type that contains component information (passed to ctors/dtors/...) +/** Type that contains component information (passed to ctors/dtors/...). * * @ingroup components */ struct ecs_type_info_t { - ecs_size_t size; /**< Size of type */ - ecs_size_t alignment; /**< Alignment of type */ - ecs_type_hooks_t hooks; /**< Type hooks */ - ecs_entity_t component; /**< Handle to component (do not set) */ + ecs_size_t size; /**< Size of the type. */ + ecs_size_t alignment; /**< Alignment of the type. */ + ecs_type_hooks_t hooks; /**< Type hooks. */ + ecs_entity_t component; /**< Handle to component (do not set). */ const char *name; /**< Type name. */ }; @@ -3759,20 +4747,20 @@ extern "C" { //// Opaque types //////////////////////////////////////////////////////////////////////////////// -/** Table data */ +/** Table data. */ typedef struct ecs_data_t ecs_data_t; -/* Cached query table data */ +/* Cached query table data. */ typedef struct ecs_query_cache_match_t ecs_query_cache_match_t; -/* Cached query group */ +/* Cached query group. */ typedef struct ecs_query_cache_group_t ecs_query_cache_group_t; //////////////////////////////////////////////////////////////////////////////// //// Non-opaque types //////////////////////////////////////////////////////////////////////////////// -/** All observers for a specific event */ +/** All observers for a specific event. */ typedef struct ecs_event_record_t { struct ecs_event_id_record_t *any; struct ecs_event_id_record_t *wildcard; @@ -3787,20 +4775,21 @@ struct ecs_observable_t { ecs_event_record_t on_set; ecs_event_record_t on_wildcard; ecs_sparse_t events; /* sparse */ + ecs_vec_t global_observers; /* vector */ uint64_t last_observer_id; }; -/** Range in table */ +/** Range in a table. */ typedef struct ecs_table_range_t { ecs_table_t *table; - int32_t offset; /* Leave both members to 0 to cover entire table */ + int32_t offset; /* Leave both members at 0 to cover the entire table. */ int32_t count; } ecs_table_range_t; -/** Value of query variable */ +/** Value of a query variable. */ typedef struct ecs_var_t { - ecs_table_range_t range; /* Set when variable stores a range of entities */ - ecs_entity_t entity; /* Set when variable stores single entity */ + ecs_table_range_t range; /* Set when variable stores a range of entities. */ + ecs_entity_t entity; /* Set when variable stores a single entity. */ /* Most entities can be stored as a range by setting range.count to 1, * however in order to also be able to store empty entities in variables, @@ -3810,40 +4799,40 @@ typedef struct ecs_var_t { /** Cached reference. */ struct ecs_ref_t { - ecs_entity_t entity; /* Entity */ - ecs_entity_t id; /* Component id */ - uint64_t table_id; /* Table id for detecting ABA issues */ - uint32_t table_version_fast; /* Fast change detection w/false positives */ - uint16_t table_version; /* Change detection */ - ecs_record_t *record; /* Entity index record */ - void *ptr; /* Cached component pointer */ + ecs_entity_t entity; /* Entity. */ + ecs_entity_t id; /* Component ID. */ + uint64_t table_id; /* Table ID for detecting ABA issues. */ + uint32_t table_version_fast; /* Fast change detection with false positives. */ + uint16_t table_version; /* Change detection. */ + ecs_record_t *record; /* Entity index record. */ + void *ptr; /* Cached component pointer. */ }; -/* Page-iterator specific data */ +/* Page-iterator-specific data. */ typedef struct ecs_page_iter_t { int32_t offset; int32_t limit; int32_t remaining; } ecs_page_iter_t; -/* Worker-iterator specific data */ +/* Worker-iterator-specific data. */ typedef struct ecs_worker_iter_t { int32_t index; int32_t count; } ecs_worker_iter_t; -/* Convenience struct to iterate table array for id */ +/* Convenience struct to iterate a table array for an ID. */ typedef struct ecs_table_cache_iter_t { const struct ecs_table_cache_hdr_t *cur, *next; bool iter_fill; bool iter_empty; } ecs_table_cache_iter_t; -/** Each iterator */ +/** Each iterator. */ typedef struct ecs_each_iter_t { ecs_table_cache_iter_t it; - /* Storage for iterator fields */ + /* Storage for iterator fields. */ ecs_id_t ids; ecs_entity_t sources; ecs_size_t sizes; @@ -3855,46 +4844,46 @@ typedef struct ecs_query_op_profile_t { int32_t count[2]; /* 0 = enter, 1 = redo */ } ecs_query_op_profile_t; -/** Query iterator */ +/** Query iterator. */ typedef struct ecs_query_iter_t { - struct ecs_var_t *vars; /* Variable storage */ - const struct ecs_query_var_t *query_vars; /* Query variable metadata */ - const struct ecs_query_op_t *ops; /* Query plan operations */ - struct ecs_query_op_ctx_t *op_ctx; /* Operation-specific state */ + struct ecs_var_t *vars; /* Variable storage. */ + const struct ecs_query_var_t *query_vars; /* Query variable metadata. */ + const struct ecs_query_op_t *ops; /* Query plan operations. */ + struct ecs_query_op_ctx_t *op_ctx; /* Operation-specific state. */ uint64_t *written; - /* Cached iteration */ - ecs_query_cache_group_t *group; /* Currently iterated group */ - ecs_vec_t *tables; /* Currently iterated table vector (vec) */ - ecs_vec_t *all_tables; /* Different from .tables if iterating wildcard matches (vec) */ - ecs_query_cache_match_t *elem; /* Current cache entry */ - int32_t cur, all_cur; /* Indices into tables & all_tables */ + /* Cached iteration. */ + ecs_query_cache_group_t *group; /* Currently iterated group. */ + ecs_vec_t *tables; /* Currently iterated table vector (vec). */ + ecs_vec_t *all_tables; /* Different from .tables if iterating wildcard matches (vec). */ + ecs_query_cache_match_t *elem; /* Current cache entry. */ + int32_t cur, all_cur; /* Indices into tables and all_tables. */ ecs_query_op_profile_t *profile; - int16_t op; /* Currently iterated query plan operation (index into ops) */ + int16_t op; /* Currently iterated query plan operation (index into ops). */ bool iter_single_group; } ecs_query_iter_t; /* Private iterator data. Used by iterator implementations to keep track of - * progress & to provide builtin storage. */ + * progress and to provide built-in storage. */ typedef struct ecs_iter_private_t { union { ecs_query_iter_t query; ecs_page_iter_t page; ecs_worker_iter_t worker; ecs_each_iter_t each; - } iter; /* Iterator specific data */ + } iter; /* Iterator-specific data. */ - void *entity_iter; /* Query applied after matching a table */ - ecs_stack_cursor_t *stack_cursor; /* Stack cursor to restore to */ + void *entity_iter; /* Query applied after matching a table. */ + ecs_stack_cursor_t *stack_cursor; /* Stack cursor to restore to. */ } ecs_iter_private_t; -/* Data structures that store the command queue */ +/* Data structures that store the command queue. */ typedef struct ecs_commands_t { ecs_vec_t queue; - ecs_stack_t stack; /* Temp memory used by deferred commands */ - ecs_sparse_t entries; /* - command batching */ + ecs_stack_t stack; /* Temp memory used by deferred commands. */ + ecs_sparse_t entries; /* - command batching. */ } ecs_commands_t; #ifdef __cplusplus @@ -3921,30 +4910,30 @@ typedef struct ecs_commands_t { extern "C" { #endif -/** This is the largest possible component id. Components for the most part - * occupy the same id range as entities, however they are not allowed to overlap - * with (8) bits reserved for id flags. */ +/** This is the largest possible component ID. Components, for the most part, + * occupy the same ID range as entities, however they are not allowed to overlap + * with (8) bits reserved for ID flags. */ #define ECS_MAX_COMPONENT_ID (~((uint32_t)(ECS_ID_FLAGS_MASK >> 32))) /** The maximum number of nested function calls before the core will throw a - * cycle detected error */ + * cycle-detected error. */ #define ECS_MAX_RECURSION (512) -/** Maximum length of a parser token (used by parser-related addons) */ +/** Maximum length of a parser token (used by parser-related addons). */ #define ECS_MAX_TOKEN_SIZE (256) /** Convert a C module name into a path. - * This operation converts a PascalCase name to a path, for example MyFooModule + * This operation converts a PascalCase name to a path, for example, MyFooModule * into my.foo.module. * - * @param c_name The C module name + * @param c_name The C module name. * @return The path. */ FLECS_API char* flecs_module_path_from_c( const char *c_name); -/** Constructor that zeromem's a component value. +/** Constructor that zero-initializes a component value. * * @param ptr Pointer to the value. * @param count Number of elements to construct. @@ -3956,7 +4945,74 @@ void flecs_default_ctor( int32_t count, const ecs_type_info_t *type_info); -/** Create allocated string from format. +/* Wrapper functions for invoking type hooks with fallback behavior. */ +FLECS_API +bool flecs_type_info_ctor( + void *ptr, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +bool flecs_type_info_dtor( + void *ptr, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +void flecs_type_info_copy( + void *dst, + const void *src, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +void flecs_type_info_move( + void *dst, + void *src, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +void flecs_type_info_copy_ctor( + void *dst, + const void *src, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +void flecs_type_info_move_ctor( + void *dst, + void *src, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +void flecs_type_info_ctor_move_dtor( + void *dst, + void *src, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +void flecs_type_info_move_dtor( + void *dst, + void *src, + int32_t count, + const ecs_type_info_t *type_info); + +FLECS_API +int flecs_type_info_cmp( + const void *a, + const void *b, + const ecs_type_info_t *type_info); + +FLECS_API +bool flecs_type_info_equals( + const void *a, + const void *b, + const ecs_type_info_t *type_info); + +/** Create an allocated string from a format. * * @param fmt The format string. * @param args Format arguments. @@ -3967,7 +5023,7 @@ char* flecs_vasprintf( const char *fmt, va_list args); -/** Create allocated string from format. +/** Create an allocated string from a format. * * @param fmt The format string. * @return The formatted string. @@ -3978,11 +5034,11 @@ char* flecs_asprintf( ...); /** Write an escaped character. - * Write a character to an output string, insert escape character if necessary. + * Write a character to an output string, inserting an escape character if necessary. * * @param out The string to write the character to. * @param in The input character. - * @param delimiter The delimiter used (for example '"') + * @param delimiter The delimiter used (for example, '"'). * @return Pointer to the character after the last one written. */ FLECS_API @@ -3994,7 +5050,7 @@ char* flecs_chresc( /** Parse an escaped character. * Parse a character with a potential escape sequence. * - * @param in Pointer to character in input string. + * @param in Pointer to a character in the input string. * @param out Output string. * @return Pointer to the character after the last one read. */ @@ -4003,14 +5059,14 @@ const char* flecs_chrparse( char *out); /** Write an escaped string. - * Write an input string to an output string, escape characters where necessary. + * Write an input string to an output string, escaping characters where necessary. * To determine the size of the output string, call the operation with a NULL * argument for 'out', and use the returned size to allocate a string that is * large enough. * - * @param out Pointer to output string (must be). + * @param out Pointer to output string (may be NULL). * @param size Maximum number of characters written to output. - * @param delimiter The delimiter used (for example '"'). + * @param delimiter The delimiter used (for example, '"'). * @param in The input string. * @return The number of characters that (would) have been written. */ @@ -4021,13 +5077,13 @@ ecs_size_t flecs_stresc( char delimiter, const char *in); -/** Return escaped string. - * Return escaped version of input string. Same as flecs_stresc(), but returns an +/** Return an escaped string. + * Same as flecs_stresc(), but returns an * allocated string of the right size. * - * @param delimiter The delimiter used (for example '"'). + * @param delimiter The delimiter used (for example, '"'). * @param in The input string. - * @return Escaped string. + * @return The escaped string. */ FLECS_API char* flecs_astresc( @@ -4037,14 +5093,14 @@ char* flecs_astresc( /** Skip whitespace and newline characters. * This function skips whitespace characters. * - * @param ptr Pointer to (potential) whitespaces to skip. + * @param ptr Pointer to (potential) whitespace to skip. * @return Pointer to the next non-whitespace character. */ FLECS_API const char* flecs_parse_ws_eol( const char *ptr); -/** Parse digit. +/** Parse a digit. * This function will parse until the first non-digit character is found. The * provided expression must contain at least one digit character. * @@ -4057,23 +5113,23 @@ const char* flecs_parse_digit( const char *ptr, char *token); -/* Convert identifier to snake case */ +/* Convert an identifier to snake case. */ FLECS_API char* flecs_to_snake_case( const char *str); -/* Suspend/resume readonly state. To fully support implicit registration of +/* Suspend and resume read-only state. To fully support implicit registration of * components, it should be possible to register components while the world is - * in readonly mode. It is not uncommon that a component is used first from - * within a system, which are often ran while in readonly mode. - * - * Suspending readonly mode is only allowed when the world is not multithreaded. + * in read-only mode. It is not uncommon that a component is used first from + * within a system, which is often run while in read-only mode. + * + * Suspending read-only mode is only allowed when the world is not multithreaded. * When a world is multithreaded, it is not safe to (even temporarily) leave - * readonly mode, so a multithreaded application should always explicitly - * register components in advance. - * + * read-only mode, so a multithreaded application should always explicitly + * register components in advance. + * * These operations also suspend deferred mode. - * + * * Functions are public to support language bindings. */ typedef struct ecs_suspend_readonly_state_t { @@ -4098,16 +5154,17 @@ void flecs_resume_readonly( ecs_world_t *world, ecs_suspend_readonly_state_t *state); -/** Number of observed entities in table. - * Operation is public to support test cases. - * +/** Return the number of observed entities in a table. + * This operation is public to support test cases. + * * @param table The table. + * @return The number of observed entities. */ FLECS_DBG_API int32_t flecs_table_observed_count( const ecs_table_t *table); -/** Print backtrace to specified stream. +/** Print a backtrace to the specified stream. * * @param stream The stream to use for printing the backtrace. */ @@ -4115,7 +5172,7 @@ FLECS_DBG_API void flecs_dump_backtrace( void *stream); -/** Increase refcount of poly object. +/** Increase the refcount of a poly object. * * @param poly The poly object. * @return The refcount after incrementing. @@ -4124,7 +5181,7 @@ FLECS_API int32_t flecs_poly_claim_( ecs_poly_t *poly); -/** Decrease refcount of poly object. +/** Decrease the refcount of a poly object. * * @param poly The poly object. * @return The refcount after decrementing. @@ -4139,7 +5196,7 @@ int32_t flecs_poly_release_( #define flecs_poly_release(poly) \ flecs_poly_release_(ECS_CONST_CAST(void*, reinterpret_cast(poly))) -/** Return refcount of poly object. +/** Return the refcount of a poly object. * * @param poly The poly object. * @return Refcount of the poly object. @@ -4148,44 +5205,44 @@ FLECS_API int32_t flecs_poly_refcount( ecs_poly_t *poly); -/** Get unused index for static world local component id array. - * This operation returns an unused index for the world-local component id - * array. This index can be used by language bindings to obtain a component id. +/** Get an unused index for the static world-local component ID array. + * This operation returns an unused index for the world-local component ID + * array. This index can be used by language bindings to obtain a component ID. * - * @return Unused index for component id array. + * @return Unused index for component ID array. */ FLECS_API int32_t flecs_component_ids_index_get(void); -/** Get world local component id. - * +/** Get a world-local component ID. + * * @param world The world. - * @param index Component id array index. - * @return The component id. + * @param index Component ID array index. + * @return The component ID. */ FLECS_API ecs_entity_t flecs_component_ids_get( const ecs_world_t *world, int32_t index); -/** Get alive world local component id. - * Same as flecs_component_ids_get, but return 0 if component is no longer - * alive. - * +/** Get an alive world-local component ID. + * Same as flecs_component_ids_get(), but returns 0 if the component is no + * longer alive. + * * @param world The world. - * @param index Component id array index. - * @return The component id. + * @param index Component ID array index. + * @return The component ID. */ FLECS_API ecs_entity_t flecs_component_ids_get_alive( const ecs_world_t *world, int32_t index); -/** Set world local component id. - * +/** Set a world-local component ID. + * * @param world The world. - * @param index Component id array index. - * @param id The component id. + * @param index Component ID array index. + * @param id The component ID. */ FLECS_API void flecs_component_ids_set( @@ -4194,8 +5251,8 @@ void flecs_component_ids_set( ecs_entity_t id); /** Query iterator function for trivially cached queries. - * This operation can be called if an iterator matches the conditions for - * trivial iteration: + * This operation can be called if an iterator matches the conditions for + * trivial iteration. * * @param it The query iterator. * @return Whether the query has more results. @@ -4205,7 +5262,7 @@ bool flecs_query_trivial_cached_next( ecs_iter_t *it); #ifdef FLECS_DEBUG -/** Check if current thread has exclusive access to world. +/** Check if the current thread has exclusive access to the world. * This operation checks if the current thread is allowed to access the world. * The operation is called by internal functions before mutating the world, and * will panic if the current thread does not have exclusive access to the world. @@ -4223,7 +5280,7 @@ FLECS_API void flecs_check_exclusive_world_access_write( const ecs_world_t *world); -/** Same as flecs_check_exclusive_world_access_write, but for read access. +/** Same as flecs_check_exclusive_world_access_write(), but for read access. * * @param world The world. */ @@ -4236,8 +5293,26 @@ void flecs_check_exclusive_world_access_read( #define flecs_check_exclusive_world_access_read(world) #endif +/** End deferred mode (executes commands when stage->defer becomes 0). */ +FLECS_API +bool flecs_defer_end( + ecs_world_t *world, + ecs_stage_t *stage); + +#ifdef FLECS_JOURNAL +/** Get the current value of the operation counter. + * The journaling addon keeps track of an operation counter, which is incremented + * for each operation. Applications can use this counter to run up to the point + * where an error occurs for easier debugging. + * This value is not thread-safe. + * + * @return The operation counter. + */ +FLECS_API +int flecs_journal_get_counter(void); +#endif -/** Calculate offset from address */ +/** Calculate an offset from an address. */ #ifdef __cplusplus #define ECS_OFFSET(o, offset) reinterpret_cast((reinterpret_cast(o)) + (static_cast(offset))) #else @@ -4248,7 +5323,7 @@ void flecs_check_exclusive_world_access_read( #define ECS_ELEM(ptr, size, index) ECS_OFFSET(ptr, (size) * (index)) #define ECS_ELEM_T(o, T, index) ECS_ELEM(o, ECS_SIZEOF(T), index) -/** Enable/disable bitsets */ +/** Enable and disable bitsets. */ #define ECS_BIT_SET(flags, bit) (flags) |= (bit) #define ECS_BIT_CLEAR(flags, bit) (flags) &= ~(bit) #define ECS_BIT_COND(flags, bit, cond) ((cond) \ @@ -4285,31 +5360,44 @@ void flecs_check_exclusive_world_access_read( extern "C" { #endif +/** A bucket in the hashmap, storing parallel key and value vectors. */ typedef struct { - ecs_vec_t keys; - ecs_vec_t values; + ecs_vec_t keys; /**< Vector of keys. */ + ecs_vec_t values; /**< Vector of values. */ } ecs_hm_bucket_t; +/** A hashmap that supports variable-sized keys and values. */ typedef struct { - ecs_hash_value_action_t hash; - ecs_compare_action_t compare; - ecs_size_t key_size; - ecs_size_t value_size; - ecs_map_t impl; + ecs_hash_value_action_t hash; /**< Hash function for keys. */ + ecs_compare_action_t compare; /**< Compare function for keys. */ + ecs_size_t key_size; /**< Size of key type. */ + ecs_size_t value_size; /**< Size of value type. */ + ecs_map_t impl; /**< Underlying map implementation. */ } ecs_hashmap_t; +/** Iterator for a hashmap. */ typedef struct { - ecs_map_iter_t it; - ecs_hm_bucket_t *bucket; - int32_t index; + ecs_map_iter_t it; /**< Underlying map iterator. */ + ecs_hm_bucket_t *bucket; /**< Current bucket. */ + int32_t index; /**< Current index within the bucket. */ } flecs_hashmap_iter_t; +/** Result of a hashmap ensure operation. */ typedef struct { - void *key; - void *value; - uint64_t hash; + void *key; /**< Pointer to the key. */ + void *value; /**< Pointer to the value. */ + uint64_t hash; /**< Hash value of the key. */ } flecs_hashmap_result_t; +/** Initialize a hashmap. + * + * @param hm The hashmap to initialize. + * @param key_size The size of the key type. + * @param value_size The size of the value type. + * @param hash The hash function. + * @param compare The compare function. + * @param allocator The allocator. + */ FLECS_DBG_API void flecs_hashmap_init_( ecs_hashmap_t *hm, @@ -4319,13 +5407,26 @@ void flecs_hashmap_init_( ecs_compare_action_t compare, ecs_allocator_t *allocator); +/** Type-safe hashmap initialization. */ #define flecs_hashmap_init(hm, K, V, hash, compare, allocator)\ flecs_hashmap_init_(hm, ECS_SIZEOF(K), ECS_SIZEOF(V), hash, compare, allocator) +/** Deinitialize a hashmap. + * + * @param map The hashmap to deinitialize. + */ FLECS_DBG_API void flecs_hashmap_fini( ecs_hashmap_t *map); +/** Get a value from the hashmap. + * + * @param map The hashmap. + * @param key_size The size of the key type. + * @param key The key to look up. + * @param value_size The size of the value type. + * @return Pointer to the value, or NULL if not found. + */ FLECS_DBG_API void* flecs_hashmap_get_( const ecs_hashmap_t *map, @@ -4333,9 +5434,18 @@ void* flecs_hashmap_get_( const void *key, ecs_size_t value_size); +/** Type-safe hashmap get. */ #define flecs_hashmap_get(map, key, V)\ (V*)flecs_hashmap_get_(map, ECS_SIZEOF(*key), key, ECS_SIZEOF(V)) +/** Ensure a key exists in the hashmap, inserting if necessary. + * + * @param map The hashmap. + * @param key_size The size of the key type. + * @param key The key to ensure. + * @param value_size The size of the value type. + * @return A result containing pointers to the key, value, and hash. + */ FLECS_DBG_API flecs_hashmap_result_t flecs_hashmap_ensure_( ecs_hashmap_t *map, @@ -4343,9 +5453,18 @@ flecs_hashmap_result_t flecs_hashmap_ensure_( const void *key, ecs_size_t value_size); +/** Type-safe hashmap ensure. */ #define flecs_hashmap_ensure(map, key, V)\ flecs_hashmap_ensure_(map, ECS_SIZEOF(*key), key, ECS_SIZEOF(V)) +/** Set a key-value pair in the hashmap. + * + * @param map The hashmap. + * @param key_size The size of the key type. + * @param key The key. + * @param value_size The size of the value type. + * @param value The value to set. + */ FLECS_DBG_API void flecs_hashmap_set_( ecs_hashmap_t *map, @@ -4354,9 +5473,17 @@ void flecs_hashmap_set_( ecs_size_t value_size, const void *value); +/** Type-safe hashmap set. */ #define flecs_hashmap_set(map, key, value)\ flecs_hashmap_set_(map, ECS_SIZEOF(*key), key, ECS_SIZEOF(*value), value) +/** Remove a key from the hashmap. + * + * @param map The hashmap. + * @param key_size The size of the key type. + * @param key The key to remove. + * @param value_size The size of the value type. + */ FLECS_DBG_API void flecs_hashmap_remove_( ecs_hashmap_t *map, @@ -4364,9 +5491,18 @@ void flecs_hashmap_remove_( const void *key, ecs_size_t value_size); +/** Type-safe hashmap remove. */ #define flecs_hashmap_remove(map, key, V)\ flecs_hashmap_remove_(map, ECS_SIZEOF(*key), key, ECS_SIZEOF(V)) +/** Remove a key from the hashmap using a precomputed hash. + * + * @param map The hashmap. + * @param key_size The size of the key type. + * @param key The key to remove. + * @param value_size The size of the value type. + * @param hash The precomputed hash of the key. + */ FLECS_DBG_API void flecs_hashmap_remove_w_hash_( ecs_hashmap_t *map, @@ -4375,14 +5511,28 @@ void flecs_hashmap_remove_w_hash_( ecs_size_t value_size, uint64_t hash); +/** Type-safe hashmap remove with precomputed hash. */ #define flecs_hashmap_remove_w_hash(map, key, V, hash)\ flecs_hashmap_remove_w_hash_(map, ECS_SIZEOF(*key), key, ECS_SIZEOF(V), hash) +/** Get a bucket from the hashmap by hash value. + * + * @param map The hashmap. + * @param hash The hash value. + * @return The bucket, or NULL if not found. + */ FLECS_DBG_API ecs_hm_bucket_t* flecs_hashmap_get_bucket( const ecs_hashmap_t *map, uint64_t hash); +/** Remove an entry from a hashmap bucket by index. + * + * @param map The hashmap. + * @param bucket The bucket. + * @param hash The hash value. + * @param index The index within the bucket to remove. + */ FLECS_DBG_API void flecs_hm_bucket_remove( ecs_hashmap_t *map, @@ -4390,15 +5540,33 @@ void flecs_hm_bucket_remove( uint64_t hash, int32_t index); +/** Copy a hashmap. + * + * @param dst The destination hashmap. + * @param src The source hashmap. + */ FLECS_DBG_API void flecs_hashmap_copy( ecs_hashmap_t *dst, const ecs_hashmap_t *src); +/** Create an iterator for a hashmap. + * + * @param map The hashmap to iterate. + * @return The iterator. + */ FLECS_DBG_API flecs_hashmap_iter_t flecs_hashmap_iter( ecs_hashmap_t *map); +/** Get the next element from a hashmap iterator. + * + * @param it The hashmap iterator. + * @param key_size The size of the key type. + * @param key_out Output parameter for the key. + * @param value_size The size of the value type. + * @return Pointer to the value, or NULL if no more elements. + */ FLECS_DBG_API void* flecs_hashmap_next_( flecs_hashmap_iter_t *it, @@ -4406,9 +5574,11 @@ void* flecs_hashmap_next_( void *key_out, ecs_size_t value_size); +/** Type-safe hashmap next (value only). */ #define flecs_hashmap_next(map, V)\ (V*)flecs_hashmap_next_(map, 0, NULL, ECS_SIZEOF(V)) +/** Type-safe hashmap next with key output. */ #define flecs_hashmap_next_w_key(map, K, key, V)\ (V*)flecs_hashmap_next_(map, ECS_SIZEOF(K), key, ECS_SIZEOF(V)) @@ -4435,39 +5605,44 @@ extern "C" { /** Record for entity index. */ struct ecs_record_t { - ecs_table_t *table; /**< Identifies a type (and table) in world */ - uint32_t row; /**< Table row of the entity */ - int32_t dense; /**< Index in dense array of entity index */ + ecs_table_t *table; /**< Identifies a type (and table) in the world. */ + uint32_t row; /**< Table row of the entity. */ + int32_t dense; /**< Index in dense array of entity index. */ }; /** Header for table cache elements. */ typedef struct ecs_table_cache_hdr_t { struct ecs_component_record_t *cr; /**< Component record for component. */ ecs_table_t *table; /**< Table associated with element. */ - struct ecs_table_cache_hdr_t *prev, *next; /**< Next/previous elements for id in table cache. */ + struct ecs_table_cache_hdr_t *prev, *next; /**< Previous and next elements for ID in table cache. */ } ecs_table_cache_hdr_t; -/** Record that stores location of a component in a table. +/** Record that stores the location of a component in a table. * Table records are registered with component records, which allows for quickly * finding all tables for a specific component. */ struct ecs_table_record_t { - ecs_table_cache_hdr_t hdr; /**< Table cache header */ - int16_t index; /**< First type index where id occurs in table */ - int16_t count; /**< Number of times id occurs in table */ - int16_t column; /**< First column index where id occurs */ + ecs_table_cache_hdr_t hdr; /**< Table cache header. */ + int16_t index; /**< First type index where ID occurs in table. */ + int16_t count; /**< Number of times ID occurs in table. */ + int16_t column; /**< First column index where ID occurs. */ }; -/** Type that contains information about which components got added/removed on +/** Type that contains information about which components got added or removed on * a table edge. */ typedef struct ecs_table_diff_t { - ecs_type_t added; /* Components added between tables */ - ecs_type_t removed; /* Components removed between tables */ + ecs_type_t added; /* Components added between tables. */ + ecs_type_t removed; /* Components removed between tables. */ ecs_flags32_t added_flags; ecs_flags32_t removed_flags; } ecs_table_diff_t; +/* Tracks which and how many non-fragmenting children are stored in a table for a parent. */ +typedef struct ecs_parent_record_t { + uint32_t entity; /* If the table only contains a single entity for the parent, this will contain the entity ID (without generation). */ + int32_t count; /* The number of children for a parent in the table. */ +} ecs_parent_record_t; -/** Find record for entity. +/** Find the record for an entity. * An entity record contains the table and row for the entity. * * To use ecs_record_t::row as the record in the table, use: @@ -4484,27 +5659,27 @@ ecs_record_t* ecs_record_find( const ecs_world_t *world, ecs_entity_t entity); -/** Get entity corresponding with record. +/** Get the entity corresponding to a record. * This operation only works for entities that are not empty. * - * @param record The record for which to obtain the entity id. - * @return The entity id for the record. + * @param record The record for which to obtain the entity ID. + * @return The entity ID for the record. */ FLECS_API ecs_entity_t ecs_record_get_entity( const ecs_record_t *record); -/** Begin exclusive write access to entity. +/** Begin exclusive write access to an entity. * This operation provides safe exclusive access to the components of an entity * without the overhead of deferring operations. * * When this operation is called simultaneously for the same entity more than - * once it will throw an assert. Note that for this to happen, asserts must be + * once, it will throw an assert. Note that for this to happen, asserts must be * enabled. It is up to the application to ensure that access is exclusive, for - * example by using a read-write mutex. + * example, by using a read-write mutex. * * Exclusive access is enforced at the table level, so only one entity can be - * exclusively accessed per table. The exclusive access check is thread safe. + * exclusively accessed per table. The exclusive access check is thread-safe. * * This operation must be followed up with ecs_write_end(). * @@ -4517,7 +5692,7 @@ ecs_record_t* ecs_write_begin( ecs_world_t *world, ecs_entity_t entity); -/** End exclusive write access to entity. +/** End exclusive write access to an entity. * This operation ends exclusive access, and must be called after * ecs_write_begin(). * @@ -4527,18 +5702,18 @@ FLECS_API void ecs_write_end( ecs_record_t *record); -/** Begin read access to entity. +/** Begin read access to an entity. * This operation provides safe read access to the components of an entity. * Multiple simultaneous reads are allowed per entity. * * This operation ensures that code attempting to mutate the entity's table will * throw an assert. Note that for this to happen, asserts must be enabled. It is - * up to the application to ensure that this does not happen, for example by + * up to the application to ensure that this does not happen, for example, by * using a read-write mutex. * * This operation does *not* provide the same guarantees as a read-write mutex, * as it is possible to call ecs_read_begin() after calling ecs_write_begin(). It is - * up to application has to ensure that this does not happen. + * up to the application to ensure that this does not happen. * * This operation must be followed up with ecs_read_end(). * @@ -4551,7 +5726,7 @@ const ecs_record_t* ecs_read_begin( ecs_world_t *world, ecs_entity_t entity); -/** End read access to entity. +/** End read access to an entity. * This operation ends read access, and must be called after ecs_read_begin(). * * @param record Record to the entity. @@ -4560,7 +5735,7 @@ FLECS_API void ecs_read_end( const ecs_record_t *record); -/** Get component from entity record. +/** Get a component from an entity record. * This operation returns a pointer to a component for the entity * associated with the provided record. For safe access to the component, obtain * the record with ecs_read_begin() or ecs_write_begin(). @@ -4570,7 +5745,7 @@ void ecs_read_end( * * @param world The world. * @param record Record to the entity. - * @param id The (component) id. + * @param id The (component) ID. * @return Pointer to component, or NULL if entity does not have the component. * * @see ecs_record_ensure_id() @@ -4586,7 +5761,7 @@ const void* ecs_record_get_id( * * @param world The world. * @param record Record to the entity. - * @param id The (component) id. + * @param id The (component) ID. * @return Pointer to component, or NULL if entity does not have the component. */ FLECS_API @@ -4595,11 +5770,11 @@ void* ecs_record_ensure_id( ecs_record_t *record, ecs_id_t id); -/** Test if entity for record has a (component) id. +/** Test if the entity for a record has a (component) ID. * * @param world The world. * @param record Record to the entity. - * @param id The (component) id. + * @param id The (component) ID. * @return Whether the entity has the component. */ FLECS_API @@ -4608,7 +5783,7 @@ bool ecs_record_has_id( const ecs_record_t *record, ecs_id_t id); -/** Get component pointer from column/record. +/** Get a component pointer from a column and record. * This returns a pointer to the component using a table column index. The * table's column index can be found with ecs_table_get_column_index(). * @@ -4630,10 +5805,10 @@ void* ecs_record_get_by_column( int32_t column, size_t size); -/** Get component record for component id. - * +/** Get the component record for a component ID. + * * @param world The world. - * @param id The component id. + * @param id The component ID. * @return The component record, or NULL if it doesn't exist. */ FLECS_API @@ -4641,27 +5816,48 @@ FLECS_ALWAYS_INLINE ecs_component_record_t* flecs_components_get( const ecs_world_t *world, ecs_id_t id); -/** Get component id from component record. - * +/** Ensure a component record for a component ID. + * + * @param world The world. + * @param id The component ID. + * @return The new or existing component record. + */ +FLECS_API +FLECS_ALWAYS_INLINE ecs_component_record_t* flecs_components_ensure( + ecs_world_t *world, + ecs_id_t id); + +/** Get the component ID from a component record. + * * @param cr The component record. - * @return The component id. + * @return The component ID. */ FLECS_API ecs_id_t flecs_component_get_id( const ecs_component_record_t *cr); -/** Get component flags for component. - * - * @param id The component id. - * @return The flags for the component id. +/** Get the component flags for a component. + * + * @param world The world. + * @param id The component ID. + * @return The flags for the component ID. */ FLECS_API ecs_flags32_t flecs_component_get_flags( const ecs_world_t *world, ecs_id_t id); -/** Find table record for component record. - * This operation returns the table record for the table/component record if it +/** Get the type info for a component record. + * + * @param cr The component record. + * @return The type info struct, or NULL if the component is a tag. + */ +FLECS_API +const ecs_type_info_t* flecs_component_get_type_info( + const ecs_component_record_t *cr); + +/** Find the table record for a component record. + * This operation returns the table record for the table and component record if it * exists. If the record exists, it means the table has the component. * * @param cr The component record. @@ -4673,7 +5869,42 @@ FLECS_ALWAYS_INLINE const ecs_table_record_t* flecs_component_get_table( const ecs_component_record_t *cr, const ecs_table_t *table); -/** Create component record iterator. +/** Get the parent record for a component and table. + * A parent record stores how many children for a parent are stored in the + * specified table. If the table only stores a single child, the parent record + * will also store the entity ID of that child. + * + * This information is used by queries to determine whether an O(n) search + * through the table is required to find all children for the parent. If the + * table only contains a single child, the query can use + * ecs_parent_record_t::entity directly, otherwise it has to do a scan. + * + * The component record specified to this function must be a ChildOf pair. Only + * tables with children that use the non-fragmenting hierarchy storage will have + * parent records. + * + * @param cr The ChildOf component record. + * @param table The table to check the number of children for. + * @return The parent record if it exists, NULL if it does not. +*/ +FLECS_API +FLECS_ALWAYS_INLINE ecs_parent_record_t* flecs_component_get_parent_record( + const ecs_component_record_t *cr, + const ecs_table_t *table); + +/** Return the hierarchy depth for a component record. + * The specified component record must be a ChildOf pair. This function does not + * compute the depth, it just returns the precomputed depth that is updated + * automatically when hierarchy changes happen. + * + * @param cr The ChildOf component record. + * @return The depth of the parent's children in the hierarchy. + */ +FLECS_API +FLECS_ALWAYS_INLINE int32_t flecs_component_get_childof_depth( + const ecs_component_record_t *cr); + +/** Create a component record iterator. * A component record iterator iterates all tables for the specified component * record. * @@ -4699,8 +5930,8 @@ bool flecs_component_iter( const ecs_component_record_t *cr, ecs_table_cache_iter_t *iter_out); -/** Get next table record for iterator. - * Returns next table record for iterator. +/** Get the next table record for the iterator. + * Returns the next table record, or NULL if there are no more results. * * @param iter The iterator. * @return The next table record, or NULL if there are no more results. @@ -4715,7 +5946,7 @@ typedef struct ecs_table_records_t { int32_t count; } ecs_table_records_t; -/** Get table records. +/** Get the table records. * This operation returns an array with all records for the specified table. * * @param table The table. @@ -4725,7 +5956,7 @@ FLECS_API ecs_table_records_t flecs_table_records( ecs_table_t* table); -/** Get component record from table record. +/** Get the component record from a table record. * * @param tr The table record. * @return The component record. @@ -4734,24 +5965,24 @@ FLECS_API ecs_component_record_t* flecs_table_record_get_component( const ecs_table_record_t *tr); -/** Get table id. +/** Get the table ID. * This operation returns a unique numerical identifier for a table. - * + * * @param table The table. - * @return The table records for the table. + * @return The unique identifier for the table. */ FLECS_API uint64_t flecs_table_id( ecs_table_t* table); -/** Find table by adding id to current table. - * Same as ecs_table_add_id, but with additional diff parameter that contains +/** Find a table by adding an ID to the current table. + * Same as ecs_table_add_id(), but with an additional diff parameter that contains * information about the traversed edge. - * + * * @param world The world. * @param table The table. - * @param id_ptr Pointer to component id to add. - * @param diff Information about traversed edge (out parameter). + * @param id_ptr Pointer to the component ID to add. + * @param diff Information about the traversed edge (out parameter). * @return The table that was traversed to. */ FLECS_API @@ -4781,7 +6012,7 @@ typedef struct ecs_value_t { typedef struct ecs_entity_desc_t { int32_t _canary; /**< Used for validity testing. Must be 0. */ - ecs_entity_t id; /**< Set to modify existing entity (optional) */ + ecs_entity_t id; /**< Set to modify existing entity (optional). */ ecs_entity_t parent; /**< Parent entity. */ @@ -4791,32 +6022,32 @@ typedef struct ecs_entity_desc_t { * with the existing entity. */ const char *sep; /**< Optional custom separator for hierarchical names. - * Leave to NULL for default ('.') separator. Set to - * an empty string to prevent tokenization of name. */ + * Leave to NULL for the default ('.') separator. Set to + * an empty string to prevent tokenization of the name. */ - const char *root_sep; /**< Optional, used for identifiers relative to root */ + const char *root_sep; /**< Optional, used for identifiers relative to the root. */ const char *symbol; /**< Optional entity symbol. A symbol is an unscoped - * identifier that can be used to lookup an entity. The + * identifier that can be used to look up an entity. The * primary use case for this is to associate the entity * with a language identifier, such as a type or * function name, where these identifiers differ from - * the name they are registered with in flecs. For + * the name they are registered with in Flecs. For * example, C type "EcsPosition" might be registered * as "flecs.components.transform.Position", with the * symbol set to "EcsPosition". */ bool use_low_id; /**< When set to true, a low id (typically reserved for * components) will be used to create the entity, if - * no id is specified. */ + * no ID is specified. */ - /** 0-terminated array of ids to add to the entity. */ + /** 0-terminated array of IDs to add to the entity. */ const ecs_id_t *add; /** 0-terminated array of values to set on the entity. */ const ecs_value_t *set; - /** String expression with components to add */ + /** String expression with components to add. */ const char *add_expr; } ecs_entity_desc_t; @@ -4827,14 +6058,14 @@ typedef struct ecs_entity_desc_t { typedef struct ecs_bulk_desc_t { int32_t _canary; /**< Used for validity testing. Must be 0. */ - ecs_entity_t *entities; /**< Entities to bulk insert. Entity ids provided by + ecs_entity_t *entities; /**< Entities to bulk insert. Entity IDs provided by * the application must be empty (cannot - * have components). If no entity ids are provided, the + * have components). If no entity IDs are provided, the * operation will create 'count' new entities. */ - int32_t count; /**< Number of entities to create/populate */ + int32_t count; /**< Number of entities to create/populate. */ - ecs_id_t ids[FLECS_ID_DESC_MAX]; /**< Ids to create the entities with */ + ecs_id_t ids[FLECS_ID_DESC_MAX]; /**< IDs to create the entities with. */ void **data; /**< Array with component data to insert. Each element in * the array must correspond with an element in the ids @@ -4857,10 +6088,10 @@ typedef struct ecs_bulk_desc_t { typedef struct ecs_component_desc_t { int32_t _canary; /**< Used for validity testing. Must be 0. */ - /** Existing entity to associate with observer (optional) */ + /** Existing entity to associate with a component (optional). */ ecs_entity_t entity; - /** Parameters for type (size, hooks, ...) */ + /** Parameters for type (size, hooks, ...). */ ecs_type_info_t type; } ecs_component_desc_t; @@ -4885,7 +6116,7 @@ typedef struct ecs_component_desc_t { * } * @endcode * - * An iterator contains resources that need to be released. By default this + * An iterator contains resources that need to be released. By default, this * is handled by the last call to next() that returns false. When iteration is * ended before iteration has completed, an application has to manually call * ecs_iter_fini() to release the iterator resources: @@ -4904,63 +6135,63 @@ typedef struct ecs_component_desc_t { */ struct ecs_iter_t { /* World */ - ecs_world_t *world; /**< The world. Can point to stage when in deferred/readonly mode. */ + ecs_world_t *world; /**< The world. Can point to a stage when in deferred or readonly mode. */ ecs_world_t *real_world; /**< Actual world. Never points to a stage. */ /* Matched data */ - int32_t offset; /**< Offset relative to current table */ - int32_t count; /**< Number of entities to iterate */ - const ecs_entity_t *entities; /**< Entity identifiers */ - void **ptrs; /**< Component pointers. If not set or if it's NULL for a field, use it.trs. */ - const ecs_table_record_t **trs; /**< Info on where to find field in table */ - const ecs_size_t *sizes; /**< Component sizes */ - ecs_table_t *table; /**< Current table */ - ecs_table_t *other_table; /**< Prev or next table when adding/removing */ - ecs_id_t *ids; /**< (Component) ids */ - ecs_entity_t *sources; /**< Entity on which the id was matched (0 if same as entities) */ - ecs_flags64_t constrained_vars; /**< Bitset that marks constrained variables */ - ecs_termset_t set_fields; /**< Fields that are set */ - ecs_termset_t ref_fields; /**< Bitset with fields that aren't component arrays */ - ecs_termset_t row_fields; /**< Fields that must be obtained with field_at */ - ecs_termset_t up_fields; /**< Bitset with fields matched through up traversal */ + int32_t offset; /**< Offset relative to the current table. */ + int32_t count; /**< Number of entities to iterate. */ + const ecs_entity_t *entities; /**< Entity identifiers. */ + void **ptrs; /**< Component pointers. If not set or if it is NULL for a field, use it->trs. */ + const ecs_table_record_t **trs; /**< Info on where to find the field in the table. */ + const ecs_size_t *sizes; /**< Component sizes. */ + ecs_table_t *table; /**< Current table. */ + ecs_table_t *other_table; /**< Previous or next table when adding or removing. */ + ecs_id_t *ids; /**< (Component) IDs. */ + ecs_entity_t *sources; /**< Entity on which the ID was matched (0 if same as entities). */ + ecs_flags64_t constrained_vars; /**< Bitset that marks constrained variables. */ + ecs_termset_t set_fields; /**< Fields that are set. */ + ecs_termset_t ref_fields; /**< Bitset with fields that aren't component arrays. */ + ecs_termset_t row_fields; /**< Fields that must be obtained with field_at. */ + ecs_termset_t up_fields; /**< Bitset with fields matched through up traversal. */ /* Input information */ - ecs_entity_t system; /**< The system (if applicable) */ - ecs_entity_t event; /**< The event (if applicable) */ - ecs_id_t event_id; /**< The (component) id for the event */ - int32_t event_cur; /**< Unique event id. Used to dedup observer calls */ + ecs_entity_t system; /**< The system (if applicable). */ + ecs_entity_t event; /**< The event (if applicable). */ + ecs_id_t event_id; /**< The (component) ID for the event. */ + int32_t event_cur; /**< Unique event ID. Used to dedup observer calls. */ /* Query information */ - int8_t field_count; /**< Number of fields in iterator */ - int8_t term_index; /**< Index of term that emitted an event. + int8_t field_count; /**< Number of fields in the iterator. */ + int8_t term_index; /**< Index of the term that emitted an event. * This field will be set to the 'index' field * of an observer term. */ - const ecs_query_t *query; /**< Query being evaluated */ + const ecs_query_t *query; /**< Query being evaluated. */ /* Context */ - void *param; /**< Param passed to ecs_run */ - void *ctx; /**< System context */ - void *binding_ctx; /**< System binding context */ - void *callback_ctx; /**< Callback language binding context */ - void *run_ctx; /**< Run language binding context */ + void *param; /**< Param passed to ecs_run(). */ + void *ctx; /**< System context. */ + void *binding_ctx; /**< System binding context. */ + void *callback_ctx; /**< Callback language binding context. */ + void *run_ctx; /**< Run language binding context. */ /* Time */ - ecs_ftime_t delta_time; /**< Time elapsed since last frame */ - ecs_ftime_t delta_system_time;/**< Time elapsed since last system invocation */ + ecs_ftime_t delta_time; /**< Time elapsed since last frame. */ + ecs_ftime_t delta_system_time;/**< Time elapsed since last system invocation. */ /* Iterator counters */ - int32_t frame_offset; /**< Offset relative to start of iteration */ + int32_t frame_offset; /**< Offset relative to the start of iteration. */ /* Misc */ - ecs_flags32_t flags; /**< Iterator flags */ - ecs_entity_t interrupted_by; /**< When set, system execution is interrupted */ - ecs_iter_private_t priv_; /**< Private data */ + ecs_flags32_t flags; /**< Iterator flags. */ + ecs_entity_t interrupted_by; /**< When set, system execution is interrupted. */ + ecs_iter_private_t priv_; /**< Private data. */ /* Chained iterators */ - ecs_iter_next_action_t next; /**< Function to progress iterator */ - ecs_iter_action_t callback; /**< Callback of system or observer */ - ecs_iter_fini_action_t fini; /**< Function to cleanup iterator resources */ - ecs_iter_t *chain_it; /**< Optional, allows for creating iterator chains */ + ecs_iter_next_action_t next; /**< Function to progress iterator. */ + ecs_iter_action_t callback; /**< Callback of system or observer. */ + ecs_iter_fini_action_t fini; /**< Function to clean up iterator resources. */ + ecs_iter_t *chain_it; /**< Optional, allows for creating iterator chains. */ }; @@ -4988,13 +6219,13 @@ struct ecs_iter_t { */ #define EcsQueryAllowUnresolvedByName (1u << 6u) -/** Query only returns whole tables (ignores toggle/member fields). +/** Query only returns whole tables (ignores toggle or member fields). * Can be combined with other query flags on the ecs_query_desc_t::flags field. * \ingroup queries */ #define EcsQueryTableOnly (1u << 7u) -/** Enable change detection for query. +/** Enable change detection for a query. * Can be combined with other query flags on the ecs_query_desc_t::flags field. * * Adding this flag makes it possible to use ecs_query_changed() and @@ -5015,19 +6246,19 @@ typedef struct ecs_query_desc_t { /** Used for validity testing. Must be 0. */ int32_t _canary; - /** Query terms */ + /** Query terms. */ ecs_term_t terms[FLECS_TERM_COUNT_MAX]; - /** Query DSL expression (optional) */ + /** Query DSL expression (optional). */ const char *expr; - /** Caching policy of query */ + /** Caching policy of the query. */ ecs_query_cache_kind_t cache_kind; - /** Flags for enabling query features */ + /** Flags for enabling query features. */ ecs_flags32_t flags; - /** Callback used for ordering query results. If order_by_id is 0, the + /** Callback used for ordering query results. If order_by is 0, the * pointer provided to the callback will be NULL. If the callback is not * set, results will not be ordered. */ ecs_order_by_action_t order_by_callback; @@ -5040,7 +6271,7 @@ typedef struct ecs_query_desc_t { * order_by_table_callback. */ ecs_entity_t order_by; - /** Component id to be used for grouping. Used together with the + /** Component ID to be used for grouping. Used together with the * group_by_callback. */ ecs_id_t group_by; @@ -5059,25 +6290,25 @@ typedef struct ecs_query_desc_t { * value of the on_group_create callback is passed as context parameter. */ ecs_group_delete_action_t on_group_delete; - /** Context to pass to group_by */ + /** Context to pass to group_by. */ void *group_by_ctx; - /** Function to free group_by_ctx */ + /** Function to free group_by_ctx. */ ecs_ctx_free_t group_by_ctx_free; - /** User context to pass to callback */ + /** User context to pass to callback. */ void *ctx; - /** Context to be used for language bindings */ + /** Context to be used for language bindings. */ void *binding_ctx; - /** Callback to free ctx */ + /** Callback to free ctx. */ ecs_ctx_free_t ctx_free; - /** Callback to free binding_ctx */ + /** Callback to free binding_ctx. */ ecs_ctx_free_t binding_ctx_free; - /** Entity associated with query (optional) */ + /** Entity associated with query (optional). */ ecs_entity_t entity; } ecs_query_desc_t; @@ -5089,34 +6320,39 @@ typedef struct ecs_observer_desc_t { /** Used for validity testing. Must be 0. */ int32_t _canary; - /** Existing entity to associate with observer (optional) */ + /** Existing entity to associate with an observer (optional). */ ecs_entity_t entity; - /** Query for observer */ + /** Query for observer. */ ecs_query_desc_t query; - /** Events to observe (OnAdd, OnRemove, OnSet) */ + /** Events to observe (OnAdd, OnRemove, OnSet). */ ecs_entity_t events[FLECS_EVENT_DESC_MAX]; - /** When observer is created, generate events from existing data. For example, + /** When an observer is created, generate events from existing data. For example, * #EcsOnAdd `Position` would match all existing instances of `Position`. */ bool yield_existing; + /** Global observers are tied to the lifespan of the world. Creating a + * global observer does not create an entity, and therefore + * ecs_observer_init() will not return an entity handle. */ + bool global_observer; + /** Callback to invoke on an event, invoked when the observer matches. */ ecs_iter_action_t callback; - /** Callback invoked on an event. When left to NULL the default runner - * is used which matches the event with the observer's query, and calls + /** Callback invoked on an event. When left to NULL, the default runner + * is used, which matches the event with the observer's query, and calls * 'callback' when it matches. * A reason to override the run function is to improve performance, if there - * are more efficient way to test whether an event matches the observer than - * the general purpose query matcher. */ + * are more efficient ways to test whether an event matches the observer than + * the general-purpose query matcher. */ ecs_run_action_t run; - /** User context to pass to callback */ + /** User context to pass to callback. */ void *ctx; - /** Callback to free ctx */ + /** Callback to free ctx. */ ecs_ctx_free_t ctx_free; /** Context associated with callback (for language bindings). */ @@ -5133,8 +6369,8 @@ typedef struct ecs_observer_desc_t { /** Used for internal purposes. Do not set. */ int32_t *last_event_id; - int8_t term_index_; - ecs_flags32_t flags_; + int8_t term_index_; /**< Used for internal purposes. Do not set. */ + ecs_flags32_t flags_; /**< Used for internal purposes. Do not set. */ } ecs_observer_desc_t; /** Used with ecs_emit(). @@ -5142,22 +6378,22 @@ typedef struct ecs_observer_desc_t { * @ingroup observers */ typedef struct ecs_event_desc_t { - /** The event id. Only observers for the specified event will be notified */ + /** The event ID. Only observers for the specified event will be notified. */ ecs_entity_t event; - /** Component ids. Only observers with a matching component id will be + /** Component IDs. Only observers with a matching component ID will be * notified. Observers are guaranteed to get notified once, even if they - * match more than one id. */ + * match more than one ID. */ const ecs_type_t *ids; /** The table for which to notify. */ ecs_table_t *table; - /** Optional 2nd table to notify. This can be used to communicate the + /** Optional second table to notify. This can be used to communicate the * previous or next table, in case an entity is moved between tables. */ ecs_table_t *other_table; - /** Limit notified entities to ones starting from offset (row) in table */ + /** Limit notified entities to ones starting from offset (row) in table. */ int32_t offset; /** Limit number of notified entities to count. offset+count must be less @@ -5165,12 +6401,12 @@ typedef struct ecs_event_desc_t { * automatically determined by doing `ecs_table_count(table) - offset`. */ int32_t count; - /** Single-entity alternative to setting table / offset / count */ + /** Single-entity alternative to setting table / offset / count. */ ecs_entity_t entity; /** Optional context. * The type of the param must be the event, where the event is a component. - * When an event is enqueued, the value of param is coped to a temporary + * When an event is enqueued, the value of param is copied to a temporary * storage of the event type. */ void *param; @@ -5179,89 +6415,89 @@ typedef struct ecs_event_desc_t { * is copied to a temporary storage of the event type. */ const void *const_param; - /** Observable (usually the world) */ + /** Observable (usually the world). */ ecs_poly_t *observable; - /** Event flags */ + /** Event flags. */ ecs_flags32_t flags; } ecs_event_desc_t; /** * @defgroup misc_types Miscellaneous types - * Types used to create entities, observers, queries and more. + * Types used to create entities, observers, queries, and more. * * @{ */ -/** Type with information about the current Flecs build */ +/** Type with information about the current Flecs build. */ typedef struct ecs_build_info_t { - const char *compiler; /**< Compiler used to compile flecs */ - const char **addons; /**< Addons included in build */ - const char **flags; /**< Compile time settings */ - const char *version; /**< Stringified version */ - int16_t version_major; /**< Major flecs version */ - int16_t version_minor; /**< Minor flecs version */ - int16_t version_patch; /**< Patch flecs version */ - bool debug; /**< Is this a debug build */ - bool sanitize; /**< Is this a sanitize build */ - bool perf_trace; /**< Is this a perf tracing build */ + const char *compiler; /**< Compiler used to compile Flecs. */ + const char **addons; /**< Addons included in the build. */ + const char **flags; /**< Compile-time settings. */ + const char *version; /**< Stringified version. */ + int16_t version_major; /**< Major Flecs version. */ + int16_t version_minor; /**< Minor Flecs version. */ + int16_t version_patch; /**< Patch Flecs version. */ + bool debug; /**< Is this a debug build? */ + bool sanitize; /**< Is this a sanitize build? */ + bool perf_trace; /**< Is this a perf tracing build? */ } ecs_build_info_t; /** Type that contains information about the world. */ typedef struct ecs_world_info_t { - ecs_entity_t last_component_id; /**< Last issued component entity id */ - ecs_entity_t min_id; /**< First allowed entity id */ - ecs_entity_t max_id; /**< Last allowed entity id */ - - ecs_ftime_t delta_time_raw; /**< Raw delta time (no time scaling) */ - ecs_ftime_t delta_time; /**< Time passed to or computed by ecs_progress() */ - ecs_ftime_t time_scale; /**< Time scale applied to delta_time */ - ecs_ftime_t target_fps; /**< Target fps */ - ecs_ftime_t frame_time_total; /**< Total time spent processing a frame */ - ecs_ftime_t system_time_total; /**< Total time spent in systems */ - ecs_ftime_t emit_time_total; /**< Total time spent notifying observers */ - ecs_ftime_t merge_time_total; /**< Total time spent in merges */ - ecs_ftime_t rematch_time_total; /**< Time spent on query rematching */ - double world_time_total; /**< Time elapsed in simulation */ - double world_time_total_raw; /**< Time elapsed in simulation (no scaling) */ - - int64_t frame_count_total; /**< Total number of frames */ - int64_t merge_count_total; /**< Total number of merges */ - int64_t eval_comp_monitors_total; /**< Total number of monitor evaluations */ - int64_t rematch_count_total; /**< Total number of rematches */ - - int64_t id_create_total; /**< Total number of times a new id was created */ - int64_t id_delete_total; /**< Total number of times an id was deleted */ - int64_t table_create_total; /**< Total number of times a table was created */ - int64_t table_delete_total; /**< Total number of times a table was deleted */ - int64_t pipeline_build_count_total; /**< Total number of pipeline builds */ - int64_t systems_ran_total; /**< Total number of systems ran */ - int64_t observers_ran_total; /**< Total number of times observer was invoked */ - int64_t queries_ran_total; /**< Total number of times a query was evaluated */ - - int32_t tag_id_count; /**< Number of tag (no data) ids in the world */ - int32_t component_id_count; /**< Number of component (data) ids in the world */ - int32_t pair_id_count; /**< Number of pair ids in the world */ - - int32_t table_count; /**< Number of tables */ - - uint32_t creation_time; /**< Time when world was created */ + ecs_entity_t last_component_id; /**< Last issued component entity ID. */ + ecs_entity_t min_id; /**< First allowed entity ID. */ + ecs_entity_t max_id; /**< Last allowed entity ID. */ + + ecs_ftime_t delta_time_raw; /**< Raw delta time (no time scaling). */ + ecs_ftime_t delta_time; /**< Time passed to or computed by ecs_progress(). */ + ecs_ftime_t time_scale; /**< Time scale applied to delta_time. */ + ecs_ftime_t target_fps; /**< Target FPS. */ + ecs_ftime_t frame_time_total; /**< Total time spent processing a frame. */ + ecs_ftime_t system_time_total; /**< Total time spent in systems. */ + ecs_ftime_t emit_time_total; /**< Total time spent notifying observers. */ + ecs_ftime_t merge_time_total; /**< Total time spent in merges. */ + ecs_ftime_t rematch_time_total; /**< Time spent on query rematching. */ + double world_time_total; /**< Time elapsed in simulation. */ + double world_time_total_raw; /**< Time elapsed in simulation (no scaling). */ + + int64_t frame_count_total; /**< Total number of frames. */ + int64_t merge_count_total; /**< Total number of merges. */ + int64_t eval_comp_monitors_total; /**< Total number of monitor evaluations. */ + int64_t rematch_count_total; /**< Total number of rematches. */ + + int64_t id_create_total; /**< Total number of times a new ID was created. */ + int64_t id_delete_total; /**< Total number of times an ID was deleted. */ + int64_t table_create_total; /**< Total number of times a table was created. */ + int64_t table_delete_total; /**< Total number of times a table was deleted. */ + int64_t pipeline_build_count_total; /**< Total number of pipeline builds. */ + int64_t systems_ran_total; /**< Total number of systems run. */ + int64_t observers_ran_total; /**< Total number of times an observer was invoked. */ + int64_t queries_ran_total; /**< Total number of times a query was evaluated. */ + + int32_t tag_id_count; /**< Number of tag (no data) IDs in the world. */ + int32_t component_id_count; /**< Number of component (data) IDs in the world. */ + int32_t pair_id_count; /**< Number of pair IDs in the world. */ + + int32_t table_count; /**< Number of tables. */ + + uint32_t creation_time; /**< Time when world was created. */ /* -- Command counts -- */ struct { - int64_t add_count; /**< Add commands processed */ - int64_t remove_count; /**< Remove commands processed */ - int64_t delete_count; /**< Delete commands processed */ - int64_t clear_count; /**< Clear commands processed */ - int64_t set_count; /**< Set commands processed */ - int64_t ensure_count; /**< Ensure/emplace commands processed */ - int64_t modified_count; /**< Modified commands processed */ - int64_t discard_count; /**< Commands discarded, happens when entity is no longer alive when running the command */ - int64_t event_count; /**< Enqueued custom events */ - int64_t other_count; /**< Other commands processed */ - int64_t batched_entity_count; /**< Entities for which commands were batched */ - int64_t batched_command_count; /**< Commands batched */ + int64_t add_count; /**< Add commands processed. */ + int64_t remove_count; /**< Remove commands processed. */ + int64_t delete_count; /**< Delete commands processed. */ + int64_t clear_count; /**< Clear commands processed. */ + int64_t set_count; /**< Set commands processed. */ + int64_t ensure_count; /**< Ensure or emplace commands processed. */ + int64_t modified_count; /**< Modified commands processed. */ + int64_t discard_count; /**< Commands discarded, happens when the entity is no longer alive when running the command. */ + int64_t event_count; /**< Enqueued custom events. */ + int64_t other_count; /**< Other commands processed. */ + int64_t batched_entity_count; /**< Entities for which commands were batched. */ + int64_t batched_command_count; /**< Commands batched. */ } cmd; /**< Command statistics. */ const char *name_prefix; /**< Value set by ecs_set_name_prefix(). Used @@ -5272,50 +6508,79 @@ typedef struct ecs_world_info_t { /** Type that contains information about a query group. */ typedef struct ecs_query_group_info_t { - uint64_t id; - int32_t match_count; /**< How often tables have been matched/unmatched */ - int32_t table_count; /**< Number of tables in group */ - void *ctx; /**< Group context, returned by on_group_create */ + uint64_t id; /**< Group ID. */ + int32_t match_count; /**< How often tables have been matched or unmatched. */ + int32_t table_count; /**< Number of tables in group. */ + void *ctx; /**< Group context, returned by on_group_create. */ } ecs_query_group_info_t; /** @} */ /** - * @defgroup builtin_components Builtin component types. - * Types that represent builtin components. + * @defgroup builtin_components Built-in component types. + * Types that represent built-in components. * * @{ */ -/** A (string) identifier. Used as pair with #EcsName and #EcsSymbol tags */ +/** A (string) identifier. Used as a pair with #EcsName and #EcsSymbol tags. */ typedef struct EcsIdentifier { - char *value; /**< Identifier string */ - ecs_size_t length; /**< Length of identifier */ - uint64_t hash; /**< Hash of current value */ - uint64_t index_hash; /**< Hash of existing record in current index */ - ecs_hashmap_t *index; /**< Current index */ + char *value; /**< Identifier string. */ + ecs_size_t length; /**< Length of identifier. */ + uint64_t hash; /**< Hash of current value. */ + uint64_t index_hash; /**< Hash of existing record in current index. */ + ecs_hashmap_t *index; /**< Current index. */ } EcsIdentifier; /** Component information. */ typedef struct EcsComponent { - ecs_size_t size; /**< Component size */ - ecs_size_t alignment; /**< Component alignment */ + ecs_size_t size; /**< Component size. */ + ecs_size_t alignment; /**< Component alignment. */ } EcsComponent; -/** Component for storing a poly object */ +/** Component for storing a poly object. */ typedef struct EcsPoly { - ecs_poly_t *poly; /**< Pointer to poly object */ + ecs_poly_t *poly; /**< Pointer to poly object. */ } EcsPoly; -/** When added to an entity this informs serialization formats which component +/** When added to an entity, this informs serialization formats which component * to use when a value is assigned to an entity without specifying the - * component. This is intended as a hint, serialization formats are not required + * component. This is intended as a hint; serialization formats are not required * to use it. Adding this component does not change the behavior of core ECS * operations. */ typedef struct EcsDefaultChildComponent { - ecs_id_t component; /**< Default component id. */ + ecs_id_t component; /**< Default component ID. */ } EcsDefaultChildComponent; +/** Non-fragmenting ChildOf relationship. */ +typedef struct EcsParent { + ecs_entity_t value; /**< Parent entity. */ +} EcsParent; + +/** Component with data to instantiate a non-fragmenting tree. */ +typedef struct { + const char *child_name; /**< Name of the prefab child. */ + ecs_table_t *table; /**< Table in which the child will be stored. */ + uint32_t child; /**< Prefab child entity (without generation). */ + int32_t parent_index; /**< Index into the children vector. */ +} ecs_tree_spawner_child_t; + +/** Tree spawner data for a single hierarchy depth. */ +typedef struct { + ecs_vec_t children; /**< vector. */ +} ecs_tree_spawner_t; + +/** Tree instantiation cache component. + * Tree instantiation cache, indexed by depth. Tables will have a + * (ParentDepth, depth) pair indicating the hierarchy depth. This means that + * for different depths, the tables the children are created in will also be + * different. Caching tables for different depths therefore speeds up + * instantiating trees even when the top-level entity is not at the root. + */ +typedef struct EcsTreeSpawner { + ecs_tree_spawner_t data[FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE]; /**< Cache data indexed by depth. */ +} EcsTreeSpawner; + /** @} */ /** @} */ @@ -5353,42 +6618,54 @@ extern "C" { */ /** - * @defgroup id_flags Component id flags. - * Id flags are bits that can be set on an id (ecs_id_t). + * @defgroup id_flags Component ID flags. + * ID flags are bits that can be set on an ID (ecs_id_t). * * @{ */ -/** Indicates that the id is a pair. */ +/** Indicate that the ID is a pair. */ FLECS_API extern const ecs_id_t ECS_PAIR; -/** Automatically override component when it is inherited */ +/** Automatically override component when it is inherited. */ FLECS_API extern const ecs_id_t ECS_AUTO_OVERRIDE; -/** Adds bitset to storage which allows component to be enabled/disabled */ +/** Add a bitset to storage, which allows a component to be enabled or disabled. */ FLECS_API extern const ecs_id_t ECS_TOGGLE; +/** Indicate that the target of a pair is an integer value. */ +FLECS_API extern const ecs_id_t ECS_VALUE_PAIR; + /** @} */ /** - * @defgroup builtin_tags Builtin component ids. + * @defgroup builtin_tags Built-in component IDs. * @{ */ -/* Builtin component ids */ +/* Built-in component IDs */ -/** Component component id. */ +/** Component component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsComponent); -/** Identifier component id. */ +/** Identifier component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsIdentifier); -/** Poly component id. */ +/** Poly component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsPoly); -/** DefaultChildComponent component id. */ +/** Parent component ID. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsParent); + +/** Component with data to instantiate a tree. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsTreeSpawner); + +/** DefaultChildComponent component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsDefaultChildComponent); +/** Relationship storing the entity's depth in a non-fragmenting hierarchy. */ +FLECS_API extern const ecs_entity_t EcsParentDepth; + /** Tag added to queries. */ FLECS_API extern const ecs_entity_t EcsQuery; @@ -5398,40 +6675,40 @@ FLECS_API extern const ecs_entity_t EcsObserver; /** Tag added to systems. */ FLECS_API extern const ecs_entity_t EcsSystem; -/** TickSource component id. */ +/** TickSource component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsTickSource); -/** Pipeline module component ids */ +/** Pipeline module component IDs. */ FLECS_API extern const ecs_entity_t ecs_id(EcsPipelineQuery); -/** Timer component id. */ +/** Timer component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsTimer); -/** RateFilter component id. */ +/** RateFilter component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsRateFilter); -/** Root scope for builtin flecs entities */ +/** Root scope for built-in Flecs entities. */ FLECS_API extern const ecs_entity_t EcsFlecs; -/** Core module scope */ +/** Core module scope. */ FLECS_API extern const ecs_entity_t EcsFlecsCore; -/** Entity associated with world (used for "attaching" components to world) */ +/** Entity associated with world (used for "attaching" components to world). */ FLECS_API extern const ecs_entity_t EcsWorld; -/** Wildcard entity ("*"). Matches any id, returns all matches. */ +/** Wildcard entity ("*"). Matches any ID, returns all matches. */ FLECS_API extern const ecs_entity_t EcsWildcard; -/** Any entity ("_"). Matches any id, returns only the first. */ +/** Any entity ("_"). Matches any ID, returns only the first. */ FLECS_API extern const ecs_entity_t EcsAny; /** This entity. Default source for queries. */ FLECS_API extern const ecs_entity_t EcsThis; -/** Variable entity ("$"). Used in expressions to prefix variable names */ +/** Variable entity ("$"). Used in expressions to prefix variable names. */ FLECS_API extern const ecs_entity_t EcsVariable; -/** Marks a relationship as transitive. +/** Mark a relationship as transitive. * Behavior: * * @code @@ -5440,7 +6717,7 @@ FLECS_API extern const ecs_entity_t EcsVariable; */ FLECS_API extern const ecs_entity_t EcsTransitive; -/** Marks a relationship as reflexive. +/** Mark a relationship as reflexive. * Behavior: * * @code @@ -5449,7 +6726,7 @@ FLECS_API extern const ecs_entity_t EcsTransitive; */ FLECS_API extern const ecs_entity_t EcsReflexive; -/** Ensures that entity/component cannot be used as target in `IsA` relationship. +/** Ensure that an entity or component cannot be used as a target in an `IsA` relationship. * Final can improve the performance of queries as they will not attempt to * substitute a final component with its subsets. * @@ -5464,7 +6741,7 @@ FLECS_API extern const ecs_entity_t EcsFinal; /** Mark component as inheritable. * This is the opposite of Final. This trait can be used to enforce that queries * take into account component inheritance before inheritance (IsA) - * relationships are added with the component as target. + * relationships are added with the component as the target. */ FLECS_API extern const ecs_entity_t EcsInheritable; @@ -5487,7 +6764,7 @@ FLECS_API extern const ecs_entity_t EcsInherit; * from the base entity. */ FLECS_API extern const ecs_entity_t EcsDontInherit; -/** Marks relationship as commutative. +/** Mark relationship as commutative. * Behavior: * * @code @@ -5496,8 +6773,8 @@ FLECS_API extern const ecs_entity_t EcsDontInherit; */ FLECS_API extern const ecs_entity_t EcsSymmetric; -/** Can be added to relationship to indicate that the relationship can only occur - * once on an entity. Adding a 2nd instance will replace the 1st. +/** Can be added to a relationship to indicate that the relationship can only occur + * once on an entity. Adding a second instance will replace the first. * * Behavior: * @@ -5507,14 +6784,14 @@ FLECS_API extern const ecs_entity_t EcsSymmetric; */ FLECS_API extern const ecs_entity_t EcsExclusive; -/** Marks a relationship as acyclic. Acyclic relationships may not form cycles. */ +/** Mark a relationship as acyclic. Acyclic relationships may not form cycles. */ FLECS_API extern const ecs_entity_t EcsAcyclic; -/** Marks a relationship as traversable. Traversable relationships may be +/** Mark a relationship as traversable. Traversable relationships may be * traversed with "up" queries. Traversable relationships are acyclic. */ FLECS_API extern const ecs_entity_t EcsTraversable; -/** Ensure that a component always is added together with another component. +/** Ensure that a component is always added together with another component. * * Behavior: * @@ -5525,7 +6802,7 @@ FLECS_API extern const ecs_entity_t EcsTraversable; */ FLECS_API extern const ecs_entity_t EcsWith; -/** Ensure that relationship target is child of specified entity. +/** Ensure that a relationship target is a child of the specified entity. * * Behavior: * @@ -5544,7 +6821,7 @@ FLECS_API extern const ecs_entity_t EcsCanToggle; */ FLECS_API extern const ecs_entity_t EcsTrait; -/** Ensure that an entity is always used in pair as relationship. +/** Ensure that an entity is always used in a pair as a relationship. * * Behavior: * @@ -5555,7 +6832,7 @@ FLECS_API extern const ecs_entity_t EcsTrait; */ FLECS_API extern const ecs_entity_t EcsRelationship; -/** Ensure that an entity is always used in pair as target. +/** Ensure that an entity is always used in a pair as a target. * * Behavior: * @@ -5566,17 +6843,17 @@ FLECS_API extern const ecs_entity_t EcsRelationship; */ FLECS_API extern const ecs_entity_t EcsTarget; -/** Can be added to relationship to indicate that it should never hold data, +/** Can be added to a relationship to indicate that it should never hold data, * even when it or the relationship target is a component. */ FLECS_API extern const ecs_entity_t EcsPairIsTag; -/** Tag to indicate name identifier */ +/** Tag to indicate name identifier. */ FLECS_API extern const ecs_entity_t EcsName; -/** Tag to indicate symbol identifier */ +/** Tag to indicate symbol identifier. */ FLECS_API extern const ecs_entity_t EcsSymbol; -/** Tag to indicate alias identifier */ +/** Tag to indicate alias identifier. */ FLECS_API extern const ecs_entity_t EcsAlias; /** Used to express parent-child relationships. */ @@ -5585,26 +6862,23 @@ FLECS_API extern const ecs_entity_t EcsChildOf; /** Used to express inheritance relationships. */ FLECS_API extern const ecs_entity_t EcsIsA; -/** Used to express dependency relationships */ +/** Used to express dependency relationships. */ FLECS_API extern const ecs_entity_t EcsDependsOn; -/** Used to express a slot (used with prefab inheritance) */ +/** Used to express a slot (used with prefab inheritance). */ FLECS_API extern const ecs_entity_t EcsSlotOf; -/** Tag that when added to a parent ensures stable order of ecs_children result. */ +/** Tag that, when added to a parent, ensures stable order of ecs_children() results. */ FLECS_API extern const ecs_entity_t EcsOrderedChildren; -/** Tag added to module entities */ +/** Tag added to module entities. */ FLECS_API extern const ecs_entity_t EcsModule; -/** Tag to indicate an entity/component/system is private to a module */ -FLECS_API extern const ecs_entity_t EcsPrivate; - /** Tag added to prefab entities. Any entity with this tag is automatically * ignored by queries, unless #EcsPrefab is explicitly queried for. */ FLECS_API extern const ecs_entity_t EcsPrefab; -/** When this tag is added to an entity it is skipped by queries, unless +/** When this tag is added to an entity, it is skipped by queries, unless * #EcsDisabled is explicitly queried for. */ FLECS_API extern const ecs_entity_t EcsDisabled; @@ -5613,16 +6887,16 @@ FLECS_API extern const ecs_entity_t EcsDisabled; * #EcsThis, #EcsWildcard, #EcsAny. */ FLECS_API extern const ecs_entity_t EcsNotQueryable; -/** Event that triggers when an id is added to an entity */ +/** Event that triggers when an ID is added to an entity. */ FLECS_API extern const ecs_entity_t EcsOnAdd; -/** Event that triggers when an id is removed from an entity */ +/** Event that triggers when an ID is removed from an entity. */ FLECS_API extern const ecs_entity_t EcsOnRemove; -/** Event that triggers when a component is set for an entity */ +/** Event that triggers when a component is set for an entity. */ FLECS_API extern const ecs_entity_t EcsOnSet; -/** Event that triggers observer when an entity starts/stops matching a query */ +/** Event that triggers an observer when an entity starts or stops matching a query. */ FLECS_API extern const ecs_entity_t EcsMonitor; /** Event that triggers when a table is created. */ @@ -5638,15 +6912,15 @@ FLECS_API extern const ecs_entity_t EcsOnDelete; * element of a pair) is deleted. */ FLECS_API extern const ecs_entity_t EcsOnDeleteTarget; -/** Remove cleanup policy. Must be used as target in pair with #EcsOnDelete or +/** Remove cleanup policy. Must be used as a target in a pair with #EcsOnDelete or * #EcsOnDeleteTarget. */ FLECS_API extern const ecs_entity_t EcsRemove; -/** Delete cleanup policy. Must be used as target in pair with #EcsOnDelete or +/** Delete cleanup policy. Must be used as a target in a pair with #EcsOnDelete or * #EcsOnDeleteTarget. */ FLECS_API extern const ecs_entity_t EcsDelete; -/** Panic cleanup policy. Must be used as target in pair with #EcsOnDelete or +/** Panic cleanup policy. Must be used as a target in a pair with #EcsOnDelete or * #EcsOnDeleteTarget. */ FLECS_API extern const ecs_entity_t EcsPanic; @@ -5654,10 +6928,10 @@ FLECS_API extern const ecs_entity_t EcsPanic; * themselves. */ FLECS_API extern const ecs_entity_t EcsSingleton; -/** Mark component as sparse */ +/** Mark component as sparse. */ FLECS_API extern const ecs_entity_t EcsSparse; -/** Mark component as non-fragmenting */ +/** Mark component as non-fragmenting. */ FLECS_API extern const ecs_entity_t EcsDontFragment; /** Marker used to indicate `$var == ...` matching in queries. */ @@ -5675,13 +6949,13 @@ FLECS_API extern const ecs_entity_t EcsScopeOpen; /** Marker used to indicate the end of a scope (`}`) in queries. */ FLECS_API extern const ecs_entity_t EcsScopeClose; -/** Tag used to indicate query is empty. +/** Tag used to indicate a query is empty. * This tag is removed automatically when a query becomes non-empty, and is not * automatically re-added when it becomes empty. */ FLECS_API extern const ecs_entity_t EcsEmpty; -FLECS_API extern const ecs_entity_t ecs_id(EcsPipeline); /**< Pipeline component id. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsPipeline); /**< Pipeline component ID. */ FLECS_API extern const ecs_entity_t EcsOnStart; /**< OnStart pipeline phase. */ FLECS_API extern const ecs_entity_t EcsPreFrame; /**< PreFrame pipeline phase. */ FLECS_API extern const ecs_entity_t EcsOnLoad; /**< OnLoad pipeline phase. */ @@ -5695,24 +6969,24 @@ FLECS_API extern const ecs_entity_t EcsOnStore; /**< OnStore pipeline phase. FLECS_API extern const ecs_entity_t EcsPostFrame; /**< PostFrame pipeline phase. */ FLECS_API extern const ecs_entity_t EcsPhase; /**< Phase pipeline phase. */ -FLECS_API extern const ecs_entity_t EcsConstant; /**< Tag added to enum/bitmask constants. */ +FLECS_API extern const ecs_entity_t EcsConstant; /**< Tag added to enum or bitmask constants. */ -/** Value used to quickly check if component is builtin. This is used to quickly - * filter out tables with builtin components (for example for ecs_delete()) */ -#define EcsLastInternalComponentId (ecs_id(EcsPoly)) +/** Value used to quickly check if a component is built-in. This is used to + * filter out tables with built-in components (for example, for ecs_delete()). */ +#define EcsLastInternalComponentId (ecs_id(EcsTreeSpawner)) -/** The first user-defined component starts from this id. Ids up to this number - * are reserved for builtin components */ +/** The first user-defined component starts from this ID. IDs up to this number + * are reserved for built-in components. */ #define EcsFirstUserComponentId (8) -/** The first user-defined entity starts from this id. Ids up to this number - * are reserved for builtin entities */ +/** The first user-defined entity starts from this ID. IDs up to this number + * are reserved for built-in entities. */ #define EcsFirstUserEntityId (FLECS_HI_COMPONENT_ID + 128) -/* When visualized the reserved id ranges look like this: - * - [1..8]: Builtin components - * - [9..FLECS_HI_COMPONENT_ID]: Low ids reserved for application components - * - [FLECS_HI_COMPONENT_ID + 1..EcsFirstUserEntityId]: Builtin entities +/* When visualized, the reserved ID ranges look like this: + * - [1..8]: Built-in components + * - [9..FLECS_HI_COMPONENT_ID]: Low IDs reserved for application components + * - [FLECS_HI_COMPONENT_ID + 1..EcsFirstUserEntityId]: Built-in entities */ /** @} */ @@ -5734,7 +7008,7 @@ FLECS_API extern const ecs_entity_t EcsConstant; /**< Tag added to enum/bitma * This operation automatically imports modules from addons Flecs has been built * with, except when the module specifies otherwise. * - * @return A new world + * @return A new world. */ FLECS_API ecs_world_t* ecs_init(void); @@ -5743,17 +7017,19 @@ ecs_world_t* ecs_init(void); * Same as ecs_init(), but doesn't import modules from addons. This operation is * faster than ecs_init() and results in less memory utilization. * - * @return A new tiny world + * @return A new tiny world. */ FLECS_API ecs_world_t* ecs_mini(void); /** Create a new world with arguments. - * Same as ecs_init(), but allows passing in command line arguments. Command line + * Same as ecs_init(), but allows passing in command-line arguments. Command-line * arguments are used to: * - automatically derive the name of the application from argv[0] * - * @return A new world + * @param argc The number of arguments. + * @param argv The argument array. + * @return A new world. */ FLECS_API ecs_world_t* ecs_init_w_args( @@ -5770,7 +7046,7 @@ FLECS_API int ecs_fini( ecs_world_t *world); -/** Returns whether the world is being deleted. +/** Return whether the world is being deleted. * This operation can be used in callbacks like type hooks or observers to * detect if they are invoked while the world is being deleted. * @@ -5781,13 +7057,14 @@ FLECS_API bool ecs_is_fini( const ecs_world_t *world); -/** Register action to be executed when world is destroyed. - * Fini actions are typically used when a module needs to clean up before a +/** Register an action to be executed when the world is destroyed. + * Fini actions are typically used when a module needs to clean up before the * world shuts down. * * @param world The world. * @param action The function to execute. - * @param ctx Userdata to pass to the function */ + * @param ctx Userdata to pass to the function. + */ FLECS_API void ecs_atfini( ecs_world_t *world, @@ -5796,17 +7073,17 @@ void ecs_atfini( /** Type returned by ecs_get_entities(). */ typedef struct ecs_entities_t { - const ecs_entity_t *ids; /**< Array with all entity ids in the world. */ - int32_t count; /**< Total number of entity ids. */ - int32_t alive_count; /**< Number of alive entity ids. */ + const ecs_entity_t *ids; /**< Array with all entity IDs in the world. */ + int32_t count; /**< Total number of entity IDs. */ + int32_t alive_count; /**< Number of alive entity IDs. */ } ecs_entities_t; -/** Return entity identifiers in world. - * This operation returns an array with all entity ids that exist in the world. +/** Return entity identifiers in the world. + * This operation returns an array with all entity IDs that exist in the world. * Note that the returned array will change and may get invalidated as a result - * of entity creation & deletion. + * of entity creation and deletion. * - * To iterate all alive entity ids, do: + * To iterate all alive entity IDs, do: * @code * ecs_entities_t entities = ecs_get_entities(world); * for (int i = 0; i < entities.alive_count; i ++) { @@ -5814,7 +7091,7 @@ typedef struct ecs_entities_t { * } * @endcode * - * To iterate not-alive ids, do: + * To iterate not-alive IDs, do: * @code * for (int i = entities.alive_count + 1; i < entities.count; i ++) { * ecs_entity_t id = entities.ids[i]; @@ -5822,10 +7099,10 @@ typedef struct ecs_entities_t { * @endcode * * The returned array does not need to be freed. Mutating the returned array - * will return in undefined behavior (and likely crashes). + * will result in undefined behavior (and likely crashes). * * @param world The world. - * @return Struct with entity id array. + * @return Struct with entity ID array. */ FLECS_API ecs_entities_t ecs_get_entities( @@ -5861,7 +7138,7 @@ ecs_flags32_t ecs_world_get_flags( * needs to sleep to ensure it does not exceed the target_fps, when it is set. * When 0 is provided for delta_time, the time will be measured. * - * This function should only be ran from the main thread. + * This function should only be run from the main thread. * * @param world The world. * @param delta_time Time elapsed since the last frame. @@ -5882,20 +7159,21 @@ FLECS_API void ecs_frame_end( ecs_world_t *world); -/** Register action to be executed once after frame. +/** Register an action to be executed once after the frame. * Post frame actions are typically used for calling operations that cannot be * invoked during iteration, such as changing the number of threads. * * @param world The world. * @param action The function to execute. - * @param ctx Userdata to pass to the function */ + * @param ctx Userdata to pass to the function. + */ FLECS_API void ecs_run_post_frame( ecs_world_t *world, ecs_fini_action_t action, void *ctx); -/** Signal exit +/** Signal exit. * This operation signals that the application should quit. It will cause * ecs_progress() to return false. * @@ -5944,16 +7222,16 @@ FLECS_API void ecs_measure_system_time( ecs_world_t *world, bool enable); -/** Set target frames per second (FPS) for application. +/** Set target frames per second (FPS) for an application. * Setting the target FPS ensures that ecs_progress() is not invoked faster than * the specified FPS. When enabled, ecs_progress() tracks the time passed since * the last invocation, and sleeps the remaining time of the frame (if any). * - * This feature ensures systems are ran at a consistent interval, as well as + * This feature ensures systems are run at a consistent interval, as well as * conserving CPU time by not running systems more often than required. * * Note that ecs_progress() only sleeps if there is time left in the frame. Both - * time spent in flecs as time spent outside of flecs are taken into + * time spent in Flecs and time spent outside of Flecs are taken into * account. * * @param world The world. @@ -5964,8 +7242,8 @@ void ecs_set_target_fps( ecs_world_t *world, ecs_ftime_t fps); -/** Set default query flags. - * Set a default value for the ecs_filter_desc_t::flags field. Default flags +/** Set the default query flags. + * Set a default value for the ecs_query_desc_t::flags field. Default flags * are applied in addition to the flags provided in the descriptor. For a * list of available flags, see include/flecs/private/api_flags.h. Typical flags * to use are: @@ -5992,28 +7270,28 @@ void ecs_set_default_query_flags( /** Begin readonly mode. * This operation puts the world in readonly mode, which disallows mutations on * the world. Readonly mode exists so that internal mechanisms can implement - * optimizations that certain aspects of the world to not change, while also + * optimizations that assume certain aspects of the world do not change, while also * providing a mechanism for applications to prevent accidental mutations in, * for example, multithreaded applications. * - * Readonly mode is a stronger version of deferred mode. In deferred mode - * ECS operations such as add/remove/set/delete etc. are added to a command + * Readonly mode is a stronger version of deferred mode. In deferred mode, + * ECS operations such as add, remove, set, delete, etc. are added to a command * queue to be executed later. In readonly mode, operations that could break * scheduler logic (such as creating systems, queries) are also disallowed. * - * Readonly mode itself has a single threaded and a multi threaded mode. In - * single threaded mode certain mutations on the world are still allowed, for + * Readonly mode itself has a single-threaded and a multithreaded mode. In + * single-threaded mode, certain mutations on the world are still allowed, for * example: - * - Entity liveliness operations (such as new, make_alive), so that systems are + * - Entity liveliness operations (such as ecs_new(), ecs_make_alive()), so that systems are * able to create new entities. - * - Implicit component registration, so that this works from systems - * - Mutations to supporting data structures for the evaluation of uncached - * queries (filters), so that these can be created on the fly. + * - Implicit component registration, so that it works from systems. + * - Mutations to supporting data structures for the evaluation of uncached + * queries, so that these can be created on the fly. * - * These mutations are safe in a single threaded applications, but for + * These mutations are safe in single-threaded applications, but for * multithreaded applications the world needs to be entirely immutable. For this - * purpose multi threaded readonly mode exists, which disallows all mutations on - * the world. This means that in multi threaded applications, entity liveliness + * purpose, multithreaded readonly mode exists, which disallows all mutations on + * the world. This means that in multithreaded applications, entity liveliness * operations, implicit component registration, and on-the-fly query creation * are not guaranteed to work. * @@ -6024,9 +7302,9 @@ void ecs_set_default_query_flags( * @code * // Number of stages typically corresponds with number of threads * ecs_set_stage_count(world, 2); - * ecs_stage_t *stage = ecs_get_stage(world, 1); + * ecs_world_t *stage = ecs_get_stage(world, 1); * - * ecs_readonly_begin(world); + * ecs_readonly_begin(world, false); * ecs_add(world, e, Tag); // readonly assert * ecs_add(stage, e, Tag); // OK * @endcode @@ -6038,7 +7316,7 @@ void ecs_set_default_query_flags( * When ecs_readonly_end() is called, all enqueued commands from configured * stages are merged back into the world. Calls to ecs_readonly_begin() and * ecs_readonly_end() should always happen from a context where the code has - * exclusive access to the world. The functions themselves are not thread safe. + * exclusive access to the world. The functions themselves are not thread-safe. * * In a typical application, a (non-exhaustive) call stack that uses * ecs_readonly_begin() and ecs_readonly_end() will look like this: @@ -6052,10 +7330,10 @@ void ecs_set_default_query_flags( * * ecs_readonly_end() * ecs_defer_end() - *@endcode + * @endcode * - * @param world The world - * @param multi_threaded Whether to enable readonly/multi threaded mode. + * @param world The world. + * @param multi_threaded Whether to enable multithreaded readonly mode. * @return Whether world is in readonly mode. */ FLECS_API @@ -6068,13 +7346,13 @@ bool ecs_readonly_begin( * ecs_readonly_begin(). Operations that were deferred while the world was in * readonly mode will be flushed. * - * @param world The world + * @param world The world. */ FLECS_API void ecs_readonly_end( ecs_world_t *world); -/** Merge stage. +/** Merge a stage. * This will merge all commands enqueued for a stage. * * @param stage The stage. @@ -6083,12 +7361,12 @@ FLECS_API void ecs_merge( ecs_world_t *stage); -/** Defer operations until end of frame. - * When this operation is invoked while iterating, operations inbetween the +/** Defer operations until the end of the frame. + * When this operation is invoked while iterating, operations between the * ecs_defer_begin() and ecs_defer_end() operations are executed at the end * of the frame. * - * This operation is thread safe. + * This operation is thread-safe. * * @param world The world. * @return true if world changed from non-deferred mode to deferred mode. @@ -6103,16 +7381,16 @@ FLECS_API bool ecs_defer_begin( ecs_world_t *world); -/** End block of operations to defer. +/** End a block of operations to defer. * See ecs_defer_begin(). * - * This operation is thread safe. + * This operation is thread-safe. * * @param world The world. * @return true if world changed from deferred mode to non-deferred mode. * * @see ecs_defer_begin() - * @see ecs_defer_is_deferred() + * @see ecs_is_deferred() * @see ecs_defer_resume() * @see ecs_defer_suspend() */ @@ -6131,7 +7409,7 @@ bool ecs_defer_end( * * @see ecs_defer_begin() * @see ecs_defer_end() - * @see ecs_defer_is_deferred() + * @see ecs_is_deferred() * @see ecs_defer_resume() */ FLECS_API @@ -6145,14 +7423,14 @@ void ecs_defer_suspend( * * @see ecs_defer_begin() * @see ecs_defer_end() - * @see ecs_defer_is_deferred() + * @see ecs_is_deferred() * @see ecs_defer_suspend() */ FLECS_API void ecs_defer_resume( ecs_world_t *world); -/** Test if deferring is enabled for current stage. +/** Test if deferring is enabled for the current stage. * * @param world The world. * @return True if deferred, false if not. @@ -6167,7 +7445,7 @@ FLECS_API bool ecs_is_deferred( const ecs_world_t *world); -/** Test if deferring is suspended for current stage. +/** Test if deferring is suspended for the current stage. * * @param world The world. * @return True if suspended, false if not. @@ -6182,7 +7460,7 @@ FLECS_API bool ecs_is_defer_suspended( const ecs_world_t *world); -/** Configure world to have N stages. +/** Configure the world to have N stages. * This initializes N stages, which allows applications to defer operations to * multiple isolated defer queues. This is typically used for applications with * multiple threads, where each thread gets its own queue, and commands are @@ -6200,8 +7478,8 @@ void ecs_set_stage_count( ecs_world_t *world, int32_t stages); -/** Get number of configured stages. - * Return number of stages set by ecs_set_stage_count(). +/** Get the number of configured stages. + * Return the number of stages set by ecs_set_stage_count(). * * @param world The world. * @return The number of stages used for threading. @@ -6215,10 +7493,10 @@ int32_t ecs_get_stage_count( * context to write to, also referred to as the stage. This function returns a * pointer to a stage, disguised as a world pointer. * - * Note that this function does not(!) create a new world. It simply wraps the + * Note that this function does not create a new world. It simply wraps the * existing world in a thread-specific context, which the API knows how to * unwrap. The reason the stage is returned as an ecs_world_t is so that it - * can be passed transparently to the existing API functions, vs. having to + * can be passed transparently to the existing API functions, instead of having to * create a dedicated API for threading. * * @param world The world. @@ -6241,7 +7519,7 @@ FLECS_API bool ecs_stage_is_readonly( const ecs_world_t *world); -/** Create unmanaged stage. +/** Create an unmanaged stage. * Create a stage whose lifecycle is not managed by the world. Must be freed * with ecs_stage_free(). * @@ -6252,7 +7530,7 @@ FLECS_API ecs_world_t* ecs_stage_new( ecs_world_t *world); -/** Free unmanaged stage. +/** Free an unmanaged stage. * * @param stage The stage to free. */ @@ -6260,12 +7538,12 @@ FLECS_API void ecs_stage_free( ecs_world_t *stage); -/** Get stage id. - * The stage id can be used by an application to learn about which stage it is - * using, which typically corresponds with the worker thread id. +/** Get the stage ID. + * The stage ID can be used by an application to learn about which stage it is + * using, which typically corresponds with the worker thread ID. * * @param world The world. - * @return The stage id. + * @return The stage ID. */ FLECS_API int32_t ecs_stage_get_id( @@ -6283,7 +7561,7 @@ int32_t ecs_stage_get_id( * that can be accessed anywhere where the application has the world. * * @param world The world. - * @param ctx A pointer to a user defined structure. + * @param ctx A pointer to a user-defined structure. * @param ctx_free A function that is invoked with ctx when the world is freed. */ FLECS_API @@ -6293,11 +7571,11 @@ void ecs_set_ctx( ecs_ctx_free_t ctx_free); /** Set a world binding context. - * Same as ecs_set_ctx() but for binding context. A binding context is intended - * specifically for language bindings to store binding specific data. + * Same as ecs_set_ctx(), but for binding context. A binding context is intended + * specifically for language bindings to store binding-specific data. * * @param world The world. - * @param ctx A pointer to a user defined structure. + * @param ctx A pointer to a user-defined structure. * @param ctx_free A function that is invoked with ctx when the world is freed. */ FLECS_API @@ -6329,17 +7607,17 @@ void* ecs_get_binding_ctx( const ecs_world_t *world); /** Get build info. - * Returns information about the current Flecs build. + * Return information about the current Flecs build. * * @return A struct with information about the current Flecs build. */ FLECS_API const ecs_build_info_t* ecs_get_build_info(void); -/** Get world info. +/** Get the world info. * * @param world The world. - * @return Pointer to the world info. Valid for as long as the world exists. + * @return A pointer to the world info. Valid for as long as the world exists. */ FLECS_API const ecs_world_info_t* ecs_get_world_info( @@ -6376,7 +7654,7 @@ FLECS_API void ecs_shrink( ecs_world_t *world); -/** Set a range for issuing new entity ids. +/** Set a range for issuing new entity IDs. * This function constrains the entity identifiers returned by ecs_new_w() to the * specified range. This operation can be used to ensure that multiple processes * can run in the same simulation without requiring a central service that @@ -6384,7 +7662,7 @@ void ecs_shrink( * * If `id_end` is set to 0, the range is infinite. If `id_end` is set to a non-zero * value, it has to be larger than `id_start`. If `id_end` is set and ecs_new() is - * invoked after an id is issued that is equal to `id_end`, the application will + * invoked after an ID is issued that is equal to `id_end`, the application will * abort. * * @param world The world. @@ -6397,11 +7675,11 @@ void ecs_set_entity_range( ecs_entity_t id_start, ecs_entity_t id_end); -/** Enable/disable range limits. +/** Enable or disable range limits. * When an application is both a receiver of range-limited entities and a * producer of range-limited entities, range checking needs to be temporarily * disabled when inserting received entities. Range checking is disabled on a - * stage, so setting this value is thread safe. + * stage, so setting this value is thread-safe. * * @param world The world. * @param enable True if range checking should be enabled, false to disable. @@ -6412,10 +7690,10 @@ bool ecs_enable_range_check( ecs_world_t *world, bool enable); -/** Get the largest issued entity id (not counting generation). +/** Get the largest issued entity ID (not counting generation). * * @param world The world. - * @return The largest issued entity id. + * @return The largest issued entity ID. */ FLECS_API ecs_entity_t ecs_get_max_id( @@ -6424,8 +7702,8 @@ ecs_entity_t ecs_get_max_id( /** Force aperiodic actions. * The world may delay certain operations until they are necessary for the * application to function correctly. This may cause observable side effects - * such as delayed triggering of events, which can be inconvenient when for - * example running a test suite. + * such as delayed triggering of events, which can be inconvenient when, for + * example, running a test suite. * * The flags parameter specifies which aperiodic actions to run. Specify 0 to * run all actions. Supported flags start with 'EcsAperiodic'. Flags identify @@ -6451,23 +7729,23 @@ typedef struct ecs_delete_empty_tables_desc_t { double time_budget_seconds; } ecs_delete_empty_tables_desc_t; -/** Cleanup empty tables. +/** Clean up empty tables. * This operation cleans up empty tables that meet certain conditions. Having * large amounts of empty tables does not negatively impact performance of the * ECS, but can take up considerable amounts of memory, especially in * applications with many components, and many components per entity. * * The generation specifies the minimum number of times this operation has - * to be called before an empty table is cleaned up. If a table becomes non - * empty, the generation is reset. + * to be called before an empty table is cleaned up. If a table becomes + * non-empty, the generation is reset. * * The operation allows for both a "clear" generation and a "delete" * generation. When the clear generation is reached, the table's * resources are freed (like component arrays) but the table itself is not * deleted. When the delete generation is reached, the empty table is deleted. * - * By specifying a non-zero id the cleanup logic can be limited to tables with - * a specific (component) id. The operation will only increase the generation + * By specifying a non-zero ID, the cleanup logic can be limited to tables with + * a specific (component) ID. The operation will only increase the generation * count of matching tables. * * The min_id_count specifies a lower bound for the number of components a table @@ -6478,14 +7756,14 @@ typedef struct ecs_delete_empty_tables_desc_t { * * @param world The world. * @param desc Configuration parameters. - * @return Number of deleted tables. + * @return The number of deleted tables. */ FLECS_API int32_t ecs_delete_empty_tables( ecs_world_t *world, const ecs_delete_empty_tables_desc_t *desc); -/** Get world from poly. +/** Get the world from a poly. * * @param poly A pointer to a poly object. * @return The world. @@ -6494,16 +7772,16 @@ FLECS_API const ecs_world_t* ecs_get_world( const ecs_poly_t *poly); -/** Get entity from poly. +/** Get the entity from a poly. * * @param poly A pointer to a poly object. - * @return Entity associated with the poly object. + * @return The entity associated with the poly object. */ FLECS_API ecs_entity_t ecs_get_entity( const ecs_poly_t *poly); -/** Test if pointer is of specified type. +/** Test if a pointer is of the specified type. * Usage: * * @code @@ -6513,7 +7791,7 @@ ecs_entity_t ecs_get_entity( * This operation only works for poly types. * * @param object The object to test. - * @param type The id of the type. + * @param type The ID of the type. * @return True if the pointer is of the specified type. */ FLECS_API @@ -6521,19 +7799,19 @@ bool flecs_poly_is_( const ecs_poly_t *object, int32_t type); -/** Test if pointer is of specified type. +/** Test if a pointer is of the specified type. * @see flecs_poly_is_() */ #define flecs_poly_is(object, type)\ flecs_poly_is_(object, type##_magic) -/** Make a pair id. +/** Make a pair ID. * This function is equivalent to using the ecs_pair() macro, and is added for - * convenience to make it easier for non C/C++ bindings to work with pairs. + * convenience to make it easier for non-C/C++ bindings to work with pairs. * - * @param first The first element of the pair of the pair. + * @param first The first element of the pair. * @param second The target of the pair. - * @return A pair id. + * @return A pair ID. */ FLECS_API ecs_id_t ecs_make_pair( @@ -6550,7 +7828,7 @@ ecs_id_t ecs_make_pair( * thread without first calling ecs_exclusive_access_end() will panic. * * A thread name can be provided to the function to improve debug messages. The - * function does not(!) copy the thread name, which means the memory for the + * function does not copy the thread name, which means the memory for the * name must remain alive for as long as the thread has exclusive access. * * This operation should only be called once per thread. Calling it multiple @@ -6560,7 +7838,7 @@ ecs_id_t ecs_make_pair( * feature requires the OS API thread_self_ callback to be set. * * @param world The world. - * @param thread_name Name of the thread obtaining exclusive access. + * @param thread_name The name of the thread obtaining exclusive access. */ FLECS_API void ecs_exclusive_access_begin( @@ -6569,17 +7847,17 @@ void ecs_exclusive_access_begin( /** End exclusive thread access. * This operation should be called after ecs_exclusive_access_begin(). After - * calling this operation other threads are no longer prevented from mutating + * calling this operation, other threads are no longer prevented from mutating * the world. * * When "lock_world" is set to true, no thread will be able to mutate the world - * until ecs_exclusive_access_begin is called again. While the world is locked - * only readonly operations are allowed. For example, ecs_get_id() is allowed, + * until ecs_exclusive_access_begin() is called again. While the world is locked, + * only read-only operations are allowed. For example, ecs_get_id() is allowed, * but ecs_get_mut_id() is not allowed. * - * A locked world can be unlocked by calling ecs_exclusive_access_end again with - * lock_world set to false. Note that this only works for locked worlds, if\ - * ecs_exclusive_access_end() is called on a world that has exclusive thread + * A locked world can be unlocked by calling ecs_exclusive_access_end() again with + * lock_world set to false. Note that this only works for locked worlds. If + * ecs_exclusive_access_end() is called on a world that has exclusive thread * access from a different thread, a panic will happen. * * This operation must be called from the same thread that called @@ -6612,21 +7890,21 @@ void ecs_exclusive_access_end( * @{ */ -/** Create new entity id. - * This operation returns an unused entity id. This operation is guaranteed to +/** Create new entity ID. + * This operation returns an unused entity ID. This operation is guaranteed to * return an empty entity as it does not use values set by ecs_set_scope() or * ecs_set_with(). * * @param world The world. - * @return The new entity id. + * @return The new entity ID. */ FLECS_API ecs_entity_t ecs_new( ecs_world_t *world); -/** Create new low id. - * This operation returns a new low id. Entity ids start after the - * FLECS_HI_COMPONENT_ID constant. This reserves a range of low ids for things +/** Create new low ID. + * This operation returns a new low ID. Entity IDs start after the + * FLECS_HI_COMPONENT_ID constant. This reserves a range of low IDs for things * like components, and allows parts of the code to optimize operations. * * Note that FLECS_HI_COMPONENT_ID does not represent the maximum number of @@ -6636,18 +7914,18 @@ ecs_entity_t ecs_new( * This operation is guaranteed to return an empty entity as it does not use * values set by ecs_set_scope() or ecs_set_with(). * - * This operation does not recycle ids. + * This operation does not recycle IDs. * * @param world The world. - * @return The new component id. + * @return The new component ID. */ FLECS_API ecs_entity_t ecs_new_low_id( ecs_world_t *world); -/** Create new entity with (component) id. - * This operation creates a new entity with an optional (component) id. When 0 - * is passed to the id parameter, no component is added to the new entity. +/** Create new entity with (component) ID. + * This operation creates a new entity with an optional (component) ID. When 0 + * is passed to the ID parameter, no component is added to the new entity. * * @param world The world. * @param component The component to create the new entity with. @@ -6680,7 +7958,7 @@ ecs_entity_t ecs_new_w_table( * the entity name matches with the provided name. If the names do not match, * the function will fail and return 0. * - * If an id to a non-existing entity is provided, that entity id become alive. + * If an ID to a non-existing entity is provided, that entity ID becomes alive. * * See the documentation of ecs_entity_desc_t for more details. * @@ -6693,7 +7971,7 @@ ecs_entity_t ecs_entity_init( ecs_world_t *world, const ecs_entity_desc_t *desc); -/** Bulk create/populate new entities. +/** Bulk create or populate new entities. * This operation bulk inserts a list of new or predefined entities into a * single table. * @@ -6701,15 +7979,15 @@ ecs_entity_t ecs_entity_init( * application. Components that are non-trivially copyable will be moved into * the storage. * - * The operation will emit OnAdd events for each added id, and OnSet events for + * The operation will emit OnAdd events for each added ID, and OnSet events for * each component that has been set. * - * If no entity ids are provided by the application, the returned array of ids - * points to an internal data structure which changes when new entities are - * created/deleted. + * If no entity IDs are provided by the application, the returned array of IDs + * points to an internal data structure, which changes when new entities are + * created or deleted. * - * If as a result of the operation triggers are invoked that deletes - * entities and no entity ids were provided by the application, the returned + * If as a result of the operation, observers are invoked that delete + * entities and no entity IDs were provided by the application, the returned * array of identifiers may be incorrect. To avoid this problem, an application * can first call ecs_bulk_init() to create empty entities, copy the array to one * that is owned by the application, and then use this array to populate the @@ -6717,7 +7995,7 @@ ecs_entity_t ecs_entity_init( * * @param world The world. * @param desc Bulk creation parameters. - * @return Array with the list of entity ids created/populated. + * @return An array with the list of entity IDs created or populated. */ FLECS_API const ecs_entity_t* ecs_bulk_init( @@ -6731,7 +8009,7 @@ const ecs_entity_t* ecs_bulk_init( * @param world The world. * @param component The component to create the entities with. * @param count The number of entities to create. - * @return The first entity id of the newly created entities. + * @return An array with the entity IDs of the newly created entities. */ FLECS_API const ecs_entity_t* ecs_bulk_new_w_id( @@ -6739,7 +8017,7 @@ const ecs_entity_t* ecs_bulk_new_w_id( ecs_id_t component, int32_t count); -/** Clone an entity +/** Clone an entity. * This operation clones the components of one entity into another entity. If * no destination entity is provided, a new entity will be created. Component * values are not copied unless copy_value is true. @@ -6762,7 +8040,7 @@ ecs_entity_t ecs_clone( bool copy_value); /** Delete an entity. - * This operation will delete an entity and all of its components. The entity id + * This operation will delete an entity and all of its components. The entity ID * will be made available for recycling. If the entity passed to ecs_delete() is * not alive, the operation will have no side effects. * @@ -6775,7 +8053,7 @@ void ecs_delete( ecs_entity_t entity); /** Delete all entities with the specified component. - * This will delete all entities (tables) that have the specified id. The + * This will delete all entities (tables) that have the specified ID. The * component may be a wildcard and/or a pair. * * @param world The world. @@ -6792,7 +8070,7 @@ void ecs_delete_with( * will fail if the parent does not have the OrderedChildren trait. * * This operation always takes place immediately, and is not deferred. When the - * operation is called from a multithreaded system it will fail. + * operation is called from a multithreaded system, it will fail. * * The reason for not deferring this operation is that by the time the deferred * command would be executed, the children of the parent could have been changed @@ -6813,7 +8091,7 @@ void ecs_set_child_order( /** Get ordered children. * If a parent has the OrderedChildren trait, this operation can be used to * obtain the array with child entities. If this operation is used on a parent - * that does not have the OrderedChildren trait, it will fail.asm + * that does not have the OrderedChildren trait, it will fail. * * @param world The world. * @param parent The parent. @@ -6833,13 +8111,13 @@ ecs_entities_t ecs_get_ordered_children( * @{ */ -/** Add a (component) id to an entity. - * This operation adds a single (component) id to an entity. If the entity - * already has the id, this operation will have no side effects. +/** Add a (component) ID to an entity. + * This operation adds a single (component) ID to an entity. If the entity + * already has the ID, this operation will have no side effects. * * @param world The world. * @param entity The entity. - * @param component The component id to add. + * @param component The component ID to add. */ FLECS_API void ecs_add_id( @@ -6861,7 +8139,7 @@ void ecs_remove_id( ecs_entity_t entity, ecs_id_t component); -/** Add auto override for component. +/** Add an auto override for a component. * An auto override is a component that is automatically added to an entity when * it is instantiated from a prefab. Auto overrides are added to the entity that * is inherited from (usually a prefab). For example: @@ -6892,7 +8170,7 @@ void ecs_remove_id( * assert(ecs_owns(world, inst, Mass)); // false * @endcode * - * This operation is equivalent to manually adding the id with the AUTO_OVERRIDE + * This operation is equivalent to manually adding the ID with the AUTO_OVERRIDE * bit applied: * * @code @@ -6905,7 +8183,7 @@ void ecs_remove_id( * * Overriding is the default behavior on prefab instantiation. Auto overriding * is only useful for components with the `(OnInstantiate, Inherit)` trait. - * When a component has the `(OnInstantiate, DontInherit)` trait and is overridden + * When a component has the `(OnInstantiate, DontInherit)` trait and is overridden, * the component is added, but the value from the prefab will not be copied. * * @param world The world. @@ -6930,7 +8208,7 @@ void ecs_clear( ecs_entity_t entity); /** Remove all instances of the specified component. - * This will remove the specified id from all entities (tables). The id may be + * This will remove the specified ID from all entities (tables). The ID may be * a wildcard and/or a pair. * * @param world The world. @@ -6941,9 +8219,10 @@ void ecs_remove_all( ecs_world_t *world, ecs_id_t component); -/** Create new entities with specified component. - * Entities created with ecs_entity_init() will be created with the specified - * component. This does not apply to entities created with ecs_new(). +/** Create new entities with a specified component. + * This operation configures a component that is automatically added to entities + * created with ecs_entity_init(). This does not apply to entities created with + * ecs_new(). * * Only one component can be specified at a time. If this operation is called * while a component is already configured, the new component will override the @@ -6953,15 +8232,16 @@ void ecs_remove_all( * @param component The component. * @return The previously set component. * @see ecs_entity_init() - * @see ecs_set_with() + * @see ecs_get_with() */ FLECS_API ecs_entity_t ecs_set_with( ecs_world_t *world, ecs_id_t component); -/** Get component set with ecs_set_with(). - * Get the component set with ecs_set_with(). +/** Get the component set with ecs_set_with(). + * This operation returns the component that was previously provided to + * ecs_set_with(). * * @param world The world. * @return The last component provided to ecs_set_with(). @@ -6980,7 +8260,7 @@ ecs_id_t ecs_get_with( * @{ */ -/** Enable or disable entity. +/** Enable or disable an entity. * This operation enables or disables an entity by adding or removing the * #EcsDisabled tag. A disabled entity will not be matched with any systems, * unless the system explicitly specifies the #EcsDisabled tag. @@ -6995,7 +8275,7 @@ void ecs_enable( ecs_entity_t entity, bool enabled); -/** Enable or disable component. +/** Enable or disable a component. * Enabling or disabling a component does not add or remove a component from an * entity, but prevents it from being matched with queries. This operation can * be useful when a component must be temporarily disabled without destroying @@ -7015,10 +8295,10 @@ void ecs_enable_id( ecs_id_t component, bool enable); -/** Test if component is enabled. +/** Test if a component is enabled. * Test whether a component is currently enabled or disabled. This operation * will return true when the entity has the component and if it has not been - * disabled by ecs_enable_component(). + * disabled by ecs_enable_id(). * * @param world The world. * @param entity The entity. @@ -7034,15 +8314,15 @@ bool ecs_is_enabled_id( /** @} */ /** - * @defgroup getting Getting & Setting - * Functions for getting/setting components. + * @defgroup getting Getting and Setting + * Functions for getting and setting components. * * @{ */ /** Get an immutable pointer to a component. * This operation obtains a const pointer to the requested component. The - * operation accepts the component entity id. + * operation accepts the component entity ID. * * This operation can return inherited components reachable through an `IsA` * relationship. @@ -7062,7 +8342,7 @@ FLECS_ALWAYS_INLINE const void* ecs_get_id( /** Get a mutable pointer to a component. * This operation obtains a mutable pointer to the requested component. The - * operation accepts the component entity id. + * operation accepts the component entity ID. * * Unlike ecs_get_id(), this operation does not return inherited components. * This is to prevent errors where an application accidentally resolves an @@ -7080,18 +8360,19 @@ FLECS_ALWAYS_INLINE void* ecs_get_mut_id( ecs_entity_t entity, ecs_id_t component); -/** Ensure entity has component, return pointer. +/** Ensure an entity has a component and return a pointer. * This operation returns a mutable pointer to a component. If the entity did * not yet have the component, it will be added. * - * If ensure is called when the world is in deferred/readonly mode, the + * If ensure() is called when the world is in deferred or read-only mode, the * function will: - * - return a pointer to a temp storage if the component does not yet exist, or + * - return a pointer to temporary storage if the component does not yet exist, or * - return a pointer to the existing component if it exists * * @param world The world. * @param entity The entity. - * @param component The component to get/add. + * @param component The component to get or add. + * @param size The size of the component. * @return The component pointer. * * @see ecs_emplace_id() @@ -7104,8 +8385,8 @@ void* ecs_ensure_id( size_t size); /** Create a component ref. - * A ref is a handle to an entity + component which caches a small amount of - * data to reduce overhead of repeatedly accessing the component. Use + * A ref is a handle to an entity and component pair, which caches a small amount of + * data to reduce the overhead of repeatedly accessing the component. Use * ecs_ref_get() to get the component data. * * @param world The world. @@ -7119,8 +8400,8 @@ ecs_ref_t ecs_ref_init_id( ecs_entity_t entity, ecs_id_t component); -/** Get component from ref. - * Get component pointer from ref. The ref must be created with ecs_ref_init(). +/** Get a component from a ref. + * Get a component pointer from a ref. The ref must be created with ecs_ref_init(). * The specified component must match the component with which the ref was * created. * @@ -7135,9 +8416,9 @@ void* ecs_ref_get_id( ecs_ref_t *ref, ecs_id_t component); -/** Update ref. - * Ensures contents of ref are up to date. Same as ecs_ref_get_id(), but does not - * return pointer to component id. +/** Update a ref. + * Ensure the contents of a ref are up to date. Same as ecs_ref_get_id(), but does not + * return a pointer to the component. * * @param world The world. * @param ref The ref. @@ -7162,7 +8443,7 @@ void ecs_ref_update( * * @param world The world. * @param entity The entity. - * @param component The component to get/add. + * @param component The component to get or add. * @param size The component size. * @param is_new Whether this is an existing or new component. * @return The (uninitialized) component pointer. @@ -7193,7 +8474,7 @@ void ecs_modified_id( /** Set the value of a component. * This operation allows an application to set the value of a component. The * operation is equivalent to calling ecs_ensure_id() followed by - * ecs_modified_id(). The operation will not modify the value of the passed in + * ecs_modified_id(). The operation will not modify the value of the passed-in * component. If the component has a copy hook registered, it will be used to * copy in the component. * @@ -7223,18 +8504,18 @@ void ecs_set_id( */ /** Test whether an entity is valid. - * This operation tests whether the entity id: + * This operation tests whether the entity ID: * - is not 0 * - has a valid bit pattern * - is alive (see ecs_is_alive()) * - * If this operation returns true, it is safe to use the entity with other + * If this operation returns true, it is safe to use the entity with * other operations. * * This operation should only be used if an application cannot be sure that an * entity is initialized with a valid value. In all other cases where an entity * was initialized with a valid value, but the application wants to check if the - * entity is (still) alive, use ecs_is_alive. + * entity is (still) alive, use ecs_is_alive(). * * @param world The world. * @param e The entity. @@ -7248,12 +8529,12 @@ bool ecs_is_valid( /** Test whether an entity is alive. * Entities are alive after they are created, and become not alive when they are - * deleted. Operations that return alive ids are (amongst others) ecs_new(), - * ecs_new_low_id() and ecs_entity_init(). Ids can be made alive with the - * ecs_make_alive() * function. + * deleted. Operations that return alive IDs are (amongst others) ecs_new(), + * ecs_new_low_id() and ecs_entity_init(). IDs can be made alive with the + * ecs_make_alive() function. * - * After an id is deleted it can be recycled. Recycled ids are different from - * the original id in that they have a different generation count. This makes it + * After an ID is deleted it can be recycled. Recycled IDs are different from + * the original ID in that they have a different generation count. This makes it * possible for the API to distinguish between the two. An example: * * @code @@ -7267,8 +8548,8 @@ bool ecs_is_valid( * ecs_is_alive(world, e1); // false * @endcode * - * Other than ecs_is_valid(), this operation will panic if the passed in entity - * id is 0 or has an invalid bit pattern. + * Unlike ecs_is_valid(), this operation will panic if the passed-in entity + * ID is 0 or has an invalid bit pattern. * * @param world The world. * @param e The entity. @@ -7280,55 +8561,55 @@ bool ecs_is_alive( const ecs_world_t *world, ecs_entity_t e); -/** Remove generation from entity id. +/** Remove the generation from an entity ID. * - * @param e The entity id. - * @return The entity id without the generation count. + * @param e The entity ID. + * @return The entity ID without the generation count. */ FLECS_API ecs_id_t ecs_strip_generation( ecs_entity_t e); -/** Get alive identifier. +/** Get an alive identifier. * In some cases an application may need to work with identifiers from which * the generation has been stripped. A typical scenario in which this happens is * when iterating relationships in an entity type. * - * For example, when obtaining the parent id from a `ChildOf` relationship, the parent - * (second element of the pair) will have been stored in a 32 bit value, which + * For example, when obtaining the parent ID from a `ChildOf` relationship, the parent + * (second element of the pair) will have been stored in a 32-bit value, which * cannot store the entity generation. This function can retrieve the identifier - * with the current generation for that id. + * with the current generation for that ID. * * If the provided identifier is not alive, the function will return 0. * * @param world The world. - * @param e The for which to obtain the current alive entity id. - * @return The alive entity id if there is one, or 0 if the id is not alive. + * @param e The entity for which to obtain the current alive entity ID. + * @return The alive entity ID if there is one, or 0 if the ID is not alive. */ FLECS_API ecs_entity_t ecs_get_alive( const ecs_world_t *world, ecs_entity_t e); -/** Ensure id is alive. - * This operation ensures that the provided id is alive. This is useful in - * scenarios where an application has an existing id that has not been created - * with ecs_new_w() (such as a global constant or an id from a remote application). +/** Ensure an ID is alive. + * This operation ensures that the provided ID is alive. This is useful in + * scenarios where an application has an existing ID that has not been created + * with ecs_new_w() (such as a global constant or an ID from a remote application). * - * When this operation is successful it guarantees that the provided id exists, - * is valid and is alive. + * When this operation is successful, it guarantees that the provided ID exists, + * is valid, and is alive. * - * Before this operation the id must either not be alive or have a generation - * that is equal to the passed in entity. + * Before this operation, the ID must either not be alive or have a generation + * that is equal to the passed-in entity. * - * If the provided id has a non-zero generation count and the id does not exist - * in the world, the id will be created with the specified generation. + * If the provided ID has a non-zero generation count and the ID does not exist + * in the world, the ID will be created with the specified generation. * - * If the provided id is alive and has a generation count that does not match - * the provided id, the operation will fail. + * If the provided ID is alive and has a generation count that does not match + * the provided ID, the operation will fail. * * @param world The world. - * @param entity The entity id to make alive. + * @param entity The entity ID to make alive. * * @see ecs_make_alive_id() */ @@ -7338,17 +8619,17 @@ void ecs_make_alive( ecs_entity_t entity); /** Same as ecs_make_alive(), but for components. - * An id can be an entity or pair, and can contain id flags. This operation + * An ID can be an entity or a pair, and can contain ID flags. This operation * ensures that the entity (or entities, for a pair) are alive. * - * When this operation is successful it guarantees that the provided id can be - * used in operations that accept an id. + * When this operation is successful, it guarantees that the provided ID can be + * used in operations that accept an ID. * - * Since entities in a pair do not encode their generation ids, this operation + * Since entities in a pair do not encode their generation IDs, this operation * will not fail when an entity with non-zero generation count already exists in * the world. * - * This is different from ecs_make_alive(), which will fail if attempted with an id + * This is different from ecs_make_alive(), which will fail if attempted with an ID * that has generation 0 and an entity with a non-zero generation is currently * alive. * @@ -7361,7 +8642,7 @@ void ecs_make_alive_id( ecs_id_t component); /** Test whether an entity exists. - * Similar as ecs_is_alive(), but ignores entity generation count. + * Similar to ecs_is_alive(), but ignores the entity generation count. * * @param world The world. * @param entity The entity. @@ -7374,26 +8655,26 @@ bool ecs_exists( /** Override the generation of an entity. * The generation count of an entity is increased each time an entity is deleted - * and is used to test whether an entity id is alive. + * and is used to test whether an entity ID is alive. * * This operation overrides the current generation of an entity with the * specified generation, which can be useful if an entity is externally managed, - * like for external pools, savefiles or netcode. + * like for external pools, savefiles, or netcode. * * This operation is similar to ecs_make_alive(), except that it will also * override the generation of an alive entity. * * @param world The world. - * @param entity Entity for which to set the generation with the new generation. + * @param entity The entity for which to set the generation. */ FLECS_API void ecs_set_version( ecs_world_t *world, ecs_entity_t entity); -/** Get generation of an entity. +/** Get the generation of an entity. * - * @param entity Entity for which to get the generation of. + * @param entity The entity for which to get the generation. * @return The generation of the entity. */ FLECS_API @@ -7404,7 +8685,7 @@ uint32_t ecs_get_version( /** * @defgroup entity_info Entity Information. - * Get information from entity. + * Get information from an entity. * * @{ */ @@ -7424,14 +8705,14 @@ const ecs_type_t* ecs_get_type( * * @param world The world. * @param entity The entity. - * @return The table of the entity, NULL if the entity has no components/tags. + * @return The table of the entity, NULL if the entity has no components or tags. */ FLECS_API ecs_table_t* ecs_get_table( const ecs_world_t *world, ecs_entity_t entity); -/** Convert type to string. +/** Convert a type to a string. * The result of this operation must be freed with ecs_os_free(). * * @param world The world. @@ -7443,7 +8724,7 @@ char* ecs_type_str( const ecs_world_t *world, const ecs_type_t* type); -/** Convert table to string. +/** Convert a table to a string. * Same as `ecs_type_str(world, ecs_table_get_type(table))`. The result of this * operation must be freed with ecs_os_free(). * @@ -7459,7 +8740,7 @@ char* ecs_table_str( const ecs_world_t *world, const ecs_table_t *table); -/** Convert entity to string. +/** Convert an entity to a string. * Same as combining: * - ecs_get_path(world, entity) * - ecs_type_str(world, ecs_get_type(world, entity)) @@ -7531,7 +8812,7 @@ ecs_entity_t ecs_get_target( ecs_entity_t rel, int32_t index); -/** Get parent (target of `ChildOf` relationship) for entity. +/** Get the parent (target of the `ChildOf` relationship) for an entity. * This operation is the same as calling: * * @code @@ -7549,13 +8830,32 @@ ecs_entity_t ecs_get_parent( const ecs_world_t *world, ecs_entity_t entity); +/** Create child with Parent component. + * This creates or returns an existing child for the specified parent. If a new + * child is created, the Parent component is used to create the parent + * relationship. + * + * If a child entity already exists with the specified name, it will be + * returned. + * + * @param world The world. + * @param parent The parent for which to create the child. + * @param name The name with which to create the entity (may be NULL). + * @return A new or existing child entity. + */ +FLECS_API +ecs_entity_t ecs_new_w_parent( + ecs_world_t *world, + ecs_entity_t parent, + const char *name); + /** Get the target of a relationship for a given component. * This operation returns the first entity that has the provided component by * following the relationship. If the entity itself has the component then it * will be returned. If the component cannot be found on the entity or by * following the relationship, the operation will return 0. * - * This operation can be used to lookup, for example, which prefab is providing + * This operation can be used to look up, for example, which prefab is providing * a component by specifying the `IsA` relationship: * * @code @@ -7566,7 +8866,7 @@ ecs_entity_t ecs_get_parent( * @param world The world. * @param entity The entity. * @param rel The relationship to follow. - * @param component The component to lookup. + * @param component The component to look up. * @return The entity for which the target has been found. */ FLECS_API @@ -7576,9 +8876,9 @@ ecs_entity_t ecs_get_target_for_id( ecs_entity_t rel, ecs_id_t component); -/** Return depth for entity in tree for the specified relationship. +/** Return the depth for an entity in the tree for the specified relationship. * Depth is determined by counting the number of targets encountered while - * traversing up the relationship tree for rel. Only acyclic relationships are + * traversing up the relationship tree for `rel`. Only acyclic relationships are * supported. * * @param world The world. @@ -7592,12 +8892,12 @@ int32_t ecs_get_depth( ecs_entity_t entity, ecs_entity_t rel); -/** Count entities that have the specified id. - * Returns the number of entities that have the specified id. +/** Count entities that have the specified ID. + * Return the number of entities that have the specified ID. * * @param world The world. - * @param entity The id to search for. - * @return The number of entities that have the id. + * @param entity The ID to search for. + * @return The number of entities that have the ID. */ FLECS_API int32_t ecs_count_id( @@ -7619,7 +8919,7 @@ int32_t ecs_count_id( * * @param world The world. * @param entity The entity. - * @return The type of the entity, NULL if the entity has no name. + * @return The name of the entity, NULL if the entity has no name. * * @see ecs_set_name() */ @@ -7633,7 +8933,7 @@ const char* ecs_get_name( * * @param world The world. * @param entity The entity. - * @return The type of the entity, NULL if the entity has no name. + * @return The symbol of the entity, NULL if the entity has no symbol. * * @see ecs_set_symbol() */ @@ -7665,7 +8965,7 @@ ecs_entity_t ecs_set_name( * This will set or overwrite the symbol of an entity. If no entity is provided, * a new entity will be created. * - * The symbol is stored in (EcsIdentifier, EcsSymbol). + * The symbol is stored in `(EcsIdentifier, EcsSymbol)`. * * @param world The world. * @param entity The entity. @@ -7680,12 +8980,12 @@ ecs_entity_t ecs_set_symbol( ecs_entity_t entity, const char *symbol); -/** Set alias for entity. +/** Set an alias for an entity. * An entity can be looked up using its alias from the root scope without - * providing the fully qualified name if its parent. An entity can only have + * providing the fully qualified name of its parent. An entity can only have * a single alias. * - * The symbol is stored in `(EcsIdentifier, EcsAlias)`. + * The alias is stored in `(EcsIdentifier, EcsAlias)`. * * @param world The world. * @param entity The entity. @@ -7697,7 +8997,7 @@ void ecs_set_alias( ecs_entity_t entity, const char *alias); -/** Lookup an entity by it's path. +/** Look up an entity by its path. * This operation is equivalent to calling: * * @code @@ -7717,13 +9017,13 @@ ecs_entity_t ecs_lookup( const ecs_world_t *world, const char *path); -/** Lookup a child entity by name. - * Returns an entity that matches the specified name. Only looks for entities in - * the provided parent. If no parent is provided, look in the current scope ( - * root if no scope is provided). +/** Look up a child entity by name. + * Return an entity that matches the specified name. Only look for entities in + * the provided parent. If no parent is provided, look in the current scope + * (root if no scope is provided). * * @param world The world. - * @param parent The parent for which to lookup the child. + * @param parent The parent for which to look up the child. * @param name The entity name. * @return The entity with the specified name, or 0 if no entity was found. * @@ -7737,14 +9037,14 @@ ecs_entity_t ecs_lookup_child( ecs_entity_t parent, const char *name); -/** Lookup an entity from a path. - * Lookup an entity from a provided path, relative to the provided parent. The +/** Look up an entity from a path. + * Look up an entity from a provided path, relative to the provided parent. The * operation will use the provided separator to tokenize the path expression. If * the provided path contains the prefix, the search will start from the root. * * If the entity is not found in the provided parent, the operation will * continue to search in the parent of the parent, until the root is reached. If - * the entity is still not found, the lookup will search in the flecs.core + * the entity is still not found, the lookup will search in the `flecs.core` * scope. If the entity is not found there either, the function returns 0. * * @param world The world. @@ -7752,7 +9052,7 @@ ecs_entity_t ecs_lookup_child( * @param path The path to resolve. * @param sep The path separator. * @param prefix The path prefix. - * @param recursive Recursively traverse up the tree until entity is found. + * @param recursive Recursively traverse up the tree until the entity is found. * @return The entity if found, else 0. * * @see ecs_lookup() @@ -7768,8 +9068,8 @@ ecs_entity_t ecs_lookup_path_w_sep( const char *prefix, bool recursive); -/** Lookup an entity by its symbol name. - * This looks up an entity by symbol stored in `(EcsIdentifier, EcsSymbol)`. The +/** Look up an entity by its symbol name. + * This looks up an entity by the symbol stored in `(EcsIdentifier, EcsSymbol)`. The * operation does not take into account hierarchies. * * This operation can be useful to resolve, for example, a type by its C @@ -7777,7 +9077,7 @@ ecs_entity_t ecs_lookup_path_w_sep( * * @param world The world. * @param symbol The symbol. - * @param lookup_as_path If not found as a symbol, lookup as path. + * @param lookup_as_path If not found as a symbol, look up as path. * @param recursive If looking up as path, recursively traverse up the tree. * @return The entity if found, else 0. * @@ -7795,11 +9095,11 @@ ecs_entity_t ecs_lookup_symbol( /** Get a path identifier for an entity. * This operation creates a path that contains the names of the entities from * the specified parent to the provided entity, separated by the provided - * separator. If no parent is provided the path will be relative to the root. If + * separator. If no parent is provided, the path will be relative to the root. If * a prefix is provided, the path will be prefixed by the prefix. * * If the parent is equal to the provided child, the operation will return an - * empty string. If a nonzero component is provided, the path will be created by + * empty string. If a non-zero component is provided, the path will be created by * looking for parents with that component. * * The returned path should be freed by the application. @@ -7821,8 +9121,8 @@ char* ecs_get_path_w_sep( const char *sep, const char *prefix); -/** Write path identifier to buffer. - * Same as ecs_get_path_w_sep(), but writes result to an ecs_strbuf_t. +/** Write a path identifier to a buffer. + * Same as ecs_get_path_w_sep(), but writes the result to an `ecs_strbuf_t`. * * @param world The world. * @param parent The entity from which to create the path. @@ -7830,6 +9130,7 @@ char* ecs_get_path_w_sep( * @param sep The separator to use between path elements. * @param prefix The initial character to use for root elements. * @param buf The buffer to write to. + * @param escape Whether to escape separator characters in names. * * @see ecs_get_path_w_sep() */ @@ -7843,7 +9144,7 @@ void ecs_get_path_w_sep_buf( ecs_strbuf_t *buf, bool escape); -/** Find or create entity from path. +/** Find or create an entity from a path. * This operation will find or create an entity from a path, and will create any * intermediate entities if required. If the entity already exists, no entities * will be created. @@ -7866,7 +9167,7 @@ ecs_entity_t ecs_new_from_path_w_sep( const char *sep, const char *prefix); -/** Add specified path to entity. +/** Add a specified path to an entity. * This operation is similar to ecs_new_from_path(), but will instead add the path * to an existing entity. * @@ -7891,7 +9192,7 @@ ecs_entity_t ecs_add_path_w_sep( /** Set the current scope. * This operation sets the scope of the current stage to the provided entity. - * As a result new entities will be created in this scope, and lookups will be + * As a result, new entities will be created in this scope, and lookups will be * relative to the provided scope. * * It is considered good practice to restore the scope to the old value. @@ -7921,7 +9222,7 @@ ecs_entity_t ecs_get_scope( /** Set a name prefix for newly created entities. * This is a utility that lets C modules use prefixed names for C types and * C functions, while using names for the entity names that do not have the - * prefix. The name prefix is currently only used by ECS_COMPONENT. + * prefix. The name prefix is currently only used by `ECS_COMPONENT`. * * @param world The world. * @param prefix The name prefix to use. @@ -7932,29 +9233,29 @@ const char* ecs_set_name_prefix( ecs_world_t *world, const char *prefix); -/** Set search path for lookup operations. - * This operation accepts an array of entity ids that will be used as search +/** Set the search path for lookup operations. + * This operation accepts an array of entity IDs that will be used as search * scopes by lookup operations. The operation returns the current search path. * It is good practice to restore the old search path. * * The search path will be evaluated starting from the last element. * - * The default search path includes flecs.core. When a custom search path is - * provided it overwrites the existing search path. Operations that rely on - * looking up names from flecs.core without providing the namespace may fail if - * the custom search path does not include flecs.core (EcsFlecsCore). + * The default search path includes `flecs.core`. When a custom search path is + * provided, it overwrites the existing search path. Operations that rely on + * looking up names from `flecs.core` without providing the namespace may fail if + * the custom search path does not include `flecs.core` (`EcsFlecsCore`). * * The search path array is not copied into managed memory. The application must * ensure that the provided array is valid for as long as it is used as the * search path. * * The provided array must be terminated with a 0 element. This enables an - * application to push/pop elements to an existing array without invoking the + * application to push or pop elements to an existing array without invoking the * ecs_set_lookup_path() operation again. * * @param world The world. - * @param lookup_path 0-terminated array with entity ids for the lookup path. - * @return Current lookup path array. + * @param lookup_path 0-terminated array with entity IDs for the lookup path. + * @return The current lookup path array. * * @see ecs_get_lookup_path() */ @@ -7963,8 +9264,8 @@ ecs_entity_t* ecs_set_lookup_path( ecs_world_t *world, const ecs_entity_t *lookup_path); -/** Get current lookup path. - * Returns value set by ecs_set_lookup_path(). +/** Get the current lookup path. + * Return the value set by ecs_set_lookup_path(). * * @param world The world. * @return The current lookup path. @@ -8002,30 +9303,30 @@ ecs_entity_t ecs_component_init( ecs_world_t *world, const ecs_component_desc_t *desc); -/** Get the type info for an component. +/** Get the type info for a component. * This function returns the type information for a component. The component can - * be a regular component or pair. For the rules on how type information is - * determined based on a component id, see ecs_get_typeid(). + * be a regular component or a pair. For the rules on how type information is + * determined based on a component ID, see ecs_get_typeid(). * * @param world The world. * @param component The component. - * @return The type information of the id. + * @return The type information of the component ID. */ FLECS_API const ecs_type_info_t* ecs_get_type_info( const ecs_world_t *world, ecs_id_t component); -/** Register hooks for component. +/** Register hooks for a component. * Hooks allow for the execution of user code when components are constructed, - * copied, moved, destructed, added, removed or set. Hooks can be assigned as + * copied, moved, destructed, added, removed, or set. Hooks can be assigned * as long as a component has not yet been used (added to an entity). * * The hooks that are currently set can be accessed with ecs_get_type_info(). * * @param world The world. - * @param component The component for which to register the actions - * @param hooks Type that contains the component actions. + * @param component The component for which to register the actions. + * @param hooks The type that contains the component actions. */ FLECS_API void ecs_set_hooks_id( @@ -8033,7 +9334,7 @@ void ecs_set_hooks_id( ecs_entity_t component, const ecs_type_hooks_t *hooks); -/** Get hooks for component. +/** Get hooks for a component. * * @param world The world. * @param component The component for which to retrieve the hooks. @@ -8047,32 +9348,32 @@ const ecs_type_hooks_t* ecs_get_hooks_id( /** @} */ /** - * @defgroup ids Ids + * @defgroup ids IDs * Functions for working with `ecs_id_t`. * * @{ */ -/** Returns whether specified component is a tag. +/** Return whether a specified component is a tag. * This operation returns whether the specified component is a tag (a component - * without data/size). + * without data or size). * - * An id is a tag when: - * - it is an entity without the EcsComponent component - * - it has an EcsComponent with size member set to 0 + * An ID is a tag when: + * - it is an entity without the `EcsComponent` component + * - it has an `EcsComponent` with size member set to 0 * - it is a pair where both elements are a tag * - it is a pair where the first element has the #EcsPairIsTag tag * * @param world The world. * @param component The component. - * @return Whether the provided id is a tag. + * @return Whether the provided ID is a tag. */ FLECS_API bool ecs_id_is_tag( const ecs_world_t *world, ecs_id_t component); -/** Returns whether specified component is in use. +/** Return whether a specified component is in use. * This operation returns whether a component is in use in the world. A * component is in use if it has been added to one or more tables. * @@ -8086,18 +9387,18 @@ bool ecs_id_in_use( ecs_id_t component); /** Get the type for a component. - * This operation returns the type for a component id, if the id is associated + * This operation returns the type for a component ID, if the ID is associated * with a type. For a regular component with a non-zero size (an entity with the - * EcsComponent component) the operation will return the component id itself. + * EcsComponent component), the operation will return the component ID itself. * * For an entity that does not have the EcsComponent component, or with an * EcsComponent value with size 0, the operation will return 0. * - * For a pair id the operation will return the type associated with the pair, by + * For a pair ID, the operation will return the type associated with the pair, by * applying the following queries in order: - * - The first pair element is returned if it is a component - * - 0 is returned if the relationship entity has the Tag property - * - The second pair element is returned if it is a component + * - The first pair element is returned if it is a component. + * - 0 is returned if the relationship entity has the Tag property. + * - The second pair element is returned if it is a component. * - 0 is returned. * * @param world The world. @@ -8115,71 +9416,71 @@ ecs_entity_t ecs_get_typeid( * * @param component The component. * @param pattern The pattern to compare with. - * @return Whether the id matches the pattern. + * @return Whether the ID matches the pattern. */ FLECS_API bool ecs_id_match( ecs_id_t component, ecs_id_t pattern); -/** Utility to check if component is a pair. +/** Utility to check if a component is a pair. * * @param component The component. - * @return True if component is a pair. + * @return True if the component is a pair. */ FLECS_API bool ecs_id_is_pair( ecs_id_t component); -/** Utility to check if component is a wildcard. +/** Utility to check if a component is a wildcard. * * @param component The component. - * @return True if component is a wildcard or a pair containing a wildcard. + * @return True if the component is a wildcard or a pair containing a wildcard. */ FLECS_API bool ecs_id_is_wildcard( ecs_id_t component); -/** Utility to check if component is an any wildcard. - * +/** Utility to check if a component is an any wildcard. + * * @param component The component. - * @return True if component is an any wildcard or a pair containing an any wildcard. + * @return True if the component is an any wildcard or a pair containing an any wildcard. */ bool ecs_id_is_any( ecs_id_t component); -/** Utility to check if id is valid. - * A valid id is an id that can be added to an entity. Invalid ids are: - * - ids that contain wildcards - * - ids that contain invalid entities - * - ids that are 0 or contain 0 entities +/** Utility to check if an ID is valid. + * A valid ID is an ID that can be added to an entity. Invalid IDs are: + * - IDs that contain wildcards + * - IDs that contain invalid entities + * - IDs that are 0 or contain 0 entities * * Note that the same rules apply to removing from an entity, with the exception * of wildcards. * * @param world The world. * @param component The component. - * @return True if the id is valid. + * @return True if the ID is valid. */ FLECS_API bool ecs_id_is_valid( const ecs_world_t *world, ecs_id_t component); -/** Get flags associated with id. +/** Get flags associated with an ID. * This operation returns the internal flags (see api_flags.h) that are - * associated with the provided id. + * associated with the provided ID. * * @param world The world. * @param component The component. - * @return Flags associated with the id, or 0 if the id is not in use. + * @return The flags associated with the ID, or 0 if the ID is not in use. */ FLECS_API ecs_flags32_t ecs_id_get_flags( const ecs_world_t *world, ecs_id_t component); -/** Convert component flag to string. +/** Convert a component flag to a string. * This operation converts a component flag to a string. Possible outputs are: * * - PAIR @@ -8187,14 +9488,14 @@ ecs_flags32_t ecs_id_get_flags( * - AUTO_OVERRIDE * * @param component_flags The component flag. - * @return The id flag string, or NULL if no valid id is provided. + * @return The ID flag string, or NULL if no valid ID is provided. */ FLECS_API const char* ecs_id_flag_str( - ecs_id_t component_flags); + uint64_t component_flags); -/** Convert component id to string. - * This operation converts the provided component id to a string. It can output +/** Convert a component ID to a string. + * This operation converts the provided component ID to a string. It can output * strings of the following formats: * * - "ComponentName" @@ -8202,7 +9503,7 @@ const char* ecs_id_flag_str( * - "(Relationship, Target)" * - "FLAG|(Relationship, Target)" * - * The PAIR flag never added to the string. + * The PAIR flag is never added to the string. * * @param world The world. * @param component The component to convert to a string. @@ -8213,8 +9514,8 @@ char* ecs_id_str( const ecs_world_t *world, ecs_id_t component); -/** Write component string to buffer. - * Same as ecs_id_str() but writes result to ecs_strbuf_t. +/** Write a component string to a buffer. + * Same as ecs_id_str(), but writes the result to ecs_strbuf_t. * * @param world The world. * @param component The component to convert to a string. @@ -8226,12 +9527,13 @@ void ecs_id_str_buf( ecs_id_t component, ecs_strbuf_t *buf); -/** Convert string to a component. +/** Convert a string to a component. * This operation is the reverse of ecs_id_str(). The FLECS_SCRIPT addon * is required for this operation to work. * * @param world The world. - * @param expr The string to convert to an id. + * @param expr The string to convert to an ID. + * @return The ID, or 0 if the string could not be converted. */ FLECS_API ecs_id_t ecs_id_from_str( @@ -8246,8 +9548,8 @@ ecs_id_t ecs_id_from_str( * @{ */ -/** Test whether term ref is set. - * A term ref is a reference to an entity, component or variable for one of the +/** Test whether a term ref is set. + * A term ref is a reference to an entity, component, or variable for one of the * three parts of a term (src, first, second). * * @param ref The term ref. @@ -8262,7 +9564,7 @@ bool ecs_term_ref_is_set( * values or whether it is empty. * * An application generally does not need to invoke this operation. It is useful - * when initializing a 0-initialized array of terms (like in ecs_term_desc_t) as + * when initializing a 0-initialized array of terms (like in ecs_query_desc_t), as * this operation can be used to find the last initialized element. * * @param term The term. @@ -8272,7 +9574,7 @@ FLECS_API bool ecs_term_is_initialized( const ecs_term_t *term); -/** Is term matched on $this variable. +/** Is a term matched on the $this variable. * This operation checks whether a term is matched on the $this variable, which * is the default source for queries. * @@ -8284,31 +9586,31 @@ bool ecs_term_is_initialized( * the $this source for the created query. * * @param term The term. - * @return True if term matches $this, false if not. + * @return True if the term matches $this, false if not. */ FLECS_API bool ecs_term_match_this( const ecs_term_t *term); -/** Is term matched on 0 source. +/** Is a term matched on a 0 source. * This operation checks whether a term is matched on a 0 source. A 0 source is * a term that isn't matched against anything, and can be used just to pass - * (component) ids to a query iterator. + * (component) IDs to a query iterator. * * A term has a 0 source when: * - ecs_term_t::src::id is 0 * - ecs_term_t::src::flags has EcsIsEntity set * * @param term The term. - * @return True if term has 0 source, false if not. + * @return True if the term has a 0 source, false if not. */ FLECS_API bool ecs_term_match_0( const ecs_term_t *term); -/** Convert term to string expression. - * Convert term to a string expression. The resulting expression is equivalent - * to the same term, with the exception of And & Or operators. +/** Convert a term to a string expression. + * Convert a term to a string expression. The resulting expression is equivalent + * to the same term, with the exception of And and Or operators. * * @param world The world. * @param term The term. @@ -8319,8 +9621,8 @@ char* ecs_term_str( const ecs_world_t *world, const ecs_term_t *term); -/** Convert query to string expression. - * Convert query to a string expression. The resulting expression can be +/** Convert a query to a string expression. + * Convert a query to a string expression. The resulting expression can be * parsed to create the same query. * * @param query The query. @@ -8334,13 +9636,13 @@ char* ecs_query_str( /** * @defgroup each_iter Each iterator - * @brief Find all entities that have a single (component) id. + * @brief Find all entities that have a single (component) ID. * @{ */ -/** Iterate all entities with specified (component id). +/** Iterate all entities with a specified (component ID). * This returns an iterator that yields all entities with a single specified - * component. This is a much lighter weight operation than creating and + * component. This is a much lighter-weight operation than creating and * iterating a query. * * Usage: @@ -8353,8 +9655,8 @@ char* ecs_query_str( * } * @endcode * - * If the specified id is a component, it is possible to access the component - * pointer with ecs_field just like with regular queries: + * If the specified ID is a component, it is possible to access the component + * pointer with ecs_field() just like with regular queries: * * @code * ecs_iter_t it = ecs_each(world, Position); @@ -8368,8 +9670,8 @@ char* ecs_query_str( * * @param world The world. * @param component The component to iterate. - * @return An iterator that iterates all entities with the (component) id. -*/ + * @return An iterator that iterates all entities with the (component) ID. + */ FLECS_API ecs_iter_t ecs_each_id( const ecs_world_t *world, @@ -8384,7 +9686,7 @@ FLECS_API bool ecs_each_next( ecs_iter_t *it); -/** Iterate children of parent. +/** Iterate children of a parent. * This operation is usually equivalent to doing: * @code * ecs_iter_t it = ecs_each_id(world, ecs_pair(EcsChildOf, parent)); @@ -8392,7 +9694,7 @@ bool ecs_each_next( * * The only exception is when the parent has the EcsOrderedChildren trait, in * which case this operation will return a single result with the ordered - * child entity ids. + * child entity IDs. * * This operation is equivalent to doing: * @@ -8405,13 +9707,13 @@ bool ecs_each_next( * @return An iterator that iterates all children of the parent. * * @see ecs_each_id() -*/ + */ FLECS_API FLECS_ALWAYS_INLINE ecs_iter_t ecs_children( const ecs_world_t *world, ecs_entity_t parent); -/** Same as ecs_children() but with custom relationship argument. +/** Same as ecs_children(), but with a custom relationship argument. * * @param world The world. * @param relationship The relationship. @@ -8445,7 +9747,7 @@ bool ecs_children_next( /** Create a query. * * @param world The world. - * @param desc The descriptor (see ecs_query_desc_t) + * @param desc The descriptor (see ecs_query_desc_t). * @return The query. */ FLECS_API @@ -8461,7 +9763,7 @@ FLECS_API void ecs_query_fini( ecs_query_t *query); -/** Find variable index. +/** Find a variable index. * This operation looks up the index of a variable in the query. This index can * be used in operations like ecs_iter_set_var() and ecs_iter_get_var(). * @@ -8474,7 +9776,7 @@ int32_t ecs_query_find_var( const ecs_query_t *query, const char *name); -/** Get variable name. +/** Get the variable name. * This operation returns the variable name for an index. * * @param query The query. @@ -8486,14 +9788,14 @@ const char* ecs_query_var_name( const ecs_query_t *query, int32_t var_id); -/** Test if variable is an entity. - * Internally the query engine has entity variables and table variables. When - * iterating through query variables (by using ecs_query_variable_count()) only +/** Test if a variable is an entity. + * Internally, the query engine has entity variables and table variables. When + * iterating through query variables (by using ecs_query_t::var_count) only * the values for entity variables are accessible. This operation enables an * application to check if a variable is an entity variable. * * @param query The query. - * @param var_id The variable id. + * @param var_id The variable ID. * @return Whether the variable is an entity variable. */ FLECS_API @@ -8502,14 +9804,14 @@ bool ecs_query_var_is_entity( int32_t var_id); /** Create a query iterator. - * Use an iterator to iterate through the entities that match an entity. Queries + * Use an iterator to iterate through the entities that match a query. Queries * can return multiple results, and have to be iterated by repeatedly calling * ecs_query_next() until the operation returns false. * * Depending on the query, a single result can contain an entire table, a range * of entities in a table, or a single entity. Iteration code has an inner and * an outer loop. The outer loop loops through the query results, and typically - * corresponds with a table. The inner loop loops entities in the result. + * corresponds with a table. The inner loop iterates entities in the result. * * Example: * @code @@ -8574,7 +9876,7 @@ ecs_iter_t ecs_query_iter( const ecs_world_t *world, const ecs_query_t *query); -/** Progress query iterator. +/** Progress a query iterator. * * @param it The iterator. * @return True if the iterator has more results, false if not. @@ -8585,7 +9887,7 @@ FLECS_API bool ecs_query_next( ecs_iter_t *it); -/** Match entity with query. +/** Match an entity with a query. * This operation matches an entity with a query and returns the result of the * match in the "it" out parameter. An application should free the iterator * resources with ecs_iter_fini() if this function returns true. @@ -8599,17 +9901,17 @@ bool ecs_query_next( * @endcode * * @param query The query. - * @param entity The entity to match + * @param entity The entity to match. * @param it The iterator with matched data. * @return True if entity matches the query, false if not. */ FLECS_API bool ecs_query_has( - ecs_query_t *query, + const ecs_query_t *query, ecs_entity_t entity, ecs_iter_t *it); -/** Match table with query. +/** Match a table with a query. * This operation matches a table with a query and returns the result of the * match in the "it" out parameter. An application should free the iterator * resources with ecs_iter_fini() if this function returns true. @@ -8623,17 +9925,17 @@ bool ecs_query_has( * @endcode * * @param query The query. - * @param table The table to match + * @param table The table to match. * @param it The iterator with matched data. * @return True if table matches the query, false if not. */ FLECS_API bool ecs_query_has_table( - ecs_query_t *query, + const ecs_query_t *query, ecs_table_t *table, ecs_iter_t *it); -/** Match range with query. +/** Match a range with a query. * This operation matches a range with a query and returns the result of the * match in the "it" out parameter. An application should free the iterator * resources with ecs_iter_fini() if this function returns true. @@ -8655,29 +9957,29 @@ bool ecs_query_has_table( * @endcode * * @param query The query. - * @param range The range to match + * @param range The range to match. * @param it The iterator with matched data. * @return True if range matches the query, false if not. */ FLECS_API bool ecs_query_has_range( - ecs_query_t *query, + const ecs_query_t *query, ecs_table_range_t *range, ecs_iter_t *it); -/** Returns how often a match event happened for a cached query. +/** Return how often a match event happened for a cached query. * This operation can be used to determine whether the query cache has been * updated with new tables. * * @param query The query. - * @return The number of match events happened. + * @return The number of match events that happened. */ FLECS_API int32_t ecs_query_match_count( const ecs_query_t *query); -/** Convert query to a string. - * This will convert the query program to a string which can aid in debugging +/** Convert a query to a string. + * This will convert the query program to a string, which can aid in debugging * the behavior of a query. * * The returned string must be freed with ecs_os_free(). @@ -8689,12 +9991,12 @@ FLECS_API char* ecs_query_plan( const ecs_query_t *query); -/** Convert query to string with profile. - * To use this you must set the EcsIterProfile flag on an iterator before +/** Convert a query to a string with a profile. + * To use this, you must set the EcsIterProfile flag on an iterator before * starting iteration: * * @code - * it.flags |= EcsIterProfile + * it.flags |= EcsIterProfile; * @endcode * * The returned string must be freed with ecs_os_free(). @@ -8708,22 +10010,31 @@ char* ecs_query_plan_w_profile( const ecs_query_t *query, const ecs_iter_t *it); -/** Populate variables from key-value string. +/** Same as ecs_query_plan(), but includes the plan for populating the cache (if any). + * + * @param query The query. + * @return The query plan. + */ +FLECS_API +char* ecs_query_plans( + const ecs_query_t *query); + +/** Populate variables from a key-value string. * Convenience function to set query variables from a key-value string separated - * by comma's. The string must have the following format: + * by commas. The string must have the following format: * * @code * var_a: value, var_b: value * @endcode * - * The key-value list may optionally be enclosed in parenthesis. + * The key-value list may optionally be enclosed in parentheses. * * This function uses the script addon. * * @param query The query. * @param it The iterator for which to set the variables. * @param expr The key-value expression. - * @return Pointer to the next character after the last parsed one. + * @return A pointer to the next character after the last parsed one. */ FLECS_API const char* ecs_query_args_parse( @@ -8731,39 +10042,34 @@ const char* ecs_query_args_parse( ecs_iter_t *it, const char *expr); -/** Returns whether the query data changed since the last iteration. +/** Return whether the query data changed since the last iteration. * The operation will return true after: - * - new entities have been matched with - * - new tables have been matched/unmatched with + * - new entities have been matched + * - new tables have been matched or unmatched * - matched entities were deleted * - matched components were changed * * The operation will not return true after a write-only (EcsOut) or filter - * (EcsInOutNone) term has changed, when a term is not matched with the - * current table (This subject) or for tag terms. + * (EcsInOutFilter) term has changed, when a term is not matched with the + * current table ($this source) or for tag terms. * * The changed state of a table is reset after it is iterated. If an iterator was * not iterated until completion, tables may still be marked as changed. * - * If no iterator is provided the operation will return the changed state of the - * all matched tables of the query. + * To check the changed state of the current iterator result, use + * ecs_iter_changed(). * - * If an iterator is provided, the operation will return the changed state of - * the currently returned iterator result. The following preconditions must be - * met before using an iterator with change detection: - * - * - The iterator is a query iterator (created with ecs_query_iter()) - * - The iterator must be valid (ecs_query_next() must have returned true) + * @param query The query. + * @return True if entities changed, otherwise false. * - * @param query The query (optional if 'it' is provided). - * @return true if entities changed, otherwise false. + * @see ecs_iter_changed() */ FLECS_API bool ecs_query_changed( ecs_query_t *query); -/** Get query object. - * Returns the query object. Can be used to access various information about +/** Get the query object. + * Return the query object. Can be used to access various information about * the query. * * @param world The world. @@ -8778,10 +10084,10 @@ const ecs_query_t* ecs_query_get( /** Skip a table while iterating. * This operation lets the query iterator know that a table was skipped while * iterating. A skipped table will not reset its changed state, and the query - * will not update the dirty flags of the table for its out columns. + * will not update the dirty flags of the table for its out fields. * - * Only valid iterators must be provided (next has to be called at least once & - * return true) and the iterator must be a query iterator. + * Only valid iterators must be provided (next() has to be called at least once + * and must return true), and the iterator must be a query iterator. * * @param it The iterator result to skip. */ @@ -8789,13 +10095,13 @@ FLECS_API void ecs_iter_skip( ecs_iter_t *it); -/** Set group to iterate for query iterator. +/** Set the group to iterate for a query iterator. * This operation limits the results returned by the query to only the selected - * group id. The query must have a group_by function, and the iterator must + * group ID. The query must have a group_by function, and the iterator must * be a query iterator. * * Groups are sets of tables that are stored together in the query cache based - * on a group id, which is calculated per table by the group_by function. To + * on a group ID, which is calculated per table by the group_by function. To * iterate a group, an iterator only needs to know the first and last cache node * for that group, which can both be found in a fast O(1) operation. * @@ -8805,7 +10111,7 @@ void ecs_iter_skip( * a world into cells, and only iterating cells close to a player. * * The group to iterate must be set before the first call to ecs_query_next(). No - * operations that can add/remove components should be invoked between calling + * operations that can add or remove components should be invoked between calling * ecs_iter_set_group() and ecs_query_next(). * * @param it The query iterator. @@ -8816,7 +10122,36 @@ void ecs_iter_set_group( ecs_iter_t *it, uint64_t group_id); -/** Get context of query group. +/** Return the map with query groups. + * This map can be used to iterate the active group identifiers of a query. The + * payload of the map is opaque. The map can be used as follows: + * + * @code + * const ecs_map_t *keys = ecs_query_get_groups(q); + * ecs_map_iter_t kit = ecs_map_iter(keys); + * while (ecs_map_next(&kit)) { + * uint64_t group_id = ecs_map_key(&kit); + * + * // Iterate query for group + * ecs_iter_t it = ecs_query_iter(world, q); + * ecs_iter_set_group(&it, group_id); + * while (ecs_query_next(&it)) { + * // Iterate as usual + * } + * } + * @endcode + * + * This operation is not valid for queries that do not use group_by. The + * returned map pointer will remain valid for as long as the query exists. + * + * @param query The query. + * @return The map with query groups. + */ +FLECS_API +const ecs_map_t* ecs_query_get_groups( + const ecs_query_t *query); + +/** Get the context of a query group. * This operation returns the context of a query group as returned by the * on_group_create callback. * @@ -8829,7 +10164,7 @@ void* ecs_query_get_group_ctx( const ecs_query_t *query, uint64_t group_id); -/** Get information about query group. +/** Get information about a query group. * This operation returns information about a query group, including the group * context returned by the on_group_create callback. * @@ -8844,14 +10179,14 @@ const ecs_query_group_info_t* ecs_query_get_group_info( /** Struct returned by ecs_query_count(). */ typedef struct ecs_query_count_t { - int32_t results; /**< Number of results returned by query. */ - int32_t entities; /**< Number of entities returned by query. */ - int32_t tables; /**< Number of tables returned by query. Only set for + int32_t results; /**< Number of results returned by the query. */ + int32_t entities; /**< Number of entities returned by the query. */ + int32_t tables; /**< Number of tables returned by the query. Only set for * queries for which the table count can be reliably * determined. */ } ecs_query_count_t; -/** Returns number of entities and results the query matches with. +/** Return the number of entities and results the query matches with. * Only entities matching the $this variable as source are counted. * * @param query The query. @@ -8861,7 +10196,7 @@ FLECS_API ecs_query_count_t ecs_query_count( const ecs_query_t *query); -/** Does query return one or more results. +/** Test whether a query returns one or more results. * * @param query The query. * @return True if query matches anything, false if not. @@ -8870,10 +10205,10 @@ FLECS_API bool ecs_query_is_true( const ecs_query_t *query); -/** Get query used to populate cache. +/** Get the query used to populate the cache. * This operation returns the query that is used to populate the query cache. - * For queries that are can be entirely cached, the returned query will be - * equivalent to the query passed to ecs_query_get_cache_query(). + * For queries that can be entirely cached, the returned query will be + * equivalent to the query passed to ecs_query_init(). * * @param query The query. * @return The query used to populate the cache, NULL if query is not cached. @@ -8891,22 +10226,22 @@ const ecs_query_t* ecs_query_get_cache_query( * @{ */ -/** Send event. - * This sends an event to matching triggers & is the mechanism used by flecs - * itself to send `OnAdd`, `OnRemove`, etc events. +/** Send an event. + * This sends an event to matching observers and is the mechanism used by Flecs + * itself to send `OnAdd`, `OnRemove`, etc. events. * * Applications can use this function to send custom events, where a custom * event can be any regular entity. * - * Applications should not send builtin flecs events, as this may violate + * Applications should not send built-in Flecs events, as this may violate * assumptions the code makes about the conditions under which those events are * sent. * - * Triggers are invoked synchronously. It is therefore safe to use stack-based + * Observers are invoked synchronously. It is therefore safe to use stack-based * data as event context, which can be set in the "param" member. * * @param world The world. - * @param desc Event parameters. + * @param desc The event parameters. * * @see ecs_enqueue() */ @@ -8915,24 +10250,24 @@ void ecs_emit( ecs_world_t *world, ecs_event_desc_t *desc); -/** Enqueue event. +/** Enqueue an event. * Same as ecs_emit(), but enqueues an event in the command queue instead. The * event will be emitted when ecs_defer_end() is called. * - * If this operation is called when the provided world is not in deferred mode + * If this operation is called when the provided world is not in deferred mode, * it behaves just like ecs_emit(). * * @param world The world. - * @param desc Event parameters. -*/ + * @param desc The event parameters. + */ FLECS_API void ecs_enqueue( ecs_world_t *world, ecs_event_desc_t *desc); -/** Create observer. - * Observers are like triggers, but can subscribe for multiple terms. An - * observer only triggers when the source of the event meets all terms. +/** Create an observer. + * Observers can subscribe for one or more terms. An observer only triggers + * when the source of the event meets all terms. * * See the documentation for ecs_observer_desc_t for more details. * @@ -8945,8 +10280,8 @@ ecs_entity_t ecs_observer_init( ecs_world_t *world, const ecs_observer_desc_t *desc); -/** Get observer object. - * Returns the observer object. Can be used to access various information about +/** Get the observer object. + * Return the observer object. Can be used to access various information about * the observer, like the query and context. * * @param world The world. @@ -8973,8 +10308,8 @@ const ecs_observer_t* ecs_observer_get( * any kind of iterator (such as serializers) or iterators created from poly * objects. * - * This operation is slightly slower than using a type-specific iterator (e.g. - * ecs_query_next, ecs_query_next) as it has to call a function pointer which + * This operation is slightly slower than using a type-specific iterator (e.g., + * ecs_query_next(), ecs_each_next()), as it has to call a function pointer, which * introduces a level of indirection. * * @param it The iterator. @@ -8984,11 +10319,11 @@ FLECS_API bool ecs_iter_next( ecs_iter_t *it); -/** Cleanup iterator resources. +/** Clean up iterator resources. * This operation cleans up any resources associated with the iterator. * * This operation should only be used when an iterator is not iterated until - * completion (next has not yet returned false). When an iterator is iterated + * completion (next() has not yet returned false). When an iterator is iterated * until completion, resources are automatically freed. * * @param it The iterator. @@ -8997,39 +10332,39 @@ FLECS_API void ecs_iter_fini( ecs_iter_t *it); -/** Count number of matched entities in query. +/** Count the number of matched entities in a query. * This operation returns the number of matched entities. If a query contains no - * matched entities but still yields results (e.g. it has no terms with This - * sources) the operation will return 0. + * matched entities but still yields results (e.g., it has no terms with $this + * sources), the operation will return 0. * * To determine the number of matched entities, the operation iterates the * iterator until it yields no more results. * * @param it The iterator. - * @return True if iterator has more results, false if not. + * @return The number of matched entities. */ FLECS_API int32_t ecs_iter_count( ecs_iter_t *it); -/** Test if iterator is true. +/** Test if an iterator is true. * This operation will return true if the iterator returns at least one result. * This is especially useful in combination with fact-checking queries (see the * queries addon). * * The operation requires a valid iterator. After the operation is invoked, the - * application should no longer invoke next on the iterator and should treat it + * application should no longer invoke next() on the iterator and should treat it * as if the iterator is iterated until completion. * * @param it The iterator. - * @return true if the iterator returns at least one result. + * @return True if the iterator returns at least one result. */ FLECS_API bool ecs_iter_is_true( ecs_iter_t *it); -/** Get first matching entity from iterator. - * After this operation the application should treat the iterator as if it has +/** Get the first matching entity from an iterator. + * After this operation, the application should treat the iterator as if it has * been iterated until completion. * * @param it The iterator. @@ -9039,7 +10374,7 @@ FLECS_API ecs_entity_t ecs_iter_first( ecs_iter_t *it); -/** Set value for iterator variable. +/** Set the value for an iterator variable. * This constrains the iterator to return only results for which the variable * equals the specified value. The default value for all variables is * EcsWildcard, which means the variable can assume any value. @@ -9054,7 +10389,7 @@ ecs_entity_t ecs_iter_first( * } * }); * - * int food_var = ecs_query_find_var(r, "food"); + * int food_var = ecs_query_find_var(q, "food"); * * // Set Food to Apples, so we're only matching (Eats, Apples) * ecs_iter_t it = ecs_query_iter(world, q); @@ -9068,7 +10403,7 @@ ecs_entity_t ecs_iter_first( * @endcode * * The variable must be initialized after creating the iterator and before the - * first call to next. + * first call to next(). * * @param it The iterator. * @param var_id The variable index. @@ -9099,7 +10434,7 @@ void ecs_iter_set_var_as_table( int32_t var_id, const ecs_table_t *table); -/** Same as ecs_iter_set_var(), but for a range of entities +/** Same as ecs_iter_set_var(), but for a range of entities. * This constrains the variable to a range of entities in a table. * * @param it The iterator. @@ -9115,13 +10450,13 @@ void ecs_iter_set_var_as_range( int32_t var_id, const ecs_table_range_t *range); -/** Get value of iterator variable as entity. - * A variable can be interpreted as entity if it is set to an entity, or if it +/** Get the value of an iterator variable as an entity. + * A variable can be interpreted as an entity if it is set to an entity, or if it * is set to a table range with count 1. * * This operation can only be invoked on valid iterators. The variable index * must be smaller than the total number of variables provided by the iterator - * (as set in ecs_iter_t::variable_count). + * (as returned by ecs_iter_get_var_count()). * * @param it The iterator. * @param var_id The variable index. @@ -9132,7 +10467,7 @@ ecs_entity_t ecs_iter_get_var( ecs_iter_t *it, int32_t var_id); -/** Get variable name. +/** Get the variable name. * * @param it The iterator. * @param var_id The variable index. @@ -9143,16 +10478,16 @@ const char* ecs_iter_get_var_name( const ecs_iter_t *it, int32_t var_id); -/** Get number of variables. +/** Get the number of variables. * * @param it The iterator. * @return The number of variables. -*/ + */ FLECS_API int32_t ecs_iter_get_var_count( const ecs_iter_t *it); -/** Get variable array. +/** Get the variable array. * * @param it The iterator. * @return The variable array (if any). @@ -9161,14 +10496,14 @@ FLECS_API ecs_var_t* ecs_iter_get_vars( const ecs_iter_t *it); -/** Get value of iterator variable as table. - * A variable can be interpreted as table if it is set as table range with +/** Get the value of an iterator variable as a table. + * A variable can be interpreted as a table if it is set as a table range with * both offset and count set to 0, or if offset is 0 and count matches the * number of elements in the table. * * This operation can only be invoked on valid iterators. The variable index * must be smaller than the total number of variables provided by the iterator - * (as set in ecs_iter_t::variable_count). + * (as returned by ecs_iter_get_var_count()). * * @param it The iterator. * @param var_id The variable index. @@ -9179,14 +10514,14 @@ ecs_table_t* ecs_iter_get_var_as_table( ecs_iter_t *it, int32_t var_id); -/** Get value of iterator variable as table range. - * A value can be interpreted as table range if it is set as table range, or if +/** Get the value of an iterator variable as a table range. + * A value can be interpreted as a table range if it is set as a table range, or if * it is set to an entity with a non-empty type (the entity must have at least - * one component, tag or relationship in its type). + * one component, tag, or relationship in its type). * * This operation can only be invoked on valid iterators. The variable index * must be smaller than the total number of variables provided by the iterator - * (as set in ecs_iter_t::variable_count). + * (as returned by ecs_iter_get_var_count()). * * @param it The iterator. * @param var_id The variable index. @@ -9197,7 +10532,7 @@ ecs_table_range_t ecs_iter_get_var_as_range( ecs_iter_t *it, int32_t var_id); -/** Returns whether variable is constrained. +/** Return whether a variable is constrained. * This operation returns true for variables set by one of the ecs_iter_set_var* * operations. * @@ -9213,24 +10548,24 @@ bool ecs_iter_var_is_constrained( ecs_iter_t *it, int32_t var_id); -/** Return the group id for the currently iterated result. - * This operation returns the group id for queries that use group_by. If this +/** Return the group ID for the currently iterated result. + * This operation returns the group ID for queries that use group_by. If this * operation is called on an iterator that is not iterating a query that uses - * group_by it will fail. + * group_by, it will fail. * * For queries that use cascade, this operation will return the hierarchy depth * of the currently iterated result. * * @param it The iterator. - * @return The group id of the currently iterated result. + * @return The group ID of the currently iterated result. */ FLECS_API uint64_t ecs_iter_get_group( const ecs_iter_t *it); -/** Returns whether current iterator result has changed. +/** Return whether the current iterator result has changed. * This operation must be used in combination with a query that supports change - * detection (e.g. is cached). The operation returns whether the currently + * detection (e.g., is cached). The operation returns whether the currently * iterated result has changed since the last time it was iterated by the query. * * Change detection works on a per-table basis. Changes to individual entities @@ -9238,12 +10573,12 @@ uint64_t ecs_iter_get_group( * * @param it The iterator. * @return True if the result changed, false if it didn't. -*/ + */ FLECS_API bool ecs_iter_changed( ecs_iter_t *it); -/** Convert iterator to string. +/** Convert an iterator to a string. * Prints the contents of an iterator to a string. Useful for debugging and/or * testing the output of an iterator. * @@ -9280,10 +10615,10 @@ ecs_iter_t ecs_page_iter( int32_t limit); /** Progress a paged iterator. - * Progresses an iterator created by ecs_page_iter(). + * Progress an iterator created by ecs_page_iter(). * * @param it The iterator. - * @return true if iterator has more results, false if not. + * @return True if the iterator has more results, false if not. */ FLECS_API bool ecs_page_next( @@ -9316,16 +10651,16 @@ ecs_iter_t ecs_worker_iter( int32_t count); /** Progress a worker iterator. - * Progresses an iterator created by ecs_worker_iter(). + * Progress an iterator created by ecs_worker_iter(). * * @param it The iterator. - * @return true if iterator has more results, false if not. + * @return True if the iterator has more results, false if not. */ FLECS_API bool ecs_worker_next( ecs_iter_t *it); -/** Get data for field. +/** Get data for a field. * This operation retrieves a pointer to an array of data that belongs to the * term in the query. The index refers to the location of the term in the query, * and starts counting from zero. @@ -9333,13 +10668,13 @@ bool ecs_worker_next( * For example, the query `"Position, Velocity"` will return the `Position` array * for index 0, and the `Velocity` array for index 1. * - * When the specified field is not owned by the entity this function returns a + * When the specified field is not owned by the entity, this function returns a * pointer instead of an array. This happens when the source of a field is not * the entity being iterated, such as a shared component (from a prefab), a * component from a parent, or another entity. The ecs_field_is_self() operation * can be used to test dynamically if a field is owned. * - * When a field contains a sparse component, use the ecs_field_at function. When + * When a field contains a sparse component, use the ecs_field_at() function. When * a field is guaranteed to be set and owned, the ecs_field_self() function can be * used. ecs_field_self() has slightly better performance, and provides stricter * validity checking. @@ -9354,7 +10689,7 @@ bool ecs_worker_next( * while (ecs_query_next(&it)) { * Position *p = ecs_field(&it, Position, 0); * Velocity *v = ecs_field(&it, Velocity, 1); - * for (int32_t i = 0; i < it->count; i ++) { + * for (int32_t i = 0; i < it.count; i ++) { * p[i].x += v[i].x; * p[i].y += v[i].y; * } @@ -9372,25 +10707,26 @@ void* ecs_field_w_size( size_t size, int8_t index); -/** Get data for field at specified row. - * This operation should be used instead of ecs_field_w_size for sparse +/** Get data for a field at a specified row. + * This operation should be used instead of ecs_field_w_size() for sparse * component fields. This operation should be called for each returned row in a - * result. In the following example the Velocity component is sparse: + * result. In the following example, the Velocity component is sparse: * * @code * while (ecs_query_next(&it)) { * Position *p = ecs_field(&it, Position, 0); - * for (int32_t i = 0; i < it->count; i ++) { - * Velocity *v = ecs_field_at(&it, Velocity, 1); + * for (int32_t i = 0; i < it.count; i ++) { + * Velocity *v = ecs_field_at(&it, Velocity, 1, i); * p[i].x += v->x; * p[i].y += v->y; * } * } * @endcode * - * @param it the iterator. + * @param it The iterator. * @param size The size of the field type. * @param index The index of the field. + * @param row The row to get data for. * @return A pointer to the data of the field. */ FLECS_API @@ -9400,35 +10736,35 @@ void* ecs_field_at_w_size( int8_t index, int32_t row); -/** Test whether the field is readonly. - * This operation returns whether the field is readonly. Readonly fields are +/** Test whether the field is read-only. + * This operation returns whether the field is read-only. Read-only fields are * annotated with [in], or are added as a const type in the C++ API. * * @param it The iterator. * @param index The index of the field in the iterator. - * @return Whether the field is readonly. + * @return Whether the field is read-only. */ FLECS_API bool ecs_field_is_readonly( const ecs_iter_t *it, int8_t index); -/** Test whether the field is writeonly. - * This operation returns whether this is a writeonly field. Writeonly terms are +/** Test whether the field is write-only. + * This operation returns whether this is a write-only field. Write-only terms are * annotated with [out]. * - * Serializers are not required to serialize the values of a writeonly field. + * Serializers are not required to serialize the values of a write-only field. * * @param it The iterator. * @param index The index of the field in the iterator. - * @return Whether the field is writeonly. + * @return Whether the field is write-only. */ FLECS_API bool ecs_field_is_writeonly( const ecs_iter_t *it, int8_t index); -/** Test whether field is set. +/** Test whether a field is set. * * @param it The iterator. * @param index The index of the field in the iterator. @@ -9439,18 +10775,18 @@ bool ecs_field_is_set( const ecs_iter_t *it, int8_t index); -/** Return id matched for field. +/** Return the ID matched for a field. * * @param it The iterator. * @param index The index of the field in the iterator. - * @return The id matched for the field. + * @return The ID matched for the field. */ FLECS_API ecs_id_t ecs_field_id( const ecs_iter_t *it, int8_t index); -/** Return index of matched table column. +/** Return the index of a matched table column. * This function only returns column indices for fields that have been matched * on the $this variable. Fields matched on other tables will return -1. * @@ -9463,7 +10799,7 @@ int32_t ecs_field_column( const ecs_iter_t *it, int8_t index); -/** Return field source. +/** Return the field source. * The field source is the entity on which the field was matched. * * @param it The iterator. @@ -9475,8 +10811,8 @@ ecs_entity_t ecs_field_src( const ecs_iter_t *it, int8_t index); -/** Return field type size. - * Return type size of the field. Returns 0 if the field has no data. +/** Return the field type size. + * Returns the type size of the field. Returns 0 if the field has no data. * * @param it The iterator. * @param index The index of the field in the iterator. @@ -9514,8 +10850,8 @@ bool ecs_field_is_self( * @{ */ -/** Get type for table. - * The table type is a vector that contains all component, tag and pair ids. +/** Get the type for a table. + * The table type is a vector that contains all component, tag, and pair IDs. * * @param table The table. * @return The type of the table. @@ -9524,7 +10860,7 @@ FLECS_API const ecs_type_t* ecs_table_get_type( const ecs_table_t *table); -/** Get type index for component. +/** Get the type index for a component. * This operation returns the index for a component in the table's type. * * @param world The world. @@ -9540,14 +10876,14 @@ int32_t ecs_table_get_type_index( const ecs_table_t *table, ecs_id_t component); -/** Get column index for component. +/** Get the column index for a component. * This operation returns the column index for a component in the table's type. * If the component doesn't have data (it is a tag), the function will return -1. * * @param world The world. * @param table The table. * @param component The component. - * @return The column index of the id, or -1 if not found/not a component. + * @return The column index of the component ID, or -1 if not found or not a component. */ FLECS_API int32_t ecs_table_get_column_index( @@ -9555,7 +10891,7 @@ int32_t ecs_table_get_column_index( const ecs_table_t *table, ecs_id_t component); -/** Return number of columns in table. +/** Return the number of columns in a table. * Similar to `ecs_table_get_type(table)->count`, except that the column count * only counts the number of components in a table. * @@ -9566,7 +10902,7 @@ FLECS_API int32_t ecs_table_column_count( const ecs_table_t *table); -/** Convert type index to column index. +/** Convert a type index to a column index. * Tables have an array of columns for each component in the table. This array * does not include elements for tags, which means that the index for a * component in the table type is not necessarily the same as the index in the @@ -9584,7 +10920,7 @@ int32_t ecs_table_type_to_column_index( const ecs_table_t *table, int32_t index); -/** Convert column index to type index. +/** Convert a column index to a type index. * Same as ecs_table_type_to_column_index(), but converts from an index in the * column array to an index in the table type. * @@ -9597,7 +10933,7 @@ int32_t ecs_table_column_to_type_index( const ecs_table_t *table, int32_t index); -/** Get column from table by column index. +/** Get a column from a table by column index. * This operation returns the component array for the provided index. * * @param table The table. @@ -9611,14 +10947,14 @@ void* ecs_table_get_column( int32_t index, int32_t offset); -/** Get column from table by component. +/** Get a column from a table by component. * This operation returns the component array for the provided component. * * @param world The world. * @param table The table. * @param component The component for the column. * @param offset The index of the first row to return (0 for entire column). - * @return The component array, or NULL if the index is not a component. + * @return The component array, or NULL if the component is not found. */ FLECS_API void* ecs_table_get_id( @@ -9627,7 +10963,7 @@ void* ecs_table_get_id( ecs_id_t component, int32_t offset); -/** Get column size from table. +/** Get the column size from a table. * This operation returns the component size for the provided index. * * @param table The table. @@ -9639,7 +10975,7 @@ size_t ecs_table_get_column_size( const ecs_table_t *table, int32_t index); -/** Returns the number of entities in the table. +/** Return the number of entities in the table. * This operation returns the number of entities in the table. * * @param table The table. @@ -9649,7 +10985,7 @@ FLECS_API int32_t ecs_table_count( const ecs_table_t *table); -/** Returns allocated size of table. +/** Return the allocated size of the table. * This operation returns the number of elements allocated in the table * per column. * @@ -9660,23 +10996,23 @@ FLECS_API int32_t ecs_table_size( const ecs_table_t *table); -/** Returns array with entity ids for table. +/** Return the array with entity IDs for the table. * The size of the returned array is the result of ecs_table_count(). * * @param table The table. - * @return Array with entity ids for table. + * @return The array with entity IDs for the table. */ FLECS_API const ecs_entity_t* ecs_table_entities( const ecs_table_t *table); -/** Test if table has component. +/** Test if a table has a component. * Same as `ecs_table_get_type_index(world, table, component) != -1`. * * @param world The world. * @param table The table. * @param component The component. - * @return True if the table has the id, false if the table doesn't. + * @return True if the table has the component ID, false if the table doesn't. * * @see ecs_table_get_type_index() */ @@ -9686,7 +11022,7 @@ bool ecs_table_has_id( const ecs_table_t *table, ecs_id_t component); -/** Get relationship target for table. +/** Get the relationship target for a table. * * @param world The world. * @param table The table. @@ -9703,9 +11039,9 @@ ecs_entity_t ecs_table_get_target( ecs_entity_t relationship, int32_t index); -/** Return depth for table in tree for relationship rel. +/** Return the depth for a table in the tree for the specified relationship. * Depth is determined by counting the number of targets encountered while - * traversing up the relationship tree for rel. Only acyclic relationships are + * traversing up the relationship tree. Only acyclic relationships are * supported. * * @param world The world. @@ -9719,14 +11055,14 @@ int32_t ecs_table_get_depth( const ecs_table_t *table, ecs_entity_t rel); -/** Get table that has all components of current table plus the specified id. - * If the provided table already has the provided id, the operation will return +/** Get the table that has all components of the current table plus the specified ID. + * If the provided table already has the provided ID, the operation will return * the provided table. * * @param world The world. * @param table The table. * @param component The component to add. - * @result The resulting table. + * @return The resulting table. */ FLECS_API ecs_table_t* ecs_table_add_id( @@ -9734,15 +11070,15 @@ ecs_table_t* ecs_table_add_id( ecs_table_t *table, ecs_id_t component); -/** Find table from id array. +/** Find a table from an ID array. * This operation finds or creates a table with the specified array of - * (component) ids. The ids in the array must be sorted, and it may not contain + * (component) IDs. The IDs in the array must be sorted, and it may not contain * duplicate elements. * * @param world The world. - * @param ids The id array. - * @param id_count The number of elements in the id array. - * @return The table with the specified (component) ids. + * @param ids The ID array. + * @param id_count The number of elements in the ID array. + * @return The table with the specified (component) IDs. */ FLECS_API ecs_table_t* ecs_table_find( @@ -9750,14 +11086,14 @@ ecs_table_t* ecs_table_find( const ecs_id_t *ids, int32_t id_count); -/** Get table that has all components of current table minus the specified component. +/** Get the table that has all components of the current table minus the specified component. * If the provided table doesn't have the provided component, the operation will * return the provided table. * * @param world The world. * @param table The table. * @param component The component to remove. - * @result The resulting table. + * @return The resulting table. */ FLECS_API ecs_table_t* ecs_table_remove_id( @@ -9796,8 +11132,8 @@ void ecs_table_unlock( ecs_world_t *world, ecs_table_t *table); -/** Test table for flags. - * Test if table has all of the provided flags. See +/** Test a table for flags. + * Test if a table has all of the provided flags. See * include/flecs/private/api_flags.h for a list of table flags that can be used * with this function. * @@ -9810,8 +11146,8 @@ bool ecs_table_has_flags( ecs_table_t *table, ecs_flags32_t flags); -/** Check if table has traversable entities. - * Traversable entities are entities that are used as target in a pair with a +/** Check if a table has traversable entities. + * Traversable entities are entities that are used as a target in a pair with a * relationship that has the Traversable trait. * * @param table The table. @@ -9821,13 +11157,15 @@ FLECS_API bool ecs_table_has_traversable( const ecs_table_t *table); -/** Swaps two elements inside the table. This is useful for implementing custom +/** Swap two elements inside the table. + * This is useful for implementing custom * table sorting algorithms. - * @param world The world - * @param table The table to swap elements in - * @param row_1 Table element to swap with row_2 - * @param row_2 Table element to swap with row_1 -*/ + * + * @param world The world. + * @param table The table to swap elements in. + * @param row_1 The table element to swap with row_2. + * @param row_2 The table element to swap with row_1. + */ FLECS_API void ecs_table_swap_rows( ecs_world_t* world, @@ -9835,26 +11173,28 @@ void ecs_table_swap_rows( int32_t row_1, int32_t row_2); -/** Commit (move) entity to a table. +/** Commit (move) an entity to a table. * This operation moves an entity from its current table to the specified * table. This may cause the following actions: - * - Ctor for each component in the target table - * - Move for each overlapping component + * - Ctor for each component in the target table. + * - Move for each overlapping component. * - Dtor for each component in the source table. - * - `OnAdd` triggers for non-overlapping components in the target table - * - `OnRemove` triggers for non-overlapping components in the source table. + * - `OnAdd` observers for non-overlapping components in the target table. + * - `OnRemove` observers for non-overlapping components in the source table. * - * This operation is a faster than adding/removing components individually. + * This operation is faster than adding or removing components individually. * * The application must explicitly provide the difference in components between - * tables as the added/removed parameters. This can usually be derived directly + * tables as the added and removed parameters. This can usually be derived directly * from the result of ecs_table_add_id() and ecs_table_remove_id(). These arrays are - * required to properly execute `OnAdd`/`OnRemove` triggers. + * required to properly execute `OnAdd` and `OnRemove` observers. * * @param world The world. * @param entity The entity to commit. * @param record The entity's record (optional, providing it saves a lookup). * @param table The table to commit the entity to. + * @param added The components added to the entity. + * @param removed The components removed from the entity. * @return True if the entity got moved, false otherwise. */ FLECS_API @@ -9867,21 +11207,21 @@ bool ecs_commit( const ecs_type_t *removed); -/** Search for component in table type. - * This operation returns the index of first occurrence of the component in the - * table type. The component may be a pair or wildcard. +/** Search for a component in a table type. + * This operation returns the index of the first occurrence of the component in the + * table type. The component may be a pair or a wildcard. * * When component_out is provided, the function will assign it with the found * component. The found component may be different from the provided component * if it is a wildcard. * - * This is a constant time operation. + * This is a constant-time operation. * * @param world The world. * @param table The table. * @param component The component to search for. * @param component_out If provided, it will be set to the found component (optional). - * @return The index of the id in the table type. + * @return The index of the ID in the table type. * * @see ecs_search_offset() * @see ecs_search_relation() @@ -9893,7 +11233,7 @@ int32_t ecs_search( ecs_id_t component, ecs_id_t *component_out); -/** Search for component in table type starting from an offset. +/** Search for a component in a table type starting from an offset. * This operation is the same as ecs_search(), but starts searching from an offset * in the table type. * @@ -9902,28 +11242,28 @@ int32_t ecs_search( * * @code * int32_t index = -1; - * while ((index = ecs_search_offset(world, table, offset, id, NULL))) { + * while ((index = ecs_search_offset(world, table, index + 1, id, NULL)) != -1) { * // do stuff * } * @endcode * - * Depending on how the operation is used it is either linear or constant time. - * When the id has the form `(id)` or `(rel, *)` and the operation is invoked as + * Depending on how the operation is used, it is either linear or constant time. + * When the ID has the form `(id)` or `(rel, *)` and the operation is invoked as * in the above example, it is guaranteed to be constant time. * - * If the provided component has the form `(*, tgt)` the operation takes linear - * time. The reason for this is that ids for an target are not packed together, - * as they are sorted relationship first. + * If the provided component has the form `(*, tgt)`, the operation takes linear + * time. The reason for this is that IDs for a target are not packed together, + * as they are sorted relationship-first. * - * If the component at the offset does not match the provided id, the operation - * will do a linear search to find a matching id. + * If the component at the offset does not match the provided ID, the operation + * will do a linear search to find a matching ID. * * @param world The world. * @param table The table. - * @param offset Offset from where to start searching. + * @param offset The offset from where to start searching. * @param component The component to search for. * @param component_out If provided, it will be set to the found component (optional). - * @return The index of the id in the table type. + * @return The index of the ID in the table type. * * @see ecs_search() * @see ecs_search_relation() @@ -9936,7 +11276,7 @@ int32_t ecs_search_offset( ecs_id_t component, ecs_id_t *component_out); -/** Search for component/relationship id in table type starting from an offset. +/** Search for a component or relationship ID in a table type starting from an offset. * This operation is the same as ecs_search_offset(), but has the additional * capability of traversing relationships to find a component. For example, if * an application wants to find a component for either the provided table or a @@ -9948,30 +11288,29 @@ int32_t ecs_search_offset( * world, // the world * table, // the table * 0, // offset 0 - * ecs_id(Position), // the component id + * ecs_id(Position), // the component ID * EcsIsA, // the relationship to traverse - * 0, // start at depth 0 (the table itself) - * 0, // no depth limit + * EcsSelf|EcsUp, // search self and up * NULL, // (optional) entity on which component was found - * NULL, // see above - * NULL); // internal type with information about matched id + * NULL, // (optional) found component ID + * NULL); // internal type with information about matched ID * @endcode * - * The operation searches depth first. If a table type has 2 `IsA` relationships, the + * The operation searches depth-first. If a table type has 2 `IsA` relationships, the * operation will first search the `IsA` tree of the first relationship. * - * When choosing between ecs_search(), ecs_search_offset() and ecs_search_relation(), - * the simpler the function the better its performance. + * When choosing between ecs_search(), ecs_search_offset(), and ecs_search_relation(), + * the simpler the function, the better its performance. * * @param world The world. * @param table The table. - * @param offset Offset from where to start searching. + * @param offset The offset from where to start searching. * @param component The component to search for. * @param rel The relationship to traverse (optional). * @param flags Whether to search EcsSelf and/or EcsUp. - * @param subject_out If provided, it will be set to the matched entity. + * @param tgt_out If provided, it will be set to the matched entity. * @param component_out If provided, it will be set to the found component (optional). - * @param tr_out Internal datatype. + * @param tr_out The internal datatype. * @return The index of the component in the table type. * * @see ecs_search() @@ -9985,13 +11324,40 @@ int32_t ecs_search_relation( ecs_id_t component, ecs_entity_t rel, ecs_flags64_t flags, /* EcsSelf and/or EcsUp */ - ecs_entity_t *subject_out, + ecs_entity_t *tgt_out, ecs_id_t *component_out, struct ecs_table_record_t **tr_out); +/** Search for a component ID by following a relationship, starting from an entity. + * This operation is the same as ecs_search_relation(), but starts the search + * from an entity rather than a table. + * + * @param world The world. + * @param entity The entity from which to begin the search. + * @param id The component ID to search for. + * @param rel The relationship to follow. + * @param self If true, also search components on the entity itself. + * @param cr Optional component record for the component ID. + * @param tgt_out Out parameter for the target entity. + * @param id_out Out parameter for the found component ID. + * @param tr_out Out parameter for the table record. + * @return The index of the component ID in the entity's type, or -1 if not found. + */ +FLECS_API +int32_t ecs_search_relation_for_entity( + const ecs_world_t *world, + ecs_entity_t entity, + ecs_id_t id, + ecs_entity_t rel, + bool self, + ecs_component_record_t *cr, + ecs_entity_t *tgt_out, + ecs_id_t *id_out, + struct ecs_table_record_t **tr_out); + /** Remove all entities in a table. Does not deallocate table memory. * Retaining table memory can be efficient when planning - * to refill the table with operations like ecs_bulk_init + * to refill the table with operations like ecs_bulk_init(). * * @param world The world. * @param table The table to clear. @@ -10005,17 +11371,17 @@ void ecs_table_clear_entities( /** * @defgroup values Values - * Construct, destruct, copy and move dynamically created values. + * Construct, destruct, copy, and move dynamically created values. * * @{ */ -/** Construct a value in existing storage +/** Construct a value in existing storage. * * @param world The world. * @param type The type of the value to create. - * @param ptr Pointer to a value of type 'type' - * @return Zero if success, nonzero if failed. + * @param ptr A pointer to a value of type 'type'. + * @return Zero if successful, nonzero if failed. */ FLECS_API int ecs_value_init( @@ -10023,12 +11389,12 @@ int ecs_value_init( ecs_entity_t type, void *ptr); -/** Construct a value in existing storage +/** Construct a value in existing storage. * * @param world The world. * @param ti The type info of the type to create. - * @param ptr Pointer to a value of type 'type' - * @return Zero if success, nonzero if failed. + * @param ptr A pointer to a value of type 'type'. + * @return Zero if successful, nonzero if failed. */ FLECS_API int ecs_value_init_w_type_info( @@ -10036,45 +11402,45 @@ int ecs_value_init_w_type_info( const ecs_type_info_t *ti, void *ptr); -/** Construct a value in new storage +/** Construct a value in new storage. * * @param world The world. * @param type The type of the value to create. - * @return Pointer to type if success, NULL if failed. + * @return A pointer to the value if successful, NULL if failed. */ FLECS_API void* ecs_value_new( ecs_world_t *world, ecs_entity_t type); -/** Construct a value in new storage +/** Construct a value in new storage. * * @param world The world. * @param ti The type info of the type to create. - * @return Pointer to type if success, NULL if failed. + * @return A pointer to the value if successful, NULL if failed. */ void* ecs_value_new_w_type_info( ecs_world_t *world, const ecs_type_info_t *ti); -/** Destruct a value +/** Destruct a value. * * @param world The world. - * @param ti Type info of the value to destruct. - * @param ptr Pointer to constructed value of type 'type'. - * @return Zero if success, nonzero if failed. + * @param ti The type info of the value to destruct. + * @param ptr A pointer to a constructed value of type 'type'. + * @return Zero if successful, nonzero if failed. */ int ecs_value_fini_w_type_info( const ecs_world_t *world, const ecs_type_info_t *ti, void *ptr); -/** Destruct a value +/** Destruct a value. * * @param world The world. * @param type The type of the value to destruct. - * @param ptr Pointer to constructed value of type 'type'. - * @return Zero if success, nonzero if failed. + * @param ptr A pointer to a constructed value of type 'type'. + * @return Zero if successful, nonzero if failed. */ FLECS_API int ecs_value_fini( @@ -10082,12 +11448,12 @@ int ecs_value_fini( ecs_entity_t type, void* ptr); -/** Destruct a value, free storage +/** Destruct a value and free storage. * * @param world The world. * @param type The type of the value to destruct. * @param ptr A pointer to the value. - * @return Zero if success, nonzero if failed. + * @return Zero if successful, nonzero if failed. */ FLECS_API int ecs_value_free( @@ -10095,13 +11461,13 @@ int ecs_value_free( ecs_entity_t type, void* ptr); -/** Copy value. +/** Copy a value. * * @param world The world. - * @param ti Type info of the value to copy. - * @param dst Pointer to the storage to copy to. - * @param src Pointer to the value to copy. - * @return Zero if success, nonzero if failed. + * @param ti The type info of the value to copy. + * @param dst A pointer to the storage to copy to. + * @param src A pointer to the value to copy. + * @return Zero if successful, nonzero if failed. */ FLECS_API int ecs_value_copy_w_type_info( @@ -10110,13 +11476,13 @@ int ecs_value_copy_w_type_info( void* dst, const void *src); -/** Copy value. +/** Copy a value. * * @param world The world. * @param type The type of the value to copy. - * @param dst Pointer to the storage to copy to. - * @param src Pointer to the value to copy. - * @return Zero if success, nonzero if failed. + * @param dst A pointer to the storage to copy to. + * @param src A pointer to the value to copy. + * @return Zero if successful, nonzero if failed. */ FLECS_API int ecs_value_copy( @@ -10125,13 +11491,13 @@ int ecs_value_copy( void* dst, const void *src); -/** Move value. +/** Move a value. * * @param world The world. - * @param ti Type info of the value to move. - * @param dst Pointer to the storage to move to. - * @param src Pointer to the value to move. - * @return Zero if success, nonzero if failed. + * @param ti The type info of the value to move. + * @param dst A pointer to the storage to move to. + * @param src A pointer to the value to move. + * @return Zero if successful, nonzero if failed. */ int ecs_value_move_w_type_info( const ecs_world_t *world, @@ -10139,13 +11505,13 @@ int ecs_value_move_w_type_info( void* dst, void *src); -/** Move value. +/** Move a value. * * @param world The world. * @param type The type of the value to move. - * @param dst Pointer to the storage to move to. - * @param src Pointer to the value to move. - * @return Zero if success, nonzero if failed. + * @param dst A pointer to the storage to move to. + * @param src A pointer to the value to move. + * @return Zero if successful, nonzero if failed. */ int ecs_value_move( const ecs_world_t *world, @@ -10153,13 +11519,13 @@ int ecs_value_move( void* dst, void *src); -/** Move construct value. +/** Move-construct a value. * * @param world The world. - * @param ti Type info of the value to move. - * @param dst Pointer to the storage to move to. - * @param src Pointer to the value to move. - * @return Zero if success, nonzero if failed. + * @param ti The type info of the value to move. + * @param dst A pointer to the storage to move to. + * @param src A pointer to the value to move. + * @return Zero if successful, nonzero if failed. */ int ecs_value_move_ctor_w_type_info( const ecs_world_t *world, @@ -10167,13 +11533,13 @@ int ecs_value_move_ctor_w_type_info( void* dst, void *src); -/** Move construct value. +/** Move-construct a value. * * @param world The world. * @param type The type of the value to move. - * @param dst Pointer to the storage to move to. - * @param src Pointer to the value to move. - * @return Zero if success, nonzero if failed. + * @param dst A pointer to the storage to move to. + * @param src A pointer to the value to move. + * @return Zero if successful, nonzero if failed. */ int ecs_value_move_ctor( const ecs_world_t *world, @@ -10205,26 +11571,26 @@ int ecs_value_move_ctor( /** * @defgroup flecs_c Macro API * @ingroup c - * Convenience macro's for C API + * Convenience macros for C API. * * @{ */ /** - * @defgroup flecs_c_creation Creation macro's - * Convenience macro's for creating entities, components and observers + * @defgroup flecs_c_creation Creation macros + * Convenience macros for creating entities, components, and observers. * * @{ */ -/* Use for declaring entity, tag, prefab / any other entity identifier */ +/** Forward declare an entity, tag, prefab, or any other entity identifier. */ #define ECS_DECLARE(id)\ ecs_entity_t id, ecs_id(id) /** Forward declare an entity. */ #define ECS_ENTITY_DECLARE ECS_DECLARE -/** Define a forward declared entity. +/** Define a forward-declared entity. * * Example: * @@ -10245,7 +11611,7 @@ int ecs_value_move_ctor( (void)id_; \ (void)ecs_id(id_) -/** Declare & define an entity. +/** Declare and define an entity. * * Example: * @@ -10261,7 +11627,7 @@ int ecs_value_move_ctor( /** Forward declare a tag. */ #define ECS_TAG_DECLARE ECS_DECLARE -/** Define a forward declared tag. +/** Define a forward-declared tag. * * Example: * @@ -10271,7 +11637,7 @@ int ecs_value_move_ctor( */ #define ECS_TAG_DEFINE(world, id) ECS_ENTITY_DEFINE(world, id, 0) -/** Declare & define a tag. +/** Declare and define a tag. * * Example: * @@ -10284,7 +11650,7 @@ int ecs_value_move_ctor( /** Forward declare a prefab. */ #define ECS_PREFAB_DECLARE ECS_DECLARE -/** Define a forward declared prefab. +/** Define a forward-declared prefab. * * Example: * @@ -10294,7 +11660,7 @@ int ecs_value_move_ctor( */ #define ECS_PREFAB_DEFINE(world, id, ...) ECS_ENTITY_DEFINE(world, id, Prefab, __VA_ARGS__) -/** Declare & define a prefab. +/** Declare and define a prefab. * * Example: * @@ -10307,7 +11673,7 @@ int ecs_value_move_ctor( /** Forward declare a component. */ #define ECS_COMPONENT_DECLARE(id) ecs_entity_t ecs_id(id) -/** Define a forward declared component. +/** Define a forward-declared component. * * Example: * @@ -10330,7 +11696,7 @@ int ecs_value_move_ctor( }\ ecs_assert(ecs_id(id_) != 0, ECS_INVALID_PARAMETER, "failed to create component %s", #id_) -/** Declare & define a component. +/** Declare and define a component. * * Example: * @@ -10343,10 +11709,10 @@ int ecs_value_move_ctor( ECS_COMPONENT_DEFINE(world, id);\ (void)ecs_id(id) -/* Forward declare an observer. */ +/** Forward declare an observer. */ #define ECS_OBSERVER_DECLARE(id) ecs_entity_t ecs_id(id) -/** Define a forward declared observer. +/** Define a forward-declared observer. * * Example: * @@ -10368,7 +11734,7 @@ int ecs_value_move_ctor( ecs_assert(ecs_id(id_) != 0, ECS_INVALID_PARAMETER, "failed to create observer %s", #id_);\ } -/** Declare & define an observer. +/** Declare and define an observer. * * Example: * @@ -10383,10 +11749,10 @@ int ecs_value_move_ctor( (void)ecs_id(id);\ (void)id -/* Forward declare a query. */ +/** Forward declare a query. */ #define ECS_QUERY_DECLARE(name) ecs_query_t* name -/** Define a forward declared query. +/** Define a forward-declared query. * * Example: * @@ -10405,7 +11771,7 @@ int ecs_value_move_ctor( ecs_assert(name_ != NULL, ECS_INVALID_PARAMETER, "failed to create query %s", #name_);\ } -/** Declare & define a query. +/** Declare and define a query. * * Example: * @@ -10445,10 +11811,10 @@ int ecs_value_move_ctor( #define ecs_component(world, ...)\ ecs_component_init(world, &(ecs_component_desc_t) __VA_ARGS__ ) -/** Shorthand for creating a query with ecs_query_cache_init. +/** Shorthand for creating a query with ecs_query_init(). * * Example: - * + * * @code * ecs_query(world, { * .terms = {{ ecs_id(Position) }} @@ -10476,8 +11842,8 @@ int ecs_value_move_ctor( /** @} */ /** - * @defgroup flecs_c_type_safe Type Safe API - * Macro's that wrap around core functions to provide a "type safe" API in C + * @defgroup flecs_c_type_safe Type-Safe API + * Macros that wrap around core functions to provide a "type-safe" API in C. * * @{ */ @@ -10492,11 +11858,14 @@ int ecs_value_move_ctor( * @{ */ +/** Create a new entity with a component. */ #define ecs_new_w(world, T) ecs_new_w_id(world, ecs_id(T)) +/** Create a new entity with a pair. */ #define ecs_new_w_pair(world, first, second)\ ecs_new_w_id(world, ecs_pair(first, second)) +/** Bulk create entities with a component. */ #define ecs_bulk_new(world, component, count)\ ecs_bulk_new_w_id(world, ecs_id(component), count) @@ -10507,23 +11876,27 @@ int ecs_value_move_ctor( * @{ */ +/** Add a component to an entity. */ #define ecs_add(world, entity, T)\ ecs_add_id(world, entity, ecs_id(T)) +/** Add a pair to an entity. */ #define ecs_add_pair(world, subject, first, second)\ ecs_add_id(world, subject, ecs_pair(first, second)) - +/** Remove a component from an entity. */ #define ecs_remove(world, entity, T)\ ecs_remove_id(world, entity, ecs_id(T)) +/** Remove a pair from an entity. */ #define ecs_remove_pair(world, subject, first, second)\ ecs_remove_id(world, subject, ecs_pair(first, second)) - +/** Auto-override a component on an entity. */ #define ecs_auto_override(world, entity, T)\ ecs_auto_override_id(world, entity, ecs_id(T)) +/** Auto-override a pair on an entity. */ #define ecs_auto_override_pair(world, subject, first, second)\ ecs_auto_override_id(world, subject, ecs_pair(first, second)) @@ -10534,120 +11907,134 @@ int ecs_value_move_ctor( * @{ */ -/* insert */ +/** Insert a new entity with a list of component values. */ #define ecs_insert(world, ...)\ ecs_entity(world, { .set = ecs_values(__VA_ARGS__)}) -/* set */ - +/** Set a component using a pointer. */ #define ecs_set_ptr(world, entity, component, ptr)\ ecs_set_id(world, entity, ecs_id(component), sizeof(component), ptr) +/** Set a component value. */ #define ecs_set(world, entity, component, ...)\ ecs_set_id(world, entity, ecs_id(component), sizeof(component), &(component)__VA_ARGS__) +/** Set the first element of a pair. */ #define ecs_set_pair(world, subject, First, second, ...)\ ecs_set_id(world, subject,\ ecs_pair(ecs_id(First), second),\ sizeof(First), &(First)__VA_ARGS__) +/** Set the second element of a pair. */ #define ecs_set_pair_second(world, subject, first, Second, ...)\ ecs_set_id(world, subject,\ ecs_pair(first, ecs_id(Second)),\ sizeof(Second), &(Second)__VA_ARGS__) +/** Set a component with auto-override. */ #define ecs_set_override(world, entity, T, ...)\ ecs_add_id(world, entity, ECS_AUTO_OVERRIDE | ecs_id(T));\ ecs_set(world, entity, T, __VA_ARGS__) -/* emplace */ - +/** Emplace a component. */ #define ecs_emplace(world, entity, T, is_new)\ (ECS_CAST(T*, ecs_emplace_id(world, entity, ecs_id(T), sizeof(T), is_new))) +/** Emplace the first element of a pair. */ #define ecs_emplace_pair(world, entity, First, second, is_new)\ (ECS_CAST(First*, ecs_emplace_id(world, entity, ecs_pair_t(First, second), sizeof(First), is_new))) -/* get */ - +/** Get a component. */ #define ecs_get(world, entity, T)\ (ECS_CAST(const T*, ecs_get_id(world, entity, ecs_id(T)))) +/** Get the first element of a pair. */ #define ecs_get_pair(world, subject, First, second)\ (ECS_CAST(const First*, ecs_get_id(world, subject,\ ecs_pair(ecs_id(First), second)))) +/** Get the second element of a pair. */ #define ecs_get_pair_second(world, subject, first, Second)\ (ECS_CAST(const Second*, ecs_get_id(world, subject,\ ecs_pair(first, ecs_id(Second))))) -/* get_mut */ - +/** Get a mutable pointer to a component. */ #define ecs_get_mut(world, entity, T)\ (ECS_CAST(T*, ecs_get_mut_id(world, entity, ecs_id(T)))) +/** Get a mutable pointer to the first element of a pair. */ #define ecs_get_mut_pair(world, subject, First, second)\ (ECS_CAST(First*, ecs_get_mut_id(world, subject,\ ecs_pair(ecs_id(First), second)))) +/** Get a mutable pointer to the second element of a pair. */ #define ecs_get_mut_pair_second(world, subject, first, Second)\ (ECS_CAST(Second*, ecs_get_mut_id(world, subject,\ ecs_pair(first, ecs_id(Second))))) +/** Get a mutable pointer to a component. */ #define ecs_get_mut(world, entity, T)\ (ECS_CAST(T*, ecs_get_mut_id(world, entity, ecs_id(T)))) -/* ensure */ - +/** Ensure entity has a component, return mutable pointer. */ #define ecs_ensure(world, entity, T)\ (ECS_CAST(T*, ecs_ensure_id(world, entity, ecs_id(T), sizeof(T)))) +/** Ensure entity has the first element of a pair, return mutable pointer. */ #define ecs_ensure_pair(world, subject, First, second)\ (ECS_CAST(First*, ecs_ensure_id(world, subject,\ ecs_pair(ecs_id(First), second), sizeof(First)))) +/** Ensure entity has the second element of a pair, return mutable pointer. */ #define ecs_ensure_pair_second(world, subject, first, Second)\ (ECS_CAST(Second*, ecs_ensure_id(world, subject,\ ecs_pair(first, ecs_id(Second)), sizeof(Second)))) -/* modified */ - +/** Signal that a component has been modified. */ #define ecs_modified(world, entity, component)\ ecs_modified_id(world, entity, ecs_id(component)) +/** Signal that a pair has been modified. */ #define ecs_modified_pair(world, subject, first, second)\ ecs_modified_id(world, subject, ecs_pair(first, second)) -/* record */ - +/** Get a component from a record. */ #define ecs_record_get(world, record, T)\ (ECS_CAST(const T*, ecs_record_get_id(world, record, ecs_id(T)))) +/** Test if a record has a component. */ #define ecs_record_has(world, record, T)\ (ecs_record_has_id(world, record, ecs_id(T))) +/** Get the first element of a pair from a record. */ #define ecs_record_get_pair(world, record, First, second)\ (ECS_CAST(const First*, ecs_record_get_id(world, record, \ ecs_pair(ecs_id(First), second)))) +/** Get the second element of a pair from a record. */ #define ecs_record_get_pair_second(world, record, first, Second)\ (ECS_CAST(const Second*, ecs_record_get_id(world, record,\ ecs_pair(first, ecs_id(Second))))) +/** Ensure a component on a record, return mutable pointer. */ #define ecs_record_ensure(world, record, T)\ (ECS_CAST(T*, ecs_record_ensure_id(world, record, ecs_id(T)))) +/** Ensure the first element of a pair on a record, return mutable pointer. */ #define ecs_record_ensure_pair(world, record, First, second)\ (ECS_CAST(First*, ecs_record_ensure_id(world, record, \ ecs_pair(ecs_id(First), second)))) +/** Ensure the second element of a pair on a record, return mutable pointer. */ #define ecs_record_ensure_pair_second(world, record, first, Second)\ (ECS_CAST(Second*, ecs_record_ensure_id(world, record,\ ecs_pair(first, ecs_id(Second))))) +/** Initialize a ref for a component. */ #define ecs_ref_init(world, entity, T)\ ecs_ref_init_id(world, entity, ecs_id(T)) +/** Get a component from a ref. */ #define ecs_ref_get(world, ref, T)\ (ECS_CAST(T*, ecs_ref_get_id(world, ref, ecs_id(T)))) @@ -10658,30 +12045,39 @@ int ecs_value_move_ctor( * @{ */ +/** Add a singleton component. */ #define ecs_singleton_add(world, comp)\ ecs_add(world, ecs_id(comp), comp) +/** Remove a singleton component. */ #define ecs_singleton_remove(world, comp)\ ecs_remove(world, ecs_id(comp), comp) +/** Get a singleton component. */ #define ecs_singleton_get(world, comp)\ ecs_get(world, ecs_id(comp), comp) +/** Get a mutable pointer to a singleton component. */ #define ecs_singleton_get_mut(world, comp)\ ecs_get_mut(world, ecs_id(comp), comp) +/** Set a singleton component using a pointer. */ #define ecs_singleton_set_ptr(world, comp, ptr)\ ecs_set_ptr(world, ecs_id(comp), comp, ptr) +/** Set a singleton component value. */ #define ecs_singleton_set(world, comp, ...)\ ecs_set(world, ecs_id(comp), comp, __VA_ARGS__) +/** Ensure a singleton component, return mutable pointer. */ #define ecs_singleton_ensure(world, comp)\ ecs_ensure(world, ecs_id(comp), comp) +/** Emplace a singleton component. */ #define ecs_singleton_emplace(world, comp, is_new)\ ecs_emplace(world, ecs_id(comp), comp, is_new) +/** Signal that a singleton component has been modified. */ #define ecs_singleton_modified(world, comp)\ ecs_modified(world, ecs_id(comp), comp) @@ -10692,28 +12088,36 @@ int ecs_value_move_ctor( * @{ */ +/** Test if an entity has a component. */ #define ecs_has(world, entity, T)\ ecs_has_id(world, entity, ecs_id(T)) +/** Test if an entity has a pair. */ #define ecs_has_pair(world, entity, first, second)\ ecs_has_id(world, entity, ecs_pair(first, second)) +/** Test if an entity owns a pair. */ #define ecs_owns_pair(world, entity, first, second)\ ecs_owns_id(world, entity, ecs_pair(first, second)) +/** Test if an entity owns a component. */ #define ecs_owns(world, entity, T)\ ecs_owns_id(world, entity, ecs_id(T)) +/** Test if an entity shares a component. */ #define ecs_shares_id(world, entity, id)\ (ecs_search_relation(world, ecs_get_table(world, entity), 0, ecs_id(id), \ EcsIsA, 1, 0, 0, 0, 0) != -1) +/** Test if an entity shares a pair. */ #define ecs_shares_pair(world, entity, first, second)\ (ecs_shares_id(world, entity, ecs_pair(first, second))) +/** Test if an entity shares a component. */ #define ecs_shares(world, entity, T)\ (ecs_shares_id(world, entity, ecs_id(T))) +/** Get the target for a relationship. */ #define ecs_get_target_for(world, entity, rel, T)\ ecs_get_target_for_id(world, entity, rel, ecs_id(T)) @@ -10724,15 +12128,19 @@ int ecs_value_move_ctor( * @{ */ +/** Enable or disable a component. */ #define ecs_enable_component(world, entity, T, enable)\ ecs_enable_id(world, entity, ecs_id(T), enable) +/** Test if a component is enabled. */ #define ecs_is_enabled(world, entity, T)\ ecs_is_enabled_id(world, entity, ecs_id(T)) +/** Enable or disable a pair. */ #define ecs_enable_pair(world, entity, First, second, enable)\ ecs_enable_id(world, entity, ecs_pair(ecs_id(First), second), enable) +/** Test if a pair is enabled. */ #define ecs_is_enabled_pair(world, entity, First, second)\ ecs_is_enabled_id(world, entity, ecs_pair(ecs_id(First), second)) @@ -10743,24 +12151,31 @@ int ecs_value_move_ctor( * @{ */ +/** Lookup an entity from a parent. */ #define ecs_lookup_from(world, parent, path)\ ecs_lookup_path_w_sep(world, parent, path, ".", NULL, true) +/** Get path from a parent. */ #define ecs_get_path_from(world, parent, child)\ ecs_get_path_w_sep(world, parent, child, ".", NULL) +/** Get path from root. */ #define ecs_get_path(world, child)\ ecs_get_path_w_sep(world, 0, child, ".", NULL) +/** Get path from root, write to buffer. */ #define ecs_get_path_buf(world, child, buf)\ ecs_get_path_w_sep_buf(world, 0, child, ".", NULL, buf, false) +/** Create a new entity from a path. */ #define ecs_new_from_path(world, parent, path)\ ecs_new_from_path_w_sep(world, parent, path, ".", NULL) +/** Add a path to an entity. */ #define ecs_add_path(world, entity, parent, path)\ ecs_add_path_w_sep(world, entity, parent, path, ".", NULL) +/** Add a full path to an entity. */ #define ecs_add_fullpath(world, entity, path)\ ecs_add_path_w_sep(world, entity, 0, path, ".", NULL) @@ -10773,9 +12188,11 @@ int ecs_value_move_ctor( * @{ */ +/** Set component hooks. */ #define ecs_set_hooks(world, T, ...)\ ecs_set_hooks_id(world, ecs_id(T), &(ecs_type_hooks_t)__VA_ARGS__) +/** Get component hooks. */ #define ecs_get_hooks(world, T)\ ecs_get_hooks_id(world, ecs_id(T)); @@ -10819,36 +12236,45 @@ int ecs_value_move_ctor( #define ECS_MOVE(type, dst_var, src_var, ...)\ ECS_MOVE_IMPL(type, dst_var, src_var, __VA_ARGS__) -/** Declare component hooks. +/** Declare an on_add hook. * Example: * * @code - * ECS_ON_SET(MyType, ptr, { printf("%d\n", ptr->value); }); + * ECS_ON_ADD(MyType, ptr, { printf("added\n"); }); * @endcode */ #define ECS_ON_ADD(type, ptr, ...)\ ECS_HOOK_IMPL(type, ecs_on_add(type), ptr, __VA_ARGS__) +/** Declare an on_remove hook. */ #define ECS_ON_REMOVE(type, ptr, ...)\ ECS_HOOK_IMPL(type, ecs_on_remove(type), ptr, __VA_ARGS__) +/** Declare an on_set hook. */ #define ECS_ON_SET(type, ptr, ...)\ ECS_HOOK_IMPL(type, ecs_on_set(type), ptr, __VA_ARGS__) -/* Map from typename to function name of component lifecycle action */ +/** Map from typename to constructor function name. */ #define ecs_ctor(type) type##_ctor +/** Map from typename to destructor function name. */ #define ecs_dtor(type) type##_dtor +/** Map from typename to copy function name. */ #define ecs_copy(type) type##_copy +/** Map from typename to move function name. */ #define ecs_move(type) type##_move +/** Map from typename to on_set function name. */ #define ecs_on_set(type) type##_on_set +/** Map from typename to on_add function name. */ #define ecs_on_add(type) type##_on_add +/** Map from typename to on_remove function name. */ #define ecs_on_remove(type) type##_on_remove /** @} */ /** - * @defgroup flecs_c_ids Id API + * @defgroup flecs_c_ids ID API * @{ */ +/** Count entities with a component. */ #define ecs_count(world, type)\ ecs_count_id(world, ecs_id(type)) @@ -10859,12 +12285,15 @@ int ecs_value_move_ctor( * @{ */ +/** Get field data for a component. */ #define ecs_field(it, T, index)\ (ECS_CAST(T*, ecs_field_w_size(it, sizeof(T), index))) +/** Get field data for a self-owned component. */ #define ecs_field_self(it, T, index)\ (ECS_CAST(T*, ecs_field_self_w_size(it, sizeof(T), index))) +/** Get field data at a specific row. */ #define ecs_field_at(it, T, index, row)\ (ECS_CAST(T*, ecs_field_at_w_size(it, sizeof(T), index, row))) @@ -10875,12 +12304,15 @@ int ecs_value_move_ctor( * @{ */ +/** Get a component from a table at an offset. */ #define ecs_table_get(world, table, T, offset)\ (ECS_CAST(T*, ecs_table_get_id(world, table, ecs_id(T), offset))) +/** Get the first element of a pair from a table at an offset. */ #define ecs_table_get_pair(world, table, First, second, offset)\ (ECS_CAST(First*, ecs_table_get_id(world, table, ecs_pair(ecs_id(First), second), offset))) +/** Get the second element of a pair from a table at an offset. */ #define ecs_table_get_pair_second(world, table, first, Second, offset)\ (ECS_CAST(Second*, ecs_table_get_id(world, table, ecs_pair(first, ecs_id(Second)), offset))) @@ -10891,25 +12323,25 @@ int ecs_value_move_ctor( * @{ */ -/** Convenience macro for creating compound literal id array */ +/** Convenience macro for creating a compound literal ID array. */ #define ecs_ids(...) (ecs_id_t[]){ __VA_ARGS__, 0 } -/** Convenience macro for creating compound literal values array */ +/** Convenience macro for creating a compound literal values array. */ #define ecs_values(...) (ecs_value_t[]){ __VA_ARGS__, {0, 0}} -/** Convenience macro for creating compound literal value */ +/** Convenience macro for creating a compound literal value. */ #define ecs_value_ptr(T, ptr) ((ecs_value_t){ecs_id(T), ptr}) -/** Convenience macro for creating compound literal pair value */ -#define ecs_value_pair(R, t, ...) ((ecs_value_t){ecs_pair_t(R, t), &(R)__VA_ARGS__}) +/** Convenience macro for creating a compound literal pair value. */ +#define ecs_pair_value(R, t, ...) ((ecs_value_t){ecs_pair_t(R, t), &(R)__VA_ARGS__}) -/** Convenience macro for creating compound literal pair value */ -#define ecs_value_pair_2nd(r, T, ...) ((ecs_value_t){ecs_pair(r, ecs_id(T)), &(T)__VA_ARGS__}) +/** Convenience macro for creating a compound literal pair value. */ +#define ecs_pair_value_2nd(r, T, ...) ((ecs_value_t){ecs_pair(r, ecs_id(T)), &(T)__VA_ARGS__}) -/** Convenience macro for creating heap allocated value */ +/** Convenience macro for creating a heap-allocated value. */ #define ecs_value_new_t(world, T) ecs_value_new(world, ecs_id(T)) -/** Convenience macro for creating compound literal value literal */ +/** Convenience macro for creating a compound literal value literal. */ #define ecs_value(T, ...) ((ecs_value_t){ecs_id(T), &(T)__VA_ARGS__}) /** @} */ @@ -10918,17 +12350,19 @@ int ecs_value_move_ctor( /** * @defgroup flecs_c_table_sorting Table sorting - * Convenience macro's for sorting tables. + * Convenience macros for sorting tables. * * @{ */ +/** Declare a table sort function. */ #define ecs_sort_table(id) ecs_id(id##_sort_table) +/** Declare a comparison function. */ #define ecs_compare(id) ecs_id(id##_compare_fn) -/* Declare efficient table sorting operation that uses provided compare function. - * For best results use LTO or make the function body visible in the same compilation unit. - * Variadic arguments are prepended before generated functions, use it to declare static +/** Declare an efficient table sorting operation that uses the provided compare function. + * For best results, use LTO or make the function body visible in the same compilation unit. + * Variadic arguments are prepended before generated functions; use them to declare static * or exported functions. * Parameters of the comparison function: * ecs_entity_t e1, const void* ptr1, @@ -11008,9 +12442,9 @@ int ecs_value_move_ctor( op_name(world, table, entities, ptr, size, p + 1, hi, order_by); \ } -/* Declare efficient table sorting operation that uses default component comparison operator. - * For best results use LTO or make the comparison operator visible in the same compilation unit. - * Variadic arguments are prepended before generated functions, use it to declare static +/** Declare an efficient table sorting operation that uses the default component comparison operator. + * For best results, use LTO or make the comparison operator visible in the same compilation unit. + * Variadic arguments are prepended before generated functions; use them to declare static * or exported functions. * Example: * @@ -11022,7 +12456,7 @@ int ecs_value_move_ctor( #define ECS_SORT_TABLE(id, ...) \ ECS_SORT_TABLE_WITH_COMPARE(id, ecs_sort_table(id), ecs_compare(id), __VA_ARGS__) -/* Declare component comparison operations. +/** Declare component comparison operations. * Parameters: * ecs_entity_t e1, const void* ptr1, * ecs_entity_t e2, const void* ptr2 @@ -11041,18 +12475,25 @@ int ecs_value_move_ctor( /** * @defgroup flecs_c_misc Misc - * Misc convenience macro's. + * Misc convenience macros. * * @{ */ +/** Construct an IsA pair. */ #define ecs_isa(e) ecs_pair(EcsIsA, e) +/** Construct a ChildOf pair. */ #define ecs_childof(e) ecs_pair(EcsChildOf, e) +/** Construct a DependsOn pair. */ #define ecs_dependson(e) ecs_pair(EcsDependsOn, e) +/** Construct a With pair. */ #define ecs_with(e) ecs_pair(EcsWith, e) +/** Iterate entities with a component. */ #define ecs_each(world, id) ecs_each_id(world, ecs_id(id)) +/** Iterate entities with a pair. */ #define ecs_each_pair(world, r, t) ecs_each_id(world, ecs_pair(r, t)) +/** Iterate entities with a pair (type-safe first element). */ #define ecs_each_pair_t(world, R, t) ecs_each_id(world, ecs_pair(ecs_id(R), t)) /** @} */ @@ -11141,7 +12582,7 @@ int ecs_value_move_ctor( #undef FLECS_JOURNAL #endif -/* Always included, if disabled functions are replaced with dummy macros */ +/* Always included; if disabled, functions are replaced with dummy macros. */ /** * @file addons/log.h * @brief Logging addon. @@ -11150,21 +12591,21 @@ int ecs_value_move_ctor( * at various levels. When enabled, the logging addon can provide more detailed * information about the state of the ECS and any errors that may occur. * - * The logging addon can be disabled to reduce footprint of the library, but - * limits information logged to only file, line and error code. + * The logging addon can be disabled to reduce the footprint of the library, but + * limits information logged to only file, line, and error code. * - * When enabled the logging addon can be configured to exclude levels of tracing - * from the build to reduce the impact on performance. By default all debug - * tracing is enabled for debug builds, tracing is enabled at release builds. + * When enabled, the logging addon can be configured to exclude levels of tracing + * from the build to reduce the impact on performance. By default, all debug + * tracing is enabled for debug builds, tracing is enabled for release builds. * * Applications can change the logging level at runtime with ecs_log_set_level(), * but what is actually logged depends on what is compiled (when compiled * without debug tracing, setting the runtime level to debug won't have an * effect). * - * The logging addon uses the OS API log_ function for all tracing. + * The logging addon uses the OS API log_() function for all tracing. * - * Note that even when the logging addon is not enabled, its header/source must + * Note that even when the logging addon is not enabled, its header and source must * be included in a build. To prevent unused variable warnings in the code, some * API functions are included when the addon is disabled, but have empty bodies. */ @@ -11190,7 +12631,12 @@ extern "C" { //// Tracing //////////////////////////////////////////////////////////////////////////////// -/** Log message indicating an operation is deprecated. */ +/** Log message indicating an operation is deprecated. + * + * @param file The source file. + * @param line The source line. + * @param msg The deprecation message. + */ FLECS_API void ecs_deprecated_( const char *file, @@ -11229,7 +12675,11 @@ bool ecs_should_log(int32_t level); //// Error reporting //////////////////////////////////////////////////////////////////////////////// -/** Get description for error code */ +/** Get description for error code. + * + * @param error_code The error code. + * @return String describing the error code. + */ FLECS_API const char* ecs_strerror( int32_t error_code); @@ -11256,9 +12706,16 @@ const char* ecs_strerror( //////////////////////////////////////////////////////////////////////////////// -//// Logging functions (do nothing when logging is enabled) +//// Logging functions (do nothing when logging is disabled) //////////////////////////////////////////////////////////////////////////////// +/** Print at the provided log level. + * + * @param level The log level. + * @param file The source file. + * @param line The source line. + * @param fmt The format string. + */ FLECS_API void ecs_print_( int32_t level, @@ -11267,6 +12724,14 @@ void ecs_print_( const char *fmt, ...); +/** Print at the provided log level (va_list). + * + * @param level The log level. + * @param file The source file. + * @param line The source line. + * @param fmt The format string. + * @param args The format argument list. + */ FLECS_API void ecs_printv_( int level, @@ -11275,6 +12740,13 @@ void ecs_printv_( const char *fmt, va_list args); +/** Log at the provided level. + * + * @param level The log level. + * @param file The source file. + * @param line The source line. + * @param fmt The format string. + */ FLECS_API void ecs_log_( int32_t level, @@ -11283,6 +12755,14 @@ void ecs_log_( const char *fmt, ...); +/** Log at the provided level (va_list). + * + * @param level The log level. + * @param file The source file. + * @param line The source line. + * @param fmt The format string. + * @param args The format argument list. + */ FLECS_API void ecs_logv_( int level, @@ -11291,6 +12771,13 @@ void ecs_logv_( const char *fmt, va_list args); +/** Abort with error code. + * + * @param error_code The error code. + * @param file The source file. + * @param line The source line. + * @param fmt The format string. + */ FLECS_API void ecs_abort_( int32_t error_code, @@ -11299,6 +12786,14 @@ void ecs_abort_( const char *fmt, ...); +/** Log an assertion failure. + * + * @param error_code The error code. + * @param condition_str The condition that was not met. + * @param file The source file. + * @param line The source line. + * @param fmt The format string. + */ FLECS_API void ecs_assert_log_( int32_t error_code, @@ -11308,6 +12803,13 @@ void ecs_assert_log_( const char *fmt, ...); +/** Log a parser error. + * + * @param name The name of the expression. + * @param expr The expression string. + * @param column The column at which the error occurred. + * @param fmt The format string. + */ FLECS_API void ecs_parser_error_( const char *name, @@ -11316,6 +12818,14 @@ void ecs_parser_error_( const char *fmt, ...); +/** Log a parser error (va_list). + * + * @param name The name of the expression. + * @param expr The expression string. + * @param column The column at which the error occurred. + * @param fmt The format string. + * @param args The format argument list. + */ FLECS_API void ecs_parser_errorv_( const char *name, @@ -11324,6 +12834,13 @@ void ecs_parser_errorv_( const char *fmt, va_list args); +/** Log a parser warning. + * + * @param name The name of the expression. + * @param expr The expression string. + * @param column The column at which the error occurred. + * @param fmt The format string. + */ FLECS_API void ecs_parser_warning_( const char *name, @@ -11332,6 +12849,14 @@ void ecs_parser_warning_( const char *fmt, ...); +/** Log a parser warning (va_list). + * + * @param name The name of the expression. + * @param expr The expression string. + * @param column The column at which the error occurred. + * @param fmt The format string. + * @param args The format argument list. + */ FLECS_API void ecs_parser_warningv_( const char *name, @@ -11347,37 +12872,45 @@ void ecs_parser_warningv_( #ifndef FLECS_LEGACY /* C89 doesn't support variadic macros */ -/* Base logging function. Accepts a custom level */ +/** Base logging function. Accepts a custom level. */ #define ecs_print(level, ...)\ ecs_print_(level, __FILE__, __LINE__, __VA_ARGS__) +/** Base logging function with va_list. */ #define ecs_printv(level, fmt, args)\ ecs_printv_(level, __FILE__, __LINE__, fmt, args) +/** Log at the provided level. */ #define ecs_log(level, ...)\ ecs_log_(level, __FILE__, __LINE__, __VA_ARGS__) +/** Log at the provided level with va_list. */ #define ecs_logv(level, fmt, args)\ ecs_logv_(level, __FILE__, __LINE__, fmt, args) -/* Tracing. Used for logging of infrequent events */ +/** Tracing. Used for logging of infrequent events. */ #define ecs_trace_(file, line, ...) ecs_log_(0, file, line, __VA_ARGS__) +/** Tracing macro. */ #define ecs_trace(...) ecs_trace_(__FILE__, __LINE__, __VA_ARGS__) -/* Warning. Used when an issue occurs, but operation is successful */ +/** Warning. Used when an issue occurs, but operation is successful. */ #define ecs_warn_(file, line, ...) ecs_log_(-2, file, line, __VA_ARGS__) +/** Warning macro. */ #define ecs_warn(...) ecs_warn_(__FILE__, __LINE__, __VA_ARGS__) -/* Error. Used when an issue occurs, and operation failed. */ +/** Error. Used when an issue occurs, and operation failed. */ #define ecs_err_(file, line, ...) ecs_log_(-3, file, line, __VA_ARGS__) +/** Error macro. */ #define ecs_err(...) ecs_err_(__FILE__, __LINE__, __VA_ARGS__) -/* Fatal. Used when an issue occurs, and the application cannot continue. */ +/** Fatal. Used when an issue occurs, and the application cannot continue. */ #define ecs_fatal_(file, line, ...) ecs_log_(-4, file, line, __VA_ARGS__) +/** Fatal macro. */ #define ecs_fatal(...) ecs_fatal_(__FILE__, __LINE__, __VA_ARGS__) -/* Optionally include warnings about using deprecated features */ +/** Optionally include warnings about using deprecated features. */ #ifndef FLECS_NO_DEPRECATED_WARNINGS +/** Emit deprecation warning. */ #define ecs_deprecated(...)\ ecs_deprecated_(__FILE__, __LINE__, __VA_ARGS__) #else @@ -11398,20 +12931,32 @@ void ecs_parser_warningv_( * out tracing statements from a build, which improves performance. */ #if defined(FLECS_LOG_3) /* All debug tracing enabled */ +/** Debug trace at level 1. */ #define ecs_dbg_1(...) ecs_log(1, __VA_ARGS__); +/** Debug trace at level 2. */ #define ecs_dbg_2(...) ecs_log(2, __VA_ARGS__); +/** Debug trace at level 3. */ #define ecs_dbg_3(...) ecs_log(3, __VA_ARGS__); +/** Push log indentation at level 1. */ #define ecs_log_push_1() ecs_log_push_(1); +/** Push log indentation at level 2. */ #define ecs_log_push_2() ecs_log_push_(2); +/** Push log indentation at level 3. */ #define ecs_log_push_3() ecs_log_push_(3); +/** Pop log indentation at level 1. */ #define ecs_log_pop_1() ecs_log_pop_(1); +/** Pop log indentation at level 2. */ #define ecs_log_pop_2() ecs_log_pop_(2); +/** Pop log indentation at level 3. */ #define ecs_log_pop_3() ecs_log_pop_(3); +/** Test if level 1 logging is enabled. */ #define ecs_should_log_1() ecs_should_log(1) +/** Test if level 2 logging is enabled. */ #define ecs_should_log_2() ecs_should_log(2) +/** Test if level 3 logging is enabled. */ #define ecs_should_log_3() ecs_should_log(3) #define FLECS_LOG_2 @@ -11491,21 +13036,22 @@ void ecs_parser_warningv_( #endif // defined(FLECS_LOG_3) -/* Default debug tracing is at level 1 */ +/** Default debug tracing is at level 1. */ #define ecs_dbg ecs_dbg_1 -/* Default level for push/pop is 0 */ +/** Push log indentation at the default level. */ #define ecs_log_push() ecs_log_push_(0) +/** Pop log indentation at the default level. */ #define ecs_log_pop() ecs_log_pop_(0) /** Abort. - * Unconditionally aborts process. */ + * Unconditionally aborts the process. */ #define ecs_abort(error_code, ...)\ ecs_abort_(error_code, __FILE__, __LINE__, __VA_ARGS__);\ ecs_os_abort(); abort(); /* satisfy compiler/static analyzers */ /** Assert. - * Aborts if condition is false, disabled in debug mode. */ + * Aborts if condition is false, disabled in release mode. */ #if defined(FLECS_NDEBUG) && !defined(FLECS_KEEP_ASSERT) #define ecs_assert(condition, error_code, ...) #else @@ -11518,7 +13064,7 @@ void ecs_parser_warningv_( #endif // FLECS_NDEBUG /** Debug assert. - * Assert that is only valid in debug mode (ignores FLECS_KEEP_ASSERT) */ + * Assert that is only valid in debug mode (ignores FLECS_KEEP_ASSERT). */ #ifndef FLECS_NDEBUG #define ecs_dbg_assert(condition, error_code, ...) ecs_assert(condition, error_code, __VA_ARGS__) #else @@ -11526,7 +13072,7 @@ void ecs_parser_warningv_( #endif /** Sanitize assert. - * Assert that is only valid in sanitized mode (ignores FLECS_KEEP_ASSERT) */ + * Assert that is only valid in sanitized mode (ignores FLECS_KEEP_ASSERT). */ #ifdef FLECS_SANITIZE #define ecs_san_assert(condition, error_code, ...) ecs_assert(condition, error_code, __VA_ARGS__) #else @@ -11534,14 +13080,14 @@ void ecs_parser_warningv_( #endif -/* Silence dead code/unused label warnings when compiling without checks. */ +/** Silence dead code/unused label warnings when compiling without checks. */ #define ecs_dummy_check\ if ((false)) {\ goto error;\ } /** Check. - * goto error if condition is false. */ + * Go to error if condition is false. */ #if defined(FLECS_NDEBUG) && !defined(FLECS_KEEP_ASSERT) #define ecs_check(condition, error_code, ...) ecs_dummy_check #else @@ -11564,7 +13110,7 @@ void ecs_parser_warningv_( #endif // FLECS_NDEBUG /** Panic. - * goto error when FLECS_SOFT_ASSERT is defined, otherwise abort */ + * Go to error when FLECS_SOFT_ASSERT is defined, otherwise abort. */ #if defined(FLECS_NDEBUG) && !defined(FLECS_KEEP_ASSERT) #define ecs_throw(error_code, ...) ecs_dummy_check #else @@ -11579,29 +13125,31 @@ void ecs_parser_warningv_( #endif #endif // FLECS_NDEBUG -/** Parser error */ +/** Parser error. */ #define ecs_parser_error(name, expr, column, ...)\ ecs_parser_error_(name, expr, column, __VA_ARGS__) +/** Parser error with va_list. */ #define ecs_parser_errorv(name, expr, column, fmt, args)\ ecs_parser_errorv_(name, expr, column, fmt, args) +/** Parser warning. */ #define ecs_parser_warning(name, expr, column, ...)\ ecs_parser_warning_(name, expr, column, __VA_ARGS__) +/** Parser warning with va_list. */ #define ecs_parser_warningv(name, expr, column, fmt, args)\ ecs_parser_warningv_(name, expr, column, fmt, args) #endif // FLECS_LEGACY - //////////////////////////////////////////////////////////////////////////////// //// Functions that are always available //////////////////////////////////////////////////////////////////////////////// /** Enable or disable log. - * This will enable builtin log. For log to work, it will have to be - * compiled in which requires defining one of the following macros: + * This will enable the built-in log. For log to work, it will have to be + * compiled in, which requires defining one of the following macros: * * FLECS_LOG_0 - All log is disabled * FLECS_LOG_1 - Enable log level 1 @@ -11623,13 +13171,13 @@ int ecs_log_set_level( /** Get current log level. * - * @return Previous log level. + * @return Current log level. */ FLECS_API int ecs_log_get_level(void); /** Enable/disable tracing with colors. - * By default colors are enabled. + * By default, colors are enabled. * * @param enabled Whether to enable tracing with colors. * @return Previous color setting. @@ -11639,7 +13187,7 @@ bool ecs_log_enable_colors( bool enabled); /** Enable/disable logging timestamp. - * By default timestamps are disabled. Note that enabling timestamps introduces + * By default, timestamps are disabled. Note that enabling timestamps introduces * overhead as the logging code will need to obtain the current time. * * @param enabled Whether to enable tracing with timestamps. @@ -11650,7 +13198,7 @@ bool ecs_log_enable_timestamp( bool enabled); /** Enable/disable logging time since last log. - * By default deltatime is disabled. Note that enabling timestamps introduces + * By default, deltatime is disabled. Note that enabling timestamps introduces * overhead as the logging code will need to obtain the current time. * * When enabled, this logs the amount of time in seconds passed since the last @@ -11674,9 +13222,17 @@ bool ecs_log_enable_timedelta( FLECS_API int ecs_log_last_error(void); +/** Start capturing log output. + * + * @param capture_try If true, also capture messages from ecs_log_try blocks. + */ FLECS_API void ecs_log_start_capture(bool capture_try); +/** Stop capturing log output. + * + * @return The captured log output, or NULL if no output was captured. + */ FLECS_API char* ecs_log_stop_capture(void); @@ -11684,40 +13240,72 @@ char* ecs_log_stop_capture(void); //// Error codes //////////////////////////////////////////////////////////////////////////////// +/** Invalid operation error code. */ #define ECS_INVALID_OPERATION (1) +/** Invalid parameter error code. */ #define ECS_INVALID_PARAMETER (2) +/** Constraint violated error code. */ #define ECS_CONSTRAINT_VIOLATED (3) +/** Out of memory error code. */ #define ECS_OUT_OF_MEMORY (4) +/** Out of range error code. */ #define ECS_OUT_OF_RANGE (5) +/** Unsupported error code. */ #define ECS_UNSUPPORTED (6) +/** Internal error code. */ #define ECS_INTERNAL_ERROR (7) +/** Already defined error code. */ #define ECS_ALREADY_DEFINED (8) +/** Missing OS API error code. */ #define ECS_MISSING_OS_API (9) +/** Operation failed error code. */ #define ECS_OPERATION_FAILED (10) +/** Invalid conversion error code. */ #define ECS_INVALID_CONVERSION (11) +/** Cycle detected error code. */ #define ECS_CYCLE_DETECTED (13) +/** Leak detected error code. */ #define ECS_LEAK_DETECTED (14) +/** Double free error code. */ #define ECS_DOUBLE_FREE (15) +/** Inconsistent name error code. */ #define ECS_INCONSISTENT_NAME (20) +/** Name in use error code. */ #define ECS_NAME_IN_USE (21) +/** Invalid component size error code. */ #define ECS_INVALID_COMPONENT_SIZE (23) +/** Invalid component alignment error code. */ #define ECS_INVALID_COMPONENT_ALIGNMENT (24) +/** Component not registered error code. */ #define ECS_COMPONENT_NOT_REGISTERED (25) +/** Inconsistent component id error code. */ #define ECS_INCONSISTENT_COMPONENT_ID (26) +/** Inconsistent component action error code. */ #define ECS_INCONSISTENT_COMPONENT_ACTION (27) +/** Module undefined error code. */ #define ECS_MODULE_UNDEFINED (28) +/** Missing symbol error code. */ #define ECS_MISSING_SYMBOL (29) +/** Already in use error code. */ #define ECS_ALREADY_IN_USE (30) +/** Access violation error code. */ #define ECS_ACCESS_VIOLATION (40) +/** Column index out of range error code. */ #define ECS_COLUMN_INDEX_OUT_OF_RANGE (41) +/** Column is not shared error code. */ #define ECS_COLUMN_IS_NOT_SHARED (42) +/** Column is shared error code. */ #define ECS_COLUMN_IS_SHARED (43) +/** Column type mismatch error code. */ #define ECS_COLUMN_TYPE_MISMATCH (45) +/** Invalid while readonly error code. */ #define ECS_INVALID_WHILE_READONLY (70) +/** Locked storage error code. */ #define ECS_LOCKED_STORAGE (71) +/** Invalid from worker error code. */ #define ECS_INVALID_FROM_WORKER (72) @@ -11725,16 +13313,27 @@ char* ecs_log_stop_capture(void); //// Used when logging with colors is enabled //////////////////////////////////////////////////////////////////////////////// +/** Black ANSI color escape code. */ #define ECS_BLACK "\033[1;30m" +/** Red ANSI color escape code. */ #define ECS_RED "\033[0;31m" +/** Green ANSI color escape code. */ #define ECS_GREEN "\033[0;32m" +/** Yellow ANSI color escape code. */ #define ECS_YELLOW "\033[0;33m" +/** Blue ANSI color escape code. */ #define ECS_BLUE "\033[0;34m" +/** Magenta ANSI color escape code. */ #define ECS_MAGENTA "\033[0;35m" +/** Cyan ANSI color escape code. */ #define ECS_CYAN "\033[0;36m" +/** White ANSI color escape code. */ #define ECS_WHITE "\033[1;37m" +/** Grey ANSI color escape code. */ #define ECS_GREY "\033[0;37m" +/** Normal ANSI color escape code. */ #define ECS_NORMAL "\033[0;49m" +/** Bold ANSI escape code. */ #define ECS_BOLD "\033[1;49m" #ifdef __cplusplus @@ -11746,7 +13345,7 @@ char* ecs_log_stop_capture(void); #endif // FLECS_LOG_H -/* Handle addon dependencies that need declarations to be visible in header */ +/* Handle addon dependencies that need declarations to be visible in the header. */ #ifdef FLECS_STATS #ifndef FLECS_PIPELINE #define FLECS_PIPELINE @@ -11773,7 +13372,7 @@ char* ecs_log_stop_capture(void); * The app addon is a wrapper around the application's main loop. Its main * purpose is to provide a hook to modules that need to take control of the * main loop, as is for example the case with native applications that use - * emscripten with webGL. + * Emscripten with WebGL. */ #ifdef FLECS_APP @@ -11804,17 +13403,17 @@ typedef int(*ecs_app_init_action_t)( /** Used with ecs_app_run(). */ typedef struct ecs_app_desc_t { ecs_ftime_t target_fps; /**< Target FPS. */ - ecs_ftime_t delta_time; /**< Frame time increment (0 for measured values) */ + ecs_ftime_t delta_time; /**< Frame time increment (0 for measured values). */ int32_t threads; /**< Number of threads. */ - int32_t frames; /**< Number of frames to run (0 for infinite) */ - bool enable_rest; /**< Enables ECS access over HTTP, necessary for explorer */ - bool enable_stats; /**< Periodically collect statistics */ - uint16_t port; /**< HTTP port used by REST API */ + int32_t frames; /**< Number of frames to run (0 for infinite). */ + bool enable_rest; /**< Enables ECS access over HTTP, necessary for the explorer. */ + bool enable_stats; /**< Periodically collects statistics. */ + uint16_t port; /**< HTTP port used by REST API. */ - ecs_app_init_action_t init; /**< If set, function is ran before starting the + ecs_app_init_action_t init; /**< If set, the function is run before starting the * main loop. */ - void *ctx; /**< Reserved for custom run/frame actions */ + void *ctx; /**< Reserved for custom run and frame actions. */ } ecs_app_desc_t; /** Callback type for run action. */ @@ -11829,7 +13428,7 @@ typedef int(*ecs_app_frame_action_t)( /** Run application. * This will run the application with the parameters specified in desc. After - * the application quits (ecs_quit() is called) the world will be cleaned up. + * the application quits (ecs_quit() is called), the world will be cleaned up. * * If a custom run action is set, it will be invoked by this operation. The * default run action calls the frame action in a loop until it returns a @@ -11837,6 +13436,7 @@ typedef int(*ecs_app_frame_action_t)( * * @param world The world. * @param desc Application parameters. + * @return Zero if success, non-zero if failed. */ FLECS_API int ecs_app_run( @@ -11844,12 +13444,12 @@ int ecs_app_run( ecs_app_desc_t *desc); /** Default frame callback. - * This operation will run a single frame. By default this operation will invoke + * This operation will run a single frame. By default, this operation will invoke * ecs_progress() directly, unless a custom frame action is set. * * @param world The world. * @param desc The desc struct passed to ecs_app_run(). - * @return value returned by ecs_progress() + * @return Value returned by ecs_progress(). */ FLECS_API int ecs_app_run_frame( @@ -11860,6 +13460,7 @@ int ecs_app_run_frame( * See ecs_app_run(). * * @param callback The run action. + * @return Zero if success, non-zero if failed. */ FLECS_API int ecs_app_set_run_action( @@ -11869,6 +13470,7 @@ int ecs_app_set_run_action( * See ecs_app_run_frame(). * * @param callback The frame action. + * @return Zero if success, non-zero if failed. */ FLECS_API int ecs_app_set_frame_action( @@ -11896,12 +13498,12 @@ int ecs_app_set_frame_action( * * Minimalistic HTTP server that can receive and reply to simple HTTP requests. * The main goal of this addon is to enable remotely connecting to a running - * Flecs application (for example, with a web-based UI) and request/visualize + * Flecs application (for example, with a web-based UI) and request and visualize * data from the ECS world. * * Each server instance creates a single thread used for receiving requests. - * Receiving requests are enqueued and handled when the application calls - * ecs_http_server_dequeue(). This increases latency of request handling vs. + * Received requests are enqueued and handled when the application calls + * ecs_http_server_dequeue(). This increases the latency of request handling vs. * responding directly in the receive thread, but is better suited for * retrieving data from ECS applications, as requests can be processed by an ECS * system without having to lock the world. @@ -11914,7 +13516,7 @@ int ecs_app_set_frame_action( /** * @defgroup c_addons_http Http * @ingroup c_addons - * Simple HTTP server used for serving up REST API. + * Simple HTTP server used for serving up the REST API. * * @{ */ @@ -11926,10 +13528,10 @@ int ecs_app_set_frame_action( #ifndef FLECS_HTTP_H #define FLECS_HTTP_H -/** Maximum number of headers in request. */ +/** Maximum number of headers in a request. */ #define ECS_HTTP_HEADER_COUNT_MAX (32) -/** Maximum number of query parameters in request. */ +/** Maximum number of query parameters in a request. */ #define ECS_HTTP_QUERY_PARAM_COUNT_MAX (32) #ifdef __cplusplus @@ -11941,17 +13543,17 @@ typedef struct ecs_http_server_t ecs_http_server_t; /** A connection manages communication with the remote host. */ typedef struct { - uint64_t id; - ecs_http_server_t *server; + uint64_t id; /**< Connection ID. */ + ecs_http_server_t *server; /**< Server. */ - char host[128]; - char port[16]; + char host[128]; /**< Remote host. */ + char port[16]; /**< Remote port. */ } ecs_http_connection_t; -/** Helper type used for headers & URL query parameters. */ +/** Helper type used for headers and URL query parameters. */ typedef struct { - const char *key; - const char *value; + const char *key; /**< Key. */ + const char *value; /**< Value. */ } ecs_http_key_value_t; /** Supported request methods. */ @@ -11966,32 +13568,33 @@ typedef enum { /** An HTTP request. */ typedef struct { - uint64_t id; + uint64_t id; /**< Request ID. */ - ecs_http_method_t method; - char *path; - char *body; - ecs_http_key_value_t headers[ECS_HTTP_HEADER_COUNT_MAX]; - ecs_http_key_value_t params[ECS_HTTP_HEADER_COUNT_MAX]; - int32_t header_count; - int32_t param_count; + ecs_http_method_t method; /**< Request method. */ + char *path; /**< Request path. */ + char *body; /**< Request body. */ + ecs_http_key_value_t headers[ECS_HTTP_HEADER_COUNT_MAX]; /**< Request headers. */ + ecs_http_key_value_t params[ECS_HTTP_QUERY_PARAM_COUNT_MAX]; /**< Request query parameters. */ + int32_t header_count; /**< Number of headers. */ + int32_t param_count; /**< Number of query parameters. */ - ecs_http_connection_t *conn; + ecs_http_connection_t *conn; /**< Connection. */ } ecs_http_request_t; /** An HTTP reply. */ typedef struct { - int code; /**< default = 200 */ - ecs_strbuf_t body; /**< default = "" */ - const char* status; /**< default = OK */ - const char* content_type; /**< default = application/json */ - ecs_strbuf_t headers; /**< default = "" */ + int code; /**< default = 200. */ + ecs_strbuf_t body; /**< default = "". */ + const char* status; /**< default = OK. */ + const char* content_type; /**< default = application/json. */ + ecs_strbuf_t headers; /**< default = "". */ } ecs_http_reply_t; +/** Default initializer for ecs_http_reply_t. */ #define ECS_HTTP_REPLY_INIT \ (ecs_http_reply_t){200, ECS_STRBUF_INIT, "OK", "application/json", ECS_STRBUF_INIT} -/* Global HTTP statistics. */ +/** Global HTTP statistics. */ extern int64_t ecs_http_request_received_count; /**< Total number of HTTP requests received. */ extern int64_t ecs_http_request_invalid_count; /**< Total number of invalid HTTP requests. */ extern int64_t ecs_http_request_handled_ok_count; /**< Total number of successful HTTP requests. */ @@ -12013,16 +13616,16 @@ typedef bool (*ecs_http_reply_action_t)( /** Used with ecs_http_server_init(). */ typedef struct { - ecs_http_reply_action_t callback; /**< Function called for each request */ - void *ctx; /**< Passed to callback (optional) */ - uint16_t port; /**< HTTP port */ - const char *ipaddr; /**< Interface to listen on (optional) */ - int32_t send_queue_wait_ms; /**< Send queue wait time when empty */ - double cache_timeout; /**< Cache invalidation timeout (0 disables caching) */ - double cache_purge_timeout; /**< Cache purge timeout (for purging cache entries) */ + ecs_http_reply_action_t callback; /**< Function called for each request. */ + void *ctx; /**< Passed to callback (optional). */ + uint16_t port; /**< HTTP port. */ + const char *ipaddr; /**< Interface to listen on (optional). */ + int32_t send_queue_wait_ms; /**< Send queue wait time when empty. */ + double cache_timeout; /**< Cache invalidation timeout (0 disables caching). */ + double cache_purge_timeout; /**< Cache purge timeout (for purging cache entries). */ } ecs_http_server_desc_t; -/** Create server. +/** Create a server. * Use ecs_http_server_start() to start receiving requests. * * @param desc Server configuration parameters. @@ -12032,7 +13635,7 @@ FLECS_API ecs_http_server_t* ecs_http_server_init( const ecs_http_server_desc_t *desc); -/** Destroy server. +/** Destroy a server. * This operation will stop the server if it was still running. * * @param server The server to destroy. @@ -12041,8 +13644,8 @@ FLECS_API void ecs_http_server_fini( ecs_http_server_t* server); -/** Start server. - * After this operation the server will be able to accept requests. +/** Start a server. + * After this operation, the server will be able to accept requests. * * @param server The server to start. * @return Zero if successful, non-zero if failed. @@ -12056,14 +13659,15 @@ int ecs_http_server_start( * requests will be enqueued while processing requests. * * @param server The server for which to process requests. + * @param delta_time The time passed since the last call to dequeue. */ FLECS_API void ecs_http_server_dequeue( ecs_http_server_t* server, ecs_ftime_t delta_time); -/** Stop server. - * After this operation no new requests can be received. +/** Stop a server. + * After this operation, no new requests can be received. * * @param server The server. */ @@ -12079,7 +13683,8 @@ void ecs_http_server_stop( * @param srv The server. * @param req The request. * @param len The length of the request (optional). - * @return The reply. + * @param reply_out The reply (out parameter). + * @return Zero if success, non-zero if failed. */ FLECS_API int ecs_http_server_http_request( @@ -12088,7 +13693,15 @@ int ecs_http_server_http_request( ecs_size_t len, ecs_http_reply_t *reply_out); -/** Convenience wrapper around ecs_http_server_http_request(). */ +/** Convenience wrapper around ecs_http_server_http_request(). + * + * @param srv The server. + * @param method The HTTP method (e.g., "GET"). + * @param req The request path. + * @param body The request body (optional). + * @param reply_out The reply (out parameter). + * @return Zero if success, non-zero if failed. + */ FLECS_API int ecs_http_server_request( ecs_http_server_t* srv, @@ -12097,15 +13710,19 @@ int ecs_http_server_request( const char *body, ecs_http_reply_t *reply_out); -/** Get context provided in ecs_http_server_desc_t */ +/** Get context provided in ecs_http_server_desc_t. + * + * @param srv The server. + * @return The context. + */ FLECS_API void* ecs_http_server_ctx( ecs_http_server_t* srv); -/** Find header in request. +/** Find a header in a request. * * @param req The request. - * @param name name of the header to find + * @param name Name of the header to find. * @return The header value, or NULL if not found. */ FLECS_API @@ -12113,7 +13730,7 @@ const char* ecs_http_get_header( const ecs_http_request_t* req, const char* name); -/** Find query parameter in request. +/** Find a query parameter in a request. * * @param req The request. * @param name The parameter name. @@ -12147,7 +13764,7 @@ const char* ecs_http_get_param( * A small REST API that uses the HTTP server and JSON serializer to provide * access to application data for remote applications. * - * A description of the API can be found in docs/FlecsRemoteApi.md + * A description of the API can be found in docs/FlecsRemoteApi.md. */ #ifdef FLECS_REST @@ -12182,6 +13799,7 @@ const char* ecs_http_get_param( extern "C" { #endif +/** Default port for the REST API server. */ #define ECS_REST_DEFAULT_PORT (27750) /** Component that instantiates the REST API. */ @@ -12189,18 +13807,18 @@ FLECS_API extern const ecs_entity_t ecs_id(EcsRest); /** Private REST data. */ typedef struct { - ecs_world_t *world; - ecs_http_server_t *srv; - int32_t rc; - ecs_map_t cmd_captures; - double last_time; + ecs_world_t *world; /**< The world. */ + ecs_http_server_t *srv; /**< HTTP server instance. */ + int32_t rc; /**< Reference count. */ + ecs_map_t cmd_captures; /**< Map of command captures. */ + double last_time; /**< Last processing time. */ } ecs_rest_ctx_t; /** Component that creates a REST API server when instantiated. */ typedef struct { - uint16_t port; /**< Port of server (optional, default = 27750) */ - char *ipaddr; /**< Interface address (optional, default = 0.0.0.0) */ - ecs_rest_ctx_t *impl; + uint16_t port; /**< Port of server (optional, default = 27750). */ + char *ipaddr; /**< Interface address (optional, default = 0.0.0.0). */ + ecs_rest_ctx_t *impl; /**< Private implementation data. */ } EcsRest; /** Create HTTP server for REST API. @@ -12216,14 +13834,16 @@ ecs_http_server_t* ecs_rest_server_init( ecs_world_t *world, const ecs_http_server_desc_t *desc); -/** Cleanup REST HTTP server. +/** Clean up REST HTTP server. * The server must have been created with ecs_rest_server_init(). + * + * @param srv The server to destroy. */ FLECS_API void ecs_rest_server_fini( ecs_http_server_t *srv); -/** Rest module import function. +/** REST module import function. * Usage: * @code * ECS_IMPORT(world, FlecsRest) @@ -12284,22 +13904,22 @@ void FlecsRestImport( extern "C" { #endif -/** Component used for one shot/interval timer functionality */ +/** Component used for one-shot and interval timer functionality. */ typedef struct EcsTimer { - ecs_ftime_t timeout; /**< Timer timeout period */ - ecs_ftime_t time; /**< Incrementing time value */ - ecs_ftime_t overshoot; /**< Used to correct returned interval time */ - int32_t fired_count; /**< Number of times ticked */ - bool active; /**< Is the timer active or not */ - bool single_shot; /**< Is this a single shot timer */ + ecs_ftime_t timeout; /**< Timer timeout period. */ + ecs_ftime_t time; /**< Incrementing time value. */ + ecs_ftime_t overshoot; /**< Used to correct returned interval time. */ + int32_t fired_count; /**< Number of times ticked. */ + bool active; /**< Is the timer active or not. */ + bool single_shot; /**< Is this a single-shot timer. */ } EcsTimer; -/** Apply a rate filter to a tick source */ +/** Apply a rate filter to a tick source. */ typedef struct EcsRateFilter { - ecs_entity_t src; /**< Source of the rate filter */ - int32_t rate; /**< Rate of the rate filter */ - int32_t tick_count; /**< Number of times the rate filter ticked */ - ecs_ftime_t time_elapsed; /**< Time elapsed since last tick */ + ecs_entity_t src; /**< Source of the rate filter. */ + int32_t rate; /**< Rate of the rate filter. */ + int32_t tick_count; /**< Number of times the rate filter ticked. */ + ecs_ftime_t time_elapsed; /**< Time elapsed since last tick. */ } EcsRateFilter; @@ -12335,13 +13955,6 @@ ecs_entity_t ecs_set_timeout( * This means that if ecs_get_timeout() is invoked after the timer is expired, the * operation will return 0. * - * The timer is synchronous, and is incremented each frame by delta_time. - * - * The tick_source entity will be a tick source after this operation. Tick - * sources can be read by getting the EcsTickSource component. If the tick - * source ticked this frame, the 'tick' member will be true. When the tick - * source is a system, the system will tick when the timer ticks. - * * @param world The world. * @param tick_source The timer. * @return The current timeout value, or 0 if no timer is active. @@ -12379,7 +13992,7 @@ ecs_entity_t ecs_set_interval( * not a timer, the operation will return 0. * * @param world The world. - * @param tick_source The timer for which to set the interval. + * @param tick_source The timer for which to get the interval. * @return The current interval value, or 0 if no timer is active. */ FLECS_API @@ -12398,7 +14011,7 @@ void ecs_start_timer( ecs_world_t *world, ecs_entity_t tick_source); -/** Stop timer +/** Stop timer. * This operation stops a timer from triggering. * * @param world The world. @@ -12438,12 +14051,12 @@ void ecs_randomize_timers( * Rate filters enable deterministic system execution which cannot be achieved * with interval timers alone. For example, if timer A has interval 2.0 and * timer B has interval 4.0, it is not guaranteed that B will tick at exactly - * twice the multiple of A. This is partly due to the indeterministic nature of - * timers, and partly due to floating point rounding errors. + * twice the multiple of A. This is partly due to the nondeterministic nature of + * timers, and partly due to floating-point rounding errors. * * Rate filters can be combined with timers (or other rate filters) to ensure * that a system ticks at an exact multiple of a tick source (which can be - * another system). If a rate filter is created with a rate of 1 it will tick + * another system). If a rate filter is created with a rate of 1, it will tick * at the exact same time as its source. * * If no tick source is provided, the rate filter will use the frame tick as @@ -12457,8 +14070,8 @@ void ecs_randomize_timers( * @param world The world. * @param tick_source The rate filter entity (0 to create one). * @param rate The rate to apply. - * @param source The tick source (0 to use frames) - * @return The filter entity. + * @param source The tick source (0 to use frames). + * @return The rate filter entity. */ FLECS_API ecs_entity_t ecs_set_rate( @@ -12469,8 +14082,8 @@ ecs_entity_t ecs_set_rate( /** Assign tick source to system. * Systems can be their own tick source, which can be any of the tick sources - * (one shot timers, interval times and rate filters). However, in some cases it - * is must be guaranteed that different systems tick on the exact same frame. + * (one-shot timers, interval timers, and rate filters). However, in some cases it + * must be guaranteed that different systems tick on the exact same frame. * * This cannot be guaranteed by giving two systems the same interval/rate filter * as it is possible that one system is (for example) disabled, which would @@ -12480,7 +14093,7 @@ ecs_entity_t ecs_set_rate( * When two systems share the same tick source, it is guaranteed that they tick * in the same frame. The provided tick source can be any entity that is a tick * source, including another system. If the provided entity is not a tick source - * the system will not be ran. + * the system will not be run. * * To disassociate a tick source from a system, use 0 for the tick_source * parameter. @@ -12534,12 +14147,12 @@ void FlecsTimerImport( * * The pipeline module provides support for running systems automatically and * on multiple threads. A pipeline is a collection of tags that can be added to - * systems. When ran, a pipeline will query for all systems that have the tags + * systems. When run, a pipeline will query for all systems that have the tags * that belong to a pipeline, and run them. * - * The module defines a number of builtin tags (EcsPreUpdate, EcsOnUpdate, - * EcsPostUpdate etc.) that are registered with the builtin pipeline. The - * builtin pipeline is ran by default when calling ecs_progress(). An + * The module defines a number of built-in tags (EcsPreUpdate, EcsOnUpdate, + * EcsPostUpdate, etc.) that are registered with the built-in pipeline. The + * built-in pipeline is run by default when calling ecs_progress(). An * application can set a custom pipeline with the ecs_set_pipeline() function. */ @@ -12574,7 +14187,7 @@ extern "C" { #ifndef FLECS_LEGACY -/** Convenience macro to create a predeclared pipeline. +/** Convenience macro to create a forward-declared pipeline. * Usage: * @code * ECS_ENTITY_DECLARE(MyPipeline); @@ -12616,7 +14229,7 @@ extern "C" { /** Pipeline descriptor, used with ecs_pipeline_init(). */ typedef struct ecs_pipeline_desc_t { - /** Existing entity to associate with pipeline (optional). */ + /** Existing entity to associate with the pipeline (optional). */ ecs_entity_t entity; /** The pipeline query. @@ -12628,20 +14241,20 @@ typedef struct ecs_pipeline_desc_t { * * That however creates a query that matches entities with OnUpdate _and_ * OnPhysics _and_ OnRender tags, which is likely undesired. Instead, a - * query could use the or operator match a system that has one of the + * query could use the or operator to match a system that has one of the * specified phases: * OnUpdate || OnPhysics || OnRender * * This will return the correct set of systems, but they likely won't be in - * the correct order. To make sure systems are returned in the correct order + * the correct order. To make sure systems are returned in the correct order, * two query ordering features can be used: * - group_by * - order_by * * Take a look at the system manual for a more detailed explanation of - * how query features can be applied to pipelines, and how the builtin + * how query features can be applied to pipelines, and how the built-in * pipeline query works. - */ + */ ecs_query_desc_t query; } ecs_pipeline_desc_t; @@ -12687,7 +14300,7 @@ ecs_entity_t ecs_get_pipeline( * invocation. * * When an application passes 0 to delta_time, ecs_progress() will automatically - * measure the time passed since the last frame. If an application does not uses + * measure the time passed since the last frame. If an application does not use * time management, it should pass a non-zero value for delta_time (1.0 is * recommended). That way, no time will be wasted measuring the time. * @@ -12725,12 +14338,12 @@ void ecs_reset_clock( * invoked from multiple threads, and only when staging is disabled, as the * pipeline manages staging and, if necessary, synchronization between threads. * - * If 0 is provided for the pipeline id, the default pipeline will be ran (this - * is either the builtin pipeline or the pipeline set with set_pipeline()). + * If 0 is provided for the pipeline ID, the default pipeline will be run (this + * is either the built-in pipeline or the pipeline set with ecs_set_pipeline()). * - * When using progress() this operation will be invoked automatically for the - * default pipeline (either the builtin pipeline or the pipeline set with - * set_pipeline()). An application may run additional pipelines. + * When using ecs_progress(), this operation will be invoked automatically for + * the default pipeline (either the built-in pipeline or the pipeline set with + * ecs_set_pipeline()). An application may run additional pipelines. * * @param world The world. * @param pipeline The pipeline to run. @@ -12748,11 +14361,11 @@ void ecs_run_pipeline( //////////////////////////////////////////////////////////////////////////////// /** Set number of worker threads. - * Setting this value to a value higher than 1 will start as many threads and + * Setting this value to a value higher than 1 will start that many threads and * will cause systems to evenly distribute matched entities across threads. The * operation may be called multiple times to reconfigure the number of threads - * used, but never while running a system / pipeline. - * Calling ecs_set_threads() will also end the use of task threads setup with + * used, but never while running a system or pipeline. + * Calling ecs_set_threads() will also end the use of task threads set up with * ecs_set_task_threads() and vice-versa. * * @param world The world. @@ -12766,28 +14379,28 @@ void ecs_set_threads( /** Set number of worker task threads. * ecs_set_task_threads() is similar to ecs_set_threads(), except threads are treated * as short-lived tasks and will be created and joined around each update of the world. - * Creation and joining of these tasks will use the os_api_t tasks APIs rather than the + * Creation and joining of these tasks will use the os_api_t task APIs rather than * the standard thread API functions, although they may be the same if desired. * This function is useful for multithreading world updates using an external - * asynchronous job system rather than long running threads by providing the APIs + * asynchronous job system rather than long-running threads by providing the APIs * to create tasks for your job system and then wait on their conclusion. * The operation may be called multiple times to reconfigure the number of task threads - * used, but never while running a system / pipeline. - * Calling ecs_set_task_threads() will also end the use of threads setup with - * ecs_set_threads() and vice-versa - * + * used, but never while running a system or pipeline. + * Calling ecs_set_task_threads() will also end the use of threads set up with + * ecs_set_threads() and vice-versa. + * * @param world The world. - * @param task_threads The number of task threads to create. + * @param task_threads The number of task threads to create. */ FLECS_API void ecs_set_task_threads( ecs_world_t *world, int32_t task_threads); -/** Returns true if task thread use have been requested. - * +/** Return true if task thread use has been requested. + * * @param world The world. - * @result Whether the world is using task threads. + * @return Whether the world is using task threads. */ FLECS_API bool ecs_using_task_threads( @@ -12830,7 +14443,7 @@ void FlecsPipelineImport( * @brief System module. * * The system module allows for creating and running systems. A system is a - * query in combination with a callback function. In addition systems have + * query in combination with a callback function. In addition, systems have * support for time management and can be monitored by the stats addon. */ @@ -12839,7 +14452,7 @@ void FlecsPipelineImport( /** * @defgroup c_addons_system System * @ingroup c_addons - * Systems are a query + function that can be ran manually or by a pipeline. + * Systems are a query + function that can be run manually or by a pipeline. * * @{ */ @@ -12855,41 +14468,45 @@ void FlecsPipelineImport( extern "C" { #endif -/** Component used to provide a tick source to systems */ +/** Component used to provide a tick source to systems. */ typedef struct EcsTickSource { - bool tick; /**< True if providing tick */ - ecs_ftime_t time_elapsed; /**< Time elapsed since last tick */ + bool tick; /**< True if providing a tick. */ + ecs_ftime_t time_elapsed; /**< Time elapsed since the last tick. */ } EcsTickSource; /** Use with ecs_system_init() to create or update a system. */ typedef struct ecs_system_desc_t { - int32_t _canary; + int32_t _canary; /**< Used for validity testing. Do not set. */ - /** Existing entity to associate with system (optional) */ + /** Existing entity to associate with the system (optional). */ ecs_entity_t entity; - /** System query parameters */ + /** System query parameters. */ ecs_query_desc_t query; - /** Callback that is ran for each result returned by the system's query. This + /** Optional pipeline phase for the system to run in. When set, it will be + * added to the system both as a tag and as a (DependsOn, phase) pair. */ + ecs_entity_t phase; + + /** Callback that is run for each result returned by the system's query. This * means that this callback can be invoked multiple times per system per * frame, typically once for each matching table. */ ecs_iter_action_t callback; - /** Callback that is invoked when a system is ran. + /** Callback that is invoked when a system is run. * When left to NULL, the default system runner is used, which calls the * "callback" action for each result returned from the system's query. * * It should not be assumed that the input iterator can always be iterated * with ecs_query_next(). When a system is multithreaded and/or paged, the - * iterator can be either a worker or paged iterator. The correct function + * iterator can be either a worker or a paged iterator. The correct function * to use for iteration is ecs_iter_next(). * * An implementation can test whether the iterator is a query iterator by * testing whether the it->next value is equal to ecs_query_next(). */ ecs_run_action_t run; - /** Context to be passed to callback (as ecs_iter_t::param) */ + /** Context to be passed to callback (as ecs_iter_t::param). */ void *ctx; /** Callback to free ctx. */ @@ -12907,61 +14524,72 @@ typedef struct ecs_system_desc_t { /** Callback to free run ctx. */ ecs_ctx_free_t run_ctx_free; - /** Interval in seconds at which the system should run */ + /** Interval in seconds at which the system should run. */ ecs_ftime_t interval; - /** Rate at which the system should run */ + /** Rate at which the system should run. */ int32_t rate; - /** External tick source that determines when system ticks */ + /** External tick source that determines when the system ticks. */ ecs_entity_t tick_source; - /** If true, system will be ran on multiple threads */ + /** If true, the system will be run on multiple threads. */ bool multi_threaded; - /** If true, system will have access to the actual world. Cannot be true at the + /** If true, the system will have access to the actual world. Cannot be true at the * same time as multi_threaded. */ bool immediate; } ecs_system_desc_t; -/** Create a system */ +/** Create a system. + * + * @param world The world. + * @param desc The system descriptor. + * @return The system entity. + */ FLECS_API ecs_entity_t ecs_system_init( ecs_world_t *world, const ecs_system_desc_t *desc); -/** System type, get with ecs_system_get() */ +/** System type, get with ecs_system_get(). */ typedef struct ecs_system_t { - ecs_header_t hdr; + ecs_header_t hdr; /**< Object header. */ - /** See ecs_system_desc_t */ + /** See ecs_system_desc_t. */ ecs_run_action_t run; - /** See ecs_system_desc_t */ + /** See ecs_system_desc_t. */ ecs_iter_action_t action; - /** System query */ + /** System query. */ ecs_query_t *query; - /** Tick source associated with system */ + /** Query group to iterate. */ + uint64_t group_id; + + /** True if a query group is configured. */ + bool group_id_set; + + /** Tick source associated with the system. */ ecs_entity_t tick_source; - /** Is system multithreaded */ + /** Whether the system is multithreaded. */ bool multi_threaded; - /** Is system ran in immediate mode */ + /** Whether the system is run in immediate mode. */ bool immediate; - /** Cached system name (for perf tracing) */ + /** Cached system name (for perf tracing). */ const char *name; - /** Userdata for system */ + /** Userdata for the system. */ void *ctx; - /** Callback language binding context */ + /** Callback language binding context. */ void *callback_ctx; - /** Run language binding context */ + /** Run language binding context. */ void *run_ctx; /** Callback to free ctx. */ @@ -12973,21 +14601,21 @@ typedef struct ecs_system_t { /** Callback to free run ctx. */ ecs_ctx_free_t run_ctx_free; - /** Time spent on running system */ + /** Time spent on running the system. */ ecs_ftime_t time_spent; - /** Time passed since last invocation */ + /** Time passed since the last invocation. */ ecs_ftime_t time_passed; - /** Last frame for which the system was considered */ + /** Last frame for which the system was considered. */ int64_t last_frame; - /* Mixins */ - flecs_poly_dtor_t dtor; + /** Mixin destructor. */ + flecs_poly_dtor_t dtor; } ecs_system_t; -/** Get system object. - * Returns the system object. Can be used to access various information about +/** Get a system object. + * Return the system object. Can be used to access various information about * the system, like the query and context. * * @param world The world. @@ -12999,12 +14627,27 @@ const ecs_system_t* ecs_system_get( const ecs_world_t *world, ecs_entity_t system); +/** Set query group for system. + * This operation configures a system created with a grouped query to only + * iterate results for the specified group ID. The group filter is applied to + * both manual runs and pipeline execution. + * + * @param world The world. + * @param system The system. + * @param group_id The query group ID to iterate. + */ +FLECS_API +void ecs_system_set_group( + ecs_world_t *world, + ecs_entity_t system, + uint64_t group_id); + #ifndef FLECS_LEGACY /** Forward declare a system. */ #define ECS_SYSTEM_DECLARE(id) ecs_entity_t ecs_id(id) -/** Define a forward declared system. +/** Define a forward-declared system. * * Example: * @@ -13012,26 +14655,21 @@ const ecs_system_t* ecs_system_get( * ECS_SYSTEM_DEFINE(world, Move, EcsOnUpdate, Position, Velocity); * @endcode */ -#define ECS_SYSTEM_DEFINE(world, id_, phase, ...) \ +#define ECS_SYSTEM_DEFINE(world, id_, phase_, ...) \ { \ ecs_system_desc_t desc = {0}; \ ecs_entity_desc_t edesc = {0}; \ - ecs_id_t add_ids[3] = {\ - ((phase) ? ecs_pair(EcsDependsOn, (phase)) : 0), \ - (phase), \ - 0 \ - };\ edesc.id = ecs_id(id_);\ edesc.name = #id_;\ - edesc.add = add_ids;\ desc.entity = ecs_entity_init(world, &edesc);\ desc.query.expr = #__VA_ARGS__; \ + desc.phase = phase_; \ desc.callback = id_; \ ecs_id(id_) = ecs_system_init(world, &desc); \ } \ ecs_assert(ecs_id(id_) != 0, ECS_INVALID_PARAMETER, "failed to create system %s", #id_) -/** Declare & define a system. +/** Declare and define a system. * * Example: * @@ -13074,7 +14712,7 @@ const ecs_system_t* ecs_system_get( * tables at creation time or after creation time, when a new table is created. * * Manual systems are useful to evaluate lists of pre-matched entities at - * application defined times. Because none of the matching logic is evaluated + * application-defined times. Because none of the matching logic is evaluated * before the system is invoked, manual systems are much more efficient than * manually obtaining a list of entities and retrieving their components. * @@ -13085,15 +14723,15 @@ const ecs_system_t* ecs_system_get( * Any system may interrupt execution by setting the interrupted_by member in * the ecs_iter_t value. This is particularly useful for manual systems, where * the value of interrupted_by is returned by this operation. This, in - * combination with the param argument lets applications use manual systems - * to lookup entities: once the entity has been found its handle is passed to + * combination with the param argument, lets applications use manual systems + * to lookup entities: once the entity has been found, its handle is passed to * interrupted_by, which is then subsequently returned. * * @param world The world. * @param system The system to run. * @param delta_time The time passed since the last system invocation. * @param param A user-defined parameter to pass to the system. - * @return handle to last evaluated entity if system was interrupted. + * @return Handle to the last evaluated entity if the system was interrupted. */ FLECS_API ecs_entity_t ecs_run( @@ -13102,15 +14740,15 @@ ecs_entity_t ecs_run( ecs_ftime_t delta_time, void *param); -/** Same as ecs_run(), but subdivides entities across number of provided stages. +/** Same as ecs_run(), but subdivides entities across a number of provided stages. * * @param world The world. * @param system The system to run. - * @param stage_current The id of the current stage. + * @param stage_current The ID of the current stage. * @param stage_count The total number of stages. * @param delta_time The time passed since the last system invocation. * @param param A user-defined parameter to pass to the system. - * @return handle to last evaluated entity if system was interrupted. + * @return Handle to the last evaluated entity if the system was interrupted. */ FLECS_API ecs_entity_t ecs_run_worker( @@ -13153,14 +14791,14 @@ void FlecsSystemImport( * @file addons/stats.h * @brief Statistics addon. * - * The stats addon tracks high resolution statistics for the world, systems and + * The stats addon tracks high-resolution statistics for the world, systems, and * pipelines. The addon can be used as an API where an application calls * functions to obtain statistics directly and as a module where statistics are * automatically tracked. The latter is required for statistics tracking in the * explorer. * - * When the addon is imported as module, statistics are tracked for each frame, - * second, minute, hour, day and week with 60 datapoints per tier. + * When the addon is imported as a module, statistics are tracked for each frame, + * second, minute, hour, day, and week with 60 data points per tier. */ #ifdef FLECS_STATS @@ -13168,7 +14806,7 @@ void FlecsSystemImport( /** * @defgroup c_addons_stats Stats * @ingroup c_addons - * Collection of statistics for world, queries, systems and pipelines. + * Collection of statistics for world, queries, systems, and pipelines. * * @{ */ @@ -13188,188 +14826,189 @@ void FlecsSystemImport( extern "C" { #endif +/** Number of samples in the stat window. */ #define ECS_STAT_WINDOW (60) -/** Simple value that indicates current state */ +/** Simple value that indicates current state. */ typedef struct ecs_gauge_t { - ecs_float_t avg[ECS_STAT_WINDOW]; - ecs_float_t min[ECS_STAT_WINDOW]; - ecs_float_t max[ECS_STAT_WINDOW]; + ecs_float_t avg[ECS_STAT_WINDOW]; /**< Windowed average. */ + ecs_float_t min[ECS_STAT_WINDOW]; /**< Windowed minimum. */ + ecs_float_t max[ECS_STAT_WINDOW]; /**< Windowed maximum. */ } ecs_gauge_t; -/** Monotonically increasing counter */ +/** Monotonically increasing counter. */ typedef struct ecs_counter_t { - ecs_gauge_t rate; /**< Keep track of deltas too */ - double value[ECS_STAT_WINDOW]; + ecs_gauge_t rate; /**< Keep track of deltas too. */ + double value[ECS_STAT_WINDOW]; /**< Monotonically increasing values. */ } ecs_counter_t; -/** Make all metrics the same size, so we can iterate over fields */ +/** Make all metrics the same size, so we can iterate over fields. */ typedef union ecs_metric_t { - ecs_gauge_t gauge; - ecs_counter_t counter; + ecs_gauge_t gauge; /**< Gauge metric. */ + ecs_counter_t counter; /**< Counter metric. */ } ecs_metric_t; +/** Type that contains world statistics. */ typedef struct ecs_world_stats_t { - int64_t first_; + int64_t first_; /**< Used for field iteration. Do not set. */ /* Entities */ struct { - ecs_metric_t count; /**< Number of entities */ - ecs_metric_t not_alive_count; /**< Number of not alive (recyclable) entity ids */ + ecs_metric_t count; /**< Number of entities. */ + ecs_metric_t not_alive_count; /**< Number of not alive (recyclable) entity IDs. */ } entities; - /* Component ids */ + /* Component IDs */ struct { - ecs_metric_t tag_count; /**< Number of tag ids (ids without data) */ - ecs_metric_t component_count; /**< Number of components ids (ids with data) */ - ecs_metric_t pair_count; /**< Number of pair ids */ - ecs_metric_t type_count; /**< Number of registered types */ - ecs_metric_t create_count; /**< Number of times id has been created */ - ecs_metric_t delete_count; /**< Number of times id has been deleted */ + ecs_metric_t tag_count; /**< Number of tag IDs (IDs without data). */ + ecs_metric_t component_count; /**< Number of component IDs (IDs with data). */ + ecs_metric_t pair_count; /**< Number of pair IDs. */ + ecs_metric_t type_count; /**< Number of registered types. */ + ecs_metric_t create_count; /**< Number of times an ID has been created. */ + ecs_metric_t delete_count; /**< Number of times an ID has been deleted. */ } components; /* Tables */ struct { - ecs_metric_t count; /**< Number of tables */ - ecs_metric_t empty_count; /**< Number of empty tables */ - ecs_metric_t create_count; /**< Number of times table has been created */ - ecs_metric_t delete_count; /**< Number of times table has been deleted */ + ecs_metric_t count; /**< Number of tables. */ + ecs_metric_t empty_count; /**< Number of empty tables. */ + ecs_metric_t create_count; /**< Number of times table has been created. */ + ecs_metric_t delete_count; /**< Number of times table has been deleted. */ } tables; - /* Queries & events */ + /* Queries and events */ struct { - ecs_metric_t query_count; /**< Number of queries */ - ecs_metric_t observer_count; /**< Number of observers */ - ecs_metric_t system_count; /**< Number of systems */ + ecs_metric_t query_count; /**< Number of queries. */ + ecs_metric_t observer_count; /**< Number of observers. */ + ecs_metric_t system_count; /**< Number of systems. */ } queries; /* Commands */ struct { - ecs_metric_t add_count; - ecs_metric_t remove_count; - ecs_metric_t delete_count; - ecs_metric_t clear_count; - ecs_metric_t set_count; - ecs_metric_t ensure_count; - ecs_metric_t modified_count; - ecs_metric_t other_count; - ecs_metric_t discard_count; - ecs_metric_t batched_entity_count; - ecs_metric_t batched_count; + ecs_metric_t add_count; /**< Number of add commands. */ + ecs_metric_t remove_count; /**< Number of remove commands. */ + ecs_metric_t delete_count; /**< Number of delete commands. */ + ecs_metric_t clear_count; /**< Number of clear commands. */ + ecs_metric_t set_count; /**< Number of set commands. */ + ecs_metric_t ensure_count; /**< Number of ensure commands. */ + ecs_metric_t modified_count; /**< Number of modified commands. */ + ecs_metric_t other_count; /**< Number of other commands. */ + ecs_metric_t discard_count; /**< Number of discarded commands. */ + ecs_metric_t batched_entity_count; /**< Number of entities for which commands were batched. */ + ecs_metric_t batched_count; /**< Number of commands batched. */ } commands; /* Frame data */ struct { ecs_metric_t frame_count; /**< Number of frames processed. */ ecs_metric_t merge_count; /**< Number of merges executed. */ - ecs_metric_t rematch_count; /**< Number of query rematches */ + ecs_metric_t rematch_count; /**< Number of query rematches. */ ecs_metric_t pipeline_build_count; /**< Number of system pipeline rebuilds (occurs when an inactive system becomes active). */ - ecs_metric_t systems_ran; /**< Number of systems ran. */ + ecs_metric_t systems_ran; /**< Number of systems run. */ ecs_metric_t observers_ran; /**< Number of times an observer was invoked. */ - ecs_metric_t event_emit_count; /**< Number of events emitted */ + ecs_metric_t event_emit_count; /**< Number of events emitted. */ } frame; /* Timing */ struct { - ecs_metric_t world_time_raw; /**< Actual time passed since simulation start (first time progress() is called) */ - ecs_metric_t world_time; /**< Simulation time passed since simulation start. Takes into account time scaling */ - ecs_metric_t frame_time; /**< Time spent processing a frame. Smaller than world_time_total when load is not 100% */ + ecs_metric_t world_time_raw; /**< Actual time passed since simulation start (first time progress() is called). */ + ecs_metric_t world_time; /**< Simulation time passed since simulation start. Takes into account time scaling. */ + ecs_metric_t frame_time; /**< Time spent processing a frame. Smaller than world_time_total when load is not 100%. */ ecs_metric_t system_time; /**< Time spent on running systems. */ ecs_metric_t emit_time; /**< Time spent on notifying observers. */ ecs_metric_t merge_time; /**< Time spent on merging commands. */ ecs_metric_t rematch_time; /**< Time spent on rematching. */ ecs_metric_t fps; /**< Frames per second. */ - ecs_metric_t delta_time; /**< Delta_time. */ + ecs_metric_t delta_time; /**< Delta time. */ } performance; struct { /* Memory allocation data */ - ecs_metric_t alloc_count; /**< Allocs per frame */ - ecs_metric_t realloc_count; /**< Reallocs per frame */ - ecs_metric_t free_count; /**< Frees per frame */ - ecs_metric_t outstanding_alloc_count; /**< Difference between allocs & frees */ + ecs_metric_t alloc_count; /**< Allocs per frame. */ + ecs_metric_t realloc_count; /**< Reallocs per frame. */ + ecs_metric_t free_count; /**< Frees per frame. */ + ecs_metric_t outstanding_alloc_count; /**< Difference between allocs and frees. */ /* Memory allocator data */ - ecs_metric_t block_alloc_count; /**< Block allocations per frame */ - ecs_metric_t block_free_count; /**< Block frees per frame */ - ecs_metric_t block_outstanding_alloc_count; /**< Difference between allocs & frees */ - ecs_metric_t stack_alloc_count; /**< Page allocations per frame */ - ecs_metric_t stack_free_count; /**< Page frees per frame */ - ecs_metric_t stack_outstanding_alloc_count; /**< Difference between allocs & frees */ + ecs_metric_t block_alloc_count; /**< Block allocations per frame. */ + ecs_metric_t block_free_count; /**< Block frees per frame. */ + ecs_metric_t block_outstanding_alloc_count; /**< Difference between allocs and frees. */ + ecs_metric_t stack_alloc_count; /**< Page allocations per frame. */ + ecs_metric_t stack_free_count; /**< Page frees per frame. */ + ecs_metric_t stack_outstanding_alloc_count; /**< Difference between allocs and frees. */ } memory; /* HTTP statistics */ struct { - ecs_metric_t request_received_count; - ecs_metric_t request_invalid_count; - ecs_metric_t request_handled_ok_count; - ecs_metric_t request_handled_error_count; - ecs_metric_t request_not_handled_count; - ecs_metric_t request_preflight_count; - ecs_metric_t send_ok_count; - ecs_metric_t send_error_count; - ecs_metric_t busy_count; + ecs_metric_t request_received_count; /**< Number of HTTP requests received. */ + ecs_metric_t request_invalid_count; /**< Number of invalid HTTP requests. */ + ecs_metric_t request_handled_ok_count; /**< Number of successfully handled HTTP requests. */ + ecs_metric_t request_handled_error_count; /**< Number of HTTP requests with error response. */ + ecs_metric_t request_not_handled_count; /**< Number of unhandled HTTP requests. */ + ecs_metric_t request_preflight_count; /**< Number of preflight HTTP requests. */ + ecs_metric_t send_ok_count; /**< Number of successful HTTP responses sent. */ + ecs_metric_t send_error_count; /**< Number of HTTP responses with send error. */ + ecs_metric_t busy_count; /**< Number of times server was busy. */ } http; - int64_t last_; + int64_t last_; /**< Used for field iteration. Do not set. */ - /** Current position in ring buffer */ + /** Current position in ring buffer. */ int32_t t; } ecs_world_stats_t; -/** Statistics for a single query (use ecs_query_cache_stats_get) */ +/** Statistics for a single query (use ecs_query_cache_stats_get()). */ typedef struct ecs_query_stats_t { - int64_t first_; - ecs_metric_t result_count; /**< Number of query results */ - ecs_metric_t matched_table_count; /**< Number of matched tables */ - ecs_metric_t matched_entity_count; /**< Number of matched entities */ - int64_t last_; + int64_t first_; /**< Used for field iteration. Do not set. */ + ecs_metric_t result_count; /**< Number of query results. */ + ecs_metric_t matched_table_count; /**< Number of matched tables. */ + ecs_metric_t matched_entity_count; /**< Number of matched entities. */ + int64_t last_; /**< Used for field iteration. Do not set. */ - /** Current position in ringbuffer */ + /** Current position in ring buffer. */ int32_t t; } ecs_query_stats_t; -/** Statistics for a single system (use ecs_system_stats_get()) */ +/** Statistics for a single system (use ecs_system_stats_get()). */ typedef struct ecs_system_stats_t { - int64_t first_; - ecs_metric_t time_spent; /**< Time spent processing a system */ - int64_t last_; + int64_t first_; /**< Used for field iteration. Do not set. */ + ecs_metric_t time_spent; /**< Time spent processing a system. */ + int64_t last_; /**< Used for field iteration. Do not set. */ - bool task; /**< Is system a task */ + bool task; /**< Whether the system is a task. */ - ecs_query_stats_t query; + ecs_query_stats_t query; /**< Query statistics. */ } ecs_system_stats_t; -/** Statistics for sync point */ +/** Statistics for sync point. */ typedef struct ecs_sync_stats_t { - int64_t first_; - ecs_metric_t time_spent; - ecs_metric_t commands_enqueued; - int64_t last_; - - int32_t system_count; - bool multi_threaded; - bool immediate; + int64_t first_; /**< Used for field iteration. Do not set. */ + ecs_metric_t time_spent; /**< Time spent in sync point. */ + ecs_metric_t commands_enqueued; /**< Number of commands enqueued. */ + int64_t last_; /**< Used for field iteration. Do not set. */ + + int32_t system_count; /**< Number of systems before sync point. */ + bool multi_threaded; /**< Whether the sync point is multi-threaded. */ + bool immediate; /**< Whether the sync point is immediate. */ } ecs_sync_stats_t; /** Statistics for all systems in a pipeline. */ typedef struct ecs_pipeline_stats_t { - /* Allow for initializing struct with {0} */ - int8_t canary_; + int8_t canary_; /**< Allow for initializing struct with {0}. Do not set. */ - /** Vector with system ids of all systems in the pipeline. The systems are + /** Vector with system IDs of all systems in the pipeline. The systems are * stored in the order they are executed. Merges are represented by a 0. */ ecs_vec_t systems; - /** Vector with sync point stats */ + /** Vector with sync point stats. */ ecs_vec_t sync_points; - /** Current position in ring buffer */ + /** Current position in ring buffer. */ int32_t t; - int32_t system_count; /**< Number of systems in pipeline */ - int32_t active_system_count; /**< Number of active systems in pipeline */ - int32_t rebuild_count; /**< Number of times pipeline has rebuilt */ + int32_t system_count; /**< Number of systems in pipeline. */ + int32_t active_system_count; /**< Number of active systems in pipeline. */ + int32_t rebuild_count; /**< Number of times pipeline has rebuilt. */ } ecs_pipeline_stats_t; /** Get world statistics. @@ -13406,6 +15045,11 @@ void ecs_world_stats_copy_last( ecs_world_stats_t *dst, const ecs_world_stats_t *src); +/** Log world statistics. + * + * @param world The world. + * @param stats The statistics to log. + */ FLECS_API void ecs_world_stats_log( const ecs_world_t *world, @@ -13462,7 +15106,7 @@ bool ecs_system_stats_get( ecs_entity_t system, ecs_system_stats_t *stats); -/** Reduce source measurement window into single destination measurement */ +/** Reduce source measurement window into single destination measurement. */ FLECS_API void ecs_system_stats_reduce( ecs_system_stats_t *dst, @@ -13508,7 +15152,7 @@ FLECS_API void ecs_pipeline_stats_fini( ecs_pipeline_stats_t *stats); -/** Reduce source measurement window into single destination measurement */ +/** Reduce source measurement window into single destination measurement. */ FLECS_API void ecs_pipeline_stats_reduce( ecs_pipeline_stats_t *dst, @@ -13546,14 +15190,14 @@ void ecs_metric_reduce( int32_t t_dst, int32_t t_src); -/** Reduce last measurement into previous measurement */ +/** Reduce last measurement into previous measurement. */ FLECS_API void ecs_metric_reduce_last( ecs_metric_t *m, int32_t t, int32_t count); -/** Copy measurement */ +/** Copy measurement. */ FLECS_API void ecs_metric_copy( ecs_metric_t *m, @@ -13561,21 +15205,21 @@ void ecs_metric_copy( int32_t src); FLECS_API extern ECS_COMPONENT_DECLARE(FlecsStats); /**< Flecs stats module. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsWorldStats); /**< Component id for EcsWorldStats. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsWorldSummary); /**< Component id for EcsWorldSummary. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsSystemStats); /**< Component id for EcsSystemStats. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsPipelineStats); /**< Component id for EcsPipelineStats. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsWorldStats); /**< Component ID for EcsWorldStats. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsWorldSummary); /**< Component ID for EcsWorldSummary. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsSystemStats); /**< Component ID for EcsSystemStats. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsPipelineStats); /**< Component ID for EcsPipelineStats. */ /* Memory statistics components */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_entities_memory_t); /**< Component id for ecs_entities_memory_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_component_index_memory_t); /**< Component id for ecs_component_index_memory_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_query_memory_t); /**< Component id for ecs_query_memory_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_component_memory_t); /**< Component id for ecs_component_memory_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_table_memory_t); /**< Component id for ecs_table_memory_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_misc_memory_t); /**< Component id for ecs_misc_memory_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_table_histogram_t); /**< Component id for ecs_table_histogram_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(ecs_allocator_memory_t); /**< Component id for ecs_allocator_memory_t. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsWorldMemory); /**< Component id for EcsWorldMemory. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_entities_memory_t); /**< Component ID for ecs_entities_memory_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_component_index_memory_t); /**< Component ID for ecs_component_index_memory_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_query_memory_t); /**< Component ID for ecs_query_memory_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_component_memory_t); /**< Component ID for ecs_component_memory_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_table_memory_t); /**< Component ID for ecs_table_memory_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_misc_memory_t); /**< Component ID for ecs_misc_memory_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_table_histogram_t); /**< Component ID for ecs_table_histogram_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(ecs_allocator_memory_t); /**< Component ID for ecs_allocator_memory_t. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsWorldMemory); /**< Component ID for EcsWorldMemory. */ FLECS_API extern ecs_entity_t EcsPeriod1s; /**< Tag used for metrics collected in last second. */ FLECS_API extern ecs_entity_t EcsPeriod1m; /**< Tag used for metrics collected in last minute. */ @@ -13583,189 +15227,189 @@ FLECS_API extern ecs_entity_t EcsPeriod1h; /**< Tag used for met FLECS_API extern ecs_entity_t EcsPeriod1d; /**< Tag used for metrics collected in last day. */ FLECS_API extern ecs_entity_t EcsPeriod1w; /**< Tag used for metrics collected in last week. */ -/** Common data for statistics. */ +/** Common header for statistics types. */ typedef struct { - ecs_ftime_t elapsed; - int32_t reduce_count; + ecs_ftime_t elapsed; /**< Elapsed time since last reset. */ + int32_t reduce_count; /**< Number of times statistics have been reduced. */ } EcsStatsHeader; /** Component that stores world statistics. */ typedef struct { - EcsStatsHeader hdr; - ecs_world_stats_t *stats; + EcsStatsHeader hdr; /**< Statistics header. */ + ecs_world_stats_t *stats; /**< World statistics data. */ } EcsWorldStats; /** Component that stores system statistics. */ typedef struct { - EcsStatsHeader hdr; - ecs_map_t stats; + EcsStatsHeader hdr; /**< Statistics header. */ + ecs_map_t stats; /**< Map of system statistics. */ } EcsSystemStats; /** Component that stores pipeline statistics. */ typedef struct { - EcsStatsHeader hdr; - ecs_map_t stats; + EcsStatsHeader hdr; /**< Statistics header. */ + ecs_map_t stats; /**< Map of pipeline statistics. */ } EcsPipelineStats; /** Component that stores a summary of world statistics. */ typedef struct { /* Time */ - double target_fps; /**< Target FPS */ - double time_scale; /**< Simulation time scale */ - double fps; /**< FPS */ + double target_fps; /**< Target FPS. */ + double time_scale; /**< Simulation time scale. */ + double fps; /**< FPS. */ /* Totals */ - double frame_time_total; /**< Total time spent processing a frame */ - double system_time_total; /**< Total time spent in systems */ - double merge_time_total; /**< Total time spent in merges */ + double frame_time_total; /**< Total time spent processing a frame. */ + double system_time_total; /**< Total time spent in systems. */ + double merge_time_total; /**< Total time spent in merges. */ - int64_t entity_count; - int64_t table_count; - int64_t frame_count; /**< Number of frames processed */ - int64_t command_count; /**< Number of commands processed */ - int64_t merge_count; /**< Number of merges executed */ + int64_t entity_count; /**< Number of entities. */ + int64_t table_count; /**< Number of tables. */ + int64_t frame_count; /**< Number of frames processed. */ + int64_t command_count; /**< Number of commands processed. */ + int64_t merge_count; /**< Number of merges executed. */ - int64_t systems_ran_total; - int64_t observers_ran_total; - int64_t queries_ran_total; + int64_t systems_ran_total; /**< Total number of systems run. */ + int64_t observers_ran_total; /**< Total number of times observers were invoked. */ + int64_t queries_ran_total; /**< Total number of queries run. */ - int32_t tag_count; /**< Number of tag (no data) ids in the world */ - int32_t component_count; /**< Number of component (data) ids in the world */ - int32_t pair_count; /**< Number of pair ids in the world */ + int32_t tag_count; /**< Number of tag (no data) IDs in the world. */ + int32_t component_count; /**< Number of component (data) IDs in the world. */ + int32_t pair_count; /**< Number of pair IDs in the world. */ /* Per frame */ - double frame_time_frame; /**< Time spent processing a frame */ - double system_time_frame; /**< Time spent in systems */ - double merge_time_frame; /**< Time spent in merges */ + double frame_time_frame; /**< Time spent processing a frame. */ + double system_time_frame; /**< Time spent in systems. */ + double merge_time_frame; /**< Time spent in merges. */ - int64_t merge_count_frame; - int64_t systems_ran_frame; - int64_t observers_ran_frame; - int64_t queries_ran_frame; - int64_t command_count_frame; /**< Number of commands processed in last frame */ + int64_t merge_count_frame; /**< Number of merges in last frame. */ + int64_t systems_ran_frame; /**< Number of systems run in last frame. */ + int64_t observers_ran_frame; /**< Number of times observers were invoked in last frame. */ + int64_t queries_ran_frame; /**< Number of queries run in last frame. */ + int64_t command_count_frame; /**< Number of commands processed in last frame. */ - double simulation_time; /**< Time spent in simulation */ - uint32_t uptime; /**< Time since world was created */ + double simulation_time; /**< Time spent in simulation. */ + uint32_t uptime; /**< Time since world was created. */ /* Build info */ - ecs_build_info_t build_info; /**< Build info */ + ecs_build_info_t build_info; /**< Build info. */ } EcsWorldSummary; /** Entity memory. */ typedef struct { - int32_t alive_count; /** Number of alive entities. */ - int32_t not_alive_count; /** Number of not alive entities. */ - ecs_size_t bytes_entity_index; /** Bytes used by entity index. */ - ecs_size_t bytes_names; /** Bytes used by names, symbols, aliases. */ - ecs_size_t bytes_doc_strings; /** Bytes used by doc strings. */ + int32_t alive_count; /**< Number of alive entities. */ + int32_t not_alive_count; /**< Number of not alive entities. */ + ecs_size_t bytes_entity_index; /**< Bytes used by entity index. */ + ecs_size_t bytes_names; /**< Bytes used by names, symbols, and aliases. */ + ecs_size_t bytes_doc_strings; /**< Bytes used by doc strings. */ } ecs_entities_memory_t; -/* Component memory. */ +/** Component memory. */ typedef struct { - int32_t instances; /** Total number of component instances. */ - ecs_size_t bytes_table_components; /** Bytes used by table columns. */ - ecs_size_t bytes_table_components_unused; /** Unused bytes in table columns. */ - ecs_size_t bytes_toggle_bitsets; /** Bytes used in bitsets (toggled components). */ - ecs_size_t bytes_sparse_components; /** Bytes used in component sparse sets. */ + int32_t instances; /**< Total number of component instances. */ + ecs_size_t bytes_table_components; /**< Bytes used by table columns. */ + ecs_size_t bytes_table_components_unused; /**< Unused bytes in table columns. */ + ecs_size_t bytes_toggle_bitsets; /**< Bytes used in bitsets (toggled components). */ + ecs_size_t bytes_sparse_components; /**< Bytes used in component sparse sets. */ } ecs_component_memory_t; /** Component index memory. */ typedef struct { - int32_t count; /** Number of component records. */ - ecs_size_t bytes_component_record; /** Bytes used by ecs_component_record_t struct. */ - ecs_size_t bytes_table_cache; /** Bytes used by table cache. */ - ecs_size_t bytes_name_index; /** Bytes used by name index. */ - ecs_size_t bytes_ordered_children; /** Bytes used by ordered children vector. */ - ecs_size_t bytes_reachable_cache; /** Bytes used by reachable cache. */ + int32_t count; /**< Number of component records. */ + ecs_size_t bytes_component_record; /**< Bytes used by ecs_component_record_t struct. */ + ecs_size_t bytes_table_cache; /**< Bytes used by table cache. */ + ecs_size_t bytes_name_index; /**< Bytes used by name index. */ + ecs_size_t bytes_ordered_children; /**< Bytes used by ordered children vector. */ + ecs_size_t bytes_children_table_map; /**< Bytes used by map for non-fragmenting ChildOf table lookups. */ + ecs_size_t bytes_reachable_cache; /**< Bytes used by reachable cache. */ } ecs_component_index_memory_t; /** Query memory. */ typedef struct { - int32_t count; /** Number of queries. */ - int32_t cached_count; /** Number of queries with caches. */ - ecs_size_t bytes_query; /** Bytes used by ecs_query_impl_t struct. */ - ecs_size_t bytes_cache; /** Bytes used by query cache. */ - ecs_size_t bytes_group_by; /** Bytes used by query cache groups (excludes cache elements). */ - ecs_size_t bytes_order_by; /** Bytes used by table_slices. */ - ecs_size_t bytes_plan; /** Bytes used by query plan. */ - ecs_size_t bytes_terms; /** Bytes used by terms array. */ - ecs_size_t bytes_misc; /** Bytes used by remaining misc arrays. */ + int32_t count; /**< Number of queries. */ + int32_t cached_count; /**< Number of queries with caches. */ + ecs_size_t bytes_query; /**< Bytes used by ecs_query_impl_t struct. */ + ecs_size_t bytes_cache; /**< Bytes used by query cache. */ + ecs_size_t bytes_group_by; /**< Bytes used by query cache groups (excludes cache elements). */ + ecs_size_t bytes_order_by; /**< Bytes used by table_slices. */ + ecs_size_t bytes_plan; /**< Bytes used by query plan. */ + ecs_size_t bytes_terms; /**< Bytes used by terms array. */ + ecs_size_t bytes_misc; /**< Bytes used by remaining misc arrays. */ } ecs_query_memory_t; -/** Table memory histogram constants */ +/** Table memory histogram constants. */ #define ECS_TABLE_MEMORY_HISTOGRAM_BUCKET_COUNT 14 #define ECS_TABLE_MEMORY_HISTOGRAM_MAX_COUNT (1 << ECS_TABLE_MEMORY_HISTOGRAM_BUCKET_COUNT) -/** Table memory */ +/** Table memory. */ typedef struct { - int32_t count; /** Total number of tables. */ - int32_t empty_count; /** Number of empty tables. */ - int32_t column_count; /** Number of table columns. */ - ecs_size_t bytes_table; /** Bytes used by ecs_table_t struct. */ - ecs_size_t bytes_type; /** Bytes used by type vector. */ - ecs_size_t bytes_entities; /** Bytes used by entity vectors. */ - ecs_size_t bytes_overrides; /** Bytes used by table overrides. */ - ecs_size_t bytes_columns; /** Bytes used by table columns (excluding component data). */ - ecs_size_t bytes_table_records; /** Bytes used by table records. */ - ecs_size_t bytes_column_map; /** Bytes used by column map. */ - ecs_size_t bytes_component_map; /** Bytes used by component map. */ - ecs_size_t bytes_dirty_state; /** Bytes used by dirty state. */ - ecs_size_t bytes_edges; /** Bytes used by table graph edges. */ + int32_t count; /**< Total number of tables. */ + int32_t empty_count; /**< Number of empty tables. */ + int32_t column_count; /**< Number of table columns. */ + ecs_size_t bytes_table; /**< Bytes used by ecs_table_t struct. */ + ecs_size_t bytes_type; /**< Bytes used by type, columns, and table records. */ + ecs_size_t bytes_entities; /**< Bytes used by entity vectors. */ + ecs_size_t bytes_overrides; /**< Bytes used by table overrides. */ + ecs_size_t bytes_column_map; /**< Bytes used by column map. */ + ecs_size_t bytes_component_map; /**< Bytes used by component map. */ + ecs_size_t bytes_dirty_state; /**< Bytes used by dirty state. */ + ecs_size_t bytes_edges; /**< Bytes used by table graph edges. */ } ecs_table_memory_t; -/** Table size histogram */ +/** Table size histogram. */ typedef struct { - int32_t entity_counts[ECS_TABLE_MEMORY_HISTOGRAM_BUCKET_COUNT]; + int32_t entity_counts[ECS_TABLE_MEMORY_HISTOGRAM_BUCKET_COUNT]; /**< Entity count histogram buckets. */ } ecs_table_histogram_t; -/** Misc memory */ +/** Misc memory. */ typedef struct { - ecs_size_t bytes_world; /** Memory used by world and stages */ - ecs_size_t bytes_observers; /** Memory used by observers. */ - ecs_size_t bytes_systems; /** Memory used by systems (excluding system queries). */ - ecs_size_t bytes_pipelines; /** Memory used by pipelines (excluding pipeline queries). */ - ecs_size_t bytes_table_lookup; /** Bytes used for table lookup data structures. */ - ecs_size_t bytes_component_record_lookup; /** Bytes used for component record lookup data structures. */ - ecs_size_t bytes_locked_components; /** Locked component map. */ - ecs_size_t bytes_type_info; /** Bytes used for storing type information. */ - ecs_size_t bytes_commands; /** Command queue */ - ecs_size_t bytes_rematch_monitor; /** Memory used by monitor used to track rematches */ - ecs_size_t bytes_component_ids; /** Memory used for mapping global to world-local component ids. */ - ecs_size_t bytes_reflection; /** Memory used for component reflection not tracked elsewhere. */ - ecs_size_t bytes_stats; /** Memory used for statistics tracking not tracked elsewhere. */ - ecs_size_t bytes_rest; /** Memory used by REST HTTP server */ + ecs_size_t bytes_world; /**< Memory used by world and stages. */ + ecs_size_t bytes_observers; /**< Memory used by observers. */ + ecs_size_t bytes_systems; /**< Memory used by systems (excluding system queries). */ + ecs_size_t bytes_pipelines; /**< Memory used by pipelines (excluding pipeline queries). */ + ecs_size_t bytes_table_lookup; /**< Bytes used for table lookup data structures. */ + ecs_size_t bytes_component_record_lookup; /**< Bytes used for component record lookup data structures. */ + ecs_size_t bytes_locked_components; /**< Locked component map. */ + ecs_size_t bytes_type_info; /**< Bytes used for storing type information. */ + ecs_size_t bytes_commands; /**< Command queue. */ + ecs_size_t bytes_rematch_monitor; /**< Memory used by monitor used to track rematches. */ + ecs_size_t bytes_component_ids; /**< Memory used for mapping global to world-local component ids. */ + ecs_size_t bytes_reflection; /**< Memory used for component reflection not tracked elsewhere. */ + ecs_size_t bytes_tree_spawner; /**< Memory used for tree (prefab) spawners. */ + ecs_size_t bytes_prefab_child_indices; /**< Memory used by map that stores indices for ordered prefab children. */ + ecs_size_t bytes_stats; /**< Memory used for statistics tracking not tracked elsewhere. */ + ecs_size_t bytes_rest; /**< Memory used by REST HTTP server. */ } ecs_misc_memory_t; /** Allocator memory. - * Returns memory that's allocated by allocators but not in use. */ + * Memory that is allocated by allocators but not in use. */ typedef struct { - ecs_size_t bytes_graph_edge; /** Graph edge allocator. */ - ecs_size_t bytes_component_record; /** Component record allocator. */ - ecs_size_t bytes_pair_record; /** Pair record allocator. */ - ecs_size_t bytes_table_diff; /** Table diff allocator. */ - ecs_size_t bytes_sparse_chunk; /** Sparse chunk allocator. */ - ecs_size_t bytes_allocator; /** Generic allocator. */ - ecs_size_t bytes_stack_allocator; /** Stack allocator. */ - ecs_size_t bytes_cmd_entry_chunk; /** Command batching entry chunk allocator. */ - ecs_size_t bytes_query_impl; /** Query struct allocator. */ - ecs_size_t bytes_query_cache; /** Query cache struct allocator. */ - ecs_size_t bytes_misc; /** Miscalleneous allocators */ + ecs_size_t bytes_graph_edge; /**< Graph edge allocator. */ + ecs_size_t bytes_component_record; /**< Component record allocator. */ + ecs_size_t bytes_pair_record; /**< Pair record allocator. */ + ecs_size_t bytes_table_diff; /**< Table diff allocator. */ + ecs_size_t bytes_sparse_chunk; /**< Sparse chunk allocator. */ + ecs_size_t bytes_allocator; /**< Generic allocator. */ + ecs_size_t bytes_stack_allocator; /**< Stack allocator. */ + ecs_size_t bytes_cmd_entry_chunk; /**< Command batching entry chunk allocator. */ + ecs_size_t bytes_query_impl; /**< Query struct allocator. */ + ecs_size_t bytes_query_cache; /**< Query cache struct allocator. */ + ecs_size_t bytes_misc; /**< Miscellaneous allocators. */ } ecs_allocator_memory_t; /** Component with memory statistics. */ typedef struct { - ecs_entities_memory_t entities; - ecs_component_memory_t components; - ecs_component_index_memory_t component_index; - ecs_query_memory_t queries; - ecs_table_memory_t tables; - ecs_table_histogram_t table_histogram; - ecs_misc_memory_t misc; - ecs_allocator_memory_t allocators; - double collection_time; /** Time spent collecting statistics. */ + ecs_entities_memory_t entities; /**< Entity memory. */ + ecs_component_memory_t components; /**< Component memory. */ + ecs_component_index_memory_t component_index; /**< Component index memory. */ + ecs_query_memory_t queries; /**< Query memory. */ + ecs_table_memory_t tables; /**< Table memory. */ + ecs_table_histogram_t table_histogram; /**< Table size histogram. */ + ecs_misc_memory_t misc; /**< Miscellaneous memory. */ + ecs_allocator_memory_t allocators; /**< Allocator memory. */ + double collection_time; /**< Time spent collecting statistics. */ } EcsWorldMemory; -/** Memory statistics getters. */ /** Get memory usage statistics for the entity index. * * @param world The world. @@ -13857,10 +15501,10 @@ FLECS_API ecs_table_histogram_t ecs_table_histogram_get( const ecs_world_t *world); -/** Get memory usage statistics for commands. - * +/** Get memory usage statistics for miscellaneous allocations. + * * @param world The world. - * @return Memory statistics for commands. + * @return Memory statistics for miscellaneous allocations. */ FLECS_API ecs_misc_memory_t ecs_misc_memory_get( @@ -13876,8 +15520,9 @@ ecs_allocator_memory_t ecs_allocator_memory_get( const ecs_world_t *world); /** Get total memory used by world. - * + * * @param world The world. + * @return Total memory used in bytes. */ FLECS_API ecs_size_t ecs_memory_get( @@ -13952,19 +15597,19 @@ extern "C" { /** Flecs metrics module. */ FLECS_API extern ECS_COMPONENT_DECLARE(FlecsMetrics); -/** Tag added to metrics, and used as first element of metric kind pair. */ +/** Tag added to metrics, and used as the first element of the metric kind pair. */ FLECS_API extern ECS_TAG_DECLARE(EcsMetric); -/** Metric that has monotonically increasing value. */ +/** Metric that has a monotonically increasing value. */ FLECS_API extern ECS_TAG_DECLARE(EcsCounter); -/** Counter metric that is auto-incremented by source value. */ +/** Counter metric that is auto-incremented by the source value. */ FLECS_API extern ECS_TAG_DECLARE(EcsCounterIncrement); -/** Counter metric that counts the number of entities with an id. */ +/** Counter metric that counts the number of entities with an ID. */ FLECS_API extern ECS_TAG_DECLARE(EcsCounterId); -/** Metric that represents current value. */ +/** Metric that represents the current value. */ FLECS_API extern ECS_TAG_DECLARE(EcsGauge); /** Tag added to metric instances. */ @@ -13986,36 +15631,36 @@ typedef struct EcsMetricSource { ecs_entity_t entity; } EcsMetricSource; -/** Used with ecs_metric_init to create metric. */ +/** Used with ecs_metric_init() to create metric. */ typedef struct ecs_metric_desc_t { - int32_t _canary; + int32_t _canary; /**< Used for validity testing. Do not set. */ - /** Entity associated with metric */ + /** Entity associated with metric. */ ecs_entity_t entity; /** Entity associated with member that stores metric value. Must not be set * at the same time as id. Cannot be combined with EcsCounterId. */ ecs_entity_t member; - /* Member dot expression. Can be used instead of member and supports nested + /** Member dot expression. Can be used instead of member and supports nested * members. Must be set together with id and should not be set at the same * time as member. */ const char *dotmember; - /** Tracks whether entities have the specified component id. Must not be set + /** Tracks whether entities have the specified component ID. Must not be set * at the same time as member. */ ecs_id_t id; /** If id is a (R, *) wildcard and relationship R has the OneOf property, * setting this value to true will track individual targets. - * If the kind is EcsCountId and the id is a (R, *) wildcard, this value + * If the kind is EcsCounterId and the id is a (R, *) wildcard, this value * will create a metric per target. */ bool targets; - /** Must be EcsGauge, EcsCounter, EcsCounterIncrement or EcsCounterId */ + /** Must be EcsGauge, EcsCounter, EcsCounterIncrement, or EcsCounterId. */ ecs_entity_t kind; - /** Description of metric. Will only be set if FLECS_DOC addon is enabled */ + /** Description of metric. Will only be set if FLECS_DOC addon is enabled. */ const char *brief; } ecs_metric_desc_t; @@ -14036,12 +15681,12 @@ typedef struct ecs_metric_desc_t { * example "velocity". A counter metric represents a value that is monotonically * increasing, for example "miles driven". * - * There are three different kinds of counter metric kinds: + * There are three different counter metric kinds: * - EcsCounter * When combined with a member, this will store the actual value of the member * in the metric. This is useful for values that are already counters, such as * a MilesDriven component. - * This kind creates a metric per entity that has the member/id. + * This kind creates a metric per entity that has the member or ID. * * - EcsCounterIncrement * When combined with a member, this will increment the value of the metric by @@ -14051,8 +15696,8 @@ typedef struct ecs_metric_desc_t { * * - EcsCounterId * This metric kind will count the number of entities with a specific - * (component) id. This kind creates a single metric instance for regular ids, - * and a metric instance per target for wildcard ids when targets is set. + * (component) ID. This kind creates a single metric instance for regular IDs, + * and a metric instance per target for wildcard IDs when targets is set. * * @param world The world. * @param desc Metric description. @@ -14135,19 +15780,20 @@ void FlecsMetricsImport( extern "C" { #endif +/** Maximum number of severity filters per alert. */ #define ECS_ALERT_MAX_SEVERITY_FILTERS (4) -/** Module id. */ +/** Module ID. */ FLECS_API extern ECS_COMPONENT_DECLARE(FlecsAlerts); -/* Module components */ +/** Module components. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsAlert); /**< Component added to alert, and used as first element of alert severity pair. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsAlert); /**< Component added to alert, and used as the first element of the alert severity pair. */ FLECS_API extern ECS_COMPONENT_DECLARE(EcsAlertInstance); /**< Component added to alert instance. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsAlertsActive); /**< Component added to alert source which tracks how many active alerts there are. */ -FLECS_API extern ECS_COMPONENT_DECLARE(EcsAlertTimeout); /**< Component added to alert which tracks how long an alert has been inactive. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsAlertsActive); /**< Component added to alert source, which tracks how many active alerts there are. */ +FLECS_API extern ECS_COMPONENT_DECLARE(EcsAlertTimeout); /**< Component added to alert, which tracks how long an alert has been inactive. */ -/* Alert severity tags */ +/** Alert severity tags. */ FLECS_API extern ECS_TAG_DECLARE(EcsAlertInfo); /**< Info alert severity. */ FLECS_API extern ECS_TAG_DECLARE(EcsAlertWarning); /**< Warning alert severity. */ FLECS_API extern ECS_TAG_DECLARE(EcsAlertError); /**< Error alert severity. */ @@ -14155,15 +15801,15 @@ FLECS_API extern ECS_TAG_DECLARE(EcsAlertCritical); /**< Critical alert s /** Component added to alert instance. */ typedef struct EcsAlertInstance { - char *message; /**< Generated alert message */ + char *message; /**< Generated alert message. */ } EcsAlertInstance; /** Map with active alerts for entity. */ typedef struct EcsAlertsActive { - int32_t info_count; /**< Number of alerts for source with info severity */ - int32_t warning_count; /**< Number of alerts for source with warning severity */ - int32_t error_count; /**< Number of alerts for source with error severity */ - ecs_map_t alerts; + int32_t info_count; /**< Number of alerts for source with info severity. */ + int32_t warning_count; /**< Number of alerts for source with warning severity. */ + int32_t error_count; /**< Number of alerts for source with error severity. */ + ecs_map_t alerts; /**< Map of active alerts for entity. */ } EcsAlertsActive; /** Alert severity filter. @@ -14173,18 +15819,18 @@ typedef struct EcsAlertsActive { * severity of an alert from Warning to Error. */ typedef struct ecs_alert_severity_filter_t { - ecs_entity_t severity; /* Severity kind */ - ecs_id_t with; /* Component to match */ - const char *var; /* Variable to match component on. Do not include the - * '$' character. Leave to NULL for $this. */ - int32_t _var_index; /* Index of variable in filter (do not set) */ + ecs_entity_t severity; /**< Severity kind. */ + ecs_id_t with; /**< Component to match. */ + const char *var; /**< Variable to match component on. Do not include the + * '$' character. Leave as NULL for $this. */ + int32_t _var_index; /**< Index of variable in query (do not set). */ } ecs_alert_severity_filter_t; /** Alert descriptor, used with ecs_alert_init(). */ typedef struct ecs_alert_desc_t { - int32_t _canary; + int32_t _canary; /**< Used for validity testing. Do not set. */ - /** Entity associated with alert */ + /** Entity associated with alert. */ ecs_entity_t entity; /** Alert query. An alert will be created for each entity that matches the @@ -14203,13 +15849,13 @@ typedef struct ecs_alert_desc_t { */ const char *message; - /** User friendly name. Will only be set if FLECS_DOC addon is enabled. */ + /** User-friendly name. Will only be set if FLECS_DOC addon is enabled. */ const char *doc_name; - /** Description of alert. Will only be set if FLECS_DOC addon is enabled */ + /** Description of alert. Will only be set if FLECS_DOC addon is enabled. */ const char *brief; - /** Metric kind. Must be EcsAlertInfo, EcsAlertWarning, EcsAlertError or + /** Alert severity. Must be EcsAlertInfo, EcsAlertWarning, EcsAlertError, or * EcsAlertCritical. Defaults to EcsAlertError. */ ecs_entity_t severity; @@ -14221,20 +15867,20 @@ typedef struct ecs_alert_desc_t { /** The retain period specifies how long an alert must be inactive before it * is cleared. This makes it easier to track noisy alerts. While an alert is - * inactive its duration won't increase. + * inactive, its duration won't increase. * When the retain period is 0, the alert will clear immediately after it no * longer matches the alert query. */ ecs_ftime_t retain_period; - /** Alert when member value is out of range. Uses the warning/error ranges + /** Alert when member value is out of range. Uses the warning and error ranges * assigned to the member in the MemberRanges component (optional). */ ecs_entity_t member; - /** (Component) id of member to monitor. If left to 0 this will be set to + /** (Component) ID of member to monitor. If left to 0, this will be set to * the parent entity of the member (optional). */ ecs_id_t id; - /** Variable from which to fetch the member (optional). When left to NULL + /** Variable from which to fetch the member (optional). When left to NULL, * 'id' will be obtained from $this. */ const char *var; } ecs_alert_desc_t; @@ -14340,7 +15986,7 @@ void FlecsAlertsImport( * @brief JSON parser addon. * * Parse expression strings into component values. Entity identifiers, - * enumerations and bitmasks are encoded as strings. + * enumerations, and bitmasks are encoded as strings. * * See docs/FlecsRemoteApi.md for a description of the JSON format. */ @@ -14356,7 +16002,7 @@ void FlecsAlertsImport( #endif #ifndef FLECS_QUERY_DSL -#define FLECS_QUERY_DSL /* For parsing component id expressions */ +#define FLECS_QUERY_DSL /* For parsing component ID expressions */ #endif #ifndef FLECS_JSON_H @@ -14365,7 +16011,7 @@ void FlecsAlertsImport( /** * @defgroup c_addons_json Json * @ingroup c_addons - * Functions for serializing to/from JSON. + * Functions for serializing to and from JSON. * * @{ */ @@ -14376,16 +16022,16 @@ extern "C" { /** Used with ecs_ptr_from_json(), ecs_entity_from_json(). */ typedef struct ecs_from_json_desc_t { - const char *name; /**< Name of expression (used for logging) */ - const char *expr; /**< Full expression (used for logging) */ + const char *name; /**< Name of the expression (used for logging). */ + const char *expr; /**< Full expression (used for logging). */ /** Callback that allows for specifying a custom lookup function. The - * default behavior uses ecs_lookup() */ + * default behavior uses ecs_lookup(). */ ecs_entity_t (*lookup_action)( ecs_world_t*, const char *value, void *ctx); - void *lookup_ctx; + void *lookup_ctx; /**< Context for lookup_action. */ /** Require components to be registered with reflection data. When not * in strict mode, values for components without reflection are ignored. */ @@ -14400,7 +16046,7 @@ typedef struct ecs_from_json_desc_t { * @param type The type of the expression to parse. * @param ptr Pointer to the memory to write to. * @param json The JSON expression to parse. - * @param desc Configuration parameters for deserializer. + * @param desc Configuration parameters for the deserializer. * @return Pointer to the character after the last one read, or NULL if failed. */ FLECS_API @@ -14411,14 +16057,14 @@ const char* ecs_ptr_from_json( const char *json, const ecs_from_json_desc_t *desc); -/** Parse JSON object with multiple component values into entity. The format - * is the same as the one outputted by ecs_entity_to_json(), but at the moment - * only supports the "ids" and "values" member. +/** Parse JSON object with multiple component values into an entity. The format + * is the same as the one output by ecs_entity_to_json(), but at the moment + * only supports the "ids" and "values" members. * * @param world The world. - * @param entity The entity to serialize to. + * @param entity The entity to deserialize into. * @param json The JSON expression to parse (see entity in JSON format manual). - * @param desc Configuration parameters for deserializer. + * @param desc Configuration parameters for the deserializer. * @return Pointer to the character after the last one read, or NULL if failed. */ FLECS_API @@ -14429,7 +16075,7 @@ const char* ecs_entity_from_json( const ecs_from_json_desc_t *desc); /** Parse JSON object with multiple entities into the world. The format is the - * same as the one outputted by ecs_world_to_json(). + * same as the one output by ecs_world_to_json(). * * @param world The world. * @param json The JSON expression to parse (see iterator in JSON format manual). @@ -14442,7 +16088,7 @@ const char* ecs_world_from_json( const char *json, const ecs_from_json_desc_t *desc); -/** Same as ecs_world_from_json(), but loads JSON from file. +/** Same as ecs_world_from_json(), but loads JSON from a file. * * @param world The world. * @param filename The file from which to load the JSON. @@ -14460,7 +16106,7 @@ const char* ecs_world_from_json_file( * memory pointed to must be large enough to contain a value of the used type. * * If count is 0, the function will serialize a single value, not wrapped in - * array brackets. If count is >= 1, the operation will serialize values to a + * array brackets. If count is >= 1, the operation will serialize values to * a comma-separated list inside of array brackets. * * @param world The world. @@ -14525,7 +16171,7 @@ int ecs_ptr_to_json_buf( ecs_strbuf_t *buf_out); /** Serialize type info to JSON. - * This serializes type information to JSON, and can be used to store/transmit + * This serializes type information to JSON, and can be used to store or transmit * the structure of a (component) value. * * If the provided type does not have reflection data, "0" will be returned. @@ -14553,19 +16199,19 @@ int ecs_type_info_to_json_buf( ecs_entity_t type, ecs_strbuf_t *buf_out); -/** Used with ecs_iter_to_json(). */ +/** Used with ecs_entity_to_json(). */ typedef struct ecs_entity_to_json_desc_t { - bool serialize_entity_id; /**< Serialize entity id */ - bool serialize_doc; /**< Serialize doc attributes */ - bool serialize_full_paths; /**< Serialize full paths for tags, components and pairs */ - bool serialize_inherited; /**< Serialize base components */ - bool serialize_values; /**< Serialize component values */ - bool serialize_builtin; /**< Serialize builtin data as components (e.g. "name", "parent") */ - bool serialize_type_info; /**< Serialize type info (requires serialize_values) */ - bool serialize_alerts; /**< Serialize active alerts for entity */ - ecs_entity_t serialize_refs; /**< Serialize references (incoming edges) for relationship */ - bool serialize_matches; /**< Serialize which queries entity matches with */ - /** Callback for if the component should be serialized */ + bool serialize_entity_id; /**< Serialize entity ID. */ + bool serialize_doc; /**< Serialize doc attributes. */ + bool serialize_full_paths; /**< Serialize full paths for tags, components, and pairs. */ + bool serialize_inherited; /**< Serialize base components. */ + bool serialize_values; /**< Serialize component values. */ + bool serialize_builtin; /**< Serialize built-in data as components (e.g., "name", "parent"). */ + bool serialize_type_info; /**< Serialize type info (requires serialize_values). */ + bool serialize_alerts; /**< Serialize active alerts for the entity. */ + ecs_entity_t serialize_refs; /**< Serialize references (incoming edges) for a relationship. */ + bool serialize_matches; /**< Serialize which queries the entity matches with. */ + /** Callback to determine if a component should be serialized. */ bool (*component_filter) (const ecs_world_t *, ecs_entity_t); } ecs_entity_to_json_desc_t; @@ -14609,11 +16255,12 @@ typedef struct ecs_entity_to_json_desc_t { * * @param world The world. * @param entity The entity to serialize to JSON. + * @param desc Serialization parameters. * @return A JSON string with the serialized entity data, or NULL if failed. */ FLECS_API char* ecs_entity_to_json( - const ecs_world_t *world, + ecs_world_t *world, ecs_entity_t entity, const ecs_entity_to_json_desc_t *desc); @@ -14623,35 +16270,38 @@ char* ecs_entity_to_json( * @param world The world. * @param entity The entity to serialize. * @param buf_out The strbuf to append the string to. + * @param desc Serialization parameters. * @return Zero if success, non-zero if failed. */ FLECS_API int ecs_entity_to_json_buf( - const ecs_world_t *world, + ecs_world_t *world, ecs_entity_t entity, ecs_strbuf_t *buf_out, const ecs_entity_to_json_desc_t *desc); /** Used with ecs_iter_to_json(). */ typedef struct ecs_iter_to_json_desc_t { - bool serialize_entity_ids; /**< Serialize entity ids */ - bool serialize_values; /**< Serialize component values */ - bool serialize_builtin; /**< Serialize builtin data as components (e.g. "name", "parent") */ - bool serialize_doc; /**< Serialize doc attributes */ - bool serialize_full_paths; /**< Serialize full paths for tags, components and pairs */ - bool serialize_fields; /**< Serialize field data */ - bool serialize_inherited; /**< Serialize inherited components */ - bool serialize_table; /**< Serialize entire table vs. matched components */ - bool serialize_type_info; /**< Serialize type information */ - bool serialize_field_info; /**< Serialize metadata for fields returned by query */ - bool serialize_query_info; /**< Serialize query terms */ - bool serialize_query_plan; /**< Serialize query plan */ - bool serialize_query_profile; /**< Profile query performance */ - bool dont_serialize_results; /**< If true, query won't be evaluated */ - bool serialize_alerts; /**< Serialize active alerts for entity */ - ecs_entity_t serialize_refs; /**< Serialize references (incoming edges) for relationship */ - bool serialize_matches; /**< Serialize which queries entity matches with */ - /** Callback for if the component should be serialized */ + bool serialize_entity_ids; /**< Serialize entity IDs. */ + bool serialize_values; /**< Serialize component values. */ + bool serialize_builtin; /**< Serialize built-in data as components (e.g., "name", "parent"). */ + bool serialize_doc; /**< Serialize doc attributes. */ + bool serialize_full_paths; /**< Serialize full paths for tags, components, and pairs. */ + bool serialize_fields; /**< Serialize field data. */ + bool serialize_inherited; /**< Serialize inherited components. */ + bool serialize_table; /**< Serialize entire table vs. matched components. */ + bool serialize_type_info; /**< Serialize type information. */ + bool serialize_field_info; /**< Serialize metadata for fields returned by the query. */ + bool serialize_query_info; /**< Serialize query terms. */ + bool serialize_query_plan; /**< Serialize query plan. */ + bool serialize_query_profile; /**< Profile query performance. */ + bool dont_serialize_results; /**< If true, the query will not be evaluated. */ + bool serialize_alerts; /**< Serialize active alerts for the entity. */ + ecs_entity_t serialize_refs; /**< Serialize references (incoming edges) for a relationship. */ + bool serialize_matches; /**< Serialize which queries the entity matches with. */ + bool serialize_parents_before_children; /**< If the query matches both children and parent, serialize the parent before children. */ + + /** Callback to determine if a component should be serialized. */ bool (*component_filter) (const ecs_world_t *, ecs_entity_t); ecs_poly_t *query; /**< Query object (required for serialize_query_[plan|profile]). */ @@ -14677,6 +16327,7 @@ typedef struct ecs_iter_to_json_desc_t { .serialize_alerts = false, \ .serialize_refs = false, \ .serialize_matches = false, \ + .serialize_parents_before_children = false,\ .component_filter = NULL, \ .query = NULL \ } @@ -14699,6 +16350,7 @@ typedef struct ecs_iter_to_json_desc_t { false, \ false, \ false, \ + false, \ nullptr, \ nullptr \ } @@ -14709,6 +16361,7 @@ typedef struct ecs_iter_to_json_desc_t { * to JSON. The function accepts iterators from any source. * * @param iter The iterator to serialize to JSON. + * @param desc Serialization parameters. * @return A JSON string with the serialized iterator data, or NULL if failed. */ FLECS_API @@ -14721,6 +16374,7 @@ char* ecs_iter_to_json( * * @param iter The iterator to serialize. * @param buf_out The strbuf to append the string to. + * @param desc Serialization parameters. * @return Zero if success, non-zero if failed. */ FLECS_API @@ -14729,27 +16383,28 @@ int ecs_iter_to_json_buf( ecs_strbuf_t *buf_out, const ecs_iter_to_json_desc_t *desc); -/** Used with ecs_iter_to_json(). */ +/** Used with ecs_world_to_json(). */ typedef struct ecs_world_to_json_desc_t { - bool serialize_builtin; /**< Exclude flecs modules & contents */ - bool serialize_modules; /**< Exclude modules & contents */ + bool serialize_builtin; /**< Serialize Flecs built-in modules and contents. */ + bool serialize_modules; /**< Serialize modules and contents. */ } ecs_world_to_json_desc_t; /** Serialize world into JSON string. - * This operation iterates the contents of the world to JSON. The operation is + * This operation serializes the contents of the world to JSON. The operation is * equivalent to the following code: * * @code - * ecs_query_t *f = ecs_query(world, { + * ecs_query_t *q = ecs_query(world, { * .terms = {{ .id = EcsAny }} * }); * - * ecs_iter_t it = ecs_query_init(world, &f); + * ecs_iter_t it = ecs_query_iter(world, q); * ecs_iter_to_json_desc_t desc = { .serialize_table = true }; - * ecs_iter_to_json(iter, &desc); + * ecs_iter_to_json(&it, &desc); * @endcode * * @param world The world to serialize. + * @param desc Serialization parameters. * @return A JSON string with the serialized iterator data, or NULL if failed. */ FLECS_API @@ -14762,6 +16417,7 @@ char* ecs_world_to_json( * * @param world The world to serialize. * @param buf_out The strbuf to append the string to. + * @param desc Serialization parameters. * @return Zero if success, non-zero if failed. */ FLECS_API @@ -14790,7 +16446,7 @@ int ecs_world_to_json_buf( * @file addons/units.h * @brief Units module. * - * Builtin standard units. The units addon is not imported by default, even if + * Built-in standard units. The units addon is not imported by default, even if * the addon is included in the build. To import the module, do: * * In C: @@ -14838,7 +16494,7 @@ extern "C" { /** * @defgroup c_addons_units_prefixes Prefixes * @ingroup c_addons_units - * Prefixes to indicate unit count (e.g. Kilo, Mega) + * Prefixes to indicate unit count (e.g., Kilo, Mega). * * @{ */ @@ -15060,7 +16716,7 @@ FLECS_API extern ecs_entity_t EcsGigaBytesPerSecond; /**< GigaBytesPerSecond /** @} */ /** - * @defgroup c_addons_units_duration Duration + * @defgroup c_addons_units_angle Angle * @ingroup c_addons_units * @{ */ @@ -15072,7 +16728,7 @@ FLECS_API extern ecs_entity_t EcsDegrees; /**< Degrees unit. */ /** @} */ /** - * @defgroup c_addons_units_angle Angle + * @defgroup c_addons_units_frequency Frequency * @ingroup c_addons_units * @{ */ @@ -15151,7 +16807,7 @@ void FlecsUnitsImport( #endif /** * @file addons/script_math.h - * @brief Math functions for flecs script. + * @brief Math functions for Flecs script. */ #ifdef FLECS_SCRIPT_MATH @@ -15163,7 +16819,7 @@ void FlecsUnitsImport( /** * @defgroup c_addons_script_math Script Math * @ingroup c_addons - * Math functions for flecs script. + * Math functions for Flecs script. * @{ */ @@ -15177,10 +16833,10 @@ extern "C" { FLECS_API extern ECS_COMPONENT_DECLARE(EcsScriptRng); -/* Randon number generator */ +/** Random number generator. */ typedef struct { - uint64_t seed; - void *impl; + uint64_t seed; /**< Random seed value. */ + void *impl; /**< Implementation data. */ } EcsScriptRng; /** Script math import function. @@ -15230,7 +16886,7 @@ void FlecsScriptMathImport( * @file addons/script.h * @brief Flecs script module. * - * For script, see examples/script. + * For script examples, see examples/script. */ #ifdef FLECS_SCRIPT @@ -15238,7 +16894,7 @@ void FlecsScriptMathImport( /** * @defgroup c_addons_script Flecs script * @ingroup c_addons - * DSL for loading scenes, assets and configuration. + * DSL for loading scenes, assets, and configuration. * * @{ */ @@ -15264,6 +16920,9 @@ extern "C" { #define FLECS_SCRIPT_FUNCTION_ARGS_MAX (16) +/* Must be the same as EcsPrimitiveKindLast */ +#define FLECS_SCRIPT_VECTOR_FUNCTION_COUNT (18) + FLECS_API extern ECS_COMPONENT_DECLARE(EcsScript); @@ -15279,58 +16938,61 @@ extern ECS_COMPONENT_DECLARE(EcsScriptFunction); FLECS_API extern ECS_COMPONENT_DECLARE(EcsScriptMethod); +FLECS_API +extern ECS_DECLARE(EcsScriptVectorType); + /* Script template. */ typedef struct ecs_script_template_t ecs_script_template_t; /** Script variable. */ typedef struct ecs_script_var_t { - const char *name; - ecs_value_t value; - const ecs_type_info_t *type_info; - int32_t sp; - bool is_const; + const char *name; /**< Variable name. */ + ecs_value_t value; /**< Variable value. */ + const ecs_type_info_t *type_info; /**< Type information. */ + int32_t sp; /**< Stack pointer. */ + bool is_const; /**< Whether the variable is constant. */ } ecs_script_var_t; /** Script variable scope. */ typedef struct ecs_script_vars_t { - struct ecs_script_vars_t *parent; - int32_t sp; + struct ecs_script_vars_t *parent; /**< Parent variable scope. */ + int32_t sp; /**< Stack pointer for this scope. */ - ecs_hashmap_t var_index; - ecs_vec_t vars; + ecs_hashmap_t var_index; /**< Index for variable name lookups. */ + ecs_vec_t vars; /**< Vector of variables in this scope. */ - const ecs_world_t *world; - struct ecs_stack_t *stack; - ecs_stack_cursor_t *cursor; - ecs_allocator_t *allocator; + const ecs_world_t *world; /**< The world. */ + struct ecs_stack_t *stack; /**< Stack allocator for variable storage. */ + ecs_stack_cursor_t *cursor; /**< Cursor into the stack allocator. */ + ecs_allocator_t *allocator; /**< General purpose allocator. */ } ecs_script_vars_t; /** Script object. */ typedef struct ecs_script_t { - ecs_world_t *world; - const char *name; - const char *code; + ecs_world_t *world; /**< The world. */ + const char *name; /**< Script name. */ + const char *code; /**< Script source code. */ } ecs_script_t; -/* Runtime for executing scripts */ +/** Runtime for executing scripts. */ typedef struct ecs_script_runtime_t ecs_script_runtime_t; /** Script component. * This component is added to the entities of managed scripts and templates. */ typedef struct EcsScript { - char *filename; - char *code; - char *error; /* Set if script evaluation had errors */ - ecs_script_t *script; - ecs_script_template_t *template_; /* Only set for template scripts */ + char *filename; /**< Script filename. */ + char *code; /**< Script source code. */ + char *error; /**< Set if script evaluation had errors. */ + ecs_script_t *script; /**< Parsed script object. */ + ecs_script_template_t *template_; /**< Only set for template scripts. */ } EcsScript; /** Script function context. */ typedef struct ecs_function_ctx_t { - ecs_world_t *world; - ecs_entity_t function; - void *ctx; + ecs_world_t *world; /**< The world. */ + ecs_entity_t function; /**< The function entity. */ + void *ctx; /**< User context. */ } ecs_function_ctx_t; /** Script function callback. */ @@ -15340,10 +17002,18 @@ typedef void(*ecs_function_callback_t)( const ecs_value_t *argv, ecs_value_t *result); +/** Script vector function callback. */ +typedef void(*ecs_vector_function_callback_t)( + const ecs_function_ctx_t *ctx, + int32_t argc, + const ecs_value_t *argv, + ecs_value_t *result, + int32_t elem_count); + /** Function argument type. */ typedef struct ecs_script_parameter_t { - const char *name; - ecs_entity_t type; + const char *name; /**< Parameter name. */ + ecs_entity_t type; /**< Parameter type. */ } ecs_script_parameter_t; /** Const component. @@ -15354,39 +17024,37 @@ typedef struct EcsScriptConstVar { const ecs_type_info_t *type_info; } EcsScriptConstVar; -/** Function component. - * This component describes a function that can be called from a script. - */ -typedef struct EcsScriptFunction { +struct ecs_script_function_t { ecs_entity_t return_type; ecs_vec_t params; /* vec */ ecs_function_callback_t callback; + ecs_vector_function_callback_t vector_callbacks[FLECS_SCRIPT_VECTOR_FUNCTION_COUNT]; void *ctx; -} EcsScriptFunction; +}; + +/** Function component. + * This component describes a function that can be called from a script. + */ +typedef struct ecs_script_function_t EcsScriptFunction; /** Method component. * This component describes a method that can be called from a script. Methods * are functions that can be called on instances of a type. A method entity is * stored in the scope of the type it belongs to. */ -typedef struct EcsScriptMethod { - ecs_entity_t return_type; - ecs_vec_t params; /* vec */ - ecs_function_callback_t callback; - void *ctx; -} EcsScriptMethod; +typedef struct ecs_script_function_t EcsScriptMethod; -/* Parsing & running scripts */ +/* Parsing and running scripts */ -/** Used with ecs_script_parse() and ecs_script_eval() */ +/** Used with ecs_script_parse() and ecs_script_eval(). */ typedef struct ecs_script_eval_desc_t { - ecs_script_vars_t *vars; /**< Variables used by script */ - ecs_script_runtime_t *runtime; /**< Reusable runtime (optional) */ + ecs_script_vars_t *vars; /**< Variables used by script. */ + ecs_script_runtime_t *runtime; /**< Reusable runtime (optional). */ } ecs_script_eval_desc_t; /** Used to capture error output from script evaluation. */ typedef struct ecs_script_eval_result_t { - char *error; + char *error; /**< Error message, or NULL if no error. Must be freed by the application. */ } ecs_script_eval_result_t; /** Parse script. @@ -15402,7 +17070,7 @@ typedef struct ecs_script_eval_result_t { * by the application. * * @param world The world. - * @param name Name of the script (typically a file/module name). + * @param name Name of the script (typically a file or module name). * @param code The script code. * @param desc Parameters for script runtime. * @param result Output of script evaluation. @@ -15429,6 +17097,7 @@ ecs_script_t* ecs_script_parse( * * @param script The script. * @param desc Parameters for script runtime. + * @param result Output of script evaluation (optional). * @return Zero if success, non-zero if failed. */ FLECS_API @@ -15463,6 +17132,7 @@ void ecs_script_free( * @param world The world. * @param name The script name (typically the file). * @param code The script. + * @param result Output of script evaluation (optional). * @return Zero if success, non-zero otherwise. */ FLECS_API @@ -15488,7 +17158,7 @@ int ecs_script_run_file( /** Create runtime for script. * A script runtime is a container for any data created during script - * evaluation. By default calling ecs_script_run() or ecs_script_eval() will + * evaluation. By default, calling ecs_script_run() or ecs_script_eval() will * create a runtime on the spot. A runtime can be created in advance and reused * across multiple script evaluations to improve performance. * @@ -15514,9 +17184,10 @@ void ecs_script_runtime_free( /** Convert script AST to string. * This operation converts the script abstract syntax tree to a string, which * can be used to debug a script. - * + * * @param script The script. * @param buf The buffer to write to. + * @param colors Whether to include ANSI color codes in the output. * @return Zero if success, non-zero if failed. */ FLECS_API @@ -15528,8 +17199,9 @@ int ecs_script_ast_to_buf( /** Convert script AST to string. * This operation converts the script abstract syntax tree to a string, which * can be used to debug a script. - * + * * @param script The script. + * @param colors Whether to include ANSI color codes in the output. * @return The string if success, NULL if failed. */ FLECS_API @@ -15540,11 +17212,11 @@ char* ecs_script_ast_to_str( /* Managed scripts (script associated with entity that outlives the function) */ -/** Used with ecs_script_init() */ +/** Used with ecs_script_init(). */ typedef struct ecs_script_desc_t { - ecs_entity_t entity; /* Set to customize entity handle associated with script */ - const char *filename; /* Set to load script from file */ - const char *code; /* Set to parse script from string */ + ecs_entity_t entity; /**< Set to customize entity handle associated with script. */ + const char *filename; /**< Set to load script from file. */ + const char *code; /**< Set to parse script from string. */ } ecs_script_desc_t; /** Load managed script. @@ -15556,6 +17228,7 @@ typedef struct ecs_script_desc_t { * * @param world The world. * @param desc Script descriptor. + * @return The script entity. */ FLECS_API ecs_entity_t ecs_script_init( @@ -15569,8 +17242,9 @@ ecs_entity_t ecs_script_init( * * @param world The world. * @param script The script entity. - * @param instance An template instance (optional). + * @param instance A template instance (optional). * @param code The script code. + * @return Zero if success, non-zero if failed. */ FLECS_API int ecs_script_update( @@ -15603,12 +17277,13 @@ void ecs_script_clear( * Use the `ecs_script_vars_push()` and `ecs_script_vars_pop()` functions to * push and pop variable scopes. * - * When a variable contains allocated resources (e.g. a string), its resources + * When a variable contains allocated resources (e.g., a string), its resources * will be freed when `ecs_script_vars_pop()` is called on the scope, the * ecs_script_vars_t::type_info field is initialized for the variable, and * `ecs_type_info_t::hooks::dtor` is set. * * @param world The world. + * @return The new root variable scope. */ FLECS_API ecs_script_vars_t* ecs_script_vars_init( @@ -15724,7 +17399,7 @@ ecs_script_var_t* ecs_script_vars_from_sp( int32_t sp); /** Print variables. - * This operation prints all variables in the vars scope and parent scopes.asm + * This operation prints all variables in the vars scope and parent scopes. * * @param vars The variable scope. */ @@ -15745,13 +17420,13 @@ void ecs_script_vars_set_size( ecs_script_vars_t *vars, int32_t count); -/** Convert iterator to vars +/** Convert iterator to vars. * This operation converts an iterator to a variable array. This allows for * using iterator results in expressions. The operation only converts a * single result at a time, and does not progress the iterator. * * Iterator fields with data will be made available as variables with as name - * the field index (e.g. "$1"). The operation does not check if reflection data + * the field index (e.g., "$1"). The operation does not check if reflection data * is registered for a field type. If no reflection data is registered for the * type, using the field variable in expressions will fail. * @@ -15788,17 +17463,17 @@ void ecs_script_vars_from_iter( /** Used with ecs_expr_run(). */ typedef struct ecs_expr_eval_desc_t { - const char *name; /**< Script name */ - const char *expr; /**< Full expression string */ - const ecs_script_vars_t *vars; /**< Variables accessible in expression */ - ecs_entity_t type; /**< Type of parsed value (optional) */ - ecs_entity_t (*lookup_action)( /**< Function for resolving entity identifiers */ + const char *name; /**< Script name. */ + const char *expr; /**< Full expression string. */ + const ecs_script_vars_t *vars; /**< Variables accessible in expression. */ + ecs_entity_t type; /**< Type of parsed value (optional). */ + ecs_entity_t (*lookup_action)( /**< Function for resolving entity identifiers. */ const ecs_world_t*, const char *value, void *ctx); - void *lookup_ctx; /**< Context passed to lookup function */ + void *lookup_ctx; /**< Context passed to lookup function. */ - /** Disable constant folding (slower evaluation, faster parsing) */ + /** Disable constant folding (slower evaluation, faster parsing). */ bool disable_folding; /** This option instructs the expression runtime to lookup variables by @@ -15807,12 +17482,12 @@ typedef struct ecs_expr_eval_desc_t { bool disable_dynamic_variable_binding; /** Allow for unresolved identifiers when parsing. Useful when entities can - * be created in between parsing & evaluating. */ + * be created in between parsing and evaluating. */ bool allow_unresolved_identifiers; - ecs_script_runtime_t *runtime; /**< Reusable runtime (optional) */ + ecs_script_runtime_t *runtime; /**< Reusable runtime (optional). */ - void *script_visitor; /**< For internal usage */ + void *script_visitor; /**< For internal usage. */ } ecs_expr_eval_desc_t; /** Run expression. @@ -15825,7 +17500,7 @@ typedef struct ecs_expr_eval_desc_t { * * @param world The world. * @param ptr The pointer to the expression to parse. - * @param value The value containing type & pointer to write to. + * @param value The value containing type and pointer to write to. * @param desc Configuration parameters for the parser. * @return Pointer to the character after the last one read, or NULL if failed. */ @@ -15882,6 +17557,7 @@ int ecs_expr_eval( * @param world The world. * @param str The string to evaluate. * @param vars The variables to use for evaluation. + * @return String with interpolated expressions, or NULL if failed. */ FLECS_API char* ecs_script_string_interpolate( @@ -15892,18 +17568,18 @@ char* ecs_script_string_interpolate( /* Global const variables */ -/** Used with ecs_const_var_init */ +/** Used with ecs_const_var_init(). */ typedef struct ecs_const_var_desc_t { - /* Variable name. */ + /** Variable name. */ const char *name; - /* Variable parent (namespace). */ + /** Variable parent (namespace). */ ecs_entity_t parent; - /* Variable type. */ + /** Variable type. */ ecs_entity_t type; - /* Pointer to value of variable. The value will be copied to an internal + /** Pointer to value of variable. The value will be copied to an internal * storage and does not need to be kept alive. */ void *value; } ecs_const_var_desc_t; @@ -15923,12 +17599,13 @@ ecs_entity_t ecs_const_var_init( ecs_const_var_init(world, &(ecs_const_var_desc_t)__VA_ARGS__) -/** Returns value for a const variable. +/** Return the value for a const variable. * This returns the value for a const variable that is created either with - * ecs_const_var_init, or in a script with "export const v: ...". - * + * ecs_const_var_init(), or in a script with "export const v: ...". + * * @param world The world. - * @param var The variable associated with the entity. + * @param var The variable associated with the entity. + * @return The value of the const variable. */ FLECS_API ecs_value_t ecs_const_var_get( @@ -15937,7 +17614,13 @@ ecs_value_t ecs_const_var_get( /* Functions */ -/** Used with ecs_function_init and ecs_method_init */ +/** Vector function callbacks for different element types. */ +typedef struct ecs_vector_fn_callbacks_t { + ecs_vector_function_callback_t i8; /**< Callback for i8 element type. */ + ecs_vector_function_callback_t i32; /**< Callback for i32 element type. */ +} ecs_vector_fn_callbacks_t; + +/** Used with ecs_function_init() and ecs_method_init(). */ typedef struct ecs_function_desc_t { /** Function name. */ const char *name; @@ -15955,6 +17638,55 @@ typedef struct ecs_function_desc_t { /** Function implementation. */ ecs_function_callback_t callback; + /** Vector function implementations. + * Set these callbacks if a function has one or more arguments of type + * flecs.script.vector, and optionally a return type of flecs.script.vector. + * + * The flecs.script.vector type allows a function to be called with types + * that meet the following constraints: + * - The same type is provided for all arguments of type flecs.script.vector + * - The provided type has one or more members of the same type + * - The member type must be a primitive type + * - The vector_callbacks array has an implementation for the primitive type. + * + * This allows for statements like: + * @code + * const a = Rgb: {100, 150, 250} + * const b = Rgb: {10, 10, 10} + * const r = lerp(a, b, 0.1) + * @endcode + * + * which would otherwise have to be written out as: + * + * @code + * const r = Rgb: { + * lerp(a.r, b.r, 0.1), + * lerp(a.g, b.g, 0.1), + * lerp(a.b, b.b, 0.1) + * } + * @endcode + * + * To register vector functions, do: + * + * @code + * ecs_function(world, { + * .name = "lerp", + * .return_type = EcsScriptVectorType, + * .params = { + * { .name = "a", .type = EcsScriptVectorType }, + * { .name = "b", .type = EcsScriptVectorType }, + * { .name = "t", .type = ecs_id(ecs_f64_t) } + * }, + * .vector_callbacks = { + * [EcsF32] = flecs_lerp32, + * [EcsF64] = flecs_lerp64 + * } + * }); + * @endcode + * + */ + ecs_vector_function_callback_t vector_callbacks[FLECS_SCRIPT_VECTOR_FUNCTION_COUNT]; + /** Context passed to function implementation. */ void *ctx; } ecs_function_desc_t; @@ -15982,9 +17714,9 @@ ecs_entity_t ecs_function_init( * Methods automatically receive the instance on which the method is invoked as * first argument. * - * @param world Method The world. + * @param world The world. * @param desc Method init parameters. - * @return The function, or 0 if failed. + * @return The method, or 0 if failed. */ FLECS_API ecs_entity_t ecs_method_init( @@ -16028,7 +17760,7 @@ int ecs_ptr_to_expr_buf( const void *data, ecs_strbuf_t *buf); -/** Similar as ecs_ptr_to_expr(), but serializes values to string. +/** Similar to ecs_ptr_to_expr(), but serializes values to string. * Whereas the output of ecs_ptr_to_expr() is a valid expression, the output of * ecs_ptr_to_str() is a string representation of the value. In most cases the * output of the two operations is the same, but there are some differences: @@ -16117,12 +17849,12 @@ extern "C" { /** * @defgroup c_addons_doc Doc * @ingroup c_addons - * Utilities for documenting entities, components and systems. + * Utilities for documenting entities, components, and systems. * * @{ */ -FLECS_API extern const ecs_entity_t ecs_id(EcsDocDescription); /**< Component id for EcsDocDescription. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsDocDescription); /**< Component ID for EcsDocDescription. */ /** Tag for adding a UUID to entities. * Added to an entity as (EcsDocDescription, EcsUuid) by ecs_doc_set_uuid(). @@ -16144,8 +17876,8 @@ FLECS_API extern const ecs_entity_t EcsDocDetail; */ FLECS_API extern const ecs_entity_t EcsDocLink; -/** Tag for adding a color to entities. - * Added to an entity as (EcsDocDescription, EcsDocColor) by ecs_doc_set_link(). +/** Tag for adding a color to entities. + * Added to an entity as (EcsDocDescription, EcsDocColor) by ecs_doc_set_color(). */ FLECS_API extern const ecs_entity_t EcsDocColor; @@ -16158,7 +17890,7 @@ FLECS_API extern const ecs_entity_t EcsDocColor; * - EcsDocColor */ typedef struct EcsDocDescription { - char *value; + char *value; /**< Description value. */ } EcsDocDescription; /** Add UUID to entity. @@ -16179,7 +17911,7 @@ void ecs_doc_set_uuid( const char *uuid); /** Add human-readable name to entity. - * Contrary to entity names, human readable names do not have to be unique and + * Contrary to entity names, human-readable names do not have to be unique and * can contain special characters used in the query language like '*'. * * @param world The world. @@ -16245,10 +17977,10 @@ void ecs_doc_set_link( const char *link); /** Add color to entity. - * UIs can use color as hint to improve visualizing entities. + * UIs can use color as a hint to improve visualizing entities. * * @param world The world. - * @param entity The entity to which to add the link. + * @param entity The entity to which to add the color. * @param color The color to add. * * @see ecs_doc_get_color() @@ -16275,11 +18007,11 @@ const char* ecs_doc_get_uuid( const ecs_world_t *world, ecs_entity_t entity); -/** Get human readable name from entity. - * If entity does not have an explicit human readable name, this operation will +/** Get human-readable name from entity. + * If the entity does not have an explicit human-readable name, this operation will * return the entity name. * - * To test if an entity has a human readable name, use: + * To test if an entity has a human-readable name, use: * * @code * ecs_has_pair(world, e, ecs_id(EcsDocDescription), EcsName); @@ -16400,10 +18132,10 @@ void FlecsDocImport( * entities, with components that store the reflection data. A type has at least * two components: * - * - EcsComponent: core component, contains size & alignment - * - EcsType: component that indicates what kind of type the entity is + * - EcsComponent: core component, contains size and alignment + * - EcsType: component that indicates what kind of type the entity is * - * Additionally the type may have an additional component that contains the + * Additionally, the type may have an additional component that contains the * reflection data for the type. For example, structs have these components: * * - EcsComponent @@ -16414,9 +18146,9 @@ void FlecsDocImport( * component. Adding a child with a Member component to an entity will * automatically add the EcsStruct component to the parent. * - * Enums/bitmasks can be populated by adding child entities with the Constant - * tag. By default constants are automatically assigned values when they are - * added to the enum/bitmask. The parent entity must have the EcsEnum or + * Enums and bitmasks can be populated by adding child entities with the Constant + * tag. By default, constants are automatically assigned values when they are + * added to the enum or bitmask. The parent entity must have the EcsEnum or * EcsBitmask component before adding the constants. * * To create enum constants with a manual value, set (Constant, i32) to the @@ -16427,7 +18159,7 @@ void FlecsDocImport( * The _init APIs are convenience wrappers around creating the entities and * components for the types. * - * When a type is created it automatically receives the EcsComponent and + * When a type is created, it automatically receives the EcsComponent and * EcsType components. The former means that the resulting type can be * used as a regular component: * @@ -16469,11 +18201,11 @@ void FlecsDocImport( extern "C" { #endif -/** Max number of constants/members that can be specified in desc structs. */ +/** Max number of constants and members that can be specified in desc structs. */ #define ECS_MEMBER_DESC_CACHE_SIZE (32) /** Primitive type definitions. - * These typedefs allow the builtin primitives to be used as regular components: + * These typedefs allow the built-in primitives to be used as regular components: * * @code * ecs_set(world, e, ecs_i32_t, {10}); @@ -16486,62 +18218,62 @@ extern "C" { * @endcode */ -typedef bool ecs_bool_t; /**< Builtin bool type */ -typedef char ecs_char_t; /**< Builtin char type */ -typedef unsigned char ecs_byte_t; /**< Builtin ecs_byte type */ -typedef uint8_t ecs_u8_t; /**< Builtin u8 type */ -typedef uint16_t ecs_u16_t; /**< Builtin u16 type */ -typedef uint32_t ecs_u32_t; /**< Builtin u32 type */ -typedef uint64_t ecs_u64_t; /**< Builtin u64 type */ -typedef uintptr_t ecs_uptr_t; /**< Builtin uptr type */ -typedef int8_t ecs_i8_t; /**< Builtin i8 type */ -typedef int16_t ecs_i16_t; /**< Builtin i16 type */ -typedef int32_t ecs_i32_t; /**< Builtin i32 type */ -typedef int64_t ecs_i64_t; /**< Builtin i64 type */ -typedef intptr_t ecs_iptr_t; /**< Builtin iptr type */ -typedef float ecs_f32_t; /**< Builtin f32 type */ -typedef double ecs_f64_t; /**< Builtin f64 type */ -typedef char* ecs_string_t; /**< Builtin string type */ - -/* Meta module component ids */ -FLECS_API extern const ecs_entity_t ecs_id(EcsType); /**< Id for component added to all types with reflection data. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsTypeSerializer); /**< Id for component that stores a type specific serializer. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsPrimitive); /**< Id for component that stores reflection data for a primitive type. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsEnum); /**< Id for component that stores reflection data for an enum type. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsBitmask); /**< Id for component that stores reflection data for a bitmask type. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsConstants); /**< Id for component that stores reflection data for a constants. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsMember); /**< Id for component that stores reflection data for struct members. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsMemberRanges); /**< Id for component that stores min/max ranges for member values. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsStruct); /**< Id for component that stores reflection data for a struct type. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsArray); /**< Id for component that stores reflection data for an array type. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsVector); /**< Id for component that stores reflection data for a vector type. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsOpaque); /**< Id for component that stores reflection data for an opaque type. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsUnit); /**< Id for component that stores unit data. */ -FLECS_API extern const ecs_entity_t ecs_id(EcsUnitPrefix); /**< Id for component that stores unit prefix data. */ +typedef bool ecs_bool_t; /**< Built-in bool type. */ +typedef char ecs_char_t; /**< Built-in char type. */ +typedef unsigned char ecs_byte_t; /**< Built-in ecs_byte type. */ +typedef uint8_t ecs_u8_t; /**< Built-in u8 type. */ +typedef uint16_t ecs_u16_t; /**< Built-in u16 type. */ +typedef uint32_t ecs_u32_t; /**< Built-in u32 type. */ +typedef uint64_t ecs_u64_t; /**< Built-in u64 type. */ +typedef uintptr_t ecs_uptr_t; /**< Built-in uptr type. */ +typedef int8_t ecs_i8_t; /**< Built-in i8 type. */ +typedef int16_t ecs_i16_t; /**< Built-in i16 type. */ +typedef int32_t ecs_i32_t; /**< Built-in i32 type. */ +typedef int64_t ecs_i64_t; /**< Built-in i64 type. */ +typedef intptr_t ecs_iptr_t; /**< Built-in iptr type. */ +typedef float ecs_f32_t; /**< Built-in f32 type. */ +typedef double ecs_f64_t; /**< Built-in f64 type. */ +typedef char* ecs_string_t; /**< Built-in string type. */ + +/* Meta module component IDs */ +FLECS_API extern const ecs_entity_t ecs_id(EcsType); /**< ID for component added to all types with reflection data. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsTypeSerializer); /**< ID for component that stores a type-specific serializer. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsPrimitive); /**< ID for component that stores reflection data for a primitive type. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsEnum); /**< ID for component that stores reflection data for an enum type. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsBitmask); /**< ID for component that stores reflection data for a bitmask type. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsConstants); /**< ID for component that stores reflection data for constants. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsMember); /**< ID for component that stores reflection data for struct members. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsMemberRanges); /**< ID for component that stores min and max ranges for member values. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsStruct); /**< ID for component that stores reflection data for a struct type. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsArray); /**< ID for component that stores reflection data for an array type. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsVector); /**< ID for component that stores reflection data for a vector type. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsOpaque); /**< ID for component that stores reflection data for an opaque type. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsUnit); /**< ID for component that stores unit data. */ +FLECS_API extern const ecs_entity_t ecs_id(EcsUnitPrefix); /**< ID for component that stores unit prefix data. */ FLECS_API extern const ecs_entity_t EcsQuantity; /**< Tag added to unit quantities. */ -/* Primitive type component ids */ - -FLECS_API extern const ecs_entity_t ecs_id(ecs_bool_t); /**< Builtin boolean type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_char_t); /**< Builtin char type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_byte_t); /**< Builtin byte type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_u8_t); /**< Builtin 8 bit unsigned int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_u16_t); /**< Builtin 16 bit unsigned int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_u32_t); /**< Builtin 32 bit unsigned int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_u64_t); /**< Builtin 64 bit unsigned int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_uptr_t); /**< Builtin pointer sized unsigned int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_i8_t); /**< Builtin 8 bit signed int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_i16_t); /**< Builtin 16 bit signed int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_i32_t); /**< Builtin 32 bit signed int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_i64_t); /**< Builtin 64 bit signed int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_iptr_t); /**< Builtin pointer sized signed int type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_f32_t); /**< Builtin 32 bit floating point type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_f64_t); /**< Builtin 64 bit floating point type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_string_t); /**< Builtin string type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_entity_t); /**< Builtin entity type. */ -FLECS_API extern const ecs_entity_t ecs_id(ecs_id_t); /**< Builtin (component) id type. */ - -/** Type kinds supported by meta addon */ +/* Primitive type component IDs */ + +FLECS_API extern const ecs_entity_t ecs_id(ecs_bool_t); /**< Built-in boolean type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_char_t); /**< Built-in char type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_byte_t); /**< Built-in byte type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_u8_t); /**< Built-in 8-bit unsigned int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_u16_t); /**< Built-in 16-bit unsigned int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_u32_t); /**< Built-in 32-bit unsigned int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_u64_t); /**< Built-in 64-bit unsigned int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_uptr_t); /**< Built-in pointer-sized unsigned int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_i8_t); /**< Built-in 8-bit signed int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_i16_t); /**< Built-in 16-bit signed int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_i32_t); /**< Built-in 32-bit signed int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_i64_t); /**< Built-in 64-bit signed int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_iptr_t); /**< Built-in pointer-sized signed int type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_f32_t); /**< Built-in 32-bit floating-point type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_f64_t); /**< Built-in 64-bit floating-point type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_string_t); /**< Built-in string type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_entity_t); /**< Built-in entity type. */ +FLECS_API extern const ecs_entity_t ecs_id(ecs_id_t); /**< Built-in (component) ID type. */ + +/** Type kinds supported by meta addon. */ typedef enum ecs_type_kind_t { EcsPrimitiveType, EcsBitmaskType, @@ -16556,11 +18288,11 @@ typedef enum ecs_type_kind_t { /** Component that is automatically added to every type with the right kind. */ typedef struct EcsType { ecs_type_kind_t kind; /**< Type kind. */ - bool existing; /**< Did the type exist or is it populated from reflection */ - bool partial; /**< Is the reflection data a partial type description */ + bool existing; /**< Whether the type existed or was populated from reflection. */ + bool partial; /**< Whether the reflection data is a partial type description. */ } EcsType; -/** Primitive type kinds supported by meta addon */ +/** Primitive type kinds supported by meta addon. */ typedef enum ecs_primitive_kind_t { EcsBool = 1, EcsChar, @@ -16583,12 +18315,12 @@ typedef enum ecs_primitive_kind_t { EcsPrimitiveKindLast = EcsId } ecs_primitive_kind_t; -/** Component added to primitive types */ +/** Component added to primitive types. */ typedef struct EcsPrimitive { ecs_primitive_kind_t kind; /**< Primitive type kind. */ } EcsPrimitive; -/** Component added to member entities */ +/** Component added to member entities. */ typedef struct EcsMember { ecs_entity_t type; /**< Member type. */ int32_t count; /**< Number of elements for inline arrays. Leave to 0 for non-array members. */ @@ -16597,22 +18329,22 @@ typedef struct EcsMember { bool use_offset; /**< If offset should be explicitly used. */ } EcsMember; -/** Type expressing a range for a member value */ +/** Type expressing a range for a member value. */ typedef struct ecs_member_value_range_t { double min; /**< Min member value. */ double max; /**< Max member value. */ } ecs_member_value_range_t; -/** Component added to member entities to express valid value ranges */ +/** Component added to member entities to express valid value ranges. */ typedef struct EcsMemberRanges { ecs_member_value_range_t value; /**< Member value range. */ ecs_member_value_range_t warning; /**< Member value warning range. */ ecs_member_value_range_t error; /**< Member value error range. */ } EcsMemberRanges; -/** Element type of members vector in EcsStruct */ +/** Element type of members vector in EcsStruct. */ typedef struct ecs_member_t { - /** Must be set when used with ecs_struct_desc_t */ + /** Must be set when used with ecs_struct_desc_t. */ const char *name; /** Member type. */ @@ -16625,8 +18357,8 @@ typedef struct ecs_member_t { /** May be set when used with ecs_struct_desc_t. Member offset. */ int32_t offset; - /** May be set when used with ecs_struct_desc_t, will be auto-populated if - * type entity is also a unit */ + /** May be set when used with ecs_struct_desc_t. Will be auto-populated if + * the type entity is also a unit. */ ecs_entity_t unit; /** Set to true to prevent automatic offset computation. This option should @@ -16643,81 +18375,81 @@ typedef struct ecs_member_t { * range may be used by UI elements to style a value. */ ecs_member_value_range_t error_range; - /** Numerical range outside of which the value represents an warning. This + /** Numerical range outside of which the value represents a warning. This * range may be used by UI elements to style a value. */ ecs_member_value_range_t warning_range; - /** Should not be set by ecs_struct_desc_t */ + /** Should not be set by ecs_struct_desc_t. */ ecs_size_t size; - /** Should not be set by ecs_struct_desc_t */ + /** Should not be set by ecs_struct_desc_t. */ ecs_entity_t member; } ecs_member_t; -/** Component added to struct type entities */ +/** Component added to struct type entities. */ typedef struct EcsStruct { - /** Populated from child entities with Member component */ + /** Populated from child entities with Member component. */ ecs_vec_t members; /* vector */ } EcsStruct; -/** Type that describes an enum constant */ +/** Type that describes an enum constant. */ typedef struct ecs_enum_constant_t { - /** Must be set when used with ecs_enum_desc_t */ + /** Must be set when used with ecs_enum_desc_t. */ const char *name; - /** May be set when used with ecs_enum_desc_t */ + /** May be set when used with ecs_enum_desc_t. */ int64_t value; - /** For when the underlying type is unsigned */ + /** For when the underlying type is unsigned. */ uint64_t value_unsigned; - /** Should not be set by ecs_enum_desc_t */ + /** Should not be set by ecs_enum_desc_t. */ ecs_entity_t constant; } ecs_enum_constant_t; -/** Component added to enum type entities */ +/** Component added to enum type entities. */ typedef struct EcsEnum { - ecs_entity_t underlying_type; + ecs_entity_t underlying_type; /**< Underlying type for enum. */ } EcsEnum; -/** Type that describes an bitmask constant */ +/** Type that describes a bitmask constant. */ typedef struct ecs_bitmask_constant_t { - /** Must be set when used with ecs_bitmask_desc_t */ + /** Must be set when used with ecs_bitmask_desc_t. */ const char *name; - /** May be set when used with ecs_bitmask_desc_t */ + /** May be set when used with ecs_bitmask_desc_t. */ ecs_flags64_t value; - /** Keep layout the same with ecs_enum_constant_t */ + /** Keep layout the same with ecs_enum_constant_t. */ int64_t _unused; - /** Should not be set by ecs_bitmask_desc_t */ + /** Should not be set by ecs_bitmask_desc_t. */ ecs_entity_t constant; } ecs_bitmask_constant_t; -/** Component added to bitmask type entities */ +/** Component added to bitmask type entities. */ typedef struct EcsBitmask { - int32_t dummy_; + int32_t dummy_; /**< Unused. */ } EcsBitmask; -/** Component with datastructures for looking up enum/bitmask constants. */ +/** Component with data structures for looking up enum or bitmask constants. */ typedef struct EcsConstants { - /** Populated from child entities with Constant component */ + /** Populated from child entities with Constant component. */ ecs_map_t *constants; /**< map */ - /** Stores the constants in registration order */ + /** Stores the constants in registration order. */ ecs_vec_t ordered_constants; /**< vector */ } EcsConstants; -/** Component added to array type entities */ +/** Component added to array type entities. */ typedef struct EcsArray { - ecs_entity_t type; /**< Element type */ - int32_t count; /**< Number of elements */ + ecs_entity_t type; /**< Element type. */ + int32_t count; /**< Number of elements. */ } EcsArray; -/** Component added to vector type entities */ +/** Component added to vector type entities. */ typedef struct EcsVector { - ecs_entity_t type; /**< Element type */ + ecs_entity_t type; /**< Element type. */ } EcsVector; @@ -16725,18 +18457,18 @@ typedef struct EcsVector { #if !defined(__cplusplus) || !defined(FLECS_CPP) -/** Serializer interface */ +/** Serializer interface. */ typedef struct ecs_serializer_t { - /* Serialize value */ + /** Serialize value. */ int (*value)( - const struct ecs_serializer_t *ser, /**< Serializer */ - ecs_entity_t type, /**< Type of the value to serialize */ - const void *value); /**< Pointer to the value to serialize */ + const struct ecs_serializer_t *ser, /**< Serializer. */ + ecs_entity_t type, /**< Type of the value to serialize. */ + const void *value); /**< Pointer to the value to serialize. */ - /* Serialize member */ + /** Serialize member. */ int (*member)( - const struct ecs_serializer_t *ser, /**< Serializer */ - const char *member); /**< Member name */ + const struct ecs_serializer_t *ser, /**< Serializer. */ + const char *member); /**< Member name. */ const ecs_world_t *world; /**< The world. */ void *ctx; /**< Serializer context. */ @@ -16746,7 +18478,7 @@ typedef struct ecs_serializer_t { } /* extern "C" { */ -/** Serializer interface (same layout as C, but with convenience methods) */ +/** Serializer interface (same layout as C, but with convenience methods). */ typedef struct ecs_serializer_t { /* Serialize value */ int (*value_)( @@ -16779,30 +18511,31 @@ extern "C" { /** Callback invoked serializing an opaque type. */ typedef int (*ecs_meta_serialize_t)( const ecs_serializer_t *ser, - const void *src); /**< Pointer to value to serialize */ + const void *src); /**< Pointer to value to serialize. */ -/** Callback invoked to serialize an opaque struct member */ +/** Callback invoked to serialize an opaque struct member. */ typedef int (*ecs_meta_serialize_member_t)( const ecs_serializer_t *ser, - const void *src, /**< Pointer to value to serialize */ - const char* name); /**< Name of member to serialize */ - -/** Callback invoked to serialize an opaque vector/array element */ + const void *src, /**< Pointer to value to serialize. */ + const char* name); /**< Name of member to serialize. */ + +/** Callback invoked to serialize an opaque vector or array element. */ typedef int (*ecs_meta_serialize_element_t)( const ecs_serializer_t *ser, - const void *src, /**< Pointer to value to serialize */ - size_t elem); /**< Element index to serialize */ - + const void *src, /**< Pointer to value to serialize. */ + size_t elem); /**< Element index to serialize. */ + + /** Opaque type reflection data. * An opaque type is a type with an unknown layout that can be mapped to a type * known to the reflection framework. See the opaque type reflection examples. */ typedef struct EcsOpaque { - ecs_entity_t as_type; /**< Type that describes the serialized output */ - ecs_meta_serialize_t serialize; /**< Serialize action */ - ecs_meta_serialize_member_t serialize_member; /**< Serialize member action */ - ecs_meta_serialize_element_t serialize_element; /**< Serialize element action */ + ecs_entity_t as_type; /**< Type that describes the serialized output. */ + ecs_meta_serialize_t serialize; /**< Serialize action. */ + ecs_meta_serialize_member_t serialize_member; /**< Serialize member action. */ + ecs_meta_serialize_element_t serialize_element; /**< Serialize element action. */ /* Deserializer interface * Only override the callbacks that are valid for the opaque type. If a @@ -16810,71 +18543,71 @@ typedef struct EcsOpaque { * interface, a conversion error is thrown. */ - /** Assign bool value */ + /** Assign bool value. */ void (*assign_bool)( void *dst, bool value); - /** Assign char value */ + /** Assign char value. */ void (*assign_char)( void *dst, char value); - /** Assign int value */ + /** Assign int value. */ void (*assign_int)( void *dst, int64_t value); - /** Assign unsigned int value */ + /** Assign unsigned int value. */ void (*assign_uint)( void *dst, uint64_t value); - /** Assign float value */ + /** Assign float value. */ void (*assign_float)( void *dst, double value); - /** Assign string value */ + /** Assign string value. */ void (*assign_string)( void *dst, const char *value); - /** Assign entity value */ + /** Assign entity value. */ void (*assign_entity)( void *dst, ecs_world_t *world, ecs_entity_t entity); - /** Assign (component) id value */ + /** Assign (component) ID value. */ void (*assign_id)( void *dst, ecs_world_t *world, ecs_id_t id); - /** Assign null value */ + /** Assign null value. */ void (*assign_null)( void *dst); - /** Clear collection elements */ + /** Clear collection elements. */ void (*clear)( void *dst); - /** Ensure & get collection element */ + /** Ensure and get collection element. */ void* (*ensure_element)( void *dst, size_t elem); - /** Ensure & get element */ + /** Ensure and get member. */ void* (*ensure_member)( void *dst, const char *member); - /** Return number of elements */ + /** Return number of elements. */ size_t (*count)( const void *dst); - /** Resize to number of elements */ + /** Resize to number of elements. */ void (*resize)( void *dst, size_t count); @@ -16884,30 +18617,30 @@ typedef struct EcsOpaque { /* Units */ /** Helper type to describe translation between two units. Note that this - * is not intended as a generic approach to unit conversions (e.g. from celsius - * to fahrenheit) but to translate between units that derive from the same base - * (e.g. meters to kilometers). + * is not intended as a generic approach to unit conversions (e.g., from Celsius + * to Fahrenheit) but to translate between units that derive from the same base + * (e.g., meters to kilometers). * * Note that power is applied to the factor. When describing a translation of * 1000, either use {factor = 1000, power = 1} or {factor = 1, power = 3}. */ typedef struct ecs_unit_translation_t { - int32_t factor; /**< Factor to apply (e.g. "1000", "1000000", "1024") */ - int32_t power; /**< Power to apply to factor (e.g. "1", "3", "-9") */ + int32_t factor; /**< Factor to apply (e.g., "1000", "1000000", "1024"). */ + int32_t power; /**< Power to apply to factor (e.g., "1", "3", "-9"). */ } ecs_unit_translation_t; /** Component that stores unit data. */ typedef struct EcsUnit { char *symbol; /**< Unit symbol. */ - ecs_entity_t prefix; /**< Order of magnitude prefix relative to derived */ - ecs_entity_t base; /**< Base unit (e.g. "meters") */ - ecs_entity_t over; /**< Over unit (e.g. "per second") */ - ecs_unit_translation_t translation; /**< Translation for derived unit */ + ecs_entity_t prefix; /**< Order of magnitude prefix relative to derived. */ + ecs_entity_t base; /**< Base unit (e.g., "meters"). */ + ecs_entity_t over; /**< Over unit (e.g., "per second"). */ + ecs_unit_translation_t translation; /**< Translation for derived unit. */ } EcsUnit; /** Component that stores unit prefix data. */ typedef struct EcsUnitPrefix { - char *symbol; /**< Symbol of prefix (e.g. "K", "M", "Ki") */ - ecs_unit_translation_t translation; /**< Translation of prefix */ + char *symbol; /**< Symbol of prefix (e.g., "K", "M", "Ki"). */ + ecs_unit_translation_t translation; /**< Translation of prefix. */ } EcsUnitPrefix; @@ -16915,7 +18648,7 @@ typedef struct EcsUnitPrefix { /** Serializer instruction opcodes. * The meta type serializer works by generating a flattened array with - * instructions that tells a serializer what kind of fields can be found in a + * instructions that tell a serializer what kind of fields can be found in a * type at which offsets. */ typedef enum ecs_meta_op_kind_t { @@ -16929,13 +18662,13 @@ typedef enum ecs_meta_op_kind_t { EcsOpOpaqueVector, /**< Opaque vector. */ EcsOpForward, /**< Forward to type. Allows for recursive types. */ - EcsOpScope, /**< Marks last constant that can open/close a scope */ + EcsOpScope, /**< Marks last constant that can open or close a scope. */ EcsOpOpaqueValue, /**< Opaque value. */ EcsOpEnum, EcsOpBitmask, - EcsOpPrimitive, /**< Marks first constant that's a primitive */ + EcsOpPrimitive, /**< Marks first constant that's a primitive. */ EcsOpBool, EcsOpChar, @@ -16963,23 +18696,23 @@ typedef struct ecs_meta_op_t { ecs_meta_op_kind_t kind; /**< Instruction opcode. */ ecs_meta_op_kind_t underlying_kind; /**< Underlying type kind (for enums). */ ecs_size_t offset; /**< Offset of current field. */ - const char *name; /**< Name of value (only used for struct members) */ - ecs_size_t elem_size; /**< Element size (for PushArray/PushVector) and element count (for PopArray) */ - int16_t op_count; /**< Number of operations until next field or end */ - int16_t member_index; /**< Index of member in struct */ - ecs_entity_t type; /**< Type entity */ - const ecs_type_info_t *type_info; /**< Type info */ + const char *name; /**< Name of value (only used for struct members). */ + ecs_size_t elem_size; /**< Element size (for PushArray or PushVector) and element count (for PopArray). */ + int16_t op_count; /**< Number of operations until next field or end. */ + int16_t member_index; /**< Index of member in struct. */ + ecs_entity_t type; /**< Type entity. */ + const ecs_type_info_t *type_info; /**< Type info. */ union { - ecs_hashmap_t *members; /**< string -> member index (structs) */ - ecs_map_t *constants; /**< (u)int -> constant entity (enums/bitmasks) */ - ecs_meta_serialize_t opaque; /**< Serialize callback for opaque types */ + ecs_hashmap_t *members; /**< string -> member index (structs). */ + ecs_map_t *constants; /**< (u)int -> constant entity (enums and bitmasks). */ + ecs_meta_serialize_t opaque; /**< Serialize callback for opaque types. */ } is; } ecs_meta_op_t; /** Component that stores the type serializer. * Added to all types with reflection data. */ typedef struct EcsTypeSerializer { - ecs_type_kind_t kind; /**< Quick access to type kind (same as EcsType) */ + ecs_type_kind_t kind; /**< Quick access to type kind (same as EcsType). */ ecs_vec_t ops; /**< vector */ } EcsTypeSerializer; @@ -16987,53 +18720,58 @@ typedef struct EcsTypeSerializer { /* Deserializer utilities */ /** Maximum level of type nesting. - * >32 levels of nesting is not sane. + * >32 levels of nesting are not sane. */ #define ECS_META_MAX_SCOPE_DEPTH (32) -/** Type with information about currently serialized scope. */ +/** Type with information about the currently iterated scope. */ typedef struct ecs_meta_scope_t { - ecs_entity_t type; /**< The type being iterated */ - ecs_meta_op_t *ops; /**< The type operations (see ecs_meta_op_t) */ - int16_t ops_count; /**< Number of elements in ops */ - int16_t ops_cur; /**< Current element in ops */ - int16_t prev_depth; /**< Depth to restore, in case dotmember was used */ - void *ptr; /**< Pointer to ops[0] */ - const EcsOpaque *opaque; /**< Opaque type interface */ - ecs_hashmap_t *members; /**< string -> member index */ - bool is_collection; /**< Is the scope iterating elements? */ - bool is_empty_scope; /**< Was scope populated (for vectors) */ - bool is_moved_scope; /**< Was scope moved in (with ecs_meta_elem, for vectors) */ - int32_t elem, elem_count; /**< Set for collections */ + ecs_entity_t type; /**< The type being iterated. */ + ecs_meta_op_t *ops; /**< The type operations (see ecs_meta_op_t). */ + int16_t ops_count; /**< Number of elements in ops. */ + int16_t ops_cur; /**< Current element in ops. */ + int16_t prev_depth; /**< Depth to restore, in case dotmember was used. */ + void *ptr; /**< Pointer to ops[0]. */ + const EcsOpaque *opaque; /**< Opaque type interface. */ + ecs_hashmap_t *members; /**< string -> member index. */ + bool is_collection; /**< Whether the scope is iterating elements. */ + bool is_empty_scope; /**< Whether the scope was populated (for vectors). */ + bool is_moved_scope; /**< Whether the scope was moved in (with ecs_meta_elem(), for vectors). */ + int32_t elem, elem_count; /**< Set for collections. */ } ecs_meta_scope_t; -/** Type that enables iterating/populating a value using reflection data. */ +/** Type that enables iterating and populating a value using reflection data. */ typedef struct ecs_meta_cursor_t { const ecs_world_t *world; /**< The world. */ ecs_meta_scope_t scope[ECS_META_MAX_SCOPE_DEPTH]; /**< Cursor scope stack. */ int16_t depth; /**< Current scope depth. */ - bool valid; /**< Does the cursor point to a valid field. */ - bool is_primitive_scope; /**< If in root scope, this allows for a push for primitive types */ + bool valid; /**< Whether the cursor points to a valid field. */ + bool is_primitive_scope; /**< If in root scope, this allows for a push for primitive types. */ - /** Custom entity lookup action for overriding default ecs_lookup */ + /** Custom entity lookup action for overriding default ecs_lookup(). */ ecs_entity_t (*lookup_action)(ecs_world_t*, const char*, void*); - void *lookup_ctx; /**< Context for lookup_action */ + void *lookup_ctx; /**< Context for lookup_action. */ } ecs_meta_cursor_t; -/** Convert serializer to string. */ +/** Convert serializer to string. + * + * @param world The world. + * @param type The type to convert. + * @return The serializer string, or NULL if failed. + */ FLECS_API char* ecs_meta_serializer_to_str( ecs_world_t *world, ecs_entity_t type); /** Create meta cursor. - * A meta cursor allows for walking over, reading and writing a value without + * A meta cursor allows for walking over, reading, and writing a value without * having to know its type at compile time. * * When a value is assigned through the cursor API, it will get converted to * the actual value of the underlying type. This allows the underlying type to * change without having to update the serialized data. For example, an integer - * field can be set by a string, a floating point can be set as integer etc. + * field can be set by a string, a floating-point value can be set as an integer, etc. * * @param world The world. * @param type The type of the value. @@ -17085,7 +18823,7 @@ int ecs_meta_member( ecs_meta_cursor_t *cursor, const char *name); -/** Same as ecs_meta_member() but doesn't throw an error. +/** Same as ecs_meta_member(), but doesn't throw an error. * * @param cursor The cursor. * @param name The name of the member. @@ -17110,7 +18848,7 @@ int ecs_meta_dotmember( ecs_meta_cursor_t *cursor, const char *name); -/** Same as ecs_meta_dotmember() but doesn't throw an error. +/** Same as ecs_meta_dotmember(), but doesn't throw an error. * * @param cursor The cursor. * @param name The name of the member. @@ -17122,7 +18860,7 @@ int ecs_meta_try_dotmember( ecs_meta_cursor_t *cursor, const char *name); -/** Push a scope (required/only valid for structs & collections). +/** Push a scope (required and only valid for structs and collections). * * @param cursor The cursor. * @return Zero if success, non-zero if failed. @@ -17140,7 +18878,7 @@ FLECS_API int ecs_meta_pop( ecs_meta_cursor_t *cursor); -/** Is the current scope a collection?. +/** Is the current scope a collection? * * @param cursor The cursor. * @return True if current scope is a collection, false if not. @@ -17186,7 +18924,7 @@ ecs_entity_t ecs_meta_get_member_id( const ecs_meta_cursor_t *cursor); /* The set functions assign the field with the specified value. If the value - * does not have the same type as the field, it will be cased to the field type. + * does not have the same type as the field, it will be cast to the field type. * If no valid conversion is available, the operation will fail. */ /** Set field with boolean value. @@ -17277,7 +19015,7 @@ int ecs_meta_set_entity( ecs_meta_cursor_t *cursor, ecs_entity_t value); -/** Set field with (component) id value. +/** Set field with (component) ID value. * * @param cursor The cursor. * @param value The value to set. @@ -17376,7 +19114,7 @@ FLECS_API ecs_entity_t ecs_meta_get_entity( const ecs_meta_cursor_t *cursor); -/** Get field value as (component) id. +/** Get field value as (component) ID. * This operation can convert from an entity. * * @param cursor The cursor. @@ -17390,19 +19128,19 @@ ecs_id_t ecs_meta_get_id( * * @param type_kind The primitive type kind of the value. * @param ptr Pointer to a value of a primitive type. - * @return The value in floating point format. + * @return The value in floating-point format. */ FLECS_API double ecs_meta_ptr_to_float( ecs_primitive_kind_t type_kind, const void *ptr); -/** Get element count for array/vector operations. +/** Get element count for array or vector operations. * The operation must either be EcsOpPushArray or EcsOpPushVector. If the * operation is EcsOpPushArray, the provided pointer may be NULL. * * @param op The serializer operation. - * @param ptr Pointer to the array/vector value. + * @param ptr Pointer to the array or vector value. * @return The number of elements. */ FLECS_API @@ -17434,7 +19172,7 @@ ecs_entity_t ecs_primitive_init( typedef struct ecs_enum_desc_t { ecs_entity_t entity; /**< Existing entity to use for type (optional). */ ecs_enum_constant_t constants[ECS_MEMBER_DESC_CACHE_SIZE]; /**< Enum constants. */ - ecs_entity_t underlying_type; + ecs_entity_t underlying_type; /**< Underlying type for enum. */ } ecs_enum_desc_t; /** Create a new enum type. @@ -17508,19 +19246,59 @@ ecs_entity_t ecs_vector_init( typedef struct ecs_struct_desc_t { ecs_entity_t entity; /**< Existing entity to use for type (optional). */ ecs_member_t members[ECS_MEMBER_DESC_CACHE_SIZE]; /**< Struct members. */ + bool create_member_entities; /**< Create entities for members. */ } ecs_struct_desc_t; -/** Create a new struct type. +/** Create a new struct type. + * + * @param world The world. + * @param desc The type descriptor. + * @return The new type, 0 if failed. + */ +FLECS_API +ecs_entity_t ecs_struct_init( + ecs_world_t *world, + const ecs_struct_desc_t *desc); + +/** Add member to struct. + * This operation adds a member to a struct type. If the provided entity is not + * a struct type, this operation will add the Struct component. + * + * @param world The world. + * @param type The struct type. + * @param member The member data. + */ +FLECS_API +int ecs_struct_add_member( + ecs_world_t *world, + ecs_entity_t type, + const ecs_member_t *member); + +/** Get member by name from struct. * * @param world The world. - * @param desc The type descriptor. - * @return The new type, 0 if failed. + * @param type The struct type. + * @param name The member name. + * @return The member if found, or NULL if no member with the provided name exists. */ FLECS_API -ecs_entity_t ecs_struct_init( +ecs_member_t* ecs_struct_get_member( ecs_world_t *world, - const ecs_struct_desc_t *desc); + ecs_entity_t type, + const char *name); +/** Get member by index from struct. + * + * @param world The world. + * @param type The struct type. + * @param i The member index. + * @return The member if found, or NULL if index is larger than the number of members for the struct. + */ +FLECS_API +ecs_member_t* ecs_struct_get_nth_member( + ecs_world_t *world, + ecs_entity_t type, + int32_t i); /** Used with ecs_opaque_init(). */ typedef struct ecs_opaque_desc_t { @@ -17532,8 +19310,8 @@ typedef struct ecs_opaque_desc_t { * Opaque types are types of which the layout doesn't match what can be modelled * with the primitives of the meta framework, but which have a structure * that can be described with meta primitives. Typical examples are STL types - * such as std::string or std::vector, types with a nontrivial layout, and types - * that only expose getter/setter methods. + * such as std::string or std::vector, types with a non-trivial layout, and types + * that only expose getter and setter methods. * * An opaque type is a combination of a serialization function, and a handle to * a meta type which describes the structure of the serialized output. For @@ -17561,16 +19339,16 @@ typedef struct ecs_unit_desc_t { /** Existing entity to associate with unit (optional). */ ecs_entity_t entity; - /** Unit symbol, e.g. "m", "%", "g". (optional). */ + /** Unit symbol, e.g., "m", "%", "g". (optional). */ const char *symbol; - /** Unit quantity, e.g. distance, percentage, weight. (optional). */ + /** Unit quantity, e.g., distance, percentage, weight. (optional). */ ecs_entity_t quantity; - /** Base unit, e.g. "meters" (optional). */ + /** Base unit, e.g., "meters" (optional). */ ecs_entity_t base; - /** Over unit, e.g. "per second" (optional). */ + /** Over unit, e.g., "per second" (optional). */ ecs_entity_t over; /** Translation to apply to derived unit (optional). */ @@ -17581,7 +19359,7 @@ typedef struct ecs_unit_desc_t { * set, setting prefix will auto-populate it. * Additionally, setting the prefix will enforce that the symbol (if set) * is consistent with the prefix symbol + symbol of the derived unit. If the - * symbol is not set, it will be auto populated. */ + * symbol is not set, it will be auto-populated. */ ecs_entity_t prefix; } ecs_unit_desc_t; @@ -17602,7 +19380,7 @@ typedef struct ecs_unit_prefix_desc_t { /** Existing entity to associate with unit prefix (optional). */ ecs_entity_t entity; - /** Unit symbol, e.g. "m", "%", "g". (optional). */ + /** Unit prefix symbol, e.g., "K", "M", "Ki". (optional). */ const char *symbol; /** Translation to apply to derived unit (optional). */ @@ -17717,11 +19495,11 @@ extern "C" { * macro is not defined, it defaults to IMPL. */ /* Define variables used by reflection utilities. This should only be defined - * by the module itself, not by the code importing the module */ + * by the module itself, not by the code importing the module. */ /* #define ECS_META_IMPL IMPL */ -/* Don't define variables used by reflection utilities but still declare the - * variable for the component id. This enables the reflection utilities to be +/* Don't define variables used by reflection utilities, but still declare the + * variable for the component ID. This enables the reflection utilities to be * used for global component variables, even if no reflection is used. */ /* #define ECS_META_IMPL DECLARE */ @@ -17774,7 +19552,7 @@ int ecs_meta_from_desc( /* ECS_STRUCT implementation */ #define ECS_STRUCT_TYPE(name, ...)\ - typedef struct __VA_ARGS__ name + typedef struct name __VA_ARGS__ name #define ECS_STRUCT_ECS_META_IMPL ECS_STRUCT_IMPL @@ -17794,7 +19572,7 @@ int ecs_meta_from_desc( /* ECS_ENUM implementation */ #define ECS_ENUM_TYPE(name, ...)\ - typedef enum __VA_ARGS__ name + typedef enum name __VA_ARGS__ name #define ECS_ENUM_ECS_META_IMPL ECS_ENUM_IMPL @@ -17814,7 +19592,7 @@ int ecs_meta_from_desc( /* ECS_BITMASK implementation */ #define ECS_BITMASK_TYPE(name, ...)\ - typedef enum __VA_ARGS__ name + typedef enum name __VA_ARGS__ name #define ECS_BITMASK_ECS_META_IMPL ECS_BITMASK_IMPL @@ -17837,7 +19615,7 @@ int ecs_meta_from_desc( } #endif -#endif // FLECS_META_H +#endif // FLECS_META_C_H /** @} */ @@ -17878,6 +19656,10 @@ int ecs_meta_from_desc( extern "C" { #endif +/** Set default OS API implementation. + * This initializes the OS API with a default implementation for the current + * platform. + */ FLECS_API void ecs_set_os_api_impl(void); @@ -17903,7 +19685,7 @@ void ecs_set_os_api_impl(void); * * The module addon allows for creating and importing modules. Flecs modules * enable applications to organize components and systems into reusable units of - * code that can easily be across projects. + * code that can easily be used across projects. */ #ifdef FLECS_MODULE @@ -17911,7 +19693,7 @@ void ecs_set_os_api_impl(void); /** * @defgroup c_addons_module Module * @ingroup c_addons - * Modules organize components, systems and more in reusable units of code. + * Modules organize components, systems, and more in reusable units of code. * * @{ */ @@ -17924,16 +19706,15 @@ extern "C" { #endif /** Import a module. - * This operation will load a modules and store the public module handles in the - * handles_out out parameter. The module name will be used to verify if the - * module was already loaded, in which case it won't be reimported. The name - * will be translated from PascalCase to an entity path (pascal.case) before the - * lookup occurs. + * This operation will load a module. The module name will be used to verify + * whether the module was already loaded, in which case it won't be reimported. + * The name will be translated from PascalCase to an entity path (pascal.case) + * before the lookup occurs. * * Module contents will be stored as children of the module entity. This * prevents modules from accidentally defining conflicting identifiers. This is * enforced by setting the scope before and after loading the module to the - * module entity id. + * module entity ID. * * A more convenient way to import a module is by using the ECS_IMPORT macro. * @@ -17972,13 +19753,14 @@ ecs_entity_t ecs_import_c( * * The library will be looked up using a canonical name, which is in the same * form as a module, like `flecs.components.transform`. To transform this - * identifier to a platform specific library name, the operation relies on the - * module_to_dl callback of the os_api which the application has to override if + * identifier to a platform-specific library name, the operation relies on the + * module_to_dl callback of the os_api, which the application has to override if * the default does not yield the correct library name. * * @param world The world. * @param library_name The name of the library to load. * @param module_name The name of the module to load. + * @return The module entity. */ FLECS_API ecs_entity_t ecs_import_from_library( @@ -17986,7 +19768,13 @@ ecs_entity_t ecs_import_from_library( const char *library_name, const char *module_name); -/** Register a new module. */ +/** Register a new module. + * + * @param world The world. + * @param c_name The name of the module. + * @param desc The component descriptor for the module component. + * @return The module entity. + */ FLECS_API ecs_entity_t ecs_module_init( ecs_world_t *world, @@ -18035,7 +19823,7 @@ ecs_entity_t ecs_module_init( #endif /** * @file addons/flecs_cpp.h - * @brief C++ utility functions + * @brief C++ utility functions. * * This header contains utility functions that are accessible from both C and * C++ code. These functions are not part of the public API and are not meant @@ -18075,19 +19863,45 @@ extern "C" { #endif +/** Get type name from compiler-generated function name. + * + * @param type_name Buffer to write the type name to. + * @param func_name The compiler-generated function name. + * @param len The length of the type name. + * @param front_len The number of characters to skip at the front. + * @return The type name. + */ FLECS_API char* ecs_cpp_get_type_name( - char *type_name, + char *type_name, const char *func_name, size_t len, size_t front_len); +/** Get symbol name from type name. + * + * @param symbol_name Buffer to write the symbol name to. + * @param type_name The type name. + * @param len The length of the type name. + * @return The symbol name. + */ FLECS_API char* ecs_cpp_get_symbol_name( + /* If symbol_name is NULL, the function allocates a buffer with ecs_os_malloc(). + * Callers must free the returned pointer with ecs_os_free(). */ char *symbol_name, const char *type_name, + /* If len is 0, the function derives it from type_name. */ size_t len); +/** Get constant name from compiler-generated function name. + * + * @param constant_name Buffer to write the constant name to. + * @param func_name The compiler-generated function name. + * @param len The length of the constant name. + * @param back_len The number of characters to skip at the back. + * @return The constant name. + */ FLECS_API char* ecs_cpp_get_constant_name( char *constant_name, @@ -18095,32 +19909,68 @@ char* ecs_cpp_get_constant_name( size_t len, size_t back_len); +/** Trim module prefix from type name. + * + * @param world The world. + * @param type_name The type name to trim. + * @return The trimmed type name. + */ FLECS_API const char* ecs_cpp_trim_module( ecs_world_t *world, const char *type_name); +typedef void (*ecs_cpp_type_action_t)( + ecs_world_t *world, + ecs_entity_t component); + +typedef struct ecs_cpp_component_desc_t { + ecs_entity_t id; + int32_t ids_index; + const char *name; + const char *cpp_name; + const char *cpp_symbol; + size_t size; + size_t alignment; + ecs_cpp_type_action_t lifecycle_action; + ecs_cpp_type_action_t enum_action; + bool is_component; + bool explicit_registration; +} ecs_cpp_component_desc_t; + +/** Register a C++ component. + * + * @param world The world. + * @param desc Component registration parameters. + */ FLECS_API ecs_entity_t ecs_cpp_component_register( ecs_world_t *world, - ecs_entity_t id, - int32_t ids_index, - const char *name, - const char *cpp_name, - const char *cpp_symbol, - size_t size, - size_t alignment, - bool is_component, - bool explicit_registration, - bool *registered_out, - bool *existing_out); + const ecs_cpp_component_desc_t *desc); +/** Initialize a C++ enum type. + * + * @param world The world. + * @param id The entity ID for the enum type. + * @param underlying_type The underlying integer type of the enum. + */ FLECS_API void ecs_cpp_enum_init( ecs_world_t *world, ecs_entity_t id, ecs_entity_t underlying_type); +/** Register a C++ enum constant. + * + * @param world The world. + * @param parent The parent enum type entity. + * @param id The entity ID for the constant. + * @param name The constant name. + * @param value Pointer to the constant value. + * @param value_type The type of the constant value. + * @param value_size The size of the constant value. + * @return The constant entity. + */ FLECS_API ecs_entity_t ecs_cpp_enum_constant_register( ecs_world_t *world, @@ -18131,11 +19981,23 @@ ecs_entity_t ecs_cpp_enum_constant_register( ecs_entity_t value_type, size_t value_size); +/** Result type for C++ set/assign operations. */ typedef struct ecs_cpp_get_mut_t { - void *ptr; - bool call_modified; + ecs_world_t *world; /**< The world. */ + ecs_stage_t *stage; /**< The stage. */ + void *ptr; /**< Pointer to the component data. */ + bool call_modified; /**< Whether modified should be called. */ } ecs_cpp_get_mut_t; +/** Set a component value for a C++ entity. + * + * @param world The world. + * @param entity The entity. + * @param component The component ID. + * @param new_ptr Pointer to the new component value. + * @param size The size of the component. + * @return Result containing the component pointer and metadata. + */ FLECS_API FLECS_ALWAYS_INLINE ecs_cpp_get_mut_t ecs_cpp_set( ecs_world_t *world, @@ -18144,6 +20006,15 @@ FLECS_ALWAYS_INLINE ecs_cpp_get_mut_t ecs_cpp_set( const void *new_ptr, size_t size); +/** Assign a component value for a C++ entity. + * + * @param world The world. + * @param entity The entity. + * @param component The component ID. + * @param new_ptr Pointer to the new component value. + * @param size The size of the component. + * @return Result containing the component pointer and metadata. + */ FLECS_API FLECS_ALWAYS_INLINE ecs_cpp_get_mut_t ecs_cpp_assign( ecs_world_t *world, @@ -18152,10 +20023,33 @@ FLECS_ALWAYS_INLINE ecs_cpp_get_mut_t ecs_cpp_assign( const void *new_ptr, size_t size); +/** Create a new entity from C++. + * + * @param world The world. + * @param parent The parent entity. + * @param name The entity name. + * @param sep The path separator. + * @param root_sep The root path separator. + * @return The new entity. + */ +FLECS_API +FLECS_ALWAYS_INLINE ecs_entity_t ecs_cpp_new( + ecs_world_t *world, + ecs_entity_t parent, + const char *name, + const char *sep, + const char *root_sep); + #ifdef FLECS_META +/** Get the last registered member for a type. + * + * @param world The world. + * @param type The type entity. + * @return Pointer to the last member, or NULL if none. + */ FLECS_API -const ecs_member_t* ecs_cpp_last_member( - const ecs_world_t *world, +ecs_member_t* ecs_cpp_last_member( + const ecs_world_t *world, ecs_entity_t type); #endif @@ -18218,7 +20112,7 @@ struct each_delegate; // Types imported from C API /** * @file addons/cpp/c_types.hpp - * @brief Aliases for types/constants from C API + * @brief Aliases for types/constants from C API. */ #pragma once @@ -18226,170 +20120,237 @@ struct each_delegate; namespace flecs { /** - * @defgroup cpp_globals API Types & Globals + * @defgroup cpp_globals API Types and Globals * @ingroup cpp_core - * Types & constants bridged from C API. + * Types and constants bridged from C API. * * @{ */ -using world_t = ecs_world_t; -using world_info_t = ecs_world_info_t; -using id_t = ecs_id_t; -using entity_t = ecs_entity_t; -using type_t = ecs_type_t; -using table_t = ecs_table_t; -using term_t = ecs_term_t; -using query_t = ecs_query_t; -using query_group_info_t = ecs_query_group_info_t; -using observer_t = ecs_observer_t; -using iter_t = ecs_iter_t; -using ref_t = ecs_ref_t; -using table_record_t = ecs_table_record_t; -using table_records_t = ecs_table_records_t; -using component_record_t = ecs_component_record_t; -using type_info_t = ecs_type_info_t; -using type_hooks_t = ecs_type_hooks_t; -using flags32_t = ecs_flags32_t; -using flags64_t = ecs_flags64_t; - +using world_t = ecs_world_t; /**< World type. */ +using world_info_t = ecs_world_info_t; /**< World info type. */ +using id_t = ecs_id_t; /**< ID type. */ +using entity_t = ecs_entity_t; /**< Entity type. */ +using type_t = ecs_type_t; /**< Type type. */ +using table_t = ecs_table_t; /**< Table type. */ +using term_t = ecs_term_t; /**< Term type. */ +using query_t = ecs_query_t; /**< Query type. */ +using query_group_info_t = ecs_query_group_info_t; /**< Query group info type. */ +using observer_t = ecs_observer_t; /**< Observer type. */ +using iter_t = ecs_iter_t; /**< Iterator type. */ +using ref_t = ecs_ref_t; /**< Ref type. */ +using table_record_t = ecs_table_record_t; /**< Table record type. */ +using table_records_t = ecs_table_records_t; /**< Table records type. */ +using component_record_t = ecs_component_record_t; /**< Component record type. */ +using type_info_t = ecs_type_info_t; /**< Type info type. */ +using type_hooks_t = ecs_type_hooks_t; /**< Type hooks type. */ +using flags32_t = ecs_flags32_t; /**< 32-bit flags type. */ +using flags64_t = ecs_flags64_t; /**< 64-bit flags type. */ + +/** Inout kind. */ enum inout_kind_t { - InOutDefault = EcsInOutDefault, - InOutNone = EcsInOutNone, - InOutFilter = EcsInOutFilter, - InOut = EcsInOut, - In = EcsIn, - Out = EcsOut + InOutDefault = EcsInOutDefault, /**< InOutDefault. */ + InOutNone = EcsInOutNone, /**< InOutNone. */ + InOutFilter = EcsInOutFilter, /**< InOutFilter. */ + InOut = EcsInOut, /**< InOut. */ + In = EcsIn, /**< In. */ + Out = EcsOut /**< Out. */ }; +/** Operator kind. */ enum oper_kind_t { - And = EcsAnd, - Or = EcsOr, - Not = EcsNot, - Optional = EcsOptional, - AndFrom = EcsAndFrom, - OrFrom = EcsOrFrom, - NotFrom = EcsNotFrom + And = EcsAnd, /**< And operator. */ + Or = EcsOr, /**< Or operator. */ + Not = EcsNot, /**< Not operator. */ + Optional = EcsOptional, /**< Optional operator. */ + AndFrom = EcsAndFrom, /**< AndFrom operator. */ + OrFrom = EcsOrFrom, /**< OrFrom operator. */ + NotFrom = EcsNotFrom /**< NotFrom operator. */ }; +/** Query cache kind. */ enum query_cache_kind_t { - QueryCacheDefault = EcsQueryCacheDefault, - QueryCacheAuto = EcsQueryCacheAuto, - QueryCacheAll = EcsQueryCacheAll, - QueryCacheNone = EcsQueryCacheNone + QueryCacheDefault = EcsQueryCacheDefault, /**< Default query cache. */ + QueryCacheAuto = EcsQueryCacheAuto, /**< Auto query cache. */ + QueryCacheAll = EcsQueryCacheAll, /**< Cache all. */ + QueryCacheNone = EcsQueryCacheNone /**< No caching. */ }; -/** Id bit flags */ -static const flecs::entity_t PAIR = ECS_PAIR; -static const flecs::entity_t AUTO_OVERRIDE = ECS_AUTO_OVERRIDE; -static const flecs::entity_t TOGGLE = ECS_TOGGLE; +/** ID bit flags. */ +static const flecs::entity_t PAIR = ECS_PAIR; /**< Pair flag. */ +static const flecs::entity_t AUTO_OVERRIDE = ECS_AUTO_OVERRIDE; /**< Auto override flag. */ +static const flecs::entity_t TOGGLE = ECS_TOGGLE; /**< Toggle flag. */ //////////////////////////////////////////////////////////////////////////////// -//// Builtin components and tags +//// Built-in components and tags //////////////////////////////////////////////////////////////////////////////// -/* Builtin components */ +/** Built-in EcsComponent type. */ using Component = EcsComponent; +/** Built-in EcsIdentifier type. */ using Identifier = EcsIdentifier; +/** Built-in EcsPoly type. */ using Poly = EcsPoly; +/** Built-in EcsDefaultChildComponent type. */ using DefaultChildComponent = EcsDefaultChildComponent; +/** Built-in EcsParent type. */ +using Parent = EcsParent; -/* Builtin tags */ +/** Built-in Query tag. */ static const flecs::entity_t Query = EcsQuery; +/** Built-in Observer tag. */ static const flecs::entity_t Observer = EcsObserver; -static const flecs::entity_t Private = EcsPrivate; +/** Built-in Module tag. */ static const flecs::entity_t Module = EcsModule; +/** Built-in Prefab tag. */ static const flecs::entity_t Prefab = EcsPrefab; +/** Built-in Disabled tag. */ static const flecs::entity_t Disabled = EcsDisabled; +/** Built-in Empty tag. */ static const flecs::entity_t Empty = EcsEmpty; +/** Built-in Monitor tag. */ static const flecs::entity_t Monitor = EcsMonitor; +/** Built-in System tag. */ static const flecs::entity_t System = EcsSystem; +/** Built-in Pipeline tag. */ static const flecs::entity_t Pipeline = ecs_id(EcsPipeline); +/** Built-in Phase tag. */ static const flecs::entity_t Phase = EcsPhase; +/** Built-in Constant tag. */ static const flecs::entity_t Constant = EcsConstant; +/** Built-in ParentDepth tag. */ +static const flecs::entity_t ParentDepth = EcsParentDepth; -/* Builtin event tags */ +/** Built-in OnAdd event. */ static const flecs::entity_t OnAdd = EcsOnAdd; +/** Built-in OnRemove event. */ static const flecs::entity_t OnRemove = EcsOnRemove; +/** Built-in OnSet event. */ static const flecs::entity_t OnSet = EcsOnSet; +/** Built-in OnTableCreate event. */ static const flecs::entity_t OnTableCreate = EcsOnTableCreate; +/** Built-in OnTableDelete event. */ static const flecs::entity_t OnTableDelete = EcsOnTableDelete; -/* Builtin term flags */ +/** Self term flag. */ static const uint64_t Self = EcsSelf; +/** Up term flag. */ static const uint64_t Up = EcsUp; +/** Trav term flag. */ static const uint64_t Trav = EcsTrav; +/** Cascade term flag. */ static const uint64_t Cascade = EcsCascade; +/** Desc term flag. */ static const uint64_t Desc = EcsDesc; +/** IsVariable term flag. */ static const uint64_t IsVariable = EcsIsVariable; +/** IsEntity term flag. */ static const uint64_t IsEntity = EcsIsEntity; +/** IsName term flag. */ static const uint64_t IsName = EcsIsName; +/** TraverseFlags term flag mask. */ static const uint64_t TraverseFlags = EcsTraverseFlags; +/** TermRefFlags term flag mask. */ static const uint64_t TermRefFlags = EcsTermRefFlags; -/* Builtin entity ids */ +/** Built-in Flecs entity. */ static const flecs::entity_t Flecs = EcsFlecs; +/** Built-in FlecsCore entity. */ static const flecs::entity_t FlecsCore = EcsFlecsCore; +/** Built-in World entity. */ static const flecs::entity_t World = EcsWorld; -/* Component traits */ +/** Wildcard entity. */ static const flecs::entity_t Wildcard = EcsWildcard; +/** Any entity. */ static const flecs::entity_t Any = EcsAny; +/** This variable entity. */ static const flecs::entity_t This = EcsThis; +/** Transitive trait. */ static const flecs::entity_t Transitive = EcsTransitive; +/** Reflexive trait. */ static const flecs::entity_t Reflexive = EcsReflexive; +/** Final trait. */ static const flecs::entity_t Final = EcsFinal; +/** Inheritable trait. */ static const flecs::entity_t Inheritable = EcsInheritable; +/** PairIsTag trait. */ static const flecs::entity_t PairIsTag = EcsPairIsTag; +/** Exclusive trait. */ static const flecs::entity_t Exclusive = EcsExclusive; +/** Acyclic trait. */ static const flecs::entity_t Acyclic = EcsAcyclic; +/** Traversable trait. */ static const flecs::entity_t Traversable = EcsTraversable; +/** Symmetric trait. */ static const flecs::entity_t Symmetric = EcsSymmetric; +/** With trait. */ static const flecs::entity_t With = EcsWith; +/** OneOf trait. */ static const flecs::entity_t OneOf = EcsOneOf; +/** Trait tag. */ static const flecs::entity_t Trait = EcsTrait; +/** Relationship tag. */ static const flecs::entity_t Relationship = EcsRelationship; +/** Target tag. */ static const flecs::entity_t Target = EcsTarget; +/** CanToggle trait. */ static const flecs::entity_t CanToggle = EcsCanToggle; -/* OnInstantiate trait */ +/** OnInstantiate trait. */ static const flecs::entity_t OnInstantiate = EcsOnInstantiate; +/** Override trait. */ static const flecs::entity_t Override = EcsOverride; +/** Inherit trait. */ static const flecs::entity_t Inherit = EcsInherit; +/** DontInherit trait. */ static const flecs::entity_t DontInherit = EcsDontInherit; -/* OnDelete/OnDeleteTarget traits */ +/** OnDelete cleanup trait. */ static const flecs::entity_t OnDelete = EcsOnDelete; +/** OnDeleteTarget cleanup trait. */ static const flecs::entity_t OnDeleteTarget = EcsOnDeleteTarget; +/** Remove cleanup action. */ static const flecs::entity_t Remove = EcsRemove; +/** Delete cleanup action. */ static const flecs::entity_t Delete = EcsDelete; +/** Panic cleanup action. */ static const flecs::entity_t Panic = EcsPanic; -/* Builtin relationships */ +/** IsA relationship. */ static const flecs::entity_t IsA = EcsIsA; +/** ChildOf relationship. */ static const flecs::entity_t ChildOf = EcsChildOf; +/** DependsOn relationship. */ static const flecs::entity_t DependsOn = EcsDependsOn; +/** SlotOf relationship. */ static const flecs::entity_t SlotOf = EcsSlotOf; -/* Misc */ +/** OrderedChildren tag. */ static const flecs::entity_t OrderedChildren = EcsOrderedChildren; +/** Singleton tag. */ static const flecs::entity_t Singleton = EcsSingleton; -/* Builtin identifiers */ +/** Name identifier. */ static const flecs::entity_t Name = EcsName; +/** Symbol identifier. */ static const flecs::entity_t Symbol = EcsSymbol; -/* Storage */ +/** Sparse storage tag. */ static const flecs::entity_t Sparse = EcsSparse; +/** DontFragment storage tag. */ static const flecs::entity_t DontFragment = EcsDontFragment; -/* Builtin predicates for comparing entity ids in queries. */ +/** PredEq query predicate. */ static const flecs::entity_t PredEq = EcsPredEq; +/** PredMatch query predicate. */ static const flecs::entity_t PredMatch = EcsPredMatch; +/** PredLookup query predicate. */ static const flecs::entity_t PredLookup = EcsPredLookup; -/* Builtin marker entities for query scopes */ +/** ScopeOpen query scope marker. */ static const flecs::entity_t ScopeOpen = EcsScopeOpen; +/** ScopeClose query scope marker. */ static const flecs::entity_t ScopeClose = EcsScopeClose; /** @} */ @@ -18401,20 +20362,19 @@ static const flecs::entity_t ScopeClose = EcsScopeClose; /** * @file addons/cpp/utils/utils.hpp * @brief Flecs STL (FTL?) - * - * Flecs STL (FTL?) - * Minimalistic utilities that allow for STL like functionality without having + * + * Minimalistic utilities that allow for STL-like functionality without having * to depend on the actual STL. */ -// Macros so that C++ new calls can allocate using ecs_os_api memory allocation functions +// Macros so that C++ new calls can allocate using ecs_os_api memory allocation functions. // Rationale: -// - Using macros here instead of a templated function bc clients might override ecs_os_malloc -// to contain extra debug info like source tracking location. Using a template function -// in that scenario would collapse all source location into said function vs. the -// actual call site -// - FLECS_PLACEMENT_NEW(): exists to remove any naked new calls/make it easy to identify any regressions -// by grepping for new/delete +// - Using macros here instead of a templated function because clients might override +// ecs_os_malloc to contain extra debug info like source tracking location. Using a +// template function in that scenario would collapse all source locations into said +// function vs. the actual call site. +// - FLECS_PLACEMENT_NEW(): exists to remove any naked new calls and make it easy to identify any +// regressions by grepping for new/delete. #define FLECS_PLACEMENT_NEW(_ptr, _type) ::new(flecs::_::placement_new_tag, _ptr) _type #define FLECS_NEW(_type) FLECS_PLACEMENT_NEW(ecs_os_malloc(sizeof(_type)), _type) @@ -18426,7 +20386,7 @@ static const flecs::entity_t ScopeClose = EcsScopeClose; } \ } while (false) -/* Faster (compile time) alternatives to std::move / std::forward. From: +/* Faster (compile-time) alternatives to std::move / std::forward. From: * https://www.foonathan.net/2020/09/move-forward/ */ @@ -18436,20 +20396,23 @@ static const flecs::entity_t ScopeClose = EcsScopeClose; #define FLECS_FWD(...) \ static_cast(__VA_ARGS__) -namespace flecs +namespace flecs { namespace _ { -// Dummy Placement new tag to disambiguate from any other operator new overrides +/** @private Placement new tag to disambiguate from other operator new overrides. */ struct placement_new_tag_t{}; +/** @private Placement new tag instance. */ constexpr placement_new_tag_t placement_new_tag{}; +/** @private Destruct an object without freeing memory. */ template inline void destruct_obj(Ty* _ptr) { _ptr->~Ty(); } -template inline void free_obj(void* _ptr) { +/** @private Destruct and free an object. */ +template inline void free_obj(void* _ptr) { if (_ptr) { - destruct_obj(static_cast(_ptr)); - ecs_os_free(_ptr); + destruct_obj(static_cast(_ptr)); + ecs_os_free(_ptr); } } @@ -18457,7 +20420,7 @@ template inline void free_obj(void* _ptr) { } // namespace flecs -// Allows overriding flecs_static_assert, which is useful when testing +// Allows overriding flecs_static_assert, which is useful when testing. #ifndef flecs_static_assert #define flecs_static_assert(cond, str) static_assert(cond, str) #endif @@ -18468,37 +20431,27 @@ inline void operator delete(void*, flecs::_::placement_new_tag_t, void*) n namespace flecs { -// faster (compile time) alternative to std::conditional +/** Compile-time conditional type selector (faster alternative to std::conditional). */ template struct condition; +/** Specialization of condition for false. */ template <> struct condition { + /** Select the second type. */ template using type = F; }; +/** Specialization of condition for true. */ template <> struct condition { + /** Select the first type. */ template using type = T; }; -// C++11/C++14 convenience template replacements - -template -using conditional_t = typename condition::template type; - -template -using decay_t = typename std::decay::type; - -template -using enable_if_t = typename std::enable_if::type; - -template -using remove_pointer_t = typename std::remove_pointer::type; - -template -using remove_reference_t = typename std::remove_reference::type; - -template -using underlying_type_t = typename std::underlying_type::type; - +using std::conditional_t; +using std::decay_t; +using std::enable_if_t; +using std::remove_pointer_t; +using std::remove_reference_t; +using std::underlying_type_t; using std::is_base_of; using std::is_empty; using std::is_const; @@ -18507,101 +20460,82 @@ using std::is_reference; using std::is_volatile; using std::is_same; using std::is_enum; - -// GCC 4.9.2 compatibility: missing C++11 type traits -#if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 9) -// Direct implementations for missing type traits in GCC 4.9.2 -} // namespace flecs - -namespace std { - // Only implement the ones that are actually missing in GCC 4.9.2 - template - struct is_trivially_constructible { - static const bool value = __is_pod(T); - }; - - template - struct is_trivially_move_assignable { - static const bool value = __is_pod(T); - }; - - template - struct is_trivially_copy_assignable { - static const bool value = __is_pod(T); - }; - - template - struct is_trivially_copy_constructible { - static const bool value = __is_pod(T); - }; - - template - struct is_trivially_move_constructible { - static const bool value = __is_pod(T); - }; - - template - struct is_trivially_copyable { - static const bool value = __is_pod(T); - }; -} - -namespace flecs { -#else using std::is_trivially_constructible; using std::is_trivially_move_assignable; using std::is_trivially_copy_assignable; using std::is_trivially_copy_constructible; using std::is_trivially_move_constructible; using std::is_trivially_copyable; -#endif - -// These exist in GCC 4.9.2, so we can always use them using std::is_move_assignable; using std::is_move_constructible; using std::is_copy_constructible; using std::is_trivially_destructible; - -// Determine constness even if T is a pointer type +using std::is_empty_v; +using std::is_const_v; +using std::is_pointer_v; +using std::is_reference_v; +using std::is_volatile_v; +using std::is_same_v; +using std::is_enum_v; +using std::is_base_of_v; +using std::is_trivially_constructible_v; +using std::is_trivially_destructible_v; +using std::is_trivially_copyable_v; +using std::is_trivially_move_constructible_v; +using std::is_trivially_copy_constructible_v; +using std::is_trivially_move_assignable_v; +using std::is_trivially_copy_assignable_v; +using std::is_default_constructible_v; +using std::is_move_constructible_v; +using std::is_copy_constructible_v; +using std::is_move_assignable_v; +using std::is_copy_assignable_v; +using std::is_destructible_v; + +/** Determine constness even if T is a pointer type. */ template using is_const_p = is_const< remove_pointer_t >; -// Apply cv modifiers from source type to destination type -// (from: https://stackoverflow.com/questions/52559336/add-const-to-type-if-template-arg-is-const) +/** Apply const from source type to destination type. */ template using transcribe_const_t = conditional_t::value, Dst const, Dst>; +/** Apply volatile from source type to destination type. */ template using transcribe_volatile_t = conditional_t::value, Dst volatile, Dst>; +/** Apply const and volatile from source type to destination type. */ template using transcribe_cv_t = transcribe_const_t< Src, transcribe_volatile_t< Src, Dst> >; +/** Apply pointer from source type to destination type. */ template using transcribe_pointer_t = conditional_t::value, Dst*, Dst>; +/** Apply const, volatile, and pointer from source type to destination type. */ template using transcribe_cvp_t = transcribe_cv_t< Src, transcribe_pointer_t< Src, Dst> >; -// More convenience templates. The if_*_t templates use int as default type -// instead of void. This enables writing code that's a bit less cluttered when -// the templates are used in a template declaration: -// -// enable_if_t* = nullptr -// vs: -// if_t = 0 - +/** Convenience enable_if alias using int as default type. + * This enables writing code that's a bit less cluttered when + * the templates are used in a template declaration: + * + * enable_if_t* = nullptr + * vs: + * if_t = 0 + */ template using if_t = enable_if_t; +/** Convenience enable_if alias for negated conditions. */ template using if_not_t = enable_if_t; namespace _ { -// Utility to prevent static assert from immediately triggering +/** @private Utility to prevent a static assert from immediately triggering. */ template struct always_false { static const bool value = false; @@ -18614,31 +20548,36 @@ struct always_false { /** * @file addons/cpp/utils/array.hpp * @brief Array class. - * - * Array class. Simple std::array like utility that is mostly there to aid + * + * Array class. Simple std::array-like utility that is mostly there to aid * template code where template expansion would lead to an array with size 0. */ namespace flecs { +/** Iterator for flecs::array. */ template struct array_iterator { + /** Construct an iterator from a pointer and index. */ explicit array_iterator(T* value, int index) { value_ = value; index_ = index; } + /** Inequality comparison operator. */ bool operator!=(array_iterator const& other) const { return index_ != other.index_; } + /** Dereference operator. */ T & operator*() const { return value_[index_]; } + /** Pre-increment operator. */ array_iterator& operator++() { ++index_; @@ -18650,13 +20589,17 @@ struct array_iterator int index_; }; -template +/** Array class (primary template, disabled). */ +template struct array final { }; +/** Array class specialization for non-zero sizes. */ template struct array > final { + /** Default constructor. */ array() {}; + /** Construct from a C array. */ array(const T (&elems)[Size]) { int i = 0; for (auto it = this->begin(); it != this->end(); ++ it) { @@ -18664,30 +20607,37 @@ struct array > final { } } + /** Element access by int index. */ T& operator[](int index) { return array_[index]; } + /** Element access by size_t index. */ T& operator[](size_t index) { return array_[index]; } + /** Return an iterator to the beginning. */ array_iterator begin() { return array_iterator(array_, 0); } + /** Return an iterator to the end. */ array_iterator end() { return array_iterator(array_, Size); } + /** Return the number of elements. */ size_t size() { return Size; } + /** Return a pointer to the underlying data. */ T* ptr() { return array_; } + /** Invoke a function for each element. */ template void each(const Func& func) { for (auto& elem : *this) { @@ -18699,24 +20649,32 @@ struct array > final { T array_[Size]; }; +/** Create a flecs::array from a C array. */ template array to_array(const T (&elems)[Size]) { return array(elems); } -// Specialized class for zero-sized array +/** Array class specialization for zero-sized arrays. */ template struct array> final { + /** Default constructor. */ array() {}; + /** Construct from a pointer (no-op). */ array(const T* (&elems)) { (void)elems; } + /** Element access (aborts, array is empty). */ T operator[](size_t index) { ecs_os_abort(); (void)index; return T(); } + /** Return an iterator to the beginning (empty range). */ array_iterator begin() { return array_iterator(nullptr, 0); } + /** Return an iterator to the end (empty range). */ array_iterator end() { return array_iterator(nullptr, 0); } + /** Return the number of elements (always 0). */ size_t size() { return 0; } + /** Return a null pointer (no data). */ T* ptr() { return NULL; } @@ -18733,20 +20691,25 @@ namespace flecs { struct string_view; -// This removes dependencies on std::string (and therefore STL) and allows the -// API to return allocated strings without incurring additional allocations when -// wrapping in an std::string. +/** Owned string wrapper. + * This removes dependencies on std::string (and therefore STL) and allows the + * API to return allocated strings without incurring additional allocations when + * wrapping in an std::string. + */ struct string { - explicit string() + /** Default constructor. */ + explicit string() : str_(nullptr) , const_str_("") , length_(0) { } - explicit string(char *str) + /** Construct from an owned char pointer. */ + explicit string(char *str) : str_(str) , const_str_(str ? str : "") , length_(str ? ecs_os_strlen(str) : 0) { } + /** Destructor. Free the owned string if set. */ ~string() { // If flecs is included in a binary but is not used, it is possible that // the OS API is not initialized. Calling ecs_os_free in that case could @@ -18757,6 +20720,7 @@ struct string { } } + /** Move constructor. */ string(string&& str) noexcept { ecs_os_free(str_); str_ = str.str_; @@ -18765,10 +20729,12 @@ struct string { str.str_ = nullptr; } + /** Implicit conversion to const char*. */ operator const char*() const { return const_str_; } + /** Move assignment operator. */ string& operator=(string&& str) noexcept { ecs_os_free(str_); str_ = str.str_; @@ -18778,10 +20744,12 @@ struct string { return *this; } - // Ban implicit copies/allocations + /** Ban implicit copies/allocations. */ string& operator=(const string& str) = delete; + /** Ban implicit copies/allocations. */ string(const string& str) = delete; + /** Equality operator. */ bool operator==(const flecs::string& str) const { if (str.const_str_ == const_str_) { return true; @@ -18798,10 +20766,12 @@ struct string { return ecs_os_strcmp(str, const_str_) == 0; } + /** Inequality operator. */ bool operator!=(const flecs::string& str) const { return !(*this == str); - } + } + /** Equality operator for a C string. */ bool operator==(const char *str) const { if (const_str_ == str) { return true; @@ -18814,33 +20784,40 @@ struct string { return ecs_os_strcmp(str, const_str_) == 0; } + /** Inequality operator for a C string. */ bool operator!=(const char *str) const { return !(*this == str); - } + } + /** Return the C string. */ const char* c_str() const { return const_str_; } + /** Return the string length. */ std::size_t length() const { return static_cast(length_); } + /** Return the length of a string literal at compile time. */ template static constexpr size_t length( char const (&)[N] ) { return N - 1; } + /** Return the string size (same as length). */ std::size_t size() const { return length(); } + /** Clear the string, freeing the owned memory. */ void clear() { ecs_os_free(str_); str_ = nullptr; const_str_ = nullptr; } + /** Check if the string contains a substring. */ bool contains(const char *substr) { if (const_str_) { return strstr(const_str_, substr) != nullptr; @@ -18850,11 +20827,13 @@ struct string { } protected: - // Must be constructed through string_view. This allows for using the string - // class for both owned and non-owned strings, which can reduce allocations - // when code conditionally should store a literal or an owned string. - // Making this constructor private forces the code to explicitly create a - // string_view which emphasizes that the string won't be freed by the class. + /** Construct from a non-owned C string. + * Must be constructed through string_view. This allows for using the string + * class for both owned and non-owned strings, which can reduce allocations + * when code conditionally should store a literal or an owned string. + * Making this constructor protected forces the code to explicitly create a + * string_view, which emphasizes that the string won't be freed by the class. + */ string(const char *str) : str_(nullptr) , const_str_(str ? str : "") @@ -18865,11 +20844,14 @@ struct string { ecs_size_t length_; }; -// For consistency, the API returns a string_view where it could have returned -// a const char*, so an application won't have to think about whether to call -// c_str() or not. The string_view is a thin wrapper around a string that forces -// the API to indicate explicitly when a string is owned or not. +/** Non-owning string view. + * For consistency, the API returns a string_view where it could have returned + * a const char*, so an application won't have to think about whether to call + * c_str() or not. The string_view is a thin wrapper around a string that forces + * the API to indicate explicitly when a string is owned or not. + */ struct string_view : string { + /** Construct from a C string (non-owning). */ explicit string_view(const char *str) : string(str) { } }; @@ -18878,25 +20860,25 @@ struct string_view : string { /** * @file addons/cpp/utils/enum.hpp - * @brief Compile time enum reflection utilities. - * - * Discover at compile time valid enumeration constants for an enumeration type + * @brief Compile-time enum reflection utilities. + * + * Discover at compile time the valid enumeration constants for an enumeration type * and their names. This is used to automatically register enum constants. */ #include -// 126, so that FLECS_ENUM_MAX_COUNT is 127 which is the largest value +// 126, so that FLECS_ENUM_MAX_COUNT is 127, which is the largest value // representable by an int8_t. #define FLECS_ENUM_MAX(T) _::to_constant::value #define FLECS_ENUM_MAX_COUNT (FLECS_ENUM_MAX(int) + 1) -// Flag to turn off enum reflection +// Flag to turn off enum reflection. #ifdef FLECS_CPP_NO_ENUM_REFLECTION #define FLECS_CPP_ENUM_REFLECTION_SUPPORT 0 #endif -// Test if we're using a compiler that supports the required features +// Test if we're using a compiler that supports the required features. #ifndef FLECS_CPP_ENUM_REFLECTION_SUPPORT #if !defined(__clang__) && defined(__GNUC__) #if __GNUC__ > 7 || (__GNUC__ == 7 && __GNUC_MINOR__ >= 5) @@ -18920,8 +20902,9 @@ struct string_view : string { namespace flecs { -/** Int to enum */ +/** Int to enum. */ namespace _ { +/** @private Convert an integral value to an enum constant. */ template Value> struct to_constant { static constexpr E value = flecs_enum_cast(E, Value); @@ -18931,19 +20914,27 @@ template Value> constexpr E to_constant::value; } -/** Convenience type with enum reflection data */ +/** Convenience type with enum reflection data. */ template struct enum_data; +/** Get enum reflection data for an enum type. + * @tparam E The enum type. + * @param world The world. + * @return Enum data wrapper. + */ template static enum_data enum_type(flecs::world_t *world); +/** Trait to define the last valid enum value for reflection. + * @tparam E The enum type. + */ template struct enum_last { static constexpr E value = FLECS_ENUM_MAX(E); }; -/* Utility macro to override enum_last trait */ +/* Utility macro to override the enum_last trait. */ #define FLECS_ENUM_LAST(T, Last)\ namespace flecs {\ template<>\ @@ -18960,7 +20951,7 @@ namespace _ { #define ECS_SIZE_T_STR "unsigned __int64" #else #define ECS_SIZE_T_STR "unsigned int" - #endif + #endif #elif defined(__clang__) #define ECS_SIZE_T_STR "size_t" #else @@ -18976,7 +20967,7 @@ namespace _ { #define ECS_SIZE_T_STR "unsigned __int32" #else #define ECS_SIZE_T_STR "unsigned int" - #endif + #endif #elif defined(__clang__) #define ECS_SIZE_T_STR "size_t" #else @@ -18988,16 +20979,18 @@ namespace _ { #endif #endif +/** @private Compute the type name length for an enum type. */ template constexpr size_t enum_type_len() { - return ECS_FUNC_TYPE_LEN(, enum_type_len, ECS_FUNC_NAME) + return ECS_FUNC_TYPE_LEN(, enum_type_len, ECS_FUNC_NAME) - (sizeof(ECS_SIZE_T_STR) - 1u); } -/** Test if value is valid for enumeration. - * This function leverages that when a valid value is provided, - * __PRETTY_FUNCTION__ contains the enumeration name, whereas if a value is - * invalid, the string contains a number or a negative (-) symbol. */ +/** Test if a value is valid for an enumeration. + * This function leverages that when a valid value is provided, the compiler's + * function name string (ECS_FUNC_NAME) contains the enumeration constant name, + * whereas if a value is invalid, the string contains a cast expression or + * numeric representation. */ #if defined(ECS_TARGET_CLANG) #if ECS_CLANG_VERSION < 13 template @@ -19014,7 +21007,7 @@ constexpr bool enum_constant_is_valid() { template constexpr bool enum_constant_is_valid() { return (ECS_FUNC_NAME[ECS_FUNC_NAME_FRONT(bool, enum_constant_is_valid) + - enum_type_len() + 6 /* ', E C = ' */] != '('); + enum_type_len() + 6 /* ', C = ' */] != '('); } #endif #elif defined(ECS_TARGET_GNU) @@ -19024,28 +21017,57 @@ constexpr bool enum_constant_is_valid() { enum_type_len() + 8 /* ', E C = ' */] != '('); } #else -/* Use different trick on MSVC, since it uses hexadecimal representation for - * invalid enum constants. We can leverage that msvc inserts a C-style cast - * into the name, and the location of its first character ('(') is known. */ +template +constexpr size_t enum_template_arg_separator( + const char (&func_name)[N], + size_t pos, + size_t end, + size_t depth = 0) +{ + return pos >= end + ? end + : func_name[pos] == '<' + ? enum_template_arg_separator(func_name, pos + 1, end, depth + 1) + : func_name[pos] == '>' + ? enum_template_arg_separator( + func_name, pos + 1, end, depth ? depth - 1 : 0) + : (func_name[pos] == ',' && !depth) + ? pos + : enum_template_arg_separator( + func_name, pos + 1, end, depth); +} + +/* Use a different trick on MSVC, since it uses a hexadecimal representation for + * invalid enum constants. We can leverage that MSVC inserts a C-style cast + * into the name. Find the template argument separator structurally instead of + * relying on the exact spelling of __FUNCSIG__ for the enum type. */ template constexpr bool enum_constant_is_valid() { - return ECS_FUNC_NAME[ECS_FUNC_NAME_FRONT(bool, enum_constant_is_valid) + - enum_type_len() + 1] != '('; + return enum_template_arg_separator( + ECS_FUNC_NAME, + ECS_FUNC_NAME_FRONT(bool, enum_constant_is_valid), + sizeof(ECS_FUNC_NAME) - ECS_FUNC_NAME_BACK - 1u) < + (sizeof(ECS_FUNC_NAME) - ECS_FUNC_NAME_BACK - 1u) && + ECS_FUNC_NAME[enum_template_arg_separator( + ECS_FUNC_NAME, + ECS_FUNC_NAME_FRONT(bool, enum_constant_is_valid), + sizeof(ECS_FUNC_NAME) - ECS_FUNC_NAME_BACK - 1u) + 1u] != '('; } #endif -/* Without this wrapper __builtin_bit_cast doesn't work */ +/** @private Wrapper for enum_constant_is_valid() using the underlying type. */ template C> constexpr bool enum_constant_is_valid_wrap() { return enum_constant_is_valid(); } +/** @private Check if an enum constant is valid (value trait). */ template struct enum_is_valid { static constexpr bool value = enum_constant_is_valid(); }; -/** Extract name of constant from string */ +/** @private Extract the name of a constant from the compiler string. */ template static const char* enum_constant_to_name() { static const size_t len = ECS_FUNC_TYPE_LEN( @@ -19057,12 +21079,12 @@ static const char* enum_constant_to_name() { } /** - * @brief Provides utilities for enum reflection. - * - * This struct provides static functions for enum reflection, including - * conversion between enum values and their underlying integral types, and + * @brief Provide utilities for enum reflection. + * + * This struct provides static functions for enum reflection, including + * conversion between enum values and their underlying integral types, and * iteration over enum values. - * + * * @tparam E The enum type. * @tparam Handler The handler for enum reflection operations. */ @@ -19071,19 +21093,19 @@ struct enum_reflection { using U = underlying_type_t; /** - * @brief Iterates over the range [Low, High] of enum values between Low and + * @brief Iterate over the range [Low, High] of enum values between Low and * High. * - * Recursively divide and conquers the search space to reduce the - * template-depth. Once recursive division is complete, calls - * Handle::handle_constant in ascending order, passing the values + * Recursively divide and conquer the search space to reduce the + * template depth. Once recursive division is complete, call + * Handler::handle_constant() in ascending order, passing the values * computed up the chain. - * + * * @tparam Low The lower bound of the search range, inclusive. * @tparam High The upper bound of the search range, inclusive. - * @tparam Args Additional arguments to be passed through to Handler::handle_constant + * @tparam Args Additional arguments to be passed through to Handler::handle_constant(). * @param last_value The last value processed in the iteration. - * @param args Additional arguments to be passed through to Handler::handle_constant + * @param args Additional arguments to be passed through to Handler::handle_constant(). * @return constexpr U The result of the iteration. */ template @@ -19092,7 +21114,7 @@ struct enum_reflection { ? High == Low ? Handler::template handle_constant(last_value, args...) : Handler::template handle_constant( - Handler::template handle_constant(last_value, args...), + Handler::template handle_constant(last_value, args...), args...) : each_enum_range<(Low + High) / 2 + 1, High>( each_enum_range(last_value, args...), @@ -19101,24 +21123,24 @@ struct enum_reflection { } /** - * @brief Iterates over the mask range (Low, High] of enum values between + * @brief Iterate over the mask range (Low, High] of enum values between * Low and High. * - * Recursively iterates the search space, looking for enums defined as - * multiple-of-2 bitmasks. Each iteration, shifts bit to the right until it - * hits Low, then calls Handler::handle_constant for each bitmask in + * Recursively iterate the search space, looking for enums defined as + * multiple-of-2 bitmasks. Each iteration shifts the bit to the right until it + * hits Low, then calls Handler::handle_constant() for each bitmask in * ascending order. - * - * @tparam Low The lower bound of the search range, not inclusive + * + * @tparam Low The lower bound of the search range, not inclusive. * @tparam High The upper bound of the search range, inclusive. - * @tparam Args Additional arguments to be passed through to Handler::handle_constant + * @tparam Args Additional arguments to be passed through to Handler::handle_constant(). * @param last_value The last value processed in the iteration. - * @param args Additional arguments to be passed through to Handler::handle_constant + * @param args Additional arguments to be passed through to Handler::handle_constant(). * @return constexpr U The result of the iteration. */ template static constexpr U each_mask_range(U last_value, Args&... args) { - // If Low shares any bits with Current Flag, or if High is less + // If Low shares any bits with Current Flag, or if High is less // than/equal to Low (and High isn't negative because max-flag signed) return (Low & High) || (High <= Low && High != high_bit) ? last_value @@ -19129,15 +21151,15 @@ struct enum_reflection { } /** - * @brief Handles enum iteration for gathering reflection data. + * @brief Handle enum iteration for gathering reflection data. * - * Iterates over all enum values up to a specified maximum value - * (each_enum_range<0, Value>), then iterates the rest of the possible bitmasks + * Iterate over all enum values up to a specified maximum value + * (each_enum_range<0, Value>), then iterate over the rest of the possible bitmasks * (each_mask_range). - * + * * @tparam Value The maximum enum value to iterate up to. - * @tparam Args Additional arguments to be passed through to Handler::handle_constant - * @param args Additional arguments to be passed through to Handler::handle_constant + * @tparam Args Additional arguments to be passed through to Handler::handle_constant(). + * @param args Additional arguments to be passed through to Handler::handle_constant(). * @return constexpr U The result of the iteration. */ template (FLECS_ENUM_MAX(E)), typename... Args> @@ -19145,23 +21167,29 @@ struct enum_reflection { return each_mask_range( each_enum_range<0, Value>(0, args...), args...); } - /* to avoid warnings with bit manipulation, calculate the high bit with an - unsigned type of the same size: */ + /* To avoid warnings with bit manipulation, calculate the high bit with an + unsigned type of the same size. */ using UU = typename std::make_unsigned::type; - static const U high_bit = + static const U high_bit = static_cast(static_cast(1) << (sizeof(UU) * 8 - 1)); }; -/** Enumeration constant data */ +/** Enumeration constant data. + * @tparam T The underlying type of the enum. + */ template struct enum_constant { - int32_t index; // Global index used to obtain world local entity id + /** Global index used to obtain a world-local entity ID. */ + int32_t index; + /** The constant value. */ T value; + /** Offset from the previous constant value. */ T offset; + /** The constant name. */ const char *name; }; -/** Class that scans an enum for constants, extracts names & creates entities */ +/** @private Class that scans an enum for constants, extracts names, and creates entities. */ template struct enum_type { private: @@ -19169,80 +21197,75 @@ struct enum_type { using U = underlying_type_t; /** - * @brief Handler struct for generating compile-time count of enum constants. + * @brief Handler struct for generating a compile-time count of enum constants. */ struct reflection_count { - template () > = 0> - static constexpr U handle_constant(U last_value) { - return last_value; - } - - template () > = 0> + template static constexpr U handle_constant(U last_value) { - return 1 + last_value; + if constexpr (enum_constant_is_valid_wrap()) { + return 1 + last_value; + } else { + return last_value; + } } }; /** - * @brief Helper struct for filling enum_type's static `enum_data_impl` - * member with reflection data. + * @brief Helper struct for filling `enum_type`'s static + * members with reflection data. * - * Because reflection occurs in-order, we can use current value/last value + * Because reflection occurs in order, we can use current value/last value * to determine continuity, and use that as a lookup heuristic later on. */ struct reflection_init { - template () > = 0> - static U handle_constant(U last_value, This&) { - // Search for constant failed. Pass last valid value through. - return last_value; - } - - template () > = 0> + template static U handle_constant(U last_value, This& me) { - // Constant is valid, so fill reflection data. - auto v = Value; - const char *name = enum_constant_to_name(); + if constexpr (enum_constant_is_valid_wrap()) { + // Constant is valid, so fill the reflection data. + auto v = Value; + const char *name = enum_constant_to_name(); - ++me.max; // Increment cursor as we build constants array. + ++me.max; // Increment cursor as we build the constants array. - // If the enum was previously contiguous, and continues to be - // through the current value... - if (me.has_contiguous && static_cast(me.max) == v && me.contiguous_until == v) { - ++me.contiguous_until; - } + // If the enum was previously contiguous, and continues to be + // through the current value... + if (me.has_contiguous && static_cast(me.max) == v && me.contiguous_until == v) { + ++me.contiguous_until; + } - // else, if the enum was never contiguous and hasn't been set as not - // contiguous... - else if (!me.contiguous_until && me.has_contiguous) { - me.has_contiguous = false; - } + // else, if the enum was never contiguous and hasn't been set as not + // contiguous... + else if (!me.contiguous_until && me.has_contiguous) { + me.has_contiguous = false; + } - ecs_assert(!(last_value > 0 && - v < std::numeric_limits::min() + last_value), - ECS_UNSUPPORTED, - "Signed integer enums causes integer overflow when recording " - "offset from high positive to low negative. Consider using " - "unsigned integers as underlying type."); - - me.constants[me.max].value = v; - me.constants[me.max].offset = v - last_value; - me.constants[me.max].name = name; - if (!me.constants[me.max].index) { - me.constants[me.max].index = - flecs_component_ids_index_get(); - } + ecs_assert(!(last_value > 0 && + v < std::numeric_limits::min() + last_value), + ECS_UNSUPPORTED, + "Signed integer enums cause integer overflow when recording " + "offset from high positive to low negative. Consider using " + "unsigned integers as the underlying type."); + + me.constants[me.max].value = v; + me.constants[me.max].offset = v - last_value; + me.constants[me.max].name = name; + if (!me.constants[me.max].index) { + me.constants[me.max].index = + flecs_component_ids_index_get(); + } - return v; + return v; + } else { + // Search for the constant failed. Pass the last valid value through. + return last_value; + } } }; public: + /** Constructor. Initialize reflection data for the enum type. */ enum_type() { - // Initialize/reset reflection data values to default state. + // Initialize/reset reflection data values to the default state. min = 0; max = -1; has_contiguous = true; @@ -19254,11 +21277,13 @@ struct enum_type { #endif } + /** Get the singleton instance of enum_type for the given enum. */ static enum_type& get() { static _::enum_type instance; return instance; } + /** Get entity for a given enum value. */ flecs::entity_t entity(E value) const { int index = index_by_value(value); if (index >= 0) { @@ -19267,6 +21292,7 @@ struct enum_type { return 0; } + /** Register enum constants for a world. */ void register_for_world(flecs::world_t *world, flecs::entity_t id) { #if !FLECS_CPP_ENUM_REFLECTION_SUPPORT ecs_abort(ECS_UNSUPPORTED, "enum reflection requires gcc 7.5 or higher") @@ -19278,30 +21304,30 @@ struct enum_type { for (U v = 0; v < static_cast(max + 1); v ++) { if (constants[v].index) { flecs::entity_t constant = ecs_cpp_enum_constant_register(world, - type::id(world), 0, constants[v].name, &constants[v].value, + type::id(world), 0, constants[v].name, &constants[v].value, type::id(world), sizeof(U)); flecs_component_ids_set(world, constants[v].index, constant); } } - + ecs_log_pop(); } int min; int max; - // If enum constants start not-sparse, contiguous_until will be the index of - // the first sparse value, or end of the constants array + // If enum constants start non-sparse, contiguous_until will be the index of + // the first sparse value, or the end of the constants array. U contiguous_until; - // Compile-time generated count of enum constants. - static constexpr unsigned int constants_size = + // Compile-time-generated count of enum constants. + static constexpr unsigned int constants_size = enum_reflection:: template each_enum< static_cast(enum_last::value) >(); - // Constants array is sized to the number of found-constants, or 1 - // to avoid 0-sized array. + // Constants array is sized to the number of found constants, or 1 + // to avoid a zero-sized array. #ifdef FLECS_CPP_ENUM_REFLECTION enum_constant constants[constants_size? constants_size: 1] = {}; bool has_contiguous; @@ -19309,32 +21335,34 @@ struct enum_type { // If we're not using enum reflection, we cannot statically determine the // upper bound of the enum, so use 128. enum_constant constants[128] = {}; - bool has_contiguous = true; // Assume contiguous ids + bool has_contiguous = true; // Assume contiguous IDs. #endif }; -template ::value > = 0> +/** @private Initialize enum reflection for a world. */ +template inline static void init_enum(flecs::world_t *world, flecs::entity_t id) { - _::enum_type::get().register_for_world(world, id); + (void)world; (void)id; + if constexpr (is_enum_v) { + _::enum_type::get().register_for_world(world, id); + } } -template ::value > = 0> -inline static void init_enum(flecs::world_t*, flecs::entity_t) { } - } // namespace _ -/** Enumeration type data wrapper with world pointer */ +/** Enumeration type data wrapper with world pointer. */ template struct enum_data { using U = underlying_type_t; + /** Construct enum_data from a world and an enum_type implementation. */ enum_data(flecs::world_t *world, _::enum_type& impl) : world_(world) , impl_(impl) { } - + /** - * @brief Checks if a given integral value is a valid enum value. - * + * @brief Check if a given integral value is a valid enum value. + * * @param value The integral value. * @return true If the value is a valid enum value. * @return false If the value is not a valid enum value. @@ -19348,8 +21376,8 @@ struct enum_data { } /** - * @brief Checks if a given enum value is valid. - * + * @brief Check if a given enum value is valid. + * * @param value The enum value. * @return true If the value is valid. * @return false If the value is not valid. @@ -19359,9 +21387,9 @@ struct enum_data { } /** - * @brief Finds the index into the constants array for a value, if one exists - * - * @param value The enum value. + * @brief Find the index into the constants array for a value, if one exists. + * + * @param value The underlying integral value. * @return int The index of the enum value. */ int index_by_value(U value) const { @@ -19369,7 +21397,7 @@ struct enum_data { return -1; } - // Check if value is in contiguous lookup section + // Check if value is in the contiguous lookup section. if (impl_.has_contiguous && value < impl_.contiguous_until && value >= 0) { return static_cast(value); } @@ -19384,8 +21412,8 @@ struct enum_data { } /** - * @brief Finds the index into the constants array for an enum value, if one exists - * + * @brief Find the index into the constants array for an enum value, if one exists. + * * @param value The enum value. * @return int The index of the enum value. */ @@ -19393,27 +21421,33 @@ struct enum_data { return index_by_value(static_cast(value)); } + /** Return the index of the first constant. */ int first() const { return impl_.min; } + /** Return the index of the last constant. */ int last() const { return impl_.max; } + /** Return the next constant index after the given one. */ int next(int cur) const { return cur + 1; } + /** Get entity for the enum type. */ flecs::entity entity() const; + /** Get entity for a given underlying enum value. */ flecs::entity entity(U value) const; + /** Get entity for a given enum value. */ flecs::entity entity(E value) const; /** - * @brief Manually register constant for enum. - * - * If automatic enum reflection is not supported, provide method for - * manually registering constant. + * @brief Manually register a constant for an enum. + * + * If automatic enum reflection is not supported, provide a method for + * manually registering a constant. */ #ifdef FLECS_CPP_NO_ENUM_REFLECTION void register_constant(flecs::world_t *world, U v, flecs::entity_t e) { @@ -19437,10 +21471,10 @@ struct enum_data { _::enum_type& impl_; }; -/** Convenience function for getting enum reflection data */ +/** Convenience function for getting enum reflection data. */ template enum_data enum_type(flecs::world_t *world) { - _::type::id(world); // Ensure enum is registered + _::type::id(world); // Ensure the enum is registered. auto& ref = _::enum_type::get(); return enum_data(world, ref); } @@ -19449,25 +21483,30 @@ enum_data enum_type(flecs::world_t *world) { /** * @file addons/cpp/utils/stringstream.hpp - * @brief Wrapper around ecs_strbuf_t that provides a simple stringstream like API. + * @brief Wrapper around ecs_strbuf_t that provides a simple stringstream-like API. */ namespace flecs { +/** Simple stringstream wrapper around ecs_strbuf_t. */ struct stringstream { - explicit stringstream() + /** Default constructor. */ + explicit stringstream() : buf_({}) { } + /** Destructor. Reset the internal buffer. */ ~stringstream() { ecs_strbuf_reset(&buf_); } + /** Move constructor. */ stringstream(stringstream&& str) noexcept { ecs_strbuf_reset(&buf_); buf_ = str.buf_; str.buf_ = {}; } + /** Move assignment operator. */ stringstream& operator=(stringstream&& str) noexcept { ecs_strbuf_reset(&buf_); buf_ = str.buf_; @@ -19475,15 +21514,18 @@ struct stringstream { return *this; } - // Ban implicit copies/allocations + /** Ban implicit copies/allocations. */ stringstream& operator=(const stringstream& str) = delete; - stringstream(const stringstream& str) = delete; + /** Ban implicit copies/allocations. */ + stringstream(const stringstream& str) = delete; + /** Append a C string to the stream. */ stringstream& operator<<(const char* str) { ecs_strbuf_appendstr(&buf_, str); return *this; } + /** Get the accumulated string as an owned flecs::string. */ flecs::string str() { return flecs::string(ecs_strbuf_get(&buf_)); } @@ -19496,18 +21538,21 @@ struct stringstream { /** * @file addons/cpp/utils/function_traits.hpp - * @brief Compile time utilities to inspect properties of functions. + * @brief Compile-time utilities to inspect properties of functions. * * Code from: https://stackoverflow.com/questions/27024238/c-template-mechanism-to-get-the-number-of-function-arguments-which-would-work */ +#pragma once + namespace flecs { namespace _ { +/** @private Argument list type holder. */ template struct arg_list { }; -// Base type that contains the traits +/** @private Base type that contains the function traits definitions. */ template struct function_traits_defs { @@ -19517,139 +21562,178 @@ struct function_traits_defs using args = arg_list; }; -// Primary template for function_traits_impl +/** @private Primary template for function_traits_impl. */ template struct function_traits_impl { static constexpr bool is_callable = false; }; -// Template specializations for the different kinds of function types (whew) +/** @private Specialization for free functions. */ template struct function_traits_impl : function_traits_defs {}; +/** @private Specialization for function pointers. */ template struct function_traits_impl : function_traits_defs {}; +/** @private Specialization for member function pointers. */ template struct function_traits_impl : function_traits_defs {}; +/** @private Specialization for const member function pointers. */ template struct function_traits_impl - : function_traits_defs {}; + : function_traits_defs {}; +/** @private Specialization for const& member function pointers. */ template struct function_traits_impl : function_traits_defs {}; - + +/** @private Specialization for const&& member function pointers. */ template struct function_traits_impl : function_traits_defs {}; - + +/** @private Specialization for volatile member function pointers. */ template struct function_traits_impl : function_traits_defs {}; +/** @private Specialization for volatile& member function pointers. */ template struct function_traits_impl : function_traits_defs {}; - + +/** @private Specialization for volatile&& member function pointers. */ template struct function_traits_impl : function_traits_defs {}; +/** @private Specialization for const volatile member function pointers. */ template struct function_traits_impl : function_traits_defs {}; +/** @private Specialization for const volatile& member function pointers. */ template struct function_traits_impl : function_traits_defs {}; - + +/** @private Specialization for const volatile&& member function pointers. */ template struct function_traits_impl : function_traits_defs {}; -// Primary template for function_traits_no_cv. If T is not a function, the -// compiler will attempt to instantiate this template and fail, because its base -// is undefined. +/** @private Primary template for function_traits_no_cv. */ template struct function_traits_no_cv : function_traits_impl {}; -// Specialized template for function types +/** @private Specialization for callable objects with operator(). */ template struct function_traits_no_cv : function_traits_impl {}; - -// Front facing template that decays T before ripping it apart. + +/** @private Front-facing template that decays T before extracting traits. */ template struct function_traits : function_traits_no_cv< decay_t > {}; -} // _ +} // namespace _ +/** Trait to check if a type is callable. */ template struct is_callable { static constexpr bool value = _::function_traits::is_callable; }; +/** Trait to get the number of arguments of a callable. */ template struct arity { static constexpr int value = _::function_traits::arity; }; +/** Get the return type of a callable. */ template using return_type_t = typename _::function_traits::return_type; +/** Get the argument list type of a callable. */ template using arg_list_t = typename _::function_traits::args; -// First arg +/** Extract the first argument type from a callable (implementation). */ template struct first_arg_impl; +/** Extract the first argument type from an arg_list. */ template struct first_arg_impl > { using type = T; }; +/** Get the first argument type of a callable. */ template struct first_arg { using type = typename first_arg_impl>::type; }; +/** Convenience alias for the first argument type of a callable. */ template using first_arg_t = typename first_arg::type; -// Last arg +/** Extract the second argument type from a callable (implementation). */ template struct second_arg_impl; +/** Extract the second argument type from an arg_list. */ template struct second_arg_impl > { using type = T; }; +/** Get the second argument type of a callable. */ template struct second_arg { using type = typename second_arg_impl>::type; }; +/** Convenience alias for the second argument type of a callable. */ template using second_arg_t = typename second_arg::type; -} // flecs +} // namespace flecs + + +namespace flecs { +namespace _ { + +/** @private Extract the type name from a type using compiler intrinsics. */ +#if defined(__GNUC__) || defined(_WIN32) +template +inline const char* type_name() { + static const size_t len = ECS_FUNC_TYPE_LEN(const char*, type_name, ECS_FUNC_NAME); + static char result[len + 1] = {}; + static const size_t front_len = ECS_FUNC_NAME_FRONT(const char*, type_name); + static const char* cppTypeName = ecs_cpp_get_type_name(result, ECS_FUNC_NAME, len, front_len); + return cppTypeName; +} +#else +#error "implicit component registration not supported" +#endif +} +} // Mixin forward declarations /** * @file addons/cpp/mixins/id/decl.hpp - * @brief Id class. + * @brief ID class. */ #pragma once @@ -19660,18 +21744,18 @@ struct id; struct entity; /** - * @defgroup cpp_ids Ids + * @defgroup cpp_ids IDs * @ingroup cpp_core - * Class for working with entity, component, tag and pair ids. + * Class for working with entity, component, tag, and pair IDs. * * @{ */ /** Class that wraps around a flecs::id_t. - * A flecs id is an identifier that can be added to entities. Ids can be: + * A flecs ID is an identifier that can be added to entities. IDs can be: * - entities (including components, tags) - * - pair ids - * - entities with id flags set (like flecs::AUTO_OVERRIDE, flecs::TOGGLE) + * - pair IDs + * - entities with ID flags set (like flecs::AUTO_OVERRIDE, flecs::TOGGLE) */ struct id { id() @@ -19702,53 +21786,53 @@ struct id { : world_(first.world_) , id_(ecs_pair(first.id_, second.id_)) { } - /** Test if id is pair (has first, second) */ + /** Test if ID is a pair (has first, second). */ bool is_pair() const { return (id_ & ECS_ID_FLAGS_MASK) == flecs::PAIR; } - /** Test if id is a wildcard */ + /** Test if ID is a wildcard. */ bool is_wildcard() const { return ecs_id_is_wildcard(id_); } - /** Test if id is entity */ + /** Test if ID is an entity. */ bool is_entity() const { return !(id_ & ECS_ID_FLAGS_MASK); } - /** Return id as entity (only allowed when id is valid entity) */ + /** Return ID as entity (only allowed when ID is a valid entity). */ flecs::entity entity() const; - /** Return id with role added */ + /** Return ID with flags added. */ flecs::entity add_flags(flecs::id_t flags) const; - /** Return id with role removed */ + /** Return ID with flags removed. */ flecs::entity remove_flags(flecs::id_t flags) const; - /** Return id without role */ + /** Return ID without flags. */ flecs::entity remove_flags() const; - /** Return id without role */ + /** Return ID without generation. */ flecs::entity remove_generation() const; - /** Return component type of id */ + /** Return component type of ID. */ flecs::entity type_id() const; - /** Test if id has specified role */ + /** Test if ID has specified flags. */ bool has_flags(flecs::id_t flags) const { return ((id_ & flags) == flags); } - /** Test if id has any role */ + /** Test if ID has any flags. */ bool has_flags() const { return (id_ & ECS_ID_FLAGS_MASK) != 0; } - /** Return id flags set on id */ + /** Return ID flags set on ID. */ flecs::entity flags() const; - /** Test if id has specified first */ + /** Test if ID has the specified first element. */ bool has_relation(flecs::id_t first) const { if (!is_pair()) { return false; @@ -19757,28 +21841,28 @@ struct id { } /** Get first element from a pair. - * If the id is not a pair, this operation will fail. When the id has a - * world, the operation will ensure that the returned id has the correct + * If the ID is not a pair, this operation will fail. When the ID has a + * world, the operation will ensure that the returned ID has the correct * generation count. */ flecs::entity first() const; /** Get second element from a pair. - * If the id is not a pair, this operation will fail. When the id has a - * world, the operation will ensure that the returned id has the correct + * If the ID is not a pair, this operation will fail. When the ID has a + * world, the operation will ensure that the returned ID has the correct * generation count. */ flecs::entity second() const; - /* Convert id to string */ + /** Convert ID to string. */ flecs::string str() const { return flecs::string(ecs_id_str(world_, id_)); } - /** Convert role of id to string. */ + /** Convert flags of ID to string. */ flecs::string flags_str() const { return flecs::string_view( ecs_id_flag_str(id_ & ECS_ID_FLAGS_MASK)); } - /** Return flecs::id_t value */ + /** Return flecs::id_t value. */ flecs::id_t raw_id() const { return id_; } @@ -19787,12 +21871,14 @@ struct id { return id_; } + /** Get the world. */ flecs::world world() const; protected: - /* World is optional, but guarantees that entity identifiers extracted from - * the id are valid */ + /** World is optional, but guarantees that entity identifiers extracted from + * the ID are valid. */ flecs::world_t *world_; + /** The raw ID value. */ flecs::id_t id_; }; @@ -19873,7 +21959,7 @@ namespace flecs { * @{ */ -/** Event builder interface */ +/** Event builder interface. */ template struct event_builder_base { event_builder_base(flecs::world_t *world, flecs::entity_t event) @@ -19885,7 +21971,7 @@ struct event_builder_base { desc_.event = event; } - /** Add component to emit for */ + /** Add a component to emit for. */ template Base& id() { ids_.array = ids_array_; @@ -19894,10 +21980,10 @@ struct event_builder_base { return *this; } - /** - * Add pair to emit for + /** Add a pair to emit for. + * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. */ template Base& id() { @@ -19906,25 +21992,30 @@ struct event_builder_base { _::type::id(this->world_))); } - /** - * Add pair to emit for + /** Add a pair to emit for. + * * @tparam First The first element of the pair. - * @param second The second element of the pair id. + * @param second The second element of the pair. */ template Base& id(entity_t second) { return id(ecs_pair(_::type::id(this->world_), second)); } - /** - * Add pair to emit for - * @param first The first element of the pair type. - * @param second The second element of the pair id. + /** Add a pair to emit for. + * + * @param first The first element of the pair. + * @param second The second element of the pair. */ Base& id(entity_t first, entity_t second) { return id(ecs_pair(first, second)); } + /** Add an enum constant to emit for. + * + * @tparam Enum The enum type. + * @param value The enum constant value. + */ template ::value> = 0> Base& id(Enum value) { const auto& et = enum_type(this->world_); @@ -19932,7 +22023,7 @@ struct event_builder_base { return id(et.entity(), target); } - /** Add (component) id to emit for */ + /** Add a (component) ID to emit for. */ Base& id(flecs::id_t id) { ids_.array = ids_array_; ids_.array[ids_.count] = id; @@ -19940,13 +22031,13 @@ struct event_builder_base { return *this; } - /** Set entity for which to emit event */ + /** Set the entity for which to emit the event. */ Base& entity(flecs::entity_t e) { desc_.entity = e; return *this; } - /* Set table for which to emit event */ + /** Set the table for which to emit the event. */ Base& table(flecs::table_t *t, int32_t offset = 0, int32_t count = 0) { desc_.table = t; desc_.offset = offset; @@ -19954,18 +22045,19 @@ struct event_builder_base { return *this; } - /* Set event data */ + /** Set event data (const). */ Base& ctx(const E* ptr) { desc_.const_param = ptr; return *this; } - /* Set event data */ + /** Set event data (mutable). */ Base& ctx(E* ptr) { desc_.param = ptr; return *this; } + /** Emit the event. */ void emit() { ids_.array = ids_array_; desc_.ids = &ids_; @@ -19973,6 +22065,7 @@ struct event_builder_base { ecs_emit(world_, &desc_); } + /** Enqueue the event. */ void enqueue() { ids_.array = ids_array_; desc_.ids = &ids_; @@ -19992,10 +22085,12 @@ struct event_builder_base { } }; +/** Untyped event builder. */ struct event_builder : event_builder_base { using event_builder_base::event_builder_base; }; +/** Typed event builder. */ template struct event_builder_typed : event_builder_base, E> { private: @@ -20004,13 +22099,13 @@ struct event_builder_typed : event_builder_base, E> { public: using event_builder_base::event_builder_base; - /* Set event data */ + /** Set event data (const reference). */ Class& ctx(const E& ptr) { this->desc_.const_param = &ptr; return *this; } - /* Set event data */ + /** Set event data (rvalue reference). */ Class& ctx(E&& ptr) { this->desc_.param = &ptr; return *this; @@ -20025,17 +22120,17 @@ struct event_builder_typed : event_builder_base, E> { namespace flecs { namespace _ { -// Utility to derive event type from function +// Utility to derive event type from function. template struct event_from_func; -// Specialization for observer callbacks with a single argument +// Specialization for observer callbacks with a single argument. template struct event_from_func::value == 1>> { using type = decay_t>; }; -// Specialization for observer callbacks with an initial entity src argument +// Specialization for observer callbacks with an initial entity src argument. template struct event_from_func::value == 2>> { using type = decay_t>; @@ -20086,15 +22181,18 @@ namespace flecs { /** * @defgroup cpp_addons_systems Systems * @ingroup cpp_addons - * Systems are a query + function that can be ran manually or by a pipeline. + * Systems are a query and a function that can be run manually or by a pipeline. * * @{ */ +/** Tick source component. */ using TickSource = EcsTickSource; +/** Forward declaration for system. */ struct system; +/** Forward declaration for system builder. */ template struct system_builder; @@ -20126,23 +22224,35 @@ namespace flecs { * @{ */ +/** Forward declaration for pipeline. */ template struct pipeline; +/** Forward declaration for pipeline builder. */ template struct pipeline_builder; -/* Builtin pipeline tags */ +/** Built-in pipeline phase run at startup. */ static const flecs::entity_t OnStart = EcsOnStart; +/** Built-in pipeline phase run before each frame. */ static const flecs::entity_t PreFrame = EcsPreFrame; +/** Built-in pipeline phase for loading data. */ static const flecs::entity_t OnLoad = EcsOnLoad; +/** Built-in pipeline phase run after loading data. */ static const flecs::entity_t PostLoad = EcsPostLoad; +/** Built-in pipeline phase run before the update. */ static const flecs::entity_t PreUpdate = EcsPreUpdate; +/** Built-in pipeline phase for the main update. */ static const flecs::entity_t OnUpdate = EcsOnUpdate; +/** Built-in pipeline phase for validation after the update. */ static const flecs::entity_t OnValidate = EcsOnValidate; +/** Built-in pipeline phase run after the update. */ static const flecs::entity_t PostUpdate = EcsPostUpdate; +/** Built-in pipeline phase run before storing data. */ static const flecs::entity_t PreStore = EcsPreStore; +/** Built-in pipeline phase for storing data. */ static const flecs::entity_t OnStore = EcsOnStore; +/** Built-in pipeline phase run after each frame. */ static const flecs::entity_t PostFrame = EcsPostFrame; /** @} */ @@ -20168,9 +22278,12 @@ namespace flecs { * @{ */ +/** Timer component. */ using Timer = EcsTimer; +/** Rate filter component. */ using RateFilter = EcsRateFilter; +/** Forward declaration for timer. */ struct timer; /** @} */ @@ -20197,27 +22310,27 @@ namespace doc { /** * @defgroup cpp_addons_doc Doc * @ingroup cpp_addons - * Utilities for documenting entities, components and systems. + * Utilities for documenting entities, components, and systems. * * @{ */ -/** flecs.doc.Description component */ +/** flecs.doc.Description component. */ using Description = EcsDocDescription; -/** flecs.doc.Uuid component */ +/** flecs.doc.Uuid component. */ static const flecs::entity_t Uuid = EcsDocUuid; -/** flecs.doc.Brief component */ +/** flecs.doc.Brief component. */ static const flecs::entity_t Brief = EcsDocBrief; -/** flecs.doc.Detail component */ +/** flecs.doc.Detail component. */ static const flecs::entity_t Detail = EcsDocDetail; -/** flecs.doc.Link component */ +/** flecs.doc.Link component. */ static const flecs::entity_t Link = EcsDocLink; -/** flecs.doc.Color component */ +/** flecs.doc.Color component. */ static const flecs::entity_t Color = EcsDocColor; /** @private */ @@ -20250,6 +22363,7 @@ namespace flecs { * @{ */ +/** REST API component. */ using Rest = EcsRest; namespace rest { @@ -20284,7 +22398,7 @@ namespace flecs { * @{ */ -/* Primitive type aliases */ +/** Primitive type aliases. */ using bool_t = ecs_bool_t; using char_t = ecs_char_t; using u8_t = ecs_u8_t; @@ -20300,12 +22414,12 @@ using iptr_t = ecs_iptr_t; using f32_t = ecs_f32_t; using f64_t = ecs_f64_t; -/* Embedded type aliases */ +/** Embedded type aliases. */ using member_t = ecs_member_t; using enum_constant_t = ecs_enum_constant_t; using bitmask_constant_t = ecs_bitmask_constant_t; -/* Components */ +/** Components. */ using Type = EcsType; using TypeSerializer = EcsTypeSerializer; using Primitive = EcsPrimitive; @@ -20318,12 +22432,12 @@ using Array = EcsArray; using Vector = EcsVector; using Unit = EcsUnit; -/** Base type for bitmasks */ +/** Base type for bitmasks. */ struct bitmask { uint32_t value; }; -/* Handles to builtin reflection types */ +/** Handles to built-in reflection types. */ static const flecs::entity_t Bool = ecs_id(ecs_bool_t); static const flecs::entity_t Char = ecs_id(ecs_char_t); static const flecs::entity_t Byte = ecs_id(ecs_byte_t); @@ -20345,7 +22459,7 @@ static const flecs::entity_t Quantity = EcsQuantity; namespace meta { -/* Type kinds supported by reflection system */ +/** Type kinds supported by the reflection system. */ using type_kind_t = ecs_type_kind_t; static const type_kind_t PrimitiveType = EcsPrimitiveType; static const type_kind_t BitmaskType = EcsBitmaskType; @@ -20356,7 +22470,7 @@ static const type_kind_t VectorType = EcsVectorType; static const type_kind_t CustomType = EcsOpaqueType; static const type_kind_t TypeKindLast = EcsTypeKindLast; -/* Primitive type kinds supported by reflection system */ +/** Primitive type kinds supported by the reflection system. */ using primitive_kind_t = ecs_primitive_kind_t; static const primitive_kind_t Bool = EcsBool; static const primitive_kind_t Char = EcsChar; @@ -20390,8 +22504,8 @@ void init(flecs::world& world); } // namespace flecs /** - * @file addons/cpp/mixins/meta/opaque.hpp - * @brief Helpers for opaque type registration. + * @file addons/cpp/mixins/meta/cursor.hpp + * @brief Cursor for reading/writing dynamic values. */ #pragma once @@ -20415,136 +22529,136 @@ struct cursor { cursor_ = ecs_meta_cursor(world, type_id, ptr); } - /** Push value scope (such as a nested struct) */ + /** Push a value scope (such as a nested struct). */ int push() { return ecs_meta_push(&cursor_); } - /** Pop value scope */ + /** Pop a value scope. */ int pop() { return ecs_meta_pop(&cursor_); } - /** Move to next member/element */ + /** Move to the next member/element. */ int next() { return ecs_meta_next(&cursor_); } - /** Move to member by name */ + /** Move to a member by name. */ int member(const char *name) { return ecs_meta_member(&cursor_, name); } - /** Move to element by index */ + /** Move to an element by index. */ int elem(int32_t elem) { return ecs_meta_elem(&cursor_, elem); } - /** Test if current scope is a collection type */ + /** Test if the current scope is a collection type. */ bool is_collection() { return ecs_meta_is_collection(&cursor_); } - /** Get member name */ + /** Get the member name. */ flecs::string_view get_member() const { return flecs::string_view(ecs_meta_get_member(&cursor_)); } - /** Get type of value */ + /** Get the type of a value. */ flecs::entity get_type() const; - /** Get unit of value */ + /** Get the unit of a value. */ flecs::entity get_unit() const; - /** Get untyped pointer to value */ + /** Get an untyped pointer to a value. */ void* get_ptr() { return ecs_meta_get_ptr(&cursor_); } - /** Set boolean value */ + /** Set boolean value. */ int set_bool(bool value) { return ecs_meta_set_bool(&cursor_, value); } - /** Set char value */ + /** Set char value. */ int set_char(char value) { return ecs_meta_set_char(&cursor_, value); } - /** Set signed int value */ + /** Set signed int value. */ int set_int(int64_t value) { return ecs_meta_set_int(&cursor_, value); } - /** Set unsigned int value */ + /** Set unsigned int value. */ int set_uint(uint64_t value) { return ecs_meta_set_uint(&cursor_, value); } - /** Set float value */ + /** Set float value. */ int set_float(double value) { return ecs_meta_set_float(&cursor_, value); } - /** Set string value */ + /** Set string value. */ int set_string(const char *value) { return ecs_meta_set_string(&cursor_, value); } - /** Set string literal value */ + /** Set string literal value. */ int set_string_literal(const char *value) { return ecs_meta_set_string_literal(&cursor_, value); } - /** Set entity value */ + /** Set entity value. */ int set_entity(flecs::entity_t value) { return ecs_meta_set_entity(&cursor_, value); } - /** Set (component) id value */ + /** Set (component) ID value. */ int set_id(flecs::id_t value) { return ecs_meta_set_id(&cursor_, value); } - /** Set null value */ + /** Set null value. */ int set_null() { return ecs_meta_set_null(&cursor_); } - /** Get boolean value */ + /** Get boolean value. */ bool get_bool() const { return ecs_meta_get_bool(&cursor_); } - /** Get char value */ + /** Get char value. */ char get_char() const { return ecs_meta_get_char(&cursor_); } - /** Get signed int value */ + /** Get signed int value. */ int64_t get_int() const { return ecs_meta_get_int(&cursor_); } - /** Get unsigned int value */ + /** Get unsigned int value. */ uint64_t get_uint() const { return ecs_meta_get_uint(&cursor_); } - /** Get float value */ + /** Get float value. */ double get_float() const { return ecs_meta_get_float(&cursor_); } - /** Get string value */ + /** Get string value. */ const char *get_string() const { return ecs_meta_get_string(&cursor_); } - /** Get entity value */ + /** Get entity value. */ flecs::entity get_entity() const; - /** Cursor object */ + /** Cursor object. */ ecs_meta_cursor_t cursor_; }; @@ -20569,26 +22683,26 @@ namespace flecs { * @{ */ -/** Serializer object, used for serializing opaque types */ +/** Serializer object, used for serializing opaque types. */ using serializer = ecs_serializer_t; -/** Serializer function, used to serialize opaque types */ +/** Serializer function, used to serialize opaque types. */ using serialize_t = ecs_meta_serialize_t; -/** Type safe variant of serializer function */ +/** Type-safe variant of the serializer function. */ template using serialize = int(*)(const serializer *, const T*); -/** Type safe variant of serialize_member function */ +/** Type-safe variant of the serialize_member() function. */ template using serialize_member = int(*)(const serializer *, const T*, const char* name); -/** Type safe variant of serialize_element function */ +/** Type-safe variant of the serialize_element() function. */ template using serialize_element = int(*)(const serializer *, const T*, size_t element); -/** Type safe interface for opaque types */ +/** Type-safe interface for opaque types. */ template struct opaque { opaque(flecs::world_t *w = nullptr) : world(w) { @@ -20597,13 +22711,13 @@ struct opaque { } } - /** Type that describes the type kind/structure of the opaque type */ + /** Set the type that describes the kind/structure of the opaque type. */ opaque& as_type(flecs::id_t func) { this->desc.type.as_type = func; return *this; } - /** Serialize function */ + /** Set the serialize function. */ opaque& serialize(flecs::serialize func) { this->desc.type.serialize = reinterpret_cast func) { this->desc.type.serialize_member = reinterpret_cast func) { this->desc.type.serialize_element = reinterpret_castdesc.type.assign_bool = reinterpret_castdesc.type.assign_char = reinterpret_castdesc.type.assign_int = reinterpret_castdesc.type.assign_uint = reinterpret_castdesc.type.assign_float = reinterpret_castdesc.type.assign_string = reinterpret_castdesc.type.assign_null = reinterpret_castdesc.type.clear = reinterpret_castdesc.type.ensure_element = reinterpret_castdesc.type.ensure_member = reinterpret_castdesc.type.count = reinterpret_castdesc.type.resize = reinterpret_cast metric_builder& member(const char *name); + /** Set the member to use for the metric using dot notation. */ metric_builder& dotmember(const char *name); + /** Set the member to use for the metric by type using dot notation. */ template metric_builder& dotmember(const char *name); + /** Set the ID for the metric. */ metric_builder& id(flecs::id_t the_id) { desc_.id = the_id; return *this; } + /** Set the ID for the metric as a pair. */ metric_builder& id(flecs::entity_t first, flecs::entity_t second) { desc_.id = ecs_pair(first, second); return *this; } + /** Set the ID for the metric by type. */ template metric_builder& id() { return id(_::type::id(world_)); } + /** Set the ID for the metric as a pair with type First. */ template metric_builder& id(flecs::entity_t second) { return id(_::type::id(world_), second); } + /** Set the ID for the metric as a pair with type Second. */ template metric_builder& id_second(flecs::entity_t first) { return id(first, _::type::id(world_)); } + /** Set the ID for the metric as a pair with types First and Second. */ template metric_builder& id() { return id(_::type::id(world_)); } + /** Set whether to create metrics for targets. */ metric_builder& targets(bool value = true) { desc_.targets = value; return *this; } + /** Set the metric kind (e.g., Counter, Gauge). */ metric_builder& kind(flecs::entity_t the_kind) { desc_.kind = the_kind; return *this; } + /** Set the metric kind by type. */ template metric_builder& kind() { return kind(_::type::id(world_)); } + /** Set a brief description for the metric. */ metric_builder& brief(const char *b) { desc_.brief = b; return *this; } + /** Finalize the metric and return the entity. */ operator flecs::entity(); protected: @@ -21286,17 +23550,27 @@ namespace flecs { * @{ */ +/** Metrics module. */ struct metrics { + /** Metric value component. */ using Value = EcsMetricValue; + /** Metric source component. */ using Source = EcsMetricSource; + /** Metric instance tag. */ struct Instance { }; + /** Metric tag. */ struct Metric { }; + /** Counter metric kind. */ struct Counter { }; + /** Counter increment metric kind. */ struct CounterIncrement { }; + /** Counter ID metric kind. */ struct CounterId { }; + /** Gauge metric kind. */ struct Gauge { }; + /** Construct the metrics module. */ metrics(flecs::world& world); }; @@ -21323,7 +23597,7 @@ namespace flecs { * @{ */ -/** Module */ +/** Module. */ struct alerts { using AlertsActive = EcsAlertsActive; using Instance = EcsAlertInstance; @@ -21399,7 +23673,7 @@ namespace flecs { * @{ */ -/** App builder interface */ +/** App builder interface. */ struct app_builder { app_builder(flecs::world_t *world) : world_(world) @@ -21413,52 +23687,61 @@ struct app_builder { } } + /** Set the target frames per second. */ app_builder& target_fps(ecs_ftime_t value) { desc_.target_fps = value; return *this; } + /** Set the fixed delta time for each frame. */ app_builder& delta_time(ecs_ftime_t value) { desc_.delta_time = value; return *this; } + /** Set the number of threads. */ app_builder& threads(int32_t value) { desc_.threads = value; return *this; } + /** Set the number of frames to run. */ app_builder& frames(int32_t value) { desc_.frames = value; return *this; } + /** Enable the REST API. */ app_builder& enable_rest(uint16_t port = 0) { desc_.enable_rest = true; desc_.port = port; return *this; } + /** Enable statistics collection. */ app_builder& enable_stats(bool value = true) { desc_.enable_stats = value; return *this; } + /** Set the init callback. */ app_builder& init(ecs_app_init_action_t value) { desc_.init = value; return *this; } + /** Set the application context. */ app_builder& ctx(void *value) { desc_.ctx = value; return *this; } + /** Run the application. */ int run() { int result = ecs_app_run(world_, &desc_); if (ecs_should_quit(world_)) { // Only free world if quit flag is set. This ensures that we won't - // try to cleanup the world if the app is used in an environment + // try to clean up the world if the app is used in an environment // that takes over the main loop, like with emscripten. if (!flecs_poly_release(world_)) { ecs_fini(world_); @@ -21500,8 +23783,12 @@ namespace flecs { * @{ */ -/** Script builder interface */ +/** Script builder interface. */ struct script_builder { + /** Construct a script builder. + * @param world The world. + * @param name Optional name for the script entity. + */ script_builder(flecs::world_t *world, const char *name = nullptr) : world_(world) , desc_{} @@ -21515,16 +23802,19 @@ struct script_builder { } } + /** Set the script code. */ script_builder& code(const char *str) { desc_.code = str; return *this; } + /** Set the script filename. */ script_builder& filename(const char *str) { desc_.filename = str; return *this; } + /** Run the script and return the script entity. */ flecs::entity run() const; protected: @@ -21580,31 +23870,50 @@ namespace log { * @{ */ -/** Set log level */ +/** Set the log level. + * + * @param level The log level to set. + */ inline void set_level(int level) { ecs_log_set_level(level); } +/** Get the log level. + * + * @return The current log level. + */ inline int get_level() { return ecs_log_get_level(); } -/** Enable colors in logging */ +/** Enable colors in logging. + * + * @param enabled Whether to enable colors (default true). + */ inline void enable_colors(bool enabled = true) { ecs_log_enable_colors(enabled); } -/** Enable timestamps in logging */ +/** Enable timestamps in logging. + * + * @param enabled Whether to enable timestamps (default true). + */ inline void enable_timestamp(bool enabled = true) { ecs_log_enable_timestamp(enabled); } -/** Enable time delta in logging */ +/** Enable time delta in logging. + * + * @param enabled Whether to enable time delta (default true). + */ inline void enable_timedelta(bool enabled = true) { ecs_log_enable_timedelta(enabled); } -/** Debug trace (level 1) */ +/** Debug trace (level 1). + * + * @param fmt The format string. + */ inline void dbg(const char *fmt, ...) { va_list args; va_start(args, fmt); @@ -21612,7 +23921,10 @@ inline void dbg(const char *fmt, ...) { va_end(args); } -/** Trace (level 0) */ +/** Trace (level 0). + * + * @param fmt The format string. + */ inline void trace(const char *fmt, ...) { va_list args; va_start(args, fmt); @@ -21620,7 +23932,10 @@ inline void trace(const char *fmt, ...) { va_end(args); } -/** Trace (level -2) */ +/** Warning (level -2). + * + * @param fmt The format string. + */ inline void warn(const char *fmt, ...) { va_list args; va_start(args, fmt); @@ -21628,7 +23943,10 @@ inline void warn(const char *fmt, ...) { va_end(args); } -/** Trace (level -3) */ +/** Error (level -3). + * + * @param fmt The format string. + */ inline void err(const char *fmt, ...) { va_list args; va_start(args, fmt); @@ -21636,7 +23954,10 @@ inline void err(const char *fmt, ...) { va_end(args); } -/** Increase log indentation */ +/** Trace and increase log indentation. + * + * @param fmt The format string. + */ inline void push(const char *fmt, ...) { va_list args; va_start(args, fmt); @@ -21645,12 +23966,12 @@ inline void push(const char *fmt, ...) { ecs_log_push(); } -/** Increase log indentation */ +/** Increase log indentation. */ inline void push() { ecs_log_push(); } -/** Increase log indentation */ +/** Decrease log indentation. */ inline void pop() { ecs_log_pop(); } @@ -21662,7 +23983,7 @@ inline void pop() { /** * @file addons/cpp/pair.hpp - * @brief Utilities for working with compile time pairs. + * @brief Utilities for working with compile-time pairs. */ #pragma once @@ -21671,19 +23992,19 @@ namespace flecs { namespace _ { struct pair_base { }; -} // _ +} // namespace _ /** * @defgroup cpp_pair_type Pair type * @ingroup cpp_core - * Compile time utilities for working with relationship pairs. + * Compile-time utilities for working with relationship pairs. * * @{ */ /** Type that represents a pair. - * The pair type can be used to represent a pair at compile time, and is able + * The pair type can be used to represent a pair at compile time and is able * to automatically derive the storage type associated with the pair, accessible * through pair::type. * @@ -21692,39 +24013,53 @@ namespace _ { * - if pair::first is empty and pair::second is non-empty, the storage type is pair::second * * The pair type can hold a temporary value so that it can be used in the - * signatures of queries + * signatures of queries. */ template struct pair : _::pair_base { - using type = conditional_t::value || is_empty::value, First, Second>; - using first = First; - using second = Second; + using type = conditional_t::value || is_empty::value, First, Second>; /**< The storage type of the pair. */ + using first = First; /**< The first element type of the pair. */ + using second = Second; /**< The second element type of the pair. */ + /** Construct pair from a mutable reference to the storage type. + * + * @param v Reference to the value. + */ pair(type& v) : ref_(v) { } - // This allows the class to be used as a temporary object + /** Construct pair from a const reference to the storage type. + * This allows the class to be used as a temporary object. + * + * @param v Const reference to the value. + */ pair(const type& v) : ref_(const_cast(v)) { } + /** Conversion to mutable reference of the storage type. */ operator type&() { return ref_; } + /** Conversion to const reference of the storage type. */ operator const type&() const { return ref_; } + /** Arrow operator for mutable access. */ type* operator->() { return &ref_; } + /** Arrow operator for const access. */ const type* operator->() const { return &ref_; } + /** Dereference operator for mutable access. */ type& operator*() { return ref_; } + /** Dereference operator for const access. */ const type& operator*() const { return ref_; } @@ -21733,31 +24068,37 @@ struct pair : _::pair_base { type& ref_; }; +/** Alias for pair when First is empty (tag). */ template ::value> = 0> using pair_object = pair; +/** Get the raw type by removing pointer and reference qualifiers. */ template using raw_type_t = remove_pointer_t>; -/** Test if type is a pair. */ +/** Test if a type is a pair. */ template struct is_pair { - static constexpr bool value = is_base_of<_::pair_base, raw_type_t >::value; + static constexpr bool value = is_base_of_v<_::pair_base, raw_type_t>; }; -/** Get pair::first from pair while preserving cv qualifiers. */ +/** Convenience variable template to check if a type is a pair. */ +template +inline constexpr bool is_pair_v = is_pair::value; + +/** Get pair::first from a pair while preserving cv qualifiers. */ template using pair_first_t = transcribe_cv_t, typename raw_type_t

::first>; -/** Get pair::second from pair while preserving cv qualifiers. */ +/** Get pair::second from a pair while preserving cv qualifiers. */ template using pair_second_t = transcribe_cv_t, typename raw_type_t

::second>; -/** Get pair::type type from pair while preserving cv qualifiers and pointer type. */ +/** Get the pair::type type from a pair while preserving cv qualifiers and pointer type. */ template using pair_type_t = transcribe_cvp_t, typename raw_type_t

::type>; -/** Get actual type from a regular type or pair. */ +/** Get the actual type from a regular type or pair. */ template struct actual_type; @@ -21775,34 +24116,41 @@ template using actual_type_t = typename actual_type::type; -// Get type without const, *, & +/** Get the type without const, *, and &. */ template struct base_type { using type = decay_t< actual_type_t >; }; +/** Convenience alias for base_type. */ template using base_type_t = typename base_type::type; -// Get type without *, & (retains const which is useful for function args) +/** Get the type without * and & (retains const, which is useful for function args). */ template struct base_arg_type { using type = remove_pointer_t< remove_reference_t< actual_type_t > >; }; +/** Convenience alias for base_arg_type. */ template using base_arg_type_t = typename base_arg_type::type; -// Test if type is the same as its actual type +/** Test if a type is the same as its actual type. */ template struct is_actual { - static constexpr bool value = - std::is_same >::value; + static constexpr bool value = is_same_v>; }; -} // flecs +/** Convenience variable template to check if a type is its own actual type. */ +template +inline constexpr bool is_actual_v = is_actual::value; + +/** @} */ + +} // namespace flecs /** * @file addons/cpp/lifecycle_traits.hpp @@ -21818,7 +24166,7 @@ namespace _ { // T() -// Can't coexist with T(flecs::entity) or T(flecs::world, flecs::entity) +// Can't coexist with T(flecs::entity) or T(flecs::world, flecs::entity). template void ctor_impl(void *ptr, int32_t count, const ecs_type_info_t *info) { (void)info; ecs_assert(info->size == ECS_SIZEOF(T), @@ -21868,9 +24216,9 @@ void move_impl(void *dst_ptr, void *src_ptr, int32_t count, } } -// T(T&) +// T(const T&) template -void copy_ctor_impl(void *dst_ptr, const void *src_ptr, int32_t count, +void copy_ctor_impl(void *dst_ptr, const void *src_ptr, int32_t count, const ecs_type_info_t *info) { (void)info; ecs_assert(info->size == ECS_SIZEOF(T), @@ -21897,12 +24245,12 @@ void move_ctor_impl(void *dst_ptr, void *src_ptr, int32_t count, } // T(T&&), ~T() -// Typically used when moving to a new table, and removing from the old table +// Typically used when moving to a new table, and removing from the old table. template -void ctor_move_dtor_impl(void *dst_ptr, void *src_ptr, int32_t count, +void ctor_move_dtor_impl(void *dst_ptr, void *src_ptr, int32_t count, const ecs_type_info_t *info) { - (void)info; ecs_assert(info->size == ECS_SIZEOF(T), + (void)info; ecs_assert(info->size == ECS_SIZEOF(T), ECS_INTERNAL_ERROR, NULL); T *dst_arr = static_cast(dst_ptr); T *src_arr = static_cast(src_ptr); @@ -21912,8 +24260,8 @@ void ctor_move_dtor_impl(void *dst_ptr, void *src_ptr, int32_t count, } } -// Move assign + dtor (non-trivial move assignment) -// Typically used when moving a component to a deleted component +// Move assign + dtor (non-trivial move assignment). +// Typically used when moving a component to a deleted component. template ::value > = 0> void move_dtor_impl(void *dst_ptr, void *src_ptr, int32_t count, @@ -21924,16 +24272,16 @@ void move_dtor_impl(void *dst_ptr, void *src_ptr, int32_t count, T *dst_arr = static_cast(dst_ptr); T *src_arr = static_cast(src_ptr); for (int i = 0; i < count; i ++) { - // Move assignment should free dst & assign dst to src + // Move assignment should free dst and assign dst to src. dst_arr[i] = FLECS_MOV(src_arr[i]); - // Destruct src. Move should have left object in a state where it no + // Destruct src. Move should have left the object in a state where it no // longer holds resources, but it still needs to be destructed. src_arr[i].~T(); } } -// Move assign + dtor (trivial move assignment) -// Typically used when moving a component to a deleted component +// Move assign + dtor (trivial move assignment). +// Typically used when moving a component to a deleted component. template ::value > = 0> void move_dtor_impl(void *dst_ptr, void *src_ptr, int32_t count, @@ -21944,19 +24292,19 @@ void move_dtor_impl(void *dst_ptr, void *src_ptr, int32_t count, T *dst_arr = static_cast(dst_ptr); T *src_arr = static_cast(src_ptr); for (int i = 0; i < count; i ++) { - // Cleanup resources of dst + // Clean up resources of dst. dst_arr[i].~T(); - // Copy src to dst + // Copy src to dst. dst_arr[i] = FLECS_MOV(src_arr[i]); - // No need to destruct src. Since this is a trivial move the code - // should be agnostic to the address of the component which means we + // No need to destruct src. Since this is a trivial move, the code + // should be agnostic to the address of the component, which means we // can pretend nothing got destructed. } } -} // _ +} // namespace _ -// Trait to test if type is constructible by flecs +/** Trait to test if a type is constructible by Flecs. */ template struct is_flecs_constructible { static constexpr bool value = @@ -21966,201 +24314,110 @@ struct is_flecs_constructible { namespace _ { -// Trivially constructible -template ::value > = 0> -ecs_xtor_t ctor(ecs_flags32_t &) { - return nullptr; -} - -// Not constructible by flecs -template ::value > = 0> +template ecs_xtor_t ctor(ecs_flags32_t &flags) { - flags |= ECS_TYPE_HOOK_CTOR_ILLEGAL; - return nullptr; -} - -// Default constructible -template ::value && - std::is_default_constructible::value > = 0> -ecs_xtor_t ctor(ecs_flags32_t &) { - return ctor_impl; -} - -// No dtor -template ::value > = 0> -ecs_xtor_t dtor(ecs_flags32_t &) { - return nullptr; -} - -// Dtor -template ::value && - ! std::is_trivially_destructible::value > = 0> -ecs_xtor_t dtor(ecs_flags32_t &) { - return dtor_impl; + if constexpr (is_trivially_constructible_v) { + return nullptr; + } else if constexpr (!is_default_constructible_v) { + flags |= ECS_TYPE_HOOK_CTOR_ILLEGAL; + return nullptr; + } else { + return ctor_impl; + } } -// Assert when the type cannot be destructed -template ::value > = 0> +template ecs_xtor_t dtor(ecs_flags32_t &flags) { - flecs_static_assert(always_false::value, - "component type must be destructible"); - flags |= ECS_TYPE_HOOK_DTOR_ILLEGAL; - return nullptr; -} - -// Trivially copyable -template ::value > = 0> -ecs_copy_t copy(ecs_flags32_t &) { - return nullptr; + if constexpr (is_trivially_destructible_v) { + return nullptr; + } else if constexpr (!is_destructible_v) { + flecs_static_assert(always_false::value, + "component type must be destructible"); + flags |= ECS_TYPE_HOOK_DTOR_ILLEGAL; + return nullptr; + } else { + return dtor_impl; + } } -// Not copyable -template ::value && - ! std::is_copy_assignable::value > = 0> +template ecs_copy_t copy(ecs_flags32_t &flags) { - flags |= ECS_TYPE_HOOK_COPY_ILLEGAL; - return nullptr; -} - -// Copy assignment -template ::value && - ! std::is_trivially_copyable::value > = 0> -ecs_copy_t copy(ecs_flags32_t &) { - return copy_impl; -} - -// Trivially move assignable -template ::value > = 0> -ecs_move_t move(ecs_flags32_t &) { - return nullptr; + if constexpr (is_trivially_copyable_v) { + return nullptr; + } else if constexpr (!is_copy_assignable_v) { + flags |= ECS_TYPE_HOOK_COPY_ILLEGAL; + return nullptr; + } else { + return copy_impl; + } } -// Component types must be move assignable -template ::value > = 0> +template ecs_move_t move(ecs_flags32_t &flags) { - flags |= ECS_TYPE_HOOK_MOVE_ILLEGAL; - return nullptr; -} - -// Move assignment -template ::value && - ! std::is_trivially_move_assignable::value > = 0> -ecs_move_t move(ecs_flags32_t &) { - return move_impl; -} - -// Trivially copy constructible -template ::value > = 0> -ecs_copy_t copy_ctor(ecs_flags32_t &) { - return nullptr; + if constexpr (is_trivially_move_assignable_v) { + return nullptr; + } else if constexpr (!is_move_assignable_v) { + flags |= ECS_TYPE_HOOK_MOVE_ILLEGAL; + return nullptr; + } else { + return move_impl; + } } -// No copy ctor -template ::value > = 0> +template ecs_copy_t copy_ctor(ecs_flags32_t &flags) { - flags |= ECS_TYPE_HOOK_COPY_CTOR_ILLEGAL; - return nullptr; - -} - -// Copy ctor -template ::value && - ! std::is_trivially_copy_constructible::value > = 0> -ecs_copy_t copy_ctor(ecs_flags32_t &) { - return copy_ctor_impl; -} - -// Trivially move constructible -template ::value > = 0> -ecs_move_t move_ctor(ecs_flags32_t &) { - return nullptr; + if constexpr (is_trivially_copy_constructible_v) { + return nullptr; + } else if constexpr (!is_copy_constructible_v) { + flags |= ECS_TYPE_HOOK_COPY_CTOR_ILLEGAL; + return nullptr; + } else { + return copy_ctor_impl; + } } -// Component types must be move constructible -template ::value > = 0> +template ecs_move_t move_ctor(ecs_flags32_t &flags) { - flags |= ECS_TYPE_HOOK_MOVE_CTOR_ILLEGAL; - return nullptr; -} - -// Move ctor -template ::value && - ! std::is_trivially_move_constructible::value > = 0> -ecs_move_t move_ctor(ecs_flags32_t &) { - return move_ctor_impl; -} - -// Trivial merge (move assign + dtor) -template ::value && - std::is_trivially_destructible::value > = 0> -ecs_move_t ctor_move_dtor(ecs_flags32_t &) { - return nullptr; + if constexpr (is_trivially_move_constructible_v) { + return nullptr; + } else if constexpr (!is_move_constructible_v) { + flags |= ECS_TYPE_HOOK_MOVE_CTOR_ILLEGAL; + return nullptr; + } else { + return move_ctor_impl; + } } -// Component types must be move constructible and destructible -template ::value || - ! std::is_destructible::value > = 0> +template ecs_move_t ctor_move_dtor(ecs_flags32_t &flags) { - flags |= ECS_TYPE_HOOK_CTOR_MOVE_DTOR_ILLEGAL; - return nullptr; -} - -// Merge ctor + dtor -template ::value && - std::is_trivially_destructible::value) && - std::is_move_constructible::value && - std::is_destructible::value > = 0> -ecs_move_t ctor_move_dtor(ecs_flags32_t &) { - return ctor_move_dtor_impl; -} - -// Trivial merge (move assign + dtor) -template ::value && - std::is_trivially_destructible::value > = 0> -ecs_move_t move_dtor(ecs_flags32_t &) { - return nullptr; + if constexpr (is_trivially_move_constructible_v && is_trivially_destructible_v) { + return nullptr; + } else if constexpr (!is_move_constructible_v || !is_destructible_v) { + flags |= ECS_TYPE_HOOK_CTOR_MOVE_DTOR_ILLEGAL; + return nullptr; + } else { + return ctor_move_dtor_impl; + } } -// Component types must be move constructible and destructible -template ::value || - ! std::is_destructible::value > = 0> +template ecs_move_t move_dtor(ecs_flags32_t &flags) { - flags |= ECS_TYPE_HOOK_MOVE_DTOR_ILLEGAL; - return nullptr; -} - -// Merge assign + dtor -template ::value && - std::is_trivially_destructible::value) && - std::is_move_assignable::value && - std::is_destructible::value > = 0> -ecs_move_t move_dtor(ecs_flags32_t &) { - return move_dtor_impl; + if constexpr (is_trivially_move_assignable_v && is_trivially_destructible_v) { + return nullptr; + } else if constexpr (!is_move_assignable_v || !is_destructible_v) { + flags |= ECS_TYPE_HOOK_MOVE_DTOR_ILLEGAL; + return nullptr; + } else { + return move_dtor_impl; + } } -// Traits to check for operator<, operator>, and operator== -template -using void_t = void; +// Traits to check for operator<, operator>, and operator==. +using std::void_t; -// These traits causes a "float comparison warning" in some compilers +// These traits cause a "float comparison warning" in some compilers // when `T` is float or double. -// Disable this warning with the following pragmas: +// Disable this warning with the following pragmas. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wfloat-equal" @@ -22169,144 +24426,107 @@ using void_t = void; #pragma GCC diagnostic ignored "-Wfloat-equal" #endif -// Trait to check for operator< +// Trait to check for operator<. template struct has_operator_less : std::false_type {}; -// Only enable if T has an operator< that takes T as the right-hand side (no implicit conversion) +// Only enable if T has an operator< that takes T as the right-hand side (no implicit conversion). template -struct has_operator_less() < std::declval())>> : +struct has_operator_less() < std::declval())>> : std::is_same() < std::declval()), bool> {}; -// Trait to check for operator> +// Trait to check for operator>. template struct has_operator_greater : std::false_type {}; -// Only enable if T has an operator> that takes T as the right-hand side (no implicit conversion) +// Only enable if T has an operator> that takes T as the right-hand side (no implicit conversion). template -struct has_operator_greater() > std::declval())>> : +struct has_operator_greater() > std::declval())>> : std::is_same() > std::declval()), bool> {}; -// Trait to check for operator== +// Trait to check for operator==. template struct has_operator_equal : std::false_type {}; -// Only enable if T has an operator== that takes T as the right-hand side (no implicit conversion) +// Only enable if T has an operator== that takes T as the right-hand side (no implicit conversion). template struct has_operator_equal() == std::declval())>> : std::is_same() == std::declval()), bool> {}; -// 1. Compare function if `<`, `>`, are defined -template ::value && - has_operator_greater::value && - !has_operator_equal::value > = 0> -int compare_impl(const void *a, const void *b, const ecs_type_info_t *) { - const T& lhs = *static_cast(a); - const T& rhs = *static_cast(b); - if (lhs < rhs) return -1; - if (lhs > rhs) return 1; - return 0; -} - -// 2. Compare function if `<` and `==` are defined, ignoring `>` -// if defined. -template ::value && - has_operator_equal::value > = 0> -int compare_impl(const void *a, const void *b, const ecs_type_info_t *) { - const T& lhs = *static_cast(a); - const T& rhs = *static_cast(b); - if (lhs == rhs) return 0; - if (lhs < rhs) return -1; - return 1; // If not less and not equal, must be greater -} - -// 3. Compare function if `>` and `==` are defined, deducing `<` -template ::value && - has_operator_equal::value && - !has_operator_less::value > = 0> -int compare_impl(const void *a, const void *b, const ecs_type_info_t *) { - const T& lhs = *static_cast(a); - const T& rhs = *static_cast(b); - if (lhs == rhs) return 0; - if (lhs > rhs) return 1; - return -1; // If not greater and not equal, must be less -} - -// 4. Compare function if only `<` is defined, deducing the rest -template ::value && - !has_operator_greater::value && - !has_operator_equal::value > = 0> -int compare_impl(const void *a, const void *b, const ecs_type_info_t *) { - const T& lhs = *static_cast(a); - const T& rhs = *static_cast(b); - if (lhs < rhs) return -1; - if (rhs < lhs) return 1; - return 0; // If neither is less, they must be equal -} - -// 5. Compare function if only `>` is defined, deducing the rest -template ::value && - !has_operator_less::value && - !has_operator_equal::value > = 0> +// Selects the best comparison strategy based on available operators. +template int compare_impl(const void *a, const void *b, const ecs_type_info_t *) { const T& lhs = *static_cast(a); const T& rhs = *static_cast(b); - if (lhs > rhs) return 1; - if (rhs > lhs) return -1; - return 0; // If neither is greater, they must be equal -} - -// In order to have a generated compare hook, at least -// operator> or operator< must be defined: -template ::value || - has_operator_greater::value > = 0> -ecs_cmp_t compare() { - return compare_impl; + + if constexpr (has_operator_less::value && has_operator_equal::value) { + // 2. Compare function if `<` and `==` are defined (preferred) + if (lhs == rhs) return 0; + if (lhs < rhs) return -1; + return 1; + } else if constexpr (has_operator_greater::value && has_operator_equal::value) { + // 3. Compare function if `>` and `==` are defined, deducing `<` + if (lhs == rhs) return 0; + if (lhs > rhs) return 1; + return -1; + } else if constexpr (has_operator_less::value && has_operator_greater::value) { + // 1. Compare function if `<`, `>` are defined + if (lhs < rhs) return -1; + if (lhs > rhs) return 1; + return 0; + } else if constexpr (has_operator_less::value) { + // 4. Compare function if only `<` is defined + if (lhs < rhs) return -1; + if (rhs < lhs) return 1; + return 0; + } else if constexpr (has_operator_greater::value) { + // 5. Compare function if only `>` is defined + if (lhs > rhs) return 1; + if (rhs > lhs) return -1; + return 0; + } else { + // This branch should never be instantiated due to the compare() check. + return 0; + } } -template ::value && - !has_operator_greater::value > = 0> +// To have a generated compare hook, at least +// operator> or operator< must be defined. +template ecs_cmp_t compare() { - return NULL; + if constexpr (has_operator_less::value || has_operator_greater::value) { + return compare_impl; + } else { + return NULL; + } } -// Equals function enabled only if `==` is defined -template ::value > = 0> +// Equals implementation. +template bool equals_impl(const void *a, const void *b, const ecs_type_info_t *) { const T& lhs = *static_cast(a); const T& rhs = *static_cast(b); return lhs == rhs; } -template ::value > = 0> -ecs_equals_t equals() { - return equals_impl; -} - -template ::value > = 0> +template ecs_equals_t equals() { - return NULL; + if constexpr (has_operator_equal::value) { + return equals_impl; + } else { + return NULL; + } } -// re-enable the float comparison warning: +// Re-enable the float comparison warning. #if defined(__clang__) #pragma clang diagnostic pop #elif defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif -} // _ -} // flecs +} // namespace _ +} // namespace flecs /** * @file addons/cpp/world.hpp @@ -22318,9 +24538,16 @@ ecs_equals_t equals() { namespace flecs { -/* Static helper functions to assign a component value */ +/** Static helper functions to assign a component value. */ -// set(T&&) +/** Set a component value using move semantics. + * + * @tparam T The component type. + * @param world The world. + * @param entity The entity. + * @param value The value to set (rvalue reference). + * @param id The component ID. + */ template inline void set(world_t *world, flecs::entity_t entity, T&& value, flecs::id_t id) { ecs_assert(_::type::size() != 0, ECS_INVALID_PARAMETER, @@ -22335,12 +24562,23 @@ inline void set(world_t *world, flecs::entity_t entity, T&& value, flecs::id_t i dst = FLECS_MOV(value); } + if (res.stage) { + flecs_defer_end(res.world, res.stage); + } + if (res.call_modified) { ecs_modified_id(world, entity, id); } } -// set(const T&) +/** Set a component value using copy semantics. + * + * @tparam T The component type. + * @param world The world. + * @param entity The entity. + * @param value The value to set (const reference). + * @param id The component ID. + */ template inline void set(world_t *world, flecs::entity_t entity, const T& value, flecs::id_t id) { ecs_assert(_::type::size() != 0, ECS_INVALID_PARAMETER, @@ -22351,26 +24589,52 @@ inline void set(world_t *world, flecs::entity_t entity, const T& value, flecs::i T& dst = *static_cast*>(res.ptr); dst = value; + if (res.stage) { + flecs_defer_end(res.world, res.stage); + } + if (res.call_modified) { ecs_modified_id(world, entity, id); } } -// set(T&&) +/** Set a component value using move semantics, with automatic ID lookup. + * + * @tparam T The component type. + * @tparam A The actual value type. + * @param world The world. + * @param entity The entity. + * @param value The value to set (rvalue reference). + */ template inline void set(world_t *world, entity_t entity, A&& value) { id_t id = _::type::id(world); flecs::set(world, entity, FLECS_FWD(value), id); } -// set(const T&) +/** Set a component value using copy semantics, with automatic ID lookup. + * + * @tparam T The component type. + * @tparam A The actual value type. + * @param world The world. + * @param entity The entity. + * @param value The value to set (const reference). + */ template inline void set(world_t *world, entity_t entity, const A& value) { id_t id = _::type::id(world); flecs::set(world, entity, value, id); } -// assign(T&&) +/** Assign a component value using move semantics. + * Similar to set(), but uses ecs_cpp_assign() instead of ecs_cpp_set(). + * + * @tparam T The component type. + * @param world The world. + * @param entity The entity. + * @param value The value to assign (rvalue reference). + * @param id The component ID. + */ template inline void assign(world_t *world, flecs::entity_t entity, T&& value, flecs::id_t id) { ecs_assert(_::type>::size() != 0, @@ -22386,12 +24650,24 @@ inline void assign(world_t *world, flecs::entity_t entity, T&& value, flecs::id_ dst = FLECS_MOV(value); } + if (res.stage) { + flecs_defer_end(res.world, res.stage); + } + if (res.call_modified) { ecs_modified_id(world, entity, id); } } -// assign(const T&) +/** Assign a component value using copy semantics. + * Similar to set(), but uses ecs_cpp_assign() instead of ecs_cpp_set(). + * + * @tparam T The component type. + * @param world The world. + * @param entity The entity. + * @param value The value to assign (const reference). + * @param id The component ID. + */ template inline void assign(world_t *world, flecs::entity_t entity, const T& value, flecs::id_t id) { ecs_assert(_::type>::size() != 0, @@ -22403,19 +24679,37 @@ inline void assign(world_t *world, flecs::entity_t entity, const T& value, flecs T& dst = *static_cast*>(res.ptr); dst = value; + if (res.stage) { + flecs_defer_end(res.world, res.stage); + } + if (res.call_modified) { ecs_modified_id(world, entity, id); } } -// set(T&&) +/** Assign a component value using move semantics, with automatic ID lookup. + * + * @tparam T The component type. + * @tparam A The actual value type. + * @param world The world. + * @param entity The entity. + * @param value The value to assign (rvalue reference). + */ template inline void assign(world_t *world, entity_t entity, A&& value) { id_t id = _::type::id(world); flecs::assign(world, entity, FLECS_FWD(value), id); } -// set(const T&) +/** Assign a component value using copy semantics, with automatic ID lookup. + * + * @tparam T The component type. + * @tparam A The actual value type. + * @param world The world. + * @param entity The entity. + * @param value The value to assign (const reference). + */ template inline void assign(world_t *world, entity_t entity, const A& value) { id_t id = _::type::id(world); @@ -22423,7 +24717,15 @@ inline void assign(world_t *world, entity_t entity, const A& value) { } -// emplace for T(Args...) +/** Emplace a component value, constructing it in place. + * + * @tparam T The component type. + * @tparam Args Constructor argument types. + * @param world The world. + * @param entity The entity. + * @param id The component ID. + * @param args Constructor arguments. + */ template , Args...>::value || std::is_default_constructible>::value > = 0> @@ -22437,7 +24739,10 @@ inline void emplace(world_t *world, flecs::entity_t entity, flecs::id_t id, Args ecs_modified_id(world, entity, id); } -/** Return id without generation. +/** Return the ID without generation. + * + * @param e The entity ID. + * @return The entity ID without generation. * * @see ecs_strip_generation() */ @@ -22445,7 +24750,10 @@ inline flecs::id_t strip_generation(flecs::entity_t e) { return ecs_strip_generation(e); } -/** Return entity generation. +/** Return the entity generation. + * + * @param e The entity ID. + * @return The generation of the entity. */ inline uint32_t get_generation(flecs::entity_t e) { return ECS_GENERATION(e); @@ -22466,15 +24774,15 @@ struct scoped_world; * deleted, all data in the world will be deleted as well. */ struct world { - /** Create world. + /** Create a world. */ explicit world() - : world_( ecs_init() ) { - init_builtin_components(); + : world_( ecs_init() ) { + init_builtin_components(); } - /** Create world with command line arguments. - * Currently command line arguments are not interpreted, but they may be + /** Create a world with command-line arguments. + * Currently, command-line arguments are not interpreted, but they may be * used in the future to configure Flecs parameters. */ explicit world(int argc, char *argv[]) @@ -22482,7 +24790,7 @@ struct world { init_builtin_components(); } - /** Create world from C world. + /** Create a world from a C world. */ explicit world(world_t *w) : world_( w ) { @@ -22491,13 +24799,14 @@ struct world { } } - /** Not allowed to copy a world. May only take a reference. + /** Copy constructor. Increases reference count on the world. */ world(const world& obj) { this->world_ = obj.world_; flecs_poly_claim(this->world_); } + /** Copy assignment operator. Increases reference count on the world. */ world& operator=(const world& obj) noexcept { release(); this->world_ = obj.world_; @@ -22505,11 +24814,13 @@ struct world { return *this; } + /** Move constructor. Transfers world ownership. */ world(world&& obj) noexcept { world_ = obj.world_; obj.world_ = nullptr; } + /** Move assignment operator. Transfers world ownership. */ world& operator=(world&& obj) noexcept { release(); world_ = obj.world_; @@ -22517,17 +24828,18 @@ struct world { return *this; } - /* Releases the underlying world object. If this is the last handle, the world - will be finalized. */ + /** Release the underlying world object. + * If this is the last handle, the world will be finalized. + */ void release() { if (world_) { if (!flecs_poly_release(world_)) { if (ecs_stage_get_id(world_) == -1) { ecs_stage_free(world_); } else { - // before we call ecs_fini(), we increment the reference count back to 1 - // otherwise, copies of this object created during ecs_fini (e.g. a component on_remove hook) - // would call again this destructor and ecs_fini(). + // Before we call ecs_fini(), we increment the reference count back to 1. + // Otherwise, copies of this object created during ecs_fini() (e.g., a component on_remove hook) + // would again call this destructor and ecs_fini(). flecs_poly_claim(world_); ecs_fini(world_); } @@ -22536,15 +24848,16 @@ struct world { } } + /** Destructor. Releases the world reference. */ ~world() { release(); } - /* Implicit conversion to world_t* */ + /** Implicit conversion to world_t*. */ operator world_t*() const { return world_; } - /** Make current world object owner of the world. This may only be called on - * one flecs::world object, an may only be called once. Failing to do so + /** Make the current world object the owner of the world. This may only be called on + * one flecs::world object, and may only be called once. Failing to do so * will result in undefined behavior. * * This operation allows a custom (C) world to be wrapped by a C++ object, @@ -22554,16 +24867,17 @@ struct world { flecs_poly_release(world_); } - /** Deletes and recreates the world. */ + /** Delete and recreate the world. */ void reset() { - /* Make sure there's only one reference to the world */ + /* Make sure there's only one reference to the world. */ ecs_assert(flecs_poly_refcount(world_) == 1, ECS_INVALID_OPERATION, "reset would invalidate other handles"); ecs_fini(world_); world_ = ecs_init(); + init_builtin_components(); } - /** Obtain pointer to C world object. + /** Obtain a pointer to the C world object. */ world_t* c_ptr() const { return world_; @@ -22601,7 +24915,7 @@ struct world { * function needs to sleep to ensure it does not exceed the target_fps, when * it is set. When 0 is provided for delta_time, the time will be measured. * - * This function should only be ran from the main thread. + * This function should only be run from the main thread. * * @param delta_time Time elapsed since the last frame. * @return The provided delta_time, or measured time if 0 was provided. @@ -22617,7 +24931,7 @@ struct world { * This operation must be called at the end of the frame, and always after * frame_begin(). * - * This function should only be ran from the main thread. + * This function should only be run from the main thread. * * @see ecs_frame_end() * @see flecs::world::frame_begin() @@ -22628,7 +24942,7 @@ struct world { /** Begin readonly mode. * - * @param multi_threaded Whether to enable readonly/multi threaded mode. + * @param multi_threaded Whether to enable readonly/multi-threaded mode. * * @return Whether world is currently readonly. * @@ -22651,10 +24965,10 @@ struct world { } /** Defer operations until end of frame. - * When this operation is invoked while iterating, operations inbetween the + * When this operation is invoked while iterating, operations in between the * defer_begin() and defer_end() operations are executed at the end of the frame. * - * This operation is thread safe. + * This operation is thread-safe. * * @return true if world changed from non-deferred mode to deferred mode. * @@ -22673,7 +24987,7 @@ struct world { /** End block of operations to defer. * See defer_begin(). * - * This operation is thread safe. + * This operation is thread-safe. * * @return true if world changed from deferred mode to non-deferred mode. * @@ -22707,7 +25021,7 @@ struct world { /** Test whether deferring is suspended. * - * @return True if deferred, false if not. + * @return True if defer is suspended, false if not. * * @see ecs_is_defer_suspended() * @see flecs::world::defer() @@ -22740,8 +25054,8 @@ struct world { ecs_set_stage_count(world_, stages); } - /** Get number of configured stages. - * Return number of stages set by set_stage_count(). + /** Get the number of configured stages. + * Return the number of stages set by set_stage_count(). * * @return The number of stages used for threading. * @@ -22752,17 +25066,17 @@ struct world { return ecs_get_stage_count(world_); } - /** Get current stage id. - * The stage id can be used by an application to learn about which stage it - * is using, which typically corresponds with the worker thread id. + /** Get current stage ID. + * The stage ID can be used by an application to learn about which stage it + * is using, which typically corresponds with the worker thread ID. * - * @return The stage id. + * @return The stage ID. */ int32_t get_stage_id() const { return ecs_stage_get_id(world_); } - /** Test if is a stage. + /** Test if this is a stage. * If this function returns false, it is guaranteed that this is a valid * world object. * @@ -22800,7 +25114,7 @@ struct world { * existing world in a thread-specific context, which the API knows how to * unwrap. The reason the stage is returned as an ecs_world_t is so that it * can be passed transparently to the existing API functions, vs. having to - * create a dediated API for threading. + * create a dedicated API for threading. * * @param stage_id The index of the stage to retrieve. * @return A thread-specific pointer to the world. @@ -22809,14 +25123,14 @@ struct world { return flecs::world(ecs_get_stage(world_, stage_id)); } - /** Create asynchronous stage. + /** Create an asynchronous stage. * An asynchronous stage can be used to asynchronously queue operations for * later merging with the world. An asynchronous stage is similar to a regular * stage, except that it does not allow reading from the world. * * Asynchronous stages are never merged automatically, and must therefore be - * manually merged with the ecs_merge function. It is not necessary to call - * defer_begin or defer_end before and after enqueuing commands, as an + * manually merged with the ecs_merge() function. It is not necessary to call + * defer_begin() or defer_end() before and after enqueuing commands, as an * asynchronous stage unconditionally defers operations. * * The application must ensure that no commands are added to the stage while the @@ -22826,7 +25140,7 @@ struct world { */ flecs::world async_stage() const { ecs_world_t *as = ecs_stage_new(world_); - flecs_poly_release(as); // world object will claim + flecs_poly_release(as); // World object will claim. return flecs::world(as); } @@ -22837,7 +25151,7 @@ struct world { * @return The actual world. */ flecs::world get_world() const { - /* Safe cast, mutability is checked */ + /* Safe cast, mutability is checked. */ return flecs::world( world_ ? const_cast(ecs_get_world(world_)) : nullptr); } @@ -22860,10 +25174,9 @@ struct world { * Set a context value that can be accessed by anyone that has a reference * to the world. * - * @param ctx A pointer to a user defined structure. + * @param ctx A pointer to a user-defined structure. * @param ctx_free A function that is invoked with ctx when the world is freed. * - * * @see ecs_set_ctx() * @see flecs::world::get_ctx() */ @@ -22874,7 +25187,7 @@ struct world { /** Get world context. * This operation retrieves a previously set world context. * - * @return The context set with set_binding_ctx(). If no context was set, the + * @return The context set with set_ctx(). If no context was set, the * function returns NULL. * * @see ecs_get_ctx() @@ -22887,9 +25200,9 @@ struct world { /** Set world binding context. * * Same as set_ctx() but for binding context. A binding context is intended - * specifically for language bindings to store binding specific data. + * specifically for language bindings to store binding-specific data. * - * @param ctx A pointer to a user defined structure. + * @param ctx A pointer to a user-defined structure. * @param ctx_free A function that is invoked with ctx when the world is freed. * * @see ecs_set_binding_ctx() @@ -22912,7 +25225,7 @@ struct world { return ecs_get_binding_ctx(world_); } - /** Preallocate memory for number of entities. + /** Preallocate memory for a number of entities. * This function preallocates memory for the entity index. * * @param entity_count Number of entities to preallocate memory for. @@ -22924,10 +25237,10 @@ struct world { } /** Set entity range. - * This function limits the range of issued entity ids between min and max. + * This function limits the range of issued entity IDs between min and max. * - * @param min Minimum entity id issued. - * @param max Maximum entity id issued. + * @param min Minimum entity ID issued. + * @param max Maximum entity ID issued. * * @see ecs_set_entity_range() */ @@ -22952,7 +25265,7 @@ struct world { /** Set current scope. * * @param scope The scope to set. - * @return The current scope; + * @return The previous scope. * * @see ecs_set_scope() * @see flecs::world::get_scope() @@ -22968,7 +25281,7 @@ struct world { */ flecs::entity get_scope() const; - /** Same as set_scope but with type. + /** Same as set_scope(), but with type. * * @see ecs_set_scope() * @see flecs::world::get_scope() @@ -22988,8 +25301,10 @@ struct world { /** Lookup entity by name. * * @param name Entity name. + * @param sep The scope separator. + * @param root_sep The root scope separator. * @param recursive When false, only the current scope is searched. - * @result The entity if found, or 0 if not found. + * @return The entity if found, or 0 if not found. */ flecs::entity lookup(const char *name, const char *sep = "::", const char *root_sep = "::", bool recursive = true) const; @@ -23180,8 +25495,8 @@ struct world { /** Test if world has the provided pair. * - * @tparam First The first element of the pair - * @tparam Second The second element of the pair + * @tparam First The first element of the pair. + * @tparam Second The second element of the pair. * @return Whether the world has the singleton pair. */ template @@ -23189,7 +25504,7 @@ struct world { /** Test if world has the provided pair. * - * @tparam First The first element of the pair + * @tparam First The first element of the pair. * @param second The second element of the pair. * @return Whether the world has the singleton pair. */ @@ -23198,14 +25513,14 @@ struct world { /** Test if world has the provided pair. * - * @param first The first element of the pair - * @param second The second element of the pair + * @param first The first element of the pair. + * @param second The second element of the pair. * @return Whether the world has the singleton pair. */ bool has(flecs::id_t first, flecs::id_t second) const; - /** Check for enum singleton constant - * + /** Check for enum singleton constant. + * * @tparam E The enum type. * @param value The enum constant to check. * @return Whether the world has the specified enum constant. @@ -23218,31 +25533,31 @@ struct world { template void add() const; - /** Adds a pair to the singleton component. + /** Add a pair to the singleton component. * - * @tparam First The first element of the pair - * @tparam Second The second element of the pair + * @tparam First The first element of the pair. + * @tparam Second The second element of the pair. */ template void add() const; - /** Adds a pair to the singleton component. + /** Add a pair to the singleton component. * - * @tparam First The first element of the pair + * @tparam First The first element of the pair. * @param second The second element of the pair. */ template void add(flecs::entity_t second) const; - /** Adds a pair to the singleton entity. + /** Add a pair to the singleton entity. * - * @param first The first element of the pair - * @param second The second element of the pair + * @param first The first element of the pair. + * @param second The second element of the pair. */ void add(flecs::entity_t first, flecs::entity_t second) const; - /** Add enum singleton constant - * + /** Add enum singleton constant. + * * @tparam E The enum type. * @param value The enum constant. */ @@ -23254,30 +25569,30 @@ struct world { template void remove() const; - /** Removes the pair singleton component. + /** Remove the pair singleton component. * - * @tparam First The first element of the pair - * @tparam Second The second element of the pair + * @tparam First The first element of the pair. + * @tparam Second The second element of the pair. */ template void remove() const; - /** Removes the pair singleton component. + /** Remove the pair singleton component. * - * @tparam First The first element of the pair + * @tparam First The first element of the pair. * @param second The second element of the pair. */ template void remove(flecs::entity_t second) const; - /** Removes the pair singleton component. + /** Remove the pair singleton component. * - * @param first The first element of the pair - * @param second The second element of the pair + * @param first The first element of the pair. + * @param second The second element of the pair. */ void remove(flecs::entity_t first, flecs::entity_t second) const; - /** Iterate entities in root of world + /** Iterate entities in root of world. * Accepts a callback with the following signature: * * @code @@ -23299,6 +25614,7 @@ struct world { * * @tparam First The first element of the pair. * @param index The index (0 for the first instance of the relationship). + * @return The target entity. */ template flecs::entity target(int32_t index = 0) const; @@ -23308,8 +25624,10 @@ struct world { * index can be used to iterate through targets, in case the entity has * multiple instances for the same relationship. * + * @tparam T The singleton type. * @param first The first element of the pair for which to retrieve the target. * @param index The index (0 for the first instance of the relationship). + * @return The target entity. */ template flecs::entity target(flecs::entity_t first, int32_t index = 0) const; @@ -23321,26 +25639,27 @@ struct world { * * @param first The first element of the pair for which to retrieve the target. * @param index The index (0 for the first instance of the relationship). + * @return The target entity. */ flecs::entity target(flecs::entity_t first, int32_t index = 0) const; - /** Create alias for component. + /** Create an alias for a component. * - * @tparam T to create an alias for. + * @tparam T The type to create an alias for. * @param alias Alias for the component. * @return Entity representing the component. */ template flecs::entity use(const char *alias = nullptr) const; - /** Create alias for entity. + /** Create an alias for an entity. * * @param name Name of the entity. * @param alias Alias for the entity. */ flecs::entity use(const char *name, const char *alias = nullptr) const; - /** Create alias for entity. + /** Create an alias for an entity. * * @param entity Entity for which to create the alias. * @param alias Alias for the entity. @@ -23349,7 +25668,8 @@ struct world { /** Count entities matching a component. * - * @param component_id The component id. + * @param component_id The component ID. + * @return The number of entities matching the component. */ int count(flecs::id_t component_id) const { return ecs_count_id(world_, component_id); @@ -23359,6 +25679,7 @@ struct world { * * @param first The first element of the pair. * @param second The second element of the pair. + * @return The number of entities matching the pair. */ int count(flecs::entity_t first, flecs::entity_t second) const { return ecs_count_id(world_, ecs_pair(first, second)); @@ -23367,6 +25688,7 @@ struct world { /** Count entities matching a component. * * @tparam T The component type. + * @return The number of entities matching the component. */ template int count() const { @@ -23377,6 +25699,7 @@ struct world { * * @tparam First The first element of the pair. * @param second The second element of the pair. + * @return The number of entities matching the pair. */ template int count(flecs::entity_t second) const { @@ -23387,6 +25710,7 @@ struct world { * * @tparam First The first element of the pair. * @tparam Second The second element of the pair. + * @return The number of entities matching the pair. */ template int count() const { @@ -23395,7 +25719,7 @@ struct world { _::type::id(world_)); } - /** All entities created in function are created with id. + /** All entities created in the function are created with the ID. */ template void with(id_t with_id, const Func& func) const { @@ -23404,36 +25728,36 @@ struct world { ecs_set_with(world_, prev); } - /** All entities created in function are created with type. + /** All entities created in the function are created with the type. */ template void with(const Func& func) const { with(this->id(), func); } - /** All entities created in function are created with pair. + /** All entities created in the function are created with the pair. */ template void with(const Func& func) const { with(ecs_pair(this->id(), this->id()), func); } - /** All entities created in function are created with pair. + /** All entities created in the function are created with the pair. */ template void with(id_t second, const Func& func) const { with(ecs_pair(this->id(), second), func); } - /** All entities created in function are created with pair. + /** All entities created in the function are created with the pair. */ template void with(id_t first, id_t second, const Func& func) const { with(ecs_pair(first, second), func); } - /** All entities created in function are created in scope. All operations - * called in function (such as lookup) are relative to scope. + /** All entities created in the function are created in the scope. All operations + * called in the function (such as lookup()) are relative to the scope. */ template void scope(id_t parent, const Func& func) const { @@ -23450,8 +25774,8 @@ struct world { scope(parent, func); } - /** Use provided scope for operations ran on returned world. - * Operations need to be ran in a single statement. + /** Use the provided scope for operations run on the returned world. + * Operations need to be run in a single statement. */ flecs::scoped_world scope(id_t parent) const; @@ -23520,7 +25844,7 @@ struct world { * * @see flecs::world::defer_begin() * @see flecs::world::defer_end() - * @see flecs::world::defer_is_deferred() + * @see flecs::world::is_deferred() * @see flecs::world::defer_resume() * @see flecs::world::defer_suspend() */ @@ -23537,7 +25861,7 @@ struct world { * @see flecs::world::defer() * @see flecs::world::defer_begin() * @see flecs::world::defer_end() - * @see flecs::world::defer_is_deferred() + * @see flecs::world::is_deferred() * @see flecs::world::defer_resume() */ void defer_suspend() const { @@ -23550,14 +25874,14 @@ struct world { * @see flecs::world::defer() * @see flecs::world::defer_begin() * @see flecs::world::defer_end() - * @see flecs::world::defer_is_deferred() + * @see flecs::world::is_deferred() * @see flecs::world::defer_suspend() */ void defer_resume() const { ecs_defer_resume(world_); } - /** Check if entity id exists in the world. + /** Check if entity ID exists in the world. * * @see ecs_exists() * @see flecs::world::is_alive() @@ -23567,7 +25891,7 @@ struct world { return ecs_exists(world_, e); } - /** Check if entity id exists in the world. + /** Check if entity is alive. * * @see ecs_is_alive() * @see flecs::world::exists() @@ -23577,7 +25901,7 @@ struct world { return ecs_is_alive(world_, e); } - /** Check if entity id is valid. + /** Check if entity ID is valid. * Invalid entities cannot be used with API functions. * * @see ecs_is_valid() @@ -23588,8 +25912,8 @@ struct world { return ecs_is_valid(world_, e); } - /** Get alive entity for id. - * Returns the entity with the current generation. + /** Get alive entity for ID. + * Return the entity with the current generation. * * @see ecs_get_alive() */ @@ -23600,7 +25924,7 @@ struct world { */ flecs::entity make_alive(flecs::entity_t e) const; - /** Set version of entity to provided. + /** Set the version of an entity to the provided value. * * @see ecs_set_version() */ @@ -23608,7 +25932,7 @@ struct world { ecs_set_version(world_, e); } - /** Get version of provided entity. + /** Get the version of the provided entity. * * @see ecs_get_version() */ @@ -23616,7 +25940,7 @@ struct world { return ecs_get_version(e); } - /* Run callback after completing frame */ + /** Run callback after completing the frame. */ void run_post_frame(ecs_fini_action_t action, void *ctx) const { ecs_run_post_frame(world_, action, ctx); } @@ -23625,11 +25949,11 @@ struct world { * * @see ecs_get_world_info() */ - const flecs::world_info_t* get_info() const{ + const flecs::world_info_t* get_info() const { return ecs_get_world_info(world_); } - /** Get delta_time */ + /** Get delta_time. */ ecs_ftime_t delta_time() const { return get_info()->delta_time; } @@ -23637,13 +25961,13 @@ struct world { /** Free unused memory. * * @see ecs_shrink() - */ + */ void shrink() const { ecs_shrink(world_); } - /** Begin exclusive access - * + /** Begin exclusive access. + * * @param thread_name Optional thread name for improved debug messages. * @see ecs_exclusive_access_begin() */ @@ -23651,8 +25975,8 @@ struct world { ecs_exclusive_access_begin(world_, thread_name); } - /** End exclusive access - * + /** End exclusive access. + * * @param lock_world Lock world for all threads, allow readonly operations. * @see ecs_exclusive_access_end() */ @@ -23660,11 +25984,11 @@ struct world { ecs_exclusive_access_end(world_, lock_world); } - /** Return component id if it has been registered. - * This operation is similar to world::id() but will never automatically + /** Return the component ID if it has been registered. + * This operation is similar to world::id(), but will never automatically * register the component. - * - * @tparam T The type for which to obtain the id. + * + * @tparam T The type for which to obtain the ID. */ template flecs::id_t id_if_registered() { @@ -23676,29 +26000,29 @@ struct world { } } - /** Return type info */ + /** Return the type info. */ const flecs::type_info_t* type_info(flecs::id_t component) { return ecs_get_type_info(world_, component); } - /** Return type info */ + /** Return the type info. */ const flecs::type_info_t* type_info(flecs::entity_t r, flecs::entity_t t) { return ecs_get_type_info(world_, ecs_pair(r, t)); } - /** Return type info */ + /** Return the type info. */ template const flecs::type_info_t* type_info() { return ecs_get_type_info(world_, _::type::id(world_)); } - /** Return type info */ + /** Return the type info. */ template const flecs::type_info_t* type_info(flecs::entity_t t) { return type_info(_::type::id(world_), t); } - /** Return type info */ + /** Return the type info. */ template const flecs::type_info_t* type_info() { return type_info(_::type::id(world_)); @@ -23706,38 +26030,38 @@ struct world { /** * @file addons/cpp/mixins/id/mixin.inl - * @brief Id world mixin. + * @brief ID world mixin. */ -/** Get id from a type. +/** Get ID from a type. * * @memberof flecs::world */ template flecs::id id() const; -/** Id factory. +/** ID factory. * * @memberof flecs::world */ template flecs::id id(Args&&... args) const; -/** Get pair id from relationship, object. +/** Get pair ID from relationship and object. * * @memberof flecs::world */ template flecs::id pair() const; -/** Get pair id from relationship, object. +/** Get pair ID from relationship and object. * * @memberof flecs::world */ template flecs::id pair(entity_t o) const; -/** Get pair id from relationship, object. +/** Get pair ID from relationship and object. * * @memberof flecs::world */ @@ -23748,7 +26072,7 @@ flecs::id pair(entity_t r, entity_t o) const; * @brief Component mixin. */ -/** Find or register component. +/** Find or register a component. * * @ingroup cpp_components * @memberof flecs::world @@ -23756,8 +26080,8 @@ flecs::id pair(entity_t r, entity_t o) const; template flecs::component component(Args &&... args) const; -/** Find or register untyped component. - * Method available on flecs::world class. +/** Find or register an untyped component. + * Method available on the flecs::world class. * * @ingroup cpp_components * @memberof flecs::world @@ -23778,7 +26102,7 @@ flecs::untyped_component component(Args &&... args) const; template flecs::entity entity(Args &&... args) const; -/** Convert enum constant to entity. +/** Convert an enum constant to an entity. * * @memberof flecs::world * @ingroup cpp_entities @@ -23786,7 +26110,7 @@ flecs::entity entity(Args &&... args) const; template ::value > = 0> flecs::id id(E value) const; -/** Convert enum constant to entity. +/** Convert an enum constant to an entity. * * @memberof flecs::world * @ingroup cpp_entities @@ -23835,7 +26159,7 @@ flecs::entity prefab(const char *name = nullptr) const; * * @memberof flecs::world * - * @param evt The event id. + * @param evt The event ID. * @return Event builder. */ flecs::event_builder event(flecs::entity_t evt) const; @@ -23887,15 +26211,15 @@ flecs::term term() const; * @brief Observer world mixin. */ -/** Observer builder. - * +/** Observer world mixin. + * * @memberof flecs::world * @ingroup cpp_observers * * @{ */ -/** Upcast entity to an observer. +/** Upcast an entity to an observer. * The provided entity must be an observer. * * @param e The entity. @@ -23907,7 +26231,7 @@ flecs::observer observer(flecs::entity e) const; * * @tparam Components The components to match on. * @tparam Args Arguments passed to the constructor of flecs::observer_builder. - * @return Observer builder. + * @return An observer builder. */ template flecs::observer_builder observer(Args &&... args) const; @@ -23928,28 +26252,34 @@ flecs::observer_builder observer(Args &&... args) const; /** Create a query. * - * @see ecs_query_init + * @see ecs_query_init() */ template flecs::query query(Args &&... args) const; -/** Create a query from entity. - * - * @see ecs_query_init +/** Create a query from an entity. + * + * @see ecs_query_init() */ flecs::query<> query(flecs::entity query_entity) const; /** Create a query builder. - * - * @see ecs_query_init + * + * @see ecs_query_init() */ template flecs::query_builder query_builder(Args &&... args) const; -/** Iterate over all entities with components in argument list of function. +/** Iterate over all entities with components in the argument list of the function. * The function parameter must match the following signature: * * @code + * void(*)(flecs::entity) + * @endcode + * + * or: + * + * @code * void(*)(T&, U&, ...) * @endcode * @@ -23963,7 +26293,7 @@ flecs::query_builder query_builder(Args &&... args) const; template void each(Func&& func) const; -/** Iterate over all entities with provided component. +/** Iterate over all entities with the provided component. * The function parameter must match the following signature: * * @code @@ -23980,7 +26310,7 @@ void each(Func&& func) const; template void each(Func&& func) const; -/** Iterate over all entities with provided (component) id. */ +/** Iterate over all entities with the provided (component) ID. */ template void each(flecs::id_t term_id, Func&& func) const; @@ -23991,7 +26321,7 @@ void each(flecs::id_t term_id, Func&& func) const; * @brief Enum world mixin. */ -/** Convert enum constant to entity. +/** Convert an enum constant to an entity. * * @memberof flecs::world * @ingroup cpp_entities @@ -24055,77 +26385,77 @@ flecs::pipeline_builder<> pipeline() const; /** Create a new pipeline. * - * @tparam Pipeline Type associated with pipeline. + * @tparam Pipeline Type associated with the pipeline. * @return A pipeline builder. */ template ::value > = 0> flecs::pipeline_builder<> pipeline() const; -/** Set pipeline. - * @see ecs_set_pipeline +/** Set the pipeline. + * @see ecs_set_pipeline() */ void set_pipeline(const flecs::entity pip) const; -/** Set pipeline. - * @see ecs_set_pipeline +/** Set the pipeline. + * @see ecs_set_pipeline() */ template void set_pipeline() const; -/** Get pipeline. - * @see ecs_get_pipeline +/** Get the pipeline. + * @see ecs_get_pipeline() */ flecs::entity get_pipeline() const; -/** Progress world one tick. - * @see ecs_progress +/** Progress the world one tick. + * @see ecs_progress() */ bool progress(ecs_ftime_t delta_time = 0.0) const; -/** Run pipeline. - * @see ecs_run_pipeline +/** Run a pipeline. + * @see ecs_run_pipeline() */ void run_pipeline(const flecs::entity_t pip, ecs_ftime_t delta_time = 0.0) const; -/** Run pipeline. - * @tparam Pipeline Type associated with pipeline. - * @see ecs_run_pipeline +/** Run a pipeline. + * @tparam Pipeline Type associated with the pipeline. + * @see ecs_run_pipeline() */ template ::value > = 0> void run_pipeline(ecs_ftime_t delta_time = 0.0) const; -/** Set timescale. - * @see ecs_set_time_scale +/** Set the time scale. + * @see ecs_set_time_scale() */ void set_time_scale(ecs_ftime_t mul) const; -/** Set target FPS. - * @see ecs_set_target_fps +/** Set the target FPS. + * @see ecs_set_target_fps() */ void set_target_fps(ecs_ftime_t target_fps) const; -/** Reset simulation clock. - * @see ecs_reset_clock +/** Reset the simulation clock. + * @see ecs_reset_clock() */ void reset_clock() const; -/** Set number of threads. - * @see ecs_set_threads +/** Set the number of threads. + * @see ecs_set_threads() */ void set_threads(int32_t threads) const; -/** Set number of threads. - * @see ecs_get_stage_count +/** Get the number of threads. + * @see ecs_get_stage_count() */ int32_t get_threads() const; -/** Set number of task threads. - * @see ecs_set_task_threads +/** Set the number of task threads. + * @see ecs_set_task_threads() */ void set_task_threads(int32_t task_threads) const; -/** Returns true if task thread use has been requested. - * @see ecs_using_task_threads +/** Return true if task thread use has been requested. + * @see ecs_using_task_threads() */ bool using_task_threads() const; @@ -24138,14 +26468,14 @@ bool using_task_threads() const; * @brief System module world mixin. */ -/** +/** * @memberof flecs::world * @ingroup cpp_addons_systems * * @{ -*/ + */ -/** Upcast entity to a system. +/** Upcast an entity to a system. * The provided entity must be a system. * * @param e The entity. @@ -24157,7 +26487,7 @@ flecs::system system(flecs::entity e) const; * * @tparam Components The components to match on. * @tparam Args Arguments passed to the constructor of flecs::system_builder. - * @return System builder. + * @return A system builder. */ template flecs::system_builder system(Args &&... args) const; @@ -24185,7 +26515,7 @@ template flecs::timer timer(Args &&... args) const; /** Enable randomization of initial time values for timers. - * @see ecs_randomize_timers + * @see ecs_randomize_timers() */ void randomize_timers() const; @@ -24204,41 +26534,41 @@ void randomize_timers() const; * @{ */ -/** Run script. - * @see ecs_script_run +/** Run a script. + * @see ecs_script_run() */ int script_run(const char *name, const char *str) const { return ecs_script_run(world_, name, str, nullptr); } -/** Run script from file. - * @see ecs_script_run_file +/** Run a script from a file. + * @see ecs_script_run_file() */ int script_run_file(const char *filename) const { return ecs_script_run_file(world_, filename); } -/** Build script. - * @see ecs_script_init +/** Build a script. + * @see ecs_script_init() */ script_builder script(const char *name = nullptr) const { return script_builder(world_, name); } -/** Convert value to string */ +/** Convert a value to a string. */ flecs::string to_expr(flecs::entity_t tid, const void* value) { char *expr = ecs_ptr_to_expr(world_, tid, value); return flecs::string(expr); } -/** Convert value to string */ +/** Convert a value to a string. */ template flecs::string to_expr(const T* value) { flecs::entity_t tid = _::type::id(world_); return to_expr(tid, value); } -/** Get value of exported script variable. +/** Get the value of an exported script variable. * This operation will panic if no const var with the provided name was found, * or if the type of the variable cannot be converted to the provided type. * @@ -24258,7 +26588,7 @@ flecs::string to_expr(const T* value) { template T get_const_var(const char *name, const T& default_value = {}) const; -/** Get value of exported script variable. +/** Get the value of an exported script variable. * This operation will panic if no const var with the provided name was found, * or if the type of the variable cannot be converted to the provided type. * @@ -24295,32 +26625,32 @@ void get_const_var(const char *name, T& out, const T& default_value = {}) const; * @{ */ -/** Return meta cursor to value */ +/** Return a meta cursor to a value. */ flecs::cursor cursor(flecs::entity_t tid, void *ptr) { return flecs::cursor(world_, tid, ptr); } -/** Return meta cursor to value */ +/** Return a meta cursor to a value. */ template flecs::cursor cursor(void *ptr) { flecs::entity_t tid = _::type::id(world_); return cursor(tid, ptr); } -/** Create primitive type */ +/** Create a primitive type. */ flecs::entity primitive(flecs::meta::primitive_kind_t kind); -/** Create array type. */ +/** Create an array type. */ flecs::entity array(flecs::entity_t elem_id, int32_t array_count); -/** Create array type. */ +/** Create an array type. */ template flecs::entity array(int32_t array_count); -/** Create vector type. */ +/** Create a vector type. */ flecs::entity vector(flecs::entity_t elem_id); -/** Create vector type. */ +/** Create a vector type. */ template flecs::entity vector(); @@ -24333,7 +26663,7 @@ flecs::entity vector(); * @brief JSON world mixin. */ -/** Serialize untyped value to JSON. +/** Serialize an untyped value to JSON. * * @memberof flecs::world * @ingroup cpp_addons_json @@ -24343,7 +26673,7 @@ flecs::string to_json(flecs::entity_t tid, const void* value) const { return flecs::string(json); } -/** Serialize value to JSON. +/** Serialize a value to JSON. * * @memberof flecs::world * @ingroup cpp_addons_json @@ -24354,7 +26684,7 @@ flecs::string to_json(const T* value) const { return to_json(tid, value); } -/** Serialize world to JSON. +/** Serialize the world to JSON. * * @memberof flecs::world * @ingroup cpp_addons_json @@ -24363,8 +26693,8 @@ flecs::string to_json() const { return flecs::string( ecs_world_to_json(world_, nullptr) ); } -/** Deserialize value from JSON. - * +/** Deserialize a value from JSON. + * * @memberof flecs::world * @ingroup cpp_addons_json */ @@ -24372,8 +26702,8 @@ const char* from_json(flecs::entity_t tid, void* value, const char *json, flecs: return ecs_ptr_from_json(world_, tid, value, json, desc); } -/** Deserialize value from JSON. - * +/** Deserialize a value from JSON. + * * @memberof flecs::world * @ingroup cpp_addons_json */ @@ -24383,7 +26713,7 @@ const char* from_json(T* value, const char *json, flecs::from_json_desc_t *desc value, json, desc); } -/** Deserialize JSON into world. +/** Deserialize JSON into the world. * * @memberof flecs::world * @ingroup cpp_addons_json @@ -24392,7 +26722,7 @@ const char* from_json(const char *json, flecs::from_json_desc_t *desc = nullptr) return ecs_world_from_json(world_, json, desc); } -/** Deserialize JSON file into world. +/** Deserialize a JSON file into the world. * * @memberof flecs::world * @ingroup cpp_addons_json @@ -24415,11 +26745,11 @@ const char* from_json_file(const char *json, flecs::from_json_desc_t *desc = nul * @{ */ -/** Return app builder. - * The app builder is a convenience wrapper around a loop that runs - * world::progress. An app allows for writing platform agnostic code, - * as it provides hooks to modules for overtaking the main loop which is - * required for frameworks like emscripten. +/** Return an app builder. + * The app builder is a convenience wrapper around a loop that runs + * world::progress(). An app allows for writing platform-agnostic code, + * as it provides hooks to modules for overtaking the main loop, which is + * required for frameworks like Emscripten. */ flecs::app_builder app() { flecs::world_t *w = world_; @@ -24431,9 +26761,13 @@ flecs::app_builder app() { # endif # ifdef FLECS_METRICS +/** + * @file addons/cpp/mixins/metrics/mixin.inl + * @brief Metrics world mixin. + */ -/** Create metric. - * +/** Create a metric. + * * @ingroup cpp_addons_metrics * @memberof flecs::world */ @@ -24442,9 +26776,13 @@ flecs::metric_builder metric(Args &&... args) const; # endif # ifdef FLECS_ALERTS +/** + * @file addons/cpp/mixins/alerts/mixin.inl + * @brief Alert world mixin. + */ -/** Create alert. - * +/** Create an alert. + * * @ingroup cpp_addons_alerts * @memberof flecs::world */ @@ -24454,15 +26792,21 @@ flecs::alert_builder alert(Args &&... args) const; # endif public: + /** Initialize built-in components. */ void init_builtin_components(); - world_t *world_; + world_t *world_; /**< Pointer to the underlying C world. */ }; /** Scoped world. - * Utility class used by the world::scope method to create entities in a scope. + * Utility class used by the world::scope() method to create entities in a scope. */ struct scoped_world : world { + /** Create a scoped world. + * + * @param w The world. + * @param s The scope entity. + */ scoped_world( flecs::world_t *w, flecs::entity_t s) : world(w) @@ -24470,17 +26814,19 @@ struct scoped_world : world { prev_scope_ = ecs_set_scope(w, s); } + /** Destructor. Restores the previous scope. */ ~scoped_world() { ecs_set_scope(world_, prev_scope_); } + /** Copy constructor. */ scoped_world(const scoped_world& obj) : world(nullptr) { prev_scope_ = obj.prev_scope_; world_ = obj.world_; flecs_poly_claim(world_); } - flecs::entity_t prev_scope_; + flecs::entity_t prev_scope_; /**< The previous scope entity. */ }; /** @} */ @@ -24519,7 +26865,7 @@ struct untyped_field { , count_(count) , is_shared_(is_shared) {} - /** Return element in component array. + /** Return an element in the component array. * This operator may only be used if the field is not shared. * * @param index Index of element. @@ -24542,7 +26888,7 @@ struct untyped_field { /** Wrapper class around a field. * - * @tparam T component type of the field. + * @tparam T Component type of the field. * * @ingroup cpp_iterator */ @@ -24551,25 +26897,25 @@ struct field { static_assert(std::is_empty::value == false, "invalid type for field, cannot iterate empty type"); - /** Create field from component array. + /** Create a field from a component array. * * @param array Pointer to the component array. - * @param count Number of elements in component array. - * @param is_shared Is the component shared or not. + * @param count Number of elements in the component array. + * @param is_shared Whether the component is shared. */ field(T* array, size_t count, bool is_shared = false) : data_(array) , count_(count) , is_shared_(is_shared) {} - /** Create field from iterator. + /** Create a field from an iterator. * * @param iter Iterator object. - * @param field Index of the signature of the query being iterated over. + * @param field Index of the field in the query being iterated over. */ field(iter &iter, int field); - /** Return element in component array. + /** Return an element in the component array. * This operator may only be used if the field is not shared. * * @param index Index of element. @@ -24577,14 +26923,14 @@ struct field { */ T& operator[](size_t index) const; - /** Return first element of component array. + /** Return the first element of the component array. * This operator is typically used when the field is shared. * * @return Reference to the first element. */ T& operator*() const; - /** Return first element of component array. + /** Return the first element of the component array. * This operator is typically used when the field is shared. * * @return Pointer to the first element. @@ -24627,7 +26973,7 @@ namespace _ { /** Iterate over an integer range (used to iterate over entity range). * - * @tparam T of the iterator + * @tparam T The value type of the iterator. */ template struct range_iterator @@ -24680,26 +27026,37 @@ struct iter { */ iter(ecs_iter_t *it) : iter_(it) { } + /** Get an iterator to the beginning of the entity range. */ row_iterator begin() const { return row_iterator(0); } + /** Get an iterator to the end of the entity range. */ row_iterator end() const { return row_iterator(static_cast(iter_->count)); } + /** Get the system entity associated with the iterator. */ flecs::entity system() const; + /** Get the event entity associated with the iterator. */ flecs::entity event() const; + /** Get the event ID associated with the iterator. */ flecs::id event_id() const; + /** Get the world associated with the iterator. */ flecs::world world() const; + /** Get a pointer to the underlying C iterator object. */ const flecs::iter_t* c_ptr() const { return iter_; } + /** Get the number of entities to iterate over. + * + * @return The number of entities in the current result. + */ size_t count() const { ecs_check(iter_->flags & EcsIterIsValid, ECS_INVALID_PARAMETER, "operation invalid before calling next()"); @@ -24708,20 +27065,35 @@ struct iter { return 0; } + /** Get the time elapsed since the last frame. + * + * @return The delta time. + */ ecs_ftime_t delta_time() const { return iter_->delta_time; } + /** Get the time elapsed since the last system invocation. + * + * @return The delta system time. + */ ecs_ftime_t delta_system_time() const { return iter_->delta_system_time; } + /** Get the type of the iterated table. */ flecs::type type() const; + /** Get the table for the current iterator result. */ flecs::table table() const; + /** Get the other table for the current iterator result. + * This is used for move operations where data is moved from one table + * to another. + */ flecs::table other_table() const; + /** Get the table range for the current iterator result. */ flecs::table_range range() const; /** Access ctx. @@ -24740,14 +27112,14 @@ struct iter { } /** Access param. - * param contains the pointer passed to the param argument of system::run + * param contains the pointer passed to the param argument of system::run(). */ void* param() { return iter_->param; } /** Access param. - * param contains the pointer passed to the param argument of system::run + * param contains the pointer passed to the param argument of system::run(). */ template T* param() { @@ -24755,121 +27127,133 @@ struct iter { return static_cast(iter_->param); } - /** Obtain mutable handle to entity being iterated over. + /** Obtain a mutable handle to the entity being iterated over. * * @param row Row being iterated over. + * @return The entity at the specified row. */ flecs::entity entity(size_t row) const; - /** Returns whether field is matched on self. + /** Return whether the field is matched on self. * * @param index The field index. + * @return True if the field is matched on self, false if not. */ bool is_self(int8_t index) const { return ecs_field_is_self(iter_, index); } - /** Returns whether field is set. + /** Return whether the field is set. * * @param index The field index. + * @return True if the field is set, false if not. */ bool is_set(int8_t index) const { return ecs_field_is_set(iter_, index); } - /** Returns whether field is readonly. + /** Return whether the field is readonly. * * @param index The field index. + * @return True if the field is readonly, false if not. */ bool is_readonly(int8_t index) const { return ecs_field_is_readonly(iter_, index); } - /** Number of fields in iterator. + /** Number of fields in the iterator. + * + * @return The number of fields. */ int32_t field_count() const { return iter_->field_count; } - /** Size of field data type. + /** Size of the field data type. * - * @param index The field id. + * @param index The field index. + * @return The size of the field data type. */ size_t size(int8_t index) const { return ecs_field_size(iter_, index); } - /** Obtain field source (0 if This). + /** Obtain the field source (0 if This). * * @param index The field index. + * @return The source entity for the field. */ flecs::entity src(int8_t index) const; - /** Obtain id matched for field. + /** Obtain the ID matched for the field. * * @param index The field index. + * @return The ID matched for the field. */ flecs::id id(int8_t index) const; - /** Obtain pair id matched for field. - * This operation will fail if the id is not a pair. + /** Obtain the pair ID matched for the field. + * This operation will fail if the ID is not a pair. * * @param index The field index. + * @return The pair ID matched for the field. */ flecs::id pair(int8_t index) const; - /** Obtain column index for field. + /** Obtain the column index for the field. * * @param index The field index. + * @return The column index for the field. */ int32_t column_index(int8_t index) const { return ecs_field_column(iter_, index); } - /** Obtain term that triggered an observer + /** Obtain the term that triggered an observer. + * + * @return The index of the term that triggered the observer. */ int8_t term_index() const { return iter_->term_index; } /** Convert current iterator result to string. + * + * @return String representation of the current iterator result. */ flecs::string str() const { char *s = ecs_iter_str(iter_); return flecs::string(s); } - /** Get readonly access to field data. + /** Get read-only access to field data. * If the specified field index does not match with the provided type, the * function will assert. * * This function should not be used in each() callbacks, unless it is to * access a shared field. For access to non-shared fields in each(), use - * field_at. + * field_at(). * * @tparam T Type of the field. * @param index The field index. * @return The field data. */ - template , - typename std::enable_if::value, void>::type* = nullptr> + template , if_t> = 0> flecs::field field(int8_t index) const; /** Get read/write access to field data. - * If the matched id for the specified field does not match with the provided + * If the matched ID for the specified field does not match with the provided * type or if the field is readonly, the function will assert. * * This function should not be used in each() callbacks, unless it is to * access a shared field. For access to non-shared fields in each(), use - * field_at. + * field_at(). * * @tparam T Type of the field. * @param index The field index. * @return The field data. */ - template , - typename std::enable_if< - std::is_const::value == false, void>::type* = nullptr> + template , if_not_t> = 0> flecs::field field(int8_t index) const; /** Get unchecked access to field data. @@ -24878,7 +27262,7 @@ struct iter { * * This function should not be used in each() callbacks, unless it is to * access a shared field. For access to non-shared fields in each(), use - * field_at. + * field_at(). * * @param index The field index. */ @@ -24889,8 +27273,12 @@ struct iter { return get_unchecked_field(index); } - /** Get pointer to field at row. + /** Get pointer to field at row. * This function may be used to access shared fields when row is set to 0. + * + * @param index The field index. + * @param row The row index. + * @return Pointer to the field value at the specified row. */ void* field_at(int8_t index, size_t row) const { if (iter_->row_fields & (1llu << index)) { @@ -24900,11 +27288,15 @@ struct iter { } } - /** Get reference to field at row. + /** Get const reference to field at row. * This function may be used to access shared fields when row is set to 0. + * + * @tparam T Type of the field (must be const-qualified). + * @param index The field index. + * @param row The row index. + * @return Const reference to the field value at the specified row. */ - template , - typename std::enable_if::value, void>::type* = nullptr> + template , if_t< is_const_v > = 0> const A& field_at(int8_t index, size_t row) const { if (iter_->row_fields & (1llu << index)) { return get_field_at(index, row)[0]; @@ -24913,12 +27305,15 @@ struct iter { } } - /** Get reference to field at row. + /** Get mutable reference to field at row. * This function may be used to access shared fields when row is set to 0. + * + * @tparam T Type of the field (must not be const-qualified). + * @param index The field index. + * @param row The row index. + * @return Mutable reference to the field value at the specified row. */ - template , - typename std::enable_if< - std::is_const::value == false, void>::type* = nullptr> + template , if_not_t< is_const_v > = 0> A& field_at(int8_t index, size_t row) const { ecs_assert(!ecs_field_is_readonly(iter_, index), ECS_ACCESS_VIOLATION, NULL); @@ -24929,9 +27324,9 @@ struct iter { } } - /** Get readonly access to entity ids. + /** Get read-only access to entity IDs. * - * @return The entity ids. + * @return The entity IDs. */ flecs::field entities() const { return flecs::field( @@ -24939,7 +27334,10 @@ struct iter { } /** Check if the current table has changed since the last iteration. - * Can only be used when iterating queries and/or systems. */ + * Can only be used when iterating queries and/or systems. + * + * @return True if the table has changed. + */ bool changed() { return ecs_iter_changed(iter_); } @@ -24955,18 +27353,27 @@ struct iter { ecs_iter_skip(iter_); } - /* Return group id for current table (grouped queries only) */ + /** Return the group ID for the current table (grouped queries only). + * + * @return The group ID. + */ uint64_t group_id() const { return ecs_iter_get_group(iter_); } - /** Get value of variable by id. + /** Get value of variable by ID. * Get value of a query variable for current result. + * + * @param var_id The variable ID. + * @return The variable value. */ flecs::entity get_var(int var_id) const; /** Get value of variable by name. * Get value of a query variable for current result. + * + * @param name The variable name. + * @return The variable value. */ flecs::entity get_var(const char *name) const; @@ -24975,6 +27382,8 @@ struct iter { * not being progressed automatically. An example of a valid context is * inside of a run() callback. An example of an invalid context is inside of * an each() callback. + * + * @return True if there is more data to iterate, false if not. */ bool next() { if (iter_->flags & EcsIterIsValid && iter_->table) { @@ -24988,9 +27397,9 @@ struct iter { return result; } - /** Forward to each. - * If a system has an each callback registered, this operation will forward - * the current iterator to the each callback. + /** Forward to each(). + * If a system has an each() callback registered, this operation will forward + * the current iterator to the each() callback. */ void each() { iter_->callback(iter_); @@ -24999,14 +27408,14 @@ struct iter { /** Iterate targets for pair field. * * @param index The field index. - * @param func Callback invoked for each target + * @param func Callback invoked for each target. */ template void targets(int8_t index, const Func& func); /** Free iterator resources. * This operation only needs to be called when the iterator is not iterated - * until completion (e.g. the last call to next() did not return false). + * until completion (e.g., the last call to next() did not return false). * * Failing to call this operation on an unfinished iterator will throw a * fatal LEAK_DETECTED error. @@ -25021,7 +27430,7 @@ struct iter { } private: - /* Get field, check if correct type is used */ + /* Get field, check if correct type is used. */ template > flecs::field get_field(int8_t index) const { @@ -25035,13 +27444,13 @@ struct iter { size_t count; bool is_shared = !ecs_field_is_self(iter_, index); - /* If a shared column is retrieved with 'column', there will only be a + /* If a shared field is retrieved with field(), there will only be a * single value. Ensure that the application does not accidentally read * out of bounds. */ if (is_shared) { count = 1; } else { - /* If column is owned, there will be as many values as there are + /* If field is owned, there will be as many values as there are * entities. */ count = static_cast(iter_->count); } @@ -25051,7 +27460,7 @@ struct iter { count, is_shared); } - /* Get field, check if correct type is used */ + /* Get field, check if correct type is used. */ template > flecs::field get_field_at(int8_t index, int32_t row) const { @@ -25072,13 +27481,13 @@ struct iter { size_t size = ecs_field_size(iter_, index); bool is_shared = !ecs_field_is_self(iter_, index); - /* If a shared column is retrieved with 'column', there will only be a + /* If a shared field is retrieved with field(), there will only be a * single value. Ensure that the application does not accidentally read * out of bounds. */ if (is_shared) { count = 1; } else { - /* If column is owned, there will be as many values as there are + /* If field is owned, there will be as many values as there are * entities. */ count = static_cast(iter_->count); } @@ -25103,7 +27512,7 @@ struct iter { /** * @file addons/cpp/ref.hpp - * @brief Class that caches data to speedup get operations. + * @brief Class that caches data to speed up get operations. */ #pragma once @@ -25124,14 +27533,21 @@ namespace flecs */ struct untyped_ref { + /** Default constructor. Creates an empty reference. */ untyped_ref () : world_(nullptr), ref_{} {} + /** Construct a reference from a world, entity, and component ID. + * + * @param world The world. + * @param entity The entity. + * @param id The component ID. + */ untyped_ref(world_t *world, entity_t entity, flecs::id_t id) : ref_() { ecs_assert(id != 0, ECS_INVALID_PARAMETER, "invalid id"); - // the world we were called with may be a stage; convert it to a world - // here if that is the case + // The world we were called with may be a stage; convert it to a world + // here if that is the case. world_ = world ? const_cast(ecs_get_world(world)) : nullptr; @@ -25144,34 +27560,46 @@ struct untyped_ref { ref_ = ecs_ref_init_id(world_, entity, id); } + /** Construct a reference from an entity and component ID. + * + * @param entity The entity. + * @param id The component ID. + */ untyped_ref(flecs::entity entity, flecs::id_t id); - /** Return entity associated with reference. */ + /** Return the entity associated with the reference. */ flecs::entity entity() const; - /** Return component associated with reference. */ + /** Return the component associated with the reference. */ flecs::id component() const { return flecs::id(world_, ref_.id); } + /** Get a pointer to the component value. */ void* get() { return ecs_ref_get_id(world_, &ref_, this->ref_.id); } + /** Check if the reference has a valid component value. */ bool has() { return !!try_get(); } + /** Get the world associated with the reference. */ flecs::world world() const { return flecs::world(world_); } - /** implicit conversion to bool. return true if there is a valid - * component instance being referred to **/ + /** Implicit conversion to bool. + * Return true if there is a valid component instance being referred to. + */ operator bool() { return has(); } + /** Try to get a pointer to the component value. + * Return nullptr if the reference is invalid. + */ void* try_get() { if (!world_ || !ref_.entity) { return nullptr; @@ -25190,14 +27618,27 @@ struct untyped_ref { */ template struct ref : public untyped_ref { + /** Default constructor. Creates an empty reference. */ ref() : untyped_ref() { } + /** Construct a reference from a world, entity, and optional component ID. + * + * @param world The world. + * @param entity The entity. + * @param id The component ID (defaults to type T's ID). + */ ref(world_t *world, entity_t entity, flecs::id_t id = 0) : untyped_ref(world, entity, id ? id : _::type::id(world)) { } + /** Construct a reference from an entity and optional component ID. + * + * @param entity The entity. + * @param id The component ID (defaults to type T's ID). + */ ref(flecs::entity entity, flecs::id_t id = 0); + /** Dereference operator. Return a pointer to the component value. */ T* operator->() { T* result = static_cast(get()); @@ -25207,10 +27648,14 @@ struct ref : public untyped_ref { return result; } + /** Get a typed pointer to the component value. */ T* get() { return static_cast(untyped_ref::get()); } + /** Try to get a typed pointer to the component value. + * Return nullptr if the reference is invalid. + */ T* try_get() { return static_cast(untyped_ref::try_get()); } @@ -25231,18 +27676,179 @@ struct ref : public untyped_ref { /** * @file addons/cpp/entity_view.hpp - * @brief Entity class with only readonly operations. + * @brief Entity class with only read-only operations. * - * This class provides readonly access to entities. Using this class to store + * This class provides read-only access to entities. Using this class to store * entities in components ensures valid handles, as this class will always store * the actual world vs. a stage. The constructors of this class will never * create a new entity. * - * To obtain a mutable handle to the entity, use the "mut" function. + * To obtain a mutable handle to the entity, use the mut() function. + */ + +#pragma once + +/** + * @file addons/cpp/entity_component_tuple.hpp + * @brief Utilities to fetch components as tuples from entities. */ #pragma once +/** + * @ingroup cpp_entities + * @{ + */ + +namespace flecs +{ + + /** Builds tuple types for a given number of component types. + * + * @tparam size The number of components. + * @tparam Args The component types. + */ + template + struct tuple_builder {}; + + /** Tuple of 2 elements. */ + template + struct tuple_2 { + T val1; /**< First element. */ + U val2; /**< Second element. */ + }; + + /** Tuple builder specialization for 2 elements. */ + template + struct tuple_builder<2, Args...> { + using type = tuple_2; /**< Reference tuple type. */ + using type_ptr = tuple_2; /**< Pointer tuple type. */ + using type_const = tuple_2; /**< Const reference tuple type. */ + using type_const_ptr = tuple_2; /**< Const pointer tuple type. */ + }; + + /** Tuple of 3 elements. */ + template + struct tuple_3 { + T val1; /**< First element. */ + U val2; /**< Second element. */ + V val3; /**< Third element. */ + }; + + /** Tuple builder specialization for 3 elements. */ + template + struct tuple_builder<3, Args...> { + using type = tuple_3; /**< Reference tuple type. */ + using type_ptr = tuple_3; /**< Pointer tuple type. */ + using type_const = tuple_3; /**< Const reference tuple type. */ + using type_const_ptr = tuple_3; /**< Const pointer tuple type. */ + }; + + /** Tuple of 4 elements. */ + template + struct tuple_4 { + T val1; /**< First element. */ + U val2; /**< Second element. */ + V val3; /**< Third element. */ + W val4; /**< Fourth element. */ + }; + + /** Tuple builder specialization for 4 elements. */ + template + struct tuple_builder<4, Args...> { + using type = tuple_4; /**< Reference tuple type. */ + using type_ptr = tuple_4; /**< Pointer tuple type. */ + using type_const = tuple_4; /**< Const reference tuple type. */ + using type_const_ptr = tuple_4; /**< Const pointer tuple type. */ + }; + + /** Tuple of 5 elements. */ + template + struct tuple_5 { + T val1; /**< First element. */ + U val2; /**< Second element. */ + V val3; /**< Third element. */ + W val4; /**< Fourth element. */ + X val5; /**< Fifth element. */ + }; + + /** Tuple builder specialization for 5 elements. */ + template + struct tuple_builder<5, Args...> { + using type = tuple_5; /**< Reference tuple type. */ + using type_ptr = tuple_5; /**< Pointer tuple type. */ + using type_const = tuple_5; /**< Const reference tuple type. */ + using type_const_ptr = tuple_5; /**< Const pointer tuple type. */ + }; + + /** Tuple of 6 elements. */ + template + struct tuple_6 { + T val1; /**< First element. */ + U val2; /**< Second element. */ + V val3; /**< Third element. */ + W val4; /**< Fourth element. */ + X val5; /**< Fifth element. */ + Y val6; /**< Sixth element. */ + }; + + /** Tuple builder specialization for 6 elements. */ + template + struct tuple_builder<6, Args...> { + using type = tuple_6; /**< Reference tuple type. */ + using type_ptr = tuple_6; /**< Pointer tuple type. */ + using type_const = tuple_6; /**< Const reference tuple type. */ + using type_const_ptr = tuple_6; /**< Const pointer tuple type. */ + }; + + /** Tuple of 7 elements. */ + template + struct tuple_7 { + T val1; /**< First element. */ + U val2; /**< Second element. */ + V val3; /**< Third element. */ + W val4; /**< Fourth element. */ + X val5; /**< Fifth element. */ + Y val6; /**< Sixth element. */ + Z val7; /**< Seventh element. */ + }; + + /** Tuple builder specialization for 7 elements. */ + template + struct tuple_builder<7, Args...> { + using type = tuple_7; /**< Reference tuple type. */ + using type_ptr = tuple_7; /**< Pointer tuple type. */ + using type_const = tuple_7; /**< Const reference tuple type. */ + using type_const_ptr = tuple_7; /**< Const pointer tuple type. */ + }; + + /** Tuple of 8 elements. */ + template + struct tuple_8 { + T val1; /**< First element. */ + U val2; /**< Second element. */ + V val3; /**< Third element. */ + W val4; /**< Fourth element. */ + X val5; /**< Fifth element. */ + Y val6; /**< Sixth element. */ + Z val7; /**< Seventh element. */ + A val8; /**< Eighth element. */ + }; + + /** Tuple builder specialization for 8 elements. */ + template + struct tuple_builder<8, Args...> { + using type = tuple_8; /**< Reference tuple type. */ + using type_ptr = tuple_8; /**< Pointer tuple type. */ + using type_const = tuple_8; /**< Const reference tuple type. */ + using type_const_ptr = tuple_8; /**< Const pointer tuple type. */ + }; + +} + +/** @} */ + + /** * @ingroup cpp_entities * @{ @@ -25258,15 +27864,16 @@ namespace flecs */ struct entity_view : public id { + /** Default constructor. Creates an empty entity view. */ entity_view() : flecs::id() { } - /** Wrap an existing entity id. + /** Wrap an existing entity ID. * * @param world The world in which the entity is created. - * @param id The entity id. + * @param id The entity ID. */ explicit entity_view(flecs::world_t *world, flecs::id_t id) - : flecs::id(world + : flecs::id(world ? const_cast(ecs_get_world(world)) : nullptr , id ) { } @@ -25275,8 +27882,8 @@ struct entity_view : public id { entity_view(entity_t id) : flecs::id( nullptr, id ) { } - /** Get entity id. - * @return The integer entity id. + /** Get entity ID. + * @return The integer entity ID. */ entity_t id() const { return id_; @@ -25284,8 +27891,8 @@ struct entity_view : public id { /** Check if entity is valid. * An entity is valid if: - * - its id is not 0 - * - the id contains a valid bit pattern for an entity + * - its ID is not 0 + * - the ID contains a valid bit pattern for an entity * - the entity is alive (see is_alive()) * * @return True if the entity is valid, false otherwise. @@ -25295,6 +27902,7 @@ struct entity_view : public id { return world_ && ecs_is_valid(world_, id_); } + /** Conversion to bool. Returns true if entity is valid. */ explicit operator bool() const { return is_valid(); } @@ -25326,14 +27934,19 @@ struct entity_view : public id { /** Return the entity path. * + * @param sep The separator used between path elements. + * @param init_sep The initial separator prepended to the path. * @return The hierarchical entity path. */ flecs::string path(const char *sep = "::", const char *init_sep = "::") const { return path_from(0, sep, init_sep); - } + } /** Return the entity path relative to a parent. * + * @param parent The parent entity to compute the path relative to. + * @param sep The separator used between path elements. + * @param init_sep The initial separator prepended to the path. * @return The relative hierarchical entity path. */ flecs::string path_from(flecs::entity_t parent, const char *sep = "::", const char *init_sep = "::") const { @@ -25341,8 +27954,11 @@ struct entity_view : public id { return flecs::string(path); } - /** Return the entity path relative to a parent. + /** Return the entity path relative to a typed parent. * + * @tparam Parent The parent type to compute the path relative to. + * @param sep The separator used between path elements. + * @param init_sep The initial separator prepended to the path. * @return The relative hierarchical entity path. */ template @@ -25350,6 +27966,10 @@ struct entity_view : public id { return path_from(_::type::id(world_), sep, init_sep); } + /** Check if entity is enabled (does not have the Disabled tag). + * + * @return True if the entity is enabled, false otherwise. + */ bool enabled() const { return !ecs_has_id(world_, id_, flecs::Disabled); } @@ -25362,39 +27982,41 @@ struct entity_view : public id { /** Get the entity's table. * - * @return Returns the entity's table. + * @return The entity's table. */ flecs::table table() const; /** Get table range for the entity. - * Returns a range with the entity's row as offset and count set to 1. If + * Return a range with the entity's row as offset and count set to 1. If * the entity is not stored in a table, the function returns a range with * count 0. * - * @return Returns the entity's table range. + * @return The entity's table range. */ flecs::table_range range() const; - /** Iterate (component) ids of an entity. + /** Iterate (component) IDs of an entity. * The function parameter must match the following signature: * * @code * void(*)(flecs::id id) * @endcode * - * @param func The function invoked for each id. + * @param func The function invoked for each ID. */ template void each(const Func& func) const; - /** Iterate matching pair ids of an entity. + /** Iterate matching pair IDs of an entity. * The function parameter must match the following signature: * * @code * void(*)(flecs::id id) * @endcode * - * @param func The function invoked for each id. + * @param first The first element of the pair to match. + * @param second The second element of the pair to match. + * @param func The function invoked for each ID. */ template void each(flecs::id_t first, flecs::id_t second, const Func& func) const; @@ -25427,7 +28049,7 @@ struct entity_view : public id { return each(_::type::id(world_), func); } - /** Iterate children for entity. + /** Iterate children for an entity. * The function parameter must match the following signature: * * @code @@ -25435,7 +28057,7 @@ struct entity_view : public id { * @endcode * * @param rel The relationship to follow. - * @param func The function invoked for each child. + * @param func The function invoked for each child. */ template void children(flecs::entity_t rel, Func&& func) const { @@ -25443,7 +28065,7 @@ struct entity_view : public id { * entities with (ChildOf, *) or (ChildOf, _) instead of querying for * the children of the wildcard entity. */ if (id_ == flecs::Wildcard || id_ == flecs::Any) { - /* This is correct, wildcard entities don't have children */ + /* This is correct, wildcard entities don't have children. */ return; } @@ -25455,7 +28077,7 @@ struct entity_view : public id { } } - /** Iterate children for entity. + /** Iterate children for an entity. * The function parameter must match the following signature: * * @code @@ -25463,23 +28085,23 @@ struct entity_view : public id { * @endcode * * @tparam Rel The relationship to follow. - * @param func The function invoked for each child. + * @param func The function invoked for each child. */ template void children(Func&& func) const { children(_::type::id(world_), FLECS_MOV(func)); } - /** Iterate children for entity. + /** Iterate children for an entity. * The function parameter must match the following signature: * * @code * void(*)(flecs::entity target) * @endcode - * + * * This operation follows the ChildOf relationship. * - * @param func The function invoked for each child. + * @param func The function invoked for each child. */ template void children(Func&& func) const { @@ -25524,9 +28146,10 @@ struct entity_view : public id { * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. + * @return Pointer to the pair component value, nullptr if not found. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value > = 0> const A* try_get() const { return this->try_get

(); @@ -25537,6 +28160,7 @@ struct entity_view : public id { * * @tparam First The first element of the pair. * @param second The second element of the pair. + * @return Pointer to the first element value, nullptr if not found. */ template::value> = 0> const First* try_get(Second second) const { @@ -25551,7 +28175,8 @@ struct entity_view : public id { * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @param constant the enum constant. + * @param constant The enum constant. + * @return Pointer to the first element value, nullptr if not found. */ template::value && !std::is_same::value > = 0> const First* try_get(Second constant) const { @@ -25572,22 +28197,36 @@ struct entity_view : public id { /** Get a pair (untyped). * This operation gets the value for a pair from the entity. If neither the - * first nor the second part of the pair are components, the operation + * first nor the second part of the pair is a component, the operation * will fail. * * @param first The first element of the pair. * @param second The second element of the pair. + * @return Pointer to the pair component value, nullptr if not found. */ const void* try_get(flecs::entity_t first, flecs::entity_t second) const { return ecs_get_id(world_, id_, ecs_pair(first, second)); } + /** Get multiple component values as a tuple of const pointers. + * + * @tparam Ts The component types (must be between 2 and 8). + * @return A tuple of const pointers to the component values. + */ + template + auto try_get_n() const { + flecs_static_assert(sizeof...(Ts) > 1, "try_get_n requires at least two components"); + flecs_static_assert(sizeof...(Ts) < 9, "try_get_n cannot fetch more than eight components"); + return typename tuple_builder::type_const_ptr {try_get()...}; + } + /** Get the second part for a pair. * This operation gets the value for a pair from the entity. The first * part of the pair should not be a component. * - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. * @param first The first part of the pair. + * @return Pointer to the second element value, nullptr if not found. */ template const Second* try_get_second(flecs::entity_t first) const { @@ -25607,7 +28246,8 @@ struct entity_view : public id { * part of the pair should not be a component. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. + * @return Pointer to the second element value, nullptr if not found. */ template const Second* try_get_second() const { @@ -25618,33 +28258,35 @@ struct entity_view : public id { /* get */ /** Get component value. - * + * * @tparam T The component to get. - * @return Ref to the component value, panics if the entity does not + * @return Reference to the component value, panics if the entity does not * have the component. */ template ::value > = 0> const T& get() const { const T *r = try_get(); ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get: entity does not have component (use try_get)"); + "invalid get: entity does not have component '%s' (use try_get)", + flecs::_::type_name()); return *r; } /** Get component value. * Overload for when T is not the same as the actual type, which happens * when using pair types. - * + * * @tparam T The component to get. - * @return Ref to the component value, panics if the entity does not + * @return Reference to the component value, panics if the entity does not * have the component. */ - template , + template , if_t< flecs::is_pair::value > = 0> const A& get() const { const A *r = try_get(); ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get: entity does not have component (use try_get)"); + "invalid get: entity does not have component '%s' (use try_get)", + flecs::_::type_name()); return *r; } @@ -25652,39 +28294,39 @@ struct entity_view : public id { * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. - * @return Ref to the component value, panics if the entity does not - * have the component. + * @tparam Second The second element of the pair. + * @return Reference to the pair value, panics if the entity does not + * have the pair. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value > = 0> const A& get() const { return this->get

(); } /** Get a pair. - * This operation gets the value for a pair from the entity. + * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. * @param second The second element of the pair. - * @return Ref to the component value, panics if the entity does not - * have the component. + * @return Reference to the first element value, panics if the entity does not + * have the pair. */ template::value> = 0> const First& get(Second second) const { const First *r = try_get(second); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get: entity does not have component (use try_get)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get: entity does not have pair (use try_get)"); return *r; } /** Get a pair. - * This operation gets the value for a pair from the entity. + * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @param constant the enum constant. - * @return Ref to the component value, panics if the entity does not - * have the component. + * @param constant The enum constant. + * @return Reference to the first element value, panics if the entity does not + * have the pair. */ template::value && !std::is_same::value > = 0> const First& get(Second constant) const { @@ -25708,18 +28350,18 @@ struct entity_view : public id { /** Get a pair (untyped). * This operation gets the value for a pair from the entity. If neither the - * first nor the second part of the pair are components, the operation + * first nor the second part of the pair is a component, the operation * will fail. * * @param first The first element of the pair. * @param second The second element of the pair. - * @return Pointer to the component value, panics if the entity does not - * have the component. + * @return Pointer to the pair value, panics if the entity does not + * have the pair. */ const void* get(flecs::entity_t first, flecs::entity_t second) const { const void *r = ecs_get_id(world_, id_, ecs_pair(first, second)); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get: entity does not have component (use try_get)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get: entity does not have pair (use try_get)"); return r; } @@ -25728,19 +28370,19 @@ struct entity_view : public id { * retrieve. The callback will only be invoked when the entity has all * the components. * - * This operation is faster than individually calling get for each component + * This operation is faster than individually calling get() for each component, * as it only obtains entity metadata once. - * - * While the callback is invoked the table in which the components are + * + * While the callback is invoked, the table in which the components are * stored is locked, which prevents mutations that could cause invalidation - * of the component references. Note that this is not an actual lock: - * invalid access causes a runtime panic and so it is still up to the + * of the component references. Note that this is not an actual lock: + * invalid access causes a runtime panic and so it is still up to the * application to ensure access is protected. - * + * * The component arguments must be references and can be either const or * non-const. When all arguments are const, the function will read-lock the - * table (see ecs_read_begin). If one or more arguments are non-const the - * function will write-lock the table (see ecs_write_begin). + * table (see ecs_read_begin()). If one or more arguments are non-const, the + * function will write-lock the table (see ecs_write_begin()). * * Example: * @@ -25760,18 +28402,32 @@ struct entity_view : public id { template ::value > = 0> bool get(const Func& func) const; + /** Get multiple component values as a tuple of const references. + * + * @tparam Ts The component types (must be between 2 and 8). + * @return A tuple of const references to the component values. + */ + template + auto get_n() const { + flecs_static_assert(sizeof...(Ts) > 1, "get_n requires at least two components"); + flecs_static_assert(sizeof...(Ts) < 9, "get_n cannot fetch more than eight components"); + return typename tuple_builder::type_const {get()...}; + } + /** Get the second part for a pair. * This operation gets the value for a pair from the entity. The first * part of the pair should not be a component. * - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. * @param first The first part of the pair. + * @return Reference to the second element value. Panics if the entity does + * not have the pair. */ template const Second& get_second(flecs::entity_t first) const { const Second *r = try_get_second(first); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get: entity does not have component (use try_get)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get_second: entity does not have pair (use try_get_second)"); return *r; } @@ -25780,13 +28436,15 @@ struct entity_view : public id { * part of the pair should not be a component. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. + * @return Reference to the second element value. Panics if the entity does + * not have the pair. */ template const Second& get_second() const { const Second *r = try_get(); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get: entity does not have component (use try_get)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get_second: entity does not have pair (use try_get_second)"); return *r; } @@ -25828,19 +28486,21 @@ struct entity_view : public id { * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. + * @return Pointer to the pair component value, nullptr if not found. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value > = 0> A* try_get_mut() const { return this->try_get_mut

(); } /** Get a mutable pair. - * This operation gets the value for a pair from the entity. + * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. * @param second The second element of the pair. + * @return Pointer to the first element value, nullptr if not found. */ template::value> = 0> First* try_get_mut(Second second) const { @@ -25852,16 +28512,17 @@ struct entity_view : public id { } /** Get a mutable pair. - * This operation gets the value for a pair from the entity. + * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @param constant the enum constant. + * @param constant The enum constant. + * @return Pointer to the first element value, nullptr if not found. */ template::value && !std::is_same::value > = 0> First* try_get_mut(Second constant) const { const auto& et = enum_type(this->world_); flecs::entity_t target = et.entity(constant); - return get_mut(target); + return try_get_mut(target); } /** Get mutable component value (untyped). @@ -25876,22 +28537,36 @@ struct entity_view : public id { /** Get a mutable pair (untyped). * This operation gets the value for a pair from the entity. If neither the - * first nor the second part of the pair are components, the operation + * first nor the second part of the pair is a component, the operation * will fail. * * @param first The first element of the pair. * @param second The second element of the pair. + * @return Pointer to the pair component value, nullptr if not found. */ void* try_get_mut(flecs::entity_t first, flecs::entity_t second) const { return ecs_get_mut_id(world_, id_, ecs_pair(first, second)); } + /** Get multiple mutable component values as a tuple of pointers. + * + * @tparam Ts The component types (must be between 2 and 8). + * @return A tuple of pointers to the mutable component values. + */ + template + auto try_get_mut_n() const { + flecs_static_assert(sizeof...(Ts) > 1, "try_get_mut_n requires at least two components"); + flecs_static_assert(sizeof...(Ts) < 9, "try_get_mut_n cannot fetch more than eight components"); + return typename tuple_builder::type_ptr {try_get_mut()...}; + } + /** Get the second part for a pair. * This operation gets the value for a pair from the entity. The first * part of the pair should not be a component. * - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. * @param first The first part of the pair. + * @return Pointer to the second element value, nullptr if not found. */ template Second* try_get_mut_second(flecs::entity_t first) const { @@ -25911,20 +28586,21 @@ struct entity_view : public id { * part of the pair should not be a component. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. + * @return Pointer to the second element value, nullptr if not found. */ template Second* try_get_mut_second() const { - return get_mut>(); + return try_get_mut>(); } /* get_mut */ /** Get mutable component value. - * + * * @tparam T The component to get. - * @return Pointer to the component value, nullptr if the entity does not + * @return Reference to the component value. Panics if the entity does not * have the component. */ template ::value > = 0> @@ -25938,12 +28614,12 @@ struct entity_view : public id { /** Get mutable component value. * Overload for when T is not the same as the actual type, which happens * when using pair types. - * + * * @tparam T The component to get. - * @return Pointer to the component value, nullptr if the entity does not + * @return Reference to the component value. Panics if the entity does not * have the component. */ - template , + template , if_t< flecs::is_pair::value > = 0> A& get_mut() const { A* r = try_get_mut(); @@ -25956,36 +28632,42 @@ struct entity_view : public id { * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. + * @return Reference to the pair component value. Panics if the entity does + * not have the pair. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value > = 0> A& get_mut() const { A* r = try_get_mut(); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get_mut: entity does not have component (use try_get_mut)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get_mut: entity does not have pair (use try_get_mut)"); return *r; } /** Get a mutable pair. - * This operation gets the value for a pair from the entity. + * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. * @param second The second element of the pair. + * @return Reference to the first element value. Panics if the entity does + * not have the pair. */ template::value> = 0> First& get_mut(Second second) const { First* r = try_get_mut(second); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get_mut: entity does not have component (use try_get_mut)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get_mut: entity does not have pair (use try_get_mut)"); return *r; } /** Get a mutable pair. - * This operation gets the value for a pair from the entity. + * This operation gets the value for a pair from the entity. * * @tparam First The first element of the pair. - * @param constant the enum constant. + * @param constant The enum constant. + * @return Reference to the first element value. Panics if the entity does + * not have the pair. */ template::value && !std::is_same::value > = 0> First& get_mut(Second constant) const { @@ -25995,45 +28677,61 @@ struct entity_view : public id { } /** Get mutable component value (untyped). - * + * * @param comp The component to get. - * @return Pointer to the component value, nullptr if the entity does not + * @return Pointer to the component value. Panics if the entity does not * have the component. */ void* get_mut(flecs::id_t comp) const { void *r = ecs_get_mut_id(world_, id_, comp); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, "invalid get_mut: entity does not have component (use try_get_mut)"); return r; } /** Get a mutable pair (untyped). * This operation gets the value for a pair from the entity. If neither the - * first nor the second part of the pair are components, the operation + * first nor the second part of the pair is a component, the operation * will fail. * * @param first The first element of the pair. * @param second The second element of the pair. + * @return Pointer to the pair component value. Panics if the entity does + * not have the pair. */ void* get_mut(flecs::entity_t first, flecs::entity_t second) const { void *r = ecs_get_mut_id(world_, id_, ecs_pair(first, second)); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get_mut: entity does not have component (use try_get_mut)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get_mut: entity does not have pair (use try_get_mut)"); return r; } + /** Get multiple mutable component values as a tuple of references. + * + * @tparam Ts The component types (must be between 2 and 8). + * @return A tuple of references to the mutable component values. + */ + template + auto get_mut_n() const { + flecs_static_assert(sizeof...(Ts) > 1, "get_mut_n requires at least two components"); + flecs_static_assert(sizeof...(Ts) < 9, "get_mut_n cannot fetch more than eight components"); + return typename tuple_builder::type {get_mut()...}; + } + /** Get the second part for a pair. * This operation gets the value for a pair from the entity. The first * part of the pair should not be a component. * - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. * @param first The first part of the pair. + * @return Reference to the second element value. Panics if the entity does + * not have the pair. */ template Second& get_mut_second(flecs::entity_t first) const { Second *r = try_get_mut_second(first); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get_mut: entity does not have component (use try_get_mut)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get_mut_second: entity does not have pair (use try_get_mut_second)"); return *r; } @@ -26042,17 +28740,23 @@ struct entity_view : public id { * part of the pair should not be a component. * * @tparam First The first element of the pair. - * @tparam Second the second element of a pair. + * @tparam Second The second element of the pair. + * @return Reference to the second element value. Panics if the entity does + * not have the pair. */ template - Second* get_mut_second() const { + Second& get_mut_second() const { Second *r = try_get_mut_second(); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get_mut: entity does not have component (use try_get_mut)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get_mut_second: entity does not have pair (use try_get_mut_second)"); return *r; } - /** Get enum constant for enum relationship. */ + /** Get enum constant for enum relationship. + * + * @tparam Enum The enum type. + * @return The enum constant value. + */ template Enum get_constant() const; @@ -26063,6 +28767,7 @@ struct entity_view : public id { * * @tparam First The first element of the pair. * @param index The index (0 for the first instance of the relationship). + * @return The target entity. */ template flecs::entity target(int32_t index = 0) const; @@ -26074,36 +28779,51 @@ struct entity_view : public id { * * @param first The first element of the pair for which to retrieve the target. * @param index The index (0 for the first instance of the relationship). + * @return The target entity. */ flecs::entity target(flecs::entity_t first, int32_t index = 0) const; - /** Get the target of a pair for a given relationship id. - * This operation returns the first entity that has the provided id by following - * the specified relationship. If the entity itself has the id then entity will - * be returned. If the id cannot be found on the entity or by following the + /** Get the target of a pair for a given relationship ID. + * This operation returns the first entity that has the provided component ID + * by following the specified relationship. If the entity itself has the + * component ID, then the entity will be returned. If the component ID cannot + * be found on the entity or by following the * relationship, the operation will return 0. - * + * * This operation can be used to lookup, for example, which prefab is providing * a component by specifying the IsA pair: - * + * * @code * // Is Position provided by the entity or one of its base entities? * ecs_get_target_for_id(world, entity, EcsIsA, ecs_id(Position)) * @endcode - * + * * @param relationship The relationship to follow. - * @param id The id to lookup. + * @param id The component ID to lookup. * @return The entity for which the target has been found. */ flecs::entity target_for(flecs::entity_t relationship, flecs::id_t id) const; + /** Get the target of a pair for a given relationship ID. + * + * @tparam T The component type to lookup. + * @param relationship The relationship to follow. + * @return The entity for which the target has been found. + */ template flecs::entity target_for(flecs::entity_t relationship) const; + /** Get the target of a pair for a given relationship ID. + * + * @tparam First The first element of the pair to lookup. + * @tparam Second The second element of the pair to lookup. + * @param relationship The relationship to follow. + * @return The entity for which the target has been found. + */ template flecs::entity target_for(flecs::entity_t relationship) const; - /** Get depth for given relationship. + /** Get the depth for a given relationship. * * @param rel The relationship. * @return The depth. @@ -26112,7 +28832,7 @@ struct entity_view : public id { return ecs_get_depth(world_, id_, rel); } - /** Get depth for given relationship. + /** Get the depth for a given relationship. * * @tparam Rel The relationship. * @return The depth. @@ -26188,7 +28908,7 @@ struct entity_view : public id { * * @tparam First The first element of the pair. * @tparam Second The second element of the pair. - * @return True if the entity has the provided component, false otherwise. + * @return True if the entity has the provided pair, false otherwise. */ template bool has() const { @@ -26199,7 +28919,7 @@ struct entity_view : public id { * * @tparam First The first element of the pair. * @param second The second element of the pair. - * @return True if the entity has the provided component, false otherwise. + * @return True if the entity has the provided pair, false otherwise. */ template::value > = 0> bool has(Second second) const { @@ -26211,7 +28931,7 @@ struct entity_view : public id { * * @tparam Second The second element of the pair. * @param first The first element of the pair. - * @return True if the entity has the provided component, false otherwise. + * @return True if the entity has the provided pair, false otherwise. */ template bool has_second(flecs::entity_t first) const { @@ -26222,7 +28942,7 @@ struct entity_view : public id { * * @tparam First The first element of the pair. * @param value The enum constant. - * @return True if the entity has the provided component, false otherwise. + * @return True if the entity has the provided pair, false otherwise. */ template::value && !std::is_same::value > = 0> bool has(E value) const { @@ -26235,7 +28955,7 @@ struct entity_view : public id { * * @param first The first element of the pair. * @param second The second element of the pair. - * @return True if the entity has the provided component, false otherwise. + * @return True if the entity has the provided pair, false otherwise. */ bool has(flecs::id_t first, flecs::id_t second) const { return ecs_has_id(world_, id_, ecs_pair(first, second)); @@ -26255,7 +28975,7 @@ struct entity_view : public id { * * @tparam First The first element of the pair. * @param second The second element of the pair. - * @return True if the entity owns the provided component, false otherwise. + * @return True if the entity owns the provided pair, false otherwise. */ template bool owns(flecs::id_t second) const { @@ -26267,14 +28987,14 @@ struct entity_view : public id { * * @param first The first element of the pair. * @param second The second element of the pair. - * @return True if the entity owns the provided component, false otherwise. + * @return True if the entity owns the provided pair, false otherwise. */ bool owns(flecs::id_t first, flecs::id_t second) const { return owns(ecs_pair(first, second)); } /** Check if entity owns the provided component. - * An component is owned if it is not shared from a base entity. + * A component is owned if it is not shared from a base entity. * * @tparam T The component to check. * @return True if the entity owns the provided component, false otherwise. @@ -26285,7 +29005,7 @@ struct entity_view : public id { } /** Check if entity owns the provided pair. - * An pair is owned if it is not shared from a base entity. + * A pair is owned if it is not shared from a base entity. * * @tparam First The first element of the pair. * @tparam Second The second element of the pair. @@ -26300,18 +29020,18 @@ struct entity_view : public id { /** Check if entity owns the provided pair. * - * @param first The first element of the pair. * @tparam Second The second element of the pair. - * @return True if the entity owns the provided component, false otherwise. + * @param first The first element of the pair. + * @return True if the entity owns the provided pair, false otherwise. */ template bool owns_second(flecs::entity_t first) const { return owns(first, _::type::id(world_)); } - /** Test if id is enabled. + /** Test if ID is enabled. * - * @param id The id to test. + * @param id The ID to test. * @return True if enabled, false if not. */ bool enabled(flecs::id_t id) const { @@ -26360,11 +29080,18 @@ struct entity_view : public id { return this->enabled(_::type::id(world_)); } + /** Clone an entity. + * Create a copy of the current entity with all of its components. + * + * @param clone_value If true, clone component values. If false, only clone the entity's type. + * @param dst_id If nonzero, clone to this entity ID instead of creating a new one. + * @return The cloned entity. + */ flecs::entity clone(bool clone_value = true, flecs::entity_t dst_id = 0) const; - /** Return mutable entity handle for current stage + /** Return a mutable entity handle for the current stage. * When an entity handle created from the world is used while the world is - * in staged mode, it will only allow for readonly operations since + * in staged mode, it will only allow for read-only operations since * structural changes are not allowed on the world while in staged mode. * * To do mutations on the entity, this operation provides a handle to the @@ -26383,7 +29110,7 @@ struct entity_view : public id { */ flecs::entity mut(const flecs::world& stage) const; - /** Same as mut(world), but for iterator. + /** Same as mut(world), but for an iterator. * This operation allows for the construction of a mutable entity handle * from an iterator. * @@ -26392,7 +29119,7 @@ struct entity_view : public id { */ flecs::entity mut(const flecs::iter& it) const; - /** Same as mut(world), but for entity. + /** Same as mut(world), but for an entity. * This operation allows for the construction of a mutable entity handle * from another entity. This is useful in each() functions, which only * provide a handle to the entity being iterated over. @@ -26408,7 +29135,7 @@ struct entity_view : public id { * @brief JSON entity mixin. */ -/** Serialize entity to JSON. +/** Serialize an entity to JSON. * * @memberof flecs::entity_view * @ingroup cpp_addons_json @@ -26425,7 +29152,7 @@ flecs::string to_json(const flecs::entity_to_json_desc_t *desc = nullptr) const * @brief Doc entity view mixin. */ -/** Get human readable name. +/** Get human-readable name. * * @see ecs_doc_get_name() * @see flecs::doc::get_name() @@ -26510,7 +29237,7 @@ const char* doc_uuid() const { * @brief Alerts entity mixin. */ -/** Return number of alerts for entity. +/** Return the number of alerts for an entity. * * @memberof flecs::entity_view * @ingroup cpp_addons_alerts @@ -26526,7 +29253,7 @@ int32_t alert_count(flecs::entity_t alert = 0) const { * @brief Enum entity view mixin. */ -/** Convert entity to enum constant. +/** Convert an entity to an enum constant. * * @memberof flecs::entity_view * @ingroup cpp_entities @@ -26540,7 +29267,7 @@ E to_constant() const; * @brief Event entity mixin. */ -/** Emit event for entity. +/** Emit an event for an entity. * * @memberof flecs::entity_view * @@ -26553,7 +29280,7 @@ void emit(flecs::entity_t evt) const { .emit(); } -/** Emit event for entity. +/** Emit an event for an entity. * * @memberof flecs::entity_view * @@ -26561,7 +29288,7 @@ void emit(flecs::entity_t evt) const { */ void emit(flecs::entity evt) const; -/** Emit event for entity. +/** Emit an event for an entity. * * @memberof flecs::entity_view * @@ -26572,7 +29299,7 @@ void emit() const { this->emit(_::type::id(world_)); } -/** Emit event with payload for entity. +/** Emit an event with payload for an entity. * * @memberof flecs::entity_view * @@ -26588,7 +29315,7 @@ void emit(const Evt& payload) const { } -/** Enqueue event for entity. +/** Enqueue an event for an entity. * * @memberof flecs::entity_view * @@ -26601,7 +29328,7 @@ void enqueue(flecs::entity_t evt) const { .enqueue(); } -/** Enqueue event for entity. +/** Enqueue an event for an entity. * * @memberof flecs::entity_view * @@ -26609,7 +29336,7 @@ void enqueue(flecs::entity_t evt) const { */ void enqueue(flecs::entity evt) const; -/** Enqueue event for entity. +/** Enqueue an event for an entity. * * @memberof flecs::entity_view * @@ -26620,7 +29347,7 @@ void enqueue() const { this->enqueue(_::type::id(world_)); } -/** Enqueue event with payload for entity. +/** Enqueue an event with payload for an entity. * * @memberof flecs::entity_view * @@ -26665,7 +29392,7 @@ struct entity_builder : entity_view { /** Add a component to an entity. * To ensure the component is initialized, it should have a constructor. * - * @tparam T the component type to add. + * @tparam T The component type to add. */ template const Self& add() const { @@ -26675,11 +29402,11 @@ struct entity_builder : entity_view { return to_base(); } - /** Add pair for enum constant. + /** Add a pair for an enum constant. * This operation will add a pair to the entity where the first element is * the enumeration type, and the second element the enumeration constant. * - * The operation may be used with regular (C style) enumerations as well as + * The operation may be used with regular (C-style) enumerations as well as * enum classes. * * @param value The enumeration value. @@ -26690,14 +29417,14 @@ struct entity_builder : entity_view { const auto& et = enum_type(this->world_); flecs::entity_t second = et.entity(value); - ecs_assert(second, ECS_INVALID_PARAMETER, "Component was not found in reflection data."); + ecs_assert(second, ECS_INVALID_PARAMETER, "Enum constant was not found in reflection data."); return this->add(first, second); } /** Add an entity to an entity. * Add an entity to the entity. This is typically used for tagging. * - * @param component The component to add. + * @param component The component or tag to add. */ const Self& add(id_t component) const { ecs_add_id(this->world_, this->id_, component); @@ -26718,8 +29445,8 @@ struct entity_builder : entity_view { /** Add a pair. * This operation adds a pair to the entity. * - * @tparam First The first element of the pair - * @tparam Second The second element of the pair + * @tparam First The first element of the pair. + * @tparam Second The second element of the pair. */ template const Self& add() const { @@ -26729,7 +29456,7 @@ struct entity_builder : entity_view { /** Add a pair. * This operation adds a pair to the entity. * - * @tparam First The first element of the pair + * @tparam First The first element of the pair. * @param second The second element of the pair. */ template::value > = 0> @@ -26740,11 +29467,11 @@ struct entity_builder : entity_view { } /** Add a pair. - * This operation adds a pair to the entity that consists out of a tag + * This operation adds a pair to the entity that consists of a tag * combined with an enum constant. * - * @tparam First The first element of the pair - * @param constant the enum constant. + * @tparam First The first element of the pair. + * @param constant The enum constant. */ template::value && !std::is_same::value > = 0> const Self& add(Second constant) const { @@ -26757,8 +29484,8 @@ struct entity_builder : entity_view { /** Add a pair. * This operation adds a pair to the entity. * - * @param first The first element of the pair - * @tparam Second The second element of the pair + * @param first The first element of the pair. + * @tparam Second The second element of the pair. */ template const Self& add_second(flecs::entity_t first) const { @@ -26819,7 +29546,7 @@ struct entity_builder : entity_view { /** Conditional add. * This operation adds if condition is true, removes if condition is false. * - * @tparam First The first element of the pair + * @tparam First The first element of the pair. * @param cond The condition to evaluate. * @param second The second element of the pair. */ @@ -26831,8 +29558,8 @@ struct entity_builder : entity_view { /** Conditional add. * This operation adds if condition is true, removes if condition is false. * - * @tparam First The first element of the pair - * @tparam Second The second element of the pair + * @tparam First The first element of the pair. + * @tparam Second The second element of the pair. * @param cond The condition to evaluate. */ template @@ -26862,7 +29589,7 @@ struct entity_builder : entity_view { /** Shortcut for `add(IsA, entity)`. * - * @tparam T the type associated with the entity. + * @tparam T The type associated with the entity. */ template const Self& is_a() const { @@ -26916,7 +29643,7 @@ struct entity_builder : entity_view { /** Shortcut for `add(ChildOf, entity)`. * - * @tparam T the type associated with the entity. + * @tparam T The type associated with the entity. */ template const Self& child_of() const { @@ -26925,7 +29652,7 @@ struct entity_builder : entity_view { /** Shortcut for `add(DependsOn, entity)`. * - * @tparam T the type associated with the entity. + * @tparam T The type associated with the entity. */ template const Self& depends_on() const { @@ -26934,7 +29661,7 @@ struct entity_builder : entity_view { /** Shortcut for `add(SlotOf, entity)`. * - * @tparam T the type associated with the entity. + * @tparam T The type associated with the entity. */ template const Self& slot_of() const { @@ -26943,7 +29670,7 @@ struct entity_builder : entity_view { /** Remove a component from an entity. * - * @tparam T the type of the component to remove. + * @tparam T The type of the component to remove. */ template const Self& remove() const { @@ -26971,11 +29698,11 @@ struct entity_builder : entity_view { return to_base(); } - /** Removes a pair. + /** Remove a pair. * This operation removes a pair from the entity. * - * @tparam First The first element of the pair - * @tparam Second The second element of the pair + * @tparam First The first element of the pair. + * @tparam Second The second element of the pair. */ template const Self& remove() const { @@ -26985,7 +29712,7 @@ struct entity_builder : entity_view { /** Remove a pair. * This operation removes the pair from the entity. * - * @tparam First The first element of the pair + * @tparam First The first element of the pair. * @param second The second element of the pair. */ template::value > = 0> @@ -26993,11 +29720,11 @@ struct entity_builder : entity_view { return this->remove(_::type::id(this->world_), second); } - /** Removes a pair. + /** Remove a pair. * This operation removes a pair from the entity. * - * @tparam Second The second element of the pair - * @param first The first element of the pair + * @tparam Second The second element of the pair. + * @param first The first element of the pair. */ template const Self& remove_second(flecs::entity_t first) const { @@ -27007,8 +29734,8 @@ struct entity_builder : entity_view { /** Remove a pair. * This operation removes the pair from the entity. * - * @tparam First The first element of the pair - * @param constant the enum constant. + * @tparam First The first element of the pair. + * @param constant The enum constant. */ template::value > = 0> const Self& remove(Second constant) const { @@ -27017,12 +29744,12 @@ struct entity_builder : entity_view { return this->remove(second); } - /** Mark id for auto-overriding. - * When an entity inherits from a base entity (using the `IsA` relationship) - * any ids marked for auto-overriding on the base will be overridden + /** Mark ID for auto-overriding. + * When an entity inherits from a base entity (using the `IsA` relationship), + * any IDs marked for auto-overriding on the base will be overridden * automatically by the entity. * - * @param id The id to mark for overriding. + * @param id The ID to mark for overriding. */ const Self& auto_override(flecs::id_t id) const { return this->add(ECS_AUTO_OVERRIDE | id); @@ -27084,7 +29811,7 @@ struct entity_builder : entity_view { /** Set component, mark component for auto-overriding. * @see auto_override(flecs::id_t) const * - * @tparam T The component to set and for which to add the OVERRIDE flag + * @tparam T The component to set and for which to add the OVERRIDE flag. * @param val The value to set. */ template @@ -27096,7 +29823,7 @@ struct entity_builder : entity_view { /** Set component, mark component for auto-overriding. * @see auto_override(flecs::id_t) const * - * @tparam T The component to set and for which to add the OVERRIDE flag + * @tparam T The component to set and for which to add the OVERRIDE flag. * @param val The value to set. */ template @@ -27105,7 +29832,7 @@ struct entity_builder : entity_view { return this->set(FLECS_FWD(val)); } - /** Set pair, mark component for auto-overriding. + /** Set pair, mark pair for auto-overriding. * @see auto_override(flecs::id_t) const * * @tparam First The first element of the pair. @@ -27118,7 +29845,7 @@ struct entity_builder : entity_view { return this->set(second, val); } - /** Set pair, mark component for auto-overriding. + /** Set pair, mark pair for auto-overriding. * @see auto_override(flecs::id_t) const * * @tparam First The first element of the pair. @@ -27131,29 +29858,29 @@ struct entity_builder : entity_view { return this->set(second, FLECS_FWD(val)); } - /** Set component, mark component for auto-overriding. + /** Set pair, mark pair for auto-overriding. * @see auto_override(flecs::id_t) const * * @tparam First The first element of the pair. * @tparam Second The second element of the pair. * @param val The value to set. */ - template , - typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> + template , + typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> const Self& set_auto_override(const A& val) const { this->auto_override(); return this->set(val); } - /** Set component, mark component for auto-overriding. + /** Set pair, mark pair for auto-overriding. * @see auto_override(flecs::id_t) const * * @tparam First The first element of the pair. * @tparam Second The second element of the pair. * @param val The value to set. */ - template , - typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> + template , + typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> const Self& set_auto_override(A&& val) const { this->auto_override(); return this->set(FLECS_FWD(val)); @@ -27214,11 +29941,11 @@ struct entity_builder : entity_view { return to_base(); } - /** Enable an id. + /** Enable an ID. * This sets the enabled bit for this component. If this is the first time * the component is enabled or disabled, the bitset is added. - * - * @param id The id to enable. + * + * @param id The ID to enable. * @param toggle True to enable, false to disable (default = true). * * @see ecs_enable_id() @@ -27270,11 +29997,11 @@ struct entity_builder : entity_view { return this->enable(_::type::id(world_)); } - /** Disable an id. - * This sets the enabled bit for this id. If this is the first time - * the id is enabled or disabled, the bitset is added. + /** Disable an ID. + * This sets the enabled bit for this ID. If this is the first time + * the ID is enabled or disabled, the bitset is added. * - * @param id The id to disable. + * @param id The ID to disable. * * @see ecs_enable_id() * @see enable(flecs::id_t) const @@ -27286,7 +30013,7 @@ struct entity_builder : entity_view { /** Disable a component. * @see disable(flecs::id_t) const * - * @tparam T The component to enable. + * @tparam T The component to disable. */ template const Self& disable() const { @@ -27341,8 +30068,8 @@ struct entity_builder : entity_view { } /** Set a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component it will be added. + * This operation sets the component value. If the entity did not yet have + * the component, it will be added. * * @tparam T The component. * @param value The value to set. @@ -27354,8 +30081,8 @@ struct entity_builder : entity_view { } /** Set a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component it will be added. + * This operation sets the component value. If the entity did not yet have + * the component, it will be added. * * @tparam T The component. * @param value The value to set. @@ -27367,13 +30094,13 @@ struct entity_builder : entity_view { } /** Set a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component it will be added. + * This operation sets the component value. If the entity did not yet have + * the component, it will be added. * * @tparam T The component. * @param value The value to set. */ - template, if_not_t< + template, if_not_t< is_actual::value > = 0> const Self& set(A&& value) const { flecs::set(this->world_, this->id_, FLECS_FWD(value)); @@ -27381,8 +30108,8 @@ struct entity_builder : entity_view { } /** Set a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component it will be added. + * This operation sets the component value. If the entity did not yet have + * the component, it will be added. * * @tparam T The component. * @param value The value to set. @@ -27399,10 +30126,10 @@ struct entity_builder : entity_view { * entity did not yet have the pair, it will be added. * * @tparam First The first element of the pair. - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param value The value to set. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> const Self& set(A&& value) const { flecs::set

(this->world_, this->id_, FLECS_FWD(value)); @@ -27414,10 +30141,10 @@ struct entity_builder : entity_view { * entity did not yet have the pair, it will be added. * * @tparam First The first element of the pair. - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param value The value to set. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> const Self& set(const A& value) const { flecs::set

(this->world_, this->id_, value); @@ -27475,7 +30202,7 @@ struct entity_builder : entity_view { * This operation sets the pair value, and uses Second as type. If the * entity did not yet have the pair, it will be added. * - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param first The first element of the pair. * @param value The value to set. */ @@ -27495,7 +30222,7 @@ struct entity_builder : entity_view { * This operation sets the pair value, and uses Second as type. If the * entity did not yet have the pair, it will be added. * - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param first The first element of the pair. * @param value The value to set. */ @@ -27516,7 +30243,7 @@ struct entity_builder : entity_view { * entity did not yet have the pair, it will be added. * * @tparam First The first element of the pair. - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param value The value to set. */ template @@ -27527,8 +30254,8 @@ struct entity_builder : entity_view { /** Assign a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component the operation will panic. + * This operation sets the component value. If the entity did not yet have + * the component, the operation will panic. * * @tparam T The component. * @param value The value to set. @@ -27540,8 +30267,8 @@ struct entity_builder : entity_view { } /** Assign a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component the operation will panic. + * This operation sets the component value. If the entity did not yet have + * the component, the operation will panic. * * @tparam T The component. * @param value The value to set. @@ -27553,13 +30280,13 @@ struct entity_builder : entity_view { } /** Assign a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component the operation will panic. + * This operation sets the component value. If the entity did not yet have + * the component, the operation will panic. * * @tparam T The component. * @param value The value to set. */ - template, if_not_t< + template, if_not_t< is_actual::value > = 0> const Self& assign(A&& value) const { flecs::assign(this->world_, this->id_, FLECS_FWD(value)); @@ -27567,8 +30294,8 @@ struct entity_builder : entity_view { } /** Assign a component for an entity. - * This operation sets the component value. If the entity did not yet have - * the component the operation will panic. + * This operation sets the component value. If the entity did not yet have + * the component, the operation will panic. * * @tparam T The component. * @param value The value to set. @@ -27582,13 +30309,13 @@ struct entity_builder : entity_view { /** Assign a pair for an entity. * This operation sets the pair value, and uses First as type. If the - * entity did not yet have the component the operation will panic. + * entity did not yet have the pair, the operation will panic. * * @tparam First The first element of the pair. - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param value The value to set. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> const Self& assign(A&& value) const { flecs::assign

(this->world_, this->id_, FLECS_FWD(value)); @@ -27597,13 +30324,13 @@ struct entity_builder : entity_view { /** Assign a pair for an entity. * This operation sets the pair value, and uses First as type. If the - * entity did not yet have the component the operation will panic. + * entity did not yet have the pair, the operation will panic. * * @tparam First The first element of the pair. - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param value The value to set. */ - template , + template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> const Self& assign(const A& value) const { flecs::assign

(this->world_, this->id_, value); @@ -27612,7 +30339,7 @@ struct entity_builder : entity_view { /** Assign a pair for an entity. * This operation sets the pair value, and uses First as type. If the - * entity did not yet have the component the operation will panic. + * entity did not yet have the pair, the operation will panic. * * @tparam First The first element of the pair. * @param second The second element of the pair. @@ -27621,14 +30348,14 @@ struct entity_builder : entity_view { template ::value > = 0> const Self& assign(Second second, const First& value) const { auto first = _::type::id(this->world_); - flecs::assign(this->world_, this->id_, value, + flecs::assign(this->world_, this->id_, value, ecs_pair(first, second)); return to_base(); } /** Assign a pair for an entity. * This operation sets the pair value, and uses First as type. If the - * entity did not yet have the component the operation will panic. + * entity did not yet have the pair, the operation will panic. * * @tparam First The first element of the pair. * @param second The second element of the pair. @@ -27637,14 +30364,14 @@ struct entity_builder : entity_view { template ::value > = 0> const Self& assign(Second second, First&& value) const { auto first = _::type::id(this->world_); - flecs::assign(this->world_, this->id_, FLECS_FWD(value), + flecs::assign(this->world_, this->id_, FLECS_FWD(value), ecs_pair(first, second)); return to_base(); } /** Assign a pair for an entity. * This operation sets the pair value, and uses First as type. If the - * entity did not yet have the component the operation will panic. + * entity did not yet have the pair, the operation will panic. * * @tparam First The first element of the pair. * @param constant The enum constant. @@ -27659,9 +30386,9 @@ struct entity_builder : entity_view { /** Assign a pair for an entity. * This operation sets the pair value, and uses Second as type. If the - * entity did not yet have the component the operation will panic. + * entity did not yet have the pair, the operation will panic. * - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param first The first element of the pair. * @param value The value to set. */ @@ -27679,9 +30406,9 @@ struct entity_builder : entity_view { /** Assign a pair for an entity. * This operation sets the pair value, and uses Second as type. If the - * entity did not yet have the component the operation will panic. + * entity did not yet have the pair, the operation will panic. * - * @tparam Second The second element of the pair + * @tparam Second The second element of the pair. * @param first The first element of the pair. * @param value The value to set. */ @@ -27709,12 +30436,12 @@ struct entity_builder : entity_view { * set. If the entity does not have all of the provided components, they * will be added. * - * This operation is faster than individually calling get for each component + * This operation is faster than individually calling ensure() for each component * as it only obtains entity metadata once. When this operation is called - * while deferred, its performance is equivalent to that of calling ensure + * while deferred, its performance is equivalent to that of calling ensure() * for each component separately. * - * The operation will invoke modified for each component after the callback + * The operation will invoke modified() for each component after the callback * has been invoked. * * @param func The callback to invoke. @@ -27722,12 +30449,12 @@ struct entity_builder : entity_view { template const Self& insert(const Func& func) const; - /** Emplace component. + /** Emplace a component. * Emplace constructs a component in the storage, which prevents calling the * destructor on the value passed into the function. * - * @tparam T the component to emplace - * @param args The arguments to pass to the constructor of T + * @tparam T The component to emplace. + * @param args The arguments to pass to the constructor of T. */ template> const Self& emplace(Args&&... args) const { @@ -27768,8 +30495,8 @@ struct entity_builder : entity_view { return to_base(); } - /** Entities created in function will have the current entity. - * This operation is thread safe. + /** Entities created in the function will have the current entity. + * This operation is thread-safe. * * @param func The function to call. */ @@ -27781,10 +30508,10 @@ struct entity_builder : entity_view { return to_base(); } - /** Entities created in function will have `(First, this)`. - * This operation is thread safe. + /** Entities created in the function will have `(First, this)`. + * This operation is thread-safe. * - * @tparam First The first element of the pair + * @tparam First The first element of the pair. * @param func The function to call. */ template @@ -27793,8 +30520,8 @@ struct entity_builder : entity_view { return to_base(); } - /** Entities created in function will have `(first, this)`. - * This operation is thread safe. + /** Entities created in the function will have `(first, this)`. + * This operation is thread-safe. * * @param first The first element of the pair. * @param func The function to call. @@ -27808,7 +30535,7 @@ struct entity_builder : entity_view { return to_base(); } - /** The function will be ran with the scope set to the current entity. */ + /** The function will be run with the scope set to the current entity. */ template const Self& scope(const Func& func) const { ecs_entity_t prev = ecs_set_scope(this->world_, this->id_); @@ -27817,20 +30544,18 @@ struct entity_builder : entity_view { return to_base(); } - /** Return world scoped to entity */ + /** Return a world scoped to the entity. */ scoped_world scope() const { return scoped_world(world_, id_); } - /* Set the entity name. - */ + /** Set the entity name. */ const Self& set_name(const char *name) const { ecs_set_name(this->world_, this->id_, name); return to_base(); } - /* Set entity alias. - */ + /** Set the entity alias. */ const Self& set_alias(const char *name) const { ecs_set_alias(this->world_, this->id_, name); return to_base(); @@ -27842,7 +30567,7 @@ struct entity_builder : entity_view { * @brief Doc entity builder mixin. */ -/** Set human readable name. +/** Set human-readable name. * This adds `(flecs.doc.Description, flecs.Name)` to the entity. * * @see ecs_doc_set_name() @@ -27941,13 +30666,13 @@ const Self& set_doc_uuid(const char *uuid) const { */ /** - * @memberof flecs::entity_view + * @memberof flecs::entity_builder * @ingroup cpp_addons_meta * * @{ */ -/** Make entity a unit */ +/** Make an entity a unit. */ const Self& unit( const char *symbol, flecs::entity_t prefix = 0, @@ -27969,7 +30694,7 @@ const Self& unit( return to_base(); } -/** Make entity a derived unit */ +/** Make an entity a derived unit. */ const Self& unit( flecs::entity_t prefix = 0, flecs::entity_t base = 0, @@ -27989,8 +30714,8 @@ const Self& unit( return to_base(); } -/** Make entity a derived unit */ -const Self& unit_prefix( +/** Make an entity a unit prefix. */ +const Self& unit_prefix( const char *symbol, int32_t factor = 0, int32_t power = 0) const @@ -28005,19 +30730,19 @@ const Self& unit_prefix( return to_base(); } -/** Add quantity to unit */ +/** Add a quantity to a unit. */ const Self& quantity(flecs::entity_t quantity) const { ecs_add_pair(this->world(), this->id(), flecs::Quantity, quantity); return to_base(); } -/** Make entity a unity prefix */ +/** Add a quantity to a unit. */ template const Self& quantity() const { return this->quantity(_::type::id(this->world())); } -/** Make entity a quantity */ +/** Make an entity a quantity. */ const Self& quantity() const { ecs_add_id(this->world(), this->id(), flecs::Quantity); return to_base(); @@ -28033,13 +30758,13 @@ const Self& quantity() const { * @brief JSON entity mixin. */ -/** Set component from JSON. - * +/** Set a component from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ const Self& set_json( - flecs::id_t e, + flecs::id_t e, const char *json, flecs::from_json_desc_t *desc = nullptr) const { @@ -28059,13 +30784,13 @@ const Self& set_json( return to_base(); } -/** Set pair from JSON. - * +/** Set a pair from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ const Self& set_json( - flecs::entity_t r, + flecs::entity_t r, flecs::entity_t t, const char *json, flecs::from_json_desc_t *desc = nullptr) const @@ -28073,21 +30798,21 @@ const Self& set_json( return set_json(ecs_pair(r, t), json, desc); } -/** Set component from JSON. - * +/** Set a component from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ template const Self& set_json( - const char *json, + const char *json, flecs::from_json_desc_t *desc = nullptr) const { return set_json(_::type::id(world_), json, desc); } -/** Set pair from JSON. - * +/** Set a pair from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ @@ -28102,8 +30827,8 @@ const Self& set_json( json, desc); } -/** Set pair from JSON. - * +/** Set a pair from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ @@ -28118,8 +30843,8 @@ const Self& set_json( json, desc); } -/** Set pair from JSON. - * +/** Set a pair from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ @@ -28141,41 +30866,40 @@ const Self& set_json_second( * @brief Event entity mixin. */ -/** Observe event on entity - * +/** Observe an event on an entity. + * * @memberof flecs::entity_builder - * - * @param evt The event id. + * + * @param evt The event ID. * @param callback The observer callback. - * @return Event builder. + * @return Reference to self. */ template const Self& observe(flecs::entity_t evt, Func&& callback) const; -/** Observe event on entity - * +/** Observe an event on an entity. + * * @memberof flecs::entity_builder - * + * * @tparam Evt The event type. * @param callback The observer callback. - * @return Event builder. + * @return Reference to self. */ template const Self& observe(Func&& callback) const; -/** Observe event on entity - * +/** Observe an event on an entity. + * The event type is deduced from the callback signature. + * * @memberof flecs::entity_builder * * @param callback The observer callback. - * @return Event builder. + * @return Reference to self. */ template const Self& observe(Func&& callback) const; - - protected: const Self& to_base() const { return *static_cast(this); @@ -28200,12 +30924,23 @@ namespace flecs * Class with read/write operations for entities. * * @ingroup cpp_entities -*/ + */ struct entity : entity_builder { + /** Default constructor. Creates an empty entity. */ entity() : entity_builder() { } - /** Create entity. + /** Wrap an existing entity ID. + * + * @param world The world in which the entity is created. + * @param id The entity ID. + */ + explicit entity(const flecs::world_t *world, flecs::entity_t id) { + world_ = const_cast(world); + id_ = id; + } + + /** Create a new entity. * * @param world The world in which to create the entity. */ @@ -28213,68 +30948,74 @@ struct entity : entity_builder : entity_builder() { world_ = world; - if (!ecs_get_scope(world_) && !ecs_get_with(world_)) { - id_ = ecs_new(world); - } else { - ecs_entity_desc_t desc = {}; - id_ = ecs_entity_init(world_, &desc); - } - } - - /** Wrap an existing entity id. - * - * @param world The world in which the entity is created. - * @param id The entity id. - */ - explicit entity(const flecs::world_t *world, flecs::entity_t id) { - world_ = const_cast(world); - id_ = id; + id_ = ecs_cpp_new(world, 0, nullptr, nullptr, nullptr); } /** Create a named entity. - * Named entities can be looked up with the lookup functions. Entity names - * may be scoped, where each element in the name is separated by "::". - * For example: "Foo::Bar". If parts of the hierarchy in the scoped name do - * not yet exist, they will be automatically created. * * @param world The world in which to create the entity. * @param name The entity name. + * @param sep String used to indicate scoping (Foo::Bar). + * @param root_sep String used to indicate name is fully scoped (::Foo::Bar). */ - explicit entity(world_t *world, const char *name) - : entity_builder() + explicit entity( + world_t *world, + const char *name, + const char *sep = "::", + const char *root_sep = "::") : entity_builder() { world_ = world; ecs_entity_desc_t desc = {}; desc.name = name; - desc.sep = "::"; - desc.root_sep = "::"; + desc.sep = sep; + desc.root_sep = root_sep; id_ = ecs_entity_init(world, &desc); } - /** Create a named entity. - * Named entities can be looked up with the lookup functions. Entity names - * may be scoped, where each element in the name is separated by sep. - * For example: "Foo.Bar". If parts of the hierarchy in the scoped name do - * not yet exist, they will be automatically created. + /** Create a named entity for a parent using ChildOf hierarchy storage. * * @param world The world in which to create the entity. + * @param parent The parent entity ID. * @param name The entity name. - * @param sep The separator to use for the scoped name. - * @param root_sep The separator to use for the root of the scoped name. - */ - explicit entity(world_t *world, const char *name, const char *sep, const char *root_sep) - : entity_builder() + * @param sep String used to indicate scoping (Foo::Bar). + * @param root_sep String used to indicate name is fully scoped (::Foo::Bar). + */ + explicit entity( + world_t *world, + flecs::entity_t parent, + const char *name, + const char *sep = "::", + const char *root_sep = "::") : entity_builder() { world_ = world; ecs_entity_desc_t desc = {}; desc.name = name; + desc.parent = parent; desc.sep = sep; desc.root_sep = root_sep; id_ = ecs_entity_init(world, &desc); } + /** Create a named entity for a parent using Parent hierarchy storage. + * The specified name cannot be a scoped identifier. For example: + * - OK: "Foo" + * - Not OK: "Foo::Bar" + * + * @param world The world in which to create the entity. + * @param parent The parent entity. + * @param name The entity name (optional). + */ + explicit entity( + world_t *world, + const flecs::Parent& parent, + const char *name = nullptr) : entity_builder() + { + world_ = world; + id_ = ecs_new_w_parent(world, parent.value, name); + } + /** Conversion from flecs::entity_t to flecs::entity. * * @param id The entity_t value to convert. @@ -28285,13 +31026,13 @@ struct entity : entity_builder #ifndef ensure /** Get mutable component value. - * This operation returns a mutable pointer to the component. If the entity + * This operation returns a mutable reference to the component. If the entity * did not yet have the component, it will be added. If a base entity had * the component, it will be overridden, and the value of the base component * will be copied to the entity before this function returns. * * @tparam T The component to get. - * @return Pointer to the component value. + * @return Reference to the component value. */ template T& ensure() const { @@ -28317,11 +31058,12 @@ struct entity : entity_builder return ecs_ensure_id(world_, id_, comp, static_cast(ti->size)); } - /** Get mutable pointer for a pair. + /** Get mutable reference for a pair. * This operation gets the value for a pair from the entity. * * @tparam First The first part of the pair. - * @tparam Second the second part of the pair. + * @tparam Second The second part of the pair. + * @return Reference to the pair component value. */ template , typename A = actual_type_t

, if_not_t< flecs::is_pair::value> = 0> @@ -28331,11 +31073,12 @@ struct entity : entity_builder _::type::id(world_)), sizeof(A))); } - /** Get mutable pointer for the first element of a pair. + /** Get mutable reference for the first element of a pair. * This operation gets the value for a pair from the entity. * * @tparam First The first part of the pair. * @param second The second element of the pair. + * @return Reference to the first element value. */ template First& ensure(entity_t second) const { @@ -28353,16 +31096,18 @@ struct entity : entity_builder * * @param first The first element of the pair. * @param second The second element of the pair. + * @return Pointer to the pair component value. */ void* ensure(entity_t first, entity_t second) const { return ensure(ecs_pair(first, second)); } - /** Get mutable pointer for the second element of a pair. + /** Get mutable reference for the second element of a pair. * This operation gets the value for a pair from the entity. * * @tparam Second The second element of the pair. * @param first The first element of the pair. + * @return Reference to the second element value. */ template Second& ensure_second(entity_t first) const { @@ -28381,7 +31126,7 @@ struct entity : entity_builder /** Signal that component was modified. * - * @tparam T component that was modified. + * @tparam T The component that was modified. */ template void modified() const { @@ -28394,7 +31139,7 @@ struct entity : entity_builder /** Signal that the first element of a pair was modified. * * @tparam First The first part of the pair. - * @tparam Second the second part of the pair. + * @tparam Second The second part of the pair. */ template >> void modified() const { @@ -28418,9 +31163,9 @@ struct entity : entity_builder this->modified(first, second); } - /** Signal that a pair has modified (untyped). - * If neither the first or second element of the pair are a component, the - * operation will fail. + /** Signal that a pair has been modified (untyped). + * If neither the first nor the second element of the pair is a component, + * the operation will fail. * * @param first The first element of the pair. * @param second The second element of the pair. @@ -28431,41 +31176,42 @@ struct entity : entity_builder /** Signal that component was modified. * - * @param comp component that was modified. + * @param comp The component that was modified. */ void modified(entity_t comp) const { ecs_modified_id(world_, id_, comp); } - /** Get reference to component specified by id. + /** Get reference to component specified by component ID. * A reference allows for quick and safe access to a component value, and is - * a faster alternative to repeatedly calling 'get' for the same component. + * a faster alternative to repeatedly calling get() for the same component. * - * The method accepts a component id argument, which can be used to create a + * The method accepts a component ID argument, which can be used to create a * ref to a component that is different from the provided type. This allows * for creating a base type ref that points to a derived type: * * @code - * flecs::ref r = e.get_ref(world.id()); + * flecs::ref r = e.get_ref_w_id(world.id()); * @endcode * - * If the provided component id is not binary compatible with the specified + * If the provided component ID is not binary compatible with the specified * type, the behavior is undefined. * - * @tparam T component for which to get a reference. + * @tparam T Component for which to get a reference. + * @param component The component ID to reference. * @return The reference. */ template ::value > = 0> ref get_ref_w_id(flecs::id_t component) const { - _::type::id(world_); // ensure type is registered + _::type::id(world_); // Ensure type is registered. return ref(world_, id_, component); } /** Get reference to component. * A reference allows for quick and safe access to a component value, and is - * a faster alternative to repeatedly calling 'get' for the same component. + * a faster alternative to repeatedly calling get() for the same component. * - * @tparam T component for which to get a reference. + * @tparam T Component for which to get a reference. * @return The reference. */ template ::value > = 0> @@ -28477,9 +31223,9 @@ struct entity : entity_builder * Overload for when T is not the same as the actual type, which happens * when using pair types. * A reference allows for quick and safe access to a component value, and is - * a faster alternative to repeatedly calling 'get' for the same component. + * a faster alternative to repeatedly calling get() for the same component. * - * @tparam T component for which to get a reference. + * @tparam T Component for which to get a reference. * @return The reference. */ template , if_t< flecs::is_pair::value > = 0> @@ -28490,6 +31236,12 @@ struct entity : entity_builder } + /** Get reference to pair component. + * + * @tparam First The first element of the pair. + * @tparam Second The second element of the pair. + * @return The reference. + */ template , typename A = actual_type_t

> ref get_ref() const { @@ -28497,20 +31249,43 @@ struct entity : entity_builder ecs_pair(_::type::id(world_), _::type::id(world_))); } + /** Get reference to the first element of a pair. + * + * @tparam First The first element of the pair. + * @param second The second element of the pair. + * @return The reference. + */ template ref get_ref(flecs::entity_t second) const { auto first = _::type::id(world_); return ref(world_, id_, ecs_pair(first, second)); } + /** Get untyped reference to component by component ID. + * + * @param component The component ID. + * @return The untyped reference. + */ untyped_ref get_ref(flecs::id_t component) const { return untyped_ref(world_, id_, component); - } + } + /** Get untyped reference to pair by first and second entity IDs. + * + * @param first The first element of the pair. + * @param second The second element of the pair. + * @return The untyped reference. + */ untyped_ref get_ref(flecs::id_t first, flecs::id_t second) const { return untyped_ref(world_, id_, ecs_pair(first, second)); - } + } + /** Get reference to the second element of a pair. + * + * @tparam Second The second element of the pair. + * @param first The first element of the pair. + * @return The reference. + */ template ref get_ref_second(flecs::entity_t first) const { auto second = _::type::id(world_); @@ -28523,7 +31298,7 @@ struct entity : entity_builder /** Clear an entity. * This operation removes all components from an entity without recycling - * the entity id. + * the entity ID. * * @see ecs_clear() */ @@ -28541,13 +31316,24 @@ struct entity : entity_builder ecs_delete(world_, id_); } - /** Create child */ + /** Create a child entity with a specified relationship. + * + * @param r The relationship to use (defaults to ChildOf). + * @param args Additional arguments forwarded to entity creation. + * @return The created child entity. + */ template flecs::entity child(flecs::entity_t r = flecs::ChildOf, Args&&... args) { flecs::world world(world_); return world.entity(FLECS_FWD(args)...).add(r, id_); } + /** Create a child entity with a typed relationship. + * + * @tparam R The relationship type. + * @param args Additional arguments forwarded to entity creation. + * @return The created child entity. + */ template flecs::entity child(Args&&... args) { flecs::world world(world_); @@ -28555,33 +31341,39 @@ struct entity : entity_builder } /** Set child order. - * Changes the order of children as returned by entity::children(). Only - * applicableo to entities with the flecs::OrderedChildren trait. - * + * Changes the order of children as returned by entity::children(). Only + * applicable to entities with the flecs::OrderedChildren trait. + * + * @param children Array of child entity IDs in the desired order. + * @param child_count Number of children in the array. + * * @see ecs_set_child_order() */ void set_child_order(flecs::entity_t *children, int32_t child_count) const { ecs_set_child_order(world_, id_, children, child_count); } - /** Return entity as entity_view. - * This returns an entity_view instance for the entity which is a readonly + /** Return the entity as an entity_view. + * This returns an entity_view instance for the entity, which is a read-only * version of the entity class. * * This is similar to a regular upcast, except that this method ensures that * the entity_view instance is instantiated with a world vs. a stage, which * a regular upcast does not guarantee. + * + * @return The entity_view. */ flecs::entity_view view() const { return flecs::entity_view( const_cast(ecs_get_world(world_)), id_); } - /** Entity id 0. + /** Entity ID 0. * This function is useful when the API must provide an entity that - * belongs to a world, but the entity id is 0. + * belongs to a world, but the entity ID is 0. * * @param world The world. + * @return An entity with ID 0. */ static flecs::entity null(const flecs::world_t *world) { @@ -28590,14 +31382,22 @@ struct entity : entity_builder return result; } + /** Entity ID 0 without a world. + * + * @return An entity with ID 0 and no world. + */ static flecs::entity null() { return flecs::entity(); } # ifdef FLECS_JSON +/** + * @file addons/cpp/mixins/json/entity.inl + * @brief JSON entity mixin. + */ -/** Deserialize entity to JSON. +/** Deserialize an entity from JSON. * * @memberof flecs::entity * @ingroup cpp_addons_json @@ -28628,7 +31428,7 @@ namespace flecs namespace _ { -// Binding ctx for component hooks +// Binding ctx for component hooks. struct component_binding_ctx { void *on_add = nullptr; void *on_remove = nullptr; @@ -28655,7 +31455,7 @@ struct component_binding_ctx { } }; -// Utility to convert template argument pack to array of term ptrs +// Utility to convert a template argument pack to an array of term pointers. struct field_ptr { void *ptr = nullptr; int8_t index = 0; @@ -28668,77 +31468,66 @@ struct field_ptrs { using array = flecs::array<_::field_ptr, sizeof...(Components)>; void populate(const ecs_iter_t *iter) { - populate(iter, 0, static_cast< - remove_reference_t< - remove_pointer_t> - *>(nullptr)...); + populate_impl(iter, std::index_sequence_for{}); } void populate_self(const ecs_iter_t *iter) { - populate_self(iter, 0, static_cast< - remove_reference_t< - remove_pointer_t> - *>(nullptr)...); + populate_self_impl(iter, std::index_sequence_for{}); } array fields_; private: - void populate(const ecs_iter_t*, size_t) { } - - template >, - if_not_t< is_empty::value > = 0> - void populate(const ecs_iter_t *iter, size_t index, T, Targs... comps) { - if (iter->row_fields & (1llu << index)) { - /* Need to fetch the value with ecs_field_at() */ - fields_[index].is_row = true; - fields_[index].is_ref = true; - fields_[index].index = static_cast(index); - } else { - fields_[index].ptr = ecs_field_w_size(iter, sizeof(A), - static_cast(index)); - fields_[index].is_ref = iter->sources[index] != 0; + template + void populate_field(const ecs_iter_t *iter, size_t index) { + using A = remove_pointer_t>; + if constexpr (!is_empty_v) { + if (iter->row_fields & (1llu << index)) { + /* Need to fetch the value with ecs_field_at() */ + fields_[index].is_row = true; + fields_[index].is_ref = true; + fields_[index].index = static_cast(index); + } else { + fields_[index].ptr = ecs_field_w_size(iter, sizeof(A), + static_cast(index)); + fields_[index].is_ref = iter->sources[index] != 0; + } } - - populate(iter, index + 1, comps ...); } - template >, - if_t< is_empty::value > = 0> - void populate(const ecs_iter_t *iter, size_t index, T, Targs... comps) { - populate(iter, index + 1, comps ...); - } + template + void populate_self_field(const ecs_iter_t *iter, size_t index) { + (void)iter; (void)index; - void populate_self(const ecs_iter_t*, size_t) { } + using A = remove_pointer_t>; + if constexpr (!is_empty_v) { + fields_[index].ptr = ecs_field_w_size(iter, sizeof(A), + static_cast(index)); + fields_[index].is_ref = false; + } + } - template >, - if_not_t< is_empty::value > = 0> - void populate_self(const ecs_iter_t *iter, size_t index, T, Targs... comps) { - fields_[index].ptr = ecs_field_w_size(iter, sizeof(A), - static_cast(index)); - fields_[index].is_ref = false; - populate_self(iter, index + 1, comps ...); + template + void populate_impl(const ecs_iter_t *iter, std::index_sequence) { + (void)iter; + (populate_field(iter, Is), ...); } - template >, - if_t< is_empty::value > = 0> - void populate_self(const ecs_iter_t *iter, size_t index, T, Targs... comps) { - populate(iter, index + 1, comps ...); + template + void populate_self_impl(const ecs_iter_t *iter, std::index_sequence) { + (void)iter; + (populate_self_field(iter, Is), ...); } }; struct delegate { }; // Template that figures out from the template parameters of a query/system -// how to pass the value to the each callback +// how to pass the value to the each callback. template struct each_field { }; -// Base class +// Base class. struct each_column_base { each_column_base(const _::field_ptr& field, size_t row) : field_(field), row_(row) { @@ -28749,9 +31538,9 @@ struct each_column_base { size_t row_; }; -// If type is not a pointer, return a reference to the type (default case) +// If the type is not a pointer, return a reference to the type (default case). template -struct each_field::value && +struct each_field::value && !is_empty>::value && is_actual::value > > : each_column_base { @@ -28763,7 +31552,7 @@ struct each_field::value && } }; -// If argument type is not the same as actual component type, return by value. +// If the argument type is not the same as the actual component type, return by value. // This requires that the actual type can be converted to the type. // A typical scenario where this happens is when using flecs::pair types. template @@ -28779,7 +31568,7 @@ struct each_field::value && } }; -// If type is empty (indicating a tag) the query will pass a nullptr. To avoid +// If the type is empty (indicating a tag), the query will pass a nullptr. To avoid // returning nullptr to reference arguments, return a temporary value. template struct each_field>::value && @@ -28794,7 +31583,7 @@ struct each_field>::value && } }; -// If type is a pointer (indicating an optional value) don't index with row if +// If the type is a pointer (indicating an optional value), don't index with row if // the field is not set. template struct each_field::value && @@ -28808,7 +31597,7 @@ struct each_field::value && if (this->field_.ptr) { return &static_cast>(this->field_.ptr)[this->row_]; } else { - // optional argument doesn't have a value + // Optional argument doesn't have a value. return nullptr; } } @@ -28818,13 +31607,15 @@ struct each_field::value && // current argument is one. template struct each_ref_field : public each_field { + using A = remove_pointer_t>; + each_ref_field(const flecs::iter_t *iter, _::field_ptr& field, size_t row) : each_field(iter, field, row) { if (field.is_ref) { - // If this is a reference, set the row to 0 as a ref always is a + // If this is a reference, set the row to 0 as a ref is always a // single value, not an array. This prevents the application from - // having to do an if-check on whether the column is owned. + // having to do an if-check on whether the field is owned. // // This check only happens when the current table being iterated // over caused the query to match a reference. The check is @@ -28833,13 +31624,13 @@ struct each_ref_field : public each_field { } if (field.is_row) { - field.ptr = ecs_field_at_w_size(iter, sizeof(T), field.index, + field.ptr = ecs_field_at_w_size(iter, sizeof(A), field.index, static_cast(row)); } } }; -// Type that handles passing components to each callbacks +// Type that handles passing components to each callbacks. template struct each_delegate : public delegate { using Terms = typename field_ptrs::array; @@ -28868,14 +31659,14 @@ struct each_delegate : public delegate { } } - // Static function that can be used as callback for systems/triggers + // Static function that can be used as callback for systems/observers. static void run(ecs_iter_t *iter) { auto self = static_cast(iter->callback_ctx); ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL); self->invoke(iter); } - // Static function that can be used as callback for systems/triggers. + // Static function that can be used as callback for systems/observers. // Different from run() in that it loops the iterator. static void run_each(ecs_iter_t *iter) { auto self = static_cast(iter->run_ctx); @@ -28885,17 +31676,17 @@ struct each_delegate : public delegate { } } - // Create instance of delegate + // Create instance of delegate. static each_delegate* make(const Func& func) { return FLECS_NEW(each_delegate)(func); } - // Function that can be used as callback to free delegate + // Function that can be used as callback to free delegate. static void destruct(void *obj) { _::free_obj(obj); } - // Static function to call for component on_add hook + // Static function to call for component on_add hook. static void run_add(ecs_iter_t *iter) { component_binding_ctx *ctx = reinterpret_cast( iter->callback_ctx); @@ -28903,7 +31694,7 @@ struct each_delegate : public delegate { run(iter); } - // Static function to call for component on_remove hook + // Static function to call for component on_remove hook. static void run_remove(ecs_iter_t *iter) { component_binding_ctx *ctx = reinterpret_cast( iter->callback_ctx); @@ -28911,7 +31702,7 @@ struct each_delegate : public delegate { run(iter); } - // Static function to call for component on_set hook + // Static function to call for component on_set hook. static void run_set(ecs_iter_t *iter) { component_binding_ctx *ctx = reinterpret_cast( iter->callback_ctx); @@ -28919,7 +31710,7 @@ struct each_delegate : public delegate { run(iter); } - // Static function to call for component on_replace hook + // Static function to call for component on_replace hook. static void run_replace(ecs_iter_t *iter) { component_binding_ctx *ctx = reinterpret_cast( iter->callback_ctx); @@ -28984,8 +31775,8 @@ struct each_delegate : public delegate { size_t count = static_cast(iter->count); if (count == 0 && !iter->table) { - // If query has no This terms, count can be 0. Since each does not - // have an entity parameter, just pass through components + // If the query has no This terms, count can be 0. Since each does not + // have an entity parameter, just pass through components. count = 1; } @@ -29038,7 +31829,7 @@ struct find_delegate : public delegate { } private: - // Number of function arguments is one more than number of components, pass + // The number of function arguments is one more than the number of components, pass // entity as argument. template class ColumnType, typename... Args, @@ -29071,7 +31862,7 @@ struct find_delegate : public delegate { return result; } - // Number of function arguments is two more than number of components, pass + // The number of function arguments is two more than the number of components, pass // iter + index as argument. template class ColumnType, typename... Args, @@ -29086,8 +31877,8 @@ struct find_delegate : public delegate { { size_t count = static_cast(iter->count); if (count == 0) { - // If query has no This terms, count can be 0. Since each does not - // have an entity parameter, just pass through components + // If the query has no This terms, count can be 0. Since each does not + // have an entity parameter, just pass through components. count = 1; } @@ -29111,7 +31902,7 @@ struct find_delegate : public delegate { return result; } - // Number of function arguments is equal to number of components, no entity + // The number of function arguments is equal to the number of components, no entity. template class ColumnType, typename... Args, typename Fn = Func, @@ -29123,8 +31914,8 @@ struct find_delegate : public delegate { { size_t count = static_cast(iter->count); if (count == 0) { - // If query has no This terms, count can be 0. Since each does not - // have an entity parameter, just pass through components + // If the query has no This terms, count can be 0. Since each does not + // have an entity parameter, just pass through components. count = 1; } @@ -29182,7 +31973,7 @@ struct run_delegate : delegate { func_(it); } - // Static function that can be used as callback for systems/triggers + // Static function that can be used as callback for systems/observers. static void run(ecs_iter_t *iter) { auto self = static_cast(iter->run_ctx); ecs_assert(self != nullptr, ECS_INTERNAL_ERROR, NULL); @@ -29202,7 +31993,7 @@ struct entity_observer_delegate : delegate { explicit entity_observer_delegate(Func&& func) noexcept : func_(FLECS_MOV(func)) { } - // Static function that can be used as callback for systems/triggers + // Static function that can be used as callback for systems/observers. static void run(ecs_iter_t *iter) { invoke(iter); } @@ -29232,7 +32023,7 @@ struct entity_payload_observer_delegate : delegate { explicit entity_payload_observer_delegate(Func&& func) noexcept : func_(FLECS_MOV(func)) { } - // Static function that can be used as callback for systems/triggers + // Static function that can be used as callback for systems/observers. static void run(ecs_iter_t *iter) { invoke(iter); } @@ -29285,17 +32076,8 @@ struct entity_with_delegate_impl> { using DummyArray = flecs::array; using IdArray = flecs::array; - static bool const_args() { - static flecs::array is_const_args ({ - flecs::is_const>::value... - }); - - for (auto is_const : is_const_args) { - if (!is_const) { - return false; - } - } - return true; + static constexpr bool const_args() { + return (is_const_v> && ...); } static @@ -29304,24 +32086,24 @@ struct entity_with_delegate_impl> { { ecs_assert(table != NULL, ECS_INTERNAL_ERROR, NULL); - /* table_index_of needs real world */ + /* table_index_of needs the real world. */ const flecs::world_t *real_world = ecs_get_world(world); IdArray ids ({ _::type().id(world)... }); - /* Get column indices for components */ + /* Get column indices for components. */ ColumnArray columns ({ - ecs_table_get_column_index(real_world, table, + ecs_table_get_column_index(real_world, table, _::type().id(world))... }); - /* Get pointers for columns for entity */ + /* Get pointers for columns for the entity. */ size_t i = 0; for (int32_t column : columns) { if (column == -1) { - /* Component could be sparse */ + /* Component could be sparse. */ void *ptr = ecs_get_mut_id(world, e, ids[i]); if (!ptr) { return false; @@ -29338,7 +32120,7 @@ struct entity_with_delegate_impl> { } static bool ensure_ptrs(world_t *world, ecs_entity_t e, ArrayType& ptrs) { - /* Get pointers w/ensure */ + /* Get pointers w/ensure. */ size_t i = 0; DummyArray dummy ({ (ptrs[i ++] = ecs_ensure_id(world, e, @@ -29396,18 +32178,18 @@ struct entity_with_delegate_impl> { template static bool invoke_get(world_t *world, entity_t e, const Func& func) { - if (const_args()) { + if constexpr (const_args()) { return invoke_read(world, e, func); } else { return invoke_write(world, e, func); } } - // Utility for storing id in array in pack expansion + // Utility for storing an ID in an array in pack expansion. static size_t store_added(IdArray& added, size_t elem, ecs_table_t *prev, ecs_table_t *next, id_t id) { - // Array should only contain ids for components that are actually added, + // Array should only contain IDs for components that are actually added, // so check if the prev and next tables are different. if (prev != next) { added[elem] = id; @@ -29460,9 +32242,9 @@ struct entity_with_delegate_impl> { ArrayType ptrs; ecs_table_t *table = NULL; - // When not deferred take the fast path. + // When not deferred, take the fast path. if (!w.is_deferred()) { - // Bit of low level code so we only do at most one table move & one + // A bit of low-level code so we only do at most one table move and one // entity lookup for the entire operation. // Make sure the object is not a stage. Operations on a stage are @@ -29470,13 +32252,13 @@ struct entity_with_delegate_impl> { // the world is in readonly mode. ecs_assert(!w.is_stage(), ECS_INVALID_PARAMETER, NULL); - // Find table for entity + // Find the table for the entity. ecs_record_t *r = ecs_record_find(world, id); if (r) { table = r->table; } - // Iterate components, only store added component ids in added array + // Iterate components, only store added component IDs in the added array. InvokeCtx ctx(table); DummyArray dummy_before ({ ( invoke_add(w, id, w.id(), ctx) @@ -29484,7 +32266,7 @@ struct entity_with_delegate_impl> { (void)dummy_before; - // If table is different, move entity straight to it + // If the table is different, move the entity straight to it. if (table != ctx.table) { ecs_type_t ids; ids.array = ctx.added.ptr(); @@ -29499,7 +32281,7 @@ struct entity_with_delegate_impl> { ECS_TABLE_LOCK(world, table); - // When deferred, obtain pointers with regular ensure + // When deferred, obtain pointers with regular ensure. } else { ensure_ptrs(world, id, ptrs); } @@ -29510,7 +32292,7 @@ struct entity_with_delegate_impl> { ECS_TABLE_UNLOCK(world, table); } - // Call modified on each component + // Call modified on each component. DummyArray dummy_after ({ ( ecs_modified_id(world, id, w.id()), 0)... }); @@ -29552,7 +32334,12 @@ struct entity_with_delegate::value > > } // namespace _ -// Experimental: allows using the each delegate for use cases outside of flecs +/** Delegate type for each callbacks. + * Experimental: allows using the each delegate for use cases outside of Flecs. + * + * @tparam Func The callback function type. + * @tparam Args The component argument types. + */ template using delegate = _::each_delegate::type, Args...>; @@ -29577,105 +32364,94 @@ namespace flecs { namespace _ { -// Trick to obtain typename from type, as described here -// https://blog.molecular-matters.com/2015/12/11/getting-the-type-of-a-template-argument-as-string-without-rtti/ -// -// The code from the link has been modified to work with more types, and across -// multiple compilers. The resulting string should be the same on all platforms -// for all compilers. -// - -#if defined(__GNUC__) || defined(_WIN32) -template -inline const char* type_name() { - static const size_t len = ECS_FUNC_TYPE_LEN(const char*, type_name, ECS_FUNC_NAME); - static char result[len + 1] = {}; - static const size_t front_len = ECS_FUNC_NAME_FRONT(const char*, type_name); - static const char* cppTypeName = ecs_cpp_get_type_name(result, ECS_FUNC_NAME, len, front_len); - return cppTypeName; -} -#else -#error "implicit component registration not supported" -#endif - -// Translate a typename into a language-agnostic identifier. This allows for -// registration of components/modules across language boundaries. template -inline const char* symbol_name() { - static const size_t len = ECS_FUNC_TYPE_LEN(const char*, symbol_name, ECS_FUNC_NAME); - static char result[len + 1] = {}; - static const char* cppSymbolName = ecs_cpp_get_symbol_name(result, type_name(), len); - return cppSymbolName; +inline const char* component_symbol_name() { + return nullptr; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "u8"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "u16"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "u32"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "u64"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "i8"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "i16"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "i32"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "i64"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "f32"; } -template <> inline const char* symbol_name() { +template <> inline const char* component_symbol_name() { return "f64"; } -// If type is trivial, don't register lifecycle actions. While the functions -// that obtain the lifecycle callback do detect whether the callback is required +// If the type is trivial, don't register lifecycle actions. While the functions +// that obtain the lifecycle callback do detect whether the callback is required, // adding a special case for trivial types eases the burden a bit on the -// compiler as it reduces the number of templates to evaluate. -template::value == true - >* = nullptr> -void register_lifecycle_actions(ecs_world_t*, ecs_entity_t) { } - -// If the component is non-trivial, register component lifecycle actions. -// Depending on the type not all callbacks may be available. -template::value == false - >* = nullptr> +// compiler, as it reduces the number of templates to evaluate. +template void register_lifecycle_actions( ecs_world_t *world, ecs_entity_t component) { - ecs_type_hooks_t cl{}; - cl.ctor = ctor(cl.flags); - cl.dtor = dtor(cl.flags); - - cl.copy = copy(cl.flags); - cl.copy_ctor = copy_ctor(cl.flags); - cl.move = move(cl.flags); - cl.move_ctor = move_ctor(cl.flags); - - cl.ctor_move_dtor = ctor_move_dtor(cl.flags); - cl.move_dtor = move_dtor(cl.flags); + (void)world; (void)component; + if constexpr (!std::is_trivial::value) { + // If the component is non-trivial, register component lifecycle actions. + // Depending on the type, not all callbacks may be available. + ecs_type_hooks_t cl{}; + cl.ctor = ctor(cl.flags); + cl.dtor = dtor(cl.flags); + + cl.copy = copy(cl.flags); + cl.copy_ctor = copy_ctor(cl.flags); + cl.move = move(cl.flags); + cl.move_ctor = move_ctor(cl.flags); + + cl.ctor_move_dtor = ctor_move_dtor(cl.flags); + cl.move_dtor = move_dtor(cl.flags); + + cl.flags &= ECS_TYPE_HOOKS_ILLEGAL; + ecs_set_hooks_id(world, component, &cl); + + if (cl.flags & (ECS_TYPE_HOOK_MOVE_ILLEGAL|ECS_TYPE_HOOK_MOVE_CTOR_ILLEGAL)) + { + ecs_add_id(world, component, flecs::Sparse); + } + } +} - cl.flags &= ECS_TYPE_HOOKS_ILLEGAL; - ecs_set_hooks_id(world, component, &cl); +template +inline ecs_cpp_type_action_t lifecycle_action() { + if constexpr (std::is_trivial::value) { + return nullptr; + } else { + return ®ister_lifecycle_actions; + } +} - if (cl.flags & (ECS_TYPE_HOOK_MOVE_ILLEGAL|ECS_TYPE_HOOK_MOVE_CTOR_ILLEGAL)) - { - ecs_add_id(world, component, flecs::Sparse); +template +inline ecs_cpp_type_action_t enum_action() { +#if FLECS_CPP_ENUM_REFLECTION_SUPPORT + if constexpr (is_enum_v) { + return &_::init_enum; } +#endif + return nullptr; } template @@ -29683,12 +32459,12 @@ struct type_impl { static_assert(is_pointer::value == false, "pointer types are not allowed for components"); - // Initialize component identifier + // Initialize the component identifier. static void init( bool allow_tag = true) { - s_index = flecs_component_ids_index_get(); - s_allow_tag = allow_tag; + index(); // Make sure the global component index is initialized. + s_size = sizeof(T); s_alignment = alignof(T); if (is_empty::value && allow_tag) { @@ -29703,56 +32479,44 @@ struct type_impl { bool allow_tag = true) { init(allow_tag); - flecs_component_ids_set(world, s_index, id); + flecs_component_ids_set(world, index(), id); } - // Register component id. + // Register the component ID. static entity_t register_id( world_t *world, // The world - const char *name = nullptr, // User provided name (overrides typename) + const char *name = nullptr, // User-provided name (overrides typename) bool allow_tag = true, // Register empty types as zero-sized components - bool is_component = true, // Add flecs::Component to result + bool is_component = true, // Add flecs::Component to the result bool explicit_registration = false, // Entered from world.component()? - flecs::id_t id = 0) // User provided component id + flecs::id_t id = 0) // User-provided component ID { - if (!s_index) { - // This is the first time (in this binary image) that this type is - // being used. Generate a static index that will identify the type - // across worlds. - init(allow_tag); - ecs_assert(s_index != 0, ECS_INTERNAL_ERROR, NULL); - } - - bool registered = false, existing = false; - - flecs::entity_t c = ecs_cpp_component_register( - world, id, s_index, name, type_name(), - symbol_name(), size(), alignment(), - is_component, explicit_registration, ®istered, &existing); + init(allow_tag); + ecs_assert(index() != 0, ECS_INTERNAL_ERROR, NULL); + + ecs_cpp_component_desc_t desc = { + id, + index(), + name, + type_name(), + component_symbol_name(), + size(), + alignment(), + lifecycle_action(), + enum_action(), + is_component, + explicit_registration + }; + + flecs::entity_t c = ecs_cpp_component_register(world, &desc); ecs_assert(c != 0, ECS_INTERNAL_ERROR, NULL); - if (registered) { - // Register lifecycle callbacks, but only if the component has a - // size. Components that don't have a size are tags, and tags don't - // require construction/destruction/copy/move's. - if (size() && !existing) { - register_lifecycle_actions(world, c); - } - - // If component is enum type, register constants. Make sure to do - // this after setting the component id, because the enum code will - // be calling type::id(). - #if FLECS_CPP_ENUM_REFLECTION_SUPPORT - _::init_enum(world, c); - #endif - } - return c; } - // Get type (component) id. - // If type was not yet registered and automatic registration is allowed, + // Get the type (component) ID. + // If the type was not yet registered and automatic registration is allowed, // this function will also register the type. static entity_t id(world_t *world) { @@ -29761,13 +32525,13 @@ struct type_impl { "component '%s' must be registered before use", type_name()); - flecs::entity_t c = flecs_component_ids_get(world, s_index); + flecs::entity_t c = flecs_component_ids_get(world, index()); ecs_assert(c != 0, ECS_INTERNAL_ERROR, NULL); ecs_assert(ecs_is_alive(world, c), ECS_INVALID_OPERATION, "component '%s' was deleted, reregister before using", type_name()); #else - flecs::entity_t c = flecs_component_ids_get_alive(world, s_index); + flecs::entity_t c = flecs_component_ids_get_alive(world, index()); if (!c) { c = register_id(world); } @@ -29777,65 +32541,58 @@ struct type_impl { // Return the size of a component. static size_t size() { - ecs_assert(s_index != 0, ECS_INTERNAL_ERROR, NULL); return s_size; } // Return the alignment of a component. static size_t alignment() { - ecs_assert(s_index != 0, ECS_INTERNAL_ERROR, NULL); return s_alignment; } - // Was the component already registered. + // Was the component already registered? static bool registered(flecs::world_t *world) { ecs_assert(world != nullptr, ECS_INVALID_PARAMETER, NULL); - if (s_index == 0) { - return false; - } - - if (!flecs_component_ids_get(world, s_index)) { + if (!flecs_component_ids_get(world, index())) { return false; } return true; } - // This function is only used to test cross-translation unit features. No + // This function is only used to test cross-translation-unit features. No // code other than test cases should invoke this function. static void reset() { - s_index = 0; s_size = 0; s_alignment = 0; - s_allow_tag = true; } - static int32_t s_index; + static int32_t index() { + static int32_t index_ = flecs_component_ids_index_get(); + return index_; + } + static size_t s_size; static size_t s_alignment; - static bool s_allow_tag; }; -// Global templated variables that hold component identifier and other info -template int32_t type_impl::s_index; -template size_t type_impl::s_size; -template size_t type_impl::s_alignment; -template bool type_impl::s_allow_tag( true ); +// Global templated variables that hold the component identifier and other info. +template inline size_t type_impl::s_size; +template inline size_t type_impl::s_alignment; -// Front facing class for implicitly registering a component & obtaining -// static component data +// Front-facing class for implicitly registering a component and obtaining +// static component data. -// Regular type +// Regular type. template struct type::value >> : type_impl> { }; -// Pair type +// Pair type. template struct type::value >> { - // Override id method to return id of pair + // Override the id() method to return the ID of a pair. static id_t id(world_t *world = nullptr) { return ecs_pair( type< pair_first_t >::id(world), @@ -29852,11 +32609,28 @@ struct type::value >> */ struct untyped_component : entity { using entity::entity; - + + /** Default constructor. */ untyped_component() : entity() { } + + /** Construct from world and entity ID. + * + * @param world The world. + * @param id The component entity ID. + */ explicit untyped_component(flecs::world_t *world, flecs::entity_t id) : entity(world, id) { } + + /** Construct from entity ID. + * + * @param id The component entity ID. + */ explicit untyped_component(flecs::entity_t id) : entity(id) { } + /** Construct from world and name. + * + * @param world The world. + * @param name The component name. + */ explicit untyped_component(flecs::world_t *world, const char *name) { world_ = world; @@ -29869,6 +32643,13 @@ struct untyped_component : entity { id_ = ecs_entity_init(world, &desc); } + /** Construct from world, name, and scope separators. + * + * @param world The world. + * @param name The component name. + * @param sep The scope separator. + * @param root_sep The root scope separator. + */ explicit untyped_component(world_t *world, const char *name, const char *sep, const char *root_sep) { world_ = world; @@ -29883,24 +32664,37 @@ struct untyped_component : entity { protected: -flecs::type_hooks_t get_hooks() const { - const flecs::type_hooks_t* h = ecs_get_hooks_id(world_, id_); - if (h) { - return *h; - } else { - return {}; + /** Get the type hooks for this component. + * + * @return The type hooks, or empty hooks if none are set. + */ + flecs::type_hooks_t get_hooks() const { + const flecs::type_hooks_t* h = ecs_get_hooks_id(world_, id_); + if (h) { + return *h; + } else { + return {}; + } } -} -void set_hooks(flecs::type_hooks_t &h) { - h.flags &= ECS_TYPE_HOOKS_ILLEGAL; - ecs_set_hooks_id(world_, id_, &h); -} + /** Set the type hooks for this component. + * + * @param h The type hooks to set. + */ + void set_hooks(flecs::type_hooks_t &h) { + h.flags &= ECS_TYPE_HOOKS_ILLEGAL; + ecs_set_hooks_id(world_, id_, &h); + } public: +/** Register a custom compare hook for this component. + * + * @param compare_callback The comparison callback function. + * @return Reference to self for chaining. + */ untyped_component& on_compare( - ecs_cmp_t compare_callback) + ecs_cmp_t compare_callback) { ecs_assert(compare_callback, ECS_INVALID_PARAMETER, NULL); flecs::type_hooks_t h = get_hooks(); @@ -29914,8 +32708,13 @@ untyped_component& on_compare( return *this; } +/** Register a custom equals hook for this component. + * + * @param equals_callback The equality callback function. + * @return Reference to self for chaining. + */ untyped_component& on_equals( - ecs_equals_t equals_callback) + ecs_equals_t equals_callback) { ecs_assert(equals_callback, ECS_INVALID_PARAMETER, NULL); flecs::type_hooks_t h = get_hooks(); @@ -29940,7 +32739,7 @@ untyped_component& on_equals( private: -/** Private method that adds member to component. */ +/** Add a member to a component. */ untyped_component& internal_member( flecs::entity_t type_id, flecs::entity_t unit, @@ -29949,38 +32748,32 @@ untyped_component& internal_member( size_t offset = 0, bool use_offset = false) { - ecs_entity_desc_t desc = {}; - desc.name = name; - desc.parent = id_; - ecs_entity_t eid = ecs_entity_init(world_, &desc); - ecs_assert(eid != 0, ECS_INTERNAL_ERROR, NULL); - - flecs::entity e(world_, eid); - - Member m = {}; + ecs_member_t m = {}; + m.name = name; m.type = type_id; m.unit = unit; m.count = count; m.offset = static_cast(offset); m.use_offset = use_offset; - e.set(m); + + ecs_struct_add_member(world_, id_, &m); return *this; } public: -/** Add member with unit. */ +/** Add a member with unit. */ untyped_component& member( - flecs::entity_t type_id, - flecs::entity_t unit, - const char *name, + flecs::entity_t type_id, + flecs::entity_t unit, + const char *name, int32_t count = 0) { return internal_member(type_id, unit, name, count, 0, false); } -/** Add member with unit, count and offset. */ +/** Add a member with unit, count, and offset. */ untyped_component& member( flecs::entity_t type_id, flecs::entity_t unit, @@ -29991,16 +32784,16 @@ untyped_component& member( return internal_member(type_id, unit, name, count, offset, true); } -/** Add member. */ +/** Add a member. */ untyped_component& member( - flecs::entity_t type_id, + flecs::entity_t type_id, const char* name, int32_t count = 0) { return member(type_id, 0, name, count); } -/** Add member with count and offset. */ +/** Add a member with count and offset. */ untyped_component& member( flecs::entity_t type_id, const char* name, @@ -30010,7 +32803,7 @@ untyped_component& member( return member(type_id, 0, name, count, offset); } -/** Add member. */ +/** Add a member. */ template untyped_component& member( const char *name, @@ -30020,41 +32813,41 @@ untyped_component& member( return member(type_id, name, count); } -/** Add member. */ +/** Add a member. */ template untyped_component& member( const char *name, - int32_t count, + int32_t count, size_t offset) { flecs::entity_t type_id = _::type::id(world_); return member(type_id, name, count, offset); } -/** Add member with unit. */ +/** Add a member with unit. */ template untyped_component& member( flecs::entity_t unit, - const char *name, + const char *name, int32_t count = 0) { flecs::entity_t type_id = _::type::id(world_); return member(type_id, unit, name, count); } -/** Add member with unit. */ +/** Add a member with unit. */ template untyped_component& member( flecs::entity_t unit, - const char *name, - int32_t count, + const char *name, + int32_t count, size_t offset) { flecs::entity_t type_id = _::type::id(world_); return member(type_id, unit, name, count, offset); } -/** Add member with unit. */ +/** Add a member with unit. */ template untyped_component& member( const char *name, @@ -30065,11 +32858,11 @@ untyped_component& member( return member(type_id, unit_id, name, count); } -/** Add member with unit. */ +/** Add a member with unit. */ template untyped_component& member( - const char *name, - int32_t count, + const char *name, + int32_t count, size_t offset) { flecs::entity_t type_id = _::type::id(world_); @@ -30077,7 +32870,7 @@ untyped_component& member( return member(type_id, unit_id, name, count, offset); } -/** Add member using pointer-to-member. */ +/** Add a member using pointer-to-member. */ template ::type> untyped_component& member( @@ -30089,7 +32882,7 @@ untyped_component& member( return member(type_id, name, std::extent::value, offset); } -/** Add member with unit using pointer-to-member. */ +/** Add a member with unit using pointer-to-member. */ template ::type> untyped_component& member( @@ -30102,7 +32895,7 @@ untyped_component& member( return member(type_id, unit, name, std::extent::value, offset); } -/** Add member with unit using pointer-to-member. */ +/** Add a member with unit using pointer-to-member. */ template ::type> untyped_component& member( @@ -30115,7 +32908,7 @@ untyped_component& member( return member(type_id, unit_id, name, std::extent::value, offset); } -/** Add constant. */ +/** Add a constant. */ template untyped_component& constant( const char *name, @@ -30136,7 +32929,7 @@ untyped_component& constant( return *this; } -/** Add bitmask constant. */ +/** Add a bitmask constant. */ template untyped_component& bit( const char *name, @@ -30157,7 +32950,7 @@ untyped_component& bit( return *this; } -/** Register array metadata for component */ +/** Register array metadata for a component. */ template untyped_component& array( int32_t elem_count) @@ -30170,71 +32963,84 @@ untyped_component& array( return *this; } -/** Add member value range */ +/** Add a member value range. */ untyped_component& range( double min, double max) { - const flecs::member_t *m = ecs_cpp_last_member(world_, id_); + flecs::member_t *m = ecs_cpp_last_member(world_, id_); if (!m) { return *this; } - flecs::world w(world_); - flecs::entity me = w.entity(m->member); + m->range.min = min; + m->range.max = max; + + if (m->member) { + flecs::world w(world_); + flecs::entity me = w.entity(m->member); + flecs::MemberRanges *mr = static_cast( + ecs_ensure_id(w, me, w.id(), + sizeof(flecs::MemberRanges))); + mr->value.min = min; + mr->value.max = max; + me.modified(); + } - // Don't use C++ ensure because Unreal defines a macro called ensure - flecs::MemberRanges *mr = static_cast( - ecs_ensure_id(w, me, w.id(), - sizeof(flecs::MemberRanges))); - mr->value.min = min; - mr->value.max = max; - me.modified(); return *this; } -/** Add member warning range */ +/** Add a member warning range. */ untyped_component& warning_range( double min, double max) { - const flecs::member_t *m = ecs_cpp_last_member(world_, id_); + flecs::member_t *m = ecs_cpp_last_member(world_, id_); if (!m) { return *this; } - flecs::world w(world_); - flecs::entity me = w.entity(m->member); + m->warning_range.min = min; + m->warning_range.max = max; + + if (m->member) { + flecs::world w(world_); + flecs::entity me = w.entity(m->member); + flecs::MemberRanges *mr = static_cast( + ecs_ensure_id(w, me, w.id(), + sizeof(flecs::MemberRanges))); + mr->warning.min = min; + mr->warning.max = max; + me.modified(); + } - // Don't use C++ ensure because Unreal defines a macro called ensure - flecs::MemberRanges *mr = static_cast( - ecs_ensure_id(w, me, w.id(), - sizeof(flecs::MemberRanges))); - mr->warning.min = min; - mr->warning.max = max; - me.modified(); return *this; } -/** Add member error range */ +/** Add a member error range. */ untyped_component& error_range( double min, double max) { - const flecs::member_t *m = ecs_cpp_last_member(world_, id_); + flecs::member_t *m = ecs_cpp_last_member(world_, id_); if (!m) { return *this; } - flecs::world w(world_); - flecs::entity me = w.entity(m->member); + m->error_range.min = min; + m->error_range.max = max; + + if (m->member) { + flecs::world w(world_); + flecs::entity me = w.entity(m->member); + flecs::MemberRanges *mr = static_cast( + ecs_ensure_id(w, me, w.id(), + sizeof(flecs::MemberRanges))); + mr->error.min = min; + mr->error.max = max; + me.modified(); + } - // Don't use C++ ensure because Unreal defines a macro called ensure - flecs::MemberRanges *mr = static_cast(ecs_ensure_id( - w, me, w.id(), sizeof(flecs::MemberRanges))); - mr->error.min = min; - mr->error.max = max; - me.modified(); return *this; } @@ -30243,7 +33049,7 @@ untyped_component& error_range( # endif # ifdef FLECS_METRICS /** - * @file addons/cpp/mixins/meta/untyped_component.inl + * @file addons/cpp/mixins/metrics/untyped_component.inl * @brief Metrics component mixin. */ @@ -30254,16 +33060,16 @@ untyped_component& error_range( * @{ */ -/** Register member as metric. +/** Register a member as a metric. * When no explicit name is provided, this operation will derive the metric name * from the member name. When the member name is "value", the operation will use * the name of the component. * * When the brief parameter is provided, it is set on the metric as if - * set_doc_brief is used. The brief description can be obtained with - * get_doc_brief. + * set_doc_brief() is used. The brief description can be obtained with + * get_doc_brief(). * - * @tparam Kind Metric kind (Counter, CounterIncrement or Gauge). + * @tparam Kind Metric kind (Counter, CounterIncrement, or Gauge). * @param parent Parent entity of the metric (optional). * @param brief Description for metric (optional). * @param name Name of metric (optional). @@ -30293,7 +33099,7 @@ struct component : untyped_component { * @param world The world for which to register the component. * @param name Optional name (overrides typename). * @param allow_tag If true, empty types will be registered with size 0. - * @param id Optional id to register component with. + * @param id Optional component ID to register the component with. */ component( flecs::world_t *world, @@ -30305,7 +33111,11 @@ struct component : untyped_component { id_ = _::type::register_id(world, name, allow_tag, true, true, id); } - /** Register on_add hook. */ + /** Register on_add hook. + * + * @param func The callback function. + * @return Reference to self for chaining. + */ template component& on_add(Func&& func) { using Delegate = typename _::each_delegate::type, T>; @@ -30320,7 +33130,11 @@ struct component : untyped_component { return *this; } - /** Register on_remove hook. */ + /** Register on_remove hook. + * + * @param func The callback function. + * @return Reference to self for chaining. + */ template component& on_remove(Func&& func) { using Delegate = typename _::each_delegate< @@ -30336,7 +33150,11 @@ struct component : untyped_component { return *this; } - /** Register on_set hook. */ + /** Register on_set hook. + * + * @param func The callback function. + * @return Reference to self for chaining. + */ template component& on_set(Func&& func) { using Delegate = typename _::each_delegate< @@ -30352,14 +33170,18 @@ struct component : untyped_component { return *this; } - /** Register on_replace hook. */ + /** Register on_replace hook. + * + * @param func The callback function. + * @return Reference to self for chaining. + */ template component& on_replace(Func&& func) { using Delegate = typename _::each_delegate< typename std::decay::type, T, T>; flecs::type_hooks_t h = get_hooks(); - ecs_assert(h.on_set == nullptr, ECS_INVALID_OPERATION, - "on_set hook is already set"); + ecs_assert(h.on_replace == nullptr, ECS_INVALID_OPERATION, + "on_replace hook is already set"); BindingCtx *ctx = get_binding_ctx(h); h.on_replace = Delegate::run_replace; ctx->on_replace = FLECS_NEW(Delegate)(FLECS_FWD(func)); @@ -30368,8 +33190,12 @@ struct component : untyped_component { return *this; } - /** Register operator compare hook. */ using untyped_component::on_compare; + + /** Register an operator compare hook using type T's comparison operators. + * + * @return Reference to self for chaining. + */ component& on_compare() { ecs_cmp_t handler = _::compare(); ecs_assert(handler != NULL, ECS_INVALID_OPERATION, @@ -30378,15 +33204,24 @@ struct component : untyped_component { return *this; } - /** Type safe variant of compare op function */ using cmp_hook = int(*)(const T* a, const T* b, const ecs_type_info_t *ti); + + /** Type-safe variant of the compare op function. + * + * @param callback The comparison callback function. + * @return Reference to self for chaining. + */ component& on_compare(cmp_hook callback) { on_compare(reinterpret_cast(callback)); return *this; } - /** Register operator equals hook. */ using untyped_component::on_equals; + + /** Register an operator equals hook using type T's equality operator. + * + * @return Reference to self for chaining. + */ component& on_equals() { ecs_equals_t handler = _::equals(); ecs_assert(handler != NULL, ECS_INVALID_OPERATION, @@ -30395,16 +33230,25 @@ struct component : untyped_component { return *this; } - /** Type safe variant of equals op function */ using equals_hook = bool(*)(const T* a, const T* b, const ecs_type_info_t *ti); + + /** Type-safe variant of the equals op function. + * + * @param callback The equality callback function. + * @return Reference to self for chaining. + */ component& on_equals(equals_hook callback) { on_equals(reinterpret_cast(callback)); return *this; } # ifdef FLECS_META +/** + * @file addons/cpp/mixins/meta/component.inl + * @brief Meta component mixin. + */ -/** Register opaque type interface */ +/** Register an opaque type interface. */ template component& opaque(const Func& type_support) { flecs::world world(world_); @@ -30414,25 +33258,28 @@ component& opaque(const Func& type_support) { return *this; } +/** Return opaque type builder for a type, serialized as the given type. */ flecs::opaque opaque(flecs::entity_t as_type) { return flecs::opaque(world_).as_type(as_type); } +/** Return opaque type builder for a type, serialized as the given type. */ flecs::opaque opaque(flecs::entity as_type) { return this->opaque(as_type.id()); } +/** Return opaque type builder for a type, serialized as the given type. */ flecs::opaque opaque(flecs::untyped_component as_type) { return this->opaque(as_type.id()); } -/** Return opaque type builder for collection type */ +/** Return opaque type builder for a collection type. */ template flecs::opaque opaque(flecs::id_t as_type) { return flecs::opaque(world_).as_type(as_type); } -/** Add constant. */ +/** Add a constant. */ component& constant(const char *name, T value) { using U = typename std::underlying_type::type; @@ -30449,7 +33296,7 @@ component& constant(const char *name, T value) { *ptr = static_cast(value); ecs_modified_id(world_, eid, pair); - // If we're not using automatic enum reflection, manually set static data + // If we're not using automatic enum reflection, manually set static data. #ifdef FLECS_CPP_NO_ENUM_REFLECTION auto et = enum_type(world_); et.register_constant(world_, static_cast(value), eid); @@ -30480,7 +33327,7 @@ component& constant(const char *name, T value) { /** * @file addons/cpp/type.hpp - * @brief Utility functions for id vector. + * @brief Utility functions for ID vector. */ #pragma once @@ -30496,21 +33343,33 @@ namespace flecs { */ /** Type class. - * A type is a vector of component ids which can be requested from entities or tables. + * A type is a vector of component IDs that can be requested from entities or tables. */ struct type { + /** Default constructor. Creates an empty type. */ type() : world_(nullptr), type_(nullptr) { } + /** Construct a type from a world and C type pointer. + * + * @param world The world. + * @param t Pointer to the C type. + */ type(world_t *world, const type_t *t) : world_(world) , type_(t) { } - /** Convert type to comma-separated string */ + /** Convert the type to a comma-separated string. + * + * @return String representation of the type. + */ flecs::string str() const { return flecs::string(ecs_type_str(world_, type_)); } - /** Return number of ids in type */ + /** Return the number of IDs in the type. + * + * @return The number of IDs. + */ int32_t count() const { if (!type_) { return 0; @@ -30518,7 +33377,10 @@ struct type { return type_->count; } - /** Return pointer to array. */ + /** Return a pointer to the ID array. + * + * @return Pointer to the array of IDs, or nullptr if empty. + */ flecs::id_t* array() const { if (!type_) { return nullptr; @@ -30526,7 +33388,11 @@ struct type { return type_->array; } - /** Get id at specified index in type */ + /** Get the ID at a specified index in the type. + * + * @param index The index of the ID to get. + * @return The ID at the specified index. + */ flecs::id get(int32_t index) const { ecs_assert(type_ != NULL, ECS_INVALID_PARAMETER, NULL); ecs_assert(type_->count > index, ECS_OUT_OF_RANGE, NULL); @@ -30536,6 +33402,7 @@ struct type { return flecs::id(world_, type_->array[index]); } + /** Get an iterator to the beginning of the type's ID array. */ const flecs::id_t* begin() const { if (type_ && type_->count) { return type_->array; @@ -30544,6 +33411,7 @@ struct type { } } + /** Get an iterator to the end of the type's ID array. */ const flecs::id_t* end() const { if (type_ && type_->count) { return &type_->array[type_->count]; @@ -30552,7 +33420,7 @@ struct type { } } - /** Implicit conversion to type_t */ + /** Implicit conversion to type_t. */ operator const type_t*() const { return type_; } @@ -30562,7 +33430,7 @@ struct type { flecs::id_t empty_; }; -/** #} */ +/** @} */ } @@ -30583,151 +33451,169 @@ namespace flecs { * @{ */ +/** Table. + * A table stores entities with the same set of components. + * + * @ingroup cpp_tables + */ struct table { + /** Default constructor. */ table() : world_(nullptr), table_(nullptr) { } + /** Construct a table from a world and C table pointer. + * + * @param world The world. + * @param t Pointer to the C table. + */ table(world_t *world, table_t *t) : world_(world) , table_(t) { } + /** Destructor. */ virtual ~table() { } - /** Convert table type to string. */ + /** Convert the table type to a string. */ flecs::string str() const { return flecs::string(ecs_table_str(world_, table_)); } - /** Get table type. */ + /** Get the table type. */ flecs::type type() const { return flecs::type(world_, ecs_table_get_type(table_)); } - /** Get table count. */ + /** Get the table count. */ int32_t count() const { return ecs_table_count(table_); } - /** Get number of allocated elements in table. */ + /** Get the number of allocated elements in the table. */ int32_t size() const { return ecs_table_size(table_); } - /** Get array with entity ids. */ + /** Get the array of entity IDs. */ const flecs::entity_t* entities() const { return ecs_table_entities(table_); } - /** Delete entities in table. */ + /** Delete entities in the table. */ void clear_entities() const { ecs_table_clear_entities(world_, table_); } - /** Find type index for (component) id. + /** Find the type index for a (component) ID. * - * @param id The (component) id. - * @return The index of the id in the table type, -1 if not found/ + * @param id The (component) ID. + * @return The index of the ID in the table type, -1 if not found. */ int32_t type_index(flecs::id_t id) const { return ecs_table_get_type_index(world_, table_, id); } - /** Find type index for type. + /** Find the type index for a type. * * @tparam T The type. - * @return True if the table has the type, false if not. + * @return The index of the ID in the table type, -1 if not found. */ template int32_t type_index() const { return type_index(_::type::id(world_)); } - /** Find type index for pair. - * @param first First element of pair. - * @param second Second element of pair. - * @return True if the table has the pair, false if not. + /** Find the type index for a pair. + * + * @param first First element of the pair. + * @param second Second element of the pair. + * @return The index of the ID in the table type, -1 if not found. */ int32_t type_index(flecs::entity_t first, flecs::entity_t second) const { return type_index(ecs_pair(first, second)); } - /** Find type index for pair. - * @tparam First First element of pair. - * @param second Second element of pair. - * @return True if the table has the pair, false if not. + /** Find the type index for a pair. + * + * @tparam First First element of the pair. + * @param second Second element of the pair. + * @return The index of the ID in the table type, -1 if not found. */ template int32_t type_index(flecs::entity_t second) const { return type_index(_::type::id(world_), second); } - /** Find type index for pair. - * @tparam First First element of pair. - * @tparam Second Second element of pair. - * @return True if the table has the pair, false if not. + /** Find the type index for a pair. + * + * @tparam First First element of the pair. + * @tparam Second Second element of the pair. + * @return The index of the ID in the table type, -1 if not found. */ template int32_t type_index() const { return type_index(_::type::id(world_)); } - /** Find column index for (component) id. + /** Find the column index for a (component) ID. * - * @param id The (component) id. - * @return The index of the id in the table type, -1 if not found/ + * @param id The (component) ID. + * @return The column index of the ID in the table, -1 if not found. */ int32_t column_index(flecs::id_t id) const { return ecs_table_get_column_index(world_, table_, id); } - /** Find column index for type. + /** Find the column index for a type. * * @tparam T The type. - * @return True if the table has the type, false if not. + * @return The column index of the ID in the table type, -1 if not found. */ template int32_t column_index() const { return column_index(_::type::id(world_)); } - /** Find column index for pair. - * @param first First element of pair. - * @param second Second element of pair. - * @return True if the table has the pair, false if not. + /** Find the column index for a pair. + * + * @param first First element of the pair. + * @param second Second element of the pair. + * @return The column index of the ID in the table type, -1 if not found. */ int32_t column_index(flecs::entity_t first, flecs::entity_t second) const { return column_index(ecs_pair(first, second)); } - /** Find column index for pair. - * @tparam First First element of pair. - * @param second Second element of pair. - * @return True if the table has the pair, false if not. + /** Find the column index for a pair. + * + * @tparam First First element of the pair. + * @param second Second element of the pair. + * @return The column index of the ID in the table type, -1 if not found. */ template int32_t column_index(flecs::entity_t second) const { return column_index(_::type::id(world_), second); } - /** Find column index for pair. - * @tparam First First element of pair. - * @tparam Second Second element of pair. - * @return True if the table has the pair, false if not. + /** Find the column index for a pair. + * + * @tparam First First element of the pair. + * @tparam Second Second element of the pair. + * @return The column index of the ID in the table type, -1 if not found. */ template int32_t column_index() const { return column_index(_::type::id(world_)); } - /** Test if table has (component) id. + /** Test if the table has a (component) ID. * - * @param id The (component) id. - * @return True if the table has the id, false if not. + * @param id The (component) ID. + * @return True if the table has the ID, false if not. */ bool has(flecs::id_t id) const { return type_index(id) != -1; } - /** Test if table has the type. + /** Test if the table has the type. * * @tparam T The type. * @return True if the table has the type, false if not. @@ -30737,20 +33623,20 @@ struct table { return type_index() != -1; } - /** Test if table has the pair. + /** Test if the table has the pair. * - * @param first First element of pair. - * @param second Second element of pair. + * @param first First element of the pair. + * @param second Second element of the pair. * @return True if the table has the pair, false if not. */ bool has(flecs::entity_t first, flecs::entity_t second) const { return type_index(first, second) != -1; } - /** Test if table has the pair. + /** Test if the table has the pair. * - * @tparam First First element of pair. - * @param second Second element of pair. + * @tparam First First element of the pair. + * @param second Second element of the pair. * @return True if the table has the pair, false if not. */ template @@ -30758,10 +33644,10 @@ struct table { return type_index(second) != -1; } - /** Test if table has the pair. + /** Test if the table has the pair. * - * @tparam First First element of pair. - * @tparam Second Second element of pair. + * @tparam First First element of the pair. + * @tparam Second Second element of the pair. * @return True if the table has the pair, false if not. */ template @@ -30769,7 +33655,7 @@ struct table { return type_index() != -1; } - /** Get pointer to component array by column index. + /** Get a pointer to the component array by column index. * * @param index The column index. * @return Pointer to the column, NULL if not a component. @@ -30781,9 +33667,9 @@ struct table { /* get */ - /** Get pointer to component array by component. + /** Get a pointer to the component array by component. * - * @param id The component id. + * @param id The component ID. * @return Pointer to the column, NULL if not found. */ void* try_get(flecs::id_t id) const { @@ -30794,7 +33680,7 @@ struct table { return get_column(index); } - /** Get pointer to component array by pair. + /** Get a pointer to the component array by pair. * * @param first The first element of the pair. * @param second The second element of the pair. @@ -30804,7 +33690,7 @@ struct table { return try_get(ecs_pair(first, second)); } - /** Get pointer to component array by component. + /** Get a pointer to the component array by component. * * @tparam T The component. * @return Pointer to the column, NULL if not found. @@ -30814,7 +33700,7 @@ struct table { return static_cast(try_get(_::type::id(world_))); } - /** Get pointer to component array by component. + /** Get a pointer to the component array by component. * * @tparam T The component. * @return Pointer to the column, NULL if not found. @@ -30825,7 +33711,7 @@ struct table { return static_cast(try_get(_::type::id(world_))); } - /** Get pointer to component array by pair. + /** Get a pointer to the component array by pair. * * @tparam First The first element of the pair. * @param second The second element of the pair. @@ -30839,9 +33725,9 @@ struct table { /* get */ - /** Get pointer to component array by component. + /** Get a pointer to the component array by component. * - * @param id The component id. + * @param id The component ID. * @return Pointer to the column, NULL if not found. */ void* get(flecs::id_t id) const { @@ -30850,12 +33736,12 @@ struct table { return NULL; } void *r = get_column(index); - ecs_assert(r != nullptr, ECS_INVALID_OPERATION, - "invalid get_mut: table does not have component (use try_get)"); + ecs_assert(r != nullptr, ECS_INVALID_OPERATION, + "invalid get: table does not have component (use try_get())"); return r; } - /** Get pointer to component array by pair. + /** Get a pointer to the component array by pair. * * @param first The first element of the pair. * @param second The second element of the pair. @@ -30865,7 +33751,7 @@ struct table { return get(ecs_pair(first, second)); } - /** Get pointer to component array by component. + /** Get a pointer to the component array by component. * * @tparam T The component. * @return Pointer to the column, NULL if not found. @@ -30875,7 +33761,7 @@ struct table { return static_cast(get(_::type::id(world_))); } - /** Get pointer to component array by component. + /** Get a pointer to the component array by component. * * @tparam T The component. * @return Pointer to the column, NULL if not found. @@ -30886,7 +33772,7 @@ struct table { return static_cast(get(_::type::id(world_))); } - /** Get pointer to component array by pair. + /** Get a pointer to the component array by pair. * * @tparam First The first element of the pair. * @param second The second element of the pair. @@ -30898,7 +33784,7 @@ struct table { } - /** Get pointer to component array by pair. + /** Get a pointer to the component array by pair. * * @tparam First The first element of the pair. * @tparam Second The second element of the pair. @@ -30910,12 +33796,16 @@ struct table { return static_cast(get(_::type::id(world_))); } - /** Get column size. */ + /** Get the column size. + * + * @param index The column index. + * @return The size of the column's component type. + */ size_t column_size(int32_t index) const { return ecs_table_get_column_size(table_, index); } - /** Get depth for given relationship. + /** Get the depth for a given relationship. * * @param rel The relationship. * @return The depth. @@ -30924,7 +33814,7 @@ struct table { return ecs_table_get_depth(world_, table_, rel); } - /** Get depth for given relationship. + /** Get the depth for a given relationship. * * @tparam Rel The relationship. * @return The depth. @@ -30934,32 +33824,42 @@ struct table { return depth(_::type::id(world_)); } - /** Get table records array */ + /** Get the table records array. + * + * @return The table records. + */ ecs_table_records_t records() const { return flecs_table_records(table_); } - /** Get table id. */ + /** Get the table ID. + * + * @return The table ID. + */ uint64_t id() const { return flecs_table_id(table_); } - /** Lock table. */ + /** Lock the table. */ void lock() const { ecs_table_lock(world_, table_); } - /** Unlock table. */ + /** Unlock the table. */ void unlock() const { ecs_table_unlock(world_, table_); } - /** Check if table has flags. */ + /** Check if the table has flags. + * + * @param flags The flags to check for. + * @return True if the table has the specified flags. + */ bool has_flags(ecs_flags32_t flags) const { return ecs_table_has_flags(table_, flags); } - /** Get table. + /** Get the table. * * @return The table. */ @@ -30967,7 +33867,7 @@ struct table { return table_; } - /* Implicit conversion to table_t */ + /** Implicit conversion to table_t*. */ operator table_t*() const { return table_; } @@ -30977,26 +33877,41 @@ struct table { table_t *table_; }; +/** Table range. + * A table range represents a contiguous range of entities in a table. + * + * @ingroup cpp_tables + */ struct table_range : table { + /** Default constructor. */ table_range() : table() , offset_(0) , count_(0) { } + /** Construct a table range from a world, table, offset, and count. + * + * @param world The world. + * @param t Pointer to the C table. + * @param offset The starting row offset. + * @param count The number of rows in the range. + */ table_range(world_t *world, table_t *t, int32_t offset, int32_t count) : table(world, t) , offset_(offset) , count_(count) { } + /** Get the offset of the range. */ int32_t offset() const { return offset_; } + /** Get the number of entities in the range. */ int32_t count() const { return count_; } - /** Get pointer to component array by column index. + /** Get a pointer to the component array by column index. * * @param index The column index. * @return Pointer to the column, NULL if not a component. @@ -31021,15 +33936,19 @@ struct table_range : table { namespace flecs { +/** Forward declaration of iter_iterable. */ template struct iter_iterable; +/** Forward declaration of page_iterable. */ template struct page_iterable; +/** Forward declaration of worker_iterable. */ template struct worker_iterable; +/** Base class for iterable query objects. */ template struct iterable { @@ -31037,8 +33956,10 @@ struct iterable { * The "each" iterator accepts a function that is invoked for each matching * entity. The following function signatures are valid: * - func(flecs::entity e, Components& ...) - * - func(flecs::iter& it, size_t index, Components& ....) + * - func(flecs::iter& it, size_t index, Components& ...) * - func(Components& ...) + * + * @param func The callback function. */ template void each(Func&& func) const { @@ -31049,10 +33970,12 @@ struct iterable { } } - /** Run iterator. - * The "each" iterator accepts a function that is invoked once for a query + /** Run the iterator. + * The "run" callback accepts a function that is invoked once for a query * with a valid iterator. The following signature is valid: * - func(flecs::iter&) + * + * @param func The callback function. */ template void run(Func&& func) const { @@ -31060,6 +33983,12 @@ struct iterable { _::run_delegate(func).invoke(&it); } + /** Find the first entity matching a condition. + * Return the first entity for which the provided function returns true. + * + * @param func The predicate function. + * @return The first matching entity, or an empty entity if none found. + */ template flecs::entity find(Func&& func) const { ecs_iter_t it = this->get_iter(nullptr); @@ -31077,24 +34006,24 @@ struct iterable { return result; } - /** Create iterator. + /** Create an iterator. * Create an iterator object that can be modified before iterating. */ iter_iterable iter(flecs::world_t *world = nullptr) const; - /** Create iterator. + /** Create an iterator. * Create an iterator object that can be modified before iterating. */ iter_iterable iter(flecs::iter& iter) const; - /** Create iterator. + /** Create an iterator. * Create an iterator object that can be modified before iterating. */ iter_iterable iter(flecs::entity e) const; /** Page iterator. * Create an iterator that limits the returned entities with offset/limit. - * + * * @param offset How many entities to skip. * @param limit The maximum number of entities to return. * @return Iterable that can be iterated with each/iter. @@ -31104,59 +34033,65 @@ struct iterable { /** Worker iterator. * Create an iterator that divides the number of matched entities across * a number of resources. - * + * * @param index The index of the current resource. * @param count The total number of resources to divide entities between. * @return Iterable that can be iterated with each/iter. */ worker_iterable worker(int32_t index, int32_t count); - /** Return number of entities matched by iterable. */ + /** Return the number of entities matched by the iterable. */ int32_t count() const { return this->iter().count(); } - /** Return whether iterable has any matches. */ + /** Return whether the iterable has any matches. */ bool is_true() const { return this->iter().is_true(); } - /** Return first entity matched by iterable. */ + /** Return the first entity matched by the iterable. */ flecs::entity first() const { return this->iter().first(); } + /** Set query variable by ID. */ iter_iterable set_var(int var_id, flecs::entity_t value) const { return this->iter().set_var(var_id, value); } + /** Set query variable by name to an entity value. */ iter_iterable set_var(const char *name, flecs::entity_t value) const { return this->iter().set_var(name, value); } + /** Set query variable by name to a table value. */ iter_iterable set_var(const char *name, flecs::table_t *value) const { return this->iter().set_var(name, value); } + /** Set query variable by name to a table range (C type). */ iter_iterable set_var(const char *name, ecs_table_range_t value) const { return this->iter().set_var(name, value); } + /** Set query variable by name to a table range. */ iter_iterable set_var(const char *name, flecs::table_range value) const { return this->iter().set_var(name, value); } - // Limit results to tables with specified group id (grouped queries only) + /** Limit results to tables with the specified group ID (grouped queries only). */ iter_iterable set_group(uint64_t group_id) const { return this->iter().set_group(group_id); } - // Limit results to tables with specified group id (grouped queries only) + /** Limit results to tables with the specified group type (grouped queries only). */ template iter_iterable set_group() const { return this->iter().template set_group(); } + /** Virtual destructor. */ virtual ~iterable() { } protected: friend iter_iterable; @@ -31167,10 +34102,12 @@ struct iterable { virtual ecs_iter_next_action_t next_action() const = 0; }; +/** Iterable adapter for iterating with iter/each/run. */ template struct iter_iterable final : iterable { + /** Construct iter_iterable from an iterable and a world. */ template - iter_iterable(Iterable *it, flecs::world_t *world) + iter_iterable(Iterable *it, flecs::world_t *world) { it_ = it->get_iter(world); next_ = it->next_action(); @@ -31179,33 +34116,38 @@ struct iter_iterable final : iterable { ecs_assert(next_each_ != nullptr, ECS_INTERNAL_ERROR, NULL); } + /** Set query variable by ID. */ iter_iterable& set_var(int var_id, flecs::entity_t value) { ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, 0); ecs_iter_set_var(&it_, var_id, value); return *this; } + /** Set query variable by name to an entity value. */ iter_iterable& set_var(const char *name, flecs::entity_t value) { int var_id = ecs_query_find_var(it_.query, name); - ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, name); + ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, "%s", name); ecs_iter_set_var(&it_, var_id, value); return *this; } + /** Set query variable by name to a table value. */ iter_iterable& set_var(const char *name, flecs::table_t *value) { int var_id = ecs_query_find_var(it_.query, name); - ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, name); + ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, "%s", name); ecs_iter_set_var_as_table(&it_, var_id, value); return *this; } + /** Set query variable by name to a table range (C type). */ iter_iterable& set_var(const char *name, ecs_table_range_t value) { int var_id = ecs_query_find_var(it_.query, name); - ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, name); + ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, "%s", name); ecs_iter_set_var_as_range(&it_, var_id, &value); return *this; } + /** Set query variable by name to a table range. */ iter_iterable& set_var(const char *name, flecs::table_range value) { ecs_table_range_t range; range.table = value.get_table(); @@ -31220,7 +34162,7 @@ struct iter_iterable final : iterable { * @brief JSON iterable mixin. */ -/** Serialize iterator result to JSON. +/** Serialize an iterator result to JSON. * * @memberof flecs::iter * @ingroup cpp_addons_json @@ -31232,7 +34174,7 @@ flecs::string to_json(flecs::iter_to_json_desc_t *desc = nullptr) { # endif - // Return total number of entities in result. + /** Return the total number of entities in the result. */ int32_t count() { int32_t result = 0; while (next_each_(&it_)) { @@ -31241,7 +34183,7 @@ flecs::string to_json(flecs::iter_to_json_desc_t *desc = nullptr) { return result; } - // Returns true if iterator yields at least once result. + /** Return whether the iterator yields at least one result. */ bool is_true() { bool result = next_each_(&it_); if (result) { @@ -31250,7 +34192,7 @@ flecs::string to_json(flecs::iter_to_json_desc_t *desc = nullptr) { return result; } - // Return first matching entity. + /** Return the first matching entity. */ flecs::entity first() { flecs::entity result; if (next_each_(&it_) && it_.count) { @@ -31260,13 +34202,13 @@ flecs::string to_json(flecs::iter_to_json_desc_t *desc = nullptr) { return result; } - // Limit results to tables with specified group id (grouped queries only) + /** Limit results to tables with the specified group ID (grouped queries only). */ iter_iterable& set_group(uint64_t group_id) { ecs_iter_set_group(&it_, group_id); return *this; } - // Limit results to tables with specified group id (grouped queries only) + /** Limit results to tables with the specified group type (grouped queries only). */ template iter_iterable& set_group() { ecs_iter_set_group(&it_, _::type().id(it_.real_world)); @@ -31311,10 +34253,12 @@ iter_iterable iterable::iter(flecs::entity e) cons return iter_iterable(this, e.world()); } +/** Paged iterable adapter. Limits iteration to a range of entities. */ template struct page_iterable final : iterable { + /** Construct a page_iterable from an offset, limit, and source iterable. */ template - page_iterable(int32_t offset, int32_t limit, Iterable *it) + page_iterable(int32_t offset, int32_t limit, Iterable *it) : offset_(offset) , limit_(limit) { @@ -31338,24 +34282,26 @@ struct page_iterable final : iterable { template page_iterable iterable::page( - int32_t offset, - int32_t limit) + int32_t offset, + int32_t limit) { return page_iterable(offset, limit, this); } +/** Worker iterable adapter. Divides entities across workers. */ template struct worker_iterable final : iterable { - worker_iterable(int32_t offset, int32_t limit, iterable *it) - : offset_(offset) - , limit_(limit) + /** Construct a worker_iterable from an index, count, and source iterable. */ + worker_iterable(int32_t index, int32_t count, iterable *it) + : index_(index) + , count_(count) { chain_it_ = it->get_iter(nullptr); } protected: ecs_iter_t get_iter(flecs::world_t*) const { - return ecs_worker_iter(&chain_it_, offset_, limit_); + return ecs_worker_iter(&chain_it_, index_, count_); } ecs_iter_next_action_t next_action() const { @@ -31364,14 +34310,14 @@ struct worker_iterable final : iterable { private: ecs_iter_t chain_it_; - int32_t offset_; - int32_t limit_; + int32_t index_; + int32_t count_; }; template worker_iterable iterable::worker( - int32_t index, - int32_t count) + int32_t index, + int32_t count) { return worker_iterable(index, count, this); } @@ -31382,7 +34328,7 @@ worker_iterable iterable::worker( // Mixin implementations /** * @file addons/cpp/mixins/id/impl.hpp - * @brief Id class implementation. + * @brief ID class implementation. */ #pragma once @@ -31446,7 +34392,7 @@ inline flecs::entity id::type_id() const { } -// Id mixin implementation +// ID mixin implementation template inline flecs::id world::id() const { @@ -31563,19 +34509,19 @@ inline flecs::entity entity_view::parent() const { inline flecs::entity entity_view::mut(const flecs::world& stage) const { ecs_assert(!stage.is_readonly(), ECS_INVALID_PARAMETER, - "cannot use readonly world/stage to create mutable handle"); + "cannot use read-only world/stage to create mutable handle"); return flecs::entity(id_).set_stage(stage.c_ptr()); } inline flecs::entity entity_view::mut(const flecs::iter& it) const { ecs_assert(!it.world().is_readonly(), ECS_INVALID_PARAMETER, - "cannot use iterator created for readonly world/stage to create mutable handle"); + "cannot use iterator created for read-only world/stage to create mutable handle"); return flecs::entity(id_).set_stage(it.world().c_ptr()); } inline flecs::entity entity_view::mut(const flecs::entity_view& e) const { ecs_assert(!e.world().is_readonly(), ECS_INVALID_PARAMETER, - "cannot use entity created for readonly world/stage to create mutable handle"); + "cannot use entity created for read-only world/stage to create mutable handle"); return flecs::entity(id_).set_stage(e.world_); } @@ -31718,7 +34664,7 @@ inline flecs::entity world::prefab(const char *name) const { /** * @file addons/cpp/mixins/component/impl.hpp - * @brief Component mixin implementation + * @brief Component mixin implementation. */ #pragma once @@ -31753,7 +34699,7 @@ inline flecs::untyped_component world::component(Args &&... args) const { /** * @file addons/cpp/utils/signature.hpp - * @brief Compile time utilities for deriving query attributes from param pack. + * @brief Compile-time utilities for deriving query attributes from a parameter pack. */ #pragma once @@ -31821,36 +34767,38 @@ namespace flecs /** Term identifier builder. * A term identifier describes a single identifier in a term. Identifier - * descriptions can reference entities by id, name or by variable, which means + * descriptions can reference entities by ID, name, or by variable, which means * the entity will be resolved when the term is evaluated. * * @ingroup cpp_core_queries */ template struct term_ref_builder_i { + /** Default constructor. */ term_ref_builder_i() : term_ref_(nullptr) { } + /** Destructor. */ virtual ~term_ref_builder_i() { } - /* The self flag indicates the term identifier itself is used */ + /** The self flag indicates that the term identifier itself is used. */ Base& self() { this->assert_term_ref(); term_ref_->id |= flecs::Self; return *this; } - /* Specify value of identifier by id */ + /** Specify the value of the identifier by ID. */ Base& id(flecs::entity_t id) { this->assert_term_ref(); term_ref_->id = id; return *this; } - /* Specify value of identifier by id. Almost the same as id(entity), but this - * operation explicitly sets the flecs::IsEntity flag. This forces the id to - * be interpreted as entity, whereas not setting the flag would implicitly - * convert ids for builtin variables such as flecs::This to a variable. - * + /** Specify the value of the identifier by ID. Almost the same as id(entity_t), but this + * operation explicitly sets the flecs::IsEntity flag. This forces the ID to + * be interpreted as an entity, whereas not setting the flag would implicitly + * convert IDs for built-in variables such as flecs::This to a variable. + * * This function can also be used to disambiguate id(0), which would match * both id(entity_t) and id(const char*). */ @@ -31860,7 +34808,7 @@ struct term_ref_builder_i { return *this; } - /* Specify value of identifier by name */ + /** Specify the value of the identifier by name. */ Base& name(const char *name) { this->assert_term_ref(); term_ref_->id |= flecs::IsEntity; @@ -31868,7 +34816,7 @@ struct term_ref_builder_i { return *this; } - /* Specify identifier is a variable (resolved at query evaluation time) */ + /** Specify that the identifier is a variable (resolved at query evaluation time). */ Base& var(const char *var_name) { this->assert_term_ref(); term_ref_->id |= flecs::IsVariable; @@ -31876,13 +34824,14 @@ struct term_ref_builder_i { return *this; } - /* Override term id flags */ + /** Override the term ID flags. */ Base& flags(flecs::flags64_t flags) { this->assert_term_ref(); term_ref_->id = flags; return *this; } + /** Pointer to the current term reference. */ ecs_term_ref_t *term_ref_; protected: @@ -31906,25 +34855,28 @@ struct term_ref_builder_i { */ template struct term_builder_i : term_ref_builder_i { + /** Default constructor. */ term_builder_i() : term_(nullptr) { } - term_builder_i(ecs_term_t *term_ptr) { + /** Construct from a term pointer. */ + term_builder_i(ecs_term_t *term_ptr) { set_term(term_ptr); } + /** Set the term ID. */ Base& term(id_t id) { return this->id(id); } - /* Call prior to setting values for src identifier */ + /** Call prior to setting values for the src identifier. */ Base& src() { this->assert_term(); this->term_ref_ = &term_->src; return *this; } - /* Call prior to setting values for first identifier. This is either the - * component identifier, or first element of a pair (in case second is + /** Call prior to setting values for the first identifier. This is either the + * component identifier, or the first element of a pair (in case the second is * populated as well). */ Base& first() { this->assert_term(); @@ -31932,7 +34884,7 @@ struct term_builder_i : term_ref_builder_i { return *this; } - /* Call prior to setting values for second identifier. This is the second + /** Call prior to setting values for the second identifier. This is the second * element of a pair. Requires that first() is populated as well. */ Base& second() { this->assert_term(); @@ -31940,21 +34892,21 @@ struct term_builder_i : term_ref_builder_i { return *this; } - /* Select src identifier, initialize it with entity id */ + /** Select the src identifier, initialize it with an entity ID. */ Base& src(flecs::entity_t id) { this->src(); this->id(id); return *this; } - /* Select src identifier, initialize it with id associated with type */ + /** Select the src identifier, initialize it with the ID associated with the type. */ template Base& src() { this->src(_::type::id(this->world_v())); return *this; } - /* Select src identifier, initialize it with name. If name starts with a $ + /** Select the src identifier, initialize it with a name. If the name starts with a $, * the name is interpreted as a variable. */ Base& src(const char *name) { ecs_assert(name != NULL, ECS_INVALID_PARAMETER, NULL); @@ -31967,21 +34919,21 @@ struct term_builder_i : term_ref_builder_i { return *this; } - /* Select first identifier, initialize it with entity id */ + /** Select the first identifier, initialize it with an entity ID. */ Base& first(flecs::entity_t id) { this->first(); this->id(id); return *this; } - /* Select first identifier, initialize it with id associated with type */ + /** Select the first identifier, initialize it with the ID associated with the type. */ template Base& first() { this->first(_::type::id(this->world_v())); return *this; } - /* Select first identifier, initialize it with name. If name starts with a $ + /** Select the first identifier, initialize it with a name. If the name starts with a $, * the name is interpreted as a variable. */ Base& first(const char *name) { ecs_assert(name != NULL, ECS_INVALID_PARAMETER, NULL); @@ -31994,21 +34946,21 @@ struct term_builder_i : term_ref_builder_i { return *this; } - /* Select second identifier, initialize it with entity id */ + /** Select the second identifier, initialize it with an entity ID. */ Base& second(flecs::entity_t id) { this->second(); this->id(id); return *this; } - /* Select second identifier, initialize it with id associated with type */ + /** Select the second identifier, initialize it with the ID associated with the type. */ template Base& second() { this->second(_::type::id(this->world_v())); return *this; } - /* Select second identifier, initialize it with name. If name starts with a $ + /** Select the second identifier, initialize it with a name. If the name starts with a $, * the name is interpreted as a variable. */ Base& second(const char *name) { ecs_assert(name != NULL, ECS_INVALID_PARAMETER, NULL); @@ -32021,8 +34973,8 @@ struct term_builder_i : term_ref_builder_i { return *this; } - /* The up flag indicates that the term identifier may be substituted by - * traversing a relationship upwards. For example: substitute the identifier + /** The up flag indicates that the term identifier may be substituted by + * traversing a relationship upwards. For example, substitute the identifier * with its parent by traversing the ChildOf relationship. */ Base& up(flecs::entity_t trav = 0) { this->assert_term_ref(); @@ -32038,13 +34990,14 @@ struct term_builder_i : term_ref_builder_i { return *this; } + /** Traverse upwards using the specified relationship type. */ template Base& up() { return this->up(_::type::id(this->world_v())); } - /* The cascade flag is like up, but returns results in breadth-first order. - * Only supported for flecs::query */ + /** The cascade flag is like up(), but returns results in breadth-first order. + * Only supported for flecs::query. */ Base& cascade(flecs::entity_t trav = 0) { this->assert_term_ref(); this->up(); @@ -32055,24 +35008,25 @@ struct term_builder_i : term_ref_builder_i { return *this; } + /** Cascade using the specified relationship type. */ template Base& cascade() { return this->cascade(_::type::id(this->world_v())); } - /* Use with cascade to iterate results in descending (bottom -> top) order */ + /** Use with cascade() to iterate results in descending (bottom-to-top) order. */ Base& desc() { this->assert_term_ref(); this->term_ref_->id |= flecs::Desc; return *this; } - /* Same as up(), exists for backwards compatibility */ + /** Same as up(). Exists for backwards compatibility. */ Base& parent() { return this->up(); } - /* Specify relationship to traverse, and flags to indicate direction */ + /** Specify the relationship to traverse, and flags to indicate direction. */ Base& trav(flecs::entity_t trav, flecs::flags32_t flags = 0) { this->assert_term_ref(); term_->trav = trav; @@ -32080,21 +35034,21 @@ struct term_builder_i : term_ref_builder_i { return *this; } - /** Set id flags for term. */ + /** Set ID flags for the term. */ Base& id_flags(id_t flags) { this->assert_term(); term_->id |= flags; return *this; } - /** Set read/write access of term. */ + /** Set read/write access of the term. */ Base& inout(flecs::inout_kind_t inout) { this->assert_term(); term_->inout = static_cast(inout); return *this; } - /** Set read/write access for stage. Use this when a system reads or writes + /** Set read/write access for a stage. Use this when a system reads or writes * components other than the ones provided by the query. This information * can be used by schedulers to insert sync/merge points between systems * where deferred operations are flushed. @@ -32111,104 +35065,107 @@ struct term_builder_i : term_ref_builder_i { return *this; } - /** Short for inout_stage(flecs::Out). - * Use when system uses add, remove or set. + /** Short for inout_stage(flecs::Out). + * Use when the system uses add(), remove(), or set(). */ Base& write() { return this->inout_stage(flecs::Out); } /** Short for inout_stage(flecs::In). - * Use when system uses get. + * Use when the system uses get(). */ Base& read() { return this->inout_stage(flecs::In); } /** Short for inout_stage(flecs::InOut). - * Use when system uses ensure. + * Use when the system uses ensure(). */ Base& read_write() { return this->inout_stage(flecs::InOut); } - /** Short for inout(flecs::In) */ + /** Short for inout(flecs::In). */ Base& in() { return this->inout(flecs::In); } - /** Short for inout(flecs::Out) */ + /** Short for inout(flecs::Out). */ Base& out() { return this->inout(flecs::Out); } - /** Short for inout(flecs::InOut) */ + /** Short for inout(flecs::InOut). */ Base& inout() { return this->inout(flecs::InOut); } - /** Short for inout(flecs::In) */ + /** Short for inout(flecs::InOutNone). */ Base& inout_none() { return this->inout(flecs::InOutNone); } - /** Set operator of term. */ + /** Set the operator of the term. */ Base& oper(flecs::oper_kind_t oper) { this->assert_term(); term_->oper = static_cast(oper); return *this; } - /* Short for oper(flecs::And) */ + /** Short for oper(flecs::And). */ Base& and_() { return this->oper(flecs::And); } - /* Short for oper(flecs::Or) */ + /** Short for oper(flecs::Or). */ Base& or_() { return this->oper(flecs::Or); } - /* Short for oper(flecs::Or) */ + /** Short for oper(flecs::Not). */ Base& not_() { return this->oper(flecs::Not); } - /* Short for oper(flecs::Or) */ + /** Short for oper(flecs::Optional). */ Base& optional() { return this->oper(flecs::Optional); } - /* Short for oper(flecs::AndFrom) */ + /** Short for oper(flecs::AndFrom). */ Base& and_from() { return this->oper(flecs::AndFrom); } - /* Short for oper(flecs::OrFrom) */ + /** Short for oper(flecs::OrFrom). */ Base& or_from() { return this->oper(flecs::OrFrom); } - /* Short for oper(flecs::NotFrom) */ + /** Short for oper(flecs::NotFrom). */ Base& not_from() { return this->oper(flecs::NotFrom); } - /* Query terms are not triggered on by observers */ + /** Mark the term as a filter. Query terms marked as a filter are not triggered + * by observers. */ Base& filter() { term_->inout = EcsInOutFilter; return *this; } + /** Pointer to the current term. */ ecs_term_t *term_; protected: virtual flecs::world_t* world_v() override = 0; + /** Set the current term pointer. */ void set_term(ecs_term_t *term) { term_ = term; if (term) { - this->term_ref_ = &term_->src; // default to subject + this->term_ref_ = &term_->src; // default to source } else { this->term_ref_ = nullptr; } @@ -32235,16 +35192,19 @@ namespace flecs { * @ingroup cpp_core_queries */ struct term final : term_builder_i { + /** Default constructor. */ term() : term_builder_i(&value) , value({}) , world_(nullptr) { } - term(flecs::world_t *world_ptr) + /** Construct from a world. */ + term(flecs::world_t *world_ptr) : term_builder_i(&value) , value({}) , world_(world_ptr) { } + /** Construct from a world and an existing term descriptor. */ term(flecs::world_t *world_ptr, ecs_term_t t) : term_builder_i(&value) , value({}) @@ -32253,6 +35213,7 @@ struct term final : term_builder_i { this->set_term(&value); } + /** Construct from a world and a component ID. */ term(flecs::world_t *world_ptr, id_t component_id) : term_builder_i(&value) , value({}) @@ -32265,6 +35226,7 @@ struct term final : term_builder_i { this->set_term(&value); } + /** Construct from a world and a pair of entity IDs. */ term(flecs::world_t *world_ptr, entity_t first, entity_t second) : term_builder_i(&value) , value({}) @@ -32273,10 +35235,11 @@ struct term final : term_builder_i { this->set_term(&value); } - term(id_t component_id) + /** Construct from a component ID (no world). */ + term(id_t component_id) : term_builder_i(&value) , value({}) - , world_(nullptr) { + , world_(nullptr) { if (component_id & ECS_ID_FLAGS_MASK) { value.id = component_id; } else { @@ -32284,51 +35247,62 @@ struct term final : term_builder_i { } } - term(id_t first, id_t second) + /** Construct from a pair of IDs (no world). */ + term(id_t first, id_t second) : term_builder_i(&value) , value({}) - , world_(nullptr) { + , world_(nullptr) { value.first.id = first; value.second.id = second; } + /** Reset the term to its default state. */ void reset() { value = {}; this->set_term(nullptr); } + /** Check if the term is initialized. */ bool is_set() { return ecs_term_is_initialized(&value); } + /** Get the term ID. */ flecs::id id() { return flecs::id(world_, value.id); } + /** Get the inout kind of the term. */ flecs::inout_kind_t inout() { return static_cast(value.inout); } + /** Get the operator kind of the term. */ flecs::oper_kind_t oper() { return static_cast(value.oper); } + /** Get the source entity of the term. */ flecs::entity get_src() { return flecs::entity(world_, ECS_TERM_REF_ID(&value.src)); } + /** Get the first element of the term. */ flecs::entity get_first() { return flecs::entity(world_, ECS_TERM_REF_ID(&value.first)); } + /** Get the second element of the term. */ flecs::entity get_second() { return flecs::entity(world_, ECS_TERM_REF_ID(&value.second)); } + /** Convert to the underlying term_t. */ operator flecs::term_t() const { return value; } + /** The underlying term value. */ flecs::term_t value; protected: @@ -32338,7 +35312,7 @@ struct term final : term_builder_i { flecs::world_t *world_; }; -// Term mixin implementation +/** Term mixin implementation. */ template inline flecs::term world::term(Args &&... args) const { return flecs::term(world_, FLECS_FWD(args)...); @@ -32384,7 +35358,7 @@ inline flecs::term world::term() const { namespace flecs { namespace _ { -// Macros for template types so we don't go cross-eyed +// Macros for template types so we don't go cross-eyed. #define FLECS_TBUILDER template class #define FLECS_IBUILDER template class @@ -32446,30 +35420,36 @@ namespace flecs */ template struct query_builder_i : term_builder_i { - query_builder_i(ecs_query_desc_t *desc, int32_t term_index = 0) + /** Construct from a query descriptor. */ + query_builder_i(ecs_query_desc_t *desc, int32_t term_index = 0) : term_index_(term_index) , expr_count_(0) , desc_(desc) { } + /** Set the query flags. */ Base& query_flags(ecs_flags32_t flags) { desc_->flags |= flags; return *this; } + /** Set the cache kind for the query. */ Base& cache_kind(query_cache_kind_t kind) { desc_->cache_kind = static_cast(kind); return *this; } + /** Enable auto-caching for the query. */ Base& cached() { return cache_kind(flecs::QueryCacheAuto); } + /** Enable change detection for the query. */ Base& detect_changes() { desc_->flags |= EcsQueryDetectChanges; return *this; } + /** Set the query expression string. */ Base& expr(const char *expr) { ecs_check(expr_count_ == 0, ECS_INVALID_OPERATION, "query_builder::expr() called more than once"); @@ -32480,8 +35460,11 @@ struct query_builder_i : term_builder_i { return *this; } - /* With methods */ + /** @name With methods + * @{ + */ + /** Add a term for the specified type. */ template Base& with() { this->term(); @@ -32491,57 +35474,67 @@ struct query_builder_i : term_builder_i { return *this; } + /** Add a term for the specified component ID. */ Base& with(id_t component_id) { this->term(); *this->term_ = flecs::term(component_id); return *this; } + /** Add a term for the specified component name. */ Base& with(const char *component_name) { this->term(); *this->term_ = flecs::term().first(component_name); return *this; } + /** Add a term for a pair specified by name. */ Base& with(const char *first, const char *second) { this->term(); *this->term_ = flecs::term().first(first).second(second); return *this; } + /** Add a term for a pair specified by entity IDs. */ Base& with(entity_t first, entity_t second) { this->term(); *this->term_ = flecs::term(first, second); return *this; } + /** Add a term for a pair with an entity ID first and a name second. */ Base& with(entity_t first, const char *second) { this->term(); *this->term_ = flecs::term(first).second(second); return *this; } + /** Add a term for a pair with a name first and an entity ID second. */ Base& with(const char *first, entity_t second) { this->term(); *this->term_ = flecs::term().first(first).second(second); return *this; } + /** Add a term for a pair with type First and an entity ID second. */ template Base& with(entity_t second) { return this->with(_::type::id(this->world_v()), second); } + /** Add a term for a pair with type First and name second. */ template Base& with(const char *second) { return this->with(_::type::id(this->world_v())).second(second); } + /** Add a term for a pair with types First and Second. */ template Base& with() { return this->with(_::type::id(this->world_v())); } + /** Add a term for an enum value. */ template ::value > = 0> Base& with(E value) { flecs::entity_t r = _::type::id(this->world_v()); @@ -32549,90 +35542,110 @@ struct query_builder_i : term_builder_i { return this->with(r, o); } + /** Add a term from an existing term reference. */ Base& with(flecs::term& term) { this->term(); *this->term_ = term; return *this; } + /** Add a term from an existing term (move). */ Base& with(flecs::term&& term) { this->term(); *this->term_ = term; return *this; } - /* Without methods, shorthand for .with(...).not_(). */ + /** @} + * @name Without methods + * Shorthand for .with(...).not_(). + * @{ + */ + /** Add a negated term. */ template Base& without(Args&&... args) { return this->with(FLECS_FWD(args)...).not_(); } + /** Add a negated term for the specified type. */ template Base& without(Args&&... args) { return this->with(FLECS_FWD(args)...).not_(); } + /** Add a negated term for a pair of types. */ template Base& without() { return this->with().not_(); } - /* Write/read methods */ + /** @} + * @name Write/read methods + * @{ + */ + /** Short for inout_stage(flecs::Out). */ Base& write() { term_builder_i::write(); return *this; } + /** Add a write term with the specified arguments. */ template Base& write(Args&&... args) { return this->with(FLECS_FWD(args)...).write(); } + /** Add a write term for the specified type. */ template Base& write(Args&&... args) { return this->with(FLECS_FWD(args)...).write(); } + /** Add a write term for a pair of types. */ template Base& write() { return this->with().write(); } + /** Short for inout_stage(flecs::In). */ Base& read() { term_builder_i::read(); return *this; } + /** Add a read term with the specified arguments. */ template Base& read(Args&&... args) { return this->with(FLECS_FWD(args)...).read(); } + /** Add a read term for the specified type. */ template Base& read(Args&&... args) { return this->with(FLECS_FWD(args)...).read(); } + /** Add a read term for a pair of types. */ template Base& read() { return this->with().read(); } - /* Scope_open/scope_close shorthand notation. */ + /** @} */ + + /** Open a query scope. */ Base& scope_open() { return this->with(flecs::ScopeOpen).entity(0); } + /** Close a query scope. */ Base& scope_close() { return this->with(flecs::ScopeClose).entity(0); } - /* Term notation for more complex query features */ - - /** Sets the current term to next one in term list. - */ + /** Set the current term to the next one in the term list. */ Base& term() { if (this->term_) { ecs_check(ecs_term_is_initialized(this->term_), @@ -32651,7 +35664,7 @@ struct query_builder_i : term_builder_i { return *this; } - /** Sets the current term to the one with the provided type. + /** Set the current term to the one with the provided type. * This loops over all terms to find the one with the provided type. * For performance-critical paths, use term_at(int32_t) instead. */ @@ -32673,8 +35686,7 @@ struct query_builder_i : term_builder_i { return *this; } - /** Sets the current term to the one at the provided index. - */ + /** Set the current term to the one at the provided index. */ Base& term_at(int32_t term_index) { ecs_assert(term_index >= 0, ECS_INVALID_PARAMETER, NULL); int32_t prev_index = term_index_; @@ -32686,8 +35698,8 @@ struct query_builder_i : term_builder_i { return *this; } - /** Sets the current term to the one at the provided index and asserts that the type matches. - */ + /** Set the current term to the one at the provided index and assert + * that the type matches. */ template Base& term_at(int32_t term_index) { this->term_at(term_index); @@ -32729,11 +35741,11 @@ struct query_builder_i : term_builder_i { } /** Sort the output of a query. - * Same as order_by, but with component identifier. + * Same as order_by(), but with a component identifier. * * @param component The component used to sort. * @param compare The compare function used to sort the components. - */ + */ Base& order_by(flecs::entity_t component, int(*compare)(flecs::entity_t, const void*, flecs::entity_t, const void*)) { desc_->order_by_callback = reinterpret_cast(compare); desc_->order_by = component; @@ -32742,7 +35754,7 @@ struct query_builder_i : term_builder_i { /** Group and sort matched tables. * Similar to ecs_query_order_by(), but instead of sorting individual entities, this - * operation only sorts matched tables. This can be useful of a query needs to + * operation only sorts matched tables. This can be useful if a query needs to * enforce a certain iteration order upon the tables it is iterating, for * example by giving a certain component or tag a higher priority. * @@ -32755,7 +35767,7 @@ struct query_builder_i : term_builder_i { * sorted within each set of tables that are assigned the same rank. * * @tparam T The component used to determine the group rank. - * @param group_by_action Callback that determines group id for table. + * @param group_by_action Callback that determines the group ID for a table. */ template Base& group_by(uint64_t(*group_by_action)(flecs::world_t*, flecs::table_t *table, flecs::id_t id, void* ctx)) { @@ -32764,10 +35776,10 @@ struct query_builder_i : term_builder_i { } /** Group and sort matched tables. - * Same as group_by, but with component identifier. + * Same as group_by(), but with a component identifier. * * @param component The component used to determine the group rank. - * @param group_by_action Callback that determines group id for table. + * @param group_by_action Callback that determines the group ID for a table. */ Base& group_by(flecs::entity_t component, uint64_t(*group_by_action)(flecs::world_t*, flecs::table_t *table, flecs::id_t id, void* ctx)) { desc_->group_by_callback = reinterpret_cast(group_by_action); @@ -32776,7 +35788,7 @@ struct query_builder_i : term_builder_i { } /** Group and sort matched tables. - * Same as group_by, but with default group_by action. + * Same as group_by(), but with the default group_by() action. * * @tparam T The component used to determine the group rank. */ @@ -32786,7 +35798,7 @@ struct query_builder_i : term_builder_i { } /** Group and sort matched tables. - * Same as group_by, but with default group_by action. + * Same as group_by(), but with the default group_by() action. * * @param component The component used to determine the group rank. */ @@ -32794,10 +35806,10 @@ struct query_builder_i : term_builder_i { return this->group_by(component, nullptr); } - /** Specify context to be passed to group_by function. + /** Specify context to be passed to the group_by() function. * - * @param ctx Context to pass to group_by function. - * @param ctx_free Function to cleanup context (called when query is deleted). + * @param ctx Context to pass to the group_by() function. + * @param ctx_free Function to clean up context (called when the query is deleted). */ Base& group_by_ctx(void *ctx, ecs_ctx_free_t ctx_free = nullptr) { desc_->group_by_ctx = ctx; @@ -32805,15 +35817,13 @@ struct query_builder_i : term_builder_i { return *this; } - /** Specify on_group_create action. - */ + /** Specify the on_group_create() action. */ Base& on_group_create(ecs_group_create_action_t action) { desc_->on_group_create = action; return *this; } - /** Specify on_group_delete action. - */ + /** Specify the on_group_delete() action. */ Base& on_group_delete(ecs_group_delete_action_t action) { desc_->on_group_delete = action; return *this; @@ -32881,19 +35891,27 @@ struct query_builder final : _::query_builder_base { namespace flecs { +/** Base class for queries. + * + * @ingroup cpp_core_queries + */ struct query_base { + /** Default constructor. */ query_base() { } + /** Construct from a mutable query pointer. */ query_base(query_t *q) - : query_(q) { + : query_(q) { flecs_poly_claim(q); } + /** Construct from a const query pointer. */ query_base(const query_t *q) - : query_(ECS_CONST_CAST(query_t*, q)) { + : query_(ECS_CONST_CAST(query_t*, q)) { flecs_poly_claim(q); } + /** Construct from a world and a query descriptor. */ query_base(world_t *world, ecs_query_desc_t *desc) { if (desc->entity && desc->terms[0].id == 0) { const flecs::Poly *query_poly = ecs_get_pair( @@ -32908,6 +35926,7 @@ struct query_base { query_ = ecs_query_init(world, desc); } + /** Copy constructor. */ query_base(const query_base& obj) { this->query_ = obj.query_; if (this->query_) @@ -32916,6 +35935,7 @@ struct query_base { } } + /** Copy assignment operator. */ query_base& operator=(const query_base& obj) { this->~query_base(); this->query_ = obj.query_; @@ -32926,37 +35946,43 @@ struct query_base { return *this; } + /** Move constructor. */ query_base(query_base&& obj) noexcept { this->query_ = obj.query_; obj.query_ = nullptr; } + /** Move assignment operator. */ query_base& operator=(query_base&& obj) noexcept { this->query_ = obj.query_; obj.query_ = nullptr; return *this; } - flecs::entity entity() { + /** Get the entity associated with the query. */ + flecs::entity entity() const { return flecs::entity(query_->world, query_->entity); } + /** Get a pointer to the underlying C query. */ const flecs::query_t* c_ptr() const { return query_; } + /** Convert to a const query pointer. */ operator const flecs::query_t*() const { return query_; } + /** Check if the query is valid. */ operator bool() const { return query_ != nullptr; } - /** Free persistent query. + /** Free a persistent query. * A persistent query is a query that is associated with an entity, such as * system queries and named queries. Persistent queries must be deleted with - * destruct(), or will be deleted automatically at world cleanup. + * destruct(), or will be deleted automatically at world cleanup. */ void destruct() { ecs_assert(query_->entity != 0, ECS_INVALID_OPERATION, "destruct() " @@ -32965,11 +35991,8 @@ struct query_base { query_ = nullptr; } + /** Destructor. Only frees the query if it is not associated with an entity. */ ~query_base() { - /* Only free if query is not associated with entity, such as system - * queries and named queries. Named queries have to be either explicitly - * deleted with the .destruct() method, or will be deleted when the - * world is deleted. */ if (query_ && !query_->entity) { if (!flecs_poly_release(query_)) { ecs_query_fini(query_); @@ -32978,7 +36001,7 @@ struct query_base { } } - /** Returns whether the query data changed since the last iteration. + /** Return whether the query data changed since the last iteration. * This operation must be invoked before obtaining the iterator, as this will * reset the changed state. The operation will return true after: * - new entities have been matched with @@ -32991,18 +36014,18 @@ struct query_base { return ecs_query_changed(query_); } - /** Get info for group. - * - * @param group_id The group id for which to retrieve the info. + /** Get info for a group. + * + * @param group_id The group ID for which to retrieve the info. * @return The group info. */ const flecs::query_group_info_t* group_info(uint64_t group_id) const { return ecs_query_get_group_info(query_, group_id); } - /** Get context for group. - * - * @param group_id The group id for which to retrieve the context. + /** Get context for a group. + * + * @param group_id The group ID for which to retrieve the context. * @return The group context. */ void* group_ctx(uint64_t group_id) const { @@ -33014,6 +36037,7 @@ struct query_base { } } + /** Iterate each term in the query, invoking a callback for each. */ template void each_term(const Func& func) { for (int i = 0; i < query_->term_count; i ++) { @@ -33023,41 +36047,51 @@ struct query_base { } } - flecs::term term(int32_t index) { + /** Get term at the specified index. */ + flecs::term term(int32_t index) const { return flecs::term(query_->world, query_->terms[index]); } - int32_t term_count() { + /** Get the number of terms in the query. */ + int32_t term_count() const { return query_->term_count; } - int32_t field_count() { + /** Get the number of fields in the query. */ + int32_t field_count() const { return query_->field_count; } - int32_t find_var(const char *name) { + /** Find a variable by name. */ + int32_t find_var(const char *name) const { return ecs_query_find_var(query_, name); } - flecs::string str() { + /** Convert the query to a string expression. */ + flecs::string str() const { char *result = ecs_query_str(query_); return flecs::string(result); } - /** Returns a string representing the query plan. - * This can be used to analyze the behavior & performance of the query. - * @see ecs_query_plan + /** Return a string representing the query plan. + * This can be used to analyze the behavior and performance of the query. + * @see ecs_query_plan() */ flecs::string plan() const { char *result = ecs_query_plan(query_); return flecs::string(result); } + /** Convert to a typed query. */ operator query<>() const; # ifdef FLECS_JSON +/** + * @file addons/cpp/mixins/json/query.inl + * @brief JSON query mixin. + */ -/** Serialize query to JSON. +/** Serialize a query to JSON. * * @memberof flecs::query_base * @ingroup cpp_addons_json @@ -33073,6 +36107,10 @@ flecs::string to_json(flecs::iter_to_json_desc_t *desc = nullptr) { query_t *query_ = nullptr; }; +/** Typed query. + * + * @ingroup cpp_core_queries + */ template struct query : query_base, iterable { private: @@ -33081,22 +36119,28 @@ struct query : query_base, iterable { public: using query_base::query_base; - query() : query_base() { } // necessary not to confuse msvc + /** Default constructor. */ + query() : query_base() { } // necessary not to confuse MSVC + /** Copy constructor. */ query(const query& obj) : query_base(obj) { } + /** Copy assignment operator. */ query& operator=(const query& obj) { query_base::operator=(obj); return *this; } + /** Move constructor. */ query(query&& obj) noexcept : query_base(FLECS_MOV(obj)) { } + /** Move assignment operator. */ query& operator=(query&& obj) noexcept { query_base::operator=(FLECS_FWD(obj)); return *this; } + /** Get the cache query, if any. */ flecs::query<> cache_query() const { const flecs::query_t *q = ecs_query_get_cache_query(query_); return flecs::query<>(q); @@ -33142,6 +36186,18 @@ namespace _ { template struct query_delegate_w_ent; +template +struct query_delegate_w_ent > +{ + query_delegate_w_ent(const flecs::world& world, Func&& func) { + ecs_entities_t entities = ecs_get_entities(ecs_get_world(world)); + + for (int32_t i = 0; i < entities.alive_count; i ++) { + func(flecs::entity(world, entities.ids[i])); + } + } +}; + template struct query_delegate_w_ent > { @@ -33164,7 +36220,7 @@ struct query_delegate_no_ent > } }; -// Switch between function with & without entity parameter +// Switch between function with and without entity parameter template struct query_delegate; @@ -33230,7 +36286,7 @@ inline query_base::operator flecs::query<> () const { /** * @file addons/cpp/utils/node_builder.hpp - * @brief Base builder class for node objects, like systems, observers. + * @brief Base builder class for node objects, like systems and observers. */ #pragma once @@ -33238,7 +36294,7 @@ inline query_base::operator flecs::query<> () const { namespace flecs { namespace _ { -// Macros for template types so we don't go cross-eyed +// Macros for template types so we don't go cross-eyed. #define FLECS_IBUILDER template class template @@ -33333,12 +36389,14 @@ namespace flecs { template struct observer_builder_i : query_builder_i { using BaseClass = query_builder_i; + /** Default constructor. */ observer_builder_i() : BaseClass(nullptr) , desc_(nullptr) , event_count_(0) { } - observer_builder_i(ecs_observer_desc_t *desc) + /** Construct from an observer descriptor. */ + observer_builder_i(ecs_observer_desc_t *desc) : BaseClass(&desc->query) , desc_(desc) , event_count_(0) { } @@ -33360,25 +36418,25 @@ struct observer_builder_i : query_builder_i { return *this; } - /** Invoke observer for anything that matches its query on creation */ + /** Invoke the observer for anything that matches its query on creation. */ Base& yield_existing(bool value = true) { desc_->yield_existing = value; return *this; } - /** Set observer flags */ + /** Set the observer flags. */ Base& observer_flags(ecs_flags32_t flags) { desc_->flags_ |= flags; return *this; } - /** Set observer context */ + /** Set the observer context. */ Base& ctx(void *ptr) { desc_->ctx = ptr; return *this; } - /** Set observer run callback */ + /** Set the observer run callback. */ Base& run(ecs_iter_action_t action) { desc_->run = action; return *this; @@ -33413,6 +36471,7 @@ namespace _ { */ template struct observer_builder final : _::observer_builder_base { + /** Construct an observer builder. */ observer_builder(flecs::world_t* world, const char *name = nullptr) : _::observer_builder_base(world, name) { @@ -33426,17 +36485,24 @@ struct observer_builder final : _::observer_builder_base { namespace flecs { +/** Observer. + * + * @ingroup cpp_observers + */ struct observer final : entity { using entity::entity; + /** Default constructor. */ explicit observer() : entity() { } + /** Construct from a world and an observer descriptor. */ observer(flecs::world_t *world, ecs_observer_desc_t *desc) { world_ = world; id_ = ecs_observer_init(world, desc); } + /** Set the observer context. */ void ctx(void *ctx) { ecs_observer_desc_t desc = {}; desc.entity = id_; @@ -33444,16 +36510,18 @@ struct observer final : entity ecs_observer_init(world_, &desc); } + /** Get the observer context. */ void* ctx() const { return ecs_observer_get(world_, id_)->ctx; } + /** Get the query for this observer. */ flecs::query<> query() const { return flecs::query<>(ecs_observer_get(world_, id_)->query); } }; -// Mixin implementation +/** Mixin implementation. */ inline observer world::observer(flecs::entity e) const { return flecs::observer(world_, e); } @@ -33613,12 +36681,12 @@ ecs_entity_t do_import(world& world, const char *symbol) { ecs_entity_t scope = ecs_set_scope(world, 0); - // Initialize module component type & don't allow it to be registered as a - // tag, as this would prevent calling emplace() + // Initialize module component type and don't allow it to be registered as a + // tag, as this would prevent calling emplace(). auto c_ = component(world, nullptr, false); // Make module component sparse so that it'll never move in memory. This - // guarantees that a module destructor can be reliably used to cleanup + // guarantees that a module destructor can be reliably used to clean up // module resources. c_.add(flecs::Sparse); @@ -33630,9 +36698,9 @@ ecs_entity_t do_import(world& world, const char *symbol) { ecs_add_id(world, c_, EcsModule); - // It should now be possible to lookup the module + // It should now be possible to look up the module. ecs_entity_t m = ecs_lookup_symbol(world, symbol, false, false); - ecs_assert(m != 0, ECS_MODULE_UNDEFINED, symbol); + ecs_assert(m != 0, ECS_MODULE_UNDEFINED, "%s", symbol); ecs_assert(m == c_, ECS_INTERNAL_ERROR, NULL); ecs_log_pop(); @@ -33642,26 +36710,27 @@ ecs_entity_t do_import(world& world, const char *symbol) { template flecs::entity import(world& world) { - const char *symbol = _::symbol_name(); + char *symbol = ecs_cpp_get_symbol_name(NULL, type_name(), 0); ecs_entity_t m = ecs_lookup_symbol(world, symbol, true, false); if (!_::type::registered(world)) { - /* Module is registered with world, initialize static data */ + // Module is registered with world, initialize static data. if (m) { _::type::init_builtin(world, m, false); - /* Module is not yet registered, register it now */ + // Module is not yet registered, register it now. } else { m = _::do_import(world, symbol); } - /* Module has been registered, but could have been for another world. Import - * if module hasn't been registered for this world. */ + // Module has been registered, but could have been for another world. + // Import if module hasn't been registered for this world. } else if (!m) { m = _::do_import(world, symbol); } + ecs_os_free(symbol); return flecs::entity(world, m); } @@ -33670,7 +36739,7 @@ flecs::entity import(world& world) { /** * @defgroup cpp_addons_modules Modules * @ingroup cpp_addons - * Modules organize components, systems and more in reusable units of code. + * Modules organize components, systems, and more in reusable units of code. * * @{ */ @@ -33685,21 +36754,12 @@ inline flecs::entity world::module(const char *name) const { ecs_add_path_w_sep(world_, result, 0, name, "::", "::"); flecs::entity parent = result.parent(); if (prev_parent != parent) { - // Module was reparented, cleanup old parent(s) + // Module was reparented, clean up old parent(s). flecs::entity cur = prev_parent, next; while (cur) { next = cur.parent(); - - ecs_iter_t it = ecs_each_id(world_, ecs_pair(EcsChildOf, cur)); - if (!ecs_iter_is_true(&it)) { - cur.destruct(); - - // Prevent increasing the generation count of the temporary - // parent. This allows entities created during - // initialization to keep non-recycled ids. - this->set_version(cur); - } - + cur.destruct(); + this->set_version(cur); cur = next; } } @@ -33776,6 +36836,10 @@ struct system_builder_i : query_builder_i { return *this; } + /** Specify in which phase the system should run, using an enum constant. + * + * @param phase The enum phase value. + */ template ::value> = 0> Base& kind(E phase) { @@ -33793,26 +36857,26 @@ struct system_builder_i : query_builder_i { return this->kind(_::type::id(world_v())); } - /** Specify whether system can run on multiple threads. + /** Specify whether the system can run on multiple threads. * - * @param value If false system will always run on a single thread. + * @param value If false, the system will always run on a single thread. */ Base& multi_threaded(bool value = true) { desc_->multi_threaded = value; return *this; } - /** Specify whether system should be ran in staged context. + /** Specify whether the system should be run in an immediate (non-staged) context. * - * @param value If false system will always run staged. + * @param value If false, the system will always run staged. */ Base& immediate(bool value = true) { desc_->immediate = value; return *this; } - /** Set system interval. - * This operation will cause the system to be ran at the specified interval. + /** Set the system interval. + * This operation will cause the system to be run at the specified interval. * * The timer is synchronous, and is incremented each frame by delta_time. * @@ -33823,8 +36887,8 @@ struct system_builder_i : query_builder_i { return *this; } - /** Set system rate. - * This operation will cause the system to be ran at a multiple of the + /** Set the system rate. + * This operation will cause the system to be run at a multiple of the * provided tick source. The tick source may be any entity, including * another system. * @@ -33837,8 +36901,8 @@ struct system_builder_i : query_builder_i { return *this; } - /** Set system rate. - * This operation will cause the system to be ran at a multiple of the + /** Set the system rate. + * This operation will cause the system to be run at a multiple of the * frame tick frequency. If a tick source was provided, this just updates * the rate of the system. * @@ -33849,7 +36913,7 @@ struct system_builder_i : query_builder_i { return *this; } - /** Set tick source. + /** Set the tick source. * This operation sets a shared tick source for the system. * * @tparam T The type associated with the singleton tick source to use for the system. @@ -33860,7 +36924,7 @@ struct system_builder_i : query_builder_i { return *this; } - /** Set tick source. + /** Set the tick source. * This operation sets a shared tick source for the system. * * @param tick_source The tick source to use for the system. @@ -33870,13 +36934,13 @@ struct system_builder_i : query_builder_i { return *this; } - /** Set system context */ + /** Set the system context. */ Base& ctx(void *ptr) { desc_->ctx = ptr; return *this; } - /** Set system run callback */ + /** Set the system run callback. */ Base& run(ecs_iter_action_t action) { desc_->run = action; return *this; @@ -33923,6 +36987,13 @@ struct system_builder final : _::system_builder_base { template system each(Func&& func); + +private: + template + system each_callback(_::arg_list, Func&& func); + + template + void prepend_each_callback_signature(); }; } @@ -33931,13 +37002,18 @@ struct system_builder final : _::system_builder_base { namespace flecs { +/** Fluent interface for running a system. + * + * @ingroup cpp_addons_systems + */ struct system_runner_fluent { + /** Construct a system runner. */ system_runner_fluent( - world_t *world, - entity_t id, - int32_t stage_current, - int32_t stage_count, - ecs_ftime_t delta_time, + world_t *world, + entity_t id, + int32_t stage_current, + int32_t stage_count, + ecs_ftime_t delta_time, void *param) : stage_(world) , id_(id) @@ -33946,21 +37022,25 @@ struct system_runner_fluent { , stage_current_(stage_current) , stage_count_(stage_count) { } + /** Set the offset for the system runner. */ system_runner_fluent& offset(int32_t offset) { offset_ = offset; return *this; } + /** Set the limit for the system runner. */ system_runner_fluent& limit(int32_t limit) { limit_ = limit; return *this; } + /** Set the stage for the system runner. */ system_runner_fluent& stage(flecs::world& stage) { stage_ = stage.c_ptr(); return *this; } + /** Destructor. Runs the system on destruction. */ ~system_runner_fluent() { if (stage_count_) { ecs_run_worker( @@ -33982,20 +37062,27 @@ struct system_runner_fluent { int32_t stage_count_; }; +/** System. + * + * @ingroup cpp_addons_systems + */ struct system final : entity { using entity::entity; + /** Default constructor. */ explicit system() { id_ = 0; world_ = nullptr; } + /** Construct from a world and a system descriptor. */ explicit system(flecs::world_t *world, ecs_system_desc_t *desc) { world_ = world; id_ = ecs_system_init(world, desc); } + /** Set the system context. */ void ctx(void *ctx) { ecs_system_desc_t desc = {}; desc.entity = id_; @@ -34003,18 +37090,35 @@ struct system final : entity ecs_system_init(world_, &desc); } + /** Get the system context. */ void* ctx() const { return ecs_system_get(world_, id_)->ctx; } + /** Get the query for this system. */ flecs::query<> query() const { return flecs::query<>(ecs_system_get(world_, id_)->query); } + /** Set the query group. */ + system& set_group(uint64_t group_id) { + ecs_system_set_group(world_, id_, group_id); + return *this; + } + + /** Set the query group. */ + template + system& set_group() { + ecs_system_set_group(world_, id_, _::type().id(world_)); + return *this; + } + + /** Run the system. */ system_runner_fluent run(ecs_ftime_t delta_time = 0.0f, void *param = nullptr) const { return system_runner_fluent(world_, id_, 0, 0, delta_time, param); } + /** Run the system on a specific worker stage. */ system_runner_fluent run_worker( int32_t stage_current, int32_t stage_count, @@ -34039,48 +37143,48 @@ struct system final : entity */ /** Set interval. - * @see ecs_set_interval + * @see ecs_set_interval() */ void interval(ecs_ftime_t interval); /** Get interval. - * @see ecs_get_interval. + * @see ecs_get_interval() */ ecs_ftime_t interval(); /** Set timeout. - * @see ecs_set_timeout + * @see ecs_set_timeout() */ void timeout(ecs_ftime_t timeout); /** Get timeout. - * @see ecs_get_timeout + * @see ecs_get_timeout() */ ecs_ftime_t timeout(); /** Set system rate (system is its own tick source). - * @see ecs_set_rate + * @see ecs_set_rate() */ void rate(int32_t rate); /** Start timer. - * @see ecs_start_timer + * @see ecs_start_timer() */ void start(); /** Stop timer. - * @see ecs_start_timer + * @see ecs_stop_timer() */ void stop(); /** Set external tick source. - * @see ecs_set_tick_source + * @see ecs_set_tick_source() */ template void set_tick_source(); /** Set external tick source. - * @see ecs_set_tick_source + * @see ecs_set_tick_source() */ void set_tick_source(flecs::entity e); @@ -34090,7 +37194,7 @@ void set_tick_source(flecs::entity e); }; -// Mixin implementation +/** Mixin implementation. */ inline system world::system(flecs::entity e) const { return flecs::system(world_, e); } @@ -34102,6 +37206,31 @@ inline system_builder world::system(Args &&... args) const { namespace _ { +template +struct system_each_normalize_args; + +template +struct system_each_normalize_args> { + using type = arg_list...>; +}; + +template +struct system_each_callback_args { + using type = typename system_each_normalize_args::type; +}; + +template +struct system_each_callback_args, + if_t, flecs::entity>::value>> { + using type = typename system_each_normalize_args>::type; +}; + +template +struct system_each_callback_args, + if_t, flecs::iter>::value>> { + using type = typename system_each_normalize_args>::type; +}; + inline void system_init(flecs::world& world) { world.component("flecs::system::TickSource"); } @@ -34111,8 +37240,60 @@ inline void system_init(flecs::world& world) { template template inline system system_builder::each(Func&& func) { - // Faster version of each() that iterates the query on the C++ side. - return this->run_each(FLECS_FWD(func)); + if constexpr (sizeof...(Components) == 0) { + using CallbackComponents = + typename _::system_each_callback_args>::type; + return this->each_callback(CallbackComponents{}, FLECS_FWD(func)); + } else { + // Faster version of each() that iterates the query on the C++ side. + return this->run_each(FLECS_FWD(func)); + } +} + +template +template +inline system system_builder::each_callback( + _::arg_list, + Func&& func) +{ + this->template prepend_each_callback_signature(); + + using Delegate = typename _::each_delegate< + typename std::decay::type, CallbackComponents...>; + + auto ctx = FLECS_NEW(Delegate)(FLECS_FWD(func)); + this->desc_.run = Delegate::run_each; + this->desc_.run_ctx = ctx; + this->desc_.run_ctx_free = _::free_obj; + return system(this->world_, &this->desc_); +} + +template +template +inline void system_builder::prepend_each_callback_signature() { + if constexpr (sizeof...(Components) == 0 && sizeof...(CallbackComponents) != 0) { + constexpr int32_t callback_term_count = + static_cast(sizeof...(CallbackComponents)); + + ecs_assert(this->term_index_ + callback_term_count <= FLECS_TERM_COUNT_MAX, + ECS_INVALID_PARAMETER, "maximum number of terms exceeded"); + + const int32_t existing_term_count = this->term_index_; + this->set_term(nullptr); + + for (int32_t i = existing_term_count - 1; i >= 0; i --) { + this->desc_.query.terms[i + callback_term_count] = + this->desc_.query.terms[i]; + } + + for (int32_t i = 0; i < callback_term_count; i ++) { + this->desc_.query.terms[i] = ecs_term_t{}; + } + + this->term_index_ = 0; + _::sig(this->world_).populate(this); + this->term_index_ = existing_term_count + callback_term_count; + } } } // namespace flecs @@ -34149,7 +37330,8 @@ namespace flecs { */ template struct pipeline_builder_i : query_builder_i { - pipeline_builder_i(ecs_pipeline_desc_t *desc, int32_t term_index = 0) + /** Construct from a pipeline descriptor. */ + pipeline_builder_i(ecs_pipeline_desc_t *desc, int32_t term_index = 0) : query_builder_i(&desc->query, term_index) , desc_(desc) { } @@ -34174,6 +37356,7 @@ namespace _ { */ template struct pipeline_builder final : _::pipeline_builder_base { + /** Construct a pipeline builder. */ pipeline_builder(flecs::world_t* world, flecs::entity_t id = 0) : _::pipeline_builder_base(world) { @@ -34276,37 +37459,47 @@ inline bool world::using_task_threads() const { namespace flecs { -// Timer class +/** Timer class. + * + * @ingroup cpp_addons_timer + */ struct timer final : entity { using entity::entity; + /** Set the timer interval. */ timer& interval(ecs_ftime_t interval) { ecs_set_interval(world_, id_, interval); return *this; } + /** Get the timer interval. */ ecs_ftime_t interval() { return ecs_get_interval(world_, id_); } + /** Set the timer timeout. */ timer& timeout(ecs_ftime_t timeout) { ecs_set_timeout(world_, id_, timeout); return *this; } + /** Get the timer timeout. */ ecs_ftime_t timeout() { return ecs_get_timeout(world_, id_); } + /** Set the timer rate. */ timer& rate(int32_t rate, flecs::entity_t tick_source = 0) { ecs_set_rate(world_, id_, rate, tick_source); return *this; } + /** Start the timer. */ void start() { ecs_start_timer(world_, id_); } + /** Stop the timer. */ void stop() { ecs_stop_timer(world_, id_); } @@ -34322,43 +37515,53 @@ inline flecs::timer world::timer(Args &&... args) const { return flecs::timer(world_, FLECS_FWD(args)...); } +/** Randomize timers for all systems. */ inline void world::randomize_timers() const { ecs_randomize_timers(world_); } +/** Set the interval for a system. */ inline void system::interval(ecs_ftime_t interval) { ecs_set_interval(world_, id_, interval); } +/** Get the interval for a system. */ inline ecs_ftime_t system::interval() { return ecs_get_interval(world_, id_); } +/** Set the timeout for a system. */ inline void system::timeout(ecs_ftime_t timeout) { ecs_set_timeout(world_, id_, timeout); } +/** Get the timeout for a system. */ inline ecs_ftime_t system::timeout() { return ecs_get_timeout(world_, id_); } +/** Set the rate for a system. */ inline void system::rate(int32_t rate) { ecs_set_rate(world_, id_, rate, 0); } +/** Start the system timer. */ inline void system::start() { ecs_start_timer(world_, id_); } +/** Stop the system timer. */ inline void system::stop() { ecs_stop_timer(world_, id_); } +/** Set the tick source for a system by type. */ template inline void system::set_tick_source() { ecs_set_tick_source(world_, id_, _::type::id(world_)); } +/** Set the tick source for a system by entity. */ inline void system::set_tick_source(flecs::entity e) { ecs_set_tick_source(world_, id_, e); } @@ -34397,7 +37600,7 @@ inline const char* get_uuid(const flecs::entity_view& e) { return ecs_doc_get_uuid(e.world(), e); } -/** Get human readable name for an entity. +/** Get human-readable name for an entity. * * @see ecs_doc_get_name() * @see flecs::doc::set_name() @@ -34469,7 +37672,7 @@ inline void set_uuid(flecs::entity& e, const char *uuid) { ecs_doc_set_uuid(e.world(), e, uuid); } -/** Set human readable name for an entity. +/** Set human-readable name for an entity. * * @see ecs_doc_set_name() * @see flecs::doc::get_name() @@ -34541,8 +37744,6 @@ inline void init(flecs::world& world) { } // namespace doc } // namespace flecs -#endif -#ifdef FLECS_DOC #endif #ifdef FLECS_REST /** @@ -34580,7 +37781,7 @@ namespace flecs { namespace meta { namespace _ { -/* Type support for entity wrappers */ +/** Type support for entity wrappers. */ template inline flecs::opaque flecs_entity_support(flecs::world&) { return flecs::opaque() @@ -34628,25 +37829,25 @@ inline void init(flecs::world& world) { world.component("flecs::meta::unit"); - // To support member and member register components - // (that do not have conflicting symbols with builtin ones) for platform - // specific types. + // To support member and member, register components + // (that do not have conflicting symbols with built-in ones) for + // platform-specific types. if (!flecs::is_same() && !flecs::is_same()) { flecs::_::type::init_builtin(world, flecs::Iptr, true); - // Remove symbol to prevent validation errors, as it doesn't match with - // the typename + // Remove symbol to prevent validation errors, as it doesn't match + // the typename. ecs_remove_pair(world, flecs::Iptr, ecs_id(EcsIdentifier), EcsSymbol); } if (!flecs::is_same() && !flecs::is_same()) { flecs::_::type::init_builtin(world, flecs::Uptr, true); - // Remove symbol to prevent validation errors, as it doesn't match with - // the typename + // Remove symbol to prevent validation errors, as it doesn't match + // the typename. ecs_remove_pair(world, flecs::Uptr, ecs_id(EcsIdentifier), EcsSymbol); } - // Register opaque type support for C++ entity wrappers + // Register opaque type support for C++ entity wrappers. world.entity("::flecs::cpp").add(flecs::Module).scope([&]{ world.component() .opaque(flecs_entity_support); @@ -34672,7 +37873,7 @@ inline flecs::entity cursor::get_entity() const { return flecs::entity(cursor_.world, ecs_meta_get_entity(&cursor_)); } -/** Create primitive type */ +/** Create a primitive type. */ inline flecs::entity world::primitive(flecs::meta::primitive_kind_t kind) { ecs_primitive_desc_t desc = {}; desc.kind = kind; @@ -34681,7 +37882,7 @@ inline flecs::entity world::primitive(flecs::meta::primitive_kind_t kind) { return flecs::entity(world_, eid); } -/** Create array type. */ +/** Create an array type. */ inline flecs::entity world::array(flecs::entity_t elem_id, int32_t array_count) { ecs_array_desc_t desc = {}; desc.type = elem_id; @@ -34691,7 +37892,7 @@ inline flecs::entity world::array(flecs::entity_t elem_id, int32_t array_count) return flecs::entity(world_, eid); } -/** Create array type. */ +/** Create an array type. */ template inline flecs::entity world::array(int32_t array_count) { return this->array(_::type::id(world_), array_count); @@ -34738,16 +37939,16 @@ inline int ecs_serializer_t::member(const char *name) const { namespace flecs { inline units::units(flecs::world& world) { - /* Import C module */ + // Import C module. FlecsUnitsImport(world); - /* Bridge between C++ types and flecs.units entities */ + // Bridge between C++ types and flecs.units entities. world.module(); - // Initialize world.entity(prefixes) scope + // Initialize world.entity(prefixes) scope. world.entity("::flecs::units::prefixes"); - // Initialize prefixes + // Initialize prefixes. world.entity("::flecs::units::prefixes::Yocto"); world.entity("::flecs::units::prefixes::Zepto"); world.entity("::flecs::units::prefixes::Atto"); @@ -34777,7 +37978,7 @@ inline units::units(flecs::world& world) { world.entity("::flecs::units::prefixes::Zebi"); world.entity("::flecs::units::prefixes::Yobi"); - // Initialize quantities + // Initialize quantities. world.entity("::flecs::units::Duration"); world.entity iter::field(int8_t index) const { - ecs_assert(!(iter_->flags & EcsIterCppEach) || + ecs_assert(!(iter_->flags & EcsIterCppEach) || ecs_field_src(iter_, index) != 0, ECS_INVALID_OPERATION, "cannot .field from .each, use .field_at<%s>(%d, row) instead", _::type_name(), index); return get_field(index); } -template ::value == false, void>::type*> +/** Get field data for a mutable component type. */ +template >> inline flecs::field iter::field(int8_t index) const { - ecs_assert(!(iter_->flags & EcsIterCppEach) || + ecs_assert(!(iter_->flags & EcsIterCppEach) || ecs_field_src(iter_, index) != 0, ECS_INVALID_OPERATION, "cannot .field from .each, use .field_at<%s>(%d, row) instead", _::type_name(), index); @@ -35709,22 +38953,24 @@ inline flecs::field iter::field(int8_t index) const { return get_field(index); } +/** Get the value of a variable by ID. */ inline flecs::entity iter::get_var(int var_id) const { ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, 0); return flecs::entity(iter_->world, ecs_iter_get_var(iter_, var_id)); } -/** Get value of variable by name. - * Get value of a query variable for current result. +/** Get the value of a variable by name. + * Get the value of a query variable for the current result. */ inline flecs::entity iter::get_var(const char *name) const { const flecs::query_t *q = iter_->query; int var_id = ecs_query_find_var(q, name); - ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, name); + ecs_assert(var_id != -1, ECS_INVALID_PARAMETER, "%s", name); return flecs::entity(iter_->world, ecs_iter_get_var(iter_, var_id)); } +/** Iterate over targets for a field. */ template void iter::targets(int8_t index, const Func& func) { ecs_assert(iter_->table != nullptr, ECS_INVALID_OPERATION, NULL); @@ -35735,9 +38981,9 @@ void iter::targets(int8_t index, const Func& func) { int32_t i = tr->index, end = i + tr->count; for (; i < end; i ++) { ecs_id_t id = table_type->array[i]; - ecs_assert(ECS_IS_PAIR(id), ECS_INVALID_PARAMETER, + ecs_assert(ECS_IS_PAIR(id), ECS_INVALID_PARAMETER, "field does not match a pair"); - flecs::entity tgt(iter_->world, + flecs::entity tgt(iter_->world, ecs_pair_second(iter_->real_world, id)); func(tgt); } @@ -35752,16 +38998,18 @@ void iter::targets(int8_t index, const Func& func) { #pragma once -namespace flecs +namespace flecs { +/** Initialize built-in components. */ inline void world::init_builtin_components() { this->component(); this->component(); this->component(); + this->component(); /* If meta is not defined and we're using enum reflection, make sure that - * primitive types are registered. This makes sure we can set components of + * primitive types are registered. This ensures we can set components of * underlying_type_t when registering constants. */ # if !defined(FLECS_META) && !defined(FLECS_CPP_NO_ENUM_REFLECTION) this->component("flecs::meta::u8"); @@ -35794,18 +39042,20 @@ inline void world::init_builtin_components() { # endif } +/** Import a type (entity/component) as an alias. */ template inline flecs::entity world::use(const char *alias) const { entity_t e = _::type::id(world_); const char *name = alias; if (!name) { - // If no name is defined, use the entity name without the scope + // If no name is defined, use the entity name without the scope. name = ecs_get_name(world_, e); } ecs_set_alias(world_, e, name); return flecs::entity(world_, e); } +/** Import an entity by name as an alias. */ inline flecs::entity world::use(const char *name, const char *alias) const { entity_t e = ecs_lookup_path_w_sep(world_, 0, name, "::", "::", true); ecs_assert(e != 0, ECS_INVALID_PARAMETER, NULL); @@ -35814,35 +39064,41 @@ inline flecs::entity world::use(const char *name, const char *alias) const { return flecs::entity(world_, e); } +/** Import an entity as an alias. */ inline void world::use(flecs::entity e, const char *alias) const { entity_t eid = e.id(); const char *name = alias; if (!name) { - // If no name is defined, use the entity name without the scope + // If no name is defined, use the entity name without the scope. name = ecs_get_name(world_, eid); } ecs_set_alias(world_, eid, name); } +/** Set the current scope. */ inline flecs::entity world::set_scope(const flecs::entity_t s) const { return flecs::entity(ecs_set_scope(world_, s)); } +/** Get the current scope. */ inline flecs::entity world::get_scope() const { return flecs::entity(world_, ecs_get_scope(world_)); } +/** Set the current scope to a type. */ template inline flecs::entity world::set_scope() const { - return set_scope( _::type::id(world_) ); + return set_scope( _::type::id(world_) ); } +/** Look up an entity by name. */ inline entity world::lookup(const char *name, const char *sep, const char *root_sep, bool recursive) const { auto e = ecs_lookup_path_w_sep(world_, 0, name, sep, root_sep, recursive); return flecs::entity(*this, e); } #ifndef ensure +/** Ensure a singleton component exists and return a mutable reference. */ template inline T& world::ensure() const { flecs::entity e(world_, _::type::id(world_)); @@ -35850,233 +39106,274 @@ inline T& world::ensure() const { } #endif +/** Mark a singleton component as modified. */ template inline void world::modified() const { flecs::entity e(world_, _::type::id(world_)); e.modified(); } +/** Set a pair component value on a singleton. */ template inline void world::set(Second second, const First& value) const { flecs::entity e(world_, _::type::id(world_)); e.set(second, value); } +/** Set a pair component value on a singleton (move). */ template inline void world::set(Second second, First&& value) const { flecs::entity e(world_, _::type::id(world_)); e.set(second, value); } +/** Get a ref for a singleton component. */ template inline ref world::get_ref() const { flecs::entity e(world_, _::type::id(world_)); return e.get_ref(); } +/** Try to get a singleton value by component ID (returns nullptr if not found). */ inline const void* world::try_get(flecs::id_t id) const { flecs::entity e(world_, id); return e.try_get(id); } +/** Try to get a singleton pair value by first and second IDs (returns nullptr if not found). */ inline const void* world::try_get(flecs::entity_t r, flecs::entity_t t) const { flecs::entity e(world_, r); return e.try_get(r, t); } +/** Try to get a singleton component (returns nullptr if not found). */ template inline const T* world::try_get() const { flecs::entity e(world_, _::type::id(world_)); return e.try_get(); } +/** Try to get a singleton pair component (returns nullptr if not found). */ template inline const A* world::try_get() const { flecs::entity e(world_, _::type::id(world_)); return e.try_get(); } +/** Try to get a singleton pair component by second entity (returns nullptr if not found). */ template inline const First* world::try_get(Second second) const { flecs::entity e(world_, _::type::id(world_)); return e.try_get(second); } +/** Get a singleton component value by component ID. */ inline const void* world::get(flecs::id_t id) const { flecs::entity e(world_, id); return e.get(id); } +/** Get a singleton pair component value by first and second IDs. */ inline const void* world::get(flecs::entity_t r, flecs::entity_t t) const { flecs::entity e(world_, r); return e.get(r, t); } +/** Get a singleton component. */ template inline const T& world::get() const { flecs::entity e(world_, _::type::id(world_)); return e.get(); } +/** Get a singleton pair component. */ template inline const A& world::get() const { flecs::entity e(world_, _::type::id(world_)); return e.get(); } +/** Get a singleton pair component by second entity. */ template const First& world::get(Second second) const { flecs::entity e(world_, _::type::id(world_)); return e.get(second); } +/** Try to get a mutable singleton component by ID (returns nullptr if not found). */ inline void* world::try_get_mut(flecs::id_t id) const { flecs::entity e(world_, id); return e.try_get_mut(id); } +/** Try to get a mutable singleton pair component by first and second IDs (returns nullptr if not found). */ inline void* world::try_get_mut(flecs::entity_t r, flecs::entity_t t) const { flecs::entity e(world_, r); return e.try_get_mut(r, t); } +/** Try to get a mutable singleton component (returns nullptr if not found). */ template inline T* world::try_get_mut() const { flecs::entity e(world_, _::type::id(world_)); return e.try_get_mut(); } +/** Try to get a mutable singleton pair component (returns nullptr if not found). */ template inline A* world::try_get_mut() const { flecs::entity e(world_, _::type::id(world_)); return e.try_get_mut(); } +/** Try to get a mutable singleton pair component by second entity (returns nullptr if not found). */ template inline First* world::try_get_mut(Second second) const { flecs::entity e(world_, _::type::id(world_)); return e.try_get_mut(second); } +/** Get a mutable singleton component by ID. */ inline void* world::get_mut(flecs::id_t id) const { flecs::entity e(world_, id); return e.get_mut(id); } +/** Get a mutable singleton pair component by first and second IDs. */ inline void* world::get_mut(flecs::entity_t r, flecs::entity_t t) const { flecs::entity e(world_, r); return e.get_mut(r, t); } +/** Get a mutable singleton component. */ template inline T& world::get_mut() const { flecs::entity e(world_, _::type::id(world_)); return e.get_mut(); } +/** Get a mutable singleton pair component. */ template inline A& world::get_mut() const { flecs::entity e(world_, _::type::id(world_)); return e.get_mut(); } +/** Get a mutable singleton pair component by second entity. */ template inline First& world::get_mut(Second second) const { flecs::entity e(world_, _::type::id(world_)); return e.get_mut(second); } +/** Check for singleton component. */ template inline bool world::has() const { flecs::entity e(world_, _::type::id(world_)); return e.has(); } +/** Check for singleton pair component. */ template inline bool world::has() const { flecs::entity e(world_, _::type::id(world_)); return e.has(); } +/** Check for singleton pair component. */ template inline bool world::has(flecs::id_t second) const { flecs::entity e(world_, _::type::id(world_)); return e.has(second); } +/** Check for singleton pair by entity IDs. */ inline bool world::has(flecs::id_t first, flecs::id_t second) const { flecs::entity e(world_, first); return e.has(first, second); } +/** Check for singleton enum constant. */ template ::value > > inline bool world::has(E value) const { flecs::entity e(world_, _::type::id(world_)); return e.has(value); } +/** Add a singleton component. */ template inline void world::add() const { flecs::entity e(world_, _::type::id(world_)); e.add(); } +/** Add a singleton pair component. */ template inline void world::add() const { flecs::entity e(world_, _::type::id(world_)); e.add(); } +/** Add a singleton pair component. */ template inline void world::add(flecs::entity_t second) const { flecs::entity e(world_, _::type::id(world_)); e.add(second); } +/** Add a singleton pair by entity IDs. */ inline void world::add(flecs::entity_t first, flecs::entity_t second) const { flecs::entity e(world_, first); e.add(first, second); } +/** Add a singleton enum constant value. */ template ::value > > inline void world::add(E value) const { flecs::entity e(world_, _::type::id(world_)); e.add(value); } +/** Remove a singleton component. */ template inline void world::remove() const { flecs::entity e(world_, _::type::id(world_)); e.remove(); } +/** Remove a singleton pair component. */ template inline void world::remove() const { flecs::entity e(world_, _::type::id(world_)); e.remove(); } +/** Remove a singleton pair component by second entity. */ template inline void world::remove(flecs::entity_t second) const { flecs::entity e(world_, _::type::id(world_)); e.remove(second); } +/** Remove a singleton pair by entity IDs. */ inline void world::remove(flecs::entity_t first, flecs::entity_t second) const { flecs::entity e(world_, first); e.remove(first, second); } +/** Iterate over children of the root entity. */ template inline void world::children(Func&& f) const { this->entity(0).children(FLECS_FWD(f)); } +/** Get the singleton entity for a component type. */ template inline flecs::entity world::singleton() const { return flecs::entity(world_, _::type::id(world_)); } +/** Get the target entity for a relationship on a singleton. */ template inline flecs::entity world::target(int32_t index) const { @@ -36084,6 +39381,7 @@ inline flecs::entity world::target(int32_t index) const ecs_get_target(world_, _::type::id(world_), _::type::id(world_), index)); } +/** Get the target entity for a relationship on a component entity. */ template inline flecs::entity world::target( flecs::entity_t relationship, @@ -36093,6 +39391,7 @@ inline flecs::entity world::target( ecs_get_target(world_, _::type::id(world_), relationship, index)); } +/** Get the target entity for a relationship. */ inline flecs::entity world::target( flecs::entity_t relationship, int32_t index) const @@ -36101,6 +39400,7 @@ inline flecs::entity world::target( ecs_get_target(world_, relationship, relationship, index)); } +/** Get a singleton component using a callback. */ template ::value > > inline void world::get(const Func& func) const { static_assert(arity::value == 1, "singleton component must be the only argument"); @@ -36108,6 +39408,7 @@ inline void world::get(const Func& func) const { this->world_, this->singleton>(), func); } +/** Set a singleton component using a callback. */ template ::value > > inline void world::set(const Func& func) const { static_assert(arity::value == 1, "singleton component must be the only argument"); @@ -36115,21 +39416,25 @@ inline void world::set(const Func& func) const { this->world_, this->singleton>(), func); } +/** Get an alive entity from an ID. */ inline flecs::entity world::get_alive(flecs::entity_t e) const { e = ecs_get_alive(world_, e); return flecs::entity(world_, e); } +/** Ensure an entity ID is alive. */ inline flecs::entity world::make_alive(flecs::entity_t e) const { ecs_make_alive(world_, e); return flecs::entity(world_, e); } +/** Get the entity for an enum type. */ template inline flecs::entity enum_data::entity() const { return flecs::entity(world_, _::type::id(world_)); } +/** Get the entity for an enum constant by underlying_type value. */ template inline flecs::entity enum_data::entity(underlying_type_t value) const { int index = index_by_value(value); @@ -36139,7 +39444,7 @@ inline flecs::entity enum_data::entity(underlying_type_t value) const { return flecs::entity(world_, entity); } #ifdef FLECS_META - // Reflection data lookup failed. Try value lookup amongst flecs::Constant relationships + // Reflection data lookup failed. Try a value lookup among flecs::Constant relationships. flecs::world world = flecs::world(world_); return world.query_builder() .with(flecs::ChildOf, world.id()) @@ -36154,24 +39459,27 @@ inline flecs::entity enum_data::entity(underlying_type_t value) const { #endif } +/** Get the entity for an enum constant. */ template inline flecs::entity enum_data::entity(E value) const { return entity(static_cast>(value)); } -/** Use provided scope for operations ran on returned world. - * Operations need to be ran in a single statement. +/** Use the provided scope for operations run on the returned world. + * Operations need to be run in a single statement. */ inline flecs::scoped_world world::scope(id_t parent) const { return scoped_world(world_, parent); } +/** Use the provided scope (by type) for operations run on the returned world. */ template inline flecs::scoped_world world::scope() const { flecs::id_t parent = _::type::id(world_); return scoped_world(world_, parent); } +/** Use the provided scope (by name) for operations run on the returned world. */ inline flecs::scoped_world world::scope(const char* name) const { return scope(entity(name)); } @@ -36181,7 +39489,7 @@ inline flecs::scoped_world world::scope(const char* name) const { /** * @defgroup cpp_core Core - * Core ECS functionality (entities, storage, queries) + * Core ECS functionality (entities, storage, queries). * * @{ * @} diff --git a/src/tests.zig b/src/tests.zig index bdc6ae7..6e579c5 100644 --- a/src/tests.zig +++ b/src/tests.zig @@ -485,7 +485,7 @@ test "zflecs.struct-dtor-hook" { ecs.COMPONENT(world, Chat); { - var system_desc = ecs.system_desc_t{}; + var system_desc = ecs.system_desc_t{ .phase = ecs.OnUpdate }; system_desc.callback = struct { pub fn chatSystem(it: *ecs.iter_t) callconv(.c) void { const chat_components = ecs.field(it, Chat, 0).?; @@ -495,7 +495,7 @@ test "zflecs.struct-dtor-hook" { } }.chatSystem; system_desc.query.terms[0] = .{ .id = ecs.id(Chat) }; - _ = ecs.SYSTEM(world, "Chat system", ecs.OnUpdate, &system_desc); + _ = ecs.SYSTEM(world, "Chat system", &system_desc); } const chat_entity = ecs.new_entity(world, "Chat entity"); diff --git a/src/zflecs.zig b/src/zflecs.zig index fe1d80a..7e9b5f0 100644 --- a/src/zflecs.zig +++ b/src/zflecs.zig @@ -6,7 +6,7 @@ const build_options = @import("build-options"); pub const flecs_version = std.SemanticVersion{ .major = 4, .minor = 1, - .patch = 4, + .patch = 5, }; const flecs_is_sanitize = build_options.debug_mode == .sanitize or @@ -166,14 +166,14 @@ pub const EcsTermReflexive = 1 << 3; pub const EcsTermIdInherited = 1 << 4; pub const EcsTermIsTrivial = 1 << 5; // 6 missing in flecs -pub const EcsTermIsCacheable = 1 << 7; -pub const EcsTermIsScope = 1 << 8; -pub const EcsTermIsMember = 1 << 9; -pub const EcsTermIsToggle = 1 << 10; -pub const EcsTermKeepAlive = 1 << 11; -pub const EcsTermIsSparse = 1 << 12; -pub const EcsTermIsOr = 1 << 13; -pub const EcsTermDontFragment = 1 << 14; +pub const EcsTermIsCacheable = 1 << 6; +pub const EcsTermIsScope = 1 << 7; +pub const EcsTermIsMember = 1 << 8; +pub const EcsTermIsToggle = 1 << 9; +pub const EcsTermIsSparse = 1 << 10; +pub const EcsTermIsOr = 1 << 11; +pub const EcsTermDontFragment = 1 << 12; +pub const EcsTermNonFragmentingChildOf = 1 << 13; // Observer flags @@ -190,11 +190,12 @@ pub const EcsObserverKeepAlive = 1 << 11; // Table flags (used by ecs_table_t::flags) -pub const EcsTableHasBuiltins = 1 << 1; -pub const EcsTableIsPrefab = 1 << 2; -pub const EcsTableHasIsA = 1 << 3; -pub const EcsTableHasMultiIsA = 1 << 4; -pub const EcsTableHasChildOf = 1 << 5; +pub const EcsTableHasBuiltins = 1 << 0; +pub const EcsTableIsPrefab = 1 << 1; +pub const EcsTableHasIsA = 1 << 2; +pub const EcsTableHasMultiIsA = 1 << 3; +pub const EcsTableHasChildOf = 1 << 4; +pub const EcsTableHasParent = 1 << 5; pub const EcsTableHasName = 1 << 6; pub const EcsTableHasPairs = 1 << 7; pub const EcsTableHasModule = 1 << 8; @@ -238,6 +239,7 @@ pub const EcsAperiodicComponentMonitors = 1 << 2; pub const EcsAperiodicEmptyQueries = 1 << 4; // Extern declarations +extern const EcsParentDepth: entity_t; extern const EcsQuery: entity_t; extern const EcsObserver: entity_t; extern const EcsSystem: entity_t; @@ -276,7 +278,6 @@ extern const EcsDependsOn: entity_t; extern const EcsSlotOf: entity_t; extern const EcsOrderedChildren: entity_t; extern const EcsModule: entity_t; -extern const EcsPrivate: entity_t; extern const EcsPrefab: entity_t; extern const EcsDisabled: entity_t; extern const EcsNotQueryable: entity_t; @@ -320,6 +321,11 @@ pub const EcsDefaultChildComponent = extern struct { component: id_t, }; +pub extern const FLECS_IDEcsParentID_: entity_t; +pub const EcsParent = extern struct { + value: entity_t, +}; + pub var Query: entity_t = undefined; pub var Observer: entity_t = undefined; pub var System: entity_t = undefined; @@ -358,7 +364,6 @@ pub var DependsOn: entity_t = undefined; pub var SlotOf: entity_t = undefined; pub var OrderedChildren: entity_t = undefined; pub var Module: entity_t = undefined; -pub var Private: entity_t = undefined; pub var Prefab: entity_t = undefined; pub var Disabled: entity_t = undefined; pub var NotQueryable: entity_t = undefined; @@ -542,6 +547,7 @@ pub const system_desc_t = extern struct { _canary: i32 = 0, entity: entity_t = 0, query: query_desc_t = .{}, + phase: entity_t = 0, callback: ?iter_action_t = null, run: ?run_action_t = null, ctx: ?*anyopaque = null, @@ -1139,6 +1145,7 @@ pub const observer_desc_t = extern struct { events: [FLECS_EVENT_DESC_MAX]entity_t = [_]entity_t{0} ** FLECS_EVENT_DESC_MAX, yield_existing: bool = false, + global_observer: bool = false, callback: ?iter_action_t, run: ?run_action_t = null, ctx: ?*anyopaque = null, @@ -1388,7 +1395,6 @@ pub fn init() *world_t { SlotOf = EcsSlotOf; OrderedChildren = EcsOrderedChildren; Module = EcsModule; - Private = EcsPrivate; Prefab = EcsPrefab; Disabled = EcsDisabled; NotQueryable = EcsNotQueryable; @@ -2904,15 +2910,11 @@ pub fn TAG(world: *world_t, comptime T: type) void { pub fn SYSTEM( world: *world_t, name: [*:0]const u8, - phase: entity_t, system_desc: *system_desc_t, ) entity_t { var entity_desc = entity_desc_t{}; entity_desc.id = new_id(world); entity_desc.name = name; - const first = if (phase != 0) pair(EcsDependsOn, phase) else 0; - const second = phase; - entity_desc.add = &.{ first, second, 0 }; system_desc.entity = entity_init(world, &entity_desc); return system_init(world, system_desc); @@ -3023,7 +3025,8 @@ pub fn ADD_SYSTEM( comptime fn_system: anytype, ) entity_t { var desc = SYSTEM_DESC(fn_system); - return SYSTEM(world, name, phase, &desc); + desc.phase = phase; + return SYSTEM(world, name, &desc); } /// Creates a system description and adds it to the world, from function parameters @@ -3036,7 +3039,8 @@ pub fn ADD_SYSTEM_WITH_FILTERS( filters: []const term_t, ) entity_t { var desc = SYSTEM_DESC_WITH_FILTERS(fn_system, filters); - return SYSTEM(world, name, phase, &desc); + desc.phase = phase; + return SYSTEM(world, name, &desc); } pub fn new_entity(world: *world_t, name: [*:0]const u8) entity_t { @@ -3415,7 +3419,7 @@ extern fn ecs_import_c(world: *world_t, module: module_action_t, module_name_c: /// `pub fn module_init(world: *world_t, c_name: [*:0]const u8, desc: *component_desc_t) entity_t` pub const module_init = ecs_module_init; -extern fn ecs_module_init(world: *world_t, c_name: [*:0]const u8, desc: *component_desc_t) entity_t; +extern fn ecs_module_init(world: *world_t, c_name: [*:0]const u8, desc: *const component_desc_t) entity_t; //-------------------------------------------------------------------------------------------------- // @@ -3485,10 +3489,11 @@ pub const member_t = extern struct { pub const struct_desc_t = extern struct { entity: entity_t, members: [ECS_MEMBER_DESC_CACHE_SIZE]member_t, + create_member_entities: bool, }; pub const struct_init = ecs_struct_init; -extern fn ecs_struct_init(world: *world_t, desc: struct_desc_t) entity_t; +extern fn ecs_struct_init(world: *world_t, desc: *const struct_desc_t) entity_t; //-------------------------------------------------------------------------------------------------- //