diff --git a/distr/flecs.c b/distr/flecs.c index 0f0a7c12a2..2f0a4b4b16 100644 --- a/distr/flecs.c +++ b/distr/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, diff --git a/distr/flecs.h b/distr/flecs.h index 0ba7f65370..0841cd34a3 100644 --- a/distr/flecs.h +++ b/distr/flecs.h @@ -27,7 +27,7 @@ /** * @defgroup options API defines - * Defines for customizing compile time features. + * Defines for customizing compile-time features. * * @{ */ @@ -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,8 +145,8 @@ /** @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 @@ -178,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 @@ -207,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 @@ -219,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 @@ -260,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 @@ -278,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 @@ -286,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. */ @@ -302,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 @@ -341,13 +341,13 @@ #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 @@ -355,7 +355,7 @@ #endif /** @def FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE - * Size of depth cache in tree spawner component. Higher values speed up prefab + * 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) @@ -422,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) @@ -453,14 +453,14 @@ 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\ @@ -471,7 +471,7 @@ extern "C" { #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)]) @@ -479,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)]) @@ -499,61 +499,61 @@ 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 EcsIterImmutableCacheData (1u << 21u) /* Internally used by engine to indicate immutable arrays from cache */ +#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) */ +/* 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) @@ -581,39 +581,39 @@ extern "C" { //// 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 << 0u) /* Does table have builtin 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 table have multiple IsA pairs */ -#define EcsTableHasChildOf (1u << 4u) /* Does the table type ChildOf relationship */ -#define EcsTableHasParent (1u << 5u) /* Does the table type 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 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) @@ -638,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 } @@ -690,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 @@ -717,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" @@ -730,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 @@ -784,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 @@ -812,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. */ /* ) (.) @@ -865,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 @@ -886,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 @@ -896,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)) @@ -930,18 +930,18 @@ typedef struct ecs_allocator_t ecs_allocator_t; #elif defined(ECS_TARGET_MSVC) #define ECS_ALIGNOF(T) (int64_t)__alignof(T) #else -/* Use struct trick since on 32 bit platforms __alignof__ can return different +/* 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 + * __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 + * __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 @@ -972,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) @@ -1015,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) @@ -1023,7 +1023,7 @@ typedef struct ecs_allocator_t ecs_allocator_t; //////////////////////////////////////////////////////////////////////////////// -//// Entity id macros +//// Entity ID macros //////////////////////////////////////////////////////////////////////////////// #define ECS_ROW_MASK (0x0FFFFFFFu) @@ -1052,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_ @@ -1090,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 @@ -1183,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]. @@ -1210,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. */ @@ -1252,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++): * @@ -1291,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 @@ -1327,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; /** @} */ @@ -1356,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, @@ -1372,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, @@ -1380,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, @@ -1478,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, @@ -1488,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, @@ -1499,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, @@ -1506,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, @@ -1516,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, @@ -1526,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, @@ -1537,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, @@ -1545,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, @@ -1552,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))) @@ -1606,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, @@ -1643,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, @@ -1748,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)) @@ -1831,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 @@ -1941,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, @@ -2042,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 @@ -2215,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, @@ -2266,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 @@ -2357,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){} @@ -2364,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)) @@ -2530,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. */ @@ -2543,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. * * @{ */ @@ -2566,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. */ @@ -2574,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. */ @@ -2658,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)( @@ -2669,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)( @@ -2690,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)( @@ -2737,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. */ @@ -2771,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. */ @@ -2804,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. */ @@ -2832,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. */ @@ -2845,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: * @@ -2888,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. * @@ -2981,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)) @@ -3024,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) @@ -3069,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 @@ -3086,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) @@ -3099,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 @@ -3111,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 @@ -3123,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 @@ -3135,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 @@ -3147,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 @@ -3157,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. @@ -3166,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. @@ -3186,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. */ @@ -3204,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 @@ -3223,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 @@ -3234,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. @@ -3336,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); @@ -3349,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, @@ -3367,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, @@ -3387,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, @@ -3429,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, @@ -3454,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) @@ -3503,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 */ @@ -3515,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 */ @@ -3547,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 @@ -3562,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. */ - void *ctx; /**< User context to pass to callback */ - void *binding_ctx; /**< Context to be used for language bindings */ + /** 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_entity_t entity; /**< Entity associated with query (optional) */ + ecs_query_cache_kind_t cache_kind; /**< Caching policy of the query. */ + + 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. */ - /** Observer events */ + ecs_query_t *query; /**< Observer query. */ + + /** 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. */ }; /** @} */ @@ -3702,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. */ }; @@ -3799,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; @@ -3831,17 +4779,17 @@ struct ecs_observable_t { 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, @@ -3851,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; @@ -3896,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 @@ -3962,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. @@ -4064,7 +5012,7 @@ bool flecs_type_info_equals( const void *b, const ecs_type_info_t *type_info); -/** Create allocated string from format. +/** Create an allocated string from a format. * * @param fmt The format string. * @param args Format arguments. @@ -4075,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. @@ -4086,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 @@ -4102,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. */ @@ -4111,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. */ @@ -4129,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( @@ -4145,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. * @@ -4165,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 { @@ -4206,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. */ @@ -4223,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. @@ -4232,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. @@ -4247,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. @@ -4256,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( @@ -4302,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. @@ -4313,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. @@ -4331,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. */ @@ -4344,18 +5293,18 @@ void flecs_check_exclusive_world_access_read( #define flecs_check_exclusive_world_access_read(world) #endif -/** End deferred mode (executes commands when stage->deref becomes 0). */ +/** 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 current value of operation counter. - * The journaling addon keeps track of an operation counter which is incremented +/** 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. + * This value is not thread-safe. * * @return The operation counter. */ @@ -4363,7 +5312,7 @@ 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 @@ -4374,7 +5323,7 @@ int flecs_journal_get_counter(void); #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) \ @@ -4411,31 +5360,44 @@ int flecs_journal_get_counter(void); 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, @@ -4445,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, @@ -4459,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, @@ -4469,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, @@ -4480,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, @@ -4490,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, @@ -4501,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, @@ -4516,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, @@ -4532,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)) @@ -4561,44 +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/how many non-fragmenting children are stored in table for parent. */ +/* 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 table only contains a single entity for parent, this will contain the entity id (without generation). */ - int32_t count; /* The number of children for a parent in the table. */ + 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: @@ -4615,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(). * @@ -4648,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(). * @@ -4658,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(). * @@ -4682,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. @@ -4691,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(). @@ -4701,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() @@ -4717,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 @@ -4726,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 @@ -4739,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(). * @@ -4761,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 @@ -4772,10 +5816,10 @@ FLECS_ALWAYS_INLINE ecs_component_record_t* flecs_components_get( const ecs_world_t *world, ecs_id_t id); -/* Ensure component record for component id - * +/** Ensure a component record for a component ID. + * * @param world The world. - * @param id The component id. + * @param id The component ID. * @return The new or existing component record. */ FLECS_API @@ -4783,36 +5827,37 @@ FLECS_ALWAYS_INLINE ecs_component_record_t* flecs_components_ensure( ecs_world_t *world, ecs_id_t id); -/** Get component id from component record. - * +/** 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); -/** Get type info for component record. +/** Get the type info for a component record. * * @param cr The component record. - * @return The type info struct, or NULL if component is a tag. + * @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 table record for component record. - * This operation returns the table record for the table/component record if it +/** 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. @@ -4824,14 +5869,14 @@ FLECS_ALWAYS_INLINE const ecs_table_record_t* flecs_component_get_table( const ecs_component_record_t *cr, const ecs_table_t *table); -/** Ger parent record for component/table. +/** 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. + * 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 + * 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 @@ -4847,7 +5892,7 @@ FLECS_ALWAYS_INLINE ecs_parent_record_t* flecs_component_get_parent_record( const ecs_component_record_t *cr, const ecs_table_t *table); -/** Return hierarchy depth for component record. +/** 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. @@ -4859,7 +5904,7 @@ FLECS_API FLECS_ALWAYS_INLINE int32_t flecs_component_get_childof_depth( const ecs_component_record_t *cr); -/** Create component record iterator. +/** Create a component record iterator. * A component record iterator iterates all tables for the specified component * record. * @@ -4885,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. @@ -4901,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. @@ -4911,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. @@ -4920,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 @@ -4967,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. */ @@ -4977,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; @@ -5013,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 @@ -5043,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; @@ -5071,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: @@ -5090,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. */ }; @@ -5174,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 @@ -5201,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; @@ -5226,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; @@ -5245,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; @@ -5275,39 +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. */ + * 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). */ @@ -5324,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(). @@ -5333,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 @@ -5356,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; @@ -5370,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 @@ -5463,74 +6508,77 @@ 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. */ +/** Non-fragmenting ChildOf relationship. */ typedef struct EcsParent { - ecs_entity_t value; + ecs_entity_t value; /**< Parent entity. */ } EcsParent; -/* Component with data to instantiate a non-fragmenting tree. */ +/** Component with data to instantiate a non-fragmenting tree. */ typedef struct { - const char *child_name; /* Name of prefab child */ - ecs_table_t *table; /* Table in which child will be stored */ - uint32_t child; /* Prefab child entity (without generation) */ - int32_t parent_index; /* Index into children vector */ + 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_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 { - /* 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. */ - ecs_tree_spawner_t data[FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE]; + ecs_tree_spawner_t data[FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE]; /**< Cache data indexed by depth. */ } EcsTreeSpawner; /** @} */ @@ -5570,49 +6618,49 @@ 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; -/** Indicates that the target of a pair is an integer value. */ +/** 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); -/** Parent 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. */ +/** DefaultChildComponent component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsDefaultChildComponent); /** Relationship storing the entity's depth in a non-fragmenting hierarchy. */ @@ -5627,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 @@ -5669,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 @@ -5678,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. * @@ -5693,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; @@ -5716,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 @@ -5725,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: * @@ -5736,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: * @@ -5754,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: * @@ -5773,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: * @@ -5784,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: * @@ -5795,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. */ @@ -5814,23 +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 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; @@ -5839,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. */ @@ -5864,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; @@ -5880,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. */ @@ -5901,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. */ @@ -5921,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()) */ +/** 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 */ /** @} */ @@ -5960,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); @@ -5969,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( @@ -5996,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. * @@ -6007,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, @@ -6022,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 ++) { @@ -6040,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]; @@ -6048,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( @@ -6087,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. @@ -6108,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. * @@ -6170,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. @@ -6190,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: @@ -6218,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. * @@ -6250,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 @@ -6264,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: @@ -6278,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 @@ -6294,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. @@ -6309,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. @@ -6329,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() */ @@ -6357,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 @@ -6371,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. @@ -6393,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. @@ -6408,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 @@ -6426,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. @@ -6441,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. @@ -6467,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(). * @@ -6478,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. */ @@ -6486,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( @@ -6509,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 @@ -6519,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 @@ -6555,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( @@ -6602,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 @@ -6610,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. @@ -6623,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. @@ -6638,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( @@ -6650,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 @@ -6677,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 @@ -6704,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. @@ -6720,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 @@ -6739,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 @@ -6747,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( @@ -6776,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 @@ -6786,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( @@ -6795,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 @@ -6838,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 @@ -6862,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. @@ -6906,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. * @@ -6919,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. * @@ -6927,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 @@ -6943,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( @@ -6957,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( @@ -6965,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. @@ -6988,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. * @@ -7001,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. @@ -7018,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 @@ -7039,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. @@ -7059,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( @@ -7087,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: @@ -7118,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 @@ -7131,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. @@ -7156,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. @@ -7167,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 @@ -7179,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(). @@ -7206,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. @@ -7221,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 @@ -7241,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. @@ -7260,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. @@ -7288,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 @@ -7306,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() @@ -7330,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. @@ -7345,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. * @@ -7361,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. @@ -7388,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. @@ -7419,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. * @@ -7449,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. @@ -7474,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 @@ -7493,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. @@ -7506,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() */ @@ -7564,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. * @@ -7587,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. @@ -7600,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 @@ -7630,7 +8685,7 @@ uint32_t ecs_get_version( /** * @defgroup entity_info Entity Information. - * Get information from entity. + * Get information from an entity. * * @{ */ @@ -7650,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. @@ -7669,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(). * @@ -7685,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)) @@ -7757,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 @@ -7800,7 +8855,7 @@ ecs_entity_t ecs_new_w_parent( * 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 @@ -7811,7 +8866,7 @@ ecs_entity_t ecs_new_w_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 @@ -7821,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. @@ -7837,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( @@ -7864,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() */ @@ -7878,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() */ @@ -7910,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. @@ -7925,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. @@ -7942,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 @@ -7962,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. * @@ -7982,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. @@ -7997,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() @@ -8013,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 @@ -8022,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. * @@ -8040,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. @@ -8066,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. @@ -8075,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() */ @@ -8088,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. @@ -8111,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. * @@ -8136,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. @@ -8166,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. @@ -8177,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() */ @@ -8208,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. @@ -8247,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( @@ -8278,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. @@ -8292,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. * @@ -8331,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. @@ -8360,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 @@ -8432,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( 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" @@ -8447,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. @@ -8458,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. @@ -8471,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( @@ -8491,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. @@ -8507,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. @@ -8517,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. * @@ -8529,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. @@ -8564,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. @@ -8579,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: @@ -8598,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); @@ -8613,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, @@ -8629,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)); @@ -8637,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: * @@ -8650,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. @@ -8690,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 @@ -8706,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(). * @@ -8719,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. @@ -8731,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 @@ -8747,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 @@ -8819,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. @@ -8830,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. @@ -8844,7 +9901,7 @@ 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. */ @@ -8854,7 +9911,7 @@ bool ecs_query_has( 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. @@ -8868,7 +9925,7 @@ 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. */ @@ -8878,7 +9935,7 @@ bool ecs_query_has_table( 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. @@ -8900,7 +9957,7 @@ 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. */ @@ -8910,19 +9967,19 @@ bool ecs_query_has_range( 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(). @@ -8934,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(). @@ -8953,7 +10010,7 @@ char* ecs_query_plan_w_profile( const ecs_query_t *query, const ecs_iter_t *it); -/** Same as ecs_query_plan(), but includes plan for populating cache (if any). +/** Same as ecs_query_plan(), but includes the plan for populating the cache (if any). * * @param query The query. * @return The query plan. @@ -8962,22 +10019,22 @@ FLECS_API char* ecs_query_plans( const ecs_query_t *query); -/** Populate variables from key-value string. +/** 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( @@ -8985,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. @@ -9032,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. */ @@ -9043,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. * @@ -9059,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. @@ -9070,7 +10122,7 @@ void ecs_iter_set_group( ecs_iter_t *it, uint64_t group_id); -/** Return map with query groups. +/** 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: * @@ -9099,7 +10151,7 @@ FLECS_API const ecs_map_t* ecs_query_get_groups( const ecs_query_t *query); -/** Get context of query group. +/** Get the context of a query group. * This operation returns the context of a query group as returned by the * on_group_create callback. * @@ -9112,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. * @@ -9127,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. @@ -9144,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. @@ -9153,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. @@ -9174,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() */ @@ -9198,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. * @@ -9228,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. @@ -9256,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. @@ -9267,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. @@ -9280,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. @@ -9322,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. @@ -9337,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); @@ -9351,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. @@ -9382,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. @@ -9398,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. @@ -9415,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. @@ -9426,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). @@ -9444,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. @@ -9462,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. @@ -9480,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. * @@ -9496,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 @@ -9521,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. * @@ -9563,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( @@ -9599,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. @@ -9616,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. @@ -9637,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; * } @@ -9655,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 @@ -9683,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. @@ -9722,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. * @@ -9746,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. @@ -9758,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. @@ -9797,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. @@ -9807,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. @@ -9823,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( @@ -9838,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. * @@ -9849,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 @@ -9867,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. * @@ -9880,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. @@ -9894,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( @@ -9910,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. @@ -9922,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. @@ -9932,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. * @@ -9943,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() */ @@ -9969,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. @@ -9986,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. @@ -10002,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( @@ -10017,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( @@ -10033,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( @@ -10079,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. * @@ -10093,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. @@ -10104,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, @@ -10118,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 @@ -10150,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() @@ -10176,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. * @@ -10185,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() @@ -10219,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 @@ -10231,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 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() @@ -10272,7 +11328,21 @@ int32_t ecs_search_relation( ecs_id_t *component_out, struct ecs_table_record_t **tr_out); -/* Up traversal from entity */ +/** 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, @@ -10287,7 +11357,7 @@ int32_t ecs_search_relation_for_entity( /** 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. @@ -10301,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( @@ -10319,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( @@ -10332,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( @@ -10378,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( @@ -10391,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( @@ -10406,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( @@ -10421,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, @@ -10435,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, @@ -10449,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, @@ -10463,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, @@ -10501,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: * @@ -10541,7 +11611,7 @@ int ecs_value_move_ctor( (void)id_; \ (void)ecs_id(id_) -/** Declare & define an entity. +/** Declare and define an entity. * * Example: * @@ -10557,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: * @@ -10567,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: * @@ -10580,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: * @@ -10590,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: * @@ -10603,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: * @@ -10626,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: * @@ -10639,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: * @@ -10664,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: * @@ -10679,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: * @@ -10701,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: * @@ -10741,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) }} @@ -10772,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. * * @{ */ @@ -10788,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) @@ -10803,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)) @@ -10830,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)))) @@ -10954,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) @@ -10988,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)) @@ -11020,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)) @@ -11039,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) @@ -11069,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)); @@ -11115,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)) @@ -11155,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))) @@ -11171,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))) @@ -11187,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 */ +/** 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 */ +/** 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__}) /** @} */ @@ -11214,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, @@ -11304,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: * @@ -11318,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 @@ -11337,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)) /** @} */ @@ -11437,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. @@ -11446,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. */ @@ -11486,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, @@ -11525,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); @@ -11552,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, @@ -11563,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, @@ -11571,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, @@ -11579,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, @@ -11587,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, @@ -11595,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, @@ -11604,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, @@ -11612,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, @@ -11620,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, @@ -11628,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, @@ -11643,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 @@ -11694,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 @@ -11787,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 @@ -11814,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 @@ -11822,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 @@ -11830,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 @@ -11860,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 @@ -11875,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 @@ -11919,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. @@ -11935,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. @@ -11946,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 @@ -11970,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); @@ -11980,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) @@ -12021,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 @@ -12042,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 @@ -12069,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 @@ -12100,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. */ @@ -12125,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 @@ -12133,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( @@ -12140,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( @@ -12156,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( @@ -12165,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( @@ -12192,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. @@ -12210,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. * * @{ */ @@ -12222,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 @@ -12237,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. */ @@ -12262,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. */ @@ -12309,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. @@ -12328,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. @@ -12337,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. @@ -12352,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. */ @@ -12375,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( @@ -12384,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, @@ -12393,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 @@ -12409,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. @@ -12443,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 @@ -12478,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. */ @@ -12485,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. @@ -12512,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) @@ -12580,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; @@ -12631,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. @@ -12675,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 @@ -12694,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. @@ -12734,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 @@ -12753,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( @@ -12765,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 @@ -12776,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. @@ -12830,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. */ @@ -12870,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); @@ -12912,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. @@ -12924,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; @@ -12983,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. * @@ -13021,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. @@ -13044,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. @@ -13062,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( @@ -13126,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. */ @@ -13135,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. * * @{ */ @@ -13151,45 +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; /** 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 ran for each result returned by the system's query. This + /** 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. */ @@ -13207,67 +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; - /** Query group to iterate */ + /** Query group to iterate. */ uint64_t group_id; - /** True if a query group is configured */ + /** True if a query group is configured. */ bool group_id_set; - /** Tick source associated with system */ + /** 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. */ @@ -13279,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. @@ -13307,12 +14629,12 @@ const ecs_system_t* ecs_system_get( /** 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 + * 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. + * @param group_id The query group ID to iterate. */ FLECS_API void ecs_system_set_group( @@ -13325,7 +14647,7 @@ void ecs_system_set_group( /** 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: * @@ -13347,7 +14669,7 @@ void ecs_system_set_group( } \ 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: * @@ -13390,7 +14712,7 @@ void ecs_system_set_group( * 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. * @@ -13401,15 +14723,15 @@ void ecs_system_set_group( * 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( @@ -13418,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( @@ -13469,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 @@ -13484,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. * * @{ */ @@ -13504,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. @@ -13722,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, @@ -13778,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, @@ -13824,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, @@ -13862,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, @@ -13877,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. */ @@ -13899,190 +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_children_table_map; /** Bytes used by map for non-fragmenting ChildOf table lookups. */ - 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, 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. */ + 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_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_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. @@ -14174,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( @@ -14193,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( @@ -14269,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. */ @@ -14303,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; @@ -14353,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 @@ -14368,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. @@ -14452,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. */ @@ -14472,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. @@ -14490,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 @@ -14520,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; @@ -14538,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; @@ -14657,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. */ @@ -14673,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 @@ -14682,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. * * @{ */ @@ -14693,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. */ @@ -14717,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 @@ -14728,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 @@ -14746,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). @@ -14759,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. @@ -14777,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. @@ -14842,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. @@ -14870,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; @@ -14926,6 +16255,7 @@ 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 @@ -14940,6 +16270,7 @@ 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 @@ -14951,26 +16282,26 @@ int ecs_entity_to_json_buf( /** 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 */ - bool serialize_parents_before_children; /** If query matches both children and parent, serialize parent before children */ + 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 for if the component should be serialized */ + /** 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]). */ @@ -15030,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 @@ -15042,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 @@ -15050,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 @@ -15083,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 @@ -15111,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: @@ -15159,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). * * @{ */ @@ -15381,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 * @{ */ @@ -15393,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 * @{ */ @@ -15472,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 @@ -15484,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. * @{ */ @@ -15498,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. @@ -15551,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 @@ -15559,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. * * @{ */ @@ -15611,53 +16946,53 @@ 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. */ @@ -15677,8 +17012,8 @@ typedef void(*ecs_vector_function_callback_t)( /** 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. @@ -15709,17 +17044,17 @@ typedef struct ecs_script_function_t EcsScriptFunction; */ 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. @@ -15735,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. @@ -15762,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 @@ -15796,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 @@ -15821,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. * @@ -15847,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 @@ -15861,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 @@ -15875,9 +17214,9 @@ char* ecs_script_ast_to_str( /** 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. @@ -15889,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( @@ -15902,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( @@ -15936,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( @@ -16057,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. */ @@ -16078,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. * @@ -16121,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 @@ -16140,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. @@ -16158,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. */ @@ -16215,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( @@ -16225,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; @@ -16256,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( @@ -16270,12 +17614,13 @@ ecs_value_t ecs_const_var_get( /* Functions */ +/** Vector function callbacks for different element types. */ typedef struct ecs_vector_fn_callbacks_t { - ecs_vector_function_callback_t i8; - ecs_vector_function_callback_t i32; + 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 */ +/** Used with ecs_function_init() and ecs_method_init(). */ typedef struct ecs_function_desc_t { /** Function name. */ const char *name; @@ -16295,12 +17640,12 @@ typedef struct ecs_function_desc_t { /** 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. + * 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 members of the same type + * - 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. * @@ -16369,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( @@ -16415,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: @@ -16504,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(). @@ -16531,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; @@ -16545,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. @@ -16566,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. @@ -16632,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() @@ -16662,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); @@ -16787,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 @@ -16801,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 @@ -16814,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: * @@ -16856,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}); @@ -16873,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, @@ -16943,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, @@ -16970,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. */ @@ -16984,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. */ @@ -17012,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 @@ -17030,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; @@ -17112,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. */ @@ -17133,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_)( @@ -17166,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 @@ -17197,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); @@ -17271,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; @@ -17302,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 { @@ -17316,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, @@ -17350,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; @@ -17374,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. @@ -17472,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. @@ -17497,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. @@ -17509,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. @@ -17527,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. @@ -17573,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. @@ -17664,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. @@ -17763,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. @@ -17777,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 @@ -17821,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. @@ -17959,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 @@ -17988,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). */ @@ -18008,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; @@ -18029,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). */ @@ -18144,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 */ @@ -18264,7 +19615,7 @@ int ecs_meta_from_desc( } #endif -#endif // FLECS_META_H +#endif // FLECS_META_C_H /** @} */ @@ -18305,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); @@ -18330,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 @@ -18338,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. * * @{ */ @@ -18351,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. * @@ -18399,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( @@ -18413,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, @@ -18462,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 @@ -18502,22 +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, function allocates a buffer with ecs_os_malloc. - * Callers must free the returned pointer with ecs_os_free. */ + /* 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, function derives it from 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, @@ -18525,6 +19909,12 @@ 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, @@ -18548,17 +19938,39 @@ typedef struct ecs_cpp_component_desc_t { 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, 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, @@ -18569,13 +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 { - ecs_world_t *world; - ecs_stage_t *stage; - 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, @@ -18584,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, @@ -18592,6 +20023,15 @@ 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, @@ -18601,9 +20041,15 @@ FLECS_ALWAYS_INLINE ecs_entity_t ecs_cpp_new( 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 ecs_member_t* ecs_cpp_last_member( - const ecs_world_t *world, + const ecs_world_t *world, ecs_entity_t type); #endif @@ -18666,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 @@ -18674,171 +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; +/** 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; /** @} */ @@ -18850,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) @@ -18875,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/ */ @@ -18885,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); } } @@ -18906,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 @@ -18917,14 +20431,18 @@ 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; }; @@ -18974,46 +20492,50 @@ 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 +/** 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; @@ -19026,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_; @@ -19062,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) { @@ -19076,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) { @@ -19111,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; } @@ -19145,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 @@ -19169,6 +20720,7 @@ struct string { } } + /** Move constructor. */ string(string&& str) noexcept { ecs_os_free(str_); str_ = str.str_; @@ -19177,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_; @@ -19190,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; @@ -19210,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; @@ -19226,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; @@ -19262,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 : "") @@ -19277,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) { } }; @@ -19290,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) @@ -19332,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); @@ -19343,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<>\ @@ -19372,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 @@ -19388,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 @@ -19400,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 @@ -19426,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) @@ -19456,8 +21037,8 @@ constexpr size_t enum_template_arg_separator( func_name, pos + 1, end, depth); } -/* Use different trick on MSVC, since it uses hexadecimal representation for - * invalid enum constants. We can leverage that msvc inserts a C-style cast +/* 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 @@ -19474,18 +21055,19 @@ constexpr bool enum_constant_is_valid() { } #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( @@ -19497,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. */ @@ -19511,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 @@ -19532,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...), @@ -19541,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 @@ -19569,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> @@ -19585,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: @@ -19609,7 +21197,7 @@ 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 @@ -19623,23 +21211,23 @@ struct enum_type { }; /** - * @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 static U handle_constant(U last_value, This& me) { if constexpr (enum_constant_is_valid_wrap()) { - // Constant is valid, so fill reflection data. + // 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 + // 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; @@ -19651,32 +21239,33 @@ struct enum_type { me.has_contiguous = false; } - ecs_assert(!(last_value > 0 && - v < std::numeric_limits::min() + last_value), + ecs_assert(!(last_value > 0 && + v < std::numeric_limits::min() + last_value), ECS_UNSUPPORTED, - "Signed integer enums causes integer overflow when recording " + "Signed integer enums cause integer overflow when recording " "offset from high positive to low negative. Consider using " - "unsigned integers as underlying type."); + "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 = + me.constants[me.max].index = flecs_component_ids_index_get(); } return v; } else { - // Search for constant failed. Pass last valid value through. + // 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; @@ -19688,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) { @@ -19701,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") @@ -19712,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; @@ -19743,10 +21335,11 @@ 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 }; +/** @private Initialize enum reflection for a world. */ template inline static void init_enum(flecs::world_t *world, flecs::entity_t id) { (void)world; (void)id; @@ -19757,18 +21350,19 @@ inline static void init_enum(flecs::world_t *world, flecs::entity_t id) { } // 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. @@ -19782,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. @@ -19793,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 { @@ -19803,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); } @@ -19818,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. */ @@ -19827,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) { @@ -19871,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); } @@ -19883,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_; @@ -19909,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_)); } @@ -19930,7 +21538,7 @@ 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 */ @@ -19940,10 +21548,11 @@ struct stringstream { 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 { @@ -19953,145 +21562,157 @@ 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 _ { -// 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. -// - +/** @private Extract the type name from a type using compiler intrinsics. */ #if defined(__GNUC__) || defined(_WIN32) template inline const char* type_name() { @@ -20112,7 +21733,7 @@ inline const char* type_name() { // Mixin forward declarations /** * @file addons/cpp/mixins/id/decl.hpp - * @brief Id class. + * @brief ID class. */ #pragma once @@ -20123,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() @@ -20165,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; @@ -20220,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_; } @@ -20250,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_; }; @@ -20336,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) @@ -20348,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_; @@ -20357,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() { @@ -20369,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_); @@ -20395,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; @@ -20403,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; @@ -20417,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_; @@ -20436,6 +22065,7 @@ struct event_builder_base { ecs_emit(world_, &desc_); } + /** Enqueue the event. */ void enqueue() { ids_.array = ids_array_; desc_.ids = &ids_; @@ -20455,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: @@ -20467,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; @@ -20488,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>; @@ -20549,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; @@ -20589,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; /** @} */ @@ -20631,9 +22278,12 @@ namespace flecs { * @{ */ +/** Timer component. */ using Timer = EcsTimer; +/** Rate filter component. */ using RateFilter = EcsRateFilter; +/** Forward declaration for timer. */ struct timer; /** @} */ @@ -20660,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 */ @@ -20713,6 +22363,7 @@ namespace flecs { * @{ */ +/** REST API component. */ using Rest = EcsRest; namespace rest { @@ -20747,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; @@ -20763,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; @@ -20781,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); @@ -20808,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; @@ -20819,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; @@ -20853,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 @@ -20878,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_; }; @@ -21032,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) { @@ -21060,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: @@ -21749,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); }; @@ -21786,7 +23597,7 @@ namespace flecs { * @{ */ -/** Module */ +/** Module. */ struct alerts { using AlertsActive = EcsAlertsActive; using Instance = EcsAlertInstance; @@ -21862,7 +23673,7 @@ namespace flecs { * @{ */ -/** App builder interface */ +/** App builder interface. */ struct app_builder { app_builder(flecs::world_t *world) : world_(world) @@ -21876,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_); @@ -21963,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_{} @@ -21978,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: @@ -22043,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); @@ -22075,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); @@ -22083,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); @@ -22091,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); @@ -22099,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); @@ -22108,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(); } @@ -22125,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 @@ -22134,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. * @@ -22155,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_; } @@ -22196,34 +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_v<_::pair_base, raw_type_t>; }; +/** 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 pair while preserving cv qualifiers. */ +/** 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; @@ -22241,36 +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 = is_same_v>; }; +/** Convenience variable template to check if a type is its own actual type. */ template inline constexpr bool is_actual_v = is_actual::value; -} // flecs +/** @} */ + +} // namespace flecs /** * @file addons/cpp/lifecycle_traits.hpp @@ -22286,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), @@ -22336,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), @@ -22365,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); @@ -22380,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, @@ -22392,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, @@ -22412,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 = @@ -22532,12 +24412,12 @@ ecs_move_t move_dtor(ecs_flags32_t &flags) { } } -// Traits to check for operator<, operator>, and operator== +// 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" @@ -22546,34 +24426,34 @@ using std::void_t; #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> {}; -// Selects the best comparison strategy based on available operators +// 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); @@ -22605,13 +24485,13 @@ int compare_impl(const void *a, const void *b, const ecs_type_info_t *) { if (rhs > lhs) return -1; return 0; } else { - // This branch should never be instantiated due to compare() check + // This branch should never be instantiated due to the compare() check. return 0; } } -// In order to have a generated compare hook, at least -// operator> or operator< must be defined: +// To have a generated compare hook, at least +// operator> or operator< must be defined. template ecs_cmp_t compare() { if constexpr (has_operator_less::value || has_operator_greater::value) { @@ -22621,7 +24501,7 @@ ecs_cmp_t compare() { } } -// Equals implementation +// Equals implementation. template bool equals_impl(const void *a, const void *b, const ecs_type_info_t *) { const T& lhs = *static_cast(a); @@ -22638,15 +24518,15 @@ ecs_equals_t equals() { } } -// 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 @@ -22658,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, @@ -22684,7 +24571,14 @@ inline void set(world_t *world, flecs::entity_t entity, T&& value, flecs::id_t i } } -// 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, @@ -22704,21 +24598,43 @@ inline void set(world_t *world, flecs::entity_t entity, const T& value, flecs::i } } -// 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, @@ -22743,7 +24659,15 @@ inline void assign(world_t *world, flecs::entity_t entity, T&& value, flecs::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, @@ -22764,14 +24688,28 @@ inline void assign(world_t *world, flecs::entity_t entity, const T& value, flecs } } -// 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); @@ -22779,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> @@ -22793,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() */ @@ -22801,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); @@ -22822,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[]) @@ -22838,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 ) { @@ -22847,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_; @@ -22861,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_; @@ -22873,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_); } @@ -22892,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, @@ -22910,9 +24867,9 @@ 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_); @@ -22920,7 +24877,7 @@ struct world { init_builtin_components(); } - /** Obtain pointer to C world object. + /** Obtain a pointer to the C world object. */ world_t* c_ptr() const { return world_; @@ -22958,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. @@ -22974,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() @@ -22985,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. * @@ -23008,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. * @@ -23030,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. * @@ -23064,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() @@ -23097,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. * @@ -23109,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. * @@ -23157,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. @@ -23166,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 @@ -23183,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); } @@ -23194,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); } @@ -23217,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() */ @@ -23231,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() @@ -23244,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() @@ -23269,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. @@ -23281,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() */ @@ -23309,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() @@ -23325,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() @@ -23345,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; @@ -23537,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 @@ -23546,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. */ @@ -23555,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. @@ -23575,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. */ @@ -23611,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 @@ -23656,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; @@ -23665,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; @@ -23678,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. @@ -23706,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); @@ -23716,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)); @@ -23724,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 { @@ -23734,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 { @@ -23744,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 { @@ -23752,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 { @@ -23761,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 { @@ -23807,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; @@ -23877,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() */ @@ -23894,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 { @@ -23907,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() @@ -23924,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() @@ -23934,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() @@ -23945,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() */ @@ -23957,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() */ @@ -23965,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() */ @@ -23973,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); } @@ -23982,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; } @@ -23994,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() */ @@ -24008,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() */ @@ -24017,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() { @@ -24033,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_)); @@ -24063,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 */ @@ -24105,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 @@ -24113,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 @@ -24135,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 @@ -24143,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 @@ -24192,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; @@ -24244,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. @@ -24264,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; @@ -24285,25 +26252,25 @@ 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 @@ -24326,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 @@ -24343,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; @@ -24354,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 @@ -24418,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; @@ -24501,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. @@ -24520,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; @@ -24548,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; @@ -24567,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. * @@ -24621,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. * @@ -24658,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(); @@ -24696,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 @@ -24706,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 @@ -24717,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 @@ -24726,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 */ @@ -24735,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 */ @@ -24746,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 @@ -24755,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 @@ -24778,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_; @@ -24794,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 */ @@ -24805,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 */ @@ -24817,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) @@ -24833,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. */ }; /** @} */ @@ -24882,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. @@ -24905,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 */ @@ -24914,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. @@ -24940,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. @@ -24990,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 @@ -25043,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()"); @@ -25071,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. @@ -25103,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() { @@ -25118,97 +27127,112 @@ 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. @@ -25218,12 +27242,12 @@ struct iter { 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. @@ -25238,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. */ @@ -25249,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)) { @@ -25260,8 +27288,13 @@ 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 , if_t< is_const_v > = 0> const A& field_at(int8_t index, size_t row) const { @@ -25272,8 +27305,13 @@ 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 , if_not_t< is_const_v > = 0> A& field_at(int8_t index, size_t row) const { @@ -25286,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( @@ -25296,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_); } @@ -25312,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; @@ -25332,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) { @@ -25345,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_); @@ -25356,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. @@ -25378,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 { @@ -25392,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); } @@ -25408,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 { @@ -25429,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); } @@ -25460,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 @@ -25481,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; @@ -25501,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; @@ -25547,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()); @@ -25564,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()); } @@ -25588,21 +27676,21 @@ 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 component as tuples from entities. + * @brief Utilities to fetch components as tuples from entities. */ #pragma once @@ -25615,112 +27703,145 @@ struct ref : public untyped_ref { 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 {}; - // Size 2 - + /** Tuple of 2 elements. */ template struct tuple_2 { - T val1; U val2; + T val1; /**< First element. */ + U val2; /**< Second element. */ }; + /** Tuple builder specialization for 2 elements. */ template struct tuple_builder<2, Args...> { - using type = tuple_2; - using type_ptr = tuple_2; - using type_const = tuple_2; - using type_const_ptr = tuple_2; + 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. */ }; - // Size 3 - + /** Tuple of 3 elements. */ template struct tuple_3 { - T val1; U val2; V val3; + 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; - using type_ptr = tuple_3; - using type_const = tuple_3; - using type_const_ptr = tuple_3; + 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. */ }; - // Size 4 - + /** Tuple of 4 elements. */ template struct tuple_4 { - T val1; U val2; V val3; W val4; + 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; - using type_ptr = tuple_4; - using type_const = tuple_4; - using type_const_ptr = tuple_4; + 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. */ }; - // Size 5 - + /** Tuple of 5 elements. */ template struct tuple_5 { - T val1; U val2; V val3; W val4; X val5; + 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; - using type_ptr = tuple_5; - using type_const = tuple_5; - using type_const_ptr = tuple_5; + 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. */ }; - // Size 6 - + /** Tuple of 6 elements. */ template struct tuple_6 { - T val1; U val2; V val3; W val4; X val5; Y val6; + 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; - using type_ptr = tuple_6; - using type_const = tuple_6; - using type_const_ptr = tuple_6; + 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. */ }; - // Size 7 - + /** Tuple of 7 elements. */ template struct tuple_7 { - T val1; U val2; V val3; W val4; X val5; Y val6; Z val7; + 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; - using type_ptr = tuple_7; - using type_const = tuple_7; - using type_const_ptr = tuple_7; + 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. */ }; - // Size 8 - + /** Tuple of 8 elements. */ template struct tuple_8 { - T val1; U val2; V val3; W val4; X val5; Y val6; Z val7; A val8; + 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; - using type_ptr = tuple_8; - using type_const = tuple_8; - using type_const_ptr = tuple_8; + 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. */ }; } @@ -25743,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 ) { } @@ -25760,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_; @@ -25769,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. @@ -25780,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(); } @@ -25811,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 { @@ -25826,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 @@ -25835,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); } @@ -25847,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; @@ -25912,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 @@ -25920,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 { @@ -25928,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; } @@ -25940,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 @@ -25948,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 { @@ -26009,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

