MassBattle Docsv1.19.20

FlowField.h

UCLASS ×2 USTRUCT ×9 UENUM ×8

Source/FlowFieldCanvas/Public/FlowField.h

概述 Overview

FlowFieldCanvas 的核心文件:流场 Actor AFlowField 及其全部支撑类型。流场系统把寻路预计算成「每格一个方向」的场——Grid 模式把世界划分成 cellSize 的方格(FCellStruct),NavMesh 模式把 Detour 网格的多边形作为单元(NavMeshCellMap)。生成管线:环境查询(EnvQuery/EnvQueryAsync)→ 建格(CreateGrid)→ 成本修改(ModifyCost)→ Dijkstra 积分场 + 方向场(CalculateFlowField/CalculateFlowField_NavMesh)→ 方向修改(ModifyFlowField)→ 可视化(DrawCells/DrawArrows)。运行时查询 API(QueryNavigation/QueryNavigationAdvanced)、个体寻路(FindPathAStar/FindPathNavMesh)与多目标层系统(Layer API)都在本文件。异步重建由 UUpdateFlowFieldAsyncAction 提供。此外本文件还承载三套 MassBattle 协作机制:托管层生命周期(引用计数层 + 延迟销毁队列,供 MoveTo 任务复用)、运行时 modifier 推模式注册(RegisterModifier/UnregisterModifier)与锁步基底同步(服务器导出 / 全端导入的 ExportSubstrateBytes/ImportSubstrateBytes 系列,同步场禁用引擎 navmesh 查询、改在导入字节上本地计算)。

The core file of FlowFieldCanvas: the flow field actor AFlowField and all its supporting types. The system precomputes pathfinding into a field of one direction per cell — Grid mode divides the world into cellSize squares (FCellStruct); NavMesh mode treats Detour-mesh polygons as cells (NavMeshCellMap). Generation pipeline: environment query (EnvQuery/EnvQueryAsync) → grid creation (CreateGrid) → cost modification (ModifyCost) → Dijkstra integration field + flow field (CalculateFlowField/CalculateFlowField_NavMesh) → direction modification (ModifyFlowField) → visualization (DrawCells/DrawArrows). Runtime query APIs (QueryNavigation/QueryNavigationAdvanced), individual pathfinding (FindPathAStar/FindPathNavMesh) and the multi-goal layer system (Layer API) live in this file. Async rebuilds are provided by UUpdateFlowFieldAsyncAction. The file also carries three MassBattle-facing mechanisms: the managed layer lifecycle (refcounted layers plus a deferred-destroy queue, reused by MoveTo tasks), push-model runtime modifier registration (RegisterModifier/UnregisterModifier), and lockstep substrate sync (the server-exported / every-peer-imported ExportSubstrateBytes/ImportSubstrateBytes family — a synced field never queries the engine navmesh again and computes locally on the imported bytes).

枚举 Enums

EFlowFieldMode

流场生成模式,AFlowField::GenerationMode 使用。

Flow field generation mode, used by AFlowField::GenerationMode.

值 Value说明 Description
Grid方格网格模式:世界被划分为 cellSize 的格子。Grid mode: the world is divided into cellSize cells.
NavMesh导航网格模式:以 RecastNavMesh 的多边形为单元。NavMesh mode: RecastNavMesh polygons are the units.
EInitMode

初始化时机,控制 InitFlowField / DrawCells / DrawArrows 的可视化分支(编辑器显示 vs 游戏内显示)。

Initialization timing, driving the visualization branches (editor vs in-game) of InitFlowField / DrawCells / DrawArrows.

值 Value说明 Description
Construction编辑器构造阶段(Construction Script / DrawDebug)。Editor construction phase (Construction Script / DrawDebug).
BeginPlay游戏启动阶段。Game start phase.
Runtime运行时更新阶段。Runtime update phase.
EStyle

方向场计算风格,AFlowField::Style 使用。

Flow field direction style, used by AFlowField::Style.

值 Value说明 Description
AdjacentFirst邻接优先:选单个最优邻居(最陡下降),路径更贴格子。Adjacent first: picks the single best neighbor (steepest descent); paths hug the grid.
DiagonalFirst对角线优先:用加权平均得到平滑方向。Diagonal first: weighted average for smoother directions.
ECellType

格子类型,FCellStruct::type 使用。

Cell type, used by FCellStruct::type.

值 Value说明 Description
Ground可行走地面。Walkable ground.
Obstacle障碍(通常 cost = 255)。Obstacle (usually cost = 255).
Empty无地面(环境查询未命中)。No ground (environment query missed).
EDigitType

数字可视化模式(成本或距离)。注意:数字绘制代码(DrawDigits、Digit 材质)在 .cpp 中均被注释掉,该枚举当前未被实际使用。

Digit visualization mode (cost or distance). Note: digit drawing code (DrawDigits, digit materials) is commented out in the .cpp — the enum is currently unused.

值 Value说明 Description
Cost显示成本。Display cost.
Dist显示距离。Display distance.
EFlowFieldGroundDetectionMode

地面检测模式,AFlowField::GetGroundLocation 使用。

Ground detection mode, used by AFlowField::GetGroundLocation.

值 Value说明 Description
FlowField仅用流场插值位置(GetInterpedWorldLocation)。Flow-field interpolated location only (GetInterpedWorldLocation).
CapsuleSweep仅用胶囊体扫描。Capsule sweep only.
FlowFieldOrCapsuleSweep先用流场插值,失败则回退胶囊扫描。Flow-field interpolation first, falling back to capsule sweep.
EIndividualPathfindingMode

个体寻路模式枚举(头文件已定义;当前实现中 FindPath 直接按 GenerationMode 分派,未读取该枚举)。

Individual pathfinding mode enum (defined in the header; the current implementation dispatches FindPath by GenerationMode and never reads this enum).

值 Value说明 Description
GridAStarGrid A*。Grid A*.
NavMeshNavMesh 寻路。NavMesh pathfinding.
None直接 / 无寻路。Direct / none.
ENavLinkQueryResult

NavLink 方向查询结果状态(QueryNavLinkDirection 返回)。

NavLink direction query result status (returned by QueryNavLinkDirection).

值 Value说明 Description
Success查询成功。Query succeeded.
NotFound缓存中未找到该 PolyRef 或条目无效。PolyRef not found in the cache or the entry is invalid.
InvalidPolyRefPolyRef 为 0。PolyRef is 0.
CacheNotInitializedNavLink 缓存尚未初始化(bNavLinkCacheInitialized 为 false)。NavLink cache not initialized yet (bNavLinkCacheInitialized is false).

结构体 Structs

FCellStruct USTRUCT (BlueprintType)

流场的核心格子数据结构。cost = 通行成本(255 = 不可通行),dist = 积分场距离(65535 = 未达),dir = 本格应走方向,type = 格子类型,gridCoord/goalCoord = 网格坐标与目标坐标,worldLoc/GoalWorldLoc = 世界位置,normal = 地面法线,NextPolyRef = NavMesh 模式下本格流向的多边形引用。

The core cell data structure of the flow field. cost = traversal cost (255 = impassable), dist = integration-field distance (65535 = unreached), dir = direction to go from this cell, type = cell type, gridCoord/goalCoord = grid coord and goal coord, worldLoc/GoalWorldLoc = world locations, normal = ground normal, NextPolyRef = the NavMesh poly ref this cell flows into.

成员变量 Members
名称 Name类型 Type默认值说明 Description
costuint8255格子成本(0 = 目标,255 = 障碍)。Cell cost (0 = goal, 255 = obstacle).
distint3265535积分场距离;65535 = 未计算/不可达。Integration field distance; 65535 = not computed / unreachable.
dirFVector3f(0,0,0)站在本格时应走的方向(流场方向)。Direction the pawn should go when standing on this cell.
typeECellTypeGround格子类型(见 ECellType)。Cell type (see ECellType).
gridCoordFIntVector(0,0,0)本格在网格上的坐标。Coordinate of this cell on the grid.
goalCoordFIntVector(0,0,0)本格流场最终通向的目标坐标。Goal coord this cell's flow leads to.
GoalWorldLocFVectorZeroVector目标的世界位置(供 string pulling / 查询返回)。World location of the goal (for string pulling / query returns).
worldLocFVector(0,0,0)本格中心的世界位置。World location of this cell's center.
normalFVector3f(0,0,1)地面法线(开启地面 trace 时由射线决定)。Ground up-vector, decided by line trace when ground tracing is enabled.
NextPolyRefint640本格流向的 NavMesh PolyRef(若适用)。The NavMesh poly ref this cell flows into (if applicable).
FNavLinkQueryData USTRUCT (BlueprintType)

QueryNavLinkDirection 返回的 NavLink 查询数据:方向、端点位置与「查询点是否靠近左/右端点」的判定。

NavLink query data returned by QueryNavLinkDirection: direction, endpoint locations, and whether the query point is near the left/right endpoint.

成员变量 Members
名称 Name类型 Type默认值说明 Description
DirectionTEnumAsByte<ENavLinkDirection::Type>BothWaysNavLink 通行方向。NavLink traversal direction.
bIsAtLeftEndboolfalse查询点是否在左端点 3 米内(或与左端地面多边形 PolyRef 匹配)。Whether the query point is within 3 m of the left endpoint (or matches the left ground poly ref).
bIsAtRightEndboolfalse查询点是否在右端点 3 米内(或与右端地面多边形 PolyRef 匹配)。Whether the query point is within 3 m of the right endpoint (or matches the right ground poly ref).
LeftEndpointFVectorZeroVector左端点世界位置。Left endpoint world location.
RightEndpointFVectorZeroVector右端点世界位置。Right endpoint world location.
SourceProxyNameFString空来源 NavLinkProxy 的 Actor 名。Name of the source NavLinkProxy actor.
FNavLinkInfo USTRUCT (BlueprintType)

NavLink 缓存信息(缓存键 = 链接多边形 PolyRef)。CollectNavLinkProxies 收集场景中的 NavLinkProxy,解析端点、方向、地面多边形引用后存入 NavLinkCache。

Cached NavLink information (cache key = link poly ref). CollectNavLinkProxies gathers NavLinkProxies from the scene, resolves endpoints, direction and ground poly refs, and stores them into NavLinkCache.

成员变量 Members
名称 Name类型 Type默认值说明 Description
LeftEndpointFVectorZeroVector左端点世界位置。Left endpoint world location.
RightEndpointFVectorZeroVector右端点世界位置。Right endpoint world location.
DirectionTEnumAsByte<ENavLinkDirection::Type>BothWays通行方向。Traversal direction.
SourceProxyTWeakObjectPtr<ANavLinkProxy>nullptr来源 NavLinkProxy 弱引用。Weak reference to the source NavLinkProxy.
LinkLengthfloat0.0f两端点距离(链接长度)。Distance between the endpoints (link length).
bIsValidboolfalse缓存条目是否有效。Whether the cache entry is valid.
LeftGroundPolyRefint640左端点投影到的地面多边形 PolyRef(收集时缓存)。Ground polygon poly ref the left endpoint projects onto (cached during CollectNavLinkProxies).
RightGroundPolyRefint640右端点投影到的地面多边形 PolyRef。Ground polygon poly ref the right endpoint projects onto.
FFlowFieldNavResult USTRUCT (BlueprintType)

QueryNavigation 系列 API 的返回结构——返回处理后的导航数据(方向、目标、有效性、距离),而非原始 FCellStruct。

Result struct of the QueryNavigation API family — processed navigation data (direction, goal, validity, distance) instead of raw FCellStruct.

成员变量 Members
名称 Name类型 Type默认值说明 Description
DirectionFVectorZeroVector插值后的流向(2D 归一化,Z = 0)。Interpolated flow direction (2D normalized, Z = 0).
GoalLocationFVectorZeroVector该流场通向的目标世界位置。World location of the goal this flow leads to.
bIsValidboolfalse查询是否成功(在流场边界内且格有效)。Whether the query succeeded (inside flow field bounds, valid cell).
bIsAtGoalboolfalse查询位置是否处于(或极接近)目标格。Whether the query location is at or very close to the goal cell.
DistanceToGoalint3265535到目标的积分场距离(可用于优先级排序)。Integration field distance to the goal (useful for prioritization).
SampledCellsHashuint320采样格子/多边形的哈希——用于检测采样组合变化(agent 移动采样到不同格时变化,即使插值方向相近)。Hash of sampled cells/polygons — detects when the sampled-cell combination changes (changes as the agent moves to different cells even if the interpolated direction is similar).
FFlowFieldTickContext USTRUCT (BlueprintType)

全局模拟 tick 的上下文(FFlowFieldGlobalTick 委托参数)。bAbortStep 由异步更新任务在超时截止时置位,用于通知宿主中止当前模拟步。

Context of the global simulation tick (FFlowFieldGlobalTick delegate argument). bAbortStep is set by async update tasks when the deadline is reached, telling the host to abort the current simulation step.

成员变量 Members
名称 Name类型 Type默认值说明 Description
DeltaTimefloat0.0f本步时间步长(秒)。This step's delta time (seconds).
bAbortStepboolfalse是否中止本模拟步(异步任务超时截止时置 true)。Whether to abort this simulation step (set true by async tasks when the deadline is hit).
FFlowFieldLayerHandle USTRUCT (BlueprintType)

流场层的轻量句柄。默认(INDEX_NONE)指代默认层;层 API 的创建/销毁/查询都通过该句柄引用层。

Lightweight handle referencing a flow field layer. The default (INDEX_NONE) refers to the default layer; the layer API refers to layers through this handle.

成员变量 Members
名称 Name类型 Type默认值说明 Description
LayerIDint32INDEX_NONE层 ID;IsValid() 判定 LayerID != INDEX_NONE。带 ==/!=/GetTypeHash。Layer ID; IsValid() checks LayerID != INDEX_NONE. Provides ==/!=/GetTypeHash.
FFlowCellOverlay USTRUCT

逐格流场叠加层——只存计算后的字段(dist/dir/goalCoord/GoalWorldLoc),不存静态格数据。层系统用它保存每层独立的计算结果。

Per-cell flow overlay — stores only the computed fields (dist/dir/goalCoord/GoalWorldLoc), not static cell data. The layer system uses it to hold each layer's independent computed results.

成员变量 Members
名称 Name类型 Type默认值说明 Description
distint3265535积分场距离。Integration field distance.
dirFVector3fZeroVector流向。Flow direction.
goalCoordFIntVector(0,0,0)目标坐标。Goal coord.
GoalWorldLocFVectorZeroVector目标世界位置。Goal world location.
FFlowFieldLayer USTRUCT (BlueprintType)

完整的流场层:拥有自己的目标与计算数据。Grid 模式用 GridOverlay(数组),NavMesh 模式用 NavMeshOverlay(PolyRef → 叠加)。bIsValid 标记层是否已计算。末尾三个字段是托管生命周期状态(仅运行时、不序列化,服务 MassBattle 引用计数层):在用的 MoveTo 任务数、自动回收标记与目标哈希复用键。

A complete flow field layer with its own goals and computed flow data. Grid mode uses GridOverlay (array); NavMesh mode uses NavMeshOverlay (PolyRef → overlay). bIsValid marks whether the layer has been computed. The last three fields are managed-lifecycle state (runtime only, NOT serialized — serving MassBattle refcounted layers): the live MoveTo-task count, the auto-release flag, and the goal-hash reuse key.

