MassAPIStructs.h
Source/MassAPI/Public/MassAPIStructs.h
概述 Overview
MassAPI 的核心数据结构头文件。包含三类内容:并行工具 FParallelGatherer<T>(受 UE FMassCommandBuffer per-worker FTaskContext 模式启发的无锁并行收集器)、蓝图可用的实体包装(FEntityHandle 包装 FMassEntityHandle、FEntityTemplateData 包装 FMassEntityTemplateData、FEntityTemplate 供设计器组合模板)、以及运行机制(FEntityFlagFragment 无 Archetype 迁移的 128 位动态旗标、FEntityQuery 惰性缓存的查询结构、FEntityQueryBuilder 流式查询构建器)。
MassAPI's core data-structure header. Three kinds of content: the parallel utility FParallelGatherer<T> (a lock-free parallel gatherer inspired by UE's FMassCommandBuffer per-worker FTaskContext pattern), Blueprint-friendly entity wrappers (FEntityHandle wrapping FMassEntityHandle, FEntityTemplateData wrapping FMassEntityTemplateData, FEntityTemplate for designer-composed templates), and the runtime machinery (FEntityFlagFragment — 128 dynamic flags without archetype migration, FEntityQuery — a lazily-cached query struct, FEntityQueryBuilder — a fluent query builder).
FParallelGatherer<T> template struct
无锁并行收集器,per-worker-slot 缓冲。每个线程经 thread_local 缓存获得私有缓冲区——每线程每 tick 仅在首次访问时执行一次原子操作(FPlatformAtomics::InterlockedIncrement 分配槽位),之后零锁零原子。并行循环结束后调用 Merge() 把全部 worker 缓冲拼接进 Items(槽位分配序;锁步消费端在 Merge 后按稳定键排序,槽容量与分配不影响结果),Reset() 清空为下一帧准备。Generation 在 Reset/Merge 时递增,使各线程的 TLS 缓存失效;TLS 缓存键为全局唯一 InstanceId + 代数(不用 this 指针——新实例落在回收地址会碰撞旧缓存)。并发线程超过 MaxSlots(64)时不崩溃:首次溢出时按本机核数一次性构建溢出表,建成后溢出分配无锁。用法:并行段内 Gatherer.GetThreadBuffer().Add(Item),并行后 Gatherer.Merge() 遍历 Items,最后 Gatherer.Reset()。
Lock-free parallel gatherer with per-worker-slot buffering. Each thread gets a private buffer via thread_local caching — one atomic op (FPlatformAtomics::InterlockedIncrement slot assignment) only on first access per thread per tick, then zero locks, zero atomics. After the parallel loop, Merge() concatenates all worker buffers into Items (slot-allocation order; lockstep consumers sort by stable keys after Merge, so slot capacity and assignment never affect results); Reset() clears for the next frame. Generation increments on Reset/Merge, invalidating the TLS caches; the TLS cache key is the globally unique InstanceId + generation (not the this pointer — a new instance at a recycled address would collide with the old cache). More than MaxSlots (64) concurrent threads no longer crash: the first overflow builds a hardware-sized overflow table once, and overflow claims are lock-free after it exists. Usage: Gatherer.GetThreadBuffer().Add(Item) inside the parallel-for, then Gatherer.Merge(), iterate Items, then Gatherer.Reset().
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
MaxSlots | static constexpr int32 | 64 | 热路径固定槽表容量(内联数组;未用容量零运行成本——分配按实际到达线程数,Merge/Reset 只循环到已用数)。超出不失败——转入溢出表。Capacity of the fixed hot-path slot table (inline array; unused capacity costs nothing at runtime — allocation is per-arriving-thread and Merge/Reset loop to the used count). Exceeding it no longer fails — claims roll into the overflow table. |
Slots | TArray<T>[64] | — | 每 worker 的私有缓冲数组(前 64 槽的内联固定表),由 GetThreadBuffer 经原子分配索引写入。Per-worker private buffers (the first 64 slots are the inline fixed table), indexed by GetThreadBuffer via atomic slot assignment. |
NumUsedSlots | int32 | 0 | 已分配的槽位数,InterlockedIncrement 维护。Number of assigned slots, maintained via InterlockedIncrement. |
Generation | int32 | 0 | 代数,Reset/Merge 时递增,使 TLS 缓存失效。Generation counter; incremented on Reset/Merge to invalidate TLS caches. |
OverflowSlots | TArray<TUniquePtr<TArray<T>>> | 空 | 溢出槽指针表(第 65+ 线程);指针数组——外层增长不搬移被指向的 TArray,已发出的引用保持有效。Overflow slot pointer table (65th+ thread); a pointer array — outer growth never relocates the pointed-to TArrays, so handed-out references stay valid. |
OverflowReady | std::atomic<bool> | false | 溢出表就绪标志;acquire 读通过后 OverflowCap 有效,溢出分配免锁。Overflow-table-ready flag; once an acquire read passes, OverflowCap is valid and overflow claims are lock-free. |
OverflowCap | int32 | 0 | 溢出表容量(临界区下写入,acquire 读 OverflowReady 后有效)。Overflow table capacity (written under the critical section; valid after acquiring OverflowReady). |
InstanceId | uint64 | 递增分配 | 全局唯一实例 ID,与 Generation 一起构成 TLS 缓存键——免疫 this 指针地址复用碰撞。Globally unique instance id; forms the TLS cache key together with Generation — immune to this-pointer address-reuse collisions. |
OverflowCS | FCriticalSection | — | 仅保护溢出表的一次性构建/扩容。Guards only the one-time overflow-table build/growth. |
Items | TArray<T> | — | 合并输出——由 Merge() 填充。Merged output — populated by Merge(). |
方法 Methods
返回本线程的私有缓冲区——每线程每 tick 首次调用后无锁。首次访问(或代数变化)时经 InterlockedIncrement 原子领取槽位并缓存三个 thread_local(槽指针、实例 InstanceId、代数)。
Returns this thread's private buffer — lock-free after first call per thread per tick. On first access (or generation change) atomically claims a slot via InterlockedIncrement and caches three thread_local values (slot pointer, instance InstanceId, generation).
Input
无参数。
No parameters.
Output
返回本线程槽位的 TArray<T> 引用,可直接 Add。槽位超 MaxSlots 时透明转入溢出表(首次构建后无锁),不再 check 失败。
Returns a reference to this thread's slot array, ready for Add. Beyond MaxSlots the claim transparently rolls into the overflow table (lock-free after its one-time build) — no check failure.
把所有 worker 缓冲区(固定表与溢出表,按槽位分配序)合并(移动)到 Items 并重置槽位计数、递增代数。并行循环结束后调用。
Moves all worker buffers (fixed table and overflow table, in slot-allocation order) into Items, resets the slot count and bumps the generation. Called after the parallel loop.
Input
无参数。
No parameters.
Output
无返回值。副作用:Items 被填充、各槽被移动清空、NumUsedSlots 归零、代数递增。
No return value. Side effects: Items filled, slots moved-empty, NumUsedSlots zeroed, generation bumped.
清空所有缓冲区为下一帧准备:Items 与全部已用槽位(含溢出槽)Reset(),槽位计数归零,代数递增使 TLS 缓存失效。
Clears all buffers for the next frame: resets Items and every used slot (overflow slots included), zeroes the slot count, and bumps the generation so TLS caches invalidate.
Input
无参数。
No parameters.
Output
无返回值。副作用:全部缓冲清空、代数递增。
No return value. Side effects: all buffers cleared, generation bumped.
FEntityHandle USTRUCT
FMassEntityHandle 的蓝图可包装器(BlueprintType),公开 Index 与 Serial 两个只读属性。提供与 FMassEntityHandle 的双向隐式转换、相等比较与哈希。注意其有效性语义与 Mass 原生句柄不同:IsSet() 要求 Index != 0 && Serial != 0,IsEmptyHandle() 要求两者皆 0——0 是「空句柄」而非有效句柄。
Blueprint-friendly wrapper (BlueprintType) around FMassEntityHandle exposing the Index and Serial properties read-only. Provides implicit conversions both ways, equality comparison and hashing. Note the validity semantics differ from Mass's native handle: IsSet() requires Index != 0 && Serial != 0, IsEmptyHandle() requires both zero — 0 is "empty handle", not a valid one.
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
Index | int32 | 0 | 实体索引(只读,BlueprintReadOnly)。Entity index (read-only, BlueprintReadOnly). |
Serial | int32 | 0 | 实体序列号(只读),用于句柄复用时的失效检测。Entity serial number (read-only), detecting stale handles after slot reuse. |
方法 Methods
从 FMassEntityHandle 隐式构造,复制 Index / SerialNumber。
Implicit construction from FMassEntityHandle, copying Index / SerialNumber.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
MassHandle | const FMassEntityHandle& | Mass 原生句柄。Native Mass handle. |
Output
构造后的 FEntityHandle。
The constructed FEntityHandle.
隐式转换回 Mass 原生句柄(FMassEntityHandle(Index, Serial)),使 FEntityHandle 可直接传给要求 FMassEntityHandle 的 API。
Implicit conversion back to the native Mass handle (FMassEntityHandle(Index, Serial)), letting FEntityHandle pass directly to APIs taking FMassEntityHandle.
Input
无参数。
No parameters.
Output
返回等价的 FMassEntityHandle。
Returns the equivalent FMassEntityHandle.
有效性三件套:IsSet() = Index != 0 && Serial != 0;IsEmptyHandle() = 两者皆 0;Reset() 把两者清 0。
Validity trio: IsSet() = Index != 0 && Serial != 0; IsEmptyHandle() = both zero; Reset() zeroes both.
Input
无参数。
No parameters.
Output
IsSet/IsEmptyHandle 返回布尔;Reset 无返回值,副作用为清零成员。
IsSet/IsEmptyHandle return bool; Reset returns void and zeroes the members.
句柄相等比较(Index 与 Serial 同时相等)与哈希(HashCombine 两者),使 FEntityHandle 可用于 TMap/TSet 键。
Equality comparison (both Index and Serial equal) and hashing (HashCombine of both), making FEntityHandle usable as a TMap/TSet key.
Input
比较操作符各取一个 const FEntityHandle& 操作数。
Each comparison operator takes one const FEntityHandle& operand.
Output
比较返回布尔;哈希返回 uint32。
Comparisons return bool; the hash returns uint32.
FEntityFlagFragment USTRUCT
不引起 Archetype 迁移的动态旗标存储(FMassFragment 派生)。用两个 int64 位掩码承载 128 位(Flags 0–63,FlagsHigh 64–127),并用 std::atomic<bool> 自旋锁保证线程安全(Lock/Unlock,源自 FStatistics 的实现)。HasFlag 是读操作,当前技术上无锁;写操作(SetFlag/ClearFlag/SetFlagValue)先做无锁快速检查,状态已符合则直接返回,否则加锁执行。因含 std::atomic 成员,自实现拷贝构造/赋值;UE 5.7+ 特化 TMassFragmentTraits 声明为非平凡可拷贝。
Dynamic flag storage that avoids archetype migration (derived from FMassFragment). Two int64 bitmasks carry 128 bits (Flags 0–63, FlagsHigh 64–127), guarded by a std::atomic<bool> spinlock (Lock/Unlock, copied from the FStatistics implementation) for thread safety. HasFlag is a read and is currently technically lock-free; the writers (SetFlag/ClearFlag/SetFlagValue) first do a lock-free fast check and return early when the state already matches, otherwise lock. Because of the std::atomic member, copy construction/assignment are hand-written; on UE 5.7+ TMassFragmentTraits is specialized to accept its non-trivially-copyable nature.
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
Flags | int64 | 0 | 低位旗标位掩码(flag 0–63),BlueprintReadWrite。Low flag bitmask (flags 0–63), BlueprintReadWrite. |
FlagsHigh | int64 | 0 | 高位旗标位掩码(flag 64–127),BlueprintReadWrite。High flag bitmask (flags 64–127), BlueprintReadWrite. |
LockFlag | mutable std::atomic<bool> | false | 私有自旋锁标志,来自 FStatistics 实现。Private spinlock flag, copied from the FStatistics implementation. |
方法 Methods
自旋锁原语:Lock 用 exchange(true, acquire) 忙等抢锁;Unlock 用 store(false, release) 释放。均为 const 成员(锁标志为 mutable)。
Spinlock primitives: Lock busy-waits with exchange(true, acquire); Unlock releases with store(false, release). Both are const members (the lock flag is mutable).
Input
无参数。
No parameters.
Output
无返回值。Lock 阻塞直至获得锁。
No return value. Lock blocks until the lock is acquired.
128 位支持的静态助手:IsHighFlag 判断索引是否 ≥ 64(存于 FlagsHigh);GetLocalBitIndex 返回 Flag & 63(等价于 % 64)得到所在 int64 内的局部位号。
Static helpers for 128-bit support: IsHighFlag tells whether the index is ≥ 64 (stored in FlagsHigh); GetLocalBitIndex returns Flag & 63 (equivalent to % 64) for the local bit position inside the target int64.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Flag | EEntityFlags | 要判断的旗标枚举值。The flag enum value to inspect. |
Output
分别返回是否高位、以及 0–63 的局部位号。
Returns whether it is a high flag, and the local bit index 0–63 respectively.
检查某旗标是否置位。读操作,当前技术上无锁。越界(>= EEntityFlags_MAX)返回 false。
Checks whether a specific flag is set. A read operation, currently technically lock-free. Out-of-range (>= EEntityFlags_MAX) returns false.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Flag | EEntityFlags | 要检查的旗标。The flag to check. |
Output
返回是否置位;越界返回 false。
Returns whether the flag is set; false out of range.
写操作三件套,均线程安全:先做无锁快速检查(已置位/已清除/状态已匹配则直接返回),否则加锁执行位操作后解锁。按 IsHighFlag 选择写 Flags 或 FlagsHigh。越界直接返回。
Thread-safe write trio: each first does a lock-free fast check (already set / already clear / state already matches → early return), otherwise locks, applies the bit op and unlocks. Writes Flags or FlagsHigh per IsHighFlag. Out-of-range returns immediately.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Flag | EEntityFlags | 要设置/清除/写入的旗标。The flag to set / clear / write. |
bValue | bool | 仅 SetFlagValue:true 置位,false 清除。SetFlagValue only: true sets, false clears. |
Output
无返回值。副作用:修改对应位掩码(受锁保护)。
No return value. Side effects: mutates the corresponding bitmask (lock-protected).
FName 版本:经 UMassAPIFlagSettings::ResolveFlag 解析为 EEntityFlags 后委托给对应枚举版本;解析失败(EEntityFlags_MAX)时读返回 false、写静默跳过。
FName variants: resolve via UMassAPIFlagSettings::ResolveFlag then delegate to the enum versions; on resolution failure (EEntityFlags_MAX) reads return false and writes silently skip.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
FlagName | FName | 注册于 FlagRegistry 的旗标名。Flag name registered in FlagRegistry. |
bValue | bool | 仅 SetFlagValueByName。SetFlagValueByName only. |
Output
HasFlagByName 返回布尔(未注册为 false);写操作无返回值,未注册时无副作用。
HasFlagByName returns bool (false when unregistered); writers return void and have no side effect when unregistered.
FEntityQuery USTRUCT
蓝图可编辑的实体查询结构:三个 UScriptStruct 列表(AllList / AnyList / NoneList 覆盖 Tag/Fragment/Chunk/Shared/ConstShared,按类型自动分派)加三个 FName 旗标列表(AllFlagsList / AnyFlagsList / NoneFlagsList)。内部惰性构建 FMassArchetypeCompositionDescriptor 缓存与旗标位掩码缓存:C++ 侧列表修改经 MarkCacheDirty 标记;访问器入口另做配置签名校验——蓝图直接改列表无法调用标脏函数,签名不一致时自动重新标脏重建,缓存不会滞留旧配置。GetNativeQuery 把本结构转译为绑定到指定 EntityManager 的原生 FMassEntityQuery(不可缓存绑定查询本身,因 Manager 可能变化,但复用结构列表高效填充)。
Blueprint-editable entity query struct: three UScriptStruct lists (AllList / AnyList / NoneList covering Tag/Fragment/Chunk/Shared/ConstShared, auto-dispatched by type) plus three FName flag lists (AllFlagsList / AnyFlagsList / NoneFlagsList). Internally it lazily builds FMassArchetypeCompositionDescriptor caches and flag bitmask caches: C++ list mutations are flagged via MarkCacheDirty, and accessors validate a config signature on entry — Blueprint edits the lists directly (it cannot call the dirty marker), so a signature mismatch re-marks the caches dirty automatically and stale caches cannot linger. GetNativeQuery translates this struct into a native FMassEntityQuery bound to a given EntityManager (the bound query itself cannot be cached since the Manager can change, but the struct lists are reused to populate it efficiently).
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
AllList | TArray<TObjectPtr<UScriptStruct>> | 空 | All(必须全部)元素列表,BlueprintReadWrite。All (must-have) element list, BlueprintReadWrite. |
AnyList | TArray<TObjectPtr<UScriptStruct>> | 空 | Any(至少其一)元素列表。Any (at least one) element list. |
NoneList | TArray<TObjectPtr<UScriptStruct>> | 空 | None(必须全无)元素列表。None (must have none) element list. |
AllFlagsList | TArray<FName> | 空 | All 旗标名列表,经 FlagRegistry 编译为位掩码。All flag-name list, compiled to bitmasks via FlagRegistry. |
AnyFlagsList | TArray<FName> | 空 | Any 旗标名列表。Any flag-name list. |
NoneFlagsList | TArray<FName> | 空 | None 旗标名列表。None flag-name list. |
方法 Methods
流式 API(Flient):向对应列表批量追加模板参数类型,CheckType 编译期断言要求全部派生自 FMassFragment/FMassTag/FMassChunkFragment/FMassSharedFragment/FMassConstSharedFragment。每次调用后 MarkCacheDirty()。提供左值引用(返回 FEntityQuery&)与右值(返回 FEntityQuery&&)两个重载以支持链式写法。
Fluent API: batch-appends the template argument types to the corresponding list; CheckType static_asserts that all derive from FMassFragment/FMassTag/FMassChunkFragment/FMassSharedFragment/FMassConstSharedFragment. Calls MarkCacheDirty() after each call. Both lvalue (returns FEntityQuery&) and rvalue (returns FEntityQuery&&) overloads support chaining.
Input
仅模板参数(编译期类型包)。
Template parameters only (compile-time type pack).
Output
返回自身引用以支持链式调用;副作用:追加列表并标记缓存脏。
Returns a reference to itself for chaining; side effect: appends lists and marks the caches dirty.
组合缓存访问器:入口先做配置签名校验(检测外部/蓝图修改并自动标脏),对应脏标志为 true 时经 BuildCompositionFromStructs 重建后返回。内部类型按 IsChildOf 分派进五个位集。
Composition cache accessors: validate the config signature on entry (detecting external/Blueprint edits and re-marking dirty), rebuild via BuildCompositionFromStructs when the matching dirty flag is set, then return. Inner types dispatch into the five bit sets via IsChildOf.
Input
无参数。
No parameters.
Output
返回惰性构建的 composition 描述符引用。
Returns the lazily-built composition descriptor reference.
旗标位掩码缓存访问器(低位与高位各三个):入口先做配置签名校验;脏时经 BuildFlagsCache 把 FName 列表经 FlagRegistry 解析为位掩码(≥64 进高位)。
Flag bitmask cache accessors (three low + three high): validate the config signature on entry; when dirty, BuildFlagsCache resolves the FName lists through FlagRegistry into bitmasks (≥64 into the high mask).
Input
无参数。
No parameters.
Output
返回 int64 位掩码(0 表示无旗标条件)。
Returns the int64 bitmask (0 means no flag condition).
生成绑定到指定 EntityManager 的原生 FMassEntityQuery:构造绑定查询后经 ConfigureQuery 填充需求——AllList 按 All/ReadOnly、AnyList 按 Any/ReadOnly、NoneList 按 None/None 添加;Tag 用 AddTagRequirement,Shared/ConstShared/Chunk/Fragment 各走对应需求 API。构造方式按引擎版本分派:5.6+ 用 FMassEntityQuery(EntityManager) 构造函数,5.4/5.5 默认构造后直接填需求。≤5.5 引擎无运行期类型(UScriptStruct*)的 Shared/Chunk 需求 API,这两类需求被跳过并打告警日志;常量共享需求为 5.5+。注意旗标列表不参与原生查询,需调用方另行过滤。
Builds a native FMassEntityQuery bound to the given EntityManager: constructs the bound query then populates requirements via ConfigureQuery — AllList as All/ReadOnly, AnyList as Any/ReadOnly, NoneList as None/None; tags via AddTagRequirement, Shared/ConstShared/Chunk/Fragment via their requirement APIs. Construction is version-dispatched: 5.6+ uses the FMassEntityQuery(EntityManager) constructor, while 5.4/5.5 default-construct and populate requirements directly. On ≤5.5 the engine has no runtime-typed (UScriptStruct*) Shared/Chunk requirement APIs, so those requirement kinds are skipped with a warning log; const-shared requirements need 5.5+. Note the flag lists do not participate in the native query; callers must filter them separately.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
EntityManager | const TSharedPtr<FMassEntityManager>& | 绑定目标 EntityManager。The EntityManager to bind to. |
Output
返回配置完成的原生查询对象(值返回)。
Returns the fully-configured native query object (by value).
把全部四个脏标志(三个 composition + 旗标缓存)置 true,强制下次访问时重建。声明为 const——脏标志为 mutable,允许 const 访问器在检测到配置签名变化时调用。C++ 列表修改与构造入口都调用它;蓝图侧修改由访问器的签名校验自动覆盖,无需手动标脏。
Sets all four dirty flags (three compositions + flag cache) to true, forcing rebuild on next access. Declared const — the flags are mutable, letting const accessors call it when the config signature changed. Called by every C++ list mutation and constructor entry; Blueprint-side edits are covered automatically by the accessors' signature validation, with no manual dirtying needed.
Input
无参数。
No parameters.
Output
无返回值。副作用:全部缓存标记为脏。
No return value. Side effect: all caches marked dirty.
FEntityQueryBuilder + FAccessTag / MARO / MARW struct
从 processor 的 ConfigureQueries 流式配置 FMassEntityQuery 的构建器。用法:FEntityQueryBuilder(EntityQuery).All<FAgentTag, FAITag>().All<FLocating, FRotating>(MARW).All<FScaling, FCollider>(MARO).RegisterWithProcessor(*this)。类型经 if constexpr 自动分派:Tag 忽略读写参数;ConstShared + ReadWrite 触发编译期 static_assert 错误;Shared/Chunk/Fragment 各走对应需求 API。FAccessTag<Val> 是编译期读写标签,全局常量 MARO(ReadOnly)与 MARW(ReadWrite)为其内联实例。
Fluent builder for configuring FMassEntityQuery from processor ConfigureQueries. Usage: FEntityQueryBuilder(EntityQuery).All<FAgentTag, FAITag>().All<FLocating, FRotating>(MARW).All<FScaling, FCollider>(MARO).RegisterWithProcessor(*this). Types dispatch via if constexpr: Tags silently ignore the access tag; ConstShared + ReadWrite triggers a compile-time static_assert; Shared/Chunk/Fragment use their requirement APIs. FAccessTag<Val> is a compile-time access tag, with the global constants MARO (ReadOnly) and MARW (ReadWrite) as inline instances.
方法 Methods
按 (Presence, Access) 分组添加需求,默认访问级别 MARO(ReadOnly)。逐参数经 AddSingle 按类型分派到 AddTagRequirement / AddConstSharedRequirement / AddSharedRequirement / AddChunkRequirement / AddRequirement。
Adds requirements grouped by (Presence, Access), defaulting to MARO (ReadOnly). Each argument goes through AddSingle, dispatching by type to AddTagRequirement / AddConstSharedRequirement / AddSharedRequirement / AddChunkRequirement / AddRequirement.
Input
模板参数为元素类型包;可选的 TAccess 访问标签参数,默认 MARO。
Template types plus an optional TAccess access tag argument, default MARO.
Output
返回自身引用以支持链式调用;副作用:向底层查询添加需求。
Returns a reference to itself for chaining; side effect: adds requirements to the underlying query.
把底层查询注册到 processor:RegisterWithProcessor 接受 UMassProcessor&;模板版本 RegisterQuery<T> 在调用点解析为 Processor.RegisterQuery(Query)。
Registers the underlying query with a processor: RegisterWithProcessor takes a UMassProcessor&; the template RegisterQuery<T> resolves to Processor.RegisterQuery(Query) at the call site.
Input
processor 对象(引用或模板类型)。
The processor object (reference or template type).
Output
无返回值。副作用:查询进入 processor 的注册表。
No return value. Side effect: the query enters the processor's registry.
FEntityTemplate USTRUCT
在编辑器中定义实体模板的蓝图可访问包装(BlueprintType):设计器用 FInstancedStruct 数组组合标签与带初值的 fragment,再经 GetTemplateData 转为 C++ 侧 FMassEntityTemplateData。实现(MassAPIStructs.cpp):先重置目标,再按序添加 Tags(仅类型)、Fragments(类型+初值)、MutableSharedFragments / ConstSharedFragments(经 EntityManager 去重存储),最后若 Flags 非空则构建 FEntityFlagFragment(0–63 进低位、64–127 进高位)一并加入。
Blueprint-accessible wrapper (BlueprintType) for defining entity templates in the editor: designers compose tags and value-initialized fragments via FInstancedStruct arrays, then GetTemplateData converts them into a C++ FMassEntityTemplateData. Implementation (MassAPIStructs.cpp): resets the target, then adds Tags (type only), Fragments (type + initial value), MutableSharedFragments / ConstSharedFragments (deduped through the EntityManager), and finally, when Flags is non-empty, builds an FEntityFlagFragment (0–63 low, 64–127 high) into the template.
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
Tags | TArray<FInstancedStruct> | 空 | 要添加到实体的标签列表(Tag 无数据,加一项即可),meta BaseStruct = MassTag。Tags to add to the entity (tags carry no data; one entry of the desired type suffices), meta BaseStruct = MassTag. |
Fragments | TArray<FInstancedStruct> | 空 | 带初值的 fragment 列表,仅允许 FMassFragment 派生结构。Fragments with initial values; only FMassFragment-derived structs allowed. |
MutableSharedFragments | TArray<FInstancedStruct> | 空 | 带初值的可变共享 fragment 列表,仅 FMassSharedFragment 派生。Mutable shared fragments with initial values; only FMassSharedFragment-derived. |
ConstSharedFragments | TArray<FInstancedStruct> | 空 | 带初值的常量共享 fragment 列表,仅 FMassConstSharedFragment 派生。Const shared fragments with initial values; only FMassConstSharedFragment-derived. |
Flags | TArray<EEntityFlags> | 空 | 初始旗标列表,GetTemplateData 时打包进 FEntityFlagFragment 位掩码。Initial flags; packed into an FEntityFlagFragment bitmask by GetTemplateData. |
方法 Methods
把本结构的数据收集进 FMassEntityTemplateData 实例(见结构体介绍的分步逻辑)。应在 C++ 侧调用,把蓝图定义的模板转换为 MassEntityManager 可用的格式。
Gathers this struct's data into an FMassEntityTemplateData instance (see the step-by-step logic in the struct description). Called from C++ to convert the Blueprint-defined template into a format the MassEntityManager can use.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
OutTemplateData | FMassEntityTemplateData& | 要填充的目标模板数据(先被重置)。Target template data to populate (reset first). |
EntityManager | FMassEntityManager& | 活动 EntityManager,用于创建共享 fragment 实例(去重)。The active EntityManager, required for creating (deduped) shared fragment instances. |
Output
无返回值。副作用:完全覆写 OutTemplateData(重置后重建);若 Flags 非空,消耗共享 fragment 去重存储。
No return value. Side effect: fully overwrites OutTemplateData (reset then rebuilt); consumes the shared-fragment dedup store when Flags is non-empty.
FEntityTemplateData USTRUCT
FMassEntityTemplateData 的蓝图可访问包装(BlueprintType):作为底层模板数据的句柄,可在蓝图中创建和修改,之后再用于构建实体。底层对象用 TSharedPtr 管理生命周期,支持拷贝共享同一数据。
Blueprint-accessible wrapper (BlueprintType) for FMassEntityTemplateData: acts as a handle to the underlying template data, allowing it to be created and modified via Blueprint before being used to build entities. The underlying object's lifetime is managed by a TSharedPtr, so copies share the same data.
方法 Methods
检查句柄是否指向有效数据(DataPtr.IsValid())。
Checks whether the handle points to valid data (DataPtr.IsValid()).
Input
无参数。
No parameters.
Output
返回底层数据是否存在。
Returns whether the underlying data exists.
提供对底层 FMassEntityTemplateData 的直接访问(DataPtr.Get());未初始化时返回 nullptr。
Provides direct access to the underlying FMassEntityTemplateData (DataPtr.Get()); returns nullptr when uninitialized.
Input
无参数。
No parameters.
Output
返回底层指针;空句柄返回 nullptr。
Returns the underlying pointer, or nullptr for an empty handle.
补充说明 Notes
MassAPI 全模块对 FMassArchetypeCompositionDescriptor / FMassEntityTemplateData 的位集访问全部经 MassAPIVersion.h 的版本条件宏(CONTAINS_*、TEMPLATE_*、BIT_SET_*、HAS_ALL/ANY_COMPOSITION)完成,保证 5.4–5.8+ 各引擎 API 形态可移植。FEntityQuery 的 BuildFlagsCache 仅解析 FlagRegistry 中已注册的 FName,未注册名静默跳过。
All bit-set access on FMassArchetypeCompositionDescriptor / FMassEntityTemplateData across the MassAPI module goes through the version-conditional macros in MassAPIVersion.h (CONTAINS_*, TEMPLATE_*, BIT_SET_*, HAS_ALL/ANY_COMPOSITION), keeping the code portable across the 5.4–5.8+ engine API shapes. FEntityQuery::BuildFlagsCache only resolves FNames registered in FlagRegistry; unregistered names are silently skipped.
文件头部为 UE 5.4/5.5 提供「旧引擎垫片」:5.4 定义占位 FMassConstSharedFragment(派生 FMassFragment)与空 FMassConstSharedFragmentBitSet——构造上惰性,5.4 无引擎级常量共享类型,不可能有类型派生自占位,CConstSharedFragment 恒为假,守卫路径全部为死代码;≤5.5 提供 MassAPIImpl::IntersectBitSet(经 ExportTypes + Contains/Remove 的公共 API 交集,供 BIT_SET_INTERSECT_COMPOSITION 的 5.4/5.5 分支使用)与 UE::Mass 概念(CFragment/CTag/CChunkFragment/CSharedFragment/CConstSharedFragment)及 TAlwaysFalse(5.6 起由引擎原生提供)。跨版本通用的 MassAPIImpl::ExportTypes(Set, Visit) 访问器形封装在此集中实现——5.4 的 TStructTypeBitSet 仅数组出参重载,5.5 起才有 TFunctionRef 重载。所有支持版本中片段基类均为独立根,TIsDerivedFrom 分发与引擎语义完全一致(源码注释)。
The top of the file provides "legacy engine shims" for UE 5.4/5.5: 5.4 defines placeholder FMassConstSharedFragment (deriving FMassFragment) and an empty FMassConstSharedFragmentBitSet — inert by construction: 5.4 has no engine-level const-shared type, nothing can derive from the placeholder, CConstSharedFragment is always false there and every guarded path is dead code; ≤5.5 gets MassAPIImpl::IntersectBitSet (a public-API intersection via ExportTypes + Contains/Remove, used by the 5.4/5.5 branches of BIT_SET_INTERSECT_COMPOSITION) plus the UE::Mass concepts (CFragment/CTag/CChunkFragment/CSharedFragment/CConstSharedFragment) and TAlwaysFalse (native from 5.6). The version-portable visitor-form MassAPIImpl::ExportTypes(Set, Visit) is centralized here — 5.4's TStructTypeBitSet only has the array-out overload; the TFunctionRef overload exists from 5.5. In all supported versions the fragment base classes are independent roots, so the TIsDerivedFrom dispatch mirrors engine semantics exactly (per source comments).