38 Commits
Author SHA1 Message Date
N0VAN0M4LY a2867063e1 docs(release): add v0.1.6 notes 2026-12-06 21:20:52 +08:00
N0VAN0M4LY 887a8262db fix(ground-ai): restore engine audio for AI tanks
Confirm drive ownership through the LocalMP mission-action reply. Keep
stock driveToPos gated for slot bots and let the game manage
MoveSystem.inactive so it can start and stop their engine audio.

Verified root and launcher type checks, the native DLL build, compile-only
checks of the changed daScript functions, and the 2.61.0.64 game-copy
build. Executable patch checks and native module resolution passed on
2.61.0.37, 2.61.0.60, and 2.61.0.64. In-game audio and driving acceptance
are pending.
2026-12-06 21:02:33 +08:00
N0VAN0M4LY 036a479aab feat(launcher): add map adaptation pack updates 2026-12-06 19:53:45 +08:00
N0VAN0M4LY 9ba92f289d feat(ground-ai): scope custom ground AI to slot bots and PvE defenders
- Capture unit_mgr, agent_unit_idx, unit_count, and unit_array inside driveToPos::update (patches/native/local_mp_ground_ai.jsonc) so local_mp_ground_ai.c short-circuits stock movement only for MPlayer slot bots (userId < -1) and leaves non-MPlayer mission wave AI (such as Ground Assault enemy tanks) on stock mission control.
- Return customBots/wtoPveMode from wtoGroundAiScriptReady so ground AI scripts in Assault PvE take over only Team A friendly defenders (army 1) and synthesize a friendly defense anchor from the mission safe_zone area.

Verified: MSVC wto_ws.dll build (0 project warnings), .37 check-patches (14/14), .37/.64 native module resolution (18/18), and temporary game-copy build packing 55 ground AI modules; in-game acceptance pending.
2026-12-06 17:43:25 +08:00
N0VAN0M4LY aaae2e4187 feat(battle): wire Simulator EC/SP, Assault PvE, unlimited respawns, and RB/SB bombing zones
- Switch air_simulation_timeDelay_battles to the 15 stock air_i2m Enduring Confrontation missions with unlimited respawns and optionalTakeOff/allowEmptyTeams passthrough.
- Extract warpoints.blk respawn_points/TankSimulation (battle-spawn-rules v5) and enable Spawn Points in Ground Simulator using tuning/battle.jsonc simGroundInitialSpawnScore.
- Fix unlimited respawns for Nuclear Escalation, Air SB EC, and Assault PvE: send -1 for BotSystem numBotRespawns/numTankBotRespawns (verified at 2.61.0.37 0x11b27b1) and explicitly disable multiRespawn so maxRespawns < -1 does not activate Silver Lions respawn-cost gates (0x1268ab0).
- Enable bombing-zone score and reward pricing in Air Realistic (including sub-modes) and Air Simulator in addition to Air Arcade.
- Enable air_assault_pve and tank_assault_pve in BattleMatchmaker: extract PvE import rankRange windows (multiplayer-missions v6), filter by player mrank to prevent low-BR Fulda mismatches, lock local player to Team A, disable autoBalance, emit customBots/wtoPveMode=1, and read Assault team size and wave AI reward multiplier from tuning/.

Verified: root and launcher typecheck, stock .37 dataset/matchmaker/economy checks, and temporary game-copy build; in-game acceptance pending.
2026-12-06 17:43:25 +08:00
N0VAN0M4LY d73221092d chore(release): prepare launcher 0.1.6 2026-12-06 16:03:53 +08:00
N0VAN0M4LY b56c5eaf58 feat(ground-ai): build and load offline map navigation packs 2026-12-06 16:03:52 +08:00
N0VAN0M4LY 710c8ecaaa chore(repo): merge tank AI checkpoint for 0.1.6 2026-12-06 15:47:46 +08:00
N0VAN0M4LY b276e686b0 chore(ground-ai): checkpoint 3d replay and simulator work 2026-12-06 15:43:04 +08:00
N0VAN0M4LY 894dd0363d build(release)!: move publishing to Gitea and R2
Prepare signed Gitea releases with the VPS entry point and protect versioned R2 assets from replacement. Use the R2 release feed as the default update source.

Verified both type checks and the VPS and R2 release commands in help mode.

BREAKING CHANGE: The GitHub Actions release workflows have been removed. Run scripts/release-vps.ts from a checkout of the release tag on Gitea.
2026-12-06 15:34:24 +08:00
N0VAN0M4LY d58ba9fb9b feat(saves)!: add offline crew editing
Add per-country crew slot controls and skill level previews to the launcher. Keep archived crews and their stable IDs in the save, update affected lineups, and back up the save before closing a slot.

Verified with both type checks, the launcher build, 2.61.0.64 patch checks, and temporary save read and write checks.

BREAKING CHANGE: The launcher automatically upgrades existing saves to format 4. Keep a pre-upgrade backup to use a save with an older launcher.
2026-12-06 15:34:24 +08:00
N0VAN0M4LY f8bd79042b fix(ground-ai): command the turret servo with the wished angle
The turret command led the current yaw by one frame's traverse step, so
the stock servo crawled: the replay trace measured about 4 deg/s relative
to the hull while the barrel was more than 20 deg off, against a median
stock traverse of 24 deg/s. Bots kept their barrels on the hull and were
mostly denied by aim error at close range.

yawLim and pitchLim now carry the wished angles, clipped to the mount's
yaw arc and to the elevation sector the barrel is in. A full-traverse
command leads the turret by at most 90 deg so it always turns the short
way. Secondary mounts use the same command, and the unused frame time
argument of their aiming path is dropped.

In a lab battle the 90th percentile turret rate rose to 28 deg/s, the
median aim error to target fell from 15-22 deg to 2 deg, and moving
shots rose from under 20% to 49% of main gun shots.
2026-12-06 13:53:52 +08:00
N0VAN0M4LY 5786fee63b feat(ground-ai): add a replay trace and the AI lab viewer
Battle behaviour could only be judged by watching one bot at a time. The
AI now logs a replay trace and a local viewer plays it back on the map.

Game scripts:
- wto_ai_trace_common.das writes every diagnostics.traceIntervalSec the
  capture zones (WTO_AI|TRACE_CAP), every ground unit including players
  (TRACE_U) and each bot's decision state (TRACE_B: order, behavior,
  targets, what the turret looks at and why, barrel heading, fire denial,
  hit probability), plus part damage with its offender (HIT) and deaths
  (DEATH). It uses no engine module so a simulator can load it as is.
- The turret state records the reason and world direction of each look.
- New tuning diagnostics.trace and diagnostics.traceIntervalSec through
  server reader, patcher constants, launcher schema, fields and labels.

packages/ground-sim: readers for the baked .wtonav pack (mesh polygons,
cover points, tactical grid) and .pois.json, the trace parser and the
names of the logged codes.

apps/ai-lab: Vite viewer with a local API that lists nav packs and lab
logs and decrypts a chosen .clog with wtotools. It draws the nav mesh,
vehicles, barrels and wished turret directions, goals, target links,
shots, hits and deaths over a timeline, with per-bot strips for behavior,
fire denial and turret reason. Paths live in an untracked lab.local.json.
The lab has its own tsconfig and stays out of the root typecheck.

Root and launcher typechecks pass; the lab typechecks and replayed two
lab battles.
2026-12-06 13:53:52 +08:00
N0VAN0M4LY 0b841ce2a2 fix(ground-ai): follow up the Berlin decision layer review
The first battles with the single-vehicle decision layer showed bots
sensing from a stale turret direction, fixed mounts and elevation-limited
guns that never got the hull turned for them, and bots braking late for
vehicles and wrecks.

- Perception samples the live barrel before sensing; near, mid and sight
  arcs are all measured from the barrel, and visible near and mid contacts
  in the barrel's front half are ranked with the same danger model.
- The turret may swing to a contact before it is confirmed; the trigger
  still waits for visual confirmation.
- A short halt only brakes. A fixed mount beyond its yaw span
  (turret.fixedMountYawSpanDeg) asks the hull to turn; an elevation-limited
  gun asks for a hull turn only when the stock elevation table shows the
  turn opens a sector that reaches the target.
- Friendly and enemy vehicles and wrecks take part in front and rear
  dynamic braking; detours try the sides, then backing off.

Builds and loads on the 2.61.0.64 lab client; played in three lab battles
together with the replay trace.
2026-12-06 13:53:51 +08:00
N0VAN0M4LY 038d897b1e fix(launcher): translate ground AI tuning labels 2026-12-06 01:53:54 +08:00
N0VAN0M4LY ee7bb12092 fix(ground-ai): finish single-vehicle combat decisions
Check the live barrel trajectory against the exposed target and shorten
fire delays. Resolve automatic and secondary guns using stock weapon data.
Keep short halts and withdrawals coherent, follow the order while engaged,
and reverse on the route with direction-aware obstacle recovery.

Verified daScript loading and native AI script readiness in the guarded
2.61.0.64 lab client. Battle behavior requires manual acceptance.
2026-12-06 01:51:00 +08:00
N0VAN0M4LY ee360a5042 feat(ground-ai): add the hull decision channel
Score driving behaviors and reuse the existing action handlers. Face the
main threat and support reverse travel on the navigation corridor.
2026-12-06 01:11:55 +08:00
N0VAN0M4LY 4e658cae9c feat(ground-ai): add the trigger decision channel
Estimate hit probability and request movement speed from the weapon solution.
Use visible aim samples, stock shell penetration, and separate burst paths.
2026-12-06 01:11:55 +08:00
N0VAN0M4LY 1590a2fea9 feat(ground-ai): layered perception, threat table and turret channel
First step of the single-bot decision layer. Not yet checked in game:
the decision layer is coupled, so it is tested once its hull and fire
parts are in.

Perception is layered: the gun sight covers perception.gunFovHalfDeg
either side of the barrel; within nearAwareM the crew notices enemies
around the hull except a rear blind arc, which a periodic look-around
opens; within midAwareM the commander covers the hull's front half.
Near and mid layers take longer to see an enemy clearly. Each track
remembers when and where its enemy was last in sight.

Each bot keeps a threat table of the enemies it has discovered, rated
by distance, whether seen clearly, whether aiming at it or recently
hitting it, and whether it is in their sight. Penetration is left out
until the engine damage test is usable.

The turret no longer rests on the hull's front: without a clearly seen
target it looks at the most dangerous discovered threat, then the last
exit, the remembered target, cues, and otherwise sweeps across the
route. A threat clearly more dangerous than the engaged target takes
the turret first.

Bot slot bookkeeping moves out of the runtime entry into
wto_ai_slots_common.das, and battle statistics count an enemy as known
when it is in the threat table.

Tuning: perception gains nine settings and loses frontConeHalfDeg and
peripheralCloseM, tactics loses visionFovDeg and peripheralRangeM, and
the new threat and turret sections are wired through the server
reader, generated constants and launcher fields in both languages.
2026-12-06 00:03:55 +08:00
N0VAN0M4LY 4136021c8c feat(ground-ai): log battle statistics for comparing builds
The decision layer rework is judged against a baseline, so the
runtime now accumulates per vehicle role and logs WTO_AI|BATTLE_STATS
every diagnostics.statsLogIntervalSec and when the battle ends:

- time from acquiring a ground target to the first shot at it, and
  targets let go without a shot;
- time with a target in sight within range and the gun ready, split by
  the last reason a shot was refused (WTO_AI|BATTLE_STATS_FIRE);
- shots by distance band and how many were fired on the move, and the
  autocannon rate;
- every statsSampleSec, the nearest enemy in line of sight within
  statsSampleRangeM: whether the bot knows it, how far the turret is
  off it, and whether a tank or tank destroyer shows it its rear
  (statsRearArcDeg).

The five diagnostics settings go through the server reader, the
generated script constants and the launcher fields in both languages.
2026-12-05 22:49:31 +08:00
N0VAN0M4LY 264c5c59b8 fix(hud): filter ground part feedback by player
Check the intended recipient of ground part damage messages in the LocalMP proxy. Keep the firing player's slot available when the ground model sends damage feedback directly to the HUD.

Verified both TypeScript projects, the native DLL build, executable patch checks on .37, .60, and .64, and native patch resolution on .37, .58, .60, and .64. Built .37 and .64 copies and checked local service health on .64. In-game verification is pending.
2026-12-05 22:37:50 +08:00
N0VAN0M4LY 77e4806ffc merge: bring main into feat/tank-ai-nav
Takes main's mounted gun traverse limits, capture and hit feedback,
LocalMP air AI sync, mod tech tree insertions and launcher changes.

Conflicts resolved:
- wto_ai_runtime.das: fire update runs before navigation, as on main,
  so a hull-aim request is driven in the same frame; navigation keeps
  the navmesh state and slot arguments of this branch.
- wto_ai_nav_common.das: main's wto_try_hull_aim replaces the old
  limited-traverse pivot and uses this branch's drive command helper
  and stuck-watch reset.
- build.ps1 and local_mp_internal.h: keep both sides' sources and
  declarations.
2026-12-05 22:14:34 +08:00
N0VAN0M4LY 58fde2030c fix(ground-ai): escalate repeated contacts with vehicles and wrecks
A bot pressed against the same wreck or stopped vehicle backed off,
planned the same path again and drove into it once more, every few
seconds for minutes, because a contact reset the stuck watch and left
no trace for path searches.

A second contact within pathFollow.contactRepeatSec near the same
place now marks the body for path searches and switches the passing
side; after unstickMaxAttempts repeats the bot gives its order up and
the place is avoided like any other unreachable spot. NAV_CONTACT logs
the repeat count and the body position.
2026-12-05 22:12:37 +08:00
N0VAN0M4LY 413bd55c54 fix(ground-ai): spread team routes, pass vehicles and keep off deep water
First in-game run of the path follower on Berlin and Poland showed whole
teams queueing on one road, bots ramming stopped teammates and wrecks,
bots clipping building corners, bots sliding into the Poland river and
the same bot getting stuck at the same spot dozens of times.

Native engine (native/wto-nav):
- Team traffic: a bot's finished path counts for its team for
  trafficHoldSec; the team's later searches pay trafficCostPerPath more
  per counted path through a polygon (up to trafficCostMaxMul), so
  teammates spread over parallel routes. A slot's previous path stops
  counting when it asks for a new one.
- Path corners are moved up to cornerOffsetM away from the edge they
  turn around, when the mesh allows both legs; off-mesh link endpoints
  stay put.
- path_request takes the team; load_map takes the new settings;
  get_stats reports live traffic paths and moved corners.

Bake (tools/navgen):
- Water deeper than navBake.maxFordDepthM (0.9 m, was a fixed 0.6 m)
  is a wall before erosion, so walkable ground keeps the tier radius
  from it, plus deepWaterMarginM on banks lower than
  deepWaterBankHeightM above the water line. Quays and ramps above it
  keep only the radius. The preview marks deep water from the terrain.

Ground AI scripts:
- The lookahead point is pulled back along the path until the mesh
  allows the straight line to it, so corners are no longer cut through
  buildings.
- New traffic module replaces the fixed sideways step: hull length and
  width along the heading; stopped vehicles, wrecks and parked players
  are passed on the side with room, or the bot stops short and after
  blockWaitSec marks the spot and plans again; moving traffic ahead is
  followed; oncoming traffic is passed in the open and in narrow
  passages the bigger vehicle goes first. Wrecks carry their heading.
- A hull pressed against a vehicle or wreck backs off after
  contactReverseSec instead of the full stuck window.
- Jams and confirmed obstacles cost far more, and a given-up place is
  all but closed (giveUpRadiusM, giveUpCostMul), so replanning leaves
  instead of returning to it.

Tuning: navEngine trafficCostPerPath, trafficCostMaxMul, trafficHoldSec,
cornerOffsetM; pathFollow stationarySpeedMps, passMarginM, passSpeedMps,
blockWaitSec, blockTtlSec, contactGapM, contactReverseSec, giveUpRadiusM,
giveUpCostMul; avoidShiftM removed; jamCostMul 4 -> 12, rubbleCostMul
8 -> 25; navBake maxFordDepthM, deepWaterMarginM, deepWaterBankHeightM
(bake only). Launcher fields and en/zh-CN labels updated (978/978 keys).

Checked: root and launcher typecheck, MSVC build with no warnings in
project code, check-patches for 2.61.0.58 and 2.61.0.60, rebake of
avg_berlin, avg_poland and avg_hurtgen (all spawn-to-zone pairs still
connected on every tier), offline run on the new avg_poland pack (eight
same-team paths spread over different roads, traffic released after
the hold time, corners moved, pump within budget), isolated game copy
build. daScript compilation and in-battle behaviour still need the
in-game run.
2026-12-05 21:39:07 +08:00
N0VAN0M4LY 470fc3746d chore(docs):update readme 2026-12-05 20:06:00 +08:00
N0VAN0M4LY f86ab99c17 feat(mods): compose shared tech tree insertions
Accept manifest declarations for inserting vehicles into an existing research link. Compose shared links in mod load order after ordinary overlays and write matching shop and economy prerequisites. Validate anchors, rank order, and cycles, and document the manifest field.

Verified type checks, a 2.61.0.64 build with shared, folded, and cross-column insertions, load-order and disable readback, and the local server health endpoint. In-game acceptance remains pending.
2026-12-05 18:36:50 +08:00
N0VAN0M4LY 0843fde6ff fix(ground-ai): respect mounted gun traverse limits
Read the selected gun mount limits from the vehicle data and constrain its aiming commands. Send out-of-traverse aim requests to the chassis driver and require alignment before firing.

Verified type checks, executable patch checks and builds on 2.61.0.37 and 2.61.0.64, and guarded daScript initialization on 2.61.0.64. In-battle acceptance remains pending.
2026-12-05 18:36:19 +08:00
N0VAN0M4LY ba947fe5b6 feat(ground-ai): follow baked navmesh paths with sliced searches
Native engine (native/wto-nav):
- Path searches are queued per slot and advanced with Detour's sliced
  search inside a per-frame time budget (navEngine.pathBudgetMsPerFrame),
  so a 4 km search no longer stalls a frame. The synchronous find_path
  op is gone.
- The battle's pack is read on a background thread when the mission
  finishes loading (prefetch); load_map only takes the result.
- New mesh queries: probe (surface, flags, room to the mesh edge),
  raycast, nearest walkable point, and dynamic cost circles for wrecks,
  jams and fresh obstacles that later searches route around.

Ground AI scripts:
- route picks the mesh tier by vehicle width and the cost filter by
  tracked or wheeled, plans on goal change, drift off the corridor, a
  timer or reported obstacles, and falls back to the stock road mesh
  only when the battle decided on the fallback.
- follow steers at a speed-scaled lookahead point and brakes ahead of
  sharp corners, narrow passages and the destination.
- avoid casts rays from both front hull corners that drive through
  objects the bake marks crushable, follows slower traffic, steps aside
  or yields by size priority in narrow passages.
- unstick escalates deterministically: back up along the corridor, mark
  a jam and replan, then log the spot and hand the order back.
- Flank lanes are built through the queued searches; rallies are not
  released while their lanes are still being built.
- Removed the 9-arc forward probing, 7-arc reverse probing, 145 m
  straight shortcuts, 165 m snapping and random sideways detours.

Tuning: new pathFollow section, navEngine.goalSnapRadiusM and
pathBudgetMsPerFrame, navBake.crushableMaxRiExtraHp passed to the
scripts; retired navigation.cornerBrakeAccel, stuckWindowSec,
stuckMinMoveM and unstickReverseSec. Launcher fields and en/zh-CN labels
updated.

Checked: root and launcher typecheck, MSVC build with no warnings in
project code, check-patches for 2.61.0.58 and 2.61.0.60, offline engine
run on avg_poland (prefetch, sliced searches within budget, slot
replacement, dynamic costs), isolated game copy build. daScript
compilation and in-battle behaviour still need the in-game run.
2026-12-05 17:38:41 +08:00
N0VAN0M4LY 39a77c04cb fix(tools): register decrypt-clog command in wtotools cli
log_commands defined decrypt-clog but the cli entry point never registered it, so the command was rejected as an invalid choice. Verified by decrypting a lab .clog through python -m wtotools.cli.
2026-12-05 17:07:17 +08:00
N0VAN0M4LY e0a344708d feat(ground-ai): load baked navigation packs in battle
Statically link upstream Detour into wto_ws.dll with a navigation engine
(native/wto-nav) that loads one .wtonav pack per battle, reads the level
file's eVER fingerprint and answers path queries through a cost filter
that multiplies chokepoint polygons. Start and goal points that do not
sit on the ground are retried over the mesh's height range.

The ground AI script talks to it through call_mission_action("wtoNav")
with load_map, unload_map, find_path and get_stats. Requests are string
parameters; replies use the DataBlock setters local_mp_awards already
resolves, with coordinates as centimetre ints, so no new native site is
needed. The local server writes the battle level into customBots
wtoLevel, and the build writes the pack folder as nav.dir in wto_ws.cfg
(build-game-copy.ts --map-nav).

The first load_map of a battle decides it once: loaded, fallback to the
script's own navigation, or refused when navEngine.allowFallback is off,
in which case bots do not plan or drive. A fingerprint mismatch is
logged and the pack is still used. The script proves the round trip
with one path per team at battle start and logs query statistics.

Add the navEngine, navCostsTracked and navCostsWheeled tuning sections
through the server reader, generated daScript constants and the
launcher's bot tuning page in both languages.

Verified with root and launcher type checks, MSVC builds without
warnings in project code, check-patches 14/14 on 2.61.0.58 and
2.61.0.60, native module resolution 14/14 on 2.61.0.37, .58, .60 and
.64, a scratch game copy build packing 29 ground AI modules, and an
offline run of the engine: all three maps load with matching
fingerprints and every spawn-to-capture path on every tier succeeds.
2026-12-05 16:39:26 +08:00
N0VAN0M4LY 21ab1084a6 fix(navgen): bake crushable riExtra objects and true chokepoints
Read both damage tables in config/rendinst_dmg.blk. riExtra blocks are
named after each destructible object and often carry hp without a
destructionImpulse, so dry-stone and wooden fences, metal railings,
sandbags and car wrecks were baked as solid walls. Stock damage data now
decides before model-name guesses, with the impulse and hp limits in the
navBake tuning section.

Flag chokepoints on the eroded voxel field instead of per polygon. A span
is a chokepoint only when no passable span within reach has room for a
passage chokepointMaxWidthVehicles wide, so long polygons touching a wall
no longer mark open yards. Chokepoints become WTO_FLAG_CHOKEPOINT on all
three tiers and keep their surface area.

Let roads cover rough slopes, map Poland's concrete streets as road, and
add an extractor --report with ground material shares and per-object
classification. Previews draw short cover ticks and record 300 DPI.

Verified with Rust release and MSVC builds without warnings, TypeScript
checks, and rebakes of Berlin, Poland and Hurtgen on 2.61.0.58 with
15/15, 416/416 and 840/840 spawn-to-capture connectivity on every tier.
2026-12-05 12:42:40 +08:00
N0VAN0M4LY f932ef096f docs(repo): clarify single-player offline scope and no-multiplayer policy 2026-12-05 11:43:23 +08:00
N0VAN0M4LY d40623cd47 fix(battle): correct LocalMP capture and hit feedback
Credit completed zone captures to the units counted by the mission engine and send the local capture fact through the existing settlement flow. Filter hit markers and shell-change hints using the actual attacker and active view.

TypeScript checks and the MSVC build passed. Verified exe, Quirrel, and native patches on 2.61.0.37, 2.61.0.58, 2.61.0.60, and 2.61.0.64. Rebuilt the .58 and .64 copies and verified local service health on .58. In-game verification is pending.
2026-12-05 10:24:14 +08:00
N0VAN0M4LY ebc36aef99 chore(patches): record Steam 2.61.0.64 compatibility
Adaptation pack / release (push) Canceled after 0s
Record the verified executable, GUI and native patches for the Steam build. All patches apply, modified Quirrel scripts compile, and the patched copy builds with a healthy local server.
2026-12-05 09:53:30 +08:00
N0VAN0M4LY ed5296e0b8 fix(navgen): restore Berlin roads and terrain access
Retain road identity on narrow polygons, bake upward support faces on the verified fountain model, and attach directional Detour links for two dry canal-bank descents. Keep map-specific inputs in the Berlin tuning file and show both surfaces and links in the preview.

Verified three-tier bakes, platform approaches, and downhill and reverse route queries on 2.61.0.58.
2026-12-04 22:56:21 +08:00
N0VAN0M4LY 6f2d9f639b fix(navgen): qualify cover against source collision geometry
Recheck continuous hull cover at the final parking height and validate both corner approaches on the navigation mesh. Preserve terrain and driving collision for low stone fences while excluding their geometry from cover traces. Add a preview raster size option.

Verified with Rust and MSVC builds, TypeScript checks, and 300 dpi 8K bakes for Berlin, Poland, and Hurtgen.
2026-12-04 19:23:22 +08:00
N0VAN0M4LY 4191d59168 feat(navgen): bake road materials and directional cover
Decode LMp2 terrain materials and decals into navigable road areas. Preserve usable cover bearings and verify left and right corner approaches independently on the standard tank mesh.

Verified with Rust and MSVC builds, TypeScript checks, and offline baking on Berlin, Poland, and Hurtgen for 2.61.0.58.
2026-12-04 12:36:07 +08:00
N0VAN0M4LY 842ee23fa4 feat(ground-ai): add offline tank navmesh and cover baking prototype
Add Stage 0 offline map geometry extraction and Recast/Detour baking tools for ground AI navigation on feat/tank-ai-nav:

- Vendor upstream recastnavigation Recast and Detour sources (zlib license) under native/third_party/recastnavigation.
- Define shared .wtogeo and .wtonav binary layouts in native/wto-nav/wto_nav_format.h.
- Add mission-bounds.mts to collect union ground battle areas, spawns, and capture zones across mission templates.
- Add Rust extractor (tools/navgen/extract) using wt-unpack and config/rendinst_dmg.blk destructionImpulse thresholds to classify hard solids, bridges, crushable objects, and tree trunks in Dagor world space.
- Add multi-threaded MSVC C++ baker (tools/navgen/bake) producing 3 vehicle-width tiled Detour navmeshes, island pruning, dual-height voxel tank covers (full, hull-down, corner peek, retreat-verified), 8m tactical grids, and spawn-to-cap connectivity checks.
- Add zero-dependency PNG top-down preview renderer (tools/navgen/render-preview.py).

Verified: Rust release build (0 warnings), MSVC x64 baker build (0 warnings), root typecheck, and end-to-end extraction/baking/100% 3-tier connectivity and preview rendering on avg_berlin, avg_poland, and avg_hurtgen (2.61.0.58).
2026-12-04 11:33:32 +08:00
263 changed files with 40412 additions and 2400 deletions

No files matched your search

+61
View File
@@ -0,0 +1,61 @@
## 简体中文
V0.1.6 改进了陆战 AI 的驾驶和交战,加入空战全真无间断作战、陆战全真和空陆守卫模式。启动器新增乘员组编辑和独立的地图适配包更新入口。
### 陆战 AI 与地图适配包
- AI **按车宽选择行驶路线**,同队坦克尽量分路推进。遇到停着的车辆或残骸时会尝试绕行,反复受阻时会后退并重新规划路线。
- AI **记住敌人上次出现的位置**,优先盯住近处或正在攻击自己的威胁。射击时综合考虑视线、炮口方向和命中机会,必要时减速、短停或转动车体。固定主炮也会借助车体转向进入射界。
- **首个地图适配包** `2026.12.06` 基于 Steam `2.61.0.64` 制作,覆盖 57 张陆战地图,下载约 541 MB。地图包单独分发,发布后可在启动器「关于 → 地图适配包」检查更新并安装。缺少对应地图数据时默认沿用原版寻路。
### 对局与结算
- **空战全真**采用 15 个原版无间断作战(EC)任务,支持无限重生。**陆战全真**使用出生点数(SP)出击。
- **空战和陆战守卫**可进入离线对局,按编队权重选择任务。陆战守卫的敌方进攻波次由原版任务 AI 控制,友方守卫使用新版 AI。
- 修复核战冲突等无限重生模式的 AI 重生规则,以及玩家无限重生时被误要求支付银狮的问题。
- 空战历史和全真中的敌方小基地伤害与摧毁现在计入个人分和战果收益。陆战占点给实际参与完成占领的玩家计分,并纳入银狮和研发点结算。
- 修复陆战命中标记、换弹种提示和右侧部件受损提示混入与玩家无关的事件。修复自定义陆战 AI 坦克行驶时缺少发动机声的问题。
### 启动器与模组
- 游戏退出后,可在「存档 → 乘员组」按国家开放、关闭或重新开放槽位,按兵种预览并调整技能等级。关闭前会自动备份,重新开放时可恢复该组的技能、训练和专精。
- 多个模组现在可在同一段科技树研发线上插入载具。启动器按模组加载顺序串接,并同步显示的连线与实际研发前置条件。
### 下载与兼容性
- **安装版** `wtoffline-launcher-0.1.6-win-x64.exe` 可覆盖安装。**便携版** `wtoffline-launcher-0.1.6-win-x64-portable.zip` 解压后即可使用。
- 已登记核对的客户端版本为 `2.61.0.37`、`2.61.0.43`、`2.61.0.55`、`2.61.0.58` 和 `2.61.0.64`。建议使用 `2.61.0.64` 搭配首个地图适配包。
- 此版本会自动把旧存档升级到格式 4。如需继续用旧版启动器,请保留升级前的存档备份。
- 首批地图的寻路已通过加载检查,部分路线仍需局内复核。全真、守卫、乘员组和发动机声修复仍待实机验收。
---
## English
V0.1.6 improves ground AI driving and combat, adds Air Simulator Enduring Confrontation, Ground Simulator and Air and Ground Assault, and gives the launcher a crew editor and a separate map pack updater.
### Ground AI and map packs
- **Driving and detours** use routes that fit each vehicle's width. Bots on the same team spread out where possible. They try to go around stopped vehicles and wrecks, and back up and replan after repeated blockages.
- **Spotting, aiming and firing** account for the last place a target was seen, nearby threats and incoming fire. Bots consider visibility, gun alignment and the chance of hitting. They can slow down, stop briefly or turn the hull, including to bring fixed guns on target.
- **The first map pack** (`2026.12.06`) covers 57 ground maps from Steam client `2.61.0.64` and is about 541 MB to download. The launcher lists it separately under **About → Map Adaptation Pack** when it is available. By default, battles use stock pathfinding when a map has no pack data.
### Battles and rewards
- **Air Simulator** uses 15 stock Enduring Confrontation missions with unlimited respawns. **Ground Simulator** uses Spawn Points.
- **Air and Ground Assault** can be played offline, with missions selected for the lineup's battle rating. In Ground Assault, stock mission AI controls the attacking waves and the new ground AI controls friendly defenders.
- Fixed bot respawns in unlimited-respawn modes such as Nuclear Escalation and removed unintended Silver Lion respawn charges in those modes.
- Damaging and destroying enemy mini-bases in Air Realistic and Simulator now counts toward personal score and battle rewards. Players who complete a ground capture receive score and credit toward Silver Lion and research rewards.
- Fixed ground hit markers, shell-change prompts and part-damage notices showing events unrelated to the player. Restored engine sound for ground AI tanks under custom driving control.
### Launcher and mods
- With the game closed, use **Saves → Crews** to open, close or reopen crew slots by nation, and preview and adjust skill levels by vehicle type. Closing a slot creates a backup. Reopening can restore its skills, training and qualifications.
- Multiple mods can insert vehicles into the same tech-tree link. The launcher composes the additions in mod load order and updates both the visible links and the research prerequisites.
### Downloads and compatibility
- **Installer** `wtoffline-launcher-0.1.6-win-x64.exe` can be installed over a previous version. **Portable** `wtoffline-launcher-0.1.6-win-x64-portable.zip` runs after extraction.
- Recorded client versions are `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, `2.61.0.58` and `2.61.0.64`. We recommend `2.61.0.64` with the first map pack.
- Existing saves upgrade automatically to format 4. Keep a pre-upgrade backup if you need to use an older launcher.
- The first set of maps passed loading checks. Some routes still need in-game checks, along with Simulator and Assault modes, the crew editor, and the engine audio fix.
-97
View File
@@ -1,97 +0,0 @@
# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release
# tagged v<version>. The launcher's update check reads v<version> releases and expects the three
# signed files (installer, manifest, signature); a release missing any of them breaks the check
# for already-installed launchers. The workflow also packages and signs the portable zip with its
# own manifest and signature so portable installations can update in place.
#
# Start it either way:
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
# branch's latest commit.
# The release note comes from .github/release-notes/v<version>.md. The signing key comes from the
# repository secret PATCH_SIGNING_KEY (the same Ed25519 key used for adaptation packs).
name: Launcher release
on:
push:
tags: ['v*']
workflow_dispatch:
inputs:
version:
description: 'Launcher version, e.g. 0.1.0 (must match apps/launcher/package.json)'
required: true
type: string
draft:
description: 'Keep the release as a draft for editing before publication'
type: boolean
default: true
permissions:
contents: write
jobs:
release:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- name: Install dependencies
run: npm ci
- name: Download the Electron runtime
run: node node_modules/electron/install.js
- name: Resolve and verify the version
run: |
if [ "${{ github.event_name }}" = 'workflow_dispatch' ]; then
VERSION="${{ inputs.version }}"
else
VERSION="${GITHUB_REF_NAME#v}"
fi
PKG_VERSION=$(node -p "require('./apps/launcher/package.json').version")
if [ "$VERSION" != "$PKG_VERSION" ]; then
echo "Version $VERSION does not match apps/launcher/package.json ($PKG_VERSION)" >&2
exit 1
fi
echo "VERSION=$VERSION" >> "$GITHUB_ENV"
- name: Typecheck
run: |
npm run typecheck
npm run typecheck --workspace "@wto/launcher"
- name: Build and package the Windows installer and portable archive
run: npm --workspace "@wto/launcher" run package:win
- name: Sign the release
env:
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
run: node scripts/sign-launcher-release.ts
- name: Create the release
env:
GH_TOKEN: ${{ github.token }}
run: |
flags=(--draft)
if [ "${{ github.event_name }}" = 'workflow_dispatch' ] && [ "${{ inputs.draft }}" = 'false' ]; then
flags=()
fi
gh release create "v$VERSION" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.exe" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json.sig" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.zip" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json.sig" \
"${flags[@]}" \
--title "WTOffline Launcher $VERSION" \
--notes-file ".github/release-notes/v$VERSION.md" \
--target "$GITHUB_SHA"
-78
View File
@@ -1,78 +0,0 @@
# Release an adaptation pack (packages/patcher/src/patch-pack/): pack and sign patches/ and publish
# it as a GitHub prerelease tagged patches-<version>, where the launcher looks for it.
#
# Start it either way:
# - push a tag: git tag patches-2026.11.29 && git push origin patches-2026.11.29
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
# branch's latest commit.
# The signing key comes from the repository secret PATCH_SIGNING_KEY
# (scripts/generate-patch-signing-key.ts).
name: Adaptation pack
on:
push:
tags: ['patches-*']
workflow_dispatch:
inputs:
version:
description: 'Pack version, YYYY.MM.DD or YYYY.MM.DD.N'
required: true
type: string
draft:
description: 'Keep the signed prerelease as a draft for editing before publication'
type: boolean
default: false
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
env:
# Packing needs no Electron binary.
ELECTRON_SKIP_BINARY_DOWNLOAD: '1'
VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || '' }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci
- name: Pack and sign
env:
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
run: |
if [ -n "$VERSION" ]; then
node scripts/build-patch-pack.ts --version "$VERSION" --out dist
else
# The version comes from the pushed tag (GITHUB_REF_NAME).
node scripts/build-patch-pack.ts --out dist
fi
- name: Create the prerelease
env:
GH_TOKEN: ${{ github.token }}
DRAFT: ${{ inputs.draft || false }}
run: |
manifest=$(ls dist/*.manifest.json)
field() { node -e "const m=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));const v=m[process.argv[2]];process.stdout.write(Array.isArray(v)?v.join(', '):String(v))" "$manifest" "$1"; }
version=$(field version)
printf 'Adaptation pack %s.\n\nChecked game versions: %s\nNeeds offline version %s or newer.\n' \
"$version" "$(field game_versions)" "$(field min_app_version)" > dist/notes.md
release_flags=(--prerelease)
if [ "$DRAFT" = 'true' ]; then
release_flags+=(--draft)
fi
gh release create "patches-$version" \
"dist/wtoffline-patches-$version.zip" \
"dist/wtoffline-patches-$version.zip.sig" \
"dist/wtoffline-patches-$version.manifest.json" \
"${release_flags[@]}" \
--title "Adaptation pack $version" \
--notes-file dist/notes.md \
--target "$GITHUB_SHA"
+1
View File
@@ -18,6 +18,7 @@ aces*.exe
/apps/launcher/out/
**/dist/
**/unpacked/
tools/navgen/extract/target/
# Node
node_modules/
+8 -4
View File
@@ -8,6 +8,8 @@
WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线项目。本地服务器模拟 Gaijin 的线上服务,客户端的所有请求都发到本机。客户端照常登录、读取档案、进入机库、提交玩家操作,游戏规则、存档和对局结算都在本地服务器上完成,对手和队友全部是 AI。
> **项目定位**:WTOffline 是为了方便玩家离线游玩的**单机**《战争雷霆》项目。为保持项目边界清晰、避免争议,项目组**不会提供也不会制作包括局域网联机在内的任何形式联机功能**。
仓库只包含源码和补丁定义,不包含任何游戏文件。构建时从玩家本机的原版安装读取文件,生成一份独立的游戏副本。
## 状态
@@ -41,7 +43,7 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
| 战后 | 结算页、战斗历史、个人统计、战斗奖章、加成道具与合同结算、修理费与自动修理 |
| 回放 | 录制与回放,回放中切换到 AI 视角 |
尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。好友、组队等多人社交功能不适用,只保证界面不报错。
尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。本项目仅面向单人离线游玩,不制作包括局域网联机在内的任何联机功能;好友、组队等多人社交功能不适用,只保证界面不报错。
AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不足。
@@ -261,7 +263,7 @@ tools/ wtotools,补丁检查工具(Python)
## 声明
本项目是同人爱好项目,与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。
本项目是面向单人离线游玩的非商业同人爱好项目,项目组不会主动制作包括局域网联机在内的任何联机功能。本项目与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。
---
@@ -273,6 +275,8 @@ tools/ wtotools,补丁检查工具(Python)
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
> **Project scope**: WTOffline is a **single-player offline** War Thunder project built to make offline play convenient for players. The project team **will not develop or provided any kind of multiplayer or networking features, including LAN multiplayer**.
The repository contains source code and patch definitions only. It does not contain any game files. The build reads files from the player's own installation and produces a separate game copy.
## Status
@@ -306,7 +310,7 @@ Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general d
| After battle | Debriefing, battle history, personal statistics, battle awards, booster and contract settlement, repair costs and auto-repair |
| Replays | Recording and playback, switching to AI vehicles during playback |
Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. Social multiplayer features such as friends and squads do not apply; the interface is only kept from breaking.
Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. This project is strictly for single-player offline play and will not develop any multiplayer features (including LAN multiplayer); social multiplayer features such as friends and squads do not apply and are only kept from breaking the interface.
AI driving, pathfinding, and tactics come from the game's built-in AI and still have clear shortcomings.
@@ -526,4 +530,4 @@ This project is released under the [GNU Affero General Public License v3.0](LICE
## Disclaimer
This is a non-commercial fan project. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client.
This is a non-commercial fan project built strictly for single-player offline play; the project team will not actively develop any multiplayer features, including LAN multiplayer. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client.
+2
View File
@@ -0,0 +1,2 @@
lab.local.json
.cache/
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WTOffline AI Lab</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
{
"mapsDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/maps",
"geoDir": "J:/GAME/WTOfflineProject-tank-ai/build/nav-stage2-fix/work",
"logsDir": "J:/GAME/WTLab/client-2.61.0.58/.game_logs",
"python": "J:/GAME/WTOfflineProject/.venv/Scripts/python.exe"
}
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@wto/ai-lab",
"version": "0.1.0",
"private": true,
"description": "Ground AI lab: replay viewer for battle traces and simulator runs.",
"type": "module",
"scripts": {
"dev": "vite",
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"@wto/ground-sim": "*",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"three": "^0.187.0"
},
"devDependencies": {
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/three": "^0.187.0",
"@vitejs/plugin-react": "^5.2.0",
"vite": "^7.3.6"
}
}
+147
View File
@@ -0,0 +1,147 @@
/**
* Dev-server API of the AI lab (local only):
* GET /api/maps levels that have a navigation pack in mapsDir
* GET /api/maps/file?name= a pack or POI file of mapsDir
* GET /api/logs game logs (.clog) in logsDir, newest first
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
* GET /api/scene?name= the 3D map (.wtoscene) of a level, built from its .wtogeo in geoDir
* (cached until the geometry changes)
* Paths come from lab.local.json next to this app (see lab.local.example.json).
*/
import { execFile } from 'node:child_process';
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import type { ServerResponse } from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildMapScene, encodeMapScene, readGeo } from '@wto/ground-sim';
import type { Connect, Plugin } from 'vite';
interface LabConfig {
readonly mapsDir: string;
/** Where the navigation bake left the levels' .wtogeo geometry. */
readonly geoDir: string;
readonly logsDir: string;
readonly python: string;
}
const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CACHE_DIR = path.join(APP_DIR, '.cache');
const SAFE_NAME = /^[\w.-]+$/;
function loadConfig(): LabConfig {
const file = path.join(APP_DIR, 'lab.local.json');
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps'));
return {
mapsDir,
geoDir: str('geoDir', path.join(mapsDir, '..', 'work')),
logsDir: str('logsDir', ''),
python: str('python', 'python'),
};
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(body));
}
function sendFile(res: ServerResponse, file: string, type: string): void {
res.statusCode = 200;
res.setHeader('Content-Type', type);
createReadStream(file).pipe(res);
}
function listMaps(cfg: LabConfig): { level: string; pois: boolean; scene: boolean }[] {
if (!existsSync(cfg.mapsDir)) return [];
return readdirSync(cfg.mapsDir)
.filter((f) => f.endsWith('.wtonav'))
.map((f) => {
const level = f.slice(0, -'.wtonav'.length);
return {
level,
pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)),
scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)),
};
});
}
function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] {
if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return [];
return readdirSync(cfg.logsDir)
.filter((f) => f.endsWith('.clog'))
.map((name) => {
const st = statSync(path.join(cfg.logsDir, name));
return { name, size: st.size, mtime: st.mtimeMs };
})
.sort((a, b) => b.mtime - a.mtime);
}
/** Decrypts `name` into the cache unless the cached text is newer than the log. */
function decryptLog(cfg: LabConfig, name: string): Promise<string> {
const source = path.join(cfg.logsDir, name);
const out = path.join(CACHE_DIR, `${name}.txt`);
mkdirSync(CACHE_DIR, { recursive: true });
if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out);
return new Promise((resolve, reject) => {
execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => {
if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`));
else resolve(out);
});
});
}
/** Builds the level's 3D map into the cache unless the cached one is newer than its geometry. */
function sceneFile(cfg: LabConfig, level: string): string | undefined {
const geo = path.join(cfg.geoDir, `${level}.wtogeo`);
if (!existsSync(geo)) return undefined;
const out = path.join(CACHE_DIR, `${level}.wtoscene`);
if (existsSync(out) && statSync(out).mtimeMs >= statSync(geo).mtimeMs) return out;
mkdirSync(CACHE_DIR, { recursive: true });
writeFileSync(out, encodeMapScene(buildMapScene(readGeo(readFileSync(geo)))));
return out;
}
async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise<boolean> {
const name = url.searchParams.get('name') ?? '';
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
const known = ['/api/maps/file', '/api/logs/text', '/api/scene'];
if (!known.includes(url.pathname)) return false;
if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; }
if (url.pathname === '/api/scene') {
const file = sceneFile(cfg, name);
if (file === undefined) sendJson(res, 404, { error: `no ${name}.wtogeo in ${cfg.geoDir}` });
else sendFile(res, file, 'application/octet-stream');
return true;
}
if (url.pathname === '/api/maps/file') {
const file = path.join(cfg.mapsDir, name);
if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` });
else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream');
return true;
}
if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) {
sendJson(res, 404, { error: `no log ${name}` });
return true;
}
sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8');
return true;
}
export function labApi(): Plugin {
return {
name: 'wto-ai-lab-api',
configureServer(server) {
const middleware: Connect.NextHandleFunction = (req, res, next) => {
const url = new URL(req.url ?? '/', 'http://localhost');
if (!url.pathname.startsWith('/api/')) { next(); return; }
handle(loadConfig(), url, res)
.then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); })
.catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }));
};
server.middlewares.use(middleware);
},
};
}
+144
View File
@@ -0,0 +1,144 @@
/** AI lab replay viewer: pick a game log, a battle in it, and play it back on the map. */
import type { TraceBattle } from '@wto/ground-sim';
import { useEffect, useMemo, useState } from 'react';
import { fetchLogs, fetchMaps, loadLog, loadMap, type LogEntry, type MapData, type MapEntry } from './data.ts';
import { sceneAt } from './frames.ts';
import { Inspector } from './Inspector.tsx';
import { Map3D, type MapLook } from './Map3D.tsx';
import { buildMapLayer } from './mapLayer.ts';
import type { ViewMode } from './three/cameraRig.ts';
import type { Layers } from './three/overlays.ts';
import { Timeline } from './Timeline.tsx';
const LAYER_LABELS: Readonly<Record<keyof Layers, string>> = {
goals: '目标点', links: '目标连线', cones: '炮塔视野', labels: '标签', events: '开火与受击',
};
const VIEW_LABELS: Readonly<Record<ViewMode, string>> = { top: '俯视', free: '自由', follow: '跟随选中车', gun: '炮口视角' };
function logLabel(l: LogEntry): string {
const when = new Date(l.mtime).toLocaleString();
return `${l.name}(${(l.size / 1e6).toFixed(1)} MB,${when})`;
}
export function App(): React.JSX.Element {
const [maps, setMaps] = useState<MapEntry[]>([]);
const [logs, setLogs] = useState<LogEntry[]>([]);
const [logName, setLogName] = useState('');
const [battles, setBattles] = useState<TraceBattle[]>([]);
const [battleIdx, setBattleIdx] = useState(0);
const [mapData, setMapData] = useState<MapData | undefined>(undefined);
const [exposure, setExposure] = useState(false);
const [covers, setCovers] = useState(false);
const [look, setLook] = useState<MapLook>({ view: 'top', navImage: true, objects: true, crushable: true });
const [layers, setLayers] = useState<Layers>({ goals: true, links: true, cones: false, labels: false, events: true });
const [t, setT] = useState(0);
const [playing, setPlaying] = useState(false);
const [speed, setSpeed] = useState(4);
const [selected, setSelected] = useState<string | undefined>(undefined);
const [status, setStatus] = useState('');
const refreshLogs = (): void => { fetchLogs().then(setLogs).catch((e: unknown) => setStatus(String(e))); };
useEffect(() => {
fetchMaps().then(setMaps).catch((e: unknown) => setStatus(String(e)));
refreshLogs();
}, []);
const openLog = (name: string): void => {
setLogName(name);
setPlaying(false);
setStatus('正在解密和读取日志…');
loadLog(name).then((list) => {
setBattles(list);
// The longest battle that has bots in its trace; a battle left right after loading has none.
let pick = list.length - 1;
let best = 0;
list.forEach((b, i) => {
const withBots = b.frames.filter((f) => f.bots.size > 0).length;
if (withBots > best) { best = withBots; pick = i; }
});
setBattleIdx(Math.max(0, pick));
setStatus(list.length === 0 ? '这份日志里没有对局。' : '');
}).catch((e: unknown) => setStatus(String(e)));
};
const battle = battles[battleIdx];
const level = battle?.level;
useEffect(() => {
setT(battle?.startT ?? 0);
setSelected(undefined);
}, [battle]);
useEffect(() => {
const entry = maps.find((m) => m.level === level);
setMapData(undefined);
if (entry === undefined) return;
loadMap(entry).then(setMapData).catch((e: unknown) => setStatus(String(e)));
}, [level, maps]);
const mapLayer = useMemo(
() => (mapData === undefined ? undefined : buildMapLayer(mapData.pack, { tier: 1, exposure, covers })),
[mapData, exposure, covers],
);
useEffect(() => {
if (!playing || battle === undefined) return;
let last = performance.now();
let handle = requestAnimationFrame(function step(now) {
const dt = (now - last) / 1000;
last = now;
setT((cur) => {
const next = cur + dt * speed;
if (next >= battle.endT) { setPlaying(false); return battle.endT; }
return next;
});
handle = requestAnimationFrame(step);
});
return () => cancelAnimationFrame(handle);
}, [playing, speed, battle]);
const scene = useMemo(() => (battle === undefined ? undefined : sceneAt(battle, t)), [battle, t]);
return (
<div className="app">
<header>
<select value={logName} onChange={(e) => openLog(e.target.value)}>
<option value="">选择游戏日志…</option>
{logs.map((l) => <option key={l.name} value={l.name}>{logLabel(l)}</option>)}
</select>
<button type="button" onClick={refreshLogs}>刷新</button>
{battles.length > 1 && (
<select value={battleIdx} onChange={(e) => setBattleIdx(Number(e.target.value))}>
{battles.map((b, i) => (
<option key={i} value={i}>{`第 ${i + 1} 局 ${b.level ?? '未知地图'}(${b.frames.length} 帧)`}</option>
))}
</select>
)}
{(Object.keys(LAYER_LABELS) as (keyof Layers)[]).map((k) => (
<label key={k}>
<input type="checkbox" checked={layers[k]} onChange={(e) => setLayers({ ...layers, [k]: e.target.checked })} />
{LAYER_LABELS[k]}
</label>
))}
<select value={look.view} onChange={(e) => setLook({ ...look, view: e.target.value as ViewMode })}>
{(Object.keys(VIEW_LABELS) as ViewMode[]).map((v) => <option key={v} value={v}>{VIEW_LABELS[v]}</option>)}
</select>
<label><input type="checkbox" checked={look.navImage} onChange={(e) => setLook({ ...look, navImage: e.target.checked })} />导航网格</label>
<label><input type="checkbox" checked={look.objects} onChange={(e) => setLook({ ...look, objects: e.target.checked })} />物体</label>
<label><input type="checkbox" checked={look.crushable} onChange={(e) => setLook({ ...look, crushable: e.target.checked })} />可碾压物</label>
<label><input type="checkbox" checked={exposure} onChange={(e) => setExposure(e.target.checked)} />暴露度</label>
<label><input type="checkbox" checked={covers} onChange={(e) => setCovers(e.target.checked)} />掩体点</label>
{status !== '' && <span className="status">{status}</span>}
{battle !== undefined && battle.frames.length === 0 && <span className="status">这一局没有轨迹(游戏里没开 diagnostics.trace)。</span>}
</header>
<main>
<Map3D mapScene={mapData?.scene} nav={mapLayer} battle={battle} scene={scene} selected={selected}
layers={layers} look={look} onSelect={setSelected} />
{battle !== undefined && <Inspector battle={battle} scene={scene} selected={selected} />}
</main>
{battle !== undefined && (
<Timeline battle={battle} t={t} playing={playing} speed={speed} selected={selected}
onSeek={setT} onPlaying={setPlaying} onSpeed={setSpeed} />
)}
</div>
);
}
+94
View File
@@ -0,0 +1,94 @@
/** Details of the selected vehicle at the current time, its recent log events, and the legends. */
import type { TraceBattle, TraceEvent } from '@wto/ground-sim';
import { eventsBetween, type SceneAt } from './frames.ts';
import {
BEHAVIOR_COLORS, BEHAVIOR_ZH, CLASS_ZH, COMMAND_ZH, DENY_COLORS, DENY_ZH, LANE_ZH, LOOK_COLORS, LOOK_ZH,
STATE_ZH, URGENCY_ZH, zh,
} from './labels.ts';
interface Props {
readonly battle: TraceBattle;
readonly scene: SceneAt | undefined;
readonly selected: string | undefined;
}
const RECENT_SEC = 20;
function angleDiff(a: number, b: number): number {
return Math.abs(((((a - b) % 360) + 540) % 360) - 180);
}
function involves(e: TraceEvent, eid: string): boolean {
return e.eid === eid || e.fields['tgt'] === eid || e.fields['off'] === eid || e.fields['target'] === eid;
}
function eventText(e: TraceEvent): string {
return Object.entries(e.fields)
.filter(([k]) => k !== 't' && k !== 'eid')
.map(([k, v]) => `${k}=${v}`)
.join(' ');
}
function Legend({ names, colors }: { names: readonly string[]; colors: readonly string[] }): React.JSX.Element {
return (
<div className="legend">
{names.map((n, i) => (
<span key={n}><i style={{ background: colors[i] ?? '#444' }} />{n}</span>
))}
</div>
);
}
function Row({ k, v }: { k: string; v: string }): React.JSX.Element {
return <tr><th>{k}</th><td>{v}</td></tr>;
}
export function Inspector({ battle, scene, selected }: Props): React.JSX.Element {
const u = selected !== undefined ? scene?.units.get(selected) : undefined;
const b = u?.bot;
const recent = selected !== undefined && scene !== undefined
? eventsBetween(battle, scene.t - RECENT_SEC, scene.t).filter((e) => involves(e, selected)).reverse()
: [];
return (
<aside className="inspector">
{u === undefined && <p className="hint">点击地图上的车辆查看详情。白框是玩家,黄色虚线是炮塔想看的方向,白线是实际炮管。</p>}
{u !== undefined && (
<table>
<tbody>
<Row k="编号" v={`${u.unit.eid}(${u.unit.army} 队,${u.unit.human ? '玩家' : u.unit.bot ? 'AI' : '原版 AI'})`} />
<Row k="存活" v={u.unit.alive ? '是' : '否'} />
<Row k="车速" v={`${u.unit.speed.toFixed(1)} m/s`} />
{b !== undefined && <>
<Row k="车型" v={zh(CLASS_ZH, b.vehicleClass)} />
<Row k="任务" v={b.hasOrder ? `${zh(COMMAND_ZH, b.command)},紧迫度${zh(URGENCY_ZH, b.urgency)},点 ${b.capIdx},${zh(LANE_ZH, b.lane)}` : '无'} />
<Row k="行为" v={`${zh(BEHAVIOR_ZH, b.behavior)}(分数 ${b.behaviorScore.toFixed(2)})`} />
<Row k="状态" v={zh(STATE_ZH, b.state)} />
<Row k="车速 期望/实际" v={`${b.wantSpeed.toFixed(1)} / ${b.forwardSpeed.toFixed(1)} m/s${b.reverseTravel ? ',倒车跟路' : ''}`} />
<Row k="感知目标" v={b.target === '0' ? '无' : `${b.target}${b.targetInSight ? '(可见)' : '(不可见)'}`} />
<Row k="威胁表" v={`${b.threatCount} 项,最高 ${b.topThreat},最高可见 ${b.topVisibleThreat}`} />
<Row k="炮塔依据" v={`${zh(LOOK_ZH, b.lookReason)}${b.lookAt !== '0' ? ` → ${b.lookAt}` : ''}`} />
<Row k="炮塔偏差" v={b.gunYaw === undefined ? '—' : `离想看的方向 ${angleDiff(b.gunYaw, b.wishYaw).toFixed(0)}°,离车头 ${angleDiff(b.gunYaw, u.yaw).toFixed(0)}°`} />
<Row k="主炮" v={b.reloading ? '装填中' : b.gunReady ? '就绪' : '未就绪'} />
<Row k="开火判定" v={`${zh(DENY_ZH, b.deny)},命中概率 ${(b.hitProb * 100).toFixed(0)}% / 门槛 ${(b.threshold * 100).toFixed(0)}%`} />
<Row k="扳机要求车速" v={b.requestedSpeed >= 99 ? '不限' : `${b.requestedSpeed.toFixed(1)} m/s`} />
</>}
</tbody>
</table>
)}
{recent.length > 0 && (
<div className="events">
<h4>最近 {RECENT_SEC} 秒的日志</h4>
{recent.map((e, i) => (
<div key={`${e.t}-${i}`}><b>{e.t.toFixed(1)}</b> {e.kind} <span>{eventText(e)}</span></div>
))}
</div>
)}
<h4>行为</h4>
<Legend names={BEHAVIOR_ZH} colors={BEHAVIOR_COLORS} />
<h4>拒绝开火</h4>
<Legend names={DENY_ZH} colors={DENY_COLORS} />
<h4>炮塔依据</h4>
<Legend names={LOOK_ZH} colors={LOOK_COLORS} />
</aside>
);
}
+179
View File
@@ -0,0 +1,179 @@
/**
* The battle in 3D: terrain and object collision shapes of the level, vehicles as simple shapes,
* and the replay's lines and markers. Left drag pans, right drag turns (except top-down), wheel
* zooms; a click on a vehicle selects it.
*/
import { BEHAVIOR_NAMES, type MapScene, type TraceBattle } from '@wto/ground-sim';
import { useEffect, useRef } from 'react';
import { AmbientLight, Color, DirectionalLight, HemisphereLight, Raycaster, Scene, Vector2, WebGLRenderer } from 'three';
import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';
import type { SceneAt, UnitAt } from './frames.ts';
import type { MapLayer } from './mapLayer.ts';
import { CameraRig, type ViewMode } from './three/cameraRig.ts';
import { buildMapMeshes, setTerrainImage, type MapMeshes } from './three/mapMeshes.ts';
import { Overlays, type Layers } from './three/overlays.ts';
import { TankPool } from './three/tanks.ts';
export interface MapLook {
readonly view: ViewMode;
/** Drape the navigation mesh image over the terrain instead of height colours. */
readonly navImage: boolean;
readonly objects: boolean;
readonly crushable: boolean;
}
interface Props {
readonly mapScene: MapScene | undefined;
readonly nav: MapLayer | undefined;
readonly battle: TraceBattle | undefined;
readonly scene: SceneAt | undefined;
readonly selected: string | undefined;
readonly layers: Layers;
readonly look: MapLook;
readonly onSelect: (eid: string | undefined) => void;
}
interface World {
readonly renderer: WebGLRenderer;
readonly labels: CSS2DRenderer;
readonly scene: Scene;
readonly rig: CameraRig;
map: MapMeshes | undefined;
tanks: TankPool;
overlays: Overlays;
selected: string | undefined;
}
const CRUSHABLE_KIND = 3;
const CLICK_PX = 4;
function labelOf(u: UnitAt): string {
const name = u.bot !== undefined ? (BEHAVIOR_NAMES[u.bot.behavior] ?? '?') : u.unit.human ? 'player' : '';
return `${u.unit.eid.replace(/^0x/, '')} ${name}`;
}
function createWorld(host: HTMLDivElement): World {
const renderer = new WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
renderer.setPixelRatio(window.devicePixelRatio);
host.appendChild(renderer.domElement);
const labels = new CSS2DRenderer();
labels.domElement.className = 'labels3d';
host.appendChild(labels.domElement);
const scene = new Scene();
scene.background = new Color(0x0b0c0d);
scene.add(new HemisphereLight(0xdfe8ff, 0x3a3326, 1.4), new AmbientLight(0xffffff, 0.25));
const sun = new DirectionalLight(0xffffff, 1.6);
sun.position.set(0.5, 1, 0.3);
scene.add(sun);
const tanks = new TankPool(undefined);
const overlays = new Overlays(tanks);
scene.add(tanks.group, overlays.group);
return { renderer, labels, scene, rig: new CameraRig(renderer.domElement), map: undefined, tanks, overlays, selected: undefined };
}
function replaceMap(w: World, mapScene: MapScene | undefined, nav: MapLayer | undefined): void {
if (w.map !== undefined) { w.scene.remove(w.map.group); w.map.dispose(); }
w.scene.remove(w.tanks.group, w.overlays.group);
w.tanks.dispose();
w.overlays.dispose();
w.map = mapScene === undefined ? undefined : buildMapMeshes(mapScene, nav);
w.tanks = new TankPool(mapScene?.terrain);
w.overlays = new Overlays(w.tanks);
if (w.map !== undefined) w.scene.add(w.map.group);
w.scene.add(w.tanks.group, w.overlays.group);
if (mapScene !== undefined) {
const t = mapScene.terrain;
let sum = 0;
for (const h of t.heights) sum += h;
w.rig.fit(mapScene.boundsMin[0], mapScene.boundsMin[1], mapScene.boundsMax[0], mapScene.boundsMax[1], sum / Math.max(1, t.heights.length));
}
}
export function Map3D({ mapScene, nav, battle, scene, selected, layers, look, onSelect }: Props): React.JSX.Element {
const hostRef = useRef<HTMLDivElement>(null);
const worldRef = useRef<World | undefined>(undefined);
const onSelectRef = useRef(onSelect);
onSelectRef.current = onSelect;
useEffect(() => {
const host = hostRef.current;
if (host === null) return;
const w = createWorld(host);
worldRef.current = w;
const resize = (): void => {
const r = host.getBoundingClientRect();
w.renderer.setSize(r.width, r.height);
w.labels.setSize(r.width, r.height);
w.rig.resize(r.width, r.height);
};
const obs = new ResizeObserver(resize);
obs.observe(host);
resize();
w.renderer.setAnimationLoop(() => {
w.rig.tick(w.selected === undefined ? undefined : w.tanks.get(w.selected));
w.renderer.render(w.scene, w.rig.camera);
w.labels.render(w.scene, w.rig.camera);
});
const down = new Vector2();
const el = w.renderer.domElement;
const onDown = (e: PointerEvent): void => { down.set(e.clientX, e.clientY); };
const onUp = (e: PointerEvent): void => {
if (e.button !== 0 || Math.hypot(e.clientX - down.x, e.clientY - down.y) > CLICK_PX) return;
const r = el.getBoundingClientRect();
const ray = new Raycaster();
ray.setFromCamera(new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), w.rig.camera);
const hit = ray.intersectObjects(w.tanks.pickables(), false)[0];
onSelectRef.current(hit?.object.userData['eid'] as string | undefined);
};
el.addEventListener('pointerdown', onDown);
el.addEventListener('pointerup', onUp);
return () => {
obs.disconnect();
el.removeEventListener('pointerdown', onDown);
el.removeEventListener('pointerup', onUp);
w.renderer.setAnimationLoop(null);
replaceMap(w, undefined, undefined);
w.rig.dispose();
w.renderer.dispose();
host.replaceChildren();
worldRef.current = undefined;
};
}, []);
useEffect(() => {
const w = worldRef.current;
if (w !== undefined) replaceMap(w, mapScene, nav);
// The navigation image is applied by the effect below; only a new level rebuilds the map.
}, [mapScene]);
useEffect(() => {
const w = worldRef.current;
if (w?.map !== undefined) setTerrainImage(w.map, look.navImage ? nav : undefined);
}, [nav, look.navImage, mapScene]);
useEffect(() => {
const w = worldRef.current;
if (w?.map === undefined) return;
w.map.kinds.forEach((g, k) => { g.visible = look.objects && (k !== CRUSHABLE_KIND || look.crushable); });
}, [look.objects, look.crushable, mapScene]);
useEffect(() => {
worldRef.current?.rig.setMode(look.view);
}, [look.view]);
useEffect(() => {
const w = worldRef.current;
if (w === undefined) return;
w.selected = selected;
w.rig.refollow();
}, [selected]);
useEffect(() => {
const w = worldRef.current;
if (w === undefined || battle === undefined || scene === undefined) return;
w.tanks.update(scene.units, selected, (u) => (layers.labels && u.unit.alive ? labelOf(u) : undefined));
w.overlays.update(battle, scene, layers);
}, [battle, scene, selected, layers, mapScene]);
return <div ref={hostRef} className="map3d" />;
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Playback controls and, for the selected bot, three strips over the whole battle: its behavior,
* the reason it did not fire, and why its turret pointed where it did. Click a strip to seek.
*/
import type { TraceBattle } from '@wto/ground-sim';
import { useEffect, useRef } from 'react';
import { BEHAVIOR_COLORS, DENY_COLORS, LOOK_COLORS } from './labels.ts';
interface Props {
readonly battle: TraceBattle;
readonly t: number;
readonly playing: boolean;
readonly speed: number;
readonly selected: string | undefined;
readonly onSeek: (t: number) => void;
readonly onPlaying: (playing: boolean) => void;
readonly onSpeed: (speed: number) => void;
}
const SPEEDS = [0.5, 1, 2, 4, 8, 16];
const STRIP_H = 10;
function drawStrips(canvas: HTMLCanvasElement, battle: TraceBattle, eid: string | undefined, t: number): void {
const ctx = canvas.getContext('2d');
if (ctx === null) return;
const w = canvas.width;
const span = Math.max(1, battle.endT - battle.startT);
ctx.fillStyle = '#16181a';
ctx.fillRect(0, 0, w, canvas.height);
if (eid !== undefined) {
const frames = battle.frames;
for (let i = 0; i < frames.length; i++) {
const f = frames[i];
const bot = f?.bots.get(eid);
if (f === undefined || bot === undefined) continue;
const x0 = ((f.t - battle.startT) / span) * w;
const x1 = (((frames[i + 1]?.t ?? f.t + 0.5) - battle.startT) / span) * w;
const bw = Math.max(1, x1 - x0);
ctx.fillStyle = BEHAVIOR_COLORS[bot.behavior] ?? '#444';
ctx.fillRect(x0, 0, bw, STRIP_H);
ctx.fillStyle = DENY_COLORS[bot.deny] ?? '#444';
ctx.fillRect(x0, STRIP_H + 2, bw, STRIP_H);
ctx.fillStyle = LOOK_COLORS[bot.lookReason] ?? '#444';
ctx.fillRect(x0, 2 * (STRIP_H + 2), bw, STRIP_H);
}
}
const cx = ((t - battle.startT) / span) * w;
ctx.fillStyle = '#fff';
ctx.fillRect(cx - 1, 0, 2, canvas.height);
}
export function Timeline({ battle, t, playing, speed, selected, onSeek, onPlaying, onSpeed }: Props): React.JSX.Element {
const stripRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const c = stripRef.current;
if (c === null) return;
c.width = Math.max(1, Math.floor(c.getBoundingClientRect().width));
drawStrips(c, battle, selected, t);
}, [battle, selected, t]);
return (
<div className="timeline">
<div className="controls">
<button type="button" onClick={() => onPlaying(!playing)}>{playing ? '暂停' : '播放'}</button>
<select value={speed} onChange={(e) => onSpeed(Number(e.target.value))}>
{SPEEDS.map((s) => <option key={s} value={s}>{s}×</option>)}
</select>
<span className="time">{t.toFixed(1)} s / {battle.endT.toFixed(0)} s</span>
<input
type="range" min={battle.startT} max={battle.endT} step={0.1} value={t}
onChange={(e) => onSeek(Number(e.target.value))}
/>
</div>
<div className="strip-labels"><span>行为</span><span>拒绝开火</span><span>炮塔依据</span></div>
<canvas
ref={stripRef}
className="strips"
height={3 * (STRIP_H + 2)}
onClick={(e) => {
const w = e.currentTarget.width;
onSeek(battle.startT + (e.nativeEvent.offsetX / w) * (battle.endT - battle.startT));
}}
/>
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
/** Loading maps and logs through the lab's dev-server API (server/lab-api.ts). */
import {
decodeMapScene, parsePois, parseTraceLog, readNavPack, type MapPois, type MapScene, type NavPack, type TraceBattle,
} from '@wto/ground-sim';
export interface LogEntry {
readonly name: string;
readonly size: number;
readonly mtime: number;
}
export interface MapEntry {
readonly level: string;
readonly pois: boolean;
/** The level's geometry is there, so it has a 3D map. */
readonly scene: boolean;
}
export interface MapData {
readonly pack: NavPack;
readonly pois: MapPois | undefined;
readonly scene: MapScene | undefined;
}
async function get(url: string): Promise<Response> {
const res = await fetch(url);
if (!res.ok) {
const body = await res.text();
throw new Error(`${url}: ${res.status} ${body}`);
}
return res;
}
export async function fetchMaps(): Promise<MapEntry[]> {
return (await (await get('/api/maps')).json()) as MapEntry[];
}
export async function fetchLogs(): Promise<LogEntry[]> {
return (await (await get('/api/logs')).json()) as LogEntry[];
}
export async function loadLog(name: string): Promise<TraceBattle[]> {
const text = await (await get(`/api/logs/text?name=${encodeURIComponent(name)}`)).text();
return parseTraceLog(text);
}
export async function loadMap(entry: MapEntry): Promise<MapData> {
const bytes = new Uint8Array(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.wtonav`)}`)).arrayBuffer());
const pois = entry.pois
? parsePois(await (await get(`/api/maps/file?name=${encodeURIComponent(`${entry.level}.pois.json`)}`)).text())
: undefined;
const scene = entry.scene
? decodeMapScene(new Uint8Array(await (await get(`/api/scene?name=${encodeURIComponent(entry.level)}`)).arrayBuffer()))
: undefined;
return { pack: readNavPack(bytes), pois, scene };
}
+95
View File
@@ -0,0 +1,95 @@
/** Looking up the battle state at any time between two trace samples. */
import type { BotSample, CapSample, TraceBattle, TraceEvent, UnitSample } from '@wto/ground-sim';
export interface UnitAt {
readonly unit: UnitSample;
/** Interpolated position, hull heading, pitch and roll. */
readonly x: number;
readonly y: number;
readonly z: number;
readonly yaw: number;
readonly hullPitch: number;
readonly hullRoll: number;
/** Interpolated gun world yaw and pitch; from the bot line, or the hull, when the unit line has none. */
readonly gunYaw: number;
readonly gunPitch: number;
/** Decision state of the sample at or before the time; undefined for players. */
readonly bot: BotSample | undefined;
}
export interface SceneAt {
readonly t: number;
readonly units: Map<string, UnitAt>;
readonly caps: CapSample[];
}
/** Index of the last frame at or before `t` (-1 before the first). */
export function frameIndexAt(battle: TraceBattle, t: number): number {
let lo = 0;
let hi = battle.frames.length - 1;
let found = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if ((battle.frames[mid]?.t ?? Infinity) <= t) { found = mid; lo = mid + 1; } else hi = mid - 1;
}
return found;
}
function lerpYaw(a: number, b: number, k: number): number {
const d = ((((b - a) % 360) + 540) % 360) - 180;
return a + d * k;
}
function lerp(a: number, b: number | undefined, k: number): number {
return a + ((b ?? a) - a) * k;
}
function gunOf(u: UnitSample, bot: BotSample | undefined): [number, number] {
return [u.gunYaw ?? bot?.gunYaw ?? u.yaw, u.gunPitch ?? 0];
}
export function sceneAt(battle: TraceBattle, t: number): SceneAt {
const i = Math.max(0, frameIndexAt(battle, t));
const a = battle.frames[i];
const b = battle.frames[i + 1];
const units = new Map<string, UnitAt>();
if (a === undefined) return { t, units, caps: [] };
const k = b !== undefined && b.t > a.t ? Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t))) : 0;
for (const [eid, ua] of a.units) {
const ub = b?.units.get(eid);
const move = ub !== undefined && ua.alive && ub.alive ? k : 0;
const bot = a.bots.get(eid);
const [gyA, gpA] = gunOf(ua, bot);
const [gyB, gpB] = ub !== undefined ? gunOf(ub, b?.bots.get(eid)) : [gyA, gpA];
units.set(eid, {
unit: ua,
x: lerp(ua.x, ub?.x, move),
y: lerp(ua.y, ub?.y, move),
z: lerp(ua.z, ub?.z, move),
yaw: lerpYaw(ua.yaw, ub?.yaw ?? ua.yaw, move),
hullPitch: lerp(ua.hullPitch ?? 0, ub?.hullPitch, move),
hullRoll: lerp(ua.hullRoll ?? 0, ub?.hullRoll, move),
gunYaw: lerpYaw(gyA, gyB, move),
gunPitch: lerp(gpA, gpB, move),
bot,
});
}
return { t, units, caps: a.caps };
}
/** Events with time in [from, to], from the sorted event list. */
export function eventsBetween(battle: TraceBattle, from: number, to: number): TraceEvent[] {
let lo = 0;
let hi = battle.events.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if ((battle.events[mid]?.t ?? Infinity) < from) lo = mid + 1; else hi = mid;
}
const out: TraceEvent[] = [];
for (let i = lo; i < battle.events.length; i++) {
const e = battle.events[i];
if (e === undefined || e.t > to) break;
out.push(e);
}
return out;
}
+37
View File
@@ -0,0 +1,37 @@
/** Chinese display names for the trace codes (the codes themselves are in @wto/ground-sim). */
export const BEHAVIOR_ZH = ['推进', '交战推进', '短停', '回掩体', '换位', '守位', '疏散', '撤回', '维修'] as const;
export const BEHAVIOR_COLORS = ['#6c8ebf', '#e0884a', '#e5d34a', '#8fbf6c', '#b07cc6', '#5fb8b0', '#9a9a9a', '#c65f5f', '#7a5a3a'] as const;
export const STATE_ZH: Readonly<Record<number, string>> = {
0: '行军', 1: '行进交战', 3: '短停', 4: '退入掩体', 5: '掩体装填', 7: '原地守位', 8: '换位',
9: '失能', 10: '疏散', 11: '坡脊撤回',
};
export const DENY_ZH = [
'放行', '无目标', '炮未就绪', '命中概率不足', '远距窗口不足', '瞄准误差', '等待炮管稳定', '检查预算',
'炮口有硬物', '弹道有硬物', '友军', '多炮检查', '射界外', '点射间歇',
] as const;
export const DENY_COLORS = [
'#4caf50', '#333', '#666', '#e53935', '#8e24aa', '#fb8c00', '#fdd835', '#90a4ae',
'#6d4c41', '#795548', '#03a9f4', '#9e9e9e', '#d81b60', '#26a69a',
] as const;
export const LOOK_ZH = ['—', '交战目标', '威胁', '目标消失处', '记忆位置', '线索', '扫视'] as const;
export const LOOK_COLORS = ['#333', '#e53935', '#fb8c00', '#fdd835', '#8e24aa', '#03a9f4', '#607d8b'] as const;
export const COMMAND_ZH = ['主攻', '侧翼', '架枪', '防守', '预备', '防空'] as const;
export const URGENCY_ZH = ['低', '中', '高'] as const;
export const LANE_ZH = ['中路', '左翼', '右翼'] as const;
export const CLASS_ZH = ['中坦', '轻坦', '重坦', '歼击车', '防空'] as const;
export function zh(names: readonly string[] | Readonly<Record<number, string>>, code: number): string {
const name = Array.isArray(names) ? names[code] : (names as Readonly<Record<number, string>>)[code];
return name ?? String(code);
}
+7
View File
@@ -0,0 +1,7 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.tsx';
import './style.css';
const root = document.getElementById('root');
if (root !== null) createRoot(root).render(<StrictMode><App /></StrictMode>);
+89
View File
@@ -0,0 +1,89 @@
/**
* The navigation image draped over the 3D terrain, drawn once into an offscreen canvas: walkable polygons of one mesh tier coloured
* by surface, optionally the tactical grid's exposure and the baked cover points.
*/
import { NAV_AREA_NAMES, type NavPack } from '@wto/ground-sim';
export interface MapLayer {
readonly canvas: HTMLCanvasElement;
/** World x of the canvas's left edge and world z of its top edge. */
readonly x0: number;
readonly z1: number;
readonly pxPerM: number;
}
export interface MapLayerOptions {
readonly tier: number;
readonly exposure: boolean;
readonly covers: boolean;
}
const AREA_COLORS: Readonly<Record<string, string>> = {
road: '#77786a', bridge: '#a0a090', ground: '#3d4a33', rough: '#5a4d34', forest: '#29402a',
crushable: '#4f5f35', shallowWater: '#35607a', chokepoint: '#7a6a35', exposed: '#5f5f33',
deepWater: '#1d3a66', noGo: '#3a2626',
};
export function buildMapLayer(pack: NavPack, opts: MapLayerOptions): MapLayer {
const [x0, , z0] = pack.header.bmin;
const [x1, , z1] = pack.header.bmax;
const pxPerM = Math.min(2, 4096 / Math.max(x1 - x0, z1 - z0));
const canvas = document.createElement('canvas');
canvas.width = Math.ceil((x1 - x0) * pxPerM);
canvas.height = Math.ceil((z1 - z0) * pxPerM);
const ctx = canvas.getContext('2d');
if (ctx === null) return { canvas, x0, z1, pxPerM };
// Off the mesh (buildings, steep or blocked ground) when draped over the 3D terrain.
ctx.fillStyle = '#55584f';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const tier = pack.tiers[opts.tier] ?? pack.tiers[1];
if (tier !== undefined) {
for (let area = 1; area < NAV_AREA_NAMES.length; area++) {
ctx.beginPath();
for (let i = 0; i < tier.polyCount; i++) {
if (tier.areas[i] !== area) continue;
const ring = tier.rings[i];
if (ring === undefined) continue;
for (let k = 0; k < ring.length; k += 2) {
const px = ((ring[k] ?? 0) - x0) * pxPerM;
const py = (z1 - (ring[k + 1] ?? 0)) * pxPerM;
if (k === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
}
ctx.closePath();
}
ctx.fillStyle = AREA_COLORS[NAV_AREA_NAMES[area] ?? ''] ?? '#444';
ctx.fill();
}
}
if (opts.exposure) drawExposure(ctx, pack, x0, z1, pxPerM);
if (opts.covers) drawCovers(ctx, pack, x0, z1, pxPerM);
return { canvas, x0, z1, pxPerM };
}
function drawExposure(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
const g = pack.tactical;
const cell = g.cellM * pxPerM;
for (let r = 0; r < g.rows; r++) {
for (let c = 0; c < g.cols; c++) {
const e = g.exposure[r * g.cols + c] ?? 0;
if (e < 16) continue;
ctx.fillStyle = `rgba(255, 80, 40, ${(e / 255) * 0.45})`;
const wx = g.origin[0] + c * g.cellM;
const wz = g.origin[1] + r * g.cellM;
ctx.fillRect((wx - x0) * pxPerM, (z1 - wz - g.cellM) * pxPerM, cell, cell);
}
}
}
function drawCovers(ctx: CanvasRenderingContext2D, pack: NavPack, x0: number, z1: number, pxPerM: number): void {
for (const cv of pack.covers) {
const px = (cv.pos[0] - x0) * pxPerM;
const py = (z1 - cv.pos[2]) * pxPerM;
ctx.strokeStyle = cv.kind === 1 ? 'rgba(120, 220, 255, 0.8)' : 'rgba(255, 230, 120, 0.8)';
ctx.beginPath();
ctx.moveTo(px, py);
ctx.lineTo(px + cv.coverDir[0] * 6 * pxPerM, py - cv.coverDir[1] * 6 * pxPerM);
ctx.stroke();
}
}
+30
View File
@@ -0,0 +1,30 @@
* { box-sizing: border-box; }
html, body, #root { margin: 0; height: 100%; background: #0b0c0d; color: #ddd; font: 13px/1.4 system-ui, 'Microsoft YaHei', sans-serif; }
.app { display: flex; flex-direction: column; height: 100%; }
header { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 6px 10px; background: #16181a; border-bottom: 1px solid #2a2d30; }
header select { max-width: 420px; }
header label { display: inline-flex; align-items: center; gap: 3px; }
.status { color: #ffb74d; }
main { flex: 1; display: flex; min-height: 0; }
.map3d { flex: 1; min-width: 0; height: 100%; position: relative; overflow: hidden; }
.map3d canvas { display: block; }
.labels3d { position: absolute; inset: 0; pointer-events: none; }
.tank-label { color: rgba(255,255,255,0.9); font-size: 11px; text-shadow: 0 0 3px #000; white-space: nowrap; }
.tank-label.human { color: #ffe14a; }
.inspector { width: 360px; overflow-y: auto; padding: 8px 10px; background: #121416; border-left: 1px solid #2a2d30; }
.inspector table { width: 100%; border-collapse: collapse; }
.inspector th { text-align: left; color: #999; font-weight: normal; padding: 2px 8px 2px 0; white-space: nowrap; vertical-align: top; }
.inspector td { padding: 2px 0; }
.inspector h4 { margin: 12px 0 4px; color: #aaa; font-weight: normal; }
.hint { color: #999; }
.events { font-size: 12px; }
.events div { padding: 1px 0; border-bottom: 1px solid #1d2023; word-break: break-all; }
.events span { color: #999; }
.legend { display: flex; flex-wrap: wrap; gap: 4px 10px; font-size: 12px; }
.legend i { display: inline-block; width: 10px; height: 10px; margin-right: 3px; vertical-align: -1px; }
.timeline { padding: 6px 10px; background: #16181a; border-top: 1px solid #2a2d30; }
.controls { display: flex; gap: 8px; align-items: center; }
.controls input[type='range'] { flex: 1; }
.time { min-width: 120px; font-variant-numeric: tabular-nums; }
.strip-labels { display: flex; gap: 12px; font-size: 11px; color: #888; margin-top: 4px; }
canvas.strips { width: 100%; height: 36px; display: block; cursor: pointer; }
+119
View File
@@ -0,0 +1,119 @@
/**
* The 3D view's cameras: a top-down orthographic map view (world +z up the screen, like the old
* flat map), a free perspective view, a view that follows the selected vehicle, and a view out of
* its muzzle along the barrel.
*/
import { OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from 'three';
import { MapControls } from 'three/addons/controls/MapControls.js';
import type { Tank } from './tanks.ts';
export type ViewMode = 'top' | 'free' | 'follow' | 'gun';
const TOP_HEIGHT = 3000;
/** Top-down camera sits this far south of its target, so the controls keep north up. */
const TOP_SOUTH = 0.01;
const FREE_MAX_POLAR = Math.PI * 0.49;
export class CameraRig {
readonly persp = new PerspectiveCamera(50, 1, 0.5, 20000);
readonly ortho = new OrthographicCamera(-1, 1, 1, -1, 1, 10000);
readonly controls: MapControls;
private mode: ViewMode = 'top';
private aspect = 1;
private readonly lastFollow = new Vector3();
private following = false;
constructor(dom: HTMLElement) {
this.controls = new MapControls(this.ortho, dom);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.15;
this.controls.screenSpacePanning = true;
this.limitTilt();
}
/** Top-down stays straight down; the other views may tilt down to just above the horizon. */
private limitTilt(): void {
this.controls.maxPolarAngle = this.mode === 'top' ? 0 : FREE_MAX_POLAR;
}
get camera(): Camera {
return this.mode === 'top' ? this.ortho : this.persp;
}
resize(w: number, h: number): void {
this.aspect = w / Math.max(1, h);
this.persp.aspect = this.aspect;
this.persp.updateProjectionMatrix();
const half = (this.ortho.top - this.ortho.bottom) / 2;
this.ortho.left = -half * this.aspect;
this.ortho.right = half * this.aspect;
this.ortho.updateProjectionMatrix();
}
/** Frames the world rectangle (x, z) in both cameras. */
fit(minX: number, minZ: number, maxX: number, maxZ: number, groundY: number): void {
const cx = (minX + maxX) / 2;
const cz = -(minZ + maxZ) / 2;
const half = (Math.max((maxX - minX) / this.aspect, maxZ - minZ) / 2) * 1.05;
Object.assign(this.ortho, { left: -half * this.aspect, right: half * this.aspect, top: half, bottom: -half, zoom: 1 });
this.ortho.updateProjectionMatrix();
this.ortho.position.set(cx, groundY + TOP_HEIGHT, cz + TOP_SOUTH);
this.persp.position.set(cx, groundY + half * 0.9, cz + half * 1.1);
this.controls.target.set(cx, groundY, cz);
this.ortho.lookAt(this.controls.target);
this.persp.lookAt(this.controls.target);
this.controls.update();
}
setMode(mode: ViewMode): void {
if (mode === this.mode) return;
const target = this.controls.target.clone();
if (this.mode === 'top' && mode !== 'gun') {
const span = (this.ortho.top - this.ortho.bottom) / this.ortho.zoom;
this.persp.position.set(target.x, target.y + span * 0.6, target.z + span * 0.6);
}
if (mode === 'top') this.ortho.position.set(target.x, target.y + TOP_HEIGHT, target.z + TOP_SOUTH);
this.mode = mode;
this.limitTilt();
this.following = false;
this.controls.object = this.camera;
this.controls.enableRotate = mode !== 'top';
this.controls.enabled = mode !== 'gun';
this.camera.lookAt(target);
this.controls.update();
}
/** The next follow frame starts over around the (newly) selected vehicle. */
refollow(): void {
this.following = false;
}
/** Per frame: keeps the followed vehicle centred, or puts the camera at the muzzle. */
tick(tank: Tank | undefined): void {
if (this.mode === 'follow' && tank !== undefined && tank.root.visible) {
const at = tank.root.position;
if (!this.following) {
this.controls.target.copy(at);
this.persp.position.set(at.x - 25, at.y + 15, at.z + 25);
this.following = true;
} else {
const d = at.clone().sub(this.lastFollow);
this.controls.target.add(d);
this.persp.position.add(d);
}
this.lastFollow.copy(at);
} else if (this.mode === 'gun' && tank !== undefined && tank.root.visible) {
const q = tank.barrel.getWorldQuaternion(new Quaternion());
const dir = new Vector3(1, 0, 0).applyQuaternion(q);
const tip = tank.barrel.getWorldPosition(new Vector3()).addScaledVector(dir, tank.length * 0.8);
this.persp.position.copy(tip);
this.persp.lookAt(tip.clone().add(dir));
return;
}
if (this.controls.enabled) this.controls.update();
}
dispose(): void {
this.controls.dispose();
}
}
+18
View File
@@ -0,0 +1,18 @@
/**
* Game world to three.js: Dagor is left-handed with Y up, three.js right-handed, so world z is
* mirrored (three z = -world z). A world heading (degrees of atan2(z, x)) then becomes the same
* angle of rotation about three's +Y, and a model's local +X is its front, +Y up, -Z its left.
*/
import { Vector3 } from 'three';
export const DEG = Math.PI / 180;
export function toThree(x: number, y: number, z: number, out: Vector3 = new Vector3()): Vector3 {
return out.set(x, y, -z);
}
/** Three.js direction of a world heading and pitch, in degrees. */
export function dirOf(yawDeg: number, pitchDeg: number, out: Vector3 = new Vector3()): Vector3 {
const c = Math.cos(pitchDeg * DEG);
return out.set(Math.cos(yawDeg * DEG) * c, Math.sin(pitchDeg * DEG), -Math.sin(yawDeg * DEG) * c);
}
+134
View File
@@ -0,0 +1,134 @@
/**
* The static 3D map: lit terrain (coloured by height, or draped with the navigation mesh image),
* the collision shapes of placed objects coloured by kind, and the water plane.
*/
import type { MapScene, SceneTerrain } from '@wto/ground-sim';
import {
BufferAttribute, BufferGeometry, CanvasTexture, Color, DoubleSide, Group, Mesh, MeshLambertMaterial,
PlaneGeometry, SRGBColorSpace, type Material,
} from 'three';
import type { MapLayer } from '../mapLayer.ts';
/** Colour and opacity per SCENE_KIND_NAMES entry. */
const KIND_LOOK: readonly (readonly [number, number])[] = [
[0xb9b2a3, 1], [0x7d7a74, 1], [0x9a7b55, 1], [0xe09a4a, 0.4], [0x4f8a3c, 1], [0x6f8aa0, 1],
];
const LOW = new Color(0x3c4a32);
const HIGH = new Color(0x9b9171);
export interface MapMeshes {
readonly group: Group;
readonly terrain: Mesh<BufferGeometry, MeshLambertMaterial>;
/** Objects per scene kind, to switch kinds on and off. */
readonly kinds: Group[];
dispose(): void;
}
function terrainGeometry(t: SceneTerrain, nav: MapLayer | undefined): BufferGeometry {
const n = t.cols * t.rows;
const pos = new Float32Array(n * 3);
const col = new Float32Array(n * 3);
const uv = new Float32Array(n * 2);
let lo = Infinity;
let hi = -Infinity;
for (const h of t.heights) { lo = Math.min(lo, h); hi = Math.max(hi, h); }
const c = new Color();
const navW = nav === undefined ? 1 : nav.canvas.width / nav.pxPerM;
const navH = nav === undefined ? 1 : nav.canvas.height / nav.pxPerM;
for (let r = 0; r < t.rows; r++) {
for (let k = 0; k < t.cols; k++) {
const i = r * t.cols + k;
const x = t.origin[0] + k * t.cellM;
const z = t.origin[1] + r * t.cellM;
const h = t.heights[i] ?? 0;
pos.set([x, h, -z], i * 3);
c.lerpColors(LOW, HIGH, hi > lo ? (h - lo) / (hi - lo) : 0);
col.set([c.r, c.g, c.b], i * 3);
if (nav !== undefined) uv.set([(x - nav.x0) / navW, (z - (nav.z1 - navH)) / navH], i * 2);
}
}
const idx = new Uint32Array((t.cols - 1) * (t.rows - 1) * 6);
let at = 0;
for (let r = 0; r + 1 < t.rows; r++) {
for (let k = 0; k + 1 < t.cols; k++) {
const i = r * t.cols + k;
idx.set([i, i + 1, i + t.cols, i + 1, i + t.cols + 1, i + t.cols], at);
at += 6;
}
}
const g = new BufferGeometry();
g.setAttribute('position', new BufferAttribute(pos, 3));
g.setAttribute('color', new BufferAttribute(col, 3));
g.setAttribute('uv', new BufferAttribute(uv, 2));
g.setIndex(new BufferAttribute(idx, 1));
g.computeVertexNormals();
return g;
}
/** Drapes the navigation image over the terrain, or goes back to height colours. */
export function setTerrainImage(m: MapMeshes, nav: MapLayer | undefined): void {
const mat = m.terrain.material;
mat.map?.dispose();
if (nav === undefined) {
mat.map = null;
mat.vertexColors = true;
} else {
const tex = new CanvasTexture(nav.canvas);
tex.colorSpace = SRGBColorSpace;
tex.anisotropy = 8;
mat.map = tex;
mat.vertexColors = false;
}
mat.needsUpdate = true;
}
function objectKinds(scene: MapScene, materials: Material[]): Group[] {
const kinds = KIND_LOOK.map(() => new Group());
const mats = KIND_LOOK.map(([color, opacity]) => new MeshLambertMaterial({
color, flatShading: true, side: DoubleSide, transparent: opacity < 1, opacity, depthWrite: opacity >= 1,
}));
materials.push(...mats);
for (const m of scene.meshes) {
const g = new BufferGeometry();
const pos = new Float32Array(m.positions);
for (let i = 2; i < pos.length; i += 3) pos[i] = -(pos[i] ?? 0);
g.setAttribute('position', new BufferAttribute(pos, 3));
g.setIndex(new BufferAttribute(m.indices, 1));
g.computeBoundingSphere();
const mat = mats[m.kind] ?? mats[0];
if (mat !== undefined) kinds[m.kind]?.add(new Mesh(g, mat));
}
return kinds;
}
export function buildMapMeshes(scene: MapScene, nav: MapLayer | undefined): MapMeshes {
const group = new Group();
const materials: Material[] = [];
const terrainMat = new MeshLambertMaterial({ vertexColors: true });
materials.push(terrainMat);
const terrain = new Mesh(terrainGeometry(scene.terrain, nav), terrainMat);
group.add(terrain);
const kinds = objectKinds(scene, materials);
for (const k of kinds) group.add(k);
if (scene.waterLevel !== undefined) {
const w = scene.boundsMax[0] - scene.boundsMin[0];
const d = scene.boundsMax[1] - scene.boundsMin[1];
const waterMat = new MeshLambertMaterial({ color: 0x2d5f8a, transparent: true, opacity: 0.55, depthWrite: false });
materials.push(waterMat);
const water = new Mesh(new PlaneGeometry(w, d), waterMat);
water.rotation.x = -Math.PI / 2;
water.position.set(scene.boundsMin[0] + w / 2, scene.waterLevel, -(scene.boundsMin[1] + d / 2));
group.add(water);
}
const meshes: MapMeshes = {
group, terrain, kinds,
dispose() {
group.traverse((o) => { if (o instanceof Mesh) (o.geometry as BufferGeometry).dispose(); });
terrainMat.map?.dispose();
for (const m of materials) m.dispose();
},
};
if (nav !== undefined) setTerrainImage(meshes, nav);
return meshes;
}
+182
View File
@@ -0,0 +1,182 @@
/**
* What is drawn over the map for one moment, rebuilt every update: goal, target and look lines,
* the gun's view cone, recent shots and hits, deaths so far, and the capture zones.
*/
import type { TraceBattle } from '@wto/ground-sim';
import {
AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Group, LineBasicMaterial,
LineSegments, Mesh, MeshBasicMaterial, Points, PointsMaterial,
} from 'three';
import { eventsBetween, type SceneAt, type UnitAt } from '../frames.ts';
import { DEG } from './coords.ts';
import { ARMY_HEX, type TankPool } from './tanks.ts';
export interface Layers {
readonly goals: boolean;
readonly links: boolean;
readonly cones: boolean;
readonly labels: boolean;
readonly events: boolean;
}
const GUN_FOV_HALF_DEG = 30;
const CONE_M = 120;
const CONE_STEPS = 12;
const EVENT_WINDOW_SEC = 2;
const CAP_STEPS = 64;
const WISH_M = 25;
/** Line segments with per-vertex colour, refilled from scratch on every update. */
class Lines {
readonly obj: LineSegments;
private pos: number[] = [];
private col: number[] = [];
constructor(opacity: number, additive = false) {
const mat = new LineBasicMaterial({ vertexColors: true, transparent: true, opacity, depthTest: !additive });
if (additive) mat.blending = AdditiveBlending;
this.obj = new LineSegments(new BufferGeometry(), mat);
this.obj.frustumCulled = false;
}
add(ax: number, ay: number, az: number, bx: number, by: number, bz: number, c: Color): void {
this.pos.push(ax, ay, -az, bx, by, -bz);
this.col.push(c.r, c.g, c.b, c.r, c.g, c.b);
}
flush(): void {
const g = this.obj.geometry;
g.setAttribute('position', new BufferAttribute(Float32Array.from(this.pos), 3));
g.setAttribute('color', new BufferAttribute(Float32Array.from(this.col), 3));
g.computeBoundingSphere();
this.pos = [];
this.col = [];
}
}
const C = {
goal: new Color(0x9aa4ad), target: new Color(0xff4646), targetLost: new Color(0x803030),
look: new Color(0xffa028), wish: new Color(0xffe14a), shot: new Color(0xffff78), dead1: new Color(ARMY_HEX[1]),
dead2: new Color(ARMY_HEX[2]), cap: new Color(0xdddddd),
};
export class Overlays {
readonly group = new Group();
private readonly faint = new Lines(0.35);
private readonly bold = new Lines(0.9);
private readonly shots = new Lines(1, true);
private readonly cones: Mesh;
private readonly hits: Points;
constructor(private readonly tanks: TankPool) {
this.cones = new Mesh(new BufferGeometry(), new MeshBasicMaterial({
color: 0xffffc8, transparent: true, opacity: 0.08, side: DoubleSide, depthWrite: false,
}));
this.cones.frustumCulled = false;
this.hits = new Points(new BufferGeometry(), new PointsMaterial({ size: 6, sizeAttenuation: false, vertexColors: true }));
this.hits.frustumCulled = false;
this.group.add(this.faint.obj, this.bold.obj, this.shots.obj, this.cones, this.hits);
}
/** Height where lines leave a vehicle: its turret top. */
private eye(u: UnitAt): number {
return this.tanks.groundY(u.x, u.y, u.z) + (this.tanks.get(u.unit.eid)?.eyeY ?? 2);
}
update(battle: TraceBattle, scene: SceneAt, layers: Layers): void {
const cone: number[] = [];
for (const u of scene.units.values()) this.botLines(u, scene, layers, cone);
if (layers.events) this.events(battle, scene);
this.deaths(battle, scene.t);
this.caps(scene);
const g = this.cones.geometry;
g.setAttribute('position', new BufferAttribute(Float32Array.from(cone), 3));
this.faint.flush();
this.bold.flush();
this.shots.flush();
}
private botLines(u: UnitAt, scene: SceneAt, layers: Layers, cone: number[]): void {
const bot = u.bot;
if (bot === undefined || !u.unit.alive) return;
const y = this.eye(u);
if (layers.goals && bot.hasOrder) this.faint.add(u.x, y, u.z, bot.goalX, this.tanks.terrainY(bot.goalX, bot.goalZ) + 1, bot.goalZ, C.goal);
const wy = bot.wishYaw * DEG;
this.bold.add(u.x, y, u.z, u.x + Math.cos(wy) * WISH_M, y, u.z + Math.sin(wy) * WISH_M, C.wish);
if (layers.cones) {
for (let i = 0; i < CONE_STEPS; i++) {
const a = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * i) / CONE_STEPS) * DEG;
const b = (u.gunYaw - GUN_FOV_HALF_DEG + (2 * GUN_FOV_HALF_DEG * (i + 1)) / CONE_STEPS) * DEG;
cone.push(u.x, y, -u.z, u.x + Math.cos(a) * CONE_M, y, -(u.z + Math.sin(a) * CONE_M),
u.x + Math.cos(b) * CONE_M, y, -(u.z + Math.sin(b) * CONE_M));
}
}
if (!layers.links) return;
const target = scene.units.get(bot.target);
if (target !== undefined && bot.target !== '0') {
(bot.targetInSight ? this.bold : this.faint).add(u.x, y, u.z, target.x, this.eye(target), target.z,
bot.targetInSight ? C.target : C.targetLost);
}
const look = scene.units.get(bot.lookAt);
if (look !== undefined && bot.lookAt !== bot.target) this.bold.add(u.x, y, u.z, look.x, this.eye(look), look.z, C.look);
}
private events(battle: TraceBattle, scene: SceneAt): void {
const pos: number[] = [];
const col: number[] = [];
const c = new Color();
for (const e of eventsBetween(battle, scene.t - EVENT_WINDOW_SEC, scene.t)) {
const fade = 1 - (scene.t - e.t) / EVENT_WINDOW_SEC;
if (e.kind === 'SHOT' && e.eid !== undefined) {
const from = scene.units.get(e.eid);
const to = scene.units.get(e.fields['tgt'] ?? '');
if (from === undefined || to === undefined) continue;
this.shots.add(from.x, this.eye(from), from.z, to.x, this.eye(to) - 1, to.z, c.copy(C.shot).multiplyScalar(fade));
} else if (e.kind === 'HIT') {
const x = Number(e.fields['x']);
const z = Number(e.fields['z']);
pos.push(x, this.tanks.terrainY(x, z) + 1.5, -z);
c.set(e.fields['drop'] === '1' ? 0xff3c3c : 0xc8c8c8).multiplyScalar(fade);
col.push(c.r, c.g, c.b);
}
}
this.hits.geometry.setAttribute('position', new BufferAttribute(Float32Array.from(pos), 3));
this.hits.geometry.setAttribute('color', new BufferAttribute(Float32Array.from(col), 3));
}
private deaths(battle: TraceBattle, t: number): void {
for (const e of eventsBetween(battle, battle.startT, t)) {
if (e.kind !== 'DEATH') continue;
const x = Number(e.fields['x']);
const z = Number(e.fields['z']);
const y = this.tanks.terrainY(x, z) + 0.5;
const c = e.fields['army'] === '1' ? C.dead1 : C.dead2;
this.faint.add(x - 4, y, z - 4, x + 4, y, z + 4, c);
this.faint.add(x - 4, y, z + 4, x + 4, y, z - 4, c);
}
}
private caps(scene: SceneAt): void {
for (const cap of scene.caps) {
const c = new Color(ARMY_HEX[cap.owner] ?? C.cap.getHex());
for (let i = 0; i < CAP_STEPS; i++) {
const a = (i / CAP_STEPS) * Math.PI * 2;
const b = ((i + 1) / CAP_STEPS) * Math.PI * 2;
const ax = cap.x + Math.cos(a) * cap.r;
const az = cap.z + Math.sin(a) * cap.r;
const bx = cap.x + Math.cos(b) * cap.r;
const bz = cap.z + Math.sin(b) * cap.r;
this.bold.add(ax, this.tanks.terrainY(ax, az) + 0.8, az, bx, this.tanks.terrainY(bx, bz) + 0.8, bz, c);
}
}
}
dispose(): void {
this.group.traverse((o) => {
if (o instanceof Mesh || o instanceof LineSegments || o instanceof Points) {
o.geometry.dispose();
(o.material as { dispose(): void }).dispose();
}
});
}
}
+141
View File
@@ -0,0 +1,141 @@
/**
* Every vehicle as simple shapes: a hull box tilted by the hull's pitch and roll, a turret box
* turned to the gun's heading, and a barrel at the gun's pitch. Sizes come from the bot's vehicle
* class (players: light or medium).
*/
import { sceneHeightAt, type SceneTerrain } from '@wto/ground-sim';
import {
BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshLambertMaterial, type Object3D,
} from 'three';
import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
import type { UnitAt } from '../frames.ts';
import { DEG } from './coords.ts';
/** Length, width, hull height per vehicle class (medium, light, heavy, tank destroyer, SPAA). */
const SIZES: readonly (readonly [number, number, number])[] = [
[7, 3.4, 1.3], [6, 3, 1.1], [7.6, 3.6, 1.4], [7, 3.3, 1.2], [6.5, 3.1, 1.2],
];
export const ARMY_HEX: Readonly<Record<number, number>> = { 1: 0x4aa3ff, 2: 0xff5c5c };
const DEAD = new Color(0x4a4a4a);
const SELECTED = new Color(0x6a5200);
const NONE = new Color(0);
/** A trace height further than this from the terrain is kept (bridge, building, platform). */
const OFF_GROUND_M = 1.5;
export interface Tank {
readonly root: Group;
readonly turret: Group;
readonly barrel: Group;
readonly label: CSS2DObject;
readonly mats: MeshLambertMaterial[];
/** Turret top above the hull origin, where lines and the gun camera start. */
readonly eyeY: number;
readonly length: number;
}
function sizeOf(u: UnitAt): readonly [number, number, number] {
const cls = u.bot?.vehicleClass ?? (u.unit.light ? 1 : 0);
return SIZES[cls] ?? SIZES[0] ?? [7, 3.4, 1.3];
}
function makeTank(u: UnitAt): Tank {
const [len, wid, hh] = sizeOf(u);
const hullMat = new MeshLambertMaterial();
const turretMat = new MeshLambertMaterial();
const root = new Group();
root.rotation.order = 'YZX';
const hull = new Mesh(new BoxGeometry(len, hh, wid), hullMat);
hull.position.y = hh / 2;
const turret = new Group();
turret.position.set(-len * 0.05, hh, 0);
const tw = wid * 0.7;
const th = hh * 0.65;
const turretBox = new Mesh(new BoxGeometry(len * 0.48, th, tw), turretMat);
turretBox.position.y = th / 2;
const barrel = new Group();
barrel.position.set(len * 0.2, th * 0.55, 0);
const tube = new Mesh(new CylinderGeometry(0.09, 0.11, len * 0.75, 8), turretMat);
tube.rotation.z = -Math.PI / 2;
tube.position.x = len * 0.375;
barrel.add(tube);
turret.add(turretBox, barrel);
root.add(hull, turret);
const div = document.createElement('div');
div.className = 'tank-label';
const label = new CSS2DObject(div);
label.position.y = hh + th + 2.5;
root.add(label);
for (const m of [hull, turretBox, tube]) m.userData['eid'] = u.unit.eid;
return { root, turret, barrel, label, mats: [hullMat, turretMat], eyeY: hh + th, length: len };
}
export class TankPool {
readonly group = new Group();
private readonly tanks = new Map<string, Tank>();
constructor(private readonly terrain: SceneTerrain | undefined) {}
get(eid: string): Tank | undefined {
return this.tanks.get(eid);
}
/** Meshes to pick with a ray. */
pickables(): Object3D[] {
const out: Object3D[] = [];
for (const t of this.tanks.values()) if (t.root.visible) t.root.traverse((o) => { if (o instanceof Mesh) out.push(o); });
return out;
}
terrainY(x: number, z: number): number {
return this.terrain === undefined ? 0 : sceneHeightAt(this.terrain, x, z);
}
/** Ground height for the vehicle: the terrain unless the trace puts it clearly above or below. */
groundY(x: number, y: number, z: number): number {
if (this.terrain === undefined) return y;
const g = sceneHeightAt(this.terrain, x, z);
return Math.abs(y - g) <= OFF_GROUND_M ? g : y;
}
update(units: ReadonlyMap<string, UnitAt>, selected: string | undefined, labels: (u: UnitAt) => string | undefined): void {
for (const [eid, t] of this.tanks) if (!units.has(eid)) t.root.visible = false;
for (const u of units.values()) {
let t = this.tanks.get(u.unit.eid);
if (t === undefined) {
t = makeTank(u);
this.tanks.set(u.unit.eid, t);
this.group.add(t.root);
}
this.place(t, u, u.unit.eid === selected, labels(u));
}
}
private place(t: Tank, u: UnitAt, selected: boolean, label: string | undefined): void {
t.root.visible = true;
t.root.position.set(u.x, this.groundY(u.x, u.y, u.z), -u.z);
t.root.rotation.set(u.hullRoll * DEG, u.yaw * DEG, u.hullPitch * DEG);
const rel = ((((u.gunYaw - u.yaw) % 360) + 540) % 360) - 180;
t.turret.rotation.y = rel * DEG;
const hullSlope = u.hullPitch * Math.cos(rel * DEG) + u.hullRoll * Math.sin(rel * DEG);
t.barrel.rotation.z = (u.gunPitch - hullSlope) * DEG;
const base = u.unit.alive ? new Color(ARMY_HEX[u.unit.army] ?? 0xcccccc) : DEAD;
t.mats.forEach((m, i) => {
m.color.copy(base).multiplyScalar(i === 0 ? 1 : 0.8);
m.emissive.copy(selected ? SELECTED : NONE);
});
t.label.visible = label !== undefined;
if (label !== undefined) t.label.element.textContent = label;
if (u.unit.human) t.label.element.classList.add('human');
}
dispose(): void {
for (const t of this.tanks.values()) {
t.root.traverse((o) => { if (o instanceof Mesh) o.geometry.dispose(); });
for (const m of t.mats) m.dispose();
t.label.element.remove();
}
this.tanks.clear();
}
}
+23
View File
@@ -0,0 +1,23 @@
{
// The lab is a Vite page plus its dev-server API (server/), so it has its own settings and stays
// out of the root typecheck, like the launcher.
"compilerOptions": {
"target": "ES2023",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": ["node"],
"jsx": "react-jsx",
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "server/**/*.ts", "vite.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { labApi } from './server/lab-api.ts';
export default defineConfig({
plugins: [react(), labApi()],
server: { host: '127.0.0.1', port: 47180, strictPort: false },
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@wto/launcher",
"productName": "WTOffline Launcher",
"version": "0.1.5",
"version": "0.1.6",
"private": true,
"description": "Installer and launcher of the War Thunder offline project.",
"type": "module",
+10
View File
@@ -16,6 +16,7 @@ import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, install
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activeMapNav, applyMapNavUpdate, checkMapNavUpdate, useLocalMapNav } from '../services/map-nav/map-nav-update.ts';
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
import {
applyModPreset,
@@ -31,6 +32,7 @@ import {
setModsOrder,
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveCrew, getSaveCrews, previewSaveCrew } from '../services/saves/manage-save-crews.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 { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts';
import { broadcast, handle } from './register.ts';
@@ -193,6 +195,9 @@ export function registerIpcHandlers(): void {
handle('saves:research', ({ copyId, userId, branch }) => getSaveResearch(copyId, userId, branch));
handle('saves:editResearch', ({ copyId, userId, branch, action }) => changeSaveResearch(copyId, userId, branch, action));
handle('saves:crews', ({ copyId, userId, country }) => getSaveCrews(copyId, userId, country));
handle('saves:previewCrew', ({ copyId, userId, country, edit }) => previewSaveCrew(copyId, userId, country, edit));
handle('saves:editCrew', ({ copyId, userId, country, edit, token }) => changeSaveCrew(copyId, userId, country, edit, token));
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
@@ -265,6 +270,11 @@ export function registerIpcHandlers(): void {
});
handle('updates:check', () => checkAppUpdate());
handle('map-nav:active', () => activeMapNav());
handle('map-nav:check', () => checkMapNavUpdate());
handle('map-nav:apply', ({ version }) => applyMapNavUpdate(version, (progress) =>
broadcast('event:map-nav-progress', progress)));
handle('map-nav:deactivate', () => useLocalMapNav());
handle('updates:download', ({ version }) => downloadAppUpdate(version, (progress) => broadcast('event:app-update-progress', progress)));
handle('updates:install', ({ version }) => installAppUpdate(version, () =>
launchInProgress() || installationInProgress() || maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()));
@@ -1,11 +1,6 @@
import { spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
import { once } from 'node:events';
import { createWriteStream } from 'node:fs';
import { mkdir, rename, unlink } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { app } from 'electron';
import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519 } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
@@ -19,7 +14,7 @@ import {
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease,
} from '../patch-pack/release-feed.ts';
import {
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset,
} from '../patch-pack/release-assets.ts';
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
import {
@@ -152,7 +147,7 @@ export function downloadAppUpdate(
? offer.release : await projectReleaseVersion('launcher', version, source);
const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer;
if (!assetUrl) throw new FeedUnreachableError(`This update source does not have the ${offer.mode} asset for ${version}.`);
await stageArtifact(assetUrl, release.source, offer.manifest, target, report);
await stageReleaseAsset(assetUrl, release.source, offer.manifest, target, report);
}, offer.release.source);
return offerResult(offer, true);
} catch (error) {
@@ -162,50 +157,6 @@ export function downloadAppUpdate(
});
}
async function stageArtifact(
assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string,
report: (progress: AppUpdateProgress) => void,
): Promise<void> {
const partial = `${target}.partial`;
const deadline = AbortSignal.timeout(30 * 60_000);
let size = 0;
let reportedAt = 0;
const hash = createHash('sha256');
try {
await mkdir(dirname(target), { recursive: true });
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
});
const response = await requestReleaseAsset(assetUrl, deadline, source);
const monitor = new Transform({
transform(chunk: Buffer, _encoding, done) {
size += chunk.length;
if (size > manifest.size) {
done(new Error('The download is larger than the signed release size.'));
return;
}
hash.update(chunk);
if (size === manifest.size || Date.now() - reportedAt >= 200) {
reportedAt = Date.now();
report({ received: size, total: manifest.size });
}
done(null, chunk);
},
});
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
if (size !== manifest.size) throw new FeedUnreachableError('The update download is incomplete.');
if (hash.digest('hex') !== manifest.sha256) throw new Error('The update download does not match the signed release.');
await rename(partial, target);
} catch (error) {
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
throw error;
} finally {
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error);
});
}
}
export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise<void> {
return exclusively(async () => {
const offer = selectedOffer(version);
@@ -14,6 +14,7 @@ import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../insta
import { findBlockingIncompleteUhqPacks } from '../install/uhq-packages.ts';
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { selectedMapNavPack } from '../map-nav/map-nav-store.ts';
import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
import { gameProcessRunning } from './game-process.ts';
@@ -222,6 +223,7 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
signal.throwIfAborted();
update(job, { phase: 'building', port });
const buildStart = Date.now();
const mapNavFolder = selectedMapNavPack(dataPath)?.folder;
let writtenFiles = 0;
await buildCopy({
kind: 'build',
@@ -231,6 +233,7 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
port,
steamLibraryConfirmed,
...resourcePaths(),
...(mapNavFolder === undefined ? {} : { mapNavFolder }),
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
@@ -0,0 +1,65 @@
import { execFile } from 'node:child_process';
import { readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { PatchPackError } from '@wto/patcher';
import { MapNavManifestSchema, type MapNavManifest } from '@shared/schemas/map-nav-pack.ts';
import { installerDigest } from '../app-update/installer-integrity.ts';
import { RELEASE_MANIFEST_MAX_BYTES } from '../patch-pack/release-assets.ts';
const execute = promisify(execFile);
/** Compare the exact maps written by the installer with the signed release manifest. */
export async function verifyMapNavFolder(folder: string, manifest: MapNavManifest): Promise<void> {
const stored = MapNavManifestSchema.parse(JSON.parse(await readFile(join(folder, 'manifest.json'), 'utf8')));
if (JSON.stringify(stored) !== JSON.stringify(MapNavManifestSchema.parse(manifest))) {
throw new PatchPackError('contents', 'The map pack manifest does not match the signed release.');
}
for (const entry of manifest.maps) {
const digest = await installerDigest(join(folder, 'maps', entry.level + '.wtonav'), entry.size);
if (digest.size !== entry.size || digest.sha256 !== entry.sha256) {
throw new PatchPackError('contents', 'The map file does not match the signed release: ' + entry.level);
}
}
}
/** The ZIP is already verified. Extract only the exact file names and sizes the manifest promises. */
export async function extractMapNavArchive(zip: string, staging: string, manifest: MapNavManifest): Promise<string> {
const folder = join(staging, 'map-nav');
const index = join(staging, 'expected-maps.json');
const script = join(staging, 'extract-maps.ps1');
const expected = manifest.maps.map(({ level, size }) => ({ name: 'map-nav/maps/' + level + '.wtonav', size }));
await writeFile(index, JSON.stringify(expected));
await writeFile(script, '\uFEFF' + EXTRACTION_SCRIPT.join('\r\n'), 'utf8');
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
zip, staging, index, String(RELEASE_MANIFEST_MAX_BYTES),
], { windowsHide: true, timeout: 180_000 });
await verifyMapNavFolder(folder, manifest);
return folder;
}
const EXTRACTION_SCRIPT = [
'param([string]$ZipPath, [string]$Root, [string]$IndexPath, [long]$ManifestLimit)',
"$ErrorActionPreference = 'Stop'",
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
'$expected = [System.Collections.Generic.Dictionary[string,long]]::new([StringComparer]::Ordinal)',
'foreach ($item in (Get-Content -LiteralPath $IndexPath -Raw -Encoding UTF8 | ConvertFrom-Json)) { $expected.Add($item.name, $item.size) }',
'$seenManifest = $false',
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
'try {',
' [System.IO.Directory]::CreateDirectory((Join-Path $Root "map-nav/maps")) | Out-Null',
' foreach ($entry in $zip.Entries) {',
' $name = $entry.FullName',
' if ($entry.Length -eq 0 -and ($name -ceq "map-nav/" -or $name -ceq "map-nav/maps/")) { continue }',
' if (!$seenManifest -and $name -ceq "map-nav/manifest.json" -and $entry.Length -le $ManifestLimit) {',
' $seenManifest = $true',
' } else {',
' if (!$expected.ContainsKey($name) -or $entry.Length -ne $expected[$name]) { throw "Unexpected map pack entry: $name" }',
' [void]$expected.Remove($name)',
' }',
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $Root $name), $false)',
' }',
' if (!$seenManifest -or $expected.Count -gt 0) { throw "The map pack is incomplete." }',
'} finally { $zip.Dispose() }',
];
@@ -0,0 +1,89 @@
import { readFileSync, readdirSync } from 'node:fs';
import { mkdir, rename, rm } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import { compareAppVersions } from '@wto/patcher';
import {
MAP_NAV_FORMAT, MapNavManifestSchema, MapNavVersionSchema, type ActiveMapNav, type MapNavManifest,
} from '@shared/schemas/map-nav-pack.ts';
import { writeJsonAtomic } from '../../util/atomic-json.ts';
import { bundledResourcePaths } from '../resources/resource-paths.ts';
interface MapNavPack {
readonly folder: string;
readonly info: NonNullable<ActiveMapNav>;
}
export function mapNavStoreFolder(): string {
return join(app.getPath('userData'), 'map-nav');
}
function activeFile(): string {
return join(mapNavStoreFolder(), 'active.json');
}
export function needsMapNavLauncherUpdate(manifest: MapNavManifest): boolean {
return manifest.format !== MAP_NAV_FORMAT || compareAppVersions(app.getVersion(), manifest.minAppVersion) < 0;
}
function readManifest(folder: string): MapNavManifest | null {
try {
return MapNavManifestSchema.parse(JSON.parse(readFileSync(join(dirname(folder), 'manifest.json'), 'utf8')));
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] could not read the pack manifest:', error);
return null;
}
}
function foundPack(folder: string, source: NonNullable<ActiveMapNav>['source']): MapNavPack | null {
let maps: string[];
try {
maps = readdirSync(folder, { withFileTypes: true })
.filter((file) => (file.isFile() || file.isSymbolicLink()) && file.name.endsWith('.wtonav'))
.map((file) => file.name);
} catch (error) {
if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) {
console.warn('[map-nav] could not read the maps folder:', error);
}
return null;
}
if (maps.length === 0) return null;
const manifest = readManifest(folder);
if (manifest && needsMapNavLauncherUpdate(manifest)) return null;
return {
folder,
info: { source, version: manifest?.version ?? null, gameVersions: manifest?.gameVersions ?? [], mapCount: maps.length },
};
}
function downloadedPack(): MapNavPack | null {
try {
const active = JSON.parse(readFileSync(activeFile(), 'utf8')) as { version?: unknown };
const version = MapNavVersionSchema.parse(active.version);
const pack = foundPack(join(mapNavStoreFolder(), version, 'maps'), 'downloaded');
return pack?.info.version === version ? pack : null;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] the active pack is unusable:', error);
return null;
}
}
export function selectedMapNavPack(dataPath: string | null): MapNavPack | null {
return downloadedPack() ??
(dataPath ? foundPack(join(dataPath, 'map-nav', 'maps'), 'local') : null) ??
foundPack(bundledResourcePaths().bundledMapNavFolder, 'bundled');
}
/** Commit a verified map directory, then switch the pointer used by new launches. */
export async function activateMapNavPack(version: string, stagedFolder?: string): Promise<void> {
const store = mapNavStoreFolder();
if (stagedFolder !== undefined) {
await mkdir(store, { recursive: true });
await rename(stagedFolder, join(store, version));
}
await writeJsonAtomic(activeFile(), { version });
}
export async function deactivateMapNavPack(): Promise<void> {
await rm(activeFile(), { force: true });
}
@@ -0,0 +1,145 @@
import { lstat, mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { app } from 'electron';
import {
comparePackVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519,
} from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { AppUpdateProgress } from '@shared/schemas/app-update.ts';
import {
MapNavReleaseManifestSchema, mapNavSignaturePayload, type ActiveMapNav, type MapNavApplyResult,
type MapNavCheck, type MapNavReleaseManifest,
} from '@shared/schemas/map-nav-pack.ts';
import { getSettings } from '../config/settings-store.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { packUpdateProblem } from '../patch-pack/pack-update.ts';
import {
readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset,
} from '../patch-pack/release-assets.ts';
import {
newestProjectRelease, projectReleaseVersion, withReleaseSources, type PackReleaseFiles,
} from '../patch-pack/release-feed.ts';
import { extractMapNavArchive, verifyMapNavFolder } from './map-nav-archive.ts';
import {
activateMapNavPack, deactivateMapNavPack, mapNavStoreFolder, needsMapNavLauncherUpdate, selectedMapNavPack,
} from './map-nav-store.ts';
let updating = false;
async function duringMapNavUpdate<T>(update: () => Promise<T>): Promise<T> {
if (updating) throw new AppError('map_nav_update_busy');
updating = true;
try {
return await update();
} finally {
updating = false;
}
}
export async function activeMapNav(): Promise<ActiveMapNav> {
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const useLab = !app.isPackaged && settings.developerMode;
const dataPath = (useLab ? settings.labDataPath : null) ?? record?.dataPath ?? null;
return selectedMapNavPack(dataPath)?.info ?? null;
}
function isNewer(version: string, active: ActiveMapNav): boolean {
return !active?.version || comparePackVersions(version, active.version) > 0;
}
async function signedManifest(files: PackReleaseFiles, key: string): Promise<MapNavReleaseManifest> {
const signal = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
const [bytes, signature] = await Promise.all([
readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, signal, files.source),
readReleaseAsset(files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, signal, files.source),
]);
const decoder = new TextDecoder('utf-8', { fatal: true });
if (!verifyEd25519(mapNavSignaturePayload(bytes), decoder.decode(signature), key)) {
throw new PatchPackError('signature', 'The map pack manifest signature does not match.');
}
const manifest = MapNavReleaseManifestSchema.parse(JSON.parse(decoder.decode(bytes)));
if (manifest.version !== files.version) throw new PatchPackError('contents', 'The signed map pack version does not match the release.');
return manifest;
}
export async function checkMapNavUpdate(): Promise<MapNavCheck> {
const active = await activeMapNav();
const key = packSigningPublicKey();
if (!key) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
try {
const offer = await withReleaseSources(async (source) => {
const files = await newestProjectRelease('mapNav', active?.version ?? null, source);
return files ? { files, manifest: await signedManifest(files, key) } : null;
});
if (!offer) return { status: 'up_to_date', active, latest: null, problem: null };
const { files, manifest } = offer;
const latest = {
version: manifest.version, gameVersions: manifest.gameVersions, minAppVersion: manifest.minAppVersion,
publishedAt: files.publishedAt, mapCount: manifest.maps.length, size: manifest.archive.size,
};
const status = !isNewer(manifest.version, active) ? 'up_to_date'
: needsMapNavLauncherUpdate(manifest) ? 'needs_app_update' : 'available';
return { status, active, latest, problem: null };
} catch (error) {
console.warn('[map-nav] update check failed:', error);
return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) };
}
}
async function installMapNav(
files: PackReleaseFiles, manifest: MapNavReleaseManifest, report: (progress: AppUpdateProgress) => void,
): Promise<void> {
const root = mapNavStoreFolder();
const installed = join(root, manifest.version);
const existing = await lstat(installed).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
return null;
});
if (existing) {
if (!existing.isDirectory()) throw new PatchPackError('contents', 'The destination for this map pack is not a directory.');
await verifyMapNavFolder(installed, manifest);
await activateMapNavPack(manifest.version);
return;
}
await mkdir(root, { recursive: true });
const staging = await mkdtemp(join(await realpath(root), '.map-nav-install-'));
try {
const zip = join(staging, 'maps.zip');
await stageReleaseAsset(files.zipUrl, files.source, manifest.archive, zip, report);
const folder = await extractMapNavArchive(zip, staging, manifest);
await activateMapNavPack(manifest.version, folder);
} finally {
await rm(staging, { recursive: true, force: true }).catch((error: unknown) =>
console.warn('[map-nav] could not remove the installation staging directory:', error));
}
}
export function applyMapNavUpdate(version: string, report: (progress: AppUpdateProgress) => void): Promise<MapNavApplyResult> {
return duringMapNavUpdate(async () => {
const key = packSigningPublicKey();
if (!key) return { ok: false, problem: 'no_signing_key' };
if (!isNewer(version, await activeMapNav())) return { ok: false, problem: 'up_to_date' };
try {
const installed = await withReleaseSources(async (source) => {
const files = await projectReleaseVersion('mapNav', version, source);
const manifest = await signedManifest(files, key);
if (needsMapNavLauncherUpdate(manifest)) return false;
await installMapNav(files, manifest, report);
return true;
});
if (!installed) return { ok: false, problem: 'needs_app_update' };
return { ok: true, active: await activeMapNav() };
} catch (error) {
console.warn('[map-nav] update failed:', error);
return { ok: false, problem: packUpdateProblem(error) };
}
});
}
export function useLocalMapNav(): Promise<ActiveMapNav> {
return duringMapNavUpdate(async () => {
await deactivateMapNavPack();
return activeMapNav();
});
}
@@ -42,7 +42,7 @@ export async function checkPackUpdate(): Promise<PackCheck> {
return { status, active, latest: release(found), problem: null };
} catch (error) {
console.warn('[patch-pack] update check failed:', error);
return { status: 'failed', active, latest: null, problem: problemOf(error) };
return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) };
}
}
@@ -69,7 +69,7 @@ export async function applyPackUpdate(version: string): Promise<PackApplyResult>
return { ok: true, active: activePatchSet() };
} catch (error) {
console.warn('[patch-pack] update failed:', error);
return { ok: false, problem: problemOf(error) };
return { ok: false, problem: packUpdateProblem(error) };
}
}
@@ -110,7 +110,7 @@ function isNewer(candidate: string, active: string | null): boolean {
return active === null || comparePackVersions(candidate, active) > 0;
}
function problemOf(error: unknown): PackProblem {
export function packUpdateProblem(error: unknown): PackProblem {
if (error instanceof ReleasePageLimitError) return 'page_limit';
if (error instanceof FeedUnreachableError) return 'network';
if (error instanceof PatchPackError) {
@@ -1,4 +1,9 @@
import type { Readable } from 'node:stream';
import { createHash } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { mkdir, rename, unlink } from 'node:fs/promises';
import { dirname } from 'node:path';
import { Transform, type Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { net, type IncomingMessage } from 'electron';
import { PatchPackError } from '@wto/patcher';
import type { ReleaseSource } from './release-feed.ts';
@@ -85,3 +90,50 @@ export async function readReleaseAsset(
}
return Buffer.concat(chunks);
}
/** Stream a large, signed asset to disk and install the file only after its size and hash match. */
export async function stageReleaseAsset(
url: URL, source: ReleaseSource, file: { readonly size: number; readonly sha256: string }, target: string,
report: (progress: { received: number; total: number }) => void,
): Promise<void> {
const partial = target + '.partial';
const deadline = AbortSignal.timeout(30 * 60_000);
const hash = createHash('sha256');
let received = 0;
let reportedAt = 0;
try {
await mkdir(dirname(target), { recursive: true });
await removePartial(partial);
const response = await requestReleaseAsset(url, deadline, source);
const monitor = new Transform({
transform(chunk: Buffer, _encoding, done) {
received += chunk.length;
if (received > file.size) {
done(new PatchPackError('size', 'The download is larger than its signed size.'));
return;
}
hash.update(chunk);
if (received === file.size || Date.now() - reportedAt >= 200) {
reportedAt = Date.now();
report({ received, total: file.size });
}
done(null, chunk);
},
});
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
if (received !== file.size) throw new FeedUnreachableError('The update download is incomplete.');
if (hash.digest('hex') !== file.sha256) throw new PatchPackError('signature', 'The download does not match the signed release.');
await rename(partial, target);
} catch (error) {
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
throw error;
} finally {
await removePartial(partial).catch((error: unknown) => console.warn('[release-assets] removing a partial download failed:', error));
}
}
async function removePartial(path: string): Promise<void> {
await unlink(path).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
});
}
@@ -8,6 +8,7 @@ import {
} from '@wto/patcher';
import { z } from 'zod';
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
import { MAP_NAV_TAG_PREFIX, MapNavVersionSchema, mapNavReleaseFiles } from '@shared/schemas/map-nav-pack.ts';
import { releaseRepositoryUrl } from '@shared/update-source.ts';
import { getSettings } from '../config/settings-store.ts';
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
@@ -45,6 +46,7 @@ export interface PackReleaseFiles {
interface ReleaseByChannel {
launcher: LauncherRelease;
pack: PackReleaseFiles;
mapNav: PackReleaseFiles;
}
type ReleaseChannel = keyof ReleaseByChannel;
@@ -170,7 +172,7 @@ export async function projectReleaseVersion<Channel extends ReleaseChannel>(
async function readProjectReleases(source: ReleaseSource): Promise<ReleaseListing> {
const tuning = patchPackTuning();
const versions: ReleaseVersions = { launcher: new Map(), pack: new Map() };
const versions: ReleaseVersions = { launcher: new Map(), pack: new Map(), mapNav: new Map() };
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
const url = new URL(source.feed);
url.searchParams.set('per_page', String(tuning.releasePageSize));
@@ -222,11 +224,16 @@ function collectReleases(
continue;
}
const version = packVersionOfTag(tag);
const mapNav = tag.startsWith(MAP_NAV_TAG_PREFIX);
const channel = mapNav ? 'mapNav' : 'pack';
const version = mapNav ? MapNavVersionSchema.safeParse(tag.slice(MAP_NAV_TAG_PREFIX.length)).data : packVersionOfTag(tag);
if (!version) continue;
const pack = packRelease(release, version, tag, source);
if (pack) versions.pack.set(pack.version, pack);
else if (!incomplete.pack || comparePackVersions(version, incomplete.pack) > 0) incomplete.pack = version;
const pack = packRelease(release, version, tag, source, mapNav ? mapNavReleaseFiles(version) : packFileNames(version));
if (pack) versions[channel].set(pack.version, pack);
else {
const partial = incomplete[channel];
if (!partial || comparePackVersions(version, partial) > 0) incomplete[channel] = version;
}
}
}
@@ -274,10 +281,12 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
};
}
function packRelease(release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null {
function packRelease(
release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource,
names: ReturnType<typeof packFileNames>,
): PackReleaseFiles | null {
if (!Array.isArray(release['assets'])) return null;
const urls = assetUrls(release['assets'], tag, source);
const names = packFileNames(version);
const zipUrl = urls.get(names.zip);
const signatureUrl = urls.get(names.signature);
const manifestUrl = urls.get(names.manifest);
@@ -21,6 +21,8 @@ export interface ResourcePaths {
readonly modTemplates: string;
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
readonly groundAiScripts: string;
/** Location of the baseline navigation maps, when included with the launcher. */
readonly bundledMapNavFolder: string;
}
export function resourcePaths(): ResourcePaths {
@@ -38,6 +40,7 @@ export function bundledResourcePaths(): ResourcePaths {
appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
bundledMapNavFolder: join(process.resourcesPath, 'map-nav', 'maps'),
};
}
// The app path is apps/launcher; the repository is two levels up.
@@ -48,6 +51,7 @@ export function bundledResourcePaths(): ResourcePaths {
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
groundAiScripts: join(repository, 'game-ai', 'ground'),
bundledMapNavFolder: join(repository, 'build', 'map-nav', 'maps'),
};
}
@@ -0,0 +1,30 @@
import { AppError } from '@shared/errors.ts';
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
import { offlineClientCacheFolders, requireSaveCopy, runSaveTask, saveLocation, writeSave } from './manage-saves.ts';
import { captureSave, restoreDirectory, saveBackup } from './save-archive.ts';
export async function getSaveCrews(copyId: string, userId: string, country: string | undefined): Promise<SaveCrewView> {
const copy = await requireSaveCopy(copyId);
return await runSaveTask({ operation: 'readCrews', ...saveLocation(copy), userId, country }) as SaveCrewView;
}
export async function previewSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit): Promise<SaveCrewPreview> {
const copy = await requireSaveCopy(copyId);
return await runSaveTask({ operation: 'previewCrew', ...saveLocation(copy), userId, country, edit }) as SaveCrewPreview;
}
export async function changeSaveCrew(copyId: string, userId: string, country: string, edit: SaveCrewEdit, token: string): Promise<SaveCrewView> {
return writeSave(async () => {
const copy = await requireSaveCopy(copyId);
const before = await captureSave(copy, userId);
const cacheFolders = edit.action === 'close' ? await offlineClientCacheFolders(userId) : [];
if (edit.action === 'close') await saveBackup(copy, userId, 'crew', before);
try {
return await runSaveTask({ operation: 'editCrew', ...saveLocation(copy), userId, country, edit, token, cacheFolders }) as SaveCrewView;
} catch (error) {
const refused = error instanceof AppError && ['save_not_found', 'save_crew_invalid', 'save_crew_slot_limit', 'save_crew_stale'].includes(error.code);
if (!refused) await restoreDirectory(copy, userId, before);
throw error;
}
});
}
@@ -15,6 +15,8 @@ import { localServerReady } from '../launch/local-server.ts';
import { forwardProcessOutput } from '../launch/process-output.ts';
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
export { location as saveLocation, offlineClientCacheFolders, requireCopy as requireSaveCopy, run as runSaveTask, write as writeSave };
let writing = false;
export function saveWriteInProgress(): boolean {
@@ -191,8 +193,18 @@ export async function restoreSaveBackup(copyId: string, userId: string, name: st
await getSaveDetails(copyId, userId);
const archive = await archivedBackup(copy, userId, name);
await validateProfile(archive, copy);
await saveBackup(copy, userId, 'restore');
const before = await captureSave(copy, userId);
const cacheFolders = name.split('.')[1] === 'crew' ? await offlineClientCacheFolders(userId) : undefined;
await saveBackup(copy, userId, 'restore', before);
await restoreDirectory(copy, userId, archive);
if (cacheFolders) {
try {
await run({ operation: 'syncRestoredCrewPresets', ...location(copy), userId, cacheFolders });
} catch (error) {
await restoreDirectory(copy, userId, before);
throw error;
}
}
return getSaveDetails(copyId, userId);
});
}
@@ -178,11 +178,11 @@ export async function backupList(copy: InstallRecord, userId: string): Promise<S
return backups;
}
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type']): Promise<void> {
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type'], archive?: SaveArchive): Promise<void> {
const root = await backupFolder(copy, userId);
await mkdir(root, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), await captureSave(copy, userId));
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), archive ?? await captureSave(copy, userId));
if (type === 'launch') {
const older = (await backupList(copy, userId)).filter((backup) => backup.type === 'launch').slice(10);
for (const backup of older) await rm(join(root, backup.name), { force: true });
@@ -10,6 +10,7 @@ export interface BuildRequest {
readonly patches: string;
readonly networkHookLibrary: string;
readonly groundAiScripts: string;
readonly mapNavFolder?: string;
readonly decalCache?: string;
readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[];
@@ -105,6 +105,7 @@ function build(request: BuildRequest): void {
placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging,
...(request.mapNavFolder === undefined ? {} : { mapNavFolder: request.mapNavFolder }),
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
@@ -1,4 +1,5 @@
import type { AppErrorCode } from '@shared/errors.ts';
import type { SaveCrewEdit, SaveCrewPreview, SaveCrewView } from '@shared/schemas/crew-saves.ts';
import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts';
interface Location {
@@ -23,9 +24,13 @@ export type SaveTask = Location & (
}
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
| { readonly operation: 'readCrews'; readonly userId: string; readonly country: string | undefined }
| { readonly operation: 'previewCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit }
| { readonly operation: 'editCrew'; readonly userId: string; readonly country: string; readonly edit: SaveCrewEdit; readonly token: string; readonly cacheFolders: readonly string[] }
| { readonly operation: 'syncRestoredCrewPresets'; readonly userId: string; readonly cacheFolders: readonly string[] }
| { readonly operation: 'remove'; readonly userId: string }
| { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean }
| { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string }
);
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | SaveCrewView | SaveCrewPreview | { userId: string } | Uint8Array | SaveAvatarChoices | string | null;
export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode };
@@ -1,7 +1,12 @@
import type { MessageEvent } from 'electron';
import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server';
import { editSaveCrew, previewSaveCrewEdit, readSaveCrews, syncRestoredCrewPresets } from '@wto/server';
import type { SaveTask, SaveReply } from './save-protocol.ts';
const CREW_ERRORS = {
'not-found': 'save_not_found', invalid: 'save_crew_invalid', 'slot-limit': 'save_crew_slot_limit', stale: 'save_crew_stale',
} as const;
function execute(task: SaveTask): SaveReply {
switch (task.operation) {
case 'list':
@@ -37,6 +42,23 @@ function execute(task: SaveTask): SaveReply {
const result = editSaveResearch(task, task.userId, task.branch, task.action);
return result ? { ok: true, result } : { ok: false, error: 'save_operation_failed' };
}
case 'readCrews': {
const result = readSaveCrews(task, task.userId, task.country);
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
}
case 'previewCrew': {
const result = previewSaveCrewEdit(task, task.userId, task.country, task.edit);
if ('preview' in result && result.preview) return { ok: true, result: result.preview };
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
}
case 'editCrew': {
const result = editSaveCrew(task, task.userId, task.country, task.edit, task.token, task.cacheFolders);
if ('view' in result && result.view) return { ok: true, result: result.view };
return { ok: false, error: CREW_ERRORS[result.error ?? 'invalid'] };
}
case 'syncRestoredCrewPresets':
syncRestoredCrewPresets(task.dataFolder, task.userId, task.cacheFolders);
return { ok: true, result: null };
case 'remove':
return new AccountStore(task.dataFolder).remove(task.userId)
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
+3
View File
@@ -38,6 +38,7 @@ import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts';
import { useAppUpdate } from './shell/useAppUpdate.ts';
import { useMapNavPack } from './shell/useMapNavPack.ts';
import { usePatchPack } from './shell/usePatchPack.ts';
import { useErrorMessage } from './useErrorMessage.ts';
@@ -69,6 +70,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
const [route, setRoute] = useState<Route>(START_ROUTE);
// The setting as the window opened: turning it on later does not check right away.
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
const mapNavPack = useMapNavPack(initialSettings.checkPatchPacksOnStart, report);
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
const maintenance = useCopyMaintenance(report);
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
@@ -159,6 +161,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
launcherVersion={info.version}
supportedVersions={supported}
patchPack={patchPack}
mapNavPack={mapNavPack}
appUpdate={appUpdate}
loggingEnabled={settings.loggingEnabled}
onError={report}
@@ -362,6 +362,7 @@
"overview": "Overview",
"battles": "Battle history",
"vehicles": "Vehicles and research",
"crews": "Crews",
"official": "Import online data",
"backup": "Backup and restore"
},
@@ -396,6 +397,37 @@
"Helicopter": "Helicopters"
}
},
"crews": {
"noCountries": "This client has no countries available for crew editing.",
"loadFailed": "Could not load crews. Check the error message and reopen this page.",
"slots": "{{open}} of {{max}} crew slots open",
"minimum": "Keep at least {{count}} slots open.",
"group": "Crew {{number}}",
"noVehicle": "Empty slot",
"opened": "Open",
"closed": "Closed",
"open": "Reopen slot",
"close": "Close slot",
"add": "Open a new slot",
"editLevel": "Set level",
"type": "Crew type",
"types": { "air": "Air", "tank": "Ground", "ship": "Naval", "human": "Infantry" },
"target": "Target crew level",
"levelRange": "Available levels {{min}} to {{max}}.",
"preview": "Preview changes",
"previewLevel": "Target level {{target}}. The game will show these levels after saving.",
"levelChange": "{{type}} {{before}} → {{after}}",
"noChange": "The current level is the closest available level to the target.",
"confirmClose": "Closing this slot backs up the save. Reopen it to restore its skills, training and qualifications.",
"removeVehicle": "{{vehicle}} will leave its hangar slot.",
"confirmOpen": "Return this crew to the hangar.",
"confirmRestoreVehicle": "Return this crew and {{vehicle}} to the hangar.",
"confirmAdd": "Open an empty crew slot for this country.",
"affectedPresets": "Affected lineup presets",
"preset": "Lineup {{number}}",
"emptyPreset": "No vehicles after closing",
"saved": "Crew changes saved. They will take effect the next time you start the game."
},
"official": {
"auto": "Automatic import",
"autoHint": "Locates local online data read-only, copies it into the offline folder, and imports from the copy without modifying the online files.",
@@ -441,7 +473,8 @@
"manual": "Manual backup",
"launch": "Before launch",
"restore": "Before restore",
"import": "Before import"
"import": "Before import",
"crew": "Before closing a crew slot"
}
},
"create": "Create save",
@@ -529,12 +562,17 @@
"loadout": "Ground AI spawn ammunition",
"commander": "Commander & role quotas",
"macro": "Macro capture & SPAA",
"stateMachine": "Hull state machine & repair",
"stateMachine": "Hull actions & repair",
"perception": "Visual perception & exposure",
"tactics": "Situational awareness & memory",
"estimation": "Lead estimation & aim bias",
"threat": "Threat assessment",
"turret": "Turret attention",
"behavior": "Hull behavior",
"fireControl": "Fire control & fire gate",
"navigation": "Driving & navigation",
"navEngine": "Map navigation mesh & path costs",
"pathFollow": "Path following & unstick",
"crowd": "Spacing & crowd dispersal",
"terrain": "Terrain & ridge limits",
"runtime": "Tick cadence & diagnostics"
@@ -545,12 +583,17 @@
"loadout": "Ready-rack carry count and primary/secondary shell split",
"commander": "Role percentages by game mode, flank lanes, rally and recall",
"macro": "Opening split, cap occupancy, death zones and SPAA positioning",
"stateMachine": "Short halts, reload cover retreat, angling, repositioning and repair",
"stateMachine": "Short halts, reload cover retreat, repositioning and repair",
"perception": "Foliage transparency, exposure accumulation and decay",
"tactics": "Vision range, audio detection, radio sharing and target memory",
"estimation": "Sample-based velocity lead, exit watch and natural shot spread",
"fireControl": "Range bands, speed gates, barrel settle and ballistic safety",
"navigation": "Drive backend, corner braking, pivot turns and unstick reverse",
"threat": "How dangerous each discovered enemy is: distance, aim, line of sight and recent hits",
"turret": "Where the turret looks without a target: threats, cues and scanning along the route",
"behavior": "Scores of the hull behaviors, commitment, facing the main threat and driving backwards",
"fireControl": "Hit probability and fire threshold, autocannon bursts, secondary weapons, barrel settle and ballistic safety",
"navigation": "Drive backend, pivot turns and tactical reverse",
"navEngine": "Baked map navigation packs, their fallback, and path costs per surface for tracked and wheeled vehicles",
"pathFollow": "Replanning, lookahead steering, corner and arrival braking, narrow passages, bumper rays, passing stopped vehicles and wrecks, giving way, three-level unstick and temporary path costs",
"crowd": "Personal space and ally cluster dispersal",
"terrain": "Climb/drop slope limits, water depth and ridge peek caps",
"runtime": "Script update intervals and telemetry logging"
@@ -609,17 +652,12 @@
"enemySpawnAvoidM": "Enemy spawn avoidance distance"
},
"stateMachine": {
"preaimAngleDeg": "Moving pre-aim angle threshold",
"movingShotWaitSec": "Time to attempt a moving shot before halting",
"shortHaltMaxSec": "Short halt max duration",
"shortHaltCooldownSec": "Short halt cooldown",
"turnLaunchSpeedMps": "Turn launch target speed",
"coverMinDistM": "Cover search min distance",
"coverMaxDistM": "Cover search max distance",
"coverRetreatBudgetSec": "Reload cover retreat max duration",
"reloadAdvanceAngleDeg": "Reload zigzag advance angle",
"hullAngleTriggerDeg": "Hull angling trigger angle",
"hullAngleTargetDeg": "Target hull angling offset",
"maxTotalHaltSec": "Max cumulative halt before reposition",
"stalemateMissShots": "Ineffective shots before reposition",
"stalemateNoShotHalts": "No-shot halts before reposition",
@@ -635,13 +673,18 @@
"normalSpotSec": "Normal exposure spot time",
"farSpotSec": "Long-range exposure spot time",
"decayPerSec": "Exposure decay rate per second",
"frontConeHalfDeg": "Forward vision cone half-angle",
"peripheralCloseM": "Close peripheral spot distance"
"gunFovHalfDeg": "Gun sight half-angle",
"nearAwareM": "Close all-round awareness range",
"nearArcDeg": "Close awareness arc around the barrel",
"midAwareM": "Medium awareness range (barrel front hemisphere)",
"nearSpotMul": "Close awareness spotting time multiplier",
"midSpotMul": "Commander awareness spotting time multiplier",
"lookAroundSec": "Look-around interval",
"lookAroundHoldSec": "Look-around duration",
"discoverScore": "Exposure at which an enemy counts as discovered"
},
"tactics": {
"visionRangeM": "Max visual detection range",
"visionFovDeg": "Vision field of view",
"peripheralRangeM": "Peripheral detection range",
"engineAudioRangeM": "Engine audio hearing range",
"shotAudioRangeM": "Gunshot audio hearing range",
"radioShareRangeM": "Allied radio sharing range",
@@ -659,24 +702,95 @@
"leadErrorFrac": "Lead estimation error fraction",
"maxBiasM": "Max per-opportunity aim bias"
},
"threat": {
"rangeScaleM": "Distance at which danger halves",
"discoveredMul": "Danger multiplier until seen clearly",
"aimConeDeg": "Cone in which an enemy counts as aiming at the bot",
"notAimingMul": "Danger multiplier when not aiming at the bot",
"unseenMul": "Danger multiplier when the bot is out of its sight",
"hitMemorySec": "How long a hit raises the shooter's danger",
"hitMul": "Danger multiplier after a hit"
},
"turret": {
"minDwellSec": "Minimum time on a chosen look direction",
"switchMargin": "Extra danger needed to turn from the engaged target",
"scanArcDeg": "Scan arc either side of the route",
"scanPeriodSec": "Scan sweep period",
"fixedMountYawSpanDeg": "Max yaw range for hull-mounted guns"
},
"behavior": {
"scoreIntervalSec": "Behavior scoring interval",
"advanceHoldSec": "Advance commitment",
"engageHoldSec": "Engage while moving commitment",
"haltHoldSec": "Short halt commitment",
"coverHoldSec": "Take cover commitment",
"repositionHoldSec": "Reposition commitment",
"postHoldSec": "Hold position commitment",
"disperseHoldSec": "Disperse commitment",
"targetValueWeight": "Weight of a viable shot while moving",
"nearThreatHaltBonus": "Short-halt bonus under a close threat",
"switchMargin": "Extra score needed to switch behavior",
"advanceScore": "Score: advance along the order route",
"engageScore": "Score: engage on the move",
"urgencyWeight": "Score shift by order urgency",
"haltScore": "Score: short halt for a shot",
"crossfirePenalty": "Short-halt penalty per extra enemy aiming at the bot",
"coverScore": "Score: pull back to cover to reload",
"coverDangerWeight": "Cover score added by threat danger",
"coverOffensivePenalty": "Cover penalty on an urgent attack",
"coverRetrySec": "Wait before searching for cover again after none was found",
"repositionScore": "Score: change firing position when the engagement is stuck",
"holdScore": "Score: hold the post, watch the last exit or wait at the rally point",
"disperseScore": "Score: spread out of a crowd",
"urgentSpeedKeep": "Share of march speed an urgent bot keeps when slowing for a shot",
"hullAngleDeg": "Hull angle to the main threat",
"faceToleranceDeg": "Facing tolerance while standing",
"faceMinDanger": "Threat danger needed to face it",
"reverseTravelAngleDeg": "Threat angle off the travel direction for driving backwards",
"reverseMaxTurnDistM": "Max distance to the next turn or route end when reversing",
"reverseMinSpeedMps": "Lowest top reverse speed for driving backwards",
"reverseHoldSec": "Minimum time between switching forwards and backwards"
},
"fireControl": {
"maxEngageRangeM": "Max engagement range",
"closeRangeM": "Close range band threshold",
"midRangeM": "Mid range band threshold",
"longRangeM": "Long range band threshold",
"midSlowSpeedRatio": "Mid-range fire-on-move speed ratio",
"midSlowMaxMps": "Mid-range fire-on-move speed cap",
"closeRangeMaxSpeedKmh": "Moving-fire speed cap at the close-range boundary",
"pointBlankMaxSpeedKmh": "Moving-fire speed cap at point blank",
"stopSpeedMaxMps": "Stopped speed threshold",
"longRangeWindowSec": "Long-range clear LOS window",
"baseAlignDeg": "Base gun alignment tolerance",
"closeHitRadiusM": "Close-range hit acceptance radius",
"barrelSettleDegSec": "Max aim error drift outside close range",
"closeSettleHoldSec": "Close-range settle hold time",
"settleHoldSec": "Standard settle hold time",
"unstabilizedStopSpeedMps": "Unstabilized stop speed cap",
"stabilizedCreepSpeedMps": "Stabilized creep fire speed cap",
"aimErrorDeg": "Crew aim error (spread)",
"moveErrDegPerMps": "Aim error per m/s of own speed",
"turnErrDegPerDegSec": "Aim error per deg/s of hull turn",
"stabErrFactor": "Motion error factor with a stabilizer",
"targetHalfHeightM": "Half height of a fully visible target",
"fireThreshold": "Base hit probability needed to fire",
"minFireThreshold": "Lowest fire threshold",
"aimingThresholdBonus": "Threshold drop when the target aims at the bot",
"closeThresholdBonus": "Threshold drop at point blank",
"enemyReloadThresholdBonus": "Threshold drop after the target fired",
"enemyReloadSec": "How long a target counts as reloading after it fired",
"fleetingThresholdBonus": "Threshold drop for a target about to slip away",
"fleetingLateralMps": "Crossing speed of a slipping-away target",
"fleetingLookAheadSec": "Look-ahead for losing line of sight",
"reloadThresholdPenalty": "Fire-threshold increase for long reloads",
"longReloadSec": "Reload time for the full threshold penalty",
"lowAmmoRounds": "Ammunition count below which shots are conserved",
"lowAmmoThresholdPenalty": "Fire-threshold increase with little ammunition",
"aimSkill": "Crew skill for aiming spread",
"autocannonMinShotsPerSec": "Minimum firing rate for automatic cannons (rounds/s)",
"retreatThresholdPenalty": "Threshold rise while pulling back to cover",
"minShotIntervalSec": "Minimum main-gun shot interval",
"autocannonAimSlack": "Autocannon aim slack (times target size)",
"burstSec": "Burst length",
"burstPauseSec": "Pause between bursts",
"autocannonReloadDetectSec": "Autocannon not-ready time that counts as a reload",
"auxWeapons": "Fire secondary and coaxial weapons",
"auxMaxRangeM": "Secondary and coaxial weapon range",
"auxFireAtArmor": "Coaxial weapons also fire at non-light vehicles",
"friendlyCorridorM": "Friendly fire corridor width",
"ballisticStepMaxM": "Ballistic occlusion step length",
"ballisticSweepRadiusM": "Ballistic sphere sweep radius",
@@ -688,15 +802,89 @@
"steerSign": "Steering input polarity",
"deadEchoSec": "Dead-echo detection timeout",
"controlTimeoutSec": "Native control release timeout",
"cornerBrakeAccel": "Corner braking deceleration",
"movingFireSpeedRampMps": "Speed error for full throttle or braking while firing on the move",
"pivotAngleDeg": "Neutral pivot turn angle threshold",
"stuckWindowSec": "Stuck detection window",
"stuckMinMoveM": "Stuck min movement distance",
"unstickReverseSec": "Unstick reverse duration",
"tacticalReverseDistM": "Tactical reverse max distance",
"tacticalReverseMaxSec": "Tactical reverse max duration"
},
"navEngine": {
"enabled": "Use map navigation packs",
"allowFallback": "Fall back to the old pathing for the battle when a pack is missing or broken",
"snapRadiusM": "Max distance from a path's start or goal to the mesh",
"goalSnapRadiusM": "Max distance a path goal may be moved onto the mesh",
"pathBudgetMsPerFrame": "Path search time per frame",
"trafficCostPerPath": "Team traffic · extra path cost per teammate route",
"trafficCostMaxMul": "Team traffic · max path cost multiplier",
"trafficHoldSec": "Team traffic · how long a planned route counts",
"cornerOffsetM": "Distance path corners keep from the walls they turn around"
},
"navCostsTracked": {
"road": "Tracked · road cost",
"bridge": "Tracked · bridge cost",
"ground": "Tracked · open ground cost",
"rough": "Tracked · steep or rocky ground cost",
"forest": "Tracked · forest cost",
"crushable": "Tracked · crushable obstacle cost",
"shallowWater": "Tracked · shallow water cost",
"chokepoint": "Tracked · chokepoint multiplier"
},
"navCostsWheeled": {
"road": "Wheeled · road cost",
"bridge": "Wheeled · bridge cost",
"ground": "Wheeled · open ground cost",
"rough": "Wheeled · steep or rocky ground cost",
"forest": "Wheeled · forest cost",
"crushable": "Wheeled · crushable obstacle cost",
"shallowWater": "Wheeled · shallow water cost",
"chokepoint": "Wheeled · chokepoint multiplier"
},
"pathFollow": {
"replanIntervalSec": "Regular path replanning interval",
"replanGoalMoveM": "Goal movement that triggers a new path",
"offCorridorReplanM": "Distance off the path that triggers a new path",
"lookaheadTimeSec": "Lookahead time at current speed",
"trackedLookaheadMinM": "Tracked · min lookahead distance",
"trackedLookaheadMaxM": "Tracked · max lookahead distance",
"wheeledLookaheadMinM": "Wheeled · min lookahead distance",
"wheeledLookaheadMaxM": "Wheeled · max lookahead distance",
"cornerAngleDeg": "Path corner angle that needs slowing down",
"cornerLateralAccelMps2": "Allowed sideways acceleration in corners",
"cornerBrakeDecelMps2": "Braking deceleration before corners and the destination",
"arriveRadiusM": "Arrival radius at the destination",
"arriveMinSpeedMps": "Min speed while approaching the destination",
"narrowWallMarginM": "Room to the mesh edge below which a passage counts as narrow",
"narrowSpeedMps": "Speed cap in narrow passages",
"bumperRayM": "Front corner ray length",
"bumperStopM": "Stop distance before an obstacle hit by the front rays",
"bumperBlockSec": "Time blocked before an obstacle is reported",
"trafficTtcSec": "Vehicle collision look-ahead time",
"yieldWaitMaxSec": "Max wait while giving way in narrow passages",
"stationarySpeedMps": "Speed below which a vehicle counts as an obstacle",
"passMarginM": "Gap kept between hulls when passing",
"passSpeedMps": "Speed cap while passing an obstacle",
"blockWaitSec": "Wait before a blocked passage is marked and replanned",
"blockTtlSec": "Blocked passage cost duration",
"contactGapM": "Gap to an obstacle that counts as contact",
"contactReverseSec": "Time in contact before backing off",
"contactRepeatSec": "Window in which a second contact counts as a repeat",
"stuckWindowSec": "Stuck detection window",
"stuckMinProgressM": "Min progress within the stuck window",
"unstickReverseM": "Unstick reverse distance",
"unstickReverseSec": "Unstick reverse max duration",
"unstickRepeatSec": "Time within which a repeated stuck escalates",
"unstickMaxAttempts": "Unstick attempts before giving up the order",
"jamRadiusM": "Jam cost radius",
"jamCostMul": "Jam path cost multiplier",
"jamTtlSec": "Jam cost duration",
"giveUpRadiusM": "Given-up place cost radius",
"giveUpCostMul": "Given-up place path cost multiplier",
"rubbleRadiusM": "Fresh obstacle cost radius",
"rubbleCostMul": "Fresh obstacle path cost multiplier",
"rubbleTtlSec": "Fresh obstacle cost duration",
"wreckRadiusM": "Wreck cost radius",
"wreckCostMul": "Wreck path cost multiplier",
"wreckTtlSec": "Wreck cost duration"
},
"crowd": {
"personalSpaceM": "Personal spacing distance",
"clusterRadiusM": "Ally cluster detection radius",
@@ -721,7 +909,14 @@
},
"diagnostics": {
"telemetry": "Enable AI telemetry logs",
"telemetryIntervalSec": "Telemetry logging interval"
"telemetryIntervalSec": "Telemetry logging interval",
"battleStats": "Log battle statistics for comparing builds",
"statsLogIntervalSec": "Battle statistics logging interval",
"statsSampleSec": "Statistics sampling interval per bot",
"statsSampleRangeM": "Range of the nearest-enemy statistics sample",
"statsRearArcDeg": "Rear arc counted as showing the rear",
"trace": "Log the AI replay trace",
"traceIntervalSec": "AI replay trace sampling interval"
}
},
"shared": "These settings apply to all saves in this client.",
@@ -745,11 +940,11 @@
"appUpdates": "Launcher updates",
"appUpdatesToggle": "Check for launcher updates at start",
"patchPacks": "Adaptation pack updates",
"patchPacksHint": "After a game update, patches for the new version are released as an adaptation pack.",
"patchPacksHint": "Checks for new client patches and ground AI map packs.",
"updateMirror": "Update mirror repository",
"updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.",
"updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.",
"patchPacksToggle": "Check for a new adaptation pack at start",
"patchPacksToggle": "Check for adaptation pack updates at start",
"windowClose": "When closing the window",
"windowQuit": "Quit launcher",
"windowTray": "Minimize to system tray",
@@ -870,6 +1065,26 @@
"up_to_date": "Up to date: there is no adaptation pack to download."
}
},
"mapNav": {
"title": "Map adaptation packs",
"hint": "The selected navigation and cover data takes effect the next time you start the game.",
"missing": "No map pack installed",
"source": {
"bundled": "Included with the launcher",
"downloaded": "Downloaded map pack",
"local": "Local map pack"
},
"mapCount_one": "{{count}} map",
"mapCount_other": "{{count}} maps",
"deactivate": "Stop using downloaded pack",
"downloading": "Downloading map pack…",
"installing": "Verifying and activating map pack…",
"upToDate": "Up to date (latest map pack {{version}}).",
"noneReleased": "No map pack has been released yet.",
"available_one": "Map pack {{version}} is available · {{count}} map · {{size}}.",
"available_other": "Map pack {{version}} is available · {{count}} maps · {{size}}.",
"compatible": "Baked for game versions {{versions}}."
},
"update": {
"title": "Launcher update",
"check": "Launcher version check",
@@ -1032,6 +1247,7 @@
"errors": {
"app_update_unavailable": "There is no launcher update available to install.",
"app_update_busy": "A launcher update operation is already in progress.",
"map_nav_update_busy": "A map pack update is already in progress.",
"app_update_launcher_busy": "Close the game and local server and finish any client or save operations before updating.",
"app_update_download_failed": "The launcher installer could not be downloaded and verified. See the launcher log.",
"app_update_installer_invalid": "The installer failed verification. Download it again.",
@@ -1045,6 +1261,9 @@
"save_not_found": "The selected save could not be found.",
"save_read_only": "Saves are read-only while the game or local server is running.",
"save_operation_failed": "The save operation failed. See the launcher log.",
"save_crew_invalid": "Invalid crew, crew type or target level. Check the selected save and level range.",
"save_crew_slot_limit": "This change exceeds the available crew slot range for the country.",
"save_crew_stale": "The save changed after the preview. Preview the change again before saving.",
"save_login_invalid": "Enter a login without spaces.",
"save_login_exists": "An account with this login already exists.",
"save_password_invalid": "Enter a password.",
@@ -362,6 +362,7 @@
"overview": "概览",
"battles": "战绩",
"vehicles": "载具与研发",
"crews": "乘员组",
"official": "导入在线版数据",
"backup": "备份与还原"
},
@@ -396,6 +397,37 @@
"Helicopter": "直升机"
}
},
"crews": {
"noCountries": "当前客户端没有可编辑的国家。",
"loadFailed": "无法读取乘员组。请查看错误提示后重新打开此页面。",
"slots": "已开放 {{open}} / {{max}} 组",
"minimum": "至少保留 {{count}} 个开放槽位。",
"group": "第 {{number}} 乘员组",
"noVehicle": "空槽",
"opened": "已开放",
"closed": "已关闭",
"open": "重新开放",
"close": "关闭槽位",
"add": "开放新槽位",
"editLevel": "设置等级",
"type": "兵种",
"types": { "air": "空军", "tank": "陆军", "ship": "海军", "human": "步兵" },
"target": "目标乘员等级",
"levelRange": "可设置 {{min}} 到 {{max}} 级。",
"preview": "预览变更",
"previewLevel": "目标 {{target}} 级,保存后游戏会显示以下等级。",
"levelChange": "{{type}} {{before}} → {{after}}",
"noChange": "当前等级已经是最接近目标的可达等级。",
"confirmClose": "关闭前会备份存档。重新开放时可恢复该组的技能、训练和专精。",
"removeVehicle": "当前载具「{{vehicle}}」将移出机库槽位。",
"confirmOpen": "将这组乘员恢复到机库。",
"confirmRestoreVehicle": "将这组乘员和载具「{{vehicle}}」恢复到机库。",
"confirmAdd": "为当前国家开放一个空乘员槽位。",
"affectedPresets": "受影响的编队预设",
"preset": "编队 {{number}}",
"emptyPreset": "关闭后没有载具",
"saved": "乘员组已保存,下次启动游戏后生效。"
},
"official": {
"auto": "自动导入",
"autoHint": "只读查找本机在线版数据并复制到离线目录后再导入,不修改在线版原文件。",
@@ -441,7 +473,8 @@
"manual": "手动备份",
"launch": "启动前自动备份",
"restore": "还原前自动备份",
"import": "导入前自动备份"
"import": "导入前自动备份",
"crew": "关闭乘员槽位前"
}
},
"create": "新建存档",
@@ -529,12 +562,17 @@
"loadout": "陆战 AI 出生携弹",
"commander": "指挥层与分路配额",
"macro": "宏观占点与防空",
"stateMachine": "单车状态机与掩体维修",
"stateMachine": "车体动作与掩体维修",
"perception": "视觉感知与曝光",
"tactics": "态势感知与目标记忆",
"estimation": "目击测速与瞄准偏差",
"threat": "威胁评估",
"turret": "炮塔关注方向",
"behavior": "车体行为",
"fireControl": "火控与开火许可",
"navigation": "机动与寻路控制",
"navEngine": "地图导航网格与通行代价",
"pathFollow": "跟路驾驶与脱困",
"crowd": "编队间距与避让",
"terrain": "地形与棱线约束",
"runtime": "运行频率与诊断"
@@ -545,12 +583,17 @@
"loadout": "待发架携弹量与主/副弹种分配",
"commander": "各模式进攻 / 侧翼 / 架枪比例、集结与回防",
"macro": "开局分兵、占点人数、死亡区规避与防空站位",
"stateMachine": "短停预算、装填回缩、摆角、换位与受损维修",
"stateMachine": "短停预算、装填回缩、换位与受损维修",
"perception": "植被透光、曝光累计速度与衰减",
"tactics": "视距、听觉发现范围、电台共享与记忆时长",
"estimation": "本车目击测速、守出口时长与自然散布",
"fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤",
"navigation": "底层驱动方式、转向刹车与脱困倒车",
"threat": "每个已发现敌人的危险程度:距离、是否瞄着本车、视线与最近是否命中本车",
"turret": "没有目标时炮塔看哪里:威胁、线索与沿路线扫视",
"behavior": "车体各行为的得分、承诺时间、车头对主威胁与倒车跟路",
"fireControl": "命中概率与开火门槛、机炮点射、副武器、炮管稳定和弹道安全",
"navigation": "驱动方式、原地转向与战术倒车",
"navEngine": "离线地图导航包的启用与降级,以及履带 / 轮式车在各类地表上的寻路代价",
"pathFollow": "重新寻路、前瞻跟路、弯道与到达前减速、窄路限速、车头射线、绕过停车和残骸、会车让路、三级脱困与临时寻路代价",
"crowd": "友军安全间距与扎堆疏散",
"terrain": "爬坡 / 下坡角度、涉水深度与探头限制",
"runtime": "脚本刷新间隔与调试遥测日志"
@@ -609,17 +652,12 @@
"enemySpawnAvoidM": "敌方出生点规避距离"
},
"stateMachine": {
"preaimAngleDeg": "行进预瞄角度阈值",
"movingShotWaitSec": "转入短停前尝试行进射击的时间",
"shortHaltMaxSec": "单次短停最长时间",
"shortHaltCooldownSec": "短停冷却时间",
"turnLaunchSpeedMps": "甩弯起步目标车速",
"coverMinDistM": "掩体搜索最小距离",
"coverMaxDistM": "掩体搜索最大距离",
"coverRetreatBudgetSec": "装填回缩掩体最长用时",
"reloadAdvanceAngleDeg": "装填折线跃进偏角",
"hullAngleTriggerDeg": "触发车体摆角阈值",
"hullAngleTargetDeg": "车体目标摆角",
"maxTotalHaltSec": "累计停留强制换位上限",
"stalemateMissShots": "无伤害连射触发换位发数",
"stalemateNoShotHalts": "未开火短停触发换位次数",
@@ -635,13 +673,18 @@
"normalSpotSec": "常规曝光用时",
"farSpotSec": "远距曝光用时",
"decayPerSec": "失联曝光每秒衰减率",
"frontConeHalfDeg": "前向主视锥半角",
"peripheralCloseM": "近身余光发现距离"
"gunFovHalfDeg": "瞄准镜视野半角",
"nearAwareM": "近距环视感知距离",
"nearArcDeg": "以炮口为基准的近距感知角度",
"midAwareM": "中距感知距离(炮口前半球)",
"nearSpotMul": "近距感知看清耗时倍数",
"midSpotMul": "车长感知看清耗时倍数",
"lookAroundSec": "环视间隔",
"lookAroundHoldSec": "环视持续时间",
"discoverScore": "曝光积分达到多少算发现"
},
"tactics": {
"visionRangeM": "最大视觉索敌距离",
"visionFovDeg": "视野总张角",
"peripheralRangeM": "外围余光索敌距离",
"engineAudioRangeM": "引擎声听觉距离",
"shotAudioRangeM": "炮声听觉距离",
"radioShareRangeM": "友军电台报点共享距离",
@@ -659,24 +702,95 @@
"leadErrorFrac": "提前量误差比例",
"maxBiasM": "单次射击最大偏移上限"
},
"threat": {
"rangeScaleM": "危险度减半的距离",
"discoveredMul": "尚未看清时的危险度倍数",
"aimConeDeg": "算作对方瞄着本车的夹角范围",
"notAimingMul": "对方没瞄着本车时的危险度倍数",
"unseenMul": "本车不在对方视线内时的危险度倍数",
"hitMemorySec": "被命中后提高射手危险度的时长",
"hitMul": "被命中后的危险度倍数"
},
"turret": {
"minDwellSec": "选定的观察方向至少保持的时间",
"switchMargin": "从交战目标转向其他威胁所需高出的危险度",
"scanArcDeg": "沿路线向两侧扫视的角度",
"scanPeriodSec": "扫视一个来回的时长",
"fixedMountYawSpanDeg": "判定为固定炮座时的最大水平射界"
},
"behavior": {
"scoreIntervalSec": "行为打分间隔",
"advanceHoldSec": "推进承诺时间",
"engageHoldSec": "交战推进承诺时间",
"haltHoldSec": "短停射击承诺时间",
"coverHoldSec": "退入掩体承诺时间",
"repositionHoldSec": "换位承诺时间",
"postHoldSec": "守位承诺时间",
"disperseHoldSec": "疏散承诺时间",
"targetValueWeight": "运动中有机会命中的权重",
"nearThreatHaltBonus": "近距威胁下的短停加分",
"switchMargin": "切换行为所需高出的分数",
"advanceScore": "得分:沿任务路线推进",
"engageScore": "得分:交战推进",
"urgencyWeight": "任务紧迫度对得分的影响",
"haltScore": "得分:短停射击",
"crossfirePenalty": "每多一个瞄着本车的敌人,短停扣分",
"coverScore": "得分:退入掩体装填",
"coverDangerWeight": "威胁危险度对掩体得分的加成",
"coverOffensivePenalty": "紧急进攻时掩体扣分",
"coverRetrySec": "找不到掩体后再次搜索的间隔",
"repositionScore": "得分:交战僵持时换位",
"holdScore": "得分:守位、盯出口或在集结点等待",
"disperseScore": "得分:拥挤疏散",
"urgentSpeedKeep": "紧急任务为射击减速时保留的行军速度比例",
"hullAngleDeg": "车头对主威胁的倾角",
"faceToleranceDeg": "停车时朝向容差",
"faceMinDanger": "需要车头对准的威胁危险度下限",
"reverseTravelAngleDeg": "威胁偏离行进方向多少度时倒车跟路",
"reverseMaxTurnDistM": "倒车时距下一拐点或路线终点的最远距离",
"reverseMinSpeedMps": "倒车跟路所需的最低倒车极速",
"reverseHoldSec": "前进与倒车切换的最短间隔"
},
"fireControl": {
"maxEngageRangeM": "最大交战开火距离",
"closeRangeM": "近距交战分界距离",
"midRangeM": "中距交战分界距离",
"longRangeM": "远距交战分界距离",
"midSlowSpeedRatio": "中距行进射击最高车速比",
"midSlowMaxMps": "中距行进射击最高车速",
"closeRangeMaxSpeedKmh": "近距分界处行进射击最高车速",
"pointBlankMaxSpeedKmh": "贴身时行进射击最高车速",
"stopSpeedMaxMps": "停稳判定最高车速",
"longRangeWindowSec": "远距连续射界观察窗",
"baseAlignDeg": "主炮对准允许角误差",
"closeHitRadiusM": "近距命中判定半径",
"barrelSettleDegSec": "近距以外瞄准误差最大变化速度",
"closeSettleHoldSec": "近距稳定保持时间",
"settleHoldSec": "常规稳定保持时间",
"unstabilizedStopSpeedMps": "无稳定器停稳车速上限",
"stabilizedCreepSpeedMps": "带稳定器慢速射击上限",
"aimErrorDeg": "炮手瞄准误差(散布)",
"moveErrDegPerMps": "本车每 m/s 车速增加的瞄准误差",
"turnErrDegPerDegSec": "车体每 °/s 转向增加的瞄准误差",
"stabErrFactor": "有稳定器时行进误差的倍数",
"targetHalfHeightM": "完全露出的目标半高",
"fireThreshold": "开火所需的基础命中概率",
"minFireThreshold": "开火门槛下限",
"aimingThresholdBonus": "目标瞄着本车时门槛降低",
"closeThresholdBonus": "贴脸时门槛降低(近距内按距离过渡)",
"enemyReloadThresholdBonus": "目标刚开过火时门槛降低",
"enemyReloadSec": "目标开火后视为装填中的时长",
"fleetingThresholdBonus": "目标即将离开视线时门槛降低",
"fleetingLateralMps": "视为即将离开视线的横穿速度",
"fleetingLookAheadSec": "预判视线遮挡的时间",
"reloadThresholdPenalty": "装填时间长时提高开火门槛",
"longReloadSec": "开火门槛加满时的装填时间",
"lowAmmoRounds": "开始节省弹药的剩余发数",
"lowAmmoThresholdPenalty": "剩余弹药少时提高开火门槛",
"aimSkill": "影响瞄点散布的炮手技能",
"autocannonMinShotsPerSec": "识别机炮的最低射速(发/秒)",
"retreatThresholdPenalty": "退入掩体途中的门槛升高",
"minShotIntervalSec": "主炮最短开火间隔",
"autocannonAimSlack": "机炮放宽倍数(目标尺寸的倍数)",
"burstSec": "点射时长",
"burstPauseSec": "点射间隔",
"autocannonReloadDetectSec": "机炮持续未就绪多久算换弹",
"auxWeapons": "使用副炮和并列武器",
"auxMaxRangeM": "副炮和并列武器的射击距离",
"auxFireAtArmor": "并列武器也可以向非轻型车辆开火",
"friendlyCorridorM": "友军弹道禁射走廊宽度",
"ballisticStepMaxM": "弹道硬遮挡检测步长",
"ballisticSweepRadiusM": "弹道扫掠半径",
@@ -688,15 +802,89 @@
"steerSign": "转向输入方向",
"deadEchoSec": "无响应回声判定时长",
"controlTimeoutSec": "原生控制超时归还时长",
"cornerBrakeAccel": "弯道减速制动强度",
"movingFireSpeedRampMps": "行进射击时全油门或全制动对应的速度差",
"pivotAngleDeg": "原地中性转向角度阈值",
"stuckWindowSec": "卡死检测窗口时长",
"stuckMinMoveM": "卡死判定最小位移",
"unstickReverseSec": "脱困倒车持续时长",
"tacticalReverseDistM": "战术倒车最大距离",
"tacticalReverseMaxSec": "战术倒车最长时长"
},
"navEngine": {
"enabled": "启用地图导航包",
"allowFallback": "缺少或损坏时整局退回旧寻路",
"snapRadiusM": "起终点吸附到导航网格的最大距离",
"goalSnapRadiusM": "目标点吸附到导航网格的最远距离",
"pathBudgetMsPerFrame": "每帧寻路计算时间上限",
"trafficCostPerPath": "同队分流 · 每条队友路线增加的寻路代价",
"trafficCostMaxMul": "同队分流 · 寻路代价最高倍率",
"trafficHoldSec": "同队分流 · 规划出的路线计入多久",
"cornerOffsetM": "路线拐点离所绕墙角的距离"
},
"navCostsTracked": {
"road": "履带车 · 道路代价",
"bridge": "履带车 · 桥面代价",
"ground": "履带车 · 普通地面代价",
"rough": "履带车 · 陡坡碎石代价",
"forest": "履带车 · 树林代价",
"crushable": "履带车 · 可碾压障碍代价",
"shallowWater": "履带车 · 浅滩涉水代价",
"chokepoint": "履带车 · 窄口代价倍率"
},
"navCostsWheeled": {
"road": "轮式车 · 道路代价",
"bridge": "轮式车 · 桥面代价",
"ground": "轮式车 · 普通地面代价",
"rough": "轮式车 · 陡坡碎石代价",
"forest": "轮式车 · 树林代价",
"crushable": "轮式车 · 可碾压障碍代价",
"shallowWater": "轮式车 · 浅滩涉水代价",
"chokepoint": "轮式车 · 窄口代价倍率"
},
"pathFollow": {
"replanIntervalSec": "定时重新寻路间隔",
"replanGoalMoveM": "目标移动多远后重新寻路",
"offCorridorReplanM": "偏离路线多远后重新寻路",
"lookaheadTimeSec": "按当前车速前瞻的时间",
"trackedLookaheadMinM": "履带车 · 最短前瞻距离",
"trackedLookaheadMaxM": "履带车 · 最长前瞻距离",
"wheeledLookaheadMinM": "轮式车 · 最短前瞻距离",
"wheeledLookaheadMaxM": "轮式车 · 最长前瞻距离",
"cornerAngleDeg": "需要减速的路线拐角角度",
"cornerLateralAccelMps2": "过弯允许的横向加速度",
"cornerBrakeDecelMps2": "弯前和到达前的减速度",
"arriveRadiusM": "到达目标的判定半径",
"arriveMinSpeedMps": "接近目标时的最低车速",
"narrowWallMarginM": "离网格边缘小于多少算窄路",
"narrowSpeedMps": "窄路限速",
"bumperRayM": "车头两侧射线长度",
"bumperStopM": "车头射线碰到障碍时的停车距离",
"bumperBlockSec": "被挡多久后上报障碍",
"trafficTtcSec": "车辆碰撞预判时间",
"yieldWaitMaxSec": "窄路让路最长等待时间",
"stationarySpeedMps": "车速低于多少算作障碍物",
"passMarginM": "绕行时与对方车体保持的间距",
"passSpeedMps": "绕行障碍时的限速",
"blockWaitSec": "无路可绕时等待多久后标记并重新寻路",
"blockTtlSec": "被堵路段代价持续时间",
"contactGapM": "离障碍多近算作顶上",
"contactReverseSec": "顶上多久后倒车",
"contactRepeatSec": "多久内在同一处再顶上算作反复顶上",
"stuckWindowSec": "卡住检测窗口时长",
"stuckMinProgressM": "检测窗口内的最小前进距离",
"unstickReverseM": "脱困倒车距离",
"unstickReverseSec": "脱困倒车最长时长",
"unstickRepeatSec": "多久内再次卡住就升级处理",
"unstickMaxAttempts": "放弃当前任务前的脱困次数",
"jamRadiusM": "堵车点代价半径",
"jamCostMul": "堵车点寻路代价倍率",
"jamTtlSec": "堵车点代价持续时间",
"giveUpRadiusM": "放弃地点代价半径",
"giveUpCostMul": "放弃地点寻路代价倍率",
"rubbleRadiusM": "新障碍代价半径",
"rubbleCostMul": "新障碍寻路代价倍率",
"rubbleTtlSec": "新障碍代价持续时间",
"wreckRadiusM": "残骸代价半径",
"wreckCostMul": "残骸寻路代价倍率",
"wreckTtlSec": "残骸代价持续时间"
},
"crowd": {
"personalSpaceM": "单车安全个人空间",
"clusterRadiusM": "扎堆检测半径",
@@ -721,7 +909,14 @@
},
"diagnostics": {
"telemetry": "输出 AI 诊断遥测日志",
"telemetryIntervalSec": "遥测日志输出间隔"
"telemetryIntervalSec": "遥测日志输出间隔",
"battleStats": "输出用于版本对比的每局统计",
"statsLogIntervalSec": "每局统计的输出间隔",
"statsSampleSec": "每辆车的统计抽查间隔",
"statsSampleRangeM": "统计抽查最近敌人的范围",
"statsRearArcDeg": "算作车尾对敌的后方扇区角度",
"trace": "输出 AI 回放轨迹",
"traceIntervalSec": "回放轨迹的采样间隔"
}
},
"shared": "这些数值适用于此客户端的全部存档。",
@@ -745,11 +940,11 @@
"appUpdates": "启动器本体更新",
"appUpdatesToggle": "启动时检查本体更新",
"patchPacks": "适配包更新",
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布。",
"patchPacksHint": "检查客户端补丁和陆战 AI 地图适配包的更新。",
"updateMirror": "备用更新仓库",
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
"patchPacksToggle": "启动时检查有没有新的适配包",
"patchPacksToggle": "启动时检查适配包更新",
"windowClose": "关闭窗口时",
"windowQuit": "退出启动器",
"windowTray": "最小化到系统托盘",
@@ -870,6 +1065,26 @@
"up_to_date": "已是最新,没有需要下载的适配包。"
}
},
"mapNav": {
"title": "地图适配包",
"hint": "所选的导航和掩体数据将在下次启动游戏时生效。",
"missing": "未安装地图适配包",
"source": {
"bundled": "启动器自带",
"downloaded": "已下载的地图包",
"local": "本地地图包"
},
"mapCount_one": "{{count}} 张地图",
"mapCount_other": "{{count}} 张地图",
"deactivate": "停用已下载的地图包",
"downloading": "正在下载地图适配包…",
"installing": "正在校验并启用地图适配包…",
"upToDate": "已是最新(最新的地图包是 {{version}})。",
"noneReleased": "还没有发布地图适配包。",
"available_one": "地图包 {{version}} 可用 · {{count}} 张地图 · {{size}}。",
"available_other": "地图包 {{version}} 可用 · {{count}} 张地图 · {{size}}。",
"compatible": "生成时使用的游戏版本为 {{versions}}。"
},
"update": {
"title": "本体更新",
"check": "检查本体版本",
@@ -1032,6 +1247,7 @@
"errors": {
"app_update_unavailable": "当前没有可安装的本体更新。",
"app_update_busy": "本体更新操作正在进行。",
"map_nav_update_busy": "地图适配包更新正在进行。",
"app_update_launcher_busy": "请在游戏退出、服务器关闭及客户端和存档操作完成后安装更新。",
"app_update_download_failed": "无法下载并验证本体安装包。请查看启动器日志。",
"app_update_installer_invalid": "安装包校验失败。请重新下载。",
@@ -1045,6 +1261,9 @@
"save_not_found": "找不到所选存档。",
"save_read_only": "游戏或本地服务器运行期间存档为只读。",
"save_operation_failed": "存档操作失败。请查看启动器日志。",
"save_crew_invalid": "乘员组、兵种或目标等级无效。请核对当前存档和可用范围。",
"save_crew_slot_limit": "这项操作超出了该系可开放的槽位范围。",
"save_crew_stale": "预览后存档发生了变化。请重新预览再保存。",
"save_login_invalid": "登录账号不能包含空格。",
"save_login_exists": "该登录账号已注册。",
"save_password_invalid": "请输入密码。",
@@ -6,6 +6,8 @@ import { ipcInvoke } from '../../ipc.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { AppUpdateSection } from './AppUpdateSection.tsx';
import type { PatchPackState } from '../../shell/usePatchPack.ts';
import type { MapNavPackState } from '../../shell/useMapNavPack.ts';
import { MapNavPackSection } from './MapNavPackSection.tsx';
const HOMEPAGE_URL = 'https://wto-project.net';
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
@@ -14,13 +16,14 @@ interface AboutPageProps {
readonly launcherVersion: string;
readonly supportedVersions: readonly string[];
readonly patchPack: PatchPackState;
readonly mapNavPack: MapNavPackState;
readonly appUpdate: AppUpdateState;
readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void;
}
/** The launcher's version, the game versions it supports, updates, community links, log export, and the project statement. */
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
export function AboutPage({ launcherVersion, supportedVersions, patchPack, mapNavPack, appUpdate, loggingEnabled, onError }: AboutPageProps) {
const { t } = useTranslation();
return (
<Sheet title={t('nav.about')}>
@@ -36,6 +39,7 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
<div className="about-column">
<AppUpdateSection state={appUpdate} />
<PatchPackSection state={patchPack} />
<MapNavPackSection state={mapNavPack} />
</div>
<div className="about-column">
<HomepageSection />
@@ -0,0 +1,66 @@
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx';
import { formatBytes } from '../../format.ts';
import type { MapNavPackState } from '../../shell/useMapNavPack.ts';
export function MapNavPackSection({ state }: { readonly state: MapNavPackState }) {
const { t } = useTranslation();
const { active, busy, check, progress } = state;
const latest = check?.latest;
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.mapNav.title')}</h3>
<div className="about-card-actions">
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{t(busy === 'checking' ? 'about.pack.checking' : 'about.pack.checkButton')}
</button>
{active?.source === 'downloaded' && (
<button type="button" className="button" disabled={busy !== null} onClick={state.deactivate}>
{t('about.mapNav.deactivate')}
</button>
)}
</div>
</div>
<p className="about-card-meta">
<span className="about-card-label">{t('about.pack.current')}</span>
{' · '}
{active === undefined ? '…' : active === null ? t('about.mapNav.missing') : [
t('about.mapNav.source.' + active.source), active.version,
t('about.mapNav.mapCount', { count: active.mapCount }),
].filter(Boolean).join(' · ')}
</p>
<p className="small">{t('about.mapNav.hint')}</p>
{busy === 'applying' && (
<div role="status">
<p className="small">
{t(progress?.total && progress.received >= progress.total ? 'about.mapNav.installing' : 'about.mapNav.downloading')}
</p>
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
</div>
)}
{state.failure && <Notice tone="error"><p>{t('about.pack.applyFailed.' + state.failure)}</p></Notice>}
{busy !== 'checking' && check?.status === 'failed' && (
<Notice tone="error"><p>{t('about.pack.checkFailed.' + (check.problem ?? 'contents'))}</p></Notice>
)}
{busy !== 'checking' && check?.status === 'up_to_date' && (
<Notice tone="info"><p>{latest ? t('about.mapNav.upToDate', { version: latest.version }) : t('about.mapNav.noneReleased')}</p></Notice>
)}
{busy !== 'checking' && check?.status === 'needs_app_update' && latest && (
<Notice tone="warning"><p>{t('about.pack.needsAppUpdate', { version: latest.version, app: latest.minAppVersion })}</p></Notice>
)}
{busy !== 'checking' && check?.status === 'available' && latest && (
<Notice tone="info">
<p>{t('about.mapNav.available', { version: latest.version, count: latest.mapCount, size: formatBytes(latest.size) })}</p>
<p className="small">{t('about.mapNav.compatible', { versions: latest.gameVersions.join(', ') })}</p>
{busy !== 'applying' && (
<button type="button" className="button button-primary" disabled={busy !== null} onClick={() => state.apply(latest.version)}>
{t('about.pack.apply', { version: latest.version })}
</button>
)}
</Notice>
)}
</section>
);
}
@@ -0,0 +1,55 @@
import { useTranslation } from 'react-i18next';
import type { SaveCrewEdit, SaveCrewPreview } from '@shared/schemas/crew-saves.ts';
export interface PendingCrewChange {
readonly edit: SaveCrewEdit;
readonly preview: SaveCrewPreview;
}
interface Props {
readonly pending: PendingCrewChange;
readonly disabled: boolean;
readonly busy: boolean;
readonly onApply: () => void;
readonly onCancel: () => void;
}
export function SaveCrewChangePreview({ pending, disabled, busy, onApply, onCancel }: Props) {
const { t, i18n } = useTranslation();
const { edit, preview } = pending;
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
const format = new Intl.NumberFormat(i18n.language);
const vehicle = preview.vehicle[language];
const restored = preview.restoredVehicle[language];
const levels = preview.levels.filter(({ type, before, after }) => (edit.action === 'level' && type === edit.type) || before !== after);
return (
<div className="maintenance-confirm" aria-live="polite">
{edit.action === 'close' && <p>{t('saves.crews.confirmClose')}</p>}
{edit.action === 'close' && vehicle && <p>{t('saves.crews.removeVehicle', { vehicle })}</p>}
{edit.action === 'open' && <p>{restored ? t('saves.crews.confirmRestoreVehicle', { vehicle: restored }) : t('saves.crews.confirmOpen')}</p>}
{edit.action === 'add' && <p>{t('saves.crews.confirmAdd')}</p>}
{edit.action === 'level' && <p>{t('saves.crews.previewLevel', { target: format.format(edit.target) })}</p>}
{levels.length > 0 && <ul>{levels.map(({ type, before, after }) => (
<li key={type}>{t('saves.crews.levelChange', { type: t(`saves.crews.types.${type}`), before: format.format(before), after: format.format(after) })}</li>
))}</ul>}
{preview.presets.length > 0 && (
<>
<p>{t('saves.crews.affectedPresets')}</p>
<ul>{preview.presets.map(({ index, title, vehicle: assignment, empty }) => (
<li key={index}>
{title || t('saves.crews.preset', { number: index + 1 })}
{assignment[language] && ` · ${assignment[language]}`}
{empty && ` · ${t('saves.crews.emptyPreset')}`}
</li>
))}</ul>
</>
)}
{!preview.changed && <p>{t('saves.crews.noChange')}</p>}
<div className="copy-list-actions">
<button type="button" className="button" disabled={busy} onClick={onCancel}>{t('wizard.cancel')}</button>
<button type="button" className="button button-primary" disabled={disabled || !preview.changed} onClick={onApply}>{t('saves.apply')}</button>
</div>
</div>
);
}
@@ -0,0 +1,49 @@
import { useState, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import type { SaveCrewEdit, SaveCrewView } from '@shared/schemas/crew-saves.ts';
import { Row } from '../../components/Row.tsx';
type Level = SaveCrewView['crews'][number]['levels'][number];
interface Props {
readonly crewId: number;
readonly levels: readonly Level[];
readonly disabled: boolean;
readonly onPreview: (edit: SaveCrewEdit) => void;
readonly onChange: () => void;
}
export function SaveCrewLevelEditor({ crewId, levels, disabled, onPreview, onChange }: Props) {
const { t } = useTranslation();
const [type, setType] = useState(levels[0]?.type);
const [target, setTarget] = useState<string | null>(null);
const range = levels.find((level) => level.type === type);
if (!range) return null;
function submit(event: FormEvent<HTMLFormElement>): void {
event.preventDefault();
const value = Number(target);
if (!disabled && range && target?.trim() && Number.isFinite(value)) {
onPreview({ action: 'level', crewId, type: range.type, target: value });
}
}
return (
<form onSubmit={submit}>
<Row label={t('saves.crews.target')} hint={t('saves.crews.levelRange', { min: range.min, max: range.max })}>
<select className="select" aria-label={t('saves.crews.type')} value={range.type} disabled={disabled} onChange={(event) => {
setType(levels.find(({ type: value }) => value === event.target.value)?.type);
setTarget(null);
onChange();
}}>
{levels.map(({ type: value }) => <option key={value} value={value}>{t(`saves.crews.types.${value}`)}</option>)}
</select>
<input className="input" type="number" aria-label={t('saves.crews.target')} disabled={disabled} required step="any"
min={range.min} max={range.max} value={target ?? String(range.level)} onChange={(event) => { setTarget(event.target.value); onChange(); }} />
<button type="submit" className="button" disabled={disabled || target === null || !target.trim() || Number(target) === range.level}>
{t('saves.crews.preview')}
</button>
</Row>
</form>
);
}
@@ -0,0 +1,115 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { SaveCrewEdit, SaveCrewView } from '@shared/schemas/crew-saves.ts';
import { Row } from '../../components/Row.tsx';
import { ipcInvoke } from '../../ipc.ts';
import { SaveCrewChangePreview, type PendingCrewChange } from './SaveCrewChangePreview.tsx';
import { SaveCrewLevelEditor } from './SaveCrewLevelEditor.tsx';
interface Props {
readonly copyId: string;
readonly userId: string;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
}
function useCrewPanel({ copyId, userId, readOnly, onError }: Props) {
const [view, setView] = useState<SaveCrewView | null>(null);
const [busy, setBusy] = useState(false);
const [loadFailed, setLoadFailed] = useState(false);
const [saved, setSaved] = useState(false);
const [pending, setPending] = useState<PendingCrewChange | null>(null);
const keys = { copyId, userId };
const disabled = busy || readOnly;
useEffect(() => {
let mounted = true;
ipcInvoke('saves:crews', { copyId, userId }).then((next) => {
if (mounted) setView(next);
}).catch((error: unknown) => {
if (mounted) {
setLoadFailed(true);
onError(error);
}
});
return () => { mounted = false; };
}, [copyId, userId, onError]);
function run(action: () => Promise<void>): void {
setBusy(true);
setSaved(false);
setPending(null);
action().catch(onError).finally(() => setBusy(false));
}
function preview(edit: SaveCrewEdit): void {
const country = view?.selected;
if (!country || disabled) return;
run(async () => setPending({ edit, preview: await ipcInvoke('saves:previewCrew', { ...keys, country, edit }) }));
}
function apply(onApplied: () => void): void {
const country = view?.selected;
if (!pending || !country || disabled) return;
run(async () => {
setView(await ipcInvoke('saves:editCrew', { ...keys, country, edit: pending.edit, token: pending.preview.token }));
setSaved(true);
onApplied();
});
}
return {
view, busy, disabled, loadFailed, saved, pending, preview, apply,
cancel: () => setPending(null),
chooseCountry: (country: string) => run(async () => setView(await ipcInvoke('saves:crews', { ...keys, country }))),
};
}
export function SaveCrews(props: Props) {
const { t, i18n } = useTranslation();
const { view, busy, disabled, loadFailed, saved, pending, chooseCountry, preview, apply, cancel } = useCrewPanel(props);
const [editing, setEditing] = useState<number | null>(null);
const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en';
const format = new Intl.NumberFormat(i18n.language);
if (!view) return <p className="lead">{t(loadFailed ? 'saves.crews.loadFailed' : 'saves.loading')}</p>;
if (!view.selected) return <p className="lead">{t('saves.crews.noCountries')}</p>;
const confirmation = pending && <SaveCrewChangePreview pending={pending} disabled={disabled} busy={busy} onApply={() => apply(() => setEditing(null))} onCancel={cancel} />;
return (
<>
<Row label={t('saves.tree.country')}>
<select className="select" aria-label={t('saves.tree.country')} value={view.selected} disabled={busy} onChange={(event) => {
setEditing(null);
chooseCountry(event.target.value);
}}>
{view.countries.map(({ id, name }) => <option value={id} key={id}>{name[language]}</option>)}
</select>
</Row>
<Row label={t('saves.crews.slots', { open: view.activeCount, max: view.max })} hint={t('saves.crews.minimum', { count: view.min })}>
<button type="button" className="button" disabled={disabled || !view.canAdd} onClick={() => preview({ action: 'add' })}>{t('saves.crews.add')}</button>
</Row>
{props.readOnly && <p className="small">{t('saves.readOnly')}</p>}
{saved && <p className="small" role="status">{t('saves.crews.saved')}</p>}
{pending?.edit.action === 'add' && confirmation}
<div className="save-crews-list">
{view.crews.map((crew, index) => (
<div key={crew.id}>
<Row label={t('saves.crews.group', { number: index + 1 })} hint={crew.vehicle[language] || t('saves.crews.noVehicle')}>
<span>{t(crew.open ? 'saves.crews.opened' : 'saves.crews.closed')}</span>
<span className="small">{crew.levels.map(({ type, level }) => `${t(`saves.crews.types.${type}`)} ${format.format(level)}`).join(' · ')}</span>
<button type="button" className="button" disabled={disabled || !crew.canToggle} onClick={() => preview({ action: crew.open ? 'close' : 'open', crewId: crew.id })}>
{t(crew.open ? 'saves.crews.close' : 'saves.crews.open')}
</button>
{crew.levels.length > 0 && <button type="button" className="button" disabled={disabled} aria-expanded={editing === crew.id} onClick={() => {
setEditing(editing === crew.id ? null : crew.id);
cancel();
}}>{t('saves.crews.editLevel')}</button>}
</Row>
{editing === crew.id && <SaveCrewLevelEditor crewId={crew.id} levels={crew.levels} disabled={disabled} onPreview={preview} onChange={cancel} />}
{pending?.edit.action !== 'add' && pending?.preview.crewId === crew.id && confirmation}
</div>
))}
</div>
</>
);
}
@@ -10,6 +10,7 @@ import { OfficialSaveImport } from './OfficialSaveImport.tsx';
import { SaveAvatarField } from './SaveAvatarField.tsx';
import { SaveResearch } from './SaveResearch.tsx';
import { SaveBackups } from './SaveBackups.tsx';
import { SaveCrews } from './SaveCrews.tsx';
interface SavesPageProps {
readonly copy: InstallRecord;
@@ -314,6 +315,7 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
)}
{section === 'backup' && <SaveBackups key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} onRestored={updateDetails} />}
{section === 'vehicles' && <SaveResearch key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
{section === 'crews' && <SaveCrews key={save.userId} copyId={copy.id} userId={save.userId} readOnly={readOnly} onError={onError} />}
</Sheet>
);
}
@@ -54,7 +54,7 @@ function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningP
if (est.watchMaxSec < est.watchMinSec || est.velStableSpanSec <= est.velSampleMinSpanSec) return false;
const fc = mergeSection(effective.fireControl, patch.fireControl);
if (fc.midRangeM <= fc.closeRangeM || fc.longRangeM <= fc.midRangeM) return false;
return fc.pointBlankMaxSpeedKmh >= fc.closeRangeMaxSpeedKmh;
return fc.minFireThreshold <= fc.fireThreshold;
}
export function BotTuningPanel({ data, saving, onSave }: Props) {
@@ -68,6 +68,9 @@ function int(
};
}
/** Surfaces of the baked navigation mesh, in the order of tuning/ground-ai.jsonc navCosts*. */
const NAV_COST_FIELDS = ['road', 'bridge', 'ground', 'rough', 'forest', 'crushable', 'shallowWater', 'chokepoint'] as const;
export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
{
id: 'general',
@@ -155,17 +158,12 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
defaultOpen: false,
customOnly: true,
fields: [
num('stateMachine', 'preaimAngleDeg', 1, 30, '°'),
num('stateMachine', 'movingShotWaitSec', 0.25, 5, 's'),
num('stateMachine', 'shortHaltMaxSec', 0.5, 12, 's'),
num('stateMachine', 'shortHaltCooldownSec', 0.5, 20, 's'),
num('stateMachine', 'turnLaunchSpeedMps', 0.5, 6, 'm/s'),
num('stateMachine', 'coverMinDistM', 2, 30, 'm'),
num('stateMachine', 'coverMaxDistM', 6, 80, 'm'),
num('stateMachine', 'coverRetreatBudgetSec', 1.5, 20, 's'),
num('stateMachine', 'reloadAdvanceAngleDeg', 0, 45, '°'),
num('stateMachine', 'hullAngleTriggerDeg', 15, 75, '°'),
num('stateMachine', 'hullAngleTargetDeg', 0, 35, '°'),
num('stateMachine', 'maxTotalHaltSec', 3, 40, 's'),
int('stateMachine', 'stalemateMissShots', 1, 8),
int('stateMachine', 'stalemateNoShotHalts', 1, 6),
@@ -186,8 +184,15 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('perception', 'normalSpotSec', 0.1, 3, 's'),
num('perception', 'farSpotSec', 0.3, 6, 's'),
num('perception', 'decayPerSec', 0.2, 10),
num('perception', 'frontConeHalfDeg', 10, 90, '°'),
num('perception', 'peripheralCloseM', 30, 250, 'm'),
num('perception', 'gunFovHalfDeg', 5, 90, '°'),
num('perception', 'nearAwareM', 30, 400, 'm'),
num('perception', 'nearArcDeg', 90, 360, '°'),
num('perception', 'midAwareM', 100, 1500, 'm'),
num('perception', 'nearSpotMul', 1, 5),
num('perception', 'midSpotMul', 1, 6),
num('perception', 'lookAroundSec', 2, 60, 's'),
num('perception', 'lookAroundHoldSec', 0.2, 5, 's'),
num('perception', 'discoverScore', 0.05, 0.95),
],
},
{
@@ -196,8 +201,6 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
customOnly: true,
fields: [
num('tactics', 'visionRangeM', 200, 3500, 'm'),
num('tactics', 'visionFovDeg', 40, 180, '°'),
num('tactics', 'peripheralRangeM', 30, 800, 'm'),
num('tactics', 'engineAudioRangeM', 10, 250, 'm'),
num('tactics', 'shotAudioRangeM', 50, 1200, 'm'),
num('tactics', 'radioShareRangeM', 50, 1500, 'm'),
@@ -221,6 +224,70 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('estimation', 'maxBiasM', 0, 6, 'm'),
],
},
{
id: 'threat',
defaultOpen: false,
customOnly: true,
fields: [
num('threat', 'rangeScaleM', 50, 3000, 'm'),
num('threat', 'discoveredMul', 0, 1),
num('threat', 'aimConeDeg', 5, 90, '°'),
num('threat', 'notAimingMul', 0, 1),
num('threat', 'unseenMul', 0, 1),
num('threat', 'hitMemorySec', 0, 60, 's'),
num('threat', 'hitMul', 1, 5),
],
},
{
id: 'turret',
defaultOpen: false,
customOnly: true,
fields: [
num('turret', 'minDwellSec', 0, 5, 's'),
num('turret', 'switchMargin', 0, 3),
num('turret', 'scanArcDeg', 0, 180, '°'),
num('turret', 'scanPeriodSec', 1, 30, 's'),
num('turret', 'fixedMountYawSpanDeg', 0, 180, '°'),
],
},
{
id: 'behavior',
defaultOpen: false,
customOnly: true,
fields: [
num('behavior', 'scoreIntervalSec', 0.1, 3, 's'),
num('behavior', 'advanceHoldSec', 0, 10, 's'),
num('behavior', 'engageHoldSec', 0, 10, 's'),
num('behavior', 'haltHoldSec', 0, 10, 's'),
num('behavior', 'coverHoldSec', 0, 10, 's'),
num('behavior', 'repositionHoldSec', 0, 10, 's'),
num('behavior', 'postHoldSec', 0, 10, 's'),
num('behavior', 'disperseHoldSec', 0, 10, 's'),
num('behavior', 'targetValueWeight', 0, 1),
num('behavior', 'nearThreatHaltBonus', 0, 1),
num('behavior', 'switchMargin', 0, 1),
num('behavior', 'advanceScore', 0, 1),
num('behavior', 'engageScore', 0, 1),
num('behavior', 'urgencyWeight', 0, 1),
num('behavior', 'haltScore', 0, 1),
num('behavior', 'crossfirePenalty', 0, 1),
num('behavior', 'coverScore', 0, 1),
num('behavior', 'coverDangerWeight', 0, 1),
num('behavior', 'coverOffensivePenalty', 0, 1),
num('behavior', 'coverRetrySec', 0.5, 30, 's'),
num('behavior', 'repositionScore', 0, 1),
num('behavior', 'holdScore', 0, 1),
num('behavior', 'disperseScore', 0, 1),
num('behavior', 'urgentSpeedKeep', 0, 1),
num('behavior', 'hullAngleDeg', 0, 45, '°'),
num('behavior', 'faceToleranceDeg', 3, 60, '°'),
num('behavior', 'faceMinDanger', 0, 2),
num('behavior', 'reverseTravelAngleDeg', 60, 180, '°'),
num('behavior', 'reverseMaxTurnDistM', 0, 200, 'm'),
num('behavior', 'reverseMinSpeedMps', 0.5, 10, 'm/s'),
num('behavior', 'reverseHoldSec', 0, 20, 's'),
],
},
{
id: 'fireControl',
defaultOpen: false,
@@ -230,19 +297,41 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('fireControl', 'closeRangeM', 30, 250, 'm'),
num('fireControl', 'midRangeM', 100, 600, 'm'),
num('fireControl', 'longRangeM', 300, 1500, 'm'),
num('fireControl', 'midSlowSpeedRatio', 0.1, 1),
num('fireControl', 'midSlowMaxMps', 1, 15, 'm/s'),
num('fireControl', 'closeRangeMaxSpeedKmh', 3.6, 100, 'km/h'),
num('fireControl', 'pointBlankMaxSpeedKmh', 3.6, 100, 'km/h'),
num('fireControl', 'stopSpeedMaxMps', 0.1, 2, 'm/s'),
num('fireControl', 'longRangeWindowSec', 1, 15, 's'),
num('fireControl', 'baseAlignDeg', 0.1, 3, '°'),
num('fireControl', 'closeHitRadiusM', 0.25, 2.2, 'm'),
num('fireControl', 'barrelSettleDegSec', 0.2, 12, '°/s'),
num('fireControl', 'closeSettleHoldSec', 0.02, 0.5, 's'),
num('fireControl', 'settleHoldSec', 0.05, 1.5, 's'),
num('fireControl', 'unstabilizedStopSpeedMps', 0.1, 3, 'm/s'),
num('fireControl', 'stabilizedCreepSpeedMps', 1.5, 15, 'm/s'),
num('fireControl', 'aimErrorDeg', 0.01, 2, '°'),
num('fireControl', 'moveErrDegPerMps', 0, 3, '°'),
num('fireControl', 'turnErrDegPerDegSec', 0, 0.5),
num('fireControl', 'stabErrFactor', 0.02, 1),
num('fireControl', 'targetHalfHeightM', 0.3, 2, 'm'),
num('fireControl', 'fireThreshold', 0.05, 0.95),
num('fireControl', 'minFireThreshold', 0.01, 0.9),
num('fireControl', 'aimingThresholdBonus', 0, 0.5),
num('fireControl', 'closeThresholdBonus', 0, 0.5),
num('fireControl', 'enemyReloadThresholdBonus', 0, 0.5),
num('fireControl', 'enemyReloadSec', 0, 15, 's'),
num('fireControl', 'fleetingThresholdBonus', 0, 0.5),
num('fireControl', 'fleetingLateralMps', 0.5, 15, 'm/s'),
num('fireControl', 'fleetingLookAheadSec', 0.1, 2, 's'),
num('fireControl', 'reloadThresholdPenalty', 0, 0.5),
num('fireControl', 'longReloadSec', 1, 60, 's'),
int('fireControl', 'lowAmmoRounds', 1, 60),
num('fireControl', 'lowAmmoThresholdPenalty', 0, 0.5),
num('fireControl', 'aimSkill', 0, 1),
num('fireControl', 'autocannonMinShotsPerSec', 0.5, 30),
num('fireControl', 'retreatThresholdPenalty', 0, 0.6),
num('fireControl', 'minShotIntervalSec', 0.1, 5, 's'),
num('fireControl', 'autocannonAimSlack', 1, 10),
num('fireControl', 'burstSec', 0.2, 6, 's'),
num('fireControl', 'burstPauseSec', 0, 5, 's'),
num('fireControl', 'autocannonReloadDetectSec', 0.1, 3, 's'),
{ id: 'groundAi.fireControl.auxWeapons', section: 'fireControl', field: 'auxWeapons', kind: 'bool' },
num('fireControl', 'auxMaxRangeM', 30, 1500, 'm'),
{ id: 'groundAi.fireControl.auxFireAtArmor', section: 'fireControl', field: 'auxFireAtArmor', kind: 'bool' },
num('fireControl', 'friendlyCorridorM', 1, 10, 'm'),
num('fireControl', 'ballisticStepMaxM', 5, 80, 'm'),
num('fireControl', 'ballisticSweepRadiusM', 0.02, 0.5, 'm'),
@@ -259,16 +348,82 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
{ id: 'groundAi.navigation.steerSign', section: 'navigation', field: 'steerSign', kind: 'steerSign' },
num('navigation', 'deadEchoSec', 0.3, 10, 's'),
num('navigation', 'controlTimeoutSec', 0.3, 10, 's'),
num('navigation', 'cornerBrakeAccel', 0.5, 8),
num('navigation', 'movingFireSpeedRampMps', 0.2, 5, 'm/s'),
num('navigation', 'pivotAngleDeg', 25, 150, '°'),
num('navigation', 'stuckWindowSec', 1, 15, 's'),
num('navigation', 'stuckMinMoveM', 0.5, 10, 'm'),
num('navigation', 'unstickReverseSec', 0.8, 10, 's'),
num('navigation', 'tacticalReverseDistM', 10, 90, 'm'),
num('navigation', 'tacticalReverseMaxSec', 2, 25, 's'),
],
},
{
id: 'navEngine',
defaultOpen: false,
customOnly: true,
fields: [
{ id: 'groundAi.navEngine.enabled', section: 'navEngine', field: 'enabled', kind: 'bool' },
{ id: 'groundAi.navEngine.allowFallback', section: 'navEngine', field: 'allowFallback', kind: 'bool' },
num('navEngine', 'snapRadiusM', 2, 40, 'm'),
num('navEngine', 'goalSnapRadiusM', 5, 150, 'm'),
num('navEngine', 'pathBudgetMsPerFrame', 0.05, 5, 'ms'),
num('navEngine', 'trafficCostPerPath', 0, 3),
num('navEngine', 'trafficCostMaxMul', 1, 10),
num('navEngine', 'trafficHoldSec', 0, 120, 's'),
num('navEngine', 'cornerOffsetM', 0, 5, 'm'),
...NAV_COST_FIELDS.map((field) => num('navCostsTracked', field, 0.1, 20)),
...NAV_COST_FIELDS.map((field) => num('navCostsWheeled', field, 0.1, 20)),
],
},
{
id: 'pathFollow',
defaultOpen: false,
customOnly: true,
fields: [
num('pathFollow', 'replanIntervalSec', 1, 15, 's'),
num('pathFollow', 'replanGoalMoveM', 3, 80, 'm'),
num('pathFollow', 'offCorridorReplanM', 3, 60, 'm'),
num('pathFollow', 'lookaheadTimeSec', 0.3, 5, 's'),
num('pathFollow', 'trackedLookaheadMinM', 2, 40, 'm'),
num('pathFollow', 'trackedLookaheadMaxM', 4, 60, 'm'),
num('pathFollow', 'wheeledLookaheadMinM', 2, 40, 'm'),
num('pathFollow', 'wheeledLookaheadMaxM', 4, 60, 'm'),
num('pathFollow', 'cornerAngleDeg', 10, 120, '°'),
num('pathFollow', 'cornerLateralAccelMps2', 0.5, 10, 'm/s²'),
num('pathFollow', 'cornerBrakeDecelMps2', 0.5, 10, 'm/s²'),
num('pathFollow', 'arriveRadiusM', 1, 20, 'm'),
num('pathFollow', 'arriveMinSpeedMps', 0.3, 6, 'm/s'),
num('pathFollow', 'narrowWallMarginM', 0.2, 6, 'm'),
num('pathFollow', 'narrowSpeedMps', 1, 15, 'm/s'),
num('pathFollow', 'bumperRayM', 2, 20, 'm'),
num('pathFollow', 'bumperStopM', 0.3, 6, 'm'),
num('pathFollow', 'bumperBlockSec', 0.2, 5, 's'),
num('pathFollow', 'trafficTtcSec', 0.5, 8, 's'),
num('pathFollow', 'yieldWaitMaxSec', 0.5, 15, 's'),
num('pathFollow', 'stationarySpeedMps', 0.2, 4, 'm/s'),
num('pathFollow', 'passMarginM', 0.2, 4, 'm'),
num('pathFollow', 'passSpeedMps', 1, 12, 'm/s'),
num('pathFollow', 'blockWaitSec', 0.5, 15, 's'),
num('pathFollow', 'blockTtlSec', 3, 120, 's'),
num('pathFollow', 'contactGapM', 0.2, 3, 'm'),
num('pathFollow', 'contactReverseSec', 0.3, 5, 's'),
num('pathFollow', 'contactRepeatSec', 3, 120, 's'),
num('pathFollow', 'stuckWindowSec', 1, 15, 's'),
num('pathFollow', 'stuckMinProgressM', 0.2, 10, 'm'),
num('pathFollow', 'unstickReverseM', 2, 25, 'm'),
num('pathFollow', 'unstickReverseSec', 0.8, 10, 's'),
num('pathFollow', 'unstickRepeatSec', 2, 60, 's'),
int('pathFollow', 'unstickMaxAttempts', 1, 10),
num('pathFollow', 'jamRadiusM', 2, 50, 'm'),
num('pathFollow', 'jamCostMul', 1, 50),
num('pathFollow', 'jamTtlSec', 5, 600, 's'),
num('pathFollow', 'giveUpRadiusM', 3, 50, 'm'),
num('pathFollow', 'giveUpCostMul', 1, 200),
num('pathFollow', 'rubbleRadiusM', 1, 40, 'm'),
num('pathFollow', 'rubbleCostMul', 1, 50),
num('pathFollow', 'rubbleTtlSec', 5, 600, 's'),
num('pathFollow', 'wreckRadiusM', 1, 40, 'm'),
num('pathFollow', 'wreckCostMul', 1, 50),
num('pathFollow', 'wreckTtlSec', 5, 600, 's'),
],
},
{
id: 'crowd',
defaultOpen: false,
@@ -306,6 +461,13 @@ export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
num('cadence', 'navTickSec', 0.05, 2, 's'),
{ id: 'groundAi.diagnostics.telemetry', section: 'diagnostics', field: 'telemetry', kind: 'bool' },
num('diagnostics', 'telemetryIntervalSec', 0.5, 60, 's'),
{ id: 'groundAi.diagnostics.battleStats', section: 'diagnostics', field: 'battleStats', kind: 'bool' },
num('diagnostics', 'statsLogIntervalSec', 10, 600, 's'),
num('diagnostics', 'statsSampleSec', 0.2, 5, 's'),
num('diagnostics', 'statsSampleRangeM', 50, 1000, 'm'),
num('diagnostics', 'statsRearArcDeg', 30, 180, '°'),
{ id: 'groundAi.diagnostics.trace', section: 'diagnostics', field: 'trace', kind: 'bool' },
num('diagnostics', 'traceIntervalSec', 0.1, 5, 's'),
],
},
];
@@ -5,7 +5,7 @@
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;
export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'crews', 'official', 'backup'] as const;
export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const TUNING_SECTIONS = ['rewards', 'battle', 'bots', 'newProfile', 'research'] as const;
@@ -0,0 +1,78 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { AppUpdateProgress } from '@shared/schemas/app-update.ts';
import type { ActiveMapNav, MapNavCheck } from '@shared/schemas/map-nav-pack.ts';
import { ipcInvoke, ipcOn } from '../ipc.ts';
import type { PackFailure } from './usePatchPack.ts';
export function useMapNavPack(checkOnStart: boolean, onError: (error: unknown) => void) {
const [active, setActive] = useState<ActiveMapNav>();
const [check, setCheck] = useState<MapNavCheck | null>(null);
const [busy, setBusy] = useState<'checking' | 'applying' | 'deactivating' | null>(null);
const [progress, setProgress] = useState<AppUpdateProgress | null>(null);
const [failure, setFailure] = useState<PackFailure | null>(null);
const startChecked = useRef(false);
useEffect(() => {
const refresh = (): void => { ipcInvoke('map-nav:active').then(setActive).catch(onError); };
refresh();
window.addEventListener('focus', refresh);
const disposeCopies = ipcOn('event:copies-changed', refresh);
const disposeProgress = ipcOn('event:map-nav-progress', setProgress);
return () => {
window.removeEventListener('focus', refresh);
disposeCopies();
disposeProgress();
};
}, [onError]);
const checkNow = useCallback((): void => {
setBusy('checking');
setFailure(null);
ipcInvoke('map-nav:check')
.then((result) => {
setCheck(result);
setActive(result.active);
})
.catch(onError)
.finally(() => setBusy(null));
}, [onError]);
useEffect(() => {
if (!checkOnStart || startChecked.current) return;
startChecked.current = true;
checkNow();
}, [checkOnStart, checkNow]);
function apply(version: string): void {
setBusy('applying');
setProgress(null);
setFailure(null);
ipcInvoke('map-nav:apply', { version })
.then((result) => {
if (!result.ok) {
setFailure(result.problem);
return;
}
setActive(result.active);
setCheck((previous) => previous ? { ...previous, status: 'up_to_date', active: result.active } : null);
})
.catch(onError)
.finally(() => setBusy(null));
}
function deactivate(): void {
setBusy('deactivating');
setFailure(null);
ipcInvoke('map-nav:deactivate')
.then((result) => {
setActive(result);
setCheck(null);
})
.catch(onError)
.finally(() => setBusy(null));
}
return { active, check, busy, progress, failure, checkNow, apply, deactivate };
}
export type MapNavPackState = ReturnType<typeof useMapNavPack>;
@@ -311,6 +311,14 @@
margin-top: 16px;
}
.save-crews-list > div {
border-top: 1px solid var(--line-soft);
}
.save-crews-list .maintenance-confirm {
margin: 0 0 12px;
}
.save-overview-actions {
display: flex;
align-items: center;
+4
View File
@@ -14,6 +14,7 @@ export const APP_ERROR_CODES = [
'internal_error',
'app_update_unavailable',
'app_update_busy',
'map_nav_update_busy',
'app_update_launcher_busy',
'app_update_download_failed',
'app_update_installer_invalid',
@@ -41,6 +42,9 @@ export const APP_ERROR_CODES = [
'save_nick_invalid',
'save_avatar_invalid',
'save_level_invalid',
'save_crew_invalid',
'save_crew_slot_limit',
'save_crew_stale',
'copies_write_failed',
'maintenance_busy',
'maintenance_location',
+2
View File
@@ -28,6 +28,8 @@ export const IPC_CHANNEL_PREFIXES = [
'settings:',
/** Adaptation packs: the active patch set, update checks, installing a newer pack. */
'patches:',
/** Map navigation pack status and updates. */
'map-nav:',
/** Checking, downloading and installing a launcher release. */
'updates:',
/** The launcher window itself (it draws its own title bar). */
+22
View File
@@ -16,10 +16,12 @@ import {
TargetFolderInspectionSchema,
} from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { ActiveMapNavSchema, MapNavApplyResultSchema, MapNavCheckSchema, MapNavVersionSchema } from '../schemas/map-nav-pack.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 { SaveCrewApplyRequest, SaveCrewPreviewRequest, SaveCrewPreviewSchema, SaveCrewViewRequest, SaveCrewViewSchema } from '../schemas/crew-saves.ts';
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
@@ -263,6 +265,9 @@ export const ipcContract = {
input: SaveKeysSchema.extend({ branch: ResearchBranchSchema, action: ResearchOperationSchema }),
output: SaveResearchSchema,
},
'saves:crews': { input: SaveCrewViewRequest, output: SaveCrewViewSchema },
'saves:previewCrew': { input: SaveCrewPreviewRequest, output: SaveCrewPreviewSchema },
'saves:editCrew': { input: SaveCrewApplyRequest, output: SaveCrewViewSchema },
'tuning:get': {
input: z.object({ copyId: CopyIdSchema }),
output: TuningViewSchema,
@@ -363,6 +368,22 @@ export const ipcContract = {
input: z.void(),
output: ActivePatchSetSchema,
},
'map-nav:active': {
input: z.void(),
output: ActiveMapNavSchema,
},
'map-nav:check': {
input: z.void(),
output: MapNavCheckSchema,
},
'map-nav:apply': {
input: z.object({ version: MapNavVersionSchema }),
output: MapNavApplyResultSchema,
},
'map-nav:deactivate': {
input: z.void(),
output: ActiveMapNavSchema,
},
'updates:check': {
input: z.void(),
output: AppUpdateCheckSchema,
@@ -389,6 +410,7 @@ export const ipcEvents = {
'event:settings-changed': SettingsSchema,
'event:install-progress': InstallProgressSchema,
'event:app-update-progress': AppUpdateProgressSchema,
'event:map-nav-progress': AppUpdateProgressSchema,
'event:launch-state': LaunchStateSchema,
'event:copies-changed': CopiesSchema,
'event:copy-maintenance': MaintenanceProgressSchema.nullable(),
@@ -0,0 +1,45 @@
import { z } from 'zod';
import { LocalizedNameSchema, SaveKeysSchema } from './saves.ts';
const CrewTypeSchema = z.enum(['air', 'tank', 'ship', 'human']);
const CrewIdSchema = z.number().int().nonnegative();
const CountrySchema = z.string().min(1);
const Level = z.number().nonnegative();
export const SaveCrewEditSchema = z.discriminatedUnion('action', [
z.object({ action: z.literal('add') }),
z.object({ action: z.literal('open'), crewId: CrewIdSchema }),
z.object({ action: z.literal('close'), crewId: CrewIdSchema }),
z.object({ action: z.literal('level'), crewId: CrewIdSchema, type: CrewTypeSchema, target: Level }),
]);
export const SaveCrewViewRequest = SaveKeysSchema.extend({ country: CountrySchema.optional() });
export const SaveCrewPreviewRequest = SaveKeysSchema.extend({ country: CountrySchema, edit: SaveCrewEditSchema });
export const SaveCrewApplyRequest = SaveCrewPreviewRequest.extend({ token: z.string().regex(/^[a-f\d]{64}$/) });
export const SaveCrewViewSchema = z.object({
countries: z.array(z.object({ id: CountrySchema, name: LocalizedNameSchema })),
selected: CountrySchema.nullable(),
activeCount: z.number().int().nonnegative(),
canAdd: z.boolean(),
min: z.number().int().nonnegative(),
max: z.number().int().nonnegative(),
crews: z.array(z.object({
id: CrewIdSchema, open: z.boolean(), canToggle: z.boolean(), vehicle: LocalizedNameSchema,
levels: z.array(z.object({ type: CrewTypeSchema, level: Level, min: Level, max: Level })),
})),
});
export const SaveCrewPreviewSchema = z.object({
token: SaveCrewApplyRequest.shape.token,
crewId: CrewIdSchema,
vehicle: LocalizedNameSchema,
restoredVehicle: LocalizedNameSchema,
changed: z.boolean(),
presets: z.array(z.object({ index: z.number().int().nonnegative(), title: z.string(), vehicle: LocalizedNameSchema, empty: z.boolean() })),
levels: z.array(z.object({ type: CrewTypeSchema, before: Level, after: Level })),
});
export type SaveCrewEdit = z.output<typeof SaveCrewEditSchema>;
export type SaveCrewView = z.output<typeof SaveCrewViewSchema>;
export type SaveCrewPreview = z.output<typeof SaveCrewPreviewSchema>;
@@ -0,0 +1,72 @@
import { z } from 'zod';
import { AppReleaseVersionSchema, MAX_INSTALLER_BYTES } from './app-update.ts';
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from './patch-pack.ts';
export const MAP_NAV_TAG_PREFIX = 'map-nav-';
export const MAP_NAV_FORMAT = 1;
export const MapNavVersionSchema = z.string().regex(/^\d{4}\.\d{2}\.\d{2}(\.[1-9]\d*)?$/);
export function mapNavReleaseFiles(version: string): { zip: string; signature: string; manifest: string } {
const name = 'wtoffline-map-nav-' + MapNavVersionSchema.parse(version);
return { zip: name + '.zip', signature: name + '.zip.sig', manifest: name + '.manifest.json' };
}
const Sha256 = z.string().regex(/^[0-9a-f]{64}$/);
const FileSize = z.number().int().positive().max(MAX_INSTALLER_BYTES);
const MapEntry = z.object({
level: z.string().regex(/^(?!(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$)[a-z0-9_]+$/),
everSha1: z.string().regex(/^[0-9a-f]{40}$/),
size: FileSize,
sha256: Sha256,
covers: z.number().int().nonnegative(),
});
export const MapNavManifestSchema = z.object({
format: z.number().int().positive(),
version: MapNavVersionSchema,
minAppVersion: AppReleaseVersionSchema,
gameVersions: z.array(z.string().regex(/^\d+\.\d+\.\d+\.\d+$/)).min(1),
createdAt: z.iso.datetime(),
maps: z.array(MapEntry).min(1).refine((maps) =>
new Set(maps.map(({ level }) => level)).size === maps.length &&
maps.reduce((size, entry) => size + entry.size, 0) <= MAX_INSTALLER_BYTES * 2),
});
export const MapNavReleaseManifestSchema = MapNavManifestSchema.extend({
archive: z.object({ size: FileSize, sha256: Sha256 }),
});
/** The signature covers a release manifest with the size and SHA-256 of the ZIP. */
export function mapNavSignaturePayload(manifest: Uint8Array): Uint8Array {
const domain = new TextEncoder().encode('WTOffline map navigation release v1\n');
const bytes = new Uint8Array(domain.length + manifest.length);
bytes.set(domain);
bytes.set(manifest, domain.length);
return bytes;
}
export const ActiveMapNavSchema = ActivePatchSetSchema.extend({
source: z.enum(['bundled', 'downloaded', 'local']),
mapCount: z.number().int().nonnegative(),
}).nullable();
export const MapNavReleaseSchema = PackReleaseSchema.extend({
mapCount: z.number().int().positive(),
size: FileSize,
});
export const MapNavCheckSchema = PackCheckSchema.extend({
active: ActiveMapNavSchema,
latest: MapNavReleaseSchema.nullable(),
});
export const MapNavApplyResultSchema = z.discriminatedUnion('ok', [
z.object({ ok: z.literal(true), active: ActiveMapNavSchema }),
PackApplyResultSchema.options[1],
]);
export type MapNavManifest = z.output<typeof MapNavManifestSchema>;
export type MapNavReleaseManifest = z.output<typeof MapNavReleaseManifestSchema>;
export type ActiveMapNav = z.output<typeof ActiveMapNavSchema>;
export type MapNavCheck = z.output<typeof MapNavCheckSchema>;
export type MapNavApplyResult = z.output<typeof MapNavApplyResultSchema>;
+2 -2
View File
@@ -67,9 +67,9 @@ export const SaveTransferSchema = SaveRegistrationSchema.extend({
z.object({ kind: z.literal('file'), path: z.string().min(1) }),
]),
});
export const SaveBackupNameSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.(manual|launch|restore|import)\.[0-9a-f-]{36}\.zip$/);
export const SaveBackupNameSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.(manual|launch|restore|import|crew)\.[0-9a-f-]{36}\.zip$/);
export const SaveBackupSchema = z.object({
name: SaveBackupNameSchema, createdAt: z.string(), type: z.enum(['manual', 'launch', 'restore', 'import']), size: z.number().int().nonnegative(),
name: SaveBackupNameSchema, createdAt: z.string(), type: z.enum(['manual', 'launch', 'restore', 'import', 'crew']), size: z.number().int().nonnegative(),
});
export const OnlineDataFileNameSchema = z.enum(['global.blk', 'machine.blk', 'storage.blk']);
+183 -20
View File
@@ -90,16 +90,84 @@ const GroundAiNavigationSchema = z.object({
steerSign: z.union([z.literal(1), z.literal(-1)]),
deadEchoSec: z.number().min(0.3).max(10),
controlTimeoutSec: z.number().min(0.3).max(10),
cornerBrakeAccel: z.number().min(0.5).max(8),
movingFireSpeedRampMps: z.number().min(0.2).max(5),
pivotAngleDeg: z.number().min(25).max(150),
stuckWindowSec: z.number().min(1).max(15),
stuckMinMoveM: z.number().min(0.5).max(10),
unstickReverseSec: z.number().min(0.8).max(10),
tacticalReverseDistM: z.number().min(10).max(90),
tacticalReverseMaxSec: z.number().min(2).max(25),
});
const GroundAiNavEngineSchema = z.object({
enabled: z.boolean(),
allowFallback: z.boolean(),
snapRadiusM: z.number().min(2).max(40),
goalSnapRadiusM: z.number().min(5).max(150),
pathBudgetMsPerFrame: z.number().min(0.05).max(5),
trafficCostPerPath: z.number().min(0).max(3),
trafficCostMaxMul: z.number().min(1).max(10),
trafficHoldSec: z.number().min(0).max(120),
cornerOffsetM: z.number().min(0).max(5),
});
const navCost = z.number().min(0.1).max(20);
const GroundAiNavCostsSchema = z.object({
road: navCost,
bridge: navCost,
ground: navCost,
rough: navCost,
forest: navCost,
crushable: navCost,
shallowWater: navCost,
chokepoint: navCost,
});
const GroundAiPathFollowSchema = z.object({
replanIntervalSec: z.number().min(1).max(15),
replanGoalMoveM: z.number().min(3).max(80),
offCorridorReplanM: z.number().min(3).max(60),
lookaheadTimeSec: z.number().min(0.3).max(5),
trackedLookaheadMinM: z.number().min(2).max(40),
trackedLookaheadMaxM: z.number().min(4).max(60),
wheeledLookaheadMinM: z.number().min(2).max(40),
wheeledLookaheadMaxM: z.number().min(4).max(60),
cornerAngleDeg: z.number().min(10).max(120),
cornerLateralAccelMps2: z.number().min(0.5).max(10),
cornerBrakeDecelMps2: z.number().min(0.5).max(10),
arriveRadiusM: z.number().min(1).max(20),
arriveMinSpeedMps: z.number().min(0.3).max(6),
narrowWallMarginM: z.number().min(0.2).max(6),
narrowSpeedMps: z.number().min(1).max(15),
bumperRayM: z.number().min(2).max(20),
bumperStopM: z.number().min(0.3).max(6),
bumperBlockSec: z.number().min(0.2).max(5),
trafficTtcSec: z.number().min(0.5).max(8),
yieldWaitMaxSec: z.number().min(0.5).max(15),
stationarySpeedMps: z.number().min(0.2).max(4),
passMarginM: z.number().min(0.2).max(4),
passSpeedMps: z.number().min(1).max(12),
blockWaitSec: z.number().min(0.5).max(15),
blockTtlSec: z.number().min(3).max(120),
contactGapM: z.number().min(0.2).max(3),
contactReverseSec: z.number().min(0.3).max(5),
contactRepeatSec: z.number().min(3).max(120),
stuckWindowSec: z.number().min(1).max(15),
stuckMinProgressM: z.number().min(0.2).max(10),
unstickReverseM: z.number().min(2).max(25),
unstickReverseSec: z.number().min(0.8).max(10),
unstickRepeatSec: z.number().min(2).max(60),
unstickMaxAttempts: z.number().int().min(1).max(10),
jamRadiusM: z.number().min(2).max(50),
jamCostMul: z.number().min(1).max(50),
jamTtlSec: z.number().min(5).max(600),
giveUpRadiusM: z.number().min(3).max(50),
giveUpCostMul: z.number().min(1).max(200),
rubbleRadiusM: z.number().min(1).max(40),
rubbleCostMul: z.number().min(1).max(50),
rubbleTtlSec: z.number().min(5).max(600),
wreckRadiusM: z.number().min(1).max(40),
wreckCostMul: z.number().min(1).max(50),
wreckTtlSec: z.number().min(5).max(600),
});
const GroundAiPerceptionSchema = z.object({
foliageTransparency: z.number().min(0.001).max(1),
nearSpotRangeM: z.number().min(20).max(250),
@@ -108,22 +176,24 @@ const GroundAiPerceptionSchema = z.object({
normalSpotSec: z.number().min(0.1).max(3),
farSpotSec: z.number().min(0.3).max(6),
decayPerSec: z.number().min(0.2).max(10),
frontConeHalfDeg: z.number().min(10).max(90),
peripheralCloseM: z.number().min(30).max(250),
gunFovHalfDeg: z.number().min(5).max(90),
nearAwareM: z.number().min(30).max(400),
nearArcDeg: z.number().min(90).max(360),
midAwareM: z.number().min(100).max(1500),
nearSpotMul: z.number().min(1).max(5),
midSpotMul: z.number().min(1).max(6),
lookAroundSec: z.number().min(2).max(60),
lookAroundHoldSec: z.number().min(0.2).max(5),
discoverScore: z.number().min(0.05).max(0.95),
});
const GroundAiStateMachineSchema = z.object({
preaimAngleDeg: z.number().min(1).max(30),
movingShotWaitSec: z.number().min(0.25).max(5),
shortHaltMaxSec: z.number().min(0.5).max(12),
shortHaltCooldownSec: z.number().min(0.5).max(20),
turnLaunchSpeedMps: z.number().min(0.5).max(6),
coverMinDistM: z.number().min(2).max(30),
coverMaxDistM: z.number().min(6).max(80),
coverRetreatBudgetSec: z.number().min(1.5).max(20),
reloadAdvanceAngleDeg: z.number().min(0).max(45),
hullAngleTriggerDeg: z.number().min(15).max(75),
hullAngleTargetDeg: z.number().min(0).max(35),
maxTotalHaltSec: z.number().min(3).max(40),
stalemateMissShots: z.number().int().min(1).max(8),
stalemateNoShotHalts: z.number().int().min(1).max(6),
@@ -134,8 +204,6 @@ const GroundAiStateMachineSchema = z.object({
const GroundAiTacticsSchema = z.object({
visionRangeM: z.number().min(200).max(3500),
visionFovDeg: z.number().min(40).max(180),
peripheralRangeM: z.number().min(30).max(800),
engineAudioRangeM: z.number().min(10).max(250),
shotAudioRangeM: z.number().min(50).max(1200),
radioShareRangeM: z.number().min(50).max(1500),
@@ -144,6 +212,58 @@ const GroundAiTacticsSchema = z.object({
peekCooldownSec: z.number().min(1).max(30),
});
const GroundAiThreatSchema = z.object({
rangeScaleM: z.number().min(50).max(3000),
discoveredMul: z.number().min(0).max(1),
aimConeDeg: z.number().min(5).max(90),
notAimingMul: z.number().min(0).max(1),
unseenMul: z.number().min(0).max(1),
hitMemorySec: z.number().min(0).max(60),
hitMul: z.number().min(1).max(5),
});
const GroundAiTurretSchema = z.object({
minDwellSec: z.number().min(0).max(5),
switchMargin: z.number().min(0).max(3),
scanArcDeg: z.number().min(0).max(180),
scanPeriodSec: z.number().min(1).max(30),
fixedMountYawSpanDeg: z.number().min(0).max(180),
});
const GroundAiBehaviorSchema = z.object({
scoreIntervalSec: z.number().min(0.1).max(3),
advanceHoldSec: z.number().min(0).max(10),
engageHoldSec: z.number().min(0).max(10),
haltHoldSec: z.number().min(0).max(10),
coverHoldSec: z.number().min(0).max(10),
repositionHoldSec: z.number().min(0).max(10),
postHoldSec: z.number().min(0).max(10),
disperseHoldSec: z.number().min(0).max(10),
targetValueWeight: z.number().min(0).max(1),
nearThreatHaltBonus: z.number().min(0).max(1),
switchMargin: z.number().min(0).max(1),
advanceScore: z.number().min(0).max(1),
engageScore: z.number().min(0).max(1),
urgencyWeight: z.number().min(0).max(1),
haltScore: z.number().min(0).max(1),
crossfirePenalty: z.number().min(0).max(1),
coverScore: z.number().min(0).max(1),
coverDangerWeight: z.number().min(0).max(1),
coverOffensivePenalty: z.number().min(0).max(1),
coverRetrySec: z.number().min(0.5).max(30),
repositionScore: z.number().min(0).max(1),
holdScore: z.number().min(0).max(1),
disperseScore: z.number().min(0).max(1),
urgentSpeedKeep: z.number().min(0).max(1),
hullAngleDeg: z.number().min(0).max(45),
faceToleranceDeg: z.number().min(3).max(60),
faceMinDanger: z.number().min(0).max(2),
reverseTravelAngleDeg: z.number().min(60).max(180),
reverseMaxTurnDistM: z.number().min(0).max(200),
reverseMinSpeedMps: z.number().min(0.5).max(10),
reverseHoldSec: z.number().min(0).max(20),
});
const GroundAiEstimationSchema = z.object({
watchMinSec: z.number().min(0.5).max(10),
watchMaxSec: z.number().min(1).max(15),
@@ -160,19 +280,41 @@ const GroundAiFireControlSchema = z.object({
closeRangeM: z.number().min(30).max(250),
midRangeM: z.number().min(100).max(600),
longRangeM: z.number().min(300).max(1500),
midSlowSpeedRatio: z.number().min(0.1).max(1),
midSlowMaxMps: z.number().min(1).max(15),
closeRangeMaxSpeedKmh: z.number().min(3.6).max(100),
pointBlankMaxSpeedKmh: z.number().min(3.6).max(100),
stopSpeedMaxMps: z.number().min(0.1).max(2),
longRangeWindowSec: z.number().min(1).max(15),
baseAlignDeg: z.number().min(0.1).max(3),
closeHitRadiusM: z.number().min(0.25).max(2.2),
barrelSettleDegSec: z.number().min(0.2).max(12),
closeSettleHoldSec: z.number().min(0.02).max(0.5),
settleHoldSec: z.number().min(0.05).max(1.5),
unstabilizedStopSpeedMps: z.number().min(0.1).max(3),
stabilizedCreepSpeedMps: z.number().min(1.5).max(15),
aimErrorDeg: z.number().min(0.01).max(2),
moveErrDegPerMps: z.number().min(0).max(3),
turnErrDegPerDegSec: z.number().min(0).max(0.5),
stabErrFactor: z.number().min(0.02).max(1),
targetHalfHeightM: z.number().min(0.3).max(2),
fireThreshold: z.number().min(0.05).max(0.95),
minFireThreshold: z.number().min(0.01).max(0.9),
aimingThresholdBonus: z.number().min(0).max(0.5),
closeThresholdBonus: z.number().min(0).max(0.5),
enemyReloadThresholdBonus: z.number().min(0).max(0.5),
enemyReloadSec: z.number().min(0).max(15),
fleetingThresholdBonus: z.number().min(0).max(0.5),
fleetingLateralMps: z.number().min(0.5).max(15),
fleetingLookAheadSec: z.number().min(0.1).max(2),
reloadThresholdPenalty: z.number().min(0).max(0.5),
longReloadSec: z.number().min(1).max(60),
lowAmmoRounds: z.number().int().min(1).max(60),
lowAmmoThresholdPenalty: z.number().min(0).max(0.5),
aimSkill: z.number().min(0).max(1),
autocannonMinShotsPerSec: z.number().min(0.5).max(30),
retreatThresholdPenalty: z.number().min(0).max(0.6),
minShotIntervalSec: z.number().min(0.1).max(5),
autocannonAimSlack: z.number().min(1).max(10),
burstSec: z.number().min(0.2).max(6),
burstPauseSec: z.number().min(0).max(5),
autocannonReloadDetectSec: z.number().min(0.1).max(3),
auxWeapons: z.boolean(),
auxMaxRangeM: z.number().min(30).max(1500),
auxFireAtArmor: z.boolean(),
friendlyCorridorM: z.number().min(1).max(10),
ballisticStepMaxM: z.number().min(5).max(80),
ballisticSweepRadiusM: z.number().min(0.02).max(0.5),
@@ -182,6 +324,13 @@ const GroundAiFireControlSchema = z.object({
const GroundAiDiagnosticsSchema = z.object({
telemetry: z.boolean(),
telemetryIntervalSec: z.number().min(0.5).max(60),
battleStats: z.boolean(),
statsLogIntervalSec: z.number().min(10).max(600),
statsSampleSec: z.number().min(0.2).max(5),
statsSampleRangeM: z.number().min(50).max(1000),
statsRearArcDeg: z.number().min(30).max(180),
trace: z.boolean(),
traceIntervalSec: z.number().min(0.1).max(5),
});
export const GroundAiTuningSchema = z.object({
@@ -194,10 +343,17 @@ export const GroundAiTuningSchema = z.object({
crowd: GroundAiCrowdSchema,
terrain: GroundAiTerrainSchema,
navigation: GroundAiNavigationSchema,
navEngine: GroundAiNavEngineSchema,
navCostsTracked: GroundAiNavCostsSchema,
navCostsWheeled: GroundAiNavCostsSchema,
pathFollow: GroundAiPathFollowSchema,
perception: GroundAiPerceptionSchema,
stateMachine: GroundAiStateMachineSchema,
tactics: GroundAiTacticsSchema,
estimation: GroundAiEstimationSchema,
threat: GroundAiThreatSchema,
turret: GroundAiTurretSchema,
behavior: GroundAiBehaviorSchema,
fireControl: GroundAiFireControlSchema,
diagnostics: GroundAiDiagnosticsSchema,
});
@@ -212,10 +368,17 @@ export const GroundAiTuningPatchSchema = z.object({
crowd: GroundAiCrowdSchema.partial().optional(),
terrain: GroundAiTerrainSchema.partial().optional(),
navigation: GroundAiNavigationSchema.partial().optional(),
navEngine: GroundAiNavEngineSchema.partial().optional(),
navCostsTracked: GroundAiNavCostsSchema.partial().optional(),
navCostsWheeled: GroundAiNavCostsSchema.partial().optional(),
pathFollow: GroundAiPathFollowSchema.partial().optional(),
perception: GroundAiPerceptionSchema.partial().optional(),
stateMachine: GroundAiStateMachineSchema.partial().optional(),
tactics: GroundAiTacticsSchema.partial().optional(),
estimation: GroundAiEstimationSchema.partial().optional(),
threat: GroundAiThreatSchema.partial().optional(),
turret: GroundAiTurretSchema.partial().optional(),
behavior: GroundAiBehaviorSchema.partial().optional(),
fireControl: GroundAiFireControlSchema.partial().optional(),
diagnostics: GroundAiDiagnosticsSchema.partial().optional(),
});
@@ -60,6 +60,26 @@ export function selectBattleCoalitions(input: CoalitionPairingInput): CoalitionP
};
}
/** Single-sided Assault PvE coalition: the player and all friendly AI defenders are always Team A. */
export function selectPveAssaultCoalition(
input: CoalitionPairingInput,
missionEnemyCountry?: string,
): CoalitionPairing {
const playerCountry = stripCountryPrefix(input.playerCountry);
const eligible = eligibleCountriesForBracket(input, playerCountry);
const countriesAllies = placeFirst(shuffle(eligible), playerCountry);
const rawEnemy = missionEnemyCountry ? stripCountryPrefix(missionEnemyCountry) : '';
const enemyCountry = rawEnemy || eligible.find((c) => c !== playerCountry) || playerCountry;
return {
playerTeam: 1,
countryAllies: playerCountry,
countryAxis: enemyCountry,
countriesAllies,
countriesAxis: [enemyCountry],
symmetricTeams: false,
};
}
interface TeamSides {
readonly playerSide: readonly string[];
readonly enemySide: readonly string[];
@@ -17,6 +17,7 @@ export interface BattleEconomyTuning {
readonly captureZoneScore: Readonly<Record<VictimGroup, number>>;
readonly navalDamageScorePerPoint: number;
readonly bombingZone: { readonly damageScore: number; readonly destructionScore: number };
readonly pveAiKillMul: number;
readonly referenceScore: Readonly<Record<VictimGroup, number>>;
readonly friendlyKillPenaltyMul: number;
}
@@ -48,6 +49,7 @@ export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuni
damageScore: bombingZone.int('damageScore', { min: 0, max: 100000 }),
destructionScore: bombingZone.int('destructionScore', { min: 0, max: 100000 }),
},
pveAiKillMul: reader.number('pveAiKillMul', { min: 0, max: 10 }),
referenceScore: perGroup('referenceScore', 1),
friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }),
};
+24 -6
View File
@@ -37,6 +37,19 @@ export type DebriefingRow =
/** LocalMP reports mini-base health as basis points (local_mp_zones.c). */
const ZONE_HEALTH_SCALE = 10_000;
/** Modes that award bombing-zone damage and destruction (Air AB, Air RB / sub-modes, Air SB EC). */
const BOMBING_ZONE_MODES: ReadonlySet<string> = new Set([
'air_arcade',
'air_realistic',
'air_simulation_timeDelay_battles',
]);
/** Assault PvE modes where wave enemies are non-MPlayer mission AI units. */
const PVE_ASSAULT_MODES: ReadonlySet<string> = new Set([
'air_assault_pve',
'tank_assault_pve',
]);
function isBombingZoneEvent(code: number): boolean {
return code === ExpEvent.DAMAGE_ZONE || code === ExpEvent.DESTROY_ZONE;
}
@@ -145,7 +158,7 @@ export class BattleEconomy {
const isCapture = fact.code === ExpEvent.CAPTURE_ZONE;
const isBombingZone = isBombingZoneEvent(fact.code);
const isZoneDamage = fact.code === ExpEvent.DAMAGE_ZONE;
if (isBombingZone && (modeName !== 'air_arcade' || fact.friendly)) return undefined;
if (isBombingZone && (!BOMBING_ZONE_MODES.has(modeName) || fact.friendly)) return undefined;
if (isZoneDamage && (!Number.isInteger(fact.damage) || fact.damage < 1 || fact.damage > ZONE_HEALTH_SCALE)) return undefined;
const isObjective = isCapture || isBombingZone;
const group = isBombingZone ? 'ground' : this.victimGroup(isCapture ? economy.unitClass : fact.expClass);
@@ -154,7 +167,7 @@ export class BattleEconomy {
if (!row || !base) return undefined;
const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1;
const quantity = isZoneDamage ? fact.damage / ZONE_HEALTH_SCALE : count;
const ai = isObjective || fact.victimIsPlayer ? 1 : this.data.aiKillK;
const ai = isObjective || fact.victimIsPlayer ? 1 : this.#aiKillMul(modeName);
const slClass = isObjective ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1;
const rpClass = isObjective ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1;
if (fact.friendly) {
@@ -170,13 +183,14 @@ export class BattleEconomy {
bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty, modeName: string): BannerParams {
const table: Record<string, Record<string, [number, number]>> = {};
const allowBombingZone = BOMBING_ZONE_MODES.has(modeName);
for (const name of vehicles) {
const economy = this.vehicle(name);
if (!economy || table[name]) continue;
const entries: Record<string, [number, number]> = {};
for (const code of Object.values(ExpEvent)) {
const isBombingZone = isBombingZoneEvent(code);
if (isBombingZone && modeName !== 'air_arcade') continue;
if (isBombingZone && !allowBombingZone) continue;
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own']
: isBombingZone ? ['ground'] : VICTIM_GROUPS;
for (const group of groups) {
@@ -192,7 +206,7 @@ export class BattleEconomy {
groups: Object.fromEntries(this.#tuning.victimGroups),
slClass: this.data.silverLionsClassFactors,
rpClass: this.data.researchClassFactors,
aiKillK: this.data.aiKillK,
aiKillK: this.#aiKillMul(modeName),
friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul,
zoneHealthScale: ZONE_HEALTH_SCALE,
};
@@ -211,14 +225,18 @@ export class BattleEconomy {
scores[`wtoScore_capture_${group}`] = this.#tuning.captureZoneScore[group];
}
scores.wtoScore_damagePerPoint = this.#tuning.navalDamageScorePerPoint;
scores.wtoScore_aiMul = this.data.aiKillK;
if (modeName === 'air_arcade') {
scores.wtoScore_aiMul = this.#aiKillMul(modeName);
if (BOMBING_ZONE_MODES.has(modeName)) {
scores.wtoScore_zoneDamage = this.#tuning.bombingZone.damageScore;
scores.wtoScore_zoneDestruction = this.#tuning.bombingZone.destructionScore;
}
return scores;
}
#aiKillMul(modeName: string): number {
return PVE_ASSAULT_MODES.has(modeName) ? this.#tuning.pveAiKillMul : this.data.aiKillK;
}
#score(code: number, group: VictimGroup): number | undefined {
const scored = (event: ScoredEvent): number => this.#tuning.eventScores[group][event];
switch (code) {
+56 -50
View File
@@ -12,8 +12,15 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { MISSION_DIFFICULTY, SINGLE_SPAWN, UNLIMITED_RESPAWNS, modeMaxRespawns } from '../game-modes/mode-definition.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
import { selectBattleCoalitions, selectPveAssaultCoalition, type CoalitionPairing } from './battle-coalitions.ts';
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
import {
eligibleMissionsOf,
isSupportedPveMode,
maxSlotsForMission,
pickMission,
resolveMissionLocName,
} from './battle-mission-pick.ts';
import {
activeVehiclesForMode,
isModeEligibleForLineup,
@@ -28,6 +35,9 @@ import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
import type { BattleTuning } from './battle-tuning.ts';
/** BotSystem (`aces.exe 2.61.0.37 0x11b27b1`) treats -1 as unlimited bot respawns. */
const BOT_UNLIMITED_RESPAWNS = -1;
export interface BattleCrewSlot {
readonly idInCountry: number;
readonly unitName: string;
@@ -68,6 +78,7 @@ export interface BattleLaunchPlan {
readonly countriesAllies: readonly string[];
readonly countriesAxis: readonly string[];
readonly symmetricTeams: boolean;
readonly isPve: boolean;
readonly minMrank: number;
readonly maxMrank: number;
readonly maxPlayers: number;
@@ -139,14 +150,17 @@ export class BattleMatchmaker {
if (!knownCountries.includes(input.country)) return { ok: false, error: 'BAD_PARAMS' };
const candidates = input.modes && input.modes.length > 0 ? input.modes : [input.mode];
const pvpModes = candidates.filter(
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
const supportedModes = candidates.filter((mode) =>
isSupportedPveMode(mode)
? eligibleMissionsOf(mode).length > 0
: mode.declaration.displayType !== 'pve_battle' && eligibleMissionsOf(mode).length > 0,
);
if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
const chosenMode = this.#pickQueuedMode(pvpModes, input);
if (supportedModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
const chosenMode = this.#pickQueuedMode(supportedModes, input);
if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' };
const { declaration } = chosenMode;
const isPve = isSupportedPveMode(chosenMode);
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
const playerMrank = lineupMrank(
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
@@ -155,7 +169,7 @@ 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 rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
const rawMissions = eligibleMissionsOf(chosenMode, isPve ? playerMrank : maxMrank);
if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const filteredMissions = this.#filterMissions
? this.#filterMissions({
@@ -170,7 +184,7 @@ export class BattleMatchmaker {
: rawMissions;
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({
const coalitionInput = {
vehicles: this.#vehicles,
knownCountries,
playerCountry: input.country,
@@ -180,12 +194,15 @@ export class BattleMatchmaker {
minMrank,
maxMrank,
tuning: this.#tuning,
});
};
const coalitions = isPve
? selectPveAssaultCoalition(coalitionInput, mission.countryAxis)
: selectBattleCoalitions(coalitionInput);
const customBots = selectCustomBots(this.#vehicles, {
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
allowedClasses: declaration.allowedClasses,
countries: [...coalitions.countriesAllies, ...coalitions.countriesAxis],
countries: isPve ? coalitions.countriesAllies : [...coalitions.countriesAllies, ...coalitions.countriesAxis],
centerMrank: playerMrank,
minMrank,
maxMrank,
@@ -193,7 +210,7 @@ export class BattleMatchmaker {
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts);
return {
ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots, isPve),
};
}
@@ -221,12 +238,18 @@ export class BattleMatchmaker {
minMrank: number,
maxMrank: number,
customBots: CustomBotsPool,
isPve: boolean,
): BattleLaunchPlan {
const { declaration } = chosenMode;
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
const desiredPlayers = isPve
? this.#tuning.pveAssaultMaxPlayers
: declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers, isPve));
const maxBots = isPve
? Math.min(this.#tuning.pveAssaultMaxBots, Math.max(0, maxPlayers - 1))
: Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
const maxRespawns = modeMaxRespawns(declaration);
const unlimitedRespawns = maxRespawns === UNLIMITED_RESPAWNS;
const missionLocName = resolveMissionLocName(mission);
const environment = declaration.environmentOverride ?? mission.environment;
const session = this.#sessions.create({
@@ -255,7 +278,10 @@ export class BattleMatchmaker {
rules: this.#spawnRules,
tuning: this.#tuning,
});
const useSpawnScore = declaration.requiredClass === 'tank' && declaration.difficulty === 'realistic';
const spawnScoreDifficulty = declaration.requiredClass === 'tank'
&& (declaration.difficulty === 'realistic' || declaration.difficulty === 'simulator')
? declaration.difficulty : undefined;
const useSpawnScore = spawnScoreDifficulty !== undefined;
return {
sessionId: session.sessionId,
modeId: declaration.gameModeId,
@@ -278,19 +304,30 @@ export class BattleMatchmaker {
countriesAllies: coalitions.countriesAllies,
countriesAxis: coalitions.countriesAxis,
symmetricTeams: coalitions.symmetricTeams,
isPve,
minMrank,
maxMrank,
maxPlayers,
maxBots,
allowSpares: declaration.multiSlot !== false && maxRespawns !== SINGLE_SPAWN && maxRespawns !== UNLIMITED_RESPAWNS,
allowSpares: declaration.multiSlot !== false && maxRespawns !== SINGLE_SPAWN && !unlimitedRespawns,
...(maxRespawns === undefined ? {} : { maxRespawns }),
tankBotRespawns: this.#tuning.tankBotRespawns,
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
tankBotRespawns: unlimitedRespawns ? BOT_UNLIMITED_RESPAWNS : this.#tuning.tankBotRespawns,
airBotRespawns: unlimitedRespawns
? BOT_UNLIMITED_RESPAWNS
: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
useTankBots: allowedSet.has('tank'),
useShipBots: allowedSet.has('ship'),
useSpawnScore,
...(useSpawnScore ? {
spawnScore: battleSpawnScore(input.slotVehicles, extraBattleSlots, maxMrank, this.#vehiclesByName, this.#spawnRules.spawnScore),
...(spawnScoreDifficulty ? {
spawnScore: battleSpawnScore(
input.slotVehicles,
extraBattleSlots,
maxMrank,
this.#vehiclesByName,
this.#spawnRules.spawnScore,
spawnScoreDifficulty,
spawnScoreDifficulty === 'simulator' ? this.#tuning.simGroundInitialSpawnScore : undefined,
),
} : {}),
customBots,
...(declaration.multiSlot === false && input.selectedSlot ? { selectedSlot: input.selectedSlot } : {}),
@@ -298,34 +335,3 @@ export class BattleMatchmaker {
};
}
}
function twoSidedMissionsOf(mode: OfferedGameMode, roomMrank?: number): MissionHeader[] {
return mode.missions.filter((mission) => {
if (mission.playerSlots.teamA === 0 || mission.playerSlots.teamB === 0) return false;
if (!mode.missionRanks || roomMrank === undefined) return true;
return mode.missionRanks.byMission.get(mission.name)?.some(({ minMRank, maxMRank }) =>
roomMrank >= minMRank && roomMrank <= maxMRank);
});
}
function pickMission(missions: readonly MissionHeader[], banned: ReadonlySet<string>, disliked: ReadonlySet<string>): MissionHeader {
const unbanned = missions.filter((mission) => !banned.has(mission.name));
const poolAfterBan = unbanned.length > 0 ? unbanned : missions;
const preferred = poolAfterBan.filter((mission) => !disliked.has(mission.name));
const pool = preferred.length > 0 ? preferred : poolAfterBan;
return pool[randomInt(pool.length)]!;
}
function maxSlotsForMission(mission: MissionHeader, desiredMaxPlayers: number): number {
const { teamA, teamB } = mission.playerSlots;
return Math.max(2, Math.min(desiredMaxPlayers, Math.min(teamA, teamB) * 2));
}
function resolveMissionLocName(mission: MissionHeader): string | undefined {
if (mission.locName && mission.locName.length > 0) return mission.locName;
if (mission.postfix && mission.postfix.length > 0 && mission.name.endsWith(mission.postfix)) {
const baseName = mission.name.slice(0, -mission.postfix.length);
if (baseName.length > 0) return `missions/${mission.postfix};missions/${baseName}`;
}
return undefined;
}
@@ -0,0 +1,59 @@
/**
* Mission eligibility, random mission picking (honoring bans/dislikes), slot-capacity limits,
* and mission localization name fallback for BattleMatchmaker.
*/
import { randomInt } from 'node:crypto';
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
import type { OfferedGameMode } from '../game-modes/game-modes.ts';
/** PvE modes wired for single-sided LocalMP Assault survival. */
const SUPPORTED_PVE_MODES: ReadonlySet<string> = new Set([
'air_assault_pve',
'tank_assault_pve',
]);
export function isSupportedPveMode(mode: OfferedGameMode): boolean {
return mode.declaration.displayType === 'pve_battle' && SUPPORTED_PVE_MODES.has(mode.declaration.name);
}
export function eligibleMissionsOf(mode: OfferedGameMode, roomMrank?: number): MissionHeader[] {
const isPve = isSupportedPveMode(mode);
return mode.missions.filter((mission) => {
if (isPve) {
if (mission.playerSlots.teamA === 0) return false;
if (roomMrank === undefined || !mission.pveRankRanges?.length) return true;
return mission.pveRankRanges.some(({ minMRank, maxMRank }) => roomMrank >= minMRank && roomMrank <= maxMRank);
}
if (mission.playerSlots.teamA === 0 || mission.playerSlots.teamB === 0) return false;
if (!mode.missionRanks || roomMrank === undefined) return true;
return mode.missionRanks.byMission.get(mission.name)?.some(({ minMRank, maxMRank }) =>
roomMrank >= minMRank && roomMrank <= maxMRank);
});
}
export function pickMission(
missions: readonly MissionHeader[],
banned: ReadonlySet<string>,
disliked: ReadonlySet<string>,
): MissionHeader {
const unbanned = missions.filter((mission) => !banned.has(mission.name));
const poolAfterBan = unbanned.length > 0 ? unbanned : missions;
const preferred = poolAfterBan.filter((mission) => !disliked.has(mission.name));
const pool = preferred.length > 0 ? preferred : poolAfterBan;
return pool[randomInt(pool.length)]!;
}
export function maxSlotsForMission(mission: MissionHeader, desiredMaxPlayers: number, isPve: boolean): number {
const { teamA, teamB } = mission.playerSlots;
if (isPve) return Math.max(1, Math.min(desiredMaxPlayers, teamA));
return Math.max(2, Math.min(desiredMaxPlayers, Math.min(teamA, teamB) * 2));
}
export function resolveMissionLocName(mission: MissionHeader): string | undefined {
if (mission.locName && mission.locName.length > 0) return mission.locName;
if (mission.postfix && mission.postfix.length > 0 && mission.name.endsWith(mission.postfix)) {
const baseName = mission.name.slice(0, -mission.postfix.length);
if (baseName.length > 0) return `missions/${mission.postfix};missions/${baseName}`;
}
return undefined;
}
@@ -23,13 +23,13 @@ const RULE_KEYS: readonly string[] = [
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
'allowedKillStreaks',
'allowedKillStreaks', 'allowEmptyTeams', 'gt_reload_explosives', 'optionalTakeOff', 'nameKillStreaks',
];
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
const VERSUS_SWITCHES: readonly string[] = [
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
'allowUseArtillerySupport', 'isBotsAllowed',
];
/**
@@ -68,10 +68,15 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
setParam(settings, 'gt_mp_solo', flag(false));
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
setParam(settings, 'autoBalance', flag(!plan.isPve));
if (plan.isPve) setParam(settings, 'allowEmptyTeams', flag(true));
// The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade' && plan.modeName !== 'air_assault_pve'));
// MissionSettings defaults isLimitedFuel to false, which disables fuel consumption and HUD timers.
setParam(settings, 'isLimitedFuel', flag(true));
// MissionSettings::load (0x1268ab0) defaults multiRespawn to true whenever maxRespawns < -1,
// which turns on Silver Lions respawn-cost checks; keep offline unlimited respawns free.
setParam(settings, 'multiRespawn', flag(false));
setParam(settings, 'allowSpare', flag(plan.allowSpares));
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
if (plan.selectedSlot) {
@@ -131,6 +136,9 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
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));
// The battle's level file: the ground AI loads its navigation pack by this name (native local_mp_nav.c).
if (plan.level !== undefined) setParam(bots, 'wtoLevel', text(plan.level));
if (plan.isPve) setParam(bots, 'wtoPveMode', text('1'));
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
+10 -5
View File
@@ -7,6 +7,7 @@
*/
import type { SpawnScoreRules } from '../game-data/datasets/battle-spawn-rules.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { ModeDifficulty } from '../game-modes/catalogue/game-mode-declaration.ts';
import { vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
import { vehicleMrank } from './battle-ranks.ts';
@@ -33,17 +34,21 @@ export function battleSpawnScore(
sessionMaxMrank: number,
vehicles: ReadonlyMap<string, CatalogueVehicle>,
rules: SpawnScoreRules,
difficulty: Extract<ModeDifficulty, 'realistic' | 'simulator'> = 'realistic',
initialScoreOverride?: number,
): BattleSpawnScore {
const override = rules.overrides.find(({ minMrank, maxMrank }) => sessionMaxMrank >= minMrank && sessionMaxMrank <= maxMrank);
const modeRules = difficulty === 'simulator' ? rules.tankSimulation : rules.tankHistorical;
const modeOverrides = difficulty === 'simulator' ? rules.tankSimulationOverrides : rules.overrides;
const override = modeOverrides.find(({ minMrank, maxMrank }) => sessionMaxMrank >= minMrank && sessionMaxMrank <= maxMrank);
const params = {
...rules.common,
...rules.tankHistorical.classCosts,
...rules.tankHistorical.parameters,
...modeRules.classCosts,
...modeRules.parameters,
...override?.classCosts,
...override?.parameters,
};
const base = params.base_respawn_points_coef ?? 450;
const maxScore = Math.max(0, Math.round(base * (params.maxRespawnPointsMul ?? 1)));
const maxScore = initialScoreOverride ?? Math.max(0, Math.round(base * (params.maxRespawnPointsMul ?? 1)));
const maxBrDiff = params.max_br_diff ?? 1;
const sessionBr = battleRating(sessionMaxMrank);
const unitCosts: Record<string, number> = {};
@@ -58,7 +63,7 @@ export function battleSpawnScore(
}
const type = vehicleTypeOfClass(unitClass);
const spawnType = unitClass === 'exp_ai_sam_tracking_radar' ? 'Tank' : type ? SPAWN_TYPES[type] : 'Invalid';
const rank = vehicle ? vehicleMrank(vehicle, 'realistic', 'tank') : sessionMaxMrank;
const rank = vehicle ? vehicleMrank(vehicle, difficulty, 'tank') : sessionMaxMrank;
const brDiff = Math.min(Math.max(0, sessionBr - battleRating(rank)), maxBrDiff);
const discount = maxBrDiff > 0 ? (params[`br_diff_mul_${spawnType}`] ?? 0) * brDiff / maxBrDiff : 0;
unitCosts[unit] = Math.max(1, Math.round(base * multiplier * (1 - discount) / 10) * 10);
+8
View File
@@ -21,6 +21,9 @@ export interface BattleTuning {
readonly rbAirMixedChance: number;
readonly rbNavalMixedChance: number;
readonly simColdWarMinMrank: number;
readonly simGroundInitialSpawnScore: number;
readonly pveAssaultMaxPlayers: number;
readonly pveAssaultMaxBots: number;
readonly strikeUcavModes: readonly string[];
readonly strikeUcavSessionMrankAllowance: number;
readonly strikeUcavSpawnScore: number;
@@ -46,6 +49,8 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
`tuning file battle.jsonc: rbCoalitionMaxCountries (${rbCoalitionMaxCountries}) must be at least rbCoalitionMinCountries (${rbCoalitionMinCountries})`,
);
}
const pveAssaultMaxPlayers = reader.int('pveAssaultMaxPlayers', { min: 1, max: 32 });
const pveAssaultMaxBots = Math.min(reader.int('pveAssaultMaxBots', { min: 0, max: 31 }), Math.max(0, pveAssaultMaxPlayers - 1));
return {
rewardMultiplierSilverLions: reader.number('rewardMultiplierSilverLions', { min: 0, max: 100 }),
rewardMultiplierResearchPoints: reader.number('rewardMultiplierResearchPoints', { min: 0, max: 100 }),
@@ -62,6 +67,9 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
rbAirMixedChance: reader.number('rbAirMixedChance', { min: 0, max: 1 }),
rbNavalMixedChance: reader.number('rbNavalMixedChance', { min: 0, max: 1 }),
simColdWarMinMrank: reader.int('simColdWarMinMrank', { min: 0, max: 40 }),
simGroundInitialSpawnScore: reader.int('simGroundInitialSpawnScore', { min: 100, max: 5000 }),
pveAssaultMaxPlayers,
pveAssaultMaxBots,
strikeUcavModes: reader.stringList('strikeUcavModes'),
strikeUcavSessionMrankAllowance: reader.int('strikeUcavSessionMrankAllowance', { min: 0, max: 12 }),
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
@@ -11,7 +11,8 @@
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk';
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { intField } from '../profile/blk-fields.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
/**
@@ -84,17 +85,21 @@ export class CloudSettingsStore {
}
loadContainer(userId: string, blkType: string): BlkBlock | undefined {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined;
if (blkType === 'GBT_GENERAL_SETTINGS') this.#ensureDefaultGeneralSettings(userId);
const blkPath = this.#blkPath(userId, blkType);
if (!existsSync(blkPath)) return undefined;
if (isValidUserId(userId) && blkType === 'GBT_GENERAL_SETTINGS') this.#ensureDefaultGeneralSettings(userId);
try {
return decodeBlk(readFileSync(blkPath));
return this.loadSavedContainer(userId, blkType);
} catch {
return undefined;
}
}
/** Read persisted settings without creating defaults or ignoring malformed data. */
loadSavedContainer(userId: string, blkType: string): BlkBlock | undefined {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined;
const blkPath = this.#blkPath(userId, blkType);
return existsSync(blkPath) ? decodeBlk(readFileSync(blkPath)) : undefined;
}
saveUpload(userId: string, upload: ParsedGblkUpload): boolean {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(upload.blkType)) return false;
const meta = this.#loadMeta(userId);
@@ -111,6 +116,17 @@ export class CloudSettingsStore {
return true;
}
/** Store a launcher edit at a version newer than the server and client copies. */
replaceContainer(userId: string, blkType: string, container: BlkBlock, cachedVersion: number): void {
const content = findBlock(container, 'content');
if (!content || !isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) throw new Error('Invalid cloud settings container.');
const previous = this.#loadMeta(userId).blocks[blkType]?.version ?? 0;
const version = Math.max(previous, intField(container, 'version'), cachedVersion) + 1;
if (!Number.isInteger(version) || version > 0x7fffffff) throw new Error('Cloud settings version exceeds the supported range.');
const contentHash = createHash('md5').update(encodeBlk({ ...content, name: '' })).digest('hex');
this.saveUpload(userId, { blkType, version, contentHash, container });
}
saveBulkUploads(userId: string, uploads: ReadonlyArray<ParsedGblkUpload>): number {
let savedCount = 0;
for (const upload of uploads) {
+138
View File
@@ -0,0 +1,138 @@
import type { BlkBlock } from '@wto/blk';
import type { CrewSkillData } from '../game-data/datasets/crew-skills.ts';
import { setSkillLevel, skillLevel } from '../profile/profile-crew-skills.ts';
import type { VehicleType } from '../research/vehicle-types.ts';
const CREW_TYPES = ['air', 'tank', 'ship', 'human'] as const;
export type CrewType = (typeof CREW_TYPES)[number];
// Stock baseunittypes.nut assigns the same crew type to aircraft and helicopters, ships and boats.
export const CREW_TYPE_BY_VEHICLE: Readonly<Partial<Record<VehicleType, CrewType>>> = {
Aircraft: 'air', Helicopter: 'air', Tank: 'tank', Ship: 'ship', Boat: 'ship', Human: 'human',
};
// crew.nut getSkillCrewLevel rounds each contribution to 0.01; crewwndhandler.nut displays half levels.
const LEVEL_SCALE = 100;
const DISPLAY_STEP = 0.5;
export interface CrewLevelSkill {
readonly page: string;
readonly skill: string;
readonly types: readonly CrewType[];
readonly min: number;
readonly max: number;
readonly step: number;
readonly contributions: readonly number[];
}
export function crewLevelSkills(data: CrewSkillData): CrewLevelSkill[] {
const { levelRatio, levelSteps } = data;
if (levelRatio === null || !Number.isFinite(levelRatio) || levelRatio <= 0 ||
levelSteps === null || !Number.isSafeInteger(levelSteps) || levelSteps < 1) {
throw new Error('Invalid crew level ratio or step count in config/crew_skills.blk.');
}
return data.pages.flatMap((page) => page.skills.flatMap((skill) => {
const tags = (skill.type || page.type).split(/[; ]+/);
const types = CREW_TYPES.filter((type) => tags.includes(type));
if (!types.length) return [];
const max = skill.levelCosts.length;
const min = skill.minLevel;
if (!max || !Number.isSafeInteger(min) || min < 0 || min > max) {
throw new Error(`Invalid crew skill range for ${page.name}/${skill.name}.`);
}
const step = Math.ceil(max / Math.min(levelSteps, max));
const contributions = Array.from({ length: max + 1 }, (_, value) => Math.round(value / max * levelRatio * LEVEL_SCALE));
return [{ page: page.name, skill: skill.name, types, min, max, step, contributions }];
})).sort((a, b) => a.page.localeCompare(b.page, 'en') || a.skill.localeCompare(b.skill, 'en'));
}
export function crewSkillValue(crew: BlkBlock | undefined, skill: CrewLevelSkill): number {
return crew ? Math.min(skill.max, Math.max(skill.min, skillLevel(crew, skill.page, skill.skill))) : skill.min;
}
export function displayedCrewLevel(contribution: number): number {
return Math.round(contribution / (LEVEL_SCALE * DISPLAY_STEP)) * DISPLAY_STEP;
}
export function crewLevels(crew: BlkBlock | undefined, skills: readonly CrewLevelSkill[], types: readonly CrewType[]) {
return types.map((type) => {
const applicable = skills.filter((skill) => skill.types.includes(type));
const levelAt = (valueOf: (skill: CrewLevelSkill) => number) => displayedCrewLevel(
applicable.reduce((total, skill) => total + skill.contributions[valueOf(skill)]!, 0),
);
return {
type, level: levelAt((skill) => crewSkillValue(crew, skill)),
min: levelAt((skill) => skill.min), max: levelAt((skill) => skill.max),
};
});
}
export interface CrewSkillChange {
readonly page: string;
readonly skill: string;
readonly value: number;
}
interface Allocation {
readonly shared: number;
readonly movement: number;
readonly value: number;
readonly previous?: Allocation;
}
function compareChanges(a: Allocation, b: Allocation): number {
return a.shared - b.shared || a.movement - b.movement;
}
function nextAllocations(sums: ReadonlyMap<number, Allocation>, skill: CrewLevelSkill, current: number, direction: number): Map<number, Allocation> {
// Existing saves may hold an intermediate value from a different version of the game.
const choices = new Set([current, skill.min, skill.max]);
for (let value = skill.step; value < skill.max; value += skill.step) if (value > skill.min) choices.add(value);
const next = new Map<number, Allocation>();
for (const value of choices) {
if ((value - current) * direction < 0) continue;
const contribution = skill.contributions[value]!;
const movement = Math.abs(contribution - skill.contributions[current]!);
const shared = skill.types.length > 1 ? movement : 0;
for (const [sum, previous] of sums) {
const total = sum + contribution;
const change = { value, shared: previous.shared + shared, movement: previous.movement + movement ** 2, previous };
const other = next.get(total);
if (!other || compareChanges(change, other) < 0) next.set(total, change);
}
}
return next;
}
/** Find the closest displayed level, preferring smaller changes to skills shared by crew types. */
export function planCrewLevel(crew: BlkBlock, skills: readonly CrewLevelSkill[], type: CrewType, target: number): CrewSkillChange[] {
const applicable = skills.filter((skill) => skill.types.includes(type));
const current = applicable.map((skill) => crewSkillValue(crew, skill));
const total = applicable.reduce((sum, skill, index) => sum + skill.contributions[current[index]!]!, 0);
const direction = Math.sign(target - displayedCrewLevel(total));
if (!direction) return [];
let sums = new Map<number, Allocation>([[0, { value: 0, shared: 0, movement: 0 }]]);
for (const [index, skill] of applicable.entries()) sums = nextAllocations(sums, skill, current[index]!, direction);
let best: { distance: number; allocation: Allocation } | undefined;
for (const [sum, allocation] of sums) {
const distance = Math.abs(displayedCrewLevel(sum) - target);
if (!best || distance < best.distance || (distance === best.distance && compareChanges(allocation, best.allocation) < 0)) {
best = { distance, allocation };
}
}
const changes: CrewSkillChange[] = [];
let allocation = best?.allocation;
for (let index = applicable.length - 1; index >= 0 && allocation; index -= 1) {
const { page, skill } = applicable[index]!;
if (allocation.value !== current[index]) changes.push({ page, skill, value: allocation.value });
allocation = allocation.previous;
}
return changes;
}
export function applyCrewLevelPlan(crew: BlkBlock, changes: readonly CrewSkillChange[]): void {
for (const { page, skill, value } of changes) setSkillLevel(crew, page, skill, value);
}
@@ -77,13 +77,17 @@ interface SpawnScoreParameterSet {
readonly classCosts: Readonly<Record<string, number>>;
}
export interface SpawnScoreRankOverride extends SpawnScoreParameterSet {
readonly minMrank: number;
readonly maxMrank: number;
}
export interface SpawnScoreRules {
readonly common: Readonly<Record<string, number>>;
readonly tankHistorical: SpawnScoreParameterSet;
readonly overrides: ReadonlyArray<SpawnScoreParameterSet & {
readonly minMrank: number;
readonly maxMrank: number;
}>;
readonly overrides: readonly SpawnScoreRankOverride[];
readonly tankSimulation: SpawnScoreParameterSet;
readonly tankSimulationOverrides: readonly SpawnScoreRankOverride[];
}
export interface BattleSpawnRulesData {
@@ -106,7 +110,7 @@ const STRATEGIC_YIELD_MIN_KT = 1000;
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
id: 'battle-spawn-rules',
version: 4,
version: 5,
extract: (source) => {
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
@@ -123,17 +127,24 @@ export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
function extractSpawnScore(root: BlkBlock | undefined): SpawnScoreRules {
const tankHistorical = blockAt(root, 'TankHistorical');
const tankSimulation = blockAt(root, 'TankSimulation');
return {
common: numericParams(root),
tankHistorical: spawnScoreParams(tankHistorical),
overrides: (blockAt(tankHistorical, 'override_params_by_session_rank')?.blocks ?? []).map((block) => ({
...spawnScoreParams(block),
minMrank: numberField(block, 'minMRank') ?? -1,
maxMrank: numberField(block, 'maxMRank') ?? -1,
})),
overrides: extractRankOverrides(tankHistorical),
tankSimulation: spawnScoreParams(tankSimulation),
tankSimulationOverrides: extractRankOverrides(tankSimulation),
};
}
function extractRankOverrides(block: BlkBlock | undefined): SpawnScoreRankOverride[] {
return (blockAt(block, 'override_params_by_session_rank')?.blocks ?? []).map((entry) => ({
...spawnScoreParams(entry),
minMrank: numberField(entry, 'minMRank') ?? -1,
maxMrank: numberField(entry, 'maxMRank') ?? -1,
}));
}
function spawnScoreParams(block: BlkBlock | undefined): SpawnScoreParameterSet {
return {
parameters: numericParams(block),
@@ -19,6 +19,8 @@ import type { Dataset } from './dataset.ts';
export interface SkillFacts {
readonly name: string;
readonly type: string;
readonly minLevel: number;
/** Cost of each level, index 0 = level 1; the length is the maximum level. */
readonly levelCosts: readonly number[];
}
@@ -49,6 +51,8 @@ export interface CrewTrainingPrices {
}
export interface CrewSkillData {
readonly levelRatio: number | null;
readonly levelSteps: number | null;
readonly pages: readonly SkillPage[];
readonly packs: readonly SkillPointPack[];
readonly aceDiscountStages: readonly AceDiscountStage[];
@@ -57,13 +61,16 @@ export interface CrewSkillData {
export const crewSkillData: Dataset<CrewSkillData> = {
id: 'crew-skills',
version: 2,
version: 3,
extract: (source) => {
const skills = findBlock(source.readBlk('char.vromfs.bin', 'config/crew_skills.blk'), 'crew_skills');
const definitions = source.readBlk('char.vromfs.bin', 'config/crew_skills.blk');
const skills = findBlock(definitions, 'crew_skills');
const warpoints = source.readBlk('char.vromfs.bin', 'config/warpoints.blk');
const packs = findBlock(warpoints, 'crewSkillPointsCost');
const aceReduce = findBlock(warpoints, 'expert_to_ace_cost_reduce');
return {
levelRatio: numberField(definitions, 'skill_to_level_ratio') ?? null,
levelSteps: numberField(definitions, 'max_skill_level_steps') ?? null,
pages: (skills?.blocks ?? []).map(pageOf),
packs: (packs?.blocks ?? []).map((pack) => ({ name: pack.name, goldenEagles: numberField(pack, 'costGold') ?? 0, points: numberField(pack, 'crewExp') ?? 0 })),
aceDiscountStages: (aceReduce?.blocks ?? [])
@@ -90,7 +97,12 @@ function pageOf(page: BlkBlock): SkillPage {
const levels = findBlock(skill, 'skill_level_exp');
const levelCosts: number[] = [];
for (let level = 1; levels && numberField(levels, `level${level}`) !== undefined; level++) levelCosts.push(numberField(levels, `level${level}`)!);
return { name: skill.name, levelCosts };
return {
name: skill.name, levelCosts,
type: stringField(skill, 'type') ?? '',
// The native skill constructor defaults min_skill_level to zero (2.61.0.37 0x933d50).
minLevel: numberField(skill, 'min_skill_level') ?? 0,
};
}),
};
}
@@ -21,6 +21,7 @@ const MISSION_LIST = 'config/mislist.blk';
const MULTIPLAYER_SECTION = 'skirmish';
const MISSION_FOLDER = 'gamedata/missions/';
export const AIR_HISTORICAL_MISSION_FOLDER = 'gamedata/missions/cta/planes/historical/';
const PVE_MISSION_FOLDER = 'gamedata/missions/pve_missions/';
const AIRFIELD_LAYOUT = /\/template_airfields_(low|mid|high|top)_ranks\.blk$/;
export interface MissionCategory {
@@ -43,9 +44,16 @@ interface AirfieldLayoutData {
export type GroundBattleMode = 'bttl' | 'conq' | 'dom';
export interface MissionRankBand {
readonly minMRank: number;
readonly maxMRank: number;
}
export interface MissionHeader extends AirfieldLayoutData {
readonly name: string;
readonly path: string;
/** Ranked preset import windows declared by PvE survival missions (`imports.import_record.rankRange`). */
readonly pveRankRanges?: readonly MissionRankBand[];
/** Ground mission tactical layout derived from mislist category (or suffix fallback for events). */
readonly groundMode?: GroundBattleMode;
readonly level?: string;
@@ -76,7 +84,7 @@ export interface MultiplayerMissions {
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
id: 'multiplayer-missions',
version: 5,
version: 6,
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`);
@@ -157,9 +165,11 @@ function readHeader(
countryAllies: stringField(mission, 'country_allies'),
timeLimit: numberField(mission, 'timeLimit'),
};
const pveRankRanges = path.startsWith(PVE_MISSION_FOLDER) ? readImportRankRanges(document) : [];
return {
name,
path,
...(pveRankRanges.length > 0 ? { pveRankRanges } : {}),
...airfields,
...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),
allowedUnitTypes: boolFields(blockAt(mission, 'allowedUnitTypes')),
@@ -214,6 +224,17 @@ function readAirfieldPart(source: DatasetSource, path: string, knownPaths: Reado
return { airfieldLayouts };
}
function readImportRankRanges(mission: BlkBlock): MissionRankBand[] {
const ranges: MissionRankBand[] = [];
for (const entry of blockAt(mission, 'imports')?.blocks ?? []) {
const range = findParam(entry, 'rankRange')?.value;
if (range?.type === 'ipoint2' && range.value[0] >= 0 && range.value[1] >= range.value[0]) {
ranges.push({ minMRank: range.value[0], maxMRank: range.value[1] });
}
}
return ranges;
}
const SCALAR_TYPES = new Set(['string', 'int', 'real', 'bool']);
/** The parameters whose values survive the dataset cache's JSON unchanged. */
@@ -23,6 +23,12 @@ export const AIR_REALISTIC_MISSIONS: MissionSelection = {
rankByAirfieldLayout: true,
};
export const AIR_EC_MISSIONS: MissionSelection = {
categories: ['air_i2m'],
requireAllowed: ['aircraft'],
exclude: NEWBIE_MISSIONS,
};
export const GROUND_BATTLE_MISSIONS: MissionSelection = {
categories: ['air_ground_Dom', 'air_ground_Conq', 'air_ground_Bttl'],
requireAllowed: ['tank'],
@@ -9,6 +9,7 @@
* (they do not state their vehicle types, so none is required of them);
* - helicopters: the "air_h2m" category (helicopter PvE missions).
*/
import { UNLIMITED_RESPAWNS } from '../mode-definition.ts';
import type { GameModeDeclaration } from './game-mode-declaration.ts';
const PVE = { difficulty: 'arcade', displayType: 'pve_battle' } as const;
@@ -16,11 +17,13 @@ const PVE = { difficulty: 'arcade', displayType: 'pve_battle' } as const;
export const PVE_BATTLES: readonly GameModeDeclaration[] = [
{
gameModeId: 21, name: 'air_assault_pve', economicName: 'air_assault_pve', locName: 'chapters/assault', ...PVE,
maxRespawns: UNLIMITED_RESPAWNS,
requiredClass: 'aircraft', allowedClasses: ['aircraft'],
missions: { categories: ['pve'], requireAllowed: ['aircraft'], include: /_survive_arcade_pve$/i },
},
{
gameModeId: 22, name: 'tank_assault_pve', economicName: 'tank_assault_pve', locName: 'chapters/air_ground_PvE', ...PVE,
maxRespawns: UNLIMITED_RESPAWNS,
requiredClass: 'tank', allowedClasses: ['tank'],
missions: { categories: ['pve'], requireAllowed: [], include: /battle_for_survival_8_players_pve$/i },
},
@@ -9,8 +9,9 @@
* display text "missions/ship_event_simulator". The ground economic name is the rank.blk
* ExpSkillBonus{} key (see random-battles.ts).
*/
import { UNLIMITED_RESPAWNS } from '../mode-definition.ts';
import type { GameModeDeclaration } from './game-mode-declaration.ts';
import { AIR_BATTLE_MISSIONS, GROUND_BATTLE_MISSIONS, NAVAL_BATTLE_MISSIONS } from './mission-pools.ts';
import { AIR_EC_MISSIONS, GROUND_BATTLE_MISSIONS, NAVAL_BATTLE_MISSIONS } from './mission-pools.ts';
const SIMULATOR = { difficulty: 'simulator', displayType: 'regular', chapter: 'simulation_battles' } as const;
@@ -18,7 +19,8 @@ export const SIMULATOR_BATTLES: readonly GameModeDeclaration[] = [
{
gameModeId: 11, name: 'air_simulation_timeDelay_battles', economicName: 'air_simulation_timeDelay_battles',
locName: 'missions/air_simulation_timeDelay_battles', ...SIMULATOR,
requiredClass: 'aircraft', allowedClasses: ['aircraft'], missions: AIR_BATTLE_MISSIONS,
maxRespawns: UNLIMITED_RESPAWNS,
requiredClass: 'aircraft', allowedClasses: ['aircraft'], missions: AIR_EC_MISSIONS,
},
{
gameModeId: 12, name: 'tank_random_battles_simulation', economicName: 'tank_event_in_random_battles_simulation',
+1
View File
@@ -7,6 +7,7 @@ export { AccountStore, type RegistrationResult } from './accounts/account-store.
export { REGISTRATION_PATH } from './accounts/registration-service.ts';
export { HEALTH_PATH } from './transport/http-listener.ts';
export { editSaveResearch, readSaveResearch } from './saves/save-research.ts';
export { editSaveCrew, previewSaveCrewEdit, readSaveCrews, syncRestoredCrewPresets } from './saves/save-crews.ts';
export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
+7 -2
View File
@@ -19,6 +19,7 @@ import { setParam, type BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import { currentClanSeason } from '../clans/clan-season.ts';
import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts';
import { CLOSED_CREWS, CREWS, crewsForClient } from './profile-crews.ts';
import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts';
import { clearStoreCart } from './profile-store-cart.ts';
import { clientHangarSpares } from './profile-vehicle-state.ts';
@@ -29,8 +30,12 @@ export function clientProfile(saved: BlkBlock, account: Account, nowMs = Date.no
const profile: BlkBlock = {
name: saved.name,
params: [...saved.params],
blocks: saved.blocks.filter((block) => block.name !== DAILY_SPARES_BLOCK)
.map((block) => block.name === 'hangar' ? clientHangarSpares(block) : block),
blocks: saved.blocks.filter((block) => block.name !== DAILY_SPARES_BLOCK && block.name !== CLOSED_CREWS)
.map((block) => {
if (block.name === 'hangar') return clientHangarSpares(block);
if (block.name === CREWS) return crewsForClient(saved, block);
return block;
}),
};
clearStoreCart(profile);
const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON;
+65 -21
View File
@@ -11,9 +11,11 @@
* "trained" lists the vehicles the crew is trained for (repeated), "current" is the vehicle
* in its slot.
*/
import { ensureBlock, type BlkBlock } from '@wto/blk';
import { emptyBlock, ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
import { stringField } from './blk-fields.ts';
const CREWS = 'crews';
export const CREWS = 'crews';
export const CLOSED_CREWS = 'wtoClosedCrews';
const VEHICLES = 'aircrafts';
const TRAINED = 'trained';
const CURRENT = 'current';
@@ -21,43 +23,54 @@ const CURRENT = 'current';
const CREW_NAME = /^c(\d+)$/;
export function crewOf(profile: BlkBlock, crewId: number): BlkBlock | undefined {
return profile.blocks.find((block) => block.name === CREWS)?.blocks.find((crew) => crew.name === `c${crewId}`);
return findBlock(profile, CREWS)?.blocks.find((crew) => crew.name === `c${crewId}`);
}
/** Every crew block, in profile order. */
export function allCrews(profile: BlkBlock): readonly BlkBlock[] {
return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => CREW_NAME.test(crew.name));
return (findBlock(profile, CREWS)?.blocks ?? []).filter((crew) => CREW_NAME.test(crew.name));
}
export function closedCrews(profile: BlkBlock): readonly BlkBlock[] {
return (findBlock(profile, CLOSED_CREWS)?.blocks ?? []).filter((crew) => CREW_NAME.test(crew.name));
}
export function crewIdOf(crew: BlkBlock): number {
return Number(CREW_NAME.exec(crew.name)?.[1] ?? -1);
}
export function crewCountry(crew: BlkBlock): string {
return stringField(crew, 'country');
}
export function crewVehicle(crew: BlkBlock): string {
const vehicles = findBlock(crew, VEHICLES);
return vehicles ? stringField(vehicles, CURRENT) : '';
}
export function crewCountOf(profile: BlkBlock, country: string): number {
return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => crewCountry(crew) === country).length;
return allCrews(profile).filter((crew) => crewCountry(crew) === country).length;
}
/** Non-empty vehicles currently slotted in the country's crews, in profile order. */
export function crewVehiclesOfCountry(profile: BlkBlock, country: string): string[] {
return allCrews(profile)
.filter((crew) => crewCountry(crew) === country)
.flatMap((crew) => {
const current = crew.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value.length > 0 ? [current.value] : [];
});
.map(crewVehicle)
.filter(Boolean);
}
/** Vehicle slotted in the country's `slotIndex`-th crew (`idInCountry`), if non-empty. */
export function crewSlotVehicleOfCountry(profile: BlkBlock, country: string, slotIndex: number): string | undefined {
if (!Number.isInteger(slotIndex) || slotIndex < 0) return undefined;
const crew = allCrews(profile).filter((entry) => crewCountry(entry) === country)[slotIndex];
const current = crew?.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value.length > 0 ? current.value : undefined;
return crew ? (crewVehicle(crew) || undefined) : undefined;
}
/** Crew block in `country` currently equipping `vehicle` (or trained for it as fallback). */
export function crewForVehicleInCountry(profile: BlkBlock, country: string, vehicle: string): BlkBlock | undefined {
const crews = allCrews(profile).filter((entry) => crewCountry(entry) === country);
const slotted = crews.find((entry) => {
const current = entry.blocks.find((block) => block.name === VEHICLES)?.params.find((param) => param.name === CURRENT)?.value;
return current?.type === 'string' && current.value === vehicle;
});
const slotted = crews.find((entry) => crewVehicle(entry) === vehicle);
if (slotted) return slotted;
return crews.find((entry) =>
(entry.blocks.find((block) => block.name === VEHICLES)?.params ?? []).some(
@@ -65,17 +78,48 @@ export function crewForVehicleInCountry(profile: BlkBlock, country: string, vehi
));
}
/** Add an empty crew for the country, numbered after every existing crew; returns its id. */
/** Add an empty crew with an ID above the active and archived IDs. */
export function addCrew(profile: BlkBlock, country: string): number {
const crews = ensureBlock(profile, CREWS);
const id = crews.blocks.reduce((highest, crew) => Math.max(highest, Number(CREW_NAME.exec(crew.name)?.[1] ?? -1)), -1) + 1;
crews.blocks.push({ name: `c${id}`, params: [{ name: 'country', value: { type: 'string', value: country } }], blocks: [{ name: VEHICLES, params: [], blocks: [] }] });
const id = Math.max(-1, ...crews.blocks.map(crewIdOf), ...closedCrews(profile).map(crewIdOf)) + 1;
crews.blocks.push({ name: `c${id}`, params: [{ name: 'country', value: { type: 'string', value: country } }], blocks: [emptyBlock(VEHICLES)] });
return id;
}
function crewCountry(crew: BlkBlock): string | undefined {
const value = crew.params.find((param) => param.name === 'country')?.value;
return value?.type === 'string' ? value.value : undefined;
export function closeCrew(profile: BlkBlock, crew: BlkBlock): void {
const active = ensureBlock(profile, CREWS);
active.blocks = active.blocks.filter((entry) => entry !== crew);
ensureBlock(profile, CLOSED_CREWS).blocks.push(crew);
}
export function reopenCrew(profile: BlkBlock, crew: BlkBlock): number {
const closed = ensureBlock(profile, CLOSED_CREWS);
closed.blocks = closed.blocks.filter((entry) => entry !== crew);
const active = ensureBlock(profile, CREWS);
const id = crewIdOf(crew);
const position = active.blocks.findIndex((entry) => crewIdOf(entry) > id);
if (position < 0) active.blocks.push(crew);
else active.blocks.splice(position, 0, crew);
return id;
}
/** A newly purchased or imported slot can reuse the country's first archived crew. */
export function openNextCrew(profile: BlkBlock, country: string): number {
const closed = closedCrews(profile).filter((crew) => crewCountry(crew) === country).sort((a, b) => crewIdOf(a) - crewIdOf(b))[0];
if (!closed) return addCrew(profile, country);
// Buying a slot leaves it empty. Its trained vehicles and qualifications stay available.
emptyCrewSlot(closed);
return reopenCrew(profile, closed);
}
/** The native crew vector is indexed by the c<N> suffix. Keep vacant IDs out of country lists. */
export function crewsForClient(profile: BlkBlock, active: BlkBlock): BlkBlock {
const closed = closedCrews(profile);
if (!closed.length) return active;
const vacant = closed.map(({ name }): BlkBlock => ({
name, params: [{ name: 'country', value: { type: 'string', value: '' } }], blocks: [emptyBlock(VEHICLES)],
}));
return { ...active, blocks: [...active.blocks, ...vacant].sort((a, b) => crewIdOf(a) - crewIdOf(b)) };
}
/** Leave the crew's slot empty; the vehicles it is trained for stay trained. */
@@ -2,7 +2,9 @@
* The save format's upgrade steps (saves/save-upgrades.ts), in version order. A later change
* to what saves hold adds a new step; released steps are not removed.
*/
import { ensureBlock } from '@wto/blk';
import { SaveUpgrades } from '../saves/save-upgrades.ts';
import { CLOSED_CREWS } from './profile-crews.ts';
import { applyStartingContent, type StartingContent } from './starting-content.ts';
export function profileUpgrades(content: StartingContent): SaveUpgrades {
@@ -14,5 +16,7 @@ export function profileUpgrades(content: StartingContent): SaveUpgrades {
addStartingContent,
// 2 -> 3: rank I open in every branch.
addStartingContent,
// 3 -> 4: archive closed crew slots separately from active crews.
(profile) => { ensureBlock(profile, CLOSED_CREWS); },
]);
}
@@ -3,11 +3,10 @@
*
* The price of a country's next slot is config/rank.blk crew_slots slot<N>, N being the
* number of crews the country has, as the client shows it (get_crew_slot_cost, aces.exe
* 2.61.0.37 0x90eaa0). Without a slot<N> there is nothing more to buy. The new crew is empty
* and numbered after every existing crew.
* 2.61.0.37 0x90eaa0). Without a slot<N> there is nothing more to buy. The purchased slot is empty.
*/
import type { BlkBlock } from '@wto/blk';
import { addCrew, crewCountOf } from '../profile/profile-crews.ts';
import { crewCountOf, openNextCrew } from '../profile/profile-crews.ts';
import { canAfford, pay } from '../profile/profile-currency.ts';
import type { ResearchRules } from './research-rules.ts';
import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts';
@@ -18,6 +17,6 @@ export function buyCrewSlot(profile: BlkBlock, rules: ResearchRules, country: st
if (!price) return refused('NOT_AVAILABLE');
if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY');
pay(profile, price);
addCrew(profile, country);
openNextCrew(profile, country);
return ACCEPTED;
}
@@ -0,0 +1,23 @@
import { lstatSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { intField } from '../profile/blk-fields.ts';
import { readBackupBlk } from './import/backup-blk.ts';
// The same local settings files accepted by the launcher's online backup import.
const SETTINGS_FILE_LIMIT = 32 * 1024 * 1024;
export function cachedSettingsVersion(folders: readonly string[], fileName: string): number {
let latest = 0;
for (const folder of folders) {
const path = join(folder, fileName);
try {
const stats = lstatSync(path);
if (!stats.isFile() || stats.size > SETTINGS_FILE_LIMIT) continue;
const version = intField(readBackupBlk(readFileSync(path)), 'version');
if (Number.isInteger(version)) latest = Math.max(latest, version);
} catch {
// A missing or unreadable cache does not have a version to supersede.
}
}
return latest;
}
+21 -92
View File
@@ -1,7 +1,6 @@
import { createHash } from 'node:crypto';
import { existsSync, lstatSync, readFileSync, rmSync } from 'node:fs';
import { basename, join } from 'node:path';
import { encodeBlk, findBlock, type BlkBlock } from '@wto/blk';
import { findBlock, type BlkBlock } from '@wto/blk';
import { AccountStore } from '../../accounts/account-store.ts';
import { ClanStore } from '../../clans/clan-store.ts';
import { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
@@ -10,15 +9,17 @@ import { crewSlotPrices } from '../../game-data/datasets/rank-settings.ts';
import { vehicleCatalogue } from '../../game-data/datasets/vehicle-catalogue.ts';
import { GameFiles } from '../../game-data/game-files.ts';
import { intField } from '../../profile/blk-fields.ts';
import { addCrew, allCrews, crewOf, emptyCrewSlot, putVehicleInCrew, trainCrewFor } from '../../profile/profile-crews.ts';
import { allCrews, crewCountry, crewIdOf, emptyCrewSlot, openNextCrew, putVehicleInCrew, trainCrewFor } from '../../profile/profile-crews.ts';
import { addOwnedVehicle } from '../../profile/profile-hangar.ts';
import { ownsModification, writeModificationRecord } from '../../profile/profile-modifications.ts';
import { addUnlock, earnedUnlocks } from '../../profile/profile-unlocks.ts';
import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.ts';
import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts';
import { loadTuning } from '../../tuning/tuning.ts';
import { cachedSettingsVersion } from '../client-settings-cache.ts';
import type { SaveLocation } from '../save-editor.ts';
import { loadSaveLabels, localizeVehicleName } from '../save-labels.ts';
import { findSlotbarAccounts, namedBlock, parseSlotbarPreset } from '../slotbar-presets.ts';
import { readBackupBlk } from './backup-blk.ts';
const TYPES = {
@@ -30,7 +31,6 @@ type BackupName = keyof typeof TYPES;
const SURVIVAL = /^(tank_tool_kit|tank_extinguisher|tank_crew_replacement|tank_laser_rangefinder|tank_night_vision|tank_thermal_vision)$/;
const TALISMAN = 'premExpMul';
const CREW_BLOCK_NAME = /^c(\d+)$/;
const FIRST_CHOSEN_UNIT_TYPES = [
'chosen_unit_type_tank',
'chosen_unit_type_air',
@@ -117,19 +117,9 @@ export function importOfficialBackup(
}
const store = new CloudSettingsStore(dataFolder);
const existing = store.buildMetaBlk(userId);
for (const file of files) {
const blkType = TYPES[file.name];
const localCachedVersion = offlineClientCacheFolders.reduce(
(highest, folder) => Math.max(highest, readCachedLocalVersion(folder, file.name)),
0,
);
const version = Math.max(file.version, intField(findBlock(existing, blkType), 'version'), localCachedVersion) + 1;
if (version > 0x7fffffff) throw new Error('Imported settings version exceeds the supported range.');
const contentHash = createHash('md5').update(encodeBlk({ ...file.content, name: '' })).digest('hex');
if (!store.saveUpload(userId, { blkType, version, contentHash, container: file.container })) {
throw new Error('Could not store the imported settings.');
}
store.replaceContainer(userId, blkType, file.container, cachedSettingsVersion(offlineClientCacheFolders, file.name));
for (const folder of offlineClientCacheFolders) {
clearCachedLocalFile(folder, file.name);
}
@@ -181,12 +171,6 @@ function readFile(path: string): OfficialFile {
return { name: name as BackupName, version, container, content };
}
function findAccountsBlock(content: BlkBlock): BlkBlock | undefined {
const settings = findBlock(content, 'settings');
const customSettings = settings ? findBlock(settings, 'customSettings') : undefined;
return (customSettings ? findBlock(customSettings, 'accounts') : undefined) ?? namedBlock(content, 'accounts');
}
function pickSourceAccountBlock(accounts: BlkBlock): BlkBlock | undefined {
const withPresets = accounts.blocks.filter((entry) => findBlock(entry, 'slotbar_presets') !== undefined);
return withPresets.find((entry) => entry.name.endsWith('.production'))
@@ -196,7 +180,7 @@ function pickSourceAccountBlock(accounts: BlkBlock): BlkBlock | undefined {
}
function readPresets(content: BlkBlock): ParsedPreset[] {
const accounts = findAccountsBlock(content);
const accounts = findSlotbarAccounts(content);
const sourceAccount = accounts ? pickSourceAccountBlock(accounts) : undefined;
const root = (sourceAccount ? findBlock(sourceAccount, 'slotbar_presets') : undefined)
?? namedBlock(content, 'slotbar_presets');
@@ -211,59 +195,17 @@ function readPresets(content: BlkBlock): ParsedPreset[] {
}
function parsePresetString(country: string, raw: string, selected: boolean): ParsedPreset | null {
const parts = raw.split('|');
if (parts.length < 3) return null;
const selectedCrewText = parts[0] ?? '';
const crewIdsText = parts[1] ?? '';
const vehiclesText = parts[2] ?? '';
const title = parts[3] ?? '';
const gameModeId = parts[4] ?? '';
const crewInSlotsText = parts[5] ?? '';
const selectedOnlineCrewId = /^\d+$/.test(selectedCrewText) ? Number(selectedCrewText) : -1;
const crewIdTokens = crewIdsText ? crewIdsText.split(',') : [];
const vehicleTokens = vehiclesText ? vehiclesText.split(',') : [];
const slotCrewIds = crewInSlotsText
? crewInSlotsText.split(',').filter((token) => /^\d+$/.test(token)).map(Number)
: [];
const units: PresetUnit[] = [];
const pairCount = Math.min(crewIdTokens.length, vehicleTokens.length);
for (let i = 0; i < pairCount; i += 1) {
const vehicle = vehicleTokens[i]?.trim() ?? '';
const token = crewIdTokens[i]?.trim() ?? '';
if (!vehicle || !/^\d+$/.test(token)) continue;
units.push({ onlineCrewId: Number(token), vehicle });
}
const slotCrewOrder: number[] = [];
const seen = new Set<number>();
for (const id of slotCrewIds) {
if (!seen.has(id)) {
seen.add(id);
slotCrewOrder.push(id);
}
}
return { country, title, gameModeId, selected, selectedOnlineCrewId, slotCrewOrder, units };
}
function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
if (block.name === name) return block;
for (const child of block.blocks) {
const found = namedBlock(child, name);
if (found) return found;
}
}
function crewIdOfBlock(crew: BlkBlock): number {
return Number(CREW_BLOCK_NAME.exec(crew.name)?.[1] ?? -1);
const preset = parseSlotbarPreset(raw);
if (!preset) return null;
return {
country, selected, title: preset.title, gameModeId: preset.gameModeId,
selectedOnlineCrewId: preset.selectedCrewId, slotCrewOrder: preset.slotCrewOrder,
units: preset.units.map(({ crewId, vehicle }) => ({ onlineCrewId: crewId, vehicle })),
};
}
function countryCrewsOf(profile: BlkBlock, country: string): BlkBlock[] {
return allCrews(profile).filter((crew) =>
crew.params.some((param) => param.name === 'country' && param.value.type === 'string' && param.value.value === country),
);
return allCrews(profile).filter((crew) => crewCountry(crew) === country);
}
/**
@@ -328,7 +270,7 @@ function buildExistingCrewMappings(
for (const country of countries) {
if (!research.techTree.hasCountry(country)) continue;
const crews = countryCrewsOf(profile, country);
const offlineCrewIds = crews.map(crewIdOfBlock).filter((id) => id >= 0);
const offlineCrewIds = crews.map(crewIdOf).filter((id) => id >= 0);
const onlineOrder = orderedOnlineCrewIdsForCountry(presets, country);
const onlineToOffline = new Map<number, number>();
for (let slot = 0; slot < Math.min(onlineOrder.length, offlineCrewIds.length); slot += 1) {
@@ -390,20 +332,21 @@ function applyVehicles(
const countries = new Set(presets.map(({ country }) => country));
for (const country of countries) {
if (!research.techTree.hasCountry(country)) continue;
const crews = countryCrewsOf(profile, country);
let crews = countryCrewsOf(profile, country);
const onlineOrder = orderedOnlineCrewIdsForCountry(presets, country);
const targetSlots = Math.min(Math.max(crews.length, onlineOrder.length), Math.max(slotLimit, crews.length));
while (crews.length < targetSlots) {
crews.push(crewOf(profile, addCrew(profile, country))!);
openNextCrew(profile, country);
crews = countryCrewsOf(profile, country);
}
const offlineCrewIds = crews.map(crewIdOfBlock).filter((id) => id >= 0);
const offlineCrewIds = crews.map(crewIdOf).filter((id) => id >= 0);
const onlineToOffline = new Map<number, number>();
const onlineToCrew = new Map<number, BlkBlock>();
for (let slot = 0; slot < Math.min(onlineOrder.length, crews.length); slot += 1) {
const onlineId = onlineOrder[slot]!;
const crew = crews[slot]!;
const offlineId = crewIdOfBlock(crew);
const offlineId = crewIdOf(crew);
if (offlineId >= 0) {
onlineToOffline.set(onlineId, offlineId);
onlineToCrew.set(onlineId, crew);
@@ -445,7 +388,7 @@ function remapGlobalAccountSettings(
mappings: ReadonlyMap<string, CountryCrewMapping>,
known: ReadonlySet<string>,
): void {
const accounts = findAccountsBlock(content);
const accounts = findSlotbarAccounts(content);
if (!accounts) return;
const source = pickSourceAccountBlock(accounts);
if (!source) return;
@@ -508,20 +451,6 @@ function rewritePresetString(
].join('|');
}
function readCachedLocalVersion(cacheFolder: string, fileName: BackupName): number {
const path = join(cacheFolder, fileName);
if (!existsSync(path)) return 0;
try {
const stats = lstatSync(path);
if (!stats.isFile() || stats.size > 32 * 1024 * 1024) return 0;
const block = readBackupBlk(readFileSync(path));
const version = intField(block, 'version', 0);
return Number.isInteger(version) && version > 0 ? version : 0;
} catch {
return 0;
}
}
function clearCachedLocalFile(cacheFolder: string, fileName: BackupName): void {
const path = join(cacheFolder, fileName);
if (!existsSync(path)) return;
+198
View File
@@ -0,0 +1,198 @@
import { createHash } from 'node:crypto';
import { emptyBlock, encodeBlk, type BlkBlock } from '@wto/blk';
import { AccountStore } from '../accounts/account-store.ts';
import { ClanStore } from '../clans/clan-store.ts';
import { CloudSettingsStore } from '../cloud-settings/cloud-settings-store.ts';
import { applyCrewLevelPlan, CREW_TYPE_BY_VEHICLE, crewLevels, crewLevelSkills, planCrewLevel, type CrewType } from '../crew/crew-levels.ts';
import { crewSkillData } from '../game-data/datasets/crew-skills.ts';
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { crewSlotPrices } from '../game-data/datasets/rank-settings.ts';
import { uiLabels } from '../game-data/datasets/ui-labels.ts';
import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts';
import { GameFiles } from '../game-data/game-files.ts';
import {
addCrew, allCrews, closeCrew, closedCrews, CLOSED_CREWS, CREWS, crewCountOf, crewCountry, crewIdOf, crewVehicle,
crewVehiclesOfCountry, emptyCrewSlot, reopenCrew,
} from '../profile/profile-crews.ts';
import { ownsVehicle } from '../profile/profile-hangar.ts';
import { setUpProfiles } from '../profiles-setup.ts';
import { TechTree } from '../research/tech-tree.ts';
import { loadTuning } from '../tuning/tuning.ts';
import { cachedSettingsVersion } from './client-settings-cache.ts';
import { readSaveSnapshot, type SaveLocation } from './save-editor.ts';
import { loadSaveLabels, localizeVehicleName } from './save-labels.ts';
import { countrySlotbarPresets, removeCrewFromPresets } from './slotbar-presets.ts';
const SETTINGS_TYPE = 'GBT_GENERAL_SETTINGS';
const SETTINGS_FILE = 'global.blk';
export type SaveCrewEdit =
| { readonly action: 'add' }
| { readonly action: 'open' | 'close'; readonly crewId: number }
| { readonly action: 'level'; readonly crewId: number; readonly type: CrewType; readonly target: number };
type CrewEditError = 'not-found' | 'invalid' | 'slot-limit' | 'stale';
function loadEditor(location: SaveLocation, userId: string) {
const accounts = new AccountStore(location.dataFolder);
if (!accounts.byUserId(userId)) return undefined;
const gameFiles = new GameFiles(location.gameFolder);
const datasets = new DatasetCache(location.dataFolder, gameFiles, () => {});
const template = gameFiles.newAccountTemplate();
const vehicles = datasets.load(vehicleCatalogue);
const branchesByCountry = new Map<string, Set<CrewType>>();
const skills = crewLevelSkills(datasets.load(crewSkillData));
for (const { country, type: vehicleType } of new TechTree(vehicles).branches()) {
const types = branchesByCountry.get(country) ?? new Set<CrewType>();
const type = CREW_TYPE_BY_VEHICLE[vehicleType];
if (type && skills.some((skill) => skill.types.includes(type))) types.add(type);
branchesByCountry.set(country, types);
}
return {
accounts, gameFiles, datasets, vehicles, branchesByCountry, skills, template,
snapshot: readSaveSnapshot(location.dataFolder, userId) ?? template,
slotPrices: datasets.load(crewSlotPrices), names: datasets.load(uiLabels),
labels: loadSaveLabels(location.dataFolder, location.gameFolder),
cloud: new CloudSettingsStore(location.dataFolder),
};
}
type Editor = NonNullable<ReturnType<typeof loadEditor>>;
function countryCrews(profile: BlkBlock, country: string) {
const active = allCrews(profile).filter((crew) => crewCountry(crew) === country);
const archived = closedCrews(profile).filter((crew) => crewCountry(crew) === country);
return { active, archived };
}
function slotLimits(editor: Editor, country: string, active: number, archived: number) {
const min = crewCountOf(editor.template, country);
const max = editor.slotPrices.length;
const canOpen = editor.slotPrices[active] != null;
return { min, max, canOpen, canAdd: canOpen && active + archived < max };
}
function viewOf(editor: Editor, profile: BlkBlock, selection?: string) {
const countries = [...editor.branchesByCountry.keys()].map((id) => ({ id, name: editor.names[id] ?? { en: id, zh: id } }));
const selected = countries.find(({ id }) => id === selection)?.id ?? countries[0]?.id ?? null;
const { active, archived } = countryCrews(profile, selected ?? '');
const { min, max, canOpen, canAdd } = slotLimits(editor, selected ?? '', active.length, archived.length);
const types = [...(selected ? editor.branchesByCountry.get(selected) ?? [] : [])];
const crews = [...active, ...archived].sort((a, b) => crewIdOf(a) - crewIdOf(b)).map((crew) => {
const open = active.includes(crew);
return {
id: crewIdOf(crew), open, canToggle: open ? active.length > min : canOpen,
vehicle: localizeVehicleName(crewVehicle(crew), editor.labels),
levels: crewLevels(crew, editor.skills, types),
};
});
return { countries, selected, activeCount: active.length, min, max, canAdd, crews };
}
export function readSaveCrews(location: SaveLocation, userId: string, country?: string) {
const editor = loadEditor(location, userId);
return editor ? viewOf(editor, editor.snapshot, country) : null;
}
function applySlotEdit(editor: Editor, profile: BlkBlock, country: string, edit: Exclude<SaveCrewEdit, { action: 'level' }>):
{ crew: BlkBlock; vehicle: string } | { error: CrewEditError } {
const { active, archived } = countryCrews(profile, country);
const limits = slotLimits(editor, country, active.length, archived.length);
if (edit.action === 'add') {
if (!limits.canAdd) return { error: 'slot-limit' };
const id = addCrew(profile, country);
return { crew: allCrews(profile).find((entry) => crewIdOf(entry) === id)!, vehicle: '' };
}
const crew = (edit.action === 'close' ? active : archived).find((entry) => crewIdOf(entry) === edit.crewId);
if (!crew) return { error: 'invalid' };
const vehicle = crewVehicle(crew);
if (edit.action === 'close') {
if (active.length <= limits.min) return { error: 'slot-limit' };
closeCrew(profile, crew);
} else {
if (!limits.canOpen) return { error: 'slot-limit' };
if (vehicle && (!ownsVehicle(profile, vehicle) || crewVehiclesOfCountry(profile, country).includes(vehicle))) emptyCrewSlot(crew);
reopenCrew(profile, crew);
}
return { crew, vehicle };
}
function applyLevelEdit(editor: Editor, profile: BlkBlock, country: string, edit: Extract<SaveCrewEdit, { action: 'level' }>) {
const { active, archived } = countryCrews(profile, country);
const crew = [...active, ...archived].find((entry) => crewIdOf(entry) === edit.crewId);
const types = [...editor.branchesByCountry.get(country)!];
if (!crew || !types.includes(edit.type) || !Number.isFinite(edit.target)) return { error: 'invalid' } as const;
const before = crewLevels(crew, editor.skills, types);
const range = before.find(({ type }) => type === edit.type)!;
if (edit.target < range.min || edit.target > range.max) return { error: 'invalid' } as const;
const changes = planCrewLevel(crew, editor.skills, edit.type, edit.target);
applyCrewLevelPlan(crew, changes);
const levels = crewLevels(crew, editor.skills, types).map(({ type, level }, index) => ({ type, before: before[index]!.level, after: level }));
return { crew, levels, changed: changes.length > 0 };
}
function isCrewBlock({ name }: BlkBlock): boolean {
return name === CREWS || name === CLOSED_CREWS;
}
function prepareEdit(editor: Editor, userId: string, country: string, edit: SaveCrewEdit) {
if (!editor.branchesByCountry.has(country)) return { error: 'invalid' } as const;
const original = editor.snapshot;
const draft = { ...original, blocks: original.blocks.map((block) => isCrewBlock(block) ? structuredClone(block) : block) };
const result = edit.action === 'level' ? applyLevelEdit(editor, draft, country, edit) : applySlotEdit(editor, draft, country, edit);
if ('error' in result) return { error: result.error };
const cloud = edit.action === 'close' ? editor.cloud.loadSavedContainer(userId, SETTINGS_TYPE) : undefined;
const presets = cloud && countrySlotbarPresets(cloud, userId, country);
const previousPresets = presets && encodeBlk(presets);
const affected = presets && edit.action === 'close' ? removeCrewFromPresets(presets, edit.crewId) : [];
const preview = {
crewId: crewIdOf(result.crew),
vehicle: localizeVehicleName('vehicle' in result ? result.vehicle : '', editor.labels),
restoredVehicle: localizeVehicleName(edit.action === 'open' ? crewVehicle(result.crew) : '', editor.labels),
presets: affected.map((preset) => ({ ...preset, vehicle: localizeVehicleName(preset.vehicle, editor.labels) })),
levels: 'levels' in result ? result.levels : [],
changed: 'changed' in result ? result.changed : true,
};
const hash = createHash('sha256').update(JSON.stringify({ userId, country, edit, preview }));
hash.update(encodeBlk({ ...emptyBlock(), blocks: original.blocks.filter(isCrewBlock) }));
hash.update(encodeBlk({ ...emptyBlock(), blocks: draft.blocks.filter(isCrewBlock) }));
if (previousPresets) hash.update(previousPresets);
return { draft, cloud: affected.length ? cloud : undefined, preview: { ...preview, token: hash.digest('hex') } };
}
export function previewSaveCrewEdit(location: SaveLocation, userId: string, country: string, edit: SaveCrewEdit) {
const editor = loadEditor(location, userId);
if (!editor) return { error: 'not-found' } as const;
const plan = prepareEdit(editor, userId, country, edit);
return 'error' in plan ? { error: plan.error } : { preview: plan.preview };
}
export function editSaveCrew(
location: SaveLocation, userId: string, country: string, edit: SaveCrewEdit, token: string, cacheFolders: readonly string[],
) {
const editor = loadEditor(location, userId);
if (!editor) return { error: 'not-found' } as const;
const plan = prepareEdit(editor, userId, country, edit);
if ('error' in plan) return { error: plan.error };
if (plan.preview.token !== token) return { error: 'stale' } as const;
if (!plan.preview.changed) return { view: viewOf(editor, editor.snapshot, country) };
const tuning = loadTuning(location.dataFolder, () => {});
const clans = new ClanStore(location.dataFolder, tuning.clans);
const { profiles } = setUpProfiles(location.dataFolder, editor.gameFiles, editor.datasets, tuning, { accounts: editor.accounts, clans }, editor.vehicles);
const saved = profiles.update(userId, (profile) => {
profile.blocks = [...profile.blocks.filter((block) => !isCrewBlock(block)), ...plan.draft.blocks.filter(isCrewBlock)];
});
if (plan.cloud) editor.cloud.replaceContainer(userId, SETTINGS_TYPE, plan.cloud, cachedSettingsVersion(cacheFolders, SETTINGS_FILE));
return { view: viewOf(editor, saved, country) };
}
/** Make restored presets take precedence over the offline game's newer cached settings. */
export function syncRestoredCrewPresets(dataFolder: string, userId: string, cacheFolders: readonly string[]): void {
const cloud = new CloudSettingsStore(dataFolder);
const settings = cloud.loadSavedContainer(userId, SETTINGS_TYPE);
if (settings) cloud.replaceContainer(userId, SETTINGS_TYPE, settings, cachedSettingsVersion(cacheFolders, SETTINGS_FILE));
}
+87
View File
@@ -0,0 +1,87 @@
import { findBlock, type BlkBlock } from '@wto/blk';
export interface SlotbarPreset {
readonly selectedCrewId: number;
readonly units: readonly { crewId: number; vehicle: string }[];
readonly slotCrewOrder: readonly number[];
readonly title: string;
readonly gameModeId: string;
readonly extraFields: readonly string[];
}
function parseCrewId(text: string): number | undefined {
const id = Number(text);
return /^\d+$/.test(text) && Number.isSafeInteger(id) ? id : undefined;
}
/** The fields serialized by saveCountryPreset in scripts/slotbar/slotbarpresets.nut. */
export function parseSlotbarPreset(raw: string): SlotbarPreset | undefined {
const fields = raw.split('|');
if (fields.length < 3) return undefined;
const [selected = '', crews = '', vehicles = '', title = '', gameModeId = '', order = '', ...extraFields] = fields;
const crewIds = crews.split(',');
const units = vehicles.split(',').flatMap((name, index) => {
const vehicle = name.trim();
const crewId = parseCrewId(crewIds[index]?.trim() ?? '');
return vehicle && crewId !== undefined ? [{ crewId, vehicle }] : [];
});
const slotIds = order.split(',').map(parseCrewId).filter((id) => id !== undefined);
return { selectedCrewId: parseCrewId(selected) ?? -1, units, slotCrewOrder: [...new Set(slotIds)], title, gameModeId, extraFields };
}
export function formatSlotbarPreset(preset: SlotbarPreset): string {
return [
preset.selectedCrewId,
preset.units.map(({ crewId }) => crewId).join(','),
preset.units.map(({ vehicle }) => vehicle).join(','),
preset.title, preset.gameModeId,
preset.slotCrewOrder.join(','),
...preset.extraFields,
].join('|');
}
export function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
if (block.name === name) return block;
for (const child of block.blocks) {
const found = namedBlock(child, name);
if (found) return found;
}
return undefined;
}
export function findSlotbarAccounts(content: BlkBlock): BlkBlock | undefined {
const settings = findBlock(content, 'settings');
const customSettings = settings && findBlock(settings, 'customSettings');
return (customSettings && findBlock(customSettings, 'accounts')) ?? namedBlock(content, 'accounts');
}
export function countrySlotbarPresets(container: BlkBlock, userId: string, country: string): BlkBlock | undefined {
const content = findBlock(container, 'content');
const accounts = content && findSlotbarAccounts(content);
const account = accounts && findBlock(accounts, `${userId}.production`);
const countries = account && findBlock(account, 'slotbar_presets');
return countries && findBlock(countries, country);
}
/** Remove a closed crew from the paired crew/vehicle arrays and the preset's slot order. */
export function removeCrewFromPresets(country: BlkBlock, crewId: number) {
const removed: { index: number; title: string; vehicle: string; empty: boolean }[] = [];
let index = 0;
for (const parameter of country.params) {
if (parameter.name !== 'preset' || parameter.value.type !== 'string') continue;
const presetIndex = index++;
const preset = parseSlotbarPreset(parameter.value.value);
if (!preset) continue;
const assignment = preset.units.find((unit) => unit.crewId === crewId);
if (!assignment && preset.selectedCrewId !== crewId && !preset.slotCrewOrder.includes(crewId)) continue;
const units = preset.units.filter((unit) => unit.crewId !== crewId);
parameter.value = { type: 'string', value: formatSlotbarPreset({
...preset, units,
selectedCrewId: preset.selectedCrewId === crewId ? (units[0]?.crewId ?? -1) : preset.selectedCrewId,
slotCrewOrder: preset.slotCrewOrder.filter((id) => id !== crewId),
}) };
removed.push({ index: presetIndex, title: preset.title, vehicle: assignment?.vehicle ?? '', empty: Boolean(assignment && units.length === 0) });
}
return removed;
}
+2 -2
View File
@@ -8,7 +8,7 @@ import { vehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts';
import { GameFiles } from '../game-data/game-files.ts';
import { InventoryCatalogue } from '../inventory/itemdef-catalogue.ts';
import { intField, stringField } from '../profile/blk-fields.ts';
import { allCrews } from '../profile/profile-crews.ts';
import { allCrews, closedCrews } from '../profile/profile-crews.ts';
import { ACTIVE_LISTS } from '../profile/profile-items.ts';
import { normalizeModificationBlocks, recordName } from '../profile/profile-modifications.ts';
import { loadTuning } from '../tuning/tuning.ts';
@@ -45,7 +45,7 @@ export function prepareTransferredProfile(location: SaveLocation, bytes: Uint8Ar
}
}
normalizeModificationBlocks(profile);
for (const crew of allCrews(profile)) {
for (const crew of [...allCrews(profile), ...closedCrews(profile)]) {
const aircraft = findBlock(crew, 'aircrafts');
if (aircraft) {
aircraft.params = aircraft.params.filter(({ name, value }) =>
+204 -24
View File
@@ -8,6 +8,8 @@ import {
type GroundAiConfig,
type GroundAiDriveMode,
type GroundAiMode,
type GroundAiNavCosts,
type GroundAiPathFollow,
} from '@wto/patcher';
import type { TankLineupWeights } from '../battle/battle-ranks.ts';
import { tuningFiles } from './tuning-loader.ts';
@@ -44,14 +46,31 @@ export function readGroundAiTuning(reader: TuningReader): GroundAiTuning {
crowd: readCrowdSection(reader.object('crowd')),
terrain: readTerrainSection(reader.object('terrain')),
navigation: readNavigationSection(reader.object('navigation')),
navEngine: readNavEngineSection(reader.object('navEngine')),
navCostsTracked: readNavCosts(reader.object('navCostsTracked')),
navCostsWheeled: readNavCosts(reader.object('navCostsWheeled')),
pathFollow: readPathFollowSection(reader.object('pathFollow')),
navBake: {
crushableMaxRiExtraHp: reader.object('navBake').number('crushableMaxRiExtraHp', { min: 0, max: 1000 }),
},
perception: readPerceptionSection(reader.object('perception')),
stateMachine: readStateMachineSection(reader.object('stateMachine')),
tactics: readTacticsSection(reader.object('tactics')),
estimation: readEstimationSection(reader.object('estimation')),
threat: readThreatSection(reader.object('threat')),
turret: readTurretSection(reader.object('turret')),
behavior: readBehaviorSection(reader.object('behavior')),
fireControl: readFireControlSection(reader.object('fireControl')),
diagnostics: {
telemetry: diag.bool('telemetry'),
telemetryIntervalSec: diag.number('telemetryIntervalSec', { min: 0.5, max: 60 }),
battleStats: diag.bool('battleStats'),
statsLogIntervalSec: diag.number('statsLogIntervalSec', { min: 10, max: 600 }),
statsSampleSec: diag.number('statsSampleSec', { min: 0.2, max: 5 }),
statsSampleRangeM: diag.number('statsSampleRangeM', { min: 50, max: 1000 }),
statsRearArcDeg: diag.number('statsRearArcDeg', { min: 30, max: 180 }),
trace: diag.bool('trace'),
traceIntervalSec: diag.number('traceIntervalSec', { min: 0.1, max: 5 }),
},
};
}
@@ -173,6 +192,91 @@ function readTerrainSection(terrain: TuningReader): GroundAiTuning['terrain'] {
};
}
function readNavEngineSection(engine: TuningReader): GroundAiTuning['navEngine'] {
return {
enabled: engine.bool('enabled'),
allowFallback: engine.bool('allowFallback'),
snapRadiusM: engine.number('snapRadiusM', { min: 2, max: 40 }),
goalSnapRadiusM: engine.number('goalSnapRadiusM', { min: 5, max: 150 }),
pathBudgetMsPerFrame: engine.number('pathBudgetMsPerFrame', { min: 0.05, max: 5 }),
trafficCostPerPath: engine.number('trafficCostPerPath', { min: 0, max: 3 }),
trafficCostMaxMul: engine.number('trafficCostMaxMul', { min: 1, max: 10 }),
trafficHoldSec: engine.number('trafficHoldSec', { min: 0, max: 120 }),
cornerOffsetM: engine.number('cornerOffsetM', { min: 0, max: 5 }),
};
}
function readNavCosts(costs: TuningReader): GroundAiNavCosts {
const read = (key: keyof GroundAiNavCosts) => costs.number(key, { min: 0.1, max: 20 });
return {
road: read('road'),
bridge: read('bridge'),
ground: read('ground'),
rough: read('rough'),
forest: read('forest'),
crushable: read('crushable'),
shallowWater: read('shallowWater'),
chokepoint: read('chokepoint'),
};
}
function readPathFollowSection(pf: TuningReader): GroundAiPathFollow {
const n = (key: keyof GroundAiPathFollow, min: number, max: number) => pf.number(key, { min, max });
const lookahead = {
trackedLookaheadMinM: n('trackedLookaheadMinM', 2, 40),
trackedLookaheadMaxM: n('trackedLookaheadMaxM', 4, 60),
wheeledLookaheadMinM: n('wheeledLookaheadMinM', 2, 40),
wheeledLookaheadMaxM: n('wheeledLookaheadMaxM', 4, 60),
};
if (lookahead.trackedLookaheadMaxM < lookahead.trackedLookaheadMinM || lookahead.wheeledLookaheadMaxM < lookahead.wheeledLookaheadMinM) {
throw new TuningError('tuning file ground-ai.jsonc: pathFollow lookahead maximum must not be below its minimum');
}
return {
replanIntervalSec: n('replanIntervalSec', 1, 15),
replanGoalMoveM: n('replanGoalMoveM', 3, 80),
offCorridorReplanM: n('offCorridorReplanM', 3, 60),
lookaheadTimeSec: n('lookaheadTimeSec', 0.3, 5),
...lookahead,
cornerAngleDeg: n('cornerAngleDeg', 10, 120),
cornerLateralAccelMps2: n('cornerLateralAccelMps2', 0.5, 10),
cornerBrakeDecelMps2: n('cornerBrakeDecelMps2', 0.5, 10),
arriveRadiusM: n('arriveRadiusM', 1, 20),
arriveMinSpeedMps: n('arriveMinSpeedMps', 0.3, 6),
narrowWallMarginM: n('narrowWallMarginM', 0.2, 6),
narrowSpeedMps: n('narrowSpeedMps', 1, 15),
bumperRayM: n('bumperRayM', 2, 20),
bumperStopM: n('bumperStopM', 0.3, 6),
bumperBlockSec: n('bumperBlockSec', 0.2, 5),
trafficTtcSec: n('trafficTtcSec', 0.5, 8),
yieldWaitMaxSec: n('yieldWaitMaxSec', 0.5, 15),
stationarySpeedMps: n('stationarySpeedMps', 0.2, 4),
passMarginM: n('passMarginM', 0.2, 4),
passSpeedMps: n('passSpeedMps', 1, 12),
blockWaitSec: n('blockWaitSec', 0.5, 15),
blockTtlSec: n('blockTtlSec', 3, 120),
contactGapM: n('contactGapM', 0.2, 3),
contactReverseSec: n('contactReverseSec', 0.3, 5),
contactRepeatSec: n('contactRepeatSec', 3, 120),
stuckWindowSec: n('stuckWindowSec', 1, 15),
stuckMinProgressM: n('stuckMinProgressM', 0.2, 10),
unstickReverseM: n('unstickReverseM', 2, 25),
unstickReverseSec: n('unstickReverseSec', 0.8, 10),
unstickRepeatSec: n('unstickRepeatSec', 2, 60),
unstickMaxAttempts: pf.int('unstickMaxAttempts', { min: 1, max: 10 }),
jamRadiusM: n('jamRadiusM', 2, 50),
jamCostMul: n('jamCostMul', 1, 50),
jamTtlSec: n('jamTtlSec', 5, 600),
giveUpRadiusM: n('giveUpRadiusM', 3, 50),
giveUpCostMul: n('giveUpCostMul', 1, 200),
rubbleRadiusM: n('rubbleRadiusM', 1, 40),
rubbleCostMul: n('rubbleCostMul', 1, 50),
rubbleTtlSec: n('rubbleTtlSec', 5, 600),
wreckRadiusM: n('wreckRadiusM', 1, 40),
wreckCostMul: n('wreckCostMul', 1, 50),
wreckTtlSec: n('wreckTtlSec', 5, 600),
};
}
function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation'] {
const driveModeRaw = nav.string('driveMode');
const driveMode = GROUND_AI_DRIVE_MODES.find((candidate): candidate is GroundAiDriveMode => candidate === driveModeRaw);
@@ -189,12 +293,8 @@ function readNavigationSection(nav: TuningReader): GroundAiTuning['navigation']
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 }),
movingFireSpeedRampMps: nav.number('movingFireSpeedRampMps', { min: 0.2, max: 5 }),
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 }),
};
@@ -209,8 +309,15 @@ function readPerceptionSection(perc: TuningReader): GroundAiTuning['perception']
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 }),
gunFovHalfDeg: perc.number('gunFovHalfDeg', { min: 5, max: 90 }),
nearAwareM: perc.number('nearAwareM', { min: 30, max: 400 }),
nearArcDeg: perc.number('nearArcDeg', { min: 90, max: 360 }),
midAwareM: perc.number('midAwareM', { min: 100, max: 1500 }),
nearSpotMul: perc.number('nearSpotMul', { min: 1, max: 5 }),
midSpotMul: perc.number('midSpotMul', { min: 1, max: 6 }),
lookAroundSec: perc.number('lookAroundSec', { min: 2, max: 60 }),
lookAroundHoldSec: perc.number('lookAroundHoldSec', { min: 0.2, max: 5 }),
discoverScore: perc.number('discoverScore', { min: 0.05, max: 0.95 }),
};
}
@@ -221,17 +328,12 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine
throw new TuningError('tuning file ground-ai.jsonc: stateMachine.coverMaxDistM must be > coverMinDistM');
}
return {
preaimAngleDeg: sm.number('preaimAngleDeg', { min: 1.0, max: 30.0 }),
movingShotWaitSec: sm.number('movingShotWaitSec', { min: 0.25, max: 5.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 }),
@@ -244,8 +346,6 @@ function readStateMachineSection(sm: TuningReader): GroundAiTuning['stateMachine
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 }),
@@ -255,6 +355,64 @@ function readTacticsSection(tactics: TuningReader): GroundAiTuning['tactics'] {
};
}
function readThreatSection(threat: TuningReader): GroundAiTuning['threat'] {
return {
rangeScaleM: threat.number('rangeScaleM', { min: 50, max: 3000 }),
discoveredMul: threat.number('discoveredMul', { min: 0, max: 1 }),
aimConeDeg: threat.number('aimConeDeg', { min: 5, max: 90 }),
notAimingMul: threat.number('notAimingMul', { min: 0, max: 1 }),
unseenMul: threat.number('unseenMul', { min: 0, max: 1 }),
hitMemorySec: threat.number('hitMemorySec', { min: 0, max: 60 }),
hitMul: threat.number('hitMul', { min: 1, max: 5 }),
};
}
function readTurretSection(turret: TuningReader): GroundAiTuning['turret'] {
return {
minDwellSec: turret.number('minDwellSec', { min: 0, max: 5 }),
switchMargin: turret.number('switchMargin', { min: 0, max: 3 }),
scanArcDeg: turret.number('scanArcDeg', { min: 0, max: 180 }),
scanPeriodSec: turret.number('scanPeriodSec', { min: 1, max: 30 }),
fixedMountYawSpanDeg: turret.number('fixedMountYawSpanDeg', { min: 0, max: 180 }),
};
}
function readBehaviorSection(bhv: TuningReader): GroundAiTuning['behavior'] {
return {
scoreIntervalSec: bhv.number('scoreIntervalSec', { min: 0.1, max: 3 }),
advanceHoldSec: bhv.number('advanceHoldSec', { min: 0, max: 10 }),
engageHoldSec: bhv.number('engageHoldSec', { min: 0, max: 10 }),
haltHoldSec: bhv.number('haltHoldSec', { min: 0, max: 10 }),
coverHoldSec: bhv.number('coverHoldSec', { min: 0, max: 10 }),
repositionHoldSec: bhv.number('repositionHoldSec', { min: 0, max: 10 }),
postHoldSec: bhv.number('postHoldSec', { min: 0, max: 10 }),
disperseHoldSec: bhv.number('disperseHoldSec', { min: 0, max: 10 }),
targetValueWeight: bhv.number('targetValueWeight', { min: 0, max: 1 }),
nearThreatHaltBonus: bhv.number('nearThreatHaltBonus', { min: 0, max: 1 }),
switchMargin: bhv.number('switchMargin', { min: 0, max: 1 }),
advanceScore: bhv.number('advanceScore', { min: 0, max: 1 }),
engageScore: bhv.number('engageScore', { min: 0, max: 1 }),
urgencyWeight: bhv.number('urgencyWeight', { min: 0, max: 1 }),
haltScore: bhv.number('haltScore', { min: 0, max: 1 }),
crossfirePenalty: bhv.number('crossfirePenalty', { min: 0, max: 1 }),
coverScore: bhv.number('coverScore', { min: 0, max: 1 }),
coverDangerWeight: bhv.number('coverDangerWeight', { min: 0, max: 1 }),
coverOffensivePenalty: bhv.number('coverOffensivePenalty', { min: 0, max: 1 }),
coverRetrySec: bhv.number('coverRetrySec', { min: 0.5, max: 30 }),
repositionScore: bhv.number('repositionScore', { min: 0, max: 1 }),
holdScore: bhv.number('holdScore', { min: 0, max: 1 }),
disperseScore: bhv.number('disperseScore', { min: 0, max: 1 }),
urgentSpeedKeep: bhv.number('urgentSpeedKeep', { min: 0, max: 1 }),
hullAngleDeg: bhv.number('hullAngleDeg', { min: 0, max: 45 }),
faceToleranceDeg: bhv.number('faceToleranceDeg', { min: 3, max: 60 }),
faceMinDanger: bhv.number('faceMinDanger', { min: 0, max: 2 }),
reverseTravelAngleDeg: bhv.number('reverseTravelAngleDeg', { min: 60, max: 180 }),
reverseMaxTurnDistM: bhv.number('reverseMaxTurnDistM', { min: 0, max: 200 }),
reverseMinSpeedMps: bhv.number('reverseMinSpeedMps', { min: 0.5, max: 10 }),
reverseHoldSec: bhv.number('reverseHoldSec', { min: 0, max: 20 }),
};
}
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 });
@@ -285,29 +443,51 @@ function readFireControlSection(fc: TuningReader): GroundAiTuning['fireControl']
if (midRangeM <= closeRangeM || longRangeM <= midRangeM) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl ranges must satisfy closeRangeM < midRangeM < longRangeM');
}
const closeRangeMaxSpeedKmh = fc.number('closeRangeMaxSpeedKmh', { min: 3.6, max: 100 });
const pointBlankMaxSpeedKmh = fc.number('pointBlankMaxSpeedKmh', { min: 3.6, max: 100 });
if (pointBlankMaxSpeedKmh < closeRangeMaxSpeedKmh) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl.pointBlankMaxSpeedKmh must be >= closeRangeMaxSpeedKmh');
const fireThreshold = fc.number('fireThreshold', { min: 0.05, max: 0.95 });
const minFireThreshold = fc.number('minFireThreshold', { min: 0.01, max: 0.9 });
if (minFireThreshold > fireThreshold) {
throw new TuningError('tuning file ground-ai.jsonc: fireControl.minFireThreshold must be <= fireThreshold');
}
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 }),
closeRangeMaxSpeedKmh,
pointBlankMaxSpeedKmh,
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 }),
aimErrorDeg: fc.number('aimErrorDeg', { min: 0.01, max: 2 }),
moveErrDegPerMps: fc.number('moveErrDegPerMps', { min: 0, max: 3 }),
turnErrDegPerDegSec: fc.number('turnErrDegPerDegSec', { min: 0, max: 0.5 }),
stabErrFactor: fc.number('stabErrFactor', { min: 0.02, max: 1 }),
targetHalfHeightM: fc.number('targetHalfHeightM', { min: 0.3, max: 2 }),
fireThreshold,
minFireThreshold,
aimingThresholdBonus: fc.number('aimingThresholdBonus', { min: 0, max: 0.5 }),
closeThresholdBonus: fc.number('closeThresholdBonus', { min: 0, max: 0.5 }),
enemyReloadThresholdBonus: fc.number('enemyReloadThresholdBonus', { min: 0, max: 0.5 }),
enemyReloadSec: fc.number('enemyReloadSec', { min: 0, max: 15 }),
fleetingThresholdBonus: fc.number('fleetingThresholdBonus', { min: 0, max: 0.5 }),
fleetingLateralMps: fc.number('fleetingLateralMps', { min: 0.5, max: 15 }),
fleetingLookAheadSec: fc.number('fleetingLookAheadSec', { min: 0.1, max: 2 }),
reloadThresholdPenalty: fc.number('reloadThresholdPenalty', { min: 0, max: 0.5 }),
longReloadSec: fc.number('longReloadSec', { min: 1, max: 60 }),
lowAmmoRounds: fc.int('lowAmmoRounds', { min: 1, max: 60 }),
lowAmmoThresholdPenalty: fc.number('lowAmmoThresholdPenalty', { min: 0, max: 0.5 }),
aimSkill: fc.number('aimSkill', { min: 0, max: 1 }),
autocannonMinShotsPerSec: fc.number('autocannonMinShotsPerSec', { min: 0.5, max: 30 }),
retreatThresholdPenalty: fc.number('retreatThresholdPenalty', { min: 0, max: 0.6 }),
minShotIntervalSec: fc.number('minShotIntervalSec', { min: 0.1, max: 5 }),
autocannonAimSlack: fc.number('autocannonAimSlack', { min: 1, max: 10 }),
burstSec: fc.number('burstSec', { min: 0.2, max: 6 }),
burstPauseSec: fc.number('burstPauseSec', { min: 0, max: 5 }),
autocannonReloadDetectSec: fc.number('autocannonReloadDetectSec', { min: 0.1, max: 3 }),
auxWeapons: fc.bool('auxWeapons'),
auxMaxRangeM: fc.number('auxMaxRangeM', { min: 30, max: 1500 }),
auxFireAtArmor: fc.bool('auxFireAtArmor'),
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 }),
+7 -2
View File
@@ -49,10 +49,15 @@
// Naval mission score per point of damage dealt: official ("0.15 -> 0.18", same update).
"navalDamageScorePerPoint": 0.18,
// Offline Air Arcade balance. Damage pays proportionally to health removed from an enemy
// mini-base. The final hit also earns the destruction score.
// Offline bombing-zone balance (Air Arcade, Air Realistic, and Air Simulator). Damage pays
// proportionally to health removed from an enemy mini-base. The final hit also earns the
// destruction score.
"bombingZone": { "damageScore": 150, "destructionScore": 30 },
// Assault PvE reward/score multiplier for mission wave AI units (offline: overrides stock
// PvP warpoints.blk aiKillK=0.3 so Assault wave kills pay full baseline value).
"pveAiKillMul": 1.0,
// The score at which an event pays exactly one reference kill (warpoints.blk aKill), by victim
// group. ground 180 and air 450 are the official base kill scores; naval 216 is the official
// example of a boat destruction ("now awarded with 216 points instead of 180").
+10
View File
@@ -36,6 +36,16 @@
// Simulator Battles Cold War / modern bloc cutoff mrank (18 = BR 7.0).
"simColdWarMinMrank": 18,
// Ground Simulator starting Spawn Points (offline: warpoints.blk TankSimulation defines
// per-class cost multipliers against base_respawn_points_coef, while the live event server
// sets the starting 1000 SP pool so aircraft/helicopters and multiple tanks are spawnable).
"simGroundInitialSpawnScore": 1000,
// Assault PvE (air_assault_pve / tank_assault_pve) team capacity (1 local player + friendly AI
// teammates in Team A; stock Assault rooms hold 8 defenders).
"pveAssaultMaxPlayers": 8,
"pveAssaultMaxBots": 7,
// Strike UCAV extra slot (char.vromfs.bin config/wpcost.blk ucav_*_killstreak, one per country).
// The game files have no rule for when it is offered or what it costs (online the battle server
// decides). Offer rule, offline design: in these game modes, when the session's top rank is at
+292 -28
View File
@@ -94,6 +94,36 @@
"ridgeMaxShots": 6
},
// Offline map baking parameters. These are copied into the generator's per-level POI input.
"coverMap": {
"minCoverHeightM": 1.55,
"peekMinM": 3.5,
"peekMaxM": 6.0,
"retreatMinM": 8.0,
// Low dry-stone fence models observed to give unreliable shot protection.
"excludedCoverRendinst": ["stone_fence_a", "damaged_stone_fence_a", "damaged_stone_fence_b"]
},
// Offline navigation mesh baking parameters, copied into the generator's per-level POI input.
"navBake": {
// Placed objects whose stock destructionImpulse (config/rendinst_dmg.blk) is at most this
// value are knocked down by tanks and baked as crushable rather than solid (N*s).
"crushableMaxImpulse": 45000,
// riExtra objects with no destructionImpulse are crushable when their stock hp is at most
// this value (wooden fences 2, dry-stone fences 12, car wrecks 20; buses 40).
"crushableMaxRiExtraHp": 20,
// Passages narrower than this many standard-tier vehicle widths are flagged as chokepoints.
"chokepointMaxWidthVehicles": 2.0,
// Water up to maxFordDepthM is forded (shallow water cost). Deeper water is a wall: besides the
// vehicle's half width, the mesh keeps deepWaterMarginM more ground from it where the bank is
// less than deepWaterBankHeightM above the water line,
// because low banks slope into the water and a hull at the water line slides in. Higher quays
// and ramps keep only the half width.
"maxFordDepthM": 0.9,
"deepWaterMarginM": 1.5,
"deepWaterBankHeightM": 1.0
},
"navigation": {
// "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement.
"driveMode": "vehicle_phys",
@@ -101,17 +131,131 @@
"steerSign": 1.0,
"deadEchoSec": 1.2,
"controlTimeoutSec": 1.0,
"cornerBrakeAccel": 1.75,
// Speed error at which the moving-fire controller applies full throttle or braking.
"movingFireSpeedRampMps": 1.0,
"pivotAngleDeg": 75.0,
"stuckWindowSec": 3.6,
"stuckMinMoveM": 2.0,
"unstickReverseSec": 3.0,
"tacticalReverseDistM": 34.0,
"tacticalReverseMaxSec": 9.5
},
// Baked navigation packs (tools/navgen), loaded once per battle by the native engine.
"navEngine": {
"enabled": true,
// When the battle's pack is missing or broken: true keeps the script's own navigation for the
// whole battle, false leaves the bots standing so the problem shows (testing). Decided once at
// battle start, never in the middle of a battle.
"allowFallback": true,
// Farthest a path's start or goal may lie from the mesh.
"snapRadiusM": 12.0,
// A goal farther than snapRadiusM from the mesh (a position chosen by tactics inside a building
// or on a slope) is moved to the nearest walkable point within this distance; beyond it the
// goal counts as unreachable. Also used to find the way back onto the mesh.
"goalSnapRadiusM": 40.0,
// Path searches are spread over frames; this is the search time allowed per frame.
"pathBudgetMsPerFrame": 0.5,
// Team traffic: each teammate path planned within trafficHoldSec through a stretch of mesh
// raises its cost for the team's next searches by trafficCostPerPath, up to trafficCostMaxMul,
// so a team spreads over parallel routes instead of queueing on one road.
"trafficCostPerPath": 0.35,
"trafficCostMaxMul": 2.5,
"trafficHoldSec": 12.0,
// Path corners are moved this far away from the building or wall they turn around.
"cornerOffsetM": 1.5
},
// Path cost multipliers per surface for tracked vehicles; chokepoint multiplies the surface cost
// of passages narrower than navBake.chokepointMaxWidthVehicles.
"navCostsTracked": {
"road": 0.75,
"bridge": 0.9,
"ground": 1.0,
"rough": 1.65,
"forest": 2.1,
"crushable": 2.4,
"shallowWater": 2.6,
"chokepoint": 1.8
},
// The same for wheeled vehicles.
"navCostsWheeled": {
"road": 0.55,
"bridge": 0.75,
"ground": 1.15,
"rough": 3.2,
"forest": 2.8,
"crushable": 3.5,
"shallowWater": 4.0,
"chokepoint": 2.2
},
// Following the path, local avoidance and unstick (offline values).
"pathFollow": {
// Plan again after this long, when the goal moved this far, or when the bot is this far off its path.
"replanIntervalSec": 3.5,
"replanGoalMoveM": 15.0,
"offCorridorReplanM": 12.0,
// Steering point: speed times lookaheadTimeSec, kept within the range of the vehicle kind.
"lookaheadTimeSec": 1.4,
"trackedLookaheadMinM": 6.0,
"trackedLookaheadMaxM": 18.0,
"wheeledLookaheadMinM": 10.0,
"wheeledLookaheadMaxM": 24.0,
// Path corners sharper than cornerAngleDeg are taken at the speed the sideways acceleration
// allows; the vehicle brakes toward it (and toward its destination) at cornerBrakeDecelMps2.
"cornerAngleDeg": 35.0,
"cornerLateralAccelMps2": 2.8,
"cornerBrakeDecelMps2": 2.0,
"arriveRadiusM": 3.0,
"arriveMinSpeedMps": 1.5,
// The mesh already keeps the vehicle's half width from walls; less room than this beyond it,
// or a baked chokepoint, counts as a narrow passage.
"narrowWallMarginM": 1.5,
"narrowSpeedMps": 4.5,
// Rays from both front corners of the hull for obstacles the baked mesh does not know.
"bumperRayM": 7.0,
"bumperStopM": 1.5,
"bumperBlockSec": 0.6,
// Moving vehicles that come within reach in trafficTtcSec: follow them, or in narrow passages
// give way to the bigger one for at most yieldWaitMaxSec.
"trafficTtcSec": 2.5,
"yieldWaitMaxSec": 3.0,
// Vehicles slower than stationarySpeedMps, wrecks and players' vehicles in the way are passed
// on the side the mesh leaves room, keeping passMarginM between hulls, at up to passSpeedMps.
"stationarySpeedMps": 1.0,
"passMarginM": 0.8,
"passSpeedMps": 4.0,
// No side free: stop short, and after blockWaitSec mark the obstacle for path searches for
// blockTtlSec and plan again. A hull within contactGapM of it for contactReverseSec backs off.
// Pressed again within contactRepeatSec near the same place: mark the obstacle, try the other
// side, and after unstickMaxAttempts such repeats give the order up.
"blockWaitSec": 2.0,
"blockTtlSec": 15.0,
"contactGapM": 0.8,
"contactReverseSec": 1.0,
"contactRepeatSec": 20.0,
// Less progress than stuckMinProgressM within stuckWindowSec while wanting to move is stuck.
"stuckWindowSec": 3.0,
"stuckMinProgressM": 0.8,
"unstickReverseM": 6.5,
"unstickReverseSec": 3.0,
"unstickRepeatSec": 8.0,
"unstickMaxAttempts": 3,
// Temporary path costs: jams found by unstick, fresh obstacles hit by the front rays, wrecks.
// A place given up on after unstickMaxAttempts is all but closed (giveUp*), so the next order
// routes elsewhere instead of returning to it.
"jamRadiusM": 10.0,
"jamCostMul": 12.0,
"jamTtlSec": 45.0,
"giveUpRadiusM": 15.0,
"giveUpCostMul": 40.0,
"rubbleRadiusM": 6.0,
"rubbleCostMul": 25.0,
"rubbleTtlSec": 90.0,
"wreckRadiusM": 6.0,
"wreckCostMul": 6.0,
"wreckTtlSec": 120.0
},
// Exposure-based visual perception (offline values; foliageTransparency matches stock infantry AI).
"perception": {
"foliageTransparency": 0.01,
@@ -121,24 +265,29 @@
"normalSpotSec": 0.60,
"farSpotSec": 1.45,
"decayPerSec": 1.5,
"frontConeHalfDeg": 60.0,
"peripheralCloseM": 100.0
// Every visual arc is relative to the barrel. The sight covers gunFovHalfDeg either side;
// near awareness covers nearArcDeg around the barrel and every lookAroundSec opens the rear
// for lookAroundHoldSec. Mid-distance awareness covers the barrel's front half.
// Near and mid spotting use nearSpotMul and midSpotMul respectively.
"gunFovHalfDeg": 30.0,
"nearAwareM": 150.0,
"nearArcDeg": 270.0,
"midAwareM": 600.0,
"nearSpotMul": 1.5,
"midSpotMul": 2.0,
"lookAroundSec": 8.0,
"lookAroundHoldSec": 1.0,
"discoverScore": 0.35
},
// Per-bot hull state machine timings and thresholds (offline values).
// Timings and thresholds of the hull actions (short halt, cover pull-back, reposition, repair).
"stateMachine": {
"preaimAngleDeg": 8.0,
// Time a ready gun can be held up by speed or aim before attempting a short halt.
"movingShotWaitSec": 1.0,
"shortHaltMaxSec": 3.0,
"shortHaltCooldownSec": 4.0,
"turnLaunchSpeedMps": 2.1,
"coverMinDistM": 6.0,
"coverMaxDistM": 24.0,
"coverRetreatBudgetSec": 6.0,
"reloadAdvanceAngleDeg": 18.0,
"hullAngleTriggerDeg": 20.0,
"hullAngleTargetDeg": 10.0,
"maxTotalHaltSec": 12.0,
"stalemateMissShots": 2,
"stalemateNoShotHalts": 2,
@@ -149,9 +298,7 @@
"tactics": {
"visionRangeM": 1250.0,
"visionFovDeg": 115.0,
"peripheralRangeM": 230.0,
"engineAudioRangeM": 65.0,
"engineAudioRangeM": 150.0,
"shotAudioRangeM": 380.0,
"radioShareRangeM": 450.0,
"memoryTtlSec": 12.0,
@@ -171,26 +318,129 @@
"maxBiasM": 2.2
},
// Threat table (decision layer design, section 4): how dangerous each discovered enemy is to the
// bot. Danger falls with distance as 1 / (1 + distance / rangeScaleM) and is multiplied by
// discoveredMul until the enemy is seen clearly, by notAimingMul unless its hull or gun points
// within aimConeDeg of the bot (or it hit the bot), by unseenMul when the bot is out of its
// sight, and by hitMul for hitMemorySec after it hit the bot. Penetration is not counted yet.
"threat": {
"rangeScaleM": 400.0,
"discoveredMul": 0.7,
"aimConeDeg": 25.0,
"notAimingMul": 0.5,
"unseenMul": 0.4,
"hitMemorySec": 6.0,
"hitMul": 2.0
},
// The turret gives visible contacts attention by danger, then checks memory and directional cues.
// While engaged, the competing threat needs switchMargin more danger to take over.
// The turret sweeps the route when it has no contact or cue.
"turret": {
"minDwellSec": 0.6,
"switchMargin": 0.25,
"scanArcDeg": 60.0,
"scanPeriodSec": 6.0,
"fixedMountYawSpanDeg": 60.0
},
// Hull channel: choose a behavior by score, holding each for its configured commitment time
// unless an emergency or a large score difference interrupts it. A cover withdrawal runs
// through its arrival or timeout. A short halt lasts through the weapon's shooting window.
// Tracked tanks and tank destroyers face the main threat at the post or during a halt.
// They can reverse along a short route segment to keep their front toward that threat.
"behavior": {
"scoreIntervalSec": 0.5,
"advanceHoldSec": 1.5,
"engageHoldSec": 1.5,
"haltHoldSec": 3.0,
"coverHoldSec": 2.0,
"repositionHoldSec": 2.0,
"postHoldSec": 1.5,
"disperseHoldSec": 1.5,
"targetValueWeight": 0.1,
"nearThreatHaltBonus": 0.28,
"switchMargin": 0.15,
"advanceScore": 0.5,
"engageScore": 0.55,
"urgencyWeight": 0.15,
"haltScore": 0.55,
"crossfirePenalty": 0.15,
"coverScore": 0.45,
"coverDangerWeight": 0.25,
"coverOffensivePenalty": 0.2,
"coverRetrySec": 4.0,
"repositionScore": 0.7,
"holdScore": 0.6,
"disperseScore": 0.62,
"urgentSpeedKeep": 0.5,
"hullAngleDeg": 20.0,
"faceToleranceDeg": 15.0,
"faceMinDanger": 0.15,
"reverseTravelAngleDeg": 110.0,
"reverseMaxTurnDistM": 45.0,
"reverseMinSpeedMps": 2.5,
"reverseHoldSec": 3.0
},
// Fire permission (decision layer design, section 6). A main-gun shot needs its estimated hit
// probability to reach the fire threshold. The hit probability compares the visible part of the
// target (its projected width, targetHalfHeightM high, shrunk when only part of it is visible)
// with the expected angular error: aimErrorDeg, plus moveErrDegPerMps per m/s of own speed and
// turnErrDegPerDegSec per deg/s of hull turn (times stabErrFactor with a stabilizer), plus the
// lead uncertainty on a crossing target, with the barrel's current offset as the mean error.
// The threshold starts at fireThreshold and drops by aimingThresholdBonus when the target aims
// at the bot, by up to closeThresholdBonus inside closeRangeM, by enemyReloadThresholdBonus for
// enemyReloadSec after the target fired, and by fleetingThresholdBonus if its estimated motion
// will take it out of sight. Longer reloads, scarce ammunition and falling back raise the threshold.
// The pre-fire budget limits ballistic checks per frame. Every firing request gets fresh checks.
"fireControl": {
"maxEngageRangeM": 1250.0,
"closeRangeM": 100.0,
"midRangeM": 300.0,
"longRangeM": 800.0,
"midSlowSpeedRatio": 0.45,
"midSlowMaxMps": 5.5,
// Moving-fire speed rises from the mid-range limit through the close-range boundary to point blank.
"closeRangeMaxSpeedKmh": 30.0,
"pointBlankMaxSpeedKmh": 35.0,
// At or below this speed the bot counts as standing (also the answer "stop" to a speed request).
"stopSpeedMaxMps": 0.45,
"longRangeWindowSec": 4.0,
"longRangeWindowSec": 1.0,
// Fixed (casemate) guns: how far off the gun may be before the hull is asked to turn.
"baseAlignDeg": 0.42,
"closeHitRadiusM": 0.85,
// Outside close range, the rate at which barrel alignment drifts relative to the aim direction.
"barrelSettleDegSec": 1.8,
"closeSettleHoldSec": 0.08,
"settleHoldSec": 0.20,
"unstabilizedStopSpeedMps": 0.45,
"stabilizedCreepSpeedMps": 5.5,
"closeSettleHoldSec": 0.06,
"settleHoldSec": 0.12,
"aimErrorDeg": 0.07,
"moveErrDegPerMps": 0.35,
"turnErrDegPerDegSec": 0.03,
"stabErrFactor": 0.2,
"targetHalfHeightM": 1.0,
"fireThreshold": 0.45,
"minFireThreshold": 0.1,
"aimingThresholdBonus": 0.1,
"closeThresholdBonus": 0.15,
"enemyReloadThresholdBonus": 0.08,
"enemyReloadSec": 3.0,
"fleetingThresholdBonus": 0.1,
"fleetingLateralMps": 3.0,
"fleetingLookAheadSec": 0.65,
"reloadThresholdPenalty": 0.08,
"longReloadSec": 15.0,
"lowAmmoRounds": 5,
"lowAmmoThresholdPenalty": 0.08,
"aimSkill": 0.5,
"autocannonMinShotsPerSec": 1.5,
"retreatThresholdPenalty": 0.2,
"minShotIntervalSec": 0.65,
// Automatic cannons are identified from stock belt and firing-rate data. They fire in bursts
// while within the aim slack. A longer wait between rounds counts as a reload.
"autocannonAimSlack": 3.0,
"burstSec": 1.2,
"burstPauseSec": 0.6,
"autocannonReloadDetectSec": 0.6,
// Secondary and coaxial guns have their own aim and ballistic checks. The armor toggle allows
// coaxial fire at vehicles outside the light-vehicle filter.
"auxWeapons": true,
"auxMaxRangeM": 300.0,
"auxFireAtArmor": false,
"friendlyCorridorM": 3.2,
"ballisticStepMaxM": 25.0,
"ballisticSweepRadiusM": 0.12,
@@ -199,6 +449,20 @@
"diagnostics": {
"telemetry": true,
"telemetryIntervalSec": 5.0
"telemetryIntervalSec": 5.0,
// Battle statistics for comparing builds (WTO_AI|BATTLE_STATS): cumulative per vehicle class,
// logged every statsLogIntervalSec and when the battle ends. Every statsSampleSec each bot
// checks the nearest enemy in line of sight within statsSampleRangeM: whether it knows it,
// how far the turret is off it, and whether its rear (statsRearArcDeg wide) faces it.
"battleStats": true,
"statsLogIntervalSec": 60.0,
"statsSampleSec": 1.0,
"statsSampleRangeM": 300.0,
"statsRearArcDeg": 120.0,
// Replay trace for the AI viewer (WTO_AI|TRACE_*, HIT, DEATH): every traceIntervalSec the
// capture zones, every ground unit and every bot's decision state. About 10 MB of log for
// 32 bots over 15 minutes at 0.5 s.
"trace": true,
"traceIntervalSec": 0.5
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"level": "avg_berlin",
"version": 1,
"bake": {
// The original arterial and ring roads use this LMp2 material.
"roadMaterials": ["concrete"],
"walkableRendinst": ["fountain_base_b_body"],
"downhillLinks": [
// Dry endpoints verified on the two meshes at the eastern canal bank.
{
"from": { "x": 2476.0, "y": 43.34, "z": 1124.0 },
"to": { "x": 2460.0, "y": 36.61, "z": 1124.0 },
"radiusM": 0.75,
"widthTiers": [0]
},
{
"from": { "x": 2476.0, "y": 43.12, "z": 1135.5 },
"to": { "x": 2458.0, "y": 36.59, "z": 1135.5 },
"radiusM": 0.75,
"widthTiers": [1]
}
]
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"level": "avg_poland",
"version": 1,
"bake": {
// The town streets and squares use this LMp2 material.
"roadMaterials": ["concrete"]
}
}
+52
View File
@@ -0,0 +1,52 @@
// Ammunition assigned to the selected primary gun by the stock ammunition stowage.
options indenting = 2
options no_global_heap = true
module wto_ai_ammo_common shared
require ecs
require math
require DagorMath
require AmmoStowage
require Unit
require Weapon
require %appGame.wtoai.wto_ai_combat_types_common
[never_inline]
def public wto_main_gun_ammo(gun : WTGun const?; fc : WtoFireState const&) : int
var stored = 0
for set in gun.properties.bulletSets
stored += max(0, set.bulletsCount)
let stockCount = fc.rackTurret == fc.turretNo ? fc.rackRounds : -1
if stockCount < 0 && stored == 0
return -1
return max(max(stockCount, stored), int(gun.currentLoadedAmmoCount))
def private wto_ammo_type_for_mount(unit : Unit const?; turret : int; first, end : int; weapons : IntList const&) : bool
for i in range(max(0, first), min(length(weapons), end))
let weapon = get_weapon(unit.weap.Weapons, weapons[i])
if weapon != null && int(weapon.turretNo) == turret
return true
return false
[never_inline]
def public wto_ammo_sample(unit : Unit const?; ammoState : uint; types : IPoint4List const&;
weapons : IntList const&; slots : UInt32List const&; counts : IPoint2List const&;
var fc : WtoFireState&)
if fc.turretNo < 0
return
fc.rackTurret = fc.turretNo
fc.rackRounds = -1
for i in range(WTO_MAX_SHELL_PROFILES)
fc.rackBySet[i] = 0
let distinctTypes = (ammoState & uint(AmmoState.ENABLE_PER_AMMO_TYPES)) != 0u
for ammoType in range(length(types))
let remap = types[ammoType]
if !wto_ammo_type_for_mount(unit, fc.turretNo, remap.y, remap.z, weapons)
continue
var rounds = 0
for i in range(min(length(slots), length(counts)))
if int(slots[i] & 0xffu) == ammoType
rounds += max(0, counts[i].x)
fc.rackRounds = max(0, fc.rackRounds) + rounds
if distinctTypes && remap.w >= 0 && remap.w < WTO_MAX_SHELL_PROFILES
fc.rackBySet[remap.w] += rounds
+82
View File
@@ -0,0 +1,82 @@
// Fresh static obstacles on top of the path: what the baked mesh cannot know. Two short physical
// rays from the front corners of the hull catch rubble and collapsed buildings and let the vehicle
// drive through what it can knock down (fences, light walls). Vehicles and wrecks are handled by
// wto_ai_traffic_common.
options indenting = 2
options no_global_heap = true
module wto_ai_avoid_common shared
require ecs
require math
require DagorMath
require Dacoll
require RendInst
require PhysMat
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_types_common
let private AVOID_STATIC_MASK = ETF_STRUCTURES | ETF_FRT
// Placed objects a tank cannot knock down. Matches the bake: riExtra objects up to
// navBake.crushableMaxRiExtraHp are crushable, destructible generated objects (fences, posts)
// fall over, indestructible ones block.
[never_inline]
def private wto_avoid_ri_blocks(desc : RendInstDesc const&) : bool
if desc.isValid && desc.isRiExtra && desc.riExtraHandle != RIEX_HANDLE_NULL
let handle = desc.riExtraHandle
let poolId = uint(handle_to_ri_type(handle))
if rendinst_isRIExtraGenPosInst(poolId)
return false
if riex_isImmortal(poolId) || riex_isInvincible(handle)
return true
return riex_getInitialHP(handle) > WTO_AI_NAVBAKE_CRUSH_MAX_HP
if !desc.isValid
return true
if rendinst_isRIGenPosInst(desc)
return false
return !rendinst_isRIGenDestr(desc)
// Clear distance along dir up to the first wall-like surface a tank cannot drive through.
[never_inline]
def private wto_avoid_drive_ray(startPos, dir : float3; maxRange : float) : float
var structDist = maxRange
var sTraveled = 0.0
for _hop in range(0, 4)
var hitD = maxRange - sTraveled
if hitD <= 0.0
break
var mat = PHYSMAT_INVALID
var norm = float3(0.0)
var desc = RendInstDesc()
let sOrigin = startPos + dir * sTraveled
if !traceray_normalized(sOrigin, dir, hitD, mat, norm, AVOID_STATIC_MASK, desc, PHYSMAT_INVALID)
break
if norm.y < 0.72
structDist = clamp(sTraveled + hitD, 0.0, maxRange)
break
sTraveled += max(0.0, hitD) + 0.5
var traveled = 0.0
for _hop in range(0, 4)
var hitDist = structDist - traveled
if hitDist <= 0.0
break
var riMat = PHYSMAT_INVALID
var riNorm = float3(0.0)
var riDesc = RendInstDesc()
let origin = startPos + dir * traveled
if !traceray_normalized(origin, dir, hitDist, riMat, riNorm, ETF_RI | ETF_RI_PHYS, riDesc, PHYSMAT_INVALID)
break
if riNorm.y < 0.72 && wto_avoid_ri_blocks(riDesc)
return clamp(traveled + hitDist, 0.0, structDist)
traveled += max(0.0, hitDist) + 0.35
return structDist
// Clear distance ahead along `dir` from both front corners of the hull (the shorter of the two).
[never_inline]
def public wto_avoid_bumper(myPos, dir : float3; spec : WtoVehicleSpec const&) : float
let left = float3(-dir.z, 0.0, dir.x)
let base = myPos + dir * max(0.5, spec.halfLen - 0.4) + float3(0.0, 1.0, 0.0)
let side = max(0.4, spec.halfWid - 0.25)
let clearL = wto_avoid_drive_ray(base + left * side, dir, WTO_AI_PF_BUMPER_RAY_M)
let clearR = wto_avoid_drive_ray(base - left * side, dir, WTO_AI_PF_BUMPER_RAY_M)
return min(clearL, clearR)
Loaded 100 of 263 files, more files were not shown because too many files have changed in this diff. Show more