(); @@ -26022,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 { @@ -26036,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 { @@ -26057,16 +28197,22 @@ 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"); @@ -26078,8 +28224,9 @@ struct entity_view : public id { * 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 { @@ -26099,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 { @@ -26110,9 +28258,9 @@ 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> @@ -26127,12 +28275,12 @@ struct entity_view : public id { /** 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(); @@ -26146,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 { @@ -26202,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; } @@ -26222,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: * @@ -26254,6 +28402,11 @@ 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"); @@ -26265,14 +28418,16 @@ struct entity_view : public id { * 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; } @@ -26281,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; } @@ -26329,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 { @@ -26353,10 +28512,11 @@ 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 { @@ -26377,16 +28537,22 @@ 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"); @@ -26398,8 +28564,9 @@ struct entity_view : public id { * 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 { @@ -26419,7 +28586,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 Second* try_get_mut_second() const { @@ -26430,9 +28598,9 @@ struct entity_view : public id { /* 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> @@ -26446,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(); @@ -26464,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 { @@ -26503,33 +28677,40 @@ 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"); @@ -26541,14 +28722,16 @@ struct entity_view : public id { * 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; } @@ -26557,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 *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; @@ -26578,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; @@ -26589,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. @@ -26627,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. @@ -26703,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 { @@ -26714,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 { @@ -26726,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 { @@ -26737,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 { @@ -26750,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)); @@ -26770,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 { @@ -26782,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. @@ -26800,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. @@ -26815,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 { @@ -26875,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 @@ -26898,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. * @@ -26907,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. @@ -26923,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 @@ -26940,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() @@ -27025,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 @@ -27041,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 @@ -27055,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 * @@ -27068,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 * @@ -27076,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 * @@ -27087,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 * @@ -27103,7 +29315,7 @@ void emit(const Evt& payload) const { } -/** Enqueue event for entity. +/** Enqueue an event for an entity. * * @memberof flecs::entity_view * @@ -27116,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 * @@ -27124,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 * @@ -27135,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 * @@ -27180,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 { @@ -27190,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. @@ -27205,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); @@ -27233,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 { @@ -27244,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> @@ -27255,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 { @@ -27272,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 { @@ -27334,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. */ @@ -27346,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 @@ -27377,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 { @@ -27431,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 { @@ -27440,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 { @@ -27449,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 { @@ -27458,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 { @@ -27486,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 { @@ -27500,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> @@ -27508,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 { @@ -27522,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 { @@ -27532,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); @@ -27599,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 @@ -27611,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 @@ -27620,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. @@ -27633,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. @@ -27646,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)); @@ -27729,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() @@ -27785,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 @@ -27801,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 { @@ -27856,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. @@ -27869,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. @@ -27882,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)); @@ -27896,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. @@ -27914,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)); @@ -27929,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); @@ -27990,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. */ @@ -28010,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. */ @@ -28031,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 @@ -28042,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. @@ -28055,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. @@ -28068,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)); @@ -28082,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. @@ -28097,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)); @@ -28112,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); @@ -28127,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. @@ -28136,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. @@ -28152,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. @@ -28174,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. */ @@ -28194,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. */ @@ -28224,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. @@ -28237,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 { @@ -28283,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. */ @@ -28296,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 @@ -28308,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. @@ -28323,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_); @@ -28332,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(); @@ -28357,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() @@ -28456,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, @@ -28484,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, @@ -28504,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 @@ -28520,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(); @@ -28548,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 { @@ -28574,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 @@ -28588,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 */ @@ -28617,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 */ @@ -28633,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 */ @@ -28656,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); @@ -28715,15 +30924,16 @@ 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() { } - /** 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(const flecs::world_t *world, flecs::entity_t id) { world_ = const_cast(world); @@ -28763,17 +30973,18 @@ struct entity : entity_builder id_ = ecs_entity_init(world, &desc); } - /** Create a named entity for parent using ChildOf hierarchy storage. - * + /** 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 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, + world_t *world, + flecs::entity_t parent, + const char *name, const char *sep = "::", const char *root_sep = "::") : entity_builder() { @@ -28787,16 +30998,17 @@ struct entity : entity_builder id_ = ecs_entity_init(world, &desc); } - /** Create a named entity for parent using Parent hierarchy storage. + /** 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, + world_t *world, const flecs::Parent& parent, const char *name = nullptr) : entity_builder() { @@ -28814,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 { @@ -28846,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> @@ -28860,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 { @@ -28882,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 { @@ -28910,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 { @@ -28923,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 { @@ -28947,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. @@ -28960,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> @@ -29006,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> @@ -29019,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 { @@ -29026,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_); @@ -29052,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() */ @@ -29070,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_); @@ -29084,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) { @@ -29119,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 @@ -29157,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; @@ -29184,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; @@ -29252,11 +31523,11 @@ struct field_ptrs { 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) { @@ -29267,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 { @@ -29281,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 @@ -29297,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 && @@ -29312,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 && @@ -29326,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; } } @@ -29342,9 +31613,9 @@ struct each_ref_field : public each_field { : 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 @@ -29359,7 +31630,7 @@ struct each_ref_field : public each_field { } }; -// 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; @@ -29388,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); @@ -29405,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); @@ -29423,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); @@ -29431,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); @@ -29439,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); @@ -29504,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; } @@ -29558,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, @@ -29591,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, @@ -29606,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; } @@ -29631,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, @@ -29643,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; } @@ -29702,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); @@ -29722,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); } @@ -29752,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); } @@ -29815,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; @@ -29849,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, @@ -29914,11 +32185,11 @@ struct entity_with_delegate_impl> { } } - // 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; @@ -29971,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 @@ -29981,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) @@ -29995,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(); @@ -30010,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); } @@ -30021,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)... }); @@ -30063,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...>; @@ -30124,10 +32400,10 @@ 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. +// compiler, as it reduces the number of templates to evaluate. template void register_lifecycle_actions( ecs_world_t *world, @@ -30136,7 +32412,7 @@ void register_lifecycle_actions( (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. + // 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); @@ -30183,11 +32459,11 @@ 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) { - index(); // Make sure global component index is initialized + index(); // Make sure the global component index is initialized. s_size = sizeof(T); s_alignment = alignof(T); @@ -30206,14 +32482,14 @@ struct type_impl { 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 { init(allow_tag); ecs_assert(index() != 0, ECS_INTERNAL_ERROR, NULL); @@ -30239,8 +32515,8 @@ struct type_impl { 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) { @@ -30273,7 +32549,7 @@ struct type_impl { 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); @@ -30284,7 +32560,7 @@ struct type_impl { 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_size = 0; @@ -30300,23 +32576,23 @@ struct type_impl { static size_t s_alignment; }; -// Global templated variables that hold component identifier and other info +// 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), @@ -30333,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; @@ -30350,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; @@ -30364,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(); @@ -30395,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(); @@ -30421,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, @@ -30445,17 +32763,17 @@ untyped_component& internal_member( 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, @@ -30466,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, @@ -30485,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, @@ -30495,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, @@ -30540,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_); @@ -30552,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( @@ -30564,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( @@ -30577,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( @@ -30590,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, @@ -30611,7 +32929,7 @@ untyped_component& constant( return *this; } -/** Add bitmask constant. */ +/** Add a bitmask constant. */ template untyped_component& bit( const char *name, @@ -30632,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) @@ -30645,7 +32963,7 @@ untyped_component& array( return *this; } -/** Add member value range */ +/** Add a member value range. */ untyped_component& range( double min, double max) @@ -30672,7 +32990,7 @@ untyped_component& range( return *this; } -/** Add member warning range */ +/** Add a member warning range. */ untyped_component& warning_range( double min, double max) @@ -30699,7 +33017,7 @@ untyped_component& warning_range( return *this; } -/** Add member error range */ +/** Add a member error range. */ untyped_component& error_range( double min, double max) @@ -30731,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. */ @@ -30742,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). @@ -30781,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, @@ -30793,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>; @@ -30808,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< @@ -30824,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< @@ -30840,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)); @@ -30856,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, @@ -30866,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, @@ -30883,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_); @@ -30902,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; @@ -30937,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); @@ -30968,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 @@ -30984,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; @@ -31006,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; @@ -31014,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); @@ -31024,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; @@ -31032,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]; @@ -31040,7 +33420,7 @@ struct type { } } - /** Implicit conversion to type_t */ + /** Implicit conversion to type_t. */ operator const type_t*() const { return type_; } @@ -31050,7 +33430,7 @@ struct type { flecs::id_t empty_; }; -/** #} */ +/** @} */ } @@ -31071,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 The index of the id in the table type, -1 if not found. + * @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 The index of the id in the table type, -1 if not found. + /** 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 The index of the id in the table type, -1 if not found. + /** 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 The index of the id in the table type, -1 if not found. + /** 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 The column index of the id in the table type, -1 if not found. + * @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 The column index of the id in the table type, -1 if not found. + /** 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 The column index of the id in the table type, -1 if not found. + /** 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 The column index of the id in the table type, -1 if not found. + /** 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. @@ -31225,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 @@ -31246,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 @@ -31257,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. @@ -31269,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 { @@ -31282,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. @@ -31292,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. @@ -31302,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. @@ -31313,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. @@ -31327,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 { @@ -31338,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. @@ -31353,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. @@ -31363,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. @@ -31374,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. @@ -31386,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. @@ -31398,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. @@ -31412,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. @@ -31422,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. */ @@ -31455,7 +33867,7 @@ struct table { return table_; } - /* Implicit conversion to table_t */ + /** Implicit conversion to table_t*. */ operator table_t*() const { return table_; } @@ -31465,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. @@ -31509,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 { @@ -31525,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 { @@ -31537,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 { @@ -31548,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); @@ -31565,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. @@ -31592,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; @@ -31655,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(); @@ -31667,12 +34116,14 @@ 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, "%s", name); @@ -31680,6 +34131,7 @@ struct iter_iterable final : iterable { 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, "%s", name); @@ -31687,6 +34139,7 @@ struct iter_iterable final : iterable { 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, "%s", name); @@ -31694,6 +34147,7 @@ struct iter_iterable final : iterable { 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(); @@ -31708,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 @@ -31720,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_)) { @@ -31729,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) { @@ -31738,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) { @@ -31748,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)); @@ -31799,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) { @@ -31826,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 { @@ -31852,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); } @@ -31870,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 @@ -31934,7 +34392,7 @@ inline flecs::entity id::type_id() const { } -// Id mixin implementation +// ID mixin implementation template inline flecs::id world::id() const { @@ -32051,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_); } @@ -32206,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 @@ -32241,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 @@ -32309,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*). */ @@ -32348,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; @@ -32356,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; @@ -32364,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: @@ -32394,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(); @@ -32420,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(); @@ -32428,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); @@ -32455,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); @@ -32482,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); @@ -32509,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(); @@ -32526,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(); @@ -32543,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; @@ -32568,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. @@ -32599,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::Not) */ + /** Short for oper(flecs::Not). */ Base& not_() { return this->oper(flecs::Not); } - /* Short for oper(flecs::Optional) */ + /** 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; } @@ -32723,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({}) @@ -32741,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({}) @@ -32753,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({}) @@ -32761,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 { @@ -32772,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: @@ -32826,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)...); @@ -32872,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 @@ -32934,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"); @@ -32968,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(); @@ -32979,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()); @@ -33037,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_), @@ -33139,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. */ @@ -33161,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_; @@ -33174,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); @@ -33217,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; @@ -33230,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. * @@ -33243,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)) { @@ -33252,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); @@ -33264,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. */ @@ -33274,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. */ @@ -33282,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; @@ -33293,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; @@ -33369,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( @@ -33396,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_) @@ -33404,6 +35935,7 @@ struct query_base { } } + /** Copy assignment operator. */ query_base& operator=(const query_base& obj) { this->~query_base(); this->query_ = obj.query_; @@ -33414,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; } + /** 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() " @@ -33453,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_); @@ -33466,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 @@ -33479,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 { @@ -33502,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 ++) { @@ -33511,41 +36047,51 @@ struct query_base { } } + /** Get term at the specified index. */ flecs::term term(int32_t index) const { return flecs::term(query_->world, query_->terms[index]); } + /** Get the number of terms in the query. */ int32_t term_count() const { return query_->term_count; } + /** Get the number of fields in the query. */ int32_t field_count() const { return query_->field_count; } + /** Find a variable by name. */ int32_t find_var(const char *name) const { return ecs_query_find_var(query_, name); } + /** 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 @@ -33561,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: @@ -33569,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); @@ -33664,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; @@ -33730,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 @@ -33738,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 @@ -33833,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) { } @@ -33860,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; @@ -33913,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) { @@ -33926,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_; @@ -33944,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); } @@ -34113,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); @@ -34130,7 +36698,7 @@ 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, "%s", symbol); ecs_assert(m == c_, ECS_INTERNAL_ERROR, NULL); @@ -34147,17 +36715,17 @@ flecs::entity import(world& world) { 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); } @@ -34171,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. * * @{ */ @@ -34186,7 +36754,7 @@ 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(); @@ -34268,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) { @@ -34285,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. * @@ -34315,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. * @@ -34329,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. * @@ -34341,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. @@ -34352,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. @@ -34362,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; @@ -34430,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) @@ -34445,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( @@ -34481,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_; @@ -34502,29 +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, @@ -34549,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); @@ -34600,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); } @@ -34736,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) { } @@ -34761,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) { @@ -34863,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_); } @@ -34909,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); } @@ -34984,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() @@ -35056,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() @@ -35128,8 +37744,6 @@ inline void init(flecs::world& world) { } // namespace doc } // namespace flecs -#endif -#ifdef FLECS_DOC #endif #ifdef FLECS_REST /** @@ -35167,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() @@ -35215,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); @@ -35259,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; @@ -35268,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; @@ -35278,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); @@ -35325,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"); @@ -35364,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); } +/** 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); @@ -36293,13 +38953,14 @@ 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; @@ -36309,6 +38970,7 @@ inline flecs::entity iter::get_var(const char *name) const { 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); @@ -36319,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); } @@ -36336,9 +38998,10 @@ 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(); @@ -36346,7 +39009,7 @@ inline void world::init_builtin_components() { 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"); @@ -36379,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); @@ -36399,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_)); @@ -36435,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 { @@ -36669,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, @@ -36678,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 @@ -36686,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"); @@ -36693,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"); @@ -36700,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); @@ -36724,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()) @@ -36739,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)); } @@ -36766,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/include/flecs.h b/include/flecs.h index 128b0a976e..737046d95c 100644 --- a/include/flecs.h +++ b/include/flecs.h @@ -25,7 +25,7 @@ /** * @defgroup options API defines - * Defines for customizing compile time features. + * Defines for customizing compile-time features. * * @{ */ @@ -47,14 +47,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 @@ -121,7 +121,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. @@ -134,7 +134,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. */ @@ -143,8 +143,8 @@ /** @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 @@ -176,22 +176,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 @@ -205,7 +205,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 @@ -217,30 +217,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 @@ -258,16 +258,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 @@ -276,7 +276,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 @@ -284,7 +284,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. */ @@ -300,24 +300,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 @@ -339,13 +339,13 @@ #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 @@ -353,7 +353,7 @@ #endif /** @def FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE - * Size of depth cache in tree spawner component. Higher values speed up prefab + * 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) @@ -369,23 +369,23 @@ * @{ */ -/** 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]. @@ -396,35 +396,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. */ @@ -438,7 +438,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++): * @@ -477,32 +477,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 @@ -513,16 +513,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; /** @} */ @@ -581,7 +582,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); @@ -594,14 +595,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, @@ -612,7 +613,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, @@ -632,29 +633,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, @@ -674,13 +675,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, @@ -699,39 +700,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) @@ -748,7 +749,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 */ @@ -760,19 +761,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 */ @@ -792,10 +793,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 @@ -807,94 +808,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. */ - /** Observer events */ + ecs_query_t *query; /**< Observer query. */ + + /** 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. */ }; /** @} */ @@ -947,79 +948,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. */ }; @@ -1041,7 +1042,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. */ @@ -1051,32 +1052,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; @@ -1087,14 +1088,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 @@ -1117,10 +1118,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; @@ -1145,7 +1146,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: @@ -1164,63 +1165,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. */ }; @@ -1248,13 +1249,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 @@ -1275,19 +1276,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; @@ -1300,7 +1301,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; @@ -1319,25 +1320,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; @@ -1349,39 +1350,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. */ + * 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). */ @@ -1398,8 +1399,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(). @@ -1407,22 +1408,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 @@ -1430,12 +1431,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; @@ -1444,89 +1445,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 @@ -1537,74 +1538,77 @@ 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. */ +/** Non-fragmenting ChildOf relationship. */ typedef struct EcsParent { - ecs_entity_t value; + ecs_entity_t value; /**< Parent entity. */ } EcsParent; -/* Component with data to instantiate a non-fragmenting tree. */ +/** Component with data to instantiate a non-fragmenting tree. */ typedef struct { - const char *child_name; /* Name of prefab child */ - ecs_table_t *table; /* Table in which child will be stored */ - uint32_t child; /* Prefab child entity (without generation) */ - int32_t parent_index; /* Index into children vector */ + 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_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 { - /* 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. */ - ecs_tree_spawner_t data[FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE]; + ecs_tree_spawner_t data[FLECS_TREE_SPAWNER_DEPTH_CACHE_SIZE]; /**< Cache data indexed by depth. */ } EcsTreeSpawner; /** @} */ @@ -1623,49 +1627,49 @@ typedef struct EcsTreeSpawner { */ /** - * @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; -/** Indicates that the target of a pair is an integer value. */ +/** 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); -/** Parent 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. */ +/** DefaultChildComponent component ID. */ FLECS_API extern const ecs_entity_t ecs_id(EcsDefaultChildComponent); /** Relationship storing the entity's depth in a non-fragmenting hierarchy. */ @@ -1680,40 +1684,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 @@ -1722,7 +1726,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 @@ -1731,7 +1735,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. * @@ -1746,7 +1750,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; @@ -1769,7 +1773,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 @@ -1778,8 +1782,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: * @@ -1789,14 +1793,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: * @@ -1807,7 +1811,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: * @@ -1826,7 +1830,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: * @@ -1837,7 +1841,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: * @@ -1848,17 +1852,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. */ @@ -1867,23 +1871,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 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; @@ -1892,16 +1896,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. */ @@ -1917,15 +1921,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; @@ -1933,10 +1937,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. */ @@ -1954,13 +1958,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. */ @@ -1974,24 +1978,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()) */ +/** 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 */ /** @} */ @@ -2013,7 +2017,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); @@ -2022,17 +2026,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( @@ -2049,7 +2055,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. * @@ -2060,13 +2066,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, @@ -2075,17 +2082,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 ++) { @@ -2093,7 +2100,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]; @@ -2101,10 +2108,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( @@ -2140,7 +2147,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. @@ -2161,20 +2168,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. * @@ -2223,16 +2231,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. @@ -2243,8 +2251,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: @@ -2271,28 +2279,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. * @@ -2303,9 +2311,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 @@ -2317,7 +2325,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: @@ -2331,10 +2339,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 @@ -2347,13 +2355,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. @@ -2362,12 +2370,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. @@ -2382,16 +2390,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() */ @@ -2410,7 +2418,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 @@ -2424,14 +2432,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. @@ -2446,7 +2454,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. @@ -2461,7 +2469,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 @@ -2479,8 +2487,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. @@ -2494,10 +2502,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. @@ -2520,7 +2528,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(). * @@ -2531,7 +2539,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. */ @@ -2539,12 +2547,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( @@ -2562,7 +2570,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 @@ -2572,11 +2580,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 @@ -2608,17 +2616,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( @@ -2655,7 +2663,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 @@ -2663,7 +2671,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. @@ -2676,11 +2684,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. @@ -2691,10 +2699,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( @@ -2703,8 +2711,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 @@ -2730,23 +2738,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 @@ -2757,14 +2765,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. @@ -2773,16 +2781,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 @@ -2792,7 +2800,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 @@ -2800,19 +2808,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( @@ -2829,7 +2837,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 @@ -2839,7 +2847,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( @@ -2848,17 +2856,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 @@ -2891,21 +2899,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 @@ -2915,18 +2923,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. @@ -2959,7 +2967,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. * @@ -2972,7 +2980,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. * @@ -2980,15 +2988,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 @@ -2996,7 +3004,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( @@ -3010,7 +3018,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( @@ -3018,7 +3026,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. @@ -3041,7 +3049,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. * @@ -3054,7 +3062,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. @@ -3071,7 +3079,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 @@ -3092,7 +3100,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. @@ -3112,13 +3120,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( @@ -3140,7 +3148,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: @@ -3171,7 +3179,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 @@ -3184,7 +3192,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. @@ -3209,7 +3217,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. @@ -3220,9 +3228,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 @@ -3232,15 +3241,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(). @@ -3259,7 +3269,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. @@ -3274,7 +3284,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 @@ -3294,10 +3304,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. @@ -3313,15 +3323,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. @@ -3341,7 +3351,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 @@ -3359,18 +3369,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() @@ -3383,8 +3394,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. @@ -3398,8 +3409,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. * @@ -3414,9 +3425,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. @@ -3441,7 +3452,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. @@ -3472,7 +3483,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. * @@ -3502,18 +3513,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. @@ -3527,12 +3538,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 @@ -3546,8 +3557,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. @@ -3559,55 +3570,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() */ @@ -3617,17 +3628,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. * @@ -3640,7 +3651,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. @@ -3653,26 +3664,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 @@ -3683,7 +3694,7 @@ uint32_t ecs_get_version( /** * @defgroup entity_info Entity Information. - * Get information from entity. + * Get information from an entity. * * @{ */ @@ -3703,14 +3714,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. @@ -3722,7 +3733,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(). * @@ -3738,7 +3749,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)) @@ -3810,7 +3821,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 @@ -3853,7 +3864,7 @@ ecs_entity_t ecs_new_w_parent( * 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 @@ -3864,7 +3875,7 @@ ecs_entity_t ecs_new_w_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 @@ -3874,9 +3885,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. @@ -3890,12 +3901,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( @@ -3917,7 +3928,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() */ @@ -3931,7 +3942,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() */ @@ -3963,7 +3974,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. @@ -3978,12 +3989,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. @@ -3995,7 +4006,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 @@ -4015,13 +4026,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. * @@ -4035,14 +4046,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. @@ -4050,7 +4061,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() @@ -4066,8 +4077,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 @@ -4075,7 +4086,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. * @@ -4093,11 +4104,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. @@ -4119,8 +4130,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. @@ -4128,6 +4139,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() */ @@ -4141,7 +4153,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. @@ -4164,7 +4176,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. * @@ -4189,7 +4201,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. @@ -4219,7 +4231,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. @@ -4230,29 +4242,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() */ @@ -4261,8 +4273,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. @@ -4300,30 +4312,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( @@ -4331,7 +4343,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. @@ -4345,32 +4357,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. * @@ -4384,18 +4396,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. @@ -4413,71 +4425,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 @@ -4485,14 +4497,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( 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" @@ -4500,7 +4512,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. @@ -4511,8 +4523,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. @@ -4524,12 +4536,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( @@ -4544,8 +4557,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. @@ -4560,7 +4573,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. @@ -4570,7 +4583,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. * @@ -4582,31 +4595,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. @@ -4617,8 +4630,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. @@ -4632,13 +4645,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: @@ -4651,8 +4664,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); @@ -4666,8 +4679,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, @@ -4682,7 +4695,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)); @@ -4690,7 +4703,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: * @@ -4703,13 +4716,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. @@ -4743,7 +4756,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 @@ -4759,7 +4772,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(). * @@ -4772,7 +4785,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. @@ -4784,14 +4797,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 @@ -4800,14 +4813,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 @@ -4872,7 +4885,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. @@ -4883,7 +4896,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. @@ -4897,7 +4910,7 @@ 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. */ @@ -4907,7 +4920,7 @@ bool ecs_query_has( 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. @@ -4921,7 +4934,7 @@ 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. */ @@ -4931,7 +4944,7 @@ bool ecs_query_has_table( 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. @@ -4953,7 +4966,7 @@ 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. */ @@ -4963,19 +4976,19 @@ bool ecs_query_has_range( 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(). @@ -4987,12 +5000,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(). @@ -5006,7 +5019,7 @@ char* ecs_query_plan_w_profile( const ecs_query_t *query, const ecs_iter_t *it); -/** Same as ecs_query_plan(), but includes plan for populating cache (if any). +/** Same as ecs_query_plan(), but includes the plan for populating the cache (if any). * * @param query The query. * @return The query plan. @@ -5015,22 +5028,22 @@ FLECS_API char* ecs_query_plans( const ecs_query_t *query); -/** Populate variables from key-value string. +/** 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( @@ -5038,39 +5051,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. @@ -5085,10 +5093,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. */ @@ -5096,13 +5104,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. * @@ -5112,7 +5120,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. @@ -5123,7 +5131,7 @@ void ecs_iter_set_group( ecs_iter_t *it, uint64_t group_id); -/** Return map with query groups. +/** 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: * @@ -5152,7 +5160,7 @@ FLECS_API const ecs_map_t* ecs_query_get_groups( const ecs_query_t *query); -/** Get context of query group. +/** Get the context of a query group. * This operation returns the context of a query group as returned by the * on_group_create callback. * @@ -5165,7 +5173,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. * @@ -5180,14 +5188,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. @@ -5197,7 +5205,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. @@ -5206,10 +5214,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. @@ -5227,22 +5235,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() */ @@ -5251,24 +5259,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. * @@ -5281,8 +5289,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. @@ -5309,8 +5317,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. @@ -5320,11 +5328,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. @@ -5333,39 +5341,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. @@ -5375,7 +5383,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. @@ -5390,7 +5398,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); @@ -5404,7 +5412,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. @@ -5435,7 +5443,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. @@ -5451,13 +5459,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. @@ -5468,7 +5476,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. @@ -5479,16 +5487,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). @@ -5497,14 +5505,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. @@ -5515,14 +5523,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. @@ -5533,7 +5541,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. * @@ -5549,24 +5557,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 @@ -5574,12 +5582,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. * @@ -5616,10 +5624,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( @@ -5652,16 +5660,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. @@ -5669,13 +5677,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. @@ -5690,7 +5698,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; * } @@ -5708,25 +5716,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 @@ -5736,35 +5745,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. @@ -5775,18 +5784,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. * @@ -5799,7 +5808,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. @@ -5811,8 +5820,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. @@ -5850,8 +5859,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. @@ -5860,7 +5869,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. @@ -5876,14 +5885,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( @@ -5891,7 +5900,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. * @@ -5902,7 +5911,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 @@ -5920,7 +5929,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. * @@ -5933,7 +5942,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. @@ -5947,14 +5956,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( @@ -5963,7 +5972,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. @@ -5975,7 +5984,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. @@ -5985,7 +5994,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. * @@ -5996,23 +6005,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() */ @@ -6022,7 +6031,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. @@ -6039,9 +6048,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. @@ -6055,14 +6064,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( @@ -6070,15 +6079,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( @@ -6086,14 +6095,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( @@ -6132,8 +6141,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. * @@ -6146,8 +6155,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. @@ -6157,13 +6166,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, @@ -6171,26 +6182,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 @@ -6203,21 +6216,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() @@ -6229,7 +6242,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. * @@ -6238,28 +6251,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() @@ -6272,7 +6285,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 @@ -6284,30 +6297,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 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() @@ -6325,7 +6337,21 @@ int32_t ecs_search_relation( ecs_id_t *component_out, struct ecs_table_record_t **tr_out); -/* Up traversal from entity */ +/** 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, @@ -6340,7 +6366,7 @@ int32_t ecs_search_relation_for_entity( /** 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. @@ -6354,17 +6380,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( @@ -6372,12 +6398,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( @@ -6385,45 +6411,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( @@ -6431,12 +6457,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( @@ -6444,13 +6470,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( @@ -6459,13 +6485,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( @@ -6474,13 +6500,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, @@ -6488,13 +6514,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, @@ -6502,13 +6528,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, @@ -6516,13 +6542,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, diff --git a/include/flecs/addons/alerts.h b/include/flecs/addons/alerts.h index 100698696f..9739670d2e 100644 --- a/include/flecs/addons/alerts.h +++ b/include/flecs/addons/alerts.h @@ -28,19 +28,20 @@ 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. */ @@ -48,15 +49,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. @@ -66,18 +67,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 @@ -96,13 +97,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; @@ -114,20 +115,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; diff --git a/include/flecs/addons/app.h b/include/flecs/addons/app.h index 454c314aaf..d4164be034 100644 --- a/include/flecs/addons/app.h +++ b/include/flecs/addons/app.h @@ -5,7 +5,7 @@ * 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 @@ -36,17 +36,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. */ @@ -61,7 +61,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 @@ -69,6 +69,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( @@ -76,12 +77,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( @@ -92,6 +93,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( @@ -101,6 +103,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( diff --git a/include/flecs/addons/cpp/c_types.hpp b/include/flecs/addons/cpp/c_types.hpp index 3d6dc9e684..c3c20b0c23 100644 --- a/include/flecs/addons/cpp/c_types.hpp +++ b/include/flecs/addons/cpp/c_types.hpp @@ -1,6 +1,6 @@ /** * @file addons/cpp/c_types.hpp - * @brief Aliases for types/constants from C API + * @brief Aliases for types/constants from C API. */ #pragma once @@ -8,171 +8,237 @@ 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; +/** 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; /** @} */ diff --git a/include/flecs/addons/cpp/component.hpp b/include/flecs/addons/cpp/component.hpp index 09886d1ab3..3627496bce 100644 --- a/include/flecs/addons/cpp/component.hpp +++ b/include/flecs/addons/cpp/component.hpp @@ -53,10 +53,10 @@ 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. +// compiler, as it reduces the number of templates to evaluate. template void register_lifecycle_actions( ecs_world_t *world, @@ -65,7 +65,7 @@ void register_lifecycle_actions( (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. + // 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); @@ -112,11 +112,11 @@ 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) { - index(); // Make sure global component index is initialized + index(); // Make sure the global component index is initialized. s_size = sizeof(T); s_alignment = alignof(T); @@ -135,14 +135,14 @@ struct type_impl { 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 { init(allow_tag); ecs_assert(index() != 0, ECS_INTERNAL_ERROR, NULL); @@ -168,8 +168,8 @@ struct type_impl { 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) { @@ -202,7 +202,7 @@ struct type_impl { 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); @@ -213,7 +213,7 @@ struct type_impl { 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_size = 0; @@ -229,23 +229,23 @@ struct type_impl { static size_t s_alignment; }; -// Global templated variables that hold component identifier and other info +// 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), @@ -262,11 +262,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; @@ -279,6 +296,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; @@ -293,24 +317,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(); @@ -324,8 +361,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(); @@ -357,7 +399,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, @@ -369,7 +411,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>; @@ -384,7 +430,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< @@ -400,7 +450,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< @@ -416,14 +470,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)); @@ -432,8 +490,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, @@ -442,15 +504,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, @@ -459,8 +530,13 @@ 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; diff --git a/include/flecs/addons/cpp/delegate.hpp b/include/flecs/addons/cpp/delegate.hpp index 1392ed411f..e08e171ab1 100644 --- a/include/flecs/addons/cpp/delegate.hpp +++ b/include/flecs/addons/cpp/delegate.hpp @@ -13,7 +13,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; @@ -40,7 +40,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; @@ -108,11 +108,11 @@ struct field_ptrs { 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) { @@ -123,9 +123,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 { @@ -137,7 +137,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 @@ -153,7 +153,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 && @@ -168,7 +168,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 && @@ -182,7 +182,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; } } @@ -198,9 +198,9 @@ struct each_ref_field : public each_field { : 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 @@ -215,7 +215,7 @@ struct each_ref_field : public each_field { } }; -// 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; @@ -244,14 +244,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); @@ -261,17 +261,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); @@ -279,7 +279,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); @@ -287,7 +287,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); @@ -295,7 +295,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); @@ -360,8 +360,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; } @@ -414,7 +414,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, @@ -447,7 +447,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, @@ -462,8 +462,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; } @@ -487,7 +487,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, @@ -499,8 +499,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; } @@ -558,7 +558,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); @@ -578,7 +578,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); } @@ -608,7 +608,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); } @@ -671,24 +671,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; @@ -705,7 +705,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, @@ -770,11 +770,11 @@ struct entity_with_delegate_impl> { } } - // 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; @@ -827,9 +827,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 @@ -837,13 +837,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) @@ -851,7 +851,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(); @@ -866,7 +866,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); } @@ -877,7 +877,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)... }); @@ -919,7 +919,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...>; diff --git a/include/flecs/addons/cpp/entity.hpp b/include/flecs/addons/cpp/entity.hpp index 73c550cd74..e6b47727cc 100644 --- a/include/flecs/addons/cpp/entity.hpp +++ b/include/flecs/addons/cpp/entity.hpp @@ -25,15 +25,16 @@ 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() { } - /** 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(const flecs::world_t *world, flecs::entity_t id) { world_ = const_cast(world); @@ -73,17 +74,18 @@ struct entity : entity_builder id_ = ecs_entity_init(world, &desc); } - /** Create a named entity for parent using ChildOf hierarchy storage. - * + /** 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 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, + world_t *world, + flecs::entity_t parent, + const char *name, const char *sep = "::", const char *root_sep = "::") : entity_builder() { @@ -97,16 +99,17 @@ struct entity : entity_builder id_ = ecs_entity_init(world, &desc); } - /** Create a named entity for parent using Parent hierarchy storage. + /** 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, + world_t *world, const flecs::Parent& parent, const char *name = nullptr) : entity_builder() { @@ -124,13 +127,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 { @@ -156,11 +159,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> @@ -170,11 +174,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 { @@ -192,16 +197,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 { @@ -220,7 +227,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 { @@ -233,7 +240,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 { @@ -257,9 +264,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. @@ -270,41 +277,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> @@ -316,9 +324,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> @@ -329,6 +337,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 { @@ -336,20 +350,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_); @@ -362,7 +399,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() */ @@ -380,13 +417,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_); @@ -394,33 +442,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) { @@ -429,6 +483,10 @@ 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(); diff --git a/include/flecs/addons/cpp/entity_component_tuple.hpp b/include/flecs/addons/cpp/entity_component_tuple.hpp index 6b4ad04e61..4ff0c6e7e5 100644 --- a/include/flecs/addons/cpp/entity_component_tuple.hpp +++ b/include/flecs/addons/cpp/entity_component_tuple.hpp @@ -1,6 +1,6 @@ /** * @file addons/cpp/entity_component_tuple.hpp - * @brief Utilities to fetch component as tuples from entities. + * @brief Utilities to fetch components as tuples from entities. */ #pragma once @@ -13,112 +13,145 @@ 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 {}; - // Size 2 - + /** Tuple of 2 elements. */ template struct tuple_2 { - T val1; U val2; + T val1; /**< First element. */ + U val2; /**< Second element. */ }; + /** Tuple builder specialization for 2 elements. */ template struct tuple_builder<2, Args...> { - using type = tuple_2; - using type_ptr = tuple_2; - using type_const = tuple_2; - using type_const_ptr = tuple_2; + 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. */ }; - // Size 3 - + /** Tuple of 3 elements. */ template struct tuple_3 { - T val1; U val2; V val3; + 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; - using type_ptr = tuple_3; - using type_const = tuple_3; - using type_const_ptr = tuple_3; + 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. */ }; - // Size 4 - + /** Tuple of 4 elements. */ template struct tuple_4 { - T val1; U val2; V val3; W val4; + 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; - using type_ptr = tuple_4; - using type_const = tuple_4; - using type_const_ptr = tuple_4; + 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. */ }; - // Size 5 - + /** Tuple of 5 elements. */ template struct tuple_5 { - T val1; U val2; V val3; W val4; X val5; + 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; - using type_ptr = tuple_5; - using type_const = tuple_5; - using type_const_ptr = tuple_5; + 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. */ }; - // Size 6 - + /** Tuple of 6 elements. */ template struct tuple_6 { - T val1; U val2; V val3; W val4; X val5; Y val6; + 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; - using type_ptr = tuple_6; - using type_const = tuple_6; - using type_const_ptr = tuple_6; + 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. */ }; - // Size 7 - + /** Tuple of 7 elements. */ template struct tuple_7 { - T val1; U val2; V val3; W val4; X val5; Y val6; Z val7; + 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; - using type_ptr = tuple_7; - using type_const = tuple_7; - using type_const_ptr = tuple_7; + 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. */ }; - // Size 8 - + /** Tuple of 8 elements. */ template struct tuple_8 { - T val1; U val2; V val3; W val4; X val5; Y val6; Z val7; A val8; + 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; - using type_ptr = tuple_8; - using type_const = tuple_8; - using type_const_ptr = tuple_8; + 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. */ }; } diff --git a/include/flecs/addons/cpp/entity_view.hpp b/include/flecs/addons/cpp/entity_view.hpp index 013a82083a..a391b62d5e 100644 --- a/include/flecs/addons/cpp/entity_view.hpp +++ b/include/flecs/addons/cpp/entity_view.hpp @@ -1,13 +1,13 @@ /** * @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 @@ -29,15 +29,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 ) { } @@ -46,8 +47,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_; @@ -55,8 +56,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. @@ -66,6 +67,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(); } @@ -97,14 +99,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 { @@ -112,8 +119,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 @@ -121,6 +131,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); } @@ -133,39 +147,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; @@ -198,7 +214,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 @@ -206,7 +222,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 { @@ -214,7 +230,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; } @@ -226,7 +242,7 @@ struct entity_view : public id { } } - /** Iterate children for entity. + /** Iterate children for an entity. * The function parameter must match the following signature: * * @code @@ -234,23 +250,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 { @@ -295,9 +311,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

(); @@ -308,6 +325,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 { @@ -322,7 +340,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 { @@ -343,16 +362,22 @@ 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"); @@ -364,8 +389,9 @@ struct entity_view : public id { * 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 { @@ -385,7 +411,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 { @@ -396,9 +423,9 @@ 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> @@ -413,12 +440,12 @@ struct entity_view : public id { /** 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(); @@ -432,39 +459,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 { @@ -488,18 +515,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; } @@ -508,19 +535,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: * @@ -540,6 +567,11 @@ 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"); @@ -551,14 +583,16 @@ struct entity_view : public id { * 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; } @@ -567,13 +601,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; } @@ -615,19 +651,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 { @@ -639,10 +677,11 @@ 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 { @@ -663,16 +702,22 @@ 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"); @@ -684,8 +729,9 @@ struct entity_view : public id { * 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 { @@ -705,7 +751,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 Second* try_get_mut_second() const { @@ -716,9 +763,9 @@ struct entity_view : public id { /* 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> @@ -732,12 +779,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(); @@ -750,36 +797,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 { @@ -789,33 +842,40 @@ 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"); @@ -827,14 +887,16 @@ struct entity_view : public id { * 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; } @@ -843,17 +905,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 *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; @@ -864,6 +932,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; @@ -875,36 +944,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. @@ -913,7 +997,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. @@ -989,7 +1073,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 { @@ -1000,7 +1084,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 { @@ -1012,7 +1096,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 { @@ -1023,7 +1107,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 { @@ -1036,7 +1120,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)); @@ -1056,7 +1140,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 { @@ -1068,14 +1152,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. @@ -1086,7 +1170,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. @@ -1101,18 +1185,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 { @@ -1161,11 +1245,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 @@ -1184,7 +1275,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. * @@ -1193,7 +1284,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. diff --git a/include/flecs/addons/cpp/field.hpp b/include/flecs/addons/cpp/field.hpp index 756fa047bd..a6ce8be146 100644 --- a/include/flecs/addons/cpp/field.hpp +++ b/include/flecs/addons/cpp/field.hpp @@ -30,7 +30,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. @@ -53,7 +53,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 */ @@ -62,25 +62,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. @@ -88,14 +88,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. diff --git a/include/flecs/addons/cpp/flecs.hpp b/include/flecs/addons/cpp/flecs.hpp index c41b89c6f6..657a243c24 100644 --- a/include/flecs/addons/cpp/flecs.hpp +++ b/include/flecs/addons/cpp/flecs.hpp @@ -134,9 +134,6 @@ struct each_delegate; #ifdef FLECS_DOC #include "mixins/doc/impl.hpp" #endif -#ifdef FLECS_DOC -#include "mixins/doc/impl.hpp" -#endif #ifdef FLECS_REST #include "mixins/rest/impl.hpp" #endif @@ -165,7 +162,7 @@ struct each_delegate; /** * @defgroup cpp_core Core - * Core ECS functionality (entities, storage, queries) + * Core ECS functionality (entities, storage, queries). * * @{ * @} diff --git a/include/flecs/addons/cpp/impl/field.hpp b/include/flecs/addons/cpp/impl/field.hpp index 3957a56a31..205e4abb7c 100644 --- a/include/flecs/addons/cpp/impl/field.hpp +++ b/include/flecs/addons/cpp/impl/field.hpp @@ -8,15 +8,25 @@ namespace flecs { +/** Construct a field from an iterator and field index. + * + * @param iter The iterator. + * @param index The field index. + */ template inline field::field(iter &iter, int32_t index) { *this = iter.field(index); } +/** Access an element at an index in the field. + * + * @param index The element index. + * @return Reference to the element. + */ template T& field::operator[](size_t index) const { - ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, - "invalid nullptr dereference of component type %s", + ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, + "invalid nullptr dereference of component type %s", _::type_name()); ecs_assert(index < count_, ECS_COLUMN_INDEX_OUT_OF_RANGE, "index %d out of range for array of component type %s", @@ -27,31 +37,31 @@ T& field::operator[](size_t index) const { return data_[index]; } -/** 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. */ template T& field::operator*() const { - ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, - "invalid nullptr dereference of component type %s", + ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, + "invalid nullptr dereference of component type %s", _::type_name()); return *data_; } -/** 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. */ template T* field::operator->() const { - ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, - "invalid nullptr dereference of component type %s", + ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, + "invalid nullptr dereference of component type %s", _::type_name()); - ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, - "-> operator invalid for array with >1 element of " + ecs_assert(data_ != nullptr, ECS_INVALID_OPERATION, + "-> operator invalid for an array with >1 element of " "component type %s, use [row] instead", _::type_name()); return data_; diff --git a/include/flecs/addons/cpp/impl/iter.hpp b/include/flecs/addons/cpp/impl/iter.hpp index da9f344ea3..eb3a6ad003 100644 --- a/include/flecs/addons/cpp/impl/iter.hpp +++ b/include/flecs/addons/cpp/impl/iter.hpp @@ -8,36 +8,44 @@ namespace flecs { +/** Get the entity associated with the system currently being run. */ inline flecs::entity iter::system() const { return flecs::entity(iter_->world, iter_->system); } +/** Get the entity associated with the event that triggered the observer. */ inline flecs::entity iter::event() const { return flecs::entity(iter_->world, iter_->event); } +/** Get the event ID (component or pair). */ inline flecs::id iter::event_id() const { return flecs::id(iter_->world, iter_->event_id); } +/** Get the iterator world. */ inline flecs::world iter::world() const { return flecs::world(iter_->world); } +/** Get the entity for a given row. */ inline flecs::entity iter::entity(size_t row) const { - ecs_assert(row < static_cast(iter_->count), + ecs_assert(row < static_cast(iter_->count), ECS_COLUMN_INDEX_OUT_OF_RANGE, NULL); return flecs::entity(iter_->world, iter_->entities[row]); } +/** Get the source entity for a field. */ inline flecs::entity iter::src(int8_t index) const { return flecs::entity(iter_->world, ecs_field_src(iter_, index)); } +/** Get the ID for a field. */ inline flecs::id iter::id(int8_t index) const { return flecs::id(iter_->world, ecs_field_id(iter_, index)); } +/** Get the pair ID for a field. */ inline flecs::id iter::pair(int8_t index) const { flecs::id_t id = ecs_field_id(iter_, index); ecs_check(ECS_HAS_ID_FLAG(id, PAIR), ECS_INVALID_PARAMETER, NULL); @@ -46,35 +54,41 @@ inline flecs::id iter::pair(int8_t index) const { return flecs::id(); } +/** Get the type of the current table. */ inline flecs::type iter::type() const { return flecs::type(iter_->world, ecs_table_get_type(iter_->table)); } +/** Get the current table. */ inline flecs::table iter::table() const { return flecs::table(iter_->real_world, iter_->table); } +/** Get the other table (used for on_add/on_remove observers). */ inline flecs::table iter::other_table() const { return flecs::table(iter_->real_world, iter_->other_table); } +/** Get the table range for the current result. */ inline flecs::table_range iter::range() const { - return flecs::table_range(iter_->real_world, iter_->table, + return flecs::table_range(iter_->real_world, iter_->table, iter_->offset, iter_->count); } +/** Get field data for a const 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); return get_field(index); } +/** 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); @@ -83,13 +97,14 @@ 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; @@ -99,6 +114,7 @@ inline flecs::entity iter::get_var(const char *name) const { 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); @@ -109,9 +125,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); } diff --git a/include/flecs/addons/cpp/impl/world.hpp b/include/flecs/addons/cpp/impl/world.hpp index ee90b9c280..615b2370ee 100644 --- a/include/flecs/addons/cpp/impl/world.hpp +++ b/include/flecs/addons/cpp/impl/world.hpp @@ -5,9 +5,10 @@ #pragma once -namespace flecs +namespace flecs { +/** Initialize built-in components. */ inline void world::init_builtin_components() { this->component(); this->component(); @@ -15,7 +16,7 @@ inline void world::init_builtin_components() { 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"); @@ -48,18 +49,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); @@ -68,35 +71,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_)); @@ -104,233 +113,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 { @@ -338,6 +388,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, @@ -347,6 +398,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 @@ -355,6 +407,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"); @@ -362,6 +415,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"); @@ -369,21 +423,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); @@ -393,7 +451,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()) @@ -408,24 +466,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)); } diff --git a/include/flecs/addons/cpp/iter.hpp b/include/flecs/addons/cpp/iter.hpp index ff101ce1f9..3a80a9f2c0 100644 --- a/include/flecs/addons/cpp/iter.hpp +++ b/include/flecs/addons/cpp/iter.hpp @@ -24,7 +24,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 @@ -77,26 +77,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()"); @@ -105,20 +116,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. @@ -137,14 +163,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() { @@ -152,97 +178,112 @@ 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. @@ -252,12 +293,12 @@ struct iter { 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. @@ -272,7 +313,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. */ @@ -283,8 +324,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)) { @@ -294,8 +339,13 @@ 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 , if_t< is_const_v > = 0> const A& field_at(int8_t index, size_t row) const { @@ -306,8 +356,13 @@ 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 , if_not_t< is_const_v > = 0> A& field_at(int8_t index, size_t row) const { @@ -320,9 +375,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( @@ -330,7 +385,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_); } @@ -346,18 +404,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; @@ -366,6 +433,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) { @@ -379,9 +448,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_); @@ -390,14 +459,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. @@ -412,7 +481,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 { @@ -426,13 +495,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); } @@ -442,7 +511,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 { @@ -463,13 +532,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); } diff --git a/include/flecs/addons/cpp/lifecycle_traits.hpp b/include/flecs/addons/cpp/lifecycle_traits.hpp index 895ef10e25..03a3b6b543 100644 --- a/include/flecs/addons/cpp/lifecycle_traits.hpp +++ b/include/flecs/addons/cpp/lifecycle_traits.hpp @@ -12,7 +12,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), @@ -62,9 +62,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), @@ -91,12 +91,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); @@ -106,8 +106,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, @@ -118,16 +118,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, @@ -138,19 +138,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 = @@ -258,12 +258,12 @@ ecs_move_t move_dtor(ecs_flags32_t &flags) { } } -// Traits to check for operator<, operator>, and operator== +// 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" @@ -272,34 +272,34 @@ using std::void_t; #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> {}; -// Selects the best comparison strategy based on available operators +// 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); @@ -331,13 +331,13 @@ int compare_impl(const void *a, const void *b, const ecs_type_info_t *) { if (rhs > lhs) return -1; return 0; } else { - // This branch should never be instantiated due to compare() check + // This branch should never be instantiated due to the compare() check. return 0; } } -// In order to have a generated compare hook, at least -// operator> or operator< must be defined: +// To have a generated compare hook, at least +// operator> or operator< must be defined. template ecs_cmp_t compare() { if constexpr (has_operator_less::value || has_operator_greater::value) { @@ -347,7 +347,7 @@ ecs_cmp_t compare() { } } -// Equals implementation +// Equals implementation. template bool equals_impl(const void *a, const void *b, const ecs_type_info_t *) { const T& lhs = *static_cast(a); @@ -364,12 +364,12 @@ ecs_equals_t equals() { } } -// 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 diff --git a/include/flecs/addons/cpp/log.hpp b/include/flecs/addons/cpp/log.hpp index b9cdf42ce1..7edfe415a2 100644 --- a/include/flecs/addons/cpp/log.hpp +++ b/include/flecs/addons/cpp/log.hpp @@ -16,31 +16,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); @@ -48,7 +67,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); @@ -56,7 +78,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); @@ -64,7 +89,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); @@ -72,7 +100,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); @@ -81,12 +112,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(); } diff --git a/include/flecs/addons/cpp/mixins/alerts/builder_i.hpp b/include/flecs/addons/cpp/mixins/alerts/builder_i.hpp index c816aa9086..7733c4981d 100644 --- a/include/flecs/addons/cpp/mixins/alerts/builder_i.hpp +++ b/include/flecs/addons/cpp/mixins/alerts/builder_i.hpp @@ -27,16 +27,16 @@ struct alert_builder_i : query_builder_i { : BaseClass(&desc->query, term_index) , desc_(desc) { } - /** Alert message. + /** Set the alert message. * * @see ecs_alert_desc_t::message - */ + */ Base& message(const char *message) { desc_->message = message; return *this; } - /** Set brief description for alert. + /** Set the brief description for an alert. * * @see ecs_alert_desc_t::brief */ @@ -45,7 +45,7 @@ struct alert_builder_i : query_builder_i { return *this; } - /** Set doc name for alert. + /** Set the doc name for an alert. * * @see ecs_alert_desc_t::doc_name */ @@ -54,8 +54,8 @@ struct alert_builder_i : query_builder_i { return *this; } - /** Set severity of alert (default is Error) - * + /** Set the severity of an alert (default is Error). + * * @see ecs_alert_desc_t::severity */ Base& severity(flecs::entity_t kind) { @@ -63,8 +63,8 @@ struct alert_builder_i : query_builder_i { return *this; } - /* Set retain period of alert. - * + /** Set the retain period of an alert. + * * @see ecs_alert_desc_t::retain_period */ Base& retain_period(ecs_ftime_t period) { @@ -72,8 +72,9 @@ struct alert_builder_i : query_builder_i { return *this; } - /** Set severity of alert (default is Error) - * + /** Set the severity of an alert (default is Error). + * + * @tparam Severity The severity type. * @see ecs_alert_desc_t::severity */ template @@ -81,7 +82,12 @@ struct alert_builder_i : query_builder_i { return severity(_::type::id(world_v())); } - /** Add severity filter */ + /** Add a severity filter. + * + * @param kind The severity entity. + * @param with The ID to match for this severity. + * @param var The variable to use for the ID (optional). + */ Base& severity_filter(flecs::entity_t kind, flecs::id_t with, const char *var = nullptr) { ecs_assert(severity_filter_count < ECS_ALERT_MAX_SEVERITY_FILTERS, ECS_INVALID_PARAMETER, "Maximum number of severity filters reached"); @@ -95,20 +101,36 @@ struct alert_builder_i : query_builder_i { return *this; } - /** Add severity filter */ + /** Add a severity filter. + * + * @tparam Severity The severity type. + * @param with The ID to match for this severity. + * @param var The variable to use for the ID (optional). + */ template Base& severity_filter(flecs::id_t with, const char *var = nullptr) { return severity_filter(_::type::id(world_v()), with, var); } - /** Add severity filter */ + /** Add a severity filter. + * + * @tparam Severity The severity type. + * @tparam T The component type to match for this severity. + * @param var The variable to use for the ID (optional). + */ template ::value > = 0> Base& severity_filter(const char *var = nullptr) { return severity_filter(_::type::id(world_v()), _::type::id(world_v()), var); } - /** Add severity filter */ + /** Add a severity filter. + * + * @tparam Severity The severity type. + * @tparam T The enum type to match for this severity. + * @param with The enum constant to match. + * @param var The variable to use for the ID (optional). + */ template ::value > = 0 > Base& severity_filter(T with, const char *var = nullptr) { flecs::world w(world_v()); @@ -117,20 +139,20 @@ struct alert_builder_i : query_builder_i { w.pair(constant), var); } - /** Set member to create an alert for out of range values */ + /** Set the member to create an alert for out-of-range values. */ Base& member(flecs::entity_t m) { desc_->member = m; return *this; } - /** Set (component) id for member (optional). If .member() is set and id - * is not set, the id will default to the member parent. */ + /** Set the (component) ID for the member (optional). If .member() is set + * and the ID is not set, the ID will default to the member parent. */ Base& id(flecs::id_t id) { desc_->id = id; return *this; } - /** Set member to create an alert for out of range values */ + /** Set the member to create an alert for out-of-range values. */ template Base& member(const char *m, const char *v = nullptr) { flecs::entity_t id = _::type::id(world_v()); @@ -141,7 +163,7 @@ struct alert_builder_i : query_builder_i { return this->member(mid); } - /** Set source variable for member (optional, defaults to $this) */ + /** Set the source variable for member (optional, defaults to $this). */ Base& var(const char *v) { desc_->var = v; return *this; diff --git a/include/flecs/addons/cpp/mixins/alerts/decl.hpp b/include/flecs/addons/cpp/mixins/alerts/decl.hpp index d5b8b5f63c..ba88255cde 100644 --- a/include/flecs/addons/cpp/mixins/alerts/decl.hpp +++ b/include/flecs/addons/cpp/mixins/alerts/decl.hpp @@ -15,7 +15,7 @@ namespace flecs { * @{ */ -/** Module */ +/** Module. */ struct alerts { using AlertsActive = EcsAlertsActive; using Instance = EcsAlertInstance; diff --git a/include/flecs/addons/cpp/mixins/alerts/entity_view.inl b/include/flecs/addons/cpp/mixins/alerts/entity_view.inl index d46832b5b7..32d3991117 100644 --- a/include/flecs/addons/cpp/mixins/alerts/entity_view.inl +++ b/include/flecs/addons/cpp/mixins/alerts/entity_view.inl @@ -3,7 +3,7 @@ * @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 diff --git a/include/flecs/addons/cpp/mixins/alerts/impl.hpp b/include/flecs/addons/cpp/mixins/alerts/impl.hpp index b01c4dd6c8..8afee4da94 100644 --- a/include/flecs/addons/cpp/mixins/alerts/impl.hpp +++ b/include/flecs/addons/cpp/mixins/alerts/impl.hpp @@ -28,7 +28,7 @@ struct alert final : entity inline alerts::alerts(flecs::world& world) { world.import(); - /* Import C module */ + // Import C module. FlecsAlertsImport(world); world.component(); diff --git a/include/flecs/addons/cpp/mixins/alerts/mixin.inl b/include/flecs/addons/cpp/mixins/alerts/mixin.inl index d0a0756b1e..1c1afc1e40 100644 --- a/include/flecs/addons/cpp/mixins/alerts/mixin.inl +++ b/include/flecs/addons/cpp/mixins/alerts/mixin.inl @@ -1,6 +1,10 @@ +/** + * @file addons/cpp/mixins/alerts/mixin.inl + * @brief Alert world mixin. + */ -/** Create alert. - * +/** Create an alert. + * * @ingroup cpp_addons_alerts * @memberof flecs::world */ diff --git a/include/flecs/addons/cpp/mixins/app/builder.hpp b/include/flecs/addons/cpp/mixins/app/builder.hpp index 9bcd1fae87..fe78cdddcb 100644 --- a/include/flecs/addons/cpp/mixins/app/builder.hpp +++ b/include/flecs/addons/cpp/mixins/app/builder.hpp @@ -15,7 +15,7 @@ namespace flecs { * @{ */ -/** App builder interface */ +/** App builder interface. */ struct app_builder { app_builder(flecs::world_t *world) : world_(world) @@ -29,52 +29,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_); diff --git a/include/flecs/addons/cpp/mixins/app/mixin.inl b/include/flecs/addons/cpp/mixins/app/mixin.inl index dee8129855..67c9fa878c 100644 --- a/include/flecs/addons/cpp/mixins/app/mixin.inl +++ b/include/flecs/addons/cpp/mixins/app/mixin.inl @@ -10,11 +10,11 @@ * @{ */ -/** 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_; diff --git a/include/flecs/addons/cpp/mixins/component/impl.hpp b/include/flecs/addons/cpp/mixins/component/impl.hpp index fe77fcc57c..c6078e551d 100644 --- a/include/flecs/addons/cpp/mixins/component/impl.hpp +++ b/include/flecs/addons/cpp/mixins/component/impl.hpp @@ -1,6 +1,6 @@ /** * @file addons/cpp/mixins/component/impl.hpp - * @brief Component mixin implementation + * @brief Component mixin implementation. */ #pragma once diff --git a/include/flecs/addons/cpp/mixins/component/mixin.inl b/include/flecs/addons/cpp/mixins/component/mixin.inl index dafed1c4a2..27c373a650 100644 --- a/include/flecs/addons/cpp/mixins/component/mixin.inl +++ b/include/flecs/addons/cpp/mixins/component/mixin.inl @@ -3,7 +3,7 @@ * @brief Component mixin. */ -/** Find or register component. +/** Find or register a component. * * @ingroup cpp_components * @memberof flecs::world @@ -11,8 +11,8 @@ 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 diff --git a/include/flecs/addons/cpp/mixins/doc/decl.hpp b/include/flecs/addons/cpp/mixins/doc/decl.hpp index 6a87ae436e..60685a0838 100644 --- a/include/flecs/addons/cpp/mixins/doc/decl.hpp +++ b/include/flecs/addons/cpp/mixins/doc/decl.hpp @@ -11,27 +11,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 */ diff --git a/include/flecs/addons/cpp/mixins/doc/entity_builder.inl b/include/flecs/addons/cpp/mixins/doc/entity_builder.inl index bfad3c7d6f..f245b009bc 100644 --- a/include/flecs/addons/cpp/mixins/doc/entity_builder.inl +++ b/include/flecs/addons/cpp/mixins/doc/entity_builder.inl @@ -3,7 +3,7 @@ * @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() diff --git a/include/flecs/addons/cpp/mixins/doc/entity_view.inl b/include/flecs/addons/cpp/mixins/doc/entity_view.inl index eee04f7199..7d15e4239b 100644 --- a/include/flecs/addons/cpp/mixins/doc/entity_view.inl +++ b/include/flecs/addons/cpp/mixins/doc/entity_view.inl @@ -3,7 +3,7 @@ * @brief Doc entity view mixin. */ -/** Get human readable name. +/** Get human-readable name. * * @see ecs_doc_get_name() * @see flecs::doc::get_name() diff --git a/include/flecs/addons/cpp/mixins/doc/impl.hpp b/include/flecs/addons/cpp/mixins/doc/impl.hpp index abcc77adf6..4fdb253d0f 100644 --- a/include/flecs/addons/cpp/mixins/doc/impl.hpp +++ b/include/flecs/addons/cpp/mixins/doc/impl.hpp @@ -20,7 +20,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() @@ -92,7 +92,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() diff --git a/include/flecs/addons/cpp/mixins/entity/builder.hpp b/include/flecs/addons/cpp/mixins/entity/builder.hpp index da9f3858cf..b7f86ba6fb 100644 --- a/include/flecs/addons/cpp/mixins/entity/builder.hpp +++ b/include/flecs/addons/cpp/mixins/entity/builder.hpp @@ -19,7 +19,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 { @@ -29,11 +29,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. @@ -44,14 +44,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); @@ -72,8 +72,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 { @@ -83,7 +83,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> @@ -94,11 +94,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 { @@ -111,8 +111,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 { @@ -173,7 +173,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. */ @@ -185,8 +185,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 @@ -216,7 +216,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 { @@ -270,7 +270,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 { @@ -279,7 +279,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 { @@ -288,7 +288,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 { @@ -297,7 +297,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 { @@ -325,11 +325,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 { @@ -339,7 +339,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> @@ -347,11 +347,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 { @@ -361,8 +361,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 { @@ -371,12 +371,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); @@ -438,7 +438,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 @@ -450,7 +450,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 @@ -459,7 +459,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. @@ -472,7 +472,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. @@ -485,29 +485,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)); @@ -568,11 +568,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() @@ -624,11 +624,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 @@ -640,7 +640,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 { @@ -695,8 +695,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. @@ -708,8 +708,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. @@ -721,13 +721,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)); @@ -735,8 +735,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. @@ -753,10 +753,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)); @@ -768,10 +768,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); @@ -829,7 +829,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. */ @@ -849,7 +849,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. */ @@ -870,7 +870,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 @@ -881,8 +881,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. @@ -894,8 +894,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. @@ -907,13 +907,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)); @@ -921,8 +921,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. @@ -936,13 +936,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)); @@ -951,13 +951,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); @@ -966,7 +966,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. @@ -975,14 +975,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. @@ -991,14 +991,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. @@ -1013,9 +1013,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. */ @@ -1033,9 +1033,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. */ @@ -1063,12 +1063,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. @@ -1076,12 +1076,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 { @@ -1122,8 +1122,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. */ @@ -1135,10 +1135,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 @@ -1147,8 +1147,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. @@ -1162,7 +1162,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_); @@ -1171,20 +1171,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(); diff --git a/include/flecs/addons/cpp/mixins/entity/impl.hpp b/include/flecs/addons/cpp/mixins/entity/impl.hpp index 1b100442a3..1d54641356 100644 --- a/include/flecs/addons/cpp/mixins/entity/impl.hpp +++ b/include/flecs/addons/cpp/mixins/entity/impl.hpp @@ -71,19 +71,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_); } diff --git a/include/flecs/addons/cpp/mixins/entity/mixin.inl b/include/flecs/addons/cpp/mixins/entity/mixin.inl index 861f3a3f83..22ee7cbeba 100644 --- a/include/flecs/addons/cpp/mixins/entity/mixin.inl +++ b/include/flecs/addons/cpp/mixins/entity/mixin.inl @@ -11,7 +11,7 @@ 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 @@ -19,7 +19,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 diff --git a/include/flecs/addons/cpp/mixins/enum/entity_view.inl b/include/flecs/addons/cpp/mixins/enum/entity_view.inl index ae5a448fe2..b5b9a5f3fc 100644 --- a/include/flecs/addons/cpp/mixins/enum/entity_view.inl +++ b/include/flecs/addons/cpp/mixins/enum/entity_view.inl @@ -3,7 +3,7 @@ * @brief Enum entity view mixin. */ -/** Convert entity to enum constant. +/** Convert an entity to an enum constant. * * @memberof flecs::entity_view * @ingroup cpp_entities diff --git a/include/flecs/addons/cpp/mixins/enum/mixin.inl b/include/flecs/addons/cpp/mixins/enum/mixin.inl index 7a1a651803..596fc2586f 100644 --- a/include/flecs/addons/cpp/mixins/enum/mixin.inl +++ b/include/flecs/addons/cpp/mixins/enum/mixin.inl @@ -3,7 +3,7 @@ * @brief Enum world mixin. */ -/** Convert enum constant to entity. +/** Convert an enum constant to an entity. * * @memberof flecs::world * @ingroup cpp_entities diff --git a/include/flecs/addons/cpp/mixins/event/builder.hpp b/include/flecs/addons/cpp/mixins/event/builder.hpp index 00ba00d35d..b2508a2c00 100644 --- a/include/flecs/addons/cpp/mixins/event/builder.hpp +++ b/include/flecs/addons/cpp/mixins/event/builder.hpp @@ -14,7 +14,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) @@ -26,7 +26,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_; @@ -35,10 +35,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() { @@ -47,25 +47,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_); @@ -73,7 +78,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; @@ -81,13 +86,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; @@ -95,18 +100,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_; @@ -114,6 +120,7 @@ struct event_builder_base { ecs_emit(world_, &desc_); } + /** Enqueue the event. */ void enqueue() { ids_.array = ids_array_; desc_.ids = &ids_; @@ -133,10 +140,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: @@ -145,13 +154,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; diff --git a/include/flecs/addons/cpp/mixins/event/decl.hpp b/include/flecs/addons/cpp/mixins/event/decl.hpp index 3208171009..1b8f8b5b76 100644 --- a/include/flecs/addons/cpp/mixins/event/decl.hpp +++ b/include/flecs/addons/cpp/mixins/event/decl.hpp @@ -10,17 +10,17 @@ 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>; diff --git a/include/flecs/addons/cpp/mixins/event/entity_builder.inl b/include/flecs/addons/cpp/mixins/event/entity_builder.inl index 68e01bc620..469844827a 100644 --- a/include/flecs/addons/cpp/mixins/event/entity_builder.inl +++ b/include/flecs/addons/cpp/mixins/event/entity_builder.inl @@ -3,36 +3,35 @@ * @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; - - diff --git a/include/flecs/addons/cpp/mixins/event/entity_view.inl b/include/flecs/addons/cpp/mixins/event/entity_view.inl index 7462a517cf..9d50367940 100644 --- a/include/flecs/addons/cpp/mixins/event/entity_view.inl +++ b/include/flecs/addons/cpp/mixins/event/entity_view.inl @@ -3,7 +3,7 @@ * @brief Event entity mixin. */ -/** Emit event for entity. +/** Emit an event for an entity. * * @memberof flecs::entity_view * @@ -16,7 +16,7 @@ void emit(flecs::entity_t evt) const { .emit(); } -/** Emit event for entity. +/** Emit an event for an entity. * * @memberof flecs::entity_view * @@ -24,7 +24,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 * @@ -35,7 +35,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 * @@ -51,7 +51,7 @@ void emit(const Evt& payload) const { } -/** Enqueue event for entity. +/** Enqueue an event for an entity. * * @memberof flecs::entity_view * @@ -64,7 +64,7 @@ void enqueue(flecs::entity_t evt) const { .enqueue(); } -/** Enqueue event for entity. +/** Enqueue an event for an entity. * * @memberof flecs::entity_view * @@ -72,7 +72,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 * @@ -83,7 +83,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 * diff --git a/include/flecs/addons/cpp/mixins/event/mixin.inl b/include/flecs/addons/cpp/mixins/event/mixin.inl index 32b31ee50b..a470e0d10d 100644 --- a/include/flecs/addons/cpp/mixins/event/mixin.inl +++ b/include/flecs/addons/cpp/mixins/event/mixin.inl @@ -15,7 +15,7 @@ * * @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; diff --git a/include/flecs/addons/cpp/mixins/id/decl.hpp b/include/flecs/addons/cpp/mixins/id/decl.hpp index f9850dea63..9a7559f8c3 100644 --- a/include/flecs/addons/cpp/mixins/id/decl.hpp +++ b/include/flecs/addons/cpp/mixins/id/decl.hpp @@ -1,6 +1,6 @@ /** * @file addons/cpp/mixins/id/decl.hpp - * @brief Id class. + * @brief ID class. */ #pragma once @@ -11,18 +11,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() @@ -53,53 +53,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; @@ -108,28 +108,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_; } @@ -138,12 +138,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_; }; diff --git a/include/flecs/addons/cpp/mixins/id/impl.hpp b/include/flecs/addons/cpp/mixins/id/impl.hpp index 3e37366610..5c5200178a 100644 --- a/include/flecs/addons/cpp/mixins/id/impl.hpp +++ b/include/flecs/addons/cpp/mixins/id/impl.hpp @@ -1,6 +1,6 @@ /** * @file addons/cpp/mixins/id/impl.hpp - * @brief Id class implementation. + * @brief ID class implementation. */ #pragma once @@ -64,7 +64,7 @@ inline flecs::entity id::type_id() const { } -// Id mixin implementation +// ID mixin implementation template inline flecs::id world::id() const { diff --git a/include/flecs/addons/cpp/mixins/id/mixin.inl b/include/flecs/addons/cpp/mixins/id/mixin.inl index 32aae0a143..853e8a292f 100644 --- a/include/flecs/addons/cpp/mixins/id/mixin.inl +++ b/include/flecs/addons/cpp/mixins/id/mixin.inl @@ -1,37 +1,37 @@ /** * @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 */ diff --git a/include/flecs/addons/cpp/mixins/json/entity.inl b/include/flecs/addons/cpp/mixins/json/entity.inl index a893e0618d..f1b28d80e9 100644 --- a/include/flecs/addons/cpp/mixins/json/entity.inl +++ b/include/flecs/addons/cpp/mixins/json/entity.inl @@ -1,5 +1,9 @@ +/** + * @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 diff --git a/include/flecs/addons/cpp/mixins/json/entity_builder.inl b/include/flecs/addons/cpp/mixins/json/entity_builder.inl index 16d2e12d4d..140b0fbff0 100644 --- a/include/flecs/addons/cpp/mixins/json/entity_builder.inl +++ b/include/flecs/addons/cpp/mixins/json/entity_builder.inl @@ -3,13 +3,13 @@ * @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 { @@ -29,13 +29,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 @@ -43,21 +43,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 */ @@ -72,8 +72,8 @@ const Self& set_json( json, desc); } -/** Set pair from JSON. - * +/** Set a pair from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ @@ -88,8 +88,8 @@ const Self& set_json( json, desc); } -/** Set pair from JSON. - * +/** Set a pair from JSON. + * * @memberof flecs::entity_builder * @ingroup cpp_addons_json */ diff --git a/include/flecs/addons/cpp/mixins/json/entity_view.inl b/include/flecs/addons/cpp/mixins/json/entity_view.inl index 5180bbf618..35a8aa35d8 100644 --- a/include/flecs/addons/cpp/mixins/json/entity_view.inl +++ b/include/flecs/addons/cpp/mixins/json/entity_view.inl @@ -3,7 +3,7 @@ * @brief JSON entity mixin. */ -/** Serialize entity to JSON. +/** Serialize an entity to JSON. * * @memberof flecs::entity_view * @ingroup cpp_addons_json diff --git a/include/flecs/addons/cpp/mixins/json/iterable.inl b/include/flecs/addons/cpp/mixins/json/iterable.inl index 612c92a94e..b7a266e45e 100644 --- a/include/flecs/addons/cpp/mixins/json/iterable.inl +++ b/include/flecs/addons/cpp/mixins/json/iterable.inl @@ -3,7 +3,7 @@ * @brief JSON iterable mixin. */ -/** Serialize iterator result to JSON. +/** Serialize an iterator result to JSON. * * @memberof flecs::iter * @ingroup cpp_addons_json diff --git a/include/flecs/addons/cpp/mixins/json/query.inl b/include/flecs/addons/cpp/mixins/json/query.inl index bcd172a848..7aa37335d8 100644 --- a/include/flecs/addons/cpp/mixins/json/query.inl +++ b/include/flecs/addons/cpp/mixins/json/query.inl @@ -1,5 +1,9 @@ +/** + * @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 diff --git a/include/flecs/addons/cpp/mixins/json/world.inl b/include/flecs/addons/cpp/mixins/json/world.inl index 1c6fba0587..92b42a82f7 100644 --- a/include/flecs/addons/cpp/mixins/json/world.inl +++ b/include/flecs/addons/cpp/mixins/json/world.inl @@ -3,7 +3,7 @@ * @brief JSON world mixin. */ -/** Serialize untyped value to JSON. +/** Serialize an untyped value to JSON. * * @memberof flecs::world * @ingroup cpp_addons_json @@ -13,7 +13,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 @@ -24,7 +24,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 @@ -33,8 +33,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 */ @@ -42,8 +42,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 */ @@ -53,7 +53,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 @@ -62,7 +62,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 diff --git a/include/flecs/addons/cpp/mixins/meta/component.inl b/include/flecs/addons/cpp/mixins/meta/component.inl index 43dc1ed858..1a163bade3 100644 --- a/include/flecs/addons/cpp/mixins/meta/component.inl +++ b/include/flecs/addons/cpp/mixins/meta/component.inl @@ -1,5 +1,9 @@ +/** + * @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_); @@ -9,25 +13,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; @@ -44,7 +51,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); diff --git a/include/flecs/addons/cpp/mixins/meta/cursor.hpp b/include/flecs/addons/cpp/mixins/meta/cursor.hpp index 868621c2db..15f7668b94 100644 --- a/include/flecs/addons/cpp/mixins/meta/cursor.hpp +++ b/include/flecs/addons/cpp/mixins/meta/cursor.hpp @@ -1,6 +1,6 @@ /** - * @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 @@ -24,136 +24,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_; }; diff --git a/include/flecs/addons/cpp/mixins/meta/decl.hpp b/include/flecs/addons/cpp/mixins/meta/decl.hpp index 0daa316251..99975c4ad6 100644 --- a/include/flecs/addons/cpp/mixins/meta/decl.hpp +++ b/include/flecs/addons/cpp/mixins/meta/decl.hpp @@ -15,7 +15,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; @@ -31,12 +31,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; @@ -49,12 +49,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); @@ -76,7 +76,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; @@ -87,7 +87,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; diff --git a/include/flecs/addons/cpp/mixins/meta/entity_builder.inl b/include/flecs/addons/cpp/mixins/meta/entity_builder.inl index a5b4843e08..cb39e67b12 100644 --- a/include/flecs/addons/cpp/mixins/meta/entity_builder.inl +++ b/include/flecs/addons/cpp/mixins/meta/entity_builder.inl @@ -4,13 +4,13 @@ */ /** - * @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, @@ -32,7 +32,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, @@ -52,8 +52,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 @@ -68,19 +68,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(); diff --git a/include/flecs/addons/cpp/mixins/meta/impl.hpp b/include/flecs/addons/cpp/mixins/meta/impl.hpp index a504ef426c..a561ed3536 100644 --- a/include/flecs/addons/cpp/mixins/meta/impl.hpp +++ b/include/flecs/addons/cpp/mixins/meta/impl.hpp @@ -12,7 +12,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() @@ -60,25 +60,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); @@ -104,7 +104,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; @@ -113,7 +113,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; @@ -123,7 +123,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); diff --git a/include/flecs/addons/cpp/mixins/meta/opaque.hpp b/include/flecs/addons/cpp/mixins/meta/opaque.hpp index e163a35a67..bf09dc3867 100644 --- a/include/flecs/addons/cpp/mixins/meta/opaque.hpp +++ b/include/flecs/addons/cpp/mixins/meta/opaque.hpp @@ -15,26 +15,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) { @@ -43,13 +43,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 untyped_component& member( const char *name, @@ -86,41 +86,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, @@ -131,11 +131,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_); @@ -143,7 +143,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( @@ -155,7 +155,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( @@ -168,7 +168,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( @@ -181,7 +181,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, @@ -202,7 +202,7 @@ untyped_component& constant( return *this; } -/** Add bitmask constant. */ +/** Add a bitmask constant. */ template untyped_component& bit( const char *name, @@ -223,7 +223,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) @@ -236,7 +236,7 @@ untyped_component& array( return *this; } -/** Add member value range */ +/** Add a member value range. */ untyped_component& range( double min, double max) @@ -263,7 +263,7 @@ untyped_component& range( return *this; } -/** Add member warning range */ +/** Add a member warning range. */ untyped_component& warning_range( double min, double max) @@ -290,7 +290,7 @@ untyped_component& warning_range( return *this; } -/** Add member error range */ +/** Add a member error range. */ untyped_component& error_range( double min, double max) diff --git a/include/flecs/addons/cpp/mixins/meta/world.inl b/include/flecs/addons/cpp/mixins/meta/world.inl index 707f94c30a..8ee1169588 100644 --- a/include/flecs/addons/cpp/mixins/meta/world.inl +++ b/include/flecs/addons/cpp/mixins/meta/world.inl @@ -10,32 +10,32 @@ * @{ */ -/** 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(); diff --git a/include/flecs/addons/cpp/mixins/metrics/builder.hpp b/include/flecs/addons/cpp/mixins/metrics/builder.hpp index b8cc961b19..28a075413d 100644 --- a/include/flecs/addons/cpp/mixins/metrics/builder.hpp +++ b/include/flecs/addons/cpp/mixins/metrics/builder.hpp @@ -5,8 +5,6 @@ #pragma once -#define ECS_EVENT_DESC_ID_COUNT_MAX (8) - namespace flecs { /** @@ -14,81 +12,99 @@ namespace flecs { * @{ */ -/** Event builder interface */ +/** Metric builder interface. */ struct metric_builder { - metric_builder(flecs::world_t *world, flecs::entity_t entity) - : world_(world) + /** Construct a metric builder. */ + metric_builder(flecs::world_t *world, flecs::entity_t entity) + : world_(world) { desc_.entity = entity; } + /** Destructor. Finalizes the metric. */ ~metric_builder(); + /** Set the member to use for the metric by entity ID. */ metric_builder& member(flecs::entity_t e) { desc_.member = e; return *this; } + /** Set the member to use for the metric by name. */ metric_builder& member(const char *name); + /** Set the member to use for the metric by type and name. */ template 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: diff --git a/include/flecs/addons/cpp/mixins/metrics/decl.hpp b/include/flecs/addons/cpp/mixins/metrics/decl.hpp index 0a394395c6..6b40569a91 100644 --- a/include/flecs/addons/cpp/mixins/metrics/decl.hpp +++ b/include/flecs/addons/cpp/mixins/metrics/decl.hpp @@ -18,17 +18,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); }; diff --git a/include/flecs/addons/cpp/mixins/metrics/impl.hpp b/include/flecs/addons/cpp/mixins/metrics/impl.hpp index e8b5b61320..377de16ce3 100644 --- a/include/flecs/addons/cpp/mixins/metrics/impl.hpp +++ b/include/flecs/addons/cpp/mixins/metrics/impl.hpp @@ -10,7 +10,7 @@ namespace flecs { inline metrics::metrics(flecs::world& world) { world.import(); - /* Import C module */ + // Import C module. FlecsMetricsImport(world); world.component(); diff --git a/include/flecs/addons/cpp/mixins/metrics/mixin.inl b/include/flecs/addons/cpp/mixins/metrics/mixin.inl index b810416590..a59dce70ae 100644 --- a/include/flecs/addons/cpp/mixins/metrics/mixin.inl +++ b/include/flecs/addons/cpp/mixins/metrics/mixin.inl @@ -1,6 +1,10 @@ +/** + * @file addons/cpp/mixins/metrics/mixin.inl + * @brief Metrics world mixin. + */ -/** Create metric. - * +/** Create a metric. + * * @ingroup cpp_addons_metrics * @memberof flecs::world */ diff --git a/include/flecs/addons/cpp/mixins/metrics/untyped_component.inl b/include/flecs/addons/cpp/mixins/metrics/untyped_component.inl index f0d458815f..10b5a02656 100644 --- a/include/flecs/addons/cpp/mixins/metrics/untyped_component.inl +++ b/include/flecs/addons/cpp/mixins/metrics/untyped_component.inl @@ -1,5 +1,5 @@ /** - * @file addons/cpp/mixins/meta/untyped_component.inl + * @file addons/cpp/mixins/metrics/untyped_component.inl * @brief Metrics component mixin. */ @@ -10,16 +10,16 @@ * @{ */ -/** 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). diff --git a/include/flecs/addons/cpp/mixins/module/impl.hpp b/include/flecs/addons/cpp/mixins/module/impl.hpp index a406d9b576..22d316aaeb 100644 --- a/include/flecs/addons/cpp/mixins/module/impl.hpp +++ b/include/flecs/addons/cpp/mixins/module/impl.hpp @@ -16,12 +16,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); @@ -33,7 +33,7 @@ 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, "%s", symbol); ecs_assert(m == c_, ECS_INTERNAL_ERROR, NULL); @@ -50,17 +50,17 @@ flecs::entity import(world& world) { 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); } @@ -74,7 +74,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. * * @{ */ @@ -89,7 +89,7 @@ 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(); diff --git a/include/flecs/addons/cpp/mixins/observer/builder.hpp b/include/flecs/addons/cpp/mixins/observer/builder.hpp index 74d1440de7..99bfda58c7 100644 --- a/include/flecs/addons/cpp/mixins/observer/builder.hpp +++ b/include/flecs/addons/cpp/mixins/observer/builder.hpp @@ -22,6 +22,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) { diff --git a/include/flecs/addons/cpp/mixins/observer/builder_i.hpp b/include/flecs/addons/cpp/mixins/observer/builder_i.hpp index 533d58ad87..2c1fb02512 100644 --- a/include/flecs/addons/cpp/mixins/observer/builder_i.hpp +++ b/include/flecs/addons/cpp/mixins/observer/builder_i.hpp @@ -16,12 +16,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) { } @@ -43,25 +45,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; diff --git a/include/flecs/addons/cpp/mixins/observer/impl.hpp b/include/flecs/addons/cpp/mixins/observer/impl.hpp index 6b0e05d1bc..3d1438b470 100644 --- a/include/flecs/addons/cpp/mixins/observer/impl.hpp +++ b/include/flecs/addons/cpp/mixins/observer/impl.hpp @@ -10,17 +10,24 @@ 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_; @@ -28,16 +35,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); } diff --git a/include/flecs/addons/cpp/mixins/observer/mixin.inl b/include/flecs/addons/cpp/mixins/observer/mixin.inl index 3becc94964..58e0574c06 100644 --- a/include/flecs/addons/cpp/mixins/observer/mixin.inl +++ b/include/flecs/addons/cpp/mixins/observer/mixin.inl @@ -3,15 +3,15 @@ * @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. @@ -23,7 +23,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; diff --git a/include/flecs/addons/cpp/mixins/pipeline/builder.hpp b/include/flecs/addons/cpp/mixins/pipeline/builder.hpp index 4e99fc00d4..2ed30019d5 100644 --- a/include/flecs/addons/cpp/mixins/pipeline/builder.hpp +++ b/include/flecs/addons/cpp/mixins/pipeline/builder.hpp @@ -22,6 +22,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) { diff --git a/include/flecs/addons/cpp/mixins/pipeline/builder_i.hpp b/include/flecs/addons/cpp/mixins/pipeline/builder_i.hpp index e3349da136..c288eab8fa 100644 --- a/include/flecs/addons/cpp/mixins/pipeline/builder_i.hpp +++ b/include/flecs/addons/cpp/mixins/pipeline/builder_i.hpp @@ -15,7 +15,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) { } diff --git a/include/flecs/addons/cpp/mixins/pipeline/decl.hpp b/include/flecs/addons/cpp/mixins/pipeline/decl.hpp index 0ea1f6f248..36eb85bae6 100644 --- a/include/flecs/addons/cpp/mixins/pipeline/decl.hpp +++ b/include/flecs/addons/cpp/mixins/pipeline/decl.hpp @@ -15,23 +15,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; /** @} */ diff --git a/include/flecs/addons/cpp/mixins/pipeline/mixin.inl b/include/flecs/addons/cpp/mixins/pipeline/mixin.inl index 0f34c7c0e4..dede7d641f 100644 --- a/include/flecs/addons/cpp/mixins/pipeline/mixin.inl +++ b/include/flecs/addons/cpp/mixins/pipeline/mixin.inl @@ -18,77 +18,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; diff --git a/include/flecs/addons/cpp/mixins/query/builder_i.hpp b/include/flecs/addons/cpp/mixins/query/builder_i.hpp index 07a27be8bb..300c72c5b8 100644 --- a/include/flecs/addons/cpp/mixins/query/builder_i.hpp +++ b/include/flecs/addons/cpp/mixins/query/builder_i.hpp @@ -16,30 +16,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"); @@ -50,8 +56,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(); @@ -61,57 +70,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()); @@ -119,90 +138,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_), @@ -221,7 +260,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. */ @@ -243,8 +282,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_; @@ -256,8 +294,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); @@ -299,11 +337,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; @@ -312,7 +350,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. * @@ -325,7 +363,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)) { @@ -334,10 +372,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); @@ -346,7 +384,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. */ @@ -356,7 +394,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. */ @@ -364,10 +402,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; @@ -375,15 +413,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; diff --git a/include/flecs/addons/cpp/mixins/query/impl.hpp b/include/flecs/addons/cpp/mixins/query/impl.hpp index 94a4e83f9f..f5632e79f6 100644 --- a/include/flecs/addons/cpp/mixins/query/impl.hpp +++ b/include/flecs/addons/cpp/mixins/query/impl.hpp @@ -10,19 +10,27 @@ 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( @@ -37,6 +45,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_) @@ -45,6 +54,7 @@ struct query_base { } } + /** Copy assignment operator. */ query_base& operator=(const query_base& obj) { this->~query_base(); this->query_ = obj.query_; @@ -55,37 +65,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; } + /** 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() " @@ -94,11 +110,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_); @@ -107,7 +120,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 @@ -120,18 +133,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 { @@ -143,6 +156,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 ++) { @@ -152,36 +166,42 @@ struct query_base { } } + /** Get term at the specified index. */ flecs::term term(int32_t index) const { return flecs::term(query_->world, query_->terms[index]); } + /** Get the number of terms in the query. */ int32_t term_count() const { return query_->term_count; } + /** Get the number of fields in the query. */ int32_t field_count() const { return query_->field_count; } + /** Find a variable by name. */ int32_t find_var(const char *name) const { return ecs_query_find_var(query_, name); } + /** 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 @@ -192,6 +212,10 @@ struct query_base { query_t *query_ = nullptr; }; +/** Typed query. + * + * @ingroup cpp_core_queries + */ template struct query : query_base, iterable { private: @@ -200,22 +224,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); @@ -295,7 +325,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; diff --git a/include/flecs/addons/cpp/mixins/query/mixin.inl b/include/flecs/addons/cpp/mixins/query/mixin.inl index 3d0a0fc8a4..132d36903b 100644 --- a/include/flecs/addons/cpp/mixins/query/mixin.inl +++ b/include/flecs/addons/cpp/mixins/query/mixin.inl @@ -12,25 +12,25 @@ /** 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 @@ -53,7 +53,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 @@ -70,7 +70,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; diff --git a/include/flecs/addons/cpp/mixins/rest/decl.hpp b/include/flecs/addons/cpp/mixins/rest/decl.hpp index fac86b2de1..2115a6e779 100644 --- a/include/flecs/addons/cpp/mixins/rest/decl.hpp +++ b/include/flecs/addons/cpp/mixins/rest/decl.hpp @@ -15,6 +15,7 @@ namespace flecs { * @{ */ +/** REST API component. */ using Rest = EcsRest; namespace rest { diff --git a/include/flecs/addons/cpp/mixins/script/builder.hpp b/include/flecs/addons/cpp/mixins/script/builder.hpp index 1a244b7545..39b79bf0b8 100644 --- a/include/flecs/addons/cpp/mixins/script/builder.hpp +++ b/include/flecs/addons/cpp/mixins/script/builder.hpp @@ -12,8 +12,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_{} @@ -27,16 +31,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: diff --git a/include/flecs/addons/cpp/mixins/script/mixin.inl b/include/flecs/addons/cpp/mixins/script/mixin.inl index 2d701dd23e..20c829df97 100644 --- a/include/flecs/addons/cpp/mixins/script/mixin.inl +++ b/include/flecs/addons/cpp/mixins/script/mixin.inl @@ -11,41 +11,41 @@ * @{ */ -/** 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. * @@ -65,7 +65,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. * diff --git a/include/flecs/addons/cpp/mixins/stats/decl.hpp b/include/flecs/addons/cpp/mixins/stats/decl.hpp index 2435aa3a64..5368d9c533 100644 --- a/include/flecs/addons/cpp/mixins/stats/decl.hpp +++ b/include/flecs/addons/cpp/mixins/stats/decl.hpp @@ -15,16 +15,18 @@ namespace flecs { * @{ */ -/** Component that stores world statistics */ +/** Component that stores world statistics. */ using WorldStats = EcsWorldStats; -/** Component that stores system/pipeline statistics */ +/** Component that stores system/pipeline statistics. */ using PipelineStats = EcsPipelineStats; -/** Component with world summary stats */ +/** Component with world summary stats. */ using WorldSummary = EcsWorldSummary; +/** Stats module. */ struct stats { + /** Construct the stats module. */ stats(flecs::world& world); }; diff --git a/include/flecs/addons/cpp/mixins/stats/impl.hpp b/include/flecs/addons/cpp/mixins/stats/impl.hpp index 8b7da3a7db..5e9ca808db 100644 --- a/include/flecs/addons/cpp/mixins/stats/impl.hpp +++ b/include/flecs/addons/cpp/mixins/stats/impl.hpp @@ -1,6 +1,6 @@ /** * @file addons/cpp/mixins/stats/impl.hpp - * @brief Monitor module implementation. + * @brief Stats module implementation. */ #pragma once @@ -12,7 +12,7 @@ inline stats::stats(flecs::world& world) { world.import(); #endif - /* Import C module */ + // Import C module. FlecsStatsImport(world); world.component(); diff --git a/include/flecs/addons/cpp/mixins/system/builder_i.hpp b/include/flecs/addons/cpp/mixins/system/builder_i.hpp index 58634cc057..69283cca47 100644 --- a/include/flecs/addons/cpp/mixins/system/builder_i.hpp +++ b/include/flecs/addons/cpp/mixins/system/builder_i.hpp @@ -42,6 +42,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) { @@ -59,26 +63,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. * @@ -89,8 +93,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. * @@ -103,8 +107,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. * @@ -115,7 +119,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. @@ -126,7 +130,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. @@ -136,13 +140,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; diff --git a/include/flecs/addons/cpp/mixins/system/decl.hpp b/include/flecs/addons/cpp/mixins/system/decl.hpp index d8203c6879..be1b880c9e 100644 --- a/include/flecs/addons/cpp/mixins/system/decl.hpp +++ b/include/flecs/addons/cpp/mixins/system/decl.hpp @@ -10,15 +10,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; diff --git a/include/flecs/addons/cpp/mixins/system/impl.hpp b/include/flecs/addons/cpp/mixins/system/impl.hpp index e50cfe8414..2e32a28fa8 100644 --- a/include/flecs/addons/cpp/mixins/system/impl.hpp +++ b/include/flecs/addons/cpp/mixins/system/impl.hpp @@ -10,13 +10,18 @@ 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) @@ -25,21 +30,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( @@ -61,20 +70,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_; @@ -82,29 +98,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, @@ -121,7 +143,7 @@ struct system final : entity }; -// Mixin implementation +/** Mixin implementation. */ inline system world::system(flecs::entity e) const { return flecs::system(world_, e); } diff --git a/include/flecs/addons/cpp/mixins/system/mixin.inl b/include/flecs/addons/cpp/mixins/system/mixin.inl index 1d6d7fcb21..52b846e909 100644 --- a/include/flecs/addons/cpp/mixins/system/mixin.inl +++ b/include/flecs/addons/cpp/mixins/system/mixin.inl @@ -3,14 +3,14 @@ * @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. @@ -22,7 +22,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; diff --git a/include/flecs/addons/cpp/mixins/term/builder_i.hpp b/include/flecs/addons/cpp/mixins/term/builder_i.hpp index a9c7c85820..18705a6b5b 100644 --- a/include/flecs/addons/cpp/mixins/term/builder_i.hpp +++ b/include/flecs/addons/cpp/mixins/term/builder_i.hpp @@ -13,36 +13,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*). */ @@ -52,7 +54,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; @@ -60,7 +62,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; @@ -68,13 +70,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: @@ -98,25 +101,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(); @@ -124,7 +130,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(); @@ -132,21 +138,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); @@ -159,21 +165,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); @@ -186,21 +192,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); @@ -213,8 +219,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(); @@ -230,13 +236,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(); @@ -247,24 +254,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; @@ -272,21 +280,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. @@ -303,104 +311,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::Not) */ + /** Short for oper(flecs::Not). */ Base& not_() { return this->oper(flecs::Not); } - /* Short for oper(flecs::Optional) */ + /** 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; } diff --git a/include/flecs/addons/cpp/mixins/term/impl.hpp b/include/flecs/addons/cpp/mixins/term/impl.hpp index e2b98d2371..de8df25488 100644 --- a/include/flecs/addons/cpp/mixins/term/impl.hpp +++ b/include/flecs/addons/cpp/mixins/term/impl.hpp @@ -14,16 +14,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({}) @@ -32,6 +35,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({}) @@ -44,6 +48,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({}) @@ -52,10 +57,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 { @@ -63,51 +69,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: @@ -117,7 +134,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)...); diff --git a/include/flecs/addons/cpp/mixins/timer/decl.hpp b/include/flecs/addons/cpp/mixins/timer/decl.hpp index ccdf879901..cf575cd170 100644 --- a/include/flecs/addons/cpp/mixins/timer/decl.hpp +++ b/include/flecs/addons/cpp/mixins/timer/decl.hpp @@ -15,9 +15,12 @@ namespace flecs { * @{ */ +/** Timer component. */ using Timer = EcsTimer; +/** Rate filter component. */ using RateFilter = EcsRateFilter; +/** Forward declaration for timer. */ struct timer; /** @} */ diff --git a/include/flecs/addons/cpp/mixins/timer/impl.hpp b/include/flecs/addons/cpp/mixins/timer/impl.hpp index e26c19db85..91818c7b75 100644 --- a/include/flecs/addons/cpp/mixins/timer/impl.hpp +++ b/include/flecs/addons/cpp/mixins/timer/impl.hpp @@ -7,37 +7,47 @@ 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_); } @@ -53,43 +63,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); } diff --git a/include/flecs/addons/cpp/mixins/timer/mixin.inl b/include/flecs/addons/cpp/mixins/timer/mixin.inl index 6c780e2aa1..92e5b2ea7c 100644 --- a/include/flecs/addons/cpp/mixins/timer/mixin.inl +++ b/include/flecs/addons/cpp/mixins/timer/mixin.inl @@ -17,6 +17,6 @@ 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; diff --git a/include/flecs/addons/cpp/mixins/timer/system_mixin.inl b/include/flecs/addons/cpp/mixins/timer/system_mixin.inl index 2457bcec3d..032a4e2e78 100644 --- a/include/flecs/addons/cpp/mixins/timer/system_mixin.inl +++ b/include/flecs/addons/cpp/mixins/timer/system_mixin.inl @@ -11,48 +11,48 @@ */ /** 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); diff --git a/include/flecs/addons/cpp/mixins/units/decl.hpp b/include/flecs/addons/cpp/mixins/units/decl.hpp index 05592bcfd5..fd1ac1e619 100644 --- a/include/flecs/addons/cpp/mixins/units/decl.hpp +++ b/include/flecs/addons/cpp/mixins/units/decl.hpp @@ -6,6 +6,7 @@ #pragma once namespace flecs { +/** Units module. */ struct units { /** @@ -16,43 +17,72 @@ struct units { * @{ */ +/** Prefixes scope. */ struct Prefixes { }; /** * @defgroup cpp_addons_units_prefixes Prefixes * @ingroup cpp_addons_units - * Prefixes to indicate unit count (e.g. Kilo, Mega) + * Prefixes to indicate unit count (e.g., Kilo, Mega). * * @{ */ +/** Yocto prefix (10^-24). */ struct Yocto { }; +/** Zepto prefix (10^-21). */ struct Zepto { }; +/** Atto prefix (10^-18). */ struct Atto { }; +/** Femto prefix (10^-15). */ struct Femto { }; +/** Pico prefix (10^-12). */ struct Pico { }; +/** Nano prefix (10^-9). */ struct Nano { }; +/** Micro prefix (10^-6). */ struct Micro { }; +/** Milli prefix (10^-3). */ struct Milli { }; +/** Centi prefix (10^-2). */ struct Centi { }; +/** Deci prefix (10^-1). */ struct Deci { }; +/** Deca prefix (10^1). */ struct Deca { }; +/** Hecto prefix (10^2). */ struct Hecto { }; +/** Kilo prefix (10^3). */ struct Kilo { }; +/** Mega prefix (10^6). */ struct Mega { }; +/** Giga prefix (10^9). */ struct Giga { }; +/** Tera prefix (10^12). */ struct Tera { }; +/** Peta prefix (10^15). */ struct Peta { }; +/** Exa prefix (10^18). */ struct Exa { }; +/** Zetta prefix (10^21). */ struct Zetta { }; +/** Yotta prefix (10^24). */ struct Yotta { }; +/** Kibi prefix (2^10). */ struct Kibi { }; +/** Mebi prefix (2^20). */ struct Mebi { }; +/** Gibi prefix (2^30). */ struct Gibi { }; +/** Tebi prefix (2^40). */ struct Tebi { }; +/** Pebi prefix (2^50). */ struct Pebi { }; +/** Exbi prefix (2^60). */ struct Exbi { }; +/** Zebi prefix (2^70). */ struct Zebi { }; +/** Yobi prefix (2^80). */ struct Yobi { }; /** @} */ @@ -60,31 +90,49 @@ struct Yobi { }; /** * @defgroup cpp_addons_units_quantities Quantities * @ingroup cpp_addons_units - * Quantities that group units (e.g. Length) + * Quantities that group units (e.g., Length). * * @{ */ +/** Duration quantity. */ struct Duration { }; +/** Time quantity. */ struct Time { }; +/** Mass quantity. */ struct Mass { }; +/** Electric current quantity. */ struct ElectricCurrent { }; +/** Luminous intensity quantity. */ struct LuminousIntensity { }; +/** Force quantity. */ struct Force { }; +/** Amount quantity. */ struct Amount { }; +/** Length quantity. */ struct Length { }; +/** Pressure quantity. */ struct Pressure { }; +/** Speed quantity. */ struct Speed { }; +/** Temperature quantity. */ struct Temperature { }; +/** Data quantity. */ struct Data { }; +/** Data rate quantity. */ struct DataRate { }; +/** Angle quantity. */ struct Angle { }; +/** Frequency quantity. */ struct Frequency { }; +/** URI quantity. */ struct Uri { }; +/** Color quantity. */ struct Color { }; /** @} */ +/** Duration units. */ struct duration { /** * @defgroup cpp_addons_units_duration Duration @@ -92,18 +140,27 @@ struct duration { * @{ */ +/** PicoSeconds unit. */ struct PicoSeconds { }; +/** NanoSeconds unit. */ struct NanoSeconds { }; +/** MicroSeconds unit. */ struct MicroSeconds { }; +/** MilliSeconds unit. */ struct MilliSeconds { }; +/** Seconds unit. */ struct Seconds { }; +/** Minutes unit. */ struct Minutes { }; +/** Hours unit. */ struct Hours { }; +/** Days unit. */ struct Days { }; /** @} */ }; +/** Angle units. */ struct angle { /** * @defgroup cpp_addons_units_angle Angle @@ -111,13 +168,16 @@ struct angle { * @{ */ +/** Radians unit. */ struct Radians { }; +/** Degrees unit. */ struct Degrees { }; /** @} */ }; +/** Time units. */ struct time { /** * @defgroup cpp_addons_units_time Time @@ -125,12 +185,14 @@ struct time { * @{ */ +/** Date unit. */ struct Date { }; /** @} */ }; +/** Mass units. */ struct mass { /** * @defgroup cpp_addons_units_mass Mass @@ -138,13 +200,16 @@ struct mass { * @{ */ +/** Grams unit. */ struct Grams { }; +/** KiloGrams unit. */ struct KiloGrams { }; /** @} */ }; +/** Electric current units. */ struct electric_current { /** * @defgroup cpp_addons_units_electric_current Electric Current @@ -152,12 +217,14 @@ struct electric_current { * @{ */ +/** Ampere unit. */ struct Ampere { }; /** @} */ }; +/** Amount units. */ struct amount { /** * @defgroup cpp_addons_units_amount Amount @@ -165,12 +232,14 @@ struct amount { * @{ */ +/** Mole unit. */ struct Mole { }; /** @} */ }; +/** Luminous intensity units. */ struct luminous_intensity { /** * @defgroup cpp_addons_units_luminous_intensity Luminous Intensity @@ -178,12 +247,14 @@ struct luminous_intensity { * @{ */ +/** Candela unit. */ struct Candela { }; /** @} */ }; +/** Force units. */ struct force { /** * @defgroup cpp_addons_units_force Force @@ -191,12 +262,14 @@ struct force { * @{ */ +/** Newton unit. */ struct Newton { }; /** @} */ }; +/** Length units. */ struct length { /** * @defgroup cpp_addons_units_length Length @@ -204,20 +277,30 @@ struct length { * @{ */ +/** Meters unit. */ struct Meters { }; +/** PicoMeters unit. */ struct PicoMeters { }; +/** NanoMeters unit. */ struct NanoMeters { }; +/** MicroMeters unit. */ struct MicroMeters { }; +/** MilliMeters unit. */ struct MilliMeters { }; +/** CentiMeters unit. */ struct CentiMeters { }; +/** KiloMeters unit. */ struct KiloMeters { }; +/** Miles unit. */ struct Miles { }; +/** Pixels unit. */ struct Pixels { }; /** @} */ }; +/** Pressure units. */ struct pressure { /** * @defgroup cpp_addons_units_pressure Pressure @@ -225,13 +308,16 @@ struct pressure { * @{ */ +/** Pascal unit. */ struct Pascal { }; +/** Bar unit. */ struct Bar { }; /** @} */ }; +/** Speed units. */ struct speed { /** * @defgroup cpp_addons_units_speed Speed @@ -239,15 +325,20 @@ struct speed { * @{ */ +/** MetersPerSecond unit. */ struct MetersPerSecond { }; +/** KiloMetersPerSecond unit. */ struct KiloMetersPerSecond { }; +/** KiloMetersPerHour unit. */ struct KiloMetersPerHour { }; +/** MilesPerHour unit. */ struct MilesPerHour { }; /** @} */ }; +/** Temperature units. */ struct temperature { /** * @defgroup cpp_addons_units_temperature Temperature @@ -255,14 +346,18 @@ struct temperature { * @{ */ +/** Kelvin unit. */ struct Kelvin { }; +/** Celsius unit. */ struct Celsius { }; +/** Fahrenheit unit. */ struct Fahrenheit { }; /** @} */ }; +/** Data units. */ struct data { /** * @defgroup cpp_addons_units_data Data @@ -270,21 +365,33 @@ struct data { * @{ */ +/** Bits unit. */ struct Bits { }; +/** KiloBits unit. */ struct KiloBits { }; +/** MegaBits unit. */ struct MegaBits { }; +/** GigaBits unit. */ struct GigaBits { }; +/** Bytes unit. */ struct Bytes { }; +/** KiloBytes unit. */ struct KiloBytes { }; +/** MegaBytes unit. */ struct MegaBytes { }; +/** GigaBytes unit. */ struct GigaBytes { }; +/** KibiBytes unit. */ struct KibiBytes { }; +/** MebiBytes unit. */ struct MebiBytes { }; +/** GibiBytes unit. */ struct GibiBytes { }; /** @} */ }; +/** Data rate units. */ struct datarate { /** * @defgroup cpp_addons_units_datarate Data Rate @@ -292,19 +399,28 @@ struct datarate { * @{ */ +/** BitsPerSecond unit. */ struct BitsPerSecond { }; +/** KiloBitsPerSecond unit. */ struct KiloBitsPerSecond { }; +/** MegaBitsPerSecond unit. */ struct MegaBitsPerSecond { }; +/** GigaBitsPerSecond unit. */ struct GigaBitsPerSecond { }; +/** BytesPerSecond unit. */ struct BytesPerSecond { }; +/** KiloBytesPerSecond unit. */ struct KiloBytesPerSecond { }; +/** MegaBytesPerSecond unit. */ struct MegaBytesPerSecond { }; +/** GigaBytesPerSecond unit. */ struct GigaBytesPerSecond { }; /** @} */ }; +/** Frequency units. */ struct frequency { /** * @defgroup cpp_addons_units_frequency Frequency @@ -312,15 +428,20 @@ struct frequency { * @{ */ +/** Hertz unit. */ struct Hertz { }; +/** KiloHertz unit. */ struct KiloHertz { }; +/** MegaHertz unit. */ struct MegaHertz { }; +/** GigaHertz unit. */ struct GigaHertz { }; /** @} */ }; +/** URI units. */ struct uri { /** * @defgroup cpp_addons_units_uri Uri @@ -328,14 +449,18 @@ struct uri { * @{ */ +/** Hyperlink unit. */ struct Hyperlink { }; +/** Image unit. */ struct Image { }; +/** File unit. */ struct File { }; /** @} */ }; +/** Color units. */ struct color { /** * @defgroup cpp_addons_units_color Color @@ -343,17 +468,24 @@ struct color { * @{ */ +/** RGB color unit. */ struct Rgb { }; +/** HSL color unit. */ struct Hsl { }; +/** CSS color unit. */ struct Css { }; /** @} */ }; +/** Percentage unit. */ struct Percentage { }; +/** Bel unit. */ struct Bel { }; +/** DeciBel unit. */ struct DeciBel { }; +/** Construct the units module. */ units(flecs::world& world); /** @} */ diff --git a/include/flecs/addons/cpp/mixins/units/impl.hpp b/include/flecs/addons/cpp/mixins/units/impl.hpp index 596e8b781f..ab06f3a137 100644 --- a/include/flecs/addons/cpp/mixins/units/impl.hpp +++ b/include/flecs/addons/cpp/mixins/units/impl.hpp @@ -8,16 +8,16 @@ 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"); @@ -47,7 +47,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

::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; @@ -116,33 +133,38 @@ 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 = is_same_v>; }; +/** Convenience variable template to check if a type is its own actual type. */ template inline constexpr bool is_actual_v = is_actual::value; -} // flecs +/** @} */ + +} // namespace flecs diff --git a/include/flecs/addons/cpp/ref.hpp b/include/flecs/addons/cpp/ref.hpp index 18d7ea2566..02ee2cb7cf 100644 --- a/include/flecs/addons/cpp/ref.hpp +++ b/include/flecs/addons/cpp/ref.hpp @@ -1,6 +1,6 @@ /** * @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 @@ -21,14 +21,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; @@ -41,34 +48,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; @@ -87,14 +106,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()); @@ -104,10 +136,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()); } diff --git a/include/flecs/addons/cpp/table.hpp b/include/flecs/addons/cpp/table.hpp index 1cbba6cc13..205a1feeb2 100644 --- a/include/flecs/addons/cpp/table.hpp +++ b/include/flecs/addons/cpp/table.hpp @@ -15,151 +15,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 The index of the id in the table type, -1 if not found. + * @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 The index of the id in the table type, -1 if not found. + /** 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 The index of the id in the table type, -1 if not found. + /** 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 The index of the id in the table type, -1 if not found. + /** 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 The column index of the id in the table type, -1 if not found. + * @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 The column index of the id in the table type, -1 if not found. + /** 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 The column index of the id in the table type, -1 if not found. + /** 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 The column index of the id in the table type, -1 if not found. + /** 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. @@ -169,20 +187,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 @@ -190,10 +208,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 @@ -201,7 +219,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. @@ -213,9 +231,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 { @@ -226,7 +244,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. @@ -236,7 +254,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. @@ -246,7 +264,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. @@ -257,7 +275,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. @@ -271,9 +289,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 { @@ -282,12 +300,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. @@ -297,7 +315,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. @@ -307,7 +325,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. @@ -318,7 +336,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. @@ -330,7 +348,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. @@ -342,12 +360,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. @@ -356,7 +378,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. @@ -366,32 +388,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. */ @@ -399,7 +431,7 @@ struct table { return table_; } - /* Implicit conversion to table_t */ + /** Implicit conversion to table_t*. */ operator table_t*() const { return table_; } @@ -409,26 +441,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. diff --git a/include/flecs/addons/cpp/type.hpp b/include/flecs/addons/cpp/type.hpp index ceef4aa14e..029d3ba467 100644 --- a/include/flecs/addons/cpp/type.hpp +++ b/include/flecs/addons/cpp/type.hpp @@ -1,6 +1,6 @@ /** * @file addons/cpp/type.hpp - * @brief Utility functions for id vector. + * @brief Utility functions for ID vector. */ #pragma once @@ -16,21 +16,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; @@ -38,7 +50,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; @@ -46,7 +61,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); @@ -56,6 +75,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; @@ -64,6 +84,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]; @@ -72,7 +93,7 @@ struct type { } } - /** Implicit conversion to type_t */ + /** Implicit conversion to type_t. */ operator const type_t*() const { return type_; } @@ -82,6 +103,6 @@ struct type { flecs::id_t empty_; }; -/** #} */ +/** @} */ } diff --git a/include/flecs/addons/cpp/utils/array.hpp b/include/flecs/addons/cpp/utils/array.hpp index b90579788d..8a86b10f21 100644 --- a/include/flecs/addons/cpp/utils/array.hpp +++ b/include/flecs/addons/cpp/utils/array.hpp @@ -1,31 +1,36 @@ /** * @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_; @@ -37,13 +42,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) { @@ -51,30 +60,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) { @@ -86,24 +102,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; } diff --git a/include/flecs/addons/cpp/utils/builder.hpp b/include/flecs/addons/cpp/utils/builder.hpp index c45d227240..84825f2b65 100644 --- a/include/flecs/addons/cpp/utils/builder.hpp +++ b/include/flecs/addons/cpp/utils/builder.hpp @@ -10,7 +10,7 @@ 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 diff --git a/include/flecs/addons/cpp/utils/enum.hpp b/include/flecs/addons/cpp/utils/enum.hpp index 1e14a81a49..38a0df6c7d 100644 --- a/include/flecs/addons/cpp/utils/enum.hpp +++ b/include/flecs/addons/cpp/utils/enum.hpp @@ -1,24 +1,24 @@ /** * @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) @@ -42,8 +42,9 @@ 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); @@ -53,19 +54,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<>\ @@ -82,7 +91,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 @@ -98,7 +107,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 @@ -110,16 +119,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 @@ -136,7 +147,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) @@ -166,8 +177,8 @@ constexpr size_t enum_template_arg_separator( func_name, pos + 1, end, depth); } -/* Use different trick on MSVC, since it uses hexadecimal representation for - * invalid enum constants. We can leverage that msvc inserts a C-style cast +/* 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 @@ -184,18 +195,19 @@ constexpr bool enum_constant_is_valid() { } #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( @@ -207,12 +219,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. */ @@ -221,19 +233,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 @@ -242,7 +254,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...), @@ -251,24 +263,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 @@ -279,15 +291,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> @@ -295,23 +307,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: @@ -319,7 +337,7 @@ 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 @@ -333,23 +351,23 @@ struct enum_type { }; /** - * @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 static U handle_constant(U last_value, This& me) { if constexpr (enum_constant_is_valid_wrap()) { - // Constant is valid, so fill reflection data. + // 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 + // 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; @@ -361,32 +379,33 @@ struct enum_type { me.has_contiguous = false; } - ecs_assert(!(last_value > 0 && - v < std::numeric_limits::min() + last_value), + ecs_assert(!(last_value > 0 && + v < std::numeric_limits::min() + last_value), ECS_UNSUPPORTED, - "Signed integer enums causes integer overflow when recording " + "Signed integer enums cause integer overflow when recording " "offset from high positive to low negative. Consider using " - "unsigned integers as underlying type."); + "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 = + me.constants[me.max].index = flecs_component_ids_index_get(); } return v; } else { - // Search for constant failed. Pass last valid value through. + // 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; @@ -398,11 +417,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) { @@ -411,6 +432,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") @@ -422,30 +444,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; @@ -453,10 +475,11 @@ 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 }; +/** @private Initialize enum reflection for a world. */ template inline static void init_enum(flecs::world_t *world, flecs::entity_t id) { (void)world; (void)id; @@ -467,18 +490,19 @@ inline static void init_enum(flecs::world_t *world, flecs::entity_t id) { } // 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. @@ -492,8 +516,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. @@ -503,9 +527,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 { @@ -513,7 +537,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); } @@ -528,8 +552,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. */ @@ -537,27 +561,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) { @@ -581,10 +611,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); } diff --git a/include/flecs/addons/cpp/utils/function_traits.hpp b/include/flecs/addons/cpp/utils/function_traits.hpp index a789d942b1..72864e57e8 100644 --- a/include/flecs/addons/cpp/utils/function_traits.hpp +++ b/include/flecs/addons/cpp/utils/function_traits.hpp @@ -1,6 +1,6 @@ /** * @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 */ @@ -10,10 +10,11 @@ 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 { @@ -23,129 +24,148 @@ 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 diff --git a/include/flecs/addons/cpp/utils/iterable.hpp b/include/flecs/addons/cpp/utils/iterable.hpp index 0fd4950140..b7304c8a75 100644 --- a/include/flecs/addons/cpp/utils/iterable.hpp +++ b/include/flecs/addons/cpp/utils/iterable.hpp @@ -5,15 +5,19 @@ 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 { @@ -21,8 +25,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 { @@ -33,10 +39,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 { @@ -44,6 +52,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); @@ -61,24 +75,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. @@ -88,59 +102,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; @@ -151,10 +171,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(); @@ -163,12 +185,14 @@ 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, "%s", name); @@ -176,6 +200,7 @@ struct iter_iterable final : iterable { 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, "%s", name); @@ -183,6 +208,7 @@ struct iter_iterable final : iterable { 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, "%s", name); @@ -190,6 +216,7 @@ struct iter_iterable final : iterable { 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(); @@ -202,7 +229,7 @@ struct iter_iterable final : iterable { # include "../mixins/json/iterable.inl" # 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_)) { @@ -211,7 +238,7 @@ struct iter_iterable final : iterable { 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) { @@ -220,7 +247,7 @@ struct iter_iterable final : iterable { return result; } - // Return first matching entity. + /** Return the first matching entity. */ flecs::entity first() { flecs::entity result; if (next_each_(&it_) && it_.count) { @@ -230,13 +257,13 @@ struct iter_iterable final : iterable { 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)); @@ -281,10 +308,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) { @@ -308,24 +337,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 { @@ -334,14 +365,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); } diff --git a/include/flecs/addons/cpp/utils/node_builder.hpp b/include/flecs/addons/cpp/utils/node_builder.hpp index a36540f28c..d44f64266a 100644 --- a/include/flecs/addons/cpp/utils/node_builder.hpp +++ b/include/flecs/addons/cpp/utils/node_builder.hpp @@ -1,6 +1,6 @@ /** * @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 @@ -8,7 +8,7 @@ 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 diff --git a/include/flecs/addons/cpp/utils/signature.hpp b/include/flecs/addons/cpp/utils/signature.hpp index fa6d54c650..899a162a6f 100644 --- a/include/flecs/addons/cpp/utils/signature.hpp +++ b/include/flecs/addons/cpp/utils/signature.hpp @@ -1,6 +1,6 @@ /** * @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 diff --git a/include/flecs/addons/cpp/utils/string.hpp b/include/flecs/addons/cpp/utils/string.hpp index 41c8a5d9ea..30b333ebef 100644 --- a/include/flecs/addons/cpp/utils/string.hpp +++ b/include/flecs/addons/cpp/utils/string.hpp @@ -7,20 +7,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 @@ -31,6 +36,7 @@ struct string { } } + /** Move constructor. */ string(string&& str) noexcept { ecs_os_free(str_); str_ = str.str_; @@ -39,10 +45,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_; @@ -52,10 +60,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; @@ -72,10 +82,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; @@ -88,33 +100,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; @@ -124,11 +143,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 : "") @@ -139,11 +160,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) { } }; diff --git a/include/flecs/addons/cpp/utils/stringstream.hpp b/include/flecs/addons/cpp/utils/stringstream.hpp index 964d516989..f647719d62 100644 --- a/include/flecs/addons/cpp/utils/stringstream.hpp +++ b/include/flecs/addons/cpp/utils/stringstream.hpp @@ -1,24 +1,29 @@ /** * @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_; @@ -26,15 +31,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_)); } diff --git a/include/flecs/addons/cpp/utils/utils.hpp b/include/flecs/addons/cpp/utils/utils.hpp index 969052b4d2..6b4d006a27 100644 --- a/include/flecs/addons/cpp/utils/utils.hpp +++ b/include/flecs/addons/cpp/utils/utils.hpp @@ -1,20 +1,19 @@ /** * @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) @@ -26,7 +25,7 @@ } \ } 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/ */ @@ -36,20 +35,23 @@ #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); } } @@ -57,7 +59,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 @@ -68,14 +70,18 @@ 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; }; @@ -125,46 +131,50 @@ 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 +/** 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; @@ -183,14 +193,7 @@ struct always_false { 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. -// - +/** @private Extract the type name from a type using compiler intrinsics. */ #if defined(__GNUC__) || defined(_WIN32) template inline const char* type_name() { diff --git a/include/flecs/addons/cpp/world.hpp b/include/flecs/addons/cpp/world.hpp index 24418da841..7e4a8fccd9 100644 --- a/include/flecs/addons/cpp/world.hpp +++ b/include/flecs/addons/cpp/world.hpp @@ -8,9 +8,16 @@ 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, @@ -34,7 +41,14 @@ inline void set(world_t *world, flecs::entity_t entity, T&& value, flecs::id_t i } } -// 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, @@ -54,21 +68,43 @@ inline void set(world_t *world, flecs::entity_t entity, const T& value, flecs::i } } -// 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, @@ -93,7 +129,15 @@ inline void assign(world_t *world, flecs::entity_t entity, T&& value, flecs::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, @@ -114,14 +158,28 @@ inline void assign(world_t *world, flecs::entity_t entity, const T& value, flecs } } -// 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); @@ -129,7 +187,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> @@ -143,7 +209,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() */ @@ -151,7 +220,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); @@ -172,15 +244,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[]) @@ -188,7 +260,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 ) { @@ -197,13 +269,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_; @@ -211,11 +284,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_; @@ -223,17 +298,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_); } @@ -242,15 +318,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, @@ -260,9 +337,9 @@ 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_); @@ -270,7 +347,7 @@ struct world { init_builtin_components(); } - /** Obtain pointer to C world object. + /** Obtain a pointer to the C world object. */ world_t* c_ptr() const { return world_; @@ -308,7 +385,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. @@ -324,7 +401,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() @@ -335,7 +412,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. * @@ -358,10 +435,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. * @@ -380,7 +457,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. * @@ -414,7 +491,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() @@ -447,8 +524,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. * @@ -459,17 +536,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. * @@ -507,7 +584,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. @@ -516,14 +593,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 @@ -533,7 +610,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); } @@ -544,7 +621,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); } @@ -567,10 +644,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() */ @@ -581,7 +657,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() @@ -594,9 +670,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() @@ -619,7 +695,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. @@ -631,10 +707,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() */ @@ -659,7 +735,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() @@ -675,7 +751,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() @@ -695,8 +771,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; @@ -887,8 +965,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 @@ -896,7 +974,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. */ @@ -905,14 +983,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. @@ -925,31 +1003,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. */ @@ -961,30 +1039,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 @@ -1006,6 +1084,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; @@ -1015,8 +1094,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; @@ -1028,26 +1109,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. @@ -1056,7 +1138,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); @@ -1066,6 +1149,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)); @@ -1074,6 +1158,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 { @@ -1084,6 +1169,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 { @@ -1094,6 +1180,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 { @@ -1102,7 +1189,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 { @@ -1111,36 +1198,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 { @@ -1157,8 +1244,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; @@ -1227,7 +1314,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() */ @@ -1244,7 +1331,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 { @@ -1257,14 +1344,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() @@ -1274,7 +1361,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() @@ -1284,7 +1371,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() @@ -1295,8 +1382,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() */ @@ -1307,7 +1394,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() */ @@ -1315,7 +1402,7 @@ struct world { ecs_set_version(world_, e); } - /** Get version of provided entity. + /** Get the version of the provided entity. * * @see ecs_get_version() */ @@ -1323,7 +1410,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); } @@ -1332,11 +1419,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; } @@ -1344,13 +1431,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() */ @@ -1358,8 +1445,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() */ @@ -1367,11 +1454,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() { @@ -1383,29 +1470,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_)); @@ -1452,15 +1539,21 @@ struct world { # 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) @@ -1468,17 +1561,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. */ }; /** @} */ diff --git a/include/flecs/addons/doc.h b/include/flecs/addons/doc.h index 9bacf3bf1d..dd2cc928ed 100644 --- a/include/flecs/addons/doc.h +++ b/include/flecs/addons/doc.h @@ -24,12 +24,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(). @@ -51,8 +51,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; @@ -65,7 +65,7 @@ FLECS_API extern const ecs_entity_t EcsDocColor; * - EcsDocColor */ typedef struct EcsDocDescription { - char *value; + char *value; /**< Description value. */ } EcsDocDescription; /** Add UUID to entity. @@ -86,7 +86,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. @@ -152,10 +152,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() @@ -182,11 +182,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); diff --git a/include/flecs/addons/flecs_c.h b/include/flecs/addons/flecs_c.h index f6ac277058..073423b99d 100644 --- a/include/flecs/addons/flecs_c.h +++ b/include/flecs/addons/flecs_c.h @@ -9,26 +9,26 @@ /** * @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: * @@ -49,7 +49,7 @@ (void)id_; \ (void)ecs_id(id_) -/** Declare & define an entity. +/** Declare and define an entity. * * Example: * @@ -65,7 +65,7 @@ /** Forward declare a tag. */ #define ECS_TAG_DECLARE ECS_DECLARE -/** Define a forward declared tag. +/** Define a forward-declared tag. * * Example: * @@ -75,7 +75,7 @@ */ #define ECS_TAG_DEFINE(world, id) ECS_ENTITY_DEFINE(world, id, 0) -/** Declare & define a tag. +/** Declare and define a tag. * * Example: * @@ -88,7 +88,7 @@ /** Forward declare a prefab. */ #define ECS_PREFAB_DECLARE ECS_DECLARE -/** Define a forward declared prefab. +/** Define a forward-declared prefab. * * Example: * @@ -98,7 +98,7 @@ */ #define ECS_PREFAB_DEFINE(world, id, ...) ECS_ENTITY_DEFINE(world, id, Prefab, __VA_ARGS__) -/** Declare & define a prefab. +/** Declare and define a prefab. * * Example: * @@ -111,7 +111,7 @@ /** 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: * @@ -134,7 +134,7 @@ }\ 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: * @@ -147,10 +147,10 @@ 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: * @@ -172,7 +172,7 @@ 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: * @@ -187,10 +187,10 @@ (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: * @@ -209,7 +209,7 @@ ecs_assert(name_ != NULL, ECS_INVALID_PARAMETER, "failed to create query %s", #name_);\ } -/** Declare & define a query. +/** Declare and define a query. * * Example: * @@ -249,10 +249,10 @@ #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) }} @@ -280,8 +280,8 @@ /** @} */ /** - * @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. * * @{ */ @@ -296,11 +296,14 @@ * @{ */ +/** 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) @@ -311,23 +314,27 @@ * @{ */ +/** 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)) @@ -338,120 +345,134 @@ * @{ */ -/* 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)))) @@ -462,30 +483,39 @@ * @{ */ +/** 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) @@ -496,28 +526,36 @@ * @{ */ +/** 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)) @@ -528,15 +566,19 @@ * @{ */ +/** 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)) @@ -547,24 +589,31 @@ * @{ */ +/** 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) @@ -577,9 +626,11 @@ * @{ */ +/** 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)); @@ -623,36 +674,45 @@ #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)) @@ -663,12 +723,15 @@ * @{ */ +/** 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))) @@ -679,12 +742,15 @@ * @{ */ +/** 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))) @@ -695,25 +761,25 @@ * @{ */ -/** 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 */ +/** 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 */ +/** 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__}) /** @} */ @@ -722,17 +788,19 @@ /** * @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, @@ -812,9 +880,9 @@ 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: * @@ -826,7 +894,7 @@ #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 @@ -845,18 +913,25 @@ /** * @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)) /** @} */ diff --git a/include/flecs/addons/flecs_cpp.h b/include/flecs/addons/flecs_cpp.h index a641ab87e6..293ae650f9 100644 --- a/include/flecs/addons/flecs_cpp.h +++ b/include/flecs/addons/flecs_cpp.h @@ -1,6 +1,6 @@ /** * @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 @@ -40,22 +40,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, function allocates a buffer with ecs_os_malloc. - * Callers must free the returned pointer with ecs_os_free. */ + /* 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, function derives it from 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, @@ -63,6 +86,12 @@ 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, @@ -86,17 +115,39 @@ typedef struct ecs_cpp_component_desc_t { 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, 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, @@ -107,13 +158,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 { - ecs_world_t *world; - ecs_stage_t *stage; - 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, @@ -122,6 +183,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, @@ -130,6 +200,15 @@ 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, @@ -139,9 +218,15 @@ FLECS_ALWAYS_INLINE ecs_entity_t ecs_cpp_new( 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 ecs_member_t* ecs_cpp_last_member( - const ecs_world_t *world, + const ecs_world_t *world, ecs_entity_t type); #endif diff --git a/include/flecs/addons/http.h b/include/flecs/addons/http.h index 2d05d54a5e..ab27a4b3b8 100644 --- a/include/flecs/addons/http.h +++ b/include/flecs/addons/http.h @@ -4,12 +4,12 @@ * * 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. @@ -22,7 +22,7 @@ /** * @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. * * @{ */ @@ -34,10 +34,10 @@ #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 @@ -49,17 +49,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. */ @@ -74,32 +74,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. */ @@ -121,16 +122,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. @@ -140,7 +141,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. @@ -149,8 +150,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. @@ -164,14 +165,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. */ @@ -187,7 +189,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( @@ -196,7 +199,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, @@ -205,15 +216,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 @@ -221,7 +236,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. diff --git a/include/flecs/addons/json.h b/include/flecs/addons/json.h index ab20a1348d..0456956484 100644 --- a/include/flecs/addons/json.h +++ b/include/flecs/addons/json.h @@ -3,7 +3,7 @@ * @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. */ @@ -19,7 +19,7 @@ #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 @@ -28,7 +28,7 @@ /** * @defgroup c_addons_json Json * @ingroup c_addons - * Functions for serializing to/from JSON. + * Functions for serializing to and from JSON. * * @{ */ @@ -39,16 +39,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. */ @@ -63,7 +63,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 @@ -74,14 +74,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 @@ -92,7 +92,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). @@ -105,7 +105,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. @@ -123,7 +123,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. @@ -188,7 +188,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. @@ -216,19 +216,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; @@ -272,6 +272,7 @@ 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 @@ -286,6 +287,7 @@ 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 @@ -297,26 +299,26 @@ int ecs_entity_to_json_buf( /** 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 */ - bool serialize_parents_before_children; /** If query matches both children and parent, serialize parent before children */ + 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 for if the component should be serialized */ + /** 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]). */ @@ -376,6 +378,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 @@ -388,6 +391,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 @@ -396,27 +400,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 @@ -429,6 +434,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 diff --git a/include/flecs/addons/log.h b/include/flecs/addons/log.h index 9db6cb2ff7..dcfd08f08f 100644 --- a/include/flecs/addons/log.h +++ b/include/flecs/addons/log.h @@ -6,21 +6,21 @@ * 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. */ @@ -46,7 +46,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, @@ -85,7 +90,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); @@ -112,9 +121,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, @@ -123,6 +139,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, @@ -131,6 +155,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, @@ -139,6 +170,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, @@ -147,6 +186,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, @@ -155,6 +201,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, @@ -164,6 +218,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, @@ -172,6 +233,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, @@ -180,6 +249,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, @@ -188,6 +264,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, @@ -203,37 +287,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 @@ -254,20 +346,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 @@ -347,21 +451,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 @@ -374,7 +479,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 @@ -382,7 +487,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 @@ -390,14 +495,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 @@ -420,7 +525,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 @@ -435,29 +540,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 @@ -479,13 +586,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. @@ -495,7 +602,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. @@ -506,7 +613,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 @@ -530,9 +637,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); @@ -540,40 +655,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) @@ -581,16 +728,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 diff --git a/include/flecs/addons/meta.h b/include/flecs/addons/meta.h index 980490e6d3..dd6f60eed6 100644 --- a/include/flecs/addons/meta.h +++ b/include/flecs/addons/meta.h @@ -6,10 +6,10 @@ * 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 @@ -20,9 +20,9 @@ * 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 @@ -33,7 +33,7 @@ * 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: * @@ -75,11 +75,11 @@ 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}); @@ -92,62 +92,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, @@ -162,11 +162,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, @@ -189,12 +189,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. */ @@ -203,22 +203,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. */ @@ -231,8 +231,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 @@ -249,81 +249,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; @@ -331,18 +331,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. */ @@ -352,7 +352,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_)( @@ -385,30 +385,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 @@ -416,71 +417,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); @@ -490,30 +491,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; @@ -521,7 +522,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 { @@ -535,13 +536,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, @@ -569,23 +570,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; @@ -593,53 +594,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. @@ -691,7 +697,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. @@ -716,7 +722,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. @@ -728,7 +734,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. @@ -746,7 +752,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. @@ -792,7 +798,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. @@ -883,7 +889,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. @@ -982,7 +988,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. @@ -996,19 +1002,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 @@ -1040,7 +1046,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. @@ -1178,8 +1184,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 @@ -1207,16 +1213,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). */ @@ -1227,7 +1233,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; @@ -1248,7 +1254,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). */ diff --git a/include/flecs/addons/meta_c.h b/include/flecs/addons/meta_c.h index 8dee8e7e4d..842b3f5b29 100644 --- a/include/flecs/addons/meta_c.h +++ b/include/flecs/addons/meta_c.h @@ -24,11 +24,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 */ @@ -144,7 +144,7 @@ int ecs_meta_from_desc( } #endif -#endif // FLECS_META_H +#endif // FLECS_META_C_H /** @} */ diff --git a/include/flecs/addons/metrics.h b/include/flecs/addons/metrics.h index e943cd80ed..d94333bbb0 100644 --- a/include/flecs/addons/metrics.h +++ b/include/flecs/addons/metrics.h @@ -38,19 +38,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. */ @@ -72,36 +72,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; @@ -122,12 +122,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 @@ -137,8 +137,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. diff --git a/include/flecs/addons/module.h b/include/flecs/addons/module.h index c04971ee50..cc99a651d9 100644 --- a/include/flecs/addons/module.h +++ b/include/flecs/addons/module.h @@ -4,7 +4,7 @@ * * 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 @@ -12,7 +12,7 @@ /** * @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. * * @{ */ @@ -25,16 +25,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. * @@ -73,13 +72,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( @@ -87,7 +87,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, diff --git a/include/flecs/addons/os_api_impl.h b/include/flecs/addons/os_api_impl.h index 4dff1e4e88..8eaa7fe719 100644 --- a/include/flecs/addons/os_api_impl.h +++ b/include/flecs/addons/os_api_impl.h @@ -20,6 +20,10 @@ 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); diff --git a/include/flecs/addons/pipeline.h b/include/flecs/addons/pipeline.h index 02106b7dca..2b996216d6 100644 --- a/include/flecs/addons/pipeline.h +++ b/include/flecs/addons/pipeline.h @@ -4,12 +4,12 @@ * * 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. */ @@ -44,7 +44,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); @@ -86,7 +86,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. @@ -98,20 +98,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; @@ -157,7 +157,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. * @@ -195,12 +195,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. @@ -218,11 +218,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. @@ -236,28 +236,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( diff --git a/include/flecs/addons/rest.h b/include/flecs/addons/rest.h index b14b6337f3..69e1ff086a 100644 --- a/include/flecs/addons/rest.h +++ b/include/flecs/addons/rest.h @@ -5,7 +5,7 @@ * 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 @@ -40,6 +40,7 @@ extern "C" { #endif +/** Default port for the REST API server. */ #define ECS_REST_DEFAULT_PORT (27750) /** Component that instantiates the REST API. */ @@ -47,18 +48,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. @@ -74,14 +75,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) diff --git a/include/flecs/addons/script.h b/include/flecs/addons/script.h index 65f643d5ec..c30c3f2547 100644 --- a/include/flecs/addons/script.h +++ b/include/flecs/addons/script.h @@ -2,7 +2,7 @@ * @file addons/script.h * @brief Flecs script module. * - * For script, see examples/script. + * For script examples, see examples/script. */ #ifdef FLECS_SCRIPT @@ -10,7 +10,7 @@ /** * @defgroup c_addons_script Flecs script * @ingroup c_addons - * DSL for loading scenes, assets and configuration. + * DSL for loading scenes, assets, and configuration. * * @{ */ @@ -62,53 +62,53 @@ 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. */ @@ -128,8 +128,8 @@ typedef void(*ecs_vector_function_callback_t)( /** 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. @@ -160,17 +160,17 @@ typedef struct ecs_script_function_t EcsScriptFunction; */ 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. @@ -186,7 +186,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. @@ -213,6 +213,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 @@ -247,6 +248,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 @@ -272,7 +274,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. * @@ -298,9 +300,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 @@ -312,8 +315,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 @@ -326,9 +330,9 @@ char* ecs_script_ast_to_str( /** 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. @@ -340,6 +344,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( @@ -353,8 +358,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( @@ -387,12 +393,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( @@ -508,7 +515,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. */ @@ -529,13 +536,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. * @@ -572,17 +579,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 @@ -591,12 +598,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. @@ -609,7 +616,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. */ @@ -666,6 +673,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( @@ -676,18 +684,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; @@ -707,12 +715,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( @@ -721,12 +730,13 @@ ecs_value_t ecs_const_var_get( /* Functions */ +/** Vector function callbacks for different element types. */ typedef struct ecs_vector_fn_callbacks_t { - ecs_vector_function_callback_t i8; - ecs_vector_function_callback_t i32; + 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 */ +/** Used with ecs_function_init() and ecs_method_init(). */ typedef struct ecs_function_desc_t { /** Function name. */ const char *name; @@ -746,12 +756,12 @@ typedef struct ecs_function_desc_t { /** 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. + * 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 members of the same type + * - 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. * @@ -820,9 +830,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( @@ -866,7 +876,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: diff --git a/include/flecs/addons/script_math.h b/include/flecs/addons/script_math.h index f2e525f388..e70e9b7f35 100644 --- a/include/flecs/addons/script_math.h +++ b/include/flecs/addons/script_math.h @@ -1,6 +1,6 @@ /** * @file addons/script_math.h - * @brief Math functions for flecs script. + * @brief Math functions for Flecs script. */ #ifdef FLECS_SCRIPT_MATH @@ -12,7 +12,7 @@ /** * @defgroup c_addons_script_math Script Math * @ingroup c_addons - * Math functions for flecs script. + * Math functions for Flecs script. * @{ */ @@ -26,10 +26,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. diff --git a/include/flecs/addons/stats.h b/include/flecs/addons/stats.h index 8d459a2cc5..c5a4cf0737 100644 --- a/include/flecs/addons/stats.h +++ b/include/flecs/addons/stats.h @@ -2,14 +2,14 @@ * @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 @@ -17,7 +17,7 @@ /** * @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. * * @{ */ @@ -37,188 +37,189 @@ 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. @@ -255,6 +256,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, @@ -311,7 +317,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, @@ -357,7 +363,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, @@ -395,14 +401,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, @@ -410,21 +416,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. */ @@ -432,190 +438,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_children_table_map; /** Bytes used by map for non-fragmenting ChildOf table lookups. */ - 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, 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. */ + 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_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_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. @@ -707,10 +712,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( @@ -726,8 +731,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( diff --git a/include/flecs/addons/system.h b/include/flecs/addons/system.h index 9581b21134..065ac37687 100644 --- a/include/flecs/addons/system.h +++ b/include/flecs/addons/system.h @@ -3,7 +3,7 @@ * @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. */ @@ -12,7 +12,7 @@ /** * @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. * * @{ */ @@ -28,45 +28,45 @@ 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; /** 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 ran for each result returned by the system's query. This + /** 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. */ @@ -84,67 +84,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; - /** Query group to iterate */ + /** Query group to iterate. */ uint64_t group_id; - /** True if a query group is configured */ + /** True if a query group is configured. */ bool group_id_set; - /** Tick source associated with system */ + /** 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. */ @@ -156,21 +161,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. @@ -184,12 +189,12 @@ const ecs_system_t* ecs_system_get( /** 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 + * 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. + * @param group_id The query group ID to iterate. */ FLECS_API void ecs_system_set_group( @@ -202,7 +207,7 @@ void ecs_system_set_group( /** 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: * @@ -224,7 +229,7 @@ void ecs_system_set_group( } \ 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: * @@ -267,7 +272,7 @@ void ecs_system_set_group( * 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. * @@ -278,15 +283,15 @@ void ecs_system_set_group( * 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( @@ -295,15 +300,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( diff --git a/include/flecs/addons/timer.h b/include/flecs/addons/timer.h index 3082360431..4a4034add4 100644 --- a/include/flecs/addons/timer.h +++ b/include/flecs/addons/timer.h @@ -31,22 +31,22 @@ 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; @@ -82,13 +82,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. @@ -126,7 +119,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 @@ -145,7 +138,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. @@ -185,12 +178,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 @@ -204,8 +197,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( @@ -216,8 +209,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 @@ -227,7 +220,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. diff --git a/include/flecs/addons/units.h b/include/flecs/addons/units.h index ab1d47daba..3cda17f341 100644 --- a/include/flecs/addons/units.h +++ b/include/flecs/addons/units.h @@ -2,7 +2,7 @@ * @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: @@ -50,7 +50,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). * * @{ */ @@ -272,7 +272,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 * @{ */ @@ -284,7 +284,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 * @{ */ diff --git a/include/flecs/datastructures/allocator.h b/include/flecs/datastructures/allocator.h index 529e90e389..11acedc099 100644 --- a/include/flecs/datastructures/allocator.h +++ b/include/flecs/datastructures/allocator.h @@ -1,6 +1,6 @@ /** * @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 @@ -8,43 +8,76 @@ #include "../private/api_defines.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, @@ -52,78 +85,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 diff --git a/include/flecs/datastructures/bitset.h b/include/flecs/datastructures/bitset.h index 7e2707daaa..1d46f8ca23 100644 --- a/include/flecs/datastructures/bitset.h +++ b/include/flecs/datastructures/bitset.h @@ -12,59 +12,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, diff --git a/include/flecs/datastructures/block_allocator.h b/include/flecs/datastructures/block_allocator.h index d5f8dd36bd..2ddd7bb002 100644 --- a/include/flecs/datastructures/block_allocator.h +++ b/include/flecs/datastructures/block_allocator.h @@ -8,104 +8,186 @@ #include "../private/api_defines.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 diff --git a/include/flecs/datastructures/hashmap.h b/include/flecs/datastructures/hashmap.h index d95e48bc1f..8180e8a19c 100644 --- a/include/flecs/datastructures/hashmap.h +++ b/include/flecs/datastructures/hashmap.h @@ -12,31 +12,44 @@ 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, @@ -46,13 +59,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, @@ -60,9 +86,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, @@ -70,9 +105,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, @@ -81,9 +125,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, @@ -91,9 +143,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, @@ -102,14 +163,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, @@ -117,15 +192,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, @@ -133,9 +226,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)) diff --git a/include/flecs/datastructures/map.h b/include/flecs/datastructures/map.h index 5609e4f792..d31cc8dfda 100644 --- a/include/flecs/datastructures/map.h +++ b/include/flecs/datastructures/map.h @@ -12,169 +12,272 @@ 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 diff --git a/include/flecs/datastructures/sparse.h b/include/flecs/datastructures/sparse.h index a929c899ba..20369a0662 100644 --- a/include/flecs/datastructures/sparse.h +++ b/include/flecs/datastructures/sparse.h @@ -12,36 +12,43 @@ 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, @@ -49,104 +56,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, @@ -154,71 +278,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)) diff --git a/include/flecs/datastructures/stack_allocator.h b/include/flecs/datastructures/stack_allocator.h index 160abd7ec6..36ba187bf2 100644 --- a/include/flecs/datastructures/stack_allocator.h +++ b/include/flecs/datastructures/stack_allocator.h @@ -6,87 +6,138 @@ #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, diff --git a/include/flecs/datastructures/strbuf.h b/include/flecs/datastructures/strbuf.h index a16e73afcc..a2561d7dcf 100644 --- a/include/flecs/datastructures/strbuf.h +++ b/include/flecs/datastructures/strbuf.h @@ -12,6 +12,7 @@ extern "C" { #endif +/** Initializer for ecs_strbuf_t. */ #ifdef __cplusplus /* Fixes missing field initializer warning on g++ */ #define ECS_STRBUF_INIT (ecs_strbuf_t){} @@ -19,158 +20,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)) diff --git a/include/flecs/datastructures/vec.h b/include/flecs/datastructures/vec.h index 13b77da9ef..dfb4ea6505 100644 --- a/include/flecs/datastructures/vec.h +++ b/include/flecs/datastructures/vec.h @@ -14,15 +14,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, @@ -30,6 +37,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, @@ -38,97 +53,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, @@ -136,9 +284,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, @@ -146,9 +308,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, @@ -157,6 +334,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, @@ -164,9 +348,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, @@ -174,9 +372,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, @@ -184,9 +396,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, @@ -195,6 +422,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, @@ -203,6 +438,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, @@ -210,38 +453,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))) diff --git a/include/flecs/os_api.h b/include/flecs/os_api.h index dba1c9fd07..69ae309064 100644 --- a/include/flecs/os_api.h +++ b/include/flecs/os_api.h @@ -3,10 +3,10 @@ * @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. */ @@ -16,7 +16,7 @@ /** * @defgroup c_os_api OS API * @ingroup c - * Interface for providing OS specific functionality. + * Interface for providing OS-specific functionality. * * @{ */ @@ -39,7 +39,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. */ @@ -47,20 +47,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. */ @@ -131,7 +131,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)( @@ -142,7 +142,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)( @@ -163,7 +163,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)( @@ -210,12 +210,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. */ @@ -244,18 +250,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. */ @@ -277,7 +288,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. */ @@ -305,10 +316,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. */ @@ -318,36 +329,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: * @@ -361,31 +370,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. * @@ -454,7 +463,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)) @@ -497,7 +505,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) @@ -542,8 +550,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 @@ -559,7 +567,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) @@ -572,8 +580,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 @@ -584,8 +592,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 @@ -596,8 +604,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 @@ -608,8 +616,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 @@ -620,8 +628,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 @@ -630,7 +638,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. @@ -639,7 +647,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. @@ -659,17 +667,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. */ @@ -677,9 +697,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 @@ -696,10 +716,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 @@ -707,7 +727,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. diff --git a/include/flecs/private/addons.h b/include/flecs/private/addons.h index d284256e97..7440f17b57 100644 --- a/include/flecs/private/addons.h +++ b/include/flecs/private/addons.h @@ -73,10 +73,10 @@ #undef FLECS_JOURNAL #endif -/* Always included, if disabled functions are replaced with dummy macros */ +/* Always included; if disabled, functions are replaced with dummy macros. */ #include "flecs/addons/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 diff --git a/include/flecs/private/api_defines.h b/include/flecs/private/api_defines.h index b49cbaf24f..ef0307cbdb 100644 --- a/include/flecs/private/api_defines.h +++ b/include/flecs/private/api_defines.h @@ -51,8 +51,8 @@ #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 @@ -78,12 +78,12 @@ /* 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" @@ -91,47 +91,47 @@ #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 @@ -145,24 +145,24 @@ #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 @@ -173,10 +173,10 @@ #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. */ #include "../bake_config.h" #ifdef __cplusplus @@ -187,8 +187,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 @@ -208,7 +208,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 @@ -218,30 +218,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)) @@ -252,18 +252,18 @@ typedef struct ecs_allocator_t ecs_allocator_t; #elif defined(ECS_TARGET_MSVC) #define ECS_ALIGNOF(T) (int64_t)__alignof(T) #else -/* Use struct trick since on 32 bit platforms __alignof__ can return different +/* 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 + * __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 + * __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 @@ -294,39 +294,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) @@ -337,7 +337,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) @@ -345,7 +345,7 @@ typedef struct ecs_allocator_t ecs_allocator_t; //////////////////////////////////////////////////////////////////////////////// -//// Entity id macros +//// Entity ID macros //////////////////////////////////////////////////////////////////////////////// #define ECS_ROW_MASK (0x0FFFFFFFu) @@ -374,7 +374,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_ @@ -412,7 +412,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 diff --git a/include/flecs/private/api_flags.h b/include/flecs/private/api_flags.h index 59f47d890b..853129d433 100644 --- a/include/flecs/private/api_flags.h +++ b/include/flecs/private/api_flags.h @@ -46,7 +46,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) @@ -77,14 +77,14 @@ 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\ @@ -95,7 +95,7 @@ extern "C" { #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)]) @@ -103,7 +103,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)]) @@ -123,61 +123,61 @@ 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 EcsIterImmutableCacheData (1u << 21u) /* Internally used by engine to indicate immutable arrays from cache */ +#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) */ +/* 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) @@ -205,39 +205,39 @@ extern "C" { //// 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 << 0u) /* Does table have builtin 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 table have multiple IsA pairs */ -#define EcsTableHasChildOf (1u << 4u) /* Does the table type ChildOf relationship */ -#define EcsTableHasParent (1u << 5u) /* Does the table type 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 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) @@ -262,11 +262,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 } diff --git a/include/flecs/private/api_internals.h b/include/flecs/private/api_internals.h index f34b2020fe..9627b895e6 100644 --- a/include/flecs/private/api_internals.h +++ b/include/flecs/private/api_internals.h @@ -16,44 +16,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/how many non-fragmenting children are stored in table for parent. */ +/* 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 table only contains a single entity for parent, this will contain the entity id (without generation). */ - int32_t count; /* The number of children for a parent in the table. */ + 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: @@ -70,27 +70,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(). * @@ -103,7 +103,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(). * @@ -113,18 +113,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(). * @@ -137,7 +137,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. @@ -146,7 +146,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(). @@ -156,7 +156,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() @@ -172,7 +172,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 @@ -181,11 +181,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 @@ -194,7 +194,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(). * @@ -216,10 +216,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 @@ -227,10 +227,10 @@ FLECS_ALWAYS_INLINE ecs_component_record_t* flecs_components_get( const ecs_world_t *world, ecs_id_t id); -/* Ensure component record for component id - * +/** Ensure a component record for a component ID. + * * @param world The world. - * @param id The component id. + * @param id The component ID. * @return The new or existing component record. */ FLECS_API @@ -238,36 +238,37 @@ FLECS_ALWAYS_INLINE ecs_component_record_t* flecs_components_ensure( ecs_world_t *world, ecs_id_t id); -/** Get component id from component record. - * +/** 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); -/** Get type info for component record. +/** Get the type info for a component record. * * @param cr The component record. - * @return The type info struct, or NULL if component is a tag. + * @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 table record for component record. - * This operation returns the table record for the table/component record if it +/** 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. @@ -279,14 +280,14 @@ FLECS_ALWAYS_INLINE const ecs_table_record_t* flecs_component_get_table( const ecs_component_record_t *cr, const ecs_table_t *table); -/** Ger parent record for component/table. +/** 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. + * 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 + * 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 @@ -302,7 +303,7 @@ FLECS_ALWAYS_INLINE ecs_parent_record_t* flecs_component_get_parent_record( const ecs_component_record_t *cr, const ecs_table_t *table); -/** Return hierarchy depth for component record. +/** 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. @@ -314,7 +315,7 @@ FLECS_API FLECS_ALWAYS_INLINE int32_t flecs_component_get_childof_depth( const ecs_component_record_t *cr); -/** Create component record iterator. +/** Create a component record iterator. * A component record iterator iterates all tables for the specified component * record. * @@ -340,8 +341,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. @@ -356,7 +357,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. @@ -366,7 +367,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. @@ -375,24 +376,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 diff --git a/include/flecs/private/api_support.h b/include/flecs/private/api_support.h index be702d7942..c300dc9c94 100644 --- a/include/flecs/private/api_support.h +++ b/include/flecs/private/api_support.h @@ -17,30 +17,30 @@ 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. @@ -119,7 +119,7 @@ bool flecs_type_info_equals( const void *b, const ecs_type_info_t *type_info); -/** Create allocated string from format. +/** Create an allocated string from a format. * * @param fmt The format string. * @param args Format arguments. @@ -130,7 +130,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. @@ -141,11 +141,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 @@ -157,7 +157,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. */ @@ -166,14 +166,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. */ @@ -184,13 +184,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( @@ -200,14 +200,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. * @@ -220,23 +220,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 { @@ -261,16 +261,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. */ @@ -278,7 +279,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. @@ -287,7 +288,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. @@ -302,7 +303,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. @@ -311,44 +312,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( @@ -357,8 +358,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. @@ -368,7 +369,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. @@ -386,7 +387,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. */ @@ -399,18 +400,18 @@ void flecs_check_exclusive_world_access_read( #define flecs_check_exclusive_world_access_read(world) #endif -/** End deferred mode (executes commands when stage->deref becomes 0). */ +/** 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 current value of operation counter. - * The journaling addon keeps track of an operation counter which is incremented +/** 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. + * This value is not thread-safe. * * @return The operation counter. */ @@ -418,7 +419,7 @@ 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 @@ -429,7 +430,7 @@ int flecs_journal_get_counter(void); #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) \ diff --git a/include/flecs/private/api_types.h b/include/flecs/private/api_types.h index 4c37860f99..272e0433ba 100644 --- a/include/flecs/private/api_types.h +++ b/include/flecs/private/api_types.h @@ -20,20 +20,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; @@ -52,17 +52,17 @@ struct ecs_observable_t { 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, @@ -72,40 +72,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; @@ -117,46 +117,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