Mass Battle Frameworkv1.20.0

UMassBattlePhysicsProcessor

UCLASS Processor AUTO-DRIVEN · NO SETUP

Source/MassBattle/Public/Processors/MassBattlePhysicsProcessor.h

概述Overview

碰撞解算处理器(MassBattle.Physics.Substeps > 1 时启用):多子步修正穿透,极端堆叠下表现更稳。由插件自动调度;子步数与解算强度通过物理子系统设置。

The collision-solve processor (armed by MassBattle.Physics.Substeps > 1): multi-substep penetration correction with steadier behavior under extreme stacking. Auto-scheduled; substep count and solve strength are set through the physics subsystem.

继承Inheritance

UMassProcessor → UMassBattlePhysicsProcessor

FSolvePassCtxFSolvePassCtx

每个子步共享的解算上下文,由扫描派发器与单体解算函数共用。它把「这次子步怎么解」的全部输入集中在一处:步长、阻尼、子步序号、是否重建邻域与接触对缓存、走哪条解算路径,以及两个跨线程汇总的原子最大值指针。

The per-substep solve context shared by the sweep dispatcher and the single-body solve function. It collects everything that says how this substep is solved: step time, damping, the substep index, whether to rebuild the neighbourhood and contact-pair cache, which solve path to take, and two atomics that collect cross-thread maxima.

成员变量Members
名称Name类型Type默认值说明Description
DeltaTimefloat0.f本帧步长(秒),所有子步共用。Frame step time in seconds, shared by every substep.
SceneDampfloat1.f场景平面的阻尼系数,已按子步数折算。Damping factor for the scene plane, already folded per substep.
Substepsint321本帧的子步总数 N。Total substep count N for this frame.
Substepint320当前正在解算的子步下标。Index of the substep being solved.
bGatherbooltrue本次子步是否重建邻域走查与接触对缓存;为 false 时消费缓存列表。Whether this substep rebuilds the neighbourhood walk and the contact-pair cache; false consumes the cached lists.
bAVBDboolfalse选择增广拉格朗日(primal/dual)解算路径。Selects the augmented-Lagrangian primal/dual solve path.
OverRelaxfloat1.f松弛(SOR)系数,在游戏线程读取。Relaxation (SOR) factor, read on the game thread.
bDebugStackingboolfalse打开堆叠探针。Turns on the stacking probes.
MaxCumDispPhasefloat0.f自适应邻域余量的输入:本帧已提升的累积漂移。Walk-margin input: the frame's promoted cumulative drift.
MaxDispSharedstd::atomic<float>*nullptr各子步累积漂移的原子最大值(CAS 取最大)。Atomic maximum of per-substep cumulative drift (CAS-max).
MaxCorrSharedstd::atomic<float>*nullptr各子步修正幅度的原子最大值(CAS 取最大)。Atomic maximum of per-substep correction magnitude (CAS-max).

方法Methods

UMassBattlePhysicsProcessor constructor

默认构造函数,只配置处理器自身的调度属性:不与引擎处理阶段自动注册,要求游戏线程执行,并在独立、服务端、客户端三种目标上启用。子步数、解算强度等行为参数全部来自物理子系统,构造函数不持有任何可调项。

Default constructor. It only configures the processor's own scheduling properties: no automatic registration with the engine's processing phases, game-thread execution required, enabled on the standalone, server and client targets. Behavioural parameters such as substep count and solve strength come from the physics subsystem; the constructor holds no tunables.

Input

无参数。

No parameters.

Output

无返回值。副作用:写入三个处理器属性——bAutoRegisterWithProcessingPhases = false、bRequiresGameThreadExecution = true、ExecutionFlags = Standalone | Server | Client。

No return value. Side effects: three processor properties are written — bAutoRegisterWithProcessingPhases = false, bRequiresGameThreadExecution = true, ExecutionFlags = Standalone | Server | Client.

PushHandoff void

移动阶段尾部的逐实体交接写入。移动侧已经算出结果,不再走一次收集与合并,而是按实体索引把记录直接写进交接表;每个实体只写自己的条目,写入互不相交。容量不足时(例如波次中途新生成的实体),记录转入线程本地的溢出收集器,由本处理器在登记阶段开头排空。

The per-agent handoff push at the tail of the move phase. The move side already has the result, so instead of a gather and merge it writes the record straight into the handoff table at the entity's index; each entity writes only its own entry, so the writes are disjoint. When capacity is short (a mid-wave spawn, for example), the record goes to a thread-local overflow gatherer that this processor drains at the start of its register stage.

