From ac35c258518562f1e7821ed3a166d6a2224306cf Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:25:04 +0800 Subject: [PATCH] feat(ground-ai): add ready-rack dual-ammo bot spawn loadouts and shell switching Select realistic ready-rack dual-shell loadouts for AI tanks on the local server, inject them natively on bot spawn, and switch between anti-armor and soft-target shells in battle: - Add the loadout section to tuning/ground-ai.jsonc (lowReadyRackThreshold, topUpAmmoCount, primaryAmmoPct, secondaryMinRounds, penetrationCompareDistM), validated in ground-ai-tuning.ts. - Add the tank-bot-ammo v2 dataset (apps/server/src/game-data/datasets/ tank-bot-ammo.ts) reading primary cannon weapon name, capacity, firstStage/autoLoad shell ready-rack counts (excluding separate charges), and selectable shell modifications (using Lanz-Odermatt kinetic fields, cumulativeDamage, armorpower, and transitive reqModification chains). - Add selectBotTankLoadouts (apps/server/src/battle/bot-tank-loadouts.ts): carry ready-rack count when >= 15 (top up to 22 when smaller or absent, clamped to gun capacity), skip SPAA/belt autocannons, pick highest-tier APFSDS/anti-armor primary (~80%) plus HE/HESH/HEAT secondary (~20%, min 3 rounds) when available, and attach required addModification entries and per-tank wtoAmmo_ strings to customBots when mode != stock. - Hook Unit::changeAircraft (already located dynamically on .37 and .58) in native/wto-net/src/local_mp_loadout.c to assign the 24-byte ChangeUnitReflection.bullets entries via bullet_vec_assign for LocalMP bot spawns (async == 0, non-local bot MPlayer), leaving player spawns untouched. - Track soft-target vs anti-armor shell classes in wto_ai_specs_common.das and write gun.nextBulletType in wto_ai_fire_common.das to queue HE/HESH against light/narrow targets and APFSDS/AP against MBTs/heavy armor. Verified MSVC build of wto_ws.dll (0 warnings in project C sources), root and launcher type checks, 14/14 check-patches on 2.61.0.58, 12/12 LocalMP module installation, clean daScript load (wto_ai_runtime.das loaded in 211 ms, 0 compile errors), and real 2.61.0.58 loadout selection on cn_ztz_96a (18 APFSDS + 4 HE), germ_leopard_2a4 (12 DM23 + 3 HEATFS), ussr_t_80bvm (22 3BM60 + 6 HE), us_m1a2_abrams (14 M829A2 + 4 HEAT-MP), ussr_t_34_1941 (18 APHEBC + 4 HE), and ussr_zsu_23_4 (stock belt kept). Live battle acceptance begins in Step 9. --- apps/server/src/battle/battle-matchmaker.ts | 6 +- .../src/battle/battle-mission-settings.ts | 16 ++ apps/server/src/battle/battle-ranks.ts | 9 +- apps/server/src/battle/bot-tank-loadouts.ts | 135 ++++++++++ .../src/game-data/datasets/tank-bot-ammo.ts | 244 ++++++++++++++++++ apps/server/src/server.ts | 6 + apps/server/src/tuning/ground-ai-tuning.ts | 11 + apps/server/tuning/ground-ai.jsonc | 11 + game-ai/ground/wto_ai_combat_types_common.das | 2 + game-ai/ground/wto_ai_fire_common.das | 52 +++- game-ai/ground/wto_ai_specs_common.das | 5 + native/wto-net/src/local_mp_loadout.c | 104 +++++++- .../patcher/src/ground-ai/ground-ai-config.ts | 9 + packages/patcher/src/index.ts | 1 + 14 files changed, 601 insertions(+), 10 deletions(-) create mode 100644 apps/server/src/battle/bot-tank-loadouts.ts create mode 100644 apps/server/src/game-data/datasets/tank-bot-ammo.ts diff --git a/apps/server/src/battle/battle-matchmaker.ts b/apps/server/src/battle/battle-matchmaker.ts index 0d2dfaa..e93b68c 100644 --- a/apps/server/src/battle/battle-matchmaker.ts +++ b/apps/server/src/battle/battle-matchmaker.ts @@ -25,6 +25,7 @@ import { import type { BattleSessionStore } from './battle-session-store.ts'; import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts'; import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts'; +import type { BotTankLoadout } from './bot-tank-loadouts.ts'; import type { BattleTuning } from './battle-tuning.ts'; export interface BattleCrewSlot { @@ -106,6 +107,7 @@ export class BattleMatchmaker { readonly #spawnRules: BattleSpawnRulesData; readonly #aircraftLoadouts: ReadonlyMap; readonly #tankWeights: TankLineupWeights | undefined; + readonly #tankLoadouts: ReadonlyMap | undefined; readonly #filterMissions: MissionPoolFilter | undefined; constructor( @@ -116,6 +118,7 @@ export class BattleMatchmaker { spawnRules: BattleSpawnRulesData, aircraftLoadouts: ReadonlyMap, tankWeights: TankLineupWeights | undefined, + tankLoadouts?: ReadonlyMap, filterMissions?: MissionPoolFilter, ) { this.#gameModes = gameModes; @@ -126,6 +129,7 @@ export class BattleMatchmaker { this.#spawnRules = spawnRules; this.#aircraftLoadouts = aircraftLoadouts; this.#tankWeights = tankWeights; + this.#tankLoadouts = tankLoadouts; this.#filterMissions = filterMissions; } @@ -185,7 +189,7 @@ export class BattleMatchmaker { minMrank, maxMrank, limitPerType: this.#tuning.botPoolLimitPerType, - }, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights); + }, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts); return { ok: true, launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots), diff --git a/apps/server/src/battle/battle-mission-settings.ts b/apps/server/src/battle/battle-mission-settings.ts index d76e8df..bc4571d 100644 --- a/apps/server/src/battle/battle-mission-settings.ts +++ b/apps/server/src/battle/battle-mission-settings.ts @@ -141,6 +141,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock { poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts), poolBlock('allowedShips', 'ship', plan.customBots.ships), ); + addTankAmmoParams(bots, plan.customBots.tanks); return bots; } @@ -156,11 +157,26 @@ function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tan setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset)); for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification)); } + if (entry.tankLoadout !== undefined) { + for (const modification of entry.tankLoadout.modifications) appendParam(block, 'addModification', text(modification)); + } pool.blocks.push(block); } return pool; } +/** Per-tank bot ammo strings (`weapon|mod0:count0|mod1:count1`) read by local_mp_loadout.c. */ +function addTankAmmoParams(bots: BlkBlock, entries: CustomBotsPool['tanks']): void { + const seen = new Set(); + for (const entry of entries) { + const loadout = entry.tankLoadout; + if (!loadout || loadout.bullets.length === 0 || seen.has(entry.name)) continue; + seen.add(entry.name); + const parts = [loadout.weaponName, ...loadout.bullets.slice(0, 2).map((s) => `${s.modName}:${s.count}`)]; + setParam(bots, `wtoAmmo_${entry.name}`, text(parts.join('|'))); + } +} + function text(value: string): BlkValue { return { type: 'string', value }; } diff --git a/apps/server/src/battle/battle-ranks.ts b/apps/server/src/battle/battle-ranks.ts index d252695..a3b21a6 100644 --- a/apps/server/src/battle/battle-ranks.ts +++ b/apps/server/src/battle/battle-ranks.ts @@ -10,6 +10,7 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts'; import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts'; +import type { BotTankLoadout } from './bot-tank-loadouts.ts'; const COUNTRY_PREFIX = 'country_'; @@ -23,6 +24,7 @@ export interface BotPoolEntry { readonly country: string; readonly weight: number; readonly aircraftLoadout?: BotAircraftLoadout; + readonly tankLoadout?: BotTankLoadout; } export interface CustomBotsPool { @@ -135,12 +137,17 @@ export function selectCustomBots( query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap, tankWeights?: TankLineupWeights, + tankLoadouts?: ReadonlyMap, ): CustomBotsPool { const allowed = new Set(query.allowedClasses); const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))]; const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : []; + const rawTanks = allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query, tankWeights) : []; return { - tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query, tankWeights) : [], + tanks: tankLoadouts ? rawTanks.map((entry) => { + const tankLoadout = tankLoadouts.get(entry.name); + return tankLoadout === undefined ? entry : { ...entry, tankLoadout }; + }) : rawTanks, aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => { const aircraftLoadout = aircraftLoadouts.get(entry.name); return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout }; diff --git a/apps/server/src/battle/bot-tank-loadouts.ts b/apps/server/src/battle/bot-tank-loadouts.ts new file mode 100644 index 0000000..d8bacfb --- /dev/null +++ b/apps/server/src/battle/bot-tank-loadouts.ts @@ -0,0 +1,135 @@ +/** + * Offline AI tank spawn ammunition selector: + * - Total carried rounds follow the vehicle's first-stage / autoloader ready rack, topped up + * when below the configured threshold (clamped to main gun capacity). + * - Primary shell prefers legal APFSDS, otherwise ranks anti-armor shells by 500 m penetration. + * - Secondary shell carries a small share of HE / HEAT / HESH when available for soft targets. + */ +import type { GroundAiLoadoutConfig } from '@wto/patcher'; +import type { TankAmmoProfile, TankBotAmmoData, TankShellChoice } from '../game-data/datasets/tank-bot-ammo.ts'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import { vehicleTypeOfClass } from '../research/vehicle-types.ts'; + +export interface BotTankBulletSlot { + readonly modName: string; + readonly count: number; +} + +export interface BotTankLoadout { + readonly weaponName: string; + readonly bullets: readonly BotTankBulletSlot[]; + readonly modifications: readonly string[]; +} + +export function selectBotTankLoadouts( + vehicles: readonly CatalogueVehicle[], + ammoData: TankBotAmmoData, + config: GroundAiLoadoutConfig, +): ReadonlyMap { + const result = new Map(); + for (const vehicle of vehicles) { + if (vehicleTypeOfClass(vehicle.unitClass) !== 'Tank' || vehicle.unitClass === 'exp_SPAA') continue; + const profile = ammoData[vehicle.name]; + if (!profile || profile.isBelt || profile.maxBullets <= 0) continue; + const loadout = chooseTankLoadout(profile, config); + if (loadout !== undefined) result.set(vehicle.name, loadout); + } + return result; +} + +function chooseTankLoadout(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): BotTankLoadout | undefined { + const combatShells = profile.shells.filter((shell) => !isNonCombatShell(shell.bulletType)); + if (combatShells.length === 0) return undefined; + + const primary = pickPrimaryShell(combatShells); + if (!primary) return undefined; + const totalRounds = computeCarriedRounds(profile, config); + if (totalRounds <= 0) return undefined; + + const secondary = pickSecondaryShell(combatShells, primary); + const bullets = splitRounds(primary, secondary, totalRounds, config); + const modSet = new Set(); + for (const chosen of [primary, ...(bullets.length > 1 && secondary ? [secondary] : [])]) { + if (chosen.modName) modSet.add(chosen.modName); + for (const req of chosen.requires) modSet.add(req); + } + return { + weaponName: profile.weaponName, + bullets, + modifications: [...modSet].sort(), + }; +} + +function computeCarriedRounds(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): number { + const want = profile.readyRack >= config.lowReadyRackThreshold + ? profile.readyRack + : config.topUpAmmoCount; + return Math.max(1, Math.min(want, profile.maxBullets)); +} + +function pickPrimaryShell(shells: readonly TankShellChoice[]): TankShellChoice | undefined { + const ranked = [...shells].sort((a, b) => compareAntiArmor(a, b)); + return ranked[0]; +} + +function compareAntiArmor(a: TankShellChoice, b: TankShellChoice): number { + const tierA = antiArmorTier(a.bulletType); + const tierB = antiArmorTier(b.bulletType); + if (tierA !== tierB) return tierB - tierA; + const scoreA = a.pen500Mm + (isApheFamily(a.bulletType) ? 12 : 0); + const scoreB = b.pen500Mm + (isApheFamily(b.bulletType) ? 12 : 0); + if (scoreA !== scoreB) return scoreB - scoreA; + if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps; + return a.modName.localeCompare(b.modName); +} + +function antiArmorTier(bulletType: string): number { + if (bulletType.includes('apds_fs')) return 5; + if (bulletType.includes('atgm')) return 4; + if (bulletType.includes('apds')) return 3; + if (bulletType.includes('heat') || isApheFamily(bulletType) || bulletType.startsWith('ap')) return 2; + if (bulletType.includes('hesh')) return 1; + return 0; +} + +function pickSecondaryShell(shells: readonly TankShellChoice[], primary: TankShellChoice): TankShellChoice | undefined { + const candidates = shells.filter((shell) => shell.modName !== primary.modName && isSoftTargetShell(shell.bulletType)); + if (candidates.length === 0) return undefined; + return [...candidates].sort((a, b) => { + const heA = a.bulletType.includes('he_frag') ? 2 : (a.bulletType.includes('hesh') ? 1 : 0); + const heB = b.bulletType.includes('he_frag') ? 2 : (b.bulletType.includes('hesh') ? 1 : 0); + if (heA !== heB) return heB - heA; + if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps; + return a.modName.localeCompare(b.modName); + })[0]; +} + +function splitRounds( + primary: TankShellChoice, + secondary: TankShellChoice | undefined, + totalRounds: number, + config: GroundAiLoadoutConfig, +): BotTankBulletSlot[] { + if (!secondary || config.primaryAmmoPct >= 100 || config.secondaryMinRounds <= 0 || totalRounds < config.secondaryMinRounds * 2 + 2) { + return [{ modName: primary.modName, count: totalRounds }]; + } + const wantSec = Math.round((totalRounds * (100 - config.primaryAmmoPct)) / 100); + const secCount = Math.min(totalRounds - 1, Math.max(config.secondaryMinRounds, wantSec)); + const priCount = totalRounds - secCount; + return [ + { modName: primary.modName, count: priCount }, + { modName: secondary.modName, count: secCount }, + ]; +} + +function isNonCombatShell(bulletType: string): boolean { + return bulletType.includes('smoke') || bulletType.includes('practice') || bulletType.includes('shrapnel'); +} + +function isSoftTargetShell(bulletType: string): boolean { + return bulletType.includes('he_frag') || bulletType.includes('hesh') || bulletType.includes('heat'); +} + +function isApheFamily(bulletType: string): boolean { + return bulletType.includes('aphe') || bulletType.includes('apcbc') || bulletType.includes('apbc'); +} diff --git a/apps/server/src/game-data/datasets/tank-bot-ammo.ts b/apps/server/src/game-data/datasets/tank-bot-ammo.ts new file mode 100644 index 0000000..91d79ab --- /dev/null +++ b/apps/server/src/game-data/datasets/tank-bot-ammo.ts @@ -0,0 +1,244 @@ +/** + * Dataset: primary cannon weapon name, capacity, first-stage/autoloader ready-rack count, + * and selectable ammunition groups (with penetration and prerequisite modifications) for + * every ground tank model in `aces.vromfs.bin` + `char.vromfs.bin`. + */ +import { findBlock, type BlkBlock } from '@wto/blk'; +import type { Dataset, DatasetSource } from './dataset.ts'; +import { boolField, numberField, stringField, stringList } from './blk-fields.ts'; + +const VEHICLE_ECONOMY = 'config/wpcost.blk'; +const MODIFICATIONS_CONFIG = 'config/modifications.blk'; +const TANK_MODELS_PREFIX = 'gamedata/units/tankmodels/'; + +export interface TankShellChoice { + /** Modification name expected by ChangeUnitReflection.bullets[i] (`""` for stock default). */ + readonly modName: string; + readonly bulletType: string; + readonly speedMps: number; + /** Estimated normal penetration at 500 m (mm) for deterministic ranking. */ + readonly pen500Mm: number; + /** Transitive prerequisite modifications needed to unlock this shell. */ + readonly requires: readonly string[]; +} + +export interface TankAmmoProfile { + readonly weaponName: string; + readonly maxBullets: number; + readonly isBelt: boolean; + /** Total firstStage / autoLoad / ammoLoadedInGun shell slots (excluding separate charges). */ + readonly readyRack: number; + readonly shells: readonly TankShellChoice[]; +} + +export type TankBotAmmoData = Readonly>; + +interface GlobalModInfo { + readonly bulletMod?: string; + readonly requires: readonly string[]; +} + +interface WeaponBulletMeta { + readonly bulletType: string; + readonly speedMps: number; + readonly pen500Mm: number; +} + +export const tankBotAmmo: Dataset = { + id: 'tank-bot-ammo', + version: 2, + extract(source: DatasetSource): TankBotAmmoData { + const globalMods = readGlobalModInfo(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG)); + const wpcost = source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY); + const acesPaths = new Set(source.listFiles('aces.vromfs.bin').map((p) => p.toLowerCase())); + const weaponCache = new Map }>(); + const out: Record = {}; + + for (const vehicleBlk of wpcost.blocks) { + const unitPath = `${TANK_MODELS_PREFIX}${vehicleBlk.name.toLowerCase()}.blk`; + if (!acesPaths.has(unitPath)) continue; + const profile = extractTankProfile(source, acesPaths, weaponCache, globalMods, vehicleBlk, unitPath); + if (profile !== undefined) out[vehicleBlk.name] = profile; + } + return out; + }, +}; + +function readGlobalModInfo(root: BlkBlock): ReadonlyMap { + const mods = findBlock(root, 'modifications'); + const map = new Map(); + for (const entry of mods?.blocks ?? []) { + const effects = findBlock(entry, 'effects'); + const bulletMod = stringField(effects, 'additiveBulletMod') ?? stringField(effects, 'bulletMod'); + map.set(entry.name, { + ...(bulletMod !== undefined ? { bulletMod } : {}), + requires: stringList(entry, 'reqModification'), + }); + } + return map; +} + +function extractTankProfile( + source: DatasetSource, + acesPaths: ReadonlySet, + weaponCache: Map }>, + globalMods: ReadonlyMap, + wpcostVehicle: BlkBlock, + unitPath: string, +): TankAmmoProfile | undefined { + const unitBlk = source.readBlk('aces.vromfs.bin', unitPath); + const mainWeapon = findMainGunBlock(unitBlk); + if (!mainWeapon) return undefined; + const rawBlkPath = stringField(mainWeapon, 'blk'); + const maxBullets = Math.trunc(numberField(mainWeapon, 'bullets') ?? 0); + if (!rawBlkPath || maxBullets <= 0) return undefined; + const lowerBlkPath = rawBlkPath.toLowerCase(); + if (!acesPaths.has(lowerBlkPath)) return undefined; + + const weaponName = basenameWithoutExt(rawBlkPath); + const weaponMeta = loadWeaponMeta(source, weaponCache, lowerBlkPath); + const readyRack = countReadyRackShells(unitBlk, stringField(mainWeapon, 'trigger') ?? 'gunner0'); + const shells = collectSelectableShells(wpcostVehicle, unitBlk, globalMods, weaponMeta); + if (shells.length === 0) return undefined; + return { weaponName, maxBullets, isBelt: weaponMeta.isBelt, readyRack, shells }; +} + +function findMainGunBlock(unitBlk: BlkBlock): BlkBlock | undefined { + const common = findBlock(unitBlk, 'commonWeapons'); + if (!common) return undefined; + return common.blocks.find((block) => + stringField(block, 'trigger') === 'gunner0' + && !(stringField(block, 'blk') ?? '').toLowerCase().includes('dummy_weapon')); +} + +function countReadyRackShells(unitBlk: BlkBlock, mainTrigger: string): number { + const stowages = findBlock(unitBlk, 'ammoStowages'); + if (!stowages) return 0; + let total = 0; + for (const stow of stowages.blocks) { + const triggers = stringList(stow, 'weaponTrigger'); + if (triggers.length > 0 && !triggers.includes(mainTrigger)) continue; + for (const cluster of stow.blocks) { + if (cluster.name !== 'shells') continue; + const isReady = boolField(cluster, 'firstStage') === true + || boolField(cluster, 'autoLoad') === true + || boolField(cluster, 'ammoLoadedInGun') === true; + if (!isReady) continue; + for (const slot of cluster.blocks) total += Math.max(0, Math.trunc(numberField(slot, 'count') ?? 0)); + } + } + return total; +} + +function loadWeaponMeta( + source: DatasetSource, + cache: Map }>, + lowerPath: string, +) { + const cached = cache.get(lowerPath); + if (cached) return cached; + const blk = source.readBlk('aces.vromfs.bin', lowerPath); + const isBelt = boolField(blk, 'isBulletBelt') === true; + const defaultBlock = findBlock(blk, 'bullet'); + const defaultBullet = defaultBlock ? parseBulletMeta(defaultBlock) : undefined; + const sets = new Map(); + for (const child of blk.blocks) { + if (child.name === 'bullet') continue; + const subBullet = findBlock(child, 'bullet'); + if (!subBullet) continue; + const meta = parseBulletMeta(subBullet); + if (meta) sets.set(child.name, meta); + } + const entry = { isBelt, ...(defaultBullet ? { defaultBullet } : {}), sets }; + cache.set(lowerPath, entry); + return entry; +} + +function parseBulletMeta(bullet: BlkBlock): WeaponBulletMeta | undefined { + const bulletType = (stringField(bullet, 'bulletType') ?? '').toLowerCase(); + if (!bulletType) return undefined; + const speedMps = numberField(bullet, 'speed') ?? 0; + const pen500Mm = estimatePen500Mm(bullet, bulletType, speedMps); + return { bulletType, speedMps, pen500Mm }; +} + +function estimatePen500Mm(bullet: BlkBlock, bulletType: string, speedMps: number): number { + const cum = numberField(findBlock(bullet, 'cumulativeDamage'), 'armorPower'); + const apBlock = findBlock(bullet, 'armorpower'); + const ap500 = numberField(apBlock, 'ArmorPower500m') ?? numberField(apBlock, 'ArmorPower0m') ?? 0; + if (bulletType.includes('apds_fs')) { + const dmgBlock = findBlock(bullet, 'damage'); + const kinetic = dmgBlock ? findBlock(dmgBlock, 'kinetic') : undefined; + const workLen = numberField(kinetic, 'lanzOdermattWorkingLength') + ?? numberField(kinetic, 'WorkingLength') + ?? numberField(kinetic, 'Length') + ?? 0; + const density = numberField(kinetic, 'lanzOdermattDensity') ?? numberField(kinetic, 'Density') ?? 17000; + if (workLen > 0) return Math.max(ap500, Math.round(workLen * Math.sqrt(density / 7850) * (speedMps / 1700) * 0.85)); + return Math.max(ap500, Math.round(speedMps * 0.24)); + } + if (cum !== undefined && cum > ap500) return cum; + if (ap500 > 0) return ap500; + const mass = numberField(bullet, 'mass') ?? 0; + const cal = numberField(bullet, 'damageCaliber') ?? numberField(bullet, 'caliber') ?? 0; + if (mass > 0 && cal > 0 && speedMps > 100 && !bulletType.includes('he_') && !bulletType.includes('smoke')) { + return Math.round(0.0022 * Math.pow(mass, 0.55) * Math.pow(speedMps, 1.43) / Math.pow(cal * 1000, 0.65)); + } + return 0; +} + +function collectSelectableShells( + wpcostVehicle: BlkBlock, + unitBlk: BlkBlock, + globalMods: ReadonlyMap, + weaponMeta: { defaultBullet?: WeaponBulletMeta; sets: Map }, +): TankShellChoice[] { + const out: TankShellChoice[] = []; + if (weaponMeta.defaultBullet) { + out.push({ modName: '', ...weaponMeta.defaultBullet, requires: [] }); + } + const wpModsBlock = findBlock(wpcostVehicle, 'modifications'); + const unitModsBlock = findBlock(unitBlk, 'modifications'); + const reqMap = new Map(); + for (const mod of wpModsBlock?.blocks ?? []) reqMap.set(mod.name, stringList(mod, 'reqModification')); + + for (const mod of wpModsBlock?.blocks ?? []) { + if (numberField(mod, 'ammoCount') === undefined) continue; + const unitMod = unitModsBlock ? findBlock(unitModsBlock, mod.name) : undefined; + const unitModEffects = unitMod ? findBlock(unitMod, 'effects') : undefined; + const setName = stringField(unitModEffects, 'additiveBulletMod') + ?? stringField(unitModEffects, 'bulletMod') + ?? globalMods.get(mod.name)?.bulletMod + ?? mod.name; + const meta = weaponMeta.sets.get(setName); + if (!meta) continue; + out.push({ + modName: mod.name, + ...meta, + requires: collectTransitiveReqs(mod.name, reqMap, globalMods), + }); + } + return out; +} + +function collectTransitiveReqs( + modName: string, + reqMap: ReadonlyMap, + globalMods: ReadonlyMap, +): string[] { + const seen = new Set(); + const queue = [...(reqMap.get(modName) ?? []), ...(globalMods.get(modName)?.requires ?? [])]; + while (queue.length > 0) { + const next = queue.pop()!; + if (!next || next === modName || seen.has(next)) continue; + seen.add(next); + for (const parent of reqMap.get(next) ?? []) queue.push(parent); + } + return [...seen].sort(); +} + +function basenameWithoutExt(path: string): string { + const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + const file = slash >= 0 ? path.slice(slash + 1) : path; + return file.endsWith('.blk') ? file.slice(0, -4) : file; +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1dc0e60..b58597d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -10,6 +10,7 @@ import { BattleEconomy } from './battle/battle-economy.ts'; import { BattleMatchmaker } from './battle/battle-matchmaker.ts'; import { BattleSessionStore } from './battle/battle-session-store.ts'; import { selectBotAircraftLoadouts } from './battle/bot-aircraft-loadouts.ts'; +import { selectBotTankLoadouts } from './battle/bot-tank-loadouts.ts'; import { actionTable } from './char/actions/action-table.ts'; import { CharService } from './char/char-service.ts'; import { ClanStore } from './clans/clan-store.ts'; @@ -31,6 +32,7 @@ import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts'; import { externalItemSources } from './game-data/datasets/external-item-sources.ts'; import { flightModelPresets } from './game-data/datasets/flight-model-presets.ts'; +import { tankBotAmmo } from './game-data/datasets/tank-bot-ammo.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.ts'; import { multiplayerMissions, type MultiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; import { shopCountries } from './game-data/datasets/shop-countries.ts'; @@ -173,6 +175,9 @@ export async function startServer(options: ServerOptions): Promise modRuntime.runBattleFilterMissions(ctx), ); const economy = new BattleEconomy( diff --git a/apps/server/src/tuning/ground-ai-tuning.ts b/apps/server/src/tuning/ground-ai-tuning.ts index 0984a62..2b464bf 100644 --- a/apps/server/src/tuning/ground-ai-tuning.ts +++ b/apps/server/src/tuning/ground-ai-tuning.ts @@ -27,6 +27,7 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning { const diag = reader.object('diagnostics'); return { mode: readMode(reader), + loadout: readLoadoutSection(reader.object('loadout')), lineupWeights: readLineupWeights(reader.object('lineupWeights')), cadence: { maxBots: cadence.int('maxBots', { min: 1, max: 64 }), @@ -60,6 +61,16 @@ function readMode(reader: TuningReader): GroundAiMode { return known; } +function readLoadoutSection(loadout: TuningReader): GroundAiTuning['loadout'] { + return { + lowReadyRackThreshold: loadout.int('lowReadyRackThreshold', { min: 1, max: 60 }), + topUpAmmoCount: loadout.int('topUpAmmoCount', { min: 4, max: 80 }), + primaryAmmoPct: loadout.int('primaryAmmoPct', { min: 50, max: 100 }), + secondaryMinRounds: loadout.int('secondaryMinRounds', { min: 0, max: 20 }), + penetrationCompareDistM: loadout.int('penetrationCompareDistM', { min: 100, max: 2000 }), + }; +} + function readLineupWeights(weights: TuningReader): TankLineupWeights { const range = { min: 0.01, max: 10 }; return { diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index ec1258a..a524ca9 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -8,6 +8,17 @@ // "stock": stock AI only, no scripts packed, stock lineup weights (troubleshooting). "mode": "full", + // AI tank spawn ammunition selection (offline values; ignored in "stock" mode). + // Carries first-stage / autoloader ready-rack capacity, topped up when below threshold, + // split between best anti-armor primary (APFSDS preferred) and HE/HEAT secondary when available. + "loadout": { + "lowReadyRackThreshold": 15, + "topUpAmmoCount": 22, + "primaryAmmoPct": 80, + "secondaryMinRounds": 3, + "penetrationCompareDistM": 500 + }, + // Relative pick weights of AI tank classes in a battle's bot pool. Offline values; ignored in // "stock" mode, where every vehicle keeps the stock weight of 1. "lineupWeights": { diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index a928357..6c30774 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -37,6 +37,8 @@ struct public WtoShellProfile dragCx : float = 0.35 massKg : float = 10.0 caliberM : float = 0.09 + isSoftShell : bool = false + isAntiArmor : bool = true [safe_when_uninitialized] struct public WtoPerceiveState diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index 0f3aada..ba6260a 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -19,6 +19,7 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_fire_gate_common @@ -74,8 +75,43 @@ def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec cons return [never_inline] -def private wto_inspect_primary_weapon(unit : Unit const?; now : float; - spec : WtoVehicleSpec const&; var fc : WtoFireState&) +def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&; wantSoft : bool) + if gun == null || spec.isAutocannonBelt + return + let setCount = length(gun.properties.bulletSets) + if setCount < 2 + return + var bestSoft = -1 + var bestArmor = -1 + var firstAvail = -1 + for bsIdx in range(setCount) + assume bs = gun.properties.bulletSets[bsIdx] + if bs.bulletsCount <= 0 || length(bs.bullet) <= 0 || bs.bullet[0] == null + continue + if firstAvail < 0 + firstAvail = bsIdx + let bName = bs.bullet[0].getName + if empty(bName) + continue + let h = ecs_hash(bName) + for si in range(spec.shellCount) + if spec.shells[si].nameHash != h + continue + if spec.shells[si].isSoftShell && bestSoft < 0 + bestSoft = bsIdx + elif spec.shells[si].isAntiArmor && bestArmor < 0 + bestArmor = bsIdx + break + var wantIdx = wantSoft ? (bestSoft >= 0 ? bestSoft : bestArmor) : (bestArmor >= 0 ? bestArmor : firstAvail) + if wantIdx < 0 + wantIdx = firstAvail + if wantIdx >= 0 && int(gun.nextBulletType) != wantIdx + gun.nextBulletType = uint8(wantIdx) + +[never_inline] +def private wto_inspect_primary_weapon(var unit : Unit?; now : float; + spec : WtoVehicleSpec const&; wantSoftShell : bool; + var fc : WtoFireState&) fc.turretNo = -1 fc.gunReady = false fc.reloading = false @@ -86,10 +122,10 @@ def private wto_inspect_primary_weapon(unit : Unit const?; now : float; var anyAlive = false var anyReserve = false var totalLoaded = 0 - foreach_primary_gun(unit.weap.Weapons) <| $(weapon) + foreach_primary_gun(unit.weap.Weapons) <| $(var weapon) if weapon == null || weapon.isDummyGun return - let gun = as_gun(weapon) + var gun = as_gun(weapon) if gun == null if weapon.prop.launcher && weapon.countBullets > 0 anyGun = true @@ -106,6 +142,7 @@ def private wto_inspect_primary_weapon(unit : Unit const?; now : float; anyAlive = true if fc.turretNo < 0 fc.turretNo = weapon.turretNo + wto_select_next_shell(gun, spec, wantSoftShell) wto_sync_active_shell(gun, spec, fc) if gun.isReadyToShoot fc.gunReady = true @@ -221,7 +258,12 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; set_unit_attack_type(unit, "attack_target") return set_unit_attack_type(unit, "dont_aim") - wto_inspect_primary_weapon(unit, now, slot.spec, slot.fire) + var wantSoftShell = false + if slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir + let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid) + if tgtIdx >= 0 + wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35 + wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire) var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0) var liveBarrelDir = unit.unitTm[0] let _preSample = wto_sample_turret_muzzle(unit, slot.fire.turretNo, muzzlePos, liveBarrelDir) diff --git a/game-ai/ground/wto_ai_specs_common.das b/game-ai/ground/wto_ai_specs_common.das index 28c5c53..b7e9339 100644 --- a/game-ai/ground/wto_ai_specs_common.das +++ b/game-ai/ground/wto_ai_specs_common.das @@ -88,11 +88,16 @@ def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicl if spec.shells[i].nameHash == h return let idx = spec.shellCount + let bt = bBlk |> datablock_getStr("bulletType", "") + let isSoft = find(bt, "he_frag") >= 0 || find(bt, "hesh") >= 0 + let isNonCombat = find(bt, "smoke") >= 0 || find(bt, "practice") >= 0 || find(bt, "shrapnel") >= 0 spec.shells[idx].nameHash = h spec.shells[idx].speedMps = spd spec.shells[idx].dragCx = cx spec.shells[idx].massKg = mass spec.shells[idx].caliberM = cal + spec.shells[idx].isSoftShell = isSoft + spec.shells[idx].isAntiArmor = !isSoft && !isNonCombat spec.shellCount = idx + 1 [never_inline] diff --git a/native/wto-net/src/local_mp_loadout.c b/native/wto-net/src/local_mp_loadout.c index 341974d..3c4e1ad 100644 --- a/native/wto-net/src/local_mp_loadout.c +++ b/native/wto-net/src/local_mp_loadout.c @@ -13,8 +13,19 @@ #include "MinHook.h" +#include #include +typedef struct ReflBulletEntry { + const char *weapon_name; + const char *bullet_mod; + uint16_t count; + uint8_t trigger_group; + uint8_t pad[5]; +} ReflBulletEntry; + +C_ASSERT(sizeof(ReflBulletEntry) == 24); + typedef void (__fastcall *SemChangeAircraftSendFn)( void *self, const char *unit_name, const char *weapon_name, const void *modifications_blk, const char *skin_name, const void *custom_preset_blk, uint8_t flags_byte, @@ -39,9 +50,9 @@ typedef uint64_t (__fastcall *StrHashFnv1Fn)(const char *str, size_t len); typedef int32_t (__fastcall *NameMapAddNameIdFn)(void *map, const char *str, size_t len, uint64_t hash); static SemChangeAircraftSendFn orig_sem_send; +static UnitChangeAircraftFn orig_unit_change_aircraft; static ReflCtorFn fn_refl_ctor; static ReflDtorFn fn_refl_dtor; -static UnitChangeAircraftFn fn_unit_change_aircraft; static DataBlockSetFromFn fn_datablock_set_from; static DataBlockDtorFn fn_datablock_dtor; static BulletSetVecAssignFn fn_bullet_vec_assign; @@ -120,6 +131,93 @@ static void apply_mplayer_spawn_base(uint8_t *mplayer, int32_t req_base_id) *(float *)(mplayer + LMP_MP_OFF_SPAWN_POS_Z) = 0.0f; } +static int is_bot_unit(const uint8_t *unit) +{ + const uint8_t *owner = *(const uint8_t *const *)(unit + LMP_UNIT_OFF_MPLAYER); + return owner != NULL && !local_mp_is_local_mplayer(owner) && + *(const int64_t *)(owner + LMP_MP_OFF_USER_ID) < -1; +} + +static int parse_bullet_pair(const char *token, char *mod_buf, size_t mod_size, uint16_t *out_count) +{ + const char *colon = strchr(token, ':'); + size_t mod_len; + unsigned long parsed; + char *end; + + if (colon == NULL) + return 0; + mod_len = (size_t)(colon - token); + if (mod_len >= mod_size) + return 0; + memcpy(mod_buf, token, mod_len); + mod_buf[mod_len] = '\0'; + parsed = strtoul(colon + 1, &end, 10); + if (end == colon + 1 || (*end != '\0' && *end != '|') || parsed == 0 || parsed > 0xfffeu) + return 0; + *out_count = (uint16_t)parsed; + return 1; +} + +static void apply_bot_tank_ammo(const uint8_t *unit, uint8_t *refl) +{ + const char *raw_name, *unit_name, *spec, *p1, *p2; + char key[128], weapon[96], b0[96], b1[96]; + uint16_t c0 = 0, c1 = 0; + size_t wlen; + ReflBulletEntry slots[2]; + size_t count = 0; + + if (g_local_mp_mission_settings == NULL || g_lmp_datablock_get_str == NULL || !is_bot_unit(unit)) + return; + raw_name = *(const char *const *)(refl + LMP_REFL_OFF_UNIT_NAME); + if (raw_name == NULL || *raw_name == '\0') + return; + unit_name = strncmp(raw_name, "tankModels/", 11) == 0 ? raw_name + 11 : raw_name; + if (strlen(unit_name) + 9 >= sizeof(key)) + return; + memcpy(key, "wtoAmmo_", 8); + strcpy_s(key + 8, sizeof(key) - 8, unit_name); + spec = g_lmp_datablock_get_str(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, key, ""); + if (spec == NULL || *spec == '\0') + return; + p1 = strchr(spec, '|'); + if (p1 == NULL) + return; + wlen = (size_t)(p1 - spec); + if (wlen == 0 || wlen >= sizeof(weapon)) + return; + memcpy(weapon, spec, wlen); + weapon[wlen] = '\0'; + if (!parse_bullet_pair(p1 + 1, b0, sizeof(b0), &c0)) + return; + + memset(slots, 0, sizeof(slots)); + slots[0].weapon_name = weapon; + slots[0].bullet_mod = b0; + slots[0].count = c0; + slots[0].trigger_group = 0xffu; + count = 1; + p2 = strchr(p1 + 1, '|'); + if (p2 != NULL && parse_bullet_pair(p2 + 1, b1, sizeof(b1), &c1)) { + slots[1].weapon_name = weapon; + slots[1].bullet_mod = b1; + slots[1].count = c1; + slots[1].trigger_group = 0xffu; + count = 2; + } + fn_bullet_vec_assign(refl + LMP_REFL_OFF_BULLETS_VEC, &slots[0], &slots[count]); + log_line("local_mp: bot tank ammo unit='%s' weapon='%s' b0='%s':%u b1='%s':%u", + unit_name, weapon, b0, (unsigned)c0, count > 1 ? b1 : "", (unsigned)c1); +} + +static uint8_t __fastcall hook_unit_change_aircraft(void *unit, void *refl, uint8_t async) +{ + if (local_mp_is_host() && unit != NULL && refl != NULL && async == 0) + apply_bot_tank_ammo((const uint8_t *)unit, (uint8_t *)refl); + return orig_unit_change_aircraft(unit, refl, async); +} + static void __fastcall hook_sem_change_aircraft_send( void *self, const char *unit_name, const char *weapon_name, const void *modifications_blk, const char *skin_name, const void *custom_preset_blk, uint8_t flags_byte, @@ -182,7 +280,7 @@ static void __fastcall hook_sem_change_aircraft_send( refl[LMP_REFL_OFF_VERT_TARGETING] = vertical_targeting ? 1u : 0u; *(float *)(refl + LMP_REFL_OFF_BOMB_FUSE) = bomb_activation_time; - fn_unit_change_aircraft(hero, refl, 1); + orig_unit_change_aircraft(hero, refl, 1); fn_refl_dtor(refl); if (mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_PILOT_CONTROL && @@ -198,6 +296,7 @@ int install_local_mp_loadout_hooks(void) { const LocalMpHookSpec hooks[] = { { "sem_change_aircraft_send", g_lmp.sem_change_aircraft_send, (void *)&hook_sem_change_aircraft_send, (void **)&orig_sem_send }, + { "unit_change_aircraft", g_lmp.unit_change_aircraft, (void *)&hook_unit_change_aircraft, (void **)&orig_unit_change_aircraft }, }; /* The reflection is built in a fixed stack buffer; its bullet sets vector is its last member. */ @@ -208,7 +307,6 @@ int install_local_mp_loadout_hooks(void) } fn_refl_ctor = (ReflCtorFn)g_lmp.refl_ctor; fn_refl_dtor = (ReflDtorFn)g_lmp.refl_dtor; - fn_unit_change_aircraft = (UnitChangeAircraftFn)g_lmp.unit_change_aircraft; fn_datablock_set_from = (DataBlockSetFromFn)g_lmp.datablock_set_from; fn_datablock_dtor = (DataBlockDtorFn)g_lmp.datablock_dtor; fn_bullet_vec_assign = (BulletSetVecAssignFn)g_lmp.bullet_vec_assign; diff --git a/packages/patcher/src/ground-ai/ground-ai-config.ts b/packages/patcher/src/ground-ai/ground-ai-config.ts index b90ede5..8f159f5 100644 --- a/packages/patcher/src/ground-ai/ground-ai-config.ts +++ b/packages/patcher/src/ground-ai/ground-ai-config.ts @@ -13,8 +13,17 @@ export const GROUND_AI_MODES = ['stock', 'fire', 'drive', 'full'] as const; export type GroundAiMode = (typeof GROUND_AI_MODES)[number]; +export interface GroundAiLoadoutConfig { + readonly lowReadyRackThreshold: number; + readonly topUpAmmoCount: number; + readonly primaryAmmoPct: number; + readonly secondaryMinRounds: number; + readonly penetrationCompareDistM: number; +} + export interface GroundAiConfig { readonly mode: GroundAiMode; + readonly loadout: GroundAiLoadoutConfig; readonly cadence: { readonly maxBots: number; readonly macroTickSec: number; diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index 61b1430..dff2b03 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -71,6 +71,7 @@ export { GROUND_AI_MODES, isGroundAiActive, type GroundAiConfig, + type GroundAiLoadoutConfig, type GroundAiMode, } from './ground-ai/ground-ai-config.ts'; export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts';