feat(ground-ai): build and load offline map navigation packs

This commit is contained in:
N0VAN0M4LY committed 2026-12-06 16:03:52 +08:00
1 parent 710c8ecaaa
commit b56c5eaf58
6 files changed
+214 -6

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
/**
* Build the navigation and cover data for the ground mission pool of a local game copy.
* Compile the Rust extractor and C++ baker first.
*
* node tools/navgen/bake-maps.mts --game <client> --out <folder>
* [--levels <level,level,...>] [--extract <exe>] [--bake <exe>] [--jobs <count>]
*/
import { spawn } from 'node:child_process';
import { mkdir, mkdtemp, open, readdir, readFile, rename, stat } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
const repository = fileURLToPath(new URL('../../', import.meta.url));
const { values } = parseArgs({
options: {
game: { type: 'string' },
out: { type: 'string' },
levels: { type: 'string' },
extract: { type: 'string', default: join(repository, 'tools/navgen/extract/target/release/wto-navgen-extract.exe') },
bake: { type: 'string', default: join(repository, 'build/navgen/wto_navgen_bake.exe') },
jobs: { type: 'string', default: '1' },
},
});
async function run(executable: string, args: string[], log?: string): Promise<void> {
const output = log === undefined ? undefined : await open(log, 'w');
try {
await new Promise<void>((done, fail) => {
const child = spawn(executable, args, {
cwd: repository,
stdio: output ? ['ignore', output.fd, output.fd] : 'inherit',
windowsHide: true,
});
child.once('error', fail);
child.once('exit', (code, signal) => {
if (code === 0) done();
else fail(new Error(`${executable} exited with ${code ?? signal}${log ? ` (see ${log})` : ''}`));
});
});
} finally {
await output?.close();
}
}
async function main(): Promise<void> {
const jobs = Number(values.jobs);
if (!values.game || !values.out || !Number.isSafeInteger(jobs) || jobs < 1) {
throw new Error('Usage: --game <client> --out <folder> [--levels <list>] [--extract <exe>] [--bake <exe>] [--jobs <count>]');
}
const game = resolve(values.game);
const output = resolve(values.out);
const extract = resolve(values.extract);
const bake = resolve(values.bake);
const maps = join(output, 'maps');
await Promise.all([stat(extract), stat(bake), mkdir(maps, { recursive: true })]);
const work = await mkdtemp(join(output, 'bake-'));
const args = [join(repository, 'tools/navgen/mission-bounds.mts'), '--game', game, '--out', work];
if (values.levels !== undefined) args.push('--levels', values.levels);
await run(process.execPath, args, join(work, 'missions.log'));
const suffix = '.pois.json';
const levels = (await readdir(work)).filter((name) => /^[a-z0-9_]+\.pois\.json$/.test(name))
.map((name) => name.slice(0, -suffix.length));
if (levels.length === 0) throw new Error(`No ground levels found. See ${join(work, 'missions.log')}.`);
if (values.levels) {
const missing = values.levels.split(',').map((level) => level.trim().toLowerCase())
.filter((level) => !levels.includes(level));
if (missing.length) throw new Error(`Levels missing from the mission pool: ${missing.join(', ')}`);
}
console.log(`Baking ${levels.length} ground levels. Logs: ${work}`);
let next = 0;
let finished = 0;
const failures: string[] = [];
const worker = async (): Promise<void> => {
while (next < levels.length) {
const level = levels[next++]!;
const pois = join(work, level + suffix);
const geo = join(work, level + '.wtogeo');
const candidate = join(work, level + '.wtonav');
try {
await run(extract, ['--game', game, '--pois', pois, '--out', geo,
'--report', join(work, level + '.extract-report.json')], join(work, level + '.extract.log'));
const bakeLog = join(work, level + '.bake.log');
await run(bake, ['--geo', geo, '--pois', pois, '--out', candidate], bakeLog);
const log = await readFile(bakeLog, 'utf8');
const routes = [...log.matchAll(/Connectivity \S+: full=(\d+)\/(\d+)/g)];
if (routes.length !== 3 || routes.some(([, , total]) => Number(total) === 0)) {
throw new Error('Missing spawn-to-capture checks. See ' + bakeLog);
}
if (routes.some(([, full, total]) => full !== total)) {
console.warn(level + ': incomplete paths in ' + bakeLog);
}
const { size } = await stat(candidate);
if (size === 0) throw new Error('The baker wrote an empty map.');
await rename(candidate, join(maps, level + '.wtonav'));
console.log(`[${++finished}/${levels.length}] ${level} (${(size / 2 ** 20).toFixed(1)} MiB)`);
} catch (error) {
failures.push(level);
console.error(`[${++finished}/${levels.length}] ${level}: ${error instanceof Error ? error.message : error}`);
}
}
};
await Promise.all(Array.from({ length: Math.min(jobs, levels.length) }, worker));
if (failures.length) throw new Error(`Map generation failed for ${failures.join(', ')}.`);
}
await main();
+3 -4
View File
@@ -297,11 +297,10 @@ function main() {
if (!n.includes('brief') && box.rad >= 5 && box.rad <= 250) {
acc.caps.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName });
}
} else if (n.includes('tankspawn') || (n.includes('spawn') && /t1|t2|team1|team2|tank/.test(n))) {
if (n.includes('brief')) continue;
if (n.includes('t1_') || n.includes('team1') || n.includes('_t1')) {
} else if (n.includes('spawn') && !n.includes('brief')) {
if (n.includes('t1_') || n.includes('team1') || n.includes('_t1') || n.startsWith('teama_spawn_')) {
acc.t1Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName });
} else if (n.includes('t2_') || n.includes('team2') || n.includes('_t2')) {
} else if (n.includes('t2_') || n.includes('team2') || n.includes('_t2') || n.startsWith('teamb_spawn_')) {
acc.t2Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName });
}
}
+92
View File
@@ -0,0 +1,92 @@
/**
* Package the baked navigation data for the launcher data directory.
* node tools/navgen/package-maps.mts --maps <folder> --inventory <pois folder> --out <folder>
* --version <YYYY.MM.DD[.N]> --game-version <x.y.z.n> [--unsigned]
*
* Signed packages use the project's PATCH_SIGNING_KEY. The unpacked map-nav directory is also
* usable locally. Each release archive contains that directory, ready to extract into the data root.
*/
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdir, mkdtemp, readFile, readdir, rename, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { parseArgs } from 'node:util';
import { isPackVersion, packSigningPublicKey, signEd25519, verifyEd25519 } from '@wto/patcher';
import { readNavPack } from '../../packages/ground-sim/src/map/wtonav.ts';
const { values } = parseArgs({
options: {
maps: { type: 'string' },
inventory: { type: 'string' },
out: { type: 'string' },
version: { type: 'string' },
'game-version': { type: 'string' },
unsigned: { type: 'boolean', default: false },
},
});
async function main(): Promise<void> {
const { maps, inventory, out, version, 'game-version': gameVersion } = values;
if (!maps || !inventory || !out || !version || !isPackVersion(version) || !gameVersion ||
!/^\d+\.\d+\.\d+\.\d+$/.test(gameVersion)) {
throw new Error('Supply --maps, --inventory, --out, --version YYYY.MM.DD[.N] and --game-version x.y.z.n.');
}
const privateKey = values.unsigned ? undefined : process.env['PATCH_SIGNING_KEY'];
if (!privateKey && !values.unsigned) throw new Error('Set PATCH_SIGNING_KEY or use --unsigned for local use.');
const output = resolve(out);
const levels = (await readdir(inventory)).filter((file) => /^[a-z0-9_]+\.pois\.json$/.test(file))
.map((file) => file.slice(0, -'.pois.json'.length)).sort();
if (levels.length === 0) throw new Error('The mission inventory is empty.');
await mkdir(output, { recursive: true });
const staging = await mkdtemp(join(output, 'map-nav-stage-'));
const pack = join(staging, 'map-nav');
await mkdir(join(pack, 'maps'), { recursive: true });
const entries = [];
for (const level of levels) {
const filename = level + '.wtonav';
const bytes = await readFile(join(maps, filename));
const { header, tiers } = readNavPack(bytes);
if (tiers.some((tier) => tier.polyCount === 0) || /^0+$/.test(header.everSha1)) {
throw new Error('Incomplete navigation data for ' + level);
}
entries.push({
level,
everSha1: header.everSha1,
size: bytes.length,
sha256: createHash('sha256').update(bytes).digest('hex'),
covers: header.coverCount,
});
await writeFile(join(pack, 'maps', filename), bytes);
}
const app = JSON.parse(await readFile(new URL('../../apps/launcher/package.json', import.meta.url), 'utf8')) as { version: string };
const manifest = JSON.stringify({
format: 1,
version,
minAppVersion: app.version,
gameVersions: [gameVersion],
createdAt: new Date().toISOString(),
maps: entries,
}, null, 2) + '\n';
await writeFile(join(pack, 'manifest.json'), manifest);
const stem = 'wtoffline-map-nav-' + version;
const archive = join(staging, stem + '.zip');
execFileSync('tar', ['-a', '-c', '-f', archive, '-C', staging, 'map-nav'], { stdio: 'inherit', windowsHide: true });
if (privateKey) {
const bytes = await readFile(archive);
const signature = signEd25519(bytes, privateKey);
const publicKey = packSigningPublicKey();
if (!publicKey || !verifyEd25519(bytes, signature, publicKey)) {
throw new Error('The map archive signature did not verify against the project public key.');
}
await writeFile(join(staging, stem + '.zip.sig'), signature);
}
await writeFile(join(staging, stem + '.manifest.json'), manifest);
const release = join(output, version);
await rename(staging, release);
console.log('Packaged ' + entries.length + ' maps in ' + join(release, stem + '.zip'));
console.log('Unpacked maps: ' + join(release, 'map-nav'));
}
await main();