+
+
+ {t.toFixed(1)} s / {battle.endT.toFixed(0)} s
+ onSeek(Number(e.target.value))}
+ />
+
+
行为拒绝开火炮塔依据
+
+ );
+}
diff --git a/apps/ai-lab/src/data.ts b/apps/ai-lab/src/data.ts
new file mode 100644
index 0000000..cfee8cc
--- /dev/null
+++ b/apps/ai-lab/src/data.ts
@@ -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 {
+ 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 {
+ return (await (await get('/api/maps')).json()) as MapEntry[];
+}
+
+export async function fetchLogs(): Promise {
+ return (await (await get('/api/logs')).json()) as LogEntry[];
+}
+
+export async function loadLog(name: string): Promise {
+ const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text();
+ return parseTraceLog(text);
+}
+
+export async function loadMap(entry: MapEntry): Promise {
+ 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 };
+}
diff --git a/apps/ai-lab/src/frames.ts b/apps/ai-lab/src/frames.ts
new file mode 100644
index 0000000..09fa89b
--- /dev/null
+++ b/apps/ai-lab/src/frames.ts
@@ -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;
+ 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();
+ 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;
+}
diff --git a/apps/ai-lab/src/labels.ts b/apps/ai-lab/src/labels.ts
new file mode 100644
index 0000000..b3fde12
--- /dev/null
+++ b/apps/ai-lab/src/labels.ts
@@ -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> = {
+ 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>, code: number): string {
+ const name = Array.isArray(names) ? names[code] : (names as Readonly>)[code];
+ return name ?? String(code);
+}
diff --git a/apps/ai-lab/src/main.tsx b/apps/ai-lab/src/main.tsx
new file mode 100644
index 0000000..90c7cf0
--- /dev/null
+++ b/apps/ai-lab/src/main.tsx
@@ -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();
diff --git a/apps/ai-lab/src/mapLayer.ts b/apps/ai-lab/src/mapLayer.ts
new file mode 100644
index 0000000..2c40b5a
--- /dev/null
+++ b/apps/ai-lab/src/mapLayer.ts
@@ -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> = {
+ 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();
+ }
+}
diff --git a/apps/ai-lab/src/style.css b/apps/ai-lab/src/style.css
new file mode 100644
index 0000000..f439f6d
--- /dev/null
+++ b/apps/ai-lab/src/style.css
@@ -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; }
diff --git a/apps/ai-lab/src/three/cameraRig.ts b/apps/ai-lab/src/three/cameraRig.ts
new file mode 100644
index 0000000..20f4b99
--- /dev/null
+++ b/apps/ai-lab/src/three/cameraRig.ts
@@ -0,0 +1,119 @@
+/**
+ * The 3D view's cameras: a top-down orthographic map view (world +z up the screen, like the old
+ * flat map), a free perspective view, a view that follows the selected vehicle, and a view out of
+ * its muzzle along the barrel.
+ */
+import { OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from 'three';
+import { MapControls } from 'three/addons/controls/MapControls.js';
+import type { Tank } from './tanks.ts';
+
+export type ViewMode = 'top' | 'free' | 'follow' | 'gun';
+
+const TOP_HEIGHT = 3000;
+/** Top-down camera sits this far south of its target, so the controls keep north up. */
+const TOP_SOUTH = 0.01;
+const FREE_MAX_POLAR = Math.PI * 0.49;
+
+export class CameraRig {
+ readonly persp = new PerspectiveCamera(50, 1, 0.5, 20000);
+ readonly ortho = new OrthographicCamera(-1, 1, 1, -1, 1, 10000);
+ readonly controls: MapControls;
+ private mode: ViewMode = 'top';
+ private aspect = 1;
+ private readonly lastFollow = new Vector3();
+ private following = false;
+
+ constructor(dom: HTMLElement) {
+ this.controls = new MapControls(this.ortho, dom);
+ this.controls.enableDamping = true;
+ this.controls.dampingFactor = 0.15;
+ this.controls.screenSpacePanning = true;
+ this.limitTilt();
+ }
+
+ /** Top-down stays straight down; the other views may tilt down to just above the horizon. */
+ private limitTilt(): void {
+ this.controls.maxPolarAngle = this.mode === 'top' ? 0 : FREE_MAX_POLAR;
+ }
+
+ get camera(): Camera {
+ return this.mode === 'top' ? this.ortho : this.persp;
+ }
+
+ resize(w: number, h: number): void {
+ this.aspect = w / Math.max(1, h);
+ this.persp.aspect = this.aspect;
+ this.persp.updateProjectionMatrix();
+ const half = (this.ortho.top - this.ortho.bottom) / 2;
+ this.ortho.left = -half * this.aspect;
+ this.ortho.right = half * this.aspect;
+ this.ortho.updateProjectionMatrix();
+ }
+
+ /** Frames the world rectangle (x, z) in both cameras. */
+ fit(minX: number, minZ: number, maxX: number, maxZ: number, groundY: number): void {
+ const cx = (minX + maxX) / 2;
+ const cz = -(minZ + maxZ) / 2;
+ const half = (Math.max((maxX - minX) / this.aspect, maxZ - minZ) / 2) * 1.05;
+ Object.assign(this.ortho, { left: -half * this.aspect, right: half * this.aspect, top: half, bottom: -half, zoom: 1 });
+ this.ortho.updateProjectionMatrix();
+ this.ortho.position.set(cx, groundY + TOP_HEIGHT, cz + TOP_SOUTH);
+ this.persp.position.set(cx, groundY + half * 0.9, cz + half * 1.1);
+ this.controls.target.set(cx, groundY, cz);
+ this.ortho.lookAt(this.controls.target);
+ this.persp.lookAt(this.controls.target);
+ this.controls.update();
+ }
+
+ setMode(mode: ViewMode): void {
+ if (mode === this.mode) return;
+ const target = this.controls.target.clone();
+ if (this.mode === 'top' && mode !== 'gun') {
+ const span = (this.ortho.top - this.ortho.bottom) / this.ortho.zoom;
+ this.persp.position.set(target.x, target.y + span * 0.6, target.z + span * 0.6);
+ }
+ if (mode === 'top') this.ortho.position.set(target.x, target.y + TOP_HEIGHT, target.z + TOP_SOUTH);
+ this.mode = mode;
+ this.limitTilt();
+ this.following = false;
+ this.controls.object = this.camera;
+ this.controls.enableRotate = mode !== 'top';
+ this.controls.enabled = mode !== 'gun';
+ this.camera.lookAt(target);
+ this.controls.update();
+ }
+
+ /** The next follow frame starts over around the (newly) selected vehicle. */
+ refollow(): void {
+ this.following = false;
+ }
+
+ /** Per frame: keeps the followed vehicle centred, or puts the camera at the muzzle. */
+ tick(tank: Tank | undefined): void {
+ if (this.mode === 'follow' && tank !== undefined && tank.root.visible) {
+ const at = tank.root.position;
+ if (!this.following) {
+ this.controls.target.copy(at);
+ this.persp.position.set(at.x - 25, at.y + 15, at.z + 25);
+ this.following = true;
+ } else {
+ const d = at.clone().sub(this.lastFollow);
+ this.controls.target.add(d);
+ this.persp.position.add(d);
+ }
+ this.lastFollow.copy(at);
+ } else if (this.mode === 'gun' && tank !== undefined && tank.root.visible) {
+ const q = tank.barrel.getWorldQuaternion(new Quaternion());
+ const dir = new Vector3(1, 0, 0).applyQuaternion(q);
+ const tip = tank.barrel.getWorldPosition(new Vector3()).addScaledVector(dir, tank.length * 0.8);
+ this.persp.position.copy(tip);
+ this.persp.lookAt(tip.clone().add(dir));
+ return;
+ }
+ if (this.controls.enabled) this.controls.update();
+ }
+
+ dispose(): void {
+ this.controls.dispose();
+ }
+}
diff --git a/apps/ai-lab/src/three/coords.ts b/apps/ai-lab/src/three/coords.ts
new file mode 100644
index 0000000..ad9c3a6
--- /dev/null
+++ b/apps/ai-lab/src/three/coords.ts
@@ -0,0 +1,18 @@
+/**
+ * Game world to three.js: Dagor is left-handed with Y up, three.js right-handed, so world z is
+ * mirrored (three z = -world z). A world heading (degrees of atan2(z, x)) then becomes the same
+ * angle of rotation about three's +Y, and a model's local +X is its front, +Y up, -Z its left.
+ */
+import { Vector3 } from 'three';
+
+export const DEG = Math.PI / 180;
+
+export function toThree(x: number, y: number, z: number, out: Vector3 = new Vector3()): Vector3 {
+ return out.set(x, y, -z);
+}
+
+/** Three.js direction of a world heading and pitch, in degrees. */
+export function dirOf(yawDeg: number, pitchDeg: number, out: Vector3 = new Vector3()): Vector3 {
+ const c = Math.cos(pitchDeg * DEG);
+ return out.set(Math.cos(yawDeg * DEG) * c, Math.sin(pitchDeg * DEG), -Math.sin(yawDeg * DEG) * c);
+}
diff --git a/apps/ai-lab/src/three/mapMeshes.ts b/apps/ai-lab/src/three/mapMeshes.ts
new file mode 100644
index 0000000..c163833
--- /dev/null
+++ b/apps/ai-lab/src/three/mapMeshes.ts
@@ -0,0 +1,134 @@
+/**
+ * The static 3D map: lit terrain (coloured by height, or draped with the navigation mesh image),
+ * the collision shapes of placed objects coloured by kind, and the water plane.
+ */
+import type { MapScene, SceneTerrain } from '@wto/ground-sim';
+import {
+ BufferAttribute, BufferGeometry, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshLambertMaterial,
+ PlaneGeometry, SRGBColorSpace, type Material,
+} from 'three';
+import type { MapLayer } from '../mapLayer.ts';
+
+/** Colour and opacity per SCENE_KIND_NAMES entry. */
+const KIND_LOOK: readonly (readonly [number, number])[] = [
+ [0xb9b2a3, 1], [0x7d7a74, 1], [0x9a7b55, 1], [0xe09a4a, 0.4], [0x4f8a3c, 1], [0x6f8aa0, 1],
+];
+
+const LOW = new Color(0x3c4a32);
+const HIGH = new Color(0x9b9171);
+
+export interface MapMeshes {
+ readonly group: Group;
+ readonly terrain: Mesh;
+ /** Objects per scene kind, to switch kinds on and off. */
+ readonly kinds: Group[];
+ dispose(): void;
+}
+
+function terrainGeometry(t: SceneTerrain, nav: MapLayer | undefined): BufferGeometry {
+ const n = t.cols * t.rows;
+ const pos = new Float32Array(n * 3);
+ const col = new Float32Array(n * 3);
+ const uv = new Float32Array(n * 2);
+ let lo = Infinity;
+ let hi = -Infinity;
+ for (const h of t.heights) { lo = Math.min(lo, h); hi = Math.max(hi, h); }
+ const c = new Color();
+ const navW = nav === undefined ? 1 : nav.canvas.width / nav.pxPerM;
+ const navH = nav === undefined ? 1 : nav.canvas.height / nav.pxPerM;
+ for (let r = 0; r < t.rows; r++) {
+ for (let k = 0; k < t.cols; k++) {
+ const i = r * t.cols + k;
+ const x = t.origin[0] + k * t.cellM;
+ const z = t.origin[1] + r * t.cellM;
+ const h = t.heights[i] ?? 0;
+ pos.set([x, h, -z], i * 3);
+ c.lerpColors(LOW, HIGH, hi > lo ? (h - lo) / (hi - lo) : 0);
+ col.set([c.r, c.g, c.b], i * 3);
+ if (nav !== undefined) uv.set([(x - nav.x0) / navW, (z - (nav.z1 - navH)) / navH], i * 2);
+ }
+ }
+ const idx = new Uint32Array((t.cols - 1) * (t.rows - 1) * 6);
+ let at = 0;
+ for (let r = 0; r + 1 < t.rows; r++) {
+ for (let k = 0; k + 1 < t.cols; k++) {
+ const i = r * t.cols + k;
+ idx.set([i, i + 1, i + t.cols, i + 1, i + t.cols + 1, i + t.cols], at);
+ at += 6;
+ }
+ }
+ const g = new BufferGeometry();
+ g.setAttribute('position', new BufferAttribute(pos, 3));
+ g.setAttribute('color', new BufferAttribute(col, 3));
+ g.setAttribute('uv', new BufferAttribute(uv, 2));
+ g.setIndex(new BufferAttribute(idx, 1));
+ g.computeVertexNormals();
+ return g;
+}
+
+/** Drapes the navigation image over the terrain, or goes back to height colours. */
+export function setTerrainImage(m: MapMeshes, nav: MapLayer | undefined): void {
+ const mat = m.terrain.material;
+ mat.map?.dispose();
+ if (nav === undefined) {
+ mat.map = null;
+ mat.vertexColors = true;
+ } else {
+ const tex = new CanvasTexture(nav.canvas);
+ tex.colorSpace = SRGBColorSpace;
+ tex.anisotropy = 8;
+ mat.map = tex;
+ mat.vertexColors = false;
+ }
+ mat.needsUpdate = true;
+}
+
+function objectKinds(scene: MapScene, materials: Material[]): Group[] {
+ const kinds = KIND_LOOK.map(() => new Group());
+ const mats = KIND_LOOK.map(([color, opacity]) => new MeshLambertMaterial({
+ color, flatShading: true, side: DoubleSide, transparent: opacity < 1, opacity, depthWrite: opacity >= 1,
+ }));
+ materials.push(...mats);
+ for (const m of scene.meshes) {
+ const g = new BufferGeometry();
+ const pos = new Float32Array(m.positions);
+ for (let i = 2; i < pos.length; i += 3) pos[i] = -(pos[i] ?? 0);
+ g.setAttribute('position', new BufferAttribute(pos, 3));
+ g.setIndex(new BufferAttribute(m.indices, 1));
+ g.computeBoundingSphere();
+ const mat = mats[m.kind] ?? mats[0];
+ if (mat !== undefined) kinds[m.kind]?.add(new Mesh(g, mat));
+ }
+ return kinds;
+}
+
+export function buildMapMeshes(scene: MapScene, nav: MapLayer | undefined): MapMeshes {
+ const group = new Group();
+ const materials: Material[] = [];
+ const terrainMat = new MeshLambertMaterial({ vertexColors: true });
+ materials.push(terrainMat);
+ const terrain = new Mesh(terrainGeometry(scene.terrain, nav), terrainMat);
+ group.add(terrain);
+ const kinds = objectKinds(scene, materials);
+ for (const k of kinds) group.add(k);
+ if (scene.waterLevel !== undefined) {
+ const w = scene.boundsMax[0] - scene.boundsMin[0];
+ const d = scene.boundsMax[1] - scene.boundsMin[1];
+ const waterMat = new MeshLambertMaterial({ color: 0x2d5f8a, transparent: true, opacity: 0.55, depthWrite: false });
+ materials.push(waterMat);
+ const water = new Mesh(new PlaneGeometry(w, d), waterMat);
+ water.rotation.x = -Math.PI / 2;
+ water.position.set(scene.boundsMin[0] + w / 2, scene.waterLevel, -(scene.boundsMin[1] + d / 2));
+ group.add(water);
+ }
+ const meshes: MapMeshes = {
+ group, terrain, kinds,
+ dispose() {
+ group.traverse((o) => { if (o instanceof Mesh) (o.geometry as BufferGeometry).dispose(); });
+ terrainMat.map?.dispose();
+ for (const m of materials) m.dispose();
+ },
+ };
+ if (nav !== undefined) setTerrainImage(meshes, nav);
+ return meshes;
+}
diff --git a/apps/ai-lab/src/three/overlays.ts b/apps/ai-lab/src/three/overlays.ts
new file mode 100644
index 0000000..762f67c
--- /dev/null
+++ b/apps/ai-lab/src/three/overlays.ts
@@ -0,0 +1,182 @@
+/**
+ * What is drawn over the map for one moment, rebuilt every update: goal, target and look lines,
+ * the gun's view cone, recent shots and hits, deaths so far, and the capture zones.
+ */
+import type { TraceBattle } from '@wto/ground-sim';
+import {
+ AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Group, LineBasicMaterial,
+ LineSegments, Mesh, MeshBasicMaterial, Points, PointsMaterial,
+} from 'three';
+import { eventsBetween, type SceneAt, type UnitAt } from '../frames.ts';
+import { DEG } from './coords.ts';
+import { ARMY_HEX, type TankPool } from './tanks.ts';
+
+export interface Layers {
+ readonly goals: boolean;
+ readonly links: boolean;
+ readonly cones: boolean;
+ readonly labels: boolean;
+ readonly events: boolean;
+}
+
+const GUN_FOV_HALF_DEG = 30;
+const CONE_M = 120;
+const CONE_STEPS = 12;
+const EVENT_WINDOW_SEC = 2;
+const CAP_STEPS = 64;
+const WISH_M = 25;
+
+/** Line segments with per-vertex colour, refilled from scratch on every update. */
+class Lines {
+ readonly obj: LineSegments;
+ private pos: number[] = [];
+ private col: number[] = [];
+
+ constructor(opacity: number, additive = false) {
+ const mat = new LineBasicMaterial({ vertexColors: true, transparent: true, opacity, depthTest: !additive });
+ if (additive) mat.blending = AdditiveBlending;
+ this.obj = new LineSegments(new BufferGeometry(), mat);
+ this.obj.frustumCulled = false;
+ }
+
+ add(ax: number, ay: number, az: number, bx: number, by: number, bz: number, c: Color): void {
+ this.pos.push(ax, ay, -az, bx, by, -bz);
+ this.col.push(c.r, c.g, c.b, c.r, c.g, c.b);
+ }
+
+ flush(): void {
+ const g = this.obj.geometry;
+ g.setAttribute('position', new BufferAttribute(Float32Array.from(this.pos), 3));
+ g.setAttribute('color', new BufferAttribute(Float32Array.from(this.col), 3));
+ g.computeBoundingSphere();
+ this.pos = [];
+ this.col = [];
+ }
+}
+
+const C = {
+ goal: new Color(0x9aa4ad), target: new Color(0xff4646), targetLost: new Color(0x803030),
+ look: new Color(0xffa028), wish: new Color(0xffe14a), shot: new Color(0xffff78), dead1: new Color(ARMY_HEX[1]),
+ dead2: new Color(ARMY_HEX[2]), cap: new Color(0xdddddd),
+};
+
+export class Overlays {
+ readonly group = new Group();
+ private readonly faint = new Lines(0.35);
+ private readonly bold = new Lines(0.9);
+ private readonly shots = new Lines(1, true);
+ private readonly cones: Mesh;
+ private readonly hits: Points;
+
+ constructor(private readonly tanks: TankPool) {
+ this.cones = new Mesh(new BufferGeometry(), new MeshBasicMaterial({
+ color: 0xffffc8, transparent: true, opacity: 0.08, side: DoubleSide, depthWrite: false,
+ }));
+ this.cones.frustumCulled = false;
+ this.hits = new Points(new BufferGeometry(), new PointsMaterial({ size: 6, sizeAttenuation: false, vertexColors: true }));
+ this.hits.frustumCulled = false;
+ this.group.add(this.faint.obj, this.bold.obj, this.shots.obj, this.cones, this.hits);
+ }
+
+ /** Height where lines leave a vehicle: its turret top. */
+ private eye(u: UnitAt): number {
+ return this.tanks.groundY(u.x, u.y, u.z) + (this.tanks.get(u.unit.eid)?.eyeY ?? 2);
+ }
+
+ update(battle: TraceBattle, scene: SceneAt, layers: Layers): void {
+ const cone: number[] = [];
+ for (const u of scene.units.values()) this.botLines(u, scene, layers, cone);
+ if (layers.events) this.events(battle, scene);
+ this.deaths(battle, scene.t);
+ this.caps(scene);
+ const g = this.cones.geometry;
+ g.setAttribute('position', new BufferAttribute(Float32Array.from(cone), 3));
+ this.faint.flush();
+ this.bold.flush();
+ this.shots.flush();
+ }
+
+ private botLines(u: UnitAt, scene: SceneAt, layers: Layers, cone: number[]): void {
+ const bot = u.bot;
+ if (bot === undefined || !u.unit.alive) return;
+ const y = this.eye(u);
+ if (layers.goals && bot.hasOrder) this.faint.add(u.x, y, u.z, bot.goalX, this.tanks.terrainY(bot.goalX, bot.goalZ) + 1, bot.goalZ, C.goal);
+ const wy = bot.wishYaw * DEG;
+ this.bold.add(u.x, y, u.z, u.x + Math.cos(wy) * WISH_M, y, u.z + Math.sin(wy) * WISH_M, C.wish);
+ if (layers.cones) {
+ for (let i = 0; i < CONE_STEPS; i++) {
+ const a = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * i) / CONE_STEPS) * DEG;
+ const b = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * (i + 1)) / CONE_STEPS) * DEG;
+ cone.push(u.x, y, -u.z, u.x + Math.cos(a) * CONE_M, y, -(u.z + Math.sin(a) * CONE_M),
+ u.x + Math.cos(b) * CONE_M, y, -(u.z + Math.sin(b) * CONE_M));
+ }
+ }
+ if (!layers.links) return;
+ const target = scene.units.get(bot.target);
+ if (target !== undefined && bot.target !== '0') {
+ (bot.targetInSight ? this.bold : this.faint).add(u.x, y, u.z, target.x, this.eye(target), target.z,
+ bot.targetInSight ? C.target : C.targetLost);
+ }
+ const look = scene.units.get(bot.lookAt);
+ if (look !== undefined && bot.lookAt !== bot.target) this.bold.add(u.x, y, u.z, look.x, this.eye(look), look.z, C.look);
+ }
+
+ private events(battle: TraceBattle, scene: SceneAt): void {
+ const pos: number[] = [];
+ const col: number[] = [];
+ const c = new Color();
+ for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) {
+ const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC;
+ if (e.kind === 'SHOT' && e.eid !== undefined) {
+ const from = scene.units.get(e.eid);
+ const to = scene.units.get(e.fields['tgt'] ?? '');
+ if (from === undefined || to === undefined) continue;
+ this.shots.add(from.x, this.eye(from), from.z, to.x, this.eye(to) - 1, to.z, c.copy(C.shot).multiplyScalar(fade));
+ } else if (e.kind === 'HIT') {
+ const x = Number(e.fields['x']);
+ const z = Number(e.fields['z']);
+ pos.push(x, this.tanks.terrainY(x, z) + 1.5, -z);
+ c.set(e.fields['drop'] === '1' ? 0xff3c3c : 0xc8c8c8).multiplyScalar(fade);
+ col.push(c.r, c.g, c.b);
+ }
+ }
+ this.hits.geometry.setAttribute('position', new BufferAttribute(Float32Array.from(pos), 3));
+ this.hits.geometry.setAttribute('color', new BufferAttribute(Float32Array.from(col), 3));
+ }
+
+ private deaths(battle: TraceBattle, t: number): void {
+ for (const e of eventsBetween(battle, battle.startT, t)) {
+ if (e.kind !== 'DEATH') continue;
+ const x = Number(e.fields['x']);
+ const z = Number(e.fields['z']);
+ const y = this.tanks.terrainY(x, z) + 0.5;
+ const c = e.fields['army'] === '1' ? C.dead1 : C.dead2;
+ this.faint.add(x - 4, y, z - 4, x + 4, y, z + 4, c);
+ this.faint.add(x - 4, y, z + 4, x + 4, y, z - 4, c);
+ }
+ }
+
+ private caps(scene: SceneAt): void {
+ for (const cap of scene.caps) {
+ const c = new Color(ARMY_HEX[cap.owner] ?? C.cap.getHex());
+ for (let i = 0; i < CAP_STEPS; i++) {
+ const a = (i / CAP_STEPS) * Math.PI * 2;
+ const b = ((i + 1) / CAP_STEPS) * Math.PI * 2;
+ const ax = cap.x + Math.cos(a) * cap.r;
+ const az = cap.z + Math.sin(a) * cap.r;
+ const bx = cap.x + Math.cos(b) * cap.r;
+ const bz = cap.z + Math.sin(b) * cap.r;
+ this.bold.add(ax, this.tanks.terrainY(ax, az) + 0.8, az, bx, this.tanks.terrainY(bx, bz) + 0.8, bz, c);
+ }
+ }
+ }
+
+ dispose(): void {
+ this.group.traverse((o) => {
+ if (o instanceof Mesh || o instanceof LineSegments || o instanceof Points) {
+ o.geometry.dispose();
+ (o.material as { dispose(): void }).dispose();
+ }
+ });
+ }
+}
diff --git a/apps/ai-lab/src/three/tanks.ts b/apps/ai-lab/src/three/tanks.ts
new file mode 100644
index 0000000..93117dd
--- /dev/null
+++ b/apps/ai-lab/src/three/tanks.ts
@@ -0,0 +1,141 @@
+/**
+ * Every vehicle as simple shapes: a hull box tilted by the hull's pitch and roll, a turret box
+ * turned to the gun's heading, and a barrel at the gun's pitch. Sizes come from the bot's vehicle
+ * class (players: light or medium).
+ */
+import { sceneHeightAt, type SceneTerrain } from '@wto/ground-sim';
+import {
+ BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshLambertMaterial, type Object3D,
+} from 'three';
+import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
+import type { UnitAt } from '../frames.ts';
+import { DEG } from './coords.ts';
+
+/** Length, width, hull height per vehicle class (medium, light, heavy, tank destroyer, SPAA). */
+const SIZES: readonly (readonly [number, number, number])[] = [
+ [7, 3.4, 1.3], [6, 3, 1.1], [7.6, 3.6, 1.4], [7, 3.3, 1.2], [6.5, 3.1, 1.2],
+];
+
+export const ARMY_HEX: Readonly> = { 1: 0x4aa3ff, 2: 0xff5c5c };
+const DEAD = new Color(0x4a4a4a);
+const SELECTED = new Color(0x6a5200);
+const NONE = new Color(0);
+
+/** A trace height further than this from the terrain is kept (bridge, building, platform). */
+const OFF_GROUND_M = 1.5;
+
+export interface Tank {
+ readonly root: Group;
+ readonly turret: Group;
+ readonly barrel: Group;
+ readonly label: CSS2DObject;
+ readonly mats: MeshLambertMaterial[];
+ /** Turret top above the hull origin, where lines and the gun camera start. */
+ readonly eyeY: number;
+ readonly length: number;
+}
+
+function sizeOf(u: UnitAt): readonly [number, number, number] {
+ const cls = u.bot?.vehicleClass ?? (u.unit.light ? 1 : 0);
+ return SIZES[cls] ?? SIZES[0] ?? [7, 3.4, 1.3];
+}
+
+function makeTank(u: UnitAt): Tank {
+ const [len, wid, hh] = sizeOf(u);
+ const hullMat = new MeshLambertMaterial();
+ const turretMat = new MeshLambertMaterial();
+ const root = new Group();
+ root.rotation.order = 'YZX';
+ const hull = new Mesh(new BoxGeometry(len, hh, wid), hullMat);
+ hull.position.y = hh / 2;
+ const turret = new Group();
+ turret.position.set(-len * 0.05, hh, 0);
+ const tw = wid * 0.7;
+ const th = hh * 0.65;
+ const turretBox = new Mesh(new BoxGeometry(len * 0.48, th, tw), turretMat);
+ turretBox.position.y = th / 2;
+ const barrel = new Group();
+ barrel.position.set(len * 0.2, th * 0.55, 0);
+ const tube = new Mesh(new CylinderGeometry(0.09, 0.11, len * 0.75, 8), turretMat);
+ tube.rotation.z = -Math.PI / 2;
+ tube.position.x = len * 0.375;
+ barrel.add(tube);
+ turret.add(turretBox, barrel);
+ root.add(hull, turret);
+ const div = document.createElement('div');
+ div.className = 'tank-label';
+ const label = new CSS2DObject(div);
+ label.position.y = hh + th + 2.5;
+ root.add(label);
+ for (const m of [hull, turretBox, tube]) m.userData['eid'] = u.unit.eid;
+ return { root, turret, barrel, label, mats: [hullMat, turretMat], eyeY: hh + th, length: len };
+}
+
+export class TankPool {
+ readonly group = new Group();
+ private readonly tanks = new Map();
+
+ constructor(private readonly terrain: SceneTerrain | undefined) {}
+
+ get(eid: string): Tank | undefined {
+ return this.tanks.get(eid);
+ }
+
+ /** Meshes to pick with a ray. */
+ pickables(): Object3D[] {
+ const out: Object3D[] = [];
+ for (const t of this.tanks.values()) if (t.root.visible) t.root.traverse((o) => { if (o instanceof Mesh) out.push(o); });
+ return out;
+ }
+
+ terrainY(x: number, z: number): number {
+ return this.terrain === undefined ? 0 : sceneHeightAt(this.terrain, x, z);
+ }
+
+ /** Ground height for the vehicle: the terrain unless the trace puts it clearly above or below. */
+ groundY(x: number, y: number, z: number): number {
+ if (this.terrain === undefined) return y;
+ const g = sceneHeightAt(this.terrain, x, z);
+ return Math.abs(y - g) <= OFF_GROUND_M ? g : y;
+ }
+
+ update(units: ReadonlyMap, selected: string | undefined, labels: (u: UnitAt) => string | undefined): void {
+ for (const [eid, t] of this.tanks) if (!units.has(eid)) t.root.visible = false;
+ for (const u of units.values()) {
+ let t = this.tanks.get(u.unit.eid);
+ if (t === undefined) {
+ t = makeTank(u);
+ this.tanks.set(u.unit.eid, t);
+ this.group.add(t.root);
+ }
+ this.place(t, u, u.unit.eid === selected, labels(u));
+ }
+ }
+
+ private place(t: Tank, u: UnitAt, selected: boolean, label: string | undefined): void {
+ t.root.visible = true;
+ t.root.position.set(u.x, this.groundY(u.x, u.y, u.z), -u.z);
+ t.root.rotation.set(u.hullRoll * DEG, u.yaw * DEG, u.hullPitch * DEG);
+ const rel = ((((u.gunYaw - u.yaw) % 360) + 540) % 360) - 180;
+ t.turret.rotation.y = rel * DEG;
+ const hullSlope = u.hullPitch * Math.cos(rel * DEG) + u.hullRoll * Math.sin(rel * DEG);
+ t.barrel.rotation.z = (u.gunPitch - hullSlope) * DEG;
+ const base = u.unit.alive ? new Color(ARMY_HEX[u.unit.army] ?? 0xcccccc) : DEAD;
+ t.mats.forEach((m, i) => {
+ m.color.copy(base).multiplyScalar(i === 0 ? 1 : 0.8);
+ m.emissive.copy(selected ? SELECTED : NONE);
+ });
+ t.label.visible = label !== undefined;
+ if (label !== undefined) t.label.element.textContent = label;
+ if (u.unit.human) t.label.element.classList.add('human');
+ }
+
+ dispose(): void {
+ for (const t of this.tanks.values()) {
+ t.root.traverse((o) => { if (o instanceof Mesh) o.geometry.dispose(); });
+ for (const m of t.mats) m.dispose();
+ t.label.element.remove();
+ }
+ this.tanks.clear();
+ }
+}
diff --git a/apps/ai-lab/tsconfig.json b/apps/ai-lab/tsconfig.json
new file mode 100644
index 0000000..1cb6c15
--- /dev/null
+++ b/apps/ai-lab/tsconfig.json
@@ -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"]
+}
diff --git a/apps/ai-lab/vite.config.ts b/apps/ai-lab/vite.config.ts
new file mode 100644
index 0000000..9df6a8a
--- /dev/null
+++ b/apps/ai-lab/vite.config.ts
@@ -0,0 +1,8 @@
+import react from '@vitejs/plugin-react';
+import { defineConfig } from 'vite';
+import { labApi } from './server/lab-api.ts';
+
+export default defineConfig({
+ plugins: [react(), labApi()],
+ server: { host: '127.0.0.1', port: 47180, strictPort: false },
+});
diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json
index 7b65b5d..b36eafe 100644
--- a/apps/launcher/src/renderer/src/i18n/locales/en.json
+++ b/apps/launcher/src/renderer/src/i18n/locales/en.json
@@ -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.",
diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
index 614e852..17f8e77 100644
--- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
+++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
@@ -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": "这些数值适用于此客户端的全部存档。",
diff --git a/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx b/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx
index f6c7653..62ede43 100644
--- a/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx
+++ b/apps/launcher/src/renderer/src/pages/tuning/BotTuningPanel.tsx
@@ -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) {
diff --git a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts
index d818982..f66dd1d 100644
--- a/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts
+++ b/apps/launcher/src/renderer/src/pages/tuning/bot-tuning-fields.ts
@@ -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'),
],
},
];
diff --git a/apps/launcher/src/shared/schemas/tuning.ts b/apps/launcher/src/shared/schemas/tuning.ts
index 4ae2c15..d19d88f 100644
--- a/apps/launcher/src/shared/schemas/tuning.ts
+++ b/apps/launcher/src/shared/schemas/tuning.ts
@@ -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(),
});
diff --git a/apps/server/src/battle/battle-mission-settings.ts b/apps/server/src/battle/battle-mission-settings.ts
index a62b74a..7813a51 100644
--- a/apps/server/src/battle/battle-mission-settings.ts
+++ b/apps/server/src/battle/battle-mission-settings.ts
@@ -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));
diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts
index 1bb7e90..6871479 100644
--- a/apps/server/src/tuning/ground-ai-tuning.ts
+++ b/apps/server/src/tuning/ground-ai-tuning.ts
@@ -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 }),
diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc
index 9270c1d..7240d18 100644
--- a/apps/server/tuning/ground-ai.jsonc
+++ b/apps/server/tuning/ground-ai.jsonc
@@ -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
}
}
diff --git a/apps/server/tuning/maps/avg_berlin.jsonc b/apps/server/tuning/maps/avg_berlin.jsonc
new file mode 100644
index 0000000..8c6ce5b
--- /dev/null
+++ b/apps/server/tuning/maps/avg_berlin.jsonc
@@ -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]
+ }
+ ]
+ }
+}
diff --git a/apps/server/tuning/maps/avg_poland.jsonc b/apps/server/tuning/maps/avg_poland.jsonc
new file mode 100644
index 0000000..d2eb2af
--- /dev/null
+++ b/apps/server/tuning/maps/avg_poland.jsonc
@@ -0,0 +1,8 @@
+{
+ "level": "avg_poland",
+ "version": 1,
+ "bake": {
+ // The town streets and squares use this LMp2 material.
+ "roadMaterials": ["concrete"]
+ }
+}
diff --git a/game-ai/ground/wto_ai_ammo_common.das b/game-ai/ground/wto_ai_ammo_common.das
new file mode 100644
index 0000000..b678370
--- /dev/null
+++ b/game-ai/ground/wto_ai_ammo_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_avoid_common.das b/game-ai/ground/wto_ai_avoid_common.das
new file mode 100644
index 0000000..650bfbe
--- /dev/null
+++ b/game-ai/ground/wto_ai_avoid_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_behavior_common.das b/game-ai/ground/wto_ai_behavior_common.das
new file mode 100644
index 0000000..06ffbb4
--- /dev/null
+++ b/game-ai/ground/wto_ai_behavior_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das
index 14a0301..9174bb9 100644
--- a/game-ai/ground/wto_ai_combat_types_common.das
+++ b/game-ai/ground/wto_ai_combat_types_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_commander_common.das b/game-ai/ground/wto_ai_commander_common.das
index d766afd..dc332a2 100644
--- a/game-ai/ground/wto_ai_commander_common.das
+++ b/game-ai/ground/wto_ai_commander_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_diag_common.das b/game-ai/ground/wto_ai_diag_common.das
index d8348e5..db2205d 100644
--- a/game-ai/ground/wto_ai_diag_common.das
+++ b/game-ai/ground/wto_ai_diag_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das
index 20bf3b4..9c55198 100644
--- a/game-ai/ground/wto_ai_drive_common.das
+++ b/game-ai/ground/wto_ai_drive_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_estimate_common.das b/game-ai/ground/wto_ai_estimate_common.das
index 59fdb91..b496246 100644
--- a/game-ai/ground/wto_ai_estimate_common.das
+++ b/game-ai/ground/wto_ai_estimate_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_facing_common.das b/game-ai/ground/wto_ai_facing_common.das
new file mode 100644
index 0000000..88aabc1
--- /dev/null
+++ b/game-ai/ground/wto_ai_facing_common.das
@@ -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")
diff --git a/game-ai/ground/wto_ai_fire_aux_common.das b/game-ai/ground/wto_ai_fire_aux_common.das
new file mode 100644
index 0000000..2240389
--- /dev/null
+++ b/game-ai/ground/wto_ai_fire_aux_common.das
@@ -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 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
diff --git a/game-ai/ground/wto_ai_fire_checks_common.das b/game-ai/ground/wto_ai_fire_checks_common.das
new file mode 100644
index 0000000..d9de437
--- /dev/null
+++ b/game-ai/ground/wto_ai_fire_checks_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das
index 73bfcbd..517de9d 100644
--- a/game-ai/ground/wto_ai_fire_common.das
+++ b/game-ai/ground/wto_ai_fire_common.das
@@ -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 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)
diff --git a/game-ai/ground/wto_ai_fire_decide_common.das b/game-ai/ground/wto_ai_fire_decide_common.das
new file mode 100644
index 0000000..17ecda6
--- /dev/null
+++ b/game-ai/ground/wto_ai_fire_decide_common.das
@@ -0,0 +1,61 @@
+// Fire control decisions, free of weapons and turret objects so the simulator runs them as they
+// are: whether the bot engages its perceived target, whether it wants a soft shell, and where
+// the turret should look. wto_ai_fire_common reads the weapons and drives the turret around them.
+options indenting = 2
+options no_global_heap = true
+module wto_ai_fire_decide_common shared
+
+require ecs
+require math
+require %appGame.wtoai.wto_ai_config_common
+require %appGame.wtoai.wto_ai_math_common
+require %appGame.wtoai.wto_ai_combat_types_common
+require %appGame.wtoai.wto_ai_types_common
+require %appGame.wtoai.wto_ai_world_common
+require %appGame.wtoai.wto_ai_estimate_common
+require %appGame.wtoai.wto_ai_turret_common
+require %appGame.wtoai.wto_ai_trigger_common
+
+[never_inline]
+def public wto_fire_has_engagement(slot : WtoBotSlot const&) : bool
+ assume p = slot.perceive
+ let yielding = slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED
+ return p.hasClearLos && !!p.targetEid && !p.targetIsAir && !yielding && !wto_turret_prefers_threat(slot)
+
+def public wto_fire_wants_soft(world : WtoWorldSnap const&; slot : WtoBotSlot const&) : bool
+ if !slot.perceive.hasClearLos || slot.perceive.targetIsAir
+ return false
+ let idx = wto_world_find_unit(world, slot.perceive.targetEid)
+ return idx >= 0 && (world.units[idx].isLightTag || world.units[idx].halfWid < 1.35)
+
+def public wto_fire_clear_aim_tracking(var fc : WtoFireState&)
+ fc.aimTargetEid = INVALID_ENTITY_ID
+ fc.aimDriftDegSec = 0.0
+ fc.settleHoldSec = 0.0
+ fc.lastAligned = false
+ fc.lastDenyReason = WTO_DENY_NO_TARGET
+
+// No shot this frame: forget the aim tracking and lift the trigger's speed request.
+def public wto_fire_hold(var slot : WtoBotSlot&)
+ wto_fire_clear_aim_tracking(slot.fire)
+ slot.trigger.wantSpeedMps = 99.0
+ slot.trigger.wantSpeedAt = -100.0
+
+// Hands the trigger its target and returns the world direction the turret should point: the
+// ballistic solution on the engaged target, or the turret channel's look direction. Writes the
+// aim point and returns the distance to the target (9999 when not engaging).
+[never_inline]
+def public wto_fire_decide_aim(now : float; engage : bool; muzzlePos, unitPos, unitVel, hullFwd : float3;
+ var slot : WtoBotSlot&; var aimPt, wishDir : float3&) : float
+ wto_trig_set_target(engage ? slot.perceive.targetEid : INVALID_ENTITY_ID, slot.trigger)
+ var distToTgt = 9999.0
+ aimPt = muzzlePos
+ if engage
+ assume fc = slot.fire
+ distToTgt = wto_solve_ballistic_aim(muzzlePos, unitVel, slot.perceive.visibleAimPt, fc.activeSpeedMps, fc.activeDragCx,
+ fc.activeMassKg, fc.activeCaliberM, slot, aimPt, wishDir)
+ slot.turret.lookReason = WTO_LOOK_ENGAGE
+ else
+ wishDir = wto_turret_look_dir(now, muzzlePos, unitPos, hullFwd, slot)
+ slot.turret.wishDir = wishDir
+ return distToTgt
diff --git a/game-ai/ground/wto_ai_fire_gate_common.das b/game-ai/ground/wto_ai_fire_gate_common.das
index d39b049..169f526 100644
--- a/game-ai/ground/wto_ai_fire_gate_common.das
+++ b/game-ai/ground/wto_ai_fire_gate_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_fire_speed_common.das b/game-ai/ground/wto_ai_fire_speed_common.das
deleted file mode 100644
index 92f822f..0000000
--- a/game-ai/ground/wto_ai_fire_speed_common.das
+++ /dev/null
@@ -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)
diff --git a/game-ai/ground/wto_ai_follow_common.das b/game-ai/ground/wto_ai_follow_common.das
new file mode 100644
index 0000000..a3eceef
--- /dev/null
+++ b/game-ai/ground/wto_ai_follow_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_hull_aim_common.das b/game-ai/ground/wto_ai_hull_aim_common.das
new file mode 100644
index 0000000..2f950f7
--- /dev/null
+++ b/game-ai/ground/wto_ai_hull_aim_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_lanes_build_common.das b/game-ai/ground/wto_ai_lanes_build_common.das
new file mode 100644
index 0000000..a0b5e4a
--- /dev/null
+++ b/game-ai/ground/wto_ai_lanes_build_common.das
@@ -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
\ No newline at end of file
diff --git a/game-ai/ground/wto_ai_lanes_common.das b/game-ai/ground/wto_ai_lanes_common.das
index 25e52cf..99815d9 100644
--- a/game-ai/ground/wto_ai_lanes_common.das
+++ b/game-ai/ground/wto_ai_lanes_common.das
@@ -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#)
- 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")
diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das
index b59708c..569a85b 100644
--- a/game-ai/ground/wto_ai_nav_common.das
+++ b/game-ai/ground/wto_ai_nav_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_nav_types_common.das b/game-ai/ground/wto_ai_nav_types_common.das
new file mode 100644
index 0000000..41b5db9
--- /dev/null
+++ b/game-ai/ground/wto_ai_nav_types_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_navmesh_common.das b/game-ai/ground/wto_ai_navmesh_common.das
new file mode 100644
index 0000000..6e17912
--- /dev/null
+++ b/game-ai/ground/wto_ai_navmesh_common.das
@@ -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")
diff --git a/game-ai/ground/wto_ai_navquery_common.das b/game-ai/ground/wto_ai_navquery_common.das
new file mode 100644
index 0000000..626f01b
--- /dev/null
+++ b/game-ai/ground/wto_ai_navquery_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_perceive_common.das b/game-ai/ground/wto_ai_perceive_common.das
index afb560b..b7204ac 100644
--- a/game-ai/ground/wto_ai_perceive_common.das
+++ b/game-ai/ground/wto_ai_perceive_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_polyline_common.das b/game-ai/ground/wto_ai_polyline_common.das
new file mode 100644
index 0000000..e0e4428
--- /dev/null
+++ b/game-ai/ground/wto_ai_polyline_common.das
@@ -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]
diff --git a/game-ai/ground/wto_ai_route_common.das b/game-ai/ground/wto_ai_route_common.das
index 086eef2..14758b6 100644
--- a/game-ai/ground/wto_ai_route_common.das
+++ b/game-ai/ground/wto_ai_route_common.das
@@ -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#)
- 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)
\ No newline at end of file
diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das
index 0352ca4..9736d4d 100644
--- a/game-ai/ground/wto_ai_runtime.das
+++ b/game-ai/ground/wto_ai_runtime.das
@@ -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])
diff --git a/game-ai/ground/wto_ai_sight_common.das b/game-ai/ground/wto_ai_sight_common.das
index efa53bd..c816c98 100644
--- a/game-ai/ground/wto_ai_sight_common.das
+++ b/game-ai/ground/wto_ai_sight_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_slots_common.das b/game-ai/ground/wto_ai_slots_common.das
new file mode 100644
index 0000000..fe81acc
--- /dev/null
+++ b/game-ai/ground/wto_ai_slots_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_specs_common.das b/game-ai/ground/wto_ai_specs_common.das
index f132497..51e6c12 100644
--- a/game-ai/ground/wto_ai_specs_common.das
+++ b/game-ai/ground/wto_ai_specs_common.das
@@ -1,6 +1,6 @@
// Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per
// spawned bot (`gamedata/units/.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]
diff --git a/game-ai/ground/wto_ai_stats_common.das b/game-ai/ground/wto_ai_stats_common.das
new file mode 100644
index 0000000..bcbb6b7
--- /dev/null
+++ b/game-ai/ground/wto_ai_stats_common.das
@@ -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()
diff --git a/game-ai/ground/wto_ai_stockpath_common.das b/game-ai/ground/wto_ai_stockpath_common.das
new file mode 100644
index 0000000..146805c
--- /dev/null
+++ b/game-ai/ground/wto_ai_stockpath_common.das
@@ -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#)
+ 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
diff --git a/game-ai/ground/wto_ai_tactics_actions_common.das b/game-ai/ground/wto_ai_tactics_actions_common.das
index 39f772f..45bb656 100644
--- a/game-ai/ground/wto_ai_tactics_actions_common.das
+++ b/game-ai/ground/wto_ai_tactics_actions_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das
index 2282dc6..679c981 100644
--- a/game-ai/ground/wto_ai_tactics_common.das
+++ b/game-ai/ground/wto_ai_tactics_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_threat_common.das b/game-ai/ground/wto_ai_threat_common.das
new file mode 100644
index 0000000..0e6ccb0
--- /dev/null
+++ b/game-ai/ground/wto_ai_threat_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_trace_common.das b/game-ai/ground/wto_ai_trace_common.das
new file mode 100644
index 0000000..7e5ddee
--- /dev/null
+++ b/game-ai/ground/wto_ai_trace_common.das
@@ -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")
diff --git a/game-ai/ground/wto_ai_traffic_common.das b/game-ai/ground/wto_ai_traffic_common.das
new file mode 100644
index 0000000..334e139
--- /dev/null
+++ b/game-ai/ground/wto_ai_traffic_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_traffic_geometry_common.das b/game-ai/ground/wto_ai_traffic_geometry_common.das
new file mode 100644
index 0000000..8fce273
--- /dev/null
+++ b/game-ai/ground/wto_ai_traffic_geometry_common.das
@@ -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))
diff --git a/game-ai/ground/wto_ai_traverse_common.das b/game-ai/ground/wto_ai_traverse_common.das
index e24d3a6..907ccb6 100644
--- a/game-ai/ground/wto_ai_traverse_common.das
+++ b/game-ai/ground/wto_ai_traverse_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_trigger_common.das b/game-ai/ground/wto_ai_trigger_common.das
new file mode 100644
index 0000000..5705072
--- /dev/null
+++ b/game-ai/ground/wto_ai_trigger_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_turret_common.das b/game-ai/ground/wto_ai_turret_common.das
new file mode 100644
index 0000000..6084464
--- /dev/null
+++ b/game-ai/ground/wto_ai_turret_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das
index b30ed94..893614d 100644
--- a/game-ai/ground/wto_ai_types_common.das
+++ b/game-ai/ground/wto_ai_types_common.das
@@ -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()
diff --git a/game-ai/ground/wto_ai_unit_pose_common.das b/game-ai/ground/wto_ai_unit_pose_common.das
new file mode 100644
index 0000000..1e96a7d
--- /dev/null
+++ b/game-ai/ground/wto_ai_unit_pose_common.das
@@ -0,0 +1,30 @@
+// Live main-gun direction of any unit, bots and players alike, for the replay trace.
+options indenting = 2
+options no_global_heap = true
+module wto_ai_unit_pose_common shared
+
+require ecs
+require math
+require DagorMath
+require Unit
+require Weapon
+require %game.utils.utils_common
+require %appGame.wtoai.wto_ai_math_common
+
+// World direction of the first real primary weapon's barrel; false when the unit has none.
+[never_inline]
+def public wto_pose_gun_dir(unit : Unit const?; var outDir : float3&) : bool
+ if unit == null || unit.weap == null
+ return false
+ var sampled = false
+ get_weapons_by_trigger_group(unit.weap.Weapons, WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) <| $(weapons : array const#)
+ for weapon in weapons
+ if weapon == null || weapon.isDummyGun
+ continue
+ var gunTm : float3x4
+ weapon_calcShootTm(weapon, unit.unitTm, gunTm)
+ if wto_is_finite3(gunTm[0]) && length_sq(gunTm[0]) > 0.25
+ outDir = normalize(gunTm[0])
+ sampled = true
+ return
+ return sampled
diff --git a/game-ai/ground/wto_ai_unstick_common.das b/game-ai/ground/wto_ai_unstick_common.das
new file mode 100644
index 0000000..97e2fe2
--- /dev/null
+++ b/game-ai/ground/wto_ai_unstick_common.das
@@ -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)
diff --git a/game-ai/ground/wto_ai_weapon_profile_common.das b/game-ai/ground/wto_ai_weapon_profile_common.das
new file mode 100644
index 0000000..23d429b
--- /dev/null
+++ b/game-ai/ground/wto_ai_weapon_profile_common.das
@@ -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
diff --git a/game-ai/ground/wto_ai_world_common.das b/game-ai/ground/wto_ai_world_common.das
index 475be20..dd9cce7 100644
--- a/game-ai/ground/wto_ai_world_common.das
+++ b/game-ai/ground/wto_ai_world_common.das
@@ -1,19 +1,17 @@
-// World observation layer: builds one flat per-frame snapshot of units, wrecks,
-// capture zones, respawn anchors, and ring buffers for deaths, jams, and radio spots.
+// World observation layer: one flat per-frame snapshot of units, wrecks, capture zones, respawn
+// anchors, and ring buffers for deaths, jams, and radio spots. Filling it from the game is
+// wto_ai_world_refresh_common's job; this module only keeps and queries it, so the simulator
+// loads it unchanged.
options indenting = 2
options no_global_heap = true
module wto_ai_world_common shared
require ecs
require math
-require DagorMath
-require Unit
-require IGroundModel
-require HeavyVehicleModel
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_types_common
-require %appGame.wtoai.wto_ai_world_zones_common
+
[never_inline]
def public wto_world_reset(var snap : WtoWorldSnap&)
@@ -120,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
diff --git a/game-ai/ground/wto_ai_world_refresh_common.das b/game-ai/ground/wto_ai_world_refresh_common.das
new file mode 100644
index 0000000..6a2b00b
--- /dev/null
+++ b/game-ai/ground/wto_ai_world_refresh_common.das
@@ -0,0 +1,100 @@
+// Fills the world snapshot from the game's units every frame: live units with their pose (and
+// the gun on trace frames), wrecks, capture zones, battle bounds and spawns. Only the runtime
+// uses it; the simulator fills the same snapshot from its own world.
+options indenting = 2
+options no_global_heap = true
+module wto_ai_world_refresh_common shared
+
+require ecs
+require math
+require DagorMath
+require Unit
+require IGroundModel
+require HeavyVehicleModel
+require %appGame.wtoai.wto_ai_math_common
+require %appGame.wtoai.wto_ai_types_common
+require %appGame.wtoai.wto_ai_world_zones_common
+require %appGame.wtoai.wto_ai_unit_pose_common
+
+[never_inline]
+def private wto_record_wreck_once(var snap : WtoWorldSnap&; eid : EntityId; u : Unit const?; gm : IGroundModel const?)
+ if gm == null || snap.wreckCount >= WTO_MAX_WRECKS
+ return
+ let box = gm.bodyBoundingBox
+ let wIdx = snap.wreckCount
+ snap.wrecks[wIdx].eid = eid
+ snap.wrecks[wIdx].pos = u.pos
+ snap.wrecks[wIdx].hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0))
+ snap.wrecks[wIdx].halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x)))
+ snap.wrecks[wIdx].halfWid = max(1.1, max(abs(box.boxMin.z), abs(box.boxMax.z)))
+ snap.wreckCount = wIdx + 1
+
+// Pose of a live unit; the gun is read only on trace frames.
+def private wto_unit_pose(var su : WtoUnitSnap&; u : Unit const?; sampleGun : bool)
+ su.pos = u.pos
+ su.vel = u.vel
+ su.hullFwd = wto_xz_normalize(u.unitTm[0], float3(1.0, 0.0, 0.0))
+ su.hullFwd3 = u.unitTm[0]
+ su.hullLeft = u.unitTm[2]
+ su.hasGun = sampleGun && wto_pose_gun_dir(u, su.gunDir)
+
+[never_inline]
+def private wto_refresh_units(var snap : WtoWorldSnap&; sampleGuns : bool)
+ snap.unitCount = 0
+ snap.wreckCount = 0
+ let maxDistSq = wto_sq(max(snap.battleRadius * 2.5, 2200.0))
+ query() <| $ [es] (eid : EntityId; unit__ref : UnitRef)
+ let u = unit__ref.unit
+ if u == null || u.isDelayed
+ return
+ let gm = as_gm(u)
+ if snap.battleRadius > 1.0 && gm != null && wto_xz_dist_sq(u.pos, snap.battleCenter) > maxDistSq
+ return
+ if !u.isAlive
+ wto_record_wreck_once(snap, eid, u, gm)
+ return
+ if snap.unitCount >= WTO_MAX_UNITS
+ return
+ let army = int(u.army)
+ if army != 1 && army != 2
+ return
+ let isGround = gm != null && as_hv(u) != null
+ let isAir = u.isFlightModelWrap
+ if !isGround && !isAir
+ return
+ var halfLen = 3.4
+ var halfWid = 1.75
+ if gm != null
+ let box = gm.bodyBoundingBox
+ halfLen = max(1.8, max(abs(box.boxMin.x), abs(box.boxMax.x)))
+ halfWid = max(0.9, max(abs(box.boxMin.z), abs(box.boxMax.z)))
+ let idx = snap.unitCount
+ snap.units[idx].eid = eid
+ snap.units[idx].army = army
+ wto_unit_pose(snap.units[idx], u, sampleGuns && isGround)
+ snap.units[idx].halfLen = halfLen
+ snap.units[idx].halfWid = halfWid
+ snap.units[idx].engineRpm = gm != null ? clamp(abs(gm.engineRelativeRPM), 0.0, 1.2) : 0.0
+ snap.units[idx].isAlive = true
+ snap.units[idx].isGround = isGround
+ snap.units[idx].isAir = isAir
+ snap.units[idx].isLightTag = false
+ snap.units[idx].isShooting = gm != null && (gm.isShooting || gm.hasMissilesInFlight)
+ snap.units[idx].isBurn = u.isBurn
+ snap.units[idx].isHuman = u.isHumanPlayer
+ snap.unitCount = idx + 1
+ for i in range(snap.unitCount)
+ if snap.units[i].isGround
+ snap.units[i].isLightTag = has(snap.units[i].eid, "unit_tag__light_vehicle")
+
+[never_inline]
+def public wto_world_refresh(now : float; sampleGuns : bool; var snap : WtoWorldSnap&)
+ snap.time = now
+ if snap.matchStartAt < -50.0
+ snap.matchStartAt = now
+ wto_refresh_units(snap, sampleGuns)
+ if now >= snap.nextCapRefreshAt
+ snap.nextCapRefreshAt = now + 0.5
+ wto_world_refresh_caps(snap)
+ wto_world_refresh_bounds_and_spawns(snap)
+ snap.valid = true
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourAlloc.h b/native/third_party/recastnavigation/Detour/Include/DetourAlloc.h
new file mode 100644
index 0000000..f87b454
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourAlloc.h
@@ -0,0 +1,61 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+
+/// 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
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourAssert.h b/native/third_party/recastnavigation/Detour/Include/DetourAssert.h
new file mode 100644
index 0000000..ea58dd9
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourAssert.h
@@ -0,0 +1,56 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+# define dtAssert(expression) \
+ { \
+ dtAssertFailFunc* failFunc = dtAssertFailGetCustom(); \
+ if(failFunc == NULL) { assert(expression); } \
+ else if(!(expression)) { (*failFunc)(#expression, __FILE__, __LINE__); } \
+ }
+
+#endif
+
+#endif // DETOURASSERT_H
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourCommon.h b/native/third_party/recastnavigation/Detour/Include/DetourCommon.h
new file mode 100644
index 0000000..d54bc7e
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourCommon.h
@@ -0,0 +1,571 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+
+/**
+@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 void dtIgnoreUnused(const T&) { }
+
+/// Swaps the values of the two parameters.
+/// @param[in,out] a Value A
+/// @param[in,out] b Value B
+template 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 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 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 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 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 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
+TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(const unsigned char*& buffer, const size_t distanceToAdvance)
+{
+ TypeToRetrieveAs* returnPointer = reinterpret_cast(buffer);
+ buffer += distanceToAdvance;
+ return returnPointer;
+}
+
+template
+TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(unsigned char*& buffer, const size_t distanceToAdvance)
+{
+ TypeToRetrieveAs* returnPointer = reinterpret_cast(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.
+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:
+
+
+
The vertices are wrapped in the normal Detour wrap direction.
+
The triangle's 3D face normal is in the general up direction.
+
+
+A negative return value indicates:
+
+
+
The vertices are reverse wrapped. (Wrapped opposite the normal Detour wrap direction.)
+
The triangle's 3D face normal is in the general down direction.
+
+
+*/
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourMath.h b/native/third_party/recastnavigation/Detour/Include/DetourMath.h
new file mode 100644
index 0000000..eec89ce
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourMath.h
@@ -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
+
+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
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNavMesh.h b/native/third_party/recastnavigation/Detour/Include/DetourNavMesh.h
new file mode 100644
index 0000000..422a334
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourNavMesh.h
@@ -0,0 +1,781 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#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_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_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_POLY_BITS+DT_TILE_BITS)) & saltMask);
+#else
+ const dtPolyRef saltMask = ((dtPolyRef)1<> (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_POLY_BITS) & tileMask);
+#else
+ const dtPolyRef tileMask = ((dtPolyRef)1<> 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<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.
+
+*/
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNavMeshBuilder.h b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshBuilder.h
new file mode 100644
index 0000000..1840ab5
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshBuilder.h
@@ -0,0 +1,149 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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.
+ /// #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 init() function or the dtNavMesh::addTile()
+function.
+
+@see dtCreateNavMeshData
+
+*/
+
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNavMeshQuery.h b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshQuery.h
new file mode 100644
index 0000000..dd8150c
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourNavMeshQuery.h
@@ -0,0 +1,590 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourNode.h b/native/third_party/recastnavigation/Detour/Include/DetourNode.h
new file mode 100644
index 0000000..8918d46
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourNode.h
@@ -0,0 +1,168 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
diff --git a/native/third_party/recastnavigation/Detour/Include/DetourStatus.h b/native/third_party/recastnavigation/Detour/Include/DetourStatus.h
new file mode 100644
index 0000000..8e1bb44
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Include/DetourStatus.h
@@ -0,0 +1,65 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
diff --git a/native/third_party/recastnavigation/Detour/Source/DetourAlloc.cpp b/native/third_party/recastnavigation/Detour/Source/DetourAlloc.cpp
new file mode 100644
index 0000000..d9ad1fc
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Source/DetourAlloc.cpp
@@ -0,0 +1,50 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#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);
+}
diff --git a/native/third_party/recastnavigation/Detour/Source/DetourAssert.cpp b/native/third_party/recastnavigation/Detour/Source/DetourAssert.cpp
new file mode 100644
index 0000000..a9727a3
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Source/DetourAssert.cpp
@@ -0,0 +1,35 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
diff --git a/native/third_party/recastnavigation/Detour/Source/DetourCommon.cpp b/native/third_party/recastnavigation/Detour/Source/DetourCommon.cpp
new file mode 100644
index 0000000..b845782
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Source/DetourCommon.cpp
@@ -0,0 +1,387 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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;
+}
+
diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNavMesh.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNavMesh.cpp
new file mode 100644
index 0000000..ee868f2
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Source/DetourNavMesh.cpp
@@ -0,0 +1,1597 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include
+#include "DetourNavMesh.h"
+#include "DetourNode.h"
+#include "DetourCommon.h"
+#include "DetourMath.h"
+#include "DetourAlloc.h"
+#include "DetourAssert.h"
+#include
+
+
+inline bool overlapSlabs(const float* amin, const float* amax,
+ const float* bmin, const float* bmax,
+ const float px, const float py)
+{
+ // Check for horizontal overlap.
+ // The segment is shrunken a little so that slabs which touch
+ // at end points are not connected.
+ const float minx = dtMax(amin[0]+px,bmin[0]+px);
+ const float maxx = dtMin(amax[0]-px,bmax[0]-px);
+ if (minx > maxx)
+ return false;
+
+ // Check vertical overlap.
+ const float ad = (amax[1]-amin[1]) / (amax[0]-amin[0]);
+ const float ak = amin[1] - ad*amin[0];
+ const float bd = (bmax[1]-bmin[1]) / (bmax[0]-bmin[0]);
+ const float bk = bmin[1] - bd*bmin[0];
+ const float aminy = ad*minx + ak;
+ const float amaxy = ad*maxx + ak;
+ const float bminy = bd*minx + bk;
+ const float bmaxy = bd*maxx + bk;
+ const float dmin = bminy - aminy;
+ const float dmax = bmaxy - amaxy;
+
+ // Crossing segments always overlap.
+ if (dmin*dmax < 0)
+ return true;
+
+ // Check for overlap at endpoints.
+ const float thr = dtSqr(py*2);
+ if (dmin*dmin <= thr || dmax*dmax <= thr)
+ return true;
+
+ return false;
+}
+
+static float getSlabCoord(const float* va, const int side)
+{
+ if (side == 0 || side == 4)
+ return va[0];
+ else if (side == 2 || side == 6)
+ return va[2];
+ return 0;
+}
+
+static void calcSlabEndPoints(const float* va, const float* vb, float* bmin, float* bmax, const int side)
+{
+ if (side == 0 || side == 4)
+ {
+ if (va[2] < vb[2])
+ {
+ bmin[0] = va[2];
+ bmin[1] = va[1];
+ bmax[0] = vb[2];
+ bmax[1] = vb[1];
+ }
+ else
+ {
+ bmin[0] = vb[2];
+ bmin[1] = vb[1];
+ bmax[0] = va[2];
+ bmax[1] = va[1];
+ }
+ }
+ else if (side == 2 || side == 6)
+ {
+ if (va[0] < vb[0])
+ {
+ bmin[0] = va[0];
+ bmin[1] = va[1];
+ bmax[0] = vb[0];
+ bmax[1] = vb[1];
+ }
+ else
+ {
+ bmin[0] = vb[0];
+ bmin[1] = vb[1];
+ bmax[0] = va[0];
+ bmax[1] = va[1];
+ }
+ }
+}
+
+inline int computeTileHash(int x, int y, const int mask)
+{
+ const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
+ const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
+ unsigned int n = h1 * x + h2 * y;
+ return (int)(n & mask);
+}
+
+inline unsigned int allocLink(dtMeshTile* tile)
+{
+ if (tile->linksFreeList == DT_NULL_LINK)
+ return DT_NULL_LINK;
+ unsigned int link = tile->linksFreeList;
+ tile->linksFreeList = tile->links[link].next;
+ return link;
+}
+
+inline void freeLink(dtMeshTile* tile, unsigned int link)
+{
+ tile->links[link].next = tile->linksFreeList;
+ tile->linksFreeList = link;
+}
+
+
+dtNavMesh* dtAllocNavMesh()
+{
+ void* mem = dtAlloc(sizeof(dtNavMesh), DT_ALLOC_PERM);
+ if (!mem) return 0;
+ return new(mem) dtNavMesh;
+}
+
+/// @par
+///
+/// This function will only free the memory for tiles with the #DT_TILE_FREE_DATA
+/// flag set.
+void dtFreeNavMesh(dtNavMesh* navmesh)
+{
+ if (!navmesh) return;
+ navmesh->~dtNavMesh();
+ dtFree(navmesh);
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////
+
+/**
+@class dtNavMesh
+
+The navigation mesh consists of one or more tiles defining three primary types of structural data:
+
+A polygon mesh which defines most of the navigation graph. (See rcPolyMesh for its structure.)
+A detail mesh used for determining surface height on the polygon mesh. (See rcPolyMeshDetail for its structure.)
+Off-mesh connections, which define custom point-to-point edges within the navigation graph.
+
+The general build process is as follows:
+
+-# Create rcPolyMesh and rcPolyMeshDetail data using the Recast build pipeline.
+-# Optionally, create off-mesh connection data.
+-# Combine the source data into a dtNavMeshCreateParams structure.
+-# Create a tile data array using dtCreateNavMeshData().
+-# Allocate at dtNavMesh object and initialize it. (For single tile navigation meshes,
+ the tile data is loaded during this step.)
+-# For multi-tile navigation meshes, load the tile data using dtNavMesh::addTile().
+
+Notes:
+
+- This class is usually used in conjunction with the dtNavMeshQuery class for pathfinding.
+- Technically, all navigation meshes are tiled. A 'solo' mesh is simply a navigation mesh initialized
+ to have only a single tile.
+- This class does not implement any asynchronous methods. So the ::dtStatus result of all methods will
+ always contain either a success or failure flag.
+
+@see dtNavMeshQuery, dtCreateNavMeshData, dtNavMeshCreateParams, #dtAllocNavMesh, #dtFreeNavMesh
+*/
+
+dtNavMesh::dtNavMesh() :
+ m_tileWidth(0),
+ m_tileHeight(0),
+ m_maxTiles(0),
+ m_tileLutSize(0),
+ m_tileLutMask(0),
+ m_posLookup(0),
+ m_nextFree(0),
+ m_tiles(0)
+{
+#ifndef DT_POLYREF64
+ m_saltBits = 0;
+ m_tileBits = 0;
+ m_polyBits = 0;
+#endif
+ memset(&m_params, 0, sizeof(dtNavMeshParams));
+ m_orig[0] = 0;
+ m_orig[1] = 0;
+ m_orig[2] = 0;
+}
+
+dtNavMesh::~dtNavMesh()
+{
+ for (int i = 0; i < m_maxTiles; ++i)
+ {
+ if (m_tiles[i].flags & DT_TILE_FREE_DATA)
+ {
+ dtFree(m_tiles[i].data);
+ m_tiles[i].data = 0;
+ m_tiles[i].dataSize = 0;
+ }
+ }
+ dtFree(m_posLookup);
+ dtFree(m_tiles);
+}
+
+dtStatus dtNavMesh::init(const dtNavMeshParams* params)
+{
+ memcpy(&m_params, params, sizeof(dtNavMeshParams));
+ dtVcopy(m_orig, params->orig);
+ m_tileWidth = params->tileWidth;
+ m_tileHeight = params->tileHeight;
+
+ // Init tiles
+ m_maxTiles = params->maxTiles;
+ m_tileLutSize = dtNextPow2(params->maxTiles/4);
+ if (!m_tileLutSize) m_tileLutSize = 1;
+ m_tileLutMask = m_tileLutSize-1;
+
+ m_tiles = (dtMeshTile*)dtAlloc(sizeof(dtMeshTile)*m_maxTiles, DT_ALLOC_PERM);
+ if (!m_tiles)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+ m_posLookup = (dtMeshTile**)dtAlloc(sizeof(dtMeshTile*)*m_tileLutSize, DT_ALLOC_PERM);
+ if (!m_posLookup)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+ memset(m_tiles, 0, sizeof(dtMeshTile)*m_maxTiles);
+ memset(m_posLookup, 0, sizeof(dtMeshTile*)*m_tileLutSize);
+ m_nextFree = 0;
+ for (int i = m_maxTiles-1; i >= 0; --i)
+ {
+ m_tiles[i].salt = 1;
+ m_tiles[i].next = m_nextFree;
+ m_nextFree = &m_tiles[i];
+ }
+
+ // Init ID generator values.
+#ifndef DT_POLYREF64
+ m_tileBits = dtIlog2(dtNextPow2((unsigned int)params->maxTiles));
+ m_polyBits = dtIlog2(dtNextPow2((unsigned int)params->maxPolys));
+
+ // Ensure that the bits of poly ref do not overflow.
+ dtAssert(m_tileBits + m_polyBits <= 31);
+
+ // Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow.
+ m_saltBits = dtMin((unsigned int)31, 32 - m_tileBits - m_polyBits);
+
+ if (m_saltBits < 10)
+ return DT_FAILURE | DT_INVALID_PARAM;
+#endif
+
+ return DT_SUCCESS;
+}
+
+dtStatus dtNavMesh::init(unsigned char* data, const int dataSize, const int flags)
+{
+ // Make sure the data is in right format.
+ dtMeshHeader* header = (dtMeshHeader*)data;
+ if (header->magic != DT_NAVMESH_MAGIC)
+ return DT_FAILURE | DT_WRONG_MAGIC;
+ if (header->version != DT_NAVMESH_VERSION)
+ return DT_FAILURE | DT_WRONG_VERSION;
+
+ dtNavMeshParams params;
+ dtVcopy(params.orig, header->bmin);
+ params.tileWidth = header->bmax[0] - header->bmin[0];
+ params.tileHeight = header->bmax[2] - header->bmin[2];
+ params.maxTiles = 1;
+ params.maxPolys = header->polyCount;
+
+ dtStatus status = init(¶ms);
+ if (dtStatusFailed(status))
+ return status;
+
+ return addTile(data, dataSize, flags, 0, 0);
+}
+
+/// @par
+///
+/// @note The parameters are created automatically when the single tile
+/// initialization is performed.
+const dtNavMeshParams* dtNavMesh::getParams() const
+{
+ return &m_params;
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////
+int dtNavMesh::findConnectingPolys(const float* va, const float* vb,
+ const dtMeshTile* tile, int side,
+ dtPolyRef* con, float* conarea, int maxcon) const
+{
+ if (!tile) return 0;
+
+ float amin[2], amax[2];
+ calcSlabEndPoints(va, vb, amin, amax, side);
+ const float apos = getSlabCoord(va, side);
+
+ // Remove links pointing to 'side' and compact the links array.
+ float bmin[2], bmax[2];
+ unsigned short m = DT_EXT_LINK | (unsigned short)side;
+ int n = 0;
+
+ dtPolyRef base = getPolyRefBase(tile);
+
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ dtPoly* poly = &tile->polys[i];
+ const int nv = poly->vertCount;
+ for (int j = 0; j < nv; ++j)
+ {
+ // Skip edges which do not point to the right side.
+ if (poly->neis[j] != m) continue;
+
+ const float* vc = &tile->verts[poly->verts[j]*3];
+ const float* vd = &tile->verts[poly->verts[(j+1) % nv]*3];
+ const float bpos = getSlabCoord(vc, side);
+
+ // Segments are not close enough.
+ if (dtAbs(apos-bpos) > 0.01f)
+ continue;
+
+ // Check if the segments touch.
+ calcSlabEndPoints(vc, vd, bmin, bmax, side);
+
+ if (!overlapSlabs(amin,amax, bmin,bmax, 0.01f, tile->header->walkableClimb)) continue;
+
+ // Add return value.
+ if (n < maxcon)
+ {
+ conarea[n*2+0] = dtMax(amin[0], bmin[0]);
+ conarea[n*2+1] = dtMin(amax[0], bmax[0]);
+ con[n] = base | (dtPolyRef)i;
+ n++;
+ }
+ break;
+ }
+ }
+ return n;
+}
+
+void dtNavMesh::unconnectLinks(dtMeshTile* tile, dtMeshTile* target)
+{
+ if (!tile || !target) return;
+
+ const unsigned int targetNum = decodePolyIdTile(getTileRef(target));
+
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ dtPoly* poly = &tile->polys[i];
+ unsigned int j = poly->firstLink;
+ unsigned int pj = DT_NULL_LINK;
+ while (j != DT_NULL_LINK)
+ {
+ if (decodePolyIdTile(tile->links[j].ref) == targetNum)
+ {
+ // Remove link.
+ unsigned int nj = tile->links[j].next;
+ if (pj == DT_NULL_LINK)
+ poly->firstLink = nj;
+ else
+ tile->links[pj].next = nj;
+ freeLink(tile, j);
+ j = nj;
+ }
+ else
+ {
+ // Advance
+ pj = j;
+ j = tile->links[j].next;
+ }
+ }
+ }
+}
+
+void dtNavMesh::connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side)
+{
+ if (!tile) return;
+
+ // Connect border links.
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ dtPoly* poly = &tile->polys[i];
+
+ // Create new links.
+// unsigned short m = DT_EXT_LINK | (unsigned short)side;
+
+ const int nv = poly->vertCount;
+ for (int j = 0; j < nv; ++j)
+ {
+ // Skip non-portal edges.
+ if ((poly->neis[j] & DT_EXT_LINK) == 0)
+ continue;
+
+ const int dir = (int)(poly->neis[j] & 0xff);
+ if (side != -1 && dir != side)
+ continue;
+
+ // Create new links
+ const float* va = &tile->verts[poly->verts[j]*3];
+ const float* vb = &tile->verts[poly->verts[(j+1) % nv]*3];
+ dtPolyRef nei[4];
+ float neia[4*2];
+ int nnei = findConnectingPolys(va,vb, target, dtOppositeTile(dir), nei,neia,4);
+ for (int k = 0; k < nnei; ++k)
+ {
+ unsigned int idx = allocLink(tile);
+ if (idx != DT_NULL_LINK)
+ {
+ dtLink* link = &tile->links[idx];
+ link->ref = nei[k];
+ link->edge = (unsigned char)j;
+ link->side = (unsigned char)dir;
+
+ link->next = poly->firstLink;
+ poly->firstLink = idx;
+
+ // Compress portal limits to a byte value.
+ if (dir == 0 || dir == 4)
+ {
+ float tmin = (neia[k*2+0]-va[2]) / (vb[2]-va[2]);
+ float tmax = (neia[k*2+1]-va[2]) / (vb[2]-va[2]);
+ if (tmin > tmax)
+ dtSwap(tmin,tmax);
+ link->bmin = (unsigned char)roundf(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
+ link->bmax = (unsigned char)roundf(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
+ }
+ else if (dir == 2 || dir == 6)
+ {
+ float tmin = (neia[k*2+0]-va[0]) / (vb[0]-va[0]);
+ float tmax = (neia[k*2+1]-va[0]) / (vb[0]-va[0]);
+ if (tmin > tmax)
+ dtSwap(tmin,tmax);
+ link->bmin = (unsigned char)roundf(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
+ link->bmax = (unsigned char)roundf(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
+ }
+ }
+ }
+ }
+ }
+}
+
+void dtNavMesh::connectExtOffMeshLinks(dtMeshTile* tile, dtMeshTile* target, int side)
+{
+ if (!tile) return;
+
+ // Connect off-mesh links.
+ // We are interested on links which land from target tile to this tile.
+ const unsigned char oppositeSide = (side == -1) ? 0xff : (unsigned char)dtOppositeTile(side);
+
+ for (int i = 0; i < target->header->offMeshConCount; ++i)
+ {
+ dtOffMeshConnection* targetCon = &target->offMeshCons[i];
+ if (targetCon->side != oppositeSide)
+ continue;
+
+ dtPoly* targetPoly = &target->polys[targetCon->poly];
+ // Skip off-mesh connections which start location could not be connected at all.
+ if (targetPoly->firstLink == DT_NULL_LINK)
+ continue;
+
+ const float halfExtents[3] = { targetCon->rad, target->header->walkableClimb, targetCon->rad };
+
+ // Find polygon to connect to.
+ const float* p = &targetCon->pos[3];
+ float nearestPt[3];
+ dtPolyRef ref = findNearestPolyInTile(tile, p, halfExtents, nearestPt);
+ if (!ref)
+ continue;
+ // findNearestPoly may return too optimistic results, further check to make sure.
+ if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(targetCon->rad))
+ continue;
+ // Make sure the location is on current mesh.
+ float* v = &target->verts[targetPoly->verts[1]*3];
+ dtVcopy(v, nearestPt);
+
+ // Link off-mesh connection to target poly.
+ unsigned int idx = allocLink(target);
+ if (idx != DT_NULL_LINK)
+ {
+ dtLink* link = &target->links[idx];
+ link->ref = ref;
+ link->edge = (unsigned char)1;
+ link->side = oppositeSide;
+ link->bmin = link->bmax = 0;
+ // Add to linked list.
+ link->next = targetPoly->firstLink;
+ targetPoly->firstLink = idx;
+ }
+
+ // Link target poly to off-mesh connection.
+ if (targetCon->flags & DT_OFFMESH_CON_BIDIR)
+ {
+ unsigned int tidx = allocLink(tile);
+ if (tidx != DT_NULL_LINK)
+ {
+ const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref);
+ dtPoly* landPoly = &tile->polys[landPolyIdx];
+ dtLink* link = &tile->links[tidx];
+ link->ref = getPolyRefBase(target) | (dtPolyRef)(targetCon->poly);
+ link->edge = 0xff;
+ link->side = (unsigned char)(side == -1 ? 0xff : side);
+ link->bmin = link->bmax = 0;
+ // Add to linked list.
+ link->next = landPoly->firstLink;
+ landPoly->firstLink = tidx;
+ }
+ }
+ }
+
+}
+
+void dtNavMesh::connectIntLinks(dtMeshTile* tile)
+{
+ if (!tile) return;
+
+ dtPolyRef base = getPolyRefBase(tile);
+
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ dtPoly* poly = &tile->polys[i];
+ poly->firstLink = DT_NULL_LINK;
+
+ if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ continue;
+
+ // Build edge links backwards so that the links will be
+ // in the linked list from lowest index to highest.
+ for (int j = poly->vertCount-1; j >= 0; --j)
+ {
+ // Skip hard and non-internal edges.
+ if (poly->neis[j] == 0 || (poly->neis[j] & DT_EXT_LINK)) continue;
+
+ unsigned int idx = allocLink(tile);
+ if (idx != DT_NULL_LINK)
+ {
+ dtLink* link = &tile->links[idx];
+ link->ref = base | (dtPolyRef)(poly->neis[j]-1);
+ link->edge = (unsigned char)j;
+ link->side = 0xff;
+ link->bmin = link->bmax = 0;
+ // Add to linked list.
+ link->next = poly->firstLink;
+ poly->firstLink = idx;
+ }
+ }
+ }
+}
+
+void dtNavMesh::baseOffMeshLinks(dtMeshTile* tile)
+{
+ if (!tile) return;
+
+ dtPolyRef base = getPolyRefBase(tile);
+
+ // Base off-mesh connection start points.
+ for (int i = 0; i < tile->header->offMeshConCount; ++i)
+ {
+ dtOffMeshConnection* con = &tile->offMeshCons[i];
+ dtPoly* poly = &tile->polys[con->poly];
+
+ const float halfExtents[3] = { con->rad, tile->header->walkableClimb, con->rad };
+
+ // Find polygon to connect to.
+ const float* p = &con->pos[0]; // First vertex
+ float nearestPt[3];
+ dtPolyRef ref = findNearestPolyInTile(tile, p, halfExtents, nearestPt);
+ if (!ref) continue;
+ // findNearestPoly may return too optimistic results, further check to make sure.
+ if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(con->rad))
+ continue;
+ // Make sure the location is on current mesh.
+ float* v = &tile->verts[poly->verts[0]*3];
+ dtVcopy(v, nearestPt);
+
+ // Link off-mesh connection to target poly.
+ unsigned int idx = allocLink(tile);
+ if (idx != DT_NULL_LINK)
+ {
+ dtLink* link = &tile->links[idx];
+ link->ref = ref;
+ link->edge = (unsigned char)0;
+ link->side = 0xff;
+ link->bmin = link->bmax = 0;
+ // Add to linked list.
+ link->next = poly->firstLink;
+ poly->firstLink = idx;
+ }
+
+ // Start end-point is always connect back to off-mesh connection.
+ unsigned int tidx = allocLink(tile);
+ if (tidx != DT_NULL_LINK)
+ {
+ const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref);
+ dtPoly* landPoly = &tile->polys[landPolyIdx];
+ dtLink* link = &tile->links[tidx];
+ link->ref = base | (dtPolyRef)(con->poly);
+ link->edge = 0xff;
+ link->side = 0xff;
+ link->bmin = link->bmax = 0;
+ // Add to linked list.
+ link->next = landPoly->firstLink;
+ landPoly->firstLink = tidx;
+ }
+ }
+}
+
+namespace
+{
+void closestPointOnDetailEdges(const dtMeshTile* tile, const dtPoly* poly, const float* pos, float* closest, bool onlyBoundary)
+{
+ const unsigned int ip = (unsigned int)(poly - tile->polys);
+ const dtPolyDetail* pd = &tile->detailMeshes[ip];
+
+ float dmin = FLT_MAX;
+ float tmin = 0;
+ const float* pmin = 0;
+ const float* pmax = 0;
+
+ for (int i = 0; i < pd->triCount; i++)
+ {
+ const unsigned char* tris = &tile->detailTris[(pd->triBase + i) * 4];
+ const int ANY_BOUNDARY_EDGE =
+ (DT_DETAIL_EDGE_BOUNDARY << 0) | (DT_DETAIL_EDGE_BOUNDARY << 2) | (DT_DETAIL_EDGE_BOUNDARY << 4);
+ if (onlyBoundary && (tris[3] & ANY_BOUNDARY_EDGE) == 0)
+ {
+ continue;
+ }
+
+ const float* v[3];
+ for (int j = 0; j < 3; ++j)
+ {
+ if (tris[j] < poly->vertCount)
+ {
+ v[j] = &tile->verts[poly->verts[tris[j]] * 3];
+ }
+ else
+ {
+ v[j] = &tile->detailVerts[(pd->vertBase + (tris[j] - poly->vertCount)) * 3];
+ }
+ }
+
+ for (int k = 0, j = 2; k < 3; j = k++)
+ {
+ if ((dtGetDetailTriEdgeFlags(tris[3], j) & DT_DETAIL_EDGE_BOUNDARY) == 0 && (onlyBoundary || tris[j] < tris[k]))
+ {
+ // Only looking at boundary edges and this is internal, or
+ // this is an inner edge that we will see again or have already seen.
+ continue;
+ }
+
+ float t;
+ float d = dtDistancePtSegSqr2D(pos, v[j], v[k], t);
+ if (d < dmin)
+ {
+ dmin = d;
+ tmin = t;
+ pmin = v[j];
+ pmax = v[k];
+ }
+ }
+ }
+
+ dtVlerp(closest, pmin, pmax, tmin);
+}
+}
+
+bool dtNavMesh::getPolyHeight(const dtMeshTile* tile, const dtPoly* poly, const float* pos, float* height) const
+{
+ // Off-mesh connections do not have detail polys and getting height
+ // over them does not make sense.
+ if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ return false;
+
+ const unsigned int ip = (unsigned int)(poly - tile->polys);
+ const dtPolyDetail* pd = &tile->detailMeshes[ip];
+
+ float verts[DT_VERTS_PER_POLYGON*3];
+ const int nv = poly->vertCount;
+ for (int i = 0; i < nv; ++i)
+ dtVcopy(&verts[i*3], &tile->verts[poly->verts[i]*3]);
+
+ if (!dtPointInPolygon(pos, verts, nv))
+ return false;
+
+ if (!height)
+ return true;
+
+ // Find height at the location.
+ for (int j = 0; j < pd->triCount; ++j)
+ {
+ const unsigned char* t = &tile->detailTris[(pd->triBase+j)*4];
+ const float* v[3];
+ for (int k = 0; k < 3; ++k)
+ {
+ if (t[k] < poly->vertCount)
+ v[k] = &tile->verts[poly->verts[t[k]]*3];
+ else
+ v[k] = &tile->detailVerts[(pd->vertBase+(t[k]-poly->vertCount))*3];
+ }
+ float h;
+ if (dtClosestHeightPointTriangle(pos, v[0], v[1], v[2], h))
+ {
+ *height = h;
+ return true;
+ }
+ }
+
+ // If all triangle checks failed above (can happen with degenerate triangles
+ // or larger floating point values) the point is on an edge, so just select
+ // closest. This should almost never happen so the extra iteration here is
+ // ok.
+ float closest[3];
+ closestPointOnDetailEdges(tile, poly, pos, closest, false);
+ *height = closest[1];
+ return true;
+}
+
+void dtNavMesh::closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const
+{
+ const dtMeshTile* tile = 0;
+ const dtPoly* poly = 0;
+ getTileAndPolyByRefUnsafe(ref, &tile, &poly);
+
+ dtVcopy(closest, pos);
+ if (getPolyHeight(tile, poly, pos, &closest[1]))
+ {
+ if (posOverPoly)
+ *posOverPoly = true;
+ return;
+ }
+
+ if (posOverPoly)
+ *posOverPoly = false;
+
+ // Off-mesh connections don't have detail polygons.
+ if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ {
+ const float* v0 = &tile->verts[poly->verts[0]*3];
+ const float* v1 = &tile->verts[poly->verts[1]*3];
+ float t;
+ dtDistancePtSegSqr2D(pos, v0, v1, t);
+ dtVlerp(closest, v0, v1, t);
+ return;
+ }
+
+ // Outside poly that is not an offmesh connection.
+ closestPointOnDetailEdges(tile, poly, pos, closest, true);
+}
+
+dtPolyRef dtNavMesh::findNearestPolyInTile(const dtMeshTile* tile,
+ const float* center, const float* halfExtents,
+ float* nearestPt) const
+{
+ float bmin[3], bmax[3];
+ dtVsub(bmin, center, halfExtents);
+ dtVadd(bmax, center, halfExtents);
+
+ // Get nearby polygons from proximity grid.
+ dtPolyRef polys[128];
+ int polyCount = queryPolygonsInTile(tile, bmin, bmax, polys, 128);
+
+ // Find nearest polygon amongst the nearby polygons.
+ dtPolyRef nearest = 0;
+ float nearestDistanceSqr = FLT_MAX;
+ for (int i = 0; i < polyCount; ++i)
+ {
+ dtPolyRef ref = polys[i];
+ float closestPtPoly[3];
+ float diff[3];
+ bool posOverPoly = false;
+ float d;
+ closestPointOnPoly(ref, center, closestPtPoly, &posOverPoly);
+
+ // If a point is directly over a polygon and closer than
+ // climb height, favor that instead of straight line nearest point.
+ dtVsub(diff, center, closestPtPoly);
+ if (posOverPoly)
+ {
+ d = dtAbs(diff[1]) - tile->header->walkableClimb;
+ d = d > 0 ? d*d : 0;
+ }
+ else
+ {
+ d = dtVlenSqr(diff);
+ }
+
+ if (d < nearestDistanceSqr)
+ {
+ dtVcopy(nearestPt, closestPtPoly);
+ nearestDistanceSqr = d;
+ nearest = ref;
+ }
+ }
+
+ return nearest;
+}
+
+int dtNavMesh::queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
+ dtPolyRef* polys, const int maxPolys) const
+{
+ if (tile->bvTree)
+ {
+ const dtBVNode* node = &tile->bvTree[0];
+ const dtBVNode* end = &tile->bvTree[tile->header->bvNodeCount];
+ const float* tbmin = tile->header->bmin;
+ const float* tbmax = tile->header->bmax;
+ const float qfac = tile->header->bvQuantFactor;
+
+ // Calculate quantized box
+ unsigned short bmin[3], bmax[3];
+ // dtClamp query box to world box.
+ float minx = dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
+ float miny = dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
+ float minz = dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
+ float maxx = dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
+ float maxy = dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
+ float maxz = dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
+ // Quantize
+ bmin[0] = (unsigned short)(qfac * minx) & 0xfffe;
+ bmin[1] = (unsigned short)(qfac * miny) & 0xfffe;
+ bmin[2] = (unsigned short)(qfac * minz) & 0xfffe;
+ bmax[0] = (unsigned short)(qfac * maxx + 1) | 1;
+ bmax[1] = (unsigned short)(qfac * maxy + 1) | 1;
+ bmax[2] = (unsigned short)(qfac * maxz + 1) | 1;
+
+ // Traverse tree
+ dtPolyRef base = getPolyRefBase(tile);
+ int n = 0;
+ while (node < end)
+ {
+ const bool overlap = dtOverlapQuantBounds(bmin, bmax, node->bmin, node->bmax);
+ const bool isLeafNode = node->i >= 0;
+
+ if (isLeafNode && overlap)
+ {
+ if (n < maxPolys)
+ polys[n++] = base | (dtPolyRef)node->i;
+ }
+
+ if (overlap || isLeafNode)
+ node++;
+ else
+ {
+ const int escapeIndex = -node->i;
+ node += escapeIndex;
+ }
+ }
+
+ return n;
+ }
+ else
+ {
+ float bmin[3], bmax[3];
+ int n = 0;
+ dtPolyRef base = getPolyRefBase(tile);
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ dtPoly* p = &tile->polys[i];
+ // Do not return off-mesh connection polygons.
+ if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ continue;
+ // Calc polygon bounds.
+ const float* v = &tile->verts[p->verts[0]*3];
+ dtVcopy(bmin, v);
+ dtVcopy(bmax, v);
+ for (int j = 1; j < p->vertCount; ++j)
+ {
+ v = &tile->verts[p->verts[j]*3];
+ dtVmin(bmin, v);
+ dtVmax(bmax, v);
+ }
+ if (dtOverlapBounds(qmin,qmax, bmin,bmax))
+ {
+ if (n < maxPolys)
+ polys[n++] = base | (dtPolyRef)i;
+ }
+ }
+ return n;
+ }
+}
+
+/// @par
+///
+/// The add operation will fail if the data is in the wrong format, the allocated tile
+/// space is full, or there is a tile already at the specified reference.
+///
+/// The lastRef parameter is used to restore a tile with the same tile
+/// reference it had previously used. In this case the #dtPolyRef's for the
+/// tile will be restored to the same values they were before the tile was
+/// removed.
+///
+/// The nav mesh assumes exclusive access to the data passed and will make
+/// changes to the dynamic portion of the data. For that reason the data
+/// should not be reused in other nav meshes until the tile has been successfully
+/// removed from this nav mesh.
+///
+/// @see dtCreateNavMeshData, #removeTile
+dtStatus dtNavMesh::addTile(unsigned char* data, int dataSize, int flags,
+ dtTileRef lastRef, dtTileRef* result)
+{
+ // Make sure the data is in right format.
+ dtMeshHeader* header = (dtMeshHeader*)data;
+ if (header->magic != DT_NAVMESH_MAGIC)
+ return DT_FAILURE | DT_WRONG_MAGIC;
+ if (header->version != DT_NAVMESH_VERSION)
+ return DT_FAILURE | DT_WRONG_VERSION;
+
+#ifndef DT_POLYREF64
+ // Do not allow adding more polygons than specified in the NavMesh's maxPolys constraint.
+ // Otherwise, the poly ID cannot be represented with the given number of bits.
+ if (m_polyBits < dtIlog2(dtNextPow2((unsigned int)header->polyCount)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+#endif
+
+ // Make sure the location is free.
+ if (getTileAt(header->x, header->y, header->layer))
+ return DT_FAILURE | DT_ALREADY_OCCUPIED;
+
+ // Allocate a tile.
+ dtMeshTile* tile = 0;
+ if (!lastRef)
+ {
+ if (m_nextFree)
+ {
+ tile = m_nextFree;
+ m_nextFree = tile->next;
+ tile->next = 0;
+ }
+ }
+ else
+ {
+ // Try to relocate the tile to specific index with same salt.
+ int tileIndex = (int)decodePolyIdTile((dtPolyRef)lastRef);
+ if (tileIndex >= m_maxTiles)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+ // Try to find the specific tile id from the free list.
+ dtMeshTile* target = &m_tiles[tileIndex];
+ dtMeshTile* prev = 0;
+ tile = m_nextFree;
+ while (tile && tile != target)
+ {
+ prev = tile;
+ tile = tile->next;
+ }
+ // Could not find the correct location.
+ if (tile != target)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+ // Remove from freelist
+ if (!prev)
+ m_nextFree = tile->next;
+ else
+ prev->next = tile->next;
+
+ // Restore salt.
+ tile->salt = decodePolyIdSalt((dtPolyRef)lastRef);
+ }
+
+ // Make sure we could allocate a tile.
+ if (!tile)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+
+ // Insert tile into the position lut.
+ int h = computeTileHash(header->x, header->y, m_tileLutMask);
+ tile->next = m_posLookup[h];
+ m_posLookup[h] = tile;
+
+ // 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;
+ tile->verts = dtGetThenAdvanceBufferPointer(d, vertsSize);
+ tile->polys = dtGetThenAdvanceBufferPointer(d, polysSize);
+ tile->links = dtGetThenAdvanceBufferPointer(d, linksSize);
+ tile->detailMeshes = dtGetThenAdvanceBufferPointer(d, detailMeshesSize);
+ tile->detailVerts = dtGetThenAdvanceBufferPointer(d, detailVertsSize);
+ tile->detailTris = dtGetThenAdvanceBufferPointer(d, detailTrisSize);
+ tile->bvTree = dtGetThenAdvanceBufferPointer(d, bvtreeSize);
+ tile->offMeshCons = dtGetThenAdvanceBufferPointer(d, offMeshLinksSize);
+
+ // If there are no items in the bvtree, reset the tree pointer.
+ if (!bvtreeSize)
+ tile->bvTree = 0;
+
+ // Build links freelist
+ tile->linksFreeList = 0;
+ tile->links[header->maxLinkCount-1].next = DT_NULL_LINK;
+ for (int i = 0; i < header->maxLinkCount-1; ++i)
+ tile->links[i].next = i+1;
+
+ // Init tile.
+ tile->header = header;
+ tile->data = data;
+ tile->dataSize = dataSize;
+ tile->flags = flags;
+
+ connectIntLinks(tile);
+
+ // Base off-mesh connections to their starting polygons and connect connections inside the tile.
+ baseOffMeshLinks(tile);
+ connectExtOffMeshLinks(tile, tile, -1);
+
+ // Create connections with neighbour tiles.
+ static const int MAX_NEIS = 32;
+ dtMeshTile* neis[MAX_NEIS];
+ int nneis;
+
+ // Connect with layers in current tile.
+ nneis = getTilesAt(header->x, header->y, neis, MAX_NEIS);
+ for (int j = 0; j < nneis; ++j)
+ {
+ if (neis[j] == tile)
+ continue;
+
+ connectExtLinks(tile, neis[j], -1);
+ connectExtLinks(neis[j], tile, -1);
+ connectExtOffMeshLinks(tile, neis[j], -1);
+ connectExtOffMeshLinks(neis[j], tile, -1);
+ }
+
+ // Connect with neighbour tiles.
+ for (int i = 0; i < 8; ++i)
+ {
+ nneis = getNeighbourTilesAt(header->x, header->y, i, neis, MAX_NEIS);
+ for (int j = 0; j < nneis; ++j)
+ {
+ connectExtLinks(tile, neis[j], i);
+ connectExtLinks(neis[j], tile, dtOppositeTile(i));
+ connectExtOffMeshLinks(tile, neis[j], i);
+ connectExtOffMeshLinks(neis[j], tile, dtOppositeTile(i));
+ }
+ }
+
+ if (result)
+ *result = getTileRef(tile);
+
+ return DT_SUCCESS;
+}
+
+const dtMeshTile* dtNavMesh::getTileAt(const int x, const int y, const int layer) const
+{
+ // Find tile based on hash.
+ int h = computeTileHash(x,y,m_tileLutMask);
+ dtMeshTile* tile = m_posLookup[h];
+ while (tile)
+ {
+ if (tile->header &&
+ tile->header->x == x &&
+ tile->header->y == y &&
+ tile->header->layer == layer)
+ {
+ return tile;
+ }
+ tile = tile->next;
+ }
+ return 0;
+}
+
+int dtNavMesh::getNeighbourTilesAt(const int x, const int y, const int side, dtMeshTile** tiles, const int maxTiles) const
+{
+ int nx = x, ny = y;
+ switch (side)
+ {
+ case 0: nx++; break;
+ case 1: nx++; ny++; break;
+ case 2: ny++; break;
+ case 3: nx--; ny++; break;
+ case 4: nx--; break;
+ case 5: nx--; ny--; break;
+ case 6: ny--; break;
+ case 7: nx++; ny--; break;
+ };
+
+ return getTilesAt(nx, ny, tiles, maxTiles);
+}
+
+int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile** tiles, const int maxTiles) const
+{
+ int n = 0;
+
+ // Find tile based on hash.
+ int h = computeTileHash(x,y,m_tileLutMask);
+ dtMeshTile* tile = m_posLookup[h];
+ while (tile)
+ {
+ if (tile->header &&
+ tile->header->x == x &&
+ tile->header->y == y)
+ {
+ if (n < maxTiles)
+ tiles[n++] = tile;
+ }
+ tile = tile->next;
+ }
+
+ return n;
+}
+
+/// @par
+///
+/// This function will not fail if the tiles array is too small to hold the
+/// entire result set. It will simply fill the array to capacity.
+int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile const** tiles, const int maxTiles) const
+{
+ int n = 0;
+
+ // Find tile based on hash.
+ int h = computeTileHash(x,y,m_tileLutMask);
+ dtMeshTile* tile = m_posLookup[h];
+ while (tile)
+ {
+ if (tile->header &&
+ tile->header->x == x &&
+ tile->header->y == y)
+ {
+ if (n < maxTiles)
+ tiles[n++] = tile;
+ }
+ tile = tile->next;
+ }
+
+ return n;
+}
+
+
+dtTileRef dtNavMesh::getTileRefAt(const int x, const int y, const int layer) const
+{
+ // Find tile based on hash.
+ int h = computeTileHash(x,y,m_tileLutMask);
+ dtMeshTile* tile = m_posLookup[h];
+ while (tile)
+ {
+ if (tile->header &&
+ tile->header->x == x &&
+ tile->header->y == y &&
+ tile->header->layer == layer)
+ {
+ return getTileRef(tile);
+ }
+ tile = tile->next;
+ }
+ return 0;
+}
+
+const dtMeshTile* dtNavMesh::getTileByRef(dtTileRef ref) const
+{
+ if (!ref)
+ return 0;
+ unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref);
+ unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref);
+ if ((int)tileIndex >= m_maxTiles)
+ return 0;
+ const dtMeshTile* tile = &m_tiles[tileIndex];
+ if (tile->salt != tileSalt)
+ return 0;
+ return tile;
+}
+
+int dtNavMesh::getMaxTiles() const
+{
+ return m_maxTiles;
+}
+
+dtMeshTile* dtNavMesh::getTile(int i)
+{
+ return &m_tiles[i];
+}
+
+const dtMeshTile* dtNavMesh::getTile(int i) const
+{
+ return &m_tiles[i];
+}
+
+void dtNavMesh::calcTileLoc(const float* pos, int* tx, int* ty) const
+{
+ *tx = (int)floorf((pos[0]-m_orig[0]) / m_tileWidth);
+ *ty = (int)floorf((pos[2]-m_orig[2]) / m_tileHeight);
+}
+
+dtStatus dtNavMesh::getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const
+{
+ if (!ref) return DT_FAILURE;
+ unsigned int salt, it, ip;
+ decodePolyId(ref, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
+ if (ip >= (unsigned int)m_tiles[it].header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
+ *tile = &m_tiles[it];
+ *poly = &m_tiles[it].polys[ip];
+ return DT_SUCCESS;
+}
+
+/// @par
+///
+/// @warning Only use this function if it is known that the provided polygon
+/// reference is valid. This function is faster than #getTileAndPolyByRef, but
+/// it does not validate the reference.
+void dtNavMesh::getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const
+{
+ unsigned int salt, it, ip;
+ decodePolyId(ref, salt, it, ip);
+ *tile = &m_tiles[it];
+ *poly = &m_tiles[it].polys[ip];
+}
+
+bool dtNavMesh::isValidPolyRef(dtPolyRef ref) const
+{
+ if (!ref) return false;
+ unsigned int salt, it, ip;
+ decodePolyId(ref, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return false;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return false;
+ if (ip >= (unsigned int)m_tiles[it].header->polyCount) return false;
+ return true;
+}
+
+/// @par
+///
+/// This function returns the data for the tile so that, if desired,
+/// it can be added back to the navigation mesh at a later point.
+///
+/// @see #addTile
+dtStatus dtNavMesh::removeTile(dtTileRef ref, unsigned char** data, int* dataSize)
+{
+ if (!ref)
+ return DT_FAILURE | DT_INVALID_PARAM;
+ unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref);
+ unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref);
+ if ((int)tileIndex >= m_maxTiles)
+ return DT_FAILURE | DT_INVALID_PARAM;
+ dtMeshTile* tile = &m_tiles[tileIndex];
+ if (tile->salt != tileSalt)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // Remove tile from hash lookup.
+ int h = computeTileHash(tile->header->x,tile->header->y,m_tileLutMask);
+ dtMeshTile* prev = 0;
+ dtMeshTile* cur = m_posLookup[h];
+ while (cur)
+ {
+ if (cur == tile)
+ {
+ if (prev)
+ prev->next = cur->next;
+ else
+ m_posLookup[h] = cur->next;
+ break;
+ }
+ prev = cur;
+ cur = cur->next;
+ }
+
+ // Remove connections to neighbour tiles.
+ static const int MAX_NEIS = 32;
+ dtMeshTile* neis[MAX_NEIS];
+ int nneis;
+
+ // Disconnect from other layers in current tile.
+ nneis = getTilesAt(tile->header->x, tile->header->y, neis, MAX_NEIS);
+ for (int j = 0; j < nneis; ++j)
+ {
+ if (neis[j] == tile) continue;
+ unconnectLinks(neis[j], tile);
+ }
+
+ // Disconnect from neighbour tiles.
+ for (int i = 0; i < 8; ++i)
+ {
+ nneis = getNeighbourTilesAt(tile->header->x, tile->header->y, i, neis, MAX_NEIS);
+ for (int j = 0; j < nneis; ++j)
+ unconnectLinks(neis[j], tile);
+ }
+
+ // Reset tile.
+ if (tile->flags & DT_TILE_FREE_DATA)
+ {
+ // Owns data
+ dtFree(tile->data);
+ tile->data = 0;
+ tile->dataSize = 0;
+ if (data) *data = 0;
+ if (dataSize) *dataSize = 0;
+ }
+ else
+ {
+ if (data) *data = tile->data;
+ if (dataSize) *dataSize = tile->dataSize;
+ }
+
+ tile->header = 0;
+ tile->flags = 0;
+ tile->linksFreeList = 0;
+ tile->polys = 0;
+ tile->verts = 0;
+ tile->links = 0;
+ tile->detailMeshes = 0;
+ tile->detailVerts = 0;
+ tile->detailTris = 0;
+ tile->bvTree = 0;
+ tile->offMeshCons = 0;
+
+ // Update salt, salt should never be zero.
+#ifdef DT_POLYREF64
+ tile->salt = (tile->salt+1) & ((1<salt = (tile->salt+1) & ((1<salt == 0)
+ tile->salt++;
+
+ // Add to free list.
+ tile->next = m_nextFree;
+ m_nextFree = tile;
+
+ return DT_SUCCESS;
+}
+
+dtTileRef dtNavMesh::getTileRef(const dtMeshTile* tile) const
+{
+ if (!tile) return 0;
+ const unsigned int it = (unsigned int)(tile - m_tiles);
+ return (dtTileRef)encodePolyId(tile->salt, it, 0);
+}
+
+/// @par
+///
+/// Example use case:
+/// @code
+///
+/// const dtPolyRef base = navmesh->getPolyRefBase(tile);
+/// for (int i = 0; i < tile->header->polyCount; ++i)
+/// {
+/// const dtPoly* p = &tile->polys[i];
+/// const dtPolyRef ref = base | (dtPolyRef)i;
+///
+/// // Use the reference to access the polygon data.
+/// }
+/// @endcode
+dtPolyRef dtNavMesh::getPolyRefBase(const dtMeshTile* tile) const
+{
+ if (!tile) return 0;
+ const unsigned int it = (unsigned int)(tile - m_tiles);
+ return encodePolyId(tile->salt, it, 0);
+}
+
+struct dtTileState
+{
+ int magic; // Magic number, used to identify the data.
+ int version; // Data version number.
+ dtTileRef ref; // Tile ref at the time of storing the data.
+};
+
+struct dtPolyState
+{
+ unsigned short flags; // Flags (see dtPolyFlags).
+ unsigned char area; // Area ID of the polygon.
+};
+
+/// @see #storeTileState
+int dtNavMesh::getTileStateSize(const dtMeshTile* tile) const
+{
+ if (!tile) return 0;
+ const int headerSize = dtAlign4(sizeof(dtTileState));
+ const int polyStateSize = dtAlign4(sizeof(dtPolyState) * tile->header->polyCount);
+ return headerSize + polyStateSize;
+}
+
+/// @par
+///
+/// Tile state includes non-structural data such as polygon flags, area ids, etc.
+/// @note The state data is only valid until the tile reference changes.
+/// @see #getTileStateSize, #restoreTileState
+dtStatus dtNavMesh::storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const
+{
+ // Make sure there is enough space to store the state.
+ const int sizeReq = getTileStateSize(tile);
+ if (maxDataSize < sizeReq)
+ return DT_FAILURE | DT_BUFFER_TOO_SMALL;
+
+ dtTileState* tileState = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtTileState)));
+ dtPolyState* polyStates = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtPolyState) * tile->header->polyCount));
+
+ // Store tile state.
+ tileState->magic = DT_NAVMESH_STATE_MAGIC;
+ tileState->version = DT_NAVMESH_STATE_VERSION;
+ tileState->ref = getTileRef(tile);
+
+ // Store per poly state.
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ const dtPoly* p = &tile->polys[i];
+ dtPolyState* s = &polyStates[i];
+ s->flags = p->flags;
+ s->area = p->getArea();
+ }
+
+ return DT_SUCCESS;
+}
+
+/// @par
+///
+/// Tile state includes non-structural data such as polygon flags, area ids, etc.
+/// @note This function does not impact the tile's #dtTileRef and #dtPolyRef's.
+/// @see #storeTileState
+dtStatus dtNavMesh::restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize)
+{
+ // Make sure there is enough space to store the state.
+ const int sizeReq = getTileStateSize(tile);
+ if (maxDataSize < sizeReq)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ const dtTileState* tileState = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtTileState)));
+ const dtPolyState* polyStates = dtGetThenAdvanceBufferPointer(data, dtAlign4(sizeof(dtPolyState) * tile->header->polyCount));
+
+ // Check that the restore is possible.
+ if (tileState->magic != DT_NAVMESH_STATE_MAGIC)
+ return DT_FAILURE | DT_WRONG_MAGIC;
+ if (tileState->version != DT_NAVMESH_STATE_VERSION)
+ return DT_FAILURE | DT_WRONG_VERSION;
+ if (tileState->ref != getTileRef(tile))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // Restore per poly state.
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ dtPoly* p = &tile->polys[i];
+ const dtPolyState* s = &polyStates[i];
+ p->flags = s->flags;
+ p->setArea(s->area);
+ }
+
+ return DT_SUCCESS;
+}
+
+/// @par
+///
+/// Off-mesh connections are stored in the navigation mesh as special 2-vertex
+/// polygons with a single edge. At least one of the vertices is expected to be
+/// inside a normal polygon. So an off-mesh connection is "entered" from a
+/// normal polygon at one of its endpoints. This is the polygon identified by
+/// the prevRef parameter.
+dtStatus dtNavMesh::getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const
+{
+ unsigned int salt, it, ip;
+
+ if (!polyRef)
+ return DT_FAILURE;
+
+ // Get current polygon
+ decodePolyId(polyRef, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
+ const dtMeshTile* tile = &m_tiles[it];
+ if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
+ const dtPoly* poly = &tile->polys[ip];
+
+ // Make sure that the current poly is indeed off-mesh link.
+ if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION)
+ return DT_FAILURE;
+
+ // Figure out which way to hand out the vertices.
+ int idx0 = 0, idx1 = 1;
+
+ // Find link that points to first vertex.
+ for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next)
+ {
+ if (tile->links[i].edge == 0)
+ {
+ if (tile->links[i].ref != prevRef)
+ {
+ idx0 = 1;
+ idx1 = 0;
+ }
+ break;
+ }
+ }
+
+ dtVcopy(startPos, &tile->verts[poly->verts[idx0]*3]);
+ dtVcopy(endPos, &tile->verts[poly->verts[idx1]*3]);
+
+ return DT_SUCCESS;
+}
+
+
+const dtOffMeshConnection* dtNavMesh::getOffMeshConnectionByRef(dtPolyRef ref) const
+{
+ unsigned int salt, it, ip;
+
+ if (!ref)
+ return 0;
+
+ // Get current polygon
+ decodePolyId(ref, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return 0;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return 0;
+ const dtMeshTile* tile = &m_tiles[it];
+ if (ip >= (unsigned int)tile->header->polyCount) return 0;
+ const dtPoly* poly = &tile->polys[ip];
+
+ // Make sure that the current poly is indeed off-mesh link.
+ if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION)
+ return 0;
+
+ const unsigned int idx = ip - tile->header->offMeshBase;
+ dtAssert(idx < (unsigned int)tile->header->offMeshConCount);
+ return &tile->offMeshCons[idx];
+}
+
+
+dtStatus dtNavMesh::setPolyFlags(dtPolyRef ref, unsigned short flags)
+{
+ if (!ref) return DT_FAILURE;
+ unsigned int salt, it, ip;
+ decodePolyId(ref, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
+ dtMeshTile* tile = &m_tiles[it];
+ if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
+ dtPoly* poly = &tile->polys[ip];
+
+ // Change flags.
+ poly->flags = flags;
+
+ return DT_SUCCESS;
+}
+
+dtStatus dtNavMesh::getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const
+{
+ if (!ref) return DT_FAILURE;
+ unsigned int salt, it, ip;
+ decodePolyId(ref, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
+ const dtMeshTile* tile = &m_tiles[it];
+ if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
+ const dtPoly* poly = &tile->polys[ip];
+
+ *resultFlags = poly->flags;
+
+ return DT_SUCCESS;
+}
+
+dtStatus dtNavMesh::setPolyArea(dtPolyRef ref, unsigned char area)
+{
+ if (!ref) return DT_FAILURE;
+ unsigned int salt, it, ip;
+ decodePolyId(ref, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
+ dtMeshTile* tile = &m_tiles[it];
+ if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
+ dtPoly* poly = &tile->polys[ip];
+
+ poly->setArea(area);
+
+ return DT_SUCCESS;
+}
+
+dtStatus dtNavMesh::getPolyArea(dtPolyRef ref, unsigned char* resultArea) const
+{
+ if (!ref) return DT_FAILURE;
+ unsigned int salt, it, ip;
+ decodePolyId(ref, salt, it, ip);
+ if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
+ if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
+ const dtMeshTile* tile = &m_tiles[it];
+ if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
+ const dtPoly* poly = &tile->polys[ip];
+
+ *resultArea = poly->getArea();
+
+ return DT_SUCCESS;
+}
+
diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNavMeshBuilder.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshBuilder.cpp
new file mode 100644
index 0000000..07ba863
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshBuilder.cpp
@@ -0,0 +1,802 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include
+#include
+#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 = ¶ms->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 = ¶ms->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 = ¶ms->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 = ¶ms->offMeshConVerts[(i*2+0)*3];
+ const float* p1 = ¶ms->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 = ¶ms->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 = ¶ms->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 = ¶ms->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(d, headerSize);
+ float* navVerts = dtGetThenAdvanceBufferPointer(d, vertsSize);
+ dtPoly* navPolys = dtGetThenAdvanceBufferPointer(d, polysSize);
+ d += linksSize; // Ignore links; just leave enough space for them. They'll be created on load.
+ dtPolyDetail* navDMeshes = dtGetThenAdvanceBufferPointer(d, detailMeshesSize);
+ float* navDVerts = dtGetThenAdvanceBufferPointer(d, detailVertsSize);
+ unsigned char* navDTris = dtGetThenAdvanceBufferPointer(d, detailTrisSize);
+ dtBVNode* navBvtree = dtGetThenAdvanceBufferPointer(d, bvTreeSize);
+ dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer(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 = ¶ms->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 = ¶ms->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], ¶ms->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 = ¶ms->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(d, vertsSize);
+ dtPoly* polys = dtGetThenAdvanceBufferPointer(d, polysSize);
+ d += linksSize; // Ignore links; they technically should be endian-swapped but all their data is overwritten on load anyway.
+ //dtLink* links = dtGetThenAdvanceBufferPointer(d, linksSize);
+ dtPolyDetail* detailMeshes = dtGetThenAdvanceBufferPointer(d, detailMeshesSize);
+ float* detailVerts = dtGetThenAdvanceBufferPointer(d, detailVertsSize);
+ d += detailTrisSize; // Ignore detail tris; single bytes can't be endian-swapped.
+ //unsigned char* detailTris = dtGetThenAdvanceBufferPointer(d, detailTrisSize);
+ dtBVNode* bvTree = dtGetThenAdvanceBufferPointer(d, bvtreeSize);
+ dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer(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;
+}
diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNavMeshQuery.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshQuery.cpp
new file mode 100644
index 0000000..7edbe3b
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Source/DetourNavMeshQuery.cpp
@@ -0,0 +1,3696 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include "DetourNavMeshQuery.h"
+#include "DetourNavMesh.h"
+#include "DetourNode.h"
+#include "DetourCommon.h"
+#include "DetourMath.h"
+#include "DetourAlloc.h"
+#include "DetourAssert.h"
+#include
+
+/// @class dtQueryFilter
+///
+/// The Default Implementation
+///
+/// At construction: All area costs default to 1.0. All flags are included
+/// and none are excluded.
+///
+/// If a polygon has both an include and an exclude flag, it will be excluded.
+///
+/// The way filtering works, a navigation mesh polygon must have at least one flag
+/// set to ever be considered by a query. So a polygon with no flags will never
+/// be considered.
+///
+/// Setting the include flags to 0 will result in all polygons being excluded.
+///
+/// Custom Implementations
+///
+/// DT_VIRTUAL_QUERYFILTER must be defined in order to extend this class.
+///
+/// Implement a custom query filter by overriding the virtual passFilter()
+/// and getCost() functions. If this is done, both functions should be as
+/// fast as possible. Use cached local copies of data rather than accessing
+/// your own objects where possible.
+///
+/// Custom implementations do not need to adhere to the flags or cost logic
+/// used by the default implementation.
+///
+/// In order for A* searches to work properly, the cost should be proportional to
+/// the travel distance. Implementing a cost modifier less than 1.0 is likely
+/// to lead to problems during pathfinding.
+///
+/// @see dtNavMeshQuery
+
+dtQueryFilter::dtQueryFilter() :
+ m_includeFlags(0xffff),
+ m_excludeFlags(0)
+{
+ for (int i = 0; i < DT_MAX_AREAS; ++i)
+ m_areaCost[i] = 1.0f;
+}
+
+#ifdef DT_VIRTUAL_QUERYFILTER
+bool dtQueryFilter::passFilter(const dtPolyRef /*ref*/,
+ const dtMeshTile* /*tile*/,
+ const dtPoly* poly) const
+{
+ return (poly->flags & m_includeFlags) != 0 && (poly->flags & m_excludeFlags) == 0;
+}
+
+float dtQueryFilter::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
+{
+ return dtVdist(pa, pb) * m_areaCost[curPoly->getArea()];
+}
+#else
+inline bool dtQueryFilter::passFilter(const dtPolyRef /*ref*/,
+ const dtMeshTile* /*tile*/,
+ const dtPoly* poly) const
+{
+ return (poly->flags & m_includeFlags) != 0 && (poly->flags & m_excludeFlags) == 0;
+}
+
+inline float dtQueryFilter::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
+{
+ return dtVdist(pa, pb) * m_areaCost[curPoly->getArea()];
+}
+#endif
+
+static const float H_SCALE = 0.999f; // Search heuristic scale.
+
+
+dtNavMeshQuery* dtAllocNavMeshQuery()
+{
+ void* mem = dtAlloc(sizeof(dtNavMeshQuery), DT_ALLOC_PERM);
+ if (!mem) return 0;
+ return new(mem) dtNavMeshQuery;
+}
+
+void dtFreeNavMeshQuery(dtNavMeshQuery* navmesh)
+{
+ if (!navmesh) return;
+ navmesh->~dtNavMeshQuery();
+ dtFree(navmesh);
+}
+
+dtPolyQuery::~dtPolyQuery()
+{
+ // Defined out of line to fix the weak v-tables warning
+}
+
+//////////////////////////////////////////////////////////////////////////////////////////
+
+/// @class dtNavMeshQuery
+///
+/// For methods that support undersized buffers, if the buffer is too small
+/// to hold the entire result set the return status of the method will include
+/// the #DT_BUFFER_TOO_SMALL flag.
+///
+/// Constant member functions can be used by multiple clients without side
+/// effects. (E.g. No change to the closed list. No impact on an in-progress
+/// sliced path query. Etc.)
+///
+/// Walls and portals: A @e wall is a polygon segment that is
+/// considered impassable. A @e portal is a passable segment between polygons.
+/// A portal may be treated as a wall based on the dtQueryFilter used for a query.
+///
+/// @see dtNavMesh, dtQueryFilter, #dtAllocNavMeshQuery(), #dtAllocNavMeshQuery()
+
+dtNavMeshQuery::dtNavMeshQuery() :
+ m_nav(0),
+ m_tinyNodePool(0),
+ m_nodePool(0),
+ m_openList(0)
+{
+ memset(&m_query, 0, sizeof(dtQueryData));
+}
+
+dtNavMeshQuery::~dtNavMeshQuery()
+{
+ if (m_tinyNodePool)
+ m_tinyNodePool->~dtNodePool();
+ if (m_nodePool)
+ m_nodePool->~dtNodePool();
+ if (m_openList)
+ m_openList->~dtNodeQueue();
+ dtFree(m_tinyNodePool);
+ dtFree(m_nodePool);
+ dtFree(m_openList);
+}
+
+/// @par
+///
+/// Must be the first function called after construction, before other
+/// functions are used.
+///
+/// This function can be used multiple times.
+dtStatus dtNavMeshQuery::init(const dtNavMesh* nav, const int maxNodes)
+{
+ if (maxNodes > DT_NULL_IDX || maxNodes > (1 << DT_NODE_PARENT_BITS) - 1)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ m_nav = nav;
+
+ if (!m_nodePool || m_nodePool->getMaxNodes() < maxNodes)
+ {
+ if (m_nodePool)
+ {
+ m_nodePool->~dtNodePool();
+ dtFree(m_nodePool);
+ m_nodePool = 0;
+ }
+ m_nodePool = new (dtAlloc(sizeof(dtNodePool), DT_ALLOC_PERM)) dtNodePool(maxNodes, dtNextPow2(maxNodes/4));
+ if (!m_nodePool)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+ }
+ else
+ {
+ m_nodePool->clear();
+ }
+
+ if (!m_tinyNodePool)
+ {
+ m_tinyNodePool = new (dtAlloc(sizeof(dtNodePool), DT_ALLOC_PERM)) dtNodePool(64, 32);
+ if (!m_tinyNodePool)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+ }
+ else
+ {
+ m_tinyNodePool->clear();
+ }
+
+ if (!m_openList || m_openList->getCapacity() < maxNodes)
+ {
+ if (m_openList)
+ {
+ m_openList->~dtNodeQueue();
+ dtFree(m_openList);
+ m_openList = 0;
+ }
+ m_openList = new (dtAlloc(sizeof(dtNodeQueue), DT_ALLOC_PERM)) dtNodeQueue(maxNodes);
+ if (!m_openList)
+ return DT_FAILURE | DT_OUT_OF_MEMORY;
+ }
+ else
+ {
+ m_openList->clear();
+ }
+
+ return DT_SUCCESS;
+}
+
+dtStatus dtNavMeshQuery::findRandomPoint(const dtQueryFilter* filter, float (*frand)(),
+ dtPolyRef* randomRef, float* randomPt) const
+{
+ dtAssert(m_nav);
+
+ if (!filter || !frand || !randomRef || !randomPt)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // Randomly pick one tile. Assume that all tiles cover roughly the same area.
+ const dtMeshTile* tile = 0;
+ float tsum = 0.0f;
+ for (int i = 0; i < m_nav->getMaxTiles(); i++)
+ {
+ const dtMeshTile* t = m_nav->getTile(i);
+ if (!t || !t->header) continue;
+
+ // Choose random tile using reservoir sampling.
+ const float area = 1.0f; // Could be tile area too.
+ tsum += area;
+ const float u = frand();
+ if (u*tsum <= area)
+ tile = t;
+ }
+ if (!tile)
+ return DT_FAILURE;
+
+ // Randomly pick one polygon weighted by polygon area.
+ const dtPoly* poly = 0;
+ dtPolyRef polyRef = 0;
+ const dtPolyRef base = m_nav->getPolyRefBase(tile);
+
+ float areaSum = 0.0f;
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ const dtPoly* p = &tile->polys[i];
+ // Do not return off-mesh connection polygons.
+ if (p->getType() != DT_POLYTYPE_GROUND)
+ continue;
+ // Must pass filter
+ const dtPolyRef ref = base | (dtPolyRef)i;
+ if (!filter->passFilter(ref, tile, p))
+ continue;
+
+ // Calc area of the polygon.
+ float polyArea = 0.0f;
+ for (int j = 2; j < p->vertCount; ++j)
+ {
+ const float* va = &tile->verts[p->verts[0]*3];
+ const float* vb = &tile->verts[p->verts[j-1]*3];
+ const float* vc = &tile->verts[p->verts[j]*3];
+ polyArea += dtTriArea2D(va,vb,vc);
+ }
+
+ // Choose random polygon weighted by area, using reservoir sampling.
+ areaSum += polyArea;
+ const float u = frand();
+ if (u*areaSum <= polyArea)
+ {
+ poly = p;
+ polyRef = ref;
+ }
+ }
+
+ if (!poly)
+ return DT_FAILURE;
+
+ // Randomly pick point on polygon.
+ const float* v = &tile->verts[poly->verts[0]*3];
+ float verts[3*DT_VERTS_PER_POLYGON];
+ float areas[DT_VERTS_PER_POLYGON];
+ dtVcopy(&verts[0*3],v);
+ for (int j = 1; j < poly->vertCount; ++j)
+ {
+ v = &tile->verts[poly->verts[j]*3];
+ dtVcopy(&verts[j*3],v);
+ }
+
+ const float s = frand();
+ const float t = frand();
+
+ float pt[3];
+ dtRandomPointInConvexPoly(verts, poly->vertCount, areas, s, t, pt);
+
+ closestPointOnPoly(polyRef, pt, pt, NULL);
+
+ dtVcopy(randomPt, pt);
+ *randomRef = polyRef;
+
+ return DT_SUCCESS;
+}
+
+dtStatus dtNavMeshQuery::findRandomPointAroundCircle(dtPolyRef startRef, const float* centerPos, const float maxRadius,
+ const dtQueryFilter* filter, float (*frand)(),
+ dtPolyRef* randomRef, float* randomPt) const
+{
+ dtAssert(m_nav);
+ dtAssert(m_nodePool);
+ dtAssert(m_openList);
+
+ // Validate input
+ if (!m_nav->isValidPolyRef(startRef) ||
+ !centerPos || !dtVisfinite(centerPos) ||
+ maxRadius < 0 || !dtMathIsfinite(maxRadius) ||
+ !filter || !frand || !randomRef || !randomPt)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ const dtMeshTile* startTile = 0;
+ const dtPoly* startPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(startRef, &startTile, &startPoly);
+ if (!filter->passFilter(startRef, startTile, startPoly))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ m_nodePool->clear();
+ m_openList->clear();
+
+ dtNode* startNode = m_nodePool->getNode(startRef);
+ dtVcopy(startNode->pos, centerPos);
+ startNode->pidx = 0;
+ startNode->cost = 0;
+ startNode->total = 0;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_OPEN;
+ m_openList->push(startNode);
+
+ dtStatus status = DT_SUCCESS;
+
+ const float radiusSqr = dtSqr(maxRadius);
+ float areaSum = 0.0f;
+
+ const dtMeshTile* randomTile = 0;
+ const dtPoly* randomPoly = 0;
+ dtPolyRef randomPolyRef = 0;
+
+ while (!m_openList->empty())
+ {
+ dtNode* bestNode = m_openList->pop();
+ bestNode->flags &= ~DT_NODE_OPEN;
+ bestNode->flags |= DT_NODE_CLOSED;
+
+ // Get poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef bestRef = bestNode->id;
+ const dtMeshTile* bestTile = 0;
+ const dtPoly* bestPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
+
+ // Place random locations on on ground.
+ if (bestPoly->getType() == DT_POLYTYPE_GROUND)
+ {
+ // Calc area of the polygon.
+ float polyArea = 0.0f;
+ for (int j = 2; j < bestPoly->vertCount; ++j)
+ {
+ const float* va = &bestTile->verts[bestPoly->verts[0]*3];
+ const float* vb = &bestTile->verts[bestPoly->verts[j-1]*3];
+ const float* vc = &bestTile->verts[bestPoly->verts[j]*3];
+ polyArea += dtTriArea2D(va,vb,vc);
+ }
+ // Choose random polygon weighted by area, using reservoir sampling.
+ areaSum += polyArea;
+ const float u = frand();
+ if (u*areaSum <= polyArea)
+ {
+ randomTile = bestTile;
+ randomPoly = bestPoly;
+ randomPolyRef = bestRef;
+ }
+ }
+
+
+ // Get parent poly and tile.
+ dtPolyRef parentRef = 0;
+ const dtMeshTile* parentTile = 0;
+ const dtPoly* parentPoly = 0;
+ if (bestNode->pidx)
+ parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
+ if (parentRef)
+ m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
+
+ for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
+ {
+ const dtLink* link = &bestTile->links[i];
+ dtPolyRef neighbourRef = link->ref;
+ // Skip invalid neighbours and do not follow back to parent.
+ if (!neighbourRef || neighbourRef == parentRef)
+ continue;
+
+ // Expand to neighbour
+ const dtMeshTile* neighbourTile = 0;
+ const dtPoly* neighbourPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
+
+ // Do not advance if the polygon is excluded by the filter.
+ if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
+ continue;
+
+ // Find edge and calc distance to the edge.
+ float va[3], vb[3];
+ if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
+ continue;
+
+ // If the circle is not touching the next polygon, skip it.
+ float tseg;
+ float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
+ if (distSqr > radiusSqr)
+ continue;
+
+ dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
+ if (!neighbourNode)
+ {
+ status |= DT_OUT_OF_NODES;
+ continue;
+ }
+
+ if (neighbourNode->flags & DT_NODE_CLOSED)
+ continue;
+
+ // Cost
+ if (neighbourNode->flags == 0)
+ dtVlerp(neighbourNode->pos, va, vb, 0.5f);
+
+ const float total = bestNode->total + dtVdist(bestNode->pos, neighbourNode->pos);
+
+ // The node is already in open list and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
+ continue;
+
+ neighbourNode->id = neighbourRef;
+ neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED);
+ neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
+ neighbourNode->total = total;
+
+ if (neighbourNode->flags & DT_NODE_OPEN)
+ {
+ m_openList->modify(neighbourNode);
+ }
+ else
+ {
+ neighbourNode->flags = DT_NODE_OPEN;
+ m_openList->push(neighbourNode);
+ }
+ }
+ }
+
+ if (!randomPoly)
+ return DT_FAILURE;
+
+ // Randomly pick point on polygon.
+ const float* v = &randomTile->verts[randomPoly->verts[0]*3];
+ float verts[3*DT_VERTS_PER_POLYGON];
+ float areas[DT_VERTS_PER_POLYGON];
+ dtVcopy(&verts[0*3],v);
+ for (int j = 1; j < randomPoly->vertCount; ++j)
+ {
+ v = &randomTile->verts[randomPoly->verts[j]*3];
+ dtVcopy(&verts[j*3],v);
+ }
+
+ const float s = frand();
+ const float t = frand();
+
+ float pt[3];
+ dtRandomPointInConvexPoly(verts, randomPoly->vertCount, areas, s, t, pt);
+
+ closestPointOnPoly(randomPolyRef, pt, pt, NULL);
+
+ dtVcopy(randomPt, pt);
+ *randomRef = randomPolyRef;
+
+ return status;
+}
+
+
+//////////////////////////////////////////////////////////////////////////////////////////
+
+/// @par
+///
+/// Uses the detail polygons to find the surface height. (Most accurate.)
+///
+/// @p pos does not have to be within the bounds of the polygon or navigation mesh.
+///
+/// See closestPointOnPolyBoundary() for a limited but faster option.
+///
+dtStatus dtNavMeshQuery::closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const
+{
+ dtAssert(m_nav);
+ if (!m_nav->isValidPolyRef(ref) ||
+ !pos || !dtVisfinite(pos) ||
+ !closest)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ m_nav->closestPointOnPoly(ref, pos, closest, posOverPoly);
+ return DT_SUCCESS;
+}
+
+/// @par
+///
+/// Much faster than closestPointOnPoly().
+///
+/// If the provided position lies within the polygon's xz-bounds (above or below),
+/// then @p pos and @p closest will be equal.
+///
+/// The height of @p closest will be the polygon boundary. The height detail is not used.
+///
+/// @p pos does not have to be within the bounds of the polybon or the navigation mesh.
+///
+dtStatus dtNavMeshQuery::closestPointOnPolyBoundary(dtPolyRef ref, const float* pos, float* closest) const
+{
+ dtAssert(m_nav);
+
+ const dtMeshTile* tile = 0;
+ const dtPoly* poly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ if (!pos || !dtVisfinite(pos) || !closest)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // Collect vertices.
+ float verts[DT_VERTS_PER_POLYGON*3];
+ float edged[DT_VERTS_PER_POLYGON];
+ float edget[DT_VERTS_PER_POLYGON];
+ int nv = 0;
+ for (int i = 0; i < (int)poly->vertCount; ++i)
+ {
+ dtVcopy(&verts[nv*3], &tile->verts[poly->verts[i]*3]);
+ nv++;
+ }
+
+ bool inside = dtDistancePtPolyEdgesSqr(pos, verts, nv, edged, edget);
+ if (inside)
+ {
+ // Point is inside the polygon, return the point.
+ dtVcopy(closest, pos);
+ }
+ else
+ {
+ // Point is outside the polygon, dtClamp to nearest edge.
+ float dmin = edged[0];
+ int imin = 0;
+ for (int i = 1; i < nv; ++i)
+ {
+ if (edged[i] < dmin)
+ {
+ dmin = edged[i];
+ imin = i;
+ }
+ }
+ const float* va = &verts[imin*3];
+ const float* vb = &verts[((imin+1)%nv)*3];
+ dtVlerp(closest, va, vb, edget[imin]);
+ }
+
+ return DT_SUCCESS;
+}
+
+/// @par
+///
+/// Will return #DT_FAILURE | DT_INVALID_PARAM if the provided position is outside the xz-bounds
+/// of the polygon.
+///
+dtStatus dtNavMeshQuery::getPolyHeight(dtPolyRef ref, const float* pos, float* height) const
+{
+ dtAssert(m_nav);
+
+ const dtMeshTile* tile = 0;
+ const dtPoly* poly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ if (!pos || !dtVisfinite2D(pos))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // We used to return success for offmesh connections, but the
+ // getPolyHeight in DetourNavMesh does not do this, so special
+ // case it here.
+ if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ {
+ const float* v0 = &tile->verts[poly->verts[0]*3];
+ const float* v1 = &tile->verts[poly->verts[1]*3];
+ float t;
+ dtDistancePtSegSqr2D(pos, v0, v1, t);
+ if (height)
+ *height = v0[1] + (v1[1] - v0[1])*t;
+
+ return DT_SUCCESS;
+ }
+
+ return m_nav->getPolyHeight(tile, poly, pos, height)
+ ? DT_SUCCESS
+ : DT_FAILURE | DT_INVALID_PARAM;
+}
+
+class dtFindNearestPolyQuery : public dtPolyQuery
+{
+ const dtNavMeshQuery* m_query;
+ const float* m_center;
+ float m_nearestDistanceSqr;
+ dtPolyRef m_nearestRef;
+ float m_nearestPoint[3];
+ bool m_overPoly;
+
+public:
+ dtFindNearestPolyQuery(const dtNavMeshQuery* query, const float* center)
+ : m_query(query), m_center(center), m_nearestDistanceSqr(FLT_MAX), m_nearestRef(0), m_nearestPoint(), m_overPoly(false)
+ {
+ }
+
+ virtual ~dtFindNearestPolyQuery();
+
+ dtPolyRef nearestRef() const { return m_nearestRef; }
+ const float* nearestPoint() const { return m_nearestPoint; }
+ bool isOverPoly() const { return m_overPoly; }
+
+ void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count)
+ {
+ dtIgnoreUnused(polys);
+
+ for (int i = 0; i < count; ++i)
+ {
+ dtPolyRef ref = refs[i];
+ float closestPtPoly[3];
+ float diff[3];
+ bool posOverPoly = false;
+ float d;
+ m_query->closestPointOnPoly(ref, m_center, closestPtPoly, &posOverPoly);
+
+ // If a point is directly over a polygon and closer than
+ // climb height, favor that instead of straight line nearest point.
+ dtVsub(diff, m_center, closestPtPoly);
+ if (posOverPoly)
+ {
+ d = dtAbs(diff[1]) - tile->header->walkableClimb;
+ d = d > 0 ? d*d : 0;
+ }
+ else
+ {
+ d = dtVlenSqr(diff);
+ }
+
+ if (d < m_nearestDistanceSqr)
+ {
+ dtVcopy(m_nearestPoint, closestPtPoly);
+
+ m_nearestDistanceSqr = d;
+ m_nearestRef = ref;
+ m_overPoly = posOverPoly;
+ }
+ }
+ }
+};
+
+dtFindNearestPolyQuery::~dtFindNearestPolyQuery()
+{
+ // Defined out of line to fix the weak v-tables warning
+}
+
+/// @par
+///
+/// @note If the search box does not intersect any polygons the search will
+/// return #DT_SUCCESS, but @p nearestRef will be zero. So if in doubt, check
+/// @p nearestRef before using @p nearestPt.
+///
+dtStatus dtNavMeshQuery::findNearestPoly(const float* center, const float* halfExtents,
+ const dtQueryFilter* filter,
+ dtPolyRef* nearestRef, float* nearestPt) const
+{
+ return findNearestPoly(center, halfExtents, filter, nearestRef, nearestPt, NULL);
+}
+
+// If center and nearestPt point to an equal position, isOverPoly will be true;
+// however there's also a special case of climb height inside the polygon (see dtFindNearestPolyQuery)
+dtStatus dtNavMeshQuery::findNearestPoly(const float* center, const float* halfExtents,
+ const dtQueryFilter* filter,
+ dtPolyRef* nearestRef, float* nearestPt, bool* isOverPoly) const
+{
+ dtAssert(m_nav);
+
+ if (!nearestRef)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // queryPolygons below will check rest of params
+
+ dtFindNearestPolyQuery query(this, center);
+
+ dtStatus status = queryPolygons(center, halfExtents, filter, &query);
+ if (dtStatusFailed(status))
+ return status;
+
+ *nearestRef = query.nearestRef();
+ // Only override nearestPt if we actually found a poly so the nearest point
+ // is valid.
+ if (nearestPt && *nearestRef)
+ {
+ dtVcopy(nearestPt, query.nearestPoint());
+ if (isOverPoly)
+ *isOverPoly = query.isOverPoly();
+ }
+
+ return DT_SUCCESS;
+}
+
+void dtNavMeshQuery::queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
+ const dtQueryFilter* filter, dtPolyQuery* query) const
+{
+ dtAssert(m_nav);
+ static const int batchSize = 32;
+ dtPolyRef polyRefs[batchSize];
+ dtPoly* polys[batchSize];
+ int n = 0;
+
+ if (tile->bvTree)
+ {
+ const dtBVNode* node = &tile->bvTree[0];
+ const dtBVNode* end = &tile->bvTree[tile->header->bvNodeCount];
+ const float* tbmin = tile->header->bmin;
+ const float* tbmax = tile->header->bmax;
+ const float qfac = tile->header->bvQuantFactor;
+
+ // Calculate quantized box
+ unsigned short bmin[3], bmax[3];
+ // dtClamp query box to world box.
+ float minx = dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
+ float miny = dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
+ float minz = dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
+ float maxx = dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
+ float maxy = dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
+ float maxz = dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
+ // Quantize
+ bmin[0] = (unsigned short)(qfac * minx) & 0xfffe;
+ bmin[1] = (unsigned short)(qfac * miny) & 0xfffe;
+ bmin[2] = (unsigned short)(qfac * minz) & 0xfffe;
+ bmax[0] = (unsigned short)(qfac * maxx + 1) | 1;
+ bmax[1] = (unsigned short)(qfac * maxy + 1) | 1;
+ bmax[2] = (unsigned short)(qfac * maxz + 1) | 1;
+
+ // Traverse tree
+ const dtPolyRef base = m_nav->getPolyRefBase(tile);
+ while (node < end)
+ {
+ const bool overlap = dtOverlapQuantBounds(bmin, bmax, node->bmin, node->bmax);
+ const bool isLeafNode = node->i >= 0;
+
+ if (isLeafNode && overlap)
+ {
+ dtPolyRef ref = base | (dtPolyRef)node->i;
+ if (filter->passFilter(ref, tile, &tile->polys[node->i]))
+ {
+ polyRefs[n] = ref;
+ polys[n] = &tile->polys[node->i];
+
+ if (n == batchSize - 1)
+ {
+ query->process(tile, polys, polyRefs, batchSize);
+ n = 0;
+ }
+ else
+ {
+ n++;
+ }
+ }
+ }
+
+ if (overlap || isLeafNode)
+ node++;
+ else
+ {
+ const int escapeIndex = -node->i;
+ node += escapeIndex;
+ }
+ }
+ }
+ else
+ {
+ float bmin[3], bmax[3];
+ const dtPolyRef base = m_nav->getPolyRefBase(tile);
+ for (int i = 0; i < tile->header->polyCount; ++i)
+ {
+ dtPoly* p = &tile->polys[i];
+ // Do not return off-mesh connection polygons.
+ if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ continue;
+ // Must pass filter
+ const dtPolyRef ref = base | (dtPolyRef)i;
+ if (!filter->passFilter(ref, tile, p))
+ continue;
+ // Calc polygon bounds.
+ const float* v = &tile->verts[p->verts[0]*3];
+ dtVcopy(bmin, v);
+ dtVcopy(bmax, v);
+ for (int j = 1; j < p->vertCount; ++j)
+ {
+ v = &tile->verts[p->verts[j]*3];
+ dtVmin(bmin, v);
+ dtVmax(bmax, v);
+ }
+ if (dtOverlapBounds(qmin, qmax, bmin, bmax))
+ {
+ polyRefs[n] = ref;
+ polys[n] = p;
+
+ if (n == batchSize - 1)
+ {
+ query->process(tile, polys, polyRefs, batchSize);
+ n = 0;
+ }
+ else
+ {
+ n++;
+ }
+ }
+ }
+ }
+
+ // Process the last polygons that didn't make a full batch.
+ if (n > 0)
+ query->process(tile, polys, polyRefs, n);
+}
+
+class dtCollectPolysQuery : public dtPolyQuery
+{
+ dtPolyRef* m_polys;
+ const int m_maxPolys;
+ int m_numCollected;
+ bool m_overflow;
+
+public:
+ dtCollectPolysQuery(dtPolyRef* polys, const int maxPolys)
+ : m_polys(polys), m_maxPolys(maxPolys), m_numCollected(0), m_overflow(false)
+ {
+ }
+
+ virtual ~dtCollectPolysQuery();
+
+ int numCollected() const { return m_numCollected; }
+ bool overflowed() const { return m_overflow; }
+
+ void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count)
+ {
+ dtIgnoreUnused(tile);
+ dtIgnoreUnused(polys);
+
+ int numLeft = m_maxPolys - m_numCollected;
+ int toCopy = count;
+ if (toCopy > numLeft)
+ {
+ m_overflow = true;
+ toCopy = numLeft;
+ }
+
+ memcpy(m_polys + m_numCollected, refs, (size_t)toCopy * sizeof(dtPolyRef));
+ m_numCollected += toCopy;
+ }
+};
+
+dtCollectPolysQuery::~dtCollectPolysQuery()
+{
+ // Defined out of line to fix the weak v-tables warning
+}
+
+/// @par
+///
+/// If no polygons are found, the function will return #DT_SUCCESS with a
+/// @p polyCount of zero.
+///
+/// If @p polys is too small to hold the entire result set, then the array will
+/// be filled to capacity. The method of choosing which polygons from the
+/// full set are included in the partial result set is undefined.
+///
+dtStatus dtNavMeshQuery::queryPolygons(const float* center, const float* halfExtents,
+ const dtQueryFilter* filter,
+ dtPolyRef* polys, int* polyCount, const int maxPolys) const
+{
+ if (!polys || !polyCount || maxPolys < 0)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ dtCollectPolysQuery collector(polys, maxPolys);
+
+ dtStatus status = queryPolygons(center, halfExtents, filter, &collector);
+ if (dtStatusFailed(status))
+ return status;
+
+ *polyCount = collector.numCollected();
+ return collector.overflowed() ? DT_SUCCESS | DT_BUFFER_TOO_SMALL : DT_SUCCESS;
+}
+
+/// @par
+///
+/// The query will be invoked with batches of polygons. Polygons passed
+/// to the query have bounding boxes that overlap with the center and halfExtents
+/// passed to this function. The dtPolyQuery::process function is invoked multiple
+/// times until all overlapping polygons have been processed.
+///
+dtStatus dtNavMeshQuery::queryPolygons(const float* center, const float* halfExtents,
+ const dtQueryFilter* filter, dtPolyQuery* query) const
+{
+ dtAssert(m_nav);
+
+ if (!center || !dtVisfinite(center) ||
+ !halfExtents || !dtVisfinite(halfExtents) ||
+ !filter || !query)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ float bmin[3], bmax[3];
+ dtVsub(bmin, center, halfExtents);
+ dtVadd(bmax, center, halfExtents);
+
+ // Find tiles the query touches.
+ int minx, miny, maxx, maxy;
+ m_nav->calcTileLoc(bmin, &minx, &miny);
+ m_nav->calcTileLoc(bmax, &maxx, &maxy);
+
+ static const int MAX_NEIS = 32;
+ const dtMeshTile* neis[MAX_NEIS];
+
+ for (int y = miny; y <= maxy; ++y)
+ {
+ for (int x = minx; x <= maxx; ++x)
+ {
+ const int nneis = m_nav->getTilesAt(x,y,neis,MAX_NEIS);
+ for (int j = 0; j < nneis; ++j)
+ {
+ queryPolygonsInTile(neis[j], bmin, bmax, filter, query);
+ }
+ }
+ }
+
+ return DT_SUCCESS;
+}
+
+/// @par
+///
+/// If the end polygon cannot be reached through the navigation graph,
+/// the last polygon in the path will be the nearest the end polygon.
+///
+/// If the path array is to small to hold the full result, it will be filled as
+/// far as possible from the start polygon toward the end polygon.
+///
+/// The start and end positions are used to calculate traversal costs.
+/// (The y-values impact the result.)
+///
+dtStatus dtNavMeshQuery::findPath(dtPolyRef startRef, dtPolyRef endRef,
+ const float* startPos, const float* endPos,
+ const dtQueryFilter* filter,
+ dtPolyRef* path, int* pathCount, const int maxPath) const
+{
+ dtAssert(m_nav);
+ dtAssert(m_nodePool);
+ dtAssert(m_openList);
+
+ if (!pathCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *pathCount = 0;
+
+ // Validate input
+ if (!m_nav->isValidPolyRef(startRef) || !m_nav->isValidPolyRef(endRef) ||
+ !startPos || !dtVisfinite(startPos) ||
+ !endPos || !dtVisfinite(endPos) ||
+ !filter || !path || maxPath <= 0)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ if (startRef == endRef)
+ {
+ path[0] = startRef;
+ *pathCount = 1;
+ return DT_SUCCESS;
+ }
+
+ m_nodePool->clear();
+ m_openList->clear();
+
+ dtNode* startNode = m_nodePool->getNode(startRef);
+ dtVcopy(startNode->pos, startPos);
+ startNode->pidx = 0;
+ startNode->cost = 0;
+ startNode->total = dtVdist(startPos, endPos) * H_SCALE;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_OPEN;
+ m_openList->push(startNode);
+
+ dtNode* lastBestNode = startNode;
+ float lastBestNodeCost = startNode->total;
+
+ bool outOfNodes = false;
+
+ while (!m_openList->empty())
+ {
+ // Remove node from open list and put it in closed list.
+ dtNode* bestNode = m_openList->pop();
+ bestNode->flags &= ~DT_NODE_OPEN;
+ bestNode->flags |= DT_NODE_CLOSED;
+
+ // Reached the goal, stop searching.
+ if (bestNode->id == endRef)
+ {
+ lastBestNode = bestNode;
+ break;
+ }
+
+ // Get current poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef bestRef = bestNode->id;
+ const dtMeshTile* bestTile = 0;
+ const dtPoly* bestPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
+
+ // Get parent poly and tile.
+ dtPolyRef parentRef = 0;
+ const dtMeshTile* parentTile = 0;
+ const dtPoly* parentPoly = 0;
+ if (bestNode->pidx)
+ parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
+ if (parentRef)
+ m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
+
+ for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
+ {
+ dtPolyRef neighbourRef = bestTile->links[i].ref;
+
+ // Skip invalid ids and do not expand back to where we came from.
+ if (!neighbourRef || neighbourRef == parentRef)
+ continue;
+
+ // Get neighbour poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtMeshTile* neighbourTile = 0;
+ const dtPoly* neighbourPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
+
+ if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
+ continue;
+
+ // deal explicitly with crossing tile boundaries
+ unsigned char crossSide = 0;
+ if (bestTile->links[i].side != 0xff)
+ crossSide = bestTile->links[i].side >> 1;
+
+ // get the node
+ dtNode* neighbourNode = m_nodePool->getNode(neighbourRef, crossSide);
+ if (!neighbourNode)
+ {
+ outOfNodes = true;
+ continue;
+ }
+
+ // If the node is visited the first time, calculate node position.
+ if (neighbourNode->flags == 0)
+ {
+ getEdgeMidPoint(bestRef, bestPoly, bestTile,
+ neighbourRef, neighbourPoly, neighbourTile,
+ neighbourNode->pos);
+ }
+
+ // Calculate cost and heuristic.
+ float cost = 0;
+ float heuristic = 0;
+
+ // Special case for last node.
+ if (neighbourRef == endRef)
+ {
+ // Cost
+ const float curCost = filter->getCost(bestNode->pos, neighbourNode->pos,
+ parentRef, parentTile, parentPoly,
+ bestRef, bestTile, bestPoly,
+ neighbourRef, neighbourTile, neighbourPoly);
+ const float endCost = filter->getCost(neighbourNode->pos, endPos,
+ bestRef, bestTile, bestPoly,
+ neighbourRef, neighbourTile, neighbourPoly,
+ 0, 0, 0);
+
+ cost = bestNode->cost + curCost + endCost;
+ heuristic = 0;
+ }
+ else
+ {
+ // Cost
+ const float curCost = filter->getCost(bestNode->pos, neighbourNode->pos,
+ parentRef, parentTile, parentPoly,
+ bestRef, bestTile, bestPoly,
+ neighbourRef, neighbourTile, neighbourPoly);
+ cost = bestNode->cost + curCost;
+ heuristic = dtVdist(neighbourNode->pos, endPos)*H_SCALE;
+ }
+
+ const float total = cost + heuristic;
+
+ // The node is already in open list and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
+ continue;
+ // The node is already visited and process, and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_CLOSED) && total >= neighbourNode->total)
+ continue;
+
+ // Add or update the node.
+ neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
+ neighbourNode->id = neighbourRef;
+ neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED);
+ neighbourNode->cost = cost;
+ neighbourNode->total = total;
+
+ if (neighbourNode->flags & DT_NODE_OPEN)
+ {
+ // Already in open, update node location.
+ m_openList->modify(neighbourNode);
+ }
+ else
+ {
+ // Put the node in open list.
+ neighbourNode->flags |= DT_NODE_OPEN;
+ m_openList->push(neighbourNode);
+ }
+
+ // Update nearest node to target so far.
+ if (heuristic < lastBestNodeCost)
+ {
+ lastBestNodeCost = heuristic;
+ lastBestNode = neighbourNode;
+ }
+ }
+ }
+
+ dtStatus status = getPathToNode(lastBestNode, path, pathCount, maxPath);
+
+ if (lastBestNode->id != endRef)
+ status |= DT_PARTIAL_RESULT;
+
+ if (outOfNodes)
+ status |= DT_OUT_OF_NODES;
+
+ return status;
+}
+
+dtStatus dtNavMeshQuery::getPathToNode(dtNode* endNode, dtPolyRef* path, int* pathCount, int maxPath) const
+{
+ // Find the length of the entire path.
+ dtNode* curNode = endNode;
+ int length = 0;
+ do
+ {
+ length++;
+ curNode = m_nodePool->getNodeAtIdx(curNode->pidx);
+ } while (curNode);
+
+ // If the path cannot be fully stored then advance to the last node we will be able to store.
+ curNode = endNode;
+ int writeCount;
+ for (writeCount = length; writeCount > maxPath; writeCount--)
+ {
+ dtAssert(curNode);
+
+ curNode = m_nodePool->getNodeAtIdx(curNode->pidx);
+ }
+
+ // Write path
+ for (int i = writeCount - 1; i >= 0; i--)
+ {
+ dtAssert(curNode);
+
+ path[i] = curNode->id;
+ curNode = m_nodePool->getNodeAtIdx(curNode->pidx);
+ }
+
+ dtAssert(!curNode);
+
+ *pathCount = dtMin(length, maxPath);
+
+ if (length > maxPath)
+ return DT_SUCCESS | DT_BUFFER_TOO_SMALL;
+
+ return DT_SUCCESS;
+}
+
+
+/// @par
+///
+/// @warning Calling any non-slice methods before calling finalizeSlicedFindPath()
+/// or finalizeSlicedFindPathPartial() may result in corrupted data!
+///
+/// The @p filter pointer is stored and used for the duration of the sliced
+/// path query.
+///
+dtStatus dtNavMeshQuery::initSlicedFindPath(dtPolyRef startRef, dtPolyRef endRef,
+ const float* startPos, const float* endPos,
+ const dtQueryFilter* filter, const unsigned int options)
+{
+ dtAssert(m_nav);
+ dtAssert(m_nodePool);
+ dtAssert(m_openList);
+
+ // Init path state.
+ memset(&m_query, 0, sizeof(dtQueryData));
+ m_query.status = DT_FAILURE;
+ m_query.startRef = startRef;
+ m_query.endRef = endRef;
+ if (startPos)
+ dtVcopy(m_query.startPos, startPos);
+ if (endPos)
+ dtVcopy(m_query.endPos, endPos);
+ m_query.filter = filter;
+ m_query.options = options;
+ m_query.raycastLimitSqr = FLT_MAX;
+
+ // Validate input
+ if (!m_nav->isValidPolyRef(startRef) || !m_nav->isValidPolyRef(endRef) ||
+ !startPos || !dtVisfinite(startPos) ||
+ !endPos || !dtVisfinite(endPos) || !filter)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ // trade quality with performance?
+ if (options & DT_FINDPATH_ANY_ANGLE)
+ {
+ // limiting to several times the character radius yields nice results. It is not sensitive
+ // so it is enough to compute it from the first tile.
+ const dtMeshTile* tile = m_nav->getTileByRef(startRef);
+ float agentRadius = tile->header->walkableRadius;
+ m_query.raycastLimitSqr = dtSqr(agentRadius * DT_RAY_CAST_LIMIT_PROPORTIONS);
+ }
+
+ if (startRef == endRef)
+ {
+ m_query.status = DT_SUCCESS;
+ return DT_SUCCESS;
+ }
+
+ m_nodePool->clear();
+ m_openList->clear();
+
+ dtNode* startNode = m_nodePool->getNode(startRef);
+ dtVcopy(startNode->pos, startPos);
+ startNode->pidx = 0;
+ startNode->cost = 0;
+ startNode->total = dtVdist(startPos, endPos) * H_SCALE;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_OPEN;
+ m_openList->push(startNode);
+
+ m_query.status = DT_IN_PROGRESS;
+ m_query.lastBestNode = startNode;
+ m_query.lastBestNodeCost = startNode->total;
+
+ return m_query.status;
+}
+
+dtStatus dtNavMeshQuery::updateSlicedFindPath(const int maxIter, int* doneIters)
+{
+ if (!dtStatusInProgress(m_query.status))
+ return m_query.status;
+
+ // Make sure the request is still valid.
+ if (!m_nav->isValidPolyRef(m_query.startRef) || !m_nav->isValidPolyRef(m_query.endRef))
+ {
+ m_query.status = DT_FAILURE;
+ return DT_FAILURE;
+ }
+
+ dtRaycastHit rayHit;
+ rayHit.maxPath = 0;
+
+ int iter = 0;
+ while (iter < maxIter && !m_openList->empty())
+ {
+ iter++;
+
+ // Remove node from open list and put it in closed list.
+ dtNode* bestNode = m_openList->pop();
+ bestNode->flags &= ~DT_NODE_OPEN;
+ bestNode->flags |= DT_NODE_CLOSED;
+
+ // Reached the goal, stop searching.
+ if (bestNode->id == m_query.endRef)
+ {
+ m_query.lastBestNode = bestNode;
+ const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
+ m_query.status = DT_SUCCESS | details;
+ if (doneIters)
+ *doneIters = iter;
+ return m_query.status;
+ }
+
+ // Get current poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef bestRef = bestNode->id;
+ const dtMeshTile* bestTile = 0;
+ const dtPoly* bestPoly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(bestRef, &bestTile, &bestPoly)))
+ {
+ // The polygon has disappeared during the sliced query, fail.
+ m_query.status = DT_FAILURE;
+ if (doneIters)
+ *doneIters = iter;
+ return m_query.status;
+ }
+
+ // Get parent and grand parent poly and tile.
+ dtPolyRef parentRef = 0, grandpaRef = 0;
+ const dtMeshTile* parentTile = 0;
+ const dtPoly* parentPoly = 0;
+ dtNode* parentNode = 0;
+ if (bestNode->pidx)
+ {
+ parentNode = m_nodePool->getNodeAtIdx(bestNode->pidx);
+ parentRef = parentNode->id;
+ if (parentNode->pidx)
+ grandpaRef = m_nodePool->getNodeAtIdx(parentNode->pidx)->id;
+ }
+ if (parentRef)
+ {
+ bool invalidParent = dtStatusFailed(m_nav->getTileAndPolyByRef(parentRef, &parentTile, &parentPoly));
+ if (invalidParent || (grandpaRef && !m_nav->isValidPolyRef(grandpaRef)) )
+ {
+ // The polygon has disappeared during the sliced query, fail.
+ m_query.status = DT_FAILURE;
+ if (doneIters)
+ *doneIters = iter;
+ return m_query.status;
+ }
+ }
+
+ // decide whether to test raycast to previous nodes
+ bool tryLOS = false;
+ if (m_query.options & DT_FINDPATH_ANY_ANGLE)
+ {
+ if ((parentRef != 0) && (dtVdistSqr(parentNode->pos, bestNode->pos) < m_query.raycastLimitSqr))
+ tryLOS = true;
+ }
+
+ for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
+ {
+ dtPolyRef neighbourRef = bestTile->links[i].ref;
+
+ // Skip invalid ids and do not expand back to where we came from.
+ if (!neighbourRef || neighbourRef == parentRef)
+ continue;
+
+ // Get neighbour poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtMeshTile* neighbourTile = 0;
+ const dtPoly* neighbourPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
+
+ if (!m_query.filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
+ continue;
+
+ // get the neighbor node
+ dtNode* neighbourNode = m_nodePool->getNode(neighbourRef, 0);
+ if (!neighbourNode)
+ {
+ m_query.status |= DT_OUT_OF_NODES;
+ continue;
+ }
+
+ // do not expand to nodes that were already visited from the same parent
+ if (neighbourNode->pidx != 0 && neighbourNode->pidx == bestNode->pidx)
+ continue;
+
+ // If the node is visited the first time, calculate node position.
+ if (neighbourNode->flags == 0)
+ {
+ getEdgeMidPoint(bestRef, bestPoly, bestTile,
+ neighbourRef, neighbourPoly, neighbourTile,
+ neighbourNode->pos);
+ }
+
+ // Calculate cost and heuristic.
+ float cost = 0;
+ float heuristic = 0;
+
+ // raycast parent
+ bool foundShortCut = false;
+ rayHit.pathCost = rayHit.t = 0;
+ if (tryLOS)
+ {
+ raycast(parentRef, parentNode->pos, neighbourNode->pos, m_query.filter, DT_RAYCAST_USE_COSTS, &rayHit, grandpaRef);
+ foundShortCut = rayHit.t >= 1.0f;
+ }
+
+ // update move cost
+ if (foundShortCut)
+ {
+ // shortcut found using raycast. Using shorter cost instead
+ cost = parentNode->cost + rayHit.pathCost;
+ }
+ else
+ {
+ // No shortcut found.
+ const float curCost = m_query.filter->getCost(bestNode->pos, neighbourNode->pos,
+ parentRef, parentTile, parentPoly,
+ bestRef, bestTile, bestPoly,
+ neighbourRef, neighbourTile, neighbourPoly);
+ cost = bestNode->cost + curCost;
+ }
+
+ // Special case for last node.
+ if (neighbourRef == m_query.endRef)
+ {
+ const float endCost = m_query.filter->getCost(neighbourNode->pos, m_query.endPos,
+ bestRef, bestTile, bestPoly,
+ neighbourRef, neighbourTile, neighbourPoly,
+ 0, 0, 0);
+
+ cost = cost + endCost;
+ heuristic = 0;
+ }
+ else
+ {
+ heuristic = dtVdist(neighbourNode->pos, m_query.endPos)*H_SCALE;
+ }
+
+ const float total = cost + heuristic;
+
+ // The node is already in open list and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
+ continue;
+ // The node is already visited and process, and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_CLOSED) && total >= neighbourNode->total)
+ continue;
+
+ // Add or update the node.
+ neighbourNode->pidx = foundShortCut ? bestNode->pidx : m_nodePool->getNodeIdx(bestNode);
+ neighbourNode->id = neighbourRef;
+ neighbourNode->flags = (neighbourNode->flags & ~(DT_NODE_CLOSED | DT_NODE_PARENT_DETACHED));
+ neighbourNode->cost = cost;
+ neighbourNode->total = total;
+ if (foundShortCut)
+ neighbourNode->flags = (neighbourNode->flags | DT_NODE_PARENT_DETACHED);
+
+ if (neighbourNode->flags & DT_NODE_OPEN)
+ {
+ // Already in open, update node location.
+ m_openList->modify(neighbourNode);
+ }
+ else
+ {
+ // Put the node in open list.
+ neighbourNode->flags |= DT_NODE_OPEN;
+ m_openList->push(neighbourNode);
+ }
+
+ // Update nearest node to target so far.
+ if (heuristic < m_query.lastBestNodeCost)
+ {
+ m_query.lastBestNodeCost = heuristic;
+ m_query.lastBestNode = neighbourNode;
+ }
+ }
+ }
+
+ // Exhausted all nodes, but could not find path.
+ if (m_openList->empty())
+ {
+ const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
+ m_query.status = DT_SUCCESS | details;
+ }
+
+ if (doneIters)
+ *doneIters = iter;
+
+ return m_query.status;
+}
+
+dtStatus dtNavMeshQuery::finalizeSlicedFindPath(dtPolyRef* path, int* pathCount, const int maxPath)
+{
+ if (!pathCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *pathCount = 0;
+
+ if (!path || maxPath <= 0)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ if (dtStatusFailed(m_query.status))
+ {
+ // Reset query.
+ memset(&m_query, 0, sizeof(dtQueryData));
+ return DT_FAILURE;
+ }
+
+ int n = 0;
+
+ if (m_query.startRef == m_query.endRef)
+ {
+ // Special case: the search starts and ends at same poly.
+ path[n++] = m_query.startRef;
+ }
+ else
+ {
+ // Reverse the path.
+ dtAssert(m_query.lastBestNode);
+
+ if (m_query.lastBestNode->id != m_query.endRef)
+ m_query.status |= DT_PARTIAL_RESULT;
+
+ dtNode* prev = 0;
+ dtNode* node = m_query.lastBestNode;
+ int prevRay = 0;
+ do
+ {
+ dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
+ node->pidx = m_nodePool->getNodeIdx(prev);
+ prev = node;
+ int nextRay = node->flags & DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)
+ node->flags = (node->flags & ~DT_NODE_PARENT_DETACHED) | prevRay; // and store it in the reversed path's node
+ prevRay = nextRay;
+ node = next;
+ }
+ while (node);
+
+ // Store path
+ node = prev;
+ do
+ {
+ dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
+ dtStatus status = 0;
+ if (node->flags & DT_NODE_PARENT_DETACHED)
+ {
+ float t, normal[3];
+ int m;
+ status = raycast(node->id, node->pos, next->pos, m_query.filter, &t, normal, path+n, &m, maxPath-n);
+ n += m;
+ // raycast ends on poly boundary and the path might include the next poly boundary.
+ if (path[n-1] == next->id)
+ n--; // remove to avoid duplicates
+ }
+ else
+ {
+ path[n++] = node->id;
+ if (n >= maxPath)
+ status = DT_BUFFER_TOO_SMALL;
+ }
+
+ if (status & DT_STATUS_DETAIL_MASK)
+ {
+ m_query.status |= status & DT_STATUS_DETAIL_MASK;
+ break;
+ }
+ node = next;
+ }
+ while (node);
+ }
+
+ const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
+
+ // Reset query.
+ memset(&m_query, 0, sizeof(dtQueryData));
+
+ *pathCount = n;
+
+ return DT_SUCCESS | details;
+}
+
+dtStatus dtNavMeshQuery::finalizeSlicedFindPathPartial(const dtPolyRef* existing, const int existingSize,
+ dtPolyRef* path, int* pathCount, const int maxPath)
+{
+ if (!pathCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *pathCount = 0;
+
+ if (!existing || existingSize <= 0 || !path || !pathCount || maxPath <= 0)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ if (dtStatusFailed(m_query.status))
+ {
+ // Reset query.
+ memset(&m_query, 0, sizeof(dtQueryData));
+ return DT_FAILURE;
+ }
+
+ int n = 0;
+
+ if (m_query.startRef == m_query.endRef)
+ {
+ // Special case: the search starts and ends at same poly.
+ path[n++] = m_query.startRef;
+ }
+ else
+ {
+ // Find furthest existing node that was visited.
+ dtNode* prev = 0;
+ dtNode* node = 0;
+ for (int i = existingSize-1; i >= 0; --i)
+ {
+ m_nodePool->findNodes(existing[i], &node, 1);
+ if (node)
+ break;
+ }
+
+ if (!node)
+ {
+ m_query.status |= DT_PARTIAL_RESULT;
+ dtAssert(m_query.lastBestNode);
+ node = m_query.lastBestNode;
+ }
+
+ // Reverse the path.
+ int prevRay = 0;
+ do
+ {
+ dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
+ node->pidx = m_nodePool->getNodeIdx(prev);
+ prev = node;
+ int nextRay = node->flags & DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)
+ node->flags = (node->flags & ~DT_NODE_PARENT_DETACHED) | prevRay; // and store it in the reversed path's node
+ prevRay = nextRay;
+ node = next;
+ }
+ while (node);
+
+ // Store path
+ node = prev;
+ do
+ {
+ dtNode* next = m_nodePool->getNodeAtIdx(node->pidx);
+ dtStatus status = 0;
+ if (node->flags & DT_NODE_PARENT_DETACHED)
+ {
+ float t, normal[3];
+ int m;
+ status = raycast(node->id, node->pos, next->pos, m_query.filter, &t, normal, path+n, &m, maxPath-n);
+ n += m;
+ // raycast ends on poly boundary and the path might include the next poly boundary.
+ if (path[n-1] == next->id)
+ n--; // remove to avoid duplicates
+ }
+ else
+ {
+ path[n++] = node->id;
+ if (n >= maxPath)
+ status = DT_BUFFER_TOO_SMALL;
+ }
+
+ if (status & DT_STATUS_DETAIL_MASK)
+ {
+ m_query.status |= status & DT_STATUS_DETAIL_MASK;
+ break;
+ }
+ node = next;
+ }
+ while (node);
+ }
+
+ const dtStatus details = m_query.status & DT_STATUS_DETAIL_MASK;
+
+ // Reset query.
+ memset(&m_query, 0, sizeof(dtQueryData));
+
+ *pathCount = n;
+
+ return DT_SUCCESS | details;
+}
+
+
+dtStatus dtNavMeshQuery::appendVertex(const float* pos, const unsigned char flags, const dtPolyRef ref,
+ float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
+ int* straightPathCount, const int maxStraightPath) const
+{
+ if ((*straightPathCount) > 0 && dtVequal(&straightPath[((*straightPathCount)-1)*3], pos))
+ {
+ // The vertices are equal, update flags and poly.
+ if (straightPathFlags)
+ straightPathFlags[(*straightPathCount)-1] = flags;
+ if (straightPathRefs)
+ straightPathRefs[(*straightPathCount)-1] = ref;
+ }
+ else
+ {
+ // Append new vertex.
+ dtVcopy(&straightPath[(*straightPathCount)*3], pos);
+ if (straightPathFlags)
+ straightPathFlags[(*straightPathCount)] = flags;
+ if (straightPathRefs)
+ straightPathRefs[(*straightPathCount)] = ref;
+ (*straightPathCount)++;
+
+ // If there is no space to append more vertices, return.
+ if ((*straightPathCount) >= maxStraightPath)
+ {
+ return DT_SUCCESS | DT_BUFFER_TOO_SMALL;
+ }
+
+ // If reached end of path, return.
+ if (flags == DT_STRAIGHTPATH_END)
+ {
+ return DT_SUCCESS;
+ }
+ }
+ return DT_IN_PROGRESS;
+}
+
+dtStatus dtNavMeshQuery::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
+{
+ const float* startPos = &straightPath[(*straightPathCount-1)*3];
+ // Append or update last vertex
+ dtStatus stat = 0;
+ for (int i = startIdx; i < endIdx; i++)
+ {
+ // Calculate portal
+ const dtPolyRef from = path[i];
+ const dtMeshTile* fromTile = 0;
+ const dtPoly* fromPoly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(from, &fromTile, &fromPoly)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ const dtPolyRef to = path[i+1];
+ const dtMeshTile* toTile = 0;
+ const dtPoly* toPoly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(to, &toTile, &toPoly)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ float left[3], right[3];
+ if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right)))
+ break;
+
+ if (options & DT_STRAIGHTPATH_AREA_CROSSINGS)
+ {
+ // Skip intersection if only area crossings are requested.
+ if (fromPoly->getArea() == toPoly->getArea())
+ continue;
+ }
+
+ // Append intersection
+ float s,t;
+ if (dtIntersectSegSeg2D(startPos, endPos, left, right, s, t))
+ {
+ float pt[3];
+ dtVlerp(pt, left,right, t);
+
+ stat = appendVertex(pt, 0, path[i+1],
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath);
+ if (stat != DT_IN_PROGRESS)
+ return stat;
+ }
+ }
+ return DT_IN_PROGRESS;
+}
+
+/// @par
+///
+/// This method peforms what is often called 'string pulling'.
+///
+/// The start position is clamped to the first polygon in the path, and the
+/// end position is clamped to the last. So the start and end positions should
+/// normally be within or very near the first and last polygons respectively.
+///
+/// The returned polygon references represent the reference id of the polygon
+/// that is entered at the associated path position. The reference id associated
+/// with the end point will always be zero. This allows, for example, matching
+/// off-mesh link points to their representative polygons.
+///
+/// If the provided result buffers are too small for the entire result set,
+/// they will be filled as far as possible from the start toward the end
+/// position.
+///
+dtStatus dtNavMeshQuery::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) const
+{
+ dtAssert(m_nav);
+
+ if (!straightPathCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *straightPathCount = 0;
+
+ if (!startPos || !dtVisfinite(startPos) ||
+ !endPos || !dtVisfinite(endPos) ||
+ !path || pathSize <= 0 || !path[0] ||
+ maxStraightPath <= 0)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ dtStatus stat = 0;
+
+ // TODO: Should this be callers responsibility?
+ float closestStartPos[3];
+ if (dtStatusFailed(closestPointOnPolyBoundary(path[0], startPos, closestStartPos)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ float closestEndPos[3];
+ if (dtStatusFailed(closestPointOnPolyBoundary(path[pathSize-1], endPos, closestEndPos)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // Add start point.
+ stat = appendVertex(closestStartPos, DT_STRAIGHTPATH_START, path[0],
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath);
+ if (stat != DT_IN_PROGRESS)
+ return stat;
+
+ if (pathSize > 1)
+ {
+ float portalApex[3], portalLeft[3], portalRight[3];
+ dtVcopy(portalApex, closestStartPos);
+ dtVcopy(portalLeft, portalApex);
+ dtVcopy(portalRight, portalApex);
+ int apexIndex = 0;
+ int leftIndex = 0;
+ int rightIndex = 0;
+
+ unsigned char leftPolyType = 0;
+ unsigned char rightPolyType = 0;
+
+ dtPolyRef leftPolyRef = path[0];
+ dtPolyRef rightPolyRef = path[0];
+
+ for (int i = 0; i < pathSize; ++i)
+ {
+ float left[3], right[3];
+ unsigned char toType;
+
+ if (i+1 < pathSize)
+ {
+ unsigned char fromType; // fromType is ignored.
+
+ // Next portal.
+ if (dtStatusFailed(getPortalPoints(path[i], path[i+1], left, right, fromType, toType)))
+ {
+ // Failed to get portal points, in practice this means that path[i+1] is invalid polygon.
+ // Clamp the end point to path[i], and return the path so far.
+
+ if (dtStatusFailed(closestPointOnPolyBoundary(path[i], endPos, closestEndPos)))
+ {
+ // This should only happen when the first polygon is invalid.
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ // Apeend portals along the current straight path segment.
+ if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
+ {
+ // Ignore status return value as we're just about to return anyway.
+ appendPortals(apexIndex, i, closestEndPos, path,
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath, options);
+ }
+
+ // Ignore status return value as we're just about to return anyway.
+ appendVertex(closestEndPos, 0, path[i],
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath);
+
+ return DT_SUCCESS | DT_PARTIAL_RESULT | ((*straightPathCount >= maxStraightPath) ? DT_BUFFER_TOO_SMALL : 0);
+ }
+
+ // If starting really close the portal, advance.
+ if (i == 0)
+ {
+ float t;
+ if (dtDistancePtSegSqr2D(portalApex, left, right, t) < dtSqr(0.001f))
+ continue;
+ }
+ }
+ else
+ {
+ // End of the path.
+ dtVcopy(left, closestEndPos);
+ dtVcopy(right, closestEndPos);
+
+ toType = DT_POLYTYPE_GROUND;
+ }
+
+ // Right vertex.
+ if (dtTriArea2D(portalApex, portalRight, right) <= 0.0f)
+ {
+ if (dtVequal(portalApex, portalRight) || dtTriArea2D(portalApex, portalLeft, right) > 0.0f)
+ {
+ dtVcopy(portalRight, right);
+ rightPolyRef = (i+1 < pathSize) ? path[i+1] : 0;
+ rightPolyType = toType;
+ rightIndex = i;
+ }
+ else
+ {
+ // Append portals along the current straight path segment.
+ if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
+ {
+ stat = appendPortals(apexIndex, leftIndex, portalLeft, path,
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath, options);
+ if (stat != DT_IN_PROGRESS)
+ return stat;
+ }
+
+ dtVcopy(portalApex, portalLeft);
+ apexIndex = leftIndex;
+
+ unsigned char flags = 0;
+ if (!leftPolyRef)
+ flags = DT_STRAIGHTPATH_END;
+ else if (leftPolyType == DT_POLYTYPE_OFFMESH_CONNECTION)
+ flags = DT_STRAIGHTPATH_OFFMESH_CONNECTION;
+ dtPolyRef ref = leftPolyRef;
+
+ // Append or update vertex
+ stat = appendVertex(portalApex, flags, ref,
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath);
+ if (stat != DT_IN_PROGRESS)
+ return stat;
+
+ dtVcopy(portalLeft, portalApex);
+ dtVcopy(portalRight, portalApex);
+ leftIndex = apexIndex;
+ rightIndex = apexIndex;
+
+ // Restart
+ i = apexIndex;
+
+ continue;
+ }
+ }
+
+ // Left vertex.
+ if (dtTriArea2D(portalApex, portalLeft, left) >= 0.0f)
+ {
+ if (dtVequal(portalApex, portalLeft) || dtTriArea2D(portalApex, portalRight, left) < 0.0f)
+ {
+ dtVcopy(portalLeft, left);
+ leftPolyRef = (i+1 < pathSize) ? path[i+1] : 0;
+ leftPolyType = toType;
+ leftIndex = i;
+ }
+ else
+ {
+ // Append portals along the current straight path segment.
+ if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
+ {
+ stat = appendPortals(apexIndex, rightIndex, portalRight, path,
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath, options);
+ if (stat != DT_IN_PROGRESS)
+ return stat;
+ }
+
+ dtVcopy(portalApex, portalRight);
+ apexIndex = rightIndex;
+
+ unsigned char flags = 0;
+ if (!rightPolyRef)
+ flags = DT_STRAIGHTPATH_END;
+ else if (rightPolyType == DT_POLYTYPE_OFFMESH_CONNECTION)
+ flags = DT_STRAIGHTPATH_OFFMESH_CONNECTION;
+ dtPolyRef ref = rightPolyRef;
+
+ // Append or update vertex
+ stat = appendVertex(portalApex, flags, ref,
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath);
+ if (stat != DT_IN_PROGRESS)
+ return stat;
+
+ dtVcopy(portalLeft, portalApex);
+ dtVcopy(portalRight, portalApex);
+ leftIndex = apexIndex;
+ rightIndex = apexIndex;
+
+ // Restart
+ i = apexIndex;
+
+ continue;
+ }
+ }
+ }
+
+ // Append portals along the current straight path segment.
+ if (options & (DT_STRAIGHTPATH_AREA_CROSSINGS | DT_STRAIGHTPATH_ALL_CROSSINGS))
+ {
+ stat = appendPortals(apexIndex, pathSize-1, closestEndPos, path,
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath, options);
+ if (stat != DT_IN_PROGRESS)
+ return stat;
+ }
+ }
+
+ // Ignore status return value as we're just about to return anyway.
+ appendVertex(closestEndPos, DT_STRAIGHTPATH_END, 0,
+ straightPath, straightPathFlags, straightPathRefs,
+ straightPathCount, maxStraightPath);
+
+ return DT_SUCCESS | ((*straightPathCount >= maxStraightPath) ? DT_BUFFER_TOO_SMALL : 0);
+}
+
+/// @par
+///
+/// This method is optimized for small delta movement and a small number of
+/// polygons. If used for too great a distance, the result set will form an
+/// incomplete path.
+///
+/// @p resultPos will equal the @p endPos if the end is reached.
+/// Otherwise the closest reachable position will be returned.
+///
+/// @p resultPos is not projected onto the surface of the navigation
+/// mesh. Use #getPolyHeight if this is needed.
+///
+/// This method treats the end position in the same manner as
+/// the #raycast method. (As a 2D point.) See that method's documentation
+/// for details.
+///
+/// If the @p visited array is too small to hold the entire result set, it will
+/// be filled as far as possible from the start position toward the end
+/// position.
+///
+dtStatus dtNavMeshQuery::moveAlongSurface(dtPolyRef startRef, const float* startPos, const float* endPos,
+ const dtQueryFilter* filter,
+ float* resultPos, dtPolyRef* visited, int* visitedCount, const int maxVisitedSize) const
+{
+ dtAssert(m_nav);
+ dtAssert(m_tinyNodePool);
+
+ if (!visitedCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *visitedCount = 0;
+
+ if (!m_nav->isValidPolyRef(startRef) ||
+ !startPos || !dtVisfinite(startPos) ||
+ !endPos || !dtVisfinite(endPos) ||
+ !filter || !resultPos || !visited ||
+ maxVisitedSize <= 0)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ dtStatus status = DT_SUCCESS;
+
+ static const int MAX_STACK = 48;
+ dtNode* stack[MAX_STACK];
+ int nstack = 0;
+
+ m_tinyNodePool->clear();
+
+ dtNode* startNode = m_tinyNodePool->getNode(startRef);
+ startNode->pidx = 0;
+ startNode->cost = 0;
+ startNode->total = 0;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_CLOSED;
+ stack[nstack++] = startNode;
+
+ float bestPos[3];
+ float bestDist = FLT_MAX;
+ dtNode* bestNode = 0;
+ dtVcopy(bestPos, startPos);
+
+ // Search constraints
+ float searchPos[3], searchRadSqr;
+ dtVlerp(searchPos, startPos, endPos, 0.5f);
+ searchRadSqr = dtSqr(dtVdist(startPos, endPos)/2.0f + 0.001f);
+
+ float verts[DT_VERTS_PER_POLYGON*3];
+
+ while (nstack)
+ {
+ // Pop front.
+ dtNode* curNode = stack[0];
+ for (int i = 0; i < nstack-1; ++i)
+ stack[i] = stack[i+1];
+ nstack--;
+
+ // Get poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef curRef = curNode->id;
+ const dtMeshTile* curTile = 0;
+ const dtPoly* curPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(curRef, &curTile, &curPoly);
+
+ // Collect vertices.
+ const int nverts = curPoly->vertCount;
+ for (int i = 0; i < nverts; ++i)
+ dtVcopy(&verts[i*3], &curTile->verts[curPoly->verts[i]*3]);
+
+ // If target is inside the poly, stop search.
+ if (dtPointInPolygon(endPos, verts, nverts))
+ {
+ bestNode = curNode;
+ dtVcopy(bestPos, endPos);
+ break;
+ }
+
+ // Find wall edges and find nearest point inside the walls.
+ for (int i = 0, j = (int)curPoly->vertCount-1; i < (int)curPoly->vertCount; j = i++)
+ {
+ // Find links to neighbours.
+ static const int MAX_NEIS = 8;
+ int nneis = 0;
+ dtPolyRef neis[MAX_NEIS];
+
+ if (curPoly->neis[j] & DT_EXT_LINK)
+ {
+ // Tile border.
+ for (unsigned int k = curPoly->firstLink; k != DT_NULL_LINK; k = curTile->links[k].next)
+ {
+ const dtLink* link = &curTile->links[k];
+ if (link->edge == j)
+ {
+ if (link->ref != 0)
+ {
+ const dtMeshTile* neiTile = 0;
+ const dtPoly* neiPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly);
+ if (filter->passFilter(link->ref, neiTile, neiPoly))
+ {
+ if (nneis < MAX_NEIS)
+ neis[nneis++] = link->ref;
+ }
+ }
+ }
+ }
+ }
+ else if (curPoly->neis[j])
+ {
+ const unsigned int idx = (unsigned int)(curPoly->neis[j]-1);
+ const dtPolyRef ref = m_nav->getPolyRefBase(curTile) | idx;
+ if (filter->passFilter(ref, curTile, &curTile->polys[idx]))
+ {
+ // Internal edge, encode id.
+ neis[nneis++] = ref;
+ }
+ }
+
+ if (!nneis)
+ {
+ // Wall edge, calc distance.
+ const float* vj = &verts[j*3];
+ const float* vi = &verts[i*3];
+ float tseg;
+ const float distSqr = dtDistancePtSegSqr2D(endPos, vj, vi, tseg);
+ if (distSqr < bestDist)
+ {
+ // Update nearest distance.
+ dtVlerp(bestPos, vj,vi, tseg);
+ bestDist = distSqr;
+ bestNode = curNode;
+ }
+ }
+ else
+ {
+ for (int k = 0; k < nneis; ++k)
+ {
+ // Skip if no node can be allocated.
+ dtNode* neighbourNode = m_tinyNodePool->getNode(neis[k]);
+ if (!neighbourNode)
+ continue;
+ // Skip if already visited.
+ if (neighbourNode->flags & DT_NODE_CLOSED)
+ continue;
+
+ // Skip the link if it is too far from search constraint.
+ // TODO: Maybe should use getPortalPoints(), but this one is way faster.
+ const float* vj = &verts[j*3];
+ const float* vi = &verts[i*3];
+ float tseg;
+ float distSqr = dtDistancePtSegSqr2D(searchPos, vj, vi, tseg);
+ if (distSqr > searchRadSqr)
+ continue;
+
+ // Mark as the node as visited and push to queue.
+ if (nstack < MAX_STACK)
+ {
+ neighbourNode->pidx = m_tinyNodePool->getNodeIdx(curNode);
+ neighbourNode->flags |= DT_NODE_CLOSED;
+ stack[nstack++] = neighbourNode;
+ }
+ }
+ }
+ }
+ }
+
+ int n = 0;
+ if (bestNode)
+ {
+ // Reverse the path.
+ dtNode* prev = 0;
+ dtNode* node = bestNode;
+ do
+ {
+ dtNode* next = m_tinyNodePool->getNodeAtIdx(node->pidx);
+ node->pidx = m_tinyNodePool->getNodeIdx(prev);
+ prev = node;
+ node = next;
+ }
+ while (node);
+
+ // Store result
+ node = prev;
+ do
+ {
+ visited[n++] = node->id;
+ if (n >= maxVisitedSize)
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ break;
+ }
+ node = m_tinyNodePool->getNodeAtIdx(node->pidx);
+ }
+ while (node);
+ }
+
+ dtVcopy(resultPos, bestPos);
+
+ *visitedCount = n;
+
+ return status;
+}
+
+
+dtStatus dtNavMeshQuery::getPortalPoints(dtPolyRef from, dtPolyRef to, float* left, float* right,
+ unsigned char& fromType, unsigned char& toType) const
+{
+ dtAssert(m_nav);
+
+ const dtMeshTile* fromTile = 0;
+ const dtPoly* fromPoly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(from, &fromTile, &fromPoly)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+ fromType = fromPoly->getType();
+
+ const dtMeshTile* toTile = 0;
+ const dtPoly* toPoly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(to, &toTile, &toPoly)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+ toType = toPoly->getType();
+
+ return getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right);
+}
+
+// Returns portal points between two polygons.
+dtStatus dtNavMeshQuery::getPortalPoints(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
+ dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
+ float* left, float* right) const
+{
+ // Find the link that points to the 'to' polygon.
+ const dtLink* link = 0;
+ for (unsigned int i = fromPoly->firstLink; i != DT_NULL_LINK; i = fromTile->links[i].next)
+ {
+ if (fromTile->links[i].ref == to)
+ {
+ link = &fromTile->links[i];
+ break;
+ }
+ }
+ if (!link)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ // Handle off-mesh connections.
+ if (fromPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ {
+ // Find link that points to first vertex.
+ for (unsigned int i = fromPoly->firstLink; i != DT_NULL_LINK; i = fromTile->links[i].next)
+ {
+ if (fromTile->links[i].ref == to)
+ {
+ const int v = fromTile->links[i].edge;
+ dtVcopy(left, &fromTile->verts[fromPoly->verts[v]*3]);
+ dtVcopy(right, &fromTile->verts[fromPoly->verts[v]*3]);
+ return DT_SUCCESS;
+ }
+ }
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ if (toPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ {
+ for (unsigned int i = toPoly->firstLink; i != DT_NULL_LINK; i = toTile->links[i].next)
+ {
+ if (toTile->links[i].ref == from)
+ {
+ const int v = toTile->links[i].edge;
+ dtVcopy(left, &toTile->verts[toPoly->verts[v]*3]);
+ dtVcopy(right, &toTile->verts[toPoly->verts[v]*3]);
+ return DT_SUCCESS;
+ }
+ }
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ // Find portal vertices.
+ const int v0 = fromPoly->verts[link->edge];
+ const int v1 = fromPoly->verts[(link->edge+1) % (int)fromPoly->vertCount];
+ dtVcopy(left, &fromTile->verts[v0*3]);
+ dtVcopy(right, &fromTile->verts[v1*3]);
+
+ // If the link is at tile boundary, dtClamp the vertices to
+ // the link width.
+ if (link->side != 0xff)
+ {
+ // Unpack portal limits.
+ if (link->bmin != 0 || link->bmax != 255)
+ {
+ const float s = 1.0f/255.0f;
+ const float tmin = link->bmin*s;
+ const float tmax = link->bmax*s;
+ dtVlerp(left, &fromTile->verts[v0*3], &fromTile->verts[v1*3], tmin);
+ dtVlerp(right, &fromTile->verts[v0*3], &fromTile->verts[v1*3], tmax);
+ }
+ }
+
+ return DT_SUCCESS;
+}
+
+// Returns edge mid point between two polygons.
+dtStatus dtNavMeshQuery::getEdgeMidPoint(dtPolyRef from, dtPolyRef to, float* mid) const
+{
+ float left[3], right[3];
+ unsigned char fromType, toType;
+ if (dtStatusFailed(getPortalPoints(from, to, left,right, fromType, toType)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+ mid[0] = (left[0]+right[0])*0.5f;
+ mid[1] = (left[1]+right[1])*0.5f;
+ mid[2] = (left[2]+right[2])*0.5f;
+ return DT_SUCCESS;
+}
+
+dtStatus dtNavMeshQuery::getEdgeMidPoint(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
+ dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
+ float* mid) const
+{
+ float left[3], right[3];
+ if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, to, toPoly, toTile, left, right)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+ mid[0] = (left[0]+right[0])*0.5f;
+ mid[1] = (left[1]+right[1])*0.5f;
+ mid[2] = (left[2]+right[2])*0.5f;
+ return DT_SUCCESS;
+}
+
+
+
+/// @par
+///
+/// This method is meant to be used for quick, short distance checks.
+///
+/// If the path array is too small to hold the result, it will be filled as
+/// far as possible from the start postion toward the end position.
+///
+/// Using the Hit Parameter (t)
+///
+/// If the hit parameter is a very high value (FLT_MAX), then the ray has hit
+/// the end position. In this case the path represents a valid corridor to the
+/// end position and the value of @p hitNormal is undefined.
+///
+/// If the hit parameter is zero, then the start position is on the wall that
+/// was hit and the value of @p hitNormal is undefined.
+///
+/// If 0 < t < 1.0 then the following applies:
+///
+/// @code
+/// distanceToHitBorder = distanceToEndPosition * t
+/// hitPoint = startPos + (endPos - startPos) * t
+/// @endcode
+///
+/// Use Case Restriction
+///
+/// The raycast ignores the y-value of the end position. (2D check.) This
+/// places significant limits on how it can be used. For example:
+///
+/// Consider a scene where there is a main floor with a second floor balcony
+/// that hangs over the main floor. So the first floor mesh extends below the
+/// balcony mesh. The start position is somewhere on the first floor. The end
+/// position is on the balcony.
+///
+/// The raycast will search toward the end position along the first floor mesh.
+/// If it reaches the end position's xz-coordinates it will indicate FLT_MAX
+/// (no wall hit), meaning it reached the end position. This is one example of why
+/// this method is meant for short distance checks.
+///
+dtStatus dtNavMeshQuery::raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
+ const dtQueryFilter* filter,
+ float* t, float* hitNormal, dtPolyRef* path, int* pathCount, const int maxPath) const
+{
+ dtRaycastHit hit;
+ hit.path = path;
+ hit.maxPath = maxPath;
+
+ dtStatus status = raycast(startRef, startPos, endPos, filter, 0, &hit);
+
+ *t = hit.t;
+ if (hitNormal)
+ dtVcopy(hitNormal, hit.hitNormal);
+ if (pathCount)
+ *pathCount = hit.pathCount;
+
+ return status;
+}
+
+
+/// @par
+///
+/// This method is meant to be used for quick, short distance checks.
+///
+/// If the path array is too small to hold the result, it will be filled as
+/// far as possible from the start postion toward the end position.
+///
+/// Using the Hit Parameter t of RaycastHit
+///
+/// If the hit parameter is a very high value (FLT_MAX), then the ray has hit
+/// the end position. In this case the path represents a valid corridor to the
+/// end position and the value of @p hitNormal is undefined.
+///
+/// If the hit parameter is zero, then the start position is on the wall that
+/// was hit and the value of @p hitNormal is undefined.
+///
+/// If 0 < t < 1.0 then the following applies:
+///
+/// @code
+/// distanceToHitBorder = distanceToEndPosition * t
+/// hitPoint = startPos + (endPos - startPos) * t
+/// @endcode
+///
+/// Use Case Restriction
+///
+/// The raycast ignores the y-value of the end position. (2D check.) This
+/// places significant limits on how it can be used. For example:
+///
+/// Consider a scene where there is a main floor with a second floor balcony
+/// that hangs over the main floor. So the first floor mesh extends below the
+/// balcony mesh. The start position is somewhere on the first floor. The end
+/// position is on the balcony.
+///
+/// The raycast will search toward the end position along the first floor mesh.
+/// If it reaches the end position's xz-coordinates it will indicate FLT_MAX
+/// (no wall hit), meaning it reached the end position. This is one example of why
+/// this method is meant for short distance checks.
+///
+dtStatus dtNavMeshQuery::raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
+ const dtQueryFilter* filter, const unsigned int options,
+ dtRaycastHit* hit, dtPolyRef prevRef) const
+{
+ dtAssert(m_nav);
+
+ if (!hit)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ hit->t = 0;
+ hit->pathCount = 0;
+ hit->pathCost = 0;
+
+ // Validate input
+ if (!m_nav->isValidPolyRef(startRef) ||
+ !startPos || !dtVisfinite(startPos) ||
+ !endPos || !dtVisfinite(endPos) ||
+ !filter ||
+ (prevRef && !m_nav->isValidPolyRef(prevRef)))
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ float dir[3], curPos[3], lastPos[3];
+ float verts[DT_VERTS_PER_POLYGON*3+3];
+ int n = 0;
+
+ dtVcopy(curPos, startPos);
+ dtVsub(dir, endPos, startPos);
+ dtVset(hit->hitNormal, 0, 0, 0);
+
+ dtStatus status = DT_SUCCESS;
+
+ const dtMeshTile* prevTile, *tile, *nextTile;
+ const dtPoly* prevPoly, *poly, *nextPoly;
+ dtPolyRef curRef;
+
+ // The API input has been checked already, skip checking internal data.
+ curRef = startRef;
+ tile = 0;
+ poly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(curRef, &tile, &poly);
+ nextTile = prevTile = tile;
+ nextPoly = prevPoly = poly;
+ if (prevRef)
+ m_nav->getTileAndPolyByRefUnsafe(prevRef, &prevTile, &prevPoly);
+
+ while (curRef)
+ {
+ // Cast ray against current polygon.
+
+ // Collect vertices.
+ int nv = 0;
+ for (int i = 0; i < (int)poly->vertCount; ++i)
+ {
+ dtVcopy(&verts[nv*3], &tile->verts[poly->verts[i]*3]);
+ nv++;
+ }
+
+ float tmin, tmax;
+ int segMin, segMax;
+ if (!dtIntersectSegmentPoly2D(startPos, endPos, verts, nv, tmin, tmax, segMin, segMax))
+ {
+ // Could not hit the polygon, keep the old t and report hit.
+ hit->pathCount = n;
+ return status;
+ }
+
+ hit->hitEdgeIndex = segMax;
+
+ // Keep track of furthest t so far.
+ if (tmax > hit->t)
+ hit->t = tmax;
+
+ // Store visited polygons.
+ if (n < hit->maxPath)
+ hit->path[n++] = curRef;
+ else
+ status |= DT_BUFFER_TOO_SMALL;
+
+ // Ray end is completely inside the polygon.
+ if (segMax == -1)
+ {
+ hit->t = FLT_MAX;
+ hit->pathCount = n;
+
+ // add the cost
+ if (options & DT_RAYCAST_USE_COSTS)
+ hit->pathCost += filter->getCost(curPos, endPos, prevRef, prevTile, prevPoly, curRef, tile, poly, curRef, tile, poly);
+ return status;
+ }
+
+ // Follow neighbours.
+ dtPolyRef nextRef = 0;
+
+ for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next)
+ {
+ const dtLink* link = &tile->links[i];
+
+ // Find link which contains this edge.
+ if ((int)link->edge != segMax)
+ continue;
+
+ // Get pointer to the next polygon.
+ nextTile = 0;
+ nextPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(link->ref, &nextTile, &nextPoly);
+
+ // Skip off-mesh connections.
+ if (nextPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ continue;
+
+ // Skip links based on filter.
+ if (!filter->passFilter(link->ref, nextTile, nextPoly))
+ continue;
+
+ // If the link is internal, just return the ref.
+ if (link->side == 0xff)
+ {
+ nextRef = link->ref;
+ break;
+ }
+
+ // If the link is at tile boundary,
+
+ // Check if the link spans the whole edge, and accept.
+ if (link->bmin == 0 && link->bmax == 255)
+ {
+ nextRef = link->ref;
+ break;
+ }
+
+ // Check for partial edge links.
+ const int v0 = poly->verts[link->edge];
+ const int v1 = poly->verts[(link->edge+1) % poly->vertCount];
+ const float* left = &tile->verts[v0*3];
+ const float* right = &tile->verts[v1*3];
+
+ // Check that the intersection lies inside the link portal.
+ if (link->side == 0 || link->side == 4)
+ {
+ // Calculate link size.
+ const float s = 1.0f/255.0f;
+ float lmin = left[2] + (right[2] - left[2])*(link->bmin*s);
+ float lmax = left[2] + (right[2] - left[2])*(link->bmax*s);
+ if (lmin > lmax) dtSwap(lmin, lmax);
+
+ // Find Z intersection.
+ float z = startPos[2] + (endPos[2]-startPos[2])*tmax;
+ if (z >= lmin && z <= lmax)
+ {
+ nextRef = link->ref;
+ break;
+ }
+ }
+ else if (link->side == 2 || link->side == 6)
+ {
+ // Calculate link size.
+ const float s = 1.0f/255.0f;
+ float lmin = left[0] + (right[0] - left[0])*(link->bmin*s);
+ float lmax = left[0] + (right[0] - left[0])*(link->bmax*s);
+ if (lmin > lmax) dtSwap(lmin, lmax);
+
+ // Find X intersection.
+ float x = startPos[0] + (endPos[0]-startPos[0])*tmax;
+ if (x >= lmin && x <= lmax)
+ {
+ nextRef = link->ref;
+ break;
+ }
+ }
+ }
+
+ // add the cost
+ if (options & DT_RAYCAST_USE_COSTS)
+ {
+ // compute the intersection point at the furthest end of the polygon
+ // and correct the height (since the raycast moves in 2d)
+ dtVcopy(lastPos, curPos);
+ dtVmad(curPos, startPos, dir, hit->t);
+ float* e1 = &verts[segMax*3];
+ float* e2 = &verts[((segMax+1)%nv)*3];
+ float eDir[3], diff[3];
+ dtVsub(eDir, e2, e1);
+ dtVsub(diff, curPos, e1);
+ float s = dtSqr(eDir[0]) > dtSqr(eDir[2]) ? diff[0] / eDir[0] : diff[2] / eDir[2];
+ curPos[1] = e1[1] + eDir[1] * s;
+
+ hit->pathCost += filter->getCost(lastPos, curPos, prevRef, prevTile, prevPoly, curRef, tile, poly, nextRef, nextTile, nextPoly);
+ }
+
+ if (!nextRef)
+ {
+ // No neighbour, we hit a wall.
+
+ // Calculate hit normal.
+ const int a = segMax;
+ const int b = segMax+1 < nv ? segMax+1 : 0;
+ const float* va = &verts[a*3];
+ const float* vb = &verts[b*3];
+ const float dx = vb[0] - va[0];
+ const float dz = vb[2] - va[2];
+ hit->hitNormal[0] = dz;
+ hit->hitNormal[1] = 0;
+ hit->hitNormal[2] = -dx;
+ dtVnormalize(hit->hitNormal);
+
+ hit->pathCount = n;
+ return status;
+ }
+
+ // No hit, advance to neighbour polygon.
+ prevRef = curRef;
+ curRef = nextRef;
+ prevTile = tile;
+ tile = nextTile;
+ prevPoly = poly;
+ poly = nextPoly;
+
+ if (status & DT_BUFFER_TOO_SMALL)
+ {
+ status |= DT_PARTIAL_RESULT;
+ break;
+ }
+ }
+
+ hit->pathCount = n;
+
+ return status;
+}
+
+/// @par
+///
+/// At least one result array must be provided.
+///
+/// The order of the result set is from least to highest cost to reach the polygon.
+///
+/// A common use case for this method is to perform Dijkstra searches.
+/// Candidate polygons are found by searching the graph beginning at the start polygon.
+///
+/// If a polygon is not found via the graph search, even if it intersects the
+/// search circle, it will not be included in the result set. For example:
+///
+/// polyA is the start polygon.
+/// polyB shares an edge with polyA. (Is adjacent.)
+/// polyC shares an edge with polyB, but not with polyA
+/// Even if the search circle overlaps polyC, it will not be included in the
+/// result set unless polyB is also in the set.
+///
+/// The value of the center point is used as the start position for cost
+/// calculations. It is not projected onto the surface of the mesh, so its
+/// y-value will effect the costs.
+///
+/// Intersection tests occur in 2D. All polygons and the search circle are
+/// projected onto the xz-plane. So the y-value of the center point does not
+/// effect intersection tests.
+///
+/// If the result arrays are to small to hold the entire result set, they will be
+/// filled to capacity.
+///
+dtStatus dtNavMeshQuery::findPolysAroundCircle(dtPolyRef startRef, const float* centerPos, const float radius,
+ const dtQueryFilter* filter,
+ dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
+ int* resultCount, const int maxResult) const
+{
+ dtAssert(m_nav);
+ dtAssert(m_nodePool);
+ dtAssert(m_openList);
+
+ if (!resultCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *resultCount = 0;
+
+ if (!m_nav->isValidPolyRef(startRef) ||
+ !centerPos || !dtVisfinite(centerPos) ||
+ radius < 0 || !dtMathIsfinite(radius) ||
+ !filter || maxResult < 0)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ m_nodePool->clear();
+ m_openList->clear();
+
+ dtNode* startNode = m_nodePool->getNode(startRef);
+ dtVcopy(startNode->pos, centerPos);
+ startNode->pidx = 0;
+ startNode->cost = 0;
+ startNode->total = 0;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_OPEN;
+ m_openList->push(startNode);
+
+ dtStatus status = DT_SUCCESS;
+
+ int n = 0;
+
+ const float radiusSqr = dtSqr(radius);
+
+ while (!m_openList->empty())
+ {
+ dtNode* bestNode = m_openList->pop();
+ bestNode->flags &= ~DT_NODE_OPEN;
+ bestNode->flags |= DT_NODE_CLOSED;
+
+ // Get poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef bestRef = bestNode->id;
+ const dtMeshTile* bestTile = 0;
+ const dtPoly* bestPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
+
+ // Get parent poly and tile.
+ dtPolyRef parentRef = 0;
+ const dtMeshTile* parentTile = 0;
+ const dtPoly* parentPoly = 0;
+ if (bestNode->pidx)
+ parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
+ if (parentRef)
+ m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
+
+ if (n < maxResult)
+ {
+ if (resultRef)
+ resultRef[n] = bestRef;
+ if (resultParent)
+ resultParent[n] = parentRef;
+ if (resultCost)
+ resultCost[n] = bestNode->total;
+ ++n;
+ }
+ else
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ }
+
+ for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
+ {
+ const dtLink* link = &bestTile->links[i];
+ dtPolyRef neighbourRef = link->ref;
+ // Skip invalid neighbours and do not follow back to parent.
+ if (!neighbourRef || neighbourRef == parentRef)
+ continue;
+
+ // Expand to neighbour
+ const dtMeshTile* neighbourTile = 0;
+ const dtPoly* neighbourPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
+
+ // Do not advance if the polygon is excluded by the filter.
+ if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
+ continue;
+
+ // Find edge and calc distance to the edge.
+ float va[3], vb[3];
+ if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
+ continue;
+
+ // If the circle is not touching the next polygon, skip it.
+ float tseg;
+ float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
+ if (distSqr > radiusSqr)
+ continue;
+
+ dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
+ if (!neighbourNode)
+ {
+ status |= DT_OUT_OF_NODES;
+ continue;
+ }
+
+ if (neighbourNode->flags & DT_NODE_CLOSED)
+ continue;
+
+ // Cost
+ if (neighbourNode->flags == 0)
+ dtVlerp(neighbourNode->pos, va, vb, 0.5f);
+
+ float cost = filter->getCost(
+ bestNode->pos, neighbourNode->pos,
+ parentRef, parentTile, parentPoly,
+ bestRef, bestTile, bestPoly,
+ neighbourRef, neighbourTile, neighbourPoly);
+
+ const float total = bestNode->total + cost;
+
+ // The node is already in open list and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
+ continue;
+
+ neighbourNode->id = neighbourRef;
+ neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
+ neighbourNode->total = total;
+
+ if (neighbourNode->flags & DT_NODE_OPEN)
+ {
+ m_openList->modify(neighbourNode);
+ }
+ else
+ {
+ neighbourNode->flags = DT_NODE_OPEN;
+ m_openList->push(neighbourNode);
+ }
+ }
+ }
+
+ *resultCount = n;
+
+ return status;
+}
+
+/// @par
+///
+/// The order of the result set is from least to highest cost.
+///
+/// At least one result array must be provided.
+///
+/// A common use case for this method is to perform Dijkstra searches.
+/// Candidate polygons are found by searching the graph beginning at the start
+/// polygon.
+///
+/// The same intersection test restrictions that apply to findPolysAroundCircle()
+/// method apply to this method.
+///
+/// The 3D centroid of the search polygon is used as the start position for cost
+/// calculations.
+///
+/// Intersection tests occur in 2D. All polygons are projected onto the
+/// xz-plane. So the y-values of the vertices do not effect intersection tests.
+///
+/// If the result arrays are is too small to hold the entire result set, they will
+/// be filled to capacity.
+///
+dtStatus dtNavMeshQuery::findPolysAroundShape(dtPolyRef startRef, const float* verts, const int nverts,
+ const dtQueryFilter* filter,
+ dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
+ int* resultCount, const int maxResult) const
+{
+ dtAssert(m_nav);
+ dtAssert(m_nodePool);
+ dtAssert(m_openList);
+
+ if (!resultCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *resultCount = 0;
+
+ if (!m_nav->isValidPolyRef(startRef) ||
+ !verts || nverts < 3 ||
+ !filter || maxResult < 0)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ // Validate input
+ if (!startRef || !m_nav->isValidPolyRef(startRef))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ m_nodePool->clear();
+ m_openList->clear();
+
+ float centerPos[3] = {0,0,0};
+ for (int i = 0; i < nverts; ++i)
+ dtVadd(centerPos,centerPos,&verts[i*3]);
+ dtVscale(centerPos,centerPos,1.0f/nverts);
+
+ dtNode* startNode = m_nodePool->getNode(startRef);
+ dtVcopy(startNode->pos, centerPos);
+ startNode->pidx = 0;
+ startNode->cost = 0;
+ startNode->total = 0;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_OPEN;
+ m_openList->push(startNode);
+
+ dtStatus status = DT_SUCCESS;
+
+ int n = 0;
+
+ while (!m_openList->empty())
+ {
+ dtNode* bestNode = m_openList->pop();
+ bestNode->flags &= ~DT_NODE_OPEN;
+ bestNode->flags |= DT_NODE_CLOSED;
+
+ // Get poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef bestRef = bestNode->id;
+ const dtMeshTile* bestTile = 0;
+ const dtPoly* bestPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
+
+ // Get parent poly and tile.
+ dtPolyRef parentRef = 0;
+ const dtMeshTile* parentTile = 0;
+ const dtPoly* parentPoly = 0;
+ if (bestNode->pidx)
+ parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
+ if (parentRef)
+ m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
+
+ if (n < maxResult)
+ {
+ if (resultRef)
+ resultRef[n] = bestRef;
+ if (resultParent)
+ resultParent[n] = parentRef;
+ if (resultCost)
+ resultCost[n] = bestNode->total;
+
+ ++n;
+ }
+ else
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ }
+
+ for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
+ {
+ const dtLink* link = &bestTile->links[i];
+ dtPolyRef neighbourRef = link->ref;
+ // Skip invalid neighbours and do not follow back to parent.
+ if (!neighbourRef || neighbourRef == parentRef)
+ continue;
+
+ // Expand to neighbour
+ const dtMeshTile* neighbourTile = 0;
+ const dtPoly* neighbourPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
+
+ // Do not advance if the polygon is excluded by the filter.
+ if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
+ continue;
+
+ // Find edge and calc distance to the edge.
+ float va[3], vb[3];
+ if (!getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
+ continue;
+
+ // If the poly is not touching the edge to the next polygon, skip the connection it.
+ float tmin, tmax;
+ int segMin, segMax;
+ if (!dtIntersectSegmentPoly2D(va, vb, verts, nverts, tmin, tmax, segMin, segMax))
+ continue;
+ if (tmin > 1.0f || tmax < 0.0f)
+ continue;
+
+ dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
+ if (!neighbourNode)
+ {
+ status |= DT_OUT_OF_NODES;
+ continue;
+ }
+
+ if (neighbourNode->flags & DT_NODE_CLOSED)
+ continue;
+
+ // Cost
+ if (neighbourNode->flags == 0)
+ dtVlerp(neighbourNode->pos, va, vb, 0.5f);
+
+ float cost = filter->getCost(
+ bestNode->pos, neighbourNode->pos,
+ parentRef, parentTile, parentPoly,
+ bestRef, bestTile, bestPoly,
+ neighbourRef, neighbourTile, neighbourPoly);
+
+ const float total = bestNode->total + cost;
+
+ // The node is already in open list and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
+ continue;
+
+ neighbourNode->id = neighbourRef;
+ neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
+ neighbourNode->total = total;
+
+ if (neighbourNode->flags & DT_NODE_OPEN)
+ {
+ m_openList->modify(neighbourNode);
+ }
+ else
+ {
+ neighbourNode->flags = DT_NODE_OPEN;
+ m_openList->push(neighbourNode);
+ }
+ }
+ }
+
+ *resultCount = n;
+
+ return status;
+}
+
+dtStatus dtNavMeshQuery::getPathFromDijkstraSearch(dtPolyRef endRef, dtPolyRef* path, int* pathCount, int maxPath) const
+{
+ if (!m_nav->isValidPolyRef(endRef) || !path || !pathCount || maxPath < 0)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *pathCount = 0;
+
+ dtNode* endNode;
+ if (m_nodePool->findNodes(endRef, &endNode, 1) != 1 ||
+ (endNode->flags & DT_NODE_CLOSED) == 0)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ return getPathToNode(endNode, path, pathCount, maxPath);
+}
+
+/// @par
+///
+/// This method is optimized for a small search radius and small number of result
+/// polygons.
+///
+/// Candidate polygons are found by searching the navigation graph beginning at
+/// the start polygon.
+///
+/// The same intersection test restrictions that apply to the findPolysAroundCircle
+/// mehtod applies to this method.
+///
+/// The value of the center point is used as the start point for cost calculations.
+/// It is not projected onto the surface of the mesh, so its y-value will effect
+/// the costs.
+///
+/// Intersection tests occur in 2D. All polygons and the search circle are
+/// projected onto the xz-plane. So the y-value of the center point does not
+/// effect intersection tests.
+///
+/// If the result arrays are is too small to hold the entire result set, they will
+/// be filled to capacity.
+///
+dtStatus dtNavMeshQuery::findLocalNeighbourhood(dtPolyRef startRef, const float* centerPos, const float radius,
+ const dtQueryFilter* filter,
+ dtPolyRef* resultRef, dtPolyRef* resultParent,
+ int* resultCount, const int maxResult) const
+{
+ dtAssert(m_nav);
+ dtAssert(m_tinyNodePool);
+
+ if (!resultCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *resultCount = 0;
+
+ if (!m_nav->isValidPolyRef(startRef) ||
+ !centerPos || !dtVisfinite(centerPos) ||
+ radius < 0 || !dtMathIsfinite(radius) ||
+ !filter || maxResult < 0)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ static const int MAX_STACK = 48;
+ dtNode* stack[MAX_STACK];
+ int nstack = 0;
+
+ m_tinyNodePool->clear();
+
+ dtNode* startNode = m_tinyNodePool->getNode(startRef);
+ startNode->pidx = 0;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_CLOSED;
+ stack[nstack++] = startNode;
+
+ const float radiusSqr = dtSqr(radius);
+
+ float pa[DT_VERTS_PER_POLYGON*3];
+ float pb[DT_VERTS_PER_POLYGON*3];
+
+ dtStatus status = DT_SUCCESS;
+
+ int n = 0;
+ if (n < maxResult)
+ {
+ resultRef[n] = startNode->id;
+ if (resultParent)
+ resultParent[n] = 0;
+ ++n;
+ }
+ else
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ }
+
+ while (nstack)
+ {
+ // Pop front.
+ dtNode* curNode = stack[0];
+ for (int i = 0; i < nstack-1; ++i)
+ stack[i] = stack[i+1];
+ nstack--;
+
+ // Get poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef curRef = curNode->id;
+ const dtMeshTile* curTile = 0;
+ const dtPoly* curPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(curRef, &curTile, &curPoly);
+
+ for (unsigned int i = curPoly->firstLink; i != DT_NULL_LINK; i = curTile->links[i].next)
+ {
+ const dtLink* link = &curTile->links[i];
+ dtPolyRef neighbourRef = link->ref;
+ // Skip invalid neighbours.
+ if (!neighbourRef)
+ continue;
+
+ // Skip if cannot alloca more nodes.
+ dtNode* neighbourNode = m_tinyNodePool->getNode(neighbourRef);
+ if (!neighbourNode)
+ continue;
+ // Skip visited.
+ if (neighbourNode->flags & DT_NODE_CLOSED)
+ continue;
+
+ // Expand to neighbour
+ const dtMeshTile* neighbourTile = 0;
+ const dtPoly* neighbourPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
+
+ // Skip off-mesh connections.
+ if (neighbourPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ continue;
+
+ // Do not advance if the polygon is excluded by the filter.
+ if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
+ continue;
+
+ // Find edge and calc distance to the edge.
+ float va[3], vb[3];
+ if (!getPortalPoints(curRef, curPoly, curTile, neighbourRef, neighbourPoly, neighbourTile, va, vb))
+ continue;
+
+ // If the circle is not touching the next polygon, skip it.
+ float tseg;
+ float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
+ if (distSqr > radiusSqr)
+ continue;
+
+ // Mark node visited, this is done before the overlap test so that
+ // we will not visit the poly again if the test fails.
+ neighbourNode->flags |= DT_NODE_CLOSED;
+ neighbourNode->pidx = m_tinyNodePool->getNodeIdx(curNode);
+
+ // Check that the polygon does not collide with existing polygons.
+
+ // Collect vertices of the neighbour poly.
+ const int npa = neighbourPoly->vertCount;
+ for (int k = 0; k < npa; ++k)
+ dtVcopy(&pa[k*3], &neighbourTile->verts[neighbourPoly->verts[k]*3]);
+
+ bool overlap = false;
+ for (int j = 0; j < n; ++j)
+ {
+ dtPolyRef pastRef = resultRef[j];
+
+ // Connected polys do not overlap.
+ bool connected = false;
+ for (unsigned int k = curPoly->firstLink; k != DT_NULL_LINK; k = curTile->links[k].next)
+ {
+ if (curTile->links[k].ref == pastRef)
+ {
+ connected = true;
+ break;
+ }
+ }
+ if (connected)
+ continue;
+
+ // Potentially overlapping.
+ const dtMeshTile* pastTile = 0;
+ const dtPoly* pastPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(pastRef, &pastTile, &pastPoly);
+
+ // Get vertices and test overlap
+ const int npb = pastPoly->vertCount;
+ for (int k = 0; k < npb; ++k)
+ dtVcopy(&pb[k*3], &pastTile->verts[pastPoly->verts[k]*3]);
+
+ if (dtOverlapPolyPoly2D(pa,npa, pb,npb))
+ {
+ overlap = true;
+ break;
+ }
+ }
+ if (overlap)
+ continue;
+
+ // This poly is fine, store and advance to the poly.
+ if (n < maxResult)
+ {
+ resultRef[n] = neighbourRef;
+ if (resultParent)
+ resultParent[n] = curRef;
+ ++n;
+ }
+ else
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ }
+
+ if (nstack < MAX_STACK)
+ {
+ stack[nstack++] = neighbourNode;
+ }
+ }
+ }
+
+ *resultCount = n;
+
+ return status;
+}
+
+
+struct dtSegInterval
+{
+ dtPolyRef ref;
+ short tmin, tmax;
+};
+
+static void insertInterval(dtSegInterval* ints, int& nints, const int maxInts,
+ const short tmin, const short tmax, const dtPolyRef ref)
+{
+ if (nints+1 > maxInts) return;
+ // Find insertion point.
+ int idx = 0;
+ while (idx < nints)
+ {
+ if (tmax <= ints[idx].tmin)
+ break;
+ idx++;
+ }
+ // Move current results.
+ if (nints-idx)
+ memmove(ints+idx+1, ints+idx, sizeof(dtSegInterval)*(nints-idx));
+ // Store
+ ints[idx].ref = ref;
+ ints[idx].tmin = tmin;
+ ints[idx].tmax = tmax;
+ nints++;
+}
+
+/// @par
+///
+/// If the @p segmentRefs parameter is provided, then all polygon segments will be returned.
+/// Otherwise only the wall segments are returned.
+///
+/// A segment that is normally a portal will be included in the result set as a
+/// wall if the @p filter results in the neighbor polygon becoomming impassable.
+///
+/// The @p segmentVerts and @p segmentRefs buffers should normally be sized for the
+/// maximum segments per polygon of the source navigation mesh.
+///
+dtStatus dtNavMeshQuery::getPolyWallSegments(dtPolyRef ref, const dtQueryFilter* filter,
+ float* segmentVerts, dtPolyRef* segmentRefs, int* segmentCount,
+ const int maxSegments) const
+{
+ dtAssert(m_nav);
+
+ if (!segmentCount)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ *segmentCount = 0;
+
+ const dtMeshTile* tile = 0;
+ const dtPoly* poly = 0;
+ if (dtStatusFailed(m_nav->getTileAndPolyByRef(ref, &tile, &poly)))
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ if (!filter || !segmentVerts || maxSegments < 0)
+ return DT_FAILURE | DT_INVALID_PARAM;
+
+ int n = 0;
+ static const int MAX_INTERVAL = 16;
+ dtSegInterval ints[MAX_INTERVAL];
+ int nints;
+
+ const bool storePortals = segmentRefs != 0;
+
+ dtStatus status = DT_SUCCESS;
+
+ for (int i = 0, j = (int)poly->vertCount-1; i < (int)poly->vertCount; j = i++)
+ {
+ // Skip non-solid edges.
+ nints = 0;
+ if (poly->neis[j] & DT_EXT_LINK)
+ {
+ // Tile border.
+ for (unsigned int k = poly->firstLink; k != DT_NULL_LINK; k = tile->links[k].next)
+ {
+ const dtLink* link = &tile->links[k];
+ if (link->edge == j)
+ {
+ if (link->ref != 0)
+ {
+ const dtMeshTile* neiTile = 0;
+ const dtPoly* neiPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly);
+ if (filter->passFilter(link->ref, neiTile, neiPoly))
+ {
+ insertInterval(ints, nints, MAX_INTERVAL, link->bmin, link->bmax, link->ref);
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ // Internal edge
+ dtPolyRef neiRef = 0;
+ if (poly->neis[j])
+ {
+ const unsigned int idx = (unsigned int)(poly->neis[j]-1);
+ neiRef = m_nav->getPolyRefBase(tile) | idx;
+ if (!filter->passFilter(neiRef, tile, &tile->polys[idx]))
+ neiRef = 0;
+ }
+
+ // If the edge leads to another polygon and portals are not stored, skip.
+ if (neiRef != 0 && !storePortals)
+ continue;
+
+ if (n < maxSegments)
+ {
+ const float* vj = &tile->verts[poly->verts[j]*3];
+ const float* vi = &tile->verts[poly->verts[i]*3];
+ float* seg = &segmentVerts[n*6];
+ dtVcopy(seg+0, vj);
+ dtVcopy(seg+3, vi);
+ if (segmentRefs)
+ segmentRefs[n] = neiRef;
+ n++;
+ }
+ else
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ }
+
+ continue;
+ }
+
+ // Add sentinels
+ insertInterval(ints, nints, MAX_INTERVAL, -1, 0, 0);
+ insertInterval(ints, nints, MAX_INTERVAL, 255, 256, 0);
+
+ // Store segments.
+ const float* vj = &tile->verts[poly->verts[j]*3];
+ const float* vi = &tile->verts[poly->verts[i]*3];
+ for (int k = 1; k < nints; ++k)
+ {
+ // Portal segment.
+ if (storePortals && ints[k].ref)
+ {
+ const float tmin = ints[k].tmin/255.0f;
+ const float tmax = ints[k].tmax/255.0f;
+ if (n < maxSegments)
+ {
+ float* seg = &segmentVerts[n*6];
+ dtVlerp(seg+0, vj,vi, tmin);
+ dtVlerp(seg+3, vj,vi, tmax);
+ if (segmentRefs)
+ segmentRefs[n] = ints[k].ref;
+ n++;
+ }
+ else
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ }
+ }
+
+ // Wall segment.
+ const int imin = ints[k-1].tmax;
+ const int imax = ints[k].tmin;
+ if (imin != imax)
+ {
+ const float tmin = imin/255.0f;
+ const float tmax = imax/255.0f;
+ if (n < maxSegments)
+ {
+ float* seg = &segmentVerts[n*6];
+ dtVlerp(seg+0, vj,vi, tmin);
+ dtVlerp(seg+3, vj,vi, tmax);
+ if (segmentRefs)
+ segmentRefs[n] = 0;
+ n++;
+ }
+ else
+ {
+ status |= DT_BUFFER_TOO_SMALL;
+ }
+ }
+ }
+ }
+
+ *segmentCount = n;
+
+ return status;
+}
+
+/// @par
+///
+/// @p hitPos is not adjusted using the height detail data.
+///
+/// @p hitDist will equal the search radius if there is no wall within the
+/// radius. In this case the values of @p hitPos and @p hitNormal are
+/// undefined.
+///
+/// The normal will become unpredicable if @p hitDist is a very small number.
+///
+dtStatus dtNavMeshQuery::findDistanceToWall(dtPolyRef startRef, const float* centerPos, const float maxRadius,
+ const dtQueryFilter* filter,
+ float* hitDist, float* hitPos, float* hitNormal) const
+{
+ dtAssert(m_nav);
+ dtAssert(m_nodePool);
+ dtAssert(m_openList);
+
+ // Validate input
+ if (!m_nav->isValidPolyRef(startRef) ||
+ !centerPos || !dtVisfinite(centerPos) ||
+ maxRadius < 0 || !dtMathIsfinite(maxRadius) ||
+ !filter || !hitDist || !hitPos || !hitNormal)
+ {
+ return DT_FAILURE | DT_INVALID_PARAM;
+ }
+
+ m_nodePool->clear();
+ m_openList->clear();
+
+ dtNode* startNode = m_nodePool->getNode(startRef);
+ dtVcopy(startNode->pos, centerPos);
+ startNode->pidx = 0;
+ startNode->cost = 0;
+ startNode->total = 0;
+ startNode->id = startRef;
+ startNode->flags = DT_NODE_OPEN;
+ m_openList->push(startNode);
+
+ float radiusSqr = dtSqr(maxRadius);
+
+ dtStatus status = DT_SUCCESS;
+
+ while (!m_openList->empty())
+ {
+ dtNode* bestNode = m_openList->pop();
+ bestNode->flags &= ~DT_NODE_OPEN;
+ bestNode->flags |= DT_NODE_CLOSED;
+
+ // Get poly and tile.
+ // The API input has been checked already, skip checking internal data.
+ const dtPolyRef bestRef = bestNode->id;
+ const dtMeshTile* bestTile = 0;
+ const dtPoly* bestPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(bestRef, &bestTile, &bestPoly);
+
+ // Get parent poly and tile.
+ dtPolyRef parentRef = 0;
+ const dtMeshTile* parentTile = 0;
+ const dtPoly* parentPoly = 0;
+ if (bestNode->pidx)
+ parentRef = m_nodePool->getNodeAtIdx(bestNode->pidx)->id;
+ if (parentRef)
+ m_nav->getTileAndPolyByRefUnsafe(parentRef, &parentTile, &parentPoly);
+
+ // Hit test walls.
+ for (int i = 0, j = (int)bestPoly->vertCount-1; i < (int)bestPoly->vertCount; j = i++)
+ {
+ // Skip non-solid edges.
+ if (bestPoly->neis[j] & DT_EXT_LINK)
+ {
+ // Tile border.
+ bool solid = true;
+ for (unsigned int k = bestPoly->firstLink; k != DT_NULL_LINK; k = bestTile->links[k].next)
+ {
+ const dtLink* link = &bestTile->links[k];
+ if (link->edge == j)
+ {
+ if (link->ref != 0)
+ {
+ const dtMeshTile* neiTile = 0;
+ const dtPoly* neiPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(link->ref, &neiTile, &neiPoly);
+ if (filter->passFilter(link->ref, neiTile, neiPoly))
+ solid = false;
+ }
+ break;
+ }
+ }
+ if (!solid) continue;
+ }
+ else if (bestPoly->neis[j])
+ {
+ // Internal edge
+ const unsigned int idx = (unsigned int)(bestPoly->neis[j]-1);
+ const dtPolyRef ref = m_nav->getPolyRefBase(bestTile) | idx;
+ if (filter->passFilter(ref, bestTile, &bestTile->polys[idx]))
+ continue;
+ }
+
+ // Calc distance to the edge.
+ const float* vj = &bestTile->verts[bestPoly->verts[j]*3];
+ const float* vi = &bestTile->verts[bestPoly->verts[i]*3];
+ float tseg;
+ float distSqr = dtDistancePtSegSqr2D(centerPos, vj, vi, tseg);
+
+ // Edge is too far, skip.
+ if (distSqr > radiusSqr)
+ continue;
+
+ // Hit wall, update radius.
+ radiusSqr = distSqr;
+ // Calculate hit pos.
+ hitPos[0] = vj[0] + (vi[0] - vj[0])*tseg;
+ hitPos[1] = vj[1] + (vi[1] - vj[1])*tseg;
+ hitPos[2] = vj[2] + (vi[2] - vj[2])*tseg;
+ }
+
+ for (unsigned int i = bestPoly->firstLink; i != DT_NULL_LINK; i = bestTile->links[i].next)
+ {
+ const dtLink* link = &bestTile->links[i];
+ dtPolyRef neighbourRef = link->ref;
+ // Skip invalid neighbours and do not follow back to parent.
+ if (!neighbourRef || neighbourRef == parentRef)
+ continue;
+
+ // Expand to neighbour.
+ const dtMeshTile* neighbourTile = 0;
+ const dtPoly* neighbourPoly = 0;
+ m_nav->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile, &neighbourPoly);
+
+ // Skip off-mesh connections.
+ if (neighbourPoly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
+ continue;
+
+ // Calc distance to the edge.
+ const float* va = &bestTile->verts[bestPoly->verts[link->edge]*3];
+ const float* vb = &bestTile->verts[bestPoly->verts[(link->edge+1) % bestPoly->vertCount]*3];
+ float tseg;
+ float distSqr = dtDistancePtSegSqr2D(centerPos, va, vb, tseg);
+
+ // If the circle is not touching the next polygon, skip it.
+ if (distSqr > radiusSqr)
+ continue;
+
+ if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
+ continue;
+
+ dtNode* neighbourNode = m_nodePool->getNode(neighbourRef);
+ if (!neighbourNode)
+ {
+ status |= DT_OUT_OF_NODES;
+ continue;
+ }
+
+ if (neighbourNode->flags & DT_NODE_CLOSED)
+ continue;
+
+ // Cost
+ if (neighbourNode->flags == 0)
+ {
+ getEdgeMidPoint(bestRef, bestPoly, bestTile,
+ neighbourRef, neighbourPoly, neighbourTile, neighbourNode->pos);
+ }
+
+ const float total = bestNode->total + dtVdist(bestNode->pos, neighbourNode->pos);
+
+ // The node is already in open list and the new result is worse, skip.
+ if ((neighbourNode->flags & DT_NODE_OPEN) && total >= neighbourNode->total)
+ continue;
+
+ neighbourNode->id = neighbourRef;
+ neighbourNode->flags = (neighbourNode->flags & ~DT_NODE_CLOSED);
+ neighbourNode->pidx = m_nodePool->getNodeIdx(bestNode);
+ neighbourNode->total = total;
+
+ if (neighbourNode->flags & DT_NODE_OPEN)
+ {
+ m_openList->modify(neighbourNode);
+ }
+ else
+ {
+ neighbourNode->flags |= DT_NODE_OPEN;
+ m_openList->push(neighbourNode);
+ }
+ }
+ }
+
+ // Calc hit normal.
+ dtVsub(hitNormal, centerPos, hitPos);
+ dtVnormalize(hitNormal);
+
+ *hitDist = dtMathSqrtf(radiusSqr);
+
+ return status;
+}
+
+bool dtNavMeshQuery::isValidPolyRef(dtPolyRef ref, const dtQueryFilter* filter) const
+{
+ const dtMeshTile* tile = 0;
+ const dtPoly* poly = 0;
+ dtStatus status = m_nav->getTileAndPolyByRef(ref, &tile, &poly);
+ // If cannot get polygon, assume it does not exists and boundary is invalid.
+ if (dtStatusFailed(status))
+ return false;
+ // If cannot pass filter, assume flags has changed and boundary is invalid.
+ if (!filter->passFilter(ref, tile, poly))
+ return false;
+ return true;
+}
+
+/// @par
+///
+/// The closed list is the list of polygons that were fully evaluated during
+/// the last navigation graph search. (A* or Dijkstra)
+///
+bool dtNavMeshQuery::isInClosedList(dtPolyRef ref) const
+{
+ if (!m_nodePool) return false;
+
+ dtNode* nodes[DT_MAX_STATES_PER_NODE];
+ int n= m_nodePool->findNodes(ref, nodes, DT_MAX_STATES_PER_NODE);
+
+ for (int i=0; iflags & DT_NODE_CLOSED)
+ return true;
+ }
+
+ return false;
+}
diff --git a/native/third_party/recastnavigation/Detour/Source/DetourNode.cpp b/native/third_party/recastnavigation/Detour/Source/DetourNode.cpp
new file mode 100644
index 0000000..48abbba
--- /dev/null
+++ b/native/third_party/recastnavigation/Detour/Source/DetourNode.cpp
@@ -0,0 +1,200 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+
+#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);
+}
diff --git a/native/third_party/recastnavigation/License.txt b/native/third_party/recastnavigation/License.txt
new file mode 100644
index 0000000..95f4bfc
--- /dev/null
+++ b/native/third_party/recastnavigation/License.txt
@@ -0,0 +1,18 @@
+Copyright (c) 2009 Mikko Mononen memon@inside.org
+
+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.
+
diff --git a/native/third_party/recastnavigation/Recast/Include/Recast.h b/native/third_party/recastnavigation/Recast/Include/Recast.h
new file mode 100644
index 0000000..30e710e
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Include/Recast.h
@@ -0,0 +1,1371 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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 RECAST_H
+#define RECAST_H
+
+/// The value of PI used by Recast.
+static const float RC_PI = 3.14159265f;
+
+/// Used to ignore unused function parameters and silence any compiler warnings.
+template void rcIgnoreUnused(const T&) { }
+
+/// Recast log categories.
+/// @see rcContext
+enum rcLogCategory
+{
+ RC_LOG_PROGRESS = 1, ///< A progress log entry.
+ RC_LOG_WARNING, ///< A warning log entry.
+ RC_LOG_ERROR ///< An error log entry.
+};
+
+/// Recast performance timer categories.
+/// @see rcContext
+enum rcTimerLabel
+{
+ /// The user defined total time of the build.
+ RC_TIMER_TOTAL,
+ /// A user defined build time.
+ RC_TIMER_TEMP,
+ /// The time to rasterize the triangles. (See: #rcRasterizeTriangle)
+ RC_TIMER_RASTERIZE_TRIANGLES,
+ /// The time to build the compact heightfield. (See: #rcBuildCompactHeightfield)
+ RC_TIMER_BUILD_COMPACTHEIGHTFIELD,
+ /// The total time to build the contours. (See: #rcBuildContours)
+ RC_TIMER_BUILD_CONTOURS,
+ /// The time to trace the boundaries of the contours. (See: #rcBuildContours)
+ RC_TIMER_BUILD_CONTOURS_TRACE,
+ /// The time to simplify the contours. (See: #rcBuildContours)
+ RC_TIMER_BUILD_CONTOURS_SIMPLIFY,
+ /// The time to filter ledge spans. (See: #rcFilterLedgeSpans)
+ RC_TIMER_FILTER_BORDER,
+ /// The time to filter low height spans. (See: #rcFilterWalkableLowHeightSpans)
+ RC_TIMER_FILTER_WALKABLE,
+ /// The time to apply the median filter. (See: #rcMedianFilterWalkableArea)
+ RC_TIMER_MEDIAN_AREA,
+ /// The time to filter low obstacles. (See: #rcFilterLowHangingWalkableObstacles)
+ RC_TIMER_FILTER_LOW_OBSTACLES,
+ /// The time to build the polygon mesh. (See: #rcBuildPolyMesh)
+ RC_TIMER_BUILD_POLYMESH,
+ /// The time to merge polygon meshes. (See: #rcMergePolyMeshes)
+ RC_TIMER_MERGE_POLYMESH,
+ /// The time to erode the walkable area. (See: #rcErodeWalkableArea)
+ RC_TIMER_ERODE_AREA,
+ /// The time to mark a box area. (See: #rcMarkBoxArea)
+ RC_TIMER_MARK_BOX_AREA,
+ /// The time to mark a cylinder area. (See: #rcMarkCylinderArea)
+ RC_TIMER_MARK_CYLINDER_AREA,
+ /// The time to mark a convex polygon area. (See: #rcMarkConvexPolyArea)
+ RC_TIMER_MARK_CONVEXPOLY_AREA,
+ /// The total time to build the distance field. (See: #rcBuildDistanceField)
+ RC_TIMER_BUILD_DISTANCEFIELD,
+ /// The time to build the distances of the distance field. (See: #rcBuildDistanceField)
+ RC_TIMER_BUILD_DISTANCEFIELD_DIST,
+ /// The time to blur the distance field. (See: #rcBuildDistanceField)
+ RC_TIMER_BUILD_DISTANCEFIELD_BLUR,
+ /// The total time to build the regions. (See: #rcBuildRegions, #rcBuildRegionsMonotone)
+ RC_TIMER_BUILD_REGIONS,
+ /// The total time to apply the watershed algorithm. (See: #rcBuildRegions)
+ RC_TIMER_BUILD_REGIONS_WATERSHED,
+ /// The time to expand regions while applying the watershed algorithm. (See: #rcBuildRegions)
+ RC_TIMER_BUILD_REGIONS_EXPAND,
+ /// The time to flood regions while applying the watershed algorithm. (See: #rcBuildRegions)
+ RC_TIMER_BUILD_REGIONS_FLOOD,
+ /// The time to filter out small regions. (See: #rcBuildRegions, #rcBuildRegionsMonotone)
+ RC_TIMER_BUILD_REGIONS_FILTER,
+ /// The time to build heightfield layers. (See: #rcBuildHeightfieldLayers)
+ RC_TIMER_BUILD_LAYERS,
+ /// The time to build the polygon mesh detail. (See: #rcBuildPolyMeshDetail)
+ RC_TIMER_BUILD_POLYMESHDETAIL,
+ /// The time to merge polygon mesh details. (See: #rcMergePolyMeshDetails)
+ RC_TIMER_MERGE_POLYMESHDETAIL,
+ /// The maximum number of timers. (Used for iterating timers.)
+ RC_MAX_TIMERS
+};
+
+/// Provides an interface for optional logging and performance tracking of the Recast
+/// build process.
+///
+/// This class does not provide logging or timer functionality on its
+/// own. Both must be provided by a concrete implementation
+/// by overriding the protected member functions. Also, this class does not
+/// provide an interface for extracting log messages. (Only adding them.)
+/// So concrete implementations must provide one.
+///
+/// If no logging or timers are required, just pass an instance of this
+/// class through the Recast build process.
+///
+/// @ingroup recast
+class rcContext
+{
+public:
+ /// Constructor.
+ /// @param[in] state TRUE if the logging and performance timers should be enabled. [Default: true]
+ inline rcContext(bool state = true) : m_logEnabled(state), m_timerEnabled(state) {}
+ virtual ~rcContext() {}
+
+ /// Enables or disables logging.
+ /// @param[in] state TRUE if logging should be enabled.
+ inline void enableLog(bool state) { m_logEnabled = state; }
+
+ /// Clears all log entries.
+ inline void resetLog() { if (m_logEnabled) doResetLog(); }
+
+ /// Logs a message.
+ ///
+ /// Example:
+ /// @code
+ /// // Where ctx is an instance of rcContext and filepath is a char array.
+ /// ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not load '%s'", filepath);
+ /// @endcode
+ ///
+ /// @param[in] category The category of the message.
+ /// @param[in] format The message.
+ void log(const rcLogCategory category, const char* format, ...);
+
+ /// Enables or disables the performance timers.
+ /// @param[in] state TRUE if timers should be enabled.
+ inline void enableTimer(bool state) { m_timerEnabled = state; }
+
+ /// Clears all performance timers. (Resets all to unused.)
+ inline void resetTimers() { if (m_timerEnabled) doResetTimers(); }
+
+ /// Starts the specified performance timer.
+ /// @param label The category of the timer.
+ inline void startTimer(const rcTimerLabel label) { if (m_timerEnabled) doStartTimer(label); }
+
+ /// Stops the specified performance timer.
+ /// @param label The category of the timer.
+ inline void stopTimer(const rcTimerLabel label) { if (m_timerEnabled) doStopTimer(label); }
+
+ /// Returns the total accumulated time of the specified performance timer.
+ /// @param label The category of the timer.
+ /// @return The accumulated time of the timer, or -1 if timers are disabled or the timer has never been started.
+ inline int getAccumulatedTime(const rcTimerLabel label) const { return m_timerEnabled ? doGetAccumulatedTime(label) : -1; }
+
+protected:
+ /// Clears all log entries.
+ virtual void doResetLog();
+
+ /// Logs a message.
+ /// @param[in] category The category of the message.
+ /// @param[in] msg The formatted message.
+ /// @param[in] len The length of the formatted message.
+ virtual void doLog(const rcLogCategory category, const char* msg, const int len) { rcIgnoreUnused(category); rcIgnoreUnused(msg); rcIgnoreUnused(len); }
+
+ /// Clears all timers. (Resets all to unused.)
+ virtual void doResetTimers() {}
+
+ /// Starts the specified performance timer.
+ /// @param[in] label The category of timer.
+ virtual void doStartTimer(const rcTimerLabel label) { rcIgnoreUnused(label); }
+
+ /// Stops the specified performance timer.
+ /// @param[in] label The category of the timer.
+ virtual void doStopTimer(const rcTimerLabel label) { rcIgnoreUnused(label); }
+
+ /// Returns the total accumulated time of the specified performance timer.
+ /// @param[in] label The category of the timer.
+ /// @return The accumulated time of the timer, or -1 if timers are disabled or the timer has never been started.
+ virtual int doGetAccumulatedTime(const rcTimerLabel label) const { rcIgnoreUnused(label); return -1; }
+
+ /// True if logging is enabled.
+ bool m_logEnabled;
+
+ /// True if the performance timers are enabled.
+ bool m_timerEnabled;
+};
+
+/// A helper to first start a timer and then stop it when this helper goes out of scope.
+/// @see rcContext
+class rcScopedTimer
+{
+public:
+ /// Constructs an instance and starts the timer.
+ /// @param[in] ctx The context to use.
+ /// @param[in] label The category of the timer.
+ inline rcScopedTimer(rcContext* ctx, const rcTimerLabel label) : m_ctx(ctx), m_label(label) { m_ctx->startTimer(m_label); }
+ inline ~rcScopedTimer() { m_ctx->stopTimer(m_label); }
+
+private:
+ // Explicitly disabled copy constructor and copy assignment operator.
+ rcScopedTimer(const rcScopedTimer&);
+ rcScopedTimer& operator=(const rcScopedTimer&);
+
+ rcContext* const m_ctx;
+ const rcTimerLabel m_label;
+};
+
+/// Specifies a configuration to use when performing Recast builds.
+/// @ingroup recast
+struct rcConfig
+{
+ /// The width of the field along the x-axis. [Limit: >= 0] [Units: vx]
+ int width;
+
+ /// The height of the field along the z-axis. [Limit: >= 0] [Units: vx]
+ int height;
+
+ /// The width/height size of tile's on the xz-plane. [Limit: >= 0] [Units: vx]
+ int tileSize;
+
+ /// The size of the non-navigable border around the heightfield. [Limit: >=0] [Units: vx]
+ int borderSize;
+
+ /// The xz-plane cell size to use for fields. [Limit: > 0] [Units: wu]
+ float cs;
+
+ /// The y-axis cell size to use for fields. [Limit: > 0] [Units: wu]
+ float ch;
+
+ /// The minimum bounds of the field's AABB. [(x, y, z)] [Units: wu]
+ float bmin[3];
+
+ /// The maximum bounds of the field's AABB. [(x, y, z)] [Units: wu]
+ float bmax[3];
+
+ /// The maximum slope that is considered walkable. [Limits: 0 <= value < 90] [Units: Degrees]
+ float walkableSlopeAngle;
+
+ /// Minimum floor to 'ceiling' height that will still allow the floor area to
+ /// be considered walkable. [Limit: >= 3] [Units: vx]
+ int walkableHeight;
+
+ /// Maximum ledge height that is considered to still be traversable. [Limit: >=0] [Units: vx]
+ int walkableClimb;
+
+ /// The distance to erode/shrink the walkable area of the heightfield away from
+ /// obstructions. [Limit: >=0] [Units: vx]
+ int walkableRadius;
+
+ /// The maximum allowed length for contour edges along the border of the mesh. [Limit: >=0] [Units: vx]
+ int maxEdgeLen;
+
+ /// The maximum distance a simplified contour's border edges should deviate
+ /// the original raw contour. [Limit: >=0] [Units: vx]
+ float maxSimplificationError;
+
+ /// The minimum number of cells allowed to form isolated island areas. [Limit: >=0] [Units: vx]
+ int minRegionArea;
+
+ /// Any regions with a span count smaller than this value will, if possible,
+ /// be merged with larger regions. [Limit: >=0] [Units: vx]
+ int mergeRegionArea;
+
+ /// The maximum number of vertices allowed for polygons generated during the
+ /// contour to polygon conversion process. [Limit: >= 3]
+ int maxVertsPerPoly;
+
+ /// Sets the sampling distance to use when generating the detail mesh.
+ /// (For height detail only.) [Limits: 0 or >= 0.9] [Units: wu]
+ float detailSampleDist;
+
+ /// The maximum distance the detail mesh surface should deviate from heightfield
+ /// data. (For height detail only.) [Limit: >=0] [Units: wu]
+ float detailSampleMaxError;
+};
+
+/// Defines the number of bits allocated to rcSpan::smin and rcSpan::smax.
+static const int RC_SPAN_HEIGHT_BITS = 13;
+/// Defines the maximum value for rcSpan::smin and rcSpan::smax.
+static const int RC_SPAN_MAX_HEIGHT = (1 << RC_SPAN_HEIGHT_BITS) - 1;
+
+/// The number of spans allocated per span spool.
+/// @see rcSpanPool
+static const int RC_SPANS_PER_POOL = 2048;
+
+/// Represents a span in a heightfield.
+/// @see rcHeightfield
+struct rcSpan
+{
+ unsigned int smin : RC_SPAN_HEIGHT_BITS; ///< The lower limit of the span. (Inclusive) [Limit: < #smax]
+ unsigned int smax : RC_SPAN_HEIGHT_BITS; ///< The upper limit of the span. (Exclusive) [Limit: <= #RC_SPAN_MAX_HEIGHT]
+ unsigned int area : 6; ///< The area id assigned to the span.
+ rcSpan* next; ///< The next span higher up in column.
+};
+
+/// A memory pool used for quick allocation of spans within a heightfield.
+/// @see rcHeightfield
+struct rcSpanPool
+{
+ rcSpanPool* next; ///< The next span pool.
+ rcSpan items[RC_SPANS_PER_POOL]; ///< Array of spans in the pool.
+};
+
+/// A dynamic heightfield representing obstructed space.
+/// @ingroup recast
+struct rcHeightfield
+{
+ rcHeightfield();
+ ~rcHeightfield();
+
+ int width; ///< The width of the heightfield. (Along the x-axis in cell units.)
+ int height; ///< The height of the heightfield. (Along the z-axis in cell units.)
+ float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)]
+ float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)]
+ float cs; ///< The size of each cell. (On the xz-plane.)
+ float ch; ///< The height of each cell. (The minimum increment along the y-axis.)
+ rcSpan** spans; ///< Heightfield of spans (width*height).
+
+ // memory pool for rcSpan instances.
+ rcSpanPool* pools; ///< Linked list of span pools.
+ rcSpan* freelist; ///< The next free span.
+
+private:
+ // Explicitly-disabled copy constructor and copy assignment operator.
+ rcHeightfield(const rcHeightfield&);
+ rcHeightfield& operator=(const rcHeightfield&);
+};
+
+/// Provides information on the content of a cell column in a compact heightfield.
+struct rcCompactCell
+{
+ unsigned int index : 24; ///< Index to the first span in the column.
+ unsigned int count : 8; ///< Number of spans in the column.
+};
+
+/// Represents a span of unobstructed space within a compact heightfield.
+struct rcCompactSpan
+{
+ unsigned short y; ///< The lower extent of the span. (Measured from the heightfield's base.)
+ unsigned short reg; ///< The id of the region the span belongs to. (Or zero if not in a region.)
+ unsigned int con : 24; ///< Packed neighbor connection data.
+ unsigned int h : 8; ///< The height of the span. (Measured from #y.)
+};
+
+/// A compact, static heightfield representing unobstructed space.
+/// @ingroup recast
+struct rcCompactHeightfield
+{
+ rcCompactHeightfield();
+ ~rcCompactHeightfield();
+
+ int width; ///< The width of the heightfield. (Along the x-axis in cell units.)
+ int height; ///< The height of the heightfield. (Along the z-axis in cell units.)
+ int spanCount; ///< The number of spans in the heightfield.
+ int walkableHeight; ///< The walkable height used during the build of the field. (See: rcConfig::walkableHeight)
+ int walkableClimb; ///< The walkable climb used during the build of the field. (See: rcConfig::walkableClimb)
+ int borderSize; ///< The AABB border size used during the build of the field. (See: rcConfig::borderSize)
+ unsigned short maxDistance; ///< The maximum distance value of any span within the field.
+ unsigned short maxRegions; ///< The maximum region id of any span within the field.
+ float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)]
+ float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)]
+ float cs; ///< The size of each cell. (On the xz-plane.)
+ float ch; ///< The height of each cell. (The minimum increment along the y-axis.)
+ rcCompactCell* cells; ///< Array of cells. [Size: #width*#height]
+ rcCompactSpan* spans; ///< Array of spans. [Size: #spanCount]
+ unsigned short* dist; ///< Array containing border distance data. [Size: #spanCount]
+ unsigned char* areas; ///< Array containing area id data. [Size: #spanCount]
+
+private:
+ // Explicitly-disabled copy constructor and copy assignment operator.
+ rcCompactHeightfield(const rcCompactHeightfield&);
+ rcCompactHeightfield& operator=(const rcCompactHeightfield&);
+};
+
+/// Represents a heightfield layer within a layer set.
+/// @see rcHeightfieldLayerSet
+struct rcHeightfieldLayer
+{
+ float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)]
+ float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)]
+ float cs; ///< The size of each cell. (On the xz-plane.)
+ float ch; ///< The height of each cell. (The minimum increment along the y-axis.)
+ int width; ///< The width of the heightfield. (Along the x-axis in cell units.)
+ int height; ///< The height of the heightfield. (Along the z-axis in cell units.)
+ int minx; ///< The minimum x-bounds of usable data.
+ int maxx; ///< The maximum x-bounds of usable data.
+ int miny; ///< The minimum y-bounds of usable data. (Along the z-axis.)
+ int maxy; ///< The maximum y-bounds of usable data. (Along the z-axis.)
+ int hmin; ///< The minimum height bounds of usable data. (Along the y-axis.)
+ int hmax; ///< The maximum height bounds of usable data. (Along the y-axis.)
+ unsigned char* heights; ///< The heightfield. [Size: width * height]
+ unsigned char* areas; ///< Area ids. [Size: Same as #heights]
+ unsigned char* cons; ///< Packed neighbor connection information. [Size: Same as #heights]
+};
+
+/// Represents a set of heightfield layers.
+/// @ingroup recast
+/// @see rcAllocHeightfieldLayerSet, rcFreeHeightfieldLayerSet
+struct rcHeightfieldLayerSet
+{
+ rcHeightfieldLayerSet();
+ ~rcHeightfieldLayerSet();
+
+ rcHeightfieldLayer* layers; ///< The layers in the set. [Size: #nlayers]
+ int nlayers; ///< The number of layers in the set.
+
+private:
+ // Explicitly-disabled copy constructor and copy assignment operator.
+ rcHeightfieldLayerSet(const rcHeightfieldLayerSet&);
+ rcHeightfieldLayerSet& operator=(const rcHeightfieldLayerSet&);
+};
+
+/// Represents a simple, non-overlapping contour in field space.
+struct rcContour
+{
+ int* verts; ///< Simplified contour vertex and connection data. [Size: 4 * #nverts]
+ int nverts; ///< The number of vertices in the simplified contour.
+ int* rverts; ///< Raw contour vertex and connection data. [Size: 4 * #nrverts]
+ int nrverts; ///< The number of vertices in the raw contour.
+ unsigned short reg; ///< The region id of the contour.
+ unsigned char area; ///< The area id of the contour.
+};
+
+/// Represents a group of related contours.
+/// @ingroup recast
+struct rcContourSet
+{
+ rcContourSet();
+ ~rcContourSet();
+
+ rcContour* conts; ///< An array of the contours in the set. [Size: #nconts]
+ int nconts; ///< The number of contours in the set.
+ float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)]
+ float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)]
+ float cs; ///< The size of each cell. (On the xz-plane.)
+ float ch; ///< The height of each cell. (The minimum increment along the y-axis.)
+ int width; ///< The width of the set. (Along the x-axis in cell units.)
+ int height; ///< The height of the set. (Along the z-axis in cell units.)
+ int borderSize; ///< The AABB border size used to generate the source data from which the contours were derived.
+ float maxError; ///< The max edge error that this contour set was simplified with.
+
+private:
+ // Explicitly-disabled copy constructor and copy assignment operator.
+ rcContourSet(const rcContourSet&);
+ rcContourSet& operator=(const rcContourSet&);
+};
+
+/// Represents a polygon mesh suitable for use in building a navigation mesh.
+/// @ingroup recast
+struct rcPolyMesh
+{
+ rcPolyMesh();
+ ~rcPolyMesh();
+
+ unsigned short* verts; ///< The mesh vertices. [Form: (x, y, z) * #nverts]
+ unsigned short* polys; ///< Polygon and neighbor data. [Length: #maxpolys * 2 * #nvp]
+ unsigned short* regs; ///< The region id assigned to each polygon. [Length: #maxpolys]
+ unsigned short* flags; ///< The user defined flags for each polygon. [Length: #maxpolys]
+ unsigned char* areas; ///< The area id assigned to each polygon. [Length: #maxpolys]
+ int nverts; ///< The number of vertices.
+ int npolys; ///< The number of polygons.
+ int maxpolys; ///< The number of allocated polygons.
+ int nvp; ///< The maximum number of vertices per polygon.
+ float bmin[3]; ///< The minimum bounds in world space. [(x, y, z)]
+ float bmax[3]; ///< The maximum bounds in world space. [(x, y, z)]
+ float cs; ///< The size of each cell. (On the xz-plane.)
+ float ch; ///< The height of each cell. (The minimum increment along the y-axis.)
+ int borderSize; ///< The AABB border size used to generate the source data from which the mesh was derived.
+ float maxEdgeError; ///< The max error of the polygon edges in the mesh.
+
+private:
+ // Explicitly-disabled copy constructor and copy assignment operator.
+ rcPolyMesh(const rcPolyMesh&);
+ rcPolyMesh& operator=(const rcPolyMesh&);
+};
+
+/// Contains triangle meshes that represent detailed height data associated
+/// with the polygons in its associated polygon mesh object.
+/// @ingroup recast
+struct rcPolyMeshDetail
+{
+ rcPolyMeshDetail();
+
+ unsigned int* meshes; ///< The sub-mesh data. [Size: 4*#nmeshes]
+ float* verts; ///< The mesh vertices. [Size: 3*#nverts]
+ unsigned char* tris; ///< The mesh triangles. [Size: 4*#ntris]
+ int nmeshes; ///< The number of sub-meshes defined by #meshes.
+ int nverts; ///< The number of vertices in #verts.
+ int ntris; ///< The number of triangles in #tris.
+
+private:
+ // Explicitly-disabled copy constructor and copy assignment operator.
+ rcPolyMeshDetail(const rcPolyMeshDetail&);
+ rcPolyMeshDetail& operator=(const rcPolyMeshDetail&);
+};
+
+/// @name Allocation Functions
+/// Functions used to allocate and de-allocate Recast objects.
+/// @see rcAllocSetCustom
+/// @{
+
+/// Allocates a heightfield object using the Recast allocator.
+/// @return A heightfield that is ready for initialization, or null on failure.
+/// @ingroup recast
+/// @see rcCreateHeightfield, rcFreeHeightField
+rcHeightfield* rcAllocHeightfield();
+
+/// Frees the specified heightfield object using the Recast allocator.
+/// @param[in] heightfield A heightfield allocated using #rcAllocHeightfield
+/// @ingroup recast
+/// @see rcAllocHeightfield
+void rcFreeHeightField(rcHeightfield* heightfield);
+
+/// Allocates a compact heightfield object using the Recast allocator.
+/// @return A compact heightfield that is ready for initialization, or null on failure.
+/// @ingroup recast
+/// @see rcBuildCompactHeightfield, rcFreeCompactHeightfield
+rcCompactHeightfield* rcAllocCompactHeightfield();
+
+/// Frees the specified compact heightfield object using the Recast allocator.
+/// @param[in] compactHeightfield A compact heightfield allocated using #rcAllocCompactHeightfield
+/// @ingroup recast
+/// @see rcAllocCompactHeightfield
+void rcFreeCompactHeightfield(rcCompactHeightfield* compactHeightfield);
+
+/// Allocates a heightfield layer set using the Recast allocator.
+/// @return A heightfield layer set that is ready for initialization, or null on failure.
+/// @ingroup recast
+/// @see rcBuildHeightfieldLayers, rcFreeHeightfieldLayerSet
+rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet();
+
+/// Frees the specified heightfield layer set using the Recast allocator.
+/// @param[in] layerSet A heightfield layer set allocated using #rcAllocHeightfieldLayerSet
+/// @ingroup recast
+/// @see rcAllocHeightfieldLayerSet
+void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* layerSet);
+
+/// Allocates a contour set object using the Recast allocator.
+/// @return A contour set that is ready for initialization, or null on failure.
+/// @ingroup recast
+/// @see rcBuildContours, rcFreeContourSet
+rcContourSet* rcAllocContourSet();
+
+/// Frees the specified contour set using the Recast allocator.
+/// @param[in] contourSet A contour set allocated using #rcAllocContourSet
+/// @ingroup recast
+/// @see rcAllocContourSet
+void rcFreeContourSet(rcContourSet* contourSet);
+
+/// Allocates a polygon mesh object using the Recast allocator.
+/// @return A polygon mesh that is ready for initialization, or null on failure.
+/// @ingroup recast
+/// @see rcBuildPolyMesh, rcFreePolyMesh
+rcPolyMesh* rcAllocPolyMesh();
+
+/// Frees the specified polygon mesh using the Recast allocator.
+/// @param[in] polyMesh A polygon mesh allocated using #rcAllocPolyMesh
+/// @ingroup recast
+/// @see rcAllocPolyMesh
+void rcFreePolyMesh(rcPolyMesh* polyMesh);
+
+/// Allocates a detail mesh object using the Recast allocator.
+/// @return A detail mesh that is ready for initialization, or null on failure.
+/// @ingroup recast
+/// @see rcBuildPolyMeshDetail, rcFreePolyMeshDetail
+rcPolyMeshDetail* rcAllocPolyMeshDetail();
+
+/// Frees the specified detail mesh using the Recast allocator.
+/// @param[in] detailMesh A detail mesh allocated using #rcAllocPolyMeshDetail
+/// @ingroup recast
+/// @see rcAllocPolyMeshDetail
+void rcFreePolyMeshDetail(rcPolyMeshDetail* detailMesh);
+
+/// @}
+
+/// Heightfield border flag.
+/// If a heightfield region ID has this bit set, then the region is a border
+/// region and its spans are considered un-walkable.
+/// (Used during the region and contour build process.)
+/// @see rcCompactSpan::reg
+static const unsigned short RC_BORDER_REG = 0x8000;
+
+/// Polygon touches multiple regions.
+/// If a polygon has this region ID it was merged with or created
+/// from polygons of different regions during the polymesh
+/// build step that removes redundant border vertices.
+/// (Used during the polymesh and detail polymesh build processes)
+/// @see rcPolyMesh::regs
+static const unsigned short RC_MULTIPLE_REGS = 0;
+
+/// Border vertex flag.
+/// If a region ID has this bit set, then the associated element lies on
+/// a tile border. If a contour vertex's region ID has this bit set, the
+/// vertex will later be removed in order to match the segments and vertices
+/// at tile boundaries.
+/// (Used during the build process.)
+/// @see rcCompactSpan::reg, #rcContour::verts, #rcContour::rverts
+static const int RC_BORDER_VERTEX = 0x10000;
+
+/// Area border flag.
+/// If a region ID has this bit set, then the associated element lies on
+/// the border of an area.
+/// (Used during the region and contour build process.)
+/// @see rcCompactSpan::reg, #rcContour::verts, #rcContour::rverts
+static const int RC_AREA_BORDER = 0x20000;
+
+/// Contour build flags.
+/// @see rcBuildContours
+enum rcBuildContoursFlags
+{
+ RC_CONTOUR_TESS_WALL_EDGES = 0x01, ///< Tessellate solid (impassable) edges during contour simplification.
+ RC_CONTOUR_TESS_AREA_EDGES = 0x02 ///< Tessellate edges between areas during contour simplification.
+};
+
+/// Applied to the region id field of contour vertices in order to extract the region id.
+/// The region id field of a vertex may have several flags applied to it. So the
+/// fields value can't be used directly.
+/// @see rcContour::verts, rcContour::rverts
+static const int RC_CONTOUR_REG_MASK = 0xffff;
+
+/// An value which indicates an invalid index within a mesh.
+/// @note This does not necessarily indicate an error.
+/// @see rcPolyMesh::polys
+static const unsigned short RC_MESH_NULL_IDX = 0xffff;
+
+/// Represents the null area.
+/// When a data element is given this value it is considered to no longer be
+/// assigned to a usable area. (E.g. It is un-walkable.)
+static const unsigned char RC_NULL_AREA = 0;
+
+/// The default area id used to indicate a walkable polygon.
+/// This is also the maximum allowed area id, and the only non-null area id
+/// recognized by some steps in the build process.
+static const unsigned char RC_WALKABLE_AREA = 63;
+
+/// The value returned by #rcGetCon if the specified direction is not connected
+/// to another span. (Has no neighbor.)
+static const int RC_NOT_CONNECTED = 0x3f;
+
+/// @name General helper functions
+/// @{
+
+/// Swaps the values of the two parameters.
+/// @param[in,out] a Value A
+/// @param[in,out] b Value B
+template inline void rcSwap(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 inline T rcMin(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 inline T rcMax(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 inline T rcAbs(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 inline T rcSqr(T a) { return a * a; }
+
+/// Clamps the value to the specified range.
+/// @param[in] value The value to clamp.
+/// @param[in] minInclusive The minimum permitted return value.
+/// @param[in] maxInclusive The maximum permitted return value.
+/// @return The value, clamped to the specified range.
+template inline T rcClamp(T value, T minInclusive, T maxInclusive)
+{
+ return value < minInclusive ? minInclusive: (value > maxInclusive ? maxInclusive : value);
+}
+
+/// Returns the square root of the value.
+/// @param[in] x The value.
+/// @return The square root of the vlaue.
+float rcSqrt(float x);
+
+/// @}
+/// @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 rcVcross(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 rcVdot(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 rcVmad(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 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 rcVadd(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 rcVsub(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];
+}
+
+/// 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 rcVmin(float* mn, const float* v)
+{
+ mn[0] = rcMin(mn[0], v[0]);
+ mn[1] = rcMin(mn[1], v[1]);
+ mn[2] = rcMin(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 rcVmax(float* mx, const float* v)
+{
+ mx[0] = rcMax(mx[0], v[0]);
+ mx[1] = rcMax(mx[1], v[1]);
+ mx[2] = rcMax(mx[2], v[2]);
+}
+
+/// Performs a vector copy.
+/// @param[out] dest The result. [(x, y, z)]
+/// @param[in] v The vector to copy. [(x, y, z)]
+inline void rcVcopy(float* dest, const float* v)
+{
+ dest[0] = v[0];
+ dest[1] = v[1];
+ dest[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 rcVdist(const float* v1, const float* v2)
+{
+ float dx = v2[0] - v1[0];
+ float dy = v2[1] - v1[1];
+ float dz = v2[2] - v1[2];
+ return rcSqrt(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 rcVdistSqr(const float* v1, const float* v2)
+{
+ float dx = v2[0] - v1[0];
+ float dy = v2[1] - v1[1];
+ float dz = v2[2] - v1[2];
+ return dx*dx + dy*dy + dz*dz;
+}
+
+/// Normalizes the vector.
+/// @param[in,out] v The vector to normalize. [(x, y, z)]
+inline void rcVnormalize(float* v)
+{
+ float d = 1.0f / rcSqrt(rcSqr(v[0]) + rcSqr(v[1]) + rcSqr(v[2]));
+ v[0] *= d;
+ v[1] *= d;
+ v[2] *= d;
+}
+
+/// @}
+/// @name Heightfield Functions
+/// @see rcHeightfield
+/// @{
+
+/// Calculates the bounding box of an array of vertices.
+/// @ingroup recast
+/// @param[in] verts An array of vertices. [(x, y, z) * @p nv]
+/// @param[in] numVerts The number of vertices in the @p verts array.
+/// @param[out] minBounds The minimum bounds of the AABB. [(x, y, z)] [Units: wu]
+/// @param[out] maxBounds The maximum bounds of the AABB. [(x, y, z)] [Units: wu]
+void rcCalcBounds(const float* verts, int numVerts, float* minBounds, float* maxBounds);
+
+/// Calculates the grid size based on the bounding box and grid cell size.
+/// @ingroup recast
+/// @param[in] minBounds The minimum bounds of the AABB. [(x, y, z)] [Units: wu]
+/// @param[in] maxBounds The maximum bounds of the AABB. [(x, y, z)] [Units: wu]
+/// @param[in] cellSize The xz-plane cell size. [Limit: > 0] [Units: wu]
+/// @param[out] sizeX The width along the x-axis. [Limit: >= 0] [Units: vx]
+/// @param[out] sizeZ The height along the z-axis. [Limit: >= 0] [Units: vx]
+void rcCalcGridSize(const float* minBounds, const float* maxBounds, float cellSize, int* sizeX, int* sizeZ);
+
+/// Initializes a new heightfield.
+/// See the #rcConfig documentation for more information on the configuration parameters.
+///
+/// @see rcAllocHeightfield, rcHeightfield
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in,out] heightfield The allocated heightfield to initialize.
+/// @param[in] sizeX The width of the field along the x-axis. [Limit: >= 0] [Units: vx]
+/// @param[in] sizeZ The height of the field along the z-axis. [Limit: >= 0] [Units: vx]
+/// @param[in] minBounds The minimum bounds of the field's AABB. [(x, y, z)] [Units: wu]
+/// @param[in] maxBounds The maximum bounds of the field's AABB. [(x, y, z)] [Units: wu]
+/// @param[in] cellSize The xz-plane cell size to use for the field. [Limit: > 0] [Units: wu]
+/// @param[in] cellHeight The y-axis cell size to use for field. [Limit: > 0] [Units: wu]
+/// @returns True if the operation completed successfully.
+bool rcCreateHeightfield(rcContext* context, rcHeightfield& heightfield, int sizeX, int sizeZ,
+ const float* minBounds, const float* maxBounds,
+ float cellSize, float cellHeight);
+
+/// Sets the area id of all triangles with a slope below the specified value
+/// to #RC_WALKABLE_AREA.
+///
+/// Only sets the area id's for the walkable triangles. Does not alter the
+/// area id's for un-walkable triangles.
+///
+/// See the #rcConfig documentation for more information on the configuration parameters.
+///
+/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
+///
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] walkableSlopeAngle The maximum slope that is considered walkable.
+/// [Limits: 0 <= value < 90] [Units: Degrees]
+/// @param[in] verts The vertices. [(x, y, z) * @p nv]
+/// @param[in] numVerts The number of vertices.
+/// @param[in] tris The triangle vertex indices. [(vertA, vertB, vertC) * @p nt]
+/// @param[in] numTris The number of triangles.
+/// @param[out] triAreaIDs The triangle area ids. [Length: >= @p nt]
+void rcMarkWalkableTriangles(rcContext* context, float walkableSlopeAngle, const float* verts, int numVerts,
+ const int* tris, int numTris, unsigned char* triAreaIDs);
+
+/// Sets the area id of all triangles with a slope greater than or equal to the specified value to #RC_NULL_AREA.
+///
+/// Only sets the area id's for the un-walkable triangles. Does not alter the
+/// area id's for walkable triangles.
+///
+/// See the #rcConfig documentation for more information on the configuration parameters.
+///
+/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
+///
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] walkableSlopeAngle The maximum slope that is considered walkable.
+/// [Limits: 0 <= value < 90] [Units: Degrees]
+/// @param[in] verts The vertices. [(x, y, z) * @p nv]
+/// @param[in] numVerts The number of vertices.
+/// @param[in] tris The triangle vertex indices. [(vertA, vertB, vertC) * @p nt]
+/// @param[in] numTris The number of triangles.
+/// @param[out] triAreaIDs The triangle area ids. [Length: >= @p nt]
+void rcClearUnwalkableTriangles(rcContext* context, float walkableSlopeAngle, const float* verts, int numVerts,
+ const int* tris, int numTris, unsigned char* triAreaIDs);
+
+/// Adds a span to the specified heightfield.
+///
+/// The span addition can be set to favor flags. If the span is merged to
+/// another span and the new @p spanMax is within @p flagMergeThreshold units
+/// from the existing span, the span flags are merged.
+///
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in,out] heightfield An initialized heightfield.
+/// @param[in] x The column x index where the span is to be added.
+/// [Limits: 0 <= value < rcHeightfield::width]
+/// @param[in] z The column z index where the span is to be added.
+/// [Limits: 0 <= value < rcHeightfield::height]
+/// @param[in] spanMin The minimum height of the span. [Limit: < @p spanMax] [Units: vx]
+/// @param[in] spanMax The maximum height of the span. [Limit: <= #RC_SPAN_MAX_HEIGHT] [Units: vx]
+/// @param[in] areaID The area id of the span. [Limit: <= #RC_WALKABLE_AREA)
+/// @param[in] flagMergeThreshold The merge threshold. [Limit: >= 0] [Units: vx]
+/// @returns True if the operation completed successfully.
+bool rcAddSpan(rcContext* context, rcHeightfield& heightfield,
+ int x, int z,
+ unsigned short spanMin, unsigned short spanMax,
+ unsigned char areaID, int flagMergeThreshold);
+
+/// Rasterizes a single triangle into the specified heightfield.
+///
+/// Calling this for each triangle in a mesh is less efficient than calling rcRasterizeTriangles
+///
+/// No spans will be added if the triangle does not overlap the heightfield grid.
+///
+/// @see rcHeightfield
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] v0 Triangle vertex 0 [(x, y, z)]
+/// @param[in] v1 Triangle vertex 1 [(x, y, z)]
+/// @param[in] v2 Triangle vertex 2 [(x, y, z)]
+/// @param[in] areaID The area id of the triangle. [Limit: <= #RC_WALKABLE_AREA]
+/// @param[in,out] heightfield An initialized heightfield.
+/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag.
+/// [Limit: >= 0] [Units: vx]
+/// @returns True if the operation completed successfully.
+bool rcRasterizeTriangle(rcContext* context,
+ const float* v0, const float* v1, const float* v2,
+ unsigned char areaID, rcHeightfield& heightfield, int flagMergeThreshold = 1);
+
+/// Rasterizes an indexed triangle mesh into the specified heightfield.
+///
+/// Spans will only be added for triangles that overlap the heightfield grid.
+///
+/// @see rcHeightfield
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] verts The vertices. [(x, y, z) * @p nv]
+/// @param[in] numVerts The number of vertices. (unused) TODO (graham): Remove in next major release
+/// @param[in] tris The triangle indices. [(vertA, vertB, vertC) * @p nt]
+/// @param[in] triAreaIDs The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt]
+/// @param[in] numTris The number of triangles.
+/// @param[in,out] heightfield An initialized heightfield.
+/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag.
+/// [Limit: >= 0] [Units: vx]
+/// @returns True if the operation completed successfully.
+bool rcRasterizeTriangles(rcContext* context,
+ const float* verts, int numVerts,
+ const int* tris, const unsigned char* triAreaIDs, int numTris,
+ rcHeightfield& heightfield, int flagMergeThreshold = 1);
+
+/// Rasterizes an indexed triangle mesh into the specified heightfield.
+///
+/// Spans will only be added for triangles that overlap the heightfield grid.
+///
+/// @see rcHeightfield
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] verts The vertices. [(x, y, z) * @p nv]
+/// @param[in] numVerts The number of vertices. (unused) TODO (graham): Remove in next major release
+/// @param[in] tris The triangle indices. [(vertA, vertB, vertC) * @p nt]
+/// @param[in] triAreaIDs The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt]
+/// @param[in] numTris The number of triangles.
+/// @param[in,out] heightfield An initialized heightfield.
+/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag.
+/// [Limit: >= 0] [Units: vx]
+/// @returns True if the operation completed successfully.
+bool rcRasterizeTriangles(rcContext* context,
+ const float* verts, int numVerts,
+ const unsigned short* tris, const unsigned char* triAreaIDs, int numTris,
+ rcHeightfield& heightfield, int flagMergeThreshold = 1);
+
+/// Rasterizes a triangle list into the specified heightfield.
+///
+/// Expects each triangle to be specified as three sequential vertices of 3 floats.
+///
+/// Spans will only be added for triangles that overlap the heightfield grid.
+///
+/// @see rcHeightfield
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] verts The triangle vertices. [(ax, ay, az, bx, by, bz, cx, by, cx) * @p nt]
+/// @param[in] triAreaIDs The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt]
+/// @param[in] numTris The number of triangles.
+/// @param[in,out] heightfield An initialized heightfield.
+/// @param[in] flagMergeThreshold The distance where the walkable flag is favored over the non-walkable flag.
+/// [Limit: >= 0] [Units: vx]
+/// @returns True if the operation completed successfully.
+bool rcRasterizeTriangles(rcContext* context,
+ const float* verts, const unsigned char* triAreaIDs, int numTris,
+ rcHeightfield& heightfield, int flagMergeThreshold = 1);
+
+/// Marks non-walkable spans as walkable if their maximum is within @p walkableClimb of the span below them.
+///
+/// This removes small obstacles and rasterization artifacts that the agent would be able to walk over
+/// such as curbs. It also allows agents to move up terraced structures like stairs.
+///
+/// Obstacle spans are marked walkable if: obstacleSpan.smax - walkableSpan.smax < walkableClimb
+///
+/// @warning Will override the effect of #rcFilterLedgeSpans. If both filters are used, call #rcFilterLedgeSpans only after applying this filter.
+///
+/// @see rcHeightfield, rcConfig
+///
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable.
+/// [Limit: >=0] [Units: vx]
+/// @param[in,out] heightfield A fully built heightfield. (All spans have been added.)
+void rcFilterLowHangingWalkableObstacles(rcContext* context, int walkableClimb, rcHeightfield& heightfield);
+
+/// Marks spans that are ledges as not-walkable.
+///
+/// A ledge is a span with one or more neighbors whose maximum is further away than @p walkableClimb
+/// from the current span's maximum.
+/// This method removes the impact of the overestimation of conservative voxelization
+/// so the resulting mesh will not have regions hanging in the air over ledges.
+///
+/// A span is a ledge if: rcAbs(currentSpan.smax - neighborSpan.smax) > walkableClimb
+///
+/// @see rcHeightfield, rcConfig
+///
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area to
+/// be considered walkable. [Limit: >= 3] [Units: vx]
+/// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable.
+/// [Limit: >=0] [Units: vx]
+/// @param[in,out] heightfield A fully built heightfield. (All spans have been added.)
+void rcFilterLedgeSpans(rcContext* context, int walkableHeight, int walkableClimb, rcHeightfield& heightfield);
+
+/// Marks walkable spans as not walkable if the clearance above the span is less than the specified walkableHeight.
+///
+/// For this filter, the clearance above the span is the distance from the span's
+/// maximum to the minimum of the next higher span in the same column.
+/// If there is no higher span in the column, the clearance is computed as the
+/// distance from the top of the span to the maximum heightfield height.
+///
+/// @see rcHeightfield, rcConfig
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area to
+/// be considered walkable. [Limit: >= 3] [Units: vx]
+/// @param[in,out] heightfield A fully built heightfield. (All spans have been added.)
+void rcFilterWalkableLowHeightSpans(rcContext* context, int walkableHeight, rcHeightfield& heightfield);
+
+/// Returns the number of spans contained in the specified heightfield.
+/// @ingroup recast
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] heightfield An initialized heightfield.
+/// @returns The number of spans in the heightfield.
+int rcGetHeightFieldSpanCount(rcContext* context, const rcHeightfield& heightfield);
+
+/// @}
+/// @name Compact Heightfield Functions
+/// @see rcCompactHeightfield
+/// @{
+
+/// Builds a compact heightfield representing open space, from a heightfield representing solid space.
+///
+/// This is just the beginning of the process of fully building a compact heightfield.
+/// Various filters may be applied, then the distance field and regions built.
+/// E.g: #rcBuildDistanceField and #rcBuildRegions
+///
+/// See the #rcConfig documentation for more information on the configuration parameters.
+///
+/// @see rcAllocCompactHeightfield, rcHeightfield, rcCompactHeightfield, rcConfig
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area
+/// to be considered walkable. [Limit: >= 3] [Units: vx]
+/// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable.
+/// [Limit: >=0] [Units: vx]
+/// @param[in] heightfield The heightfield to be compacted.
+/// @param[out] compactHeightfield The resulting compact heightfield. (Must be pre-allocated.)
+/// @returns True if the operation completed successfully.
+bool rcBuildCompactHeightfield(rcContext* context, int walkableHeight, int walkableClimb,
+ const rcHeightfield& heightfield, rcCompactHeightfield& compactHeightfield);
+
+/// Erodes the walkable area within the heightfield by the specified radius.
+///
+/// Basically, any spans that are closer to a boundary or obstruction than the specified radius
+/// are marked as un-walkable.
+///
+/// This method is usually called immediately after the heightfield has been built.
+///
+/// @see rcCompactHeightfield, rcBuildCompactHeightfield, rcConfig::walkableRadius
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] erosionRadius The radius of erosion. [Limits: 0 < value < 255] [Units: vx]
+/// @param[in,out] compactHeightfield The populated compact heightfield to erode.
+/// @returns True if the operation completed successfully.
+bool rcErodeWalkableArea(rcContext* context, int erosionRadius, rcCompactHeightfield& compactHeightfield);
+
+/// Applies a median filter to walkable area types (based on area id), removing noise.
+///
+/// This filter is usually applied after applying area id's using functions
+/// such as #rcMarkBoxArea, #rcMarkConvexPolyArea, and #rcMarkCylinderArea.
+///
+/// @see rcCompactHeightfield
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in,out] compactHeightfield A populated compact heightfield.
+/// @returns True if the operation completed successfully.
+bool rcMedianFilterWalkableArea(rcContext* context, rcCompactHeightfield& compactHeightfield);
+
+/// Applies an area id to all spans within the specified bounding box. (AABB)
+///
+/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] boxMinBounds The minimum extents of the bounding box. [(x, y, z)] [Units: wu]
+/// @param[in] boxMaxBounds The maximum extents of the bounding box. [(x, y, z)] [Units: wu]
+/// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA]
+/// @param[in,out] compactHeightfield A populated compact heightfield.
+void rcMarkBoxArea(rcContext* context, const float* boxMinBounds, const float* boxMaxBounds, unsigned char areaId,
+ rcCompactHeightfield& compactHeightfield);
+
+/// Applies the area id to the all spans within the specified convex polygon.
+///
+/// The value of spacial parameters are in world units.
+///
+/// The y-values of the polygon vertices are ignored. So the polygon is effectively
+/// projected onto the xz-plane, translated to @p minY, and extruded to @p maxY.
+///
+/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] verts The vertices of the polygon [For: (x, y, z) * @p numVerts]
+/// @param[in] numVerts The number of vertices in the polygon.
+/// @param[in] minY The height of the base of the polygon. [Units: wu]
+/// @param[in] maxY The height of the top of the polygon. [Units: wu]
+/// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA]
+/// @param[in,out] compactHeightfield A populated compact heightfield.
+void rcMarkConvexPolyArea(rcContext* context, const float* verts, int numVerts,
+ float minY, float maxY, unsigned char areaId,
+ rcCompactHeightfield& compactHeightfield);
+
+/// Expands a convex polygon along its vertex normals by the given offset amount.
+/// Inserts extra vertices to bevel sharp corners.
+///
+/// Helper function to offset convex polygons for rcMarkConvexPolyArea.
+///
+/// @ingroup recast
+///
+/// @param[in] verts The vertices of the polygon [Form: (x, y, z) * @p numVerts]
+/// @param[in] numVerts The number of vertices in the polygon.
+/// @param[in] offset How much to offset the polygon by. [Units: wu]
+/// @param[out] outVerts The offset vertices (should hold up to 2 * @p numVerts) [Form: (x, y, z) * return value]
+/// @param[in] maxOutVerts The max number of vertices that can be stored to @p outVerts.
+/// @returns Number of vertices in the offset polygon or 0 if too few vertices in @p outVerts.
+int rcOffsetPoly(const float* verts, int numVerts, float offset, float* outVerts, int maxOutVerts);
+
+/// Applies the area id to all spans within the specified y-axis-aligned cylinder.
+///
+/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
+///
+/// @ingroup recast
+///
+/// @param[in,out] context The build context to use during the operation.
+/// @param[in] position The center of the base of the cylinder. [Form: (x, y, z)] [Units: wu]
+/// @param[in] radius The radius of the cylinder. [Units: wu] [Limit: > 0]
+/// @param[in] height The height of the cylinder. [Units: wu] [Limit: > 0]
+/// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA]
+/// @param[in,out] compactHeightfield A populated compact heightfield.
+void rcMarkCylinderArea(rcContext* context, const float* position, float radius, float height,
+ unsigned char areaId, rcCompactHeightfield& compactHeightfield);
+
+/// Builds the distance field for the specified compact heightfield.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in,out] chf A populated compact heightfield.
+/// @returns True if the operation completed successfully.
+bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf);
+
+/// Builds region data for the heightfield using watershed partitioning.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in,out] chf A populated compact heightfield.
+/// @param[in] borderSize The size of the non-navigable border around the heightfield.
+/// [Limit: >=0] [Units: vx]
+/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas.
+/// [Limit: >=0] [Units: vx].
+/// @param[in] mergeRegionArea Any regions with a span count smaller than this value will, if possible,
+/// be merged with larger regions. [Limit: >=0] [Units: vx]
+/// @returns True if the operation completed successfully.
+bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf, int borderSize, int minRegionArea, int mergeRegionArea);
+
+/// Builds region data for the heightfield by partitioning the heightfield in non-overlapping layers.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in,out] chf A populated compact heightfield.
+/// @param[in] borderSize The size of the non-navigable border around the heightfield.
+/// [Limit: >=0] [Units: vx]
+/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas.
+/// [Limit: >=0] [Units: vx].
+/// @returns True if the operation completed successfully.
+bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf, int borderSize, int minRegionArea);
+
+/// Builds region data for the heightfield using simple monotone partitioning.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in,out] chf A populated compact heightfield.
+/// @param[in] borderSize The size of the non-navigable border around the heightfield.
+/// [Limit: >=0] [Units: vx]
+/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas.
+/// [Limit: >=0] [Units: vx].
+/// @param[in] mergeRegionArea Any regions with a span count smaller than this value will, if possible,
+/// be merged with larger regions. [Limit: >=0] [Units: vx]
+/// @returns True if the operation completed successfully.
+bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
+ int borderSize, int minRegionArea, int mergeRegionArea);
+
+/// Sets the neighbor connection data for the specified direction.
+/// @param[in] span The span to update.
+/// @param[in] direction The direction to set. [Limits: 0 <= value < 4]
+/// @param[in] neighborIndex The index of the neighbor span.
+inline void rcSetCon(rcCompactSpan& span, int direction, int neighborIndex)
+{
+ const unsigned int shift = (unsigned int)direction * 6;
+ const unsigned int con = span.con;
+ span.con = (con & ~(0x3f << shift)) | (((unsigned int)neighborIndex & 0x3f) << shift);
+}
+
+/// Gets neighbor connection data for the specified direction.
+/// @param[in] span The span to check.
+/// @param[in] direction The direction to check. [Limits: 0 <= value < 4]
+/// @return The neighbor connection data for the specified direction, or #RC_NOT_CONNECTED if there is no connection.
+inline int rcGetCon(const rcCompactSpan& span, int direction)
+{
+ const unsigned int shift = (unsigned int)direction * 6;
+ return (span.con >> shift) & 0x3f;
+}
+
+/// Gets the standard width (x-axis) offset for the specified direction.
+/// @param[in] direction The direction. [Limits: 0 <= value < 4]
+/// @return The width offset to apply to the current cell position to move in the direction.
+inline int rcGetDirOffsetX(int direction)
+{
+ static const int offset[4] = { -1, 0, 1, 0, };
+ return offset[direction & 0x03];
+}
+
+// TODO (graham): Rename this to rcGetDirOffsetZ
+/// Gets the standard height (z-axis) offset for the specified direction.
+/// @param[in] direction The direction. [Limits: 0 <= value < 4]
+/// @return The height offset to apply to the current cell position to move in the direction.
+inline int rcGetDirOffsetY(int direction)
+{
+ static const int offset[4] = { 0, 1, 0, -1 };
+ return offset[direction & 0x03];
+}
+
+/// Gets the direction for the specified offset. One of x and y should be 0.
+/// @param[in] offsetX The x offset. [Limits: -1 <= value <= 1]
+/// @param[in] offsetZ The z offset. [Limits: -1 <= value <= 1]
+/// @return The direction that represents the offset.
+inline int rcGetDirForOffset(int offsetX, int offsetZ)
+{
+ static const int dirs[5] = { 3, 0, -1, 2, 1 };
+ return dirs[((offsetZ + 1) << 1) + offsetX];
+}
+
+/// @}
+/// @name Layer, Contour, Polymesh, and Detail Mesh Functions
+/// @see rcHeightfieldLayer, rcContourSet, rcPolyMesh, rcPolyMeshDetail
+/// @{
+
+/// Builds a layer set from the specified compact heightfield.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in] chf A fully built compact heightfield.
+/// @param[in] borderSize The size of the non-navigable border around the heightfield. [Limit: >=0]
+/// [Units: vx]
+/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area
+/// to be considered walkable. [Limit: >= 3] [Units: vx]
+/// @param[out] lset The resulting layer set. (Must be pre-allocated.)
+/// @returns True if the operation completed successfully.
+bool rcBuildHeightfieldLayers(rcContext* ctx, const rcCompactHeightfield& chf,
+ int borderSize, int walkableHeight,
+ rcHeightfieldLayerSet& lset);
+
+/// Builds a contour set from the region outlines in the provided compact heightfield.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in] chf A fully built compact heightfield.
+/// @param[in] maxError The maximum distance a simplified contour's border edges should deviate
+/// the original raw contour. [Limit: >=0] [Units: wu]
+/// @param[in] maxEdgeLen The maximum allowed length for contour edges along the border of the mesh.
+/// [Limit: >=0] [Units: vx]
+/// @param[out] cset The resulting contour set. (Must be pre-allocated.)
+/// @param[in] buildFlags The build flags. (See: #rcBuildContoursFlags)
+/// @returns True if the operation completed successfully.
+bool rcBuildContours(rcContext* ctx, const rcCompactHeightfield& chf,
+ float maxError, int maxEdgeLen,
+ rcContourSet& cset, int buildFlags = RC_CONTOUR_TESS_WALL_EDGES);
+
+/// Builds a polygon mesh from the provided contours.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in] cset A fully built contour set.
+/// @param[in] nvp The maximum number of vertices allowed for polygons generated during the
+/// contour to polygon conversion process. [Limit: >= 3]
+/// @param[out] mesh The resulting polygon mesh. (Must be re-allocated.)
+/// @returns True if the operation completed successfully.
+bool rcBuildPolyMesh(rcContext* ctx, const rcContourSet& cset, const int nvp, rcPolyMesh& mesh);
+
+/// Merges multiple polygon meshes into a single mesh.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in] meshes An array of polygon meshes to merge. [Size: @p nmeshes]
+/// @param[in] nmeshes The number of polygon meshes in the meshes array.
+/// @param[in] mesh The resulting polygon mesh. (Must be pre-allocated.)
+/// @returns True if the operation completed successfully.
+bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh);
+
+/// Builds a detail mesh from the provided polygon mesh.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in] mesh A fully built polygon mesh.
+/// @param[in] chf The compact heightfield used to build the polygon mesh.
+/// @param[in] sampleDist Sets the distance to use when sampling the heightfield. [Limit: >=0] [Units: wu]
+/// @param[in] sampleMaxError The maximum distance the detail mesh surface should deviate from
+/// heightfield data. [Limit: >=0] [Units: wu]
+/// @param[out] dmesh The resulting detail mesh. (Must be pre-allocated.)
+/// @returns True if the operation completed successfully.
+bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf,
+ float sampleDist, float sampleMaxError,
+ rcPolyMeshDetail& dmesh);
+
+/// Copies the poly mesh data from src to dst.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in] src The source mesh to copy from.
+/// @param[out] dst The resulting detail mesh. (Must be pre-allocated, must be empty mesh.)
+/// @returns True if the operation completed successfully.
+bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst);
+
+/// Merges multiple detail meshes into a single detail mesh.
+/// @ingroup recast
+/// @param[in,out] ctx The build context to use during the operation.
+/// @param[in] meshes An array of detail meshes to merge. [Size: @p nmeshes]
+/// @param[in] nmeshes The number of detail meshes in the meshes array.
+/// @param[out] mesh The resulting detail mesh. (Must be pre-allocated.)
+/// @returns True if the operation completed successfully.
+bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh);
+
+/// @}
+
+#endif // RECAST_H
+
+///////////////////////////////////////////////////////////////////////////
+
+// Due to the large amount of detail documentation for this file,
+// the content normally located at the end of the header file has been separated
+// out to a file in /Docs/Extern.
diff --git a/native/third_party/recastnavigation/Recast/Include/RecastAlloc.h b/native/third_party/recastnavigation/Recast/Include/RecastAlloc.h
new file mode 100644
index 0000000..2ca43ec
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Include/RecastAlloc.h
@@ -0,0 +1,391 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+
+/// 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 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
+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& 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& other);
+
+ // Explicitly deleted.
+ rcVectorBase& operator=(const rcVectorBase& other);
+};
+
+template
+bool rcVectorBase::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
+T* rcVectorBase::allocate_and_copy(rcSizeType size)
+{
+ rcAssert(RC_SIZE_MAX / static_cast(sizeof(T)) >= size);
+ T* new_data = static_cast(rcAlloc(sizeof(T) * size, H));
+ if (new_data)
+ {
+ copy_range(new_data, m_data, m_data + m_size);
+ }
+ return new_data;
+}
+
+template
+void rcVectorBase::assign(const T* begin, const T* end)
+{
+ clear();
+ reserve(end - begin);
+ m_size = end - begin;
+ copy_range(m_data, begin, end);
+}
+
+template
+void rcVectorBase::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
+rcSizeType rcVectorBase::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
+void rcVectorBase::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
+void rcVectorBase::swap(rcVectorBase& 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
+void rcVectorBase::construct_range(T* begin, T* end)
+{
+ for (T* p = begin; p < end; p++)
+ {
+ construct(p);
+ }
+}
+
+// static
+template
+void rcVectorBase::construct_range(T* begin, T* end, const T& value)
+{
+ for (T* p = begin; p < end; p++)
+ {
+ construct(p, value);
+ }
+}
+
+// static
+template
+void rcVectorBase::copy_range(T* dst, const T* begin, const T* end)
+{
+ for (rcSizeType i = 0 ; i < end - begin; i++)
+ {
+ construct(dst + i, begin[i]);
+ }
+}
+
+template
+void rcVectorBase::destroy_range(rcSizeType begin, rcSizeType end)
+{
+ for (rcSizeType i = begin; i < end; i++)
+ {
+ m_data[i].~T();
+ }
+}
+
+template
+class rcTempVector : public rcVectorBase
+{
+ typedef rcVectorBase Base;
+public:
+ rcTempVector() : Base() {}
+ explicit rcTempVector(rcSizeType size) : Base(size) {}
+ rcTempVector(rcSizeType size, const T& value) : Base(size, value) {}
+ rcTempVector(const rcTempVector& other) : Base(other) {}
+ rcTempVector(const T* begin, const T* end) : Base(begin, end) {}
+};
+
+template
+class rcPermVector : public rcVectorBase
+{
+ typedef rcVectorBase Base;
+public:
+ rcPermVector() : Base() {}
+ explicit rcPermVector(rcSizeType size) : Base(size) {}
+ rcPermVector(rcSizeType size, const T& value) : Base(size, value) {}
+ rcPermVector(const rcPermVector& 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 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
\ No newline at end of file
diff --git a/native/third_party/recastnavigation/Recast/Include/RecastAssert.h b/native/third_party/recastnavigation/Recast/Include/RecastAssert.h
new file mode 100644
index 0000000..7527cff
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Include/RecastAssert.h
@@ -0,0 +1,49 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+# 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
diff --git a/native/third_party/recastnavigation/Recast/Source/Recast.cpp b/native/third_party/recastnavigation/Recast/Source/Recast.cpp
new file mode 100644
index 0000000..d75a9f5
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/Recast.cpp
@@ -0,0 +1,542 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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 "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+#include
+#include
+#include
+#include
+
+namespace
+{
+/// Allocates and constructs an object of the given type, returning a pointer.
+/// @param[in] allocLifetime Allocation lifetime hint
+template
+T* rcNew(const rcAllocHint allocLifetime)
+{
+ T* ptr = (T*)rcAlloc(sizeof(T), allocLifetime);
+ ::new(rcNewTag(), (void*)ptr) T();
+ return ptr;
+}
+
+/// Destroys and frees an object allocated with rcNew.
+/// @param[in] ptr The object pointer to delete.
+template
+void rcDelete(T* ptr)
+{
+ if (ptr)
+ {
+ ptr->~T();
+ rcFree((void*)ptr);
+ }
+}
+} // anonymous namespace
+
+float rcSqrt(float x)
+{
+ return sqrtf(x);
+}
+
+void rcContext::log(const rcLogCategory category, const char* format, ...)
+{
+ if (!m_logEnabled)
+ {
+ return;
+ }
+ static const int MSG_SIZE = 512;
+ char msg[MSG_SIZE];
+ va_list argList;
+ va_start(argList, format);
+ int len = vsnprintf(msg, MSG_SIZE, format, argList);
+ if (len >= MSG_SIZE)
+ {
+ len = MSG_SIZE - 1;
+ msg[MSG_SIZE - 1] = '\0';
+
+ const char* errorMessage = "Log message was truncated";
+ doLog(RC_LOG_ERROR, errorMessage, (int)strlen(errorMessage));
+ }
+ va_end(argList);
+ doLog(category, msg, len);
+}
+
+void rcContext::doResetLog()
+{
+ // Defined out of line to fix the weak v-tables warning
+}
+
+rcHeightfield* rcAllocHeightfield()
+{
+ return rcNew(RC_ALLOC_PERM);
+}
+
+void rcFreeHeightField(rcHeightfield* heightfield)
+{
+ rcDelete(heightfield);
+}
+
+rcHeightfield::rcHeightfield()
+: width()
+, height()
+, bmin()
+, bmax()
+, cs()
+, ch()
+, spans()
+, pools()
+, freelist()
+{
+}
+
+rcHeightfield::~rcHeightfield()
+{
+ // Delete span array.
+ rcFree(spans);
+ // Delete span pools.
+ while (pools)
+ {
+ rcSpanPool* next = pools->next;
+ rcFree(pools);
+ pools = next;
+ }
+}
+
+rcCompactHeightfield* rcAllocCompactHeightfield()
+{
+ return rcNew(RC_ALLOC_PERM);
+}
+
+void rcFreeCompactHeightfield(rcCompactHeightfield* compactHeightfield)
+{
+ rcDelete(compactHeightfield);
+}
+
+rcCompactHeightfield::rcCompactHeightfield()
+: width()
+, height()
+, spanCount()
+, walkableHeight()
+, walkableClimb()
+, borderSize()
+, maxDistance()
+, maxRegions()
+, bmin()
+, bmax()
+, cs()
+, ch()
+, cells()
+, spans()
+, dist()
+, areas()
+{
+}
+
+rcCompactHeightfield::~rcCompactHeightfield()
+{
+ rcFree(cells);
+ rcFree(spans);
+ rcFree(dist);
+ rcFree(areas);
+}
+
+rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet()
+{
+ return rcNew(RC_ALLOC_PERM);
+}
+
+void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* layerSet)
+{
+ rcDelete(layerSet);
+}
+
+rcHeightfieldLayerSet::rcHeightfieldLayerSet()
+: layers()
+, nlayers()
+{
+}
+
+rcHeightfieldLayerSet::~rcHeightfieldLayerSet()
+{
+ for (int i = 0; i < nlayers; ++i)
+ {
+ rcFree(layers[i].heights);
+ rcFree(layers[i].areas);
+ rcFree(layers[i].cons);
+ }
+ rcFree(layers);
+}
+
+
+rcContourSet* rcAllocContourSet()
+{
+ return rcNew(RC_ALLOC_PERM);
+}
+
+void rcFreeContourSet(rcContourSet* contourSet)
+{
+ rcDelete(contourSet);
+}
+
+rcContourSet::rcContourSet()
+: conts()
+, nconts()
+, bmin()
+, bmax()
+, cs()
+, ch()
+, width()
+, height()
+, borderSize()
+, maxError()
+{
+}
+
+rcContourSet::~rcContourSet()
+{
+ for (int i = 0; i < nconts; ++i)
+ {
+ rcFree(conts[i].verts);
+ rcFree(conts[i].rverts);
+ }
+ rcFree(conts);
+}
+
+rcPolyMesh* rcAllocPolyMesh()
+{
+ return rcNew(RC_ALLOC_PERM);
+}
+
+void rcFreePolyMesh(rcPolyMesh* polyMesh)
+{
+ rcDelete(polyMesh);
+}
+
+rcPolyMesh::rcPolyMesh()
+: verts()
+, polys()
+, regs()
+, flags()
+, areas()
+, nverts()
+, npolys()
+, maxpolys()
+, nvp()
+, bmin()
+, bmax()
+, cs()
+, ch()
+, borderSize()
+, maxEdgeError()
+{
+}
+
+rcPolyMesh::~rcPolyMesh()
+{
+ rcFree(verts);
+ rcFree(polys);
+ rcFree(regs);
+ rcFree(flags);
+ rcFree(areas);
+}
+
+rcPolyMeshDetail* rcAllocPolyMeshDetail()
+{
+ return rcNew(RC_ALLOC_PERM);
+}
+
+void rcFreePolyMeshDetail(rcPolyMeshDetail* detailMesh)
+{
+ if (detailMesh == NULL)
+ {
+ return;
+ }
+ rcFree(detailMesh->meshes);
+ rcFree(detailMesh->verts);
+ rcFree(detailMesh->tris);
+ rcFree(detailMesh);
+}
+
+rcPolyMeshDetail::rcPolyMeshDetail()
+: meshes()
+, verts()
+, tris()
+, nmeshes()
+, nverts()
+, ntris()
+{
+}
+
+void rcCalcBounds(const float* verts, int numVerts, float* minBounds, float* maxBounds)
+{
+ // Calculate bounding box.
+ rcVcopy(minBounds, verts);
+ rcVcopy(maxBounds, verts);
+ for (int i = 1; i < numVerts; ++i)
+ {
+ const float* v = &verts[i * 3];
+ rcVmin(minBounds, v);
+ rcVmax(maxBounds, v);
+ }
+}
+
+void rcCalcGridSize(const float* minBounds, const float* maxBounds, const float cellSize, int* sizeX, int* sizeZ)
+{
+ *sizeX = (int)((maxBounds[0] - minBounds[0]) / cellSize + 0.5f);
+ *sizeZ = (int)((maxBounds[2] - minBounds[2]) / cellSize + 0.5f);
+}
+
+bool rcCreateHeightfield(rcContext* context, rcHeightfield& heightfield, int sizeX, int sizeZ,
+ const float* minBounds, const float* maxBounds,
+ float cellSize, float cellHeight)
+{
+ rcIgnoreUnused(context);
+
+ heightfield.width = sizeX;
+ heightfield.height = sizeZ;
+ rcVcopy(heightfield.bmin, minBounds);
+ rcVcopy(heightfield.bmax, maxBounds);
+ heightfield.cs = cellSize;
+ heightfield.ch = cellHeight;
+ heightfield.spans = (rcSpan**)rcAlloc(sizeof(rcSpan*) * heightfield.width * heightfield.height, RC_ALLOC_PERM);
+ if (!heightfield.spans)
+ {
+ return false;
+ }
+ memset(heightfield.spans, 0, sizeof(rcSpan*) * heightfield.width * heightfield.height);
+ return true;
+}
+
+static void calcTriNormal(const float* v0, const float* v1, const float* v2, float* faceNormal)
+{
+ float e0[3], e1[3];
+ rcVsub(e0, v1, v0);
+ rcVsub(e1, v2, v0);
+ rcVcross(faceNormal, e0, e1);
+ rcVnormalize(faceNormal);
+}
+
+void rcMarkWalkableTriangles(rcContext* context, const float walkableSlopeAngle,
+ const float* verts, const int numVerts,
+ const int* tris, const int numTris,
+ unsigned char* triAreaIDs)
+{
+ rcIgnoreUnused(context);
+ rcIgnoreUnused(numVerts);
+
+ const float walkableThr = cosf(walkableSlopeAngle / 180.0f * RC_PI);
+
+ float norm[3];
+
+ for (int i = 0; i < numTris; ++i)
+ {
+ const int* tri = &tris[i * 3];
+ calcTriNormal(&verts[tri[0] * 3], &verts[tri[1] * 3], &verts[tri[2] * 3], norm);
+ // Check if the face is walkable.
+ if (norm[1] > walkableThr)
+ {
+ triAreaIDs[i] = RC_WALKABLE_AREA;
+ }
+ }
+}
+
+void rcClearUnwalkableTriangles(rcContext* context, const float walkableSlopeAngle,
+ const float* verts, int numVerts,
+ const int* tris, int numTris,
+ unsigned char* triAreaIDs)
+{
+ rcIgnoreUnused(context);
+ rcIgnoreUnused(numVerts);
+
+ // The minimum Y value for a face normal of a triangle with a walkable slope.
+ const float walkableLimitY = cosf(walkableSlopeAngle / 180.0f * RC_PI);
+
+ float faceNormal[3];
+ for (int i = 0; i < numTris; ++i)
+ {
+ const int* tri = &tris[i * 3];
+ calcTriNormal(&verts[tri[0] * 3], &verts[tri[1] * 3], &verts[tri[2] * 3], faceNormal);
+ // Check if the face is walkable.
+ if (faceNormal[1] <= walkableLimitY)
+ {
+ triAreaIDs[i] = RC_NULL_AREA;
+ }
+ }
+}
+
+int rcGetHeightFieldSpanCount(rcContext* context, const rcHeightfield& heightfield)
+{
+ rcIgnoreUnused(context);
+
+ const int numCols = heightfield.width * heightfield.height;
+ int spanCount = 0;
+ for (int columnIndex = 0; columnIndex < numCols; ++columnIndex)
+ {
+ for (rcSpan* span = heightfield.spans[columnIndex]; span != NULL; span = span->next)
+ {
+ if (span->area != RC_NULL_AREA)
+ {
+ spanCount++;
+ }
+ }
+ }
+ return spanCount;
+}
+
+bool rcBuildCompactHeightfield(rcContext* context, const int walkableHeight, const int walkableClimb,
+ const rcHeightfield& heightfield, rcCompactHeightfield& compactHeightfield)
+{
+ rcAssert(context);
+
+ rcScopedTimer timer(context, RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
+
+ const int xSize = heightfield.width;
+ const int zSize = heightfield.height;
+ const int spanCount = rcGetHeightFieldSpanCount(context, heightfield);
+
+ // Fill in header.
+ compactHeightfield.width = xSize;
+ compactHeightfield.height = zSize;
+ compactHeightfield.spanCount = spanCount;
+ compactHeightfield.walkableHeight = walkableHeight;
+ compactHeightfield.walkableClimb = walkableClimb;
+ compactHeightfield.maxRegions = 0;
+ rcVcopy(compactHeightfield.bmin, heightfield.bmin);
+ rcVcopy(compactHeightfield.bmax, heightfield.bmax);
+ compactHeightfield.bmax[1] += walkableHeight * heightfield.ch;
+ compactHeightfield.cs = heightfield.cs;
+ compactHeightfield.ch = heightfield.ch;
+ compactHeightfield.cells = (rcCompactCell*)rcAlloc(sizeof(rcCompactCell) * xSize * zSize, RC_ALLOC_PERM);
+ if (!compactHeightfield.cells)
+ {
+ context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.cells' (%d)", xSize * zSize);
+ return false;
+ }
+ memset(compactHeightfield.cells, 0, sizeof(rcCompactCell) * xSize * zSize);
+ compactHeightfield.spans = (rcCompactSpan*)rcAlloc(sizeof(rcCompactSpan) * spanCount, RC_ALLOC_PERM);
+ if (!compactHeightfield.spans)
+ {
+ context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.spans' (%d)", spanCount);
+ return false;
+ }
+ memset(compactHeightfield.spans, 0, sizeof(rcCompactSpan) * spanCount);
+ compactHeightfield.areas = (unsigned char*)rcAlloc(sizeof(unsigned char) * spanCount, RC_ALLOC_PERM);
+ if (!compactHeightfield.areas)
+ {
+ context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.areas' (%d)", spanCount);
+ return false;
+ }
+ memset(compactHeightfield.areas, RC_NULL_AREA, sizeof(unsigned char) * spanCount);
+
+ const int MAX_HEIGHT = 0xffff;
+
+ // Fill in cells and spans.
+ int currentCellIndex = 0;
+ const int numColumns = xSize * zSize;
+ for (int columnIndex = 0; columnIndex < numColumns; ++columnIndex)
+ {
+ const rcSpan* span = heightfield.spans[columnIndex];
+
+ // If there are no spans at this cell, just leave the data to index=0, count=0.
+ if (span == NULL)
+ {
+ continue;
+ }
+
+ rcCompactCell& cell = compactHeightfield.cells[columnIndex];
+ cell.index = currentCellIndex;
+ cell.count = 0;
+
+ for (; span != NULL; span = span->next)
+ {
+ if (span->area != RC_NULL_AREA)
+ {
+ const int bot = (int)span->smax;
+ const int top = span->next ? (int)span->next->smin : MAX_HEIGHT;
+ compactHeightfield.spans[currentCellIndex].y = (unsigned short)rcClamp(bot, 0, 0xffff);
+ compactHeightfield.spans[currentCellIndex].h = (unsigned char)rcClamp(top - bot, 0, 0xff);
+ compactHeightfield.areas[currentCellIndex] = span->area;
+ currentCellIndex++;
+ cell.count++;
+ }
+ }
+ }
+
+ // Find neighbour connections.
+ const int MAX_LAYERS = RC_NOT_CONNECTED - 1;
+ int maxLayerIndex = 0;
+ const int zStride = xSize; // for readability
+ for (int z = 0; z < zSize; ++z)
+ {
+ for (int x = 0; x < xSize; ++x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ for (int i = (int)cell.index, ni = (int)(cell.index + cell.count); i < ni; ++i)
+ {
+ rcCompactSpan& span = compactHeightfield.spans[i];
+
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ rcSetCon(span, dir, RC_NOT_CONNECTED);
+ const int neighborX = x + rcGetDirOffsetX(dir);
+ const int neighborZ = z + rcGetDirOffsetY(dir);
+ // First check that the neighbour cell is in bounds.
+ if (neighborX < 0 || neighborZ < 0 || neighborX >= xSize || neighborZ >= zSize)
+ {
+ continue;
+ }
+
+ // Iterate over all neighbour spans and check if any of the is
+ // accessible from current cell.
+ const rcCompactCell& neighborCell = compactHeightfield.cells[neighborX + neighborZ * zStride];
+ for (int k = (int)neighborCell.index, nk = (int)(neighborCell.index + neighborCell.count); k < nk; ++k)
+ {
+ const rcCompactSpan& neighborSpan = compactHeightfield.spans[k];
+ const int bot = rcMax(span.y, neighborSpan.y);
+ const int top = rcMin(span.y + span.h, neighborSpan.y + neighborSpan.h);
+
+ // Check that the gap between the spans is walkable,
+ // and that the climb height between the gaps is not too high.
+ if ((top - bot) >= walkableHeight && rcAbs((int)neighborSpan.y - (int)span.y) <= walkableClimb)
+ {
+ // Mark direction as walkable.
+ const int layerIndex = k - (int)neighborCell.index;
+ if (layerIndex < 0 || layerIndex > MAX_LAYERS)
+ {
+ maxLayerIndex = rcMax(maxLayerIndex, layerIndex);
+ continue;
+ }
+ rcSetCon(span, dir, layerIndex);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (maxLayerIndex > MAX_LAYERS)
+ {
+ context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)",
+ maxLayerIndex, MAX_LAYERS);
+ }
+
+ return true;
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastAlloc.cpp b/native/third_party/recastnavigation/Recast/Source/RecastAlloc.cpp
new file mode 100644
index 0000000..e919daf
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastAlloc.cpp
@@ -0,0 +1,51 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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 "RecastAlloc.h"
+
+static void* rcAllocDefault(size_t size, rcAllocHint)
+{
+ return malloc(size);
+}
+
+static void rcFreeDefault(void *ptr)
+{
+ free(ptr);
+}
+
+static rcAllocFunc* sRecastAllocFunc = rcAllocDefault;
+static rcFreeFunc* sRecastFreeFunc = rcFreeDefault;
+
+void rcAllocSetCustom(rcAllocFunc* allocFunc, rcFreeFunc* freeFunc)
+{
+ sRecastAllocFunc = allocFunc ? allocFunc : rcAllocDefault;
+ sRecastFreeFunc = freeFunc ? freeFunc : rcFreeDefault;
+}
+
+void* rcAlloc(size_t size, rcAllocHint hint)
+{
+ return sRecastAllocFunc(size, hint);
+}
+
+void rcFree(void* ptr)
+{
+ if (ptr != NULL)
+ {
+ sRecastFreeFunc(ptr);
+ }
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastArea.cpp b/native/third_party/recastnavigation/Recast/Source/RecastArea.cpp
new file mode 100644
index 0000000..7a7091c
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastArea.cpp
@@ -0,0 +1,717 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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 "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+#include // for memcpy and memset
+
+/// Sorts the given data in-place using insertion sort.
+///
+/// @param data The data to sort
+/// @param dataLength The number of elements in @p data
+static void insertSort(unsigned char* data, const int dataLength)
+{
+ for (int valueIndex = 1; valueIndex < dataLength; valueIndex++)
+ {
+ const unsigned char value = data[valueIndex];
+ int insertionIndex;
+ for (insertionIndex = valueIndex - 1; insertionIndex >= 0 && data[insertionIndex] > value; insertionIndex--)
+ {
+ // Shift over values
+ data[insertionIndex + 1] = data[insertionIndex];
+ }
+
+ // Insert the value in sorted order.
+ data[insertionIndex + 1] = value;
+ }
+}
+
+// TODO (graham): This is duplicated in the ConvexVolumeTool in RecastDemo
+/// Checks if a point is contained within a polygon
+///
+/// @param[in] numVerts Number of vertices in the polygon
+/// @param[in] verts The polygon vertices
+/// @param[in] point The point to check
+/// @returns true if the point lies within the polygon, false otherwise.
+static bool pointInPoly(int numVerts, const float* verts, const float* point)
+{
+ bool inPoly = false;
+ for (int i = 0, j = numVerts - 1; i < numVerts; j = i++)
+ {
+ const float* vi = &verts[i * 3];
+ const float* vj = &verts[j * 3];
+
+ if ((vi[2] > point[2]) == (vj[2] > point[2]))
+ {
+ continue;
+ }
+
+ if (point[0] >= (vj[0] - vi[0]) * (point[2] - vi[2]) / (vj[2] - vi[2]) + vi[0])
+ {
+ continue;
+ }
+ inPoly = !inPoly;
+ }
+ return inPoly;
+}
+
+bool rcErodeWalkableArea(rcContext* context, const int erosionRadius, rcCompactHeightfield& compactHeightfield)
+{
+ rcAssert(context != NULL);
+
+ const int xSize = compactHeightfield.width;
+ const int zSize = compactHeightfield.height;
+ const int& zStride = xSize; // For readability
+
+ rcScopedTimer timer(context, RC_TIMER_ERODE_AREA);
+
+ unsigned char* distanceToBoundary = (unsigned char*)rcAlloc(sizeof(unsigned char) * compactHeightfield.spanCount,
+ RC_ALLOC_TEMP);
+ if (!distanceToBoundary)
+ {
+ context->log(RC_LOG_ERROR, "erodeWalkableArea: Out of memory 'dist' (%d).", compactHeightfield.spanCount);
+ return false;
+ }
+ memset(distanceToBoundary, 0xff, sizeof(unsigned char) * compactHeightfield.spanCount);
+
+ // Mark boundary cells.
+ for (int z = 0; z < zSize; ++z)
+ {
+ for (int x = 0; x < xSize; ++x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ for (int spanIndex = (int)cell.index, maxSpanIndex = (int)(cell.index + cell.count); spanIndex < maxSpanIndex; ++spanIndex)
+ {
+ if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
+ {
+ distanceToBoundary[spanIndex] = 0;
+ continue;
+ }
+ const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
+
+ // Check that there is a non-null adjacent span in each of the 4 cardinal directions.
+ int neighborCount = 0;
+ for (int direction = 0; direction < 4; ++direction)
+ {
+ const int neighborConnection = rcGetCon(span, direction);
+ if (neighborConnection == RC_NOT_CONNECTED)
+ {
+ break;
+ }
+
+ const int neighborX = x + rcGetDirOffsetX(direction);
+ const int neighborZ = z + rcGetDirOffsetY(direction);
+ const int neighborSpanIndex = (int)compactHeightfield.cells[neighborX + neighborZ * zStride].index + neighborConnection;
+
+ if (compactHeightfield.areas[neighborSpanIndex] == RC_NULL_AREA)
+ {
+ break;
+ }
+ neighborCount++;
+ }
+
+ // At least one missing neighbour, so this is a boundary cell.
+ if (neighborCount != 4)
+ {
+ distanceToBoundary[spanIndex] = 0;
+ }
+ }
+ }
+ }
+
+ unsigned char newDistance;
+
+ // Pass 1
+ for (int z = 0; z < zSize; ++z)
+ {
+ for (int x = 0; x < xSize; ++x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ const int maxSpanIndex = (int)(cell.index + cell.count);
+ for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
+ {
+ const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
+
+ if (rcGetCon(span, 0) != RC_NOT_CONNECTED)
+ {
+ // (-1,0)
+ const int aX = x + rcGetDirOffsetX(0);
+ const int aY = z + rcGetDirOffsetY(0);
+ const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 0);
+ const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+
+ // (-1,-1)
+ if (rcGetCon(aSpan, 3) != RC_NOT_CONNECTED)
+ {
+ const int bX = aX + rcGetDirOffsetX(3);
+ const int bY = aY + rcGetDirOffsetY(3);
+ const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 3);
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+ }
+ }
+ if (rcGetCon(span, 3) != RC_NOT_CONNECTED)
+ {
+ // (0,-1)
+ const int aX = x + rcGetDirOffsetX(3);
+ const int aY = z + rcGetDirOffsetY(3);
+ const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 3);
+ const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+
+ // (1,-1)
+ if (rcGetCon(aSpan, 2) != RC_NOT_CONNECTED)
+ {
+ const int bX = aX + rcGetDirOffsetX(2);
+ const int bY = aY + rcGetDirOffsetY(2);
+ const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 2);
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Pass 2
+ for (int z = zSize - 1; z >= 0; --z)
+ {
+ for (int x = xSize - 1; x >= 0; --x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ const int maxSpanIndex = (int)(cell.index + cell.count);
+ for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
+ {
+ const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
+
+ if (rcGetCon(span, 2) != RC_NOT_CONNECTED)
+ {
+ // (1,0)
+ const int aX = x + rcGetDirOffsetX(2);
+ const int aY = z + rcGetDirOffsetY(2);
+ const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 2);
+ const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+
+ // (1,1)
+ if (rcGetCon(aSpan, 1) != RC_NOT_CONNECTED)
+ {
+ const int bX = aX + rcGetDirOffsetX(1);
+ const int bY = aY + rcGetDirOffsetY(1);
+ const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 1);
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+ }
+ }
+ if (rcGetCon(span, 1) != RC_NOT_CONNECTED)
+ {
+ // (0,1)
+ const int aX = x + rcGetDirOffsetX(1);
+ const int aY = z + rcGetDirOffsetY(1);
+ const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 1);
+ const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+
+ // (-1,1)
+ if (rcGetCon(aSpan, 0) != RC_NOT_CONNECTED)
+ {
+ const int bX = aX + rcGetDirOffsetX(0);
+ const int bY = aY + rcGetDirOffsetY(0);
+ const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 0);
+ newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
+ if (newDistance < distanceToBoundary[spanIndex])
+ {
+ distanceToBoundary[spanIndex] = newDistance;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ const unsigned char minBoundaryDistance = (unsigned char)(erosionRadius * 2);
+ for (int spanIndex = 0; spanIndex < compactHeightfield.spanCount; ++spanIndex)
+ {
+ if (distanceToBoundary[spanIndex] < minBoundaryDistance)
+ {
+ compactHeightfield.areas[spanIndex] = RC_NULL_AREA;
+ }
+ }
+
+ rcFree(distanceToBoundary);
+
+ return true;
+}
+
+bool rcMedianFilterWalkableArea(rcContext* context, rcCompactHeightfield& compactHeightfield)
+{
+ rcAssert(context);
+
+ const int xSize = compactHeightfield.width;
+ const int zSize = compactHeightfield.height;
+ const int zStride = xSize; // For readability
+
+ rcScopedTimer timer(context, RC_TIMER_MEDIAN_AREA);
+
+ unsigned char* areas = (unsigned char*)rcAlloc(sizeof(unsigned char) * compactHeightfield.spanCount, RC_ALLOC_TEMP);
+ if (!areas)
+ {
+ context->log(RC_LOG_ERROR, "medianFilterWalkableArea: Out of memory 'areas' (%d).",
+ compactHeightfield.spanCount);
+ return false;
+ }
+ memset(areas, 0xff, sizeof(unsigned char) * compactHeightfield.spanCount);
+
+ for (int z = 0; z < zSize; ++z)
+ {
+ for (int x = 0; x < xSize; ++x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ const int maxSpanIndex = (int)(cell.index + cell.count);
+ for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
+ {
+ const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
+ if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
+ {
+ areas[spanIndex] = compactHeightfield.areas[spanIndex];
+ continue;
+ }
+
+ unsigned char neighborAreas[9];
+ for (int neighborIndex = 0; neighborIndex < 9; ++neighborIndex)
+ {
+ neighborAreas[neighborIndex] = compactHeightfield.areas[spanIndex];
+ }
+
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(span, dir) == RC_NOT_CONNECTED)
+ {
+ continue;
+ }
+
+ const int aX = x + rcGetDirOffsetX(dir);
+ const int aZ = z + rcGetDirOffsetY(dir);
+ const int aIndex = (int)compactHeightfield.cells[aX + aZ * zStride].index + rcGetCon(span, dir);
+ if (compactHeightfield.areas[aIndex] != RC_NULL_AREA)
+ {
+ neighborAreas[dir * 2 + 0] = compactHeightfield.areas[aIndex];
+ }
+
+ const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
+ const int dir2 = (dir + 1) & 0x3;
+ const int neighborConnection2 = rcGetCon(aSpan, dir2);
+ if (neighborConnection2 != RC_NOT_CONNECTED)
+ {
+ const int bX = aX + rcGetDirOffsetX(dir2);
+ const int bZ = aZ + rcGetDirOffsetY(dir2);
+ const int bIndex = (int)compactHeightfield.cells[bX + bZ * zStride].index + neighborConnection2;
+ if (compactHeightfield.areas[bIndex] != RC_NULL_AREA)
+ {
+ neighborAreas[dir * 2 + 1] = compactHeightfield.areas[bIndex];
+ }
+ }
+ }
+ insertSort(neighborAreas, 9);
+ areas[spanIndex] = neighborAreas[4];
+ }
+ }
+ }
+
+ memcpy(compactHeightfield.areas, areas, sizeof(unsigned char) * compactHeightfield.spanCount);
+
+ rcFree(areas);
+
+ return true;
+}
+
+void rcMarkBoxArea(rcContext* context, const float* boxMinBounds, const float* boxMaxBounds, unsigned char areaId,
+ rcCompactHeightfield& compactHeightfield)
+{
+ rcAssert(context);
+
+ rcScopedTimer timer(context, RC_TIMER_MARK_BOX_AREA);
+
+ const int xSize = compactHeightfield.width;
+ const int zSize = compactHeightfield.height;
+ const int zStride = xSize; // For readability
+
+ // Find the footprint of the box area in grid cell coordinates.
+ int minX = (int)((boxMinBounds[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
+ int minY = (int)((boxMinBounds[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
+ int minZ = (int)((boxMinBounds[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
+ int maxX = (int)((boxMaxBounds[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
+ int maxY = (int)((boxMaxBounds[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
+ int maxZ = (int)((boxMaxBounds[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
+
+ // Early-out if the box is outside the bounds of the grid.
+ if (maxX < 0) { return; }
+ if (minX >= xSize) { return; }
+ if (maxZ < 0) { return; }
+ if (minZ >= zSize) { return; }
+
+ // Clamp relevant bound coordinates to the grid.
+ if (minX < 0) { minX = 0; }
+ if (maxX >= xSize) { maxX = xSize - 1; }
+ if (minZ < 0) { minZ = 0; }
+ if (maxZ >= zSize) { maxZ = zSize - 1; }
+
+ // Mark relevant cells.
+ for (int z = minZ; z <= maxZ; ++z)
+ {
+ for (int x = minX; x <= maxX; ++x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ const int maxSpanIndex = (int)(cell.index + cell.count);
+ for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
+ {
+ rcCompactSpan& span = compactHeightfield.spans[spanIndex];
+
+ // Skip if the span is outside the box extents.
+ if ((int)span.y < minY || (int)span.y > maxY)
+ {
+ continue;
+ }
+
+ // Skip if the span has been removed.
+ if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
+ {
+ continue;
+ }
+
+ // Mark the span.
+ compactHeightfield.areas[spanIndex] = areaId;
+ }
+ }
+ }
+}
+
+void rcMarkConvexPolyArea(rcContext* context, const float* verts, const int numVerts,
+ const float minY, const float maxY, unsigned char areaId,
+ rcCompactHeightfield& compactHeightfield)
+{
+ rcAssert(context);
+
+ rcScopedTimer timer(context, RC_TIMER_MARK_CONVEXPOLY_AREA);
+
+ const int xSize = compactHeightfield.width;
+ const int zSize = compactHeightfield.height;
+ const int zStride = xSize; // For readability
+
+ // Compute the bounding box of the polygon
+ float bmin[3];
+ float bmax[3];
+ rcVcopy(bmin, verts);
+ rcVcopy(bmax, verts);
+ for (int i = 1; i < numVerts; ++i)
+ {
+ rcVmin(bmin, &verts[i * 3]);
+ rcVmax(bmax, &verts[i * 3]);
+ }
+ bmin[1] = minY;
+ bmax[1] = maxY;
+
+ // Compute the grid footprint of the polygon
+ int minx = (int)((bmin[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
+ int miny = (int)((bmin[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
+ int minz = (int)((bmin[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
+ int maxx = (int)((bmax[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
+ int maxy = (int)((bmax[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
+ int maxz = (int)((bmax[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
+
+ // Early-out if the polygon lies entirely outside the grid.
+ if (maxx < 0) { return; }
+ if (minx >= xSize) { return; }
+ if (maxz < 0) { return; }
+ if (minz >= zSize) { return; }
+
+ // Clamp the polygon footprint to the grid
+ if (minx < 0) { minx = 0; }
+ if (maxx >= xSize) { maxx = xSize - 1; }
+ if (minz < 0) { minz = 0; }
+ if (maxz >= zSize) { maxz = zSize - 1; }
+
+ // TODO: Optimize.
+ for (int z = minz; z <= maxz; ++z)
+ {
+ for (int x = minx; x <= maxx; ++x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ const int maxSpanIndex = (int)(cell.index + cell.count);
+ for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
+ {
+ rcCompactSpan& span = compactHeightfield.spans[spanIndex];
+
+ // Skip if span is removed.
+ if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
+ {
+ continue;
+ }
+
+ // Skip if y extents don't overlap.
+ if ((int)span.y < miny || (int)span.y > maxy)
+ {
+ continue;
+ }
+
+ const float point[] = {
+ compactHeightfield.bmin[0] + ((float)x + 0.5f) * compactHeightfield.cs,
+ 0,
+ compactHeightfield.bmin[2] + ((float)z + 0.5f) * compactHeightfield.cs
+ };
+
+ if (pointInPoly(numVerts, verts, point))
+ {
+ compactHeightfield.areas[spanIndex] = areaId;
+ }
+ }
+ }
+ }
+}
+
+static const float EPSILON = 1e-6f;
+
+/// Normalizes the vector if the length is greater than zero.
+/// If the magnitude is zero, the vector is unchanged.
+/// @param[in,out] v The vector to normalize. [(x, y, z)]
+static void rcVsafeNormalize(float* v)
+{
+ const float sqMag = rcSqr(v[0]) + rcSqr(v[1]) + rcSqr(v[2]);
+ if (sqMag > EPSILON)
+ {
+ const float inverseMag = 1.0f / rcSqrt(sqMag);
+ v[0] *= inverseMag;
+ v[1] *= inverseMag;
+ v[2] *= inverseMag;
+ }
+}
+
+int rcOffsetPoly(const float* verts, const int numVerts, const float offset, float* outVerts, const int maxOutVerts)
+{
+ // Defines the limit at which a miter becomes a bevel.
+ // Similar in behavior to https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit
+ const float MITER_LIMIT = 1.20f;
+
+ int numOutVerts = 0;
+
+ for (int vertIndex = 0; vertIndex < numVerts; vertIndex++)
+ {
+ // Grab three vertices of the polygon.
+ const int vertIndexA = (vertIndex + numVerts - 1) % numVerts;
+ const int vertIndexB = vertIndex;
+ const int vertIndexC = (vertIndex + 1) % numVerts;
+ const float* vertA = &verts[vertIndexA * 3];
+ const float* vertB = &verts[vertIndexB * 3];
+ const float* vertC = &verts[vertIndexC * 3];
+
+ // From A to B on the x/z plane
+ float prevSegmentDir[3];
+ rcVsub(prevSegmentDir, vertB, vertA);
+ prevSegmentDir[1] = 0; // Squash onto x/z plane
+ rcVsafeNormalize(prevSegmentDir);
+
+ // From B to C on the x/z plane
+ float currSegmentDir[3];
+ rcVsub(currSegmentDir, vertC, vertB);
+ currSegmentDir[1] = 0; // Squash onto x/z plane
+ rcVsafeNormalize(currSegmentDir);
+
+ // The y component of the cross product of the two normalized segment directions.
+ // The X and Z components of the cross product are both zero because the two
+ // segment direction vectors fall within the x/z plane.
+ float cross = currSegmentDir[0] * prevSegmentDir[2] - prevSegmentDir[0] * currSegmentDir[2];
+
+ // CCW perpendicular vector to AB. The segment normal.
+ const float prevSegmentNormX = -prevSegmentDir[2];
+ const float prevSegmentNormZ = prevSegmentDir[0];
+
+ // CCW perpendicular vector to BC. The segment normal.
+ const float currSegmentNormX = -currSegmentDir[2];
+ const float currSegmentNormZ = currSegmentDir[0];
+
+ // Average the two segment normals to get the proportional miter offset for B.
+ // This isn't normalized because it's defining the distance and direction the corner will need to be
+ // adjusted proportionally to the edge offsets to properly miter the adjoining edges.
+ float cornerMiterX = (prevSegmentNormX + currSegmentNormX) * 0.5f;
+ float cornerMiterZ = (prevSegmentNormZ + currSegmentNormZ) * 0.5f;
+ const float cornerMiterSqMag = rcSqr(cornerMiterX) + rcSqr(cornerMiterZ);
+
+ // If the magnitude of the segment normal average is less than about .69444,
+ // the corner is an acute enough angle that the result should be beveled.
+ const bool bevel = cornerMiterSqMag * MITER_LIMIT * MITER_LIMIT < 1.0f;
+
+ // Scale the corner miter so it's proportional to how much the corner should be offset compared to the edges.
+ if (cornerMiterSqMag > EPSILON)
+ {
+ const float scale = 1.0f / cornerMiterSqMag;
+ cornerMiterX *= scale;
+ cornerMiterZ *= scale;
+ }
+
+ if (bevel && cross < 0.0f) // If the corner is convex and an acute enough angle, generate a bevel.
+ {
+ if (numOutVerts + 2 > maxOutVerts)
+ {
+ return 0;
+ }
+
+ // Generate two bevel vertices at a distances from B proportional to the angle between the two segments.
+ // Move each bevel vertex out proportional to the given offset.
+ float d = (1.0f - (prevSegmentDir[0] * currSegmentDir[0] + prevSegmentDir[2] * currSegmentDir[2])) * 0.5f;
+
+ outVerts[numOutVerts * 3 + 0] = vertB[0] + (-prevSegmentNormX + prevSegmentDir[0] * d) * offset;
+ outVerts[numOutVerts * 3 + 1] = vertB[1];
+ outVerts[numOutVerts * 3 + 2] = vertB[2] + (-prevSegmentNormZ + prevSegmentDir[2] * d) * offset;
+ numOutVerts++;
+
+ outVerts[numOutVerts * 3 + 0] = vertB[0] + (-currSegmentNormX - currSegmentDir[0] * d) * offset;
+ outVerts[numOutVerts * 3 + 1] = vertB[1];
+ outVerts[numOutVerts * 3 + 2] = vertB[2] + (-currSegmentNormZ - currSegmentDir[2] * d) * offset;
+ numOutVerts++;
+ }
+ else
+ {
+ if (numOutVerts + 1 > maxOutVerts)
+ {
+ return 0;
+ }
+
+ // Move B along the miter direction by the specified offset.
+ outVerts[numOutVerts * 3 + 0] = vertB[0] - cornerMiterX * offset;
+ outVerts[numOutVerts * 3 + 1] = vertB[1];
+ outVerts[numOutVerts * 3 + 2] = vertB[2] - cornerMiterZ * offset;
+ numOutVerts++;
+ }
+ }
+
+ return numOutVerts;
+}
+
+void rcMarkCylinderArea(rcContext* context, const float* position, const float radius, const float height,
+ unsigned char areaId, rcCompactHeightfield& compactHeightfield)
+{
+ rcAssert(context);
+
+ rcScopedTimer timer(context, RC_TIMER_MARK_CYLINDER_AREA);
+
+ const int xSize = compactHeightfield.width;
+ const int zSize = compactHeightfield.height;
+ const int zStride = xSize; // For readability
+
+ // Compute the bounding box of the cylinder
+ const float cylinderBBMin[] =
+ {
+ position[0] - radius,
+ position[1],
+ position[2] - radius
+ };
+ const float cylinderBBMax[] =
+ {
+ position[0] + radius,
+ position[1] + height,
+ position[2] + radius
+ };
+
+ // Compute the grid footprint of the cylinder
+ int minx = (int)((cylinderBBMin[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
+ int miny = (int)((cylinderBBMin[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
+ int minz = (int)((cylinderBBMin[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
+ int maxx = (int)((cylinderBBMax[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
+ int maxy = (int)((cylinderBBMax[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
+ int maxz = (int)((cylinderBBMax[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
+
+ // Early-out if the cylinder is completely outside the grid bounds.
+ if (maxx < 0) { return; }
+ if (minx >= xSize) { return; }
+ if (maxz < 0) { return; }
+ if (minz >= zSize) { return; }
+
+ // Clamp the cylinder bounds to the grid.
+ if (minx < 0) { minx = 0; }
+ if (maxx >= xSize) { maxx = xSize - 1; }
+ if (minz < 0) { minz = 0; }
+ if (maxz >= zSize) { maxz = zSize - 1; }
+
+ const float radiusSq = radius * radius;
+
+ for (int z = minz; z <= maxz; ++z)
+ {
+ for (int x = minx; x <= maxx; ++x)
+ {
+ const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
+ const int maxSpanIndex = (int)(cell.index + cell.count);
+
+ const float cellX = compactHeightfield.bmin[0] + ((float)x + 0.5f) * compactHeightfield.cs;
+ const float cellZ = compactHeightfield.bmin[2] + ((float)z + 0.5f) * compactHeightfield.cs;
+ const float deltaX = cellX - position[0];
+ const float deltaZ = cellZ - position[2];
+
+ // Skip this column if it's too far from the center point of the cylinder.
+ if (rcSqr(deltaX) + rcSqr(deltaZ) >= radiusSq)
+ {
+ continue;
+ }
+
+ // Mark all overlapping spans
+ for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
+ {
+ rcCompactSpan& span = compactHeightfield.spans[spanIndex];
+
+ // Skip if span is removed.
+ if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
+ {
+ continue;
+ }
+
+ // Mark if y extents overlap.
+ if ((int)span.y >= miny && (int)span.y <= maxy)
+ {
+ compactHeightfield.areas[spanIndex] = areaId;
+ }
+ }
+ }
+ }
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastAssert.cpp b/native/third_party/recastnavigation/Recast/Source/RecastAssert.cpp
new file mode 100644
index 0000000..08a05a6
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastAssert.cpp
@@ -0,0 +1,31 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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 "RecastAssert.h"
+
+static rcAssertFailFunc* sRecastAssertFailFunc = 0;
+
+void rcAssertFailSetCustom(rcAssertFailFunc* assertFailFunc)
+{
+ sRecastAssertFailFunc = assertFailFunc;
+}
+
+rcAssertFailFunc* rcAssertFailGetCustom()
+{
+ return sRecastAssertFailFunc;
+}
\ No newline at end of file
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastContour.cpp b/native/third_party/recastnavigation/Recast/Source/RecastContour.cpp
new file mode 100644
index 0000000..ce50c78
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastContour.cpp
@@ -0,0 +1,1095 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include
+#include
+#include "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+
+static int getCornerHeight(int x, int y, int i, int dir,
+ const rcCompactHeightfield& chf,
+ bool& isBorderVertex)
+{
+ const rcCompactSpan& s = chf.spans[i];
+ int ch = (int)s.y;
+ int dirp = (dir+1) & 0x3;
+
+ unsigned int regs[4] = {0,0,0,0};
+
+ // Combine region and area codes in order to prevent
+ // border vertices which are in between two areas to be removed.
+ regs[0] = chf.spans[i].reg | (chf.areas[i] << 16);
+
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dir);
+ const int ay = y + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
+ const rcCompactSpan& as = chf.spans[ai];
+ ch = rcMax(ch, (int)as.y);
+ regs[1] = chf.spans[ai].reg | (chf.areas[ai] << 16);
+ if (rcGetCon(as, dirp) != RC_NOT_CONNECTED)
+ {
+ const int ax2 = ax + rcGetDirOffsetX(dirp);
+ const int ay2 = ay + rcGetDirOffsetY(dirp);
+ const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dirp);
+ const rcCompactSpan& as2 = chf.spans[ai2];
+ ch = rcMax(ch, (int)as2.y);
+ regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
+ }
+ }
+ if (rcGetCon(s, dirp) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dirp);
+ const int ay = y + rcGetDirOffsetY(dirp);
+ const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dirp);
+ const rcCompactSpan& as = chf.spans[ai];
+ ch = rcMax(ch, (int)as.y);
+ regs[3] = chf.spans[ai].reg | (chf.areas[ai] << 16);
+ if (rcGetCon(as, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax2 = ax + rcGetDirOffsetX(dir);
+ const int ay2 = ay + rcGetDirOffsetY(dir);
+ const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dir);
+ const rcCompactSpan& as2 = chf.spans[ai2];
+ ch = rcMax(ch, (int)as2.y);
+ regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
+ }
+ }
+
+ // Check if the vertex is special edge vertex, these vertices will be removed later.
+ for (int j = 0; j < 4; ++j)
+ {
+ const int a = j;
+ const int b = (j+1) & 0x3;
+ const int c = (j+2) & 0x3;
+ const int d = (j+3) & 0x3;
+
+ // The vertex is a border vertex there are two same exterior cells in a row,
+ // followed by two interior cells and none of the regions are out of bounds.
+ const bool twoSameExts = (regs[a] & regs[b] & RC_BORDER_REG) != 0 && regs[a] == regs[b];
+ const bool twoInts = ((regs[c] | regs[d]) & RC_BORDER_REG) == 0;
+ const bool intsSameArea = (regs[c]>>16) == (regs[d]>>16);
+ const bool noZeros = regs[a] != 0 && regs[b] != 0 && regs[c] != 0 && regs[d] != 0;
+ if (twoSameExts && twoInts && intsSameArea && noZeros)
+ {
+ isBorderVertex = true;
+ break;
+ }
+ }
+
+ return ch;
+}
+
+static void walkContour(int x, int y, int i,
+ const rcCompactHeightfield& chf,
+ unsigned char* flags, rcTempVector& points)
+{
+ // Choose the first non-connected edge
+ unsigned char dir = 0;
+ while ((flags[i] & (1 << dir)) == 0)
+ dir++;
+
+ unsigned char startDir = dir;
+ int starti = i;
+
+ const unsigned char area = chf.areas[i];
+
+ int iter = 0;
+ while (++iter < 40000)
+ {
+ if (flags[i] & (1 << dir))
+ {
+ // Choose the edge corner
+ bool isBorderVertex = false;
+ bool isAreaBorder = false;
+ int px = x;
+ int py = getCornerHeight(x, y, i, dir, chf, isBorderVertex);
+ int pz = y;
+ switch(dir)
+ {
+ case 0: pz++; break;
+ case 1: px++; pz++; break;
+ case 2: px++; break;
+ }
+ int r = 0;
+ const rcCompactSpan& s = chf.spans[i];
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dir);
+ const int ay = y + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
+ r = (int)chf.spans[ai].reg;
+ if (area != chf.areas[ai])
+ isAreaBorder = true;
+ }
+ if (isBorderVertex)
+ r |= RC_BORDER_VERTEX;
+ if (isAreaBorder)
+ r |= RC_AREA_BORDER;
+ points.push_back(px);
+ points.push_back(py);
+ points.push_back(pz);
+ points.push_back(r);
+
+ flags[i] &= ~(1 << dir); // Remove visited edges
+ dir = (dir+1) & 0x3; // Rotate CW
+ }
+ else
+ {
+ int ni = -1;
+ const int nx = x + rcGetDirOffsetX(dir);
+ const int ny = y + rcGetDirOffsetY(dir);
+ const rcCompactSpan& s = chf.spans[i];
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const rcCompactCell& nc = chf.cells[nx+ny*chf.width];
+ ni = (int)nc.index + rcGetCon(s, dir);
+ }
+ if (ni == -1)
+ {
+ // Should not happen.
+ return;
+ }
+ x = nx;
+ y = ny;
+ i = ni;
+ dir = (dir+3) & 0x3; // Rotate CCW
+ }
+
+ if (starti == i && startDir == dir)
+ {
+ break;
+ }
+ }
+}
+
+static float distancePtSeg(const int x, const int z,
+ const int px, const int pz,
+ const int qx, const int qz)
+{
+ float pqx = (float)(qx - px);
+ float pqz = (float)(qz - pz);
+ float dx = (float)(x - px);
+ float dz = (float)(z - pz);
+ float d = pqx*pqx + pqz*pqz;
+ float t = pqx*dx + pqz*dz;
+ if (d > 0)
+ t /= d;
+ if (t < 0)
+ t = 0;
+ else if (t > 1)
+ t = 1;
+
+ dx = px + t*pqx - x;
+ dz = pz + t*pqz - z;
+
+ return dx*dx + dz*dz;
+}
+
+static void simplifyContour(rcTempVector& points, rcTempVector& simplified,
+ const float maxError, const int maxEdgeLen, const int buildFlags)
+{
+ // Add initial points.
+ bool hasConnections = false;
+ for (int i = 0; i < points.size(); i += 4)
+ {
+ if ((points[i+3] & RC_CONTOUR_REG_MASK) != 0)
+ {
+ hasConnections = true;
+ break;
+ }
+ }
+
+ if (hasConnections)
+ {
+ // The contour has some portals to other regions.
+ // Add a new point to every location where the region changes.
+ for (int i = 0, ni = static_cast(points.size()) / 4; i < ni; ++i)
+ {
+ int ii = (i+1) % ni;
+ const bool differentRegs = (points[i*4+3] & RC_CONTOUR_REG_MASK) != (points[ii*4+3] & RC_CONTOUR_REG_MASK);
+ const bool areaBorders = (points[i*4+3] & RC_AREA_BORDER) != (points[ii*4+3] & RC_AREA_BORDER);
+ if (differentRegs || areaBorders)
+ {
+ simplified.push_back(points[i*4+0]);
+ simplified.push_back(points[i*4+1]);
+ simplified.push_back(points[i*4+2]);
+ simplified.push_back(i);
+ }
+ }
+ }
+
+ if (simplified.size() == 0)
+ {
+ // If there is no connections at all,
+ // create some initial points for the simplification process.
+ // Find lower-left and upper-right vertices of the contour.
+ int llx = points[0];
+ int lly = points[1];
+ int llz = points[2];
+ int lli = 0;
+ int urx = points[0];
+ int ury = points[1];
+ int urz = points[2];
+ int uri = 0;
+ for (int i = 0; i < points.size(); i += 4)
+ {
+ int x = points[i+0];
+ int y = points[i+1];
+ int z = points[i+2];
+ if (x < llx || (x == llx && z < llz))
+ {
+ llx = x;
+ lly = y;
+ llz = z;
+ lli = i/4;
+ }
+ if (x > urx || (x == urx && z > urz))
+ {
+ urx = x;
+ ury = y;
+ urz = z;
+ uri = i/4;
+ }
+ }
+ simplified.push_back(llx);
+ simplified.push_back(lly);
+ simplified.push_back(llz);
+ simplified.push_back(lli);
+
+ simplified.push_back(urx);
+ simplified.push_back(ury);
+ simplified.push_back(urz);
+ simplified.push_back(uri);
+ }
+
+ // Add points until all raw points are within
+ // error tolerance to the simplified shape.
+ const int pn = static_cast(points.size()) / 4;
+ for (int i = 0; i < simplified.size()/4; )
+ {
+ int ii = (i+1) % (simplified.size()/4);
+
+ int ax = simplified[i*4+0];
+ int az = simplified[i*4+2];
+ int ai = simplified[i*4+3];
+
+ int bx = simplified[ii*4+0];
+ int bz = simplified[ii*4+2];
+ int bi = simplified[ii*4+3];
+
+ // Find maximum deviation from the segment.
+ float maxd = 0;
+ int maxi = -1;
+ int ci, cinc, endi;
+
+ // Traverse the segment in lexilogical order so that the
+ // max deviation is calculated similarly when traversing
+ // opposite segments.
+ if (bx > ax || (bx == ax && bz > az))
+ {
+ cinc = 1;
+ ci = (ai+cinc) % pn;
+ endi = bi;
+ }
+ else
+ {
+ cinc = pn-1;
+ ci = (bi+cinc) % pn;
+ endi = ai;
+ rcSwap(ax, bx);
+ rcSwap(az, bz);
+ }
+
+ // Tessellate only outer edges or edges between areas.
+ if ((points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0 ||
+ (points[ci*4+3] & RC_AREA_BORDER))
+ {
+ while (ci != endi)
+ {
+ float d = distancePtSeg(points[ci*4+0], points[ci*4+2], ax, az, bx, bz);
+ if (d > maxd)
+ {
+ maxd = d;
+ maxi = ci;
+ }
+ ci = (ci+cinc) % pn;
+ }
+ }
+
+
+ // If the max deviation is larger than accepted error,
+ // add new point, else continue to next segment.
+ if (maxi != -1 && maxd > (maxError*maxError))
+ {
+ // Add space for the new point.
+ simplified.resize(simplified.size()+4);
+ const int n = static_cast(simplified.size()) / 4;
+ for (int j = n-1; j > i; --j)
+ {
+ simplified[j*4+0] = simplified[(j-1)*4+0];
+ simplified[j*4+1] = simplified[(j-1)*4+1];
+ simplified[j*4+2] = simplified[(j-1)*4+2];
+ simplified[j*4+3] = simplified[(j-1)*4+3];
+ }
+ // Add the point.
+ simplified[(i+1)*4+0] = points[maxi*4+0];
+ simplified[(i+1)*4+1] = points[maxi*4+1];
+ simplified[(i+1)*4+2] = points[maxi*4+2];
+ simplified[(i+1)*4+3] = maxi;
+ }
+ else
+ {
+ ++i;
+ }
+ }
+
+ // Split too long edges.
+ if (maxEdgeLen > 0 && (buildFlags & (RC_CONTOUR_TESS_WALL_EDGES|RC_CONTOUR_TESS_AREA_EDGES)) != 0)
+ {
+ for (int i = 0; i < simplified.size()/4; )
+ {
+ const int ii = (i+1) % (simplified.size()/4);
+
+ const int ax = simplified[i*4+0];
+ const int az = simplified[i*4+2];
+ const int ai = simplified[i*4+3];
+
+ const int bx = simplified[ii*4+0];
+ const int bz = simplified[ii*4+2];
+ const int bi = simplified[ii*4+3];
+
+ // Find maximum deviation from the segment.
+ int maxi = -1;
+ int ci = (ai+1) % pn;
+
+ // Tessellate only outer edges or edges between areas.
+ bool tess = false;
+ // Wall edges.
+ if ((buildFlags & RC_CONTOUR_TESS_WALL_EDGES) && (points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0)
+ tess = true;
+ // Edges between areas.
+ if ((buildFlags & RC_CONTOUR_TESS_AREA_EDGES) && (points[ci*4+3] & RC_AREA_BORDER))
+ tess = true;
+
+ if (tess)
+ {
+ int dx = bx - ax;
+ int dz = bz - az;
+ if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen)
+ {
+ // Round based on the segments in lexilogical order so that the
+ // max tesselation is consistent regardless in which direction
+ // segments are traversed.
+ const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
+ if (n > 1)
+ {
+ if (bx > ax || (bx == ax && bz > az))
+ maxi = (ai + n/2) % pn;
+ else
+ maxi = (ai + (n+1)/2) % pn;
+ }
+ }
+ }
+
+ // If the max deviation is larger than accepted error,
+ // add new point, else continue to next segment.
+ if (maxi != -1)
+ {
+ // Add space for the new point.
+ simplified.resize(simplified.size()+4);
+ const int n = static_cast(simplified.size()) / 4;
+ for (int j = n-1; j > i; --j)
+ {
+ simplified[j*4+0] = simplified[(j-1)*4+0];
+ simplified[j*4+1] = simplified[(j-1)*4+1];
+ simplified[j*4+2] = simplified[(j-1)*4+2];
+ simplified[j*4+3] = simplified[(j-1)*4+3];
+ }
+ // Add the point.
+ simplified[(i+1)*4+0] = points[maxi*4+0];
+ simplified[(i+1)*4+1] = points[maxi*4+1];
+ simplified[(i+1)*4+2] = points[maxi*4+2];
+ simplified[(i+1)*4+3] = maxi;
+ }
+ else
+ {
+ ++i;
+ }
+ }
+ }
+
+ for (int i = 0; i < simplified.size()/4; ++i)
+ {
+ // The edge vertex flag is take from the current raw point,
+ // and the neighbour region is take from the next raw point.
+ const int ai = (simplified[i*4+3]+1) % pn;
+ const int bi = simplified[i*4+3];
+ simplified[i*4+3] = (points[ai*4+3] & (RC_CONTOUR_REG_MASK|RC_AREA_BORDER)) | (points[bi*4+3] & RC_BORDER_VERTEX);
+ }
+
+}
+
+static int calcAreaOfPolygon2D(const int* verts, const int nverts)
+{
+ int area = 0;
+ for (int i = 0, j = nverts-1; i < nverts; j=i++)
+ {
+ const int* vi = &verts[i*4];
+ const int* vj = &verts[j*4];
+ area += vi[0] * vj[2] - vj[0] * vi[2];
+ }
+ return (area+1) / 2;
+}
+
+// TODO: these are the same as in RecastMesh.cpp, consider using the same.
+// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
+inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
+inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
+
+inline int area2(const int* a, const int* b, const int* c)
+{
+ return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
+}
+
+// Returns true iff c is strictly to the left of the directed
+// line through a to b.
+inline bool left(const int* a, const int* b, const int* c)
+{
+ return area2(a, b, c) < 0;
+}
+
+inline bool leftOn(const int* a, const int* b, const int* c)
+{
+ return area2(a, b, c) <= 0;
+}
+
+inline bool collinear(const int* a, const int* b, const int* c)
+{
+ return area2(a, b, c) == 0;
+}
+
+// Returns true iff ab properly intersects cd: they share
+// a point interior to both segments. The properness of the
+// intersection is ensured by using strict leftness.
+static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
+{
+ // Eliminate improper cases.
+ if (collinear(a,b,c) || collinear(a,b,d) ||
+ collinear(c,d,a) || collinear(c,d,b))
+ return false;
+
+ return (left(a,b,c) ^ left(a,b,d)) && (left(c,d,a) ^ left(c,d,b));
+}
+
+// Returns T iff (a,b,c) are collinear and point c lies
+// on the closed segment ab.
+static bool between(const int* a, const int* b, const int* c)
+{
+ if (!collinear(a, b, c))
+ return false;
+ // If ab not vertical, check betweenness on x; else on y.
+ if (a[0] != b[0])
+ return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
+ else
+ return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
+}
+
+// Returns true iff segments ab and cd intersect, properly or improperly.
+static bool intersect(const int* a, const int* b, const int* c, const int* d)
+{
+ if (intersectProp(a, b, c, d))
+ return true;
+ else if (between(a, b, c) || between(a, b, d) ||
+ between(c, d, a) || between(c, d, b))
+ return true;
+ else
+ return false;
+}
+
+static bool vequal(const int* a, const int* b)
+{
+ return a[0] == b[0] && a[2] == b[2];
+}
+
+static bool intersectSegContour(const int* d0, const int* d1, int i, int n, const int* verts)
+{
+ // For each edge (k,k+1) of P
+ for (int k = 0; k < n; k++)
+ {
+ int k1 = next(k, n);
+ // Skip edges incident to i.
+ if (i == k || i == k1)
+ continue;
+ const int* p0 = &verts[k * 4];
+ const int* p1 = &verts[k1 * 4];
+ if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
+ continue;
+
+ if (intersect(d0, d1, p0, p1))
+ return true;
+ }
+ return false;
+}
+
+static bool inCone(int i, int n, const int* verts, const int* pj)
+{
+ const int* pi = &verts[i * 4];
+ const int* pi1 = &verts[next(i, n) * 4];
+ const int* pin1 = &verts[prev(i, n) * 4];
+
+ // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
+ if (leftOn(pin1, pi, pi1))
+ return left(pi, pj, pin1) && left(pj, pi, pi1);
+ // Assume (i-1,i,i+1) not collinear.
+ // else P[i] is reflex.
+ return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
+}
+
+
+static void removeDegenerateSegments(rcTempVector& simplified)
+{
+ // Remove adjacent vertices which are equal on xz-plane,
+ // or else the triangulator will get confused.
+ int npts = static_cast(simplified.size()) / 4;
+ for (int i = 0; i < npts; ++i)
+ {
+ int ni = next(i, npts);
+
+ if (vequal(&simplified[i*4], &simplified[ni*4]))
+ {
+ // Degenerate segment, remove.
+ for (int j = i; j < simplified.size()/4-1; ++j)
+ {
+ simplified[j*4+0] = simplified[(j+1)*4+0];
+ simplified[j*4+1] = simplified[(j+1)*4+1];
+ simplified[j*4+2] = simplified[(j+1)*4+2];
+ simplified[j*4+3] = simplified[(j+1)*4+3];
+ }
+ simplified.resize(simplified.size()-4);
+ npts--;
+ }
+ }
+}
+
+
+static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
+{
+ const int maxVerts = ca.nverts + cb.nverts + 2;
+ int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM);
+ if (!verts)
+ return false;
+
+ int nv = 0;
+
+ // Copy contour A.
+ for (int i = 0; i <= ca.nverts; ++i)
+ {
+ int* dst = &verts[nv*4];
+ const int* src = &ca.verts[((ia+i)%ca.nverts)*4];
+ dst[0] = src[0];
+ dst[1] = src[1];
+ dst[2] = src[2];
+ dst[3] = src[3];
+ nv++;
+ }
+
+ // Copy contour B
+ for (int i = 0; i <= cb.nverts; ++i)
+ {
+ int* dst = &verts[nv*4];
+ const int* src = &cb.verts[((ib+i)%cb.nverts)*4];
+ dst[0] = src[0];
+ dst[1] = src[1];
+ dst[2] = src[2];
+ dst[3] = src[3];
+ nv++;
+ }
+
+ rcFree(ca.verts);
+ ca.verts = verts;
+ ca.nverts = nv;
+
+ rcFree(cb.verts);
+ cb.verts = 0;
+ cb.nverts = 0;
+
+ return true;
+}
+
+struct rcContourHole
+{
+ rcContour* contour;
+ int minx, minz, leftmost;
+};
+
+struct rcContourRegion
+{
+ rcContour* outline;
+ rcContourHole* holes;
+ int nholes;
+};
+
+struct rcPotentialDiagonal
+{
+ int vert;
+ int dist;
+};
+
+// Finds the lowest leftmost vertex of a contour.
+static void findLeftMostVertex(rcContour* contour, int* minx, int* minz, int* leftmost)
+{
+ *minx = contour->verts[0];
+ *minz = contour->verts[2];
+ *leftmost = 0;
+ for (int i = 1; i < contour->nverts; i++)
+ {
+ const int x = contour->verts[i*4+0];
+ const int z = contour->verts[i*4+2];
+ if (x < *minx || (x == *minx && z < *minz))
+ {
+ *minx = x;
+ *minz = z;
+ *leftmost = i;
+ }
+ }
+}
+
+static int compareHoles(const void* va, const void* vb)
+{
+ const rcContourHole* a = (const rcContourHole*)va;
+ const rcContourHole* b = (const rcContourHole*)vb;
+ if (a->minx == b->minx)
+ {
+ if (a->minz < b->minz)
+ return -1;
+ if (a->minz > b->minz)
+ return 1;
+ }
+ else
+ {
+ if (a->minx < b->minx)
+ return -1;
+ if (a->minx > b->minx)
+ return 1;
+ }
+ return 0;
+}
+
+
+static int compareDiagDist(const void* va, const void* vb)
+{
+ const rcPotentialDiagonal* a = (const rcPotentialDiagonal*)va;
+ const rcPotentialDiagonal* b = (const rcPotentialDiagonal*)vb;
+ if (a->dist < b->dist)
+ return -1;
+ if (a->dist > b->dist)
+ return 1;
+ return 0;
+}
+
+
+static void mergeRegionHoles(rcContext* ctx, rcContourRegion& region)
+{
+ // Sort holes from left to right.
+ for (int i = 0; i < region.nholes; i++)
+ findLeftMostVertex(region.holes[i].contour, ®ion.holes[i].minx, ®ion.holes[i].minz, ®ion.holes[i].leftmost);
+
+ qsort(region.holes, region.nholes, sizeof(rcContourHole), compareHoles);
+
+ int maxVerts = region.outline->nverts;
+ for (int i = 0; i < region.nholes; i++)
+ maxVerts += region.holes[i].contour->nverts;
+
+ rcScopedDelete diags((rcPotentialDiagonal*)rcAlloc(sizeof(rcPotentialDiagonal)*maxVerts, RC_ALLOC_TEMP));
+ if (!diags)
+ {
+ ctx->log(RC_LOG_WARNING, "mergeRegionHoles: Failed to allocated diags %d.", maxVerts);
+ return;
+ }
+
+ rcContour* outline = region.outline;
+
+ // Merge holes into the outline one by one.
+ for (int i = 0; i < region.nholes; i++)
+ {
+ rcContour* hole = region.holes[i].contour;
+
+ int index = -1;
+ int bestVertex = region.holes[i].leftmost;
+ for (int iter = 0; iter < hole->nverts; iter++)
+ {
+ // Find potential diagonals.
+ // The 'best' vertex must be in the cone described by 3 consecutive vertices of the outline.
+ // ..o j-1
+ // |
+ // | * best
+ // |
+ // j o-----o j+1
+ // :
+ int ndiags = 0;
+ const int* corner = &hole->verts[bestVertex*4];
+ for (int j = 0; j < outline->nverts; j++)
+ {
+ if (inCone(j, outline->nverts, outline->verts, corner))
+ {
+ int dx = outline->verts[j*4+0] - corner[0];
+ int dz = outline->verts[j*4+2] - corner[2];
+ diags[ndiags].vert = j;
+ diags[ndiags].dist = dx*dx + dz*dz;
+ ndiags++;
+ }
+ }
+ // Sort potential diagonals by distance, we want to make the connection as short as possible.
+ qsort(diags, ndiags, sizeof(rcPotentialDiagonal), compareDiagDist);
+
+ // Find a diagonal that is not intersecting the outline not the remaining holes.
+ index = -1;
+ for (int j = 0; j < ndiags; j++)
+ {
+ const int* pt = &outline->verts[diags[j].vert*4];
+ bool intersect = intersectSegContour(pt, corner, diags[i].vert, outline->nverts, outline->verts);
+ for (int k = i; k < region.nholes && !intersect; k++)
+ intersect |= intersectSegContour(pt, corner, -1, region.holes[k].contour->nverts, region.holes[k].contour->verts);
+ if (!intersect)
+ {
+ index = diags[j].vert;
+ break;
+ }
+ }
+ // If found non-intersecting diagonal, stop looking.
+ if (index != -1)
+ break;
+ // All the potential diagonals for the current vertex were intersecting, try next vertex.
+ bestVertex = (bestVertex + 1) % hole->nverts;
+ }
+
+ if (index == -1)
+ {
+ ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to find merge points for %p and %p.", region.outline, hole);
+ continue;
+ }
+ if (!mergeContours(*region.outline, *hole, index, bestVertex))
+ {
+ ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to merge contours %p and %p.", region.outline, hole);
+ continue;
+ }
+ }
+}
+
+
+/// @par
+///
+/// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen
+/// parameters control how closely the simplified contours will match the raw contours.
+///
+/// Simplified contours are generated such that the vertices for portals between areas match up.
+/// (They are considered mandatory vertices.)
+///
+/// Setting @p maxEdgeLength to zero will disabled the edge length feature.
+///
+/// See the #rcConfig documentation for more information on the configuration parameters.
+///
+/// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig
+bool rcBuildContours(rcContext* ctx, const rcCompactHeightfield& chf,
+ const float maxError, const int maxEdgeLen,
+ rcContourSet& cset, const int buildFlags)
+{
+ rcAssert(ctx);
+
+ const int w = chf.width;
+ const int h = chf.height;
+ const int borderSize = chf.borderSize;
+
+ rcScopedTimer timer(ctx, RC_TIMER_BUILD_CONTOURS);
+
+ rcVcopy(cset.bmin, chf.bmin);
+ rcVcopy(cset.bmax, chf.bmax);
+ if (borderSize > 0)
+ {
+ // If the heightfield was build with bordersize, remove the offset.
+ const float pad = borderSize*chf.cs;
+ cset.bmin[0] += pad;
+ cset.bmin[2] += pad;
+ cset.bmax[0] -= pad;
+ cset.bmax[2] -= pad;
+ }
+ cset.cs = chf.cs;
+ cset.ch = chf.ch;
+ cset.width = chf.width - chf.borderSize*2;
+ cset.height = chf.height - chf.borderSize*2;
+ cset.borderSize = chf.borderSize;
+ cset.maxError = maxError;
+
+ int maxContours = rcMax((int)chf.maxRegions, 8);
+ cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
+ if (!cset.conts)
+ return false;
+ cset.nconts = 0;
+
+ rcScopedDelete flags((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
+ if (!flags)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount);
+ return false;
+ }
+
+ ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
+
+ // Mark boundaries.
+ for (int y = 0; y < h; ++y)
+ {
+ for (int x = 0; x < w; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ unsigned char res = 0;
+ const rcCompactSpan& s = chf.spans[i];
+ if (!chf.spans[i].reg || (chf.spans[i].reg & RC_BORDER_REG))
+ {
+ flags[i] = 0;
+ continue;
+ }
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ unsigned short r = 0;
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dir);
+ const int ay = y + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
+ r = chf.spans[ai].reg;
+ }
+ if (r == chf.spans[i].reg)
+ res |= (1 << dir);
+ }
+ flags[i] = res ^ 0xf; // Inverse, mark non connected edges.
+ }
+ }
+ }
+
+ ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
+
+ rcTempVector verts(256);
+ rcTempVector simplified(64);
+
+ for (int y = 0; y < h; ++y)
+ {
+ for (int x = 0; x < w; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ if (flags[i] == 0 || flags[i] == 0xf)
+ {
+ flags[i] = 0;
+ continue;
+ }
+ const unsigned short reg = chf.spans[i].reg;
+ if (!reg || (reg & RC_BORDER_REG))
+ continue;
+ const unsigned char area = chf.areas[i];
+
+ verts.clear();
+ simplified.clear();
+
+ ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
+ walkContour(x, y, i, chf, flags, verts);
+ ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
+
+ ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
+ simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags);
+ removeDegenerateSegments(simplified);
+ ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
+
+
+ // Store region->contour remap info.
+ // Create contour.
+ if (simplified.size()/4 >= 3)
+ {
+ if (cset.nconts >= maxContours)
+ {
+ // Allocate more contours.
+ // This happens when a region has holes.
+ const int oldMax = maxContours;
+ maxContours *= 2;
+ rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
+ for (int j = 0; j < cset.nconts; ++j)
+ {
+ newConts[j] = cset.conts[j];
+ // Reset source pointers to prevent data deletion.
+ cset.conts[j].verts = 0;
+ cset.conts[j].rverts = 0;
+ }
+ rcFree(cset.conts);
+ cset.conts = newConts;
+
+ ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours);
+ }
+
+ rcContour* cont = &cset.conts[cset.nconts++];
+
+ cont->nverts = static_cast(simplified.size()) / 4;
+ cont->verts = (int*)rcAlloc(sizeof(int)*cont->nverts*4, RC_ALLOC_PERM);
+ if (!cont->verts)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'verts' (%d).", cont->nverts);
+ return false;
+ }
+ memcpy(cont->verts, &simplified[0], sizeof(int)*cont->nverts*4);
+ if (borderSize > 0)
+ {
+ // If the heightfield was build with bordersize, remove the offset.
+ for (int j = 0; j < cont->nverts; ++j)
+ {
+ int* v = &cont->verts[j*4];
+ v[0] -= borderSize;
+ v[2] -= borderSize;
+ }
+ }
+
+ cont->nrverts = static_cast(verts.size()) / 4;
+ cont->rverts = static_cast(rcAlloc(sizeof(int) * cont->nrverts * 4, RC_ALLOC_PERM));
+ if (!cont->rverts)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'rverts' (%d).", cont->nrverts);
+ return false;
+ }
+ memcpy(cont->rverts, &verts[0], sizeof(int)*cont->nrverts*4);
+ if (borderSize > 0)
+ {
+ // If the heightfield was build with bordersize, remove the offset.
+ for (int j = 0; j < cont->nrverts; ++j)
+ {
+ int* v = &cont->rverts[j*4];
+ v[0] -= borderSize;
+ v[2] -= borderSize;
+ }
+ }
+
+ cont->reg = reg;
+ cont->area = area;
+ }
+ }
+ }
+ }
+
+ // Merge holes if needed.
+ if (cset.nconts > 0)
+ {
+ // Calculate winding of all polygons.
+ rcScopedDelete winding((signed char*)rcAlloc(sizeof(signed char)*cset.nconts, RC_ALLOC_TEMP));
+ if (!winding)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'hole' (%d).", cset.nconts);
+ return false;
+ }
+ int nholes = 0;
+ for (int i = 0; i < cset.nconts; ++i)
+ {
+ rcContour& cont = cset.conts[i];
+ // If the contour is wound backwards, it is a hole.
+ winding[i] = calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0 ? -1 : 1;
+ if (winding[i] < 0)
+ nholes++;
+ }
+
+ if (nholes > 0)
+ {
+ // Collect outline contour and holes contours per region.
+ // We assume that there is one outline and multiple holes.
+ const int nregions = chf.maxRegions+1;
+ rcScopedDelete regions((rcContourRegion*)rcAlloc(sizeof(rcContourRegion)*nregions, RC_ALLOC_TEMP));
+ if (!regions)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'regions' (%d).", nregions);
+ return false;
+ }
+ memset(regions, 0, sizeof(rcContourRegion)*nregions);
+
+ rcScopedDelete holes((rcContourHole*)rcAlloc(sizeof(rcContourHole)*cset.nconts, RC_ALLOC_TEMP));
+ if (!holes)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'holes' (%d).", cset.nconts);
+ return false;
+ }
+ memset(holes, 0, sizeof(rcContourHole)*cset.nconts);
+
+ for (int i = 0; i < cset.nconts; ++i)
+ {
+ rcContour& cont = cset.conts[i];
+ // Positively would contours are outlines, negative holes.
+ if (winding[i] > 0)
+ {
+ if (regions[cont.reg].outline)
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Multiple outlines for region %d.", cont.reg);
+ regions[cont.reg].outline = &cont;
+ }
+ else
+ {
+ regions[cont.reg].nholes++;
+ }
+ }
+ int index = 0;
+ for (int i = 0; i < nregions; i++)
+ {
+ if (regions[i].nholes > 0)
+ {
+ regions[i].holes = &holes[index];
+ index += regions[i].nholes;
+ regions[i].nholes = 0;
+ }
+ }
+ for (int i = 0; i < cset.nconts; ++i)
+ {
+ rcContour& cont = cset.conts[i];
+ rcContourRegion& reg = regions[cont.reg];
+ if (winding[i] < 0)
+ reg.holes[reg.nholes++].contour = &cont;
+ }
+
+ // Finally merge each regions holes into the outline.
+ for (int i = 0; i < nregions; i++)
+ {
+ rcContourRegion& reg = regions[i];
+ if (!reg.nholes) continue;
+
+ if (reg.outline)
+ {
+ mergeRegionHoles(ctx, reg);
+ }
+ else
+ {
+ // The region does not have an outline.
+ // This can happen if the contour becaomes selfoverlapping because of
+ // too aggressive simplification settings.
+ ctx->log(RC_LOG_ERROR, "rcBuildContours: Bad outline for region %d, contour simplification is likely too aggressive.", i);
+ }
+ }
+ }
+
+ }
+
+ return true;
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastFilter.cpp b/native/third_party/recastnavigation/Recast/Source/RecastFilter.cpp
new file mode 100644
index 0000000..7875040
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastFilter.cpp
@@ -0,0 +1,201 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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 "Recast.h"
+#include "RecastAssert.h"
+
+#include
+
+namespace
+{
+ const int MAX_HEIGHTFIELD_HEIGHT = 0xffff; // TODO (graham): Move this to a more visible constant and update usages.
+}
+
+void rcFilterLowHangingWalkableObstacles(rcContext* context, const int walkableClimb, rcHeightfield& heightfield)
+{
+ rcAssert(context);
+
+ rcScopedTimer timer(context, RC_TIMER_FILTER_LOW_OBSTACLES);
+
+ const int xSize = heightfield.width;
+ const int zSize = heightfield.height;
+
+ for (int z = 0; z < zSize; ++z)
+ {
+ for (int x = 0; x < xSize; ++x)
+ {
+ rcSpan* previousSpan = NULL;
+ bool previousWasWalkable = false;
+ unsigned char previousAreaID = RC_NULL_AREA;
+
+ // For each span in the column...
+ for (rcSpan* span = heightfield.spans[x + z * xSize]; span != NULL; previousSpan = span, span = span->next)
+ {
+ const bool walkable = span->area != RC_NULL_AREA;
+
+ // If current span is not walkable, but there is walkable span just below it and the height difference
+ // is small enough for the agent to walk over, mark the current span as walkable too.
+ if (!walkable && previousWasWalkable && (int)span->smax - (int)previousSpan->smax <= walkableClimb)
+ {
+ span->area = previousAreaID;
+ }
+
+ // Copy the original walkable value regardless of whether we changed it.
+ // This prevents multiple consecutive non-walkable spans from being erroneously marked as walkable.
+ previousWasWalkable = walkable;
+ previousAreaID = span->area;
+ }
+ }
+ }
+}
+
+void rcFilterLedgeSpans(rcContext* context, const int walkableHeight, const int walkableClimb, rcHeightfield& heightfield)
+{
+ rcAssert(context);
+
+ rcScopedTimer timer(context, RC_TIMER_FILTER_BORDER);
+
+ const int xSize = heightfield.width;
+ const int zSize = heightfield.height;
+
+ // Mark spans that are adjacent to a ledge as unwalkable..
+ for (int z = 0; z < zSize; ++z)
+ {
+ for (int x = 0; x < xSize; ++x)
+ {
+ for (rcSpan* span = heightfield.spans[x + z * xSize]; span; span = span->next)
+ {
+ // Skip non-walkable spans.
+ if (span->area == RC_NULL_AREA)
+ {
+ continue;
+ }
+
+ const int floor = (int)(span->smax);
+ const int ceiling = span->next ? (int)(span->next->smin) : MAX_HEIGHTFIELD_HEIGHT;
+
+ // The difference between this walkable area and the lowest neighbor walkable area.
+ // This is the difference between the current span and all neighbor spans that have
+ // enough space for an agent to move between, but not accounting at all for surface slope.
+ int lowestNeighborFloorDifference = MAX_HEIGHTFIELD_HEIGHT;
+
+ // Min and max height of accessible neighbours.
+ int lowestTraversableNeighborFloor = span->smax;
+ int highestTraversableNeighborFloor = span->smax;
+
+ for (int direction = 0; direction < 4; ++direction)
+ {
+ const int neighborX = x + rcGetDirOffsetX(direction);
+ const int neighborZ = z + rcGetDirOffsetY(direction);
+
+ // Skip neighbours which are out of bounds.
+ if (neighborX < 0 || neighborZ < 0 || neighborX >= xSize || neighborZ >= zSize)
+ {
+ lowestNeighborFloorDifference = -walkableClimb - 1;
+ break;
+ }
+
+ const rcSpan* neighborSpan = heightfield.spans[neighborX + neighborZ * xSize];
+
+ // The most we can step down to the neighbor is the walkableClimb distance.
+ // Start with the area under the neighbor span
+ int neighborCeiling = neighborSpan ? (int)neighborSpan->smin : MAX_HEIGHTFIELD_HEIGHT;
+
+ // Skip neighbour if the gap between the spans is too small.
+ if (rcMin(ceiling, neighborCeiling) - floor >= walkableHeight)
+ {
+ lowestNeighborFloorDifference = (-walkableClimb - 1);
+ break;
+ }
+
+ // For each span in the neighboring column...
+ for (; neighborSpan != NULL; neighborSpan = neighborSpan->next)
+ {
+ const int neighborFloor = (int)neighborSpan->smax;
+ neighborCeiling = neighborSpan->next ? (int)neighborSpan->next->smin : MAX_HEIGHTFIELD_HEIGHT;
+
+ // Only consider neighboring areas that have enough overlap to be potentially traversable.
+ if (rcMin(ceiling, neighborCeiling) - rcMax(floor, neighborFloor) < walkableHeight)
+ {
+ // No space to traverse between them.
+ continue;
+ }
+
+ const int neighborFloorDifference = neighborFloor - floor;
+ lowestNeighborFloorDifference = rcMin(lowestNeighborFloorDifference, neighborFloorDifference);
+
+ // Find min/max accessible neighbor height.
+ // Only consider neighbors that are at most walkableClimb away.
+ if (rcAbs(neighborFloorDifference) <= walkableClimb)
+ {
+ // There is space to move to the neighbor cell and the slope isn't too much.
+ lowestTraversableNeighborFloor = rcMin(lowestTraversableNeighborFloor, neighborFloor);
+ highestTraversableNeighborFloor = rcMax(highestTraversableNeighborFloor, neighborFloor);
+ }
+ else if (neighborFloorDifference < -walkableClimb)
+ {
+ // We already know this will be considered a ledge span so we can early-out
+ break;
+ }
+ }
+ }
+
+ // The current span is close to a ledge if the magnitude of the drop to any neighbour span is greater than the walkableClimb distance.
+ // That is, there is a gap that is large enough to let an agent move between them, but the drop (surface slope) is too large to allow it.
+ // (If this is the case, then biggestNeighborStepDown will be negative, so compare against the negative walkableClimb as a means of checking
+ // the magnitude of the delta)
+ if (lowestNeighborFloorDifference < -walkableClimb)
+ {
+ span->area = RC_NULL_AREA;
+ }
+ // If the difference between all neighbor floors is too large, this is a steep slope, so mark the span as an unwalkable ledge.
+ else if (highestTraversableNeighborFloor - lowestTraversableNeighborFloor > walkableClimb)
+ {
+ span->area = RC_NULL_AREA;
+ }
+ }
+ }
+ }
+}
+
+void rcFilterWalkableLowHeightSpans(rcContext* context, const int walkableHeight, rcHeightfield& heightfield)
+{
+ rcAssert(context);
+ rcScopedTimer timer(context, RC_TIMER_FILTER_WALKABLE);
+
+ const int xSize = heightfield.width;
+ const int zSize = heightfield.height;
+
+ // Remove walkable flag from spans which do not have enough
+ // space above them for the agent to stand there.
+ for (int z = 0; z < zSize; ++z)
+ {
+ for (int x = 0; x < xSize; ++x)
+ {
+ for (rcSpan* span = heightfield.spans[x + z*xSize]; span; span = span->next)
+ {
+ const int floor = (int)(span->smax);
+ const int ceiling = span->next ? (int)(span->next->smin) : MAX_HEIGHTFIELD_HEIGHT;
+ if (ceiling - floor < walkableHeight)
+ {
+ span->area = RC_NULL_AREA;
+ }
+ }
+ }
+ }
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastLayers.cpp b/native/third_party/recastnavigation/Recast/Source/RecastLayers.cpp
new file mode 100644
index 0000000..ca37ebb
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastLayers.cpp
@@ -0,0 +1,656 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include
+#include
+#include
+#include "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+
+// Must be 255 or smaller (not 256) because layer IDs are stored as
+// a byte where 255 is a special value.
+#ifndef RC_MAX_LAYERS_DEF
+#define RC_MAX_LAYERS_DEF 63
+#endif
+
+#if RC_MAX_LAYERS_DEF > 255
+#error RC_MAX_LAYERS_DEF must be 255 or smaller
+#endif
+
+#ifndef RC_MAX_NEIS_DEF
+#define RC_MAX_NEIS_DEF 16
+#endif
+
+// Keep type checking.
+static const int RC_MAX_LAYERS = RC_MAX_LAYERS_DEF;
+static const int RC_MAX_NEIS = RC_MAX_NEIS_DEF;
+
+struct rcLayerRegion
+{
+ unsigned char layers[RC_MAX_LAYERS];
+ unsigned char neis[RC_MAX_NEIS];
+ unsigned short ymin, ymax;
+ unsigned char layerId; // Layer ID
+ unsigned char nlayers; // Layer count
+ unsigned char nneis; // Neighbour count
+ unsigned char base; // Flag indicating if the region is the base of merged regions.
+};
+
+
+static bool contains(const unsigned char* a, const unsigned char an, const unsigned char v)
+{
+ const int n = (int)an;
+ for (int i = 0; i < n; ++i)
+ {
+ if (a[i] == v)
+ return true;
+ }
+ return false;
+}
+
+static bool addUnique(unsigned char* a, unsigned char& an, int anMax, unsigned char v)
+{
+ if (contains(a, an, v))
+ return true;
+
+ if ((int)an >= anMax)
+ return false;
+
+ a[an] = v;
+ an++;
+ return true;
+}
+
+
+inline bool overlapRange(const unsigned short amin, const unsigned short amax,
+ const unsigned short bmin, const unsigned short bmax)
+{
+ return (amin > bmax || amax < bmin) ? false : true;
+}
+
+
+
+struct rcLayerSweepSpan
+{
+ unsigned short ns; // number samples
+ unsigned char id; // region id
+ unsigned char nei; // neighbour id
+};
+
+/// @par
+///
+/// See the #rcConfig documentation for more information on the configuration parameters.
+///
+/// @see rcAllocHeightfieldLayerSet, rcCompactHeightfield, rcHeightfieldLayerSet, rcConfig
+bool rcBuildHeightfieldLayers(rcContext* ctx, const rcCompactHeightfield& chf,
+ const int borderSize, const int walkableHeight,
+ rcHeightfieldLayerSet& lset)
+{
+ rcAssert(ctx);
+
+ rcScopedTimer timer(ctx, RC_TIMER_BUILD_LAYERS);
+
+ const int w = chf.width;
+ const int h = chf.height;
+
+ rcScopedDelete srcReg((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
+ if (!srcReg)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount);
+ return false;
+ }
+ memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);
+
+ const int nsweeps = chf.width;
+ rcScopedDelete sweeps((rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP));
+ if (!sweeps)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps);
+ return false;
+ }
+
+
+ // Partition walkable area into monotone regions.
+ int prevCount[256];
+ unsigned char regId = 0;
+
+ for (int y = borderSize; y < h-borderSize; ++y)
+ {
+ memset(prevCount,0,sizeof(int)*regId);
+ unsigned char sweepId = 0;
+
+ for (int x = borderSize; x < w-borderSize; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+ if (chf.areas[i] == RC_NULL_AREA) continue;
+
+ unsigned char sid = 0xff;
+
+ // -x
+ if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(0);
+ const int ay = y + rcGetDirOffsetY(0);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
+ if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xff)
+ sid = srcReg[ai];
+ }
+
+ if (sid == 0xff)
+ {
+ sid = sweepId++;
+ sweeps[sid].nei = 0xff;
+ sweeps[sid].ns = 0;
+ }
+
+ // -y
+ if (rcGetCon(s,3) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(3);
+ const int ay = y + rcGetDirOffsetY(3);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
+ const unsigned char nr = srcReg[ai];
+ if (nr != 0xff)
+ {
+ // Set neighbour when first valid neighbour is encoutered.
+ if (sweeps[sid].ns == 0)
+ sweeps[sid].nei = nr;
+
+ if (sweeps[sid].nei == nr)
+ {
+ // Update existing neighbour
+ sweeps[sid].ns++;
+ prevCount[nr]++;
+ }
+ else
+ {
+ // This is hit if there is nore than one neighbour.
+ // Invalidate the neighbour.
+ sweeps[sid].nei = 0xff;
+ }
+ }
+ }
+
+ srcReg[i] = sid;
+ }
+ }
+
+ // Create unique ID.
+ for (int i = 0; i < sweepId; ++i)
+ {
+ // If the neighbour is set and there is only one continuous connection to it,
+ // the sweep will be merged with the previous one, else new region is created.
+ if (sweeps[i].nei != 0xff && prevCount[sweeps[i].nei] == (int)sweeps[i].ns)
+ {
+ sweeps[i].id = sweeps[i].nei;
+ }
+ else
+ {
+ if (regId == 255)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Region ID overflow.");
+ return false;
+ }
+ sweeps[i].id = regId++;
+ }
+ }
+
+ // Remap local sweep ids to region ids.
+ for (int x = borderSize; x < w-borderSize; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ if (srcReg[i] != 0xff)
+ srcReg[i] = sweeps[srcReg[i]].id;
+ }
+ }
+ }
+
+ // Allocate and init layer regions.
+ const int nregs = (int)regId;
+ rcScopedDelete regs((rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP));
+ if (!regs)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs);
+ return false;
+ }
+ memset(regs, 0, sizeof(rcLayerRegion)*nregs);
+ for (int i = 0; i < nregs; ++i)
+ {
+ regs[i].layerId = 0xff;
+ regs[i].ymin = 0xffff;
+ regs[i].ymax = 0;
+ }
+
+ // Find region neighbours and overlapping regions.
+ for (int y = 0; y < h; ++y)
+ {
+ for (int x = 0; x < w; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+
+ unsigned char lregs[RC_MAX_LAYERS];
+ int nlregs = 0;
+
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+ const unsigned char ri = srcReg[i];
+ if (ri == 0xff) continue;
+
+ regs[ri].ymin = rcMin(regs[ri].ymin, s.y);
+ regs[ri].ymax = rcMax(regs[ri].ymax, s.y);
+
+ // Collect all region layers.
+ if (nlregs < RC_MAX_LAYERS)
+ lregs[nlregs++] = ri;
+
+ // Update neighbours
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dir);
+ const int ay = y + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
+ const unsigned char rai = srcReg[ai];
+ if (rai != 0xff && rai != ri)
+ {
+ // Don't check return value -- if we cannot add the neighbor
+ // it will just cause a few more regions to be created, which
+ // is fine.
+ addUnique(regs[ri].neis, regs[ri].nneis, RC_MAX_NEIS, rai);
+ }
+ }
+ }
+
+ }
+
+ // Update overlapping regions.
+ for (int i = 0; i < nlregs-1; ++i)
+ {
+ for (int j = i+1; j < nlregs; ++j)
+ {
+ if (lregs[i] != lregs[j])
+ {
+ rcLayerRegion& ri = regs[lregs[i]];
+ rcLayerRegion& rj = regs[lregs[j]];
+
+ if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, lregs[j]) ||
+ !addUnique(rj.layers, rj.nlayers, RC_MAX_LAYERS, lregs[i]))
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");
+ return false;
+ }
+ }
+ }
+ }
+
+ }
+ }
+
+ // Create 2D layers from regions.
+ unsigned char layerId = 0;
+
+ static const int MAX_STACK = 64;
+ unsigned char stack[MAX_STACK];
+ int nstack = 0;
+
+ for (int i = 0; i < nregs; ++i)
+ {
+ rcLayerRegion& root = regs[i];
+ // Skip already visited.
+ if (root.layerId != 0xff)
+ continue;
+
+ // Start search.
+ root.layerId = layerId;
+ root.base = 1;
+
+ nstack = 0;
+ stack[nstack++] = (unsigned char)i;
+
+ while (nstack)
+ {
+ // Pop front
+ rcLayerRegion& reg = regs[stack[0]];
+ nstack--;
+ for (int j = 0; j < nstack; ++j)
+ stack[j] = stack[j+1];
+
+ const int nneis = (int)reg.nneis;
+ for (int j = 0; j < nneis; ++j)
+ {
+ const unsigned char nei = reg.neis[j];
+ rcLayerRegion& regn = regs[nei];
+ // Skip already visited.
+ if (regn.layerId != 0xff)
+ continue;
+ // Skip if the neighbour is overlapping root region.
+ if (contains(root.layers, root.nlayers, nei))
+ continue;
+ // Skip if the height range would become too large.
+ const int ymin = rcMin(root.ymin, regn.ymin);
+ const int ymax = rcMax(root.ymax, regn.ymax);
+ if ((ymax - ymin) >= 255)
+ continue;
+
+ if (nstack < MAX_STACK)
+ {
+ // Deepen
+ stack[nstack++] = (unsigned char)nei;
+
+ // Mark layer id
+ regn.layerId = layerId;
+ // Merge current layers to root.
+ for (int k = 0; k < regn.nlayers; ++k)
+ {
+ if (!addUnique(root.layers, root.nlayers, RC_MAX_LAYERS, regn.layers[k]))
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");
+ return false;
+ }
+ }
+ root.ymin = rcMin(root.ymin, regn.ymin);
+ root.ymax = rcMax(root.ymax, regn.ymax);
+ }
+ }
+ }
+
+ layerId++;
+ }
+
+ // Merge non-overlapping regions that are close in height.
+ const unsigned short mergeHeight = (unsigned short)walkableHeight * 4;
+
+ for (int i = 0; i < nregs; ++i)
+ {
+ rcLayerRegion& ri = regs[i];
+ if (!ri.base) continue;
+
+ unsigned char newId = ri.layerId;
+
+ for (;;)
+ {
+ unsigned char oldId = 0xff;
+
+ for (int j = 0; j < nregs; ++j)
+ {
+ if (i == j) continue;
+ rcLayerRegion& rj = regs[j];
+ if (!rj.base) continue;
+
+ // Skip if the regions are not close to each other.
+ if (!overlapRange(ri.ymin,ri.ymax+mergeHeight, rj.ymin,rj.ymax+mergeHeight))
+ continue;
+ // Skip if the height range would become too large.
+ const int ymin = rcMin(ri.ymin, rj.ymin);
+ const int ymax = rcMax(ri.ymax, rj.ymax);
+ if ((ymax - ymin) >= 255)
+ continue;
+
+ // Make sure that there is no overlap when merging 'ri' and 'rj'.
+ bool overlap = false;
+ // Iterate over all regions which have the same layerId as 'rj'
+ for (int k = 0; k < nregs; ++k)
+ {
+ if (regs[k].layerId != rj.layerId)
+ continue;
+ // Check if region 'k' is overlapping region 'ri'
+ // Index to 'regs' is the same as region id.
+ if (contains(ri.layers,ri.nlayers, (unsigned char)k))
+ {
+ overlap = true;
+ break;
+ }
+ }
+ // Cannot merge of regions overlap.
+ if (overlap)
+ continue;
+
+ // Can merge i and j.
+ oldId = rj.layerId;
+ break;
+ }
+
+ // Could not find anything to merge with, stop.
+ if (oldId == 0xff)
+ break;
+
+ // Merge
+ for (int j = 0; j < nregs; ++j)
+ {
+ rcLayerRegion& rj = regs[j];
+ if (rj.layerId == oldId)
+ {
+ rj.base = 0;
+ // Remap layerIds.
+ rj.layerId = newId;
+ // Add overlaid layers from 'rj' to 'ri'.
+ for (int k = 0; k < rj.nlayers; ++k)
+ {
+ if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, rj.layers[k]))
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");
+ return false;
+ }
+ }
+
+ // Update height bounds.
+ ri.ymin = rcMin(ri.ymin, rj.ymin);
+ ri.ymax = rcMax(ri.ymax, rj.ymax);
+ }
+ }
+ }
+ }
+
+ // Compact layerIds
+ unsigned char remap[256];
+ memset(remap, 0, 256);
+
+ // Find number of unique layers.
+ layerId = 0;
+ for (int i = 0; i < nregs; ++i)
+ remap[regs[i].layerId] = 1;
+ for (int i = 0; i < 256; ++i)
+ {
+ if (remap[i])
+ remap[i] = layerId++;
+ else
+ remap[i] = 0xff;
+ }
+ // Remap ids.
+ for (int i = 0; i < nregs; ++i)
+ regs[i].layerId = remap[regs[i].layerId];
+
+ // No layers, return empty.
+ if (layerId == 0)
+ return true;
+
+ // Create layers.
+ rcAssert(lset.layers == 0);
+
+ const int lw = w - borderSize*2;
+ const int lh = h - borderSize*2;
+
+ // Build contracted bbox for layers.
+ float bmin[3], bmax[3];
+ rcVcopy(bmin, chf.bmin);
+ rcVcopy(bmax, chf.bmax);
+ bmin[0] += borderSize*chf.cs;
+ bmin[2] += borderSize*chf.cs;
+ bmax[0] -= borderSize*chf.cs;
+ bmax[2] -= borderSize*chf.cs;
+
+ lset.nlayers = (int)layerId;
+
+ lset.layers = (rcHeightfieldLayer*)rcAlloc(sizeof(rcHeightfieldLayer)*lset.nlayers, RC_ALLOC_PERM);
+ if (!lset.layers)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'layers' (%d).", lset.nlayers);
+ return false;
+ }
+ memset(lset.layers, 0, sizeof(rcHeightfieldLayer)*lset.nlayers);
+
+
+ // Store layers.
+ for (int i = 0; i < lset.nlayers; ++i)
+ {
+ unsigned char curId = (unsigned char)i;
+
+ rcHeightfieldLayer* layer = &lset.layers[i];
+
+ const int gridSize = sizeof(unsigned char)*lw*lh;
+
+ layer->heights = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
+ if (!layer->heights)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'heights' (%d).", gridSize);
+ return false;
+ }
+ memset(layer->heights, 0xff, gridSize);
+
+ layer->areas = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
+ if (!layer->areas)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'areas' (%d).", gridSize);
+ return false;
+ }
+ memset(layer->areas, 0, gridSize);
+
+ layer->cons = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
+ if (!layer->cons)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'cons' (%d).", gridSize);
+ return false;
+ }
+ memset(layer->cons, 0, gridSize);
+
+ // Find layer height bounds.
+ int hmin = 0, hmax = 0;
+ for (int j = 0; j < nregs; ++j)
+ {
+ if (regs[j].base && regs[j].layerId == curId)
+ {
+ hmin = (int)regs[j].ymin;
+ hmax = (int)regs[j].ymax;
+ }
+ }
+
+ layer->width = lw;
+ layer->height = lh;
+ layer->cs = chf.cs;
+ layer->ch = chf.ch;
+
+ // Adjust the bbox to fit the heightfield.
+ rcVcopy(layer->bmin, bmin);
+ rcVcopy(layer->bmax, bmax);
+ layer->bmin[1] = bmin[1] + hmin*chf.ch;
+ layer->bmax[1] = bmin[1] + hmax*chf.ch;
+ layer->hmin = hmin;
+ layer->hmax = hmax;
+
+ // Update usable data region.
+ layer->minx = layer->width;
+ layer->maxx = 0;
+ layer->miny = layer->height;
+ layer->maxy = 0;
+
+ // Copy height and area from compact heightfield.
+ for (int y = 0; y < lh; ++y)
+ {
+ for (int x = 0; x < lw; ++x)
+ {
+ const int cx = borderSize+x;
+ const int cy = borderSize+y;
+ const rcCompactCell& c = chf.cells[cx+cy*w];
+ for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j)
+ {
+ const rcCompactSpan& s = chf.spans[j];
+ // Skip unassigned regions.
+ if (srcReg[j] == 0xff)
+ continue;
+ // Skip of does nto belong to current layer.
+ unsigned char lid = regs[srcReg[j]].layerId;
+ if (lid != curId)
+ continue;
+
+ // Update data bounds.
+ layer->minx = rcMin(layer->minx, x);
+ layer->maxx = rcMax(layer->maxx, x);
+ layer->miny = rcMin(layer->miny, y);
+ layer->maxy = rcMax(layer->maxy, y);
+
+ // Store height and area type.
+ const int idx = x+y*lw;
+ layer->heights[idx] = (unsigned char)(s.y - hmin);
+ layer->areas[idx] = chf.areas[j];
+
+ // Check connection.
+ unsigned char portal = 0;
+ unsigned char con = 0;
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = cx + rcGetDirOffsetX(dir);
+ const int ay = cy + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
+ unsigned char alid = srcReg[ai] != 0xff ? regs[srcReg[ai]].layerId : 0xff;
+ // Portal mask
+ if (chf.areas[ai] != RC_NULL_AREA && lid != alid)
+ {
+ portal |= (unsigned char)(1< hmin)
+ layer->heights[idx] = rcMax(layer->heights[idx], (unsigned char)(as.y - hmin));
+ }
+ // Valid connection mask
+ if (chf.areas[ai] != RC_NULL_AREA && lid == alid)
+ {
+ const int nx = ax - borderSize;
+ const int ny = ay - borderSize;
+ if (nx >= 0 && ny >= 0 && nx < lw && ny < lh)
+ con |= (unsigned char)(1<cons[idx] = (portal << 4) | con;
+ }
+ }
+ }
+
+ if (layer->minx > layer->maxx)
+ layer->minx = layer->maxx = 0;
+ if (layer->miny > layer->maxy)
+ layer->miny = layer->maxy = 0;
+ }
+
+ return true;
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastMesh.cpp b/native/third_party/recastnavigation/Recast/Source/RecastMesh.cpp
new file mode 100644
index 0000000..98e15cd
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastMesh.cpp
@@ -0,0 +1,1541 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include
+#include "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+struct rcEdge
+{
+ unsigned short vert[2];
+ unsigned short polyEdge[2];
+ unsigned short poly[2];
+};
+
+static bool buildMeshAdjacency(unsigned short* polys, const int npolys,
+ const int nverts, const int vertsPerPoly)
+{
+ // Based on code by Eric Lengyel from:
+ // https://web.archive.org/web/20080704083314/http://www.terathon.com/code/edges.php
+
+ int maxEdgeCount = npolys*vertsPerPoly;
+ unsigned short* firstEdge = (unsigned short*)rcAlloc(sizeof(unsigned short)*(nverts + maxEdgeCount), RC_ALLOC_TEMP);
+ if (!firstEdge)
+ return false;
+ unsigned short* nextEdge = firstEdge + nverts;
+ int edgeCount = 0;
+
+ rcEdge* edges = (rcEdge*)rcAlloc(sizeof(rcEdge)*maxEdgeCount, RC_ALLOC_TEMP);
+ if (!edges)
+ {
+ rcFree(firstEdge);
+ return false;
+ }
+
+ for (int i = 0; i < nverts; i++)
+ firstEdge[i] = RC_MESH_NULL_IDX;
+
+ for (int i = 0; i < npolys; ++i)
+ {
+ unsigned short* t = &polys[i*vertsPerPoly*2];
+ for (int j = 0; j < vertsPerPoly; ++j)
+ {
+ if (t[j] == RC_MESH_NULL_IDX) break;
+ unsigned short v0 = t[j];
+ unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
+ if (v0 < v1)
+ {
+ rcEdge& edge = edges[edgeCount];
+ edge.vert[0] = v0;
+ edge.vert[1] = v1;
+ edge.poly[0] = (unsigned short)i;
+ edge.polyEdge[0] = (unsigned short)j;
+ edge.poly[1] = (unsigned short)i;
+ edge.polyEdge[1] = 0;
+ // Insert edge
+ nextEdge[edgeCount] = firstEdge[v0];
+ firstEdge[v0] = (unsigned short)edgeCount;
+ edgeCount++;
+ }
+ }
+ }
+
+ for (int i = 0; i < npolys; ++i)
+ {
+ unsigned short* t = &polys[i*vertsPerPoly*2];
+ for (int j = 0; j < vertsPerPoly; ++j)
+ {
+ if (t[j] == RC_MESH_NULL_IDX) break;
+ unsigned short v0 = t[j];
+ unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
+ if (v0 > v1)
+ {
+ for (unsigned short e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = nextEdge[e])
+ {
+ rcEdge& edge = edges[e];
+ if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1])
+ {
+ edge.poly[1] = (unsigned short)i;
+ edge.polyEdge[1] = (unsigned short)j;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // Store adjacency
+ for (int i = 0; i < edgeCount; ++i)
+ {
+ const rcEdge& e = edges[i];
+ if (e.poly[0] != e.poly[1])
+ {
+ unsigned short* p0 = &polys[e.poly[0]*vertsPerPoly*2];
+ unsigned short* p1 = &polys[e.poly[1]*vertsPerPoly*2];
+ p0[vertsPerPoly + e.polyEdge[0]] = e.poly[1];
+ p1[vertsPerPoly + e.polyEdge[1]] = e.poly[0];
+ }
+ }
+
+ rcFree(firstEdge);
+ rcFree(edges);
+
+ return true;
+}
+
+
+static const int VERTEX_BUCKET_COUNT = (1<<12);
+
+inline int computeVertexHash(int x, int y, int z)
+{
+ const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
+ const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
+ const unsigned int h3 = 0xcb1ab31f;
+ unsigned int n = h1 * x + h2 * y + h3 * z;
+ return (int)(n & (VERTEX_BUCKET_COUNT-1));
+}
+
+static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z,
+ unsigned short* verts, int* firstVert, int* nextVert, int& nv)
+{
+ int bucket = computeVertexHash(x, 0, z);
+ int i = firstVert[bucket];
+
+ while (i != -1)
+ {
+ const unsigned short* v = &verts[i*3];
+ if (v[0] == x && (rcAbs(v[1] - y) <= 2) && v[2] == z)
+ return (unsigned short)i;
+ i = nextVert[i]; // next
+ }
+
+ // Could not find, create new.
+ i = nv; nv++;
+ unsigned short* v = &verts[i*3];
+ v[0] = x;
+ v[1] = y;
+ v[2] = z;
+ nextVert[i] = firstVert[bucket];
+ firstVert[bucket] = i;
+
+ return (unsigned short)i;
+}
+
+// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
+inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
+inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
+
+inline int area2(const int* a, const int* b, const int* c)
+{
+ return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
+}
+
+// Returns true iff c is strictly to the left of the directed
+// line through a to b.
+inline bool left(const int* a, const int* b, const int* c)
+{
+ return area2(a, b, c) < 0;
+}
+
+inline bool leftOn(const int* a, const int* b, const int* c)
+{
+ return area2(a, b, c) <= 0;
+}
+
+inline bool collinear(const int* a, const int* b, const int* c)
+{
+ return area2(a, b, c) == 0;
+}
+
+// Returns true iff ab properly intersects cd: they share
+// a point interior to both segments. The properness of the
+// intersection is ensured by using strict leftness.
+static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
+{
+ // Eliminate improper cases.
+ if (collinear(a,b,c) || collinear(a,b,d) ||
+ collinear(c,d,a) || collinear(c,d,b))
+ return false;
+
+ return (left(a,b,c) ^ left(a,b,d)) && (left(c,d,a) ^ left(c,d,b));
+}
+
+// Returns T iff (a,b,c) are collinear and point c lies
+// on the closed segement ab.
+static bool between(const int* a, const int* b, const int* c)
+{
+ if (!collinear(a, b, c))
+ return false;
+ // If ab not vertical, check betweenness on x; else on y.
+ if (a[0] != b[0])
+ return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
+
+ return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
+}
+
+// Returns true iff segments ab and cd intersect, properly or improperly.
+static bool intersect(const int* a, const int* b, const int* c, const int* d)
+{
+ if (intersectProp(a, b, c, d))
+ return true;
+
+ if (between(a, b, c) || between(a, b, d) ||
+ between(c, d, a) || between(c, d, b))
+ return true;
+
+ return false;
+}
+
+static bool vequal(const int* a, const int* b)
+{
+ return a[0] == b[0] && a[2] == b[2];
+}
+
+// Returns T iff (v_i, v_j) is a proper internal *or* external
+// diagonal of P, *ignoring edges incident to v_i and v_j*.
+static bool diagonalie(int i, int j, int n, const int* verts, int* indices)
+{
+ const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
+ const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
+
+ // For each edge (k,k+1) of P
+ for (int k = 0; k < n; k++)
+ {
+ int k1 = next(k, n);
+ // Skip edges incident to i or j
+ if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
+ {
+ const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
+ const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
+
+ if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
+ continue;
+
+ if (intersect(d0, d1, p0, p1))
+ return false;
+ }
+ }
+ return true;
+}
+
+// Returns true iff the diagonal (i,j) is strictly internal to the
+// polygon P in the neighborhood of the i endpoint.
+static bool inCone(int i, int j, int n, const int* verts, int* indices)
+{
+ const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
+ const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
+ const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
+ const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
+
+ // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
+ if (leftOn(pin1, pi, pi1))
+ return left(pi, pj, pin1) && left(pj, pi, pi1);
+ // Assume (i-1,i,i+1) not collinear.
+ // else P[i] is reflex.
+ return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
+}
+
+// Returns T iff (v_i, v_j) is a proper internal
+// diagonal of P.
+static bool diagonal(int i, int j, int n, const int* verts, int* indices)
+{
+ return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
+}
+
+
+static bool diagonalieLoose(int i, int j, int n, const int* verts, int* indices)
+{
+ const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
+ const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
+
+ // For each edge (k,k+1) of P
+ for (int k = 0; k < n; k++)
+ {
+ int k1 = next(k, n);
+ // Skip edges incident to i or j
+ if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
+ {
+ const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
+ const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
+
+ if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
+ continue;
+
+ if (intersectProp(d0, d1, p0, p1))
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool inConeLoose(int i, int j, int n, const int* verts, int* indices)
+{
+ const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
+ const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
+ const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
+ const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
+
+ // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
+ if (leftOn(pin1, pi, pi1))
+ return leftOn(pi, pj, pin1) && leftOn(pj, pi, pi1);
+ // Assume (i-1,i,i+1) not collinear.
+ // else P[i] is reflex.
+ return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
+}
+
+static bool diagonalLoose(int i, int j, int n, const int* verts, int* indices)
+{
+ return inConeLoose(i, j, n, verts, indices) && diagonalieLoose(i, j, n, verts, indices);
+}
+
+
+static int triangulate(int n, const int* verts, int* indices, int* tris)
+{
+ int ntris = 0;
+ int* dst = tris;
+
+ // The last bit of the index is used to indicate if the vertex can be removed.
+ for (int i = 0; i < n; i++)
+ {
+ int i1 = next(i, n);
+ int i2 = next(i1, n);
+ if (diagonal(i, i2, n, verts, indices))
+ indices[i1] |= 0x80000000;
+ }
+
+ while (n > 3)
+ {
+ int minLen = -1;
+ int mini = -1;
+ for (int i = 0; i < n; i++)
+ {
+ int i1 = next(i, n);
+ if (indices[i1] & 0x80000000)
+ {
+ const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
+ const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4];
+
+ int dx = p2[0] - p0[0];
+ int dy = p2[2] - p0[2];
+ int len = dx*dx + dy*dy;
+
+ if (minLen < 0 || len < minLen)
+ {
+ minLen = len;
+ mini = i;
+ }
+ }
+ }
+
+ if (mini == -1)
+ {
+ // We might get here because the contour has overlapping segments, like this:
+ //
+ // A o-o=====o---o B
+ // / |C D| \.
+ // o o o o
+ // : : : :
+ // We'll try to recover by loosing up the inCone test a bit so that a diagonal
+ // like A-B or C-D can be found and we can continue.
+ minLen = -1;
+ mini = -1;
+ for (int i = 0; i < n; i++)
+ {
+ int i1 = next(i, n);
+ int i2 = next(i1, n);
+ if (diagonalLoose(i, i2, n, verts, indices))
+ {
+ const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
+ const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4];
+ int dx = p2[0] - p0[0];
+ int dy = p2[2] - p0[2];
+ int len = dx*dx + dy*dy;
+
+ if (minLen < 0 || len < minLen)
+ {
+ minLen = len;
+ mini = i;
+ }
+ }
+ }
+ if (mini == -1)
+ {
+ // The contour is messed up. This sometimes happens
+ // if the contour simplification is too aggressive.
+ return -ntris;
+ }
+ }
+
+ int i = mini;
+ int i1 = next(i, n);
+ int i2 = next(i1, n);
+
+ *dst++ = indices[i] & 0x0fffffff;
+ *dst++ = indices[i1] & 0x0fffffff;
+ *dst++ = indices[i2] & 0x0fffffff;
+ ntris++;
+
+ // Removes P[i1] by copying P[i+1]...P[n-1] left one index.
+ n--;
+ for (int k = i1; k < n; k++)
+ indices[k] = indices[k+1];
+
+ if (i1 >= n) i1 = 0;
+ i = prev(i1,n);
+ // Update diagonal flags.
+ if (diagonal(prev(i, n), i1, n, verts, indices))
+ indices[i] |= 0x80000000;
+ else
+ indices[i] &= 0x0fffffff;
+
+ if (diagonal(i, next(i1, n), n, verts, indices))
+ indices[i1] |= 0x80000000;
+ else
+ indices[i1] &= 0x0fffffff;
+ }
+
+ // Append the remaining triangle.
+ *dst++ = indices[0] & 0x0fffffff;
+ *dst++ = indices[1] & 0x0fffffff;
+ *dst++ = indices[2] & 0x0fffffff;
+ ntris++;
+
+ return ntris;
+}
+
+static int countPolyVerts(const unsigned short* p, const int nvp)
+{
+ for (int i = 0; i < nvp; ++i)
+ if (p[i] == RC_MESH_NULL_IDX)
+ return i;
+ return nvp;
+}
+
+inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c)
+{
+ return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) -
+ ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0;
+}
+
+static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
+ const unsigned short* verts, int& ea, int& eb,
+ const int nvp)
+{
+ const int na = countPolyVerts(pa, nvp);
+ const int nb = countPolyVerts(pb, nvp);
+
+ // If the merged polygon would be too big, do not merge.
+ if (na+nb-2 > nvp)
+ return -1;
+
+ // Check if the polygons share an edge.
+ ea = -1;
+ eb = -1;
+
+ for (int i = 0; i < na; ++i)
+ {
+ unsigned short va0 = pa[i];
+ unsigned short va1 = pa[(i+1) % na];
+ if (va0 > va1)
+ rcSwap(va0, va1);
+ for (int j = 0; j < nb; ++j)
+ {
+ unsigned short vb0 = pb[j];
+ unsigned short vb1 = pb[(j+1) % nb];
+ if (vb0 > vb1)
+ rcSwap(vb0, vb1);
+ if (va0 == vb0 && va1 == vb1)
+ {
+ ea = i;
+ eb = j;
+ break;
+ }
+ }
+ }
+
+ // No common edge, cannot merge.
+ if (ea == -1 || eb == -1)
+ return -1;
+
+ // Check to see if the merged polygon would be convex.
+ unsigned short va, vb, vc;
+
+ va = pa[(ea+na-1) % na];
+ vb = pa[ea];
+ vc = pb[(eb+2) % nb];
+ if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
+ return -1;
+
+ va = pb[(eb+nb-1) % nb];
+ vb = pb[eb];
+ vc = pa[(ea+2) % na];
+ if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
+ return -1;
+
+ va = pa[ea];
+ vb = pa[(ea+1)%na];
+
+ int dx = (int)verts[va*3+0] - (int)verts[vb*3+0];
+ int dy = (int)verts[va*3+2] - (int)verts[vb*3+2];
+
+ return dx*dx + dy*dy;
+}
+
+static void mergePolyVerts(unsigned short* pa, unsigned short* pb, int ea, int eb,
+ unsigned short* tmp, const int nvp)
+{
+ const int na = countPolyVerts(pa, nvp);
+ const int nb = countPolyVerts(pb, nvp);
+
+ // Merge polygons.
+ memset(tmp, 0xff, sizeof(unsigned short)*nvp);
+ int n = 0;
+ // Add pa
+ for (int i = 0; i < na-1; ++i)
+ tmp[n++] = pa[(ea+1+i) % na];
+ // Add pb
+ for (int i = 0; i < nb-1; ++i)
+ tmp[n++] = pb[(eb+1+i) % nb];
+
+ memcpy(pa, tmp, sizeof(unsigned short)*nvp);
+}
+
+
+static void pushFront(int v, int* arr, int& an)
+{
+ an++;
+ for (int i = an-1; i > 0; --i) arr[i] = arr[i-1];
+ arr[0] = v;
+}
+
+static void pushBack(int v, int* arr, int& an)
+{
+ arr[an] = v;
+ an++;
+}
+
+static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem)
+{
+ const int nvp = mesh.nvp;
+
+ // Count number of polygons to remove.
+ int numTouchedVerts = 0;
+ int numRemainingEdges = 0;
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ unsigned short* p = &mesh.polys[i*nvp*2];
+ const int nv = countPolyVerts(p, nvp);
+ int numRemoved = 0;
+ int numVerts = 0;
+ for (int j = 0; j < nv; ++j)
+ {
+ if (p[j] == rem)
+ {
+ numTouchedVerts++;
+ numRemoved++;
+ }
+ numVerts++;
+ }
+ if (numRemoved)
+ {
+ numRemainingEdges += numVerts-(numRemoved+1);
+ }
+ }
+
+ // There would be too few edges remaining to create a polygon.
+ // This can happen for example when a tip of a triangle is marked
+ // as deletion, but there are no other polys that share the vertex.
+ // In this case, the vertex should not be removed.
+ if (numRemainingEdges <= 2)
+ return false;
+
+ // Find edges which share the removed vertex.
+ const int maxEdges = numTouchedVerts*2;
+ int nedges = 0;
+ rcScopedDelete edges((int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP));
+ if (!edges)
+ {
+ ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3);
+ return false;
+ }
+
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ unsigned short* p = &mesh.polys[i*nvp*2];
+ const int nv = countPolyVerts(p, nvp);
+
+ // Collect edges which touches the removed vertex.
+ for (int j = 0, k = nv-1; j < nv; k = j++)
+ {
+ if (p[j] == rem || p[k] == rem)
+ {
+ // Arrange edge so that a=rem.
+ int a = p[j], b = p[k];
+ if (b == rem)
+ rcSwap(a,b);
+
+ // Check if the edge exists
+ bool exists = false;
+ for (int m = 0; m < nedges; ++m)
+ {
+ int* e = &edges[m*3];
+ if (e[1] == b)
+ {
+ // Exists, increment vertex share count.
+ e[2]++;
+ exists = true;
+ }
+ }
+ // Add new edge.
+ if (!exists)
+ {
+ int* e = &edges[nedges*3];
+ e[0] = a;
+ e[1] = b;
+ e[2] = 1;
+ nedges++;
+ }
+ }
+ }
+ }
+
+ // There should be no more than 2 open edges.
+ // This catches the case that two non-adjacent polygons
+ // share the removed vertex. In that case, do not remove the vertex.
+ int numOpenEdges = 0;
+ for (int i = 0; i < nedges; ++i)
+ {
+ if (edges[i*3+2] < 2)
+ numOpenEdges++;
+ }
+ if (numOpenEdges > 2)
+ return false;
+
+ return true;
+}
+
+static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem, const int maxTris)
+{
+ const int nvp = mesh.nvp;
+
+ // Count number of polygons to remove.
+ int numRemovedVerts = 0;
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ unsigned short* p = &mesh.polys[i*nvp*2];
+ const int nv = countPolyVerts(p, nvp);
+ for (int j = 0; j < nv; ++j)
+ {
+ if (p[j] == rem)
+ numRemovedVerts++;
+ }
+ }
+
+ int nedges = 0;
+ rcScopedDelete edges((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP));
+ if (!edges)
+ {
+ ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4);
+ return false;
+ }
+
+ int nhole = 0;
+ rcScopedDelete hole((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
+ if (!hole)
+ {
+ ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp);
+ return false;
+ }
+
+ int nhreg = 0;
+ rcScopedDelete hreg((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
+ if (!hreg)
+ {
+ ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp);
+ return false;
+ }
+
+ int nharea = 0;
+ rcScopedDelete harea((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
+ if (!harea)
+ {
+ ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp);
+ return false;
+ }
+
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ unsigned short* p = &mesh.polys[i*nvp*2];
+ const int nv = countPolyVerts(p, nvp);
+ bool hasRem = false;
+ for (int j = 0; j < nv; ++j)
+ if (p[j] == rem) hasRem = true;
+ if (hasRem)
+ {
+ // Collect edges which does not touch the removed vertex.
+ for (int j = 0, k = nv-1; j < nv; k = j++)
+ {
+ if (p[j] != rem && p[k] != rem)
+ {
+ int* e = &edges[nedges*4];
+ e[0] = p[k];
+ e[1] = p[j];
+ e[2] = mesh.regs[i];
+ e[3] = mesh.areas[i];
+ nedges++;
+ }
+ }
+ // Remove the polygon.
+ unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2];
+ if (p != p2)
+ memcpy(p,p2,sizeof(unsigned short)*nvp);
+ memset(p+nvp,0xff,sizeof(unsigned short)*nvp);
+ mesh.regs[i] = mesh.regs[mesh.npolys-1];
+ mesh.areas[i] = mesh.areas[mesh.npolys-1];
+ mesh.npolys--;
+ --i;
+ }
+ }
+
+ // Remove vertex.
+ for (int i = (int)rem; i < mesh.nverts - 1; ++i)
+ {
+ mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
+ mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
+ mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2];
+ }
+ mesh.nverts--;
+
+ // Adjust indices to match the removed vertex layout.
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ unsigned short* p = &mesh.polys[i*nvp*2];
+ const int nv = countPolyVerts(p, nvp);
+ for (int j = 0; j < nv; ++j)
+ if (p[j] > rem) p[j]--;
+ }
+ for (int i = 0; i < nedges; ++i)
+ {
+ if (edges[i*4+0] > rem) edges[i*4+0]--;
+ if (edges[i*4+1] > rem) edges[i*4+1]--;
+ }
+
+ if (nedges == 0)
+ return true;
+
+ // Start with one vertex, keep appending connected
+ // segments to the start and end of the hole.
+ pushBack(edges[0], hole, nhole);
+ pushBack(edges[2], hreg, nhreg);
+ pushBack(edges[3], harea, nharea);
+
+ while (nedges)
+ {
+ bool match = false;
+
+ for (int i = 0; i < nedges; ++i)
+ {
+ const int ea = edges[i*4+0];
+ const int eb = edges[i*4+1];
+ const int r = edges[i*4+2];
+ const int a = edges[i*4+3];
+ bool add = false;
+ if (hole[0] == eb)
+ {
+ // The segment matches the beginning of the hole boundary.
+ pushFront(ea, hole, nhole);
+ pushFront(r, hreg, nhreg);
+ pushFront(a, harea, nharea);
+ add = true;
+ }
+ else if (hole[nhole-1] == ea)
+ {
+ // The segment matches the end of the hole boundary.
+ pushBack(eb, hole, nhole);
+ pushBack(r, hreg, nhreg);
+ pushBack(a, harea, nharea);
+ add = true;
+ }
+ if (add)
+ {
+ // The edge segment was added, remove it.
+ edges[i*4+0] = edges[(nedges-1)*4+0];
+ edges[i*4+1] = edges[(nedges-1)*4+1];
+ edges[i*4+2] = edges[(nedges-1)*4+2];
+ edges[i*4+3] = edges[(nedges-1)*4+3];
+ --nedges;
+ match = true;
+ --i;
+ }
+ }
+
+ if (!match)
+ break;
+ }
+
+ rcScopedDelete tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP));
+ if (!tris)
+ {
+ ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3);
+ return false;
+ }
+
+ rcScopedDelete tverts((int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP));
+ if (!tverts)
+ {
+ ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4);
+ return false;
+ }
+
+ rcScopedDelete thole((int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP));
+ if (!thole)
+ {
+ ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole);
+ return false;
+ }
+
+ // Generate temp vertex array for triangulation.
+ for (int i = 0; i < nhole; ++i)
+ {
+ const int pi = hole[i];
+ tverts[i*4+0] = mesh.verts[pi*3+0];
+ tverts[i*4+1] = mesh.verts[pi*3+1];
+ tverts[i*4+2] = mesh.verts[pi*3+2];
+ tverts[i*4+3] = 0;
+ thole[i] = i;
+ }
+
+ // Triangulate the hole.
+ int ntris = triangulate(nhole, &tverts[0], &thole[0], tris);
+ if (ntris < 0)
+ {
+ ntris = -ntris;
+ ctx->log(RC_LOG_WARNING, "removeVertex: triangulate() returned bad results.");
+ }
+
+ // Merge the hole triangles back to polygons.
+ rcScopedDelete polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP));
+ if (!polys)
+ {
+ ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp);
+ return false;
+ }
+ rcScopedDelete pregs((unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP));
+ if (!pregs)
+ {
+ ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris);
+ return false;
+ }
+ rcScopedDelete pareas((unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP));
+ if (!pareas)
+ {
+ ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris);
+ return false;
+ }
+
+ unsigned short* tmpPoly = &polys[ntris*nvp];
+
+ // Build initial polygons.
+ int npolys = 0;
+ memset(polys, 0xff, ntris*nvp*sizeof(unsigned short));
+ for (int j = 0; j < ntris; ++j)
+ {
+ int* t = &tris[j*3];
+ if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
+ {
+ polys[npolys*nvp+0] = (unsigned short)hole[t[0]];
+ polys[npolys*nvp+1] = (unsigned short)hole[t[1]];
+ polys[npolys*nvp+2] = (unsigned short)hole[t[2]];
+
+ // If this polygon covers multiple region types then
+ // mark it as such
+ if (hreg[t[0]] != hreg[t[1]] || hreg[t[1]] != hreg[t[2]])
+ pregs[npolys] = RC_MULTIPLE_REGS;
+ else
+ pregs[npolys] = (unsigned short)hreg[t[0]];
+
+ pareas[npolys] = (unsigned char)harea[t[0]];
+ npolys++;
+ }
+ }
+ if (!npolys)
+ return true;
+
+ // Merge polygons.
+ if (nvp > 3)
+ {
+ for (;;)
+ {
+ // Find best polygons to merge.
+ int bestMergeVal = 0;
+ int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
+
+ for (int j = 0; j < npolys-1; ++j)
+ {
+ unsigned short* pj = &polys[j*nvp];
+ for (int k = j+1; k < npolys; ++k)
+ {
+ unsigned short* pk = &polys[k*nvp];
+ int ea, eb;
+ int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);
+ if (v > bestMergeVal)
+ {
+ bestMergeVal = v;
+ bestPa = j;
+ bestPb = k;
+ bestEa = ea;
+ bestEb = eb;
+ }
+ }
+ }
+
+ if (bestMergeVal > 0)
+ {
+ // Found best, merge.
+ unsigned short* pa = &polys[bestPa*nvp];
+ unsigned short* pb = &polys[bestPb*nvp];
+ mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
+ if (pregs[bestPa] != pregs[bestPb])
+ pregs[bestPa] = RC_MULTIPLE_REGS;
+
+ unsigned short* last = &polys[(npolys-1)*nvp];
+ if (pb != last)
+ memcpy(pb, last, sizeof(unsigned short)*nvp);
+ pregs[bestPb] = pregs[npolys-1];
+ pareas[bestPb] = pareas[npolys-1];
+ npolys--;
+ }
+ else
+ {
+ // Could not merge any polygons, stop.
+ break;
+ }
+ }
+ }
+
+ // Store polygons.
+ for (int i = 0; i < npolys; ++i)
+ {
+ if (mesh.npolys >= maxTris) break;
+ unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];
+ memset(p,0xff,sizeof(unsigned short)*nvp*2);
+ for (int j = 0; j < nvp; ++j)
+ p[j] = polys[i*nvp+j];
+ mesh.regs[mesh.npolys] = pregs[i];
+ mesh.areas[mesh.npolys] = pareas[i];
+ mesh.npolys++;
+ if (mesh.npolys > maxTris)
+ {
+ ctx->log(RC_LOG_ERROR, "removeVertex: Too many polygons %d (max:%d).", mesh.npolys, maxTris);
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/// @par
+///
+/// @note If the mesh data is to be used to construct a Detour navigation mesh, then the upper
+/// limit must be restricted to <= #DT_VERTS_PER_POLYGON.
+///
+/// @see rcAllocPolyMesh, rcContourSet, rcPolyMesh, rcConfig
+bool rcBuildPolyMesh(rcContext* ctx, const rcContourSet& cset, const int nvp, rcPolyMesh& mesh)
+{
+ rcAssert(ctx);
+
+ rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESH);
+
+ rcVcopy(mesh.bmin, cset.bmin);
+ rcVcopy(mesh.bmax, cset.bmax);
+ mesh.cs = cset.cs;
+ mesh.ch = cset.ch;
+ mesh.borderSize = cset.borderSize;
+ mesh.maxEdgeError = cset.maxError;
+
+ int maxVertices = 0;
+ int maxTris = 0;
+ int maxVertsPerCont = 0;
+ for (int i = 0; i < cset.nconts; ++i)
+ {
+ // Skip null contours.
+ if (cset.conts[i].nverts < 3) continue;
+ maxVertices += cset.conts[i].nverts;
+ maxTris += cset.conts[i].nverts - 2;
+ maxVertsPerCont = rcMax(maxVertsPerCont, cset.conts[i].nverts);
+ }
+
+ if (maxVertices >= 0xfffe)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many vertices %d.", maxVertices);
+ return false;
+ }
+
+ rcScopedDelete vflags((unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP));
+ if (!vflags)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices);
+ return false;
+ }
+ memset(vflags, 0, maxVertices);
+
+ mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertices*3, RC_ALLOC_PERM);
+ if (!mesh.verts)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices);
+ return false;
+ }
+ mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris*nvp*2, RC_ALLOC_PERM);
+ if (!mesh.polys)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.polys' (%d).", maxTris*nvp*2);
+ return false;
+ }
+ mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris, RC_ALLOC_PERM);
+ if (!mesh.regs)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.regs' (%d).", maxTris);
+ return false;
+ }
+ mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris, RC_ALLOC_PERM);
+ if (!mesh.areas)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.areas' (%d).", maxTris);
+ return false;
+ }
+
+ mesh.nverts = 0;
+ mesh.npolys = 0;
+ mesh.nvp = nvp;
+ mesh.maxpolys = maxTris;
+
+ memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3);
+ memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*nvp*2);
+ memset(mesh.regs, 0, sizeof(unsigned short)*maxTris);
+ memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
+
+ rcScopedDelete nextVert((int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP));
+ if (!nextVert)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices);
+ return false;
+ }
+ memset(nextVert, 0, sizeof(int)*maxVertices);
+
+ rcScopedDelete firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
+ if (!firstVert)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
+ return false;
+ }
+ for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
+ firstVert[i] = -1;
+
+ rcScopedDelete indices((int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP));
+ if (!indices)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont);
+ return false;
+ }
+ rcScopedDelete tris((int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP));
+ if (!tris)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3);
+ return false;
+ }
+ rcScopedDelete polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP));
+ if (!polys)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp);
+ return false;
+ }
+ unsigned short* tmpPoly = &polys[maxVertsPerCont*nvp];
+
+ for (int i = 0; i < cset.nconts; ++i)
+ {
+ rcContour& cont = cset.conts[i];
+
+ // Skip null contours.
+ if (cont.nverts < 3)
+ continue;
+
+ // Triangulate contour
+ for (int j = 0; j < cont.nverts; ++j)
+ indices[j] = j;
+
+ int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]);
+ if (ntris <= 0)
+ {
+ // Bad triangulation, should not happen.
+/* printf("\tconst float bmin[3] = {%ff,%ff,%ff};\n", cset.bmin[0], cset.bmin[1], cset.bmin[2]);
+ printf("\tconst float cs = %ff;\n", cset.cs);
+ printf("\tconst float ch = %ff;\n", cset.ch);
+ printf("\tconst int verts[] = {\n");
+ for (int k = 0; k < cont.nverts; ++k)
+ {
+ const int* v = &cont.verts[k*4];
+ printf("\t\t%d,%d,%d,%d,\n", v[0], v[1], v[2], v[3]);
+ }
+ printf("\t};\n\tconst int nverts = sizeof(verts)/(sizeof(int)*4);\n");*/
+ ctx->log(RC_LOG_WARNING, "rcBuildPolyMesh: Bad triangulation Contour %d.", i);
+ ntris = -ntris;
+ }
+
+ // Add and merge vertices.
+ for (int j = 0; j < cont.nverts; ++j)
+ {
+ const int* v = &cont.verts[j*4];
+ indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2],
+ mesh.verts, firstVert, nextVert, mesh.nverts);
+ if (v[3] & RC_BORDER_VERTEX)
+ {
+ // This vertex should be removed.
+ vflags[indices[j]] = 1;
+ }
+ }
+
+ // Build initial polygons.
+ int npolys = 0;
+ memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short));
+ for (int j = 0; j < ntris; ++j)
+ {
+ int* t = &tris[j*3];
+ if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
+ {
+ polys[npolys*nvp+0] = (unsigned short)indices[t[0]];
+ polys[npolys*nvp+1] = (unsigned short)indices[t[1]];
+ polys[npolys*nvp+2] = (unsigned short)indices[t[2]];
+ npolys++;
+ }
+ }
+ if (!npolys)
+ continue;
+
+ // Merge polygons.
+ if (nvp > 3)
+ {
+ for(;;)
+ {
+ // Find best polygons to merge.
+ int bestMergeVal = 0;
+ int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
+
+ for (int j = 0; j < npolys-1; ++j)
+ {
+ unsigned short* pj = &polys[j*nvp];
+ for (int k = j+1; k < npolys; ++k)
+ {
+ unsigned short* pk = &polys[k*nvp];
+ int ea, eb;
+ int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);
+ if (v > bestMergeVal)
+ {
+ bestMergeVal = v;
+ bestPa = j;
+ bestPb = k;
+ bestEa = ea;
+ bestEb = eb;
+ }
+ }
+ }
+
+ if (bestMergeVal > 0)
+ {
+ // Found best, merge.
+ unsigned short* pa = &polys[bestPa*nvp];
+ unsigned short* pb = &polys[bestPb*nvp];
+ mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
+ unsigned short* lastPoly = &polys[(npolys-1)*nvp];
+ if (pb != lastPoly)
+ memcpy(pb, lastPoly, sizeof(unsigned short)*nvp);
+ npolys--;
+ }
+ else
+ {
+ // Could not merge any polygons, stop.
+ break;
+ }
+ }
+ }
+
+ // Store polygons.
+ for (int j = 0; j < npolys; ++j)
+ {
+ unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];
+ unsigned short* q = &polys[j*nvp];
+ for (int k = 0; k < nvp; ++k)
+ p[k] = q[k];
+ mesh.regs[mesh.npolys] = cont.reg;
+ mesh.areas[mesh.npolys] = cont.area;
+ mesh.npolys++;
+ if (mesh.npolys > maxTris)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many polygons %d (max:%d).", mesh.npolys, maxTris);
+ return false;
+ }
+ }
+ }
+
+
+ // Remove edge vertices.
+ for (int i = 0; i < mesh.nverts; ++i)
+ {
+ if (vflags[i])
+ {
+ if (!canRemoveVertex(ctx, mesh, (unsigned short)i))
+ continue;
+ if (!removeVertex(ctx, mesh, (unsigned short)i, maxTris))
+ {
+ // Failed to remove vertex
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Failed to remove edge vertex %d.", i);
+ return false;
+ }
+ // Remove vertex
+ // Note: mesh.nverts is already decremented inside removeVertex()!
+ // Fixup vertex flags
+ for (int j = i; j < mesh.nverts; ++j)
+ vflags[j] = vflags[j+1];
+ --i;
+ }
+ }
+
+ // Calculate adjacency.
+ if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, nvp))
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Adjacency failed.");
+ return false;
+ }
+
+ // Find portal edges
+ if (mesh.borderSize > 0)
+ {
+ const int w = cset.width;
+ const int h = cset.height;
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ unsigned short* p = &mesh.polys[i*2*nvp];
+ for (int j = 0; j < nvp; ++j)
+ {
+ if (p[j] == RC_MESH_NULL_IDX) break;
+ // Skip connected edges.
+ if (p[nvp+j] != RC_MESH_NULL_IDX)
+ continue;
+ int nj = j+1;
+ if (nj >= nvp || p[nj] == RC_MESH_NULL_IDX) nj = 0;
+ const unsigned short* va = &mesh.verts[p[j]*3];
+ const unsigned short* vb = &mesh.verts[p[nj]*3];
+
+ if ((int)va[0] == 0 && (int)vb[0] == 0)
+ p[nvp+j] = 0x8000 | 0;
+ else if ((int)va[2] == h && (int)vb[2] == h)
+ p[nvp+j] = 0x8000 | 1;
+ else if ((int)va[0] == w && (int)vb[0] == w)
+ p[nvp+j] = 0x8000 | 2;
+ else if ((int)va[2] == 0 && (int)vb[2] == 0)
+ p[nvp+j] = 0x8000 | 3;
+ }
+ }
+ }
+
+ // Just allocate the mesh flags array. The user is resposible to fill it.
+ mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*mesh.npolys, RC_ALLOC_PERM);
+ if (!mesh.flags)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.flags' (%d).", mesh.npolys);
+ return false;
+ }
+ memset(mesh.flags, 0, sizeof(unsigned short) * mesh.npolys);
+
+ if (mesh.nverts > 0xffff)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);
+ }
+ if (mesh.npolys > 0xffff)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
+ }
+
+ return true;
+}
+
+/// @see rcAllocPolyMesh, rcPolyMesh
+bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh)
+{
+ rcAssert(ctx);
+
+ if (!nmeshes || !meshes)
+ return true;
+
+ rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESH);
+
+ mesh.nvp = meshes[0]->nvp;
+ mesh.cs = meshes[0]->cs;
+ mesh.ch = meshes[0]->ch;
+ rcVcopy(mesh.bmin, meshes[0]->bmin);
+ rcVcopy(mesh.bmax, meshes[0]->bmax);
+
+ int maxVerts = 0;
+ int maxPolys = 0;
+ int maxVertsPerMesh = 0;
+ for (int i = 0; i < nmeshes; ++i)
+ {
+ rcVmin(mesh.bmin, meshes[i]->bmin);
+ rcVmax(mesh.bmax, meshes[i]->bmax);
+ maxVertsPerMesh = rcMax(maxVertsPerMesh, meshes[i]->nverts);
+ maxVerts += meshes[i]->nverts;
+ maxPolys += meshes[i]->npolys;
+ }
+
+ mesh.nverts = 0;
+ mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVerts*3, RC_ALLOC_PERM);
+ if (!mesh.verts)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.verts' (%d).", maxVerts*3);
+ return false;
+ }
+
+ mesh.npolys = 0;
+ mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys*2*mesh.nvp, RC_ALLOC_PERM);
+ if (!mesh.polys)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.polys' (%d).", maxPolys*2*mesh.nvp);
+ return false;
+ }
+ memset(mesh.polys, 0xff, sizeof(unsigned short)*maxPolys*2*mesh.nvp);
+
+ mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);
+ if (!mesh.regs)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.regs' (%d).", maxPolys);
+ return false;
+ }
+ memset(mesh.regs, 0, sizeof(unsigned short)*maxPolys);
+
+ mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxPolys, RC_ALLOC_PERM);
+ if (!mesh.areas)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.areas' (%d).", maxPolys);
+ return false;
+ }
+ memset(mesh.areas, 0, sizeof(unsigned char)*maxPolys);
+
+ mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);
+ if (!mesh.flags)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.flags' (%d).", maxPolys);
+ return false;
+ }
+ memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys);
+
+ rcScopedDelete nextVert((int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP));
+ if (!nextVert)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts);
+ return false;
+ }
+ memset(nextVert, 0, sizeof(int)*maxVerts);
+
+ rcScopedDelete firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
+ if (!firstVert)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
+ return false;
+ }
+ for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
+ firstVert[i] = -1;
+
+ rcScopedDelete vremap((unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM));
+ if (!vremap)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh);
+ return false;
+ }
+ memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh);
+
+ for (int i = 0; i < nmeshes; ++i)
+ {
+ const rcPolyMesh* pmesh = meshes[i];
+
+ const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f);
+ const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f);
+
+ bool isMinX = (ox == 0);
+ bool isMinZ = (oz == 0);
+ bool isMaxX = ((unsigned short)floorf((mesh.bmax[0] - pmesh->bmax[0]) / mesh.cs + 0.5f)) == 0;
+ bool isMaxZ = ((unsigned short)floorf((mesh.bmax[2] - pmesh->bmax[2]) / mesh.cs + 0.5f)) == 0;
+ bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ);
+
+ for (int j = 0; j < pmesh->nverts; ++j)
+ {
+ unsigned short* v = &pmesh->verts[j*3];
+ vremap[j] = addVertex(v[0]+ox, v[1], v[2]+oz,
+ mesh.verts, firstVert, nextVert, mesh.nverts);
+ }
+
+ for (int j = 0; j < pmesh->npolys; ++j)
+ {
+ unsigned short* tgt = &mesh.polys[mesh.npolys*2*mesh.nvp];
+ unsigned short* src = &pmesh->polys[j*2*mesh.nvp];
+ mesh.regs[mesh.npolys] = pmesh->regs[j];
+ mesh.areas[mesh.npolys] = pmesh->areas[j];
+ mesh.flags[mesh.npolys] = pmesh->flags[j];
+ mesh.npolys++;
+ for (int k = 0; k < mesh.nvp; ++k)
+ {
+ if (src[k] == RC_MESH_NULL_IDX) break;
+ tgt[k] = vremap[src[k]];
+ }
+
+ if (isOnBorder)
+ {
+ for (int k = mesh.nvp; k < mesh.nvp * 2; ++k)
+ {
+ if (src[k] & 0x8000 && src[k] != 0xffff)
+ {
+ unsigned short dir = src[k] & 0xf;
+ switch (dir)
+ {
+ case 0: // Portal x-
+ if (isMinX)
+ tgt[k] = src[k];
+ break;
+ case 1: // Portal z+
+ if (isMaxZ)
+ tgt[k] = src[k];
+ break;
+ case 2: // Portal x+
+ if (isMaxX)
+ tgt[k] = src[k];
+ break;
+ case 3: // Portal z-
+ if (isMinZ)
+ tgt[k] = src[k];
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Calculate adjacency.
+ if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, mesh.nvp))
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Adjacency failed.");
+ return false;
+ }
+
+ if (mesh.nverts > 0xffff)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);
+ }
+ if (mesh.npolys > 0xffff)
+ {
+ ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
+ }
+
+ return true;
+}
+
+bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst)
+{
+ rcAssert(ctx);
+
+ // Destination must be empty.
+ rcAssert(dst.verts == 0);
+ rcAssert(dst.polys == 0);
+ rcAssert(dst.regs == 0);
+ rcAssert(dst.areas == 0);
+ rcAssert(dst.flags == 0);
+
+ dst.nverts = src.nverts;
+ dst.npolys = src.npolys;
+ dst.maxpolys = src.npolys;
+ dst.nvp = src.nvp;
+ rcVcopy(dst.bmin, src.bmin);
+ rcVcopy(dst.bmax, src.bmax);
+ dst.cs = src.cs;
+ dst.ch = src.ch;
+ dst.borderSize = src.borderSize;
+ dst.maxEdgeError = src.maxEdgeError;
+
+ dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM);
+ if (!dst.verts)
+ {
+ ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3);
+ return false;
+ }
+ memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3);
+
+ dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM);
+ if (!dst.polys)
+ {
+ ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp);
+ return false;
+ }
+ memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp);
+
+ dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
+ if (!dst.regs)
+ {
+ ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys);
+ return false;
+ }
+ memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys);
+
+ dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM);
+ if (!dst.areas)
+ {
+ ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys);
+ return false;
+ }
+ memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys);
+
+ dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
+ if (!dst.flags)
+ {
+ ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys);
+ return false;
+ }
+ memcpy(dst.flags, src.flags, sizeof(unsigned short)*src.npolys);
+
+ return true;
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastMeshDetail.cpp b/native/third_party/recastnavigation/Recast/Source/RecastMeshDetail.cpp
new file mode 100644
index 0000000..07bbdbd
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastMeshDetail.cpp
@@ -0,0 +1,1476 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include
+#include
+#include
+#include "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+
+static const unsigned RC_UNSET_HEIGHT = 0xffff;
+
+struct rcHeightPatch
+{
+ inline rcHeightPatch() : data(0), xmin(0), ymin(0), width(0), height(0) {}
+ inline ~rcHeightPatch() { rcFree(data); }
+ unsigned short* data;
+ int xmin, ymin, width, height;
+};
+
+
+inline float vdot2(const float* a, const float* b)
+{
+ return a[0]*b[0] + a[2]*b[2];
+}
+
+inline float vdistSq2(const float* p, const float* q)
+{
+ const float dx = q[0] - p[0];
+ const float dy = q[2] - p[2];
+ return dx*dx + dy*dy;
+}
+
+inline float vdist2(const float* p, const float* q)
+{
+ return sqrtf(vdistSq2(p,q));
+}
+
+inline float vcross2(const float* p1, const float* p2, const float* p3)
+{
+ const float u1 = p2[0] - p1[0];
+ const float v1 = p2[2] - p1[2];
+ const float u2 = p3[0] - p1[0];
+ const float v2 = p3[2] - p1[2];
+ return u1 * v2 - v1 * u2;
+}
+
+static bool circumCircle(const float* p1, const float* p2, const float* p3,
+ float* c, float& r)
+{
+ static const float EPS = 1e-6f;
+ // Calculate the circle relative to p1, to avoid some precision issues.
+ const float v1[3] = {0,0,0};
+ float v2[3], v3[3];
+ rcVsub(v2, p2,p1);
+ rcVsub(v3, p3,p1);
+
+ const float cp = vcross2(v1, v2, v3);
+ if (fabsf(cp) > EPS)
+ {
+ const float v1Sq = vdot2(v1,v1);
+ const float v2Sq = vdot2(v2,v2);
+ const float v3Sq = vdot2(v3,v3);
+ c[0] = (v1Sq*(v2[2]-v3[2]) + v2Sq*(v3[2]-v1[2]) + v3Sq*(v1[2]-v2[2])) / (2*cp);
+ c[1] = 0;
+ c[2] = (v1Sq*(v3[0]-v2[0]) + v2Sq*(v1[0]-v3[0]) + v3Sq*(v2[0]-v1[0])) / (2*cp);
+ r = vdist2(c, v1);
+ rcVadd(c, c, p1);
+ return true;
+ }
+
+ rcVcopy(c, p1);
+ r = 0;
+ return false;
+}
+
+static float distPtTri(const float* p, const float* a, const float* b, const float* c)
+{
+ float v0[3], v1[3], v2[3];
+ rcVsub(v0, c,a);
+ rcVsub(v1, b,a);
+ rcVsub(v2, p,a);
+
+ const float dot00 = vdot2(v0, v0);
+ const float dot01 = vdot2(v0, v1);
+ const float dot02 = vdot2(v0, v2);
+ const float dot11 = vdot2(v1, v1);
+ const float dot12 = vdot2(v1, v2);
+
+ // Compute barycentric coordinates
+ const float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
+ const float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
+ float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
+
+ // If point lies inside the triangle, return interpolated y-coord.
+ static const float EPS = 1e-4f;
+ if (u >= -EPS && v >= -EPS && (u+v) <= 1+EPS)
+ {
+ const float y = a[1] + v0[1]*u + v1[1]*v;
+ return fabsf(y-p[1]);
+ }
+ return FLT_MAX;
+}
+
+static float distancePtSeg(const float* pt, const float* p, const float* q)
+{
+ float pqx = q[0] - p[0];
+ float pqy = q[1] - p[1];
+ float pqz = q[2] - p[2];
+ float dx = pt[0] - p[0];
+ float dy = pt[1] - p[1];
+ float dz = pt[2] - p[2];
+ float d = pqx*pqx + pqy*pqy + pqz*pqz;
+ float t = pqx*dx + pqy*dy + 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];
+ dy = p[1] + t*pqy - pt[1];
+ dz = p[2] + t*pqz - pt[2];
+
+ return dx*dx + dy*dy + dz*dz;
+}
+
+static float distancePtSeg2d(const float* pt, const float* p, const float* q)
+{
+ 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;
+ float 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;
+}
+
+static float distToTriMesh(const float* p, const float* verts, const int /*nverts*/, const int* tris, const int ntris)
+{
+ float dmin = FLT_MAX;
+ for (int i = 0; i < ntris; ++i)
+ {
+ const float* va = &verts[tris[i*4+0]*3];
+ const float* vb = &verts[tris[i*4+1]*3];
+ const float* vc = &verts[tris[i*4+2]*3];
+ float d = distPtTri(p, va,vb,vc);
+ if (d < dmin)
+ dmin = d;
+ }
+ if (dmin == FLT_MAX) return -1;
+ return dmin;
+}
+
+static float distToPoly(int nvert, const float* verts, const float* p)
+{
+
+ float dmin = FLT_MAX;
+ int i, j, c = 0;
+ for (i = 0, j = nvert-1; i < nvert; j = i++)
+ {
+ const float* vi = &verts[i*3];
+ const float* vj = &verts[j*3];
+ if (((vi[2] > p[2]) != (vj[2] > p[2])) &&
+ (p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
+ c = !c;
+ dmin = rcMin(dmin, distancePtSeg2d(p, vj, vi));
+ }
+ return c ? -dmin : dmin;
+}
+
+
+static unsigned short getHeight(const float fx, const float fy, const float fz,
+ const float /*cs*/, const float ics, const float ch,
+ const int radius, const rcHeightPatch& hp)
+{
+ int ix = (int)floorf(fx*ics + 0.01f);
+ int iz = (int)floorf(fz*ics + 0.01f);
+ ix = rcClamp(ix-hp.xmin, 0, hp.width - 1);
+ iz = rcClamp(iz-hp.ymin, 0, hp.height - 1);
+ unsigned short h = hp.data[ix+iz*hp.width];
+ if (h == RC_UNSET_HEIGHT)
+ {
+ // Special case when data might be bad.
+ // Walk adjacent cells in a spiral up to 'radius', and look
+ // for a pixel which has a valid height.
+ int x = 1, z = 0, dx = 1, dz = 0;
+ int maxSize = radius * 2 + 1;
+ int maxIter = maxSize * maxSize - 1;
+
+ int nextRingIterStart = 8;
+ int nextRingIters = 16;
+
+ float dmin = FLT_MAX;
+ for (int i = 0; i < maxIter; i++)
+ {
+ const int nx = ix + x;
+ const int nz = iz + z;
+
+ if (nx >= 0 && nz >= 0 && nx < hp.width && nz < hp.height)
+ {
+ const unsigned short nh = hp.data[nx + nz*hp.width];
+ if (nh != RC_UNSET_HEIGHT)
+ {
+ const float d = fabsf(nh*ch - fy);
+ if (d < dmin)
+ {
+ h = nh;
+ dmin = d;
+ }
+ }
+ }
+
+ // We are searching in a grid which looks approximately like this:
+ // __________
+ // |2 ______ 2|
+ // | |1 __ 1| |
+ // | | |__| | |
+ // | |______| |
+ // |__________|
+ // We want to find the best height as close to the center cell as possible. This means that
+ // if we find a height in one of the neighbor cells to the center, we don't want to
+ // expand further out than the 8 neighbors - we want to limit our search to the closest
+ // of these "rings", but the best height in the ring.
+ // For example, the center is just 1 cell. We checked that at the entrance to the function.
+ // The next "ring" contains 8 cells (marked 1 above). Those are all the neighbors to the center cell.
+ // The next one again contains 16 cells (marked 2). In general each ring has 8 additional cells, which
+ // can be thought of as adding 2 cells around the "center" of each side when we expand the ring.
+ // Here we detect if we are about to enter the next ring, and if we are and we have found
+ // a height, we abort the search.
+ if (i + 1 == nextRingIterStart)
+ {
+ if (h != RC_UNSET_HEIGHT)
+ break;
+
+ nextRingIterStart += nextRingIters;
+ nextRingIters += 8;
+ }
+
+ if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z)))
+ {
+ int tmp = dx;
+ dx = -dz;
+ dz = tmp;
+ }
+ x += dx;
+ z += dz;
+ }
+ }
+ return h;
+}
+
+
+enum EdgeValues
+{
+ EV_UNDEF = -1,
+ EV_HULL = -2
+};
+
+static int findEdge(const int* edges, int nedges, int s, int t)
+{
+ for (int i = 0; i < nedges; i++)
+ {
+ const int* e = &edges[i*4];
+ if ((e[0] == s && e[1] == t) || (e[0] == t && e[1] == s))
+ return i;
+ }
+ return EV_UNDEF;
+}
+
+static int addEdge(rcContext* ctx, int* edges, int& nedges, const int maxEdges, int s, int t, int l, int r)
+{
+ if (nedges >= maxEdges)
+ {
+ ctx->log(RC_LOG_ERROR, "addEdge: Too many edges (%d/%d).", nedges, maxEdges);
+ return EV_UNDEF;
+ }
+
+ // Add edge if not already in the triangulation.
+ int e = findEdge(edges, nedges, s, t);
+ if (e == EV_UNDEF)
+ {
+ int* edge = &edges[nedges*4];
+ edge[0] = s;
+ edge[1] = t;
+ edge[2] = l;
+ edge[3] = r;
+ return nedges++;
+ }
+ else
+ {
+ return EV_UNDEF;
+ }
+}
+
+static void updateLeftFace(int* e, int s, int t, int f)
+{
+ if (e[0] == s && e[1] == t && e[2] == EV_UNDEF)
+ e[2] = f;
+ else if (e[1] == s && e[0] == t && e[3] == EV_UNDEF)
+ e[3] = f;
+}
+
+static int overlapSegSeg2d(const float* a, const float* b, const float* c, const float* d)
+{
+ const float a1 = vcross2(a, b, d);
+ const float a2 = vcross2(a, b, c);
+ if (a1*a2 < 0.0f)
+ {
+ float a3 = vcross2(c, d, a);
+ float a4 = a3 + a2 - a1;
+ if (a3 * a4 < 0.0f)
+ return 1;
+ }
+ return 0;
+}
+
+static bool overlapEdges(const float* pts, const int* edges, int nedges, int s1, int t1)
+{
+ for (int i = 0; i < nedges; ++i)
+ {
+ const int s0 = edges[i*4+0];
+ const int t0 = edges[i*4+1];
+ // Same or connected edges do not overlap.
+ if (s0 == s1 || s0 == t1 || t0 == s1 || t0 == t1)
+ continue;
+ if (overlapSegSeg2d(&pts[s0*3],&pts[t0*3], &pts[s1*3],&pts[t1*3]))
+ return true;
+ }
+ return false;
+}
+
+static void completeFacet(rcContext* ctx, const float* pts, int npts, int* edges, int& nedges, const int maxEdges, int& nfaces, int e)
+{
+ static const float EPS = 1e-5f;
+
+ int* edge = &edges[e*4];
+
+ // Cache s and t.
+ int s,t;
+ if (edge[2] == EV_UNDEF)
+ {
+ s = edge[0];
+ t = edge[1];
+ }
+ else if (edge[3] == EV_UNDEF)
+ {
+ s = edge[1];
+ t = edge[0];
+ }
+ else
+ {
+ // Edge already completed.
+ return;
+ }
+
+ // Find best point on left of edge.
+ int pt = npts;
+ float c[3] = {0,0,0};
+ float r = -1;
+ for (int u = 0; u < npts; ++u)
+ {
+ if (u == s || u == t) continue;
+ if (vcross2(&pts[s*3], &pts[t*3], &pts[u*3]) > EPS)
+ {
+ if (r < 0)
+ {
+ // The circle is not updated yet, do it now.
+ pt = u;
+ circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
+ continue;
+ }
+ const float d = vdist2(c, &pts[u*3]);
+ const float tol = 0.001f;
+ if (d > r*(1+tol))
+ {
+ // Outside current circumcircle, skip.
+ continue;
+ }
+ else if (d < r*(1-tol))
+ {
+ // Inside safe circumcircle, update circle.
+ pt = u;
+ circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
+ }
+ else
+ {
+ // Inside epsilon circum circle, do extra tests to make sure the edge is valid.
+ // s-u and t-u cannot overlap with s-pt nor t-pt if they exists.
+ if (overlapEdges(pts, edges, nedges, s,u))
+ continue;
+ if (overlapEdges(pts, edges, nedges, t,u))
+ continue;
+ // Edge is valid.
+ pt = u;
+ circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
+ }
+ }
+ }
+
+ // Add new triangle or update edge info if s-t is on hull.
+ if (pt < npts)
+ {
+ // Update face information of edge being completed.
+ updateLeftFace(&edges[e*4], s, t, nfaces);
+
+ // Add new edge or update face info of old edge.
+ e = findEdge(edges, nedges, pt, s);
+ if (e == EV_UNDEF)
+ addEdge(ctx, edges, nedges, maxEdges, pt, s, nfaces, EV_UNDEF);
+ else
+ updateLeftFace(&edges[e*4], pt, s, nfaces);
+
+ // Add new edge or update face info of old edge.
+ e = findEdge(edges, nedges, t, pt);
+ if (e == EV_UNDEF)
+ addEdge(ctx, edges, nedges, maxEdges, t, pt, nfaces, EV_UNDEF);
+ else
+ updateLeftFace(&edges[e*4], t, pt, nfaces);
+
+ nfaces++;
+ }
+ else
+ {
+ updateLeftFace(&edges[e*4], s, t, EV_HULL);
+ }
+}
+
+static void delaunayHull(rcContext* ctx, const int npts, const float* pts,
+ const int nhull, const int* hull,
+ rcTempVector& tris, rcTempVector& edges)
+{
+ int nfaces = 0;
+ int nedges = 0;
+ const int maxEdges = npts*10;
+ edges.resize(maxEdges*4);
+
+ for (int i = 0, j = nhull-1; i < nhull; j=i++)
+ addEdge(ctx, &edges[0], nedges, maxEdges, hull[j],hull[i], EV_HULL, EV_UNDEF);
+
+ int currentEdge = 0;
+ while (currentEdge < nedges)
+ {
+ if (edges[currentEdge*4+2] == EV_UNDEF)
+ completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
+ if (edges[currentEdge*4+3] == EV_UNDEF)
+ completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
+ currentEdge++;
+ }
+
+ // Create tris
+ tris.resize(nfaces*4);
+ for (int i = 0; i < nfaces*4; ++i)
+ tris[i] = -1;
+
+ for (int i = 0; i < nedges; ++i)
+ {
+ const int* e = &edges[i*4];
+ if (e[3] >= 0)
+ {
+ // Left face
+ int* t = &tris[e[3]*4];
+ if (t[0] == -1)
+ {
+ t[0] = e[0];
+ t[1] = e[1];
+ }
+ else if (t[0] == e[1])
+ t[2] = e[0];
+ else if (t[1] == e[0])
+ t[2] = e[1];
+ }
+ if (e[2] >= 0)
+ {
+ // Right
+ int* t = &tris[e[2]*4];
+ if (t[0] == -1)
+ {
+ t[0] = e[1];
+ t[1] = e[0];
+ }
+ else if (t[0] == e[0])
+ t[2] = e[1];
+ else if (t[1] == e[1])
+ t[2] = e[0];
+ }
+ }
+
+ for (int i = 0; i < tris.size()/4; ++i)
+ {
+ int* t = &tris[i*4];
+ if (t[0] == -1 || t[1] == -1 || t[2] == -1)
+ {
+ ctx->log(RC_LOG_WARNING, "delaunayHull: Removing dangling face %d [%d,%d,%d].", i, t[0],t[1],t[2]);
+ t[0] = tris[tris.size()-4];
+ t[1] = tris[tris.size()-3];
+ t[2] = tris[tris.size()-2];
+ t[3] = tris[tris.size()-1];
+ tris.resize(tris.size()-4);
+ --i;
+ }
+ }
+}
+
+// Calculate minimum extend of the polygon.
+static float polyMinExtent(const float* verts, const int nverts)
+{
+ float minDist = FLT_MAX;
+ for (int i = 0; i < nverts; i++)
+ {
+ const int ni = (i+1) % nverts;
+ const float* p1 = &verts[i*3];
+ const float* p2 = &verts[ni*3];
+ float maxEdgeDist = 0;
+ for (int j = 0; j < nverts; j++)
+ {
+ if (j == i || j == ni) continue;
+ float d = distancePtSeg2d(&verts[j*3], p1,p2);
+ maxEdgeDist = rcMax(maxEdgeDist, d);
+ }
+ minDist = rcMin(minDist, maxEdgeDist);
+ }
+ return rcSqrt(minDist);
+}
+
+// Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
+inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
+inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
+
+static void triangulateHull(const int /*nverts*/, const float* verts, const int nhull, const int* hull, const int nin, rcTempVector& tris)
+{
+ int start = 0, left = 1, right = nhull-1;
+
+ // Start from an ear with shortest perimeter.
+ // This tends to favor well formed triangles as starting point.
+ float dmin = FLT_MAX;
+ for (int i = 0; i < nhull; i++)
+ {
+ if (hull[i] >= nin) continue; // Ears are triangles with original vertices as middle vertex while others are actually line segments on edges
+ int pi = prev(i, nhull);
+ int ni = next(i, nhull);
+ const float* pv = &verts[hull[pi]*3];
+ const float* cv = &verts[hull[i]*3];
+ const float* nv = &verts[hull[ni]*3];
+ const float d = vdist2(pv,cv) + vdist2(cv,nv) + vdist2(nv,pv);
+ if (d < dmin)
+ {
+ start = i;
+ left = ni;
+ right = pi;
+ dmin = d;
+ }
+ }
+
+ // Add first triangle
+ tris.push_back(hull[start]);
+ tris.push_back(hull[left]);
+ tris.push_back(hull[right]);
+ tris.push_back(0);
+
+ // Triangulate the polygon by moving left or right,
+ // depending on which triangle has shorter perimeter.
+ // This heuristic was chose empirically, since it seems
+ // handle tessellated straight edges well.
+ while (next(left, nhull) != right)
+ {
+ // Check to see if se should advance left or right.
+ int nleft = next(left, nhull);
+ int nright = prev(right, nhull);
+
+ const float* cvleft = &verts[hull[left]*3];
+ const float* nvleft = &verts[hull[nleft]*3];
+ const float* cvright = &verts[hull[right]*3];
+ const float* nvright = &verts[hull[nright]*3];
+ const float dleft = vdist2(cvleft, nvleft) + vdist2(nvleft, cvright);
+ const float dright = vdist2(cvright, nvright) + vdist2(cvleft, nvright);
+
+ if (dleft < dright)
+ {
+ tris.push_back(hull[left]);
+ tris.push_back(hull[nleft]);
+ tris.push_back(hull[right]);
+ tris.push_back(0);
+ left = nleft;
+ }
+ else
+ {
+ tris.push_back(hull[left]);
+ tris.push_back(hull[nright]);
+ tris.push_back(hull[right]);
+ tris.push_back(0);
+ right = nright;
+ }
+ }
+}
+
+
+inline float getJitterX(const int i)
+{
+ return (((i * 0x8da6b343) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
+}
+
+inline float getJitterY(const int i)
+{
+ return (((i * 0xd8163841) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
+}
+
+static bool onHull(int a, int b, int nhull, int* hull)
+{
+ // All internal sampled points come after the hull so we can early out for those.
+ if (a >= nhull || b >= nhull)
+ return false;
+
+ for (int j = nhull - 1, i = 0; i < nhull; j = i++)
+ {
+ if (a == hull[j] && b == hull[i])
+ return true;
+ }
+
+ return false;
+}
+
+// Find edges that lie on hull and mark them as such.
+static void setTriFlags(rcTempVector& tris, int nhull, int* hull)
+{
+ // Matches DT_DETAIL_EDGE_BOUNDARY
+ const int DETAIL_EDGE_BOUNDARY = 0x1;
+
+ for (int i = 0; i < tris.size(); i += 4)
+ {
+ int a = tris[i + 0];
+ int b = tris[i + 1];
+ int c = tris[i + 2];
+ unsigned short flags = 0;
+ flags |= (onHull(a, b, nhull, hull) ? DETAIL_EDGE_BOUNDARY : 0) << 0;
+ flags |= (onHull(b, c, nhull, hull) ? DETAIL_EDGE_BOUNDARY : 0) << 2;
+ flags |= (onHull(c, a, nhull, hull) ? DETAIL_EDGE_BOUNDARY : 0) << 4;
+ tris[i + 3] = (int)flags;
+ }
+}
+
+static bool buildPolyDetail(rcContext* ctx, const float* in, const int nin,
+ const float sampleDist, const float sampleMaxError,
+ const int heightSearchRadius, const rcCompactHeightfield& chf,
+ const rcHeightPatch& hp, float* verts, int& nverts,
+ rcTempVector& tris, rcTempVector& edges, rcTempVector& samples)
+{
+ static const int MAX_VERTS = 127;
+ static const int MAX_TRIS = 255; // Max tris for delaunay is 2n-2-k (n=num verts, k=num hull verts).
+ static const int MAX_VERTS_PER_EDGE = 32;
+ float edge[(MAX_VERTS_PER_EDGE+1)*3];
+ int hull[MAX_VERTS];
+ int nhull = 0;
+
+ nverts = nin;
+
+ for (int i = 0; i < nin; ++i)
+ rcVcopy(&verts[i*3], &in[i*3]);
+
+ edges.clear();
+ tris.clear();
+
+ const float cs = chf.cs;
+ const float ics = 1.0f/cs;
+
+ // Calculate minimum extents of the polygon based on input data.
+ float minExtent = polyMinExtent(verts, nverts);
+
+ // Tessellate outlines.
+ // This is done in separate pass in order to ensure
+ // seamless height values across the ply boundaries.
+ if (sampleDist > 0)
+ {
+ for (int i = 0, j = nin-1; i < nin; j=i++)
+ {
+ const float* vj = &in[j*3];
+ const float* vi = &in[i*3];
+ bool swapped = false;
+ // Make sure the segments are always handled in same order
+ // using lexological sort or else there will be seams.
+ if (fabsf(vj[0]-vi[0]) < 1e-6f)
+ {
+ if (vj[2] > vi[2])
+ {
+ rcSwap(vj,vi);
+ swapped = true;
+ }
+ }
+ else
+ {
+ if (vj[0] > vi[0])
+ {
+ rcSwap(vj,vi);
+ swapped = true;
+ }
+ }
+ // Create samples along the edge.
+ float dx = vi[0] - vj[0];
+ float dy = vi[1] - vj[1];
+ float dz = vi[2] - vj[2];
+ float d = sqrtf(dx*dx + dz*dz);
+ int nn = 1 + (int)floorf(d/sampleDist);
+ if (nn >= MAX_VERTS_PER_EDGE) nn = MAX_VERTS_PER_EDGE-1;
+ if (nverts+nn >= MAX_VERTS)
+ nn = MAX_VERTS-1-nverts;
+
+ for (int k = 0; k <= nn; ++k)
+ {
+ float u = (float)k/(float)nn;
+ float* pos = &edge[k*3];
+ pos[0] = vj[0] + dx*u;
+ pos[1] = vj[1] + dy*u;
+ pos[2] = vj[2] + dz*u;
+ pos[1] = getHeight(pos[0],pos[1],pos[2], cs, ics, chf.ch, heightSearchRadius, hp)*chf.ch;
+ }
+ // Simplify samples.
+ int idx[MAX_VERTS_PER_EDGE] = {0,nn};
+ int nidx = 2;
+ for (int k = 0; k < nidx-1; )
+ {
+ const int a = idx[k];
+ const int b = idx[k+1];
+ const float* va = &edge[a*3];
+ const float* vb = &edge[b*3];
+ // Find maximum deviation along the segment.
+ float maxd = 0;
+ int maxi = -1;
+ for (int m = a+1; m < b; ++m)
+ {
+ float dev = distancePtSeg(&edge[m*3],va,vb);
+ if (dev > maxd)
+ {
+ maxd = dev;
+ maxi = m;
+ }
+ }
+ // If the max deviation is larger than accepted error,
+ // add new point, else continue to next segment.
+ if (maxi != -1 && maxd > rcSqr(sampleMaxError))
+ {
+ for (int m = nidx; m > k; --m)
+ idx[m] = idx[m-1];
+ idx[k+1] = maxi;
+ nidx++;
+ }
+ else
+ {
+ ++k;
+ }
+ }
+
+ hull[nhull++] = j;
+ // Add new vertices.
+ if (swapped)
+ {
+ for (int k = nidx-2; k > 0; --k)
+ {
+ rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
+ hull[nhull++] = nverts;
+ nverts++;
+ }
+ }
+ else
+ {
+ for (int k = 1; k < nidx-1; ++k)
+ {
+ rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
+ hull[nhull++] = nverts;
+ nverts++;
+ }
+ }
+ }
+ }
+
+ // If the polygon minimum extent is small (sliver or small triangle), do not try to add internal points.
+ if (minExtent < sampleDist*2)
+ {
+ triangulateHull(nverts, verts, nhull, hull, nin, tris);
+ setTriFlags(tris, nhull, hull);
+ return true;
+ }
+
+ // Tessellate the base mesh.
+ // We're using the triangulateHull instead of delaunayHull as it tends to
+ // create a bit better triangulation for long thin triangles when there
+ // are no internal points.
+ triangulateHull(nverts, verts, nhull, hull, nin, tris);
+
+ if (tris.size() == 0)
+ {
+ // Could not triangulate the poly, make sure there is some valid data there.
+ ctx->log(RC_LOG_WARNING, "buildPolyDetail: Could not triangulate polygon (%d verts).", nverts);
+ return true;
+ }
+
+ if (sampleDist > 0)
+ {
+ // Create sample locations in a grid.
+ float bmin[3], bmax[3];
+ rcVcopy(bmin, in);
+ rcVcopy(bmax, in);
+ for (int i = 1; i < nin; ++i)
+ {
+ rcVmin(bmin, &in[i*3]);
+ rcVmax(bmax, &in[i*3]);
+ }
+ int x0 = (int)floorf(bmin[0]/sampleDist);
+ int x1 = (int)ceilf(bmax[0]/sampleDist);
+ int z0 = (int)floorf(bmin[2]/sampleDist);
+ int z1 = (int)ceilf(bmax[2]/sampleDist);
+ samples.clear();
+ for (int z = z0; z < z1; ++z)
+ {
+ for (int x = x0; x < x1; ++x)
+ {
+ float pt[3];
+ pt[0] = x*sampleDist;
+ pt[1] = (bmax[1]+bmin[1])*0.5f;
+ pt[2] = z*sampleDist;
+ // Make sure the samples are not too close to the edges.
+ if (distToPoly(nin,in,pt) > -sampleDist/2) continue;
+ samples.push_back(x);
+ samples.push_back(getHeight(pt[0], pt[1], pt[2], cs, ics, chf.ch, heightSearchRadius, hp));
+ samples.push_back(z);
+ samples.push_back(0); // Not added
+ }
+ }
+
+ // Add the samples starting from the one that has the most
+ // error. The procedure stops when all samples are added
+ // or when the max error is within treshold.
+ const int nsamples = static_cast(samples.size()) / 4;
+ for (int iter = 0; iter < nsamples; ++iter)
+ {
+ if (nverts >= MAX_VERTS)
+ break;
+
+ // Find sample with most error.
+ float bestpt[3] = {0,0,0};
+ float bestd = 0;
+ int besti = -1;
+ for (int i = 0; i < nsamples; ++i)
+ {
+ const int* s = &samples[i*4];
+ if (s[3]) continue; // skip added.
+ float pt[3];
+ // The sample location is jittered to get rid of some bad triangulations
+ // which are cause by symmetrical data from the grid structure.
+ pt[0] = s[0]*sampleDist + getJitterX(i)*cs*0.1f;
+ pt[1] = s[1]*chf.ch;
+ pt[2] = s[2]*sampleDist + getJitterY(i)*cs*0.1f;
+ if (tris.size() == 0) continue;
+ float d = distToTriMesh(pt, verts, nverts, &tris[0], static_cast(tris.size()) / 4);
+ if (d < 0) continue; // did not hit the mesh.
+ if (d > bestd)
+ {
+ bestd = d;
+ besti = i;
+ rcVcopy(bestpt,pt);
+ }
+ }
+ // If the max error is within accepted threshold, stop tesselating.
+ if (bestd <= sampleMaxError || besti == -1)
+ break;
+ // Mark sample as added.
+ samples[besti*4+3] = 1;
+ // Add the new sample point.
+ rcVcopy(&verts[nverts*3],bestpt);
+ nverts++;
+
+ // Create new triangulation.
+ // TODO: Incremental add instead of full rebuild.
+ edges.clear();
+ tris.clear();
+ delaunayHull(ctx, nverts, verts, nhull, hull, tris, edges);
+ }
+ }
+
+ const int ntris = static_cast(tris.size()) / 4;
+ if (ntris > MAX_TRIS)
+ {
+ tris.resize(MAX_TRIS*4);
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Shrinking triangle count from %d to max %d.", ntris, MAX_TRIS);
+ }
+
+ setTriFlags(tris, nhull, hull);
+
+ return true;
+}
+
+static void seedArrayWithPolyCenter(rcContext* ctx, const rcCompactHeightfield& chf,
+ const unsigned short* poly, const int npoly,
+ const unsigned short* verts, const int bs,
+ rcHeightPatch& hp, rcTempVector& array)
+{
+ // Note: Reads to the compact heightfield are offset by border size (bs)
+ // since border size offset is already removed from the polymesh vertices.
+
+ static const int offset[9*2] =
+ {
+ 0,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1, -1,0,
+ };
+
+ // Find cell closest to a poly vertex
+ int startCellX = 0, startCellY = 0, startSpanIndex = -1;
+ int dmin = RC_UNSET_HEIGHT;
+ for (int j = 0; j < npoly && dmin > 0; ++j)
+ {
+ for (int k = 0; k < 9 && dmin > 0; ++k)
+ {
+ const int ax = (int)verts[poly[j]*3+0] + offset[k*2+0];
+ const int ay = (int)verts[poly[j]*3+1];
+ const int az = (int)verts[poly[j]*3+2] + offset[k*2+1];
+ if (ax < hp.xmin || ax >= hp.xmin+hp.width ||
+ az < hp.ymin || az >= hp.ymin+hp.height)
+ continue;
+
+ const rcCompactCell& c = chf.cells[(ax+bs)+(az+bs)*chf.width];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni && dmin > 0; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+ int d = rcAbs(ay - (int)s.y);
+ if (d < dmin)
+ {
+ startCellX = ax;
+ startCellY = az;
+ startSpanIndex = i;
+ dmin = d;
+ }
+ }
+ }
+ }
+
+ rcAssert(startSpanIndex != -1);
+ // Find center of the polygon
+ int pcx = 0, pcy = 0;
+ for (int j = 0; j < npoly; ++j)
+ {
+ pcx += (int)verts[poly[j]*3+0];
+ pcy += (int)verts[poly[j]*3+2];
+ }
+ pcx /= npoly;
+ pcy /= npoly;
+
+ // Use seeds array as a stack for DFS
+ array.clear();
+ array.push_back(startCellX);
+ array.push_back(startCellY);
+ array.push_back(startSpanIndex);
+
+ int dirs[] = { 0, 1, 2, 3 };
+ memset(hp.data, 0, sizeof(unsigned short)*hp.width*hp.height);
+ // DFS to move to the center. Note that we need a DFS here and can not just move
+ // directly towards the center without recording intermediate nodes, even though the polygons
+ // are convex. In very rare we can get stuck due to contour simplification if we do not
+ // record nodes.
+ int cx = -1, cy = -1, ci = -1;
+ while (true)
+ {
+ if (array.size() < 3)
+ {
+ ctx->log(RC_LOG_WARNING, "Walk towards polygon center failed to reach center");
+ break;
+ }
+
+ ci = array.back(); array.pop_back();
+ cy = array.back(); array.pop_back();
+ cx = array.back(); array.pop_back();
+
+ if (cx == pcx && cy == pcy)
+ break;
+
+ // If we are already at the correct X-position, prefer direction
+ // directly towards the center in the Y-axis; otherwise prefer
+ // direction in the X-axis
+ int directDir;
+ if (cx == pcx)
+ directDir = rcGetDirForOffset(0, pcy > cy ? 1 : -1);
+ else
+ directDir = rcGetDirForOffset(pcx > cx ? 1 : -1, 0);
+
+ // Push the direct dir last so we start with this on next iteration
+ rcSwap(dirs[directDir], dirs[3]);
+
+ const rcCompactSpan& cs = chf.spans[ci];
+ for (int i = 0; i < 4; i++)
+ {
+ int dir = dirs[i];
+ if (rcGetCon(cs, dir) == RC_NOT_CONNECTED)
+ continue;
+
+ int newX = cx + rcGetDirOffsetX(dir);
+ int newY = cy + rcGetDirOffsetY(dir);
+
+ int hpx = newX - hp.xmin;
+ int hpy = newY - hp.ymin;
+ if (hpx < 0 || hpx >= hp.width || hpy < 0 || hpy >= hp.height)
+ continue;
+
+ if (hp.data[hpx+hpy*hp.width] != 0)
+ continue;
+
+ hp.data[hpx+hpy*hp.width] = 1;
+ array.push_back(newX);
+ array.push_back(newY);
+ array.push_back((int)chf.cells[(newX+bs)+(newY+bs)*chf.width].index + rcGetCon(cs, dir));
+ }
+
+ rcSwap(dirs[directDir], dirs[3]);
+ }
+
+ array.clear();
+ // getHeightData seeds are given in coordinates with borders
+ array.push_back(cx+bs);
+ array.push_back(cy+bs);
+ array.push_back(ci);
+
+ memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
+ const rcCompactSpan& cs = chf.spans[ci];
+ hp.data[cx-hp.xmin+(cy-hp.ymin)*hp.width] = cs.y;
+}
+
+
+static void push3(rcTempVector& queue, int v1, int v2, int v3)
+{
+ queue.resize(queue.size() + 3);
+ queue[queue.size() - 3] = v1;
+ queue[queue.size() - 2] = v2;
+ queue[queue.size() - 1] = v3;
+}
+
+static void getHeightData(rcContext* ctx, const rcCompactHeightfield& chf,
+ const unsigned short* poly, const int npoly,
+ const unsigned short* verts, const int bs,
+ rcHeightPatch& hp, rcTempVector& queue,
+ int region)
+{
+ // Note: Reads to the compact heightfield are offset by border size (bs)
+ // since border size offset is already removed from the polymesh vertices.
+
+ queue.clear();
+ // Set all heights to RC_UNSET_HEIGHT.
+ memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
+
+ bool empty = true;
+
+ // We cannot sample from this poly if it was created from polys
+ // of different regions. If it was then it could potentially be overlapping
+ // with polys of that region and the heights sampled here could be wrong.
+ if (region != RC_MULTIPLE_REGS)
+ {
+ // Copy the height from the same region, and mark region borders
+ // as seed points to fill the rest.
+ for (int hy = 0; hy < hp.height; hy++)
+ {
+ int y = hp.ymin + hy + bs;
+ for (int hx = 0; hx < hp.width; hx++)
+ {
+ int x = hp.xmin + hx + bs;
+ const rcCompactCell& c = chf.cells[x + y*chf.width];
+ for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+ if (s.reg == region)
+ {
+ // Store height
+ hp.data[hx + hy*hp.width] = s.y;
+ empty = false;
+
+ // If any of the neighbours is not in same region,
+ // add the current location as flood fill start
+ bool border = false;
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dir);
+ const int ay = y + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(s, dir);
+ const rcCompactSpan& as = chf.spans[ai];
+ if (as.reg != region)
+ {
+ border = true;
+ break;
+ }
+ }
+ }
+ if (border)
+ push3(queue, x, y, i);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // if the polygon does not contain any points from the current region (rare, but happens)
+ // or if it could potentially be overlapping polygons of the same region,
+ // then use the center as the seed point.
+ if (empty)
+ seedArrayWithPolyCenter(ctx, chf, poly, npoly, verts, bs, hp, queue);
+
+ static const int RETRACT_SIZE = 256;
+ int head = 0;
+
+ // We assume the seed is centered in the polygon, so a BFS to collect
+ // height data will ensure we do not move onto overlapping polygons and
+ // sample wrong heights.
+ while (head*3 < queue.size())
+ {
+ int cx = queue[head*3+0];
+ int cy = queue[head*3+1];
+ int ci = queue[head*3+2];
+ head++;
+ if (head >= RETRACT_SIZE)
+ {
+ head = 0;
+ if (queue.size() > RETRACT_SIZE*3)
+ memmove(&queue[0], &queue[RETRACT_SIZE*3], sizeof(int)*(queue.size()-RETRACT_SIZE*3));
+ queue.resize(queue.size()-RETRACT_SIZE*3);
+ }
+
+ const rcCompactSpan& cs = chf.spans[ci];
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) continue;
+
+ const int ax = cx + rcGetDirOffsetX(dir);
+ const int ay = cy + rcGetDirOffsetY(dir);
+ const int hx = ax - hp.xmin - bs;
+ const int hy = ay - hp.ymin - bs;
+
+ if ((unsigned int)hx >= (unsigned int)hp.width || (unsigned int)hy >= (unsigned int)hp.height)
+ continue;
+
+ if (hp.data[hx + hy*hp.width] != RC_UNSET_HEIGHT)
+ continue;
+
+ const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(cs, dir);
+ const rcCompactSpan& as = chf.spans[ai];
+
+ hp.data[hx + hy*hp.width] = as.y;
+
+ push3(queue, ax, ay, ai);
+ }
+ }
+}
+
+/// @par
+///
+/// See the #rcConfig documentation for more information on the configuration parameters.
+///
+/// @see rcAllocPolyMeshDetail, rcPolyMesh, rcCompactHeightfield, rcPolyMeshDetail, rcConfig
+bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf,
+ const float sampleDist, const float sampleMaxError,
+ rcPolyMeshDetail& dmesh)
+{
+ rcAssert(ctx);
+
+ rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESHDETAIL);
+
+ if (mesh.nverts == 0 || mesh.npolys == 0)
+ return true;
+
+ const int nvp = mesh.nvp;
+ const float cs = mesh.cs;
+ const float ch = mesh.ch;
+ const float* orig = mesh.bmin;
+ const int borderSize = mesh.borderSize;
+ const int heightSearchRadius = rcMax(1, (int)ceilf(mesh.maxEdgeError));
+
+ rcTempVector edges(64);
+ rcTempVector tris(512);
+ rcTempVector arr(512);
+ rcTempVector samples(512);
+ float verts[256*3];
+ rcHeightPatch hp;
+ int nPolyVerts = 0;
+ int maxhw = 0, maxhh = 0;
+
+ rcScopedDelete bounds((int*)rcAlloc(sizeof(int)*mesh.npolys*4, RC_ALLOC_TEMP));
+ if (!bounds)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'bounds' (%d).", mesh.npolys*4);
+ return false;
+ }
+ rcScopedDelete poly((float*)rcAlloc(sizeof(float)*nvp*3, RC_ALLOC_TEMP));
+ if (!poly)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'poly' (%d).", nvp*3);
+ return false;
+ }
+
+ // Find max size for a polygon area.
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ const unsigned short* p = &mesh.polys[i*nvp*2];
+ int& xmin = bounds[i*4+0];
+ int& xmax = bounds[i*4+1];
+ int& ymin = bounds[i*4+2];
+ int& ymax = bounds[i*4+3];
+ xmin = chf.width;
+ xmax = 0;
+ ymin = chf.height;
+ ymax = 0;
+ for (int j = 0; j < nvp; ++j)
+ {
+ if(p[j] == RC_MESH_NULL_IDX) break;
+ const unsigned short* v = &mesh.verts[p[j]*3];
+ xmin = rcMin(xmin, (int)v[0]);
+ xmax = rcMax(xmax, (int)v[0]);
+ ymin = rcMin(ymin, (int)v[2]);
+ ymax = rcMax(ymax, (int)v[2]);
+ nPolyVerts++;
+ }
+ xmin = rcMax(0,xmin-1);
+ xmax = rcMin(chf.width,xmax+1);
+ ymin = rcMax(0,ymin-1);
+ ymax = rcMin(chf.height,ymax+1);
+ if (xmin >= xmax || ymin >= ymax) continue;
+ maxhw = rcMax(maxhw, xmax-xmin);
+ maxhh = rcMax(maxhh, ymax-ymin);
+ }
+
+ hp.data = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP);
+ if (!hp.data)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'hp.data' (%d).", maxhw*maxhh);
+ return false;
+ }
+
+ dmesh.nmeshes = mesh.npolys;
+ dmesh.nverts = 0;
+ dmesh.ntris = 0;
+ dmesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*dmesh.nmeshes*4, RC_ALLOC_PERM);
+ if (!dmesh.meshes)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.meshes' (%d).", dmesh.nmeshes*4);
+ return false;
+ }
+
+ int vcap = nPolyVerts+nPolyVerts/2;
+ int tcap = vcap*2;
+
+ dmesh.nverts = 0;
+ dmesh.verts = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
+ if (!dmesh.verts)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", vcap*3);
+ return false;
+ }
+ dmesh.ntris = 0;
+ dmesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
+ if (!dmesh.tris)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", tcap*4);
+ return false;
+ }
+
+ for (int i = 0; i < mesh.npolys; ++i)
+ {
+ const unsigned short* p = &mesh.polys[i*nvp*2];
+
+ // Store polygon vertices for processing.
+ int npoly = 0;
+ for (int j = 0; j < nvp; ++j)
+ {
+ if(p[j] == RC_MESH_NULL_IDX) break;
+ const unsigned short* v = &mesh.verts[p[j]*3];
+ poly[j*3+0] = v[0]*cs;
+ poly[j*3+1] = v[1]*ch;
+ poly[j*3+2] = v[2]*cs;
+ npoly++;
+ }
+
+ // Get the height data from the area of the polygon.
+ hp.xmin = bounds[i*4+0];
+ hp.ymin = bounds[i*4+2];
+ hp.width = bounds[i*4+1]-bounds[i*4+0];
+ hp.height = bounds[i*4+3]-bounds[i*4+2];
+ getHeightData(ctx, chf, p, npoly, mesh.verts, borderSize, hp, arr, mesh.regs[i]);
+
+ // Build detail mesh.
+ int nverts = 0;
+ if (!buildPolyDetail(ctx, poly, npoly,
+ sampleDist, sampleMaxError,
+ heightSearchRadius, chf, hp,
+ verts, nverts, tris,
+ edges, samples))
+ {
+ return false;
+ }
+
+ // Move detail verts to world space.
+ for (int j = 0; j < nverts; ++j)
+ {
+ verts[j*3+0] += orig[0];
+ verts[j*3+1] += orig[1] + chf.ch; // Is this offset necessary?
+ verts[j*3+2] += orig[2];
+ }
+ // Offset poly too, will be used to flag checking.
+ for (int j = 0; j < npoly; ++j)
+ {
+ poly[j*3+0] += orig[0];
+ poly[j*3+1] += orig[1];
+ poly[j*3+2] += orig[2];
+ }
+
+ // Store detail submesh.
+ const int ntris = static_cast(tris.size()) / 4;
+
+ dmesh.meshes[i*4+0] = (unsigned int)dmesh.nverts;
+ dmesh.meshes[i*4+1] = (unsigned int)nverts;
+ dmesh.meshes[i*4+2] = (unsigned int)dmesh.ntris;
+ dmesh.meshes[i*4+3] = (unsigned int)ntris;
+
+ // Store vertices, allocate more memory if necessary.
+ if (dmesh.nverts+nverts > vcap)
+ {
+ while (dmesh.nverts+nverts > vcap)
+ vcap += 256;
+
+ float* newv = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
+ if (!newv)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newv' (%d).", vcap*3);
+ return false;
+ }
+ if (dmesh.nverts)
+ memcpy(newv, dmesh.verts, sizeof(float)*3*dmesh.nverts);
+ rcFree(dmesh.verts);
+ dmesh.verts = newv;
+ }
+ for (int j = 0; j < nverts; ++j)
+ {
+ dmesh.verts[dmesh.nverts*3+0] = verts[j*3+0];
+ dmesh.verts[dmesh.nverts*3+1] = verts[j*3+1];
+ dmesh.verts[dmesh.nverts*3+2] = verts[j*3+2];
+ dmesh.nverts++;
+ }
+
+ // Store triangles, allocate more memory if necessary.
+ if (dmesh.ntris+ntris > tcap)
+ {
+ while (dmesh.ntris+ntris > tcap)
+ tcap += 256;
+ unsigned char* newt = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
+ if (!newt)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newt' (%d).", tcap*4);
+ return false;
+ }
+ if (dmesh.ntris)
+ memcpy(newt, dmesh.tris, sizeof(unsigned char)*4*dmesh.ntris);
+ rcFree(dmesh.tris);
+ dmesh.tris = newt;
+ }
+ for (int j = 0; j < ntris; ++j)
+ {
+ const int* t = &tris[j*4];
+ dmesh.tris[dmesh.ntris*4+0] = (unsigned char)t[0];
+ dmesh.tris[dmesh.ntris*4+1] = (unsigned char)t[1];
+ dmesh.tris[dmesh.ntris*4+2] = (unsigned char)t[2];
+ dmesh.tris[dmesh.ntris*4+3] = (unsigned char)t[3];
+ dmesh.ntris++;
+ }
+ }
+
+ return true;
+}
+
+/// @see rcAllocPolyMeshDetail, rcPolyMeshDetail
+bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh)
+{
+ rcAssert(ctx);
+
+ rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESHDETAIL);
+
+ int maxVerts = 0;
+ int maxTris = 0;
+ int maxMeshes = 0;
+
+ for (int i = 0; i < nmeshes; ++i)
+ {
+ if (!meshes[i]) continue;
+ maxVerts += meshes[i]->nverts;
+ maxTris += meshes[i]->ntris;
+ maxMeshes += meshes[i]->nmeshes;
+ }
+
+ mesh.nmeshes = 0;
+ mesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*maxMeshes*4, RC_ALLOC_PERM);
+ if (!mesh.meshes)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'pmdtl.meshes' (%d).", maxMeshes*4);
+ return false;
+ }
+
+ mesh.ntris = 0;
+ mesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris*4, RC_ALLOC_PERM);
+ if (!mesh.tris)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", maxTris*4);
+ return false;
+ }
+
+ mesh.nverts = 0;
+ mesh.verts = (float*)rcAlloc(sizeof(float)*maxVerts*3, RC_ALLOC_PERM);
+ if (!mesh.verts)
+ {
+ ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", maxVerts*3);
+ return false;
+ }
+
+ // Merge datas.
+ for (int i = 0; i < nmeshes; ++i)
+ {
+ rcPolyMeshDetail* dm = meshes[i];
+ if (!dm) continue;
+ for (int j = 0; j < dm->nmeshes; ++j)
+ {
+ unsigned int* dst = &mesh.meshes[mesh.nmeshes*4];
+ unsigned int* src = &dm->meshes[j*4];
+ dst[0] = (unsigned int)mesh.nverts+src[0];
+ dst[1] = src[1];
+ dst[2] = (unsigned int)mesh.ntris+src[2];
+ dst[3] = src[3];
+ mesh.nmeshes++;
+ }
+
+ for (int k = 0; k < dm->nverts; ++k)
+ {
+ rcVcopy(&mesh.verts[mesh.nverts*3], &dm->verts[k*3]);
+ mesh.nverts++;
+ }
+ for (int k = 0; k < dm->ntris; ++k)
+ {
+ mesh.tris[mesh.ntris*4+0] = dm->tris[k*4+0];
+ mesh.tris[mesh.ntris*4+1] = dm->tris[k*4+1];
+ mesh.tris[mesh.ntris*4+2] = dm->tris[k*4+2];
+ mesh.tris[mesh.ntris*4+3] = dm->tris[k*4+3];
+ mesh.ntris++;
+ }
+ }
+
+ return true;
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastRasterization.cpp b/native/third_party/recastnavigation/Recast/Source/RecastRasterization.cpp
new file mode 100644
index 0000000..c65d6ea
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastRasterization.cpp
@@ -0,0 +1,562 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+/// Check whether two bounding boxes overlap
+///
+/// @param[in] aMin Min axis extents of bounding box A
+/// @param[in] aMax Max axis extents of bounding box A
+/// @param[in] bMin Min axis extents of bounding box B
+/// @param[in] bMax Max axis extents of bounding box B
+/// @returns true if the two bounding boxes overlap. False otherwise.
+static bool overlapBounds(const float* aMin, const float* aMax, const float* bMin, const float* bMax)
+{
+ return
+ aMin[0] <= bMax[0] && aMax[0] >= bMin[0] &&
+ aMin[1] <= bMax[1] && aMax[1] >= bMin[1] &&
+ aMin[2] <= bMax[2] && aMax[2] >= bMin[2];
+}
+
+/// Allocates a new span in the heightfield.
+/// Use a memory pool and free list to minimize actual allocations.
+///
+/// @param[in] heightfield The heightfield
+/// @returns A pointer to the allocated or re-used span memory.
+static rcSpan* allocSpan(rcHeightfield& heightfield)
+{
+ // If necessary, allocate new page and update the freelist.
+ if (heightfield.freelist == NULL || heightfield.freelist->next == NULL)
+ {
+ // Create new page.
+ // Allocate memory for the new pool.
+ rcSpanPool* spanPool = (rcSpanPool*)rcAlloc(sizeof(rcSpanPool), RC_ALLOC_PERM);
+ if (spanPool == NULL)
+ {
+ return NULL;
+ }
+
+ // Add the pool into the list of pools.
+ spanPool->next = heightfield.pools;
+ heightfield.pools = spanPool;
+
+ // Add new spans to the free list.
+ rcSpan* freeList = heightfield.freelist;
+ rcSpan* head = &spanPool->items[0];
+ rcSpan* it = &spanPool->items[RC_SPANS_PER_POOL];
+ do
+ {
+ --it;
+ it->next = freeList;
+ freeList = it;
+ }
+ while (it != head);
+ heightfield.freelist = it;
+ }
+
+ // Pop item from the front of the free list.
+ rcSpan* newSpan = heightfield.freelist;
+ heightfield.freelist = heightfield.freelist->next;
+ return newSpan;
+}
+
+/// Releases the memory used by the span back to the heightfield, so it can be re-used for new spans.
+/// @param[in] heightfield The heightfield.
+/// @param[in] span A pointer to the span to free
+static void freeSpan(rcHeightfield& heightfield, rcSpan* span)
+{
+ if (span == NULL)
+ {
+ return;
+ }
+ // Add the span to the front of the free list.
+ span->next = heightfield.freelist;
+ heightfield.freelist = span;
+}
+
+/// Adds a span to the heightfield. If the new span overlaps existing spans,
+/// it will merge the new span with the existing ones.
+///
+/// @param[in] heightfield Heightfield to add spans to
+/// @param[in] x The new span's column cell x index
+/// @param[in] z The new span's column cell z index
+/// @param[in] min The new span's minimum cell index
+/// @param[in] max The new span's maximum cell index
+/// @param[in] areaID The new span's area type ID
+/// @param[in] flagMergeThreshold How close two spans maximum extents need to be to merge area type IDs
+static bool addSpan(rcHeightfield& heightfield,
+ const int x, const int z,
+ const unsigned short min, const unsigned short max,
+ const unsigned char areaID, const int flagMergeThreshold)
+{
+ // Create the new span.
+ rcSpan* newSpan = allocSpan(heightfield);
+ if (newSpan == NULL)
+ {
+ return false;
+ }
+ newSpan->smin = min;
+ newSpan->smax = max;
+ newSpan->area = areaID;
+ newSpan->next = NULL;
+
+ const int columnIndex = x + z * heightfield.width;
+ rcSpan* previousSpan = NULL;
+ rcSpan* currentSpan = heightfield.spans[columnIndex];
+
+ // Insert the new span, possibly merging it with existing spans.
+ while (currentSpan != NULL)
+ {
+ if (currentSpan->smin > newSpan->smax)
+ {
+ // Current span is completely after the new span, break.
+ break;
+ }
+
+ if (currentSpan->smax < newSpan->smin)
+ {
+ // Current span is completely before the new span. Keep going.
+ previousSpan = currentSpan;
+ currentSpan = currentSpan->next;
+ }
+ else
+ {
+ // The new span overlaps with an existing span. Merge them.
+ if (currentSpan->smin < newSpan->smin)
+ {
+ newSpan->smin = currentSpan->smin;
+ }
+ if (currentSpan->smax > newSpan->smax)
+ {
+ newSpan->smax = currentSpan->smax;
+ }
+
+ // Merge flags.
+ if (rcAbs((int)newSpan->smax - (int)currentSpan->smax) <= flagMergeThreshold)
+ {
+ // Higher area ID numbers indicate higher resolution priority.
+ newSpan->area = rcMax(newSpan->area, currentSpan->area);
+ }
+
+ // Remove the current span since it's now merged with newSpan.
+ // Keep going because there might be other overlapping spans that also need to be merged.
+ rcSpan* next = currentSpan->next;
+ freeSpan(heightfield, currentSpan);
+ if (previousSpan)
+ {
+ previousSpan->next = next;
+ }
+ else
+ {
+ heightfield.spans[columnIndex] = next;
+ }
+ currentSpan = next;
+ }
+ }
+
+ // Insert new span after prev
+ if (previousSpan != NULL)
+ {
+ newSpan->next = previousSpan->next;
+ previousSpan->next = newSpan;
+ }
+ else
+ {
+ // This span should go before the others in the list
+ newSpan->next = heightfield.spans[columnIndex];
+ heightfield.spans[columnIndex] = newSpan;
+ }
+
+ return true;
+}
+
+bool rcAddSpan(rcContext* context, rcHeightfield& heightfield,
+ const int x, const int z,
+ const unsigned short spanMin, const unsigned short spanMax,
+ const unsigned char areaID, const int flagMergeThreshold)
+{
+ rcAssert(context);
+
+ // Span is zero size or inverted size. Ignore.
+ if (spanMin >= spanMax)
+ {
+ context->log(RC_LOG_WARNING, "rcAddSpan: Adding a span with zero or negative size. Ignored.");
+ return true;
+ }
+
+ if (!addSpan(heightfield, x, z, spanMin, spanMax, areaID, flagMergeThreshold))
+ {
+ context->log(RC_LOG_ERROR, "rcAddSpan: Out of memory.");
+ return false;
+ }
+
+ return true;
+}
+
+enum rcAxis
+{
+ RC_AXIS_X = 0,
+ RC_AXIS_Y = 1,
+ RC_AXIS_Z = 2
+};
+
+/// Divides a convex polygon of max 12 vertices into two convex polygons
+/// across a separating axis.
+///
+/// @param[in] inVerts The input polygon vertices
+/// @param[in] inVertsCount The number of input polygon vertices
+/// @param[out] outVerts1 Resulting polygon 1's vertices
+/// @param[out] outVerts1Count The number of resulting polygon 1 vertices
+/// @param[out] outVerts2 Resulting polygon 2's vertices
+/// @param[out] outVerts2Count The number of resulting polygon 2 vertices
+/// @param[in] axisOffset THe offset along the specified axis
+/// @param[in] axis The separating axis
+static void dividePoly(const float* inVerts, int inVertsCount,
+ float* outVerts1, int* outVerts1Count,
+ float* outVerts2, int* outVerts2Count,
+ float axisOffset, rcAxis axis)
+{
+ rcAssert(inVertsCount <= 12);
+
+ // How far positive or negative away from the separating axis is each vertex.
+ float inVertAxisDelta[12];
+ for (int inVert = 0; inVert < inVertsCount; ++inVert)
+ {
+ inVertAxisDelta[inVert] = axisOffset - inVerts[inVert * 3 + axis];
+ }
+
+ int poly1Vert = 0;
+ int poly2Vert = 0;
+ for (int inVertA = 0, inVertB = inVertsCount - 1; inVertA < inVertsCount; inVertB = inVertA, ++inVertA)
+ {
+ // If the two vertices are on the same side of the separating axis
+ bool sameSide = (inVertAxisDelta[inVertA] >= 0) == (inVertAxisDelta[inVertB] >= 0);
+
+ if (!sameSide)
+ {
+ float s = inVertAxisDelta[inVertB] / (inVertAxisDelta[inVertB] - inVertAxisDelta[inVertA]);
+ outVerts1[poly1Vert * 3 + 0] = inVerts[inVertB * 3 + 0] + (inVerts[inVertA * 3 + 0] - inVerts[inVertB * 3 + 0]) * s;
+ outVerts1[poly1Vert * 3 + 1] = inVerts[inVertB * 3 + 1] + (inVerts[inVertA * 3 + 1] - inVerts[inVertB * 3 + 1]) * s;
+ outVerts1[poly1Vert * 3 + 2] = inVerts[inVertB * 3 + 2] + (inVerts[inVertA * 3 + 2] - inVerts[inVertB * 3 + 2]) * s;
+ rcVcopy(&outVerts2[poly2Vert * 3], &outVerts1[poly1Vert * 3]);
+ poly1Vert++;
+ poly2Vert++;
+
+ // add the inVertA point to the right polygon. Do NOT add points that are on the dividing line
+ // since these were already added above
+ if (inVertAxisDelta[inVertA] > 0)
+ {
+ rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]);
+ poly1Vert++;
+ }
+ else if (inVertAxisDelta[inVertA] < 0)
+ {
+ rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]);
+ poly2Vert++;
+ }
+ }
+ else
+ {
+ // add the inVertA point to the right polygon. Addition is done even for points on the dividing line
+ if (inVertAxisDelta[inVertA] >= 0)
+ {
+ rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]);
+ poly1Vert++;
+ if (inVertAxisDelta[inVertA] != 0)
+ {
+ continue;
+ }
+ }
+ rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]);
+ poly2Vert++;
+ }
+ }
+
+ *outVerts1Count = poly1Vert;
+ *outVerts2Count = poly2Vert;
+}
+
+/// Rasterize a single triangle to the heightfield.
+///
+/// This code is extremely hot, so much care should be given to maintaining maximum perf here.
+///
+/// @param[in] v0 Triangle vertex 0
+/// @param[in] v1 Triangle vertex 1
+/// @param[in] v2 Triangle vertex 2
+/// @param[in] areaID The area ID to assign to the rasterized spans
+/// @param[in] heightfield Heightfield to rasterize into
+/// @param[in] heightfieldBBMin The min extents of the heightfield bounding box
+/// @param[in] heightfieldBBMax The max extents of the heightfield bounding box
+/// @param[in] cellSize The x and z axis size of a voxel in the heightfield
+/// @param[in] inverseCellSize 1 / cellSize
+/// @param[in] inverseCellHeight 1 / cellHeight
+/// @param[in] flagMergeThreshold The threshold in which area flags will be merged
+/// @returns true if the operation completes successfully. false if there was an error adding spans to the heightfield.
+static bool rasterizeTri(const float* v0, const float* v1, const float* v2,
+ const unsigned char areaID, rcHeightfield& heightfield,
+ const float* heightfieldBBMin, const float* heightfieldBBMax,
+ const float cellSize, const float inverseCellSize, const float inverseCellHeight,
+ const int flagMergeThreshold)
+{
+ // Calculate the bounding box of the triangle.
+ float triBBMin[3];
+ rcVcopy(triBBMin, v0);
+ rcVmin(triBBMin, v1);
+ rcVmin(triBBMin, v2);
+
+ float triBBMax[3];
+ rcVcopy(triBBMax, v0);
+ rcVmax(triBBMax, v1);
+ rcVmax(triBBMax, v2);
+
+ // If the triangle does not touch the bounding box of the heightfield, skip the triangle.
+ if (!overlapBounds(triBBMin, triBBMax, heightfieldBBMin, heightfieldBBMax))
+ {
+ return true;
+ }
+
+ const int w = heightfield.width;
+ const int h = heightfield.height;
+ const float by = heightfieldBBMax[1] - heightfieldBBMin[1];
+
+ // Calculate the footprint of the triangle on the grid's z-axis
+ int z0 = (int)((triBBMin[2] - heightfieldBBMin[2]) * inverseCellSize);
+ int z1 = (int)((triBBMax[2] - heightfieldBBMin[2]) * inverseCellSize);
+
+ // use -1 rather than 0 to cut the polygon properly at the start of the tile
+ z0 = rcClamp(z0, -1, h - 1);
+ z1 = rcClamp(z1, 0, h - 1);
+
+ // Clip the triangle into all grid cells it touches.
+ float buf[7 * 3 * 4];
+ float* in = buf;
+ float* inRow = buf + 7 * 3;
+ float* p1 = inRow + 7 * 3;
+ float* p2 = p1 + 7 * 3;
+
+ rcVcopy(&in[0], v0);
+ rcVcopy(&in[1 * 3], v1);
+ rcVcopy(&in[2 * 3], v2);
+ int nvRow;
+ int nvIn = 3;
+
+ for (int z = z0; z <= z1; ++z)
+ {
+ // Clip polygon to row. Store the remaining polygon as well
+ const float cellZ = heightfieldBBMin[2] + (float)z * cellSize;
+ dividePoly(in, nvIn, inRow, &nvRow, p1, &nvIn, cellZ + cellSize, RC_AXIS_Z);
+ rcSwap(in, p1);
+
+ if (nvRow < 3)
+ {
+ continue;
+ }
+ if (z < 0)
+ {
+ continue;
+ }
+
+ // find X-axis bounds of the row
+ float minX = inRow[0];
+ float maxX = inRow[0];
+ for (int vert = 1; vert < nvRow; ++vert)
+ {
+ if (minX > inRow[vert * 3])
+ {
+ minX = inRow[vert * 3];
+ }
+ if (maxX < inRow[vert * 3])
+ {
+ maxX = inRow[vert * 3];
+ }
+ }
+ int x0 = (int)((minX - heightfieldBBMin[0]) * inverseCellSize);
+ int x1 = (int)((maxX - heightfieldBBMin[0]) * inverseCellSize);
+ if (x1 < 0 || x0 >= w)
+ {
+ continue;
+ }
+ x0 = rcClamp(x0, -1, w - 1);
+ x1 = rcClamp(x1, 0, w - 1);
+
+ int nv;
+ int nv2 = nvRow;
+
+ for (int x = x0; x <= x1; ++x)
+ {
+ // Clip polygon to column. store the remaining polygon as well
+ const float cx = heightfieldBBMin[0] + (float)x * cellSize;
+ dividePoly(inRow, nv2, p1, &nv, p2, &nv2, cx + cellSize, RC_AXIS_X);
+ rcSwap(inRow, p2);
+
+ if (nv < 3)
+ {
+ continue;
+ }
+ if (x < 0)
+ {
+ continue;
+ }
+
+ // Calculate min and max of the span.
+ float spanMin = p1[1];
+ float spanMax = p1[1];
+ for (int vert = 1; vert < nv; ++vert)
+ {
+ spanMin = rcMin(spanMin, p1[vert * 3 + 1]);
+ spanMax = rcMax(spanMax, p1[vert * 3 + 1]);
+ }
+ spanMin -= heightfieldBBMin[1];
+ spanMax -= heightfieldBBMin[1];
+
+ // Skip the span if it's completely outside the heightfield bounding box
+ if (spanMax < 0.0f)
+ {
+ continue;
+ }
+ if (spanMin > by)
+ {
+ continue;
+ }
+
+ // Clamp the span to the heightfield bounding box.
+ if (spanMin < 0.0f)
+ {
+ spanMin = 0;
+ }
+ if (spanMax > by)
+ {
+ spanMax = by;
+ }
+
+ // Snap the span to the heightfield height grid.
+ unsigned short spanMinCellIndex = (unsigned short)rcClamp((int)floorf(spanMin * inverseCellHeight), 0, RC_SPAN_MAX_HEIGHT);
+ unsigned short spanMaxCellIndex = (unsigned short)rcClamp((int)ceilf(spanMax * inverseCellHeight), (int)spanMinCellIndex + 1, RC_SPAN_MAX_HEIGHT);
+
+ if (!addSpan(heightfield, x, z, spanMinCellIndex, spanMaxCellIndex, areaID, flagMergeThreshold))
+ {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+bool rcRasterizeTriangle(rcContext* context,
+ const float* v0, const float* v1, const float* v2,
+ const unsigned char areaID, rcHeightfield& heightfield, const int flagMergeThreshold)
+{
+ rcAssert(context != NULL);
+
+ rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
+
+ // Rasterize the single triangle.
+ const float inverseCellSize = 1.0f / heightfield.cs;
+ const float inverseCellHeight = 1.0f / heightfield.ch;
+ if (!rasterizeTri(v0, v1, v2, areaID, heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
+ {
+ context->log(RC_LOG_ERROR, "rcRasterizeTriangle: Out of memory.");
+ return false;
+ }
+
+ return true;
+}
+
+bool rcRasterizeTriangles(rcContext* context,
+ const float* verts, const int /*nv*/,
+ const int* tris, const unsigned char* triAreaIDs, const int numTris,
+ rcHeightfield& heightfield, const int flagMergeThreshold)
+{
+ rcAssert(context != NULL);
+
+ rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
+
+ // Rasterize the triangles.
+ const float inverseCellSize = 1.0f / heightfield.cs;
+ const float inverseCellHeight = 1.0f / heightfield.ch;
+ for (int triIndex = 0; triIndex < numTris; ++triIndex)
+ {
+ const float* v0 = &verts[tris[triIndex * 3 + 0] * 3];
+ const float* v1 = &verts[tris[triIndex * 3 + 1] * 3];
+ const float* v2 = &verts[tris[triIndex * 3 + 2] * 3];
+ if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
+ {
+ context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool rcRasterizeTriangles(rcContext* context,
+ const float* verts, const int /*nv*/,
+ const unsigned short* tris, const unsigned char* triAreaIDs, const int numTris,
+ rcHeightfield& heightfield, const int flagMergeThreshold)
+{
+ rcAssert(context != NULL);
+
+ rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
+
+ // Rasterize the triangles.
+ const float inverseCellSize = 1.0f / heightfield.cs;
+ const float inverseCellHeight = 1.0f / heightfield.ch;
+ for (int triIndex = 0; triIndex < numTris; ++triIndex)
+ {
+ const float* v0 = &verts[tris[triIndex * 3 + 0] * 3];
+ const float* v1 = &verts[tris[triIndex * 3 + 1] * 3];
+ const float* v2 = &verts[tris[triIndex * 3 + 2] * 3];
+ if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
+ {
+ context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool rcRasterizeTriangles(rcContext* context,
+ const float* verts, const unsigned char* triAreaIDs, const int numTris,
+ rcHeightfield& heightfield, const int flagMergeThreshold)
+{
+ rcAssert(context != NULL);
+
+ rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
+
+ // Rasterize the triangles.
+ const float inverseCellSize = 1.0f / heightfield.cs;
+ const float inverseCellHeight = 1.0f / heightfield.ch;
+ for (int triIndex = 0; triIndex < numTris; ++triIndex)
+ {
+ const float* v0 = &verts[(triIndex * 3 + 0) * 3];
+ const float* v1 = &verts[(triIndex * 3 + 1) * 3];
+ const float* v2 = &verts[(triIndex * 3 + 2) * 3];
+ if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
+ {
+ context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
+ return false;
+ }
+ }
+
+ return true;
+}
diff --git a/native/third_party/recastnavigation/Recast/Source/RecastRegion.cpp b/native/third_party/recastnavigation/Recast/Source/RecastRegion.cpp
new file mode 100644
index 0000000..48eed36
--- /dev/null
+++ b/native/third_party/recastnavigation/Recast/Source/RecastRegion.cpp
@@ -0,0 +1,1820 @@
+//
+// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
+//
+// 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
+#include
+#include
+#include
+#include
+#include "Recast.h"
+#include "RecastAlloc.h"
+#include "RecastAssert.h"
+
+namespace
+{
+struct LevelStackEntry
+{
+ LevelStackEntry(int x_, int y_, int index_) : x(x_), y(y_), index(index_) {}
+ int x;
+ int y;
+ int index;
+};
+} // namespace
+
+static void calculateDistanceField(rcCompactHeightfield& chf, unsigned short* src, unsigned short& maxDist)
+{
+ const int w = chf.width;
+ const int h = chf.height;
+
+ // Init distance and points.
+ for (int i = 0; i < chf.spanCount; ++i)
+ src[i] = 0xffff;
+
+ // Mark boundary cells.
+ for (int y = 0; y < h; ++y)
+ {
+ for (int x = 0; x < w; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+ const unsigned char area = chf.areas[i];
+
+ int nc = 0;
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dir);
+ const int ay = y + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
+ if (area == chf.areas[ai])
+ nc++;
+ }
+ }
+ if (nc != 4)
+ src[i] = 0;
+ }
+ }
+ }
+
+
+ // Pass 1
+ for (int y = 0; y < h; ++y)
+ {
+ for (int x = 0; x < w; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+
+ if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
+ {
+ // (-1,0)
+ const int ax = x + rcGetDirOffsetX(0);
+ const int ay = y + rcGetDirOffsetY(0);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
+ const rcCompactSpan& as = chf.spans[ai];
+ if (src[ai]+2 < src[i])
+ src[i] = src[ai]+2;
+
+ // (-1,-1)
+ if (rcGetCon(as, 3) != RC_NOT_CONNECTED)
+ {
+ const int aax = ax + rcGetDirOffsetX(3);
+ const int aay = ay + rcGetDirOffsetY(3);
+ const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 3);
+ if (src[aai]+3 < src[i])
+ src[i] = src[aai]+3;
+ }
+ }
+ if (rcGetCon(s, 3) != RC_NOT_CONNECTED)
+ {
+ // (0,-1)
+ const int ax = x + rcGetDirOffsetX(3);
+ const int ay = y + rcGetDirOffsetY(3);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
+ const rcCompactSpan& as = chf.spans[ai];
+ if (src[ai]+2 < src[i])
+ src[i] = src[ai]+2;
+
+ // (1,-1)
+ if (rcGetCon(as, 2) != RC_NOT_CONNECTED)
+ {
+ const int aax = ax + rcGetDirOffsetX(2);
+ const int aay = ay + rcGetDirOffsetY(2);
+ const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 2);
+ if (src[aai]+3 < src[i])
+ src[i] = src[aai]+3;
+ }
+ }
+ }
+ }
+ }
+
+ // Pass 2
+ for (int y = h-1; y >= 0; --y)
+ {
+ for (int x = w-1; x >= 0; --x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+
+ if (rcGetCon(s, 2) != RC_NOT_CONNECTED)
+ {
+ // (1,0)
+ const int ax = x + rcGetDirOffsetX(2);
+ const int ay = y + rcGetDirOffsetY(2);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 2);
+ const rcCompactSpan& as = chf.spans[ai];
+ if (src[ai]+2 < src[i])
+ src[i] = src[ai]+2;
+
+ // (1,1)
+ if (rcGetCon(as, 1) != RC_NOT_CONNECTED)
+ {
+ const int aax = ax + rcGetDirOffsetX(1);
+ const int aay = ay + rcGetDirOffsetY(1);
+ const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 1);
+ if (src[aai]+3 < src[i])
+ src[i] = src[aai]+3;
+ }
+ }
+ if (rcGetCon(s, 1) != RC_NOT_CONNECTED)
+ {
+ // (0,1)
+ const int ax = x + rcGetDirOffsetX(1);
+ const int ay = y + rcGetDirOffsetY(1);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 1);
+ const rcCompactSpan& as = chf.spans[ai];
+ if (src[ai]+2 < src[i])
+ src[i] = src[ai]+2;
+
+ // (-1,1)
+ if (rcGetCon(as, 0) != RC_NOT_CONNECTED)
+ {
+ const int aax = ax + rcGetDirOffsetX(0);
+ const int aay = ay + rcGetDirOffsetY(0);
+ const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 0);
+ if (src[aai]+3 < src[i])
+ src[i] = src[aai]+3;
+ }
+ }
+ }
+ }
+ }
+
+ maxDist = 0;
+ for (int i = 0; i < chf.spanCount; ++i)
+ maxDist = rcMax(src[i], maxDist);
+
+}
+
+static unsigned short* boxBlur(rcCompactHeightfield& chf, int thr,
+ unsigned short* src, unsigned short* dst)
+{
+ const int w = chf.width;
+ const int h = chf.height;
+
+ thr *= 2;
+
+ for (int y = 0; y < h; ++y)
+ {
+ for (int x = 0; x < w; ++x)
+ {
+ const rcCompactCell& c = chf.cells[x+y*w];
+ for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
+ {
+ const rcCompactSpan& s = chf.spans[i];
+ const unsigned short cd = src[i];
+ if (cd <= thr)
+ {
+ dst[i] = cd;
+ continue;
+ }
+
+ int d = (int)cd;
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = x + rcGetDirOffsetX(dir);
+ const int ay = y + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
+ d += (int)src[ai];
+
+ const rcCompactSpan& as = chf.spans[ai];
+ const int dir2 = (dir+1) & 0x3;
+ if (rcGetCon(as, dir2) != RC_NOT_CONNECTED)
+ {
+ const int ax2 = ax + rcGetDirOffsetX(dir2);
+ const int ay2 = ay + rcGetDirOffsetY(dir2);
+ const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
+ d += (int)src[ai2];
+ }
+ else
+ {
+ d += cd;
+ }
+ }
+ else
+ {
+ d += cd*2;
+ }
+ }
+ dst[i] = (unsigned short)((d+5)/9);
+ }
+ }
+ }
+ return dst;
+}
+
+
+static bool floodRegion(int x, int y, int i,
+ unsigned short level, unsigned short r,
+ rcCompactHeightfield& chf,
+ unsigned short* srcReg, unsigned short* srcDist,
+ rcTempVector& stack)
+{
+ const int w = chf.width;
+
+ const unsigned char area = chf.areas[i];
+
+ // Flood fill mark region.
+ stack.clear();
+ stack.push_back(LevelStackEntry(x, y, i));
+ srcReg[i] = r;
+ srcDist[i] = 0;
+
+ unsigned short lev = level >= 2 ? level-2 : 0;
+ int count = 0;
+
+ while (stack.size() > 0)
+ {
+ LevelStackEntry& back = stack.back();
+ int cx = back.x;
+ int cy = back.y;
+ int ci = back.index;
+ stack.pop_back();
+
+ const rcCompactSpan& cs = chf.spans[ci];
+
+ // Check if any of the neighbours already have a valid region set.
+ unsigned short ar = 0;
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ // 8 connected
+ if (rcGetCon(cs, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = cx + rcGetDirOffsetX(dir);
+ const int ay = cy + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
+ if (chf.areas[ai] != area)
+ continue;
+ unsigned short nr = srcReg[ai];
+ if (nr & RC_BORDER_REG) // Do not take borders into account.
+ continue;
+ if (nr != 0 && nr != r)
+ {
+ ar = nr;
+ break;
+ }
+
+ const rcCompactSpan& as = chf.spans[ai];
+
+ const int dir2 = (dir+1) & 0x3;
+ if (rcGetCon(as, dir2) != RC_NOT_CONNECTED)
+ {
+ const int ax2 = ax + rcGetDirOffsetX(dir2);
+ const int ay2 = ay + rcGetDirOffsetY(dir2);
+ const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
+ if (chf.areas[ai2] != area)
+ continue;
+ unsigned short nr2 = srcReg[ai2];
+ if (nr2 != 0 && nr2 != r)
+ {
+ ar = nr2;
+ break;
+ }
+ }
+ }
+ }
+ if (ar != 0)
+ {
+ srcReg[ci] = 0;
+ continue;
+ }
+
+ count++;
+
+ // Expand neighbours.
+ for (int dir = 0; dir < 4; ++dir)
+ {
+ if (rcGetCon(cs, dir) != RC_NOT_CONNECTED)
+ {
+ const int ax = cx + rcGetDirOffsetX(dir);
+ const int ay = cy + rcGetDirOffsetY(dir);
+ const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
+ if (chf.areas[ai] != area)
+ continue;
+ if (chf.dist[ai] >= lev && srcReg[ai] == 0)
+ {
+ srcReg[ai] = r;
+ srcDist[ai] = 0;
+ stack.push_back(LevelStackEntry(ax, ay, ai));
+ }
+ }
+ }
+ }
+
+ return count > 0;
+}
+
+// Struct to keep track of entries in the region table that have been changed.
+struct DirtyEntry
+{
+ DirtyEntry(int index_, unsigned short region_, unsigned short distance2_)
+ : index(index_), region(region_), distance2(distance2_) {}
+ int index;
+ unsigned short region;
+ unsigned short distance2;
+};
+static void expandRegions(int maxIter, unsigned short level,
+ rcCompactHeightfield& chf,
+ unsigned short* srcReg, unsigned short* srcDist,
+ rcTempVector