UMassBattleAgentSubsystem
Source/MassBattle/Public/Subsystems/MassBattleAgentSubsystem.h
概述 Overview
Agent 实体的生成与管理中心,MassBattle 中体量最大的子系统(实现约 4900 行)。核心职责:① 全部 agent 生成入口——矩形/圆形/多边形区域生成、EQS 异步生成、延迟(Deferred)批量生成,统一汇聚到 SpawnAgentsAtLocations_Internal,按「串行预计算(UID 预留 + 子系统 RandomStream 随机乘数)→ BuildEntities 批量建实体 → MBParallelFor 并行填 fragment → 串行 UID 注册」三阶段执行,保证锁步双端 UID 分配顺序一致;② ExecuteTick 每逻辑帧排空延迟生成队列与 Actor 生成/回收队列(Particle ↔ Actor 表现互换,确定性排序);③ 端侧本地 select 视觉体系——LocalVisualRegistry 按 agent UID 登记纯本地宿主(UID=-1、无 FNetworkTag),resync 后由 RebindLocalVisualsAfterResync 重挂;④ 一批 agent 运行时读写接口(控制模式、移动输入、行为切换、变换读写、FX/宿主附着)。网络模式下所有 agent 生成路径都经 IsOffLockstep 守卫,锁步命令路径外一律拦截([RULE7])。
The spawn and management center for Agent entities and the largest subsystem in MassBattle (~4900 lines of implementation). Core duties: ① all agent-spawn entry points — rectangular / circular-polygon region spawning, async EQS spawning, and deferred batch spawning — funnel into SpawnAgentsAtLocations_Internal, which runs in three phases ("serial pre-compute (UID reservation + per-agent random multipliers from the subsystem RandomStream) → batch entity creation via BuildEntities → parallel fragment fill via MBParallelFor → serial UID registration") so UID allocation order is identical across lockstep peers; ② ExecuteTick drains the deferred spawn queue and the Actor spawn/recycle queues (Particle ↔ Actor representation swapping, deterministically sorted) every logic frame; ③ the peer-local select-visual system — LocalVisualRegistry keys purely-local hosts (UID=-1, no FNetworkTag) by agent UID, re-attached by RebindLocalVisualsAfterResync after a resync; ④ a set of runtime read/write APIs for agents (control mode, movement input, behavior switching, transform reads/writes, FX/host attachment). In networked mode every agent-spawn path is guarded by IsOffLockstep and blocked outside the lockstep command path ([RULE7]).
继承 Inheritance
辅助结构体 Helper Structs
头文件中四个非 USTRUCT 的普通 C++ 结构体,分别服务 EQS 生成、Actor 绑定队列、本地视觉登记与延迟生成队列。
Four plain C++ structs (not USTRUCTs) in the header, serving EQS spawning, actor-binding queues, local visual registration, and the deferred spawn queue respectively.
延迟生成完成回调的委托类型:参数为本次生成的全部实体句柄数组 const TArray<FEntityHandle>&。由 ProcessDeferredSpawnRequests 在请求完成(达到目标数量或位置耗尽)时调用。
Delegate type for deferred-spawn completion callbacks: takes the full array of spawned entity handles (const TArray<FEntityHandle>&). Invoked by ProcessDeferredSpawnRequests when a request completes (target quantity reached or all locations exhausted).
挂起的 EQS 生成请求记录。SpawnAgentsByTemplateEQS 发起 EQS 查询时存入 PendingEQSRequests(先以自增 RequestID 为键,查询返回后再改用运行时 QueryID 为键);查询完成后由 OnEQSQueryFinished 取出并执行生成。
Pending EQS spawn request record. Stored in PendingEQSRequests by SpawnAgentsByTemplateEQS when the EQS query is issued (keyed by an incrementing RequestID first, then re-keyed to the runtime QueryID); consumed by OnEQSQueryFinished once the query completes.
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
RequestID | int32 | -1 | 内部自增请求 ID(EQSRequestIDCounter 生成),查询完成后被 QueryID 取代。Internal incrementing request ID (from EQSRequestIDCounter), replaced by the QueryID once the query runs. |
BaseTemplate | FEntityTemplateData | — | 生成所用的实体模板(含全部 fragment/tag 组合)。Entity template used for spawning (full fragment/tag composition). |
Quantity | int32 | 0 | 目标生成数量。Target spawn quantity. |
Team | int32 | 0 | 队伍索引,写入 FTeam.index。Team index, written into FTeam.index. |
LaunchVelocity | FVector2D | — | 出生初速度:X = 前向速度、Y = 垂直速度(注入 FMoving.CurrentVelocity)。Spawn initial velocity: X = forward speed, Y = vertical speed (injected into FMoving.CurrentVelocity). |
InitialRotation | EInitialRotation | — | 出生朝向策略(FacePlayer / CustomRotation)。Spawn facing policy (FacePlayer / CustomRotation). |
CustomRotation | FRotator | — | CustomRotation 模式下的出生旋转。Spawn rotation used in CustomRotation mode. |
Multipliers | FSpawnerMult | — | 每实体随机乘数范围(生命/移速/伤害/缩放)。Per-agent random multiplier ranges (health / move speed / damage / scale). |
LatentInfo | FLatentActionInfo | — | 延迟动作信息,用于挂一个空的 FMassPendingLatentAction 使蓝图 EQS 节点保持挂起。Latent action info; a no-op FMassPendingLatentAction is attached so the Blueprint EQS node stays pending. |
Actor 生成/回收队列的请求记录。「支持确定性排序」——ExecuteTick 排空 ActorSpawnRequestQueue / ActorRecycleQueue 时,若 bDeterministic 开启则按 UniqueID 升序排序后再逐个处理,保证双端 Actor 绑定/回收顺序一致。
Request record for the Actor spawn/recycle queues. "Supporting deterministic sorting" — when draining ActorSpawnRequestQueue / ActorRecycleQueue in ExecuteTick, requests are sorted ascending by UniqueID when bDeterministic is on, keeping actor bind/recycle order identical across peers.
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
Entity | FMassEntityHandle | — | 请求绑定的 agent 实体句柄。Agent entity handle to bind. |
UniqueID | int32 | -1 | 实体 UID,确定性排序键(-1 = 无效)。Entity UID, the deterministic sort key (-1 = invalid). |
本地视觉登记项:每个被选中 agent 一项(键 = agent UID),持有 select 视觉生成的纯本地宿主实体(UID=-1、无 FNetworkTag)。这些宿主永不进入快照/hash/网络池——resync 后按 UID 重新挂接到重建的 agent。登记表是端侧本地 select 状态的唯一事实来源;agent 的 FBeingSelect fragment 数组镜像它(重链时写回,使 DeselectAgents 既有的 DestroyStateData 路径销毁正确的宿主)。与 FBeingSelect 同构——宿主按 select 状态分组,deselect 单个状态不会误销毁另一状态的宿主。仅限游戏线程访问(严禁放入 MBParallelFor 并行体)。
Local-visual registry entry: one per selected agent (keyed by agent UID), holding the purely local host entities (UID=-1, no FNetworkTag) spawned for select visuals. These hosts never enter snapshot/hash/network pools — after a resync they are re-attached to the rebuilt agent by UID. The registry is the single source of truth for peer-local select state; the agent's FBeingSelect fragment arrays mirror it (the rebind writes them back so DeselectAgents' existing DestroyStateData path destroys the right hosts). Isomorphic to FBeingSelect — hosts are split per select state, so deselecting one state never destroys the other state's hosts. Game-thread only (never mutate inside MBParallelFor bodies).
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
bSelected | bool | false | Selected flag + SelectedData 宿主;resync 后重放为 agent 的 Selected flag。Selected flag + SelectedData hosts; replayed as the agent's Selected flag after resync. |
bBeingSelect | bool | false | BeingSelect flag + BeingSelectData 宿主;resync 后重放为 agent 的 BeingSelect flag。BeingSelect flag + BeingSelectData hosts; replayed as the agent's BeingSelect flag after resync. |
BeingSelectData | FBeingSelectStateData | — | BeingSelect 状态的宿主数组(Actor/Fx/Sound 三组,见 Fragments/Select.h)。Host arrays for the BeingSelect state (Actor/Fx/Sound groups, see Fragments/Select.h). |
SelectedData | FBeingSelectStateData | — | Selected 状态的宿主数组。Host arrays for the Selected state. |
AttachedVisuals | FBeingSelectStateData | — | 通用附着视觉(SpawnBatchedFx / AttachNiagaraToAgent / AttachCascadeToAgent / AttachActorToAgent 且 AttachToEntity 有效):跟随实体、resync 后需重链的本地宿主,但不是 select 状态——无 flag 位、不写回 FBeingSelect、不受 DeselectAgents 影响。与 select 组一起清理/重链/销毁(同为 UID 键 = 父实体 UID)。General attached visuals (SpawnBatchedFx / AttachNiagaraToAgent / AttachCascadeToAgent / AttachActorToAgent with a valid AttachToEntity): peer-local hosts that follow the entity and need re-linking after resync, but are NOT select state — no flag bits, no FBeingSelect write-back, unaffected by DeselectAgents. Pruned/re-linked/destroyed together with the select groups (same UID key = the parent entity's UID). |
方法:Reset()(FORCEINLINE)——清除两个 flag 并重置三组数据。
Method: Reset() (FORCEINLINE) — clears both flags and resets all three state-data groups.
延迟生成请求记录,由 SpawnAgentsAtLocations_Internal(bDeferred=true)在 DeferredSpawnLock 保护下追加到 DeferredSpawnRequests,ProcessDeferredSpawnRequests 每 tick 批量处理。支持子步(substep)分摊:Substeps > 0 时生成分摊到 (Substeps + 1) 个 tick(如 Substeps=1 表示 2 个 tick)。
Deferred spawn request record, appended to DeferredSpawnRequests under DeferredSpawnLock by SpawnAgentsAtLocations_Internal (bDeferred=true) and processed in batch each tick by ProcessDeferredSpawnRequests. Supports substep spreading: with Substeps > 0 spawns are spread across (Substeps + 1) ticks (e.g. Substeps=1 means 2 ticks).
成员变量 Members
| 名称 Name | 类型 Type | 默认值 | 说明 Description |
|---|---|---|---|
BaseTemplate | FEntityTemplateData | — | 生成所用的实体模板。Entity template used for spawning. |
Locations | TArray<FVector> | — | 候选生成位置列表(数量可大于目标 Quantity,供验证失败后重试)。Candidate spawn locations (may exceed the target Quantity to allow retries after validation failures). |
Quantity | int32 | 0 | 目标生成数量;-1 = 生成所有有效位置。Target spawn quantity; -1 = spawn all valid locations. |
Team | int32 | 0 | 队伍索引。Team index. |
LaunchVelocity | FVector2D | ZeroVector | 出生初速度(X = 前向、Y = 垂直)。Spawn initial velocity (X = forward, Y = vertical). |
InitialRotation | EInitialRotation | FacePlayer | 出生朝向策略。Spawn facing policy. |
CustomRotation | FRotator | ZeroRotator | CustomRotation 模式下的出生旋转。Spawn rotation in CustomRotation mode. |
Multipliers | FSpawnerMult | — | 每实体随机乘数范围。Per-agent random multiplier ranges. |
GroundTraceChannel | ECollisionChannel | ECC_WorldStatic | 落地检测通道;入队时取自模板 FMove.Z.GroundTraceChannel(无 FMove 时保持默认)。仅当未指定 ObjectTypes 时作回退单通道检测。Ground trace channel; taken from the template's FMove.Z.GroundTraceChannel at enqueue time (default kept when FMove is absent). Used as the fallback single-channel trace only when no object types are specified. |
GroundTraceHeightRange | FVector2D | (1000.f, -1000.f) | 向下检测的高度范围(入队时规范化:X = 起测偏移 max、Y = 终点偏移 min)。Vertical range for the downward trace (normalized at enqueue: X = start offset max, Y = end offset min). |
GroundObjectTypes | TArray<TEnumAsByte<EObjectTypeQuery>> | 空 | 地面对象类型(命中后取 ImpactPoint 为出生点;空 = 不做地面检测)。Ground object types (ImpactPoint becomes the spawn point on hit; empty = no ground check). |
ObstacleObjectTypes | TArray<TEnumAsByte<EObjectTypeQuery>> | 空 | 障碍对象类型(命中即判定该位置无效)。Obstacle object types (a hit invalidates the location). |
MaxSlopeCosine | float | 0.f | 最大坡度余弦阈值(> 0 时启用坡度拒绝,法线 Z 小于该值的位置无效)。Max slope cosine threshold (> 0 enables slope rejection; locations whose normal Z is below it are invalid). |
bAutoActivated | bool | true | 生成后是否立即设置 Activated flag。Whether to set the Activated flag on spawn. |
OnFinished | FOnAgentSpawnFinished | — | 全部生成完成(或位置耗尽)时触发,携带累计的有效句柄。Fired when spawning completes (or locations are exhausted), carrying the accumulated valid handles. |
Substeps | int32 | 0 | 子步数:0 = 单 tick 全部生成;> 0 = 分摊到 (Substeps + 1) 个 tick。Substep count: 0 = all spawned in one tick; > 0 = spread across (Substeps + 1) ticks. |
bFirstTickPending | bool | false | 为 true 时本 tick 跳过处理并置回 false(Substeps > 0 时用于把起始延迟到下一帧)。When true, processing is skipped this tick and the flag resets to false (used with Substeps > 0 to delay the start to the next frame). |
CurrentSubstepIndex | int32 | 0 | 运行时子步进度(剩余 tick 数 = Substeps + 1 - 当前索引)。Runtime substep progress (remaining ticks = Substeps + 1 - current index). |
NextLocationIndex | int32 | 0 | 下一 tick 的起始位置索引。Location index where the next tick starts. |
AccumulatedHandles | TArray<FEntityHandle> | 空 | 跨 tick 累计的有效生成句柄(达到 Quantity 即完成)。Valid spawned handles accumulated across ticks (completion when reaching Quantity). |
AccumulatedUIDs | TArray<int32> | 空 | 平行 UID 列表——与句柄追加点同步维护(生成时经 FindUIDByEntityFast 一次查找入列);快照捕获直接拷贝本数组,取代逐句柄经 UID TMap 反查(暴兵规模下几十万次查找曾是 DeferredSpawns 的最大头)。Parallel UID list — maintained at every handle-append site (one FindUIDByEntityFast lookup at spawn time); snapshot capture copies this array directly instead of reverse-mapping every handle through the UID TMap (hundreds of thousands of lookups at mass-spawn scale dominated the DeferredSpawns cost). |
公开方法 Public Methods
生命周期 Lifecycle
默认构造函数,实现体为空({})。所有成员使用类内初始化;确定性随机流 RandomStream 的种子在 Initialize 中设置。
Default constructor with an empty body ({}). All members use in-class initializers; the deterministic RandomStream seed is set in Initialize.
Input
无参数。
No parameters.
Output
无返回值,无副作用。
No return value, no side effects.
USubsystem 生命周期入口。调用父类后预热 UMassAPISubsystem 与 UMassBattleSubsystem 缓存,然后把 RandomStream 以固定常量种子 0x5EEDBEEF 初始化——保证所有客户端默认确定一致;如需会话级变化,从 BP 重新设置 RandomStream(源码注释)。
USubsystem lifecycle entry. After calling the parent, it warms the UMassAPISubsystem / UMassBattleSubsystem caches and initializes RandomStream with the fixed constant seed 0x5EEDBEEF — all clients are deterministic by default; for per-session variation, re-seed RandomStream from BP (source comment).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Collection | FSubsystemCollectionBase& | 子系统集合,由引擎传入。Subsystem collection provided by the engine. |
Output
无返回值。副作用:填充两个子系统缓存、重置 RandomStream 种子(源码中「Reset UniqueID Counter」注释处无对应实现)。
No return value. Side effects: fills two subsystem caches, re-seeds RandomStream (the "Reset UniqueID Counter" comment in source has no implementation behind it).
USubsystem 生命周期出口。调用父类后清空三个子系统缓存指针、清空 ActorSpawnRequestQueue / ActorRecycleQueue,并清空 LocalVisualRegistry——本地视觉宿主随世界消亡,清空登记表防止子系统实例复用时向新世界重放过期登记项(源码注释)。
USubsystem lifecycle exit. After calling the parent, it nulls the three subsystem caches, empties ActorSpawnRequestQueue / ActorRecycleQueue, and empties LocalVisualRegistry — local visual hosts die with the world, and clearing the registry prevents a reused subsystem instance from replaying stale entries into a fresh world (source comment).
Input
无参数。
No parameters.
Output
无返回值。副作用:清空三个缓存指针、两个队列与本地视觉登记表。
No return value. Side effects: clears the three cache pointers, both queues, and the local visual registry.
每帧 Tick Per-Frame Tick
每逻辑帧 tick 入口(由 UMassBattleSubsystem::ExecuteTick 在模拟阶段之前调用)。流程:① ProcessDeferredSpawnRequests() 批量处理延迟生成;② 排空 ActorSpawnRequestQueue(Particle→Actor 绑定)——bDeterministic 时按 UniqueID 升序排序,逐请求校验实体有效性与 bIsBindingActorSwappable,从池取 Actor 或现场 SpawnActor(碰撞覆盖为 AlwaysSpawn),经 FindAvailableComponent 找空闲 UMassBattleAgentComponent(没有则运行时 NewObject 添加)后 InitializeWithEntity,写回 FVisualizing.BindingActorPtr,并按 FAgentEvent 配置把 FPoolData(PoolSpawn) 推入 MB->OnPoolQueue;③ 排空 ActorRecycleQueue(Actor→Particle)——同样确定性排序,DeinitializeFromEntity 解绑组件,全部组件解绑(IsActorFullyRecyclable)才隐藏并 ReturnActorToPool,清空绑定指针;④ SweepLocalVisuals() 每 tick 本地视觉清理。
Per-logic-frame tick entry (called by UMassBattleSubsystem::ExecuteTick before the simulation stages). Flow: ① ProcessDeferredSpawnRequests() processes deferred spawns in batch; ② drains ActorSpawnRequestQueue (Particle→Actor binding) — sorted ascending by UniqueID when bDeterministic; per request it validates the entity and bIsBindingActorSwappable, takes an actor from the pool or spawns one (collision override AlwaysSpawn), finds a free UMassBattleAgentComponent via FindAvailableComponent (NewObject + RegisterComponent at runtime if none exists) and calls InitializeWithEntity, writes back FVisualizing.BindingActorPtr, and pushes FPoolData(PoolSpawn) into MB->OnPoolQueue per FAgentEvent config; ③ drains ActorRecycleQueue (Actor→Particle) — same deterministic sort, unbinds via DeinitializeFromEntity, hides and returns the actor to the pool only when all components are unbound (IsActorFullyRecyclable), then clears the binding pointers; ④ SweepLocalVisuals() for per-tick local visual cleanup.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
DeltaTime | float | 本逻辑帧时间步长(秒);当前实现未直接使用。Current logic-frame delta time in seconds; not used directly by the current implementation. |
Output
无返回值。副作用:消费延迟生成请求与两个 Actor 队列、可能 SpawnActor/回池 Actor、改写 FVisualizing/FAgentEventRT 等 fragment、向 OnPoolQueue 写池事件、清理本地视觉登记表。子系统缓存缺失时提前返回。
No return value. Side effects: consumes deferred spawn requests and both actor queues, may spawn/return actors, mutates fragments such as FVisualizing/FAgentEventRT, writes pool events into OnPoolQueue, and prunes the local visual registry. Returns early when subsystem caches are missing.
静态访问器 Static Accessors
静态访问器:从任意世界上下文对象解析出 UWorld,再取其 Agent 子系统。世界无效时返回 nullptr(不崩溃)。
Static accessor: resolves the UWorld from any world-context object and returns its Agent subsystem. Returns nullptr if the world is invalid (does not crash).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 任意 UObject 世界上下文(通过 GEngine->GetWorldFromContextObject 解析)。Any UObject world context (resolved via GEngine->GetWorldFromContextObject). |
Output
返回子系统指针;世界上下文无效时返回 nullptr。
Returns the subsystem pointer, or nullptr when the world context is invalid.
静态访问器的引用版本:失败即 checkf 断言崩溃——用于「子系统必须存在」的不变式场景。
Reference version of the static accessor: fails via checkf assertion — for invariant paths where the subsystem must exist.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 任意 UObject 世界上下文。Any UObject world context. |
Output
返回子系统引用;取不到时触发 checkf 断言("Failed to get UMassBattleAgentSubsystem from world context.")。
Returns a subsystem reference; triggers a checkf assertion ("Failed to get UMassBattleAgentSubsystem from world context.") when unavailable.
子系统获取 Subsystem Getters
惰性访问并缓存 UMassAPISubsystem:命中缓存直接返回;否则从当前世界取子系统并写入 MassAPISubsystem / CurrentWorld 缓存。声明为 const,经 mutable 缓存成员实现。
Lazily accesses and caches UMassAPISubsystem: returns the cache on hit; otherwise fetches the subsystem from the current world and fills the MassAPISubsystem / CurrentWorld cache. Declared const, implemented via the mutable cache members.
Input
无参数。
No parameters.
Output
返回 UMassAPISubsystem 指针(世界不存在时可能为 nullptr)。副作用:写入两个缓存成员。
Returns the UMassAPISubsystem pointer (may be nullptr if the world is missing). Side effect: fills the two cache members.
惰性访问并缓存 UMassBattleSubsystem(全局 UID 游标、确定性开关、池事件队列的宿主)。
Lazily accesses and caches UMassBattleSubsystem (home of the global UID cursor, the determinism switch, and the pool event queue).
Input
无参数。
No parameters.
Output
返回 UMassBattleSubsystem 指针;世界缺失时可能为 nullptr。
Returns the UMassBattleSubsystem pointer; may be nullptr if the world is missing.
惰性访问并缓存 UMassBattleHashGridSubsystem(空间哈希网格)。注意:在 Initialize 中未预热此缓存,首次使用才填充。
Lazily accesses and caches UMassBattleHashGridSubsystem (spatial hash grid). Note: this cache is NOT warmed in Initialize; it is filled on first use.
Input
无参数。
No parameters.
Output
返回 UMassBattleHashGridSubsystem 指针;世界缺失时可能为 nullptr。
Returns the UMassBattleHashGridSubsystem pointer; may be nullptr if the world is missing.
UID 注册 UID Registration
把 agent 实体的 UID→句柄映射写入 UMassBattleSubsystem 的全局 UID 注册表。守卫:UID 为负直接返回;句柄经 MA->IsValid 校验,无效返回;最后 MB->RegisterUIDEntity 双写。由 UMassBattleAgentComponent 在实体句柄重绑路径调用(MassBattleAgentComponent.cpp:934)。
Writes the agent entity's UID→handle mapping into UMassBattleSubsystem's global UID registry. Guarded: negative UID returns immediately; the handle is validated with MA->IsValid; finally MB->RegisterUIDEntity dual-writes the mapping. Called from UMassBattleAgentComponent's entity re-bind path (MassBattleAgentComponent.cpp:934).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
UniqueID | int32 | 实体全局 UID(-1 = 无效,直接忽略)。Global entity UID (-1 = invalid, ignored). |
Handle | FEntityHandle | 实体句柄;无效则忽略本次注册。Entity handle; invalid handles are ignored. |
Output
无返回值。副作用:向全局 UID 注册表写入/覆盖 (UID, Handle) 映射。
No return value. Side effect: writes/overwrites the (UID, Handle) mapping in the global UID registry.
Actor 池 Actor Pool
从按类分组的 Actor 池取一个 Actor:池中弹出一个(后进先出),池空返回 nullptr。仅限游戏线程调用(头文件注释)。
Pops an actor from the class-keyed actor pool (LIFO); returns nullptr when the pool is empty. Game-thread only (header comment).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
ActorClass | TSubclassOf<AActor> | Actor 类,作为池的键。Actor class, used as the pool key. |
Output
返回池中 Actor 指针;该类别池为空时返回 nullptr。副作用:弹出即从池中移除。
Returns the pooled actor, or nullptr when that class's pool is empty. Side effect: popping removes it from the pool.
把 Actor 归还到按类分组的池(FindOrAdd 保证键存在后追加)。无效 Actor 直接忽略。仅限游戏线程调用。
Returns an actor to the class-keyed pool (appends after FindOrAdd guarantees the key exists). Invalid actors are ignored. Game-thread only.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Actor | AActor* | 要归还的 Actor;无效(!IsValid)时静默返回。Actor to return; silently ignored when invalid (!IsValid). |
Output
无返回值。副作用:按 Actor->GetClass() 追加到对应池槽。
No return value. Side effect: appends to the pool slot keyed by Actor->GetClass().
蓝图生成节点(已弃用) Blueprint Spawn Nodes (Deprecated)
以下 UFUNCTION(BlueprintCallable) 节点全部带 meta=(DeprecatedFunction, DeprecationMessage = "Use the corresponding function in MassBattleFuncLib instead. This subsystem node will be removed in a future update.")——已弃用,后续版本移除,请改用 MassBattleFuncLib 中的对应函数。C++ 调用不受影响。
All of the following UFUNCTION(BlueprintCallable) nodes carry meta=(DeprecatedFunction, DeprecationMessage = "Use the corresponding function in MassBattleFuncLib instead. This subsystem node will be removed in a future update.") — deprecated and slated for removal; use the corresponding MassBattleFuncLib function instead. C++ callers are unaffected.
用给定种子重新初始化 RandomStream。实现即 RandomStream.Initialize(NewSeed),影响后续所有使用该流的随机(生成点洗牌、每实体乘数等)。
Re-initializes RandomStream with the given seed. Implementation is simply RandomStream.Initialize(NewSeed); affects all subsequent randomness using that stream (spawn-point shuffling, per-agent multipliers, etc.).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
NewSeed | int32 | 新的随机流种子。New random stream seed. |
Output
无返回值。副作用:重置 RandomStream 状态。
No return value. Side effect: resets the RandomStream state.
从 agent 配置 DataAsset 构建 FEntityTemplateData 模板。流程:① 取 DataAsset->ExtraData 经 UMassBattleFuncLib::Conv_BattleTemplateToEntityTemplate 转为基础模板;② 追加 FAgentTag、FMainType(Agent)、Agent/AI 两个 flag,以及 DataAsset 上的全部配置 fragment(Health/HealthBar/Damage/Debuff/Defence/Behavior/Move/Controller/Chase/Patrol/Navigation/Avoidance/Appear/Trace/Attack/Hit/Death/Visualize/TextPop/Statistics/Gather/Reinforce/Select/Event 等)与共享 fragment(FTrafficShared/FPhysicsShared/FAnimShared/FLODShared/FCurveShared/FTracingShared,共享 fragment 的 DeterministicHash 用 DataAsset 路径 hash 覆写);③ LoadAndRegisterAssets 预注册全部可达资源并把 DataAsset 本身记入 RegisteredAgentConfigDataAssetPtrs(防 GC);④ 网络模式下追加 FNetworking.Key = DataAsset 路径名 + FNetworkTag,并经 RegisterNetworkTemplateData 幂等注册进快照注册表。无效 DataAsset 打 Warning 并返回空模板。
Builds an FEntityTemplateData from an agent config DataAsset. Flow: ① converts DataAsset->ExtraData into a base template via UMassBattleFuncLib::Conv_BattleTemplateToEntityTemplate; ② adds FAgentTag, FMainType(Agent), the Agent/AI flags, plus every config fragment from the DataAsset (Health/HealthBar/Damage/Debuff/Defence/Behavior/Move/Controller/Chase/Patrol/Navigation/Avoidance/Appear/Trace/Attack/Hit/Death/Visualize/TextPop/Statistics/Gather/Reinforce/Select/Event, etc.) and shared fragments (FTrafficShared/FPhysicsShared/FAnimShared/FLODShared/FCurveShared/FTracingShared, with DeterministicHash overwritten by the DataAsset path hash); ③ LoadAndRegisterAssets pre-registers all reachable assets and records the DataAsset itself in RegisteredAgentConfigDataAssetPtrs (GC rooting); ④ in networked mode adds FNetworking.Key = DataAsset path name + FNetworkTag and idempotently registers the template into the snapshot registry via RegisterNetworkTemplateData. An invalid DataAsset logs a Warning and returns an empty template.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
DataAsset | const UMassBattleAgentConfigDataAsset* | agent 配置数据资产;无效则返回空模板。Agent configuration data asset; invalid input returns an empty template. |
Output
返回配置完成的 FEntityTemplateData(内部 FMassEntityTemplateData 经 MakeShared 共享)。副作用:预注册资源、网络模式下注册模板 Key 并写入 FNetworking/FNetworkTag。
Returns the configured FEntityTemplateData (inner FMassEntityTemplateData shared via MakeShared). Side effects: pre-registers assets; in networked mode registers the template key and writes FNetworking/FNetworkTag.
在矩形区域内按模板生成 agent(同步版)。流程:① 网格点生成——Region 与 Spacing 均 > 0 时按 ShapeDirection 定向生成居中网格(数量 = Floor(Region/Spacing)),否则生成 Quantity 个原点位置(由 Offset 后续散布);② 点验证——GroundObjectTypes/ObstacleObjectTypes 全空则全部点直接有效(可悬空);否则按高度范围向下 LineTraceMultiByObjectType,障碍命中或地面法线 Z < MaxSlope 余弦阈值即无效,地面命中取 ImpactPoint;③ 选点——Quantity=-1 或超出可用点数时全部采用;Sequential 取前 N 个,Random 用 RandomStream 洗牌取 N;④ Offset > 0 时加随机 XY 偏移并重测地面/障碍;⑤ 汇入 SpawnAgentsAtLocations_Internal 实际生成。
Spawns agents from a template within a rectangular region (synchronous). Flow: ① grid point generation — when both Region and Spacing are > 0, a centered grid oriented by ShapeDirection is produced (count = Floor(Region/Spacing)); otherwise Quantity points at the origin are produced (spread later by Offset); ② point validation — with both GroundObjectTypes/ObstacleObjectTypes empty all points are valid as-is (may float); otherwise a downward LineTraceMultiByObjectType over the height range runs, obstacle hits or ground normals below the MaxSlope cosine threshold invalidate a point, and ground hits yield the ImpactPoint; ③ point selection — Quantity=-1 (or exceeding available points) takes all; Sequential takes the first N; Random shuffles with RandomStream and takes N; ④ with Offset > 0, random XY offsets are applied and the ground/obstacle trace re-runs; ⑤ funnels into SpawnAgentsAtLocations_Internal for the actual spawn.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
BaseTemplate | const FEntityTemplateData& (ref) | 实体模板(由 MakeAgentTemplateDataFromDataAsset 或蓝图构造)。Entity template (from MakeAgentTemplateDataFromDataAsset or built in Blueprint). |
Quantity | const int32 | 目标数量;0 或 < -1 直接返回空;-1 = 生成全部有效点。Target count; 0 or < -1 returns empty; -1 = spawn every valid point. |
Team | const int32 | 队伍索引,写入 FTeam.index。Team index, written to FTeam.index. |
Origin | const FVector& | 区域中心世界坐标。Region center in world space. |
ShapeData | const FAgentSpawnRectangleShapeData& (ref) | 矩形区域参数:Region/Spacing/ShapeDirection/Offset/PositioningMode/MaxSlope/GroundTraceHeightRange/GroundObjectTypes/ObstacleObjectTypes。Rectangular region params: Region/Spacing/ShapeDirection/Offset/PositioningMode/MaxSlope/GroundTraceHeightRange/GroundObjectTypes/ObstacleObjectTypes. |
LaunchVelocity | const FVector2D& | 出生初速度(X = 前向、Y = 垂直;Size==0 时不注入)。Spawn initial velocity (X = forward, Y = vertical; skipped when Size==0). |
InitialRotation | EInitialRotation | 出生朝向:FacePlayer(取玩家 0 位置)或 CustomRotation。Spawn facing: FacePlayer (toward player 0) or CustomRotation. |
CustomRotation | const FRotator& | CustomRotation 模式下的出生旋转。Spawn rotation in CustomRotation mode. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围(生命/移速/伤害/缩放),串行由 RandomStream 采样保证确定性。Per-agent random multiplier ranges (health / move speed / damage / scale), sampled serially from RandomStream for determinism. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
PreAssignedUID | int32 | 预分配 UID(>= 0 时本批全部使用该 UID,否则逐个 AllocNextUID)。Pre-assigned UID (when >= 0, every agent in the batch uses it; otherwise AllocNextUID per agent). |
Output
返回实际生成实体的句柄数组;无效输入(子系统/世界缺失、Quantity 非法)返回空数组。副作用:分配全局 UID、构建实体并填 fragment、注册 UID 映射、消耗 RandomStream。
Returns the handles of the actually spawned entities; empty array on invalid input (missing subsystems/world, illegal Quantity). Side effects: allocates global UIDs, builds entities and fills fragments, registers UID mappings, and consumes RandomStream.
在圆形/多边形区域按模板生成 agent(同步版)。与矩形版本同构,差异在点生成:极坐标网格(Spacing.X = 切向弧长、Spacing.Y = 径向环距,从 InnerRadius 到 OuterRadius 布环;全圆 360° 不含端点、扇区含端点)或随机散布(数量 = Quantity×2,默认 1000,面积加权半径);Segments < 3 或 > 32 视为圆,否则按边数计算外接半径与扇形校验;多边形点超出外接半径即跳过;验证/选点/偏移与矩形版本相同。
Spawns agents from a template within a circular/polygonal region (synchronous). Isomorphic to the rectangular version; the difference is point generation: a polar grid (Spacing.X = tangential arc length, Spacing.Y = radial ring spacing, rings from InnerRadius to OuterRadius; full circles exclude the endpoint, sectors include both) or random scatter (Quantity×2 points, 1000 by default, area-weighted radius); Segments < 3 or > 32 is treated as a circle, otherwise the circumradius and sector check use the segment count; polygon points beyond the max radius are skipped; validation / selection / offset match the rectangular version.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
BaseTemplate | const FEntityTemplateData& (ref) | 实体模板。Entity template. |
Quantity | const int32 | 目标数量;0 或 < -1 返回空;-1 = 全部有效点。Target count; 0 or < -1 returns empty; -1 = all valid points. |
Team | const int32 | 队伍索引。Team index. |
Origin | const FVector& | 区域中心世界坐标。Region center in world space. |
ShapeData | const FAgentSpawnPolygonShapeData& (ref) | 圆形/多边形参数:OuterRadius/InnerRadius/Segments/SectorAngle/PolygonRotation/Spacing/ShapeDirection/Offset/PositioningMode/MaxSlope 等。Circular/polygon params: OuterRadius/InnerRadius/Segments/SectorAngle/PolygonRotation/Spacing/ShapeDirection/Offset/PositioningMode/MaxSlope, etc. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Output
返回实际生成实体的句柄数组;无效输入返回空数组。副作用同矩形版本(UID 分配、实体构建、fragment 填充、UID 注册)。
Returns the handles of the actually spawned entities; empty on invalid input. Side effects as in the rectangular version (UID allocation, entity building, fragment fill, UID registration).
矩形区域按 DataAsset 生成 agent 的便捷入口:先 MakeAgentTemplateDataFromDataAsset 建模板,再委托 SpawnAgentsByTemplateRectangular。DataAsset 无效时返回空数组。
Convenience entry for rectangular spawning from a DataAsset: builds the template via MakeAgentTemplateDataFromDataAsset, then delegates to SpawnAgentsByTemplateRectangular. Returns an empty array when the DataAsset is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
DataAsset | const UMassBattleAgentConfigDataAsset* | agent 配置数据资产(默认 nullptr)。Agent config data asset (default nullptr). |
Quantity | const int32 | 目标数量。Target count. |
Team | const int32 | 队伍索引。Team index. |
Origin | const FVector& | 区域中心。Region center. |
ShapeData | const FAgentSpawnRectangleShapeData& | 矩形区域参数。Rectangular region params. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Output
返回生成实体的句柄数组;DataAsset 无效时返回空数组。
Returns the spawned handles; empty when the DataAsset is invalid.
圆形/多边形区域按 DataAsset 生成 agent 的便捷入口:建模板后委托 SpawnAgentsByTemplateCircular。DataAsset 无效时返回空数组。
Convenience entry for circular/polygon spawning from a DataAsset: builds the template, then delegates to SpawnAgentsByTemplateCircular. Returns an empty array when the DataAsset is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
DataAsset | const UMassBattleAgentConfigDataAsset* | agent 配置数据资产(默认 nullptr)。Agent config data asset (default nullptr). |
Quantity | const int32 | 目标数量。Target count. |
Team | const int32 | 队伍索引。Team index. |
Origin | const FVector& | 区域中心。Region center. |
ShapeData | const FAgentSpawnPolygonShapeData& | 圆形/多边形参数。Circular/polygon params. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Output
返回生成实体的句柄数组;DataAsset 无效时返回空数组。
Returns the spawned handles; empty when the DataAsset is invalid.
矩形区域按模板生成 agent 的延迟版:与同步版共享点生成逻辑,但不做地面/障碍验证(验证推迟到 ProcessDeferredSpawnRequests 内并行执行,保留全部候选点以支持失败重试),按 PositioningMode 洗牌后经 SpawnAgentsAtLocations_Internal(bDeferred=true)入队。Substeps > 0 时生成分摊到 (Substeps + 1) 个 tick,且首 tick 跳过(bFirstTickPending);全部完成后触发 OnFinished 委托。
The deferred rectangular-template spawn: shares the point-generation logic with the synchronous version, but skips ground/obstacle validation here (validation happens in parallel inside ProcessDeferredSpawnRequests; all candidate points are kept for retry), shuffles per PositioningMode, and enqueues via SpawnAgentsAtLocations_Internal (bDeferred=true). With Substeps > 0 spawns spread across (Substeps + 1) ticks and the first tick is skipped (bFirstTickPending); OnFinished fires when everything completes.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
BaseTemplate | const FEntityTemplateData& (ref) | 实体模板。Entity template. |
Quantity | const int32 | 目标数量(0 或 < -1 直接返回)。Target count (0 or < -1 returns immediately). |
Team | const int32 | 队伍索引。Team index. |
Origin | const FVector& | 区域中心。Region center. |
ShapeData | const FAgentSpawnRectangleShapeData& | 矩形区域参数。Rectangular region params. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Substeps | const int32 | 0 = 单 tick 全部生成;> 0 = 分摊到 (Substeps + 1) 个 tick。0 = all in one tick; > 0 = spread across (Substeps + 1) ticks. |
OnFinished | const FOnAgentSpawnFinished& | 完成回调,携带累计有效句柄。Completion callback carrying the accumulated valid handles. |
Output
无返回值。副作用:向 DeferredSpawnRequests 追加请求(加锁),实际生成发生在后续 ExecuteTick。
No return value. Side effect: appends a request to DeferredSpawnRequests (under lock); actual spawning happens on later ExecuteTick calls.
圆形/多边形区域按模板生成 agent 的延迟版:点生成与同步版一致(极坐标网格或随机散布),不做验证直接入队,其余行为与 SpawnAgentsByTemplateRectangularDeferred 相同。
The deferred circular/polygon-template spawn: point generation matches the synchronous version (polar grid or random scatter); no validation here, enqueued directly; otherwise behaves like SpawnAgentsByTemplateRectangularDeferred.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
BaseTemplate | const FEntityTemplateData& (ref) | 实体模板。Entity template. |
Quantity | const int32 | 目标数量(0 或 < -1 直接返回)。Target count (0 or < -1 returns immediately). |
Team | const int32 | 队伍索引。Team index. |
Origin | const FVector& | 区域中心。Region center. |
ShapeData | const FAgentSpawnPolygonShapeData& | 圆形/多边形参数。Circular/polygon params. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Substeps | const int32 | 子步数(0 = 单 tick)。Substep count (0 = single tick). |
OnFinished | const FOnAgentSpawnFinished& | 完成回调。Completion callback. |
Output
无返回值。副作用:向 DeferredSpawnRequests 追加请求。
No return value. Side effect: appends a request to DeferredSpawnRequests.
矩形区域按 DataAsset 延迟生成:建模板后委托 SpawnAgentsByTemplateRectangularDeferred。DataAsset 无效时直接返回。
Deferred rectangular spawn from a DataAsset: builds the template, then delegates to SpawnAgentsByTemplateRectangularDeferred. Returns immediately when the DataAsset is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
DataAsset | const UMassBattleAgentConfigDataAsset* | agent 配置数据资产。Agent config data asset. |
Quantity | const int32 | 目标数量。Target count. |
Team | const int32 | 队伍索引。Team index. |
Origin | const FVector& | 区域中心。Region center. |
ShapeData | const FAgentSpawnRectangleShapeData& | 矩形区域参数。Rectangular region params. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Substeps | const int32 | 子步数。Substep count. |
OnFinished | const FOnAgentSpawnFinished& | 完成回调。Completion callback. |
Output
无返回值。副作用:入队延迟生成请求。
No return value. Side effect: enqueues a deferred spawn request.
圆形/多边形区域按 DataAsset 延迟生成:建模板后委托 SpawnAgentsByTemplateCircularDeferred。DataAsset 无效时直接返回。
Deferred circular/polygon spawn from a DataAsset: builds the template, then delegates to SpawnAgentsByTemplateCircularDeferred. Returns immediately when the DataAsset is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
DataAsset | const UMassBattleAgentConfigDataAsset* | agent 配置数据资产。Agent config data asset. |
Quantity | const int32 | 目标数量。Target count. |
Team | const int32 | 队伍索引。Team index. |
Origin | const FVector& | 区域中心。Region center. |
ShapeData | const FAgentSpawnPolygonShapeData& | 圆形/多边形参数。Circular/polygon params. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bAutoActivated | const bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Substeps | const int32 | 子步数。Substep count. |
OnFinished | const FOnAgentSpawnFinished& | 完成回调。Completion callback. |
Output
无返回值。副作用:入队延迟生成请求。
No return value. Side effect: enqueues a deferred spawn request.
激活与标签同步 Activation & Tag Sync
激活/停用单个 agent:仅设置/清除 Activated flag,不做 tag 操作(避免昂贵的 archetype 迁移);激活时额外调用 SyncAgentTagsAndController 同步子类型/队伍标签与控制器状态。无效句柄静默返回。
Activates/deactivates a single agent: only sets/clears the Activated flag — no tag operations (avoiding expensive archetype migration); on activation it also calls SyncAgentTagsAndController to sync subtype/team tags and controller state. Invalid handles return silently.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
AgentHandle | const FEntityHandle& | 目标 agent 句柄。Target agent handle. |
bActivated | bool | true = 设置 flag 并同步标签;false = 清除 flag。true = set the flag and sync tags; false = clear the flag. |
Output
无返回值。副作用:改写 Activated flag;激活时可能迁移 SubType/Team tag 并改写 FAgentControlling.PreviousControlMode。
No return value. Side effects: mutates the Activated flag; on activation may migrate SubType/Team tags and write FAgentControlling.PreviousControlMode.
批量激活/停用:对数组内每个有效句柄执行与 ActivateAgent 相同的逻辑。
Batch activate/deactivate: runs the same logic as ActivateAgent for every valid handle in the array.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
AgentHandles | const TArray<FEntityHandle>& | 目标 agent 句柄数组。Target agent handle array. |
bActivated | bool | true = 设置 flag 并同步标签;false = 清除 flag。true = set the flag and sync tags; false = clear the flag. |
Output
无返回值。副作用:逐实体改写 flag/标签(无效句柄跳过)。
No return value. Side effects: per-entity flag/tag mutation (invalid handles skipped).
从当前 fragment 值同步 agent 的 SubType/Team tag 与控制器状态:① SubType.Index ≠ PreviousIndex 时移除旧 tag、添加新 tag 并更新 PreviousIndex;② Team.index ≠ PreviousIndex 时同理(索引 ≥ 0 才操作);③ Controlling.PreviousControlMode = Controller.ControlMode。使用直接(非延迟)tag 变更——在手动初始化或激活后调用,确保下一处理器 tick 前 tag 正确;头文件注释明确「不要每帧调用」。PlayerDrivenFlag 不在此处同步(由 SetAgentControlMode / AddAgentMovementInput / ReactionProcessor 设置)。
Syncs the agent's SubType/Team tags and controller state from current fragment values: ① when SubType.Index ≠ PreviousIndex, removes the old tag, adds the new one, and updates PreviousIndex; ② likewise for Team.index ≠ PreviousIndex (only when the index ≥ 0); ③ Controlling.PreviousControlMode = Controller.ControlMode. Uses direct (non-deferred) tag mutations — call after manual init or activation so tags are correct before the next processor tick; the header comment says "do not call per-frame". PlayerDrivenFlag is not synced here (set by SetAgentControlMode / AddAgentMovementInput / ReactionProcessor).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
AgentHandle | const FEntityHandle& | 目标 agent 句柄(无效则返回;所需 fragment 缺失时按 fail-loud 原则直接访问)。Target agent handle (returns if invalid; missing required fragments are accessed directly per the fail-loud rule). |
Output
无返回值。副作用:可能触发 archetype 迁移(SubType/Team tag 交换)、更新两个 PreviousIndex 与 FAgentControlling.PreviousControlMode。
No return value. Side effects: may trigger archetype migration (SubType/Team tag swap), updates both PreviousIndex fields and FAgentControlling.PreviousControlMode.
选择视觉 Select Visuals
端侧本地 select(网络模式下锁步外,即时反馈):设置本地 Selected/BeingSelect flag,并按 FSelect.SpawnOnSelected / SpawnOnBeingSelect 配置生成本地视觉宿主(经 Host 子系统 SpawnActorHost/SpawnFxHost/SpawnSoundHost)。流程:去重 pass → Phase 1(并行,数量达阈值时)过滤(有效性、Query 匹配、FSelect.bEnable、flag 未设置)并设置 flag、提取位置/旋转 → Phase 2(串行)逐 agent 生成宿主、写入 FBeingSelect 状态数组,网络模式下把非 FNetworkTag 的本地宿主登记进 LocalVisualRegistry(键 = agent UID,镜像 flag 位)。锁步命令路径调用(ExecuteNetCommand)仍生成同步宿主(FNetworkTag),被 HasTag 检查排除在登记表外。
Peer-local select (off-lockstep in networked mode — instant feedback): sets the local Selected/BeingSelect flags and spawns local visual hosts per the FSelect.SpawnOnSelected / SpawnOnBeingSelect config (via the host subsystem's SpawnActorHost/SpawnFxHost/SpawnSoundHost). Flow: dedup pass → Phase 1 (parallel when count reaches the threshold) filters (validity, query match, FSelect.bEnable, flag not already set), sets the flag, extracts position/rotation → Phase 2 (serial) spawns hosts per agent, writes them into the FBeingSelect state arrays, and in networked mode registers non-FNetworkTag local hosts into LocalVisualRegistry (keyed by agent UID, mirroring the flag bits). Lockstep-command-path calls (ExecuteNetCommand) still produce synchronized hosts (FNetworkTag), excluded from the registry by the HasTag check.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Agents | const TArray<FEntityHandle>& | 要选中的 agent 数组(内部去重)。Agents to select (deduplicated internally). |
State | ESelectState | 选中状态:Selected 或 BeingSelect(默认 Selected)。Select state: Selected or BeingSelect (default Selected). |
Query | const FMassBattleQuery& | 附加过滤查询(默认空 = 不过滤)。Additional filter query (default empty = no filtering). |
Output
无返回值。副作用:设置本地 select flag、经 Host 子系统生成宿主实体(本地宿主 UID=-1、无 FNetworkTag)、写入 FBeingSelect 数组、登记 LocalVisualRegistry。
No return value. Side effects: sets local select flags, spawns host entities via the host subsystem (local hosts have UID=-1 and no FNetworkTag), writes the FBeingSelect arrays, and registers LocalVisualRegistry.
端侧本地 deselect(锁步外):清除本地 select flag,并经 FBeingSelect fragment 数组销毁本地视觉宿主——DestroyStateData lambda 对每个仍有效的 Actor/Fx/Sound 宿主置 bShouldDestroy = true(走 HostMonoProcessor 销毁管线)后 Reset() 数组。流程:去重 pass → 并行(阈值)或串行处理(清 flag + 销毁宿主)→ 末尾串行 pass(仅网络模式)把清除位镜像进 LocalVisualRegistry,空登记项移除。锁步路径宿主(FNetworkTag)不在此处理,由各自的确定性命令路径销毁。
Peer-local deselect (off-lockstep): clears the local select flags and destroys the local visual hosts via the FBeingSelect fragment arrays — the DestroyStateData lambda sets bShouldDestroy = true on every still-valid Actor/Fx/Sound host (routing through the HostMonoProcessor destroy pipeline) then Reset()s the arrays. Flow: dedup pass → parallel (threshold) or serial processing (clear flags + destroy hosts) → final serial pass (networked mode only) mirrors the cleared bits into LocalVisualRegistry, removing empty entries. Lockstep-path hosts (FNetworkTag) are untouched here and destroyed via their deterministic command path.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Agents | const TArray<FEntityHandle>& | 要取消选中的 agent 数组(内部去重)。Agents to deselect (deduplicated internally). |
State | ESelectState | 清除范围:BeingSelect / Selected / All(默认 All,两者都清)。Clear scope: BeingSelect / Selected / All (default All, clears both). |
Query | const FMassBattleQuery& | 附加过滤查询(默认空 = 不过滤)。Additional filter query (default empty = no filtering). |
Output
无返回值。副作用:清除本地 select flag、对宿主置 bShouldDestroy(由 HostMonoProcessor 回收)、清空 FBeingSelect 数组、镜像并裁剪 LocalVisualRegistry。
No return value. Side effects: clears local select flags, sets bShouldDestroy on hosts (recycled by HostMonoProcessor), empties the FBeingSelect arrays, and mirrors/prunes LocalVisualRegistry.
把每个本地视觉宿主重挂到最新快照 resync 重建的 agent 上(每次 resync 由 UMassBattleNetworkSubsystem::ProcessDeferredSnapshot 调用一次,在组件 RebindToEntity pass 之后)。流程:逐登记项——agent 已消失则 DestroyEntryHosts 销毁其宿主并移除登记项;否则对三类数据(Actor/Fx/Sound × BeingSelect/Selected/AttachedVisuals)逐一重链:经 IsHostOwnedByUID 判定归属(已销毁/回收/复用的剔除),重指向 FHostHierarchy.AttachmentEntity(仅 ExternalEntity 源)与 config 的 AttachToEntity(FX 的 PairedFxEntity 父级经 FFxVisualizing.ParentEntity 跟随;注释强调 InitialRelativeTransform 是固定偏移,勿重算以免视觉跳变);然后重放本地 select flag(SnapshotStrippedRenderFlagsMask 已从恢复中剥离);最后把 Selected/BeingSelect 宿主数组镜像回 FBeingSelect fragment(重建 agent 的数组为空,写回使 DeselectAgents 的 DestroyStateData 恰好销毁这些宿主;AttachedVisuals 不镜像)。非网络模式下为空操作(登记表恒空)。
Re-attaches every local visual host to the agent rebuilt by the latest snapshot resync (called once per resync from UMassBattleNetworkSubsystem::ProcessDeferredSnapshot, after the component RebindToEntity pass). Flow: per entry — if the agent is gone, DestroyEntryHosts destroys its hosts and the entry is removed; otherwise all three data groups (Actor/Fx/Sound × BeingSelect/Selected/AttachedVisuals) are re-linked: ownership is probed via IsHostOwnedByUID (destroyed/recycled/reused hosts are dropped), FHostHierarchy.AttachmentEntity (ExternalEntity sources only) and the config AttachToEntity are re-pointed (an FX's PairedFxEntity parent follows via FFxVisualizing.ParentEntity; the comment stresses InitialRelativeTransform is a fixed offset — do NOT recompute, to avoid visual snapping); the peer-local select flags are then replayed (stripped from the restore by SnapshotStrippedRenderFlagsMask); finally the Selected/BeingSelect host arrays are mirrored back into the FBeingSelect fragment (the rebuilt agent's arrays are empty; the write-back makes DeselectAgents' DestroyStateData destroy exactly these hosts; AttachedVisuals is NOT mirrored). No-op in non-networked mode (registry stays empty).
Input
无参数。
No parameters.
Output
无返回值。副作用:改写宿主 config 的 AttachToEntity/FHostHierarchy.AttachmentEntity/FFxVisualizing.ParentEntity,重放 agent 的 select flag,写回 FBeingSelect 数组,销毁孤儿宿主并移除登记项。
No return value. Side effects: rewrites host configs' AttachToEntity/FHostHierarchy.AttachmentEntity/FFxVisualizing.ParentEntity, replays the agents' select flags, writes back the FBeingSelect arrays, destroys orphan hosts, and removes entries.
每 tick 清理(由 ExecuteTick 末尾调用):移除 agent 已消失的登记项(先 DestroyEntryHosts 销毁其宿主)与已被销毁/回收/复用的宿主(逐数组经 IsHostOwnedByUID 剔除);空登记项移除。兜底 resync 钩子被跳过的路径(快照 apply 失败)。仅限游戏线程。
Per-tick cleanup (called at the end of ExecuteTick): removes entries whose agent is gone (destroying their hosts via DestroyEntryHosts first) and hosts that were destroyed/recycled/reused (pruned per array via IsHostOwnedByUID); empty entries are removed. Catches the paths where the resync hook was skipped (failed snapshot apply). Game-thread only.
Input
无参数。
No parameters.
Output
无返回值。副作用:销毁孤儿宿主(bShouldDestroy)、从登记表移除失效宿主与空登记项。
No return value. Side effects: destroys orphan hosts (bShouldDestroy), removes dead hosts and empty entries from the registry.
EQS 生成 EQS Spawning
按 EQS 查询结果生成 agent(异步,蓝图 latent 节点):校验失败(子系统/模板/Query/Querier 缺失或 Quantity ≤ 0)时 Branches = Invalid 并返回;否则 LoadAndRegisterAssets 预注册资源,以自增 EQSRequestIDCounter 存入 PendingEQSRequests,经 UEnvQueryManager::RunQuery(AllMatching) 发起查询并绑定 OnEQSQueryFinished;同时为蓝图挂一个空的 FMassPendingLatentAction 使节点保持挂起;查询返回后把请求从 RequestID 键改为 QueryID 键。成功发起后 Branches = Valid。生成本身在 OnEQSQueryFinished 回调中完成。
Spawns agents from EQS query results (async, Blueprint latent node): on validation failure (missing subsystems/template/Query/Querier or Quantity ≤ 0) sets Branches = Invalid and returns; otherwise calls LoadAndRegisterAssets, stores the request in PendingEQSRequests under an incrementing EQSRequestIDCounter, issues the query via UEnvQueryManager::RunQuery(AllMatching) bound to OnEQSQueryFinished, and attaches a no-op FMassPendingLatentAction so the Blueprint node stays pending; after the query returns, the request is re-keyed from the RequestID to the QueryID. On successful issue, Branches = Valid. The actual spawning happens in the OnEQSQueryFinished callback.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | UObject* | 世界上下文,用于取 EQS 管理器。World context, used to fetch the EQS manager. |
Branches | EValidityBranches& | 输出分支:成功发起 = Valid;校验失败 = Invalid。Output branch: Valid on successful issue; Invalid on validation failure. |
BaseTemplate | const FEntityTemplateData& (ref) | 实体模板。Entity template. |
Quantity | const int32 | 目标数量(≤ 0 直接 Invalid)。Target count (≤ 0 → Invalid). |
Team | const int32 | 队伍索引。Team index. |
QueryTemplate | UEnvQuery* | EQS 查询模板。EQS query template. |
Querier | AActor* | 查询发起者。Query requester. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
LatentInfo | FLatentActionInfo | 蓝图 latent 动作信息,用于挂起与移除动作。Blueprint latent action info, used to attach and remove the action. |
Output
无直接返回值(实体经回调生成)。副作用:写入 Branches、登记挂起请求、发起 EQS 查询、挂 latent 动作、预注册资源。
No direct return (entities are spawned via the callback). Side effects: writes Branches, registers a pending request, issues the EQS query, attaches a latent action, pre-registers assets.
按 EQS 查询结果从 DataAsset 生成 agent:DataAsset 无效时 Branches = Invalid 并返回;否则建模板后委托 SpawnAgentsByTemplateEQS(Branches 由后者写入)。
Spawns agents from a DataAsset using EQS query results: an invalid DataAsset sets Branches = Invalid and returns; otherwise it builds the template and delegates to SpawnAgentsByTemplateEQS (which writes Branches).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | UObject* | 世界上下文。World context. |
Branches | EValidityBranches& | 输出分支。Output branch. |
DataAsset | const UMassBattleAgentConfigDataAsset* | agent 配置数据资产;无效 = Invalid 分支。Agent config data asset; invalid → Invalid branch. |
Quantity | const int32 | 目标数量。Target count. |
Team | const int32 | 队伍索引。Team index. |
QueryTemplate | UEnvQuery* | EQS 查询模板。EQS query template. |
Querier | AActor* | 查询发起者。Query requester. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
LatentInfo | FLatentActionInfo | 蓝图 latent 动作信息。Blueprint latent action info. |
Output
无直接返回值。副作用:写入 Branches,其余同 SpawnAgentsByTemplateEQS。
No direct return. Side effects: writes Branches; otherwise identical to SpawnAgentsByTemplateEQS.
控制模式与移动 Control Mode & Movement
读取 agent 的控制模式:实体带 FAgentController 时返回其 ControlMode;否则回退为按 PlayerDrivenFlag 判定(带 = PlayerDriven,否则 AI)。无效句柄返回 AI。
Reads an agent's control mode: returns FAgentController::ControlMode when the fragment exists; otherwise falls back to the PlayerDrivenFlag (set → PlayerDriven, else AI). Invalid handles return AI.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文,经 UMassAPISubsystem::GetPtr 解析。World context, resolved via UMassAPISubsystem::GetPtr. |
Agent | FEntityHandle | 目标 agent 句柄。Target agent handle. |
Output
返回 EAgentControlMode(AI / PlayerDriven);无效句柄或 MA 缺失返回 AI。
Returns EAgentControlMode (AI / PlayerDriven); AI when the handle is invalid or MA is missing.
设置 agent 控制模式。切到 PlayerDriven:写 FAgentController.ControlMode、设置 PlayerDrivenFlag、FMoving.bMoveToLocked = true、bMovingToGoal = true;切回 AI:清 flag、bMoveToLocked = bMovingToGoal = false、清零 PendingInputVector/DesiredVelocity、MoveState = None(让 AI 从干净状态重新开始)。缺 FMoving/FAgentController 或句柄无效时返回。
Sets an agent's control mode. To PlayerDriven: writes FAgentController.ControlMode, sets the PlayerDrivenFlag, FMoving.bMoveToLocked = true, bMovingToGoal = true; back to AI: clears the flag, bMoveToLocked = bMovingToGoal = false, zeroes PendingInputVector/DesiredVelocity, MoveState = None (so AI restarts from a clean state). Returns when FMoving/FAgentController are missing or the handle is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
Agent | FEntityHandle | 目标 agent 句柄。Target agent handle. |
Mode | EAgentControlMode | 目标控制模式(AI / PlayerDriven)。Target control mode (AI / PlayerDriven). |
Output
无返回值。副作用:改写 FAgentController.ControlMode、PlayerDrivenFlag 与 FMoving 多个字段。
No return value. Side effects: mutates FAgentController.ControlMode, the PlayerDrivenFlag, and several FMoving fields.
给 agent 添加移动输入(对应 APawn::Internal_AddMovementInput):bMoveInputIgnored 且非强制时丢弃;否则直接设置 PendingInputVector = WorldDirection × Scale(调用者传入完整合并输入)、bMoveToLocked = bMovingToGoal = true,并把 FAgentController.ControlMode 置为 PlayerDriven、设置 PlayerDrivenFlag。
Adds movement input to an agent (mirrors APawn::Internal_AddMovementInput): discarded when bMoveInputIgnored and not forced; otherwise directly sets PendingInputVector = WorldDirection × Scale (the caller passes the full combined input), bMoveToLocked = bMovingToGoal = true, sets FAgentController.ControlMode to PlayerDriven and the PlayerDrivenFlag.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
Agent | FEntityHandle | 目标 agent 句柄。Target agent handle. |
WorldDirection | FVector | 世界空间输入方向(未归一化也可,乘 Scale 后整体作为待处理向量)。World-space input direction (need not be normalized; multiplied by Scale to form the pending vector). |
Scale | float | 输入缩放。Input scale. |
bForce | bool | true = 即使 bMoveInputIgnored 也应用。true = applied even when bMoveInputIgnored. |
Output
无返回值。副作用:写 FMoving.PendingInputVector、锁定移动目标、切控制模式为 PlayerDriven 并设 PlayerDrivenFlag。
No return value. Side effects: writes FMoving.PendingInputVector, locks the move target, switches control mode to PlayerDriven and sets the PlayerDrivenFlag.
停止一批 agent 的全部移动:逐实体清零 CurrentVelocity/DesiredVelocity,bMovingToGoal = false、MoveState = None、ActiveMoveToTaskID = 0、bMoveToLocked = bMoveToSuspended = false;清除 FNavigating 的 RequestedNavMode 与 PathPoints;清除 AStarMovingTo 与 BPTask_MoveTo 两个 flag。无效句柄跳过。
Stops all movement for a batch of agents: per entity, zeroes CurrentVelocity/DesiredVelocity, sets bMovingToGoal = false, MoveState = None, ActiveMoveToTaskID = 0, bMoveToLocked = bMoveToSuspended = false; clears FNavigating's RequestedNavMode and PathPoints; clears the AStarMovingTo and BPTask_MoveTo flags. Invalid handles are skipped.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | UObject* | 世界上下文。World context. |
Agents | const TArray<FEntityHandle>& | 目标 agent 句柄数组。Target agent handle array. |
Output
无返回值。副作用:改写 FMoving/FNavigating 与两个移动 flag。
No return value. Side effects: mutates FMoving/FNavigating and the two movement flags.
请求一批 agent 停止当前主动移动:对每个有效实体置 FMove.XY.bStopActiveMovement = true(由移动处理器消费该一次性请求)。
Requests a batch of agents to stop their current active movement: sets FMove.XY.bStopActiveMovement = true on each valid entity (a one-shot request consumed by the movement processor).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | UObject* | 世界上下文。World context. |
Agents | const TArray<FEntityHandle>& | 目标 agent 句柄数组。Target agent handle array. |
Output
无返回值。副作用:置 FMove.XY.bStopActiveMovement。
No return value. Side effect: sets FMove.XY.bStopActiveMovement.
切换单个 agent 的行为状态。守卫:句柄/必需 fragment 缺失、Dying/PendingDestroy、bMoveToLocked 且目标非 Idle 时返回 false;目标行为对应的配置 fragment bEnable 为假或为不支持的状态(如 Return——被动反馈,非行为)时降级为 Idle。成功时:写 FBehaving.ActiveBehavior/RequestedBehavior,清除全部行为 flag 与 FAppearingTag,重置 FAppearing/FPatrolling/FAttacking/FReinforcing/FReturning,按目标行为设置对应 flag(Appear 额外设 Dissolve 并加 FAppearingTag;Chase 设 bMovingToGoal = true),最后 FNavigating.TimeLeft = 0。
Switches a single agent's behavior state. Guards: returns false on invalid handle / missing required fragments, Dying/PendingDestroy flags, or bMoveToLocked with a non-Idle target; targets whose config fragment bEnable is false, or unsupported states (e.g. Return — a passive feedback, not a behavior), degrade to Idle. On success: writes FBehaving.ActiveBehavior/RequestedBehavior, clears all behavior flags and FAppearingTag, resets FAppearing/FPatrolling/FAttacking/FReinforcing/FReturning, sets the flag for the target behavior (Appear also sets Dissolve and adds FAppearingTag; Chase sets bMovingToGoal = true), then FNavigating.TimeLeft = 0.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
Agent | const FEntityHandle& | 目标 agent 句柄。Target agent handle. |
TargetBehavior | EBehaviorState | 目标行为状态(Idle/Appear/Sleep/Patrol/Chase/Attack/Reinforce)。Target behavior state (Idle/Appear/Sleep/Patrol/Chase/Attack/Reinforce). |
Output
返回 true = 切换成功;false = 守卫拦截(无效句柄/死亡/移动锁定等)。副作用:改写行为 fragment、flag 与 tag,可能触发 archetype 迁移(FAppearingTag)。
Returns true on success; false when a guard blocks (invalid handle / dying / movement-locked, etc.). Side effects: mutates behavior fragments, flags, and tags; may trigger archetype migration (FAppearingTag).
设置实体的事件接收 Actor:agent(FAgentTag)写 FAgentEvent.EventReceiveSoftActor;projectile(FProjectileTag)写 FProjectileEvent.EventReceiveSoftActor;其它实体类型或无效句柄忽略。
Sets an entity's event receiver actor: agents (FAgentTag) write FAgentEvent.EventReceiveSoftActor; projectiles (FProjectileTag) write FProjectileEvent.EventReceiveSoftActor; other entity types or invalid handles are ignored.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
ReceiverActor | AActor* | 事件接收 Actor。Event receiver actor. |
Output
无返回值。副作用:改写事件 fragment 的 EventReceiveSoftActor。
No return value. Side effect: mutates the event fragment's EventReceiveSoftActor.
设置实体使用的流场:写 FNavigation.FlowFieldToUse 后调用 UMassBattleSubsystem::ResolveAgentRuntimeObjectPtrs 解析运行时指针(同步到 FNavigating.FlowFieldToUsePtr)。
Sets the flow field an entity uses: writes FNavigation.FlowFieldToUse, then calls UMassBattleSubsystem::ResolveAgentRuntimeObjectPtrs to resolve runtime pointers (syncing FNavigating.FlowFieldToUsePtr).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
FlowField | AFlowField* | 要使用的流场。Flow field to use. |
Output
无返回值。副作用:写 FNavigation.FlowFieldToUse 并解析运行时指针。
No return value. Side effects: writes FNavigation.FlowFieldToUse and resolves runtime pointers.
属性设置 Property Setters
设置 agent 角速度:写 FMoving.CurrentAngularVelocity。无效句柄/缺 fragment 忽略。
Sets an agent's angular velocity: writes FMoving.CurrentAngularVelocity. Invalid handles / missing fragments are ignored.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
NewAngularVelocity | float | 新的角速度值(单位:度/秒,与 FMoving 约定一致)。New angular velocity (unit: degrees/second, per the FMoving convention). |
Output
无返回值。副作用:改写 FMoving.CurrentAngularVelocity。
No return value. Side effect: mutates FMoving.CurrentAngularVelocity.
设置 agent 线速度:写 FMoving.CurrentVelocity(FVector3f)。无效句柄/缺 fragment 忽略。
Sets an agent's linear velocity: writes FMoving.CurrentVelocity (FVector3f). Invalid handles / missing fragments are ignored.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
NewVelocity | FVector | 新的速度向量(世界空间,单位:u/秒)。New velocity vector (world space, u/s). |
Output
无返回值。副作用:改写 FMoving.CurrentVelocity。
No return value. Side effect: mutates FMoving.CurrentVelocity.
设置 agent 缩放:写 FScaling.Scale。无效句柄/缺 fragment 忽略。
Sets an agent's scale: writes FScaling.Scale. Invalid handles / missing fragments are ignored.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
NewScale | float | 新的统一缩放倍率。New uniform scale multiplier. |
Output
无返回值。副作用:改写 FScaling.Scale。
No return value. Side effect: mutates FScaling.Scale.
设置 agent 旋转:写 FRotating.Rotation、RotationQuat(由 NewRotation.Quaternion() 转换)与 Direction(四元数前向)。无效句柄/缺 fragment 忽略。
Sets an agent's rotation: writes FRotating.Rotation, RotationQuat (from NewRotation.Quaternion()) and Direction (quaternion forward). Invalid handles / missing fragments are ignored.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
NewRotation | FRotator | 新的旋转(欧拉角)。New rotation (Euler angles). |
Output
无返回值。副作用:改写 FRotating 三个字段。
No return value. Side effect: mutates the three FRotating fields.
设置 agent 位置:写 FLocating.Location。无效句柄/缺 fragment 忽略。
Sets an agent's location: writes FLocating.Location. Invalid handles / missing fragments are ignored.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
NewLocation | FVector | 新的世界坐标位置。New world-space location. |
Output
无返回值。副作用:改写 FLocating.Location。
No return value. Side effect: mutates FLocating.Location.
属性获取 Property Getters
读取 agent 线速度(FMoving.CurrentVelocity)。无效句柄/缺 fragment 返回 FVector::ZeroVector。
Reads an agent's linear velocity (FMoving.CurrentVelocity). Returns FVector::ZeroVector for invalid handles / missing fragments.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Output
返回当前速度向量;失败时零向量。无副作用。
Returns the current velocity vector; zero vector on failure. No side effects.
读取 agent 右向量(FRotating.RotationQuat.GetRightVector())。失败返回 FVector::RightVector。
Reads an agent's right vector (FRotating.RotationQuat.GetRightVector()). Returns FVector::RightVector on failure.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Output
返回右向量;失败时默认右向量。无副作用。
Returns the right vector; default right vector on failure. No side effects.
读取 agent 上向量(FRotating.RotationQuat.GetUpVector())。失败返回 FVector::UpVector。
Reads an agent's up vector (FRotating.RotationQuat.GetUpVector()). Returns FVector::UpVector on failure.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Output
返回上向量;失败时默认上向量。无副作用。
Returns the up vector; default up vector on failure. No side effects.
读取 agent 前向向量(FRotating.Direction)。失败返回 FVector::ForwardVector。
Reads an agent's forward vector (FRotating.Direction). Returns FVector::ForwardVector on failure.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Output
返回前向向量;失败时默认前向向量。无副作用。
Returns the forward vector; default forward vector on failure. No side effects.
读取 agent 变换:由 FRotating.RotationQuat、FLocating.Location、FScaling.Scale 组装 FTransform。三个 fragment 任一缺失或句柄无效返回 FTransform::Identity。
Reads an agent's transform: assembled from FRotating.RotationQuat, FLocating.Location, and FScaling.Scale. Returns FTransform::Identity when any fragment is missing or the handle is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Output
返回组合变换;失败时恒等变换。无副作用。
Returns the composed transform; identity on failure. No side effects.
读取 agent 缩放三件套:先全部初始化为默认值(1.f / OneVector / OneVector),再写 FScaling.Scale 与 JiggleMultiplier;渲染缩放取自 FVisualize.Transform 的 Scale3D(非 agent 实体无 FVisualize 时回退为均匀 FVector(Scale))。
Reads an agent's scale triple: initializes all outputs to defaults first (1.f / OneVector / OneVector), then writes FScaling.Scale and JiggleMultiplier; the render scale comes from FVisualize.Transform's Scale3D (falling back to uniform FVector(Scale) for non-agent entities without FVisualize).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Scale | float& (out) | 逻辑缩放。Logical scale. |
RenderScale | FVector& (out) | 渲染缩放(含 FVisualize 变换缩放)。Render scale (including the FVisualize transform scale). |
JiggleMultiplier | FVector& (out) | 抖动倍率。Jiggle multiplier. |
Output
无返回值(结果写入 out 参数)。失败时保持默认值。无副作用。
No return value (results go to the out params). Defaults are kept on failure. No side effects.
读取 agent 旋转三件套:先全部初始化为默认值(ZeroRotator / Identity / ForwardVector),再写 FRotating.Rotation、RotationQuat 与 Direction。
Reads an agent's rotation triple: initializes all outputs to defaults first (ZeroRotator / Identity / ForwardVector), then writes FRotating.Rotation, RotationQuat, and Direction.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Rotation | FRotator& (out) | 欧拉角旋转。Euler rotation. |
RotationQuat | FQuat& (out) | 四元数旋转。Quaternion rotation. |
Direction | FVector& (out) | 朝向向量。Direction vector. |
Output
无返回值(结果写入 out 参数)。失败时保持默认值。无副作用。
No return value (results go to the out params). Defaults are kept on failure. No side effects.
计算一批 agent 的平均位置:累加有效实体的 FLocating.Location 后除以有效数量(double 除法)。空数组、MA 缺失或全部无效返回 FVector::ZeroVector。
Computes the average location of a batch of agents: sums the FLocating.Location of valid entities and divides by the valid count (double division). Returns FVector::ZeroVector for an empty array, missing MA, or all-invalid input.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandles | const TArray<FEntityHandle>& | 目标实体句柄数组。Target entity handle array. |
Output
返回平均位置;边界情况返回零向量。无副作用。
Returns the average location; zero vector on edge cases. No side effects.
读取 agent 位置三件套:先全部初始化为零,再写 FLocating.Location、PreLocation 与 InitialLocation。
Reads an agent's location triple: initializes all outputs to zero first, then writes FLocating.Location, PreLocation, and InitialLocation.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体句柄。Target entity handle. |
Location | FVector& (out) | 当前位置。Current location. |
PreviousLocation | FVector& (out) | 上一帧位置。Previous-frame location. |
InitialLocation | FVector& (out) | 出生位置。Spawn location. |
Output
无返回值(结果写入 out 参数)。失败时保持零向量。无副作用。
No return value (results go to the out params). Zero vectors are kept on failure. No side effects.
宿主生成与附着 Host Spawning & Attachment
生成战利品宿主:组装 FLootConfig_Final(bEnable=true、LootConfigDataAsset、Multipliers.Ballistic、SpawnTransform、OwnerEntity=Spawner、FromPoint=生成点、Delay=0)后经 UMassBattleHostSubsystem::SpawnLootHost 生成。网络模式下锁步外调用被 [RULE7] 拦截(打 Error 并返回);确定性命令路径(ExecuteNetCommand)放行。DataAsset 或 MB 缺失时返回。
Spawns a loot host: assembles an FLootConfig_Final (bEnable=true, LootConfigDataAsset, Multipliers.Ballistic, SpawnTransform, OwnerEntity=Spawner, FromPoint=spawn point, Delay=0) and spawns via UMassBattleHostSubsystem::SpawnLootHost. Off-lockstep calls in networked mode are blocked by [RULE7] (logs an Error and returns); deterministic command-path calls (ExecuteNetCommand) pass. Returns when the DataAsset or MB is missing.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
LootConfigDataAsset | UMassBattleLootConfigDataAsset* | 战利品配置数据资产(无效则返回)。Loot config data asset (returns when invalid). |
SpawnTransform | const FTransform& | 生成变换(位置兼作 FromPoint)。Spawn transform (location doubles as FromPoint). |
Multipliers | const FLootMultipliers_Ballistic& | 弹道战利品倍率。Ballistic loot multipliers. |
Spawner | const FEntityHandle& | 生成者实体(写入 OwnerEntity)。Spawning entity (written to OwnerEntity). |
Output
无返回值。副作用:经 Host 子系统生成战利品宿主实体(锁步外网络模式被拦截)。
No return value. Side effect: spawns a loot host entity via the host subsystem (blocked off-lockstep in networked mode).
在世界位置生成合批 FX:校验 FxConfig.bEnable 与至少一个资源(SoftNiagara/SoftCascade/SubType_Index)后,组装 FFxConfig_Final,SpawnTransform = LocalOffsetToWorld(世界位置 + 本地偏移),InitialRelativeTransform 相对附着实体(有效时)或基础生成变换计算,经 SpawnFxHost 生成。自动分流:锁步命令窗口 → 同步版;锁步外(BP 直调)→ 纯表现版(FX/Sound 永不破坏确定性)。网络模式下,附着且无 FNetworkTag 的本地宿主登记进 LocalVisualRegistry(键 = 父实体 UID,AttachedVisuals.FxHostEntities);不附着的即抛 FX 无需登记。
Spawns a batched FX at a world location: after validating FxConfig.bEnable and at least one asset (SoftNiagara/SoftCascade/SubType_Index), it assembles an FFxConfig_Final, computes SpawnTransform = LocalOffsetToWorld (world location + local offset), computes InitialRelativeTransform relative to the attach entity (when valid) or the base spawn transform, and spawns via SpawnFxHost. Auto-split: lockstep command window → synchronized version; off-lockstep (direct BP call) → local-only version (FX/Sound never corrupt determinism). In networked mode, attached local hosts without FNetworkTag are registered into LocalVisualRegistry (keyed by the parent entity's UID, AttachedVisuals.FxHostEntities); unattached one-shot FX needs no registration.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
FxConfig | const FFxConfig& | FX 配置(资源、本地偏移、合批参数等)。FX config (assets, local offset, batching params, etc.). |
SpawnLocation | const FVector& | 世界空间生成位置。World-space spawn location. |
SpawnRotation | const FRotator& | 生成旋转(基础变换)。Spawn rotation (base transform). |
OwnerEntity | const FEntityHandle& | 所有者实体。Owner entity. |
AttachToEntity | const FEntityHandle& | 附着目标实体(无效 = 即抛 FX)。Attach target entity (invalid = one-shot FX). |
Output
无返回值。副作用:经 SpawnFxHost 生成 FX 宿主实体;附着本地宿主登记 LocalVisualRegistry。
No return value. Side effects: spawns an FX host entity via SpawnFxHost; attached local hosts are registered in LocalVisualRegistry.
播放动画 montage(模拟侧驱动):AnimIndex == INVALID_ANIM_INDEX(255) 且实体带 FDeterminism 时,从 FAnimShared.AnimData.OtherAnimData 用 FDeterminism.RandomStream 随机选槽——模拟侧消耗 RNG,进入 SYNC(FAnimating) 快照,绝不落在渲染阶段(自 RenderProcessor 迁移);随后写 SelectedMontageAnimIndex(Clamp 0..255)、MontagePlayRate、bMontageLooping,置 AnimState = Montage、bUpdateAnimState = true。
Plays an animation montage (sim-side driven): when AnimIndex == INVALID_ANIM_INDEX (255) and the entity has FDeterminism, a slot is randomly picked from FAnimShared.AnimData.OtherAnimData using FDeterminism.RandomStream — the RNG draw happens on the sim side so it enters the SYNC(FAnimating) snapshot and never runs in the render pass (migrated from RenderProcessor); then it writes SelectedMontageAnimIndex (Clamped 0..255), MontagePlayRate, bMontageLooping, sets AnimState = Montage, bUpdateAnimState = true.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
EntityHandle | const FEntityHandle& | 目标实体(须带 FAnimating)。Target entity (must have FAnimating). |
AnimIndex | int32 | 动画槽索引;255(INVALID) = 随机选槽。Animation slot index; 255 (INVALID) = random slot. |
PlayRate | float | 播放速率。Play rate. |
bLooping | bool | 是否循环。Whether to loop. |
Output
无返回值。副作用:改写 FAnimating 五个字段;随机选槽时消耗 FDeterminism.RandomStream。
No return value. Side effects: mutates five FAnimating fields; consumes FDeterminism.RandomStream when picking a random slot.
把 Cascade 粒子系统附着到实体:组装 FFxConfig_Final(bAttached=true、CascadeAsset、AttachToEntity、InitialRelativeTransform=相对变换)后经 SpawnFxHost 生成。自动分流:锁步窗口 → 同步版;锁步外 → 纯表现版。网络模式下附着本地宿主登记 LocalVisualRegistry(同 SpawnBatchedFx 机制)。资源无效返回。
Attaches a Cascade particle system to an entity: assembles an FFxConfig_Final (bAttached=true, CascadeAsset, AttachToEntity, InitialRelativeTransform=relative transform) and spawns via SpawnFxHost. Auto-split: lockstep window → synchronized version; off-lockstep → local-only version. In networked mode, attached local hosts are registered in LocalVisualRegistry (same mechanism as SpawnBatchedFx). Returns when the asset is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
CascadeAsset | UParticleSystem* | Cascade 粒子系统资产(无效返回)。Cascade particle system asset (returns when invalid). |
AttachToEntity | const FEntityHandle& | 附着目标实体。Attach target entity. |
RelativeTransform | const FTransform& | 相对父实体的偏移变换。Transform relative to the parent entity. |
Config | const FFxConfig& | FX 配置(其余参数)。FX config (remaining parameters). |
Output
无返回值。副作用:生成附着 FX 宿主并登记本地视觉(网络模式)。
No return value. Side effects: spawns an attached FX host and registers local visuals (networked mode).
把 Niagara 系统附着到实体:与 AttachCascadeToAgent 完全同构,仅资源类型为 UNiagaraSystem(写 FFxConfig_Final.NiagaraAsset)。
Attaches a Niagara system to an entity: fully isomorphic to AttachCascadeToAgent, except the asset type is UNiagaraSystem (written to FFxConfig_Final.NiagaraAsset).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
NiagaraAsset | UNiagaraSystem* | Niagara 系统资产(无效返回)。Niagara system asset (returns when invalid). |
AttachToEntity | const FEntityHandle& | 附着目标实体。Attach target entity. |
RelativeTransform | const FTransform& | 相对父实体的偏移变换。Transform relative to the parent entity. |
Config | const FFxConfig& | FX 配置。FX config. |
Output
无返回值。副作用:生成附着 FX 宿主并登记本地视觉(网络模式)。
No return value. Side effects: spawns an attached FX host and registers local visuals (networked mode).
把现有 Actor 作为宿主附着到实体:组装 FActorSpawnConfig_Final(bAttached=true、bSpawned=true——把现有 Actor 视为已生成、SpawnedActor=ActorToAttach、AttachToEntity、InitialRelativeTransform)后经 SpawnActorHost 生成。锁步外生成天然安全(四元分流分配 UID=-1、跳过 FNetworkTag),网络模式下附着本地宿主登记 LocalVisualRegistry。资源无效返回。
Attaches an existing actor to an entity as a host: assembles an FActorSpawnConfig_Final (bAttached=true, bSpawned=true — treating the existing actor as already spawned, SpawnedActor=ActorToAttach, AttachToEntity, InitialRelativeTransform) and spawns via SpawnActorHost. Off-lockstep spawning is safe by design (the four-way split allocates UID=-1 and skips FNetworkTag); in networked mode, attached local hosts are registered in LocalVisualRegistry. Returns when the actor is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
ActorToAttach | AActor* | 要附着的 Actor(无效返回)。Actor to attach (returns when invalid). |
AttachToEntity | const FEntityHandle& | 附着目标实体。Attach target entity. |
RelativeTransform | const FTransform& | 相对父实体的偏移变换。Transform relative to the parent entity. |
Config | const FActorSpawnConfig& | Actor 宿主配置(其余参数)。Actor host config (remaining parameters). |
Output
无返回值。副作用:生成附着 Actor 宿主并登记本地视觉(网络模式)。
No return value. Side effects: spawns an attached actor host and registers local visuals (networked mode).
把 agent 实体作为宿主附着到另一实体:组装 FAgentHostConfig_Final(bAttached=true、Transform=相对变换、AgentToAttach、AttachToEntity)后经 SpawnAgentHost 生成。[RULE7 保留]——agent host 是模拟实体(折叠进逐实体 hash),挂接关系是锁步状态,网络模式下锁步外调用被拦截(打 Error 并返回);仅限锁步命令路径(ExecuteNetCommand)。与纯视觉的 FX/actor/sound 宿主形成对比(后者有安全的本地路径)。
Attaches an agent entity to another entity as a host: assembles an FAgentHostConfig_Final (bAttached=true, Transform=relative transform, AgentToAttach, AttachToEntity) and spawns via SpawnAgentHost. [RULE7 retained] — agent hosts are simulation entities (folded into the per-entity hash), so the attach relationship is lockstep state; off-lockstep calls in networked mode are blocked (logs an Error and returns); lockstep command path only (ExecuteNetCommand). In contrast to purely-visual FX/actor/sound hosts (which have a safe local-only path).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文。World context. |
AgentToAttach | const FEntityHandle& | 作为宿主挂接的 agent。Agent attached as the host. |
AttachToEntity | const FEntityHandle& | 附着目标实体。Attach target entity. |
RelativeTransform | const FTransform& | 相对父实体的偏移变换。Transform relative to the parent entity. |
Config | const FAgentHostConfig& | agent 宿主配置(其余参数)。Agent host config (remaining parameters). |
Output
无返回值。副作用:经 SpawnAgentHost 生成 agent 宿主实体;网络模式下锁步外被拦截。
No return value. Side effects: spawns an agent host entity via SpawnAgentHost; blocked off-lockstep in networked mode.
私有方法 Private Methods
全部 public agent 生成 API(矩形/圆形/EQS/deferred)的唯一汇聚点。入口守卫:网络模式下锁步外直接打 [RULE7] Error 并返回空(命令路径外的 BP/C++ 调用会在单端消耗全局 UID);模板无效/为空或位置列表为空返回空。bDeferred=true 时在 DeferredSpawnLock 下构造 FDeferredAgentSpawnRequest(含从模板 FMove 读取的 GroundTraceChannel、规范化高度范围、Substeps 钳制、bFirstTickPending)入队后返回空。非延迟路径三阶段:Phase 1 串行预计算——逐 agent 分配 UID(PreAssignedUID >= 0 时复用,否则 AllocNextUID)、用子系统 RandomStream 串行采样四组随机乘数、以 UID 派生确定性局部流,计算出生点(飞行高度或胶囊地面偏移)、出生旋转(FacePlayer 取玩家 0 / CustomRotation)、地面倾斜(FlowField 多点采样或射线多点采样,俯仰/翻滚钳制,TiltMode 区分 OnlyCollider/OnlyMesh/ColliderAndMesh)、初速度(注入 CurrentVelocity,不写 LaunchVelSum——避免触发 Launching 状态 3 秒冻结)、动画槽与随机起始帧;Phase 2 MA.BuildEntities 批量建实体;Phase 3 MBParallelFor(BackgroundPriority)并行填 fragment(确定性种子、位置/旋转/移动/巡逻原点/动画/表示/OnBirth 行为解析——flag 与 ActiveBehavior 必须同步/乘数应用),随后串行注册 UID 映射、为 Appear 实体加 FAppearingTag、ResolveAgentRuntimeObjectPtrs。
The single funnel for all public agent-spawn APIs (rectangular/circular/EQS/deferred). Entry guards: in networked mode, off-lockstep calls log a [RULE7] Error and return empty (BP/C++ calls outside the command path would consume global UIDs on one peer only); invalid/empty templates or empty location lists return empty. With bDeferred=true, an FDeferredAgentSpawnRequest is constructed under DeferredSpawnLock (GroundTraceChannel read from the template's FMove, normalized height range, clamped Substeps, bFirstTickPending) and enqueued, returning empty. The non-deferred path runs three phases: Phase 1 serial pre-compute — per agent, allocates a UID (reused when PreAssignedUID >= 0, else AllocNextUID), samples the four random multiplier ranges serially from the subsystem RandomStream, derives a deterministic local stream from the UID, and computes the spawn point (fly height or capsule ground offset), spawn rotation (FacePlayer toward player 0 / CustomRotation), ground tilt (FlowField multi-point sampling or raycast multi-point sampling, clamped pitch/roll, TiltMode distinguishing OnlyCollider/OnlyMesh/ColliderAndMesh), initial velocity (injected into CurrentVelocity, NOT LaunchVelSum — avoiding the Launching state's 3-second freeze), and animation slots with random start frames; Phase 2 batch-creates entities via MA.BuildEntities; Phase 3 fills fragments in parallel via MBParallelFor (BackgroundPriority) — deterministic seed, location/rotation/movement/patrol origin/animation/representation/OnBirth behavior resolution (flag and ActiveBehavior must stay in sync) /multiplier application — followed by serial UID registration, FAppearingTag for Appear entities, and ResolveAgentRuntimeObjectPtrs.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
BaseTemplate | const FEntityTemplateData& | 实体模板。Entity template. |
Quantity | int32 | 目标数量(实际生成数 = min(Quantity, Locations.Num()))。Target quantity (actual spawn count = min(Quantity, Locations.Num())). |
Locations | const TArray<FVector>& | 生成位置列表。Spawn location list. |
Team | int32 | 队伍索引。Team index. |
LaunchVelocity | const FVector2D& | 出生初速度。Spawn initial velocity. |
InitialRotation | EInitialRotation | 出生朝向策略。Spawn facing policy. |
CustomRotation | const FRotator& | 自定义出生旋转。Custom spawn rotation. |
Multipliers | const FSpawnerMult& | 每实体随机乘数范围。Per-agent random multiplier ranges. |
bDeferred | bool | true = 入队延迟处理;false = 立即三阶段生成。true = enqueue for deferred processing; false = immediate three-phase spawn. |
bAutoActivated | bool | 生成后是否设置 Activated flag。Whether to set the Activated flag on spawn. |
Substeps | int32 | 子步数(仅 bDeferred 生效)。Substep count (only effective with bDeferred). |
OnFinished | const FOnAgentSpawnFinished& | 完成回调(仅 bDeferred)。Completion callback (only with bDeferred). |
GroundTraceHeightRange | const FVector2D& | 落地检测高度范围(默认 (1000, -1000))。Ground trace height range (default (1000, -1000)). |
GroundObjectTypes | const TArray<TEnumAsByte<EObjectTypeQuery>>& | 地面对象类型。Ground object types. |
ObstacleObjectTypes | const TArray<TEnumAsByte<EObjectTypeQuery>>& | 障碍对象类型。Obstacle object types. |
MaxSlopeCosine | float | 最大坡度余弦阈值(默认 0 = 不启用)。Max slope cosine threshold (default 0 = disabled). |
PreAssignedUID | int32 | 预分配 UID(默认 -1 = 逐 agent 分配)。Pre-assigned UID (default -1 = per-agent allocation). |
Output
返回实际生成实体的句柄数组;延迟路径与守卫拦截路径返回空数组。副作用:分配全局 UID、构建实体、并行填 fragment、注册 UID 映射、消耗 RandomStream。
Returns the handles of the actually spawned entities; empty for the deferred path and guard-blocked paths. Side effects: allocates global UIDs, builds entities, fills fragments in parallel, registers UID mappings, consumes RandomStream.
延迟生成请求的每 tick 批量处理(ExecuteTick 第一步调用)。流程:空队列快速返回(先于锁步守卫,避免网络模式空队列刷 Error)→ 锁步外守卫([RULE7] 拦截并打 Error)→ 加锁把请求 MoveTemp 到局部数组 → 逐请求计算本 tick 生成数(bFirstTickPending 置 false 跳过本 tick;Substeps > 0 时按剩余 tick 数向上取整均分;目标达成或位置耗尽则本 tick 为 0;全部为 0 时未完成请求重新入队并返回)→ 分配连续 UID 块、构建共享模板与碰撞查询参数 → Phase 1a 串行采样随机乘数(子系统 RandomStream,保证跨请求/索引确定性)→ Phase 1 并行(位置验证——障碍/坡度/落地,出生点/旋转/倾斜/初速度/动画计算)→ Phase 2 按请求批量 BuildEntities → Phase 3 并行填 fragment → 解析运行时指针、注册 UID 映射、加 FAppearingTag → 按请求累计有效句柄、更新进度、完成(达量或耗尽)则触发 OnFinished,未完成请求置顶重新入队。
Per-tick batch processing of deferred spawn requests (the first step of ExecuteTick). Flow: fast-exit on an empty queue (before the off-lockstep guard, so networked mode with an empty queue doesn't spam Errors) → off-lockstep guard ([RULE7] blocks with an Error) → requests are MoveTemp'd into a local array under lock → per request, the tick's spawn count is computed (bFirstTickPending clears and skips this tick; Substeps > 0 distributes evenly by remaining ticks with ceiling division; zero when the target is reached or locations are exhausted; if all are zero, unfinished requests are re-enqueued and the function returns) → a contiguous UID block is allocated, shared templates and collision query params are built → Phase 1a serially samples the random multipliers (subsystem RandomStream, deterministic across requests and indices) → Phase 1 in parallel (location validation — obstacle/slope/ground, plus spawn point/rotation/tilt/initial velocity/animation computation) → Phase 2 batch-creates entities per request via BuildEntities → Phase 3 fills fragments in parallel → runtime pointers resolve, UID mappings register, FAppearingTag is added → valid handles accumulate per request, progress updates, completed requests (target reached or exhausted) fire OnFinished, and unfinished requests are re-enqueued at the front.
Input
无参数(请求来自 DeferredSpawnRequests)。
No parameters (requests come from DeferredSpawnRequests).
Output
无返回值。副作用:消费/重排延迟请求队列、分配全局 UID、构建实体、注册映射、触发完成委托。
No return value. Side effects: consumes/reorders the deferred request queue, allocates global UIDs, builds entities, registers mappings, fires completion delegates.
EQS 查询完成回调:按 Result->QueryID 从 PendingEQSRequests 取出请求并移除;移除对应的 latent 动作(FMassPendingLatentAction);GetAllAsLocations 取位置列表,非空则经 SpawnAgentsAtLocations_Internal(非延迟、bAutoActivated=true、无委托)生成,空则打 Warning。
EQS query completion callback: looks up the request in PendingEQSRequests by Result->QueryID and removes it; removes the corresponding latent action (FMassPendingLatentAction); fetches the location list via GetAllAsLocations and, when non-empty, spawns through SpawnAgentsAtLocations_Internal (non-deferred, bAutoActivated=true, no delegate); logs a Warning when no locations are yielded.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Result | TSharedPtr<FEnvQueryResult> | EQS 查询结果(无效或无对应请求时直接返回)。EQS query result (returns immediately when invalid or unmatched). |
Output
无返回值。副作用:消费挂起请求、移除 latent 动作、生成 agent 实体。
No return value. Side effects: consumes the pending request, removes the latent action, spawns agent entities.
预注册模板可达的全部资源(热循环避免 LoadSynchronous):经 MB.RegisterSpawnContentAssets 遍历 Appear/Hit/Death 的事件内容(SpawActor + SpawnFx + PlaySound),经 RegisterSpawnContentAssetsWithProjectile 处理 Attack(含 SpawnProjectile,触发子资源级联注册链),最后 InitializeAgentTemplateRuntimeObjectPtrs 初始化运行时对象指针。原仅供 EQS 路径调用,后推广到全部生成路径(源码注释)。
Pre-registers all assets reachable from the template (so the hot loop never hits LoadSynchronous): walks the event-content structs Appear/Hit/Death via MB.RegisterSpawnContentAssets (SpawnActor + SpawnFx + PlaySound), processes Attack (with SpawnProjectile) via RegisterSpawnContentAssetsWithProjectile (triggering the cascade-chain asset registration), and finally calls InitializeAgentTemplateRuntimeObjectPtrs. Originally only called from the EQS path; extended to all spawn paths (source comment).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
BaseTemplatePtr | FMassEntityTemplateData* | 实体模板指针(null 时直接返回);资源注册会就地改写其 Config fragment。Entity template pointer (returns when null); asset registration mutates its Config fragments in place. |
Output
无返回值。副作用:向全局资源注册表登记可达资产、改写模板 Config 的硬指针字段。
No return value. Side effects: registers reachable assets into the global asset registry, fills hard-pointer fields on the template's Configs.
用确定性流计算动画随机起始帧:AnimLength > 0 时在 [TimeOffset.X, TimeOffset.Y] 区间采样随机时间,乘 SampleRate 后对动画长度取模,返回 StartFrame + 偏移;长度无效时直接返回 StartFrame。
Computes a random animation start frame with a deterministic stream: when AnimLength > 0, samples a random time in [TimeOffset.X, TimeOffset.Y], multiplies by SampleRate, wraps by the animation length, and returns StartFrame + offset; returns StartFrame when the length is invalid.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
StartFrame | float | 动画起始帧。Animation start frame. |
EndFrame | float | 动画结束帧。Animation end frame. |
SampleRate | int32 | 采样率(帧/秒)。Sample rate (frames/second). |
Stream | FRandomStream& | 确定性随机流(被消耗)。Deterministic random stream (consumed). |
TimeOffset | FVector2D | 随机时间偏移范围(秒)。Random time offset range (seconds). |
Output
返回随机起始帧;边界情况返回 StartFrame。副作用:消耗传入随机流。
Returns the random start frame; StartFrame on edge cases. Side effect: consumes the passed random stream.
在 Actor 上找第一个未绑定(Handle.Index == 0)的 UMassBattleAgentComponent;全部已绑定或 Actor 无效返回 nullptr。支持多组件 Actor。
Finds the first unbound (Handle.Index == 0) UMassBattleAgentComponent on the actor; returns nullptr when all are bound or the actor is invalid. Supports multi-component actors.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Actor | AActor* | 目标 Actor。Target actor. |
Output
返回第一个未绑定组件;无可用组件或 Actor 无效时返回 nullptr。
Returns the first unbound component; nullptr when none is available or the actor is invalid.
统计 Actor 上当前绑定到实体的组件数(Handle.Index != 0 即视为已绑定)。Actor 无效返回 0。
Counts the actor's components currently bound to entities (Handle.Index != 0 counts as bound). Returns 0 for an invalid actor.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Actor | AActor* | 目标 Actor。Target actor. |
Output
返回已绑定组件数。
Returns the number of bound components.
判定 Actor 是否可整体回池:GetActiveComponentCount == 0(无任何活动组件绑定)。供回收队列决定「全部组件解绑才回池,否则保持可见」。
Determines whether the actor can be returned to the pool: GetActiveComponentCount == 0 (no active component bindings). Used by the recycle queue to decide "return to pool only when all components are unbound; otherwise keep visible".
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Actor | AActor* | 目标 Actor。Target actor. |
Output
返回是否可回池(无活动绑定)。
Returns whether the actor is recyclable (no active bindings).
归属判定:宿主 config 的 AttachToEntity 是否仍指向 UID == AgentUID 的实体。区分「仍是本 agent 的宿主」与「已回池被他方复用」(复用的句柄仍然有效,仅 IsValid 不足以判定归属)。带 FNetworkTag 的宿主(快照托管)直接返回 false;从 FFxConfig_Final / FActorSpawnConfig_Final / FSoundConfig_Final 探测归属实体(按序),最终 MB->FindUIDByEntity(Owner) == AgentUID。
Ownership probe: whether the host config's AttachToEntity still points at an entity whose UID == AgentUID. Distinguishes "still this agent's host" from "pool-recycled and reused by someone else" (recycled handles stay valid, so IsValid alone is NOT a sufficient ownership test). Hosts with FNetworkTag (snapshot-managed) return false immediately; the owning entity is probed from FFxConfig_Final / FActorSpawnConfig_Final / FSoundConfig_Final (in order), concluding with MB->FindUIDByEntity(Owner) == AgentUID.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Host | const FMassEntityHandle& | 待判定宿主实体。Host entity to probe. |
AgentUID | int32 | 期望的父实体 UID。Expected parent entity UID. |
Output
返回宿主是否仍归该 UID 实体所有。无副作用。
Returns whether the host is still owned by the UID's entity. No side effects.
销毁登记项下所有仍有效且仍归其所有的宿主并重置登记项:对 BeingSelectData / SelectedData / AttachedVisuals 三组的 Actor/Fx/Sound 数组逐一置 bShouldDestroy = true(走 HostMonoProcessor 既有销毁管线——UObject 释放 → 池回收,绝不用 DestroyEntity 绕过),最后 Entry.Reset()。
Destroys all still-valid hosts owned by the entry and resets it: for each of the Actor/Fx/Sound arrays in BeingSelectData / SelectedData / AttachedVisuals, sets bShouldDestroy = true (routing through HostMonoProcessor's existing destroy pipeline — UObject release → pool recycle; never bypass with DestroyEntity), then Entry.Reset().
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Entry | FLocalVisualEntry& | 要清理的登记项(会被重置)。Entry to clean (gets reset). |
Output
无返回值。副作用:对宿主置 bShouldDestroy(由 HostMonoProcessor 回收)、重置登记项。
No return value. Side effects: sets bShouldDestroy on hosts (recycled by HostMonoProcessor) and resets the entry.
成员变量 Members
子系统级确定性随机流:Initialize 时以固定种子 0x5EEDBEEF 初始化(保证所有客户端默认一致);用于生成点洗牌、随机 XY 偏移、每实体随机乘数(生命/移速/伤害/缩放)等。所有消费必须串行(并行阶段只读或经 UID 派生局部流),以保证锁步确定性。BP 可重设种子。
Subsystem-level deterministic random stream: seeded with the fixed constant 0x5EEDBEEF in Initialize (identical across all clients by default); used for spawn-point shuffling, random XY offsets, and per-agent random multipliers (health / move speed / damage / scale). All consumption must be serial (parallel phases only read or use UID-derived local streams) to keep lockstep determinism. Re-seedable from BP.
公开缓存:三个子系统 getter 首次访问时记录当前世界。Deinitialize 时清空。
Public cache: records the current world on first access by the three subsystem getters. Cleared in Deinitialize.
公开缓存:UMassAPISubsystem 惰性指针(GetMassAPISubsystem 填充)。
Public cache: lazily-resolved UMassAPISubsystem pointer (filled by GetMassAPISubsystem).
公开缓存:UMassBattleSubsystem 惰性指针(全局 UID 游标/确定性开关/池事件队列的宿主)。
Public cache: lazily-resolved UMassBattleSubsystem pointer (home of the global UID cursor / determinism switch / pool event queue).
公开缓存:UMassBattleHashGridSubsystem 惰性指针;不在 Initialize 预热,首次使用填充。
Public cache: lazily-resolved UMassBattleHashGridSubsystem pointer; not warmed in Initialize, filled on first use.
主 Actor 池,按类分组。GetActorFromPool 弹出、ReturnActorToPool 追加。头文件注「WIP:Shrink」——尚未实现收缩。
The main actor pool, keyed by class. GetActorFromPool pops, ReturnActorToPool appends. Header comment "WIP:Shrink" — no shrinking implemented yet.
线程安全(Particle→Actor 转换)绑定请求队列:Actor 绑定路径入队,ExecuteTick 排空(确定性排序后逐个绑定)。
Thread-safe binding request queue (Particle→Actor conversion): enqueued by the actor binding path, drained by ExecuteTick (deterministically sorted before binding).
线程安全(Actor→Particle 转换)回收请求队列:由 ExecuteTick 排空(确定性排序后逐个回收)。
Thread-safe recycle request queue (Actor→Particle conversion): drained by ExecuteTick (deterministically sorted before recycling).
延迟生成请求数组,ExecuteTick 中批量处理;访问受 DeferredSpawnLock 保护。
Deferred spawn request array, processed in batch during ExecuteTick; access is guarded by DeferredSpawnLock.
DeferredSpawnRequests 的线程安全临界区(入队/交换/重排均持锁)。
Critical section for thread-safe access to DeferredSpawnRequests (enqueue/swap/reorder all hold the lock).
端侧本地 select 视觉登记表(AgentUID → 登记项)。仅网络模式启用;仅游戏线程访问——严禁在 MBParallelFor 并行体内变更(见 FLocalVisualEntry 注释)。
Peer-local select visual registry (AgentUID → entry). Networked mode only; game-thread only — never mutate inside MBParallelFor bodies (see the FLocalVisualEntry comment).
挂起 EQS 请求映射,以 latent 动作的 UUID 为键(先 RequestID 后 QueryID)。
Map of pending EQS requests, keyed by the latent action's UUID (RequestID first, then QueryID).
EQS 请求唯一 ID 计数器(自增,从 0 起)。
Counter for generating unique EQS request IDs (incrementing from 0).
缓存旗标枚举值(EBattleFlags → EEntityFlags 转换):BeingSelect / Selected / PlayerDriven / AStarMovingTo / BPTask_MoveTo,供 SelectAgents/DeselectAgents/StopAgentsAllMovement 等内部使用。
Cached flag enum values (EBattleFlags → EEntityFlags conversions): BeingSelect / Selected / PlayerDriven / AStarMovingTo / BPTask_MoveTo, used internally by SelectAgents/DeselectAgents/StopAgentsAllMovement, etc.
管线角色 Pipeline Role
调用关系(全部经 grep 验证):本子系统被 UMassBattleSubsystem::ExecuteTick(MassBattleSubsystem.cpp:1437)每逻辑帧在 MassBattleTick 广播之后、锁步命令与模拟阶段之前调用 AgentSub->ExecuteTick(CalculatedStepTime)。ExecuteTick 内部依次驱动 ProcessDeferredSpawnRequests(延迟生成)、ActorSpawnRequestQueue/ActorRecycleQueue 排空(Particle ↔ Actor 表现互换,确定性排序,池/生成/组件绑定)、SweepLocalVisuals。resync 钩子:RebindLocalVisualsAfterResync 由 UMassBattleNetworkSubsystem::ProcessDeferredSnapshot(MassBattleNetworkSubsystem.cpp:2817)在组件 RebindToEntity pass 之后调用。UID 注册:RegisterUniqueIDEntity 由 UMassBattleAgentComponent(MassBattleAgentComponent.cpp:934)调用,双写进 UMassBattleSubsystem::RegisterUIDEntity。生成路径:全部 public spawn API 汇聚 SpawnAgentsAtLocations_Internal → UMassBattleSubsystem::AllocNextUID(UID)/RegisterUIDEntity(映射)/ResolveAgentRuntimeObjectPtrs(运行时指针)、UMassAPISubsystem::BuildEntities + MBParallelFor 并行填 fragment;延迟路径经 DeferredSpawnRequests 由 ExecuteTick 排空。宿主生成:SelectAgents/DeselectAgents/SpawnBatchedFx/AttachXxx/SpawnLoot 调用 UMassBattleHostSubsystem 的 SpawnActorHost/SpawnFxHost/SpawnSoundHost/SpawnAgentHost/SpawnLootHost;网络模式下本地宿主(UID=-1、无 FNetworkTag)登记 LocalVisualRegistry,由 HostMonoProcessor 消费 bShouldDestroy 完成销毁/回收。处理器侧:生成的 agent 由各处理器查询消费;PlayerDrivenFlag 由 ReactionProcessor 等联动(源码注释)。
Call relationships (all verified by grep): this subsystem is called by UMassBattleSubsystem::ExecuteTick (MassBattleSubsystem.cpp:1437) via AgentSub->ExecuteTick(CalculatedStepTime) every logic frame, right after the MassBattleTick broadcast and before lockstep commands and the simulation stages. Inside ExecuteTick it drives ProcessDeferredSpawnRequests (deferred spawning), the ActorSpawnRequestQueue/ActorRecycleQueue drains (Particle ↔ Actor representation swapping with deterministic sorting, pooling/spawning/component binding), and SweepLocalVisuals. Resync hook: RebindLocalVisualsAfterResync is called from UMassBattleNetworkSubsystem::ProcessDeferredSnapshot (MassBattleNetworkSubsystem.cpp:2817) after the component RebindToEntity pass. UID registration: RegisterUniqueIDEntity is called from UMassBattleAgentComponent (MassBattleAgentComponent.cpp:934) and dual-writes into UMassBattleSubsystem::RegisterUIDEntity. Spawn path: all public spawn APIs funnel into SpawnAgentsAtLocations_Internal → UMassBattleSubsystem::AllocNextUID (UIDs) / RegisterUIDEntity (mappings) / ResolveAgentRuntimeObjectPtrs (runtime pointers), UMassAPISubsystem::BuildEntities plus MBParallelFor for parallel fragment fill; the deferred path goes through DeferredSpawnRequests drained by ExecuteTick. Host spawning: SelectAgents/DeselectAgents/SpawnBatchedFx/AttachXxx/SpawnLoot call UMassBattleHostSubsystem's SpawnActorHost/SpawnFxHost/SpawnSoundHost/SpawnAgentHost/SpawnLootHost; in networked mode local hosts (UID=-1, no FNetworkTag) are registered in LocalVisualRegistry, and HostMonoProcessor consumes bShouldDestroy for destruction/recycling. On the processor side, spawned agents are consumed by the various processors' queries; PlayerDrivenFlag is also set by ReactionProcessor et al. (source comment).
补充说明 Notes
① 孤儿注释:头文件 527-533 行残留一段「Creates an array of FEntityTemplateData by reading the composition...」的文档注释,其后没有对应函数声明——原复制模板函数已删除,注释未清理。
② 弃用节点:12 个 BlueprintCallable 节点(SetSpawnerSeed、MakeAgentTemplateDataFromDataAsset、4 个同步生成、4 个延迟生成、ActivateAgent/ActivateAgents)全部标记 DeprecatedFunction,DeprecationMessage 指向 MassBattleFuncLib 对应函数。
③ [RULE7] 锁步守卫:网络模式下 SpawnAgentsAtLocations_Internal、ProcessDeferredSpawnRequests、SpawnLoot、AttachAgentToAgent 对锁步外调用打 Error 并拦截——agent/agent-host 生成是模拟状态,必须走确定性命令路径;纯视觉宿主(FX/actor/sound)的锁步外本地生成已按设计允许。
④ 本地视觉纪律:LocalVisualRegistry 仅游戏线程访问;宿主销毁一律置 bShouldDestroy 走 HostMonoProcessor 管线,不直接 DestroyEntity。
⑤ 确定性纪律:子系统 RandomStream 的所有消费(洗牌、乘数采样、随机偏移)都发生在串行段;并行阶段仅用 UID 派生的局部流。
① Orphaned comment: header lines 527-533 carry a leftover doc comment ("Creates an array of FEntityTemplateData by reading the composition...") with no corresponding function declaration — the copy-template function was removed but the comment was not.
② Deprecated nodes: all 12 BlueprintCallable nodes (SetSpawnerSeed, MakeAgentTemplateDataFromDataAsset, 4 synchronous spawns, 4 deferred spawns, ActivateAgent/ActivateAgents) carry DeprecatedFunction, with the DeprecationMessage pointing to the corresponding MassBattleFuncLib function.
③ [RULE7] lockstep guard: in networked mode, SpawnAgentsAtLocations_Internal, ProcessDeferredSpawnRequests, SpawnLoot, and AttachAgentToAgent log an Error and block off-lockstep calls — agent/agent-host spawning is simulation state and must go through the deterministic command path; off-lockstep local spawning of purely-visual hosts (FX/actor/sound) is allowed by design.
④ Local visual discipline: LocalVisualRegistry is game-thread only; host destruction always sets bShouldDestroy through the HostMonoProcessor pipeline, never direct DestroyEntity.
⑤ Determinism discipline: all consumption of the subsystem RandomStream (shuffles, multiplier sampling, random offsets) happens in serial sections; parallel phases use only UID-derived local streams.