53 Commits
Author SHA1 Message Date
N0VAN0M4LY 37cbcd806f docs(mods): align handbook chapters with .patch.blk and UI image format notes 2026-12-04 02:52:47 +08:00
N0VAN0M4LY 0af4183cb1 merge(ground-ai): merge feat/tank-ai phase 1 into main 2026-12-04 02:50:48 +08:00
N0VAN0M4LY 65363ce9de feat(mods): support Dagor-style BLK patches and include compilation
Add native-style *.blk.patch.blk and client/config-blk.patch.blk incremental patching alongside compile-time include/includeOnce and Dagor @-directive expansion (@override, @override-last, @replace, @delete, @delete-last, @delete-all, @clone, @clone-last, @inherit, @after, @before, indexed paths, unquoted @ syntax, triple-quoted strings, packed hex colors, and CDK #/develop/gameBase/ paths) while preserving full *.blk.patch.jsonc backwards compatibility.
2026-12-04 02:36:16 +08:00
N0VAN0M4LY 69d95df88e fix(hud): correct LocalMP damage feedback
Use the stock effective-hit flag to award normal hits and show ineffective hits without rewards. Route enemy parts feedback by the actual attacker or recipient and the active spectator state.

Verified both TypeScript projects, the native DLL build, and patch and Quirrel checks on 2.61.0.37, 2.61.0.58, and 2.61.0.60. Built fresh 2.61.0.58 and 2.61.0.60 copies. In-game verification is pending.
2026-12-04 02:35:47 +08:00
N0VAN0M4LY b3f9ff589c fix(ground-ai): short-circuit driveToPos instead of skipping setBehaviorTree
Skipping Unit::setBehaviorTree left unit->behTree null on LocalMP bot tanks, which prevented VehiclePhysActor from applying producedCT to appliedCT (100% dead_echo in sinai_Conq1). Hook driveToPos::update (.37 0x861370, .58 0x863a90) instead and return ER_SUCCESS (1) when the ground AI script is ready, keeping the BehTree initialized while completely suppressing stock tankBot driving. Verified MSVC build (0 warnings) and .37/.58 native module resolution (0 failures).
2026-12-04 01:54:14 +08:00
N0VAN0M4LY 85532cd930 feat(ground-ai)!: disable stock tankBot globally when AI script loads
Replace per-bot mid-battle movement handback to stock AI with a clean
binary startup gate:

- Locate Unit::setBehaviorTree (ground_ai_set_beh_tree: .37 0x4e89b0,
  .58 0x4e8f60) in patches/native/local_mp_ground_ai.jsonc and hook it
  in native/wto-net/src/local_mp_ground_ai.c.
- Announce readiness from [init] in wto_ai_runtime.das via
  wtoGroundAiScriptReady once the ground AI scripts finish compiling
  cleanly with custom movement enabled. When announced, hook_set_beh_tree
  suppresses attaching "tankBot" to LocalMP bot tanks and keeps their
  MoveSystem.inactive pinned to 1 for the life of the vehicle, ending
  all tug-of-war (external_inactive_reset) with stock AI.
- If scripts fail to compile, are missing, or mode is "stock" / "fire",
  ownMovement stays 0 and stock tankBot runs untouched.
- Remove per-bot handback, timeout release, and the now-obsolete
  navigation.returnToStockOnFailure config plumbing; on genuine script
  failure a bot halts in place and logs DRIVE_FAIL instead of silently
  switching to stock. Also initialize newly spawned bot ticks to run on
  frame 0 to eliminate spawn-frame invalid_drive_cmd noise.

Verified MSVC build of wto_ws.dll (0 warnings in project C sources), root
and launcher type checks, native module resolution on both 2.61.0.37 and
2.61.0.58 (0 failures), isolated 2.61.0.58 startup confirming 12/12
LocalMP modules installed, wto_ai_runtime.das loaded in 213 ms (0 compile
errors), and "ground AI script ready (ownMovement=1; stock tankBot
disabled)" in wto_ws.log.

BREAKING CHANGE: removes navigation.returnToStockOnFailure from
tuning/ground-ai.jsonc; stock tankBot is now controlled strictly by
whether the custom ground AI script loaded with custom movement enabled.
2026-12-04 01:06:04 +08:00
N0VAN0M4LY 651b023d2a fix(launcher): preserve skipped files during game updates
Reuse source scan exclusions during stale-file cleanup so updates preserve user content and tool files copied by earlier installers.

Verified with root and launcher typechecks and an update run against temporary folders.
2026-12-04 00:47:29 +08:00
N0VAN0M4LY 1d3e47b082 feat(launcher): allow changing the online update source
Let registered clients set or replace their online installation source
from the maintenance page. Validate the source and persist its path
before refreshing the available update status.

Verified launcher and workspace type checks, a launcher build, and an
incremental update of a registered client using local game snapshots.
2026-12-04 00:11:55 +08:00
N0VAN0M4LY ac35c25851 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_<unit> 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.
2026-12-03 19:25:04 +08:00
N0VAN0M4LY d5008baeff feat(ground-ai): add navmesh flank lanes, rally staging, recall, and air-aware SPAA
Complete the team commander layer with validated flank routes, coordinated
rally launches, dynamic cap recall, and air-threat-responsive SPAA:

- Add flank, rally, and recall parameters to the commander section of
  tuning/ground-ai.jsonc (flankMaxLengthRatio, flankMinSeparationM,
  rallyProgressFrac, rallyWaitSec, rallyMinFrac, rallyRadiusM,
  recallSafeHoldSec), validated in ground-ai-tuning.ts and compiled into
  WTO_AI_CMD_* constants.
- Add wto_ai_lanes_common.das:
  - Lazily build and cache per-(team, cap) center and left/right flank
    lanes using two-segment navmesh find_path_ex; reject flanks exceeding
    1.6x center path length or closer than 45 m to the center midpoint.
  - Stage offensive groups at the 40% rally point along their lane and
    launch once 2/3 of the group arrives or 25 s elapse, resetting on cap
    ownership flips.
  - Track enemy ground count and contested state on friendly caps,
    holding recall active until safe for 15 s; track enemy aircraft
    presence for team SPAA intel.
- Split mode planners and recall demand overrides into
  wto_ai_commander_plans_common.das; pull (enemies + 1) nearest support
  or reserve bots to defend contested friendly caps while always keeping
  at least one offensive assault bot.
- Update wto_ai_commander_anchors_common.das so SPAA follows behind the
  actual Assault group centroid and checks upward open-sky clearance when
  enemy aircraft are active.
- Wire WtoTaskOrder lane/relay/rally fields into wto_ai_route_common.das
  (replacing unvalidated wing relays and preserving corridor turning
  corners), wto_ai_tactics_common.das (rally staging hold), and
  wto_ai_runtime.das (1 s rally release check).

Verified root and launcher type checks, isolated 2.61.0.58 build (27
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 183 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 18:46:53 +08:00
N0VAN0M4LY 45ff082a36 feat(ground-ai): add sample-based lead estimation, exit watch, and bounded bias
Replace direct reads of true enemy velocity with an own-sight sample
estimator, add 2-5 s last-seen exit watching, and sample bounded aiming
bias once per shooting opportunity:

- Add the estimation section to tuning/ground-ai.jsonc (watchMinSec,
  watchMaxSec, velSampleMinSpanSec, velStableSpanSec, velJumpResetMps,
  baseAimSigmaM, leadErrorFrac, maxBiasM), validated in
  ground-ai-tuning.ts and compiled into WTO_AI_EST_* constants.
- Add wto_ai_estimate_common.das:
  - Maintain a 6-sample timestamped ring buffer from each bot's own
    visual sightings; compute smoothed observed velocity and convergence
    quality, dropping quality and re-seeding bias on sudden braking/turns
    or target switches.
  - On LOS loss from an active ground engagement, freeze watchPos at the
    last-seen exit point, clear observed velocity, and draw one random
    2-5 s watch duration; stationary overwatch/defend bots hold their
    post while watching, whereas pushing/retreating bots keep moving
    while keeping their turret on the exit.
  - Compute lead from observed velocity and loaded-shell flight time,
    sampling one bounded bias vector per shooting opportunity (target,
    shot count, state, 12 m position cell) that narrows as observation
    quality improves and still passes the single fire-permission gate.

Verified root and launcher type checks, isolated 2.61.0.58 build (25
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 184 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 18:23:12 +08:00
N0VAN0M4LY 80113bdd2e feat(ground-ai): add cover reload, stalemate reposition, and damage repair
Complete the single-vehicle tactical loop for reload survival, stalemate
breaking, and vehicle damage repair:

- Add cover, reload, hull-angle, stalemate, reposition, and repair-cover
  parameters to tuning/ground-ai.jsonc, validated in ground-ai-tuning.ts
  and compiled into WTO_AI_SM_* constants.
- Add wto_ai_cover_common.das: continuously record the last hard-concealed
  hull position before peeking, and evaluate 9 cover candidates around
  the tank (with enemy-clearance scoring when searching for a repair
  cover).
- Add wto_ai_tactics_actions_common.das and wire wto_ai_tactics_common.das:
  - Damage retreat & repair (plan 6.1): when gun is inoperable while
    mobile, retreat to an enemy-free cover and send
    EventRepairSystemRequestRepair(repair=true) once safe; when engine or
    tracks immobilize the chassis, halt in place, request repair, and keep
    gun self-defense active; stay halted while
    repair_system_remaining_repair_time > 0.
  - 3-way reload action: pull back into remembered/nearby cover (up to 6 s
    budget, uninterrupted by flashes/new orders) -> zigzag advance at
    +/-18 deg when pushing without cover -> angle hull front +/-15 deg
    when side-exposed >30 deg with pivot room.
  - Stalemate reposition: confirm outgoing effective damage via
    EventUnitDamage (uint(hpFixed) < uint(prevHpFixed)) and enemy death;
    trigger lateral reposition after 2 no-effect shots, 2 no-shot halts,
    or 12 s cumulative halt time, unlocking short-halt only after 20 m
    progress or reaching the new position.
- Split periodic telemetry out of wto_ai_runtime.das into
  wto_ai_diag_common.das to keep every module under 300 lines.

Verified root and launcher type checks, isolated 2.61.0.58 build (24
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 228 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 18:14:43 +08:00
N0VAN0M4LY 314bdfe68e feat(ground-ai): add hull state machine and two-beat turn driving
Replace the legacy tactics posture heuristics with an explicit per-bot
hull state machine driven by WtoTaskOrder and the 100/300/800 m distance
tiers, and fix chassis steering bugs:

- Add the stateMachine section to tuning/ground-ai.jsonc (preaimAngleDeg,
  shortHaltMaxSec, shortHaltCooldownSec, turnLaunchSpeedMps), validated in
  ground-ai-tuning.ts and compiled into WTO_AI_SM_* constants.
- Replace WTO_POSTURE_* with the unified WTO_STATE_* hull state enum in
  wto_ai_types_common.das and decouple wto_perceive_update into
  wto_ai_runtime.das so perception runs independently of hull tactics.
- Rewrite wto_ai_tactics_common.das as a priority-arbitrated state
  machine: safety/SPAA -> ridge withdrawal -> active SHORT_HALT budget
  (3 s limit with cooldown on timeout) -> crowd dispersion -> distance-tier
  combat (RUN_AND_GUN <=100 m and high-urgency 100-300 m slow-move-fire;
  PREAIM keeping the hull moving while gun reloads or turret error >8 deg;
  SHORT_HALT only when ready and permitted by order.maxStopRangeM / 800 m
  4 s window; RELOAD_ADVANCE when reloading away from cover) -> MARCH.
  Log every state transition with reason, distance and speed.
- Fix the inverted neutral-pivot condition in wto_ai_drive_common.das,
  add 2nd-gear straight-launch before full steering when turning with
  open front clearance, and use full throttle when accelerating to target
  speed so the automatic gearbox upshifts cleanly.

Verified root and launcher type checks, isolated 2.61.0.58 build (21
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 195 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 17:47:10 +08:00
N0VAN0M4LY 9229045042 feat(ground-ai): add exposure perception and single ballistic fire gate
Replace the old foliage-ignoring LOS check and 45 m pre-fire ray with
separate vision/hard-occlusion queries, exposure-integrated spotting, and
a single fire-permission gate for every ground weapon:

- Add perception and fire-gate distance/ballistics/budget parameters to
  tuning/ground-ai.jsonc, validated in ground-ai-tuning.ts and compiled
  into wto_ai_config_common.das.
- Extract wto_ai_combat_types_common.das and add wto_ai_sight_common.das:
  visual checks use smoke occluders, ETF_ALL with aimRay material,
  traceTransparencyRayRIGenNormalized foliage transparency, and vehicle/
  wreck checks; hard-occlusion checks test terrain/structures plus both
  ETF_RI and ETF_RI_PHYS without skipping soft foliage, plus swept
  sphere_cast and wreck/vehicle bounds along the full shot distance.
- Rewrite wto_ai_perceive_common.das with per-target exposure integration
  (fast/normal/far fill times and occlusion decay), 4-point visibility
  sampling with continuous >=2-point LOS tracking for the 800 m 4-second
  window, frozen last-seen coordinates with zeroed velocity on LOS loss,
  and impact-time hit direction (no live offender lookup).
- Record per-shell ballistics profiles (speed, Cx, mass, ballisticCaliber)
  in wto_ai_specs_common.das and sync the currently loaded shell from
  gun.chosenBulletType / bulletSets at runtime.
- Add wto_ai_fire_gate_common.das as the sole ground trigger exit: checks
  visual lock, weapon readiness, distance-tier measured chassis speed
  limits (100/300/800 m), 800 m 4-second window, aim settle, per-frame
  check budget, straight muzzle hard-ray, drag-integrated ballistic arc
  sweep, predicted friendly corridor, and every barrel in the primary
  trigger group. Confirm real shot departure from loaded ammo/readiness,
  remove the pure-launcher stock bypass and add_unit_for_target leak, and
  log exact deny/shot reasons.

Verified root and launcher type checks, isolated 2.61.0.58 build (21
ground AI modules packed), and clean in-engine daScript compilation/load
(wto_ai_runtime.das loaded in 186 ms, 0 compile errors). Live battle
acceptance deferred until the full pipeline is wired.
2026-12-03 17:34:59 +08:00
N0VAN0M4LY 7e5eb99696 feat(ground-ai): add task order, mode-aware commander v1, and world fixes
Replace the per-bot greedy cap scorer (wto_ai_macro_common.das) with a
whole-team commander and explicit task order contract, and fix the world,
spec, and navigation bugs found during the codebase audit:

- Classify ground battle modes (bttl, conq, dom) in multiplayer-missions
  v5 from mislist.blk categories (with suffix fallback for event maps) and
  emit wtoGroundMode in customRules/customBots.
- Add the commander section to tuning/ground-ai.jsonc with range and sum
  validation, compiled into WTO_AI_CMD_* constants.
- Split zone/mode/spawn refresh into wto_ai_world_zones_common.das and fix
  four world snapshot bugs: stop double-recording deaths in wreck scans
  and deduplicate with a ring cursor, refresh units before spawn fallback
  while retrying real respawn points, fall back battleCenter to spawns
  when capCount is 0, and relax cap radius clamping to 10..180 m.
- Fix limited-traverse yaw overwrite in wto_ai_specs_common.das and
  compute pivot turn angle against wishDir in wto_ai_nav_common.das.
- Introduce WtoTaskOrder (wto_ai_order_common.das) and whole-team
  commander v1 (wto_ai_commander_common.das +
  wto_ai_commander_anchors_common.das): mode-aware role quotas (Bttl,
  Conq, Dom), deterministic distance + vehicle-suitability matching,
  20-second role hysteresis, separate total-assigned vs cap-insider
  counters, frontline-relative SPAA anchors, EventZoneCaptured immediate
  rebalance, and per-team WTO_AI|CMD telemetry.

Verified root and launcher type checks, multiplayer-missions v5 dataset
extraction (1140 missions with Bttl/Conq/Dom classification), isolated
2.61.0.58 build (18 ground AI modules packed), and clean in-engine
daScript compilation/load (wto_ai_runtime.das loaded in 155 ms, 0 compile
errors). Live battle tuning and acceptance deferred until the full
pipeline is wired.
2026-12-03 17:20:17 +08:00
N0VAN0M4LY 73bae4785f fix(ground-ai): harden drive ownership, teardown and failure switch
Address two issues found in the first isolated 2.61.0.58 live runs and add
a test switch to disable silent fallback to stock movement:

- Add navigation.returnToStockOnFailure in tuning/ground-ai.jsonc (default
  true), compiled into WTO_AI_NAV_RETURN_TO_STOCK and written to wto_ws.cfg
  as ground_ai_return_to_stock=0 when disabled. When false, failed or
  timed-out bots keep stock movement paused, brake in place and log the
  failure once instead of silently handing control back to stock tankBot.
- Allow holdMs=0 release actions even after local_mp_is_host() flips false
  during mission unload, add eid=0 bulk release on wto_reset_runtime(), and
  match slots by eid rather than live owner lookup so match exit cleans up
  the native control table immediately.
- Stop releasing drive ownership when a vehicle is immobilized by damage or
  repair; brake in place and pause the echo watchdog instead, avoiding the
  1-second release/re-acquire flapping observed during combat. Log exact
  release reasons and back off for 1 second if MoveSystem.inactive is
  cleared externally.

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, and a temporary
2.61.0.58 game copy build confirming ground_ai_return_to_stock=0 in
wto_ws.cfg and 15 packed daScript modules. Live battle re-check pending.
2026-12-03 16:47:44 +08:00
N0VAN0M4LY 89242e91f0 feat(ground-ai): default to the full custom ground AI
Stock tankBot only drives each bot to a capture point, so the custom AI is the intended player default. Stock mode stays available for troubleshooting, and per-vehicle control still returns to stock movement on failure. Verified the shipped tuning loads with mode full.
2026-12-03 16:09:36 +08:00
N0VAN0M4LY 5e521295a3 feat(ground-ai)!: replace layer switches with complete modes
Ground AI layers could be enabled in any combination, including ones the
scripts cannot run (fire control without perception disabled stock aiming
and never fired). The configuration now selects one of four complete modes:
stock, fire (stock movement, custom fire permission), drive (custom orders
and driving, stock firing) and full. The build derives the compiled layer
constants from the mode, and an unknown mode is rejected at load time.

The offline tank class weights for the AI bot pool move from code into
tuning/ground-ai.jsonc (lineupWeights). They apply only when a custom mode
is active; stock mode keeps the stock weight of 1 for every vehicle.

Verified root and launcher type checks, mode-to-constant compilation for
all four modes, rejection of an unknown mode, bot pool weights in stock and
custom modes, and temporary 2.61.0.58 game copy builds in full mode (15
script modules packed) and stock mode (no game pack written).

BREAKING CHANGE: ground-ai.jsonc drops "enabled" and "layers". Override
files set "mode" to "stock", "fire", "drive" or "full" instead.
2026-12-03 16:05:03 +08:00
N0VAN0M4LY 885e3bbb5d feat(ground-ai): return bot movement control on failure
Grant custom physics control per LocalMP bot and let the native layer release it when the script stops renewing control. Verified both TypeScript checks, the MSVC build, native resolution and check-patches on .37 and .58, and isolated .58 script loading.
2026-12-03 14:24:32 +08:00
N0VAN0M4LY bb680c6abd fix(patcher): retain stock tank AI movement
Keep the original behavior tree installed and validate the optional script entry and dependencies after mod overlays. Verified stock tree bytes and the enable/disable rebuild on 2.61.0.58.
2026-12-03 14:24:32 +08:00
N0VAN0M4LY 975a28441a feat(ground-ai): implement modular zero-heap tank AI daScript layers
Add 14 modular daScript files under game-ai/ground covering per-vehicle
DataBlock specs, foliage-filtered terrain and cliff crest lookahead,
flat world snapshots, anti-clustering telemetry and active dispersion,
cap-insider-bounded macro scheduling, sticky 6-channel perception,
ridge snipe/reverse withdraw tactics, wide-projected NavMesh routing,
bidirectional forward/reverse DWA local planning, closed-loop
VehiclePhys chassis control, and settled ballistic fire control.
2026-12-03 12:12:17 +08:00
N0VAN0M4LY 4ac3484f56 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.
2026-12-03 12:07:30 +08:00
N0VAN0M4LY a2fdcc1f15 docs(mods): fix schema errors and expand bilingual mod handbook to full parity
Fix store.jsonc vehiclePacks nesting and gjn field name, matchingApiFunc callback argument order, and DaGui CSS @import/lowercase rules; add stock archive inspection steps, BR-to-mrank table, cloned vehicle walkthrough, tuning field reference, and official-map-selector full-stack trace while bringing en/01..07.md to full 1:1 parity with zh-CN/.
2026-12-03 11:25:54 +08:00
N0VAN0M4LY e79866b96e docs(dev-docs): rewrite bilingual developer handbook with real code and byte walkthroughs
Expand dev-docs with a plain-language glossary, accurate single-port server flow, real apps/server directory map and cln_set_researchable trace, un-elided 57-byte EXE patch anatomy, 6-file Native C wiring guide, real Good vs. Bad code comparisons, AI constraint prompt, and traffic-log debugging steps at 1:1 zh-CN/en parity.
2026-12-03 11:25:53 +08:00
N0VAN0M4LY e2ac4fa744 fix(launcher): use original-fs for copy and guard nested launcher folders
Electron patches node:fs to treat any .asar file on disk as a virtual
archive directory. When a player's War Thunder source directory contains
an .asar file (for example from a leftover portable launcher folder
previously unpacked inside the game folder), createReadStream fails with
ENOENT and aborts full-copy installation.

Changes:
- Add rawFs() helper using Electron's original-fs (with node:fs fallback)
  and use it across copy-game.ts and change-copy-files.ts for directory
  scans, streaming copies, timestamp preservation, rollback and cleanup.
- Preserve the first non-cancellation worker error in copyPlannedFiles so
  sibling AbortError rejections do not mask the real filesystem or
  hardlink error.
- Skip nested subfolders containing WTOffline Launcher.exe during
  planCopy, and reject copy installation upfront with
  launcher_inside_source when the packaged launcher itself runs from
  inside the selected source game directory (with en and zh-CN messages).

Verification:
- Root and launcher typecheck passed.
- Launcher electron-vite build passed.
- en.json and zh-CN.json key parity check passed (720 keys).
- Verified in Electron that patched node:fs reproduces ENOENT on
  default_app.asar while original-fs copies and cleans it up cleanly.
- Packaged installer end-to-end verification pending.
2026-12-03 10:40:49 +08:00
N0VAN0M4LY 01bafb6db7 fix(launcher): detach portable updater via Start-Process on Windows
Spawning powershell.exe directly with Node detached: true sets DETACHED_PROCESS (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before running -File. Spawning without detached lets it run, but Electron tears down attached children on app.quit(). Launch the apply script via a short hidden PowerShell Start-Process helper before quitting, properly quoting paths with spaces or non-ASCII characters, and clean up staged files if launching fails.
2026-12-03 07:48:44 +08:00
N0VAN0M4LY 18637cf1ff fix(launcher): skip user skins, sights, CDK, and launcher log folders when copying game
Exclude UserSkins and UserSights from stock client scans as player data folders (matching UserMissions and keeping them protected from symlink redirection during launch), and skip WarThunderCDK plus official launcher/updater log and obsolete folders when copying, sizing, or incrementally updating from a stock installation.

Verified: root typecheck, launcher typecheck, and launcher electron-vite build pass; runtime copy test pending.
2026-12-03 07:24:54 +08:00
N0VAN0M4LY 10427912e2 feat(launcher): display rendered markdown release notes in a modal
Keep the About page launcher update notice compact by showing only the available version, package size, and action buttons, with a compact button to open a scrollable release notes dialog when notes are present. Render GFM Markdown safely into React elements via marked.lexer without injecting raw HTML, and raise the release notes cap from 1,600 chars to 64 KiB so full bilingual notes are preserved.
2026-12-03 07:18:31 +08:00
N0VAN0M4LY 214f9d7f4b fix(launcher): use original-fs in portable updater and drop default_app.asar
Electron patches node:fs to treat .asar archives as virtual directories, so portable update verification failed on staged resources/default_app.asar and recursive cleanup could leave staging folders behind. Switch staging lstat and cleanup rm in portable-update.ts to original-fs (falling back to node:fs outside Electron), strip unused resources/default_app.asar during packaging so already-released 0.1.2/0.1.3 portable builds can update cleanly to future releases, and include portable-update.log in exported diagnostics.
2026-12-03 07:18:14 +08:00
N0VAN0M4LY f6b00bc787 fix(modifications): emit RESEARCHED status and align buy-all pricing
Add ModuleStatus.RESEARCHED (0x40, ES_ITEM_STATUS_RESEARCHED) for modifications that have reached their RP requirement while a reqModification prerequisite is not yet owned, and keep unresearched modifications locked until their prerequisites are researched.

Update buyAllModifications / buyAllEntry to accept both CAN_BUY and RESEARCHED so the server matches client getAllModsCost (canBuyMod || isModStatusResearched) instead of rejecting cln_buy_all_modification with PRICE_CHANGED (shown as Internal character server error).

Verified: root and launcher typecheck, and runtime check against 2.61.0.58 wpcost.blk chained modifications. Pending in-game acceptance.
2026-12-03 06:38:15 +08:00
N0VAN0M4LY 638bc75724 fix(native): filter air enemy damage MPI feed and keep repeat air hits
Hook AcesApp's local MPI proxy dispatch to drop enemy-part-damage messages (0xf104 / 0xf118, captured dynamically) whose recipient_pid does not belong to the local player or watched hero, preventing AI-vs-AI aircraft damage from leaking into the local kill feed.

Remove the mistaken !is_kill gate in hook_dispatch_hit_crit: the 5th argument from Unit::flushOffenderHitAward is a repeat-flush flag rather than a kill flag, which dropped follow-up aircraft hits because fixed-wing units flush exclusively through the timer path. Add a same-team guard to match the severe-damage hook.

Verified: MSVC build.ps1 (0 warnings in project code), check-patches (14/14) and 12/12 native module resolution on 2.61.0.37 and 2.61.0.58. Pending in-game acceptance.
2026-12-03 06:37:58 +08:00
N0VAN0M4LY 02fe867cf1 refactor(launcher): open mod documentation on wto-project.net
Replace the local offline HTML mod docs viewer in the launcher Mods page with a direct link to https://wto-project.net/mod-docs, remove the unused mods:openDocs IPC path and resource entry, and drop build-mod-docs-html.ts from Windows packaging while keeping bundled mod templates intact. Root typecheck, launcher typecheck, and electron-vite build passed.
2026-12-03 06:26:52 +08:00
N0VAN0M4LY 742094ea1e chore(launcher): bump version to 0.1.3 and add release notes 2026-12-03 06:13:23 +08:00
N0VAN0M4LY c8ba395e4f docs(dev-docs): add common implementation pitfalls and PR self-check 2026-12-03 06:13:23 +08:00
N0VAN0M4LYandduduyagame 4e99d2c484 fix(training): persist tutorial completions and grant first-time rewards
On returning from a stock training mission, the client reports the outcome in
cln_update under missionAwards while sending an empty pveProgress block. Because
the local server did not record this completion, the hangar repeated tutorial
prompts after restart and never credited first-completion rewards.

Add a cached training-missions dataset (config/mislist.blk,
config/pve_awards.blk, config/unlocks.blk), pure completion rules in
TrainingCatalogue, and missionAwards parsing in clientUpdateAction. Completed
tutorials now persist pveProgress/missions and grant per-mission decals, the
shared first-basic-tutorial Golden Eagles unlock, and per-difficulty first-win
Silver Lions once per account during cln_update before replying.

Credit to duduyagame for identifying the cln_update missionAwards reporting flow
and stock reward definitions (PR #6).

Checks: root `npm run typecheck` passed; verified training-missions dataset
extraction/caching and TrainingCatalogue idempotency against read-only stock
2.61.0.37 files in a temporary data folder. In-game acceptance pending on an
isolated client copy.

Co-authored-by: duduyagame <[email protected]>
2026-12-03 05:23:18 +08:00
N0VAN0M4LYandduduyagame 42b8275151 fix(battle): write root numBotRespawns and numTankBotRespawns for all modes
MissionSettings::load (2.61.0.37 0x126b1f4..0x126b2e6) initializes AI respawn
limits from global config/bots.blk defaults (numBotRespawnsInMultiSlot=1,
numTankBotRespawnsInMultiSlot=3) and then overrides them from the mission root
fields numBotRespawns and numTankBotRespawns rather than customRules/customBots.

Previously only single-slot modes wrote numBotRespawns at the mission root, so
Air Arcade and other multi-slot modes stayed at 1 aircraft respawn and all modes
ignored tuning.battle.tankBotRespawns. Write both root fields unconditionally
using the per-mode values already resolved by BattleMatchmaker.

Credit to duduyagame for identifying the missing root numBotRespawns in Air
Arcade (PR #7).

Checks: root `npm run typecheck` passed. In-game acceptance pending on an
isolated client copy.

Co-authored-by: duduyagame <[email protected]>
2026-12-03 05:22:40 +08:00
N0VAN0M4LY 594ff5ab54 feat(launcher): add project homepage link to About page
Add a Project homepage card and button pointing to https://wto-project.net on the launcher About page with matching zh-CN and en locale entries. Root typecheck, launcher typecheck, electron-vite build, and locale key parity checks passed.
2026-12-03 04:34:22 +08:00
N0VAN0M4LY 41088d5377 docs(mods): use neutral, self-contained phrasing in mod developer documentation 2026-12-03 03:45:13 +08:00
N0VAN0M4LY d94c8fe687 feat(mods): merge additive mod system, official map selector, and mod-dev-docs
# Conflicts:
#	apps/launcher/src/main/workers/build-worker.ts
#	apps/launcher/src/renderer/src/i18n/locales/en.json
#	apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
2026-12-03 03:43:56 +08:00
N0VAN0M4LY de967dd993 feat(repo): add R2 release staging, download page, and S3 publish script
Add scripts/publish-r2-releases.ts with a zero-dependency SigV4 R2 client and bilingual static index.html generator. Staged launcher releases and adaptation packs are verified against the committed Ed25519 public key and SHA-256 digests before publishing, assets are uploaded ahead of the releases feed with SHA-256 skip checks, and .env*.local is gitignored for local R2 credentials. Verified with root typecheck, local staging, and live R2 upload.
2026-12-03 03:03:14 +08:00
N0VAN0M4LY dc5e637e20 fix(mods): track additive pack overlay folders inside mod templates 2026-12-03 03:02:19 +08:00
N0VAN0M4LY 240ee81712 feat(launcher): use dl.wto-project.net as primary release source with GitHub fallback
Replace the single GitHub repository field in release-channels.jsonc with primary_source (https://dl.wto-project.net) and ordered fallback_sources (GitHub), and update withReleaseSources to walk the deduplicated primary, player mirror, and fallback list while keeping preferred-source downloads and Ed25519 signature verification intact. Verified with root and launcher typecheck and launcher production build.
2026-12-03 03:02:14 +08:00
N0VAN0M4LY 6e65cec4c0 feat(mods): add official map selector mod template and move templates into mod-dev-docs 2026-12-03 03:01:18 +08:00
N0VAN0M4LY aa952e7cca docs(mods): add standalone mod-dev-docs handbook and launcher quick-open button 2026-12-03 02:51:54 +08:00
N0VAN0M4LY 5983e3f3e2 feat(mods): add battle.onFilterMissions hook and per-template bundled seeding 2026-12-03 02:40:38 +08:00
N0VAN0M4LY 8636d0b71d fix(mods): serialize initial example seeding and refresh on window focus 2026-12-03 01:55:20 +08:00
N0VAN0M4LY 97707f533d feat(launcher): bundle example mod templates and seed fresh mods folder once 2026-12-03 01:51:43 +08:00
N0VAN0M4LY ada635ecc7 refactor(launcher): move experimental mod notice to hover tooltip chip 2026-12-03 01:48:47 +08:00
N0VAN0M4LY 3aac60c8a3 docs(mods): add bilingual mod authoring guide and runnable example mod templates 2026-12-03 00:41:47 +08:00
N0VAN0M4LY dbc21182a2 feat(launcher): add Mods page, per-client presets, custom repo folder, and launch integration 2026-12-03 00:34:07 +08:00
N0VAN0M4LY aa7a6e7d02 feat(server): add experimental JS/TS mod runtime, hooks, tuning list ops, and isolated mod storage 2026-12-03 00:00:36 +08:00
N0VAN0M4LY fd9d25d346 feat(patcher): support additive mod pack overlays, addon mounts, and protected exe patches 2026-12-02 23:48:34 +08:00
N0VAN0M4LY 8fbaeb4228 feat(mods): add core mod manifest, resolver, BLK/CSV patchers, and server API types 2026-12-02 23:42:26 +08:00
197 changed files with 25126 additions and 2027 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
## 简体中文
`v0.1.3` 是 WTOffline的一次大型功能更新,正式引入**第一版模组系统(开放社区模组制作)**、初步接通**原子雷霆**模式,并包含多项对局机制、存档容量、贴花导入与更新链路修复。
### 该下载哪一个文件?
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.3-win-x64.exe`** ,下载后安装即可。
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** ,解压到任意目录后运行其中的启动器即可。
### 重点新功能
- **第一版模组系统与开放模组制作(实验性)。**
- 启动器新增「模组」管理页:支持为每个客户端独立开关模组、调整加载顺序、保存/切换模组方案以及自定义模组目录,并可直接一键打开完整模组开发文档。
- 支持客户端数据包增量覆写(BLK / CSV / 附加包挂载,且核心隔离补丁受保护不可被误覆盖)、服务端 JS/TS 脚本钩子与独立模组数据存储,以及数值列表增量修改。
- 内置并首次自动生成 3 套官方示例模组模板(含可直接使用的「官方地图选择器」、服务端脚本示例与载具参数微调示例),配套完整中英文 `mod-dev-docs` 开发手册,欢迎玩家与创作者制作并分享自己的模组。
- **接通「原子雷霆」模式。**
- 完整接入空战历史子模式「原子雷霆」的专用 HUD、阶段推进门槛、不限出击次数与机场独立冷却机制,并按 10 国与房间权重自动分配战术核弹载机(5 kt / 30 kt)。
- 在启动器「数值 → 对局」新增「原子雷霆战略核轰炸机」开关(默认开启),可在阶段 3 追加战略核轰炸机(`B-52H` / `Tu-95M`)。
### 修复与改进
- **对局与战斗体验**:
- 恢复陆战街机空中支援事件(呼叫战斗机 / 攻击机 / 轰炸机);
- 修复本地主机下玩家乘员技能与专家 / 王牌资格在战局内未生效的问题;
- 恢复空战街机模式下的空中重新装填弹药;
- 修复部分载具出生时改装件效果反转,以及单弹链航空武器被未选中的隐身弹链覆盖导致无曳光弹的问题;
- 恢复对战模式飞机有限燃油消耗与油量倒计时,并修复局内小队黄色标记;
- 支持在机库切换并保存载具的可选分房权重(如部分直升机 / 挂载升档),开局按所选权重参与匹配;
- 修复空战街机等多槽模式下 AI 飞机重生次数受限,以及坦克 AI 重生次数配置未对全部模式生效的问题(感谢 `duduyagame`);
- 修复新手教程完成进度未保存的问题:通关后重启不再反复提示教程,并按原版规则发放首次通关的贴花、基础教程金鹰及各难度银狮奖励(感谢 `duduyagame`)。
- **启动器、存档与更新链路**:
- 修复新版在线客户端贴花与可下载涂装缓存导入失败的问题(兼容现行 `regional.vromfs.bin` + `.ddsx` 及旧版缓存格式);
- 修复全车库改装件总数超过 65,535 个时的存档溢出问题;
- 将启动器「存档 → 载具和研发」中的「全部研发」与「获得常规载具」合并为一步到位的「全部研发并购买」;
- 优化默认更新线路并保留 GitHub 自动回退,全流程继续保持 Ed25519 签名校验;
- 「关于」页改版为双栏布局,新增「项目主页」与「Discord」快捷入口,修复切换页面时维护进度丢失的问题。
### 社区交流与模组分享
欢迎加入 WTOffline 官方 Discord 服务器,一起交流玩法、反馈 Bug、分享你的调参或自制模组,并关注最新客户端适配进度:
- **Discord 社区**:https://discord.gg/P566xWNpEs
- **项目主页**:https://wto-project.net
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动尝试适配后续小版本更新。
---
## English
`v0.1.3` is a major feature release of WTOffline introducing the **first version of the experimental Mod System** (opening up community mod authoring), Add support for **Nuclear Escalation**, and a broad set of battle, save, decal import, and launcher fixes.
### Which file should I download?
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.3-win-x64.exe`** — the standard Windows installer with built-in automatic update checks.
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
### Highlights
- **Experimental Mod System v1 & Mod Authoring.**
- New **Mods** page in the launcher with per-client enablement, load-order management, presets, custom mod repository folder, and a quick-open button for the mod developer handbook.
- Supports additive client archive overlays (BLK / CSV / addon mounts while protecting essential isolation patches), server-side JS/TS lifecycle hooks with isolated mod storage, and tuning list operations.
- Ships with 3 bundled example mod templates (including a ready-to-use **Official Map Selector**, a server script example, and a vehicle tweak example) plus full bilingual documentation in `mod-dev-docs/`.
- **Nuclear Escalation mode.**
- Full support for Air Realistic sub-mode **Nuclear Escalation**, including custom HUD, stage thresholds, unlimited respawns, per-airfield cooldowns, and nation-matched tactical nuclear carriers (5 kt / 30 kt) scaled to room BR.
- Added a **Nuclear Escalation strategic bombers** toggle under **Tuning → Battle** (enabled by default) to unlock stage-3 strategic nuclear bombers (`B-52H` / `Tu-95M`).
### Fixes and improvements
- **Battles & gameplay**:
- Restored Ground Arcade air support events (fighters, attackers, bombers).
- Fixed player crew skills and Expert / Ace qualifications not applying on the local host.
- Restored in-flight ammunition reload in Air Arcade.
- Fixed inverted modification effects on spawn and single-belt aircraft tracers being overwritten by unselected stealth belts.
- Restored limited fuel consumption / HUD fuel timer in versus modes and yellow squad target markers.
- Persisted selectable battle ratings for units with BR-changing modifications and applied them during matchmaking.
- Fixed AI aircraft respawn limits in Air Arcade and other multi-slot modes, and applied configured ground AI respawn counts across all modes (thanks to `duduyagame`).
- Persisted stock training/tutorial completion progress so finished tutorials no longer re-prompt after restart, and granted one-time first-completion decals, basic tutorial Golden Eagles, and per-difficulty Silver Lions rewards (thanks to `duduyagame`).
- **Launcher, saves & updates**:
- Fixed online decal and downloadable skin cache import on modern 2.61 clients (supports both `regional.vromfs.bin` + `.ddsx` and legacy cache layouts).
- Fixed save overflow when total owned modifications exceed 65,535 by splitting across native sibling blocks.
- Merged "Research all" and "Grant regular vehicles" into a single **Research and buy all** action in the launcher.
- Improved default release update routing with automatic GitHub fallback and continued Ed25519 signature verification.
- Updated the About page to a two-column layout with **Project homepage** and **Discord** buttons, and preserved copy maintenance progress across tab switches.
### Community & Mod Sharing
Join the official WTOffline Discord server to chat, report issues, share tuning presets or custom mods, and follow client adaptation updates:
- **Discord**: https://discord.gg/P566xWNpEs
- **Homepage**: https://wto-project.net
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates.
+5 -1
View File
@@ -1,5 +1,8 @@
# Never commit game files (copyright, size). The build reads them from a game folder.
*.vromfs.bin
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
*.vromfs.bin.orig
aces.exe
aces*.exe
@@ -25,10 +28,11 @@ __pycache__/
*.pyc
.venv/
# Saves, logs, local runtime data
# Saves, logs, local runtime data, local secrets
/data/
/saves/
*.log
.env*.local
# Editors / OS
.vscode/
+3 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@wto/launcher",
"productName": "WTOffline Launcher",
"version": "0.1.2",
"version": "0.1.3",
"private": true,
"description": "Installer and launcher of the War Thunder offline project.",
"type": "module",
@@ -14,10 +14,12 @@
},
"dependencies": {
"@fontsource/roboto-condensed": "^5.3.0",
"@wto/mods": "*",
"@wto/patcher": "*",
"@wto/server": "*",
"fflate": "^0.8.2",
"i18next": "^26.3.6",
"marked": "^18.4.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-i18next": "^17.0.10",
+55
View File
@@ -17,6 +17,19 @@ import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesSta
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
import {
applyModPreset,
autoSortMods,
deleteModPreset,
exportModPreset,
getModsState,
importModPreset,
openModsFolder,
saveModPreset,
setModEnabled,
setModsFolder,
setModsOrder,
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { broadcast, handle } from './register.ts';
@@ -175,6 +188,48 @@ export function registerIpcHandlers(): void {
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
const requireModsWritable = (): void => {
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
};
handle('mods:getState', ({ copyId }) => getModsState(copyId));
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
requireModsWritable();
return setModEnabled(copyId, modId, enabled);
});
handle('mods:setOrder', ({ copyId, order }) => {
requireModsWritable();
return setModsOrder(copyId, order);
});
handle('mods:autoSort', ({ copyId }) => {
requireModsWritable();
return autoSortMods(copyId);
});
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
requireModsWritable();
return saveModPreset(copyId, name, overwriteId);
});
handle('mods:applyPreset', ({ copyId, presetId }) => {
requireModsWritable();
return applyModPreset(copyId, presetId);
});
handle('mods:deletePreset', ({ copyId, presetId }) => {
requireModsWritable();
return deleteModPreset(copyId, presetId);
});
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
handle('mods:importPreset', ({ copyId }, sender) => {
requireModsWritable();
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
});
handle('mods:openFolder', () => openModsFolder());
handle('mods:setFolder', async ({ copyId, path }) => {
requireModsWritable();
const state = await setModsFolder(copyId, path);
broadcast('event:settings-changed', await getSettings());
return state;
});
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => {
@@ -22,7 +22,9 @@ import {
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
} from '../patch-pack/release-assets.ts';
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
import {
cleanupPreparedPortableInstall, isPortableLauncher, launchPortableUpdater, preparePortableInstall,
} from './portable-update.ts';
type UpdateMode = 'installer' | 'portable';
@@ -215,7 +217,12 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
try {
if (offer.mode === 'portable') {
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
launchPortableUpdater(prepared);
try {
await launchPortableUpdater(prepared);
} catch (launchError) {
await cleanupPreparedPortableInstall(prepared);
throw launchError;
}
app.quit();
return;
}
@@ -7,21 +7,35 @@
* only obsolete files listed in the previous portable inventory (never touching unrelated user
* files in the same folder), and restarts the updated executable.
*/
import { execFile, spawn } from 'node:child_process';
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import * as nodeFs from 'node:fs';
import { existsSync } from 'node:fs';
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
import { z } from 'zod';
const execute = promisify(execFile);
const require = createRequire(import.meta.url);
export const PORTABLE_MARKER_FILE = 'portable-mode';
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
export const PORTABLE_UPDATE_LOG_FILENAME = 'portable-update.log';
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
// Electron patches node:fs to expose .asar archives as virtual directories, which makes
// lstat().isFile() return false and recursive rm() fail on staged .asar files.
function rawFsPromises(): typeof nodeFs.promises {
try {
return (require('original-fs') as typeof nodeFs).promises;
} catch {
return nodeFs.promises;
}
}
const PortableInventorySchema = z.object({
format: z.literal(1),
version: z.string().min(1),
@@ -216,6 +230,7 @@ export async function preparePortableInstall(
): Promise<PreparedPortableUpdate> {
await assertWritableFolder(installDir);
await mkdir(updatesRoot, { recursive: true });
const rawFs = rawFsPromises();
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
await mkdir(stagingDir, { recursive: true });
try {
@@ -238,7 +253,7 @@ export async function preparePortableInstall(
}
for (const rel of newFiles) {
const stagedPath = resolveInside(stagingDir, rel);
const stats = await lstat(stagedPath);
const stats = await rawFs.lstat(stagedPath);
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
}
@@ -254,7 +269,7 @@ export async function preparePortableInstall(
installDir: resolve(installDir),
stagingDir,
archivePath,
logPath: join(updatesRoot, 'portable-update.log'),
logPath: join(updatesRoot, PORTABLE_UPDATE_LOG_FILENAME),
executable: LAUNCHER_EXECUTABLE,
newFiles,
staleFiles,
@@ -263,21 +278,46 @@ export async function preparePortableInstall(
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
return { scriptPath, planPath, stagingDir };
} catch (error) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
await rawFs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
throw error;
}
}
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
const child = spawn('powershell.exe', [
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
'-File', prepared.scriptPath, prepared.planPath,
], {
cwd: dirname(prepared.scriptPath),
detached: true,
stdio: 'ignore',
windowsHide: true,
shell: false,
});
child.unref();
export async function cleanupPreparedPortableInstall(prepared: PreparedPortableUpdate): Promise<void> {
const rawFs = rawFsPromises();
await rawFs.rm(prepared.stagingDir, { recursive: true, force: true }).catch(() => undefined);
await rm(prepared.planPath, { force: true }).catch(() => undefined);
}
/**
* Launch the portable apply script in a hidden PowerShell process that survives Electron exit.
*
* On Windows, spawning powershell.exe directly with Node's `detached: true` sets DETACHED_PROCESS
* (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before
* running `-File`. Spawning without `detached` lets PowerShell run, but Electron tears down
* attached children on `app.quit()`. Using a short hidden PowerShell helper with `Start-Process`
* gives the updater its own hidden console and cleanly detaches it before the launcher quits.
*/
export async function launchPortableUpdater(prepared: PreparedPortableUpdate): Promise<void> {
const workDir = dirname(prepared.scriptPath);
const launcherPath = join(workDir, `launch-portable-${randomUUID()}.ps1`);
const script = [
'param([string]$ScriptPath, [string]$PlanPath, [string]$WorkDir)',
"$ErrorActionPreference = 'Stop'",
'$argsList = @(',
" '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',",
' \'-File\', "`"$ScriptPath`"", "`"$PlanPath`""',
')',
"Start-Process -FilePath 'powershell.exe' -WorkingDirectory $WorkDir -WindowStyle Hidden -ArgumentList $argsList",
].join('\r\n');
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
await writeFile(launcherPath, `\uFEFF${script}\r\n`, 'utf8');
try {
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', launcherPath, prepared.scriptPath, prepared.planPath, workDir,
], { cwd: workDir, windowsHide: true, timeout: 30_000 });
} finally {
await rm(launcherPath, { force: true }).catch(() => undefined);
}
}
@@ -1,10 +1,11 @@
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
import { rawFs } from '../../util/raw-fs.ts';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
export async function fileInfo(path: string) {
const fsPromises = rawFs().promises;
try {
return await lstat(path);
return await fsPromises.lstat(path);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return null;
@@ -28,7 +29,8 @@ export async function changeCopyFiles<T>(
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
recordChange: () => Promise<T>,
): Promise<T> {
const work = await mkdtemp(join(dirname(root), '.wto-copy-'));
const fsPromises = rawFs().promises;
const work = await fsPromises.mkdtemp(join(dirname(root), '.wto-copy-'));
const incoming = join(work, 'new');
const backups = join(work, 'old');
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
@@ -44,14 +46,14 @@ export async function changeCopyFiles<T>(
const entry = { target, saved: null as string | null, replaced: false };
if (old) {
const saved = join(backups, path);
await mkdir(dirname(saved), { recursive: true });
await rename(target, saved);
await fsPromises.mkdir(dirname(saved), { recursive: true });
await fsPromises.rename(target, saved);
entry.saved = saved;
}
changes.push(entry);
if (add) {
await mkdir(dirname(target), { recursive: true });
await rename(join(incoming, path), target);
await fsPromises.mkdir(dirname(target), { recursive: true });
await fsPromises.rename(join(incoming, path), target);
entry.replaced = true;
}
}
@@ -60,8 +62,8 @@ export async function changeCopyFiles<T>(
} catch (error) {
for (const { target, saved, replaced } of changes.reverse()) {
try {
if (replaced) await rm(target, { force: true });
if (saved) await rename(saved, target);
if (replaced) await fsPromises.rm(target, { force: true });
if (saved) await fsPromises.rename(saved, target);
} catch (rollbackError) {
keepBackups = true;
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
@@ -70,7 +72,7 @@ export async function changeCopyFiles<T>(
throw error;
} finally {
if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
await fsPromises.rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
}
}
}
@@ -7,7 +7,7 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
import {
fileHash,
linkVerifiedResource,
@@ -21,20 +21,10 @@ import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } fro
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import { readSource } from './copy-source.ts';
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
const game = await inspectGameFolder(record.sourcePath);
return game.missingFiles.length > 0 ? null : game;
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
}
@@ -67,7 +57,10 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key));
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
// Older installs may have tracked files in folders that source scans now skip.
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter(
(name) => !found.has(key(name)) && !isInSkippedSourceFolder(name),
);
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
);
@@ -13,7 +13,8 @@ import { gameProcessRunning, launchInProgress } from '../launch/launch-controlle
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import { readSource, setCopySource } from './copy-source.ts';
let current: {
stop: AbortController;
@@ -92,6 +93,8 @@ export async function maintainCopy(
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
const { id, operation, steamLocations } = request;
const record = await requireCopy(id);
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
const root = await checkedRoot(record);
const dataPath = await canonicalCopyPath(record.dataPath);
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
@@ -0,0 +1,52 @@
import { isAbsolute, join } from 'node:path';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { canonicalCopyPath, copyPathContains, updateCopyRecord } from '../install/install-record.ts';
import { fileInfo } from './change-copy-files.ts';
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
return await inspectSource(record, record.sourcePath);
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export async function setCopySource(record: InstallRecord, path: string | undefined): Promise<Copies> {
const source = await inspectSource(record, path);
return updateCopyRecord(record.id, (latest) => {
if (latest.copyPath !== record.copyPath || latest.dataPath !== record.dataPath) {
throw new AppError('maintenance_location');
}
return { ...latest, sourcePath: source.resolvedPath };
});
}
async function inspectSource(record: InstallRecord, path: string | undefined): Promise<GameFolderInspection> {
if (!path || !isAbsolute(path)) throw new AppError('maintenance_source_invalid');
const [game, copyPath, dataPath] = await Promise.all([
inspectGameFolder(path), canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath),
]);
const source = game.resolvedPath;
const overlapsCopy = copyPathContains(source, copyPath) || copyPathContains(copyPath, source);
if (overlapsCopy || copyPathContains(source, dataPath)) {
throw new AppError('maintenance_source_overlap');
}
if (game.missingFiles.length || !game.version || game.hasOfflineBackup || game.needsStockSource) {
throw new AppError('maintenance_source_invalid');
}
// Verify that the directory has game resources beyond the four files used for patching.
const [content, languages, missions] = await Promise.all([
fileInfo(join(source, 'content')),
fileInfo(join(source, 'lang.vromfs.bin')),
fileInfo(join(source, 'mis.vromfs.bin')),
]);
if (!content?.isDirectory() || !languages?.isFile() || !missions?.isFile()) {
throw new AppError('maintenance_source_invalid');
}
return { ...game, path: source };
}
@@ -7,6 +7,7 @@ import { zipSync } from 'fflate';
import { GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { PORTABLE_UPDATE_LOG_FILENAME } from '../app-update/portable-update.ts';
import { getSettings } from '../config/settings-store.ts';
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
@@ -58,6 +59,11 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
}
}
await addFile(
files,
`launcher-logs/${PORTABLE_UPDATE_LOG_FILENAME}`,
join(userData, 'launcher-updates', PORTABLE_UPDATE_LOG_FILENAME),
);
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
if (dataPath) await addServerLogs(files, dataPath);
@@ -1,9 +1,9 @@
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs';
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises';
import { join, relative } from 'node:path';
import type { BigIntStats, Dirent } from 'node:fs';
import { join, normalize, relative, sep } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { AppError } from '@shared/errors.ts';
import { rawFs } from '../../util/raw-fs.ts';
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
/**
@@ -12,14 +12,45 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
*/
/**
* Top-level folders of an installation that hold what the game produced while the player played
* online, not the game itself: logs, the web content cache, replays, screenshots and the player's
* own missions. The offline copy does not take the online game's data (working rules 18); the
* Top-level folders of an installation that hold player-generated data or user content from
* playing online, not the stock client itself: logs, the web content cache, replays, screenshots,
* and user missions, skins and sights. The offline copy does not take the online game's data; the
* game creates these folders again when it needs them.
*/
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']);
export const PLAYER_DATA_FOLDERS = new Set([
'.game_logs',
'cache',
'replays',
'screenshots',
'usermissions',
'userskins',
'usersights',
]);
/**
* Top-level folders ignored when scanning a stock source in addition to player data:
* official launcher/updater logs and obsolete files, the War Thunder CDK toolkit, and any stray
* offline backup directory.
*/
const SKIPPED_SOURCE_FOLDERS = new Set([
...PLAYER_DATA_FOLDERS,
'.gaijin_updater_logs',
'.launcher_log',
'.obsolete',
'.start_app_logs',
'warthundercdk',
'wtoffline',
]);
const LAUNCHER_EXECUTABLE_LOWER = 'wtoffline launcher.exe';
/** Whether a relative path starts with a top-level entry excluded from source scans. */
export function isInSkippedSourceFolder(relativePath: string): boolean {
const [topLevel = ''] = normalize(relativePath).split(sep, 1);
return SKIPPED_SOURCE_FOLDERS.has(topLevel.toLowerCase());
}
function isLauncherFolder(entries: readonly Dirent[]): boolean {
return entries.some((entry) => entry.isFile() && entry.name.toLowerCase() === LAUNCHER_EXECUTABLE_LOWER);
}
interface CopyEntry {
readonly relativePath: string;
@@ -40,20 +71,26 @@ export interface CopyProgress {
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
export async function planCopy(source: string): Promise<CopyPlan> {
const fsPromises = rawFs().promises;
const files: CopyEntry[] = [];
const folders: string[] = [];
let totalBytes = 0;
const pending = [source];
while (pending.length) {
const folder = pending.pop()!;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const entries = await fsPromises.readdir(folder, { withFileTypes: true });
if (folder !== source) {
// Skip any WTOffline Launcher folder that was previously extracted inside the game directory.
if (isLauncherFolder(entries)) continue;
folders.push(relative(source, folder));
}
for (const entry of entries) {
const path = join(folder, entry.name);
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue;
if (folder === source && isInSkippedSourceFolder(entry.name)) continue;
if (entry.isDirectory()) {
folders.push(relative(source, path));
pending.push(path);
} else if (entry.isFile()) {
const { size, mtimeMs } = await lstat(path);
const { size, mtimeMs } = await fsPromises.lstat(path);
files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs });
totalBytes += size;
}
@@ -78,8 +115,10 @@ export async function copyPlannedFiles(
onProgress: (progress: CopyProgress) => void,
hardlinks?: ReadonlyMap<string, BigIntStats>,
): Promise<void> {
await mkdir(target, { recursive: true });
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
const fs = rawFs();
const fsPromises = fs.promises;
await fsPromises.mkdir(target, { recursive: true });
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
let next = 0;
let doneBytes = 0;
@@ -95,6 +134,8 @@ export async function copyPlannedFiles(
// caller cleaning up after an error never races a copy still writing.
const stop = new AbortController();
const stopSignal = AbortSignal.any([signal, stop.signal]);
let firstError: unknown = null;
let hasError = false;
const copyNext = async (): Promise<void> => {
try {
while (next < plan.files.length) {
@@ -109,30 +150,35 @@ export async function copyPlannedFiles(
doneBytes += file.bytes;
} else {
await pipeline(
createReadStream(from),
fs.createReadStream(from),
countBytes(),
// 'wx': fail instead of overwriting a file that is already there.
createWriteStream(to, { flags: 'wx' }),
fs.createWriteStream(to, { flags: 'wx' }),
{ signal: stopSignal },
);
const modified = new Date(file.modifiedAt);
await utimes(to, modified, modified);
await fsPromises.utimes(to, modified, modified);
}
doneFiles += 1;
onProgress({ doneBytes, doneFiles });
}
} catch (error) {
if (!hasError && !stop.signal.aborted && !signal.aborted) {
hasError = true;
firstError = error;
}
stop.abort(error);
throw error;
}
};
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
if (hasError) throw firstError;
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failed) throw failed.reason;
if (linkedTargets) {
for (const [path, stamp] of linkedTargets) {
signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
if (!sameResource(stamp, await fsPromises.lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
}
}
}
@@ -142,9 +188,10 @@ export async function copyPlannedFiles(
* when the copy started, so everything in it came from the copy.
*/
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
const fsPromises = rawFs().promises;
if (!targetExisted) {
await rm(target, { recursive: true, force: true });
await fsPromises.rm(target, { recursive: true, force: true });
return;
}
for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true });
for (const entry of await fsPromises.readdir(target)) await fsPromises.rm(join(target, entry), { recursive: true, force: true });
}
@@ -1,6 +1,7 @@
import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path';
import { app } from 'electron';
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
@@ -140,6 +141,12 @@ async function inspectInstallation(request: InstallRequest) {
const [copyPath, dataPath, sourcePath] = await Promise.all([
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
]);
if (request.method === 'copy' && app.isPackaged) {
const launcherDir = await canonicalCopyPath(dirname(process.execPath));
if (copyPathContains(sourcePath, launcherDir)) {
throw new AppError('launcher_inside_source');
}
}
await requireAvailableCopy(request.id, copyPath, dataPath);
const dataProblem = dataFolderProblem(
dataPath,
@@ -11,6 +11,7 @@ import type { Settings } from '@shared/schemas/settings.ts';
import { getSettings } from '../config/settings-store.ts';
import { decalCachePath } from '../install/decals.ts';
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
@@ -108,7 +109,7 @@ async function launch(job: LaunchJob): Promise<void> {
job.copyId = record.id;
const plan = await planLaunch(job, record, settings);
if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port } = plan;
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
await buildForLaunch(job, record, plan, settings);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
@@ -123,7 +124,15 @@ async function launch(job: LaunchJob): Promise<void> {
update(job, { phase: 'ready' });
return;
}
const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish);
const gameExit = await runOrdinaryLaunch(
copyPath,
dataPath,
port,
settings,
signal,
publish,
{ modsDir, enabledModIds },
);
update(job, { phase: 'game-exited', gameExit });
}
@@ -134,6 +143,8 @@ interface LaunchPlan {
readonly dataPath: string;
readonly steamLibraryConfirmed: boolean;
readonly port: number;
readonly modsDir: string;
readonly enabledModIds: readonly string[];
}
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
@@ -183,13 +194,15 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
}
if (games) throw new AppError('launch_game_running');
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
const port = await selectPort(requestedPort);
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
}
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
@@ -211,6 +224,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
modsDir,
enabledModIds,
}, signal, (filesWritten, filesTotal, file) => {
writtenFiles = filesWritten;
if (!signal.aborted) update(job, {
@@ -33,13 +33,22 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
}
}
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
}
export async function startLocalServer(
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
{ gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
): Promise<LocalServer> {
signal.throwIfAborted();
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
if (modsDir && enabledModIds && enabledModIds.length > 0) {
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
}
const worker = utilityProcess.fork(
join(import.meta.dirname, 'server-worker.js'),
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
workerArgs,
{
serviceName: 'WTOffline local server',
stdio: 'pipe',
@@ -45,12 +45,19 @@ type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-r
export async function runOrdinaryLaunch(
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
): Promise<GameExit> {
const args = parseLaunchArguments(settings.launchArguments);
if (!args) throw new AppError('launch_game_failed');
publish('starting-server');
const server = await startLocalServer(
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
{
gameFolder: copyPath,
dataFolder: dataPath,
port,
loggingEnabled: settings.loggingEnabled,
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
},
signal,
);
const stop = new AbortController();
@@ -0,0 +1,428 @@
import { randomUUID } from 'node:crypto';
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { app, BrowserWindow, dialog, shell } from 'electron';
import {
computeAutoSortOrder,
discoverMods,
emptyClientModsConfig,
MOD_API_VERSION,
normalizeClientModsConfig,
resolveModLoadOrder,
type ClientModsConfig,
type DiscoveredMod,
type ModPreset,
} from '@wto/mods';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { getSettings, updateSettings } from '../config/settings-store.ts';
import { listCopies } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
const inFlightSeeds = new Map<string, Promise<void>>();
export function defaultModsFolder(): string {
return join(app.getPath('userData'), 'mods');
}
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
const settings = await getSettings();
const defaultModsDir = defaultModsFolder();
const isCustomModsDir = settings.modsFolder !== null;
const modsDir = settings.modsFolder ?? defaultModsDir;
await mkdir(modsDir, { recursive: true });
await seedBundledExampleModsOnce(modsDir);
return { modsDir, defaultModsDir, isCustomModsDir };
}
/**
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
* deleting a bundled template never restores it, while newly added official templates still
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
*/
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
const key = modsDir.toLowerCase();
const pending = inFlightSeeds.get(key);
if (pending) {
await pending;
return;
}
const task = (async () => {
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
try {
const templatesRoot = resourcePaths().modTemplates;
if (!(await pathExists(templatesRoot))) return;
const seeded = await readSeededTemplateNames(markerPath, modsDir);
const templates = await readdir(templatesRoot, { withFileTypes: true });
let changed = false;
for (const entry of templates) {
if (!entry.isDirectory()) continue;
if (seeded.has(entry.name)) continue;
const dest = join(modsDir, entry.name);
if (!(await pathExists(dest))) {
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
}
seeded.add(entry.name);
changed = true;
}
if (changed || !(await pathExists(markerPath))) {
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
}
} catch (error) {
console.warn('[mods] seeding bundled example mods skipped:', error);
}
})().finally(() => {
inFlightSeeds.delete(key);
});
inFlightSeeds.set(key, task);
await task;
}
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
if (!(await pathExists(markerPath))) return new Set();
try {
const raw = (await readFile(markerPath, 'utf8')).trim();
if (raw === '1') {
// Legacy marker from initial 2-template version: mark existing folders as already seeded
// so newly added official templates (e.g. official-map-selector) are still delivered once.
const existing = await readdir(modsDir);
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
for (const name of existing) set.add(name);
return set;
}
const parsed = JSON.parse(raw) as { seeded?: unknown };
if (Array.isArray(parsed.seeded)) {
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
}
} catch { /* ignore */ }
return new Set();
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
export async function openModsFolder(): Promise<void> {
const { modsDir } = await resolveModsFolder();
const failure = await shell.openPath(modsDir);
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
}
export async function getModsState(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next: ClientModsConfig = {
...current,
activePresetId: null,
enabled: { ...current.enabled, [modId]: enabled },
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
const next: ClientModsConfig = {
...current,
activePresetId: null,
order: sortedOrder,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const now = new Date().toISOString();
let presets: ModPreset[];
let presetId: string;
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
presetId = overwriteId;
presets = current.presets.map((preset) => (
preset.id === overwriteId
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
: preset
));
} else {
presetId = randomUUID();
presets = [
...current.presets,
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
];
}
const next: ClientModsConfig = {
...current,
activePresetId: presetId,
presets,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const next = normalizeClientModsConfig({
...current,
order: preset.order,
enabled: preset.enabled,
activePresetId: preset.id,
}, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const next: ClientModsConfig = {
...current,
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
presets: current.presets.filter((preset) => preset.id !== presetId),
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function exportModPreset(
copyId: string,
presetId: string,
window: BrowserWindow | null,
): Promise<{ readonly path: string | null }> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
const dialogOptions = {
defaultPath: `${safeName}.wto-mods-preset.json`,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showSaveDialog(window, dialogOptions)
: await dialog.showSaveDialog(dialogOptions);
if (choice.canceled || !choice.filePath) return { path: null };
const payload = {
format: 1 as const,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
};
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
return { path: choice.filePath };
}
export async function importModPreset(
copyId: string,
window: BrowserWindow | null,
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
const copy = await requireCopy(copyId);
const dialogOptions = {
properties: ['openFile'] as Array<'openFile'>,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showOpenDialog(window, dialogOptions)
: await dialog.showOpenDialog(dialogOptions);
if (choice.canceled || !choice.filePaths[0]) {
return { imported: false, state: await buildModsStateView(copy) };
}
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
} catch {
throw new AppError('mods_preset_invalid');
}
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
if (!validated.success) throw new AppError('mods_preset_invalid');
const current = await readClientModsConfig(copy.dataPath);
const newPreset: ModPreset = {
id: randomUUID(),
name: validated.data.name,
order: validated.data.order,
enabled: validated.data.enabled,
updatedAt: new Date().toISOString(),
};
const next: ClientModsConfig = {
...current,
presets: [...current.presets, newPreset],
};
await writeClientModsConfig(copy.dataPath, next);
return { imported: true, state: await buildModsStateView(copy, next) };
}
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
if (folderPath !== null) {
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
try {
await mkdir(folderPath, { recursive: true });
const info = await stat(folderPath);
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError('mods_folder_invalid');
}
}
await updateSettings({ modsFolder: folderPath });
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
export async function resolveEnabledModsForLaunch(
dataPath: string,
gameVersion: string | null,
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
if (resolved.hasBlockingErrors) {
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
throw new AppError('mods_blocking_issues');
}
return { modsDir, enabledMods: resolved.enabledMods };
}
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const orderedMods: ModListItem[] = config.order
.map((id) => byId.get(id))
.filter((mod): mod is DiscoveredMod => mod !== undefined)
.map(toModListItem);
return {
modsDir,
defaultModsDir,
isCustomModsDir,
apiVersion: MOD_API_VERSION,
mods: orderedMods,
discoveryErrors: [...discovered.errors],
order: [...config.order],
enabled: { ...config.enabled },
activePresetId: config.activePresetId,
presets: config.presets.map((preset) => ({
id: preset.id,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
updatedAt: preset.updatedAt,
})),
issues: [...resolved.issues],
hasBlockingErrors: resolved.hasBlockingErrors,
};
}
function toModListItem(mod: DiscoveredMod): ModListItem {
return {
id: mod.manifest.id,
folderName: mod.folderName,
rootDir: mod.rootDir,
name: mod.manifest.name,
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
version: mod.manifest.version,
author: mod.manifest.author,
apiVersion: mod.manifest.apiVersion,
gameVersions: [...mod.manifest.gameVersions],
requires: [...mod.manifest.requires],
conflicts: [...mod.manifest.conflicts],
loadAfter: [...mod.manifest.loadAfter],
loadBefore: [...mod.manifest.loadBefore],
badges: [...mod.content.badges],
hasServerScript: mod.content.serverEntry !== undefined,
serverTuningFiles: [...mod.content.serverTuningFiles],
packOperations: [...mod.content.packOperations],
guiPatchCount: mod.content.guiPatchDirs.length,
exePatchCount: mod.content.exePatchDirs.length,
hasClientAddon: mod.content.hasClientAddon,
addonFileCount: mod.content.addonRelativeFiles.length,
clientFileCount: mod.content.clientFiles.length,
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
};
}
async function requireCopy(copyId: string): Promise<InstallRecord> {
const copies = await listCopies();
const copy = copies.copies.find((entry) => entry.id === copyId);
if (!copy) throw new AppError('copy_not_found');
return copy;
}
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
try {
const raw = await readJsonOr(path, null);
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
const obj = raw as Partial<ClientModsConfig>;
return {
format: 1,
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
presets: Array.isArray(obj.presets) ? obj.presets : [],
};
} catch (error) {
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
return emptyClientModsConfig();
}
}
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
try {
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
} catch (error) {
console.error('[mods] writing client mods config failed:', error);
throw new AppError('mods_write_failed');
}
}
@@ -1,6 +1,6 @@
/**
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
* The project repository is tried first, with an optional player-configured fallback.
* The primary release source is tried first, followed by any player-configured mirror and default fallbacks.
*/
import { net } from 'electron';
import {
@@ -62,6 +62,7 @@ export class ReleasePageLimitError extends Error {
}
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
const MAX_RELEASE_NOTES_CHARS = 64 * 1024;
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
const LauncherReleaseEntry = z.object({
draft: z.literal(false),
@@ -98,18 +99,35 @@ export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
export async function withReleaseSources<T>(
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
): Promise<T> {
const primary = releaseSource(new URL(`https://github.com/${patchPackTuning().repository}`));
const repository = releaseRepositoryUrl((await getSettings()).updateMirrorUrl);
const mirror = repository ? releaseSource(repository) : null;
if (!mirror || sameReleaseSource(primary, mirror)) return read(primary);
const [first, second] = preferred && sameReleaseSource(preferred, mirror) ? [mirror, primary] : [primary, mirror];
try {
return await read(first);
} catch (error) {
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
console.info(`[release-feed] ${first.feed.hostname} was unavailable, trying ${second.feed.hostname}.`);
return read(second);
const tuning = patchPackTuning();
const candidates: ReleaseSource[] = [];
const add = (url: URL | null): void => {
if (!url) return;
const source = releaseSource(url);
if (!candidates.some((existing) => sameReleaseSource(existing, source))) candidates.push(source);
};
add(releaseRepositoryUrl(tuning.primarySource));
add(releaseRepositoryUrl((await getSettings()).updateMirrorUrl));
for (const fallback of tuning.fallbackSources) add(releaseRepositoryUrl(fallback));
if (candidates.length === 0) throw new FeedUnreachableError('No valid release sources are configured.');
const ordered = preferred
? [preferred, ...candidates.filter((source) => !sameReleaseSource(source, preferred))]
: candidates;
let lastError: unknown;
for (let index = 0; index < ordered.length; index += 1) {
const current = ordered[index]!;
try {
return await read(current);
} catch (error) {
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
lastError = error;
const next = ordered[index + 1];
if (next) console.info(`[release-feed] ${current.feed.hostname} was unavailable, trying ${next.feed.hostname}.`);
}
}
throw lastError;
}
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
@@ -248,7 +266,7 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
return {
source,
version,
notes: body?.trim().slice(0, 1600) ?? '',
notes: body?.trim().slice(0, MAX_RELEASE_NOTES_CHARS) ?? '',
installer,
manifest,
signature,
@@ -17,6 +17,10 @@ export interface ResourcePaths {
readonly networkHookLibrary: string;
/** Multi-resolution Windows icon for the window and system tray. */
readonly appIcon: string;
/** Bundled example mod templates seeded into an empty mods folder on first use. */
readonly modTemplates: string;
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
readonly groundAiScripts: string;
}
export function resourcePaths(): ResourcePaths {
@@ -32,6 +36,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(process.resourcesPath, 'patches'),
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
};
}
// The app path is apps/launcher; the repository is two levels up.
@@ -40,6 +46,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(repository, 'patches'),
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
groundAiScripts: join(repository, 'game-ai', 'ground'),
};
}
+23
View File
@@ -0,0 +1,23 @@
import * as nodeFs from 'node:fs';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
let cached: typeof nodeFs | null = null;
/**
* Return Node's unpatched fs module inside Electron.
*
* Electron patches `node:fs` to treat any `.asar` file anywhere on disk as a virtual archive
* directory, which breaks streaming reads, stats and recursive cleanup when copying or managing
* player folders that happen to contain an `.asar` file. Falls back to `node:fs` outside Electron.
*/
export function rawFs(): typeof nodeFs {
if (cached) return cached;
try {
cached = require('original-fs') as typeof nodeFs;
} catch {
cached = nodeFs;
}
return cached;
}
@@ -9,9 +9,12 @@ export interface BuildRequest {
readonly port: number;
readonly patches: string;
readonly networkHookLibrary: string;
readonly groundAiScripts: string;
readonly decalCache?: string;
readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[];
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
}
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
+83 -6
View File
@@ -1,14 +1,34 @@
import { readFileSync, realpathSync } from 'node:fs';
import { relative } from 'node:path';
import type { MessageEvent } from 'electron';
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readPlayerDecalIndexFiles, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server';
import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import {
assertWritableCopy,
buildGameCopy,
computeModsBuildFingerprint,
copyPlayerDecalCache,
CORE_BUILD_PACKS,
GAME_PACK_FILE,
isGroundAiActive,
playerDecalCacheProblem,
prepareOptionalStockPacks,
readPlayerDecalIndexFiles,
readStockGameFiles,
syncExternalModFiles,
writeGameCopy,
type GameCopyBuild,
type GameCopyFile,
} from '@wto/patcher';
import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
let prepared: {
readonly request: BuildRequest;
readonly files: readonly GameCopyFile[];
readonly decalCache: string | undefined;
readonly enabledMods: readonly DiscoveredMod[];
readonly optionalPacksInBuild: readonly ModdableClientPack[];
readonly fingerprint: string;
} | null = null;
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
@@ -31,19 +51,63 @@ function importedDecals(path: string | undefined): string | undefined {
return undefined;
}
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const ordered: DiscoveredMod[] = [];
for (const id of enabledModIds) {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
ordered.push(mod);
}
return ordered;
}
function logModBuildSummary(result: GameCopyBuild): void {
if (result.gamePack) {
console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`);
}
if (result.mods.enabledModIds.length === 0) return;
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
function build(request: BuildRequest): void {
checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
const groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods);
const groundAiActive = isGroundAiActive(groundAiConfig);
const touchedSet = new Set<ModdableClientPack>(
touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)),
);
if (groundAiActive) touchedSet.add(GAME_PACK_FILE);
const optionalPacksInBuild = [...touchedSet];
const extraStockPacks = optionalPacksInBuild.length > 0
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
: undefined;
const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath),
patches: request.patches,
networkHookLibrary: readFileSync(request.networkHookLibrary),
port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging,
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
});
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable);
@@ -52,7 +116,13 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' });
return;
}
prepared = { request, files: result.files, decalCache };
logModBuildSummary(result);
const fingerprint = computeModsBuildFingerprint(
enabledMods,
request.port,
`${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`,
);
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
send({ kind: 'prepared', total: prepared.files.length });
}
@@ -64,15 +134,22 @@ process.parentPort.on('message', (event: MessageEvent) => {
return;
}
if (!prepared) throw new Error('No build is ready to write.');
const { request, files, decalCache } = prepared;
const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
prepared = null;
checkBuildLocation(request);
const { copyPath } = request;
const { copyPath, stockPath } = request;
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
for (const [index, file] of files.entries()) {
writeGameCopy(copyPath, [file]);
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
}
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
for (const warning of deployResult.warnings) {
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
}
if (deployResult.restoredOptionalPacks.length > 0) {
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
}
send({ kind: 'written' });
} catch (error) {
console.error('[build] preparing the game copy failed:', error);
@@ -1,16 +1,42 @@
import { discoverMods, type DiscoveredMod } from '@wto/mods';
import { startServer } from '@wto/server';
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
if (!modsDir || !enabledJson) return [];
const ids = JSON.parse(enabledJson) as unknown;
if (!Array.isArray(ids) || ids.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const mods: DiscoveredMod[] = [];
for (const id of ids) {
if (typeof id !== 'string') continue;
const mod = byId.get(id);
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
mods.push(mod);
}
return mods;
}
async function serve(): Promise<void> {
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2);
const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
const port = Number(portText);
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid local server arguments.');
}
const loggingEnabled = loggingFlag !== '0';
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
const mods = loadOrderedMods(modsDir, enabledModIdsJson);
const server = await startServer({
gameFolder,
dataFolder,
port,
loggingEnabled,
...(mods.length > 0 ? { mods } : {}),
report: console.info,
});
if (server.logFolder) console.info('Traffic log:', server.logFolder);
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
process.parentPort.once('message', () => {
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
console.error('Could not close the local server:', error);
+10 -1
View File
@@ -22,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts';
import { ModsPage } from './pages/mods/ModsPage.tsx';
import { TuningPage } from './pages/tuning/TuningPage.tsx';
import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
@@ -32,7 +33,7 @@ import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts';
import { Footer } from './shell/Footer.tsx';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts';
@@ -195,6 +196,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
bar: home,
};
case 'mods':
return {
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
main: record
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
bar: home,
};
case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') {
@@ -0,0 +1,152 @@
import { createElement, Fragment, useMemo, type ReactNode } from 'react';
import { marked, type Token, type Tokens } from 'marked';
const SAFE_EXTERNAL_URL = /^https?:\/\//i;
const HTML_COMMENT = /^<!--[\s\S]*?-->$/;
function isSafeExternalUrl(href: string | undefined): href is string {
return typeof href === 'string' && SAFE_EXTERNAL_URL.test(href.trim());
}
function renderInline(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderInlineToken(token, `${keyPrefix}-${index}`));
}
function renderInlineToken(token: Token, key: string): ReactNode {
switch (token.type) {
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'escape':
return <Fragment key={key}>{(token as Tokens.Escape).text}</Fragment>;
case 'strong':
return <strong key={key}>{renderInline((token as Tokens.Strong).tokens, key)}</strong>;
case 'em':
return <em key={key}>{renderInline((token as Tokens.Em).tokens, key)}</em>;
case 'del':
return <del key={key}>{renderInline((token as Tokens.Del).tokens, key)}</del>;
case 'codespan':
return <code key={key}>{(token as Tokens.Codespan).text}</code>;
case 'br':
return <br key={key} />;
case 'link': {
const link = token as Tokens.Link;
const content = link.tokens.length ? renderInline(link.tokens, key) : link.text;
if (!isSafeExternalUrl(link.href)) return <Fragment key={key}>{content}</Fragment>;
return (
<a key={key} href={link.href} title={link.title ?? undefined} target="_blank" rel="noreferrer">
{content}
</a>
);
}
case 'image':
return <Fragment key={key}>{(token as Tokens.Image).text}</Fragment>;
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <Fragment key={key}>{raw}</Fragment>;
}
default:
return 'raw' in token && typeof token.raw === 'string' ? <Fragment key={key}>{token.raw}</Fragment> : null;
}
}
function renderTable(table: Tokens.Table, key: string): ReactNode {
return (
<div key={key} className="markdown-table-wrap">
<table>
<thead>
<tr>
{table.header.map((cell, column) => (
<th key={`${key}-h-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-h-${column}`)}
</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row, rowIndex) => (
<tr key={`${key}-r-${rowIndex}`}>
{row.map((cell, column) => (
<td key={`${key}-r-${rowIndex}-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-r-${rowIndex}-${column}`)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
function renderListItem(item: Tokens.ListItem, key: string): ReactNode {
return (
<li key={key}>
{item.task && <input type="checkbox" checked={Boolean(item.checked)} disabled readOnly className="markdown-task" />}
{renderBlocks(item.tokens, key)}
</li>
);
}
function renderBlock(token: Token, key: string): ReactNode {
switch (token.type) {
case 'space':
case 'def':
case 'checkbox':
return null;
case 'heading': {
const heading = token as Tokens.Heading;
const level = Math.min(6, Math.max(1, heading.depth));
return createElement(`h${level}`, { key }, renderInline(heading.tokens, key));
}
case 'paragraph':
return <p key={key}>{renderInline((token as Tokens.Paragraph).tokens, key)}</p>;
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'blockquote':
return <blockquote key={key}>{renderBlocks((token as Tokens.Blockquote).tokens, key)}</blockquote>;
case 'list': {
const list = token as Tokens.List;
const items = list.items.map((item, index) => renderListItem(item, `${key}-i-${index}`));
if (list.ordered) {
return <ol key={key} start={typeof list.start === 'number' && list.start !== 1 ? list.start : undefined}>{items}</ol>;
}
return <ul key={key}>{items}</ul>;
}
case 'code':
return (
<pre key={key}>
<code>{(token as Tokens.Code).text}</code>
</pre>
);
case 'hr':
return <hr key={key} />;
case 'table':
return renderTable(token as Tokens.Table, key);
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <p key={key}>{raw}</p>;
}
default:
return 'raw' in token && typeof token.raw === 'string' && token.raw.trim()
? <p key={key}>{token.raw}</p>
: null;
}
}
function renderBlocks(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderBlock(token, `${keyPrefix}-${index}`));
}
/** Safe React renderer for GFM Markdown without injecting raw HTML. */
export function MarkdownContent({ markdown }: { readonly markdown: string }) {
const tokens = useMemo(() => marked.lexer(markdown, { gfm: true, breaks: false }), [markdown]);
return <div className="markdown-body">{renderBlocks(tokens, 'md')}</div>;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -7,6 +7,7 @@ import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { AppUpdateSection } from './AppUpdateSection.tsx';
import type { PatchPackState } from '../../shell/usePatchPack.ts';
const HOMEPAGE_URL = 'https://wto-project.net';
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
interface AboutPageProps {
@@ -37,6 +38,7 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
<PatchPackSection state={patchPack} />
</div>
<div className="about-column">
<HomepageSection />
<CommunitySection />
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
<section className="about-card">
@@ -49,6 +51,23 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
);
}
function HomepageSection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
<div className="about-card-actions">
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
{t('about.homepage.open')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.homepage.hint')}</p>
</section>
);
}
function CommunitySection() {
const { t } = useTranslation();
return (
@@ -1,13 +1,19 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx';
import { formatBytes } from '../../format.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { ReleaseNotesModal } from './ReleaseNotesModal.tsx';
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
const { t } = useTranslation();
const [notesOpen, setNotesOpen] = useState(false);
if (!state.supported) return null;
const { check, busy, progress } = state;
const available = check?.status === 'available' && busy !== 'checking' ? check : null;
const notes = available?.release.notes.trim() ?? '';
return (
<section className="about-card">
<div className="about-card-head">
@@ -21,30 +27,46 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
<p className="about-card-meta">{t('about.update.check')}</p>
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
{check?.status === 'available' && busy !== 'checking' && (
{available && (
<Notice tone="info">
<p>{t('about.update.available', { version: check.release.version, size: formatBytes(check.release.size) })}</p>
{check.release.notes && <p className="small update-notes">{check.release.notes}</p>}
{busy === 'downloading' ? (
<p>{t('about.update.available', { version: available.release.version, size: formatBytes(available.release.size) })}</p>
{busy === 'downloading' && (
<>
<p>{t('about.update.downloading')}</p>
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
</>
) : (
<button
type="button"
className="button button-primary"
disabled={busy !== null}
onClick={() => {
if (check.ready) state.install(check.release.version);
else state.download(check.release.version);
}}
>
{t(busy === 'installing' ? 'about.update.installing' : check.ready ? 'about.update.install' : 'about.update.download')}
</button>
)}
{(busy !== 'downloading' || notes) && (
<div className="update-actions">
{busy !== 'downloading' && (
<button
type="button"
className="button button-primary"
disabled={busy !== null}
onClick={() => {
if (available.ready) state.install(available.release.version);
else state.download(available.release.version);
}}
>
{t(busy === 'installing' ? 'about.update.installing' : available.ready ? 'about.update.install' : 'about.update.download')}
</button>
)}
{notes && (
<button type="button" className="button button-compact" onClick={() => setNotesOpen(true)}>
{t('about.update.viewNotes')}
</button>
)}
</div>
)}
</Notice>
)}
{notesOpen && available && notes && (
<ReleaseNotesModal
version={available.release.version}
notes={notes}
onClose={() => setNotesOpen(false)}
/>
)}
</section>
);
}
@@ -0,0 +1,57 @@
import { useEffect, useId } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { MarkdownContent } from '../../components/MarkdownContent.tsx';
interface ReleaseNotesModalProps {
readonly version: string;
readonly notes: string;
readonly onClose: () => void;
}
/** Standalone dialog displaying rendered Markdown release notes for an available launcher update. */
export function ReleaseNotesModal({ version, notes, onClose }: ReleaseNotesModalProps) {
const { t } = useTranslation();
const titleId = useId();
useEffect(() => {
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [onClose]);
return createPortal(
<div
className="modal-backdrop"
role="presentation"
onClick={(event) => {
if (event.target === event.currentTarget) onClose();
}}
>
<div className="modal-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}>
<header className="modal-head">
<h3 id={titleId} className="modal-title">{t('about.update.notesTitle', { version })}</h3>
<button
type="button"
className="modal-close"
aria-label={t('about.update.closeNotes')}
onClick={onClose}
>
×
</button>
</header>
<div className="modal-body">
<MarkdownContent markdown={notes} />
</div>
<footer className="modal-foot">
<button type="button" className="button" onClick={onClose}>
{t('about.update.closeNotes')}
</button>
</footer>
</div>
</div>,
document.body,
);
}
@@ -22,17 +22,24 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
useEffect(() => {
let mounted = true;
setInfo(null);
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
if (mounted) setInfo(value);
}).catch(onError);
return () => { mounted = false; };
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
}, [record.id, record.gameVersion, record.sourcePath, record.steamLibraryConfirmation, maintenance.revision, onError]);
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
if (operation === 'delete') setRemoval(null);
maintenance.run(record.id, operation, options);
};
const chooseUpdateSource = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('copies.maintenance.chooseSource') }).then(({ path }) => {
if (path) run('set-source', { sourcePath: path });
}).catch(onError);
};
const active = maintenance.active;
const busy = active !== null;
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
@@ -44,6 +51,7 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc
info={info}
busy={busy}
onRun={run}
onChooseSource={chooseUpdateSource}
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
/>
<CopyRemoval
@@ -12,12 +12,20 @@ interface CopyMaintenanceControlsProps {
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
readonly onChooseSource: () => void;
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
}
export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSteam }: CopyMaintenanceActionsProps) {
export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSource, onConfirmSteam }: CopyMaintenanceActionsProps) {
const { t, i18n } = useTranslation();
const steam = info?.steamLocations;
const updateHint = info?.sourceVersion
? t(info.updateAvailable
? (record.hardlinkedFiles?.length
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t(record.sourcePath ? (info ? 'copies.maintenance.noSource' : 'copies.maintenance.phase.checking') : 'copies.maintenance.sourceNotSet');
return (
<>
{info?.steamConfirmationRequired && steam && (
@@ -30,13 +38,10 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
</button>
</Notice>
)}
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
? t(info.updateAvailable
? (record.hardlinkedFiles?.length
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t('copies.maintenance.noSource')}>
<Row label={t('copies.maintenance.update')} hint={record.sourcePath ? <>{record.sourcePath}<br />{updateHint}</> : updateHint}>
<button type="button" className="button" disabled={busy} onClick={onChooseSource}>
{t(record.sourcePath ? 'copies.maintenance.changeSource' : 'copies.maintenance.setSource')}
</button>
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
{t('copies.maintenance.updateAction')}
@@ -4,7 +4,7 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
export type MaintenanceOperation = MaintenanceRequest['operation'];
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations' | 'sourcePath'>;
export interface MaintenanceOutcome {
readonly copyId: string;
@@ -0,0 +1,591 @@
import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { ModsSection } from '../../shell/navigation.ts';
const MOD_DOCS_URL = 'https://wto-project.net/mod-docs';
interface Props {
readonly copy: InstallRecord;
readonly section: ModsSection;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
}
function localized(value: string | Readonly<Record<string, string>> | undefined, language: string): string {
if (!value) return '';
if (typeof value === 'string') return value;
const exact = value[language];
if (exact) return exact;
const prefix = language.split('-')[0];
if (prefix) {
const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
if (match?.[1]) return match[1];
}
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
}
export function ModsPage({ copy, section, readOnly, onError }: Props) {
const { t, i18n } = useTranslation();
const [state, setState] = useState<ModsStateView | null>(null);
const [busy, setBusy] = useState(false);
const [query, setQuery] = useState('');
const [expandedId, setExpandedId] = useState<string | null>(null);
const [draggedId, setDraggedId] = useState<string | null>(null);
const [presetName, setPresetName] = useState('');
const [notice, setNotice] = useState<string | null>(null);
const load = useCallback(() => {
setBusy(true);
ipcInvoke('mods:getState', { copyId: copy.id })
.then(setState)
.catch(onError)
.finally(() => setBusy(false));
}, [copy.id, onError]);
useEffect(() => {
let mounted = true;
const sync = (): void => {
ipcInvoke('mods:getState', { copyId: copy.id })
.then((result) => { if (mounted) setState(result); })
.catch(onError);
};
sync();
window.addEventListener('focus', sync);
return () => {
mounted = false;
window.removeEventListener('focus', sync);
};
}, [copy.id, onError]);
const runAction = (action: Promise<ModsStateView>, successNotice?: string): void => {
setBusy(true);
setNotice(null);
action
.then((next) => {
setState(next);
if (successNotice) setNotice(successNotice);
})
.catch(onError)
.finally(() => setBusy(false));
};
const issuesByMod = useMemo(() => {
const map = new Map<string, ModIssueView[]>();
for (const issue of state?.issues ?? []) {
const list = map.get(issue.modId) ?? [];
list.push(issue);
map.set(issue.modId, list);
}
return map;
}, [state]);
const title = t(`mods.sections.${section}`);
if (!state) {
return <Sheet title={title} aside={copy.name}><p className="lead">{t('mods.loading')}</p></Sheet>;
}
const disabled = readOnly || busy;
const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length;
const toggleMod = (modId: string, nextEnabled: boolean): void => {
runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled }));
};
const reorder = (nextOrder: string[]): void => {
runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder }));
};
const moveMod = (modId: string, delta: -1 | 1): void => {
const idx = state.order.indexOf(modId);
const target = idx + delta;
if (idx < 0 || target < 0 || target >= state.order.length) return;
const next = [...state.order];
const [item] = next.splice(idx, 1);
next.splice(target, 0, item!);
reorder(next);
};
const handleDrop = (targetId: string, event: DragEvent<HTMLDivElement>): void => {
event.preventDefault();
const sourceId = draggedId;
setDraggedId(null);
if (!sourceId || sourceId === targetId || disabled) return;
const from = state.order.indexOf(sourceId);
const to = state.order.indexOf(targetId);
if (from < 0 || to < 0) return;
const next = [...state.order];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved!);
reorder(next);
};
const savePreset = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const trimmed = presetName.trim();
if (!trimmed) return;
runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }),
t('mods.presets.saved', { name: trimmed }),
);
setPresetName('');
};
const pickCustomFolder = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') })
.then(({ path }) => {
if (!path) return;
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated'));
})
.catch(onError);
};
const resetFolder = (): void => {
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone'));
};
const exportPreset = (presetId: string): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId })
.then(({ path }) => {
if (path) setNotice(t('mods.presets.exported', { path }));
})
.catch(onError)
.finally(() => setBusy(false));
};
const importPreset = (): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:importPreset', { copyId: copy.id })
.then(({ imported, state: next }) => {
setState(next);
if (imported) setNotice(t('mods.presets.imported'));
})
.catch(onError)
.finally(() => setBusy(false));
};
const normalizedQuery = query.trim().toLowerCase();
const visibleMods = normalizedQuery
? state.mods.filter((mod) => {
const displayName = localized(mod.name, i18n.language).toLowerCase();
return displayName.includes(normalizedQuery)
|| mod.id.toLowerCase().includes(normalizedQuery)
|| mod.author.toLowerCase().includes(normalizedQuery);
})
: state.mods;
const canDrag = !disabled && normalizedQuery.length === 0;
return (
<Sheet
title={title}
aside={(
<span className="mods-aside">
<span>{copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })}</span>
<span
className="mods-exp-chip"
tabIndex={0}
aria-label={t('mods.experimentalBody', { api: state.apiVersion })}
>
<span>{t('mods.experimentalChip')}</span>
<span className="mods-exp-icon" aria-hidden="true">i</span>
<span className="mods-exp-popover" role="tooltip">
<strong>{t('mods.experimentalTitle')}</strong>
<span>{t('mods.experimentalBody', { api: state.apiVersion })}</span>
</span>
</span>
</span>
)}
>
{readOnly && (
<div className="mods-banner mods-banner-warn" role="status">
{t('mods.readOnlyNotice')}
</div>
)}
{notice && (
<div className="mods-banner mods-banner-ok" role="status">
{notice}
</div>
)}
{section === 'list' ? (
<>
<div className="mods-toolbar">
<input
type="search"
className="input mods-search"
placeholder={t('mods.searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
{state.presets.length > 0 && (
<select
className="select mods-preset-select"
aria-label={t('mods.presets.quickSwitch')}
disabled={disabled}
value={state.activePresetId ?? ''}
onChange={(event) => {
const id = event.target.value;
if (id) runAction(ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: id }));
}}
>
<option value="">{t('mods.presets.customOption')}</option>
{state.presets.map((preset) => (
<option key={preset.id} value={preset.id}>{preset.name}</option>
))}
</select>
)}
<button
type="button"
className="button"
disabled={disabled || state.mods.length < 2}
onClick={() => runAction(ipcInvoke('mods:autoSort', { copyId: copy.id }), t('mods.autoSorted'))}
>
{t('mods.autoSort')}
</button>
<button type="button" className="button" disabled={busy} onClick={load}>
{t('mods.refresh')}
</button>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<a className="button" href={MOD_DOCS_URL} target="_blank" rel="noreferrer">
{t('mods.openDocs')}
</a>
</div>
{state.discoveryErrors.length > 0 && (
<div className="mods-issues-box mods-issues-error">
<div className="mods-issues-title">{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}</div>
<ul>
{state.discoveryErrors.map((err) => (
<li key={err.folderName}>
<code>{err.folderName}</code>: {err.reason}
</li>
))}
</ul>
</div>
)}
{state.issues.length > 0 && (
<div className={state.hasBlockingErrors ? 'mods-issues-box mods-issues-error' : 'mods-issues-box mods-issues-warn'}>
<div className="mods-issues-title">
{state.hasBlockingErrors
? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length })
: t('mods.issuesTitle', { count: state.issues.length })}
</div>
<ul>
{state.issues.map((issue, idx) => (
<li key={`${issue.modId}-${issue.kind}-${idx}`} className={`mods-issue-${issue.severity}`}>
<span className="mods-issue-tag">{t(`mods.severity.${issue.severity}`)}</span>
<strong>{issue.modId}</strong>: {issue.detail}
</li>
))}
</ul>
</div>
)}
{visibleMods.length === 0 ? (
<div className="mods-empty">
<p className="lead">{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}</p>
{state.mods.length === 0 && (
<>
<p className="mods-hint">{t('mods.emptyHint', { path: state.modsDir })}</p>
<button type="button" className="button button-primary" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
</>
)}
</div>
) : (
<div className="mods-list">
{visibleMods.map((mod) => {
const index = state.order.indexOf(mod.id);
const isEnabled = state.enabled[mod.id] === true;
const isExpanded = expandedId === mod.id;
const modIssues = issuesByMod.get(mod.id) ?? [];
return (
<ModCard
key={mod.id}
mod={mod}
index={index}
total={state.order.length}
enabled={isEnabled}
expanded={isExpanded}
disabled={disabled}
canDrag={canDrag}
language={i18n.language}
issues={modIssues}
onToggle={(next) => toggleMod(mod.id, next)}
onMove={(delta) => moveMod(mod.id, delta)}
onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)}
onDragStart={() => setDraggedId(mod.id)}
onDrop={(event) => handleDrop(mod.id, event)}
/>
);
})}
</div>
)}
</>
) : (
<>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.presets.heading')}</h3>
<p className="mods-hint">{t('mods.presets.description')}</p>
<form className="mods-preset-form" onSubmit={savePreset}>
<input
type="text"
className="input"
maxLength={80}
disabled={disabled}
placeholder={t('mods.presets.namePlaceholder')}
value={presetName}
onChange={(event) => setPresetName(event.target.value)}
/>
<button type="submit" className="button button-primary" disabled={disabled || !presetName.trim()}>
{t('mods.presets.saveCurrent')}
</button>
<button type="button" className="button" disabled={disabled} onClick={importPreset}>
{t('mods.presets.import')}
</button>
</form>
{state.presets.length === 0 ? (
<p className="mods-hint">{t('mods.presets.empty')}</p>
) : (
<div className="mods-preset-list">
{state.presets.map((preset) => {
const active = state.activePresetId === preset.id;
const count = Object.values(preset.enabled).filter(Boolean).length;
return (
<div key={preset.id} className={active ? 'mods-preset-item mods-preset-active' : 'mods-preset-item'}>
<div className="mods-preset-meta">
<div className="mods-preset-name">
{preset.name}
{active && <span className="mods-badge mods-badge-data">{t('mods.presets.activeTag')}</span>}
</div>
<div className="mods-preset-sub">
{t('mods.presets.summary', { count, total: preset.order.length })}
</div>
</div>
<div className="copy-list-actions">
<button
type="button"
className="button button-primary"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: preset.id }),
t('mods.presets.applied', { name: preset.name }),
)}
>
{t('mods.presets.apply')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: preset.name, overwriteId: preset.id }),
t('mods.presets.updated', { name: preset.name }),
)}
>
{t('mods.presets.overwrite')}
</button>
<button type="button" className="button" disabled={busy} onClick={() => exportPreset(preset.id)}>
{t('mods.presets.export')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(ipcInvoke('mods:deletePreset', { copyId: copy.id, presetId: preset.id }))}
>
{t('mods.presets.delete')}
</button>
</div>
</div>
);
})}
</div>
)}
</section>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.repo.heading')}</h3>
<p className="mods-hint">{t('mods.repo.description')}</p>
<Row
label={t('mods.repo.pathLabel')}
hint={state.isCustomModsDir ? t('mods.repo.customNote') : t('mods.repo.defaultNote')}
>
<code className="mods-path">{state.modsDir}</code>
</Row>
<div className="copy-list-actions" style={{ marginTop: 12 }}>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<button type="button" className="button" disabled={disabled} onClick={pickCustomFolder}>
{t('mods.repo.changeFolder')}
</button>
{state.isCustomModsDir && (
<button type="button" className="button" disabled={disabled} onClick={resetFolder}>
{t('mods.repo.resetDefault')}
</button>
)}
</div>
</section>
</>
)}
</Sheet>
);
}
interface ModCardProps {
readonly mod: ModListItem;
readonly index: number;
readonly total: number;
readonly enabled: boolean;
readonly expanded: boolean;
readonly disabled: boolean;
readonly canDrag: boolean;
readonly language: string;
readonly issues: readonly ModIssueView[];
readonly onToggle: (next: boolean) => void;
readonly onMove: (delta: -1 | 1) => void;
readonly onToggleExpand: () => void;
readonly onDragStart: () => void;
readonly onDrop: (event: DragEvent<HTMLDivElement>) => void;
}
function ModCard({
mod,
index,
total,
enabled,
expanded,
disabled,
canDrag,
language,
issues,
onToggle,
onMove,
onToggleExpand,
onDragStart,
onDrop,
}: ModCardProps) {
const { t } = useTranslation();
const displayName = localized(mod.name, language) || mod.id;
const description = localized(mod.description, language);
const errorCount = issues.filter((i) => i.severity === 'error').length;
const warnCount = issues.filter((i) => i.severity === 'warning').length;
return (
<div
className={`mods-card${enabled ? ' mods-card-enabled' : ''}`}
draggable={canDrag}
onDragStart={onDragStart}
onDragOver={(event) => { if (canDrag) event.preventDefault(); }}
onDrop={onDrop}
>
<div className="mods-card-row">
<span className="mods-order-num" title={t('mods.loadOrderHint')}>#{index + 1}</span>
<input
type="checkbox"
className="mods-checkbox"
checked={enabled}
disabled={disabled}
aria-label={displayName}
onChange={(event) => onToggle(event.target.checked)}
/>
<div className="mods-card-main" onClick={onToggleExpand}>
<div className="mods-card-title">
<span className="mods-name">{displayName}</span>
<span className="mods-version">v{mod.version}</span>
<span className="mods-author">· {mod.author}</span>
<div className="mods-badges">
{mod.badges.map((badge) => (
<span key={badge} className={`mods-badge mods-badge-${badge}`}>
{t(`mods.badges.${badge}`)}
</span>
))}
{errorCount > 0 && <span className="mods-badge mods-badge-error">{t('mods.errorCount', { count: errorCount })}</span>}
{warnCount > 0 && <span className="mods-badge mods-badge-warn">{t('mods.warnCount', { count: warnCount })}</span>}
</div>
</div>
{description && <div className="mods-card-desc">{description}</div>}
</div>
<div className="mods-card-actions">
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index <= 0}
title={t('mods.moveUp')}
onClick={() => onMove(-1)}
>
↑
</button>
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index < 0 || index >= total - 1}
title={t('mods.moveDown')}
onClick={() => onMove(1)}
>
↓
</button>
<button type="button" className="button" onClick={onToggleExpand}>
{expanded ? t('mods.hideDetails') : t('mods.showDetails')}
</button>
</div>
</div>
{expanded && (
<div className="mods-card-details">
<div className="mods-detail-grid">
<div><span>ID:</span> <code>{mod.id}</code></div>
<div><span>API:</span> <code>{mod.apiVersion}</code></div>
<div><span>{t('mods.details.folder')}:</span> <code>{mod.folderName}</code></div>
{mod.gameVersions.length > 0 && (
<div><span>{t('mods.details.gameVersions')}:</span> <code>{mod.gameVersions.join(', ')}</code></div>
)}
{mod.requires.length > 0 && (
<div><span>{t('mods.details.requires')}:</span> <code>{mod.requires.join(', ')}</code></div>
)}
{mod.conflicts.length > 0 && (
<div><span>{t('mods.details.conflicts')}:</span> <code>{mod.conflicts.join(', ')}</code></div>
)}
</div>
<div className="mods-detail-summary">
{mod.serverTuningFiles.length > 0 && (
<span>{t('mods.details.tuning', { count: mod.serverTuningFiles.length })}</span>
)}
{mod.hasServerScript && <span>{t('mods.details.serverScript')}</span>}
{mod.packOperations.length > 0 && (
<span>{t('mods.details.packOps', { count: mod.packOperations.length })}</span>
)}
{mod.hasClientAddon && (
<span>{t('mods.details.addon', { count: mod.addonFileCount })}</span>
)}
{mod.guiPatchCount > 0 && (
<span>{t('mods.details.guiPatches', { count: mod.guiPatchCount })}</span>
)}
{mod.exePatchCount > 0 && (
<span>{t('mods.details.exePatches', { count: mod.exePatchCount })}</span>
)}
{mod.clientFileCount > 0 && (
<span>{t('mods.details.companionFiles', { count: mod.clientFileCount })}</span>
)}
{mod.hasConfigBlkPatch && <span>{t('mods.details.configBlk')}</span>}
</div>
</div>
)}
</div>
);
}
@@ -1,9 +1,8 @@
/**
* The window's pages and the sections of those that have a section list in the side panel.
* Pages for later features (saves, tuning) join this list when they are built.
*/
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const;
export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number];
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const;
@@ -12,6 +11,9 @@ export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const;
export type TuningSection = (typeof TUNING_SECTIONS)[number];
export const MODS_SECTIONS = ['list', 'presets'] as const;
export type ModsSection = (typeof MODS_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number];
@@ -23,16 +25,25 @@ export interface Route {
readonly copies: CopySection;
readonly saves: SaveSection;
readonly tuning: TuningSection;
readonly mods: ModsSection;
readonly settings: SettingsSection;
}
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' };
export const START_ROUTE: Route = {
page: 'home',
saves: 'list',
tuning: 'rewards',
mods: 'list',
copies: 'list',
settings: 'general',
};
/** Where a link points: a page, and for pages with sections, which one. */
export type Destination =
| { readonly page: 'home' | 'about' }
| { readonly page: 'saves'; readonly section?: SaveSection }
| { readonly page: 'tuning'; readonly section?: TuningSection }
| { readonly page: 'mods'; readonly section?: ModsSection }
| { readonly page: 'copies'; readonly section?: CopySection }
| { readonly page: 'settings'; readonly section?: SettingsSection };
@@ -42,6 +53,8 @@ export function navigate(route: Route, to: Destination): Route {
return { ...route, page: 'saves', saves: to.section ?? route.saves };
case 'tuning':
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
case 'mods':
return { ...route, page: 'mods', mods: to.section ?? route.mods };
case 'copies':
return { ...route, page: 'copies', copies: to.section ?? route.copies };
case 'settings':
@@ -252,6 +252,11 @@
background: var(--red);
}
.button-compact {
font-size: 13px;
padding: 5px 12px;
}
.link {
font: inherit;
color: var(--white);
@@ -481,3 +486,245 @@
left: 100%;
}
}
/* ===== Modal dialog & Markdown content ===== */
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 40;
display: flex;
align-items: center;
justify-content: center;
padding: 28px;
background: rgba(7, 10, 12, 0.72);
}
.modal-dialog {
width: min(760px, 100%);
max-height: min(600px, 100%);
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--sheet);
border: 1px solid var(--line-strong);
border-radius: var(--radius);
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.65);
}
.modal-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 14px 12px 20px;
background: linear-gradient(180deg, #343a40, #2b3136);
border-bottom: 1px solid #000;
}
.modal-title {
margin: 0;
font: 500 18px var(--font-display);
color: var(--white);
letter-spacing: 0.02em;
}
.modal-close {
flex: none;
width: 28px;
height: 28px;
display: grid;
place-items: center;
padding: 0;
border: 0;
border-radius: var(--radius);
background: none;
color: var(--text-dim);
font-size: 20px;
line-height: 1;
cursor: pointer;
}
.modal-close:hover {
color: var(--white);
background: rgba(255, 255, 255, 0.1);
}
.modal-body {
flex: 1;
min-height: 0;
overflow: auto;
padding: 18px 22px 22px;
user-select: text;
}
.modal-foot {
display: flex;
justify-content: flex-end;
gap: 10px;
padding: 10px 20px;
border-top: 1px solid var(--line);
background: rgba(0, 0, 0, 0.17);
}
.markdown-body {
font-size: 13.5px;
line-height: 1.65;
color: var(--text);
overflow-wrap: anywhere;
}
.markdown-body > :first-child {
margin-top: 0;
}
.markdown-body > :last-child {
margin-bottom: 0;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
margin: 18px 0 8px;
font-family: var(--font-display);
font-weight: 500;
color: var(--white);
line-height: 1.3;
}
.markdown-body h1 {
font-size: 20px;
padding-bottom: 6px;
border-bottom: 1px solid var(--line);
}
.markdown-body h2 {
font-size: 17px;
padding-bottom: 5px;
border-bottom: 1px solid var(--line);
}
.markdown-body h3 {
font-size: 15px;
}
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
font-size: 14px;
color: var(--text);
}
.markdown-body p {
margin: 0 0 10px;
}
.markdown-body strong {
color: var(--white);
font-weight: 600;
}
.markdown-body ul,
.markdown-body ol {
margin: 6px 0 10px;
padding-left: 22px;
}
.markdown-body li {
margin: 4px 0;
}
.markdown-body li > ul,
.markdown-body li > ol {
margin: 4px 0;
}
.markdown-body li > p {
margin: 0 0 4px;
}
.markdown-body li > p:last-child {
margin-bottom: 0;
}
.markdown-body code {
padding: 1px 5px;
font-family: var(--font-mono);
font-size: 12.5px;
color: #e6eff2;
background: rgba(0, 0, 0, 0.34);
border: 1px solid var(--line-soft);
border-radius: 2px;
}
.markdown-body pre {
margin: 10px 0;
padding: 10px 12px;
overflow: auto;
background: rgba(0, 0, 0, 0.38);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.markdown-body pre code {
padding: 0;
background: none;
border: 0;
font-size: 12.5px;
line-height: 1.5;
}
.markdown-body blockquote {
margin: 10px 0;
padding: 6px 12px;
color: var(--text-dim);
background: rgba(255, 255, 255, 0.03);
border-left: 3px solid var(--line-strong);
}
.markdown-body hr {
margin: 16px 0;
border: 0;
border-top: 1px solid var(--line);
}
.markdown-body a {
color: #7feaf2;
text-decoration: none;
border-bottom: 1px solid rgba(127, 234, 242, 0.35);
}
.markdown-body a:hover {
color: var(--white);
border-bottom-color: var(--white);
}
.markdown-table-wrap {
margin: 10px 0;
overflow-x: auto;
}
.markdown-body table {
width: 100%;
border-collapse: collapse;
font-size: 12.5px;
}
.markdown-body th,
.markdown-body td {
padding: 6px 10px;
border: 1px solid var(--line);
text-align: left;
}
.markdown-body th {
color: var(--white);
background: rgba(255, 255, 255, 0.05);
}
.markdown-task {
margin-right: 6px;
vertical-align: middle;
}
+400 -3
View File
@@ -344,9 +344,12 @@
}
/* ===== About ===== */
.update-notes {
white-space: pre-line;
overflow-wrap: anywhere;
.update-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-top: 10px;
}
.about-head {
@@ -435,3 +438,397 @@
.about-card .notice .button {
margin-top: 8px;
}
/* ===== Mods ===== */
.mods-aside {
display: inline-flex;
align-items: center;
gap: 10px;
}
.mods-exp-chip {
position: relative;
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 7px;
font-size: 11.5px;
line-height: 1.3;
color: rgba(255, 227, 163, 0.9);
background: rgba(214, 158, 46, 0.14);
border: 1px solid rgba(214, 158, 46, 0.38);
border-radius: var(--radius);
cursor: help;
user-select: none;
}
.mods-exp-chip:hover,
.mods-exp-chip:focus-visible {
background: rgba(214, 158, 46, 0.22);
border-color: rgba(214, 158, 46, 0.6);
outline: none;
}
.mods-exp-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
font-size: 10px;
font-weight: 700;
font-style: normal;
border-radius: 50%;
border: 1px solid rgba(255, 227, 163, 0.55);
}
.mods-exp-popover {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 40;
width: 340px;
max-width: min(340px, 70vw);
display: flex;
flex-direction: column;
gap: 4px;
padding: 10px 12px;
font-size: 12px;
line-height: 1.5;
text-align: left;
white-space: normal;
color: rgba(255, 244, 218, 0.94);
background: rgba(16, 20, 24, 0.97);
border: 1px solid rgba(214, 158, 46, 0.5);
border-radius: var(--radius);
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
opacity: 0;
visibility: hidden;
pointer-events: none;
transform: translateY(-2px);
transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease;
}
.mods-exp-chip:hover .mods-exp-popover,
.mods-exp-chip:focus-visible .mods-exp-popover {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.mods-banner {
display: flex;
flex-direction: column;
gap: 3px;
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
line-height: 1.5;
border: 1px solid var(--line);
border-radius: var(--radius);
}
.mods-banner-warn {
background: rgba(206, 65, 55, 0.16);
border-color: rgba(206, 65, 55, 0.5);
color: #ffd7d4;
}
.mods-banner-ok {
background: rgba(68, 170, 102, 0.16);
border-color: rgba(68, 170, 102, 0.5);
color: #d7ffe4;
}
.mods-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.mods-search {
flex: 1 1 180px;
min-width: 140px;
}
.mods-preset-select {
max-width: 210px;
}
.mods-issues-box {
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
border-radius: var(--radius);
border: 1px solid var(--line);
}
.mods-issues-error {
background: rgba(206, 65, 55, 0.15);
border-color: rgba(206, 65, 55, 0.55);
}
.mods-issues-warn {
background: rgba(214, 158, 46, 0.13);
border-color: rgba(214, 158, 46, 0.45);
}
.mods-issues-title {
font-weight: 600;
margin-bottom: 6px;
}
.mods-issues-box ul {
margin: 0;
padding-left: 18px;
display: flex;
flex-direction: column;
gap: 4px;
}
.mods-issue-tag {
display: inline-block;
margin-right: 6px;
padding: 1px 5px;
font-size: 11px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.12);
}
.mods-empty {
padding: 20px 14px;
text-align: center;
border: 1px dashed var(--line);
border-radius: var(--radius);
}
.mods-hint {
font-size: 12.5px;
color: var(--text-dim);
line-height: 1.5;
margin: 6px 0 12px;
}
.mods-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-card {
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
transition: border-color 120ms ease;
}
.mods-card-enabled {
border-left: 3px solid var(--red);
background: rgba(18, 24, 29, 0.78);
}
.mods-card-row {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
}
.mods-order-num {
min-width: 26px;
font-size: 12px;
color: var(--text-dim);
text-align: right;
cursor: grab;
}
.mods-checkbox {
width: 16px;
height: 16px;
flex: none;
cursor: pointer;
}
.mods-card-main {
flex: 1;
min-width: 0;
cursor: pointer;
}
.mods-card-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.mods-name {
font-weight: 600;
color: var(--white);
}
.mods-version,
.mods-author {
font-size: 12px;
color: var(--text-dim);
}
.mods-card-desc {
margin-top: 3px;
font-size: 12px;
color: var(--text-dim);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mods-badges {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
}
.mods-badge {
padding: 1px 6px;
font-size: 11px;
border-radius: 2px;
border: 1px solid rgba(255, 255, 255, 0.16);
}
.mods-badge-data {
background: rgba(88, 166, 255, 0.16);
color: #b7d7ff;
}
.mods-badge-gui {
background: rgba(163, 113, 247, 0.18);
color: #dec8ff;
}
.mods-badge-script {
background: rgba(214, 158, 46, 0.22);
color: #ffe3a3;
}
.mods-badge-exe {
background: rgba(206, 65, 55, 0.28);
color: #ffc2be;
border-color: rgba(206, 65, 55, 0.55);
}
.mods-badge-error {
background: rgba(206, 65, 55, 0.35);
color: #ffd5d2;
}
.mods-badge-warn {
background: rgba(214, 158, 46, 0.25);
color: #ffe8b3;
}
.mods-card-actions {
display: flex;
align-items: center;
gap: 4px;
flex: none;
}
.mods-move-btn {
min-width: 28px;
padding: 4px 6px;
}
.mods-card-details {
padding: 10px 12px 12px 48px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--text-dim);
}
.mods-detail-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 4px 12px;
margin-bottom: 8px;
}
.mods-detail-summary {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.mods-detail-summary span {
padding: 2px 7px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.85);
}
.mods-section {
margin-bottom: 22px;
}
.mods-subheading {
margin: 0 0 4px;
font: 600 15px var(--font-display);
color: var(--white);
}
.mods-preset-form {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 10px 0 14px;
}
.mods-preset-form .input {
flex: 1 1 200px;
}
.mods-preset-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-preset-item {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
}
.mods-preset-active {
border-left: 3px solid var(--red);
}
.mods-preset-meta {
min-width: 0;
}
.mods-preset-name {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: var(--white);
}
.mods-preset-sub {
font-size: 12px;
color: var(--text-dim);
margin-top: 2px;
}
.mods-path {
font-size: 12px;
word-break: break-all;
}
+9
View File
@@ -24,6 +24,11 @@ export const APP_ERROR_CODES = [
'diagnostics_export_failed',
'copy_not_found',
'tuning_invalid',
'mods_read_only',
'mods_write_failed',
'mods_preset_invalid',
'mods_blocking_issues',
'mods_folder_invalid',
'save_not_found',
'save_archive_invalid',
'save_official_invalid',
@@ -40,6 +45,8 @@ export const APP_ERROR_CODES = [
'maintenance_busy',
'maintenance_location',
'maintenance_no_update',
'maintenance_source_invalid',
'maintenance_source_overlap',
'maintenance_cancelled',
'maintenance_failed',
'maintenance_source_changed',
@@ -89,6 +96,8 @@ export const APP_ERROR_CODES = [
'missing_features_not_accepted',
/** Working out which patches fit failed; the details are in the log. */
'patch_check_failed',
/** The packaged launcher itself sits inside the selected stock War Thunder folder. */
'launcher_inside_source',
/** Copying the game failed; what was copied has been removed. */
'copy_failed',
'hardlink_unavailable',
+2
View File
@@ -16,6 +16,8 @@ export const IPC_CHANNEL_PREFIXES = [
'copies:',
/** Settings shared by the saves of a game copy. */
'tuning:',
/** Additive mods repository, per-copy ordering/toggles, and presets. */
'mods:',
/** Local account and save management. */
'saves:',
/** Starting and stopping the active copy. */
+45
View File
@@ -17,6 +17,7 @@ import {
} from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
import { ModsStateViewSchema } from '../schemas/mods.ts';
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
@@ -262,6 +263,50 @@ export const ipcContract = {
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
output: TuningViewSchema,
},
'mods:getState': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:setEnabled': {
input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }),
output: ModsStateViewSchema,
},
'mods:setOrder': {
input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }),
output: ModsStateViewSchema,
},
'mods:autoSort': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:savePreset': {
input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }),
output: ModsStateViewSchema,
},
'mods:applyPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:deletePreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:exportPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: z.object({ path: z.string().nullable() }),
},
'mods:importPreset': {
input: z.object({ copyId: CopyIdSchema }),
output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }),
},
'mods:openFolder': {
input: z.void(),
output: z.void(),
},
'mods:setFolder': {
input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }),
output: ModsStateViewSchema,
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
+1 -1
View File
@@ -150,7 +150,7 @@ export type InstallProgress = z.output<typeof InstallProgressSchema>;
export const InstallRecordSchema = z.object({
id: CopyIdSchema,
name: CopyNameSchema,
/** Recorded only for a separate source copied during installation. */
/** Separate online installation used as the read-only update source. */
sourcePath: z.string().min(1).nullable(),
method: z.enum(INSTALL_METHODS),
copyPath: z.string(),
@@ -1,11 +1,12 @@
import { z } from 'zod';
import { CopyIdSchema } from './install.ts';
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam']);
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam', 'set-source']);
export const MaintenanceRequestSchema = z.object({
id: CopyIdSchema,
operation: MaintenanceOperationSchema,
deleteData: z.boolean().default(false),
sourcePath: z.string().min(1).optional(),
steamLocations: z.object({
copyPath: z.string().min(1),
dataPath: z.string().min(1),
+87
View File
@@ -0,0 +1,87 @@
import { z } from 'zod';
export const ModRiskBadgeSchema = z.enum(['data', 'gui', 'script', 'exe']);
export const ModIssueSeveritySchema = z.enum(['error', 'warning', 'info']);
export const LocalizedTextSchema = z.union([z.string(), z.record(z.string(), z.string())]);
export const ModPackOperationSchema = z.object({
pack: z.string(),
targetPath: z.string(),
action: z.enum(['blk-patch', 'csv-patch', 'file']),
sourceRelativePath: z.string(),
});
export const ModListItemSchema = z.object({
id: z.string(),
folderName: z.string(),
rootDir: z.string(),
name: LocalizedTextSchema,
description: LocalizedTextSchema.optional(),
version: z.string(),
author: z.string(),
apiVersion: z.string(),
gameVersions: z.array(z.string()),
requires: z.array(z.string()),
conflicts: z.array(z.string()),
loadAfter: z.array(z.string()),
loadBefore: z.array(z.string()),
badges: z.array(ModRiskBadgeSchema),
hasServerScript: z.boolean(),
serverTuningFiles: z.array(z.string()),
packOperations: z.array(ModPackOperationSchema),
guiPatchCount: z.number().int().nonnegative(),
exePatchCount: z.number().int().nonnegative(),
hasClientAddon: z.boolean(),
addonFileCount: z.number().int().nonnegative(),
clientFileCount: z.number().int().nonnegative(),
hasConfigBlkPatch: z.boolean(),
});
export const ModDiscoveryErrorSchema = z.object({
folderName: z.string(),
rootDir: z.string(),
reason: z.string(),
});
export const ModIssueSchema = z.object({
severity: ModIssueSeveritySchema,
kind: z.string(),
modId: z.string(),
otherModId: z.string().optional(),
detail: z.string(),
});
export const ModPresetSchema = z.object({
id: z.string().min(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
updatedAt: z.string(),
});
export const ModsStateViewSchema = z.object({
modsDir: z.string(),
defaultModsDir: z.string(),
isCustomModsDir: z.boolean(),
apiVersion: z.string(),
mods: z.array(ModListItemSchema),
discoveryErrors: z.array(ModDiscoveryErrorSchema),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
activePresetId: z.string().nullable(),
presets: z.array(ModPresetSchema),
issues: z.array(ModIssueSchema),
hasBlockingErrors: z.boolean(),
});
export const ModPresetTransferSchema = z.object({
format: z.literal(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
});
export type ModListItem = z.output<typeof ModListItemSchema>;
export type ModPresetView = z.output<typeof ModPresetSchema>;
export type ModIssueView = z.output<typeof ModIssueSchema>;
export type ModsStateView = z.output<typeof ModsStateViewSchema>;
@@ -37,6 +37,8 @@ export const SettingsSchema = z.object({
developerMode: z.boolean().default(true),
labStockPath: LabPathSchema.default(null),
labDataPath: LabPathSchema.default(null),
/** Custom global mods repository directory; null uses `<userData>/mods`. */
modsFolder: LabPathSchema.default(null),
});
export type Settings = z.output<typeof SettingsSchema>;
@@ -60,6 +62,7 @@ export const SettingsPatchSchema = z.object({
developerMode: z.boolean().optional(),
labStockPath: LabPathSchema.optional(),
labDataPath: LabPathSchema.optional(),
modsFolder: LabPathSchema.optional(),
});
export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
+1
View File
@@ -9,6 +9,7 @@
"dependencies": {
"@wto/blk": "*",
"@wto/jsonc": "*",
"@wto/mods": "*",
"@wto/vromfs": "*"
}
}
+36 -3
View File
@@ -19,11 +19,13 @@ import {
isModeEligibleForLineup,
lineupMrank,
selectCustomBots,
type TankLineupWeights,
type CustomBotsPool,
} from './battle-ranks.ts';
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 {
@@ -86,6 +88,16 @@ export type MatchmakeOutcome =
| { readonly ok: true; readonly launch: BattleLaunchPlan }
| { readonly ok: false; readonly error: string };
export type MissionPoolFilter = (ctx: {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly MissionHeader[];
}) => readonly MissionHeader[];
export class BattleMatchmaker {
readonly #gameModes: GameModes;
readonly #vehicles: readonly CatalogueVehicle[];
@@ -94,6 +106,9 @@ export class BattleMatchmaker {
readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
readonly #tankWeights: TankLineupWeights | undefined;
readonly #tankLoadouts: ReadonlyMap<string, BotTankLoadout> | undefined;
readonly #filterMissions: MissionPoolFilter | undefined;
constructor(
gameModes: GameModes,
@@ -102,6 +117,9 @@ export class BattleMatchmaker {
tuning: BattleTuning,
spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights: TankLineupWeights | undefined,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
filterMissions?: MissionPoolFilter,
) {
this.#gameModes = gameModes;
this.#vehicles = vehicles;
@@ -110,6 +128,9 @@ export class BattleMatchmaker {
this.#tuning = tuning;
this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts;
this.#tankWeights = tankWeights;
this.#tankLoadouts = tankLoadouts;
this.#filterMissions = filterMissions;
}
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
@@ -133,8 +154,20 @@ export class BattleMatchmaker {
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
const missions = twoSidedMissionsOf(chosenMode, maxMrank);
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const filteredMissions = this.#filterMissions
? this.#filterMissions({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
minMrank,
maxMrank,
missions: rawMissions,
})
: rawMissions;
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({
vehicles: this.#vehicles,
@@ -156,7 +189,7 @@ export class BattleMatchmaker {
minMrank,
maxMrank,
limitPerType: this.#tuning.botPoolLimitPerType,
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts);
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts);
return {
ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
@@ -76,9 +76,11 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
if (plan.selectedSlot) {
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
// The native mission loader reads the AI limit at the top level, after its bots.blk default.
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
}
// MissionSettings::load (2.61.0.37 0x126b1f4..0x126b2e6) reads global config/bots.blk defaults
// first, then overrides aircraft and tank AI respawn limits from the mission root, not customBots.
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
setParam(settings, 'numTankBotRespawns', integer(plan.tankBotRespawns));
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
setParam(settings, 'useTankBots', flag(plan.useTankBots));
setParam(settings, 'useShipBots', flag(plan.useShipBots));
@@ -128,6 +130,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode));
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
@@ -138,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;
}
@@ -153,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<string>();
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 };
}
+39 -4
View File
@@ -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 {
@@ -31,6 +33,16 @@ export interface CustomBotsPool {
readonly ships: readonly BotPoolEntry[];
}
/** Offline tank pool weights by vehicle class (`tuning/ground-ai.jsonc` `lineupWeights`). */
export interface TankLineupWeights {
readonly spaa: number;
readonly lightTank: number;
readonly tankDestroyer: number;
readonly heavyTank: number;
readonly mediumTank: number;
readonly other: number;
}
export interface BotPoolQuery {
readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass;
@@ -117,14 +129,25 @@ function lineupVehicleMrank(
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
}
/**
* Without `tankWeights` every pool entry keeps the stock weight of 1.
*/
export function selectCustomBots(
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
vehicles: readonly CatalogueVehicle[],
query: BotPoolQuery,
aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights?: TankLineupWeights,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
): 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) : [],
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 };
@@ -138,6 +161,7 @@ function pickCategoryPool(
orderedCountries: readonly string[],
category: 'tank' | 'aircraft' | 'ship',
query: BotPoolQuery,
tankWeights?: TankLineupWeights,
): BotPoolEntry[] {
const countrySet = new Set(orderedCountries);
const eligible = vehicles.filter((vehicle) =>
@@ -161,13 +185,14 @@ function pickCategoryPool(
return mrank >= query.minMrank && mrank <= query.maxMrank;
});
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
return roundRobinByCountry(source, orderedCountries, query.limitPerType);
return roundRobinByCountry(source, orderedCountries, query.limitPerType, (vehicle) => tankPoolWeight(vehicle, tankWeights));
}
function roundRobinByCountry(
vehicles: readonly CatalogueVehicle[],
orderedCountries: readonly string[],
limit: number,
weightOf: (vehicle: CatalogueVehicle) => number,
): BotPoolEntry[] {
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
@@ -177,7 +202,7 @@ function roundRobinByCountry(
for (const country of orderedCountries) {
const vehicle = buckets.get(country)?.[index];
if (!vehicle) continue;
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 });
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: weightOf(vehicle) });
added = true;
if (out.length >= limit) break;
}
@@ -186,6 +211,16 @@ function roundRobinByCountry(
return out;
}
function tankPoolWeight(vehicle: CatalogueVehicle, weights: TankLineupWeights | undefined): number {
if (weights === undefined) return 1;
if (vehicle.unitClass === 'exp_SPAA') return weights.spaa;
if (vehicle.isLightTank) return weights.lightTank;
if (vehicle.unitClass === 'exp_tank_destroyer') return weights.tankDestroyer;
if (vehicle.unitClass === 'exp_heavy_tank') return weights.heavyTank;
if (vehicle.unitClass === 'exp_tank') return weights.mediumTank;
return weights.other;
}
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
if (type === 'Tank') return 'tank';
if (type === 'Aircraft') return 'aircraft';
+135
View File
@@ -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<string, BotTankLoadout> {
const result = new Map<string, BotTankLoadout>();
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<string>();
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');
}
+3 -1
View File
@@ -12,6 +12,7 @@ import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts';
import type { StoreCatalogue } from '../../store/store-catalogue.ts';
import type { TrainingCatalogue } from '../../training/training-completion.ts';
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
import type { CharActionHandler } from '../char-action.ts';
import { acceptEula } from './agreement-actions.ts';
@@ -94,6 +95,7 @@ export interface ActionDependencies {
readonly store: StoreCatalogue;
readonly inventory: InventoryCatalogue;
readonly trophies: TrophyCatalogue;
readonly training?: TrainingCatalogue;
readonly clans?: ClanActionDependencies;
readonly cloudSettings?: CloudSettingsStore;
readonly battle?: BattleActionDependencies;
@@ -118,7 +120,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
['cln_update', clientUpdateAction(deps.profiles, deps.accounts)],
['cln_update', clientUpdateAction(deps.profiles, deps.accounts, deps.training)],
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
@@ -3,6 +3,7 @@
* settles them into the player's save (battle-settlement.ts) and answers the updated profile,
* whose new `EULT_SESSION_RESULT` log carries the debriefing table.
*/
import type { BattleSettlementContext } from '@wto/mods';
import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
@@ -28,6 +29,7 @@ export interface BattleActionDependencies {
readonly streaks: BattleStreaks;
/** Units whose lives and events are not settled (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>;
readonly onAfterSettle?: (ctx: BattleSettlementContext) => void;
}
export interface FinishBattleContext {
@@ -62,6 +64,11 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
}
const updated = ctx.profiles.update(account.userId, (profile) => {
settleBattle(profile, report, session, settlementDeps);
battle.onAfterSettle?.({
userId: account.userId,
roomId: session.sessionId,
summary: { profile, report, session },
});
});
battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) };
@@ -2,19 +2,48 @@
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
* triggered by `save_online_single_job` when the client marks seen user logs as disabled
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
* auto-repair / auto-refill / auto-buy-modifications and map preferences. Answers the whole
* updated profile.
* auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from
* a stock training mission, the client also reports completion in `missionAwards` while
* `pveProgress` is empty. Answers the whole updated profile.
*/
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts';
import { boolField, stringField } from '../../game-data/datasets/blk-fields.ts';
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { ACCEPTED } from '../../research/rule-outcome.ts';
import type { TrainingCatalogue, TrainingCompletionReport } from '../../training/training-completion.ts';
import type { CharActionHandler } from '../char-action.ts';
import { ruleAction } from './rule-answer.ts';
export function clientUpdateAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => (profile) => {
applyClientProfileUpdate(profile, payload);
return ACCEPTED;
export function clientUpdateAction(
profiles: PlayerProfiles,
accounts: AccountStore,
training?: TrainingCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const completion = training ? readTrainingCompletion(payload) : undefined;
return (profile) => {
applyClientProfileUpdate(profile, payload);
if (completion && training) training.applyCompletion(profile, completion);
return ACCEPTED;
};
});
}
function readTrainingCompletion(request: BlkBlock): TrainingCompletionReport | undefined {
const awards = findBlock(request, 'missionAwards');
if (!awards
|| stringField(awards, 'gameModeName') !== 'training'
|| boolField(awards, 'success') !== true
|| boolField(awards, 'early') !== false
|| boolField(awards, 'onlineGame') !== false) return undefined;
const chapter = stringField(awards, 'chapterName');
const mission = stringField(awards, 'missionName');
const difficulty = findParam(awards, 'difficulty')?.value;
if (!chapter || !mission || difficulty?.type !== 'int'
|| (difficulty.value !== 0 && difficulty.value !== 1 && difficulty.value !== 2)) return undefined;
return { chapter, mission, difficulty: difficulty.value };
}
+53 -2
View File
@@ -13,6 +13,8 @@
* default lets the client continue and reveal what it asks for next.
*/
import { emptyBlock } from '@wto/blk';
import type { ModCharRequest, ModCharResponse } from '@wto/mods';
import type { ServerModRuntime } from '../mods/server-mod-runtime.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import type { CharActionHandler } from './char-action.ts';
import { toResponse, type CharAnswer } from './char-answers.ts';
@@ -23,17 +25,26 @@ const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
export class CharService implements Service {
readonly name = 'char';
readonly #actions: ReadonlyMap<string, CharActionHandler>;
readonly #modRuntime: ServerModRuntime | undefined;
constructor(actions: ReadonlyMap<string, CharActionHandler>) {
constructor(actions: ReadonlyMap<string, CharActionHandler>, modRuntime?: ServerModRuntime) {
this.#actions = actions;
this.#modRuntime = modRuntime;
}
accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
}
handle(request: ServiceRequest): ServiceResponse {
handle(request: ServiceRequest): ServiceResponse | Promise<ServiceResponse> {
const action = header(request, 'action') ?? '(no action header)';
if (this.#modRuntime?.hasCharOverride(action)) {
return this.#handleWithModOverride(action, request);
}
return this.#handleCore(action, request);
}
#handleCore(action: string, request: ServiceRequest): ServiceResponse {
const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action);
const answer: CharAnswer = handler
@@ -56,6 +67,46 @@ export class CharService implements Service {
},
};
}
async #handleWithModOverride(action: string, request: ServiceRequest): Promise<ServiceResponse> {
const headers: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(request.headers)) {
headers[key] = Array.isArray(value) ? value[0] : value;
}
const query: Record<string, string> = {};
for (const [key, value] of request.query.entries()) query[key] = value;
const modReq: ModCharRequest = {
action,
userId: header(request, 'uidhint') ?? '',
headers,
body: request.body,
query,
};
const result = await this.#modRuntime!.dispatchCharOverride(action, modReq, async (nextReq): Promise<ModCharResponse> => {
const forwarded: ServiceRequest = { ...request, body: nextReq.body };
const coreResp = this.#handleCore(nextReq.action, forwarded);
return {
status: coreResp.status,
...(coreResp.headers ? { headers: coreResp.headers } : {}),
body: coreResp.body ?? '',
};
});
const responseHeaders: Record<string, string> = { ...(result.headers ?? {}) };
if (result.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
responseHeaders['content-type'] = result.contentType;
}
return {
status: result.status ?? 200,
headers: responseHeaders,
body: result.body,
logNotes: {
summary: `${action} [mod handler] -> ${result.status ?? 200}`,
},
};
}
}
function header(request: ServiceRequest, name: string): string | undefined {
+23 -2
View File
@@ -7,24 +7,45 @@
* will start the service the same way. Stops on Ctrl+C.
*/
import { parseArgs } from 'node:util';
import { discoverMods, type DiscoveredMod } from '@wto/mods';
import { LOOPBACK, startServer } from './server.ts';
function resolveCliMods(modsDir: string | undefined, modIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !modIds || modIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
return modIds.map((id) => {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
return mod;
});
}
async function main(): Promise<number> {
const { values } = parseArgs({
options: {
game: { type: 'string' },
data: { type: 'string' },
port: { type: 'string' },
'mods-dir': { type: 'string' },
mod: { type: 'string', multiple: true },
},
});
const port = Number(values.port);
if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) {
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n>');
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n> [--mods-dir <dir> --mod <id>...]');
return 2;
}
let service;
try {
service = await startServer({ gameFolder: values.game, dataFolder: values.data, port, report: (line) => console.log(line) });
const mods = resolveCliMods(values['mods-dir'], values.mod);
service = await startServer({
gameFolder: values.game,
dataFolder: values.data,
port,
report: (line) => console.log(line),
...(mods.length > 0 ? { mods } : {}),
});
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error));
@@ -41,9 +41,13 @@ interface AirfieldLayoutData {
readonly airfieldLayoutProblem?: string;
}
export type GroundBattleMode = 'bttl' | 'conq' | 'dom';
export interface MissionHeader extends AirfieldLayoutData {
readonly name: string;
readonly path: string;
/** Ground mission tactical layout derived from mislist category (or suffix fallback for events). */
readonly groundMode?: GroundBattleMode;
readonly level?: string;
readonly type?: string;
readonly environment?: string;
@@ -72,7 +76,7 @@ export interface MultiplayerMissions {
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions',
version: 4,
version: 5,
extract(source: DatasetSource): MultiplayerMissions {
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
@@ -82,6 +86,7 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
missions: stringList(block, 'm'),
}));
const groundModeByMission = indexGroundModes(categories);
const paths = source.listFiles('mis.vromfs.bin');
const pathByName = missionPathsByLowerName(paths);
const knownPaths = new Set(paths);
@@ -94,12 +99,34 @@ export const multiplayerMissions: Dataset<MultiplayerMissions> = {
const document = source.readBlk('mis.vromfs.bin', path);
const airfields = path.startsWith(AIR_HISTORICAL_MISSION_FOLDER)
? readAirfieldLayouts(source, document, knownPaths, airfieldsByPath) : { airfieldLayouts: [] };
missions[name] = readHeader(name, path, document, airfields);
const groundMode = groundModeByMission.get(name) ?? groundModeFromName(name);
missions[name] = readHeader(name, path, document, airfields, groundMode);
}
return { categories, missions };
},
};
function indexGroundModes(categories: readonly MissionCategory[]): Map<string, GroundBattleMode> {
const byName = new Map<string, GroundBattleMode>();
for (const category of categories) {
const mode: GroundBattleMode | undefined =
category.name === 'air_ground_Bttl' ? 'bttl'
: category.name === 'air_ground_Conq' ? 'conq'
: category.name === 'air_ground_Dom' ? 'dom'
: undefined;
if (!mode) continue;
for (const name of category.missions) if (!byName.has(name)) byName.set(name, mode);
}
return byName;
}
function groundModeFromName(name: string): GroundBattleMode | undefined {
if (/_Bttl\d*$/i.test(name)) return 'bttl';
if (/_Conq\d*$/i.test(name)) return 'conq';
if (/_Dom\d*$/i.test(name)) return 'dom';
return undefined;
}
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
const byName = new Map<string, string>();
const repeated = new Set<string>();
@@ -114,11 +141,12 @@ function missionPathsByLowerName(paths: readonly string[]): Map<string, string>
}
function readHeader(
name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData,
name: string, path: string, document: BlkBlock, airfields: AirfieldLayoutData, groundMode?: GroundBattleMode,
): MissionHeader {
const settings = blockAt(document, 'mission_settings');
const mission = blockAt(settings, 'mission');
const optional = {
groundMode,
level: stringField(mission, 'level'),
type: stringField(mission, 'type'),
environment: stringField(mission, 'environment'),
@@ -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<Record<string, TankAmmoProfile>>;
interface GlobalModInfo {
readonly bulletMod?: string;
readonly requires: readonly string[];
}
interface WeaponBulletMeta {
readonly bulletType: string;
readonly speedMps: number;
readonly pen500Mm: number;
}
export const tankBotAmmo: Dataset<TankBotAmmoData> = {
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<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>();
const out: Record<string, TankAmmoProfile> = {};
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<string, GlobalModInfo> {
const mods = findBlock(root, 'modifications');
const map = new Map<string, GlobalModInfo>();
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<string>,
weaponCache: Map<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
globalMods: ReadonlyMap<string, GlobalModInfo>,
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<string, { isBelt: boolean; defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> }>,
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<string, WeaponBulletMeta>();
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<string, GlobalModInfo>,
weaponMeta: { defaultBullet?: WeaponBulletMeta; sets: Map<string, WeaponBulletMeta> },
): 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<string, readonly string[]>();
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<string, readonly string[]>,
globalMods: ReadonlyMap<string, GlobalModInfo>,
): string[] {
const seen = new Set<string>();
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;
}
@@ -0,0 +1,117 @@
/**
* Dataset: stock training missions and their first-completion rewards from char.vromfs.bin:
* - config/mislist.blk ("training" block): chapter/mission full names accepted for progress;
* - config/pve_awards.blk ("training" block): per-mission decal, shared first-completion unlock,
* and per-difficulty Silver Lions rewards (`wpEarnedWinDiff0..2`);
* - config/unlocks.blk: decal unlock verification and `oneTimeAwardUnlock` Golden Eagles amount
* and mutually exclusive `char_unlocked` conditions.
*/
import { findParam, type BlkBlock } from '@wto/blk';
import { blockAt, boolField, stringField, stringList } from './blk-fields.ts';
import type { Dataset, DatasetSource } from './dataset.ts';
const CHAR_PACK = 'char.vromfs.bin';
const MISLIST = 'config/mislist.blk';
const PVE_AWARDS = 'config/pve_awards.blk';
const UNLOCKS = 'config/unlocks.blk';
const TRAINING_SECTION = 'training';
export interface TrainingFirstCompletionAward {
readonly id: string;
readonly goldenEagles: number;
readonly blockedBy: readonly string[];
}
export interface TrainingMissionEntry {
readonly fullName: string;
readonly decal?: string;
readonly firstCompletion?: TrainingFirstCompletionAward;
/** First-win Silver Lions rewards (`wpEarnedWinDiff0..2`) for arcade, realistic, simulator. */
readonly silverLionsByDifficulty: readonly [number, number, number];
}
export interface TrainingMissionsData {
readonly missions: readonly TrainingMissionEntry[];
}
export const trainingMissions: Dataset<TrainingMissionsData> = {
id: 'training-missions',
version: 1,
extract(source: DatasetSource): TrainingMissionsData {
const misSection = blockAt(source.readBlk(CHAR_PACK, MISLIST), TRAINING_SECTION);
if (!misSection) throw new Error(`${MISLIST} has no "${TRAINING_SECTION}" block`);
const awardSection = blockAt(source.readBlk(CHAR_PACK, PVE_AWARDS), TRAINING_SECTION);
if (!awardSection) throw new Error(`${PVE_AWARDS} has no "${TRAINING_SECTION}" block`);
const awardsByMission = new Map<string, BlkBlock>(awardSection.blocks.map((entry) => [entry.name, entry]));
const unlocksById = new Map<string, BlkBlock>();
for (const entry of source.readBlk(CHAR_PACK, UNLOCKS).blocks) {
const id = stringField(entry, 'id');
if (id) unlocksById.set(id, entry);
}
const seen = new Set<string>();
const missions: TrainingMissionEntry[] = [];
for (const chapter of misSection.blocks) {
for (const mission of stringList(chapter, 'm')) {
const fullName = `${chapter.name}/${mission}`;
if (seen.has(fullName)) continue;
seen.add(fullName);
missions.push(buildMissionEntry(fullName, mission, awardsByMission.get(mission), unlocksById));
}
}
return { missions };
},
};
function buildMissionEntry(
fullName: string,
mission: string,
award: BlkBlock | undefined,
unlocks: ReadonlyMap<string, BlkBlock>,
): TrainingMissionEntry {
const decalId = stringField(award, 'decal');
const decal = decalId && stringField(unlocks.get(decalId), 'type') === 'decal' ? decalId : undefined;
const firstCompletion = award ? readFirstCompletionAward(award, mission, unlocks) : undefined;
return {
fullName,
...(decal ? { decal } : {}),
...(firstCompletion ? { firstCompletion } : {}),
silverLionsByDifficulty: [
readWinSilverLions(award, 0),
readWinSilverLions(award, 1),
readWinSilverLions(award, 2),
],
};
}
function readFirstCompletionAward(
award: BlkBlock,
mission: string,
unlocks: ReadonlyMap<string, BlkBlock>,
): TrainingFirstCompletionAward | undefined {
const id = stringField(award, 'oneTimeAwardUnlock');
if (!id) return undefined;
const unlock = unlocks.get(id);
if (stringField(unlock, 'type') !== 'award') return undefined;
const amount = unlock && findParam(unlock, 'amount_gold')?.value;
const mode = blockAt(unlock, 'mode');
if (amount?.type !== 'int' || amount.value <= 0
|| stringField(mode, 'type') !== 'char_mission_list'
|| !stringList(mode, 'name').includes(mission)) return undefined;
const blocked = mode?.blocks.flatMap((condition) =>
condition.name === 'condition'
&& stringField(condition, 'type') === 'char_unlocked'
&& boolField(condition, 'positive') === false
? stringList(condition, 'unlock')
: []) ?? [];
const hideIfEarned = stringField(award, 'hideOneTimeAwardIfUnlockIsOpen');
if (hideIfEarned) blocked.push(hideIfEarned);
return { id, goldenEagles: amount.value, blockedBy: [...new Set(blocked)] };
}
function readWinSilverLions(award: BlkBlock | undefined, difficulty: 0 | 1 | 2): number {
const value = award && findParam(award, `wpEarnedWinDiff${difficulty}`)?.value;
return value?.type === 'int' && value.value > 0 ? value.value : 0;
}
@@ -27,11 +27,14 @@ import type { Dataset } from './dataset.ts';
import { shopEntriesByName } from './shop-tree.ts';
const VEHICLE_ECONOMY = 'config/wpcost.blk';
const UNIT_TAGS = 'config/unittags.blk';
export interface CatalogueVehicle {
readonly name: string;
readonly country: string;
readonly unitClass: string;
/** True when config/unittags.blk tags the vehicle with type_light_tank. */
readonly isLightTank?: boolean;
readonly rank: number;
/** wpcost.blk reqAir; absent when empty or missing. */
readonly requires?: string;
@@ -70,15 +73,27 @@ export interface CatalogueVehicle {
export const vehicleCatalogue: Dataset<readonly CatalogueVehicle[]> = {
id: 'vehicle-catalogue',
version: 6,
version: 7,
extract: (source) => {
const shopEntries = shopEntriesByName(source);
const treeOrder = new Map([...shopEntries.keys()].map((name, index) => [name, index]));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1));
const lightTanks = lightTankNames(source.readBlk('char.vromfs.bin', UNIT_TAGS));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) =>
catalogueVehicle(vehicle, shopEntries.get(vehicle.name), treeOrder.get(vehicle.name) ?? -1, lightTanks.has(vehicle.name)),
);
},
};
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number): CatalogueVehicle {
function lightTankNames(unitTagsRoot: BlkBlock): ReadonlySet<string> {
const names = new Set<string>();
for (const unit of unitTagsRoot.blocks) {
const tags = unit.blocks.find((block) => block.name === 'tags');
if (tags && boolField(tags, 'type_light_tank') === true) names.add(unit.name);
}
return names;
}
function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, treeOrder: number, isLightTank: boolean): CatalogueVehicle {
const requires = stringField(vehicle, 'reqAir');
const researchType = stringField(vehicle, 'researchType');
const requiredUnlock = stringField(shopEntry, 'reqUnlock');
@@ -90,6 +105,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined, tr
name: vehicle.name,
country: stringField(vehicle, 'country') ?? '',
unitClass: stringField(vehicle, 'unitClass') ?? '',
...(isLightTank ? { isLightTank: true } : {}),
rank: numberField(vehicle, 'rank') ?? 0,
...(requires ? { requires } : {}),
researchPoints: numberField(vehicle, 'reqExp') ?? 0,
+1
View File
@@ -11,5 +11,6 @@ export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
export { loadGroundAiTuning, type GroundAiTuning } from './tuning/ground-ai-tuning.ts';
export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
@@ -11,6 +11,7 @@
* "strike": time:f the local player's nuclear bomb exploded
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
*/
import type { BattleLiveFactContext } from '@wto/mods';
import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { BattleStreaks } from '../battle/battle-streaks.ts';
@@ -23,6 +24,7 @@ export interface BattleLiveDependencies {
readonly streaks: BattleStreaks;
/** Units whose lives and events earn no awards (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>;
readonly onLiveFact?: (ctx: BattleLiveFactContext) => void;
}
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
@@ -34,6 +36,11 @@ export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string,
if (!session || session.settled) return { streaks: [] };
const log = deps.liveLogs.of(session.sessionId);
if (!recordFact(log, p)) return { streaks: [] };
deps.onLiveFact?.({
userId: userId!,
roomId: session.sessionId,
fact: p as Record<string, unknown>,
});
const awarded = deps.streaks.evaluate({
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
feed: log.feed,
@@ -5,6 +5,7 @@
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
import type { BattleMatchmakeContext } from '@wto/mods';
import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts';
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
@@ -24,6 +25,7 @@ export interface BattleQueueDependencies {
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
readonly onBeforeMatchmake?: (ctx: BattleMatchmakeContext) => void;
}
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
@@ -85,6 +87,11 @@ function handleEnqueue(
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
const idInCountry = playerEntry.selectedSlot;
const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry);
deps.onBeforeMatchmake?.({
userId,
eventName: modes[0]!.declaration.name,
request: params as Record<string, unknown>,
});
const outcome = deps.matchmaker.enqueue({
userId,
mode: modes[0]!,
@@ -21,7 +21,7 @@ import { moduleResearchTarget, setModuleResearchTarget } from '../profile/profil
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts';
import { currentModuleStatus } from './module-state.ts';
import { ModuleStatus } from './module-status.ts';
import { ModuleStatus, vehicleModuleState } from './module-status.ts';
export interface ModificationOrder {
readonly vehicle: string;
@@ -48,8 +48,9 @@ export function buyModification(profile: BlkBlock, catalogue: EquipmentCatalogue
export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome {
const equipment = catalogue.vehicle(vehicle);
if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS');
const { statuses } = vehicleModuleState(profile, equipment);
const purchases = equipment.modifications.flatMap((modification) => {
const purchase = buyAllEntry(profile, vehicle, modification, catalogue, outright);
const purchase = buyAllEntry(profile, vehicle, modification, statuses.get(modification.name), outright);
return purchase ? [{ modification, purchase }] : [];
});
const price = purchases.reduce<Price>((sum, { purchase }) => ({
@@ -114,17 +115,24 @@ function outrightPurchase(profile: BlkBlock, vehicle: string, modification: Modi
/**
* One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost):
* skip what is at its maximum; with forceOpen every modification starts at its outright price
* (whatever its status); a buyable one (canBuyMod) with a non-zero price takes its own price
* instead, and is skipped altogether when counted or priced in golden eagles.
* (whatever its status); a buyable or researched one (canBuyMod || isModStatusResearched) with a
* non-zero price takes its own price instead, and is skipped altogether when counted or priced in
* golden eagles.
*/
function buyAllEntry(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, outright: boolean): Purchase | undefined {
function buyAllEntry(
profile: BlkBlock,
vehicle: string,
modification: ModificationFacts,
status: ModuleStatus | undefined,
outright: boolean,
): Purchase | undefined {
const record = modificationRecord(profile, vehicle, modification.name);
const maxAmount = Math.max(1, modification.maxCount);
if ((record?.count ?? 0) >= maxAmount) return undefined;
let purchase: Purchase | undefined;
const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0;
if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 };
const buyable = record !== undefined || currentModuleStatus(profile, catalogue, vehicle, modification.name) === ModuleStatus.CAN_BUY;
const buyable = record !== undefined || status === ModuleStatus.CAN_BUY || status === ModuleStatus.RESEARCHED;
if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) {
if (isCounted(modification) || modification.goldenEagles > 0) return undefined;
purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 };
+27 -3
View File
@@ -10,11 +10,12 @@ import { moduleResearchPoints } from '../profile/profile-module-research.ts';
import { countsForTier, isResearchable } from './equipment-catalogue.ts';
import type { ProfileEquipmentIndex } from './profile-equipment-index.ts';
/** shopItemConsts ES_ITEM_STATUS_*; the same values as the vehicle statuses. */
/** shopItemConsts ES_ITEM_STATUS_* (aces.exe 2.61.0.58 0x17e2894..0x17e294b); same values as VehicleStatus. */
export const ModuleStatus = {
LOCKED: 1,
CAN_RESEARCH: 2,
CAN_BUY: 8,
RESEARCHED: 0x40,
} as const;
export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus];
@@ -32,10 +33,11 @@ export function vehicleModuleState(
index?: ProfileEquipmentIndex,
): VehicleModuleState {
const openTier = openTierOf(profile, equipment, index);
const byName = new Map(equipment.modifications.map((mod) => [mod.name, mod]));
const statuses = new Map<string, ModuleStatus>();
for (const modification of equipment.modifications) {
if (isOwned(profile, equipment.vehicle, modification.name, index)) continue;
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, index));
statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, byName, index));
}
return { openTier, statuses };
}
@@ -80,16 +82,38 @@ function openTierOf(profile: BlkBlock, equipment: VehicleEquipment, index?: Prof
return tier;
}
function arePrerequisitesResearched(
profile: BlkBlock,
vehicle: string,
requires: readonly string[],
byName: ReadonlyMap<string, ModificationFacts>,
index?: ProfileEquipmentIndex,
): boolean {
return requires.every((required) => {
if (isOwned(profile, vehicle, required, index)) return true;
const mod = byName.get(required);
return mod !== undefined && isResearchable(mod) && isModuleResearched(profile, vehicle, mod, index);
});
}
function statusOf(
profile: BlkBlock,
vehicle: string,
modification: ModificationFacts,
openTier: number,
byName: ReadonlyMap<string, ModificationFacts>,
index?: ProfileEquipmentIndex,
): ModuleStatus {
if (isResearchable(modification)) {
if (modification.tier > openTier) return ModuleStatus.LOCKED;
return isModuleResearched(profile, vehicle, modification, index) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH;
if (isModuleResearched(profile, vehicle, modification, index)) {
return arePrerequisitesOwned(profile, vehicle, modification.requires, index)
? ModuleStatus.CAN_BUY
: ModuleStatus.RESEARCHED;
}
return arePrerequisitesResearched(profile, vehicle, modification.requires, byName, index)
? ModuleStatus.CAN_RESEARCH
: ModuleStatus.LOCKED;
}
return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED;
}
+82
View File
@@ -0,0 +1,82 @@
/**
* HTTP router service that exposes mod-registered routes under `/mods/<modId>/...`
* so mods can provide custom APIs or embedded-browser pages without touching core routes.
*/
import type { ModHttpHandler, ModHttpRequest } from '@wto/mods';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
export interface RegisteredModHttpRoute {
readonly modId: string;
/** Full normalized path prefix or exact path under `/mods/<modId>/...`. */
readonly pattern: string;
readonly isWildcard: boolean;
readonly prefix: string;
readonly handler: ModHttpHandler;
}
export class ModHttpService implements Service {
readonly name = 'mods-http';
readonly #routes: readonly RegisteredModHttpRoute[];
constructor(routes: readonly RegisteredModHttpRoute[]) {
this.#routes = routes;
}
accepts(request: ServiceRequest): boolean {
if (request.originalHost !== undefined) return false;
return this.#match(request.path) !== undefined;
}
async handle(request: ServiceRequest): Promise<ServiceResponse> {
const matched = this.#match(request.path);
if (!matched) {
return { status: 404, body: 'mod route not found' };
}
const headers: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(request.headers)) {
headers[key] = Array.isArray(value) ? value[0] : value;
}
const query: Record<string, string> = {};
for (const [key, value] of request.query.entries()) query[key] = value;
const modReq: ModHttpRequest = {
method: request.method,
path: request.path,
query,
headers,
body: request.body,
};
const answer = await matched.handler(modReq);
const responseHeaders: Record<string, string> = { ...(answer.headers ?? {}) };
if (answer.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
responseHeaders['content-type'] = answer.contentType;
}
return {
status: answer.status ?? 200,
headers: responseHeaders,
body: answer.body,
logNotes: { summary: `mod:${matched.modId} ${request.method} ${request.path}` },
};
}
#match(path: string): RegisteredModHttpRoute | undefined {
for (const route of this.#routes) {
if (route.isWildcard) {
if (path.startsWith(route.prefix)) return route;
} else if (path === route.pattern) {
return route;
}
}
return undefined;
}
}
export function buildModHttpRoute(modId: string, subPath: string, handler: ModHttpHandler): RegisteredModHttpRoute {
const cleaned = subPath.startsWith('/') ? subPath : `/${subPath}`;
const full = `/mods/${modId}${cleaned === '/' ? '' : cleaned}`;
if (full.endsWith('/*')) {
const prefix = full.slice(0, -1); // keeps trailing '/'
return { modId, pattern: full, isWildcard: true, prefix, handler };
}
return { modId, pattern: full, isWildcard: false, prefix: full, handler };
}
+55
View File
@@ -0,0 +1,55 @@
/**
* Isolated JSON storage for server mods:
* - per-player files under `<dataFolder>/saves/<userId>/mods/<safeModId>.json`
* - shared mod state under `<dataFolder>/mods-data/<safeModId>.json`
*
* Keeping mod state outside `profile.blk` guarantees uninstalling a mod never corrupts stock saves.
*/
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import type { ModPlayerStorage, ModStorageApi } from '@wto/mods';
import { writeFileAtomic } from '../storage/atomic-file.ts';
export function createModStorage(dataFolder: string, modId: string): ModStorageApi {
const safeMod = sanitizeSegment(modId);
return {
forPlayer(userId: string): ModPlayerStorage {
const safeUser = sanitizeSegment(userId);
const filePath = join(dataFolder, 'saves', safeUser, 'mods', `${safeMod}.json`);
return createJsonFileStorage(filePath);
},
shared(): ModPlayerStorage {
const filePath = join(dataFolder, 'mods-data', `${safeMod}.json`);
return createJsonFileStorage(filePath);
},
};
}
function createJsonFileStorage(filePath: string): ModPlayerStorage {
return {
read<T = unknown>(): T | undefined {
if (!existsSync(filePath)) return undefined;
try {
return JSON.parse(readFileSync(filePath, 'utf8')) as T;
} catch {
return undefined;
}
},
write(value: unknown): void {
writeFileAtomic(filePath, JSON.stringify(value, null, 2));
},
remove(): void {
try {
rmSync(filePath, { force: true });
} catch { /* ignore */ }
},
};
}
function sanitizeSegment(raw: string): string {
const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, '_');
if (!cleaned || cleaned === '.' || cleaned === '..') {
throw new Error(`invalid storage path segment "${raw}"`);
}
return cleaned;
}
+362
View File
@@ -0,0 +1,362 @@
/**
* Experimental server-side JS/TS mod runtime.
*
* Loads each enabled mod's server script entry (`.ts`, `.mjs`, or `.js` via Node 24's built-in
* TypeScript stripping and ESM dynamic import), injects an isolated `WtoServerModContext`, and
* coordinates lifecycle hooks, profile/battle hooks, char/matching wrappers, and `/mods/<id>/*`
* HTTP routes.
*/
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import type { BlkBlock } from '@wto/blk';
import {
MOD_API_VERSION,
type BattleFilterMissionsContext,
type BattleLiveFactContext,
type BattleMatchmakeContext,
type BattleMissionCandidate,
type BattleSettlementContext,
type DiscoveredMod,
type ModCharHandler,
type ModCharRequest,
type ModCharResponse,
type ModCharWrapper,
type ModHttpHandler,
type ModMatchingHandler,
type ModMatchingRequest,
type ModMatchingWrapper,
type ServerModCataloguesView,
type ServerModDatasetsView,
type WtoServerMod,
type WtoServerModContext,
} from '@wto/mods';
import type { MatchingRequestHandler, MatchingRequestTable } from '../matching/matching-requests.ts';
import { buildModHttpRoute, ModHttpService, type RegisteredModHttpRoute } from './mod-http-service.ts';
import { createModStorage } from './mod-storage.ts';
interface RuntimeInitOptions {
readonly mods: readonly DiscoveredMod[];
readonly gameFolder: string;
readonly dataFolder: string;
readonly port: number;
readonly report: (line: string) => void;
}
interface ScopedHandler<T> {
readonly modId: string;
readonly fn: T;
}
export class ServerModRuntime {
readonly #report: (line: string) => void;
readonly #loadedModIds: string[] = [];
readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise<void>>[] = [];
readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise<void>>[] = [];
readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise<void>>[] = [];
readonly #onServerClosing: ScopedHandler<() => void | Promise<void>>[] = [];
readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = [];
readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = [];
readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = [];
readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = [];
readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = [];
readonly #charHandlers = new Map<string, ScopedHandler<ModCharHandler>>();
readonly #charWrappers = new Map<string, ScopedHandler<ModCharWrapper>[]>();
readonly #matchingHandlers = new Map<string, ScopedHandler<ModMatchingHandler>>();
readonly #matchingWrappers = new Map<string, ScopedHandler<ModMatchingWrapper>[]>();
readonly #httpRoutes: RegisteredModHttpRoute[] = [];
private constructor(report: (line: string) => void) {
this.#report = report;
}
static async load(options: RuntimeInitOptions): Promise<ServerModRuntime> {
const runtime = new ServerModRuntime(options.report);
const scriptMods = options.mods.filter((mod) => mod.content.serverEntry !== undefined);
if (scriptMods.length === 0) return runtime;
const cacheBust = Date.now();
for (const mod of scriptMods) {
const entryRel = mod.content.serverEntry!;
const entryAbs = join(mod.rootDir, ...entryRel.split('/'));
const modId = mod.manifest.id;
const url = `${pathToFileURL(entryAbs).href}?wto_mod=${cacheBust}`;
let loadedModule: Record<string, unknown>;
try {
loadedModule = (await import(url)) as Record<string, unknown>;
} catch (error) {
throw new Error(
`Failed to load server mod "${modId}" (${entryRel}): ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
);
}
const modExport = resolveModExport(loadedModule);
if (!modExport) {
throw new Error(
`Server mod "${modId}" (${entryRel}) must export default { setup(ctx) { ... } } or named setup(ctx)`,
);
}
const ctx = runtime.#createContext(mod, options);
try {
await modExport.setup(ctx);
} catch (error) {
throw new Error(
`Server mod "${modId}" setup() failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`,
);
}
runtime.#loadedModIds.push(modId);
options.report(`mod ${modId}: server script loaded (${entryRel})`);
}
return runtime;
}
get loadedModIds(): readonly string[] {
return this.#loadedModIds;
}
async runDatasetsLoaded(view: ServerModDatasetsView): Promise<void> {
for (const { modId, fn } of this.#onDatasetsLoaded) {
try {
await fn(view);
} catch (error) {
throw new Error(`Server mod "${modId}" onDatasetsLoaded failed: ${formatError(error)}`);
}
}
}
async runCataloguesReady(view: ServerModCataloguesView): Promise<void> {
for (const { modId, fn } of this.#onCataloguesReady) {
try {
await fn(view);
} catch (error) {
throw new Error(`Server mod "${modId}" onCataloguesReady failed: ${formatError(error)}`);
}
}
}
async runServerListening(port: number): Promise<void> {
for (const { modId, fn } of this.#onServerListening) {
try {
await fn({ port });
} catch (error) {
this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`);
}
}
}
async runServerClosing(): Promise<void> {
for (const { modId, fn } of [...this.#onServerClosing].reverse()) {
try {
await fn();
} catch (error) {
this.#report(`[mod:${modId}] onServerClosing error: ${formatError(error)}`);
}
}
}
runProfileRefresh(profile: BlkBlock, userId: string): void {
for (const { modId, fn } of this.#onProfileRefresh) {
try {
fn(profile, userId);
} catch (error) {
this.#report(`[mod:${modId}] profile.onRefresh error: ${formatError(error)}`);
}
}
}
runBattleBeforeMatchmake(ctx: BattleMatchmakeContext): void {
for (const { modId, fn } of this.#onBeforeMatchmake) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onBeforeMatchmake error: ${formatError(error)}`);
}
}
}
runBattleFilterMissions<T extends BattleMissionCandidate>(
ctx: Omit<BattleFilterMissionsContext, 'missions'> & { readonly missions: readonly T[] },
): readonly T[] {
if (this.#onFilterMissions.length === 0) return ctx.missions;
let current: readonly T[] = ctx.missions;
for (const { modId, fn } of this.#onFilterMissions) {
try {
const next = fn({ ...ctx, missions: current });
if (Array.isArray(next)) {
const allowed = new Set(next.map((item) => item.name));
const filtered = current.filter((item) => allowed.has(item.name));
if (filtered.length > 0) {
current = filtered;
} else {
this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`);
}
}
} catch (error) {
this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`);
}
}
return current;
}
runBattleLiveFact(ctx: BattleLiveFactContext): void {
for (const { modId, fn } of this.#onLiveFact) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onLiveFact error: ${formatError(error)}`);
}
}
}
runBattleAfterSettle(ctx: BattleSettlementContext): void {
for (const { modId, fn } of this.#onAfterSettle) {
try {
fn(ctx);
} catch (error) {
this.#report(`[mod:${modId}] battle.onAfterSettle error: ${formatError(error)}`);
}
}
}
hasCharOverride(action: string): boolean {
return this.#charHandlers.has(action) || this.#charWrappers.has(action);
}
async dispatchCharOverride(
action: string,
request: ModCharRequest,
baseDispatch: (req: ModCharRequest) => Promise<ModCharResponse>,
): Promise<ModCharResponse> {
const custom = this.#charHandlers.get(action);
const terminal: (req: ModCharRequest) => Promise<ModCharResponse> = custom
? async (req) => await custom.fn(req)
: baseDispatch;
const wrappers = this.#charWrappers.get(action);
if (!wrappers || wrappers.length === 0) return terminal(request);
let chain = terminal;
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
const wrapper = wrappers[i]!.fn;
const next = chain;
chain = async (req) => await wrapper(req, next);
}
return chain(request);
}
applyMatchingRoutes(baseTable: MatchingRequestTable): MatchingRequestTable {
if (this.#matchingHandlers.size === 0 && this.#matchingWrappers.size === 0) {
return baseTable;
}
const merged = new Map<string, MatchingRequestHandler>(baseTable);
for (const [method, custom] of this.#matchingHandlers) {
merged.set(method, (request, session) => custom.fn({
method,
params: request.params,
userId: session.authenticatedUserId(),
}));
}
for (const [method, wrappers] of this.#matchingWrappers) {
const original = merged.get(method);
merged.set(method, (request, session) => {
const baseFn = (req: ModMatchingRequest): Record<string, unknown> => (
original ? original({ ...request, params: req.params }, session) : {}
);
let chain = baseFn;
for (let i = wrappers.length - 1; i >= 0; i -= 1) {
const wrap = wrappers[i]!.fn;
const next = chain;
chain = (req) => wrap(req, next);
}
return chain({
method,
params: request.params,
userId: session.authenticatedUserId(),
});
});
}
return merged;
}
httpService(): ModHttpService {
return new ModHttpService(this.#httpRoutes);
}
#createContext(mod: DiscoveredMod, options: RuntimeInitOptions): WtoServerModContext {
const modId = mod.manifest.id;
return {
apiVersion: MOD_API_VERSION,
manifest: mod.manifest,
modDir: mod.rootDir,
gameFolder: options.gameFolder,
dataFolder: options.dataFolder,
port: options.port,
logger: {
info: (message) => options.report(`[mod:${modId}] ${message}`),
warn: (message) => options.report(`[mod:${modId}] WARN: ${message}`),
error: (message) => options.report(`[mod:${modId}] ERROR: ${message}`),
},
storage: createModStorage(options.dataFolder, modId),
hooks: {
onDatasetsLoaded: (fn) => { this.#onDatasetsLoaded.push({ modId, fn }); },
onCataloguesReady: (fn) => { this.#onCataloguesReady.push({ modId, fn }); },
onServerListening: (fn) => { this.#onServerListening.push({ modId, fn }); },
onServerClosing: (fn) => { this.#onServerClosing.push({ modId, fn }); },
profile: {
onRefresh: (fn) => { this.#onProfileRefresh.push({ modId, fn }); },
},
battle: {
onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); },
onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); },
onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); },
onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); },
},
},
routes: {
char: {
register: (action, fn) => { this.#charHandlers.set(action, { modId, fn }); },
wrap: (action, fn) => {
const list = this.#charWrappers.get(action) ?? [];
list.push({ modId, fn });
this.#charWrappers.set(action, list);
},
},
matching: {
register: (method, fn) => { this.#matchingHandlers.set(method, { modId, fn }); },
wrap: (method, fn) => {
const list = this.#matchingWrappers.get(method) ?? [];
list.push({ modId, fn });
this.#matchingWrappers.set(method, list);
},
},
http: {
register: (subPath: string, handler: ModHttpHandler) => {
this.#httpRoutes.push(buildModHttpRoute(modId, subPath, handler));
},
},
},
};
}
}
function resolveModExport(mod: Record<string, unknown>): WtoServerMod | undefined {
const def = mod.default;
if (def && typeof def === 'object' && typeof (def as Record<string, unknown>).setup === 'function') {
return def as WtoServerMod;
}
if (typeof def === 'function') {
return { setup: def as WtoServerMod['setup'] };
}
if (typeof mod.setup === 'function') {
return { setup: mod.setup as WtoServerMod['setup'] };
}
return undefined;
}
function formatError(error: unknown): string {
return error instanceof Error ? error.stack ?? error.message : String(error);
}
@@ -17,12 +17,20 @@
* script function get_mission_progress (0x179c900 -> 0xebad60) looks up. It returns the
* highest difficulty completed (0, 1, 2), or 3 or more when there is none.
*/
import { ensureBlock, setParam, type BlkBlock } from '@wto/blk';
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const PVE_PROGRESS = 'pveProgress';
const MISSIONS = 'missions';
const DIFFICULTIES = [0, 1, 2] as const;
export function hasCompletedMissionDifficulty(profile: BlkBlock, fullMissionName: string, difficulty: 0 | 1 | 2): boolean {
const pve = findBlock(profile, PVE_PROGRESS);
const missions = pve && findBlock(pve, MISSIONS);
const mission = missions && findBlock(missions, fullMissionName);
const flag = mission && findParam(mission, `diff_${difficulty}`)?.value;
return flag?.type === 'bool' && flag.value;
}
/** Record the mission as completed on every difficulty up to and including `highest` (0, 1 or 2). */
export function recordMissionCompleted(profile: BlkBlock, fullMissionName: string, highest: 0 | 1 | 2): void {
const entry = ensureBlock(ensureBlock(ensureBlock(profile, PVE_PROGRESS), MISSIONS), fullMissionName);
+3
View File
@@ -5,6 +5,7 @@
* (with the modifications the mission support planes' presets need) and the free repair over time (repair/repair-over-time.ts) kept up to date and persisted on
* every read or write.
*/
import type { BlkBlock } from '@wto/blk';
import type { AccountStore } from './accounts/account-store.ts';
import type { ClanStore } from './clans/clan-store.ts';
import type { DatasetCache } from './game-data/datasets/dataset-cache.ts';
@@ -50,6 +51,7 @@ export function setUpProfiles(
tuning: Tuning,
sync?: ProfileSyncContext,
vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue),
onProfileRefresh?: (profile: BlkBlock, userId: string) => void,
): ProfileServices {
const startingContent: StartingContent = {
reserveVehicles: datasets.load(reserveVehicles),
@@ -70,6 +72,7 @@ export function setUpProfiles(
removeExpiredItems(profile, serverTimeNow());
repairVehiclesOverTime(profile, repair, serverTimeNow());
trimUserLogs(profile, tuning.limits.userLogsKept);
onProfileRefresh?.(profile, userId);
});
return { profiles, research, equipment, repair };
}
+168 -35
View File
@@ -1,14 +1,16 @@
/**
* Assemble the local server: data layer, save layer, rules,
* Assemble the local server: data layer, save layer, rules, experimental additive mod runtime,
* protocol-layer services, and the single loopback listening port.
*/
import type { Server } from 'node:net';
import type { DiscoveredMod, ServerModDatasetsView } from '@wto/mods';
import { AccountStore } from './accounts/account-store.ts';
import { RegistrationService } from './accounts/registration-service.ts';
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';
@@ -16,7 +18,7 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts';
import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts';
import { DecorShop } from './decor/decor-purchase.ts';
import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts';
import { battleEconomy } from './game-data/datasets/battle-economy.ts';
import { battleEconomy, type BattleEconomyData } from './game-data/datasets/battle-economy.ts';
import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts';
import { researchEfficiency } from './game-data/datasets/research-efficiency.ts';
import { ResearchEfficiency } from './research/research-efficiency.ts';
@@ -30,12 +32,14 @@ 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 } from './game-data/datasets/multiplayer-missions.ts';
import { multiplayerMissions, type MultiplayerMissions } from './game-data/datasets/multiplayer-missions.ts';
import { shopCountries } from './game-data/datasets/shop-countries.ts';
import { storeBundles } from './game-data/datasets/store-bundles.ts';
import { trainingMissions } from './game-data/datasets/training-missions.ts';
import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.ts';
import { unitNames } from './game-data/datasets/unit-names.ts';
import { unitNames, type UnitNamesMap } from './game-data/datasets/unit-names.ts';
import { unlockPrices } from './game-data/datasets/unlock-prices.ts';
import { vehicleCatalogue, type CatalogueVehicle } from './game-data/datasets/vehicle-catalogue.ts';
import { webIcons } from './game-data/datasets/web-icons.ts';
@@ -49,12 +53,14 @@ import { ItemCatalogue } from './items/item-catalogue.ts';
import { LoginService } from './login/login-service.ts';
import { matchingRequests } from './matching/matching-requests.ts';
import type { MatchingService } from './matching/matching-service.ts';
import { ServerModRuntime } from './mods/server-mod-runtime.ts';
import { setUpProfiles } from './profiles-setup.ts';
import { createPortListener } from './transport/port-listener.ts';
import { Router } from './transport/router.ts';
import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts';
import { StoreCatalogue } from './store/store-catalogue.ts';
import { StoreService } from './store/store-service.ts';
import { TrainingCatalogue } from './training/training-completion.ts';
import { TrafficLog } from './traffic-log/traffic-log.ts';
import { loadTuning, type Tuning } from './tuning/tuning.ts';
import { UnlockShop } from './unlocks/unlock-purchase.ts';
@@ -67,39 +73,100 @@ export interface ServerOptions {
/** Accounts, saves and logs. */
readonly dataFolder: string;
readonly port: number;
/** Start-up progress lines (static data extraction, game modes). */
/** Start-up progress lines (static data extraction, game modes, mod loading). */
readonly report?: (line: string) => void;
/** Whether to write traffic logs under `<dataFolder>/logs`; defaults to true. */
readonly loggingEnabled?: boolean;
/** Ordered list of enabled additive mods to load for this session. */
readonly mods?: readonly DiscoveredMod[];
}
export const LOOPBACK = '127.0.0.1';
export interface RunningServer {
readonly logFolder: string;
readonly loadedModIds: readonly string[];
close(): Promise<void>;
}
export async function startServer(options: ServerOptions): Promise<RunningServer> {
const report = options.report ?? (() => {});
const enabledMods = options.mods ?? [];
const modRuntime = await ServerModRuntime.load({
mods: enabledMods,
gameFolder: options.gameFolder,
dataFolder: options.dataFolder,
port: options.port,
report,
});
const gameFiles = new GameFiles(options.gameFolder);
// Static data and stores first, before the port opens.
const datasets = new DatasetCache(options.dataFolder, gameFiles, report);
const tuning = loadTuning(options.dataFolder, report);
const tuning = loadTuning(options.dataFolder, report, enabledMods);
const mutableDatasets = new Map<string, unknown>();
const vehiclesList: CatalogueVehicle[] = [...datasets.load(vehicleCatalogue)];
const rawMissions = datasets.load(multiplayerMissions);
const missionsObj: MultiplayerMissions = {
categories: [...rawMissions.categories],
missions: { ...rawMissions.missions },
};
const spawnRulesObj = datasets.load(battleSpawnRules);
const economyDataObj: BattleEconomyData = { ...datasets.load(battleEconomy), vehicles: { ...datasets.load(battleEconomy).vehicles } };
const labelsObj: UiLabels = { ...datasets.load(uiLabels) };
const localizedUnitNamesObj: UnitNamesMap = { ...datasets.load(unitNames) };
mutableDatasets.set('vehicle-catalogue', vehiclesList);
mutableDatasets.set('multiplayer-missions', missionsObj);
mutableDatasets.set('battle-spawn-rules', spawnRulesObj);
mutableDatasets.set('battle-economy', economyDataObj);
mutableDatasets.set('ui-labels', labelsObj);
mutableDatasets.set('unit-names', localizedUnitNamesObj);
const datasetsView: ServerModDatasetsView = {
vehicles: vehiclesList,
battleEconomy: economyDataObj as unknown as Record<string, unknown>,
battleSpawnRules: spawnRulesObj,
multiplayerMissions: missionsObj as unknown as Record<string, unknown>,
uiLabels: labelsObj as unknown as Record<string, unknown>,
unitNames: localizedUnitNamesObj as unknown as Record<string, unknown>,
get: <T = unknown>(id: string) => mutableDatasets.get(id) as T | undefined,
set: (id: string, value: unknown) => { mutableDatasets.set(id, value); },
};
await modRuntime.runDatasetsLoaded(datasetsView);
const vehicles = (mutableDatasets.get('vehicle-catalogue') as readonly CatalogueVehicle[]) ?? vehiclesList;
const missions = (mutableDatasets.get('multiplayer-missions') as MultiplayerMissions) ?? missionsObj;
const spawnRules = (mutableDatasets.get('battle-spawn-rules') as typeof spawnRulesObj) ?? spawnRulesObj;
const economyData = (mutableDatasets.get('battle-economy') as BattleEconomyData) ?? economyDataObj;
const labels = (mutableDatasets.get('ui-labels') as UiLabels) ?? labelsObj;
const localizedUnitNames = (mutableDatasets.get('unit-names') as UnitNamesMap) ?? localizedUnitNamesObj;
const gameModes = new GameModes(
datasets.load(multiplayerMissions), datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank,
missions, datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank,
);
const accounts = new AccountStore(options.dataFolder);
const clans = new ClanStore(options.dataFolder, tuning.clans);
const cloudSettings = new CloudSettingsStore(options.dataFolder);
const vehicles = datasets.load(vehicleCatalogue);
const spawnRules = datasets.load(battleSpawnRules);
const economyData = datasets.load(battleEconomy);
const efficiencyData = datasets.load(researchEfficiency);
const streakDefinitions = datasets.load(battleStreaks);
const labels = datasets.load(uiLabels);
const { profiles, research, equipment, repair } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels);
const { profiles, research, equipment, repair } = setUpProfiles(
options.dataFolder,
gameFiles,
datasets,
tuning,
{ accounts, clans },
vehicles,
(profile, userId) => modRuntime.runProfileRefresh(profile, userId),
);
const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(
datasets,
tuning,
vehicles,
labels,
localizedUnitNames,
);
const storeProducts = catalogues.store.allProducts();
const artwork = new GameArtwork(options.gameFolder, {
vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []),
@@ -108,12 +175,28 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
}, report);
const webUi = new WebUiService(datasets.load(webIcons), labels, options.dataFolder, artwork);
const botAircraftLoadouts = selectBotAircraftLoadouts(vehicles, datasets.load(flightModelPresets), equipment);
const botTankLoadouts = tuning.groundAi.mode === 'stock'
? undefined
: selectBotTankLoadouts(vehicles, datasets.load(tankBotAmmo), tuning.groundAi.loadout);
gameFiles.releasePacks();
let matching: MatchingService | undefined;
const notifyInventoryChanged = () => matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' });
const notifyUser = (userId: string, eventName: string, payload: Record<string, unknown>) => {
matching?.notifyUser(userId, eventName, payload);
};
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules, botAircraftLoadouts);
const battleMatchmaker = new BattleMatchmaker(
gameModes,
vehicles,
battleSessions,
tuning.battle,
spawnRules,
botAircraftLoadouts,
tuning.groundAi.mode === 'stock' ? undefined : tuning.groundAi.lineupWeights,
botTankLoadouts,
(ctx) => modRuntime.runBattleFilterMissions(ctx),
);
const economy = new BattleEconomy(
economyData,
tuning.battleEconomy,
@@ -124,7 +207,31 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
const streaks = new BattleStreaks(streakDefinitions, vehicles, economy);
const supportPlanes = supportPlaneUnits(spawnRules);
await modRuntime.runCataloguesReady({
tuning: tuning as unknown as Readonly<Record<string, unknown>>,
gameModes,
profiles,
accounts,
research,
equipment,
repair,
store: catalogues.store,
inventory: catalogues.inventory,
trophies: catalogues.trophies,
items: catalogues.items,
crew: catalogues.crew,
decor: catalogues.decor,
unlocks: catalogues.unlocks,
clans,
battleMatchmaker,
battleEconomy: economy,
battleStreaks: streaks,
notifyInventoryChanged,
notifyUser,
});
const router = new Router([
modRuntime.httpService(),
webUi,
new RegistrationService(accounts),
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
@@ -140,44 +247,69 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
...catalogues,
clans: { store: clans, economy: squadronEconomy },
cloudSettings,
battle: { sessions: battleSessions, economy, efficiency: new ResearchEfficiency(efficiencyData, research.techTree), streaks, supportPlanes },
battle: {
sessions: battleSessions,
economy,
efficiency: new ResearchEfficiency(efficiencyData, research.techTree),
streaks,
supportPlanes,
onAfterSettle: (ctx) => modRuntime.runBattleAfterSettle(ctx),
},
notifyInventoryChanged,
})),
}), modRuntime),
new DownloadableContentService(),
]);
const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true);
const matchingTable = modRuntime.applyMatchingRoutes(matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
onBeforeMatchmake: (ctx) => modRuntime.runBattleBeforeMatchmake(ctx),
},
battleLive: {
sessions: battleSessions,
liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept),
streaks,
supportPlanes,
onLiveFact: (ctx) => modRuntime.runBattleLiveFact(ctx),
},
}));
const listener = createPortListener(
router,
matchingRequests({
gameModes,
accounts,
battle: {
gameModes,
profiles,
matchmaker: battleMatchmaker,
sessions: battleSessions,
economy,
notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload),
},
battleLive: { sessions: battleSessions, liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept), streaks, supportPlanes },
}),
matchingTable,
log,
loadOrCreateCredentials(options.dataFolder),
);
matching = listener.matching;
await listen(listener.server, options.port);
await modRuntime.runServerListening(options.port);
return {
logFolder: log.folder,
close: () => new Promise((resolve) => {
listener.server.close(() => resolve());
listener.destroyConnections();
}),
loadedModIds: modRuntime.loadedModIds,
close: async () => {
await modRuntime.runServerClosing();
await new Promise<void>((resolve) => {
listener.server.close(() => resolve());
listener.destroyConnections();
});
},
};
}
function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles: readonly CatalogueVehicle[], labels: UiLabels) {
function loadDomainCatalogues(
datasets: DatasetCache,
tuning: Tuning,
vehicles: readonly CatalogueVehicle[],
labels: UiLabels,
localizedUnitNames: UnitNamesMap,
) {
const classicItemDefs = datasets.load(itemCatalogue);
const localizedUnitNames = datasets.load(unitNames);
return {
crew: new CrewSkillCatalogue(datasets.load(crewSkillData)),
decor: new DecorShop(datasets.load(decorCatalogue)),
@@ -186,6 +318,7 @@ function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles:
store: new StoreCatalogue(vehicles, datasets.load(storeBundles), localizedUnitNames, labels, tuning.store),
inventory: new InventoryCatalogue(vehicles, localizedUnitNames, datasets.load(externalItemSources), classicItemDefs, tuning),
trophies: new TrophyCatalogue(vehicles, classicItemDefs, tuning.trophies),
training: new TrainingCatalogue(datasets.load(trainingMissions)),
clanEconomy: datasets.load(clanEconomy),
};
}
+7 -2
View File
@@ -6,9 +6,14 @@
* `bundles/guid` registers a GUID for its id, so the build must register every pack this server
* will sell from the same data folder.
*/
import type { DiscoveredMod } from '@wto/mods';
import { tuningFiles } from '../tuning/tuning-loader.ts';
import { readStoreTuning } from './store-tuning.ts';
export function multiVehiclePackIds(dataFolder: string, report: (line: string) => void): string[] {
return readStoreTuning(tuningFiles(dataFolder, report).read('store')).multiVehiclePacks.map((pack) => pack.id);
export function multiVehiclePackIds(
dataFolder: string,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): string[] {
return readStoreTuning(tuningFiles(dataFolder, report, undefined, mods).read('store')).multiVehiclePacks.map((pack) => pack.id);
}
@@ -0,0 +1,73 @@
/**
* Rules for completing stock training missions reported by `cln_update` (`missionAwards`):
* persists `pveProgress/missions` completion flags and grants first-completion rewards
* (decal unlock/resource, shared first-basic-tutorial Golden Eagles unlock, and per-difficulty
* first-win Silver Lions) once per account.
*/
import type { BlkBlock } from '@wto/blk';
import type { TrainingMissionEntry, TrainingMissionsData } from '../game-data/datasets/training-missions.ts';
import { addGoldenEagles, addSilverLions } from '../profile/profile-currency.ts';
import { hasCompletedMissionDifficulty, recordMissionCompleted } from '../profile/profile-mission-progress.ts';
import { addResource, ownsResource } from '../profile/profile-resources.ts';
import { addUnlock, earnedUnlocks } from '../profile/profile-unlocks.ts';
export type TrainingDifficulty = 0 | 1 | 2;
export interface TrainingCompletionReport {
readonly chapter: string;
readonly mission: string;
readonly difficulty: TrainingDifficulty;
}
const DIFFICULTIES: readonly TrainingDifficulty[] = [0, 1, 2];
export class TrainingCatalogue {
readonly #byFullName: ReadonlyMap<string, TrainingMissionEntry>;
constructor(data: TrainingMissionsData) {
this.#byFullName = new Map(data.missions.map((entry) => [entry.fullName, entry]));
}
/**
* Persist a completed training mission and grant its one-time rewards. Repeated reports keep
* existing completion flags intact without paying any reward twice.
*/
applyCompletion(profile: BlkBlock, report: TrainingCompletionReport): void {
const entry = this.#byFullName.get(`${report.chapter}/${report.mission}`);
if (!entry) return;
let silverLions = 0;
for (const difficulty of DIFFICULTIES) {
if (difficulty <= report.difficulty && !hasCompletedMissionDifficulty(profile, entry.fullName, difficulty)) {
silverLions += entry.silverLionsByDifficulty[difficulty];
}
}
recordMissionCompleted(profile, entry.fullName, report.difficulty);
if (silverLions > 0) addSilverLions(profile, silverLions);
grantMissionUnlocks(profile, entry);
}
}
function grantMissionUnlocks(profile: BlkBlock, entry: TrainingMissionEntry): void {
if (!entry.decal && !entry.firstCompletion) return;
const earned = earnedUnlocks(profile);
const grantUnlock = (id: string): void => {
if (earned.has(id)) return;
addUnlock(profile, id);
earned.add(id);
};
if (entry.decal) {
grantUnlock(entry.decal);
if (!ownsResource(profile, entry.decal)) {
addResource(profile, entry.decal, { silverLions: 0, goldenEagles: 0 });
}
}
const first = entry.firstCompletion;
if (first && !earned.has(first.id) && !first.blockedBy.some((id) => earned.has(id))) {
addGoldenEagles(profile, first.goldenEagles);
grantUnlock(first.id);
}
}
+302
View File
@@ -0,0 +1,302 @@
/**
* Typed, range-validated reader for `tuning/ground-ai.jsonc`.
*/
import type { DiscoveredMod } from '@wto/mods';
import { GROUND_AI_MODES, type GroundAiConfig, type GroundAiMode } from '@wto/patcher';
import type { TankLineupWeights } from '../battle/battle-ranks.ts';
import { tuningFiles } from './tuning-loader.ts';
import { TuningError, type TuningReader } from './tuning-reader.ts';
export interface GroundAiTuning extends GroundAiConfig {
/** Tank pool weights by class, used only when a custom ground AI mode is active. */
readonly lineupWeights: TankLineupWeights;
}
const DRIVE_MODES = new Set(['vehicle_phys', 'movesys']);
export function loadGroundAiTuning(
dataFolder: string | null,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): GroundAiTuning {
return readGroundAiTuning(tuningFiles(dataFolder, report, undefined, mods).read('ground-ai'));
}
export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
const cadence = reader.object('cadence');
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 }),
macroTickSec: cadence.number('macroTickSec', { min: 0.1, max: 5 }),
tacticsTickSec: cadence.number('tacticsTickSec', { min: 0.05, max: 2 }),
navTickSec: cadence.number('navTickSec', { min: 0.05, max: 2 }),
},
commander: readCommanderSection(reader.object('commander')),
macro: readMacroSection(reader.object('macro')),
crowd: readCrowdSection(reader.object('crowd')),
terrain: readTerrainSection(reader.object('terrain')),
navigation: readNavigationSection(reader.object('navigation')),
perception: readPerceptionSection(reader.object('perception')),
stateMachine: readStateMachineSection(reader.object('stateMachine')),
tactics: readTacticsSection(reader.object('tactics')),
estimation: readEstimationSection(reader.object('estimation')),
fireControl: readFireControlSection(reader.object('fireControl')),
diagnostics: {
telemetry: diag.bool('telemetry'),
telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }),
},
};
}
function readMode(reader: TuningReader): GroundAiMode {
const mode = reader.string('mode');
const known = GROUND_AI_MODES.find((candidate) => candidate === mode);
if (known === undefined) {
throw new TuningError(`tuning file ground-ai.jsonc: mode must be one of ${GROUND_AI_MODES.map((m) => `"${m}"`).join(', ')} (found "${mode}")`);
}
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 {
spaa: weights.number('spaa', range),
lightTank: weights.number('lightTank', range),
tankDestroyer: weights.number('tankDestroyer', range),
heavyTank: weights.number('heavyTank', range),
mediumTank: weights.number('mediumTank', range),
other: weights.number('other', range),
};
}
function readCommanderSection(cmd: TuningReader): GroundAiTuning['commander'] {
const pct = { min: 0, max: 100 };
const bttlAssaultPct = cmd.int('bttlAssaultPct', pct);
const bttlFlankPct = cmd.int('bttlFlankPct', pct);
const bttlOverwatchPct = cmd.int('bttlOverwatchPct', pct);
if (bttlAssaultPct + bttlFlankPct + bttlOverwatchPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Bttl percentages must sum to <= 100');
}
const conqAssaultPct = cmd.int('conqAssaultPct', pct);
const conqFlankPct = cmd.int('conqFlankPct', pct);
if (conqAssaultPct + conqFlankPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Conq assault + flank percentages must sum to <= 100');
}
const conqHoldDefendPct = cmd.int('conqHoldDefendPct', pct);
const conqHoldOverwatchPct = cmd.int('conqHoldOverwatchPct', pct);
if (conqHoldDefendPct + conqHoldOverwatchPct > 100) {
throw new TuningError('tuning file ground-ai.jsonc: commander Conq hold percentages must sum to <= 100');
}
return {
rebalanceSec: cmd.number('rebalanceSec', { min: 1.0, max: 30.0 }),
roleHoldSec: cmd.number('roleHoldSec', { min: 0.0, max: 120.0 }),
bttlAssaultPct,
bttlFlankPct,
bttlOverwatchPct,
conqAssaultPct,
conqFlankPct,
conqHoldDefendPct,
conqHoldOverwatchPct,
domAssaultPct: cmd.int('domAssaultPct', pct),
domMaxDefendersPerCap: cmd.int('domMaxDefendersPerCap', { min: 0, max: 4 }),
overwatchStandOffM: cmd.number('overwatchStandOffM', { min: 25.0, max: 350.0 }),
flankStandOffM: cmd.number('flankStandOffM', { min: 25.0, max: 300.0 }),
spaaFollowOffsetM: cmd.number('spaaFollowOffsetM', { min: 40.0, max: 500.0 }),
flankMaxLengthRatio: cmd.number('flankMaxLengthRatio', { min: 1.05, max: 3.0 }),
flankMinSeparationM: cmd.number('flankMinSeparationM', { min: 15.0, max: 200.0 }),
rallyProgressFrac: cmd.number('rallyProgressFrac', { min: 0.1, max: 0.75 }),
rallyWaitSec: cmd.number('rallyWaitSec', { min: 3.0, max: 60.0 }),
rallyMinFrac: cmd.number('rallyMinFrac', { min: 0.25, max: 1.0 }),
rallyRadiusM: cmd.number('rallyRadiusM', { min: 15.0, max: 140.0 }),
recallSafeHoldSec: cmd.number('recallSafeHoldSec', { min: 3.0, max: 60.0 }),
};
}
function readMacroSection(macro: TuningReader): GroundAiTuning['macro'] {
const recaptureMinBots = macro.int('recaptureMinBots', { min: 1, max: 8 });
const recaptureMaxBots = macro.int('recaptureMaxBots', { min: 1, max: 12 });
if (recaptureMaxBots < recaptureMinBots) {
throw new TuningError('tuning file ground-ai.jsonc: macro.recaptureMaxBots must be >= macro.recaptureMinBots');
}
return {
openingSplitSec: macro.number('openingSplitSec', { min: 0, max: 180 }),
capMaxInsiders: macro.int('capMaxInsiders', { min: 1, max: 8 }),
recaptureMinBots,
recaptureMaxBots,
capStickyBonusM: macro.number('capStickyBonusM', { min: 0, max: 800 }),
deathZoneRadiusM: macro.number('deathZoneRadiusM', { min: 10, max: 250 }),
deathZoneTtlSec: macro.number('deathZoneTtlSec', { min: 5, max: 300 }),
deathZoneMinKills: macro.int('deathZoneMinKills', { min: 1, max: 16 }),
spaaRearOffsetM: macro.number('spaaRearOffsetM', { min: 40, max: 600 }),
spaaRelocateSec: macro.number('spaaRelocateSec', { min: 5, max: 180 }),
enemySpawnAvoidM: macro.number('enemySpawnAvoidM', { min: 60, max: 600 }),
};
}
function readCrowdSection(crowd: TuningReader): GroundAiTuning['crowd'] {
return {
personalSpaceM: crowd.number('personalSpaceM', { min: 6, max: 40 }),
clusterRadiusM: crowd.number('clusterRadiusM', { min: 12, max: 80 }),
clusterMaxAllies: crowd.int('clusterMaxAllies', { min: 1, max: 10 }),
disperseStepM: crowd.number('disperseStepM', { min: 8, max: 65 }),
disperseHoldSec: crowd.number('disperseHoldSec', { min: 1, max: 15 }),
};
}
function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] {
return {
maxClimbSlopeDeg: terrain.number('maxClimbSlopeDeg', { min: 10, max: 42 }),
maxDropSlopeDeg: terrain.number('maxDropSlopeDeg', { min: 8, max: 40 }),
maxWaterDepthM: terrain.number('maxWaterDepthM', { min: 0.2, max: 2.5 }),
collisionMarginM: terrain.number('collisionMarginM', { min: 0.05, max: 2.0 }),
crestLookaheadM: terrain.number('crestLookaheadM', { min: 8, max: 80 }),
ridgeMaxDwellSec: terrain.number('ridgeMaxDwellSec', { min: 2, max: 60 }),
ridgeMaxShots: terrain.int('ridgeMaxShots', { min: 1, max: 10 }),
};
}
function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] {
const driveMode = nav.string('driveMode');
if (!DRIVE_MODES.has(driveMode)) {
throw new TuningError(`tuning file ground-ai.jsonc: navigation.driveMode must be "vehicle_phys" or "movesys" (found "${driveMode}")`);
}
const steerSign = nav.number('steerSign', { min: -1, max: 1 });
if (steerSign !== 1 && steerSign !== -1) {
throw new TuningError('tuning file ground-ai.jsonc: navigation.steerSign must be 1 or -1');
}
return {
driveMode,
maxPhysBots: nav.int('maxPhysBots', { min: 0, max: 64 }),
steerSign,
deadEchoSec: nav.number('deadEchoSec', { min: 0.3, max: 10 }),
controlTimeoutSec: nav.number('controlTimeoutSec', { min: 0.3, max: 10 }),
cornerBrakeAccel: nav.number('cornerBrakeAccel', { min: 0.5, max: 8 }),
pivotAngleDeg: nav.number('pivotAngleDeg', { min: 25, max: 150 }),
stuckWindowSec: nav.number('stuckWindowSec', { min: 1, max: 15 }),
stuckMinMoveM: nav.number('stuckMinMoveM', { min: 0.5, max: 10 }),
unstickReverseSec: nav.number('unstickReverseSec', { min: 0.8, max: 10 }),
tacticalReverseDistM: nav.number('tacticalReverseDistM', { min: 10, max: 90 }),
tacticalReverseMaxSec: nav.number('tacticalReverseMaxSec', { min: 2, max: 25 }),
};
}
function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception'] {
return {
foliageTransparency: perc.number('foliageTransparency', { min: 0.001, max: 1.0 }),
nearSpotRangeM: perc.number('nearSpotRangeM', { min: 20, max: 250 }),
firingSpotRangeM: perc.number('firingSpotRangeM', { min: 150, max: 1500 }),
fastSpotSec: perc.number('fastSpotSec', { min: 0.05, max: 1.5 }),
normalSpotSec: perc.number('normalSpotSec', { min: 0.1, max: 3.0 }),
farSpotSec: perc.number('farSpotSec', { min: 0.3, max: 6.0 }),
decayPerSec: perc.number('decayPerSec', { min: 0.2, max: 10.0 }),
frontConeHalfDeg: perc.number('frontConeHalfDeg', { min: 10, max: 90 }),
peripheralCloseM: perc.number('peripheralCloseM', { min: 30, max: 250 }),
};
}
function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine'] {
const coverMinDistM = sm.number('coverMinDistM', { min: 2.0, max: 30.0 });
const coverMaxDistM = sm.number('coverMaxDistM', { min: 6.0, max: 80.0 });
if (coverMaxDistM <= coverMinDistM) {
throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM');
}
return {
preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }),
shortHaltMaxSec: sm.number('shortHaltMaxSec', { min: 0.5, max: 12.0 }),
shortHaltCooldownSec: sm.number('shortHaltCooldownSec', { min: 0.5, max: 20.0 }),
turnLaunchSpeedMps: sm.number('turnLaunchSpeedMps', { min: 0.5, max: 6.0 }),
coverMinDistM,
coverMaxDistM,
coverRetreatBudgetSec: sm.number('coverRetreatBudgetSec', { min: 1.5, max: 20.0 }),
reloadAdvanceAngleDeg: sm.number('reloadAdvanceAngleDeg', { min: 0.0, max: 45.0 }),
hullAngleTriggerDeg: sm.number('hullAngleTriggerDeg', { min: 15.0, max: 75.0 }),
hullAngleTargetDeg: sm.number('hullAngleTargetDeg', { min: 0.0, max: 35.0 }),
maxTotalHaltSec: sm.number('maxTotalHaltSec', { min: 3.0, max: 40.0 }),
stalemateMissShots: sm.int('stalemateMissShots', { min: 1, max: 8 }),
stalemateNoShotHalts: sm.int('stalemateNoShotHalts', { min: 1, max: 6 }),
repositionMinMoveM: sm.number('repositionMinMoveM', { min: 5.0, max: 80.0 }),
repositionStepM: sm.number('repositionStepM', { min: 15.0, max: 120.0 }),
repairSafeEnemyDistM: sm.number('repairSafeEnemyDistM', { min: 30.0, max: 400.0 }),
};
}
function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] {
return {
visionRangeM: tactics.number('visionRangeM', { min: 200, max: 3500 }),
visionFovDeg: tactics.number('visionFovDeg', { min: 40, max: 180 }),
peripheralRangeM: tactics.number('peripheralRangeM', { min: 30, max: 800 }),
engineAudioRangeM: tactics.number('engineAudioRangeM', { min: 10, max: 250 }),
shotAudioRangeM: tactics.number('shotAudioRangeM', { min: 50, max: 1200 }),
radioShareRangeM: tactics.number('radioShareRangeM', { min: 50, max: 1500 }),
memoryTtlSec: tactics.number('memoryTtlSec', { min: 1, max: 45 }),
targetStickinessSec: tactics.number('targetStickinessSec', { min: 0.5, max: 20 }),
peekCooldownSec: tactics.number('peekCooldownSec', { min: 1, max: 30 }),
};
}
function readEstimationSection(est: TuningReader): GroundAiTuning['estimation'] {
const watchMinSec = est.number('watchMinSec', { min: 0.5, max: 10.0 });
const watchMaxSec = est.number('watchMaxSec', { min: 1.0, max: 15.0 });
if (watchMaxSec < watchMinSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.watchMaxSec must be >= watchMinSec');
}
const velSampleMinSpanSec = est.number('velSampleMinSpanSec', { min: 0.05, max: 2.0 });
const velStableSpanSec = est.number('velStableSpanSec', { min: 0.2, max: 6.0 });
if (velStableSpanSec <= velSampleMinSpanSec) {
throw new TuningError('tuning file ground-ai.jsonc: estimation.velStableSpanSec must be > velSampleMinSpanSec');
}
return {
watchMinSec,
watchMaxSec,
velSampleMinSpanSec,
velStableSpanSec,
velJumpResetMps: est.number('velJumpResetMps', { min: 1.0, max: 20.0 }),
baseAimSigmaM: est.number('baseAimSigmaM', { min: 0.0, max: 2.0 }),
leadErrorFrac: est.number('leadErrorFrac', { min: 0.0, max: 1.0 }),
maxBiasM: est.number('maxBiasM', { min: 0.0, max: 6.0 }),
};
}
function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl'] {
const closeRangeM = fc.number('closeRangeM', { min: 30, max: 250 });
const midRangeM = fc.number('midRangeM', { min: 100, max: 600 });
const longRangeM = fc.number('longRangeM', { min: 300, max: 1500 });
if (midRangeM <= closeRangeM || longRangeM <= midRangeM) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM');
}
return {
maxEngageRangeM: fc.number('maxEngageRangeM', { min: 150, max: 3000 }),
closeRangeM,
midRangeM,
longRangeM,
midSlowSpeedRatio: fc.number('midSlowSpeedRatio', { min: 0.1, max: 1.0 }),
midSlowMaxMps: fc.number('midSlowMaxMps', { min: 1.0, max: 15.0 }),
stopSpeedMaxMps: fc.number('stopSpeedMaxMps', { min: 0.1, max: 2.0 }),
longRangeWindowSec: fc.number('longRangeWindowSec', { min: 1.0, max: 15.0 }),
baseAlignDeg: fc.number('baseAlignDeg', { min: 0.1, max: 3.0 }),
closeHitRadiusM: fc.number('closeHitRadiusM', { min: 0.25, max: 2.2 }),
barrelSettleDegSec: fc.number('barrelSettleDegSec', { min: 0.2, max: 12.0 }),
closeSettleHoldSec: fc.number('closeSettleHoldSec', { min: 0.02, max: 0.5 }),
settleHoldSec: fc.number('settleHoldSec', { min: 0.05, max: 1.5 }),
unstabilizedStopSpeedMps: fc.number('unstabilizedStopSpeedMps', { min: 0.1, max: 3.0 }),
stabilizedCreepSpeedMps: fc.number('stabilizedCreepSpeedMps', { min: 1.5, max: 15.0 }),
friendlyCorridorM: fc.number('friendlyCorridorM', { min: 1.0, max: 10.0 }),
ballisticStepMaxM: fc.number('ballisticStepMaxM', { min: 5.0, max: 80.0 }),
ballisticSweepRadiusM: fc.number('ballisticSweepRadiusM', { min: 0.02, max: 0.5 }),
maxPreFireChecksPerTick: fc.int('maxPreFireChecksPerTick', { min: 1, max: 16 }),
};
}
+30 -20
View File
@@ -1,16 +1,21 @@
/**
* Load one tuning file: the defaults shipped in
* apps/server/tuning/<name>.jsonc, with <data folder>/tuning/<name>.jsonc laid
* over them field by field when the player or a developer put one there. Objects merge key
* by key; any other value (numbers, texts, lists) in the override replaces the default.
* Load one tuning file with multi-layer overrides:
* shipped defaults (`apps/server/tuning/<name>.jsonc`)
* -> each enabled mod's `<server.tuning>/<name>.jsonc` in load order
* -> player overrides (`<dataFolder>/tuning/<name>.jsonc`).
*
* Objects merge key by key; plain lists replace the base list; `{ "$listOps": [...] }`
* performs additive append/prepend/upsertBy/removeBy operations across layers.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseJsonc } from '@wto/jsonc';
import { mergeTuningLayer, type DiscoveredMod } from '@wto/mods';
import { TuningError, TuningReader } from './tuning-reader.ts';
const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url));
const DEFAULT_MOD_TUNING_DIR = 'server/tuning';
export interface TuningFiles {
/** The merged content of <name>.jsonc, ready for typed reads. */
@@ -21,19 +26,35 @@ export function tuningFiles(
dataFolder: string | null,
report: (line: string) => void,
proposed?: ReadonlyMap<string, Record<string, unknown>>,
mods: readonly DiscoveredMod[] = [],
): TuningFiles {
const overridesFolder = dataFolder === null ? null : join(dataFolder, 'tuning');
return {
read(name: string): TuningReader {
const fileName = `${name}.jsonc`;
const defaults = parseFile(join(DEFAULTS_FOLDER, fileName));
let merged = parseFile(join(DEFAULTS_FOLDER, fileName));
for (const mod of mods) {
const modTuningDir = mod.manifest.server?.tuning ?? DEFAULT_MOD_TUNING_DIR;
const modFilePath = join(mod.rootDir, ...modTuningDir.split('/'), fileName);
if (!existsSync(modFilePath)) continue;
report(`tuning ${fileName}: applying mod "${mod.manifest.id}" overrides`);
try {
merged = mergeTuningLayer(merged, parseFile(modFilePath));
} catch (error) {
throw new TuningError(
`mod "${mod.manifest.id}" tuning ${fileName} merge failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
const candidate = proposed?.get(name);
if (candidate) return new TuningReader(fileName, mergeOverride(defaults, candidate));
if (overridesFolder === null) return new TuningReader(fileName, defaults);
if (candidate) return new TuningReader(fileName, mergeTuningLayer(merged, candidate));
if (overridesFolder === null) return new TuningReader(fileName, merged);
const overridePath = join(overridesFolder, fileName);
if (!existsSync(overridePath)) return new TuningReader(fileName, defaults);
if (!existsSync(overridePath)) return new TuningReader(fileName, merged);
report(`tuning ${fileName}: using overrides from ${overridePath}`);
return new TuningReader(fileName, mergeOverride(defaults, parseFile(overridePath)));
return new TuningReader(fileName, mergeTuningLayer(merged, parseFile(overridePath)));
},
};
}
@@ -45,14 +66,3 @@ function parseFile(path: string): unknown {
throw new TuningError(`tuning file ${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
}
}
function mergeOverride(base: unknown, override: unknown): unknown {
if (!isObject(base) || !isObject(override)) return override;
const merged: Record<string, unknown> = { ...base };
for (const [key, value] of Object.entries(override)) merged[key] = key in base ? mergeOverride(base[key], value) : value;
return merged;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+10 -2
View File
@@ -13,6 +13,8 @@ import { readNewProfileTuning, type NewProfileTuning } from '../profile/new-prof
import { readResearchTuning, type ResearchTuning } from '../research/research-tuning.ts';
import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts';
import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts';
import type { DiscoveredMod } from '@wto/mods';
import { readGroundAiTuning, type GroundAiTuning } from './ground-ai-tuning.ts';
import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts';
import { tuningFiles } from './tuning-loader.ts';
@@ -28,11 +30,16 @@ export interface Tuning {
readonly clans: ClanTuning;
readonly battle: BattleTuning;
readonly battleEconomy: BattleEconomyTuning;
readonly groundAi: GroundAiTuning;
readonly limits: LimitsTuning;
}
export function loadTuning(dataFolder: string, report: (line: string) => void): Tuning {
const files = tuningFiles(dataFolder, report);
export function loadTuning(
dataFolder: string,
report: (line: string) => void,
mods: readonly DiscoveredMod[] = [],
): Tuning {
const files = tuningFiles(dataFolder, report, undefined, mods);
return {
store: readStoreTuning(files.read('store')),
redeemCodes: readRedeemTuning(files.read('redeem-codes')),
@@ -45,6 +52,7 @@ export function loadTuning(dataFolder: string, report: (line: string) => void):
clans: readClanTuning(files.read('clans')),
battle: readBattleTuning(files.read('battle')),
battleEconomy: readBattleEconomyTuning(files.read('battle-economy')),
groundAi: readGroundAiTuning(files.read('ground-ai')),
limits: readLimitsTuning(files.read('limits')),
};
}
+196
View File
@@ -0,0 +1,196 @@
// Ground battle AI configuration.
// Per-client overrides live in <dataDir>/tuning/ground-ai.jsonc. The game copy build compiles the
// layer settings into game/wtoai/wto_ai_config_common.das; the local server reads lineupWeights.
{
// "full": every custom layer (default).
// "fire": stock movement and destinations, custom perception and fire permission.
// "drive": custom team orders and driving, stock aiming and firing (debugging).
// "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": {
"spaa": 0.12,
"lightTank": 0.45,
"tankDestroyer": 0.55,
"heavyTank": 0.85,
"mediumTank": 1.15,
"other": 1.0
},
"cadence": {
"maxBots": 64,
"macroTickSec": 0.5,
"tacticsTickSec": 0.25,
"navTickSec": 0.2
},
// Team commander role quotas and timing (offline values).
"commander": {
"rebalanceSec": 5.0,
"roleHoldSec": 20.0,
"bttlAssaultPct": 45,
"bttlFlankPct": 15,
"bttlOverwatchPct": 20,
"conqAssaultPct": 50,
"conqFlankPct": 20,
"conqHoldDefendPct": 30,
"conqHoldOverwatchPct": 30,
"domAssaultPct": 70,
"domMaxDefendersPerCap": 1,
"overwatchStandOffM": 95.0,
"flankStandOffM": 75.0,
"spaaFollowOffsetM": 160.0,
"flankMaxLengthRatio": 1.6,
"flankMinSeparationM": 45.0,
"rallyProgressFrac": 0.40,
"rallyWaitSec": 25.0,
"rallyMinFrac": 0.66,
"rallyRadiusM": 55.0,
"recallSafeHoldSec": 15.0
},
"macro": {
"openingSplitSec": 40.0,
"capMaxInsiders": 2,
"recaptureMinBots": 2,
"recaptureMaxBots": 4,
"capStickyBonusM": 165.0,
"deathZoneRadiusM": 55.0,
"deathZoneTtlSec": 60.0,
"deathZoneMinKills": 3,
"spaaRearOffsetM": 185.0,
"spaaRelocateSec": 28.0,
"enemySpawnAvoidM": 180.0
},
"crowd": {
"personalSpaceM": 14.0,
"clusterRadiusM": 28.0,
"clusterMaxAllies": 2,
"disperseStepM": 24.0,
"disperseHoldSec": 4.2
},
"terrain": {
"maxClimbSlopeDeg": 25.0,
"maxDropSlopeDeg": 20.0,
"maxWaterDepthM": 0.6,
"collisionMarginM": 0.3,
"crestLookaheadM": 28.0,
"ridgeMaxDwellSec": 10.0,
"ridgeMaxShots": 2
},
"navigation": {
// "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement.
"driveMode": "vehicle_phys",
"maxPhysBots": 64,
"steerSign": 1.0,
"deadEchoSec": 1.2,
"controlTimeoutSec": 1.0,
"cornerBrakeAccel": 1.75,
"pivotAngleDeg": 75.0,
"stuckWindowSec": 3.6,
"stuckMinMoveM": 2.0,
"unstickReverseSec": 3.0,
"tacticalReverseDistM": 34.0,
"tacticalReverseMaxSec": 9.5
},
// Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI).
"perception": {
"foliageTransparency": 0.01,
"nearSpotRangeM": 90.0,
"firingSpotRangeM": 650.0,
"fastSpotSec": 0.25,
"normalSpotSec": 0.60,
"farSpotSec": 1.45,
"decayPerSec": 1.5,
"frontConeHalfDeg": 30.0,
"peripheralCloseM": 100.0
},
// Per-bot hull state machine timings and thresholds (offline values).
"stateMachine": {
"preaimAngleDeg": 8.0,
"shortHaltMaxSec": 3.0,
"shortHaltCooldownSec": 4.0,
"turnLaunchSpeedMps": 2.1,
"coverMinDistM": 6.0,
"coverMaxDistM": 24.0,
"coverRetreatBudgetSec": 6.0,
"reloadAdvanceAngleDeg": 18.0,
"hullAngleTriggerDeg": 30.0,
"hullAngleTargetDeg": 15.0,
"maxTotalHaltSec": 12.0,
"stalemateMissShots": 2,
"stalemateNoShotHalts": 2,
"repositionMinMoveM": 20.0,
"repositionStepM": 48.0,
"repairSafeEnemyDistM": 140.0
},
"tactics": {
"visionRangeM": 1250.0,
"visionFovDeg": 115.0,
"peripheralRangeM": 230.0,
"engineAudioRangeM": 65.0,
"shotAudioRangeM": 380.0,
"radioShareRangeM": 450.0,
"memoryTtlSec": 12.0,
"targetStickinessSec": 4.5,
"peekCooldownSec": 6.0
},
// Target velocity estimation from own visual samples, last-seen watch, and bounded shot bias.
"estimation": {
"watchMinSec": 2.0,
"watchMaxSec": 5.0,
"velSampleMinSpanSec": 0.25,
"velStableSpanSec": 1.2,
"velJumpResetMps": 4.5,
"baseAimSigmaM": 0.28,
"leadErrorFrac": 0.26,
"maxBiasM": 2.2
},
"fireControl": {
"maxEngageRangeM": 1250.0,
"closeRangeM": 100.0,
"midRangeM": 300.0,
"longRangeM": 800.0,
"midSlowSpeedRatio": 0.45,
"midSlowMaxMps": 5.5,
"stopSpeedMaxMps": 0.45,
"longRangeWindowSec": 4.0,
"baseAlignDeg": 0.42,
"closeHitRadiusM": 0.85,
"barrelSettleDegSec": 1.8,
"closeSettleHoldSec": 0.08,
"settleHoldSec": 0.20,
"unstabilizedStopSpeedMps": 0.45,
"stabilizedCreepSpeedMps": 5.5,
"friendlyCorridorM": 3.2,
"ballisticStepMaxM": 25.0,
"ballisticSweepRadiusM": 0.12,
"maxPreFireChecksPerTick": 2
},
"diagnostics": {
"telemetry": false,
"telemetryIntervalSec": 5.0
}
}
+231 -19
View File
@@ -1,31 +1,243 @@
# Dev Docs
# WTOffline Developer Documentation / 开发者文档
<a id="zh-cn"></a>
简体中文 · [English](#english)
简体中文 · [English](#english) · [在线文档站](https://wto-project.net/dev-docs)
这是 WTOffline 的开发与贡献入口。请先准备一份自己持有的原版客户端,只读使用,并从 [主 README 的开发章节](../README.md#开发)安装工具和依赖。要启动游戏验证时,另备一份 Steam 游戏库之外的离线副本和独立的数据目录,先按[开发规范](development-rules.md#zh-cn)核实隔离。
欢迎参与 WTOffline 开发。本目录面向**项目贡献者、客户端新版本适配者,以及使用 AI 编程工具辅助逆向定位与编写代码的协作者**。无论你之前是否接触过 Dagor 引擎或《战争雷霆》客户端内部结构,都可以按本指南一步步上手。
| 要做的事 | 从这里开始 |
| --- | --- |
| 改启动器或安装流程 | [apps/launcher](../apps/launcher) |
| 改游戏规则、档案或本地服务 | [apps/server](../apps/server) |
| 改游戏副本的构建或补丁检查 | [packages/patcher](../packages/patcher)、[scripts](../scripts)、[tools](../tools) |
| 写客户端补丁或适配新的游戏版本 | [补丁指南](patches.md#zh-cn)和[补丁集](../patches) |
> **如果你只是想制作载具属性魔改、自定义地图池、全新 3D 载具模型或服务端脚本模组**:你完全不需要修改 WTOffline 核心源码,请直接阅读 [模组开发文档(mod-dev-docs)](../mod-dev-docs/README.md) 或访问 [在线模组文档](https://wto-project.net/mod-docs)。
提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。
---
## 第一次来,建议按什么顺序读?
不要一上来就啃二进制补丁字段或反汇编地址。按下面三步顺读,大约 15–20 分钟就能建立完整的全局认知:
1. **[开发理念、架构分层与工程规范](development-rules.md#zh-cn)**(**必读第一站**):搞清楚启动器、单端口本地模拟服务器(`apps/server`)与进程内网络/对局桥接库(`wto_ws.dll`)是如何协同工作的;顺着一个真实的 `cln_set_researchable` 动作看懂服务端四层代码怎么流转;掌握「三类数值放哪里」「好代码 vs 坏代码」真实对比,以及可直接复制给 AI 编程助手的工程约束提示词。
2. **[补丁编写与新版本适配指南](patches.md#zh-cn)**:当确认本地服务器与原版配置确实无法解决问题、必须修改客户端时,按这篇手把手教程拆包查看原版文件、用 `tools/re/cli.py` 反汇编定位,并对照完整无省略的 GUI(`patches/gui/`)、EXE(`patches/exe/`)和 Native(`patches/native/` + `native/wto-net/`)真实案例编写跨版本自适应补丁。
3. **[环境搭建、流量调试与提交自查](contributing.md#zh-cn)**:配齐本地开发环境,学会直接阅读 `<数据目录>/logs/` 下自动解码的明文 BLK 流量日志快速抓 Bug,按改动类型运行对应的必跑检查命令,并对照 [PR 模板](templates/pull-request.md) 提交高质量改动。
---
<a id="glossary-zh"></a>
## 核心概念与术语词典
在阅读后续文档或翻阅源码时,你会频繁遇到以下专有名词。这里用大白话一次性讲透:
### 1. `vromfs.bin`(Dagor 虚拟只读归档包)
《战争雷霆》不会把成千上万个零散脚本和配置文件直接摊在硬盘上,而是打包进若干个 `.vromfs.bin` 归档文件中。它在结构上分两层:外层是带简单异或混淆的 Zstandard(zstd)压缩容器、内部镜像 MD5 与末尾 256 字节签名;内层是文件表(全小写相对路径、偏移量、可选 SHA-1 摘要,以及可选的共享键名表 `nm` 与 `.dict` 压缩字典)。项目中的 `@wto/vromfs`(`readArchive` / `getFile` / `putFile` / `writeArchive`)负责无损读写这些归档包。
不同归档包各司其职,查数据时按下面这张表找最快:
| 归档包路径(相对于游戏根目录) | 里面装什么核心内容 | WTOffline 哪里会用到它 |
| --- | --- | --- |
| `char.vromfs.bin` | 科技树排布(`config/shop.blk`)、载具价格/研发点/修车费/改装件(`config/wpcost.blk`)、全局经济与分房公式(`config/warpoints.blk`、`config/rank.blk`)、初始档案模板(`config/default_user.blk`)、任务列表与成就解锁(`config/mislist.blk`、`config/pve_awards.blk`、`config/unlocks.blk`)、涂装/贴花/挂件/道具定义(`config/skins.blk`、`config/decals.blk`、`config/attachable.blk`、`config/items.blk`)以及 `config/network.blk` | `packages/patcher` 构建副本时改写服务地址与隐藏载具可见性;`apps/server` 启动时从中提取绝大部分静态经济与科技树数据集 |
| `aces.vromfs.bin` | 局内玩法与连杀支援规则(`config/gameplay.blk`)、界面与礼包 GUID 映射(`config/gui.blk`)、工坊配方(`config/workshop.blk`)以及全部载具的气动/损伤/武器预设模型(`gamedata/flightmodels/…`、`gamedata/units/…`) | `packages/patcher` 写入本地商店礼包 GUID;`apps/server` 提取对局出生规则、礼包映射与载具武器预设 |
| `gui.vromfs.bin` | 客户端全部机库、弹窗、商店、战后结算与 HUD 界面的 Quirrel 脚本(`scripts/**/*.nut`)与布局模板(`.blk` / `.css`) | `patches/gui/` 在构建副本时对少数客户端界面脚本做精确片段替换 |
| `mis.vromfs.bin` | 多人对战与单人任务的地图逻辑、出生点区域、战区与胜利条件定义(`gamedata/missions/**/*.blk`) | `apps/server` 启动时扫描提取多人任务目录(`multiplayer-missions` 数据集),用于匹配开局 |
| `lang.vromfs.bin` | 分号分隔的多语言本地化词条表(`lang/units.csv`、`lang/menu.csv`、`lang/unlocks_achievements.csv` 等) | `apps/server` 提取载具、国家与物品的多语言显示名称,供本地网页商店、交易所和启动器展示 |
| `ui/atlases.vromfs.bin` | 科技树载具剪影与阵营国旗等矢量图标(`gameuiskin/*.svg`) | `apps/server` 按需提取金币车/礼包车/市场车图标与国旗(`web-icons` 数据集)供游戏内嵌网页商店渲染 |
| `ui/images.vromfs.bin` | 界面位图插画、礼包封面与飞行员头像贴图(`images/**`) | `apps/server` 为内嵌网页商店展示商品封面,并为启动器存档页渲染玩家头像 |
### 2. `BLK` / `DataBlock`(Dagor 树状键值与块数据格式)
`BLK`(引擎 C++ 类名为 `DataBlock`)是贯穿整个游戏的通用配置与通信载体,结构类似「带严格值类型的树状 JSON」:每个节点既可以挂载带类型的参数(如整数 `:i`、浮点 `:r`、字符串 `:t`、布尔 `:b`、三维向量 `:p3`、矩阵 `:m` 等),也可以嵌套任意多层同名或异名子块。在 WTOffline 中你会见到它的四种形态,全部由 `@wto/blk`(`decodeBlk`、`encodeBlk`、`formatBlkText`、`parseBlkText`)统一处理:
- **归档包内的紧凑二进制 BLK**:`char.vromfs.bin` 与 `aces.vromfs.bin` 里的 `.blk` 通常将键名抽离到包内共享键名表 `nm`(甚至配合 `.dict` 字典做二次 zstd 压缩),解码时需传入 `SharedNameContext`;
- **`char` 协议单包二进制 BLK**:HTTP 响应体首字节带压缩标记(例如 `0x69` 即 `'i'` 表示未压缩二进制 BLK,另有 zlib / zstd 标记),后面紧跟自包含二进制 BLK;
- **`PBBD` 批处理流**:客户端上传云端键位与设置(`cln_bulk_set_gblk`)时使用的多段二进制容器(魔数 `"PBBD"`),每段内嵌独立 BLK 块;
- **本地存档自包含二进制 BLK**:`<数据目录>/saves/<userId>/profile.blk` 直接用 `encodeBlk()` 落盘,完整保留每个字段的原始值类型,避免整数与浮点数混淆导致客户端解析异常。
### 3. 本地模拟的四大 Gaijin 后端服务
原版联网客户端并不是只跟一台服务器通信,而是同时访问多套职责不同的后端服务。`apps/server` 在本机 `127.0.0.1:<端口>` 上把这四大核心服务全部接管并模拟:
- **`yuplay2`(登录与权益服务,`login/`、`store/`)**:处理客户端启动时的账号密码表单登录(`POST /login.php`),签发本地会话凭据与 `userId`,并提供商店礼包与激活码相关的 Web 接口;
- **`char`(角色档案服务器 Character Server,`char/`)**:机库阶段最核心的请求入口(原域名 `char-*.warthunder.com`)。客户端通过 HTTP 请求头 `action` 指明动作名(如 `cln_get_user_stat`、`cln_buy_aircraft`、`cln_set_researchable`、`cln_update`),通过 `uidhint` 指明当前账号,请求与响应主体以二进制 BLK 为主,负责完整玩家档案下发、科技树研发、买车买改装、乘员组训练、联队、云端键位设置及战后经济结算;
- **`matching`(匹配与开局二进制长连接服务,`matching/`)**:基于 TCP 的自定义二进制长连接协议(首字节固定为 `0x01`,9 字节包头 + LZ4 压缩负载,握手后启用流加密)。负责向客户端下发可用游戏模式列表、接收排队与小队状态,并在匹配成功时向客户端下发完整的对局启动参数(地图、天气、AI 名单、自定义计分参数等);
- **`inventory`(外部物品库与交易所服务,`inventory/`)**:模拟 `inventory-proxy-*.gaijin.net/char` 接口(动作名如 `GetInventory`、`GetItemDefsClient`、`GetItemPrices`、`GetItemDefChances`、`ExchangeItems`)。与 `char` 不同,客户端 `charsq` 模块直接将响应解析为 UTF-8 JSON,且要求关键响应附带 RSA 内容签名;用于驱动补给箱开箱、载具兑换券、工坊合成与本地模拟交易所。
### 4. `LocalMP`(为什么既要有 `apps/server`,又必须有 `wto_ws.dll`?)
初看代码库时最容易产生的疑问是:**既然已经用 Node.js 写了本地服务器 `apps/server`,为什么还要用 C 写一个 `native/wto-net/`(编译为 `wto_ws.dll`)注入进游戏进程?**
原因在于《战争雷霆》客户端与专用对局服务器(Dedicated Server)的代码裁剪边界:
- 原版零售客户端 `aces.exe` 内部其实保留了一套名为 **`LocalMP`(本地多人主机,`mp_is_host == 1 && mp_is_local_mp == 1`)** 的局内会话模式,能够在本机直接跑完整的物理引擎、弹道解算、损伤模型与 AI 驾驶逻辑,因此 WTOffline 不需要重写整套游戏物理服务器;
- **但是**,Gaijin 在编译零售版 `aces.exe` 时,把原本只在云端专用对局服务器上运行的大量「对局裁判(Host Referee)」处理逻辑裁掉了——包括:**响应玩家选车与挂载弹药并生成实体、允许 `BotSystem` 刷出 AI 载具、判定击杀/助攻/占点并往记分牌加分、陆战街机连杀空中支援事件生成、核弹落地直接判胜,以及过滤本不该发给受害者之外玩家的炮管/炮闩受损提示**;
- 因此两套组件分工明确、缺一不可:**`apps/server` 负责对局之外的一切**(登录、机库养成、商店市场、排队拼装任务配置、战后发银狮/研发点与存档持久化);而 **`wto_ws.dll` 在对局进行期间通过 MinHook 挂载在 `aces.exe` 进程内**,一方面把所有硬编码外网 Socket 连接重定向回 `127.0.0.1`,另一方面通过 `local_mp_*` 模块把被客户端裁掉的局内主机裁判逻辑原原本本补齐。
### 5. `Quirrel (.nut)` 与 `sq.exe` 字节码编译器
`gui.vromfs.bin` 中的 `.nut` 文件使用的是 Gaijin 基于 Squirrel 深度定制的强词法作用域脚本语言 **[Quirrel](https://quirrel.io/)**。客户端在玩家点击登录、进入机库前会一次性编译加载大批 `.nut` 脚本。
为什么修改 `patches/gui/` 后**不能只靠肉眼或普通语法树(AST)检查**,而需要用对应提交版本的原生编译器 `sq.exe` 跑 `wtotools check-gui`?因为 Quirrel 的 `compilestring` 字节码编译阶段会执行严格的词法绑定检查:
- 如果你在 `replace.nut` 里声明了一个 `local` 变量,恰好与该文件顶部 `from ... import *` 通配导入的某个全局常量重名;
- 或者在函数尚未定义/绑定前做了前向调用;
- 或者把 Quirrel 保留字(最典型的坑是 `base`)当成了普通变量名;
普通语法检查器都会放行,但真进游戏时 Quirrel 虚拟机就会直接中断模块加载,导致客户端**永远卡死在登录后的「正在加载…」转圈界面**。`wtotools check-gui` 会在内存中打上所有 GUI 补丁并逐个调用 `sq.exe` 编译字节码,把这类致命隐患在提交前 100% 拦住。
### 6. `RVA`、虚拟地址(`VA`)与进程运行时指针
在看 `patches/exe/`、`patches/native/` 或使用逆向工具时,务必分清这三种地址表示:
- **`VA`(Virtual Address,静态虚拟地址)**:Ghidra 或 IDA 打开 64 位 Windows 程序 `aces.exe` 时,默认镜像基址(`ImageBase`)是 `0x140000000`,因此反编译器里显示的函数地址往往长这样:`0x1412657a0`;
- **`RVA`(Relative Virtual Address,相对虚拟地址)**:减去镜像基址后的纯偏移,即 **`RVA = VA - ImageBase`**(例如 `0x1412657a0 - 0x140000000 = 0x12657a0`)。因为 Windows 的 ASLR(地址空间布局随机化)每次启动游戏都会把 `aces.exe` 加载到不同的内存基址,**仓库内所有补丁注释、`tools/re/cli.py` 参数以及生成的 `win64/wto_ws.cfg` 一律使用 RVA**;
- **运行时绝对指针(Runtime Pointer)**:游戏启动后,`wto_ws.dll`(见 `native/wto-net/src/local_mp_values.c`)通过 `(uint8_t *)GetModuleHandleW(NULL) + rva` 把 `wto_ws.cfg` 里的 RVA 换算成当次进程内的真实内存地址存入 `g_lmp`。
### 7. `features` 功能标签与三条「核心安全锁」(`ESSENTIAL_FEATURES`)
每个 `patches/exe/**/patch.jsonc`、`patches/gui/**/patch.jsonc` 和 `patches/native/*.jsonc` 都包含一个 `features` 字符串数组,标签以功能分组字母 `A-`..`K-` 开头(例如 `"G-Store"`、`"K-AI opponents and teammates"`、`"K-Kill, assist and capture scoring"`)。当游戏刚发布小版本更新、个别非关键补丁暂时失配时,启动器依靠这些标签清晰告知玩家「当前版本哪一项具体子功能暂不可用」,其余功能仍可正常游玩。
但其中有 **3 个定义在 `packages/patcher/src/essential-features.ts`(`ESSENTIAL_FEATURES`)中的硬阻断安全标签**例外:
1. **`A-Offline startup`**:离线副本能否启动的根基(例如跳过修改后 `.vromfs.bin` 的官方签名校验);
2. **`A-Isolation from the official game`**:与官方正版客户端的完全隔离(将用户配置存档改到独立 `WTOffline` 目录、注册表改到 `Software\WTOffline`、剥离反作弊启动器与崩溃上报);
3. **`A-No Gaijin connections`**:彻底阻断连向 Gaijin 官方服务器(例如将导入表 `WS2_32.dll` 替换为 `wto_ws.dll` 并在加载时强制挂载网络重定向钩子)。
只要带有上述任一标签的补丁未能成功定位和应用,`blockingFailures()` 就会**终止副本构建与启动**,防止离线客户端触碰玩家的线上正版数据或直连官方服务器,从而保护玩家的线上账号安全。
---
## 按你想做的事,直接定位代码目录
| 你想做什么 | 具体源码子目录 | 对口参考章节 |
| --- | --- | --- |
| 新增或修复机库动作路由(买车、研发、乘员、联队、贴花、战后结算等 `char` 接口) | `apps/server/src/char/actions/`(协议适配)+ `apps/server/src/<领域>/`(纯业务规则,如 `research/`、`modifications/`、`crew/`、`battle/`) | [架构分层与真实动作追踪](development-rules.md#server-layers-zh) |
| 修改玩家档案字段读写、新号初始资产或存档落盘格式 | `apps/server/src/profile/`、`apps/server/src/saves/`、`apps/server/src/storage/` | [存档层与原子写盘规范](development-rules.md#walkthrough-zh) |
| 从游戏原版数据包提取新的载具/经济/任务/本地化静态数据 | `apps/server/src/game-data/datasets/` | [三类数值与缓存数据集](development-rules.md#values-zh) |
| 调整离线版默认倍率、商店定价、补给箱权重、AI 重生数或上限参数 | `apps/server/tuning/*.jsonc` + `apps/server/src/tuning/` + 各领域 `*-tuning.ts` | [三类数值放哪里](development-rules.md#values-zh) |
| 修改本地内嵌网页商店、模拟交易所或服务器脚本模组运行时 | `apps/server/src/store/`、`apps/server/src/inventory/`、`apps/server/src/web-ui/`、`apps/server/src/mods/` | [服务器目录全景图](development-rules.md#server-layers-zh) |
| 修改桌面启动器界面、安装向导、存档管理页、模组管理页或更新器 | `apps/launcher/src/` | [检查命令清单](contributing.md#checks) |
| 修改离线副本构建管线、归档包改写、BLK 编解码、EXE 补丁引擎或模组加载器 | `packages/patcher/`、`packages/blk/`、`packages/vromfs/`、`packages/exepatch/`、`packages/mods/` | [仓库级单向依赖约定](development-rules.md#workspace-rule-zh) |
| 修改游戏内界面弹窗、按钮或结算页脚本(Quirrel `.nut`) | `patches/gui/<领域>/<名称>/` | [GUI 补丁完整范例](patches.md#gui-patches-zh) |
| 修改 `aces.exe` 机器码分支或只读常量字符串 | `patches/exe/<领域>/<名称>/` | [EXE 补丁 57 字节逐指令拆解](patches.md#exe-patches-zh) |
| 编写或修复 `wto_ws.dll` 局内 `LocalMP` 原生裁判钩子 | `patches/native/<模块>.jsonc` + `native/wto-net/src/` | [Native 模块 6 文件串联教程](patches.md#native-modules-zh) |
| 协助适配刚发布的《战争雷霆》客户端小版本更新 | `patches/versions/`、`scripts/record-game-version.ts` | [适配新版本客户端四步流程](patches.md#adapt-version-zh) |
---
<a id="english"></a>
[简体中文](#zh-cn) · English
[简体中文](#zh-cn) · English · [Online Docs](https://wto-project.net/dev-docs)
Start with a stock client you own and use it as a read-only source. Install the tools and dependencies listed in the [main README](../README.md#development). To launch the game for verification, prepare an offline copy outside the Steam library and a separate data directory, then verify isolation using the [development rules](development-rules.md#english).
Welcome to WTOffline development. This directory is written for **project contributors, client build adapters, and collaborators using AI coding assistants to reverse-engineer, investigate, and fix issues**. Even if you have never worked with the Dagor Engine or War Thunder internals before, these guides walk you through every layer from first principles.
| Task | Start here |
| --- | --- |
| Change the launcher or installer | [apps/launcher](../apps/launcher) |
| Change game rules, saves, or local services | [apps/server](../apps/server) |
| Change the game copy build or patch checks | [packages/patcher](../packages/patcher), [scripts](../scripts), [tools](../tools) |
| Write a client patch or adapt a new game build | [Patch guide](patches.md#english) and the [patch set](../patches) |
> **Just want to create vehicle stat tweaks, custom map pools, standalone 3D vehicles, or server script mods?** You do not need to modify WTOffline's core source code at all—head straight to the [Mod Development Docs (`mod-dev-docs`)](../mod-dev-docs/README.md#english) or the [online Mod Docs](https://wto-project.net/mod-docs).
Before submitting, follow the [review checklist](contributing.md#english), run the applicable [checks](contributing.md#checks), and record the results and in-game steps in the [PR template](templates/pull-request.md).
---
## Recommended Reading Order
Do not jump straight into raw byte patterns or disassembly offsets on your first visit. Reading the three core guides in this order builds the full mental model in 15–20 minutes:
1. **[Design Philosophy, Architecture & Engineering Rules](development-rules.md#english)** (**Start here**): Understand how the launcher, single-port local server (`apps/server`), and in-process Winsock/LocalMP bridge (`wto_ws.dll`) fit together; trace one real `cln_set_researchable` request end-to-end across all four server layers; learn where the three categories of numbers belong; review four real Good vs. Bad code comparisons; and grab the copy-paste prompt block for AI coding assistants.
2. **[Patch Authoring & Version Adaptation Guide](patches.md#english)**: Once you have confirmed that the local server and stock configuration genuinely cannot solve an issue, follow step-by-step instructions to unpack stock archives, disassemble `aces.exe` with `tools/re/cli.py`, and study un-elided real patches across `patches/gui/`, `patches/exe/`, and `patches/native/` + `native/wto-net/`.
3. **[Environment Setup, Traffic Debugging & PR Guide](contributing.md#english)**: Set up the Windows x64 toolchain, inspect auto-decoded readable BLK payloads under `<data-dir>/logs/` to pinpoint bugs in minutes, run the required verification commands for your change type, and fill out the [PR template](templates/pull-request.md).
---
<a id="glossary-en"></a>
## Core Concepts & Glossary
You will encounter these War Thunder and WTOffline terms throughout the codebase and documentation. Here is what each one means in plain language:
### 1. `vromfs.bin` (Dagor Virtual Read-Only File System Archive)
Instead of shipping tens of thousands of loose scripts and config files on disk, War Thunder bundles them into `.vromfs.bin` archives. Each archive has two layers: an outer container (Zstandard compression with lightweight XOR obfuscation, an MD5 digest of the inner image, and a 256-byte signature tail) and an inner image (a lowercase relative path table, byte offsets, optional SHA-1 digests, plus an optional shared name map `nm` and `.dict` zstd dictionary). `@wto/vromfs` (`readArchive`, `getFile`, `putFile`, `writeArchive`) reads and repacks these archives losslessly.
Use this lookup table whenever you need to find where a stock script, config, or asset lives:
| Archive path (relative to game root) | What it stores | How WTOffline uses it |
| --- | --- | --- |
| `char.vromfs.bin` | Tech-tree layout (`config/shop.blk`), per-vehicle prices, RP, repair costs, and modifications (`config/wpcost.blk`), global economy and BR formulas (`config/warpoints.blk`, `config/rank.blk`), new-account profile template (`config/default_user.blk`), mission lists and unlock definitions (`config/mislist.blk`, `config/pve_awards.blk`, `config/unlocks.blk`), camos/decals/decorators/classic items (`config/skins.blk`, `config/decals.blk`, `config/attachable.blk`, `config/items.blk`), and `config/network.blk` | `packages/patcher` rewrites backend URLs and hidden-vehicle visibility during copy builds; `apps/server` extracts most economy, tech-tree, unlock, and mission datasets from it at startup |
| `aces.vromfs.bin` | Match gameplay and killstreak rules (`config/gameplay.blk`), UI config and store bundle GUID mappings (`config/gui.blk`), workshop recipes (`config/workshop.blk`), and all vehicle flight/damage/weapon preset files (`gamedata/flightmodels/…`, `gamedata/units/…`) | `packages/patcher` injects offline store bundle GUIDs; `apps/server` extracts spawn rules, bundle mappings, and weapon presets |
| `gui.vromfs.bin` | All in-game hangar, modal, store, debriefing, and HUD Quirrel scripts (`scripts/**/*.nut`) and layout templates (`.blk` / `.css`) | `patches/gui/` applies minimal surgical text replacements to UI scripts when building the offline copy |
| `mis.vromfs.bin` | Multiplayer and single-player mission logic, spawn zones, capture points, and victory rules (`gamedata/missions/**/*.blk`) | `apps/server` scans it at startup (`multiplayer-missions` dataset) to build matchmaking mission definitions |
| `lang.vromfs.bin` | Semicolon-separated localization CSV tables (`lang/units.csv`, `lang/menu.csv`, `lang/unlocks_achievements.csv`, etc.) | `apps/server` extracts localized vehicle, country, and item names for the in-game web store, marketplace, and launcher |
| `ui/atlases.vromfs.bin` | Tech-tree vehicle silhouettes and country flags in SVG format (`gameuiskin/*.svg`) | `apps/server` extracts icons for gift/premium/market vehicles and flags (`web-icons` dataset) for the local web store and marketplace |
| `ui/images.vromfs.bin` | UI raster artwork, bundle cover images, and pilot avatar textures (`images/**`) | `apps/server` serves store/marketplace item artwork and renders player profile icons for the launcher's saves page |
### 2. `BLK` / `DataBlock` (Dagor Typed Hierarchical Data Format)
`BLK` (named `DataBlock` in Dagor Engine C++ code) is the typed tree format used everywhere in War Thunder for configs, network payloads, and player profiles. Think of it as a tree of named blocks and typed key-value parameters (`:i` integers, `:r` floats, `:t` strings, `:b` booleans, `:p3` 3D vectors, `:m` matrices, etc.). You will encounter four binary/wire representations in WTOffline, all handled by `@wto/blk` (`decodeBlk`, `encodeBlk`, `formatBlkText`, `parseBlkText`):
- **Slimmed binary BLK inside `.vromfs.bin`**: `.blk` files inside `char.vromfs.bin` and `aces.vromfs.bin` strip repeated key names into the archive's shared name map `nm` (and may compress payloads with an archive `.dict` zstd dictionary), decoded by passing `SharedNameContext` to `decodeBlk`;
- **Framed binary BLK on `char` HTTP exchanges**: Single-document HTTP payloads prefixed with a 1-byte compression marker (e.g., `0x69` / `'i'` for uncompressed binary BLK, or zlib/zstd markers);
- **`PBBD` batch streams**: Multi-chunk binary streams (magic `"PBBD"`) used by `online_storage` (`cln_bulk_set_gblk`) when uploading keybindings and cloud settings, where each chunk carries an embedded BLK block;
- **Self-contained binary BLK on disk**: Player profiles saved at `<data>/saves/<userId>/profile.blk` via `encodeBlk()`, preserving every parameter's exact scalar/vector type so the game client never misinterprets ints as floats or vice versa.
### 3. The Four Gaijin Backend Services Emulated Locally
A live War Thunder client talks to several distinct backend services rather than a single monolithic API. `apps/server` emulates all four locally on a single `127.0.0.1:<port>` listener:
- **`yuplay2` (Login & Entitlement APIs, `login/`, `store/`)**: Handles form-encoded credential sign-in (`POST /login.php`), issues local session tokens and `userId`s, and serves store/redeem-code web endpoints;
- **`char` (Character Server, `char/`)**: The primary hangar RPC service (`char-*.warthunder.com`). Requests specify the operation via the `action` HTTP header (such as `cln_get_user_stat`, `cln_buy_aircraft`, `cln_set_researchable`, `cln_update`) and identify the player via `uidhint`, exchanging binary BLK payloads for full profile sync, tech-tree research, vehicle/modification/crew purchases, squadrons, cloud settings, and post-battle settlement;
- **`matching` (Binary Matchmaking & Session RPC, `matching/`)**: A persistent binary TCP protocol (first byte `0x01`, 9-byte header + LZ4-compressed frame, stream-encrypted after handshake) that serves game-mode lists, manages queues and squad state, and dispatches complete battle launch configurations (map, weather, AI bot rosters, `customScoreParams`, etc.);
- **`inventory` (External Inventory & Marketplace Service, `inventory/`)**: Emulates `inventory-proxy-*.gaijin.net/char` (`GetInventory`, `GetItemDefsClient`, `GetItemPrices`, `GetItemDefChances`, `ExchangeItems`). Unlike `char`, the client's `charsq` subsystem parses raw HTTP bodies directly as UTF-8 JSON and verifies RSA content signatures—powering supply chests, vehicle coupons, workshop crafting, and the simulated marketplace.
### 4. `LocalMP` (Why WTOffline Needs Both `apps/server` AND `wto_ws.dll`)
A natural question for newcomers is: **If `apps/server` already emulates Gaijin's backend in TypeScript, why do we also compile `native/wto-net/` into `wto_ws.dll` and load it inside `aces.exe`?**
The answer comes down to what Gaijin kept vs. stripped in the retail game client:
- Retail `aces.exe` still contains an in-process **`LocalMP` session mode (`mp_is_host == 1 && mp_is_local_mp == 1`)** capable of running full physics, ballistics, damage models, and AI piloting/driving locally—meaning WTOffline does not have to reimplement a Dedicated Server physics engine from scratch;
- **However**, when building retail `aces.exe`, Gaijin compiled out many **Dedicated Server battle referee handlers** that normally run only in the cloud during live matches: **spawning player vehicles and weapon loadouts on selection, granting `BotSystem` permission to spawn AI vehicles, awarding kill/assist/capture scoreboard points, running Ground Arcade killstreak air events, triggering nuclear instant victories, and filtering barrel/breech/part-damage HUD notices so enemy hits are not misdelivered to the local player**;
- Consequently, the two halves have a crisp boundary: **`apps/server` owns everything before and after a battle** (login, hangar progression, economy, store/market, matchmaking setup, post-battle Silver Lions/RP settlement, and atomic save persistence), while **`wto_ws.dll` hooks `aces.exe` in-process via MinHook**—redirecting hardcoded outbound Winsock traffic to `127.0.0.1` and restoring stripped host-side referee logic **during** live `LocalMP` battles via modular `local_mp_*` bridges.
### 5. `Quirrel (.nut)` & the `sq.exe` Bytecode Compiler
UI scripts inside `gui.vromfs.bin` (`.nut` files) are written in **[Quirrel](https://quirrel.io/)**, Gaijin's Squirrel-derived scripting language with strict lexical scoping. When logging into the hangar, the client preloads and compiles UI script modules en masse.
Why is running `wtotools check-gui` with the matching `sq.exe` compiler mandatory whenever you touch `patches/gui/`, instead of eyeballing diffs or running an AST-only syntax check? Because Quirrel's `compilestring` bytecode compiler enforces lexical binding rules that AST parsers ignore:
- Declaring a `local` identifier that collides with a constant imported via `from ... import *` at the top of the file;
- Referencing an unbound local/module function before its declaration;
- Using a Quirrel reserved keyword (most notoriously `base`) as a variable name.
Any of those mistakes looks syntactically innocent on paper, yet aborts module compilation inside the game client and **freezes login indefinitely on the `"Loading..."` spinner**. `wtotools check-gui` applies every GUI patch in memory and compiles each modified `.nut` file to Quirrel bytecode via `sq.exe`, catching 100% of lexical and constant-binding errors before commit.
### 6. `RVA` vs. Virtual Address (`VA`) vs. Runtime Pointer
Keep these three address forms straight whenever you read disassembly or write `patches/`:
- **`VA` (Virtual Address)**: When you open 64-bit `aces.exe` in Ghidra or IDA, the default PE `ImageBase` is `0x140000000`, so addresses appear as `0x1412657a0`;
- **`RVA` (Relative Virtual Address)**: Offset from the image base, i.e., **`RVA = VA - ImageBase`** (`0x1412657a0 - 0x140000000 = 0x12657a0`). Because Windows ASLR loads `aces.exe` at a fresh random base address on every launch, **every `patches/` comment, `tools/re/cli.py` argument, and `win64/wto_ws.cfg` entry uses RVAs exclusively**;
- **Runtime Pointer**: When the game starts, `wto_ws.dll` (`native/wto-net/src/local_mp_values.c`) adds the live module base `(uint8_t *)GetModuleHandleW(NULL) + rva` and stores the resulting process pointer in `g_lmp`.
### 7. `features` Tags & the Three Essential Safety Locks (`ESSENTIAL_FEATURES`)
Every definition in `patches/exe/**/patch.jsonc`, `patches/gui/**/patch.jsonc`, and `patches/native/*.jsonc` lists one or more `features` tags prefixed by inventory category (`A-` through `K-`, such as `"G-Store"`, `"K-AI opponents and teammates"`, or `"K-Kill, assist and capture scoring"`). If a minor client update breaks an optional patch, the launcher uses these tags to show the player exactly which non-essential gameplay feature is degraded while still letting them play.
Three tags defined in `packages/patcher/src/essential-features.ts` (`ESSENTIAL_FEATURES`) are **hard-blocking safety locks**:
1. **`A-Offline startup`**: Required for the offline copy to boot at all (e.g., bypassing `.vromfs.bin` pack signature checks so modified archives load);
2. **`A-Isolation from the official game`**: Keeps the offline copy completely separate from the official client (redirecting user saves/settings to `WTOffline`, registry keys to `Software\WTOffline`, and disabling the anti-cheat launcher and crash reporter);
3. **`A-No Gaijin connections`**: Guarantees zero traffic reaches Gaijin's live servers (e.g., rewriting the PE import descriptor from `WS2_32.dll` to `wto_ws.dll` and enforcing Winsock redirection hooks on attach).
If **any** patch carrying one of these three tags fails to resolve, `blockingFailures()` immediately aborts copy installation and launch—protecting the player's official online installation and account from ever being touched.
---
## Jump Straight to Your Task
| What you want to do | Specific codebase directories | Primary reference |
| --- | --- | --- |
| Add or fix hangar actions (research, purchases, crews, squadrons, decals, post-battle settlement, etc.) | `apps/server/src/char/actions/` (wire handlers) + `apps/server/src/<domain>/` (pure rules: `research/`, `modifications/`, `crew/`, `battle/`, etc.) | [Server Layers & Action Walkthrough](development-rules.md#server-layers-en) |
| Change player profile fields, new-account defaults, or save persistence / format upgrades | `apps/server/src/profile/`, `apps/server/src/saves/`, `apps/server/src/storage/` | [Persistence & Atomic Writes](development-rules.md#walkthrough-en) |
| Extract new static vehicle, economy, mission, or localization data from stock archives | `apps/server/src/game-data/datasets/` | [Three Categories of Values](development-rules.md#values-en) |
| Adjust offline reward multipliers, store prices, supply-chest weights, AI respawn counts, or limits | `apps/server/tuning/*.jsonc` + `apps/server/src/tuning/` + `<domain>/*-tuning.ts` | [Three Categories of Values](development-rules.md#values-en) |
| Work on the in-game web store, simulated marketplace, or server script mod runtime | `apps/server/src/store/`, `apps/server/src/inventory/`, `apps/server/src/web-ui/`, `apps/server/src/mods/` | [Server Directory Map](development-rules.md#server-layers-en) |
| Change the desktop launcher UI, install wizard, saves manager, mods page, or auto-updater | `apps/launcher/src/` | [Required Check Commands](contributing.md#checks-en) |
| Modify copy building, archive patching, BLK/vromfs codecs, EXE patch engine, or mod loader | `packages/patcher/`, `packages/blk/`, `packages/vromfs/`, `packages/exepatch/`, `packages/mods/` | [Workspace Dependency Rule](development-rules.md#workspace-rule-en) |
| Patch in-game UI modals, buttons, or debriefing Quirrel scripts (`.nut`) | `patches/gui/<domain>/<name>/` | [GUI Patches Full Example](patches.md#gui-patches-en) |
| Patch machine instructions or constant `.rdata` strings in `aces.exe` | `patches/exe/<domain>/<name>/` | [EXE Patch 57-Byte Anatomy](patches.md#exe-patches-en) |
| Write or fix `wto_ws.dll` in-process `LocalMP` battle host hooks | `patches/native/<module>.jsonc` + `native/wto-net/src/` | [Native Modules 6-File Wiring](patches.md#native-modules-en) |
| Adapt WTOffline to a newly released minor War Thunder client build | `patches/versions/`, `scripts/record-game-version.ts` | [Adapting a New Client Build](patches.md#adapt-version-en) |
+254 -46
View File
@@ -1,79 +1,122 @@
# Contributing
# 环境搭建、流量调试与提交指南 / Contributing Guide
<a id="zh-cn"></a>
简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn)
## 提交前自查
这篇指南带你从零搭好本地开发环境、用内置的自动解码流量日志快速定位机库与对局问题,并在发起 Pull Request 前跑通对应的真实工程检查。
- 改动只解决一个目标。实现、配置、补丁说明和相关开发文档一致。提交标题用英文 `type(scope): description`,scope 用小写模块名,仓库级改动用 `repo`。破坏兼容时用 `type(scope)!: description`,并在 `BREAKING CHANGE:` 脚注说明影响和处理方式。正文交代原因、依据和验证结果,代码注释也用英文。联署留给实际协作的开发者。
- 游戏行为的判断有目标版本和一手出处。新动作写清客户端怎样发请求、怎样读取应答。客户端改动登记到对应补丁或构建模块,并说明为何需要。涉及新数值时,按[三类数值规则](development-rules.md#数值和数据来源)检查来源、配置和校验。
- 检查模块职责、依赖方向和重复逻辑。涉及账号、余额和档案时,检查错误输入、写盘顺序,以及多个账号之间的数据隔离。选择奖品或其他数据项时,按明确规则排序和筛选。
- 只做类型、补丁、构建和可运行检查。功能验收由人使用隔离副本在游戏里做。注明实际执行过的命令、对应版本和结果。还要实机核对时写出入口、操作和预期现象。商城或交易所改动覆盖内置浏览器打开、相关操作和关窗后的档案刷新。
- 提交前看一遍差异,确认来源、路径、记录和玩家数据可以分享。用 [PR 模板](templates/pull-request.md) 提供复核所需的信息。
---
<a id="english"></a>
## 1. 开发环境准备
[简体中文](#zh-cn) · English · [Dev Docs](README.md#english)
你需要一台 **Windows x64** 电脑,并安装以下基础工具:
## Review before submitting
1. **Node.js 24+**:仓库内的 CLI 脚本与 `apps/server` 直接以 Node 24 原生类型剥离模式运行 `.ts` 源码(Node 20/22 旧版本会因 `.ts` 扩展名或模块解析报错)。
2. **Visual Studio 2022 或 Build Tools(勾选「使用 C++ 的桌面开发」x64 工具链与 CMake)**:用于通过 `cl.exe` 编译 `native/wto-net/`(生成 `wto_ws.dll`),以及一次性编译 Quirrel 字节码检查器 `sq.exe`。
3. **Python 3.12+**:用于运行补丁校验器 `wtotools`、静态逆向工具 `tools/re/cli.py` 与客户端 `.clog` 日志解密命令。
4. **一份玩家本人合法持有的官方原版客户端(严格保持只读)**,以及在 Steam 游戏库目录之外单独准备的**离线副本目录**与**本地服务器数据目录**。
- Keep one purpose per change. Update the affected implementation, configuration, patch notes, and developer docs together. Use English `type(scope): description` commit subjects with a lowercase module scope or `repo` for repository-wide changes. For a breaking change, use `type(scope)!: description` and a `BREAKING CHANGE:` footer that explains the impact and what to do. Explain the reason, evidence, and verification in the commit body. Use English comments and reserve co-author credits for developers who actually collaborated.
- Cite the target build and primary evidence for game behavior. For new actions, explain how the client sends the request and consumes the reply. Register client edits in their patch or build module and explain why they are needed. For new values, check the source, tuning, and validation using the [three kinds of values](development-rules.md#data-and-tuning).
- Check module responsibilities, dependency direction, and reuse. For accounts, currency, and saves, check bad inputs, when updates reach disk, and separation between accounts. Use explicit ordering and selection rules for prize pools and other lists.
- Limit automated checks to type, patch, build, and startup checks. Functional acceptance is performed by a person in an isolated game copy. Report the commands actually run, the client builds, and the results. For pending in-game checks, give the entry point, action, and expected result. Store and marketplace changes cover opening the embedded browser, the affected action, and the profile refresh on close.
- Review the diff for shareable sources, paths, records, and player data. Use the [PR template](templates/pull-request.md) to provide enough detail for review.
首次克隆仓库后,在仓库根目录依次执行:
```powershell
# 1. 安装工作区依赖
npm install
# 2. 编译进程内网络重定向与 LocalMP 桥接库 -> build\native\wto_ws.dll
powershell -NoProfile -File .\native\wto-net\build.ps1
# 3. 下载桌面启动器所需的 Electron 二进制运行时
node node_modules/electron/install.js
# 4. 初始化 Python 虚拟环境并安装本地补丁/逆向工具包 wtotools
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ./tools
```
如果你想脱离桌面启动器,直接从命令行快速构建一份离线副本并以前台模式启动本地服务器查看实时输出(注意:**`--game` 在构建时传只读原版目录、启动服务器时传离线副本目录,两条命令的 `--data` 与 `--port` 必须完全一致**):
```powershell
node scripts/build-game-copy.ts --game "<原版目录>" --out "<离线副本目录>" --data "<独立数据目录>" --port 27015
node apps/server/src/cli.ts --game "<离线副本目录>" --data "<独立数据目录>" --port 27015
```
---
<a id="debugging-zh"></a>
## 2. 怎么调试与查日志(排查 Bug 最快的路径)
排查机库动作报错、购买失败、匹配卡住或对局计分异常时,**千万不要靠盲猜客户端发了什么包**。WTOffline 在四处关键节点都留有可直接阅读的诊断日志:
### 2.1 本地服务器流量日志:`<数据目录>/logs/<启动时间戳>/`(第一站!)
每次启动 `apps/server`,`TrafficLog`(`apps/server/src/traffic-log/traffic-log.ts`)都会在 `<数据目录>/logs/` 下新建一个带 ISO 时间戳的会话文件夹,里面包含两部分:
1. **`requests.jsonl`(全量请求索引流)**
每行是一条 JSON 记录,按全局递增序号 `id` 记录每一次 HTTP 交互(`kind: "http"`)、每一条匹配服双向消息(`kind: "matching"`)、被拒绝的 WebSocket 升级请求(`kind: "websocket"`)以及连接开关事件:
- **一秒定位未实现接口**:直接在 `requests.jsonl` 中搜索 `"unhandled":true`(或看终端输出末尾带 `[UNHANDLED]` 标记的行),就能立刻抓出客户端刚发了哪个尚未挂载处理器的 `char` 动作、`yuplay2` 路径或 `matching` 消息!
- 每条记录中的 `files` 字段直接指明该次请求与响应对应的负载文件名。
2. **`bodies/` 子目录(自动解码的可读明文负载!)**
每个序号 `id`(补零至 6 位,如 `000042`)按需生成以下文件:
- `000042.req.bin` / `000042.resp.bin`:原始线上传输字节(登录表单中的密码字段会自动脱敏);
- **`000042.req.txt` / `000042.resp.txt`**:**自动解包并格式化好的可读明文 BLK 文本**(无论是带 `0x69` / zlib / zstd 标记的 `char` 二进制 BLK,还是 `cln_bulk_set_gblk` 上传的 `PBBD` 多段批处理流,都会自动转成缩进清晰的文本 BLK!)或 UTF-8 JSON 文本——你无需手写任何解包脚本,直接用编辑器打开 `.txt` 就能看清每一个字段与类型;
- **`000042.matching-in.json` / `000042.matching-out.json`**:解密并解压后的匹配长连接双向 RPC 消息(`in` 为客户端发来,`out` 为本地服务器下发)。
### 2.2 其余三类配套诊断日志
- **进程内钩子与 `LocalMP` 日志:`<离线副本目录>/win64/wto_ws.log`**
由 `wto_ws.dll` 每次启动游戏时重写。记录本地服务器端口号、每一次域名拦截与 Socket 连接重定向结果、`wto_ws.cfg` 与当前 `aces.exe` 的 PE 头校验结果,以及 **11 个 `local_mp_*` 模块中哪些成功安装、哪些因缺少 `wto_ws.cfg` 键值被优雅跳过**(并打印缺失的具体键名)。排查局内不刷 AI、选车无响应、记分牌为 0 或连杀飞机异常时先看这里。
- **游戏引擎客户端日志:`<离线副本目录>/.game_logs/*.clog`**
Dagor 引擎原生日志,记录 Quirrel 脚本编译/运行期报错、进机库卡死在「正在加载…」的具体栈信息、任务脚本报错与资源缺失。由于 `.clog` 是二进制异或加密格式,直接用 `tools/re/cli.py` 解密成纯文本再查阅:
```powershell
.\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<离线副本目录>\.game_logs\<最新文件>.clog" --out "<临时目录>\game.clog.txt"
```
- **桌面启动器日志:`launcher.log`**
在启动器界面打开「设置 → 诊断 → 打开日志目录」即可查看,记录副本构建、补丁包校验、子进程启停与更新器状态。
---
<a id="checks"></a>
## 检查命令 / Check commands
## 3. 提交前必跑的工程检查命令(按改动范围对照执行)
在仓库根目录执行适用于本次改动的命令。尖括号内的占位内容换成自己的实际值。所有游戏输入文件用只读原版来源,构建输出用单独目录。
WTOffline **不要求也不提倡编写庞大的模拟(Mock)单元测试套件**,而是要求你按实际触碰的代码目录,跑通下面对应的**真实编译器、补丁字节核对与 Quirrel 字节码检查**;最终交互体验则在独立隔离副本中进游戏实机验收。
Run the applicable commands from the repository root. Replace placeholders in angle brackets with your own values. Use read-only stock inputs and a separate build output directory.
| 改动 / Change | 检查 / Check |
| 你修改了哪里 | 提交前必须跑通的检查 |
| --- | --- |
| 共用库或本地服务器 / Shared packages or local server | 根目录类型检查,必要时用独立数据目录确认服务器能启动<br>Root type check and server startup with separate data when applicable |
| 启动器 / Launcher | 启动器的类型检查和构建<br>Launcher type check and build |
| exe 补丁 / Exe patch | `check-patches` 核对定位、原字节和源码<br>Verify matches, original bytes, and the patch source with `check-patches` |
| 修改 `patch.jsonc` 或 GUI 片段 / Edits to `patch.jsonc` or GUI fragments | 完整 `check-gui` 检查所有 GUI 补丁的命中、词法作用域和字节码编译<br>Run the full `check-gui` location, lexical scope, and bytecode checks |
| Native 或构建流程 / Native or copy build | Native 改动先编译 DLL,再用临时输出目录构建,核对定位和可用性<br>Build the DLL for native changes, then check locations and availability with a temporary copy build |
| 版本适配 / New client build | 生成版本核对记录,完成适用的补丁和构建检查,再走实机验收<br>Generate a version record, run the applicable checks, then perform in-game acceptance |
| 共享库 `packages/*`、本地服务器 `apps/server` 或 `scripts/*` | 根目录 `npm run typecheck`;若动了服务端启动逻辑或 `tuning/*.jsonc`,用临时数据目录启动一次 `apps/server/src/cli.ts` 确认数据集提取与配置校验零报错 |
| 桌面启动器 `apps/launcher` | 启动器 `typecheck` + `electron-vite build`;若增改了界面多语言词条,确认 `en.json` 与 `zh-CN.json` 键名完全对齐 |
| `patches/exe/`(任何 `patch.jsonc`) | `wtotools check-patches`(验证特征码唯一命中、`expect_original` 匹配,且 `asm`/`data` 编译结果与 `bytes` 逐字节一致) |
| `patches/gui/`(任何 `patch.jsonc` 或 `.nut` 片段) | **完整** `wtotools check-gui`(调用 `sq.exe` 执行 `compilestring` 词法作用域与字节码编译检查) + 临时副本构建确认 `gui-patch-definition.ts` Schema 无未知键报错 |
| `native/wto-net/` 或 `patches/native/` | MSVC `native\wto-net\build.ps1`(`/W4` **零警告**)+ 临时目录 `scripts/build-game-copy.ts` 确认所有原生站点全部解析就绪 |
| 适配客户端新版本(`patches/versions/`) | `scripts/record-game-version.ts` + 上述全部适用检查 + **在隔离副本中实机登录进机库并完成 `LocalMP` 对局验收后**,方可提交 `patches/versions/<版本号>.jsonc` |
常用检查命令汇总(均在仓库根目录执行,将尖括号替换为你的本地路径):
```powershell
# TypeScript / launcher
# 1. TypeScript 类型与语法剥离约束检查(校验 .ts 后缀、import type、erasableSyntaxOnly 等)
npm run typecheck
npm run typecheck --workspace "@wto/launcher"
npm run build --workspace "@wto/launcher"
# Patch tool setup
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ./tools
# 2. EXE 与 GUI 补丁核对(输入源必须是只读原版客户端目录!)
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<原版目录>\win64\aces.exe"
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
# Patch verification
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-client-dir>\win64\aces.exe"
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-client-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
# Native build and copy build check
# 3. Native DLL 编译(MSVC /W4 零警告)与完整离线副本试构建
powershell -NoProfile -File .\native\wto-net\build.ps1
node scripts/build-game-copy.ts --game "<stock-client-dir>" --out "<temporary-output-dir>" --data "<separate-data-dir>" --port <port>
node scripts/build-game-copy.ts --game "<原版目录>" --out "<临时副本目录>" --data "<临时数据目录>" --port 27015
# Version adaptation
node scripts/record-game-version.ts --game "<stock-client-dir>"
# 4. 客户端版本适配记录核对
node scripts/record-game-version.ts --game "<原版目录>"
```
实际启动时,离线副本需要包含完整游戏文件,本地服务器与副本构建使用同一端口和数据目录。版本记录命令会写入 `patches/versions/`,按[补丁指南](patches.md#核对版本与提交)核对后再提交。[服务器启动命令](../README.md#构建副本并启动服务器)
For an actual launch, use a full offline copy and match the server's port and data directory to the copy build. The record generator writes to `patches/versions/`. Follow the [patch guide](patches.md#check-versions-and-submit) before committing a record. [Server startup command](../README.md#build-the-copy-and-start-the-server)
<a id="quirrel"></a>
## 构建 Quirrel 编译器 / Build the Quirrel compiler
### 一次性编译 Quirrel 字节码检查器 `sq.exe`(注意 `--sq` 路径参数!)
GUI 检查使用 `sq.exe` 调用 `compilestring`,检查词法作用域和字节码编译。成功时会报告所有改动脚本都编译通过。以下步骤使用 Visual Studio 2022 的 x64 C++ 工具和 CMake 3.31。将实际编译器路径传给 `check-gui --sq`。[Quirrel 源码版本](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)
The GUI checker uses `sq.exe` and `compilestring` to check lexical scope and compile bytecode. A passing run reports successful compilation for all changed scripts. These steps use the Visual Studio 2022 x64 C++ tools and CMake 3.31. Pass the path to your compiler to `check-gui --sq`. [Quirrel source revision](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)
`check-gui` 需要调用与《战争雷霆》客户端同代的官方 Quirrel 编译器(固定在 [Quirrel 仓库提交 `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe`](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe))。使用 Visual Studio 2022 C++ 工具链与 CMake 编译一次即可长期复用:
```powershell
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
@@ -81,3 +124,168 @@ git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec7
cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
cmake --build build/quirrel-cli --config Release --target sq
```
> **关于 `--sq` 参数的重要说明**:`wtotools check-gui` 在不传 `--sq` 时的默认查找路径是 `build/quirrel-check/sq.exe`(见 `tools/src/wtotools/cli/gui_commands.py`),而上面这条 Visual Studio CMake 多配置构建命令会把可执行文件生成在 **`build\quirrel-cli\bin\Release\sq.exe`**。因此运行 `check-gui` 时请像上方命令一样显式传入 `--sq "build\quirrel-cli\bin\Release\sq.exe"`(或者手动把生成的 `sq.exe` 复制一份到 `build\quirrel-check\sq.exe`)。
---
## 4. 提交消息规范与 PR 自查清单
- **一笔 PR 只聚焦一个清晰目标**:不要在修某个结算 Bug 的 PR 里顺手重排无关目录或大面积格式化其他文件。
- **全英文约定式提交(Conventional Commits)与英文注释**:
- 提交标题格式:`type(scope): concise summary`(例如 `fix(battle): credit Ground Arcade air event kills from AI victims`、`feat(launcher): show missing optional patch features`;仓库级工程或文档改动用 `repo` 或 `docs`);
- 若包含破坏性变更,在 `scope` 后加 `!` 并在正文末尾附上 `BREAKING CHANGE:` 说明;
- 代码注释、补丁顶部三行说明、补丁 `title` 与 Git 提交消息正文统一使用英文;
- `Co-authored-by` 尾注仅用于署名实际参与协作的人类开发者,不要填写 AI 模型或编程工具。
- **发起 PR 前最后 5 项自检**:
1. 对照 [开发规范第 4 节](development-rules.md#good-vs-bad-zh):零硬编码 RVA/结构体偏移/`_ReturnAddress()`、零手抄游戏静态数值、零越层 I/O;
2. 核对语法与 Schema 细节:TS 相对导入全部带 `.ts` 后缀且遵守 `erasableSyntaxOnly`;补丁 JSONC 无多余未知键(特别是 `patches/gui/**/patch.jsonc` 未误写 `requires`);带尾随立即数的 `rel32` 捕获已显式填写 `"end"`;
3. 涉及货币、研发、库存或存档改动时,确认所有修改均通过 `PlayerProfiles` / `SaveStore` **先完成原子写盘再向客户端返回响应**,且多账号目录严格隔离;
4. 通读一遍 `git diff`,确认没有带入任何本机个人路径、原版游戏文件、解包产物、测试存档或未脱敏日志;
5. 完整填写 [PR 模板](templates/pull-request.md),如实列出实际运行过的命令与输出结论,并把「已在隔离副本实机验收的界面步骤」与「尚待维护者实机验收的步骤」明确区分开。
---
<a id="english"></a>
[简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english)
This guide walks you through setting up a Windows x64 development environment, diagnosing bugs rapidly with auto-decoded local traffic logs, and running the required verification checks before opening a Pull Request.
---
## 1. Environment Setup
You need a **Windows x64** machine with:
1. **Node.js 24+**: Repository CLI scripts and `apps/server` execute `.ts` files directly via Node 24's native type-stripping (older Node 20/22 releases will fail on `.ts` import specifiers).
2. **Visual Studio 2022 or Build Tools (with "Desktop development with C++" x64 tools & CMake)**: Used by `native/wto-net/build.ps1` (`cl.exe`) to build `wto_ws.dll` and once to compile the Quirrel bytecode checker `sq.exe`.
3. **Python 3.12+**: Used for the patch verifier (`wtotools`), static disassembler (`tools/re/cli.py`), and `.clog` log decryptor.
4. **Your own legitimate stock War Thunder installation (kept strictly read-only)**, plus a separate **offline copy folder** and **server data folder** located outside any Steam library directory.
After cloning the repository, bootstrap everything from the repo root:
```powershell
# 1. Install npm workspace dependencies
npm install
# 2. Compile the Winsock redirector & LocalMP host bridge -> build\native\wto_ws.dll
powershell -NoProfile -File .\native\wto-net\build.ps1
# 3. Download the Electron runtime binary for the desktop launcher
node node_modules/electron/install.js
# 4. Create the Python virtual environment and install `wtotools` in editable mode
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ./tools
```
To build an offline game copy and run the local server directly from the terminal without the desktop launcher (note: pass the **read-only stock folder** to `build-game-copy.ts --game`, pass the **offline copy folder** to `cli.ts --game`, and keep `--data` and `--port` identical across both commands):
```powershell
node scripts/build-game-copy.ts --game "<stock-dir>" --out "<copy-dir>" --data "<data-dir>" --port 27015
node apps/server/src/cli.ts --game "<copy-dir>" --data "<data-dir>" --port 27015
```
---
<a id="debugging-en"></a>
## 2. Traffic Log Debugging & Diagnostic Logs
Never guess what payload the game client sent or why a hangar action failed—WTOffline records human-readable diagnostics across four log locations:
### 2.1 Local Server Traffic Logs: `<data-dir>/logs/<ISO-timestamp>/` (Check Here First!)
Every time `apps/server` starts, `TrafficLog` (`apps/server/src/traffic-log/traffic-log.ts`) creates a timestamped session folder under `<data-dir>/logs/` containing:
1. **`requests.jsonl` (Indexed Exchange Log)**
One JSON line per HTTP request/response (`kind: "http"`), matching message (`kind: "matching"`), refused WebSocket upgrade (`kind: "websocket"`), or TCP connection open/close, numbered sequentially by `id`:
- **Spot missing endpoints instantly**: Search `requests.jsonl` for `"unhandled":true` (or look for `[UNHANDLED]` in the server console) to immediately see any unimplemented `char` action, `yuplay2` endpoint, or `matching` RPC!
- Each entry's `files` object points directly to its corresponding payload files inside `bodies/`.
2. **`bodies/` Subdirectory (Auto-Decoded Readable BLK & JSON Payloads!)**
Numbered by zero-padded sequence ID (e.g., `000042.*`):
- `000042.req.bin` / `000042.resp.bin`: Raw wire bytes (with sign-in passwords automatically redacted);
- **`000042.req.txt` / `000042.resp.txt`**: **Automatically unpacked and formatted readable BLK text** (covering `0x69`/zlib/zstd-framed `char` binary BLK payloads as well as multi-chunk `PBBD` streams on `cln_bulk_set_gblk`!) or UTF-8 JSON/form text—open any `.txt` file directly in your editor to inspect exact block trees and parameter types without manual decoding;
- **`000042.matching-in.json` / `000042.matching-out.json`**: Decrypted, LZ4-decompressed inbound (`in`) and outbound (`out`) `matching` binary RPC messages.
### 2.2 The Other Three Diagnostic Logs
- **Native Hook & `LocalMP` Log: `<copy-dir>/win64/wto_ws.log`**
Rewritten on every client launch by `wto_ws.dll`. Logs the active local port, every locally answered hostname and redirected/refused socket, whether `wto_ws.cfg` matched the running `aces.exe` PE `TimeDateStamp` / `SizeOfImage`, and **which of the 11 `local_mp_*` modules installed vs. were skipped** (naming the exact missing `wto_ws.cfg` key when skipped), plus live battle referee events.
- **Dagor Client Log: `<copy-dir>/.game_logs/*.clog`**
Records Quirrel script compilation/runtime errors, exact call stacks behind `"Loading..."` login hangs, mission errors, and missing assets. Because `.clog` files are XOR-encrypted binary logs, decrypt them to plain text with `tools/re/cli.py`:
```powershell
.\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<copy-dir>\.game_logs\<latest>.clog" --out "<temp-dir>\game.clog.txt"
```
- **Desktop Launcher Log: `launcher.log`**
Accessible from Launcher **Settings -> Diagnostics -> Open log folder**, covering copy builds, patch-pack checks, server process lifecycle, and updater activity.
---
<a id="checks-en"></a>
## 3. Required Checks Before Submitting
WTOffline **does not require or encourage large mock unit test suites**. Instead, run the real compiler, binary-patch, and Quirrel bytecode verifiers matching the files you touched, followed by live acceptance in an isolated game copy:
| What you changed | Required checks before opening a PR |
| --- | --- |
| `packages/*`, `apps/server`, or `scripts/*` | Root `npm run typecheck`; if you touched server startup or `tuning/*.jsonc`, boot `apps/server/src/cli.ts` against a temporary data folder to confirm clean dataset extraction and tuning validation |
| `apps/launcher` | Launcher `typecheck` + `electron-vite build`; if you edited UI strings, verify `en.json` and `zh-CN.json` locale key parity |
| `patches/exe/` (any `patch.jsonc`) | `wtotools check-patches` (verifies unique signature hits, `expect_original` bytes, and exact byte-for-byte agreement between `asm`/`data` and `bytes`) |
| `patches/gui/` (any `patch.jsonc` or `.nut` fragment) | **Full** `wtotools check-gui` using `sq.exe` `compilestring` (required) + a temporary copy build to confirm zero unknown schema keys in `gui-patch-definition.ts` |
| `native/wto-net/` or `patches/native/` | MSVC `native\wto-net\build.ps1` (`/W4`, **zero warnings**) + temporary `scripts/build-game-copy.ts` run confirming every native module resolves cleanly |
| Adapting a new client build (`patches/versions/`) | `scripts/record-game-version.ts` + all applicable checks above + **live in-game verification in an isolated copy (hangar login + `LocalMP` battle)** before committing `patches/versions/<version>.jsonc` |
Complete command reference (run from the repository root, substituting bracketed paths):
```powershell
# 1. TypeScript typecheck & Node 24 erasable-syntax checks (.ts extensions, import type, etc.)
npm run typecheck
npm run typecheck --workspace "@wto/launcher"
npm run build --workspace "@wto/launcher"
# 2. EXE & GUI patch verification (always point at your READ-ONLY stock folder!)
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-dir>\win64\aces.exe"
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
# 3. Native DLL build (MSVC /W4 zero warnings) & temporary offline copy build
powershell -NoProfile -File .\native\wto-net\build.ps1
node scripts/build-game-copy.ts --game "<stock-dir>" --out "<temp-copy-dir>" --data "<temp-data-dir>" --port 27015
# 4. Client build compatibility record
node scripts/record-game-version.ts --game "<stock-dir>"
```
<a id="quirrel-en"></a>
### One-Time Build of the Quirrel Bytecode Compiler `sq.exe` (Note the `--sq` Flag!)
`check-gui` requires the official Quirrel compiler pinned to the revision matching War Thunder's client VM ([Quirrel commit `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe`](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)). Build it once with Visual Studio 2022 C++ tools and CMake:
```powershell
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
cmake --build build/quirrel-cli --config Release --target sq
```
> **Important note on `--sq`**: `wtotools check-gui` defaults `--sq` to `build/quirrel-check/sq.exe` (`tools/src/wtotools/cli/gui_commands.py`), whereas the multi-config Visual Studio CMake build above outputs **`build\quirrel-cli\bin\Release\sq.exe`**. Always pass `--sq "build\quirrel-cli\bin\Release\sq.exe"` explicitly as shown in the command block above (or copy `sq.exe` to `build\quirrel-check\sq.exe`).
---
## 4. Commit Conventions & Pre-PR Checklist
- **One focused goal per PR**: Avoid mixing unrelated refactors or repo-wide formatting into a bugfix or feature PR.
- **English Conventional Commits & English code comments**:
- Format commit titles as `type(scope): concise summary` (e.g., `fix(battle): credit Ground Arcade air event kills from AI victims`, `feat(launcher): show missing optional patch features`; use `repo` or `docs` for repository-level or documentation changes);
- Mark breaking changes with `!` after the scope and a `BREAKING CHANGE:` footer;
- Write all code comments, 3-line patch header comments, patch `title` fields, and commit bodies in English;
- Reserve `Co-authored-by` trailers strictly for human collaborators—never list AI models or coding tools.
- **Final 5-point self-check before opening a PR**:
1. Check against [Development Rules — Section 4](development-rules.md#good-vs-bad-en): zero hardcoded RVAs, struct offsets, or `_ReturnAddress()` checks; zero hardcoded stock game numbers; zero cross-layer I/O;
2. Verify syntax & schema discipline: explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys (no `requires` in `patches/gui/**/patch.jsonc`, explicit `"end"` on `rel32` captures with trailing immediates);
3. For currency, research, inventory, or profile mutations, verify changes persist atomically via `PlayerProfiles` / `SaveStore` **before** replying to the client, with strict per-account isolation;
4. Review `git diff` to ensure zero personal machine paths, copyrighted game files, extracted stock scripts, personal saves, or unredacted logs slipped in;
5. Fill out the [PR template](templates/pull-request.md) completely, recording exact commands run and clearly separating observed in-game checks from pending in-game acceptance steps.
+576 -36
View File
@@ -1,59 +1,599 @@
# Development rules
# 开发理念、架构分层与工程规范 / Development Rules
<a id="zh-cn"></a>
简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn)
## 实现位置
这篇文档不只罗列「能做什么、不能做什么」,而是先把 **WTOffline 为什么这样分层、客户端与本地服务器各自承担什么角色** 彻底讲透。只要底层运行模型在脑子里立住了,项目里的每一条工程规范都是自然而然的推论。
- 开工前明确玩家会看到什么变化和准备改的范围。涉及玩法或架构取舍,先和维护者对齐。先查目标版本的游戏文件、原版界面脚本和官方公开源码,记录版本、文件或函数以及支持结论的事实。把推测标为推测。需要读写游戏格式时,先评估已有工具的许可、维护情况和版本适用性。[DagorEngine 源码](https://github.com/GaijinEntertainment/DagorEngine)
- 客户端沿用原有流程,由本地服务器按协议回应。先看服务器或游戏自带配置能否解决。确实需要改客户端时,注明对应功能、原有行为和更小的改动为什么不够。界面脚本进 `patches/gui/`,数据包配置改动归 `packages/patcher/`,其他补丁按[补丁指南](patches.md#zh-cn)登记。
- 服务端按领域分模块。协议层处理请求和应答格式,规则层处理游戏规则,存档层负责持久化,数据层只提取游戏文件中的事实。修改档案的动作写盘成功后再回复。无法识别账号、缺必填参数或余额不足时,明确拒绝。初期开发用新存档验收,无需增加旧存档迁移。
- 应用通过参数把配置和路径交给共享库。按职责拆文件、函数和类,复用现有逻辑和常量。文件接近 300 行或函数接近 50 行就检查是否该拆分。商城与交易所的 HTML、CSS、JS 使用独立文件并复用[网页模块](../apps/server/src/web-ui)。
---
## 数值和数据来源
<a id="architecture-zh"></a>
| 数值类别 | 做法 |
| --- | --- |
| 协议规定的值,如包头长度和消息类型 | 保留在代码中,注明版本和出处。 |
| 游戏文件已有的值,如车价、改装件价格 | 启动时从玩家的游戏文件读取。缺少必需值时报告具体字段并停止,避免悄悄代入编造的默认值。 |
| 离线版决定的值,如奖励、价格、权重、倍率、等级门槛、数量上限 | 写进对应模块的 `tuning/`。服务端默认值位于 [apps/server/tuning](../apps/server/tuning),启动时校验类型、范围和必填字段。 |
## 1. 先建立全景图:WTOffline 到底是怎么跑起来的?
经济数值先查游戏数据和官方资料。商城以官方美元价作为 GJN 标价依据。官方资料缺项时,沿用已有出处的参考数据,或说明它属于离线设计。配置注释或 PR 记录出处、单位和取值规则,具体数值以配置为准。展示给玩家的数字也从同一数据来源生成。
WTOffline 采用与《逃离塔科夫》单机版(SPT)一脉相承的本地模拟架构:**不推翻重写游戏引擎,而是让原版客户端相信自己正连着完整的线上后端,把它的全部网络请求收口到本机 `127.0.0.1` 的模拟服务器,并仅在进程内补齐客户端被裁剪掉的局内主机裁判函数。**
本地服务器每次启动加载数值配置。数据目录下的同名 `tuning/*.jsonc` 可逐键覆盖默认对象。数字、字符串和列表整体替换。
```text
玩家在启动器点击「启动游戏」
│
├─ 1. 桌面启动器(apps/launcher)调用构建引擎(packages/patcher)
│ └─ 以「严格只读」方式读取玩家的官方原版客户端目录,向独立离线副本目录生成:
│ ├─ char.vromfs.bin / aces.vromfs.bin:改写 network.blk 服务地址 -> 127.0.0.1:<端口>,注入本地商店礼包 GUID
│ ├─ gui.vromfs.bin:应用 patches/gui/(仅修补本地服务器无法覆盖的极少数界面脚本点)
│ ├─ win64/aces.exe:应用 patches/exe/(跳过包验签、隔离存档与注册表、禁用反作弊、把导入表 WS2_32.dll 改为 wto_ws.dll)
│ └─ win64/wto_ws.dll + win64/wto_ws.cfg:按 patches/native/*.jsonc 动态解析函数 RVA 与结构体偏移写入配置文件
│
├─ 2. 本地模拟服务器(apps/server,仅绑定 127.0.0.1:<端口> 单端口监听)
│ ├─ 启动阶段:通过 DatasetCache 从游戏归档包提取静态事实(科技树、价格、改装件、任务、多语言词条),加载 tuning/*.jsonc
│ └─ 运行阶段:port-listener.ts 按每个 TCP 连接的首批字节自动分流多协议:
│ ├─ 首字节 0x01 ──▶ MatchingService(9 字节头 + LZ4 压缩帧,握手后流加密)
│ ├─ 明文 PASS/NICK/USER/CAP/PING ──▶ IrcServer(机库与小队聊天)
│ ├─ 首字节 0x16(TLS ClientHello) ──▶ 本地证书 TLSSocket 解密后再二次分流至 IrcServer 或 HTTP
│ └─ 其余全部明文连接 ──▶ HTTP 服务器(yuplay2 登录、char 二进制 BLK 档案、inventory 签名 JSON、内嵌网页商店)
│ (注:HTTP WebSocket upgrade 请求会被记录日志后直接 socket.destroy() 拒绝)
│
└─ 3. 隔离离线副本(win64/aces.exe + win64/wto_ws.dll)
├─ 进程加载时(DllMain):wto_ws.dll 通过 wto_ws.def 把全部 Winsock 导出(含序号导出)转发至系统 ws2_32.dll,
│ 同时用 MinHook 挂钩系统 ws2_32.dll 的域名解析与连接函数;若任一网络钩子安装失败,DllMain 直接返回 FALSE 终止启动!
├─ 机库阶段:登录、拉取档案、科技树研发、买车买改装、乘员训练、开箱、逛商店,全部走原版协议由 apps/server 处理并原子落盘
└─ 对局阶段:MatchingService 下发任务参数使客户端以 LocalMP 本地主机开局;
wto_ws.dll 校验 PE 指纹匹配后启用 local_mp_* 模块,在进程内补齐选车出生、AI 刷出、击杀助攻占点计分、
陆战街机空中支援、核弹判胜与受损提示过滤;战后由客户端经 cln_update 回传 apps/server 结算银狮/研发点并落盘
```
## 本地开发与材料
### 1.1 单端口多协议分流细节(`apps/server/src/transport/`)
- 游戏只在专用副本和隔离环境里启动。启动前验证断网限制、本地服务、Steam 和账号身份,以及文件、注册表、机器标识、反作弊和崩溃上报的隔离。需要观察启动行为时,在一次性环境里核对前后变化。原版来源只读,通过离线副本启动并使用本地账号。
- 商城和交易所通过游戏内置浏览器访问本地服务。改动时核对该客户端内置浏览器支持的语法,沿用游戏语言和游戏文件中的本地化文字。包括浏览器子进程在内都要检查网络和缓存位置。
- 提交材料使用自己的代码和最小改动片段。游戏文件、解包产物和玩家数据留在本机。PR 使用可公开复核的出处和已清理的日志节选。
客户端内部既有读取 `config/network.blk` 的模块,也有把域名、端口甚至 `https://` 写死在二进制常量里的模块。为了不占用一串本地端口,本地服务器在 `apps/server/src/transport/port-listener.ts` 中用**单个 TCP 监听端口**接住所有流量,在 `socket.once('data', ...)` 窥探首批字节后原样退回缓冲区(`socket.unshift`)并精准派发:
1. **匹配二进制协议(首字节 `0x01`)**:匹配 `startsMatchingPacket(first)` 后交由 `MatchingService` 处理(9 字节小端包头 + LZ4 数据块,见 `matching/matching-frame.ts`);
2. **明文 IRC 握手**:首行以 `PASS`、`NICK`、`USER`、`CAP` 或 `PING` 开头时交由 `IrcServer` 处理;
3. **TLS 加密连接(首字节 `0x16`)**:使用本地动态生成的自签名证书建立 `TLSSocket` 解密,再窥探解密后的首包字节——若是 TLS 承载的 IRC 握手则交由 `IrcServer`,否则派发给 HTTP 服务器;
4. **常规 HTTP 连接**:其余连接直接进入 `http-listener.ts` 的 `createHttpServer`,由 `Router` 按原始目标域名(`originalHost`)和路径分发给 `login`、`char`、`inventory`、`store`、`downloadable-content` 等服务。注意:**WTOffline 不使用 WebSocket**——客户端偶然发起的 HTTP `upgrade` 请求会在 `http-listener.ts` 中记入流量日志(`WebSocket ... (refused)`)并立即调用 `socket.destroy()` 断开。
### 1.2 `wto_ws.dll` 是如何在零外联风险下接管网络的?
在 `patches/exe/online/network-hook-library/patch.jsonc` 中,补丁将 `aces.exe` 只读数据段(`.rdata`)导入描述符引用的字符串 `"WS2_32.dll\0"`(`57 53 32 5f 33 32 2e 64 6c 6c 00`,共 **11 字节**)原位替换为等长的 `"wto_ws.dll\0"`(`77 74 6f 5f 77 73 2e 64 6c 6c 00`,同样 **11 字节**):
- Windows 加载器启动 `aces.exe` 时会自动加载同目录下的 `win64/wto_ws.dll`,由 `native/wto-net/src/wto_ws.def` 将客户端导入的全部 Winsock API(包含 31 个按 `@序号` 导入的函数)无缝转发给系统 `ws2_32.dll`;
- 在 `native/wto-net/src/dll_main.c` 的 `DllMain(DLL_PROCESS_ATTACH)` 中,DLL 读取同目录 `wto_ws.cfg`,通过 MinHook 直接挂钩系统 `ws2_32.dll` 本身的域名解析与连接/数据报函数(这样进程内**所有模块**的网络调用都会经过重定向,而不只是主程序);
- **安全熔断**:如果 `MH_Initialize`、`install_resolver_hooks`、`install_connection_hooks` 或 `MH_ApplyQueued` 中任何一步失败,`DllMain` 会记录日志并直接返回 `FALSE`,让 Windows 加载器中止启动游戏进程,避免游戏在未挂钩状态下连接外网。
### 1.3 基本设计原则
> **遇到功能缺失或 Bug 时,先评估能否在 `apps/server` 或通过下发原版配置字段解决。**
> 能通过修正服务端协议响应、补齐下发给客户端的任务 BLK 字段、或读取原版静态配置解决的问题,优先在服务端解决,不新增 `.nut` 界面脚本或 `aces.exe` / `wto_ws.dll` 客户端补丁。客户端补丁留给原版客户端确实缺少对应通路的场景——因为游戏每次小版本更新都会重排二进制代码,而服务端协议与配置字段跨版本稳定得多。
---
<a id="2-代码地图与分层边界"></a>
<a id="workspace-rule-zh"></a>
## 2. 仓库依赖约定与 `apps/server` 真实代码地图
### 2.1 仓库级单向依赖约定
```text
apps/launcher ──┐
├──▶ packages/* (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
apps/server ──┘
```
- **依赖方向单向朝下**:应用层 `apps/*` 可以导入共享包 `packages/*`(开发脚本 `scripts/*` 可组合两者),`packages/*` 不应反向导入、引用或硬编码读取 `apps/*` 下的代码或配置文件。
- 当共享包需要补丁集目录、数据目录、端口或礼包列表时,一律由上层调用方通过函数参数显式传入。
<a id="server-layers-zh"></a>
### 2.2 本地服务器 `apps/server/src/` 四层目录全景图
注意:**`apps/server/src/` 下并没有一个笼统的 `rules/` 文件夹**——业务规则是按游戏业务领域拆分成独立目录的。动手写代码前请对照下面这张真实目录表放对位置:
| 职责分层 | `apps/server/src/` 下的真实子目录 | 这一层负责什么 | 应避免放在这一层的内容 |
| --- | --- | --- | --- |
| **1. 传输与协议层**(Transport & Protocol) | `transport/`(单端口分流、HTTP 路由、TLS 证书)、`traffic-log/`(流量落盘)、`login/`(`yuplay2` 登录与会话凭据)、`char/`(含 `char-service.ts`、`pbbd-stream.ts`、`char/actions/*-actions.ts` 与路由总表 `char/actions/action-table.ts`)、`matching/`(LZ4 帧、流加密与排队 RPC)、`inventory/`(外部物品库与 RSA 内容签名)、`store/`(礼包与激活码路由)、`chat/`(IRC 服务端)、`cloud-settings/`、`downloadable-content/`、`web-ui/`(内嵌商店/市场页面渲染)、`mods/`(服务端模组运行时) | 解码线上传输格式(表单、JSON、压缩标记二进制 BLK、`PBBD` 流、LZ4 帧),提取并校验请求参数,调用对应领域规则,再把结果编码回客户端期待的原版响应格式 | 避免在 `*-actions.ts` 里堆砌几百行扣钱、算研发点或改档案树的业务逻辑;不要绕过 `PlayerProfiles` / `SaveStore` 直接读写磁盘文件 |
| **2. 领域规则层**(Domain Rules) | `battle/`(开局配置与战后经济结算)、`research/`(科技树状态、选定研发、自由研发点兑换)、`modifications/`(改装件、弹链、备用载具、自定义挂载)、`crew/`(乘员组槽位与技能加点)、`items/`(加成卡、赌注、折扣券)、`repair/`(战损折算与免费修车时间)、`clans/`(联队管理与联队载具研发)、`decor/`(涂装、贴花、3D 挂件)、`unlocks/`(成就、头衔、阶段解锁)、`player-card/`(头像、资料卡展柜)、`training/`(新手教程首通奖励)、`game-modes/` | **纯业务逻辑**:接收内存中的档案 `BlkBlock`、已加载的静态数据集与可调参数,校验前置条件,计算并更新档案状态,返回明确的成功或拒绝错误码(如 `RuleOutcome`) | **零网络、零磁盘 I/O**:不导入 `node:http`、`node:net` 或 `node:fs`,也不要感知外层是 HTTP 还是匹配长连接 |
| **3. 档案与持久化层**(Profile & Persistence) | `profile/`(`player-profiles.ts` 及按领域拆分的 `profile-*.ts` 档案节点读写器、派生状态刷新器)、`saves/`(`save-store.ts` 账号存档读写、`save-upgrades.ts` 版本演进)、`accounts/`(本地多账号密码与隔离)、`storage/`(`atomic-file.ts` 原子落盘) | 封装档案 BLK 树的底层字段读写,管理多账号目录隔离(`<data>/saves/<userId>/`),维护存档 `formatVersion`,并通过临时文件 + `fsync` + 原子重命名保证断电不坏档 | 不掺杂具体购买价格或研发公式;**任何修改档案的动作必须在磁盘原子写入完成后才能向客户端返回成功响应** |
| **4. 静态数据集与可调配置层**(Datasets & Tuning) | `game-data/`(`game-files.ts`、`game-pack.ts`、`datasets/*.ts`、`datasets/dataset-cache.ts`)、仓库默认配置 `apps/server/tuning/*.jsonc` + 加载校验器 `src/tuning/`(`tuning-loader.ts`、`tuning-reader.ts`、`limits-tuning.ts`、`launcher-tuning.ts`)+ 各领域 `<领域>/*-tuning.ts` | 启动时从玩家原版 `.vromfs.bin` 提取静态事实并按包时间戳 + 内部文件 SHA-1 缓存到 `<data>/cache/datasets/`;按「仓库默认 → 已启用模组 → 玩家 `<data>/tuning/` 覆盖」三层合并 JSONC 并做严格类型与范围校验 | 不要凭空编造原版数据;必填字段缺失时应明确报错停止启动,避免用隐式假默认值掩盖问题 |
**模块粒度与复用准则**:
- 当单个源文件接近 **300 行** 或单个函数接近 **50 行** 时,主动检查是否把协议拆包、档案树遍历和业务公式塞进了同一个文件,及时按上表拆开;
- 动手前先搜现有公共基础设施(如 `char/actions/rule-answer.ts`、`profile/profile-*.ts`、`modifications/equipment-catalogue.ts`、`web-ui/` 公共组件、`native` 侧的 `local_mp_core`),尽量复用而不是重复实现。
---
<a id="walkthrough-zh"></a>
### 2.3 跟着真实代码走一遍:`cln_set_researchable` 是怎么穿透四层的?
光看分层表还不够直观。下面我们顺着玩家在科技树点击「研发此载具」时触发的真实动作 **`cln_set_researchable`**,逐文件看一遍标准请求流(你在写任何新 `char` 动作时直接照这个模板写即可):
1. **客户端发包 → 协议入口解码(`apps/server/src/char/char-service.ts`)**
客户端向 `char-*.warthunder.com` 发送 HTTP POST,请求头带 `action: cln_set_researchable` 与 `uidhint: <userId>`,请求体是带压缩标记的二进制 BLK(包含 `unit:t = "us_m4a1_1942_sherman"` 与 `type:i = 0`)。`CharService.#handleCore` 调用 `decodeRequestPayload(request.body)`(`char/char-payload.ts`)把二进制负载解码为 `BlkBlock`(同时生成可读文本供流量日志记录),然后从 `char/actions/action-table.ts` 注册表里查出对应的处理器 `setResearchable`。
2. **协议动作适配与参数提取(`apps/server/src/char/actions/research-actions.ts`)**
`setResearchable` 本身只有十几行:它使用公共包装器 `ruleAction`(`char/actions/rule-answer.ts`),通过 `stringParam(payload, 'unit')` 和 `intParam(payload, 'type')`(`char/actions/payload-params.ts`)做基础类型提取。如果缺字段就返回 `undefined`(由 `ruleAction` 统一回 `!ERROR:BAD_PARAMS`);参数齐全则返回一个闭包:
`(profile) => chooseResearchTarget(profile, rules, vehicle, type)`。
3. **加载档案与执行纯领域规则(`apps/server/src/research/research-progress.ts`)**
`ruleAction` 校验完账号后调用 `profiles.updateWhen(account.userId, ...)`(`profile/player-profiles.ts`),由 `SaveStore.loadProfile` 从 `<data>/saves/<userId>/profile.blk` 读出当前档案并交给纯规则函数 `chooseResearchTarget`:
- 先从启动期提取好的科技树数据集 `rules.techTree.vehicle(vehicleName)` 查找该载具并核对 `typeId`;
- 调用 `currentStatus(profile, rules, vehicleName)` 确认该载具在玩家当前档案下确实处于 `VehicleStatus.CAN_RESEARCH` 状态;若尚未解锁前置车或已拥有,则返回 `refused('NOT_AVAILABLE')`(`{ ok: false, refusal: 'NOT_AVAILABLE' }`),`updateWhen` 看到 `false` **不触碰磁盘**,`ruleAction` 向客户端回复纯文本 `!ERROR:NOT_AVAILABLE`;
- 校验通过后,调用 `profile/profile-research-targets.ts` 的访问器写入新研发目标、清空刚完成研发弹窗标记,返回 `ACCEPTED`(`{ ok: true }`)。
4. **先原子落盘,再回包给客户端(`profile/player-profiles.ts` → `saves/save-store.ts` → `storage/atomic-file.ts`)**
`updateWhen` 收到 `true` 后,先运行 `#refresh(profile, userId)` 同步档案内的派生状态(解锁阶段、头衔、联队同步等),随即调用 `SaveStore.saveProfile(userId, profile)`。`saveProfile` 使用 `writeFileAtomic` 先在同目录写出临时文件 `profile.blk.<pid>.<rand>.tmp`、调用 `fsyncSync(fd)` 刷入物理磁盘、再原位 `renameSync` 覆盖目标文件并更新 `save.json`。**只有在磁盘写入彻底成功后**,`ruleAction` 才调用 `clientProfile(profile, account)` 组装客户端视图,由 `toResponse`(`char/char-answers.ts`)加上 `0x69` 标记编码成二进制 BLK 返回 HTTP 200。
### 2.4 存档结构演进规则(`saves/save-upgrades.ts`)
- **领域规则只面向「当前最新版」存档结构编程**:避免在 `research/`、`modifications/`、`battle/` 等业务代码里散落兼容旧测试字段的 `if/else` 分支;
- 当正式版本演进确实改变了 `profile.blk` 的存储结构时,统一在档案升级链(`saves/save-upgrades.ts` 的 `SaveUpgrades`)中追加一步升级函数(`steps[n]` 负责把 `formatVersion` 从 `n + 1` 原地升级到 `n + 2`)。`SaveStore.loadProfile` 打开旧版存档时会按顺序跑完升级步骤并立即以最新 `formatVersion` 原子回写磁盘。仍在同一分支开发调试、尚未发布的草稿改动无需写迁移代码。
---
<a id="values-zh"></a>
## 3. 三类数值放哪里(保持边界清晰)
在代码审查中,最常见的返工原因就是把不同性质的数字混写在了业务逻辑里。写下任何一个字面量前,先问它属于下面哪一类:
| 数值类别 | 典型例子 | 唯一正确的存放位置 | 常见错误示范 |
| --- | --- | --- | --- |
| **① 协议与引擎固定常量** | 匹配/局内消息号(如 `LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u`)、`PBBD` 魔数(`0x44424250`)、Dagor 容器布局(`dag::Vector` 偏移、`FastNameMap` 移位)、状态位掩码 | 定义为具名常量放在对应协议或头文件中,并用**英文注释写明一手来源**(目标客户端版本号 + RVA,或 [DagorEngine 公开源码](https://github.com/GaijinEntertainment/DagorEngine) 文件路径) | 在函数中间裸写 `if (msgId == 61488)` 或 `if (status == 64)` 且没有任何来源注释 |
| **② 原版游戏包里本来就有的静态事实** | 载具购买银狮/金鹰价、研发点需求、分房权重、维修费、改装件树、多人地图列表、新手教程首通奖励、连杀支援出生高度/距离/速度 | 在 `apps/server/src/game-data/datasets/` 编写 `Dataset<T>`,服务启动时经 `DatasetCache` 从玩家原版 `.vromfs.bin` 动态读取并缓存在 `<data>/cache/datasets/<id>.json`;若原版文件缺失必填块/字段,直接 `throw new Error(...)` 明确报错停止 | 把某一个客户端版本的载具表、奖励金额或出生坐标手抄成 TS/C 常量表;或者读不到原版字段时悄悄 `?? 10000` 填个假默认值蒙混过关 |
| **③ 离线版自己决定的可调参数** | 银狮/研发点收益倍率、新账号初始货币、本地商店礼包定价、补给箱掉落权重、AI 机器人重生次数、单次请求数量上限、玩法开关 | 仓库默认值放进 `apps/server/tuning/<领域>.jsonc`,在对应 `<领域>/*-tuning.ts` 用 `TuningReader` 做启动期类型与上下界校验;运行期由 `tuning-loader.ts` 自动按「仓库默认 → 已启用模组覆盖 → 玩家 `<data>/tuning/<领域>.jsonc` 覆盖」合并 | 把 `const RP_MULTIPLIER = 3.0` 或硬上限直接写死在结算函数内部,导致玩家和模组作者无法通过 `tuning/` 调参 |
---
<a id="4-好代码-vs-坏代码4-组最常见的真实对比"></a>
<a id="good-vs-bad-zh"></a>
## 4. 好代码 vs 坏代码:4 组来自真实仓库的代码对比
下面所有正面代码全部取自仓库内的真实文件与真实符号,提交前请逐条对照自查。
### 对比 1:Native C 钩子 —— `g_lmp` 动态捕获与外层作用域标志 vs 硬编码偏移与 `_ReturnAddress()`
客户端只要发一个小版本更新(例如 `2.61.0.37` → `2.61.0.58`),函数 RVA 会整体漂移,C++ 类成员偏移也会随着字段增删而移动(例如 `gameplay` 里的连杀规则表偏移就会跨版本变化)。
```c
// ❌ 坏写法:硬编码 RVA、硬编码结构体偏移 +0x3798、用 _ReturnAddress() 猜调用栈
// 只要游戏发一个小补丁,轻则功能静默失效,重则当场非法内存访问崩溃!
static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
{
uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
return;
const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
/* ... */
}
```
```c
// ✅ 好写法(真实代码:native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
// 1. 所有函数地址与结构体偏移均在 patches/native/local_mp_air_events.jsonc 动态捕获写入 wto_ws.cfg,
// 运行时由 local_mp_values.c 填入全局 extern LmpValues g_lmp(LMP_GP_OFF_KS_RULES 展开为 g_lmp.gp_ks_rules);
// 2. 用外层函数钩子 + 线程局部标志(__declspec(thread))精确界定调用上下文,彻底告别脆弱的 _ReturnAddress()。
static SwitchPlayerUnitFn orig_switch_player_unit;
static __declspec(thread) int g_in_air_event_switch;
static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
{
int previous = g_in_air_event_switch;
if (to_air != 0 && ground_arcade_air_events_enabled())
g_in_air_event_switch = 1;
orig_switch_player_unit(event_mgr, participant, to_air);
g_in_air_event_switch = previous;
}
// 读取连杀规则表时全部走 g_lmp 动态解析值,跨小版本自动适配:
const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
```
### 对比 2:原版静态数据 —— `DatasetCache` 提取与纯领域目录消费 vs 在业务里手抄常量表
```ts
// ❌ 坏写法:把某一个版本的新手教程首通银狮/金鹰奖励硬编码成服务端字典
const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
};
```
```ts
// ✅ 好写法(真实代码:apps/server/src/game-data/datasets/training-missions.ts
// + apps/server/src/training/training-completion.ts):
// 1. 在 datasets/ 定义带版本号的 Dataset,从玩家原版 char.vromfs.bin 的
// config/mislist.blk、config/pve_awards.blk、config/unlocks.blk 提取真实配置;缺失必填块立即抛错。
export const trainingMissions: Dataset<TrainingMissionsData> = {
id: 'training-missions',
version: 1,
extract(source: DatasetSource): TrainingMissionsData {
const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
if (!misSection) throw new Error('config/mislist.blk has no "training" block');
const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
// ... 组装 missions 列表并返回纯数据对象
return { missions };
},
};
// 2. 启动时通过 DatasetCache 加载(包未变直接命中缓存),交由纯领域类 TrainingCatalogue 执行幂等发奖:
const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
```
### 对比 3:找准修复层级与严格遵守工具链语法(MSVC C 与 Node 24 原生 TS)
**(A)先查原版读取逻辑,别急着动刀写客户端补丁**
- ❌ **坏思路**:发现多载具出击模式下 AI 机器人死一次就不再重生,立刻去反汇编 `BotSystem` 准备写 `patches/exe/` 强改内存计数器。
- ✅ **好思路**:先看 `MissionSettings::load` 是怎么读任务配置的——结果发现原版客户端本来就会读取任务 BLK 根节点的 `numBotRespawns` 与 `numTankBotRespawns`,只是服务端组装匹配开局配置时漏填了这两个根字段。在 `apps/server` 补上几行配置下发即可解决,**零客户端补丁、跨版本永久免疫失效**。
**(B)MSVC C 编译规范与 Node 24 原生 TypeScript 语法规范**
- **Native C(`native/wto-net/`)**:由 `native/wto-net/build.ps1` 调用 Visual Studio `cl.exe` 以 `/W4` 编译,要求**零编译警告**。校验自定义结构体大小与成员偏移时使用 `<windows.h>` 的编译期断言 `C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);`,线程局部存储使用 `__declspec(thread)`,内存对齐使用 `__declspec(align(16))`;避免使用 `__attribute__((...))`、零长数组、可变长数组(VLA)或 `void *` 算术运算等 GCC/Clang 专属扩展。
- **TypeScript(`tsconfig.json`)**:Node.js 24 直接剥离类型运行 `.ts` 源码,仓库开启了 `erasableSyntaxOnly: true`、`verbatimModuleSyntax: true`、`allowImportingTsExtensions: true` 与 `exactOptionalPropertyTypes: true`:
```ts
// ❌ 坏写法:省略 .ts 后缀、值导入混用纯类型、使用 enum 或构造函数参数属性(Node 24 类型剥离与 tsc 均会报错!)
import { SaveStore, SaveUpgrades } from '../saves/save-store';
export enum ResearchState { Locked = 0, Available = 1 }
export class Handler {
constructor(private readonly saves: SaveStore) {}
}
```
```ts
// ✅ 好写法:相对路径一律写明 .ts 扩展名;纯类型必须用 import type;用 as const 对象或联合类型代替 enum;用 #私有字段
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import type { SaveUpgrades } from './save-upgrades.ts';
export const VehicleStatus = {
CAN_RESEARCH: 2,
OWNED: 4,
} as const;
```
### 对比 4:工程验证 —— 跑真实工具链检查 vs 写几百行假 Mock 单元测试
- ❌ **坏写法**:改了 `patches/gui/` 只肉眼扫一眼 `.nut` 缩进,或者自己造一套模拟客户端行为的 300 行 Mock 单测跑绿就宣称「测试全部通过」——结果真进游戏时因为 Quirrel 词法作用域冲突卡死在登录界面,或者 `patch.jsonc` 多写了一个非法键在构建副本时直接抛 `DefinitionError`。
- ✅ **好写法**:按改动范围老老实实运行真实检查工具(`npm run typecheck`、`wtotools check-patches`、带 `sq.exe` 的完整 `wtotools check-gui`、`native\wto-net\build.ps1`、`scripts/build-game-copy.ts`),并在 PR 描述中**如实把「已在命令行跑过的检查」与「尚待在隔离副本进游戏实机验收的步骤」分开写清楚**。
---
<a id="ai-guide-zh"></a>
## 5. 使用 AI 编程助手协作指南(含一键复制约束提示词)
我们非常鼓励你使用 Claude Code、Codex、Cursor 等 AI 工具协助阅读反汇编、梳理 `.nut` 界面调用链、核对 BLK 字段以及快速定位协议差异。
但 AI 如果事先不知道 WTOffline 的工程边界,很容易顺手写出硬编码 RVA、在 `patches/gui/**/patch.jsonc` 里误加 `requires` 字段、漏写 `.ts` 导入后缀、用 `enum` 语法或生成一大堆无意义的 Mock 测试。**在让 AI 动手修改任何文件之前,请先把下面这段完整提示词发给它**:
```text
我正在为 WTOffline 仓库开发改动。在编写或修改代码前,请遵循以下项目规范(写任何符号、结构体字段、CLI 参数前先读取仓库真实源文件核实):
1. 修复层级优先顺序:先查原版一手依据(玩家只读原版 .vromfs.bin、gui.vromfs.bin 里的 .nut 脚本、DagorEngine 公开源码)。凡是能在本地服务器(apps/server)协议响应、任务配置字段或静态数据集里解决的问题,不要新增 patches/gui/、patches/exe/ 或 native/wto-net/ 客户端补丁。
2. 动态定位,不硬编码地址与偏移:不要在 C 或 TS 代码里写死 exe 函数地址、RVA、C++ 结构体偏移或 _ReturnAddress() 调用栈判断。所有原生地址与偏移通过 patches/exe/ 或 patches/native/*.jsonc 的 signature / string_ref / within 动态捕获写入 wto_ws.cfg,C 侧通过 extern LmpValues g_lmp(local_mp_values.h / local_mp_offsets.h)读取,并用外层钩子 + __declspec(thread) 标志替代返回地址检查。带尾随立即数的 rip-relative 指令捕获 rel32 时需显式指定 "end"(指令总字节长度)。
3. 三类数值严格归位:原版游戏自带数值(载具价格、研发点、奖励、任务、出生参数)必须通过 apps/server/src/game-data/datasets/(DatasetCache)从原版归档提取,缺必填字段直接抛错;离线版自定参数与开关统一放入 apps/server/tuning/*.jsonc 并在对应 *-tuning.ts 做启动校验;协议/引擎常量写英文注释注明客户端版本 RVA 或 DagorEngine 源码路径。
4. 分层与依赖方向:packages/* 不导入或读取 apps/*。apps/server/src/ 内区分传输协议层(char/actions/ 等)、领域规则层(research/、battle/、modifications/ 等纯逻辑目录,无 rules/ 目录,零网络零磁盘 I/O)、档案持久化层(profile/、saves/、storage/atomic-file.ts —— 改档动作先原子写盘成功再回包);存档兼容升级统一通过 saves/save-upgrades.ts 的 formatVersion 步骤处理,不在业务规则里散落旧版兼容分支。单文件接近 300 行或函数接近 50 行时主动拆分。
5. 严格语法与 Schema 约束:
- TypeScript 运行在 Node 24 原生类型剥离模式(erasableSyntaxOnly + verbatimModuleSyntax + allowImportingTsExtensions):所有相对导入必须带显式 `.ts` 后缀,纯类型必须用 `import type`,禁止使用 `enum`、`namespace` 和构造函数参数属性。
- Native C 必须通过 MSVC `native/wto-net/build.ps1`(/W4 零警告),使用 `C_ASSERT` 做编译期布局检查,禁止 GCC 扩展;新增 `.c` 文件需同步加入 `build.ps1` 的 `$sources`。
- 补丁 JSONC 严格校检未知键:特别是 `patches/gui/**/patch.jsonc` 顶层只允许 `id`、`title`、`features`、`variants`(不要写 `requires`,否则会抛出 DefinitionError)。
6. 真实工具验证:不要编写庞大的模拟(mock)单元测试套件。按改动运行真实检查命令(`npm run typecheck`、`wtotools check-patches`、带 `--sq` 的完整 `wtotools check-gui`、`native/wto-net/build.ps1`、`scripts/build-game-copy.ts`),并如实区分已跑过的命令与待隔离副本实机验收项。
7. 提交规范:一笔 PR 只聚焦单一目标;代码注释、补丁 `title`/头部三行说明与约定式提交消息统一使用英文;不把 AI 写入 Co-authored-by;在隔离副本实机进游戏验收前不提交 `patches/versions/*.jsonc`。
```
---
<a id="isolation-zh"></a>
## 6. 隔离安全与资产边界
1. **官方原版客户端目录保持只读**:无论是拆包查 `.blk`、跑 `tools/re/cli.py` 反汇编、`wtotools` 核对补丁还是构建游戏副本,原版目录都只作为只读输入源,不要向 Steam 或官方启动器安装目录写入、覆盖或残留文件。
2. **仅在独立隔离副本中运行测试**:实机运行客户端必须在 Steam 库目录之外的独立离线副本中进行,并确保三大核心安全锁(`ESSENTIAL_FEATURES`)全部生效——所有联网请求经 `wto_ws.dll` 收口至 `127.0.0.1`、本地配置落入独立 `WTOffline` 用户目录与 `Software\WTOffline` 注册表路径、反作弊与崩溃上报已剥离,且只使用离线本地账号登录。
3. **代码仓库不包含受版权保护资产与隐私信息**:不要将 `.vromfs.bin`、`aces.exe`、解包出的原版 `.nut` / `.blk` 完整文件、真实玩家存档、本机绝对路径或未脱敏日志提交进 Git 仓库。
---
<a id="english"></a>
[简体中文](#zh-cn) · English · [Dev Docs](README.md#english)
[简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english)
## Where changes belong
Rather than handing you a dry list of dos and don'ts, this guide first explains **how WTOffline actually works under the hood and why its layers are separated the way they are**. Once that architecture clicks, every engineering rule follows naturally.
- State the player-visible result and the intended scope before starting. Discuss gameplay or architectural changes with maintainers. Check the target build, stock UI scripts, and official public source. Record the version, file or symbol, and the evidence for the behavior. Mark any inference as such. For game formats, look for existing tools and review their licensing, maintenance, and version support. [DagorEngine source](https://github.com/GaijinEntertainment/DagorEngine)
- Keep the client's normal flow by responding from the local server. Check the server and stock configuration first. When a client change is necessary, document the feature, the stock behavior, and why a lighter change is insufficient. Put UI edits in `patches/gui/` and archive configuration edits in `packages/patcher/`. See the [patch guide](patches.md#english) for the other patch types.
- Keep protocol encoding, game rules, persistence, and game data extraction in their own layers. Persist a save change before returning success. Reject unknown accounts, missing required inputs, and insufficient balances. During early development, use fresh saves for acceptance and omit legacy migrations.
- Pass configuration and paths from applications into shared packages. Reuse existing logic and constants. Review files near 300 lines or functions near 50 lines for responsibilities that can be split. Store shop and marketplace HTML, CSS, and JavaScript in separate files and reuse the [web UI module](../apps/server/src/web-ui).
---
## Data and tuning
<a id="architecture-en"></a>
| Kind of value | Where it belongs |
| --- | --- |
| Protocol constants such as header sizes and message types | Keep them in code with the source and relevant version. |
| Values already in the game files such as vehicle and modification prices | Read them from the player's game files at startup. Report the field and stop if a required value is missing. |
| Offline defaults such as rewards, prices, weights, multipliers, rank thresholds, and limits | Put them in the module's `tuning/` directory. Server defaults are in [apps/server/tuning](../apps/server/tuning) and are validated at startup. |
## 1. End-to-End Architecture: How WTOffline Works
Use game data and official material as the first sources for economic defaults. The local store uses official USD prices as the basis for GJN prices. For gaps, use reference data with a recorded source or document the offline design choice. Put the source, unit, and reasoning in a comment or the PR. Read the exact values and any player-facing numbers from the configuration.
WTOffline uses the same core philosophy as Single Player Tarkov (SPT): **do not rewrite the game engine—keep the retail client running its native code paths, redirect all network traffic to a local emulation server on `127.0.0.1`, and hook `aces.exe` in-process only where retail builds stripped Dedicated Server battle handlers.**
At startup, the server can load a same-named `tuning/*.jsonc` file from the data directory. Object keys merge. Numbers, strings, and arrays are replaced as a whole.
```text
Player clicks "Launch" in the Launcher
│
├─ 1. Desktop Launcher (apps/launcher) invokes Copy Builder (packages/patcher)
│ └─ Reads the player's official stock install STRICTLY READ-ONLY and writes an isolated copy:
│ ├─ char.vromfs.bin / aces.vromfs.bin: rewrite network.blk endpoints -> 127.0.0.1:<port>, inject store bundle GUIDs
│ ├─ gui.vromfs.bin: apply patches/gui/ (surgical UI script edits only where server responses cannot suffice)
│ ├─ win64/aces.exe: apply patches/exe/ (bypass pack signature checks, isolate user dir & registry, disable anti-cheat,
│ │ rewrite PE import name "WS2_32.dll\0" -> "wto_ws.dll\0")
│ └─ win64/wto_ws.dll + win64/wto_ws.cfg: resolve patches/native/*.jsonc RVAs & struct offsets into wto_ws.cfg
│
├─ 2. Local Emulation Server (apps/server, bound strictly to 127.0.0.1:<port>)
│ ├─ Startup: DatasetCache extracts static facts from stock .vromfs.bin archives; tuning-loader merges tuning/*.jsonc
│ └─ Runtime: transport/port-listener.ts peeks at the first bytes of every TCP socket on that single port:
│ ├─ First byte 0x01 ──▶ MatchingService (9-byte header + LZ4 frames, encrypted after handshake)
│ ├─ Plaintext PASS/NICK/USER/CAP/PING ──▶ IrcServer (hangar & squad chat)
│ ├─ First byte 0x16 (TLS ClientHello) ──▶ Local-cert TLSSocket decrypts, then routes to IrcServer or HTTP
│ └─ Everything else ──▶ HTTP server (yuplay2 login, char binary BLK RPC, signed inventory JSON, web store)
│ (Note: HTTP WebSocket `upgrade` requests are logged and explicitly refused via socket.destroy()!)
│
└─ 3. Isolated Offline Client Copy (win64/aces.exe + win64/wto_ws.dll)
├─ Process attach (DllMain): wto_ws.dll forwards all Winsock exports (including 31 ordinal imports) via wto_ws.def
│ to system ws2_32.dll and installs MinHook detours on ws2_32's resolver/connect APIs; if ANY network hook fails,
│ DllMain returns FALSE so Windows immediately aborts launch before a single packet can go online!
├─ Hangar phase: sign-in, profile load, tech-tree research, purchases, crews, chests, and store all run over stock
│ protocols against apps/server with atomic disk persistence
└─ Battle phase: MatchingService launches a LocalMP host session; after verifying PE headers against wto_ws.cfg,
wto_ws.dll activates local_mp_* modules to restore stripped host handlers (vehicle/loadout spawn, AI bot spawn,
kill/assist/capture scoring, Ground Arcade air events, nuclear instant win, damage-notice filtering), and post-battle
results return to apps/server via cln_update for reward settlement and save persistence
```
## Local development and contributions
### 1.1 Single-Port Protocol Multiplexing (`apps/server/src/transport/`)
- Launch the game in a dedicated copy and isolated environment. Before launch, verify the network restrictions, local service, and isolation of Steam identity, accounts, files, registry, machine identifiers, anti-cheat, and crash reporting. Observe before and after effects in a disposable environment when needed. Use a read-only stock source and a local account, and launch from the offline copy.
- The store and marketplace use the game's embedded browser and the local service. Check the browser features supported by the target build and reuse the game's language and localized data. Include the browser subprocess when checking network access and cache paths.
- Submit your own code and the smallest fragments needed for a patch. Keep game files, extracted assets, and player data local. Use sources that reviewers can access and redact any log excerpts.
Because some client subsystems read URLs from `config/network.blk` while others use compiled-in hostnames, ports, and `https://` URLs, `apps/server/src/transport/port-listener.ts` multiplexes every protocol over **one `127.0.0.1` TCP port**. On each incoming connection, `socket.once('data', ...)` inspects the initial bytes, pushes them back with `socket.unshift(first)`, and hands the socket to the matching protocol handler:
1. **Matching binary RPC (`first[0] === 0x01`)**: Matched by `startsMatchingPacket(first)` (`matching/matching-frame.ts` — 9-byte little-endian header + LZ4 block) and handed to `MatchingService`;
2. **Plaintext IRC handshake**: Connections starting with `PASS`, `NICK`, `USER`, `CAP`, or `PING` (`startsIrcHandshake`) go straight to `IrcServer`;
3. **TLS ClientHello (`first[0] === 0x16`)**: Wrapped in a `TLSSocket` using the local certificate, after which the first decrypted bytes are inspected again—routing TLS-wrapped IRC handshakes to `IrcServer` and all other decrypted streams to the HTTP server;
4. **Plaintext HTTP**: All remaining connections go to `createHttpServer` (`transport/http-listener.ts`), where `Router` dispatches requests by `originalHost` and path across `login`, `char`, `inventory`, `store`, `downloadable-content`, etc. **Note on WebSockets**: WTOffline does **not** use WebSockets—any HTTP `upgrade` request hits `server.on('upgrade', ...)` in `http-listener.ts`, which logs `WebSocket <host><path> (refused)` in the traffic log and immediately closes the socket with `socket.destroy()`.
### 1.2 How `wto_ws.dll` Intercepts All Outbound Traffic Safely
`patches/exe/online/network-hook-library/patch.jsonc` locates the 11-byte import descriptor name `"WS2_32.dll\0"` (`57 53 32 5f 33 32 2e 64 6c 6c 00`) in `aces.exe`'s `.rdata` section and overwrites it in place with `"wto_ws.dll\0"` (`77 74 6f 5f 77 73 2e 64 6c 6c 00`, also **11 bytes**):
- When Windows loads `aces.exe`, it loads `win64/wto_ws.dll` instead of `WS2_32.dll`. `native/wto-net/src/wto_ws.def` forwards every imported Winsock symbol (preserving exact `@ordinal` numbers for all 31 ordinal-imported functions) to the operating system's `ws2_32.dll`;
- Inside `DllMain` (`native/wto-net/src/dll_main.c`), `wto_ws.dll` loads `wto_ws.cfg` and uses MinHook to hook the name-resolution, `connect`, and datagram functions inside the system's `ws2_32.dll` itself—so network calls from **every module** in the process pass through local redirection, not just calls made directly by `aces.exe`;
- **Hard fail-closed guarantee**: If `MH_Initialize`, `install_resolver_hooks()`, `install_connection_hooks()`, or `MH_ApplyQueued()` fails for any reason, `DllMain` logs the failure and **returns `FALSE`**, causing the Windows loader to abort process startup immediately rather than risking an unhooked online connection.
### 1.3 The Golden Priority Rule
> **Before touching any client file, always ask: "Can `apps/server` or stock mission/config fields solve this?"**
> If a bug or feature can be implemented by returning the right server payload, populating a stock BLK field in the mission launch config, or extracting stock archive data, **never add a `.nut`, `aces.exe`, or `wto_ws.dll` patch**. Client patches are strictly a last resort when retail `aces.exe` or `gui.vromfs.bin` genuinely lacks the path—because minor game updates frequently shift binary code while wire protocols and BLK schemas remain stable across builds.
---
<a id="2-code-map-and-layer-boundaries"></a>
<a id="workspace-rule-en"></a>
## 2. Workspace Dependency Rule & Real `apps/server` Directory Map
### 2.1 One-Way Workspace Dependency Rule
```text
apps/launcher ──┐
├──▶ packages/* (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
apps/server ──┘
```
- **Dependencies flow strictly downward**: `apps/*` may import from `packages/*` (and developer CLI scripts under `scripts/*` may compose both), **but `packages/*` must never import from, reference, or hardcode paths into `apps/*`**.
- Whenever a shared package needs a patch directory, data folder, port number, or bundle list, pass it explicitly as a function parameter from the caller.
<a id="server-layers-en"></a>
### 2.2 Complete `apps/server/src/` Four-Layer Directory Map
Note that **there is NO monolithic `rules/` folder in `apps/server/src/`**—domain rules live in dedicated per-domain directories. Use this map to place every file in the right layer:
| Layer | Real directories under `apps/server/src/` | What belongs here | What must NOT go here |
| --- | --- | --- | --- |
| **1. Transport & Protocol** | `transport/` (single-port listener, HTTP router, TLS cert), `traffic-log/` (JSONL + decoded body logger), `login/` (`yuplay2` sign-in & session tokens), `char/` (`char-service.ts`, `pbbd-stream.ts`, `char/actions/*-actions.ts`, and `char/actions/action-table.ts`), `matching/` (LZ4 framing, stream cipher, queue/battle RPC), `inventory/` (external inventory & RSA content signing), `store/` (bundle & redeem-code endpoints), `chat/` (IRC server), `cloud-settings/`, `downloadable-content/`, `web-ui/` (in-game store & market HTML/CSS), `mods/` (server mod runtime) | Decode wire payloads (HTML forms, JSON, marker-prefixed binary BLK, `PBBD` streams, LZ4 packets), validate request parameters, invoke domain rules, and serialize results back into stock wire formats | Do not write multi-hundred-line currency, research, or profile-mutation logic inside `*-actions.ts`; never read or write save files directly bypassing `PlayerProfiles` / `SaveStore` |
| **2. Domain Rules** | `battle/` (mission setup & post-battle economy settlement), `research/` (tech-tree state, target selection, free-RP conversion), `modifications/` (modules, ammo belts, spares, custom weapon presets), `crew/` (slots & skill progression), `items/` (boosters, wagers, discounts), `repair/` (battle damage & timed free repair), `clans/` (squadrons & squadron vehicle RP), `decor/` (skins, decals, 3D attachables), `unlocks/` (streaks, titles, progression unlocks), `player-card/` (pilot icons & showcases), `training/` (tutorial completion rewards), `game-modes/` | **Pure domain logic**: take an in-memory profile `BlkBlock`, loaded datasets, and validated tuning; verify preconditions; mutate or compute the next state; return an explicit `RuleOutcome` (`ACCEPTED` or `refused('CODE')`) | **Zero network or filesystem I/O**: never import `node:http`, `node:net`, or `node:fs`, and keep domain logic agnostic of HTTP headers or sockets |
| **3. Profile & Persistence** | `profile/` (`player-profiles.ts` plus focused `profile-*.ts` BLK accessors and derived-state refresh), `saves/` (`save-store.ts` & `save-upgrades.ts` `formatVersion`), `accounts/` (multi-account credentials & isolation), `storage/` (`atomic-file.ts` `writeFileAtomic`) | Encapsulate typed `BlkBlock` profile accessors, isolate per-account saves under `<data>/saves/<userId>/`, run ordered `formatVersion` upgrades, and guarantee crash-safe writes via temp file + `fsync` + atomic rename | Do not embed shop pricing or research formulas here; **every profile mutation must finish writing to disk before replying to the client** |
| **4. Datasets & Tuning** | `game-data/` (`game-files.ts`, `game-pack.ts`, `datasets/*.ts`, `datasets/dataset-cache.ts`), shipped defaults in `apps/server/tuning/*.jsonc` + loader/validators in `src/tuning/` (`tuning-loader.ts`, `tuning-reader.ts`, `limits-tuning.ts`, `launcher-tuning.ts`) + per-domain `<domain>/*-tuning.ts` | Extract static facts from stock `.vromfs.bin` archives at startup (cached in `<data>/cache/datasets/<id>.json` by pack size/mtime and inner file SHA-1 digests), and merge/validate JSONC tuning across shipped defaults -> enabled mods -> player `<data>/tuning/` overrides | Never invent stock game numbers; if a required stock block or field is missing, throw an explicit error at startup instead of silently substituting a fake default |
**File granularity & reuse**:
- When a file approaches **300 lines** or a function approaches **50 lines**, check whether wire parsing, BLK tree traversal, and domain rules have been mixed together and split them cleanly along the table above;
- Reuse existing building blocks (`char/actions/rule-answer.ts`, `profile/profile-*.ts`, `modifications/equipment-catalogue.ts`, shared `web-ui/` helpers, and `local_mp_core` in C) instead of duplicating helpers.
---
<a id="walkthrough-en"></a>
### 2.3 End-to-End Walkthrough of One Real Action: `cln_set_researchable`
To see how those four layers collaborate in practice, let's trace what happens when a player clicks **"Research"** on a vehicle in the tech tree and the client sends **`cln_set_researchable`** (use this exact pattern whenever you add a new profile-mutating `char` action):
1. **Wire Arrival & Payload Decoding (`apps/server/src/char/char-service.ts`)**
The client sends an HTTP POST to `char-*.warthunder.com` with headers `action: cln_set_researchable` and `uidhint: <userId>`, carrying a marker-prefixed binary BLK body (`unit:t = "us_m4a1_1942_sherman"`, `type:i = 0`). `CharService.#handleCore` calls `decodeRequestPayload(request.body)` (`char/char-payload.ts`) to decode the `BlkBlock` (and format readable BLK text for the traffic log), then looks up `'cln_set_researchable'` in `char/actions/action-table.ts` to invoke `setResearchable`.
2. **Protocol Adapter & Parameter Extraction (`apps/server/src/char/actions/research-actions.ts`)**
`setResearchable` is a thin 14-line adapter built on `ruleAction` (`char/actions/rule-answer.ts`). It extracts `unit` and `type` (or `mod` for module research) using `stringParam` and `intParam` (`char/actions/payload-params.ts`). Missing parameters return `undefined` (which `ruleAction` turns into `!ERROR:BAD_PARAMS`); valid parameters return a pure rule closure:
`(profile) => chooseResearchTarget(profile, rules, vehicle, type)`.
3. **Profile Load & Pure Domain Rule (`apps/server/src/research/research-progress.ts`)**
After resolving the account via `withAccount`, `ruleAction` calls `profiles.updateWhen(account.userId, ...)` (`profile/player-profiles.ts`), which loads `<data>/saves/<userId>/profile.blk` through `SaveStore.loadProfile` and passes the `BlkBlock` into `chooseResearchTarget`:
- Looks up the vehicle in the startup-extracted tech-tree dataset via `rules.techTree.vehicle(vehicleName)` and verifies `vehicleTypeById(typeId) === vehicle.type`;
- Verifies `currentStatus(profile, rules, vehicleName) === VehicleStatus.CAN_RESEARCH`. If the vehicle is locked or already owned, it returns `refused('NOT_AVAILABLE')` (`{ ok: false, refusal: 'NOT_AVAILABLE' }`)—causing `updateWhen` to return `undefined` **without touching the disk** and `ruleAction` to reply `!ERROR:NOT_AVAILABLE`;
- Otherwise, updates the active target and clears any pending finished-research prompt via `profile/profile-research-targets.ts`, returning `ACCEPTED` (`{ ok: true }`).
4. **Atomic Disk Persistence BEFORE Replying (`profile/player-profiles.ts` -> `saves/save-store.ts` -> `storage/atomic-file.ts`)**
When the closure accepts, `PlayerProfiles.updateWhen` runs `#refresh(profile, userId)` to bring derived profile state (unlocked ranks, statuses, clan sync, earned unlocks) up to date, then calls `SaveStore.saveProfile(userId, profile)`. `saveProfile` calls `writeFileAtomic` (`storage/atomic-file.ts`), which writes `profile.blk.<pid>.<rand>.tmp`, flushes hardware buffers via `fsyncSync(fd)`, and atomically `renameSync`s it over `profile.blk` (with Windows transient-lock retries) before updating `save.json`. **Only after both atomic writes succeed** does `ruleAction` project `clientProfile(profile, account)` and `toResponse` (`char/char-answers.ts`) send HTTP 200 (`0x69` uncompressed marker + binary BLK) back to `aces.exe`.
### 2.4 Save Schema Upgrades (`saves/save-upgrades.ts`)
- **Domain rules always target only the current profile schema**: never scatter ad-hoc legacy compatibility branches (`if (oldFieldExists) ...`) across `research/`, `modifications/`, or `battle/`.
- When a release changes what `profile.blk` stores, append an ordered `SaveUpgrade` step to `SaveUpgrades` (`saves/save-upgrades.ts`, where `steps[n]` transforms a `formatVersion` `n + 1` profile into `n + 2` in place, bumping `currentFormat`). When `SaveStore.loadProfile` opens a save from an earlier release, it runs the missing steps in order and immediately persists the upgraded profile at `currentFormat`. Unreleased work-in-progress structures on a development branch do not need migration shims.
---
<a id="values-en"></a>
## 3. Three Categories of Values (Keep Boundaries Clear)
Every number or constant in WTOffline belongs to exactly one of three categories:
| Category | Concrete examples | Where it MUST live | Anti-pattern to avoid |
| --- | --- | --- | --- |
| **1. Protocol & engine constants** | Wire/MPI message IDs (`LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u`), `PBBD` magic (`0x44424250`), Dagor container layouts (`dag::Vector` offsets, `FastNameMap` shifts), bitmasks | Named constants in the relevant protocol module or header, with an **English comment citing the primary source** (client version + RVA, or [DagorEngine open-source](https://github.com/GaijinEntertainment/DagorEngine) file path) | Bare magic numbers like `if (msgId == 61488)` or `if (st == 64)` with zero provenance comment |
| **2. Stock game facts** | Vehicle SL/GE prices, RP requirements, battle ratings, repair costs, modification trees, mission lists, tutorial first-win rewards, killstreak spawn altitude/distance/speed | Extracted from the player's read-only `.vromfs.bin` archives at startup via `apps/server/src/game-data/datasets/` (`Dataset<T>`) and cached in `<data>/cache/datasets/<id>.json` by `DatasetCache`. Throw an explicit `Error` if a required block/field is missing | Copying a table of vehicle costs, tutorial rewards, or spawn coordinates from one client build into TS/C code, or silently falling back to `?? 10000` when a lookup fails |
| **3. Offline tuning & defaults** | SL/RP reward multipliers, new-profile starting balances, local store bundle prices, supply-chest drop weights, AI bot respawn counts, request caps, gameplay toggles | Shipped defaults in `apps/server/tuning/<domain>.jsonc`, validated for type and bounds at startup via `TuningReader` in `<domain>/*-tuning.ts`, and merged by `tuning-loader.ts` across shipped defaults -> enabled mod overrides -> player `<data>/tuning/<domain>.jsonc` overrides | Hardcoding `const RP_MULTIPLIER = 3.0` or arbitrary caps inside a settlement function where players and mods cannot override them |
---
<a id="4-good-vs-bad-code-patterns-real-pitfalls"></a>
<a id="good-vs-bad-en"></a>
## 4. Good vs. Bad Code: 4 Real Codebase Comparisons
Every "✅ Good" snippet below uses the exact symbols and files from this repository. Check your changes against all four before opening a PR.
### Comparison 1: Native C Hooks — `g_lmp` Dynamic Captures & Scoped TLS Flags vs. Hardcoded Offsets & `_ReturnAddress()`
Whenever War Thunder ships a minor patch (e.g., `2.61.0.37` -> `2.61.0.58`), function RVAs shift across `.text` and C++ class member offsets move whenever fields are added or reordered.
```c
// ❌ BAD: Hardcoded RVAs, hardcoded struct offset (+0x3798), and brittle _ReturnAddress() caller check.
// The very next minor game update will silently break the feature or crash the client!
static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
{
uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
return;
const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
/* ... */
}
```
```c
// ✅ GOOD (Real code: native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
// 1. Every RVA and struct offset is dynamically captured in patches/native/local_mp_air_events.jsonc,
// written to wto_ws.cfg, and loaded into extern LmpValues g_lmp (LMP_GP_OFF_KS_RULES -> g_lmp.gp_ks_rules);
// 2. An outer detour + thread-local flag (__declspec(thread)) scopes the call cleanly without _ReturnAddress().
static SwitchPlayerUnitFn orig_switch_player_unit;
static __declspec(thread) int g_in_air_event_switch;
static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
{
int previous = g_in_air_event_switch;
if (to_air != 0 && ground_arcade_air_events_enabled())
g_in_air_event_switch = 1;
orig_switch_player_unit(event_mgr, participant, to_air);
g_in_air_event_switch = previous;
}
// Struct offsets come from g_lmp, surviving minor client updates automatically:
const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
```
### Comparison 2: Stock Game Data — `DatasetCache` Extraction + Pure Catalogue vs. Hardcoded TS Maps
```ts
// ❌ BAD: Hardcoding tutorial mission rewards from one client build directly in server code
const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
};
```
```ts
// ✅ GOOD (Real code: apps/server/src/game-data/datasets/training-missions.ts
// + apps/server/src/training/training-completion.ts):
// 1. Define a versioned Dataset<T> that extracts stock data from char.vromfs.bin
// (config/mislist.blk, config/pve_awards.blk, config/unlocks.blk) and throws if required blocks are missing.
export const trainingMissions: Dataset<TrainingMissionsData> = {
id: 'training-missions',
version: 1,
extract(source: DatasetSource): TrainingMissionsData {
const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
if (!misSection) throw new Error('config/mislist.blk has no "training" block');
const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
// ... build and return { missions }
return { missions };
},
};
// 2. Load through DatasetCache at startup and pass pure data into TrainingCatalogue:
const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
```
### Comparison 3: Fixing at the Right Layer & Toolchain Discipline (MSVC C & Node 24 TypeScript)
**(A) Check stock loader fields before writing a client patch**
- ❌ **Bad instinct**: Notice AI bots only respawn once in multi-slot Air Arcade battles and immediately start reversing `BotSystem` to write an `aces.exe` memory patch.
- ✅ **Good engineering**: Inspect `MissionSettings::load` first and discover that the stock client already reads `numBotRespawns` and `numTankBotRespawns` from the mission root `DataBlock`—the local server simply omitted those two root parameters when assembling multi-slot missions. Adding them in `apps/server` fixes the issue in 5 lines with **zero client patches** and permanent cross-version stability.
**(B) MSVC C rules & Node 24 native TypeScript rules**
- **Native C (`native/wto-net/`)**: Compiled by Visual Studio `cl.exe` via `native/wto-net/build.ps1` with `/W4` and **zero warnings**. Verify stack/wire struct layouts at compile time with `C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);`, use `__declspec(thread)` for TLS and `__declspec(align(16))` for alignment, and **never use GCC/Clang extensions** (`__attribute__`, VLAs, zero-length arrays, or `void *` pointer arithmetic).
- **TypeScript (`tsconfig.json`)**: Executed directly by Node.js 24 native type-stripping with `erasableSyntaxOnly: true`, `verbatimModuleSyntax: true`, `allowImportingTsExtensions: true`, and `exactOptionalPropertyTypes: true`:
```ts
// ❌ BAD: Extensionless relative import, value-importing a type, using `enum`, and constructor parameter properties
import { SaveStore, SaveUpgrades } from '../saves/save-store';
export enum ResearchState { Locked = 0, Available = 1 }
export class Handler {
constructor(private readonly saves: SaveStore) {}
}
```
```ts
// ✅ GOOD: Explicit `.ts` extension on all relative imports, `import type` for types, `as const` objects instead of `enum`, and `#private` fields
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import type { SaveUpgrades } from './save-upgrades.ts';
export const VehicleStatus = {
CAN_RESEARCH: 2,
OWNED: 4,
} as const;
```
### Comparison 4: Real Verification vs. Mock Test Suites
- ❌ **Bad practice**: Editing `patches/gui/` and only eyeballing indentation—or writing 300 lines of mock unit tests that simulate fake server/client calls—and declaring the change "fully tested", only for login to hang forever on a Quirrel `from ... import *` scope collision or `loadGuiPatches` to throw `DefinitionError` on an unknown JSONC key.
- ✅ **Good practice**: Run the real verification tools matching your change (`npm run typecheck`, `wtotools check-patches`, full `wtotools check-gui` with `sq.exe`, MSVC `native\wto-net\build.ps1`, `scripts/build-game-copy.ts`), and **honestly separate executed CLI checks from pending in-game acceptance steps** in your PR description.
---
<a id="ai-guide-en"></a>
## 5. Working Effectively with AI Coding Assistants (Copy-Paste Prompt Block)
Using AI assistants (Claude Code, Codex, Cursor, etc.) to read disassembly, trace `.nut` UI call chains, inspect BLK schemas, and pinpoint protocol mismatches is warmly welcomed.
However, without explicit project context, AI tools frequently invent hardcoded RVAs, add an invalid `requires` field to `patches/gui/**/patch.jsonc`, omit `.ts` import extensions, write `enum` declarations, or generate bloated mock test suites. **Paste the constraint block below into your AI session before asking it to write or edit code**:
```text
I am preparing a change for the WTOffline repository. Before writing any code, always read the real source files to verify symbols, struct fields, and CLI flags, and follow these engineering rules strictly:
1. Layer priority: Ground every change in primary sources (read-only stock .vromfs.bin archives, gui.vromfs.bin .nut scripts, DagorEngine open-source code). Solve issues in apps/server protocol answers, mission BLK fields, or stock datasets before adding any client patch under patches/gui/, patches/exe/, or native/wto-net/.
2. Zero hardcoded addresses or offsets: Never hardcode function RVAs, global addresses, C++ struct offsets, or _ReturnAddress() caller checks in C or TS. Capture all native symbols and offsets dynamically via patches/exe/ or patches/native/*.jsonc (signature / string_ref / within) into wto_ws.cfg, read them in C exclusively through `extern LmpValues g_lmp` (local_mp_values.h / local_mp_offsets.h), and replace caller checks with an outer hook + `__declspec(thread)` flag. When capturing a `rel32` from an instruction that has trailing immediate bytes after disp32, always pass `"end"` set to the full instruction byte length.
3. Three value categories: Extract stock game numbers (vehicle prices, RP, rewards, missions, spawn params) from stock archives via `apps/server/src/game-data/datasets/` (`DatasetCache`), throwing explicitly if required fields are missing. Put offline defaults/multipliers/toggles in `apps/server/tuning/*.jsonc` validated via `*-tuning.ts`. Keep protocol/engine constants in code with English comments citing the client build RVA or DagorEngine source path.
4. Layer & dependency rules: `packages/*` must never import or read from `apps/*`. Inside `apps/server/src/`, keep transport/protocol (`char/actions/`, etc.), pure domain rules (`research/`, `battle/`, `modifications/`, etc. — note there is NO `rules/` folder; zero network/disk I/O in domain modules), and profile/persistence (`profile/`, `saves/`, `storage/atomic-file.ts` — always persist atomically to disk BEFORE replying) cleanly separated. Handle save schema evolution only via `formatVersion` steps in `saves/save-upgrades.ts`, never ad-hoc legacy branches in domain rules. Split files near 300 lines or functions near 50 lines.
5. Strict toolchain & schema rules:
- TypeScript runs on Node 24 native type-stripping (`erasableSyntaxOnly`, `verbatimModuleSyntax`, `allowImportingTsExtensions`): include explicit `.ts` extensions on all relative imports, use `import type` for type-only imports, and never use `enum`, `namespace`, or constructor parameter properties.
- Native C must compile cleanly with MSVC `native/wto-net/build.ps1` (`/W4`, zero warnings), using `C_ASSERT` for layout checks and zero GCC extensions; register any new `.c` file in `build.ps1`'s `$sources` list.
- Patch JSONC files reject unknown keys: in particular, `patches/gui/**/patch.jsonc` allows ONLY `id`, `title`, `features`, and `variants` at top level (adding `requires` throws `DefinitionError`!).
6. Real verification: Do not add large mock unit test suites. Run the applicable real checks (`npm run typecheck`, `wtotools check-patches`, full `wtotools check-gui` with `--sq`, `native/wto-net/build.ps1`, `scripts/build-game-copy.ts`) and clearly separate executed CLI checks from pending isolated in-game acceptance steps.
7. PR hygiene: Keep one focused goal per PR; write code comments, patch `title`/3-line header comments, and conventional commit messages in English; never list AI tools in `Co-authored-by`; and never commit `patches/versions/*.jsonc` before live in-game verification in an isolated copy.
```
---
<a id="isolation-en"></a>
## 6. Isolation & Asset Boundaries (Non-Negotiable)
1. **Keep the official stock installation strictly read-only**: Unpacking archives, running `tools/re/cli.py`, checking patches with `wtotools`, and building game copies must only ever read the stock client folder—**never write, modify, or drop files inside a Steam or official launcher installation**.
2. **Test exclusively in an isolated offline copy**: Run the patched client only from a separate directory outside your Steam library, with all three `ESSENTIAL_FEATURES` safety locks active—all network calls redirected to `127.0.0.1` by `wto_ws.dll`, user files isolated under `WTOffline`, registry state under `Software\WTOffline`, anti-cheat and crash reporting disabled, and signed in only with a local offline account.
3. **Zero copyrighted assets or private data in Git**: Never commit `.vromfs.bin` packs, `aces.exe`, full extracted stock `.nut` / `.blk` files, personal player saves, machine-specific paths, or unredacted logs to the repository.
+943 -44
View File
File diff suppressed because it is too large. Load diff
+18 -7
View File
@@ -1,23 +1,34 @@
## Change
<!-- Describe the player-visible result and the scope of this PR. -->
<!-- Describe the player-visible result and the single focused goal of this PR. -->
## Reason and evidence
<!-- Give the target client build and the relevant game file, script, or official source. -->
<!-- For a client patch, explain why the local service or game configuration is insufficient. -->
<!-- For tuning changes, record the source and unit of the new defaults. -->
<!-- Give the target client build (e.g. 2.61.0.37) and cite the primary source: stock archive file, .nut script, RVA, or DagorEngine source path. -->
<!-- For any client patch (patches/gui, patches/exe, native/wto-net), explain why apps/server or stock BLK configuration cannot solve it. -->
<!-- For tuning changes (apps/server/tuning/*.jsonc), record the rationale, bounds, and units of the new defaults. -->
## Client compatibility
<!-- List the affected builds and any change to patch variants or version records. -->
<!-- List the tested/affected client builds and any added patch variants or patches/versions/<version>.jsonc updates. -->
<!-- Reminder: never commit patches/versions/<version>.jsonc until live isolated in-game acceptance is complete. -->
## Self-check
- [ ] No hardcoded addresses, RVAs, C++ struct offsets, or `_ReturnAddress()` checks (all native values resolved dynamically into `g_lmp` via `patches/`, with explicit `"end"` on `rel32` captures that have trailing immediate bytes)
- [ ] No hardcoded stock game numbers or silent fallback defaults (extracted from stock archives via `game-data/datasets/` or validated in `tuning/*.jsonc`)
- [ ] Layer & persistence rules preserved (`packages/*` never imports `apps/*`; domain modules stay free of network/disk I/O; profile mutations persist atomically via `PlayerProfiles` / `SaveStore` before replying)
- [ ] Toolchain & schema rules met (explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys—e.g., no `requires` in `patches/gui/**/patch.jsonc`; new `.c` files added to `native/wto-net/build.ps1`)
- [ ] Focused on one goal, English comments / patch `title` / conventional commit message used, no AI `Co-authored-by` trailers, and no personal paths, game assets, or unredacted logs in `git diff`
- [ ] Every command listed in **Checks run** was actually executed (including `wtotools check-gui --sq ...` for `patches/gui/` and MSVC `native/wto-net/build.ps1` with zero warnings for `native/`)
## Checks run
| Command or check | Client build if relevant | Result |
| Command or check | Client build (if relevant) | Result |
| --- | --- | --- |
| | | |
## In-game acceptance
<!-- Give the screen or entry point, the action, and the expected result. Record what was observed or mark the check pending. -->
<!-- Give the exact screen or entry point, the action to perform, and the expected result in an isolated offline copy. -->
<!-- Clearly state what was observed in-game, or explicitly mark steps that are still pending live verification. -->
@@ -0,0 +1,113 @@
// Zero-heap POD types for perception exposure, shell ballistics profiles, and fire control.
options indenting = 2
options no_global_heap = true
module wto_ai_combat_types_common shared
require ecs
let public WTO_MAX_EXPOSURE_TRACKS = 8
let public WTO_MAX_VEL_SAMPLES = 6
let public WTO_MAX_SHELL_PROFILES = 12
let public WTO_BLOCK_NONE = 0
let public WTO_BLOCK_TERRAIN = 1
let public WTO_BLOCK_OBJECT = 2
let public WTO_BLOCK_WRECK = 3
let public WTO_BLOCK_VEHICLE = 4
let public WTO_BLOCK_SMOKE = 5
let public WTO_BLOCK_FOLIAGE = 6
let public WTO_DENY_OK = 0
let public WTO_DENY_NO_TARGET = 1
let public WTO_DENY_NOT_READY = 2
let public WTO_DENY_SPEED = 3
let public WTO_DENY_LONG_WINDOW = 4
let public WTO_DENY_AIM_ERR = 5
let public WTO_DENY_SETTLE = 6
let public WTO_DENY_BUDGET = 7
let public WTO_DENY_MUZZLE_HARD = 8
let public WTO_DENY_ARC_HARD = 9
let public WTO_DENY_FRIENDLY = 10
let public WTO_DENY_MULTI_GUN = 11
[safe_when_uninitialized]
struct public WtoShellProfile
nameHash : uint = 0u
speedMps : float = 880.0
dragCx : float = 0.35
massKg : float = 10.0
caliberM : float = 0.09
isSoftShell : bool = false
isAntiArmor : bool = true
[safe_when_uninitialized]
struct public WtoPerceiveState
targetEid : EntityId = INVALID_ENTITY_ID
targetIsAir : bool = false
hasClearLos : bool = false
visiblePointCount : int = 0
goodLosSec : float = 0.0
visibleAimPt : float3 = float3(0.0, 0.0, 0.0)
knownPos : float3 = float3(0.0, 0.0, 0.0)
estVel : float3 = float3(0.0, 0.0, 0.0)
velQuality : float = 0.0
sampleTargetEid : EntityId = INVALID_ENTITY_ID
sampleCount : int = 0
sampleHead : int = 0
samplePos : float3[6]
sampleAt : float[6]
wasEngaging : bool = false
watchPos : float3 = float3(0.0, 0.0, 0.0)
watchUntil : float = -100.0
oppKey : uint = 0u
oppBiasU : float = 0.0
oppBiasV : float = 0.0
oppSeeded : bool = false
lastSeenAt : float = -100.0
lockedEid : EntityId = INVALID_ENTITY_ID
lockedUntil : float = -100.0
alertYawRad : float = 0.0
alertUntil : float = -100.0
lastDamagedAt : float = -100.0
lastHitYawRad : float = 0.0
lastOffenderEid : EntityId = INVALID_ENTITY_ID
lastRadioSentAt : float = -100.0
expEids : EntityId[8]
expScore : float[8]
expGoodLosSec : float[8]
[safe_when_uninitialized]
struct public WtoFireState
turretNo : int = -1
gunReady : bool = false
reloading : bool = false
gunDamaged : bool = false
loadedBulletIdx : int = -1
activeSpeedMps : float = 880.0
activeDragCx : float = 0.35
activeMassKg : float = 10.0
activeCaliberM : float = 0.09
pitchBlocked : bool = false
pitchClampSec : float = 0.0
cmdYawDeg : float = 0.0
cmdPitchDeg : float = 0.0
curYawDeg : float = 0.0
curPitchDeg : float = 0.0
prevPitchDeg : float = 0.0
servoInit : bool = false
prevBarrelDir : float3 = float3(1.0, 0.0, 0.0)
prevBarrelAt : float = -100.0
barrelOmegaDegSec : float = 0.0
settleHoldSec : float = 0.0
lastAligned : bool = false
lastAimErrDeg : float = 0.0
lastShotAt : float = -100.0
prevLoadedAmmo : int = -1
pendingShotConfirm : bool = false
pendingShotAt : float = -100.0
lastDenyReason : int = 0
lastDenyBlock : int = 0
lastDenyLogAt : float = -100.0
shotCount : int = 0
shotErrSumDeg : float = 0.0
maxShotErrDeg : float = 0.0
@@ -0,0 +1,182 @@
// Anchor point selection and safety helpers for the team commander.
options indenting = 2
options no_global_heap = true
module wto_ai_commander_anchors_common shared
require ecs
require math
require Dacoll
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
[never_inline]
def public wto_cmd_vehicle_penalty(unitRole, cmdRole : int) : float
if cmdRole == WTO_CMD_FLANK
if unitRole == WTO_ROLE_LIGHT
return -180.0
if unitRole == WTO_ROLE_HEAVY
return 120.0
if unitRole == WTO_ROLE_TD
return 160.0
return 0.0
if cmdRole == WTO_CMD_OVERWATCH || cmdRole == WTO_CMD_DEFEND
if unitRole == WTO_ROLE_TD
return -160.0
if unitRole == WTO_ROLE_HEAVY
return -40.0
if unitRole == WTO_ROLE_LIGHT
return 120.0
return 0.0
if cmdRole == WTO_CMD_ASSAULT
if unitRole == WTO_ROLE_MEDIUM || unitRole == WTO_ROLE_HEAVY
return -80.0
if unitRole == WTO_ROLE_TD
return 140.0
return 0.0
return 0.0
[never_inline]
def public wto_cmd_log_summary(world : WtoWorldSnap const&; army : int; now : float;
candCount : int; cands : int[64]; candPos : float3[64];
capAssigned, capInsiders : int[8]; spaaCount : int;
bots : WtoBotSlot[64])
if !WTO_AI_DIAG_TELEMETRY
return
var rCnt : int[6]
for r in range(6)
rCnt[r] = 0
rCnt[WTO_CMD_SPAA] = spaaCount
var atFront = 0
for ci in range(candCount)
assume b = bots[cands[ci]]
rCnt[clamp(b.order.role, 0, 5)]++
if wto_order_is_offensive(b.order.role) && b.order.capIndex >= 0 && wto_xz_dist_sq(candPos[ci], world.caps[b.order.capIndex].center) <= 40000.0
atFront++
print("WTO_AI|CMD|t={now}|army={army}|mode={world.battleMode}|n={candCount}|roles={rCnt[0]}/{rCnt[1]}/{rCnt[2]}/{rCnt[3]}/{rCnt[5]}|caps={capAssigned[0]}/{capAssigned[1]}/{capAssigned[2]}|in={capInsiders[0]}/{capInsiders[1]}/{capInsiders[2]}|front={atFront}\n")
[never_inline]
def public wto_cmd_death_zone_kills(world : WtoWorldSnap const&; army : int; pos : float3; now : float) : int
let radSq = wto_sq(WTO_AI_MACRO_DEATH_ZONE_RAD_M)
var kills = 0
for i in range(WTO_MAX_DEATHS)
assume d = world.deaths[i]
if d.army == army && (now - d.at) <= WTO_AI_MACRO_DEATH_ZONE_TTL_SEC && wto_xz_dist_sq(pos, d.pos) <= radSq
kills++
return kills
[never_inline]
def public wto_cmd_clamp_away_enemy_spawn(world : WtoWorldSnap const&; army : int; pos : float3) : float3
let enemyArmy = army == 1 ? 2 : 1
if enemyArmy < 1 || enemyArmy > 2 || !world.teamSpawnValid[enemyArmy]
return pos
let eSpawn = world.teamSpawnCenter[enemyArmy]
let minDist = WTO_AI_MACRO_ENEMY_SPAWN_AVOID_M
let dSq = wto_xz_dist_sq(pos, eSpawn)
if dSq >= minDist * minDist
return pos
let away = wto_xz_normalize(pos - eSpawn, float3(1.0, 0.0, 0.0))
return float3(eSpawn.x + away.x * minDist, pos.y, eSpawn.z + away.z * minDist)
[never_inline]
def private wto_try_anchor_candidate(world : WtoWorldSnap const&; army : int; rawPos : float3;
var outPos : float3&) : bool
var cand = wto_cmd_clamp_away_enemy_spawn(world, army, rawPos)
cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0)
if wto_terrain_point_valid(army, cand)
outPos = cand
return true
return false
[never_inline]
def public wto_cmd_pick_role_anchor(world : WtoWorldSnap const&; army : int; eid : EntityId;
capIdx, cmdRole : int; insideCircle : bool) : float3
assume cap = world.caps[capIdx]
let h = uint(eid)
let friendlySpawn = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter
let toCap = wto_xz_normalize(cap.center - friendlySpawn, float3(1.0, 0.0, 0.0))
let lat = float3(-toCap.z, 0.0, toCap.x)
var chosen = cap.center
if cmdRole == WTO_CMD_ASSAULT && insideCircle
let slotAng = float(h % 5u) * (2.0 * WTO_PI / 5.0) + float(capIdx) * 0.7
let inRad = clamp(cap.radius * 0.52, 7.0, max(8.0, cap.radius - 4.5))
var pt = float3(cap.center.x + cos(slotAng) * inRad, cap.center.y, cap.center.z + sin(slotAng) * inRad)
if wto_terrain_point_valid(army, pt)
return pt
return cap.center
let sideSign = (h & 1u) == 0u ? 1.0 : -1.0
let tier = float((h / 2u) % 3u)
var latDist = cap.radius + 18.0 + tier * 12.0
var backDist = 14.0 + tier * 10.0
if cmdRole == WTO_CMD_FLANK
latDist = max(cap.radius + 20.0, WTO_AI_CMD_FLANK_STANDOFF_M + tier * 16.0)
backDist = 8.0 - tier * 12.0
elif cmdRole == WTO_CMD_OVERWATCH
latDist = (tier - 1.0) * 34.0 + sideSign * 22.0
backDist = max(cap.radius + 25.0, WTO_AI_CMD_OVERWATCH_STANDOFF_M + tier * 18.0)
elif cmdRole == WTO_CMD_DEFEND || cmdRole == WTO_CMD_RESERVE
latDist = sideSign * (cap.radius + 14.0 + tier * 12.0)
backDist = 12.0 + tier * 10.0
for attempt in range(4)
let flip = (attempt == 1 || attempt == 3) ? -1.0 : 1.0
let scale = attempt >= 2 ? 0.6 : 1.0
let cand = cap.center + lat * (sideSign * latDist * flip * scale) - toCap * (backDist * scale)
if wto_try_anchor_candidate(world, army, cand, chosen)
return chosen
return wto_clamp_battle_xz(cap.center - toCap * (cap.radius + 18.0), world.battleCenter, world.battleRadius, 40.0)
[never_inline]
def private wto_cmd_has_open_sky(pos : float3) : bool
var p0 = pos + float3(0.0, 2.5, 0.0)
let upDir = float3(0.0, 1.0, 0.0)
return !rayhit_normalized(p0, upDir, 45.0, ETF_ALL, -1)
[never_inline]
def public wto_cmd_assign_spaa(world : WtoWorldSnap const&; now : float; myPos, frontPt : float3;
airActive : bool; var slot : WtoBotSlot&)
let army = slot.army
assume ord = slot.order
let needNew = !ord.spaaAnchorValid || now >= ord.spaaRelocateAt || (slot.fire.lastShotAt > ord.spaaRelocateAt - WTO_AI_MACRO_SPAA_RELOCATE_SEC && (now - slot.fire.lastShotAt) > 3.0)
if needNew
let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : myPos
let toFront = wto_xz_normalize(frontPt - spawnPt, float3(1.0, 0.0, 0.0))
let lat = float3(-toFront.z, 0.0, toFront.x)
let followOff = airActive ? (WTO_AI_CMD_SPAA_FOLLOW_OFFSET_M * 1.15) : WTO_AI_CMD_SPAA_FOLLOW_OFFSET_M
let base = frontPt - toFront * followOff
let tickIdx = max(0, int(now / max(5.0, WTO_AI_MACRO_SPAA_RELOCATE_SEC)))
var picked = myPos
var foundOpen = false
for attempt in range(5)
let phase = int((uint(slot.eid) + uint(tickIdx) + uint(attempt)) % 5u)
let side = float(phase - 2) * 42.0
var cand = wto_clamp_battle_xz(base + lat * side, world.battleCenter, world.battleRadius, 45.0)
cand = wto_cmd_clamp_away_enemy_spawn(world, army, cand)
if !wto_terrain_point_valid(army, cand)
continue
if !foundOpen
picked = cand
if wto_cmd_has_open_sky(cand)
picked = cand
foundOpen = true
break
ord.spaaAnchorPos = picked
ord.spaaAnchorValid = true
ord.spaaRelocateAt = now + WTO_AI_MACRO_SPAA_RELOCATE_SEC
ord.role = WTO_CMD_SPAA
ord.capIndex = -1
ord.laneId = 0
ord.routeRelayValid = false
ord.rallyHold = false
ord.goalPos = ord.spaaAnchorPos
ord.urgency = airActive ? WTO_URGENCY_MED : WTO_URGENCY_LOW
ord.maxStopRangeM = wto_order_max_stop_range(WTO_CMD_SPAA, ord.urgency, WTO_AI_FC_MAX_RANGE_M)
ord.overwatchOutside = true
ord.cautious = false
ord.assignedAt = now
ord.expiresAt = now + WTO_AI_MACRO_SPAA_RELOCATE_SEC
ord.valid = true
+197
View File
@@ -0,0 +1,197 @@
// Whole-team commander (v1): mode-aware role quotas (Bttl / Conq / Dom), deterministic
// distance + vehicle-suitability matching, 20-second role hysteresis, separate total-assigned
// vs insider counters, and per-team assignment telemetry.
options indenting = 2
options no_global_heap = true
module wto_ai_commander_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_lanes_common
require %appGame.wtoai.wto_ai_commander_anchors_common
require %appGame.wtoai.wto_ai_commander_plans_common
[never_inline]
def private wto_cmd_apply_order(world : WtoWorldSnap const&; army : int; now : float;
capIdx, cmdRole, urgency : int; lanes : WtoTeamLanes const&;
var capInsiders : int[8]&; var capAssigned : int[8]&;
var slot : WtoBotSlot&)
assume ord = slot.order
let sameTask = ord.valid && ord.role == cmdRole && ord.capIndex == capIdx
let insideCircle = cmdRole == WTO_CMD_ASSAULT && capInsiders[capIdx] < WTO_AI_MACRO_CAP_MAX_INSIDERS
if insideCircle
capInsiders[capIdx]++
capAssigned[capIdx]++
ord.role = cmdRole
ord.capIndex = capIdx
ord.urgency = urgency
ord.maxStopRangeM = wto_order_max_stop_range(cmdRole, urgency, WTO_AI_FC_MAX_RANGE_M)
ord.overwatchOutside = !insideCircle
ord.cautious = wto_cmd_death_zone_kills(world, army, world.caps[capIdx].center, now) >= WTO_AI_MACRO_DEATH_ZONE_MIN_KILLS
ord.goalPos = wto_cmd_pick_role_anchor(world, army, slot.eid, capIdx, cmdRole, insideCircle)
// Assign validated navmesh lane (center / left flank / right flank) and rally staging point.
let ck = wto_lanes_cap_key(army, capIdx)
ord.laneId = WTO_LANE_CENTER
ord.routeRelayValid = false
ord.rallyHold = false
if cmdRole == WTO_CMD_FLANK
let prefSide = int(uint(slot.eid) & 1u)
let altSide = 1 - prefSide
if lanes.flankValid[ck * 2 + prefSide]
ord.laneId = prefSide + 1
ord.routeRelayValid = true
ord.routeRelayPos = lanes.flankRelay[ck * 2 + prefSide]
elif lanes.flankValid[ck * 2 + altSide]
ord.laneId = altSide + 1
ord.routeRelayValid = true
ord.routeRelayPos = lanes.flankRelay[ck * 2 + altSide]
if wto_order_is_offensive(cmdRole)
let sk = wto_lanes_sub_key(army, capIdx, ord.laneId)
if !lanes.rallyReleased[sk] && length_sq(lanes.rallyPos[sk]) > 1.0
ord.rallyHold = true
ord.routeRelayValid = true
ord.routeRelayPos = lanes.rallyPos[sk]
if !sameTask
ord.assignedAt = now
ord.expiresAt = now + max(10.0, WTO_AI_CMD_ROLE_HOLD_SEC * 2.0)
ord.valid = true
[never_inline]
def private wto_cmd_match_and_log(world : WtoWorldSnap const&; army : int; now : float; forceRebalance : bool;
lanes : WtoTeamLanes const&;
candCount : int; cands : int[64]; candPos : float3[64];
dCount : int; dCap : int[64]; dRole : int[64]; dUrg : int[64];
spaaCount : int; var bots : WtoBotSlot[64]&)
var botUsed : bool[64]
var demUsed : bool[64]
for i in range(WTO_MAX_BOTS)
botUsed[i] = false
demUsed[i] = false
var capInsiders : int[8]
var capAssigned : int[8]
for c in range(WTO_MAX_CAPS)
capInsiders[c] = 0
capAssigned[c] = 0
if !forceRebalance
for ci in range(candCount)
let bIdx = cands[ci]
assume ord = bots[bIdx].order
if !ord.valid || (now - ord.assignedAt) >= WTO_AI_CMD_ROLE_HOLD_SEC || now >= ord.expiresAt
continue
for di in range(dCount)
if !demUsed[di] && dCap[di] == ord.capIndex && dRole[di] == ord.role
demUsed[di] = true
botUsed[ci] = true
wto_cmd_apply_order(world, army, now, dCap[di], dRole[di], dUrg[di], lanes, capInsiders, capAssigned, bots[bIdx])
break
for di in range(dCount)
if demUsed[di]
continue
var bestCi = -1
var bestScore = 1.0e12
var bestEid = 0xffffffffu
let tgtPos = world.caps[dCap[di]].center
for ci in range(candCount)
if botUsed[ci]
continue
let bIdx = cands[ci]
let dist = sqrt(wto_xz_dist_sq(candPos[ci], tgtPos))
let sc = dist + wto_cmd_vehicle_penalty(bots[bIdx].spec.role, dRole[di])
let eidU = uint(bots[bIdx].eid)
if sc < bestScore - 0.1 || (abs(sc - bestScore) <= 0.1 && eidU < bestEid)
bestScore = sc
bestEid = eidU
bestCi = ci
if bestCi >= 0
demUsed[di] = true
botUsed[bestCi] = true
wto_cmd_apply_order(world, army, now, dCap[di], dRole[di], dUrg[di], lanes, capInsiders, capAssigned, bots[cands[bestCi]])
wto_cmd_log_summary(world, army, now, candCount, cands, candPos, capAssigned, capInsiders, spaaCount, bots)
[never_inline]
def private wto_cmd_assign_army(world : WtoWorldSnap const&; army : int; now : float;
forceRebalance : bool; var lanes : WtoTeamLanes&;
var bots : WtoBotSlot[64]&)
var cands : int[64]
var candPos : float3[64]
var spaaIdx : int[64]
var spaaPos : float3[64]
var candCount = 0
var spaaCount = 0
for i in range(WTO_MAX_BOTS)
if !bots[i].used || bots[i].army != army
continue
let uIdx = wto_world_find_unit(world, bots[i].eid)
if uIdx < 0
continue
if bots[i].spec.role == WTO_ROLE_SPAA
spaaIdx[spaaCount] = i
spaaPos[spaaCount] = world.units[uIdx].pos
spaaCount++
else
cands[candCount] = i
candPos[candCount] = world.units[uIdx].pos
candCount++
if world.capCount <= 0
for ci in range(candCount)
assume ord = bots[cands[ci]].order
ord.role = WTO_CMD_ASSAULT
ord.capIndex = -1
ord.laneId = WTO_LANE_CENTER
ord.routeRelayValid = false
ord.rallyHold = false
ord.goalPos = wto_cmd_clamp_away_enemy_spawn(world, army, world.battleCenter)
ord.urgency = WTO_URGENCY_MED
ord.maxStopRangeM = 300.0
ord.assignedAt = now
ord.expiresAt = now + 30.0
ord.valid = true
for si in range(spaaCount)
wto_cmd_assign_spaa(world, now, spaaPos[si], world.battleCenter, lanes.enemyAirActive[army], bots[spaaIdx[si]])
return
var enemiesInCap : int[8]
wto_lanes_update_recall(world, army, now, lanes, enemiesInCap)
for c in range(world.capCount)
wto_lanes_ensure_cap(world, army, c, lanes)
var dCap : int[64]
var dRole : int[64]
var dUrg : int[64]
var dCount = 0
var primaryCap = 0
if candCount > 0
if world.battleMode == WTO_MODE_BTTL
primaryCap = wto_cmd_plan_bttl(world, army, candCount, dCap, dRole, dUrg, dCount)
elif world.battleMode == WTO_MODE_CONQ || world.capCount == 1
primaryCap = wto_cmd_plan_conq(world, army, candCount, dCap, dRole, dUrg, dCount)
else
primaryCap = wto_cmd_plan_dom(world, army, candCount, dCap, dRole, dUrg, dCount)
wto_cmd_apply_recall_demands(world, army, candCount, lanes, enemiesInCap, dCap, dRole, dUrg, dCount)
wto_cmd_match_and_log(world, army, now, forceRebalance, lanes, candCount, cands, candPos, dCount, dCap, dRole, dUrg, spaaCount, bots)
var frontPt = world.caps[clamp(primaryCap, 0, world.capCount - 1)].center
var assaultSum = float3(0.0, 0.0, 0.0)
var assaultCnt = 0
for ci in range(candCount)
if bots[cands[ci]].order.role == WTO_CMD_ASSAULT
assaultSum += candPos[ci]
assaultCnt++
if assaultCnt > 0
frontPt = assaultSum / float(assaultCnt)
for si in range(spaaCount)
wto_cmd_assign_spaa(world, now, spaaPos[si], frontPt, lanes.enemyAirActive[army], bots[spaaIdx[si]])
[never_inline]
def public wto_commander_update_all(world : WtoWorldSnap const&; now : float;
forceRebalance : bool; var lanes : WtoTeamLanes&;
var bots : WtoBotSlot[64]&)
wto_lanes_update_team_intel(world, now, lanes)
wto_cmd_assign_army(world, 1, now, forceRebalance, lanes, bots)
wto_cmd_assign_army(world, 2, now, forceRebalance, lanes, bots)
wto_lanes_update_rallies(world, 1, now, lanes, bots)
wto_lanes_update_rallies(world, 2, now, lanes, bots)
@@ -0,0 +1,168 @@
// Mode-aware team quota planners (Bttl / Conq / Dom) and dynamic recall demand overrides.
options indenting = 2
options no_global_heap = true
module wto_ai_commander_plans_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_lanes_common
[never_inline]
def private wto_cmd_push_demands(capIdx, role, urgency, count : int;
var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&;
var dCount : int&)
for _k in range(count)
if dCount >= WTO_MAX_BOTS
return
dCap[dCount] = capIdx
dRole[dCount] = role
dUrg[dCount] = urgency
dCount++
[never_inline]
def public wto_cmd_plan_bttl(world : WtoWorldSnap const&; army, n : int;
var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&;
var dCount : int&) : int
let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter
var enemyCap = -1
var friendlyCap = -1
var bestEnemyD = 1.0e12
var bestFriendD = 1.0e12
for c in range(world.capCount)
let dSq = wto_xz_dist_sq(spawnPt, world.caps[c].center)
if world.caps[c].ownerArmy != army && dSq < bestEnemyD
bestEnemyD = dSq
enemyCap = c
elif world.caps[c].ownerArmy == army && dSq < bestFriendD
bestFriendD = dSq
friendlyCap = c
if enemyCap < 0
enemyCap = friendlyCap >= 0 ? (world.capCount > 1 ? (1 - friendlyCap) : friendlyCap) : 0
if friendlyCap < 0
friendlyCap = enemyCap
let nAssault = clamp((n * WTO_AI_CMD_BTTL_ASSAULT_PCT + 50) / 100, 1, n)
let rem1 = max(0, n - nAssault)
let nFlank = min(rem1, (n * WTO_AI_CMD_BTTL_FLANK_PCT + 50) / 100)
let rem2 = max(0, rem1 - nFlank)
let nOverwatch = min(rem2, (n * WTO_AI_CMD_BTTL_OVERWATCH_PCT + 50) / 100)
let nDefend = max(0, rem2 - nOverwatch)
let defUrg = world.caps[friendlyCap].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW
wto_cmd_push_demands(enemyCap, WTO_CMD_ASSAULT, WTO_URGENCY_HIGH, nAssault, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(enemyCap, WTO_CMD_FLANK, WTO_URGENCY_HIGH, nFlank, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(enemyCap, WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(friendlyCap, WTO_CMD_DEFEND, defUrg, nDefend, dCap, dRole, dUrg, dCount)
return enemyCap
[never_inline]
def public wto_cmd_plan_conq(world : WtoWorldSnap const&; army, n : int;
var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&;
var dCount : int&) : int
if world.caps[0].ownerArmy != army
let nAssault = clamp((n * WTO_AI_CMD_CONQ_ASSAULT_PCT + 50) / 100, 1, n)
let rem1 = max(0, n - nAssault)
let nFlank = min(rem1, (n * WTO_AI_CMD_CONQ_FLANK_PCT + 50) / 100)
let nOverwatch = max(0, rem1 - nFlank)
wto_cmd_push_demands(0, WTO_CMD_ASSAULT, WTO_URGENCY_HIGH, nAssault, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(0, WTO_CMD_FLANK, WTO_URGENCY_HIGH, nFlank, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(0, WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount)
else
let nDefend = min(n, (n * WTO_AI_CMD_CONQ_HOLD_DEFEND_PCT + 50) / 100)
let rem1 = max(0, n - nDefend)
let nOverwatch = min(rem1, (n * WTO_AI_CMD_CONQ_HOLD_OVERWATCH_PCT + 50) / 100)
let nFlank = max(0, rem1 - nOverwatch)
let defUrg = world.caps[0].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW
wto_cmd_push_demands(0, WTO_CMD_DEFEND, defUrg, nDefend, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(0, WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(0, WTO_CMD_FLANK, WTO_URGENCY_MED, nFlank, dCap, dRole, dUrg, dCount)
return 0
[never_inline]
def public wto_cmd_plan_dom(world : WtoWorldSnap const&; army, n : int;
var dCap : int[64]&; var dRole : int[64]&; var dUrg : int[64]&;
var dCount : int&) : int
let spawnPt = world.teamSpawnValid[army] ? world.teamSpawnCenter[army] : world.battleCenter
var prio : int[2]
prio[0] = -1
prio[1] = -1
var prioCnt = 0
var bestMidScore = 1.0e12
for c in range(world.capCount)
if world.caps[c].ownerArmy != army
let sc = wto_xz_dist_sq(world.caps[c].center, world.battleCenter)
if sc < bestMidScore
bestMidScore = sc
prio[0] = c
if prio[0] >= 0
prioCnt = 1
var bestNear = 1.0e12
for c in range(world.capCount)
if c != prio[0] && world.caps[c].ownerArmy != army
let sc = wto_xz_dist_sq(world.caps[c].center, spawnPt)
if sc < bestNear
bestNear = sc
prio[1] = c
if prio[1] >= 0
prioCnt = 2
var remaining = n
for c in range(world.capCount)
if world.caps[c].ownerArmy == army && remaining > (prioCnt > 0 ? 1 : 0)
let keep = min(WTO_AI_CMD_DOM_MAX_DEFENDERS, remaining - (prioCnt > 0 ? 1 : 0))
let urg = world.caps[c].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW
wto_cmd_push_demands(c, WTO_CMD_DEFEND, urg, keep, dCap, dRole, dUrg, dCount)
remaining -= keep
if prioCnt == 0
let perCap = max(1, remaining / max(1, world.capCount))
for c in range(world.capCount)
let take = c == world.capCount - 1 ? remaining : min(remaining, perCap)
let urg = world.caps[c].contested ? WTO_URGENCY_HIGH : WTO_URGENCY_LOW
wto_cmd_push_demands(c, WTO_CMD_OVERWATCH, urg, take, dCap, dRole, dUrg, dCount)
remaining -= take
return 0
let firstShare = prioCnt == 1 ? remaining : (remaining + 1) / 2
for p in range(prioCnt)
let share = p == 0 ? firstShare : (remaining - firstShare)
if share <= 0
continue
let nAssault = clamp((share * WTO_AI_CMD_DOM_ASSAULT_PCT + 50) / 100, 1, share)
let nOverwatch = max(0, share - nAssault)
wto_cmd_push_demands(prio[p], WTO_CMD_ASSAULT, WTO_URGENCY_HIGH, nAssault, dCap, dRole, dUrg, dCount)
wto_cmd_push_demands(prio[p], WTO_CMD_OVERWATCH, WTO_URGENCY_MED, nOverwatch, dCap, dRole, dUrg, dCount)
return prio[0]
[never_inline]
def public wto_cmd_apply_recall_demands(world : WtoWorldSnap const&; army, n : int;
lanes : WtoTeamLanes const&; enemiesInCap : int[8];
var dCap : int[64]&; var dRole : int[64]&;
var dUrg : int[64]&; dCount : int)
for c in range(world.capCount)
let k = wto_lanes_cap_key(army, c)
if !lanes.recallActive[k]
continue
let needed = clamp(enemiesInCap[c] + 1, 1, max(1, n - 1))
var curDef = 0
var curOff = 0
for di in range(dCount)
if dCap[di] == c && dRole[di] == WTO_CMD_DEFEND
dUrg[di] = WTO_URGENCY_HIGH
curDef++
if wto_order_is_offensive(dRole[di])
curOff++
for stage in range(2)
for di in range(dCount)
if curDef >= needed
break
if dCap[di] == c && dRole[di] == WTO_CMD_DEFEND
continue
let isSupport = dRole[di] == WTO_CMD_RESERVE || dRole[di] == WTO_CMD_OVERWATCH
let canPullOff = stage == 1 && wto_order_is_offensive(dRole[di]) && curOff > 1
if (stage == 0 && isSupport) || canPullOff
if wto_order_is_offensive(dRole[di])
curOff--
dCap[di] = c
dRole[di] = WTO_CMD_DEFEND
dUrg[di] = WTO_URGENCY_HIGH
curDef++
+121
View File
@@ -0,0 +1,121 @@
// Cover memory, hull concealment check, 9-candidate retreat cover search, and
// enemy-free repair cover search (plan sections 5.1, 6, 6.1).
options indenting = 2
options no_global_heap = true
module wto_ai_cover_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_sight_common
[never_inline]
def public wto_cover_is_hull_concealed(world : WtoWorldSnap const&;
selfEid, targetEid : EntityId;
myPos, threatPos : float3) : bool
let myHull = myPos + float3(0.0, 1.15, 0.0)
let tgtEye = threatPos + float3(0.0, 1.85, 0.0)
return wto_sight_hard_segment_blocked(world, selfEid, targetEid, myHull, tgtEye, 0.0, 0.45, 0.65) != WTO_BLOCK_NONE
[never_inline]
def public wto_cover_update_memory(world : WtoWorldSnap const&; now : float;
myPos : float3; var slot : WtoBotSlot&)
assume tac = slot.tactics
assume p = slot.perceive
if tac.state == WTO_STATE_RETREAT_COVER || tac.state == WTO_STATE_COVER_RELOAD || tac.state == WTO_STATE_DISABLED
return
if !p.targetEid || p.targetIsAir || (now - p.lastSeenAt) > WTO_AI_TACTICS_MEMORY_TTL_SEC
return
if wto_cover_is_hull_concealed(world, slot.eid, p.targetEid, myPos, p.knownPos)
tac.lastCoverPos = myPos
tac.lastCoverValid = true
tac.lastCoverAt = now
[never_inline]
def private wto_cover_enemy_danger(world : WtoWorldSnap const&; now : float;
army : int; cand : float3) : float
var danger = 0.0
let safeR = WTO_AI_SM_REPAIR_SAFE_DIST_M
let safeRSq = safeR * safeR
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army == army
continue
let dSq = wto_xz_dist_sq(cand, u.pos)
if dSq < safeRSq
let d = sqrt(dSq)
danger += (safeR - d) * 2.5
for r in range(WTO_MAX_RADIO)
assume sp = world.radioSpots[r]
if sp.untilAt <= now || sp.army != army
continue
let dSq = wto_xz_dist_sq(cand, sp.pos)
if dSq < safeRSq
let d = sqrt(dSq)
danger += (safeR - d) * 1.2
return danger
[never_inline]
def private wto_cover_eval_candidate(world : WtoWorldSnap const&; now : float;
myPos, threatPos, spawnDir : float3;
avoidEnemies : bool; isOriginalCover : bool;
candIn : float3; slot : WtoBotSlot const&;
var bestScore : float&; var outPos : float3&) : bool
var cand = wto_clamp_battle_xz(candIn, world.battleCenter, world.battleRadius, 35.0)
if !wto_terrain_point_valid(slot.army, cand)
return false
if !wto_cover_is_hull_concealed(world, slot.eid, slot.perceive.targetEid, cand, threatPos)
return false
let dist = sqrt(wto_xz_dist_sq(myPos, cand))
var sc = dist
if isOriginalCover
sc -= 14.0
let stepDir = wto_xz_normalize(cand - myPos, spawnDir)
sc -= dot(stepDir, spawnDir) * (avoidEnemies ? 18.0 : 6.0)
if avoidEnemies
sc += wto_cover_enemy_danger(world, now, slot.army, cand)
if sc < bestScore
bestScore = sc
outPos = cand
return true
return false
[never_inline]
def public wto_cover_pick_candidate(world : WtoWorldSnap const&; now : float;
myPos, threatPos : float3; avoidEnemies : bool;
slot : WtoBotSlot const&; var outPos : float3&) : bool
let threatDir = wto_xz_normalize(threatPos - myPos, float3(1.0, 0.0, 0.0))
let away = -threatDir
let lat = float3(-threatDir.z, 0.0, threatDir.x)
let spawnDir = world.teamSpawnValid[slot.army] ? wto_xz_normalize(world.teamSpawnCenter[slot.army] - myPos, away) : away
var bestScore = 1.0e9
var found = false
// Candidate 0: remembered last cover position along the peek path.
assume tac = slot.tactics
if tac.lastCoverValid && (now - tac.lastCoverAt) <= 25.0
let dOrig = sqrt(wto_xz_dist_sq(myPos, tac.lastCoverPos))
if dOrig >= WTO_AI_SM_COVER_MIN_DIST_M && dOrig <= (avoidEnemies ? 45.0 : WTO_AI_SM_COVER_MAX_DIST_M)
if wto_cover_eval_candidate(world, now, myPos, threatPos, spawnDir, avoidEnemies, true, tac.lastCoverPos, slot, bestScore, outPos)
found = true
// Candidates 1..8: two rings (rear + side-rear) around current position.
let r1 = avoidEnemies ? 24.0 : 14.0
let r2 = avoidEnemies ? 44.0 : 24.0
var offsets : float3[8]
offsets[0] = away * r1
offsets[1] = wto_xz_normalize(away + lat * 0.75, away) * r1
offsets[2] = wto_xz_normalize(away - lat * 0.75, away) * r1
offsets[3] = lat * r1
offsets[4] = -lat * r1
offsets[5] = away * r2
offsets[6] = wto_xz_normalize(away + lat * 0.9, away) * r2
offsets[7] = wto_xz_normalize(away - lat * 0.9, away) * r2
for k in range(8)
if wto_cover_eval_candidate(world, now, myPos, threatPos, spawnDir, avoidEnemies, false, myPos + offsets[k], slot, bestScore, outPos)
found = true
return found
+128
View File
@@ -0,0 +1,128 @@
// Anti-clustering telemetry & active dispersion solver: measures local friendly density around
// every tracked bot, updates match-wide crowd statistics for `.clog`, and computes drivable
// lateral/oblique dispersion anchors whenever allies bunch up.
options indenting = 2
options no_global_heap = true
module wto_ai_crowd_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
def public wto_crowd_point_penalty(world : WtoWorldSnap const&; army : int; selfEid : EntityId;
pt : float3) : float
let rad = max(12.0, WTO_AI_CROWD_CLUSTER_RADIUS_M)
let radSq = rad * rad
var pen = 0.0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid
continue
let dSq = wto_xz_dist_sq(pt, u.pos)
if dSq < radSq
let d = sqrt(dSq)
pen += (1.0 - d / rad) * 24.0
if d < WTO_AI_CROWD_PERSONAL_SPACE_M
pen += (WTO_AI_CROWD_PERSONAL_SPACE_M - d) * 4.5
return pen
[never_inline]
def private wto_eval_bot_crowd(world : WtoWorldSnap const&; myPos : float3; mySpeed : float;
slot : WtoBotSlot const&; var outInfo : WtoCrowdInfo&)
outInfo = WtoCrowdInfo()
let personalSq = wto_sq(WTO_AI_CROWD_PERSONAL_SPACE_M)
let clusterSq = wto_sq(WTO_AI_CROWD_CLUSTER_RADIUS_M)
var repulse = float3(0.0, 0.0, 0.0)
var nearestSpeed = 0.0
var higherPriorityAllies = 0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != slot.army || u.eid == slot.eid
continue
let dSq = wto_xz_dist_sq(myPos, u.pos)
if dSq >= clusterSq
continue
let d = max(0.5, sqrt(dSq))
outInfo.clusterAllyCount++
if u.isHuman || uint(u.eid) < uint(slot.eid)
higherPriorityAllies++
if d < outInfo.nearestAllyDistM
outInfo.nearestAllyDistM = d
outInfo.nearestAllyEid = u.eid
nearestSpeed = wto_xz_len(u.vel)
if dSq <= personalSq
outInfo.nearPersonalCount++
let away = wto_xz_normalize(myPos - u.pos, float3(1.0, 0.0, 0.0))
let w = clamp((WTO_AI_CROWD_CLUSTER_RADIUS_M - d) / max(4.0, d), 0.15, 6.0)
repulse += away * w
let hashYaw = float(int(uint(slot.eid) % 7u) - 3) * 0.45
let fallbackDir = float3(cos(hashYaw), 0.0, sin(hashYaw))
outInfo.repulseDirXZ = wto_xz_normalize(repulse, fallbackDir)
// Trigger dispersion when personal space is violated (yielding to human or lower-eid leader,
// or whenever both tanks are nearly parked) OR when local cluster exceeds max allies.
let yieldPair = higherPriorityAllies > 0 || (mySpeed < 1.5 && nearestSpeed < 1.5)
if outInfo.nearPersonalCount > 0 && yieldPair
outInfo.isCrowded = true
elif outInfo.clusterAllyCount >= WTO_AI_CROWD_CLUSTER_MAX_ALLIES && higherPriorityAllies >= 1
outInfo.isCrowded = true
[never_inline]
def public wto_crowd_update_all(world : WtoWorldSnap const&; var bots : WtoBotSlot[64]&;
var summary : WtoCrowdSummary&)
summary.crowdedBotCount = 0
summary.maxClusterSize = 1
summary.minPairDistM = 999.0
for i in range(WTO_MAX_BOTS)
if !bots[i].used
continue
let uIdx = wto_world_find_unit(world, bots[i].eid)
if uIdx < 0
bots[i].crowd = WtoCrowdInfo()
continue
let myPos = world.units[uIdx].pos
let mySpd = wto_xz_len(world.units[uIdx].vel)
wto_eval_bot_crowd(world, myPos, mySpd, bots[i], bots[i].crowd)
if bots[i].crowd.isCrowded
summary.crowdedBotCount++
summary.maxClusterSize = max(summary.maxClusterSize, bots[i].crowd.clusterAllyCount + 1)
summary.minPairDistM = min(summary.minPairDistM, bots[i].crowd.nearestAllyDistM)
// Pick a drivable dispersion target 22..34m laterally/away from the cluster that maximizes
// spacing from teammates without stepping onto a cliff or into enemy spawn.
[never_inline]
def public wto_crowd_pick_disperse_pos(world : WtoWorldSnap const&; army : int; selfEid : EntityId;
myPos, threatDirXZ : float3; crowd : WtoCrowdInfo const&) : float3
let fwd = wto_xz_normalize(threatDirXZ, float3(1.0, 0.0, 0.0))
let lat = float3(-fwd.z, 0.0, fwd.x)
let rep = wto_xz_normalize(crowd.repulseDirXZ, lat)
let baseYaw = atan2(rep.z, rep.x)
let stepM = WTO_AI_CROWD_DISPERSE_STEP_M
let sideBias = (uint(selfEid) & 1u) == 0u ? 1.0 : -1.0
var bestPos = myPos + rep * stepM
var bestScore = -1.0e9
for k in range(8)
let angOff = float(k - 3) * 0.52 * sideBias
let candYaw = baseYaw + angOff
let dir = float3(cos(candYaw), 0.0, sin(candYaw))
var cand = float3(myPos.x + dir.x * stepM, myPos.y, myPos.z + dir.z * stepM)
cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 35.0)
if !wto_terrain_point_valid(army, cand)
continue
if wto_terrain_has_cliff_ahead(myPos, dir, min(stepM, 18.0))
continue
if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), dir, min(stepM, 16.0)) < 9.0
continue
// Prefer lateral dispersion over pushing blindly forward into enemy guns.
let fwdProj = dot(dir, fwd)
let repAlign = dot(dir, rep) * 14.0
let latBonus = (1.0 - abs(fwdProj)) * 12.0 - max(0.0, fwdProj) * 8.0
let score = repAlign + latBonus - wto_crowd_point_penalty(world, army, selfEid, cand)
if score > bestScore
bestScore = score
bestPos = cand
return bestPos
+64
View File
@@ -0,0 +1,64 @@
// Periodic telemetry and sample logging for the ground AI runtime.
options indenting = 2
options no_global_heap = true
module wto_ai_diag_common shared
require ecs
require math
require pathfinder
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
def private wto_log_bot_and_cap_samples(world : WtoWorldSnap const&; bots : WtoBotSlot[64])
var sampled = 0
for i in range(WTO_MAX_BOTS)
if !bots[i].used || sampled >= 2
continue
assume b = bots[i]
print("WTO_AI|BOT_SAMPLE|eid={uint(b.eid)}|role={b.spec.role}|stab={b.spec.hasVertStab}|v0={b.fire.activeSpeedMps}|st={b.tactics.state}|allyD={b.crowd.nearestAllyDistM}|clust={b.crowd.clusterAllyCount}|ridge={b.tactics.onExposedRidge}|los={b.perceive.hasClearLos}|fc={b.fire.gunReady}/{b.fire.reloading}/{b.fire.lastAligned}|err={b.fire.lastAimErrDeg}|omB={b.fire.barrelOmegaDegSec}|mode={b.driveCmd.mode}|v={b.drive.lastVFwd}|clr={b.nav.frontClearM}/{b.nav.rearClearM}|wp={b.route.corridorIdx}/{b.route.corridorLen}|proj={b.route.lastStartOk}/{b.route.lastGoalOk}\n")
sampled++
for c in range(world.capCount)
assume z = world.caps[c]
print("WTO_AI|CAP|idx={c}|owner={z.ownerArmy}|rad={z.radius}|prog={z.progress}\n")
[never_inline]
def public wto_diag_log_telemetry(world : WtoWorldSnap const&; now : float;
bots : WtoBotSlot[64]; crowd : WtoCrowdSummary const&)
var active = 0
var routeB = 0
var revNow = 0
var engNow = 0
var dispNow = 0
var ridgeNow = 0
var revEvents = 0
var ridgeWithdraws = 0
var detours = 0
var shots = 0
var errSum = 0.0
var maxErr = 0.0
var roles : int[5]
for r in range(5)
roles[r] = 0
for i in range(WTO_MAX_BOTS)
if !bots[i].used
continue
assume b = bots[i]
active++
roles[clamp(b.spec.role, 0, 4)]++
routeB += b.drive.routeBOwned ? 1 : 0
revNow += b.driveCmd.mode == WTO_DRIVE_REVERSE ? 1 : 0
engNow += b.tactics.state == WTO_STATE_SHORT_HALT ? 1 : 0
dispNow += b.tactics.state == WTO_STATE_DISPERSE ? 1 : 0
ridgeNow += b.tactics.onExposedRidge ? 1 : 0
revEvents += b.nav.reverseCount
ridgeWithdraws += b.nav.ridgeWithdrawEvents
detours += b.route.detourCount
shots += b.fire.shotCount
errSum += b.fire.shotErrSumDeg
maxErr = max(maxErr, b.fire.maxShotErrDeg)
let avgErr = shots > 0 ? (errSum / float(shots)) : 0.0
let jams = wto_world_active_jams(world, now)
let nm1 = pathfinder_is_loaded_ex(1)
print("WTO_AI|STAT|t={now}|bots={active}|roles={roles[0]}/{roles[1]}/{roles[2]}/{roles[3]}/{roles[4]}|crowd={crowd.crowdedBotCount}|maxClust={crowd.maxClusterSize}|minAllyD={crowd.minPairDistM}|dispNow={dispNow}|dispEv={crowd.disperseEvents}|ridgeNow={ridgeNow}|ridgeRevEv={ridgeWithdraws}|eng={engNow}|revNow={revNow}|revEv={revEvents}|jams={jams}|detours={detours}|shots={shots}|avgAimErr={avgErr}|maxAimErr={maxErr}|routeB={routeB}|caps={world.capCount}|nm1={nm1}\n")
wto_log_bot_and_cap_samples(world, bots)
+234
View File
@@ -0,0 +1,234 @@
// Chassis drive actuator: translates `WtoDriveCmd` into closed-loop `VehiclePhysActor` axes
// (throttle, steering, brakes, auto-transmission) with space-aware 3-point turns, smooth
// long-distance reverse control, and dead-echo watchdog return to stock movement.
options indenting = 2
options no_global_heap = true
module wto_ai_drive_common shared
require ecs
require math
require DagorMath
require DagorDataBlock
require DagorSystem
require Mission
require Unit
require IGroundModel
require vehicle
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
[never_inline]
def public wto_drive_announce_script_ready()
let own = (WTO_AI_ENABLED && WTO_AI_LAYER_NAVIGATION && WTO_AI_NAV_DRIVE_MODE == "vehicle_phys") ? "1" : "0"
using() <| $(var blk : DataBlock)
add(blk, "ownMovement", own)
call_mission_action("wtoGroundAiScriptReady", blk)
[never_inline]
def public wto_drive_request_control(eid : EntityId; holdMs : int)
using() <| $(var blk : DataBlock)
add(blk, "eid", "{uint(eid)}")
add(blk, "holdMs", "{holdMs}")
call_mission_action("wtoGroundAiDriveControl", blk)
[never_inline]
def public wto_drive_release_all()
using() <| $(var blk : DataBlock)
add(blk, "eid", "0")
add(blk, "holdMs", "0")
call_mission_action("wtoGroundAiDriveControl", blk)
[never_inline]
def private wto_set_phys_axes(var actor : VehiclePhysActor&; thr, str, brk, handBrk : float)
actor.phys.producedCT |> ground_control_state_setAutomaticTransmission(true)
actor.phys.producedCT |> ground_control_state_setCruiseControl(int8(0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_THROTTLE, clamp(thr, -1.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_STEERING, clamp(str, -1.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_BRAKE_LEFT, clamp(brk, 0.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_BRAKE_RIGHT, clamp(brk, 0.0, 1.0))
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_CLUTCH, 0.0)
actor.phys.producedCT |> ground_control_state_setAxisValue(EGroundControlAxis.GCA_HAND_BRAKE, clamp(handBrk, 0.0, 1.0))
[never_inline]
def private wto_check_echo_watchdog(unitMissionName : string; var actor : VehiclePhysActor&;
dt : float; var slot : WtoBotSlot&) : bool
assume st = slot.drive
let appThr = ground_control_state_getAxisValue(actor.phys.appliedCT, EGroundControlAxis.GCA_THROTTLE)
let appStr = ground_control_state_getAxisValue(actor.phys.appliedCT, EGroundControlAxis.GCA_STEERING)
let wantsThrottle = abs(st.prevThr) >= 0.35
let wantsSteering = abs(st.prevStr) >= 0.45
let throttleEchoed = !wantsThrottle || abs(appThr) >= 0.05
let steeringEchoed = !wantsSteering || abs(appStr) >= 0.05
if !throttleEchoed || !steeringEchoed
st.deadEchoSec += clamp(dt, 0.0, 0.15)
if st.deadEchoSec >= WTO_AI_NAV_DEAD_ECHO_SEC
if !st.failLogged
print("WTO_AI|PHYS_STALL|actor={unitMissionName}|eid={uint(slot.eid)}\n")
return false
else
st.deadEchoSec = 0.0
return true
[never_inline]
def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
fwd, left : float3; vFwd, omega : float;
var outThr, outStr, outBrk : float&)
let wish = wto_xz_normalize(cmd.desiredDir, fwd)
let errRad = atan2(dot(wish, left), dot(wish, fwd))
let turnSign = errRad >= 0.0 ? 1.0 : -1.0
if abs(vFwd) > 3.6
outThr = vFwd > 0.0 ? -0.9 : 0.9
outBrk = 1.0
outStr = turnSign * WTO_AI_NAV_STEER_SIGN
return
let openFront = cmd.frontClearM >= spec.halfLen + 3.5
if openFront
// Two-beat turn micro: launch straight to 2nd gear before applying full steering.
outThr = 1.0
outStr = abs(vFwd) < WTO_AI_SM_TURN_LAUNCH_MPS ? 0.0 : (turnSign * WTO_AI_NAV_STEER_SIGN)
return
if spec.canPivot && cmd.frontClearM >= spec.halfLen + 1.2 && cmd.rearClearM >= spec.halfLen + 1.0
outThr = 0.0
outStr = clamp(turnSign - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
return
// Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall.
outThr = vFwd > -WTO_AI_SM_TURN_LAUNCH_MPS ? -1.0 : -0.6
outStr = (abs(vFwd) < 1.2 ? 0.0 : -turnSign) * WTO_AI_NAV_STEER_SIGN
[never_inline]
def private wto_compute_reverse_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
fwd, left : float3; vFwd, omega : float;
var outThr, outStr, outBrk, outHand : float&)
if cmd.rearClearM < 2.1
outThr = 0.0
outBrk = 1.0
outHand = 1.0
return
if vFwd > 0.30
outThr = -1.0
outBrk = 1.0
return
let rear = -fwd
let wishRear = wto_xz_normalize(cmd.desiredDir, rear)
// Coordinate-free signed rear angle: >0 means desired rear travel lies toward hull LEFT (+Z).
let rearErr = atan2(dot(wishRear, left), dot(wishRear, rear))
outStr = clamp(rearErr * 1.45 + omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
let maxSafeRev = min(spec.vMaxRev, sqrt(max(1.0, (cmd.rearClearM - 1.8) * 2.2)))
let vTarget = -clamp(cmd.speedMps, 1.2, max(1.4, maxSafeRev))
let vErr = vTarget - vFwd
outThr = vErr < -0.15 ? clamp(-0.52 + vErr * 0.32, -1.0, -0.35) : -0.28
[never_inline]
def private wto_compute_cruise_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
fwd, left : float3; vFwd, omega : float;
var outThr, outStr, outBrk : float&)
let wish = wto_xz_normalize(cmd.desiredDir, fwd)
let yawErr = atan2(dot(wish, left), dot(wish, fwd))
outStr = clamp(yawErr * 1.38 - omega * 0.28, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
let absErr = abs(yawErr)
var vLimit = min(cmd.speedMps, spec.vMaxFwd)
if absErr > 0.22
let radiusEst = max(4.0, 14.0 / max(0.25, absErr))
vLimit = min(vLimit, sqrt(WTO_AI_NAV_CORNER_BRAKE_ACCEL * radiusEst))
if cmd.frontClearM < 12.0
vLimit = min(vLimit, max(2.2, (cmd.frontClearM - 2.0) * 0.75))
let vErr = vLimit - vFwd
if vErr < -1.5
outThr = 0.0
outBrk = clamp((-vErr - 1.2) * 0.35, 0.2, 1.0)
elif vErr >= 0.6
outThr = 1.0
else
outThr = clamp(0.45 + vErr * 0.45, 0.15, 1.0)
[never_inline]
def private wto_drive_is_immobilized(actor : VehiclePhysActor const&) : bool
assume dmg = actor.phys.currentState.damageState
return (!dmg.allowMoveControl || dmg.engineReadyness <= 0.0 ||
dmg.driverReadyness <= 0.0 || (dmg.trackLBroken && dmg.trackRBroken))
[never_inline]
def private wto_drive_halt_on_failure(var actor : VehiclePhysActor&;
var slot : WtoBotSlot&; reason : string)
assume st = slot.drive
if !st.failLogged
st.failLogged = true
print("WTO_AI|DRIVE_FAIL|eid={uint(slot.eid)}|reason={reason}\n")
st.prevThr = 0.0
st.prevStr = 0.0
st.deadEchoSec = 0.0
wto_set_phys_axes(actor, 0.0, 0.0, 1.0, 1.0)
[never_inline]
def private wto_ensure_phys_owner(gm : IGroundModel const?; var actor : VehiclePhysActor&;
var slot : WtoBotSlot&) : bool
assume st = slot.drive
if gm == null || gm.moveSys == null
return false
if !st.routeBOwned || !gm.moveSys.inactive
wto_drive_request_control(slot.eid, 1000)
if !gm.moveSys.inactive
return false
if !st.routeBOwned
slot.spec.isTracked = actor.phys.trackWidth > 0.01
slot.spec.canPivot = slot.spec.isTracked && actor.phys.haveSeparateBrakes
st.routeBOwned = true
return st.routeBOwned
[never_inline]
def public wto_drive_step_phys(var unit : Unit?; unitMissionName : string;
gm : IGroundModel const?; var actor : VehiclePhysActor&;
dt, now : float; var slot : WtoBotSlot&)
if unit == null || actor.physEdit == null
return
if !wto_ensure_phys_owner(gm, actor, slot)
return
if !slot.driveCmd.valid || (!slot.order.valid && !WTO_AI_LAYER_TACTICS)
wto_drive_halt_on_failure(actor, slot, "invalid_drive_cmd")
return
if now > slot.nextNavAt + WTO_AI_NAV_TICK_SEC * 2.0
wto_drive_halt_on_failure(actor, slot, "stale_nav_tick")
return
let immobile = wto_drive_is_immobilized(actor)
slot.tactics.immobilized = immobile
if immobile
slot.drive.prevThr = 0.0
slot.drive.prevStr = 0.0
slot.drive.deadEchoSec = 0.0
wto_set_phys_axes(actor, 0.0, 0.0, 1.0, 1.0)
return
if !wto_check_echo_watchdog(unitMissionName, actor, dt, slot)
wto_drive_halt_on_failure(actor, slot, "dead_echo")
return
slot.drive.failLogged = false
vehicle_actor_set_allow_move_control(actor, true)
assume st = slot.drive
assume cmd = slot.driveCmd
let fwd = wto_xz_normalize(unit.unitTm[0], float3(1.0, 0.0, 0.0))
let left = float3(-fwd.z, 0.0, fwd.x)
let curYaw = atan2(fwd.z, fwd.x)
let vFwd = dot(vehicle_phys_getCurrentStateVelocity(actor.phys), fwd)
st.lastVFwd = vFwd
let age = now - st.prevYawAt
st.omegaYawRad = (age > 1.0e-4 && age <= 0.25) ? lerp(clamp(wto_wrap_rad(curYaw - st.prevYaw) / age, -3.0, 3.0), st.omegaYawRad, 0.6) : 0.0
st.prevYaw = curYaw
st.prevYawAt = now
var thr = 0.0
var str = 0.0
var brk = 0.0
var hand = 0.0
if !cmd.valid || cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05
thr = abs(vFwd) > 0.35 ? (vFwd > 0.0 ? -1.0 : 1.0) : 0.0
brk = 1.0
hand = abs(vFwd) > 0.35 ? 0.0 : 1.0
elif cmd.mode == WTO_DRIVE_PIVOT
wto_compute_pivot_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk)
elif cmd.mode == WTO_DRIVE_REVERSE
wto_compute_reverse_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk, hand)
else
wto_compute_cruise_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk)
st.prevThr = thr
st.prevStr = str
wto_set_phys_axes(actor, thr, str, brk, hand)
+134
View File
@@ -0,0 +1,134 @@
// Own-sight target velocity estimator, bounded 2-5 s last-seen exit watch, and
// once-per-opportunity bounded aiming bias (never reads true target velocity).
options indenting = 2
options no_global_heap = true
module wto_ai_estimate_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
[never_inline]
def private wto_est_hash(seed : uint) : uint
var x = seed ^ 0x9e3779b9u
x = (x ^ (x >> 16u)) * 0x85ebca6bu
x = (x ^ (x >> 13u)) * 0xc2b2ae35u
return x ^ (x >> 16u)
[never_inline]
def private wto_est_rand01(seed : uint) : float
return float(wto_est_hash(seed) & 0xffffu) / 65535.0
[never_inline]
def public wto_est_reset_samples(var p : WtoPerceiveState&)
p.sampleCount = 0
p.sampleHead = 0
p.estVel = float3(0.0, 0.0, 0.0)
p.velQuality = 0.0
p.oppSeeded = false
[never_inline]
def public wto_est_push_visual_sample(now : float; tgtEid : EntityId; tgtPos : float3;
var p : WtoPerceiveState&)
if p.sampleTargetEid != tgtEid
p.sampleTargetEid = tgtEid
wto_est_reset_samples(p)
if p.sampleCount > 0
let lastIdx = (p.sampleHead + WTO_MAX_VEL_SAMPLES - 1) % WTO_MAX_VEL_SAMPLES
if (now - p.sampleAt[lastIdx]) < 0.05
return
let dst = p.sampleHead
p.samplePos[dst] = tgtPos
p.sampleAt[dst] = now
p.sampleHead = (dst + 1) % WTO_MAX_VEL_SAMPLES
p.sampleCount = min(p.sampleCount + 1, WTO_MAX_VEL_SAMPLES)
// Find oldest still-fresh sample (<= 1.8 s old) to compute smoothed observed velocity.
var oldIdx = dst
var oldestAt = now
for k in range(p.sampleCount)
let idx = (dst + WTO_MAX_VEL_SAMPLES - k) % WTO_MAX_VEL_SAMPLES
let t = p.sampleAt[idx]
if (now - t) <= 1.8 && t < oldestAt
oldestAt = t
oldIdx = idx
let span = now - oldestAt
if span < WTO_AI_EST_MIN_SPAN_SEC
p.estVel = float3(0.0, 0.0, 0.0)
p.velQuality = 0.0
return
var vRaw = (tgtPos - p.samplePos[oldIdx]) / span
let rawSpd = length(vRaw)
if rawSpd > 34.0
vRaw = vRaw * (34.0 / rawSpd)
let vDiff = length(vRaw - p.estVel)
if p.velQuality > 0.25 && vDiff > WTO_AI_EST_JUMP_RESET_MPS
p.oppSeeded = false
p.estVel = lerp(p.estVel, vRaw, 0.58)
p.velQuality *= 0.35
return
p.estVel = p.velQuality <= 0.01 ? vRaw : lerp(p.estVel, vRaw, 0.38)
let spanQ = clamp((span - WTO_AI_EST_MIN_SPAN_SEC) / max(0.1, WTO_AI_EST_STABLE_SPAN_SEC - WTO_AI_EST_MIN_SPAN_SEC), 0.0, 1.0)
let steadyQ = clamp(1.0 - vDiff * 0.07, 0.35, 1.0)
p.velQuality = spanQ * steadyQ
[never_inline]
def public wto_est_on_los_lost(now : float; selfEid : EntityId; var p : WtoPerceiveState&)
wto_est_reset_samples(p)
if !p.wasEngaging
return
p.wasEngaging = false
if !p.targetEid || p.targetIsAir
return
p.watchPos = length_sq(p.visibleAimPt) > 1.0 ? p.visibleAimPt : (p.knownPos + float3(0.0, 1.4, 0.0))
let seed = uint(selfEid) ^ (uint(p.targetEid) * 2654435761u) ^ uint(max(0.0, now * 100.0))
let frac = wto_est_rand01(seed)
let dur = lerp(WTO_AI_EST_WATCH_MIN_SEC, WTO_AI_EST_WATCH_MAX_SEC, frac)
p.watchUntil = now + dur
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|WATCH|eid={uint(selfEid)}|tgt={uint(p.targetEid)}|dur={dur}\n")
[never_inline]
def public wto_est_compute_biased_lead(muzzlePos, myVel, aimBase : float3;
var slot : WtoBotSlot&;
var outLeadPt : float3&) : float
assume p = slot.perceive
let rawDelta = aimBase - muzzlePos
let rawDist = length(rawDelta)
let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss))
// Lead uses ONLY our own visual velocity estimate, scaled by observation quality.
let leadScale = p.sampleCount >= 2 ? clamp(0.35 + 0.65 * p.velQuality, 0.0, 1.0) : 0.0
let usedVel = p.estVel * leadScale
var leadPt = aimBase
var tof = 0.0
for _iter in range(2)
tof = clamp(length(leadPt - muzzlePos) / vEff, 0.0, 3.5)
leadPt = aimBase + usedVel * tof - myVel * (tof * 0.85)
// Sample bounded natural bias ONCE per shooting opportunity (target + shot + state + 12m grid).
let gx = uint(int(muzzlePos.x / 12.0) + 4096)
let gz = uint(int(muzzlePos.z / 12.0) + 4096)
let key = (uint(p.targetEid) ^ (uint(slot.fire.shotCount) * 2654435761u) ^
(uint(slot.tactics.state) * 40503u) ^ (gx * 73856093u) ^ (gz * 19349663u))
if !p.oppSeeded || p.oppKey != key
p.oppKey = key
p.oppSeeded = true
let sBase = key ^ (uint(slot.eid) * 2246822519u)
p.oppBiasU = (wto_est_rand01(sBase) + wto_est_rand01(sBase ^ 0x517cc1b7u)) - 1.0
p.oppBiasV = (wto_est_rand01(sBase ^ 0x9e3779b9u) + wto_est_rand01(sBase ^ 0x85ebca6bu)) - 1.0
// Error envelope shrinks naturally as observation quality converges.
let tgtSpd = length(p.estVel)
let leadSpread = tgtSpd * tof * WTO_AI_EST_LEAD_ERR_FRAC * (1.0 - 0.72 * p.velQuality)
let distSpread = WTO_AI_EST_BASE_SIGMA_M * clamp(rawDist / 350.0, 0.25, 2.6) * (1.2 - 0.55 * p.velQuality)
let latOff = clamp((leadSpread + distSpread) * p.oppBiasU, -WTO_AI_EST_MAX_BIAS_M, WTO_AI_EST_MAX_BIAS_M)
let vertOff = clamp(distSpread * 0.65 * p.oppBiasV, -WTO_AI_EST_MAX_BIAS_M * 0.5, WTO_AI_EST_MAX_BIAS_M * 0.5)
let toAimXZ = wto_xz_normalize(rawDelta, float3(1.0, 0.0, 0.0))
let latAxis = float3(-toAimXZ.z, 0.0, toAimXZ.x)
outLeadPt = leadPt + latAxis * latOff + float3(0.0, vertOff, 0.0)
return rawDist
+296
View File
@@ -0,0 +1,296 @@
// Turret servo, active loaded-shell inspection, and ballistic aim solver.
// All ground weapon firing goes exclusively through wto_fire_gate_try_shoot.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_common shared
require ecs
require app
require math
require strings
require DagorMath
require Mission
require Unit
require IGroundModel
require Weapon
require Ballistics
require %game.utils.utils_common
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_estimate_common
require %appGame.wtoai.wto_ai_fire_gate_common
[never_inline]
def private wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3;
var outYawDeg, outPitchDeg : float&)
let len = length(worldDir)
if len < 1.0e-5
outYawDeg = 0.0
outPitchDeg = 0.0
return
let d = worldDir / len
let f = dot(d, hullFwd)
let u = dot(d, hullUp)
let l = dot(d, hullLeft)
let horiz = sqrt(f * f + l * l)
outYawDeg = horiz > 1.0e-5 ? (-atan2(l, f) * WTO_RAD_TO_DEG) : 0.0
outPitchDeg = clamp(atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG, -24.0, 65.0)
[never_inline]
def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3
let yr = yawDeg * WTO_DEG_TO_RAD
let pr = pitchDeg * WTO_DEG_TO_RAD
let cp = cos(pr)
let dir = hullFwd * (cp * cos(yr)) - hullLeft * (cp * sin(yr)) + hullUp * sin(pr)
let l = length(dir)
return l > 1.0e-5 ? (dir / l) : hullFwd
[never_inline]
def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&)
if gun == null
return
let chosenIdx = int(gun.chosenBulletType)
if fc.loadedBulletIdx == chosenIdx && fc.activeSpeedMps > 80.0
return
fc.loadedBulletIdx = chosenIdx
fc.activeSpeedMps = spec.muzzleSpeedMps
fc.activeDragCx = spec.shellDragCx
fc.activeMassKg = spec.shellMassKg
fc.activeCaliberM = spec.shellCaliberM
if chosenIdx >= 0 && chosenIdx < length(gun.properties.bulletSets)
assume bs = gun.properties.bulletSets[chosenIdx]
if length(bs.bullet) > 0 && bs.bullet[0] != null
let bName = bs.bullet[0].getName
if !empty(bName)
let h = ecs_hash(bName)
for i in range(spec.shellCount)
if spec.shells[i].nameHash == h
fc.activeSpeedMps = spec.shells[i].speedMps
fc.activeDragCx = spec.shells[i].dragCx
fc.activeMassKg = spec.shells[i].massKg
fc.activeCaliberM = spec.shells[i].caliberM
return
[never_inline]
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
fc.gunDamaged = false
if unit == null || unit.weap == null
return
var anyGun = false
var anyAlive = false
var anyReserve = false
var totalLoaded = 0
foreach_primary_gun(unit.weap.Weapons) <| $(var weapon)
if weapon == null || weapon.isDummyGun
return
var gun = as_gun(weapon)
if gun == null
if weapon.prop.launcher && weapon.countBullets > 0
anyGun = true
anyAlive = true
anyReserve = true
if fc.turretNo < 0
fc.turretNo = weapon.turretNo
fc.gunReady = true
totalLoaded += weapon.countBullets
return
anyGun = true
if gun.isInoperable
return
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
totalLoaded += max(0, gun.currentLoadedAmmoCount)
if gun.currentLoadedAmmoCount > 0 || gun.currentBulletSet.bulletsCount > 0 || weapon.countBullets > 0
anyReserve = true
fc.gunDamaged = anyGun && !anyAlive
fc.reloading = anyAlive && !fc.gunReady && anyReserve
if fc.pendingShotConfirm
if (fc.prevLoadedAmmo >= 0 && totalLoaded < fc.prevLoadedAmmo) || !fc.gunReady
fc.shotCount++
fc.pendingShotConfirm = false
elif (now - fc.pendingShotAt) > 0.35
fc.pendingShotConfirm = false
fc.prevLoadedAmmo = totalLoaded
[never_inline]
def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&;
aimBase : float3; var outAimPt, outWishDir : float3&) : float
var leadPt = aimBase
let rawDist = wto_est_compute_biased_lead(muzzlePos, myVel, aimBase, slot, leadPt)
let dragLoss = clamp(slot.fire.activeDragCx * 0.00011 * rawDist, 0.0, 0.28)
let vEff = max(120.0, slot.fire.activeSpeedMps * (1.0 - dragLoss))
outAimPt = leadPt
var arcDir = float3(0.0, 0.0, 0.0)
if calculate_arc_low_start_dir(muzzlePos, leadPt, vEff, arcDir) && length_sq(arcDir) > 0.25
outWishDir = normalize(arcDir)
else
let d = max(1.0, length(leadPt - muzzlePos))
let tof = d / vEff
let dropComp = float3(0.0, 0.5 * 9.81 * tof * tof, 0.0)
outWishDir = normalize(leadPt + dropComp - muzzlePos)
return rawDist
[never_inline]
def private wto_sample_turret_muzzle(unit : Unit const?; turretNo : int;
var outPos, outDir : float3&) : bool
if unit == null || unit.weap == null
return false
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if (turretNo >= 0 && tIdx != turretNo) || (turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
continue
let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex))
if weapon == null
continue
var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) > 0.25
outPos = gunTm[3]
outDir = normalize(gunTm[0])
return true
return false
[never_inline]
def private wto_drive_turret_and_sample_barrel(var unit : Unit?; dt, now : float;
wishYawDeg, wishPitchDeg : float;
var slot : WtoBotSlot&;
var outMuzzlePos, outLiveDir : float3&)
assume fc = slot.fire
let dtStep = clamp(dt, 0.005, 0.12)
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if (fc.turretNo >= 0 && tIdx != fc.turretNo) || (fc.turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
continue
fc.curYawDeg = turret.currentState.yaw
fc.curPitchDeg = turret.currentState.pitch
if !fc.servoInit
fc.cmdYawDeg = fc.curYawDeg
fc.cmdPitchDeg = fc.curPitchDeg
fc.prevPitchDeg = fc.curPitchDeg
fc.servoInit = true
let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep
fc.prevPitchDeg = fc.curPitchDeg
if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8
fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep)
fc.pitchBlocked = fc.pitchClampSec >= 0.75
else
fc.pitchClampSec = max(0.0, fc.pitchClampSec - dtStep * 2.5)
if fc.pitchClampSec <= 0.05
fc.pitchBlocked = false
let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep
let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep
let yawDelta = clamp(wto_wrap_deg(wishYawDeg - fc.curYawDeg), -maxYawStep, maxYawStep)
let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep)
fc.cmdYawDeg = wto_wrap_deg(fc.curYawDeg + yawDelta)
fc.cmdPitchDeg = clamp(fc.curPitchDeg + pitchDelta, slot.spec.minPitchDeg - 2.0, slot.spec.maxPitchDeg + 2.0)
turret.yawLim = fc.cmdYawDeg
turret.pitchLim = fc.cmdPitchDeg
break
var uPos = unit.pos
updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos)
if !wto_sample_turret_muzzle(unit, fc.turretNo, outMuzzlePos, outLiveDir)
outLiveDir = wto_hull_deg_to_world(fc.curYawDeg, fc.curPitchDeg, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2])
let bAge = now - fc.prevBarrelAt
if bAge > 1.0e-4 && bAge <= 0.25
let stepDeg = acos(clamp(dot(outLiveDir, fc.prevBarrelDir), -1.0, 1.0)) * WTO_RAD_TO_DEG
fc.barrelOmegaDegSec = lerp(stepDeg / bAge, fc.barrelOmegaDegSec, 0.45)
else
fc.barrelOmegaDegSec = 0.0
fc.prevBarrelDir = outLiveDir
fc.prevBarrelAt = now
[never_inline]
def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?;
now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&)
if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null
return
// SPAA vs aircraft only delegates to stock air-target fire control (never ground targets).
if slot.tactics.spaaYieldAir
var gm = as_gm(unit)
if gm != null
*gm |> set_check_visibility_target(true)
*gm |> set_ignore_stop_for_fire(true)
set_unit_attack_type(unit, "attack_target")
return
set_unit_attack_type(unit, "dont_aim")
var wantSoftShell = false
if slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir
let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid)
if tgtIdx >= 0
wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35
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)
let hFwd = unit.unitTm[0]
var wishWorldDir = hFwd
var aimPt = muzzlePos + hFwd * 50.0
var distToTgt = 9999.0
let engageValid = (slot.perceive.hasClearLos && !!slot.perceive.targetEid && !slot.perceive.targetIsAir &&
!(slot.spec.role == WTO_ROLE_SPAA && slot.tactics.state == WTO_STATE_DISABLED))
if engageValid
let baseAim = slot.perceive.visibleAimPt
distToTgt = wto_solve_ballistic_aim(muzzlePos, unit.vel, slot, baseAim, aimPt, wishWorldDir)
elif now < slot.perceive.watchUntil
wishWorldDir = normalize(slot.perceive.watchPos - muzzlePos)
elif !!slot.perceive.targetEid && (now - slot.perceive.lastSeenAt) <= WTO_AI_TACTICS_MEMORY_TTL_SEC
wishWorldDir = normalize((slot.perceive.knownPos + float3(0.0, 1.4, 0.0)) - muzzlePos)
elif now < slot.perceive.alertUntil
wishWorldDir = float3(cos(slot.perceive.alertYawRad), 0.0, sin(slot.perceive.alertYawRad))
var wishYaw = 0.0
var wishPitch = 0.0
wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch)
wto_drive_turret_and_sample_barrel(unit, dt, now, wishYaw, wishPitch, slot, muzzlePos, liveBarrelDir)
if !engageValid || distToTgt > WTO_AI_FC_MAX_RANGE_M
slot.fire.settleHoldSec = 0.0
slot.fire.lastAligned = false
return
let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos))
wto_fire_gate_try_shoot(world, unit, now, dt, distXZ, muzzlePos, aimPt, liveBarrelDir, wishWorldDir, slot, fireBudget)
+199
View File
@@ -0,0 +1,199 @@
// Single fire-permission gate for every ground weapon (main cannon, launcher, SPAA self-defense).
// Every shot must pass visual confirmation, weapon readiness, distance-tier speed limits,
// 800 m continuous LOS window, aim settle, frame pre-fire budget, muzzle hard-ray, drag-integrated
// ballistic trajectory sweep, predicted friendly corridor, and multi-barrel group validation.
options indenting = 2
options no_global_heap = true
module wto_ai_fire_gate_common shared
require ecs
require math
require DagorMath
require Mission
require Unit
require Weapon
require %game.utils.utils_common
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_sight_common
[never_inline]
def private wto_gate_friendly_segment_clear(world : WtoWorldSnap const&; selfEid : EntityId;
army : int; p0, p1 : float3; tMid : float) : bool
let delta = p1 - p0
let segLen = length(delta)
if segLen < 0.2
return true
let dir = delta / segLen
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army != army || u.eid == selfEid
continue
let predPos = u.pos + u.vel * tMid + float3(0.0, 1.3, 0.0)
let along = clamp(dot(predPos - p0, dir), 0.0, segLen)
let clearR = WTO_AI_FC_FRIENDLY_CORRIDOR_M + u.halfWid
if length_sq(predPos - (p0 + dir * along)) < clearR * clearR
return false
return true
[never_inline]
def private wto_gate_check_ballistic_arc(world : WtoWorldSnap const&;
selfEid, targetEid : EntityId; army : int;
muzzlePos, liveDir, carrierVel, aimPt : float3;
speedMps, dragCx, massKg, caliberM : float;
var outBlock : int&) : int
let toAim = aimPt - muzzlePos
let targetDist = length(toAim)
if targetDist < 1.5
return WTO_DENY_OK
let toAimDir = toAim / targetDist
let area = 0.25 * WTO_PI * caliberM * caliberM
let dragK = 0.5 * 1.225 * dragCx * area / max(0.1, massKg)
var cur = muzzlePos
var vel = liveDir * max(80.0, speedMps) + carrierVel
var t = 0.0
var traveled = 0.0
for step in range(64)
let spd = length(vel)
if spd < 20.0
return WTO_DENY_AIM_ERR
let remain = max(0.5, targetDist - traveled)
let segWant = min(WTO_AI_FC_BALLISTIC_STEP_M, remain)
let dt = clamp(segWant / spd, 0.004, 0.14)
let accel = float3(0.0, -9.81, 0.0) - vel * (dragK * spd)
var next = cur + vel * dt + accel * (0.5 * dt * dt)
let nextProj = dot(next - muzzlePos, toAimDir)
let isLast = nextProj >= targetDist - 0.5
if isLast && nextProj > targetDist && length_sq(next - cur) > 0.01
let curProj = dot(cur - muzzlePos, toAimDir)
let frac = clamp((targetDist - curProj) / max(0.01, nextProj - curProj), 0.0, 1.0)
next = lerp(cur, next, frac)
let trimS = step == 0 ? 0.35 : 0.0
let trimE = isLast ? 0.65 : 0.0
let blk = wto_sight_hard_segment_blocked(world, selfEid, targetEid, cur, next, WTO_AI_FC_BALLISTIC_SWEEP_R_M, trimS, trimE)
if blk != WTO_BLOCK_NONE
outBlock = blk
return WTO_DENY_ARC_HARD
if !wto_gate_friendly_segment_clear(world, selfEid, army, cur, next, t + dt * 0.5)
return WTO_DENY_FRIENDLY
traveled += length(next - cur)
cur = next
vel = vel + accel * dt
t += dt
if isLast
let missTol = max(3.2, targetDist * 0.012)
if length_sq(cur - aimPt) > missTol * missTol
return WTO_DENY_AIM_ERR
return WTO_DENY_OK
return WTO_DENY_AIM_ERR
[never_inline]
def private wto_gate_check_barrel(world : WtoWorldSnap const&; unit : Unit const?;
slot : WtoBotSlot const&; muzzlePos, liveDir, aimPt : float3;
var outBlock : int&) : int
let straightBlk = wto_sight_hard_segment_blocked(world, slot.eid, slot.perceive.targetEid, muzzlePos, aimPt, 0.05, 0.35, 0.65)
if straightBlk != WTO_BLOCK_NONE
outBlock = straightBlk
return WTO_DENY_MUZZLE_HARD
return wto_gate_check_ballistic_arc(world, slot.eid, slot.perceive.targetEid, slot.army,
muzzlePos, liveDir, unit.vel, aimPt,
slot.fire.activeSpeedMps, slot.fire.activeDragCx, slot.fire.activeMassKg, slot.fire.activeCaliberM, outBlock)
[never_inline]
def private wto_gate_check_all_primary_guns(world : WtoWorldSnap const&; unit : Unit const?;
slot : WtoBotSlot const&; primaryMuzzle, primaryDir, aimPt : float3;
var outBlock : int&) : int
let primaryRes = wto_gate_check_barrel(world, unit, slot, primaryMuzzle, primaryDir, aimPt, outBlock)
if primaryRes != WTO_DENY_OK
return primaryRes
if unit == null || unit.weap == null
return WTO_DENY_OK
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if tIdx == slot.fire.turretNo || int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)
continue
let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex))
if weapon == null || weapon.isDummyGun
continue
var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) <= 0.25
continue
let secRes = wto_gate_check_barrel(world, unit, slot, gunTm[3], normalize(gunTm[0]), aimPt, outBlock)
if secRes != WTO_DENY_OK
return secRes == WTO_DENY_FRIENDLY ? WTO_DENY_FRIENDLY : WTO_DENY_MULTI_GUN
return WTO_DENY_OK
[never_inline]
def private wto_gate_speed_allowed(distXZ, measuredSpeed : float; spec : WtoVehicleSpec const&) : bool
if distXZ > WTO_AI_FC_MID_RANGE_M
return measuredSpeed <= WTO_AI_FC_STOP_SPEED_MAX_MPS
if distXZ > WTO_AI_FC_CLOSE_RANGE_M
let slowCap = min(spec.vMaxFwd * WTO_AI_FC_MID_SLOW_RATIO, WTO_AI_FC_MID_SLOW_MAX_MPS)
return measuredSpeed <= slowCap
return true
[never_inline]
def private wto_gate_log_deny(now, distXZ, measuredSpeed : float; reason, blk : int; var slot : WtoBotSlot&)
assume fc = slot.fire
let changed = fc.lastDenyReason != reason || fc.lastDenyBlock != blk
fc.lastDenyReason = reason
fc.lastDenyBlock = blk
if WTO_AI_DIAG_TELEMETRY && reason >= WTO_DENY_SPEED && (changed || (now - fc.lastDenyLogAt) >= 4.0)
fc.lastDenyLogAt = now
print("WTO_AI|DENY|eid={uint(slot.eid)}|reason={reason}|block={blk}|dist={distXZ}|spd={measuredSpeed}\n")
[never_inline]
def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?;
now, dt, distXZ : float; muzzlePos, aimPt, liveDir, wishDir : float3;
var slot : WtoBotSlot&; var fireBudget : int&)
assume fc = slot.fire
let aimErrDeg = acos(clamp(dot(liveDir, wishDir), -1.0, 1.0)) * WTO_RAD_TO_DEG
fc.lastAimErrDeg = aimErrDeg
let measuredSpeed = length(unit.vel)
let speedOk = wto_gate_speed_allowed(distXZ, measuredSpeed, slot.spec)
let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distXZ, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4)
let settled = aimErrDeg <= allowErrDeg && fc.barrelOmegaDegSec <= WTO_AI_FC_BARREL_SETTLE_DEG_SEC && speedOk
fc.lastAligned = settled
fc.settleHoldSec = settled ? (fc.settleHoldSec + clamp(dt, 0.005, 0.10)) : max(0.0, fc.settleHoldSec - dt * 2.0)
let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65
if !fc.gunReady || (now - fc.lastShotAt) < minCadence
wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_NOT_READY, WTO_BLOCK_NONE, slot)
return
if !speedOk
wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_SPEED, WTO_BLOCK_NONE, slot)
return
if distXZ > WTO_AI_FC_LONG_RANGE_M && (slot.perceive.goodLosSec < WTO_AI_FC_LONG_WINDOW_SEC || slot.perceive.visiblePointCount < 2)
wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_LONG_WINDOW, WTO_BLOCK_NONE, slot)
return
if aimErrDeg > allowErrDeg
wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_AIM_ERR, WTO_BLOCK_NONE, slot)
return
let reqHold = distXZ <= WTO_AI_FC_CLOSE_RANGE_M ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC
if fc.settleHoldSec < reqHold
wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_SETTLE, WTO_BLOCK_NONE, slot)
return
if fireBudget <= 0
wto_gate_log_deny(now, distXZ, measuredSpeed, WTO_DENY_BUDGET, WTO_BLOCK_NONE, slot)
return
fireBudget--
var blk = WTO_BLOCK_NONE
let gateRes = wto_gate_check_all_primary_guns(world, unit, slot, muzzlePos, liveDir, aimPt, blk)
if gateRes != WTO_DENY_OK
wto_gate_log_deny(now, distXZ, measuredSpeed, gateRes, blk, slot)
return
unit_single_shot(unit, int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
fc.lastShotAt = now
fc.pendingShotConfirm = true
fc.pendingShotAt = now
fc.lastDenyReason = WTO_DENY_OK
fc.lastDenyBlock = WTO_BLOCK_NONE
fc.shotErrSumDeg += aimErrDeg
fc.maxShotErrDeg = max(fc.maxShotErrDeg, aimErrDeg)
if !slot.spec.isAutocannonBelt
fc.settleHoldSec = 0.0
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|SHOT|eid={uint(slot.eid)}|tgt={uint(slot.perceive.targetEid)}|dist={distXZ}|spd={measuredSpeed}|v0={fc.activeSpeedMps}|err={aimErrDeg}\n")
+234
View File
@@ -0,0 +1,234 @@
// Team-level navmesh flank lanes (center / left / right), 40% rally staging & launch state,
// cap recall timers, and enemy air threat tracking.
options indenting = 2
options no_global_heap = true
module wto_ai_lanes_common shared
require ecs
require math
require pathfinder
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
let public WTO_LANE_CENTER = 0
let public WTO_LANE_LEFT = 1
let public WTO_LANE_RIGHT = 2
[safe_when_uninitialized]
struct public WtoTeamLanes
built : bool[16]
centerLen : float[16]
centerMid : float3[16]
flankValid : bool[32]
flankRelay : float3[32]
rallyPos : float3[48]
rallyStartAt : float[48]
rallyReleased : bool[48]
capSafeSince : float[16]
recallActive : bool[16]
enemyAirActive : bool[3]
enemyAirSeenAt : float[3]
[never_inline]
def public wto_lanes_cap_key(army, capIdx : int) : int
return clamp(army - 1, 0, 1) * 8 + clamp(capIdx, 0, 7)
[never_inline]
def public wto_lanes_sub_key(army, capIdx, laneId : int) : int
return wto_lanes_cap_key(army, capIdx) * 3 + clamp(laneId, 0, 2)
[never_inline]
def public wto_lanes_reset(var lanes : WtoTeamLanes&)
for i in range(16)
lanes.built[i] = false
lanes.centerLen[i] = 0.0
lanes.centerMid[i] = float3(0.0, 0.0, 0.0)
lanes.capSafeSince[i] = -100.0
lanes.recallActive[i] = false
for i in range(32)
lanes.flankValid[i] = false
lanes.flankRelay[i] = float3(0.0, 0.0, 0.0)
for i in range(48)
lanes.rallyPos[i] = float3(0.0, 0.0, 0.0)
lanes.rallyStartAt[i] = -100.0
lanes.rallyReleased[i] = false
for a in range(3)
lanes.enemyAirActive[a] = false
lanes.enemyAirSeenAt[a] = -100.0
[never_inline]
def public wto_lanes_reset_rallies(var lanes : WtoTeamLanes&)
for i in range(48)
lanes.rallyStartAt[i] = -100.0
lanes.rallyReleased[i] = false
[never_inline]
def private wto_nav_project_pt(navIdx : int; var pt : float3&) : bool
if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0))
return true
return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(150.0, 120.0, 150.0))
[never_inline]
def private wto_measure_nav_path(navIdx : int; fromPt, toPt : float3; sampleFrac : float;
var outLen : float&; var outSample : float3&) : bool
var sPt = fromPt
var gPt = toPt
if !wto_nav_project_pt(navIdx, sPt) || !wto_nav_project_pt(navIdx, gPt)
return false
var ok = false
var totalLen = 0.0
var sample = lerp(sPt, gPt, sampleFrac)
find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array<float3>#)
let n = length(path)
if n < 2
return
ok = true
for i in range(1, n)
totalLen += length(path[i] - path[i - 1])
let targetD = totalLen * clamp(sampleFrac, 0.05, 0.95)
var acc = 0.0
sample = path[n - 1]
for i in range(1, n)
let seg = length(path[i] - path[i - 1])
if acc + seg >= targetD && seg > 0.01
sample = lerp(path[i - 1], path[i], (targetD - acc) / seg)
break
acc += seg
outLen = totalLen
outSample = sample
return ok && totalLen > 1.0
[never_inline]
def public wto_lanes_ensure_cap(world : WtoWorldSnap const&; army, capIdx : int;
var lanes : WtoTeamLanes&)
let k = wto_lanes_cap_key(army, capIdx)
if lanes.built[k] || capIdx < 0 || capIdx >= world.capCount || !world.teamSpawnValid[army]
return
let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1)
if navIdx < 0
return
lanes.built[k] = true
let spawnPt = world.teamSpawnCenter[army]
let capPt = world.caps[capIdx].center
var cLen = 0.0
var cRally = lerp(spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC)
if !wto_measure_nav_path(navIdx, spawnPt, capPt, WTO_AI_CMD_RALLY_PROG_FRAC, cLen, cRally)
cLen = max(80.0, sqrt(wto_xz_dist_sq(spawnPt, capPt)))
var cMid = lerp(spawnPt, capPt, 0.5)
var dummyLen = 0.0
let _midOk = wto_measure_nav_path(navIdx, spawnPt, capPt, 0.5, dummyLen, cMid)
lanes.centerLen[k] = cLen
lanes.centerMid[k] = cMid
lanes.rallyPos[k * 3 + WTO_LANE_CENTER] = cRally
let toCap = wto_xz_normalize(capPt - spawnPt, float3(1.0, 0.0, 0.0))
let lat = float3(-toCap.z, 0.0, toCap.x)
let straightD = sqrt(wto_xz_dist_sq(spawnPt, capPt))
let swing = clamp(straightD * 0.34, 80.0, 260.0)
for side in range(2)
let sign = side == 0 ? 1.0 : -1.0
var relay = wto_clamp_battle_xz(lerp(spawnPt, capPt, 0.5) + lat * (sign * swing), world.battleCenter, world.battleRadius, 45.0)
let fKey = k * 2 + side
lanes.flankValid[fKey] = false
if !wto_nav_project_pt(navIdx, relay) || !wto_terrain_point_valid(army, relay)
continue
if sqrt(wto_xz_dist_sq(relay, cMid)) < WTO_AI_CMD_FLANK_MIN_SEP_M
continue
var len1 = 0.0
var len2 = 0.0
var rPt = lerp(spawnPt, relay, 0.8)
var dummy = relay
if !wto_measure_nav_path(navIdx, spawnPt, relay, 0.8, len1, rPt)
continue
if !wto_measure_nav_path(navIdx, relay, capPt, 0.5, len2, dummy)
continue
if (len1 + len2) > cLen * WTO_AI_CMD_FLANK_MAX_RATIO
continue
lanes.flankValid[fKey] = true
lanes.flankRelay[fKey] = relay
lanes.rallyPos[k * 3 + side + 1] = rPt
[never_inline]
def public wto_lanes_update_team_intel(world : WtoWorldSnap const&; now : float;
var lanes : WtoTeamLanes&)
let airMaxSq = wto_sq(3200.0)
for a in range(1, 3)
var sawAir = false
for i in range(world.unitCount)
assume u = world.units[i]
if u.isAlive && u.isAir && u.army != a && wto_xz_dist_sq(u.pos, world.battleCenter) <= airMaxSq
sawAir = true
break
if sawAir
lanes.enemyAirSeenAt[a] = now
lanes.enemyAirActive[a] = sawAir || (now - lanes.enemyAirSeenAt[a]) <= 12.0
[never_inline]
def public wto_lanes_update_recall(world : WtoWorldSnap const&; army : int; now : float;
var lanes : WtoTeamLanes&; var outEnemiesInCap : int[8]&)
for c in range(WTO_MAX_CAPS)
outEnemiesInCap[c] = 0
for c in range(world.capCount)
let k = wto_lanes_cap_key(army, c)
if world.caps[c].ownerArmy != army
lanes.recallActive[k] = false
lanes.capSafeSince[k] = now
continue
let radSq = wto_sq(world.caps[c].radius + 35.0)
var enemies = 0
for i in range(world.unitCount)
assume u = world.units[i]
if u.isAlive && u.isGround && u.army != army && wto_xz_dist_sq(u.pos, world.caps[c].center) <= radSq
enemies++
outEnemiesInCap[c] = enemies
if world.caps[c].contested || enemies > 0
if !lanes.recallActive[k] && WTO_AI_DIAG_TELEMETRY
print("WTO_AI|RECALL|t={now}|army={army}|cap={c}|enemies={enemies}|contested={world.caps[c].contested}\n")
lanes.recallActive[k] = true
lanes.capSafeSince[k] = now
elif lanes.recallActive[k] && (now - lanes.capSafeSince[k]) >= WTO_AI_CMD_RECALL_SAFE_SEC
lanes.recallActive[k] = false
[never_inline]
def public wto_lanes_update_rallies(world : WtoWorldSnap const&; army : int; now : float;
var lanes : WtoTeamLanes&; var bots : WtoBotSlot[64]&)
let rallyRadSq = wto_sq(WTO_AI_CMD_RALLY_RADIUS_M)
for c in range(world.capCount)
wto_lanes_ensure_cap(world, army, c, lanes)
for lane in range(3)
let sk = wto_lanes_sub_key(army, c, lane)
if lanes.rallyReleased[sk]
continue
let rPos = lanes.rallyPos[sk]
if length_sq(rPos) < 1.0
lanes.rallyReleased[sk] = true
continue
let rDistToCapSq = wto_xz_dist_sq(rPos, world.caps[c].center)
var assigned = 0
var arrived = 0
for i in range(WTO_MAX_BOTS)
assume b = bots[i]
if !b.used || b.army != army || !b.order.valid || b.order.capIndex != c || b.order.laneId != lane || !wto_order_is_offensive(b.order.role)
continue
let uIdx = wto_world_find_unit(world, b.eid)
if uIdx < 0
continue
assigned++
let pos = world.units[uIdx].pos
if wto_xz_dist_sq(pos, rPos) <= rallyRadSq || wto_xz_dist_sq(pos, world.caps[c].center) < rDistToCapSq
arrived++
if assigned <= 1
lanes.rallyReleased[sk] = true
continue
if arrived > 0 && lanes.rallyStartAt[sk] < 0.0
lanes.rallyStartAt[sk] = now
let enough = float(arrived) >= float(assigned) * WTO_AI_CMD_RALLY_MIN_FRAC
let timedOut = lanes.rallyStartAt[sk] >= 0.0 && (now - lanes.rallyStartAt[sk]) >= WTO_AI_CMD_RALLY_WAIT_SEC
if enough || timedOut
lanes.rallyReleased[sk] = true
if WTO_AI_DIAG_TELEMETRY
print("WTO_AI|RALLY_GO|t={now}|army={army}|cap={c}|lane={lane}|arrived={arrived}/{assigned}|timeout={timedOut}\n")
+57
View File
@@ -0,0 +1,57 @@
// Pure zero-heap scalar, angle, and XZ plane math helpers for WTOffline's ground AI modules.
options indenting = 2
options no_global_heap = true
module wto_ai_math_common shared
require math
let public WTO_PI = 3.14159265
let public WTO_RAD_TO_DEG = 57.29577951
let public WTO_DEG_TO_RAD = 0.01745329
def public wto_sq(x : float) : float
return x * x
def public wto_is_finite(x : float) : bool
return x == x && x > -1.0e20 && x < 1.0e20
def public wto_is_finite3(v : float3) : bool
return wto_is_finite(v.x) && wto_is_finite(v.y) && wto_is_finite(v.z)
def public wto_xz_dist_sq(a, b : float3) : float
return wto_sq(a.x - b.x) + wto_sq(a.z - b.z)
def public wto_xz_len(v : float3) : float
return sqrt(v.x * v.x + v.z * v.z)
def public wto_xz_normalize(v, fallback : float3) : float3
let l = sqrt(v.x * v.x + v.z * v.z)
return l > 1.0e-4 ? float3(v.x / l, 0.0, v.z / l) : fallback
def public wto_wrap_rad(angle : float) : float
var a = angle
while a > WTO_PI
a -= 2.0 * WTO_PI
while a < -WTO_PI
a += 2.0 * WTO_PI
return a
def public wto_wrap_deg(angle : float) : float
var a = angle
while a > 180.0
a -= 360.0
while a < -180.0
a += 360.0
return a
def public wto_clamp_battle_xz(pos, center : float3; radius, margin : float) : float3
if radius <= margin + 10.0
return pos
let maxR = radius - margin
let dx = pos.x - center.x
let dz = pos.z - center.z
let dSq = dx * dx + dz * dz
if dSq <= maxR * maxR
return pos
let s = maxR / max(1.0, sqrt(dSq))
return float3(center.x + dx * s, pos.y, center.z + dz * s)
+258
View File
@@ -0,0 +1,258 @@
// Bidirectional non-holonomic local planner:
// - Directed 7-arc reverse trajectory planner for ridge withdrawals, tactical peeks, cliff escapes,
// and jam unsticking (enabling sustained 30-50m reverse transfers);
// - Stationary combat hull discipline (zero hull-pivot whip on turreted tanks during ENGAGE_HALT);
// - Forward 9-arc DWA rollout with cliff rejection, TTC ally overtaking, and jam/crowd penalties.
options indenting = 2
options no_global_heap = true
module wto_ai_nav_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_route_common
[never_inline]
def private wto_wreck_or_ally_clearance(world : WtoWorldSnap const&; selfEid : EntityId;
pt : float3; tSec, selfRad : float) : float
var pen = 0.0
for w in range(world.wreckCount)
let r = selfRad + max(world.wrecks[w].halfLen, world.wrecks[w].halfWid) + WTO_AI_TERRAIN_MARGIN_M
let dSq = wto_xz_dist_sq(pt, world.wrecks[w].pos)
if dSq < r * r
return 1.0e6
elif dSq < wto_sq(r + 3.5)
pen += 18.0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.eid == selfEid
continue
let predPos = u.pos + u.vel * min(tSec, 1.6)
let r = selfRad + max(u.halfLen, u.halfWid) + WTO_AI_TERRAIN_MARGIN_M
let dSq = wto_xz_dist_sq(pt, predPos)
if dSq < r * r
return 1.0e6
elif dSq < wto_sq(r + 5.0)
pen += 22.0
return pen
// Evaluate 7 curved rear trajectories (`16m` behind chassis) toward `reverseGoal`.
[never_inline]
def private wto_eval_reverse_arcs(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, reverseGoal : float3;
var slot : WtoBotSlot&; var outRearDir : float3&) : bool
let rearBase = -wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
let baseYaw = atan2(rearBase.z, rearBase.x)
let wishDir = wto_xz_normalize(reverseGoal - myPos, rearBase)
let selfRad = max(slot.spec.halfWid, 1.65)
var bestScore = -1.0e9
var found = false
outRearDir = rearBase
for a in range(7)
let steerFrac = float(a - 3) / 3.0
let arcCurv = steerFrac * 0.042
var cur = myPos
var blocked = false
var arcPen = abs(steerFrac) * 2.5
for s in range(1, 5)
let dist = float(s) * 3.8
let yaw = baseYaw + arcCurv * dist
let stepDir = float3(cos(yaw), 0.0, sin(yaw))
let nx = cur.x + stepDir.x * 3.8
let nz = cur.z + stepDir.z * 3.8
var gy = cur.y
if !wto_terrain_drivable_y(cur, nx, nz, gy)
blocked = true
break
if wto_terrain_hard_ray(cur + float3(0.0, 1.25, 0.0), stepDir, 4.2) < 3.7
blocked = true
break
let nxt = float3(nx, gy, nz)
let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(1.8, slot.spec.vMaxRev), selfRad)
if dynPen >= 1.0e5
blocked = true
break
arcPen += dynPen * 0.25 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.2
cur = nxt
if blocked
continue
let firstYaw = baseYaw + arcCurv * 5.5
let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw))
if wto_terrain_has_cliff_ahead(myPos, candDir, 15.0)
continue
let score = dot(candDir, wishDir) * 35.0 - arcPen - wto_world_jam_penalty(world, cur, now) * 0.4
if score > bestScore
bestScore = score
outRearDir = candDir
found = true
return found
// Evaluate 9 curved forward trajectories (`22m` ahead) with hard cliff rejection and traffic cost.
[never_inline]
def private wto_eval_forward_arcs(world : WtoWorldSnap const&; now : float;
myPos, hullFwd, wishDir : float3; speedCmd : float;
var slot : WtoBotSlot&; var outFwdDir : float3&) : bool
let fwdBase = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
let baseYaw = atan2(fwdBase.z, fwdBase.x)
let selfRad = max(slot.spec.halfWid, 1.65)
var bestScore = -1.0e9
var found = false
outFwdDir = wishDir
for a in range(9)
let steerFrac = float(a - 4) / 4.0
let arcCurv = steerFrac * 0.038
let firstYaw = baseYaw + arcCurv * 6.5
let candDir = float3(cos(firstYaw), 0.0, sin(firstYaw))
if wto_terrain_has_cliff_ahead(myPos, candDir, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M)
continue
var cur = myPos
var blocked = false
var arcPen = abs(steerFrac) * 2.2
for s in range(1, 6)
let dist = float(s) * 4.2
let yaw = baseYaw + arcCurv * dist
let stepDir = float3(cos(yaw), 0.0, sin(yaw))
let nx = cur.x + stepDir.x * 4.2
let nz = cur.z + stepDir.z * 4.2
var gy = cur.y
if !wto_terrain_drivable_y(cur, nx, nz, gy)
blocked = true
break
if wto_terrain_hard_ray(cur + float3(0.0, 1.3, 0.0), stepDir, 4.6) < 4.1
blocked = true
break
let nxt = float3(nx, gy, nz)
let dynPen = wto_wreck_or_ally_clearance(world, slot.eid, nxt, dist / max(2.5, speedCmd), selfRad)
if dynPen >= 1.0e5
blocked = true
break
arcPen += dynPen * 0.3 + wto_crowd_point_penalty(world, slot.army, slot.eid, nxt) * 0.35
cur = nxt
if blocked
continue
let align = dot(candDir, wishDir) * 40.0 + dot(candDir, slot.nav.steerDir) * 4.5
let score = align - arcPen - wto_world_jam_penalty(world, cur, now)
if score > bestScore
bestScore = score
outFwdDir = candDir
found = true
return found
[never_inline]
def private wto_set_drive_cmd(var cmd : WtoDriveCmd&; mode : int; targetPos, desiredDir : float3;
speedMps, frontClr, rearClr : float)
cmd.valid = true
cmd.mode = mode
cmd.targetPos = targetPos
cmd.desiredDir = desiredDir
cmd.speedMps = speedMps
cmd.frontClearM = frontClr
cmd.rearClearM = rearClr
[never_inline]
def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : WtoBotSlot&)
// Casemate / limited-traverse TDs rotate hull ONLY while target is outside 78% of gun arc.
if slot.spec.isLimitedTraverse && !!slot.perceive.targetEid
let toTgt = wto_xz_normalize(slot.perceive.knownPos - myPos, hullFwd)
let angDeg = acos(clamp(dot(toTgt, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
if angDeg > slot.spec.yawLimitDeg * 0.78
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM)
return
// Turreted tanks (and aligned TDs) hold chassis completely still so barrel settles cleanly!
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
[never_inline]
def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float;
myPos, wishDir : float3; var slot : WtoBotSlot&)
assume nav = slot.nav
let movingIntent = slot.tactics.desiredSpeedMps > 1.2 && now >= nav.reverseUntil
if !movingIntent
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
return
if nav.stuckCheckAt < -50.0
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
return
if now < nav.stuckCheckAt
return
let moved = sqrt(wto_xz_dist_sq(myPos, nav.stuckOrigin))
nav.stuckOrigin = myPos
nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
if moved >= WTO_AI_NAV_STUCK_MIN_MOVE_M
return
wto_world_record_jam(world, myPos + wishDir * 6.0, now)
wto_route_request_detour(world, now, myPos, wishDir, slot)
let backIdx = clamp(slot.route.corridorIdx - 2, 0, max(0, slot.route.corridorLen - 1))
nav.reverseAnchor = slot.route.corridorLen > 0 ? slot.route.corridor[backIdx] : (myPos - wishDir * 22.0)
nav.reverseUntil = now + max(WTO_AI_NAV_UNSTICK_REV_SEC, 3.6)
nav.reverseCount++
[never_inline]
def private wto_try_reverse_drive(world : WtoWorldSnap const&; now : float;
myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
let stMode = slot.tactics.state
let wantTacRev = stMode == WTO_STATE_RIDGE_WITHDRAW || (stMode == WTO_STATE_RETREAT_COVER && slot.tactics.retreatReverse)
if !wantTacRev && now >= slot.nav.reverseUntil
return false
let revGoal = wantTacRev ? slot.tactics.moveGoal : slot.nav.reverseAnchor
var rearDir = -hullFwd
if slot.nav.rearClearM > 2.4 && wto_eval_reverse_arcs(world, now, myPos, hullFwd, revGoal, slot, rearDir)
slot.nav.steerDir = rearDir
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, myPos + rearDir * 18.0, rearDir, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM)
return true
slot.nav.reverseUntil = -100.0
return false
[never_inline]
def public wto_nav_update(var world : WtoWorldSnap&; now : float;
myPos, rawHullFwd : float3; var slot : WtoBotSlot&)
if !WTO_AI_LAYER_NAVIGATION
slot.driveCmd.valid = false
return
let hullFwd = wto_xz_normalize(rawHullFwd, float3(1.0, 0.0, 0.0))
let probeBase = myPos + float3(0.0, 1.25, 0.0)
slot.nav.frontClearM = wto_terrain_hard_ray(probeBase, hullFwd, 24.0)
slot.nav.rearClearM = wto_terrain_hard_ray(probeBase, -hullFwd, 18.0)
slot.nav.cliffAhead = wto_terrain_has_cliff_ahead(myPos, hullFwd, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M)
if slot.tactics.state == WTO_STATE_HULL_ANGLE
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
let wishAngle = wto_xz_normalize(slot.tactics.hullAngleDir, hullFwd)
let angErr = acos(clamp(dot(wishAngle, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
if angErr > 8.0
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + wishAngle * 14.0, wishAngle, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
else
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
return
if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
wto_handle_stationary_engage(myPos, hullFwd, slot)
return
if wto_try_reverse_drive(world, now, myPos, hullFwd, slot)
return
let wp = wto_route_select_waypoint(world, now, myPos, slot.tactics.moveGoal, slot)
let wishDir = wto_xz_normalize(wp - myPos, hullFwd)
wto_check_stuck_watchdog(world, now, myPos, wishDir, slot)
var bestDir = wishDir
if !wto_eval_forward_arcs(world, now, myPos, hullFwd, wishDir, slot.tactics.desiredSpeedMps, slot, bestDir)
if slot.nav.rearClearM > 3.2
slot.nav.reverseAnchor = myPos - hullFwd * 26.0
slot.nav.reverseUntil = now + 4.8
slot.nav.reverseCount++
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_REVERSE, slot.nav.reverseAnchor, -hullFwd, max(2.0, slot.spec.vMaxRev), slot.nav.frontClearM, slot.nav.rearClearM)
return
bestDir = wishDir
slot.nav.steerDir = bestDir
let turnDeg = acos(clamp(dot(wishDir, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG
let needPivot = turnDeg >= WTO_AI_NAV_PIVOT_ANGLE_DEG || (slot.nav.frontClearM < slot.spec.halfLen + 1.8 && turnDeg > 32.0)
let cmdDir = needPivot ? wishDir : bestDir
wto_set_drive_cmd(slot.driveCmd, needPivot ? WTO_DRIVE_PIVOT : WTO_DRIVE_CRUISE, myPos + cmdDir * 22.0, cmdDir, slot.tactics.desiredSpeedMps, slot.nav.frontClearM, slot.nav.rearClearM)
+57
View File
@@ -0,0 +1,57 @@
// Task order contract between the team commander and per-bot hull behavior.
// Every per-bot decision reads `WtoTaskOrder` rather than guessing team intent.
options indenting = 2
options no_global_heap = true
module wto_ai_order_common shared
let public WTO_MODE_UNKNOWN = 0
let public WTO_MODE_BTTL = 1
let public WTO_MODE_CONQ = 2
let public WTO_MODE_DOM = 3
let public WTO_CMD_ASSAULT = 0
let public WTO_CMD_FLANK = 1
let public WTO_CMD_OVERWATCH = 2
let public WTO_CMD_DEFEND = 3
let public WTO_CMD_RESERVE = 4
let public WTO_CMD_SPAA = 5
let public WTO_URGENCY_LOW = 0
let public WTO_URGENCY_MED = 1
let public WTO_URGENCY_HIGH = 2
[safe_when_uninitialized]
struct public WtoTaskOrder
valid : bool = false
role : int = 0
capIndex : int = -1
laneId : int = 0
goalPos : float3 = float3(0.0, 0.0, 0.0)
routeRelayValid : bool = false
routeRelayPos : float3 = float3(0.0, 0.0, 0.0)
rallyHold : bool = false
urgency : int = 1
maxStopRangeM : float = 800.0
assignedAt : float = -100.0
expiresAt : float = -100.0
cautious : bool = false
overwatchOutside : bool = false
spaaAnchorValid : bool = false
spaaAnchorPos : float3 = float3(0.0, 0.0, 0.0)
spaaRelocateAt : float = -100.0
[never_inline]
def public wto_order_is_offensive(role : int) : bool
return role == WTO_CMD_ASSAULT || role == WTO_CMD_FLANK
[never_inline]
def public wto_order_max_stop_range(role, urgency : int; maxEngageRangeM : float) : float
if role == WTO_CMD_ASSAULT || role == WTO_CMD_FLANK
return 300.0
if role == WTO_CMD_OVERWATCH
return maxEngageRangeM
if role == WTO_CMD_DEFEND
return urgency == WTO_URGENCY_HIGH ? 300.0 : maxEngageRangeM
if role == WTO_CMD_RESERVE
return 800.0
return 300.0
+233
View File
@@ -0,0 +1,233 @@
// Exposure-integrated visual perception with strict foliage/smoke/hard occlusion,
// directional-only audio/hit/radio clues, and frozen last-seen memory.
options indenting = 2
options no_global_heap = true
module wto_ai_perceive_common shared
require ecs
require math
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_sight_common
require %appGame.wtoai.wto_ai_estimate_common
require %appGame.wtoai.wto_ai_world_common
[never_inline]
def private wto_exp_find_or_alloc(var p : WtoPerceiveState&; eid : EntityId) : int
var freeIdx = -1
var minIdx = 0
var minScore = 2.0
for i in range(WTO_MAX_EXPOSURE_TRACKS)
if p.expEids[i] == eid
return i
if !p.expEids[i] && freeIdx < 0
freeIdx = i
if p.expScore[i] < minScore
minScore = p.expScore[i]
minIdx = i
let dst = freeIdx >= 0 ? freeIdx : minIdx
p.expEids[dst] = eid
p.expScore[dst] = 0.0
p.expGoodLosSec[dst] = 0.0
return dst
[never_inline]
def private wto_exp_decay_all(world : WtoWorldSnap const&; dt : float; var p : WtoPerceiveState&)
let decay = WTO_AI_PERC_DECAY_PER_SEC * dt
for i in range(WTO_MAX_EXPOSURE_TRACKS)
if !p.expEids[i]
continue
let uIdx = wto_world_find_unit(world, p.expEids[i])
if uIdx < 0 || !world.units[uIdx].isAlive
p.expEids[i] = INVALID_ENTITY_ID
p.expScore[i] = 0.0
p.expGoodLosSec[i] = 0.0
continue
p.expScore[i] = max(0.0, p.expScore[i] - decay)
if p.expScore[i] <= 0.001
p.expEids[i] = INVALID_ENTITY_ID
p.expScore[i] = 0.0
p.expGoodLosSec[i] = 0.0
[never_inline]
def private wto_spot_fill_time(dist : float; cosAngle : float; isShooting : bool; visCount : int) : float
let cosFront = cos(WTO_AI_PERC_FRONT_CONE_DEG * WTO_DEG_TO_RAD)
var t = WTO_AI_PERC_FAR_SPOT_SEC
if dist < WTO_AI_PERC_NEAR_SPOT_M || (isShooting && dist < WTO_AI_PERC_FIRING_SPOT_M)
t = WTO_AI_PERC_FAST_SPOT_SEC
elif dist <= 550.0 && cosAngle >= cosFront
t = WTO_AI_PERC_NORMAL_SPOT_SEC
if visCount >= 3
t *= 0.85
return max(0.08, t)
[never_inline]
def private wto_update_audio_and_radio_alerts(world : WtoWorldSnap const&; now : float;
myPos : float3; var slot : WtoBotSlot&)
assume p = slot.perceive
// Priority A: Recent hit direction captured at impact time (never reveals hidden true position).
if (now - p.lastDamagedAt) <= 4.0 && !!p.lastOffenderEid
p.alertYawRad = p.lastHitYawRad
p.alertUntil = now + 4.5
return
// Priority B: Close enemy engine / cannon sound direction clue.
var bestAudioDist = 1.0e9
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.army == slot.army
continue
let d = sqrt(wto_xz_dist_sq(myPos, u.pos))
let engRange = WTO_AI_TACTICS_ENGINE_AUDIO_M * (0.35 + 0.65 * u.engineRpm)
let heard = d <= engRange || (u.isShooting && d <= WTO_AI_TACTICS_SHOT_AUDIO_M)
if heard && d < bestAudioDist
bestAudioDist = d
let dir = u.pos - myPos
p.alertYawRad = atan2(dir.z, dir.x)
p.alertUntil = now + 3.2
if bestAudioDist < 1.0e8
return
// Priority C: Friendly radio spot direction clue (alert only, never enables firing).
let radioSq = wto_sq(WTO_AI_TACTICS_RADIO_SHARE_M)
for r in range(WTO_MAX_RADIO)
assume sp = world.radioSpots[r]
if sp.untilAt > now && sp.army == slot.army && wto_xz_dist_sq(myPos, sp.pos) <= radioSq
let dir = sp.pos - myPos
p.alertYawRad = atan2(dir.z, dir.x)
p.alertUntil = now + 2.8
return
[never_inline]
def private wto_scan_visual_exposure(world : WtoWorldSnap const&; now, dt : float;
myEye, lookDir : float3; var slot : WtoBotSlot&;
var outBestIdx, outVisCount : int&;
var outGoodLosSec : float&; var outAimPt : float3&)
assume p = slot.perceive
let cosHalfFov = cos(0.5 * WTO_AI_TACTICS_VISION_FOV_DEG * WTO_DEG_TO_RAD)
let isSpaa = slot.spec.role == WTO_ROLE_SPAA
let decay = WTO_AI_PERC_DECAY_PER_SEC * dt
var bestScore = 1.0e9
outBestIdx = -1
outVisCount = 0
outGoodLosSec = 0.0
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || u.army == slot.army || (u.isAir && !isSpaa)
continue
let delta = u.pos - myEye
let dist = length(delta)
let maxRange = u.isAir ? 2600.0 : WTO_AI_TACTICS_VISION_RANGE_M
if dist > maxRange || dist < 1.0
continue
let dirXZ = wto_xz_normalize(delta, lookDir)
let cosAng = dot(dirXZ, lookDir)
let inFov = cosAng >= cosHalfFov || (dist <= WTO_AI_PERC_PERIPH_CLOSE_M && cosAng >= 0.0)
if !inFov && !u.isAir
continue
let maxSamples = dist > WTO_AI_FC_LONG_RANGE_M ? 2 : 4
var samplePt = u.pos + float3(0.0, 1.3, 0.0)
let vis = wto_sight_check_target_samples(world, slot.eid, myEye, u, maxSamples, samplePt)
if vis <= 0
for k in range(WTO_MAX_EXPOSURE_TRACKS)
if p.expEids[k] == u.eid
p.expGoodLosSec[k] = 0.0
continue
let tIdx = wto_exp_find_or_alloc(p, u.eid)
let fillSec = wto_spot_fill_time(dist, cosAng, u.isShooting, vis)
p.expScore[tIdx] = clamp(p.expScore[tIdx] + decay + dt / fillSec, 0.0, 1.0)
p.expGoodLosSec[tIdx] = vis >= 2 ? (p.expGoodLosSec[tIdx] + dt) : 0.0
if p.expScore[tIdx] < 0.999
continue
var score = dist - (u.isAir && isSpaa ? 900.0 : 0.0)
if u.eid == p.lockedEid && now < p.lockedUntil
score -= 320.0
elif u.eid == p.lastOffenderEid && (now - p.lastDamagedAt) <= 5.0
score -= 90.0
elif u.isShooting && dist < 220.0
score -= 35.0
if dist < 45.0
score -= 180.0
if score < bestScore
bestScore = score
outBestIdx = i
outVisCount = vis
outGoodLosSec = p.expGoodLosSec[tIdx]
outAimPt = samplePt
[never_inline]
def public wto_perceive_update(var world : WtoWorldSnap&; now, dt : float;
myPos, hullFwd : float3; var slot : WtoBotSlot&)
assume p = slot.perceive
let myEye = myPos + float3(0.0, 2.15, 0.0)
var lookDir = wto_xz_normalize(hullFwd, float3(1.0, 0.0, 0.0))
if slot.fire.servoInit
let worldYaw = atan2(hullFwd.z, hullFwd.x) - slot.fire.curYawDeg * WTO_DEG_TO_RAD
lookDir = float3(cos(worldYaw), 0.0, sin(worldYaw))
wto_exp_decay_all(world, dt, p)
var bestIdx = -1
var visCount = 0
var goodLosSec = 0.0
var aimPt = myPos
wto_scan_visual_exposure(world, now, dt, myEye, lookDir, slot, bestIdx, visCount, goodLosSec, aimPt)
if bestIdx >= 0
assume tgt = world.units[bestIdx]
p.targetEid = tgt.eid
p.targetIsAir = tgt.isAir
p.hasClearLos = true
p.visiblePointCount = visCount
p.goodLosSec = goodLosSec
p.visibleAimPt = aimPt
p.knownPos = tgt.pos
p.lastSeenAt = now
p.wasEngaging = !tgt.isAir
p.watchUntil = -100.0
wto_est_push_visual_sample(now, tgt.eid, tgt.pos, p)
if p.lockedEid != tgt.eid || now >= p.lockedUntil - 0.5
p.lockedEid = tgt.eid
p.lockedUntil = now + WTO_AI_TACTICS_STICKY_SEC
if !tgt.isAir && (now - p.lastRadioSentAt) >= 2.5
p.lastRadioSentAt = now
wto_world_broadcast_radio(world, slot.army, tgt.eid, tgt.pos, now)
return
// Lost visual confirmation: immediately revoke LOS, freeze exit point for 2-5 s watch, zero velocity.
p.hasClearLos = false
p.visiblePointCount = 0
p.goodLosSec = 0.0
wto_est_on_los_lost(now, slot.eid, p)
let tgtIdx = wto_world_find_unit(world, p.targetEid)
if !!p.targetEid && (tgtIdx < 0 || !world.units[tgtIdx].isAlive || (now - p.lastSeenAt) > WTO_AI_TACTICS_MEMORY_TTL_SEC)
p.targetEid = INVALID_ENTITY_ID
p.lockedEid = INVALID_ENTITY_ID
p.watchUntil = -100.0
wto_update_audio_and_radio_alerts(world, now, myPos, slot)
[never_inline]
def public wto_perceive_pick_hunt_pos(world : WtoWorldSnap const&; army : int; eid : EntityId;
myPos : float3; now : float; var outPos : float3&) : bool
var bestDistSq = wto_sq(min(WTO_AI_TACTICS_RADIO_SHARE_M, 560.0))
var found = false
var spotPos = myPos
for r in range(WTO_MAX_RADIO)
assume sp = world.radioSpots[r]
if sp.untilAt <= now || sp.army != army
continue
let dSq = wto_xz_dist_sq(myPos, sp.pos)
if dSq < bestDistSq && dSq > 2500.0
bestDistSq = dSq
spotPos = sp.pos
found = true
if !found
return false
let toSpot = wto_xz_normalize(spotPos - myPos, float3(1.0, 0.0, 0.0))
let lat = float3(-toSpot.z, 0.0, toSpot.x)
let fanOffset = float(int(uint(eid) % 5u) - 2) * 28.0
var cand = spotPos - toSpot * 65.0 + lat * fanOffset
cand = wto_clamp_battle_xz(cand, world.battleCenter, world.battleRadius, 40.0)
if !wto_terrain_point_valid(army, cand)
cand = spotPos
outPos = cand
return true
+169
View File
@@ -0,0 +1,169 @@
// Corridor route planner: wide-projected `nm1` NavMesh pathfinding (fixing off-road hill caps),
// 5-wing lateral approach relays, crest-safe cross-country shortcuts, and corridor-independent
// jam/cluster bypass waypoints.
options indenting = 2
options no_global_heap = true
module wto_ai_route_common shared
require ecs
require math
require pathfinder
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
[never_inline]
def private wto_project_nav_wide(navIdx : int; var pt : float3&) : bool
if project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(28.0, 64.0, 28.0))
return true
return project_to_nearest_navmesh_point_no_obstacles_ex(navIdx, pt, float3(165.0, 130.0, 165.0))
[never_inline]
def private wto_replan_corridor(now : float; myPos, goal : float3; var rt : WtoRouteState&)
rt.nextReplanAt = now + 2.8
rt.corridorGoal = goal
rt.corridorLen = 0
rt.corridorIdx = 0
let navIdx = pathfinder_is_loaded_ex(1) ? 1 : (pathfinder_is_loaded_ex(0) ? 0 : -1)
if navIdx < 0
rt.lastStartOk = false
rt.lastGoalOk = false
return
var sPt = myPos
var gPt = goal
rt.lastStartOk = wto_project_nav_wide(navIdx, sPt)
rt.lastGoalOk = wto_project_nav_wide(navIdx, gPt)
if !rt.lastStartOk || !rt.lastGoalOk
return
let maxKeep = WTO_MAX_PATH_PTS - 1
find_path_ex(navIdx, sPt, gPt, float3(32.0, 48.0, 32.0), 9.0, 2.5, null) <| $(path : array<float3>#)
let total = length(path)
if total <= 0
return
rt.corridor[0] = path[0]
rt.corridorLen = 1
let minStepSq = total > maxKeep ? wto_sq(max(12.0, float(total) * 9.0 / float(maxKeep))) : 0.0
for i in range(1, total)
if rt.corridorLen >= maxKeep
break
let prev = rt.corridor[rt.corridorLen - 1]
var isCorner = false
if i + 1 < total
let d0 = wto_xz_normalize(path[i] - prev, float3(1.0, 0.0, 0.0))
let d1 = wto_xz_normalize(path[i + 1] - path[i], d0)
isCorner = dot(d0, d1) < 0.86
if i == total - 1 || isCorner || wto_xz_dist_sq(prev, path[i]) >= minStepSq
rt.corridor[rt.corridorLen] = path[i]
rt.corridorLen++
if rt.corridorLen < maxKeep && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], path[total - 1]) > 9.0
rt.corridor[rt.corridorLen] = path[total - 1]
rt.corridorLen++
if rt.corridorLen > 0 && rt.corridorLen < WTO_MAX_PATH_PTS && wto_xz_dist_sq(rt.corridor[rt.corridorLen - 1], goal) > 64.0
rt.corridor[rt.corridorLen] = goal
rt.corridorLen++
// Validate a crest-safe cross-country shortcut (<= 145m) with zero cliff drop-offs or jams.
[never_inline]
def private wto_try_shortcut(world : WtoWorldSnap const&; now : float; myPos, target : float3;
var slot : WtoBotSlot&)
assume rt = slot.route
rt.shortcutValid = false
rt.nextShortcutAt = now + 1.1
let dist = sqrt(wto_xz_dist_sq(myPos, target))
if dist < 22.0 || dist > 145.0
return
let dir = wto_xz_normalize(target - myPos, float3(1.0, 0.0, 0.0))
if wto_terrain_has_cliff_ahead(myPos, dir, min(dist, WTO_AI_TERRAIN_CREST_LOOKAHEAD_M + 8.0))
return
let steps = clamp(int(dist / 7.5), 2, 20)
var prev = myPos
for s in range(1, steps + 1)
let d = (dist * float(s)) / float(steps)
let tx = myPos.x + dir.x * d
let tz = myPos.z + dir.z * d
var gy = prev.y
if !wto_terrain_drivable_y(prev, tx, tz, gy)
return
let samplePt = float3(tx, gy, tz)
if wto_world_jam_penalty(world, samplePt, now) > 4.0 || wto_crowd_point_penalty(world, slot.army, slot.eid, samplePt) > 18.0
return
if wto_terrain_hard_ray(prev + float3(0.0, 1.3, 0.0), dir, 8.0) < 7.5
return
prev = samplePt
rt.shortcutPos = target
rt.shortcutValid = true
// Generate a lateral bypass waypoint around an obstacle/jam, even when no NavMesh corridor exists.
[never_inline]
def public wto_route_request_detour(world : WtoWorldSnap const&; now : float;
myPos, blockedDir : float3; var slot : WtoBotSlot&)
assume rt = slot.route
let fwd = wto_xz_normalize(blockedDir, float3(1.0, 0.0, 0.0))
let lat = float3(-fwd.z, 0.0, fwd.x)
let pref = ((uint(slot.eid) + uint(rt.detourCount)) & 1u) == 0u ? 1.0 : -1.0
var bestScore = -1.0e9
var found = false
var bestPt = myPos
for k in range(4)
let side = (k % 2 == 0 ? pref : -pref) * (k < 2 ? 38.0 : 56.0)
let fwdStep = k < 2 ? 22.0 : 12.0
var cand = wto_clamp_battle_xz(myPos + fwd * fwdStep + lat * side, world.battleCenter, world.battleRadius, 35.0)
if !wto_terrain_point_valid(slot.army, cand)
continue
let candDir = wto_xz_normalize(cand - myPos, lat)
if wto_terrain_has_cliff_ahead(myPos, candDir, 18.0)
continue
if wto_terrain_hard_ray(myPos + float3(0.0, 1.3, 0.0), candDir, 16.0) < 10.0
continue
let score = -wto_world_jam_penalty(world, cand, now) - wto_crowd_point_penalty(world, slot.army, slot.eid, cand)
if score > bestScore
bestScore = score
bestPt = cand
found = true
if found
rt.detourPos = bestPt
rt.detourValid = true
rt.detourUntil = now + 11.0
rt.detourCount++
[never_inline]
def public wto_route_select_waypoint(world : WtoWorldSnap const&; now : float;
myPos, finalGoal : float3; var slot : WtoBotSlot&) : float3
assume rt = slot.route
if rt.detourValid
if now < rt.detourUntil && wto_xz_dist_sq(myPos, rt.detourPos) > 100.0
return rt.detourPos
rt.detourValid = false
if !rt.wingInit
rt.wingInit = true
rt.laneOffsetM = float(int((uint(slot.eid) / 5u) % 5u) - 2) * 4.0
let st = slot.tactics.state
let useRelay = (st == WTO_STATE_MARCH || st == WTO_STATE_PREAIM || st == WTO_STATE_RELOAD_ADVANCE) && slot.order.routeRelayValid
var activeGoal = finalGoal
if useRelay
let relay = slot.order.routeRelayPos
let distMeToRelaySq = wto_xz_dist_sq(myPos, relay)
let distMeToGoalSq = wto_xz_dist_sq(myPos, finalGoal)
let distRelayToGoalSq = wto_xz_dist_sq(relay, finalGoal)
if slot.order.rallyHold || (distMeToRelaySq > 1444.0 && distMeToGoalSq > distRelayToGoalSq)
activeGoal = relay
if now >= rt.nextShortcutAt
wto_try_shortcut(world, now, myPos, activeGoal, slot)
if rt.shortcutValid && wto_xz_dist_sq(rt.shortcutPos, activeGoal) <= 144.0
return activeGoal
if now >= rt.nextReplanAt || wto_xz_dist_sq(rt.corridorGoal, activeGoal) > 400.0
wto_replan_corridor(now, myPos, activeGoal, rt)
while rt.corridorIdx < rt.corridorLen - 1 && wto_xz_dist_sq(myPos, rt.corridor[rt.corridorIdx]) <= 256.0
rt.corridorIdx++
if rt.corridorLen > 0 && rt.corridorIdx < rt.corridorLen
let wp = rt.corridor[rt.corridorIdx]
let toWp = wto_xz_normalize(wp - myPos, float3(1.0, 0.0, 0.0))
let lat = float3(-toWp.z, 0.0, toWp.x)
return wp + lat * clamp(rt.laneOffsetM, -6.0, 6.0)
return activeGoal
+286
View File
@@ -0,0 +1,286 @@
// Thin ECS orchestrator for WTOffline's modular ground AI system.
// Frame pipeline: world snapshot -> crowd density -> macro objectives -> tactics & perception ->
// corridor & bidirectional local nav -> chassis drive actuator -> deterministic fire control.
options indenting = 2
options no_global_variables = false
options no_global_heap = true
options stack = 65536
require ecs
require app
require math
require DagorMath
require dm
require WTDamageModel
require Unit
require IGroundModel
require HeavyVehicleModel
require vehicle
require pathfinder
require %appGame.wt_events
require %game.events
require %game.unit.unit_events
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_order_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_specs_common
require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common
require %appGame.wtoai.wto_ai_lanes_common
require %appGame.wtoai.wto_ai_commander_common
require %appGame.wtoai.wto_ai_perceive_common
require %appGame.wtoai.wto_ai_tactics_common
require %appGame.wtoai.wto_ai_nav_common
require %appGame.wtoai.wto_ai_drive_common
require %appGame.wtoai.wto_ai_fire_common
require %appGame.wtoai.wto_ai_diag_common
var private @safe_when_uninitialized g_world : WtoWorldSnap
var private @safe_when_uninitialized g_crowd : WtoCrowdSummary
var private @safe_when_uninitialized g_lanes : WtoTeamLanes
var private @safe_when_uninitialized g_bots : WtoBotSlot[64]
var private g_last_world_frame : float = -1.0
var private g_next_cmd_at : float = 0.0
var private g_next_rally_at : float = 0.0
var private g_cmd_dirty : bool = true
var private g_last_zone_ver : int = -1
var private g_fire_budget : int = 0
var private g_next_diag_at : float = 0.0
def private wto_any_layer_active() : bool
return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL)
[init]
def wto_ai_script_init()
wto_drive_announce_script_ready()
[never_inline]
def private wto_reset_runtime()
wto_world_reset(g_world)
wto_lanes_reset(g_lanes)
g_crowd = WtoCrowdSummary()
g_last_world_frame = -1.0
g_next_cmd_at = 0.0
g_next_rally_at = 0.0
g_cmd_dirty = true
g_last_zone_ver = -1
g_next_diag_at = 0.0
for i in range(WTO_MAX_BOTS)
if g_bots[i].drive.routeBOwned
wto_drive_request_control(g_bots[i].eid, 0)
g_bots[i] = WtoBotSlot()
wto_drive_release_all()
[never_inline]
def private wto_find_slot(eid : EntityId) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
for i in range(cap)
if g_bots[i].used && g_bots[i].eid == eid
return i
return -1
[never_inline]
def private wto_acquire_slot(eid : EntityId; army : int; now : float) : int
let cap = min(WTO_MAX_BOTS, WTO_AI_MAX_TRACKED_BOTS)
var freeIdx = -1
for i in range(cap)
if g_bots[i].used && g_bots[i].eid == eid
g_bots[i].army = army
g_bots[i].lastSeenAt = now
return i
if !g_bots[i].used && freeIdx < 0
freeIdx = i
if freeIdx >= 0
g_bots[freeIdx] = WtoBotSlot()
g_bots[freeIdx].used = true
g_bots[freeIdx].eid = eid
g_bots[freeIdx].army = army
g_bots[freeIdx].lastSeenAt = now
g_bots[freeIdx].nextTacticsAt = now - 0.01
g_bots[freeIdx].nextNavAt = now - 0.01
g_bots[freeIdx].route.nextReplanAt = now - 0.01
g_cmd_dirty = true
return freeIdx
[never_inline]
def private wto_phys_slot_available() : bool
if WTO_AI_NAV_MAX_PHYS_BOTS <= 0
return false
var count = 0
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && g_bots[i].drive.routeBOwned && !g_bots[i].drive.routeAFallback
count++
if count >= WTO_AI_NAV_MAX_PHYS_BOTS
return false
return true
[es(tag=server, on_event=(EventMissionUnload, EventEntityManagerBeforeClear, EventEcsMissionLoaded))]
def wto_ai_mission_reset_es(evt : Event)
wto_reset_runtime()
wto_drive_announce_script_ready()
[es(tag=server)]
def wto_ai_zone_captured_es(evt : EventZoneCaptured)
if !wto_any_layer_active()
return
g_world.zoneVersion++
g_cmd_dirty = true
print("WTO_AI|ZONE_CAP|area={evt.areaId}|from={int(evt.wasArmy)}|to={int(evt.army)}\n")
[es(tag=server, on_event=(EventOnUnitDead, EventUnitBecameDead))]
def wto_ai_unit_dead_es(evt : Event; eid : EntityId; unit__ref : UnitRef)
let u = unit__ref.unit
if u != null && as_gm(u) != null && (int(u.army) == 1 || int(u.army) == 2)
wto_world_record_death(g_world, eid, int(u.army), u.pos, float(get_app().usefulTotalTime))
let idx = wto_find_slot(eid)
if idx >= 0
if g_bots[idx].drive.routeBOwned
wto_drive_request_control(eid, 0)
g_bots[idx] = WtoBotSlot()
g_cmd_dirty = true
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid
g_bots[i].tactics.engageShotsNoEffect = 0
g_bots[i].tactics.engageNoShotHalts = 0
g_bots[i].tactics.engageTotalHaltSec = 0.0
[es(tag=server, on_disappear, on_event=EventUnitRespawn)]
def wto_ai_unit_cleanup_es(evt : Event; eid : EntityId)
let idx = wto_find_slot(eid)
if idx >= 0
if g_bots[idx].drive.routeBOwned
wto_drive_request_control(eid, 0)
g_bots[idx] = WtoBotSlot()
g_cmd_dirty = true
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && g_bots[i].tactics.engageTargetEid == eid
g_bots[i].tactics.engageShotsNoEffect = 0
g_bots[i].tactics.engageNoShotHalts = 0
g_bots[i].tactics.engageTotalHaltSec = 0.0
[es(tag=server)]
def wto_ai_unit_damage_es(evt : EventUnitDamage; eid : EntityId; unit__ref : UnitRef)
if !wto_any_layer_active() || !WTO_AI_LAYER_TACTICS
return
let offEid = evt.offender.eid
let u = unit__ref.unit
if u == null || !offEid || offEid == eid
return
let now = float(get_app().usefulTotalTime)
let vicArmy = int(u.army)
// Outgoing effective damage confirmation for our firing bot (resets stalemate counters).
let offBotIdx = wto_find_slot(offEid)
if offBotIdx >= 0 && g_bots[offBotIdx].army != vicArmy && uint(evt.hpFixed) < uint(evt.prevHpFixed)
assume tac = g_bots[offBotIdx].tactics
if tac.engageTargetEid == eid || g_bots[offBotIdx].perceive.targetEid == eid
tac.engageShotsNoEffect = 0
tac.engageNoShotHalts = 0
tac.lastEffectAt = now
// Incoming hit direction cue for our damaged bot (never leaks hidden offender coords).
let idx = wto_find_slot(eid)
if idx < 0
return
let offUnitIdx = wto_world_find_unit(g_world, offEid)
if offUnitIdx >= 0 && g_world.units[offUnitIdx].army == g_bots[idx].army
return
let imp = evt.pos - u.pos
g_bots[idx].perceive.lastHitYawRad = (imp.x * imp.x + imp.z * imp.z) > 0.04 ? atan2(imp.z, imp.x) : atan2(u.unitTm[0].z, u.unitTm[0].x)
g_bots[idx].perceive.lastDamagedAt = now
g_bots[idx].perceive.lastOffenderEid = offEid
[es(tag=server, before=wto_ai_pipeline_es)]
def wto_ai_world_tick_es(act : UpdateStageInfoAct)
if !wto_any_layer_active() || !is_app_in_flight()
return
if abs(act.curTime - g_last_world_frame) <= 1.0e-4
return
g_last_world_frame = act.curTime
g_fire_budget = WTO_AI_FC_MAX_CHECKS_PER_TICK
let now = float(get_app().usefulTotalTime)
if g_world.valid && now < g_world.time - 1.0
wto_reset_runtime()
for i in range(WTO_MAX_BOTS)
if g_bots[i].used && (now - g_bots[i].lastSeenAt) > 3.5
g_bots[i] = WtoBotSlot()
if !g_world.valid
wto_drive_announce_script_ready()
print("WTO_AI|RUNTIME_READY\n")
wto_world_refresh(now, g_world)
wto_crowd_update_all(g_world, g_bots, g_crowd)
let zoneChanged = g_world.zoneVersion != g_last_zone_ver
if zoneChanged
g_last_zone_ver = g_world.zoneVersion
wto_lanes_reset_rallies(g_lanes)
g_cmd_dirty = true
if WTO_AI_LAYER_MACRO && (now >= g_next_cmd_at || g_cmd_dirty)
g_next_cmd_at = now + WTO_AI_CMD_REBALANCE_SEC
g_next_rally_at = now + 1.0
g_cmd_dirty = false
wto_commander_update_all(g_world, now, zoneChanged, g_lanes, g_bots)
elif WTO_AI_LAYER_MACRO && now >= g_next_rally_at
g_next_rally_at = now + 1.0
wto_lanes_update_rallies(g_world, 1, now, g_lanes, g_bots)
wto_lanes_update_rallies(g_world, 2, now, g_lanes, g_bots)
for i in range(WTO_MAX_BOTS)
assume b = g_bots[i]
if b.used && b.order.valid && b.order.rallyHold && b.order.capIndex >= 0
let sk = wto_lanes_sub_key(b.army, b.order.capIndex, b.order.laneId)
if g_lanes.rallyReleased[sk]
b.order.rallyHold = false
if b.order.role == WTO_CMD_FLANK && b.order.laneId > 0
let ck = wto_lanes_cap_key(b.army, b.order.capIndex)
b.order.routeRelayValid = g_lanes.flankValid[ck * 2 + b.order.laneId - 1]
b.order.routeRelayPos = g_lanes.flankRelay[ck * 2 + b.order.laneId - 1]
else
b.order.routeRelayValid = false
if WTO_AI_DIAG_TELEMETRY && now >= g_next_diag_at
g_next_diag_at = now + WTO_AI_DIAG_INTERVAL_SEC
wto_diag_log_telemetry(g_world, now, g_bots, g_crowd)
[es(tag=server, no_order)]
def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
unit__className : string = "";
repair_system_remaining_repair_time : float = -1.0)
if !wto_any_layer_active() || !g_world.valid
return
var unit = unit__ref.unit
if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer
return
let army = int(unit.army)
let gm = as_gm(unit)
if (army != 1 && army != 2) || gm == null || gm.moveSys == null || as_hv(unit) == null
return
let now = float(get_app().usefulTotalTime)
let idx = wto_acquire_slot(eid, army, now)
if idx < 0
return
assume slot = g_bots[idx]
if !slot.prepared
slot.prepared = true
wto_specs_load(eid, unit__className, unit, gm, slot.spec)
if now >= slot.nextTacticsAt
slot.nextTacticsAt = now + WTO_AI_TACTICS_TICK_SEC
if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL
wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot)
wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd)
if now >= slot.nextNavAt
slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC
wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot)
wto_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget)
[es(tag=server, after=wto_ai_pipeline_es)]
def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
unit__missionName : string; var vehicle_net_phys : VehiclePhysActor&)
if !wto_any_layer_active() || !WTO_AI_LAYER_NAVIGATION || WTO_AI_NAV_DRIVE_MODE != "vehicle_phys"
return
var unit = unit__ref.unit
if unit == null || !unit.isAlive || unit.isDelayed || unit.isHumanPlayer || vehicle_net_phys.physEdit == null
return
let idx = wto_find_slot(eid)
if idx < 0
return
if !g_bots[idx].drive.routeBOwned && !wto_phys_slot_available()
return
let now = float(get_app().usefulTotalTime)
wto_drive_step_phys(unit, unit__missionName, as_gm(unit), vehicle_net_phys, act.dt, now, g_bots[idx])
+126
View File
@@ -0,0 +1,126 @@
// Scene visibility, foliage transparency, smoke, and strict hard-occlusion queries.
// Completely separate from driving's soft-obstacle avoidance in wto_ai_terrain_common.
options indenting = 2
options no_global_heap = true
module wto_ai_sight_common shared
require ecs
require math
require DagorMath
require Dacoll
require RendInst
require PhysMat
require SmokeOccluder
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
let private SIGHT_TERRAIN_MASK = ETF_LMESH | ETF_HEIGHTMAP | ETF_STRUCTURES | ETF_FRT
[never_inline]
def private wto_seg_hits_box_xz(p0, segDir : float3; segLen : float;
boxPos : float3; halfLen, halfWid, heightM : float) : bool
let rad = max(halfLen, halfWid) * 0.88
let center = boxPos + float3(0.0, heightM * 0.5, 0.0)
let rel = center - p0
let along = dot(rel, segDir)
if along < 0.25 || along > segLen - 0.25
return false
let closest = p0 + segDir * along
let dy = abs(closest.y - center.y)
if dy > heightM * 0.55 + 0.35
return false
let dx = closest.x - center.x
let dz = closest.z - center.z
return (dx * dx + dz * dz) <= rad * rad
[never_inline]
def public wto_sight_units_block_segment(world : WtoWorldSnap const&;
selfEid, targetEid : EntityId;
p0, segDir : float3; segLen : float) : int
for w in range(world.wreckCount)
assume wr = world.wrecks[w]
if wr.eid != selfEid && wr.eid != targetEid
if wto_seg_hits_box_xz(p0, segDir, segLen, wr.pos, wr.halfLen, wr.halfWid, 2.2)
return WTO_BLOCK_WRECK
for i in range(world.unitCount)
assume u = world.units[i]
if !u.isAlive || !u.isGround || u.eid == selfEid || u.eid == targetEid
continue
if wto_seg_hits_box_xz(p0, segDir, segLen, u.pos, u.halfLen, u.halfWid, 2.3)
return WTO_BLOCK_VEHICLE
return WTO_BLOCK_NONE
[never_inline]
def public wto_sight_hard_segment_blocked(world : WtoWorldSnap const&;
selfEid, targetEid : EntityId;
fromPos, toPos : float3;
sweepRadius : float; trimStartM, trimEndM : float) : int
let delta = toPos - fromPos
let fullLen = length(delta)
if fullLen <= trimStartM + trimEndM + 0.2
return WTO_BLOCK_NONE
let dir = delta / fullLen
var p0 = fromPos + dir * trimStartM
let traceLen = fullLen - trimStartM - trimEndM
if rayhit_normalized(p0, dir, traceLen, SIGHT_TERRAIN_MASK, PHYSMAT_INVALID)
return WTO_BLOCK_TERRAIN
if rayhit_normalized(p0, dir, traceLen, ETF_RI, PHYSMAT_INVALID)
return WTO_BLOCK_OBJECT
if rayhit_normalized(p0, dir, traceLen, ETF_RI_PHYS, PHYSMAT_INVALID)
return WTO_BLOCK_OBJECT
if sweepRadius > 0.02
var s1 = p0 + dir * traceLen
var queryOut = ShapeQueryOutput()
if sphere_cast(p0, s1, sweepRadius, queryOut)
return WTO_BLOCK_OBJECT
return wto_sight_units_block_segment(world, selfEid, targetEid, p0, dir, traceLen)
[never_inline]
def public wto_sight_visual_clear(world : WtoWorldSnap const&;
selfEid, targetEid : EntityId;
eyePos, targetPt : float3) : int
let delta = targetPt - eyePos
let dist = length(delta)
if dist <= 1.2
return WTO_BLOCK_NONE
let dir = delta / dist
let traceLen = max(0.4, dist - 1.1)
var p0 = eyePos
var p1 = targetPt
if rayhit_smoke_occluders(p0, p1)
return WTO_BLOCK_SMOKE
let aimMat = get_material_id("aimRay")
if rayhit_normalized(p0, dir, traceLen, ETF_ALL, aimMat)
return WTO_BLOCK_TERRAIN
if traceTransparencyRayRIGenNormalized(p0, dir, traceLen, WTO_AI_PERC_FOLIAGE_TRANS)
return WTO_BLOCK_FOLIAGE
return wto_sight_units_block_segment(world, selfEid, targetEid, p0, dir, traceLen)
[never_inline]
def public wto_sight_check_target_samples(world : WtoWorldSnap const&;
selfEid : EntityId; eyePos : float3;
tgt : WtoUnitSnap const&; maxSamples : int;
var outBestPt : float3&) : int
if tgt.isAir
outBestPt = tgt.pos
return wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, tgt.pos) == WTO_BLOCK_NONE ? 2 : 0
let fwd = wto_xz_normalize(tgt.hullFwd, float3(1.0, 0.0, 0.0))
let left = float3(-fwd.z, 0.0, fwd.x)
let sideOff = max(0.75, tgt.halfWid * 0.72)
var pts : float3[4]
pts[0] = tgt.pos + float3(0.0, 1.15, 0.0)
pts[1] = tgt.pos + float3(0.0, 1.95, 0.0)
pts[2] = tgt.pos + left * sideOff + float3(0.0, 1.25, 0.0)
pts[3] = tgt.pos - left * sideOff + float3(0.0, 1.25, 0.0)
let count = clamp(maxSamples, 1, 4)
var vis = 0
var picked = false
for s in range(count)
if wto_sight_visual_clear(world, selfEid, tgt.eid, eyePos, pts[s]) == WTO_BLOCK_NONE
if !picked
outBestPt = pts[s]
picked = true
vis++
return vis
+202
View File
@@ -0,0 +1,202 @@
// Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per
// spawned bot (`gamedata/units/<className>.blk`) to extract exact role, gun stabilizer,
// traverse limits, turret slew rates, shell muzzle velocity, and reverse speed capability.
options indenting = 2
options no_global_heap = true
module wto_ai_specs_common shared
require ecs
require app
require math
require strings
require DagorMath
require DagorDataBlock
require Unit
require IGroundModel
require HeavyVehicleModel
require Weapon
require %game.utils.utils_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common
[never_inline]
def private wto_parse_role_strings(unitType : string; expClass : string; isLightTag : bool) : int
if unitType == "typeSPAA" || expClass == "exp_SPAA"
return WTO_ROLE_SPAA
if unitType == "typeTankDestroyer" || expClass == "exp_tank_destroyer"
return WTO_ROLE_TD
if unitType == "typeHeavyTank" || expClass == "exp_heavy_tank"
return WTO_ROLE_HEAVY
if unitType == "typeLightTank" || isLightTag
return WTO_ROLE_LIGHT
return WTO_ROLE_MEDIUM
[never_inline]
def private wto_parse_turret_limits(turretBlk : DataBlock const?; var spec : WtoVehicleSpec&)
if turretBlk == null
return
let lim1 = *turretBlk |> datablock_getPoint4("lim1", float4(0.0, 0.0, 0.0, 0.0))
let lim2 = *turretBlk |> datablock_getPoint4("lim2", float4(0.0, 0.0, 0.0, 0.0))
var maxAbsYaw = 0.0
var minPitch = 0.0
var maxPitch = 0.0
if abs(lim1.x) > 0.1 || abs(lim1.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(lim1.x), abs(lim1.y)))
minPitch = min(minPitch, lim1.z)
maxPitch = max(maxPitch, lim1.w)
if abs(lim2.x) > 0.1 || abs(lim2.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(lim2.x), abs(lim2.y)))
minPitch = min(minPitch, lim2.z)
maxPitch = max(maxPitch, lim2.w)
let limitsBlk = *turretBlk |> datablock_get_block_by_name("limits")
if limitsBlk != null
let yawRange = *limitsBlk |> datablock_getPoint2("yaw", float2(0.0, 0.0))
let pitchRange = *limitsBlk |> datablock_getPoint2("pitch", float2(0.0, 0.0))
if abs(yawRange.x) > 0.1 || abs(yawRange.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(yawRange.x), abs(yawRange.y)))
if pitchRange.x < -0.1 || pitchRange.y > 0.1
minPitch = min(minPitch, pitchRange.x)
maxPitch = max(maxPitch, pitchRange.y)
if maxAbsYaw > 0.5
spec.yawLimitDeg = clamp(maxAbsYaw, 4.0, 180.0)
spec.isLimitedTraverse = spec.yawLimitDeg < 75.0
if minPitch < -0.5
spec.minPitchDeg = clamp(minPitch, -25.0, -2.0)
if maxPitch > 1.0
spec.maxPitchDeg = clamp(maxPitch, 8.0, 88.0)
[never_inline]
def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicleSpec&; isDefault : bool)
let spd = bBlk |> datablock_getReal("speed", 0.0)
if spd <= 80.0 || spd >= 2600.0
return
let cx = clamp(bBlk |> datablock_getReal("Cx", 0.35), 0.05, 1.5)
let mass = clamp(bBlk |> datablock_getReal("mass", 10.0), 0.05, 250.0)
let rawCal = bBlk |> datablock_getReal("ballisticCaliber", 0.0)
let cal = clamp(rawCal > 0.002 ? rawCal : bBlk |> datablock_getReal("caliber", 0.09), 0.005, 0.4)
if isDefault && spec.shellCount == 0
spec.muzzleSpeedMps = spd
spec.shellDragCx = cx
spec.shellMassKg = mass
spec.shellCaliberM = cal
let bName = bBlk |> datablock_getStr("bulletName", "")
if empty(bName) || spec.shellCount >= WTO_MAX_SHELL_PROFILES
return
let h = ecs_hash(bName)
for i in range(spec.shellCount)
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]
def private wto_parse_weapon_blk(weapBlkPath : string; var spec : WtoVehicleSpec&)
if empty(weapBlkPath) || find(weapBlkPath, "dummy_weapon") >= 0
return
datablock_load_cached(weapBlkPath, DataBlockReadFlag.ROBUST) <| $(wBlk)
let isRocket = wBlk |> datablock_getBool("rocketGun", false)
let isCannon = wBlk |> datablock_getBool("cannon", false)
let isBelt = wBlk |> datablock_getBool("isBulletBelt", false)
if isRocket && !isCannon
return
spec.isAutocannonBelt = isBelt
spec.shellCount = 0
datablock_for_each_block(wBlk, "bullet") <| $(bBlk)
wto_record_shell_block(bBlk, spec, true)
datablock_for_each_block(wBlk) <| $(subBlk)
datablock_for_each_block(subBlk, "bullet") <| $(bBlk)
wto_record_shell_block(bBlk, spec, false)
[never_inline]
def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : WtoVehicleSpec&) : bool
if empty(className)
return false
let relPath = find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk")
var loaded = false
datablock_load_cached(relPath, DataBlockReadFlag.ROBUST) <| $(mBlk)
if mBlk.paramCount == 0u && mBlk.blockCount == 0u
return
loaded = true
let uType = mBlk |> datablock_getStr("type", "")
let expCls = mBlk |> datablock_getStr("expClass", "")
spec.role = wto_parse_role_strings(uType, expCls, isLightTag)
let fwdKmh = mBlk |> datablock_getReal("maxFwdSpeed", 0.0)
let revKmh = mBlk |> datablock_getReal("maxRevSpeed", 0.0)
if fwdKmh > 5.0
spec.vMaxFwd = clamp(fwdKmh / 3.6, 4.0, 28.0)
if revKmh > 1.0
spec.vMaxRev = clamp(revKmh / 3.6, 1.0, 16.0)
let commonBlk = mBlk |> datablock_get_block_by_name("commonWeapons")
if commonBlk == null
return
var primaryParsed = false
datablock_for_each_block(*commonBlk, "Weapon") <| $(weapBlk)
if primaryParsed
return
let trig = weapBlk |> datablock_getStr("triggerGroup", "primary")
let wPath = weapBlk |> datablock_getStr("blk", "")
if trig != "primary" || empty(wPath) || find(wPath, "dummy_weapon") >= 0 || find(wPath, "machinegun") >= 0
return
primaryParsed = true
let sy = weapBlk |> datablock_getReal("speedYaw", 24.0)
let sp = weapBlk |> datablock_getReal("speedPitch", 8.0)
spec.turretYawSpd = clamp(sy, 4.0, 120.0)
spec.turretPitchSpd = clamp(sp, 2.0, 90.0)
let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer")
if stabBlk != null
spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false)
wto_parse_turret_limits(weapBlk |> datablock_get_block_by_name("turret"), spec)
wto_parse_weapon_blk(wPath, spec)
return loaded
[never_inline]
def private wto_apply_runtime_fallbacks(unit : Unit const?; gm : IGroundModel const?;
isLightTag : bool; blkLoaded : bool; var spec : WtoVehicleSpec&)
if gm != null
let box = gm.bodyBoundingBox
spec.halfLen = max(2.0, max(abs(box.boxMin.x), abs(box.boxMax.x)) + 0.15)
spec.halfWid = max(1.0, max(abs(box.boxMin.z), abs(box.boxMax.z)) + 0.18)
let hv = unit != null ? as_hv(unit) : null
if hv != null && hv.getMaxSpeed > 1.5 && wto_is_finite(hv.getMaxSpeed)
spec.vMaxFwd = min(spec.vMaxFwd, hv.getMaxSpeed)
if unit == null || unit.weap == null
return
var gunCount = 0
var launcherCount = 0
foreach_primary_gun(unit.weap.Weapons) <| $(weapon)
if weapon == null || weapon.isDummyGun
return
if weapon.prop.launcher
launcherCount++
elif as_gun(weapon) != null
gunCount++
spec.isPureLauncher = gunCount == 0 && launcherCount > 0
if length(unit.weap.turret) == 0 && gunCount > 0
spec.isLimitedTraverse = true
spec.yawLimitDeg = min(spec.yawLimitDeg, 12.0)
if !blkLoaded
if spec.isLimitedTraverse
spec.role = WTO_ROLE_TD
elif isLightTag
spec.role = WTO_ROLE_LIGHT
elif spec.vMaxFwd <= 10.5 && spec.halfLen >= 3.3
spec.role = WTO_ROLE_HEAVY
[never_inline]
def public wto_specs_load(eid : EntityId; className : string; unit : Unit const?;
gm : IGroundModel const?; var spec : WtoVehicleSpec&)
let isLightTag = has(eid, "unit_tag__light_vehicle")
let blkLoaded = wto_parse_unit_blk(className, isLightTag, spec)
wto_apply_runtime_fallbacks(unit, gm, isLightTag, blkLoaded, spec)
spec.ready = true
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more