feat(ground-ai): add a replay trace and the AI lab viewer
Battle behaviour could only be judged by watching one bot at a time. The AI now logs a replay trace and a local viewer plays it back on the map. Game scripts: - wto_ai_trace_common.das writes every diagnostics.traceIntervalSec the capture zones (WTO_AI|TRACE_CAP), every ground unit including players (TRACE_U) and each bot's decision state (TRACE_B: order, behavior, targets, what the turret looks at and why, barrel heading, fire denial, hit probability), plus part damage with its offender (HIT) and deaths (DEATH). It uses no engine module so a simulator can load it as is. - The turret state records the reason and world direction of each look. - New tuning diagnostics.trace and diagnostics.traceIntervalSec through server reader, patcher constants, launcher schema, fields and labels. packages/ground-sim: readers for the baked .wtonav pack (mesh polygons, cover points, tactical grid) and .pois.json, the trace parser and the names of the logged codes. apps/ai-lab: Vite viewer with a local API that lists nav packs and lab logs and decrypts a chosen .clog with wtotools. It draws the nav mesh, vehicles, barrels and wished turret directions, goals, target links, shots, hits and deaths over a timeline, with per-bot strips for behavior, fire denial and turret reason. Paths live in an untracked lab.local.json. The lab has its own tsconfig and stays out of the root typecheck. Root and launcher typechecks pass; the lab typechecks and replayed two lab battles.
This commit is contained in:
1 parent
0b841ce2a2
commit
5786fee63b
39 files changed
+1784
-6
No files matched your search
@@ -0,0 +1,2 @@
|
||||
lab.local.json
|
||||
.cache/
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>WTOffline AI Lab</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps",
|
||||
"logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs",
|
||||
"python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@wto/ai-lab",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Ground AI lab: replay viewer for battle traces and simulator runs.",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@wto/ground-sim": "*",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"vite": "^7.3.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Dev-server API of the AI lab (local only):
|
||||
* GET /api/maps levels that have a navigation pack in mapsDir
|
||||
* GET /api/maps/file?name= a pack or POI file of mapsDir
|
||||
* GET /api/logs game logs (.clog) in logsDir, newest first
|
||||
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
|
||||
* Paths come from lab.local.json next to this app (see lab.local.example.json).
|
||||
*/
|
||||
import { execFile } from 'node:child_process';
|
||||
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import type { ServerResponse } from 'node:http';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import type { Connect, Plugin } from 'vite';
|
||||
|
||||
interface LabConfig {
|
||||
readonly mapsDir: string;
|
||||
readonly logsDir: string;
|
||||
readonly python: string;
|
||||
}
|
||||
|
||||
const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const CACHE_DIR = path.join(APP_DIR, '.cache');
|
||||
const SAFE_NAME = /^[\w.-]+$/;
|
||||
|
||||
function loadConfig(): LabConfig {
|
||||
const file = path.join(APP_DIR, 'lab.local.json');
|
||||
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
|
||||
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
|
||||
return {
|
||||
mapsDir: str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')),
|
||||
logsDir: str('logsDir', ''),
|
||||
python: str('python', 'python'),
|
||||
};
|
||||
}
|
||||
|
||||
function sendJson(res: ServerResponse, status: number, body: unknown): void {
|
||||
res.statusCode = status;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
function sendFile(res: ServerResponse, file: string, type: string): void {
|
||||
res.statusCode = 200;
|
||||
res.setHeader('Content-Type', type);
|
||||
createReadStream(file).pipe(res);
|
||||
}
|
||||
|
||||
function listMaps(cfg: LabConfig): { level: string; pois: boolean }[] {
|
||||
if (!existsSync(cfg.mapsDir)) return [];
|
||||
return readdirSync(cfg.mapsDir)
|
||||
.filter((f) => f.endsWith('.wtonav'))
|
||||
.map((f) => {
|
||||
const level = f.slice(0, -'.wtonav'.length);
|
||||
return { level, pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)) };
|
||||
});
|
||||
}
|
||||
|
||||
function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] {
|
||||
if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return [];
|
||||
return readdirSync(cfg.logsDir)
|
||||
.filter((f) => f.endsWith('.clog'))
|
||||
.map((name) => {
|
||||
const st = statSync(path.join(cfg.logsDir, name));
|
||||
return { name, size: st.size, mtime: st.mtimeMs };
|
||||
})
|
||||
.sort((a, b) => b.mtime - a.mtime);
|
||||
}
|
||||
|
||||
/** Decrypts `name` into the cache unless the cached text is newer than the log. */
|
||||
function decryptLog(cfg: LabConfig, name: string): Promise<string> {
|
||||
const source = path.join(cfg.logsDir, name);
|
||||
const out = path.join(CACHE_DIR, `${name}.txt`);
|
||||
mkdirSync(CACHE_DIR, { recursive: true });
|
||||
if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out);
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => {
|
||||
if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`));
|
||||
else resolve(out);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise<boolean> {
|
||||
const name = url.searchParams.get('name') ?? '';
|
||||
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
|
||||
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
|
||||
if (url.pathname !== '/api/maps/file' && url.pathname !== '/api/logs/text') return false;
|
||||
if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; }
|
||||
if (url.pathname === '/api/maps/file') {
|
||||
const file = path.join(cfg.mapsDir, name);
|
||||
if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` });
|
||||
else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream');
|
||||
return true;
|
||||
}
|
||||
if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) {
|
||||
sendJson(res, 404, { error: `no log ${name}` });
|
||||
return true;
|
||||
}
|
||||
sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8');
|
||||
return true;
|
||||
}
|
||||
|
||||
export function labApi(): Plugin {
|
||||
return {
|
||||
name: 'wto-ai-lab-api',
|
||||
configureServer(server) {
|
||||
const middleware: Connect.NextHandleFunction = (req, res, next) => {
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
if (!url.pathname.startsWith('/api/')) { next(); return; }
|
||||
handle(loadConfig(), url, res)
|
||||
.then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); })
|
||||
.catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }));
|
||||
};
|
||||
server.middlewares.use(middleware);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/** AI lab replay viewer: pick a game log, a battle in it, and play it back on the map. */
|
||||
import type { TraceBattle } from '@wto/ground-sim';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts';
|
||||
import type { Layers } from './draw.ts';
|
||||
import { sceneAt } from './frames.ts';
|
||||
import { Inspector } from './Inspector.tsx';
|
||||
import { buildMapLayer } from './mapLayer.ts';
|
||||
import { MapView } from './MapView.tsx';
|
||||
import { Timeline } from './Timeline.tsx';
|
||||
|
||||
const LAYER_LABELS: Readonly<Record<keyof Layers, string>> = {
|
||||
goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击',
|
||||
};
|
||||
|
||||
function logLabel(l: LogEntry): string {
|
||||
const when = new Date(l.mtime).toLocaleString();
|
||||
return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`;
|
||||
}
|
||||
|
||||
export function App(): React.JSX.Element {
|
||||
const [maps, setMaps] = useState<MapEntry[]>([]);
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [logName, setLogName] = useState('');
|
||||
const [battles, setBattles] = useState<TraceBattle[]>([]);
|
||||
const [battleIdx, setBattleIdx] = useState(0);
|
||||
const [mapData, setMapData] = useState<MapData | undefined>(undefined);
|
||||
const [exposure, setExposure] = useState(false);
|
||||
const [covers, setCovers] = useState(false);
|
||||
const [layers, setLayers] = useState<Layers>({ goals: true, links: true, cones: false, labels: false, events: true });
|
||||
const [t, setT] = useState(0);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [speed, setSpeed] = useState(4);
|
||||
const [selected, setSelected] = useState<string | undefined>(undefined);
|
||||
const [status, setStatus] = useState('');
|
||||
|
||||
const refreshLogs = (): void => { fetchLogs().then(setLogs).catch((e: unknown) => setStatus(String(e))); };
|
||||
useEffect(() => {
|
||||
fetchMaps().then(setMaps).catch((e: unknown) => setStatus(String(e)));
|
||||
refreshLogs();
|
||||
}, []);
|
||||
|
||||
const openLog = (name: string): void => {
|
||||
setLogName(name);
|
||||
setPlaying(false);
|
||||
setStatus('正在解密和读取日志…');
|
||||
loadLog(name).then((list) => {
|
||||
setBattles(list);
|
||||
// The longest battle that has bots in its trace; a battle left right after loading has none.
|
||||
let pick = list.length - 1;
|
||||
let best = 0;
|
||||
list.forEach((b, i) => {
|
||||
const withBots = b.frames.filter((f) => f.bots.size > 0).length;
|
||||
if (withBots > best) { best = withBots; pick = i; }
|
||||
});
|
||||
setBattleIdx(Math.max(0, pick));
|
||||
setStatus(list.length === 0 ? '这份日志里没有对局。' : '');
|
||||
}).catch((e: unknown) => setStatus(String(e)));
|
||||
};
|
||||
|
||||
const battle = battles[battleIdx];
|
||||
const level = battle?.level;
|
||||
useEffect(() => {
|
||||
setT(battle?.startT ?? 0);
|
||||
setSelected(undefined);
|
||||
}, [battle]);
|
||||
useEffect(() => {
|
||||
const entry = maps.find((m) => m.level === level);
|
||||
setMapData(undefined);
|
||||
if (entry === undefined) return;
|
||||
loadMap(entry).then(setMapData).catch((e: unknown) => setStatus(String(e)));
|
||||
}, [level, maps]);
|
||||
|
||||
const mapLayer = useMemo(
|
||||
() => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })),
|
||||
[mapData, exposure, covers],
|
||||
);
|
||||
const bounds = useMemo((): readonly [number, number, number, number] | undefined => {
|
||||
if (mapData === undefined) return undefined;
|
||||
const p = mapData.pois;
|
||||
if (p !== undefined) return [p.boundsMin[0], p.boundsMin[1], p.boundsMax[0], p.boundsMax[1]];
|
||||
return [mapData.pack.header.bmin[0], mapData.pack.header.bmin[2], mapData.pack.header.bmax[0], mapData.pack.header.bmax[2]];
|
||||
}, [mapData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!playing || battle === undefined) return;
|
||||
let last = performance.now();
|
||||
let handle = requestAnimationFrame(function step(now) {
|
||||
const dt = (now - last) / 1000;
|
||||
last = now;
|
||||
setT((cur) => {
|
||||
const next = cur + dt * speed;
|
||||
if (next >= battle.endT) { setPlaying(false); return battle.endT; }
|
||||
return next;
|
||||
});
|
||||
handle = requestAnimationFrame(step);
|
||||
});
|
||||
return () => cancelAnimationFrame(handle);
|
||||
}, [playing, speed, battle]);
|
||||
|
||||
const scene = useMemo(() => (battle === undefined ? undefined : sceneAt(battle, t)), [battle, t]);
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<header>
|
||||
<select value={logName} onChange={(e) => openLog(e.target.value)}>
|
||||
<option value="">选择游戏日志…</option>
|
||||
{logs.map((l) => <option key={l.name} value={l.name}>{logLabel(l)}</option>)}
|
||||
</select>
|
||||
<button type="button" onClick={refreshLogs}>刷新</button>
|
||||
{battles.length > 1 && (
|
||||
<select value={battleIdx} onChange={(e) => setBattleIdx(Number(e.target.value))}>
|
||||
{battles.map((b, i) => (
|
||||
<option key={i} value={i}>{`第 ${i + 1} 局 ${b.level ?? '未知地图'}(${b.frames.length} 帧)`}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{(Object.keys(LAYER_LABELS) as (keyof Layers)[]).map((k) => (
|
||||
<label key={k}>
|
||||
<input type="checkbox" checked={layers[k]} onChange={(e) => setLayers({ ...layers, [k]: e.target.checked })} />
|
||||
{LAYER_LABELS[k]}
|
||||
</label>
|
||||
))}
|
||||
<label><input type="checkbox" checked={exposure} onChange={(e) => setExposure(e.target.checked)} />暴露度</label>
|
||||
<label><input type="checkbox" checked={covers} onChange={(e) => setCovers(e.target.checked)} />掩体点</label>
|
||||
{status !== '' && <span className="status">{status}</span>}
|
||||
{battle !== undefined && battle.frames.length === 0 && <span className="status">这一局没有轨迹(游戏里没开 diagnostics.trace)。</span>}
|
||||
</header>
|
||||
<main>
|
||||
<MapView map={mapLayer} bounds={bounds} battle={battle} scene={scene} selected={selected} layers={layers} onSelect={setSelected} />
|
||||
{battle !== undefined && <Inspector battle={battle} scene={scene} selected={selected} />}
|
||||
</main>
|
||||
{battle !== undefined && (
|
||||
<Timeline battle={battle} t={t} playing={playing} speed={speed} selected={selected}
|
||||
onSeek={setT} onPlaying={setPlaying} onSpeed={setSpeed} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/** Details of the selected vehicle at the current time, its recent log events, and the legends. */
|
||||
import type { TraceBattle, TraceEvent } from '@wto/ground-sim';
|
||||
import { eventsBetween, type SceneAt } from './frames.ts';
|
||||
import {
|
||||
BEHAVIOR_COLORS, BEHAVIOR_ZH, CLASS_ZH, COMMAND_ZH, DENY_COLORS, DENY_ZH, LANE_ZH, LOOK_COLORS, LOOK_ZH,
|
||||
STATE_ZH, URGENCY_ZH, zh,
|
||||
} from './labels.ts';
|
||||
|
||||
interface Props {
|
||||
readonly battle: TraceBattle;
|
||||
readonly scene: SceneAt | undefined;
|
||||
readonly selected: string | undefined;
|
||||
}
|
||||
|
||||
const RECENT_SEC = 20;
|
||||
|
||||
function angleDiff(a: number, b: number): number {
|
||||
return Math.abs(((((a - b) % 360) + 540) % 360) - 180);
|
||||
}
|
||||
|
||||
function involves(e: TraceEvent, eid: string): boolean {
|
||||
return e.eid === eid || e.fields['tgt'] === eid || e.fields['off'] === eid || e.fields['target'] === eid;
|
||||
}
|
||||
|
||||
function eventText(e: TraceEvent): string {
|
||||
return Object.entries(e.fields)
|
||||
.filter(([k]) => k !== 't' && k !== 'eid')
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
function Legend({ names, colors }: { names: readonly string[]; colors: readonly string[] }): React.JSX.Element {
|
||||
return (
|
||||
<div className="legend">
|
||||
{names.map((n, i) => (
|
||||
<span key={n}><i style={{ background: colors[i] ?? '#444' }} />{n}</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ k, v }: { k: string; v: string }): React.JSX.Element {
|
||||
return <tr><th>{k}</th><td>{v}</td></tr>;
|
||||
}
|
||||
|
||||
export function Inspector({ battle, scene, selected }: Props): React.JSX.Element {
|
||||
const u = selected !== undefined ? scene?.units.get(selected) : undefined;
|
||||
const b = u?.bot;
|
||||
const recent = selected !== undefined && scene !== undefined
|
||||
? eventsBetween(battle, scene.t - RECENT_SEC, scene.t).filter((e) => involves(e, selected)).reverse()
|
||||
: [];
|
||||
return (
|
||||
<aside className="inspector">
|
||||
{u === undefined && <p className="hint">点击地图上的车辆查看详情。白框是玩家,黄色虚线是炮塔想看的方向,白线是实际炮管。</p>}
|
||||
{u !== undefined && (
|
||||
<table>
|
||||
<tbody>
|
||||
<Row k="编号" v={`${u.unit.eid}(${u.unit.army} 队,${u.unit.human ? '玩家' : u.unit.bot ? 'AI' : '原版 AI'})`} />
|
||||
<Row k="存活" v={u.unit.alive ? '是' : '否'} />
|
||||
<Row k="车速" v={`${u.unit.speed.toFixed(1)} m/s`} />
|
||||
{b !== undefined && <>
|
||||
<Row k="车型" v={zh(CLASS_ZH, b.vehicleClass)} />
|
||||
<Row k="任务" v={b.hasOrder ? `${zh(COMMAND_ZH, b.command)},紧迫度${zh(URGENCY_ZH, b.urgency)},点 ${b.capIdx},${zh(LANE_ZH, b.lane)}` : '无'} />
|
||||
<Row k="行为" v={`${zh(BEHAVIOR_ZH, b.behavior)}(分数 ${b.behaviorScore.toFixed(2)})`} />
|
||||
<Row k="状态" v={zh(STATE_ZH, b.state)} />
|
||||
<Row k="车速 期望/实际" v={`${b.wantSpeed.toFixed(1)} / ${b.forwardSpeed.toFixed(1)} m/s${b.reverseTravel ? ',倒车跟路' : ''}`} />
|
||||
<Row k="感知目标" v={b.target === '0' ? '无' : `${b.target}${b.targetInSight ? '(可见)' : '(不可见)'}`} />
|
||||
<Row k="威胁表" v={`${b.threatCount} 项,最高 ${b.topThreat},最高可见 ${b.topVisibleThreat}`} />
|
||||
<Row k="炮塔依据" v={`${zh(LOOK_ZH, b.lookReason)}${b.lookAt !== '0' ? ` → ${b.lookAt}` : ''}`} />
|
||||
<Row k="炮塔偏差" v={b.gunYaw === undefined ? '—' : `离想看的方向 ${angleDiff(b.gunYaw, b.wishYaw).toFixed(0)}°,离车头 ${angleDiff(b.gunYaw, u.yaw).toFixed(0)}°`} />
|
||||
<Row k="主炮" v={b.reloading ? '装填中' : b.gunReady ? '就绪' : '未就绪'} />
|
||||
<Row k="开火判定" v={`${zh(DENY_ZH, b.deny)},命中概率 ${(b.hitProb * 100).toFixed(0)}% / 门槛 ${(b.threshold * 100).toFixed(0)}%`} />
|
||||
<Row k="扳机要求车速" v={b.requestedSpeed >= 99 ? '不限' : `${b.requestedSpeed.toFixed(1)} m/s`} />
|
||||
</>}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{recent.length > 0 && (
|
||||
<div className="events">
|
||||
<h4>最近 {RECENT_SEC} 秒的日志</h4>
|
||||
{recent.map((e, i) => (
|
||||
<div key={`${e.t}-${i}`}><b>{e.t.toFixed(1)}</b> {e.kind} <span>{eventText(e)}</span></div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<h4>行为</h4>
|
||||
<Legend names={BEHAVIOR_ZH} colors={BEHAVIOR_COLORS} />
|
||||
<h4>拒绝开火</h4>
|
||||
<Legend names={DENY_ZH} colors={DENY_COLORS} />
|
||||
<h4>炮塔依据</h4>
|
||||
<Legend names={LOOK_ZH} colors={LOOK_COLORS} />
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/** The battle map: drag to pan, wheel to zoom, click a vehicle to select it. */
|
||||
import type { TraceBattle } from '@wto/ground-sim';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { drawScene, type Layers } from './draw.ts';
|
||||
import type { SceneAt } from './frames.ts';
|
||||
import type { MapLayer } from './mapLayer.ts';
|
||||
import { fitView, toScreen, zoomAt, type View } from './view.ts';
|
||||
|
||||
interface Props {
|
||||
readonly map: MapLayer | undefined;
|
||||
readonly bounds: readonly [number, number, number, number] | undefined;
|
||||
readonly battle: TraceBattle | undefined;
|
||||
readonly scene: SceneAt | undefined;
|
||||
readonly selected: string | undefined;
|
||||
readonly layers: Layers;
|
||||
readonly onSelect: (eid: string | undefined) => void;
|
||||
}
|
||||
|
||||
const PICK_PX = 14;
|
||||
|
||||
export function MapView({ map, bounds, battle, scene, selected, layers, onSelect }: Props): React.JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const [view, setView] = useState<View>({ cx: 0, cz: 0, scale: 1, w: 800, h: 600 });
|
||||
const drag = useRef<{ x: number; y: number; moved: boolean } | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (canvas === null) return;
|
||||
const resize = (): void => {
|
||||
const r = canvas.getBoundingClientRect();
|
||||
canvas.width = Math.max(1, Math.floor(r.width));
|
||||
canvas.height = Math.max(1, Math.floor(r.height));
|
||||
setView((v) => ({ ...v, w: canvas.width, h: canvas.height }));
|
||||
};
|
||||
const obs = new ResizeObserver(resize);
|
||||
obs.observe(canvas);
|
||||
resize();
|
||||
return () => obs.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (bounds === undefined) return;
|
||||
setView((v) => fitView(bounds[0], bounds[1], bounds[2], bounds[3], v.w, v.h));
|
||||
}, [bounds]);
|
||||
|
||||
useEffect(() => {
|
||||
const ctx = canvasRef.current?.getContext('2d');
|
||||
if (ctx === undefined || ctx === null) return;
|
||||
drawScene(ctx, view, map, battle, scene, selected, layers);
|
||||
}, [view, map, battle, scene, selected, layers]);
|
||||
|
||||
const pick = (sx: number, sy: number): string | undefined => {
|
||||
let best: string | undefined;
|
||||
let bestD = PICK_PX * PICK_PX;
|
||||
for (const u of scene?.units.values() ?? []) {
|
||||
const [x, y] = toScreen(view, u.x, u.z);
|
||||
const d = (x - sx) ** 2 + (y - sy) ** 2;
|
||||
if (d < bestD) { bestD = d; best = u.unit.eid; }
|
||||
}
|
||||
return best;
|
||||
};
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="map"
|
||||
onWheel={(e) => setView((v) => zoomAt(v, e.nativeEvent.offsetX, e.nativeEvent.offsetY, e.deltaY < 0 ? 1.2 : 1 / 1.2))}
|
||||
onMouseDown={(e) => { drag.current = { x: e.clientX, y: e.clientY, moved: false }; }}
|
||||
onMouseMove={(e) => {
|
||||
const d = drag.current;
|
||||
if (d === undefined) return;
|
||||
const dx = e.clientX - d.x;
|
||||
const dy = e.clientY - d.y;
|
||||
if (Math.abs(dx) + Math.abs(dy) > 2) d.moved = true;
|
||||
d.x = e.clientX;
|
||||
d.y = e.clientY;
|
||||
setView((v) => ({ ...v, cx: v.cx - dx / v.scale, cz: v.cz + dy / v.scale }));
|
||||
}}
|
||||
onMouseUp={(e) => {
|
||||
const d = drag.current;
|
||||
drag.current = undefined;
|
||||
if (d !== undefined && !d.moved) onSelect(pick(e.nativeEvent.offsetX, e.nativeEvent.offsetY));
|
||||
}}
|
||||
onMouseLeave={() => { drag.current = undefined; }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Playback controls and, for the selected bot, three strips over the whole battle: its behavior,
|
||||
* the reason it did not fire, and why its turret pointed where it did. Click a strip to seek.
|
||||
*/
|
||||
import type { TraceBattle } from '@wto/ground-sim';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { BEHAVIOR_COLORS, DENY_COLORS, LOOK_COLORS } from './labels.ts';
|
||||
|
||||
interface Props {
|
||||
readonly battle: TraceBattle;
|
||||
readonly t: number;
|
||||
readonly playing: boolean;
|
||||
readonly speed: number;
|
||||
readonly selected: string | undefined;
|
||||
readonly onSeek: (t: number) => void;
|
||||
readonly onPlaying: (playing: boolean) => void;
|
||||
readonly onSpeed: (speed: number) => void;
|
||||
}
|
||||
|
||||
const SPEEDS = [0.5, 1, 2, 4, 8, 16];
|
||||
const STRIP_H = 10;
|
||||
|
||||
function drawStrips(canvas: HTMLCanvasElement, battle: TraceBattle, eid: string | undefined, t: number): void {
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx === null) return;
|
||||
const w = canvas.width;
|
||||
const span = Math.max(1, battle.endT - battle.startT);
|
||||
ctx.fillStyle = '#16181a';
|
||||
ctx.fillRect(0, 0, w, canvas.height);
|
||||
if (eid !== undefined) {
|
||||
const frames = battle.frames;
|
||||
for (let i = 0; i < frames.length; i++) {
|
||||
const f = frames[i];
|
||||
const bot = f?.bots.get(eid);
|
||||
if (f === undefined || bot === undefined) continue;
|
||||
const x0 = ((f.t - battle.startT) / span) * w;
|
||||
const x1 = (((frames[i + 1]?.t ?? f.t + 0.5) - battle.startT) / span) * w;
|
||||
const bw = Math.max(1, x1 - x0);
|
||||
ctx.fillStyle = BEHAVIOR_COLORS[bot.behavior] ?? '#444';
|
||||
ctx.fillRect(x0, 0, bw, STRIP_H);
|
||||
ctx.fillStyle = DENY_COLORS[bot.deny] ?? '#444';
|
||||
ctx.fillRect(x0, STRIP_H + 2, bw, STRIP_H);
|
||||
ctx.fillStyle = LOOK_COLORS[bot.lookReason] ?? '#444';
|
||||
ctx.fillRect(x0, 2 * (STRIP_H + 2), bw, STRIP_H);
|
||||
}
|
||||
}
|
||||
const cx = ((t - battle.startT) / span) * w;
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(cx - 1, 0, 2, canvas.height);
|
||||
}
|
||||
|
||||
export function Timeline({ battle, t, playing, speed, selected, onSeek, onPlaying, onSpeed }: Props): React.JSX.Element {
|
||||
const stripRef = useRef<HTMLCanvasElement>(null);
|
||||
useEffect(() => {
|
||||
const c = stripRef.current;
|
||||
if (c === null) return;
|
||||
c.width = Math.max(1, Math.floor(c.getBoundingClientRect().width));
|
||||
drawStrips(c, battle, selected, t);
|
||||
}, [battle, selected, t]);
|
||||
|
||||
return (
|
||||
<div className="timeline">
|
||||
<div className="controls">
|
||||
<button type="button" onClick={() => onPlaying(!playing)}>{playing ? '暂停' : '播放'}</button>
|
||||
<select value={speed} onChange={(e) => onSpeed(Number(e.target.value))}>
|
||||
{SPEEDS.map((s) => <option key={s} value={s}>{s}×</option>)}
|
||||
</select>
|
||||
<span className="time">{t.toFixed(1)} s / {battle.endT.toFixed(0)} s</span>
|
||||
<input
|
||||
type="range" min={battle.startT} max={battle.endT} step={0.1} value={t}
|
||||
onChange={(e) => onSeek(Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="strip-labels"><span>行为</span><span>拒绝开火</span><span>炮塔依据</span></div>
|
||||
<canvas
|
||||
ref={stripRef}
|
||||
className="strips"
|
||||
height={3 * (STRIP_H + 2)}
|
||||
onClick={(e) => {
|
||||
const w = e.currentTarget.width;
|
||||
onSeek(battle.startT + (e.nativeEvent.offsetX / w) * (battle.endT - battle.startT));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */
|
||||
import { parsePois, parseTraceLog, readNavPack, type MapPois, type NavPack, type TraceBattle } from '@wto/ground-sim';
|
||||
|
||||
export interface LogEntry {
|
||||
readonly name: string;
|
||||
readonly size: number;
|
||||
readonly mtime: number;
|
||||
}
|
||||
|
||||
export interface MapEntry {
|
||||
readonly level: string;
|
||||
readonly pois: boolean;
|
||||
}
|
||||
|
||||
export interface MapData {
|
||||
readonly pack: NavPack;
|
||||
readonly pois: MapPois | undefined;
|
||||
}
|
||||
|
||||
async function get(url: string): Promise<Response> {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) {
|
||||
const body = await res.text();
|
||||
throw new Error(`${url}: ${res.status} ${body}`);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function fetchMaps(): Promise<MapEntry[]> {
|
||||
return (await (await get('/api/maps')).json()) as MapEntry[];
|
||||
}
|
||||
|
||||
export async function fetchLogs(): Promise<LogEntry[]> {
|
||||
return (await (await get('/api/logs')).json()) as LogEntry[];
|
||||
}
|
||||
|
||||
export async function loadLog(name: string): Promise<TraceBattle[]> {
|
||||
const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text();
|
||||
return parseTraceLog(text);
|
||||
}
|
||||
|
||||
export async function loadMap(entry: MapEntry): Promise<MapData> {
|
||||
const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer());
|
||||
const pois = entry.pois
|
||||
? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text())
|
||||
: undefined;
|
||||
return { pack: readNavPack(bytes), pois };
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/** Everything drawn over the static map for one moment of the replay. */
|
||||
import { BEHAVIOR_NAMES, type TraceBattle } from '@wto/ground-sim';
|
||||
import { eventsBetween, type SceneAt, type UnitAt } from './frames.ts';
|
||||
import type { MapLayer } from './mapLayer.ts';
|
||||
import { screenDir, toScreen, type View } from './view.ts';
|
||||
|
||||
export interface Layers {
|
||||
readonly goals: boolean;
|
||||
readonly links: boolean;
|
||||
readonly cones: boolean;
|
||||
readonly labels: boolean;
|
||||
readonly events: boolean;
|
||||
}
|
||||
|
||||
export const ARMY_COLORS: Readonly<Record<number, string>> = { 1: '#4aa3ff', 2: '#ff5c5c' };
|
||||
|
||||
const GUN_FOV_HALF_DEG = 30;
|
||||
const CONE_M = 120;
|
||||
const EVENT_WINDOW_SEC = 2;
|
||||
|
||||
function line(ctx: CanvasRenderingContext2D, ax: number, ay: number, bx: number, by: number): void {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(ax, ay);
|
||||
ctx.lineTo(bx, by);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
function drawHull(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, selected: boolean): void {
|
||||
const [sx, sy] = toScreen(v, u.x, u.z);
|
||||
const [dx, dy] = screenDir(u.yaw);
|
||||
const len = Math.max(5, (u.unit.light ? 3 : 3.6) * v.scale);
|
||||
const wid = Math.max(3, 1.7 * v.scale);
|
||||
ctx.save();
|
||||
ctx.translate(sx, sy);
|
||||
ctx.rotate(Math.atan2(dy, dx));
|
||||
ctx.fillStyle = u.unit.alive ? (ARMY_COLORS[u.unit.army] ?? '#ccc') : '#555';
|
||||
ctx.fillRect(-len, -wid, len * 2, wid * 2);
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(len * 0.6, -wid * 0.5, len * 0.4, wid);
|
||||
if (u.unit.human || selected) {
|
||||
ctx.strokeStyle = selected ? '#ffe14a' : '#fff';
|
||||
ctx.lineWidth = selected ? 3 : 1.5;
|
||||
ctx.strokeRect(-len - 2, -wid - 2, len * 2 + 4, wid * 2 + 4);
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawBotIntent(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, scene: SceneAt, layers: Layers): void {
|
||||
const bot = u.bot;
|
||||
if (bot === undefined || !u.unit.alive) return;
|
||||
const [sx, sy] = toScreen(v, u.x, u.z);
|
||||
if (layers.goals && bot.hasOrder) {
|
||||
const [gx, gy] = toScreen(v, bot.goalX, bot.goalZ);
|
||||
ctx.setLineDash([4, 6]);
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.25)';
|
||||
ctx.lineWidth = 1;
|
||||
line(ctx, sx, sy, gx, gy);
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
if (bot.gunYaw !== undefined) {
|
||||
const [dx, dy] = screenDir(bot.gunYaw);
|
||||
if (layers.cones) {
|
||||
const r = CONE_M * v.scale;
|
||||
const a = Math.atan2(dy, dx);
|
||||
const half = (GUN_FOV_HALF_DEG * Math.PI) / 180;
|
||||
ctx.fillStyle = 'rgba(255,255,200,0.07)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(sx, sy);
|
||||
ctx.arc(sx, sy, r, a - half, a + half);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
const gl = Math.max(14, 8 * v.scale);
|
||||
ctx.strokeStyle = '#fff';
|
||||
ctx.lineWidth = 2;
|
||||
line(ctx, sx, sy, sx + dx * gl, sy + dy * gl);
|
||||
}
|
||||
const [wx, wy] = screenDir(bot.wishYaw);
|
||||
const wl = Math.max(22, 14 * v.scale);
|
||||
ctx.setLineDash([2, 3]);
|
||||
ctx.strokeStyle = 'rgba(255,225,74,0.8)';
|
||||
ctx.lineWidth = 1;
|
||||
line(ctx, sx, sy, sx + wx * wl, sy + wy * wl);
|
||||
ctx.setLineDash([]);
|
||||
if (!layers.links) return;
|
||||
const target = scene.units.get(bot.target);
|
||||
if (target !== undefined && bot.target !== '0') {
|
||||
const [tx, ty] = toScreen(v, target.x, target.z);
|
||||
ctx.strokeStyle = bot.targetInSight ? 'rgba(255,70,70,0.85)' : 'rgba(255,70,70,0.3)';
|
||||
ctx.lineWidth = 1.5;
|
||||
line(ctx, sx, sy, tx, ty);
|
||||
}
|
||||
const look = scene.units.get(bot.lookAt);
|
||||
if (look !== undefined && bot.lookAt !== bot.target) {
|
||||
const [lx, ly] = toScreen(v, look.x, look.z);
|
||||
ctx.strokeStyle = 'rgba(255,160,40,0.85)';
|
||||
ctx.lineWidth = 1.5;
|
||||
line(ctx, sx, sy, lx, ly);
|
||||
}
|
||||
}
|
||||
|
||||
function drawLabel(ctx: CanvasRenderingContext2D, v: View, u: UnitAt): void {
|
||||
const [sx, sy] = toScreen(v, u.x, u.z);
|
||||
const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : '';
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.85)';
|
||||
ctx.font = '11px sans-serif';
|
||||
ctx.fillText(`${u.unit.eid.replace(/^0x/, '')} ${name}`, sx + 8, sy - 8);
|
||||
}
|
||||
|
||||
function drawEvents(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, scene: SceneAt): void {
|
||||
for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) {
|
||||
const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC;
|
||||
if (e.kind === 'SHOT' && e.eid !== undefined) {
|
||||
const from = scene.units.get(e.eid);
|
||||
const to = scene.units.get(e.fields['tgt'] ?? '');
|
||||
if (from === undefined || to === undefined) continue;
|
||||
const [ax, ay] = toScreen(v, from.x, from.z);
|
||||
const [bx, by] = toScreen(v, to.x, to.z);
|
||||
ctx.strokeStyle = `rgba(255,255,120,${fade})`;
|
||||
ctx.lineWidth = 2;
|
||||
line(ctx, ax, ay, bx, by);
|
||||
} else if (e.kind === 'HIT') {
|
||||
const [hx, hy] = toScreen(v, Number(e.fields['x']), Number(e.fields['z']));
|
||||
ctx.fillStyle = e.fields['drop'] === '1' ? `rgba(255,60,60,${fade})` : `rgba(200,200,200,${fade})`;
|
||||
ctx.beginPath();
|
||||
ctx.arc(hx, hy, 4, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawDeaths(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, t: number): void {
|
||||
ctx.lineWidth = 2;
|
||||
for (const e of eventsBetween(battle, battle.startT, t)) {
|
||||
if (e.kind !== 'DEATH') continue;
|
||||
const [x, y] = toScreen(v, Number(e.fields['x']), Number(e.fields['z']));
|
||||
ctx.strokeStyle = e.fields['army'] === '1' ? 'rgba(74,163,255,0.6)' : 'rgba(255,92,92,0.6)';
|
||||
line(ctx, x - 5, y - 5, x + 5, y + 5);
|
||||
line(ctx, x - 5, y + 5, x + 5, y - 5);
|
||||
}
|
||||
}
|
||||
|
||||
export function drawScene(ctx: CanvasRenderingContext2D, v: View, map: MapLayer | undefined, battle: TraceBattle | undefined,
|
||||
scene: SceneAt | undefined, selected: string | undefined, layers: Layers): void {
|
||||
ctx.fillStyle = '#0b0c0d';
|
||||
ctx.fillRect(0, 0, v.w, v.h);
|
||||
if (map !== undefined) {
|
||||
const [mx, my] = toScreen(v, map.x0, map.z1);
|
||||
const k = v.scale / map.pxPerM;
|
||||
ctx.imageSmoothingEnabled = k < 1;
|
||||
ctx.drawImage(map.canvas, mx, my, map.canvas.width * k, map.canvas.height * k);
|
||||
}
|
||||
if (battle === undefined || scene === undefined) return;
|
||||
for (const cap of scene.caps) {
|
||||
const [cx, cy] = toScreen(v, cap.x, cap.z);
|
||||
ctx.strokeStyle = ARMY_COLORS[cap.owner] ?? '#ddd';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, Math.max(4, cap.r * v.scale), 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
}
|
||||
drawDeaths(ctx, v, battle, scene.t);
|
||||
const units = [...scene.units.values()];
|
||||
for (const u of units) drawBotIntent(ctx, v, u, scene, layers);
|
||||
if (layers.events) drawEvents(ctx, v, battle, scene);
|
||||
for (const u of units) drawHull(ctx, v, u, u.unit.eid === selected);
|
||||
if (layers.labels) for (const u of units) if (u.unit.alive) drawLabel(ctx, v, u);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/** Looking up the battle state at any time between two trace samples. */
|
||||
import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '@wto/ground-sim';
|
||||
|
||||
export interface UnitAt {
|
||||
readonly unit: UnitSample;
|
||||
/** Interpolated position and heading. */
|
||||
readonly x: number;
|
||||
readonly z: number;
|
||||
readonly yaw: number;
|
||||
/** Decision state of the sample at or before the time; undefined for players. */
|
||||
readonly bot: BotSample | undefined;
|
||||
}
|
||||
|
||||
export interface SceneAt {
|
||||
readonly t: number;
|
||||
readonly units: Map<string, UnitAt>;
|
||||
readonly caps: CapSample[];
|
||||
}
|
||||
|
||||
/** Index of the last frame at or before `t` (-1 before the first). */
|
||||
export function frameIndexAt(battle: TraceBattle, t: number): number {
|
||||
let lo = 0;
|
||||
let hi = battle.frames.length - 1;
|
||||
let found = -1;
|
||||
while (lo <= hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if ((battle.frames[mid]?.t ?? Infinity) <= t) { found = mid; lo = mid + 1; } else hi = mid - 1;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function lerpYaw(a: number, b: number, k: number): number {
|
||||
const d = ((((b - a) % 360) + 540) % 360) - 180;
|
||||
return a + d * k;
|
||||
}
|
||||
|
||||
export function sceneAt(battle: TraceBattle, t: number): SceneAt {
|
||||
const i = Math.max(0, frameIndexAt(battle, t));
|
||||
const a = battle.frames[i];
|
||||
const b = battle.frames[i + 1];
|
||||
const units = new Map<string, UnitAt>();
|
||||
if (a === undefined) return { t, units, caps: [] };
|
||||
const k = b !== undefined && b.t > a.t ? Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t))) : 0;
|
||||
for (const [eid, ua] of a.units) {
|
||||
const ub = b?.units.get(eid);
|
||||
const move = ub !== undefined && ua.alive && ub.alive ? k : 0;
|
||||
units.set(eid, {
|
||||
unit: ua,
|
||||
x: ua.x + ((ub?.x ?? ua.x) - ua.x) * move,
|
||||
z: ua.z + ((ub?.z ?? ua.z) - ua.z) * move,
|
||||
yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move),
|
||||
bot: a.bots.get(eid),
|
||||
});
|
||||
}
|
||||
return { t, units, caps: a.caps };
|
||||
}
|
||||
|
||||
/** Events with time in [from, to], from the sorted event list. */
|
||||
export function eventsBetween(battle: TraceBattle, from: number, to: number): TraceEvent[] {
|
||||
let lo = 0;
|
||||
let hi = battle.events.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if ((battle.events[mid]?.t ?? Infinity) < from) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
const out: TraceEvent[] = [];
|
||||
for (let i = lo; i < battle.events.length; i++) {
|
||||
const e = battle.events[i];
|
||||
if (e === undefined || e.t > to) break;
|
||||
out.push(e);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** Chinese display names for the trace codes (the codes themselves are in @wto/ground-sim). */
|
||||
|
||||
export const BEHAVIOR_ZH = ['推进', '交战推进', '短停', '回掩体', '换位', '守位', '疏散', '撤回', '维修'] as const;
|
||||
|
||||
export const BEHAVIOR_COLORS = ['#6c8ebf', '#e0884a', '#e5d34a', '#8fbf6c', '#b07cc6', '#5fb8b0', '#9a9a9a', '#c65f5f', '#7a5a3a'] as const;
|
||||
|
||||
export const STATE_ZH: Readonly<Record<number, string>> = {
|
||||
0: '行军', 1: '行进交战', 3: '短停', 4: '退入掩体', 5: '掩体装填', 7: '原地守位', 8: '换位',
|
||||
9: '失能', 10: '疏散', 11: '坡脊撤回',
|
||||
};
|
||||
|
||||
export const DENY_ZH = [
|
||||
'放行', '无目标', '炮未就绪', '命中概率不足', '远距窗口不足', '瞄准误差', '等待炮管稳定', '检查预算',
|
||||
'炮口有硬物', '弹道有硬物', '友军', '多炮检查', '射界外', '点射间歇',
|
||||
] as const;
|
||||
|
||||
export const DENY_COLORS = [
|
||||
'#4caf50', '#333', '#666', '#e53935', '#8e24aa', '#fb8c00', '#fdd835', '#90a4ae',
|
||||
'#6d4c41', '#795548', '#03a9f4', '#9e9e9e', '#d81b60', '#26a69a',
|
||||
] as const;
|
||||
|
||||
export const LOOK_ZH = ['—', '交战目标', '威胁', '目标消失处', '记忆位置', '线索', '扫视'] as const;
|
||||
|
||||
export const LOOK_COLORS = ['#333', '#e53935', '#fb8c00', '#fdd835', '#8e24aa', '#03a9f4', '#607d8b'] as const;
|
||||
|
||||
export const COMMAND_ZH = ['主攻', '侧翼', '架枪', '防守', '预备', '防空'] as const;
|
||||
|
||||
export const URGENCY_ZH = ['低', '中', '高'] as const;
|
||||
|
||||
export const LANE_ZH = ['中路', '左翼', '右翼'] as const;
|
||||
|
||||
export const CLASS_ZH = ['中坦', '轻坦', '重坦', '歼击车', '防空'] as const;
|
||||
|
||||
export function zh(names: readonly string[] | Readonly<Record<number, string>>, code: number): string {
|
||||
const name = Array.isArray(names) ? names[code] : (names as Readonly<Record<number, string>>)[code];
|
||||
return name ?? String(code);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App } from './App.tsx';
|
||||
import './style.css';
|
||||
|
||||
const root = document.getElementById('root');
|
||||
if (root !== null) createRoot(root).render(<StrictMode><App /></StrictMode>);
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* The static map drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured
|
||||
* by surface, optionally the tactical grid's exposure and the baked cover points.
|
||||
*/
|
||||
import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim';
|
||||
|
||||
export interface MapLayer {
|
||||
readonly canvas: HTMLCanvasElement;
|
||||
/** World x of the canvas's left edge and world z of its top edge. */
|
||||
readonly x0: number;
|
||||
readonly z1: number;
|
||||
readonly pxPerM: number;
|
||||
}
|
||||
|
||||
export interface MapLayerOptions {
|
||||
readonly tier: number;
|
||||
readonly exposure: boolean;
|
||||
readonly covers: boolean;
|
||||
}
|
||||
|
||||
const AREA_COLORS: Readonly<Record<string, string>> = {
|
||||
road: '#77786a', bridge: '#a0a090', ground: '#3d4a33', rough: '#5a4d34', forest: '#29402a',
|
||||
crushable: '#4f5f35', shallowWater: '#35607a', chokepoint: '#7a6a35', exposed: '#5f5f33',
|
||||
deepWater: '#1d3a66', noGo: '#3a2626',
|
||||
};
|
||||
|
||||
export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer {
|
||||
const [x0, , z0] = pack.header.bmin;
|
||||
const [x1, , z1] = pack.header.bmax;
|
||||
const pxPerM = Math.min(2, 4096 / Math.max(x1 - x0, z1 - z0));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.ceil((x1 - x0) * pxPerM);
|
||||
canvas.height = Math.ceil((z1 - z0) * pxPerM);
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx === null) return { canvas, x0, z1, pxPerM };
|
||||
ctx.fillStyle = '#121416';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
const tier = pack.tiers[opts.tier] ?? pack.tiers[1];
|
||||
if (tier !== undefined) {
|
||||
for (let area = 1; area < NAV_AREA_NAMES.length; area++) {
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < tier.polyCount; i++) {
|
||||
if (tier.areas[i] !== area) continue;
|
||||
const ring = tier.rings[i];
|
||||
if (ring === undefined) continue;
|
||||
for (let k = 0; k < ring.length; k += 2) {
|
||||
const px = ((ring[k] ?? 0) - x0) * pxPerM;
|
||||
const py = (z1 - (ring[k + 1] ?? 0)) * pxPerM;
|
||||
if (k === 0) ctx.moveTo(px, py);
|
||||
else ctx.lineTo(px, py);
|
||||
}
|
||||
ctx.closePath();
|
||||
}
|
||||
ctx.fillStyle = AREA_COLORS[NAV_AREA_NAMES[area] ?? ''] ?? '#444';
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
if (opts.exposure) drawExposure(ctx, pack, x0, z1, pxPerM);
|
||||
if (opts.covers) drawCovers(ctx, pack, x0, z1, pxPerM);
|
||||
return { canvas, x0, z1, pxPerM };
|
||||
}
|
||||
|
||||
function drawExposure(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
|
||||
const g = pack.tactical;
|
||||
const cell = g.cellM * pxPerM;
|
||||
for (let r = 0; r < g.rows; r++) {
|
||||
for (let c = 0; c < g.cols; c++) {
|
||||
const e = g.exposure[r * g.cols + c] ?? 0;
|
||||
if (e < 16) continue;
|
||||
ctx.fillStyle = `rgba(255, 80, 40, ${(e / 255) * 0.45})`;
|
||||
const wx = g.origin[0] + c * g.cellM;
|
||||
const wz = g.origin[1] + r * g.cellM;
|
||||
ctx.fillRect((wx - x0) * pxPerM, (z1 - wz - g.cellM) * pxPerM, cell, cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawCovers(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
|
||||
for (const cv of pack.covers) {
|
||||
const px = (cv.pos[0] - x0) * pxPerM;
|
||||
const py = (z1 - cv.pos[2]) * pxPerM;
|
||||
ctx.strokeStyle = cv.kind === 1 ? 'rgba(120, 220, 255, 0.8)' : 'rgba(255, 230, 120, 0.8)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(px, py);
|
||||
ctx.lineTo(px + cv.coverDir[0] * 6 * pxPerM, py - cv.coverDir[1] * 6 * pxPerM);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #root { margin: 0; height: 100%; background: #0b0c0d; color: #ddd; font: 13px/1.4 system-ui, 'Microsoft YaHei', sans-serif; }
|
||||
.app { display: flex; flex-direction: column; height: 100%; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 6px 10px; background: #16181a; border-bottom: 1px solid #2a2d30; }
|
||||
header select { max-width: 420px; }
|
||||
header label { display: inline-flex; align-items: center; gap: 3px; }
|
||||
.status { color: #ffb74d; }
|
||||
main { flex: 1; display: flex; min-height: 0; }
|
||||
canvas.map { flex: 1; min-width: 0; height: 100%; cursor: grab; display: block; }
|
||||
.inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; }
|
||||
.inspector table { width: 100%; border-collapse: collapse; }
|
||||
.inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; }
|
||||
.inspector td { padding: 2px 0; }
|
||||
.inspector h4 { margin: 12px 0 4px; color: #aaa; font-weight: normal; }
|
||||
.hint { color: #999; }
|
||||
.events { font-size: 12px; }
|
||||
.events div { padding: 1px 0; border-bottom: 1px solid #1d2023; word-break: break-all; }
|
||||
.events span { color: #999; }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; }
|
||||
.legend i { display: inline-block; width: 10px; height: 10px; margin-right: 3px; vertical-align: -1px; }
|
||||
.timeline { padding: 6px 10px; background: #16181a; border-top: 1px solid #2a2d30; }
|
||||
.controls { display: flex; gap: 8px; align-items: center; }
|
||||
.controls input[type='range'] { flex: 1; }
|
||||
.time { min-width: 120px; font-variant-numeric: tabular-nums; }
|
||||
.strip-labels { display: flex; gap: 12px; font-size: 11px; color: #888; margin-top: 4px; }
|
||||
canvas.strips { width: 100%; height: 36px; display: block; cursor: pointer; }
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Top-down view of the battle: world x to the right, world z up (Dagor is Y-up). Headings are
|
||||
* degrees of atan2(z, x), as the trace writes them.
|
||||
*/
|
||||
export interface View {
|
||||
/** World point at the centre of the canvas. */
|
||||
readonly cx: number;
|
||||
readonly cz: number;
|
||||
/** Screen pixels per world metre. */
|
||||
readonly scale: number;
|
||||
readonly w: number;
|
||||
readonly h: number;
|
||||
}
|
||||
|
||||
export function toScreen(v: View, x: number, z: number): [number, number] {
|
||||
return [v.w / 2 + (x - v.cx) * v.scale, v.h / 2 - (z - v.cz) * v.scale];
|
||||
}
|
||||
|
||||
export function toWorld(v: View, sx: number, sy: number): [number, number] {
|
||||
return [v.cx + (sx - v.w / 2) / v.scale, v.cz - (sy - v.h / 2) / v.scale];
|
||||
}
|
||||
|
||||
/** Screen direction (unit vector) of a world heading. */
|
||||
export function screenDir(yawDeg: number): [number, number] {
|
||||
const r = (yawDeg * Math.PI) / 180;
|
||||
return [Math.cos(r), -Math.sin(r)];
|
||||
}
|
||||
|
||||
export function fitView(minX: number, minZ: number, maxX: number, maxZ: number, w: number, h: number): View {
|
||||
const scale = Math.min(w / Math.max(1, maxX - minX), h / Math.max(1, maxZ - minZ)) * 0.95;
|
||||
return { cx: (minX + maxX) / 2, cz: (minZ + maxZ) / 2, scale, w, h };
|
||||
}
|
||||
|
||||
/** Zoom by `factor` keeping the world point under the screen point (sx, sy) in place. */
|
||||
export function zoomAt(v: View, sx: number, sy: number, factor: number): View {
|
||||
const [wx, wz] = toWorld(v, sx, sy);
|
||||
const scale = Math.min(40, Math.max(0.05, v.scale * factor));
|
||||
return { ...v, scale, cx: wx - (sx - v.w / 2) / scale, cz: wz + (sy - v.h / 2) / scale };
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
// The lab is a Vite page plus its dev-server API (server/), so it has its own settings and stays
|
||||
// out of the root typecheck, like the launcher.
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"types": ["node"],
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"useDefineForClassFields": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "server/**/*.ts", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { defineConfig } from 'vite';
|
||||
import { labApi } from './server/lab-api.ts';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), labApi()],
|
||||
server: { host: '127.0.0.1', port: 47180, strictPort: false },
|
||||
});
|
||||
@@ -881,7 +881,9 @@
|
||||
"statsLogIntervalSec": "Battle statistics logging interval",
|
||||
"statsSampleSec": "Statistics sampling interval per bot",
|
||||
"statsSampleRangeM": "Range of the nearest-enemy statistics sample",
|
||||
"statsRearArcDeg": "Rear arc counted as showing the rear"
|
||||
"statsRearArcDeg": "Rear arc counted as showing the rear",
|
||||
"trace": "Log the AI replay trace",
|
||||
"traceIntervalSec": "AI replay trace sampling interval"
|
||||
}
|
||||
},
|
||||
"shared": "These settings apply to all saves in this client.",
|
||||
|
||||
@@ -881,7 +881,9 @@
|
||||
"statsLogIntervalSec": "每局统计的输出间隔",
|
||||
"statsSampleSec": "每辆车的统计抽查间隔",
|
||||
"statsSampleRangeM": "统计抽查最近敌人的范围",
|
||||
"statsRearArcDeg": "算作车尾对敌的后方扇区角度"
|
||||
"statsRearArcDeg": "算作车尾对敌的后方扇区角度",
|
||||
"trace": "输出 AI 回放轨迹",
|
||||
"traceIntervalSec": "回放轨迹的采样间隔"
|
||||
}
|
||||
},
|
||||
"shared": "这些数值适用于此客户端的全部存档。",
|
||||
|
||||
@@ -466,6 +466,8 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
|
||||
num('diagnostics', 'statsSampleSec', 0.2, 5, 's'),
|
||||
num('diagnostics', 'statsSampleRangeM', 50, 1000, 'm'),
|
||||
num('diagnostics', 'statsRearArcDeg', 30, 180, '°'),
|
||||
{ id: 'groundAi.diagnostics.trace', section: 'diagnostics', field: 'trace', kind: 'bool' },
|
||||
num('diagnostics', 'traceIntervalSec', 0.1, 5, 's'),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -329,6 +329,8 @@ const GroundAiDiagnosticsSchema = z.object({
|
||||
statsSampleSec: z.number().min(0.2).max(5),
|
||||
statsSampleRangeM: z.number().min(50).max(1000),
|
||||
statsRearArcDeg: z.number().min(30).max(180),
|
||||
trace: z.boolean(),
|
||||
traceIntervalSec: z.number().min(0.1).max(5),
|
||||
});
|
||||
|
||||
export const GroundAiTuningSchema = z.object({
|
||||
|
||||
@@ -69,6 +69,8 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
|
||||
statsSampleSec: diag.number('statsSampleSec', { min: 0.2, max: 5 }),
|
||||
statsSampleRangeM: diag.number('statsSampleRangeM', { min: 50, max: 1000 }),
|
||||
statsRearArcDeg: diag.number('statsRearArcDeg', { min: 30, max: 180 }),
|
||||
trace: diag.bool('trace'),
|
||||
traceIntervalSec: diag.number('traceIntervalSec', { min: 0.1, max: 5 }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -458,6 +458,11 @@
|
||||
"statsLogIntervalSec": 60.0,
|
||||
"statsSampleSec": 1.0,
|
||||
"statsSampleRangeM": 300.0,
|
||||
"statsRearArcDeg": 120.0
|
||||
"statsRearArcDeg": 120.0,
|
||||
// Replay trace for the AI viewer (WTO_AI|TRACE_*, HIT, DEATH): every traceIntervalSec the
|
||||
// capture zones, every ground unit and every bot's decision state. About 10 MB of log for
|
||||
// 32 bots over 15 minutes at 0.5 s.
|
||||
"trace": true,
|
||||
"traceIntervalSec": 0.5
|
||||
}
|
||||
}
|
||||
@@ -112,12 +112,23 @@ struct public WtoThreatTable
|
||||
topIdx : int = -1
|
||||
topVisibleIdx : int = -1
|
||||
|
||||
// Why the turret points where it does this frame (WtoTurretState.lookReason, replay trace).
|
||||
let public WTO_LOOK_NONE = 0
|
||||
let public WTO_LOOK_ENGAGE = 1
|
||||
let public WTO_LOOK_THREAT = 2
|
||||
let public WTO_LOOK_WATCH = 3
|
||||
let public WTO_LOOK_MEMORY = 4
|
||||
let public WTO_LOOK_CUE = 5
|
||||
let public WTO_LOOK_SCAN = 6
|
||||
|
||||
// Turret channel (decision layer design, section 5): the threat it is looking at and until when
|
||||
// that look is held.
|
||||
// that look is held, plus the world direction it was asked for this frame and why.
|
||||
[safe_when_uninitialized]
|
||||
struct public WtoTurretState
|
||||
lookEid : EntityId = INVALID_ENTITY_ID
|
||||
holdUntil : float = -100.0
|
||||
lookReason : int = 0
|
||||
wishDir : float3 = float3(1.0, 0.0, 0.0)
|
||||
|
||||
[safe_when_uninitialized]
|
||||
struct public WtoWeaponBurst
|
||||
|
||||
@@ -272,8 +272,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN
|
||||
let aimBase = slot.perceive.visibleAimPt
|
||||
distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, aimBase, slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, slot, aimPt, wishWorldDir)
|
||||
auxAimed = wto_fire_aux_aim(unit, className, dt, distXZ, slot)
|
||||
slot.turret.lookReason = WTO_LOOK_ENGAGE
|
||||
else
|
||||
wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot)
|
||||
slot.turret.wishDir = wishWorldDir
|
||||
var wishYaw = 0.0
|
||||
var wishPitch = 0.0
|
||||
wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch)
|
||||
|
||||
@@ -43,6 +43,7 @@ require %appGame.wtoai.wto_ai_diag_common
|
||||
require %appGame.wtoai.wto_ai_stats_common
|
||||
require %appGame.wtoai.wto_ai_slots_common
|
||||
require %appGame.wtoai.wto_ai_threat_common
|
||||
require %appGame.wtoai.wto_ai_trace_common
|
||||
|
||||
var private @safe_when_uninitialized g_world : WtoWorldSnap
|
||||
var private @safe_when_uninitialized g_crowd : WtoCrowdSummary
|
||||
@@ -57,6 +58,8 @@ var private g_fire_budget : int = 0
|
||||
var private g_next_diag_at : float = 0.0
|
||||
var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle
|
||||
var private @safe_when_uninitialized g_stats : WtoBattleStats
|
||||
var private g_next_trace_at : float = 0.0
|
||||
var private g_trace_due : bool = false
|
||||
|
||||
// Custom ground AI must only run inside a real multiplayer battle. Single-player test
|
||||
// drives also dispatch tag=server ECS, but their target vehicles must never be taken over.
|
||||
@@ -81,6 +84,8 @@ def private wto_reset_runtime()
|
||||
g_cmd_dirty = true
|
||||
g_last_zone_ver = -1
|
||||
g_next_diag_at = 0.0
|
||||
g_next_trace_at = 0.0
|
||||
g_trace_due = false
|
||||
wto_navmesh_battle_reset(g_navmesh)
|
||||
wto_slots_reset_all(g_bots)
|
||||
|
||||
@@ -109,6 +114,7 @@ def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef)
|
||||
if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2)
|
||||
let now = float(get_app().usefulTotalTime)
|
||||
wto_world_record_death(g_world, eid, int(u.army), u.pos, now)
|
||||
wto_trace_death(now, eid, int(u.army), u.pos)
|
||||
wto_route_report_wreck(g_navmesh.state, now, u.pos, g_bots)
|
||||
if wto_slots_forget(g_bots, eid)
|
||||
g_cmd_dirty = true
|
||||
@@ -127,6 +133,7 @@ def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : Uni
|
||||
if u == null || !offEid || offEid == eid
|
||||
return
|
||||
let hpDropped = uint(evt.hpFixed) < uint(evt.prevHpFixed)
|
||||
wto_trace_hit(float(get_app().usefulTotalTime), eid, offEid, evt.pos, evt.damage, evt.damageTypeId, hpDropped)
|
||||
wto_slots_on_damage(g_world, g_bots, eid, offEid, u, evt.pos, hpDropped, float(get_app().usefulTotalTime))
|
||||
|
||||
[es(tag=server, before=wto_ai_pipeline_es)]
|
||||
@@ -166,6 +173,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct)
|
||||
g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC
|
||||
wto_diag_log_telemetry(g_world, now, g_bots, g_crowd)
|
||||
wto_navmesh_log_stats(g_navmesh)
|
||||
g_trace_due = wto_trace_tick(g_world, now, g_bots, g_next_trace_at)
|
||||
wto_stats_tick(now, g_stats)
|
||||
|
||||
[es(tag=server, before=wto_ai_pipeline_es)]
|
||||
@@ -218,6 +226,8 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref :
|
||||
slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC
|
||||
wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot)
|
||||
wto_stats_bot_frame(g_world, now, act.dt, unit.pos, unit.unitTm[0], slot, g_stats)
|
||||
if g_trace_due
|
||||
wto_trace_bot(now, slot)
|
||||
|
||||
[es(tag=server, after=wto_ai_pipeline_es)]
|
||||
def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// Replay trace for the ground AI viewer (apps/ai-lab), written every diagnostics.traceIntervalSec:
|
||||
// WTO_AI|TRACE_CAP capture zones (position, radius, owner, progress)
|
||||
// WTO_AI|TRACE_U every ground unit, bots and players alike (position, hull heading, speed)
|
||||
// WTO_AI|TRACE_B every bot's decision state (order, behavior, targets, turret, trigger)
|
||||
// and as they happen: WTO_AI|HIT (part damage with its offender) and WTO_AI|DEATH.
|
||||
// Positions are whole metres, headings whole degrees of atan2(z, x) in world space.
|
||||
// The simulator writes the same lines, so this module uses no engine module.
|
||||
options indenting = 2
|
||||
options no_global_heap = true
|
||||
module wto_ai_trace_common shared
|
||||
|
||||
require ecs
|
||||
require math
|
||||
require %appGame.wtoai.wto_ai_config_common
|
||||
require %appGame.wtoai.wto_ai_math_common
|
||||
require %appGame.wtoai.wto_ai_combat_types_common
|
||||
require %appGame.wtoai.wto_ai_types_common
|
||||
|
||||
def private wto_tr_m(v : float) : int
|
||||
return int(floor(v + 0.5))
|
||||
|
||||
def private wto_tr_yaw(dir : float3) : int
|
||||
return int(floor(atan2(dir.z, dir.x) * WTO_RAD_TO_DEG + 0.5))
|
||||
|
||||
def private wto_tr_b(flag : bool) : int
|
||||
return flag ? 1 : 0
|
||||
|
||||
def private wto_tr_is_bot(bots : WtoBotSlot[64] const&; eid : EntityId) : int
|
||||
for i in range(WTO_MAX_BOTS)
|
||||
if bots[i].used && bots[i].eid == eid
|
||||
return 1
|
||||
return 0
|
||||
|
||||
// True when this frame writes a trace sample; then the capture zones and all ground units are
|
||||
// written at once, and the pipeline adds one TRACE_B line per bot.
|
||||
[never_inline]
|
||||
def public wto_trace_tick(world : WtoWorldSnap const&; now : float; bots : WtoBotSlot[64] const&;
|
||||
var nextAt : float&) : bool
|
||||
if !WTO_AI_TRACE_ENABLED || now < nextAt
|
||||
return false
|
||||
nextAt = now + WTO_AI_TRACE_SEC
|
||||
for c in range(world.capCount)
|
||||
assume z = world.caps[c]
|
||||
print("WTO_AI|TRACE_CAP|t={now}|idx={c}|x={wto_tr_m(z.center.x)}|z={wto_tr_m(z.center.z)}|r={wto_tr_m(z.radius)}|owner={z.ownerArmy}|prog={z.progress}\n")
|
||||
for i in range(world.unitCount)
|
||||
assume u = world.units[i]
|
||||
if !u.isGround
|
||||
continue
|
||||
let bot = wto_tr_is_bot(bots, u.eid)
|
||||
print("WTO_AI|TRACE_U|t={now}|eid={uint(u.eid)}|army={u.army}|bot={bot}|human={wto_tr_b(u.isHuman)}|alive={wto_tr_b(u.isAlive)}|x={wto_tr_m(u.pos.x)}|y={wto_tr_m(u.pos.y)}|z={wto_tr_m(u.pos.z)}|yaw={wto_tr_yaw(u.hullFwd)}|v={length(u.vel)}|shoot={wto_tr_b(u.isShooting)}|light={wto_tr_b(u.isLightTag)}\n")
|
||||
return true
|
||||
|
||||
def private wto_tr_threat_eid(slot : WtoBotSlot const&; idx : int) : uint
|
||||
return idx >= 0 && idx < slot.threat.count ? uint(slot.threat.entries[idx].eid) : 0u
|
||||
|
||||
// The thing the turret aims at: the engaged target or the threat it looks at; 0 otherwise.
|
||||
def private wto_tr_look_eid(slot : WtoBotSlot const&) : uint
|
||||
let why = slot.turret.lookReason
|
||||
if why == WTO_LOOK_ENGAGE
|
||||
return uint(slot.perceive.targetEid)
|
||||
if why == WTO_LOOK_THREAT
|
||||
return uint(slot.turret.lookEid)
|
||||
return 0u
|
||||
|
||||
[never_inline]
|
||||
def public wto_trace_bot(now : float; slot : WtoBotSlot const&)
|
||||
assume o = slot.order
|
||||
assume tac = slot.tactics
|
||||
assume p = slot.perceive
|
||||
assume tr = slot.trigger
|
||||
let gx = o.valid ? wto_tr_m(o.goalPos.x) : 0
|
||||
let gz = o.valid ? wto_tr_m(o.goalPos.z) : 0
|
||||
let gun = slot.fire.hasBarrelSight ? wto_tr_yaw(slot.fire.barrelSight) : 9999
|
||||
let topEid = wto_tr_threat_eid(slot, slot.threat.topIdx)
|
||||
let topVis = wto_tr_threat_eid(slot, slot.threat.topVisibleIdx)
|
||||
print("WTO_AI|TRACE_B|t={now}|eid={uint(slot.eid)}|cls={slot.spec.role}|ord={wto_tr_b(o.valid)}|cmd={o.role}|urg={o.urgency}|cap={o.capIndex}|lane={o.laneId}|gx={gx}|gz={gz}|bhv={tac.behavior}|bs={tac.behaviorScore}|st={tac.state}|wantV={tac.desiredSpeedMps}|vf={slot.drive.lastVFwd}|rev={wto_tr_b(tac.reverseTravel)}|tgt={uint(p.targetEid)}|los={wto_tr_b(p.hasClearLos)}|threats={slot.threat.count}|top={topEid}|topVis={topVis}|look={wto_tr_look_eid(slot)}|why={slot.turret.lookReason}|wish={wto_tr_yaw(slot.turret.wishDir)}|gun={gun}|ready={wto_tr_b(slot.fire.gunReady)}|reload={wto_tr_b(slot.fire.reloading)}|deny={slot.fire.lastDenyReason}|p={tr.hitProb}|thr={tr.threshold}|reqV={tr.wantSpeedMps}\n")
|
||||
|
||||
// Part damage on any unit with its offender, so the viewer can draw who hit whom and the last
|
||||
// offender before a death. `dropped` tells whether the part lost hit points.
|
||||
def public wto_trace_hit(now : float; victim, offender : EntityId; pos : float3; damage : float; damageType : int; dropped : bool)
|
||||
if WTO_AI_TRACE_ENABLED
|
||||
print("WTO_AI|HIT|t={now}|eid={uint(victim)}|off={uint(offender)}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}|dmg={damage}|type={damageType}|drop={wto_tr_b(dropped)}\n")
|
||||
|
||||
def public wto_trace_death(now : float; eid : EntityId; army : int; pos : float3)
|
||||
if WTO_AI_TRACE_ENABLED
|
||||
print("WTO_AI|DEATH|t={now}|eid={uint(eid)}|army={army}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}\n")
|
||||
@@ -60,13 +60,19 @@ def private wto_turret_scan_dir(now : float; myPos, hullFwd : float3; slot : Wto
|
||||
[never_inline]
|
||||
def public wto_turret_look_dir(now : float; muzzlePos, myPos, hullFwd : float3; var slot : WtoBotSlot&) : float3
|
||||
assume p = slot.perceive
|
||||
assume tr = slot.turret
|
||||
let threat = wto_turret_pick_threat(now, slot)
|
||||
if threat >= 0
|
||||
tr.lookReason = WTO_LOOK_THREAT
|
||||
return normalize((slot.threat.entries[threat].pos + float3(0.0, 1.4, 0.0)) - muzzlePos)
|
||||
if now < p.watchUntil
|
||||
tr.lookReason = WTO_LOOK_WATCH
|
||||
return normalize(p.watchPos - muzzlePos)
|
||||
if !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
|
||||
tr.lookReason = WTO_LOOK_MEMORY
|
||||
return normalize((p.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos)
|
||||
if now < p.alertUntil
|
||||
tr.lookReason = WTO_LOOK_CUE
|
||||
return float3(cos(p.alertYawRad), 0.0, sin(p.alertYawRad))
|
||||
tr.lookReason = WTO_LOOK_SCAN
|
||||
return wto_turret_scan_dir(now, myPos, hullFwd, slot)
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "@wto/ground-sim",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Ground AI lab: map data readers and the replay trace shared by the replay viewer (apps/ai-lab)
|
||||
* and the simulator (docs: tank-ai-revision-plan, section 3).
|
||||
*/
|
||||
export {
|
||||
NAV_AREA_NAMES, NAV_FLAG, NAV_TIER_NAMES, NavPackError, readNavPack,
|
||||
type NavCover, type NavHeader, type NavPack, type NavTactical, type NavTier,
|
||||
} from './map/wtonav.ts';
|
||||
export { parsePois, type MapPoint, type MapPois } from './map/pois.ts';
|
||||
export {
|
||||
BEHAVIOR_NAMES, BLOCK_NAMES, COMMAND_NAMES, DENY_NAMES, LANE_NAMES, LOOK_NAMES, STATE_NAMES,
|
||||
URGENCY_NAMES, VEHICLE_CLASS_NAMES, nameOf,
|
||||
} from './trace/names.ts';
|
||||
export { parseTraceLog } from './trace/parse.ts';
|
||||
export type { BotSample, CapSample, TraceBattle, TraceEvent, TraceFrame, UnitSample } from './trace/types.ts';
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Points of interest written next to each navigation pack (`<level>.pois.json`, tools/navgen):
|
||||
* battle bounds, and per mission the team spawns and the capture zones.
|
||||
*/
|
||||
|
||||
export interface MapPoint {
|
||||
readonly name: string;
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly z: number;
|
||||
readonly radius: number;
|
||||
readonly mission: string;
|
||||
}
|
||||
|
||||
export interface MapPois {
|
||||
readonly level: string;
|
||||
readonly missions: string[];
|
||||
readonly boundsMin: readonly [number, number];
|
||||
readonly boundsMax: readonly [number, number];
|
||||
readonly team1Spawns: MapPoint[];
|
||||
readonly team2Spawns: MapPoint[];
|
||||
readonly captureZones: MapPoint[];
|
||||
}
|
||||
|
||||
function points(value: unknown): MapPoint[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.flatMap((p: unknown): MapPoint[] => {
|
||||
if (typeof p !== 'object' || p === null) return [];
|
||||
const r = p as Record<string, unknown>;
|
||||
const n = (k: string): number => (typeof r[k] === 'number' ? (r[k] as number) : 0);
|
||||
return [{ name: String(r['name'] ?? ''), x: n('x'), y: n('y'), z: n('z'), radius: n('radius'), mission: String(r['mission'] ?? '') }];
|
||||
});
|
||||
}
|
||||
|
||||
function pair(value: unknown): readonly [number, number] {
|
||||
return Array.isArray(value) && typeof value[0] === 'number' && typeof value[1] === 'number' ? [value[0], value[1]] : [0, 0];
|
||||
}
|
||||
|
||||
/** Parses the text of a `.pois.json` file. */
|
||||
export function parsePois(text: string): MapPois {
|
||||
const raw = JSON.parse(text) as Record<string, unknown>;
|
||||
return {
|
||||
level: String(raw['level'] ?? ''),
|
||||
missions: Array.isArray(raw['missions']) ? raw['missions'].map(String) : [],
|
||||
boundsMin: pair(raw['boundsMin']),
|
||||
boundsMax: pair(raw['boundsMax']),
|
||||
team1Spawns: points(raw['team1Spawns']),
|
||||
team2Spawns: points(raw['team2Spawns']),
|
||||
captureZones: points(raw['captureZones']),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Reader for the baked `.wtonav` navigation pack (native/wto-nav/wto_nav_format.h): the header,
|
||||
* the walkable polygons of each mesh tier (upstream Detour tile data), the cover points and the
|
||||
* 8 m tactical grid. Only plain views over the bytes, so it runs in Node and in the browser.
|
||||
*/
|
||||
|
||||
export const NAV_TIER_NAMES = ['narrow', 'standard', 'wide'] as const;
|
||||
|
||||
/** Detour polygon area ids written by the baker (WtoPolyArea). */
|
||||
export const NAV_AREA_NAMES = [
|
||||
'unwalkable', 'road', 'bridge', 'ground', 'rough', 'forest', 'crushable',
|
||||
'shallowWater', 'chokepoint', 'exposed', 'deepWater', 'noGo',
|
||||
] as const;
|
||||
|
||||
/** Detour polygon flags (WtoPolyFlag). */
|
||||
export const NAV_FLAG = {
|
||||
walk: 0x01, shallowWater: 0x02, deepWater: 0x04, chokepoint: 0x08,
|
||||
blocked: 0x10, road: 0x20, downhill: 0x40, platform: 0x80,
|
||||
} as const;
|
||||
|
||||
export interface NavHeader {
|
||||
readonly version: number;
|
||||
readonly flags: number;
|
||||
readonly everSha1: string;
|
||||
readonly bmin: readonly [number, number, number];
|
||||
readonly bmax: readonly [number, number, number];
|
||||
readonly waterLevel: number;
|
||||
readonly coverCount: number;
|
||||
readonly tacCols: number;
|
||||
readonly tacRows: number;
|
||||
readonly tacCellM: number;
|
||||
readonly tacOrigin: readonly [number, number];
|
||||
}
|
||||
|
||||
/**
|
||||
* Every ground polygon of one tier. `ring[i]` is the polygon's outline as x, z pairs in world
|
||||
* metres; `y[i]` the mean height of its corners.
|
||||
*/
|
||||
export interface NavTier {
|
||||
readonly polyCount: number;
|
||||
readonly rings: Float32Array[];
|
||||
readonly heights: Float32Array;
|
||||
readonly areas: Uint8Array;
|
||||
readonly flags: Uint16Array;
|
||||
}
|
||||
|
||||
export interface NavCover {
|
||||
readonly pos: readonly [number, number, number];
|
||||
readonly coverDir: readonly [number, number];
|
||||
readonly retreatDir: readonly [number, number];
|
||||
readonly halfAngleDeg: number;
|
||||
readonly heightM: number;
|
||||
readonly widthM: number;
|
||||
/** 1 full cover, 2 hull-down. */
|
||||
readonly kind: number;
|
||||
}
|
||||
|
||||
/** Tactical grid, row-major from tacOrigin: each cell is exposure, clearance, team 1 and 2 priors. */
|
||||
export interface NavTactical {
|
||||
readonly cols: number;
|
||||
readonly rows: number;
|
||||
readonly cellM: number;
|
||||
readonly origin: readonly [number, number];
|
||||
readonly exposure: Uint8Array;
|
||||
readonly clearanceHalfM: Uint8Array;
|
||||
}
|
||||
|
||||
export interface NavPack {
|
||||
readonly header: NavHeader;
|
||||
readonly tiers: NavTier[];
|
||||
readonly covers: NavCover[];
|
||||
readonly tactical: NavTactical;
|
||||
}
|
||||
|
||||
export class NavPackError extends Error {}
|
||||
|
||||
const NAV_MAGIC = 'WTONAV\0\x01';
|
||||
const NAV_VERSION = 1;
|
||||
const TIER_COUNT = 3;
|
||||
const HEADER_BYTES = 124;
|
||||
const COVER_BYTES = 68;
|
||||
const NAV_PARAMS_BYTES = 28;
|
||||
const TILE_HEADER_BYTES = 100;
|
||||
const POLY_BYTES = 32;
|
||||
const VERTS_PER_POLY = 6;
|
||||
const DT_NULL_IDX = 0xffff;
|
||||
const DT_POLYTYPE_GROUND = 0;
|
||||
|
||||
function align4(n: number): number {
|
||||
return (n + 3) & ~3;
|
||||
}
|
||||
|
||||
function readHeader(view: DataView): NavHeader & { tierOffsets: number[]; tierSizes: number[]; coverOffset: number; tacOffset: number } {
|
||||
if (view.byteLength < HEADER_BYTES) throw new NavPackError('file shorter than the pack header');
|
||||
let magic = '';
|
||||
for (let i = 0; i < 8; i++) magic += String.fromCharCode(view.getUint8(i));
|
||||
const version = view.getUint32(8, true);
|
||||
if (magic !== NAV_MAGIC || version !== NAV_VERSION || view.getUint32(64, true) !== TIER_COUNT) {
|
||||
throw new NavPackError(`not a version ${NAV_VERSION} navigation pack`);
|
||||
}
|
||||
let sha = '';
|
||||
for (let i = 0; i < 20; i++) sha += view.getUint8(16 + i).toString(16).padStart(2, '0');
|
||||
const f = (at: number): number => view.getFloat32(at, true);
|
||||
const u = (at: number): number => view.getUint32(at, true);
|
||||
return {
|
||||
version,
|
||||
flags: u(12),
|
||||
everSha1: sha,
|
||||
bmin: [f(36), f(40), f(44)],
|
||||
bmax: [f(48), f(52), f(56)],
|
||||
waterLevel: f(60),
|
||||
tierOffsets: [u(68), u(72), u(76)],
|
||||
tierSizes: [u(80), u(84), u(88)],
|
||||
coverOffset: u(92),
|
||||
coverCount: u(96),
|
||||
tacOffset: u(100),
|
||||
tacCols: u(104),
|
||||
tacRows: u(108),
|
||||
tacCellM: f(112),
|
||||
tacOrigin: [f(116), f(120)],
|
||||
};
|
||||
}
|
||||
|
||||
interface TierBuilder {
|
||||
rings: Float32Array[];
|
||||
heights: number[];
|
||||
areas: number[];
|
||||
flags: number[];
|
||||
}
|
||||
|
||||
function readTile(view: DataView, at: number, size: number, out: TierBuilder): void {
|
||||
if (size < TILE_HEADER_BYTES) throw new NavPackError('Detour tile shorter than its header');
|
||||
const polyCount = view.getInt32(at + 24, true);
|
||||
const vertCount = view.getInt32(at + 28, true);
|
||||
const vertsAt = at + align4(TILE_HEADER_BYTES);
|
||||
const polysAt = vertsAt + align4(vertCount * 12);
|
||||
if (polysAt + polyCount * POLY_BYTES > at + size) throw new NavPackError('Detour tile polygons truncated');
|
||||
for (let p = 0; p < polyCount; p++) {
|
||||
const pa = polysAt + p * POLY_BYTES;
|
||||
const n = view.getUint8(pa + 30);
|
||||
const areaAndType = view.getUint8(pa + 31);
|
||||
if (areaAndType >> 6 !== DT_POLYTYPE_GROUND || n < 3) continue;
|
||||
const ring = new Float32Array(n * 2);
|
||||
let ySum = 0;
|
||||
for (let k = 0; k < n && k < VERTS_PER_POLY; k++) {
|
||||
const vi = view.getUint16(pa + 4 + k * 2, true);
|
||||
if (vi === DT_NULL_IDX || vi >= vertCount) throw new NavPackError('Detour polygon vertex out of range');
|
||||
const va = vertsAt + vi * 12;
|
||||
ring[k * 2] = view.getFloat32(va, true);
|
||||
ySum += view.getFloat32(va + 4, true);
|
||||
ring[k * 2 + 1] = view.getFloat32(va + 8, true);
|
||||
}
|
||||
out.rings.push(ring);
|
||||
out.heights.push(ySum / n);
|
||||
out.areas.push(areaAndType & 0x3f);
|
||||
out.flags.push(view.getUint16(pa + 28, true));
|
||||
}
|
||||
}
|
||||
|
||||
function readTier(view: DataView, offset: number, size: number): NavTier {
|
||||
if (offset + size > view.byteLength || size < NAV_PARAMS_BYTES + 4) throw new NavPackError('tier outside the file');
|
||||
const end = offset + size;
|
||||
const tileCount = view.getUint32(offset + NAV_PARAMS_BYTES, true);
|
||||
let at = offset + NAV_PARAMS_BYTES + 4;
|
||||
const out: TierBuilder = { rings: [], heights: [], areas: [], flags: [] };
|
||||
for (let t = 0; t < tileCount; t++) {
|
||||
if (at + 4 > end) throw new NavPackError(`tile ${t} header truncated`);
|
||||
const tileSize = view.getUint32(at, true);
|
||||
at += 4;
|
||||
if (tileSize === 0 || at + tileSize > end) throw new NavPackError(`tile ${t} truncated`);
|
||||
readTile(view, at, tileSize, out);
|
||||
at += tileSize;
|
||||
}
|
||||
return {
|
||||
polyCount: out.rings.length,
|
||||
rings: out.rings,
|
||||
heights: Float32Array.from(out.heights),
|
||||
areas: Uint8Array.from(out.areas),
|
||||
flags: Uint16Array.from(out.flags),
|
||||
};
|
||||
}
|
||||
|
||||
function readCovers(view: DataView, offset: number, count: number): NavCover[] {
|
||||
if (offset + count * COVER_BYTES > view.byteLength) throw new NavPackError('cover points outside the file');
|
||||
const covers: NavCover[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const a = offset + i * COVER_BYTES;
|
||||
const f = (k: number): number => view.getFloat32(a + k * 4, true);
|
||||
covers.push({
|
||||
pos: [f(0), f(1), f(2)],
|
||||
coverDir: [f(3), f(4)],
|
||||
retreatDir: [f(5), f(6)],
|
||||
halfAngleDeg: f(13),
|
||||
heightM: f(14),
|
||||
widthM: f(15),
|
||||
kind: view.getUint8(a + 64),
|
||||
});
|
||||
}
|
||||
return covers;
|
||||
}
|
||||
|
||||
function readTactical(view: DataView, h: ReturnType<typeof readHeader>): NavTactical {
|
||||
const cells = h.tacCols * h.tacRows;
|
||||
if (h.tacOffset + cells * 4 > view.byteLength) throw new NavPackError('tactical grid outside the file');
|
||||
const exposure = new Uint8Array(cells);
|
||||
const clearance = new Uint8Array(cells);
|
||||
for (let i = 0; i < cells; i++) {
|
||||
exposure[i] = view.getUint8(h.tacOffset + i * 4);
|
||||
clearance[i] = view.getUint8(h.tacOffset + i * 4 + 1);
|
||||
}
|
||||
return { cols: h.tacCols, rows: h.tacRows, cellM: h.tacCellM, origin: h.tacOrigin, exposure, clearanceHalfM: clearance };
|
||||
}
|
||||
|
||||
/** Parses a whole `.wtonav` file. Throws NavPackError when the bytes are not a valid pack. */
|
||||
export function readNavPack(bytes: Uint8Array): NavPack {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const h = readHeader(view);
|
||||
const tiers: NavTier[] = [];
|
||||
for (let t = 0; t < TIER_COUNT; t++) tiers.push(readTier(view, h.tierOffsets[t] ?? 0, h.tierSizes[t] ?? 0));
|
||||
const header: NavHeader = {
|
||||
version: h.version, flags: h.flags, everSha1: h.everSha1, bmin: h.bmin, bmax: h.bmax,
|
||||
waterLevel: h.waterLevel, coverCount: h.coverCount, tacCols: h.tacCols, tacRows: h.tacRows,
|
||||
tacCellM: h.tacCellM, tacOrigin: h.tacOrigin,
|
||||
};
|
||||
return { header, tiers, covers: readCovers(view, h.coverOffset, h.coverCount), tactical: readTactical(view, h) };
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Display names of the numeric codes the ground AI writes into its log lines. They mirror the
|
||||
* `let public WTO_*` constants of game-ai/ground; index = code.
|
||||
*/
|
||||
|
||||
export const BEHAVIOR_NAMES = ['advance', 'engage', 'halt', 'cover', 'reposition', 'hold', 'disperse', 'withdraw', 'repair'] as const;
|
||||
|
||||
export const STATE_NAMES: Readonly<Record<number, string>> = {
|
||||
0: 'march', 1: 'runAndGun', 3: 'shortHalt', 4: 'retreatCover', 5: 'coverReload',
|
||||
7: 'hullAngle', 8: 'reposition', 9: 'disabled', 10: 'disperse', 11: 'ridgeWithdraw',
|
||||
};
|
||||
|
||||
export const DENY_NAMES = [
|
||||
'ok', 'noTarget', 'notReady', 'hitProb', 'longWindow', 'aimErr', 'settle', 'budget',
|
||||
'muzzleHard', 'arcHard', 'friendly', 'multiGun', 'traverse', 'burstPause',
|
||||
] as const;
|
||||
|
||||
export const BLOCK_NAMES = ['none', 'terrain', 'object', 'wreck', 'vehicle', 'smoke', 'foliage'] as const;
|
||||
|
||||
export const COMMAND_NAMES = ['assault', 'flank', 'overwatch', 'defend', 'reserve', 'spaa'] as const;
|
||||
|
||||
export const URGENCY_NAMES = ['low', 'medium', 'high'] as const;
|
||||
|
||||
export const LANE_NAMES = ['center', 'left', 'right'] as const;
|
||||
|
||||
export const VEHICLE_CLASS_NAMES = ['medium', 'light', 'heavy', 'td', 'spaa'] as const;
|
||||
|
||||
/** Why the turret points where it does (WTO_LOOK_*). */
|
||||
export const LOOK_NAMES = ['none', 'engage', 'threat', 'watch', 'memory', 'cue', 'scan'] as const;
|
||||
|
||||
export function nameOf(names: readonly string[] | Readonly<Record<number, string>>, code: number): string {
|
||||
const name = Array.isArray(names) ? names[code] : (names as Readonly<Record<number, string>>)[code];
|
||||
return name ?? String(code);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Reads the ground AI replay trace out of a decrypted game log (wtotools decrypt-clog). Every
|
||||
* `WTO_AI|` line is `<log clock> [D] WTO_AI|KIND|key=value|...`. A battle starts at
|
||||
* RUNTIME_READY; lines before the first one (hangar) are skipped. TRACE_CAP, TRACE_U and TRACE_B
|
||||
* lines with the same time form one frame; all other kinds become events. Lines without a `t` field get
|
||||
* their mission time from the log clock, offset by the last line that had both.
|
||||
*/
|
||||
import type { BotSample, CapSample, TraceBattle, TraceEvent, TraceFrame, UnitSample } from './types.ts';
|
||||
|
||||
type Fields = Record<string, string>;
|
||||
|
||||
interface MutableBattle {
|
||||
level: string | undefined;
|
||||
frames: TraceFrame[];
|
||||
events: TraceEvent[];
|
||||
}
|
||||
|
||||
const MARK = 'WTO_AI|';
|
||||
|
||||
function splitLine(line: string): { clock: number; kind: string; fields: Fields } | undefined {
|
||||
const at = line.indexOf(MARK);
|
||||
if (at < 0) return undefined;
|
||||
const clock = Number.parseFloat(line);
|
||||
const parts = line.slice(at + MARK.length).trimEnd().split('|');
|
||||
const kind = parts[0] ?? '';
|
||||
const fields: Fields = {};
|
||||
for (let i = 1; i < parts.length; i++) {
|
||||
const part = parts[i] ?? '';
|
||||
const eq = part.indexOf('=');
|
||||
if (eq > 0) fields[part.slice(0, eq)] = part.slice(eq + 1);
|
||||
}
|
||||
return { clock, kind, fields };
|
||||
}
|
||||
|
||||
function num(f: Fields, key: string): number {
|
||||
const v = Number(f[key]);
|
||||
return Number.isFinite(v) ? v : 0;
|
||||
}
|
||||
|
||||
function flag(f: Fields, key: string): boolean {
|
||||
return f[key] === '1';
|
||||
}
|
||||
|
||||
function id(f: Fields, key: string): string {
|
||||
return f[key] ?? '0';
|
||||
}
|
||||
|
||||
function readCap(f: Fields): CapSample {
|
||||
return { idx: num(f, 'idx'), x: num(f, 'x'), z: num(f, 'z'), r: num(f, 'r'), owner: num(f, 'owner'), progress: num(f, 'prog') };
|
||||
}
|
||||
|
||||
function readUnit(f: Fields): UnitSample {
|
||||
return {
|
||||
eid: id(f, 'eid'), army: num(f, 'army'), bot: flag(f, 'bot'), human: flag(f, 'human'), alive: flag(f, 'alive'),
|
||||
x: num(f, 'x'), y: num(f, 'y'), z: num(f, 'z'), yaw: num(f, 'yaw'), speed: num(f, 'v'),
|
||||
shooting: flag(f, 'shoot'), light: flag(f, 'light'),
|
||||
};
|
||||
}
|
||||
|
||||
function readBot(f: Fields): BotSample {
|
||||
const gun = num(f, 'gun');
|
||||
return {
|
||||
eid: id(f, 'eid'), vehicleClass: num(f, 'cls'), hasOrder: flag(f, 'ord'), command: num(f, 'cmd'),
|
||||
urgency: num(f, 'urg'), capIdx: num(f, 'cap'), lane: num(f, 'lane'), goalX: num(f, 'gx'), goalZ: num(f, 'gz'),
|
||||
behavior: num(f, 'bhv'), behaviorScore: num(f, 'bs'), state: num(f, 'st'), wantSpeed: num(f, 'wantV'),
|
||||
forwardSpeed: num(f, 'vf'), reverseTravel: flag(f, 'rev'), target: id(f, 'tgt'), targetInSight: flag(f, 'los'),
|
||||
threatCount: num(f, 'threats'), topThreat: id(f, 'top'), topVisibleThreat: id(f, 'topVis'),
|
||||
lookAt: id(f, 'look'), lookReason: num(f, 'why'), wishYaw: num(f, 'wish'),
|
||||
gunYaw: gun === 9999 ? undefined : gun, gunReady: flag(f, 'ready'), reloading: flag(f, 'reload'),
|
||||
deny: num(f, 'deny'), hitProb: num(f, 'p'), threshold: num(f, 'thr'), requestedSpeed: num(f, 'reqV'),
|
||||
};
|
||||
}
|
||||
|
||||
function frameAt(battle: MutableBattle, t: number): TraceFrame {
|
||||
const last = battle.frames[battle.frames.length - 1];
|
||||
if (last !== undefined && last.t === t) return last;
|
||||
const frame: TraceFrame = { t, caps: [], units: new Map(), bots: new Map() };
|
||||
battle.frames.push(frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
function finish(b: MutableBattle): TraceBattle {
|
||||
b.events.sort((a, c) => a.t - c.t);
|
||||
const firstFrame = b.frames[0];
|
||||
const lastFrame = b.frames[b.frames.length - 1];
|
||||
const firstEvent = b.events[0];
|
||||
const lastEvent = b.events[b.events.length - 1];
|
||||
const startT = Math.min(firstFrame?.t ?? Infinity, firstEvent?.t ?? Infinity);
|
||||
const endT = Math.max(lastFrame?.t ?? -Infinity, lastEvent?.t ?? -Infinity);
|
||||
return { level: b.level, frames: b.frames, events: b.events, startT: Number.isFinite(startT) ? startT : 0, endT: Number.isFinite(endT) ? endT : 0 };
|
||||
}
|
||||
|
||||
/** All battles of one decrypted log, in log order. Battles without any trace frame are kept. */
|
||||
export function parseTraceLog(text: string): TraceBattle[] {
|
||||
const battles: TraceBattle[] = [];
|
||||
let current: MutableBattle | undefined;
|
||||
let pendingLevel: string | undefined;
|
||||
let clockOffset: number | undefined;
|
||||
const open = (): MutableBattle => {
|
||||
if (current !== undefined) battles.push(finish(current));
|
||||
current = { level: pendingLevel, frames: [], events: [] };
|
||||
return current;
|
||||
};
|
||||
for (const line of text.split('\n')) {
|
||||
const parsed = splitLine(line);
|
||||
if (parsed === undefined) continue;
|
||||
const { clock, kind, fields } = parsed;
|
||||
if (kind.startsWith('NAVMESH') && fields['level'] !== undefined && fields['level'] !== '') {
|
||||
pendingLevel = fields['level'];
|
||||
if (current !== undefined && current.level === undefined) current.level = pendingLevel;
|
||||
}
|
||||
if (kind === 'RUNTIME_READY') {
|
||||
open();
|
||||
clockOffset = undefined;
|
||||
continue;
|
||||
}
|
||||
const hasT = fields['t'] !== undefined;
|
||||
let t: number;
|
||||
if (hasT) {
|
||||
t = num(fields, 't');
|
||||
if (Number.isFinite(clock)) clockOffset = clock - t;
|
||||
} else if (clockOffset !== undefined && Number.isFinite(clock)) {
|
||||
t = clock - clockOffset;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
const battle: MutableBattle | undefined = current;
|
||||
if (battle === undefined) continue;
|
||||
if (kind === 'TRACE_CAP') frameAt(battle, t).caps.push(readCap(fields));
|
||||
else if (kind === 'TRACE_U') { const u = readUnit(fields); frameAt(battle, t).units.set(u.eid, u); }
|
||||
else if (kind === 'TRACE_B') { const b = readBot(fields); frameAt(battle, t).bots.set(b.eid, b); }
|
||||
else battle.events.push({ t, kind, eid: fields['eid'], fields });
|
||||
}
|
||||
if (current !== undefined) battles.push(finish(current));
|
||||
return battles;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* One battle of the ground AI replay trace (game-ai/ground/wto_ai_trace_common.das), as read from
|
||||
* a decrypted game log or written by the simulator. Times are mission seconds; positions world
|
||||
* metres; headings degrees of atan2(z, x). Entity ids stay the strings the log prints.
|
||||
*/
|
||||
|
||||
export interface CapSample {
|
||||
readonly idx: number;
|
||||
readonly x: number;
|
||||
readonly z: number;
|
||||
readonly r: number;
|
||||
readonly owner: number;
|
||||
readonly progress: number;
|
||||
}
|
||||
|
||||
export interface UnitSample {
|
||||
readonly eid: string;
|
||||
readonly army: number;
|
||||
readonly bot: boolean;
|
||||
readonly human: boolean;
|
||||
readonly alive: boolean;
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly z: number;
|
||||
readonly yaw: number;
|
||||
readonly speed: number;
|
||||
readonly shooting: boolean;
|
||||
readonly light: boolean;
|
||||
}
|
||||
|
||||
export interface BotSample {
|
||||
readonly eid: string;
|
||||
readonly vehicleClass: number;
|
||||
readonly hasOrder: boolean;
|
||||
readonly command: number;
|
||||
readonly urgency: number;
|
||||
readonly capIdx: number;
|
||||
readonly lane: number;
|
||||
readonly goalX: number;
|
||||
readonly goalZ: number;
|
||||
readonly behavior: number;
|
||||
readonly behaviorScore: number;
|
||||
readonly state: number;
|
||||
readonly wantSpeed: number;
|
||||
readonly forwardSpeed: number;
|
||||
readonly reverseTravel: boolean;
|
||||
/** Perception target; "0" when none. */
|
||||
readonly target: string;
|
||||
readonly targetInSight: boolean;
|
||||
readonly threatCount: number;
|
||||
readonly topThreat: string;
|
||||
readonly topVisibleThreat: string;
|
||||
/** What the turret aims at (engaged target or watched threat); "0" otherwise. */
|
||||
readonly lookAt: string;
|
||||
readonly lookReason: number;
|
||||
readonly wishYaw: number;
|
||||
/** Live barrel heading; undefined when the barrel could not be sampled. */
|
||||
readonly gunYaw: number | undefined;
|
||||
readonly gunReady: boolean;
|
||||
readonly reloading: boolean;
|
||||
readonly deny: number;
|
||||
readonly hitProb: number;
|
||||
readonly threshold: number;
|
||||
readonly requestedSpeed: number;
|
||||
}
|
||||
|
||||
export interface TraceFrame {
|
||||
readonly t: number;
|
||||
readonly caps: CapSample[];
|
||||
readonly units: Map<string, UnitSample>;
|
||||
readonly bots: Map<string, BotSample>;
|
||||
}
|
||||
|
||||
/** Any other WTO_AI line of the battle (SHOT, HIT, DEATH, BEHAVIOR, DENY, TURRET_FOCUS, NAV_*...). */
|
||||
export interface TraceEvent {
|
||||
readonly t: number;
|
||||
readonly kind: string;
|
||||
/** Entity the line is about (its `eid` field), when it has one. */
|
||||
readonly eid: string | undefined;
|
||||
readonly fields: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface TraceBattle {
|
||||
/** Level name from the navigation pack line (e.g. avg_berlin), when logged. */
|
||||
readonly level: string | undefined;
|
||||
readonly frames: TraceFrame[];
|
||||
readonly events: TraceEvent[];
|
||||
readonly startT: number;
|
||||
readonly endT: number;
|
||||
}
|
||||
@@ -339,6 +339,8 @@ export interface GroundAiConfig {
|
||||
readonly statsSampleSec: number;
|
||||
readonly statsSampleRangeM: number;
|
||||
readonly statsRearArcDeg: number;
|
||||
readonly trace: boolean;
|
||||
readonly traceIntervalSec: number;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -590,6 +592,8 @@ function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] {
|
||||
['WTO_AI_STATS_SAMPLE_SEC', 'float', c.diagnostics.statsSampleSec],
|
||||
['WTO_AI_STATS_RANGE_M', 'float', c.diagnostics.statsSampleRangeM],
|
||||
['WTO_AI_STATS_REAR_ARC_DEG', 'float', c.diagnostics.statsRearArcDeg],
|
||||
['WTO_AI_TRACE_ENABLED', 'bool', c.diagnostics.trace],
|
||||
['WTO_AI_TRACE_SEC', 'float', c.diagnostics.traceIntervalSec],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -17,6 +17,7 @@
|
||||
},
|
||||
"include": ["apps/*/src/**/*.ts", "packages/*/src/**/*.ts", "scripts/**/*.ts"],
|
||||
// The launcher is an Electron app with a window: it has its own tsconfig.node.json and
|
||||
// tsconfig.web.json and its own typecheck script.
|
||||
"exclude": ["apps/launcher/**"]
|
||||
// tsconfig.web.json and its own typecheck script. The AI lab (apps/ai-lab) is a Vite page with
|
||||
// its own tsconfig.json and typecheck script too.
|
||||
"exclude": ["apps/launcher/**", "apps/ai-lab/**"]
|
||||
}
|
||||
Reference in new issue
Block a user