feat(ground-ai): follow baked navmesh paths with sliced searches

Native engine (native/wto-nav):
- Path searches are queued per slot and advanced with Detour's sliced
  search inside a per-frame time budget (navEngine.pathBudgetMsPerFrame),
  so a 4 km search no longer stalls a frame. The synchronous find_path
  op is gone.
- The battle's pack is read on a background thread when the mission
  finishes loading (prefetch); load_map only takes the result.
- New mesh queries: probe (surface, flags, room to the mesh edge),
  raycast, nearest walkable point, and dynamic cost circles for wrecks,
  jams and fresh obstacles that later searches route around.

Ground AI scripts:
- route picks the mesh tier by vehicle width and the cost filter by
  tracked or wheeled, plans on goal change, drift off the corridor, a
  timer or reported obstacles, and falls back to the stock road mesh
  only when the battle decided on the fallback.
- follow steers at a speed-scaled lookahead point and brakes ahead of
  sharp corners, narrow passages and the destination.
- avoid casts rays from both front hull corners that drive through
  objects the bake marks crushable, follows slower traffic, steps aside
  or yields by size priority in narrow passages.
- unstick escalates deterministically: back up along the corridor, mark
  a jam and replan, then log the spot and hand the order back.
- Flank lanes are built through the queued searches; rallies are not
  released while their lanes are still being built.
- Removed the 9-arc forward probing, 7-arc reverse probing, 145 m
  straight shortcuts, 165 m snapping and random sideways detours.

Tuning: new pathFollow section, navEngine.goalSnapRadiusM and
pathBudgetMsPerFrame, navBake.crushableMaxRiExtraHp passed to the
scripts; retired navigation.cornerBrakeAccel, stuckWindowSec,
stuckMinMoveM and unstickReverseSec. Launcher fields and en/zh-CN labels
updated.

Checked: root and launcher typecheck, MSVC build with no warnings in
project code, check-patches for 2.61.0.58 and 2.61.0.60, offline engine
run on avg_poland (prefetch, sliced searches within budget, slot
replacement, dynamic costs), isolated game copy build. daScript
compilation and in-battle behaviour still need the in-game run.
This commit is contained in:
N0VAN0M4LY committed 2026-12-05 17:38:41 +08:00
1 parent e0a344708d
commit ba947fe5b6
34 files changed
+2810 -911

No files matched your search