Input
参数Param类型Type说明Description
Entityconst FMassEntityHandle记录所属实体;其 Index 是直接写入的位置,SerialNumber 用于识别索引被回收后的过期记录。Entity the record belongs to; its Index is the direct write position and its SerialNumber identifies stale records after index recycling.
RecFPhysicsHandoffRecord&&交接记录,右值引用,整体移入交接表或溢出收集器。The handoff record, an rvalue reference moved whole into the handoff table or the overflow gatherer.
Output

无返回值。副作用:按实体索引写入记录并盖上序号与帧代;容量不足时该记录进入线程本地溢出收集器。

No return value. Side effects: the record lands at the entity's index stamped with its serial and the frame generation, or enters the thread-local overflow gatherer when capacity is short.

ConfigureQueries virtual void

构建并注册主查询。实体必须带 FAgentTag,并同时具备缩放、碰撞体、移动、死亡、濒死、确定性以及物理 fragment(只读);写出侧是定位、移动、旋转与实体标志(可写)。相对移动处理器的 fragment 集合,这里去掉了纯转向与导航类 fragment——本处理器只读取移动状态,从不产生它。

Builds and registers the main query. An entity must carry FAgentTag plus the scaling, collider, move, death, dying, determinism and physics fragments (read access); the write side is locating, moving, rotating and the entity flags (read-write). Compared with the move processors' fragment set, the pure steering and navigation fragments are absent — this processor reads movement state and never produces it.

Input
参数Param类型Type说明Description
EntityManagerconst TSharedRef<FMassEntityManager>&实体管理器,查询在它上面初始化。Entity manager the query is initialized against.
Output

无返回值。副作用:EntityQuery 完成初始化并注册到本处理器。

No return value. Side effects: EntityQuery is initialized and registered with this processor.

Execute virtual void

每帧入口。先做一组自检:战斗子系统与持久物理网格子系统必须存在;独立物理求解必须已由子系统启用(MassBattle.Physics.Substeps > 1 且不在定点模式);必须处在 Subtick2 引擎 tick——此时完整移动阶段已经跑完;步长必须为正。随后读取子步数与求解器选择,在本次会话首次走增广拉格朗日路径时按 [PHYS_AVBD] 标签打一条日志,并排空交接溢出。接着进入登记阶段:第一遍只统计可参与解算的实体(已激活、未等待销毁、网格登记模式不为 None)并据此扩容槽位数组;第二遍由各 chunk 用一次票号认领下标,把解算前的刚体数据直接写到最终槽位。登记阶段是本帧唯一读取 fragment 的时刻,持久网格也在这一阶段重置。

Frame entry. It first runs a set of checks: the battle subsystem and the persistent physics grid subsystem must exist; standalone physics solving must be armed by the subsystem (MassBattle.Physics.Substeps > 1 and not in fixed-point mode); the Subtick2 engine tick must be scheduled, meaning the full move phase has already run; and the step time must be positive. It then reads the substep count and the solver selection, logs the augmented-Lagrangian path once per session under the [PHYS_AVBD] tag, and drains the handoff overflow. The register stage follows: a first pass only counts the eligible bodies (activated, not pending destroy, grid register mode not None) and resizes the slot arrays to that count, then a second pass lets each chunk claim an index range with one ticket and write the pre-solve body data directly at its final slot. This stage is the frame's only fragment read, and the persistent grid is reset here too.

Input
参数Param类型Type说明Description
EntityManagerFMassEntityManager&实体管理器,处理器通过它访问实体。Entity manager the processor accesses entities through.
ContextFMassExecutionContext&本帧执行上下文,用于逐 chunk 遍历查询。Execution context for this frame, used to walk the query chunk by chunk.
Output

无返回值。副作用:槽位数组(PreData / CurData / Selves)按本帧实体数重建或清空;实体索引簿记与持久网格按帧重置;PhysGrid 被重新缓存;AVBD 首次激活时写一条日志;交接溢出被消费。

No return value. Side effects: the slot arrays (PreData / CurData / Selves) are rebuilt or cleared to this frame's body count; the entity-index bookkeeping and the persistent grid are reset for the frame; PhysGrid is re-cached; a log line is written on the first AVBD activation; the handoff overflow is consumed.

常量Constants

四个标志常量把共享战斗标志的枚举值预先缓存成 EEntityFlags,让状态判定不必每次做枚举转换;另一个是接触对缓存的刷新阈值,决定子步之间何时重新收集邻居对。

Four flag constants cache the shared battle-flag enum values as EEntityFlags, so state tests skip the enum conversion; the other is the contact-pair refresh threshold that decides when neighbouring pairs are gathered again between substeps.

