diff --git a/apps/ai-lab/lab.local.example.json b/apps/ai-lab/lab.local.example.json index 8341569..2ef08bd 100644 --- a/apps/ai-lab/lab.local.example.json +++ b/apps/ai-lab/lab.local.example.json @@ -1,5 +1,6 @@ { "mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps", + "geoDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/work", "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 index 0330bcb..19efe18 100644 --- a/apps/ai-lab/package.json +++ b/apps/ai-lab/package.json @@ -11,11 +11,13 @@ "dependencies": { "@wto/ground-sim": "*", "react": "^19.2.8", - "react-dom": "^19.2.8" + "react-dom": "^19.2.8", + "three": "^0.187.0" }, "devDependencies": { "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", + "@types/three": "^0.187.0", "@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 index 78c31db..f808bf4 100644 --- a/apps/ai-lab/server/lab-api.ts +++ b/apps/ai-lab/server/lab-api.ts @@ -4,17 +4,22 @@ * 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) + * GET /api/scene?name= the 3D map (.wtoscene) of a level, built from its .wtogeo in geoDir + * (cached until the geometry 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 { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'; import type { ServerResponse } from 'node:http'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { buildMapScene, encodeMapScene, readGeo } from '@wto/ground-sim'; import type { Connect, Plugin } from 'vite'; interface LabConfig { readonly mapsDir: string; + /** Where the navigation bake left the levels' .wtogeo geometry. */ + readonly geoDir: string; readonly logsDir: string; readonly python: string; } @@ -27,8 +32,10 @@ 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); + const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')); return { - mapsDir: str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')), + mapsDir, + geoDir: str('geoDir', path.join(mapsDir, '..', 'work')), logsDir: str('logsDir', ''), python: str('python', 'python'), }; @@ -46,13 +53,17 @@ function sendFile(res: ServerResponse, file: string, type: string): void { createReadStream(file).pipe(res); } -function listMaps(cfg: LabConfig): { level: string; pois: boolean }[] { +function listMaps(cfg: LabConfig): { level: string; pois: boolean; scene: 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`)) }; + return { + level, + pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)), + scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)), + }; }); } @@ -81,12 +92,30 @@ function decryptLog(cfg: LabConfig, name: string): Promise { }); } +/** Builds the level's 3D map into the cache unless the cached one is newer than its geometry. */ +function sceneFile(cfg: LabConfig, level: string): string | undefined { + const geo = path.join(cfg.geoDir, `${level}.wtogeo`); + if (!existsSync(geo)) return undefined; + const out = path.join(CACHE_DIR, `${level}.wtoscene`); + if (existsSync(out) && statSync(out).mtimeMs >= statSync(geo).mtimeMs) return out; + mkdirSync(CACHE_DIR, { recursive: true }); + writeFileSync(out, encodeMapScene(buildMapScene(readGeo(readFileSync(geo))))); + return 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; + const known = ['/api/maps/file', '/api/logs/text', '/api/scene']; + if (!known.includes(url.pathname)) return false; if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; } + if (url.pathname === '/api/scene') { + const file = sceneFile(cfg, name); + if (file === undefined) sendJson(res, 404, { error: `no ${name}.wtogeo in ${cfg.geoDir}` }); + else sendFile(res, file, 'application/octet-stream'); + 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}` }); diff --git a/apps/ai-lab/src/App.tsx b/apps/ai-lab/src/App.tsx index 161f5cd..c20616e 100644 --- a/apps/ai-lab/src/App.tsx +++ b/apps/ai-lab/src/App.tsx @@ -2,17 +2,20 @@ 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 { Map3D, type MapLook } from './Map3D.tsx'; import { buildMapLayer } from './mapLayer.ts'; -import { MapView } from './MapView.tsx'; +import type { ViewMode } from './three/cameraRig.ts'; +import type { Layers } from './three/overlays.ts'; import { Timeline } from './Timeline.tsx'; const LAYER_LABELS: Readonly> = { goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击', }; +const VIEW_LABELS: Readonly> = { top: '俯视', free: '自由', follow: '跟随选中车', gun: '炮口视角' }; + function logLabel(l: LogEntry): string { const when = new Date(l.mtime).toLocaleString(); return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`; @@ -27,6 +30,7 @@ export function App(): React.JSX.Element { const [mapData, setMapData] = useState(undefined); const [exposure, setExposure] = useState(false); const [covers, setCovers] = useState(false); + const [look, setLook] = useState({ view: 'top', navImage: true, objects: true, crushable: true }); const [layers, setLayers] = useState({ goals: true, links: true, cones: false, labels: false, events: true }); const [t, setT] = useState(0); const [playing, setPlaying] = useState(false); @@ -75,12 +79,6 @@ export function App(): React.JSX.Element { () => (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; @@ -121,13 +119,20 @@ export function App(): React.JSX.Element { {LAYER_LABELS[k]} ))} + + + + {status !== '' && {status}} {battle !== undefined && battle.frames.length === 0 && 这一局没有轨迹(游戏里没开 diagnostics.trace)。}
- + {battle !== undefined && }
{battle !== undefined && ( diff --git a/apps/ai-lab/src/Map3D.tsx b/apps/ai-lab/src/Map3D.tsx new file mode 100644 index 0000000..dfc8082 --- /dev/null +++ b/apps/ai-lab/src/Map3D.tsx @@ -0,0 +1,179 @@ +/** + * The battle in 3D: terrain and object collision shapes of the level, vehicles as simple shapes, + * and the replay's lines and markers. Left drag pans, right drag turns (except top-down), wheel + * zooms; a click on a vehicle selects it. + */ +import { BEHAVIOR_NAMES, type MapScene, type TraceBattle } from '@wto/ground-sim'; +import { useEffect, useRef } from 'react'; +import { AmbientLight, Color, DirectionalLight, HemisphereLight, Raycaster, Scene, Vector2, WebGLRenderer } from 'three'; +import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js'; +import type { SceneAt, UnitAt } from './frames.ts'; +import type { MapLayer } from './mapLayer.ts'; +import { CameraRig, type ViewMode } from './three/cameraRig.ts'; +import { buildMapMeshes, setTerrainImage, type MapMeshes } from './three/mapMeshes.ts'; +import { Overlays, type Layers } from './three/overlays.ts'; +import { TankPool } from './three/tanks.ts'; + +export interface MapLook { + readonly view: ViewMode; + /** Drape the navigation mesh image over the terrain instead of height colours. */ + readonly navImage: boolean; + readonly objects: boolean; + readonly crushable: boolean; +} + +interface Props { + readonly mapScene: MapScene | undefined; + readonly nav: MapLayer | undefined; + readonly battle: TraceBattle | undefined; + readonly scene: SceneAt | undefined; + readonly selected: string | undefined; + readonly layers: Layers; + readonly look: MapLook; + readonly onSelect: (eid: string | undefined) => void; +} + +interface World { + readonly renderer: WebGLRenderer; + readonly labels: CSS2DRenderer; + readonly scene: Scene; + readonly rig: CameraRig; + map: MapMeshes | undefined; + tanks: TankPool; + overlays: Overlays; + selected: string | undefined; +} + +const CRUSHABLE_KIND = 3; +const CLICK_PX = 4; + +function labelOf(u: UnitAt): string { + const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : ''; + return `${u.unit.eid.replace(/^0x/, '')} ${name}`; +} + +function createWorld(host: HTMLDivElement): World { + const renderer = new WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true }); + renderer.setPixelRatio(window.devicePixelRatio); + host.appendChild(renderer.domElement); + const labels = new CSS2DRenderer(); + labels.domElement.className = 'labels3d'; + host.appendChild(labels.domElement); + const scene = new Scene(); + scene.background = new Color(0x0b0c0d); + scene.add(new HemisphereLight(0xdfe8ff, 0x3a3326, 1.4), new AmbientLight(0xffffff, 0.25)); + const sun = new DirectionalLight(0xffffff, 1.6); + sun.position.set(0.5, 1, 0.3); + scene.add(sun); + const tanks = new TankPool(undefined); + const overlays = new Overlays(tanks); + scene.add(tanks.group, overlays.group); + return { renderer, labels, scene, rig: new CameraRig(renderer.domElement), map: undefined, tanks, overlays, selected: undefined }; +} + +function replaceMap(w: World, mapScene: MapScene | undefined, nav: MapLayer | undefined): void { + if (w.map !== undefined) { w.scene.remove(w.map.group); w.map.dispose(); } + w.scene.remove(w.tanks.group, w.overlays.group); + w.tanks.dispose(); + w.overlays.dispose(); + w.map = mapScene === undefined ? undefined : buildMapMeshes(mapScene, nav); + w.tanks = new TankPool(mapScene?.terrain); + w.overlays = new Overlays(w.tanks); + if (w.map !== undefined) w.scene.add(w.map.group); + w.scene.add(w.tanks.group, w.overlays.group); + if (mapScene !== undefined) { + const t = mapScene.terrain; + let sum = 0; + for (const h of t.heights) sum += h; + w.rig.fit(mapScene.boundsMin[0], mapScene.boundsMin[1], mapScene.boundsMax[0], mapScene.boundsMax[1], sum / Math.max(1, t.heights.length)); + } +} + +export function Map3D({ mapScene, nav, battle, scene, selected, layers, look, onSelect }: Props): React.JSX.Element { + const hostRef = useRef(null); + const worldRef = useRef(undefined); + const onSelectRef = useRef(onSelect); + onSelectRef.current = onSelect; + + useEffect(() => { + const host = hostRef.current; + if (host === null) return; + const w = createWorld(host); + worldRef.current = w; + const resize = (): void => { + const r = host.getBoundingClientRect(); + w.renderer.setSize(r.width, r.height); + w.labels.setSize(r.width, r.height); + w.rig.resize(r.width, r.height); + }; + const obs = new ResizeObserver(resize); + obs.observe(host); + resize(); + w.renderer.setAnimationLoop(() => { + w.rig.tick(w.selected === undefined ? undefined : w.tanks.get(w.selected)); + w.renderer.render(w.scene, w.rig.camera); + w.labels.render(w.scene, w.rig.camera); + }); + const down = new Vector2(); + const el = w.renderer.domElement; + const onDown = (e: PointerEvent): void => { down.set(e.clientX, e.clientY); }; + const onUp = (e: PointerEvent): void => { + if (e.button !== 0 || Math.hypot(e.clientX - down.x, e.clientY - down.y) > CLICK_PX) return; + const r = el.getBoundingClientRect(); + const ray = new Raycaster(); + ray.setFromCamera(new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), w.rig.camera); + const hit = ray.intersectObjects(w.tanks.pickables(), false)[0]; + onSelectRef.current(hit?.object.userData['eid'] as string | undefined); + }; + el.addEventListener('pointerdown', onDown); + el.addEventListener('pointerup', onUp); + return () => { + obs.disconnect(); + el.removeEventListener('pointerdown', onDown); + el.removeEventListener('pointerup', onUp); + w.renderer.setAnimationLoop(null); + replaceMap(w, undefined, undefined); + w.rig.dispose(); + w.renderer.dispose(); + host.replaceChildren(); + worldRef.current = undefined; + }; + }, []); + + useEffect(() => { + const w = worldRef.current; + if (w !== undefined) replaceMap(w, mapScene, nav); + // The navigation image is applied by the effect below; only a new level rebuilds the map. + }, [mapScene]); + + useEffect(() => { + const w = worldRef.current; + if (w?.map !== undefined) setTerrainImage(w.map, look.navImage ? nav : undefined); + }, [nav, look.navImage, mapScene]); + + useEffect(() => { + const w = worldRef.current; + if (w?.map === undefined) return; + w.map.kinds.forEach((g, k) => { g.visible = look.objects && (k !== CRUSHABLE_KIND || look.crushable); }); + }, [look.objects, look.crushable, mapScene]); + + useEffect(() => { + worldRef.current?.rig.setMode(look.view); + }, [look.view]); + + useEffect(() => { + const w = worldRef.current; + if (w === undefined) return; + w.selected = selected; + w.rig.refollow(); + }, [selected]); + + useEffect(() => { + const w = worldRef.current; + if (w === undefined || battle === undefined || scene === undefined) return; + w.tanks.update(scene.units, selected, (u) => (layers.labels && u.unit.alive ? labelOf(u) : undefined)); + w.overlays.update(battle, scene, layers); + }, [battle, scene, selected, layers, mapScene]); + + return
; +} diff --git a/apps/ai-lab/src/MapView.tsx b/apps/ai-lab/src/MapView.tsx deleted file mode 100644 index 14e3b67..0000000 --- a/apps/ai-lab/src/MapView.tsx +++ /dev/null @@ -1,87 +0,0 @@ -/** 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 ( - 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; }} - /> - ); -} diff --git a/apps/ai-lab/src/data.ts b/apps/ai-lab/src/data.ts index 7bd8a73..cfee8cc 100644 --- a/apps/ai-lab/src/data.ts +++ b/apps/ai-lab/src/data.ts @@ -1,5 +1,7 @@ /** 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'; +import { + decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle, +} from '@wto/ground-sim'; export interface LogEntry { readonly name: string; @@ -10,11 +12,14 @@ export interface LogEntry { export interface MapEntry { readonly level: string; readonly pois: boolean; + /** The level's geometry is there, so it has a 3D map. */ + readonly scene: boolean; } export interface MapData { readonly pack: NavPack; readonly pois: MapPois | undefined; + readonly scene: MapScene | undefined; } async function get(url: string): Promise { @@ -44,5 +49,8 @@ export async function loadMap(entry: MapEntry): Promise { const pois = entry.pois ? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text()) : undefined; - return { pack: readNavPack(bytes), pois }; + const scene = entry.scene + ? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer())) + : undefined; + return { pack: readNavPack(bytes), pois, scene }; } diff --git a/apps/ai-lab/src/draw.ts b/apps/ai-lab/src/draw.ts deleted file mode 100644 index e1313e4..0000000 --- a/apps/ai-lab/src/draw.ts +++ /dev/null @@ -1,168 +0,0 @@ -/** 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> = { 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); -} diff --git a/apps/ai-lab/src/frames.ts b/apps/ai-lab/src/frames.ts index ce5f04f..09fa89b 100644 --- a/apps/ai-lab/src/frames.ts +++ b/apps/ai-lab/src/frames.ts @@ -3,10 +3,16 @@ import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from ' export interface UnitAt { readonly unit: UnitSample; - /** Interpolated position and heading. */ + /** Interpolated position, hull heading, pitch and roll. */ readonly x: number; + readonly y: number; readonly z: number; readonly yaw: number; + readonly hullPitch: number; + readonly hullRoll: number; + /** Interpolated gun world yaw and pitch; from the bot line, or the hull, when the unit line has none. */ + readonly gunYaw: number; + readonly gunPitch: number; /** Decision state of the sample at or before the time; undefined for players. */ readonly bot: BotSample | undefined; } @@ -34,6 +40,14 @@ function lerpYaw(a: number, b: number, k: number): number { return a + d * k; } +function lerp(a: number, b: number | undefined, k: number): number { + return a + ((b ?? a) - a) * k; +} + +function gunOf(u: UnitSample, bot: BotSample | undefined): [number, number] { + return [u.gunYaw ?? bot?.gunYaw ?? u.yaw, u.gunPitch ?? 0]; +} + export function sceneAt(battle: TraceBattle, t: number): SceneAt { const i = Math.max(0, frameIndexAt(battle, t)); const a = battle.frames[i]; @@ -44,12 +58,20 @@ export function sceneAt(battle: TraceBattle, t: number): SceneAt { for (const [eid, ua] of a.units) { const ub = b?.units.get(eid); const move = ub !== undefined && ua.alive && ub.alive ? k : 0; + const bot = a.bots.get(eid); + const [gyA, gpA] = gunOf(ua, bot); + const [gyB, gpB] = ub !== undefined ? gunOf(ub, b?.bots.get(eid)) : [gyA, gpA]; 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, + x: lerp(ua.x, ub?.x, move), + y: lerp(ua.y, ub?.y, move), + z: lerp(ua.z, ub?.z, move), yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move), - bot: a.bots.get(eid), + hullPitch: lerp(ua.hullPitch ?? 0, ub?.hullPitch, move), + hullRoll: lerp(ua.hullRoll ?? 0, ub?.hullRoll, move), + gunYaw: lerpYaw(gyA, gyB, move), + gunPitch: lerp(gpA, gpB, move), + bot, }); } return { t, units, caps: a.caps }; diff --git a/apps/ai-lab/src/mapLayer.ts b/apps/ai-lab/src/mapLayer.ts index de2a125..2c40b5a 100644 --- a/apps/ai-lab/src/mapLayer.ts +++ b/apps/ai-lab/src/mapLayer.ts @@ -1,5 +1,5 @@ /** - * The static map drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured + * The navigation image draped over the 3D terrain, 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'; @@ -33,7 +33,8 @@ export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer { canvas.height = Math.ceil((z1 - z0) * pxPerM); const ctx = canvas.getContext('2d'); if (ctx === null) return { canvas, x0, z1, pxPerM }; - ctx.fillStyle = '#121416'; + // Off the mesh (buildings, steep or blocked ground) when draped over the 3D terrain. + ctx.fillStyle = '#55584f'; ctx.fillRect(0, 0, canvas.width, canvas.height); const tier = pack.tiers[opts.tier] ?? pack.tiers[1]; if (tier !== undefined) { diff --git a/apps/ai-lab/src/style.css b/apps/ai-lab/src/style.css index 7e1c828..f439f6d 100644 --- a/apps/ai-lab/src/style.css +++ b/apps/ai-lab/src/style.css @@ -6,7 +6,11 @@ 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; } +.map3d { flex: 1; min-width: 0; height: 100%; position: relative; overflow: hidden; } +.map3d canvas { display: block; } +.labels3d { position: absolute; inset: 0; pointer-events: none; } +.tank-label { color: rgba(255,255,255,0.9); font-size: 11px; text-shadow: 0 0 3px #000; white-space: nowrap; } +.tank-label.human { color: #ffe14a; } .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; } diff --git a/apps/ai-lab/src/three/cameraRig.ts b/apps/ai-lab/src/three/cameraRig.ts new file mode 100644 index 0000000..20f4b99 --- /dev/null +++ b/apps/ai-lab/src/three/cameraRig.ts @@ -0,0 +1,119 @@ +/** + * The 3D view's cameras: a top-down orthographic map view (world +z up the screen, like the old + * flat map), a free perspective view, a view that follows the selected vehicle, and a view out of + * its muzzle along the barrel. + */ +import { OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from 'three'; +import { MapControls } from 'three/addons/controls/MapControls.js'; +import type { Tank } from './tanks.ts'; + +export type ViewMode = 'top' | 'free' | 'follow' | 'gun'; + +const TOP_HEIGHT = 3000; +/** Top-down camera sits this far south of its target, so the controls keep north up. */ +const TOP_SOUTH = 0.01; +const FREE_MAX_POLAR = Math.PI * 0.49; + +export class CameraRig { + readonly persp = new PerspectiveCamera(50, 1, 0.5, 20000); + readonly ortho = new OrthographicCamera(-1, 1, 1, -1, 1, 10000); + readonly controls: MapControls; + private mode: ViewMode = 'top'; + private aspect = 1; + private readonly lastFollow = new Vector3(); + private following = false; + + constructor(dom: HTMLElement) { + this.controls = new MapControls(this.ortho, dom); + this.controls.enableDamping = true; + this.controls.dampingFactor = 0.15; + this.controls.screenSpacePanning = true; + this.limitTilt(); + } + + /** Top-down stays straight down; the other views may tilt down to just above the horizon. */ + private limitTilt(): void { + this.controls.maxPolarAngle = this.mode === 'top' ? 0 : FREE_MAX_POLAR; + } + + get camera(): Camera { + return this.mode === 'top' ? this.ortho : this.persp; + } + + resize(w: number, h: number): void { + this.aspect = w / Math.max(1, h); + this.persp.aspect = this.aspect; + this.persp.updateProjectionMatrix(); + const half = (this.ortho.top - this.ortho.bottom) / 2; + this.ortho.left = -half * this.aspect; + this.ortho.right = half * this.aspect; + this.ortho.updateProjectionMatrix(); + } + + /** Frames the world rectangle (x, z) in both cameras. */ + fit(minX: number, minZ: number, maxX: number, maxZ: number, groundY: number): void { + const cx = (minX + maxX) / 2; + const cz = -(minZ + maxZ) / 2; + const half = (Math.max((maxX - minX) / this.aspect, maxZ - minZ) / 2) * 1.05; + Object.assign(this.ortho, { left: -half * this.aspect, right: half * this.aspect, top: half, bottom: -half, zoom: 1 }); + this.ortho.updateProjectionMatrix(); + this.ortho.position.set(cx, groundY + TOP_HEIGHT, cz + TOP_SOUTH); + this.persp.position.set(cx, groundY + half * 0.9, cz + half * 1.1); + this.controls.target.set(cx, groundY, cz); + this.ortho.lookAt(this.controls.target); + this.persp.lookAt(this.controls.target); + this.controls.update(); + } + + setMode(mode: ViewMode): void { + if (mode === this.mode) return; + const target = this.controls.target.clone(); + if (this.mode === 'top' && mode !== 'gun') { + const span = (this.ortho.top - this.ortho.bottom) / this.ortho.zoom; + this.persp.position.set(target.x, target.y + span * 0.6, target.z + span * 0.6); + } + if (mode === 'top') this.ortho.position.set(target.x, target.y + TOP_HEIGHT, target.z + TOP_SOUTH); + this.mode = mode; + this.limitTilt(); + this.following = false; + this.controls.object = this.camera; + this.controls.enableRotate = mode !== 'top'; + this.controls.enabled = mode !== 'gun'; + this.camera.lookAt(target); + this.controls.update(); + } + + /** The next follow frame starts over around the (newly) selected vehicle. */ + refollow(): void { + this.following = false; + } + + /** Per frame: keeps the followed vehicle centred, or puts the camera at the muzzle. */ + tick(tank: Tank | undefined): void { + if (this.mode === 'follow' && tank !== undefined && tank.root.visible) { + const at = tank.root.position; + if (!this.following) { + this.controls.target.copy(at); + this.persp.position.set(at.x - 25, at.y + 15, at.z + 25); + this.following = true; + } else { + const d = at.clone().sub(this.lastFollow); + this.controls.target.add(d); + this.persp.position.add(d); + } + this.lastFollow.copy(at); + } else if (this.mode === 'gun' && tank !== undefined && tank.root.visible) { + const q = tank.barrel.getWorldQuaternion(new Quaternion()); + const dir = new Vector3(1, 0, 0).applyQuaternion(q); + const tip = tank.barrel.getWorldPosition(new Vector3()).addScaledVector(dir, tank.length * 0.8); + this.persp.position.copy(tip); + this.persp.lookAt(tip.clone().add(dir)); + return; + } + if (this.controls.enabled) this.controls.update(); + } + + dispose(): void { + this.controls.dispose(); + } +} diff --git a/apps/ai-lab/src/three/coords.ts b/apps/ai-lab/src/three/coords.ts new file mode 100644 index 0000000..ad9c3a6 --- /dev/null +++ b/apps/ai-lab/src/three/coords.ts @@ -0,0 +1,18 @@ +/** + * Game world to three.js: Dagor is left-handed with Y up, three.js right-handed, so world z is + * mirrored (three z = -world z). A world heading (degrees of atan2(z, x)) then becomes the same + * angle of rotation about three's +Y, and a model's local +X is its front, +Y up, -Z its left. + */ +import { Vector3 } from 'three'; + +export const DEG = Math.PI / 180; + +export function toThree(x: number, y: number, z: number, out: Vector3 = new Vector3()): Vector3 { + return out.set(x, y, -z); +} + +/** Three.js direction of a world heading and pitch, in degrees. */ +export function dirOf(yawDeg: number, pitchDeg: number, out: Vector3 = new Vector3()): Vector3 { + const c = Math.cos(pitchDeg * DEG); + return out.set(Math.cos(yawDeg * DEG) * c, Math.sin(pitchDeg * DEG), -Math.sin(yawDeg * DEG) * c); +} diff --git a/apps/ai-lab/src/three/mapMeshes.ts b/apps/ai-lab/src/three/mapMeshes.ts new file mode 100644 index 0000000..c163833 --- /dev/null +++ b/apps/ai-lab/src/three/mapMeshes.ts @@ -0,0 +1,134 @@ +/** + * The static 3D map: lit terrain (coloured by height, or draped with the navigation mesh image), + * the collision shapes of placed objects coloured by kind, and the water plane. + */ +import type { MapScene, SceneTerrain } from '@wto/ground-sim'; +import { + BufferAttribute, BufferGeometry, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshLambertMaterial, + PlaneGeometry, SRGBColorSpace, type Material, +} from 'three'; +import type { MapLayer } from '../mapLayer.ts'; + +/** Colour and opacity per SCENE_KIND_NAMES entry. */ +const KIND_LOOK: readonly (readonly [number, number])[] = [ + [0xb9b2a3, 1], [0x7d7a74, 1], [0x9a7b55, 1], [0xe09a4a, 0.4], [0x4f8a3c, 1], [0x6f8aa0, 1], +]; + +const LOW = new Color(0x3c4a32); +const HIGH = new Color(0x9b9171); + +export interface MapMeshes { + readonly group: Group; + readonly terrain: Mesh; + /** Objects per scene kind, to switch kinds on and off. */ + readonly kinds: Group[]; + dispose(): void; +} + +function terrainGeometry(t: SceneTerrain, nav: MapLayer | undefined): BufferGeometry { + const n = t.cols * t.rows; + const pos = new Float32Array(n * 3); + const col = new Float32Array(n * 3); + const uv = new Float32Array(n * 2); + let lo = Infinity; + let hi = -Infinity; + for (const h of t.heights) { lo = Math.min(lo, h); hi = Math.max(hi, h); } + const c = new Color(); + const navW = nav === undefined ? 1 : nav.canvas.width / nav.pxPerM; + const navH = nav === undefined ? 1 : nav.canvas.height / nav.pxPerM; + for (let r = 0; r < t.rows; r++) { + for (let k = 0; k < t.cols; k++) { + const i = r * t.cols + k; + const x = t.origin[0] + k * t.cellM; + const z = t.origin[1] + r * t.cellM; + const h = t.heights[i] ?? 0; + pos.set([x, h, -z], i * 3); + c.lerpColors(LOW, HIGH, hi > lo ? (h - lo) / (hi - lo) : 0); + col.set([c.r, c.g, c.b], i * 3); + if (nav !== undefined) uv.set([(x - nav.x0) / navW, (z - (nav.z1 - navH)) / navH], i * 2); + } + } + const idx = new Uint32Array((t.cols - 1) * (t.rows - 1) * 6); + let at = 0; + for (let r = 0; r + 1 < t.rows; r++) { + for (let k = 0; k + 1 < t.cols; k++) { + const i = r * t.cols + k; + idx.set([i, i + 1, i + t.cols, i + 1, i + t.cols + 1, i + t.cols], at); + at += 6; + } + } + const g = new BufferGeometry(); + g.setAttribute('position', new BufferAttribute(pos, 3)); + g.setAttribute('color', new BufferAttribute(col, 3)); + g.setAttribute('uv', new BufferAttribute(uv, 2)); + g.setIndex(new BufferAttribute(idx, 1)); + g.computeVertexNormals(); + return g; +} + +/** Drapes the navigation image over the terrain, or goes back to height colours. */ +export function setTerrainImage(m: MapMeshes, nav: MapLayer | undefined): void { + const mat = m.terrain.material; + mat.map?.dispose(); + if (nav === undefined) { + mat.map = null; + mat.vertexColors = true; + } else { + const tex = new CanvasTexture(nav.canvas); + tex.colorSpace = SRGBColorSpace; + tex.anisotropy = 8; + mat.map = tex; + mat.vertexColors = false; + } + mat.needsUpdate = true; +} + +function objectKinds(scene: MapScene, materials: Material[]): Group[] { + const kinds = KIND_LOOK.map(() => new Group()); + const mats = KIND_LOOK.map(([color, opacity]) => new MeshLambertMaterial({ + color, flatShading: true, side: DoubleSide, transparent: opacity < 1, opacity, depthWrite: opacity >= 1, + })); + materials.push(...mats); + for (const m of scene.meshes) { + const g = new BufferGeometry(); + const pos = new Float32Array(m.positions); + for (let i = 2; i < pos.length; i += 3) pos[i] = -(pos[i] ?? 0); + g.setAttribute('position', new BufferAttribute(pos, 3)); + g.setIndex(new BufferAttribute(m.indices, 1)); + g.computeBoundingSphere(); + const mat = mats[m.kind] ?? mats[0]; + if (mat !== undefined) kinds[m.kind]?.add(new Mesh(g, mat)); + } + return kinds; +} + +export function buildMapMeshes(scene: MapScene, nav: MapLayer | undefined): MapMeshes { + const group = new Group(); + const materials: Material[] = []; + const terrainMat = new MeshLambertMaterial({ vertexColors: true }); + materials.push(terrainMat); + const terrain = new Mesh(terrainGeometry(scene.terrain, nav), terrainMat); + group.add(terrain); + const kinds = objectKinds(scene, materials); + for (const k of kinds) group.add(k); + if (scene.waterLevel !== undefined) { + const w = scene.boundsMax[0] - scene.boundsMin[0]; + const d = scene.boundsMax[1] - scene.boundsMin[1]; + const waterMat = new MeshLambertMaterial({ color: 0x2d5f8a, transparent: true, opacity: 0.55, depthWrite: false }); + materials.push(waterMat); + const water = new Mesh(new PlaneGeometry(w, d), waterMat); + water.rotation.x = -Math.PI / 2; + water.position.set(scene.boundsMin[0] + w / 2, scene.waterLevel, -(scene.boundsMin[1] + d / 2)); + group.add(water); + } + const meshes: MapMeshes = { + group, terrain, kinds, + dispose() { + group.traverse((o) => { if (o instanceof Mesh) (o.geometry as BufferGeometry).dispose(); }); + terrainMat.map?.dispose(); + for (const m of materials) m.dispose(); + }, + }; + if (nav !== undefined) setTerrainImage(meshes, nav); + return meshes; +} diff --git a/apps/ai-lab/src/three/overlays.ts b/apps/ai-lab/src/three/overlays.ts new file mode 100644 index 0000000..762f67c --- /dev/null +++ b/apps/ai-lab/src/three/overlays.ts @@ -0,0 +1,182 @@ +/** + * What is drawn over the map for one moment, rebuilt every update: goal, target and look lines, + * the gun's view cone, recent shots and hits, deaths so far, and the capture zones. + */ +import type { TraceBattle } from '@wto/ground-sim'; +import { + AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Group, LineBasicMaterial, + LineSegments, Mesh, MeshBasicMaterial, Points, PointsMaterial, +} from 'three'; +import { eventsBetween, type SceneAt, type UnitAt } from '../frames.ts'; +import { DEG } from './coords.ts'; +import { ARMY_HEX, type TankPool } from './tanks.ts'; + +export interface Layers { + readonly goals: boolean; + readonly links: boolean; + readonly cones: boolean; + readonly labels: boolean; + readonly events: boolean; +} + +const GUN_FOV_HALF_DEG = 30; +const CONE_M = 120; +const CONE_STEPS = 12; +const EVENT_WINDOW_SEC = 2; +const CAP_STEPS = 64; +const WISH_M = 25; + +/** Line segments with per-vertex colour, refilled from scratch on every update. */ +class Lines { + readonly obj: LineSegments; + private pos: number[] = []; + private col: number[] = []; + + constructor(opacity: number, additive = false) { + const mat = new LineBasicMaterial({ vertexColors: true, transparent: true, opacity, depthTest: !additive }); + if (additive) mat.blending = AdditiveBlending; + this.obj = new LineSegments(new BufferGeometry(), mat); + this.obj.frustumCulled = false; + } + + add(ax: number, ay: number, az: number, bx: number, by: number, bz: number, c: Color): void { + this.pos.push(ax, ay, -az, bx, by, -bz); + this.col.push(c.r, c.g, c.b, c.r, c.g, c.b); + } + + flush(): void { + const g = this.obj.geometry; + g.setAttribute('position', new BufferAttribute(Float32Array.from(this.pos), 3)); + g.setAttribute('color', new BufferAttribute(Float32Array.from(this.col), 3)); + g.computeBoundingSphere(); + this.pos = []; + this.col = []; + } +} + +const C = { + goal: new Color(0x9aa4ad), target: new Color(0xff4646), targetLost: new Color(0x803030), + look: new Color(0xffa028), wish: new Color(0xffe14a), shot: new Color(0xffff78), dead1: new Color(ARMY_HEX[1]), + dead2: new Color(ARMY_HEX[2]), cap: new Color(0xdddddd), +}; + +export class Overlays { + readonly group = new Group(); + private readonly faint = new Lines(0.35); + private readonly bold = new Lines(0.9); + private readonly shots = new Lines(1, true); + private readonly cones: Mesh; + private readonly hits: Points; + + constructor(private readonly tanks: TankPool) { + this.cones = new Mesh(new BufferGeometry(), new MeshBasicMaterial({ + color: 0xffffc8, transparent: true, opacity: 0.08, side: DoubleSide, depthWrite: false, + })); + this.cones.frustumCulled = false; + this.hits = new Points(new BufferGeometry(), new PointsMaterial({ size: 6, sizeAttenuation: false, vertexColors: true })); + this.hits.frustumCulled = false; + this.group.add(this.faint.obj, this.bold.obj, this.shots.obj, this.cones, this.hits); + } + + /** Height where lines leave a vehicle: its turret top. */ + private eye(u: UnitAt): number { + return this.tanks.groundY(u.x, u.y, u.z) + (this.tanks.get(u.unit.eid)?.eyeY ?? 2); + } + + update(battle: TraceBattle, scene: SceneAt, layers: Layers): void { + const cone: number[] = []; + for (const u of scene.units.values()) this.botLines(u, scene, layers, cone); + if (layers.events) this.events(battle, scene); + this.deaths(battle, scene.t); + this.caps(scene); + const g = this.cones.geometry; + g.setAttribute('position', new BufferAttribute(Float32Array.from(cone), 3)); + this.faint.flush(); + this.bold.flush(); + this.shots.flush(); + } + + private botLines(u: UnitAt, scene: SceneAt, layers: Layers, cone: number[]): void { + const bot = u.bot; + if (bot === undefined || !u.unit.alive) return; + const y = this.eye(u); + if (layers.goals && bot.hasOrder) this.faint.add(u.x, y, u.z, bot.goalX, this.tanks.terrainY(bot.goalX, bot.goalZ) + 1, bot.goalZ, C.goal); + const wy = bot.wishYaw * DEG; + this.bold.add(u.x, y, u.z, u.x + Math.cos(wy) * WISH_M, y, u.z + Math.sin(wy) * WISH_M, C.wish); + if (layers.cones) { + for (let i = 0; i < CONE_STEPS; i++) { + const a = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * i) / CONE_STEPS) * DEG; + const b = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * (i + 1)) / CONE_STEPS) * DEG; + cone.push(u.x, y, -u.z, u.x + Math.cos(a) * CONE_M, y, -(u.z + Math.sin(a) * CONE_M), + u.x + Math.cos(b) * CONE_M, y, -(u.z + Math.sin(b) * CONE_M)); + } + } + if (!layers.links) return; + const target = scene.units.get(bot.target); + if (target !== undefined && bot.target !== '0') { + (bot.targetInSight ? this.bold : this.faint).add(u.x, y, u.z, target.x, this.eye(target), target.z, + bot.targetInSight ? C.target : C.targetLost); + } + const look = scene.units.get(bot.lookAt); + if (look !== undefined && bot.lookAt !== bot.target) this.bold.add(u.x, y, u.z, look.x, this.eye(look), look.z, C.look); + } + + private events(battle: TraceBattle, scene: SceneAt): void { + const pos: number[] = []; + const col: number[] = []; + const c = new Color(); + 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; + this.shots.add(from.x, this.eye(from), from.z, to.x, this.eye(to) - 1, to.z, c.copy(C.shot).multiplyScalar(fade)); + } else if (e.kind === 'HIT') { + const x = Number(e.fields['x']); + const z = Number(e.fields['z']); + pos.push(x, this.tanks.terrainY(x, z) + 1.5, -z); + c.set(e.fields['drop'] === '1' ? 0xff3c3c : 0xc8c8c8).multiplyScalar(fade); + col.push(c.r, c.g, c.b); + } + } + this.hits.geometry.setAttribute('position', new BufferAttribute(Float32Array.from(pos), 3)); + this.hits.geometry.setAttribute('color', new BufferAttribute(Float32Array.from(col), 3)); + } + + private deaths(battle: TraceBattle, t: number): void { + for (const e of eventsBetween(battle, battle.startT, t)) { + if (e.kind !== 'DEATH') continue; + const x = Number(e.fields['x']); + const z = Number(e.fields['z']); + const y = this.tanks.terrainY(x, z) + 0.5; + const c = e.fields['army'] === '1' ? C.dead1 : C.dead2; + this.faint.add(x - 4, y, z - 4, x + 4, y, z + 4, c); + this.faint.add(x - 4, y, z + 4, x + 4, y, z - 4, c); + } + } + + private caps(scene: SceneAt): void { + for (const cap of scene.caps) { + const c = new Color(ARMY_HEX[cap.owner] ?? C.cap.getHex()); + for (let i = 0; i < CAP_STEPS; i++) { + const a = (i / CAP_STEPS) * Math.PI * 2; + const b = ((i + 1) / CAP_STEPS) * Math.PI * 2; + const ax = cap.x + Math.cos(a) * cap.r; + const az = cap.z + Math.sin(a) * cap.r; + const bx = cap.x + Math.cos(b) * cap.r; + const bz = cap.z + Math.sin(b) * cap.r; + this.bold.add(ax, this.tanks.terrainY(ax, az) + 0.8, az, bx, this.tanks.terrainY(bx, bz) + 0.8, bz, c); + } + } + } + + dispose(): void { + this.group.traverse((o) => { + if (o instanceof Mesh || o instanceof LineSegments || o instanceof Points) { + o.geometry.dispose(); + (o.material as { dispose(): void }).dispose(); + } + }); + } +} diff --git a/apps/ai-lab/src/three/tanks.ts b/apps/ai-lab/src/three/tanks.ts new file mode 100644 index 0000000..93117dd --- /dev/null +++ b/apps/ai-lab/src/three/tanks.ts @@ -0,0 +1,141 @@ +/** + * Every vehicle as simple shapes: a hull box tilted by the hull's pitch and roll, a turret box + * turned to the gun's heading, and a barrel at the gun's pitch. Sizes come from the bot's vehicle + * class (players: light or medium). + */ +import { sceneHeightAt, type SceneTerrain } from '@wto/ground-sim'; +import { + BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshLambertMaterial, type Object3D, +} from 'three'; +import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js'; +import type { UnitAt } from '../frames.ts'; +import { DEG } from './coords.ts'; + +/** Length, width, hull height per vehicle class (medium, light, heavy, tank destroyer, SPAA). */ +const SIZES: readonly (readonly [number, number, number])[] = [ + [7, 3.4, 1.3], [6, 3, 1.1], [7.6, 3.6, 1.4], [7, 3.3, 1.2], [6.5, 3.1, 1.2], +]; + +export const ARMY_HEX: Readonly> = { 1: 0x4aa3ff, 2: 0xff5c5c }; +const DEAD = new Color(0x4a4a4a); +const SELECTED = new Color(0x6a5200); +const NONE = new Color(0); + +/** A trace height further than this from the terrain is kept (bridge, building, platform). */ +const OFF_GROUND_M = 1.5; + +export interface Tank { + readonly root: Group; + readonly turret: Group; + readonly barrel: Group; + readonly label: CSS2DObject; + readonly mats: MeshLambertMaterial[]; + /** Turret top above the hull origin, where lines and the gun camera start. */ + readonly eyeY: number; + readonly length: number; +} + +function sizeOf(u: UnitAt): readonly [number, number, number] { + const cls = u.bot?.vehicleClass ?? (u.unit.light ? 1 : 0); + return SIZES[cls] ?? SIZES[0] ?? [7, 3.4, 1.3]; +} + +function makeTank(u: UnitAt): Tank { + const [len, wid, hh] = sizeOf(u); + const hullMat = new MeshLambertMaterial(); + const turretMat = new MeshLambertMaterial(); + const root = new Group(); + root.rotation.order = 'YZX'; + const hull = new Mesh(new BoxGeometry(len, hh, wid), hullMat); + hull.position.y = hh / 2; + const turret = new Group(); + turret.position.set(-len * 0.05, hh, 0); + const tw = wid * 0.7; + const th = hh * 0.65; + const turretBox = new Mesh(new BoxGeometry(len * 0.48, th, tw), turretMat); + turretBox.position.y = th / 2; + const barrel = new Group(); + barrel.position.set(len * 0.2, th * 0.55, 0); + const tube = new Mesh(new CylinderGeometry(0.09, 0.11, len * 0.75, 8), turretMat); + tube.rotation.z = -Math.PI / 2; + tube.position.x = len * 0.375; + barrel.add(tube); + turret.add(turretBox, barrel); + root.add(hull, turret); + const div = document.createElement('div'); + div.className = 'tank-label'; + const label = new CSS2DObject(div); + label.position.y = hh + th + 2.5; + root.add(label); + for (const m of [hull, turretBox, tube]) m.userData['eid'] = u.unit.eid; + return { root, turret, barrel, label, mats: [hullMat, turretMat], eyeY: hh + th, length: len }; +} + +export class TankPool { + readonly group = new Group(); + private readonly tanks = new Map(); + + constructor(private readonly terrain: SceneTerrain | undefined) {} + + get(eid: string): Tank | undefined { + return this.tanks.get(eid); + } + + /** Meshes to pick with a ray. */ + pickables(): Object3D[] { + const out: Object3D[] = []; + for (const t of this.tanks.values()) if (t.root.visible) t.root.traverse((o) => { if (o instanceof Mesh) out.push(o); }); + return out; + } + + terrainY(x: number, z: number): number { + return this.terrain === undefined ? 0 : sceneHeightAt(this.terrain, x, z); + } + + /** Ground height for the vehicle: the terrain unless the trace puts it clearly above or below. */ + groundY(x: number, y: number, z: number): number { + if (this.terrain === undefined) return y; + const g = sceneHeightAt(this.terrain, x, z); + return Math.abs(y - g) <= OFF_GROUND_M ? g : y; + } + + update(units: ReadonlyMap, selected: string | undefined, labels: (u: UnitAt) => string | undefined): void { + for (const [eid, t] of this.tanks) if (!units.has(eid)) t.root.visible = false; + for (const u of units.values()) { + let t = this.tanks.get(u.unit.eid); + if (t === undefined) { + t = makeTank(u); + this.tanks.set(u.unit.eid, t); + this.group.add(t.root); + } + this.place(t, u, u.unit.eid === selected, labels(u)); + } + } + + private place(t: Tank, u: UnitAt, selected: boolean, label: string | undefined): void { + t.root.visible = true; + t.root.position.set(u.x, this.groundY(u.x, u.y, u.z), -u.z); + t.root.rotation.set(u.hullRoll * DEG, u.yaw * DEG, u.hullPitch * DEG); + const rel = ((((u.gunYaw - u.yaw) % 360) + 540) % 360) - 180; + t.turret.rotation.y = rel * DEG; + const hullSlope = u.hullPitch * Math.cos(rel * DEG) + u.hullRoll * Math.sin(rel * DEG); + t.barrel.rotation.z = (u.gunPitch - hullSlope) * DEG; + const base = u.unit.alive ? new Color(ARMY_HEX[u.unit.army] ?? 0xcccccc) : DEAD; + t.mats.forEach((m, i) => { + m.color.copy(base).multiplyScalar(i === 0 ? 1 : 0.8); + m.emissive.copy(selected ? SELECTED : NONE); + }); + t.label.visible = label !== undefined; + if (label !== undefined) t.label.element.textContent = label; + if (u.unit.human) t.label.element.classList.add('human'); + } + + dispose(): void { + for (const t of this.tanks.values()) { + t.root.traverse((o) => { if (o instanceof Mesh) o.geometry.dispose(); }); + for (const m of t.mats) m.dispose(); + t.label.element.remove(); + } + this.tanks.clear(); + } +} diff --git a/apps/ai-lab/src/view.ts b/apps/ai-lab/src/view.ts deleted file mode 100644 index 6bfe133..0000000 --- a/apps/ai-lab/src/view.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 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 }; -} diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index 503229f..9c55198 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -19,6 +19,7 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_follow_common [never_inline] def public wto_drive_announce_script_ready() @@ -72,15 +73,6 @@ def private wto_check_echo_watchdog(unitMissionName : string; var actor : Vehicl st.deadEchoSec = 0.0 return true -def public wto_pivot_drive_mode(spec : WtoVehicleSpec const&; frontClearM, rearClearM : float; preferNeutral : bool) : int - let openFront = frontClearM >= spec.halfLen + 3.5 - let neutralTurn = spec.canPivot && frontClearM >= spec.halfLen + 1.2 && rearClearM >= spec.halfLen + 1.0 - if neutralTurn && (preferNeutral || !openFront) - return WTO_DRIVE_PIVOT - if openFront - return WTO_DRIVE_CRUISE - return rearClearM >= spec.halfLen + WTO_AI_TERRAIN_MARGIN_M ? WTO_DRIVE_REVERSE : WTO_DRIVE_HALT - [never_inline] def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; fwd, left : float3; vFwd, omega : float; diff --git a/game-ai/ground/wto_ai_facing_common.das b/game-ai/ground/wto_ai_facing_common.das index 6df8aec..88aabc1 100644 --- a/game-ai/ground/wto_ai_facing_common.das +++ b/game-ai/ground/wto_ai_facing_common.das @@ -11,7 +11,6 @@ require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_follow_common -require %appGame.wtoai.wto_ai_drive_common def private wto_face_bound(spec : WtoVehicleSpec const&) : bool return spec.isTracked && (spec.role == WTO_ROLE_MEDIUM || spec.role == WTO_ROLE_HEAVY || spec.role == WTO_ROLE_TD) diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index b91406a..517de9d 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -1,6 +1,7 @@ -// Turret servo, active loaded-shell inspection, and ballistic aim solver. -// Main weapon firing goes exclusively through wto_fire_gate_try_shoot, secondary and coaxial -// weapons through wto_fire_aux_update. +// Fire control on the game's weapons: reads the primary weapon (shell, readiness, reload), samples +// the live barrel, drives the turret toward the direction wto_ai_fire_decide_common picks, and +// fires the main weapon only through wto_fire_gate_try_shoot, secondary and coaxial weapons +// through wto_fire_aux_update. options indenting = 2 options no_global_heap = true module wto_ai_fire_common shared @@ -19,12 +20,10 @@ 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 -require %appGame.wtoai.wto_ai_world_common -require %appGame.wtoai.wto_ai_estimate_common +require %appGame.wtoai.wto_ai_fire_decide_common require %appGame.wtoai.wto_ai_fire_gate_common require %appGame.wtoai.wto_ai_traverse_common require %appGame.wtoai.wto_ai_hull_aim_common -require %appGame.wtoai.wto_ai_turret_common require %appGame.wtoai.wto_ai_trigger_common require %appGame.wtoai.wto_ai_fire_aux_common require %appGame.wtoai.wto_ai_ammo_common @@ -214,18 +213,11 @@ def private wto_fire_sample_primary(unit : Unit const?; var state : WtoFireState state.barrelSight = barrelDir return true -def private wto_clear_aim_tracking(var fc : WtoFireState&) - fc.aimTargetEid = INVALID_ENTITY_ID - fc.aimDriftDegSec = 0.0 - fc.settleHoldSec = 0.0 - fc.lastAligned = false - fc.lastDenyReason = WTO_DENY_NO_TARGET - // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). [never_inline] def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) wto_set_hull_aim(unit, "", false, 0.0, 0.0, unit.unitTm[0], slot) - wto_clear_aim_tracking(slot.fire) + wto_fire_clear_aim_tracking(slot.fire) wto_trig_set_target(INVALID_ENTITY_ID, slot.trigger) var gm = as_gm(unit) if gm != null @@ -233,18 +225,6 @@ def private wto_yield_air_fire(var unit : Unit?; var slot : WtoBotSlot&) *gm |> set_ignore_stop_for_fire(true) set_unit_attack_type(unit, "attack_target") -[never_inline] -def private wto_fire_has_engagement(slot : WtoBotSlot const&) : bool - assume p = slot.perceive - let yielding = slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED - return p.hasClearLos && !!p.targetEid && !p.targetIsAir && !yielding && !wto_turret_prefers_threat(slot) - -def private wto_fire_wants_soft(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool - if !slot.perceive.hasClearLos || slot.perceive.targetIsAir - return false - let idx = wto_world_find_unit(world, slot.perceive.targetEid) - return idx >= 0 && (world.units[idx].isLightTag || world.units[idx].halfWid < 1.35) - [never_inline] def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&) @@ -262,20 +242,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN let hFwd = unit.unitTm[0] var wishWorldDir = hFwd var aimPt = muzzlePos - var distToTgt = 9999.0 let engage = wto_fire_has_engagement(slot) let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) - let target = engage ? slot.perceive.targetEid : INVALID_ENTITY_ID - wto_trig_set_target(target, slot.trigger) - var auxAimed = false - if engage - 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, distXZ, slot) - slot.turret.lookReason = WTO_LOOK_ENGAGE - else - wishWorldDir = wto_turret_look_dir(now, muzzlePos, unit.pos, hFwd, slot) - slot.turret.wishDir = wishWorldDir + let distToTgt = wto_fire_decide_aim(now, engage, muzzlePos, unit.pos, unit.vel, hFwd, slot, aimPt, wishWorldDir) + let auxAimed = engage && wto_fire_aux_aim(unit, className, distXZ, slot) var wishYaw = 0.0 var wishPitch = 0.0 wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) @@ -288,8 +258,6 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; classN if canEngage wto_fire_gate_try_shoot(world, unit, className, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget) else - wto_clear_aim_tracking(slot.fire) - slot.trigger.wantSpeedMps = 99.0 - slot.trigger.wantSpeedAt = -100.0 + wto_fire_hold(slot) if engage wto_fire_aux_update(world, unit, className, now, distXZ, slot, fireBudget) diff --git a/game-ai/ground/wto_ai_fire_decide_common.das b/game-ai/ground/wto_ai_fire_decide_common.das new file mode 100644 index 0000000..17ecda6 --- /dev/null +++ b/game-ai/ground/wto_ai_fire_decide_common.das @@ -0,0 +1,61 @@ +// Fire control decisions, free of weapons and turret objects so the simulator runs them as they +// are: whether the bot engages its perceived target, whether it wants a soft shell, and where +// the turret should look. wto_ai_fire_common reads the weapons and drives the turret around them. +options indenting = 2 +options no_global_heap = true +module wto_ai_fire_decide_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 +require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_estimate_common +require %appGame.wtoai.wto_ai_turret_common +require %appGame.wtoai.wto_ai_trigger_common + +[never_inline] +def public wto_fire_has_engagement(slot : WtoBotSlot const&) : bool + assume p = slot.perceive + let yielding = slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED + return p.hasClearLos && !!p.targetEid && !p.targetIsAir && !yielding && !wto_turret_prefers_threat(slot) + +def public wto_fire_wants_soft(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool + if !slot.perceive.hasClearLos || slot.perceive.targetIsAir + return false + let idx = wto_world_find_unit(world, slot.perceive.targetEid) + return idx >= 0 && (world.units[idx].isLightTag || world.units[idx].halfWid < 1.35) + +def public wto_fire_clear_aim_tracking(var fc : WtoFireState&) + fc.aimTargetEid = INVALID_ENTITY_ID + fc.aimDriftDegSec = 0.0 + fc.settleHoldSec = 0.0 + fc.lastAligned = false + fc.lastDenyReason = WTO_DENY_NO_TARGET + +// No shot this frame: forget the aim tracking and lift the trigger's speed request. +def public wto_fire_hold(var slot : WtoBotSlot&) + wto_fire_clear_aim_tracking(slot.fire) + slot.trigger.wantSpeedMps = 99.0 + slot.trigger.wantSpeedAt = -100.0 + +// Hands the trigger its target and returns the world direction the turret should point: the +// ballistic solution on the engaged target, or the turret channel's look direction. Writes the +// aim point and returns the distance to the target (9999 when not engaging). +[never_inline] +def public wto_fire_decide_aim(now : float; engage : bool; muzzlePos, unitPos, unitVel, hullFwd : float3; + var slot : WtoBotSlot&; var aimPt, wishDir : float3&) : float + wto_trig_set_target(engage ? slot.perceive.targetEid : INVALID_ENTITY_ID, slot.trigger) + var distToTgt = 9999.0 + aimPt = muzzlePos + if engage + assume fc = slot.fire + distToTgt = wto_solve_ballistic_aim(muzzlePos, unitVel, slot.perceive.visibleAimPt, fc.activeSpeedMps, fc.activeDragCx, + fc.activeMassKg, fc.activeCaliberM, slot, aimPt, wishDir) + slot.turret.lookReason = WTO_LOOK_ENGAGE + else + wishDir = wto_turret_look_dir(now, muzzlePos, unitPos, hullFwd, slot) + slot.turret.wishDir = wishDir + return distToTgt diff --git a/game-ai/ground/wto_ai_follow_common.das b/game-ai/ground/wto_ai_follow_common.das index 3d75722..a3eceef 100644 --- a/game-ai/ground/wto_ai_follow_common.das +++ b/game-ai/ground/wto_ai_follow_common.das @@ -12,6 +12,17 @@ require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_polyline_common +// Drive mode for turning in place or getting out: pivot when both ends have room, cruise when +// the front is open, reverse when only the rear is, halt otherwise. +def public wto_pivot_drive_mode(spec : WtoVehicleSpec const&; frontClearM, rearClearM : float; preferNeutral : bool) : int + let openFront = frontClearM >= spec.halfLen + 3.5 + let neutralTurn = spec.canPivot && frontClearM >= spec.halfLen + 1.2 && rearClearM >= spec.halfLen + 1.0 + if neutralTurn && (preferNeutral || !openFront) + return WTO_DRIVE_PIVOT + if openFront + return WTO_DRIVE_CRUISE + return rearClearM >= spec.halfLen + WTO_AI_TERRAIN_MARGIN_M ? WTO_DRIVE_REVERSE : WTO_DRIVE_HALT + [never_inline] def public wto_drive_cmd_set(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3; speedMps, frontClr, rearClr : float) diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index 82b4e99..569a85b 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -15,7 +15,6 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common -require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_navquery_common require %appGame.wtoai.wto_ai_navmesh_common diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index 7fcefd5..9736d4d 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -27,6 +27,7 @@ require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common require %appGame.wtoai.wto_ai_specs_common require %appGame.wtoai.wto_ai_world_common +require %appGame.wtoai.wto_ai_world_refresh_common require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_lanes_common require %appGame.wtoai.wto_ai_lanes_build_common @@ -151,7 +152,7 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct) if !g_world.valid wto_drive_announce_script_ready() print("WTO_AI|RUNTIME_READY\n") - wto_world_refresh(now, g_world) + wto_world_refresh(now, wto_trace_is_due(now, g_next_trace_at), g_world) if WTO_AI_LAYER_NAVIGATION wto_navmesh_battle_tick(g_world, now, g_navmesh) g_lanes.navState = g_navmesh.state diff --git a/game-ai/ground/wto_ai_trace_common.das b/game-ai/ground/wto_ai_trace_common.das index c6bfb2c..7e5ddee 100644 --- a/game-ai/ground/wto_ai_trace_common.das +++ b/game-ai/ground/wto_ai_trace_common.das @@ -1,6 +1,7 @@ // 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_U every ground unit, bots and players alike (position, hull attitude, gun +// direction, 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. @@ -31,12 +32,19 @@ def private wto_tr_is_bot(bots : WtoBotSlot[64] const&; eid : EntityId) : int return 1 return 0 +def private wto_tr_pitch(dir : float3) : int + return int(floor(asin(clamp(dir.y, -1.0, 1.0)) * WTO_RAD_TO_DEG + 0.5)) + +// The world refresh reads every gun on the frames this returns true. +def public wto_trace_is_due(now, nextAt : float) : bool + return WTO_AI_TRACE_ENABLED && now >= nextAt + // 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 + if !wto_trace_is_due(now, nextAt) return false nextAt = now + WTO_AI_TRACE_SEC for c in range(world.capCount) @@ -47,7 +55,11 @@ def public wto_trace_tick(world : WtoWorldSnap const&; now : float; bots : WtoBo 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") + // hp: hull pitch, nose up positive; hr: roll, left side up positive; gy, gp: gun world yaw + // and pitch, 9999 when the gun was not read. + let gy = u.hasGun ? wto_tr_yaw(u.gunDir) : 9999 + let gp = u.hasGun ? wto_tr_pitch(u.gunDir) : 9999 + 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)}|hp={wto_tr_pitch(u.hullFwd3)}|hr={wto_tr_pitch(u.hullLeft)}|gy={gy}|gp={gp}\n") return true def private wto_tr_threat_eid(slot : WtoBotSlot const&; idx : int) : uint diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index 4122da4..893614d 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -82,6 +82,10 @@ struct public WtoUnitSnap pos : float3 = float3(0.0, 0.0, 0.0) vel : float3 = float3(0.0, 0.0, 0.0) hullFwd : float3 = float3(1.0, 0.0, 0.0) + hullFwd3 : float3 = float3(1.0, 0.0, 0.0) + hullLeft : float3 = float3(0.0, 0.0, 1.0) + gunDir : float3 = float3(0.0, 0.0, 0.0) + hasGun : bool = false halfLen : float = 3.4 halfWid : float = 1.75 engineRpm : float = 0.0 diff --git a/game-ai/ground/wto_ai_unit_pose_common.das b/game-ai/ground/wto_ai_unit_pose_common.das new file mode 100644 index 0000000..1e96a7d --- /dev/null +++ b/game-ai/ground/wto_ai_unit_pose_common.das @@ -0,0 +1,30 @@ +// Live main-gun direction of any unit, bots and players alike, for the replay trace. +options indenting = 2 +options no_global_heap = true +module wto_ai_unit_pose_common shared + +require ecs +require math +require DagorMath +require Unit +require Weapon +require %game.utils.utils_common +require %appGame.wtoai.wto_ai_math_common + +// World direction of the first real primary weapon's barrel; false when the unit has none. +[never_inline] +def public wto_pose_gun_dir(unit : Unit const?; var outDir : float3&) : bool + if unit == null || unit.weap == null + return false + var sampled = false + get_weapons_by_trigger_group(unit.weap.Weapons, WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) <| $(weapons : array const#) + for weapon in weapons + if weapon == null || weapon.isDummyGun + continue + var gunTm : float3x4 + weapon_calcShootTm(weapon, unit.unitTm, gunTm) + if wto_is_finite3(gunTm[0]) && length_sq(gunTm[0]) > 0.25 + outDir = normalize(gunTm[0]) + sampled = true + return + return sampled diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das index 05ce8b8..dd9cce7 100644 --- a/game-ai/ground/wto_ai_world_common.das +++ b/game-ai/ground/wto_ai_world_common.das @@ -1,19 +1,17 @@ -// World observation layer: builds one flat per-frame snapshot of units, wrecks, -// capture zones, respawn anchors, and ring buffers for deaths, jams, and radio spots. +// World observation layer: one flat per-frame snapshot of units, wrecks, capture zones, respawn +// anchors, and ring buffers for deaths, jams, and radio spots. Filling it from the game is +// wto_ai_world_refresh_common's job; this module only keeps and queries it, so the simulator +// loads it unchanged. options indenting = 2 options no_global_heap = true module wto_ai_world_common shared require ecs require math -require DagorMath -require Unit -require IGroundModel -require HeavyVehicleModel require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_order_common require %appGame.wtoai.wto_ai_types_common -require %appGame.wtoai.wto_ai_world_zones_common + [never_inline] def public wto_world_reset(var snap : WtoWorldSnap&) @@ -120,79 +118,3 @@ def public wto_world_find_unit(snap : WtoWorldSnap const&; eid : EntityId) : int if snap.units[i].eid == eid return i return -1 - -[never_inline] -def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : Unit const?; gm : IGroundModel const?) - if gm == null || snap.wreckCount >= WTO_MAX_WRECKS - return - let box = gm.bodyBoundingBox - let wIdx = snap.wreckCount - snap.wrecks[wIdx].eid = eid - snap.wrecks[wIdx].pos = u.pos - snap.wrecks[wIdx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) - snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x))) - snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z))) - snap.wreckCount = wIdx + 1 - -[never_inline] -def private wto_refresh_units(var snap : WtoWorldSnap&) - snap.unitCount = 0 - snap.wreckCount = 0 - let maxDistSq = wto_sq(max(snap.battleRadius * 2.5, 2200.0)) - query() <| $ [es] (eid : EntityId; unit__ref : UnitRef) - let u = unit__ref.unit - if u == null || u.isDelayed - return - let gm = as_gm(u) - if snap.battleRadius > 1.0 && gm != null && wto_xz_dist_sq(u.pos, snap.battleCenter) > maxDistSq - return - if !u.isAlive - wto_record_wreck_once(snap, eid, u, gm) - return - if snap.unitCount >= WTO_MAX_UNITS - return - let army = int(u.army) - if army != 1 && army != 2 - return - let isGround = gm != null && as_hv(u) != null - let isAir = u.isFlightModelWrap - if !isGround && !isAir - return - var halfLen = 3.4 - var halfWid = 1.75 - if gm != null - let box = gm.bodyBoundingBox - halfLen = max(1.8, max(abs(box.boxMin.x), abs(box.boxMax.x))) - halfWid = max(0.9, max(abs(box.boxMin.z), abs(box.boxMax.z))) - let idx = snap.unitCount - snap.units[idx].eid = eid - snap.units[idx].army = army - snap.units[idx].pos = u.pos - snap.units[idx].vel = u.vel - snap.units[idx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) - snap.units[idx].halfLen = halfLen - snap.units[idx].halfWid = halfWid - snap.units[idx].engineRpm = gm != null ? clamp(abs(gm.engineRelativeRPM), 0.0, 1.2) : 0.0 - snap.units[idx].isAlive = true - snap.units[idx].isGround = isGround - snap.units[idx].isAir = isAir - snap.units[idx].isLightTag = false - snap.units[idx].isShooting = gm != null && (gm.isShooting || gm.hasMissilesInFlight) - snap.units[idx].isBurn = u.isBurn - snap.units[idx].isHuman = u.isHumanPlayer - snap.unitCount = idx + 1 - for i in range(snap.unitCount) - if snap.units[i].isGround - snap.units[i].isLightTag = has(snap.units[i].eid, "unit_tag__light_vehicle") - -[never_inline] -def public wto_world_refresh(now : float; var snap : WtoWorldSnap&) - snap.time = now - if snap.matchStartAt < -50.0 - snap.matchStartAt = now - wto_refresh_units(snap) - if now >= snap.nextCapRefreshAt - snap.nextCapRefreshAt = now + 0.5 - wto_world_refresh_caps(snap) - wto_world_refresh_bounds_and_spawns(snap) - snap.valid = true diff --git a/game-ai/ground/wto_ai_world_refresh_common.das b/game-ai/ground/wto_ai_world_refresh_common.das new file mode 100644 index 0000000..6a2b00b --- /dev/null +++ b/game-ai/ground/wto_ai_world_refresh_common.das @@ -0,0 +1,100 @@ +// Fills the world snapshot from the game's units every frame: live units with their pose (and +// the gun on trace frames), wrecks, capture zones, battle bounds and spawns. Only the runtime +// uses it; the simulator fills the same snapshot from its own world. +options indenting = 2 +options no_global_heap = true +module wto_ai_world_refresh_common shared + +require ecs +require math +require DagorMath +require Unit +require IGroundModel +require HeavyVehicleModel +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_zones_common +require %appGame.wtoai.wto_ai_unit_pose_common + +[never_inline] +def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : Unit const?; gm : IGroundModel const?) + if gm == null || snap.wreckCount >= WTO_MAX_WRECKS + return + let box = gm.bodyBoundingBox + let wIdx = snap.wreckCount + snap.wrecks[wIdx].eid = eid + snap.wrecks[wIdx].pos = u.pos + snap.wrecks[wIdx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) + snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x))) + snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z))) + snap.wreckCount = wIdx + 1 + +// Pose of a live unit; the gun is read only on trace frames. +def private wto_unit_pose(var su : WtoUnitSnap&; u : Unit const?; sampleGun : bool) + su.pos = u.pos + su.vel = u.vel + su.hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0)) + su.hullFwd3 = u.unitTm[0] + su.hullLeft = u.unitTm[2] + su.hasGun = sampleGun && wto_pose_gun_dir(u, su.gunDir) + +[never_inline] +def private wto_refresh_units(var snap : WtoWorldSnap&; sampleGuns : bool) + snap.unitCount = 0 + snap.wreckCount = 0 + let maxDistSq = wto_sq(max(snap.battleRadius * 2.5, 2200.0)) + query() <| $ [es] (eid : EntityId; unit__ref : UnitRef) + let u = unit__ref.unit + if u == null || u.isDelayed + return + let gm = as_gm(u) + if snap.battleRadius > 1.0 && gm != null && wto_xz_dist_sq(u.pos, snap.battleCenter) > maxDistSq + return + if !u.isAlive + wto_record_wreck_once(snap, eid, u, gm) + return + if snap.unitCount >= WTO_MAX_UNITS + return + let army = int(u.army) + if army != 1 && army != 2 + return + let isGround = gm != null && as_hv(u) != null + let isAir = u.isFlightModelWrap + if !isGround && !isAir + return + var halfLen = 3.4 + var halfWid = 1.75 + if gm != null + let box = gm.bodyBoundingBox + halfLen = max(1.8, max(abs(box.boxMin.x), abs(box.boxMax.x))) + halfWid = max(0.9, max(abs(box.boxMin.z), abs(box.boxMax.z))) + let idx = snap.unitCount + snap.units[idx].eid = eid + snap.units[idx].army = army + wto_unit_pose(snap.units[idx], u, sampleGuns && isGround) + snap.units[idx].halfLen = halfLen + snap.units[idx].halfWid = halfWid + snap.units[idx].engineRpm = gm != null ? clamp(abs(gm.engineRelativeRPM), 0.0, 1.2) : 0.0 + snap.units[idx].isAlive = true + snap.units[idx].isGround = isGround + snap.units[idx].isAir = isAir + snap.units[idx].isLightTag = false + snap.units[idx].isShooting = gm != null && (gm.isShooting || gm.hasMissilesInFlight) + snap.units[idx].isBurn = u.isBurn + snap.units[idx].isHuman = u.isHumanPlayer + snap.unitCount = idx + 1 + for i in range(snap.unitCount) + if snap.units[i].isGround + snap.units[i].isLightTag = has(snap.units[i].eid, "unit_tag__light_vehicle") + +[never_inline] +def public wto_world_refresh(now : float; sampleGuns : bool; var snap : WtoWorldSnap&) + snap.time = now + if snap.matchStartAt < -50.0 + snap.matchStartAt = now + wto_refresh_units(snap, sampleGuns) + if now >= snap.nextCapRefreshAt + snap.nextCapRefreshAt = now + 0.5 + wto_world_refresh_caps(snap) + wto_world_refresh_bounds_and_spawns(snap) + snap.valid = true diff --git a/native/wto-ai-sim/build.ps1 b/native/wto-ai-sim/build.ps1 new file mode 100644 index 0000000..ff208fc --- /dev/null +++ b/native/wto-ai-sim/build.ps1 @@ -0,0 +1,58 @@ +<# + Build the ground AI simulator's runtime: the open-source daScript interpreter (daslang.exe) at a + pinned commit, with this project's native module `wto_sim` (native\wto-ai-sim\module). + + powershell -NoProfile -ExecutionPolicy Bypass -File native\wto-ai-sim\build.ps1 + + The daScript checkout goes to build\daslang (cloned when missing, about 420 MB), the build to + build\daslang-build. Neither is part of the repository. The module folder is linked into the + checkout as modules\wtoSim, so the daScript build compiles it with its own module rules and + daslang loads it at start. Needs Visual Studio with the x64 C++ tools; CMake and Ninja are the + ones Visual Studio bundles. +#> +param( + [string]$DasRoot = (Join-Path $PSScriptRoot '..\..\build\daslang'), + [string]$BuildDir = (Join-Path $PSScriptRoot '..\..\build\daslang-build') +) +$ErrorActionPreference = 'Stop' + +# daScript 0.6.6, the version the simulator was verified with (docs: tank-ai-revision-plan 3.3.1). +$pin = '7a51c4ef9927dbc92ecf4cab67ae41b41d239f4a' +$repo = 'https://github.com/GaijinEntertainment/daScript.git' + +if (-not (Test-Path (Join-Path $DasRoot '.git'))) { + git clone --no-checkout $repo $DasRoot + if ($LASTEXITCODE -ne 0) { throw 'git clone of daScript failed' } +} +$head = (git -C $DasRoot rev-parse HEAD 2>$null) +if ($head -ne $pin) { + git -C $DasRoot fetch origin $pin + git -C $DasRoot checkout --detach $pin + if ($LASTEXITCODE -ne 0) { throw "checkout of daScript $pin failed" } +} + +$moduleLink = Join-Path $DasRoot 'modules\wtoSim' +if (-not (Test-Path $moduleLink)) { + New-Item -ItemType Junction -Path $moduleLink -Target (Join-Path $PSScriptRoot 'module') | Out-Null +} + +$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' +$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +if (-not $vs) { throw 'Visual Studio with the x64 C++ tools was not found' } +$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' +$cmakeDir = Join-Path $vs 'Common7\IDE\CommonExtensions\Microsoft\CMake' +$cmake = Join-Path $cmakeDir 'CMake\bin\cmake.exe' +$ninja = Join-Path $cmakeDir 'Ninja\ninja.exe' + +# Only the interpreter and the core runtime; every optional module of daScript stays off. +$off = @('ACCELERATE', 'AOT_EXAMPLES', 'AUDIO', 'CLANG_BIND', 'CLIPBOARD', 'CRYPTO', 'CUDA', 'FLEX_BISON', 'GLFW', 'HV', + 'IMGUI', 'LLVM', 'MESHOPTIMIZER', 'METAL', 'PUGIXML', 'SMT', 'SQLITE', 'STBIMAGE', 'STDDLG', 'TERMINAL', 'TESTS', + 'TREE_SITTER', 'TUTORIAL', 'VULKAN') | ForEach-Object { "-DDAS_$($_)_DISABLED=ON" } +$native = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path -replace '\\', '/' +$configure = "`"$cmake`" -S `"$DasRoot`" -B `"$BuildDir`" -G Ninja -DCMAKE_MAKE_PROGRAM=`"$ninja`" " + + "-DCMAKE_BUILD_TYPE=Release -DDAS_TOOLS_DISABLED=OFF -DWTO_SIM_NATIVE_ROOT=`"$native`" $($off -join ' ')" +cmd /c "`"$vcvars`" >nul && $configure" +if ($LASTEXITCODE -ne 0) { throw "cmake configure failed with $LASTEXITCODE" } +cmd /c "`"$vcvars`" >nul && `"$cmake`" --build `"$BuildDir`" --target daslang dasModuleWtoSim" +if ($LASTEXITCODE -ne 0) { throw "cmake build failed with $LASTEXITCODE" } +Write-Output (Join-Path $DasRoot 'bin\daslang.exe') diff --git a/native/wto-ai-sim/module/.das_module b/native/wto-ai-sim/module/.das_module new file mode 100644 index 0000000..e3cac50 --- /dev/null +++ b/native/wto-ai-sim/module/.das_module @@ -0,0 +1,9 @@ +options gen2 +require daslib/fio + +[export] +def initialize(project_path : string) { + if (das_is_dll_build()) { + register_dynamic_module("{project_path}/dasModuleWtoSim.shared_module", "Module_WtoSim") + } +} diff --git a/native/wto-ai-sim/module/.gitignore b/native/wto-ai-sim/module/.gitignore new file mode 100644 index 0000000..b642b90 --- /dev/null +++ b/native/wto-ai-sim/module/.gitignore @@ -0,0 +1,6 @@ +# The daScript build writes the shared module next to its sources. +*.shared_module +*.pdb +*.lib +*.exp +*.ilk diff --git a/native/wto-ai-sim/module/CMakeLists.txt b/native/wto-ai-sim/module/CMakeLists.txt new file mode 100644 index 0000000..37e31f2 --- /dev/null +++ b/native/wto-ai-sim/module/CMakeLists.txt @@ -0,0 +1,49 @@ +# Ground AI simulator module `wto_sim` for the open-source daScript build. native/wto-ai-sim/build.ps1 +# links this folder into the daScript checkout as modules/wtoSim, so its build includes it like its +# own modules and daslang loads the shared module at start (.das_module). +IF ((NOT DAS_WTOSIM_INCLUDED) AND ((NOT ${DAS_WTOSIM_DISABLED}) OR (NOT DEFINED DAS_WTOSIM_DISABLED))) + SET(DAS_WTOSIM_INCLUDED TRUE) + MESSAGE(STATUS "wtoSim module included.") + + # The project's native folder: given by build.ps1, else found through the link. + IF(DEFINED WTO_SIM_NATIVE_ROOT) + SET(WTO_SIM_NATIVE ${WTO_SIM_NATIVE_ROOT}) + ELSE() + FILE(REAL_PATH "${CMAKE_CURRENT_LIST_DIR}" _wto_sim_here) + GET_FILENAME_COMPONENT(WTO_SIM_NATIVE "${_wto_sim_here}/../.." ABSOLUTE) + ENDIF() + SET(WTO_SIM_DIR ${CMAKE_CURRENT_LIST_DIR}) + SET(WTO_SIM_NAV_DIR ${WTO_SIM_NATIVE}/wto-nav) + SET(WTO_SIM_DETOUR_DIR ${WTO_SIM_NATIVE}/third_party/recastnavigation/Detour) + + # The game's navigation engine and request protocol with upstream Detour, at their own warning level. + FILE(GLOB WTO_SIM_DETOUR_SRC ${WTO_SIM_DETOUR_DIR}/Source/*.cpp) + ADD_LIBRARY(wtoSimNav STATIC + ${WTO_SIM_DETOUR_SRC} + ${WTO_SIM_NAV_DIR}/wto_nav_runtime.cpp + ${WTO_SIM_NAV_DIR}/wto_nav_paths.cpp + ${WTO_SIM_NAV_DIR}/wto_nav_queries.cpp + ${WTO_SIM_NAV_DIR}/wto_nav_protocol.c + ) + TARGET_INCLUDE_DIRECTORIES(wtoSimNav PUBLIC + $ $) + # Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp). + TARGET_COMPILE_DEFINITIONS(wtoSimNav PUBLIC DT_VIRTUAL_QUERYFILTER PRIVATE _CRT_SECURE_NO_WARNINGS WIN32_LEAN_AND_MEAN) + SET_TARGET_PROPERTIES(wtoSimNav PROPERTIES POSITION_INDEPENDENT_CODE ON) + # The module's static library is in daScript's export set, so what it links must be too. + INSTALL(TARGETS wtoSimNav EXPORT DASTargets ARCHIVE DESTINATION ${DAS_INSTALL_LIBDIR}) + + SET(WTO_SIM_MODULE_SRC + ${WTO_SIM_DIR}/src/wto_sim_module.cpp + ${WTO_SIM_DIR}/src/sim_geo.cpp + ${WTO_SIM_DIR}/src/sim_geo.h + ${WTO_SIM_DIR}/src/sim_nav.cpp + ${WTO_SIM_DIR}/src/sim_nav.h + ) + ADD_MODULE_CPP(WtoSim) + ADD_MODULE_LIB(libDasModuleWtoSim dasModuleWtoSim ${WTO_SIM_MODULE_SRC}) + TARGET_LINK_LIBRARIES(libDasModuleWtoSim PUBLIC wtoSimNav) + TARGET_LINK_LIBRARIES(dasModuleWtoSim PUBLIC wtoSimNav) + SETUP_CPP11(libDasModuleWtoSim) + SETUP_CPP11(dasModuleWtoSim) +ENDIF() diff --git a/native/wto-ai-sim/module/src/sim_geo.cpp b/native/wto-ai-sim/module/src/sim_geo.cpp new file mode 100644 index 0000000..d56b033 --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_geo.cpp @@ -0,0 +1,443 @@ +// Terrain and object geometry of the simulated level (see sim_geo.h). Objects are indexed on an +// 8 m grid in XZ, with each cell's highest triangle and highest ground; a ray walks the cells it +// crosses, tests their triangles and marches the terrain only where it dips low enough. +#include "sim_geo.h" + +#include +#include +#include +#include +#include + +namespace wto_sim { + +namespace { + +const char GEO_MAGIC[8] = { 'W', 'T', 'O', 'G', 'E', 'O', '\0', '\x01' }; +const uint32_t GEO_MAX_VERSION = 3; +const float CELL_M = 8.0f; +const float BURIED_M = 0.3f; + +#pragma pack(push, 1) +struct GeoHeader { + char magic[8]; + uint32_t version; + uint32_t flags; + uint8_t everSha1[20]; + float waterLevel; + float boundsMin[2]; + float boundsMax[2]; + uint32_t hmWidth; + uint32_t hmHeight; + float hmCellSize; + float hmOrigin[2]; + uint32_t obsVertCount; + uint32_t obsTriCount; +}; +#pragma pack(pop) + +// One triangle ready for the ray test: a corner, two edges, and the group it belongs to. +struct Tri { + float v0[3]; + float e1[3]; + float e2[3]; + int kind; +}; + +// Obstacle class (WtoObstacleClass) to ray group. +const int KIND_OF_CLASS[8] = { RAY_HARD, RAY_BRIDGE, RAY_CRUSHABLE, RAY_TREE, RAY_TREE, RAY_HARD, RAY_PLATFORM, RAY_PLATFORM }; + +struct Geo { + bool loaded = false; + float water = -1.0e6f; + uint32_t hmW = 0; + uint32_t hmH = 0; + float hmCell = 1.0f; + float hmOrigin[2] = { 0.0f, 0.0f }; + std::vector heights; + std::vector tris; + // Grid over the objects: cell (c, r) holds items[offsets[i] .. offsets[i + 1]). + float gridOrigin[2] = { 0.0f, 0.0f }; + int gridCols = 0; + int gridRows = 0; + std::vector offsets; + std::vector items; + std::vector cellTop; + // Highest terrain sample in each cell (with its border), so a ray above it skips the march. + std::vector cellGround; + // Ray id stamped on each triangle already tested by the current ray. + std::vector stamp; + uint32_t rayId = 0; +}; + +Geo g_geo; + +float height_at(const Geo & g, float x, float z) +{ + if (g.hmW < 2 || g.hmH < 2) + return 0.0f; + const float fx = std::min(float(g.hmW) - 1.001f, std::max(0.0f, (x - g.hmOrigin[0]) / g.hmCell)); + const float fz = std::min(float(g.hmH) - 1.001f, std::max(0.0f, (z - g.hmOrigin[1]) / g.hmCell)); + const uint32_t x0 = uint32_t(fx); + const uint32_t z0 = uint32_t(fz); + const float tx = fx - float(x0); + const float tz = fz - float(z0); + const float * row0 = &g.heights[size_t(z0) * g.hmW + x0]; + const float * row1 = row0 + g.hmW; + const float a = row0[0] + (row0[1] - row0[0]) * tx; + const float b = row1[0] + (row1[1] - row1[0]) * tx; + return a + (b - a) * tz; +} + +void sub(const float a[3], const float b[3], float out[3]) +{ + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; +} + +void cross(const float a[3], const float b[3], float out[3]) +{ + out[0] = a[1] * b[2] - a[2] * b[1]; + out[1] = a[2] * b[0] - a[0] * b[2]; + out[2] = a[0] * b[1] - a[1] * b[0]; +} + +float dot(const float a[3], const float b[3]) +{ + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} + +bool read_bytes(std::ifstream & in, void * out, size_t size) +{ + in.read(static_cast(out), std::streamsize(size)); + return bool(in); +} + +bool buried(const Geo & g, const float * v) +{ + return v[1] < height_at(g, v[0], v[2]) - BURIED_M; +} + +// Keeps the triangles that are not wholly under the terrain, as ready-to-test records. +void keep_triangles(Geo & g, const std::vector & verts, const std::vector & raw, uint32_t count) +{ + g.tris.clear(); + g.tris.reserve(count); + const uint32_t vertCount = uint32_t(verts.size() / 3); + for (uint32_t i = 0; i < count; i++) { + const uint8_t * rec = &raw[size_t(i) * 13]; + uint32_t idx[3]; + std::memcpy(idx, rec, sizeof(idx)); + if (idx[0] >= vertCount || idx[1] >= vertCount || idx[2] >= vertCount) + continue; + const float * a = &verts[size_t(idx[0]) * 3]; + const float * b = &verts[size_t(idx[1]) * 3]; + const float * c = &verts[size_t(idx[2]) * 3]; + if (buried(g, a) && buried(g, b) && buried(g, c)) + continue; + Tri t; + std::memcpy(t.v0, a, sizeof(t.v0)); + sub(b, a, t.e1); + sub(c, a, t.e2); + t.kind = KIND_OF_CLASS[rec[12] & 7]; + g.tris.push_back(t); + } +} + +void tri_bounds(const Tri & t, float lo[3], float hi[3]) +{ + for (int k = 0; k < 3; k++) { + const float b = t.v0[k] + t.e1[k]; + const float c = t.v0[k] + t.e2[k]; + lo[k] = std::min(t.v0[k], std::min(b, c)); + hi[k] = std::max(t.v0[k], std::max(b, c)); + } +} + +void cell_span(const Geo & g, const float lo[3], const float hi[3], int & c0, int & c1, int & r0, int & r1) +{ + c0 = std::clamp(int(std::floor((lo[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1); + c1 = std::clamp(int(std::floor((hi[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1); + r0 = std::clamp(int(std::floor((lo[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1); + r1 = std::clamp(int(std::floor((hi[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1); +} + +// Two passes over the triangles: count per cell, then fill the cells' item lists. +void build_grid(Geo & g, const float boundsMin[2], const float boundsMax[2]) +{ + g.gridOrigin[0] = boundsMin[0]; + g.gridOrigin[1] = boundsMin[1]; + g.gridCols = std::max(1, int(std::ceil((boundsMax[0] - boundsMin[0]) / CELL_M))); + g.gridRows = std::max(1, int(std::ceil((boundsMax[1] - boundsMin[1]) / CELL_M))); + const size_t cells = size_t(g.gridCols) * size_t(g.gridRows); + std::vector counts(cells, 0); + g.cellTop.assign(cells, -1.0e9f); + float lo[3], hi[3]; + int c0, c1, r0, r1; + for (const Tri & t : g.tris) { + tri_bounds(t, lo, hi); + cell_span(g, lo, hi, c0, c1, r0, r1); + for (int r = r0; r <= r1; r++) { + for (int c = c0; c <= c1; c++) { + const size_t i = size_t(r) * g.gridCols + c; + counts[i]++; + g.cellTop[i] = std::max(g.cellTop[i], hi[1]); + } + } + } + g.offsets.assign(cells + 1, 0); + for (size_t i = 0; i < cells; i++) + g.offsets[i + 1] = g.offsets[i] + counts[i]; + g.items.assign(g.offsets[cells], 0); + std::fill(counts.begin(), counts.end(), 0); + for (uint32_t ti = 0; ti < uint32_t(g.tris.size()); ti++) { + tri_bounds(g.tris[ti], lo, hi); + cell_span(g, lo, hi, c0, c1, r0, r1); + for (int r = r0; r <= r1; r++) { + for (int c = c0; c <= c1; c++) { + const size_t i = size_t(r) * g.gridCols + c; + g.items[g.offsets[i] + counts[i]++] = ti; + } + } + } + g.stamp.assign(g.tris.size(), 0); + g.rayId = 0; +} + +void build_ground_tops(Geo & g) +{ + g.cellGround.assign(size_t(g.gridCols) * g.gridRows, -1.0e9f); + for (int r = 0; r < g.gridRows; r++) { + for (int c = 0; c < g.gridCols; c++) { + const float x0 = g.gridOrigin[0] + float(c) * CELL_M; + const float z0 = g.gridOrigin[1] + float(r) * CELL_M; + float top = -1.0e9f; + for (float z = z0 - g.hmCell; z <= z0 + CELL_M + g.hmCell; z += g.hmCell) + for (float x = x0 - g.hmCell; x <= x0 + CELL_M + g.hmCell; x += g.hmCell) + top = std::max(top, height_at(g, x, z)); + g.cellGround[size_t(r) * g.gridCols + c] = top; + } + } +} + +// Möller–Trumbore, both faces. Returns the distance along the ray, or -1. +float ray_tri(const Tri & t, const float p[3], const float dir[3]) +{ + float pv[3], tv[3], qv[3]; + cross(dir, t.e2, pv); + const float det = dot(t.e1, pv); + if (std::fabs(det) < 1.0e-9f) + return -1.0f; + const float inv = 1.0f / det; + sub(p, t.v0, tv); + const float u = dot(tv, pv) * inv; + if (u < 0.0f || u > 1.0f) + return -1.0f; + cross(tv, t.e1, qv); + const float v = dot(dir, qv) * inv; + if (v < 0.0f || u + v > 1.0f) + return -1.0f; + return dot(t.e2, qv) * inv; +} + +void tri_normal(const Tri & t, const float dir[3], float out[3]) +{ + cross(t.e1, t.e2, out); + const float len = std::sqrt(dot(out, out)); + const float s = (len > 0.0f ? 1.0f / len : 0.0f) * (dot(out, dir) > 0.0f ? -1.0f : 1.0f); + out[0] *= s; + out[1] *= s; + out[2] *= s; +} + +// Tests the cell's triangles of the selected groups; keeps the nearest hit within maxT. +void test_cell(Geo & g, size_t cell, const float p[3], const float dir[3], float maxT, int mask, RayHit & best) +{ + for (uint32_t k = g.offsets[cell]; k < g.offsets[cell + 1]; k++) { + const uint32_t ti = g.items[k]; + if (g.stamp[ti] == g.rayId) + continue; + g.stamp[ti] = g.rayId; + const Tri & t = g.tris[ti]; + if ((t.kind & mask) == 0) + continue; + const float d = ray_tri(t, p, dir); + if (d >= 0.0f && d <= maxT && (best.dist < 0.0f || d < best.dist)) { + best.dist = d; + best.kind = t.kind; + tri_normal(t, dir, best.normal); + } + } +} + +void terrain_normal(const Geo & g, float x, float z, float out[3]) +{ + const float e = g.hmCell; + const float dx = height_at(g, x + e, z) - height_at(g, x - e, z); + const float dz = height_at(g, x, z + e) - height_at(g, x, z - e); + out[0] = -dx; + out[1] = 2.0f * e; + out[2] = -dz; + const float len = std::sqrt(dot(out, out)); + out[0] /= len; + out[1] /= len; + out[2] /= len; +} + +// Height of the ray above the terrain at distance t. +float above_ground(const Geo & g, const float p[3], const float dir[3], float t) +{ + return p[1] + dir[1] * t - height_at(g, p[0] + dir[0] * t, p[2] + dir[2] * t); +} + +// Terrain crossing of the ray within [t0, t1], marched at half the heightmap spacing and bisected. +bool terrain_in(const Geo & g, const float p[3], const float dir[3], float t0, float t1, RayHit & best) +{ + const float step = g.hmCell * 0.5f; + float prevT = t0; + if (above_ground(g, p, dir, t0) <= 0.0f) { + best.dist = t0; + } else { + bool crossed = false; + for (float t = std::min(t0 + step, t1); prevT < t1; t = std::min(t + step, t1)) { + if (above_ground(g, p, dir, t) <= 0.0f) { + float lo = prevT; + float hi = t; + for (int i = 0; i < 8; i++) { + const float mid = 0.5f * (lo + hi); + if (above_ground(g, p, dir, mid) > 0.0f) + lo = mid; + else + hi = mid; + } + best.dist = hi; + crossed = true; + break; + } + prevT = t; + } + if (!crossed) + return false; + } + best.kind = 0; + terrain_normal(g, p[0] + dir[0] * best.dist, p[2] + dir[2] * best.dist, best.normal); + return true; +} + +// Walks the grid cells under the ray (2D DDA in XZ). In each cell the terrain is marched only when +// the ray dips below the cell's highest ground, the objects tested only when it dips below the +// cell's highest triangle. Stops at the first cell that holds a hit. +void ray_walk(Geo & g, const float p[3], const float dir[3], float len, int mask, RayHit & best) +{ + if (++g.rayId == 0) { + std::fill(g.stamp.begin(), g.stamp.end(), 0); + g.rayId = 1; + } + const bool terrain = (mask & RAY_TERRAIN) != 0; + const int objects = mask & ~RAY_TERRAIN; + const float gx = (p[0] - g.gridOrigin[0]) / CELL_M; + const float gz = (p[2] - g.gridOrigin[1]) / CELL_M; + int c = int(std::floor(gx)); + int r = int(std::floor(gz)); + const int stepC = dir[0] > 0.0f ? 1 : -1; + const int stepR = dir[2] > 0.0f ? 1 : -1; + const float big = 1.0e30f; + const float dtC = std::fabs(dir[0]) > 1.0e-7f ? CELL_M / std::fabs(dir[0]) : big; + const float dtR = std::fabs(dir[2]) > 1.0e-7f ? CELL_M / std::fabs(dir[2]) : big; + float nextC = std::fabs(dir[0]) > 1.0e-7f ? ((stepC > 0 ? float(c + 1) - gx : gx - float(c)) * dtC) : big; + float nextR = std::fabs(dir[2]) > 1.0e-7f ? ((stepR > 0 ? float(r + 1) - gz : gz - float(r)) * dtR) : big; + float t0 = 0.0f; + while (t0 <= len) { + const float t1 = std::min(len, std::min(nextC, nextR)); + const bool inside = c >= 0 && r >= 0 && c < g.gridCols && r < g.gridRows; + const size_t cell = inside ? size_t(r) * g.gridCols + c : 0; + const float lowY = std::min(p[1] + dir[1] * t0, p[1] + dir[1] * t1); + if (objects != 0 && inside && lowY <= g.cellTop[cell]) + test_cell(g, cell, p, dir, len, objects, best); + const float groundEnd = best.dist >= 0.0f ? std::min(t1, best.dist) : t1; + if (terrain && (!inside || lowY <= g.cellGround[cell]) && terrain_in(g, p, dir, t0, groundEnd, best)) + return; + if (best.dist >= 0.0f && best.dist <= t1) + return; + if (t1 >= len) + return; + if (nextC < nextR) { + c += stepC; + t0 = nextC; + nextC += dtC; + } else { + r += stepR; + t0 = nextR; + nextR += dtR; + } + } +} + +} + +bool geo_load(const std::string & path, std::string & error) +{ + Geo g; + std::ifstream in(path, std::ios::binary); + GeoHeader h; + if (!in || !read_bytes(in, &h, sizeof(h))) { + error = "cannot read " + path; + return false; + } + if (std::memcmp(h.magic, GEO_MAGIC, sizeof(GEO_MAGIC)) != 0 || h.version < 1 || h.version > GEO_MAX_VERSION) { + error = "not a .wtogeo file of a known version"; + return false; + } + g.water = h.waterLevel; + g.hmW = h.hmWidth; + g.hmH = h.hmHeight; + g.hmCell = h.hmCellSize > 0.0f ? h.hmCellSize : 1.0f; + g.hmOrigin[0] = h.hmOrigin[0]; + g.hmOrigin[1] = h.hmOrigin[1]; + g.heights.resize(size_t(h.hmWidth) * h.hmHeight); + std::vector verts(size_t(h.obsVertCount) * 3); + std::vector raw(size_t(h.obsTriCount) * 13); + if (!read_bytes(in, g.heights.data(), g.heights.size() * sizeof(float)) || + !read_bytes(in, verts.data(), verts.size() * sizeof(float)) || !read_bytes(in, raw.data(), raw.size())) { + error = "file is truncated"; + return false; + } + keep_triangles(g, verts, raw, h.obsTriCount); + build_grid(g, h.boundsMin, h.boundsMax); + build_ground_tops(g); + g.loaded = true; + g_geo = std::move(g); + return true; +} + +bool geo_loaded() +{ + return g_geo.loaded; +} + +float geo_height(float x, float z) +{ + return height_at(g_geo, x, z); +} + +float geo_water_level() +{ + return g_geo.water; +} + +RayHit geo_ray(const float p[3], const float dir[3], float len, int mask) +{ + RayHit best; + if (!g_geo.loaded || !(len > 0.0f)) + return best; + ray_walk(g_geo, p, dir, len, mask, best); + return best; +} + +uint32_t geo_triangle_count() +{ + return uint32_t(g_geo.tris.size()); +} + +} diff --git a/native/wto-ai-sim/module/src/sim_geo.h b/native/wto-ai-sim/module/src/sim_geo.h new file mode 100644 index 0000000..2f731b8 --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_geo.h @@ -0,0 +1,42 @@ +// The simulator's world geometry: the level's terrain heightmap and the collision triangles of its +// placed objects, read from the navigation extractor's `.wtogeo` (native/wto-nav/wto_nav_format.h), +// which is also what the AI lab's 3D view draws. Rays answer the AI script's line of sight, ground +// and obstacle probes in place of the engine's traces. +#pragma once + +#include +#include + +namespace wto_sim { + +// Ray masks: terrain plus groups of WtoObstacleClass. +enum RayMask : int { + RAY_TERRAIN = 1, + RAY_HARD = 2, // buildings, rocks, walls (hard solid and hard without cover) + RAY_BRIDGE = 4, // bridge decks + RAY_CRUSHABLE = 8, // fences, bushes, light objects a tank drives through + RAY_TREE = 16, // tree trunks + RAY_PLATFORM = 32, // walkable tops of placed objects + RAY_ALL = 63, +}; + +// What a ray hit: -1 nothing, 0 terrain, otherwise the RayMask bit of the object group. +struct RayHit { + float dist = -1.0f; + int kind = -1; + float normal[3] = { 0.0f, 1.0f, 0.0f }; +}; + +// Loads the geometry; on failure returns false and `error` says why. Replaces what was loaded. +bool geo_load(const std::string & path, std::string & error); +bool geo_loaded(); +// Bilinear terrain height (clamped to the heightmap); 0 when nothing is loaded. +float geo_height(float x, float z); +// The level's water level, or -1e6 when it has none. +float geo_water_level(); +// First hit of the ray p + dir * t for t in [0, len], against what `mask` selects. `dir` is unit. +RayHit geo_ray(const float p[3], const float dir[3], float len, int mask); +// Triangles kept after dropping buried faces, and grid cells, for the load log. +uint32_t geo_triangle_count(); + +} diff --git a/native/wto-ai-sim/module/src/sim_nav.cpp b/native/wto-ai-sim/module/src/sim_nav.cpp new file mode 100644 index 0000000..92c2864 --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_nav.cpp @@ -0,0 +1,137 @@ +// "wtoNav" requests in the simulator (see sim_nav.h). The script's DataBlock arrives as text +// lines; queries go through the shared protocol, the pack ops are answered here: the simulated +// battle's pack is set by the host, so there is no prefetch and no fingerprint check. +#include "sim_nav.h" + +#include "wto_nav_protocol.h" +#include "wto_nav_runtime.h" + +#include +#include +#include + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +namespace wto_sim { + +namespace { + +struct Block { + std::map values; + std::vector> reply; +}; + +std::string g_pack; +std::string g_level; + +const char * block_get(const void * blk, const char * name) +{ + const Block * b = static_cast(blk); + const auto it = b->values.find(name); + return it == b->values.end() ? "" : it->second.c_str(); +} + +void block_set(Block * b, const char * name, const std::string & value) +{ + b->values[name] = value; + b->reply.emplace_back(name, value); +} + +void block_set_str(void * blk, const char * name, const char * value) +{ + block_set(static_cast(blk), name, value ? value : ""); +} + +void block_set_int(void * blk, const char * name, int32_t value) +{ + block_set(static_cast(blk), name, std::to_string(value)); +} + +void parse(const std::string & text, Block & b) +{ + size_t at = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + if (end == std::string::npos) + end = text.size(); + const size_t eq = text.find('=', at); + if (eq != std::string::npos && eq < end) + b.values[text.substr(at, eq - at)] = text.substr(eq + 1, end - eq - 1); + at = end + 1; + } +} + +std::wstring widen(const std::string & s) +{ + if (s.empty()) + return std::wstring(); + const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), nullptr, 0); + std::wstring out(size_t(n), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), out.data(), n); + return out; +} + +void load_map(const WtoNavBlock & nb, Block & b) +{ + WtoNavLoadInfo info = {}; + std::string reason; + if (g_pack.empty()) { + reason = "no pack set for the simulated level"; + } else { + wto_nav_protocol_setup(&nb); + wto_nav_load(widen(g_pack).c_str(), nullptr, &info); + if (info.result != WTO_NAV_LOAD_OK) + reason = info.detail; + } + const bool ok = reason.empty(); + const bool fallback = std::string(block_get(&b, "allowFallback")) != "0"; + block_set(&b, "state", ok ? "loaded" : fallback ? "fallback" : "failed"); + block_set(&b, "fingerprint", "unknown"); + block_set(&b, "level", g_level); + block_set(&b, "reason", reason); + block_set_int(&b, "tiers", ok ? int32_t(info.tiers) : 0); + block_set_int(&b, "covers", ok ? int32_t(info.covers) : 0); +} + +} + +void nav_set_pack(const std::string & packPath, const std::string & level) +{ + g_pack = packPath; + g_level = level; +} + +std::string nav_request(const std::string & request) +{ + Block b; + parse(request, b); + WtoNavBlock nb; + nb.blk = &b; + nb.get_str = block_get; + nb.set_str = block_set_str; + nb.set_int = block_set_int; + const std::string op = block_get(&b, "op"); + if (!wto_nav_protocol_query(&nb, op.c_str())) { + if (op == "load_map") { + load_map(nb, b); + } else if (op == "prefetch") { + block_set(&b, "state", "skipped"); + block_set(&b, "level", g_level); + block_set(&b, "reason", "the simulator loads on load_map"); + } else if (op == "unload_map") { + wto_nav_unload(); + block_set_int(&b, "ok", 1); + } else { + std::fprintf(stderr, "WTO_NAV|BAD_REQUEST|op=%s\n", op.c_str()); + } + } + std::string out; + for (const auto & kv : b.reply) + out += kv.first + "=" + kv.second + "\n"; + return out; +} + +} diff --git a/native/wto-ai-sim/module/src/sim_nav.h b/native/wto-ai-sim/module/src/sim_nav.h new file mode 100644 index 0000000..04b84dd --- /dev/null +++ b/native/wto-ai-sim/module/src/sim_nav.h @@ -0,0 +1,15 @@ +// The simulator's side of the AI script's "wtoNav" requests: the same navigation engine and +// request protocol as the game (native/wto-nav), fed from the simulated level's pack. +#pragma once + +#include + +namespace wto_sim { + +// The pack load_map will read; the level name is reported back to the script. +void nav_set_pack(const std::string & packPath, const std::string & level); + +// Answers one request. Both are "key=value" lines; the reply holds only the values written back. +std::string nav_request(const std::string & request); + +} diff --git a/native/wto-ai-sim/module/src/wto_sim_module.cpp b/native/wto-ai-sim/module/src/wto_sim_module.cpp new file mode 100644 index 0000000..cd1e34f --- /dev/null +++ b/native/wto-ai-sim/module/src/wto_sim_module.cpp @@ -0,0 +1,93 @@ +// daScript module `wto_sim`: what the ground AI simulator's scripts need from native code, the +// level geometry (rays, ground height, water) and the navigation engine behind "wtoNav" requests. +// The engine stand-ins of the simulator (Dacoll, RendInst, Mission...) are scripts built on it. +#include "daScript/misc/platform.h" + +#include "daScript/ast/ast.h" +#include "daScript/ast/ast_interop.h" +#include "daScript/ast/ast_handle.h" + +#include "sim_geo.h" +#include "sim_nav.h" + +#include + +namespace das { + +// Loads the level geometry; prints why when it fails. +static bool wto_sim_geo_load(const char * path) +{ + std::string error; + if (wto_sim::geo_load(path ? path : "", error)) { + std::printf("WTO_SIM|GEO_LOADED|path=%s|tris=%u\n", path, wto_sim::geo_triangle_count()); + return true; + } + std::printf("WTO_SIM|GEO_FAILED|path=%s|reason=%s\n", path ? path : "", error.c_str()); + return false; +} + +static float wto_sim_geo_height(float x, float z) +{ + return wto_sim::geo_height(x, z); +} + +static float wto_sim_geo_water() +{ + return wto_sim::geo_water_level(); +} + +// Distance to the first hit of the ray, or -1; `kind` is 0 for terrain, else the object group. +static float wto_sim_geo_ray(float3 p, float3 dir, float len, int32_t mask, int32_t & kind, float3 & normal) +{ + const float pa[3] = { p.x, p.y, p.z }; + const float da[3] = { dir.x, dir.y, dir.z }; + const wto_sim::RayHit hit = wto_sim::geo_ray(pa, da, len, mask); + kind = hit.kind; + normal = float3(hit.normal[0], hit.normal[1], hit.normal[2]); + return hit.dist; +} + +static void wto_sim_nav_set_pack(const char * packPath, const char * level) +{ + wto_sim::nav_set_pack(packPath ? packPath : "", level ? level : ""); +} + +static char * wto_sim_nav_request(const char * request, Context * context, LineInfoArg * at) +{ + const std::string reply = wto_sim::nav_request(request ? request : ""); + return context->allocateString(reply, at); +} + +class Module_WtoSim : public Module { +public: + Module_WtoSim() : Module("wto_sim") { + ModuleLibrary lib; + lib.addModule(this); + lib.addBuiltInModule(); + addConstant(*this, "WTO_SIM_RAY_TERRAIN", int32_t(wto_sim::RAY_TERRAIN)); + addConstant(*this, "WTO_SIM_RAY_HARD", int32_t(wto_sim::RAY_HARD)); + addConstant(*this, "WTO_SIM_RAY_BRIDGE", int32_t(wto_sim::RAY_BRIDGE)); + addConstant(*this, "WTO_SIM_RAY_CRUSHABLE", int32_t(wto_sim::RAY_CRUSHABLE)); + addConstant(*this, "WTO_SIM_RAY_TREE", int32_t(wto_sim::RAY_TREE)); + addConstant(*this, "WTO_SIM_RAY_PLATFORM", int32_t(wto_sim::RAY_PLATFORM)); + addConstant(*this, "WTO_SIM_RAY_ALL", int32_t(wto_sim::RAY_ALL)); + addExtern(*this, lib, "wto_sim_geo_load", + SideEffects::modifyExternal, "wto_sim_geo_load")->args({"path"}); + addExtern(*this, lib, "wto_sim_geo_height", + SideEffects::accessExternal, "wto_sim_geo_height")->args({"x", "z"}); + addExtern(*this, lib, "wto_sim_geo_water", + SideEffects::accessExternal, "wto_sim_geo_water"); + addExtern(*this, lib, "wto_sim_geo_ray", + SideEffects::modifyArgumentAndExternal, "wto_sim_geo_ray") + ->args({"p", "dir", "len", "mask", "kind", "normal"}); + addExtern(*this, lib, "wto_sim_nav_set_pack", + SideEffects::modifyExternal, "wto_sim_nav_set_pack")->args({"pack", "level"}); + addExtern(*this, lib, "wto_sim_nav_request", + SideEffects::modifyExternal, "wto_sim_nav_request")->args({"request", "context", "at"}); + } +}; + +REGISTER_DYN_MODULE(Module_WtoSim, Module_WtoSim); +} + +REGISTER_MODULE_IN_NAMESPACE(Module_WtoSim, das); diff --git a/native/wto-nav/wto_nav_protocol.c b/native/wto-nav/wto_nav_protocol.c new file mode 100644 index 0000000..ed98fad --- /dev/null +++ b/native/wto-nav/wto_nav_protocol.c @@ -0,0 +1,247 @@ +/* The "wtoNav" request protocol on top of the navigation engine (see wto_nav_protocol.h). */ +#include "wto_nav_protocol.h" +#include "wto_nav_runtime.h" + +#include +#include +#include + +/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */ +static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = { + "", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "", +}; + +static float get_real(const WtoNavBlock *b, const char *name, float def) +{ + const char *text = b->get_str(b->blk, name); + char *end; + float value; + if (text == NULL || text[0] == '\0') + return def; + value = strtof(text, &end); + return (*end == '\0' && value == value) ? value : def; +} + +static long get_long(const WtoNavBlock *b, const char *name, long def) +{ + const char *text = b->get_str(b->blk, name); + char *end; + long value; + if (text == NULL || text[0] == '\0') + return def; + value = strtol(text, &end, 10); + return *end == '\0' ? value : def; +} + +/* x, y, z */ +static void get_vec(const WtoNavBlock *b, char prefix, float out[3]) +{ + char key[3]; + key[0] = prefix; + key[1] = 'x'; + key[2] = '\0'; + out[0] = get_real(b, key, 0.0f); + key[1] = 'y'; + out[1] = get_real(b, key, 0.0f); + key[1] = 'z'; + out[2] = get_real(b, key, 0.0f); +} + +static void set_int(const WtoNavBlock *b, const char *name, int32_t value) +{ + b->set_int(b->blk, name, value); +} + +static int32_t to_cm(float metres) +{ + const float cm = metres * 100.0f; + if (cm > 2.0e9f) + return INT32_MAX; + if (cm < -2.0e9f) + return INT32_MIN; + return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); +} + +static void set_vec_cm(const WtoNavBlock *b, const char *x, const char *y, const char *z, const float v[3]) +{ + set_int(b, x, to_cm(v[0])); + set_int(b, y, to_cm(v[1])); + set_int(b, z, to_cm(v[2])); +} + +static void read_costs(const WtoNavBlock *b, const char *prefix, WtoNavCosts *costs) +{ + char key[48]; + int area; + for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) { + costs->area[area] = 1.0f; + if (AREA_KEYS[area][0] == '\0') + continue; + snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]); + costs->area[area] = get_real(b, key, 1.0f); + if (!(costs->area[area] > 0.0f)) + costs->area[area] = 1.0f; + } + snprintf(key, sizeof(key), "%s_chokepoint", prefix); + costs->chokepointMul = get_real(b, key, 1.0f); + if (!(costs->chokepointMul > 0.0f)) + costs->chokepointMul = 1.0f; +} + +void wto_nav_protocol_setup(const WtoNavBlock *b) +{ + WtoNavCosts costs; + WtoNavTuning tuning; + read_costs(b, "t", &costs); + wto_nav_set_costs(0, &costs); + read_costs(b, "w", &costs); + wto_nav_set_costs(1, &costs); + tuning.trafficCostPerPath = get_real(b, "trafficPerPath", 0.0f); + tuning.trafficCostMaxMul = get_real(b, "trafficMaxMul", 1.0f); + tuning.trafficHoldSec = get_real(b, "trafficHoldSec", 0.0f); + tuning.cornerOffsetM = get_real(b, "cornerOffset", 0.0f); + wto_nav_set_tuning(&tuning); +} + +static void path_request(const WtoNavBlock *b) +{ + WtoNavPathRequest req; + const long slot = get_long(b, "slot", -1), tier = get_long(b, "tier", -1), filter = get_long(b, "filter", 0); + const long group = get_long(b, "group", 0); + uint32_t ticket = 0; + + memset(&req, 0, sizeof(req)); + req.tier = (uint32_t)tier; + req.filter = (uint32_t)filter; + req.group = group > 0 ? (uint32_t)group : 0u; + req.snapM = get_real(b, "snap", 0.0f); + req.goalSnapM = get_real(b, "goalSnap", 0.0f); + get_vec(b, 's', req.start); + get_vec(b, 'g', req.goal); + if (slot >= 0 && tier >= 0 && filter >= 0) + ticket = wto_nav_path_request((uint32_t)slot, &req); + set_int(b, "ticket", (int32_t)ticket); +} + +static void path_result(const WtoNavBlock *b) +{ + static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" }; + float points[WTO_NAV_RT_MAX_CORNERS * 3]; + const long slot = get_long(b, "slot", -1), ticket = get_long(b, "ticket", 0); + WtoNavPathResult result; + int i; + + wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket, + points, WTO_NAV_RT_MAX_CORNERS, &result); + b->set_str(b->blk, "status", STATUS[result.status]); + set_int(b, "count", result.count); + set_int(b, "lenCm", to_cm(result.lengthM)); + set_int(b, "truncated", result.truncated); + set_int(b, "goalMoved", result.goalMoved); + for (i = 0; i < result.count; i++) { + char kx[16], ky[16], kz[16]; + snprintf(kx, sizeof(kx), "p%dx", i); + snprintf(ky, sizeof(ky), "p%dy", i); + snprintf(kz, sizeof(kz), "p%dz", i); + set_vec_cm(b, kx, ky, kz, points + i * 3); + } +} + +static void probe(const WtoNavBlock *b) +{ + WtoNavProbe info; + float pos[3]; + get_vec(b, 'p', pos); + if (!wto_nav_probe((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), pos, + get_real(b, "snap", 0.0f), get_real(b, "wallR", 0.0f), &info)) + info.onMesh = -1; + set_int(b, "onMesh", info.onMesh); + if (info.onMesh != 1) + return; + set_int(b, "offCm", to_cm(info.offsetM)); + set_int(b, "wallCm", to_cm(info.wallDistM)); + set_int(b, "area", (int32_t)info.area); + set_int(b, "flags", (int32_t)info.flags); + set_vec_cm(b, "nx", "ny", "nz", info.nearest); +} + +static void raycast(const WtoNavBlock *b) +{ + float start[3], goal[3], hit[3], frac = 0.0f; + int clear; + get_vec(b, 's', start); + get_vec(b, 'g', goal); + clear = wto_nav_raycast((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), + get_real(b, "snap", 0.0f), start, goal, &frac, hit); + set_int(b, "clear", clear); + set_int(b, "hitPm", (int32_t)(frac * 1000.0f + 0.5f)); + set_vec_cm(b, "hx", "hy", "hz", hit); +} + +static void nearest(const WtoNavBlock *b) +{ + float pos[3], out[3] = { 0.0f, 0.0f, 0.0f }; + int found; + get_vec(b, 'p', pos); + found = wto_nav_nearest((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), + get_real(b, "radius", 0.0f), pos, out); + set_int(b, "found", found); + set_vec_cm(b, "x", "y", "z", out); +} + +static void add_dynamic(const WtoNavBlock *b) +{ + float pos[3]; + get_vec(b, 'p', pos); + set_int(b, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(b, "radius", 0.0f), get_real(b, "mul", 1.0f), + get_real(b, "until", 0.0f))); +} + +static void get_stats(const WtoNavBlock *b) +{ + WtoNavStats stats; + wto_nav_get_stats(&stats); + set_int(b, "loaded", stats.loaded); + set_int(b, "queries", (int32_t)stats.queries); + set_int(b, "failures", (int32_t)stats.failures); + set_int(b, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0); + set_int(b, "maxUs", (int32_t)stats.maxMicros); + set_int(b, "maxFrames", (int32_t)stats.maxFrames); + set_int(b, "pumpMaxUs", (int32_t)stats.pumpMaxMicros); + set_int(b, "pending", (int32_t)stats.pending); + set_int(b, "dynamic", (int32_t)stats.dynamic); + set_int(b, "meshQueries", (int32_t)stats.meshQueries); + set_int(b, "traffic", (int32_t)stats.trafficPaths); + set_int(b, "cornersMoved", (int32_t)stats.cornersMoved); +} + +static void pump(const WtoNavBlock *b) +{ + WtoNavStats stats; + wto_nav_pump((double)get_real(b, "budgetUs", 500.0f), get_real(b, "now", 0.0f)); + wto_nav_get_stats(&stats); + set_int(b, "pending", (int32_t)stats.pending); +} + +int wto_nav_protocol_query(const WtoNavBlock *b, const char *op) +{ + if (strcmp(op, "probe") == 0) + probe(b); + else if (strcmp(op, "path_result") == 0) + path_result(b); + else if (strcmp(op, "path_request") == 0) + path_request(b); + else if (strcmp(op, "raycast") == 0) + raycast(b); + else if (strcmp(op, "pump") == 0) + pump(b); + else if (strcmp(op, "nearest") == 0) + nearest(b); + else if (strcmp(op, "dynamic") == 0) + add_dynamic(b); + else if (strcmp(op, "get_stats") == 0) + get_stats(b); + else + return 0; + return 1; +} diff --git a/native/wto-nav/wto_nav_protocol.h b/native/wto-nav/wto_nav_protocol.h new file mode 100644 index 0000000..8835d67 --- /dev/null +++ b/native/wto-nav/wto_nav_protocol.h @@ -0,0 +1,49 @@ +/* + * The "wtoNav" request protocol of the ground AI script, shared by the game (wto-net + * local_mp_nav.c) and the AI simulator (native/wto-ai-sim): the script fills a block of string + * values with `op` and its arguments, the host answers by writing ints and strings back into it. + * Coordinates in replies are centimetres. The host keeps the ops that depend on where the battle's + * pack comes from (prefetch, load_map, unload_map); everything that only needs the loaded pack is + * answered here. + * + * op=pump now (script seconds), budgetUs -> pending + * op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap, + * goalSnap, sx..sz, gx..gz -> ticket + * op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale, + * count, lenCm, truncated, goalMoved, px/py/pz + * op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags, + * nx/ny/nz + * op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz + * op=nearest tier, filter, radius, px..pz -> found, x/y/z + * op=dynamic px..pz, radius, mul, until (script seconds) -> count + * op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending, + * dynamic, meshQueries, traffic, cornersMoved + * + * load_map carries the per-class costs t_, w_ and the search tuning trafficPerPath, + * trafficMaxMul, trafficHoldSec, cornerOffset; wto_nav_protocol_setup applies them. + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Access to one request block. get_str returns "" for a value the block does not have. */ +typedef struct WtoNavBlock { + void *blk; + const char *(*get_str)(const void *blk, const char *name); + void (*set_str)(void *blk, const char *name, const char *value); + void (*set_int)(void *blk, const char *name, int32_t value); +} WtoNavBlock; + +/* Hands the costs and search tuning of a load_map request to the engine, before it loads. */ +void wto_nav_protocol_setup(const WtoNavBlock *b); + +/* Answers `op` when it is one of the queries above; returns 0 for any other op. */ +int wto_nav_protocol_query(const WtoNavBlock *b, const char *op); + +#ifdef __cplusplus +} +#endif diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index 2138e2d..7dbe352 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -32,7 +32,7 @@ $sources = Quote @( "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", "$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c", "$src\local_mp_damage_notifications.c", "$src\local_mp_hit_feedback.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", "$src\local_mp_captures.c", "$src\local_mp_air_ai_sync.c", - "$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", + "$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", "$nav\wto_nav_protocol.c", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" ) $detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName diff --git a/native/wto-net/src/local_mp_nav.c b/native/wto-net/src/local_mp_nav.c index 0fb4c43..dfea6f0 100644 --- a/native/wto-net/src/local_mp_nav.c +++ b/native/wto-net/src/local_mp_nav.c @@ -1,30 +1,17 @@ /* * "wtoNav" requests of the ground AI script (call_mission_action, local_mp_ground_ai.c) and the - * battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request, this - * module answers synchronously by writing into the same block: + * battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request and this + * module answers synchronously into the same block. The queries are the shared protocol of + * native/wto-nav/wto_nav_protocol.h; this module adds the ops that depend on the battle: * * op=prefetch -> state=started|skipped, level, reason (battle still loading) - * op=load_map allowFallback="0|1", tracked/wheeled costs t_, w_, - * trafficPerPath, trafficMaxMul, trafficHoldSec, cornerOffset + * op=load_map allowFallback="0|1", plus the costs and tuning of the protocol * -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level, * reason, tiers, covers * op=unload_map -> ok - * op=pump now (script seconds), budgetUs -> pending - * op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap, - * goalSnap, sx..sz, gx..gz -> ticket - * op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale, - * count, lenCm, truncated, goalMoved, px/py/pz - * op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags, - * nx/ny/nz - * op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz - * op=nearest tier, filter, radius, px..pz -> found, x/y/z - * op=dynamic px..pz, radius, mul, until (script seconds) -> count - * op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending, - * dynamic, meshQueries, traffic, cornersMoved * - * Coordinates in replies are centimetres (ints). Request values are strings: the script only uses - * the DataBlock string add it already relies on. Replies are ints and strings written with the - * setters local_mp_awards resolves. + * Request values are strings: the script only uses the DataBlock string add it already relies on. + * Replies are ints and strings written with the setters local_mp_awards resolves. * * The level comes from the mission settings (customBots wtoLevel, written by the local server), * the pack folder from wto_ws.cfg (nav.dir). The script asks for a prefetch while the battle @@ -36,6 +23,7 @@ #include "local_mp_internal.h" #include "local_mp_offsets.h" #include "local_mp_values.h" +#include "wto_nav_protocol.h" #include "wto_nav_runtime.h" #include @@ -64,11 +52,6 @@ typedef struct NavBattle { uint32_t covers; } NavBattle; -/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */ -static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = { - "", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "", -}; - static NavBattle g_battle; static SRWLOCK g_battle_lock = SRWLOCK_INIT; static LONG g_missing_values_logged; @@ -96,17 +79,6 @@ static void set_int(void *blk, const char *name, int32_t value) ((BlkSetIntFn)g_lmp.blk_set_int)(blk, name, &value); } -static float get_real(const void *blk, const char *name, float def) -{ - const char *text = g_lmp_datablock_get_str(blk, name, ""); - char *end; - float value; - if (text == NULL || text[0] == '\0') - return def; - value = strtof(text, &end); - return (*end == '\0' && value == value) ? value : def; -} - static long get_long(const void *blk, const char *name, long def) { const char *text = g_lmp_datablock_get_str(blk, name, ""); @@ -118,32 +90,20 @@ static long get_long(const void *blk, const char *name, long def) return *end == '\0' ? value : def; } -/* x, y, z */ -static void get_vec(const void *blk, char prefix, float out[3]) +static const char *block_get_str(const void *blk, const char *name) { - char key[3] = { prefix, 'x', '\0' }; - out[0] = get_real(blk, key, 0.0f); - key[1] = 'y'; - out[1] = get_real(blk, key, 0.0f); - key[1] = 'z'; - out[2] = get_real(blk, key, 0.0f); + const char *text = g_lmp_datablock_get_str(blk, name, ""); + return text ? text : ""; } -static int32_t to_cm(float metres) +static WtoNavBlock game_block(void *blk) { - const float cm = metres * 100.0f; - if (cm > 2.0e9f) - return INT32_MAX; - if (cm < -2.0e9f) - return INT32_MIN; - return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f); -} - -static void set_vec_cm(void *blk, const char *x, const char *y, const char *z, const float v[3]) -{ - set_int(blk, x, to_cm(v[0])); - set_int(blk, y, to_cm(v[1])); - set_int(blk, z, to_cm(v[2])); + WtoNavBlock b; + b.blk = blk; + b.get_str = block_get_str; + b.set_str = set_str; + b.set_int = set_int; + return b; } static void hex20(const uint8_t *sha1, char out[41]) @@ -227,35 +187,6 @@ static int battle_paths(char level[NAV_LEVEL_MAX], wchar_t pack[MAX_PATH], wchar return 1; } -static void read_costs(const void *blk, const char *prefix, WtoNavCosts *costs) -{ - char key[48]; - int area; - for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) { - costs->area[area] = 1.0f; - if (AREA_KEYS[area][0] == '\0') - continue; - snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]); - costs->area[area] = get_real(blk, key, 1.0f); - if (!(costs->area[area] > 0.0f)) - costs->area[area] = 1.0f; - } - snprintf(key, sizeof(key), "%s_chokepoint", prefix); - costs->chokepointMul = get_real(blk, key, 1.0f); - if (!(costs->chokepointMul > 0.0f)) - costs->chokepointMul = 1.0f; -} - -static void read_tuning(const void *blk) -{ - WtoNavTuning tuning; - tuning.trafficCostPerPath = get_real(blk, "trafficPerPath", 0.0f); - tuning.trafficCostMaxMul = get_real(blk, "trafficMaxMul", 1.0f); - tuning.trafficHoldSec = get_real(blk, "trafficHoldSec", 0.0f); - tuning.cornerOffsetM = get_real(blk, "cornerOffset", 0.0f); - wto_nav_set_tuning(&tuning); -} - static void log_loaded(const WtoNavLoadInfo *info) { char expected[41], actual[41]; @@ -272,16 +203,12 @@ static void decide_locked(const void *blk, int allow_fallback) { wchar_t pack[MAX_PATH], level_path[MAX_PATH]; WtoNavLoadInfo info; - WtoNavCosts costs; + WtoNavBlock request = game_block((void *)blk); memset(&info, 0, sizeof(info)); info.result = WTO_NAV_LOAD_MISSING; if (battle_paths(g_battle.level, pack, level_path, g_battle.reason, sizeof(g_battle.reason))) { - read_costs(blk, "t", &costs); - wto_nav_set_costs(0, &costs); - read_costs(blk, "w", &costs); - wto_nav_set_costs(1, &costs); - read_tuning(blk); + wto_nav_protocol_setup(&request); wto_nav_load(pack, level_path[0] ? level_path : NULL, &info); if (info.result != WTO_NAV_LOAD_OK) snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail); @@ -358,129 +285,9 @@ static void unload_locked(const char *why) memset(&g_battle, 0, sizeof(g_battle)); } -static void path_request(void *blk) -{ - WtoNavPathRequest req; - const long slot = get_long(blk, "slot", -1), tier = get_long(blk, "tier", -1), filter = get_long(blk, "filter", 0); - const long group = get_long(blk, "group", 0); - uint32_t ticket = 0; - - memset(&req, 0, sizeof(req)); - req.tier = (uint32_t)tier; - req.filter = (uint32_t)filter; - req.group = group > 0 ? (uint32_t)group : 0u; - req.snapM = get_real(blk, "snap", 0.0f); - req.goalSnapM = get_real(blk, "goalSnap", 0.0f); - get_vec(blk, 's', req.start); - get_vec(blk, 'g', req.goal); - if (slot >= 0 && tier >= 0 && filter >= 0) - ticket = wto_nav_path_request((uint32_t)slot, &req); - set_int(blk, "ticket", (int32_t)ticket); -} - -static void path_result(void *blk) -{ - static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" }; - float points[WTO_NAV_RT_MAX_CORNERS * 3]; - const long slot = get_long(blk, "slot", -1), ticket = get_long(blk, "ticket", 0); - WtoNavPathResult result; - char key[16]; - int i; - - wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket, - points, WTO_NAV_RT_MAX_CORNERS, &result); - set_str(blk, "status", STATUS[result.status]); - set_int(blk, "count", result.count); - set_int(blk, "lenCm", to_cm(result.lengthM)); - set_int(blk, "truncated", result.truncated); - set_int(blk, "goalMoved", result.goalMoved); - for (i = 0; i < result.count; i++) { - char ky[16], kz[16]; - snprintf(key, sizeof(key), "p%dx", i); - snprintf(ky, sizeof(ky), "p%dy", i); - snprintf(kz, sizeof(kz), "p%dz", i); - set_vec_cm(blk, key, ky, kz, points + i * 3); - } -} - -static void probe(void *blk) -{ - WtoNavProbe info; - float pos[3]; - get_vec(blk, 'p', pos); - if (!wto_nav_probe((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), pos, - get_real(blk, "snap", 0.0f), get_real(blk, "wallR", 0.0f), &info)) - info.onMesh = -1; - set_int(blk, "onMesh", info.onMesh); - if (info.onMesh != 1) - return; - set_int(blk, "offCm", to_cm(info.offsetM)); - set_int(blk, "wallCm", to_cm(info.wallDistM)); - set_int(blk, "area", (int32_t)info.area); - set_int(blk, "flags", (int32_t)info.flags); - set_vec_cm(blk, "nx", "ny", "nz", info.nearest); -} - -static void raycast(void *blk) -{ - float start[3], goal[3], hit[3], frac = 0.0f; - int clear; - get_vec(blk, 's', start); - get_vec(blk, 'g', goal); - clear = wto_nav_raycast((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), - get_real(blk, "snap", 0.0f), start, goal, &frac, hit); - set_int(blk, "clear", clear); - set_int(blk, "hitPm", (int32_t)(frac * 1000.0f + 0.5f)); - set_vec_cm(blk, "hx", "hy", "hz", hit); -} - -static void nearest(void *blk) -{ - float pos[3], out[3] = { 0.0f, 0.0f, 0.0f }; - int found; - get_vec(blk, 'p', pos); - found = wto_nav_nearest((uint32_t)get_long(blk, "tier", 0), (uint32_t)get_long(blk, "filter", 0), - get_real(blk, "radius", 0.0f), pos, out); - set_int(blk, "found", found); - set_vec_cm(blk, "x", "y", "z", out); -} - -static void add_dynamic(void *blk) -{ - float pos[3]; - get_vec(blk, 'p', pos); - set_int(blk, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(blk, "radius", 0.0f), get_real(blk, "mul", 1.0f), - get_real(blk, "until", 0.0f))); -} - -static void get_stats(void *blk) -{ - WtoNavStats stats; - wto_nav_get_stats(&stats); - set_int(blk, "loaded", stats.loaded); - set_int(blk, "queries", (int32_t)stats.queries); - set_int(blk, "failures", (int32_t)stats.failures); - set_int(blk, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0); - set_int(blk, "maxUs", (int32_t)stats.maxMicros); - set_int(blk, "maxFrames", (int32_t)stats.maxFrames); - set_int(blk, "pumpMaxUs", (int32_t)stats.pumpMaxMicros); - set_int(blk, "pending", (int32_t)stats.pending); - set_int(blk, "dynamic", (int32_t)stats.dynamic); - set_int(blk, "meshQueries", (int32_t)stats.meshQueries); - set_int(blk, "traffic", (int32_t)stats.trafficPaths); - set_int(blk, "cornersMoved", (int32_t)stats.cornersMoved); -} - -static void pump(void *blk) -{ - WtoNavStats stats; - wto_nav_pump((double)get_real(blk, "budgetUs", 500.0f), get_real(blk, "now", 0.0f)); - wto_nav_get_stats(&stats); - set_int(blk, "pending", (int32_t)stats.pending); -} - void local_mp_nav_request(void *blk) { + WtoNavBlock request; const char *op; if (blk == NULL || !values_ready()) @@ -488,21 +295,10 @@ void local_mp_nav_request(void *blk) op = g_lmp_datablock_get_str(blk, "op", ""); if (op == NULL) return; - if (strcmp(op, "probe") == 0) { - probe(blk); - } else if (strcmp(op, "path_result") == 0) { - path_result(blk); - } else if (strcmp(op, "path_request") == 0) { - path_request(blk); - } else if (strcmp(op, "raycast") == 0) { - raycast(blk); - } else if (strcmp(op, "pump") == 0) { - pump(blk); - } else if (strcmp(op, "nearest") == 0) { - nearest(blk); - } else if (strcmp(op, "dynamic") == 0) { - add_dynamic(blk); - } else if (strcmp(op, "prefetch") == 0) { + request = game_block(blk); + if (wto_nav_protocol_query(&request, op)) + return; + if (strcmp(op, "prefetch") == 0) { prefetch(blk); } else if (strcmp(op, "load_map") == 0) { load_map(blk); @@ -511,8 +307,6 @@ void local_mp_nav_request(void *blk) unload_locked("battle ended"); ReleaseSRWLockExclusive(&g_battle_lock); set_int(blk, "ok", 1); - } else if (strcmp(op, "get_stats") == 0) { - get_stats(blk); } else { log_line("WTO_NAV|BAD_REQUEST|op=%s", op); } diff --git a/packages/ground-sim/src/index.ts b/packages/ground-sim/src/index.ts index c769fef..55c35c7 100644 --- a/packages/ground-sim/src/index.ts +++ b/packages/ground-sim/src/index.ts @@ -6,6 +6,11 @@ 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 { GEO_CLASS_NAMES, GeoError, geoHeightAt, readGeo, type GeoData } from './map/wtogeo.ts'; +export { + SCENE_BUILD_DEFAULTS, SCENE_KIND_NAMES, buildMapScene, decodeMapScene, encodeMapScene, sceneHeightAt, + type MapScene, type SceneBuildOptions, type SceneMesh, type SceneTerrain, +} from './map/scene.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, diff --git a/packages/ground-sim/src/map/scene.ts b/packages/ground-sim/src/map/scene.ts new file mode 100644 index 0000000..d3ae6bb --- /dev/null +++ b/packages/ground-sim/src/map/scene.ts @@ -0,0 +1,214 @@ +/** + * The 3D map of the AI lab: the level's terrain and the collision shapes of its placed objects, + * made from the `.wtogeo` geometry that the simulator's line of sight also uses. Building it + * thins the heightmap to a display size, drops object faces buried under the terrain, cuts the + * objects into square tiles by kind and welds shared vertices, so the browser can draw them in a + * few large meshes. `.wtoscene` is that result as one binary file. + */ +import { geoHeightAt, type GeoData } from './wtogeo.ts'; + +/** How the viewer colours the objects; several obstacle classes share a kind. */ +export const SCENE_KIND_NAMES = ['solid', 'noCover', 'bridge', 'crushable', 'tree', 'platform'] as const; + +/** Obstacle class (GEO_CLASS_NAMES) to scene kind. */ +const KIND_OF_CLASS = [0, 2, 3, 4, 4, 1, 5, 5] as const; + +export interface SceneTerrain { + readonly cols: number; + readonly rows: number; + readonly cellM: number; + readonly origin: readonly [number, number]; + /** `heights[row * cols + col]` at origin + (col, row) * cellM. */ + readonly heights: Float32Array; +} + +export interface SceneMesh { + /** SCENE_KIND_NAMES index. */ + readonly kind: number; + /** x, y, z triples in world metres. */ + readonly positions: Float32Array; + readonly indices: Uint32Array; +} + +export interface MapScene { + readonly boundsMin: readonly [number, number]; + readonly boundsMax: readonly [number, number]; + readonly waterLevel: number | undefined; + readonly terrain: SceneTerrain; + readonly meshes: SceneMesh[]; +} + +export interface SceneBuildOptions { + /** Most terrain samples kept; the heightmap is thinned by a whole stride to fit. */ + readonly maxTerrainSamples: number; + readonly tileM: number; + /** Vertices closer than this are welded into one. */ + readonly weldM: number; + /** A face whose corners all lie this far under the terrain is dropped. */ + readonly buriedM: number; +} + +export const SCENE_BUILD_DEFAULTS: SceneBuildOptions = { maxTerrainSamples: 1_200_000, tileM: 256, weldM: 0.05, buriedM: 0.3 }; + +function thinTerrain(geo: GeoData, maxSamples: number): SceneTerrain { + const stride = Math.max(1, Math.ceil(Math.sqrt((geo.hmCols * geo.hmRows) / maxSamples))); + const cols = Math.floor((geo.hmCols - 1) / stride) + 1; + const rows = Math.floor((geo.hmRows - 1) / stride) + 1; + const heights = new Float32Array(cols * rows); + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) heights[r * cols + c] = geo.heights[r * stride * geo.hmCols + c * stride] ?? 0; + } + return { cols, rows, cellM: geo.hmCellM * stride, origin: geo.hmOrigin, heights }; +} + +function buried(geo: GeoData, v: Float32Array, i: number, depth: number): boolean { + const x = v[i * 3] ?? 0; + const z = v[i * 3 + 2] ?? 0; + return (v[i * 3 + 1] ?? 0) < geoHeightAt(geo, x, z) - depth; +} + +/** Triangle ids per tile and kind, after dropping buried faces. */ +function bucketTriangles(geo: GeoData, opts: SceneBuildOptions): Map { + const { verts, tris, triClass } = geo; + const tilesX = Math.ceil((geo.boundsMax[0] - geo.boundsMin[0]) / opts.tileM) + 1; + const buckets = new Map(); + for (let t = 0; t < triClass.length; t++) { + const a = tris[t * 3] ?? 0; + const b = tris[t * 3 + 1] ?? 0; + const c = tris[t * 3 + 2] ?? 0; + if (buried(geo, verts, a, opts.buriedM) && buried(geo, verts, b, opts.buriedM) && buried(geo, verts, c, opts.buriedM)) continue; + const cx = ((verts[a * 3] ?? 0) + (verts[b * 3] ?? 0) + (verts[c * 3] ?? 0)) / 3; + const cz = ((verts[a * 3 + 2] ?? 0) + (verts[b * 3 + 2] ?? 0) + (verts[c * 3 + 2] ?? 0)) / 3; + const tx = Math.max(0, Math.floor((cx - geo.boundsMin[0]) / opts.tileM)); + const tz = Math.max(0, Math.floor((cz - geo.boundsMin[1]) / opts.tileM)); + const kind = KIND_OF_CLASS[triClass[t] ?? 0] ?? 0; + const key = (tz * tilesX + tx) * SCENE_KIND_NAMES.length + kind; + let list = buckets.get(key); + if (list === undefined) { list = []; buckets.set(key, list); } + list.push(t); + } + return buckets; +} + +/** One tile's triangles as an indexed mesh with welded, snapped vertices; degenerate faces dropped. */ +function weldTile(geo: GeoData, kind: number, triIds: readonly number[], weldM: number): SceneMesh | undefined { + const [bx, bz] = geo.boundsMin; + const slot = new Map(); + const pos: number[] = []; + const idx: number[] = []; + const corner = [0, 0, 0]; + for (const t of triIds) { + for (let k = 0; k < 3; k++) { + const v = geo.tris[t * 3 + k] ?? 0; + const qx = Math.round(((geo.verts[v * 3] ?? 0) - bx) / weldM); + const qy = Math.round(((geo.verts[v * 3 + 1] ?? 0) + 1000) / weldM); + const qz = Math.round(((geo.verts[v * 3 + 2] ?? 0) - bz) / weldM); + const key = (qx * 65536 + qy) * 131072 + qz; + let at = slot.get(key); + if (at === undefined) { + at = pos.length / 3; + slot.set(key, at); + pos.push(bx + qx * weldM, qy * weldM - 1000, bz + qz * weldM); + } + corner[k] = at; + } + const [a, b, c] = corner as [number, number, number]; + if (a !== b && b !== c && a !== c) idx.push(a, b, c); + } + if (idx.length === 0) return undefined; + return { kind, positions: Float32Array.from(pos), indices: Uint32Array.from(idx) }; +} + +export function buildMapScene(geo: GeoData, opts: SceneBuildOptions = SCENE_BUILD_DEFAULTS): MapScene { + const meshes: SceneMesh[] = []; + for (const [key, triIds] of bucketTriangles(geo, opts)) { + const mesh = weldTile(geo, key % SCENE_KIND_NAMES.length, triIds, opts.weldM); + if (mesh !== undefined) meshes.push(mesh); + } + return { + boundsMin: geo.boundsMin, + boundsMax: geo.boundsMax, + waterLevel: geo.waterLevel, + terrain: thinTerrain(geo, opts.maxTerrainSamples), + meshes, + }; +} + +/** Bilinear height of the scene's terrain at world (x, z), clamped to its grid. */ +export function sceneHeightAt(t: SceneTerrain, x: number, z: number): number { + const fx = Math.min(t.cols - 1.001, Math.max(0, (x - t.origin[0]) / t.cellM)); + const fz = Math.min(t.rows - 1.001, Math.max(0, (z - t.origin[1]) / t.cellM)); + const x0 = Math.floor(fx); + const z0 = Math.floor(fz); + const i = z0 * t.cols + x0; + const h = t.heights; + const a = (h[i] ?? 0) + ((h[i + 1] ?? 0) - (h[i] ?? 0)) * (fx - x0); + const b = (h[i + t.cols] ?? 0) + ((h[i + t.cols + 1] ?? 0) - (h[i + t.cols] ?? 0)) * (fx - x0); + return a + (b - a) * (fz - z0); +} + +const SCENE_MAGIC = 'WTOSCN\0\x01'; +const SCENE_VERSION = 1; +const SCENE_HEADER_BYTES = 56; + +/** + * `.wtoscene`: magic, version, bounds, water level (-1e6 when none), terrain grid, mesh count; + * the terrain heights; then per mesh its kind, vertex and index counts, positions and indices. + * Little-endian, every block 4-byte aligned. + */ +export function encodeMapScene(s: MapScene): Uint8Array { + let size = SCENE_HEADER_BYTES + s.terrain.heights.byteLength; + for (const m of s.meshes) size += 12 + m.positions.byteLength + m.indices.byteLength; + const out = new Uint8Array(size); + const dv = new DataView(out.buffer); + for (let i = 0; i < 8; i++) out[i] = SCENE_MAGIC.charCodeAt(i); + const head = [SCENE_VERSION, s.meshes.length, s.terrain.cols, s.terrain.rows]; + head.forEach((v, i) => dv.setUint32(8 + i * 4, v, true)); + const floats = [s.boundsMin[0], s.boundsMin[1], s.boundsMax[0], s.boundsMax[1], s.waterLevel ?? -1e6, + s.terrain.cellM, s.terrain.origin[0], s.terrain.origin[1]]; + floats.forEach((v, i) => dv.setFloat32(24 + i * 4, v, true)); + let at = SCENE_HEADER_BYTES; + const put = (a: Float32Array | Uint32Array): void => { out.set(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), at); at += a.byteLength; }; + put(s.terrain.heights); + for (const m of s.meshes) { + dv.setUint32(at, m.kind, true); + dv.setUint32(at + 4, m.positions.length / 3, true); + dv.setUint32(at + 8, m.indices.length, true); + at += 12; + put(m.positions); + put(m.indices); + } + return out; +} + +export function decodeMapScene(bytes: Uint8Array): MapScene { + if (String.fromCharCode(...bytes.subarray(0, 8)) !== SCENE_MAGIC) throw new Error('not a .wtoscene file'); + const own = bytes.byteOffset % 4 === 0 ? bytes : bytes.slice(); + const dv = new DataView(own.buffer, own.byteOffset, own.byteLength); + if (dv.getUint32(8, true) !== SCENE_VERSION) throw new Error('unsupported .wtoscene version'); + const meshCount = dv.getUint32(12, true); + const cols = dv.getUint32(16, true); + const rows = dv.getUint32(20, true); + const f = (i: number): number => dv.getFloat32(24 + i * 4, true); + let at = own.byteOffset + SCENE_HEADER_BYTES; + const floats = (n: number): Float32Array => { const a = new Float32Array(own.buffer, at, n); at += n * 4; return a; }; + const uints = (n: number): Uint32Array => { const a = new Uint32Array(own.buffer, at, n); at += n * 4; return a; }; + const heights = floats(cols * rows); + const meshes: SceneMesh[] = []; + for (let i = 0; i < meshCount; i++) { + const base = at - own.byteOffset; + const kind = dv.getUint32(base, true); + const verts = dv.getUint32(base + 4, true); + const count = dv.getUint32(base + 8, true); + at += 12; + meshes.push({ kind, positions: floats(verts * 3), indices: uints(count) }); + } + const water = f(4); + return { + boundsMin: [f(0), f(1)], + boundsMax: [f(2), f(3)], + waterLevel: water > -1e5 ? water : undefined, + terrain: { cols, rows, cellM: f(5), origin: [f(6), f(7)], heights }, + meshes, + }; +} diff --git a/packages/ground-sim/src/map/wtogeo.ts b/packages/ground-sim/src/map/wtogeo.ts new file mode 100644 index 0000000..4318473 --- /dev/null +++ b/packages/ground-sim/src/map/wtogeo.ts @@ -0,0 +1,99 @@ +/** + * Reader for the `.wtogeo` intermediate geometry (native/wto-nav/wto_nav_format.h) that the + * navigation extractor writes from the game's level: the cropped terrain heightmap and every + * collision triangle of placed objects, each with its obstacle class. Trailers (road mask, + * downhill links) are not read. Only plain views over the bytes, so it runs in Node and in the + * browser. + */ + +const MAGIC = 'WTOGEO\0\x01'; +const HEADER_BYTES = 84; +const TRI_BYTES = 13; + +/** WtoObstacleClass. */ +export const GEO_CLASS_NAMES = [ + 'hardSolid', 'bridgeDeck', 'crushable', 'treeThick', 'treeThin', 'hardNoCover', 'platform', 'platformNoCover', +] as const; + +export interface GeoData { + readonly version: number; + readonly waterLevel: number | undefined; + /** World x, z of the crop (battle area union plus margin). */ + readonly boundsMin: readonly [number, number]; + readonly boundsMax: readonly [number, number]; + /** Heightmap: `heights[row * cols + col]` is the height at origin + (col, row) * cellM. */ + readonly hmCols: number; + readonly hmRows: number; + readonly hmCellM: number; + readonly hmOrigin: readonly [number, number]; + readonly heights: Float32Array; + /** Obstacle vertices as x, y, z triples in world metres. */ + readonly verts: Float32Array; + /** Three vertex indices per triangle, and its class (GEO_CLASS_NAMES). */ + readonly tris: Uint32Array; + readonly triClass: Uint8Array; +} + +export class GeoError extends Error {} + +function floatsAt(bytes: Uint8Array, offset: number, count: number): Float32Array { + const at = bytes.byteOffset + offset; + if (at % 4 === 0) return new Float32Array(bytes.buffer, at, count); + return new Float32Array(bytes.slice(offset, offset + count * 4).buffer); +} + +export function readGeo(bytes: Uint8Array): GeoData { + if (bytes.byteLength < HEADER_BYTES) throw new GeoError('file shorter than its header'); + const magic = String.fromCharCode(...bytes.subarray(0, 8)); + if (magic !== MAGIC) throw new GeoError('not a .wtogeo file'); + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const u32 = (o: number): number => dv.getUint32(o, true); + const f32 = (o: number): number => dv.getFloat32(o, true); + const hmCols = u32(56); + const hmRows = u32(60); + const vertCount = u32(76); + const triCount = u32(80); + const hOff = HEADER_BYTES; + const vOff = hOff + hmCols * hmRows * 4; + const tOff = vOff + vertCount * 12; + if (tOff + triCount * TRI_BYTES > bytes.byteLength) throw new GeoError('file is truncated'); + const tris = new Uint32Array(triCount * 3); + const triClass = new Uint8Array(triCount); + for (let i = 0; i < triCount; i++) { + const o = tOff + i * TRI_BYTES; + tris[i * 3] = u32(o); + tris[i * 3 + 1] = u32(o + 4); + tris[i * 3 + 2] = u32(o + 8); + triClass[i] = bytes[o + 12] ?? 0; + } + const water = f32(36); + return { + version: u32(8), + waterLevel: water > -1e5 ? water : undefined, + boundsMin: [f32(40), f32(44)], + boundsMax: [f32(48), f32(52)], + hmCols, + hmRows, + hmCellM: f32(64), + hmOrigin: [f32(68), f32(72)], + heights: floatsAt(bytes, hOff, hmCols * hmRows), + verts: floatsAt(bytes, vOff, vertCount * 3), + tris, + triClass, + }; +} + +/** Bilinear terrain height at world (x, z), clamped to the heightmap. */ +export function geoHeightAt(geo: GeoData, x: number, z: number): number { + const fx = Math.min(geo.hmCols - 1.001, Math.max(0, (x - geo.hmOrigin[0]) / geo.hmCellM)); + const fz = Math.min(geo.hmRows - 1.001, Math.max(0, (z - geo.hmOrigin[1]) / geo.hmCellM)); + const x0 = Math.floor(fx); + const z0 = Math.floor(fz); + const tx = fx - x0; + const tz = fz - z0; + const h = geo.heights; + const i = z0 * geo.hmCols + x0; + const a = (h[i] ?? 0) + ((h[i + 1] ?? 0) - (h[i] ?? 0)) * tx; + const b = (h[i + geo.hmCols] ?? 0) + ((h[i + geo.hmCols + 1] ?? 0) - (h[i + geo.hmCols] ?? 0)) * tx; + return a + (b - a) * tz; +} diff --git a/packages/ground-sim/src/trace/parse.ts b/packages/ground-sim/src/trace/parse.ts index 899c89e..42ef36a 100644 --- a/packages/ground-sim/src/trace/parse.ts +++ b/packages/ground-sim/src/trace/parse.ts @@ -37,6 +37,14 @@ function num(f: Fields, key: string): number { return Number.isFinite(v) ? v : 0; } +/** A number that older traces lack, or that the game marks unknown with 9999. */ +function optNum(f: Fields, key: string): number | undefined { + const raw = f[key]; + if (raw === undefined) return undefined; + const v = Number(raw); + return Number.isFinite(v) && v !== 9999 ? v : undefined; +} + function flag(f: Fields, key: string): boolean { return f[key] === '1'; } @@ -53,6 +61,7 @@ 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'), + hullPitch: optNum(f, 'hp'), hullRoll: optNum(f, 'hr'), gunYaw: optNum(f, 'gy'), gunPitch: optNum(f, 'gp'), shooting: flag(f, 'shoot'), light: flag(f, 'light'), }; } diff --git a/packages/ground-sim/src/trace/types.ts b/packages/ground-sim/src/trace/types.ts index f859b04..809f077 100644 --- a/packages/ground-sim/src/trace/types.ts +++ b/packages/ground-sim/src/trace/types.ts @@ -23,6 +23,12 @@ export interface UnitSample { readonly y: number; readonly z: number; readonly yaw: number; + /** Hull pitch, nose up positive, and roll, left side up positive; undefined in older traces. */ + readonly hullPitch: number | undefined; + readonly hullRoll: number | undefined; + /** Main gun world yaw and pitch; undefined when the gun was not read. */ + readonly gunYaw: number | undefined; + readonly gunPitch: number | undefined; readonly speed: number; readonly shooting: boolean; readonly light: boolean;