成员变量 Members
名称 Name类型 Type默认值说明 Description
LayerNameFName—层名称。Layer name.
LayerIDint32INDEX_NONE层 ID。Layer ID.
GoalLocationsTArray<FVector>空层的目标位置列表(策划可编辑)。Layer goal locations (editable).
GoalActorsTArray<TSoftObjectPtr<AActor>>空层的目标 Actor 列表(策划可编辑)。Layer goal actors (editable).
GridOverlayTArray<FFlowCellOverlay>空Grid 模式计算数据(逐格叠加)。Grid-mode computed data (per-cell overlay).
BaseDirArrayTArray<FVector3f>空Grid 模式方向修改前的基准方向(Erase 用)。Grid-mode base directions before direction modifiers (for Erase).
DirModifiedSetTSet<FIntVector>空Grid 模式被方向修改器改动的坐标集。Grid-mode coords modified by direction modifiers.
NavMeshOverlayTMap<int64, FFlowCellOverlay>空NavMesh 模式计算数据(PolyRef → 叠加)。NavMesh-mode computed data (PolyRef → overlay).
BaseNavMeshDirMapTMap<int64, FVector3f>空NavMesh 模式方向修改前的基准方向。NavMesh-mode base directions before direction modifiers.
NavMeshDirModifiedSetTSet<int64>空NavMesh 模式被方向修改器改动的 PolyRef 集。NavMesh-mode poly refs modified by direction modifiers.
GoalActorLocationsTArray<FVector>空解析后的目标 Actor 位置(UpdateLayer 时刷新)。Resolved goal actor locations (refreshed by UpdateLayer).
GoalGridCoordsTArray<FIntVector>空解析后的目标网格坐标。Resolved goal grid coords.
bIsValidboolfalse层是否已成功计算。Whether the layer has been computed successfully.
UserCountint320托管生命周期:在用本层的 MoveTo 任务数(任务侧 AcquireLayerUser/ReleaseLayerUser,每任务一引用,非按 agent——一个任务的 agent 共享一层且先于任务结束结算)。仅运行时、不序列化。Managed lifecycle: live MoveTo tasks holding this layer (task-side AcquireLayerUser/ReleaseLayerUser — one reference per task, not per agent: a task's agents share one layer and resolve before the task ends). Runtime only, not serialized.
bAutoReleaseboolfalse托管生命周期:自动回收标记。归零时经 ReleaseLayerUser 排入待销毁队列;手动 CreateLayer 创建的层保持手动生命周期(不会被自动回收)。Managed lifecycle: auto-release flag. When the count hits zero the layer is queued for deferred destruction by ReleaseLayerUser; manually created layers keep their manual lifecycle.
ManagedGoalHashuint320托管生命周期:GoalLocations 的确定性哈希(-0.0 规范化)——FindManagedLayerByGoalHash 按它查找复用托管层的键。Managed lifecycle: deterministic hash of GoalLocations (canonicalized -0.0) — the reuse key FindManagedLayerByGoalHash looks managed layers up by.
FFlowfieldScratchContext USTRUCT

A* 寻路的复用暂存上下文(带内置最小堆,无 STL/Algo 依赖)。Prepare 用递增的 CurrentSearchId 惰性清场(避免每帧清空数组),GetGScore/SetGScore/SetCameFrom 按搜索 ID 判定有效项;HeapPush/HeapPop 是手写最小堆。另含 NavMesh 查询的 dtNavMeshQuery 缓存。

Reusable scratch context for A* pathfinding with a built-in Min-Heap (no STL/Algo deps). Prepare lazily clears via an incrementing CurrentSearchId (avoiding per-frame array clears); GetGScore/SetGScore/SetCameFrom validate entries by search ID; HeapPush/HeapPop are a hand-written min-heap. Also caches a dtNavMeshQuery for NavMesh queries.

成员变量 Members
名称 Name类型 Type默认值说明 Description
CellSearchIdsTArray<int32>空每格所属搜索 ID(惰性清场标记)。Per-cell search ID (lazy-clear marker).
CurrentSearchIdint320当前搜索 ID,每次 Prepare 递增(回绕 0 时全量清零重建)。Current search ID, incremented per Prepare (on wrap to 0, arrays are fully re-initialized).
GScoreTArray<float>空每格 G 值。Per-cell G score.
CameFromTArray<FIntVector>空回溯路径的前驱坐标。Predecessor coords for path back-tracing.
OpenSetHeapTArray<FPriorityNode>空最小堆开集(FPriorityNode = Priority + Coord)。Min-heap open set (FPriorityNode = Priority + Coord).
PathCoordsTArray<FIntVector>空A* 回溯路径重建。A* back-trace path reconstruction.
NavQuerydtNavMeshQuery—NavMesh 查询缓存(按 LastNavMesh 惰性初始化)。NavMesh query cache (lazily initialized per LastNavMesh).
LastNavMeshconst dtNavMesh*nullptr上次初始化的 NavMesh 指针。The NavMesh the query was last initialized with.
方法 Methods
Prepare void (int32 NumCells)

为一次搜索做准备:按需扩容三个数组,递增 CurrentSearchId(回绕 0 时全量清零重建),重置堆与路径。

Prepares for a search: grows the three arrays when needed, increments CurrentSearchId (fully re-initializing on wrap to 0), and resets the heap and path.

Input
参数 Param类型 Type说明 Description
NumCellsint32格子总数(数组扩容目标)。Total cell count (array growth target).
Output

无返回值。副作用:重置搜索状态并递增搜索 ID。

No return value. Side effects: resets search state and increments the search ID.

GetGScore float (int32 Index) const

按搜索 ID 判定后返回格子的 G 值;不属于当前搜索的格子返回 FLT_MAX。

Returns the cell's G score when it belongs to the current search; cells of other searches return FLT_MAX.

Input
参数 Param类型 Type说明 Description
Indexint32格子索引。Cell index.
Output

返回 G 值;未访问过(非当前搜索)为 FLT_MAX。

Returns the G score; FLT_MAX when not visited by the current search.

SetGScore void (int32 Index, float Val)

写入格子 G 值并标记为当前搜索所属。

Writes the cell's G score and marks it as belonging to the current search.

Input
参数 Param类型 Type说明 Description
Indexint32格子索引。Cell index.
ValfloatG 值。G score.
Output

无返回值。副作用:写入 GScore 与搜索标记。

No return value. Side effects: writes GScore and the search marker.

SetCameFrom void (int32 Index, const FIntVector& FromCoord)

记录格子前驱坐标并标记为当前搜索所属。

Records the cell's predecessor coord and marks it as belonging to the current search.

Input
参数 Param类型 Type说明 Description
Indexint32格子索引。Cell index.
FromCoordconst FIntVector&前驱坐标。Predecessor coord.
Output

无返回值。副作用:写入 CameFrom 与搜索标记。

No return value. Side effects: writes CameFrom and the search marker.

HeapPush void (const FPriorityNode& Node)

最小堆插入:尾部追加后向上冒泡,保持父节点优先级 ≤ 子节点。

Min-heap insert: appends to the tail and bubbles up, keeping parent priority ≤ children.

Input
参数 Param类型 Type说明 Description
Nodeconst FPriorityNode&要插入的节点(Priority + Coord)。Node to insert (Priority + Coord).
Output

无返回值。副作用:堆新增一项。

No return value. Side effect: adds one entry to the heap.

HeapPop FPriorityNode

最小堆弹出:取堆顶,把末项移到根部后向下冒泡,返回最小优先级节点。假定堆非空(源码注释:Assumes Array is not empty)。

Min-heap pop: takes the top, moves the last entry to the root and bubbles down, returning the minimum-priority node. Assumes the array is not empty (per the source comment).

Input

无参数。

No parameters.

Output

返回堆顶 FPriorityNode。副作用:堆移除一项。

Returns the top FPriorityNode. Side effect: removes one entry from the heap.

委托 Delegates

名称 Name类型 Type说明 Description
FDoneTraceDelegateDECLARE_DYNAMIC_DELEGATE_OneParam(FCellStruct)单个异步 trace 完成的回调(绑定到 UpdateCellMap)。Callback when a single async trace completes (bound to UpdateCellMap).
FDoneAllTracesDelegateDECLARE_DYNAMIC_DELEGATE全部异步 trace 完成的回调(绑定到 AsyncUpdateStep2)。Callback when all async traces finish (bound to AsyncUpdateStep2).
FDoneUpdateDelegateDECLARE_DYNAMIC_MULTICAST_DELEGATE异步更新完成的多播委托(UUpdateFlowFieldAsyncAction::OnCompleted 蓝图输出)。Multicast delegate for async update completion (UUpdateFlowFieldAsyncAction::OnCompleted blueprint output).
FFlowFieldGlobalTickDECLARE_MULTICAST_DELEGATE_OneParam(FFlowFieldTickContext&)全局模拟 tick 多播(AFlowField::OnSimulationTick 静态成员)。异步更新任务在「限 tick 完成」模式下订阅它轮询 future。Global simulation tick multicast (static member AFlowField::OnSimulationTick). Async update tasks subscribe to it in tick-limited mode to poll their futures.

AFlowField UCLASS

流场 Actor——整个系统的核心。负责:环境查询与建格(Grid)/Detour 网格单元化(NavMesh)、Dijkstra 积分场 + 方向场计算、成本/方向修改器编排、调试可视化(DrawCells/DrawArrows)、运行时导航查询(QueryNavigation 系列)、个体寻路(FindPath 系列)、NavLink 缓存与 Layer 层系统(含托管层生命周期)、运行时 modifier 推模式注册,以及锁步基底同步(导出/导入/差分/复制品寻路)。构造时创建 Volume(盒体边界)、ISM_Arrows(箭头实例化网格)、Decal_Cells(格子贴花)与 Billboard 组件。BeginPlay 注册进静态 LiveInstances 表并收编同世界 modifier;EndPlay/BeginDestroy 释放同步复制品。静态成员 OnSimulationTick 供异步更新在模拟 tick 中轮询。

The flow field actor — the core of the whole system. Responsible for: environment queries and grid creation (Grid) / Detour mesh cell mapping (NavMesh), Dijkstra integration + direction field computation, cost/direction modifier orchestration, debug visualization (DrawCells/DrawArrows), runtime navigation queries (QueryNavigation family), individual pathfinding (FindPath family), NavLink caching, the layer system (with the managed layer lifecycle), push-model runtime modifier registration, and lockstep substrate sync (export/import/delta/replica pathfinding). The constructor creates Volume (box bounds), ISM_Arrows (instanced arrow mesh), Decal_Cells (cell decal) and Billboard components. BeginPlay registers into the static LiveInstances table and adopts same-world modifiers; EndPlay/BeginDestroy free the synced replica. The static OnSimulationTick lets async updates poll during simulation ticks.

继承 Inheritance

AActor → AFlowField

公开方法 Public Methods

AFlowField 构造函数

启用每帧 Tick;创建默认场景根与四个组件:Volume(无碰撞盒体,不参与导航)、ISM_Arrows(无碰撞、无阴影、不接收贴花、不参与导航的方向箭头实例化网格)、Decal_Cells(格子贴花,相对旋转 (90,0,0))、Billboard(编辑器图标)。

Enables per-frame tick; creates the default scene root and four components: Volume (non-colliding box, no navigation participation), ISM_Arrows (non-colliding, no shadows, no decals, no navigation — instanced arrow mesh), Decal_Cells (cell decal, relative rotation (90,0,0)), and Billboard (editor icon).

Input

无参数。

No parameters.

Output

无返回值。副作用:创建根组件与四个可视化/边界组件。

No return value. Side effects: creates the root and four visualization/bounds components.

OnConstruction virtual void (const FTransform& Transform)

编辑器构造回调:调用父类后调用 DrawDebug()——编辑器里改动配置即触发整条生成管线重算。

Editor construction callback: calls the parent, then DrawDebug() — touching configuration in the editor triggers a full generation-pipeline recalculation.

Input
参数 Param类型 Type说明 Description
Transformconst FTransform&构造变换,透传给父类。Construction transform; forwarded to the parent.
Output

无返回值。副作用:触发流场重算与可视化重绘(DrawDebug)。

No return value. Side effects: triggers flow field recalculation and visualization redraw (DrawDebug).

Tick virtual void (float DeltaSeconds)

每帧回调(构造函数启用 Tick)。当前唯一逻辑:当 drawGraphEdgesInGame 开启且本场为已导入基底的 NavMesh 同步场时,逐帧绘制复制品的真实多边形轮廓(锁步端真正寻路的网格,而非引擎 navmesh):银色 = 普通地面多边形(区域代价 1),橙色 = 代价被 modifier 改动的地面多边形,品红线段 = NavLink(离网连接端点连线)。单帧调试线(无累积),大网格开销高,需显式开启。仅 Game/PIE 世界绘制。

Per-frame callback (tick enabled by the constructor). Its only current logic: with drawGraphEdgesInGame on and this field being a synced NavMesh field with an imported substrate, draws per-frame one-shot debug lines of the replica's actual polygon outlines (the mesh the lockstep peers really path over — not the engine navmesh): silver = normal ground poly (area cost 1), orange = ground poly whose cost was touched by a modifier, magenta segment = NavLink (off-mesh connection endpoints). No accumulation; heavy on large meshes and strictly opt-in. Draws in Game/PIE worlds only.

Input
参数 Param类型 Type说明 Description
DeltaSecondsfloat本帧时间步长(秒),透传给父类,当前未使用。Frame delta time in seconds; forwarded to the parent, currently unused.
Output

无返回值。副作用:按开关绘制复制品轮廓调试线。

No return value. Side effect: draws the replica outline debug lines per the toggle.

DrawDebug void (CallInEditor, BlueprintCallable)

编辑器调试入口:先 InitFlowField(Construction),在 bEditorLiveUpdate 开启时执行完整重算管线——GetGoalLocation → GetAllModifiers → Grid 分支(CreateGrid → ModifyGrid → ModifyCost → CalculateFlowField → 存 BaseDirArray → ModifyFlowField → DrawCells → DrawArrows)/NavMesh 分支(CalculateFlowField_NavMesh → 存 BaseNavMeshDirMap → ModifyFlowField_NavMesh → DrawArrows → DebugDrawNavMeshAreaCosts)。

Editor debug entry: first InitFlowField(Construction); with bEditorLiveUpdate on, runs the full recalculation pipeline — GetGoalLocation → GetAllModifiers → Grid branch (CreateGrid → ModifyGrid → ModifyCost → CalculateFlowField → store BaseDirArray → ModifyFlowField → DrawCells → DrawArrows) / NavMesh branch (CalculateFlowField_NavMesh → store BaseNavMeshDirMap → ModifyFlowField_NavMesh → DrawArrows → DebugDrawNavMeshAreaCosts).

Input

无参数。

No parameters.

Output

无返回值。副作用:按当前配置重算流场并重绘可视化。

No return value. Side effects: recalculates the field with current settings and redraws the visualization.

UpdateFlowField void (bool bFullRebuild)

运行时完整更新入口(同步)。bFullRebuild 为 true 时从环境查询重建整张网格,并重扫 modifier(重扫基底 = 运行时注册,Include/Attach 条目在其上合并去重——重扫不再抹掉运行时注册);否则沿用现有网格,只整合目标/修改器变化后重算。流程与 DrawDebug 一致,初始化模式按 bIsBeginPlay 取 BeginPlay/Runtime。末尾 bIsBeginPlay = false。Grid 模式下 bFullRebuild 时跳过 ModifyGrid(全新网格不含修改)。同步场守卫:已导入基底(bSyncedSubstrate)时——NavMesh 模式任何端都只在导入复制品上重洪泛方向(目标/修改器刷新,绝不触碰基底字节;目标取流内快照),客户端 Grid 场的本地构建被忽略(一次性 Warning),服务器重建 Grid 场则退出同步模式(需重新导出基底)。

Runtime full-update entry (synchronous). With bFullRebuild true, rebuilds the entire grid from environment queries and rescans modifiers (the rescan base = runtime registrations, with Include/Attach entries merged on top, deduplicated — rescans no longer wipe runtime registrations); otherwise reuses the existing grid, integrating only goal/modifier changes before recalculating. The flow matches DrawDebug, with the init mode picked as BeginPlay/Runtime from bIsBeginPlay. Ends with bIsBeginPlay = false. In Grid mode a full rebuild skips ModifyGrid (the fresh grid carries no modifications). Synced-field guard: with an imported substrate (bSyncedSubstrate) — NavMesh mode re-floods directions on the imported replica on ANY peer (goal/modifier refresh; substrate bytes are never touched; goals come from the stream snapshot), a client-side Grid build is ignored (one-shot Warning), and a server-side Grid rebuild leaves synced mode (re-export the substrate to re-sync).

Input
参数 Param类型 Type说明 Description
bFullRebuildbool是否整格重建(默认 false);true 时也重新收集运行时生成的 modifier。Whether to rebuild the entire grid (default false); true also recollects runtime-spawned modifiers.
Output

无返回值。副作用:重算流场数据并更新可视化;清 bIsBeginPlay 标记。

No return value. Side effects: recalculates flow field data and updates visualization; clears the bIsBeginPlay marker.

TickFlowField void (bool bFullRebuild)

定时更新入口:nextTickTimeLeft <= 0 时调用 UpdateFlowField(bFullRebuild),随后调用 UpdateTimer() 推进定时器(间隔 = RefreshInterval,按世界 DeltaSeconds 倒计时)。

Timed update entry: calls UpdateFlowField(bFullRebuild) when nextTickTimeLeft <= 0, then UpdateTimer() to advance the timer (interval = RefreshInterval, counted down by world delta seconds).

Input
参数 Param类型 Type说明 Description
bFullRebuildbool是否整格重建,透传给 UpdateFlowField。Whether to full-rebuild; forwarded to UpdateFlowField.
Output

无返回值。副作用:到达间隔时触发一次流场更新;推进定时器。

No return value. Side effects: triggers a field update when the interval elapses; advances the timer.

IsValidPath bool (const FVector& StartLocation, const FVector& EndLocation)

检查两点间路径是否有效。已导入基底的 NavMesh 同步场:经复制品 A*(FindPathReplica)测试,绝不查引擎;普通 NavMesh 模式:用 TestPathSync 在导航系统上做同步可达性测试;Grid 模式:不做完整寻路(成本太高),仅验证两端点都是有效格子且非障碍(type != Obstacle 且 cost != 255)。

Checks whether a path from Start to End is valid. A synced NavMesh field with an imported substrate tests via the replica A* (FindPathReplica), never the engine; regular NavMesh mode: synchronous reachability test via TestPathSync on the navigation system; Grid mode: no full pathfinding (too expensive for a reachability check), only verifies both endpoints are valid non-obstacle cells (type != Obstacle and cost != 255).

Input
参数 Param类型 Type说明 Description
StartLocationconst FVector&起点世界位置。Start world location.
EndLocationconst FVector&终点世界位置。End world location.
Output

返回路径是否有效。NavMesh 模式无导航系统时返回 false;Grid 模式两端点任一无有效格或为障碍时返回 false。

Returns whether the path is valid. NavMesh mode returns false without a navigation system; Grid mode returns false when either endpoint is invalid or an obstacle.

GetRecastNavMesh ARecastNavMesh* const

解析并缓存 RecastNavMesh:① 缓存命中直接返回;② 非游戏线程返回 nullptr(缓存仅限游戏线程写入);③ TargetNavMeshName 非空时按名字搜索场景中的 RecastNavMesh;④ 未找到回退到导航系统默认 NavMesh;⑤ 找到后写入 CachedRecastNavMesh(const_cast 缓存)。

Resolves and caches the RecastNavMesh: ① returns the cache on hit; ② returns nullptr off the game thread (cache writes are game-thread only); ③ with a non-empty TargetNavMeshName, searches the scene by name; ④ falls back to the navigation system's default NavMesh; ⑤ caches the result into CachedRecastNavMesh (via const_cast).

Input

无参数。

No parameters.

Output

返回 RecastNavMesh 指针;找不到或非游戏线程时为 nullptr。副作用:写入缓存。

Returns the RecastNavMesh pointer, or nullptr when not found or off the game thread. Side effect: fills the cache.

ReportNavMeshFlowFieldMissing void (const FString& Reason)

NavMesh 模式「未能生成流场」的诊断入口:递增 NavMeshFlowMissingStreak,仅当失败连续持续(达到 3 次)且尚未记录过时,输出一条 LogTemp Error 日志(含原因与连续失败次数)。world/地图加载期间的单次失败(导航系统或 navmesh 尚未就绪)是预期瞬态,保持静默;成功生成一次后清零重置(重新武装)。由 CalculateFlowField_NavMesh 的各失败分支调用。

Diagnostics entry for "NavMesh mode produced no flow field": increments NavMeshFlowMissingStreak and — only when the failure persists (streak reaches 3) and hasn't been logged yet — emits one LogTemp Error (with the reason and the streak count). Single-shot failures during world/map init (navigation system or navmesh not ready yet) are expected transients and stay silent; a successful generation resets the counters (re-arms). Called from the failure branches of CalculateFlowField_NavMesh.

Input
参数 Param类型 Type说明 Description
Reasonconst FString&失败原因描述,写入日志。Failure reason text, included in the log.
Output

无返回值。副作用:递增连续失败计数;达阈值时置一次性日志标记并输出 Error。

No return value. Side effects: increments the streak counter; past the threshold, sets the one-shot log flag and emits the Error.

WarnNavMeshNoGoals void

NavMesh 模式未配置目标的一次性 LogTemp Warning:此时不生成任何流向——这是合法用法(流场仅作高度场/个体寻路使用);如需流向请配置 GoalActors/GoalLocations。由 CalculateFlowField_NavMesh 在目标集为空时调用,成功生成后重置可再次告警。

One-shot LogTemp Warning for NavMesh mode with no goals configured: no flow directions are produced — this is legal usage (the flow field serves as a height field / individual pathfinding only); add GoalActors/GoalLocations if flow directions are needed. Called by CalculateFlowField_NavMesh when the goal set is empty; reset by a successful generation so it can warn again.

Input

无参数。

No parameters.

Output

无返回值。副作用:首次调用置 bNavMeshNoGoalsWarned 并输出 Warning。

No return value. Side effect: sets bNavMeshNoGoalsWarned and logs the Warning on the first call.

WorldToGrid bool (const FVector& Location, FIntVector& OutGridCoord)

世界位置 → 网格坐标。把位置变换到 Actor 的相对系(旋转 -actorRot.Yaw + offsetLoc),按 cellSize 取整;越界时返回 false 但输出仍钳制到 [0, xNum-1] × [0, yNum-1]。

World location → grid coord. Transforms the location into the actor's relative frame (rotate -actorRot.Yaw + offsetLoc) and rounds by cellSize; out of bounds returns false while the output is still clamped to [0, xNum-1] × [0, yNum-1].

Input
参数 Param类型 Type说明 Description
Locationconst FVector&世界位置。World location.
OutGridCoordFIntVector&输出网格坐标(Z 恒为 0)。Output grid coord (Z always 0).
Output

返回位置是否在网格内;无论是否在内,输出坐标都会被钳制到合法边界。

Returns whether the location is inside the grid; the output coord is always clamped to valid bounds either way.

WorldToIndex bool (const FVector& Location, int32& OutIndex)

世界位置 → 格子数组索引。经 WorldToGrid(钳制)+ CoordToIndex 计算;网格未初始化(bIsBeginPlay)时输出 0 并返回 false;越界时索引钳制到 [0, CellCount-1] 但返回 false。

World location → cell array index. Computed via WorldToGrid (clamping) + CoordToIndex; when the grid is uninitialized (bIsBeginPlay) outputs 0 and returns false; out of bounds clamps the index to [0, CellCount-1] but returns false.

Input
参数 Param类型 Type说明 Description
Locationconst FVector&世界位置。World location.
OutIndexint32&输出索引(越界钳制)。Output index (clamped when out of bounds).
Output

返回索引是否有效(未钳制前);网格未初始化时为 false 且输出 0。

Returns whether the index is valid (before clamping); false with output 0 when the grid is uninitialized.

CoordToIndex int32 (const FIntVector& GridCoord)

网格坐标 → 数组索引:Z 忽略,X * yNum + Y。NavMesh 模式恒返回 0。

Grid coord → array index: Z ignored, X * yNum + Y. Always returns 0 in NavMesh mode.

Input
参数 Param类型 Type说明 Description
GridCoordconst FIntVector&网格坐标。Grid coord.
Output

返回数组索引;NavMesh 模式返回 0。调用方负责越界检查。

Returns the array index; 0 in NavMesh mode. Callers are responsible for bounds checks.

GetCellAtLocation FCellStruct& (const FVector& Location, bool& bOutIsValid, FVector SearchExtent)

取世界位置对应的格子引用。NavMesh 模式:把位置投影到导航网格(ProjectPointToNavigation,extent 默认取 PathStopSearchDist,水平 500 兜底),跳过 off-mesh 连接,从 NavMeshCellMap 按 NodeRef 查找;Grid 模式:钳制坐标取 CurrentCellsArray 中对应格,越界时仍返回钳制格的引用但 bOutIsValid = false(注释说明钳制格数据有效)。网格未初始化时返回 DefaultCell 且无效。

Returns the cell reference at a world location. NavMesh mode: projects the location onto the nav mesh (ProjectPointToNavigation, default extent from PathStopSearchDist with a 500 horizontal fallback), skips off-mesh connections, and looks up NavMeshCellMap by NodeRef; Grid mode: clamps the coord and returns the corresponding CurrentCellsArray cell — out of bounds still returns the clamped cell's reference with bOutIsValid = false (the comment notes clamped cell data is valid). Returns DefaultCell (invalid) when the grid is uninitialized.

Input
参数 Param类型 Type说明 Description
Locationconst FVector&世界位置。World location.
bOutIsValidbool&输出:查询是否有效。Output: whether the query is valid.
SearchExtentFVectorNavMesh 投影范围(可选,默认 ZeroVector = 用 PathStopSearchDist)。NavMesh projection extent (optional; ZeroVector = use PathStopSearchDist).
Output

返回格子引用(无效时为 DefaultCell 引用);同时写 bOutIsValid。

Returns the cell reference (DefaultCell when invalid); also writes bOutIsValid.

GetCellAtCoord FCellStruct& (const FIntVector& Coord, bool& bOutIsValid)

取网格坐标对应的格子引用。NavMesh 模式:CurrentCellsArray 非空时返回第 0 项(占位目标格);Grid 模式:坐标与索引都有效时返回对应格,越界钳制返回但 bOutIsValid = false。

Returns the cell reference for a grid coord. NavMesh mode: returns element 0 of CurrentCellsArray (the placeholder goal cell) when non-empty; Grid mode: returns the cell when both the coord and index are valid; out of bounds returns the clamped cell with bOutIsValid = false.

Input
参数 Param类型 Type说明 Description
Coordconst FIntVector&网格坐标。Grid coord.
bOutIsValidbool&输出:是否有效。Output: whether valid.
Output

返回格子引用(无效时为 DefaultCell);同时写 bOutIsValid。

Returns the cell reference (DefaultCell when invalid); also writes bOutIsValid.

GetAverageDirection FVector (const FVector& Location, const float Radius, bool& bOutIsValid)

取位置周围半径内的平均流场方向。Grid 模式:遍历半径覆盖的格子(用格边界相交检测),对与圆相交的格方向求和平均(Z 清零归一化);无有效格时按 PathStopSearchDist.X 做环形螺旋搜索最近 Ground 格,返回指向它的方向。NavMesh 模式:直接返回该位置的精确方向;投影失败时按 PathStopSearchDist 搜索最近 NavMesh 点并返回指向它的方向。均失败返回零向量。

Returns the average flow field direction within a radius around a location. Grid mode: walks the cells the circle covers (cell-boundary intersection test), sums and averages the directions of intersecting cells (Z zeroed then normalized); with no valid cells, spiral-searches the nearest Ground cell within PathStopSearchDist.X and returns the direction toward it. NavMesh mode: returns the exact direction at the location; when projection fails, searches the nearest NavMesh point within PathStopSearchDist and returns the direction toward it. Returns a zero vector when everything fails.

Input
参数 Param类型 Type说明 Description
Locationconst FVector&查询位置。Query location.
Radiusconst float平均半径。Averaging radius.
bOutIsValidbool&输出:是否取到有效方向。Output: whether a valid direction was found.
Output

返回平均方向(2D 归一化);失败返回零向量并写 bOutIsValid = false。

Returns the averaged direction (2D normalized); zero vector with bOutIsValid = false on failure.

QueryNavigation FFlowFieldNavResult (const FVector& Location, FVector SearchExtent)

单格导航查询的便捷入口:直接转发到 QueryNavigationAdvanced(Location, 0.0f, SearchExtent, nullptr)。

Convenience entry for single-cell navigation queries: forwards directly to QueryNavigationAdvanced(Location, 0.0f, SearchExtent, nullptr).

Input
参数 Param类型 Type说明 Description
Locationconst FVector&查询世界位置。Query world location.
SearchExtentFVectorNavMesh 投影范围(可选,默认零向量 = 用 PathStopSearchDist)。NavMesh projection extent (optional; zero vector = use PathStopSearchDist).
Output

返回 FFlowFieldNavResult。

Returns an FFlowFieldNavResult.

QueryNavigationAdvanced FFlowFieldNavResult (const FVector& Location, float SearchRadius, FVector SearchExtent, FFlowfieldScratchContext* Context)

高级导航查询(半径插值)。NavMesh 模式:① 投影到网格,跳过 off-mesh 连接;② SearchRadius = 0 单格返回 dir/GoalWorldLoc/dist;③ > 0 时用 findPolysAroundCircle 收集附近多边形(复用 Context 的 dtNavMeshQuery 或栈上新建),按到共享边距离(直接邻居)或最近点(兜底)加权平均方向,SampledCellsHash 为采样多边形哈希;④ 投影失败按 PathStopSearchDist 兜底投影。Grid 模式:① 未初始化返回无效;② 单格查询(钳制格,数据有效);③ 半径查询——按格中心二维距离加权平均(权重 1/(1+d/R)),跳过 cost ≥ 255 或非 Ground 格,hash 为采样索引组合;④ 无命中时环形螺旋搜索最近 Ground 格。`

Advanced navigation query with radius-based interpolation. NavMesh mode: ① projects onto the mesh, skipping off-mesh connections; ② SearchRadius = 0 returns the single cell's dir/GoalWorldLoc/dist; ③ with > 0, collects nearby polygons via findPolysAroundCircle (reusing the Context's dtNavMeshQuery or a stack query), weighting by distance to the shared edge (direct neighbors) or the closest point (fallback); SampledCellsHash hashes the sampled polygons; ④ on projection failure, falls back via PathStopSearchDist. Grid mode: ① uninitialized returns invalid; ② single-cell query (clamped cell, data valid); ③ radius query — 2D distance-weighted average by cell center (weight 1/(1+d/R)), skipping cost ≥ 255 or non-Ground cells, hash combines sampled indices; ④ with no hits, spiral-searches the nearest Ground cell.

Input
参数 Param类型 Type说明 Description
Locationconst FVector&查询世界位置。Query world location.
SearchRadiusfloat0 = 单格查询;>0 = 半径内加权平均。0 = single cell; >0 = weighted average within the radius.
SearchExtentFVectorNavMesh 投影范围(可选)。NavMesh projection extent (optional).
ContextFFlowfieldScratchContext*性能用暂存上下文(可选,复用 dtNavMeshQuery)。Scratch context for performance (optional; reuses the dtNavMeshQuery).
Output

返回 FFlowFieldNavResult(失败时 bIsValid = false,方向为零向量,DistanceToGoal = 65535)。

Returns an FFlowFieldNavResult (bIsValid = false, zero direction, DistanceToGoal = 65535 on failure).

CreateLayer FFlowFieldLayerHandle (FName LayerName, const TArray<FVector>& InGoalLocations, const TArray<TSoftObjectPtr<AActor>>& InGoalActors)

创建新层:分配 NextLayerID++ 的 ID,保存层名与目标,存入 FlowFieldLayers,返回句柄。注意创建后需调用 UpdateLayer 计算。

Creates a new layer: allocates an ID from NextLayerID++, stores the name and goals, inserts into FlowFieldLayers, and returns the handle. Note UpdateLayer must be called afterwards to compute it.

Input
参数 Param类型 Type说明 Description
LayerNameFName层名称。Layer name.
InGoalLocationsconst TArray<FVector>&目标位置列表。Goal locations.
InGoalActorsconst TArray<TSoftObjectPtr<AActor>>&目标 Actor 列表。Goal actors.
Output

返回新层的句柄。副作用:分配一个层 ID 并加入 FlowFieldLayers。

Returns the new layer's handle. Side effects: allocates a layer ID and adds the layer to FlowFieldLayers.

DestroyLayer void (FFlowFieldLayerHandle Handle)

销毁层并释放其数据(从 FlowFieldLayers 移除)。无效句柄静默无操作。

Destroys a layer and frees its data (removes it from FlowFieldLayers). Invalid handles are silent no-ops.

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle要销毁的层句柄。Handle of the layer to destroy.
Output

无返回值。副作用:移除层数据。

No return value. Side effect: removes the layer data.

IsLayerValid bool const (FFlowFieldLayerHandle Handle)

检查层句柄是否有效:句柄自身有效且 FlowFieldLayers 中存在该 ID。

Checks whether a layer handle is valid: the handle is valid and the ID exists in FlowFieldLayers.

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle层句柄。Layer handle.
Output

返回句柄是否有效。

Returns whether the handle is valid.

SetLayerGoals void (FFlowFieldLayerHandle Handle, const TArray<FVector>& InGoalLocations, const TArray<TSoftObjectPtr<AActor>>& InGoalActors)

更新已有层的目标并置 bIsValid = false 使其失效——之后需调用 UpdateLayer 重算。无效句柄输出 Warning 日志。

Updates an existing layer's goals and invalidates it (bIsValid = false) — call UpdateLayer afterwards to recalculate. Invalid handles emit a Warning log.

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle层句柄。Layer handle.
InGoalLocationsconst TArray<FVector>&新目标位置。New goal locations.
InGoalActorsconst TArray<TSoftObjectPtr<AActor>>&新目标 Actor。New goal actors.
Output

无返回值。副作用:更新目标并使层失效;无效句柄输出 LogTemp Warning。

No return value. Side effects: updates the goals and invalidates the layer; invalid handles emit a LogTemp Warning.

UpdateLayer void (FFlowFieldLayerHandle Handle)

(重)计算指定层(同步)。流程:解析目标 Actor 位置 → 与目标位置合并;无目标则置无效返回。Grid 模式:目标转网格坐标(钳制,含网格外),把 CurrentCellsArray 拷贝到临时数组并清零计算字段,以层目标调用 CalculateFlowField,提取 GridOverlay/BaseDirArray,再套用方向修改器写回。NavMesh 模式:目标投影到网格多边形(ProjectPointToNavigation),以层目标调用 CalculateNavMeshFlow,提取 NavMeshOverlay/BaseNavMeshDirMap,套用方向修改器。成功置 bIsValid = true。默认层(网格/导航)必须先初始化。

(Re)computes a layer synchronously. Flow: resolves goal actor locations → merges with goal locations; no goals → invalid and return. Grid mode: converts goals to grid coords (clamped, including off-grid), copies CurrentCellsArray into a temp array with computed fields zeroed, runs CalculateFlowField with the layer's goals, extracts GridOverlay/BaseDirArray, then applies the direction modifiers back. NavMesh mode: projects goals onto the mesh (ProjectPointToNavigation), runs CalculateNavMeshFlow with the layer's goals, extracts NavMeshOverlay/BaseNavMeshDirMap, applies the direction modifiers. Sets bIsValid = true on success. The default layer (grid/navmesh) must already be initialized.

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle层句柄;无效时输出 Warning 并返回。Layer handle; invalid handles warn and return.
Output

无返回值。副作用:填充层的计算数据并置 bIsValid;无目标/无效句柄时输出 Warning。

No return value. Side effects: fills the layer's computed data and sets bIsValid; warns on no goals / invalid handles.

QueryNavigationLayer FFlowFieldNavResult (const FVector& Location, FFlowFieldLayerHandle LayerHandle, FVector SearchExtent)

单格查询指定层:转发到 QueryNavigationAdvancedLayer(Location, LayerHandle, 0.0f, SearchExtent, nullptr)。

Single-cell query on a specific layer: forwards to QueryNavigationAdvancedLayer(Location, LayerHandle, 0.0f, SearchExtent, nullptr).

Input
参数 Param类型 Type说明 Description
Locationconst FVector&查询位置。Query location.
LayerHandleFFlowFieldLayerHandle目标层句柄。Target layer handle.
SearchExtentFVectorNavMesh 投影范围(可选)。NavMesh projection extent (optional).
Output

返回 FFlowFieldNavResult。

Returns an FFlowFieldNavResult.

QueryNavigationAdvancedLayer FFlowFieldNavResult (const FVector& Location, FFlowFieldLayerHandle LayerHandle, float SearchRadius, FVector SearchExtent, FFlowfieldScratchContext* Context)

指定层的高级查询。层不存在或未计算(bIsValid = false)时返回无效。NavMesh 模式:投影位置后从 Layer->NavMeshOverlay 按 NodeRef 取叠加数据(无半径插值)。Grid 模式:单格查询取 GridOverlay[Index];半径查询按格中心二维距离加权平均(权重 1/(1+d/R)),跳过 cost == 255 或 dist == 65535 的格子,最近格决定目标信息。

Advanced query on a specific layer. Invalid when the layer is missing or not computed (bIsValid = false). NavMesh mode: projects the location and reads the overlay from Layer->NavMeshOverlay by NodeRef (no radius interpolation). Grid mode: single-cell query reads GridOverlay[Index]; radius query computes a 2D distance-weighted average by cell center (weight 1/(1+d/R)), skipping cells with cost == 255 or dist == 65535, with the closest cell deciding the goal metadata.

Input
参数 Param类型 Type说明 Description
Locationconst FVector&查询位置。Query location.
LayerHandleFFlowFieldLayerHandle目标层句柄。Target layer handle.
SearchRadiusfloat0 = 单格;>0 = 半径加权平均(Grid 模式)。0 = single cell; >0 = radius weighted average (Grid mode).
SearchExtentFVectorNavMesh 投影范围(可选,零向量 = 500 兜底)。NavMesh projection extent (optional; zero vector falls back to 500).
ContextFFlowfieldScratchContext*暂存上下文(当前实现未使用,预留)。Scratch context (unused in the current implementation; reserved).
Output

返回 FFlowFieldNavResult;层无效/投影失败时 bIsValid = false。

Returns an FFlowFieldNavResult; bIsValid = false when the layer is invalid or projection fails.

AcquireLayerUser bool (FFlowFieldLayerHandle Handle)

为层增加一个使用者(一个 MoveTo 任务)——按任务计数,非按 agent:任务的 agent 共享一层,先于任务结束统一结算。层不存在时输出 LogTemp Warning 并返回 false。

Acquires one layer user (one MoveTo task) — task-level counting, not per agent: a task's agents share one layer and resolve before the task ends. A missing layer logs a LogTemp Warning and returns false.

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle要获取的层句柄。Layer to acquire.
Output

返回是否成功;层存活时递增 UserCount。副作用:计数 +1。

Returns success; increments UserCount on a live layer. Side effect: count +1.

ReleaseLayerUser bool (FFlowFieldLayerHandle Handle)

释放一个层使用者。托管(自动回收)层计数归零时入队待销毁(PendingLayerDestroys),绝不即时删除——并行移动阶段的 worker 线程还在读 FlowFieldLayers;冲刷时会复查计数,期间被重新 Acquire 的层得以存活(如 resync 后任务重建重新取层)。层不存在或计数已为 0(重复释放/未获取就释放)时输出 Warning 并返回 false,计数钳制不为负。

Releases one layer user. When an auto-release (managed) layer's count reaches 0 it is QUEUED for deferred destruction (PendingLayerDestroys), never removed inline — worker threads query FlowFieldLayers during the parallel move stages; the flush re-checks the count, so a layer re-acquired meanwhile survives (e.g. task rebuild after resync re-acquires its layers). A missing layer, or a count already at 0 (double release / release without acquire), warns and returns false with the count clamped at zero.

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle要释放的层句柄。Layer to release.
Output

返回是否成功。副作用:计数 -1;托管层归零时把 LayerID 加入待销毁队列。

Returns success. Side effects: count -1; a managed layer hitting zero queues its LayerID for deferred destruction.

FlushAllPendingLayerDestroys static void

待销毁层的静态冲刷:遍历 LiveInstances 中全部存活实例(顺手清理失效弱引用),逐个调用其 FlushPendingLayerDestroys。必须在并行移动阶段之外的游戏线程串行窗口执行——由 UMassBattleSubsystem 在其串行窗口调用(任务重建窗口内抑制)。

Static drain of pending layer destroys: iterates every live instance in LiveInstances (pruning stale weak references along the way) and calls each one's FlushPendingLayerDestroys. MUST run on the game thread OUTSIDE the parallel move stages — called by UMassBattleSubsystem from its serial window (suppressed during the task-rebuild window).

Input

无参数。

No parameters.

Output

无返回值。副作用:移除仍归零的托管层、清空待销毁队列、清理实例表。

No return value. Side effects: removes managed layers still at zero, clears the pending queue, prunes the instance registry.

CreateManagedLayer FFlowFieldLayerHandle (FName LayerName, const TArray<FVector>& InGoalLocations, uint32 GoalHash)

创建托管(自动回收)层:经 CreateLayer 创建后标记 bAutoRelease 与 ManagedGoalHash,并同步 UpdateLayer 计算。LayerName 为 None 时自动由哈希命名(MBManaged_<hash>)。GoalHash 为 0 或目标为空时返回无效句柄。

Creates a managed (auto-release) layer: creates it via CreateLayer, stamps bAutoRelease and ManagedGoalHash, then computes synchronously with UpdateLayer. A None LayerName auto-derives from the hash (MBManaged_<hash>). A zero GoalHash or empty goals returns an invalid handle.

Input
参数 Param类型 Type说明 Description
LayerNameFName层名称;None 时自动命名。Layer name; auto-derived from the hash when None.
InGoalLocationsconst TArray<FVector>&目标世界位置列表。Goal world locations.
GoalHashuint32目标的确定性哈希(复用键);0 拒绝创建。Deterministic hash of the goals (reuse key); 0 refuses creation.
Output

返回新层句柄(失败为无效句柄)。副作用:创建并同步计算托管层。

Returns the new layer's handle (invalid on failure). Side effects: creates and synchronously computes the managed layer.

UpdateManagedLayerGoals bool (FFlowFieldLayerHandle Handle, const TArray<FVector>& InGoalLocations, uint32 GoalHash)

更新托管层的目标 + 哈希并同步重算——单用 SetLayerGoals 会留下一段失效窗(它只置失效不重算),本函数在同一调用内闭合。层不存在或 GoalHash 为 0 时返回 false。

Updates a managed layer's goals + hash and recomputes synchronously — SetLayerGoals alone leaves an invalid window (it only invalidates), which this closes in one call. Returns false for a missing layer or a zero GoalHash.

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle要更新的层句柄。Layer to update.
InGoalLocationsconst TArray<FVector>&新目标世界位置列表。New goal world locations.
GoalHashuint32新目标哈希。New goal hash.
Output

返回是否成功。副作用:改写目标与 ManagedGoalHash 并立即重算。

Returns success. Side effects: rewrites the goals and ManagedGoalHash and recomputes immediately.

FindManagedLayerByGoalHash bool const (uint32 GoalHash, FFlowFieldLayerHandle& OutHandle)

按目标哈希查找存活托管层——UMassBattleFuncLib::GetOrAcquireFlowFieldLayer 的复用路径:命中即复用(必要时先 UpdateManagedLayerGoals),未命中则创建。只匹配 bAutoRelease 的层;哈希为 0 直接返回 false。

Finds a live managed layer by goal hash — the reuse path of UMassBattleFuncLib::GetOrAcquireFlowFieldLayer: a hit is reused (with an UpdateManagedLayerGoals first when needed), a miss creates one. Matches only bAutoRelease layers; a zero hash returns false immediately.

Input
参数 Param类型 Type说明 Description
GoalHashuint32要查找的目标哈希。Goal hash to look up.
OutHandleFFlowFieldLayerHandle&输出:命中层的句柄。Output: the matched layer's handle.
Output

返回是否命中;命中时写 OutHandle。

Returns whether a layer matched; writes OutHandle on hit.

GetLayerUserCount int32 const (FFlowFieldLayerHandle Handle)

读取层的在用使用者数(诊断用,BlueprintPure)。

Reads a layer's live user count (diagnostics; BlueprintPure).

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle层句柄。Layer handle.
Output

返回 UserCount;层不存在时返回 INDEX_NONE。

Returns the UserCount, or INDEX_NONE when the layer is missing.

FindLayer const FFlowFieldLayer* const (FFlowFieldLayerHandle Handle)

只读层查找:直接在 FlowFieldLayers 中按 LayerID 取指针,不存在为 nullptr(内联实现)。

Read-only layer lookup: a direct FlowFieldLayers find by LayerID; nullptr when absent (inline).

Input
参数 Param类型 Type说明 Description
HandleFFlowFieldLayerHandle层句柄。Layer handle.
Output

返回层指针(只读);不存在为 nullptr。无副作用。

Returns the (read-only) layer pointer, nullptr when absent. No side effects.

FlushPendingLayerDestroys void

本实例的待销毁层冲刷(静态 FlushAllPendingLayerDestroys 的实例级实现):逐项复查 UserCount == 0 且 bAutoRelease 才从 FlowFieldLayers 移除——入队后被重新 Acquire 的层存活;无论是否移除,队列条目都会被清掉(再次归零的层会在下次 Release 重新入队)。

Instance-level drain of pending layer destroys (what the static FlushAllPendingLayerDestroys calls): re-checks UserCount == 0 and bAutoRelease before removing a layer from FlowFieldLayers — layers re-acquired since queuing survive; the queue entry is dropped either way (a layer hitting zero again re-queues on its next release).

Input

无参数。

No parameters.

Output

无返回值。副作用:移除仍归零的托管层并清空 PendingLayerDestroys。

No return value. Side effects: removes managed layers still at zero and clears PendingLayerDestroys.

InitFlowField void (EInitMode InitMode)

初始化几何与可视化状态:① Construction/BeginPlay 模式重置定时器与 bIsGridDirty,NavMesh 模式缓存 NavMesh 并收集 NavLink;② 钳制 cellSize/flowFieldSize/initialCost,重算 xNum/yNum、缓存 actorLoc/actorRot/offsetLoc/relativeLoc;③ 设置 Volume 盒体范围与贴花尺寸;④ 按模式创建/更新动态材质(CellDMI/ArrowDMI)并写入 XNum/YNum/CellSize/Offset/Yaw 参数;⑤ 按 GenerationMode 与绘制开关切换 Volume/贴花/箭头(及 NavMesh 多边形的填充/边线)可见性。

Initializes geometry and visualization state: ① in Construction/BeginPlay modes resets the timer and bIsGridDirty, caching the NavMesh and collecting NavLinks in NavMesh mode; ② clamps cellSize/flowFieldSize/initialCost, recomputes xNum/yNum and caches actorLoc/actorRot/offsetLoc/relativeLoc; ③ sets the Volume box extent and decal size; ④ creates/updates the dynamic materials (CellDMI/ArrowDMI) per mode and writes the XNum/YNum/CellSize/Offset/Yaw parameters; ⑤ toggles Volume/decal/arrow visibility (and NavMesh poly fill/edge drawing) per generation mode and draw toggles.

Input
参数 Param类型 Type说明 Description
InitModeEInitMode初始化时机(Construction / BeginPlay / Runtime),决定重置行为与可见性分支。Init timing (Construction / BeginPlay / Runtime), deciding reset behavior and visibility branches.
Output

无返回值。副作用:重算网格尺寸、更新组件范围/材质/可见性。

No return value. Side effects: recomputes grid dimensions, updates component extents/materials/visibility.

GetGoalLocation void

收集目标:解析 GoalActors 的当前位置填入 GoalActorLocations,把目标 Actor 位置与 GoalLocations 合并后经 WorldToGrid 转为 GoalGridCoords。

Collects goals: resolves GoalActors current locations into GoalActorLocations, merges them with GoalLocations, and converts all into GoalGridCoords via WorldToGrid.

Input

无参数。

No parameters.

Output

无返回值。副作用:刷新 GoalActorLocations 与 GoalGridCoords。

No return value. Side effects: refreshes GoalActorLocations and GoalGridCoords.

CreateGrid void

创建/重建整张网格:bIsGridDirty 为 false 时直接返回;否则清空 InitialCellsArray/CurrentCellsArray,按 xNum × yNum 逐格调用 EnvQuery 填充初始格数据,末尾清 bIsGridDirty。

Creates/rebuilds the whole grid: returns immediately when bIsGridDirty is false; otherwise clears InitialCellsArray/CurrentCellsArray, fills initial cell data cell by cell via EnvQuery over xNum × yNum, then clears bIsGridDirty.

Input

无参数。

No parameters.

Output

无返回值。副作用:重建两个格子数组并清 bIsGridDirty。

No return value. Side effects: rebuilds both cell arrays and clears bIsGridDirty.

RegisterModifier void (AFlowFieldModifier* Modifier)

向本场注册 modifier(运行时推送——或 BP 手动按需)。按类型分派到 RuntimeGridModifiers/RuntimeCostModifiers/RuntimeDirModifiers,并同步进入活动列表(GridModifiers/CostModifiers/DirModifiers,AddUnique 去重),方向/成本列表注册后按 priority 重排——UpdateFlowField/ModifyGrid 当帧即可见到。幂等(Include/Attach 成员重复注册无害,Contains 守卫使副作用只在真新增时触发);与 GetAllModifiers 一致地盖写 modifier 的 FlowField 反向指针;重扫不丢(GetAllModifiers 以运行时注册为基底再合并)。NavMesh 模式下注册 Cost/Grid modifier 仍输出 Warning(不支持)。背景:GetAllModifiers 只认 Include 列表与挂场子 Actor 两个来源,运行时独立 spawn 的 modifier 原本要付一次 full rebuild 才能被看见——推模式取代之;全部 modifier 家族都是空间圈选型(体积/样条),注册到同世界全部场在圈外零开销。

Registers a modifier with this field (runtime push — or manual on-demand from BP). Dispatches by type into RuntimeGridModifiers/RuntimeCostModifiers/RuntimeDirModifiers and simultaneously enters the active lists (GridModifiers/CostModifiers/DirModifiers, AddUnique-deduped); direction/cost lists are re-sorted by priority after registration — UpdateFlowField/ModifyGrid see it the same frame. Idempotent (Include/Attach members re-register harmlessly; a Contains guard fires side effects only on true additions); stamps the modifier's FlowField back-pointer like GetAllModifiers; survives rescans (GetAllModifiers merges on top of the runtime set). Registering Cost/Grid modifiers in NavMesh mode still warns (unsupported). Background: GetAllModifiers only sees the Include list and attached child actors — a runtime-spawned standalone modifier used to require paying a full rebuild to be seen; the push model replaces that. All modifier flavors are spatial (volume/spline-scoped), so registering with every same-world field is free outside their shape.

Input
参数 Param类型 Type说明 Description
ModifierAFlowFieldModifier*要注册的 modifier(无效指针直接返回)。The modifier to register (an invalid pointer returns immediately).
Output

无返回值。副作用:写入运行时集合与活动列表、盖 FlowField 反向指针、重排方向/成本列表。

No return value. Side effects: writes the runtime set and active lists, stamps the FlowField back-pointer, re-sorts the direction/cost lists.

UnregisterModifier void (AFlowFieldModifier* Modifier)

移除一个运行时/手动注册(幂等):从对应的运行时集合与活动列表同时移除。Include/Attach 成员关系不动——那些条目在下次 GetAllModifiers 重扫时会回来。

Removes a runtime/manual registration (idempotent): drops it from both the matching runtime set and the active list. Include/Attach membership is untouched — those entries return on the next GetAllModifiers rescan.

Input
参数 Param类型 Type说明 Description
ModifierAFlowFieldModifier*要注销的 modifier(无效指针直接返回)。The modifier to unregister (an invalid pointer returns immediately).
Output

无返回值。副作用:从运行时集合与活动列表移除该 modifier。

No return value. Side effect: removes the modifier from the runtime set and the active list.

GetAllModifiers void

收集场景中的修改器:重扫基底 = 运行时/手动注册(推模式的 Runtime*Modifiers 集合),再遍历 IncludeModifiers 与挂在本 Actor 下的子 Actor,在其上合并去重并回填 FlowField 软引用——full rebuild 重扫不再抹掉运行时注册;方向与成本修改器(合并整体)按 priority 升序重排,应用顺序不因来源失稳。NavMesh 模式下对 Cost/Grid 修改器输出 Warning(不支持)。

Collects scene modifiers: the rescan base = runtime/manual registrations (the push model's Runtime*Modifiers sets), then iterates IncludeModifiers and child actors attached under this actor, merging deduped on top with their FlowField soft references back-filled — a full-rebuild rescan no longer wipes runtime registrations; the merged direction and cost lists are re-sorted ascending by priority so application order stays source-stable. In NavMesh mode, warns about Cost/Grid modifiers (unsupported).

Input

无参数。

No parameters.

Output

无返回值。副作用:重置并填充三个修改器数组,回填 FlowField 引用;NavMesh 模式输出告警。

No return value. Side effects: resets and fills the three modifier arrays, back-fills FlowField references; warns in NavMesh mode.

ModifyGrid void

同步应用全部启用的网格修改器:清空 GridModifiedSet,依序调用每个修改器的 ApplyGridModification(this, GridModifiedSet)(跳过 bEnable = false)。

Applies all enabled grid modifiers synchronously: clears GridModifiedSet, then calls each modifier's ApplyGridModification(this, GridModifiedSet) in order (skipping bEnable = false).

Input

无参数。

No parameters.

Output

无返回值。副作用:重建 InitialCellsArray 中的受影响格子并填充 GridModifiedSet。

No return value. Side effects: rebuilds affected cells in InitialCellsArray and fills GridModifiedSet.

ModifyGridAsync void

异步应用全部启用的网格修改器:逻辑与 ModifyGrid 相同,但调用 ApplyGridModificationAsync——各修改器通过 EnvQueryAsync 发起异步 trace 并递增 TraceRemaining;全部完成后由 UpdateCellMap 触发 DoneAllTracesDelegate。

Applies all enabled grid modifiers asynchronously: same logic as ModifyGrid, but calls ApplyGridModificationAsync — modifiers launch async traces via EnvQueryAsync and increment TraceRemaining; when all finish, UpdateCellMap triggers DoneAllTracesDelegate.

Input

无参数。

No parameters.

Output

无返回值。副作用:发起异步环境查询,递增 TraceRemaining,填充 GridModifiedSet。

No return value. Side effects: launches async environment queries, increments TraceRemaining, fills GridModifiedSet.

ModifyCost void (TArray<FCellStruct>& InInitialCellsArray, TArray<FCellStruct>& InCurrentCellsArray, TArray<TWeakObjectPtr<AFlowFieldCostModifier>>& InCostModifiers)

应用成本修改:① InCurrentCellsArray = InInitialCellsArray 拷贝;② 目标格 cost 置 0;③ 依序调用启用的成本修改器;④ 叠加静态 ExtraCosts(键 = 格子索引,值相加后钳制 [0,255])。

Applies cost modifications: ① copies InInitialCellsArray into InCurrentCellsArray; ② zeroes the goal cells' cost; ③ calls enabled cost modifiers in order; ④ overlays static ExtraCosts (key = cell index, value added then clamped to [0,255]).

Input
参数 Param类型 Type说明 Description
InInitialCellsArrayTArray<FCellStruct>&基础格数据(源)。Base cell data (source).
InCurrentCellsArrayTArray<FCellStruct>&输出:修改后的格数据。Output: modified cell data.
InCostModifiersTArray<TWeakObjectPtr<AFlowFieldCostModifier>>&成本修改器列表。Cost modifier list.
Output

无返回值。副作用:写入 InCurrentCellsArray 的 cost(目标 = 0,修改器与 ExtraCosts 叠加)。

No return value. Side effects: writes cost into InCurrentCellsArray (goals = 0, modifiers and ExtraCosts applied).

CalculateFlowField void (const TArray<FCellStruct>& InBaseCellsArray, TArray<FCellStruct>& InCurrentCellsArray, const TArray<FIntVector>& InGoalGridCoords)

Grid 模式的核心求解器。Phase 1 积分场(Dijkstra):目标格 dist = 0 入最小堆,按 Style 决定邻居顺序(AdjacentFirst 对角线先行校验 / DiagonalFirst 仅四邻),跳过越界、障碍(bIgnoreInternalObstacleCells 时)、坡度超 maxWalkableAngle 的邻居;newDist = 邻居cost + 当前dist 更小则更新并继承目标坐标。Phase 2 方向场(ParallelFor 并行):cost 255 或 dist 65535 置零方向;开启 bStraightFirst 时用 Bresenham 视线检查(Bresenham 线上任一格 cost 255 或与基础数组 cost 不一致即无视线),有视线则直接指向目标;否则在 8 邻居中取 dist 最小的格(邻接/对角有效性校验 + 坡度校验),指向该格。

The core solver for Grid mode. Phase 1 integration field (Dijkstra): goal cells start at dist = 0 in a min-heap; neighbor order follows Style (AdjacentFirst checks diagonals first / DiagonalFirst uses only four neighbors); skips out-of-bounds, obstacle (bIgnoreInternalObstacleCells on) and over-maxWalkableAngle slope neighbors; a smaller newDist = neighbor.cost + current.dist updates the cell and inherits the goal coord. Phase 2 direction field (ParallelFor): cost 255 or dist 65535 cells get a zero direction; with bStraightFirst a Bresenham line-of-sight check runs (any cell on the line with cost 255 or differing from the base array's cost kills LOS), pointing directly at the goal when clear; otherwise the 8-neighbor cell with the smallest dist is chosen (diagonal validity + slope checks) and pointed at.

Input
参数 Param类型 Type说明 Description
InBaseCellsArrayconst TArray<FCellStruct>&基础格数据(Bresenham 视线校验的 cost 基准)。Base cell data (cost reference for Bresenham LOS checks).
InCurrentCellsArrayTArray<FCellStruct>&待计算的格数据(dist/dir/goalCoord 被覆写)。Cell data to compute (dist/dir/goalCoord overwritten).
InGoalGridCoordsconst TArray<FIntVector>&目标网格坐标列表。Goal grid coord list.
Output

无返回值。副作用:覆写所有格子的 dist / dir / goalCoord。

No return value. Side effects: overwrites every cell's dist / dir / goalCoord.

CalculateFlowField_NavMesh void

NavMesh 模式求解入口:清空 NavMeshCellMap;构造占位目标格(首目标位置,存 CurrentCellsArray[0]);把目标合并后投影到网格得到目标多边形集合;初始化面积成本上下文;调用静态 CalculateNavMeshFlow 完成 Dijkstra 积分场(多边形中心/共享边中点计距、面积成本、NavLink 单向/双向规则)+ 并行方向场(string pulling 射线 + 拓扑一致性校验、NextPolyRef 直连、直接链接邻居与空间对角搜索)。

NavMesh-mode solver entry: clears NavMeshCellMap; builds the placeholder goal cell (first goal location, stored in CurrentCellsArray[0]); merges goals, projects them onto the mesh to get the goal polygon set; initializes the area-cost context; then calls the static CalculateNavMeshFlow for the Dijkstra integration field (polygon centers / shared-edge midpoints for distance, area costs, one-way/bidirectional NavLink rules) plus the parallel direction field (string pulling raycast + topological consistency check, NextPolyRef direct links, direct-link neighbors and spatial diagonal search).

Input

无参数。

No parameters.

Output

无返回值。副作用:填充 NavMeshCellMap(PolyRef → 格子)与 CurrentCellsArray 占位目标格。

No return value. Side effects: fills NavMeshCellMap (PolyRef → cell) and the placeholder goal cell in CurrentCellsArray.

ModifyFlowField void (TArray<FCellStruct>& InCurrentCellsArray, TSet<FIntVector>& InDirModifiedSet, TArray<TWeakObjectPtr<AFlowFieldDirModifier>>& InDirModifiers)

Grid 模式应用方向修改器:清空 InDirModifiedSet,依序调用启用的方向修改器(跳过 bEnable = false)。

Applies direction modifiers in Grid mode: clears InDirModifiedSet, then calls each enabled direction modifier in order (skipping bEnable = false).

Input
参数 Param类型 Type说明 Description
InCurrentCellsArrayTArray<FCellStruct>&待修改的格数据。Cell data to modify.
InDirModifiedSetTSet<FIntVector>&输出集合:被修改的网格坐标。Output set: modified grid coords.
InDirModifiersTArray<TWeakObjectPtr<AFlowFieldDirModifier>>&方向修改器列表。Direction modifier list.
Output

无返回值。副作用:覆写格子 dir 并填充 InDirModifiedSet。

No return value. Side effects: overwrites cell dir and fills InDirModifiedSet.

ModifyFlowField_NavMesh void (TMap<int64, FCellStruct>& InNavMeshCellMap, TSet<int64>& InDirModifiedSet, TArray<TWeakObjectPtr<AFlowFieldDirModifier>>& InDirModifiers)

NavMesh 模式应用方向修改器:清空 InDirModifiedSet,依序调用各修改器的 ApplyDirectionModification_NavMesh。

Applies direction modifiers in NavMesh mode: clears InDirModifiedSet, then calls each modifier's ApplyDirectionModification_NavMesh in order.

Input
参数 Param类型 Type说明 Description
InNavMeshCellMapTMap<int64, FCellStruct>&PolyRef → 格子映射。PolyRef → cell map.
InDirModifiedSetTSet<int64>&输出集合:被修改的 PolyRef。Output set: modified poly refs.
InDirModifiersTArray<TWeakObjectPtr<AFlowFieldDirModifier>>&方向修改器列表。Direction modifier list.
Output

无返回值。副作用:覆写格子 dir 并填充 InDirModifiedSet。

No return value. Side effects: overwrites cell dir and fills InDirModifiedSet.

DrawCells void (EInitMode InitMode)

把格子数据烘焙成瞬时纹理并交给贴花材质:构造 xNum × yNum 的 transient UTexture2D,每格写 RGBA——A = 非 Empty, R = cost, G = 被网格修改(GridModifiedSet),B = dist 归一化到最大距离;随后把纹理参数写入 CellDMI。仅在对应绘制开关开启时执行。

Bakes cell data into a transient texture for the decal material: builds an xNum × yNum transient UTexture2D, writing RGBA per cell — A = non-Empty, R = cost, G = grid-modified (GridModifiedSet), B = dist normalized to the maximum distance; then writes the texture parameter into CellDMI. Runs only when the matching draw toggle is on.

Input
参数 Param类型 Type说明 Description
InitModeEInitMode决定走编辑器(drawCellsInEditor)还是游戏内(drawCellsInGame)开关。Selects the editor (drawCellsInEditor) or in-game (drawCellsInGame) toggle.
Output

无返回值。副作用:重建瞬时纹理并更新贴花材质参数。

No return value. Side effects: rebuilds the transient texture and updates the decal material parameter.

DrawArrows void (EInitMode InitMode)

重建 ISM 箭头实例(每次绘制全量重建)。Grid 模式:每格按 normal 对齐方向(先对齐法线再平面内旋转),高度按坡度偏移(越陡抬越高),Empty 格隐藏、无方向格染红(custom data 2)、被方向修改的格染蓝(1)、其余白色(0)。NavMesh 模式(仅编辑器宏内):逐多边形地面射线定位、贴表面定向,跳过 NavLink;未覆盖的多边形(无流场/不可达)渲染红点。实例自定义数据经 SetCustomDataValue 写入。

Rebuilds the ISM arrow instances (full rebuild every draw). Grid mode: per cell, aligns the direction to the normal (normal-align then in-plane rotate), offsets height by slope (steeper = higher); Empty cells are hidden, direction-less cells tint red (custom data 2), direction-modified cells blue (1), the rest white (0). NavMesh mode (inside an editor-only macro): per polygon, ground-trace positions with surface-aligned orientation, skipping NavLinks; uncovered polygons (no flow field / unreachable) render as red dots. Instance custom data is written via SetCustomDataValue.

Input
参数 Param类型 Type说明 Description
InitModeEInitMode决定走编辑器(drawArrowsInEditor)还是游戏内(drawArrowsInGame)开关。Selects the editor (drawArrowsInEditor) or in-game (drawArrowsInGame) toggle.
Output

无返回值。副作用:清空并重建 ISM_Arrows 实例与自定义数据。

No return value. Side effects: clears and rebuilds ISM_Arrows instances and custom data.

UpdateTimer void

推进定时器:nextTickTimeLeft <= 0 时重置为 RefreshInterval(钳制 ≥ 0),否则按世界 DeltaSeconds 递减。

Advances the timer: resets nextTickTimeLeft to RefreshInterval (clamped ≥ 0) when it is ≤ 0, otherwise decrements it by the world delta seconds.

Input

无参数。

No parameters.

Output

无返回值。副作用:修改 nextTickTimeLeft。

No return value. Side effect: mutates nextTickTimeLeft.

EnvQuery FCellStruct (const FIntVector gridCoord)

单格环境查询(同步):按 gridCoord 计算格心世界位置;开启 traceGround 时向 groundObjectType 做线 trace——命中则取撞击点高度/法线,坡度超 maxWalkableAngle 判为障碍,否则(开启 traceObstacles)再做球体 trace(半径 cellSize/2)判障碍;未命中地面为 Empty。未开启地面 trace 时格高取 actorLoc.Z + flowFieldSize.Z/2,同样按 traceObstacles 判障碍。未命中障碍时 cost = initialCost(255 时 type = Obstacle)。

Single-cell environment query (synchronous): computes the cell-center world location from gridCoord; with traceGround on, line-traces groundObjectType — a hit takes the impact height/normal, cells steeper than maxWalkableAngle become obstacles, otherwise (with traceObstacles on) a sphere trace (radius cellSize/2) decides obstacles; a miss makes the cell Empty. Without ground tracing the cell height is actorLoc.Z + flowFieldSize.Z/2, again obstacle-checked per traceObstacles. Without obstacle hits, cost = initialCost (type = Obstacle when 255).

Input
参数 Param类型 Type说明 Description
gridCoordconst FIntVector网格坐标。Grid coord.
Output

返回填好的 FCellStruct(类型/cost/法线/世界位置)。副作用:无(仅 trace)。

Returns a filled FCellStruct (type/cost/normal/world location). Side effects: none (traces only).

EnvQueryAsync void (const FIntVector gridCoord)

单格环境查询(异步):与 EnvQuery 同语义,但经 AsyncLineTraceByObjectType / AsyncSweepByObjectType 发起(弱引用捕获 this,避免销毁后回调);每个 trace 完成经 lambda 按同规则判定,通过 DoneTraceDelegate(即 UpdateCellMap)交回结果并递减 TraceRemaining。

Single-cell environment query (asynchronous): same semantics as EnvQuery but launched via AsyncLineTraceByObjectType / AsyncSweepByObjectType (capturing a weak reference to this to survive destruction); each completion lambda applies the same rules and hands the result back through DoneTraceDelegate (i.e. UpdateCellMap), which decrements TraceRemaining.

Input
参数 Param类型 Type说明 Description
gridCoordconst FIntVector网格坐标。Grid coord.
Output

无返回值。副作用:发起异步 trace;完成后经 DoneTraceDelegate 写回格子。

No return value. Side effects: launches async traces; results are written back via DoneTraceDelegate.

GetInterpedWorldLocation bool (const FVector& Location, const FQuat& Rotation, FVector& OutInterpLoc, FVector& OutInterpNormal, float SearchRadius, float HalfHeight, FFlowfieldScratchContext* Context)

取位置处的地面插值位置与法线。NavMesh 模式:ProjectPointToNavigation 投影到网格表面,再对中心与 ±X 三个采样点做三角形法线混合(中心权重 2,两侧各 1),输出连续法线。Grid 模式:连续网格坐标下对 4 邻格做双线性插值(位置与法线均插值,法线中间步骤归一化);四邻任一无效即失败。失败时输出置零/向上并返回 false。

Gets the interpolated ground location and normal at a location. NavMesh mode: projects onto the mesh surface via ProjectPointToNavigation, then blends triangle normals sampled at the center and ±X (center weight 2, sides 1) for a continuous normal. Grid mode: bilinear interpolation of the four neighbor cells at continuous grid coords (both location and normal; normals normalized at intermediate steps); any invalid neighbor fails. On failure outputs zero/up and returns false.

Input
参数 Param类型 Type说明 Description
Locationconst FVector&查询位置。Query location.
Rotationconst FQuat&旋转(当前实现未使用,预留)。Rotation (unused in the current implementation; reserved).
OutInterpLocFVector&输出:插值地面位置。Output: interpolated ground location.
OutInterpNormalFVector&输出:插值地面法线。Output: interpolated ground normal.
SearchRadiusfloat投影/采样水平范围。Projection/sampling horizontal extent.
HalfHeightfloat半高(Grid 模式未使用;NavMesh 模式垂直范围取 PathStopSearchDist.Y 兜底)。Half height (unused in Grid mode; NavMesh mode's vertical extent falls back to PathStopSearchDist.Y).
ContextFFlowfieldScratchContext*暂存上下文(当前实现未使用,预留)。Scratch context (unused in the current implementation; reserved).
Output

返回是否成功;失败时输出零位置与向上法线。

Returns whether the query succeeded; outputs a zero location and up normal on failure.

GetGroundLocation bool (const FVector& InSelfLocation, const FQuat& InSelfRotation, const float InSelfRadius, const float InSelfHalfHeight, EFlowFieldGroundDetectionMode TraceMode, const TArray<TEnumAsByte<EObjectTypeQuery>>& GroundObjectTypes, float KillZ, FVector& OutGroundLocation, FVector& OutGroundNormal)

按 TraceMode 取地面位置与法线:FlowField 用 GetInterpedWorldLocation(半径 = InSelfRadius);CapsuleSweep 从自身位置向 KillZ 做胶囊体对象扫描(complex trace);FlowFieldOrCapsuleSweep 先流场插值、失败再胶囊扫描。胶囊扫描的命中点/法线取自 HitResult。

Gets the ground location and normal per TraceMode: FlowField uses GetInterpedWorldLocation (radius = InSelfRadius); CapsuleSweep capsule-sweeps from the self location down to KillZ (complex trace); FlowFieldOrCapsuleSweep tries the flow field first and falls back to the capsule sweep. Capsule hit point/normal come from the HitResult.

Input
参数 Param类型 Type说明 Description
InSelfLocationconst FVector&查询者位置(胶囊扫描起点)。Query location (capsule sweep start).
InSelfRotationconst FQuat&胶囊旋转。Capsule rotation.
InSelfRadiusconst float胶囊半径。Capsule radius.
InSelfHalfHeightconst float胶囊半高。Capsule half height.
TraceModeEFlowFieldGroundDetectionMode地面检测模式(见枚举)。Ground detection mode (see the enum).
GroundObjectTypesconst TArray<TEnumAsByte<EObjectTypeQuery>>&视为地面的对象类型。Object types treated as ground.
KillZfloat胶囊扫描的终点 Z(低于该高度视为无地面)。Capsule sweep end Z (below this, no ground).
OutGroundLocationFVector&输出:地面位置。Output: ground location.
OutGroundNormalFVector&输出:地面法线。Output: ground normal.
Output

返回是否取到地面;失败时输出零位置与向上法线。

Returns whether ground was found; outputs a zero location and up normal on failure.

FindPathAStar bool (const FVector& StartLocation, const FVector& GoalLocation, TArray<FVector>& OutPath, FFlowfieldScratchContext& Context, float AgentRadius, float AgentHalfHeight)

Grid A* 个体寻路。流程:① 网格未初始化返回 false;② 起终点经 WorldToGrid 钳制,网格外位置若钳制到障碍格则螺旋找最近 Ground 格;③ 同格直连 [Start, Goal];④ Context.Prepare 惰性清场;⑤ 网格内起终点在障碍格内时触发「紧急路径」(启发权重 ×2、允许穿越障碍格 cost 5、对角障碍不拦截);⑥ bStraightFirst 且非紧急时做 Bresenham 视线检查,通畅直接返回 [Start, Goal];⑦ 主循环用上下文内建最小堆,按 Style 决定 8 邻顺序(对角 cost √2),邻居启发为网格曼哈顿距离;⑧ 到达目标后回溯路径——路径点取途经格中心(不含目标格中心),末尾直连真实 GoalLocation,并把末点 Z 对齐前一点。失败返回 false 且路径清空。

Grid A* individual pathfinding. Flow: ① uninitialized grid returns false; ② start/goal coords are clamped via WorldToGrid; off-grid positions clamped onto obstacle cells spiral-search for the nearest Ground cell; ③ same cell connects directly [Start, Goal]; ④ Context.Prepare lazily clears; ⑤ on-grid start/goal inside obstacle cells trigger an "emergency path" (heuristic weight ×2, obstacle cells passable at cost 5, diagonal obstacles not blocking); ⑥ with bStraightFirst and non-emergency, a Bresenham LOS check returns [Start, Goal] directly when clear; ⑦ the main loop uses the context's built-in min-heap, with 8-neighbor order per Style (diagonal cost √2) and grid Manhattan-distance heuristics; ⑧ on reaching the goal, back-traces — path points are intermediate cell centers (the goal cell center excluded), the real GoalLocation connects at the end, and the last point's Z aligns with its predecessor. Returns false with an empty path on failure.

Input
参数 Param类型 Type说明 Description
StartLocationconst FVector&起点世界位置。Start world location.
GoalLocationconst FVector&终点世界位置。Goal world location.
OutPathTArray<FVector>&输出:路径点(世界位置)。Output: path points (world locations).
ContextFFlowfieldScratchContext&复用暂存上下文(堆/G 值/回溯)。Reusable scratch context (heap/G scores/back-trace).
AgentRadiusfloatAgent 半径(当前实现未使用,预留)。Agent radius (unused in the current implementation; reserved).
AgentHalfHeightfloatAgent 半高(当前实现未使用,预留)。Agent half height (unused in the current implementation; reserved).
Output

返回是否找到路径;成功时 OutPath 含路径点(≥ 2),失败时清空。

Returns whether a path was found; on success OutPath holds the points (≥ 2), on failure it is emptied.

FindPathNavMesh bool (const FVector& StartLocation, const FVector& GoalLocation, TArray<FVector>& OutPath)

NavMesh 个体寻路。流程:① 无导航系统/默认 NavData 返回 false;② 目标投影到网格(PathStopSearchDist extent);③ bStraightFirst 时做表面射线 LOS + 拓扑一致性校验(终点多边形 == 目标投影多边形),通畅直接返回 [Start, 投影目标];④ FindPathSync(允许部分路径)常规寻路,路径点替换首点为真实起点;⑤ 失败时离网恢复:起终点投影到网格,在投影端点间寻路,再拼接离网补丁段——首尾替换为真实起终点并修剪与起终点重合的冗余点。任一端投影失败返回 false。

NavMesh individual pathfinding. Flow: ① no navigation system / default NavData returns false; ② projects the goal onto the mesh (PathStopSearchDist extent); ③ with bStraightFirst, a surface raycast LOS plus topological consistency check (end polygon == the goal projection's polygon) returns [Start, projected goal] directly when clear; ④ FindPathSync (partial paths allowed) runs the normal search, with the first point replaced by the real start; ⑤ on failure, off-mesh recovery: projects start/goal onto the mesh, paths between the projected endpoints, then splices the off-mesh patch segments — the ends are replaced by the real start/goal and redundant points collapsed onto them are pruned. Returns false when either end fails to project.

Input
参数 Param类型 Type说明 Description
StartLocationconst FVector&起点世界位置。Start world location.
GoalLocationconst FVector&终点世界位置。Goal world location.
OutPathTArray<FVector>&输出:路径点(世界位置)。Output: path points (world locations).
Output

返回是否找到路径;成功时 OutPath 含路径点。

Returns whether a path was found; on success OutPath holds the points.

ExportSubstrateBytes bool const (TArray<uint8>& OutData)

锁步基底同步的导出(仅服务器端有意义,实现于 FlowFieldSync.cpp):把已构建的基底序列化为紧凑量化流——Grid 模式序列化格子数据(cost/type/世界 Z/法线,厘米量化),NavMesh 模式(v3 线格式)原样上传服务器原始 tile blob(dtCreateNavMeshData 输出的原始字节),全端可用 Detour 自有 addTile 解析器重建逐字节一致的 dtNavMesh 复制品(拓扑、detail 网格、BVtree、离网连接与量化顶点高度原样过线)。同时一次性捕获目标集快照(导出时刻解析 GoalActors)。场未构建(bIsBeginPlay)或尺寸/navmesh 缺失时返回 false。由 AMassBattleNetworkGameModeBase::SendLockstepCommandToClients_RebuildFlowField 调用(导出后服务器同样自导入)。

Export side of lockstep substrate sync (server-only meaningful; implemented in FlowFieldSync.cpp): serializes the built substrate into a compact quantized stream — Grid mode writes the cell data (cost/type/world Z/normals, centimeter-quantized); NavMesh mode (v3 wire format) ships the server's original tile blobs verbatim (the raw bytes dtCreateNavMeshData emitted), from which every peer rebuilds a byte-identical dtNavMesh replica via Detour's own addTile parser (topology, detail meshes, BVtree, off-mesh connections and quantized vertex heights cross the wire intact). Also captures the goal-set snapshot ONCE (GoalActors resolved at export time). Returns false when the field isn't built (bIsBeginPlay) or the dims/navmesh are missing. Called by AMassBattleNetworkGameModeBase::SendLockstepCommandToClients_RebuildFlowField (which then self-imports on the server too).

Input
参数 Param类型 Type说明 Description
OutDataTArray<uint8>&输出:序列化字节流(含魔数/版本/模式/内容哈希/位置与朝向 identity/目标段)。Output: the serialized byte stream (magic/version/mode/content hash/origin-yaw identity/goal section).
Output

返回是否导出成功;失败时 OutData 已重置并记录 Error 日志。副作用:刷新一次目标解析(GetGoalLocation,const_cast)。

Returns whether the export succeeded; on failure OutData is reset and an Error logged. Side effect: refreshes goal resolution once (GetGoalLocation via const_cast).

ImportSubstrateBytes bool (const TArray<uint8>& InData)

用导入基底替换场数据(全端——服务器也重导入自己的导出,全端持有相同字节)。校验魔数/版本与流布局后:Grid 模式按流内 xNum/yNum/cellSize/位置/朝向重建两个格子数组(世界 XY 为 EnvQuery 构造的精确逆推导);NavMesh 模式从 tile blob 重建完整 dtNavMesh 复制品(SyncedReplicaMesh),此后引擎 navmesh 查询被禁用(FindPath 分派到 FindPathAStar/FindPathReplica)。洪泛用流内目标快照(SyncedGoalLocations)、绝不读本地 GoalActors(晚加入端 goal actor 尚未解析,读本地会分叉)。幂等(收窄):同版本补发仅在目标洪泛已完成(bSyncedFloodApplied)时跳过;未洪泛的同版本补发只在现行基底上重跑洪泛(复制品 PolyRef 保持稳定)。成功尾部置位 bSyncedSubstrate/版本/模式,并清 bIsBeginPlay/bIsGridDirty(查询就绪闸)。调用方:AMassBattleNetworkGameModeBase(服务器自导入)、AMassBattleNetworkGameStateBase(命令执行,全量/差分选择)、UMassBattleNetworkSubsystem(晚加入补发)。

Replaces the field's data with the imported substrate (both peers — the server re-imports its own export so every peer holds identical bytes). After validating magic/version and stream layout: Grid mode rebuilds both cell arrays from the stream's xNum/yNum/cellSize/origin/yaw (world XY derived as the exact inverse of EnvQuery's construction); NavMesh mode rebuilds the full dtNavMesh replica (SyncedReplicaMesh) from the tile blobs, and from then on engine navmesh queries are forbidden (FindPath dispatches to FindPathAStar/FindPathReplica). Flooding uses the in-stream goal snapshot (SyncedGoalLocations), never local GoalActors (late-join imports run before goal actors resolve; reading locals forked peers). Idempotent (narrowed): re-delivery of the same version skips only when the goal flood ran to completion (bSyncedFloodApplied); an unflooded same-version re-delivery re-runs JUST the flood on the standing substrate (replica PolyRefs stay stable). The success tail stamps bSyncedSubstrate/version/mode and clears bIsBeginPlay/bIsGridDirty (the queries-ready gate). Callers: AMassBattleNetworkGameModeBase (server self-import), AMassBattleNetworkGameStateBase (command execution, full/delta selection), UMassBattleNetworkSubsystem (late-join re-delivery).

Input
参数 Param类型 Type说明 Description
InDataconst TArray<uint8>&全量基底流(ExportSubstrateBytes 的输出)。The full substrate stream (ExportSubstrateBytes' output).
Output

返回是否导入成功;失败/跳过时基底不动并记录日志。副作用:替换格数组或复制品、写入同步状态组、按 drawArrowsInGame 重绘箭头。

Returns whether the import succeeded; on failure/skip the substrate is untouched and a log emitted. Side effects: replaces the cell arrays or the replica, writes the synced-state group, redraws arrows per drawArrowsInGame.

ImportSubstrateDeltaBytes bool (const TArray<uint8>& InData)

在现行基底上应用差分流('FFD1',见 FlowFieldSync.h):Grid 格子就地更新;NavMesh tile 在复制品上经 removeTile/addTile 换版(全端同序 ⇒ PolyRef salt 历史一致)。补丁后以流内目标重跑洪泛并推进版本。前置校验:本地必须已同步且版本恰为差分的 BaseHash(不匹配返回 false——晚加入跳过差分/分叉链只能全量重发,由调用方决定)、位置/朝向 identity 不得漂移、魔数/版本必须匹配。由 AMassBattleNetworkGameStateBase 在命令执行处按命令类型选择全量或差分导入。

Applies a delta stream ('FFD1' — see FlowFieldSync.h) on top of the standing substrate: Grid cells are updated in place; NavMesh tiles are swapped via removeTile/addTile on the replica (identical order on every peer ⇒ identical PolyRef salt history). The stream-goal flood re-runs after the patch and the version advances. Preconditions: the local field must already be synced with the version EXACTLY matching the delta's BaseHash (a mismatch returns false — a late joiner that skipped deltas or a forked chain is repairable only by a full re-send, at the caller's discretion), the origin/yaw identity must not have drifted, and magic/version must match. AMassBattleNetworkGameStateBase picks full vs delta import per command type at command execution.

Input
参数 Param类型 Type说明 Description
InDataconst TArray<uint8>&差分基底流(含新版本哈希与基准哈希)。The delta substrate stream (carrying the new-version hash and the base hash).
Output

返回是否应用成功;前置不符或流损坏时返回 false 且基底不动。副作用:就地补丁格/tile、重跑洪泛、推进 SyncedSubstrateVersion。

Returns whether the delta applied; precondition failures or malformed streams return false with the substrate untouched. Side effects: patches cells/tiles in place, re-runs the flood, advances SyncedSubstrateVersion.

RunStreamGoalFloodInternal bool (uint8 StreamMode)

全量与差分两条导入路径共用的流内目标洪泛(差分路径加入时从 ImportSubstrateBytes 提取):只以 SyncedGoalLocations 洪泛,绝不读本地 GoalActors(导出快照在流里,构造性免竞态)。NavMesh 模式调 CalculateFlowField_NavMesh(复制品感知,以流内目标洪泛复制品);Grid 模式把流目标转网格坐标后调 CalculateFlowField,并做方向修改器对齐(地图摆放的修改器双端一致存在,无解析竞态)与基准方向存档。无目标场视为成功(洪泛不属基底契约);成功置 bSyncedFloodApplied。

The stream-goal flood shared by both import paths (full + delta; extracted from ImportSubstrateBytes when the delta path joined): floods ONLY from SyncedGoalLocations, never local GoalActors (the export-time snapshot lives in the stream — race-free by construction). NavMesh mode calls CalculateFlowField_NavMesh (replica-aware: floods the replica from the stream goals); Grid mode converts the stream goals to grid coords and calls CalculateFlowField, plus direction-modifier parity (map-placed modifiers exist identically on both peers — no resolution race) and base-direction archiving. A goal-less field counts as success (flooding is not part of the substrate contract); success stamps bSyncedFloodApplied.

Input
参数 Param类型 Type说明 Description
StreamModeuint8调用流的模式(0 = Grid,1 = NavMesh)——注意用调用流的 Mode,而非导入尾部才盖戳的 SyncedSubstrateMode。The calling stream's mode (0 = Grid, 1 = NavMesh) — note it uses the stream's Mode, not SyncedSubstrateMode which is stamped at the import tail after the flood.
Output

返回洪泛是否完成;写 bSyncedFloodApplied。副作用:重算方向数据(NavMeshCellMap 或格方向)。

Returns whether the flood completed; writes bSyncedFloodApplied. Side effect: recomputes the direction data (NavMeshCellMap or cell directions).

FindPathReplica bool (const FVector& StartLocation, const FVector& GoalLocation, TArray<FVector>& OutPath, FFlowfieldScratchContext* Context)

同步 dtNavMesh 复制品上的确定性 A*(2026-09-09 NavMesh-A* 失步结论的产物):在相同字节上跑 Detour 自有 findPath + findStraightPath(走廊拉绳)——无引擎而有引擎级路径形状,全端构造确定。查询过滤器取导入的 SyncedAreaCosts 表(modifier 代价如同服务器引擎查询一样塑形 A*;NavArea_Null 多边形被阻断)。流程:双端点 findNearestPoly 投影(离网起终点与引擎对齐;投影到离网连接视为无效);bStraightFirst 时表面射线捷径(无墙命中且终点多边形与目标投影一致则直接两点返回);主路径走廊 A* + 拉绳,接受部分路径(镜像 FindPathNavMesh 的 AllowPartialPaths),首点替换为真实起点。每次调用栈上新建查询对象(KI-011:废除跨调用复用,构造性消灭跨端/跨线程残留状态)。Context 参数当前实现未使用(预留)。

Deterministic A* on the synced dtNavMesh replica (product of the 2026-09-09 NavMesh-A* desync conclusion): runs Detour's own findPath + findStraightPath (corridor string-pull) over identical bytes — engine-level path shapes without the engine, construction-deterministic on every peer. The query filter comes from the imported SyncedAreaCosts table (modifier costs shape the A* exactly like the server's engine queries; NavArea_Null polys are blocked). Flow: findNearestPoly projects both endpoints (engine-parity for off-mesh starts/goals; a con as the nearest poly counts as no valid spot); with bStraightFirst, a surface-raycast shortcut (no wall hit and the end poly matches the goal projection returns two points directly); the main path is corridor A* + string-pull, partial results accepted (mirroring FindPathNavMesh's AllowPartialPaths), first point replaced by the true start. A fresh stack query per call (KI-011: scratch-query reuse removed — kills all cross-call/cross-thread carry-over state by construction). The Context parameter is unused in the current implementation (reserved).

Input
参数 Param类型 Type说明 Description
StartLocationconst FVector&起点世界位置。Start world location.
GoalLocationconst FVector&终点世界位置。Goal world location.
OutPathTArray<FVector>&输出:路径点(世界位置)。Output: path points (world locations).
ContextFFlowfieldScratchContext*可选暂存上下文(当前实现未使用,预留)。Optional scratch context (unused in the current implementation; reserved).
Output

返回是否找到路径;成功时 OutPath ≥ 2 点,失败时已清空。绝不查询引擎 navmesh。

Returns whether a path was found; on success OutPath holds ≥ 2 points, on failure it is emptied. Never consults the engine navmesh.

DestroySyncedReplica void

释放复制品网格(dtFreeNavMesh,连同 tile blob 由 DT_TILE_FREE_DATA 生命周期托管一并释放)并置空指针。调用时机:重导入、EndPlay、BeginDestroy(幂等——EndPlay 可能未跑,世界拆除时兜底)。

Frees the replica mesh (dtFreeNavMesh, releasing the tiles and their blobs via the DT_TILE_FREE_DATA lifecycle) and nulls the pointer. Called on re-import, EndPlay, and BeginDestroy (idempotent — EndPlay may not run during world teardown).

Input

无参数。

No parameters.

Output

无返回值。副作用:释放 SyncedReplicaMesh。

No return value. Side effect: frees SyncedReplicaMesh.

GetActiveDetourMesh const dtNavMesh* const

本场一切查询应使用的 dtNavMesh:同步 NavMesh 基底激活时为 SyncedReplicaMesh(可能为空——导入失败或未送达);否则解析引擎网格(GetRecastNavMesh 的 RecastMesh;世界无 navmesh 时为 nullptr)。

The dtNavMesh every query on this field should use: the SyncedReplicaMesh when a synced NavMesh substrate is active (may be null — import failed or not yet delivered); otherwise the engine mesh (GetRecastNavMesh's RecastMesh; nullptr when the world has no navmesh at all).

Input

无参数。

No parameters.

Output

返回活动网格指针,可能为 nullptr。无副作用。

Returns the active mesh pointer, possibly nullptr. No side effects.

ProjectPointToDetour bool const (const FVector& Point, const FVector& HalfExtents, FNavLocation& OutNavLoc, FFlowfieldScratchContext* Context)

把世界点投影到活动网格(findNearestPoly + 隐式最近点,半范围为 UE 单位,UE→Recast 坐标转换)——同步时原生走复制品,否则走引擎网格(引擎投影的统一替代,兼容两种载体)。过滤器在同步 NavMesh 场取导入的 SyncedAreaCosts(全端一致;NavArea_Null 阻断)。传入 Context 时复用其 dtNavMeshQuery(网格变化时重新 init),否则栈上新建。范围内无多边形返回 false。

Projects a world point onto the active detour mesh (findNearestPoly + implicit closest point, half extents in UE units, UE→Recast axis conversion) — replica-native when synced, otherwise the engine mesh (a unified replacement for the engine projection, covering both carriers). The filter takes the imported SyncedAreaCosts on a synced NavMesh field (identical on every peer; NavArea_Null blocks). With a Context, its dtNavMeshQuery is reused (re-inited on mesh change); otherwise a stack query is built. Returns false when no poly is in range.

Input
参数 Param类型 Type说明 Description
Pointconst FVector&要投影的世界点。World point to project.
HalfExtentsconst FVector&搜索半范围(X/Y = 水平,Z = 垂直)。Search half extents (X/Y horizontal, Z vertical).
OutNavLocFNavLocation&输出:投影位置与多边形引用(NodeRef)。Output: projected location and polygon ref (NodeRef).
ContextFFlowfieldScratchContext*可选暂存上下文(复用查询对象)。Optional scratch context (query object reuse).
Output

返回是否投影成功;成功时写 OutNavLoc。无网格/无命中为 false。

Returns whether the projection succeeded; writes OutNavLoc on success. No mesh / no hit yields false.

IsSyncedSubstrateActive bool const

ImportSubstrateBytes 生效后为真(内联读 bSyncedSubstrate)——消费方可据此避开引擎查询。

True once ImportSubstrateBytes has been applied (inline read of bSyncedSubstrate) — consumers can avoid engine queries with it.

Input

无参数。

No parameters.

Output

返回是否处于同步基底态。无副作用。

Returns whether the synced-substrate state is active. No side effects.

GetSyncedSubstrateVersion int32 const (BlueprintPure)

已应用基底版本(全量流体的 ContentHash,差分使其前进;0 = 从未同步)。BP 诊断用——跨端对比该值可发现分叉的版本链(哈希在 BP 侧截断为 int32,值域远够)。

The applied substrate version (the full stream's body ContentHash; deltas advance it; 0 = never synced). A BP diagnosis aid — comparing it across peers spots a forked version chain (the hash is truncated to int32 on the BP side, well within range).

Input

无参数。

No parameters.

Output

返回已应用版本(int32);0 = 从未同步。无副作用。

Returns the applied version (int32); 0 = never synced. No side effects.

FindPath bool (const FVector& StartLocation, const FVector& GoalLocation, TArray<FVector>& OutPath, FFlowfieldScratchContext& Context, float AgentRadius, float AgentHalfHeight)

统一寻路入口。已导入基底(bSyncedSubstrate)时引擎查询被禁用——NavMesh 同步场转发 FindPathReplica(在导入字节上本地计算),Grid 同步场转发 FindPathAStar;否则 NavMesh 模式转发 FindPathNavMesh,Grid 模式转发 FindPathAStar。

Unified pathfinding entry. With an imported substrate (bSyncedSubstrate) engine queries are forbidden — a synced NavMesh field forwards to FindPathReplica (computing locally on the imported bytes) and a synced Grid field to FindPathAStar; otherwise NavMesh mode forwards to FindPathNavMesh and Grid mode to FindPathAStar.

Input
参数 Param类型 Type说明 Description
StartLocationconst FVector&起点世界位置。Start world location.
GoalLocationconst FVector&终点世界位置。Goal world location.
OutPathTArray<FVector>&输出:路径点。Output: path points.
ContextFFlowfieldScratchContext&暂存上下文(Grid A* 用)。Scratch context (for Grid A*).
AgentRadiusfloatAgent 半径(Grid A* 透传)。Agent radius (forwarded to Grid A*).
AgentHalfHeightfloatAgent 半高(Grid A* 透传)。Agent half height (forwarded to Grid A*).
Output

返回是否找到路径。

Returns whether a path was found.

GetSteeringDirection static void (const FVector& CurrentLocation, const FVector& GoalLocation, const TArray<FVector>& PathPoints, int32& CurrentPathIndex, float MoveSpeed, float LookAheadDistance, float PathRadius, float AcceptanceRadius, FVector& SteeringDirection, bool& bHasPath, bool& bIsCurrentNearPath, bool& bIsGoalNearEnd)

静态路径转向助手(简化版路径跟随:指向当前段,到达后推进)。流程:① 路径点不足时无路径——直接指向目标并置 bHasPath = false/bIsGoalNearEnd = true;② 钳制路径索引;③ 若 Agent 被推离当前段起点较远(3 × PathRadius),向后搜索最近的早期段并回退索引;④ 推进:当前目标点被越过(点积 < 0,与 UE PathFollowingComponent 的判定一致)或进入接受半径(终点用 AcceptanceRadius,中间点用 PathRadius)即推进,最多 5 次;⑤ 转向 = 指向当前段终点(GetSafeNormal2D),零方向时依次兜底段方向、目标方向;⑥ 更新 bIsCurrentNearPath(距当前段 ≤ 2 × PathRadius)与 bIsGoalNearEnd(目标距路径末点 ≤ AcceptanceRadius)。MoveSpeed/LookAheadDistance 当前未使用。

Static path-steering helper (simplified path following: point at the current segment, advance when reached). Flow: ① too few path points → no path: point straight at the goal with bHasPath = false/bIsGoalNearEnd = true; ② clamps the path index; ③ when the agent is pushed far from the current segment start (> 3 × PathRadius), searches backward for the closest earlier segment and rewinds; ④ advance: the current target counts as reached when passed (dot product < 0, matching UE's PathFollowingComponent check) or within the acceptance radius (final point uses AcceptanceRadius, intermediate points PathRadius), up to 5 iterations; ⑤ steering = direction to the current segment end (GetSafeNormal2D), falling back to the segment direction then the goal when zero; ⑥ updates bIsCurrentNearPath (within 2 × PathRadius of the current segment) and bIsGoalNearEnd (goal within AcceptanceRadius of the path's last point). MoveSpeed/LookAheadDistance are currently unused.

Input
参数 Param类型 Type说明 Description
CurrentLocationconst FVector&Agent 当前位置。Agent's current location.
GoalLocationconst FVector&最终目标(兜底方向与到达判定)。Final goal (fallback direction and arrival check).
PathPointsconst TArray<FVector>&路径点数组。Path point array.
CurrentPathIndexint32&当前段索引(输入输出,函数内推进/回退)。Current segment index (in/out; advanced/rewound inside).
MoveSpeedfloat移动速度(当前实现未使用)。Move speed (unused in the current implementation).
LookAheadDistancefloat预瞄距离(当前实现未使用)。Look-ahead distance (unused in the current implementation).
PathRadiusfloat中间途经点接受半径。Intermediate waypoint acceptance radius.
AcceptanceRadiusfloat终点接受半径。Final point acceptance radius.
SteeringDirectionFVector&输出:转向方向。Output: steering direction.
bHasPathbool&输出:路径是否有效。Output: whether a valid path exists.
bIsCurrentNearPathbool&输出:Agent 是否靠近当前路径段。Output: whether the agent is near the current path segment.
bIsGoalNearEndbool&输出:目标是否接近路径末端。Output: whether the goal is near the path's end.
Output

无返回值。副作用:写入转向方向与三个状态标志,推进/回退 CurrentPathIndex。

No return value. Side effects: writes the steering direction and three status flags, advances/rewinds CurrentPathIndex.

InitializeNavMeshAreaCosts void (struct FAreaCostContext& OutContext)

初始化面积成本上下文:bEnabled = bUseNavMeshAreaCosts,MaxMultiplier = MaxAreaCostMultiplier;关闭时保持默认(全 1.0)。开启时:① 从 NavMesh 的 64 个面积 ID 查面积类 CDO,取其 DefaultCost;② 应用 AreaCostOverrides(钳制 [0.1, 255])。供 Dijkstra 与可视化使用(>1000 视为不可通行,×100 惩罚)。

Initializes the area cost context: bEnabled = bUseNavMeshAreaCosts, MaxMultiplier = MaxAreaCostMultiplier; disabled keeps the defaults (all 1.0). When enabled: ① queries the NavMesh's 64 area IDs for the area class CDO and reads its DefaultCost; ② applies AreaCostOverrides (clamped to [0.1, 255]). Used by Dijkstra and visualization (costs > 1000 treated as impassable with a ×100 penalty).

Input
参数 Param类型 Type说明 Description
OutContextstruct FAreaCostContext&输出:填好的面积成本上下文(静态文件内结构,含 64 项成本数组)。Output: the filled area cost context (a file-local static struct with a 64-entry cost array).
Output

无返回值。副作用:填充 OutContext 的成本数组与开关。

No return value. Side effects: fills OutContext's cost array and toggles.

DebugDrawNavMeshAreaCosts void

编辑器调试:在 bDebugDrawAreaCosts 且 NavMesh 模式下,遍历 Detour 网格的地面多边形,对非默认成本(≠1.0)的多边形按成本梯度上色(绿 1.0 → 黄 5.0 → 红 10.0+)。注意当前实现只计算了颜色与中心点,未找到实际 DrawDebug 调用的完整代码路径。

Editor debug: with bDebugDrawAreaCosts in NavMesh mode, walks the Detour mesh's ground polygons and colors non-default-cost (≠1.0) polygons by a cost gradient (green 1.0 → yellow 5.0 → red 10.0+). Note the current implementation computes colors and centers but the full DrawDebug call path is not present.

Input

无参数。

No parameters.

Output

无返回值。副作用:计算面积成本可视化数据(绘制调用不完整)。

No return value. Side effects: computes area-cost visualization data (drawing call incomplete).

UpdateCellMap UFUNCTION void (FCellStruct NewCell)

异步 trace 完成回调(绑定到 DoneTraceDelegate):把结果写回 InitialCellsArray[CoordToIndex(NewCell.gridCoord)],加入 GridModifiedSet,递减 TraceRemaining;归零时执行 DoneAllTracesDelegate(推进异步更新的下一步)。

Async trace completion callback (bound to DoneTraceDelegate): writes the result back into InitialCellsArray[CoordToIndex(NewCell.gridCoord)], adds it to GridModifiedSet, and decrements TraceRemaining; at zero, fires DoneAllTracesDelegate (advancing the async update).

Input
参数 Param类型 Type说明 Description
NewCellFCellStruct异步查询完成的格子数据。Cell data completed by an async query.
Output

无返回值。副作用:写回格子、更新修改集合、递减计数并可能触发完成委托。

No return value. Side effects: writes back the cell, updates the modified set, decrements the counter and may fire the completion delegate.

CollectNavLinkProxies void

收集场景中的 NavLinkProxy 并建立 NavLinkCache:清空缓存;遍历所有 NavLinkProxy 的 PointLinks,把链接端点变换到世界后与 Detour 网格的 off-mesh 连接按端点距离匹配(50cm 容差,含反向匹配)得到链接 PolyRef;把两端投影到导航网格并验证为地面多边形,记录 LeftGroundPolyRef/RightGroundPolyRef;存入缓存并置 bNavLinkCacheInitialized = true。无代理时缓存直接标记为已初始化。

Collects NavLinkProxies from the scene and builds NavLinkCache: clears the cache; for every NavLinkProxy's PointLinks, transforms the link endpoints to world space and matches them against the Detour mesh's off-mesh connections by endpoint distance (50 cm tolerance, reversed matching included) to obtain the link poly ref; projects both ends onto the nav mesh, verifying ground polygons, recording LeftGroundPolyRef/RightGroundPolyRef; stores the entry and sets bNavLinkCacheInitialized = true. With no proxies, the cache is marked initialized immediately.

Input

无参数。

No parameters.

Output

无返回值。副作用:重建 NavLinkCache 并置初始化标记。

No return value. Side effects: rebuilds NavLinkCache and sets the initialization flag.

QueryNavLinkDirection ENavLinkQueryResult const (int64 LinkPolyRef, const FVector& QueryLocation, FNavLinkQueryData& OutData)

从缓存查询 NavLink 方向(无回退,找不到即失败):缓存未初始化 → CacheNotInitialized;PolyRef 为 0 → InvalidPolyRef;缓存无此条或无效 → NotFound;命中则填 OutData(方向/端点/来源名),并按查询点与端点的 3 米距离阈值置 bIsAtLeftEnd/bIsAtRightEnd,返回 Success。

Queries NavLink direction from the cache (no fallback — fails loudly): cache not initialized → CacheNotInitialized; poly ref 0 → InvalidPolyRef; entry missing or invalid → NotFound; on hit fills OutData (direction/endpoints/source name), sets bIsAtLeftEnd/bIsAtRightEnd by the 3 m distance threshold from the query point, and returns Success.

Input
参数 Param类型 Type说明 Description
LinkPolyRefint64链接多边形 PolyRef。Link polygon poly ref.
QueryLocationconst FVector&查询位置(用于端点邻近判定)。Query location (for endpoint proximity).
OutDataFNavLinkQueryData&输出:查询数据。Output: query data.
Output

返回 ENavLinkQueryResult;成功时填充 OutData。

Returns an ENavLinkQueryResult; fills OutData on success.

ValidateNavLinkCache void

编辑器调试工具(头文件 UFUNCTION 已注释):校验缓存条目的 bIsValid 与来源代理有效性,统计有效/无效数量。当前实现只统计,无日志输出或其它动作。

Editor debug tool (UFUNCTION commented out in the header): validates each cache entry's bIsValid and source proxy validity, counting valid/invalid entries. The current implementation only counts — no logging or other action.

Input

无参数。

No parameters.

Output

无返回值。副作用:无(缓存未初始化时直接返回)。

No return value. Side effects: none (returns early when the cache is uninitialized).

成员变量 Members

生成模式与边界 Generation & Bounds

名称 Name类型 Type默认值说明 Description
GenerationModeEFlowFieldModeGrid生成模式(见 EFlowFieldMode)。Generation mode (see EFlowFieldMode).
TargetNavMeshNameFName空要使用的 RecastNavMesh Actor 名;空 = 用默认 NavMesh(仅 NavMesh 模式可编辑)。Name of the RecastNavMesh actor to use; empty = default NavMesh (editable in NavMesh mode only).
DiagonalNeighborSearchDistfloat0.0f网格状 NavMesh 上搜索对角邻居的距离(启用对角流场);0 = 禁用。Distance to search for diagonal neighbors on grid-like NavMesh (enables diagonal flow); 0 = disabled.
flowFieldSizeFVector(10000, 10000, 1000)流场寻路边界缩放(单位),仅 Grid 模式可编辑。Flow field pathfinding boundary scale (units); editable in Grid mode only.
cellSizefloat300.f格子尺寸(单位)。Cell size (units).
initialCostint321所有格的初始成本(0–255),仅 Grid 模式可编辑。Initial cost of all cells (0–255); editable in Grid mode only.
StyleEStyleAdjacentFirst方向偏好风格(见 EStyle)。Direction preference style (see EStyle).
bStraightFirstbooltrue开启时先做目标视线检查,通畅则直接指向目标(两种风格均生效)。When on, performs a line-of-sight check to the goal and points directly when clear (works with both styles).
PathStopSearchDistFVector2D(500.0, 500.0)在障碍内或无网格时搜索有效地面的最大距离(X = 水平,Y = 垂直)。Max distance to search for valid ground when inside an obstacle or off the navmesh (X = horizontal, Y = vertical).
RefreshIntervalfloat0.5f运行时定时更新间隔(秒)。Runtime timed-update interval (seconds).
bIgnoreInternalObstacleCellsboolfalse计算时跳过障碍内部的格子(仅 Grid 模式可编辑)。Skip cells inside obstacles during calculation (editable in Grid mode only).

目标与修改器 Goals & Modifiers

名称 Name类型 Type默认值说明 Description
GoalActorsTArray<TSoftObjectPtr<AActor>>空目标 Actor;不填时用 GoalLocations。Goal actors; when empty, GoalLocations is used instead.
GoalLocationsTArray<FVector>空手动目标位置(不想填目标 Actor 时用)。Manual goal locations (used when no goal actor is filled in).
IncludeModifiersTArray<TSoftObjectPtr<AFlowFieldModifier>>空额外包含的修改器(也可以把修改器挂到流场 Actor 下),仅 Grid 模式可编辑。Additional modifiers to include (modifiers may also be attached to the flow field actor); editable in Grid mode only.
ExtraCostsTMap<int32,int32>空静态附加成本:键 = 格子索引,值加到该格 cost(钳制 [0,255])。Static extra costs: key = cell index, value added to that cell's cost (clamped to [0,255]).
DirModifiersTArray<TWeakObjectPtr<AFlowFieldDirModifier>>空方向修改器活动列表(运行时注册 + Include/Attach 合并收集,按 priority 排序)。Direction-modifier active list (runtime registrations merged with Include/Attach collection, sorted by priority).
CostModifiersTArray<TWeakObjectPtr<AFlowFieldCostModifier>>空成本修改器活动列表(运行时注册 + Include/Attach 合并收集,按 priority 排序)。Cost-modifier active list (runtime registrations merged with Include/Attach collection, sorted by priority).
GridModifiersTArray<TWeakObjectPtr<AFlowFieldGridModifier>>空网格修改器活动列表(运行时注册 + Include/Attach 合并收集)。Grid-modifier active list (runtime registrations merged with Include/Attach collection).
RuntimeDirModifiersTArray<TWeakObjectPtr<AFlowFieldDirModifier>>空运行时/手动注册的方向修改器集合(推模式)——GetAllModifiers 重扫的基底,重扫不丢;每次重扫重新盖回活动列表。与活动列表同为弱引用。Runtime/manual-registered direction modifier set (push model) — the rescan-surviving base GetAllModifiers merges on top of; re-stamped into the actives on every rescan. Weak like the active lists.
RuntimeCostModifiersTArray<TWeakObjectPtr<AFlowFieldCostModifier>>空运行时/手动注册的成本修改器集合(推模式),语义同 RuntimeDirModifiers。Runtime/manual-registered cost modifier set (push model); same semantics as RuntimeDirModifiers.
RuntimeGridModifiersTArray<TWeakObjectPtr<AFlowFieldGridModifier>>空运行时/手动注册的网格修改器集合(推模式),语义同 RuntimeDirModifiers。Runtime/manual-registered grid modifier set (push model); same semantics as RuntimeDirModifiers.

环境查询 Environment Query

名称 Name类型 Type默认值说明 Description
traceGroundboolfalse开启后对所有格 trace 地面对象类型并对齐地面(仅 Grid 模式可编辑)。When on, traces all cells for ground object types and aligns to the ground (editable in Grid mode only).
groundObjectTypeTArray<TEnumAsByte<EObjectTypeQuery>>空流场系统对齐的对象类型。Object types the flow field aligns to.
traceObstaclesboolfalse开启后建格时对非地面对象类型做球体 trace 判障碍。When on, sphere-traces for meshes not in the ground object types during grid creation.
obstacleObjectTypeTArray<TEnumAsByte<EObjectTypeQuery>>空被视为障碍的对象类型。Object types the flow field deems obstacles.
maxWalkableAnglefloat45.f超过该坡度的格视为障碍(度)。Cells steeper than this inclination are obstacles (degrees).

可视化 Visualization

名称 Name类型 Type默认值说明 Description
bEditorLiveUpdatebooltrue编辑器内实时更新流场。Live-update the flow field in the editor.
drawCellsInEditorbooltrue编辑器内显示调试网格。Shows the debug grid in the editor.
drawArrowsInEditorbooltrue编辑器内显示流场箭头。Shows the flow field arrows in the editor.
drawCellsInGameboolfalse游戏内显示调试网格。Shows the debug grid in-game.
drawArrowsInGameboolfalse游戏内显示流场箭头。Shows the flow field arrows in-game.
drawGraphEdgesInGameboolfalse游戏内逐帧绘制同步 NavMesh 基底的图边调试线(Tick 中):银 = 普通地面多边形,橙 = 代价被 modifier 改动的多边形,品红 = NavLink 段。仅对锁步同步 NavMesh 场有意义(画复制品的真实轮廓);大网格开销高。Draws the synced NavMesh substrate's graph edges in-game as per-frame debug lines (in Tick): silver = normal ground polys, orange = cost-modified polys, magenta = NavLink segments. Only meaningful on a lockstep-synced NavMesh field (draws the replica's actual outlines); heavy on large meshes.
ArrowSizefloat300.0f调试箭头尺寸。Debug arrow size.
DrawOffsetfloat20.0f调试箭头额外高度偏移。Additional height offset for debug arrows.
ArrowBaseMatTObjectPtr<UMaterialInterface>—箭头基础材质(生成 DMI)。Arrow base material (for the DMI).
CellBaseMatTObjectPtr<UMaterialInterface>—格子贴花基础材质(生成 DMI)。Cell decal base material (for the DMI).

NavMesh 面积成本 NavMesh Area Costs

名称 Name类型 Type默认值说明 Description
bUseNavMeshAreaCostsbooltrue在 NavMesh 模式生成期间应用 NavModifierVolume 面积成本(UPROPERTY 已注释,但变量生效,代码读取它)。Apply NavModifierVolume area costs during NavMesh-mode generation (the UPROPERTY is commented out, but the variable is live and read).
AreaCostOverridesTMap<int32, float>空手动面积成本覆盖(面积 ID → 成本乘数);空 = 用 NavMesh 默认。Manual area cost overrides (Area ID → cost multiplier); empty = NavMesh defaults.
MaxAreaCostMultiplierfloat10.0f面积成本乘数上限(防止无限成本破坏 Dijkstra)。Maximum area cost multiplier (prevents infinite costs from breaking Dijkstra).
bDebugDrawAreaCostsboolfalse编辑器内按面积成本给多边形着色(调试)。Debug-draw NavMesh polygons colored by area cost in the editor.

锁步同步基底 Lockstep-synced Substrate

名称 Name类型 Type默认值说明 Description
bSyncedSubstrateboolfalse是否已导入基底(ImportSubstrateBytes 生效)。置位后本场禁用引擎 navmesh 查询,路径/方向在导入字节上本地计算(2026-09-09 失步结论:引擎查询链是逐端发散源)。Whether a substrate has been imported (ImportSubstrateBytes applied). Once set, engine navmesh queries are forbidden on this field — paths/directions compute locally on the imported bytes (2026-09-09 desync conclusion: the engine query chain is a per-peer divergence source).
SyncedSubstrateVersionuint320已应用流的内容哈希(幂等键;差分使其前进)。BP 侧经 GetSyncedSubstrateVersion 读(int32)。Applied stream's content hash (idempotency key; deltas advance it). Read on the BP side via GetSyncedSubstrateVersion (int32).
SyncedSubstrateModeuint80导出时的生成模式(0 = Grid,1 = NavMesh)。Generation mode at export time (0 = Grid, 1 = NavMesh).
bSyncedClientBuildWarnedboolfalse客户端构建闸的一次性日志标记(首个 Warning 后不再重复)。One-shot guard log flag for the client-side build gate (no repeat after the first Warning).
SyncedReplicaMeshdtNavMesh*nullptrFFC 自有的 dtNavMesh 复制品(dtAllocNavMesh/dtFreeNavMesh;tile blob 由 DT_TILE_FREE_DATA 生命周期托管)。由服务器原始 tile blob 重建——拓扑、detail 网格、离网连接与引擎逐字节一致;此前的质心图载体已退役(无法复现引擎路径形状)。FFC-owned dtNavMesh replica (dtAllocNavMesh/dtFreeNavMesh; tiles own their blobs via DT_TILE_FREE_DATA). Rebuilt from the server's original tile blobs — topology, detail meshes and off-mesh cons byte-identical to the engine; the earlier centroid-graph carrier was retired (could not reproduce engine path shapes).
SyncedAreaCostsTStaticArray<float, 64>—导入的 UNavArea CDO 代价表——供 FAreaCostContext 洪泛与复制品查询过滤器(客户端无 navmesh actor 可查)。由 bSyncedAreaCostsValid 标记有效性。Imported UNavArea CDO cost table — feeds FAreaCostContext flooding and the replica query filters (clients hold no navmesh actor to ask). Validity marked by bSyncedAreaCostsValid.
bSyncedAreaCostsValidboolfalseSyncedAreaCosts 是否来自导入流。Whether SyncedAreaCosts came from the stream.
SyncedGoalLocationsTArray<FVector>空服务器导出时一次性捕获的目标集——零竞态洪泛输入(晚加入端导入早于 goal actor 解析,读本地 GoalActors 曾使双端分叉)。运行时改目标需重发基底。Goal set captured ONCE at server export — the race-free flood input (late-join imports run before goal actors resolve on the client; flooding from local GoalActors forked peers). Runtime goal changes require re-sending the substrate.
bSyncedFloodAppliedboolfalse已在应用版本上完成目标洪泛——幂等补发仅在此为真时跳过(未洪泛的同版本补发只重跑洪泛)。Goal flood ran to completion on the applied stream version — idempotent re-delivery skips ONLY when this is true (an unflooded same-version re-delivery re-runs just the flood).

组件与运行时数据 Components & Runtime Data

名称 Name类型 Type默认值说明 Description
VolumeTObjectPtr<UBoxComponent>—流场边界盒体(无碰撞)。Flow field bounds box (non-colliding).
ISM_ArrowsTObjectPtr<UInstancedStaticMeshComponent>—方向箭头实例化网格。Instanced arrow mesh.
Decal_CellsTObjectPtr<UDecalComponent>—格子贴花组件。Cell decal component.
BillboardTObjectPtr<UBillboardComponent>—编辑器图标。Editor icon.
InitialCellsArrayTArray<FCellStruct>空环境查询后的基础格数据(Erase 恢复源)。Base cell data after environment queries (Erase restore source).
CurrentCellsArrayTArray<FCellStruct>空当前流场数据(含成本/方向修改)。Current flow field data (with cost/direction modifications).
BaseDirArrayTArray<FVector3f>空Grid 模式方向修改前的基准方向(Erase 恢复源)。Grid-mode base directions before direction modifiers (Erase restore source).
BaseNavMeshDirMapTMap<int64, FVector3f>空NavMesh 模式方向修改前的基准方向(PolyRef → 方向)。NavMesh-mode base directions before direction modifiers (PolyRef → direction).
NavMeshCellMapTMap<int64, FCellStruct>空NavMesh 模式的 PolyRef → 格子映射。NavMesh-mode PolyRef → cell map.
GridModifiedSetTSet<FIntVector>空被网格修改器改动的坐标(贴花 G 通道)。Coords modified by grid modifiers (decal G channel).
DirModifiedSetTSet<FIntVector>空被方向修改器改动的坐标(箭头染蓝)。Coords modified by direction modifiers (blue arrows).
NavMeshDirModifiedSetTSet<int64>空被方向修改器改动的 PolyRef。Poly refs modified by direction modifiers.
GoalActorLocationsTArray<FVector>空解析后的目标 Actor 位置。Resolved goal actor locations.
GoalGridCoordsTArray<FIntVector>空目标网格坐标。Goal grid coords.
bIsValidGoalCoordsTArray<bool>空目标坐标有效性(当前实现未使用)。Goal coord validity (unused in the current implementation).
xNumint32RoundToInt(flowFieldSize.X / cellSize)X 方向格数。Grid count on X.
yNumint32RoundToInt(flowFieldSize.Y / cellSize)Y 方向格数。Grid count on Y.
nextTickTimeLeftfloatRefreshInterval定时更新剩余时间。Remaining time until the timed update.
bIsGridDirtybooltrue网格是否需要重建(CreateGrid 的闸门)。Whether the grid needs rebuilding (CreateGrid's gate).
bIsBeginPlaybooltrue首次运行标记:为 true 时网格未初始化,查询返回无效;首次更新后置 false。First-run marker: while true the grid is uninitialized and queries return invalid; cleared after the first update.
bNavMeshFlowMissingLoggedboolfalseNavMesh 模式「无流场」Error 是否已记录(下次成功生成时清零重置)。Whether the NavMesh-mode "no flow field" Error has been logged (cleared on the next successful generation).
NavMeshFlowMissingStreakint320连续失败的 NavMesh 生成次数——Error 仅在超过阈值(3)后触发,跳过加载期瞬态。Consecutive failed NavMesh generations — the Error fires only past the threshold (3) to skip init-time transients.
bNavMeshNoGoalsWarnedboolfalse合法的「无目标 NavMesh 用法」一次性 Warning 是否已发出(高度场/独立寻路仍可用)。Whether the one-shot Warning for the legal no-goal NavMesh usage has been emitted (height field / individual pathfinding still work).
NavLinkCacheTMap<int64, FNavLinkInfo>空NavLink 方向缓存(PolyRef → 信息)。NavLink direction cache (PolyRef → info).
bNavLinkCacheInitializedboolfalseNavLink 缓存是否已初始化。Whether the NavLink cache has been initialized.
actorLocFVectorGetActorLocation()缓存的 Actor 位置(InitFlowField 刷新)。Cached actor location (refreshed by InitFlowField).
actorRotFRotatorGetActorRotation()缓存的 Actor 旋转。Cached actor rotation.
offsetLocFVector(0,0,0)网格半尺寸偏移(xNum*cellSize/2, yNum*cellSize/2, 0)。Grid half-size offset (xNum*cellSize/2, yNum*cellSize/2, 0).
relativeLocFVector(0,0,0)actorLoc - offsetLoc,世界↔网格转换的基准。actorLoc - offsetLoc, the world↔grid conversion base.
ArrowDMITObjectPtr<UMaterialInstanceDynamic>—箭头动态材质。Arrow dynamic material instance.
CellDMITObjectPtr<UMaterialInstanceDynamic>—格子贴花动态材质。Cell decal dynamic material instance.
DigitDMITObjectPtr<UMaterialInstanceDynamic>—数字动态材质(数字绘制被注释,当前未使用)。Digit dynamic material (digit drawing is commented out; currently unused).
TransientTextureTObjectPtr<UTexture2D>—格子数据烘焙的瞬时纹理。Transient texture baking cell data.
CachedRecastNavMeshTWeakObjectPtr<ARecastNavMesh>—缓存的 RecastNavMesh(UPROPERTY Transient)。Cached RecastNavMesh (UPROPERTY Transient).
TraceRemainingTAtomic<int32>0进行中的异步 trace 计数。In-flight async trace counter.
DoneTraceDelegateFDoneTraceDelegate—单个 trace 完成委托(绑定 UpdateCellMap)。Single-trace completion delegate (bound to UpdateCellMap).
DoneAllTracesDelegateFDoneAllTracesDelegate—全部 trace 完成委托(绑定 AsyncUpdateStep2)。All-traces-complete delegate (bound to AsyncUpdateStep2).
DefaultCellFCellStructFCellStruct()查询失败时返回的默认格。Default cell returned on failed queries.
FlowFieldLayersTMap<int32, FFlowFieldLayer>空层存储(LayerID → 层)。Layer storage (LayerID → layer).
NextLayerIDint320下一个层 ID 分配计数。Next layer ID allocation counter.
PendingLayerDestroysTArray<int32>空ReleaseLayerUser 排入的待销毁层(LayerID)——仅在串行窗口经 FlushAllPendingLayerDestroys 冲刷;移除前复查 UserCount == 0。Layer IDs queued for deferred destruction by ReleaseLayerUser — drained ONLY in the serial window via FlushAllPendingLayerDestroys; the flush re-checks UserCount == 0 before removal.
LiveInstancesstatic TArray<TWeakObjectPtr<AFlowField>>空存活实例登记表(静态,仅游戏线程)——静态冲刷遍历它;modifier 的推模式自注册/收编也扫描它。Live-instance registry (static, game thread only) — iterated by the static flush; the modifier push model's self-registration/adoption scans it too.
OnSimulationTickstatic FFlowFieldGlobalTick—全局模拟 tick 委托(静态)。Global simulation tick delegate (static).

UUpdateFlowFieldAsyncAction UCLASS

流场异步重建的蓝图异步节点。两种模式:MaxTicksToComplete > 0 时把计算 offload 到线程池,并订阅 AFlowField::OnSimulationTick 在模拟 tick 中轮询 future——达到截止 tick 时置 Context.bAbortStep 通知宿主中止模拟步等待;否则后台线程计算 + 游戏线程应用。完成后广播 OnCompleted 并销毁。

Blueprint async node for asynchronous flow field rebuilds. Two modes: with MaxTicksToComplete > 0, the computation is offloaded to the thread pool and AFlowField::OnSimulationTick is subscribed to poll the future during simulation ticks — hitting the tick deadline sets Context.bAbortStep to make the host abort the simulation step and wait; otherwise a background thread computes and the game thread applies. On completion, broadcasts OnCompleted and destroys itself.

继承 Inheritance

UBlueprintAsyncActionBase → UUpdateFlowFieldAsyncAction

公开方法 Public Methods

UpdateFlowFieldAsync static UUpdateFlowFieldAsyncAction* (UObject* WorldContext, AFlowField* InFlowField, int32 MaxTicksToComplete, bool bFullRebuild)

节点工厂:校验世界上下文与流场(无效返回 nullptr);创建动作对象,保存流场弱引用、MaxTicksToComplete 与 bFullRebuild,注册到 GameInstance;把流场的 DoneTraceDelegate 绑定到 UpdateCellMap、DoneAllTracesDelegate 绑定到本对象的 AsyncUpdateStep2。

Node factory: validates the world context and flow field (returns nullptr when invalid); creates the action, stores the flow field weak reference, MaxTicksToComplete and bFullRebuild, and registers with the game instance; binds the flow field's DoneTraceDelegate to UpdateCellMap and DoneAllTracesDelegate to this object's AsyncUpdateStep2.

Input
参数 Param类型 Type说明 Description
WorldContextUObject*世界上下文。World context.
InFlowFieldAFlowField*要更新的流场。The flow field to update.
MaxTicksToCompleteint320 = 完全异步不限期;>0 = 限制在该数量个模拟 tick 内完成。0 = fully async without a time limit; >0 = complete within that many simulation ticks.
bFullRebuildbool是否整格重建(完整环境查询)。Whether to rebuild the grid from scratch (full environment queries).
Output

返回动作对象;世界/流场无效时返回 nullptr。副作用:绑定两个 trace 委托。

Returns the action object, or nullptr when the world/flow field is invalid. Side effects: binds the two trace delegates.

Activate virtual void

节点启动:① MaxTicksToComplete > 0 时走同步预备——InitFlowField/GetGoalLocation,NavMesh 模式直接 AsyncUpdateStep2,Grid 模式按需收集修改器/建格/同步修改网格后进 Step2;② 否则走默认异步路径 AsyncUpdateStep1(下帧游戏线程执行预备)。

Node activation: ① with MaxTicksToComplete > 0, runs the synchronous prep — InitFlowField/GetGoalLocation; NavMesh mode goes straight to AsyncUpdateStep2; Grid mode collects modifiers/creates the grid/synchronously modifies it as needed, then Step2; ② otherwise the default async path runs AsyncUpdateStep1 (prep on the game thread next frame).

Input

无参数。

No parameters.

Output

无返回值。副作用:启动流场更新的预备流程;流场已失效时直接销毁。

No return value. Side effects: starts the flow field update prep; destroys itself when the flow field is gone.

AsyncUpdateStep1 void

异步预备(游戏线程,下帧执行):InitFlowField/GetGoalLocation;NavMesh 模式直接 Step2;Grid 模式按需收集修改器/建格,非全量重建时走 ModifyGridAsync 发起异步 trace——TraceRemaining == 0(无 trace)时直接 Step2,否则等 DoneAllTracesDelegate。

Async prep (game thread, next frame): InitFlowField/GetGoalLocation; NavMesh mode goes straight to Step2; Grid mode collects modifiers / creates the grid as needed, and for non-full rebuilds runs ModifyGridAsync to launch async traces — with TraceRemaining == 0 (no traces) Step2 runs directly, otherwise it waits for DoneAllTracesDelegate.

Input

无参数。

No parameters.

Output

无返回值。副作用:执行预备并启动异步 trace(或直接进入 Step2)。

No return value. Side effects: runs the prep and launches async traces (or enters Step2 directly).

AsyncUpdateStep2 UFUNCTION void

计算与应用:① NavMesh 模式——游戏线程准备目标多边形与面积成本上下文,构造计算 lambda(调 CalculateNavMeshFlow,无 line trace)与应用 lambda(写回 NavMeshCellMap、存基准方向、套方向修改器、重建占位目标格、按开关重绘箭头、清 bIsBeginPlay、广播 OnCompleted);MaxTicksToComplete > 0 时 offload 线程池并订阅 OnSimulationTick,否则后台线程计算 + 游戏线程应用。② Grid 模式——捕获格数组/修改器/目标,计算 lambda(ModifyCost → CalculateFlowField → 存 BaseDirArray → ModifyFlowField)与应用 lambda(写回三个数组、按开关重绘、清标记、广播、销毁),分发同上。

Computation and application: ① NavMesh mode — the game thread prepares goal polygons and the area cost context, builds a calculate lambda (calls CalculateNavMeshFlow, no line trace) and an apply lambda (writes back NavMeshCellMap, stores base directions, applies direction modifiers, rebuilds the placeholder goal cell, redraws arrows per toggles, clears bIsBeginPlay, broadcasts OnCompleted); with MaxTicksToComplete > 0 it offloads to the thread pool and subscribes to OnSimulationTick, otherwise a background thread computes and the game thread applies. ② Grid mode — captures the cell arrays/modifiers/goals; the calculate lambda runs ModifyCost → CalculateFlowField → stores BaseDirArray → ModifyFlowField; the apply lambda writes back the three arrays, redraws per toggles, clears the marker, broadcasts and destroys; dispatch as above.

Input

无参数。

No parameters.

Output

无返回值。副作用:更新流场数据/可视化,广播 OnCompleted,销毁本对象。

No return value. Side effects: updates the flow field data/visualization, broadcasts OnCompleted, destroys this object.

OnMassBattleTick void (FFlowFieldTickContext& Context)

限 tick 模式下的模拟 tick 回调:递增 ElapsedTicks;流场失效则解绑、销毁;future 就绪则应用结果(与 ApplyTask 相同的写回逻辑)、解绑、重置 future、广播 OnCompleted 并销毁;未就绪但已达到 MaxTicksToComplete 时置 Context.bAbortStep = true 让宿主中止模拟步等待。

Simulation tick callback in tick-limited mode: increments ElapsedTicks; an invalid flow field unbinds and destroys; a ready future applies the result (same write-back logic as ApplyTask), unbinds, resets the future, broadcasts OnCompleted and destroys; when not ready but at MaxTicksToComplete, sets Context.bAbortStep = true so the host aborts the simulation step and waits.

Input
参数 Param类型 Type说明 Description
ContextFFlowFieldTickContext&tick 上下文;超截止时写 bAbortStep。Tick context; bAbortStep is written when the deadline is exceeded.
Output

无返回值。副作用:应用结果/置中止标记/解绑并销毁。

No return value. Side effects: applies the result / sets the abort flag / unbinds and destroys.

成员变量 Members

名称 Name类型 Type默认值说明 Description
OnCompletedFDoneUpdateDelegate (BlueprintAssignable)—更新完成输出引脚。Update-completed output pin.
FlowFieldTWeakObjectPtr<AFlowField>—要更新的流场弱引用。Weak reference to the flow field to update.
MaxTicksToCompleteint3200 = 完全异步;>0 = 限 tick 完成。0 = fully async; >0 = tick-limited completion.
ElapsedTicksint320已消耗的模拟 tick 数。Simulation ticks consumed so far.
bFullRebuildboolfalse是否整格重建。Whether to rebuild the grid from scratch.
NavMeshFutureTFuture<TMap<int64, FCellStruct>>—NavMesh 计算 future。NavMesh computation future.
GridFutureTFuture<FGridResult>—Grid 计算 future(FGridResult = 格数组 + 修改集 + 基准方向)。Grid computation future (FGridResult = cell array + modified set + base directions).
MassBattleTickHandleFDelegateHandle—OnSimulationTick 订阅句柄。OnSimulationTick subscription handle.
CachedWorldTWeakObjectPtr<UWorld>—缓存的世界弱引用(当前实现未使用)。Cached world weak reference (unused in the current implementation).

管线角色 Pipeline Role

生成管线(每类入口一致):InitFlowField → GetGoalLocation → GetAllModifiers → CreateGrid(Grid)→ ModifyGrid/ModifyGridAsync(Grid)→ ModifyCost → CalculateFlowField(Grid)/CalculateFlowField_NavMesh(NavMesh,内部 InitializeNavMeshAreaCosts + 静态 CalculateNavMeshFlow)→ 存 BaseDirArray/BaseNavMeshDirMap → ModifyFlowField/ModifyFlowField_NavMesh → DrawCells/DrawArrows。入口包括:编辑器 DrawDebug(Construction)、运行时 UpdateFlowField/TickFlowField(定时)、异步 UUpdateFlowFieldAsyncAction(Step1 → [异步 trace 经 UpdateCellMap → DoneAllTracesDelegate] → Step2 → 完成广播;限 tick 模式经 OnSimulationTick 轮询 future,截止时置 bAbortStep)。运行时消费方:查询 QueryNavigation/QueryNavigationAdvanced(含螺旋兜底)、平均方向 GetAverageDirection、个体寻路 FindPath/FindPathAStar/FindPathNavMesh、路径转向 GetSteeringDirection(供 UFFCPathingComponent),以及 UFFCPathingComponent 的 FlowField 跟随模式。Layer API 复用同一套计算(UpdateLayer 调 CalculateFlowField/CalculateNavMeshFlow)产出独立叠加。

托管层生命周期(MassBattle 协作):UMassBattleFuncLib::GetOrAcquireFlowFieldLayer(仅限锁步指令内,任务重建窗口拒绝)→ FindManagedLayerByGoalHash 命中复用(必要时 UpdateManagedLayerGoals)或 CreateManagedLayer 新建,随后 AcquireLayerUser;UMassBattleBPTaskAgentsMoveTo 持层并在任务结算时 ReleaseLayerUser;UMassBattleSubsystem 在串行窗口(任何并行移动阶段读层之前;resync 任务重建窗口内抑制)调用静态 FlushAllPendingLayerDestroys 排空待销毁队列。

modifier 推模式(双向发现,免疫加载顺序):AFlowFieldModifier::BeginPlay 报到 LiveModifiers 并遍历 AFlowField::LiveInstances 对同世界场 RegisterModifier;AFlowField::BeginPlay 对称地遍历 LiveModifiers 收编同世界成员;两侧 EndPlay 互撤销。注册即时进活动列表并记入 Runtime*Modifiers 集合——GetAllModifiers 以其为重扫基底,full rebuild 不再抹掉运行时注册。

锁步基底同步:服务器 AMassBattleNetworkGameModeBase::SendLockstepCommandToClients_RebuildFlowField → ExportSubstrateBytes + 服务器自导入 ImportSubstrateBytes(全端同字节);命令在 AMassBattleNetworkGameStateBase 执行时按命令类型选择 ImportSubstrateBytes/ImportSubstrateDeltaBytes;晚加入补发由 UMassBattleNetworkSubsystem 调 ImportSubstrateBytes(幂等)。同步场的 FindPath 分派到 FindPathReplica(NavMesh)/FindPathAStar(Grid),IsValidPath 走 FindPathReplica;引擎 navmesh 查询自此绝迹。

Generation pipeline (identical across entries): InitFlowField → GetGoalLocation → GetAllModifiers → CreateGrid (Grid) → ModifyGrid/ModifyGridAsync (Grid) → ModifyCost → CalculateFlowField (Grid) / CalculateFlowField_NavMesh (NavMesh; internally InitializeNavMeshAreaCosts + the static CalculateNavMeshFlow) → store BaseDirArray/BaseNavMeshDirMap → ModifyFlowField/ModifyFlowField_NavMesh → DrawCells/DrawArrows. Entries include: editor DrawDebug (Construction), runtime UpdateFlowField/TickFlowField (timed), and the async UUpdateFlowFieldAsyncAction (Step1 → [async traces via UpdateCellMap → DoneAllTracesDelegate] → Step2 → completion broadcast; tick-limited mode polls futures via OnSimulationTick, setting bAbortStep at the deadline). Runtime consumers: queries QueryNavigation/QueryNavigationAdvanced (with spiral fallback), average direction GetAverageDirection, individual pathfinding FindPath/FindPathAStar/FindPathNavMesh, path steering GetSteeringDirection (used by UFFCPathingComponent), and UFFCPathingComponent's flow field following mode. The Layer API reuses the same solvers (UpdateLayer calls CalculateFlowField/CalculateNavMeshFlow) to produce independent overlays.

Managed layer lifecycle (MassBattle-facing): UMassBattleFuncLib::GetOrAcquireFlowFieldLayer (lockstep command only; refused during the task-rebuild window) → reuse on a FindManagedLayerByGoalHash hit (with UpdateManagedLayerGoals when needed) or create via CreateManagedLayer, then AcquireLayerUser; UMassBattleBPTaskAgentsMoveTo holds layers and calls ReleaseLayerUser at task resolution; UMassBattleSubsystem calls the static FlushAllPendingLayerDestroys in its serial window (before any parallel move stage reads the layers; suppressed during the resync task-rebuild window) to drain the pending-destroy queue.

Modifier push model (two-way discovery, load-order-proof): AFlowFieldModifier::BeginPlay checks into LiveModifiers and iterates AFlowField::LiveInstances calling RegisterModifier on same-world fields; AFlowField::BeginPlay symmetrically iterates LiveModifiers to adopt same-world members; both EndPlays withdraw. Registration enters the active lists immediately plus the Runtime*Modifiers sets — GetAllModifiers uses those as its rescan base, so a full rebuild no longer wipes runtime registrations.

Lockstep substrate sync: the server's AMassBattleNetworkGameModeBase::SendLockstepCommandToClients_RebuildFlowField → ExportSubstrateBytes plus a server self-ImportSubstrateBytes (identical bytes on every peer); command execution in AMassBattleNetworkGameStateBase picks ImportSubstrateBytes/ImportSubstrateDeltaBytes by command type; late-join re-delivery goes through UMassBattleNetworkSubsystem calling ImportSubstrateBytes (idempotent). A synced field's FindPath dispatches to FindPathReplica (NavMesh) / FindPathAStar (Grid), and IsValidPath goes through FindPathReplica; engine navmesh queries never run on it again.

补充说明 Notes

1. EIndividualPathfindingMode 与 EDigitType(数字绘制)、DigitDMI 相关代码被注释/未使用,为预留设计。
2. bUseNavMeshAreaCosts / AreaCostOverrides / MaxAreaCostMultiplier / bDebugDrawAreaCosts 的 UPROPERTY 声明被注释掉(变量本身有效,代码读取),因此当前不可在编辑器面板配置,需代码设置。
3. DebugDrawNavMeshAreaCosts 计算了着色数据但缺少完整的绘制调用,视觉输出不完整。
4. GetCellAtCoord 在 NavMesh 模式返回 CurrentCellsArray[0](占位目标格),非真实多边形格;真实查询应走 GetCellAtLocation 或 QueryNavigation。

1. EIndividualPathfindingMode, EDigitType (digit drawing) and DigitDMI are commented-out/unused — reserved designs.
2. The UPROPERTY declarations of bUseNavMeshAreaCosts / AreaCostOverrides / MaxAreaCostMultiplier / bDebugDrawAreaCosts are commented out (the variables themselves are live and read), so they are not currently configurable in the editor panel — set them from code.
3. DebugDrawNavMeshAreaCosts computes coloring data but lacks the full draw call — the visual output is incomplete.
4. GetCellAtCoord returns CurrentCellsArray[0] (the placeholder goal cell) in NavMesh mode, not a real polygon cell; real queries should use GetCellAtLocation or QueryNavigation.