chore(repo): merge tank AI checkpoint for 0.1.6

This commit is contained in:
N0VAN0M4LY committed 2026-12-06 15:47:46 +08:00
commit 710c8ecaaa
159 files changed
+35721 -1572

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ aces*.exe
/apps/launcher/out/
**/dist/
**/unpacked/
tools/navgen/extract/target/
# Node
node_modules/
+2
View File
@@ -0,0 +1,2 @@
lab.local.json
.cache/
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WTOffline AI Lab</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+6
View File
@@ -0,0 +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"
}
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@wto/ai-lab",
"version": "0.1.0",
"private": true,
"description": "Ground AI lab: replay viewer for battle traces and simulator runs.",
"type": "module",
"scripts": {
"dev": "vite",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"@wto/ground-sim": "*",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"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"
}
}
+147
View File
@@ -0,0 +1,147 @@
/**
* Dev-server API of the AI lab (local only):
* GET /api/maps levels that have a navigation pack in mapsDir
* GET /api/maps/file?name= a pack or POI file of mapsDir
* GET /api/logs game logs (.clog) in logsDir, newest first
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
* 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, 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;
}
const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CACHE_DIR = path.join(APP_DIR, '.cache');
const SAFE_NAME = /^[\w.-]+$/;
function loadConfig(): LabConfig {
const file = path.join(APP_DIR, 'lab.local.json');
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps'));
return {
mapsDir,
geoDir: str('geoDir', path.join(mapsDir, '..', 'work')),
logsDir: str('logsDir', ''),
python: str('python', 'python'),
};
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(body));
}
function sendFile(res: ServerResponse, file: string, type: string): void {
res.statusCode = 200;
res.setHeader('Content-Type', type);
createReadStream(file).pipe(res);
}
function listMaps(cfg: LabConfig): { level: string; pois: boolean; 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`)),
scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)),
};
});
}
function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] {
if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return [];
return readdirSync(cfg.logsDir)
.filter((f) => f.endsWith('.clog'))
.map((name) => {
const st = statSync(path.join(cfg.logsDir, name));
return { name, size: st.size, mtime: st.mtimeMs };
})
.sort((a, b) => b.mtime - a.mtime);
}
/** Decrypts `name` into the cache unless the cached text is newer than the log. */
function decryptLog(cfg: LabConfig, name: string): Promise<string> {
const source = path.join(cfg.logsDir, name);
const out = path.join(CACHE_DIR, `${name}.txt`);
mkdirSync(CACHE_DIR, { recursive: true });
if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out);
return new Promise((resolve, reject) => {
execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => {
if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`));
else resolve(out);
});
});
}
/** 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<boolean> {
const name = url.searchParams.get('name') ?? '';
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
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}` });
else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream');
return true;
}
if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) {
sendJson(res, 404, { error: `no log ${name}` });
return true;
}
sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8');
return true;
}
export function labApi(): Plugin {
return {
name: 'wto-ai-lab-api',
configureServer(server) {
const middleware: Connect.NextHandleFunction = (req, res, next) => {
const url = new URL(req.url ?? '/', 'http://localhost');
if (!url.pathname.startsWith('/api/')) { next(); return; }
handle(loadConfig(), url, res)
.then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); })
.catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }));
};
server.middlewares.use(middleware);
},
};
}
+144
View File
@@ -0,0 +1,144 @@
/** AI lab replay viewer: pick a game log, a battle in it, and play it back on the map. */
import type { TraceBattle } from '@wto/ground-sim';
import { useEffect, useMemo, useState } from 'react';
import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts';
import { sceneAt } from './frames.ts';
import { Inspector } from './Inspector.tsx';
import { Map3D, type MapLook } from './Map3D.tsx';
import { buildMapLayer } from './mapLayer.ts';
import type { ViewMode } from './three/cameraRig.ts';
import type { Layers } from './three/overlays.ts';
import { Timeline } from './Timeline.tsx';
const LAYER_LABELS: Readonly<Record<keyof Layers, string>> = {
goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击',
};
const VIEW_LABELS: Readonly<Record<ViewMode, string>> = { 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})`;
}
export function App(): React.JSX.Element {
const [maps, setMaps] = useState<MapEntry[]>([]);
const [logs, setLogs] = useState<LogEntry[]>([]);
const [logName, setLogName] = useState('');
const [battles, setBattles] = useState<TraceBattle[]>([]);
const [battleIdx, setBattleIdx] = useState(0);
const [mapData, setMapData] = useState<MapData | undefined>(undefined);
const [exposure, setExposure] = useState(false);
const [covers, setCovers] = useState(false);
const [look, setLook] = useState<MapLook>({ view: 'top', navImage: true, objects: true, crushable: true });
const [layers, setLayers] = useState<Layers>({ goals: true, links: true, cones: false, labels: false, events: true });
const [t, setT] = useState(0);
const [playing, setPlaying] = useState(false);
const [speed, setSpeed] = useState(4);
const [selected, setSelected] = useState<string | undefined>(undefined);
const [status, setStatus] = useState('');
const refreshLogs = (): void => { fetchLogs().then(setLogs).catch((e: unknown) => setStatus(String(e))); };
useEffect(() => {
fetchMaps().then(setMaps).catch((e: unknown) => setStatus(String(e)));
refreshLogs();
}, []);
const openLog = (name: string): void => {
setLogName(name);
setPlaying(false);
setStatus('正在解密和读取日志…');
loadLog(name).then((list) => {
setBattles(list);
// The longest battle that has bots in its trace; a battle left right after loading has none.
let pick = list.length - 1;
let best = 0;
list.forEach((b, i) => {
const withBots = b.frames.filter((f) => f.bots.size > 0).length;
if (withBots > best) { best = withBots; pick = i; }
});
setBattleIdx(Math.max(0, pick));
setStatus(list.length === 0 ? '这份日志里没有对局。' : '');
}).catch((e: unknown) => setStatus(String(e)));
};
const battle = battles[battleIdx];
const level = battle?.level;
useEffect(() => {
setT(battle?.startT ?? 0);
setSelected(undefined);
}, [battle]);
useEffect(() => {
const entry = maps.find((m) => m.level === level);
setMapData(undefined);
if (entry === undefined) return;
loadMap(entry).then(setMapData).catch((e: unknown) => setStatus(String(e)));
}, [level, maps]);
const mapLayer = useMemo(
() => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })),
[mapData, exposure, covers],
);
useEffect(() => {
if (!playing || battle === undefined) return;
let last = performance.now();
let handle = requestAnimationFrame(function step(now) {
const dt = (now - last) / 1000;
last = now;
setT((cur) => {
const next = cur + dt * speed;
if (next >= battle.endT) { setPlaying(false); return battle.endT; }
return next;
});
handle = requestAnimationFrame(step);
});
return () => cancelAnimationFrame(handle);
}, [playing, speed, battle]);
const scene = useMemo(() => (battle === undefined ? undefined : sceneAt(battle, t)), [battle, t]);
return (
<div className="app">
<header>
<select value={logName} onChange={(e) => openLog(e.target.value)}>
<option value="">选择游戏日志…</option>
{logs.map((l) => <option key={l.name} value={l.name}>{logLabel(l)}</option>)}
</select>
<button type="button" onClick={refreshLogs}>刷新</button>
{battles.length > 1 && (
<select value={battleIdx} onChange={(e) => setBattleIdx(Number(e.target.value))}>
{battles.map((b, i) => (
<option key={i} value={i}>{`第 ${i + 1} 局 ${b.level ?? '未知地图'}(${b.frames.length} 帧)`}</option>
))}
</select>
)}
{(Object.keys(LAYER_LABELS) as (keyof Layers)[]).map((k) => (
<label key={k}>
<input type="checkbox" checked={layers[k]} onChange={(e) => setLayers({ ...layers, [k]: e.target.checked })} />
{LAYER_LABELS[k]}
</label>
))}
<select value={look.view} onChange={(e) => setLook({ ...look, view: e.target.value as ViewMode })}>
{(Object.keys(VIEW_LABELS) as ViewMode[]).map((v) => <option key={v} value={v}>{VIEW_LABELS[v]}</option>)}
</select>
<label><input type="checkbox" checked={look.navImage} onChange={(e) => setLook({ ...look, navImage: e.target.checked })} />导航网格</label>
<label><input type="checkbox" checked={look.objects} onChange={(e) => setLook({ ...look, objects: e.target.checked })} />物体</label>
<label><input type="checkbox" checked={look.crushable} onChange={(e) => setLook({ ...look, crushable: e.target.checked })} />可碾压物</label>
<label><input type="checkbox" checked={exposure} onChange={(e) => setExposure(e.target.checked)} />暴露度</label>
<label><input type="checkbox" checked={covers} onChange={(e) => setCovers(e.target.checked)} />掩体点</label>
{status !== '' && <span className="status">{status}</span>}
{battle !== undefined && battle.frames.length === 0 && <span className="status">这一局没有轨迹(游戏里没开 diagnostics.trace)。</span>}
</header>
<main>
<Map3D mapScene={mapData?.scene} nav={mapLayer} battle={battle} scene={scene} selected={selected}
layers={layers} look={look} onSelect={setSelected} />
{battle !== undefined && <Inspector battle={battle} scene={scene} selected={selected} />}
</main>
{battle !== undefined && (
<Timeline battle={battle} t={t} playing={playing} speed={speed} selected={selected}
onSeek={setT} onPlaying={setPlaying} onSpeed={setSpeed} />
)}
</div>
);
}
+94
View File
@@ -0,0 +1,94 @@
/** Details of the selected vehicle at the current time, its recent log events, and the legends. */
import type { TraceBattle, TraceEvent } from '@wto/ground-sim';
import { eventsBetween, type SceneAt } from './frames.ts';
import {
BEHAVIOR_COLORS, BEHAVIOR_ZH, CLASS_ZH, COMMAND_ZH, DENY_COLORS, DENY_ZH, LANE_ZH, LOOK_COLORS, LOOK_ZH,
STATE_ZH, URGENCY_ZH, zh,
} from './labels.ts';
interface Props {
readonly battle: TraceBattle;
readonly scene: SceneAt | undefined;
readonly selected: string | undefined;
}
const RECENT_SEC = 20;
function angleDiff(a: number, b: number): number {
return Math.abs(((((a - b) % 360) + 540) % 360) - 180);
}
function involves(e: TraceEvent, eid: string): boolean {
return e.eid === eid || e.fields['tgt'] === eid || e.fields['off'] === eid || e.fields['target'] === eid;
}
function eventText(e: TraceEvent): string {
return Object.entries(e.fields)
.filter(([k]) => k !== 't' && k !== 'eid')
.map(([k, v]) => `${k}=${v}`)
.join(' ');
}
function Legend({ names, colors }: { names: readonly string[]; colors: readonly string[] }): React.JSX.Element {
return (
<div className="legend">
{names.map((n, i) => (
<span key={n}><i style={{ background: colors[i] ?? '#444' }} />{n}</span>
))}
</div>
);
}
function Row({ k, v }: { k: string; v: string }): React.JSX.Element {
return <tr><th>{k}</th><td>{v}</td></tr>;
}
export function Inspector({ battle, scene, selected }: Props): React.JSX.Element {
const u = selected !== undefined ? scene?.units.get(selected) : undefined;
const b = u?.bot;
const recent = selected !== undefined && scene !== undefined
? eventsBetween(battle, scene.t - RECENT_SEC, scene.t).filter((e) => involves(e, selected)).reverse()
: [];
return (
<aside className="inspector">
{u === undefined && <p className="hint">点击地图上的车辆查看详情。白框是玩家,黄色虚线是炮塔想看的方向,白线是实际炮管。</p>}
{u !== undefined && (
<table>
<tbody>
<Row k="编号" v={`${u.unit.eid}(${u.unit.army} 队,${u.unit.human ? '玩家' : u.unit.bot ? 'AI' : '原版 AI'})`} />
<Row k="存活" v={u.unit.alive ? '是' : '否'} />
<Row k="车速" v={`${u.unit.speed.toFixed(1)} m/s`} />
{b !== undefined && <>
<Row k="车型" v={zh(CLASS_ZH, b.vehicleClass)} />
<Row k="任务" v={b.hasOrder ? `${zh(COMMAND_ZH, b.command)},紧迫度${zh(URGENCY_ZH, b.urgency)},点 ${b.capIdx},${zh(LANE_ZH, b.lane)}` : '无'} />
<Row k="行为" v={`${zh(BEHAVIOR_ZH, b.behavior)}(分数 ${b.behaviorScore.toFixed(2)})`} />
<Row k="状态" v={zh(STATE_ZH, b.state)} />
<Row k="车速 期望/实际" v={`${b.wantSpeed.toFixed(1)} / ${b.forwardSpeed.toFixed(1)} m/s${b.reverseTravel ? ',倒车跟路' : ''}`} />
<Row k="感知目标" v={b.target === '0' ? '无' : `${b.target}${b.targetInSight ? '(可见)' : '(不可见)'}`} />
<Row k="威胁表" v={`${b.threatCount} 项,最高 ${b.topThreat},最高可见 ${b.topVisibleThreat}`} />
<Row k="炮塔依据" v={`${zh(LOOK_ZH, b.lookReason)}${b.lookAt !== '0' ? ` → ${b.lookAt}` : ''}`} />
<Row k="炮塔偏差" v={b.gunYaw === undefined ? '—' : `离想看的方向 ${angleDiff(b.gunYaw, b.wishYaw).toFixed(0)}°,离车头 ${angleDiff(b.gunYaw, u.yaw).toFixed(0)}°`} />
<Row k="主炮" v={b.reloading ? '装填中' : b.gunReady ? '就绪' : '未就绪'} />
<Row k="开火判定" v={`${zh(DENY_ZH, b.deny)},命中概率 ${(b.hitProb * 100).toFixed(0)}% / 门槛 ${(b.threshold * 100).toFixed(0)}%`} />
<Row k="扳机要求车速" v={b.requestedSpeed >= 99 ? '不限' : `${b.requestedSpeed.toFixed(1)} m/s`} />
</>}
</tbody>
</table>
)}
{recent.length > 0 && (
<div className="events">
<h4>最近 {RECENT_SEC} 秒的日志</h4>
{recent.map((e, i) => (
<div key={`${e.t}-${i}`}><b>{e.t.toFixed(1)}</b> {e.kind} <span>{eventText(e)}</span></div>
))}
</div>
)}
<h4>行为</h4>
<Legend names={BEHAVIOR_ZH} colors={BEHAVIOR_COLORS} />
<h4>拒绝开火</h4>
<Legend names={DENY_ZH} colors={DENY_COLORS} />
<h4>炮塔依据</h4>
<Legend names={LOOK_ZH} colors={LOOK_COLORS} />
</aside>
);
}
+179
View File
@@ -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<HTMLDivElement>(null);
const worldRef = useRef<World | undefined>(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 <div ref={hostRef} className="map3d" />;
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Playback controls and, for the selected bot, three strips over the whole battle: its behavior,
* the reason it did not fire, and why its turret pointed where it did. Click a strip to seek.
*/
import type { TraceBattle } from '@wto/ground-sim';
import { useEffect, useRef } from 'react';
import { BEHAVIOR_COLORS, DENY_COLORS, LOOK_COLORS } from './labels.ts';
interface Props {
readonly battle: TraceBattle;
readonly t: number;
readonly playing: boolean;
readonly speed: number;
readonly selected: string | undefined;
readonly onSeek: (t: number) => void;
readonly onPlaying: (playing: boolean) => void;
readonly onSpeed: (speed: number) => void;
}
const SPEEDS = [0.5, 1, 2, 4, 8, 16];
const STRIP_H = 10;
function drawStrips(canvas: HTMLCanvasElement, battle: TraceBattle, eid: string | undefined, t: number): void {
const ctx = canvas.getContext('2d');
if (ctx === null) return;
const w = canvas.width;
const span = Math.max(1, battle.endT - battle.startT);
ctx.fillStyle = '#16181a';
ctx.fillRect(0, 0, w, canvas.height);
if (eid !== undefined) {
const frames = battle.frames;
for (let i = 0; i < frames.length; i++) {
const f = frames[i];
const bot = f?.bots.get(eid);
if (f === undefined || bot === undefined) continue;
const x0 = ((f.t - battle.startT) / span) * w;
const x1 = (((frames[i + 1]?.t ?? f.t + 0.5) - battle.startT) / span) * w;
const bw = Math.max(1, x1 - x0);
ctx.fillStyle = BEHAVIOR_COLORS[bot.behavior] ?? '#444';
ctx.fillRect(x0, 0, bw, STRIP_H);
ctx.fillStyle = DENY_COLORS[bot.deny] ?? '#444';
ctx.fillRect(x0, STRIP_H + 2, bw, STRIP_H);
ctx.fillStyle = LOOK_COLORS[bot.lookReason] ?? '#444';
ctx.fillRect(x0, 2 * (STRIP_H + 2), bw, STRIP_H);
}
}
const cx = ((t - battle.startT) / span) * w;
ctx.fillStyle = '#fff';
ctx.fillRect(cx - 1, 0, 2, canvas.height);
}
export function Timeline({ battle, t, playing, speed, selected, onSeek, onPlaying, onSpeed }: Props): React.JSX.Element {
const stripRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const c = stripRef.current;
if (c === null) return;
c.width = Math.max(1, Math.floor(c.getBoundingClientRect().width));
drawStrips(c, battle, selected, t);
}, [battle, selected, t]);
return (
<div className="timeline">
<div className="controls">
<button type="button" onClick={() => onPlaying(!playing)}>{playing ? '暂停' : '播放'}</button>
<select value={speed} onChange={(e) => onSpeed(Number(e.target.value))}>
{SPEEDS.map((s) => <option key={s} value={s}>{s}×</option>)}
</select>
<span className="time">{t.toFixed(1)} s / {battle.endT.toFixed(0)} s</span>
<input
type="range" min={battle.startT} max={battle.endT} step={0.1} value={t}
onChange={(e) => onSeek(Number(e.target.value))}
/>
</div>
<div className="strip-labels"><span>行为</span><span>拒绝开火</span><span>炮塔依据</span></div>
<canvas
ref={stripRef}
className="strips"
height={3 * (STRIP_H + 2)}
onClick={(e) => {
const w = e.currentTarget.width;
onSeek(battle.startT + (e.nativeEvent.offsetX / w) * (battle.endT - battle.startT));
}}
/>
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */
import {
decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle,
} from '@wto/ground-sim';
export interface LogEntry {
readonly name: string;
readonly size: number;
readonly mtime: number;
}
export interface MapEntry {
readonly level: string;
readonly pois: boolean;
/** 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<Response> {
const res = await fetch(url);
if (!res.ok) {
const body = await res.text();
throw new Error(`${url}: ${res.status} ${body}`);
}
return res;
}
export async function fetchMaps(): Promise<MapEntry[]> {
return (await (await get('/api/maps')).json()) as MapEntry[];
}
export async function fetchLogs(): Promise<LogEntry[]> {
return (await (await get('/api/logs')).json()) as LogEntry[];
}
export async function loadLog(name: string): Promise<TraceBattle[]> {
const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text();
return parseTraceLog(text);
}
export async function loadMap(entry: MapEntry): Promise<MapData> {
const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer());
const pois = entry.pois
? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text())
: undefined;
const scene = entry.scene
? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer()))
: undefined;
return { pack: readNavPack(bytes), pois, scene };
}
+95
View File
@@ -0,0 +1,95 @@
/** Looking up the battle state at any time between two trace samples. */
import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '@wto/ground-sim';
export interface UnitAt {
readonly unit: UnitSample;
/** Interpolated position, 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;
}
export interface SceneAt {
readonly t: number;
readonly units: Map<string, UnitAt>;
readonly caps: CapSample[];
}
/** Index of the last frame at or before `t` (-1 before the first). */
export function frameIndexAt(battle: TraceBattle, t: number): number {
let lo = 0;
let hi = battle.frames.length - 1;
let found = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if ((battle.frames[mid]?.t ?? Infinity) <= t) { found = mid; lo = mid + 1; } else hi = mid - 1;
}
return found;
}
function lerpYaw(a: number, b: number, k: number): number {
const d = ((((b - a) % 360) + 540) % 360) - 180;
return a + d * k;
}
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];
const b = battle.frames[i + 1];
const units = new Map<string, UnitAt>();
if (a === undefined) return { t, units, caps: [] };
const k = b !== undefined && b.t > a.t ? Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t))) : 0;
for (const [eid, ua] of a.units) {
const ub = b?.units.get(eid);
const move = ub !== undefined && ua.alive && ub.alive ? k : 0;
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: 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),
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 };
}
/** Events with time in [from, to], from the sorted event list. */
export function eventsBetween(battle: TraceBattle, from: number, to: number): TraceEvent[] {
let lo = 0;
let hi = battle.events.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if ((battle.events[mid]?.t ?? Infinity) < from) lo = mid + 1; else hi = mid;
}
const out: TraceEvent[] = [];
for (let i = lo; i < battle.events.length; i++) {
const e = battle.events[i];
if (e === undefined || e.t > to) break;
out.push(e);
}
return out;
}
+37
View File
@@ -0,0 +1,37 @@
/** Chinese display names for the trace codes (the codes themselves are in @wto/ground-sim). */
export const BEHAVIOR_ZH = ['推进', '交战推进', '短停', '回掩体', '换位', '守位', '疏散', '撤回', '维修'] as const;
export const BEHAVIOR_COLORS = ['#6c8ebf', '#e0884a', '#e5d34a', '#8fbf6c', '#b07cc6', '#5fb8b0', '#9a9a9a', '#c65f5f', '#7a5a3a'] as const;
export const STATE_ZH: Readonly<Record<number, string>> = {
0: '行军', 1: '行进交战', 3: '短停', 4: '退入掩体', 5: '掩体装填', 7: '原地守位', 8: '换位',
9: '失能', 10: '疏散', 11: '坡脊撤回',
};
export const DENY_ZH = [
'放行', '无目标', '炮未就绪', '命中概率不足', '远距窗口不足', '瞄准误差', '等待炮管稳定', '检查预算',
'炮口有硬物', '弹道有硬物', '友军', '多炮检查', '射界外', '点射间歇',
] as const;
export const DENY_COLORS = [
'#4caf50', '#333', '#666', '#e53935', '#8e24aa', '#fb8c00', '#fdd835', '#90a4ae',
'#6d4c41', '#795548', '#03a9f4', '#9e9e9e', '#d81b60', '#26a69a',
] as const;
export const LOOK_ZH = ['—', '交战目标', '威胁', '目标消失处', '记忆位置', '线索', '扫视'] as const;
export const LOOK_COLORS = ['#333', '#e53935', '#fb8c00', '#fdd835', '#8e24aa', '#03a9f4', '#607d8b'] as const;
export const COMMAND_ZH = ['主攻', '侧翼', '架枪', '防守', '预备', '防空'] as const;
export const URGENCY_ZH = ['低', '中', '高'] as const;
export const LANE_ZH = ['中路', '左翼', '右翼'] as const;
export const CLASS_ZH = ['中坦', '轻坦', '重坦', '歼击车', '防空'] as const;
export function zh(names: readonly string[] | Readonly<Record<number, string>>, code: number): string {
const name = Array.isArray(names) ? names[code] : (names as Readonly<Record<number, string>>)[code];
return name ?? String(code);
}
+7
View File
@@ -0,0 +1,7 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.tsx';
import './style.css';
const root = document.getElementById('root');
if (root !== null) createRoot(root).render(<StrictMode><App /></StrictMode>);
+89
View File
@@ -0,0 +1,89 @@
/**
* 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';
export interface MapLayer {
readonly canvas: HTMLCanvasElement;
/** World x of the canvas's left edge and world z of its top edge. */
readonly x0: number;
readonly z1: number;
readonly pxPerM: number;
}
export interface MapLayerOptions {
readonly tier: number;
readonly exposure: boolean;
readonly covers: boolean;
}
const AREA_COLORS: Readonly<Record<string, string>> = {
road: '#77786a', bridge: '#a0a090', ground: '#3d4a33', rough: '#5a4d34', forest: '#29402a',
crushable: '#4f5f35', shallowWater: '#35607a', chokepoint: '#7a6a35', exposed: '#5f5f33',
deepWater: '#1d3a66', noGo: '#3a2626',
};
export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer {
const [x0, , z0] = pack.header.bmin;
const [x1, , z1] = pack.header.bmax;
const pxPerM = Math.min(2, 4096 / Math.max(x1 - x0, z1 - z0));
const canvas = document.createElement('canvas');
canvas.width = Math.ceil((x1 - x0) * pxPerM);
canvas.height = Math.ceil((z1 - z0) * pxPerM);
const ctx = canvas.getContext('2d');
if (ctx === null) return { canvas, x0, z1, pxPerM };
// 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) {
for (let area = 1; area < NAV_AREA_NAMES.length; area++) {
ctx.beginPath();
for (let i = 0; i < tier.polyCount; i++) {
if (tier.areas[i] !== area) continue;
const ring = tier.rings[i];
if (ring === undefined) continue;
for (let k = 0; k < ring.length; k += 2) {
const px = ((ring[k] ?? 0) - x0) * pxPerM;
const py = (z1 - (ring[k + 1] ?? 0)) * pxPerM;
if (k === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
}
ctx.closePath();
}
ctx.fillStyle = AREA_COLORS[NAV_AREA_NAMES[area] ?? ''] ?? '#444';
ctx.fill();
}
}
if (opts.exposure) drawExposure(ctx, pack, x0, z1, pxPerM);
if (opts.covers) drawCovers(ctx, pack, x0, z1, pxPerM);
return { canvas, x0, z1, pxPerM };
}
function drawExposure(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
const g = pack.tactical;
const cell = g.cellM * pxPerM;
for (let r = 0; r < g.rows; r++) {
for (let c = 0; c < g.cols; c++) {
const e = g.exposure[r * g.cols + c] ?? 0;
if (e < 16) continue;
ctx.fillStyle = `rgba(255, 80, 40, ${(e / 255) * 0.45})`;
const wx = g.origin[0] + c * g.cellM;
const wz = g.origin[1] + r * g.cellM;
ctx.fillRect((wx - x0) * pxPerM, (z1 - wz - g.cellM) * pxPerM, cell, cell);
}
}
}
function drawCovers(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
for (const cv of pack.covers) {
const px = (cv.pos[0] - x0) * pxPerM;
const py = (z1 - cv.pos[2]) * pxPerM;
ctx.strokeStyle = cv.kind === 1 ? 'rgba(120, 220, 255, 0.8)' : 'rgba(255, 230, 120, 0.8)';
ctx.beginPath();
ctx.moveTo(px, py);
ctx.lineTo(px + cv.coverDir[0] * 6 * pxPerM, py - cv.coverDir[1] * 6 * pxPerM);
ctx.stroke();
}
}
+30
View File
@@ -0,0 +1,30 @@
* { box-sizing: border-box; }
html, body, #root { margin: 0; height: 100%; background: #0b0c0d; color: #ddd; font: 13px/1.4 system-ui, 'Microsoft YaHei', sans-serif; }
.app { display: flex; flex-direction: column; height: 100%; }
header { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 6px 10px; background: #16181a; border-bottom: 1px solid #2a2d30; }
header select { max-width: 420px; }
header label { display: inline-flex; align-items: center; gap: 3px; }
.status { color: #ffb74d; }
main { flex: 1; display: flex; min-height: 0; }
.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; }
.inspector td { padding: 2px 0; }
.inspector h4 { margin: 12px 0 4px; color: #aaa; font-weight: normal; }
.hint { color: #999; }
.events { font-size: 12px; }
.events div { padding: 1px 0; border-bottom: 1px solid #1d2023; word-break: break-all; }
.events span { color: #999; }
.legend { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; }
.legend i { display: inline-block; width: 10px; height: 10px; margin-right: 3px; vertical-align: -1px; }
.timeline { padding: 6px 10px; background: #16181a; border-top: 1px solid #2a2d30; }
.controls { display: flex; gap: 8px; align-items: center; }
.controls input[type='range'] { flex: 1; }
.time { min-width: 120px; font-variant-numeric: tabular-nums; }
.strip-labels { display: flex; gap: 12px; font-size: 11px; color: #888; margin-top: 4px; }
canvas.strips { width: 100%; height: 36px; display: block; cursor: pointer; }
+119
View File
@@ -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();
}
}
+18
View File
@@ -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);
}
+134
View File
@@ -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<BufferGeometry, MeshLambertMaterial>;
/** 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;
}
+182
View File
@@ -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();
}
});
}
}
+141
View File
@@ -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<Record<number, number>> = { 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<string, Tank>();
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<string, UnitAt>, 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();
}
}
+23
View File
@@ -0,0 +1,23 @@
{
// The lab is a Vite page plus its dev-server API (server/), so it has its own settings and stays
// out of the root typecheck, like the launcher.
"compilerOptions": {
"target": "ES2023",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": ["node"],
"jsx": "react-jsx",
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "server/**/*.ts", "vite.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { labApi } from './server/lab-api.ts';
export default defineConfig({
plugins: [react(), labApi()],
server: { host: '127.0.0.1', port: 47180, strictPort: false },
});
@@ -562,12 +562,17 @@
"loadout": "Ground AI spawn ammunition",
"commander": "Commander & role quotas",
"macro": "Macro capture & SPAA",
"stateMachine": "Hull state machine & repair",
"stateMachine": "Hull actions & repair",
"perception": "Visual perception & exposure",
"tactics": "Situational awareness & memory",
"estimation": "Lead estimation & aim bias",
"threat": "Threat assessment",
"turret": "Turret attention",
"behavior": "Hull behavior",
"fireControl": "Fire control & fire gate",
"navigation": "Driving & navigation",
"navEngine": "Map navigation mesh & path costs",
"pathFollow": "Path following & unstick",
"crowd": "Spacing & crowd dispersal",
"terrain": "Terrain & ridge limits",
"runtime": "Tick cadence & diagnostics"
@@ -578,12 +583,17 @@
"loadout": "Ready-rack carry count and primary/secondary shell split",
"commander": "Role percentages by game mode, flank lanes, rally and recall",
"macro": "Opening split, cap occupancy, death zones and SPAA positioning",
"stateMachine": "Short halts, reload cover retreat, angling, repositioning and repair",
"stateMachine": "Short halts, reload cover retreat, repositioning and repair",
"perception": "Foliage transparency, exposure accumulation and decay",
"tactics": "Vision range, audio detection, radio sharing and target memory",
"estimation": "Sample-based velocity lead, exit watch and natural shot spread",
"fireControl": "Range bands, speed gates, barrel settle and ballistic safety",
"navigation": "Drive backend, corner braking, pivot turns and unstick reverse",
"threat": "How dangerous each discovered enemy is: distance, aim, line of sight and recent hits",
"turret": "Where the turret looks without a target: threats, cues and scanning along the route",
"behavior": "Scores of the hull behaviors, commitment, facing the main threat and driving backwards",
"fireControl": "Hit probability and fire threshold, autocannon bursts, secondary weapons, barrel settle and ballistic safety",
"navigation": "Drive backend, pivot turns and tactical reverse",
"navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles",
"pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, passing stopped vehicles and wrecks, giving way, three-level unstick and temporary path costs",
"crowd": "Personal space and ally cluster dispersal",
"terrain": "Climb/drop slope limits, water depth and ridge peek caps",
"runtime": "Script update intervals and telemetry logging"
@@ -642,17 +652,12 @@
"enemySpawnAvoidM": "Enemy spawn avoidance distance"
},
"stateMachine": {
"preaimAngleDeg": "Moving pre-aim angle threshold",
"movingShotWaitSec": "Time to attempt a moving shot before halting",
"shortHaltMaxSec": "Short halt max duration",
"shortHaltCooldownSec": "Short halt cooldown",
"turnLaunchSpeedMps": "Turn launch target speed",
"coverMinDistM": "Cover search min distance",
"coverMaxDistM": "Cover search max distance",
"coverRetreatBudgetSec": "Reload cover retreat max duration",
"reloadAdvanceAngleDeg": "Reload zigzag advance angle",
"hullAngleTriggerDeg": "Hull angling trigger angle",
"hullAngleTargetDeg": "Target hull angling offset",
"maxTotalHaltSec": "Max cumulative halt before reposition",
"stalemateMissShots": "Ineffective shots before reposition",
"stalemateNoShotHalts": "No-shot halts before reposition",
@@ -668,13 +673,18 @@
"normalSpotSec": "Normal exposure spot time",
"farSpotSec": "Long-range exposure spot time",
"decayPerSec": "Exposure decay rate per second",
"frontConeHalfDeg": "Forward vision cone half-angle",
"peripheralCloseM": "Close peripheral spot distance"
"gunFovHalfDeg": "Gun sight half-angle",
"nearAwareM": "Close all-round awareness range",
"nearArcDeg": "Close awareness arc around the barrel",
"midAwareM": "Medium awareness range (barrel front hemisphere)",
"nearSpotMul": "Close awareness spotting time multiplier",
"midSpotMul": "Commander awareness spotting time multiplier",
"lookAroundSec": "Look-around interval",
"lookAroundHoldSec": "Look-around duration",
"discoverScore": "Exposure at which an enemy counts as discovered"
},
"tactics": {
"visionRangeM": "Max visual detection range",
"visionFovDeg": "Vision field of view",
"peripheralRangeM": "Peripheral detection range",
"engineAudioRangeM": "Engine audio hearing range",
"shotAudioRangeM": "Gunshot audio hearing range",
"radioShareRangeM": "Allied radio sharing range",
@@ -692,24 +702,95 @@
"leadErrorFrac": "Lead estimation error fraction",
"maxBiasM": "Max per-opportunity aim bias"
},
"threat": {
"rangeScaleM": "Distance at which danger halves",
"discoveredMul": "Danger multiplier until seen clearly",
"aimConeDeg": "Cone in which an enemy counts as aiming at the bot",
"notAimingMul": "Danger multiplier when not aiming at the bot",
"unseenMul": "Danger multiplier when the bot is out of its sight",
"hitMemorySec": "How long a hit raises the shooter's danger",
"hitMul": "Danger multiplier after a hit"
},
"turret": {
"minDwellSec": "Minimum time on a chosen look direction",
"switchMargin": "Extra danger needed to turn from the engaged target",
"scanArcDeg": "Scan arc either side of the route",
"scanPeriodSec": "Scan sweep period",
"fixedMountYawSpanDeg": "Max yaw range for hull-mounted guns"
},
"behavior": {
"scoreIntervalSec": "Behavior scoring interval",
"advanceHoldSec": "Advance commitment",
"engageHoldSec": "Engage while moving commitment",
"haltHoldSec": "Short halt commitment",
"coverHoldSec": "Take cover commitment",
"repositionHoldSec": "Reposition commitment",
"postHoldSec": "Hold position commitment",
"disperseHoldSec": "Disperse commitment",
"targetValueWeight": "Weight of a viable shot while moving",
"nearThreatHaltBonus": "Short-halt bonus under a close threat",
"switchMargin": "Extra score needed to switch behavior",
"advanceScore": "Score: advance along the order route",
"engageScore": "Score: engage on the move",
"urgencyWeight": "Score shift by order urgency",
"haltScore": "Score: short halt for a shot",
"crossfirePenalty": "Short-halt penalty per extra enemy aiming at the bot",
"coverScore": "Score: pull back to cover to reload",
"coverDangerWeight": "Cover score added by threat danger",
"coverOffensivePenalty": "Cover penalty on an urgent attack",
"coverRetrySec": "Wait before searching for cover again after none was found",
"repositionScore": "Score: change firing position when the engagement is stuck",
"holdScore": "Score: hold the post, watch the last exit or wait at the rally point",
"disperseScore": "Score: spread out of a crowd",
"urgentSpeedKeep": "Share of march speed an urgent bot keeps when slowing for a shot",
"hullAngleDeg": "Hull angle to the main threat",
"faceToleranceDeg": "Facing tolerance while standing",
"faceMinDanger": "Threat danger needed to face it",
"reverseTravelAngleDeg": "Threat angle off the travel direction for driving backwards",
"reverseMaxTurnDistM": "Max distance to the next turn or route end when reversing",
"reverseMinSpeedMps": "Lowest top reverse speed for driving backwards",
"reverseHoldSec": "Minimum time between switching forwards and backwards"
},
"fireControl": {
"maxEngageRangeM": "Max engagement range",
"closeRangeM": "Close range band threshold",
"midRangeM": "Mid range band threshold",
"longRangeM": "Long range band threshold",
"midSlowSpeedRatio": "Mid-range fire-on-move speed ratio",
"midSlowMaxMps": "Mid-range fire-on-move speed cap",
"closeRangeMaxSpeedKmh": "Moving-fire speed cap at the close-range boundary",
"pointBlankMaxSpeedKmh": "Moving-fire speed cap at point blank",
"stopSpeedMaxMps": "Stopped speed threshold",
"longRangeWindowSec": "Long-range clear LOS window",
"baseAlignDeg": "Base gun alignment tolerance",
"closeHitRadiusM": "Close-range hit acceptance radius",
"barrelSettleDegSec": "Max aim error drift outside close range",
"closeSettleHoldSec": "Close-range settle hold time",
"settleHoldSec": "Standard settle hold time",
"unstabilizedStopSpeedMps": "Unstabilized stop speed cap",
"stabilizedCreepSpeedMps": "Stabilized creep fire speed cap",
"aimErrorDeg": "Crew aim error (spread)",
"moveErrDegPerMps": "Aim error per m/s of own speed",
"turnErrDegPerDegSec": "Aim error per deg/s of hull turn",
"stabErrFactor": "Motion error factor with a stabilizer",
"targetHalfHeightM": "Half height of a fully visible target",
"fireThreshold": "Base hit probability needed to fire",
"minFireThreshold": "Lowest fire threshold",
"aimingThresholdBonus": "Threshold drop when the target aims at the bot",
"closeThresholdBonus": "Threshold drop at point blank",
"enemyReloadThresholdBonus": "Threshold drop after the target fired",
"enemyReloadSec": "How long a target counts as reloading after it fired",
"fleetingThresholdBonus": "Threshold drop for a target about to slip away",
"fleetingLateralMps": "Crossing speed of a slipping-away target",
"fleetingLookAheadSec": "Look-ahead for losing line of sight",
"reloadThresholdPenalty": "Fire-threshold increase for long reloads",
"longReloadSec": "Reload time for the full threshold penalty",
"lowAmmoRounds": "Ammunition count below which shots are conserved",
"lowAmmoThresholdPenalty": "Fire-threshold increase with little ammunition",
"aimSkill": "Crew skill for aiming spread",
"autocannonMinShotsPerSec": "Minimum firing rate for automatic cannons (rounds/s)",
"retreatThresholdPenalty": "Threshold rise while pulling back to cover",
"minShotIntervalSec": "Minimum main-gun shot interval",
"autocannonAimSlack": "Autocannon aim slack (times target size)",
"burstSec": "Burst length",
"burstPauseSec": "Pause between bursts",
"autocannonReloadDetectSec": "Autocannon not-ready time that counts as a reload",
"auxWeapons": "Fire secondary and coaxial weapons",
"auxMaxRangeM": "Secondary and coaxial weapon range",
"auxFireAtArmor": "Coaxial weapons also fire at non-light vehicles",
"friendlyCorridorM": "Friendly fire corridor width",
"ballisticStepMaxM": "Ballistic occlusion step length",
"ballisticSweepRadiusM": "Ballistic sphere sweep radius",
@@ -721,15 +802,89 @@
"steerSign": "Steering input polarity",
"deadEchoSec": "Dead-echo detection timeout",
"controlTimeoutSec": "Native control release timeout",
"cornerBrakeAccel": "Corner braking deceleration",
"movingFireSpeedRampMps": "Speed error for full throttle or braking while firing on the move",
"pivotAngleDeg": "Neutral pivot turn angle threshold",
"stuckWindowSec": "Stuck detection window",
"stuckMinMoveM": "Stuck min movement distance",
"unstickReverseSec": "Unstick reverse duration",
"tacticalReverseDistM": "Tactical reverse max distance",
"tacticalReverseMaxSec": "Tactical reverse max duration"
},
"navEngine": {
"enabled": "Use map navigation packs",
"allowFallback": "Fall back to the old pathing for the battle when a pack is missing or broken",
"snapRadiusM": "Max distance from a path's start or goal to the mesh",
"goalSnapRadiusM": "Max distance a path goal may be moved onto the mesh",
"pathBudgetMsPerFrame": "Path search time per frame",
"trafficCostPerPath": "Team traffic · extra path cost per teammate route",
"trafficCostMaxMul": "Team traffic · max path cost multiplier",
"trafficHoldSec": "Team traffic · how long a planned route counts",
"cornerOffsetM": "Distance path corners keep from the walls they turn around"
},
"navCostsTracked": {
"road": "Tracked · road cost",
"bridge": "Tracked · bridge cost",
"ground": "Tracked · open ground cost",
"rough": "Tracked · steep or rocky ground cost",
"forest": "Tracked · forest cost",
"crushable": "Tracked · crushable obstacle cost",
"shallowWater": "Tracked · shallow water cost",
"chokepoint": "Tracked · chokepoint multiplier"
},
"navCostsWheeled": {
"road": "Wheeled · road cost",
"bridge": "Wheeled · bridge cost",
"ground": "Wheeled · open ground cost",
"rough": "Wheeled · steep or rocky ground cost",
"forest": "Wheeled · forest cost",
"crushable": "Wheeled · crushable obstacle cost",
"shallowWater": "Wheeled · shallow water cost",
"chokepoint": "Wheeled · chokepoint multiplier"
},
"pathFollow": {
"replanIntervalSec": "Regular path replanning interval",
"replanGoalMoveM": "Goal movement that triggers a new path",
"offCorridorReplanM": "Distance off the path that triggers a new path",
"lookaheadTimeSec": "Lookahead time at current speed",
"trackedLookaheadMinM": "Tracked · min lookahead distance",
"trackedLookaheadMaxM": "Tracked · max lookahead distance",
"wheeledLookaheadMinM": "Wheeled · min lookahead distance",
"wheeledLookaheadMaxM": "Wheeled · max lookahead distance",
"cornerAngleDeg": "Path corner angle that needs slowing down",
"cornerLateralAccelMps2": "Allowed sideways acceleration in corners",
"cornerBrakeDecelMps2": "Braking deceleration before corners and the destination",
"arriveRadiusM": "Arrival radius at the destination",
"arriveMinSpeedMps": "Min speed while approaching the destination",
"narrowWallMarginM": "Room to the mesh edge below which a passage counts as narrow",
"narrowSpeedMps": "Speed cap in narrow passages",
"bumperRayM": "Front corner ray length",
"bumperStopM": "Stop distance before an obstacle hit by the front rays",
"bumperBlockSec": "Time blocked before an obstacle is reported",
"trafficTtcSec": "Vehicle collision look-ahead time",
"yieldWaitMaxSec": "Max wait while giving way in narrow passages",
"stationarySpeedMps": "Speed below which a vehicle counts as an obstacle",
"passMarginM": "Gap kept between hulls when passing",
"passSpeedMps": "Speed cap while passing an obstacle",
"blockWaitSec": "Wait before a blocked passage is marked and replanned",
"blockTtlSec": "Blocked passage cost duration",
"contactGapM": "Gap to an obstacle that counts as contact",
"contactReverseSec": "Time in contact before backing off",
"contactRepeatSec": "Window in which a second contact counts as a repeat",
"stuckWindowSec": "Stuck detection window",
"stuckMinProgressM": "Min progress within the stuck window",
"unstickReverseM": "Unstick reverse distance",
"unstickReverseSec": "Unstick reverse max duration",
"unstickRepeatSec": "Time within which a repeated stuck escalates",
"unstickMaxAttempts": "Unstick attempts before giving up the order",
"jamRadiusM": "Jam cost radius",
"jamCostMul": "Jam path cost multiplier",
"jamTtlSec": "Jam cost duration",
"giveUpRadiusM": "Given-up place cost radius",
"giveUpCostMul": "Given-up place path cost multiplier",
"rubbleRadiusM": "Fresh obstacle cost radius",
"rubbleCostMul": "Fresh obstacle path cost multiplier",
"rubbleTtlSec": "Fresh obstacle cost duration",
"wreckRadiusM": "Wreck cost radius",
"wreckCostMul": "Wreck path cost multiplier",
"wreckTtlSec": "Wreck cost duration"
},
"crowd": {
"personalSpaceM": "Personal spacing distance",
"clusterRadiusM": "Ally cluster detection radius",
@@ -754,7 +909,14 @@
},
"diagnostics": {
"telemetry": "Enable AI telemetry logs",
"telemetryIntervalSec": "Telemetry logging interval"
"telemetryIntervalSec": "Telemetry logging interval",
"battleStats": "Log battle statistics for comparing builds",
"statsLogIntervalSec": "Battle statistics logging interval",
"statsSampleSec": "Statistics sampling interval per bot",
"statsSampleRangeM": "Range of the nearest-enemy statistics sample",
"statsRearArcDeg": "Rear arc counted as showing the rear",
"trace": "Log the AI replay trace",
"traceIntervalSec": "AI replay trace sampling interval"
}
},
"shared": "These settings apply to all saves in this client.",
@@ -562,12 +562,17 @@
"loadout": "陆战 AI 出生携弹",
"commander": "指挥层与分路配额",
"macro": "宏观占点与防空",
"stateMachine": "单车状态机与掩体维修",
"stateMachine": "车体动作与掩体维修",
"perception": "视觉感知与曝光",
"tactics": "态势感知与目标记忆",
"estimation": "目击测速与瞄准偏差",
"threat": "威胁评估",
"turret": "炮塔关注方向",
"behavior": "车体行为",
"fireControl": "火控与开火许可",
"navigation": "机动与寻路控制",
"navEngine": "地图导航网格与通行代价",
"pathFollow": "跟路驾驶与脱困",
"crowd": "编队间距与避让",
"terrain": "地形与棱线约束",
"runtime": "运行频率与诊断"
@@ -578,12 +583,17 @@
"loadout": "待发架携弹量与主/副弹种分配",
"commander": "各模式进攻 / 侧翼 / 架枪比例、集结与回防",
"macro": "开局分兵、占点人数、死亡区规避与防空站位",
"stateMachine": "短停预算、装填回缩、摆角、换位与受损维修",
"stateMachine": "短停预算、装填回缩、换位与受损维修",
"perception": "植被透光、曝光累计速度与衰减",
"tactics": "视距、听觉发现范围、电台共享与记忆时长",
"estimation": "本车目击测速、守出口时长与自然散布",
"fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤",
"navigation": "底层驱动方式、转向刹车与脱困倒车",
"threat": "每个已发现敌人的危险程度:距离、是否瞄着本车、视线与最近是否命中本车",
"turret": "没有目标时炮塔看哪里:威胁、线索与沿路线扫视",
"behavior": "车体各行为的得分、承诺时间、车头对主威胁与倒车跟路",
"fireControl": "命中概率与开火门槛、机炮点射、副武器、炮管稳定和弹道安全",
"navigation": "驱动方式、原地转向与战术倒车",
"navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价",
"pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、绕过停车和残骸、会车让路、三级脱困与临时寻路代价",
"crowd": "友军安全间距与扎堆疏散",
"terrain": "爬坡 / 下坡角度、涉水深度与探头限制",
"runtime": "脚本刷新间隔与调试遥测日志"
@@ -642,17 +652,12 @@
"enemySpawnAvoidM": "敌方出生点规避距离"
},
"stateMachine": {
"preaimAngleDeg": "行进预瞄角度阈值",
"movingShotWaitSec": "转入短停前尝试行进射击的时间",
"shortHaltMaxSec": "单次短停最长时间",
"shortHaltCooldownSec": "短停冷却时间",
"turnLaunchSpeedMps": "甩弯起步目标车速",
"coverMinDistM": "掩体搜索最小距离",
"coverMaxDistM": "掩体搜索最大距离",
"coverRetreatBudgetSec": "装填回缩掩体最长用时",
"reloadAdvanceAngleDeg": "装填折线跃进偏角",
"hullAngleTriggerDeg": "触发车体摆角阈值",
"hullAngleTargetDeg": "车体目标摆角",
"maxTotalHaltSec": "累计停留强制换位上限",
"stalemateMissShots": "无伤害连射触发换位发数",
"stalemateNoShotHalts": "未开火短停触发换位次数",
@@ -668,13 +673,18 @@
"normalSpotSec": "常规曝光用时",
"farSpotSec": "远距曝光用时",
"decayPerSec": "失联曝光每秒衰减率",
"frontConeHalfDeg": "前向主视锥半角",
"peripheralCloseM": "近身余光发现距离"
"gunFovHalfDeg": "瞄准镜视野半角",
"nearAwareM": "近距环视感知距离",
"nearArcDeg": "以炮口为基准的近距感知角度",
"midAwareM": "中距感知距离(炮口前半球)",
"nearSpotMul": "近距感知看清耗时倍数",
"midSpotMul": "车长感知看清耗时倍数",
"lookAroundSec": "环视间隔",
"lookAroundHoldSec": "环视持续时间",
"discoverScore": "曝光积分达到多少算发现"
},
"tactics": {
"visionRangeM": "最大视觉索敌距离",
"visionFovDeg": "视野总张角",
"peripheralRangeM": "外围余光索敌距离",
"engineAudioRangeM": "引擎声听觉距离",
"shotAudioRangeM": "炮声听觉距离",
"radioShareRangeM": "友军电台报点共享距离",
@@ -692,24 +702,95 @@
"leadErrorFrac": "提前量误差比例",
"maxBiasM": "单次射击最大偏移上限"
},
"threat": {
"rangeScaleM": "危险度减半的距离",
"discoveredMul": "尚未看清时的危险度倍数",
"aimConeDeg": "算作对方瞄着本车的夹角范围",
"notAimingMul": "对方没瞄着本车时的危险度倍数",
"unseenMul": "本车不在对方视线内时的危险度倍数",
"hitMemorySec": "被命中后提高射手危险度的时长",
"hitMul": "被命中后的危险度倍数"
},
"turret": {
"minDwellSec": "选定的观察方向至少保持的时间",
"switchMargin": "从交战目标转向其他威胁所需高出的危险度",
"scanArcDeg": "沿路线向两侧扫视的角度",
"scanPeriodSec": "扫视一个来回的时长",
"fixedMountYawSpanDeg": "判定为固定炮座时的最大水平射界"
},
"behavior": {
"scoreIntervalSec": "行为打分间隔",
"advanceHoldSec": "推进承诺时间",
"engageHoldSec": "交战推进承诺时间",
"haltHoldSec": "短停射击承诺时间",
"coverHoldSec": "退入掩体承诺时间",
"repositionHoldSec": "换位承诺时间",
"postHoldSec": "守位承诺时间",
"disperseHoldSec": "疏散承诺时间",
"targetValueWeight": "运动中有机会命中的权重",
"nearThreatHaltBonus": "近距威胁下的短停加分",
"switchMargin": "切换行为所需高出的分数",
"advanceScore": "得分:沿任务路线推进",
"engageScore": "得分:交战推进",
"urgencyWeight": "任务紧迫度对得分的影响",
"haltScore": "得分:短停射击",
"crossfirePenalty": "每多一个瞄着本车的敌人,短停扣分",
"coverScore": "得分:退入掩体装填",
"coverDangerWeight": "威胁危险度对掩体得分的加成",
"coverOffensivePenalty": "紧急进攻时掩体扣分",
"coverRetrySec": "找不到掩体后再次搜索的间隔",
"repositionScore": "得分:交战僵持时换位",
"holdScore": "得分:守位、盯出口或在集结点等待",
"disperseScore": "得分:拥挤疏散",
"urgentSpeedKeep": "紧急任务为射击减速时保留的行军速度比例",
"hullAngleDeg": "车头对主威胁的倾角",
"faceToleranceDeg": "停车时朝向容差",
"faceMinDanger": "需要车头对准的威胁危险度下限",
"reverseTravelAngleDeg": "威胁偏离行进方向多少度时倒车跟路",
"reverseMaxTurnDistM": "倒车时距下一拐点或路线终点的最远距离",
"reverseMinSpeedMps": "倒车跟路所需的最低倒车极速",
"reverseHoldSec": "前进与倒车切换的最短间隔"
},
"fireControl": {
"maxEngageRangeM": "最大交战开火距离",
"closeRangeM": "近距交战分界距离",
"midRangeM": "中距交战分界距离",
"longRangeM": "远距交战分界距离",
"midSlowSpeedRatio": "中距行进射击最高车速比",
"midSlowMaxMps": "中距行进射击最高车速",
"closeRangeMaxSpeedKmh": "近距分界处行进射击最高车速",
"pointBlankMaxSpeedKmh": "贴身时行进射击最高车速",
"stopSpeedMaxMps": "停稳判定最高车速",
"longRangeWindowSec": "远距连续射界观察窗",
"baseAlignDeg": "主炮对准允许角误差",
"closeHitRadiusM": "近距命中判定半径",
"barrelSettleDegSec": "近距以外瞄准误差最大变化速度",
"closeSettleHoldSec": "近距稳定保持时间",
"settleHoldSec": "常规稳定保持时间",
"unstabilizedStopSpeedMps": "无稳定器停稳车速上限",
"stabilizedCreepSpeedMps": "带稳定器慢速射击上限",
"aimErrorDeg": "炮手瞄准误差(散布)",
"moveErrDegPerMps": "本车每 m/s 车速增加的瞄准误差",
"turnErrDegPerDegSec": "车体每 °/s 转向增加的瞄准误差",
"stabErrFactor": "有稳定器时行进误差的倍数",
"targetHalfHeightM": "完全露出的目标半高",
"fireThreshold": "开火所需的基础命中概率",
"minFireThreshold": "开火门槛下限",
"aimingThresholdBonus": "目标瞄着本车时门槛降低",
"closeThresholdBonus": "贴脸时门槛降低(近距内按距离过渡)",
"enemyReloadThresholdBonus": "目标刚开过火时门槛降低",
"enemyReloadSec": "目标开火后视为装填中的时长",
"fleetingThresholdBonus": "目标即将离开视线时门槛降低",
"fleetingLateralMps": "视为即将离开视线的横穿速度",
"fleetingLookAheadSec": "预判视线遮挡的时间",
"reloadThresholdPenalty": "装填时间长时提高开火门槛",
"longReloadSec": "开火门槛加满时的装填时间",
"lowAmmoRounds": "开始节省弹药的剩余发数",
"lowAmmoThresholdPenalty": "剩余弹药少时提高开火门槛",
"aimSkill": "影响瞄点散布的炮手技能",
"autocannonMinShotsPerSec": "识别机炮的最低射速(发/秒)",
"retreatThresholdPenalty": "退入掩体途中的门槛升高",
"minShotIntervalSec": "主炮最短开火间隔",
"autocannonAimSlack": "机炮放宽倍数(目标尺寸的倍数)",
"burstSec": "点射时长",
"burstPauseSec": "点射间隔",
"autocannonReloadDetectSec": "机炮持续未就绪多久算换弹",
"auxWeapons": "使用副炮和并列武器",
"auxMaxRangeM": "副炮和并列武器的射击距离",
"auxFireAtArmor": "并列武器也可以向非轻型车辆开火",
"friendlyCorridorM": "友军弹道禁射走廊宽度",
"ballisticStepMaxM": "弹道硬遮挡检测步长",
"ballisticSweepRadiusM": "弹道扫掠半径",
@@ -721,15 +802,89 @@
"steerSign": "转向输入方向",
"deadEchoSec": "无响应回声判定时长",
"controlTimeoutSec": "原生控制超时归还时长",
"cornerBrakeAccel": "弯道减速制动强度",
"movingFireSpeedRampMps": "行进射击时全油门或全制动对应的速度差",
"pivotAngleDeg": "原地中性转向角度阈值",
"stuckWindowSec": "卡死检测窗口时长",
"stuckMinMoveM": "卡死判定最小位移",
"unstickReverseSec": "脱困倒车持续时长",
"tacticalReverseDistM": "战术倒车最大距离",
"tacticalReverseMaxSec": "战术倒车最长时长"
},
"navEngine": {
"enabled": "启用地图导航包",
"allowFallback": "缺少或损坏时整局退回旧寻路",
"snapRadiusM": "起终点吸附到导航网格的最大距离",
"goalSnapRadiusM": "目标点吸附到导航网格的最远距离",
"pathBudgetMsPerFrame": "每帧寻路计算时间上限",
"trafficCostPerPath": "同队分流 · 每条队友路线增加的寻路代价",
"trafficCostMaxMul": "同队分流 · 寻路代价最高倍率",
"trafficHoldSec": "同队分流 · 规划出的路线计入多久",
"cornerOffsetM": "路线拐点离所绕墙角的距离"
},
"navCostsTracked": {
"road": "履带车 · 道路代价",
"bridge": "履带车 · 桥面代价",
"ground": "履带车 · 普通地面代价",
"rough": "履带车 · 陡坡碎石代价",
"forest": "履带车 · 树林代价",
"crushable": "履带车 · 可碾压障碍代价",
"shallowWater": "履带车 · 浅滩涉水代价",
"chokepoint": "履带车 · 窄口代价倍率"
},
"navCostsWheeled": {
"road": "轮式车 · 道路代价",
"bridge": "轮式车 · 桥面代价",
"ground": "轮式车 · 普通地面代价",
"rough": "轮式车 · 陡坡碎石代价",
"forest": "轮式车 · 树林代价",
"crushable": "轮式车 · 可碾压障碍代价",
"shallowWater": "轮式车 · 浅滩涉水代价",
"chokepoint": "轮式车 · 窄口代价倍率"
},
"pathFollow": {
"replanIntervalSec": "定时重新寻路间隔",
"replanGoalMoveM": "目标移动多远后重新寻路",
"offCorridorReplanM": "偏离路线多远后重新寻路",
"lookaheadTimeSec": "按当前车速前瞻的时间",
"trackedLookaheadMinM": "履带车 · 最短前瞻距离",
"trackedLookaheadMaxM": "履带车 · 最长前瞻距离",
"wheeledLookaheadMinM": "轮式车 · 最短前瞻距离",
"wheeledLookaheadMaxM": "轮式车 · 最长前瞻距离",
"cornerAngleDeg": "需要减速的路线拐角角度",
"cornerLateralAccelMps2": "过弯允许的横向加速度",
"cornerBrakeDecelMps2": "弯前和到达前的减速度",
"arriveRadiusM": "到达目标的判定半径",
"arriveMinSpeedMps": "接近目标时的最低车速",
"narrowWallMarginM": "离网格边缘小于多少算窄路",
"narrowSpeedMps": "窄路限速",
"bumperRayM": "车头两侧射线长度",
"bumperStopM": "车头射线碰到障碍时的停车距离",
"bumperBlockSec": "被挡多久后上报障碍",
"trafficTtcSec": "车辆碰撞预判时间",
"yieldWaitMaxSec": "窄路让路最长等待时间",
"stationarySpeedMps": "车速低于多少算作障碍物",
"passMarginM": "绕行时与对方车体保持的间距",
"passSpeedMps": "绕行障碍时的限速",
"blockWaitSec": "无路可绕时等待多久后标记并重新寻路",
"blockTtlSec": "被堵路段代价持续时间",
"contactGapM": "离障碍多近算作顶上",
"contactReverseSec": "顶上多久后倒车",
"contactRepeatSec": "多久内在同一处再顶上算作反复顶上",
"stuckWindowSec": "卡住检测窗口时长",
"stuckMinProgressM": "检测窗口内的最小前进距离",
"unstickReverseM": "脱困倒车距离",
"unstickReverseSec": "脱困倒车最长时长",
"unstickRepeatSec": "多久内再次卡住就升级处理",
"unstickMaxAttempts": "放弃当前任务前的脱困次数",
"jamRadiusM": "堵车点代价半径",
"jamCostMul": "堵车点寻路代价倍率",
"jamTtlSec": "堵车点代价持续时间",
"giveUpRadiusM": "放弃地点代价半径",
"giveUpCostMul": "放弃地点寻路代价倍率",
"rubbleRadiusM": "新障碍代价半径",
"rubbleCostMul": "新障碍寻路代价倍率",
"rubbleTtlSec": "新障碍代价持续时间",
"wreckRadiusM": "残骸代价半径",
"wreckCostMul": "残骸寻路代价倍率",
"wreckTtlSec": "残骸代价持续时间"
},
"crowd": {
"personalSpaceM": "单车安全个人空间",
"clusterRadiusM": "扎堆检测半径",
@@ -754,7 +909,14 @@
},
"diagnostics": {
"telemetry": "输出 AI 诊断遥测日志",
"telemetryIntervalSec": "遥测日志输出间隔"
"telemetryIntervalSec": "遥测日志输出间隔",
"battleStats": "输出用于版本对比的每局统计",
"statsLogIntervalSec": "每局统计的输出间隔",
"statsSampleSec": "每辆车的统计抽查间隔",
"statsSampleRangeM": "统计抽查最近敌人的范围",
"statsRearArcDeg": "算作车尾对敌的后方扇区角度",
"trace": "输出 AI 回放轨迹",
"traceIntervalSec": "回放轨迹的采样间隔"
}
},
"shared": "这些数值适用于此客户端的全部存档。",
@@ -54,7 +54,7 @@ function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningP
if (est.watchMaxSec < est.watchMinSec || est.velStableSpanSec <= est.velSampleMinSpanSec) return false;
const fc = mergeSection(effective.fireControl, patch.fireControl);
if (fc.midRangeM <= fc.closeRangeM || fc.longRangeM <= fc.midRangeM) return false;
return fc.pointBlankMaxSpeedKmh >= fc.closeRangeMaxSpeedKmh;
return fc.minFireThreshold <= fc.fireThreshold;
}
export function BotTuningPanel({ data, saving, onSave }: Props) {
@@ -68,6 +68,9 @@ function int(
};
}
/** Surfaces of the baked navigation mesh, in the order of tuning/ground-ai.jsonc navCosts*. */
const NAV_COST_FIELDS = ['road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint'] as const;
export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
{
id: 'general',
@@ -155,17 +158,12 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
defaultOpen: false,
customOnly: true,
fields: [
num('stateMachine', 'preaimAngleDeg', 1, 30, '°'),
num('stateMachine', 'movingShotWaitSec', 0.25, 5, 's'),
num('stateMachine', 'shortHaltMaxSec', 0.5, 12, 's'),
num('stateMachine', 'shortHaltCooldownSec', 0.5, 20, 's'),
num('stateMachine', 'turnLaunchSpeedMps', 0.5, 6, 'm/s'),
num('stateMachine', 'coverMinDistM', 2, 30, 'm'),
num('stateMachine', 'coverMaxDistM', 6, 80, 'm'),
num('stateMachine', 'coverRetreatBudgetSec', 1.5, 20, 's'),
num('stateMachine', 'reloadAdvanceAngleDeg', 0, 45, '°'),
num('stateMachine', 'hullAngleTriggerDeg', 15, 75, '°'),
num('stateMachine', 'hullAngleTargetDeg', 0, 35, '°'),
num('stateMachine', 'maxTotalHaltSec', 3, 40, 's'),
int('stateMachine', 'stalemateMissShots', 1, 8),
int('stateMachine', 'stalemateNoShotHalts', 1, 6),
@@ -186,8 +184,15 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('perception', 'normalSpotSec', 0.1, 3, 's'),
num('perception', 'farSpotSec', 0.3, 6, 's'),
num('perception', 'decayPerSec', 0.2, 10),
num('perception', 'frontConeHalfDeg', 10, 90, '°'),
num('perception', 'peripheralCloseM', 30, 250, 'm'),
num('perception', 'gunFovHalfDeg', 5, 90, '°'),
num('perception', 'nearAwareM', 30, 400, 'm'),
num('perception', 'nearArcDeg', 90, 360, '°'),
num('perception', 'midAwareM', 100, 1500, 'm'),
num('perception', 'nearSpotMul', 1, 5),
num('perception', 'midSpotMul', 1, 6),
num('perception', 'lookAroundSec', 2, 60, 's'),
num('perception', 'lookAroundHoldSec', 0.2, 5, 's'),
num('perception', 'discoverScore', 0.05, 0.95),
],
},
{
@@ -196,8 +201,6 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
customOnly: true,
fields: [
num('tactics', 'visionRangeM', 200, 3500, 'm'),
num('tactics', 'visionFovDeg', 40, 180, '°'),
num('tactics', 'peripheralRangeM', 30, 800, 'm'),
num('tactics', 'engineAudioRangeM', 10, 250, 'm'),
num('tactics', 'shotAudioRangeM', 50, 1200, 'm'),
num('tactics', 'radioShareRangeM', 50, 1500, 'm'),
@@ -221,6 +224,70 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('estimation', 'maxBiasM', 0, 6, 'm'),
],
},
{
id: 'threat',
defaultOpen: false,
customOnly: true,
fields: [
num('threat', 'rangeScaleM', 50, 3000, 'm'),
num('threat', 'discoveredMul', 0, 1),
num('threat', 'aimConeDeg', 5, 90, '°'),
num('threat', 'notAimingMul', 0, 1),
num('threat', 'unseenMul', 0, 1),
num('threat', 'hitMemorySec', 0, 60, 's'),
num('threat', 'hitMul', 1, 5),
],
},
{
id: 'turret',
defaultOpen: false,
customOnly: true,
fields: [
num('turret', 'minDwellSec', 0, 5, 's'),
num('turret', 'switchMargin', 0, 3),
num('turret', 'scanArcDeg', 0, 180, '°'),
num('turret', 'scanPeriodSec', 1, 30, 's'),
num('turret', 'fixedMountYawSpanDeg', 0, 180, '°'),
],
},
{
id: 'behavior',
defaultOpen: false,
customOnly: true,
fields: [
num('behavior', 'scoreIntervalSec', 0.1, 3, 's'),
num('behavior', 'advanceHoldSec', 0, 10, 's'),
num('behavior', 'engageHoldSec', 0, 10, 's'),
num('behavior', 'haltHoldSec', 0, 10, 's'),
num('behavior', 'coverHoldSec', 0, 10, 's'),
num('behavior', 'repositionHoldSec', 0, 10, 's'),
num('behavior', 'postHoldSec', 0, 10, 's'),
num('behavior', 'disperseHoldSec', 0, 10, 's'),
num('behavior', 'targetValueWeight', 0, 1),
num('behavior', 'nearThreatHaltBonus', 0, 1),
num('behavior', 'switchMargin', 0, 1),
num('behavior', 'advanceScore', 0, 1),
num('behavior', 'engageScore', 0, 1),
num('behavior', 'urgencyWeight', 0, 1),
num('behavior', 'haltScore', 0, 1),
num('behavior', 'crossfirePenalty', 0, 1),
num('behavior', 'coverScore', 0, 1),
num('behavior', 'coverDangerWeight', 0, 1),
num('behavior', 'coverOffensivePenalty', 0, 1),
num('behavior', 'coverRetrySec', 0.5, 30, 's'),
num('behavior', 'repositionScore', 0, 1),
num('behavior', 'holdScore', 0, 1),
num('behavior', 'disperseScore', 0, 1),
num('behavior', 'urgentSpeedKeep', 0, 1),
num('behavior', 'hullAngleDeg', 0, 45, '°'),
num('behavior', 'faceToleranceDeg', 3, 60, '°'),
num('behavior', 'faceMinDanger', 0, 2),
num('behavior', 'reverseTravelAngleDeg', 60, 180, '°'),
num('behavior', 'reverseMaxTurnDistM', 0, 200, 'm'),
num('behavior', 'reverseMinSpeedMps', 0.5, 10, 'm/s'),
num('behavior', 'reverseHoldSec', 0, 20, 's'),
],
},
{
id: 'fireControl',
defaultOpen: false,
@@ -230,19 +297,41 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('fireControl', 'closeRangeM', 30, 250, 'm'),
num('fireControl', 'midRangeM', 100, 600, 'm'),
num('fireControl', 'longRangeM', 300, 1500, 'm'),
num('fireControl', 'midSlowSpeedRatio', 0.1, 1),
num('fireControl', 'midSlowMaxMps', 1, 15, 'm/s'),
num('fireControl', 'closeRangeMaxSpeedKmh', 3.6, 100, 'km/h'),
num('fireControl', 'pointBlankMaxSpeedKmh', 3.6, 100, 'km/h'),
num('fireControl', 'stopSpeedMaxMps', 0.1, 2, 'm/s'),
num('fireControl', 'longRangeWindowSec', 1, 15, 's'),
num('fireControl', 'baseAlignDeg', 0.1, 3, '°'),
num('fireControl', 'closeHitRadiusM', 0.25, 2.2, 'm'),
num('fireControl', 'barrelSettleDegSec', 0.2, 12, '°/s'),
num('fireControl', 'closeSettleHoldSec', 0.02, 0.5, 's'),
num('fireControl', 'settleHoldSec', 0.05, 1.5, 's'),
num('fireControl', 'unstabilizedStopSpeedMps', 0.1, 3, 'm/s'),
num('fireControl', 'stabilizedCreepSpeedMps', 1.5, 15, 'm/s'),
num('fireControl', 'aimErrorDeg', 0.01, 2, '°'),
num('fireControl', 'moveErrDegPerMps', 0, 3, '°'),
num('fireControl', 'turnErrDegPerDegSec', 0, 0.5),
num('fireControl', 'stabErrFactor', 0.02, 1),
num('fireControl', 'targetHalfHeightM', 0.3, 2, 'm'),
num('fireControl', 'fireThreshold', 0.05, 0.95),
num('fireControl', 'minFireThreshold', 0.01, 0.9),
num('fireControl', 'aimingThresholdBonus', 0, 0.5),
num('fireControl', 'closeThresholdBonus', 0, 0.5),
num('fireControl', 'enemyReloadThresholdBonus', 0, 0.5),
num('fireControl', 'enemyReloadSec', 0, 15, 's'),
num('fireControl', 'fleetingThresholdBonus', 0, 0.5),
num('fireControl', 'fleetingLateralMps', 0.5, 15, 'm/s'),
num('fireControl', 'fleetingLookAheadSec', 0.1, 2, 's'),
num('fireControl', 'reloadThresholdPenalty', 0, 0.5),
num('fireControl', 'longReloadSec', 1, 60, 's'),
int('fireControl', 'lowAmmoRounds', 1, 60),
num('fireControl', 'lowAmmoThresholdPenalty', 0, 0.5),
num('fireControl', 'aimSkill', 0, 1),
num('fireControl', 'autocannonMinShotsPerSec', 0.5, 30),
num('fireControl', 'retreatThresholdPenalty', 0, 0.6),
num('fireControl', 'minShotIntervalSec', 0.1, 5, 's'),
num('fireControl', 'autocannonAimSlack', 1, 10),
num('fireControl', 'burstSec', 0.2, 6, 's'),
num('fireControl', 'burstPauseSec', 0, 5, 's'),
num('fireControl', 'autocannonReloadDetectSec', 0.1, 3, 's'),
{ id: 'groundAi.fireControl.auxWeapons', section: 'fireControl', field: 'auxWeapons', kind: 'bool' },
num('fireControl', 'auxMaxRangeM', 30, 1500, 'm'),
{ id: 'groundAi.fireControl.auxFireAtArmor', section: 'fireControl', field: 'auxFireAtArmor', kind: 'bool' },
num('fireControl', 'friendlyCorridorM', 1, 10, 'm'),
num('fireControl', 'ballisticStepMaxM', 5, 80, 'm'),
num('fireControl', 'ballisticSweepRadiusM', 0.02, 0.5, 'm'),
@@ -259,16 +348,82 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
{ id: 'groundAi.navigation.steerSign', section: 'navigation', field: 'steerSign', kind: 'steerSign' },
num('navigation', 'deadEchoSec', 0.3, 10, 's'),
num('navigation', 'controlTimeoutSec', 0.3, 10, 's'),
num('navigation', 'cornerBrakeAccel', 0.5, 8),
num('navigation', 'movingFireSpeedRampMps', 0.2, 5, 'm/s'),
num('navigation', 'pivotAngleDeg', 25, 150, '°'),
num('navigation', 'stuckWindowSec', 1, 15, 's'),
num('navigation', 'stuckMinMoveM', 0.5, 10, 'm'),
num('navigation', 'unstickReverseSec', 0.8, 10, 's'),
num('navigation', 'tacticalReverseDistM', 10, 90, 'm'),
num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'),
],
},
{
id: 'navEngine',
defaultOpen: false,
customOnly: true,
fields: [
{ id: 'groundAi.navEngine.enabled', section: 'navEngine', field: 'enabled', kind: 'bool' },
{ id: 'groundAi.navEngine.allowFallback', section: 'navEngine', field: 'allowFallback', kind: 'bool' },
num('navEngine', 'snapRadiusM', 2, 40, 'm'),
num('navEngine', 'goalSnapRadiusM', 5, 150, 'm'),
num('navEngine', 'pathBudgetMsPerFrame', 0.05, 5, 'ms'),
num('navEngine', 'trafficCostPerPath', 0, 3),
num('navEngine', 'trafficCostMaxMul', 1, 10),
num('navEngine', 'trafficHoldSec', 0, 120, 's'),
num('navEngine', 'cornerOffsetM', 0, 5, 'm'),
...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)),
...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)),
],
},
{
id: 'pathFollow',
defaultOpen: false,
customOnly: true,
fields: [
num('pathFollow', 'replanIntervalSec', 1, 15, 's'),
num('pathFollow', 'replanGoalMoveM', 3, 80, 'm'),
num('pathFollow', 'offCorridorReplanM', 3, 60, 'm'),
num('pathFollow', 'lookaheadTimeSec', 0.3, 5, 's'),
num('pathFollow', 'trackedLookaheadMinM', 2, 40, 'm'),
num('pathFollow', 'trackedLookaheadMaxM', 4, 60, 'm'),
num('pathFollow', 'wheeledLookaheadMinM', 2, 40, 'm'),
num('pathFollow', 'wheeledLookaheadMaxM', 4, 60, 'm'),
num('pathFollow', 'cornerAngleDeg', 10, 120, '°'),
num('pathFollow', 'cornerLateralAccelMps2', 0.5, 10, 'm/s²'),
num('pathFollow', 'cornerBrakeDecelMps2', 0.5, 10, 'm/s²'),
num('pathFollow', 'arriveRadiusM', 1, 20, 'm'),
num('pathFollow', 'arriveMinSpeedMps', 0.3, 6, 'm/s'),
num('pathFollow', 'narrowWallMarginM', 0.2, 6, 'm'),
num('pathFollow', 'narrowSpeedMps', 1, 15, 'm/s'),
num('pathFollow', 'bumperRayM', 2, 20, 'm'),
num('pathFollow', 'bumperStopM', 0.3, 6, 'm'),
num('pathFollow', 'bumperBlockSec', 0.2, 5, 's'),
num('pathFollow', 'trafficTtcSec', 0.5, 8, 's'),
num('pathFollow', 'yieldWaitMaxSec', 0.5, 15, 's'),
num('pathFollow', 'stationarySpeedMps', 0.2, 4, 'm/s'),
num('pathFollow', 'passMarginM', 0.2, 4, 'm'),
num('pathFollow', 'passSpeedMps', 1, 12, 'm/s'),
num('pathFollow', 'blockWaitSec', 0.5, 15, 's'),
num('pathFollow', 'blockTtlSec', 3, 120, 's'),
num('pathFollow', 'contactGapM', 0.2, 3, 'm'),
num('pathFollow', 'contactReverseSec', 0.3, 5, 's'),
num('pathFollow', 'contactRepeatSec', 3, 120, 's'),
num('pathFollow', 'stuckWindowSec', 1, 15, 's'),
num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'),
num('pathFollow', 'unstickReverseM', 2, 25, 'm'),
num('pathFollow', 'unstickReverseSec', 0.8, 10, 's'),
num('pathFollow', 'unstickRepeatSec', 2, 60, 's'),
int('pathFollow', 'unstickMaxAttempts', 1, 10),
num('pathFollow', 'jamRadiusM', 2, 50, 'm'),
num('pathFollow', 'jamCostMul', 1, 50),
num('pathFollow', 'jamTtlSec', 5, 600, 's'),
num('pathFollow', 'giveUpRadiusM', 3, 50, 'm'),
num('pathFollow', 'giveUpCostMul', 1, 200),
num('pathFollow', 'rubbleRadiusM', 1, 40, 'm'),
num('pathFollow', 'rubbleCostMul', 1, 50),
num('pathFollow', 'rubbleTtlSec', 5, 600, 's'),
num('pathFollow', 'wreckRadiusM', 1, 40, 'm'),
num('pathFollow', 'wreckCostMul', 1, 50),
num('pathFollow', 'wreckTtlSec', 5, 600, 's'),
],
},
{
id: 'crowd',
defaultOpen: false,
@@ -306,6 +461,13 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('cadence', 'navTickSec', 0.05, 2, 's'),
{ id: 'groundAi.diagnostics.telemetry', section: 'diagnostics', field: 'telemetry', kind: 'bool' },
num('diagnostics', 'telemetryIntervalSec', 0.5, 60, 's'),
{ id: 'groundAi.diagnostics.battleStats', section: 'diagnostics', field: 'battleStats', kind: 'bool' },
num('diagnostics', 'statsLogIntervalSec', 10, 600, 's'),
num('diagnostics', 'statsSampleSec', 0.2, 5, 's'),
num('diagnostics', 'statsSampleRangeM', 50, 1000, 'm'),
num('diagnostics', 'statsRearArcDeg', 30, 180, '°'),
{ id: 'groundAi.diagnostics.trace', section: 'diagnostics', field: 'trace', kind: 'bool' },
num('diagnostics', 'traceIntervalSec', 0.1, 5, 's'),
],
},
];
+183 -20
View File
@@ -90,16 +90,84 @@ const GroundAiNavigationSchema = z.object({
steerSign: z.union([z.literal(1), z.literal(-1)]),
deadEchoSec: z.number().min(0.3).max(10),
controlTimeoutSec: z.number().min(0.3).max(10),
cornerBrakeAccel: z.number().min(0.5).max(8),
movingFireSpeedRampMps: z.number().min(0.2).max(5),
pivotAngleDeg: z.number().min(25).max(150),
stuckWindowSec: z.number().min(1).max(15),
stuckMinMoveM: z.number().min(0.5).max(10),
unstickReverseSec: z.number().min(0.8).max(10),
tacticalReverseDistM: z.number().min(10).max(90),
tacticalReverseMaxSec: z.number().min(2).max(25),
});
const GroundAiNavEngineSchema = z.object({
enabled: z.boolean(),
allowFallback: z.boolean(),
snapRadiusM: z.number().min(2).max(40),
goalSnapRadiusM: z.number().min(5).max(150),
pathBudgetMsPerFrame: z.number().min(0.05).max(5),
trafficCostPerPath: z.number().min(0).max(3),
trafficCostMaxMul: z.number().min(1).max(10),
trafficHoldSec: z.number().min(0).max(120),
cornerOffsetM: z.number().min(0).max(5),
});
const navCost = z.number().min(0.1).max(20);
const GroundAiNavCostsSchema = z.object({
road: navCost,
bridge: navCost,
ground: navCost,
rough: navCost,
forest: navCost,
crushable: navCost,
shallowWater: navCost,
chokepoint: navCost,
});
const GroundAiPathFollowSchema = z.object({
replanIntervalSec: z.number().min(1).max(15),
replanGoalMoveM: z.number().min(3).max(80),
offCorridorReplanM: z.number().min(3).max(60),
lookaheadTimeSec: z.number().min(0.3).max(5),
trackedLookaheadMinM: z.number().min(2).max(40),
trackedLookaheadMaxM: z.number().min(4).max(60),
wheeledLookaheadMinM: z.number().min(2).max(40),
wheeledLookaheadMaxM: z.number().min(4).max(60),
cornerAngleDeg: z.number().min(10).max(120),
cornerLateralAccelMps2: z.number().min(0.5).max(10),
cornerBrakeDecelMps2: z.number().min(0.5).max(10),
arriveRadiusM: z.number().min(1).max(20),
arriveMinSpeedMps: z.number().min(0.3).max(6),
narrowWallMarginM: z.number().min(0.2).max(6),
narrowSpeedMps: z.number().min(1).max(15),
bumperRayM: z.number().min(2).max(20),
bumperStopM: z.number().min(0.3).max(6),
bumperBlockSec: z.number().min(0.2).max(5),
trafficTtcSec: z.number().min(0.5).max(8),
yieldWaitMaxSec: z.number().min(0.5).max(15),
stationarySpeedMps: z.number().min(0.2).max(4),
passMarginM: z.number().min(0.2).max(4),
passSpeedMps: z.number().min(1).max(12),
blockWaitSec: z.number().min(0.5).max(15),
blockTtlSec: z.number().min(3).max(120),
contactGapM: z.number().min(0.2).max(3),
contactReverseSec: z.number().min(0.3).max(5),
contactRepeatSec: z.number().min(3).max(120),
stuckWindowSec: z.number().min(1).max(15),
stuckMinProgressM: z.number().min(0.2).max(10),
unstickReverseM: z.number().min(2).max(25),
unstickReverseSec: z.number().min(0.8).max(10),
unstickRepeatSec: z.number().min(2).max(60),
unstickMaxAttempts: z.number().int().min(1).max(10),
jamRadiusM: z.number().min(2).max(50),
jamCostMul: z.number().min(1).max(50),
jamTtlSec: z.number().min(5).max(600),
giveUpRadiusM: z.number().min(3).max(50),
giveUpCostMul: z.number().min(1).max(200),
rubbleRadiusM: z.number().min(1).max(40),
rubbleCostMul: z.number().min(1).max(50),
rubbleTtlSec: z.number().min(5).max(600),
wreckRadiusM: z.number().min(1).max(40),
wreckCostMul: z.number().min(1).max(50),
wreckTtlSec: z.number().min(5).max(600),
});
const GroundAiPerceptionSchema = z.object({
foliageTransparency: z.number().min(0.001).max(1),
nearSpotRangeM: z.number().min(20).max(250),
@@ -108,22 +176,24 @@ const GroundAiPerceptionSchema = z.object({
normalSpotSec: z.number().min(0.1).max(3),
farSpotSec: z.number().min(0.3).max(6),
decayPerSec: z.number().min(0.2).max(10),
frontConeHalfDeg: z.number().min(10).max(90),
peripheralCloseM: z.number().min(30).max(250),
gunFovHalfDeg: z.number().min(5).max(90),
nearAwareM: z.number().min(30).max(400),
nearArcDeg: z.number().min(90).max(360),
midAwareM: z.number().min(100).max(1500),
nearSpotMul: z.number().min(1).max(5),
midSpotMul: z.number().min(1).max(6),
lookAroundSec: z.number().min(2).max(60),
lookAroundHoldSec: z.number().min(0.2).max(5),
discoverScore: z.number().min(0.05).max(0.95),
});
const GroundAiStateMachineSchema = z.object({
preaimAngleDeg: z.number().min(1).max(30),
movingShotWaitSec: z.number().min(0.25).max(5),
shortHaltMaxSec: z.number().min(0.5).max(12),
shortHaltCooldownSec: z.number().min(0.5).max(20),
turnLaunchSpeedMps: z.number().min(0.5).max(6),
coverMinDistM: z.number().min(2).max(30),
coverMaxDistM: z.number().min(6).max(80),
coverRetreatBudgetSec: z.number().min(1.5).max(20),
reloadAdvanceAngleDeg: z.number().min(0).max(45),
hullAngleTriggerDeg: z.number().min(15).max(75),
hullAngleTargetDeg: z.number().min(0).max(35),
maxTotalHaltSec: z.number().min(3).max(40),
stalemateMissShots: z.number().int().min(1).max(8),
stalemateNoShotHalts: z.number().int().min(1).max(6),
@@ -134,8 +204,6 @@ const GroundAiStateMachineSchema = z.object({
const GroundAiTacticsSchema = z.object({
visionRangeM: z.number().min(200).max(3500),
visionFovDeg: z.number().min(40).max(180),
peripheralRangeM: z.number().min(30).max(800),
engineAudioRangeM: z.number().min(10).max(250),
shotAudioRangeM: z.number().min(50).max(1200),
radioShareRangeM: z.number().min(50).max(1500),
@@ -144,6 +212,58 @@ const GroundAiTacticsSchema = z.object({
peekCooldownSec: z.number().min(1).max(30),
});
const GroundAiThreatSchema = z.object({
rangeScaleM: z.number().min(50).max(3000),
discoveredMul: z.number().min(0).max(1),
aimConeDeg: z.number().min(5).max(90),
notAimingMul: z.number().min(0).max(1),
unseenMul: z.number().min(0).max(1),
hitMemorySec: z.number().min(0).max(60),
hitMul: z.number().min(1).max(5),
});
const GroundAiTurretSchema = z.object({
minDwellSec: z.number().min(0).max(5),
switchMargin: z.number().min(0).max(3),
scanArcDeg: z.number().min(0).max(180),
scanPeriodSec: z.number().min(1).max(30),
fixedMountYawSpanDeg: z.number().min(0).max(180),
});
const GroundAiBehaviorSchema = z.object({
scoreIntervalSec: z.number().min(0.1).max(3),
advanceHoldSec: z.number().min(0).max(10),
engageHoldSec: z.number().min(0).max(10),
haltHoldSec: z.number().min(0).max(10),
coverHoldSec: z.number().min(0).max(10),
repositionHoldSec: z.number().min(0).max(10),
postHoldSec: z.number().min(0).max(10),
disperseHoldSec: z.number().min(0).max(10),
targetValueWeight: z.number().min(0).max(1),
nearThreatHaltBonus: z.number().min(0).max(1),
switchMargin: z.number().min(0).max(1),
advanceScore: z.number().min(0).max(1),
engageScore: z.number().min(0).max(1),
urgencyWeight: z.number().min(0).max(1),
haltScore: z.number().min(0).max(1),
crossfirePenalty: z.number().min(0).max(1),
coverScore: z.number().min(0).max(1),
coverDangerWeight: z.number().min(0).max(1),
coverOffensivePenalty: z.number().min(0).max(1),
coverRetrySec: z.number().min(0.5).max(30),
repositionScore: z.number().min(0).max(1),
holdScore: z.number().min(0).max(1),
disperseScore: z.number().min(0).max(1),
urgentSpeedKeep: z.number().min(0).max(1),
hullAngleDeg: z.number().min(0).max(45),
faceToleranceDeg: z.number().min(3).max(60),
faceMinDanger: z.number().min(0).max(2),
reverseTravelAngleDeg: z.number().min(60).max(180),
reverseMaxTurnDistM: z.number().min(0).max(200),
reverseMinSpeedMps: z.number().min(0.5).max(10),
reverseHoldSec: z.number().min(0).max(20),
});
const GroundAiEstimationSchema = z.object({
watchMinSec: z.number().min(0.5).max(10),
watchMaxSec: z.number().min(1).max(15),
@@ -160,19 +280,41 @@ const GroundAiFireControlSchema = z.object({
closeRangeM: z.number().min(30).max(250),
midRangeM: z.number().min(100).max(600),
longRangeM: z.number().min(300).max(1500),
midSlowSpeedRatio: z.number().min(0.1).max(1),
midSlowMaxMps: z.number().min(1).max(15),
closeRangeMaxSpeedKmh: z.number().min(3.6).max(100),
pointBlankMaxSpeedKmh: z.number().min(3.6).max(100),
stopSpeedMaxMps: z.number().min(0.1).max(2),
longRangeWindowSec: z.number().min(1).max(15),
baseAlignDeg: z.number().min(0.1).max(3),
closeHitRadiusM: z.number().min(0.25).max(2.2),
barrelSettleDegSec: z.number().min(0.2).max(12),
closeSettleHoldSec: z.number().min(0.02).max(0.5),
settleHoldSec: z.number().min(0.05).max(1.5),
unstabilizedStopSpeedMps: z.number().min(0.1).max(3),
stabilizedCreepSpeedMps: z.number().min(1.5).max(15),
aimErrorDeg: z.number().min(0.01).max(2),
moveErrDegPerMps: z.number().min(0).max(3),
turnErrDegPerDegSec: z.number().min(0).max(0.5),
stabErrFactor: z.number().min(0.02).max(1),
targetHalfHeightM: z.number().min(0.3).max(2),
fireThreshold: z.number().min(0.05).max(0.95),
minFireThreshold: z.number().min(0.01).max(0.9),
aimingThresholdBonus: z.number().min(0).max(0.5),
closeThresholdBonus: z.number().min(0).max(0.5),
enemyReloadThresholdBonus: z.number().min(0).max(0.5),
enemyReloadSec: z.number().min(0).max(15),
fleetingThresholdBonus: z.number().min(0).max(0.5),
fleetingLateralMps: z.number().min(0.5).max(15),
fleetingLookAheadSec: z.number().min(0.1).max(2),
reloadThresholdPenalty: z.number().min(0).max(0.5),
longReloadSec: z.number().min(1).max(60),
lowAmmoRounds: z.number().int().min(1).max(60),
lowAmmoThresholdPenalty: z.number().min(0).max(0.5),
aimSkill: z.number().min(0).max(1),
autocannonMinShotsPerSec: z.number().min(0.5).max(30),
retreatThresholdPenalty: z.number().min(0).max(0.6),
minShotIntervalSec: z.number().min(0.1).max(5),
autocannonAimSlack: z.number().min(1).max(10),
burstSec: z.number().min(0.2).max(6),
burstPauseSec: z.number().min(0).max(5),
autocannonReloadDetectSec: z.number().min(0.1).max(3),
auxWeapons: z.boolean(),
auxMaxRangeM: z.number().min(30).max(1500),
auxFireAtArmor: z.boolean(),
friendlyCorridorM: z.number().min(1).max(10),
ballisticStepMaxM: z.number().min(5).max(80),
ballisticSweepRadiusM: z.number().min(0.02).max(0.5),
@@ -182,6 +324,13 @@ const GroundAiFireControlSchema = z.object({
const GroundAiDiagnosticsSchema = z.object({
telemetry: z.boolean(),
telemetryIntervalSec: z.number().min(0.5).max(60),
battleStats: z.boolean(),
statsLogIntervalSec: z.number().min(10).max(600),
statsSampleSec: z.number().min(0.2).max(5),
statsSampleRangeM: z.number().min(50).max(1000),
statsRearArcDeg: z.number().min(30).max(180),
trace: z.boolean(),
traceIntervalSec: z.number().min(0.1).max(5),
});
export const GroundAiTuningSchema = z.object({
@@ -194,10 +343,17 @@ export const GroundAiTuningSchema = z.object({
crowd: GroundAiCrowdSchema,
terrain: GroundAiTerrainSchema,
navigation: GroundAiNavigationSchema,
navEngine: GroundAiNavEngineSchema,
navCostsTracked: GroundAiNavCostsSchema,
navCostsWheeled: GroundAiNavCostsSchema,
pathFollow: GroundAiPathFollowSchema,
perception: GroundAiPerceptionSchema,
stateMachine: GroundAiStateMachineSchema,
tactics: GroundAiTacticsSchema,
estimation: GroundAiEstimationSchema,
threat: GroundAiThreatSchema,
turret: GroundAiTurretSchema,
behavior: GroundAiBehaviorSchema,
fireControl: GroundAiFireControlSchema,
diagnostics: GroundAiDiagnosticsSchema,
});
@@ -212,10 +368,17 @@ export const GroundAiTuningPatchSchema = z.object({
crowd: GroundAiCrowdSchema.partial().optional(),
terrain: GroundAiTerrainSchema.partial().optional(),
navigation: GroundAiNavigationSchema.partial().optional(),
navEngine: GroundAiNavEngineSchema.partial().optional(),
navCostsTracked: GroundAiNavCostsSchema.partial().optional(),
navCostsWheeled: GroundAiNavCostsSchema.partial().optional(),
pathFollow: GroundAiPathFollowSchema.partial().optional(),
perception: GroundAiPerceptionSchema.partial().optional(),
stateMachine: GroundAiStateMachineSchema.partial().optional(),
tactics: GroundAiTacticsSchema.partial().optional(),
estimation: GroundAiEstimationSchema.partial().optional(),
threat: GroundAiThreatSchema.partial().optional(),
turret: GroundAiTurretSchema.partial().optional(),
behavior: GroundAiBehaviorSchema.partial().optional(),
fireControl: GroundAiFireControlSchema.partial().optional(),
diagnostics: GroundAiDiagnosticsSchema.partial().optional(),
});
@@ -131,6 +131,8 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode));
// The battle's level file: the ground AI loads its navigation pack by this name (native local_mp_nav.c).
if (plan.level !== undefined) setParam(bots, 'wtoLevel', text(plan.level));
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
+204 -24
View File
@@ -8,6 +8,8 @@ import {
type GroundAiConfig,
type GroundAiDriveMode,
type GroundAiMode,
type GroundAiNavCosts,
type GroundAiPathFollow,
} from '@wto/patcher';
import type { TankLineupWeights } from '../battle/battle-ranks.ts';
import { tuningFiles } from './tuning-loader.ts';
@@ -44,14 +46,31 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
crowd: readCrowdSection(reader.object('crowd')),
terrain: readTerrainSection(reader.object('terrain')),
navigation: readNavigationSection(reader.object('navigation')),
navEngine: readNavEngineSection(reader.object('navEngine')),
navCostsTracked: readNavCosts(reader.object('navCostsTracked')),
navCostsWheeled: readNavCosts(reader.object('navCostsWheeled')),
pathFollow: readPathFollowSection(reader.object('pathFollow')),
navBake: {
crushableMaxRiExtraHp: reader.object('navBake').number('crushableMaxRiExtraHp', { min: 0, max: 1000 }),
},
perception: readPerceptionSection(reader.object('perception')),
stateMachine: readStateMachineSection(reader.object('stateMachine')),
tactics: readTacticsSection(reader.object('tactics')),
estimation: readEstimationSection(reader.object('estimation')),
threat: readThreatSection(reader.object('threat')),
turret: readTurretSection(reader.object('turret')),
behavior: readBehaviorSection(reader.object('behavior')),
fireControl: readFireControlSection(reader.object('fireControl')),
diagnostics: {
telemetry: diag.bool('telemetry'),
telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }),
battleStats: diag.bool('battleStats'),
statsLogIntervalSec: diag.number('statsLogIntervalSec', { min: 10, max: 600 }),
statsSampleSec: diag.number('statsSampleSec', { min: 0.2, max: 5 }),
statsSampleRangeM: diag.number('statsSampleRangeM', { min: 50, max: 1000 }),
statsRearArcDeg: diag.number('statsRearArcDeg', { min: 30, max: 180 }),
trace: diag.bool('trace'),
traceIntervalSec: diag.number('traceIntervalSec', { min: 0.1, max: 5 }),
},
};
}
@@ -173,6 +192,91 @@ function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] {
};
}
function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] {
return {
enabled: engine.bool('enabled'),
allowFallback: engine.bool('allowFallback'),
snapRadiusM: engine.number('snapRadiusM', { min: 2, max: 40 }),
goalSnapRadiusM: engine.number('goalSnapRadiusM', { min: 5, max: 150 }),
pathBudgetMsPerFrame: engine.number('pathBudgetMsPerFrame', { min: 0.05, max: 5 }),
trafficCostPerPath: engine.number('trafficCostPerPath', { min: 0, max: 3 }),
trafficCostMaxMul: engine.number('trafficCostMaxMul', { min: 1, max: 10 }),
trafficHoldSec: engine.number('trafficHoldSec', { min: 0, max: 120 }),
cornerOffsetM: engine.number('cornerOffsetM', { min: 0, max: 5 }),
};
}
function readNavCosts(costs: TuningReader): GroundAiNavCosts {
const read = (key: keyof GroundAiNavCosts) => costs.number(key, { min: 0.1, max: 20 });
return {
road: read('road'),
bridge: read('bridge'),
ground: read('ground'),
rough: read('rough'),
forest: read('forest'),
crushable: read('crushable'),
shallowWater: read('shallowWater'),
chokepoint: read('chokepoint'),
};
}
function readPathFollowSection(pf: TuningReader): GroundAiPathFollow {
const n = (key: keyof GroundAiPathFollow, min: number, max: number) => pf.number(key, { min, max });
const lookahead = {
trackedLookaheadMinM: n('trackedLookaheadMinM', 2, 40),
trackedLookaheadMaxM: n('trackedLookaheadMaxM', 4, 60),
wheeledLookaheadMinM: n('wheeledLookaheadMinM', 2, 40),
wheeledLookaheadMaxM: n('wheeledLookaheadMaxM', 4, 60),
};
if (lookahead.trackedLookaheadMaxM < lookahead.trackedLookaheadMinM || lookahead.wheeledLookaheadMaxM < lookahead.wheeledLookaheadMinM) {
throw new TuningError('tuning file ground-ai.jsonc: pathFollow lookahead maximum must not be below its minimum');
}
return {
replanIntervalSec: n('replanIntervalSec', 1, 15),
replanGoalMoveM: n('replanGoalMoveM', 3, 80),
offCorridorReplanM: n('offCorridorReplanM', 3, 60),
lookaheadTimeSec: n('lookaheadTimeSec', 0.3, 5),
...lookahead,
cornerAngleDeg: n('cornerAngleDeg', 10, 120),
cornerLateralAccelMps2: n('cornerLateralAccelMps2', 0.5, 10),
cornerBrakeDecelMps2: n('cornerBrakeDecelMps2', 0.5, 10),
arriveRadiusM: n('arriveRadiusM', 1, 20),
arriveMinSpeedMps: n('arriveMinSpeedMps', 0.3, 6),
narrowWallMarginM: n('narrowWallMarginM', 0.2, 6),
narrowSpeedMps: n('narrowSpeedMps', 1, 15),
bumperRayM: n('bumperRayM', 2, 20),
bumperStopM: n('bumperStopM', 0.3, 6),
bumperBlockSec: n('bumperBlockSec', 0.2, 5),
trafficTtcSec: n('trafficTtcSec', 0.5, 8),
yieldWaitMaxSec: n('yieldWaitMaxSec', 0.5, 15),
stationarySpeedMps: n('stationarySpeedMps', 0.2, 4),
passMarginM: n('passMarginM', 0.2, 4),
passSpeedMps: n('passSpeedMps', 1, 12),
blockWaitSec: n('blockWaitSec', 0.5, 15),
blockTtlSec: n('blockTtlSec', 3, 120),
contactGapM: n('contactGapM', 0.2, 3),
contactReverseSec: n('contactReverseSec', 0.3, 5),
contactRepeatSec: n('contactRepeatSec', 3, 120),
stuckWindowSec: n('stuckWindowSec', 1, 15),
stuckMinProgressM: n('stuckMinProgressM', 0.2, 10),
unstickReverseM: n('unstickReverseM', 2, 25),
unstickReverseSec: n('unstickReverseSec', 0.8, 10),
unstickRepeatSec: n('unstickRepeatSec', 2, 60),
unstickMaxAttempts: pf.int('unstickMaxAttempts', { min: 1, max: 10 }),
jamRadiusM: n('jamRadiusM', 2, 50),
jamCostMul: n('jamCostMul', 1, 50),
jamTtlSec: n('jamTtlSec', 5, 600),
giveUpRadiusM: n('giveUpRadiusM', 3, 50),
giveUpCostMul: n('giveUpCostMul', 1, 200),
rubbleRadiusM: n('rubbleRadiusM', 1, 40),
rubbleCostMul: n('rubbleCostMul', 1, 50),
rubbleTtlSec: n('rubbleTtlSec', 5, 600),
wreckRadiusM: n('wreckRadiusM', 1, 40),
wreckCostMul: n('wreckCostMul', 1, 50),
wreckTtlSec: n('wreckTtlSec', 5, 600),
};
}
function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] {
const driveModeRaw = nav.string('driveMode');
const driveMode = GROUND_AI_DRIVE_MODES.find((candidate): candidate is GroundAiDriveMode => candidate === driveModeRaw);
@@ -189,12 +293,8 @@ function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation']
steerSign,
deadEchoSec: nav.number('deadEchoSec', { min: 0.3, max: 10 }),
controlTimeoutSec: nav.number('controlTimeoutSec', { min: 0.3, max: 10 }),
cornerBrakeAccel: nav.number('cornerBrakeAccel', { min: 0.5, max: 8 }),
movingFireSpeedRampMps: nav.number('movingFireSpeedRampMps', { min: 0.2, max: 5 }),
pivotAngleDeg: nav.number('pivotAngleDeg', { min: 25, max: 150 }),
stuckWindowSec: nav.number('stuckWindowSec', { min: 1, max: 15 }),
stuckMinMoveM: nav.number('stuckMinMoveM', { min: 0.5, max: 10 }),
unstickReverseSec: nav.number('unstickReverseSec', { min: 0.8, max: 10 }),
tacticalReverseDistM: nav.number('tacticalReverseDistM', { min: 10, max: 90 }),
tacticalReverseMaxSec: nav.number('tacticalReverseMaxSec', { min: 2, max: 25 }),
};
@@ -209,8 +309,15 @@ function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception']
normalSpotSec: perc.number('normalSpotSec', { min: 0.1, max: 3.0 }),
farSpotSec: perc.number('farSpotSec', { min: 0.3, max: 6.0 }),
decayPerSec: perc.number('decayPerSec', { min: 0.2, max: 10.0 }),
frontConeHalfDeg: perc.number('frontConeHalfDeg', { min: 10, max: 90 }),
peripheralCloseM: perc.number('peripheralCloseM', { min: 30, max: 250 }),
gunFovHalfDeg: perc.number('gunFovHalfDeg', { min: 5, max: 90 }),
nearAwareM: perc.number('nearAwareM', { min: 30, max: 400 }),
nearArcDeg: perc.number('nearArcDeg', { min: 90, max: 360 }),
midAwareM: perc.number('midAwareM', { min: 100, max: 1500 }),
nearSpotMul: perc.number('nearSpotMul', { min: 1, max: 5 }),
midSpotMul: perc.number('midSpotMul', { min: 1, max: 6 }),
lookAroundSec: perc.number('lookAroundSec', { min: 2, max: 60 }),
lookAroundHoldSec: perc.number('lookAroundHoldSec', { min: 0.2, max: 5 }),
discoverScore: perc.number('discoverScore', { min: 0.05, max: 0.95 }),
};
}
@@ -221,17 +328,12 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine
throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM');
}
return {
preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }),
movingShotWaitSec: sm.number('movingShotWaitSec', { min: 0.25, max: 5.0 }),
shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }),
shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }),
turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }),
coverMinDistM,
coverMaxDistM,
coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }),
reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }),
hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }),
hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }),
maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }),
stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }),
stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }),
@@ -244,8 +346,6 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine
function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] {
return {
visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }),
visionFovDeg: tactics.number('visionFovDeg', { min: 40, max: 180 }),
peripheralRangeM: tactics.number('peripheralRangeM', { min: 30, max: 800 }),
engineAudioRangeM: tactics.number('engineAudioRangeM', { min: 10, max: 250 }),
shotAudioRangeM: tactics.number('shotAudioRangeM', { min: 50, max: 1200 }),
radioShareRangeM: tactics.number('radioShareRangeM', { min: 50, max: 1500 }),
@@ -255,6 +355,64 @@ function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] {
};
}
function readThreatSection(threat: TuningReader): GroundAiTuning['threat'] {
return {
rangeScaleM: threat.number('rangeScaleM', { min: 50, max: 3000 }),
discoveredMul: threat.number('discoveredMul', { min: 0, max: 1 }),
aimConeDeg: threat.number('aimConeDeg', { min: 5, max: 90 }),
notAimingMul: threat.number('notAimingMul', { min: 0, max: 1 }),
unseenMul: threat.number('unseenMul', { min: 0, max: 1 }),
hitMemorySec: threat.number('hitMemorySec', { min: 0, max: 60 }),
hitMul: threat.number('hitMul', { min: 1, max: 5 }),
};
}
function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] {
return {
minDwellSec: turret.number('minDwellSec', { min: 0, max: 5 }),
switchMargin: turret.number('switchMargin', { min: 0, max: 3 }),
scanArcDeg: turret.number('scanArcDeg', { min: 0, max: 180 }),
scanPeriodSec: turret.number('scanPeriodSec', { min: 1, max: 30 }),
fixedMountYawSpanDeg: turret.number('fixedMountYawSpanDeg', { min: 0, max: 180 }),
};
}
function readBehaviorSection(bhv: TuningReader): GroundAiTuning['behavior'] {
return {
scoreIntervalSec: bhv.number('scoreIntervalSec', { min: 0.1, max: 3 }),
advanceHoldSec: bhv.number('advanceHoldSec', { min: 0, max: 10 }),
engageHoldSec: bhv.number('engageHoldSec', { min: 0, max: 10 }),
haltHoldSec: bhv.number('haltHoldSec', { min: 0, max: 10 }),
coverHoldSec: bhv.number('coverHoldSec', { min: 0, max: 10 }),
repositionHoldSec: bhv.number('repositionHoldSec', { min: 0, max: 10 }),
postHoldSec: bhv.number('postHoldSec', { min: 0, max: 10 }),
disperseHoldSec: bhv.number('disperseHoldSec', { min: 0, max: 10 }),
targetValueWeight: bhv.number('targetValueWeight', { min: 0, max: 1 }),
nearThreatHaltBonus: bhv.number('nearThreatHaltBonus', { min: 0, max: 1 }),
switchMargin: bhv.number('switchMargin', { min: 0, max: 1 }),
advanceScore: bhv.number('advanceScore', { min: 0, max: 1 }),
engageScore: bhv.number('engageScore', { min: 0, max: 1 }),
urgencyWeight: bhv.number('urgencyWeight', { min: 0, max: 1 }),
haltScore: bhv.number('haltScore', { min: 0, max: 1 }),
crossfirePenalty: bhv.number('crossfirePenalty', { min: 0, max: 1 }),
coverScore: bhv.number('coverScore', { min: 0, max: 1 }),
coverDangerWeight: bhv.number('coverDangerWeight', { min: 0, max: 1 }),
coverOffensivePenalty: bhv.number('coverOffensivePenalty', { min: 0, max: 1 }),
coverRetrySec: bhv.number('coverRetrySec', { min: 0.5, max: 30 }),
repositionScore: bhv.number('repositionScore', { min: 0, max: 1 }),
holdScore: bhv.number('holdScore', { min: 0, max: 1 }),
disperseScore: bhv.number('disperseScore', { min: 0, max: 1 }),
urgentSpeedKeep: bhv.number('urgentSpeedKeep', { min: 0, max: 1 }),
hullAngleDeg: bhv.number('hullAngleDeg', { min: 0, max: 45 }),
faceToleranceDeg: bhv.number('faceToleranceDeg', { min: 3, max: 60 }),
faceMinDanger: bhv.number('faceMinDanger', { min: 0, max: 2 }),
reverseTravelAngleDeg: bhv.number('reverseTravelAngleDeg', { min: 60, max: 180 }),
reverseMaxTurnDistM: bhv.number('reverseMaxTurnDistM', { min: 0, max: 200 }),
reverseMinSpeedMps: bhv.number('reverseMinSpeedMps', { min: 0.5, max: 10 }),
reverseHoldSec: bhv.number('reverseHoldSec', { min: 0, max: 20 }),
};
}
function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] {
const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 });
const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 });
@@ -285,29 +443,51 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl']
if (midRangeM <= closeRangeM || longRangeM <= midRangeM) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM');
}
const closeRangeMaxSpeedKmh = fc.number('closeRangeMaxSpeedKmh', { min: 3.6, max: 100 });
const pointBlankMaxSpeedKmh = fc.number('pointBlankMaxSpeedKmh', { min: 3.6, max: 100 });
if (pointBlankMaxSpeedKmh < closeRangeMaxSpeedKmh) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl.pointBlankMaxSpeedKmh must be >= closeRangeMaxSpeedKmh');
const fireThreshold = fc.number('fireThreshold', { min: 0.05, max: 0.95 });
const minFireThreshold = fc.number('minFireThreshold', { min: 0.01, max: 0.9 });
if (minFireThreshold > fireThreshold) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl.minFireThreshold must be <= fireThreshold');
}
return {
maxEngageRangeM: fc.number('maxEngageRangeM', { min: 150, max: 3000 }),
closeRangeM,
midRangeM,
longRangeM,
midSlowSpeedRatio: fc.number('midSlowSpeedRatio', { min: 0.1, max: 1.0 }),
midSlowMaxMps: fc.number('midSlowMaxMps', { min: 1.0, max: 15.0 }),
closeRangeMaxSpeedKmh,
pointBlankMaxSpeedKmh,
stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }),
longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }),
baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }),
closeHitRadiusM: fc.number('closeHitRadiusM', { min: 0.25, max: 2.2 }),
barrelSettleDegSec: fc.number('barrelSettleDegSec', { min: 0.2, max: 12.0 }),
closeSettleHoldSec: fc.number('closeSettleHoldSec', { min: 0.02, max: 0.5 }),
settleHoldSec: fc.number('settleHoldSec', { min: 0.05, max: 1.5 }),
unstabilizedStopSpeedMps: fc.number('unstabilizedStopSpeedMps', { min: 0.1, max: 3.0 }),
stabilizedCreepSpeedMps: fc.number('stabilizedCreepSpeedMps', { min: 1.5, max: 15.0 }),
aimErrorDeg: fc.number('aimErrorDeg', { min: 0.01, max: 2 }),
moveErrDegPerMps: fc.number('moveErrDegPerMps', { min: 0, max: 3 }),
turnErrDegPerDegSec: fc.number('turnErrDegPerDegSec', { min: 0, max: 0.5 }),
stabErrFactor: fc.number('stabErrFactor', { min: 0.02, max: 1 }),
targetHalfHeightM: fc.number('targetHalfHeightM', { min: 0.3, max: 2 }),
fireThreshold,
minFireThreshold,
aimingThresholdBonus: fc.number('aimingThresholdBonus', { min: 0, max: 0.5 }),
closeThresholdBonus: fc.number('closeThresholdBonus', { min: 0, max: 0.5 }),
enemyReloadThresholdBonus: fc.number('enemyReloadThresholdBonus', { min: 0, max: 0.5 }),
enemyReloadSec: fc.number('enemyReloadSec', { min: 0, max: 15 }),
fleetingThresholdBonus: fc.number('fleetingThresholdBonus', { min: 0, max: 0.5 }),
fleetingLateralMps: fc.number('fleetingLateralMps', { min: 0.5, max: 15 }),
fleetingLookAheadSec: fc.number('fleetingLookAheadSec', { min: 0.1, max: 2 }),
reloadThresholdPenalty: fc.number('reloadThresholdPenalty', { min: 0, max: 0.5 }),
longReloadSec: fc.number('longReloadSec', { min: 1, max: 60 }),
lowAmmoRounds: fc.int('lowAmmoRounds', { min: 1, max: 60 }),
lowAmmoThresholdPenalty: fc.number('lowAmmoThresholdPenalty', { min: 0, max: 0.5 }),
aimSkill: fc.number('aimSkill', { min: 0, max: 1 }),
autocannonMinShotsPerSec: fc.number('autocannonMinShotsPerSec', { min: 0.5, max: 30 }),
retreatThresholdPenalty: fc.number('retreatThresholdPenalty', { min: 0, max: 0.6 }),
minShotIntervalSec: fc.number('minShotIntervalSec', { min: 0.1, max: 5 }),
autocannonAimSlack: fc.number('autocannonAimSlack', { min: 1, max: 10 }),
burstSec: fc.number('burstSec', { min: 0.2, max: 6 }),
burstPauseSec: fc.number('burstPauseSec', { min: 0, max: 5 }),
autocannonReloadDetectSec: fc.number('autocannonReloadDetectSec', { min: 0.1, max: 3 }),
auxWeapons: fc.bool('auxWeapons'),
auxMaxRangeM: fc.number('auxMaxRangeM', { min: 30, max: 1500 }),
auxFireAtArmor: fc.bool('auxFireAtArmor'),
friendlyCorridorM: fc.number('friendlyCorridorM', { min: 1.0, max: 10.0 }),
ballisticStepMaxM: fc.number('ballisticStepMaxM', { min: 5.0, max: 80.0 }),
ballisticSweepRadiusM: fc.number('ballisticSweepRadiusM', { min: 0.02, max: 0.5 }),
+292 -28
View File
@@ -94,6 +94,36 @@
"ridgeMaxShots": 6
},
// Offline map baking parameters. These are copied into the generator's per-level POI input.
"coverMap": {
"minCoverHeightM": 1.55,
"peekMinM": 3.5,
"peekMaxM": 6.0,
"retreatMinM": 8.0,
// Low dry-stone fence models observed to give unreliable shot protection.
"excludedCoverRendinst": ["stone_fence_a", "damaged_stone_fence_a", "damaged_stone_fence_b"]
},
// Offline navigation mesh baking parameters, copied into the generator's per-level POI input.
"navBake": {
// Placed objects whose stock destructionImpulse (config/rendinst_dmg.blk) is at most this
// value are knocked down by tanks and baked as crushable rather than solid (N*s).
"crushableMaxImpulse": 45000,
// riExtra objects with no destructionImpulse are crushable when their stock hp is at most
// this value (wooden fences 2, dry-stone fences 12, car wrecks 20; buses 40).
"crushableMaxRiExtraHp": 20,
// Passages narrower than this many standard-tier vehicle widths are flagged as chokepoints.
"chokepointMaxWidthVehicles": 2.0,
// Water up to maxFordDepthM is forded (shallow water cost). Deeper water is a wall: besides the
// vehicle's half width, the mesh keeps deepWaterMarginM more ground from it where the bank is
// less than deepWaterBankHeightM above the water line,
// because low banks slope into the water and a hull at the water line slides in. Higher quays
// and ramps keep only the half width.
"maxFordDepthM": 0.9,
"deepWaterMarginM": 1.5,
"deepWaterBankHeightM": 1.0
},
"navigation": {
// "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement.
"driveMode": "vehicle_phys",
@@ -101,17 +131,131 @@
"steerSign": 1.0,
"deadEchoSec": 1.2,
"controlTimeoutSec": 1.0,
"cornerBrakeAccel": 1.75,
// Speed error at which the moving-fire controller applies full throttle or braking.
"movingFireSpeedRampMps": 1.0,
"pivotAngleDeg": 75.0,
"stuckWindowSec": 3.6,
"stuckMinMoveM": 2.0,
"unstickReverseSec": 3.0,
"tacticalReverseDistM": 34.0,
"tacticalReverseMaxSec": 9.5
},
// Baked navigation packs (tools/navgen), loaded once per battle by the native engine.
"navEngine": {
"enabled": true,
// When the battle's pack is missing or broken: true keeps the script's own navigation for the
// whole battle, false leaves the bots standing so the problem shows (testing). Decided once at
// battle start, never in the middle of a battle.
"allowFallback": true,
// Farthest a path's start or goal may lie from the mesh.
"snapRadiusM": 12.0,
// A goal farther than snapRadiusM from the mesh (a position chosen by tactics inside a building
// or on a slope) is moved to the nearest walkable point within this distance; beyond it the
// goal counts as unreachable. Also used to find the way back onto the mesh.
"goalSnapRadiusM": 40.0,
// Path searches are spread over frames; this is the search time allowed per frame.
"pathBudgetMsPerFrame": 0.5,
// Team traffic: each teammate path planned within trafficHoldSec through a stretch of mesh
// raises its cost for the team's next searches by trafficCostPerPath, up to trafficCostMaxMul,
// so a team spreads over parallel routes instead of queueing on one road.
"trafficCostPerPath": 0.35,
"trafficCostMaxMul": 2.5,
"trafficHoldSec": 12.0,
// Path corners are moved this far away from the building or wall they turn around.
"cornerOffsetM": 1.5
},
// Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost
// of passages narrower than navBake.chokepointMaxWidthVehicles.
"navCostsTracked": {
"road": 0.75,
"bridge": 0.9,
"ground": 1.0,
"rough": 1.65,
"forest": 2.1,
"crushable": 2.4,
"shallowWater": 2.6,
"chokepoint": 1.8
},
// The same for wheeled vehicles.
"navCostsWheeled": {
"road": 0.55,
"bridge": 0.75,
"ground": 1.15,
"rough": 3.2,
"forest": 2.8,
"crushable": 3.5,
"shallowWater": 4.0,
"chokepoint": 2.2
},
// Following the path, local avoidance and unstick (offline values).
"pathFollow": {
// Plan again after this long, when the goal moved this far, or when the bot is this far off its path.
"replanIntervalSec": 3.5,
"replanGoalMoveM": 15.0,
"offCorridorReplanM": 12.0,
// Steering point: speed times lookaheadTimeSec, kept within the range of the vehicle kind.
"lookaheadTimeSec": 1.4,
"trackedLookaheadMinM": 6.0,
"trackedLookaheadMaxM": 18.0,
"wheeledLookaheadMinM": 10.0,
"wheeledLookaheadMaxM": 24.0,
// Path corners sharper than cornerAngleDeg are taken at the speed the sideways acceleration
// allows; the vehicle brakes toward it (and toward its destination) at cornerBrakeDecelMps2.
"cornerAngleDeg": 35.0,
"cornerLateralAccelMps2": 2.8,
"cornerBrakeDecelMps2": 2.0,
"arriveRadiusM": 3.0,
"arriveMinSpeedMps": 1.5,
// The mesh already keeps the vehicle's half width from walls; less room than this beyond it,
// or a baked chokepoint, counts as a narrow passage.
"narrowWallMarginM": 1.5,
"narrowSpeedMps": 4.5,
// Rays from both front corners of the hull for obstacles the baked mesh does not know.
"bumperRayM": 7.0,
"bumperStopM": 1.5,
"bumperBlockSec": 0.6,
// Moving vehicles that come within reach in trafficTtcSec: follow them, or in narrow passages
// give way to the bigger one for at most yieldWaitMaxSec.
"trafficTtcSec": 2.5,
"yieldWaitMaxSec": 3.0,
// Vehicles slower than stationarySpeedMps, wrecks and players' vehicles in the way are passed
// on the side the mesh leaves room, keeping passMarginM between hulls, at up to passSpeedMps.
"stationarySpeedMps": 1.0,
"passMarginM": 0.8,
"passSpeedMps": 4.0,
// No side free: stop short, and after blockWaitSec mark the obstacle for path searches for
// blockTtlSec and plan again. A hull within contactGapM of it for contactReverseSec backs off.
// Pressed again within contactRepeatSec near the same place: mark the obstacle, try the other
// side, and after unstickMaxAttempts such repeats give the order up.
"blockWaitSec": 2.0,
"blockTtlSec": 15.0,
"contactGapM": 0.8,
"contactReverseSec": 1.0,
"contactRepeatSec": 20.0,
// Less progress than stuckMinProgressM within stuckWindowSec while wanting to move is stuck.
"stuckWindowSec": 3.0,
"stuckMinProgressM": 0.8,
"unstickReverseM": 6.5,
"unstickReverseSec": 3.0,
"unstickRepeatSec": 8.0,
"unstickMaxAttempts": 3,
// Temporary path costs: jams found by unstick, fresh obstacles hit by the front rays, wrecks.
// A place given up on after unstickMaxAttempts is all but closed (giveUp*), so the next order
// routes elsewhere instead of returning to it.
"jamRadiusM": 10.0,
"jamCostMul": 12.0,
"jamTtlSec": 45.0,
"giveUpRadiusM": 15.0,
"giveUpCostMul": 40.0,
"rubbleRadiusM": 6.0,
"rubbleCostMul": 25.0,
"rubbleTtlSec": 90.0,
"wreckRadiusM": 6.0,
"wreckCostMul": 6.0,
"wreckTtlSec": 120.0
},
// Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI).
"perception": {
"foliageTransparency": 0.01,
@@ -121,24 +265,29 @@
"normalSpotSec": 0.60,
"farSpotSec": 1.45,
"decayPerSec": 1.5,
"frontConeHalfDeg": 60.0,
"peripheralCloseM": 100.0
// Every visual arc is relative to the barrel. The sight covers gunFovHalfDeg either side;
// near awareness covers nearArcDeg around the barrel and every lookAroundSec opens the rear
// for lookAroundHoldSec. Mid-distance awareness covers the barrel's front half.
// Near and mid spotting use nearSpotMul and midSpotMul respectively.
"gunFovHalfDeg": 30.0,
"nearAwareM": 150.0,
"nearArcDeg": 270.0,
"midAwareM": 600.0,
"nearSpotMul": 1.5,
"midSpotMul": 2.0,
"lookAroundSec": 8.0,
"lookAroundHoldSec": 1.0,
"discoverScore": 0.35
},
// Per-bot hull state machine timings and thresholds (offline values).
// Timings and thresholds of the hull actions (short halt, cover pull-back, reposition, repair).
"stateMachine": {
"preaimAngleDeg": 8.0,
// Time a ready gun can be held up by speed or aim before attempting a short halt.
"movingShotWaitSec": 1.0,
"shortHaltMaxSec": 3.0,
"shortHaltCooldownSec": 4.0,
"turnLaunchSpeedMps": 2.1,
"coverMinDistM": 6.0,
"coverMaxDistM": 24.0,
"coverRetreatBudgetSec": 6.0,
"reloadAdvanceAngleDeg": 18.0,
"hullAngleTriggerDeg": 20.0,
"hullAngleTargetDeg": 10.0,
"maxTotalHaltSec": 12.0,
"stalemateMissShots": 2,
"stalemateNoShotHalts": 2,
@@ -149,9 +298,7 @@
"tactics": {
"visionRangeM": 1250.0,
"visionFovDeg": 115.0,
"peripheralRangeM": 230.0,
"engineAudioRangeM": 65.0,
"engineAudioRangeM": 150.0,
"shotAudioRangeM": 380.0,
"radioShareRangeM": 450.0,
"memoryTtlSec": 12.0,
@@ -171,26 +318,129 @@
"maxBiasM": 2.2
},
// Threat table (decision layer design, section 4): how dangerous each discovered enemy is to the
// bot. Danger falls with distance as 1 / (1 + distance / rangeScaleM) and is multiplied by
// discoveredMul until the enemy is seen clearly, by notAimingMul unless its hull or gun points
// within aimConeDeg of the bot (or it hit the bot), by unseenMul when the bot is out of its
// sight, and by hitMul for hitMemorySec after it hit the bot. Penetration is not counted yet.
"threat": {
"rangeScaleM": 400.0,
"discoveredMul": 0.7,
"aimConeDeg": 25.0,
"notAimingMul": 0.5,
"unseenMul": 0.4,
"hitMemorySec": 6.0,
"hitMul": 2.0
},
// The turret gives visible contacts attention by danger, then checks memory and directional cues.
// While engaged, the competing threat needs switchMargin more danger to take over.
// The turret sweeps the route when it has no contact or cue.
"turret": {
"minDwellSec": 0.6,
"switchMargin": 0.25,
"scanArcDeg": 60.0,
"scanPeriodSec": 6.0,
"fixedMountYawSpanDeg": 60.0
},
// Hull channel: choose a behavior by score, holding each for its configured commitment time
// unless an emergency or a large score difference interrupts it. A cover withdrawal runs
// through its arrival or timeout. A short halt lasts through the weapon's shooting window.
// Tracked tanks and tank destroyers face the main threat at the post or during a halt.
// They can reverse along a short route segment to keep their front toward that threat.
"behavior": {
"scoreIntervalSec": 0.5,
"advanceHoldSec": 1.5,
"engageHoldSec": 1.5,
"haltHoldSec": 3.0,
"coverHoldSec": 2.0,
"repositionHoldSec": 2.0,
"postHoldSec": 1.5,
"disperseHoldSec": 1.5,
"targetValueWeight": 0.1,
"nearThreatHaltBonus": 0.28,
"switchMargin": 0.15,
"advanceScore": 0.5,
"engageScore": 0.55,
"urgencyWeight": 0.15,
"haltScore": 0.55,
"crossfirePenalty": 0.15,
"coverScore": 0.45,
"coverDangerWeight": 0.25,
"coverOffensivePenalty": 0.2,
"coverRetrySec": 4.0,
"repositionScore": 0.7,
"holdScore": 0.6,
"disperseScore": 0.62,
"urgentSpeedKeep": 0.5,
"hullAngleDeg": 20.0,
"faceToleranceDeg": 15.0,
"faceMinDanger": 0.15,
"reverseTravelAngleDeg": 110.0,
"reverseMaxTurnDistM": 45.0,
"reverseMinSpeedMps": 2.5,
"reverseHoldSec": 3.0
},
// Fire permission (decision layer design, section 6). A main-gun shot needs its estimated hit
// probability to reach the fire threshold. The hit probability compares the visible part of the
// target (its projected width, targetHalfHeightM high, shrunk when only part of it is visible)
// with the expected angular error: aimErrorDeg, plus moveErrDegPerMps per m/s of own speed and
// turnErrDegPerDegSec per deg/s of hull turn (times stabErrFactor with a stabilizer), plus the
// lead uncertainty on a crossing target, with the barrel's current offset as the mean error.
// The threshold starts at fireThreshold and drops by aimingThresholdBonus when the target aims
// at the bot, by up to closeThresholdBonus inside closeRangeM, by enemyReloadThresholdBonus for
// enemyReloadSec after the target fired, and by fleetingThresholdBonus if its estimated motion
// will take it out of sight. Longer reloads, scarce ammunition and falling back raise the threshold.
// The pre-fire budget limits ballistic checks per frame. Every firing request gets fresh checks.
"fireControl": {
"maxEngageRangeM": 1250.0,
"closeRangeM": 100.0,
"midRangeM": 300.0,
"longRangeM": 800.0,
"midSlowSpeedRatio": 0.45,
"midSlowMaxMps": 5.5,
// Moving-fire speed rises from the mid-range limit through the close-range boundary to point blank.
"closeRangeMaxSpeedKmh": 30.0,
"pointBlankMaxSpeedKmh": 35.0,
// At or below this speed the bot counts as standing (also the answer "stop" to a speed request).
"stopSpeedMaxMps": 0.45,
"longRangeWindowSec": 4.0,
"longRangeWindowSec": 1.0,
// Fixed (casemate) guns: how far off the gun may be before the hull is asked to turn.
"baseAlignDeg": 0.42,
"closeHitRadiusM": 0.85,
// Outside close range, the rate at which barrel alignment drifts relative to the aim direction.
"barrelSettleDegSec": 1.8,
"closeSettleHoldSec": 0.08,
"settleHoldSec": 0.20,
"unstabilizedStopSpeedMps": 0.45,
"stabilizedCreepSpeedMps": 5.5,
"closeSettleHoldSec": 0.06,
"settleHoldSec": 0.12,
"aimErrorDeg": 0.07,
"moveErrDegPerMps": 0.35,
"turnErrDegPerDegSec": 0.03,
"stabErrFactor": 0.2,
"targetHalfHeightM": 1.0,
"fireThreshold": 0.45,
"minFireThreshold": 0.1,
"aimingThresholdBonus": 0.1,
"closeThresholdBonus": 0.15,
"enemyReloadThresholdBonus": 0.08,
"enemyReloadSec": 3.0,
"fleetingThresholdBonus": 0.1,
"fleetingLateralMps": 3.0,
"fleetingLookAheadSec": 0.65,
"reloadThresholdPenalty": 0.08,
"longReloadSec": 15.0,
"lowAmmoRounds": 5,
"lowAmmoThresholdPenalty": 0.08,
"aimSkill": 0.5,
"autocannonMinShotsPerSec": 1.5,
"retreatThresholdPenalty": 0.2,
"minShotIntervalSec": 0.65,
// Automatic cannons are identified from stock belt and firing-rate data. They fire in bursts
// while within the aim slack. A longer wait between rounds counts as a reload.
"autocannonAimSlack": 3.0,
"burstSec": 1.2,
"burstPauseSec": 0.6,
"autocannonReloadDetectSec": 0.6,
// Secondary and coaxial guns have their own aim and ballistic checks. The armor toggle allows
// coaxial fire at vehicles outside the light-vehicle filter.
"auxWeapons": true,
"auxMaxRangeM": 300.0,
"auxFireAtArmor": false,
"friendlyCorridorM": 3.2,
"ballisticStepMaxM": 25.0,
"ballisticSweepRadiusM": 0.12,
@@ -199,6 +449,20 @@
"diagnostics": {
"telemetry": true,
"telemetryIntervalSec": 5.0
"telemetryIntervalSec": 5.0,
// Battle statistics for comparing builds (WTO_AI|BATTLE_STATS): cumulative per vehicle class,
// logged every statsLogIntervalSec and when the battle ends. Every statsSampleSec each bot
// checks the nearest enemy in line of sight within statsSampleRangeM: whether it knows it,
// how far the turret is off it, and whether its rear (statsRearArcDeg wide) faces it.
"battleStats": true,
"statsLogIntervalSec": 60.0,
"statsSampleSec": 1.0,
"statsSampleRangeM": 300.0,
"statsRearArcDeg": 120.0,
// Replay trace for the AI viewer (WTO_AI|TRACE_*, HIT, DEATH): every traceIntervalSec the
// capture zones, every ground unit and every bot's decision state. About 10 MB of log for
// 32 bots over 15 minutes at 0.5 s.
"trace": true,
"traceIntervalSec": 0.5
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"level": "avg_berlin",
"version": 1,
"bake": {
// The original arterial and ring roads use this LMp2 material.
"roadMaterials": ["concrete"],
"walkableRendinst": ["fountain_base_b_body"],
"downhillLinks": [
// Dry endpoints verified on the two meshes at the eastern canal bank.
{
"from": { "x": 2476.0, "y": 43.34, "z": 1124.0 },
"to": { "x": 2460.0, "y": 36.61, "z": 1124.0 },
"radiusM": 0.75,
"widthTiers": [0]
},
{
"from": { "x": 2476.0, "y": 43.12, "z": 1135.5 },
"to": { "x": 2458.0, "y": 36.59, "z": 1135.5 },
"radiusM": 0.75,
"widthTiers": [1]
}
]
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"level": "avg_poland",
"version": 1,
"bake": {
// The town streets and squares use this LMp2 material.
"roadMaterials": ["concrete"]
}
}
+52
View File
@@ -0,0 +1,52 @@
// Ammunition assigned to the selected primary gun by the stock ammunition stowage.
options indenting = 2
options no_global_heap = true
module wto_ai_ammo_common shared
require ecs
require math
require DagorMath
require AmmoStowage
require Unit
require Weapon
require %appGame.wtoai.wto_ai_combat_types_common
[never_inline]
def public wto_main_gun_ammo(gun : WTGun const?; fc : WtoFireState const&) : int
var stored = 0
for set in gun.properties.bulletSets
stored += max(0, set.bulletsCount)
let stockCount = fc.rackTurret == fc.turretNo ? fc.rackRounds : -1
if stockCount < 0 && stored == 0
return -1
return max(max(stockCount, stored), int(gun.currentLoadedAmmoCount))
def private wto_ammo_type_for_mount(unit : Unit const?; turret : int; first, end : int; weapons : IntList const&) : bool
for i in range(max(0, first), min(length(weapons), end))
let weapon = get_weapon(unit.weap.Weapons, weapons[i])
if weapon != null && int(weapon.turretNo) == turret
return true
return false
[never_inline]
def public wto_ammo_sample(unit : Unit const?; ammoState : uint; types : IPoint4List const&;
weapons : IntList const&; slots : UInt32List const&; counts : IPoint2List const&;
var fc : WtoFireState&)
if fc.turretNo < 0
return
fc.rackTurret = fc.turretNo
fc.rackRounds = -1
for i in range(WTO_MAX_SHELL_PROFILES)
fc.rackBySet[i] = 0
let distinctTypes = (ammoState & uint(AmmoState.ENABLE_PER_AMMO_TYPES)) != 0u
for ammoType in range(length(types))
let remap = types[ammoType]
if !wto_ammo_type_for_mount(unit, fc.turretNo, remap.y, remap.z, weapons)
continue
var rounds = 0
for i in range(min(length(slots), length(counts)))
if int(slots[i] & 0xffu) == ammoType
rounds += max(0, counts[i].x)
fc.rackRounds = max(0, fc.rackRounds) + rounds
if distinctTypes && remap.w >= 0 && remap.w < WTO_MAX_SHELL_PROFILES
fc.rackBySet[remap.w] += rounds
+82
View File
@@ -0,0 +1,82 @@
// Fresh static obstacles on top of the path: what the baked mesh cannot know. Two short physical
// rays from the front corners of the hull catch rubble and collapsed buildings and let the vehicle
// drive through what it can knock down (fences, light walls). Vehicles and wrecks are handled by
// wto_ai_traffic_common.
options indenting = 2
options no_global_heap = true
module wto_ai_avoid_common shared
require ecs
require math
require DagorMath
require Dacoll
require RendInst
require PhysMat
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_types_common
let private AVOID_STATIC_MASK = ETF_STRUCTURES | ETF_FRT
// Placed objects a tank cannot knock down. Matches the bake: riExtra objects up to
// navBake.crushableMaxRiExtraHp are crushable, destructible generated objects (fences, posts)
// fall over, indestructible ones block.
[never_inline]
def private wto_avoid_ri_blocks(desc : RendInstDesc const&) : bool
if desc.isValid && desc.isRiExtra && desc.riExtraHandle != RIEX_HANDLE_NULL
let handle = desc.riExtraHandle
let poolId = uint(handle_to_ri_type(handle))
if rendinst_isRIExtraGenPosInst(poolId)
return false
if riex_isImmortal(poolId) || riex_isInvincible(handle)
return true
return riex_getInitialHP(handle) > WTO_AI_NAVBAKE_CRUSH_MAX_HP
if !desc.isValid
return true
if rendinst_isRIGenPosInst(desc)
return false
return !rendinst_isRIGenDestr(desc)
// Clear distance along dir up to the first wall-like surface a tank cannot drive through.
[never_inline]
def private wto_avoid_drive_ray(startPos, dir : float3; maxRange : float) : float
var structDist = maxRange
var sTraveled = 0.0
for _hop in range(0, 4)
var hitD = maxRange - sTraveled
if hitD <= 0.0
break
var mat = PHYSMAT_INVALID
var norm = float3(0.0)
var desc = RendInstDesc()
let sOrigin = startPos + dir * sTraveled
if !traceray_normalized(sOrigin, dir, hitD, mat, norm, AVOID_STATIC_MASK, desc, PHYSMAT_INVALID)
break
if norm.y < 0.72
structDist = clamp(sTraveled + hitD, 0.0, maxRange)
break
sTraveled += max(0.0, hitD) + 0.5
var traveled = 0.0
for _hop in range(0, 4)
var hitDist = structDist - traveled
if hitDist <= 0.0
break
var riMat = PHYSMAT_INVALID
var riNorm = float3(0.0)
var riDesc = RendInstDesc()
let origin = startPos + dir * traveled
if !traceray_normalized(origin, dir, hitDist, riMat, riNorm, ETF_RI | ETF_RI_PHYS, riDesc, PHYSMAT_INVALID)
break
if riNorm.y < 0.72 && wto_avoid_ri_blocks(riDesc)
return clamp(traveled + hitDist, 0.0, structDist)
traveled += max(0.0, hitDist) + 0.35
return structDist
// Clear distance ahead along `dir` from both front corners of the hull (the shorter of the two).
[never_inline]
def public wto_avoid_bumper(myPos, dir : float3; spec : WtoVehicleSpec const&) : float
let left = float3(-dir.z, 0.0, dir.x)
let base = myPos + dir * max(0.5, spec.halfLen - 0.4) + float3(0.0, 1.0, 0.0)
let side = max(0.4, spec.halfWid - 0.25)
let clearL = wto_avoid_drive_ray(base + left * side, dir, WTO_AI_PF_BUMPER_RAY_M)
let clearR = wto_avoid_drive_ray(base - left * side, dir, WTO_AI_PF_BUMPER_RAY_M)
return min(clearL, clearR)
+235
View File
@@ -0,0 +1,235 @@
// Hull channel behavior choice from the order, threats, vehicle state and weapon requests.
// Actions own their completion conditions. Critical threats and hits can interrupt a commitment.
options indenting = 2
options no_global_heap = true
module wto_ai_behavior_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_order_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_threat_common
require %appGame.wtoai.wto_ai_facing_common
// What one tactics tick knows, built once (wto_ai_tactics_common.das) and read by the scores and
// the behaviors. threatPos: the most dangerous known threat, else the remembered target, else the
// order goal. haltWanted: the trigger channel asks to stand for its shot.
[safe_when_uninitialized]
struct public WtoBhvCtx
hasTarget : bool = false
distTarget : float = 9999.0
remembered : bool = false
threatPos : float3 = float3(0.0, 0.0, 0.0)
threatDir : float3 = float3(1.0, 0.0, 0.0)
topDanger : float = 0.0
aimingCount : int = 0
nearThreat : bool = false
targetValue : float = 0.0
baseGoal : float3 = float3(0.0, 0.0, 0.0)
distGoal : float = 0.0
atGoal : bool = false
urgent : bool = false
offensive : bool = false
haltWanted : bool = false
turnWanted : bool = false
stopRangeOk : bool = false
stale : bool = false
crowded : bool = false
holdReason : int = 0
// Why HOLD applies (holdReason): at the order's post, watching where the target vanished, or
// waiting at the rally point for the group.
let public WTO_HOLD_NONE = 0
let public WTO_HOLD_POST = 1
let public WTO_HOLD_WATCH = 2
let public WTO_HOLD_RALLY = 3
// The order allows standing for a shot at this distance (beyond longRangeM only after a long
// enough clear look at a target showing at least two sample points).
def private wto_bhv_stop_range_ok(distXZ : float; slot : WtoBotSlot const&) : bool
let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M
if distXZ > min(maxStop, WTO_AI_FC_MAX_RANGE_M)
return false
return (distXZ <= WTO_AI_FC_LONG_RANGE_M ||
(slot.perceive.goodLosSec >= WTO_AI_FC_LONG_WINDOW_SEC && slot.perceive.visiblePointCount >= 2))
def private wto_bhv_hold_reason(now : float; myPos : float3; c : WtoBhvCtx const&; slot : WtoBotSlot const&) : int
if c.atGoal
return WTO_HOLD_POST
// A defending or watching bot near its post keeps watching the target's last exit for a while.
if !c.hasTarget && now < slot.perceive.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && c.distGoal <= 35.0
return WTO_HOLD_WATCH
// Wait at the rally point until the group sets off, unless a target is in sight within midRangeM.
if slot.order.rallyHold && slot.order.routeRelayValid && c.distTarget > WTO_AI_FC_MID_RANGE_M
let rallyHoldRad = max(18.0, WTO_AI_CMD_RALLY_RADIUS_M * 0.55)
if wto_xz_dist_sq(myPos, slot.order.routeRelayPos) <= rallyHoldRad * rallyHoldRad
return WTO_HOLD_RALLY
return WTO_HOLD_NONE
// Builds the tick's context. `stale` comes from the action layer (engagement stuck).
[never_inline]
def public wto_bhv_context(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; stale : bool;
slot : WtoBotSlot const&; var c : WtoBhvCtx&)
assume p = slot.perceive
c.baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter
c.distGoal = sqrt(wto_xz_dist_sq(myPos, c.baseGoal))
c.atGoal = c.distGoal <= 8.0
c.hasTarget = p.hasClearLos && !!p.targetEid && !p.targetIsAir
c.distTarget = c.hasTarget ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0
c.remembered = !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
c.threatPos = c.remembered ? p.knownPos : c.baseGoal
let top = slot.threat.topIdx
if top >= 0
c.threatPos = slot.threat.entries[top].pos
c.topDanger = slot.threat.entries[top].danger
c.threatDir = wto_xz_normalize(c.threatPos - myPos, hullFwd)
for i in range(slot.threat.count)
assume entry = slot.threat.entries[i]
if entry.aiming && entry.seesMe
c.aimingCount++
c.nearThreat = c.nearThreat || entry.dist <= WTO_AI_FC_CLOSE_RANGE_M
c.urgent = slot.order.valid && slot.order.urgency == WTO_URGENCY_HIGH
c.offensive = wto_order_is_offensive(slot.order.role)
c.targetValue = min(1.0, wto_threat_danger_of(slot, p.targetEid)) * slot.trigger.hitProbAligned
assume tr = slot.trigger
let requestFresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0
c.haltWanted = requestFresh && tr.targetEid == p.targetEid && slot.fire.gunReady && !slot.spec.isAutocannon && tr.wantSpeedMps <= WTO_AI_FC_STOP_SPEED_MAX_MPS
c.turnWanted = !slot.fire.reloading && wto_face_has_request(slot)
c.stopRangeOk = c.hasTarget && wto_bhv_stop_range_ok(c.distTarget, slot)
c.stale = stale
c.crowded = slot.crowd.isCrowded
c.holdReason = wto_bhv_hold_reason(now, myPos, c, slot)
def private wto_bhv_name(bhv : int) : string
if bhv == WTO_BHV_ADVANCE
return "advance"
if bhv == WTO_BHV_ENGAGE
return "engage"
if bhv == WTO_BHV_HALT
return "halt"
if bhv == WTO_BHV_COVER
return "cover"
if bhv == WTO_BHV_REPOSITION
return "reposition"
if bhv == WTO_BHV_HOLD
return "hold"
if bhv == WTO_BHV_DISPERSE
return "disperse"
if bhv == WTO_BHV_WITHDRAW
return "withdraw"
return "repair"
[never_inline]
def private wto_bhv_scores(now : float; c : WtoBhvCtx const&; slot : WtoBotSlot const&; var s : float[9]&)
for i in range(WTO_BHV_COUNT)
s[i] = 0.0
let urgentF = c.urgent ? 1.0 : 0.0
if !c.atGoal && c.holdReason != WTO_HOLD_RALLY
s[WTO_BHV_ADVANCE] = c.hasTarget ? 0.0 : WTO_AI_BHV_ADVANCE
if c.hasTarget
s[WTO_BHV_ENGAGE] = WTO_AI_BHV_ENGAGE + WTO_AI_BHV_URGENCY_W * urgentF + WTO_AI_BHV_TARGET_VALUE_W * c.targetValue
let halting = slot.tactics.behavior == WTO_BHV_HALT && slot.tactics.state == WTO_STATE_SHORT_HALT
let haltRequest = c.haltWanted || c.turnWanted || halting
if haltRequest && c.stopRangeOk && !c.atGoal && now >= slot.tactics.shortHaltCooldownUntil
let crossfire = float(max(0, c.aimingCount - 1))
let near = c.nearThreat || c.distTarget <= WTO_AI_PERC_NEAR_AWARE_M
let nearBonus = near ? WTO_AI_BHV_NEAR_HALT_BONUS : 0.0
s[WTO_BHV_HALT] = WTO_AI_BHV_HALT + WTO_AI_BHV_URGENCY_W * (1.0 - urgentF) + nearBonus - WTO_AI_BHV_CROSSFIRE * crossfire
let coverRetry = now - slot.tactics.coverFailedAt >= WTO_AI_BHV_COVER_RETRY_SEC
if slot.fire.reloading && (c.hasTarget || c.remembered) && !slot.spec.isAutocannon && coverRetry
let pushing = c.offensive && c.urgent ? 1.0 : 0.0
s[WTO_BHV_COVER] = WTO_AI_BHV_COVER + WTO_AI_BHV_COVER_DANGER_W * min(1.0, c.topDanger) - WTO_AI_BHV_COVER_OFFENSIVE * pushing
if c.stale || slot.tactics.repositionActive
s[WTO_BHV_REPOSITION] = WTO_AI_BHV_REPOSITION
if c.holdReason != WTO_HOLD_NONE
s[WTO_BHV_HOLD] = WTO_AI_BHV_HOLD
if (c.crowded || now < slot.tactics.disperseUntil) && c.distTarget > WTO_AI_FC_CLOSE_RANGE_M
s[WTO_BHV_DISPERSE] = WTO_AI_BHV_DISPERSE
for i in range(WTO_BHV_COUNT)
s[i] = clamp(s[i], 0.0, 1.0)
def private wto_bhv_best(s : float[9] const&; skip : int; var bestScore, secondScore : float&; var second : int&) : int
var best = WTO_BHV_ADVANCE
bestScore = -1.0
secondScore = -1.0
second = -1
for i in range(WTO_BHV_COUNT)
if i == skip
continue
if s[i] > bestScore
secondScore = bestScore
second = best
bestScore = s[i]
best = i
elif s[i] > secondScore
secondScore = s[i]
second = i
return best
def private wto_bhv_hold_sec(bhv : int) : float
if bhv == WTO_BHV_ADVANCE
return WTO_AI_BHV_ADVANCE_HOLD_SEC
if bhv == WTO_BHV_ENGAGE
return WTO_AI_BHV_ENGAGE_HOLD_SEC
if bhv == WTO_BHV_HALT
return WTO_AI_BHV_HALT_HOLD_SEC
if bhv == WTO_BHV_COVER
return WTO_AI_BHV_COVER_HOLD_SEC
if bhv == WTO_BHV_REPOSITION
return WTO_AI_BHV_REPOSITION_HOLD_SEC
if bhv == WTO_BHV_HOLD
return WTO_AI_BHV_POST_HOLD_SEC
if bhv == WTO_BHV_DISPERSE
return WTO_AI_BHV_DISPERSE_HOLD_SEC
return 0.0
// The retreat action owns movement until arrival or timeout. Damage handling runs before this.
[never_inline]
def public wto_bhv_choose(now : float; c : WtoBhvCtx const&; force : bool; var slot : WtoBotSlot&)
assume tac = slot.tactics
if !force && tac.behavior == WTO_BHV_COVER && tac.state == WTO_STATE_RETREAT_COVER
return
let emergency = slot.perceive.lastDamagedAt > tac.scoredDamageAt || (c.nearThreat && !tac.scoredNearThreat)
let due = (force || emergency || now >= tac.nextScoreAt || c.hasTarget != tac.scoredHasTarget ||
slot.fire.reloading != tac.scoredReloading)
if !due
return
tac.nextScoreAt = now + WTO_AI_BHV_SCORE_SEC
tac.scoredHasTarget = c.hasTarget
tac.scoredReloading = slot.fire.reloading
tac.scoredNearThreat = c.nearThreat
tac.scoredDamageAt = slot.perceive.lastDamagedAt
var s : float[9]
wto_bhv_scores(now, c, slot, s)
var bestScore = 0.0
var secondScore = 0.0
var second = -1
let best = wto_bhv_best(s, force ? tac.behavior : -1, bestScore, secondScore, second)
let cur = tac.behavior
let curScore = s[cur]
tac.behaviorScore = curScore
if best == cur || bestScore <= 0.0
return
let held = (now - tac.behaviorSince) < wto_bhv_hold_sec(cur)
if !force && curScore > 0.0 && held && !emergency && bestScore < curScore + WTO_AI_BHV_SWITCH_MARGIN
return
if WTO_AI_DIAG_TELEMETRY
let secondName = second >= 0 ? wto_bhv_name(second) : "-"
print("WTO_AI|BEHAVIOR|t={now}|eid={uint(slot.eid)}|from={wto_bhv_name(cur)}|to={wto_bhv_name(best)}|score={bestScore}|cur={curScore}|second={secondName}:{secondScore}|force={force}\n")
tac.behavior = best
tac.behaviorScore = bestScore
tac.behaviorSince = now
// A behavior that is not scored (repair, ridge withdrawal) took over this tick.
def public wto_bhv_take_over(now : float; bhv : int; var slot : WtoBotSlot&)
assume tac = slot.tactics
if tac.behavior != bhv
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|BEHAVIOR|t={now}|eid={uint(slot.eid)}|from={wto_bhv_name(tac.behavior)}|to={wto_bhv_name(bhv)}|score=1|cur=0|second=-:0|force=true\n")
tac.behavior = bhv
tac.behaviorSince = now
tac.behaviorScore = 1.0
tac.nextScoreAt = now
+98 -1
View File
@@ -20,7 +20,8 @@ let public WTO_BLOCK_FOLIAGE = 6
let public WTO_DENY_OK = 0
let public WTO_DENY_NO_TARGET = 1
let public WTO_DENY_NOT_READY = 2
let public WTO_DENY_SPEED = 3
// The estimated hit probability is below the fire threshold (decision layer design, 6.1).
let public WTO_DENY_HIT_PROB = 3
let public WTO_DENY_LONG_WINDOW = 4
let public WTO_DENY_AIM_ERR = 5
let public WTO_DENY_SETTLE = 6
@@ -30,6 +31,9 @@ let public WTO_DENY_ARC_HARD = 9
let public WTO_DENY_FRIENDLY = 10
let public WTO_DENY_MULTI_GUN = 11
let public WTO_DENY_TRAVERSE = 12
// An autocannon between two bursts (decision layer design, 6.3).
let public WTO_DENY_BURST_PAUSE = 13
let public WTO_DENY_COUNT = 14
[safe_when_uninitialized]
struct public WtoShellProfile
@@ -40,6 +44,8 @@ struct public WtoShellProfile
caliberM : float = 0.09
isSoftShell : bool = false
isAntiArmor : bool = true
// Stock maximum penetration (calc_max_penetration), mm.
penMm : float = 0.0
[safe_when_uninitialized]
struct public WtoPerceiveState
@@ -75,7 +81,77 @@ struct public WtoPerceiveState
lastRadioSentAt : float = -100.0
expEids : EntityId[8]
expScore : float[8]
expDanger : float[8]
expGoodLosSec : float[8]
expSeenAt : float[8]
expPos : float3[8]
nextLookAroundAt : float = 0.0
lookAroundUntil : float = -100.0
// When the engaged target was last seen firing (it is likely reloading for a while after).
targetShotAt : float = -100.0
targetFleeting : bool = false
// One discovered enemy in the bot's threat table (decision layer design, section 4). `seen`: seen
// clearly (fireable); `seesMe`: in line of sight this tick; `aiming`: its hull points at the bot or
// it hit the bot recently.
[safe_when_uninitialized]
struct public WtoThreatEntry
eid : EntityId = INVALID_ENTITY_ID
seen : bool = false
pos : float3 = float3(0.0, 0.0, 0.0)
dist : float = 0.0
aiming : bool = false
seesMe : bool = false
danger : float = 0.0
// Rebuilt every perception tick, with the highest danger overall and among visible contacts.
[safe_when_uninitialized]
struct public WtoThreatTable
count : int = 0
entries : WtoThreatEntry[8]
topIdx : int = -1
topVisibleIdx : int = -1
// Why the turret points where it does this frame (WtoTurretState.lookReason, replay trace).
let public WTO_LOOK_NONE = 0
let public WTO_LOOK_ENGAGE = 1
let public WTO_LOOK_THREAT = 2
let public WTO_LOOK_WATCH = 3
let public WTO_LOOK_MEMORY = 4
let public WTO_LOOK_CUE = 5
let public WTO_LOOK_SCAN = 6
// Turret channel (decision layer design, section 5): the threat it is looking at and until when
// that look is held, plus the world direction it was asked for this frame and why.
[safe_when_uninitialized]
struct public WtoTurretState
lookEid : EntityId = INVALID_ENTITY_ID
holdUntil : float = -100.0
lookReason : int = 0
wishDir : float3 = float3(1.0, 0.0, 0.0)
[safe_when_uninitialized]
struct public WtoWeaponBurst
untilAt : float = -100.0
pauseUntil : float = -100.0
lastShotAt : float = -100.0
// The main gun's hit estimate and speed request, plus independent burst timers.
[safe_when_uninitialized]
struct public WtoTriggerState
hitProb : float = 0.0
hitProbAligned : float = 0.0
threshold : float = 1.0
aimSlackDeg : float = 1.0
wantSpeedMps : float = 99.0
wantSpeedAt : float = -100.0
targetEid : EntityId = INVALID_ENTITY_ID
biasEpoch : int = 0
burstUntil : float = -100.0
burstPauseUntil : float = -100.0
secondary : WtoWeaponBurst = WtoWeaponBurst()
coaxial : WtoWeaponBurst = WtoWeaponBurst()
auxShots : int = 0
[safe_when_uninitialized]
struct public WtoGunTraverse
@@ -85,27 +161,48 @@ struct public WtoGunTraverse
hasPitchTable : bool = false
pitchSector : float4 = float4(1.0, 0.0, 1.0, 0.0)
[safe_when_uninitialized]
struct public WtoMountFire
shellHash : uint = 0u
shellValid : bool = false
automatic : bool = false
shell : WtoShellProfile = WtoShellProfile()
traverseReady : bool = false
traverse : WtoGunTraverse = WtoGunTraverse()
[safe_when_uninitialized]
struct public WtoFireState
turretNo : int = -1
traverseTurretNo : int = -1
traverse : WtoGunTraverse = WtoGunTraverse()
hullAimTarget : EntityId = INVALID_ENTITY_ID
hullAimForPitch : bool = false
mountCanAim : bool = true
hullAimDir : float3 = float3(0.0, 0.0, 0.0)
gunReady : bool = false
reloading : bool = false
gunDamaged : bool = false
notReadySince : float = -100.0
loadedBulletIdx : int = -1
ammoRemaining : int = -1
rackTurret : int = -1
rackRounds : int = -1
rackBySet : int[12]
mounts : WtoMountFire[16]
activeSpeedMps : float = 880.0
activeDragCx : float = 0.35
activeMassKg : float = 10.0
activeCaliberM : float = 0.09
pitchBlocked : bool = false
pitchAtLimit : bool = false
pitchClampSec : float = 0.0
curYawDeg : float = 0.0
curPitchDeg : float = 0.0
prevPitchDeg : float = 0.0
servoInit : bool = false
sightPrimaryIndex : int = -1
hasBarrelSight : bool = false
barrelSight : float3 = float3(1.0, 0.0, 0.0)
aimTargetEid : EntityId = INVALID_ENTITY_ID
prevAimOffset : float3 = float3(0.0, 0.0, 0.0)
prevAimAt : float = -100.0
+2 -2
View File
@@ -13,6 +13,7 @@ require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_lanes_common
require %appGame.wtoai.wto_ai_lanes_build_common
require %appGame.wtoai.wto_ai_commander_anchors_common
require %appGame.wtoai.wto_ai_commander_plans_common
@@ -193,5 +194,4 @@ def public wto_commander_update_all(world : WtoWorldSnap const&; now : float;
wto_lanes_update_team_intel(world, now, lanes)
wto_cmd_assign_army(world, 1, now, forceRebalance, lanes, bots)
wto_cmd_assign_army(world, 2, now, forceRebalance, lanes, bots)
wto_lanes_update_rallies(world, 1, now, lanes, bots)
wto_lanes_update_rallies(world, 2, now, lanes, bots)
wto_lanes_tick_rallies(world, now, lanes, bots)
+11 -6
View File
@@ -5,8 +5,8 @@ module wto_ai_diag_common shared
require ecs
require math
require pathfinder
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_nav_types_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
@@ -16,7 +16,7 @@ def private wto_log_bot_and_cap_samples(world : WtoWorldSnap const&; bots : WtoB
if !bots[i].used || sampled >= 2
continue
assume b = bots[i]
print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|drift={b.fire.aimDriftDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n")
print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|drift={b.fire.aimDriftDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|bump={b.nav.bumperClearM}|wall={b.nav.wallDistM}|seg={b.route.segIdx}/{b.route.corridorLen}|src={b.route.source}|path={b.route.lastStatus}|off={b.route.offTrackM}\n")
sampled++
for c in range(world.capCount)
assume z = world.caps[c]
@@ -33,7 +33,10 @@ def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float;
var ridgeNow = 0
var revEvents = 0
var ridgeWithdraws = 0
var detours = 0
var stuckEv = 0
var unreachable = 0
var noGoal = 0
var paths = 0
var shots = 0
var errSum = 0.0
var maxErr = 0.0
@@ -53,12 +56,14 @@ def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float;
ridgeNow += b.tactics.onExposedRidge ? 1 : 0
revEvents += b.nav.reverseCount
ridgeWithdraws += b.nav.ridgeWithdrawEvents
detours += b.route.detourCount
stuckEv += b.nav.unstickEvents
unreachable += b.nav.unreachableEvents
noGoal += b.route.noGoalCount
paths += b.route.requests
shots += b.fire.shotCount
errSum += b.fire.shotErrSumDeg
maxErr = max(maxErr, b.fire.maxShotErrDeg)
let avgErr = shots > 0 ? (errSum / float(shots)) : 0.0
let jams = wto_world_active_jams(world, now)
let nm1 = pathfinder_is_loaded_ex(1)
print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|detours={detours}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}|nm1={nm1}\n")
print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|paths={paths}|stuckEv={stuckEv}|unreachable={unreachable}|noGoal={noGoal}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}\n")
wto_log_bot_and_cap_samples(world, bots)
+24 -19
View File
@@ -1,6 +1,7 @@
// Chassis drive actuator: translates `WtoDriveCmd` into closed-loop `VehiclePhysActor` axes
// (throttle, steering, brakes, auto-transmission) with space-aware 3-point turns, smooth
// long-distance reverse control, and dead-echo watchdog return to stock movement.
// reverse control, and a dead-echo watchdog. Speed limits for corners and obstacles come from
// the navigation layer through the command; heading error alone slows the vehicle here.
options indenting = 2
options no_global_heap = true
module wto_ai_drive_common shared
@@ -17,6 +18,8 @@ require vehicle
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()
@@ -70,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;
@@ -126,10 +120,11 @@ def private wto_compute_reverse_axes(cmd : WtoDriveCmd const&; spec : WtoVehicle
// Coordinate-free signed rear angle: >0 means desired rear travel lies toward hull LEFT (+Z).
let rearErr = atan2(dot(wishRear, left), dot(wishRear, rear))
outStr = clamp(rearErr * 1.45 + omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
let maxSafeRev = min(spec.vMaxRev, sqrt(max(1.0, (cmd.rearClearM - 1.8) * 2.2)))
let vTarget = -clamp(cmd.speedMps, 1.2, max(1.4, maxSafeRev))
let vErr = vTarget - vFwd
outThr = vErr < -0.15 ? clamp(-0.52 + vErr * 0.32, -1.0, -0.35) : -0.28
let clearanceCap = sqrt(max(0.0, (cmd.rearClearM - 1.8) * 2.2))
let vTarget = min(cmd.speedMps, min(spec.vMaxRev, clearanceCap))
let response = (vTarget + vFwd) / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS
outThr = -clamp(response, 0.0, 1.0)
outBrk = clamp(-response, 0.0, 1.0)
[never_inline]
def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
@@ -142,18 +137,16 @@ def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleS
var vLimit = min(cmd.speedMps, spec.vMaxFwd)
if absErr > 0.22
let radiusEst = max(4.0, 14.0 / max(0.25, absErr))
vLimit = min(vLimit, sqrt(WTO_AI_NAV_CORNER_BRAKE_ACCEL * radiusEst))
if cmd.frontClearM < 12.0
vLimit = min(vLimit, max(2.2, (cmd.frontClearM - 2.0) * 0.75))
vLimit = min(vLimit, sqrt(WTO_AI_PF_CORNER_LAT_ACCEL * radiusEst))
let vErr = vLimit - speedMps
if firingOnMove
let response = vErr / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS
outThr = clamp(response, 0.0, 1.0)
outBrk = clamp(-response, 0.0, 1.0)
return
if vErr < -1.5
if vErr < 0.0
outThr = 0.0
outBrk = clamp((-vErr - 1.2) * 0.35, 0.2, 1.0)
outBrk = clamp(-vErr / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS, 0.0, 1.0)
elif vErr >= 0.6
outThr = 1.0
else
@@ -193,6 +186,17 @@ def private wto_ensure_phys_owner(gm : IGroundModel const?; var actor : VehicleP
st.routeBOwned = true
return st.routeBOwned
// Keep the physical brake active even while a pivot or unstick has requested throttle.
def private wto_drive_traffic_brake(vFwd : float; nav : WtoNavState const&; var thr, brk : float&)
if (thr > 0.0 && nav.frontTrafficSpeedCap <= 0.05) || (thr < 0.0 && nav.rearTrafficSpeedCap <= 0.05)
thr = 0.0
brk = 1.0
let excess = max(vFwd - nav.frontTrafficSpeedCap, -vFwd - nav.rearTrafficSpeedCap)
if excess > 0.0
if thr * vFwd > 0.0
thr = 0.0
brk = max(brk, clamp(excess / WTO_AI_NAV_MOVING_FIRE_SPEED_RAMP_MPS, 0.0, 1.0))
[never_inline]
def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, velocity : float3;
var slot : WtoBotSlot&)
@@ -215,6 +219,7 @@ def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, veloci
let firingOnMove = slot.tactics.state == WTO_STATE_RUN_AND_GUN
let speed = firingOnMove ? length(velocity) : vFwd
wto_compute_cruise_axes(cmd, slot.spec, fwd, left, speed, st.omegaYawRad, firingOnMove, thr, str, brk)
wto_drive_traffic_brake(vFwd, slot.nav, thr, brk)
st.prevThr = thr
st.prevStr = str
wto_set_phys_axes(actor, thr, str, brk, hand)
+42 -16
View File
@@ -6,6 +6,7 @@ module wto_ai_estimate_common shared
require ecs
require math
require Ballistics
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
@@ -91,30 +92,37 @@ def public wto_est_on_los_lost(now : float; selfEid : EntityId; var p : WtoPerce
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|WATCH|eid={uint(selfEid)}|tgt={uint(p.targetEid)}|dur={dur}\n")
// The same estimated target motion is used to lead and to validate the real barrel shot.
def public wto_est_target_vel(p : WtoPerceiveState const&) : float3
let scale = p.sampleCount >= 2 ? clamp(0.35 + 0.65 * p.velQuality, 0.0, 1.0) : 0.0
return p.estVel * scale
def public wto_shot_drag(dragCx, massKg, caliberM : float) : float
let area = 0.25 * WTO_PI * caliberM * caliberM
return 0.5 * 1.225 * dragCx * area / max(0.1, massKg)
def private wto_est_avg_speed(speedMps, drag, dist : float) : float
let dragDist = min(drag * dist, 60.0)
if dragDist <= 1.0e-4
return max(120.0, speedMps)
return max(120.0, speedMps * (dragDist / (exp(dragDist) - 1.0)))
[never_inline]
def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3;
var slot : WtoBotSlot&;
var outLeadPt : float3&) : float
def private wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3; speedMps, drag : float;
var slot : WtoBotSlot&; var outLeadPt : float3&) : float
assume p = slot.perceive
let rawDelta = aimBase - muzzlePos
let rawDist = length(rawDelta)
let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss))
// Lead uses ONLY our own visual velocity estimate, scaled by observation quality.
let leadScale = p.sampleCount >= 2 ? clamp(0.35 + 0.65 * p.velQuality, 0.0, 1.0) : 0.0
let usedVel = p.estVel * leadScale
let vEff = wto_est_avg_speed(speedMps, drag, rawDist)
let usedVel = wto_est_target_vel(p)
var leadPt = aimBase
var tof = 0.0
for _iter in range(2)
tof = clamp(length(leadPt - muzzlePos) / vEff, 0.0, 3.5)
leadPt = aimBase + usedVel * tof - myVel * (tof * 0.85)
leadPt = aimBase + (usedVel - myVel) * tof
// Sample bounded natural bias ONCE per shooting opportunity (target + shot + state + 12m grid).
let gx = uint(int(muzzlePos.x / 12.0) + 4096)
let gz = uint(int(muzzlePos.z / 12.0) + 4096)
let key = (uint(p.targetEid) ^ (uint(slot.fire.shotCount) * 2654435761u) ^
(uint(slot.tactics.state) * 40503u) ^ (gx * 73856093u) ^ (gz * 19349663u))
// Keep the same bias until the target, shot opportunity or velocity estimate changes.
let key = uint(p.targetEid) ^ (uint(slot.trigger.biasEpoch) * 2654435761u)
if !p.oppSeeded || p.oppKey != key
p.oppKey = key
p.oppSeeded = true
@@ -125,10 +133,28 @@ def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3;
// Error envelope shrinks naturally as observation quality converges.
let tgtSpd = length(p.estVel)
let leadSpread = tgtSpd * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality)
let distSpread = WTO_AI_EST_BASE_SIGMA_M * clamp(rawDist / 350.0, 0.25, 2.6) * (1.2 - 0.55 * p.velQuality)
let distSpread = (1.0 - WTO_AI_FC_AIM_SKILL) * WTO_AI_EST_BASE_SIGMA_M * clamp(rawDist / 350.0, 0.25, 2.6) * (1.2 - 0.55 * p.velQuality)
let latOff = clamp((leadSpread + distSpread) * p.oppBiasU, -WTO_AI_EST_MAX_BIAS_M, WTO_AI_EST_MAX_BIAS_M)
let vertOff = clamp(distSpread * 0.65 * p.oppBiasV, -WTO_AI_EST_MAX_BIAS_M * 0.5, WTO_AI_EST_MAX_BIAS_M * 0.5)
let toAimXZ = wto_xz_normalize(rawDelta, float3(1.0, 0.0, 0.0))
let latAxis = float3(-toAimXZ.z, 0.0, toAimXZ.x)
outLeadPt = leadPt + latAxis * latOff + float3(0.0, vertOff, 0.0)
return rawDist
[never_inline]
def public wto_solve_ballistic_aim(muzzlePos, myVel, aimBase : float3; speedMps, dragCx, massKg, caliberM : float;
var slot : WtoBotSlot&; var outAimPt, outWishDir : float3&) : float
var leadPt = aimBase
let drag = wto_shot_drag(dragCx, massKg, caliberM)
let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, speedMps, drag, slot, leadPt)
let vEff = wto_est_avg_speed(speedMps, drag, rawDist)
outAimPt = leadPt
var arcDir = float3(0.0, 0.0, 0.0)
if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25
outWishDir = normalize(arcDir)
else
let d = max(1.0, length(leadPt - muzzlePos))
let tof = d / vEff
let dropComp = float3(0.0, 0.5 * 9.81 * tof * tof, 0.0)
outWishDir = normalize(leadPt + dropComp - muzzlePos)
return rawDist
+103
View File
@@ -0,0 +1,103 @@
// Hull facing and the direction of travel along a navigation corridor.
options indenting = 2
options no_global_heap = true
module wto_ai_facing_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_nav_types_common
require %appGame.wtoai.wto_ai_follow_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)
def private wto_face_rotate(dir : float3; rad : float) : float3
return float3(dir.x * cos(rad) - dir.z * sin(rad), 0.0, dir.x * sin(rad) + dir.z * cos(rad))
// `toThreat` turned by hullAngleDeg toward whichever side is nearer the current hull heading.
def private wto_face_angled(toThreat, hullFwd : float3) : float3
let rad = WTO_AI_BHV_HULL_ANGLE_DEG * WTO_DEG_TO_RAD
let a = wto_face_rotate(toThreat, rad)
let b = wto_face_rotate(toThreat, -rad)
return dot(a, hullFwd) >= dot(b, hullFwd) ? a : b
// Where the threat to face is: the most dangerous entry of the threat table above
// behavior.faceMinDanger, else the engaged target while remembered.
def private wto_face_threat_pos(now : float; slot : WtoBotSlot const&; var outPos : float3&) : bool
let top = slot.threat.topIdx
if top >= 0 && slot.threat.entries[top].danger >= WTO_AI_BHV_FACE_MIN_DANGER
outPos = slot.threat.entries[top].pos
return true
assume p = slot.perceive
if !!p.targetEid && !p.targetIsAir && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
outPos = p.knownPos
return true
return false
// The turret can request a turn for a visible target that is outside the mount traverse.
def public wto_face_has_request(slot : WtoBotSlot const&) : bool
let target = slot.fire.hullAimTarget
if !target || !slot.perceive.hasClearLos || target != slot.perceive.targetEid || slot.tactics.immobilized
return false
return wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) != WTO_DRIVE_HALT
[never_inline]
def public wto_face_update(now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&)
assume tac = slot.tactics
tac.faceActive = false
tac.faceFromThreat = false
tac.faceForGun = false
var threatPos = myPos
if !wto_face_bound(slot.spec) || !wto_face_threat_pos(now, slot, threatPos)
return
tac.faceThreatDir = wto_xz_normalize(threatPos - myPos, hullFwd)
tac.faceDir = wto_face_angled(tac.faceThreatDir, hullFwd)
tac.faceActive = true
tac.faceFromThreat = true
// A standing action can keep the hull facing its gun's target if the strongest threat remains in front.
[never_inline]
def public wto_face_accept_gun(hullFwd : float3; var slot : WtoBotSlot&)
assume tac = slot.tactics
if !wto_face_has_request(slot)
return
let wanted = wto_xz_normalize(slot.fire.hullAimDir, hullFwd)
let allowedAngle = min(90.0, WTO_AI_BHV_HULL_ANGLE_DEG + WTO_AI_BHV_FACE_TOL_DEG)
if tac.faceFromThreat && dot(wanted, tac.faceThreatDir) < cos(allowedAngle * WTO_DEG_TO_RAD)
return
tac.faceDir = wanted
tac.faceActive = true
tac.faceForGun = true
def public wto_face_side_exposed(slot : WtoBotSlot const&) : bool
assume tac = slot.tactics
if !tac.faceFromThreat
return false
let travel = wto_xz_normalize(slot.nav.steerDir, tac.faceThreatDir)
return abs(dot(travel, tac.faceThreatDir)) < sin(WTO_AI_BHV_FACE_TOL_DEG * WTO_DEG_TO_RAD)
// Choose steering direction after tracking the active corridor and before updating traffic.
[never_inline]
def public wto_face_reverse_update(now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&)
assume tac = slot.tactics
assume rt = slot.route
let moving = tac.behavior == WTO_BHV_ADVANCE || tac.behavior == WTO_BHV_ENGAGE
let able = slot.spec.vMaxRev >= WTO_AI_BHV_REVERSE_MIN_MPS && !tac.immobilized
var want = moving && able && tac.faceFromThreat && rt.corridorLen >= 2
if want
let seg = clamp(rt.segIdx, 0, rt.corridorLen - 2)
let travel = wto_xz_normalize(rt.corridor[seg + 1] - rt.corridor[seg], hullFwd)
let opposite = dot(travel, tac.faceThreatDir) <= cos(WTO_AI_BHV_REVERSE_ANGLE_DEG * WTO_DEG_TO_RAD)
want = opposite && wto_follow_near_turn(rt, myPos, WTO_AI_BHV_REVERSE_MAX_TURN_M)
if want == tac.reverseTravel
return
if want && (now - tac.reverseSince) < WTO_AI_BHV_REVERSE_HOLD_SEC
return
tac.reverseTravel = want
tac.reverseSince = now
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|REVERSE_TRAVEL|t={now}|eid={uint(slot.eid)}|on={want}\n")
+148
View File
@@ -0,0 +1,148 @@
// Secondary and coaxial guns have their own aim solution, readiness, burst timer and safety checks.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_aux_common shared
require ecs
require math
require DagorMath
require Mission
require Unit
require Weapon
require %game.utils.utils_common
require %appGame.wtoai.wto_ai_config_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_trigger_common
require %appGame.wtoai.wto_ai_traverse_common
require %appGame.wtoai.wto_ai_weapon_profile_common
require %appGame.wtoai.wto_ai_fire_checks_common
def private wto_aux_in_range(dist : float) : bool
return WTO_AI_FC_AUX_ENABLED && dist <= min(WTO_AI_FC_AUX_MAX_RANGE_M, WTO_AI_FC_MAX_RANGE_M)
def private wto_aux_group(groupNo : int) : bool
return groupNo == int(WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY) || groupNo == int(WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN)
[never_inline]
def public wto_fire_aux_aim(var unit : Unit?; className : string; dist : float; var slot : WtoBotSlot&) : bool
if !wto_aux_in_range(dist)
return false
var changed = false
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if !wto_aux_group(int(turret.triggerGroupNo)) || tIdx >= length(slot.fire.mounts)
continue
let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex))
if weapon == null || weapon.isDummyGun || weapon.prop.launcher
continue
let gun = as_gun(weapon)
assume mount = slot.fire.mounts[tIdx]
if gun == null || gun.isInoperable || !wto_mount_load_shell(unit, className, tIdx, gun, mount)
continue
var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) <= 0.25
continue
let base = slot.perceive.visibleAimPt
var aimPt = base
var direction = gunTm[0]
let _range = wto_solve_ballistic_aim(gunTm[3], unit.vel, base, mount.shell.speedMps, mount.shell.dragCx, mount.shell.massKg, mount.shell.caliberM, slot, aimPt, direction)
if wto_aim_aux_mount(unit, className, tIdx, direction, mount)
changed = true
return changed
[never_inline]
def private wto_aux_check_barrel(world : WtoWorldSnap const&; unit : Unit const?; weapon : Weapon const?;
now, dist : float; target : WtoUnitSnap const&; mount : WtoMountFire const&;
var slot : WtoBotSlot&) : bool
var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) <= 0.25
return false
let actual = normalize(gunTm[0])
let base = slot.perceive.visibleAimPt
var aimPt = base
var direction = actual
let _range = wto_solve_ballistic_aim(gunTm[3], unit.vel, base, mount.shell.speedMps, mount.shell.dragCx, mount.shell.massKg, mount.shell.caliberM, slot, aimPt, direction)
let error = wto_trig_aim_error(actual, direction)
if !wto_trig_aux_aim_ok(now, dist, length(unit.vel), error, unit.pos, target, mount, slot)
return false
var blockCode = WTO_BLOCK_NONE
return wto_fire_check_barrel(world, unit, slot, gunTm[3], actual, aimPt, mount.shell, !mount.automatic, blockCode) == WTO_DENY_OK
// Count all guns the native trigger would fire, including barrels without a usable turret entry.
def private wto_aux_ready_count(unit : Unit const?; group : WeaponTriggerGroups) : int
var ready = 0
var supported = true
get_weapons_by_trigger_group(unit.weap.Weapons, group) <| $(weapons : array<Weapon const? const> const#)
for i in range(length(weapons))
assume weapon = weapons[i]
if weapon == null || weapon.isDummyGun
continue
let gun = as_gun(weapon)
if weapon.prop.launcher || gun == null
supported = false
elif !gun.isInoperable && gun.isReadyToShoot
ready++
return supported ? ready : 0
[never_inline]
def private wto_aux_fire_group(world : WtoWorldSnap const&; var unit : Unit?; className : string;
group : WeaponTriggerGroups; now, dist : float; target : WtoUnitSnap const&;
var slot : WtoBotSlot&; var burst : WtoWeaponBurst&; var fireBudget : int&)
if fireBudget <= 0 || (now >= burst.untilAt && now < burst.pauseUntil)
return
let needed = wto_aux_ready_count(unit, group)
if needed <= 0
return
var checked = 0
var rapid = true
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if int(turret.triggerGroupNo) != int(group) || tIdx >= length(slot.fire.mounts)
continue
let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex))
if weapon == null || weapon.isDummyGun
continue
let gun = as_gun(weapon)
if gun == null || gun.isInoperable || !gun.isReadyToShoot
continue
assume mount = slot.fire.mounts[tIdx]
if checked == 0
fireBudget--
if (!wto_mount_load_shell(unit, className, tIdx, gun, mount) ||
!wto_aux_check_barrel(world, unit, weapon, now, dist, target, mount, slot))
return
checked++
rapid = rapid && mount.automatic
if checked != needed
return
if rapid
var opening = false
if wto_trig_burst_gate(now, true, burst.untilAt, burst.pauseUntil, opening) != WTO_DENY_OK
return
elif now - burst.lastShotAt < WTO_AI_FC_MIN_SHOT_INTERVAL_SEC
return
unit_single_shot(unit, int(group))
burst.lastShotAt = now
slot.trigger.auxShots++
[never_inline]
def public wto_fire_aux_update(world : WtoWorldSnap const&; var unit : Unit?; className : string;
now, dist : float; var slot : WtoBotSlot&; var fireBudget : int&)
if !wto_aux_in_range(dist)
return
let idx = wto_world_find_unit(world, slot.perceive.targetEid)
if idx < 0
return
assume target = world.units[idx]
var secondary = slot.trigger.secondary
wto_aux_fire_group(world, unit, className, WeaponTriggerGroups.TRIGGER_GROUP_SECONDARY, now, dist, target,
slot, secondary, fireBudget)
slot.trigger.secondary = secondary
if WTO_AI_FC_AUX_FIRE_AT_ARMOR || target.isLightTag || target.halfWid < 1.35
var coaxial = slot.trigger.coaxial
wto_aux_fire_group(world, unit, className, WeaponTriggerGroups.TRIGGER_GROUP_COAXIAL_GUN, now, dist, target,
slot, coaxial, fireBudget)
slot.trigger.coaxial = coaxial
@@ -0,0 +1,110 @@
// Per-barrel pre-fire checks: muzzle clearance, the drag-integrated trajectory and friendlies.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_checks_common shared
require ecs
require math
require DagorMath
require Unit
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_sight_common
require %appGame.wtoai.wto_ai_estimate_common
require %appGame.wtoai.wto_ai_trigger_common
require %appGame.wtoai.wto_ai_world_common
[safe_when_uninitialized]
struct private WtoShotWindow
center : float3 = float3(0.0, 0.0, 0.0)
velocity : float3 = float3(0.0, 0.0, 0.0)
along : float3 = float3(1.0, 0.0, 0.0)
halfWidth : float = 0.0
halfHeight : float = 0.0
def private wto_shot_hits_window(window : WtoShotWindow const&; at : float3; time : float) : bool
let miss = at - (window.center + window.velocity * time)
let across = float3(-window.along.z, 0.0, window.along.x)
return abs(dot(miss, across)) <= window.halfWidth && abs(miss.y) <= window.halfHeight
[never_inline]
def public wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId;
army : int; p0, p1 : float3; tMid : float) : bool
let delta = p1 - p0
let segLen = length(delta)
if segLen < 0.2
return true
let dir = delta / segLen
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid
continue
let predPos = u.pos + u.vel * tMid + float3(0.0, 1.3, 0.0)
let along = clamp(dot(predPos - p0, dir), 0.0, segLen)
let clearR = WTO_AI_FC_FRIENDLY_CORRIDOR_M + u.halfWid
if length_sq(predPos - (p0 + dir * along)) < clearR * clearR
return false
return true
[never_inline]
def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&; selfEid, targetEid : EntityId; army : int;
muzzlePos, liveDir, carrierVel : float3; shell : WtoShellProfile const&;
window : WtoShotWindow const&; checkMiss : bool; var outBlock : int&) : int
let dragK = wto_shot_drag(shell.dragCx, shell.massKg, shell.caliberM)
var cur = muzzlePos
var vel = liveDir * shell.speedMps + carrierVel
var t = 0.0
for step in range(64)
let spd = length(vel)
let remaining = dot(window.center + window.velocity * t - cur, window.along)
if spd < 20.0 || remaining <= 0.0
return WTO_DENY_AIM_ERR
let segWant = min(WTO_AI_FC_BALLISTIC_STEP_M, remaining)
let dt = clamp(segWant / spd, 0.004, 0.14)
let accel = float3(0.0, -9.81, 0.0) - vel * (dragK * spd)
var next = cur + vel * dt + accel * (0.5 * dt * dt)
let nextRemaining = dot(window.center + window.velocity * (t + dt) - next, window.along)
let ends = nextRemaining <= 0.0
var segmentTime = dt
if ends
let fraction = clamp(remaining / max(1.0e-5, remaining - nextRemaining), 0.0, 1.0)
next = lerp(cur, next, fraction)
segmentTime *= fraction
let trimS = step == 0 ? 0.35 : 0.0
let trimE = ends ? 0.65 : 0.0
let blk = wto_sight_hard_segment_blocked(world, selfEid, targetEid, cur, next, WTO_AI_FC_BALLISTIC_SWEEP_R_M, trimS, trimE)
if blk != WTO_BLOCK_NONE
outBlock = blk
return WTO_DENY_ARC_HARD
if !wto_gate_friendly_segment_clear(world, selfEid, army, cur, next, t + segmentTime * 0.5)
return WTO_DENY_FRIENDLY
t += segmentTime
if ends
return (!checkMiss || wto_shot_hits_window(window, next, t)) ? WTO_DENY_OK : WTO_DENY_AIM_ERR
cur = next
vel = vel + accel * dt
return WTO_DENY_AIM_ERR
[never_inline]
def public wto_fire_check_barrel(world : WtoWorldSnap const&; unit : Unit const?;
slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3;
shell : WtoShellProfile const&; checkMiss : bool;
var outBlock : int&) : int
let straightBlk = wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzlePos, aimPt, 0.05, 0.35, 0.65)
if straightBlk != WTO_BLOCK_NONE
outBlock = straightBlk
return WTO_DENY_MUZZLE_HARD
let idx = wto_world_find_unit(world, slot.perceive.targetEid)
if idx < 0
return WTO_DENY_NO_TARGET
assume target = world.units[idx]
var window = WtoShotWindow()
window.center = slot.perceive.visibleAimPt
window.velocity = wto_est_target_vel(slot.perceive)
window.along = wto_xz_normalize(window.center - muzzlePos, liveDir)
let dist = sqrt(wto_xz_dist_sq(unit.pos, target.pos))
wto_trig_target_half(unit.pos, target, dist, slot.perceive.visiblePointCount, window.halfWidth, window.halfHeight)
return wto_gate_check_ballistic_arc(world, slot.eid, slot.perceive.targetEid, slot.army,
muzzlePos, liveDir, unit.vel, shell, window, checkMiss, outBlock)
+107 -89
View File
@@ -1,5 +1,7 @@
// Turret servo, active loaded-shell inspection, and ballistic aim solver.
// All ground weapon firing goes exclusively through wto_fire_gate_try_shoot.
// 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
@@ -13,16 +15,18 @@ require Mission
require Unit
require IGroundModel
require Weapon
require Ballistics
require %game.utils.utils_common
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_trigger_common
require %appGame.wtoai.wto_ai_fire_aux_common
require %appGame.wtoai.wto_ai_ammo_common
[never_inline]
def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&)
@@ -51,18 +55,21 @@ def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec cons
return
[never_inline]
def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&; wantSoft : bool)
if gun == null || spec.isAutocannonBelt
def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&; wantSoft : bool; fc : WtoFireState const&)
if gun == null || spec.isAutocannon
return
let setCount = length(gun.properties.bulletSets)
if setCount < 2
return
var bestSoft = -1
var bestArmor = -1
var bestArmorPen = -1.0
var firstAvail = -1
for bsIdx in range(setCount)
assume bs = gun.properties.bulletSets[bsIdx]
if bs.bulletsCount <= 0 || length(bs.bullet) <= 0 || bs.bullet[0] == null
let loaded = bsIdx == int(gun.chosenBulletType) && gun.currentLoadedAmmoCount > 0
let stocked = fc.rackTurret == fc.turretNo && bsIdx < length(fc.rackBySet) && fc.rackBySet[bsIdx] > 0
if !(loaded || stocked || bs.bulletsCount > 0) || length(bs.bullet) <= 0 || bs.bullet[0] == null
continue
if firstAvail < 0
firstAvail = bsIdx
@@ -75,8 +82,9 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&
continue
if spec.shells[si].isSoftShell && bestSoft < 0
bestSoft = bsIdx
elif spec.shells[si].isAntiArmor && bestArmor < 0
if spec.shells[si].isAntiArmor && spec.shells[si].penMm > bestArmorPen
bestArmor = bsIdx
bestArmorPen = spec.shells[si].penMm
break
var wantIdx = wantSoft ? (bestSoft >= 0 ? bestSoft : bestArmor) : (bestArmor >= 0 ? bestArmor : firstAvail)
if wantIdx < 0
@@ -84,6 +92,16 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&
if wantIdx >= 0 && int(gun.nextBulletType) != wantIdx
gun.nextBulletType = uint8(wantIdx)
// The first working gun of the primary group becomes the weapon the fire control aims and loads.
[never_inline]
def private wto_take_primary_gun(var gun : WTGun?; turretNo, previousTurret : int; spec : WtoVehicleSpec const&;
wantSoftShell : bool; var fc : WtoFireState&)
fc.turretNo = turretNo
if fc.turretNo != previousTurret
fc.loadedBulletIdx = -1
wto_select_next_shell(gun, spec, wantSoftShell, fc)
wto_sync_active_shell(gun, spec, fc)
[never_inline]
def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
spec : WtoVehicleSpec const&; wantSoftShell : bool;
@@ -93,6 +111,7 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
fc.gunReady = false
fc.reloading = false
fc.gunDamaged = false
fc.ammoRemaining = -1
if unit == null || unit.weap == null
return -1
var selected = -1
@@ -124,18 +143,26 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
anyAlive = true
if selected < 0
selected = index
fc.turretNo = weapon.turretNo
if fc.turretNo != previousTurret
fc.loadedBulletIdx = -1
wto_select_next_shell(gun, spec, wantSoftShell)
wto_sync_active_shell(gun, spec, fc)
if gun.isReadyToShoot
fc.gunReady = true
wto_take_primary_gun(gun, int(weapon.turretNo), previousTurret, spec, wantSoftShell, fc)
fc.ammoRemaining = wto_main_gun_ammo(gun, fc)
anyReserve = anyReserve || fc.ammoRemaining > 0
fc.gunReady = fc.gunReady || gun.isReadyToShoot
totalLoaded += max(0, gun.currentLoadedAmmoCount)
if gun.currentLoadedAmmoCount > 0 || gun.currentBulletSet.bulletsCount > 0 || weapon.countBullets > 0
anyReserve = true
wto_finish_weapon_state(now, spec, anyGun, anyAlive, anyReserve, totalLoaded, fc)
return selected
// Damage, reload and shot confirmation from what wto_inspect_primary_weapon found.
[never_inline]
def private wto_finish_weapon_state(now : float; spec : WtoVehicleSpec const&; anyGun, anyAlive, anyReserve : bool;
totalLoaded : int; var fc : WtoFireState&)
fc.gunDamaged = anyGun && !anyAlive
fc.reloading = anyAlive && !fc.gunReady && anyReserve
// An autocannon is not ready between two rounds; only a longer wait is a reload.
if fc.gunReady || !anyAlive
fc.notReadySince = now
let acReload = (now - fc.notReadySince) > WTO_AI_FC_AC_RELOAD_DETECT_SEC
fc.reloading = anyAlive && !fc.gunReady && anyReserve && (!spec.isAutocannon || acReload)
if fc.pendingShotConfirm
if (fc.prevLoadedAmmo >= 0 && totalLoaded < fc.prevLoadedAmmo) || !fc.gunReady
fc.shotCount++
@@ -143,103 +170,94 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
elif (now - fc.pendingShotAt) > 0.35
fc.pendingShotConfirm = false
fc.prevLoadedAmmo = totalLoaded
return selected
[never_inline]
def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&;
aimBase : float3; var outAimPt, outWishDir : float3&) : float
var leadPt = aimBase
let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, slot, leadPt)
let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss))
outAimPt = leadPt
var arcDir = float3(0.0, 0.0, 0.0)
if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25
outWishDir = normalize(arcDir)
else
let d = max(1.0, length(leadPt - muzzlePos))
let tof = d / vEff
let dropComp = float3(0.0, 0.5 * 9.81 * tof * tof, 0.0)
outWishDir = normalize(leadPt + dropComp - muzzlePos)
return rawDist
[never_inline]
def private wto_sample_muzzle(unit : Unit const?; primaryIndex : int;
var outPos, outDir : float3&) : bool
if unit == null || unit.weap == null || primaryIndex < 0
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<Weapon const? const> const#)
if primaryIndex >= length(weapons)
return
assume weapon = weapons[primaryIndex]
if weapon == null
return
var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) > 0.25
outPos = gunTm[3]
outDir = normalize(gunTm[0])
sampled = true
let first = max(0, primaryIndex)
let end = primaryIndex < 0 ? length(weapons) : min(primaryIndex + 1, length(weapons))
for i in range(first, end)
assume weapon = weapons[i]
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
outPos = gunTm[3]
outDir = normalize(gunTm[0])
sampled = true
return
return sampled
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
// Sense from the live barrel even when the stock controller is moving the turret.
def public wto_fire_sample_sight(unit : Unit const?; var state : WtoFireState&)
var muzzlePos = float3(0.0, 0.0, 0.0)
var barrelDir = muzzlePos
let primary = state.sightPrimaryIndex
state.hasBarrelSight = wto_sample_muzzle(unit, primary, muzzlePos, barrelDir)
if !state.hasBarrelSight && primary >= 0
state.hasBarrelSight = wto_sample_muzzle(unit, -1, muzzlePos, barrelDir)
if state.hasBarrelSight
state.barrelSight = barrelDir
def private wto_fire_sample_primary(unit : Unit const?; var state : WtoFireState&; var muzzlePos, barrelDir : float3&) : bool
if state.sightPrimaryIndex < 0 || !wto_sample_muzzle(unit, state.sightPrimaryIndex, muzzlePos, barrelDir)
return false
state.hasBarrelSight = true
state.barrelSight = barrelDir
return true
// 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_fire_clear_aim_tracking(slot.fire)
wto_trig_set_target(INVALID_ENTITY_ID, slot.trigger)
var gm = as_gm(unit)
if gm != null
*gm |> set_check_visibility_target(true)
*gm |> set_ignore_stop_for_fire(true)
set_unit_attack_type(unit, "attack_target")
[never_inline]
def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; className : string;
now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&)
if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null
return
// SPAA vs aircraft only delegates to stock air-target fire control (never ground targets).
if slot.tactics.spaaYieldAir
wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot)
wto_clear_aim_tracking(slot.fire)
var gm = as_gm(unit)
if gm != null
*gm |> set_check_visibility_target(true)
*gm |> set_ignore_stop_for_fire(true)
set_unit_attack_type(unit, "attack_target")
wto_yield_air_fire(unit, slot)
return
set_unit_attack_type(unit, "dont_aim")
var wantSoftShell = false
if slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir
let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid)
if tgtIdx >= 0
wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35
let primaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire)
let wantSoft = wto_fire_wants_soft(world, slot)
slot.fire.sightPrimaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoft, slot.fire)
var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0)
var liveBarrelDir = unit.unitTm[0]
let _preSample = wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir)
var muzzleReady = wto_fire_sample_primary(unit, slot.fire, muzzlePos, liveBarrelDir)
let hFwd = unit.unitTm[0]
var wishWorldDir = hFwd
var aimPt = muzzlePos + hFwd * 50.0
var distToTgt = 9999.0
let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir &&
!(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED))
if engageValid
let baseAim = slot.perceive.visibleAimPt
distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir)
elif now < slot.perceive.watchUntil
wishWorldDir = normalize(slot.perceive.watchPos - muzzlePos)
elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
wishWorldDir = normalize((slot.perceive.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos)
elif now < slot.perceive.alertUntil
wishWorldDir = float3(cos(slot.perceive.alertYawRad), 0.0, sin(slot.perceive.alertYawRad))
var aimPt = muzzlePos
let engage = wto_fire_has_engagement(slot)
let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos))
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)
wto_drive_mounted_gun(unit, className, dt, wishYaw, wishPitch, slot)
let canEngage = engageValid && distToTgt <= WTO_AI_FC_MAX_RANGE_M && wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir)
wto_set_hull_aim(unit, canEngage, wishYaw, liveBarrelDir, slot)
if !canEngage
wto_clear_aim_tracking(slot.fire)
return
let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos))
wto_fire_gate_try_shoot(world, unit, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget)
if slot.fire.traverse.known || auxAimed
wto_apply_weapon_aim(unit, dt)
muzzleReady = wto_fire_sample_primary(unit, slot.fire, muzzlePos, liveBarrelDir)
let canEngage = engage && distToTgt <= WTO_AI_FC_MAX_RANGE_M && muzzleReady
wto_set_hull_aim(unit, className, canEngage, wishYaw, wishPitch, liveBarrelDir, slot)
if canEngage
wto_fire_gate_try_shoot(world, unit, className, now, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget)
else
wto_fire_hold(slot)
if engage
wto_fire_aux_update(world, unit, className, now, distXZ, slot, fireBudget)
@@ -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
+101 -131
View File
@@ -1,7 +1,4 @@
// Single fire-permission gate for every ground weapon (main cannon, launcher, SPAA self-defense).
// Every shot must pass visual confirmation, weapon readiness, distance-tier speed limits,
// 800 m continuous LOS window, aim settle, frame pre-fire budget, muzzle hard-ray, drag-integrated
// ballistic trajectory sweep, predicted friendly corridor, and multi-barrel group validation.
// Main weapon fire permission and burst control. All fired barrels pass a fresh safety check.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_gate_common shared
@@ -16,114 +13,46 @@ require %game.utils.utils_common
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_fire_speed_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_sight_common
require %appGame.wtoai.wto_ai_fire_checks_common
require %appGame.wtoai.wto_ai_weapon_profile_common
require %appGame.wtoai.wto_ai_trigger_common
[never_inline]
def private wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId;
army : int; p0, p1 : float3; tMid : float) : bool
let delta = p1 - p0
let segLen = length(delta)
if segLen < 0.2
return true
let dir = delta / segLen
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid
continue
let predPos = u.pos + u.vel * tMid + float3(0.0, 1.3, 0.0)
let along = clamp(dot(predPos - p0, dir), 0.0, segLen)
let clearR = WTO_AI_FC_FRIENDLY_CORRIDOR_M + u.halfWid
if length_sq(predPos - (p0 + dir * along)) < clearR * clearR
return false
return true
[never_inline]
def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&;
selfEid, targetEid : EntityId; army : int;
muzzlePos, liveDir, carrierVel, aimPt : float3;
speedMps, dragCx, massKg, caliberM : float;
var outBlock : int&) : int
let toAim = aimPt - muzzlePos
let targetDist = length(toAim)
if targetDist < 1.5
return WTO_DENY_OK
let toAimDir = toAim / targetDist
let area = 0.25 * WTO_PI * caliberM * caliberM
let dragK = 0.5 * 1.225 * dragCx * area / max(0.1, massKg)
var cur = muzzlePos
var vel = liveDir * max(80.0, speedMps) + carrierVel
var t = 0.0
var traveled = 0.0
for step in range(64)
let spd = length(vel)
if spd < 20.0
return WTO_DENY_AIM_ERR
let remain = max(0.5, targetDist - traveled)
let segWant = min(WTO_AI_FC_BALLISTIC_STEP_M, remain)
let dt = clamp(segWant / spd, 0.004, 0.14)
let accel = float3(0.0, -9.81, 0.0) - vel * (dragK * spd)
var next = cur + vel * dt + accel * (0.5 * dt * dt)
let nextProj = dot(next - muzzlePos, toAimDir)
let isLast = nextProj >= targetDist - 0.5
if isLast && nextProj > targetDist && length_sq(next - cur) > 0.01
let curProj = dot(cur - muzzlePos, toAimDir)
let frac = clamp((targetDist - curProj) / max(0.01, nextProj - curProj), 0.0, 1.0)
next = lerp(cur, next, frac)
let trimS = step == 0 ? 0.35 : 0.0
let trimE = isLast ? 0.65 : 0.0
let blk = wto_sight_hard_segment_blocked(world, selfEid, targetEid, cur, next, WTO_AI_FC_BALLISTIC_SWEEP_R_M, trimS, trimE)
if blk != WTO_BLOCK_NONE
outBlock = blk
return WTO_DENY_ARC_HARD
if !wto_gate_friendly_segment_clear(world, selfEid, army, cur, next, t + dt * 0.5)
return WTO_DENY_FRIENDLY
traveled += length(next - cur)
cur = next
vel = vel + accel * dt
t += dt
if isLast
let missTol = max(3.2, targetDist * 0.012)
if length_sq(cur - aimPt) > missTol * missTol
return WTO_DENY_AIM_ERR
return WTO_DENY_OK
return WTO_DENY_AIM_ERR
[never_inline]
def private wto_gate_check_barrel(world : WtoWorldSnap const&; unit : Unit const?;
slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3;
var outBlock : int&) : int
let straightBlk = wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzlePos, aimPt, 0.05, 0.35, 0.65)
if straightBlk != WTO_BLOCK_NONE
outBlock = straightBlk
return WTO_DENY_MUZZLE_HARD
return wto_gate_check_ballistic_arc(world, slot.eid, slot.perceive.targetEid, slot.army,
muzzlePos, liveDir, unit.vel, aimPt,
slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, outBlock)
[never_inline]
def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : Unit const?;
slot : WtoBotSlot const&; primaryMuzzle, primaryDir, aimPt : float3;
var outBlock : int&) : int
let primaryRes = wto_gate_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, outBlock)
if primaryRes != WTO_DENY_OK
return primaryRes
if unit == null || unit.weap == null
return WTO_DENY_OK
def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : Unit const?; className : string;
primaryMuzzle, primaryDir, aimPt : float3; checkMiss : bool;
var slot : WtoBotSlot&; var outBlock : int&) : int
var shell = WtoShellProfile()
shell.speedMps = slot.fire.activeSpeedMps
shell.dragCx = slot.fire.activeDragCx
shell.massKg = slot.fire.activeMassKg
shell.caliberM = slot.fire.activeCaliberM
let result = wto_fire_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, shell, checkMiss, outBlock)
if result != WTO_DENY_OK
return result
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if tIdx == slot.fire.turretNo || int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)
continue
let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex))
if weapon == null || weapon.isDummyGun
continue
let gun = as_gun(weapon)
if gun == null
return WTO_DENY_MULTI_GUN
if gun.isInoperable || !gun.isReadyToShoot
continue
if tIdx >= length(slot.fire.mounts)
return WTO_DENY_MULTI_GUN
assume cached = slot.fire.mounts[tIdx]
if !wto_mount_load_shell(unit, className, tIdx, gun, cached)
return WTO_DENY_MULTI_GUN
var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) <= 0.25
continue
let secRes = wto_gate_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, outBlock)
if secRes != WTO_DENY_OK
return secRes == WTO_DENY_FRIENDLY ? WTO_DENY_FRIENDLY : WTO_DENY_MULTI_GUN
return WTO_DENY_MULTI_GUN
let next = wto_fire_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, cached.shell, checkMiss, outBlock)
if next != WTO_DENY_OK
return next == WTO_DENY_FRIENDLY ? WTO_DENY_FRIENDLY : WTO_DENY_MULTI_GUN
return WTO_DENY_OK
[never_inline]
@@ -147,20 +76,22 @@ def private wto_gate_track_aim(now : float; offset : float3; target : EntityId;
fc.settleHoldSec = max(0.0, fc.settleHoldSec - age)
[never_inline]
def private wto_gate_log_deny(now, distXZ, measuredSpeed, speedLimit : float; reason, blk : int; var slot : WtoBotSlot&)
def private wto_gate_log_deny(now, distXZ : float; reason, blk : int; var slot : WtoBotSlot&)
assume fc = slot.fire
assume tr = slot.trigger
let changed = fc.lastDenyReason != reason || fc.lastDenyBlock != blk
fc.lastDenyReason = reason
fc.lastDenyBlock = blk
if WTO_AI_DIAG_TELEMETRY && reason >= WTO_DENY_SPEED && (changed || (now - fc.lastDenyLogAt) >= 4.0)
let logged = reason >= WTO_DENY_HIT_PROB && reason != WTO_DENY_BURST_PAUSE
if WTO_AI_DIAG_TELEMETRY && logged && (changed || (now - fc.lastDenyLogAt) >= 4.0)
fc.lastDenyLogAt = now
print("WTO_AI|DENY|eid={uint(slot.eid)}|reason={reason}|block={blk}|dist={distXZ}|spd={measuredSpeed}|limit={speedLimit}|err={fc.lastAimErrDeg}|drift={fc.aimDriftDegSec}\n")
print("WTO_AI|DENY|eid={uint(slot.eid)}|reason={reason}|block={blk}|dist={distXZ}|p={tr.hitProb}|pAligned={tr.hitProbAligned}|thr={tr.threshold}|wantV={tr.wantSpeedMps}|err={fc.lastAimErrDeg}|drift={fc.aimDriftDegSec}\n")
[never_inline]
def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ, measuredSpeed, speedLimit : float;
var slot : WtoBotSlot&)
def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ : float; var slot : WtoBotSlot&)
assume fc = slot.fire
unit_single_shot(unit, int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
let firstOfBurst = !slot.spec.isAutocannon || (now - fc.lastShotAt) > 0.5
fc.lastShotAt = now
fc.pendingShotConfirm = true
fc.pendingShotAt = now
@@ -168,51 +99,90 @@ def private wto_gate_request_primary_shot(var unit : Unit?; now, distXZ, measure
fc.lastDenyBlock = WTO_BLOCK_NONE
fc.shotErrSumDeg += fc.lastAimErrDeg
fc.maxShotErrDeg = max(fc.maxShotErrDeg, fc.lastAimErrDeg)
if !slot.spec.isAutocannonBelt
if !slot.spec.isAutocannon
fc.settleHoldSec = 0.0
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|SHOT|eid={uint(slot.eid)}|tgt={uint(slot.perceive.targetEid)}|dist={distXZ}|spd={measuredSpeed}|limit={speedLimit}|v0={fc.activeSpeedMps}|err={fc.lastAimErrDeg}\n")
slot.trigger.biasEpoch++
if WTO_AI_DIAG_TELEMETRY && firstOfBurst
print("WTO_AI|SHOT|eid={uint(slot.eid)}|tgt={uint(slot.perceive.targetEid)}|dist={distXZ}|spd={length(unit.vel)}|p={slot.trigger.hitProb}|thr={slot.trigger.threshold}|v0={fc.activeSpeedMps}|err={fc.lastAimErrDeg}\n")
// Main gun: one shot per permission, once the hit probability reaches the threshold and the
// barrel has settled on the target.
[never_inline]
def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?;
now, distXZ : float; muzzlePos, aimPt, liveDir, wishDir : float3;
var slot : WtoBotSlot&; var fireBudget : int&)
def private wto_gate_try_single(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, distXZ : float;
muzzlePos, aimPt, liveDir, wishDir : float3; probOk, withinTraverse : bool;
var slot : WtoBotSlot&; var fireBudget : int&)
assume fc = slot.fire
let aimErrDeg = acos(clamp(dot(liveDir, wishDir), -1.0, 1.0)) * WTO_RAD_TO_DEG
fc.lastAimErrDeg = aimErrDeg
let measuredSpeed = length(unit.vel)
let halting = slot.drive.routeBOwned && slot.tactics.state == WTO_STATE_SHORT_HALT
let speedLimit = halting ? WTO_AI_FC_STOP_SPEED_MAX_MPS : wto_fire_speed_limit_mps(distXZ, slot.spec.vMaxFwd)
let speedOk = measuredSpeed <= speedLimit
let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M
let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distXZ, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4)
let withinTraverse = fc.hullAimTarget == INVALID_ENTITY_ID
wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, withinTraverse && aimErrDeg <= allowErrDeg && speedOk, close, fc)
let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65
wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, withinTraverse && probOk, close, fc)
let reqHold = close ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC
var deny = WTO_DENY_OK
if !withinTraverse
deny = WTO_DENY_TRAVERSE
elif !fc.gunReady || (now - fc.lastShotAt) < minCadence
elif !fc.gunReady || (now - fc.lastShotAt) < WTO_AI_FC_MIN_SHOT_INTERVAL_SEC
deny = WTO_DENY_NOT_READY
elif !speedOk
deny = WTO_DENY_SPEED
elif distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2)
deny = WTO_DENY_LONG_WINDOW
elif aimErrDeg > allowErrDeg
deny = WTO_DENY_AIM_ERR
elif !probOk
// Only the barrel still swinging onto the target, or the shot itself not good enough.
deny = slot.trigger.hitProbAligned >= slot.trigger.threshold ? WTO_DENY_AIM_ERR : WTO_DENY_HIT_PROB
elif !fc.lastAligned || fc.settleHoldSec < reqHold
deny = WTO_DENY_SETTLE
elif fireBudget <= 0
deny = WTO_DENY_BUDGET
if deny != WTO_DENY_OK
wto_gate_log_deny(now, distXZ, measuredSpeed, speedLimit, deny, WTO_BLOCK_NONE, slot)
wto_gate_log_deny(now, distXZ, deny, WTO_BLOCK_NONE, slot)
return
fireBudget--
var blk = WTO_BLOCK_NONE
let gateRes = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, blk)
let gateRes = wto_gate_check_all_primary_guns(world, unit, className, muzzlePos, liveDir, aimPt, true, slot, blk)
if gateRes != WTO_DENY_OK
wto_gate_log_deny(now, distXZ, measuredSpeed, speedLimit, gateRes, blk, slot)
wto_gate_log_deny(now, distXZ, gateRes, blk, slot)
return
wto_gate_request_primary_shot(unit, now, distXZ, measuredSpeed, speedLimit, slot)
wto_gate_request_primary_shot(unit, now, distXZ, slot)
// An automatic gun uses burst timing and the looser aim window, with a fresh safety check per shot.
[never_inline]
def private wto_gate_try_burst(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, distXZ : float;
muzzlePos, aimPt, liveDir : float3; aimErrDeg : float; withinTraverse : bool;
var slot : WtoBotSlot&; var fireBudget : int&)
assume fc = slot.fire
assume tr = slot.trigger
var deny = WTO_DENY_OK
var started = false
if !withinTraverse
deny = WTO_DENY_TRAVERSE
elif !fc.gunReady
deny = WTO_DENY_NOT_READY
elif distXZ > WTO_AI_FC_LONG_RANGE_M && slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC
deny = WTO_DENY_LONG_WINDOW
else
deny = wto_trig_burst_gate(now, aimErrDeg <= tr.aimSlackDeg, tr.burstUntil, tr.burstPauseUntil, started)
var blk = WTO_BLOCK_NONE
if deny == WTO_DENY_OK
if fireBudget <= 0
deny = WTO_DENY_BUDGET
else
fireBudget--
deny = wto_gate_check_all_primary_guns(world, unit, className, muzzlePos, liveDir, aimPt, false, slot, blk)
if deny != WTO_DENY_OK
wto_gate_log_deny(now, distXZ, deny, blk, slot)
return
if started
tr.biasEpoch++
wto_gate_request_primary_shot(unit, now, distXZ, slot)
[never_inline]
def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?; className : string;
now, distXZ : float; muzzlePos, aimPt, liveDir, wishDir : float3;
var slot : WtoBotSlot&; var fireBudget : int&)
assume fc = slot.fire
let aimErrDeg = acos(clamp(dot(liveDir, wishDir), -1.0, 1.0)) * WTO_RAD_TO_DEG
fc.lastAimErrDeg = aimErrDeg
let turnDegSec = abs(slot.drive.omegaYawRad) * WTO_RAD_TO_DEG
let offset = wto_trig_aim_error(liveDir, wishDir)
let probOk = wto_trig_evaluate(world, now, unit.pos, length(unit.vel), turnDegSec, distXZ, offset, slot)
let withinTraverse = fc.mountCanAim && fc.hullAimTarget == INVALID_ENTITY_ID
if slot.spec.isAutocannon
wto_gate_try_burst(world, unit, className, now, distXZ, muzzlePos, aimPt, liveDir, aimErrDeg, withinTraverse, slot, fireBudget)
else
wto_gate_try_single(world, unit, className, now, distXZ, muzzlePos, aimPt, liveDir, wishDir, probOk, withinTraverse, slot, fireBudget)
@@ -1,19 +0,0 @@
// Shared speed limit for the movement command and the shot permission check.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_speed_common shared
require math
require %appGame.wtoai.wto_ai_config_common
def public wto_fire_speed_limit_mps(distXZ, maxFwdMps : float) : float
let stop = WTO_AI_FC_STOP_SPEED_MAX_MPS
if distXZ > WTO_AI_FC_MID_RANGE_M
return stop
let close = max(stop, min(maxFwdMps, WTO_AI_FC_CLOSE_MAX_MPS))
let mid = clamp(min(maxFwdMps * WTO_AI_FC_MID_SLOW_RATIO, WTO_AI_FC_MID_SLOW_MAX_MPS), stop, close)
if distXZ <= WTO_AI_FC_CLOSE_RANGE_M
let pointBlank = max(close, min(maxFwdMps, WTO_AI_FC_POINT_BLANK_MAX_MPS))
return lerp(pointBlank, close, distXZ / WTO_AI_FC_CLOSE_RANGE_M)
let frac = (distXZ - WTO_AI_FC_CLOSE_RANGE_M) / (WTO_AI_FC_MID_RANGE_M - WTO_AI_FC_CLOSE_RANGE_M)
return lerp(close, mid, frac)
+128
View File
@@ -0,0 +1,128 @@
// Pure-pursuit path following on a bot's corridor: where the bot is along it, the lookahead point
// it steers at, how fast it may go so it slows down before sharp corners and its destination
// instead of braking at the wall, and whether it drives forwards or backwards along it.
options indenting = 2
options no_global_heap = true
module wto_ai_follow_common shared
require math
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_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)
cmd.valid = true
cmd.mode = mode
cmd.targetPos = targetPos
cmd.desiredDir = desiredDir
cmd.speedMps = speedMps
cmd.frontClearM = frontClr
cmd.rearClearM = rearClr
// Drive mode for travelling along `dir` (decision layer design, 7.3). Forward: cruise, or pivot
// for a sharp turn. Reverse route following: the rear leads along `dir` and the front stays
// toward the threat; for a sharp turn the hull first pivots until its rear points along `dir`.
def public wto_follow_drive_mode(dir, hullFwd : float3; reverse : bool; var outDir : float3&) : int
let lead = reverse ? -hullFwd : hullFwd
let turnDeg = acos(clamp(dot(dir, lead), -1.0, 1.0)) * WTO_RAD_TO_DEG
outDir = dir
if turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG
if reverse
outDir = -dir
return WTO_DRIVE_PIVOT
return reverse ? WTO_DRIVE_REVERSE : WTO_DRIVE_CRUISE
// Moves the bot's place on its corridor forward and records its XZ distance from the corridor.
[never_inline]
def public wto_follow_track(myPos : float3; var rt : WtoRouteState&)
var seg = 0
var t = 0.0
rt.offTrackM = wto_poly_track(rt.corridor, rt.corridorLen, rt.segIdx, myPos, seg, t)
rt.segIdx = seg
rt.segT = t
// Lookahead distance: grows with speed, wheeled vehicles look further (wider turns).
[never_inline]
def public wto_follow_lookahead(spec : WtoVehicleSpec const&; speedMps : float) : float
let lookMin = spec.isTracked ? WTO_AI_PF_TRACKED_LOOK_MIN_M : WTO_AI_PF_WHEELED_LOOK_MIN_M
let lookMax = spec.isTracked ? WTO_AI_PF_TRACKED_LOOK_MAX_M : WTO_AI_PF_WHEELED_LOOK_MAX_M
return clamp(abs(speedMps) * WTO_AI_PF_LOOKAHEAD_SEC, lookMin, max(lookMin, lookMax))
[never_inline]
def public wto_follow_target(rt : WtoRouteState const&; lookM : float) : float3
return wto_poly_walk(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, lookM)
// A bend, or the end of the route, is within the distance the hull is willing to reverse.
[never_inline]
def public wto_follow_near_turn(rt : WtoRouteState const&; myPos : float3; limitM : float) : bool
let corner = clamp(rt.segIdx + 1, 1, rt.corridorLen - 1)
var dist = sqrt(wto_xz_dist_sq(myPos, rt.corridor[corner]))
let bendDot = cos(WTO_AI_PF_CORNER_ANGLE_DEG * WTO_DEG_TO_RAD)
for i in range(corner, rt.corridorLen - 1)
if dist > limitM
return false
let into = wto_xz_normalize(rt.corridor[i] - rt.corridor[i - 1], float3(1.0, 0.0, 0.0))
let out = wto_xz_normalize(rt.corridor[i + 1] - rt.corridor[i], into)
if dot(into, out) <= bendDot
return true
dist += sqrt(wto_xz_dist_sq(rt.corridor[i], rt.corridor[i + 1]))
return !rt.truncated && dist <= limitM
// Highest speed at `distToB` metres before corner b (a -> b -> c) that still allows turning it.
[never_inline]
def private wto_follow_corner_cap(a, b, c : float3; distToB, lookM, halfLen : float) : float
let inDir = wto_xz_normalize(b - a, float3(1.0, 0.0, 0.0))
let outDir = wto_xz_normalize(c - b, inDir)
let turnRad = acos(clamp(dot(inDir, outDir), -1.0, 1.0))
if turnRad * WTO_RAD_TO_DEG < WTO_AI_PF_CORNER_ANGLE_DEG
return 99.0
let legs = min(sqrt(wto_xz_dist_sq(a, b)), sqrt(wto_xz_dist_sq(b, c)))
let cut = max(1.0, min(lookM * 0.5, legs * 0.5))
let radius = max(2.5, cut / max(0.05, tan(turnRad * 0.5)))
let vCorner = sqrt(WTO_AI_PF_CORNER_LAT_ACCEL * radius)
return sqrt(vCorner * vCorner + 2.0 * WTO_AI_PF_BRAKE_DECEL * max(0.0, distToB - halfLen))
// Speed allowed by the next two corners and, when the corridor ends at the destination, by it.
[never_inline]
def public wto_follow_speed_cap(rt : WtoRouteState const&; spec : WtoVehicleSpec const&; lookM : float) : float
if rt.corridorLen < 2
return 99.0
let s = clamp(rt.segIdx, 0, rt.corridorLen - 2)
let here = lerp(rt.corridor[s], rt.corridor[s + 1], rt.segT)
var dist = sqrt(wto_xz_dist_sq(here, rt.corridor[s + 1]))
var cap = 99.0
for j in range(2)
let b = s + 1 + j
if b >= rt.corridorLen - 1
break
cap = min(cap, wto_follow_corner_cap(rt.corridor[b - 1], rt.corridor[b], rt.corridor[b + 1], dist, lookM, spec.halfLen))
dist += sqrt(wto_xz_dist_sq(rt.corridor[b], rt.corridor[b + 1]))
if rt.truncated || s < rt.corridorLen - 4
return cap
var remaining = sqrt(wto_xz_dist_sq(here, rt.corridor[s + 1]))
for k in range(s + 1, rt.corridorLen - 1)
remaining += sqrt(wto_xz_dist_sq(rt.corridor[k], rt.corridor[k + 1]))
let arrive = sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * max(0.0, remaining - WTO_AI_PF_ARRIVE_RADIUS_M))
return min(cap, max(WTO_AI_PF_ARRIVE_MIN_MPS, arrive))
// True when the corridor ends at the destination and the bot is within the arrival radius of it.
[never_inline]
def public wto_follow_arrived(rt : WtoRouteState const&; myPos : float3) : bool
if rt.corridorLen <= 0 || rt.truncated
return false
return wto_xz_dist_sq(myPos, rt.corridor[rt.corridorLen - 1]) <= wto_sq(WTO_AI_PF_ARRIVE_RADIUS_M)
+107
View File
@@ -0,0 +1,107 @@
// The chassis helps a fixed mount that runs out of yaw, or opens an elevation sector for a turret.
options indenting = 2
options no_global_heap = true
module wto_ai_hull_aim_common shared
require ecs
require math
require DagorMath
require DagorDataBlock
require Unit
require Weapon
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_traverse_common
def private wto_pitch_reaches(pitch : float2; wanted : float) : bool
return wto_valid_angle_range(pitch) && wanted >= pitch.x && wanted <= pitch.y
// Keep some space from a boundary shared by two pitch sectors.
def private wto_pitch_sector_yaw(preferred : float; arc : float2) : float
let margin = min(WTO_AI_FC_BASE_ALIGN_DEG, (arc.y - arc.x) * 0.5)
return clamp(wto_yaw_in_mount_coordinates(preferred, arc), arc.x + margin, arc.y - margin)
[never_inline]
def private wto_find_pitch_yaw(className : string; triggerNo, weaponIndex : int;
preferred, wantedPitch : float; var traverse : WtoGunTraverse&;
var outYaw : float&) : bool
let arc = traverse.yaw
let preferredYaw = wto_pitch_sector_yaw(preferred, arc)
let preferredPitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, preferredYaw, traverse)
if wto_pitch_reaches(preferredPitch, wantedPitch)
outYaw = preferredYaw
return true
var best = 360.0
wto_read_gunner_mount(className, triggerNo, weaponIndex) <| $(mount)
let pitchTable = mount |> datablock_get_block_by_name("limitsTable")
if pitchTable == null
return
for i in 0u..pitchTable.paramCount
if (*pitchTable |> datablock_getParamType(i)) != int(DataBlockParamType.TYPE_POINT4)
continue
let sector = *pitchTable |> datablock_getPoint4(int(i))
if !wto_pitch_reaches(float2(sector.z, sector.w), wantedPitch)
continue
let yaw = float2(max(arc.x, sector.x), min(arc.y, sector.y))
if !wto_valid_angle_range(yaw)
continue
let candidate = wto_pitch_sector_yaw(preferred, yaw)
let cost = abs(wto_wrap_deg(candidate - preferred))
if cost < best
best = cost
outYaw = candidate
return best < 360.0
// Prefer a solution that preserves frontal armor if the hull channel has a threat facing.
[never_inline]
def private wto_pitch_turn(unit : Unit const?; className : string; wantedYaw, wantedPitch : float;
var slot : WtoBotSlot&; var outYaw : float&) : bool
assume fc = slot.fire
if !fc.traverse.hasPitchTable || fc.turretNo < 0 || fc.turretNo >= length(unit.weap.turret)
return false
var preferred = wantedYaw
if slot.tactics.faceFromThreat
var armorYaw = 0.0
var armorPitch = 0.0
wto_world_to_hull_deg(slot.tactics.faceDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], armorYaw, armorPitch)
preferred = wto_wrap_deg(wantedYaw - armorYaw)
assume turret = unit.weap.turret[fc.turretNo]
return wto_find_pitch_yaw(className, int(turret.triggerNo), int(turret.weaponIndex), preferred, wantedPitch, fc.traverse, outYaw)
[never_inline]
def public wto_set_hull_aim(unit : Unit const?; className : string; active : bool;
wishYaw, wishPitch : float; liveBarrelDir : float3; var slot : WtoBotSlot&)
assume fc = slot.fire
var target = INVALID_ENTITY_ID
var pitchTurn = false
fc.mountCanAim = true
if active
var arc = fc.traverse.yaw
let hasLimits = fc.traverse.known
let hullMounted = !fc.servoInit || (hasLimits && arc.y - arc.x <= WTO_AI_TURRET_FIXED_MOUNT_SPAN_DEG)
if !fc.servoInit
var fixedYaw = 0.0
var barrelPitch = 0.0
wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, barrelPitch)
arc = float2(fixedYaw, fixedYaw)
let yaw = wto_yaw_in_mount_coordinates(wishYaw, arc)
let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0
let limited = hasLimits || !fc.servoInit
let yawBlocked = limited && !wto_full_gun_traverse(arc) && (yaw < arc.x - tolerance || yaw > arc.y + tolerance)
fc.mountCanAim = !yawBlocked && !fc.pitchAtLimit
var mountYaw = 0.5 * (arc.x + arc.y)
let fixedTurn = hullMounted && yawBlocked
if !yawBlocked && fc.pitchAtLimit
pitchTurn = wto_pitch_turn(unit, className, wishYaw, wishPitch, slot, mountYaw)
if fixedTurn || pitchTurn
target = slot.perceive.targetEid
let turn = wto_wrap_deg(wishYaw - mountYaw)
fc.hullAimDir = wto_hull_deg_to_world(turn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2])
if target != fc.hullAimTarget || pitchTurn != fc.hullAimForPitch
slot.nextNavAt = 0.0
if WTO_AI_DIAG_TELEMETRY && !!target
print("WTO_AI|HULL_AIM|eid={uint(slot.eid)}|target={uint(target)}|pitch={pitchTurn}\n")
fc.hullAimTarget = target
fc.hullAimForPitch = pitchTurn
@@ -0,0 +1,236 @@
// Builds the flank lanes of every team x capture zone and releases their 40% rally points.
// With the battle's navigation pack the paths are queued native searches (one step per call until
// built); without it (fallback) they come from the stock road mesh at once. Center: spawn to the
// zone. Flanks: spawn to a walkable relay beside the center path's middle, then on to the zone;
// a flank longer than flankMaxLengthRatio times the center path is dropped.
options indenting = 2
options no_global_heap = true
module wto_ai_lanes_build_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_order_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_polyline_common
require %appGame.wtoai.wto_ai_navquery_common
require %appGame.wtoai.wto_ai_navmesh_common
require %appGame.wtoai.wto_ai_stockpath_common
require %appGame.wtoai.wto_ai_lanes_common
[never_inline]
def private wto_lanes_slot(k, leg : int) : int
return WTO_NAVQ_LANE_SLOT0 + k * 5 + leg
// Center path known: length, rally at rallyProgressFrac and middle of the path.
[never_inline]
def private wto_lanes_set_center(k : int; pts : float3[96]; count : int; var lanes : WtoTeamLanes&)
lanes.centerLen[k] = wto_poly_length(pts, count)
lanes.centerMid[k] = wto_poly_sample(pts, count, 0.5)
lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = wto_poly_sample(pts, count, WTO_AI_CMD_RALLY_PROG_FRAC)
// No center path: straight-line stand-ins, no flanks.
[never_inline]
def private wto_lanes_set_straight(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&)
let spawnPt = world.teamSpawnCenter[army]
let capPt = world.caps[capIdx].center
lanes.centerLen[k] = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt)))
lanes.centerMid[k] = lerp(spawnPt, capPt, 0.5)
lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC)
// Relay of one side beside the center path's middle, on walkable ground; false when unusable.
[never_inline]
def private wto_lanes_relay(world : WtoWorldSnap const&; army, capIdx, k, side : int;
lanes : WtoTeamLanes const&; var relay : float3&) : bool
let spawnPt = world.teamSpawnCenter[army]
let capPt = world.caps[capIdx].center
let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0))
let lat = float3(-toCap.z, 0.0, toCap.x)
let swing = clamp(sqrt(wto_xz_dist_sq(spawnPt, capPt)) * 0.34, 80.0, 260.0)
let sign = side == 0 ? 1.0 : -1.0
relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0)
if lanes.navState == WTO_NAVMESH_LOADED
var onMesh = relay
if !wto_navq_nearest(WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED, relay, WTO_AI_NAVMESH_GOAL_SNAP_M, onMesh)
return false
relay = onMesh
if !wto_terrain_point_valid(army, relay)
return false
return sqrt(wto_xz_dist_sq(relay, lanes.centerMid[k])) >= WTO_AI_CMD_FLANK_MIN_SEP_M
// A flank whose two legs are known: keep it when it is not too long.
[never_inline]
def private wto_lanes_accept_flank(k, side : int; leg1 : float3[96]; count1 : int; len2 : float;
relay : float3; var lanes : WtoTeamLanes&)
let fKey = k * 2 + side
lanes.flankValid[fKey] = false
if (wto_poly_length(leg1, count1) + len2) > lanes.centerLen[k] * WTO_AI_CMD_FLANK_MAX_RATIO
return
lanes.flankValid[fKey] = true
lanes.flankRelay[fKey] = relay
lanes.rallyPos[k * 3 + side + 1] = wto_poly_sample(leg1, count1, 0.8)
// Fallback battles: every path from the stock road mesh at once.
[never_inline]
def private wto_lanes_build_stock(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&)
lanes.phase[k] = WTO_LANES_BUILT
var pts : float3[96]
var count = 0
if !wto_stock_path(world.teamSpawnCenter[army], world.caps[capIdx].center, pts, count)
wto_lanes_set_straight(world, army, capIdx, k, lanes)
return
wto_lanes_set_center(k, pts, count, lanes)
var leg2 : float3[96]
for side in range(2)
var relay = float3(0.0, 0.0, 0.0)
lanes.flankValid[k * 2 + side] = false
if !wto_lanes_relay(world, army, capIdx, k, side, lanes, relay)
continue
var count2 = 0
if !wto_stock_path(world.teamSpawnCenter[army], relay, pts, count) || !wto_stock_path(relay, world.caps[capIdx].center, leg2, count2)
continue
wto_lanes_accept_flank(k, side, pts, count, wto_poly_length(leg2, count2), pts[count - 1], lanes)
// Queues both legs of each usable flank (slots k*5+1..4).
[never_inline]
def private wto_lanes_request_legs(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&)
for side in range(2)
var relay = float3(0.0, 0.0, 0.0)
lanes.flankValid[k * 2 + side] = false
lanes.ticket[k * 5 + 1 + side * 2] = 0
lanes.ticket[k * 5 + 2 + side * 2] = 0
if !wto_lanes_relay(world, army, capIdx, k, side, lanes, relay)
continue
lanes.flankRelay[k * 2 + side] = relay
lanes.ticket[k * 5 + 1 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 1 + side * 2), WTO_NAVMESH_TIER_STANDARD,
WTO_NAVMESH_FILTER_TRACKED, 0, world.teamSpawnCenter[army], relay)
lanes.ticket[k * 5 + 2 + side * 2] = wto_navq_path_request(wto_lanes_slot(k, 2 + side * 2), WTO_NAVMESH_TIER_STANDARD,
WTO_NAVMESH_FILTER_TRACKED, 0, relay, world.caps[capIdx].center)
lanes.phase[k] = WTO_LANES_LEGS
// Center path queued: take it once found and queue the flank legs.
[never_inline]
def private wto_lanes_mesh_center(world : WtoWorldSnap const&; army, capIdx, k : int; var lanes : WtoTeamLanes&)
var pts : float3[96]
var count = 0
var lenM = 0.0
var truncated = false
let status = wto_navq_path_result(wto_lanes_slot(k, 0), lanes.ticket[k * 5], pts, count, lenM, truncated)
if status == WTO_PATH_PENDING
return
if (status != WTO_PATH_FULL && status != WTO_PATH_PARTIAL) || count < 2
wto_lanes_set_straight(world, army, capIdx, k, lanes)
lanes.phase[k] = WTO_LANES_BUILT
return
wto_lanes_set_center(k, pts, count, lanes)
wto_lanes_request_legs(world, army, capIdx, k, lanes)
// Flank legs queued: once none is pending, keep the flanks whose legs both arrived.
[never_inline]
def private wto_lanes_mesh_legs(k : int; var lanes : WtoTeamLanes&)
var leg1 : float3[96]
var leg2 : float3[96]
for side in range(2)
var count1 = 0
var count2 = 0
var len1 = 0.0
var len2 = 0.0
var trunc1 = false
var trunc2 = false
let t1 = lanes.ticket[k * 5 + 1 + side * 2]
let t2 = lanes.ticket[k * 5 + 2 + side * 2]
if t1 == 0 || t2 == 0
continue
let s1 = wto_navq_path_result(wto_lanes_slot(k, 1 + side * 2), t1, leg1, count1, len1, trunc1)
let s2 = wto_navq_path_result(wto_lanes_slot(k, 2 + side * 2), t2, leg2, count2, len2, trunc2)
if s1 == WTO_PATH_PENDING || s2 == WTO_PATH_PENDING
return
lanes.ticket[k * 5 + 1 + side * 2] = 0
lanes.ticket[k * 5 + 2 + side * 2] = 0
if s1 == WTO_PATH_FULL && s2 == WTO_PATH_FULL && count1 >= 2
wto_lanes_accept_flank(k, side, leg1, count1, len2, lanes.flankRelay[k * 2 + side], lanes)
lanes.phase[k] = WTO_LANES_BUILT
// Builds (or advances the building of) the lanes of one team x capture zone.
[never_inline]
def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int; var lanes : WtoTeamLanes&)
let k = wto_lanes_cap_key(army, capIdx)
if lanes.phase[k] == WTO_LANES_BUILT || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army]
return
if lanes.navState != WTO_NAVMESH_LOADED
if lanes.navState == WTO_NAVMESH_FALLBACK || lanes.navState == WTO_NAVMESH_OFF
wto_lanes_build_stock(world, army, capIdx, k, lanes)
return
if lanes.phase[k] == WTO_LANES_IDLE
lanes.ticket[k * 5] = wto_navq_path_request(wto_lanes_slot(k, 0), WTO_NAVMESH_TIER_STANDARD, WTO_NAVMESH_FILTER_TRACKED,
0, world.teamSpawnCenter[army], world.caps[capIdx].center)
lanes.phase[k] = WTO_LANES_CENTER
elif lanes.phase[k] == WTO_LANES_CENTER
wto_lanes_mesh_center(world, army, capIdx, k, lanes)
else
wto_lanes_mesh_legs(k, lanes)
[never_inline]
def private wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float;
var lanes : WtoTeamLanes&; bots : WtoBotSlot[64])
let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M)
for c in range(world.capCount)
wto_lanes_ensure_cap(world, army, c, lanes)
if lanes.phase[wto_lanes_cap_key(army, c)] != WTO_LANES_BUILT
continue
for lane in range(3)
let sk = wto_lanes_sub_key(army, c, lane)
if lanes.rallyReleased[sk]
continue
let rPos = lanes.rallyPos[sk]
if length_sq(rPos) < 1.0
lanes.rallyReleased[sk] = true
continue
let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center)
var assigned = 0
var arrived = 0
for i in range(WTO_MAX_BOTS)
assume b = bots[i]
if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role)
continue
let uIdx = wto_world_find_unit(world, b.eid)
if uIdx < 0
continue
assigned++
let pos = world.units[uIdx].pos
if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq
arrived++
if assigned <= 1
lanes.rallyReleased[sk] = true
continue
if arrived > 0 && lanes.rallyStartAt[sk] < 0.0
lanes.rallyStartAt[sk] = now
let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC
let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC
if enough || timedOut
lanes.rallyReleased[sk] = true
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n")
// Once a second: advance lane building, release rallies and send released bots on their way.
[never_inline]
def public wto_lanes_tick_rallies(world : WtoWorldSnap const&; now : float; var lanes : WtoTeamLanes&;
var bots : WtoBotSlot[64]&)
wto_lanes_update_rallies(world, 1, now, lanes, bots)
wto_lanes_update_rallies(world, 2, now, lanes, bots)
for i in range(WTO_MAX_BOTS)
assume b = bots[i]
if !b.used || !b.order.valid || !b.order.rallyHold || b.order.capIndex < 0
continue
if !lanes.rallyReleased[wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId)]
continue
b.order.rallyHold = false
if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0
let fKey = wto_lanes_cap_key(b.army, b.order.capIndex) * 2 + b.order.laneId - 1
b.order.routeRelayValid = lanes.flankValid[fKey]
b.order.routeRelayPos = lanes.flankRelay[fKey]
else
b.order.routeRelayValid = false
+14 -131
View File
@@ -1,26 +1,32 @@
// Team-level navmesh flank lanes (center / left / right), 40% rally staging & launch state,
// cap recall timers, and enemy air threat tracking.
// Team-level flank lanes (center / left / right) and their 40% rally staging state, cap recall
// timers, and enemy air threat tracking. Lanes are built in wto_ai_lanes_build_common.
options indenting = 2
options no_global_heap = true
module wto_ai_lanes_common shared
require ecs
require math
require pathfinder
require %appGame.wtoai.wto_ai_config_common
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_terrain_common
require %appGame.wtoai.wto_ai_world_common
let public WTO_LANE_CENTER = 0
let public WTO_LANE_LEFT = 1
let public WTO_LANE_RIGHT = 2
// Lane building per team x capture zone: not started, center path queued, flank legs queued, done.
let public WTO_LANES_IDLE = 0
let public WTO_LANES_CENTER = 1
let public WTO_LANES_LEGS = 2
let public WTO_LANES_BUILT = 3
[safe_when_uninitialized]
struct public WtoTeamLanes
built : bool[16]
navState : int = 0
phase : int[16]
ticket : int[80]
centerLen : float[16]
centerMid : float3[16]
flankValid : bool[32]
@@ -44,7 +50,7 @@ def public wto_lanes_sub_key(army, capIdx, laneId : int) : int
[never_inline]
def public wto_lanes_reset(var lanes : WtoTeamLanes&)
for i in range(16)
lanes.built[i] = false
lanes.phase[i] = WTO_LANES_IDLE
lanes.centerLen[i] = 0.0
lanes.centerMid[i] = float3(0.0, 0.0, 0.0)
lanes.capSafeSince[i] = -100.0
@@ -56,6 +62,8 @@ def public wto_lanes_reset(var lanes : WtoTeamLanes&)
lanes.rallyPos[i] = float3(0.0, 0.0, 0.0)
lanes.rallyStartAt[i] = -100.0
lanes.rallyReleased[i] = false
for i in range(80)
lanes.ticket[i] = 0
for a in range(3)
lanes.enemyAirActive[a] = false
lanes.enemyAirSeenAt[a] = -100.0
@@ -66,92 +74,6 @@ def public wto_lanes_reset_rallies(var lanes : WtoTeamLanes&)
lanes.rallyStartAt[i] = -100.0
lanes.rallyReleased[i] = false
[never_inline]
def private wto_nav_project_pt(navIdx : int; var pt : float3&) : bool
if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0))
return true
return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(150.0, 120.0, 150.0))
[never_inline]
def private wto_measure_nav_path(navIdx : int; fromPt, toPt : float3; sampleFrac : float;
var outLen : float&; var outSample : float3&) : bool
var sPt = fromPt
var gPt = toPt
if !wto_nav_project_pt(navIdx, sPt) || !wto_nav_project_pt(navIdx, gPt)
return false
var ok = false
var totalLen = 0.0
var sample = lerp(sPt, gPt, sampleFrac)
find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array<float3>#)
let n = length(path)
if n < 2
return
ok = true
for i in range(1, n)
totalLen += length(path[i] - path[i - 1])
let targetD = totalLen * clamp(sampleFrac, 0.05, 0.95)
var acc = 0.0
sample = path[n - 1]
for i in range(1, n)
let seg = length(path[i] - path[i - 1])
if acc + seg >= targetD && seg > 0.01
sample = lerp(path[i - 1], path[i], (targetD - acc) / seg)
break
acc += seg
outLen = totalLen
outSample = sample
return ok && totalLen > 1.0
[never_inline]
def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int;
var lanes : WtoTeamLanes&)
let k = wto_lanes_cap_key(army, capIdx)
if lanes.built[k] || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army]
return
let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1)
if navIdx < 0
return
lanes.built[k] = true
let spawnPt = world.teamSpawnCenter[army]
let capPt = world.caps[capIdx].center
var cLen = 0.0
var cRally = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC)
if !wto_measure_nav_path(navIdx, spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC, cLen, cRally)
cLen = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt)))
var cMid = lerp(spawnPt, capPt, 0.5)
var dummyLen = 0.0
let _midOk = wto_measure_nav_path(navIdx, spawnPt, capPt, 0.5, dummyLen, cMid)
lanes.centerLen[k] = cLen
lanes.centerMid[k] = cMid
lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = cRally
let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0))
let lat = float3(-toCap.z, 0.0, toCap.x)
let straightD = sqrt(wto_xz_dist_sq(spawnPt, capPt))
let swing = clamp(straightD * 0.34, 80.0, 260.0)
for side in range(2)
let sign = side == 0 ? 1.0 : -1.0
var relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0)
let fKey = k * 2 + side
lanes.flankValid[fKey] = false
if !wto_nav_project_pt(navIdx, relay) || !wto_terrain_point_valid(army, relay)
continue
if sqrt(wto_xz_dist_sq(relay, cMid)) < WTO_AI_CMD_FLANK_MIN_SEP_M
continue
var len1 = 0.0
var len2 = 0.0
var rPt = lerp(spawnPt, relay, 0.8)
var dummy = relay
if !wto_measure_nav_path(navIdx, spawnPt, relay, 0.8, len1, rPt)
continue
if !wto_measure_nav_path(navIdx, relay, capPt, 0.5, len2, dummy)
continue
if (len1 + len2) > cLen * WTO_AI_CMD_FLANK_MAX_RATIO
continue
lanes.flankValid[fKey] = true
lanes.flankRelay[fKey] = relay
lanes.rallyPos[k * 3 + side + 1] = rPt
[never_inline]
def public wto_lanes_update_team_intel(world : WtoWorldSnap const&; now : float;
var lanes : WtoTeamLanes&)
@@ -193,42 +115,3 @@ def public wto_lanes_update_recall(world : WtoWorldSnap const&; army : int; now
elif lanes.recallActive[k] && (now - lanes.capSafeSince[k]) >= WTO_AI_CMD_RECALL_SAFE_SEC
lanes.recallActive[k] = false
[never_inline]
def public wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float;
var lanes : WtoTeamLanes&; var bots : WtoBotSlot[64]&)
let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M)
for c in range(world.capCount)
wto_lanes_ensure_cap(world, army, c, lanes)
for lane in range(3)
let sk = wto_lanes_sub_key(army, c, lane)
if lanes.rallyReleased[sk]
continue
let rPos = lanes.rallyPos[sk]
if length_sq(rPos) < 1.0
lanes.rallyReleased[sk] = true
continue
let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center)
var assigned = 0
var arrived = 0
for i in range(WTO_MAX_BOTS)
assume b = bots[i]
if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role)
continue
let uIdx = wto_world_find_unit(world, b.eid)
if uIdx < 0
continue
assigned++
let pos = world.units[uIdx].pos
if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq
arrived++
if assigned <= 1
lanes.rallyReleased[sk] = true
continue
if arrived > 0 && lanes.rallyStartAt[sk] < 0.0
lanes.rallyStartAt[sk] = now
let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC
let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC
if enough || timedOut
lanes.rallyReleased[sk] = true
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n")
+177 -223
View File
@@ -1,8 +1,10 @@
// Bidirectional non-holonomic local planner:
// - Directed 7-arc reverse trajectory planner for ridge withdrawals, tactical peeks, cliff escapes,
// and jam unsticking (enabling sustained 30-50m reverse transfers);
// - Stationary combat hull discipline (zero hull-pivot whip on turreted tanks during ENGAGE_HALT);
// - Forward 9-arc DWA rollout with cliff rejection, TTC ally overtaking, and jam/crowd penalties.
// Navigation layer of one bot per nav tick: turns the tactics goal into a drive command.
// Stationary states hold, or pivot in place toward the facing direction of the hull channel;
// tactical withdrawals and unstick manoeuvres back up along checked ground; a bot keeping its front
// toward a threat drives its corridor backwards; otherwise the bot follows its corridor (route) with a
// lookahead point it can reach in a straight line (follow), passes or follows vehicles and wrecks
// (traffic), slows for corners, narrow passages and fresh obstacles (avoid), backs off at once
// when pressed against a vehicle, and escalates when it stops making progress (unstick).
options indenting = 2
options no_global_heap = true
module wto_ai_nav_common shared
@@ -12,252 +14,204 @@ require math
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_drive_common
require %appGame.wtoai.wto_ai_nav_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_navquery_common
require %appGame.wtoai.wto_ai_navmesh_common
require %appGame.wtoai.wto_ai_route_common
require %appGame.wtoai.wto_ai_follow_common
require %appGame.wtoai.wto_ai_facing_common
require %appGame.wtoai.wto_ai_avoid_common
require %appGame.wtoai.wto_ai_traffic_common
require %appGame.wtoai.wto_ai_traffic_geometry_common
require %appGame.wtoai.wto_ai_unstick_common
[never_inline]
def private wto_wreck_or_ally_clearance(world : WtoWorldSnap const&; selfEid : EntityId;
pt : float3; tSec, selfRad : float) : float
var pen = 0.0
for w in range(world.wreckCount)
let r = selfRad + max(world.wrecks[w].halfLen, world.wrecks[w].halfWid) + WTO_AI_TERRAIN_MARGIN_M
let dSq = wto_xz_dist_sq(pt, world.wrecks[w].pos)
if dSq < r * r
return 1.0e6
elif dSq < wto_sq(r + 3.5)
pen += 18.0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.eid == selfEid
continue
let predPos = u.pos + u.vel * min(tSec, 1.6)
let r = selfRad + max(u.halfLen, u.halfWid) + WTO_AI_TERRAIN_MARGIN_M
let dSq = wto_xz_dist_sq(pt, predPos)
if dSq < r * r
return 1.0e6
elif dSq < wto_sq(r + 5.0)
pen += 22.0
return pen
def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&)
slot.nav.stuckCheckAt = -100.0
slot.nav.stuckOrigin = myPos
wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
slot.nav.bumperBlockedSince = -100.0
// Evaluate 7 curved rear trajectories (`16m` behind chassis) toward `reverseGoal`.
// Standing for a shot or in cover: turn toward the facing direction (decision layer design, 7.3)
// only when the hull is more than limitDeg off it, else hold still.
[never_inline]
def private wto_eval_reverse_arcs(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, reverseGoal : float3;
var slot : WtoBotSlot&; var outRearDir : float3&) : bool
let rearBase = -wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
let baseYaw = atan2(rearBase.z, rearBase.x)
let wishDir = wto_xz_normalize(reverseGoal - myPos, rearBase)
let selfRad = max(slot.spec.halfWid, 1.65)
var bestScore = -1.0e9
var found = false
outRearDir = rearBase
for a in range(7)
let steerFrac = float(a - 3) / 3.0
let arcCurv = steerFrac * 0.042
var cur = myPos
var blocked = false
var arcPen = abs(steerFrac) * 2.5
for s in range(1, 5)
let dist = float(s) * 3.8
let yaw = baseYaw + arcCurv * dist
let stepDir = float3(cos(yaw), 0.0, sin(yaw))
let nx = cur.x + stepDir.x * 3.8
let nz = cur.z + stepDir.z * 3.8
var gy = cur.y
if !wto_terrain_drivable_y(cur, nx, nz, gy)
blocked = true
break
if wto_terrain_hard_ray(cur + float3(0.0, 1.25, 0.0), stepDir, 4.2) < 3.7
blocked = true
break
let nxt = float3(nx, gy, nz)
let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(1.8, slot.spec.vMaxRev), selfRad)
if dynPen >= 1.0e5
blocked = true
break
arcPen += dynPen * 0.25 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.2
cur = nxt
if blocked
continue
let firstYaw = baseYaw + arcCurv * 5.5
let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw))
if wto_terrain_has_cliff_ahead(myPos, candDir, 15.0)
continue
let score = dot(candDir, wishDir) * 35.0 - arcPen - wto_world_jam_penalty(world, cur, now) * 0.4
if score > bestScore
bestScore = score
outRearDir = candDir
found = true
return found
def private wto_nav_stand(myPos, hullFwd : float3; var slot : WtoBotSlot&)
assume tac = slot.tactics
if tac.state == WTO_STATE_SHORT_HALT && !tac.faceForGun
wto_nav_halt(myPos, hullFwd, slot)
return
let limit = tac.faceForGun ? WTO_AI_FC_BASE_ALIGN_DEG : WTO_AI_BHV_FACE_TOL_DEG
let errorDeg = acos(clamp(dot(tac.faceDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
if tac.faceActive && errorDeg > limit && wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) != WTO_DRIVE_HALT
slot.nav.stuckCheckAt = -100.0
wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos, tac.faceDir, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
return
wto_nav_halt(myPos, hullFwd, slot)
// Evaluate 9 curved forward trajectories (`22m` ahead) with hard cliff rejection and traffic cost.
// Ridge withdrawal and backing into cover: reverse straight to the goal when the way is free.
[never_inline]
def private wto_eval_forward_arcs(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, wishDir : float3; speedCmd : float;
var slot : WtoBotSlot&; var outFwdDir : float3&) : bool
let fwdBase = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
let baseYaw = atan2(fwdBase.z, fwdBase.x)
let selfRad = max(slot.spec.halfWid, 1.65)
var bestScore = -1.0e9
var found = false
outFwdDir = wishDir
for a in range(9)
let steerFrac = float(a - 4) / 4.0
let arcCurv = steerFrac * 0.038
let firstYaw = baseYaw + arcCurv * 6.5
let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw))
if wto_terrain_has_cliff_ahead(myPos, candDir, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M)
continue
var cur = myPos
var blocked = false
var arcPen = abs(steerFrac) * 2.2
for s in range(1, 6)
let dist = float(s) * 4.2
let yaw = baseYaw + arcCurv * dist
let stepDir = float3(cos(yaw), 0.0, sin(yaw))
let nx = cur.x + stepDir.x * 4.2
let nz = cur.z + stepDir.z * 4.2
var gy = cur.y
if !wto_terrain_drivable_y(cur, nx, nz, gy)
blocked = true
break
if wto_terrain_hard_ray(cur + float3(0.0, 1.3, 0.0), stepDir, 4.6) < 4.1
blocked = true
break
let nxt = float3(nx, gy, nz)
let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(2.5, speedCmd), selfRad)
if dynPen >= 1.0e5
blocked = true
break
arcPen += dynPen * 0.3 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.35
cur = nxt
if blocked
continue
let align = dot(candDir, wishDir) * 40.0 + dot(candDir, slot.nav.steerDir) * 4.5
let score = align - arcPen - wto_world_jam_penalty(world, cur, now)
if score > bestScore
bestScore = score
outFwdDir = candDir
found = true
return found
[never_inline]
def private wto_set_drive_cmd(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3;
speedMps, frontClr, rearClr : float)
cmd.valid = true
cmd.mode = mode
cmd.targetPos = targetPos
cmd.desiredDir = desiredDir
cmd.speedMps = speedMps
cmd.frontClearM = frontClr
cmd.rearClearM = rearClr
[never_inline]
def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
let state = slot.tactics.state
if state != WTO_STATE_MARCH && state != WTO_STATE_RUN_AND_GUN && state != WTO_STATE_PREAIM && state != WTO_STATE_SHORT_HALT
def private wto_nav_tactical_reverse(navState : int; myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
let st = slot.tactics.state
if st != WTO_STATE_RIDGE_WITHDRAW && !(st == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse)
return false
if !slot.fire.hullAimTarget || slot.fire.hullAimTarget != slot.perceive.targetEid || slot.tactics.immobilized
let goal = slot.tactics.moveGoal
let dist = sqrt(wto_xz_dist_sq(myPos, goal))
if dist < 2.0 || slot.nav.rearClearM < 2.4
return false
if wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) == WTO_DRIVE_HALT
return false
let direction = wto_xz_normalize(slot.fire.hullAimDir, hullFwd)
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos, direction, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
if navState == WTO_NAVMESH_LOADED && slot.route.tier >= 0
var frac = 0.0
if wto_navq_raycast(slot.route.tier, slot.route.filter, myPos, goal, frac) == 0 && frac * dist < 3.0
return false
let dir = wto_xz_normalize(goal - myPos, -hullFwd)
slot.nav.steerDir = dir
slot.nav.stuckCheckAt = -100.0
let speed = min(slot.spec.vMaxRev, slot.nav.rearTrafficSpeedCap)
wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_REVERSE, goal, dir, speed, slot.nav.frontClearM, slot.nav.rearClearM)
return true
// Surface, flags and room to the mesh edge under the bot (battles with a pack only).
[never_inline]
def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float;
myPos, wishDir : float3; var slot : WtoBotSlot&)
def private wto_nav_probe_mesh(navState : int; myPos : float3; var slot : WtoBotSlot&)
assume nav = slot.nav
let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= nav.reverseUntil
if !movingIntent
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
nav.onMesh = false
nav.wallDistM = 99.0
nav.surfaceArea = 0
nav.chokepoint = false
if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0
return
if nav.stuckCheckAt < -50.0
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
var probe = WtoNavProbeOut()
if !wto_navq_probe(slot.route.tier, slot.route.filter, myPos, WTO_AI_PF_NARROW_WALL_M + 1.0, probe) || !probe.onMesh
return
if now < nav.stuckCheckAt
nav.onMesh = true
nav.wallDistM = probe.wallDistM
nav.surfaceArea = probe.area
nav.chokepoint = (probe.flags & WTO_NAVQ_FLAG_CHOKEPOINT) != 0
// Lookahead point the bot can drive to in a straight line: around a corner the full lookahead
// would cut through the building the path turns around, so it is pulled back along the path
// until the mesh allows the straight line, at worst to the next path corner.
[never_inline]
def private wto_nav_visible_target(navState : int; myPos : float3; lookM : float; slot : WtoBotSlot const&) : float3
assume rt = slot.route
var look = lookM
var target = wto_follow_target(rt, look)
if navState != WTO_NAVMESH_LOADED || rt.tier < 0 || rt.source != WTO_ROUTE_SRC_MESH
return target
for _try in range(3)
var frac = 0.0
if wto_navq_raycast(rt.tier, rt.filter, myPos, target, frac) != 0
return target
look *= 0.5
target = wto_follow_target(rt, look)
return rt.corridor[min(rt.segIdx + 1, rt.corridorLen - 1)]
// A fresh obstacle in front for bumperBlockSec: mark it for path searches and plan again.
[never_inline]
def private wto_nav_bumper_block(navState : int; now : float; myPos, dir : float3; clear : float; var slot : WtoBotSlot&)
assume nav = slot.nav
if clear >= WTO_AI_PF_BUMPER_STOP_M + 0.5
nav.bumperBlockedSince = -100.0
return
let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin))
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
if moved >= WTO_AI_NAV_STUCK_MIN_MOVE_M
if nav.bumperBlockedSince < -50.0
nav.bumperBlockedSince = now
return
wto_world_record_jam(world, myPos + wishDir * 6.0, now)
wto_route_request_detour(world, now, myPos, wishDir, slot)
let backIdx = clamp(slot.route.corridorIdx - 2, 0, max(0, slot.route.corridorLen - 1))
nav.reverseAnchor = slot.route.corridorLen > 0 ? slot.route.corridor[backIdx] : (myPos - wishDir * 22.0)
nav.reverseUntil = now + max(WTO_AI_NAV_UNSTICK_REV_SEC, 3.6)
nav.reverseCount++
if now - nav.bumperBlockedSince < WTO_AI_PF_BUMPER_BLOCK_SEC
return
nav.bumperBlockedSince = -100.0
let spot = myPos + dir * (slot.spec.halfLen + clear + 1.0)
if navState == WTO_NAVMESH_LOADED
wto_navq_add_dynamic(spot, WTO_AI_PF_RUBBLE_RADIUS_M, WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_RUBBLE_TTL_SEC)
slot.route.replanRequested = true
print("WTO_AI|NAV_BLOCKED|eid={uint(slot.eid)}|pos={myPos}|spot={spot}\n")
[never_inline]
def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float;
myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
let stMode = slot.tactics.state
let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || (stMode == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse)
if !wantTacRev && now >= slot.nav.reverseUntil
return false
let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor
var rearDir = -hullFwd
if slot.nav.rearClearM > 2.4 && wto_eval_reverse_arcs(world, now, myPos, hullFwd, revGoal, slot, rearDir)
slot.nav.steerDir = rearDir
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, myPos + rearDir * 18.0, rearDir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM)
return true
slot.nav.reverseUntil = -100.0
return false
def private wto_nav_speed(navState : int; now : float; myPos, dir : float3; lookM : float; narrow : bool;
var slot : WtoBotSlot&) : float
var speed = min(slot.tactics.desiredSpeedMps, wto_follow_speed_cap(slot.route, slot.spec, lookM))
if narrow
speed = min(speed, WTO_AI_PF_NARROW_SPEED_MPS)
speed = min(speed, slot.nav.avoidSpeedCap)
let clear = wto_avoid_bumper(myPos, dir, slot.spec)
slot.nav.bumperClearM = clear
if clear < WTO_AI_PF_BUMPER_RAY_M
speed = min(speed, max(0.0, clear - WTO_AI_PF_BUMPER_STOP_M) * 1.2)
wto_nav_bumper_block(navState, now, myPos, dir, clear, slot)
return speed
[never_inline]
def public wto_nav_update(var world : WtoWorldSnap&; now : float;
def private wto_nav_follow(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd : float3;
var slot : WtoBotSlot&)
assume rt = slot.route
if rt.corridorLen == 0 || wto_follow_arrived(rt, myPos)
wto_nav_halt(myPos, hullFwd, slot)
return
wto_follow_track(myPos, rt)
wto_face_reverse_update(now, myPos, hullFwd, slot)
let reverse = slot.tactics.reverseTravel
let lead = reverse ? -hullFwd : hullFwd
let speedNow = abs(slot.drive.lastVFwd)
let lookM = wto_follow_lookahead(slot.spec, speedNow)
let pathTarget = wto_nav_visible_target(navState, myPos, lookM, slot)
let pathDir = wto_xz_normalize(pathTarget - myPos, lead)
let narrow = slot.nav.wallDistM < WTO_AI_PF_NARROW_WALL_M || slot.nav.chokepoint
wto_traffic_update(world, navState, now, myPos, pathDir, speedNow, narrow, slot)
if wto_traffic_in_contact(now, slot.nav)
wto_unstick_contact(world, navState, now, myPos, hullFwd, slot)
if !wto_unstick_reversing(now, myPos, slot)
wto_nav_halt(myPos, hullFwd, slot)
return
let target = slot.nav.avoidActive ? slot.nav.avoidTarget : pathTarget
let dir = wto_xz_normalize(target - myPos, lead)
var speed = wto_nav_speed(navState, now, myPos, dir, lookM, narrow, slot)
let trafficLimit = reverse ? slot.nav.rearTrafficSpeedCap : slot.nav.frontTrafficSpeedCap
speed = min(speed, trafficLimit)
if reverse
speed = min(speed, slot.spec.vMaxRev)
slot.nav.steerDir = dir
var cmdDir = dir
let mode = wto_follow_drive_mode(dir, hullFwd, reverse, cmdDir)
wto_drive_cmd_set(slot.driveCmd, mode, target, cmdDir, speed, slot.nav.frontClearM, slot.nav.rearClearM)
let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= slot.nav.yieldUntil
wto_unstick_watch(world, navState, now, myPos, hullFwd, myPos + dir * 6.0, movingIntent, slot)
// Check both ends in the actual chassis frame. This also applies during pivots, short halts,
// tactical withdrawal and unstick, when the usual route traffic solver may not run.
[never_inline]
def private wto_nav_clearance(world : WtoWorldSnap const&; myPos, hullFwd : float3; var slot : WtoBotSlot&)
let probeBase = myPos + float3(0.0, 1.25, 0.0)
var traffic = WtoTrafficClearance()
wto_traffic_clearance(world, myPos, hullFwd, slot, traffic)
assume nav = slot.nav
nav.frontClearM = min(wto_terrain_hard_ray(probeBase, hullFwd, 24.0), traffic.frontM)
nav.rearClearM = min(wto_terrain_hard_ray(probeBase, -hullFwd, 18.0), traffic.rearM)
let speed = slot.drive.lastVFwd
nav.frontTrafficSpeedCap = wto_traffic_brake_speed(traffic.frontM, traffic.frontSpeed, max(0.0, speed), slot.spec.halfLen)
nav.rearTrafficSpeedCap = wto_traffic_brake_speed(traffic.rearM, traffic.rearSpeed, max(0.0, -speed), slot.spec.halfLen)
[never_inline]
def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; now : float;
myPos, rawHullFwd : float3; var slot : WtoBotSlot&)
if !WTO_AI_LAYER_NAVIGATION
slot.driveCmd.valid = false
return
let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0))
let probeBase = myPos + float3(0.0, 1.25, 0.0)
slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0)
slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0)
slot.nav.cliffAhead = wto_terrain_has_cliff_ahead(myPos, hullFwd, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M)
if slot.tactics.state == WTO_STATE_HULL_ANGLE
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd)
let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
if angErr > 8.0
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
else
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
wto_nav_clearance(world, myPos, hullFwd, slot)
let st = slot.tactics.state
if st != WTO_STATE_MARCH && st != WTO_STATE_RUN_AND_GUN
slot.tactics.reverseTravel = false
if st == WTO_STATE_HULL_ANGLE || st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD
wto_nav_stand(myPos, hullFwd, slot)
return
if wto_try_hull_aim(myPos, hullFwd, slot)
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
if slot.tactics.desiredSpeedMps <= 0.05
wto_nav_halt(myPos, hullFwd, slot)
return
if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
if wto_nav_tactical_reverse(navState, myPos, hullFwd, slot) || wto_unstick_reversing(now, myPos, slot)
return
if wto_try_reverse_drive(world, now, myPos, hullFwd, slot)
if navState == WTO_NAVMESH_UNDECIDED
wto_nav_halt(myPos, hullFwd, slot)
return
let wp = wto_route_select_waypoint(world, now, myPos, slot.tactics.moveGoal, slot)
let wishDir = wto_xz_normalize(wp - myPos, hullFwd)
wto_check_stuck_watchdog(world, now, myPos, wishDir, slot)
var bestDir = wishDir
if !wto_eval_forward_arcs(world, now, myPos, hullFwd, wishDir, slot.tactics.desiredSpeedMps, slot, bestDir)
if slot.nav.rearClearM > 3.2
slot.nav.reverseAnchor = myPos - hullFwd * 26.0
slot.nav.reverseUntil = now + 4.8
slot.nav.reverseCount++
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, slot.nav.reverseAnchor, -hullFwd, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM)
return
bestDir = wishDir
slot.nav.steerDir = bestDir
let turnDeg = acos(clamp(dot(wishDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
let needPivot = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG || (slot.nav.frontClearM < slot.spec.halfLen + 1.8 && turnDeg > 32.0)
let cmdDir = needPivot ? wishDir : bestDir
wto_set_drive_cmd(slot.driveCmd, needPivot ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE, myPos + cmdDir * 22.0, cmdDir, slot.tactics.desiredSpeedMps, slot.nav.frontClearM, slot.nav.rearClearM)
let goal = wto_route_active_goal(myPos, slot.tactics.moveGoal, slot)
wto_route_update(navState, slotIdx, now, myPos, goal, slot)
wto_nav_probe_mesh(navState, myPos, slot)
wto_nav_follow(world, navState, now, myPos, hullFwd, slot)
@@ -0,0 +1,84 @@
// Per-bot path, path-following, avoidance and unstick state (route / follow / avoid / unstick /
// nav modules) and the shared constants of the navigation layer.
options indenting = 2
options no_global_heap = true
module wto_ai_nav_types_common shared
// Corners a path may carry; matches WTO_NAV_RT_MAX_CORNERS of the native engine.
let public WTO_NAV_MAX_CORNERS = 96
// Where a bot's corridor came from.
let public WTO_ROUTE_SRC_NONE = 0
let public WTO_ROUTE_SRC_MESH = 1
let public WTO_ROUTE_SRC_STOCK = 2
let public WTO_ROUTE_SRC_RECOVER = 3
[safe_when_uninitialized]
struct public WtoRouteState
corridor : float3[96]
corridorLen : int = 0
source : int = 0
segIdx : int = 0
segT : float = 0.0
offTrackM : float = 0.0
goal : float3 = float3(0.0, 0.0, 0.0)
truncated : bool = false
pending : bool = false
ticket : int = 0
pendingGoal : float3 = float3(0.0, 0.0, 0.0)
nextReplanAt : float = -100.0
replanRequested : bool = false
tier : int = -1
filter : int = 0
lastStatus : int = -1
goalUnreachable : bool = false
unreachableGoal : float3 = float3(0.0, 0.0, 0.0)
requests : int = 0
noGoalCount : int = 0
[safe_when_uninitialized]
struct public WtoNavState
steerDir : float3 = float3(1.0, 0.0, 0.0)
frontClearM : float = 30.0
rearClearM : float = 16.0
frontTrafficSpeedCap : float = 99.0
rearTrafficSpeedCap : float = 99.0
onMesh : bool = false
wallDistM : float = 99.0
surfaceArea : int = 0
chokepoint : bool = false
bumperClearM : float = 99.0
bumperBlockedSince : float = -100.0
yieldUntil : float = -100.0
yieldCooldownUntil : float = -100.0
avoidActive : bool = false
avoidTarget : float3 = float3(0.0, 0.0, 0.0)
passEntry : float3 = float3(0.0, 0.0, 0.0)
passExit : float3 = float3(0.0, 0.0, 0.0)
passAtSide : bool = false
passUntil : float = -100.0
avoidSide : float = 0.0
avoidSideUntil : float = -100.0
avoidSpeedCap : float = 99.0
blockedSince : float = -100.0
contactSince : float = -100.0
contactBodyPos : float3 = float3(0.0, 0.0, 0.0)
contactBodyRadiusM : float = 0.0
lastContactAt : float = -100.0
lastContactPos : float3 = float3(0.0, 0.0, 0.0)
contactRepeats : int = 0
stuckOrigin : float3 = float3(0.0, 0.0, 0.0)
stuckCheckAt : float = -100.0
unstickAnchor : float3 = float3(0.0, 0.0, 0.0)
unstickLevel : int = 0
unstickAttempts : int = 0
lastUnstickAt : float = -100.0
reverseTarget : float3 = float3(0.0, 0.0, 0.0)
reverseUntil : float = -100.0
unstickForward : bool = false
reverseCount : int = 0
unstickEvents : int = 0
contactEvents : int = 0
blockEvents : int = 0
unreachableEvents : int = 0
ridgeWithdrawEvents : int = 0
+190
View File
@@ -0,0 +1,190 @@
// Baked navigation pack of the battle (native/wto-nav through the "wtoNav" mission action).
// The pack is read in the background while the battle loads (prefetch) and taken at the first
// world tick (load_map); whether the battle uses it, falls back to stock road paths or refuses to
// drive is decided by that load and never changes mid-battle. Queued path searches advance once
// per world tick within the per-frame budget (pump).
options indenting = 2
options no_global_heap = true
module wto_ai_navmesh_common shared
require ecs
require math
require DagorDataBlock
require DagorSystem
require Mission
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_navquery_common
let public WTO_NAVMESH_UNDECIDED = 0
let public WTO_NAVMESH_LOADED = 1
let public WTO_NAVMESH_FALLBACK = 2
let public WTO_NAVMESH_FAILED = 3
let public WTO_NAVMESH_OFF = 4
let public WTO_NAVMESH_TIER_STANDARD = 1
let public WTO_NAVMESH_FILTER_TRACKED = 0
[safe_when_uninitialized]
struct public WtoNavmeshBattle
state : int = 0
selfTestPhase : int = 0
selfTestTicket : int[3]
lastQueries : int = -1
lastMeshQueries : int = -1
[never_inline]
def private wto_navmesh_add_costs(var blk : DataBlock&)
add(blk, "t_road", "{WTO_AI_NAVMESH_T_ROAD}")
add(blk, "t_bridge", "{WTO_AI_NAVMESH_T_BRIDGE}")
add(blk, "t_ground", "{WTO_AI_NAVMESH_T_GROUND}")
add(blk, "t_rough", "{WTO_AI_NAVMESH_T_ROUGH}")
add(blk, "t_forest", "{WTO_AI_NAVMESH_T_FOREST}")
add(blk, "t_crushable", "{WTO_AI_NAVMESH_T_CRUSHABLE}")
add(blk, "t_shallowWater", "{WTO_AI_NAVMESH_T_SHALLOW_WATER}")
add(blk, "t_chokepoint", "{WTO_AI_NAVMESH_T_CHOKEPOINT}")
add(blk, "w_road", "{WTO_AI_NAVMESH_W_ROAD}")
add(blk, "w_bridge", "{WTO_AI_NAVMESH_W_BRIDGE}")
add(blk, "w_ground", "{WTO_AI_NAVMESH_W_GROUND}")
add(blk, "w_rough", "{WTO_AI_NAVMESH_W_ROUGH}")
add(blk, "w_forest", "{WTO_AI_NAVMESH_W_FOREST}")
add(blk, "w_crushable", "{WTO_AI_NAVMESH_W_CRUSHABLE}")
add(blk, "w_shallowWater", "{WTO_AI_NAVMESH_W_SHALLOW_WATER}")
add(blk, "w_chokepoint", "{WTO_AI_NAVMESH_W_CHOKEPOINT}")
// Team traffic and corner offset of the battle's searches.
[never_inline]
def private wto_navmesh_add_tuning(var blk : DataBlock&)
add(blk, "trafficPerPath", "{WTO_AI_NAVMESH_TRAFFIC_PER_PATH}")
add(blk, "trafficMaxMul", "{WTO_AI_NAVMESH_TRAFFIC_MAX_MUL}")
add(blk, "trafficHoldSec", "{WTO_AI_NAVMESH_TRAFFIC_HOLD_SEC}")
add(blk, "cornerOffset", "{WTO_AI_NAVMESH_CORNER_OFFSET_M}")
// Battle loading: start reading this battle's pack on a background thread.
[never_inline]
def public wto_navmesh_prefetch()
if !WTO_AI_NAVMESH_ENABLED
return
using() <| $(var blk : DataBlock)
add(blk, "op", "prefetch")
call_mission_action("wtoNav", blk)
let answer = datablock_getStr(blk, "state", "")
let level = datablock_getStr(blk, "level", "")
let reason = datablock_getStr(blk, "reason", "")
print("WTO_AI|NAVMESH_PREFETCH|state={answer}|level={level}|reason={reason}\n")
// Asks the native engine for this battle's pack once; returns a WTO_NAVMESH_* state.
[never_inline]
def public wto_navmesh_load() : int
if !WTO_AI_NAVMESH_ENABLED
print("WTO_AI|NAVMESH|state=off\n")
return WTO_NAVMESH_OFF
var state = WTO_AI_NAVMESH_ALLOW_FALLBACK ? WTO_NAVMESH_FALLBACK : WTO_NAVMESH_FAILED
using() <| $(var blk : DataBlock)
add(blk, "op", "load_map")
add(blk, "allowFallback", WTO_AI_NAVMESH_ALLOW_FALLBACK ? "1" : "0")
wto_navmesh_add_costs(blk)
wto_navmesh_add_tuning(blk)
call_mission_action("wtoNav", blk)
let answer = datablock_getStr(blk, "state", "")
if answer == "loaded"
state = WTO_NAVMESH_LOADED
elif answer == "fallback"
state = WTO_NAVMESH_FALLBACK
elif answer == "failed"
state = WTO_NAVMESH_FAILED
let reason = answer == "" ? "native navigation unavailable" : datablock_getStr(blk, "reason", "")
let level = datablock_getStr(blk, "level", "")
let fp = datablock_getStr(blk, "fingerprint", "")
let tiers = datablock_getInt(blk, "tiers", 0)
let covers = datablock_getInt(blk, "covers", 0)
print("WTO_AI|NAVMESH|state={state}|answer={answer}|level={level}|fp={fp}|tiers={tiers}|covers={covers}|reason={reason}\n")
return state
[never_inline]
def private wto_navmesh_unload()
using() <| $(var blk : DataBlock)
add(blk, "op", "unload_map")
call_mission_action("wtoNav", blk)
// Advances queued path searches within the per-frame budget and expires dynamic costs.
[never_inline]
def private wto_navmesh_pump(now : float)
using() <| $(var blk : DataBlock)
add(blk, "op", "pump")
add(blk, "now", "{now}")
add(blk, "budgetUs", "{WTO_AI_NAVMESH_PATH_BUDGET_US}")
call_mission_action("wtoNav", blk)
// One path per team from its spawn to the first capture zone through the queued search.
[never_inline]
def private wto_navmesh_self_test(world : WtoWorldSnap const&; var nm : WtoNavmeshBattle&)
if nm.selfTestPhase == 0
if world.capCount <= 0 || !world.teamSpawnValid[1] || !world.teamSpawnValid[2]
return
for army in range(1, 3)
nm.selfTestTicket[army] = wto_navq_path_request(WTO_NAVQ_SELFTEST_SLOT0 + army - 1, WTO_NAVMESH_TIER_STANDARD,
WTO_NAVMESH_FILTER_TRACKED, 0, world.teamSpawnCenter[army], world.caps[0].center)
nm.selfTestPhase = 1
return
if nm.selfTestPhase != 1
return
var pts : float3[96]
var finished = 0
for army in range(1, 3)
var count = 0
var lenM = 0.0
var truncated = false
let status = wto_navq_path_result(WTO_NAVQ_SELFTEST_SLOT0 + army - 1, nm.selfTestTicket[army], pts, count, lenM, truncated)
if status == WTO_PATH_PENDING
continue
finished++
if nm.selfTestTicket[army] == 0
continue
let last = count > 0 ? pts[count - 1] : float3(0.0, 0.0, 0.0)
print("WTO_AI|NAVMESH_SELFTEST|army={army}|status={status}|corners={count}|lenM={lenM}|from={world.teamSpawnCenter[army]}|to={world.caps[0].center}|end={last}\n")
nm.selfTestTicket[army] = 0
if finished == 2
nm.selfTestPhase = 2
// Per world tick: decide the battle's navigation once, then pump searches and run the self test.
[never_inline]
def public wto_navmesh_battle_tick(world : WtoWorldSnap const&; now : float; var nm : WtoNavmeshBattle&)
if nm.state == WTO_NAVMESH_UNDECIDED
nm.state = wto_navmesh_load()
if nm.state != WTO_NAVMESH_LOADED
return
wto_navmesh_pump(now)
wto_navmesh_self_test(world, nm)
// Battle end: release the pack and forget the decision.
[never_inline]
def public wto_navmesh_battle_reset(var nm : WtoNavmeshBattle&)
if nm.state != WTO_NAVMESH_UNDECIDED && nm.state != WTO_NAVMESH_OFF
wto_navmesh_unload()
nm = WtoNavmeshBattle()
// Engine statistics, printed only when they changed since the last print.
[never_inline]
def public wto_navmesh_log_stats(var nm : WtoNavmeshBattle&)
if nm.state != WTO_NAVMESH_LOADED
return
using() <| $(var blk : DataBlock)
add(blk, "op", "get_stats")
call_mission_action("wtoNav", blk)
let queries = datablock_getInt(blk, "queries", 0)
let meshQueries = datablock_getInt(blk, "meshQueries", 0)
if queries == nm.lastQueries && meshQueries == nm.lastMeshQueries
return
nm.lastQueries = queries
nm.lastMeshQueries = meshQueries
let failures = datablock_getInt(blk, "failures", 0)
let avgUs = datablock_getInt(blk, "avgUs", 0)
let maxUs = datablock_getInt(blk, "maxUs", 0)
let maxFrames = datablock_getInt(blk, "maxFrames", 0)
let pumpMaxUs = datablock_getInt(blk, "pumpMaxUs", 0)
let pending = datablock_getInt(blk, "pending", 0)
let dynCount = datablock_getInt(blk, "dynamic", 0)
let traffic = datablock_getInt(blk, "traffic", 0)
let moved = datablock_getInt(blk, "cornersMoved", 0)
print("WTO_AI|NAVMESH_STATS|paths={queries}|failures={failures}|avgUs={avgUs}|maxUs={maxUs}|maxFrames={maxFrames}|pumpMaxUs={pumpMaxUs}|pending={pending}|dynamic={dynCount}|meshQueries={meshQueries}|traffic={traffic}|cornersMoved={moved}\n")
+175
View File
@@ -0,0 +1,175 @@
// Script side of the native navigation queries ("wtoNav" mission action, local_mp_nav.c):
// queued path searches, mesh probes, mesh raycasts, nearest walkable point and dynamic costs.
// Requests are strings; replies are ints (coordinates in centimetres) and strings.
options indenting = 2
options no_global_heap = true
module wto_ai_navquery_common shared
require ecs
require math
require DagorDataBlock
require DagorSystem
require Mission
require %appGame.wtoai.wto_ai_config_common
let public WTO_PATH_FULL = 0
let public WTO_PATH_PARTIAL = 1
let public WTO_PATH_NO_START = 2
let public WTO_PATH_NO_GOAL = 3
let public WTO_PATH_FAILED = 4
let public WTO_PATH_PENDING = 5
let public WTO_PATH_STALE = 6
// Path slots of the native engine: 0..63 bots, 64..143 team lanes, 144..145 battle self test.
let public WTO_NAVQ_LANE_SLOT0 = 64
let public WTO_NAVQ_SELFTEST_SLOT0 = 144
let public WTO_NAVQ_FLAG_CHOKEPOINT = 8
let public WTO_NAVQ_FLAG_ROAD = 32
[safe_when_uninitialized]
struct public WtoNavProbeOut
onMesh : bool = false
nearest : float3 = float3(0.0, 0.0, 0.0)
offsetM : float = 0.0
wallDistM : float = 99.0
area : int = 0
flags : int = 0
[never_inline]
def private wto_navq_status(answer : string) : int
if answer == "full"
return WTO_PATH_FULL
if answer == "partial"
return WTO_PATH_PARTIAL
if answer == "no_start"
return WTO_PATH_NO_START
if answer == "no_goal"
return WTO_PATH_NO_GOAL
if answer == "pending"
return WTO_PATH_PENDING
if answer == "stale"
return WTO_PATH_STALE
return WTO_PATH_FAILED
[never_inline]
def private wto_navq_add_point(var blk : DataBlock&; prefix : string; p : float3)
add(blk, "{prefix}x", "{p.x}")
add(blk, "{prefix}y", "{p.y}")
add(blk, "{prefix}z", "{p.z}")
[never_inline]
def private wto_navq_get_point(blk : DataBlock const&; kx, ky, kz : string) : float3
let x = float(datablock_getInt(blk, kx, 0)) * 0.01
let y = float(datablock_getInt(blk, ky, 0)) * 0.01
let z = float(datablock_getInt(blk, kz, 0)) * 0.01
return float3(x, y, z)
// Queues a path search in native slot `slot`; returns its ticket (0 when refused). With a team
// (`group` 1 or 2) the search avoids routes teammates planned recently and counts as one itself.
[never_inline]
def public wto_navq_path_request(slot, tier, costFilter, group : int; start, goal : float3) : int
var ticket = 0
using() <| $(var blk : DataBlock)
add(blk, "op", "path_request")
add(blk, "slot", "{slot}")
add(blk, "tier", "{tier}")
add(blk, "filter", "{costFilter}")
add(blk, "group", "{group}")
add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}")
add(blk, "goalSnap", "{WTO_AI_NAVMESH_GOAL_SNAP_M}")
wto_navq_add_point(blk, "s", start)
wto_navq_add_point(blk, "g", goal)
call_mission_action("wtoNav", blk)
ticket = datablock_getInt(blk, "ticket", 0)
return ticket
// Result of a ticket; corners are copied into `pts` only for full and partial paths.
[never_inline]
def public wto_navq_path_result(slot, ticket : int; var pts : float3[96]&; var count : int&;
var lenM : float&; var truncated : bool&) : int
var status = WTO_PATH_FAILED
using() <| $(var blk : DataBlock)
add(blk, "op", "path_result")
add(blk, "slot", "{slot}")
add(blk, "ticket", "{ticket}")
call_mission_action("wtoNav", blk)
status = wto_navq_status(datablock_getStr(blk, "status", ""))
if status != WTO_PATH_FULL && status != WTO_PATH_PARTIAL
return
count = clamp(datablock_getInt(blk, "count", 0), 0, 96)
lenM = float(datablock_getInt(blk, "lenCm", 0)) * 0.01
truncated = datablock_getInt(blk, "truncated", 0) != 0
for i in range(count)
pts[i] = wto_navq_get_point(blk, "p{i}x", "p{i}y", "p{i}z")
return status
// Surface, flags and distance to the mesh edge under `pos`; false when the engine gave no answer.
[never_inline]
def public wto_navq_probe(tier, costFilter : int; pos : float3; wallRadiusM : float;
var probe : WtoNavProbeOut&) : bool
var answered = false
using() <| $(var blk : DataBlock)
add(blk, "op", "probe")
add(blk, "tier", "{tier}")
add(blk, "filter", "{costFilter}")
add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}")
add(blk, "wallR", "{wallRadiusM}")
wto_navq_add_point(blk, "p", pos)
call_mission_action("wtoNav", blk)
let onMesh = datablock_getInt(blk, "onMesh", -1)
answered = onMesh >= 0
probe.onMesh = onMesh == 1
if !probe.onMesh
return
probe.offsetM = float(datablock_getInt(blk, "offCm", 0)) * 0.01
probe.wallDistM = float(datablock_getInt(blk, "wallCm", 0)) * 0.01
probe.area = datablock_getInt(blk, "area", 0)
probe.flags = datablock_getInt(blk, "flags", 0)
probe.nearest = wto_navq_get_point(blk, "nx", "ny", "nz")
return answered
// 1 when the mesh lets a vehicle go straight from start to goal, 0 when an edge blocks it
// (`hitFrac` of the way), -1 when start is off the mesh or the engine gave no answer.
[never_inline]
def public wto_navq_raycast(tier, costFilter : int; start, goal : float3; var hitFrac : float&) : int
var clear = -1
hitFrac = 0.0
using() <| $(var blk : DataBlock)
add(blk, "op", "raycast")
add(blk, "tier", "{tier}")
add(blk, "filter", "{costFilter}")
add(blk, "snap", "{WTO_AI_NAVMESH_SNAP_M}")
wto_navq_add_point(blk, "s", start)
wto_navq_add_point(blk, "g", goal)
call_mission_action("wtoNav", blk)
clear = datablock_getInt(blk, "clear", -1)
hitFrac = float(datablock_getInt(blk, "hitPm", 0)) * 0.001
return clear
// Nearest walkable point within `radiusM` horizontally (any height).
[never_inline]
def public wto_navq_nearest(tier, costFilter : int; pos : float3; radiusM : float; var outPt : float3&) : bool
var found = false
using() <| $(var blk : DataBlock)
add(blk, "op", "nearest")
add(blk, "tier", "{tier}")
add(blk, "filter", "{costFilter}")
add(blk, "radius", "{radiusM}")
wto_navq_add_point(blk, "p", pos)
call_mission_action("wtoNav", blk)
found = datablock_getInt(blk, "found", 0) == 1
if found
outPt = wto_navq_get_point(blk, "x", "y", "z")
return found
// Makes later path searches avoid a circle (wreck, jam, rubble) until script time `untilAt`.
[never_inline]
def public wto_navq_add_dynamic(pos : float3; radiusM, costMul, untilAt : float)
using() <| $(var blk : DataBlock)
add(blk, "op", "dynamic")
wto_navq_add_point(blk, "p", pos)
add(blk, "radius", "{radiusM}")
add(blk, "mul", "{costMul}")
add(blk, "until", "{untilAt}")
call_mission_action("wtoNav", blk)
+127 -98
View File
@@ -10,51 +10,54 @@ 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_terrain_common
require %appGame.wtoai.wto_ai_sight_common
require %appGame.wtoai.wto_ai_estimate_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_threat_common
// The current engagement and more dangerous contacts keep their tracks when the table is full.
[never_inline]
def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId) : int
def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId; now, danger : float) : int
var freeIdx = -1
var minIdx = 0
var minScore = 2.0
var weakest = -1
var minScore = danger
for i in range(WTO_MAX_EXPOSURE_TRACKS)
if p.expEids[i] == eid
return i
if !p.expEids[i] && freeIdx < 0
freeIdx = i
if p.expScore[i] < minScore
minScore = p.expScore[i]
minIdx = i
let dst = freeIdx >= 0 ? freeIdx : minIdx
p.expEids[dst] = eid
p.expScore[dst] = 0.0
p.expGoodLosSec[dst] = 0.0
if !p.expEids[i]
if freeIdx < 0
freeIdx = i
continue
if p.hasClearLos && p.expEids[i] == p.targetEid
continue
let fresh = now - p.expSeenAt[i] <= WTO_AI_TACTICS_TICK_SEC * 1.5
let score = p.expDanger[i] * (fresh ? 1.0 : WTO_AI_THREAT_UNSEEN_MUL)
if score < minScore
minScore = score
weakest = i
let dst = freeIdx >= 0 ? freeIdx : weakest
if dst >= 0
p.expEids[dst] = eid
p.expScore[dst] = 0.0
p.expGoodLosSec[dst] = 0.0
return dst
[never_inline]
def private wto_exp_decay_all(world : WtoWorldSnap const&; dt : float; var p : WtoPerceiveState&)
def private wto_exp_decay_unseen(world : WtoWorldSnap const&; now, dt : float; var p : WtoPerceiveState&)
let decay = WTO_AI_PERC_DECAY_PER_SEC * dt
for i in range(WTO_MAX_EXPOSURE_TRACKS)
if !p.expEids[i]
continue
let uIdx = wto_world_find_unit(world, p.expEids[i])
if uIdx < 0 || !world.units[uIdx].isAlive
p.expEids[i] = INVALID_ENTITY_ID
p.expScore[i] = 0.0
p.expGoodLosSec[i] = 0.0
if !p.expEids[i] || p.expSeenAt[i] >= now
continue
let idx = wto_world_find_unit(world, p.expEids[i])
p.expGoodLosSec[i] = 0.0
p.expScore[i] = max(0.0, p.expScore[i] - decay)
if p.expScore[i] <= 0.001
if idx < 0 || !world.units[idx].isAlive || p.expScore[i] <= 0.001
p.expEids[i] = INVALID_ENTITY_ID
p.expScore[i] = 0.0
p.expGoodLosSec[i] = 0.0
[never_inline]
def private wto_spot_fill_time(dist : float; cosAngle : float; isShooting : bool; visCount : int) : float
let cosFront = cos(WTO_AI_PERC_FRONT_CONE_DEG * WTO_DEG_TO_RAD)
let cosFront = cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD)
var t = WTO_AI_PERC_FAR_SPOT_SEC
if dist < WTO_AI_PERC_NEAR_SPOT_M || (isShooting && dist < WTO_AI_PERC_FIRING_SPOT_M)
t = WTO_AI_PERC_FAST_SPOT_SEC
@@ -99,16 +102,72 @@ def private wto_update_audio_and_radio_alerts(world : WtoWorldSnap const&; now :
p.alertUntil = now + 2.8
return
// Horizontal bearings for ground targets use the live barrel yaw. For airborne targets or a
// vertical barrel the full 3D angle gives a bearing without inventing a horizontal forward axis.
def private wto_perc_bearing(delta, barrel : float3; isAir : bool) : float
let ground = float2(delta.x, delta.z)
let sight = float2(barrel.x, barrel.z)
if !isAir && length_sq(ground) > 1.0e-6 && length_sq(sight) > 1.0e-6
return clamp(dot(normalize(ground), normalize(sight)), -1.0, 1.0)
return clamp(dot(normalize(delta), barrel), -1.0, 1.0)
def private wto_perc_layer_mul(dist, cosBarrel : float; lookAround : bool) : float
if cosBarrel >= cos(WTO_AI_PERC_GUN_FOV_HALF_DEG * WTO_DEG_TO_RAD)
return 1.0
if dist <= WTO_AI_PERC_NEAR_AWARE_M && (lookAround || cosBarrel >= cos(0.5 * WTO_AI_PERC_NEAR_ARC_DEG * WTO_DEG_TO_RAD))
return WTO_AI_PERC_NEAR_SPOT_MUL
if dist <= WTO_AI_PERC_MID_AWARE_M && cosBarrel >= 0.0
return WTO_AI_PERC_MID_SPOT_MUL
return 0.0
// Integrates one enemy's exposure this tick; its track index, or -1 when no perception layer
// covers it or it is hidden. The output is the visible sample count and its center.
[never_inline]
def private wto_exp_observe(world : WtoWorldSnap const&; now, dt : float; myEye, barrelDir : float3;
lookAround : bool; u : WtoUnitSnap const&; var slot : WtoBotSlot&;
var vis : int&; var aimPt : float3&) : int
assume p = slot.perceive
let delta = u.pos - myEye
let dist = length(delta)
if dist > (u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M) || dist < 1.0
return -1
let cosAng = wto_perc_bearing(delta, barrelDir, u.isAir)
let airFront = u.isAir && cosAng >= 0.0
let layerMul = airFront ? 1.0 : wto_perc_layer_mul(dist, cosAng, lookAround)
if layerMul <= 0.0
return -1
aimPt = u.pos + float3(0.0, 1.3, 0.0)
vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4, aimPt)
if vis <= 0
return -1
let danger = wto_threat_observed_danger(now, myEye, u, p)
let tIdx = wto_exp_find_or_alloc(p, u.eid, now, danger)
if tIdx < 0
return -1
let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis) * layerMul
p.expScore[tIdx] = clamp(p.expScore[tIdx] + dt / fillSec, 0.0, 1.0)
p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0
p.expDanger[tIdx] = danger
p.expSeenAt[tIdx] = now
p.expPos[tIdx] = u.pos
return tIdx
def private wto_exp_shot_priority(u : WtoUnitSnap const&; myEye : float3; isSpaa : bool) : int
if !isSpaa
return 0
if u.isAir
return 1
return wto_xz_dist_sq(u.pos, myEye) <= wto_sq(WTO_AI_FC_CLOSE_RANGE_M) ? 2 : 0
[never_inline]
def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : float;
myEye, lookDir : float3; var slot : WtoBotSlot&;
myEye, barrelDir : float3; lookAround : bool; var slot : WtoBotSlot&;
var outBestIdx, outVisCount : int&;
var outGoodLosSec : float&; var outAimPt : float3&)
assume p = slot.perceive
let cosHalfFov = cos(0.5 * WTO_AI_TACTICS_VISION_FOV_DEG * WTO_DEG_TO_RAD)
let isSpaa = slot.spec.role == WTO_ROLE_SPAA
let decay = WTO_AI_PERC_DECAY_PER_SEC * dt
var bestScore = 1.0e9
var bestScore = -1.0
var bestPriority = -1
outBestIdx = -1
outVisCount = 0
outGoodLosSec = 0.0
@@ -116,64 +175,59 @@ def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : floa
assume u = world.units[i]
if !u.isAlive || u.army == slot.army || (u.isAir && !isSpaa)
continue
let delta = u.pos - myEye
let dist = length(delta)
let maxRange = u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M
if dist > maxRange || dist < 1.0
var vis = 0
var aimPt = u.pos
let tIdx = wto_exp_observe(world, now, dt, myEye, barrelDir, lookAround, u, slot, vis, aimPt)
if tIdx < 0 || p.expScore[tIdx] < 0.999
continue
let dirXZ = wto_xz_normalize(delta, lookDir)
let cosAng = dot(dirXZ, lookDir)
let inFov = cosAng >= cosHalfFov || (dist <= WTO_AI_PERC_PERIPH_CLOSE_M && cosAng >= 0.0)
if !inFov && !u.isAir
continue
let maxSamples = dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4
var samplePt = u.pos + float3(0.0, 1.3, 0.0)
let vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, maxSamples, samplePt)
if vis <= 0
for k in range(WTO_MAX_EXPOSURE_TRACKS)
if p.expEids[k] == u.eid
p.expGoodLosSec[k] = 0.0
continue
let tIdx = wto_exp_find_or_alloc(p, u.eid)
let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis)
p.expScore[tIdx] = clamp(p.expScore[tIdx] + decay + dt / fillSec, 0.0, 1.0)
p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0
if p.expScore[tIdx] < 0.999
continue
var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0)
if u.eid == p.lockedEid && now < p.lockedUntil
score -= 320.0
elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0
score -= 90.0
elif u.isShooting && dist < 220.0
score -= 35.0
if dist < 45.0
score -= 180.0
if score < bestScore
let priority = wto_exp_shot_priority(u, myEye, isSpaa)
let locked = u.eid == p.lockedEid && now < p.lockedUntil
let score = p.expDanger[tIdx] * (locked ? 1.0 + WTO_AI_TURRET_SWITCH_MARGIN : 1.0)
if priority > bestPriority || (priority == bestPriority && score > bestScore)
bestPriority = priority
bestScore = score
outBestIdx = i
outVisCount = vis
outGoodLosSec = p.expGoodLosSec[tIdx]
outAimPt = samplePt
outAimPt = aimPt
// Look-around temporarily opens the close rear arc relative to the barrel.
def private wto_perc_look_around(now : float; eid : EntityId; var p : WtoPerceiveState&) : bool
if p.nextLookAroundAt <= 0.0
p.nextLookAroundAt = now + float(int(uint(eid) % 8u))
elif now >= p.nextLookAroundAt && !p.hasClearLos
p.lookAroundUntil = now + WTO_AI_PERC_LOOK_AROUND_HOLD_SEC
p.nextLookAroundAt = now + WTO_AI_PERC_LOOK_AROUND_SEC
return now < p.lookAroundUntil
// A quick prediction from the bot's own motion estimate, using the existing visual occluders.
[never_inline]
def private wto_perc_fleeting(world : WtoWorldSnap const&; myEye : float3; slot : WtoBotSlot const&) : bool
assume p = slot.perceive
let los = wto_xz_normalize(p.knownPos - myEye, float3(1.0, 0.0, 0.0))
let laterally = abs(dot(p.estVel, float3(-los.z, 0.0, los.x)))
if laterally < WTO_AI_FC_FLEETING_LAT_MPS
return false
let future = p.visibleAimPt + p.estVel * WTO_AI_FC_FLEETING_LOOKAHEAD_SEC
return wto_sight_visual_clear(world, slot.eid, p.targetEid, myEye, future) != WTO_BLOCK_NONE
[never_inline]
def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
myPos, hullFwd : float3; var slot : WtoBotSlot&)
myPos : float3; var slot : WtoBotSlot&)
assume p = slot.perceive
let myEye = myPos + float3(0.0, 2.15, 0.0)
var lookDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
if slot.fire.servoInit
let worldYaw = atan2(hullFwd.z, hullFwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD
lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw))
wto_exp_decay_all(world, dt, p)
let lookAround = wto_perc_look_around(now, slot.eid, p)
var bestIdx = -1
var visCount = 0
var goodLosSec = 0.0
var aimPt = myPos
wto_scan_visual_exposure(world, now, dt, myEye, lookDir, slot, bestIdx, visCount, goodLosSec, aimPt)
if slot.fire.hasBarrelSight
wto_scan_visual_exposure(world, now, dt, myEye, slot.fire.barrelSight, lookAround, slot, bestIdx, visCount, goodLosSec, aimPt)
wto_exp_decay_unseen(world, now, dt, p)
if bestIdx >= 0
assume tgt = world.units[bestIdx]
if tgt.isShooting || p.targetEid != tgt.eid
p.targetShotAt = tgt.isShooting ? now : -100.0
p.targetEid = tgt.eid
p.targetIsAir = tgt.isAir
p.hasClearLos = true
@@ -185,7 +239,8 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
p.wasEngaging = !tgt.isAir
p.watchUntil = -100.0
wto_est_push_visual_sample(now, tgt.eid, tgt.pos, p)
if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5
p.targetFleeting = !tgt.isAir && wto_perc_fleeting(world, myEye, slot)
if p.lockedEid != tgt.eid
p.lockedEid = tgt.eid
p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC
if !tgt.isAir && (now - p.lastRadioSentAt) >= 2.5
@@ -195,6 +250,7 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
// Lost visual confirmation: immediately revoke LOS, freeze exit point for 2-5 s watch, zero velocity.
p.hasClearLos = false
p.targetFleeting = false
p.visiblePointCount = 0
p.goodLosSec = 0.0
wto_est_on_los_lost(now, slot.eid, p)
@@ -204,30 +260,3 @@ def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
p.lockedEid = INVALID_ENTITY_ID
p.watchUntil = -100.0
wto_update_audio_and_radio_alerts(world, now, myPos, slot)
[never_inline]
def public wto_perceive_pick_hunt_pos(world : WtoWorldSnap const&; army : int; eid : EntityId;
myPos : float3; now : float; var outPos : float3&) : bool
var bestDistSq = wto_sq(min(WTO_AI_TACTICS_RADIO_SHARE_M, 560.0))
var found = false
var spotPos = myPos
for r in range(WTO_MAX_RADIO)
assume sp = world.radioSpots[r]
if sp.untilAt <= now || sp.army != army
continue
let dSq = wto_xz_dist_sq(myPos, sp.pos)
if dSq < bestDistSq && dSq > 2500.0
bestDistSq = dSq
spotPos = sp.pos
found = true
if !found
return false
let toSpot = wto_xz_normalize(spotPos - myPos, float3(1.0, 0.0, 0.0))
let lat = float3(-toSpot.z, 0.0, toSpot.x)
let fanOffset = float(int(uint(eid) % 5u) - 2) * 28.0
var cand = spotPos - toSpot * 65.0 + lat * fanOffset
cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0)
if !wto_terrain_point_valid(army, cand)
cand = spotPos
outPos = cand
return true
+97
View File
@@ -0,0 +1,97 @@
// XZ geometry on path corner lists (float3[96] plus a count): length, sampling, tracking a
// position along the path and walking forward or back from it.
options indenting = 2
options no_global_heap = true
module wto_ai_polyline_common shared
require math
require %appGame.wtoai.wto_ai_math_common
// Closest point of segment a-b to p in the XZ plane: `t` in 0..1, returns the squared distance.
[never_inline]
def public wto_poly_seg_closest(a, b, p : float3; var t : float&) : float
let abx = b.x - a.x
let abz = b.z - a.z
let lenSq = abx * abx + abz * abz
t = lenSq > 1.0e-6 ? clamp(((p.x - a.x) * abx + (p.z - a.z) * abz) / lenSq, 0.0, 1.0) : 0.0
let cx = a.x + abx * t
let cz = a.z + abz * t
return wto_sq(p.x - cx) + wto_sq(p.z - cz)
[never_inline]
def public wto_poly_length(pts : float3[96]; count : int) : float
var total = 0.0
for i in range(1, count)
total += sqrt(wto_xz_dist_sq(pts[i - 1], pts[i]))
return total
// Point `frac` (0..1) of the way along the path.
[never_inline]
def public wto_poly_sample(pts : float3[96]; count : int; frac : float) : float3
if count <= 0
return float3(0.0, 0.0, 0.0)
let target = wto_poly_length(pts, count) * clamp(frac, 0.0, 1.0)
var acc = 0.0
for i in range(1, count)
let seg = sqrt(wto_xz_dist_sq(pts[i - 1], pts[i]))
if acc + seg >= target && seg > 0.01
return lerp(pts[i - 1], pts[i], (target - acc) / seg)
acc += seg
return pts[count - 1]
// Segment closest to `pos` among the few after `fromSeg` (never behind it); returns the XZ distance.
[never_inline]
def public wto_poly_track(pts : float3[96]; count : int; fromSeg : int; pos : float3;
var seg : int&; var t : float&) : float
seg = clamp(fromSeg, 0, max(0, count - 2))
t = 0.0
if count < 2
return count == 1 ? sqrt(wto_xz_dist_sq(pos, pts[0])) : 0.0
var bestSq = 1.0e12
let last = min(count - 2, seg + 6)
for k in range(seg, last + 1)
var tk = 0.0
let dSq = wto_poly_seg_closest(pts[k], pts[k + 1], pos, tk)
if dSq <= bestSq
bestSq = dSq
seg = k
t = tk
return sqrt(bestSq)
// Point `dist` metres further along the path than (seg, t); the last corner when past the end.
[never_inline]
def public wto_poly_walk(pts : float3[96]; count : int; seg : int; t, dist : float) : float3
if count <= 0
return float3(0.0, 0.0, 0.0)
if count == 1
return pts[0]
let s0 = clamp(seg, 0, count - 2)
var cur = lerp(pts[s0], pts[s0 + 1], t)
var left = dist
for k in range(s0 + 1, count)
let segLen = sqrt(wto_xz_dist_sq(cur, pts[k]))
if segLen >= left && segLen > 1.0e-3
return lerp(cur, pts[k], left / segLen)
left -= segLen
cur = pts[k]
return pts[count - 1]
// Point `dist` metres back along the path from (seg, t); the first corner when past the start.
[never_inline]
def public wto_poly_walk_back(pts : float3[96]; count : int; seg : int; t, dist : float) : float3
if count <= 0
return float3(0.0, 0.0, 0.0)
if count == 1
return pts[0]
let s0 = clamp(seg, 0, count - 2)
var cur = lerp(pts[s0], pts[s0 + 1], t)
var left = dist
var k = s0
while k >= 0
let segLen = sqrt(wto_xz_dist_sq(cur, pts[k]))
if segLen >= left && segLen > 1.0e-3
return lerp(cur, pts[k], left / segLen)
left -= segLen
cur = pts[k]
k--
return pts[0]
+144 -153
View File
@@ -1,169 +1,160 @@
// Corridor route planner: wide-projected `nm1` NavMesh pathfinding (fixing off-road hill caps),
// 5-wing lateral approach relays, crest-safe cross-country shortcuts, and corridor-independent
// jam/cluster bypass waypoints.
// Corridor of every bot: which mesh tier and cost filter fit the vehicle, when to plan again
// (goal moved, off the corridor, timer, obstacle reported) and where the path comes from — queued
// native searches on the battle's pack, or the stock road mesh when the battle fell back.
options indenting = 2
options no_global_heap = true
module wto_ai_route_common shared
require ecs
require math
require pathfinder
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_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_nav_types_common
require %appGame.wtoai.wto_ai_polyline_common
require %appGame.wtoai.wto_ai_navquery_common
require %appGame.wtoai.wto_ai_navmesh_common
require %appGame.wtoai.wto_ai_stockpath_common
// Mesh tier by vehicle width as baked: narrow up to 2.9 m, standard up to 3.6 m, wide above.
// spec.halfWid carries the 0.18 m collision margin of wto_specs_load, removed here.
[never_inline]
def public wto_route_tier(spec : WtoVehicleSpec const&) : int
let width = max(0.0, spec.halfWid - 0.18) * 2.0
if width <= 2.9
return 0
if width <= 3.6
return 1
return 2
[never_inline]
def private wto_project_nav_wide(navIdx : int; var pt : float3&) : bool
if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0))
return true
return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(165.0, 130.0, 165.0))
def public wto_route_filter(spec : WtoVehicleSpec const&) : int
return spec.isTracked ? 0 : 1
// Destination of this tick: the order's relay (flank or rally) while marching toward it.
[never_inline]
def private wto_replan_corridor(now : float; myPos, goal : float3; var rt : WtoRouteState&)
rt.nextReplanAt = now + 2.8
rt.corridorGoal = goal
rt.corridorLen = 0
rt.corridorIdx = 0
let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1)
if navIdx < 0
rt.lastStartOk = false
rt.lastGoalOk = false
return
var sPt = myPos
var gPt = goal
rt.lastStartOk = wto_project_nav_wide(navIdx, sPt)
rt.lastGoalOk = wto_project_nav_wide(navIdx, gPt)
if !rt.lastStartOk || !rt.lastGoalOk
return
let maxKeep = WTO_MAX_PATH_PTS - 1
find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array<float3>#)
let total = length(path)
if total <= 0
return
rt.corridor[0] = path[0]
rt.corridorLen = 1
let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0
for i in range(1, total)
if rt.corridorLen >= maxKeep
break
let prev = rt.corridor[rt.corridorLen - 1]
var isCorner = false
if i + 1 < total
let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0))
let d1 = wto_xz_normalize(path[i + 1] - path[i], d0)
isCorner = dot(d0, d1) < 0.86
if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq
rt.corridor[rt.corridorLen] = path[i]
rt.corridorLen++
if rt.corridorLen < maxKeep && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], path[total - 1]) > 9.0
rt.corridor[rt.corridorLen] = path[total - 1]
rt.corridorLen++
if rt.corridorLen > 0 && rt.corridorLen < WTO_MAX_PATH_PTS && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], goal) > 64.0
rt.corridor[rt.corridorLen] = goal
rt.corridorLen++
// Validate a crest-safe cross-country shortcut (<= 145m) with zero cliff drop-offs or jams.
[never_inline]
def private wto_try_shortcut(world : WtoWorldSnap const&; now : float; myPos, target : float3;
var slot : WtoBotSlot&)
assume rt = slot.route
rt.shortcutValid = false
rt.nextShortcutAt = now + 1.1
let dist = sqrt(wto_xz_dist_sq(myPos, target))
if dist < 22.0 || dist > 145.0
return
let dir = wto_xz_normalize(target - myPos, float3(1.0, 0.0, 0.0))
if wto_terrain_has_cliff_ahead(myPos, dir, min(dist, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M + 8.0))
return
let steps = clamp(int(dist / 7.5), 2, 20)
var prev = myPos
for s in range(1, steps + 1)
let d = (dist * float(s)) / float(steps)
let tx = myPos.x + dir.x * d
let tz = myPos.z + dir.z * d
var gy = prev.y
if !wto_terrain_drivable_y(prev, tx, tz, gy)
return
let samplePt = float3(tx, gy, tz)
if wto_world_jam_penalty(world, samplePt, now) > 4.0 || wto_crowd_point_penalty(world, slot.army, slot.eid, samplePt) > 18.0
return
if wto_terrain_hard_ray(prev + float3(0.0, 1.3, 0.0), dir, 8.0) < 7.5
return
prev = samplePt
rt.shortcutPos = target
rt.shortcutValid = true
// Generate a lateral bypass waypoint around an obstacle/jam, even when no NavMesh corridor exists.
[never_inline]
def public wto_route_request_detour(world : WtoWorldSnap const&; now : float;
myPos, blockedDir : float3; var slot : WtoBotSlot&)
assume rt = slot.route
let fwd = wto_xz_normalize(blockedDir, float3(1.0, 0.0, 0.0))
let lat = float3(-fwd.z, 0.0, fwd.x)
let pref = ((uint(slot.eid) + uint(rt.detourCount)) & 1u) == 0u ? 1.0 : -1.0
var bestScore = -1.0e9
var found = false
var bestPt = myPos
for k in range(4)
let side = (k % 2 == 0 ? pref : -pref) * (k < 2 ? 38.0 : 56.0)
let fwdStep = k < 2 ? 22.0 : 12.0
var cand = wto_clamp_battle_xz(myPos + fwd * fwdStep + lat * side, world.battleCenter, world.battleRadius, 35.0)
if !wto_terrain_point_valid(slot.army, cand)
continue
let candDir = wto_xz_normalize(cand - myPos, lat)
if wto_terrain_has_cliff_ahead(myPos, candDir, 18.0)
continue
if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), candDir, 16.0) < 10.0
continue
let score = -wto_world_jam_penalty(world, cand, now) - wto_crowd_point_penalty(world, slot.army, slot.eid, cand)
if score > bestScore
bestScore = score
bestPt = cand
found = true
if found
rt.detourPos = bestPt
rt.detourValid = true
rt.detourUntil = now + 11.0
rt.detourCount++
[never_inline]
def public wto_route_select_waypoint(world : WtoWorldSnap const&; now : float;
myPos, finalGoal : float3; var slot : WtoBotSlot&) : float3
assume rt = slot.route
if rt.detourValid
if now < rt.detourUntil && wto_xz_dist_sq(myPos, rt.detourPos) > 100.0
return rt.detourPos
rt.detourValid = false
if !rt.wingInit
rt.wingInit = true
rt.laneOffsetM = float(int((uint(slot.eid) / 5u) % 5u) - 2) * 4.0
def public wto_route_active_goal(myPos, finalGoal : float3; slot : WtoBotSlot const&) : float3
let st = slot.tactics.state
let useRelay = (st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE) && slot.order.routeRelayValid
var activeGoal = finalGoal
if useRelay
let relay = slot.order.routeRelayPos
let distMeToRelaySq = wto_xz_dist_sq(myPos, relay)
let distMeToGoalSq = wto_xz_dist_sq(myPos, finalGoal)
let distRelayToGoalSq = wto_xz_dist_sq(relay, finalGoal)
if slot.order.rallyHold || (distMeToRelaySq > 1444.0 && distMeToGoalSq > distRelayToGoalSq)
activeGoal = relay
let marching = st == WTO_STATE_MARCH || st == WTO_STATE_RUN_AND_GUN
if !marching || !slot.order.routeRelayValid
return finalGoal
let relay = slot.order.routeRelayPos
let meToRelaySq = wto_xz_dist_sq(myPos, relay)
if slot.order.rallyHold || (meToRelaySq > 1444.0 && wto_xz_dist_sq(myPos, finalGoal) > wto_xz_dist_sq(relay, finalGoal))
return relay
return finalGoal
if now >= rt.nextShortcutAt
wto_try_shortcut(world, now, myPos, activeGoal, slot)
if rt.shortcutValid && wto_xz_dist_sq(rt.shortcutPos, activeGoal) <= 144.0
return activeGoal
[never_inline]
def private wto_route_accept(var rt : WtoRouteState&; count : int; goal : float3; truncated : bool; source : int)
rt.corridorLen = count
rt.segIdx = 0
rt.segT = 0.0
rt.offTrackM = 0.0
rt.goal = goal
rt.truncated = truncated
rt.source = source
rt.goalUnreachable = false
if now >= rt.nextReplanAt || wto_xz_dist_sq(rt.corridorGoal, activeGoal) > 400.0
wto_replan_corridor(now, myPos, activeGoal, rt)
while rt.corridorIdx < rt.corridorLen - 1 && wto_xz_dist_sq(myPos, rt.corridor[rt.corridorIdx]) <= 256.0
rt.corridorIdx++
if rt.corridorLen > 0 && rt.corridorIdx < rt.corridorLen
let wp = rt.corridor[rt.corridorIdx]
let toWp = wto_xz_normalize(wp - myPos, float3(1.0, 0.0, 0.0))
let lat = float3(-toWp.z, 0.0, toWp.x)
return wp + lat * clamp(rt.laneOffsetM, -6.0, 6.0)
return activeGoal
// Straight two-point corridor (stock fallback without a road path, or back onto the mesh).
[never_inline]
def private wto_route_straight(var rt : WtoRouteState&; myPos, goal : float3; source : int)
rt.corridor[0] = myPos
rt.corridor[1] = goal
wto_route_accept(rt, 2, goal, source == WTO_ROUTE_SRC_RECOVER, source)
[never_inline]
def private wto_route_request(navState, slotIdx : int; now : float; myPos, goal : float3; var slot : WtoBotSlot&)
assume rt = slot.route
rt.tier = wto_route_tier(slot.spec)
rt.filter = wto_route_filter(slot.spec)
rt.nextReplanAt = now + WTO_AI_PF_REPLAN_SEC
rt.replanRequested = false
rt.requests++
if navState == WTO_NAVMESH_LOADED
rt.ticket = wto_navq_path_request(slotIdx, rt.tier, rt.filter, slot.army, myPos, goal)
rt.pending = rt.ticket > 0
rt.pendingGoal = goal
return
var count = 0
if wto_stock_path(myPos, goal, rt.corridor, count)
wto_route_accept(rt, count, goal, false, WTO_ROUTE_SRC_STOCK)
else
wto_route_straight(rt, myPos, goal, WTO_ROUTE_SRC_STOCK)
// The bot stands off the mesh: head for the nearest walkable point, then plan again from there.
[never_inline]
def private wto_route_recover(now : float; myPos : float3; var rt : WtoRouteState&)
var onMesh = myPos
rt.nextReplanAt = now + 1.0
if wto_navq_nearest(rt.tier, rt.filter, myPos, WTO_AI_NAVMESH_GOAL_SNAP_M, onMesh)
wto_route_straight(rt, myPos, onMesh, WTO_ROUTE_SRC_RECOVER)
else
rt.corridorLen = 0
[never_inline]
def private wto_route_poll(slotIdx : int; now : float; myPos : float3; var slot : WtoBotSlot&)
assume rt = slot.route
var count = 0
var lenM = 0.0
var truncated = false
let status = wto_navq_path_result(slotIdx, rt.ticket, rt.corridor, count, lenM, truncated)
if status == WTO_PATH_PENDING
return
rt.pending = false
rt.lastStatus = status
if (status == WTO_PATH_FULL || status == WTO_PATH_PARTIAL) && count >= 1
wto_route_accept(rt, count, rt.pendingGoal, truncated, WTO_ROUTE_SRC_MESH)
elif status == WTO_PATH_NO_START
wto_route_recover(now, myPos, rt)
elif status == WTO_PATH_NO_GOAL
rt.corridorLen = 0
rt.goalUnreachable = true
rt.unreachableGoal = rt.pendingGoal
rt.noGoalCount++
print("WTO_AI|ROUTE_NO_GOAL|eid={uint(slot.eid)}|tier={rt.tier}|pos={myPos}|goal={rt.pendingGoal}\n")
else
rt.nextReplanAt = now + 1.0
[never_inline]
def private wto_route_needs_plan(now : float; goal : float3; slot : WtoBotSlot const&) : bool
assume rt = slot.route
let moveSq = wto_sq(WTO_AI_PF_REPLAN_GOAL_MOVE_M)
if rt.goalUnreachable && wto_xz_dist_sq(rt.unreachableGoal, goal) <= moveSq
return now >= rt.nextReplanAt
return (rt.corridorLen == 0 || rt.replanRequested || now >= rt.nextReplanAt ||
wto_xz_dist_sq(rt.goal, goal) > moveSq || rt.offTrackM > WTO_AI_PF_OFF_TRACK_REPLAN_M ||
rt.tier != wto_route_tier(slot.spec) || rt.filter != wto_route_filter(slot.spec))
// Per nav tick: collect a finished search, then plan again when the corridor no longer fits.
[never_inline]
def public wto_route_update(navState, slotIdx : int; now : float; myPos, goal : float3; var slot : WtoBotSlot&)
assume rt = slot.route
if rt.pending
wto_route_poll(slotIdx, now, myPos, slot)
if rt.pending && wto_xz_dist_sq(rt.pendingGoal, goal) <= wto_sq(WTO_AI_PF_REPLAN_GOAL_MOVE_M)
return
if wto_route_needs_plan(now, goal, slot)
wto_route_request(navState, slotIdx, now, myPos, goal, slot)
// Bots whose corridor ahead passes near a new obstacle (wreck, rubble) plan again next tick.
[never_inline]
def public wto_route_note_obstacle(pos : float3; radiusM : float; var bots : WtoBotSlot[64]&)
let reachSq = wto_sq(radiusM + 4.0)
for i in range(WTO_MAX_BOTS)
assume rt = bots[i].route
if !bots[i].used || rt.corridorLen < 2
continue
let last = min(rt.corridorLen - 2, rt.segIdx + 8)
for k in range(rt.segIdx, last + 1)
var t = 0.0
if wto_poly_seg_closest(rt.corridor[k], rt.corridor[k + 1], pos, t) <= reachSq
rt.replanRequested = true
break
// A vehicle died at `pos`: later path searches route around its wreck, nearby bots plan again.
[never_inline]
def public wto_route_report_wreck(navState : int; now : float; pos : float3; var bots : WtoBotSlot[64]&)
if navState != WTO_NAVMESH_LOADED
return
wto_navq_add_dynamic(pos, WTO_AI_PF_WRECK_RADIUS_M, WTO_AI_PF_WRECK_COST_MUL, now + WTO_AI_PF_WRECK_TTL_SEC)
wto_route_note_obstacle(pos, WTO_AI_PF_WRECK_RADIUS_M, bots)
+72 -115
View File
@@ -24,17 +24,27 @@ require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_order_common
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_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
require %appGame.wtoai.wto_ai_commander_common
require %appGame.wtoai.wto_ai_perceive_common
require %appGame.wtoai.wto_ai_tactics_common
require %appGame.wtoai.wto_ai_route_common
require %appGame.wtoai.wto_ai_nav_common
require %appGame.wtoai.wto_ai_navmesh_common
require %appGame.wtoai.wto_ai_drive_common
require %appGame.wtoai.wto_ai_fire_common
require %appGame.wtoai.wto_ai_ammo_common
require %appGame.wtoai.wto_ai_diag_common
require %appGame.wtoai.wto_ai_stats_common
require %appGame.wtoai.wto_ai_slots_common
require %appGame.wtoai.wto_ai_threat_common
require %appGame.wtoai.wto_ai_trace_common
var private @safe_when_uninitialized g_world : WtoWorldSnap
var private @safe_when_uninitialized g_crowd : WtoCrowdSummary
@@ -47,6 +57,10 @@ var private g_cmd_dirty : bool = true
var private g_last_zone_ver : int = -1
var private g_fire_budget : int = 0
var private g_next_diag_at : float = 0.0
var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle
var private @safe_when_uninitialized g_stats : WtoBattleStats
var private g_next_trace_at : float = 0.0
var private g_trace_due : bool = false
// Custom ground AI must only run inside a real multiplayer battle. Single-player test
// drives also dispatch tag=server ECS, but their target vehicles must never be taken over.
@@ -61,6 +75,7 @@ def wto_ai_script_init()
[never_inline]
def private wto_reset_runtime()
wto_stats_battle_end(float(get_app().usefulTotalTime), g_stats)
wto_world_reset(g_world)
wto_lanes_reset(g_lanes)
g_crowd = WtoCrowdSummary()
@@ -70,60 +85,22 @@ def private wto_reset_runtime()
g_cmd_dirty = true
g_last_zone_ver = -1
g_next_diag_at = 0.0
for i in range(WTO_MAX_BOTS)
if g_bots[i].drive.routeBOwned
wto_drive_request_control(g_bots[i].eid, 0)
g_bots[i] = WtoBotSlot()
wto_drive_release_all()
[never_inline]
def private wto_find_slot(eid : EntityId) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
for i in range(cap)
if g_bots[i].used && g_bots[i].eid == eid
return i
return -1
[never_inline]
def private wto_acquire_slot(eid : EntityId; army : int; now : float) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
var freeIdx = -1
for i in range(cap)
if g_bots[i].used && g_bots[i].eid == eid
g_bots[i].army = army
g_bots[i].lastSeenAt = now
return i
if !g_bots[i].used && freeIdx < 0
freeIdx = i
if freeIdx >= 0
g_bots[freeIdx] = WtoBotSlot()
g_bots[freeIdx].used = true
g_bots[freeIdx].eid = eid
g_bots[freeIdx].army = army
g_bots[freeIdx].lastSeenAt = now
g_bots[freeIdx].nextTacticsAt = now - 0.01
g_bots[freeIdx].nextNavAt = now - 0.01
g_bots[freeIdx].route.nextReplanAt = now - 0.01
g_cmd_dirty = true
return freeIdx
[never_inline]
def private wto_phys_slot_available() : bool
if WTO_AI_NAV_MAX_PHYS_BOTS <= 0
return false
var count = 0
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && g_bots[i].drive.routeBOwned && !g_bots[i].drive.routeAFallback
count++
if count >= WTO_AI_NAV_MAX_PHYS_BOTS
return false
return true
g_next_trace_at = 0.0
g_trace_due = false
wto_navmesh_battle_reset(g_navmesh)
wto_slots_reset_all(g_bots)
[es(tag=server, on_event=(EventMissionUnload, EventEntityManagerBeforeClear, EventEcsMissionLoaded))]
def wto_ai_mission_reset_es(evt : Event)
wto_reset_runtime()
wto_drive_announce_script_ready()
// Battle loading: read the navigation pack in the background before the first world tick.
[es(tag=server, on_event=EventEcsMissionLoaded)]
def wto_ai_mission_loaded_es(evt : Event)
if wto_any_layer_active() && WTO_AI_LAYER_NAVIGATION
wto_navmesh_prefetch()
[es(tag=server)]
def wto_ai_zone_captured_es(evt : EventZoneCaptured)
if !wto_any_layer_active()
@@ -136,32 +113,17 @@ def wto_ai_zone_captured_es(evt : EventZoneCaptured)
def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef)
let u = unit__ref.unit
if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2)
wto_world_record_death(g_world, eid, int(u.army), u.pos, float(get_app().usefulTotalTime))
let idx = wto_find_slot(eid)
if idx >= 0
if g_bots[idx].drive.routeBOwned
wto_drive_request_control(eid, 0)
g_bots[idx] = WtoBotSlot()
let now = float(get_app().usefulTotalTime)
wto_world_record_death(g_world, eid, int(u.army), u.pos, now)
wto_trace_death(now, eid, int(u.army), u.pos)
wto_route_report_wreck(g_navmesh.state, now, u.pos, g_bots)
if wto_slots_forget(g_bots, eid)
g_cmd_dirty = true
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid
g_bots[i].tactics.engageShotsNoEffect = 0
g_bots[i].tactics.engageNoShotHalts = 0
g_bots[i].tactics.engageTotalHaltSec = 0.0
[es(tag=server, on_disappear, on_event=EventUnitRespawn)]
def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId)
let idx = wto_find_slot(eid)
if idx >= 0
if g_bots[idx].drive.routeBOwned
wto_drive_request_control(eid, 0)
g_bots[idx] = WtoBotSlot()
if wto_slots_forget(g_bots, eid)
g_cmd_dirty = true
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid
g_bots[i].tactics.engageShotsNoEffect = 0
g_bots[i].tactics.engageNoShotHalts = 0
g_bots[i].tactics.engageTotalHaltSec = 0.0
[es(tag=server)]
def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef)
@@ -171,27 +133,9 @@ def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : Uni
let u = unit__ref.unit
if u == null || !offEid || offEid == eid
return
let now = float(get_app().usefulTotalTime)
let vicArmy = int(u.army)
// Outgoing effective damage confirmation for our firing bot (resets stalemate counters).
let offBotIdx = wto_find_slot(offEid)
if offBotIdx >= 0 && g_bots[offBotIdx].army != vicArmy && uint(evt.hpFixed) < uint(evt.prevHpFixed)
assume tac = g_bots[offBotIdx].tactics
if tac.engageTargetEid == eid || g_bots[offBotIdx].perceive.targetEid == eid
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.lastEffectAt = now
// Incoming hit direction cue for our damaged bot (never leaks hidden offender coords).
let idx = wto_find_slot(eid)
if idx < 0
return
let offUnitIdx = wto_world_find_unit(g_world, offEid)
if offUnitIdx >= 0 && g_world.units[offUnitIdx].army == g_bots[idx].army
return
let imp = evt.pos - u.pos
g_bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x)
g_bots[idx].perceive.lastDamagedAt = now
g_bots[idx].perceive.lastOffenderEid = offEid
let hpDropped = uint(evt.hpFixed) < uint(evt.prevHpFixed)
wto_trace_hit(float(get_app().usefulTotalTime), eid, offEid, evt.pos, evt.damage, evt.damageTypeId, hpDropped)
wto_slots_on_damage(g_world, g_bots, eid, offEid, u, evt.pos, hpDropped, float(get_app().usefulTotalTime))
[es(tag=server, before=wto_ai_pipeline_es)]
def wto_ai_world_tick_es(act : UpdateStageInfoAct)
@@ -204,13 +148,14 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct)
let now = float(get_app().usefulTotalTime)
if g_world.valid && now < g_world.time - 1.0
wto_reset_runtime()
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && (now - g_bots[i].lastSeenAt) > 3.5
g_bots[i] = WtoBotSlot()
wto_slots_drop_stale(g_bots, now)
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
wto_crowd_update_all(g_world, g_bots, g_crowd)
let zoneChanged = g_world.zoneVersion != g_last_zone_ver
if zoneChanged
@@ -224,23 +169,27 @@ def wto_ai_world_tick_es(act : UpdateStageInfoAct)
wto_commander_update_all(g_world, now, zoneChanged, g_lanes, g_bots)
elif WTO_AI_LAYER_MACRO && now >= g_next_rally_at
g_next_rally_at = now + 1.0
wto_lanes_update_rallies(g_world, 1, now, g_lanes, g_bots)
wto_lanes_update_rallies(g_world, 2, now, g_lanes, g_bots)
for i in range(WTO_MAX_BOTS)
assume b = g_bots[i]
if b.used && b.order.valid && b.order.rallyHold && b.order.capIndex >= 0
let sk = wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId)
if g_lanes.rallyReleased[sk]
b.order.rallyHold = false
if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0
let ck = wto_lanes_cap_key(b.army, b.order.capIndex)
b.order.routeRelayValid = g_lanes.flankValid[ck * 2 + b.order.laneId - 1]
b.order.routeRelayPos = g_lanes.flankRelay[ck * 2 + b.order.laneId - 1]
else
b.order.routeRelayValid = false
wto_lanes_tick_rallies(g_world, now, g_lanes, g_bots)
if WTO_AI_DIAG_TELEMETRY && now >= g_next_diag_at
g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC
wto_diag_log_telemetry(g_world, now, g_bots, g_crowd)
wto_navmesh_log_stats(g_navmesh)
g_trace_due = wto_trace_tick(g_world, now, g_bots, g_next_trace_at)
wto_stats_tick(now, g_stats)
[es(tag=server, before=wto_ai_pipeline_es)]
def wto_ai_ammo_sample_es(act : UpdateStageInfoAct; eid : EntityId; unit__ref : UnitRef;
ammo_stowage__ammoState : uint; ammo_stowage__ammoTypeRemap : IPoint4List;
ammo_stowage__weaponsIds : IntList; ammo_slots__ammoMaskAndType : UInt32List;
ammo_slots__numAmmo : IPoint2List)
if act.dt <= 0.0 || !g_world.valid || !WTO_AI_LAYER_FIRE_CONTROL
return
let index = wto_slots_find(g_bots, eid)
let u = unit__ref.unit
if index < 0 || u == null || u.weap == null || g_world.time < g_bots[index].nextTacticsAt
return
wto_ammo_sample(u, ammo_stowage__ammoState, ammo_stowage__ammoTypeRemap, ammo_stowage__weaponsIds,
ammo_slots__ammoMaskAndType, ammo_slots__numAmmo, g_bots[index].fire)
[es(tag=server, no_order)]
def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
@@ -256,7 +205,9 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref :
if (army != 1 && army != 2) || gm == null || gm.moveSys == null || as_hv(unit) == null
return
let now = float(get_app().usefulTotalTime)
let idx = wto_acquire_slot(eid, army, now)
var created = false
let idx = wto_slots_acquire(g_bots, eid, army, now, created)
g_cmd_dirty = g_cmd_dirty || created
if idx < 0
return
assume slot = g_bots[idx]
@@ -266,25 +217,31 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref :
if now >= slot.nextTacticsAt
slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC
if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL
wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot)
wto_fire_sample_sight(unit, slot.fire)
wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, slot)
wto_threat_update(g_world, now, unit.pos, slot)
wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd)
wto_fire_update(g_world, unit, unit__className, now, act.dt, slot, g_fire_budget)
if now >= slot.nextNavAt
// A failed pack with navEngine.allowFallback off leaves every bot standing for the battle.
if now >= slot.nextNavAt && g_navmesh.state != WTO_NAVMESH_FAILED
slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC
wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot)
wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot)
wto_stats_bot_frame(g_world, now, act.dt, unit.pos, unit.unitTm[0], slot, g_stats)
if g_trace_due
wto_trace_bot(now, slot)
[es(tag=server, after=wto_ai_pipeline_es)]
def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
unit__missionName : string; var vehicle_net_phys : VehiclePhysActor&)
if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys"
if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys" || g_navmesh.state == WTO_NAVMESH_FAILED
return
var unit = unit__ref.unit
if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null
return
let idx = wto_find_slot(eid)
let idx = wto_slots_find(g_bots, eid)
if idx < 0
return
if !g_bots[idx].drive.routeBOwned && !wto_phys_slot_available()
if !g_bots[idx].drive.routeBOwned && !wto_slots_phys_available(g_bots)
return
let now = float(get_app().usefulTotalTime)
wto_drive_step_phys(unit, unit__missionName, as_gm(unit), vehicle_net_phys, act.dt, now, g_bots[idx])
+19 -5
View File
@@ -116,11 +116,25 @@ def public wto_sight_check_target_samples(world : WtoWorldSnap const&;
pts[3] = tgt.pos - left * sideOff + float3(0.0, 1.25, 0.0)
let count = clamp(maxSamples, 1, 4)
var vis = 0
var picked = false
var sum = float3(0.0, 0.0, 0.0)
var visible : bool[4]
for s in range(count)
if wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, pts[s]) == WTO_BLOCK_NONE
if !picked
outBestPt = pts[s]
picked = true
visible[s] = wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, pts[s]) == WTO_BLOCK_NONE
if visible[s]
sum += pts[s]
vis++
// Aim at the middle of what is visible (decision layer design, 6.2), not at the first visible
// point, which with the hull hidden is the gun mantlet every time.
if vis > 0
outBestPt = sum / float(vis)
if vis > 1 && wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, outBestPt) != WTO_BLOCK_NONE
let center = outBestPt
var bestDist = 1.0e9
for s in range(count)
if !visible[s]
continue
let d = length_sq(pts[s] - center)
if d < bestDist
bestDist = d
outBestPt = pts[s]
return vis
+113
View File
@@ -0,0 +1,113 @@
// Bot slots of the ground AI runtime: finding, acquiring and freeing a bot's slot, the cap on
// bots driven through vehicle physics, and the per-hit bookkeeping of EventUnitDamage.
options indenting = 2
options no_global_heap = true
module wto_ai_slots_common shared
require ecs
require math
require Unit
require %appGame.wtoai.wto_ai_config_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_drive_common
[never_inline]
def public wto_slots_find(bots : WtoBotSlot[64]; eid : EntityId) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
for i in range(cap)
if bots[i].used && bots[i].eid == eid
return i
return -1
// Frees the unit's slot and clears engagement counters aimed at it; true when a slot was freed.
[never_inline]
def public wto_slots_forget(var bots : WtoBotSlot[64]&; eid : EntityId) : bool
let idx = wto_slots_find(bots, eid)
if idx >= 0
if bots[idx].drive.routeBOwned
wto_drive_request_control(eid, 0)
bots[idx] = WtoBotSlot()
for i in range(WTO_MAX_BOTS)
if bots[i].used && bots[i].tactics.engageTargetEid == eid
bots[i].tactics.engageShotsNoEffect = 0
bots[i].tactics.engageNoShotHalts = 0
bots[i].tactics.engageTotalHaltSec = 0.0
return idx >= 0
// The unit's slot, taking a free one for a new unit (then `created` is set); -1 when full.
[never_inline]
def public wto_slots_acquire(var bots : WtoBotSlot[64]&; eid : EntityId; army : int; now : float;
var created : bool&) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
var freeIdx = -1
for i in range(cap)
if bots[i].used && bots[i].eid == eid
bots[i].army = army
bots[i].lastSeenAt = now
return i
if !bots[i].used && freeIdx < 0
freeIdx = i
if freeIdx >= 0
bots[freeIdx] = WtoBotSlot()
bots[freeIdx].used = true
bots[freeIdx].eid = eid
bots[freeIdx].army = army
bots[freeIdx].lastSeenAt = now
bots[freeIdx].nextTacticsAt = now - 0.01
bots[freeIdx].nextNavAt = now - 0.01
bots[freeIdx].route.nextReplanAt = now - 0.01
created = true
return freeIdx
// Releases vehicle control of every bot and clears all slots.
[never_inline]
def public wto_slots_reset_all(var bots : WtoBotSlot[64]&)
for i in range(WTO_MAX_BOTS)
if bots[i].drive.routeBOwned
wto_drive_request_control(bots[i].eid, 0)
bots[i] = WtoBotSlot()
wto_drive_release_all()
// Slots not refreshed by the pipeline for a while belong to units that are gone.
[never_inline]
def public wto_slots_drop_stale(var bots : WtoBotSlot[64]&; now : float)
for i in range(WTO_MAX_BOTS)
if bots[i].used && (now - bots[i].lastSeenAt) > 3.5
bots[i] = WtoBotSlot()
[never_inline]
def public wto_slots_phys_available(bots : WtoBotSlot[64]) : bool
if WTO_AI_NAV_MAX_PHYS_BOTS <= 0
return false
var count = 0
for i in range(WTO_MAX_BOTS)
if bots[i].used && bots[i].drive.routeBOwned && !bots[i].drive.routeAFallback
count++
if count >= WTO_AI_NAV_MAX_PHYS_BOTS
return false
return true
// A hit on `eid` by `offEid`: confirms an effective shot of our firing bot (resetting its stalemate
// counters) and gives our damaged bot the direction it was hit from (never the offender's position).
[never_inline]
def public wto_slots_on_damage(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]&; eid, offEid : EntityId;
u : Unit const?; hitPos : float3; hpDropped : bool; now : float)
let offBotIdx = wto_slots_find(bots, offEid)
if offBotIdx >= 0 && bots[offBotIdx].army != int(u.army) && hpDropped
assume tac = bots[offBotIdx].tactics
if tac.engageTargetEid == eid || bots[offBotIdx].perceive.targetEid == eid
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.lastEffectAt = now
let idx = wto_slots_find(bots, eid)
if idx < 0
return
let offUnitIdx = wto_world_find_unit(world, offEid)
if offUnitIdx >= 0 && world.units[offUnitIdx].army == bots[idx].army
return
let imp = hitPos - u.pos
bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x)
bots[idx].perceive.lastDamagedAt = now
bots[idx].perceive.lastOffenderEid = offEid
+21 -23
View File
@@ -1,6 +1,6 @@
// Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per
// spawned bot (`gamedata/units/<className>.blk`) to extract role, gun stabilizer,
// turret slew rates, shell muzzle velocity, and chassis capabilities.
// turret slew rates, shell muzzle velocity and stock maximum penetration, and chassis capabilities.
options indenting = 2
options no_global_heap = true
module wto_ai_specs_common shared
@@ -15,6 +15,9 @@ require Unit
require IGroundModel
require HeavyVehicleModel
require Weapon
require WTBallistics
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_weapon_profile_common
require %game.utils.utils_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
@@ -35,18 +38,14 @@ def private wto_parse_role_strings(unitType : string; expClass : string; isLight
[never_inline]
def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicleSpec&; isDefault : bool)
let spd = bBlk |> datablock_getReal("speed", 0.0)
if spd <= 80.0 || spd >= 2600.0
var shell = WtoShellProfile()
if !wto_profile_read(bBlk, shell)
return
let cx = clamp(bBlk |> datablock_getReal("Cx", 0.35), 0.05, 1.5)
let mass = clamp(bBlk |> datablock_getReal("mass", 10.0), 0.05, 250.0)
let rawCal = bBlk |> datablock_getReal("ballisticCaliber", 0.0)
let cal = clamp(rawCal > 0.002 ? rawCal : bBlk |> datablock_getReal("caliber", 0.09), 0.005, 0.4)
if isDefault && spec.shellCount == 0
spec.muzzleSpeedMps = spd
spec.shellDragCx = cx
spec.shellMassKg = mass
spec.shellCaliberM = cal
spec.muzzleSpeedMps = shell.speedMps
spec.shellDragCx = shell.dragCx
spec.shellMassKg = shell.massKg
spec.shellCaliberM = shell.caliberM
let bName = bBlk |> datablock_getStr("bulletName", "")
if empty(bName) || spec.shellCount >= WTO_MAX_SHELL_PROFILES
return
@@ -56,28 +55,26 @@ def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicl
return
let idx = spec.shellCount
let bt = bBlk |> datablock_getStr("bulletType", "")
let isSoft = find(bt, "he_frag") >= 0 || find(bt, "hesh") >= 0
let isSoft = find(bt, "he_frag") >= 0 || find(bt, "hesh") >= 0 || find(bt, "he_part") >= 0 || find(bt, "heat") >= 0
let isNonCombat = find(bt, "smoke") >= 0 || find(bt, "practice") >= 0 || find(bt, "shrapnel") >= 0
spec.shells[idx].nameHash = h
spec.shells[idx].speedMps = spd
spec.shells[idx].dragCx = cx
spec.shells[idx].massKg = mass
spec.shells[idx].caliberM = cal
spec.shells[idx].isSoftShell = isSoft
spec.shells[idx].isAntiArmor = !isSoft && !isNonCombat
shell.nameHash = h
shell.isSoftShell = isSoft
shell.isAntiArmor = !isSoft && !isNonCombat || find(bt, "heat") >= 0
shell.penMm = float(calc_max_penetration(bBlk))
spec.shells[idx] = shell
spec.shellCount = idx + 1
[never_inline]
def private wto_parse_weapon_blk(weapBlkPath : string; var spec : WtoVehicleSpec&)
def private wto_parse_weapon_blk(weapBlkPath : string; beltMount : bool; var spec : WtoVehicleSpec&)
if empty(weapBlkPath) || find(weapBlkPath, "dummy_weapon") >= 0
return
datablock_load_cached(weapBlkPath, DataBlockReadFlag.ROBUST) <| $(wBlk)
let isRocket = wBlk |> datablock_getBool("rocketGun", false)
let isCannon = wBlk |> datablock_getBool("cannon", false)
let isBelt = wBlk |> datablock_getBool("isBulletBelt", false)
if isRocket && !isCannon
return
spec.isAutocannonBelt = isBelt
spec.isAutocannon = beltMount || wto_profile_is_automatic(wBlk)
spec.reloadSec = wBlk |> datablock_getReal("reloadTime", 0.0)
spec.shellCount = 0
datablock_for_each_block(wBlk, "bullet") <| $(bBlk)
wto_record_shell_block(bBlk, spec, true)
@@ -128,7 +125,8 @@ def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec :
let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer")
if stabBlk != null
spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false)
wto_parse_weapon_blk(wPath, spec)
let beltMount = weapBlk |> datablock_getBool("isBulletBelt", false)
wto_parse_weapon_blk(wPath, beltMount, spec)
return loaded
[never_inline]
+220
View File
@@ -0,0 +1,220 @@
// Battle statistics for comparing builds (decision layer design, section 12). Cumulative per
// vehicle role and logged as WTO_AI|BATTLE_STATS every statsLogIntervalSec and when the battle
// ends: time from acquiring a target to the first shot at it, time with a target in sight and the
// gun ready split by the last reason a shot was refused, shots by distance band and motion, and a
// sample every statsSampleSec of the nearest enemy in line of sight (known or not, turret error,
// rear facing it). "Known" means discovered: in the bot's threat table.
options indenting = 2
options no_global_heap = true
module wto_ai_stats_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_sight_common
// Arrays of five are indexed by WTO_ROLE_*; bands are within closeRangeM, within midRangeM and
// beyond; denySec is indexed by WTO_DENY_*.
[safe_when_uninitialized]
struct public WtoBattleStats
active : bool = false
nextLogAt : float = 0.0
spotted : int[5]
spotShot : int[5]
spotShotSec : float[5]
spotNoShot : int[5]
windowSec : float[5]
samples : int[5]
unaware : int[5]
turretSamples : int[5]
turretErrSum : float[5]
rearSamples : int[5]
rearExposed : int[5]
shots : int[5]
movingShots : int[5]
bandShots : int[3]
bandMoving : int[3]
denySec : float[14]
acWindowSec : float = 0.0
acShots : int = 0
auxShots : int = 0
def private wto_stats_role(slot : WtoBotSlot const&) : int
return clamp(slot.spec.role, 0, 4)
def private wto_stats_role_name(role : int) : string
if role == WTO_ROLE_LIGHT
return "light"
if role == WTO_ROLE_HEAVY
return "heavy"
if role == WTO_ROLE_TD
return "td"
if role == WTO_ROLE_SPAA
return "spaa"
return "medium"
def private wto_stats_ratio(part, whole : int) : float
return whole > 0 ? float(part) / float(whole) : 0.0
def private wto_stats_band(dist : float) : int
if dist <= WTO_AI_FC_CLOSE_RANGE_M
return 0
return dist <= WTO_AI_FC_MID_RANGE_M ? 1 : 2
// A target acquired (seen clearly) and whether it was shot at before the bot let it go.
[never_inline]
def private wto_stats_spot(now : float; groundTgt : bool; var slot : WtoBotSlot&; var bs : WtoBattleStats&)
assume st = slot.stats
let role = wto_stats_role(slot)
if st.spotPending && slot.fire.shotCount > st.spotShots
st.spotPending = false
bs.spotShot[role]++
bs.spotShotSec[role] += now - st.spotAt
let tgt = slot.perceive.targetEid
if groundTgt && tgt != st.spotEid
if st.spotPending
bs.spotNoShot[role]++
st.spotEid = tgt
st.spotAt = now
st.spotShots = slot.fire.shotCount
st.spotPending = true
bs.spotted[role]++
elif !tgt
if st.spotPending
bs.spotNoShot[role]++
st.spotPending = false
st.spotEid = INVALID_ENTITY_ID
[never_inline]
def private wto_stats_shots(myPos : float3; var slot : WtoBotSlot&; var bs : WtoBattleStats&)
assume st = slot.stats
bs.auxShots += slot.trigger.auxShots - st.lastAuxShots
st.lastAuxShots = slot.trigger.auxShots
let fired = slot.fire.shotCount - st.lastShots
st.lastShots = slot.fire.shotCount
if fired <= 0
return
let role = wto_stats_role(slot)
let band = wto_stats_band(sqrt(wto_xz_dist_sq(myPos, slot.perceive.knownPos)))
bs.shots[role] += fired
bs.bandShots[band] += fired
if abs(slot.drive.lastVFwd) >= WTO_AI_PF_STATIONARY_MPS
bs.movingShots[role] += fired
bs.bandMoving[band] += fired
if slot.spec.isAutocannon
bs.acShots += fired
// A shooting window: a ground target seen clearly within engagement range and the gun ready.
[never_inline]
def private wto_stats_window(dt : float; myPos : float3; groundTgt : bool; slot : WtoBotSlot const&;
var bs : WtoBattleStats&)
// An autocannon is briefly not ready between rounds; that still counts as a window.
let ready = slot.fire.gunReady || slot.spec.isAutocannon
if !groundTgt || !ready || slot.fire.reloading
return
if wto_xz_dist_sq(myPos, slot.perceive.knownPos) > WTO_AI_FC_MAX_RANGE_M * WTO_AI_FC_MAX_RANGE_M
return
bs.windowSec[wto_stats_role(slot)] += dt
bs.denySec[clamp(slot.fire.lastDenyReason, 0, WTO_DENY_COUNT - 1)] += dt
if slot.spec.isAutocannon
bs.acWindowSec += dt
// The nearest enemy ground vehicle within statsSampleRangeM if it is in line of sight, else -1.
[never_inline]
def private wto_stats_nearest_seen(world : WtoWorldSnap const&; myPos : float3; slot : WtoBotSlot const&) : int
var best = -1
var bestDistSq = WTO_AI_STATS_RANGE_M * WTO_AI_STATS_RANGE_M
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army == slot.army
continue
let distSq = wto_xz_dist_sq(myPos, u.pos)
if distSq < bestDistSq
bestDistSq = distSq
best = i
if best < 0
return -1
let eye = myPos + float3(0.0, 2.15, 0.0)
assume enemy = world.units[best]
return wto_sight_visual_clear(world, slot.eid, enemy.eid, eye, enemy.pos + float3(0.0, 1.3, 0.0)) == WTO_BLOCK_NONE ? best : -1
def private wto_stats_knows(slot : WtoBotSlot const&; eid : EntityId) : bool
if slot.perceive.targetEid == eid
return true
for i in range(slot.threat.count)
if slot.threat.entries[i].eid == eid
return true
return false
[never_inline]
def private wto_stats_sample(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3;
var slot : WtoBotSlot&; var bs : WtoBattleStats&)
if now < slot.stats.nextSampleAt
return
slot.stats.nextSampleAt = now + WTO_AI_STATS_SAMPLE_SEC
let idx = wto_stats_nearest_seen(world, myPos, slot)
if idx < 0
return
assume u = world.units[idx]
let role = wto_stats_role(slot)
let fwd = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
let toEnemy = wto_xz_normalize(u.pos - myPos, fwd)
bs.samples[role]++
if !wto_stats_knows(slot, u.eid)
bs.unaware[role]++
if slot.fire.hasBarrelSight
let gunDir = wto_xz_normalize(slot.fire.barrelSight, fwd)
bs.turretSamples[role]++
bs.turretErrSum[role] += acos(clamp(dot(gunDir, toEnemy), -1.0, 1.0)) * WTO_RAD_TO_DEG
if role == WTO_ROLE_MEDIUM || role == WTO_ROLE_HEAVY || role == WTO_ROLE_TD
bs.rearSamples[role]++
if acos(clamp(dot(-fwd, toEnemy), -1.0, 1.0)) * WTO_RAD_TO_DEG <= WTO_AI_STATS_REAR_ARC_DEG * 0.5
bs.rearExposed[role]++
// Per frame and bot, after fire control.
[never_inline]
def public wto_stats_bot_frame(world : WtoWorldSnap const&; now, dt : float; myPos, hullFwd : float3;
var slot : WtoBotSlot&; var bs : WtoBattleStats&)
if !WTO_AI_STATS_ENABLED
return
bs.active = true
let groundTgt = slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir
wto_stats_spot(now, groundTgt, slot, bs)
wto_stats_shots(myPos, slot, bs)
wto_stats_window(dt, myPos, groundTgt, slot, bs)
wto_stats_sample(world, now, myPos, hullFwd, slot, bs)
[never_inline]
def private wto_stats_log_role(now : float; why : string; role : int; bs : WtoBattleStats const&)
let spotAvg = bs.spotShot[role] > 0 ? bs.spotShotSec[role] / float(bs.spotShot[role]) : 0.0
let turretErr = bs.turretSamples[role] > 0 ? bs.turretErrSum[role] / float(bs.turretSamples[role]) : 0.0
print("WTO_AI|BATTLE_STATS|why={why}|t={now}|class={wto_stats_role_name(role)}|spotted={bs.spotted[role]}|spotToShotSec={spotAvg}|spotShot={bs.spotShot[role]}|spotNoShot={bs.spotNoShot[role]}|windowSec={bs.windowSec[role]}|samples={bs.samples[role]}|unaware={wto_stats_ratio(bs.unaware[role], bs.samples[role])}|turretErrDeg={turretErr}|rear={wto_stats_ratio(bs.rearExposed[role], bs.rearSamples[role])}|shots={bs.shots[role]}|moving={wto_stats_ratio(bs.movingShots[role], bs.shots[role])}\n")
[never_inline]
def private wto_stats_log(now : float; why : string; bs : WtoBattleStats const&)
for role in range(5)
if bs.spotted[role] + bs.samples[role] + bs.shots[role] > 0
wto_stats_log_role(now, why, role, bs)
assume d = bs.denySec
print("WTO_AI|BATTLE_STATS_FIRE|why={why}|t={now}|shotsBand={bs.bandShots[0]}/{bs.bandShots[1]}/{bs.bandShots[2]}|movingBand={bs.bandMoving[0]}/{bs.bandMoving[1]}/{bs.bandMoving[2]}|denySec=ok:{d[0]},noTarget:{d[1]},notReady:{d[2]},hitProb:{d[3]},longWindow:{d[4]},aimErr:{d[5]},settle:{d[6]},budget:{d[7]},muzzle:{d[8]},arc:{d[9]},friendly:{d[10]},multiGun:{d[11]},traverse:{d[12]},burstPause:{d[13]}|acWindowSec={bs.acWindowSec}|acShots={bs.acShots}|auxShots={bs.auxShots}\n")
// Per world tick: the cumulative statistics every statsLogIntervalSec.
[never_inline]
def public wto_stats_tick(now : float; var bs : WtoBattleStats&)
if !WTO_AI_STATS_ENABLED || !bs.active
return
if bs.nextLogAt <= 0.0
bs.nextLogAt = now + WTO_AI_STATS_LOG_SEC
elif now >= bs.nextLogAt
bs.nextLogAt = now + WTO_AI_STATS_LOG_SEC
wto_stats_log(now, "periodic", bs)
// Battle over (or a new one loading): the final statistics, then a clean slate.
[never_inline]
def public wto_stats_battle_end(now : float; var bs : WtoBattleStats&)
if WTO_AI_STATS_ENABLED && bs.active
wto_stats_log(now, "end", bs)
bs = WtoBattleStats()
@@ -0,0 +1,53 @@
// Path source for battles without a baked navigation pack (navEngine fallback): the level's stock
// road navmesh, thinned to direction changes. Used only when the battle decided on the fallback.
options indenting = 2
options no_global_heap = true
module wto_ai_stockpath_common shared
require ecs
require math
require pathfinder
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
[never_inline]
def private wto_stock_project(navIdx : int; var pt : float3&) : bool
if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(WTO_AI_NAVMESH_SNAP_M, 64.0, WTO_AI_NAVMESH_SNAP_M))
return true
return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(WTO_AI_NAVMESH_GOAL_SNAP_M, 130.0, WTO_AI_NAVMESH_GOAL_SNAP_M))
// Stock road path from start to goal as at most 96 corners; false when the stock mesh has none.
[never_inline]
def public wto_stock_path(start, goal : float3; var pts : float3[96]&; var count : int&) : bool
count = 0
let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1)
if navIdx < 0
return false
var sPt = start
var gPt = goal
if !wto_stock_project(navIdx, sPt) || !wto_stock_project(navIdx, gPt)
return false
let maxKeep = 95
find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array<float3>#)
let total = length(path)
if total <= 0
return
pts[0] = path[0]
count = 1
let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0
for i in range(1, total)
if count >= maxKeep
break
let prev = pts[count - 1]
var isCorner = false
if i + 1 < total
let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0))
let d1 = wto_xz_normalize(path[i + 1] - path[i], d0)
isCorner = dot(d0, d1) < 0.86
if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq
pts[count] = path[i]
count++
if count < maxKeep && wto_xz_dist_sq(pts[count - 1], path[total - 1]) > 9.0
pts[count] = path[total - 1]
count++
return count >= 2
@@ -1,5 +1,6 @@
// Tactics action handlers: damage retreat & repair (plan 6.1), cover retreat & 3-way reload
// actions, and stalemate detection / reposition unlock.
// Hull channel actions (decision layer design, 7.1): damage retreat & repair (rebuild plan 6.1),
// cover pull-back while reloading, and stalemate detection / reposition. The behaviors in
// wto_ai_tactics_common.das run them.
options indenting = 2
options no_global_heap = true
module wto_ai_tactics_actions_common shared
@@ -12,6 +13,7 @@ require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
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_terrain_common
require %appGame.wtoai.wto_ai_cover_common
@@ -40,24 +42,30 @@ def public wto_friendly_retreat_dir(world : WtoWorldSnap const&; army : int;
return wto_xz_normalize(blended, toSpawn)
return wto_xz_normalize(-threatDir, float3(1.0, 0.0, 0.0))
[never_inline]
def public wto_sm_handle_spaa(world : WtoWorldSnap const&; now : float;
myPos, threatDir : float3; distXZ : float; var slot : WtoBotSlot&) : bool
assume p = slot.perceive
if slot.spec.role != WTO_ROLE_SPAA || !p.hasClearLos || !p.targetEid
return false
if p.targetIsAir
slot.tactics.spaaYieldAir = true
wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot)
return true
if distXZ >= 220.0
return false
let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir)
let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0)
wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot)
return true
[never_inline]
def public wto_sm_handle_disabled_and_repair(world : WtoWorldSnap const&; now : float;
myPos, threatPos, threatDir : float3;
isBurn : bool; repairRemainingSec, distXZ : float;
var slot : WtoBotSlot&) : bool
myPos, threatPos, threatDir : float3;
isBurn : bool; repairRemainingSec, distXZ : float;
var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
assume p = slot.perceive
tac.spaaYieldAir = false
if slot.spec.role == WTO_ROLE_SPAA
if p.hasClearLos && p.targetIsAir && !!p.targetEid
tac.spaaYieldAir = true
wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "spaa_air_engage", distXZ, slot)
return true
if p.hasClearLos && !p.targetIsAir && !!p.targetEid && distXZ < 220.0
let backDir = wto_friendly_retreat_dir(world, slot.army, myPos, threatDir)
let goal = wto_clamp_battle_xz(myPos + backDir * 70.0, world.battleCenter, world.battleRadius, 40.0)
wto_sm_set_state(now, WTO_STATE_DISABLED, goal, slot.spec.vMaxFwd, "spaa_evade_tank", distXZ, slot)
return true
// Engine/tracks broken (cannot move): halt in place and request native repair; gun keeps self-defending.
if tac.immobilized
@@ -115,42 +123,32 @@ def public wto_sm_continue_cover_retreat(world : WtoWorldSnap const&; now : floa
return false
return false
// Reloading under threat: pull back into remembered or nearby cover (6..24 m), backwards when the
// cover lies behind the hull. False when no cover is found.
[never_inline]
def public wto_sm_start_reload_action(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, threatPos, baseGoal : float3;
distXZ, distGoal : float; var slot : WtoBotSlot&) : bool
def public wto_sm_start_cover_retreat(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, threatPos : float3; distXZ : float;
var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
// Option 1: pull back into remembered or nearby cover (6..24m).
var cov = myPos
if wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov)
let toCov = wto_xz_normalize(cov - myPos, -hullFwd)
let behindHull = dot(toCov, hullFwd) < -0.15
tac.retreatTarget = cov
tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC
tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0
let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92)
wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot)
return true
// Option 2: no near cover and offensive/advancing -> zigzag push toward objective.
if wto_order_is_offensive(slot.order.role) || distGoal > 35.0
let toGoal = wto_xz_normalize(baseGoal - myPos, hullFwd)
let zigSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
let ang = zigSign * WTO_AI_SM_RELOAD_ADV_DEG * WTO_DEG_TO_RAD
let zigDir = float3(toGoal.x * cos(ang) - toGoal.z * sin(ang), 0.0, toGoal.x * sin(ang) + toGoal.z * cos(ang))
let zigGoal = wto_clamp_battle_xz(myPos + zigDir * min(distGoal, 48.0), world.battleCenter, world.battleRadius, 35.0)
wto_sm_set_state(now, WTO_STATE_RELOAD_ADVANCE, zigGoal, slot.spec.vMaxFwd * 0.92, "reload_advance", distXZ, slot)
return true
// Option 3: defensive hold with side/rear exposed > 30 deg -> angle hull front +/-15 deg toward threat.
let toThreat = wto_xz_normalize(threatPos - myPos, hullFwd)
let exposureDeg = acos(clamp(dot(hullFwd, toThreat), -1.0, 1.0)) * WTO_RAD_TO_DEG
let hasPivotRoom = slot.nav.frontClearM >= slot.spec.halfLen + 1.5 && slot.nav.rearClearM >= slot.spec.halfLen + 1.2
if exposureDeg > WTO_AI_SM_HULL_ANGLE_TRIG_DEG && hasPivotRoom
let angSign = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
let ang = angSign * WTO_AI_SM_HULL_ANGLE_TGT_DEG * WTO_DEG_TO_RAD
tac.hullAngleDir = float3(toThreat.x * cos(ang) - toThreat.z * sin(ang), 0.0, toThreat.x * sin(ang) + toThreat.z * cos(ang))
wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, "reload_angle_hull", distXZ, slot)
return true
return false
if !wto_cover_pick_candidate(world, now, myPos, threatPos, false, slot, cov)
return false
let toCov = wto_xz_normalize(cov - myPos, -hullFwd)
let behindHull = dot(toCov, hullFwd) < -0.15
tac.retreatTarget = cov
tac.retreatUntil = now + WTO_AI_SM_COVER_RETREAT_SEC
tac.retreatReverse = behindHull && slot.nav.rearClearM > 3.2 && slot.spec.vMaxRev >= 2.0
let spd = tac.retreatReverse ? max(2.2, slot.spec.vMaxRev) : (slot.spec.vMaxFwd * 0.92)
wto_sm_set_state(now, WTO_STATE_RETREAT_COVER, cov, spd, "reload_pullback", distXZ, slot)
return true
// The engagement is stuck: shots without effect, halts without a shot, or too long halted.
def public wto_sm_reposition_stale(now : float; slot : WtoBotSlot const&) : bool
assume tac = slot.tactics
let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2
let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk
let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS
return staleShots || staleHalts || tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC
[never_inline]
def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float;
@@ -169,11 +167,7 @@ def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float;
wto_sm_set_state(now, WTO_STATE_REPOSITION, tac.repositionGoal, slot.spec.vMaxFwd * 0.92, "reposition_move", distXZ, slot)
return true
let shotTimeoutOk = (now - slot.fire.lastShotAt) >= 1.2
let staleShots = tac.engageShotsNoEffect >= WTO_AI_SM_STALE_MISS_SHOTS && shotTimeoutOk
let staleHalts = tac.engageNoShotHalts >= WTO_AI_SM_STALE_NOSHOT_HALTS
let staleTime = tac.engageTotalHaltSec >= WTO_AI_SM_MAX_TOTAL_HALT_SEC
if !staleShots && !staleHalts && !staleTime
if !wto_sm_reposition_stale(now, slot)
return false
let lat = float3(-threatDir.z, 0.0, threatDir.x)
let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
@@ -190,5 +184,5 @@ def public wto_sm_handle_reposition(world : WtoWorldSnap const&; now : float;
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.engageTotalHaltSec = 0.0
wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, staleShots ? "stale_no_effect" : (staleHalts ? "stale_no_shot" : "stale_halt_time"), distXZ, slot)
wto_sm_set_state(now, WTO_STATE_REPOSITION, goal, slot.spec.vMaxFwd * 0.92, "stale_engagement", distXZ, slot)
return true
+113 -117
View File
@@ -1,6 +1,9 @@
// Per-bot hull state machine orchestrator: strict priority arbitration across safety/repair,
// active cover retreat, ridge withdrawal, stalemate reposition, short-halt budget, dispersion,
// 3-way reload actions, and distance-tier x task-order movement/shooting.
// Hull channel (decision layer design, section 7), once per tactics tick: damage/repair and ridge
// withdrawal take over at once; otherwise the behavior chosen by score (wto_ai_behavior_common.das)
// runs as a small action that sets the goal, speed and WTO_STATE_* for navigation. The facing
// constraint is updated here, while navigation decides the direction to follow its corridor.
// A behavior that ends by itself (shot taken, cover reached and reloaded, no cover found) is
// replaced in the same tick.
options indenting = 2
options no_global_heap = true
module wto_ai_tactics_common shared
@@ -11,23 +14,29 @@ require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_fire_speed_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_nav_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_cover_common
require %appGame.wtoai.wto_ai_tactics_actions_common
require %appGame.wtoai.wto_ai_behavior_common
require %appGame.wtoai.wto_ai_facing_common
[never_inline]
def private wto_sm_sync_engagement_counters(dt : float; var slot : WtoBotSlot&)
assume tac = slot.tactics
assume p = slot.perceive
if p.hasClearLos && !!p.targetEid && !p.targetIsAir && tac.engageTargetEid != p.targetEid
tac.engageTargetEid = p.targetEid
tac.movingShotBlockedSince = -100.0
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.engageTotalHaltSec = 0.0
let shots = slot.fire.shotCount - tac.engageObservedShots
tac.engageObservedShots = slot.fire.shotCount
if p.hasClearLos && !!p.targetEid && !p.targetIsAir
if tac.engageTargetEid != p.targetEid
tac.engageTargetEid = p.targetEid
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.engageTotalHaltSec = 0.0
elif shots > 0 && slot.fire.lastShotAt > tac.lastEffectAt
tac.engageShotsNoEffect += shots
if tac.state == WTO_STATE_SHORT_HALT
tac.engageTotalHaltSec += dt
@@ -49,7 +58,7 @@ def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float;
tac.ridgeShotsStart = slot.fire.shotCount
let dwellOver = (now - tac.ridgeEnterAt) >= WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC
let shotsOver = (slot.fire.shotCount - tac.ridgeShotsStart) >= WTO_AI_TERRAIN_RIDGE_MAX_SHOTS
if dwellOver || shotsOver || slot.fire.pitchBlocked
if dwellOver || shotsOver || (slot.fire.pitchBlocked && !slot.fire.hullAimForPitch)
let lat = float3(-backDir.z, 0.0, backDir.x)
let side = (uint(slot.eid) & 1u) == 0u ? 1.0 : -1.0
var anc = myPos + backDir * WTO_AI_NAV_TAC_REV_DIST_M + lat * (side * 16.0)
@@ -63,49 +72,18 @@ def private wto_sm_handle_ridge(world : WtoWorldSnap const&; now : float;
return false
[never_inline]
def private wto_sm_stop_range_allowed(distXZ : float; slot : WtoBotSlot const&) : bool
let maxStop = slot.order.valid ? slot.order.maxStopRangeM : WTO_AI_FC_MAX_RANGE_M
if distXZ > min(maxStop, WTO_AI_FC_MAX_RANGE_M)
return false
return (distXZ <= WTO_AI_FC_LONG_RANGE_M ||
(slot.perceive.goodLosSec >= WTO_AI_FC_LONG_WINDOW_SEC && slot.perceive.visiblePointCount >= 2))
[never_inline]
def private wto_sm_continue_short_halt(now : float; myPos : float3; hasGroundTgt : bool;
distXZ : float; var slot : WtoBotSlot&) : bool
def private wto_tac_disperse(world : WtoWorldSnap const&; now : float; myPos : float3; c : WtoBhvCtx const&;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool
assume tac = slot.tactics
if tac.state != WTO_STATE_SHORT_HALT
return false
if slot.fire.shotCount > tac.haltStartShots || slot.fire.reloading
if slot.fire.shotCount > tac.haltStartShots
tac.engageShotsNoEffect += slot.fire.shotCount - tac.haltStartShots
tac.haltStartShots = slot.fire.shotCount
return false
if !hasGroundTgt || !wto_sm_stop_range_allowed(distXZ, slot)
return false
if (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC
tac.engageNoShotHalts++
tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC
return false
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_continue", distXZ, slot)
return true
[never_inline]
def private wto_sm_handle_dispersion(world : WtoWorldSnap const&; now : float;
myPos, threatDir : float3; distXZ : float;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool
assume tac = slot.tactics
if distXZ <= WTO_AI_FC_CLOSE_RANGE_M
return false
if now < tac.disperseUntil && wto_xz_dist_sq(myPos, tac.disperseGoal) > 25.0
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", distXZ, slot)
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_hold", c.distTarget, slot)
return true
if !slot.crowd.isCrowded
return false
tac.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, threatDir, slot.crowd)
tac.disperseGoal = wto_crowd_pick_disperse_pos(world, slot.army, slot.eid, myPos, c.threatDir, slot.crowd)
tac.disperseUntil = now + WTO_AI_CROWD_DISPERSE_HOLD_SEC
crowdSummary.disperseEvents++
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", distXZ, slot)
wto_sm_set_state(now, WTO_STATE_DISPERSE, tac.disperseGoal, slot.spec.vMaxFwd * 0.85, "disperse_start", c.distTarget, slot)
return true
[never_inline]
@@ -115,93 +93,111 @@ def private wto_sm_march_speed(slot : WtoBotSlot const&; distGoal : float) : flo
let capScale = slot.order.cautious ? 0.78 : 0.98
return distGoal < 24.0 ? min(slot.spec.vMaxFwd * 0.55, 6.0) : (slot.spec.vMaxFwd * capScale)
// Short halt (7.1): stand until the shot leaves, the reload starts, the target is gone or
// stateMachine.shortHaltMaxSec runs out; then a cooldown of shortHaltCooldownSec.
[never_inline]
def private wto_sm_waited_for_moving_shot(now : float; aimReady : bool; var slot : WtoBotSlot&) : bool
def private wto_tac_halt(now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
let deny = slot.fire.lastDenyReason
let blocked = deny == WTO_DENY_SPEED || deny == WTO_DENY_AIM_ERR || deny == WTO_DENY_SETTLE
if tac.state != WTO_STATE_RUN_AND_GUN || !aimReady || !blocked
tac.movingShotBlockedSince = -100.0
if tac.state != WTO_STATE_SHORT_HALT
wto_face_accept_gun(hullFwd, slot)
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_for_shot", c.distTarget, slot)
return true
let shots = slot.fire.shotCount - tac.haltStartShots
let timeout = (now - tac.haltEnterAt) >= WTO_AI_SM_SHORT_HALT_MAX_SEC
if timeout && shots <= 0
tac.engageNoShotHalts++
if shots > 0 || timeout || slot.fire.reloading || !c.hasTarget || !c.stopRangeOk
tac.shortHaltCooldownUntil = now + WTO_AI_SM_SHORT_HALT_COOLDOWN_SEC
return false
if tac.movingShotBlockedSince < tac.stateEnteredAt
tac.movingShotBlockedSince = now
return now - tac.movingShotBlockedSince >= WTO_AI_SM_MOVING_SHOT_WAIT_SEC
wto_face_accept_gun(hullFwd, slot)
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "halt_hold", c.distTarget, slot)
return true
// Engaging on the move (7.1): along the route, as fast as the trigger channel's speed request
// allows; an urgent order keeps behavior.urgentSpeedKeep of the march speed regardless.
[never_inline]
def private wto_tac_engage(now : float; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
let march = wto_sm_march_speed(slot, c.distGoal)
var speed = march
assume tr = slot.trigger
let fresh = (now - tr.wantSpeedAt) <= WTO_AI_TACTICS_TICK_SEC * 3.0
let urgentAdvance = c.urgent && c.distTarget > WTO_AI_PERC_NEAR_AWARE_M
let crossExposed = urgentAdvance && wto_face_side_exposed(slot)
if fresh && tr.targetEid == slot.perceive.targetEid && !crossExposed && tr.wantSpeedMps > WTO_AI_FC_STOP_SPEED_MAX_MPS && tr.wantSpeedMps < march
speed = lerp(tr.wantSpeedMps, march, urgentAdvance ? WTO_AI_BHV_URGENT_SPEED_KEEP : 0.0)
wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, c.baseGoal, speed, "engage", c.distTarget, slot)
return true
[never_inline]
def private wto_sm_handle_combat(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, threatPos, baseGoal : float3;
distXZ, distGoal : float; var slot : WtoBotSlot&) : bool
def private wto_tac_hold(now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
wto_face_accept_gun(hullFwd, slot)
let why = c.holdReason == WTO_HOLD_WATCH ? "watch_last_exit" : (c.holdReason == WTO_HOLD_RALLY ? "rally_wait" : "hold_post")
wto_sm_set_state(now, WTO_STATE_HULL_ANGLE, myPos, 0.0, why, c.distTarget, slot)
return c.holdReason != WTO_HOLD_NONE
[never_inline]
def private wto_tac_cover(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&;
var slot : WtoBotSlot&) : bool
assume tac = slot.tactics
assume fc = slot.fire
let marchSpd = wto_sm_march_speed(slot, distGoal)
if fc.reloading
return wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot)
let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M
let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0
let canHalt = now >= tac.shortHaltCooldownUntil && !tac.repositionActive && wto_sm_stop_range_allowed(distXZ, slot)
let aimReady = (fc.gunReady && fc.aimTargetEid == slot.perceive.targetEid && fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG)
if marchSpd > 0.0 && (close || (distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush))
if wto_sm_waited_for_moving_shot(now, aimReady, slot) && canHalt
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "moving_shot_halt", distXZ, slot)
else
let speed = min(marchSpd, wto_fire_speed_limit_mps(distXZ, slot.spec.vMaxFwd))
wto_sm_set_state(now, WTO_STATE_RUN_AND_GUN, baseGoal, speed, close ? "close_run_gun" : "mid_slow_fire", distXZ, slot)
if tac.state == WTO_STATE_RETREAT_COVER || tac.state == WTO_STATE_COVER_RELOAD
return wto_sm_continue_cover_retreat(world, now, myPos, c.threatPos, c.distTarget, slot)
if wto_sm_start_cover_retreat(world, now, myPos, hullFwd, c.threatPos, c.distTarget, slot)
return true
if !canHalt
return false
if !aimReady
wto_sm_set_state(now, WTO_STATE_PREAIM, baseGoal, marchSpd, "preaim_move", distXZ, slot)
return true
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "short_halt_ready", distXZ, slot)
tac.coverFailedAt = now
return false
[never_inline]
def private wto_tac_advance(now : float; myPos : float3; c : WtoBhvCtx const&; var slot : WtoBotSlot&) : bool
let speed = wto_sm_march_speed(slot, c.distGoal)
wto_sm_set_state(now, WTO_STATE_MARCH, c.atGoal ? myPos : c.baseGoal, speed, "advance", c.distTarget, slot)
return true
// Runs the chosen behavior; false when it has ended or cannot run.
[never_inline]
def private wto_tac_run(world : WtoWorldSnap const&; now : float; myPos, hullFwd : float3; c : WtoBhvCtx const&;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&) : bool
let bhv = slot.tactics.behavior
if bhv == WTO_BHV_ENGAGE
return c.hasTarget && wto_tac_engage(now, c, slot)
if bhv == WTO_BHV_HALT
return wto_tac_halt(now, myPos, hullFwd, c, slot)
if bhv == WTO_BHV_COVER
return wto_tac_cover(world, now, myPos, hullFwd, c, slot)
if bhv == WTO_BHV_REPOSITION
return wto_sm_handle_reposition(world, now, myPos, c.threatDir, c.baseGoal, c.distTarget, slot)
if bhv == WTO_BHV_HOLD
return wto_tac_hold(now, myPos, hullFwd, c, slot)
if bhv == WTO_BHV_DISPERSE
return wto_tac_disperse(world, now, myPos, c, slot, crowdSummary)
if bhv == WTO_BHV_ADVANCE
return wto_tac_advance(now, myPos, c, slot)
return false
[never_inline]
def public wto_tactics_update(world : WtoWorldSnap const&; now, dt : float;
myPos, rawHullFwd : float3; isBurn : bool;
repairRemainingSec : float;
var slot : WtoBotSlot&; var crowdSummary : WtoCrowdSummary&)
let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0))
let baseGoal = slot.order.valid ? slot.order.goalPos : world.battleCenter
let distGoal = sqrt(wto_xz_dist_sq(myPos, baseGoal))
if !WTO_AI_LAYER_TACTICS
wto_sm_set_state(now, WTO_STATE_MARCH, slot.order.valid ? slot.order.goalPos : myPos, slot.spec.vMaxFwd * 0.9, "layer_off", 9999.0, slot)
return
assume p = slot.perceive
let hasGroundTgt = p.hasClearLos && !!p.targetEid && !p.targetIsAir
let distXZ = hasGroundTgt ? sqrt(wto_xz_dist_sq(myPos, p.knownPos)) : 9999.0
let threatPos = !!p.targetEid ? p.knownPos : baseGoal
let threatDir = wto_xz_normalize(threatPos - myPos, hullFwd)
wto_sm_sync_engagement_counters(dt, slot)
wto_face_update(now, myPos, hullFwd, slot)
var c = WtoBhvCtx()
wto_bhv_context(world, now, myPos, hullFwd, wto_sm_reposition_stale(now, slot), slot, c)
wto_cover_update_memory(world, now, myPos, slot)
if wto_sm_handle_disabled_and_repair(world, now, myPos, threatPos, threatDir, isBurn, repairRemainingSec, distXZ, slot)
return
if wto_sm_continue_cover_retreat(world, now, myPos, threatPos, distXZ, slot)
return
if wto_sm_handle_ridge(world, now, myPos, threatDir, distXZ, slot)
return
if wto_sm_handle_reposition(world, now, myPos, threatDir, baseGoal, distXZ, slot)
return
if wto_sm_continue_short_halt(now, myPos, hasGroundTgt, distXZ, slot)
return
if wto_sm_handle_dispersion(world, now, myPos, threatDir, distXZ, slot, crowdSummary)
return
if hasGroundTgt && wto_sm_handle_combat(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot)
return
if slot.fire.reloading && !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
if wto_sm_start_reload_action(world, now, myPos, hullFwd, threatPos, baseGoal, distXZ, distGoal, slot)
return
// Stationary overwatch/defend bots hold their firing post briefly to watch the enemy's last exit point;
// marching/pushing bots keep advancing while the turret watches.
if !hasGroundTgt && now < p.watchUntil && slot.order.urgency != WTO_URGENCY_HIGH && distGoal <= 35.0
wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "watch_last_exit", distXZ, slot)
return
// Hold at the 40% rally staging point until the group launches (unless threatened inside 300 m).
if slot.order.rallyHold && slot.order.routeRelayValid && distXZ > WTO_AI_FC_MID_RANGE_M
let rallyHoldRad = max(18.0, WTO_AI_CMD_RALLY_RADIUS_M * 0.55)
if wto_xz_dist_sq(myPos, slot.order.routeRelayPos) <= rallyHoldRad * rallyHoldRad
wto_sm_set_state(now, WTO_STATE_MARCH, myPos, 0.0, "rally_wait", distXZ, slot)
return
let marchSpd = wto_sm_march_speed(slot, distGoal)
let marchGoal = distGoal <= 8.0 ? myPos : baseGoal
wto_sm_set_state(now, WTO_STATE_MARCH, marchGoal, marchSpd, "march_task", distXZ, slot)
slot.tactics.spaaYieldAir = false
if wto_sm_handle_disabled_and_repair(world, now, myPos, c.threatPos, c.threatDir, isBurn, repairRemainingSec, c.distTarget, slot)
wto_bhv_take_over(now, WTO_BHV_REPAIR, slot)
elif wto_sm_handle_spaa(world, now, myPos, c.threatDir, c.distTarget, slot)
wto_bhv_take_over(now, slot.tactics.spaaYieldAir ? WTO_BHV_HOLD : WTO_BHV_WITHDRAW, slot)
elif wto_sm_handle_ridge(world, now, myPos, c.threatDir, c.distTarget, slot)
wto_bhv_take_over(now, WTO_BHV_WITHDRAW, slot)
else
wto_bhv_choose(now, c, false, slot)
if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary)
wto_bhv_choose(now, c, true, slot)
if !wto_tac_run(world, now, myPos, hullFwd, c, slot, crowdSummary)
wto_bhv_take_over(now, WTO_BHV_ADVANCE, slot)
wto_tac_advance(now, myPos, c, slot)
+77
View File
@@ -0,0 +1,77 @@
// Threats measured by this bot. Near and mid visual contacts can enter before confirmation.
options indenting = 2
options no_global_heap = true
module wto_ai_threat_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
// The enemy's hull points within aimConeDeg of the bot, or it hit the bot within hitMemorySec.
def private wto_threat_aiming(now : float; myPos : float3; u : WtoUnitSnap const&; p : WtoPerceiveState const&) : bool
if p.lastOffenderEid == u.eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC
return true
let toMe = wto_xz_normalize(myPos - u.pos, u.hullFwd)
return dot(u.hullFwd, toMe) >= cos(WTO_AI_THREAT_AIM_CONE_DEG * WTO_DEG_TO_RAD)
def private wto_threat_score(now, dist : float; aiming : bool; eid : EntityId; p : WtoPerceiveState const&) : float
var danger = 1.0 / (1.0 + dist / WTO_AI_THREAT_RANGE_SCALE_M)
if !aiming
danger *= WTO_AI_THREAT_NOT_AIMING_MUL
if p.lastOffenderEid == eid && now - p.lastDamagedAt <= WTO_AI_THREAT_HIT_MEMORY_SEC
danger *= WTO_AI_THREAT_HIT_MUL
return danger
// The same danger model ranks visible targets at every distance.
def public wto_threat_observed_danger(now : float; eye : float3; u : WtoUnitSnap const&; p : WtoPerceiveState const&) : float
let dist = sqrt(wto_xz_dist_sq(eye, u.pos))
return wto_threat_score(now, dist, wto_threat_aiming(now, eye, u, p), u.eid, p)
[never_inline]
def private wto_threat_add(now : float; myPos : float3; u : WtoUnitSnap const&; track : int; var slot : WtoBotSlot&)
assume tt = slot.threat
assume p = slot.perceive
assume e = tt.entries[tt.count]
e.eid = u.eid
e.seesMe = p.expSeenAt[track] >= now
e.seen = e.seesMe && p.expScore[track] >= 0.999
e.pos = p.expPos[track]
e.dist = sqrt(wto_xz_dist_sq(myPos, e.pos))
e.aiming = wto_threat_aiming(now, myPos, u, p)
e.danger = wto_threat_score(now, e.dist, e.aiming, u.eid, p)
if !e.seen
e.danger *= WTO_AI_THREAT_DISCOVERED_MUL
if !e.seesMe
e.danger *= WTO_AI_THREAT_UNSEEN_MUL
if tt.topIdx < 0 || e.danger > tt.entries[tt.topIdx].danger
tt.topIdx = tt.count
if e.seesMe && (tt.topVisibleIdx < 0 || e.danger > tt.entries[tt.topVisibleIdx].danger)
tt.topVisibleIdx = tt.count
tt.count++
// Per perception tick, right after wto_perceive_update.
[never_inline]
def public wto_threat_update(world : WtoWorldSnap const&; now : float; myPos : float3; var slot : WtoBotSlot&)
slot.threat = WtoThreatTable()
assume p = slot.perceive
for k in range(WTO_MAX_EXPOSURE_TRACKS)
if !p.expEids[k]
continue
let awareness = max(WTO_AI_PERC_NEAR_AWARE_M, WTO_AI_PERC_MID_AWARE_M)
let fresh = p.expSeenAt[k] >= now && wto_xz_dist_sq(myPos, p.expPos[k]) <= wto_sq(awareness)
if p.expScore[k] < WTO_AI_PERC_DISCOVER_SCORE && !fresh
continue
let uIdx = wto_world_find_unit(world, p.expEids[k])
if uIdx >= 0 && world.units[uIdx].isAlive && !world.units[uIdx].isAir
wto_threat_add(now, myPos, world.units[uIdx], k, slot)
// Danger of `eid` in the bot's table; 0 when it is not there.
def public wto_threat_danger_of(slot : WtoBotSlot const&; eid : EntityId) : float
for i in range(slot.threat.count)
if slot.threat.entries[i].eid == eid
return slot.threat.entries[i].danger
return 0.0
+98
View File
@@ -0,0 +1,98 @@
// 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 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.
// The simulator writes the same lines, so this module uses no engine module.
options indenting = 2
options no_global_heap = true
module wto_ai_trace_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
def private wto_tr_m(v : float) : int
return int(floor(v + 0.5))
def private wto_tr_yaw(dir : float3) : int
return int(floor(atan2(dir.z, dir.x) * WTO_RAD_TO_DEG + 0.5))
def private wto_tr_b(flag : bool) : int
return flag ? 1 : 0
def private wto_tr_is_bot(bots : WtoBotSlot[64] const&; eid : EntityId) : int
for i in range(WTO_MAX_BOTS)
if bots[i].used && bots[i].eid == eid
return 1
return 0
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_trace_is_due(now, nextAt)
return false
nextAt = now + WTO_AI_TRACE_SEC
for c in range(world.capCount)
assume z = world.caps[c]
print("WTO_AI|TRACE_CAP|t={now}|idx={c}|x={wto_tr_m(z.center.x)}|z={wto_tr_m(z.center.z)}|r={wto_tr_m(z.radius)}|owner={z.ownerArmy}|prog={z.progress}\n")
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isGround
continue
let bot = wto_tr_is_bot(bots, u.eid)
// 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
return idx >= 0 && idx < slot.threat.count ? uint(slot.threat.entries[idx].eid) : 0u
// The thing the turret aims at: the engaged target or the threat it looks at; 0 otherwise.
def private wto_tr_look_eid(slot : WtoBotSlot const&) : uint
let why = slot.turret.lookReason
if why == WTO_LOOK_ENGAGE
return uint(slot.perceive.targetEid)
if why == WTO_LOOK_THREAT
return uint(slot.turret.lookEid)
return 0u
[never_inline]
def public wto_trace_bot(now : float; slot : WtoBotSlot const&)
assume o = slot.order
assume tac = slot.tactics
assume p = slot.perceive
assume tr = slot.trigger
let gx = o.valid ? wto_tr_m(o.goalPos.x) : 0
let gz = o.valid ? wto_tr_m(o.goalPos.z) : 0
let gun = slot.fire.hasBarrelSight ? wto_tr_yaw(slot.fire.barrelSight) : 9999
let topEid = wto_tr_threat_eid(slot, slot.threat.topIdx)
let topVis = wto_tr_threat_eid(slot, slot.threat.topVisibleIdx)
print("WTO_AI|TRACE_B|t={now}|eid={uint(slot.eid)}|cls={slot.spec.role}|ord={wto_tr_b(o.valid)}|cmd={o.role}|urg={o.urgency}|cap={o.capIndex}|lane={o.laneId}|gx={gx}|gz={gz}|bhv={tac.behavior}|bs={tac.behaviorScore}|st={tac.state}|wantV={tac.desiredSpeedMps}|vf={slot.drive.lastVFwd}|rev={wto_tr_b(tac.reverseTravel)}|tgt={uint(p.targetEid)}|los={wto_tr_b(p.hasClearLos)}|threats={slot.threat.count}|top={topEid}|topVis={topVis}|look={wto_tr_look_eid(slot)}|why={slot.turret.lookReason}|wish={wto_tr_yaw(slot.turret.wishDir)}|gun={gun}|ready={wto_tr_b(slot.fire.gunReady)}|reload={wto_tr_b(slot.fire.reloading)}|deny={slot.fire.lastDenyReason}|p={tr.hitProb}|thr={tr.threshold}|reqV={tr.wantSpeedMps}\n")
// Part damage on any unit with its offender, so the viewer can draw who hit whom and the last
// offender before a death. `dropped` tells whether the part lost hit points.
def public wto_trace_hit(now : float; victim, offender : EntityId; pos : float3; damage : float; damageType : int; dropped : bool)
if WTO_AI_TRACE_ENABLED
print("WTO_AI|HIT|t={now}|eid={uint(victim)}|off={uint(offender)}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}|dmg={damage}|type={damageType}|drop={wto_tr_b(dropped)}\n")
def public wto_trace_death(now : float; eid : EntityId; army : int; pos : float3)
if WTO_AI_TRACE_ENABLED
print("WTO_AI|DEATH|t={now}|eid={uint(eid)}|army={army}|x={wto_tr_m(pos.x)}|z={wto_tr_m(pos.z)}\n")
+244
View File
@@ -0,0 +1,244 @@
// Vehicles and wrecks on the path: what the baked mesh cannot know. Distances use each hull's
// length and width along the bot's heading, not a circle. A vehicle slower than stationarySpeedMps,
// a wreck or a parked player is an obstacle whatever its size: the bot passes it on the side where
// the mesh leaves room for its hull, or stops short and, after blockWaitSec, marks it for path
// searches and plans again. Moving traffic ahead is followed at its speed; oncoming traffic is
// passed in the open, and in narrow passages the bigger vehicle goes first.
options indenting = 2
options no_global_heap = true
module wto_ai_traffic_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_nav_types_common
require %appGame.wtoai.wto_ai_navquery_common
require %appGame.wtoai.wto_ai_navmesh_common
require %appGame.wtoai.wto_ai_traffic_geometry_common
require %appGame.wtoai.wto_ai_math_common
// The nearest standing body (stopped vehicle or wreck) in the bot's lane within `lookM`.
[never_inline]
def private wto_traffic_find_standing(world : WtoWorldSnap const&; myPos, dir : float3; lookM : float;
slot : WtoBotSlot const&; var best : WtoTrafficBody&) : bool
var maxGap = lookM
var found = false
var body = WtoTrafficBody()
for i in range(world.unitCount)
assume u = world.units[i]
let flatVel = float3(u.vel.x, 0.0, u.vel.z)
if !u.isAlive || !u.isGround || u.eid == slot.eid || length(flatVel) >= WTO_AI_PF_STATIONARY_MPS
continue
wto_traffic_frame(myPos, dir, u.pos, flatVel, u.hullFwd, u.halfLen, u.halfWid, body)
if wto_traffic_in_lane(body, slot.spec, maxGap)
maxGap = wto_traffic_gap(body, slot.spec)
body.idx = i
body.isWreck = false
best = body
found = true
let still = float3(0.0, 0.0, 0.0)
for w in range(world.wreckCount)
assume wr = world.wrecks[w]
wto_traffic_frame(myPos, dir, wr.pos, still, wr.hullFwd, wr.halfLen, wr.halfWid, body)
if wto_traffic_in_lane(body, slot.spec, maxGap)
maxGap = wto_traffic_gap(body, slot.spec)
body.idx = w
body.isWreck = true
best = body
found = true
return found
// Whether a moving body and the bot come within passing distance in the next trafficTtcSec.
[never_inline]
def private wto_traffic_meets(dir : float3; speedMps : float; body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : bool
let left = float3(-dir.z, 0.0, dir.x)
let closeAlong = dot(body.vel, dir) - speedMps
let closeLat = dot(body.vel, left)
let need = wto_traffic_need(body, spec)
let reach = spec.halfLen + body.extAlong + WTO_AI_PF_PASS_MARGIN_M
for k in range(5)
let t = WTO_AI_PF_TRAFFIC_TTC_SEC * float(k) * 0.25
if abs(body.lat + closeLat * t) < need && abs(body.along + closeAlong * t) < reach
return true
return false
// Moving vehicles: one ahead in the lane going the same way caps the speed so the bot can still
// stop behind it; the nearest one the bot would meet is returned in `oncoming`.
[never_inline]
def private wto_traffic_moving(world : WtoWorldSnap const&; myPos, dir : float3; speedMps : float;
var slot : WtoBotSlot&; var oncoming : WtoTrafficBody&) : bool
let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC)
var nearest = 99999.0
var body = WtoTrafficBody()
for i in range(world.unitCount)
assume u = world.units[i]
let flatVel = float3(u.vel.x, 0.0, u.vel.z)
let speed = length(flatVel)
if !u.isAlive || !u.isGround || u.eid == slot.eid || speed < WTO_AI_PF_STATIONARY_MPS
continue
wto_traffic_frame(myPos, dir, u.pos, flatVel, u.hullFwd, u.halfLen, u.halfWid, body)
let ahead = dot(flatVel, dir)
if ahead > 0.7 * speed
if wto_traffic_in_lane(body, slot.spec, lookM)
let room = max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_BUMPER_STOP_M)
slot.nav.avoidSpeedCap = min(slot.nav.avoidSpeedCap, ahead + sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * room))
continue
if body.along > 0.0 && body.along < nearest && wto_traffic_meets(dir, speedMps, body, slot.spec)
nearest = body.along
body.idx = i
oncoming = body
return nearest < 99990.0
// Side room for the hull: the mesh must allow the straight line to the passing point.
[never_inline]
def private wto_traffic_room(world : WtoWorldSnap const&; navState : int; fromPos, toPos : float3; slot : WtoBotSlot const&) : bool
let delta = toPos - fromPos
let dist = wto_xz_len(delta)
if dist <= 0.1
return true
let dir = wto_xz_normalize(delta, float3(1.0, 0.0, 0.0))
var body = WtoTrafficBody()
if wto_traffic_find_standing(world, fromPos, dir, dist, slot, body)
return false
if navState != WTO_NAVMESH_LOADED || slot.route.tier < 0
return true
var frac = 0.0
return wto_navq_raycast(slot.route.tier, slot.route.filter, fromPos, toPos, frac) != 0
// A stationary obstruction must be passed in two legs: get to its side before the near end,
// then drive past its far end. Keeping those points prevents a premature return to the path.
[never_inline]
def private wto_traffic_pass(world : WtoWorldSnap const&; navState : int; now : float; myPos, dir : float3; body : WtoTrafficBody const&;
persistent : bool; var slot : WtoBotSlot&) : bool
assume nav = slot.nav
let left = float3(-dir.z, 0.0, dir.x)
let need = wto_traffic_need(body, slot.spec)
var side = abs(body.lat + need) <= abs(body.lat - need) ? 1.0 : -1.0
if now < nav.avoidSideUntil && nav.avoidSide != 0.0
side = nav.avoidSide
let front = max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_BUMPER_STOP_M)
let back = body.along + body.extAlong + slot.spec.halfLen + WTO_AI_PF_BUMPER_STOP_M
for _i in range(2)
let lateral = left * (body.lat + side * (need + WTO_AI_PF_PASS_MARGIN_M))
let entry = myPos + dir * front + lateral
let exit = myPos + dir * back + lateral
if wto_traffic_room(world, navState, myPos, entry, slot) && wto_traffic_room(world, navState, entry, exit, slot)
nav.avoidActive = true
nav.avoidTarget = entry
nav.avoidSide = side
nav.avoidSideUntil = now + WTO_AI_PF_BLOCK_WAIT_SEC
nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS)
if persistent
nav.passEntry = entry
nav.passExit = exit
nav.passAtSide = false
nav.passUntil = now + WTO_AI_PF_BLOCK_TTL_SEC + max(0.0, back) / WTO_AI_PF_PASS_SPEED_MPS
return true
side = -side
return false
[never_inline]
def private wto_traffic_follow_pass(now : float; myPos, routeDir : float3; var nav : WtoNavState&) : bool
if now >= nav.passUntil
return false
let along = wto_xz_normalize(nav.passExit - nav.passEntry, routeDir)
let marginSq = wto_sq(WTO_AI_PF_PASS_MARGIN_M)
if dot(along, routeDir) < 0.0 || wto_xz_dist_sq(myPos, nav.passExit) <= marginSq || dot(myPos - nav.passExit, along) >= 0.0
nav.passUntil = -100.0
return false
if wto_xz_dist_sq(myPos, nav.passEntry) <= marginSq
nav.passAtSide = true
nav.avoidActive = true
nav.avoidTarget = nav.passAtSide ? nav.passExit : nav.passEntry
nav.avoidSpeedCap = min(nav.avoidSpeedCap, WTO_AI_PF_PASS_SPEED_MPS)
return true
// No way past: stop short; after blockWaitSec mark the body for path searches and plan again.
[never_inline]
def private wto_traffic_blocked(navState : int; now : float; body : WtoTrafficBody const&; var slot : WtoBotSlot&)
assume nav = slot.nav
nav.avoidSpeedCap = min(nav.avoidSpeedCap, max(0.0, wto_traffic_gap(body, slot.spec) - WTO_AI_PF_CONTACT_GAP_M))
if nav.blockedSince < -50.0
nav.blockedSince = now
return
if now - nav.blockedSince < WTO_AI_PF_BLOCK_WAIT_SEC
return
nav.blockedSince = -100.0
nav.blockEvents++
if navState == WTO_NAVMESH_LOADED
wto_navq_add_dynamic(body.pos, wto_traffic_need(body, slot.spec), WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_BLOCK_TTL_SEC)
slot.route.replanRequested = true
print("WTO_AI|NAV_BLOCKED_BY|eid={uint(slot.eid)}|wreck={body.isWreck}|pos={body.pos}\n")
// The bigger vehicle goes first; equal sizes by entity id. Players always keep their way.
[never_inline]
def private wto_traffic_has_priority(slot : WtoBotSlot const&; other : WtoUnitSnap const&) : bool
if other.isHuman
return false
let mine = slot.spec.halfLen * slot.spec.halfWid
let theirs = other.halfLen * other.halfWid
if abs(mine - theirs) > 0.5
return mine > theirs
return uint(slot.eid) < uint(other.eid)
// Waits for the vehicle with priority, at most yieldWaitMaxSec, then not again for as long.
[never_inline]
def private wto_traffic_yield(now : float; var nav : WtoNavState&)
if nav.yieldUntil < now && now >= nav.yieldCooldownUntil
nav.yieldUntil = now + WTO_AI_PF_YIELD_WAIT_SEC
nav.yieldCooldownUntil = nav.yieldUntil + WTO_AI_PF_YIELD_WAIT_SEC
nav.avoidSpeedCap = min(nav.avoidSpeedCap, now < nav.yieldUntil ? 0.0 : WTO_AI_PF_PASS_SPEED_MPS)
// Hull pressed against a standing body: when that started (cleared once there is room again),
// and where the body is and how much room passing it takes, for marking it on repeats.
[never_inline]
def private wto_traffic_contact(now, speedMps : float; body : WtoTrafficBody const&; var slot : WtoBotSlot&)
assume nav = slot.nav
if wto_traffic_gap(body, slot.spec) >= WTO_AI_PF_CONTACT_GAP_M || speedMps >= WTO_AI_PF_STATIONARY_MPS
nav.contactSince = -100.0
return
if nav.contactSince < -50.0
nav.contactSince = now
nav.contactBodyPos = body.pos
nav.contactBodyRadiusM = wto_traffic_need(body, slot.spec)
// True after contactReverseSec pressed against a vehicle or wreck: the caller backs off at once.
[never_inline]
def public wto_traffic_in_contact(now : float; nav : WtoNavState const&) : bool
return nav.contactSince > -50.0 && now - nav.contactSince >= WTO_AI_PF_CONTACT_REVERSE_SEC
// Per nav tick: sets slot.nav.avoidActive / avoidTarget (a point beside an obstacle to steer at)
// and avoidSpeedCap for the bot heading along `dir` on its path.
[never_inline]
def public wto_traffic_update(world : WtoWorldSnap const&; navState : int; now : float; myPos, dir : float3;
speedMps : float; narrow : bool; var slot : WtoBotSlot&)
assume nav = slot.nav
nav.avoidActive = false
nav.avoidSpeedCap = 99.0
var oncoming = WtoTrafficBody()
let meets = wto_traffic_moving(world, myPos, dir, speedMps, slot, oncoming)
var standing = WtoTrafficBody()
let lookM = max(WTO_AI_PF_BUMPER_RAY_M, speedMps * WTO_AI_PF_TRAFFIC_TTC_SEC)
let blockedAhead = wto_traffic_find_standing(world, myPos, dir, lookM, slot, standing)
if blockedAhead
wto_traffic_contact(now, speedMps, standing, slot)
else
nav.contactSince = -100.0
if wto_traffic_follow_pass(now, myPos, dir, nav)
return
if blockedAhead
if !wto_traffic_pass(world, navState, now, myPos, dir, standing, true, slot)
wto_traffic_blocked(navState, now, standing, slot)
return
nav.blockedSince = -100.0
if !meets
nav.yieldUntil = -100.0
return
if !narrow
if !wto_traffic_pass(world, navState, now, myPos, dir, oncoming, false, slot)
wto_traffic_yield(now, nav)
return
if !wto_traffic_has_priority(slot, world.units[oncoming.idx])
wto_traffic_yield(now, nav)
@@ -0,0 +1,97 @@
// Shared hull projections for route traffic, speed caps, and forward and rear clearance.
options indenting = 2
options no_global_heap = true
module wto_ai_traffic_geometry_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_types_common
// A vehicle or wreck seen from the bot: how far ahead (along) and to the left (lat) its centre is,
// and the half extents of its hull along and across the bot's heading.
[safe_when_uninitialized]
struct public WtoTrafficBody
idx : int = -1
isWreck : bool = false
pos : float3 = float3(0.0, 0.0, 0.0)
vel : float3 = float3(0.0, 0.0, 0.0)
along : float = 0.0
lat : float = 0.0
extAlong : float = 0.0
extLat : float = 0.0
[never_inline]
def public wto_traffic_frame(myPos, dir, pos, vel, fwd : float3; halfLen, halfWid : float; var body : WtoTrafficBody&)
let left = float3(-dir.z, 0.0, dir.x)
let rel = float3(pos.x - myPos.x, 0.0, pos.z - myPos.z)
let fd = abs(dot(fwd, dir))
let fl = abs(dot(fwd, left))
body.pos = pos
body.vel = vel
body.along = dot(rel, dir)
body.lat = dot(rel, left)
body.extAlong = halfLen * fd + halfWid * fl
body.extLat = halfLen * fl + halfWid * fd
// Free distance from the bot's front to the body's near end; negative once they overlap.
[never_inline]
def public wto_traffic_gap(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float
return body.along - spec.halfLen - body.extAlong
// Sideways distance between the centres that lets the hulls pass with passMarginM between them.
[never_inline]
def public wto_traffic_need(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&) : float
return spec.halfWid + body.extLat + WTO_AI_PF_PASS_MARGIN_M
[never_inline]
def public wto_traffic_in_lane(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&; maxGap : float) : bool
return body.along > 0.0 && abs(body.lat) < wto_traffic_need(body, spec) && wto_traffic_gap(body, spec) < maxGap
[safe_when_uninitialized]
struct public WtoTrafficClearance
frontM : float = 99.0
rearM : float = 99.0
frontSpeed : float = 0.0
rearSpeed : float = 0.0
def private wto_traffic_clip(body : WtoTrafficBody const&; spec : WtoVehicleSpec const&;
hullDir : float3; var clearance : WtoTrafficClearance&)
if abs(body.lat) >= wto_traffic_need(body, spec)
return
let edge = max(0.0, abs(body.along) - body.extAlong)
if body.along >= 0.0 && edge < clearance.frontM
clearance.frontM = edge
clearance.frontSpeed = dot(body.vel, hullDir)
elif body.along < 0.0 && edge < clearance.rearM
clearance.rearM = edge
clearance.rearSpeed = -dot(body.vel, hullDir)
// Project both ends of the current hull against living vehicles of either team and wrecks.
[never_inline]
def public wto_traffic_clearance(world : WtoWorldSnap const&; myPos, hullDir : float3;
slot : WtoBotSlot const&; var clear : WtoTrafficClearance&)
var body = WtoTrafficBody()
for i in range(world.unitCount)
assume u = world.units[i]
if u.eid == slot.eid || !u.isGround || !u.isAlive
continue
wto_traffic_frame(myPos, hullDir, u.pos, u.vel, u.hullFwd, u.halfLen, u.halfWid, body)
wto_traffic_clip(body, slot.spec, hullDir, clear)
let still = float3(0.0, 0.0, 0.0)
for i in range(world.wreckCount)
assume w = world.wrecks[i]
if w.eid == slot.eid
continue
wto_traffic_frame(myPos, hullDir, w.pos, still, w.hullFwd, w.halfLen, w.halfWid, body)
wto_traffic_clip(body, slot.spec, hullDir, clear)
def public wto_traffic_brake_speed(edgeM, neighborSpeed, currentSpeed, halfLen : float) : float
if edgeM >= 99.0
return 99.0
let room = edgeM - halfLen - WTO_AI_PF_BUMPER_STOP_M
if room <= 0.0
return 0.0
let closing = max(0.0, currentSpeed - neighborSpeed)
let remaining = max(0.0, room - closing * WTO_AI_NAV_TICK_SEC)
return max(0.0, neighborSpeed + sqrt(2.0 * WTO_AI_PF_BRAKE_DECEL * remaining))
+59 -45
View File
@@ -23,11 +23,11 @@ let private WTO_FIRST_GUNNER_TRIGGER = int(0x13)
def public wto_unit_model_path(className : string) : string
return find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk")
def private wto_valid_angle_range(angles : float2) : bool
def public wto_valid_angle_range(angles : float2) : bool
return wto_is_finite(angles.x) && wto_is_finite(angles.y) && angles.x <= angles.y
[never_inline]
def private wto_read_gunner_mount(className : string; triggerNo, weaponIndex : int;
def public wto_read_gunner_mount(className : string; triggerNo, weaponIndex : int;
readMount : block<(mount : DataBlock) : void>)
if empty(className) || triggerNo < WTO_FIRST_GUNNER_TRIGGER || weaponIndex < 0
return
@@ -40,7 +40,7 @@ def private wto_read_gunner_mount(className : string; triggerNo, weaponIndex : i
datablock_for_each_block(*common, "Weapon") <| $(mount)
if (mount |> datablock_getStr("trigger", "")) != trigger
return
if index == weaponIndex && (mount |> datablock_getStr("triggerGroup", "primary")) == "primary"
if index == weaponIndex
invoke(readMount, mount)
index++
@@ -62,15 +62,15 @@ def private wto_load_gun_traverse(className : string; triggerNo, weaponIndex : i
let sectors = mount |> datablock_get_block_by_name("limitsTable")
traverse.hasPitchTable = sectors != null && sectors.paramCount > 0u
def private wto_full_gun_traverse(yaw : float2) : bool
def public wto_full_gun_traverse(yaw : float2) : bool
return yaw.y - yaw.x >= 360.0
def private wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float
def public wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float
let center = (arc.x + arc.y) * 0.5
return center + wto_wrap_deg(yaw - center)
[never_inline]
def private wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float;
def public wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float;
var traverse : WtoGunTraverse&) : float2
if !traverse.hasPitchTable
return traverse.pitch
@@ -115,7 +115,7 @@ def public wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3;
outPitchDeg = atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG
[never_inline]
def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3
def public wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3
let yr = yawDeg * WTO_DEG_TO_RAD
let pr = pitchDeg * WTO_DEG_TO_RAD
let cp = cos(pr)
@@ -123,18 +123,28 @@ def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hul
let l = length(dir)
return l > 1.0e-5 ? (dir / l) : hullFwd
def private wto_step_mounted_yaw(current, desired, step : float; arc : float2) : float
if wto_full_gun_traverse(arc)
return wto_wrap_deg(current + clamp(wto_wrap_deg(desired - current), -step, step))
let clampedCurrent = clamp(wto_yaw_in_mount_coordinates(current, arc), arc.x, arc.y)
let clampedTarget = clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y)
return clamp(clampedCurrent + clamp(clampedTarget - clampedCurrent, -step, step), arc.x, arc.y)
// A full-traverse command never leads the turret by more than this, so the stock servo always
// takes the short way round; any value below 180 keeps that, it does not set the speed.
let private WTO_SERVO_MAX_LEAD_DEG = 90.0
def private wto_track_blocked_pitch(wishPitchDeg, dtStep : float; var slot : WtoBotSlot&)
// Yaw command for the stock servo: the wished yaw itself, inside the mount's arc. The servo then
// turns at the vehicle's own traverse speed instead of being led one frame's step at a time.
def private wto_servo_yaw(current, desired : float; arc : float2) : float
if wto_full_gun_traverse(arc)
let lead = clamp(wto_wrap_deg(desired - current), -WTO_SERVO_MAX_LEAD_DEG, WTO_SERVO_MAX_LEAD_DEG)
return wto_wrap_deg(current + lead)
return clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y)
// `atYaw` is where the barrel points now: elevation counts as blocked only once it is there.
def private wto_track_blocked_pitch(wishPitch, wishYaw, atYaw, dtStep : float; pitch : float2; var slot : WtoBotSlot&)
assume fc = slot.fire
let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep
fc.prevPitchDeg = fc.curPitchDeg
if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8
let align = WTO_AI_FC_BASE_ALIGN_DEG
let aimedYaw = abs(wto_wrap_deg(atYaw - wishYaw)) <= align
let outside = wishPitch < pitch.x - align || wishPitch > pitch.y + align
fc.pitchAtLimit = aimedYaw && wto_valid_angle_range(pitch) && outside
if slot.perceive.hasClearLos && fc.pitchAtLimit && pitchSpd < 0.8
fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep)
fc.pitchBlocked = fc.pitchClampSec >= 0.75
else
@@ -147,6 +157,7 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa
wishYawDeg, wishPitchDeg : float; var slot : WtoBotSlot&)
assume fc = slot.fire
let dtStep = clamp(dt, 0.005, 0.12)
fc.pitchAtLimit = false
if fc.traverseTurretNo != fc.turretNo
fc.traverseTurretNo = fc.turretNo
fc.traverse = WtoGunTraverse()
@@ -166,37 +177,40 @@ def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : floa
fc.curPitchDeg = turret.currentState.pitch
if !fc.traverse.known
return
wto_track_blocked_pitch(wishPitchDeg, dtStep, slot)
let yaw = fc.traverse.yaw
let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep
let cmdYaw = wto_step_mounted_yaw(fc.curYawDeg, wishYawDeg, maxYawStep, yaw)
let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep
let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, fc.traverse)
turret.yawLim = cmdYaw
// Elevation limits where the barrel is now; they change by sector as the turret turns.
let hereYaw = wto_yaw_in_mount_coordinates(fc.curYawDeg, yaw)
let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, hereYaw, fc.traverse)
wto_track_blocked_pitch(wishPitchDeg, wishYawDeg, fc.curYawDeg, dtStep, pitch, slot)
turret.yawLim = wto_servo_yaw(fc.curYawDeg, wishYawDeg, yaw)
if pitch.x <= pitch.y
let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep)
turret.pitchLim = clamp(fc.curPitchDeg + pitchDelta, pitch.x, pitch.y)
turret.pitchLim = clamp(wishPitchDeg, pitch.x, pitch.y)
break
if fc.traverse.known
var uPos = unit.pos
updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos)
def public wto_set_hull_aim(unit : Unit const?; active : bool; wishYaw : float; liveBarrelDir : float3;
var slot : WtoBotSlot&)
assume fc = slot.fire
var target = INVALID_ENTITY_ID
if active
var arc = fc.traverse.yaw
if !fc.traverse.known
var fixedYaw, pitch : float
wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, pitch)
arc = float2(fixedYaw, fixedYaw)
let aimYaw = wto_yaw_in_mount_coordinates(wishYaw, arc)
let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0
if !wto_full_gun_traverse(arc) && (aimYaw < arc.x - tolerance || aimYaw > arc.y + tolerance)
target = slot.perceive.targetEid
let yawToTurn = wto_wrap_deg(wishYaw - (arc.x + arc.y) * 0.5)
fc.hullAimDir = wto_hull_deg_to_world(yawToTurn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2])
if target != fc.hullAimTarget
slot.nextNavAt = 0.0
fc.hullAimTarget = target
// Secondary mounts with their own limits can track independently. Coaxial mounts with no
// limits follow the main turret through the stock weapon animation.
[never_inline]
def public wto_aim_aux_mount(var unit : Unit?; className : string; turretNo : int;
wishDir : float3; var cached : WtoMountFire&) : bool
assume turret = unit.weap.turret[turretNo]
let triggerNo = int(turret.triggerNo)
let weaponIndex = int(turret.weaponIndex)
if !cached.traverseReady
wto_load_gun_traverse(className, triggerNo, weaponIndex, cached.traverse)
cached.traverseReady = true
if !cached.traverse.known
return false
var wishYaw = 0.0
var wishPitch = 0.0
wto_world_to_hull_deg(wishDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch)
let arc = cached.traverse.yaw
let hereYaw = wto_yaw_in_mount_coordinates(turret.currentState.yaw, arc)
let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, hereYaw, cached.traverse)
turret.yawLim = wto_servo_yaw(turret.currentState.yaw, wishYaw, arc)
if pitch.x <= pitch.y
turret.pitchLim = clamp(wishPitch, pitch.x, pitch.y)
return true
def public wto_apply_weapon_aim(var unit : Unit?; dt : float)
var pos = unit.pos
updateWeaponAnims(*unit.weap, clamp(dt, 0.005, 0.12), 1.0, pos)
+187
View File
@@ -0,0 +1,187 @@
// Trigger channel (decision layer design, section 6): instead of a speed limit per distance band,
// a shot is taken when its estimated hit probability reaches a fire threshold that moves with the
// situation. The hit probability comes from the angular size of the target's visible part against
// the expected angular error of the shot: the crew's aim, the bot's own motion (much less with a
// stabilizer), the uncertainty of the lead on a crossing target, and where the barrel points now.
// It also asks the hull channel for the highest speed at which the shot would be good enough.
options indenting = 2
options no_global_heap = true
module wto_ai_trigger_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_threat_common
// Error function, Abramowitz and Stegun 7.1.26 (absolute error below 1.5e-7).
def private wto_trig_erf(x : float) : float
let ax = abs(x)
let t = 1.0 / (1.0 + 0.3275911 * ax)
let poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t
let y = 1.0 - poly * exp(-ax * ax)
return x >= 0.0 ? y : -y
// Chance that a shot with mean error `offset` and normal spread `sigma` lands within +-half.
def private wto_trig_window(half, offset, sigma : float) : float
let s = max(1.0e-5, sigma) * 1.41421356
return clamp(0.5 * (wto_trig_erf((half - offset) / s) + wto_trig_erf((half + offset) / s)), 0.0, 1.0)
// Hit probability against a target `halfW` x `halfH` metres at `dist` (angles in radians).
def private wto_trig_prob(halfW, halfH, dist : float; offset : float2; sigmaRad : float) : float
let d = max(dist, 5.0)
return wto_trig_window(atan2(halfW, d), offset.x, sigmaRad) * wto_trig_window(atan2(halfH, d), offset.y, sigmaRad)
def public wto_trig_aim_error(actual, wanted : float3) : float2
let across = wto_xz_normalize(float3(-wanted.z, 0.0, wanted.x), float3(0.0, 0.0, 1.0))
let up = cross(across, wanted)
let ahead = dot(actual, wanted)
return float2(atan2(dot(actual, across), ahead), atan2(dot(actual, up), ahead))
// Expected angular spread of a shot (radians) at own speed and hull turn rate.
def private wto_trig_sigma(spec : WtoVehicleSpec const&; speedMps, turnDegSec, leadErrM, dist : float) : float
let stab = spec.hasVertStab ? WTO_AI_FC_STAB_ERR_FACTOR : 1.0
let moveDeg = (speedMps * WTO_AI_FC_MOVE_ERR_DEG_PER_MPS + turnDegSec * WTO_AI_FC_TURN_ERR_DEG_PER_DEG_SEC) * stab
let base = WTO_AI_FC_AIM_ERROR_DEG * WTO_DEG_TO_RAD
let move = moveDeg * WTO_DEG_TO_RAD
let lead = leadErrM / max(dist, 10.0)
return sqrt(base * base + move * move + lead * lead)
// Half width and half height (m) of the visible part of the target as seen from `myPos`.
def public wto_trig_target_half(myPos : float3; tgt : WtoUnitSnap const&; dist : float; visCount : int;
var halfW, halfH : float&)
let los = wto_xz_normalize(tgt.pos - myPos, float3(1.0, 0.0, 0.0))
let perp = float3(-los.z, 0.0, los.x)
let fwd = wto_xz_normalize(tgt.hullFwd, los)
let left = float3(-fwd.z, 0.0, fwd.x)
let sampled = dist > WTO_AI_FC_LONG_RANGE_M ? 2.0 : 4.0
let part = 0.35 + 0.65 * clamp(float(visCount) / sampled, 0.0, 1.0)
halfW = (abs(dot(fwd, perp)) * tgt.halfLen + abs(dot(left, perp)) * tgt.halfWid) * part
halfH = WTO_AI_FC_TARGET_HALF_HEIGHT_M * part
// Fire threshold (decision layer design, 6.1): lower when the target aims at the bot, is close,
// has just fired (reloading) or is about to slip out of sight; higher for big slow-loading guns
// and while pulling back to cover.
[never_inline]
def private wto_trig_threshold(now, dist, reloadSec : float; ammo : int; slot : WtoBotSlot const&) : float
assume p = slot.perceive
var thr = WTO_AI_FC_FIRE_THRESHOLD
for i in range(slot.threat.count)
if slot.threat.entries[i].eid == p.targetEid && slot.threat.entries[i].aiming
thr -= WTO_AI_FC_AIMING_BONUS
if dist < WTO_AI_FC_CLOSE_RANGE_M
thr -= WTO_AI_FC_CLOSE_BONUS * (1.0 - dist / WTO_AI_FC_CLOSE_RANGE_M)
if now - p.targetShotAt <= WTO_AI_FC_ENEMY_RELOAD_SEC
thr -= WTO_AI_FC_ENEMY_RELOAD_BONUS
if p.targetFleeting
thr -= WTO_AI_FC_FLEETING_BONUS
thr += WTO_AI_FC_RELOAD_PENALTY * clamp(reloadSec / WTO_AI_FC_LONG_RELOAD_SEC, 0.0, 1.0)
if ammo >= 0 && ammo < WTO_AI_FC_LOW_AMMO_ROUNDS
thr += WTO_AI_FC_LOW_AMMO_PENALTY * (1.0 - float(ammo) / float(WTO_AI_FC_LOW_AMMO_ROUNDS))
if slot.tactics.state == WTO_STATE_RETREAT_COVER
thr += WTO_AI_FC_RETREAT_PENALTY
return clamp(thr, WTO_AI_FC_MIN_THRESHOLD, 0.95)
// Highest own speed (driving straight, barrel on target) at which the shot still reaches the
// threshold: 99 when the current speed is fine or when even standing would not help.
[never_inline]
def private wto_trig_speed_request(spec : WtoVehicleSpec const&; halfW, halfH, dist, leadErrM, speedNow, thr : float) : float
if wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), wto_trig_sigma(spec, speedNow, 0.0, leadErrM, dist)) >= thr
return 99.0
if wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), wto_trig_sigma(spec, 0.0, 0.0, leadErrM, dist)) < thr
return 99.0
var lo = 0.0
var hi = speedNow
for _i in range(6)
let mid = 0.5 * (lo + hi)
if wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), wto_trig_sigma(spec, mid, 0.0, leadErrM, dist)) >= thr
lo = mid
else
hi = mid
return lo <= WTO_AI_FC_STOP_SPEED_MAX_MPS ? 0.0 : lo
// Evaluates the main weapon's shot at the engaged target this frame and fills slot.trigger:
// hitProb (with the barrel where it points now), hitProbAligned (barrel on target), threshold,
// the autocannon aim slack and the speed request. True when the shot is good enough.
[never_inline]
def public wto_trig_evaluate(world : WtoWorldSnap const&; now : float; myPos : float3; speedNow, turnDegSec,
dist : float; offset : float2; var slot : WtoBotSlot&) : bool
assume tr = slot.trigger
assume p = slot.perceive
let tgtIdx = wto_world_find_unit(world, p.targetEid)
if tgtIdx < 0
tr.hitProb = 0.0
tr.hitProbAligned = 0.0
tr.wantSpeedMps = 99.0
return false
assume tgt = world.units[tgtIdx]
var halfW = 1.5
var halfH = 1.0
wto_trig_target_half(myPos, tgt, dist, p.visiblePointCount, halfW, halfH)
let los = wto_xz_normalize(tgt.pos - myPos, float3(1.0, 0.0, 0.0))
let latSpeed = abs(dot(p.estVel, float3(-los.z, 0.0, los.x)))
let tof = dist / max(120.0, slot.fire.activeSpeedMps)
let leadErrM = latSpeed * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality)
let sigma = wto_trig_sigma(slot.spec, speedNow, turnDegSec, leadErrM, dist)
tr.threshold = wto_trig_threshold(now, dist, slot.spec.reloadSec, slot.fire.ammoRemaining, slot)
tr.hitProb = wto_trig_prob(halfW, halfH, dist, offset, sigma)
tr.hitProbAligned = wto_trig_prob(halfW, halfH, dist, float2(0.0, 0.0), sigma)
tr.aimSlackDeg = max(WTO_AI_FC_BASE_ALIGN_DEG, WTO_AI_FC_AC_AIM_SLACK * atan2(0.5 * (halfW + halfH), max(dist, 5.0)) * WTO_RAD_TO_DEG)
if slot.fire.gunReady && !slot.fire.reloading && !slot.spec.isAutocannon
tr.wantSpeedMps = wto_trig_speed_request(slot.spec, halfW, halfH, dist, leadErrM, speedNow, tr.threshold)
tr.wantSpeedAt = now
else
tr.wantSpeedMps = 99.0
tr.wantSpeedAt = -100.0
return tr.hitProb >= tr.threshold
// Autocannon and coaxial bursts (decision layer design, 6.3): fire for burstSec, pause for
// burstPauseSec. Within a burst the weapon fires whenever it is roughly on target and stops while
// it is not; a new burst starts only when it is. `started` is set when this call opened a burst.
def public wto_trig_burst_gate(now : float; aimOk : bool; var burstUntil, pauseUntil : float&; var started : bool&) : int
started = false
if now < burstUntil
return aimOk ? WTO_DENY_OK : WTO_DENY_AIM_ERR
if now < pauseUntil
return WTO_DENY_BURST_PAUSE
if !aimOk
return WTO_DENY_AIM_ERR
burstUntil = now + WTO_AI_FC_BURST_SEC
pauseUntil = burstUntil + WTO_AI_FC_BURST_PAUSE_SEC
started = true
return WTO_DENY_OK
// Track burst schedules and speed requests by target. Leaving it starts a fresh opportunity.
def public wto_trig_set_target(eid : EntityId; var tr : WtoTriggerState&)
if eid == tr.targetEid
return
tr.targetEid = eid
tr.biasEpoch++
tr.wantSpeedMps = 99.0
tr.wantSpeedAt = -100.0
tr.hitProb = 0.0
tr.hitProbAligned = 0.0
tr.burstUntil = -100.0
tr.burstPauseUntil = -100.0
tr.secondary = WtoWeaponBurst()
tr.coaxial = WtoWeaponBurst()
[never_inline]
def public wto_trig_aux_aim_ok(now, dist, ownSpeed : float; aimErr : float2; myPos : float3;
target : WtoUnitSnap const&; mount : WtoMountFire const&;
slot : WtoBotSlot const&) : bool
var halfW = 0.0
var halfH = 0.0
wto_trig_target_half(myPos, target, dist, slot.perceive.visiblePointCount, halfW, halfH)
if mount.automatic
let slack = atan2(0.5 * (halfW + halfH), max(dist, 5.0)) * WTO_AI_FC_AC_AIM_SLACK
return length(aimErr) <= max(WTO_AI_FC_BASE_ALIGN_DEG * WTO_DEG_TO_RAD, slack)
let los = wto_xz_normalize(target.pos - myPos, float3(1.0, 0.0, 0.0))
let lateral = abs(dot(slot.perceive.estVel, float3(-los.z, 0.0, los.x)))
let leadErr = lateral * (dist / mount.shell.speedMps) * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * slot.perceive.velQuality)
let turn = abs(slot.drive.omegaYawRad) * WTO_RAD_TO_DEG
let sigma = wto_trig_sigma(slot.spec, ownSpeed, turn, leadErr, dist)
return wto_trig_prob(halfW, halfH, dist, aimErr, sigma) >= wto_trig_threshold(now, dist, 0.0, -1, slot)
+78
View File
@@ -0,0 +1,78 @@
// The turret focuses the most dangerous visible contact, then watches memory and cues or scans.
options indenting = 2
options no_global_heap = true
module wto_ai_turret_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_nav_types_common
require %appGame.wtoai.wto_ai_threat_common
def public wto_turret_prefers_threat(slot : WtoBotSlot const&) : bool
let top = slot.threat.topVisibleIdx
if top < 0 || slot.perceive.targetIsAir
return false
assume threat = slot.threat.entries[top]
if threat.eid == slot.perceive.targetEid
return false
let engaged = wto_threat_danger_of(slot, slot.perceive.targetEid)
return threat.danger > engaged * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN)
[never_inline]
def private wto_turret_pick_threat(now : float; var slot : WtoBotSlot&) : int
assume tr = slot.turret
assume tt = slot.threat
let top = tt.topVisibleIdx
if top < 0
tr.lookEid = INVALID_ENTITY_ID
return -1
assume threat = tt.entries[top]
if threat.eid != tr.lookEid
if now < tr.holdUntil
for i in range(tt.count)
assume held = tt.entries[i]
if held.eid == tr.lookEid && held.seesMe && threat.danger <= held.danger * (1.0 + WTO_AI_TURRET_SWITCH_MARGIN)
return i
tr.lookEid = threat.eid
tr.holdUntil = now + WTO_AI_TURRET_MIN_DWELL_SEC
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|TURRET_FOCUS|eid={uint(slot.eid)}|target={uint(tr.lookEid)}|dist={threat.dist}|danger={threat.danger}\n")
return top
// Sweep across the route: scanArcDeg either side of where the bot drives (or of its order goal
// when it stands), one sweep every scanPeriodSec, phase spread by entity id.
[never_inline]
def private wto_turret_scan_dir(now : float; myPos, hullFwd : float3; slot : WtoBotSlot const&) : float3
var base = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
if slot.tactics.desiredSpeedMps > 0.5
base = wto_xz_normalize(slot.nav.steerDir, base)
elif slot.order.valid
base = wto_xz_normalize(slot.order.goalPos - myPos, base)
let phase = now * 6.2831853 / WTO_AI_TURRET_SCAN_PERIOD_SEC + float(int(uint(slot.eid) % 16u)) * 0.4
let yaw = atan2(base.z, base.x) + WTO_AI_TURRET_SCAN_ARC_DEG * WTO_DEG_TO_RAD * sin(phase)
return float3(cos(yaw), 0.0, sin(yaw))
// World direction from the muzzle for the turret when it is not aiming at an engaged target.
[never_inline]
def public wto_turret_look_dir(now : float; muzzlePos, myPos, hullFwd : float3; var slot : WtoBotSlot&) : float3
assume p = slot.perceive
assume tr = slot.turret
let threat = wto_turret_pick_threat(now, slot)
if threat >= 0
tr.lookReason = WTO_LOOK_THREAT
return normalize((slot.threat.entries[threat].pos + float3(0.0, 1.4, 0.0)) - muzzlePos)
if now < p.watchUntil
tr.lookReason = WTO_LOOK_WATCH
return normalize(p.watchPos - muzzlePos)
if !!p.targetEid && (now - p.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
tr.lookReason = WTO_LOOK_MEMORY
return normalize((p.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos)
if now < p.alertUntil
tr.lookReason = WTO_LOOK_CUE
return float3(cos(p.alertYawRad), 0.0, sin(p.alertYawRad))
tr.lookReason = WTO_LOOK_SCAN
return wto_turret_scan_dir(now, myPos, hullFwd, slot)
+59 -42
View File
@@ -6,12 +6,12 @@ module wto_ai_types_common shared
require ecs
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_nav_types_common
let public WTO_MAX_BOTS = 64
let public WTO_MAX_UNITS = 96
let public WTO_MAX_WRECKS = 64
let public WTO_MAX_CAPS = 8
let public WTO_MAX_PATH_PTS = 32
let public WTO_MAX_DEATHS = 32
let public WTO_MAX_JAMS = 24
let public WTO_MAX_RADIO = 24
@@ -24,17 +24,29 @@ let public WTO_ROLE_SPAA = 4
let public WTO_STATE_MARCH = 0
let public WTO_STATE_RUN_AND_GUN = 1
let public WTO_STATE_PREAIM = 2
let public WTO_STATE_SHORT_HALT = 3
let public WTO_STATE_RETREAT_COVER = 4
let public WTO_STATE_COVER_RELOAD = 5
let public WTO_STATE_RELOAD_ADVANCE = 6
let public WTO_STATE_HULL_ANGLE = 7
let public WTO_STATE_REPOSITION = 8
let public WTO_STATE_DISABLED = 9
let public WTO_STATE_DISPERSE = 10
let public WTO_STATE_RIDGE_WITHDRAW = 11
// Hull channel behaviors, chosen by score in
// wto_ai_behavior_common.das; each runs as one or more WTO_STATE_* actions. REPAIR and WITHDRAW
// are not scored: they take over at once.
let public WTO_BHV_ADVANCE = 0
let public WTO_BHV_ENGAGE = 1
let public WTO_BHV_HALT = 2
let public WTO_BHV_COVER = 3
let public WTO_BHV_REPOSITION = 4
let public WTO_BHV_HOLD = 5
let public WTO_BHV_DISPERSE = 6
let public WTO_BHV_WITHDRAW = 7
let public WTO_BHV_REPAIR = 8
let public WTO_BHV_COUNT = 9
let public WTO_DRIVE_HALT = 0
let public WTO_DRIVE_CRUISE = 1
let public WTO_DRIVE_PIVOT = 2
@@ -53,7 +65,8 @@ struct public WtoVehicleSpec
shellCaliberM : float = 0.09
shellCount : int = 0
shells : WtoShellProfile[12]
isAutocannonBelt : bool = false
isAutocannon : bool = false
reloadSec : float = 0.0
isPureLauncher : bool = false
halfLen : float = 3.4
halfWid : float = 1.75
@@ -69,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
@@ -84,6 +101,7 @@ struct public WtoUnitSnap
struct public WtoWreckSnap
eid : EntityId = INVALID_ENTITY_ID
pos : float3 = float3(0.0, 0.0, 0.0)
hullFwd : float3 = float3(1.0, 0.0, 0.0)
halfLen : float = 3.4
halfWid : float = 1.75
@@ -165,7 +183,6 @@ struct public WtoTacticsState
stateEnteredAt : float = -100.0
moveGoal : float3 = float3(0.0, 0.0, 0.0)
desiredSpeedMps : float = 10.0
movingShotBlockedSince : float = -100.0
haltEnterAt : float = -100.0
haltStartShots : int = 0
shortHaltCooldownUntil : float = -100.0
@@ -176,12 +193,12 @@ struct public WtoTacticsState
retreatTarget : float3 = float3(0.0, 0.0, 0.0)
retreatUntil : float = -100.0
retreatReverse : bool = false
hullAngleDir : float3 = float3(1.0, 0.0, 0.0)
repositionGoal : float3 = float3(0.0, 0.0, 0.0)
repositionOrigin : float3 = float3(0.0, 0.0, 0.0)
repositionActive : bool = false
engageTargetEid : EntityId = INVALID_ENTITY_ID
engageShotsNoEffect : int = 0
engageObservedShots : int = 0
engageNoShotHalts : int = 0
engageTotalHaltSec : float = 0.0
lastEffectAt : float = -100.0
@@ -195,42 +212,27 @@ struct public WtoTacticsState
withdrawUntil : float = -100.0
disperseGoal : float3 = float3(0.0, 0.0, 0.0)
disperseUntil : float = -100.0
[safe_when_uninitialized]
struct public WtoRouteState
corridor : float3[32]
corridorLen : int = 0
corridorIdx : int = 0
corridorGoal : float3 = float3(0.0, 0.0, 0.0)
nextReplanAt : float = -100.0
nextShortcutAt : float = -100.0
wingInit : bool = false
wingSign : int = 0
laneOffsetM : float = 0.0
wingCapIdx : int = -2
wingRelayPos : float3 = float3(0.0, 0.0, 0.0)
wingRelayValid : bool = false
shortcutPos : float3 = float3(0.0, 0.0, 0.0)
shortcutValid : bool = false
detourPos : float3 = float3(0.0, 0.0, 0.0)
detourValid : bool = false
detourUntil : float = -100.0
detourCount : int = 0
lastStartOk : bool = false
lastGoalOk : bool = false
[safe_when_uninitialized]
struct public WtoNavState
steerDir : float3 = float3(1.0, 0.0, 0.0)
frontClearM : float = 30.0
rearClearM : float = 16.0
cliffAhead : bool = false
stuckOrigin : float3 = float3(0.0, 0.0, 0.0)
stuckCheckAt : float = -100.0
reverseAnchor : float3 = float3(0.0, 0.0, 0.0)
reverseUntil : float = -100.0
reverseCount : int = 0
ridgeWithdrawEvents : int = 0
// Hull channel (decision layer design, section 7): the chosen behavior, its score, since when
// it runs, when to score again, and what the last scoring saw (a change scores at once).
behavior : int = 0
behaviorScore : float = 0.0
behaviorSince : float = -100.0
nextScoreAt : float = 0.0
scoredHasTarget : bool = false
scoredReloading : bool = false
scoredNearThreat : bool = false
scoredDamageAt : float = -100.0
coverFailedAt : float = -100.0
// Facing constraint (7.3): the hull should point along faceDir (within the facing tolerance)
// when it stands; threatDir is the threat it faces. reverseTravel: drive the route backwards
// to keep the front toward that threat, decided at reverseSince.
faceActive : bool = false
faceDir : float3 = float3(1.0, 0.0, 0.0)
faceThreatDir : float3 = float3(1.0, 0.0, 0.0)
faceFromThreat : bool = false
faceForGun : bool = false
reverseTravel : bool = false
reverseSince : float = -100.0
[safe_when_uninitialized]
struct public WtoDriveCmd
@@ -256,6 +258,17 @@ struct public WtoDriveState
prevStr : float = 0.0
lastVFwd : float = 0.0
// Per-bot bookkeeping of the battle statistics (wto_ai_stats_common.das).
[safe_when_uninitialized]
struct public WtoBotStats
spotEid : EntityId = INVALID_ENTITY_ID
spotAt : float = -100.0
spotShots : int = 0
spotPending : bool = false
lastShots : int = 0
lastAuxShots : int = 0
nextSampleAt : float = 0.0
[safe_when_uninitialized]
struct public WtoBotSlot
used : bool = false
@@ -275,3 +288,7 @@ struct public WtoBotSlot
driveCmd : WtoDriveCmd = WtoDriveCmd()
drive : WtoDriveState = WtoDriveState()
fire : WtoFireState = WtoFireState()
stats : WtoBotStats = WtoBotStats()
threat : WtoThreatTable = WtoThreatTable()
turret : WtoTurretState = WtoTurretState()
trigger : WtoTriggerState = WtoTriggerState()
@@ -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<Weapon const? const> 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
+163
View File
@@ -0,0 +1,163 @@
// Deterministic three-level unstick. A bot that wants to move but makes no progress within
// stuckWindowSec backs up along the corridor it came by (level 1). Stuck again soon after, it also
// marks the spot ahead as a jam that path searches avoid and plans again (level 2). After
// unstickMaxAttempts without real progress it logs the place, marks it harder and gives its order
// back to the commander (level 3).
options indenting = 2
options no_global_heap = true
module wto_ai_unstick_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_types_common
require %appGame.wtoai.wto_ai_nav_types_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_polyline_common
require %appGame.wtoai.wto_ai_navquery_common
require %appGame.wtoai.wto_ai_navmesh_common
require %appGame.wtoai.wto_ai_follow_common
// Move against the previous direction of travel along the corridor, cut short
// where the mesh ends; false when there is no room behind.
[never_inline]
def private wto_unstick_reverse_target(navState : int; myPos, hullFwd : float3; forward : bool; slot : WtoBotSlot const&;
var target : float3&) : bool
let clear = forward ? slot.nav.frontClearM : slot.nav.rearClearM
if clear < 2.5
return false
assume rt = slot.route
let leaveDir = forward ? hullFwd : -hullFwd
let straightBack = myPos + leaveDir * WTO_AI_PF_UNSTICK_REV_M
target = rt.corridorLen >= 2 ? wto_poly_walk_back(rt.corridor, rt.corridorLen, rt.segIdx, rt.segT, WTO_AI_PF_UNSTICK_REV_M) : straightBack
if wto_xz_dist_sq(myPos, target) < 4.0 || dot(target - myPos, leaveDir) <= 0.0
target = straightBack
if navState != WTO_NAVMESH_LOADED || rt.tier < 0
return true
var frac = 0.0
if wto_navq_raycast(rt.tier, rt.filter, myPos, target, frac) != 0
return true
if frac * sqrt(wto_xz_dist_sq(myPos, target)) < 2.0
return false
target = lerp(myPos, target, frac * 0.9)
return true
[never_inline]
def private wto_unstick_start_reverse(navState : int; now : float; myPos, hullFwd : float3; var slot : WtoBotSlot&)
var target = myPos
let forward = slot.tactics.reverseTravel
if !wto_unstick_reverse_target(navState, myPos, hullFwd, forward, slot, target)
return
slot.nav.passUntil = -100.0
slot.nav.reverseTarget = target
slot.nav.unstickForward = forward
slot.nav.reverseUntil = now + WTO_AI_PF_UNSTICK_REV_SEC
slot.nav.reverseCount++
[never_inline]
def private wto_unstick_mark(var world : WtoWorldSnap&; navState : int; now : float; pos : float3; radiusM, costMul : float)
wto_world_record_jam(world, pos, now)
if navState == WTO_NAVMESH_LOADED
wto_navq_add_dynamic(pos, radiusM, costMul, now + WTO_AI_PF_JAM_TTL_SEC)
[never_inline]
def private wto_unstick_give_up(var world : WtoWorldSnap&; navState : int; now : float; myPos, ahead : float3;
var slot : WtoBotSlot&)
print("WTO_AI|NAV_UNREACHABLE|eid={uint(slot.eid)}|tier={slot.route.tier}|pos={myPos}|goal={slot.route.goal}|attempts={slot.nav.unstickAttempts}\n")
wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_GIVE_UP_RADIUS_M, WTO_AI_PF_GIVE_UP_COST_MUL)
slot.order.expiresAt = now
slot.nav.unreachableEvents++
slot.nav.unstickAttempts = 0
slot.nav.unstickLevel = 0
// Pressed against the same body again: mark it for path searches and try its other side; after
// unstickMaxAttempts repeats give the order up like a bot stuck for good.
[never_inline]
def private wto_unstick_contact_repeat(var world : WtoWorldSnap&; navState : int; now : float; myPos : float3;
var slot : WtoBotSlot&)
assume nav = slot.nav
nav.contactRepeats++
if nav.contactRepeats >= WTO_AI_PF_UNSTICK_MAX_ATTEMPTS
nav.unstickAttempts = nav.contactRepeats
nav.contactRepeats = 0
wto_unstick_give_up(world, navState, now, myPos, nav.contactBodyPos, slot)
return
if navState == WTO_NAVMESH_LOADED
wto_navq_add_dynamic(nav.contactBodyPos, nav.contactBodyRadiusM, WTO_AI_PF_RUBBLE_COST_MUL, now + WTO_AI_PF_BLOCK_TTL_SEC)
if nav.avoidSide != 0.0
nav.avoidSide = -nav.avoidSide
nav.avoidSideUntil = now + WTO_AI_PF_UNSTICK_REV_SEC + WTO_AI_PF_BLOCK_WAIT_SEC
// Pressed against a vehicle or wreck: back up at once instead of waiting for the stuck window,
// and plan again. Pressed again near the same place within contactRepeatSec escalates.
[never_inline]
def public wto_unstick_contact(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd : float3;
var slot : WtoBotSlot&)
assume nav = slot.nav
let again = (now - nav.lastContactAt <= WTO_AI_PF_CONTACT_REPEAT_SEC &&
wto_xz_dist_sq(myPos, nav.lastContactPos) <= WTO_AI_PF_JAM_RADIUS_M * WTO_AI_PF_JAM_RADIUS_M)
nav.lastContactAt = now
nav.lastContactPos = myPos
nav.contactSince = -100.0
nav.contactEvents++
nav.stuckCheckAt = -100.0
slot.route.replanRequested = true
if again
wto_unstick_contact_repeat(world, navState, now, myPos, slot)
else
nav.contactRepeats = 0
print("WTO_AI|NAV_CONTACT|eid={uint(slot.eid)}|repeat={nav.contactRepeats}|pos={myPos}|body={nav.contactBodyPos}\n")
wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot)
// True while moving away from a blockage, with the drive command set.
[never_inline]
def public wto_unstick_reversing(now : float; myPos : float3; var slot : WtoBotSlot&) : bool
assume nav = slot.nav
if now >= nav.reverseUntil
return false
let clear = nav.unstickForward ? nav.frontClearM : nav.rearClearM
if wto_xz_dist_sq(myPos, nav.reverseTarget) < 1.0 || clear < 2.1
nav.reverseUntil = -100.0
nav.stuckCheckAt = -100.0
return false
let dir = wto_xz_normalize(nav.reverseTarget - myPos, -nav.steerDir)
nav.steerDir = dir
let mode = nav.unstickForward ? WTO_DRIVE_CRUISE : WTO_DRIVE_REVERSE
let axisCap = nav.unstickForward ? nav.frontTrafficSpeedCap : nav.rearTrafficSpeedCap
let speed = min(slot.spec.vMaxRev, axisCap)
wto_drive_cmd_set(slot.driveCmd, mode, nav.reverseTarget, dir, speed, nav.frontClearM, nav.rearClearM)
return true
// Per nav tick while following: detects no progress and escalates through the three levels.
[never_inline]
def public wto_unstick_watch(var world : WtoWorldSnap&; navState : int; now : float; myPos, hullFwd, ahead : float3;
movingIntent : bool; var slot : WtoBotSlot&)
assume nav = slot.nav
if !movingIntent || nav.stuckCheckAt < -50.0
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_PF_STUCK_WINDOW_SEC
return
if now < nav.stuckCheckAt
return
let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin))
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_PF_STUCK_WINDOW_SEC
if moved >= WTO_AI_PF_STUCK_MIN_PROGRESS_M
if wto_xz_dist_sq(myPos, nav.unstickAnchor) > 144.0
nav.unstickAttempts = 0
nav.unstickLevel = 0
return
nav.unstickAttempts++
nav.unstickEvents++
nav.unstickLevel = (now - nav.lastUnstickAt) <= WTO_AI_PF_UNSTICK_REPEAT_SEC ? min(nav.unstickLevel + 1, 2) : 1
nav.lastUnstickAt = now
nav.unstickAnchor = myPos
print("WTO_AI|NAV_STUCK|eid={uint(slot.eid)}|level={nav.unstickLevel}|attempt={nav.unstickAttempts}|pos={myPos}\n")
if nav.unstickAttempts >= WTO_AI_PF_UNSTICK_MAX_ATTEMPTS
wto_unstick_give_up(world, navState, now, myPos, ahead, slot)
slot.route.replanRequested = true
elif nav.unstickLevel >= 2
wto_unstick_mark(world, navState, now, ahead, WTO_AI_PF_JAM_RADIUS_M, WTO_AI_PF_JAM_COST_MUL)
slot.route.replanRequested = true
wto_unstick_start_reverse(navState, now, myPos, hullFwd, slot)
@@ -0,0 +1,76 @@
// Stock shell data for a gun mount's active ammunition. Modules sharing a trigger still check
// each available barrel and its ammunition before firing.
options indenting = 2
options no_global_heap = true
module wto_ai_weapon_profile_common shared
require ecs
require app
require math
require strings
require DagorDataBlock
require Unit
require Weapon
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_traverse_common
def public wto_profile_read(bullet : DataBlock const&; var shell : WtoShellProfile&) : bool
let speed = bullet |> datablock_getReal("speed", 0.0)
if speed <= 80.0 || speed >= 2600.0
return false
let cal = bullet |> datablock_getReal("ballisticCaliber", 0.0)
shell.speedMps = speed
shell.dragCx = clamp(bullet |> datablock_getReal("Cx", 0.35), 0.05, 1.5)
shell.massKg = clamp(bullet |> datablock_getReal("mass", 10.0), 0.05, 250.0)
shell.caliberM = clamp(cal > 0.002 ? cal : bullet |> datablock_getReal("caliber", 0.09), 0.005, 0.4)
return true
def public wto_profile_is_automatic(weapon : DataBlock const&) : bool
let cannon = weapon |> datablock_getBool("cannon", false)
let belt = weapon |> datablock_getBool("isBulletBelt", false)
let rate = weapon |> datablock_getReal("shotFreq", 0.0)
return belt || (cannon && rate >= WTO_AI_FC_AC_MIN_RATE_HZ)
def private wto_profile_match(bullet : DataBlock const&; var cached : WtoMountFire&)
let name = bullet |> datablock_getStr("bulletName", "")
if !cached.shellValid && !empty(name) && ecs_hash(name) == cached.shellHash
cached.shellValid = wto_profile_read(bullet, cached.shell)
[never_inline]
def private wto_profile_read_weapon(mount : DataBlock const&; var cached : WtoMountFire&)
let path = mount |> datablock_getStr("blk", "")
if empty(path)
return
let belt = mount |> datablock_getBool("isBulletBelt", false)
datablock_load_cached(path, DataBlockReadFlag.ROBUST) <| $(weapon)
cached.automatic = belt || wto_profile_is_automatic(weapon)
datablock_for_each_block(weapon, "bullet") <| $(bullet)
wto_profile_match(bullet, cached)
if !cached.shellValid
datablock_for_each_block(weapon) <| $(set)
datablock_for_each_block(set, "bullet") <| $(bullet)
wto_profile_match(bullet, cached)
// Cache per turret and loaded projectile. Every ballistic check uses that weapon's profile.
[never_inline]
def public wto_mount_load_shell(unit : Unit const?; className : string; turretNo : int;
gun : WTGun const?; var cached : WtoMountFire&) : bool
let idx = int(gun.chosenBulletType)
if idx < 0 || idx >= length(gun.properties.bulletSets)
return false
assume bulletSet = gun.properties.bulletSets[idx]
if length(bulletSet.bullet) == 0 || bulletSet.bullet[0] == null
return false
let name = bulletSet.bullet[0].getName
if empty(name)
return false
let hash = ecs_hash(name)
if cached.shellHash == hash
return cached.shellValid
cached.shellHash = hash
cached.shellValid = false
assume turret = unit.weap.turret[turretNo]
wto_read_gunner_mount(className, int(turret.triggerNo), int(turret.weaponIndex)) <| $(mount)
wto_profile_read_weapon(mount, cached)
return cached.shellValid
+5 -82
View File
@@ -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,78 +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].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 && gm.moveSys != 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
@@ -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
@@ -0,0 +1,61 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURALLOCATOR_H
#define DETOURALLOCATOR_H
#include <stddef.h>
/// Provides hint values to the memory allocator on how long the
/// memory is expected to be used.
enum dtAllocHint
{
DT_ALLOC_PERM, ///< Memory persist after a function call.
DT_ALLOC_TEMP ///< Memory used temporarily within a function.
};
/// A memory allocation function.
// @param[in] size The size, in bytes of memory, to allocate.
// @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use.
// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
/// @see dtAllocSetCustom
typedef void* (dtAllocFunc)(size_t size, dtAllocHint hint);
/// A memory deallocation function.
/// @param[in] ptr A pointer to a memory block previously allocated using #dtAllocFunc.
/// @see dtAllocSetCustom
typedef void (dtFreeFunc)(void* ptr);
/// Sets the base custom allocation functions to be used by Detour.
/// @param[in] allocFunc The memory allocation function to be used by #dtAlloc
/// @param[in] freeFunc The memory de-allocation function to be used by #dtFree
void dtAllocSetCustom(dtAllocFunc *allocFunc, dtFreeFunc *freeFunc);
/// Allocates a memory block.
/// @param[in] size The size, in bytes of memory, to allocate.
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
/// @see dtFree
void* dtAlloc(size_t size, dtAllocHint hint);
/// Deallocates a memory block.
/// @param[in] ptr A pointer to a memory block previously allocated using #dtAlloc.
/// @see dtAlloc
void dtFree(void* ptr);
#endif
@@ -0,0 +1,56 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURASSERT_H
#define DETOURASSERT_H
// Note: This header file's only purpose is to include define assert.
// Feel free to change the file and include your own implementation instead.
#ifdef RC_DISABLE_ASSERTS
// From https://web.archive.org/web/20210117002833/http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
# define dtAssert(x) do { (void)sizeof(x); } while((void)(__LINE__==-1),false)
#else
/// An assertion failure function.
// @param[in] expression asserted expression.
// @param[in] file Filename of the failed assertion.
// @param[in] line Line number of the failed assertion.
/// @see dtAssertFailSetCustom
typedef void (dtAssertFailFunc)(const char* expression, const char* file, int line);
/// Sets the base custom assertion failure function to be used by Detour.
/// @param[in] assertFailFunc The function to be invoked in case of failure of #dtAssert
void dtAssertFailSetCustom(dtAssertFailFunc *assertFailFunc);
/// Gets the base custom assertion failure function to be used by Detour.
dtAssertFailFunc* dtAssertFailGetCustom();
# include <assert.h>
# define dtAssert(expression) \
{ \
dtAssertFailFunc* failFunc = dtAssertFailGetCustom(); \
if(failFunc == NULL) { assert(expression); } \
else if(!(expression)) { (*failFunc)(#expression, __FILE__, __LINE__); } \
}
#endif
#endif // DETOURASSERT_H
@@ -0,0 +1,571 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURCOMMON_H
#define DETOURCOMMON_H
#include "DetourMath.h"
#include <stddef.h>
/**
@defgroup detour Detour
Members in this module are used to create, manipulate, and query navigation
meshes.
@note This is a summary list of members. Use the index or search
feature to find minor members.
*/
/// @name General helper functions
/// @{
/// Used to ignore a function parameter. VS complains about unused parameters
/// and this silences the warning.
template<class T> void dtIgnoreUnused(const T&) { }
/// Swaps the values of the two parameters.
/// @param[in,out] a Value A
/// @param[in,out] b Value B
template<class T> inline void dtSwap(T& a, T& b) { T t = a; a = b; b = t; }
/// Returns the minimum of two values.
/// @param[in] a Value A
/// @param[in] b Value B
/// @return The minimum of the two values.
template<class T> inline T dtMin(T a, T b) { return a < b ? a : b; }
/// Returns the maximum of two values.
/// @param[in] a Value A
/// @param[in] b Value B
/// @return The maximum of the two values.
template<class T> inline T dtMax(T a, T b) { return a > b ? a : b; }
/// Returns the absolute value.
/// @param[in] a The value.
/// @return The absolute value of the specified value.
template<class T> inline T dtAbs(T a) { return a < 0 ? -a : a; }
/// Returns the square of the value.
/// @param[in] a The value.
/// @return The square of the value.
template<class T> inline T dtSqr(T a) { return a*a; }
/// Clamps the value to the specified range.
/// @param[in] v The value to clamp.
/// @param[in] mn The minimum permitted return value.
/// @param[in] mx The maximum permitted return value.
/// @return The value, clamped to the specified range.
template<class T> inline T dtClamp(T v, T mn, T mx) { return v < mn ? mn : (v > mx ? mx : v); }
/// @}
/// @name Vector helper functions.
/// @{
/// Derives the cross product of two vectors. (@p v1 x @p v2)
/// @param[out] dest The cross product. [(x, y, z)]
/// @param[in] v1 A Vector [(x, y, z)]
/// @param[in] v2 A vector [(x, y, z)]
inline void dtVcross(float* dest, const float* v1, const float* v2)
{
dest[0] = v1[1]*v2[2] - v1[2]*v2[1];
dest[1] = v1[2]*v2[0] - v1[0]*v2[2];
dest[2] = v1[0]*v2[1] - v1[1]*v2[0];
}
/// Derives the dot product of two vectors. (@p v1 . @p v2)
/// @param[in] v1 A Vector [(x, y, z)]
/// @param[in] v2 A vector [(x, y, z)]
/// @return The dot product.
inline float dtVdot(const float* v1, const float* v2)
{
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
}
/// Performs a scaled vector addition. (@p v1 + (@p v2 * @p s))
/// @param[out] dest The result vector. [(x, y, z)]
/// @param[in] v1 The base vector. [(x, y, z)]
/// @param[in] v2 The vector to scale and add to @p v1. [(x, y, z)]
/// @param[in] s The amount to scale @p v2 by before adding to @p v1.
inline void dtVmad(float* dest, const float* v1, const float* v2, const float s)
{
dest[0] = v1[0]+v2[0]*s;
dest[1] = v1[1]+v2[1]*s;
dest[2] = v1[2]+v2[2]*s;
}
/// Performs a linear interpolation between two vectors. (@p v1 toward @p v2)
/// @param[out] dest The result vector. [(x, y, x)]
/// @param[in] v1 The starting vector.
/// @param[in] v2 The destination vector.
/// @param[in] t The interpolation factor. [Limits: 0 <= value <= 1.0]
inline void dtVlerp(float* dest, const float* v1, const float* v2, const float t)
{
dest[0] = v1[0]+(v2[0]-v1[0])*t;
dest[1] = v1[1]+(v2[1]-v1[1])*t;
dest[2] = v1[2]+(v2[2]-v1[2])*t;
}
/// Performs a vector addition. (@p v1 + @p v2)
/// @param[out] dest The result vector. [(x, y, z)]
/// @param[in] v1 The base vector. [(x, y, z)]
/// @param[in] v2 The vector to add to @p v1. [(x, y, z)]
inline void dtVadd(float* dest, const float* v1, const float* v2)
{
dest[0] = v1[0]+v2[0];
dest[1] = v1[1]+v2[1];
dest[2] = v1[2]+v2[2];
}
/// Performs a vector subtraction. (@p v1 - @p v2)
/// @param[out] dest The result vector. [(x, y, z)]
/// @param[in] v1 The base vector. [(x, y, z)]
/// @param[in] v2 The vector to subtract from @p v1. [(x, y, z)]
inline void dtVsub(float* dest, const float* v1, const float* v2)
{
dest[0] = v1[0]-v2[0];
dest[1] = v1[1]-v2[1];
dest[2] = v1[2]-v2[2];
}
/// Scales the vector by the specified value. (@p v * @p t)
/// @param[out] dest The result vector. [(x, y, z)]
/// @param[in] v The vector to scale. [(x, y, z)]
/// @param[in] t The scaling factor.
inline void dtVscale(float* dest, const float* v, const float t)
{
dest[0] = v[0]*t;
dest[1] = v[1]*t;
dest[2] = v[2]*t;
}
/// Selects the minimum value of each element from the specified vectors.
/// @param[in,out] mn A vector. (Will be updated with the result.) [(x, y, z)]
/// @param[in] v A vector. [(x, y, z)]
inline void dtVmin(float* mn, const float* v)
{
mn[0] = dtMin(mn[0], v[0]);
mn[1] = dtMin(mn[1], v[1]);
mn[2] = dtMin(mn[2], v[2]);
}
/// Selects the maximum value of each element from the specified vectors.
/// @param[in,out] mx A vector. (Will be updated with the result.) [(x, y, z)]
/// @param[in] v A vector. [(x, y, z)]
inline void dtVmax(float* mx, const float* v)
{
mx[0] = dtMax(mx[0], v[0]);
mx[1] = dtMax(mx[1], v[1]);
mx[2] = dtMax(mx[2], v[2]);
}
/// Sets the vector elements to the specified values.
/// @param[out] dest The result vector. [(x, y, z)]
/// @param[in] x The x-value of the vector.
/// @param[in] y The y-value of the vector.
/// @param[in] z The z-value of the vector.
inline void dtVset(float* dest, const float x, const float y, const float z)
{
dest[0] = x; dest[1] = y; dest[2] = z;
}
/// Performs a vector copy.
/// @param[out] dest The result. [(x, y, z)]
/// @param[in] a The vector to copy. [(x, y, z)]
inline void dtVcopy(float* dest, const float* a)
{
dest[0] = a[0];
dest[1] = a[1];
dest[2] = a[2];
}
/// Derives the scalar length of the vector.
/// @param[in] v The vector. [(x, y, z)]
/// @return The scalar length of the vector.
inline float dtVlen(const float* v)
{
return dtMathSqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
}
/// Derives the square of the scalar length of the vector. (len * len)
/// @param[in] v The vector. [(x, y, z)]
/// @return The square of the scalar length of the vector.
inline float dtVlenSqr(const float* v)
{
return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
}
/// Returns the distance between two points.
/// @param[in] v1 A point. [(x, y, z)]
/// @param[in] v2 A point. [(x, y, z)]
/// @return The distance between the two points.
inline float dtVdist(const float* v1, const float* v2)
{
const float dx = v2[0] - v1[0];
const float dy = v2[1] - v1[1];
const float dz = v2[2] - v1[2];
return dtMathSqrtf(dx*dx + dy*dy + dz*dz);
}
/// Returns the square of the distance between two points.
/// @param[in] v1 A point. [(x, y, z)]
/// @param[in] v2 A point. [(x, y, z)]
/// @return The square of the distance between the two points.
inline float dtVdistSqr(const float* v1, const float* v2)
{
const float dx = v2[0] - v1[0];
const float dy = v2[1] - v1[1];
const float dz = v2[2] - v1[2];
return dx*dx + dy*dy + dz*dz;
}
/// Derives the distance between the specified points on the xz-plane.
/// @param[in] v1 A point. [(x, y, z)]
/// @param[in] v2 A point. [(x, y, z)]
/// @return The distance between the point on the xz-plane.
///
/// The vectors are projected onto the xz-plane, so the y-values are ignored.
inline float dtVdist2D(const float* v1, const float* v2)
{
const float dx = v2[0] - v1[0];
const float dz = v2[2] - v1[2];
return dtMathSqrtf(dx*dx + dz*dz);
}
/// Derives the square of the distance between the specified points on the xz-plane.
/// @param[in] v1 A point. [(x, y, z)]
/// @param[in] v2 A point. [(x, y, z)]
/// @return The square of the distance between the point on the xz-plane.
inline float dtVdist2DSqr(const float* v1, const float* v2)
{
const float dx = v2[0] - v1[0];
const float dz = v2[2] - v1[2];
return dx*dx + dz*dz;
}
/// Normalizes the vector.
/// @param[in,out] v The vector to normalize. [(x, y, z)]
inline void dtVnormalize(float* v)
{
float d = 1.0f / dtMathSqrtf(dtSqr(v[0]) + dtSqr(v[1]) + dtSqr(v[2]));
v[0] *= d;
v[1] *= d;
v[2] *= d;
}
/// Performs a 'sloppy' colocation check of the specified points.
/// @param[in] p0 A point. [(x, y, z)]
/// @param[in] p1 A point. [(x, y, z)]
/// @return True if the points are considered to be at the same location.
///
/// Basically, this function will return true if the specified points are
/// close enough to eachother to be considered colocated.
inline bool dtVequal(const float* p0, const float* p1)
{
static const float thr = dtSqr(1.0f/16384.0f);
const float d = dtVdistSqr(p0, p1);
return d < thr;
}
/// Checks that the specified vector's components are all finite.
/// @param[in] v A point. [(x, y, z)]
/// @return True if all of the point's components are finite, i.e. not NaN
/// or any of the infinities.
inline bool dtVisfinite(const float* v)
{
bool result =
dtMathIsfinite(v[0]) &&
dtMathIsfinite(v[1]) &&
dtMathIsfinite(v[2]);
return result;
}
/// Checks that the specified vector's 2D components are finite.
/// @param[in] v A point. [(x, y, z)]
inline bool dtVisfinite2D(const float* v)
{
bool result = dtMathIsfinite(v[0]) && dtMathIsfinite(v[2]);
return result;
}
/// Derives the dot product of two vectors on the xz-plane. (@p u . @p v)
/// @param[in] u A vector [(x, y, z)]
/// @param[in] v A vector [(x, y, z)]
/// @return The dot product on the xz-plane.
///
/// The vectors are projected onto the xz-plane, so the y-values are ignored.
inline float dtVdot2D(const float* u, const float* v)
{
return u[0]*v[0] + u[2]*v[2];
}
/// Derives the xz-plane 2D perp product of the two vectors. (uz*vx - ux*vz)
/// @param[in] u The LHV vector [(x, y, z)]
/// @param[in] v The RHV vector [(x, y, z)]
/// @return The perp dot product on the xz-plane.
///
/// The vectors are projected onto the xz-plane, so the y-values are ignored.
inline float dtVperp2D(const float* u, const float* v)
{
return u[2]*v[0] - u[0]*v[2];
}
/// @}
/// @name Computational geometry helper functions.
/// @{
/// Derives the signed xz-plane area of the triangle ABC, or the relationship of line AB to point C.
/// @param[in] a Vertex A. [(x, y, z)]
/// @param[in] b Vertex B. [(x, y, z)]
/// @param[in] c Vertex C. [(x, y, z)]
/// @return The signed xz-plane area of the triangle.
inline float dtTriArea2D(const float* a, const float* b, const float* c)
{
const float abx = b[0] - a[0];
const float abz = b[2] - a[2];
const float acx = c[0] - a[0];
const float acz = c[2] - a[2];
return acx*abz - abx*acz;
}
/// Determines if two axis-aligned bounding boxes overlap.
/// @param[in] amin Minimum bounds of box A. [(x, y, z)]
/// @param[in] amax Maximum bounds of box A. [(x, y, z)]
/// @param[in] bmin Minimum bounds of box B. [(x, y, z)]
/// @param[in] bmax Maximum bounds of box B. [(x, y, z)]
/// @return True if the two AABB's overlap.
/// @see dtOverlapBounds
inline bool dtOverlapQuantBounds(const unsigned short amin[3], const unsigned short amax[3],
const unsigned short bmin[3], const unsigned short bmax[3])
{
bool overlap = true;
overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap;
overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap;
overlap = (amin[2] > bmax[2] || amax[2] < bmin[2]) ? false : overlap;
return overlap;
}
/// Determines if two axis-aligned bounding boxes overlap.
/// @param[in] amin Minimum bounds of box A. [(x, y, z)]
/// @param[in] amax Maximum bounds of box A. [(x, y, z)]
/// @param[in] bmin Minimum bounds of box B. [(x, y, z)]
/// @param[in] bmax Maximum bounds of box B. [(x, y, z)]
/// @return True if the two AABB's overlap.
/// @see dtOverlapQuantBounds
inline bool dtOverlapBounds(const float* amin, const float* amax,
const float* bmin, const float* bmax)
{
bool overlap = true;
overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap;
overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap;
overlap = (amin[2] > bmax[2] || amax[2] < bmin[2]) ? false : overlap;
return overlap;
}
/// Derives the closest point on a triangle from the specified reference point.
/// @param[out] closest The closest point on the triangle.
/// @param[in] p The reference point from which to test. [(x, y, z)]
/// @param[in] a Vertex A of triangle ABC. [(x, y, z)]
/// @param[in] b Vertex B of triangle ABC. [(x, y, z)]
/// @param[in] c Vertex C of triangle ABC. [(x, y, z)]
void dtClosestPtPointTriangle(float* closest, const float* p,
const float* a, const float* b, const float* c);
/// Derives the y-axis height of the closest point on the triangle from the specified reference point.
/// @param[in] p The reference point from which to test. [(x, y, z)]
/// @param[in] a Vertex A of triangle ABC. [(x, y, z)]
/// @param[in] b Vertex B of triangle ABC. [(x, y, z)]
/// @param[in] c Vertex C of triangle ABC. [(x, y, z)]
/// @param[out] h The resulting height.
bool dtClosestHeightPointTriangle(const float* p, const float* a, const float* b, const float* c, float& h);
bool dtIntersectSegmentPoly2D(const float* p0, const float* p1,
const float* verts, int nverts,
float& tmin, float& tmax,
int& segMin, int& segMax);
bool dtIntersectSegSeg2D(const float* ap, const float* aq,
const float* bp, const float* bq,
float& s, float& t);
/// Determines if the specified point is inside the convex polygon on the xz-plane.
/// @param[in] pt The point to check. [(x, y, z)]
/// @param[in] verts The polygon vertices. [(x, y, z) * @p nverts]
/// @param[in] nverts The number of vertices. [Limit: >= 3]
/// @return True if the point is inside the polygon.
bool dtPointInPolygon(const float* pt, const float* verts, const int nverts);
bool dtDistancePtPolyEdgesSqr(const float* pt, const float* verts, const int nverts,
float* ed, float* et);
float dtDistancePtSegSqr2D(const float* pt, const float* p, const float* q, float& t);
/// Derives the centroid of a convex polygon.
/// @param[out] tc The centroid of the polgyon. [(x, y, z)]
/// @param[in] idx The polygon indices. [(vertIndex) * @p nidx]
/// @param[in] nidx The number of indices in the polygon. [Limit: >= 3]
/// @param[in] verts The polygon vertices. [(x, y, z) * vertCount]
void dtCalcPolyCenter(float* tc, const unsigned short* idx, int nidx, const float* verts);
/// Determines if the two convex polygons overlap on the xz-plane.
/// @param[in] polya Polygon A vertices. [(x, y, z) * @p npolya]
/// @param[in] npolya The number of vertices in polygon A.
/// @param[in] polyb Polygon B vertices. [(x, y, z) * @p npolyb]
/// @param[in] npolyb The number of vertices in polygon B.
/// @return True if the two polygons overlap.
bool dtOverlapPolyPoly2D(const float* polya, const int npolya,
const float* polyb, const int npolyb);
/// @}
/// @name Miscellanious functions.
/// @{
inline unsigned int dtNextPow2(unsigned int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
inline unsigned int dtIlog2(unsigned int v)
{
unsigned int r;
unsigned int shift;
r = (v > 0xffff) << 4; v >>= r;
shift = (v > 0xff) << 3; v >>= shift; r |= shift;
shift = (v > 0xf) << 2; v >>= shift; r |= shift;
shift = (v > 0x3) << 1; v >>= shift; r |= shift;
r |= (v >> 1);
return r;
}
inline int dtAlign4(int x) { return (x+3) & ~3; }
inline int dtOppositeTile(int side) { return (side+4) & 0x7; }
inline void dtSwapByte(unsigned char* a, unsigned char* b)
{
unsigned char tmp = *a;
*a = *b;
*b = tmp;
}
inline void dtSwapEndian(unsigned short* v)
{
unsigned char* x = (unsigned char*)v;
dtSwapByte(x+0, x+1);
}
inline void dtSwapEndian(short* v)
{
unsigned char* x = (unsigned char*)v;
dtSwapByte(x+0, x+1);
}
inline void dtSwapEndian(unsigned int* v)
{
unsigned char* x = (unsigned char*)v;
dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2);
}
inline void dtSwapEndian(int* v)
{
unsigned char* x = (unsigned char*)v;
dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2);
}
inline void dtSwapEndian(float* v)
{
unsigned char* x = (unsigned char*)v;
dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2);
}
void dtRandomPointInConvexPoly(const float* pts, const int npts, float* areas,
const float s, const float t, float* out);
template<typename TypeToRetrieveAs>
TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(const unsigned char*& buffer, const size_t distanceToAdvance)
{
TypeToRetrieveAs* returnPointer = reinterpret_cast<TypeToRetrieveAs*>(buffer);
buffer += distanceToAdvance;
return returnPointer;
}
template<typename TypeToRetrieveAs>
TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(unsigned char*& buffer, const size_t distanceToAdvance)
{
TypeToRetrieveAs* returnPointer = reinterpret_cast<TypeToRetrieveAs*>(buffer);
buffer += distanceToAdvance;
return returnPointer;
}
/// @}
#endif // DETOURCOMMON_H
///////////////////////////////////////////////////////////////////////////
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
/**
@fn float dtTriArea2D(const float* a, const float* b, const float* c)
@par
The vertices are projected onto the xz-plane, so the y-values are ignored.
This is a low cost function than can be used for various purposes. Its main purpose
is for point/line relationship testing.
In all cases: A value of zero indicates that all vertices are collinear or represent the same point.
(On the xz-plane.)
When used for point/line relationship tests, AB usually represents a line against which
the C point is to be tested. In this case:
A positive value indicates that point C is to the left of line AB, looking from A toward B.<br/>
A negative value indicates that point C is to the right of lineAB, looking from A toward B.
When used for evaluating a triangle:
The absolute value of the return value is two times the area of the triangle when it is
projected onto the xz-plane.
A positive return value indicates:
<ul>
<li>The vertices are wrapped in the normal Detour wrap direction.</li>
<li>The triangle's 3D face normal is in the general up direction.</li>
</ul>
A negative return value indicates:
<ul>
<li>The vertices are reverse wrapped. (Wrapped opposite the normal Detour wrap direction.)</li>
<li>The triangle's 3D face normal is in the general down direction.</li>
</ul>
*/
@@ -0,0 +1,30 @@
/**
@defgroup detour Detour
Members in this module are wrappers around the standard math library
*/
#ifndef DETOURMATH_H
#define DETOURMATH_H
#include <math.h>
inline float dtMathFabsf(float x) { return fabsf(x); }
inline float dtMathSqrtf(float x) { return sqrtf(x); }
inline float dtMathFloorf(float x) { return floorf(x); }
inline float dtMathCeilf(float x) { return ceilf(x); }
inline float dtMathCosf(float x) { return cosf(x); }
inline float dtMathSinf(float x) { return sinf(x); }
inline float dtMathAtan2f(float y, float x) { return atan2f(y, x); }
inline bool dtMathIsfinite(float x)
{
#ifndef RC_FAST_MATH
return isfinite(x);
#else
// Infinity and NaN are disabled when compiling with -ffast-math
(void)x;
return true;
#endif
}
#endif
@@ -0,0 +1,781 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURNAVMESH_H
#define DETOURNAVMESH_H
#include "DetourAlloc.h"
#include "DetourStatus.h"
// Undefine (or define in a build config) the following line to use 64bit polyref.
// Generally not needed, useful for very large worlds.
// Note: tiles build using 32bit refs are not compatible with 64bit refs!
//#define DT_POLYREF64 1
#ifdef DT_POLYREF64
// TODO: figure out a multiplatform version of uint64_t
// - maybe: https://code.google.com/p/msinttypes/
// - or: http://www.azillionmonkeys.com/qed/pstdint.h
#include <stdint.h>
#endif
// Note: If you want to use 64-bit refs, change the types of both dtPolyRef & dtTileRef.
// It is also recommended that you change dtHashRef() to a proper 64-bit hash.
/// A handle to a polygon within a navigation mesh tile.
/// @ingroup detour
#ifdef DT_POLYREF64
static const unsigned int DT_SALT_BITS = 16;
static const unsigned int DT_TILE_BITS = 28;
static const unsigned int DT_POLY_BITS = 20;
typedef uint64_t dtPolyRef;
#else
typedef unsigned int dtPolyRef;
#endif
/// A handle to a tile within a navigation mesh.
/// @ingroup detour
#ifdef DT_POLYREF64
typedef uint64_t dtTileRef;
#else
typedef unsigned int dtTileRef;
#endif
/// The maximum number of vertices per navigation polygon.
/// @ingroup detour
static const int DT_VERTS_PER_POLYGON = 6;
/// @{
/// @name Tile Serialization Constants
/// These constants are used to detect whether a navigation tile's data
/// and state format is compatible with the current build.
///
/// A magic number used to detect compatibility of navigation tile data.
static const int DT_NAVMESH_MAGIC = 'D'<<24 | 'N'<<16 | 'A'<<8 | 'V';
/// A version number used to detect compatibility of navigation tile data.
static const int DT_NAVMESH_VERSION = 7;
/// A magic number used to detect the compatibility of navigation tile states.
static const int DT_NAVMESH_STATE_MAGIC = 'D'<<24 | 'N'<<16 | 'M'<<8 | 'S';
/// A version number used to detect compatibility of navigation tile states.
static const int DT_NAVMESH_STATE_VERSION = 1;
/// @}
/// A flag that indicates that an entity links to an external entity.
/// (E.g. A polygon edge is a portal that links to another polygon.)
static const unsigned short DT_EXT_LINK = 0x8000;
/// A value that indicates the entity does not link to anything.
static const unsigned int DT_NULL_LINK = 0xffffffff;
/// A flag that indicates that an off-mesh connection can be traversed in both directions. (Is bidirectional.)
static const unsigned int DT_OFFMESH_CON_BIDIR = 1;
/// The maximum number of user defined area ids.
/// @ingroup detour
static const int DT_MAX_AREAS = 64;
/// Tile flags used for various functions and fields.
/// For an example, see dtNavMesh::addTile().
enum dtTileFlags
{
/// The navigation mesh owns the tile memory and is responsible for freeing it.
DT_TILE_FREE_DATA = 0x01
};
/// Vertex flags returned by dtNavMeshQuery::findStraightPath.
enum dtStraightPathFlags
{
DT_STRAIGHTPATH_START = 0x01, ///< The vertex is the start position in the path.
DT_STRAIGHTPATH_END = 0x02, ///< The vertex is the end position in the path.
DT_STRAIGHTPATH_OFFMESH_CONNECTION = 0x04 ///< The vertex is the start of an off-mesh connection.
};
/// Options for dtNavMeshQuery::findStraightPath.
enum dtStraightPathOptions
{
DT_STRAIGHTPATH_AREA_CROSSINGS = 0x01, ///< Add a vertex at every polygon edge crossing where area changes.
DT_STRAIGHTPATH_ALL_CROSSINGS = 0x02 ///< Add a vertex at every polygon edge crossing.
};
/// Options for dtNavMeshQuery::initSlicedFindPath and updateSlicedFindPath
enum dtFindPathOptions
{
DT_FINDPATH_ANY_ANGLE = 0x02 ///< use raycasts during pathfind to "shortcut" (raycast still consider costs)
};
/// Options for dtNavMeshQuery::raycast
enum dtRaycastOptions
{
DT_RAYCAST_USE_COSTS = 0x01 ///< Raycast should calculate movement cost along the ray and fill RaycastHit::cost
};
enum dtDetailTriEdgeFlags
{
DT_DETAIL_EDGE_BOUNDARY = 0x01 ///< Detail triangle edge is part of the poly boundary
};
/// Limit raycasting during any angle pahfinding
/// The limit is given as a multiple of the character radius
static const float DT_RAY_CAST_LIMIT_PROPORTIONS = 50.0f;
/// Flags representing the type of a navigation mesh polygon.
enum dtPolyTypes
{
/// The polygon is a standard convex polygon that is part of the surface of the mesh.
DT_POLYTYPE_GROUND = 0,
/// The polygon is an off-mesh connection consisting of two vertices.
DT_POLYTYPE_OFFMESH_CONNECTION = 1
};
/// Defines a polygon within a dtMeshTile object.
/// @ingroup detour
struct dtPoly
{
/// Index to first link in linked list. (Or #DT_NULL_LINK if there is no link.)
unsigned int firstLink;
/// The indices of the polygon's vertices.
/// The actual vertices are located in dtMeshTile::verts.
unsigned short verts[DT_VERTS_PER_POLYGON];
/// Packed data representing neighbor polygons references and flags for each edge.
unsigned short neis[DT_VERTS_PER_POLYGON];
/// The user defined polygon flags.
unsigned short flags;
/// The number of vertices in the polygon.
unsigned char vertCount;
/// The bit packed area id and polygon type.
/// @note Use the structure's set and get methods to access this value.
unsigned char areaAndtype;
/// Sets the user defined area id. [Limit: < #DT_MAX_AREAS]
inline void setArea(unsigned char a) { areaAndtype = (areaAndtype & 0xc0) | (a & 0x3f); }
/// Sets the polygon type. (See: #dtPolyTypes.)
inline void setType(unsigned char t) { areaAndtype = (areaAndtype & 0x3f) | (t << 6); }
/// Gets the user defined area id.
inline unsigned char getArea() const { return areaAndtype & 0x3f; }
/// Gets the polygon type. (See: #dtPolyTypes)
inline unsigned char getType() const { return areaAndtype >> 6; }
};
/// Defines the location of detail sub-mesh data within a dtMeshTile.
struct dtPolyDetail
{
unsigned int vertBase; ///< The offset of the vertices in the dtMeshTile::detailVerts array.
unsigned int triBase; ///< The offset of the triangles in the dtMeshTile::detailTris array.
unsigned char vertCount; ///< The number of vertices in the sub-mesh.
unsigned char triCount; ///< The number of triangles in the sub-mesh.
};
/// Defines a link between polygons.
/// @note This structure is rarely if ever used by the end user.
/// @see dtMeshTile
struct dtLink
{
dtPolyRef ref; ///< Neighbour reference. (The neighbor that is linked to.)
unsigned int next; ///< Index of the next link.
unsigned char edge; ///< Index of the polygon edge that owns this link.
unsigned char side; ///< If a boundary link, defines on which side the link is.
unsigned char bmin; ///< If a boundary link, defines the minimum sub-edge area.
unsigned char bmax; ///< If a boundary link, defines the maximum sub-edge area.
};
/// Bounding volume node.
/// @note This structure is rarely if ever used by the end user.
/// @see dtMeshTile
struct dtBVNode
{
unsigned short bmin[3]; ///< Minimum bounds of the node's AABB. [(x, y, z)]
unsigned short bmax[3]; ///< Maximum bounds of the node's AABB. [(x, y, z)]
int i; ///< The node's index. (Negative for escape sequence.)
};
/// Defines an navigation mesh off-mesh connection within a dtMeshTile object.
/// An off-mesh connection is a user defined traversable connection made up to two vertices.
struct dtOffMeshConnection
{
/// The endpoints of the connection. [(ax, ay, az, bx, by, bz)]
float pos[6];
/// The radius of the endpoints. [Limit: >= 0]
float rad;
/// The polygon reference of the connection within the tile.
unsigned short poly;
/// Link flags.
/// @note These are not the connection's user defined flags. Those are assigned via the
/// connection's dtPoly definition. These are link flags used for internal purposes.
unsigned char flags;
/// End point side.
unsigned char side;
/// The id of the offmesh connection. (User assigned when the navigation mesh is built.)
unsigned int userId;
};
/// Provides high level information related to a dtMeshTile object.
/// @ingroup detour
struct dtMeshHeader
{
int magic; ///< Tile magic number. (Used to identify the data format.)
int version; ///< Tile data format version number.
int x; ///< The x-position of the tile within the dtNavMesh tile grid. (x, y, layer)
int y; ///< The y-position of the tile within the dtNavMesh tile grid. (x, y, layer)
int layer; ///< The layer of the tile within the dtNavMesh tile grid. (x, y, layer)
unsigned int userId; ///< The user defined id of the tile.
int polyCount; ///< The number of polygons in the tile.
int vertCount; ///< The number of vertices in the tile.
int maxLinkCount; ///< The number of allocated links.
int detailMeshCount; ///< The number of sub-meshes in the detail mesh.
/// The number of unique vertices in the detail mesh. (In addition to the polygon vertices.)
int detailVertCount;
int detailTriCount; ///< The number of triangles in the detail mesh.
int bvNodeCount; ///< The number of bounding volume nodes. (Zero if bounding volumes are disabled.)
int offMeshConCount; ///< The number of off-mesh connections.
int offMeshBase; ///< The index of the first polygon which is an off-mesh connection.
float walkableHeight; ///< The height of the agents using the tile.
float walkableRadius; ///< The radius of the agents using the tile.
float walkableClimb; ///< The maximum climb height of the agents using the tile.
float bmin[3]; ///< The minimum bounds of the tile's AABB. [(x, y, z)]
float bmax[3]; ///< The maximum bounds of the tile's AABB. [(x, y, z)]
/// The bounding volume quantization factor.
float bvQuantFactor;
};
/// Defines a navigation mesh tile.
/// @ingroup detour
struct dtMeshTile
{
unsigned int salt; ///< Counter describing modifications to the tile.
unsigned int linksFreeList; ///< Index to the next free link.
dtMeshHeader* header; ///< The tile header.
dtPoly* polys; ///< The tile polygons. [Size: dtMeshHeader::polyCount]
float* verts; ///< The tile vertices. [(x, y, z) * dtMeshHeader::vertCount]
dtLink* links; ///< The tile links. [Size: dtMeshHeader::maxLinkCount]
dtPolyDetail* detailMeshes; ///< The tile's detail sub-meshes. [Size: dtMeshHeader::detailMeshCount]
/// The detail mesh's unique vertices. [(x, y, z) * dtMeshHeader::detailVertCount]
float* detailVerts;
/// The detail mesh's triangles. [(vertA, vertB, vertC, triFlags) * dtMeshHeader::detailTriCount].
/// See dtDetailTriEdgeFlags and dtGetDetailTriEdgeFlags.
unsigned char* detailTris;
/// The tile bounding volume nodes. [Size: dtMeshHeader::bvNodeCount]
/// (Will be null if bounding volumes are disabled.)
dtBVNode* bvTree;
dtOffMeshConnection* offMeshCons; ///< The tile off-mesh connections. [Size: dtMeshHeader::offMeshConCount]
unsigned char* data; ///< The tile data. (Not directly accessed under normal situations.)
int dataSize; ///< Size of the tile data.
int flags; ///< Tile flags. (See: #dtTileFlags)
dtMeshTile* next; ///< The next free tile, or the next tile in the spatial grid.
};
/// Get flags for edge in detail triangle.
/// @param[in] triFlags The flags for the triangle (last component of detail vertices above).
/// @param[in] edgeIndex The index of the first vertex of the edge. For instance, if 0,
/// returns flags for edge AB.
inline int dtGetDetailTriEdgeFlags(unsigned char triFlags, int edgeIndex)
{
return (triFlags >> (edgeIndex * 2)) & 0x3;
}
/// Configuration parameters used to define multi-tile navigation meshes.
/// The values are used to allocate space during the initialization of a navigation mesh.
/// @see dtNavMesh::init()
/// @ingroup detour
struct dtNavMeshParams
{
float orig[3]; ///< The world space origin of the navigation mesh's tile space. [(x, y, z)]
float tileWidth; ///< The width of each tile. (Along the x-axis.)
float tileHeight; ///< The height of each tile. (Along the z-axis.)
int maxTiles; ///< The maximum number of tiles the navigation mesh can contain. This and maxPolys are used to calculate how many bits are needed to identify tiles and polygons uniquely.
int maxPolys; ///< The maximum number of polygons each tile can contain. This and maxTiles are used to calculate how many bits are needed to identify tiles and polygons uniquely.
};
/// A navigation mesh based on tiles of convex polygons.
/// @ingroup detour
class dtNavMesh
{
public:
dtNavMesh();
~dtNavMesh();
/// @{
/// @name Initialization and Tile Management
/// Initializes the navigation mesh for tiled use.
/// @param[in] params Initialization parameters.
/// @return The status flags for the operation.
dtStatus init(const dtNavMeshParams* params);
/// Initializes the navigation mesh for single tile use.
/// @param[in] data Data of the new tile. (See: #dtCreateNavMeshData)
/// @param[in] dataSize The data size of the new tile.
/// @param[in] flags The tile flags. (See: #dtTileFlags)
/// @return The status flags for the operation.
/// @see dtCreateNavMeshData
dtStatus init(unsigned char* data, const int dataSize, const int flags);
/// The navigation mesh initialization params.
const dtNavMeshParams* getParams() const;
/// Adds a tile to the navigation mesh.
/// @param[in] data Data for the new tile mesh. (See: #dtCreateNavMeshData)
/// @param[in] dataSize Data size of the new tile mesh.
/// @param[in] flags Tile flags. (See: #dtTileFlags)
/// @param[in] lastRef The desired reference for the tile. (When reloading a tile.) [opt] [Default: 0]
/// @param[out] result The tile reference. (If the tile was succesfully added.) [opt]
/// @return The status flags for the operation.
dtStatus addTile(unsigned char* data, int dataSize, int flags, dtTileRef lastRef, dtTileRef* result);
/// Removes the specified tile from the navigation mesh.
/// @param[in] ref The reference of the tile to remove.
/// @param[out] data Data associated with deleted tile.
/// @param[out] dataSize Size of the data associated with deleted tile.
/// @return The status flags for the operation.
dtStatus removeTile(dtTileRef ref, unsigned char** data, int* dataSize);
/// @}
/// @{
/// @name Query Functions
/// Calculates the tile grid location for the specified world position.
/// @param[in] pos The world position for the query. [(x, y, z)]
/// @param[out] tx The tile's x-location. (x, y)
/// @param[out] ty The tile's y-location. (x, y)
void calcTileLoc(const float* pos, int* tx, int* ty) const;
/// Gets the tile at the specified grid location.
/// @param[in] x The tile's x-location. (x, y, layer)
/// @param[in] y The tile's y-location. (x, y, layer)
/// @param[in] layer The tile's layer. (x, y, layer)
/// @return The tile, or null if the tile does not exist.
const dtMeshTile* getTileAt(const int x, const int y, const int layer) const;
/// Gets all tiles at the specified grid location. (All layers.)
/// @param[in] x The tile's x-location. (x, y)
/// @param[in] y The tile's y-location. (x, y)
/// @param[out] tiles A pointer to an array of tiles that will hold the result.
/// @param[in] maxTiles The maximum tiles the tiles parameter can hold.
/// @return The number of tiles returned in the tiles array.
int getTilesAt(const int x, const int y,
dtMeshTile const** tiles, const int maxTiles) const;
/// Gets the tile reference for the tile at specified grid location.
/// @param[in] x The tile's x-location. (x, y, layer)
/// @param[in] y The tile's y-location. (x, y, layer)
/// @param[in] layer The tile's layer. (x, y, layer)
/// @return The tile reference of the tile, or 0 if there is none.
dtTileRef getTileRefAt(int x, int y, int layer) const;
/// Gets the tile reference for the specified tile.
/// @param[in] tile The tile.
/// @return The tile reference of the tile.
dtTileRef getTileRef(const dtMeshTile* tile) const;
/// Gets the tile for the specified tile reference.
/// @param[in] ref The tile reference of the tile to retrieve.
/// @return The tile for the specified reference, or null if the
/// reference is invalid.
const dtMeshTile* getTileByRef(dtTileRef ref) const;
/// The maximum number of tiles supported by the navigation mesh.
/// @return The maximum number of tiles supported by the navigation mesh.
int getMaxTiles() const;
/// Gets the tile at the specified index.
/// @param[in] i The tile index. [Limit: 0 >= index < #getMaxTiles()]
/// @return The tile at the specified index.
const dtMeshTile* getTile(int i) const;
/// Gets the tile and polygon for the specified polygon reference.
/// @param[in] ref The reference for the a polygon.
/// @param[out] tile The tile containing the polygon.
/// @param[out] poly The polygon.
/// @return The status flags for the operation.
dtStatus getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const;
/// Returns the tile and polygon for the specified polygon reference.
/// @param[in] ref A known valid reference for a polygon.
/// @param[out] tile The tile containing the polygon.
/// @param[out] poly The polygon.
void getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const;
/// Checks the validity of a polygon reference.
/// @param[in] ref The polygon reference to check.
/// @return True if polygon reference is valid for the navigation mesh.
bool isValidPolyRef(dtPolyRef ref) const;
/// Gets the polygon reference for the tile's base polygon.
/// @param[in] tile The tile.
/// @return The polygon reference for the base polygon in the specified tile.
dtPolyRef getPolyRefBase(const dtMeshTile* tile) const;
/// Gets the endpoints for an off-mesh connection, ordered by "direction of travel".
/// @param[in] prevRef The reference of the polygon before the connection.
/// @param[in] polyRef The reference of the off-mesh connection polygon.
/// @param[out] startPos The start position of the off-mesh connection. [(x, y, z)]
/// @param[out] endPos The end position of the off-mesh connection. [(x, y, z)]
/// @return The status flags for the operation.
dtStatus getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const;
/// Gets the specified off-mesh connection.
/// @param[in] ref The polygon reference of the off-mesh connection.
/// @return The specified off-mesh connection, or null if the polygon reference is not valid.
const dtOffMeshConnection* getOffMeshConnectionByRef(dtPolyRef ref) const;
/// @}
/// @{
/// @name State Management
/// These functions do not effect #dtTileRef or #dtPolyRef's.
/// Sets the user defined flags for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[in] flags The new flags for the polygon.
/// @return The status flags for the operation.
dtStatus setPolyFlags(dtPolyRef ref, unsigned short flags);
/// Gets the user defined flags for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[out] resultFlags The polygon flags.
/// @return The status flags for the operation.
dtStatus getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const;
/// Sets the user defined area for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[in] area The new area id for the polygon. [Limit: < #DT_MAX_AREAS]
/// @return The status flags for the operation.
dtStatus setPolyArea(dtPolyRef ref, unsigned char area);
/// Gets the user defined area for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[out] resultArea The area id for the polygon.
/// @return The status flags for the operation.
dtStatus getPolyArea(dtPolyRef ref, unsigned char* resultArea) const;
/// Gets the size of the buffer required by #storeTileState to store the specified tile's state.
/// @param[in] tile The tile.
/// @return The size of the buffer required to store the state.
int getTileStateSize(const dtMeshTile* tile) const;
/// Stores the non-structural state of the tile in the specified buffer. (Flags, area ids, etc.)
/// @param[in] tile The tile.
/// @param[out] data The buffer to store the tile's state in.
/// @param[in] maxDataSize The size of the data buffer. [Limit: >= #getTileStateSize]
/// @return The status flags for the operation.
dtStatus storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const;
/// Restores the state of the tile.
/// @param[in] tile The tile.
/// @param[in] data The new state. (Obtained from #storeTileState.)
/// @param[in] maxDataSize The size of the state within the data buffer.
/// @return The status flags for the operation.
dtStatus restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize);
/// @}
/// @{
/// @name Encoding and Decoding
/// These functions are generally meant for internal use only.
/// Derives a standard polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] salt The tile's salt value.
/// @param[in] it The index of the tile.
/// @param[in] ip The index of the polygon within the tile.
inline dtPolyRef encodePolyId(unsigned int salt, unsigned int it, unsigned int ip) const
{
#ifdef DT_POLYREF64
return ((dtPolyRef)salt << (DT_POLY_BITS+DT_TILE_BITS)) | ((dtPolyRef)it << DT_POLY_BITS) | (dtPolyRef)ip;
#else
return ((dtPolyRef)salt << (m_polyBits+m_tileBits)) | ((dtPolyRef)it << m_polyBits) | (dtPolyRef)ip;
#endif
}
/// Decodes a standard polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference to decode.
/// @param[out] salt The tile's salt value.
/// @param[out] it The index of the tile.
/// @param[out] ip The index of the polygon within the tile.
/// @see #encodePolyId
inline void decodePolyId(dtPolyRef ref, unsigned int& salt, unsigned int& it, unsigned int& ip) const
{
#ifdef DT_POLYREF64
const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1;
const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1;
const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1;
salt = (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask);
it = (unsigned int)((ref >> DT_POLY_BITS) & tileMask);
ip = (unsigned int)(ref & polyMask);
#else
const dtPolyRef saltMask = ((dtPolyRef)1<<m_saltBits)-1;
const dtPolyRef tileMask = ((dtPolyRef)1<<m_tileBits)-1;
const dtPolyRef polyMask = ((dtPolyRef)1<<m_polyBits)-1;
salt = (unsigned int)((ref >> (m_polyBits+m_tileBits)) & saltMask);
it = (unsigned int)((ref >> m_polyBits) & tileMask);
ip = (unsigned int)(ref & polyMask);
#endif
}
/// Extracts a tile's salt value from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
inline unsigned int decodePolyIdSalt(dtPolyRef ref) const
{
#ifdef DT_POLYREF64
const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1;
return (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask);
#else
const dtPolyRef saltMask = ((dtPolyRef)1<<m_saltBits)-1;
return (unsigned int)((ref >> (m_polyBits+m_tileBits)) & saltMask);
#endif
}
/// Extracts the tile's index from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
inline unsigned int decodePolyIdTile(dtPolyRef ref) const
{
#ifdef DT_POLYREF64
const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1;
return (unsigned int)((ref >> DT_POLY_BITS) & tileMask);
#else
const dtPolyRef tileMask = ((dtPolyRef)1<<m_tileBits)-1;
return (unsigned int)((ref >> m_polyBits) & tileMask);
#endif
}
/// Extracts the polygon's index (within its tile) from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
inline unsigned int decodePolyIdPoly(dtPolyRef ref) const
{
#ifdef DT_POLYREF64
const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1;
return (unsigned int)(ref & polyMask);
#else
const dtPolyRef polyMask = ((dtPolyRef)1<<m_polyBits)-1;
return (unsigned int)(ref & polyMask);
#endif
}
/// @}
private:
// Explicitly disabled copy constructor and copy assignment operator.
dtNavMesh(const dtNavMesh&);
dtNavMesh& operator=(const dtNavMesh&);
/// Returns pointer to tile in the tile array.
dtMeshTile* getTile(int i);
/// Returns neighbour tile based on side.
int getTilesAt(const int x, const int y,
dtMeshTile** tiles, const int maxTiles) const;
/// Returns neighbour tile based on side.
int getNeighbourTilesAt(const int x, const int y, const int side,
dtMeshTile** tiles, const int maxTiles) const;
/// Returns all polygons in neighbour tile based on portal defined by the segment.
int findConnectingPolys(const float* va, const float* vb,
const dtMeshTile* tile, int side,
dtPolyRef* con, float* conarea, int maxcon) const;
/// Builds internal polygons links for a tile.
void connectIntLinks(dtMeshTile* tile);
/// Builds internal polygons links for a tile.
void baseOffMeshLinks(dtMeshTile* tile);
/// Builds external polygon links for a tile.
void connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side);
/// Builds external polygon links for a tile.
void connectExtOffMeshLinks(dtMeshTile* tile, dtMeshTile* target, int side);
/// Removes external links at specified side.
void unconnectLinks(dtMeshTile* tile, dtMeshTile* target);
// TODO: These methods are duplicates from dtNavMeshQuery, but are needed for off-mesh connection finding.
/// Queries polygons within a tile.
int queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
dtPolyRef* polys, const int maxPolys) const;
/// Find nearest polygon within a tile.
dtPolyRef findNearestPolyInTile(const dtMeshTile* tile, const float* center,
const float* halfExtents, float* nearestPt) const;
/// Returns whether position is over the poly and the height at the position if so.
bool getPolyHeight(const dtMeshTile* tile, const dtPoly* poly, const float* pos, float* height) const;
/// Returns closest point on polygon.
void closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const;
dtNavMeshParams m_params; ///< Current initialization params. TODO: do not store this info twice.
float m_orig[3]; ///< Origin of the tile (0,0)
float m_tileWidth, m_tileHeight; ///< Dimensions of each tile.
int m_maxTiles; ///< Max number of tiles.
int m_tileLutSize; ///< Tile hash lookup size (must be pot).
int m_tileLutMask; ///< Tile hash lookup mask.
dtMeshTile** m_posLookup; ///< Tile hash lookup.
dtMeshTile* m_nextFree; ///< Freelist of tiles.
dtMeshTile* m_tiles; ///< List of tiles.
#ifndef DT_POLYREF64
unsigned int m_saltBits; ///< Number of salt bits in the tile ID.
unsigned int m_tileBits; ///< Number of tile bits in the tile ID.
unsigned int m_polyBits; ///< Number of poly bits in the tile ID.
#endif
friend class dtNavMeshQuery;
};
/// Allocates a navigation mesh object using the Detour allocator.
/// @return A navigation mesh that is ready for initialization, or null on failure.
/// @ingroup detour
dtNavMesh* dtAllocNavMesh();
/// Frees the specified navigation mesh object using the Detour allocator.
/// @param[in] navmesh A navigation mesh allocated using #dtAllocNavMesh
/// @ingroup detour
void dtFreeNavMesh(dtNavMesh* navmesh);
#endif // DETOURNAVMESH_H
///////////////////////////////////////////////////////////////////////////
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
/**
@typedef dtPolyRef
@par
Polygon references are subject to the same invalidate/preserve/restore
rules that apply to #dtTileRef's. If the #dtTileRef for the polygon's
tile changes, the polygon reference becomes invalid.
Changing a polygon's flags, area id, etc. does not impact its polygon
reference.
@typedef dtTileRef
@par
The following changes will invalidate a tile reference:
- The referenced tile has been removed from the navigation mesh.
- The navigation mesh has been initialized using a different set
of #dtNavMeshParams.
A tile reference is preserved/restored if the tile is added to a navigation
mesh initialized with the original #dtNavMeshParams and is added at the
original reference location. (E.g. The lastRef parameter is used with
dtNavMesh::addTile.)
Basically, if the storage structure of a tile changes, its associated
tile reference changes.
@var unsigned short dtPoly::neis[DT_VERTS_PER_POLYGON]
@par
Each entry represents data for the edge starting at the vertex of the same index.
E.g. The entry at index n represents the edge data for vertex[n] to vertex[n+1].
A value of zero indicates the edge has no polygon connection. (It makes up the
border of the navigation mesh.)
The information can be extracted as follows:
@code
neighborRef = neis[n] & 0xff; // Get the neighbor polygon reference.
if (neis[n] & #DT_EX_LINK)
{
// The edge is an external (portal) edge.
}
@endcode
@var float dtMeshHeader::bvQuantFactor
@par
This value is used for converting between world and bounding volume coordinates.
For example:
@code
const float cs = 1.0f / tile->header->bvQuantFactor;
const dtBVNode* n = &tile->bvTree[i];
if (n->i >= 0)
{
// This is a leaf node.
float worldMinX = tile->header->bmin[0] + n->bmin[0]*cs;
float worldMinY = tile->header->bmin[0] + n->bmin[1]*cs;
// Etc...
}
@endcode
@struct dtMeshTile
@par
Tiles generally only exist within the context of a dtNavMesh object.
Some tile content is optional. For example, a tile may not contain any
off-mesh connections. In this case the associated pointer will be null.
If a detail mesh exists it will share vertices with the base polygon mesh.
Only the vertices unique to the detail mesh will be stored in #detailVerts.
@warning Tiles returned by a dtNavMesh object are not guarenteed to be populated.
For example: The tile at a location might not have been loaded yet, or may have been removed.
In this case, pointers will be null. So if in doubt, check the polygon count in the
tile's header to determine if a tile has polygons defined.
@var float dtOffMeshConnection::pos[6]
@par
For a properly built navigation mesh, vertex A will always be within the bounds of the mesh.
Vertex B is not required to be within the bounds of the mesh.
*/
@@ -0,0 +1,149 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURNAVMESHBUILDER_H
#define DETOURNAVMESHBUILDER_H
#include "DetourAlloc.h"
/// Represents the source data used to build an navigation mesh tile.
/// @ingroup detour
struct dtNavMeshCreateParams
{
/// @name Polygon Mesh Attributes
/// Used to create the base navigation graph.
/// See #rcPolyMesh for details related to these attributes.
/// @{
const unsigned short* verts; ///< The polygon mesh vertices. [(x, y, z) * #vertCount] [Unit: vx]
int vertCount; ///< The number vertices in the polygon mesh. [Limit: >= 3]
const unsigned short* polys; ///< The polygon data. [Size: #polyCount * 2 * #nvp]
const unsigned short* polyFlags; ///< The user defined flags assigned to each polygon. [Size: #polyCount]
const unsigned char* polyAreas; ///< The user defined area ids assigned to each polygon. [Size: #polyCount]
int polyCount; ///< Number of polygons in the mesh. [Limit: >= 1]
int nvp; ///< Number maximum number of vertices per polygon. [Limit: >= 3]
/// @}
/// @name Height Detail Attributes (Optional)
/// See #rcPolyMeshDetail for details related to these attributes.
/// @{
const unsigned int* detailMeshes; ///< The height detail sub-mesh data. [Size: 4 * #polyCount]
const float* detailVerts; ///< The detail mesh vertices. [Size: 3 * #detailVertsCount] [Unit: wu]
int detailVertsCount; ///< The number of vertices in the detail mesh.
const unsigned char* detailTris; ///< The detail mesh triangles. [Size: 4 * #detailTriCount]
int detailTriCount; ///< The number of triangles in the detail mesh.
/// @}
/// @name Off-Mesh Connections Attributes (Optional)
/// Used to define a custom point-to-point edge within the navigation graph, an
/// off-mesh connection is a user defined traversable connection made up to two vertices,
/// at least one of which resides within a navigation mesh polygon.
/// @{
/// Off-mesh connection vertices. [(ax, ay, az, bx, by, bz) * #offMeshConCount] [Unit: wu]
const float* offMeshConVerts;
/// Off-mesh connection radii. [Size: #offMeshConCount] [Unit: wu]
const float* offMeshConRad;
/// User defined flags assigned to the off-mesh connections. [Size: #offMeshConCount]
const unsigned short* offMeshConFlags;
/// User defined area ids assigned to the off-mesh connections. [Size: #offMeshConCount]
const unsigned char* offMeshConAreas;
/// The permitted travel direction of the off-mesh connections. [Size: #offMeshConCount]
///
/// 0 = Travel only from endpoint A to endpoint B.<br/>
/// #DT_OFFMESH_CON_BIDIR = Bidirectional travel.
const unsigned char* offMeshConDir;
/// The user defined ids of the off-mesh connection. [Size: #offMeshConCount]
const unsigned int* offMeshConUserID;
/// The number of off-mesh connections. [Limit: >= 0]
int offMeshConCount;
/// @}
/// @name Tile Attributes
/// @note The tile grid/layer data can be left at zero if the destination is a single tile mesh.
/// @{
unsigned int userId; ///< The user defined id of the tile.
int tileX; ///< The tile's x-grid location within the multi-tile destination mesh. (Along the x-axis.)
int tileY; ///< The tile's y-grid location within the multi-tile destination mesh. (Along the z-axis.)
int tileLayer; ///< The tile's layer within the layered destination mesh. [Limit: >= 0] (Along the y-axis.)
float bmin[3]; ///< The minimum bounds of the tile. [(x, y, z)] [Unit: wu]
float bmax[3]; ///< The maximum bounds of the tile. [(x, y, z)] [Unit: wu]
/// @}
/// @name General Configuration Attributes
/// @{
float walkableHeight; ///< The agent height. [Unit: wu]
float walkableRadius; ///< The agent radius. [Unit: wu]
float walkableClimb; ///< The agent maximum traversable ledge. (Up/Down) [Unit: wu]
float cs; ///< The xz-plane cell size of the polygon mesh. [Limit: > 0] [Unit: wu]
float ch; ///< The y-axis cell height of the polygon mesh. [Limit: > 0] [Unit: wu]
/// True if a bounding volume tree should be built for the tile.
/// @note The BVTree is not normally needed for layered navigation meshes.
bool buildBvTree;
/// @}
};
/// Builds navigation mesh tile data from the provided tile creation data.
/// @ingroup detour
/// @param[in] params Tile creation data.
/// @param[out] outData The resulting tile data.
/// @param[out] outDataSize The size of the tile data array.
/// @return True if the tile data was successfully created.
bool dtCreateNavMeshData(dtNavMeshCreateParams* params, unsigned char** outData, int* outDataSize);
/// Swaps the endianness of the tile data's header (#dtMeshHeader).
/// @param[in,out] data The tile data array.
/// @param[in] dataSize The size of the data array.
bool dtNavMeshHeaderSwapEndian(unsigned char* data, const int dataSize);
/// Swaps endianness of the tile data.
/// @param[in,out] data The tile data array.
/// @param[in] dataSize The size of the data array.
bool dtNavMeshDataSwapEndian(unsigned char* data, const int dataSize);
#endif // DETOURNAVMESHBUILDER_H
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
/**
@struct dtNavMeshCreateParams
@par
This structure is used to marshal data between the Recast mesh generation pipeline and Detour navigation components.
See the rcPolyMesh and rcPolyMeshDetail documentation for detailed information related to mesh structure.
Units are usually in voxels (vx) or world units (wu). The units for voxels, grid size, and cell size
are all based on the values of #cs and #ch.
The standard navigation mesh build process is to create tile data using dtCreateNavMeshData, then add the tile
to a navigation mesh using either the dtNavMesh single tile <tt>init()</tt> function or the dtNavMesh::addTile()
function.
@see dtCreateNavMeshData
*/
@@ -0,0 +1,590 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURNAVMESHQUERY_H
#define DETOURNAVMESHQUERY_H
#include "DetourNavMesh.h"
#include "DetourStatus.h"
// Define DT_VIRTUAL_QUERYFILTER if you wish to derive a custom filter from dtQueryFilter.
// On certain platforms indirect or virtual function call is expensive. The default
// setting is to use non-virtual functions, the actual implementations of the functions
// are declared as inline for maximum speed.
//#define DT_VIRTUAL_QUERYFILTER 1
/// Defines polygon filtering and traversal costs for navigation mesh query operations.
/// @ingroup detour
class dtQueryFilter
{
float m_areaCost[DT_MAX_AREAS]; ///< Cost per area type. (Used by default implementation.)
unsigned short m_includeFlags; ///< Flags for polygons that can be visited. (Used by default implementation.)
unsigned short m_excludeFlags; ///< Flags for polygons that should not be visited. (Used by default implementation.)
public:
dtQueryFilter();
#ifdef DT_VIRTUAL_QUERYFILTER
virtual ~dtQueryFilter() { }
#endif
/// Returns true if the polygon can be visited. (I.e. Is traversable.)
/// @param[in] ref The reference id of the polygon test.
/// @param[in] tile The tile containing the polygon.
/// @param[in] poly The polygon to test.
#ifdef DT_VIRTUAL_QUERYFILTER
virtual bool passFilter(const dtPolyRef ref,
const dtMeshTile* tile,
const dtPoly* poly) const;
#else
bool passFilter(const dtPolyRef ref,
const dtMeshTile* tile,
const dtPoly* poly) const;
#endif
/// Returns cost to move from the beginning to the end of a line segment
/// that is fully contained within a polygon.
/// @param[in] pa The start position on the edge of the previous and current polygon. [(x, y, z)]
/// @param[in] pb The end position on the edge of the current and next polygon. [(x, y, z)]
/// @param[in] prevRef The reference id of the previous polygon. [opt]
/// @param[in] prevTile The tile containing the previous polygon. [opt]
/// @param[in] prevPoly The previous polygon. [opt]
/// @param[in] curRef The reference id of the current polygon.
/// @param[in] curTile The tile containing the current polygon.
/// @param[in] curPoly The current polygon.
/// @param[in] nextRef The refernece id of the next polygon. [opt]
/// @param[in] nextTile The tile containing the next polygon. [opt]
/// @param[in] nextPoly The next polygon. [opt]
#ifdef DT_VIRTUAL_QUERYFILTER
virtual float getCost(const float* pa, const float* pb,
const dtPolyRef prevRef, const dtMeshTile* prevTile, const dtPoly* prevPoly,
const dtPolyRef curRef, const dtMeshTile* curTile, const dtPoly* curPoly,
const dtPolyRef nextRef, const dtMeshTile* nextTile, const dtPoly* nextPoly) const;
#else
float getCost(const float* pa, const float* pb,
const dtPolyRef prevRef, const dtMeshTile* prevTile, const dtPoly* prevPoly,
const dtPolyRef curRef, const dtMeshTile* curTile, const dtPoly* curPoly,
const dtPolyRef nextRef, const dtMeshTile* nextTile, const dtPoly* nextPoly) const;
#endif
/// @name Getters and setters for the default implementation data.
///@{
/// Returns the traversal cost of the area.
/// @param[in] i The id of the area.
/// @returns The traversal cost of the area.
inline float getAreaCost(const int i) const { return m_areaCost[i]; }
/// Sets the traversal cost of the area.
/// @param[in] i The id of the area.
/// @param[in] cost The new cost of traversing the area.
inline void setAreaCost(const int i, const float cost) { m_areaCost[i] = cost; }
/// Returns the include flags for the filter.
/// Any polygons that include one or more of these flags will be
/// included in the operation.
inline unsigned short getIncludeFlags() const { return m_includeFlags; }
/// Sets the include flags for the filter.
/// @param[in] flags The new flags.
inline void setIncludeFlags(const unsigned short flags) { m_includeFlags = flags; }
/// Returns the exclude flags for the filter.
/// Any polygons that include one ore more of these flags will be
/// excluded from the operation.
inline unsigned short getExcludeFlags() const { return m_excludeFlags; }
/// Sets the exclude flags for the filter.
/// @param[in] flags The new flags.
inline void setExcludeFlags(const unsigned short flags) { m_excludeFlags = flags; }
///@}
};
/// Provides information about raycast hit
/// filled by dtNavMeshQuery::raycast
/// @ingroup detour
struct dtRaycastHit
{
/// The hit parameter. (FLT_MAX if no wall hit.)
float t;
/// hitNormal The normal of the nearest wall hit. [(x, y, z)]
float hitNormal[3];
/// The index of the edge on the final polygon where the wall was hit.
int hitEdgeIndex;
/// Pointer to an array of reference ids of the visited polygons. [opt]
dtPolyRef* path;
/// The number of visited polygons. [opt]
int pathCount;
/// The maximum number of polygons the @p path array can hold.
int maxPath;
/// The cost of the path until hit.
float pathCost;
};
/// Provides custom polygon query behavior.
/// Used by dtNavMeshQuery::queryPolygons.
/// @ingroup detour
class dtPolyQuery
{
public:
virtual ~dtPolyQuery();
/// Called for each batch of unique polygons touched by the search area in dtNavMeshQuery::queryPolygons.
/// This can be called multiple times for a single query.
virtual void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count) = 0;
};
/// Provides the ability to perform pathfinding related queries against
/// a navigation mesh.
/// @ingroup detour
class dtNavMeshQuery
{
public:
dtNavMeshQuery();
~dtNavMeshQuery();
/// Initializes the query object.
/// @param[in] nav Pointer to the dtNavMesh object to use for all queries.
/// @param[in] maxNodes Maximum number of search nodes. [Limits: 0 < value <= 65535]
/// @returns The status flags for the query.
dtStatus init(const dtNavMesh* nav, const int maxNodes);
/// @name Standard Pathfinding Functions
/// @{
/// Finds a path from the start polygon to the end polygon.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] endRef The reference id of the end polygon.
/// @param[in] startPos A position within the start polygon. [(x, y, z)]
/// @param[in] endPos A position within the end polygon. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
/// [(polyRef) * @p pathCount]
/// @param[out] pathCount The number of polygons returned in the @p path array.
/// @param[in] maxPath The maximum number of polygons the @p path array can hold. [Limit: >= 1]
dtStatus findPath(dtPolyRef startRef, dtPolyRef endRef,
const float* startPos, const float* endPos,
const dtQueryFilter* filter,
dtPolyRef* path, int* pathCount, const int maxPath) const;
/// Finds the straight path from the start to the end position within the polygon corridor.
/// @param[in] startPos Path start position. [(x, y, z)]
/// @param[in] endPos Path end position. [(x, y, z)]
/// @param[in] path An array of polygon references that represent the path corridor.
/// @param[in] pathSize The number of polygons in the @p path array.
/// @param[out] straightPath Points describing the straight path. [(x, y, z) * @p straightPathCount].
/// @param[out] straightPathFlags Flags describing each point. (See: #dtStraightPathFlags) [opt]
/// @param[out] straightPathRefs The reference id of the polygon that is being entered at each point. [opt]
/// @param[out] straightPathCount The number of points in the straight path.
/// @param[in] maxStraightPath The maximum number of points the straight path arrays can hold. [Limit: > 0]
/// @param[in] options Query options. (see: #dtStraightPathOptions)
/// @returns The status flags for the query.
dtStatus findStraightPath(const float* startPos, const float* endPos,
const dtPolyRef* path, const int pathSize,
float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
int* straightPathCount, const int maxStraightPath, const int options = 0) const;
///@}
/// @name Sliced Pathfinding Functions
/// Common use case:
/// -# Call initSlicedFindPath() to initialize the sliced path query.
/// -# Call updateSlicedFindPath() until it returns complete.
/// -# Call finalizeSlicedFindPath() to get the path.
///@{
/// Initializes a sliced path query.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] endRef The reference id of the end polygon.
/// @param[in] startPos A position within the start polygon. [(x, y, z)]
/// @param[in] endPos A position within the end polygon. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] options query options (see: #dtFindPathOptions)
/// @returns The status flags for the query.
dtStatus initSlicedFindPath(dtPolyRef startRef, dtPolyRef endRef,
const float* startPos, const float* endPos,
const dtQueryFilter* filter, const unsigned int options = 0);
/// Updates an in-progress sliced path query.
/// @param[in] maxIter The maximum number of iterations to perform.
/// @param[out] doneIters The actual number of iterations completed. [opt]
/// @returns The status flags for the query.
dtStatus updateSlicedFindPath(const int maxIter, int* doneIters);
/// Finalizes and returns the results of a sliced path query.
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
/// [(polyRef) * @p pathCount]
/// @param[out] pathCount The number of polygons returned in the @p path array.
/// @param[in] maxPath The max number of polygons the path array can hold. [Limit: >= 1]
/// @returns The status flags for the query.
dtStatus finalizeSlicedFindPath(dtPolyRef* path, int* pathCount, const int maxPath);
/// Finalizes and returns the results of an incomplete sliced path query, returning the path to the furthest
/// polygon on the existing path that was visited during the search.
/// @param[in] existing An array of polygon references for the existing path.
/// @param[in] existingSize The number of polygon in the @p existing array.
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
/// [(polyRef) * @p pathCount]
/// @param[out] pathCount The number of polygons returned in the @p path array.
/// @param[in] maxPath The max number of polygons the @p path array can hold. [Limit: >= 1]
/// @returns The status flags for the query.
dtStatus finalizeSlicedFindPathPartial(const dtPolyRef* existing, const int existingSize,
dtPolyRef* path, int* pathCount, const int maxPath);
///@}
/// @name Dijkstra Search Functions
/// @{
/// Finds the polygons along the navigation graph that touch the specified circle.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
/// @param[in] radius The radius of the search circle.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultRef The reference ids of the polygons touched by the circle. [opt]
/// @param[out] resultParent The reference ids of the parent polygons for each result.
/// Zero if a result polygon has no parent. [opt]
/// @param[out] resultCost The search cost from @p centerPos to the polygon. [opt]
/// @param[out] resultCount The number of polygons found. [opt]
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
/// @returns The status flags for the query.
dtStatus findPolysAroundCircle(dtPolyRef startRef, const float* centerPos, const float radius,
const dtQueryFilter* filter,
dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
int* resultCount, const int maxResult) const;
/// Finds the polygons along the naviation graph that touch the specified convex polygon.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] verts The vertices describing the convex polygon. (CCW)
/// [(x, y, z) * @p nverts]
/// @param[in] nverts The number of vertices in the polygon.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultRef The reference ids of the polygons touched by the search polygon. [opt]
/// @param[out] resultParent The reference ids of the parent polygons for each result. Zero if a
/// result polygon has no parent. [opt]
/// @param[out] resultCost The search cost from the centroid point to the polygon. [opt]
/// @param[out] resultCount The number of polygons found.
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
/// @returns The status flags for the query.
dtStatus findPolysAroundShape(dtPolyRef startRef, const float* verts, const int nverts,
const dtQueryFilter* filter,
dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
int* resultCount, const int maxResult) const;
/// Gets a path from the explored nodes in the previous search.
/// @param[in] endRef The reference id of the end polygon.
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
/// [(polyRef) * @p pathCount]
/// @param[out] pathCount The number of polygons returned in the @p path array.
/// @param[in] maxPath The maximum number of polygons the @p path array can hold. [Limit: >= 0]
/// @returns The status flags. Returns DT_FAILURE | DT_INVALID_PARAM if any parameter is wrong, or if
/// @p endRef was not explored in the previous search. Returns DT_SUCCESS | DT_BUFFER_TOO_SMALL
/// if @p path cannot contain the entire path. In this case it is filled to capacity with a partial path.
/// Otherwise returns DT_SUCCESS.
/// @remarks The result of this function depends on the state of the query object. For that reason it should only
/// be used immediately after one of the two Dijkstra searches, findPolysAroundCircle or findPolysAroundShape.
dtStatus getPathFromDijkstraSearch(dtPolyRef endRef, dtPolyRef* path, int* pathCount, int maxPath) const;
/// @}
/// @name Local Query Functions
///@{
/// Finds the polygon nearest to the specified center point.
/// [opt] means the specified parameter can be a null pointer, in that case the output parameter will not be set.
///
/// @param[in] center The center of the search box. [(x, y, z)]
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] nearestRef The reference id of the nearest polygon. Will be set to 0 if no polygon is found.
/// @param[out] nearestPt The nearest point on the polygon. Unchanged if no polygon is found. [opt] [(x, y, z)]
/// @returns The status flags for the query.
dtStatus findNearestPoly(const float* center, const float* halfExtents,
const dtQueryFilter* filter,
dtPolyRef* nearestRef, float* nearestPt) const;
/// Finds the polygon nearest to the specified center point.
/// [opt] means the specified parameter can be a null pointer, in that case the output parameter will not be set.
///
/// @param[in] center The center of the search box. [(x, y, z)]
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] nearestRef The reference id of the nearest polygon. Will be set to 0 if no polygon is found.
/// @param[out] nearestPt The nearest point on the polygon. Unchanged if no polygon is found. [opt] [(x, y, z)]
/// @param[out] isOverPoly Set to true if the point's X/Z coordinate lies inside the polygon, false otherwise. Unchanged if no polygon is found. [opt]
/// @returns The status flags for the query.
dtStatus findNearestPoly(const float* center, const float* halfExtents,
const dtQueryFilter* filter,
dtPolyRef* nearestRef, float* nearestPt, bool* isOverPoly) const;
/// Finds polygons that overlap the search box.
/// @param[in] center The center of the search box. [(x, y, z)]
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] polys The reference ids of the polygons that overlap the query box.
/// @param[out] polyCount The number of polygons in the search result.
/// @param[in] maxPolys The maximum number of polygons the search result can hold.
/// @returns The status flags for the query.
dtStatus queryPolygons(const float* center, const float* halfExtents,
const dtQueryFilter* filter,
dtPolyRef* polys, int* polyCount, const int maxPolys) const;
/// Finds polygons that overlap the search box.
/// @param[in] center The center of the search box. [(x, y, z)]
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] query The query. Polygons found will be batched together and passed to this query.
dtStatus queryPolygons(const float* center, const float* halfExtents,
const dtQueryFilter* filter, dtPolyQuery* query) const;
/// Finds the non-overlapping navigation polygons in the local neighbourhood around the center position.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] centerPos The center of the query circle. [(x, y, z)]
/// @param[in] radius The radius of the query circle.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultRef The reference ids of the polygons touched by the circle.
/// @param[out] resultParent The reference ids of the parent polygons for each result.
/// Zero if a result polygon has no parent. [opt]
/// @param[out] resultCount The number of polygons found.
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
/// @returns The status flags for the query.
dtStatus findLocalNeighbourhood(dtPolyRef startRef, const float* centerPos, const float radius,
const dtQueryFilter* filter,
dtPolyRef* resultRef, dtPolyRef* resultParent,
int* resultCount, const int maxResult) const;
/// Moves from the start to the end position constrained to the navigation mesh.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] startPos A position of the mover within the start polygon. [(x, y, x)]
/// @param[in] endPos The desired end position of the mover. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultPos The result position of the mover. [(x, y, z)]
/// @param[out] visited The reference ids of the polygons visited during the move.
/// @param[out] visitedCount The number of polygons visited during the move.
/// @param[in] maxVisitedSize The maximum number of polygons the @p visited array can hold.
/// @returns The status flags for the query.
dtStatus moveAlongSurface(dtPolyRef startRef, const float* startPos, const float* endPos,
const dtQueryFilter* filter,
float* resultPos, dtPolyRef* visited, int* visitedCount, const int maxVisitedSize) const;
/// Casts a 'walkability' ray along the surface of the navigation mesh from
/// the start position toward the end position.
/// @note A wrapper around raycast(..., RaycastHit*). Retained for backward compatibility.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] startPos A position within the start polygon representing
/// the start of the ray. [(x, y, z)]
/// @param[in] endPos The position to cast the ray toward. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] t The hit parameter. (FLT_MAX if no wall hit.)
/// @param[out] hitNormal The normal of the nearest wall hit. [(x, y, z)]
/// @param[out] path The reference ids of the visited polygons. [opt]
/// @param[out] pathCount The number of visited polygons. [opt]
/// @param[in] maxPath The maximum number of polygons the @p path array can hold.
/// @returns The status flags for the query.
dtStatus raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
const dtQueryFilter* filter,
float* t, float* hitNormal, dtPolyRef* path, int* pathCount, const int maxPath) const;
/// Casts a 'walkability' ray along the surface of the navigation mesh from
/// the start position toward the end position.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] startPos A position within the start polygon representing
/// the start of the ray. [(x, y, z)]
/// @param[in] endPos The position to cast the ray toward. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] options govern how the raycast behaves. See dtRaycastOptions
/// @param[out] hit Pointer to a raycast hit structure which will be filled by the results.
/// @param[in] prevRef parent of start ref. Used during for cost calculation [opt]
/// @returns The status flags for the query.
dtStatus raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
const dtQueryFilter* filter, const unsigned int options,
dtRaycastHit* hit, dtPolyRef prevRef = 0) const;
/// Finds the distance from the specified position to the nearest polygon wall.
/// @param[in] startRef The reference id of the polygon containing @p centerPos.
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
/// @param[in] maxRadius The radius of the search circle.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] hitDist The distance to the nearest wall from @p centerPos.
/// @param[out] hitPos The nearest position on the wall that was hit. [(x, y, z)]
/// @param[out] hitNormal The normalized ray formed from the wall point to the
/// source point. [(x, y, z)]
/// @returns The status flags for the query.
dtStatus findDistanceToWall(dtPolyRef startRef, const float* centerPos, const float maxRadius,
const dtQueryFilter* filter,
float* hitDist, float* hitPos, float* hitNormal) const;
/// Returns the segments for the specified polygon, optionally including portals.
/// @param[in] ref The reference id of the polygon.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] segmentVerts The segments. [(ax, ay, az, bx, by, bz) * segmentCount]
/// @param[out] segmentRefs The reference ids of each segment's neighbor polygon.
/// Or zero if the segment is a wall. [opt] [(parentRef) * @p segmentCount]
/// @param[out] segmentCount The number of segments returned.
/// @param[in] maxSegments The maximum number of segments the result arrays can hold.
/// @returns The status flags for the query.
dtStatus getPolyWallSegments(dtPolyRef ref, const dtQueryFilter* filter,
float* segmentVerts, dtPolyRef* segmentRefs, int* segmentCount,
const int maxSegments) const;
/// Returns random location on navmesh.
/// Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] frand Function returning a random number [0..1).
/// @param[out] randomRef The reference id of the random location.
/// @param[out] randomPt The random location.
/// @returns The status flags for the query.
dtStatus findRandomPoint(const dtQueryFilter* filter, float (*frand)(),
dtPolyRef* randomRef, float* randomPt) const;
/// Returns random location on navmesh within the reach of specified location.
/// Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
/// The location is not exactly constrained by the circle, but it limits the visited polygons.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
/// @param[in] maxRadius The radius of the search circle. [Units: wu]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] frand Function returning a random number [0..1).
/// @param[out] randomRef The reference id of the random location.
/// @param[out] randomPt The random location. [(x, y, z)]
/// @returns The status flags for the query.
dtStatus findRandomPointAroundCircle(dtPolyRef startRef, const float* centerPos, const float maxRadius,
const dtQueryFilter* filter, float (*frand)(),
dtPolyRef* randomRef, float* randomPt) const;
/// Finds the closest point on the specified polygon.
/// @param[in] ref The reference id of the polygon.
/// @param[in] pos The position to check. [(x, y, z)]
/// @param[out] closest The closest point on the polygon. [(x, y, z)]
/// @param[out] posOverPoly True of the position is over the polygon.
/// @returns The status flags for the query.
dtStatus closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const;
/// Returns a point on the boundary closest to the source point if the source point is outside the
/// polygon's xz-bounds.
/// @param[in] ref The reference id to the polygon.
/// @param[in] pos The position to check. [(x, y, z)]
/// @param[out] closest The closest point. [(x, y, z)]
/// @returns The status flags for the query.
dtStatus closestPointOnPolyBoundary(dtPolyRef ref, const float* pos, float* closest) const;
/// Gets the height of the polygon at the provided position using the height detail. (Most accurate.)
/// @param[in] ref The reference id of the polygon.
/// @param[in] pos A position within the xz-bounds of the polygon. [(x, y, z)]
/// @param[out] height The height at the surface of the polygon.
/// @returns The status flags for the query.
dtStatus getPolyHeight(dtPolyRef ref, const float* pos, float* height) const;
/// @}
/// @name Miscellaneous Functions
/// @{
/// Returns true if the polygon reference is valid and passes the filter restrictions.
/// @param[in] ref The polygon reference to check.
/// @param[in] filter The filter to apply.
bool isValidPolyRef(dtPolyRef ref, const dtQueryFilter* filter) const;
/// Returns true if the polygon reference is in the closed list.
/// @param[in] ref The reference id of the polygon to check.
/// @returns True if the polygon is in closed list.
bool isInClosedList(dtPolyRef ref) const;
/// Gets the node pool.
/// @returns The node pool.
class dtNodePool* getNodePool() const { return m_nodePool; }
/// Gets the navigation mesh the query object is using.
/// @return The navigation mesh the query object is using.
const dtNavMesh* getAttachedNavMesh() const { return m_nav; }
/// @}
private:
// Explicitly disabled copy constructor and copy assignment operator
dtNavMeshQuery(const dtNavMeshQuery&);
dtNavMeshQuery& operator=(const dtNavMeshQuery&);
/// Queries polygons within a tile.
void queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
const dtQueryFilter* filter, dtPolyQuery* query) const;
/// Returns portal points between two polygons.
dtStatus getPortalPoints(dtPolyRef from, dtPolyRef to, float* left, float* right,
unsigned char& fromType, unsigned char& toType) const;
dtStatus getPortalPoints(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
float* left, float* right) const;
/// Returns edge mid point between two polygons.
dtStatus getEdgeMidPoint(dtPolyRef from, dtPolyRef to, float* mid) const;
dtStatus getEdgeMidPoint(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
float* mid) const;
// Appends vertex to a straight path
dtStatus appendVertex(const float* pos, const unsigned char flags, const dtPolyRef ref,
float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
int* straightPathCount, const int maxStraightPath) const;
// Appends intermediate portal points to a straight path.
dtStatus appendPortals(const int startIdx, const int endIdx, const float* endPos, const dtPolyRef* path,
float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
int* straightPathCount, const int maxStraightPath, const int options) const;
// Gets the path leading to the specified end node.
dtStatus getPathToNode(struct dtNode* endNode, dtPolyRef* path, int* pathCount, int maxPath) const;
const dtNavMesh* m_nav; ///< Pointer to navmesh data.
struct dtQueryData
{
dtStatus status;
struct dtNode* lastBestNode;
float lastBestNodeCost;
dtPolyRef startRef, endRef;
float startPos[3], endPos[3];
const dtQueryFilter* filter;
unsigned int options;
float raycastLimitSqr;
};
dtQueryData m_query; ///< Sliced query state.
class dtNodePool* m_tinyNodePool; ///< Pointer to small node pool.
class dtNodePool* m_nodePool; ///< Pointer to node pool.
class dtNodeQueue* m_openList; ///< Pointer to open list queue.
};
/// Allocates a query object using the Detour allocator.
/// @return An allocated query object, or null on failure.
/// @ingroup detour
dtNavMeshQuery* dtAllocNavMeshQuery();
/// Frees the specified query object using the Detour allocator.
/// @param[in] query A query object allocated using #dtAllocNavMeshQuery
/// @ingroup detour
void dtFreeNavMeshQuery(dtNavMeshQuery* query);
#endif // DETOURNAVMESHQUERY_H
@@ -0,0 +1,168 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURNODE_H
#define DETOURNODE_H
#include "DetourNavMesh.h"
enum dtNodeFlags
{
DT_NODE_OPEN = 0x01,
DT_NODE_CLOSED = 0x02,
DT_NODE_PARENT_DETACHED = 0x04 // parent of the node is not adjacent. Found using raycast.
};
typedef unsigned short dtNodeIndex;
static const dtNodeIndex DT_NULL_IDX = (dtNodeIndex)~0;
static const int DT_NODE_PARENT_BITS = 24;
static const int DT_NODE_STATE_BITS = 2;
struct dtNode
{
float pos[3]; ///< Position of the node.
float cost; ///< Cost from previous node to current node.
float total; ///< Cost up to the node.
unsigned int pidx : DT_NODE_PARENT_BITS; ///< Index to parent node.
unsigned int state : DT_NODE_STATE_BITS; ///< extra state information. A polyRef can have multiple nodes with different extra info. see DT_MAX_STATES_PER_NODE
unsigned int flags : 3; ///< Node flags. A combination of dtNodeFlags.
dtPolyRef id; ///< Polygon ref the node corresponds to.
};
static const int DT_MAX_STATES_PER_NODE = 1 << DT_NODE_STATE_BITS; // number of extra states per node. See dtNode::state
class dtNodePool
{
public:
dtNodePool(int maxNodes, int hashSize);
~dtNodePool();
void clear();
// Get a dtNode by ref and extra state information. If there is none then - allocate
// There can be more than one node for the same polyRef but with different extra state information
dtNode* getNode(dtPolyRef id, unsigned char state=0);
dtNode* findNode(dtPolyRef id, unsigned char state);
unsigned int findNodes(dtPolyRef id, dtNode** nodes, const int maxNodes);
inline unsigned int getNodeIdx(const dtNode* node) const
{
if (!node) return 0;
return (unsigned int)(node - m_nodes) + 1;
}
inline dtNode* getNodeAtIdx(unsigned int idx)
{
if (!idx) return 0;
return &m_nodes[idx - 1];
}
inline const dtNode* getNodeAtIdx(unsigned int idx) const
{
if (!idx) return 0;
return &m_nodes[idx - 1];
}
inline int getMemUsed() const
{
return sizeof(*this) +
sizeof(dtNode)*m_maxNodes +
sizeof(dtNodeIndex)*m_maxNodes +
sizeof(dtNodeIndex)*m_hashSize;
}
inline int getMaxNodes() const { return m_maxNodes; }
inline int getHashSize() const { return m_hashSize; }
inline dtNodeIndex getFirst(int bucket) const { return m_first[bucket]; }
inline dtNodeIndex getNext(int i) const { return m_next[i]; }
inline int getNodeCount() const { return m_nodeCount; }
private:
// Explicitly disabled copy constructor and copy assignment operator.
dtNodePool(const dtNodePool&);
dtNodePool& operator=(const dtNodePool&);
dtNode* m_nodes;
dtNodeIndex* m_first;
dtNodeIndex* m_next;
const int m_maxNodes;
const int m_hashSize;
int m_nodeCount;
};
class dtNodeQueue
{
public:
dtNodeQueue(int n);
~dtNodeQueue();
inline void clear() { m_size = 0; }
inline dtNode* top() { return m_heap[0]; }
inline dtNode* pop()
{
dtNode* result = m_heap[0];
m_size--;
trickleDown(0, m_heap[m_size]);
return result;
}
inline void push(dtNode* node)
{
m_size++;
bubbleUp(m_size-1, node);
}
inline void modify(dtNode* node)
{
for (int i = 0; i < m_size; ++i)
{
if (m_heap[i] == node)
{
bubbleUp(i, node);
return;
}
}
}
inline bool empty() const { return m_size == 0; }
inline int getMemUsed() const
{
return sizeof(*this) +
sizeof(dtNode*) * (m_capacity + 1);
}
inline int getCapacity() const { return m_capacity; }
private:
// Explicitly disabled copy constructor and copy assignment operator.
dtNodeQueue(const dtNodeQueue&);
dtNodeQueue& operator=(const dtNodeQueue&);
void bubbleUp(int i, dtNode* node);
void trickleDown(int i, dtNode* node);
dtNode** m_heap;
const int m_capacity;
int m_size;
};
#endif // DETOURNODE_H
@@ -0,0 +1,65 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOURSTATUS_H
#define DETOURSTATUS_H
typedef unsigned int dtStatus;
// High level status.
static const unsigned int DT_FAILURE = 1u << 31; // Operation failed.
static const unsigned int DT_SUCCESS = 1u << 30; // Operation succeed.
static const unsigned int DT_IN_PROGRESS = 1u << 29; // Operation still in progress.
// Detail information for status.
static const unsigned int DT_STATUS_DETAIL_MASK = 0x0ffffff;
static const unsigned int DT_WRONG_MAGIC = 1 << 0; // Input data is not recognized.
static const unsigned int DT_WRONG_VERSION = 1 << 1; // Input data is in wrong version.
static const unsigned int DT_OUT_OF_MEMORY = 1 << 2; // Operation ran out of memory.
static const unsigned int DT_INVALID_PARAM = 1 << 3; // An input parameter was invalid.
static const unsigned int DT_BUFFER_TOO_SMALL = 1 << 4; // Result buffer for the query was too small to store all results.
static const unsigned int DT_OUT_OF_NODES = 1 << 5; // Query ran out of nodes during search.
static const unsigned int DT_PARTIAL_RESULT = 1 << 6; // Query did not reach the end location, returning best guess.
static const unsigned int DT_ALREADY_OCCUPIED = 1 << 7; // A tile has already been assigned to the given x,y coordinate
// Returns true of status is success.
inline bool dtStatusSucceed(dtStatus status)
{
return (status & DT_SUCCESS) != 0;
}
// Returns true of status is failure.
inline bool dtStatusFailed(dtStatus status)
{
return (status & DT_FAILURE) != 0;
}
// Returns true of status is in progress.
inline bool dtStatusInProgress(dtStatus status)
{
return (status & DT_IN_PROGRESS) != 0;
}
// Returns true if specific detail is set.
inline bool dtStatusDetail(dtStatus status, unsigned int detail)
{
return (status & detail) != 0;
}
#endif // DETOURSTATUS_H
@@ -0,0 +1,50 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include <stdlib.h>
#include "DetourAlloc.h"
static void *dtAllocDefault(size_t size, dtAllocHint)
{
return malloc(size);
}
static void dtFreeDefault(void *ptr)
{
free(ptr);
}
static dtAllocFunc* sAllocFunc = dtAllocDefault;
static dtFreeFunc* sFreeFunc = dtFreeDefault;
void dtAllocSetCustom(dtAllocFunc *allocFunc, dtFreeFunc *freeFunc)
{
sAllocFunc = allocFunc ? allocFunc : dtAllocDefault;
sFreeFunc = freeFunc ? freeFunc : dtFreeDefault;
}
void* dtAlloc(size_t size, dtAllocHint hint)
{
return sAllocFunc(size, hint);
}
void dtFree(void* ptr)
{
if (ptr)
sFreeFunc(ptr);
}
@@ -0,0 +1,35 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include "DetourAssert.h"
#ifndef RC_DISABLE_ASSERTS
static dtAssertFailFunc* sAssertFailFunc = 0;
void dtAssertFailSetCustom(dtAssertFailFunc *assertFailFunc)
{
sAssertFailFunc = assertFailFunc;
}
dtAssertFailFunc* dtAssertFailGetCustom()
{
return sAssertFailFunc;
}
#endif
@@ -0,0 +1,387 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include "DetourCommon.h"
#include "DetourMath.h"
//////////////////////////////////////////////////////////////////////////////////////////
void dtClosestPtPointTriangle(float* closest, const float* p,
const float* a, const float* b, const float* c)
{
// Check if P in vertex region outside A
float ab[3], ac[3], ap[3];
dtVsub(ab, b, a);
dtVsub(ac, c, a);
dtVsub(ap, p, a);
float d1 = dtVdot(ab, ap);
float d2 = dtVdot(ac, ap);
if (d1 <= 0.0f && d2 <= 0.0f)
{
// barycentric coordinates (1,0,0)
dtVcopy(closest, a);
return;
}
// Check if P in vertex region outside B
float bp[3];
dtVsub(bp, p, b);
float d3 = dtVdot(ab, bp);
float d4 = dtVdot(ac, bp);
if (d3 >= 0.0f && d4 <= d3)
{
// barycentric coordinates (0,1,0)
dtVcopy(closest, b);
return;
}
// Check if P in edge region of AB, if so return projection of P onto AB
float vc = d1*d4 - d3*d2;
if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f)
{
// barycentric coordinates (1-v,v,0)
float v = d1 / (d1 - d3);
closest[0] = a[0] + v * ab[0];
closest[1] = a[1] + v * ab[1];
closest[2] = a[2] + v * ab[2];
return;
}
// Check if P in vertex region outside C
float cp[3];
dtVsub(cp, p, c);
float d5 = dtVdot(ab, cp);
float d6 = dtVdot(ac, cp);
if (d6 >= 0.0f && d5 <= d6)
{
// barycentric coordinates (0,0,1)
dtVcopy(closest, c);
return;
}
// Check if P in edge region of AC, if so return projection of P onto AC
float vb = d5*d2 - d1*d6;
if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f)
{
// barycentric coordinates (1-w,0,w)
float w = d2 / (d2 - d6);
closest[0] = a[0] + w * ac[0];
closest[1] = a[1] + w * ac[1];
closest[2] = a[2] + w * ac[2];
return;
}
// Check if P in edge region of BC, if so return projection of P onto BC
float va = d3*d6 - d5*d4;
if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f)
{
// barycentric coordinates (0,1-w,w)
float w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
closest[0] = b[0] + w * (c[0] - b[0]);
closest[1] = b[1] + w * (c[1] - b[1]);
closest[2] = b[2] + w * (c[2] - b[2]);
return;
}
// P inside face region. Compute Q through its barycentric coordinates (u,v,w)
float denom = 1.0f / (va + vb + vc);
float v = vb * denom;
float w = vc * denom;
closest[0] = a[0] + ab[0] * v + ac[0] * w;
closest[1] = a[1] + ab[1] * v + ac[1] * w;
closest[2] = a[2] + ab[2] * v + ac[2] * w;
}
bool dtIntersectSegmentPoly2D(const float* p0, const float* p1,
const float* verts, int nverts,
float& tmin, float& tmax,
int& segMin, int& segMax)
{
static const float EPS = 0.000001f;
tmin = 0;
tmax = 1;
segMin = -1;
segMax = -1;
float dir[3];
dtVsub(dir, p1, p0);
for (int i = 0, j = nverts-1; i < nverts; j=i++)
{
float edge[3], diff[3];
dtVsub(edge, &verts[i*3], &verts[j*3]);
dtVsub(diff, p0, &verts[j*3]);
const float n = dtVperp2D(edge, diff);
const float d = dtVperp2D(dir, edge);
if (fabsf(d) < EPS)
{
// S is nearly parallel to this edge
if (n < 0)
return false;
else
continue;
}
const float t = n / d;
if (d < 0)
{
// segment S is entering across this edge
if (t > tmin)
{
tmin = t;
segMin = j;
// S enters after leaving polygon
if (tmin > tmax)
return false;
}
}
else
{
// segment S is leaving across this edge
if (t < tmax)
{
tmax = t;
segMax = j;
// S leaves before entering polygon
if (tmax < tmin)
return false;
}
}
}
return true;
}
float dtDistancePtSegSqr2D(const float* pt, const float* p, const float* q, float& t)
{
float pqx = q[0] - p[0];
float pqz = q[2] - p[2];
float dx = pt[0] - p[0];
float dz = pt[2] - p[2];
float d = pqx*pqx + pqz*pqz;
t = pqx*dx + pqz*dz;
if (d > 0) t /= d;
if (t < 0) t = 0;
else if (t > 1) t = 1;
dx = p[0] + t*pqx - pt[0];
dz = p[2] + t*pqz - pt[2];
return dx*dx + dz*dz;
}
void dtCalcPolyCenter(float* tc, const unsigned short* idx, int nidx, const float* verts)
{
tc[0] = 0.0f;
tc[1] = 0.0f;
tc[2] = 0.0f;
for (int j = 0; j < nidx; ++j)
{
const float* v = &verts[idx[j]*3];
tc[0] += v[0];
tc[1] += v[1];
tc[2] += v[2];
}
const float s = 1.0f / nidx;
tc[0] *= s;
tc[1] *= s;
tc[2] *= s;
}
bool dtClosestHeightPointTriangle(const float* p, const float* a, const float* b, const float* c, float& h)
{
const float EPS = 1e-6f;
float v0[3], v1[3], v2[3];
dtVsub(v0, c, a);
dtVsub(v1, b, a);
dtVsub(v2, p, a);
// Compute scaled barycentric coordinates
float denom = v0[0] * v1[2] - v0[2] * v1[0];
if (fabsf(denom) < EPS)
return false;
float u = v1[2] * v2[0] - v1[0] * v2[2];
float v = v0[0] * v2[2] - v0[2] * v2[0];
if (denom < 0) {
denom = -denom;
u = -u;
v = -v;
}
// If point lies inside the triangle, return interpolated ycoord.
if (u >= 0.0f && v >= 0.0f && (u + v) <= denom) {
h = a[1] + (v0[1] * u + v1[1] * v) / denom;
return true;
}
return false;
}
/// @par
///
/// All points are projected onto the xz-plane, so the y-values are ignored.
bool dtPointInPolygon(const float* pt, const float* verts, const int nverts)
{
// TODO: Replace pnpoly with triArea2D tests?
int i, j;
bool c = false;
for (i = 0, j = nverts-1; i < nverts; j = i++)
{
const float* vi = &verts[i*3];
const float* vj = &verts[j*3];
if (((vi[2] > pt[2]) != (vj[2] > pt[2])) &&
(pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
c = !c;
}
return c;
}
bool dtDistancePtPolyEdgesSqr(const float* pt, const float* verts, const int nverts,
float* ed, float* et)
{
// TODO: Replace pnpoly with triArea2D tests?
int i, j;
bool c = false;
for (i = 0, j = nverts-1; i < nverts; j = i++)
{
const float* vi = &verts[i*3];
const float* vj = &verts[j*3];
if (((vi[2] > pt[2]) != (vj[2] > pt[2])) &&
(pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
c = !c;
ed[j] = dtDistancePtSegSqr2D(pt, vj, vi, et[j]);
}
return c;
}
static void projectPoly(const float* axis, const float* poly, const int npoly,
float& rmin, float& rmax)
{
rmin = rmax = dtVdot2D(axis, &poly[0]);
for (int i = 1; i < npoly; ++i)
{
const float d = dtVdot2D(axis, &poly[i*3]);
rmin = dtMin(rmin, d);
rmax = dtMax(rmax, d);
}
}
inline bool overlapRange(const float amin, const float amax,
const float bmin, const float bmax,
const float eps)
{
return ((amin+eps) > bmax || (amax-eps) < bmin) ? false : true;
}
/// @par
///
/// All vertices are projected onto the xz-plane, so the y-values are ignored.
bool dtOverlapPolyPoly2D(const float* polya, const int npolya,
const float* polyb, const int npolyb)
{
const float eps = 1e-4f;
for (int i = 0, j = npolya-1; i < npolya; j=i++)
{
const float* va = &polya[j*3];
const float* vb = &polya[i*3];
const float n[3] = { vb[2]-va[2], 0, -(vb[0]-va[0]) };
float amin,amax,bmin,bmax;
projectPoly(n, polya, npolya, amin,amax);
projectPoly(n, polyb, npolyb, bmin,bmax);
if (!overlapRange(amin,amax, bmin,bmax, eps))
{
// Found separating axis
return false;
}
}
for (int i = 0, j = npolyb-1; i < npolyb; j=i++)
{
const float* va = &polyb[j*3];
const float* vb = &polyb[i*3];
const float n[3] = { vb[2]-va[2], 0, -(vb[0]-va[0]) };
float amin,amax,bmin,bmax;
projectPoly(n, polya, npolya, amin,amax);
projectPoly(n, polyb, npolyb, bmin,bmax);
if (!overlapRange(amin,amax, bmin,bmax, eps))
{
// Found separating axis
return false;
}
}
return true;
}
// Returns a random point in a convex polygon.
// Adapted from Graphics Gems article.
void dtRandomPointInConvexPoly(const float* pts, const int npts, float* areas,
const float s, const float t, float* out)
{
// Calc triangle araes
float areasum = 0.0f;
for (int i = 2; i < npts; i++) {
areas[i] = dtTriArea2D(&pts[0], &pts[(i-1)*3], &pts[i*3]);
areasum += dtMax(0.001f, areas[i]);
}
// Find sub triangle weighted by area.
const float thr = s*areasum;
float acc = 0.0f;
float u = 1.0f;
int tri = npts - 1;
for (int i = 2; i < npts; i++) {
const float dacc = areas[i];
if (thr >= acc && thr < (acc+dacc))
{
u = (thr - acc) / dacc;
tri = i;
break;
}
acc += dacc;
}
float v = dtMathSqrtf(t);
const float a = 1 - v;
const float b = (1 - u) * v;
const float c = u * v;
const float* pa = &pts[0];
const float* pb = &pts[(tri-1)*3];
const float* pc = &pts[tri*3];
out[0] = a*pa[0] + b*pb[0] + c*pc[0];
out[1] = a*pa[1] + b*pb[1] + c*pc[1];
out[2] = a*pa[2] + b*pb[2] + c*pc[2];
}
inline float vperpXZ(const float* a, const float* b) { return a[0]*b[2] - a[2]*b[0]; }
bool dtIntersectSegSeg2D(const float* ap, const float* aq,
const float* bp, const float* bq,
float& s, float& t)
{
float u[3], v[3], w[3];
dtVsub(u,aq,ap);
dtVsub(v,bq,bp);
dtVsub(w,ap,bp);
float d = vperpXZ(u,v);
if (fabsf(d) < 1e-6f) return false;
s = vperpXZ(v,w) / d;
t = vperpXZ(u,w) / d;
return true;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,802 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
#include "DetourNavMesh.h"
#include "DetourCommon.h"
#include "DetourMath.h"
#include "DetourNavMeshBuilder.h"
#include "DetourAlloc.h"
#include "DetourAssert.h"
static unsigned short MESH_NULL_IDX = 0xffff;
struct BVItem
{
unsigned short bmin[3];
unsigned short bmax[3];
int i;
};
static int compareItemX(const void* va, const void* vb)
{
const BVItem* a = (const BVItem*)va;
const BVItem* b = (const BVItem*)vb;
if (a->bmin[0] < b->bmin[0])
return -1;
if (a->bmin[0] > b->bmin[0])
return 1;
return 0;
}
static int compareItemY(const void* va, const void* vb)
{
const BVItem* a = (const BVItem*)va;
const BVItem* b = (const BVItem*)vb;
if (a->bmin[1] < b->bmin[1])
return -1;
if (a->bmin[1] > b->bmin[1])
return 1;
return 0;
}
static int compareItemZ(const void* va, const void* vb)
{
const BVItem* a = (const BVItem*)va;
const BVItem* b = (const BVItem*)vb;
if (a->bmin[2] < b->bmin[2])
return -1;
if (a->bmin[2] > b->bmin[2])
return 1;
return 0;
}
static void calcExtends(BVItem* items, const int /*nitems*/, const int imin, const int imax,
unsigned short* bmin, unsigned short* bmax)
{
bmin[0] = items[imin].bmin[0];
bmin[1] = items[imin].bmin[1];
bmin[2] = items[imin].bmin[2];
bmax[0] = items[imin].bmax[0];
bmax[1] = items[imin].bmax[1];
bmax[2] = items[imin].bmax[2];
for (int i = imin+1; i < imax; ++i)
{
const BVItem& it = items[i];
if (it.bmin[0] < bmin[0]) bmin[0] = it.bmin[0];
if (it.bmin[1] < bmin[1]) bmin[1] = it.bmin[1];
if (it.bmin[2] < bmin[2]) bmin[2] = it.bmin[2];
if (it.bmax[0] > bmax[0]) bmax[0] = it.bmax[0];
if (it.bmax[1] > bmax[1]) bmax[1] = it.bmax[1];
if (it.bmax[2] > bmax[2]) bmax[2] = it.bmax[2];
}
}
inline int longestAxis(unsigned short x, unsigned short y, unsigned short z)
{
int axis = 0;
unsigned short maxVal = x;
if (y > maxVal)
{
axis = 1;
maxVal = y;
}
if (z > maxVal)
{
axis = 2;
}
return axis;
}
static void subdivide(BVItem* items, int nitems, int imin, int imax, int& curNode, dtBVNode* nodes)
{
int inum = imax - imin;
int icur = curNode;
dtBVNode& node = nodes[curNode++];
if (inum == 1)
{
// Leaf
node.bmin[0] = items[imin].bmin[0];
node.bmin[1] = items[imin].bmin[1];
node.bmin[2] = items[imin].bmin[2];
node.bmax[0] = items[imin].bmax[0];
node.bmax[1] = items[imin].bmax[1];
node.bmax[2] = items[imin].bmax[2];
node.i = items[imin].i;
}
else
{
// Split
calcExtends(items, nitems, imin, imax, node.bmin, node.bmax);
int axis = longestAxis(node.bmax[0] - node.bmin[0],
node.bmax[1] - node.bmin[1],
node.bmax[2] - node.bmin[2]);
if (axis == 0)
{
// Sort along x-axis
qsort(items+imin, inum, sizeof(BVItem), compareItemX);
}
else if (axis == 1)
{
// Sort along y-axis
qsort(items+imin, inum, sizeof(BVItem), compareItemY);
}
else
{
// Sort along z-axis
qsort(items+imin, inum, sizeof(BVItem), compareItemZ);
}
int isplit = imin+inum/2;
// Left
subdivide(items, nitems, imin, isplit, curNode, nodes);
// Right
subdivide(items, nitems, isplit, imax, curNode, nodes);
int iescape = curNode - icur;
// Negative index means escape.
node.i = -iescape;
}
}
static int createBVTree(dtNavMeshCreateParams* params, dtBVNode* nodes, int /*nnodes*/)
{
// Build tree
float quantFactor = 1 / params->cs;
BVItem* items = (BVItem*)dtAlloc(sizeof(BVItem)*params->polyCount, DT_ALLOC_TEMP);
for (int i = 0; i < params->polyCount; i++)
{
BVItem& it = items[i];
it.i = i;
// Calc polygon bounds. Use detail meshes if available.
if (params->detailMeshes)
{
int vb = (int)params->detailMeshes[i*4+0];
int ndv = (int)params->detailMeshes[i*4+1];
float bmin[3];
float bmax[3];
const float* dv = &params->detailVerts[vb*3];
dtVcopy(bmin, dv);
dtVcopy(bmax, dv);
for (int j = 1; j < ndv; j++)
{
dtVmin(bmin, &dv[j * 3]);
dtVmax(bmax, &dv[j * 3]);
}
// BV-tree uses cs for all dimensions
it.bmin[0] = (unsigned short)dtClamp((int)((bmin[0] - params->bmin[0])*quantFactor), 0, 0xffff);
it.bmin[1] = (unsigned short)dtClamp((int)((bmin[1] - params->bmin[1])*quantFactor), 0, 0xffff);
it.bmin[2] = (unsigned short)dtClamp((int)((bmin[2] - params->bmin[2])*quantFactor), 0, 0xffff);
it.bmax[0] = (unsigned short)dtClamp((int)((bmax[0] - params->bmin[0])*quantFactor), 0, 0xffff);
it.bmax[1] = (unsigned short)dtClamp((int)((bmax[1] - params->bmin[1])*quantFactor), 0, 0xffff);
it.bmax[2] = (unsigned short)dtClamp((int)((bmax[2] - params->bmin[2])*quantFactor), 0, 0xffff);
}
else
{
const unsigned short* p = &params->polys[i*params->nvp * 2];
it.bmin[0] = it.bmax[0] = params->verts[p[0] * 3 + 0];
it.bmin[1] = it.bmax[1] = params->verts[p[0] * 3 + 1];
it.bmin[2] = it.bmax[2] = params->verts[p[0] * 3 + 2];
for (int j = 1; j < params->nvp; ++j)
{
if (p[j] == MESH_NULL_IDX) break;
unsigned short x = params->verts[p[j] * 3 + 0];
unsigned short y = params->verts[p[j] * 3 + 1];
unsigned short z = params->verts[p[j] * 3 + 2];
if (x < it.bmin[0]) it.bmin[0] = x;
if (y < it.bmin[1]) it.bmin[1] = y;
if (z < it.bmin[2]) it.bmin[2] = z;
if (x > it.bmax[0]) it.bmax[0] = x;
if (y > it.bmax[1]) it.bmax[1] = y;
if (z > it.bmax[2]) it.bmax[2] = z;
}
// Remap y
it.bmin[1] = (unsigned short)dtMathFloorf((float)it.bmin[1] * params->ch / params->cs);
it.bmax[1] = (unsigned short)dtMathCeilf((float)it.bmax[1] * params->ch / params->cs);
}
}
int curNode = 0;
subdivide(items, params->polyCount, 0, params->polyCount, curNode, nodes);
dtFree(items);
return curNode;
}
static unsigned char classifyOffMeshPoint(const float* pt, const float* bmin, const float* bmax)
{
static const unsigned char XP = 1<<0;
static const unsigned char ZP = 1<<1;
static const unsigned char XM = 1<<2;
static const unsigned char ZM = 1<<3;
unsigned char outcode = 0;
outcode |= (pt[0] >= bmax[0]) ? XP : 0;
outcode |= (pt[2] >= bmax[2]) ? ZP : 0;
outcode |= (pt[0] < bmin[0]) ? XM : 0;
outcode |= (pt[2] < bmin[2]) ? ZM : 0;
switch (outcode)
{
case XP: return 0;
case XP|ZP: return 1;
case ZP: return 2;
case XM|ZP: return 3;
case XM: return 4;
case XM|ZM: return 5;
case ZM: return 6;
case XP|ZM: return 7;
};
return 0xff;
}
// TODO: Better error handling.
/// @par
///
/// The output data array is allocated using the detour allocator (dtAlloc()). The method
/// used to free the memory will be determined by how the tile is added to the navigation
/// mesh.
///
/// @see dtNavMesh, dtNavMesh::addTile()
bool dtCreateNavMeshData(dtNavMeshCreateParams* params, unsigned char** outData, int* outDataSize)
{
if (params->nvp > DT_VERTS_PER_POLYGON)
return false;
if (params->vertCount >= 0xffff)
return false;
if (!params->vertCount || !params->verts)
return false;
if (!params->polyCount || !params->polys)
return false;
const int nvp = params->nvp;
// Classify off-mesh connection points. We store only the connections
// whose start point is inside the tile.
unsigned char* offMeshConClass = 0;
int storedOffMeshConCount = 0;
int offMeshConLinkCount = 0;
if (params->offMeshConCount > 0)
{
offMeshConClass = (unsigned char*)dtAlloc(sizeof(unsigned char)*params->offMeshConCount*2, DT_ALLOC_TEMP);
if (!offMeshConClass)
return false;
// Find tight heigh bounds, used for culling out off-mesh start locations.
float hmin = FLT_MAX;
float hmax = -FLT_MAX;
if (params->detailVerts && params->detailVertsCount)
{
for (int i = 0; i < params->detailVertsCount; ++i)
{
const float h = params->detailVerts[i*3+1];
hmin = dtMin(hmin,h);
hmax = dtMax(hmax,h);
}
}
else
{
for (int i = 0; i < params->vertCount; ++i)
{
const unsigned short* iv = &params->verts[i*3];
const float h = params->bmin[1] + iv[1] * params->ch;
hmin = dtMin(hmin,h);
hmax = dtMax(hmax,h);
}
}
hmin -= params->walkableClimb;
hmax += params->walkableClimb;
float bmin[3], bmax[3];
dtVcopy(bmin, params->bmin);
dtVcopy(bmax, params->bmax);
bmin[1] = hmin;
bmax[1] = hmax;
for (int i = 0; i < params->offMeshConCount; ++i)
{
const float* p0 = &params->offMeshConVerts[(i*2+0)*3];
const float* p1 = &params->offMeshConVerts[(i*2+1)*3];
offMeshConClass[i*2+0] = classifyOffMeshPoint(p0, bmin, bmax);
offMeshConClass[i*2+1] = classifyOffMeshPoint(p1, bmin, bmax);
// Zero out off-mesh start positions which are not even potentially touching the mesh.
if (offMeshConClass[i*2+0] == 0xff)
{
if (p0[1] < bmin[1] || p0[1] > bmax[1])
offMeshConClass[i*2+0] = 0;
}
// Cound how many links should be allocated for off-mesh connections.
if (offMeshConClass[i*2+0] == 0xff)
offMeshConLinkCount++;
if (offMeshConClass[i*2+1] == 0xff)
offMeshConLinkCount++;
if (offMeshConClass[i*2+0] == 0xff)
storedOffMeshConCount++;
}
}
// Off-mesh connections are stored as polygons, adjust values.
const int totPolyCount = params->polyCount + storedOffMeshConCount;
const int totVertCount = params->vertCount + storedOffMeshConCount*2;
// Find portal edges which are at tile borders.
int edgeCount = 0;
int portalCount = 0;
for (int i = 0; i < params->polyCount; ++i)
{
const unsigned short* p = &params->polys[i*2*nvp];
for (int j = 0; j < nvp; ++j)
{
if (p[j] == MESH_NULL_IDX) break;
edgeCount++;
if (p[nvp+j] & 0x8000)
{
unsigned short dir = p[nvp+j] & 0xf;
if (dir != 0xf)
portalCount++;
}
}
}
const int maxLinkCount = edgeCount + portalCount*2 + offMeshConLinkCount*2;
// Find unique detail vertices.
int uniqueDetailVertCount = 0;
int detailTriCount = 0;
if (params->detailMeshes)
{
// Has detail mesh, count unique detail vertex count and use input detail tri count.
detailTriCount = params->detailTriCount;
for (int i = 0; i < params->polyCount; ++i)
{
const unsigned short* p = &params->polys[i*nvp*2];
int ndv = params->detailMeshes[i*4+1];
int nv = 0;
for (int j = 0; j < nvp; ++j)
{
if (p[j] == MESH_NULL_IDX) break;
nv++;
}
ndv -= nv;
uniqueDetailVertCount += ndv;
}
}
else
{
// No input detail mesh, build detail mesh from nav polys.
uniqueDetailVertCount = 0; // No extra detail verts.
detailTriCount = 0;
for (int i = 0; i < params->polyCount; ++i)
{
const unsigned short* p = &params->polys[i*nvp*2];
int nv = 0;
for (int j = 0; j < nvp; ++j)
{
if (p[j] == MESH_NULL_IDX) break;
nv++;
}
detailTriCount += nv-2;
}
}
// Calculate data size
const int headerSize = dtAlign4(sizeof(dtMeshHeader));
const int vertsSize = dtAlign4(sizeof(float)*3*totVertCount);
const int polysSize = dtAlign4(sizeof(dtPoly)*totPolyCount);
const int linksSize = dtAlign4(sizeof(dtLink)*maxLinkCount);
const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*params->polyCount);
const int detailVertsSize = dtAlign4(sizeof(float)*3*uniqueDetailVertCount);
const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*detailTriCount);
const int bvTreeSize = params->buildBvTree ? dtAlign4(sizeof(dtBVNode)*params->polyCount*2) : 0;
const int offMeshConsSize = dtAlign4(sizeof(dtOffMeshConnection)*storedOffMeshConCount);
const int dataSize = headerSize + vertsSize + polysSize + linksSize +
detailMeshesSize + detailVertsSize + detailTrisSize +
bvTreeSize + offMeshConsSize;
unsigned char* data = (unsigned char*)dtAlloc(sizeof(unsigned char)*dataSize, DT_ALLOC_PERM);
if (!data)
{
dtFree(offMeshConClass);
return false;
}
memset(data, 0, dataSize);
unsigned char* d = data;
dtMeshHeader* header = dtGetThenAdvanceBufferPointer<dtMeshHeader>(d, headerSize);
float* navVerts = dtGetThenAdvanceBufferPointer<float>(d, vertsSize);
dtPoly* navPolys = dtGetThenAdvanceBufferPointer<dtPoly>(d, polysSize);
d += linksSize; // Ignore links; just leave enough space for them. They'll be created on load.
dtPolyDetail* navDMeshes = dtGetThenAdvanceBufferPointer<dtPolyDetail>(d, detailMeshesSize);
float* navDVerts = dtGetThenAdvanceBufferPointer<float>(d, detailVertsSize);
unsigned char* navDTris = dtGetThenAdvanceBufferPointer<unsigned char>(d, detailTrisSize);
dtBVNode* navBvtree = dtGetThenAdvanceBufferPointer<dtBVNode>(d, bvTreeSize);
dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer<dtOffMeshConnection>(d, offMeshConsSize);
// Store header
header->magic = DT_NAVMESH_MAGIC;
header->version = DT_NAVMESH_VERSION;
header->x = params->tileX;
header->y = params->tileY;
header->layer = params->tileLayer;
header->userId = params->userId;
header->polyCount = totPolyCount;
header->vertCount = totVertCount;
header->maxLinkCount = maxLinkCount;
dtVcopy(header->bmin, params->bmin);
dtVcopy(header->bmax, params->bmax);
header->detailMeshCount = params->polyCount;
header->detailVertCount = uniqueDetailVertCount;
header->detailTriCount = detailTriCount;
header->bvQuantFactor = 1.0f / params->cs;
header->offMeshBase = params->polyCount;
header->walkableHeight = params->walkableHeight;
header->walkableRadius = params->walkableRadius;
header->walkableClimb = params->walkableClimb;
header->offMeshConCount = storedOffMeshConCount;
header->bvNodeCount = params->buildBvTree ? params->polyCount*2 : 0;
const int offMeshVertsBase = params->vertCount;
const int offMeshPolyBase = params->polyCount;
// Store vertices
// Mesh vertices
for (int i = 0; i < params->vertCount; ++i)
{
const unsigned short* iv = &params->verts[i*3];
float* v = &navVerts[i*3];
v[0] = params->bmin[0] + iv[0] * params->cs;
v[1] = params->bmin[1] + iv[1] * params->ch;
v[2] = params->bmin[2] + iv[2] * params->cs;
}
// Off-mesh link vertices.
int n = 0;
for (int i = 0; i < params->offMeshConCount; ++i)
{
// Only store connections which start from this tile.
if (offMeshConClass[i*2+0] == 0xff)
{
const float* linkv = &params->offMeshConVerts[i*2*3];
float* v = &navVerts[(offMeshVertsBase + n*2)*3];
dtVcopy(&v[0], &linkv[0]);
dtVcopy(&v[3], &linkv[3]);
n++;
}
}
// Store polygons
// Mesh polys
const unsigned short* src = params->polys;
for (int i = 0; i < params->polyCount; ++i)
{
dtPoly* p = &navPolys[i];
p->vertCount = 0;
p->flags = params->polyFlags[i];
p->setArea(params->polyAreas[i]);
p->setType(DT_POLYTYPE_GROUND);
for (int j = 0; j < nvp; ++j)
{
if (src[j] == MESH_NULL_IDX) break;
p->verts[j] = src[j];
if (src[nvp+j] & 0x8000)
{
// Border or portal edge.
unsigned short dir = src[nvp+j] & 0xf;
if (dir == 0xf) // Border
p->neis[j] = 0;
else if (dir == 0) // Portal x-
p->neis[j] = DT_EXT_LINK | 4;
else if (dir == 1) // Portal z+
p->neis[j] = DT_EXT_LINK | 2;
else if (dir == 2) // Portal x+
p->neis[j] = DT_EXT_LINK | 0;
else if (dir == 3) // Portal z-
p->neis[j] = DT_EXT_LINK | 6;
}
else
{
// Normal connection
p->neis[j] = src[nvp+j]+1;
}
p->vertCount++;
}
src += nvp*2;
}
// Off-mesh connection vertices.
n = 0;
for (int i = 0; i < params->offMeshConCount; ++i)
{
// Only store connections which start from this tile.
if (offMeshConClass[i*2+0] == 0xff)
{
dtPoly* p = &navPolys[offMeshPolyBase+n];
p->vertCount = 2;
p->verts[0] = (unsigned short)(offMeshVertsBase + n*2+0);
p->verts[1] = (unsigned short)(offMeshVertsBase + n*2+1);
p->flags = params->offMeshConFlags[i];
p->setArea(params->offMeshConAreas[i]);
p->setType(DT_POLYTYPE_OFFMESH_CONNECTION);
n++;
}
}
// Store detail meshes and vertices.
// The nav polygon vertices are stored as the first vertices on each mesh.
// We compress the mesh data by skipping them and using the navmesh coordinates.
if (params->detailMeshes)
{
unsigned short vbase = 0;
for (int i = 0; i < params->polyCount; ++i)
{
dtPolyDetail& dtl = navDMeshes[i];
const int vb = (int)params->detailMeshes[i*4+0];
const int ndv = (int)params->detailMeshes[i*4+1];
const int nv = navPolys[i].vertCount;
dtl.vertBase = (unsigned int)vbase;
dtl.vertCount = (unsigned char)(ndv-nv);
dtl.triBase = (unsigned int)params->detailMeshes[i*4+2];
dtl.triCount = (unsigned char)params->detailMeshes[i*4+3];
// Copy vertices except the first 'nv' verts which are equal to nav poly verts.
if (ndv-nv)
{
memcpy(&navDVerts[vbase*3], &params->detailVerts[(vb+nv)*3], sizeof(float)*3*(ndv-nv));
vbase += (unsigned short)(ndv-nv);
}
}
// Store triangles.
memcpy(navDTris, params->detailTris, sizeof(unsigned char)*4*params->detailTriCount);
}
else
{
// Create dummy detail mesh by triangulating polys.
int tbase = 0;
for (int i = 0; i < params->polyCount; ++i)
{
dtPolyDetail& dtl = navDMeshes[i];
const int nv = navPolys[i].vertCount;
dtl.vertBase = 0;
dtl.vertCount = 0;
dtl.triBase = (unsigned int)tbase;
dtl.triCount = (unsigned char)(nv-2);
// Triangulate polygon (local indices).
for (int j = 2; j < nv; ++j)
{
unsigned char* t = &navDTris[tbase*4];
t[0] = 0;
t[1] = (unsigned char)(j-1);
t[2] = (unsigned char)j;
// Bit for each edge that belongs to poly boundary.
t[3] = (1<<2);
if (j == 2) t[3] |= (1<<0);
if (j == nv-1) t[3] |= (1<<4);
tbase++;
}
}
}
// Store and create BVtree.
if (params->buildBvTree)
{
createBVTree(params, navBvtree, 2*params->polyCount);
}
// Store Off-Mesh connections.
n = 0;
for (int i = 0; i < params->offMeshConCount; ++i)
{
// Only store connections which start from this tile.
if (offMeshConClass[i*2+0] == 0xff)
{
dtOffMeshConnection* con = &offMeshCons[n];
con->poly = (unsigned short)(offMeshPolyBase + n);
// Copy connection end-points.
const float* endPts = &params->offMeshConVerts[i*2*3];
dtVcopy(&con->pos[0], &endPts[0]);
dtVcopy(&con->pos[3], &endPts[3]);
con->rad = params->offMeshConRad[i];
con->flags = params->offMeshConDir[i] ? DT_OFFMESH_CON_BIDIR : 0;
con->side = offMeshConClass[i*2+1];
if (params->offMeshConUserID)
con->userId = params->offMeshConUserID[i];
n++;
}
}
dtFree(offMeshConClass);
*outData = data;
*outDataSize = dataSize;
return true;
}
bool dtNavMeshHeaderSwapEndian(unsigned char* data, const int /*dataSize*/)
{
dtMeshHeader* header = (dtMeshHeader*)data;
int swappedMagic = DT_NAVMESH_MAGIC;
int swappedVersion = DT_NAVMESH_VERSION;
dtSwapEndian(&swappedMagic);
dtSwapEndian(&swappedVersion);
if ((header->magic != DT_NAVMESH_MAGIC || header->version != DT_NAVMESH_VERSION) &&
(header->magic != swappedMagic || header->version != swappedVersion))
{
return false;
}
dtSwapEndian(&header->magic);
dtSwapEndian(&header->version);
dtSwapEndian(&header->x);
dtSwapEndian(&header->y);
dtSwapEndian(&header->layer);
dtSwapEndian(&header->userId);
dtSwapEndian(&header->polyCount);
dtSwapEndian(&header->vertCount);
dtSwapEndian(&header->maxLinkCount);
dtSwapEndian(&header->detailMeshCount);
dtSwapEndian(&header->detailVertCount);
dtSwapEndian(&header->detailTriCount);
dtSwapEndian(&header->bvNodeCount);
dtSwapEndian(&header->offMeshConCount);
dtSwapEndian(&header->offMeshBase);
dtSwapEndian(&header->walkableHeight);
dtSwapEndian(&header->walkableRadius);
dtSwapEndian(&header->walkableClimb);
dtSwapEndian(&header->bmin[0]);
dtSwapEndian(&header->bmin[1]);
dtSwapEndian(&header->bmin[2]);
dtSwapEndian(&header->bmax[0]);
dtSwapEndian(&header->bmax[1]);
dtSwapEndian(&header->bmax[2]);
dtSwapEndian(&header->bvQuantFactor);
// Freelist index and pointers are updated when tile is added, no need to swap.
return true;
}
/// @par
///
/// @warning This function assumes that the header is in the correct endianness already.
/// Call #dtNavMeshHeaderSwapEndian() first on the data if the data is expected to be in wrong endianness
/// to start with. Call #dtNavMeshHeaderSwapEndian() after the data has been swapped if converting from
/// native to foreign endianness.
bool dtNavMeshDataSwapEndian(unsigned char* data, const int /*dataSize*/)
{
// Make sure the data is in right format.
dtMeshHeader* header = (dtMeshHeader*)data;
if (header->magic != DT_NAVMESH_MAGIC)
return false;
if (header->version != DT_NAVMESH_VERSION)
return false;
// Patch header pointers.
const int headerSize = dtAlign4(sizeof(dtMeshHeader));
const int vertsSize = dtAlign4(sizeof(float)*3*header->vertCount);
const int polysSize = dtAlign4(sizeof(dtPoly)*header->polyCount);
const int linksSize = dtAlign4(sizeof(dtLink)*(header->maxLinkCount));
const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*header->detailMeshCount);
const int detailVertsSize = dtAlign4(sizeof(float)*3*header->detailVertCount);
const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*header->detailTriCount);
const int bvtreeSize = dtAlign4(sizeof(dtBVNode)*header->bvNodeCount);
const int offMeshLinksSize = dtAlign4(sizeof(dtOffMeshConnection)*header->offMeshConCount);
unsigned char* d = data + headerSize;
float* verts = dtGetThenAdvanceBufferPointer<float>(d, vertsSize);
dtPoly* polys = dtGetThenAdvanceBufferPointer<dtPoly>(d, polysSize);
d += linksSize; // Ignore links; they technically should be endian-swapped but all their data is overwritten on load anyway.
//dtLink* links = dtGetThenAdvanceBufferPointer<dtLink>(d, linksSize);
dtPolyDetail* detailMeshes = dtGetThenAdvanceBufferPointer<dtPolyDetail>(d, detailMeshesSize);
float* detailVerts = dtGetThenAdvanceBufferPointer<float>(d, detailVertsSize);
d += detailTrisSize; // Ignore detail tris; single bytes can't be endian-swapped.
//unsigned char* detailTris = dtGetThenAdvanceBufferPointer<unsigned char>(d, detailTrisSize);
dtBVNode* bvTree = dtGetThenAdvanceBufferPointer<dtBVNode>(d, bvtreeSize);
dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer<dtOffMeshConnection>(d, offMeshLinksSize);
// Vertices
for (int i = 0; i < header->vertCount*3; ++i)
{
dtSwapEndian(&verts[i]);
}
// Polys
for (int i = 0; i < header->polyCount; ++i)
{
dtPoly* p = &polys[i];
// poly->firstLink is update when tile is added, no need to swap.
for (int j = 0; j < DT_VERTS_PER_POLYGON; ++j)
{
dtSwapEndian(&p->verts[j]);
dtSwapEndian(&p->neis[j]);
}
dtSwapEndian(&p->flags);
}
// Links are rebuild when tile is added, no need to swap.
// Detail meshes
for (int i = 0; i < header->detailMeshCount; ++i)
{
dtPolyDetail* pd = &detailMeshes[i];
dtSwapEndian(&pd->vertBase);
dtSwapEndian(&pd->triBase);
}
// Detail verts
for (int i = 0; i < header->detailVertCount*3; ++i)
{
dtSwapEndian(&detailVerts[i]);
}
// BV-tree
for (int i = 0; i < header->bvNodeCount; ++i)
{
dtBVNode* node = &bvTree[i];
for (int j = 0; j < 3; ++j)
{
dtSwapEndian(&node->bmin[j]);
dtSwapEndian(&node->bmax[j]);
}
dtSwapEndian(&node->i);
}
// Off-mesh Connections.
for (int i = 0; i < header->offMeshConCount; ++i)
{
dtOffMeshConnection* con = &offMeshCons[i];
for (int j = 0; j < 6; ++j)
dtSwapEndian(&con->pos[j]);
dtSwapEndian(&con->rad);
dtSwapEndian(&con->poly);
}
return true;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,200 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include "DetourNode.h"
#include "DetourAlloc.h"
#include "DetourAssert.h"
#include "DetourCommon.h"
#include <string.h>
#ifdef DT_POLYREF64
// From Thomas Wang, https://gist.github.com/badboy/6267743
inline unsigned int dtHashRef(dtPolyRef a)
{
a = (~a) + (a << 18); // a = (a << 18) - a - 1;
a = a ^ (a >> 31);
a = a * 21; // a = (a + (a << 2)) + (a << 4);
a = a ^ (a >> 11);
a = a + (a << 6);
a = a ^ (a >> 22);
return (unsigned int)a;
}
#else
inline unsigned int dtHashRef(dtPolyRef a)
{
a += ~(a<<15);
a ^= (a>>10);
a += (a<<3);
a ^= (a>>6);
a += ~(a<<11);
a ^= (a>>16);
return (unsigned int)a;
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////
dtNodePool::dtNodePool(int maxNodes, int hashSize) :
m_nodes(0),
m_first(0),
m_next(0),
m_maxNodes(maxNodes),
m_hashSize(hashSize),
m_nodeCount(0)
{
dtAssert(dtNextPow2(m_hashSize) == (unsigned int)m_hashSize);
// pidx is special as 0 means "none" and 1 is the first node. For that reason
// we have 1 fewer nodes available than the number of values it can contain.
dtAssert(m_maxNodes > 0 && m_maxNodes <= DT_NULL_IDX && m_maxNodes <= (1 << DT_NODE_PARENT_BITS) - 1);
m_nodes = (dtNode*)dtAlloc(sizeof(dtNode)*m_maxNodes, DT_ALLOC_PERM);
m_next = (dtNodeIndex*)dtAlloc(sizeof(dtNodeIndex)*m_maxNodes, DT_ALLOC_PERM);
m_first = (dtNodeIndex*)dtAlloc(sizeof(dtNodeIndex)*hashSize, DT_ALLOC_PERM);
dtAssert(m_nodes);
dtAssert(m_next);
dtAssert(m_first);
memset(m_first, 0xff, sizeof(dtNodeIndex)*m_hashSize);
memset(m_next, 0xff, sizeof(dtNodeIndex)*m_maxNodes);
}
dtNodePool::~dtNodePool()
{
dtFree(m_nodes);
dtFree(m_next);
dtFree(m_first);
}
void dtNodePool::clear()
{
memset(m_first, 0xff, sizeof(dtNodeIndex)*m_hashSize);
m_nodeCount = 0;
}
unsigned int dtNodePool::findNodes(dtPolyRef id, dtNode** nodes, const int maxNodes)
{
int n = 0;
unsigned int bucket = dtHashRef(id) & (m_hashSize-1);
dtNodeIndex i = m_first[bucket];
while (i != DT_NULL_IDX)
{
if (m_nodes[i].id == id)
{
if (n >= maxNodes)
return n;
nodes[n++] = &m_nodes[i];
}
i = m_next[i];
}
return n;
}
dtNode* dtNodePool::findNode(dtPolyRef id, unsigned char state)
{
unsigned int bucket = dtHashRef(id) & (m_hashSize-1);
dtNodeIndex i = m_first[bucket];
while (i != DT_NULL_IDX)
{
if (m_nodes[i].id == id && m_nodes[i].state == state)
return &m_nodes[i];
i = m_next[i];
}
return 0;
}
dtNode* dtNodePool::getNode(dtPolyRef id, unsigned char state)
{
unsigned int bucket = dtHashRef(id) & (m_hashSize-1);
dtNodeIndex i = m_first[bucket];
dtNode* node = 0;
while (i != DT_NULL_IDX)
{
if (m_nodes[i].id == id && m_nodes[i].state == state)
return &m_nodes[i];
i = m_next[i];
}
if (m_nodeCount >= m_maxNodes)
return 0;
i = (dtNodeIndex)m_nodeCount;
m_nodeCount++;
// Init node
node = &m_nodes[i];
node->pidx = 0;
node->cost = 0;
node->total = 0;
node->id = id;
node->state = state;
node->flags = 0;
m_next[i] = m_first[bucket];
m_first[bucket] = i;
return node;
}
//////////////////////////////////////////////////////////////////////////////////////////
dtNodeQueue::dtNodeQueue(int n) :
m_heap(0),
m_capacity(n),
m_size(0)
{
dtAssert(m_capacity > 0);
m_heap = (dtNode**)dtAlloc(sizeof(dtNode*)*(m_capacity+1), DT_ALLOC_PERM);
dtAssert(m_heap);
}
dtNodeQueue::~dtNodeQueue()
{
dtFree(m_heap);
}
void dtNodeQueue::bubbleUp(int i, dtNode* node)
{
int parent = (i-1)/2;
// note: (index > 0) means there is a parent
while ((i > 0) && (m_heap[parent]->total > node->total))
{
m_heap[i] = m_heap[parent];
i = parent;
parent = (i-1)/2;
}
m_heap[i] = node;
}
void dtNodeQueue::trickleDown(int i, dtNode* node)
{
int child = (i*2)+1;
while (child < m_size)
{
if (((child+1) < m_size) &&
(m_heap[child]->total > m_heap[child+1]->total))
{
child++;
}
m_heap[i] = m_heap[child];
i = child;
child = (i*2)+1;
}
bubbleUp(i, node);
}
+18
View File
@@ -0,0 +1,18 @@
Copyright (c) 2009 Mikko Mononen [email protected]
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,391 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef RECASTALLOC_H
#define RECASTALLOC_H
#include "RecastAssert.h"
#include <stdlib.h>
#include <stdint.h>
/// Provides hint values to the memory allocator on how long the
/// memory is expected to be used.
enum rcAllocHint
{
RC_ALLOC_PERM, ///< Memory will persist after a function call.
RC_ALLOC_TEMP ///< Memory used temporarily within a function.
};
/// A memory allocation function.
/// @param[in] size The size, in bytes of memory, to allocate.
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
/// @see rcAllocSetCustom
typedef void* (rcAllocFunc)(size_t size, rcAllocHint hint);
/// A memory deallocation function.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAllocFunc.
/// @see rcAllocSetCustom
typedef void (rcFreeFunc)(void* ptr);
/// Sets the base custom allocation functions to be used by Recast.
/// @param[in] allocFunc The memory allocation function to be used by #rcAlloc
/// @param[in] freeFunc The memory de-allocation function to be used by #rcFree
/// @see rcAlloc, rcFree
void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc);
/// Allocates a memory block.
/// @param[in] size The size, in bytes of memory, to allocate.
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
/// @see rcFree, rcAllocSetCustom
void* rcAlloc(size_t size, rcAllocHint hint);
/// Deallocates a memory block. If @p ptr is NULL, this does nothing.
/// @warning This function leaves the value of @p ptr unchanged. So it still
/// points to the same (now invalid) location, and not to null.
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
/// @see rcAlloc, rcAllocSetCustom
void rcFree(void* ptr);
/// An implementation of operator new usable for placement new. The default one is part of STL (which we don't use).
/// rcNewTag is a dummy type used to differentiate our operator from the STL one, in case users import both Recast
/// and STL.
struct rcNewTag {};
inline void* operator new(size_t, const rcNewTag&, void* p) { return p; }
inline void operator delete(void*, const rcNewTag&, void*) {}
/// Signed to avoid warnings when comparing to int loop indexes, and common error with comparing to zero.
/// MSVC2010 has a bug where ssize_t is unsigned (!!!).
typedef intptr_t rcSizeType;
#define RC_SIZE_MAX INTPTR_MAX
/// Macros to hint to the compiler about the likeliest branch. Please add a benchmark that demonstrates a performance
/// improvement before introducing use cases.
#if defined(__GNUC__) || defined(__clang__)
#define rcLikely(x) __builtin_expect((x), true)
#define rcUnlikely(x) __builtin_expect((x), false)
#else
#define rcLikely(x) (x)
#define rcUnlikely(x) (x)
#endif
/// Variable-sized storage type. Mimics the interface of std::vector<T> with some notable differences:
/// * Uses rcAlloc()/rcFree() to handle storage.
/// * No support for a custom allocator.
/// * Uses signed size instead of size_t to avoid warnings in for loops: "for (int i = 0; i < foo.size(); i++)"
/// * Omits methods of limited utility: insert/erase, (bad performance), at (we don't use exceptions), operator=.
/// * assign() and the pre-sizing constructor follow C++11 semantics -- they don't construct a temporary if no value is provided.
/// * push_back() and resize() support adding values from the current vector. Range-based constructors and assign(begin, end) do not.
/// * No specialization for bool.
template <typename T, rcAllocHint H>
class rcVectorBase
{
rcSizeType m_size;
rcSizeType m_cap;
T* m_data;
// Constructs a T at the give address with either the copy constructor or the default.
static void construct(T* p, const T& v) { ::new(rcNewTag(), (void*)p) T(v); }
static void construct(T* p) { ::new(rcNewTag(), (void*)p) T; }
static void construct_range(T* begin, T* end);
static void construct_range(T* begin, T* end, const T& value);
static void copy_range(T* dst, const T* begin, const T* end);
void destroy_range(rcSizeType begin, rcSizeType end);
// Creates an array of the given size, copies all of this vector's data into it, and returns it.
T* allocate_and_copy(rcSizeType size);
void resize_impl(rcSizeType size, const T* value);
// Requires: min_capacity > m_cap.
rcSizeType get_new_capacity(rcSizeType min_capacity);
public:
typedef rcSizeType size_type;
typedef T value_type;
rcVectorBase() : m_size(0), m_cap(0), m_data(0) {}
rcVectorBase(const rcVectorBase<T, H>& other) : m_size(0), m_cap(0), m_data(0) { assign(other.begin(), other.end()); }
explicit rcVectorBase(rcSizeType count) : m_size(0), m_cap(0), m_data(0) { resize(count); }
rcVectorBase(rcSizeType count, const T& value) : m_size(0), m_cap(0), m_data(0) { resize(count, value); }
rcVectorBase(const T* begin, const T* end) : m_size(0), m_cap(0), m_data(0) { assign(begin, end); }
~rcVectorBase() { destroy_range(0, m_size); rcFree(m_data); }
// Unlike in std::vector, we return a bool to indicate whether the alloc was successful.
bool reserve(rcSizeType size);
void assign(rcSizeType count, const T& value) { clear(); resize(count, value); }
void assign(const T* begin, const T* end);
void resize(rcSizeType size) { resize_impl(size, NULL); }
void resize(rcSizeType size, const T& value) { resize_impl(size, &value); }
// Not implemented as resize(0) because resize requires T to be default-constructible.
void clear() { destroy_range(0, m_size); m_size = 0; }
void push_back(const T& value);
void pop_back() { rcAssert(m_size > 0); back().~T(); m_size--; }
rcSizeType size() const { return m_size; }
rcSizeType capacity() const { return m_cap; }
bool empty() const { return size() == 0; }
const T& operator[](rcSizeType i) const { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
T& operator[](rcSizeType i) { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
const T& front() const { rcAssert(m_size); return m_data[0]; }
T& front() { rcAssert(m_size); return m_data[0]; }
const T& back() const { rcAssert(m_size); return m_data[m_size - 1]; }
T& back() { rcAssert(m_size); return m_data[m_size - 1]; }
const T* data() const { return m_data; }
T* data() { return m_data; }
T* begin() { return m_data; }
T* end() { return m_data + m_size; }
const T* begin() const { return m_data; }
const T* end() const { return m_data + m_size; }
void swap(rcVectorBase<T, H>& other);
// Explicitly deleted.
rcVectorBase& operator=(const rcVectorBase<T, H>& other);
};
template<typename T, rcAllocHint H>
bool rcVectorBase<T, H>::reserve(rcSizeType count)
{
if (count <= m_cap)
{
return true;
}
T* new_data = allocate_and_copy(count);
if (!new_data)
{
return false;
}
destroy_range(0, m_size);
rcFree(m_data);
m_data = new_data;
m_cap = count;
return true;
}
template <typename T, rcAllocHint H>
T* rcVectorBase<T, H>::allocate_and_copy(rcSizeType size)
{
rcAssert(RC_SIZE_MAX / static_cast<rcSizeType>(sizeof(T)) >= size);
T* new_data = static_cast<T*>(rcAlloc(sizeof(T) * size, H));
if (new_data)
{
copy_range(new_data, m_data, m_data + m_size);
}
return new_data;
}
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::assign(const T* begin, const T* end)
{
clear();
reserve(end - begin);
m_size = end - begin;
copy_range(m_data, begin, end);
}
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::push_back(const T& value)
{
// rcLikely increases performance by ~50% on BM_rcVector_PushPreallocated,
// and by ~2-5% on BM_rcVector_Push.
if (rcLikely(m_size < m_cap))
{
construct(m_data + m_size++, value);
return;
}
const rcSizeType new_cap = get_new_capacity(m_cap + 1);
T* data = allocate_and_copy(new_cap);
// construct between allocate and destroy+free in case value is
// in this vector.
construct(data + m_size, value);
destroy_range(0, m_size);
m_size++;
m_cap = new_cap;
rcFree(m_data);
m_data = data;
}
template <typename T, rcAllocHint H>
rcSizeType rcVectorBase<T, H>::get_new_capacity(rcSizeType min_capacity)
{
rcAssert(min_capacity <= RC_SIZE_MAX);
if (rcUnlikely(m_cap >= RC_SIZE_MAX / 2))
{
return RC_SIZE_MAX;
}
return 2 * m_cap > min_capacity ? 2 * m_cap : min_capacity;
}
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::resize_impl(rcSizeType size, const T* value)
{
if (size < m_size)
{
destroy_range(size, m_size);
m_size = size;
}
else if (size > m_size)
{
if (size <= m_cap)
{
if (value)
{
construct_range(m_data + m_size, m_data + size, *value);
}
else
{
construct_range(m_data + m_size, m_data + size);
}
m_size = size;
}
else
{
const rcSizeType new_cap = get_new_capacity(size);
T* new_data = allocate_and_copy(new_cap);
// We defer deconstructing/freeing old data until after constructing
// new elements in case "value" is there.
if (value)
{
construct_range(new_data + m_size, new_data + size, *value);
}
else
{
construct_range(new_data + m_size, new_data + size);
}
destroy_range(0, m_size);
rcFree(m_data);
m_data = new_data;
m_cap = new_cap;
m_size = size;
}
}
}
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::swap(rcVectorBase<T, H>& other)
{
// TODO: Reorganize headers so we can use rcSwap here.
rcSizeType tmp_cap = other.m_cap;
rcSizeType tmp_size = other.m_size;
T* tmp_data = other.m_data;
other.m_cap = m_cap;
other.m_size = m_size;
other.m_data = m_data;
m_cap = tmp_cap;
m_size = tmp_size;
m_data = tmp_data;
}
// static
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::construct_range(T* begin, T* end)
{
for (T* p = begin; p < end; p++)
{
construct(p);
}
}
// static
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::construct_range(T* begin, T* end, const T& value)
{
for (T* p = begin; p < end; p++)
{
construct(p, value);
}
}
// static
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::copy_range(T* dst, const T* begin, const T* end)
{
for (rcSizeType i = 0 ; i < end - begin; i++)
{
construct(dst + i, begin[i]);
}
}
template <typename T, rcAllocHint H>
void rcVectorBase<T, H>::destroy_range(rcSizeType begin, rcSizeType end)
{
for (rcSizeType i = begin; i < end; i++)
{
m_data[i].~T();
}
}
template <typename T>
class rcTempVector : public rcVectorBase<T, RC_ALLOC_TEMP>
{
typedef rcVectorBase<T, RC_ALLOC_TEMP> Base;
public:
rcTempVector() : Base() {}
explicit rcTempVector(rcSizeType size) : Base(size) {}
rcTempVector(rcSizeType size, const T& value) : Base(size, value) {}
rcTempVector(const rcTempVector<T>& other) : Base(other) {}
rcTempVector(const T* begin, const T* end) : Base(begin, end) {}
};
template <typename T>
class rcPermVector : public rcVectorBase<T, RC_ALLOC_PERM>
{
typedef rcVectorBase<T, RC_ALLOC_PERM> Base;
public:
rcPermVector() : Base() {}
explicit rcPermVector(rcSizeType size) : Base(size) {}
rcPermVector(rcSizeType size, const T& value) : Base(size, value) {}
rcPermVector(const rcPermVector<T>& other) : Base(other) {}
rcPermVector(const T* begin, const T* end) : Base(begin, end) {}
};
/// A simple helper class used to delete an array when it goes out of scope.
/// @note This class is rarely if ever used by the end user.
template<class T> class rcScopedDelete
{
T* ptr;
public:
/// Constructs an instance with a null pointer.
inline rcScopedDelete() : ptr(0) {}
/// Constructs an instance with the specified pointer.
/// @param[in] p An pointer to an allocated array.
inline rcScopedDelete(T* p) : ptr(p) {}
inline ~rcScopedDelete() { rcFree(ptr); }
/// The root array pointer.
/// @return The root array pointer.
inline operator T*() { return ptr; }
private:
// Explicitly disabled copy constructor and copy assignment operator.
rcScopedDelete(const rcScopedDelete&);
rcScopedDelete& operator=(const rcScopedDelete&);
};
#endif
@@ -0,0 +1,49 @@
//
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef RECASTASSERT_H
#define RECASTASSERT_H
/// An assertion failure callback function.
/// @param[in] expression Asserted expression.
/// @param[in] file Filename of the failed assertion.
/// @param[in] line Line number of the failed assertion.
/// @see rcAssertFailSetCustom
typedef void (rcAssertFailFunc)(const char* expression, const char* file, int line);
/// Sets the base custom assertion failure callback function to be used by Recast.
/// @param[in] assertFailFunc The function to be used in case of failure of #dtAssert
void rcAssertFailSetCustom(rcAssertFailFunc* assertFailFunc);
/// Gets the base custom assertion failure function to be used by Recast.
rcAssertFailFunc* rcAssertFailGetCustom();
#ifdef RC_DISABLE_ASSERTS
// From https://web.archive.org/web/20210117002833/http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
# define rcAssert(x) do { (void)sizeof(x); } while ((void)(__LINE__==-1), false)
#else
# include <assert.h>
# define rcAssert(expression) \
{ \
rcAssertFailFunc* failFunc = rcAssertFailGetCustom(); \
if (failFunc == NULL) { assert(expression); } \
else if (!(expression)) { (*failFunc)(#expression, __FILE__, __LINE__); } \
}
#endif // !defined(RC_DISABLE_ASSERTS)
#endif // RECASTASSERT_H
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more