chore(ground-ai): checkpoint 3d replay and simulator work
This commit is contained in:
1 parent
f8bd79042b
commit
b276e686b0
47 files changed
+2613
-688
No files matched your search
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps",
|
||||
"geoDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/work",
|
||||
"logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs",
|
||||
"python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe"
|
||||
}
|
||||
@@ -11,11 +11,13 @@
|
||||
"dependencies": {
|
||||
"@wto/ground-sim": "*",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
"react-dom": "^19.2.8",
|
||||
"three": "^0.187.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/three": "^0.187.0",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"vite": "^7.3.6"
|
||||
}
|
||||
|
||||
@@ -4,17 +4,22 @@
|
||||
* GET /api/maps/file?name= a pack or POI file of mapsDir
|
||||
* GET /api/logs game logs (.clog) in logsDir, newest first
|
||||
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
|
||||
* GET /api/scene?name= the 3D map (.wtoscene) of a level, built from its .wtogeo in geoDir
|
||||
* (cached until the geometry changes)
|
||||
* Paths come from lab.local.json next to this app (see lab.local.example.json).
|
||||
*/
|
||||
import { execFile } from 'node:child_process';
|
||||
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
||||
import type { ServerResponse } from 'node:http';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { buildMapScene, encodeMapScene, readGeo } from '@wto/ground-sim';
|
||||
import type { Connect, Plugin } from 'vite';
|
||||
|
||||
interface LabConfig {
|
||||
readonly mapsDir: string;
|
||||
/** Where the navigation bake left the levels' .wtogeo geometry. */
|
||||
readonly geoDir: string;
|
||||
readonly logsDir: string;
|
||||
readonly python: string;
|
||||
}
|
||||
@@ -27,8 +32,10 @@ function loadConfig(): LabConfig {
|
||||
const file = path.join(APP_DIR, 'lab.local.json');
|
||||
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
|
||||
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
|
||||
const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps'));
|
||||
return {
|
||||
mapsDir: str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')),
|
||||
mapsDir,
|
||||
geoDir: str('geoDir', path.join(mapsDir, '..', 'work')),
|
||||
logsDir: str('logsDir', ''),
|
||||
python: str('python', 'python'),
|
||||
};
|
||||
@@ -46,13 +53,17 @@ function sendFile(res: ServerResponse, file: string, type: string): void {
|
||||
createReadStream(file).pipe(res);
|
||||
}
|
||||
|
||||
function listMaps(cfg: LabConfig): { level: string; pois: boolean }[] {
|
||||
function listMaps(cfg: LabConfig): { level: string; pois: boolean; scene: boolean }[] {
|
||||
if (!existsSync(cfg.mapsDir)) return [];
|
||||
return readdirSync(cfg.mapsDir)
|
||||
.filter((f) => f.endsWith('.wtonav'))
|
||||
.map((f) => {
|
||||
const level = f.slice(0, -'.wtonav'.length);
|
||||
return { level, pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)) };
|
||||
return {
|
||||
level,
|
||||
pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)),
|
||||
scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -81,12 +92,30 @@ function decryptLog(cfg: LabConfig, name: string): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
/** Builds the level's 3D map into the cache unless the cached one is newer than its geometry. */
|
||||
function sceneFile(cfg: LabConfig, level: string): string | undefined {
|
||||
const geo = path.join(cfg.geoDir, `${level}.wtogeo`);
|
||||
if (!existsSync(geo)) return undefined;
|
||||
const out = path.join(CACHE_DIR, `${level}.wtoscene`);
|
||||
if (existsSync(out) && statSync(out).mtimeMs >= statSync(geo).mtimeMs) return out;
|
||||
mkdirSync(CACHE_DIR, { recursive: true });
|
||||
writeFileSync(out, encodeMapScene(buildMapScene(readGeo(readFileSync(geo)))));
|
||||
return out;
|
||||
}
|
||||
|
||||
async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise<boolean> {
|
||||
const name = url.searchParams.get('name') ?? '';
|
||||
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
|
||||
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
|
||||
if (url.pathname !== '/api/maps/file' && url.pathname !== '/api/logs/text') return false;
|
||||
const known = ['/api/maps/file', '/api/logs/text', '/api/scene'];
|
||||
if (!known.includes(url.pathname)) return false;
|
||||
if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; }
|
||||
if (url.pathname === '/api/scene') {
|
||||
const file = sceneFile(cfg, name);
|
||||
if (file === undefined) sendJson(res, 404, { error: `no ${name}.wtogeo in ${cfg.geoDir}` });
|
||||
else sendFile(res, file, 'application/octet-stream');
|
||||
return true;
|
||||
}
|
||||
if (url.pathname === '/api/maps/file') {
|
||||
const file = path.join(cfg.mapsDir, name);
|
||||
if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` });
|
||||
|
||||
+14
-9
@@ -2,17 +2,20 @@
|
||||
import type { TraceBattle } from '@wto/ground-sim';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts';
|
||||
import type { Layers } from './draw.ts';
|
||||
import { sceneAt } from './frames.ts';
|
||||
import { Inspector } from './Inspector.tsx';
|
||||
import { Map3D, type MapLook } from './Map3D.tsx';
|
||||
import { buildMapLayer } from './mapLayer.ts';
|
||||
import { MapView } from './MapView.tsx';
|
||||
import type { ViewMode } from './three/cameraRig.ts';
|
||||
import type { Layers } from './three/overlays.ts';
|
||||
import { Timeline } from './Timeline.tsx';
|
||||
|
||||
const LAYER_LABELS: Readonly<Record<keyof Layers, string>> = {
|
||||
goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击',
|
||||
};
|
||||
|
||||
const VIEW_LABELS: Readonly<Record<ViewMode, string>> = { top: '俯视', free: '自由', follow: '跟随选中车', gun: '炮口视角' };
|
||||
|
||||
function logLabel(l: LogEntry): string {
|
||||
const when = new Date(l.mtime).toLocaleString();
|
||||
return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`;
|
||||
@@ -27,6 +30,7 @@ export function App(): React.JSX.Element {
|
||||
const [mapData, setMapData] = useState<MapData | undefined>(undefined);
|
||||
const [exposure, setExposure] = useState(false);
|
||||
const [covers, setCovers] = useState(false);
|
||||
const [look, setLook] = useState<MapLook>({ view: 'top', navImage: true, objects: true, crushable: true });
|
||||
const [layers, setLayers] = useState<Layers>({ goals: true, links: true, cones: false, labels: false, events: true });
|
||||
const [t, setT] = useState(0);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
@@ -75,12 +79,6 @@ export function App(): React.JSX.Element {
|
||||
() => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })),
|
||||
[mapData, exposure, covers],
|
||||
);
|
||||
const bounds = useMemo((): readonly [number, number, number, number] | undefined => {
|
||||
if (mapData === undefined) return undefined;
|
||||
const p = mapData.pois;
|
||||
if (p !== undefined) return [p.boundsMin[0], p.boundsMin[1], p.boundsMax[0], p.boundsMax[1]];
|
||||
return [mapData.pack.header.bmin[0], mapData.pack.header.bmin[2], mapData.pack.header.bmax[0], mapData.pack.header.bmax[2]];
|
||||
}, [mapData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!playing || battle === undefined) return;
|
||||
@@ -121,13 +119,20 @@ export function App(): React.JSX.Element {
|
||||
{LAYER_LABELS[k]}
|
||||
</label>
|
||||
))}
|
||||
<select value={look.view} onChange={(e) => setLook({ ...look, view: e.target.value as ViewMode })}>
|
||||
{(Object.keys(VIEW_LABELS) as ViewMode[]).map((v) => <option key={v} value={v}>{VIEW_LABELS[v]}</option>)}
|
||||
</select>
|
||||
<label><input type="checkbox" checked={look.navImage} onChange={(e) => setLook({ ...look, navImage: e.target.checked })} />导航网格</label>
|
||||
<label><input type="checkbox" checked={look.objects} onChange={(e) => setLook({ ...look, objects: e.target.checked })} />物体</label>
|
||||
<label><input type="checkbox" checked={look.crushable} onChange={(e) => setLook({ ...look, crushable: e.target.checked })} />可碾压物</label>
|
||||
<label><input type="checkbox" checked={exposure} onChange={(e) => setExposure(e.target.checked)} />暴露度</label>
|
||||
<label><input type="checkbox" checked={covers} onChange={(e) => setCovers(e.target.checked)} />掩体点</label>
|
||||
{status !== '' && <span className="status">{status}</span>}
|
||||
{battle !== undefined && battle.frames.length === 0 && <span className="status">这一局没有轨迹(游戏里没开 diagnostics.trace)。</span>}
|
||||
</header>
|
||||
<main>
|
||||
<MapView map={mapLayer} bounds={bounds} battle={battle} scene={scene} selected={selected} layers={layers} onSelect={setSelected} />
|
||||
<Map3D mapScene={mapData?.scene} nav={mapLayer} battle={battle} scene={scene} selected={selected}
|
||||
layers={layers} look={look} onSelect={setSelected} />
|
||||
{battle !== undefined && <Inspector battle={battle} scene={scene} selected={selected} />}
|
||||
</main>
|
||||
{battle !== undefined && (
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* The battle in 3D: terrain and object collision shapes of the level, vehicles as simple shapes,
|
||||
* and the replay's lines and markers. Left drag pans, right drag turns (except top-down), wheel
|
||||
* zooms; a click on a vehicle selects it.
|
||||
*/
|
||||
import { BEHAVIOR_NAMES, type MapScene, type TraceBattle } from '@wto/ground-sim';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { AmbientLight, Color, DirectionalLight, HemisphereLight, Raycaster, Scene, Vector2, WebGLRenderer } from 'three';
|
||||
import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';
|
||||
import type { SceneAt, UnitAt } from './frames.ts';
|
||||
import type { MapLayer } from './mapLayer.ts';
|
||||
import { CameraRig, type ViewMode } from './three/cameraRig.ts';
|
||||
import { buildMapMeshes, setTerrainImage, type MapMeshes } from './three/mapMeshes.ts';
|
||||
import { Overlays, type Layers } from './three/overlays.ts';
|
||||
import { TankPool } from './three/tanks.ts';
|
||||
|
||||
export interface MapLook {
|
||||
readonly view: ViewMode;
|
||||
/** Drape the navigation mesh image over the terrain instead of height colours. */
|
||||
readonly navImage: boolean;
|
||||
readonly objects: boolean;
|
||||
readonly crushable: boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
readonly mapScene: MapScene | undefined;
|
||||
readonly nav: MapLayer | undefined;
|
||||
readonly battle: TraceBattle | undefined;
|
||||
readonly scene: SceneAt | undefined;
|
||||
readonly selected: string | undefined;
|
||||
readonly layers: Layers;
|
||||
readonly look: MapLook;
|
||||
readonly onSelect: (eid: string | undefined) => void;
|
||||
}
|
||||
|
||||
interface World {
|
||||
readonly renderer: WebGLRenderer;
|
||||
readonly labels: CSS2DRenderer;
|
||||
readonly scene: Scene;
|
||||
readonly rig: CameraRig;
|
||||
map: MapMeshes | undefined;
|
||||
tanks: TankPool;
|
||||
overlays: Overlays;
|
||||
selected: string | undefined;
|
||||
}
|
||||
|
||||
const CRUSHABLE_KIND = 3;
|
||||
const CLICK_PX = 4;
|
||||
|
||||
function labelOf(u: UnitAt): string {
|
||||
const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : '';
|
||||
return `${u.unit.eid.replace(/^0x/, '')} ${name}`;
|
||||
}
|
||||
|
||||
function createWorld(host: HTMLDivElement): World {
|
||||
const renderer = new WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
|
||||
renderer.setPixelRatio(window.devicePixelRatio);
|
||||
host.appendChild(renderer.domElement);
|
||||
const labels = new CSS2DRenderer();
|
||||
labels.domElement.className = 'labels3d';
|
||||
host.appendChild(labels.domElement);
|
||||
const scene = new Scene();
|
||||
scene.background = new Color(0x0b0c0d);
|
||||
scene.add(new HemisphereLight(0xdfe8ff, 0x3a3326, 1.4), new AmbientLight(0xffffff, 0.25));
|
||||
const sun = new DirectionalLight(0xffffff, 1.6);
|
||||
sun.position.set(0.5, 1, 0.3);
|
||||
scene.add(sun);
|
||||
const tanks = new TankPool(undefined);
|
||||
const overlays = new Overlays(tanks);
|
||||
scene.add(tanks.group, overlays.group);
|
||||
return { renderer, labels, scene, rig: new CameraRig(renderer.domElement), map: undefined, tanks, overlays, selected: undefined };
|
||||
}
|
||||
|
||||
function replaceMap(w: World, mapScene: MapScene | undefined, nav: MapLayer | undefined): void {
|
||||
if (w.map !== undefined) { w.scene.remove(w.map.group); w.map.dispose(); }
|
||||
w.scene.remove(w.tanks.group, w.overlays.group);
|
||||
w.tanks.dispose();
|
||||
w.overlays.dispose();
|
||||
w.map = mapScene === undefined ? undefined : buildMapMeshes(mapScene, nav);
|
||||
w.tanks = new TankPool(mapScene?.terrain);
|
||||
w.overlays = new Overlays(w.tanks);
|
||||
if (w.map !== undefined) w.scene.add(w.map.group);
|
||||
w.scene.add(w.tanks.group, w.overlays.group);
|
||||
if (mapScene !== undefined) {
|
||||
const t = mapScene.terrain;
|
||||
let sum = 0;
|
||||
for (const h of t.heights) sum += h;
|
||||
w.rig.fit(mapScene.boundsMin[0], mapScene.boundsMin[1], mapScene.boundsMax[0], mapScene.boundsMax[1], sum / Math.max(1, t.heights.length));
|
||||
}
|
||||
}
|
||||
|
||||
export function Map3D({ mapScene, nav, battle, scene, selected, layers, look, onSelect }: Props): React.JSX.Element {
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const worldRef = useRef<World | undefined>(undefined);
|
||||
const onSelectRef = useRef(onSelect);
|
||||
onSelectRef.current = onSelect;
|
||||
|
||||
useEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (host === null) return;
|
||||
const w = createWorld(host);
|
||||
worldRef.current = w;
|
||||
const resize = (): void => {
|
||||
const r = host.getBoundingClientRect();
|
||||
w.renderer.setSize(r.width, r.height);
|
||||
w.labels.setSize(r.width, r.height);
|
||||
w.rig.resize(r.width, r.height);
|
||||
};
|
||||
const obs = new ResizeObserver(resize);
|
||||
obs.observe(host);
|
||||
resize();
|
||||
w.renderer.setAnimationLoop(() => {
|
||||
w.rig.tick(w.selected === undefined ? undefined : w.tanks.get(w.selected));
|
||||
w.renderer.render(w.scene, w.rig.camera);
|
||||
w.labels.render(w.scene, w.rig.camera);
|
||||
});
|
||||
const down = new Vector2();
|
||||
const el = w.renderer.domElement;
|
||||
const onDown = (e: PointerEvent): void => { down.set(e.clientX, e.clientY); };
|
||||
const onUp = (e: PointerEvent): void => {
|
||||
if (e.button !== 0 || Math.hypot(e.clientX - down.x, e.clientY - down.y) > CLICK_PX) return;
|
||||
const r = el.getBoundingClientRect();
|
||||
const ray = new Raycaster();
|
||||
ray.setFromCamera(new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), w.rig.camera);
|
||||
const hit = ray.intersectObjects(w.tanks.pickables(), false)[0];
|
||||
onSelectRef.current(hit?.object.userData['eid'] as string | undefined);
|
||||
};
|
||||
el.addEventListener('pointerdown', onDown);
|
||||
el.addEventListener('pointerup', onUp);
|
||||
return () => {
|
||||
obs.disconnect();
|
||||
el.removeEventListener('pointerdown', onDown);
|
||||
el.removeEventListener('pointerup', onUp);
|
||||
w.renderer.setAnimationLoop(null);
|
||||
replaceMap(w, undefined, undefined);
|
||||
w.rig.dispose();
|
||||
w.renderer.dispose();
|
||||
host.replaceChildren();
|
||||
worldRef.current = undefined;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const w = worldRef.current;
|
||||
if (w !== undefined) replaceMap(w, mapScene, nav);
|
||||
// The navigation image is applied by the effect below; only a new level rebuilds the map.
|
||||
}, [mapScene]);
|
||||
|
||||
useEffect(() => {
|
||||
const w = worldRef.current;
|
||||
if (w?.map !== undefined) setTerrainImage(w.map, look.navImage ? nav : undefined);
|
||||
}, [nav, look.navImage, mapScene]);
|
||||
|
||||
useEffect(() => {
|
||||
const w = worldRef.current;
|
||||
if (w?.map === undefined) return;
|
||||
w.map.kinds.forEach((g, k) => { g.visible = look.objects && (k !== CRUSHABLE_KIND || look.crushable); });
|
||||
}, [look.objects, look.crushable, mapScene]);
|
||||
|
||||
useEffect(() => {
|
||||
worldRef.current?.rig.setMode(look.view);
|
||||
}, [look.view]);
|
||||
|
||||
useEffect(() => {
|
||||
const w = worldRef.current;
|
||||
if (w === undefined) return;
|
||||
w.selected = selected;
|
||||
w.rig.refollow();
|
||||
}, [selected]);
|
||||
|
||||
useEffect(() => {
|
||||
const w = worldRef.current;
|
||||
if (w === undefined || battle === undefined || scene === undefined) return;
|
||||
w.tanks.update(scene.units, selected, (u) => (layers.labels && u.unit.alive ? labelOf(u) : undefined));
|
||||
w.overlays.update(battle, scene, layers);
|
||||
}, [battle, scene, selected, layers, mapScene]);
|
||||
|
||||
return <div ref={hostRef} className="map3d" />;
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/** The battle map: drag to pan, wheel to zoom, click a vehicle to select it. */
|
||||
import type { TraceBattle } from '@wto/ground-sim';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { drawScene, type Layers } from './draw.ts';
|
||||
import type { SceneAt } from './frames.ts';
|
||||
import type { MapLayer } from './mapLayer.ts';
|
||||
import { fitView, toScreen, zoomAt, type View } from './view.ts';
|
||||
|
||||
interface Props {
|
||||
readonly map: MapLayer | undefined;
|
||||
readonly bounds: readonly [number, number, number, number] | undefined;
|
||||
readonly battle: TraceBattle | undefined;
|
||||
readonly scene: SceneAt | undefined;
|
||||
readonly selected: string | undefined;
|
||||
readonly layers: Layers;
|
||||
readonly onSelect: (eid: string | undefined) => void;
|
||||
}
|
||||
|
||||
const PICK_PX = 14;
|
||||
|
||||
export function MapView({ map, bounds, battle, scene, selected, layers, onSelect }: Props): React.JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const [view, setView] = useState<View>({ cx: 0, cz: 0, scale: 1, w: 800, h: 600 });
|
||||
const drag = useRef<{ x: number; y: number; moved: boolean } | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (canvas === null) return;
|
||||
const resize = (): void => {
|
||||
const r = canvas.getBoundingClientRect();
|
||||
canvas.width = Math.max(1, Math.floor(r.width));
|
||||
canvas.height = Math.max(1, Math.floor(r.height));
|
||||
setView((v) => ({ ...v, w: canvas.width, h: canvas.height }));
|
||||
};
|
||||
const obs = new ResizeObserver(resize);
|
||||
obs.observe(canvas);
|
||||
resize();
|
||||
return () => obs.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (bounds === undefined) return;
|
||||
setView((v) => fitView(bounds[0], bounds[1], bounds[2], bounds[3], v.w, v.h));
|
||||
}, [bounds]);
|
||||
|
||||
useEffect(() => {
|
||||
const ctx = canvasRef.current?.getContext('2d');
|
||||
if (ctx === undefined || ctx === null) return;
|
||||
drawScene(ctx, view, map, battle, scene, selected, layers);
|
||||
}, [view, map, battle, scene, selected, layers]);
|
||||
|
||||
const pick = (sx: number, sy: number): string | undefined => {
|
||||
let best: string | undefined;
|
||||
let bestD = PICK_PX * PICK_PX;
|
||||
for (const u of scene?.units.values() ?? []) {
|
||||
const [x, y] = toScreen(view, u.x, u.z);
|
||||
const d = (x - sx) ** 2 + (y - sy) ** 2;
|
||||
if (d < bestD) { bestD = d; best = u.unit.eid; }
|
||||
}
|
||||
return best;
|
||||
};
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="map"
|
||||
onWheel={(e) => setView((v) => zoomAt(v, e.nativeEvent.offsetX, e.nativeEvent.offsetY, e.deltaY < 0 ? 1.2 : 1 / 1.2))}
|
||||
onMouseDown={(e) => { drag.current = { x: e.clientX, y: e.clientY, moved: false }; }}
|
||||
onMouseMove={(e) => {
|
||||
const d = drag.current;
|
||||
if (d === undefined) return;
|
||||
const dx = e.clientX - d.x;
|
||||
const dy = e.clientY - d.y;
|
||||
if (Math.abs(dx) + Math.abs(dy) > 2) d.moved = true;
|
||||
d.x = e.clientX;
|
||||
d.y = e.clientY;
|
||||
setView((v) => ({ ...v, cx: v.cx - dx / v.scale, cz: v.cz + dy / v.scale }));
|
||||
}}
|
||||
onMouseUp={(e) => {
|
||||
const d = drag.current;
|
||||
drag.current = undefined;
|
||||
if (d !== undefined && !d.moved) onSelect(pick(e.nativeEvent.offsetX, e.nativeEvent.offsetY));
|
||||
}}
|
||||
onMouseLeave={() => { drag.current = undefined; }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+10
-2
@@ -1,5 +1,7 @@
|
||||
/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */
|
||||
import { parsePois, parseTraceLog, readNavPack, type MapPois, type NavPack, type TraceBattle } from '@wto/ground-sim';
|
||||
import {
|
||||
decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle,
|
||||
} from '@wto/ground-sim';
|
||||
|
||||
export interface LogEntry {
|
||||
readonly name: string;
|
||||
@@ -10,11 +12,14 @@ export interface LogEntry {
|
||||
export interface MapEntry {
|
||||
readonly level: string;
|
||||
readonly pois: boolean;
|
||||
/** The level's geometry is there, so it has a 3D map. */
|
||||
readonly scene: boolean;
|
||||
}
|
||||
|
||||
export interface MapData {
|
||||
readonly pack: NavPack;
|
||||
readonly pois: MapPois | undefined;
|
||||
readonly scene: MapScene | undefined;
|
||||
}
|
||||
|
||||
async function get(url: string): Promise<Response> {
|
||||
@@ -44,5 +49,8 @@ export async function loadMap(entry: MapEntry): Promise<MapData> {
|
||||
const pois = entry.pois
|
||||
? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text())
|
||||
: undefined;
|
||||
return { pack: readNavPack(bytes), pois };
|
||||
const scene = entry.scene
|
||||
? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer()))
|
||||
: undefined;
|
||||
return { pack: readNavPack(bytes), pois, scene };
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
/** Everything drawn over the static map for one moment of the replay. */
|
||||
import { BEHAVIOR_NAMES, type TraceBattle } from '@wto/ground-sim';
|
||||
import { eventsBetween, type SceneAt, type UnitAt } from './frames.ts';
|
||||
import type { MapLayer } from './mapLayer.ts';
|
||||
import { screenDir, toScreen, type View } from './view.ts';
|
||||
|
||||
export interface Layers {
|
||||
readonly goals: boolean;
|
||||
readonly links: boolean;
|
||||
readonly cones: boolean;
|
||||
readonly labels: boolean;
|
||||
readonly events: boolean;
|
||||
}
|
||||
|
||||
export const ARMY_COLORS: Readonly<Record<number, string>> = { 1: '#4aa3ff', 2: '#ff5c5c' };
|
||||
|
||||
const GUN_FOV_HALF_DEG = 30;
|
||||
const CONE_M = 120;
|
||||
const EVENT_WINDOW_SEC = 2;
|
||||
|
||||
function line(ctx: CanvasRenderingContext2D, ax: number, ay: number, bx: number, by: number): void {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(ax, ay);
|
||||
ctx.lineTo(bx, by);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
function drawHull(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, selected: boolean): void {
|
||||
const [sx, sy] = toScreen(v, u.x, u.z);
|
||||
const [dx, dy] = screenDir(u.yaw);
|
||||
const len = Math.max(5, (u.unit.light ? 3 : 3.6) * v.scale);
|
||||
const wid = Math.max(3, 1.7 * v.scale);
|
||||
ctx.save();
|
||||
ctx.translate(sx, sy);
|
||||
ctx.rotate(Math.atan2(dy, dx));
|
||||
ctx.fillStyle = u.unit.alive ? (ARMY_COLORS[u.unit.army] ?? '#ccc') : '#555';
|
||||
ctx.fillRect(-len, -wid, len * 2, wid * 2);
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(len * 0.6, -wid * 0.5, len * 0.4, wid);
|
||||
if (u.unit.human || selected) {
|
||||
ctx.strokeStyle = selected ? '#ffe14a' : '#fff';
|
||||
ctx.lineWidth = selected ? 3 : 1.5;
|
||||
ctx.strokeRect(-len - 2, -wid - 2, len * 2 + 4, wid * 2 + 4);
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawBotIntent(ctx: CanvasRenderingContext2D, v: View, u: UnitAt, scene: SceneAt, layers: Layers): void {
|
||||
const bot = u.bot;
|
||||
if (bot === undefined || !u.unit.alive) return;
|
||||
const [sx, sy] = toScreen(v, u.x, u.z);
|
||||
if (layers.goals && bot.hasOrder) {
|
||||
const [gx, gy] = toScreen(v, bot.goalX, bot.goalZ);
|
||||
ctx.setLineDash([4, 6]);
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.25)';
|
||||
ctx.lineWidth = 1;
|
||||
line(ctx, sx, sy, gx, gy);
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
if (bot.gunYaw !== undefined) {
|
||||
const [dx, dy] = screenDir(bot.gunYaw);
|
||||
if (layers.cones) {
|
||||
const r = CONE_M * v.scale;
|
||||
const a = Math.atan2(dy, dx);
|
||||
const half = (GUN_FOV_HALF_DEG * Math.PI) / 180;
|
||||
ctx.fillStyle = 'rgba(255,255,200,0.07)';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(sx, sy);
|
||||
ctx.arc(sx, sy, r, a - half, a + half);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
}
|
||||
const gl = Math.max(14, 8 * v.scale);
|
||||
ctx.strokeStyle = '#fff';
|
||||
ctx.lineWidth = 2;
|
||||
line(ctx, sx, sy, sx + dx * gl, sy + dy * gl);
|
||||
}
|
||||
const [wx, wy] = screenDir(bot.wishYaw);
|
||||
const wl = Math.max(22, 14 * v.scale);
|
||||
ctx.setLineDash([2, 3]);
|
||||
ctx.strokeStyle = 'rgba(255,225,74,0.8)';
|
||||
ctx.lineWidth = 1;
|
||||
line(ctx, sx, sy, sx + wx * wl, sy + wy * wl);
|
||||
ctx.setLineDash([]);
|
||||
if (!layers.links) return;
|
||||
const target = scene.units.get(bot.target);
|
||||
if (target !== undefined && bot.target !== '0') {
|
||||
const [tx, ty] = toScreen(v, target.x, target.z);
|
||||
ctx.strokeStyle = bot.targetInSight ? 'rgba(255,70,70,0.85)' : 'rgba(255,70,70,0.3)';
|
||||
ctx.lineWidth = 1.5;
|
||||
line(ctx, sx, sy, tx, ty);
|
||||
}
|
||||
const look = scene.units.get(bot.lookAt);
|
||||
if (look !== undefined && bot.lookAt !== bot.target) {
|
||||
const [lx, ly] = toScreen(v, look.x, look.z);
|
||||
ctx.strokeStyle = 'rgba(255,160,40,0.85)';
|
||||
ctx.lineWidth = 1.5;
|
||||
line(ctx, sx, sy, lx, ly);
|
||||
}
|
||||
}
|
||||
|
||||
function drawLabel(ctx: CanvasRenderingContext2D, v: View, u: UnitAt): void {
|
||||
const [sx, sy] = toScreen(v, u.x, u.z);
|
||||
const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : '';
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.85)';
|
||||
ctx.font = '11px sans-serif';
|
||||
ctx.fillText(`${u.unit.eid.replace(/^0x/, '')} ${name}`, sx + 8, sy - 8);
|
||||
}
|
||||
|
||||
function drawEvents(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, scene: SceneAt): void {
|
||||
for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) {
|
||||
const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC;
|
||||
if (e.kind === 'SHOT' && e.eid !== undefined) {
|
||||
const from = scene.units.get(e.eid);
|
||||
const to = scene.units.get(e.fields['tgt'] ?? '');
|
||||
if (from === undefined || to === undefined) continue;
|
||||
const [ax, ay] = toScreen(v, from.x, from.z);
|
||||
const [bx, by] = toScreen(v, to.x, to.z);
|
||||
ctx.strokeStyle = `rgba(255,255,120,${fade})`;
|
||||
ctx.lineWidth = 2;
|
||||
line(ctx, ax, ay, bx, by);
|
||||
} else if (e.kind === 'HIT') {
|
||||
const [hx, hy] = toScreen(v, Number(e.fields['x']), Number(e.fields['z']));
|
||||
ctx.fillStyle = e.fields['drop'] === '1' ? `rgba(255,60,60,${fade})` : `rgba(200,200,200,${fade})`;
|
||||
ctx.beginPath();
|
||||
ctx.arc(hx, hy, 4, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawDeaths(ctx: CanvasRenderingContext2D, v: View, battle: TraceBattle, t: number): void {
|
||||
ctx.lineWidth = 2;
|
||||
for (const e of eventsBetween(battle, battle.startT, t)) {
|
||||
if (e.kind !== 'DEATH') continue;
|
||||
const [x, y] = toScreen(v, Number(e.fields['x']), Number(e.fields['z']));
|
||||
ctx.strokeStyle = e.fields['army'] === '1' ? 'rgba(74,163,255,0.6)' : 'rgba(255,92,92,0.6)';
|
||||
line(ctx, x - 5, y - 5, x + 5, y + 5);
|
||||
line(ctx, x - 5, y + 5, x + 5, y - 5);
|
||||
}
|
||||
}
|
||||
|
||||
export function drawScene(ctx: CanvasRenderingContext2D, v: View, map: MapLayer | undefined, battle: TraceBattle | undefined,
|
||||
scene: SceneAt | undefined, selected: string | undefined, layers: Layers): void {
|
||||
ctx.fillStyle = '#0b0c0d';
|
||||
ctx.fillRect(0, 0, v.w, v.h);
|
||||
if (map !== undefined) {
|
||||
const [mx, my] = toScreen(v, map.x0, map.z1);
|
||||
const k = v.scale / map.pxPerM;
|
||||
ctx.imageSmoothingEnabled = k < 1;
|
||||
ctx.drawImage(map.canvas, mx, my, map.canvas.width * k, map.canvas.height * k);
|
||||
}
|
||||
if (battle === undefined || scene === undefined) return;
|
||||
for (const cap of scene.caps) {
|
||||
const [cx, cy] = toScreen(v, cap.x, cap.z);
|
||||
ctx.strokeStyle = ARMY_COLORS[cap.owner] ?? '#ddd';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, Math.max(4, cap.r * v.scale), 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
}
|
||||
drawDeaths(ctx, v, battle, scene.t);
|
||||
const units = [...scene.units.values()];
|
||||
for (const u of units) drawBotIntent(ctx, v, u, scene, layers);
|
||||
if (layers.events) drawEvents(ctx, v, battle, scene);
|
||||
for (const u of units) drawHull(ctx, v, u, u.unit.eid === selected);
|
||||
if (layers.labels) for (const u of units) if (u.unit.alive) drawLabel(ctx, v, u);
|
||||
}
|
||||
@@ -3,10 +3,16 @@ import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '
|
||||
|
||||
export interface UnitAt {
|
||||
readonly unit: UnitSample;
|
||||
/** Interpolated position and heading. */
|
||||
/** Interpolated position, hull heading, pitch and roll. */
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly z: number;
|
||||
readonly yaw: number;
|
||||
readonly hullPitch: number;
|
||||
readonly hullRoll: number;
|
||||
/** Interpolated gun world yaw and pitch; from the bot line, or the hull, when the unit line has none. */
|
||||
readonly gunYaw: number;
|
||||
readonly gunPitch: number;
|
||||
/** Decision state of the sample at or before the time; undefined for players. */
|
||||
readonly bot: BotSample | undefined;
|
||||
}
|
||||
@@ -34,6 +40,14 @@ function lerpYaw(a: number, b: number, k: number): number {
|
||||
return a + d * k;
|
||||
}
|
||||
|
||||
function lerp(a: number, b: number | undefined, k: number): number {
|
||||
return a + ((b ?? a) - a) * k;
|
||||
}
|
||||
|
||||
function gunOf(u: UnitSample, bot: BotSample | undefined): [number, number] {
|
||||
return [u.gunYaw ?? bot?.gunYaw ?? u.yaw, u.gunPitch ?? 0];
|
||||
}
|
||||
|
||||
export function sceneAt(battle: TraceBattle, t: number): SceneAt {
|
||||
const i = Math.max(0, frameIndexAt(battle, t));
|
||||
const a = battle.frames[i];
|
||||
@@ -44,12 +58,20 @@ export function sceneAt(battle: TraceBattle, t: number): SceneAt {
|
||||
for (const [eid, ua] of a.units) {
|
||||
const ub = b?.units.get(eid);
|
||||
const move = ub !== undefined && ua.alive && ub.alive ? k : 0;
|
||||
const bot = a.bots.get(eid);
|
||||
const [gyA, gpA] = gunOf(ua, bot);
|
||||
const [gyB, gpB] = ub !== undefined ? gunOf(ub, b?.bots.get(eid)) : [gyA, gpA];
|
||||
units.set(eid, {
|
||||
unit: ua,
|
||||
x: ua.x + ((ub?.x ?? ua.x) - ua.x) * move,
|
||||
z: ua.z + ((ub?.z ?? ua.z) - ua.z) * move,
|
||||
x: lerp(ua.x, ub?.x, move),
|
||||
y: lerp(ua.y, ub?.y, move),
|
||||
z: lerp(ua.z, ub?.z, move),
|
||||
yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move),
|
||||
bot: a.bots.get(eid),
|
||||
hullPitch: lerp(ua.hullPitch ?? 0, ub?.hullPitch, move),
|
||||
hullRoll: lerp(ua.hullRoll ?? 0, ub?.hullRoll, move),
|
||||
gunYaw: lerpYaw(gyA, gyB, move),
|
||||
gunPitch: lerp(gpA, gpB, move),
|
||||
bot,
|
||||
});
|
||||
}
|
||||
return { t, units, caps: a.caps };
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* The static map drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured
|
||||
* The navigation image draped over the 3D terrain, drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured
|
||||
* by surface, optionally the tactical grid's exposure and the baked cover points.
|
||||
*/
|
||||
import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim';
|
||||
@@ -33,7 +33,8 @@ export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer {
|
||||
canvas.height = Math.ceil((z1 - z0) * pxPerM);
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx === null) return { canvas, x0, z1, pxPerM };
|
||||
ctx.fillStyle = '#121416';
|
||||
// Off the mesh (buildings, steep or blocked ground) when draped over the 3D terrain.
|
||||
ctx.fillStyle = '#55584f';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
const tier = pack.tiers[opts.tier] ?? pack.tiers[1];
|
||||
if (tier !== undefined) {
|
||||
|
||||
@@ -6,7 +6,11 @@ header select { max-width: 420px; }
|
||||
header label { display: inline-flex; align-items: center; gap: 3px; }
|
||||
.status { color: #ffb74d; }
|
||||
main { flex: 1; display: flex; min-height: 0; }
|
||||
canvas.map { flex: 1; min-width: 0; height: 100%; cursor: grab; display: block; }
|
||||
.map3d { flex: 1; min-width: 0; height: 100%; position: relative; overflow: hidden; }
|
||||
.map3d canvas { display: block; }
|
||||
.labels3d { position: absolute; inset: 0; pointer-events: none; }
|
||||
.tank-label { color: rgba(255,255,255,0.9); font-size: 11px; text-shadow: 0 0 3px #000; white-space: nowrap; }
|
||||
.tank-label.human { color: #ffe14a; }
|
||||
.inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; }
|
||||
.inspector table { width: 100%; border-collapse: collapse; }
|
||||
.inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; }
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* The static 3D map: lit terrain (coloured by height, or draped with the navigation mesh image),
|
||||
* the collision shapes of placed objects coloured by kind, and the water plane.
|
||||
*/
|
||||
import type { MapScene, SceneTerrain } from '@wto/ground-sim';
|
||||
import {
|
||||
BufferAttribute, BufferGeometry, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshLambertMaterial,
|
||||
PlaneGeometry, SRGBColorSpace, type Material,
|
||||
} from 'three';
|
||||
import type { MapLayer } from '../mapLayer.ts';
|
||||
|
||||
/** Colour and opacity per SCENE_KIND_NAMES entry. */
|
||||
const KIND_LOOK: readonly (readonly [number, number])[] = [
|
||||
[0xb9b2a3, 1], [0x7d7a74, 1], [0x9a7b55, 1], [0xe09a4a, 0.4], [0x4f8a3c, 1], [0x6f8aa0, 1],
|
||||
];
|
||||
|
||||
const LOW = new Color(0x3c4a32);
|
||||
const HIGH = new Color(0x9b9171);
|
||||
|
||||
export interface MapMeshes {
|
||||
readonly group: Group;
|
||||
readonly terrain: Mesh<BufferGeometry, MeshLambertMaterial>;
|
||||
/** Objects per scene kind, to switch kinds on and off. */
|
||||
readonly kinds: Group[];
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
function terrainGeometry(t: SceneTerrain, nav: MapLayer | undefined): BufferGeometry {
|
||||
const n = t.cols * t.rows;
|
||||
const pos = new Float32Array(n * 3);
|
||||
const col = new Float32Array(n * 3);
|
||||
const uv = new Float32Array(n * 2);
|
||||
let lo = Infinity;
|
||||
let hi = -Infinity;
|
||||
for (const h of t.heights) { lo = Math.min(lo, h); hi = Math.max(hi, h); }
|
||||
const c = new Color();
|
||||
const navW = nav === undefined ? 1 : nav.canvas.width / nav.pxPerM;
|
||||
const navH = nav === undefined ? 1 : nav.canvas.height / nav.pxPerM;
|
||||
for (let r = 0; r < t.rows; r++) {
|
||||
for (let k = 0; k < t.cols; k++) {
|
||||
const i = r * t.cols + k;
|
||||
const x = t.origin[0] + k * t.cellM;
|
||||
const z = t.origin[1] + r * t.cellM;
|
||||
const h = t.heights[i] ?? 0;
|
||||
pos.set([x, h, -z], i * 3);
|
||||
c.lerpColors(LOW, HIGH, hi > lo ? (h - lo) / (hi - lo) : 0);
|
||||
col.set([c.r, c.g, c.b], i * 3);
|
||||
if (nav !== undefined) uv.set([(x - nav.x0) / navW, (z - (nav.z1 - navH)) / navH], i * 2);
|
||||
}
|
||||
}
|
||||
const idx = new Uint32Array((t.cols - 1) * (t.rows - 1) * 6);
|
||||
let at = 0;
|
||||
for (let r = 0; r + 1 < t.rows; r++) {
|
||||
for (let k = 0; k + 1 < t.cols; k++) {
|
||||
const i = r * t.cols + k;
|
||||
idx.set([i, i + 1, i + t.cols, i + 1, i + t.cols + 1, i + t.cols], at);
|
||||
at += 6;
|
||||
}
|
||||
}
|
||||
const g = new BufferGeometry();
|
||||
g.setAttribute('position', new BufferAttribute(pos, 3));
|
||||
g.setAttribute('color', new BufferAttribute(col, 3));
|
||||
g.setAttribute('uv', new BufferAttribute(uv, 2));
|
||||
g.setIndex(new BufferAttribute(idx, 1));
|
||||
g.computeVertexNormals();
|
||||
return g;
|
||||
}
|
||||
|
||||
/** Drapes the navigation image over the terrain, or goes back to height colours. */
|
||||
export function setTerrainImage(m: MapMeshes, nav: MapLayer | undefined): void {
|
||||
const mat = m.terrain.material;
|
||||
mat.map?.dispose();
|
||||
if (nav === undefined) {
|
||||
mat.map = null;
|
||||
mat.vertexColors = true;
|
||||
} else {
|
||||
const tex = new CanvasTexture(nav.canvas);
|
||||
tex.colorSpace = SRGBColorSpace;
|
||||
tex.anisotropy = 8;
|
||||
mat.map = tex;
|
||||
mat.vertexColors = false;
|
||||
}
|
||||
mat.needsUpdate = true;
|
||||
}
|
||||
|
||||
function objectKinds(scene: MapScene, materials: Material[]): Group[] {
|
||||
const kinds = KIND_LOOK.map(() => new Group());
|
||||
const mats = KIND_LOOK.map(([color, opacity]) => new MeshLambertMaterial({
|
||||
color, flatShading: true, side: DoubleSide, transparent: opacity < 1, opacity, depthWrite: opacity >= 1,
|
||||
}));
|
||||
materials.push(...mats);
|
||||
for (const m of scene.meshes) {
|
||||
const g = new BufferGeometry();
|
||||
const pos = new Float32Array(m.positions);
|
||||
for (let i = 2; i < pos.length; i += 3) pos[i] = -(pos[i] ?? 0);
|
||||
g.setAttribute('position', new BufferAttribute(pos, 3));
|
||||
g.setIndex(new BufferAttribute(m.indices, 1));
|
||||
g.computeBoundingSphere();
|
||||
const mat = mats[m.kind] ?? mats[0];
|
||||
if (mat !== undefined) kinds[m.kind]?.add(new Mesh(g, mat));
|
||||
}
|
||||
return kinds;
|
||||
}
|
||||
|
||||
export function buildMapMeshes(scene: MapScene, nav: MapLayer | undefined): MapMeshes {
|
||||
const group = new Group();
|
||||
const materials: Material[] = [];
|
||||
const terrainMat = new MeshLambertMaterial({ vertexColors: true });
|
||||
materials.push(terrainMat);
|
||||
const terrain = new Mesh(terrainGeometry(scene.terrain, nav), terrainMat);
|
||||
group.add(terrain);
|
||||
const kinds = objectKinds(scene, materials);
|
||||
for (const k of kinds) group.add(k);
|
||||
if (scene.waterLevel !== undefined) {
|
||||
const w = scene.boundsMax[0] - scene.boundsMin[0];
|
||||
const d = scene.boundsMax[1] - scene.boundsMin[1];
|
||||
const waterMat = new MeshLambertMaterial({ color: 0x2d5f8a, transparent: true, opacity: 0.55, depthWrite: false });
|
||||
materials.push(waterMat);
|
||||
const water = new Mesh(new PlaneGeometry(w, d), waterMat);
|
||||
water.rotation.x = -Math.PI / 2;
|
||||
water.position.set(scene.boundsMin[0] + w / 2, scene.waterLevel, -(scene.boundsMin[1] + d / 2));
|
||||
group.add(water);
|
||||
}
|
||||
const meshes: MapMeshes = {
|
||||
group, terrain, kinds,
|
||||
dispose() {
|
||||
group.traverse((o) => { if (o instanceof Mesh) (o.geometry as BufferGeometry).dispose(); });
|
||||
terrainMat.map?.dispose();
|
||||
for (const m of materials) m.dispose();
|
||||
},
|
||||
};
|
||||
if (nav !== undefined) setTerrainImage(meshes, nav);
|
||||
return meshes;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Every vehicle as simple shapes: a hull box tilted by the hull's pitch and roll, a turret box
|
||||
* turned to the gun's heading, and a barrel at the gun's pitch. Sizes come from the bot's vehicle
|
||||
* class (players: light or medium).
|
||||
*/
|
||||
import { sceneHeightAt, type SceneTerrain } from '@wto/ground-sim';
|
||||
import {
|
||||
BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshLambertMaterial, type Object3D,
|
||||
} from 'three';
|
||||
import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
|
||||
import type { UnitAt } from '../frames.ts';
|
||||
import { DEG } from './coords.ts';
|
||||
|
||||
/** Length, width, hull height per vehicle class (medium, light, heavy, tank destroyer, SPAA). */
|
||||
const SIZES: readonly (readonly [number, number, number])[] = [
|
||||
[7, 3.4, 1.3], [6, 3, 1.1], [7.6, 3.6, 1.4], [7, 3.3, 1.2], [6.5, 3.1, 1.2],
|
||||
];
|
||||
|
||||
export const ARMY_HEX: Readonly<Record<number, number>> = { 1: 0x4aa3ff, 2: 0xff5c5c };
|
||||
const DEAD = new Color(0x4a4a4a);
|
||||
const SELECTED = new Color(0x6a5200);
|
||||
const NONE = new Color(0);
|
||||
|
||||
/** A trace height further than this from the terrain is kept (bridge, building, platform). */
|
||||
const OFF_GROUND_M = 1.5;
|
||||
|
||||
export interface Tank {
|
||||
readonly root: Group;
|
||||
readonly turret: Group;
|
||||
readonly barrel: Group;
|
||||
readonly label: CSS2DObject;
|
||||
readonly mats: MeshLambertMaterial[];
|
||||
/** Turret top above the hull origin, where lines and the gun camera start. */
|
||||
readonly eyeY: number;
|
||||
readonly length: number;
|
||||
}
|
||||
|
||||
function sizeOf(u: UnitAt): readonly [number, number, number] {
|
||||
const cls = u.bot?.vehicleClass ?? (u.unit.light ? 1 : 0);
|
||||
return SIZES[cls] ?? SIZES[0] ?? [7, 3.4, 1.3];
|
||||
}
|
||||
|
||||
function makeTank(u: UnitAt): Tank {
|
||||
const [len, wid, hh] = sizeOf(u);
|
||||
const hullMat = new MeshLambertMaterial();
|
||||
const turretMat = new MeshLambertMaterial();
|
||||
const root = new Group();
|
||||
root.rotation.order = 'YZX';
|
||||
const hull = new Mesh(new BoxGeometry(len, hh, wid), hullMat);
|
||||
hull.position.y = hh / 2;
|
||||
const turret = new Group();
|
||||
turret.position.set(-len * 0.05, hh, 0);
|
||||
const tw = wid * 0.7;
|
||||
const th = hh * 0.65;
|
||||
const turretBox = new Mesh(new BoxGeometry(len * 0.48, th, tw), turretMat);
|
||||
turretBox.position.y = th / 2;
|
||||
const barrel = new Group();
|
||||
barrel.position.set(len * 0.2, th * 0.55, 0);
|
||||
const tube = new Mesh(new CylinderGeometry(0.09, 0.11, len * 0.75, 8), turretMat);
|
||||
tube.rotation.z = -Math.PI / 2;
|
||||
tube.position.x = len * 0.375;
|
||||
barrel.add(tube);
|
||||
turret.add(turretBox, barrel);
|
||||
root.add(hull, turret);
|
||||
const div = document.createElement('div');
|
||||
div.className = 'tank-label';
|
||||
const label = new CSS2DObject(div);
|
||||
label.position.y = hh + th + 2.5;
|
||||
root.add(label);
|
||||
for (const m of [hull, turretBox, tube]) m.userData['eid'] = u.unit.eid;
|
||||
return { root, turret, barrel, label, mats: [hullMat, turretMat], eyeY: hh + th, length: len };
|
||||
}
|
||||
|
||||
export class TankPool {
|
||||
readonly group = new Group();
|
||||
private readonly tanks = new Map<string, Tank>();
|
||||
|
||||
constructor(private readonly terrain: SceneTerrain | undefined) {}
|
||||
|
||||
get(eid: string): Tank | undefined {
|
||||
return this.tanks.get(eid);
|
||||
}
|
||||
|
||||
/** Meshes to pick with a ray. */
|
||||
pickables(): Object3D[] {
|
||||
const out: Object3D[] = [];
|
||||
for (const t of this.tanks.values()) if (t.root.visible) t.root.traverse((o) => { if (o instanceof Mesh) out.push(o); });
|
||||
return out;
|
||||
}
|
||||
|
||||
terrainY(x: number, z: number): number {
|
||||
return this.terrain === undefined ? 0 : sceneHeightAt(this.terrain, x, z);
|
||||
}
|
||||
|
||||
/** Ground height for the vehicle: the terrain unless the trace puts it clearly above or below. */
|
||||
groundY(x: number, y: number, z: number): number {
|
||||
if (this.terrain === undefined) return y;
|
||||
const g = sceneHeightAt(this.terrain, x, z);
|
||||
return Math.abs(y - g) <= OFF_GROUND_M ? g : y;
|
||||
}
|
||||
|
||||
update(units: ReadonlyMap<string, UnitAt>, selected: string | undefined, labels: (u: UnitAt) => string | undefined): void {
|
||||
for (const [eid, t] of this.tanks) if (!units.has(eid)) t.root.visible = false;
|
||||
for (const u of units.values()) {
|
||||
let t = this.tanks.get(u.unit.eid);
|
||||
if (t === undefined) {
|
||||
t = makeTank(u);
|
||||
this.tanks.set(u.unit.eid, t);
|
||||
this.group.add(t.root);
|
||||
}
|
||||
this.place(t, u, u.unit.eid === selected, labels(u));
|
||||
}
|
||||
}
|
||||
|
||||
private place(t: Tank, u: UnitAt, selected: boolean, label: string | undefined): void {
|
||||
t.root.visible = true;
|
||||
t.root.position.set(u.x, this.groundY(u.x, u.y, u.z), -u.z);
|
||||
t.root.rotation.set(u.hullRoll * DEG, u.yaw * DEG, u.hullPitch * DEG);
|
||||
const rel = ((((u.gunYaw - u.yaw) % 360) + 540) % 360) - 180;
|
||||
t.turret.rotation.y = rel * DEG;
|
||||
const hullSlope = u.hullPitch * Math.cos(rel * DEG) + u.hullRoll * Math.sin(rel * DEG);
|
||||
t.barrel.rotation.z = (u.gunPitch - hullSlope) * DEG;
|
||||
const base = u.unit.alive ? new Color(ARMY_HEX[u.unit.army] ?? 0xcccccc) : DEAD;
|
||||
t.mats.forEach((m, i) => {
|
||||
m.color.copy(base).multiplyScalar(i === 0 ? 1 : 0.8);
|
||||
m.emissive.copy(selected ? SELECTED : NONE);
|
||||
});
|
||||
t.label.visible = label !== undefined;
|
||||
if (label !== undefined) t.label.element.textContent = label;
|
||||
if (u.unit.human) t.label.element.classList.add('human');
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const t of this.tanks.values()) {
|
||||
t.root.traverse((o) => { if (o instanceof Mesh) o.geometry.dispose(); });
|
||||
for (const m of t.mats) m.dispose();
|
||||
t.label.element.remove();
|
||||
}
|
||||
this.tanks.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/**
|
||||
* Top-down view of the battle: world x to the right, world z up (Dagor is Y-up). Headings are
|
||||
* degrees of atan2(z, x), as the trace writes them.
|
||||
*/
|
||||
export interface View {
|
||||
/** World point at the centre of the canvas. */
|
||||
readonly cx: number;
|
||||
readonly cz: number;
|
||||
/** Screen pixels per world metre. */
|
||||
readonly scale: number;
|
||||
readonly w: number;
|
||||
readonly h: number;
|
||||
}
|
||||
|
||||
export function toScreen(v: View, x: number, z: number): [number, number] {
|
||||
return [v.w / 2 + (x - v.cx) * v.scale, v.h / 2 - (z - v.cz) * v.scale];
|
||||
}
|
||||
|
||||
export function toWorld(v: View, sx: number, sy: number): [number, number] {
|
||||
return [v.cx + (sx - v.w / 2) / v.scale, v.cz - (sy - v.h / 2) / v.scale];
|
||||
}
|
||||
|
||||
/** Screen direction (unit vector) of a world heading. */
|
||||
export function screenDir(yawDeg: number): [number, number] {
|
||||
const r = (yawDeg * Math.PI) / 180;
|
||||
return [Math.cos(r), -Math.sin(r)];
|
||||
}
|
||||
|
||||
export function fitView(minX: number, minZ: number, maxX: number, maxZ: number, w: number, h: number): View {
|
||||
const scale = Math.min(w / Math.max(1, maxX - minX), h / Math.max(1, maxZ - minZ)) * 0.95;
|
||||
return { cx: (minX + maxX) / 2, cz: (minZ + maxZ) / 2, scale, w, h };
|
||||
}
|
||||
|
||||
/** Zoom by `factor` keeping the world point under the screen point (sx, sy) in place. */
|
||||
export function zoomAt(v: View, sx: number, sy: number, factor: number): View {
|
||||
const [wx, wz] = toWorld(v, sx, sy);
|
||||
const scale = Math.min(40, Math.max(0.05, v.scale * factor));
|
||||
return { ...v, scale, cx: wx - (sx - v.w / 2) / scale, cz: wz + (sy - v.h / 2) / scale };
|
||||
}
|
||||
Reference in new issue
Block a user