名称Name值Value说明Description
FallingFlagEBattleFlags::Falling处于下落状态的共享标志。Shared flag for an entity being airborne in a fall.
LaunchingFlagEBattleFlags::Launching被击飞(发射)状态的共享标志。Shared flag for the launched state.
DyingFlagEBattleFlags::Dying处于死亡过程的共享标志。Shared flag for the entity being in the death process.
ActivatedFlagEBattleFlags::Activated实体已激活的共享标志;登记波次用它筛掉未激活实体。Shared flag for an activated entity; the register wave uses it to skip inactive entities.
PairRefreshMargin24.f接触对缓存的刷新阈值(世界单位):全局累积漂移超过该值即重新收集;两次收集之间的漂移由它加上一次子步的修正幅度界定。Contact-pair refresh threshold in world units: a global cumulative drift beyond this value triggers a re-gather; drift between gathers is bounded by this margin plus one substep's correction.

成员变量Members

名称Name类型Type默认值说明Description
EntityQueryFMassEntityQuery—主实体查询,由 ConfigureQueries 构建,Execute 用它遍历参与解算的实体。Main entity query, built by ConfigureQueries and walked by Execute.
bLoggedAvbdActiveThisSessionboolfalse本次 PIE 会话是否已打印 AVBD 激活日志;处理器实例按世界创建,所以每个会话重置一次。Whether this PIE session already logged the AVBD activation; processor instances are per-world, so it resets each session.
SlotTicketstd::atomic<int32>0登记波次的槽位票号;每个 chunk 用一次原子加认领一段下标,把刚体数据直接写到最终位置。每次波次前归零。Slot ticket for the register wave; each chunk claims an index range with one atomic add and writes the body data at its final position. Reset to zero before each wave.
PreDataTArray<FAgentPhysicsData>空上一轮提升后的(已收敛)刚体状态;子步只读它。Body state from the last promotion (settled); substeps only read it.
CurDataTArray<FAgentPhysicsData>空各子步写出的当前刚体状态;子步之间由网格更新把 Current 提升为 Pre。Current body state written by each substep; between substeps the grid update promotes Current into Pre.
SelvesTArray<FPhysicsSlotSelf>空与槽位一一对应的本体数据。Per-slot self data, index-aligned with the slot arrays.
BodySlotByEntityIndexTArray<int32>空实体索引到槽位的直接查表;INDEX_NONE 表示该实体本帧不在解算中。Direct entity-index-to-slot lookup; INDEX_NONE means the entity is not being solved this frame.
BodySerialByEntityIndexTArray<int32>空实体序号校验表,防止索引被回收后把结果写错实体。Entity serial validation table, so a recycled index cannot receive another entity's result.
HandoffRecByEntityIndexTArray<FPhysicsHandoffRecord>空移动阶段按实体索引直接写入的交接记录。Handoff records written directly by the move phase at entity indices.
HandoffSerialByEntityIndexTArray<int32>空交接记录的序号戳,用于识别过期条目。Serial stamps for handoff records, used to spot stale entries.
HandoffGenByEntityIndexTArray<uint32>空交接记录的帧代号戳;代数不同即视为过期,所以不需要逐帧清零。Frame-generation stamps for handoff records; a different generation marks an entry stale, so no per-frame clear is needed.
HandoffGenCounterstd::atomic<uint32>1帧代计数器;只靠它就能把不同帧的记录区分开。Frame-generation counter; on its own it separates records of different frames.
HandoffOverflowFParallelGatherer<FPhysicsHandoffRecord>空容量不足时的线程本地溢出收集器,在登记阶段开头排空。Thread-local overflow gatherer for capacity misses, drained at the start of the register stage.
PhysGridTObjectPtr<UMassBattlePhysicsSubsystem> (private, UPROPERTY)nullptr每个 Execute 缓存的持久物理网格子系统;子步收集邻居时读取它。Persistent physics grid subsystem cached per Execute; the substeps' neighbour gather reads it.
MaxCumDispfloat0.f本帧所有刚体相对起始位置的累计位移最大值,供自适应邻域余量使用。Running maximum of each body's displacement from its start position this frame, feeding the adaptive walk margin.
SubstepResidualsTArray<float>空诊断用:每个子步开始时的 agent 对重叠总量,仅在 MassBattle.Physics.DebugResidual 开启时填充。Diagnostics: total agent-pair overlap observed at each substep start, populated only while MassBattle.Physics.DebugResidual is on.
PairGatherDispfloat0.f上一次收集接触对时的 MaxCumDisp 值,用来判断是否已超出刷新阈值。The MaxCumDisp value at the last contact-pair gather, used to tell whether the refresh threshold is exceeded.
FrameMaxCorrectionfloat0.f本帧单次子步修正幅度的运行最大值。Running maximum of a single substep's correction magnitude this frame.