+172 -139
View File
@@ -1,69 +1,49 @@
/*
* In-game navigation engine (wto_nav_runtime.h): loads one `.wtonav` pack written by
* tools/navgen/bake into upstream Detour meshes and answers path queries for the ground AI.
* tools/navgen/bake into upstream Detour meshes, optionally on a background thread while the
* battle is still loading. Path searches live in wto_nav_paths.cpp, point queries and dynamic
* costs in wto_nav_queries.cpp.
*/
#include "wto_nav_runtime.h"
#include "wto_nav_format.h"
#include "wto_nav_internal.h"
#include "DetourAlloc.h"
#include "DetourCommon.h"
#include "DetourNavMesh.h"
#include "DetourNavMeshQuery.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <string>
#ifndef DT_VIRTUAL_QUERYFILTER
#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint cost filter"
#endif
namespace wtonav {
SRWLOCK g_lock = SRWLOCK_INIT;
Pack *g_pack;
QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT];
WtoNavStats g_stats;
namespace {
constexpr int kMaxSearchNodes = 32768;
constexpr int kMaxPathPolys = 4096;
constexpr size_t kMaxPackBytes = 512u * 1024u * 1024u;
constexpr size_t kMaxEverBytes = 64u * 1024u;
constexpr int kMaxLevelBlocks = 4096;
/* Area costs per WtoPolyArea, times a multiplier on chokepoint polygons. */
class WtoQueryFilter : public dtQueryFilter {
public:
float chokepointMul = 1.0f;
float getCost(const float *pa, const float *pb,
const dtPolyRef, const dtMeshTile *, const dtPoly *,
const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly,
const dtPolyRef, const dtMeshTile *, const dtPoly *) const override
{
float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea());
if (curPoly->flags & WTO_FLAG_CHOKEPOINT)
cost *= chokepointMul;
return cost;
}
};
struct Pack {
float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */
dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {};
dtNavMeshQuery *queries[WTO_NAV_TIER_COUNT] = {};
std::vector<WtoCoverPoint> covers;
std::vector<WtoTacticalCell> tactical;
};
SRWLOCK g_lock = SRWLOCK_INIT;
Pack *g_pack;
WtoQueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT];
bool g_filters_ready;
WtoNavStats g_stats;
/* A pack read on a background thread, waiting for wto_nav_load. Guarded by g_stage_lock. */
struct Staged {
std::wstring packPath;
std::wstring levelPath;
HANDLE thread = nullptr;
Pack *pack = nullptr;
WtoNavLoadInfo info = {};
};
SRWLOCK g_stage_lock = SRWLOCK_INIT;
Staged *g_staged;
void init_filters_locked()
{
if (g_filters_ready)
return;
for (WtoQueryFilter &filter : g_filters) {
for (QueryFilter &filter : g_filters) {
filter.setIncludeFlags(WTO_FLAG_WALK);
filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
}
@@ -75,7 +55,8 @@ void free_pack(Pack *pack)
if (pack == nullptr)
return;
for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) {
dtFreeNavMeshQuery(pack->queries[t]);
dtFreeNavMeshQuery(pack->pathQueries[t]);
dtFreeNavMeshQuery(pack->pointQueries[t]);
dtFreeNavMesh(pack->meshes[t]);
}
delete pack;
@@ -109,6 +90,15 @@ bool fits(const std::vector<uint8_t> &data, uint64_t offset, uint64_t size)
return offset <= data.size() && size <= data.size() - offset;
}
bool init_queries(Pack *pack, uint32_t tier)
{
pack->pathQueries[tier] = dtAllocNavMeshQuery();
pack->pointQueries[tier] = dtAllocNavMeshQuery();
return pack->pathQueries[tier] != nullptr && pack->pointQueries[tier] != nullptr &&
dtStatusSucceed(pack->pathQueries[tier]->init(pack->meshes[tier], kPathSearchNodes)) &&
dtStatusSucceed(pack->pointQueries[tier]->init(pack->meshes[tier], kPointSearchNodes));
}
bool load_tier(const std::vector<uint8_t> &data, const WtoNavHeader &hdr, uint32_t tier, Pack *pack, uint32_t *polys, char *detail, size_t detail_size)
{
uint64_t at = hdr.tierOffsets[tier];
@@ -156,8 +146,7 @@ bool load_tier(const std::vector<uint8_t> &data, const WtoNavHeader &hdr, uint32
}
*polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount;
}
pack->queries[tier] = dtAllocNavMeshQuery();
if (pack->queries[tier] == nullptr || dtStatusFailed(pack->queries[tier]->init(pack->meshes[tier], kMaxSearchNodes))) {
if (!init_queries(pack, tier)) {
snprintf(detail, detail_size, "tier %u query init failed", tier);
return false;
}
@@ -204,11 +193,96 @@ Pack *parse_pack(const std::vector<uint8_t> &data, WtoNavLoadInfo *info)
return pack;
}
/*
* Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry
* heights that are not on the ground, so a miss is retried over the mesh's whole height range,
* still within `snap` horizontally.
*/
/* Reads and parses a pack plus the level fingerprint; runs on any thread, touches no globals. */
Pack *read_pack(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info)
{
const double began = now_micros();
std::vector<uint8_t> data;
Pack *pack = nullptr;
memset(info, 0, sizeof(*info));
if (level_path != nullptr && level_path[0] != L'\0')
info->fingerprintKnown = wto_nav_read_level_fingerprint(level_path, info->levelSha1);
if (read_file(pack_path, data, info)) {
pack = parse_pack(data, info);
info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT;
}
if (pack != nullptr && info->fingerprintKnown)
info->fingerprintMatch = memcmp(info->packSha1, info->levelSha1, sizeof(info->packSha1)) == 0;
info->readMs = (now_micros() - began) / 1000.0;
return pack;
}
DWORD WINAPI prefetch_main(void *arg)
{
Staged *staged = (Staged *)arg;
staged->pack = read_pack(staged->packPath.c_str(), staged->levelPath.c_str(), &staged->info);
return 0;
}
/* Waits for the background read of `staged` and frees what it produced. */
void discard_staged(Staged *staged)
{
if (staged == nullptr)
return;
if (staged->thread != nullptr) {
WaitForSingleObject(staged->thread, INFINITE);
CloseHandle(staged->thread);
}
free_pack(staged->pack);
delete staged;
}
/* Takes the staged pack if it is `pack_path`; the caller then owns (and joins) it. */
Staged *take_staged(const wchar_t *pack_path)
{
AcquireSRWLockExclusive(&g_stage_lock);
Staged *staged = g_staged;
if (staged != nullptr && staged->packPath == pack_path)
g_staged = nullptr;
else
staged = nullptr;
ReleaseSRWLockExclusive(&g_stage_lock);
return staged;
}
void replace_pack(Pack *pack)
{
AcquireSRWLockExclusive(&g_lock);
init_filters_locked();
free_pack(g_pack);
g_pack = pack;
paths_reset_locked();
dynamic_reset_locked();
memset(&g_stats, 0, sizeof(g_stats));
g_stats.loaded = pack != nullptr;
ReleaseSRWLockExclusive(&g_lock);
}
} // namespace
float QueryFilter::getCost(const float *pa, const float *pb,
const dtPolyRef, const dtMeshTile *, const dtPoly *,
const dtPolyRef, const dtMeshTile *, const dtPoly *curPoly,
const dtPolyRef, const dtMeshTile *, const dtPoly *) const
{
float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea());
if (curPoly->flags & WTO_FLAG_CHOKEPOINT)
cost *= chokepointMul;
if (g_dynamic_count != 0) {
const float mx = (pa[0] + pb[0]) * 0.5f, mz = (pa[2] + pb[2]) * 0.5f;
float mul = 1.0f;
for (uint32_t i = 0; i < g_dynamic_count; i++) {
const DynamicCost &d = g_dynamic[i];
const float dx = mx - d.pos[0], dz = mz - d.pos[2];
if (dx * dx + dz * dz < d.radius * d.radius && d.mul > mul)
mul = d.mul;
}
cost *= mul;
}
return cost;
}
bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span,
const float point[3], dtPolyRef *ref, float nearest[3])
{
@@ -229,45 +303,9 @@ double now_micros()
return (double)counter.QuadPart * 1e6 / (double)frequency.QuadPart;
}
WtoNavPathStatus find_path_locked(uint32_t tier, uint32_t filter_index, float snap_radius_m,
const float start[3], const float goal[3],
float *points, int max_points, int *count, float *length_m)
{
if (g_pack == nullptr || tier >= WTO_NAV_TIER_COUNT || filter_index >= WTO_NAV_RT_FILTER_COUNT ||
points == nullptr || max_points < 2 || !(snap_radius_m > 0.0f))
return WTO_NAV_PATH_FAILED;
dtNavMeshQuery *query = g_pack->queries[tier];
const WtoQueryFilter &filter = g_filters[filter_index];
dtPolyRef start_ref = 0, goal_ref = 0;
float start_pt[3], goal_pt[3];
} // namespace wtonav
if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, start, &start_ref, start_pt))
return WTO_NAV_PATH_NO_START;
if (!snap_to_mesh(query, filter, snap_radius_m, g_pack->heightSpan, goal, &goal_ref, goal_pt))
return WTO_NAV_PATH_NO_GOAL;
static dtPolyRef path[kMaxPathPolys];
int path_count = 0;
dtStatus status = query->findPath(start_ref, goal_ref, start_pt, goal_pt, &filter, path, &path_count, kMaxPathPolys);
if (dtStatusFailed(status) || path_count == 0)
return WTO_NAV_PATH_FAILED;
bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || path[path_count - 1] != goal_ref;
if (partial && dtStatusFailed(query->closestPointOnPoly(path[path_count - 1], goal, goal_pt, nullptr)))
return WTO_NAV_PATH_FAILED;
int corners = 0;
status = query->findStraightPath(start_pt, goal_pt, path, path_count, points, nullptr, nullptr, &corners, max_points, 0);
if (dtStatusFailed(status) || corners == 0)
return WTO_NAV_PATH_FAILED;
float length = 0.0f;
for (int i = 1; i < corners; i++)
length += dtVdist(points + (i - 1) * 3, points + i * 3);
*count = corners;
*length_m = length;
return partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL;
}
} // namespace
using namespace wtonav;
extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20])
{
@@ -314,39 +352,54 @@ extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t
return found;
}
extern "C" void wto_nav_load(const wchar_t *pack_path, const uint8_t *level_sha1, WtoNavLoadInfo *info)
extern "C" void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path)
{
std::vector<uint8_t> data;
Pack *pack = nullptr;
memset(info, 0, sizeof(*info));
if (level_sha1 != nullptr) {
info->fingerprintKnown = 1;
memcpy(info->levelSha1, level_sha1, sizeof(info->levelSha1));
if (pack_path == nullptr || pack_path[0] == L'\0')
return;
AcquireSRWLockExclusive(&g_stage_lock);
if (g_staged != nullptr && g_staged->packPath == pack_path) {
ReleaseSRWLockExclusive(&g_stage_lock);
return;
}
if (read_file(pack_path, data, info)) {
pack = parse_pack(data, info);
info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT;
Staged *previous = g_staged;
Staged *staged = new Staged();
staged->packPath = pack_path;
staged->levelPath = level_path != nullptr ? level_path : L"";
staged->thread = CreateThread(nullptr, 0, prefetch_main, staged, 0, nullptr);
if (staged->thread == nullptr) {
delete staged;
staged = nullptr;
}
if (pack != nullptr && level_sha1 != nullptr)
info->fingerprintMatch = memcmp(info->packSha1, level_sha1, sizeof(info->packSha1)) == 0;
g_staged = staged;
ReleaseSRWLockExclusive(&g_stage_lock);
discard_staged(previous);
}
AcquireSRWLockExclusive(&g_lock);
init_filters_locked();
free_pack(g_pack);
g_pack = pack;
memset(&g_stats, 0, sizeof(g_stats));
g_stats.loaded = pack != nullptr;
ReleaseSRWLockExclusive(&g_lock);
extern "C" void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info)
{
const double began = now_micros();
Staged *staged = take_staged(pack_path);
Pack *pack;
if (staged != nullptr) {
WaitForSingleObject(staged->thread, INFINITE);
CloseHandle(staged->thread);
staged->thread = nullptr;
pack = staged->pack;
staged->pack = nullptr;
*info = staged->info;
info->prefetched = 1;
discard_staged(staged);
} else {
pack = read_pack(pack_path, level_path, info);
}
info->waitMs = (now_micros() - began) / 1000.0;
replace_pack(pack);
}
extern "C" void wto_nav_unload(void)
{
AcquireSRWLockExclusive(&g_lock);
free_pack(g_pack);
g_pack = nullptr;
g_stats.loaded = 0;
ReleaseSRWLockExclusive(&g_lock);
replace_pack(nullptr);
}
extern "C" int wto_nav_is_loaded(void)
@@ -369,31 +422,11 @@ extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs)
ReleaseSRWLockExclusive(&g_lock);
}
extern "C" WtoNavPathStatus wto_nav_find_path(uint32_t tier, uint32_t filter, float snap_radius_m,
const float start[3], const float goal[3],
float *points, int max_points, int *count, float *length_m)
{
*count = 0;
*length_m = 0.0f;
AcquireSRWLockExclusive(&g_lock);
const double began = now_micros();
const WtoNavPathStatus status = find_path_locked(tier, filter, snap_radius_m, start, goal, points, max_points, count, length_m);
const double spent = now_micros() - began;
if (g_pack != nullptr) {
g_stats.queries++;
g_stats.totalMicros += spent;
if (spent > g_stats.maxMicros)
g_stats.maxMicros = spent;
if (status != WTO_NAV_PATH_FULL)
g_stats.failures++;
}
ReleaseSRWLockExclusive(&g_lock);
return status;
}
extern "C" void wto_nav_get_stats(WtoNavStats *stats)
{
AcquireSRWLockShared(&g_lock);
AcquireSRWLockExclusive(&g_lock);
g_stats.pending = paths_pending_locked();
g_stats.dynamic = g_dynamic_count;
*stats = g_stats;
ReleaseSRWLockShared(&g_lock);
ReleaseSRWLockExclusive(&g_lock);
}