UMassBattleBPTaskAgentsChaseAttack
Source/MassBattle/Public/Tasks/MassBattleBPTaskAgentsChaseAttack.h
概述 Overview
批量 Agent 追击并攻击单一目标的异步蓝图节点(UBlueprintAsyncActionBase + FTickableGameObject)。把传入 Agent 锁定到 Target 上,由现有 Chase/Attack 流程驱动实际移动与挥击;移动经 FTracing 的 ActiveChaseAttackTaskID / LockedTarget / bChaseAttackInterruptible 与 Trace 处理器协作:硬锁定(BehaviorsCanInterrupt=false)索敌被钉在 Target 上,永不偏离;软锁定索敌正常运行,切换目标时触发一次 OnAgentInterrupt(保留在跟踪表,Target 作回退)。每 tick:帧首目标有效性检查(无效 → 一次性 OnAgentSuccess 并结束)、逐 agent 分类(死亡/被新 ChaseAttack 或 MoveTo 接管 → Transfer、超 FChase.MaxChaseDistance(仅硬锁定)→ Fail、卡住 AverageSpeed 低于阈值持续 StuckTimeLimit 且在 FailRadius 内 → Fail、进入 Chase.AcceptanceRadius → 到达成功)并广播对应 delegate。快照采集/恢复(FAgentTaskSnapshotRecord)支持 resync 任务重建。两阶段 tick(Phase A 并行分类 + Phase B 串行应用)。
Batch-agent chase-and-attack a single target async Blueprint node (UBlueprintAsyncActionBase + FTickableGameObject). Locks the given agents onto Target; the existing Chase/Attack pipeline drives the actual movement and swings. Movement collaborates with the Trace processor via FTracing's ActiveChaseAttackTaskID / LockedTarget / bChaseAttackInterruptible: HARD lock (BehaviorsCanInterrupt=false) pins the trace to Target, never deviating; SOFT lock lets the trace run normally, firing OnAgentInterrupt once when the agent switches targets (kept in tracking; Target is the fallback). Each tick: top-of-frame target validity check (invalid → one-shot OnAgentSuccess and end), per-agent classification (dead / taken over by a newer ChaseAttack or MoveTo → Transfer; beyond FChase.MaxChaseDistance (HARD lock only) → Fail; stuck — AverageSpeed below threshold for StuckTimeLimit within FailRadius → Fail; within Chase.AcceptanceRadius → goal-reached success), broadcasting the matching delegates. Snapshot capture/restore (FAgentTaskSnapshotRecord) supports resync task rebuild. Two-phase tick (Phase A parallel classification + Phase B serial apply).
继承 Inheritance
公开方法 Public Methods
主工厂。锁步门控:IsOffLockstep 为真(网络会话且不在命令执行内)时拒绝并返回 nullptr。创建实例、经每 World 计数器 UMassBattleSubsystem::AllocChaseAttackTaskID() 铸 MyTaskID(跳过 0;原进程级 static 计数器已于 2026-09-12 PIE 修复迁至 UMassBattleSubsystem::NextChaseAttackTaskID,PIE 双世界不再从同一共享计数器分叉铸号)、把 Target 解析为 FDeterminism.UniqueID 存入 StoredTargetUID、逐 agent 建跟踪行;工厂内即 RegisterTask(快照采集 tick 当帧创建的任务在引擎激活前就要被采到)。
Main factory. Lockstep gate: rejects with nullptr when IsOffLockstep is true (networked session outside command execution). Creates the instance, mints MyTaskID from the per-world counter UMassBattleSubsystem::AllocChaseAttackTaskID() (skipping 0; the former process-static counter moved to UMassBattleSubsystem::NextChaseAttackTaskID in the 2026-09-12 PIE fix, so PIE's two worlds no longer mint from one shared counter and fork IDs), resolves Target to FDeterminism.UniqueID into StoredTargetUID, builds a tracking row per agent; registers via RegisterTask inside the factory (a task created on the snapshot-capture tick must be captured before the engine activates it).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | UObject* | 世界上下文。World context. |
Agents | const TArray<FEntityHandle>& | 要命令的 agent 数组,无效实体静默跳过。Agents to command; invalid entities silently skipped. |
Target | FEntityHandle | 单一目标实体,必须是已激活、存活、含 FLocating 的 Agent。Single target entity; must be an activated agent, alive, with FLocating. |
BehaviorsCanInterrupt | bool | false = 硬锁定(索敌钉住);true = 软锁定(索敌可切换)。false = HARD lock (trace pinned); true = SOFT lock (trace can switch). |
FailConditions | FMBMoveFailCondition | 卡住检测设置(与 AgentsMoveTo 同语义);StuckTimeLimit=0 禁用。Stuck detection settings (same semantics as AgentsMoveTo); 0 disables. |
Visualization | FAgentTaskVisualizationConfig | 逐帧可视化配置(默认关闭)。Per-tick visualization config (disabled by default). |
Output
返回任务实例;门控拒绝时 nullptr。副作用:铸任务 ID、缓存参数、注册任务。
Returns the task instance, or nullptr when gated. Side effects: mints the task ID, caches parameters, registers the task.
模板化创建:经模板实例创建、记录模板键、绑定 delegate(BindChaseAttackTask)。守卫与 MoveTo 版一致:任务重建窗口拒绝 BP 创建;工厂不得自行 Activate(async 节点展开调用一次)。
Template-based creation: creates via the template instance, records the template key, binds delegates (BindChaseAttackTask). Guards match the MoveTo version: the task-rebuild window rejects BP creation; the factory must not activate (the async node expansion activates once).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
TemplateClass | TSubclassOf<UMassBattleBPTaskTemplateBase> | 任务模板类。Task template class. |
| 其余参数 | 同 AgentsChaseAttack | 与主工厂一致。Same as AgentsChaseAttack. |
Output
返回任务实例(已绑定模板 delegate);守卫/模板失败时 nullptr。
Returns the task instance (delegates bound), or nullptr when guarded/template fails.
resync 快照重建入口(仅 UMassBattleSubsystem::RebuildTasksFromSnapshot 调用):同锁步门控(恢复窗口绕过 IsOffLockstep),经 RestoreFromSnapshot 填充状态后返回。
Resync snapshot rebuild entry (called by UMassBattleSubsystem::RebuildTasksFromSnapshot only): same lockstep gate (the restore window bypasses IsOffLockstep), fills state via RestoreFromSnapshot and returns.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | UObject* | 世界上下文。World context. |
Snapshot | const FAgentTaskSnapshotRecord& | 任务快照记录。Task snapshot record. |
Output
返回重建的任务实例(待显式 Activate);门控拒绝时 nullptr。
Returns the rebuilt task (awaiting explicit Activate), or nullptr when gated.
任务 ID 计数器访问器,经快照 payload 同步。2026-09-12 PIE 失步修复起按 World 落位:计数器存于 UMassBattleSubsystem::NextChaseAttackTaskID(每 World 一份),不再是本类的进程级 static——PIE 下两个世界曾从同一共享计数器为同一锁步命令铸出分叉的 ID。快照捕获时 UMassBattleNetworkSubsystem 读取计数器入 payload,恢复时写回。
Task-ID counter accessors, synced through the snapshot payload. World-scoped since the 2026-09-12 PIE desync fix: the counter lives on UMassBattleSubsystem::NextChaseAttackTaskID (one per world), no longer a process-static on this class — under PIE, both worlds used to mint from one shared counter for the same lockstep command and fork IDs. UMassBattleNetworkSubsystem reads the counter into the payload at capture and writes it back on restore.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
WorldContext | const UObject* | 世界上下文(解析目标 UMassBattleSubsystem)。World context (resolves the target UMassBattleSubsystem). |
InNext | uint32 | 恢复写回的下一任务 ID(SetNextTaskID 用)。Next task ID written back on restore (SetNextTaskID). |
Output
GetNextTaskID 返回该世界的当前计数(子系统无效时 0);SetNextTaskID 无返回值,副作用为覆写计数器。
GetNextTaskID returns the world's current counter (0 when the subsystem is invalid); SetNextTaskID returns nothing and overwrites the counter.
激活:一次性校验目标(IsTargetValid:Agent 标签 / 已激活 / 未濒死 / 有 FLocating / Health > 0;无效 → 全部 agent 计失败并结束,不触发 OnAgentSuccess——任务尚未开始跟踪);逐 agent 过滤无效/濒死/自指,释放残留 MoveTo 锁(清 BPTaskMoveToFlag 与 ActiveMoveToTaskID,旧 MoveTo 任务下一帧检测 ID 不匹配静默丢弃)、清残留 Sleep/Patrol 旗标、SetupAgentLock(置 BPTaskChaseAttackFlag,写 ActiveChaseAttackTaskID / LockedTarget / bChaseAttackInterruptible,经 WriteTarget 原子播种 TraceResult + 位置缓存);广播 OnTaskStart;记录可视化墙钟起点;注册 MassBattleTick。
Activation: one-shot target validation (IsTargetValid: Agent tag / activated / not dying / has FLocating / Health > 0; invalid → all agents fail and finish, no OnAgentSuccess — nothing is tracked yet); per-agent filtering of invalid/dying/self-referencing entities, releases any residual MoveTo lock (clears BPTaskMoveToFlag and ActiveMoveToTaskID; the old MoveTo task silently drops the agent next frame on the ID mismatch), clears stale Sleep/Patrol flags, SetupAgentLock (sets BPTaskChaseAttackFlag, writes ActiveChaseAttackTaskID / LockedTarget / bChaseAttackInterruptible, atomically seeds TraceResult + location cache via WriteTarget); broadcasts OnTaskStart; records the visualization wall-clock start; registers with MassBattleTick.
Input
无参数。
No parameters.
Output
无返回值。副作用:写被命令实体的 FTracing 与旗标、广播 OnTaskStart、注册 tick 驱动。
No return value. Side effects: writes commanded entities' FTracing and flags, broadcasts OnTaskStart, registers the tick driver.
快照恢复激活路径(bRestoringFromSnapshot 时 Activate 走此分支):对重建实体一次性校验目标 + 复检 agent(死亡/濒死/自指语义同常规 Activate),仅补写快照注册表未覆盖的 fragment 字段(ActiveChaseAttackTaskID / bChaseAttackInterruptible / bLostTargetRetraceTriggered);TraceResult / LockedTarget / 位置缓存 / BPTask_ChaseAttack 旗标由快照权威,Trace 处理器每帧重钉硬锁。重置可视化墙钟预算并注册 tick。
Snapshot-restore activation path (taken by Activate when bRestoringFromSnapshot): one-shot target validation against the rebuilt entity + agent re-validation (same dead/dying/self semantics as normal Activate), re-claims only fragment fields the snapshot registry does not cover (ActiveChaseAttackTaskID / bChaseAttackInterruptible / bLostTargetRetraceTriggered); TraceResult / LockedTarget / location cache / BPTask_ChaseAttack flag are snapshot-authoritative, and the Trace processor re-pins the hard lock each frame. Restarts the visualization wall-clock budget and registers the tick.
Input
无参数。
No parameters.
Output
无返回值。副作用:过滤跟踪行、补写索敌字段、注册 tick。
No return value. Side effects: filters tracking rows, re-writes trace fields, registers the tick.
采集运行状态到快照记录(由 UMassBattleSubsystem::CaptureTaskRecords 调用):任务类型/ID/模板键、TargetUID / bBehaviorsCanInterrupt / FailConditions / Visualization、每 agent 卡住状态与中断边沿、累计失败 UID、bSuccessFired 闩。
Captures runtime state into a snapshot record (called by UMassBattleSubsystem::CaptureTaskRecords): task type/ID/template key, TargetUID / bBehaviorsCanInterrupt / FailConditions / Visualization, per-agent stuck state and interrupt latch, accumulated failed UIDs, and the bSuccessFired latch.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
OutRecord | FAgentTaskSnapshotRecord& | 输出的快照记录。Output snapshot record. |
Output
无返回值。副作用:OutRecord 被填充。
No return value. Side effect: OutRecord filled.
与 MoveTo 版同构:TerminateForResync 退订 tick + 可选 OnTaskEnd + 标记销毁,不写 fragment(快照 blob 权威),清空 TrackedAgents 使 GC 延迟清理零写入;RestoreFromSnapshot 直接填充不重新推导,任务 ID 必须与服务器存活任务一致。
Isomorphic to the MoveTo version: TerminateForResync deregisters the tick + optional OnTaskEnd + ready-to-destroy without fragment writes (snapshot-blob authoritative), emptying TrackedAgents so the deferred GC cleanup writes nothing; RestoreFromSnapshot fills directly with no re-derivation; the task ID must match the surviving server task.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
bBroadcastOnTaskEnd / InWorldContext + Record | 同 MoveTo 版 | 参数语义与 MoveTo 版一致。Same parameter semantics as the MoveTo version. |
Output
无返回值。副作用:清理/填充任务状态。
No return value. Side effects: clears/fills task state.
逐帧驱动(注册于 MassBattleTick)。帧首:目标有效性检查——无效(句柄无效 / 缺 AgentTag / 未激活 / 已濒死 / 缺 FLocating / Health ≤ 0)且 bSuccessFired 未触发 → 用仍在跟踪的 agent 触发一次 OnAgentSuccess 并结束(任务成功条件);缓存目标位置。Phase A 并行分类(MBParallelFor Unbalanced,不相交内存):① 死亡/无效/丢 FTracing → Fail;② 被更新的 ChaseAttack 接管(ActiveChaseAttackTaskID != MyTaskID)→ Transfer(不清锁);③ 被 MoveTo 接管(ActiveMoveToTaskID != 0 && BPTaskMoveToFlag)→ 清锁 + Transfer;④ 软锁定:无自身目标 → WriteTarget 回退到 StoredTarget;有其它目标 → 上升沿触发一次 OnAgentInterrupt(bWasOnInterruptedTarget 闩);硬锁定 → 防御式重钉(WriteTarget + LockedTarget);⑤ 距离检查(AttackingFlag 表示在攻击范围);⑥ MaxChaseDistance 失败(仅硬锁定,实时 2D 距离);⑦ 调试绘制(硬=品红 / 软=橙);⑧ 卡住检测(进入攻击范围重置窗口;AverageSpeed < StuckVelocityThreshold 累计 StuckTimeLimit 且距 LastKnownTargetLocation ≤ FailRadius → Fail);⑨ 到达成功(距 Chase.AcceptanceRadius 内——即使目标仍存活也成功,让被遮挡/越界追击干净结束)。Phase B 串行应用并广播 OnAgentFail / OnAgentInterrupt / OnAgentTransfer / OnAgentSuccess;重建可视化;全部解决后 Cleanup + FinishTask。
Per-frame tick driver (registered with MassBattleTick). Top of frame: target validity check — invalid (bad handle / missing AgentTag / deactivated / has DyingTag / missing FLocating / Health ≤ 0) and bSuccessFired not yet set → fire OnAgentSuccess once with all still-tracking agents and end (the task's success condition); caches the target location. Phase A parallel classification (MBParallelFor Unbalanced, disjoint memory): ① dead/invalid/lost FTracing → Fail; ② taken over by a newer ChaseAttack (ActiveChaseAttackTaskID != MyTaskID) → Transfer (no lock clear); ③ taken over by MoveTo (ActiveMoveToTaskID != 0 && BPTaskMoveToFlag) → clear lock + Transfer; ④ soft lock: no self target → WriteTarget fallback to StoredTarget; on another target → fire OnAgentInterrupt once on the rising edge (bWasOnInterruptedTarget latch); hard lock → defensive re-pin (WriteTarget + LockedTarget); ⑤ range check (AttackingFlag implies within attack range); ⑥ MaxChaseDistance fail (HARD lock only, live 2D distance); ⑦ debug drawing (hard = magenta / soft = orange); ⑧ stuck detection (entering attack range resets the window; AverageSpeed < StuckVelocityThreshold accumulating StuckTimeLimit within ≤ FailRadius of LastKnownTargetLocation → Fail); ⑨ goal-reached success (within Chase.AcceptanceRadius — succeeds even while the target is alive, so LOS-blocked or out-of-range chases resolve cleanly). Phase B serial applies and broadcasts OnAgentFail / OnAgentInterrupt / OnAgentTransfer / OnAgentSuccess; rebuilds visualization; when all agents resolve → Cleanup + FinishTask.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
DeltaTime | float | 模拟步长(秒)。Simulation step (seconds). |
TickCount | int32 | 逻辑 tick 计数。Logic tick count. |
Output
无返回值。副作用:写被命令实体的 FTracing 与旗标、广播四个逐帧 delegate(成功条件路径广播一次 OnAgentSuccess)、重建可视化、任务完成时清理。
No return value. Side effects: writes commanded entities' FTracing and flags, broadcasts the four per-frame delegates (the success-condition path broadcasts OnAgentSuccess once), rebuilds visualization, cleans up on completion.
SetupAgentLock:置 BPTaskChaseAttackFlag,写 ActiveChaseAttackTaskID / LockedTarget / bLostTargetRetraceTriggered / bChaseAttackInterruptible,WriteTarget 播种;ClearAgentLock:清旗标并仅当仍是拥有者时(ActiveChaseAttackTaskID == MyTaskID)释放所有权,TraceResult 保留由下一次索敌冷却自然覆盖。worker 安全重载由调用方传入已解析的 UMassAPISubsystem*。
SetupAgentLock: sets BPTaskChaseAttackFlag, writes ActiveChaseAttackTaskID / LockedTarget / bLostTargetRetraceTriggered / bChaseAttackInterruptible, seeds via WriteTarget; ClearAgentLock: clears the flag and releases ownership only while still the owner (ActiveChaseAttackTaskID == MyTaskID); TraceResult is left for the next trace cooldown to overwrite naturally. Worker-safe overloads take a caller-resolved UMassAPISubsystem*.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Entity (或 MA + Entity) | const FEntityHandle | 目标 agent 实体。Target agent entity. |
Output
无返回值。副作用:实体 FTracing 与旗标被修改。
No return value. Side effects: entity FTracing and flags mutated.
Cleanup:释放剩余 agent 的锁(仅当仍拥有)、退订 tick、注销任务、清可视化缓存;FinishTask:用累计失败 UID 广播 OnTaskEnd 并标记可销毁——所有终止路径的最后一步。
Cleanup: releases remaining agents' locks (only while owned), deregisters the tick, unregisters the task, clears visualization caches; FinishTask: broadcasts OnTaskEnd with the accumulated failed UIDs and marks ready to destroy — the final hop of every termination path.
Input
无参数。
No parameters.
Output
无返回值。副作用:清理注册与实体状态;广播结束事件。
No return value. Side effects: clears registrations and entity state; broadcasts the end event.
引擎 tick 渲染路径,与 MoveTo 版一致:IsTickable 仅当有内容可绘制;每渲染帧重新提交可视化线段(墙钟预算闸门),MassBattle tick 与引擎 tick 双路径保证渲染频率高于模拟频率时不闪烁。
Engine-tick render path, identical to the MoveTo version: IsTickable only when there is something to draw; re-submits visualization lines every render frame (wall-clock budget gate); the MassBattle-tick + engine-tick dual path keeps rendering from blinking when the render rate exceeds the sim rate.
Input
无参数(Tick 收 float DeltaTime)。
No parameters (Tick takes float DeltaTime).
Output
无返回值。副作用:向世界线批处理提交可视化。
No return value. Side effect: submits visualization to the world's line batcher.
管线角色 Pipeline Role
由蓝图经 AgentsChaseAttack(或模板化 CreateAgentsChaseAttackTask)创建;锁步会话中必须由 ExecuteNetCommand 创建。TickCheck 注册在 UMassBattleSubsystem::MassBattleTick;移动由 Trace 处理器(硬锁钉 TraceResult)与 Move/Behavior 处理器(Chase/Attack 流程)执行;任务间竞争经 ActiveChaseAttackTaskID / ActiveMoveToTaskID 所有权检测;resync 时经 FAgentTaskSnapshotRecord 采集/重建,模板实例重新绑定 delegate。
Created from Blueprint via AgentsChaseAttack (or template-based CreateAgentsChaseAttackTask); in lockstep sessions it must be created by ExecuteNetCommand. TickCheck registers with UMassBattleSubsystem::MassBattleTick; movement is executed by the Trace processor (hard lock pins TraceResult) and the Move/Behavior processors (Chase/Attack flow); inter-task competition is resolved via ActiveChaseAttackTaskID / ActiveMoveToTaskID ownership checks; on resync it is captured/rebuild via FAgentTaskSnapshotRecord, with the template instance re-binding delegates.