diff --git a/apps/ai-lab/.gitignore b/apps/ai-lab/.gitignore
new file mode 100644
index 0000000..2429ea8
--- /dev/null
+++ b/apps/ai-lab/.gitignore
@@ -0,0 +1,2 @@
+lab.local.json
+.cache/
diff --git a/apps/ai-lab/index.html b/apps/ai-lab/index.html
new file mode 100644
index 0000000..403ef2d
--- /dev/null
+++ b/apps/ai-lab/index.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+ WTOffline AI Lab
+
+
+
+
+
+
diff --git a/apps/ai-lab/lab.local.example.json b/apps/ai-lab/lab.local.example.json
new file mode 100644
index 0000000..8341569
--- /dev/null
+++ b/apps/ai-lab/lab.local.example.json
@@ -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"
+}
diff --git a/apps/ai-lab/package.json b/apps/ai-lab/package.json
new file mode 100644
index 0000000..0330bcb
--- /dev/null
+++ b/apps/ai-lab/package.json
@@ -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"
+ }
+}
diff --git a/apps/ai-lab/server/lab-api.ts b/apps/ai-lab/server/lab-api.ts
new file mode 100644
index 0000000..78c31db
--- /dev/null
+++ b/apps/ai-lab/server/lab-api.ts
@@ -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) : {};
+ 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 {
+ 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 {
+ 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);
+ },
+ };
+}
diff --git a/apps/ai-lab/src/App.tsx b/apps/ai-lab/src/App.tsx
new file mode 100644
index 0000000..161f5cd
--- /dev/null
+++ b/apps/ai-lab/src/App.tsx
@@ -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> = {
+ 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([]);
+ const [logs, setLogs] = useState([]);
+ const [logName, setLogName] = useState('');
+ const [battles, setBattles] = useState([]);
+ const [battleIdx, setBattleIdx] = useState(0);
+ const [mapData, setMapData] = useState(undefined);
+ const [exposure, setExposure] = useState(false);
+ const [covers, setCovers] = useState(false);
+ const [layers, setLayers] = useState({ 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(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 (
+
+
+
+
+ {battle !== undefined && }
+
+ {battle !== undefined && (
+
+ )}
+
+ );
+}
diff --git a/apps/ai-lab/src/Inspector.tsx b/apps/ai-lab/src/Inspector.tsx
new file mode 100644
index 0000000..a0d6c88
--- /dev/null
+++ b/apps/ai-lab/src/Inspector.tsx
@@ -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 (
+
+ {names.map((n, i) => (
+ {n}
+ ))}
+
+ );
+}
+
+function Row({ k, v }: { k: string; v: string }): React.JSX.Element {
+ return | {k} | {v} |
;
+}
+
+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 (
+
+ );
+}
diff --git a/apps/ai-lab/src/MapView.tsx b/apps/ai-lab/src/MapView.tsx
new file mode 100644
index 0000000..14e3b67
--- /dev/null
+++ b/apps/ai-lab/src/MapView.tsx
@@ -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(null);
+ const [view, setView] = useState({ 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 (
+