feat(patcher,server): wire ground AI tuning, bot weights, and pack build

Add ground-ai.jsonc tuning validation, realistic tank class weights for
customBots pools, on-demand game.vromfs.bin / ailist.blk injection in
@wto/patcher, and launcher/CLI build integration while keeping all
ground AI layers disabled by default in shipped configuration.
This commit is contained in:
N0VAN0M4LY committed 2026-12-03 12:07:30 +08:00
1 parent 18637cf1ff
commit 4ac3484f56
17 files changed
+836 -75

No files matched your search

+96 -37
View File
@@ -16,6 +16,13 @@ import { rebuildCharPack, type CharPackResult } from './char-pack.ts';
import { blockingFailures } from './essential-features.ts';
import { patchExecutableWithMods, type ModExePatchFailure } from './executable.ts';
import { GAME_FILES } from './game-copy.ts';
import {
GAME_PACK_FILE,
rebuildGamePack,
type GamePackResult,
type GroundAiBuildInputs,
} from './ground-ai/game-pack.ts';
import { isGroundAiActive } from './ground-ai/ground-ai-config.ts';
import { rebuildGuiPack } from './gui-pack.ts';
import { rebuildMainPack } from './main-pack.ts';
import { collectModAddonMounts, type ModAddonMount } from './mods/addon-register.ts';
@@ -57,8 +64,10 @@ export interface GameCopyInputs {
readonly hookLogging?: boolean;
/** Ordered list of enabled additive mods to overlay onto this build. */
readonly mods?: readonly DiscoveredMod[];
/** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods. */
/** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods or ground AI. */
readonly extraStockPacks?: Partial<Record<ModdableClientPack, Uint8Array>>;
/** Optional modular ground AI scripts and tuning compiled into `game.vromfs.bin` when active. */
readonly groundAi?: GroundAiBuildInputs;
}
/** One file of the game copy, by its path relative to the copy folder. */
@@ -96,6 +105,8 @@ export interface GameCopyBuild {
readonly engineAddresses: readonly AddressChange[];
/** Store bundle GUIDs registered in config/gui.blk. */
readonly bundleGuids: number;
/** Injected ground AI modules when `groundAi` is active; undefined when stock AI is kept. */
readonly gamePack?: Omit<GamePackResult, 'pack'>;
/** Details of additive mod overlays applied during this build. */
readonly mods: ModBuildReport;
}
@@ -114,12 +125,58 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
const folders = patchSetFolders(inputs.patches);
const enabledMods = inputs.mods ?? [];
const packOverlays: PackOverlayReport[] = [];
const groundAiActive = inputs.groundAi !== undefined && isGroundAiActive(inputs.groundAi.config);
const executable = patchExecutableWithMods(inputs.stock.executable, folders.exe, enabledMods);
const stockImage = new PeImage(inputs.stock.executable);
const native = resolveNativeModules(stockImage, loadNativeModules(folders.native));
const core = buildCorePacks(inputs, endpoint, folders.gui, enabledMods, packOverlays, groundAiActive);
const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui);
const executableFolder = dirname(GAME_FILES.executable);
const hookSettings = networkHookSettings(endpoint, stockImage, native.values, {
loggingEnabled: inputs.hookLogging ?? true,
});
const files: GameCopyFile[] = [
{ path: GAME_FILES.charPack, content: core.charPack },
{ path: GAME_FILES.mainPack, content: core.mainPack },
{ path: GAME_FILES.guiPack, content: core.guiPack },
{ path: GAME_FILES.executable, content: executable.executable },
{ path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary },
{ path: join(executableFolder, hookSettings.name), content: hookSettings.content },
];
const gamePackReport = appendOptionalPackFiles(files, packOverlays, inputs, enabledMods, groundAiActive);
const failures = [...executable.plan.failures, ...core.guiFailures, ...native.failures];
return {
files,
endpoint,
exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures },
guiPatches: { applied: core.appliedGuiPatches, failures: core.guiFailures },
nativeModules: { available: [...native.available.keys()], failures: native.failures },
blocking: blockingFailures(failures),
charPack: core.charReport,
engineAddresses: core.engineAddresses,
bundleGuids: core.bundleCount,
...(gamePackReport ? { gamePack: gamePackReport } : {}),
mods: {
enabledModIds: enabledMods.map((mod) => mod.manifest.id),
packOverlays,
addonMounts: core.addonMounts,
guiPatches: { applied: core.modGuiApplied, failures: core.modGuiFailures },
exePatches: { applied: executable.modApplied, failures: executable.modFailures },
},
};
}
function buildCorePacks(
inputs: GameCopyInputs,
endpoint: LocalEndpoint,
guiPatchFolder: string,
enabledMods: readonly DiscoveredMod[],
packOverlays: PackOverlayReport[],
groundAiActive: boolean,
) {
const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, guiPatchFolder);
const appliedGuiPatches = coreGuiPack.applied.map((item) => item.patch.id);
const guiPackFileOverlay = applyModPackOverlays(coreGuiPack.pack, 'gui.vromfs.bin', enabledMods);
if (guiPackFileOverlay.report.operationsApplied > 0) packOverlays.push(guiPackFileOverlay.report);
@@ -135,8 +192,6 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods);
if (charOverlay.report.operationsApplied > 0) packOverlays.push(charOverlay.report);
// Derive store bundle GUIDs from the mod-overlaid charPack so newly added mod gift vehicles
// automatically receive deterministic offline store bundle GUIDs.
const bundles = offlinePackBundleGuids(charOverlay.pack, inputs.multiVehiclePackIds);
const addonMounts = collectModAddonMounts(enabledMods);
const coreMainPack = rebuildMainPack(
@@ -144,26 +199,49 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
endpoint,
bundles,
addonMounts.map((mount) => mount.mountFolder),
{ yieldStockTankDrive: groundAiActive && inputs.groundAi!.config.layers.navigation },
);
const mainOverlay = applyModPackOverlays(coreMainPack.pack, 'aces.vromfs.bin', enabledMods);
if (mainOverlay.report.operationsApplied > 0) packOverlays.push(mainOverlay.report);
const executableFolder = dirname(GAME_FILES.executable);
const hookSettings = networkHookSettings(endpoint, stockImage, native.values, {
loggingEnabled: inputs.hookLogging ?? true,
});
const files: GameCopyFile[] = [
{ path: GAME_FILES.charPack, content: charOverlay.pack },
{ path: GAME_FILES.mainPack, content: mainOverlay.pack },
{ path: GAME_FILES.guiPack, content: modGuiResult.pack },
{ path: GAME_FILES.executable, content: executable.executable },
{ path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary },
{ path: join(executableFolder, hookSettings.name), content: hookSettings.content },
];
return {
charPack: charOverlay.pack,
mainPack: mainOverlay.pack,
guiPack: modGuiResult.pack,
charReport,
appliedGuiPatches,
guiFailures: coreGuiPack.failures,
modGuiApplied: modGuiResult.applied,
modGuiFailures: modGuiResult.failures,
engineAddresses: coreMainPack.addresses,
bundleCount: bundles.length,
addonMounts,
};
}
function appendOptionalPackFiles(
files: GameCopyFile[],
packOverlays: PackOverlayReport[],
inputs: GameCopyInputs,
enabledMods: readonly DiscoveredMod[],
groundAiActive: boolean,
): Omit<GamePackResult, 'pack'> | undefined {
let gamePackReport: Omit<GamePackResult, 'pack'> | undefined;
if (groundAiActive && inputs.groundAi) {
const stockGameBytes = inputs.extraStockPacks?.[GAME_PACK_FILE];
if (!stockGameBytes) {
throw new Error(`ground AI requires stock pack "${GAME_PACK_FILE}" in extraStockPacks`);
}
const { pack: aiGamePack, ...report } = rebuildGamePack(stockGameBytes, inputs.groundAi);
const overlay = applyModPackOverlays(aiGamePack, GAME_PACK_FILE, enabledMods);
if (overlay.report.operationsApplied > 0) packOverlays.push(overlay.report);
files.push({ path: GAME_PACK_FILE, content: overlay.pack });
gamePackReport = report;
}
// Rebuild any optional client packs (lang, mis, game, ui/atlases, ui/images) touched by enabled mods.
for (const pack of touchedClientPacks(enabledMods)) {
if (CORE_BUILD_PACKS.has(pack)) continue;
if (groundAiActive && pack === GAME_PACK_FILE) continue;
const stockBytes = inputs.extraStockPacks?.[pack];
if (!stockBytes) {
throw new Error(`mod overlay requires stock pack "${pack}" in extraStockPacks`);
@@ -174,24 +252,5 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
files.push({ path: join(...pack.split('/')), content: overlay.pack });
}
}
const failures = [...executable.plan.failures, ...coreGuiPack.failures, ...native.failures];
return {
files,
endpoint,
exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures },
guiPatches: { applied: appliedGuiPatches, failures: coreGuiPack.failures },
nativeModules: { available: [...native.available.keys()], failures: native.failures },
blocking: blockingFailures(failures),
charPack: charReport,
engineAddresses: coreMainPack.addresses,
bundleGuids: bundles.length,
mods: {
enabledModIds: enabledMods.map((mod) => mod.manifest.id),
packOverlays,
addonMounts,
guiPatches: { applied: modGuiResult.applied, failures: modGuiResult.failures },
exePatches: { applied: executable.modApplied, failures: executable.modFailures },
},
};
return gamePackReport;
}
@@ -0,0 +1,79 @@
/**
* Rebuild `game.vromfs.bin` with WTOffline's modular ground AI daScript files injected under
* `game/wtoai/` and one anchored `load_optional_folder("%appGame/wtoai")` line in `game/main.das`.
*/
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { getFile, putFile, readArchive, writeArchive } from '@wto/vromfs';
import { compileGroundAiConfigDas, type GroundAiConfig } from './ground-ai-config.ts';
export const GAME_PACK_FILE = 'game.vromfs.bin';
export const GAME_MAIN_SCRIPT_PATH = 'game/main.das';
export const GAME_AI_ARCHIVE_FOLDER = 'game/wtoai';
export const GAME_AI_CONFIG_FILE = 'wto_ai_config_common.das';
const GAME_MAIN_ANCHOR = 'ok = load_optional_folder("%appGame/ai") && ok';
const GAME_MAIN_INJECT = 'ok = load_optional_folder("%appGame/wtoai") && ok';
const MODULE_NAME = /^[a-z0-9_]+\.das$/;
export interface GroundAiBuildInputs {
readonly scriptsFolder: string;
readonly config: GroundAiConfig;
}
export interface GamePackResult {
readonly pack: Uint8Array;
readonly archiveFolder: string;
readonly modules: readonly string[];
}
export function rebuildGamePack(stockGamePack: Uint8Array, inputs: GroundAiBuildInputs): GamePackResult {
const archive = readArchive(stockGamePack);
const mainText = new TextDecoder('utf-8').decode(getFile(archive, GAME_MAIN_SCRIPT_PATH));
putFile(archive, GAME_MAIN_SCRIPT_PATH, new TextEncoder().encode(injectLoaderLine(mainText)));
const encoder = new TextEncoder();
const modules: string[] = [];
const configPath = `${GAME_AI_ARCHIVE_FOLDER}/${GAME_AI_CONFIG_FILE}`;
if (archive.files.has(configPath)) throw new Error(`game.vromfs.bin already contains ${configPath}`);
putFile(archive, configPath, encoder.encode(compileGroundAiConfigDas(inputs.config)));
modules.push(configPath);
const scriptFiles = readdirSync(inputs.scriptsFolder, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.das'))
.map((entry) => entry.name)
.sort();
for (const name of scriptFiles) {
if (!MODULE_NAME.test(name)) throw new Error(`invalid ground AI daScript module name: ${name}`);
if (name === GAME_AI_CONFIG_FILE) throw new Error(`${GAME_AI_CONFIG_FILE} is generated at build time`);
const archivePath = `${GAME_AI_ARCHIVE_FOLDER}/${name}`;
if (archive.files.has(archivePath)) throw new Error(`game.vromfs.bin already contains ${archivePath}`);
putFile(archive, archivePath, readFileSync(join(inputs.scriptsFolder, name)));
modules.push(archivePath);
}
return { pack: writeArchive(archive), archiveFolder: GAME_AI_ARCHIVE_FOLDER, modules };
}
function injectLoaderLine(source: string): string {
if (source.includes(GAME_MAIN_INJECT)) {
throw new Error(`${GAME_MAIN_SCRIPT_PATH} already contains ${GAME_MAIN_INJECT}`);
}
const eol = source.includes('\r\n') ? '\r\n' : '\n';
const normalized = source.replaceAll('\r\n', '\n');
const pattern = new RegExp(`^([ \\t]*)${escapeRegExp(GAME_MAIN_ANCHOR)}[ \\t]*$`, 'gm');
const matches = [...normalized.matchAll(pattern)];
if (matches.length !== 1) {
throw new Error(`expected 1 loader anchor in ${GAME_MAIN_SCRIPT_PATH}, found ${matches.length}`);
}
const match = matches[0]!;
const indent = match[1] ?? '';
const end = match.index! + match[0].length;
const patched = `${normalized.slice(0, end)}\n${indent}${GAME_MAIN_INJECT}${normalized.slice(end)}`;
return eol === '\r\n' ? patched.replaceAll('\n', '\r\n') : patched;
}
function escapeRegExp(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
@@ -0,0 +1,200 @@
/**
* Ground AI configuration contract shared between `@wto/server` tuning and `@wto/patcher`
* build-time daScript constant compilation (`game/wtoai/wto_ai_config_common.das`).
*/
export interface GroundAiConfig {
readonly enabled: boolean;
readonly layers: {
readonly macro: boolean;
readonly tactics: boolean;
readonly navigation: boolean;
readonly fireControl: boolean;
};
readonly cadence: {
readonly maxBots: number;
readonly macroTickSec: number;
readonly tacticsTickSec: number;
readonly navTickSec: number;
};
readonly macro: {
readonly openingSplitSec: number;
readonly capMaxInsiders: number;
readonly recaptureMinBots: number;
readonly recaptureMaxBots: number;
readonly capStickyBonusM: number;
readonly deathZoneRadiusM: number;
readonly deathZoneTtlSec: number;
readonly deathZoneMinKills: number;
readonly spaaRearOffsetM: number;
readonly spaaRelocateSec: number;
readonly enemySpawnAvoidM: number;
};
readonly crowd: {
readonly personalSpaceM: number;
readonly clusterRadiusM: number;
readonly clusterMaxAllies: number;
readonly disperseStepM: number;
readonly disperseHoldSec: number;
};
readonly terrain: {
readonly maxClimbSlopeDeg: number;
readonly maxDropSlopeDeg: number;
readonly maxWaterDepthM: number;
readonly collisionMarginM: number;
readonly crestLookaheadM: number;
readonly ridgeMaxDwellSec: number;
readonly ridgeMaxShots: number;
};
readonly navigation: {
readonly driveMode: string;
readonly maxPhysBots: number;
readonly steerSign: number;
readonly deadEchoSec: number;
readonly cornerBrakeAccel: number;
readonly pivotAngleDeg: number;
readonly stuckWindowSec: number;
readonly stuckMinMoveM: number;
readonly unstickReverseSec: number;
readonly tacticalReverseDistM: number;
readonly tacticalReverseMaxSec: number;
};
readonly tactics: {
readonly visionRangeM: number;
readonly visionFovDeg: number;
readonly peripheralRangeM: number;
readonly engineAudioRangeM: number;
readonly shotAudioRangeM: number;
readonly radioShareRangeM: number;
readonly memoryTtlSec: number;
readonly targetStickinessSec: number;
readonly peekCooldownSec: number;
};
readonly fireControl: {
readonly maxEngageRangeM: number;
readonly baseAlignDeg: number;
readonly closeHitRadiusM: number;
readonly barrelSettleDegSec: number;
readonly settleHoldSec: number;
readonly unstabilizedStopSpeedMps: number;
readonly stabilizedCreepSpeedMps: number;
readonly friendlyCorridorM: number;
};
readonly diagnostics: {
readonly telemetry: boolean;
readonly telemetryIntervalSec: number;
};
}
export function isGroundAiActive(config: GroundAiConfig | undefined): boolean {
if (!config || !config.enabled) return false;
const { macro, tactics, navigation, fireControl } = config.layers;
return macro || tactics || navigation || fireControl;
}
type DasEntry = readonly [name: string, kind: 'bool' | 'int' | 'float' | 'string', value: boolean | number | string];
export function compileGroundAiConfigDas(config: GroundAiConfig): string {
const entries = collectConfigEntries(config);
const lines = [
'// Auto-generated from tuning/ground-ai.jsonc during game copy build. Do not edit by hand.',
'options indenting = 2',
'options no_global_heap = true',
'module wto_ai_config_common shared',
'',
];
for (const [name, kind, value] of entries) {
lines.push(`let public ${name} : ${kind} = ${formatDasLiteral(name, kind, value)}`);
}
lines.push('');
return lines.join('\n');
}
function collectConfigEntries(c: GroundAiConfig): readonly DasEntry[] {
return [
['WTO_AI_ENABLED', 'bool', c.enabled],
['WTO_AI_LAYER_MACRO', 'bool', c.layers.macro],
['WTO_AI_LAYER_TACTICS', 'bool', c.layers.tactics],
['WTO_AI_LAYER_NAVIGATION', 'bool', c.layers.navigation],
['WTO_AI_LAYER_FIRE_CONTROL', 'bool', c.layers.fireControl],
['WTO_AI_MAX_TRACKED_BOTS', 'int', c.cadence.maxBots],
['WTO_AI_MACRO_TICK_SEC', 'float', c.cadence.macroTickSec],
['WTO_AI_TACTICS_TICK_SEC', 'float', c.cadence.tacticsTickSec],
['WTO_AI_NAV_TICK_SEC', 'float', c.cadence.navTickSec],
['WTO_AI_MACRO_OPENING_SPLIT_SEC', 'float', c.macro.openingSplitSec],
['WTO_AI_MACRO_CAP_MAX_INSIDERS', 'int', c.macro.capMaxInsiders],
['WTO_AI_MACRO_RECAP_MIN_BOTS', 'int', c.macro.recaptureMinBots],
['WTO_AI_MACRO_RECAP_MAX_BOTS', 'int', c.macro.recaptureMaxBots],
['WTO_AI_MACRO_CAP_STICKY_BONUS_M', 'float', c.macro.capStickyBonusM],
['WTO_AI_MACRO_DEATH_ZONE_RAD_M', 'float', c.macro.deathZoneRadiusM],
['WTO_AI_MACRO_DEATH_ZONE_TTL_SEC', 'float', c.macro.deathZoneTtlSec],
['WTO_AI_MACRO_DEATH_ZONE_MIN_KILLS', 'int', c.macro.deathZoneMinKills],
['WTO_AI_MACRO_SPAA_REAR_OFFSET_M', 'float', c.macro.spaaRearOffsetM],
['WTO_AI_MACRO_SPAA_RELOCATE_SEC', 'float', c.macro.spaaRelocateSec],
['WTO_AI_MACRO_ENEMY_SPAWN_AVOID_M', 'float', c.macro.enemySpawnAvoidM],
['WTO_AI_CROWD_PERSONAL_SPACE_M', 'float', c.crowd.personalSpaceM],
['WTO_AI_CROWD_CLUSTER_RADIUS_M', 'float', c.crowd.clusterRadiusM],
['WTO_AI_CROWD_CLUSTER_MAX_ALLIES', 'int', c.crowd.clusterMaxAllies],
['WTO_AI_CROWD_DISPERSE_STEP_M', 'float', c.crowd.disperseStepM],
['WTO_AI_CROWD_DISPERSE_HOLD_SEC', 'float', c.crowd.disperseHoldSec],
['WTO_AI_TERRAIN_MAX_CLIMB_DEG', 'float', c.terrain.maxClimbSlopeDeg],
['WTO_AI_TERRAIN_MAX_DROP_DEG', 'float', c.terrain.maxDropSlopeDeg],
['WTO_AI_TERRAIN_MAX_WATER_M', 'float', c.terrain.maxWaterDepthM],
['WTO_AI_TERRAIN_MARGIN_M', 'float', c.terrain.collisionMarginM],
['WTO_AI_TERRAIN_CREST_LOOKAHEAD_M', 'float', c.terrain.crestLookaheadM],
['WTO_AI_TERRAIN_RIDGE_MAX_DWELL_SEC', 'float', c.terrain.ridgeMaxDwellSec],
['WTO_AI_TERRAIN_RIDGE_MAX_SHOTS', 'int', c.terrain.ridgeMaxShots],
['WTO_AI_NAV_DRIVE_MODE', 'string', c.navigation.driveMode],
['WTO_AI_NAV_MAX_PHYS_BOTS', 'int', c.navigation.maxPhysBots],
['WTO_AI_NAV_STEER_SIGN', 'float', c.navigation.steerSign],
['WTO_AI_NAV_DEAD_ECHO_SEC', 'float', c.navigation.deadEchoSec],
['WTO_AI_NAV_CORNER_BRAKE_ACCEL', 'float', c.navigation.cornerBrakeAccel],
['WTO_AI_NAV_PIVOT_ANGLE_DEG', 'float', c.navigation.pivotAngleDeg],
['WTO_AI_NAV_STUCK_WINDOW_SEC', 'float', c.navigation.stuckWindowSec],
['WTO_AI_NAV_STUCK_MIN_MOVE_M', 'float', c.navigation.stuckMinMoveM],
['WTO_AI_NAV_UNSTICK_REV_SEC', 'float', c.navigation.unstickReverseSec],
['WTO_AI_NAV_TAC_REV_DIST_M', 'float', c.navigation.tacticalReverseDistM],
['WTO_AI_NAV_TAC_REV_MAX_SEC', 'float', c.navigation.tacticalReverseMaxSec],
['WTO_AI_TACTICS_VISION_RANGE_M', 'float', c.tactics.visionRangeM],
['WTO_AI_TACTICS_VISION_FOV_DEG', 'float', c.tactics.visionFovDeg],
['WTO_AI_TACTICS_PERIPHERAL_RANGE_M', 'float', c.tactics.peripheralRangeM],
['WTO_AI_TACTICS_ENGINE_AUDIO_M', 'float', c.tactics.engineAudioRangeM],
['WTO_AI_TACTICS_SHOT_AUDIO_M', 'float', c.tactics.shotAudioRangeM],
['WTO_AI_TACTICS_RADIO_SHARE_M', 'float', c.tactics.radioShareRangeM],
['WTO_AI_TACTICS_MEMORY_TTL_SEC', 'float', c.tactics.memoryTtlSec],
['WTO_AI_TACTICS_STICKY_SEC', 'float', c.tactics.targetStickinessSec],
['WTO_AI_TACTICS_PEEK_COOLDOWN_SEC', 'float', c.tactics.peekCooldownSec],
['WTO_AI_FC_MAX_RANGE_M', 'float', c.fireControl.maxEngageRangeM],
['WTO_AI_FC_BASE_ALIGN_DEG', 'float', c.fireControl.baseAlignDeg],
['WTO_AI_FC_CLOSE_HIT_RADIUS_M', 'float', c.fireControl.closeHitRadiusM],
['WTO_AI_FC_BARREL_SETTLE_DEG_SEC', 'float', c.fireControl.barrelSettleDegSec],
['WTO_AI_FC_SETTLE_HOLD_SEC', 'float', c.fireControl.settleHoldSec],
['WTO_AI_FC_UNSTAB_STOP_MPS', 'float', c.fireControl.unstabilizedStopSpeedMps],
['WTO_AI_FC_STAB_CREEP_MPS', 'float', c.fireControl.stabilizedCreepSpeedMps],
['WTO_AI_FC_FRIENDLY_CORRIDOR_M', 'float', c.fireControl.friendlyCorridorM],
['WTO_AI_DIAG_TELEMETRY', 'bool', c.diagnostics.telemetry],
['WTO_AI_DIAG_INTERVAL_SEC', 'float', c.diagnostics.telemetryIntervalSec],
];
}
function formatDasLiteral(name: string, kind: 'bool' | 'int' | 'float' | 'string', value: boolean | number | string): string {
if (kind === 'bool') {
if (typeof value !== 'boolean') throw new Error(`ground AI config ${name} must be boolean`);
return value ? 'true' : 'false';
}
if (kind === 'int') {
if (typeof value !== 'number' || !Number.isInteger(value) || value < -2147483648 || value > 2147483647) {
throw new Error(`ground AI config ${name} must be a 32-bit integer`);
}
return String(value);
}
if (kind === 'float') {
if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`ground AI config ${name} must be finite`);
const text = String(value);
return text.includes('.') || text.includes('e') || text.includes('E') ? text : `${text}.0`;
}
if (typeof value !== 'string' || /[\r\n\0]/.test(value)) {
throw new Error(`ground AI config ${name} must be a single-line string`);
}
return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
}
+22 -1
View File
@@ -58,9 +58,30 @@ export {
isHardlinkableResource,
type HardlinkResourceRules,
} from './hardlink-resources.ts';
export {
GAME_AI_ARCHIVE_FOLDER,
GAME_AI_CONFIG_FILE,
GAME_PACK_FILE,
rebuildGamePack,
type GamePackResult,
type GroundAiBuildInputs,
} from './ground-ai/game-pack.ts';
export {
compileGroundAiConfigDas,
isGroundAiActive,
type GroundAiConfig,
} from './ground-ai/ground-ai-config.ts';
export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts';
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts';
export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts';
export {
AI_LIST_PATH,
ENGINE_SETTINGS_PATH,
EXTRA_STORE_BUNDLE_GUID_MAP,
EXTRA_STORE_BUNDLE_GUIDS,
rebuildMainPack,
type MainPackOptions,
type MainPackResult,
} from './main-pack.ts';
export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts';
export { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts';
+31 -5
View File
@@ -20,6 +20,7 @@ import { editPackBlks } from './pack-edit.ts';
export const ENGINE_SETTINGS_PATH = 'config/settings.blk';
export const GUI_CONFIG_PATH = 'config/gui.blk';
export const AI_LIST_PATH = 'gamedata/ai/ailist.blk';
const NETWORK_BLOCK = 'network';
/**
@@ -34,9 +35,15 @@ export const EXTRA_STORE_BUNDLE_GUIDS: ReadonlyArray<readonly [entitlement: stri
export const EXTRA_STORE_BUNDLE_GUID_MAP: Readonly<Record<string, string>> = Object.fromEntries(EXTRA_STORE_BUNDLE_GUIDS);
export interface MainPackOptions {
/** Replace stock tankBot behavior children with `success` so custom chassis control owns steering. */
readonly yieldStockTankDrive?: boolean;
}
export interface MainPackResult {
readonly pack: Uint8Array;
readonly addresses: readonly AddressChange[];
readonly yieldedStockTankDrive: boolean;
}
export function rebuildMainPack(
@@ -44,12 +51,13 @@ export function rebuildMainPack(
endpoint: LocalEndpoint,
extraBundles: ReadonlyArray<readonly [string, string]> = [],
extraAddonFolders: readonly string[] = [],
options: MainPackOptions = {},
): MainPackResult {
let addresses: AddressChange[] = [];
const pack = editPackBlks(stockPack, [
const edits = [
{
path: ENGINE_SETTINGS_PATH,
edit: (root) => {
edit: (root: BlkBlock) => {
const network = findBlock(root, NETWORK_BLOCK);
if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`);
addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]);
@@ -58,10 +66,15 @@ export function rebuildMainPack(
},
{
path: GUI_CONFIG_PATH,
edit: (root) => registerStoreBundleGuids(root, [...EXTRA_STORE_BUNDLE_GUIDS, ...extraBundles]),
edit: (root: BlkBlock) => registerStoreBundleGuids(root, [...EXTRA_STORE_BUNDLE_GUIDS, ...extraBundles]),
},
]);
return { pack, addresses };
...(options.yieldStockTankDrive ? [{
path: AI_LIST_PATH,
edit: (root: BlkBlock) => yieldTankBotBehaviorTree(root),
}] : []),
];
const pack = editPackBlks(stockPack, edits);
return { pack, addresses, yieldedStockTankDrive: options.yieldStockTankDrive === true };
}
function registerStoreBundleGuids(guiRoot: BlkBlock, bundles: ReadonlyArray<readonly [string, string]>): void {
@@ -70,3 +83,16 @@ function registerStoreBundleGuids(guiRoot: BlkBlock, bundles: ReadonlyArray<read
setParam(guidBlock, entitlement, { type: 'string', value: guid });
}
}
function yieldTankBotBehaviorTree(aiRoot: BlkBlock): void {
const matches = aiRoot.blocks.filter((block) =>
block.name === 'selector' &&
block.params.some((param) => param.name === 'name' && param.value.type === 'string' && param.value.value === 'tankBot'),
);
if (matches.length !== 1) {
throw new Error(`expected 1 "tankBot" selector in ${AI_LIST_PATH}, found ${matches.length}`);
}
const tankBot = matches[0]!;
tankBot.blocks.length = 0;
tankBot.blocks.push({ name: 'success', params: [], blocks: [] });
}