chore(ground-ai): checkpoint 3d replay and simulator work

This commit is contained in:
N0VAN0M4LY committed 2026-12-06 15:43:04 +08:00
1 parent f8bd79042b
commit b276e686b0
47 files changed
+2613 -688

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
<#
Build the ground AI simulator's runtime: the open-source daScript interpreter (daslang.exe) at a
pinned commit, with this project's native module `wto_sim` (native\wto-ai-sim\module).
powershell -NoProfile -ExecutionPolicy Bypass -File native\wto-ai-sim\build.ps1
The daScript checkout goes to build\daslang (cloned when missing, about 420 MB), the build to
build\daslang-build. Neither is part of the repository. The module folder is linked into the
checkout as modules\wtoSim, so the daScript build compiles it with its own module rules and
daslang loads it at start. Needs Visual Studio with the x64 C++ tools; CMake and Ninja are the
ones Visual Studio bundles.
#>
param(
[string]$DasRoot = (Join-Path $PSScriptRoot '..\..\build\daslang'),
[string]$BuildDir = (Join-Path $PSScriptRoot '..\..\build\daslang-build')
)
$ErrorActionPreference = 'Stop'
# daScript 0.6.6, the version the simulator was verified with (docs: tank-ai-revision-plan 3.3.1).
$pin = '7a51c4ef9927dbc92ecf4cab67ae41b41d239f4a'
$repo = 'https://github.com/GaijinEntertainment/daScript.git'
if (-not (Test-Path (Join-Path $DasRoot '.git'))) {
git clone --no-checkout $repo $DasRoot
if ($LASTEXITCODE -ne 0) { throw 'git clone of daScript failed' }
}
$head = (git -C $DasRoot rev-parse HEAD 2>$null)
if ($head -ne $pin) {
git -C $DasRoot fetch origin $pin
git -C $DasRoot checkout --detach $pin
if ($LASTEXITCODE -ne 0) { throw "checkout of daScript $pin failed" }
}
$moduleLink = Join-Path $DasRoot 'modules\wtoSim'
if (-not (Test-Path $moduleLink)) {
New-Item -ItemType Junction -Path $moduleLink -Target (Join-Path $PSScriptRoot 'module') | Out-Null
}
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if (-not $vs) { throw 'Visual Studio with the x64 C++ tools was not found' }
$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat'
$cmakeDir = Join-Path $vs 'Common7\IDE\CommonExtensions\Microsoft\CMake'
$cmake = Join-Path $cmakeDir 'CMake\bin\cmake.exe'
$ninja = Join-Path $cmakeDir 'Ninja\ninja.exe'
# Only the interpreter and the core runtime; every optional module of daScript stays off.
$off = @('ACCELERATE', 'AOT_EXAMPLES', 'AUDIO', 'CLANG_BIND', 'CLIPBOARD', 'CRYPTO', 'CUDA', 'FLEX_BISON', 'GLFW', 'HV',
'IMGUI', 'LLVM', 'MESHOPTIMIZER', 'METAL', 'PUGIXML', 'SMT', 'SQLITE', 'STBIMAGE', 'STDDLG', 'TERMINAL', 'TESTS',
'TREE_SITTER', 'TUTORIAL', 'VULKAN') | ForEach-Object { "-DDAS_$($_)_DISABLED=ON" }
$native = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path -replace '\\', '/'
$configure = "`"$cmake`" -S `"$DasRoot`" -B `"$BuildDir`" -G Ninja -DCMAKE_MAKE_PROGRAM=`"$ninja`" " +
"-DCMAKE_BUILD_TYPE=Release -DDAS_TOOLS_DISABLED=OFF -DWTO_SIM_NATIVE_ROOT=`"$native`" $($off -join ' ')"
cmd /c "`"$vcvars`" >nul && $configure"
if ($LASTEXITCODE -ne 0) { throw "cmake configure failed with $LASTEXITCODE" }
cmd /c "`"$vcvars`" >nul && `"$cmake`" --build `"$BuildDir`" --target daslang dasModuleWtoSim"
if ($LASTEXITCODE -ne 0) { throw "cmake build failed with $LASTEXITCODE" }
Write-Output (Join-Path $DasRoot 'bin\daslang.exe')
+9
View File
@@ -0,0 +1,9 @@
options gen2
require daslib/fio
[export]
def initialize(project_path : string) {
if (das_is_dll_build()) {
register_dynamic_module("{project_path}/dasModuleWtoSim.shared_module", "Module_WtoSim")
}
}
+6
View File
@@ -0,0 +1,6 @@
# The daScript build writes the shared module next to its sources.
*.shared_module
*.pdb
*.lib
*.exp
*.ilk
+49
View File
@@ -0,0 +1,49 @@
# Ground AI simulator module `wto_sim` for the open-source daScript build. native/wto-ai-sim/build.ps1
# links this folder into the daScript checkout as modules/wtoSim, so its build includes it like its
# own modules and daslang loads the shared module at start (.das_module).
IF ((NOT DAS_WTOSIM_INCLUDED) AND ((NOT ${DAS_WTOSIM_DISABLED}) OR (NOT DEFINED DAS_WTOSIM_DISABLED)))
SET(DAS_WTOSIM_INCLUDED TRUE)
MESSAGE(STATUS "wtoSim module included.")
# The project's native folder: given by build.ps1, else found through the link.
IF(DEFINED WTO_SIM_NATIVE_ROOT)
SET(WTO_SIM_NATIVE ${WTO_SIM_NATIVE_ROOT})
ELSE()
FILE(REAL_PATH "${CMAKE_CURRENT_LIST_DIR}" _wto_sim_here)
GET_FILENAME_COMPONENT(WTO_SIM_NATIVE "${_wto_sim_here}/../.." ABSOLUTE)
ENDIF()
SET(WTO_SIM_DIR ${CMAKE_CURRENT_LIST_DIR})
SET(WTO_SIM_NAV_DIR ${WTO_SIM_NATIVE}/wto-nav)
SET(WTO_SIM_DETOUR_DIR ${WTO_SIM_NATIVE}/third_party/recastnavigation/Detour)
# The game's navigation engine and request protocol with upstream Detour, at their own warning level.
FILE(GLOB WTO_SIM_DETOUR_SRC ${WTO_SIM_DETOUR_DIR}/Source/*.cpp)
ADD_LIBRARY(wtoSimNav STATIC
${WTO_SIM_DETOUR_SRC}
${WTO_SIM_NAV_DIR}/wto_nav_runtime.cpp
${WTO_SIM_NAV_DIR}/wto_nav_paths.cpp
${WTO_SIM_NAV_DIR}/wto_nav_queries.cpp
${WTO_SIM_NAV_DIR}/wto_nav_protocol.c
)
TARGET_INCLUDE_DIRECTORIES(wtoSimNav PUBLIC
$<BUILD_INTERFACE:${WTO_SIM_NAV_DIR}> $<BUILD_INTERFACE:${WTO_SIM_DETOUR_DIR}/Include>)
# Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp).
TARGET_COMPILE_DEFINITIONS(wtoSimNav PUBLIC DT_VIRTUAL_QUERYFILTER PRIVATE _CRT_SECURE_NO_WARNINGS WIN32_LEAN_AND_MEAN)
SET_TARGET_PROPERTIES(wtoSimNav PROPERTIES POSITION_INDEPENDENT_CODE ON)
# The module's static library is in daScript's export set, so what it links must be too.
INSTALL(TARGETS wtoSimNav EXPORT DASTargets ARCHIVE DESTINATION ${DAS_INSTALL_LIBDIR})
SET(WTO_SIM_MODULE_SRC
${WTO_SIM_DIR}/src/wto_sim_module.cpp
${WTO_SIM_DIR}/src/sim_geo.cpp
${WTO_SIM_DIR}/src/sim_geo.h
${WTO_SIM_DIR}/src/sim_nav.cpp
${WTO_SIM_DIR}/src/sim_nav.h
)
ADD_MODULE_CPP(WtoSim)
ADD_MODULE_LIB(libDasModuleWtoSim dasModuleWtoSim ${WTO_SIM_MODULE_SRC})
TARGET_LINK_LIBRARIES(libDasModuleWtoSim PUBLIC wtoSimNav)
TARGET_LINK_LIBRARIES(dasModuleWtoSim PUBLIC wtoSimNav)
SETUP_CPP11(libDasModuleWtoSim)
SETUP_CPP11(dasModuleWtoSim)
ENDIF()
+443
View File
@@ -0,0 +1,443 @@
// Terrain and object geometry of the simulated level (see sim_geo.h). Objects are indexed on an
// 8 m grid in XZ, with each cell's highest triangle and highest ground; a ray walks the cells it
// crosses, tests their triangles and marches the terrain only where it dips low enough.
#include "sim_geo.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <fstream>
#include <vector>
namespace wto_sim {
namespace {
const char GEO_MAGIC[8] = { 'W', 'T', 'O', 'G', 'E', 'O', '\0', '\x01' };
const uint32_t GEO_MAX_VERSION = 3;
const float CELL_M = 8.0f;
const float BURIED_M = 0.3f;
#pragma pack(push, 1)
struct GeoHeader {
char magic[8];
uint32_t version;
uint32_t flags;
uint8_t everSha1[20];
float waterLevel;
float boundsMin[2];
float boundsMax[2];
uint32_t hmWidth;
uint32_t hmHeight;
float hmCellSize;
float hmOrigin[2];
uint32_t obsVertCount;
uint32_t obsTriCount;
};
#pragma pack(pop)
// One triangle ready for the ray test: a corner, two edges, and the group it belongs to.
struct Tri {
float v0[3];
float e1[3];
float e2[3];
int kind;
};
// Obstacle class (WtoObstacleClass) to ray group.
const int KIND_OF_CLASS[8] = { RAY_HARD, RAY_BRIDGE, RAY_CRUSHABLE, RAY_TREE, RAY_TREE, RAY_HARD, RAY_PLATFORM, RAY_PLATFORM };
struct Geo {
bool loaded = false;
float water = -1.0e6f;
uint32_t hmW = 0;
uint32_t hmH = 0;
float hmCell = 1.0f;
float hmOrigin[2] = { 0.0f, 0.0f };
std::vector<float> heights;
std::vector<Tri> tris;
// Grid over the objects: cell (c, r) holds items[offsets[i] .. offsets[i + 1]).
float gridOrigin[2] = { 0.0f, 0.0f };
int gridCols = 0;
int gridRows = 0;
std::vector<uint32_t> offsets;
std::vector<uint32_t> items;
std::vector<float> cellTop;
// Highest terrain sample in each cell (with its border), so a ray above it skips the march.
std::vector<float> cellGround;
// Ray id stamped on each triangle already tested by the current ray.
std::vector<uint32_t> stamp;
uint32_t rayId = 0;
};
Geo g_geo;
float height_at(const Geo & g, float x, float z)
{
if (g.hmW < 2 || g.hmH < 2)
return 0.0f;
const float fx = std::min(float(g.hmW) - 1.001f, std::max(0.0f, (x - g.hmOrigin[0]) / g.hmCell));
const float fz = std::min(float(g.hmH) - 1.001f, std::max(0.0f, (z - g.hmOrigin[1]) / g.hmCell));
const uint32_t x0 = uint32_t(fx);
const uint32_t z0 = uint32_t(fz);
const float tx = fx - float(x0);
const float tz = fz - float(z0);
const float * row0 = &g.heights[size_t(z0) * g.hmW + x0];
const float * row1 = row0 + g.hmW;
const float a = row0[0] + (row0[1] - row0[0]) * tx;
const float b = row1[0] + (row1[1] - row1[0]) * tx;
return a + (b - a) * tz;
}
void sub(const float a[3], const float b[3], float out[3])
{
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
}
void cross(const float a[3], const float b[3], float out[3])
{
out[0] = a[1] * b[2] - a[2] * b[1];
out[1] = a[2] * b[0] - a[0] * b[2];
out[2] = a[0] * b[1] - a[1] * b[0];
}
float dot(const float a[3], const float b[3])
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
bool read_bytes(std::ifstream & in, void * out, size_t size)
{
in.read(static_cast<char *>(out), std::streamsize(size));
return bool(in);
}
bool buried(const Geo & g, const float * v)
{
return v[1] < height_at(g, v[0], v[2]) - BURIED_M;
}
// Keeps the triangles that are not wholly under the terrain, as ready-to-test records.
void keep_triangles(Geo & g, const std::vector<float> & verts, const std::vector<uint8_t> & raw, uint32_t count)
{
g.tris.clear();
g.tris.reserve(count);
const uint32_t vertCount = uint32_t(verts.size() / 3);
for (uint32_t i = 0; i < count; i++) {
const uint8_t * rec = &raw[size_t(i) * 13];
uint32_t idx[3];
std::memcpy(idx, rec, sizeof(idx));
if (idx[0] >= vertCount || idx[1] >= vertCount || idx[2] >= vertCount)
continue;
const float * a = &verts[size_t(idx[0]) * 3];
const float * b = &verts[size_t(idx[1]) * 3];
const float * c = &verts[size_t(idx[2]) * 3];
if (buried(g, a) && buried(g, b) && buried(g, c))
continue;
Tri t;
std::memcpy(t.v0, a, sizeof(t.v0));
sub(b, a, t.e1);
sub(c, a, t.e2);
t.kind = KIND_OF_CLASS[rec[12] & 7];
g.tris.push_back(t);
}
}
void tri_bounds(const Tri & t, float lo[3], float hi[3])
{
for (int k = 0; k < 3; k++) {
const float b = t.v0[k] + t.e1[k];
const float c = t.v0[k] + t.e2[k];
lo[k] = std::min(t.v0[k], std::min(b, c));
hi[k] = std::max(t.v0[k], std::max(b, c));
}
}
void cell_span(const Geo & g, const float lo[3], const float hi[3], int & c0, int & c1, int & r0, int & r1)
{
c0 = std::clamp(int(std::floor((lo[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1);
c1 = std::clamp(int(std::floor((hi[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1);
r0 = std::clamp(int(std::floor((lo[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1);
r1 = std::clamp(int(std::floor((hi[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1);
}
// Two passes over the triangles: count per cell, then fill the cells' item lists.
void build_grid(Geo & g, const float boundsMin[2], const float boundsMax[2])
{
g.gridOrigin[0] = boundsMin[0];
g.gridOrigin[1] = boundsMin[1];
g.gridCols = std::max(1, int(std::ceil((boundsMax[0] - boundsMin[0]) / CELL_M)));
g.gridRows = std::max(1, int(std::ceil((boundsMax[1] - boundsMin[1]) / CELL_M)));
const size_t cells = size_t(g.gridCols) * size_t(g.gridRows);
std::vector<uint32_t> counts(cells, 0);
g.cellTop.assign(cells, -1.0e9f);
float lo[3], hi[3];
int c0, c1, r0, r1;
for (const Tri & t : g.tris) {
tri_bounds(t, lo, hi);
cell_span(g, lo, hi, c0, c1, r0, r1);
for (int r = r0; r <= r1; r++) {
for (int c = c0; c <= c1; c++) {
const size_t i = size_t(r) * g.gridCols + c;
counts[i]++;
g.cellTop[i] = std::max(g.cellTop[i], hi[1]);
}
}
}
g.offsets.assign(cells + 1, 0);
for (size_t i = 0; i < cells; i++)
g.offsets[i + 1] = g.offsets[i] + counts[i];
g.items.assign(g.offsets[cells], 0);
std::fill(counts.begin(), counts.end(), 0);
for (uint32_t ti = 0; ti < uint32_t(g.tris.size()); ti++) {
tri_bounds(g.tris[ti], lo, hi);
cell_span(g, lo, hi, c0, c1, r0, r1);
for (int r = r0; r <= r1; r++) {
for (int c = c0; c <= c1; c++) {
const size_t i = size_t(r) * g.gridCols + c;
g.items[g.offsets[i] + counts[i]++] = ti;
}
}
}
g.stamp.assign(g.tris.size(), 0);
g.rayId = 0;
}
void build_ground_tops(Geo & g)
{
g.cellGround.assign(size_t(g.gridCols) * g.gridRows, -1.0e9f);
for (int r = 0; r < g.gridRows; r++) {
for (int c = 0; c < g.gridCols; c++) {
const float x0 = g.gridOrigin[0] + float(c) * CELL_M;
const float z0 = g.gridOrigin[1] + float(r) * CELL_M;
float top = -1.0e9f;
for (float z = z0 - g.hmCell; z <= z0 + CELL_M + g.hmCell; z += g.hmCell)
for (float x = x0 - g.hmCell; x <= x0 + CELL_M + g.hmCell; x += g.hmCell)
top = std::max(top, height_at(g, x, z));
g.cellGround[size_t(r) * g.gridCols + c] = top;
}
}
}
// Möller–Trumbore, both faces. Returns the distance along the ray, or -1.
float ray_tri(const Tri & t, const float p[3], const float dir[3])
{
float pv[3], tv[3], qv[3];
cross(dir, t.e2, pv);
const float det = dot(t.e1, pv);
if (std::fabs(det) < 1.0e-9f)
return -1.0f;
const float inv = 1.0f / det;
sub(p, t.v0, tv);
const float u = dot(tv, pv) * inv;
if (u < 0.0f || u > 1.0f)
return -1.0f;
cross(tv, t.e1, qv);
const float v = dot(dir, qv) * inv;
if (v < 0.0f || u + v > 1.0f)
return -1.0f;
return dot(t.e2, qv) * inv;
}
void tri_normal(const Tri & t, const float dir[3], float out[3])
{
cross(t.e1, t.e2, out);
const float len = std::sqrt(dot(out, out));
const float s = (len > 0.0f ? 1.0f / len : 0.0f) * (dot(out, dir) > 0.0f ? -1.0f : 1.0f);
out[0] *= s;
out[1] *= s;
out[2] *= s;
}
// Tests the cell's triangles of the selected groups; keeps the nearest hit within maxT.
void test_cell(Geo & g, size_t cell, const float p[3], const float dir[3], float maxT, int mask, RayHit & best)
{
for (uint32_t k = g.offsets[cell]; k < g.offsets[cell + 1]; k++) {
const uint32_t ti = g.items[k];
if (g.stamp[ti] == g.rayId)
continue;
g.stamp[ti] = g.rayId;
const Tri & t = g.tris[ti];
if ((t.kind & mask) == 0)
continue;
const float d = ray_tri(t, p, dir);
if (d >= 0.0f && d <= maxT && (best.dist < 0.0f || d < best.dist)) {
best.dist = d;
best.kind = t.kind;
tri_normal(t, dir, best.normal);
}
}
}
void terrain_normal(const Geo & g, float x, float z, float out[3])
{
const float e = g.hmCell;
const float dx = height_at(g, x + e, z) - height_at(g, x - e, z);
const float dz = height_at(g, x, z + e) - height_at(g, x, z - e);
out[0] = -dx;
out[1] = 2.0f * e;
out[2] = -dz;
const float len = std::sqrt(dot(out, out));
out[0] /= len;
out[1] /= len;
out[2] /= len;
}
// Height of the ray above the terrain at distance t.
float above_ground(const Geo & g, const float p[3], const float dir[3], float t)
{
return p[1] + dir[1] * t - height_at(g, p[0] + dir[0] * t, p[2] + dir[2] * t);
}
// Terrain crossing of the ray within [t0, t1], marched at half the heightmap spacing and bisected.
bool terrain_in(const Geo & g, const float p[3], const float dir[3], float t0, float t1, RayHit & best)
{
const float step = g.hmCell * 0.5f;
float prevT = t0;
if (above_ground(g, p, dir, t0) <= 0.0f) {
best.dist = t0;
} else {
bool crossed = false;
for (float t = std::min(t0 + step, t1); prevT < t1; t = std::min(t + step, t1)) {
if (above_ground(g, p, dir, t) <= 0.0f) {
float lo = prevT;
float hi = t;
for (int i = 0; i < 8; i++) {
const float mid = 0.5f * (lo + hi);
if (above_ground(g, p, dir, mid) > 0.0f)
lo = mid;
else
hi = mid;
}
best.dist = hi;
crossed = true;
break;
}
prevT = t;
}
if (!crossed)
return false;
}
best.kind = 0;
terrain_normal(g, p[0] + dir[0] * best.dist, p[2] + dir[2] * best.dist, best.normal);
return true;
}
// Walks the grid cells under the ray (2D DDA in XZ). In each cell the terrain is marched only when
// the ray dips below the cell's highest ground, the objects tested only when it dips below the
// cell's highest triangle. Stops at the first cell that holds a hit.
void ray_walk(Geo & g, const float p[3], const float dir[3], float len, int mask, RayHit & best)
{
if (++g.rayId == 0) {
std::fill(g.stamp.begin(), g.stamp.end(), 0);
g.rayId = 1;
}
const bool terrain = (mask & RAY_TERRAIN) != 0;
const int objects = mask & ~RAY_TERRAIN;
const float gx = (p[0] - g.gridOrigin[0]) / CELL_M;
const float gz = (p[2] - g.gridOrigin[1]) / CELL_M;
int c = int(std::floor(gx));
int r = int(std::floor(gz));
const int stepC = dir[0] > 0.0f ? 1 : -1;
const int stepR = dir[2] > 0.0f ? 1 : -1;
const float big = 1.0e30f;
const float dtC = std::fabs(dir[0]) > 1.0e-7f ? CELL_M / std::fabs(dir[0]) : big;
const float dtR = std::fabs(dir[2]) > 1.0e-7f ? CELL_M / std::fabs(dir[2]) : big;
float nextC = std::fabs(dir[0]) > 1.0e-7f ? ((stepC > 0 ? float(c + 1) - gx : gx - float(c)) * dtC) : big;
float nextR = std::fabs(dir[2]) > 1.0e-7f ? ((stepR > 0 ? float(r + 1) - gz : gz - float(r)) * dtR) : big;
float t0 = 0.0f;
while (t0 <= len) {
const float t1 = std::min(len, std::min(nextC, nextR));
const bool inside = c >= 0 && r >= 0 && c < g.gridCols && r < g.gridRows;
const size_t cell = inside ? size_t(r) * g.gridCols + c : 0;
const float lowY = std::min(p[1] + dir[1] * t0, p[1] + dir[1] * t1);
if (objects != 0 && inside && lowY <= g.cellTop[cell])
test_cell(g, cell, p, dir, len, objects, best);
const float groundEnd = best.dist >= 0.0f ? std::min(t1, best.dist) : t1;
if (terrain && (!inside || lowY <= g.cellGround[cell]) && terrain_in(g, p, dir, t0, groundEnd, best))
return;
if (best.dist >= 0.0f && best.dist <= t1)
return;
if (t1 >= len)
return;
if (nextC < nextR) {
c += stepC;
t0 = nextC;
nextC += dtC;
} else {
r += stepR;
t0 = nextR;
nextR += dtR;
}
}
}
}
bool geo_load(const std::string & path, std::string & error)
{
Geo g;
std::ifstream in(path, std::ios::binary);
GeoHeader h;
if (!in || !read_bytes(in, &h, sizeof(h))) {
error = "cannot read " + path;
return false;
}
if (std::memcmp(h.magic, GEO_MAGIC, sizeof(GEO_MAGIC)) != 0 || h.version < 1 || h.version > GEO_MAX_VERSION) {
error = "not a .wtogeo file of a known version";
return false;
}
g.water = h.waterLevel;
g.hmW = h.hmWidth;
g.hmH = h.hmHeight;
g.hmCell = h.hmCellSize > 0.0f ? h.hmCellSize : 1.0f;
g.hmOrigin[0] = h.hmOrigin[0];
g.hmOrigin[1] = h.hmOrigin[1];
g.heights.resize(size_t(h.hmWidth) * h.hmHeight);
std::vector<float> verts(size_t(h.obsVertCount) * 3);
std::vector<uint8_t> raw(size_t(h.obsTriCount) * 13);
if (!read_bytes(in, g.heights.data(), g.heights.size() * sizeof(float)) ||
!read_bytes(in, verts.data(), verts.size() * sizeof(float)) || !read_bytes(in, raw.data(), raw.size())) {
error = "file is truncated";
return false;
}
keep_triangles(g, verts, raw, h.obsTriCount);
build_grid(g, h.boundsMin, h.boundsMax);
build_ground_tops(g);
g.loaded = true;
g_geo = std::move(g);
return true;
}
bool geo_loaded()
{
return g_geo.loaded;
}
float geo_height(float x, float z)
{
return height_at(g_geo, x, z);
}
float geo_water_level()
{
return g_geo.water;
}
RayHit geo_ray(const float p[3], const float dir[3], float len, int mask)
{
RayHit best;
if (!g_geo.loaded || !(len > 0.0f))
return best;
ray_walk(g_geo, p, dir, len, mask, best);
return best;
}
uint32_t geo_triangle_count()
{
return uint32_t(g_geo.tris.size());
}
}
+42
View File
@@ -0,0 +1,42 @@
// The simulator's world geometry: the level's terrain heightmap and the collision triangles of its
// placed objects, read from the navigation extractor's `.wtogeo` (native/wto-nav/wto_nav_format.h),
// which is also what the AI lab's 3D view draws. Rays answer the AI script's line of sight, ground
// and obstacle probes in place of the engine's traces.
#pragma once
#include <cstdint>
#include <string>
namespace wto_sim {
// Ray masks: terrain plus groups of WtoObstacleClass.
enum RayMask : int {
RAY_TERRAIN = 1,
RAY_HARD = 2, // buildings, rocks, walls (hard solid and hard without cover)
RAY_BRIDGE = 4, // bridge decks
RAY_CRUSHABLE = 8, // fences, bushes, light objects a tank drives through
RAY_TREE = 16, // tree trunks
RAY_PLATFORM = 32, // walkable tops of placed objects
RAY_ALL = 63,
};
// What a ray hit: -1 nothing, 0 terrain, otherwise the RayMask bit of the object group.
struct RayHit {
float dist = -1.0f;
int kind = -1;
float normal[3] = { 0.0f, 1.0f, 0.0f };
};
// Loads the geometry; on failure returns false and `error` says why. Replaces what was loaded.
bool geo_load(const std::string & path, std::string & error);
bool geo_loaded();
// Bilinear terrain height (clamped to the heightmap); 0 when nothing is loaded.
float geo_height(float x, float z);
// The level's water level, or -1e6 when it has none.
float geo_water_level();
// First hit of the ray p + dir * t for t in [0, len], against what `mask` selects. `dir` is unit.
RayHit geo_ray(const float p[3], const float dir[3], float len, int mask);
// Triangles kept after dropping buried faces, and grid cells, for the load log.
uint32_t geo_triangle_count();
}
+137
View File
@@ -0,0 +1,137 @@
// "wtoNav" requests in the simulator (see sim_nav.h). The script's DataBlock arrives as text
// lines; queries go through the shared protocol, the pack ops are answered here: the simulated
// battle's pack is set by the host, so there is no prefetch and no fingerprint check.
#include "sim_nav.h"
#include "wto_nav_protocol.h"
#include "wto_nav_runtime.h"
#include <cstdio>
#include <map>
#include <vector>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
namespace wto_sim {
namespace {
struct Block {
std::map<std::string, std::string> values;
std::vector<std::pair<std::string, std::string>> reply;
};
std::string g_pack;
std::string g_level;
const char * block_get(const void * blk, const char * name)
{
const Block * b = static_cast<const Block *>(blk);
const auto it = b->values.find(name);
return it == b->values.end() ? "" : it->second.c_str();
}
void block_set(Block * b, const char * name, const std::string & value)
{
b->values[name] = value;
b->reply.emplace_back(name, value);
}
void block_set_str(void * blk, const char * name, const char * value)
{
block_set(static_cast<Block *>(blk), name, value ? value : "");
}
void block_set_int(void * blk, const char * name, int32_t value)
{
block_set(static_cast<Block *>(blk), name, std::to_string(value));
}
void parse(const std::string & text, Block & b)
{
size_t at = 0;
while (at < text.size()) {
size_t end = text.find('\n', at);
if (end == std::string::npos)
end = text.size();
const size_t eq = text.find('=', at);
if (eq != std::string::npos && eq < end)
b.values[text.substr(at, eq - at)] = text.substr(eq + 1, end - eq - 1);
at = end + 1;
}
}
std::wstring widen(const std::string & s)
{
if (s.empty())
return std::wstring();
const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), nullptr, 0);
std::wstring out(size_t(n), L'\0');
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), out.data(), n);
return out;
}
void load_map(const WtoNavBlock & nb, Block & b)
{
WtoNavLoadInfo info = {};
std::string reason;
if (g_pack.empty()) {
reason = "no pack set for the simulated level";
} else {
wto_nav_protocol_setup(&nb);
wto_nav_load(widen(g_pack).c_str(), nullptr, &info);
if (info.result != WTO_NAV_LOAD_OK)
reason = info.detail;
}
const bool ok = reason.empty();
const bool fallback = std::string(block_get(&b, "allowFallback")) != "0";
block_set(&b, "state", ok ? "loaded" : fallback ? "fallback" : "failed");
block_set(&b, "fingerprint", "unknown");
block_set(&b, "level", g_level);
block_set(&b, "reason", reason);
block_set_int(&b, "tiers", ok ? int32_t(info.tiers) : 0);
block_set_int(&b, "covers", ok ? int32_t(info.covers) : 0);
}
}
void nav_set_pack(const std::string & packPath, const std::string & level)
{
g_pack = packPath;
g_level = level;
}
std::string nav_request(const std::string & request)
{
Block b;
parse(request, b);
WtoNavBlock nb;
nb.blk = &b;
nb.get_str = block_get;
nb.set_str = block_set_str;
nb.set_int = block_set_int;
const std::string op = block_get(&b, "op");
if (!wto_nav_protocol_query(&nb, op.c_str())) {
if (op == "load_map") {
load_map(nb, b);
} else if (op == "prefetch") {
block_set(&b, "state", "skipped");
block_set(&b, "level", g_level);
block_set(&b, "reason", "the simulator loads on load_map");
} else if (op == "unload_map") {
wto_nav_unload();
block_set_int(&b, "ok", 1);
} else {
std::fprintf(stderr, "WTO_NAV|BAD_REQUEST|op=%s\n", op.c_str());
}
}
std::string out;
for (const auto & kv : b.reply)
out += kv.first + "=" + kv.second + "\n";
return out;
}
}
+15
View File
@@ -0,0 +1,15 @@
// The simulator's side of the AI script's "wtoNav" requests: the same navigation engine and
// request protocol as the game (native/wto-nav), fed from the simulated level's pack.
#pragma once
#include <string>
namespace wto_sim {
// The pack load_map will read; the level name is reported back to the script.
void nav_set_pack(const std::string & packPath, const std::string & level);
// Answers one request. Both are "key=value" lines; the reply holds only the values written back.
std::string nav_request(const std::string & request);
}
@@ -0,0 +1,93 @@
// daScript module `wto_sim`: what the ground AI simulator's scripts need from native code, the
// level geometry (rays, ground height, water) and the navigation engine behind "wtoNav" requests.
// The engine stand-ins of the simulator (Dacoll, RendInst, Mission...) are scripts built on it.
#include "daScript/misc/platform.h"
#include "daScript/ast/ast.h"
#include "daScript/ast/ast_interop.h"
#include "daScript/ast/ast_handle.h"
#include "sim_geo.h"
#include "sim_nav.h"
#include <cstdio>
namespace das {
// Loads the level geometry; prints why when it fails.
static bool wto_sim_geo_load(const char * path)
{
std::string error;
if (wto_sim::geo_load(path ? path : "", error)) {
std::printf("WTO_SIM|GEO_LOADED|path=%s|tris=%u\n", path, wto_sim::geo_triangle_count());
return true;
}
std::printf("WTO_SIM|GEO_FAILED|path=%s|reason=%s\n", path ? path : "", error.c_str());
return false;
}
static float wto_sim_geo_height(float x, float z)
{
return wto_sim::geo_height(x, z);
}
static float wto_sim_geo_water()
{
return wto_sim::geo_water_level();
}
// Distance to the first hit of the ray, or -1; `kind` is 0 for terrain, else the object group.
static float wto_sim_geo_ray(float3 p, float3 dir, float len, int32_t mask, int32_t & kind, float3 & normal)
{
const float pa[3] = { p.x, p.y, p.z };
const float da[3] = { dir.x, dir.y, dir.z };
const wto_sim::RayHit hit = wto_sim::geo_ray(pa, da, len, mask);
kind = hit.kind;
normal = float3(hit.normal[0], hit.normal[1], hit.normal[2]);
return hit.dist;
}
static void wto_sim_nav_set_pack(const char * packPath, const char * level)
{
wto_sim::nav_set_pack(packPath ? packPath : "", level ? level : "");
}
static char * wto_sim_nav_request(const char * request, Context * context, LineInfoArg * at)
{
const std::string reply = wto_sim::nav_request(request ? request : "");
return context->allocateString(reply, at);
}
class Module_WtoSim : public Module {
public:
Module_WtoSim() : Module("wto_sim") {
ModuleLibrary lib;
lib.addModule(this);
lib.addBuiltInModule();
addConstant(*this, "WTO_SIM_RAY_TERRAIN", int32_t(wto_sim::RAY_TERRAIN));
addConstant(*this, "WTO_SIM_RAY_HARD", int32_t(wto_sim::RAY_HARD));
addConstant(*this, "WTO_SIM_RAY_BRIDGE", int32_t(wto_sim::RAY_BRIDGE));
addConstant(*this, "WTO_SIM_RAY_CRUSHABLE", int32_t(wto_sim::RAY_CRUSHABLE));
addConstant(*this, "WTO_SIM_RAY_TREE", int32_t(wto_sim::RAY_TREE));
addConstant(*this, "WTO_SIM_RAY_PLATFORM", int32_t(wto_sim::RAY_PLATFORM));
addConstant(*this, "WTO_SIM_RAY_ALL", int32_t(wto_sim::RAY_ALL));
addExtern<DAS_BIND_FUN(wto_sim_geo_load)>(*this, lib, "wto_sim_geo_load",
SideEffects::modifyExternal, "wto_sim_geo_load")->args({"path"});
addExtern<DAS_BIND_FUN(wto_sim_geo_height)>(*this, lib, "wto_sim_geo_height",
SideEffects::accessExternal, "wto_sim_geo_height")->args({"x", "z"});
addExtern<DAS_BIND_FUN(wto_sim_geo_water)>(*this, lib, "wto_sim_geo_water",
SideEffects::accessExternal, "wto_sim_geo_water");
addExtern<DAS_BIND_FUN(wto_sim_geo_ray)>(*this, lib, "wto_sim_geo_ray",
SideEffects::modifyArgumentAndExternal, "wto_sim_geo_ray")
->args({"p", "dir", "len", "mask", "kind", "normal"});
addExtern<DAS_BIND_FUN(wto_sim_nav_set_pack)>(*this, lib, "wto_sim_nav_set_pack",
SideEffects::modifyExternal, "wto_sim_nav_set_pack")->args({"pack", "level"});
addExtern<DAS_BIND_FUN(wto_sim_nav_request)>(*this, lib, "wto_sim_nav_request",
SideEffects::modifyExternal, "wto_sim_nav_request")->args({"request", "context", "at"});
}
};
REGISTER_DYN_MODULE(Module_WtoSim, Module_WtoSim);
}
REGISTER_MODULE_IN_NAMESPACE(Module_WtoSim, das);
+247
View File
@@ -0,0 +1,247 @@
/* The "wtoNav" request protocol on top of the navigation engine (see wto_nav_protocol.h). */
#include "wto_nav_protocol.h"
#include "wto_nav_runtime.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */
static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = {
"", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "",
};
static float get_real(const WtoNavBlock *b, const char *name, float def)
{
const char *text = b->get_str(b->blk, name);
char *end;
float value;
if (text == NULL || text[0] == '\0')
return def;
value = strtof(text, &end);
return (*end == '\0' && value == value) ? value : def;
}
static long get_long(const WtoNavBlock *b, const char *name, long def)
{
const char *text = b->get_str(b->blk, name);
char *end;
long value;
if (text == NULL || text[0] == '\0')
return def;
value = strtol(text, &end, 10);
return *end == '\0' ? value : def;
}
/* <prefix>x, <prefix>y, <prefix>z */
static void get_vec(const WtoNavBlock *b, char prefix, float out[3])
{
char key[3];
key[0] = prefix;
key[1] = 'x';
key[2] = '\0';
out[0] = get_real(b, key, 0.0f);
key[1] = 'y';
out[1] = get_real(b, key, 0.0f);
key[1] = 'z';
out[2] = get_real(b, key, 0.0f);
}
static void set_int(const WtoNavBlock *b, const char *name, int32_t value)
{
b->set_int(b->blk, name, value);
}
static int32_t to_cm(float metres)
{
const float cm = metres * 100.0f;
if (cm > 2.0e9f)
return INT32_MAX;
if (cm < -2.0e9f)
return INT32_MIN;
return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f);
}
static void set_vec_cm(const WtoNavBlock *b, const char *x, const char *y, const char *z, const float v[3])
{
set_int(b, x, to_cm(v[0]));
set_int(b, y, to_cm(v[1]));
set_int(b, z, to_cm(v[2]));
}
static void read_costs(const WtoNavBlock *b, const char *prefix, WtoNavCosts *costs)
{
char key[48];
int area;
for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) {
costs->area[area] = 1.0f;
if (AREA_KEYS[area][0] == '\0')
continue;
snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]);
costs->area[area] = get_real(b, key, 1.0f);
if (!(costs->area[area] > 0.0f))
costs->area[area] = 1.0f;
}
snprintf(key, sizeof(key), "%s_chokepoint", prefix);
costs->chokepointMul = get_real(b, key, 1.0f);
if (!(costs->chokepointMul > 0.0f))
costs->chokepointMul = 1.0f;
}
void wto_nav_protocol_setup(const WtoNavBlock *b)
{
WtoNavCosts costs;
WtoNavTuning tuning;
read_costs(b, "t", &costs);
wto_nav_set_costs(0, &costs);
read_costs(b, "w", &costs);
wto_nav_set_costs(1, &costs);
tuning.trafficCostPerPath = get_real(b, "trafficPerPath", 0.0f);
tuning.trafficCostMaxMul = get_real(b, "trafficMaxMul", 1.0f);
tuning.trafficHoldSec = get_real(b, "trafficHoldSec", 0.0f);
tuning.cornerOffsetM = get_real(b, "cornerOffset", 0.0f);
wto_nav_set_tuning(&tuning);
}
static void path_request(const WtoNavBlock *b)
{
WtoNavPathRequest req;
const long slot = get_long(b, "slot", -1), tier = get_long(b, "tier", -1), filter = get_long(b, "filter", 0);
const long group = get_long(b, "group", 0);
uint32_t ticket = 0;
memset(&req, 0, sizeof(req));
req.tier = (uint32_t)tier;
req.filter = (uint32_t)filter;
req.group = group > 0 ? (uint32_t)group : 0u;
req.snapM = get_real(b, "snap", 0.0f);
req.goalSnapM = get_real(b, "goalSnap", 0.0f);
get_vec(b, 's', req.start);
get_vec(b, 'g', req.goal);
if (slot >= 0 && tier >= 0 && filter >= 0)
ticket = wto_nav_path_request((uint32_t)slot, &req);
set_int(b, "ticket", (int32_t)ticket);
}
static void path_result(const WtoNavBlock *b)
{
static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" };
float points[WTO_NAV_RT_MAX_CORNERS * 3];
const long slot = get_long(b, "slot", -1), ticket = get_long(b, "ticket", 0);
WtoNavPathResult result;
int i;
wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket,
points, WTO_NAV_RT_MAX_CORNERS, &result);
b->set_str(b->blk, "status", STATUS[result.status]);
set_int(b, "count", result.count);
set_int(b, "lenCm", to_cm(result.lengthM));
set_int(b, "truncated", result.truncated);
set_int(b, "goalMoved", result.goalMoved);
for (i = 0; i < result.count; i++) {
char kx[16], ky[16], kz[16];
snprintf(kx, sizeof(kx), "p%dx", i);
snprintf(ky, sizeof(ky), "p%dy", i);
snprintf(kz, sizeof(kz), "p%dz", i);
set_vec_cm(b, kx, ky, kz, points + i * 3);
}
}
static void probe(const WtoNavBlock *b)
{
WtoNavProbe info;
float pos[3];
get_vec(b, 'p', pos);
if (!wto_nav_probe((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), pos,
get_real(b, "snap", 0.0f), get_real(b, "wallR", 0.0f), &info))
info.onMesh = -1;
set_int(b, "onMesh", info.onMesh);
if (info.onMesh != 1)
return;
set_int(b, "offCm", to_cm(info.offsetM));
set_int(b, "wallCm", to_cm(info.wallDistM));
set_int(b, "area", (int32_t)info.area);
set_int(b, "flags", (int32_t)info.flags);
set_vec_cm(b, "nx", "ny", "nz", info.nearest);
}
static void raycast(const WtoNavBlock *b)
{
float start[3], goal[3], hit[3], frac = 0.0f;
int clear;
get_vec(b, 's', start);
get_vec(b, 'g', goal);
clear = wto_nav_raycast((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0),
get_real(b, "snap", 0.0f), start, goal, &frac, hit);
set_int(b, "clear", clear);
set_int(b, "hitPm", (int32_t)(frac * 1000.0f + 0.5f));
set_vec_cm(b, "hx", "hy", "hz", hit);
}
static void nearest(const WtoNavBlock *b)
{
float pos[3], out[3] = { 0.0f, 0.0f, 0.0f };
int found;
get_vec(b, 'p', pos);
found = wto_nav_nearest((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0),
get_real(b, "radius", 0.0f), pos, out);
set_int(b, "found", found);
set_vec_cm(b, "x", "y", "z", out);
}
static void add_dynamic(const WtoNavBlock *b)
{
float pos[3];
get_vec(b, 'p', pos);
set_int(b, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(b, "radius", 0.0f), get_real(b, "mul", 1.0f),
get_real(b, "until", 0.0f)));
}
static void get_stats(const WtoNavBlock *b)
{
WtoNavStats stats;
wto_nav_get_stats(&stats);
set_int(b, "loaded", stats.loaded);
set_int(b, "queries", (int32_t)stats.queries);
set_int(b, "failures", (int32_t)stats.failures);
set_int(b, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0);
set_int(b, "maxUs", (int32_t)stats.maxMicros);
set_int(b, "maxFrames", (int32_t)stats.maxFrames);
set_int(b, "pumpMaxUs", (int32_t)stats.pumpMaxMicros);
set_int(b, "pending", (int32_t)stats.pending);
set_int(b, "dynamic", (int32_t)stats.dynamic);
set_int(b, "meshQueries", (int32_t)stats.meshQueries);
set_int(b, "traffic", (int32_t)stats.trafficPaths);
set_int(b, "cornersMoved", (int32_t)stats.cornersMoved);
}
static void pump(const WtoNavBlock *b)
{
WtoNavStats stats;
wto_nav_pump((double)get_real(b, "budgetUs", 500.0f), get_real(b, "now", 0.0f));
wto_nav_get_stats(&stats);
set_int(b, "pending", (int32_t)stats.pending);
}
int wto_nav_protocol_query(const WtoNavBlock *b, const char *op)
{
if (strcmp(op, "probe") == 0)
probe(b);
else if (strcmp(op, "path_result") == 0)
path_result(b);
else if (strcmp(op, "path_request") == 0)
path_request(b);
else if (strcmp(op, "raycast") == 0)
raycast(b);
else if (strcmp(op, "pump") == 0)
pump(b);
else if (strcmp(op, "nearest") == 0)
nearest(b);
else if (strcmp(op, "dynamic") == 0)
add_dynamic(b);
else if (strcmp(op, "get_stats") == 0)
get_stats(b);
else
return 0;
return 1;
}
+49
View File
@@ -0,0 +1,49 @@
/*
* The "wtoNav" request protocol of the ground AI script, shared by the game (wto-net
* local_mp_nav.c) and the AI simulator (native/wto-ai-sim): the script fills a block of string
* values with `op` and its arguments, the host answers by writing ints and strings back into it.
* Coordinates in replies are centimetres. The host keeps the ops that depend on where the battle's
* pack comes from (prefetch, load_map, unload_map); everything that only needs the loaded pack is
* answered here.
*
* op=pump now (script seconds), budgetUs -> pending
* op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap,
* goalSnap, sx..sz, gx..gz -> ticket
* op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale,
* count, lenCm, truncated, goalMoved, p<i>x/p<i>y/p<i>z
* op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags,
* nx/ny/nz
* op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz
* op=nearest tier, filter, radius, px..pz -> found, x/y/z
* op=dynamic px..pz, radius, mul, until (script seconds) -> count
* op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending,
* dynamic, meshQueries, traffic, cornersMoved
*
* load_map carries the per-class costs t_<area>, w_<area> and the search tuning trafficPerPath,
* trafficMaxMul, trafficHoldSec, cornerOffset; wto_nav_protocol_setup applies them.
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Access to one request block. get_str returns "" for a value the block does not have. */
typedef struct WtoNavBlock {
void *blk;
const char *(*get_str)(const void *blk, const char *name);
void (*set_str)(void *blk, const char *name, const char *value);
void (*set_int)(void *blk, const char *name, int32_t value);
} WtoNavBlock;
/* Hands the costs and search tuning of a load_map request to the engine, before it loads. */
void wto_nav_protocol_setup(const WtoNavBlock *b);
/* Answers `op` when it is one of the queries above; returns 0 for any other op. */
int wto_nav_protocol_query(const WtoNavBlock *b, const char *op);
#ifdef __cplusplus
}
#endif
+1 -1
View File
@@ -32,7 +32,7 @@ $sources = Quote @(
"$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c",
"$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c",
"$src\local_mp_damage_notifications.c", "$src\local_mp_hit_feedback.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", "$src\local_mp_captures.c", "$src\local_mp_air_ai_sync.c",
"$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp",
"$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", "$nav\wto_nav_protocol.c",
"$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c"
)
$detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName
+24 -230
View File
@@ -1,30 +1,17 @@
/*
* "wtoNav" requests of the ground AI script (call_mission_action, local_mp_ground_ai.c) and the
* battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request, this
* module answers synchronously by writing into the same block:
* battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request and this
* module answers synchronously into the same block. The queries are the shared protocol of
* native/wto-nav/wto_nav_protocol.h; this module adds the ops that depend on the battle:
*
* op=prefetch -> state=started|skipped, level, reason (battle still loading)
* op=load_map allowFallback="0|1", tracked/wheeled costs t_<area>, w_<area>,
* trafficPerPath, trafficMaxMul, trafficHoldSec, cornerOffset
* op=load_map allowFallback="0|1", plus the costs and tuning of the protocol
* -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level,
* reason, tiers, covers
* op=unload_map -> ok
* op=pump now (script seconds), budgetUs -> pending
* op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap,
* goalSnap, sx..sz, gx..gz -> ticket
* op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale,
* count, lenCm, truncated, goalMoved, p<i>x/p<i>y/p<i>z
* op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags,
* nx/ny/nz
* op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz
* op=nearest tier, filter, radius, px..pz -> found, x/y/z
* op=dynamic px..pz, radius, mul, until (script seconds) -> count
* op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending,
* dynamic, meshQueries, traffic, cornersMoved
*
* Coordinates in replies are centimetres (ints). Request values are strings: the script only uses
* the DataBlock string add it already relies on. Replies are ints and strings written with the
* setters local_mp_awards resolves.
* Request values are strings: the script only uses the DataBlock string add it already relies on.
* Replies are ints and strings written with the setters local_mp_awards resolves.
*
* The level comes from the mission settings (customBots wtoLevel, written by the local server),
* the pack folder from wto_ws.cfg (nav.dir). The script asks for a prefetch while the battle
@@ -36,6 +23,7 @@
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include "local_mp_values.h"
#include "wto_nav_protocol.h"
#include "wto_nav_runtime.h"
#include <stdio.h>
@@ -64,11 +52,6 @@ typedef struct NavBattle {
uint32_t covers;
} NavBattle;
/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */
static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = {
"", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "",
};
static NavBattle g_battle;
static SRWLOCK g_battle_lock = SRWLOCK_INIT;
static LONG g_missing_values_logged;
@@ -96,17 +79,6 @@ static void set_int(void *blk, const char *name, int32_t value)
((BlkSetIntFn)g_lmp.blk_set_int)(blk, name, &value);
}
static float get_real(const void *blk, const char *name, float def)
{
const char *text = g_lmp_datablock_get_str(blk, name, "");
char *end;
float value;
if (text == NULL || text[0] == '\0')
return def;
value = strtof(text, &end);
return (*end == '\0' && value == value) ? value : def;
}
static long get_long(const void *blk, const char *name, long def)
{
const char *text = g_lmp_datablock_get_str(blk, name, "");
@@ -118,32 +90,20 @@ static long get_long(const void *blk, const char *name, long def)
return *end == '\0' ? value : def;
}
/* <prefix>x, <prefix>y, <prefix>z */
static void get_vec(const void *blk, char prefix, float out[3])
static const char *block_get_str(const void *blk, const char *name)
{
char key[3] = { prefix, 'x', '\0' };
out[0] = get_real(blk, key, 0.0f);
key[1] = 'y';
out[1] = get_real(blk, key, 0.0f);
key[1] = 'z';
out[2] = get_real(blk, key, 0.0f);
const char *text = g_lmp_datablock_get_str(blk, name, "");
return text ? text : "";
}
static int32_t to_cm(float metres)
static WtoNavBlock game_block(void *blk)
{
const float cm = metres * 100.0f;
if (cm > 2.0e9f)
return INT32_MAX;
if (cm < -2.0e9f)
return INT32_MIN;
return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f);
}
static void set_vec_cm(void *blk, const char *x, const char *y, const char *z, const float v[3])
{
set_int(blk, x, to_cm(v[0]));
set_int(blk, y, to_cm(v[1]));
set_int(blk, z, to_cm(v[2]));
WtoNavBlock b;
b.blk = blk;
b.get_str = block_get_str;
b.set_str = set_str;
b.set_int = set_int;
return b;
}
static void hex20(const uint8_t *sha1, char out[41])
@@ -227,35 +187,6 @@ static int battle_paths(char level[NAV_LEVEL_MAX], wchar_t pack[MAX_PATH], wchar
return 1;
}
static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs)
{
char key[48];
int area;
for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) {
costs->area[area] = 1.0f;
if (AREA_KEYS[area][0] == '\0')
continue;
snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]);
costs->area[area] = get_real(blk, key, 1.0f);
if (!(costs->area[area] > 0.0f))
costs->area[area] = 1.0f;
}
snprintf(key, sizeof(key), "%s_chokepoint", prefix);
costs->chokepointMul = get_real(blk, key, 1.0f);
if (!(costs->chokepointMul > 0.0f))
costs->chokepointMul = 1.0f;
}
static void read_tuning(const void *blk)
{
WtoNavTuning tuning;
tuning.trafficCostPerPath = get_real(blk, "trafficPerPath", 0.0f);
tuning.trafficCostMaxMul = get_real(blk, "trafficMaxMul", 1.0f);
tuning.trafficHoldSec = get_real(blk, "trafficHoldSec", 0.0f);
tuning.cornerOffsetM = get_real(blk, "cornerOffset", 0.0f);
wto_nav_set_tuning(&tuning);
}
static void log_loaded(const WtoNavLoadInfo *info)
{
char expected[41], actual[41];
@@ -272,16 +203,12 @@ static void decide_locked(const void *blk, int allow_fallback)
{
wchar_t pack[MAX_PATH], level_path[MAX_PATH];
WtoNavLoadInfo info;
WtoNavCosts costs;
WtoNavBlock request = game_block((void *)blk);
memset(&info, 0, sizeof(info));
info.result = WTO_NAV_LOAD_MISSING;
if (battle_paths(g_battle.level, pack, level_path, g_battle.reason, sizeof(g_battle.reason))) {
read_costs(blk, "t", &costs);
wto_nav_set_costs(0, &costs);
read_costs(blk, "w", &costs);
wto_nav_set_costs(1, &costs);
read_tuning(blk);
wto_nav_protocol_setup(&request);
wto_nav_load(pack, level_path[0] ? level_path : NULL, &info);
if (info.result != WTO_NAV_LOAD_OK)
snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail);
@@ -358,129 +285,9 @@ static void unload_locked(const char *why)
memset(&g_battle, 0, sizeof(g_battle));
}
static void path_request(void *blk)
{
WtoNavPathRequest req;
const long slot = get_long(blk, "slot", -1), tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0);
const long group = get_long(blk, "group", 0);
uint32_t ticket = 0;
memset(&req, 0, sizeof(req));
req.tier = (uint32_t)tier;
req.filter = (uint32_t)filter;
req.group = group > 0 ? (uint32_t)group : 0u;
req.snapM = get_real(blk, "snap", 0.0f);
req.goalSnapM = get_real(blk, "goalSnap", 0.0f);
get_vec(blk, 's', req.start);
get_vec(blk, 'g', req.goal);
if (slot >= 0 && tier >= 0 && filter >= 0)
ticket = wto_nav_path_request((uint32_t)slot, &req);
set_int(blk, "ticket", (int32_t)ticket);
}
static void path_result(void *blk)
{
static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" };
float points[WTO_NAV_RT_MAX_CORNERS * 3];
const long slot = get_long(blk, "slot", -1), ticket = get_long(blk, "ticket", 0);
WtoNavPathResult result;
char key[16];
int i;
wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket,
points, WTO_NAV_RT_MAX_CORNERS, &result);
set_str(blk, "status", STATUS[result.status]);
set_int(blk, "count", result.count);
set_int(blk, "lenCm", to_cm(result.lengthM));
set_int(blk, "truncated", result.truncated);
set_int(blk, "goalMoved", result.goalMoved);
for (i = 0; i < result.count; i++) {
char ky[16], kz[16];
snprintf(key, sizeof(key), "p%dx", i);
snprintf(ky, sizeof(ky), "p%dy", i);
snprintf(kz, sizeof(kz), "p%dz", i);
set_vec_cm(blk, key, ky, kz, points + i * 3);
}
}
static void probe(void *blk)
{
WtoNavProbe info;
float pos[3];
get_vec(blk, 'p', pos);
if (!wto_nav_probe((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), pos,
get_real(blk, "snap", 0.0f), get_real(blk, "wallR", 0.0f), &info))
info.onMesh = -1;
set_int(blk, "onMesh", info.onMesh);
if (info.onMesh != 1)
return;
set_int(blk, "offCm", to_cm(info.offsetM));
set_int(blk, "wallCm", to_cm(info.wallDistM));
set_int(blk, "area", (int32_t)info.area);
set_int(blk, "flags", (int32_t)info.flags);
set_vec_cm(blk, "nx", "ny", "nz", info.nearest);
}
static void raycast(void *blk)
{
float start[3], goal[3], hit[3], frac = 0.0f;
int clear;
get_vec(blk, 's', start);
get_vec(blk, 'g', goal);
clear = wto_nav_raycast((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0),
get_real(blk, "snap", 0.0f), start, goal, &frac, hit);
set_int(blk, "clear", clear);
set_int(blk, "hitPm", (int32_t)(frac * 1000.0f + 0.5f));
set_vec_cm(blk, "hx", "hy", "hz", hit);
}
static void nearest(void *blk)
{
float pos[3], out[3] = { 0.0f, 0.0f, 0.0f };
int found;
get_vec(blk, 'p', pos);
found = wto_nav_nearest((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0),
get_real(blk, "radius", 0.0f), pos, out);
set_int(blk, "found", found);
set_vec_cm(blk, "x", "y", "z", out);
}
static void add_dynamic(void *blk)
{
float pos[3];
get_vec(blk, 'p', pos);
set_int(blk, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(blk, "radius", 0.0f), get_real(blk, "mul", 1.0f),
get_real(blk, "until", 0.0f)));
}
static void get_stats(void *blk)
{
WtoNavStats stats;
wto_nav_get_stats(&stats);
set_int(blk, "loaded", stats.loaded);
set_int(blk, "queries", (int32_t)stats.queries);
set_int(blk, "failures", (int32_t)stats.failures);
set_int(blk, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0);
set_int(blk, "maxUs", (int32_t)stats.maxMicros);
set_int(blk, "maxFrames", (int32_t)stats.maxFrames);
set_int(blk, "pumpMaxUs", (int32_t)stats.pumpMaxMicros);
set_int(blk, "pending", (int32_t)stats.pending);
set_int(blk, "dynamic", (int32_t)stats.dynamic);
set_int(blk, "meshQueries", (int32_t)stats.meshQueries);
set_int(blk, "traffic", (int32_t)stats.trafficPaths);
set_int(blk, "cornersMoved", (int32_t)stats.cornersMoved);
}
static void pump(void *blk)
{
WtoNavStats stats;
wto_nav_pump((double)get_real(blk, "budgetUs", 500.0f), get_real(blk, "now", 0.0f));
wto_nav_get_stats(&stats);
set_int(blk, "pending", (int32_t)stats.pending);
}
void local_mp_nav_request(void *blk)
{
WtoNavBlock request;
const char *op;
if (blk == NULL || !values_ready())
@@ -488,21 +295,10 @@ void local_mp_nav_request(void *blk)
op = g_lmp_datablock_get_str(blk, "op", "");
if (op == NULL)
return;
if (strcmp(op, "probe") == 0) {
probe(blk);
} else if (strcmp(op, "path_result") == 0) {
path_result(blk);
} else if (strcmp(op, "path_request") == 0) {
path_request(blk);
} else if (strcmp(op, "raycast") == 0) {
raycast(blk);
} else if (strcmp(op, "pump") == 0) {
pump(blk);
} else if (strcmp(op, "nearest") == 0) {
nearest(blk);
} else if (strcmp(op, "dynamic") == 0) {
add_dynamic(blk);
} else if (strcmp(op, "prefetch") == 0) {
request = game_block(blk);
if (wto_nav_protocol_query(&request, op))
return;
if (strcmp(op, "prefetch") == 0) {
prefetch(blk);
} else if (strcmp(op, "load_map") == 0) {
load_map(blk);
@@ -511,8 +307,6 @@ void local_mp_nav_request(void *blk)
unload_locked("battle ended");
ReleaseSRWLockExclusive(&g_battle_lock);
set_int(blk, "ok", 1);
} else if (strcmp(op, "get_stats") == 0) {
get_stats(blk);
} else {
log_line("WTO_NAV|BAD_REQUEST|op=%s", op);
}