私有方法Private Methods

名称Name返回类型Return参数Parameters说明Description
SolveOneBodyvoidconst FSolvePassCtx& Ctx, const int32 i单个刚体的完整子步:场景平面 → 缓存的接触或网格收集 → 缓存的障碍物 → 分裂写出。One body's full substep: scene planes → cached contacts or grid gather → cached obstacles → split write-out.
RunSolvePassvoidconst FSolvePassCtx& Ctx每个子步的并行派发器;调试开关下改为串行执行。Per-substep parallel dispatcher; serial under the debug toggle.
BuildObstacleCacheForSlotvoidconst int32 k, UMassBattleHashGridSubsystem& NeighborGrid为单个刚体建立本帧的障碍物缓存(合并构建阶段的消费者)。Builds one body's per-frame obstacle cache (consumer of the merged build pass).

管线角色Pipeline Role

运行位置与门控:它是移动阶段的下游——只在 Subtick2 引擎 tick 上运行,此时完整移动阶段(两个 UID 分区)都已跑完;并且只在独立物理求解启用时工作,即 MassBattle.Physics.Substeps > 1 且不在定点模式。子步数为 1 时由移动处理器内联的单遍解算负责,本处理器直接返回。移动阶段在自己的尾部通过 PushHandoff 把每个实体的交接记录直接写进实体索引表,本处理器在登记阶段开头只处理容量溢出。一帧分三段:登记是唯一读取 fragment 的时刻,每个刚体打包成一条网格记录,障碍物引用每帧只缓存一次;子步 × N 在槽位数组上并行,每个刚体只读 PreData、只写自己的 CurData,子步之间把 Current 提升为 Pre;写出是唯一写 fragment 的时刻,把最终状态写回 FLocating::Location,并回写速度反馈、旋转阻力与标志发布。槽位顺序取决于调度、不承载确定性;需要顺序的消费者通过网格单元中按 UID 排序的成员读取,每个刚体只写自己的记录。

Position and gating: it sits downstream of the move phase, running only on the Subtick2 engine tick, when the full move phase (both UID partitions) has already finished, and only while standalone physics solving is armed — MassBattle.Physics.Substeps > 1 and not in fixed-point mode. With a single substep the move processor's inline single-pass solve is the authority and this processor returns immediately. The move phase writes each agent's handoff record directly at its entity index through PushHandoff at its tail; the register stage here only handles capacity overflow. A frame has three segments: register is the only fragment read, packing each body into one grid record and caching obstacle references once per frame; substep × N runs in parallel over the slot arrays, each body reading only PreData and writing only its own CurData, with Current promoted to Pre between substeps; writeback is the only fragment write, putting the final state back into FLocating::Location along with the velocity feedback, rotational resistance and flag publications. Slot order is scheduling-dependent and carries no determinism; order-sensitive consumers read the grid cells' UID-sorted members, and each body writes only its own record.

补充说明Notes

① 子步强度按帧等效折算:刚度按 1-(1-k)^(1/N) 折算,场景阻尼按同一次方折算,所以把子步调大不会改变一帧的总响应,只是把同样的修正拆成更多遍执行。
② 诊断:MassBattle.Physics.DebugResidual 置 1 后,每个子步开始时会记录一次 agent 对重叠总量;单调递减的序列就是收敛的证据。默认 PositionRelaxation_Agent = 1.0 时每个子步都施加完整修正,所以 N=2 看起来可能与 N=8 一样——与 N=1 对比,并读残差序列观察链路是否在起作用。
③ 不参与的两种情形:定点模式下物理子系统会关闭独立求解;子步数为 1 时由移动处理器的内联单遍解算负责。两种情形下本处理器都不运行,也不会报错。

① Substep strength is folded frame-equivalently: stiffness is folded as 1-(1-k)^(1/N) and scene damping by the same root, so raising the substep count does not change the frame's total response — it splits the same correction into more passes.
② Diagnostics: with MassBattle.Physics.DebugResidual set to 1, the total agent-pair overlap is recorded at each substep start; a monotonically decaying series is the convergence proof. With the default PositionRelaxation_Agent = 1.0 every substep applies full corrections, so N=2 can look identical to N=8 — compare against N=1 and read the residual series to see the chain work.
③ Two cases where it does not run: fixed-point mode makes the subsystem turn standalone solving off, and a single substep hands the work to the move processor's inline single-pass solve. In both cases this processor does not run and reports no error.