91 Commits
Author SHA1 Message Date
N0VAN0M4LY dddcdde62c chore(launcher): bump version to 0.1.5 and add release notes
Launcher release / release (push) Waiting to run
2026-12-05 00:23:44 +08:00
N0VAN0M4LY fe29b5fe9c fix(battle): serialize LocalMP air AI unsortedPlanes updates
Add the local_mp_air_ai_sync native module to serialize calls to
TeamAiManager::addToUnsortedPlanes with an exclusive SRWLOCK on LocalMP
hosts.

Root cause (verified on 2.61.0.60, 2.61.0.58, and 2.61.0.37):
Aircraft physics and AI updates run concurrently across worker threads
via threadpool::parallel_for. When bot aircraft finish their behavior
tree (such as right after an aircraft crashes), AirAi::update tail-calls
TeamAiManager::addToUnsortedPlanes, which locks the global unit table
for lookup but mutates the team's shared unsortedPlanes
dag::Vector<uint32_t> (including reserve/HeapReAlloc) without a lock.
Under 32-bot LocalMP air battles, concurrent reallocations on this
vector corrupt the Windows heap (0xC0000374).

Also guard resolve_offender_killer in local_mp_kills.c with an
install-time check that LMP_OFFENDER_STRIDE <= LMP_OFFENDER_BUF_SIZE so
future struct growth skips cleanly instead of overflowing the stack
buffer.

Checks:
- MSVC /W4 build of wto_ws.dll (0 warnings in repository C files)
- Root and @wto/launcher npm run typecheck
- 15/15 native module resolution on 2.61.0.37 (0x807be0), 2.61.0.58
  (0x80a2b0), and 2.61.0.60 (0x80a150), checkPatchSet, wtotools
  check-patches on 2.61.0.60 (14/14), and temporary copy build
  verification (build-game-copy.ts)
- Pending live multi-match air/nuclear-escalation acceptance in an
  isolated copy.
2026-12-05 00:03:27 +08:00
N0VAN0M4LY 647eff35fe fix(battle): unblock LocalMP backup respawns and normalize unit names
Store the selected LocalMP backup token in a separate wtoLastBackup handler field instead of mutating requestData.wtoBackup. Mutating requestData caused respawn.nut checkReady() u.isEqual(lastRequestData, getSelectedRequestData()) to always evaluate false for backup spawns, preventing doRespawnPlayer() from ever running.

Also fix downstream ground and naval backup accounting where native UnitInfo::name carries folder prefixes (e.g. tankModels/cn_type_59) that mismatched bare unit IDs in session.spareSlots, by stripping path prefixes in local_mp_awards.c, record-local-battle-awards, battle-spares.ts, and battle-queue-requests.ts. Update hook_is_slot_ready_at_host to check USED_SPARES_MASK rather than BROKEN_SLOTS_MASK so unrepaired slots remain eligible for a backup spawn.

Verified root and launcher typecheck, 2.61.0.37 and 2.61.0.58 check-gui (50 patches / 37 .nut), check-patches (14/14), checkPatchSet, battle-spares runnable check, and MSVC temp build of wto_ws.dll (0 warnings in project C sources). Pending regular-terminal build of build/native/wto_ws.dll and in-game acceptance.
2026-12-04 23:56:13 +08:00
N0VAN0M4LY c3cf4e3707 feat(launcher): auto-detect decal cache from selected or recorded game folder
Extend resolvePlayerDecalCacheFolder to resolve <game>/cache/content when the player picks a game root folder directly. Add read-only decals:detectSource IPC so the install wizard auto-fills a detected decal cache from the chosen source (with one-click reset to placeholders) and the client details view offers one-click import from the recorded online sourcePath.
2026-12-04 21:09:57 +08:00
N0VAN0M4LY 49264b0326 feat(launcher): add client origin marker and stock restore removal flow
Write a self-describing wtoffline/client.json origin marker (copy, hardlink, or in-place) on install, space-saving compaction, and hardlink-detaching updates, and read it with lightweight hardlink nlink sampling when inspecting existing folders. Allow deleting existing folders only when backed by a valid copy/hardlink marker outside Steam and disjoint from all registered source paths, and add an atomic restore-stock-and-remove option that restores the four stock core files and removes only wto_ws.{dll,cfg,log} and wtoffline/.
2026-12-04 20:38:08 +08:00
N0VAN0M4LY 29736870ac fix(launcher): split copied and hardlinked bytes in space-saving install progress
Report actual disk-copied bytes separately from NTFS hardlinked asset bytes during space-saving installation, display both counts clearly in the installer progress view, and note that Windows Explorer folder properties double-count hardlinked space.
2026-12-04 19:55:05 +08:00
N0VAN0M4LY 9e6e13895e fix(launcher): separate client removal from deleting disk files
Split deleteFiles from deleteData in copy maintenance requests with safe false defaults. Block disk deletion for non-copy (in-place/existing) and Steam-library clients on both main and renderer sides, and allow pure list removal to bypass stockBackup/root checks so missing or damaged client entries can always be removed.
2026-12-04 19:55:05 +08:00
N0VAN0M4LY 12a573a333 feat(store): default free offline payment label to Direct Claim and make it tunable
Add tuning/store.jsonc freePaymentLabel (default Direct Claim in Chinese and English) and apply it consistently across the local web store, local marketplace, and the in-game payment dialog via cln_get_entitlements_price_ex top-level metadata.
2026-12-04 19:55:04 +08:00
N0VAN0M4LY 429c5eec12 fix(clans): fix squadron timestamps, 20k RP cap, and configurable initial RP
Fix two 1970 squadron timestamps by sending nextRewardDayId as a 64-bit Unix timestamp in seconds and emitting dynamic bi-monthly season fields (clanDuelNextReward, clanSeasonStart, clanSeasonOrdinal, clanSeasonInYear) in clientProfile. Backfill preset normal squadrons to 58-60 deterministic NPC members so the client activity reward cap reaches 20,000, default startingPeriods and startingActivity to 0 in tuning/clans.jsonc, remove the hardcoded 20,000 empty-history fallback, and wire battle RP into squadron activity accumulation and period settlement.
2026-12-04 19:55:04 +08:00
N0VAN0M4LY b3211b89cd feat(launcher): remember last selected directory in file and folder pickers
Persist per-category dialog directories under userData/dialog-paths.json and resolve existing parent fallbacks for folder pickers, save archive import/export, online backup selection, and mod preset/folder dialogs.
2026-12-04 19:55:04 +08:00
N0VAN0M4LY 8f1d175d55 fix(patcher): filter uncached decal and skin entries with placeholder fallback
Scan locally cached .ddsx files under cache/content (<first2>/<rest>.ddsx) when building char.vromfs.bin from player decal snapshots or regional.vromfs.bin. Repair single-LOD cache hits by falling back missing lodN/hdrN pairs to available LODs, fall back uncached stock decals to built-in placeholders, and drop uncached extra decals and incomplete downloadable skins.
2026-12-04 19:55:03 +08:00
N0VAN0M4LY 48f01b533e fix(patcher): strip cross-promo locks so promo gift vehicles can be ordered
Strip isCrossPromo and crossPromoBanner from config/shop.blk entries alongside tech-tree hiding flags so cross-promotion gift vehicles (bf-109c_1_promo, us_m4_sherman_promo, jp_destroyer_hatsuzuki) can be ordered directly through their generated local store packs while keeping showOnlyWhenBought intact.
2026-12-04 19:55:03 +08:00
N0VAN0M4LYandduduyagame f2e73c1cfe fix(profile): persist vehicle camouflage, loadout, and trim preferences
Accept the full client-writable hangar/<vehicle> field set emitted by AircraftInfo::serialize (mode 0x20/0x80) in cln_update for owned vehicles: lastSkin, lastWeapon, lastBullets0..5 (strings), and aileronTrim/elevatorTrim/rudderTrim (finite reals). Ownership and server-authoritative hangar fields remain untouched, matching the stock chard guard (2.61.0.37 0x938081) and serializer (2.61.0.37 0x940510, 2.61.0.58 0x942f80).

Extends the camouflage persistence fix from PR #17 to cover weapon presets, ammo belts, and flight trims reported on the same cln_update path. Verified root and launcher typecheck and SaveStore + clientProfile round-trip persistence. In-game acceptance is pending.

Co-authored-by: duduyagame <[email protected]>
2026-12-04 17:47:09 +08:00
N0VAN0M4LY bc35cc89ab fix(ground-ai): only run custom AI in multiplayer battles 2026-12-04 15:20:14 +08:00
N0VAN0M4LY 8c7d4a44a4 docs(release): complete v0.1.4 notes
Document the merged ground AI tuning and moving-fire changes, battle reward and backup fixes, and incomplete UHQ pack handling in both languages.
2026-12-04 09:56:59 +08:00
N0VAN0M4LY 688406bb76 fix(ground-ai): improve firing on the move
Share a distance-based speed cap between tactics and the fire gate.
Brake toward it and try a short halt when speed or aim keeps blocking
a ready shot.

Measure tracking drift relative to the aim direction and use the
close-range alignment window for quick shots. Expose the controls in
the launcher and record measured and permitted speeds in diagnostics.

Verified both TypeScript typechecks, 2.61.0.58 and 2.61.0.60 patch
checks and builds, and daScript loading in the guarded 2.61.0.58 client.
2026-12-04 07:35:31 +08:00
N0VAN0M4LY 0167c3ea7d chore(ground-ai): adopt adjusted bot defaults
Set the shipped defaults to the saved launcher values for lineup
weights, perception, capture assignments, ridge firing and hull
angles. Enable the saved diagnostics setting by default.
2026-12-04 07:35:31 +08:00
N0VAN0M4LYandduduyagame 3282320fb7 fix(battle): show and debit confirmed backup vehicles
Use the signed i64 profile encoding identified in PR #13. Make attached backups selectable in LocalMP after the daily quota, and debit backups only after the engine confirms the selected slot entered play.

Record the stock daily allowance once per room and slot. Settle owned backups using the confirmed spawn facts and keep repeat settlement from charging the same battle again.

Verified server and launcher types, MSVC compilation, three client builds for patch and Quirrel checks, and a temporary 2.61.0.58 build. In-game acceptance is pending.

Co-authored-by: duduyagame <[email protected]>
2026-12-04 06:24:34 +08:00
N0VAN0M4LYandduduyagame 6d0abf9caf fix(battle): award Air Arcade mini-base score
Use the native health update identified in PR #10 to report enemy mini-base damage and destruction. Preserve fractional personal score across hits and use the selected mode to gate both the HUD reward and settlement.

Verified server and launcher types, MSVC compilation, Quirrel bytecode, and patch resolution on 2.61.0.37, 2.61.0.58, and 2.61.0.60. In-game acceptance is pending.

Co-authored-by: duduyagame <[email protected]>
2026-12-04 06:13:21 +08:00
N0VAN0M4LY 194417a388 fix(battle): ignore non-player kills for firstKill and clamp assist loop
Ignore HUD kill feed entries with killer == -1 (mission air defense SAM/AAA and NPC units, common in Nuclear Escalation) when awarding firstKill, matching avengeAwards.

Also re-read the offenders vector count after orig_iground_award_assists in local_mp_events.c so the post-call scan never reads past a shrunk array.

Verified with root typecheck, MSVC x64 wto_ws.dll rebuild (0 warnings in project C code), and a runnable streak check.
2026-12-04 03:43:05 +08:00
N0VAN0M4LY 480496ca93 fix(launcher): skip and guard incomplete optional UHQ texture packs
Detect optional UHQ texture packs whose content/pkg_uhq_*.rq2 lacks a matching .ver file (PACKAGE_STATUS_REQUESTED) or whose grp_hdr.vromfs.bin has no .dxp.bin files.

planCopy now skips incomplete UHQ packs during copy installs and incremental updates (cleaning previously copied incomplete files on update), and planLaunch refuses to launch clients containing incomplete UHQ headers with a localized error instead of letting aces.exe crash with fatal error 81110007.

Verified with root and launcher typecheck, electron-vite build, en/zh-CN locale key parity (905/905), and a temp-folder runnable check.
2026-12-04 03:42:49 +08:00
N0VAN0M4LY 428b2d3601 chore(launcher): bump version to 0.1.4 and add release notes 2026-12-04 03:23:43 +08:00
N0VAN0M4LY 2d3287937f feat(launcher): add Bot parameters tuning page for ground AI and lineup weights
Extend readLauncherTuning/writeLauncherTuning and launcher IPC schemas to read, validate, and atomically persist battle.botPoolLimitPerType and nested ground-ai.jsonc overrides (including mode, vehicle class lineupWeights, spawn loadout, and all advanced ground AI sections). Add a dedicated Bot parameters section under Tuning with collapsible groups, bilingual labels, cross-field validation, and per-section reset. Verified with root/launcher typecheck, electron-vite build, 904-key locale parity check, and temp-dir read/write/reset round-trip.
2026-12-04 03:22:50 +08:00
N0VAN0M4LY 37cbcd806f docs(mods): align handbook chapters with .patch.blk and UI image format notes 2026-12-04 02:52:47 +08:00
N0VAN0M4LY 0af4183cb1 merge(ground-ai): merge feat/tank-ai phase 1 into main 2026-12-04 02:50:48 +08:00
N0VAN0M4LY 65363ce9de feat(mods): support Dagor-style BLK patches and include compilation
Add native-style *.blk.patch.blk and client/config-blk.patch.blk incremental patching alongside compile-time include/includeOnce and Dagor @-directive expansion (@override, @override-last, @replace, @delete, @delete-last, @delete-all, @clone, @clone-last, @inherit, @after, @before, indexed paths, unquoted @ syntax, triple-quoted strings, packed hex colors, and CDK #/develop/gameBase/ paths) while preserving full *.blk.patch.jsonc backwards compatibility.
2026-12-04 02:36:16 +08:00
N0VAN0M4LY 69d95df88e fix(hud): correct LocalMP damage feedback
Use the stock effective-hit flag to award normal hits and show ineffective hits without rewards. Route enemy parts feedback by the actual attacker or recipient and the active spectator state.

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

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

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

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

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

Verified launcher and workspace type checks, a launcher build, and an
incremental update of a registered client using local game snapshots.
2026-12-04 00:11:55 +08:00
N0VAN0M4LY ac35c25851 feat(ground-ai): add ready-rack dual-ammo bot spawn loadouts and shell switching
Select realistic ready-rack dual-shell loadouts for AI tanks on the local
server, inject them natively on bot spawn, and switch between anti-armor
and soft-target shells in battle:

- Add the loadout section to tuning/ground-ai.jsonc (lowReadyRackThreshold,
  topUpAmmoCount, primaryAmmoPct, secondaryMinRounds,
  penetrationCompareDistM), validated in ground-ai-tuning.ts.
- Add the tank-bot-ammo v2 dataset (apps/server/src/game-data/datasets/
  tank-bot-ammo.ts) reading primary cannon weapon name, capacity,
  firstStage/autoLoad shell ready-rack counts (excluding separate charges),
  and selectable shell modifications (using Lanz-Odermatt kinetic fields,
  cumulativeDamage, armorpower, and transitive reqModification chains).
- Add selectBotTankLoadouts (apps/server/src/battle/bot-tank-loadouts.ts):
  carry ready-rack count when >= 15 (top up to 22 when smaller or absent,
  clamped to gun capacity), skip SPAA/belt autocannons, pick highest-tier
  APFSDS/anti-armor primary (~80%) plus HE/HESH/HEAT secondary (~20%, min
  3 rounds) when available, and attach required addModification entries and
  per-tank wtoAmmo_<unit> strings to customBots when mode != stock.
- Hook Unit::changeAircraft (already located dynamically on .37 and .58) in
  native/wto-net/src/local_mp_loadout.c to assign the 24-byte
  ChangeUnitReflection.bullets entries via bullet_vec_assign for LocalMP
  bot spawns (async == 0, non-local bot MPlayer), leaving player spawns
  untouched.
- Track soft-target vs anti-armor shell classes in wto_ai_specs_common.das
  and write gun.nextBulletType in wto_ai_fire_common.das to queue HE/HESH
  against light/narrow targets and APFSDS/AP against MBTs/heavy armor.

Verified MSVC build of wto_ws.dll (0 warnings in project C sources), root
and launcher type checks, 14/14 check-patches on 2.61.0.58, 12/12 LocalMP
module installation, clean daScript load (wto_ai_runtime.das loaded in
211 ms, 0 compile errors), and real 2.61.0.58 loadout selection on
cn_ztz_96a (18 APFSDS + 4 HE), germ_leopard_2a4 (12 DM23 + 3 HEATFS),
ussr_t_80bvm (22 3BM60 + 6 HE), us_m1a2_abrams (14 M829A2 + 4 HEAT-MP),
ussr_t_34_1941 (18 APHEBC + 4 HE), and ussr_zsu_23_4 (stock belt kept).
Live battle acceptance begins in Step 9.
2026-12-03 19:25:04 +08:00
N0VAN0M4LY d5008baeff feat(ground-ai): add navmesh flank lanes, rally staging, recall, and air-aware SPAA
Complete the team commander layer with validated flank routes, coordinated
rally launches, dynamic cap recall, and air-threat-responsive SPAA:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-authored-by: duduyagame <[email protected]>
2026-12-03 05:22:40 +08:00
N0VAN0M4LY 594ff5ab54 feat(launcher): add project homepage link to About page
Add a Project homepage card and button pointing to https://wto-project.net on the launcher About page with matching zh-CN and en locale entries. Root typecheck, launcher typecheck, electron-vite build, and locale key parity checks passed.
2026-12-03 04:34:22 +08:00
N0VAN0M4LY 41088d5377 docs(mods): use neutral, self-contained phrasing in mod developer documentation 2026-12-03 03:45:13 +08:00
N0VAN0M4LY d94c8fe687 feat(mods): merge additive mod system, official map selector, and mod-dev-docs
# Conflicts:
#	apps/launcher/src/main/workers/build-worker.ts
#	apps/launcher/src/renderer/src/i18n/locales/en.json
#	apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
2026-12-03 03:43:56 +08:00
N0VAN0M4LY de967dd993 feat(repo): add R2 release staging, download page, and S3 publish script
Add scripts/publish-r2-releases.ts with a zero-dependency SigV4 R2 client and bilingual static index.html generator. Staged launcher releases and adaptation packs are verified against the committed Ed25519 public key and SHA-256 digests before publishing, assets are uploaded ahead of the releases feed with SHA-256 skip checks, and .env*.local is gitignored for local R2 credentials. Verified with root typecheck, local staging, and live R2 upload.
2026-12-03 03:03:14 +08:00
N0VAN0M4LY dc5e637e20 fix(mods): track additive pack overlay folders inside mod templates 2026-12-03 03:02:19 +08:00
N0VAN0M4LY 240ee81712 feat(launcher): use dl.wto-project.net as primary release source with GitHub fallback
Replace the single GitHub repository field in release-channels.jsonc with primary_source (https://dl.wto-project.net) and ordered fallback_sources (GitHub), and update withReleaseSources to walk the deduplicated primary, player mirror, and fallback list while keeping preferred-source downloads and Ed25519 signature verification intact. Verified with root and launcher typecheck and launcher production build.
2026-12-03 03:02:14 +08:00
N0VAN0M4LY 6e65cec4c0 feat(mods): add official map selector mod template and move templates into mod-dev-docs 2026-12-03 03:01:18 +08:00
N0VAN0M4LY aa952e7cca docs(mods): add standalone mod-dev-docs handbook and launcher quick-open button 2026-12-03 02:51:54 +08:00
N0VAN0M4LY 5983e3f3e2 feat(mods): add battle.onFilterMissions hook and per-template bundled seeding 2026-12-03 02:40:38 +08:00
N0VAN0M4LY 662e837ab2 fix(patcher): support regional.vromfs.bin decal and skin indexes on cache import
Modern online War Thunder clients (verified on 2.61.0.58) ship their decal and
skin indexes (dldata/downloadable_decals.blk and dldata/downloadable_skins.blk)
inside cache/binary.<ver>/regional.vromfs.bin rather than downloading
downloadable_decals.<hash>.blk into cache/content/. Requiring
downloadable_decals.<hash>.blk rejected every live 2.61 cache/content folder.

- Accept modern online caches containing cached .ddsx textures alongside a
  sibling binary.<ver>/regional.vromfs.bin (as well as selecting the parent
  cache folder or legacy downloadable_decals.<hash>.blk caches).
- Extract both dldata/downloadable_decals.blk and dldata/downloadable_skins.blk
  into a self-contained .wto-index snapshot on launcher import (excluded from
  the copied game cache/content folder) and embed them into char.vromfs.bin
  during copy build so webdlcontent::init mounts cache/content and resolves
  cached real decals and downloadable skins natively without client patches.
- Log the specific rejection reason in launcher decal import and clarify the
  en/zh-CN prompts.

Verified with root and launcher npm run typecheck, launcher electron-vite
build, and an end-to-end temporary import + char.vromfs.bin build against a
read-only 2.61.0.58 online cache (4,080 decals / 1,930 skins embedded).
In-game acceptance pending on an isolated 2.61.0.58 client copy.
2026-12-03 01:58:28 +08:00
N0VAN0M4LY 8636d0b71d fix(mods): serialize initial example seeding and refresh on window focus 2026-12-03 01:55:20 +08:00
N0VAN0M4LY 97707f533d feat(launcher): bundle example mod templates and seed fresh mods folder once 2026-12-03 01:51:43 +08:00
N0VAN0M4LY ada635ecc7 refactor(launcher): move experimental mod notice to hover tooltip chip 2026-12-03 01:48:47 +08:00
N0VAN0M4LY deffcd6dde feat(saves): merge bulk research and purchase into one launcher action
In the launcher's Saves -> Vehicles & Research page, "Research all" only
filled vehicle RP without purchasing them, requiring players to buy each
vehicle manually in-game while a separate "Grant regular vehicles" button
already added them to the hangar.

Merge the two actions into a single "Research and buy all" (`purchase`) action
alongside "Unlock modifications" (`equipment`), and switch bulk modification
unlocking in save-research.ts to ProfileEquipmentIndex so large saves stay
O(N) and write cleanly across chunked modification blocks.

Verified with root and launcher npm run typecheck, launcher electron-vite
build, and en/zh-CN locale key parity (631 keys).
2026-12-03 01:19:20 +08:00
N0VAN0M4LY 4e72bf3746 fix(profile): split modifications across sibling blocks at 65,535 entries
Dagor's binary DataBlock stores child block counts in a uint16 (65,535 max),
and the full 2.61.0.58 vehicle catalogue contains 76,041 modifications. Writing
all owned modifications into a single `modifications` block caused encodeBlk to
throw BlkFormatError once a save crossed 65,535 entries, preventing saving and
login.

Match aces.exe's native multi-block layout (2.61.0.37 0x938fae..0x9397e6,
2.61.0.58 0x93ba70 / 0x93bb53), which splits modifications across up to 3
sibling top-level `modifications` blocks of at most 65,535 entries each:

- Add allModificationBlocks, appendModificationEntry, and
  normalizeModificationBlocks in profile-modifications.ts and span all chunks
  in modificationRecord, ownsModification, and writeModificationRecord.
- Index and append across sibling chunks in ProfileEquipmentIndex and
  grantSupportPlaneModifications.
- Filter all sibling chunks in prepareTransferredProfile and normalize before
  encoding in SaveStore.saveProfile.

Verified with root npm run typecheck and a 2.61.0.58 temporary save check
encoding, decoding, and filtering >65,535 modifications across sibling chunks.
In-game acceptance pending on an isolated 2.61.0.58 client copy.
2026-12-03 01:18:14 +08:00
N0VAN0M4LY 3aac60c8a3 docs(mods): add bilingual mod authoring guide and runnable example mod templates 2026-12-03 00:41:47 +08:00
N0VAN0M4LY dbc21182a2 feat(launcher): add Mods page, per-client presets, custom repo folder, and launch integration 2026-12-03 00:34:07 +08:00
N0VAN0M4LY 5c09c4e47a fix(battle): enable limited fuel in LocalMP versus battles
MissionSettings initializes isLimitedFuel to false by default (2.61.0.37
0x12620af), leaving LocalMP versus battles with infinite fuel, no fuel
burn weight reduction, and no HUD fuel timer. Set isLimitedFuel=true in
battleMissionSettings across all versus modes to match live behavior.

Verified with root npm run typecheck. In-game acceptance pending on an
isolated 2.61.0.58 client copy.
2026-12-03 00:31:35 +08:00
N0VAN0M4LY dce9b59765 fix(battle): match native modification inversion and bullet belt filtering on spawn
Align battle/pass-spawn-modifications-blk with the native UnitModifications
construction rules verified on 2.61.0.37 and 2.61.0.58:

- Filter effects.bulletMod belts against the spawn request's selected
  bullets0..N so unlocked belts (whose last wpcost.blk entry is usually
  *_stealth) do not overwrite single-belt aircraft guns with non-tracer
  stealth belts.
- Resolve invertEnableLogic (unit BLK overriding config/modifications.blk)
  so spaded vehicles move inverted performance modifications to disabledMods
  instead of applying stock penalties (and arcade double-inversion) in
  LocalMP battles.
- Include unequipped modifications in disabledMods only when they define
  disableModEffects (e.g. stock fire extinguisher / repair kit), keeping
  unequipped normal modifications out of disabledMods.

Verified with full Quirrel bytecode check-gui on 2.61.0.37 and 2.61.0.58
(49 GUI patches across 37 .nut files). In-game acceptance pending on an
isolated 2.61.0.58 client copy.
2026-12-03 00:29:51 +08:00
N0VAN0M4LYandAlem Bek e8122d7c6b fix(battle): restore LocalMP Ground Arcade air events
Copy allowedKillStreaks and set useKillStreaks for Ground Arcade in battle-mission-settings.ts, and add a dedicated dynamic native module (local_mp_air_events) that preserves MissionSettings.useKillStreaks across prepare_local_mission, credits local player AI kills toward native killstreak counters, delivers UnitRespawn (0xf030) to the LocalMP host via shared unit_on_event, and recovers invalid surface poses from gameplay.blk spawnPos parameters for the match rank.

Based on PR #3 by Rivfflot, who diagnosed the LocalMP Ground Arcade air-event gaps and verified the fix in-game; refactored here onto patches/native dynamic resolution for cross-version and MSVC build compatibility.

Checked: root and launcher typecheck, MSVC native/wto-net/build.ps1, native resolution across 2.61.0.37 and 2.61.0.58 (12/12 modules), 2.61.0.58 check-patches (14/14), and temporary 2.61.0.58 copy build all passed. Pending in-game acceptance on the refactored module.

Co-authored-by: Alem Bek <[email protected]>
2026-12-03 00:14:32 +08:00
N0VAN0M4LY aa7a6e7d02 feat(server): add experimental JS/TS mod runtime, hooks, tuning list ops, and isolated mod storage 2026-12-03 00:00:36 +08:00
N0VAN0M4LY fd9d25d346 feat(patcher): support additive mod pack overlays, addon mounts, and protected exe patches 2026-12-02 23:48:34 +08:00
N0VAN0M4LY 8fbaeb4228 feat(mods): add core mod manifest, resolver, BLK/CSV patchers, and server API types 2026-12-02 23:42:26 +08:00
N0VAN0M4LY 4999c7f5a3 fix(native): assign local player squad ID for yellow squad target mark
Pressing ID_SQUAD_TARGET_DESIGNATION ("Set target for squad") checks
MPlayer+0xab0 (squadId) and returns early when it is zero (2.61.0.58
0x1600a4f). The LocalMP host already retains the 0xf10f relay and
0xf142 HUD indicator path (0xcb045c -> 0xcb1646 -> 0xcafffb ->
0x19a65e0), which also requires a non-zero squadId from matchingInfo+0x0.

Set matchingInfo+0x0 (squadId) to 1 for the local player when zero in
hook_mplayer_init_from_matching so MPlayer::initFromMatching (0x59e660
on 2.61.0.37, 0x59f370 on 2.61.0.58) copies it into MPlayer+0xab0 and
restores the yellow squad target marker without extra hooks or exe patches.

Verified with native wto_ws.dll build; pending in-game verification.
2026-12-02 23:16:49 +08:00
N0VAN0M4LY d0e4797fe7 feat(battle): add Nuclear Escalation tactical and strategic nuclear carriers
Connect stage-unlocked nuclear carriers to Air Realistic sub-mode 103
(Nuclear Escalation) and expose a player toggle for stage-3 megaton
strategic bombers:

- Dataset & profile grants: extract tactical killstreak nuclear carriers
  (5 kt / 30 kt Nuclear Escalation presets) and megaton strategic bombers
  (nt_b_52h / nt_tu_95m) from wpcost.blk in battle-spawn-rules (v4), and
  grant their required weapon/modification records in
  support-plane-modifications.ts.
- Server slot selection & tuning: add nuclearEscalationStrategicBombers
  (default true) in tuning/battle.jsonc, battle-tuning.ts, and
  launcher-tuning.ts; add one nation-matched tactical carrier per session
  rank bracket (with allowedWeapons limited to its Nuclear Escalation
  presets) and, when enabled, one stage-3 strategic bomber to
  extraBattleSlots; include modeTag in battle launch notifications.
- GUI patch & launcher UI: add battle/filter-extra-slot-weapons on
  scripts/weaponry/weaponryinfo.nut to filter extra-slot presets by
  allowedWeapons (hiding Ground RB zero-yield presets at stage 0) and to
  fall back to LocalMP launch metadata for GameModeRestrictions; expose
  the strategic bomber toggle in the launcher Battle tuning section.

Verified with root and launcher typechecks, launcher build, full
check-gui on 2.61.0.37 and 2.61.0.58 (49 patches across 37 .nut files),
and slot selection check across all 10 nations on 2.61.0.58 stock data;
pending in-game verification.
2026-12-02 23:03:15 +08:00
N0VAN0M4LY f1ec034994 feat(battle): wire Nuclear Escalation launch and airfield cooldowns
Connect Air Realistic sub-mode 103 (Nuclear Escalation) mission launch
settings and LocalMP respawn/airfield-cooldown handling:

- Server: support mode-level maxRespawns (UNLIMITED_RESPAWNS = -2) and
  per-mode missionRuleKeys so Nuclear Escalation forwards customHUD,
  stage thresholds, useSpawnDelay, afterRespawnDelaySec, and battle
  display flags from the stock missions; reject queues when no candidate
  mode is eligible for the lineup; disable spares and emit
  wtoUnlimitedRespawns for unlimited-respawn modes.
- Native: keep slots usable when wtoUnlimitedRespawns is set and emit
  wtoLocalMpAirfieldSpawn with the unit name and spawn base ID when the
  local player actually enters pilot control.
- GUI patches: track confirmed LocalMP airfield departures in
  scripts/respawn/respawnbases.nut and feed the computed per-base delays
  into scripts/respawn/respawn.nut slot countdowns and spawn checks.

Stage-unlocked dedicated event aircraft allocation by faction and room
BR is not yet wired and remains pending research. Verified with root and
launcher typechecks, check-patches and check-gui on 2.61.0.37 and
2.61.0.58, and native wto_ws.dll build; pending in-game verification.
2026-12-02 21:35:17 +08:00
N0VAN0M4LY 646be7afb9 fix(battle): load player crew skills on LocalMP host
Unit::loadCrew previously skipped reading the player's equipped crew from
the profile whenever Multiplayer+0x60 (host flag) was non-zero, leaving
human players with default skills and no Expert/Ace bonuses. Calling
UnitCrewSkills::initFromSave after Unit::changeAircraft in the native
loadout hook ran too late to affect live vehicle crew state.

Add exe patch battle/load-local-host-player-crew to check both the host
and LocalMP flags (+0x60 and +0x61) in Unit::loadCrew so only non-LocalMP
hosts skip directly to the default crew while preserving the owner check.
Remove the late initFromSave workaround from local_mp_loadout.c (keeping
its native patch sites for compatibility with 0.1.2 hook DLLs) and add
the E-Crew skills in battle feature labels to the launcher locales.

Verified with check-patches on 2.61.0.37 (0x10025dd) and 2.61.0.58
(0x100700d), native wto_ws.dll build, launcher typecheck and build;
pending in-game verification.
2026-12-02 21:33:46 +08:00
N0VAN0M4LY 7bd17c4f74 fix(battle): enable in-flight reload in air arcade
Air arcade battles previously set isLimitedAmmo=true via VERSUS_SWITCHES.
Both the native in-flight rearm request and its host handler require
unlimited reserve ammunition, which prevented airborne reloading in Air AB.

Move isLimitedAmmo out of VERSUS_SWITCHES and set it to false only when
modeName is air_arcade, keeping limited ammunition for all other modes.

Verified with root npm run typecheck; pending in-game verification.
2026-12-02 21:32:42 +08:00
N0VAN0M4LY be772c0cea fix(launcher): keep copy maintenance progress across tab switches 2026-12-02 20:24:30 +08:00
N0VAN0M4LY fa7f68b942 feat(launcher): use two-column About layout and add Discord link 2026-12-02 20:06:51 +08:00
N0VAN0M4LY 899fb5d91b fix(server): persist selectable battle ratings
Validate the selected rank against owned modifications and return the saved profile.

Use the saved rank delta for mode eligibility and room matchmaking.

Verified with typecheck and a local 2.61.0.58 server run using temporary data. In-game acceptance is pending.
2026-12-02 19:55:41 +08:00
N0VAN0M4LY 3f0e08c5b7 docs(repo): add Discord community links to README 2026-12-02 19:19:41 +08:00
329 changed files with 30579 additions and 1139 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
## 简体中文
`v0.1.3` 是 WTOffline的一次大型功能更新,正式引入**第一版模组系统(开放社区模组制作)**、初步接通**原子雷霆**模式,并包含多项对局机制、存档容量、贴花导入与更新链路修复。
### 该下载哪一个文件?
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.3-win-x64.exe`** ,下载后安装即可。
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** ,解压到任意目录后运行其中的启动器即可。
### 重点新功能
- **第一版模组系统与开放模组制作(实验性)。**
- 启动器新增「模组」管理页:支持为每个客户端独立开关模组、调整加载顺序、保存/切换模组方案以及自定义模组目录,并可直接一键打开完整模组开发文档。
- 支持客户端数据包增量覆写(BLK / CSV / 附加包挂载,且核心隔离补丁受保护不可被误覆盖)、服务端 JS/TS 脚本钩子与独立模组数据存储,以及数值列表增量修改。
- 内置并首次自动生成 3 套官方示例模组模板(含可直接使用的「官方地图选择器」、服务端脚本示例与载具参数微调示例),配套完整中英文 `mod-dev-docs` 开发手册,欢迎玩家与创作者制作并分享自己的模组。
- **接通「原子雷霆」模式。**
- 完整接入空战历史子模式「原子雷霆」的专用 HUD、阶段推进门槛、不限出击次数与机场独立冷却机制,并按 10 国与房间权重自动分配战术核弹载机(5 kt / 30 kt)。
- 在启动器「数值 → 对局」新增「原子雷霆战略核轰炸机」开关(默认开启),可在阶段 3 追加战略核轰炸机(`B-52H` / `Tu-95M`)。
### 修复与改进
- **对局与战斗体验**:
- 恢复陆战街机空中支援事件(呼叫战斗机 / 攻击机 / 轰炸机);
- 修复本地主机下玩家乘员技能与专家 / 王牌资格在战局内未生效的问题;
- 恢复空战街机模式下的空中重新装填弹药;
- 修复部分载具出生时改装件效果反转,以及单弹链航空武器被未选中的隐身弹链覆盖导致无曳光弹的问题;
- 恢复对战模式飞机有限燃油消耗与油量倒计时,并修复局内小队黄色标记;
- 支持在机库切换并保存载具的可选分房权重(如部分直升机 / 挂载升档),开局按所选权重参与匹配;
- 修复空战街机等多槽模式下 AI 飞机重生次数受限,以及坦克 AI 重生次数配置未对全部模式生效的问题(感谢 `duduyagame`);
- 修复新手教程完成进度未保存的问题:通关后重启不再反复提示教程,并按原版规则发放首次通关的贴花、基础教程金鹰及各难度银狮奖励(感谢 `duduyagame`)。
- **启动器、存档与更新链路**:
- 修复新版在线客户端贴花与可下载涂装缓存导入失败的问题(兼容现行 `regional.vromfs.bin` + `.ddsx` 及旧版缓存格式);
- 修复全车库改装件总数超过 65,535 个时的存档溢出问题;
- 将启动器「存档 → 载具和研发」中的「全部研发」与「获得常规载具」合并为一步到位的「全部研发并购买」;
- 优化默认更新线路并保留 GitHub 自动回退,全流程继续保持 Ed25519 签名校验;
- 「关于」页改版为双栏布局,新增「项目主页」与「Discord」快捷入口,修复切换页面时维护进度丢失的问题。
### 社区交流与模组分享
欢迎加入 WTOffline 官方 Discord 服务器,一起交流玩法、反馈 Bug、分享你的调参或自制模组,并关注最新客户端适配进度:
- **Discord 社区**:https://discord.gg/P566xWNpEs
- **项目主页**:https://wto-project.net
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动尝试适配后续小版本更新。
---
## English
`v0.1.3` is a major feature release of WTOffline introducing the **first version of the experimental Mod System** (opening up community mod authoring), Add support for **Nuclear Escalation**, and a broad set of battle, save, decal import, and launcher fixes.
### Which file should I download?
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.3-win-x64.exe`** — the standard Windows installer with built-in automatic update checks.
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.3-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
### Highlights
- **Experimental Mod System v1 & Mod Authoring.**
- New **Mods** page in the launcher with per-client enablement, load-order management, presets, custom mod repository folder, and a quick-open button for the mod developer handbook.
- Supports additive client archive overlays (BLK / CSV / addon mounts while protecting essential isolation patches), server-side JS/TS lifecycle hooks with isolated mod storage, and tuning list operations.
- Ships with 3 bundled example mod templates (including a ready-to-use **Official Map Selector**, a server script example, and a vehicle tweak example) plus full bilingual documentation in `mod-dev-docs/`.
- **Nuclear Escalation mode.**
- Full support for Air Realistic sub-mode **Nuclear Escalation**, including custom HUD, stage thresholds, unlimited respawns, per-airfield cooldowns, and nation-matched tactical nuclear carriers (5 kt / 30 kt) scaled to room BR.
- Added a **Nuclear Escalation strategic bombers** toggle under **Tuning → Battle** (enabled by default) to unlock stage-3 strategic nuclear bombers (`B-52H` / `Tu-95M`).
### Fixes and improvements
- **Battles & gameplay**:
- Restored Ground Arcade air support events (fighters, attackers, bombers).
- Fixed player crew skills and Expert / Ace qualifications not applying on the local host.
- Restored in-flight ammunition reload in Air Arcade.
- Fixed inverted modification effects on spawn and single-belt aircraft tracers being overwritten by unselected stealth belts.
- Restored limited fuel consumption / HUD fuel timer in versus modes and yellow squad target markers.
- Persisted selectable battle ratings for units with BR-changing modifications and applied them during matchmaking.
- Fixed AI aircraft respawn limits in Air Arcade and other multi-slot modes, and applied configured ground AI respawn counts across all modes (thanks to `duduyagame`).
- Persisted stock training/tutorial completion progress so finished tutorials no longer re-prompt after restart, and granted one-time first-completion decals, basic tutorial Golden Eagles, and per-difficulty Silver Lions rewards (thanks to `duduyagame`).
- **Launcher, saves & updates**:
- Fixed online decal and downloadable skin cache import on modern 2.61 clients (supports both `regional.vromfs.bin` + `.ddsx` and legacy cache layouts).
- Fixed save overflow when total owned modifications exceed 65,535 by splitting across native sibling blocks.
- Merged "Research all" and "Grant regular vehicles" into a single **Research and buy all** action in the launcher.
- Improved default release update routing with automatic GitHub fallback and continued Ed25519 signature verification.
- Updated the About page to a two-column layout with **Project homepage** and **Discord** buttons, and preserved copy maintenance progress across tab switches.
### Community & Mod Sharing
Join the official WTOffline Discord server to chat, report issues, share tuning presets or custom mods, and follow client adaptation updates:
- **Discord**: https://discord.gg/P566xWNpEs
- **Homepage**: https://wto-project.net
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates.
+101
View File
@@ -0,0 +1,101 @@
## 简体中文
`v0.1.4` 带来**实验性新版陆战 AI(第一阶段)**、启动器全新**「Bot 参数」调参页(含陆战 AI 出车权重)**、**Dagor 风格 `.blk.patch.blk` 模组补丁引擎**,以及多项对局伤害反馈、改装件批量购买与启动器便携更新修复。
### 该下载哪一个文件?
- **绝大多数玩家**:下载 **`wtoffline-launcher-0.1.4-win-x64.exe`**,下载后直接安装即可(覆盖安装保留全部存档与配置)。
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.4-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。
### 重点新功能
- **实验性新版陆战 AI(第一阶段,默认启用)。**
- 引入全新的模块化陆战 AI 架构:包含整队指挥层与任务单(按坚守 / 征服 / 制霸模式分配进攻、侧翼、架枪与防空角色,支持分路包抄、集结出发、占点回防与防空阵位)、曝光积分视觉感知与唯一弹道开火许可门(含植被透光、硬遮挡弹道扫掠与友军走廊防误伤)、单车车体状态机(短停射击预算、掩体装填回缩、摆角、僵持换位与受损维修)、本车目击测速提前量与失联守出口,以及按待发架容量配置主/副双弹种出生装弹与局内自动切弹。
- 当前为第一阶段实验版本,默认以完整模式(`full`)运行并持续调优中;若遇到寻路或行为异常,可随时在启动器「数值 → Bot 参数」切回「原版 AI(`stock`)」。
- 移动射击的车速上限随距离缩短而提高。车辆会主动减速,持续无法开火时可短停争取一炮,瞄准也改为按跟踪目标的误差判断。同步更新了出车权重、感知、占点与车体动作的默认参数。
- **启动器新增「数值 → Bot 参数」页面。**
- 统一集中管理陆战 AI 模式切换、AI 坦克 / 飞机重生次数、每类载具候选池上限、**陆战 AI 出车权重**(中坦 / 主战、重坦、坦歼、轻坦、防空车、其他)与出生携弹策略。
- 同时以折叠分组开放全部陆战 AI 进阶参数(指挥配额、占点宏观、状态机、视觉感知、测速偏差、火控开火门、机动寻路、编队避让与地形约束),支持参数校验与一键恢复默认值。
- **模组系统新增 Dagor 风格 `.blk.patch.blk` 与 `include` 编译支持。**
- 支持原生风格的 `*.blk.patch.blk` 与 `client/config-blk.patch.blk` 增量补丁、编译期 `include` / `includeOnce` 展开,以及 Dagor `@` 指令(`@override`、`@replace`、`@delete`、`@clone`、`@inherit`、`@after`、`@before` 等),同时完全保留 `*.blk.patch.jsonc` 兼容。
- 同步重写并补齐中英双语开发者手册(`dev-docs/`)与模组制作手册(`mod-dev-docs/`)。
### 修复与改进
- **对局伤害反馈与改装件**:
- 修复空战右下角敌机部件受损播报串台(仅显示本机及观战目标,不再混入 AI 互打记录)以及空战持续命中时重复普通命中丢失的问题;
- 修正普通命中与跳弹等引擎判定无效命中的奖励分类,并修正右侧部件受损反馈的攻击者与收件人归属;
- 修复机库一键「购买所有已研发改装件」时因前置依赖状态与价格核算不一致报「角色服务器内部错误」的问题。
- **对局奖励与备用载具**
- 空战街机可因伤害或摧毁敌方小基地获得个人分,摧毁奖励也会列入战后明细。
- 修复重生界面中已购买的单车备用载具显示。每日免费出击、单车备用和通用备用按实际成功出击结算。
- 修复部分任务单位击杀被误计为首杀的问题,并加固助攻事件处理。
- **启动器维护、便携版更新与界面**:
- 客户端维护页新增「设置 / 更换在线版安装来源」,方便在线版移动目录后继续一键增量更新;
- 复制安装与「从在线版更新」自动跳过并保留玩家自定义内容目录(`UserSkins`、`UserSights`、`WarThunderCDK` 与启动器日志),避免更新覆盖自制涂装或瞄具;
- 复制安装与增量更新会跳过下载不完整的超清材质包(UHQ)。已有离线客户端遇到残缺材质包时,启动器会在启动前提示处理。
- 修复便携版原地更新在 Windows 下的文件复制、Electron `.asar` 检查冲突与进程分离重启问题,并防止客户端或数据目录嵌套于启动器安装目录内;
- 更新日志改为支持 Markdown 排版的弹窗展示。
### 社区交流与反馈
欢迎加入 WTOffline 官方 Discord 服务器,反馈新版陆战 AI 实机体验、分享你的 Bot 调参或自制模组,并关注最新客户端适配进度:
- **Discord 社区**:https://discord.gg/P566xWNpEs
- **项目主页**:https://wto-project.net
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。
---
## English
`v0.1.4` introduces the **experimental Ground AI Rebuild (Phase 1)**, a new **Bot parameters** page in the launcher (including **ground AI vehicle class weights**), **Dagor-style `.blk.patch.blk` mod patching**, and a set of battle damage feedback, bulk modification purchase, and portable updater fixes.
### Which file should I download?
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.4-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning).
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.4-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
### Highlights
- **Experimental Ground AI Rebuild (Phase 1, enabled by default).**
- Introduces a modular custom ground AI architecture: a team commander & task orders (mode-aware Assault / Flank / Overwatch / SPAA role quotas for Battle, Conquest, and Domination with flank lanes, rally staging, cap recall, and air-aware SPAA positioning), exposure-based visual perception and a single ballistic fire gate (foliage transparency, hard-cover ballistic sweeps, and friendly-fire corridor protection), a hull state machine (short-halt budget, cover reload retreat, angling, stalemate repositioning, and damage repair), sample-based velocity lead estimation with last-seen exit watch, and ready-rack dual-ammo bot spawn loadouts with automatic shell switching.
- Ships in `full` mode by default for testing and live tuning; if you run into pathing or behavior issues, you can switch back to **Stock AI (`stock`)** anytime under **Tuning → Bot parameters**.
- The speed limit for firing on the move rises as targets get closer. Bots slow down and can briefly stop when they cannot fire while moving. Aim stability now uses tracking error. Vehicle weights, perception, capture assignments, and hull behavior also have updated defaults.
- **New "Tuning → Bot parameters" page in the launcher.**
- Brings together ground AI mode selection, AI tank / aircraft respawn limits, per-type AI pool cap, **ground AI vehicle class weights** (Medium/MBT, Heavy, TD, Light, SPAA, Other), and spawn ammunition rules in one place.
- Exposes all advanced ground AI tuning sections in collapsible groups (commander, macro, state machine, perception, tactics, estimation, fire control, navigation, crowd, terrain, and runtime cadence/diagnostics) with validation and one-click section reset.
- **Dagor-style `.blk.patch.blk` & compile-time `include` support for mods.**
- Supports native-style `*.blk.patch.blk` and `client/config-blk.patch.blk` incremental patching, `include` / `includeOnce` expansion, and Dagor `@`-directives (`@override`, `@replace`, `@delete`, `@clone`, `@inherit`, `@after`, `@before`, etc.) while maintaining full backwards compatibility with `*.blk.patch.jsonc`.
- Rewrote and expanded both the bilingual Developer Handbook (`dev-docs/`) and Mod Developer Handbook (`mod-dev-docs/`).
### Fixes and improvements
- **Battle feedback & modifications**:
- Fixed Air battle bottom-right enemy part damage feed bleed-through from AI-vs-AI fights (now filtered to the local player or spectated unit) and stopped dropping repeated normal hits on aircraft.
- Corrected normal hit vs. ineffective hit (e.g., ricochet) award classification and right-side component damage feedback ownership.
- Fixed "Internal character server error" when clicking **Buy all researched modifications** by emitting native `RESEARCHED` status for prerequisite chains and aligning bulk pricing.
- **Battle rewards and backups**
- Damaging or destroying enemy mini-bases in Air Arcade now awards personal score. Base destruction rewards appear in the post-battle breakdown.
- Fixed how purchased vehicle backups appear in the respawn screen. Daily free spawns, vehicle backups, and universal backups are accounted for after a confirmed spawn.
- Fixed some mission-unit kills being counted as the first player kill and tightened assist event handling.
- **Launcher maintenance, portable updater & UI**:
- Added support for setting or changing the online client update source on the client maintenance page.
- Skipped and preserved player-created folders (`UserSkins`, `UserSights`, `WarThunderCDK`, and launcher logs) when copying or updating from the online client.
- Copy installs and incremental updates skip incomplete Ultra High Quality (UHQ) texture packs. The launcher flags incomplete packs in existing offline installations before starting the client.
- Fixed portable in-place updates on Windows (`original-fs`, removing unused `default_app.asar`, detached `Start-Process` relaunch) and guarded against nested launcher/data directories.
- Rendered launcher release notes in a dedicated Markdown modal.
### Community & Feedback
Join the official WTOffline Discord server to share feedback on the new ground AI, post custom Bot tuning presets or mods, and follow client adaptation updates:
- **Discord**: https://discord.gg/P566xWNpEs
- **Homepage**: https://wto-project.net
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates (static and build checks pass on `2.61.0.60`).
+89
View File
@@ -0,0 +1,89 @@
## 简体中文
`v0.1.5` 是一次集中维护与修复版本,重点解决 **空战坠机后偶发崩溃(`0xC0000374`)**、**备用载具无法出击与扣减失效**、**单车涂装/挂载/弹链与配平未保存**、**联队时间与 20,000 研发点上限异常**、**贴花缓存缺失导致大面积无法显示**,以及 **启动器客户端移除防误删与安装体验改进**。
### 该下载哪一个文件?
- **绝大多数玩家(推荐)**:下载 **`wtoffline-launcher-0.1.5-win-x64.exe`**,直接覆盖安装即可(保留全部存档与配置)。
- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.5-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。
### 重点修复
- **对局与战斗**:
- 修复空战与核战冲突中飞机坠毁后 0.1–4 秒内偶发堆损坏崩溃(`0xC0000374`)的问题:新增原生模块 `local_mp_air_ai_sync`,在本地主机下串行化 AI 飞机队列扩容操作,同时保留多核并行物理更新;
- 修复战局内选择备用载具后无法点击出击,以及陆战 / 海战载具因内部路径前缀导致备用载具结算扣减失效、未修车槽位被误拦的问题;
- 修复新版陆战 AI 在单人试驾中错误接管靶车的问题,限定仅在多人对局中运行。
- **档案、联队与商店**:
- 修复载具涂装、挂载预设、弹链选择以及试飞配平(副翼 / 升降舵 / 方向舵)在重启后未保存的问题(感谢 `duduyagame`);
- 修复联队活跃度下次结算时间与排行榜赛季时间显示为 1970 年的问题;预置普通联队补齐 58–60 名 NPC 成员以恢复 20,000 周期研发点上限,接通对局活跃度累计与 3 天周期结算,并在 `tuning/clans.jsonc` 开放初始周期与初始活跃度配置(默认 `0`);
- 解除部分联动促销载具(`bf-109c_1_promo`、`us_m4_sherman_promo`、`jp_destroyer_hatsuzuki`)的跨平台促销锁定,支持在科技树直接订购;
- 免扣款支付按钮默认名称改为「直接获取」(`Direct Claim`),并可在 `tuning/store.jsonc`(`freePaymentLabel`)中自定义,同步热生效于游戏内支付弹窗、内置商城和内置交易所。
- **贴花缓存与涂装索引**:
- 修复从在线版导入贴花缓存时因部分 `.ddsx` 文件尚未缓存而导致贴花大面积读取失败的问题:构建时自动按实际缓存文件过滤索引、自动补齐缺失 LOD、未缓存标准贴花回退内置占位图并丢弃残缺涂装;
- 支持直接选择游戏根目录识别贴花缓存,安装向导可自动探测并预填在线版贴花缓存,客户端详情页新增一键从在线版来源导入贴花缓存。
### 启动器改进
- **更安全的客户端移除与还原流程**:
- 彻底拆分「从列表移除客户端」与「删除磁盘文件」,默认均不勾选;坏记录或已移动目录可直接安全移出列表;
- 新增 `wtoffline/client.json` 来源标记,仅允许对明确标记为独立副本 / 硬链接副本、非 Steam 且不与其他客户端来源目录重叠的目录执行删除;原地安装或无标记目录提供原子「还原原版文件并清理离线补丁」与「打开所在文件夹」入口。
- **安装进度与对话框体验**:
- 省空间复制进度条拆分展示实际写入字节与硬链接共享字节,并补充 Windows 资源管理器属性会重复统计硬链接空间的说明;
- 启动器所有分类文件 / 目录选择与导出对话框自动记住上次路径,并在原路径不存在时回退至最近的现存父目录。
### 社区交流与反馈
欢迎加入 WTOffline 官方 Discord 服务器反馈问题、分享调参配置或自制模组,并关注最新客户端适配进度:
- **Discord 社区**:https://discord.gg/P566xWNpEs
- **项目主页**:https://wto-project.net
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。
---
## English
`v0.1.5` is a maintenance and bug-fix release addressing the **Air battle post-crash heap corruption (`0xC0000374`)**, **backup vehicle respawn and accounting issues**, **vehicle camouflage/loadout/trim persistence**, **squadron timestamps and 20,000 RP cap**, **decal cache missing-file failures**, and **safer launcher client removal and installation UX**.
### Which file should I download?
- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.5-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning).
- **No-install / Portable**: Download **`wtoffline-launcher-0.1.5-win-x64-portable.zip`** — extract anywhere and run the launcher directly.
### Key Fixes
- **Battles & gameplay**:
- Fixed intermittent heap corruption crashes (`0xC0000374`) 0.1–4 seconds after aircraft crashes in Air battles and Nuclear Escalation via a new native module (`local_mp_air_ai_sync`) that serializes `TeamAiManager::addToUnsortedPlanes` on the local host while keeping multi-threaded aircraft updates intact.
- Fixed backup vehicles failing to respawn in LocalMP battles, normalized ground/naval unit path prefixes so backup deductions match correctly after battle, and stopped unrepaired crew slots from blocking backup spawns.
- Restricted the custom ground AI runtime to multiplayer battles so it no longer takes over target vehicles in single-player test drives.
- **Profile, squadrons & store**:
- Persisted per-vehicle camouflage, weapon preset, ammo belt selections, and test-flight trim preferences across restarts (thanks to `duduyagame`).
- Fixed 1970 timestamps for squadron activity rewards and leaderboard seasons, backfilled preset normal squadrons to 58–60 NPC members to restore the 20,000 RP period cap, wired battle RP into 3-day squadron activity cycles, and made initial periods/activity configurable in `tuning/clans.jsonc` (defaulting to `0`).
- Stripped cross-promotion locks from promo gift vehicles (`bf-109c_1_promo`, `us_m4_sherman_promo`, `jp_destroyer_hatsuzuki`) so they can be ordered directly from the tech tree.
- Changed the default free offline payment button label to **Direct Claim** (Chinese: 「直接获取」) and made it tunable via `tuning/store.jsonc` (`freePaymentLabel`) across the in-game payment dialog, local store, and local marketplace.
- **Decal & skin cache**:
- Fixed widespread decal load failures when importing partially cached online `cache/content` folders by filtering against locally present `.ddsx` files, repairing single-LOD hits, falling back uncached stock decals to built-in placeholders, and dropping incomplete downloadable skins.
- Added support for picking a game root folder directly, auto-detecting decal cache in the install wizard, and one-click import from the recorded online source in client details.
### Launcher Improvements
- **Safer client removal & stock restore**:
- Separated removing a client from the launcher list from deleting files on disk (both unchecked by default), allowing broken or missing entries to be removed cleanly.
- Added a `wtoffline/client.json` origin marker so disk deletion is only permitted for verified copy/hardlink clients outside Steam that do not overlap any registered source folder, plus an atomic **Restore stock files & clean offline patches** flow and **Open folder** action for in-place or unmarked directories.
- **Install progress & file pickers**:
- Split actual disk-copied bytes from hardlinked shared bytes in space-saving install progress, with a note explaining that Windows Explorer properties double-count hardlinked space.
- Remembered the last selected directory per category across all file/folder picker and export dialogs with automatic parent fallback.
### Community & Feedback
Join the official WTOffline Discord server to report issues, share custom tuning presets or mods, and follow client adaptation updates:
- **Discord**: https://discord.gg/P566xWNpEs
- **Homepage**: https://wto-project.net
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates (static and build checks pass on `2.61.0.60`).
+5 -1
View File
@@ -1,5 +1,8 @@
# Never commit game files (copyright, size). The build reads them from a game folder. # Never commit game files (copyright, size). The build reads them from a game folder.
*.vromfs.bin *.vromfs.bin
# Allow additive patch directories named after target packs inside mod templates (never binary archives).
!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/
!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/
*.vromfs.bin.orig *.vromfs.bin.orig
aces.exe aces.exe
aces*.exe aces*.exe
@@ -25,10 +28,11 @@ __pycache__/
*.pyc *.pyc
.venv/ .venv/
# Saves, logs, local runtime data # Saves, logs, local runtime data, local secrets
/data/ /data/
/saves/ /saves/
*.log *.log
.env*.local
# Editors / OS # Editors / OS
.vscode/ .vscode/
+12 -4
View File
@@ -2,7 +2,7 @@
<a id="zh-cn"></a> <a id="zh-cn"></a>
简体中文 · [English](#english) 简体中文 · [English](#english) · [Discord](https://discord.gg/P566xWNpEs)
------ ------
@@ -21,6 +21,10 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
`patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。 `patches/versions/` 中每份核对记录对应一个检查通过并在游戏中验证过的客户端版本。补丁和 native 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
## 开发讨论、交流与求助
欢迎加入 [WTOffline Discord 服务器](https://discord.gg/P566xWNpEs),用于日常交流、使用求助、问题反馈、调参分享以及开发和版本适配讨论。
## 功能 ## 功能
| 领域 | 已实现 | | 领域 | 已实现 |
@@ -151,7 +155,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
## 开发 ## 开发
开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn)。 开发规范、补丁指南和 PR 自查清单见 [Dev Docs](dev-docs/README.md#zh-cn),开发与版本适配讨论欢迎前往 [Discord](https://discord.gg/P566xWNpEs)。
### 环境要求 ### 环境要求
@@ -265,7 +269,7 @@ tools/ wtotools,补丁检查工具(Python)
# WTOffline (English) # WTOffline (English)
[简体中文](#zh-cn) · English [简体中文](#zh-cn) · English · [Discord](https://discord.gg/P566xWNpEs)
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. 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.
@@ -282,6 +286,10 @@ The repository contains source code and patch definitions only. It does not cont
Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record. Each check record in `patches/versions/` stands for a client version that passed the checks and was verified in game. Patches and native modules are located by signatures, string references and values read from the code rather than fixed addresses, so they usually still match after a minor update, but correct behavior is not guaranteed for a version without a check record.
## Community
Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general discussion, troubleshooting, bug reports, and development or patch adaptation discussions.
## Features ## Features
| Area | Implemented | | Area | Implemented |
@@ -412,7 +420,7 @@ To override defaults, create `tuning/<same file name>.jsonc` in the data folder
## Development ## Development
See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist. See [Dev Docs](dev-docs/README.md#english) for development rules, patch templates, and the PR checklist, or join [Discord](https://discord.gg/P566xWNpEs) for development and patch adaptation discussions.
### Requirements ### Requirements
+3 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "@wto/launcher", "name": "@wto/launcher",
"productName": "WTOffline Launcher", "productName": "WTOffline Launcher",
"version": "0.1.2", "version": "0.1.5",
"private": true, "private": true,
"description": "Installer and launcher of the War Thunder offline project.", "description": "Installer and launcher of the War Thunder offline project.",
"type": "module", "type": "module",
@@ -14,10 +14,12 @@
}, },
"dependencies": { "dependencies": {
"@fontsource/roboto-condensed": "^5.3.0", "@fontsource/roboto-condensed": "^5.3.0",
"@wto/mods": "*",
"@wto/patcher": "*", "@wto/patcher": "*",
"@wto/server": "*", "@wto/server": "*",
"fflate": "^0.8.2", "fflate": "^0.8.2",
"i18next": "^26.3.6", "i18next": "^26.3.6",
"marked": "^18.4.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8", "react-dom": "^19.2.8",
"react-i18next": "^17.0.10", "react-i18next": "^17.0.10",
+70 -5
View File
@@ -5,20 +5,34 @@ import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdat
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts'; import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts'; import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
import { getSettings, updateSettings } from '../services/config/settings-store.ts'; import { getSettings, updateSettings } from '../services/config/settings-store.ts';
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts'; import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress, maintenanceState } from '../services/copies/copy-maintenance.ts';
import { relocateCopy } from '../services/copies/relocate-copy.ts'; import { relocateCopy } from '../services/copies/relocate-copy.ts';
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts'; import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
import { measureFolder } from '../services/game-folder/folder-size.ts'; import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts'; import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts'; import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts'; import { changeDecalSource, decalImportInProgress, detectDecalCacheSource } from '../services/install/decals.ts';
import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts'; import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, installationInProgress } from '../services/install/install-game.ts';
import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts'; import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts'; import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
import {
applyModPreset,
autoSortMods,
deleteModPreset,
exportModPreset,
getModsState,
importModPreset,
openModsFolder,
saveModPreset,
setModEnabled,
setModsFolder,
setModsOrder,
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; import { 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'; import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */ /** Registers the handler of every contract channel. One line per channel; the work is in services/. */
@@ -55,11 +69,18 @@ export function registerIpcHandlers(): void {
BrowserWindow.fromWebContents(sender)?.close(); BrowserWindow.fromWebContents(sender)?.close();
}); });
handle('dialog:pickFolder', async ({ title }, sender) => { handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => {
const window = BrowserWindow.fromWebContents(sender); const window = BrowserWindow.fromWebContents(sender);
const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) }; const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath);
const options = {
properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>,
...(title ? { title } : {}),
...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : (result.filePaths[0] ?? null) }; const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('folder', chosen);
return { path: chosen };
}); });
handle('install:prepareCopy', () => createCopyDraft()); handle('install:prepareCopy', () => createCopyDraft());
@@ -135,6 +156,7 @@ export function registerIpcHandlers(): void {
return updated; return updated;
}); });
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id)); handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
handle('copies:maintenanceState', () => maintenanceState());
handle('copies:maintain', async (request) => { handle('copies:maintain', async (request) => {
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy'); if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress))); const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
@@ -142,6 +164,7 @@ export function registerIpcHandlers(): void {
return updated; return updated;
}); });
handle('copies:cancelMaintenance', () => cancelMaintenance()); handle('copies:cancelMaintenance', () => cancelMaintenance());
handle('decals:detectSource', async ({ path }) => ({ path: await detectDecalCacheSource(path) }));
handle('saves:list', ({ copyId }) => getSaveList(copyId)); handle('saves:list', ({ copyId }) => getSaveList(copyId));
handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId)); handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId));
@@ -174,6 +197,48 @@ export function registerIpcHandlers(): void {
handle('tuning:get', ({ copyId }) => getCopyTuning(copyId)); handle('tuning:get', ({ copyId }) => getCopyTuning(copyId));
handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch)); handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch));
const requireModsWritable = (): void => {
if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only');
};
handle('mods:getState', ({ copyId }) => getModsState(copyId));
handle('mods:setEnabled', ({ copyId, modId, enabled }) => {
requireModsWritable();
return setModEnabled(copyId, modId, enabled);
});
handle('mods:setOrder', ({ copyId, order }) => {
requireModsWritable();
return setModsOrder(copyId, order);
});
handle('mods:autoSort', ({ copyId }) => {
requireModsWritable();
return autoSortMods(copyId);
});
handle('mods:savePreset', ({ copyId, name, overwriteId }) => {
requireModsWritable();
return saveModPreset(copyId, name, overwriteId);
});
handle('mods:applyPreset', ({ copyId, presetId }) => {
requireModsWritable();
return applyModPreset(copyId, presetId);
});
handle('mods:deletePreset', ({ copyId, presetId }) => {
requireModsWritable();
return deleteModPreset(copyId, presetId);
});
handle('mods:exportPreset', ({ copyId, presetId }, sender) =>
exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender)));
handle('mods:importPreset', ({ copyId }, sender) => {
requireModsWritable();
return importModPreset(copyId, BrowserWindow.fromWebContents(sender));
});
handle('mods:openFolder', () => openModsFolder());
handle('mods:setFolder', async ({ copyId, path }) => {
requireModsWritable();
const state = await setModsFolder(copyId, path);
broadcast('event:settings-changed', await getSettings());
return state;
});
handle('launch:getState', () => getLaunchState()); handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null)); handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => { handle('launch:start', () => {
@@ -22,7 +22,9 @@ import {
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset, FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
} from '../patch-pack/release-assets.ts'; } from '../patch-pack/release-assets.ts';
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts'; import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts'; import {
cleanupPreparedPortableInstall, isPortableLauncher, launchPortableUpdater, preparePortableInstall,
} from './portable-update.ts';
type UpdateMode = 'installer' | 'portable'; type UpdateMode = 'installer' | 'portable';
@@ -215,7 +217,12 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
try { try {
if (offer.mode === 'portable') { if (offer.mode === 'portable') {
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot()); const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
launchPortableUpdater(prepared); try {
await launchPortableUpdater(prepared);
} catch (launchError) {
await cleanupPreparedPortableInstall(prepared);
throw launchError;
}
app.quit(); app.quit();
return; return;
} }
@@ -7,21 +7,35 @@
* only obsolete files listed in the previous portable inventory (never touching unrelated user * only obsolete files listed in the previous portable inventory (never touching unrelated user
* files in the same folder), and restarts the updated executable. * files in the same folder), and restarts the updated executable.
*/ */
import { execFile, spawn } from 'node:child_process'; import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import * as nodeFs from 'node:fs';
import { existsSync } from 'node:fs'; import { existsSync } from 'node:fs';
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import { z } from 'zod'; import { z } from 'zod';
const execute = promisify(execFile); const execute = promisify(execFile);
const require = createRequire(import.meta.url);
export const PORTABLE_MARKER_FILE = 'portable-mode'; export const PORTABLE_MARKER_FILE = 'portable-mode';
export const PORTABLE_FILES_MANIFEST = 'portable-files.json'; export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
export const PORTABLE_UPDATE_LOG_FILENAME = 'portable-update.log';
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe'; const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe'; const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
// Electron patches node:fs to expose .asar archives as virtual directories, which makes
// lstat().isFile() return false and recursive rm() fail on staged .asar files.
function rawFsPromises(): typeof nodeFs.promises {
try {
return (require('original-fs') as typeof nodeFs).promises;
} catch {
return nodeFs.promises;
}
}
const PortableInventorySchema = z.object({ const PortableInventorySchema = z.object({
format: z.literal(1), format: z.literal(1),
version: z.string().min(1), version: z.string().min(1),
@@ -216,6 +230,7 @@ export async function preparePortableInstall(
): Promise<PreparedPortableUpdate> { ): Promise<PreparedPortableUpdate> {
await assertWritableFolder(installDir); await assertWritableFolder(installDir);
await mkdir(updatesRoot, { recursive: true }); await mkdir(updatesRoot, { recursive: true });
const rawFs = rawFsPromises();
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`); const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
await mkdir(stagingDir, { recursive: true }); await mkdir(stagingDir, { recursive: true });
try { try {
@@ -238,7 +253,7 @@ export async function preparePortableInstall(
} }
for (const rel of newFiles) { for (const rel of newFiles) {
const stagedPath = resolveInside(stagingDir, rel); const stagedPath = resolveInside(stagingDir, rel);
const stats = await lstat(stagedPath); const stats = await rawFs.lstat(stagedPath);
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`); if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
} }
@@ -254,7 +269,7 @@ export async function preparePortableInstall(
installDir: resolve(installDir), installDir: resolve(installDir),
stagingDir, stagingDir,
archivePath, archivePath,
logPath: join(updatesRoot, 'portable-update.log'), logPath: join(updatesRoot, PORTABLE_UPDATE_LOG_FILENAME),
executable: LAUNCHER_EXECUTABLE, executable: LAUNCHER_EXECUTABLE,
newFiles, newFiles,
staleFiles, staleFiles,
@@ -263,21 +278,46 @@ export async function preparePortableInstall(
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8'); await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
return { scriptPath, planPath, stagingDir }; return { scriptPath, planPath, stagingDir };
} catch (error) { } catch (error) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined); await rawFs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
throw error; throw error;
} }
} }
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void { export async function cleanupPreparedPortableInstall(prepared: PreparedPortableUpdate): Promise<void> {
const child = spawn('powershell.exe', [ const rawFs = rawFsPromises();
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass', await rawFs.rm(prepared.stagingDir, { recursive: true, force: true }).catch(() => undefined);
'-File', prepared.scriptPath, prepared.planPath, await rm(prepared.planPath, { force: true }).catch(() => undefined);
], { }
cwd: dirname(prepared.scriptPath),
detached: true, /**
stdio: 'ignore', * Launch the portable apply script in a hidden PowerShell process that survives Electron exit.
windowsHide: true, *
shell: false, * On Windows, spawning powershell.exe directly with Node's `detached: true` sets DETACHED_PROCESS
}); * (no console), causing Windows PowerShell 5.1 ConsoleHost to exit silently with code 0 before
child.unref(); * running `-File`. Spawning without `detached` lets PowerShell run, but Electron tears down
* attached children on `app.quit()`. Using a short hidden PowerShell helper with `Start-Process`
* gives the updater its own hidden console and cleanly detaches it before the launcher quits.
*/
export async function launchPortableUpdater(prepared: PreparedPortableUpdate): Promise<void> {
const workDir = dirname(prepared.scriptPath);
const launcherPath = join(workDir, `launch-portable-${randomUUID()}.ps1`);
const script = [
'param([string]$ScriptPath, [string]$PlanPath, [string]$WorkDir)',
"$ErrorActionPreference = 'Stop'",
'$argsList = @(',
" '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',",
' \'-File\', "`"$ScriptPath`"", "`"$PlanPath`""',
')',
"Start-Process -FilePath 'powershell.exe' -WorkingDirectory $WorkDir -WindowStyle Hidden -ArgumentList $argsList",
].join('\r\n');
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
await writeFile(launcherPath, `\uFEFF${script}\r\n`, 'utf8');
try {
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', launcherPath, prepared.scriptPath, prepared.planPath, workDir,
], { cwd: workDir, windowsHide: true, timeout: 30_000 });
} finally {
await rm(launcherPath, { force: true }).catch(() => undefined);
}
} }
@@ -1,10 +1,11 @@
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'; import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
import { rawFs } from '../../util/raw-fs.ts';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts'; import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
export async function fileInfo(path: string) { export async function fileInfo(path: string) {
const fsPromises = rawFs().promises;
try { try {
return await lstat(path); return await fsPromises.lstat(path);
} catch (error) { } catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return null; return null;
@@ -28,7 +29,8 @@ export async function changeCopyFiles<T>(
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>, prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
recordChange: () => Promise<T>, recordChange: () => Promise<T>,
): Promise<T> { ): Promise<T> {
const work = await mkdtemp(join(dirname(root), '.wto-copy-')); const fsPromises = rawFs().promises;
const work = await fsPromises.mkdtemp(join(dirname(root), '.wto-copy-'));
const incoming = join(work, 'new'); const incoming = join(work, 'new');
const backups = join(work, 'old'); const backups = join(work, 'old');
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = []; const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
@@ -44,14 +46,14 @@ export async function changeCopyFiles<T>(
const entry = { target, saved: null as string | null, replaced: false }; const entry = { target, saved: null as string | null, replaced: false };
if (old) { if (old) {
const saved = join(backups, path); const saved = join(backups, path);
await mkdir(dirname(saved), { recursive: true }); await fsPromises.mkdir(dirname(saved), { recursive: true });
await rename(target, saved); await fsPromises.rename(target, saved);
entry.saved = saved; entry.saved = saved;
} }
changes.push(entry); changes.push(entry);
if (add) { if (add) {
await mkdir(dirname(target), { recursive: true }); await fsPromises.mkdir(dirname(target), { recursive: true });
await rename(join(incoming, path), target); await fsPromises.rename(join(incoming, path), target);
entry.replaced = true; entry.replaced = true;
} }
} }
@@ -60,8 +62,8 @@ export async function changeCopyFiles<T>(
} catch (error) { } catch (error) {
for (const { target, saved, replaced } of changes.reverse()) { for (const { target, saved, replaced } of changes.reverse()) {
try { try {
if (replaced) await rm(target, { force: true }); if (replaced) await fsPromises.rm(target, { force: true });
if (saved) await rename(saved, target); if (saved) await fsPromises.rename(saved, target);
} catch (rollbackError) { } catch (rollbackError) {
keepBackups = true; keepBackups = true;
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError); console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
@@ -70,7 +72,7 @@ export async function changeCopyFiles<T>(
throw error; throw error;
} finally { } finally {
if (!keepBackups && relative(dirname(root), dirname(work)) === '') { if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error)); await fsPromises.rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
} }
} }
} }
@@ -7,7 +7,8 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts'; import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts'; import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts'; import { readClientMarker, writeClientMarker } from '../install/client-marker.ts';
import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { import {
fileHash, fileHash,
linkVerifiedResource, linkVerifiedResource,
@@ -21,20 +22,10 @@ import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } fro
import { checkPatches } from '../install/patch-check.ts'; import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts'; import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import { readSource } from './copy-source.ts';
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void; export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
const game = await inspectGameFolder(record.sourcePath);
return game.missingFiles.length > 0 ? null : game;
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean { export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0; return !!source?.version && !!version && compareVersions(source.version, version) > 0;
} }
@@ -67,7 +58,10 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
const linked = record.hardlinkedFiles ?? []; const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key)); const linkedPaths = new Set(linked.map(key));
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root); const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name))); // Older installs may have tracked files in folders that source scans now skip.
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter(
(name) => !found.has(key(name)) && !isInSkippedSourceFolder(name),
);
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles( const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal, game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
); );
@@ -76,7 +70,7 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
signal.throwIfAborted(); signal.throwIfAborted();
const check = await checkPatches(game.path, record.dataPath); const check = await checkPatches(game.path, record.dataPath);
signal.throwIfAborted(); signal.throwIfAborted();
return changeCopyFiles(root, async (incoming) => { const updated = await changeCopyFiles(root, async (incoming) => {
report('copying', 0, copy.totalBytes); report('copying', 0, copy.totalBytes);
let lastReport = 0; let lastReport = 0;
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => { await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
@@ -111,6 +105,13 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory, lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}), ...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
}))); })));
if (!preserveHardlinks && linked.length > 0) {
const marker = await readClientMarker(root);
if (marker?.origin === 'hardlink' || (marker === null && record.method === 'copy')) {
await writeClientMarker(root, 'copy');
}
}
return updated;
} }
interface UpdateFilePlan { interface UpdateFilePlan {
@@ -195,7 +196,7 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0); const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
const dataPath = await canonicalCopyPath(record.dataPath); const dataPath = await canonicalCopyPath(record.dataPath);
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path])); const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
return changeCopyFiles(root, async (incoming) => { const updated = await changeCopyFiles(root, async (incoming) => {
const replacements: string[] = []; const replacements: string[] = [];
const unchanged = new Map<string, BigIntStats>(); const unchanged = new Map<string, BigIntStats>();
let checked = 0; let checked = 0;
@@ -232,6 +233,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
report('applying', total, total); report('applying', total, total);
return { replace: replacements, remove: [] }; return { replace: replacements, remove: [] };
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] }))); }, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
await writeClientMarker(root, 'hardlink');
return updated;
} }
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> { async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
@@ -1,34 +1,65 @@
import { readdir, rm } from 'node:fs/promises'; import { isAbsolute, relative } from 'node:path';
import { isAbsolute, join, parse, relative } from 'node:path';
import { app } from 'electron';
import { isInSteamLibrary } from '@wto/patcher'; import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { Copies, InstallRecord } from '@shared/schemas/install.ts'; import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
import { installationInProgress } from '../install/install-game.ts'; import { installationInProgress } from '../install/install-game.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts'; import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts'; import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts'; import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { readInstalledLab } from '../launch/lab-handoff.ts'; import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts'; import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts'; import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts'; import {
canDeleteCopyFiles,
canRestoreStock,
checkedRoot,
failLocation,
removeCopy,
resolveClientOrigin,
withCanonicalSources,
} from './copy-removal.ts';
import { readSource, setCopySource } from './copy-source.ts';
let current: { stop: AbortController; interruptible: boolean } | null = null; export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts';
let current: {
stop: AbortController;
interruptible: boolean;
progress: MaintenanceProgress;
} | null = null;
export function maintenanceInProgress(): boolean { export function maintenanceInProgress(): boolean {
return current !== null; return current !== null;
} }
export function maintenanceState(): MaintenanceProgress | null {
return current ? { ...current.progress } : null;
}
export function cancelMaintenance(): void { export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort(); if (current?.interruptible) current.stop.abort();
} }
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> { export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
const record = await requireCopy(id); const registry = await listCopies();
const source = await readSource(record); const record = registry.copies.find((copy) => copy.id === id);
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]); if (!record) throw new AppError('copy_not_found');
const [source, copyPath, dataPath, canonicalCopies] = await Promise.all([
readSource(record),
canonicalCopyPath(record.copyPath),
canonicalCopyPath(record.dataPath),
withCanonicalSources(registry.copies),
]);
const [diskMarker, hasHardlinkedResources, canRestoreAndRemove] = await Promise.all([
readClientMarker(copyPath),
detectHardlinkedResources(copyPath),
canRestoreStock(record, copyPath),
]);
const clientOrigin = resolveClientOrigin(record, diskMarker);
const canDeleteFiles = canDeleteCopyFiles(record, copyPath, clientOrigin, registry.copies) &&
canDeleteCopyFiles(record, copyPath, clientOrigin, canonicalCopies);
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath); const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath); const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
return { return {
@@ -38,23 +69,37 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath), spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath), steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null, steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
clientOrigin,
hasHardlinkedResources,
canDeleteFiles,
canRestoreAndRemove,
}; };
} }
export async function maintainCopy( export async function maintainCopy(
request: MaintenanceRequest, request: MaintenanceRequest,
publish: (progress: MaintenanceProgress) => void, publish: (progress: MaintenanceProgress | null) => void,
): Promise<Copies> { ): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy'); if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const initial: MaintenanceProgress = {
id: request.id,
operation: request.operation,
phase: 'checking',
doneBytes: 0,
totalBytes: 0,
};
const job = { const job = {
stop: new AbortController(), stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact', interruptible: request.operation === 'update' || request.operation === 'compact',
progress: initial,
}; };
current = job; current = job;
const signal = job.stop.signal; const signal = job.stop.signal;
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => { const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
if (phase === 'applying') job.interruptible = false; if (phase === 'applying') job.interruptible = false;
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes }); const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
job.progress = next;
publish(next);
}; };
try { try {
@@ -67,19 +112,35 @@ export async function maintainCopy(
throw new AppError('maintenance_failed'); throw new AppError('maintenance_failed');
} finally { } finally {
current = null; current = null;
publish(null);
} }
} }
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> { async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
const { id, operation, steamLocations } = request; const { id, operation, steamLocations } = request;
const record = await requireCopy(id); const record = await requireCopy(id);
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
if (operation === 'delete') {
return removeCopy(
record,
{
deleteFiles: request.deleteFiles === true,
restoreStock: request.restoreStock === true,
deleteData: request.deleteData === true,
},
signal,
report,
labServerUses,
);
}
const root = await checkedRoot(record); const root = await checkedRoot(record);
const dataPath = await canonicalCopyPath(record.dataPath); const dataPath = await canonicalCopyPath(record.dataPath);
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath); const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy'); if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted(); signal.throwIfAborted();
if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) { if (operation !== 'confirm-steam' && needsConfirmation) {
throw new AppError('launch_steam_confirmation_required'); throw new AppError('launch_steam_confirmation_required');
} }
@@ -101,9 +162,6 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
return updateFromSource(record, root, signal, report); return updateFromSource(record, root, signal, report);
case 'compact': case 'compact':
return compactCopy(record, root, signal, report); return compactCopy(record, root, signal, report);
case 'delete':
report('applying');
return remove(record, root, request.deleteData);
} }
} }
@@ -113,42 +171,6 @@ async function requireCopy(id: string): Promise<InstallRecord> {
return record; return record;
} }
function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath, true);
const backup = await canonicalCopyPath(record.stockBackupPath);
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
if (relative(expectedBackup, backup) !== '') {
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
}
if (record.sourcePath) {
const source = await canonicalCopyPath(record.sourcePath);
if (copyPathContains(source, root) || copyPathContains(root, source)) {
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
}
}
return root;
}
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
const root = await canonicalCopyPath(path);
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
const appPath = await canonicalCopyPath(app.getAppPath());
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
}
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
failLocation('folder_is_symlink', { path, root });
}
return root;
}
async function labServerUses(root: string): Promise<boolean> { async function labServerUses(root: string): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null); const lab = await readInstalledLab().catch(() => null);
if (!lab || relative(lab.copyPath, root) !== '') return false; if (!lab || relative(lab.copyPath, root) !== '') return false;
@@ -161,38 +183,3 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(), ...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
})); }));
} }
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
return removeCopyRecord(record.id);
}
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
}
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await rm(root, { recursive: true, force: true });
}
if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true });
return removeCopyRecord(record.id);
}
/** Keep the data folder in place when it was chosen inside this copy. */
async function removeExcept(folder: string, kept: string): Promise<void> {
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
await removeExcept(path, kept);
} else {
await rm(path, { recursive: true, force: true });
}
}
}
@@ -0,0 +1,272 @@
import { constants } from 'node:fs';
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
import { app } from 'electron';
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { ClientOrigin, Copies, InstallRecord } from '@shared/schemas/install.ts';
import { rawFs } from '../../util/raw-fs.ts';
import { readClientMarker, type ClientMarker } from '../install/client-marker.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord } from '../install/install-record.ts';
import { requireStockBackupLocation, STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning } from '../launch/launch-controller.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import type { Report } from './copy-file-maintenance.ts';
const OFFLINE_HOOK_FILES = ['wto_ws.dll', 'wto_ws.cfg', 'wto_ws.log'] as const;
export interface RemoveCopyOptions {
readonly deleteFiles: boolean;
readonly restoreStock: boolean;
readonly deleteData: boolean;
}
export function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
/**
* Resolve the effective client origin by preferring a valid on-disk marker while
* keeping in-place registrations conservatively locked as `in-place`.
*/
export function resolveClientOrigin(
record: InstallRecord,
diskMarker: ClientMarker | null,
): ClientOrigin | null {
if (record.method === 'in-place') return 'in-place';
if (diskMarker) return diskMarker.origin;
if (record.method === 'copy') return record.hardlinkedFiles?.length ? 'hardlink' : 'copy';
return null;
}
/**
* Only launcher-created copies or existing folders carrying a valid copy/hardlink marker
* outside any Steam library and disjoint from every registered copy's sourcePath may be deleted.
*/
export function canDeleteCopyFiles(
record: InstallRecord,
root: string,
effectiveOrigin: ClientOrigin | null,
allCopies: readonly InstallRecord[] = [],
): boolean {
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) return false;
if (effectiveOrigin !== 'copy' && effectiveOrigin !== 'hardlink') return false;
const normalizedRoot = resolve(root);
const normalizedCopyPath = resolve(record.copyPath);
const sources = record.sourcePath
? [record.sourcePath, ...allCopies.map((copy) => copy.sourcePath)]
: allCopies.map((copy) => copy.sourcePath);
for (const candidate of sources) {
if (!candidate) continue;
const source = resolve(candidate);
if (pathsOverlap(normalizedRoot, source) || pathsOverlap(normalizedCopyPath, source)) {
return false;
}
}
return true;
}
/** Check that `record` has a safe root and all four original core files readable in wtoffline/stock. */
export async function canRestoreStock(record: InstallRecord, root: string): Promise<boolean> {
try {
const safeRoot = await checkedRoot(record);
const canonicalRoot = await canonicalCopyPath(root);
if (relative(safeRoot, canonicalRoot) !== '') return false;
const backup = await requireStockBackupLocation(safeRoot);
const fsPromises = rawFs().promises;
for (const file of Object.values(GAME_FILES)) {
const stockFile = join(backup, file);
const info = await fileInfo(stockFile);
if (!info?.isFile()) return false;
await fsPromises.access(stockFile, constants.R_OK);
}
return true;
} catch {
return false;
}
}
/** Resolve every copy's `sourcePath` through symlinks/junctions for overlap checks. */
export async function withCanonicalSources(copies: readonly InstallRecord[]): Promise<InstallRecord[]> {
return Promise.all(copies.map(async (copy) => (
copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy
)));
}
export async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath, true);
const backup = await canonicalCopyPath(record.stockBackupPath);
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
if (relative(expectedBackup, backup) !== '') {
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
}
if (record.sourcePath) {
const source = await canonicalCopyPath(record.sourcePath);
if (pathsOverlap(source, root)) {
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
}
}
return root;
}
export async function safeFolder(path: string, steamAllowed = false): Promise<string> {
const root = await canonicalCopyPath(path);
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
const appPath = await canonicalCopyPath(app.getAppPath());
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
}
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
failLocation('folder_is_symlink', { path, root });
}
return root;
}
export async function removeCopy(
record: InstallRecord,
options: RemoveCopyOptions,
signal: AbortSignal,
report: Report,
labServerUses: (root: string) => Promise<boolean>,
): Promise<Copies> {
const { deleteFiles, restoreStock, deleteData } = options;
if (deleteFiles && restoreStock) {
failLocation('delete_files_and_restore_stock_conflict', { id: record.id });
}
const canonicalRoot = await canonicalCopyPath(record.copyPath);
if (await gameProcessRunning(signal) || await labServerUses(canonicalRoot)) {
throw new AppError('maintenance_busy');
}
signal.throwIfAborted();
// Pure list removal touches no files on disk and skips copyPath/stockBackup checks
// so missing, moved, or damaged client registrations can always be removed safely.
if (!deleteFiles && !deleteData && !restoreStock) {
report('applying');
return removeCopyRecord(record.id);
}
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot);
if ((deleteFiles || deleteData) && copyInSteam) {
failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', {
method: record.method,
copyPath: record.copyPath,
root: canonicalRoot,
});
}
let root = canonicalRoot;
if (deleteFiles) {
const allCopies = (await listCopies()).copies;
const canonicalCopies = await withCanonicalSources(allCopies);
const initialOrigin = resolveClientOrigin(record, await readClientMarker(canonicalRoot));
if (!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, allCopies) ||
!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, canonicalCopies)) {
failLocation('delete_files_blocked', { method: record.method, origin: initialOrigin, copyPath: record.copyPath, root: canonicalRoot });
}
root = await checkedRoot(record);
const verifiedOrigin = resolveClientOrigin(record, await readClientMarker(root));
if (!canDeleteCopyFiles(record, root, verifiedOrigin, allCopies) ||
!canDeleteCopyFiles(record, root, verifiedOrigin, canonicalCopies)) {
failLocation('delete_files_blocked', { method: record.method, origin: verifiedOrigin, copyPath: record.copyPath, root });
}
} else if (restoreStock) {
root = await checkedRoot(record);
if (!(await canRestoreStock(record, root))) {
failLocation('restore_stock_unavailable', { copyPath: record.copyPath, root, stockBackupPath: record.stockBackupPath });
}
}
const data = deleteData ? await safeFolder(record.dataPath, false) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
const stockBackup = await canonicalCopyPath(record.stockBackupPath);
if (deleteData) {
const rawRoot = resolve(record.copyPath);
const overlapsSource = source !== null && pathsOverlap(data, source);
const containsCopy = deleteFiles
? relative(data, root) !== '' && copyPathContains(data, root)
: copyPathContains(data, root) || copyPathContains(data, rawRoot) || copyPathContains(data, stockBackup);
if (overlapsSource || containsCopy) {
failLocation('delete_data_overlaps_source_or_copy', { root, data, source, stockBackup, deleteFiles, restoreStock });
}
}
report('applying');
const fsPromises = rawFs().promises;
if (restoreStock) {
await restoreStockAndCleanOfflineFiles(root, data, deleteData);
} else if (deleteFiles) {
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await fsPromises.rm(root, { recursive: true, force: true });
}
}
if (deleteData && (!deleteFiles || !copyPathContains(root, data))) {
await fsPromises.rm(data, { recursive: true, force: true });
}
return removeCopyRecord(record.id);
}
/**
* Atomically restore the four stock core files from `wtoffline/stock`, then remove
* only launcher-created hook files and the `wtoffline` folder without touching base game files.
*/
async function restoreStockAndCleanOfflineFiles(root: string, data: string, deleteData: boolean): Promise<void> {
const fsPromises = rawFs().promises;
const backup = await requireStockBackupLocation(root);
await changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) {
const sourceFile = join(backup, file);
if (!(await fileInfo(sourceFile))?.isFile()) {
failLocation('stock_backup_source_missing', { root, file, sourceFile });
}
const targetFile = join(incoming, file);
await fsPromises.mkdir(dirname(targetFile), { recursive: true });
await fsPromises.copyFile(sourceFile, targetFile);
}
return { replace: files, remove: [] };
}, async () => undefined);
const exeDir = dirname(GAME_FILES.executable);
for (const name of OFFLINE_HOOK_FILES) {
const hookFile = await stagedPath(root, join(exeDir, name));
const info = await fileInfo(hookFile);
if (info && !info.isDirectory()) {
await fsPromises.rm(hookFile, { force: true });
}
}
const wtofflineFolder = await stagedPath(root, dirname(STOCK_BACKUP_FOLDER));
const wtofflineInfo = await fileInfo(wtofflineFolder);
if (wtofflineInfo?.isDirectory()) {
if (!deleteData && copyPathContains(wtofflineFolder, data)) {
await removeExcept(wtofflineFolder, data);
} else {
await fsPromises.rm(wtofflineFolder, { recursive: true, force: true });
}
}
}
function pathsOverlap(left: string, right: string): boolean {
return copyPathContains(left, right) || copyPathContains(right, left);
}
/** Keep the data folder in place when it was chosen inside this copy. */
async function removeExcept(folder: string, kept: string): Promise<void> {
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
const fsPromises = rawFs().promises;
for (const entry of await fsPromises.readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
await removeExcept(path, kept);
} else {
await fsPromises.rm(path, { recursive: true, force: true });
}
}
}
@@ -0,0 +1,52 @@
import { isAbsolute, join } from 'node:path';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { canonicalCopyPath, copyPathContains, updateCopyRecord } from '../install/install-record.ts';
import { fileInfo } from './change-copy-files.ts';
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
return await inspectSource(record, record.sourcePath);
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export async function setCopySource(record: InstallRecord, path: string | undefined): Promise<Copies> {
const source = await inspectSource(record, path);
return updateCopyRecord(record.id, (latest) => {
if (latest.copyPath !== record.copyPath || latest.dataPath !== record.dataPath) {
throw new AppError('maintenance_location');
}
return { ...latest, sourcePath: source.resolvedPath };
});
}
async function inspectSource(record: InstallRecord, path: string | undefined): Promise<GameFolderInspection> {
if (!path || !isAbsolute(path)) throw new AppError('maintenance_source_invalid');
const [game, copyPath, dataPath] = await Promise.all([
inspectGameFolder(path), canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath),
]);
const source = game.resolvedPath;
const overlapsCopy = copyPathContains(source, copyPath) || copyPathContains(copyPath, source);
if (overlapsCopy || copyPathContains(source, dataPath)) {
throw new AppError('maintenance_source_overlap');
}
if (game.missingFiles.length || !game.version || game.hasOfflineBackup || game.needsStockSource) {
throw new AppError('maintenance_source_invalid');
}
// Verify that the directory has game resources beyond the four files used for patching.
const [content, languages, missions] = await Promise.all([
fileInfo(join(source, 'content')),
fileInfo(join(source, 'lang.vromfs.bin')),
fileInfo(join(source, 'mis.vromfs.bin')),
]);
if (!content?.isDirectory() || !languages?.isFile() || !missions?.isFile()) {
throw new AppError('maintenance_source_invalid');
}
return { ...game, path: source };
}
@@ -7,6 +7,7 @@ import { zipSync } from 'fflate';
import { GAME_FILES } from '@wto/patcher'; import { GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts'; import type { InstallRecord } from '@shared/schemas/install.ts';
import { PORTABLE_UPDATE_LOG_FILENAME } from '../app-update/portable-update.ts';
import { getSettings } from '../config/settings-store.ts'; import { getSettings } from '../config/settings-store.ts';
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts'; import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts'; import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
@@ -58,6 +59,11 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name)); await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
} }
} }
await addFile(
files,
`launcher-logs/${PORTABLE_UPDATE_LOG_FILENAME}`,
join(userData, 'launcher-updates', PORTABLE_UPDATE_LOG_FILENAME),
);
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath; const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
if (dataPath) await addServerLogs(files, dataPath); if (dataPath) await addServerLogs(files, dataPath);
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher'; import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { GameFolderInspection } from '@shared/schemas/install.ts'; import type { GameFolderInspection } from '@shared/schemas/install.ts';
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { resourcePaths } from '../resources/resource-paths.ts'; import { resourcePaths } from '../resources/resource-paths.ts';
@@ -61,6 +62,10 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
needsStockSource = hasMarkerFile || liveExePatched; needsStockSource = hasMarkerFile || liveExePatched;
} }
} }
const [clientMarker, hasHardlinkedResources] = await Promise.all([
readClientMarker(resolved),
detectHardlinkedResources(resolved),
]);
return { return {
path, path,
resolvedPath: resolved, resolvedPath: resolved,
@@ -70,6 +75,8 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved), inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
hasOfflineBackup, hasOfflineBackup,
needsStockSource, needsStockSource,
clientOrigin: clientMarker?.origin ?? null,
hasHardlinkedResources,
}; };
} }
@@ -0,0 +1,114 @@
import { join } from 'node:path';
import { z } from 'zod';
import { hardlinkResourceRules, isHardlinkableResource } from '@wto/patcher';
import { ClientOriginSchema, type ClientOrigin } from '@shared/schemas/install.ts';
import { writeJsonAtomic } from '../../util/atomic-json.ts';
import { rawFs } from '../../util/raw-fs.ts';
/** Relative path of the self-describing client identity marker inside a client folder. */
export const CLIENT_MARKER_FILE = join('wtoffline', 'client.json');
export const ClientMarkerSchema = z.object({
format: z.literal(1),
origin: ClientOriginSchema,
createdBy: z.literal('wtoffline-launcher'),
createdAt: z.string().min(1),
updatedAt: z.string().min(1).optional(),
});
export type ClientMarker = z.output<typeof ClientMarkerSchema>;
/** Cap on qualifying resource files inspected when sampling for hard links. */
const MAX_RESOURCE_SAMPLES = 64;
export function clientMarkerPath(copyFolder: string): string {
return join(copyFolder, CLIENT_MARKER_FILE);
}
/**
* Safely read and validate `<copyFolder>/wtoffline/client.json`.
* Returns `null` when missing, unreadable, malformed, or schema-invalid without throwing.
*/
export async function readClientMarker(copyFolder: string): Promise<ClientMarker | null> {
try {
const text = await rawFs().promises.readFile(clientMarkerPath(copyFolder), 'utf8');
const parsed = ClientMarkerSchema.safeParse(JSON.parse(text) as unknown);
return parsed.success ? parsed.data : null;
} catch {
return null;
}
}
/**
* Atomically write `<copyFolder>/wtoffline/client.json`.
* Preserves `createdAt` and records `updatedAt` when updating an existing valid marker.
*/
export async function writeClientMarker(copyFolder: string, origin: ClientOrigin): Promise<ClientMarker> {
const existing = await readClientMarker(copyFolder);
const now = new Date().toISOString();
const marker: ClientMarker = existing
? {
format: 1,
origin,
createdBy: 'wtoffline-launcher',
createdAt: existing.createdAt,
updatedAt: now,
}
: {
format: 1,
origin,
createdBy: 'wtoffline-launcher',
createdAt: now,
};
await writeJsonAtomic(clientMarkerPath(copyFolder), marker);
return marker;
}
/**
* Lightweight probe for hard-linked read-only resource packs under allowed content directories.
* Returns `true` as soon as a single qualifying resource reports `nlink >= 2`, or `false` on
* missing/unreadable directories or when no sampled resource is hard-linked.
*/
export async function detectHardlinkedResources(copyFolder: string): Promise<boolean> {
const fsPromises = rawFs().promises;
const rules = hardlinkResourceRules();
const queue: Array<{ absDir: string; relDir: string }> = rules.allowedDirectories.map((dir) => {
const clean = dir.replace(/\/+$/, '');
return { absDir: join(copyFolder, clean), relDir: clean };
});
let sampled = 0;
while (queue.length > 0 && sampled < MAX_RESOURCE_SAMPLES) {
const current = queue.shift()!;
let entries;
try {
entries = await fsPromises.readdir(current.absDir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (entry.isSymbolicLink()) continue;
const absPath = join(current.absDir, entry.name);
const relPath = `${current.relDir}/${entry.name}`;
if (entry.isDirectory()) {
queue.push({ absDir: absPath, relDir: relPath });
continue;
}
if (!entry.isFile()) continue;
const lower = entry.name.toLowerCase();
if (!rules.allowedExtensions.some((ext) => lower.endsWith(ext))) continue;
try {
const stats = await fsPromises.lstat(absPath);
if (!stats.isFile() || !isHardlinkableResource(relPath, stats.size)) continue;
if (stats.nlink >= 2) return true;
sampled += 1;
if (sampled >= MAX_RESOURCE_SAMPLES) return false;
} catch {
continue;
}
}
}
return false;
}
@@ -1,10 +1,11 @@
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs'; import type { BigIntStats, Dirent } from 'node:fs';
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises'; import { join, normalize, relative, sep } from 'node:path';
import { join, relative } from 'node:path';
import { Transform } from 'node:stream'; import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises'; import { pipeline } from 'node:stream/promises';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import { rawFs } from '../../util/raw-fs.ts';
import { linkVerifiedResource, sameResource } from './hardlink-files.ts'; import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
import { findIncompleteUhqPacks, isPathInUhqPacks } from './uhq-packages.ts';
/** /**
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock * Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
@@ -12,14 +13,45 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
*/ */
/** /**
* Top-level folders of an installation that hold what the game produced while the player played * Top-level folders of an installation that hold player-generated data or user content from
* online, not the game itself: logs, the web content cache, replays, screenshots and the player's * playing online, not the stock client itself: logs, the web content cache, replays, screenshots,
* own missions. The offline copy does not take the online game's data (working rules 18); the * and user missions, skins and sights. The offline copy does not take the online game's data; the
* game creates these folders again when it needs them. * game creates these folders again when it needs them.
*/ */
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']); export const PLAYER_DATA_FOLDERS = new Set([
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */ '.game_logs',
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']); 'cache',
'replays',
'screenshots',
'usermissions',
'userskins',
'usersights',
]);
/**
* Top-level folders ignored when scanning a stock source in addition to player data:
* official launcher/updater logs and obsolete files, the War Thunder CDK toolkit, and any stray
* offline backup directory.
*/
const SKIPPED_SOURCE_FOLDERS = new Set([
...PLAYER_DATA_FOLDERS,
'.gaijin_updater_logs',
'.launcher_log',
'.obsolete',
'.start_app_logs',
'warthundercdk',
'wtoffline',
]);
const LAUNCHER_EXECUTABLE_LOWER = 'wtoffline launcher.exe';
/** Whether a relative path starts with a top-level entry excluded from source scans. */
export function isInSkippedSourceFolder(relativePath: string): boolean {
const [topLevel = ''] = normalize(relativePath).split(sep, 1);
return SKIPPED_SOURCE_FOLDERS.has(topLevel.toLowerCase());
}
function isLauncherFolder(entries: readonly Dirent[]): boolean {
return entries.some((entry) => entry.isFile() && entry.name.toLowerCase() === LAUNCHER_EXECUTABLE_LOWER);
}
interface CopyEntry { interface CopyEntry {
readonly relativePath: string; readonly relativePath: string;
@@ -36,25 +68,44 @@ export interface CopyPlan {
export interface CopyProgress { export interface CopyProgress {
readonly doneBytes: number; readonly doneBytes: number;
readonly doneFiles: number; readonly doneFiles: number;
/** Bytes actually written to disk so far (excludes hard-linked files). */
readonly copiedBytes: number;
/** Bytes shared via hard links so far (occupies no extra disk space). */
readonly linkedBytes: number;
/** Number of hard-linked files created so far. */
readonly linkedFiles: number;
} }
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */ /** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
export async function planCopy(source: string): Promise<CopyPlan> { export async function planCopy(source: string): Promise<CopyPlan> {
const fsPromises = rawFs().promises;
const incompleteUhq = await findIncompleteUhqPacks(source);
const skippedUhq = new Set(incompleteUhq);
if (incompleteUhq.length > 0) {
console.warn(`[install] skipping incomplete optional UHQ pack(s) in ${source}: ${incompleteUhq.join(', ')}`);
}
const files: CopyEntry[] = []; const files: CopyEntry[] = [];
const folders: string[] = []; const folders: string[] = [];
let totalBytes = 0; let totalBytes = 0;
const pending = [source]; const pending = [source];
while (pending.length) { while (pending.length) {
const folder = pending.pop()!; const folder = pending.pop()!;
for (const entry of await readdir(folder, { withFileTypes: true })) { const entries = await fsPromises.readdir(folder, { withFileTypes: true });
if (folder !== source) {
// Skip any WTOffline Launcher folder that was previously extracted inside the game directory.
if (isLauncherFolder(entries)) continue;
folders.push(relative(source, folder));
}
for (const entry of entries) {
const path = join(folder, entry.name); const path = join(folder, entry.name);
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue; if (folder === source && isInSkippedSourceFolder(entry.name)) continue;
const relPath = relative(source, path);
if (isPathInUhqPacks(relPath, skippedUhq)) continue;
if (entry.isDirectory()) { if (entry.isDirectory()) {
folders.push(relative(source, path));
pending.push(path); pending.push(path);
} else if (entry.isFile()) { } else if (entry.isFile()) {
const { size, mtimeMs } = await lstat(path); const { size, mtimeMs } = await fsPromises.lstat(path);
files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs }); files.push({ relativePath: relPath, bytes: size, modifiedAt: mtimeMs });
totalBytes += size; totalBytes += size;
} }
} }
@@ -78,16 +129,25 @@ export async function copyPlannedFiles(
onProgress: (progress: CopyProgress) => void, onProgress: (progress: CopyProgress) => void,
hardlinks?: ReadonlyMap<string, BigIntStats>, hardlinks?: ReadonlyMap<string, BigIntStats>,
): Promise<void> { ): Promise<void> {
await mkdir(target, { recursive: true }); const fs = rawFs();
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true }); const fsPromises = fs.promises;
await fsPromises.mkdir(target, { recursive: true });
for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true });
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined; const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
let next = 0; let next = 0;
let doneBytes = 0; let copiedBytes = 0;
let linkedBytes = 0;
let linkedFiles = 0;
let doneFiles = 0; let doneFiles = 0;
const emitProgress = (): void => {
// Keep doneBytes aligned with actual bytes written to disk so hard-linked files
// do not inflate copy progress.
onProgress({ doneBytes: copiedBytes, doneFiles, copiedBytes, linkedBytes, linkedFiles });
};
const countBytes = (): Transform => new Transform({ const countBytes = (): Transform => new Transform({
transform(chunk: Buffer, _encoding, callback) { transform(chunk: Buffer, _encoding, callback) {
doneBytes += chunk.length; copiedBytes += chunk.length;
onProgress({ doneBytes, doneFiles }); emitProgress();
callback(null, chunk); callback(null, chunk);
}, },
}); });
@@ -95,6 +155,8 @@ export async function copyPlannedFiles(
// caller cleaning up after an error never races a copy still writing. // caller cleaning up after an error never races a copy still writing.
const stop = new AbortController(); const stop = new AbortController();
const stopSignal = AbortSignal.any([signal, stop.signal]); const stopSignal = AbortSignal.any([signal, stop.signal]);
let firstError: unknown = null;
let hasError = false;
const copyNext = async (): Promise<void> => { const copyNext = async (): Promise<void> => {
try { try {
while (next < plan.files.length) { while (next < plan.files.length) {
@@ -106,33 +168,39 @@ export async function copyPlannedFiles(
if (verified) { if (verified) {
const linked = await linkVerifiedResource(from, to, verified); const linked = await linkVerifiedResource(from, to, verified);
linkedTargets?.set(to, linked); linkedTargets?.set(to, linked);
doneBytes += file.bytes; linkedBytes += file.bytes;
linkedFiles += 1;
} else { } else {
await pipeline( await pipeline(
createReadStream(from), fs.createReadStream(from),
countBytes(), countBytes(),
// 'wx': fail instead of overwriting a file that is already there. // 'wx': fail instead of overwriting a file that is already there.
createWriteStream(to, { flags: 'wx' }), fs.createWriteStream(to, { flags: 'wx' }),
{ signal: stopSignal }, { signal: stopSignal },
); );
const modified = new Date(file.modifiedAt); const modified = new Date(file.modifiedAt);
await utimes(to, modified, modified); await fsPromises.utimes(to, modified, modified);
} }
doneFiles += 1; doneFiles += 1;
onProgress({ doneBytes, doneFiles }); emitProgress();
} }
} catch (error) { } catch (error) {
if (!hasError && !stop.signal.aborted && !signal.aborted) {
hasError = true;
firstError = error;
}
stop.abort(error); stop.abort(error);
throw error; throw error;
} }
}; };
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext)); const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
if (hasError) throw firstError;
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected'); const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failed) throw failed.reason; if (failed) throw failed.reason;
if (linkedTargets) { if (linkedTargets) {
for (const [path, stamp] of linkedTargets) { for (const [path, stamp] of linkedTargets) {
signal.throwIfAborted(); signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed'); if (!sameResource(stamp, await fsPromises.lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
} }
} }
} }
@@ -142,9 +210,10 @@ export async function copyPlannedFiles(
* when the copy started, so everything in it came from the copy. * when the copy started, so everything in it came from the copy.
*/ */
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> { export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
const fsPromises = rawFs().promises;
if (!targetExisted) { if (!targetExisted) {
await rm(target, { recursive: true, force: true }); await fsPromises.rm(target, { recursive: true, force: true });
return; return;
} }
for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true }); for (const entry of await fsPromises.readdir(target)) await fsPromises.rm(join(target, entry), { recursive: true, force: true });
} }
@@ -1,6 +1,31 @@
import { readdir } from 'node:fs/promises'; import { readdir } from 'node:fs/promises';
import { join } from 'node:path'; import { dirname, join } from 'node:path';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { DataFolderProblem } from '@shared/schemas/install.ts';
import { copyPathContains } from './install-record.ts';
import { STOCK_BACKUP_FOLDER } from './stock-backup.ts';
/**
* Validate where the offline data folder sits relative to the client and stock folders.
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
* client folder itself or an ancestor of it would mix game files into the data root.
*/
export function dataFolderProblem(
dataPath: string,
copyPath: string | null,
sourcePath: string | null,
externalStockPath: string | null,
): DataFolderProblem | null {
if (copyPath && (copyPathContains(dataPath, copyPath) ||
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
return 'overlaps_client';
}
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
return 'overlaps_stock';
}
return null;
}
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */ /** A data tree must keep the server's saves, logs and caches inside the selected folder. */
export async function requireUnredirectedData(root: string): Promise<void> { export async function requireUnredirectedData(root: string): Promise<void> {
@@ -1,7 +1,12 @@
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises'; import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path'; import { dirname, isAbsolute, join, relative } from 'node:path';
import { isInSteamLibrary, playerDecalCacheProblem } from '@wto/patcher'; import {
isInSteamLibrary,
playerDecalCacheProblem,
resolvePlayerDecalCacheFolder,
writeDecalCacheIndexSnapshot,
} from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { Copies } from '@shared/schemas/install.ts'; import type { Copies } from '@shared/schemas/install.ts';
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts'; import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
@@ -17,6 +22,25 @@ export function decalCachePath(dataPath: string, cacheId: string): string {
return join(dataPath, CACHE_FOLDER, cacheId); return join(dataPath, CACHE_FOLDER, cacheId);
} }
/**
* Read-only check whether a player-chosen or registered folder contains a usable decal cache
* (<game>, <game>/cache, or <game>/cache/content). Returns the canonical cache/content path when
* valid, or null when absent, invalid, or unreadable.
*/
export async function detectDecalCacheSource(folderPath: string): Promise<string | null> {
if (!folderPath || !isAbsolute(folderPath)) return null;
try {
const rawSource = await realpath(folderPath).catch(() => null);
if (!rawSource) return null;
const resolved = resolvePlayerDecalCacheFolder(rawSource);
const canonical = await realpath(resolved).catch(() => null);
if (!canonical) return null;
return playerDecalCacheProblem(canonical) === undefined ? canonical : null;
} catch {
return null;
}
}
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> { async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed'); if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
const data = await canonicalCopyPath(dataPath); const data = await canonicalCopyPath(dataPath);
@@ -33,8 +57,13 @@ export async function importDecalCache(
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false, dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
): Promise<string> { ): Promise<string> {
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid'); if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
const source = await realpath(sourcePath).catch(() => null); const rawSource = await realpath(sourcePath).catch(() => null);
if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid'); const source = rawSource ? await realpath(resolvePlayerDecalCacheFolder(rawSource)).catch(() => null) : null;
const problem = source ? playerDecalCacheProblem(source) : 'selected folder could not be resolved';
if (!source || problem) {
console.warn('[decals] invalid decal cache source:', sourcePath, '->', problem);
throw new AppError('decal_source_invalid');
}
const root = await cacheRoot(dataPath, steamDataConfirmed); const root = await cacheRoot(dataPath, steamDataConfirmed);
if (copyPathContains(source, root) || copyPathContains(root, source)) { if (copyPathContains(source, root) || copyPathContains(root, source)) {
@@ -56,7 +85,12 @@ export async function importDecalCache(
}, },
}); });
signal?.throwIfAborted(); signal?.throwIfAborted();
if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid'); writeDecalCacheIndexSnapshot(source, target);
const copiedProblem = playerDecalCacheProblem(target);
if (copiedProblem) {
console.warn('[decals] copied decal cache failed validation:', copiedProblem);
throw new AppError('decal_source_invalid');
}
return id; return id;
} catch (error) { } catch (error) {
await discardDecalCache(dataPath, id, steamDataConfirmed); await discardDecalCache(dataPath, id, steamDataConfirmed);
@@ -1,7 +1,11 @@
import { createHash } from 'node:crypto'; import { createHash } from 'node:crypto';
import { createReadStream, type BigIntStats } from 'node:fs'; import { createReadStream, type BigIntStats } from 'node:fs';
import { link, lstat } from 'node:fs/promises'; import { link, lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { isHardlinkableResource } from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { InstallProgress } from '@shared/schemas/install.ts';
import type { CopyPlan } from './copy-game.ts';
export type ResourceMatchResult = export type ResourceMatchResult =
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats } | { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
@@ -83,3 +87,27 @@ function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean
return right.isFile() && left.dev === right.dev && left.ino === right.ino && return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
left.size === right.size && left.mtimeNs === right.mtimeNs; left.size === right.size && left.mtimeNs === right.mtimeNs;
} }
/** Collect and stat every eligible read-only resource pack in `plan` before hard-linking. */
export async function prepareHardlinks(
source: string,
plan: CopyPlan,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<ReadonlyMap<string, BigIntStats>> {
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
const links = new Map<string, BigIntStats>();
let doneBytes = 0;
let doneFiles = 0;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
for (const file of candidates) {
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
if (verified) links.set(file.relativePath, verified);
doneBytes += file.bytes;
doneFiles += 1;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
}
if (!links.size) throw new AppError('hardlink_no_match');
return links;
}
@@ -1,18 +1,21 @@
import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises'; import { access, mkdir } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path'; import { dirname, isAbsolute, relative } from 'node:path';
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher'; import { app } from 'electron';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts'; import { AppError } from '@shared/errors.ts';
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; import type { ClientOrigin, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts'; import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts'; import { readClientMarker, writeClientMarker } from './client-marker.ts';
import { requireUnredirectedData } from './data-location.ts'; import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
import { dataFolderProblem, requireUnredirectedData } from './data-location.ts';
import { discardDecalCache, importDecalCache } from './decals.ts'; import { discardDecalCache, importDecalCache } from './decals.ts';
import { statHardlinkResource } from './hardlink-files.ts'; import { prepareHardlinks } from './hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts'; import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts'; import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts'; import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation } from './stock-backup.ts';
export { dataFolderProblem } from './data-location.ts';
/** /**
* Install the offline version: check the patches against the player's game, * Install the offline version: check the patches against the player's game,
@@ -100,6 +103,16 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
? await refreshStockBackup(copyPath) ? await refreshStockBackup(copyPath)
: await backUpStockFiles(copyPath); : await backUpStockFiles(copyPath);
// Record launcher-created client origin on disk; never overwrite or fabricate a marker for existing folders.
let detectedOrigin: ClientOrigin | undefined;
if (request.method === 'copy') {
await writeClientMarker(copyPath, useHardLinks ? 'hardlink' : 'copy');
} else if (request.method === 'in-place') {
await writeClientMarker(copyPath, 'in-place');
} else {
detectedOrigin = (await readClientMarker(copyPath))?.origin;
}
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const record: InstallRecord = { const record: InstallRecord = {
id: request.id, id: request.id,
@@ -115,6 +128,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
installedAt: new Date().toISOString(), installedAt: new Date().toISOString(),
lastCheckedAt: new Date().toISOString(), lastCheckedAt: new Date().toISOString(),
...(decalCacheId ? { decalCacheId } : {}), ...(decalCacheId ? { decalCacheId } : {}),
...(detectedOrigin ? { detectedOrigin } : {}),
...copied, ...copied,
}; };
await writeInstallRecord(record); await writeInstallRecord(record);
@@ -140,6 +154,12 @@ async function inspectInstallation(request: InstallRequest) {
const [copyPath, dataPath, sourcePath] = await Promise.all([ const [copyPath, dataPath, sourcePath] = await Promise.all([
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder), canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
]); ]);
if (request.method === 'copy' && app.isPackaged) {
const launcherDir = await canonicalCopyPath(dirname(process.execPath));
if (copyPathContains(sourcePath, launcherDir)) {
throw new AppError('launcher_inside_source');
}
}
await requireAvailableCopy(request.id, copyPath, dataPath); await requireAvailableCopy(request.id, copyPath, dataPath);
const dataProblem = dataFolderProblem( const dataProblem = dataFolderProblem(
dataPath, dataPath,
@@ -169,28 +189,6 @@ async function inspectInstallation(request: InstallRequest) {
return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam }; return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, externalStockPath, target, useHardLinks, copyInSteam, dataInSteam };
} }
/**
* Validate where the offline data folder sits relative to the client and stock folders.
* A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the
* client folder itself or an ancestor of it would mix game files into the data root.
*/
export function dataFolderProblem(
dataPath: string,
copyPath: string | null,
sourcePath: string | null,
externalStockPath: string | null,
): DataFolderProblem | null {
if (copyPath && (copyPathContains(dataPath, copyPath) ||
copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) {
return 'overlaps_client';
}
if ((sourcePath && copyPathContains(sourcePath, dataPath)) ||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
return 'overlaps_stock';
}
return null;
}
async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) { async function resolveExternalStockSource(stockSourcePath: string, expectedVersion: string | null) {
const stockGame = await requireGameFolder(stockSourcePath); const stockGame = await requireGameFolder(stockSourcePath);
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid'); if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
@@ -212,8 +210,10 @@ async function copyGame(
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source); const plan = await planCopy(source);
const hardlinks = useHardLinks ? await prepareHardlinks(source, plan, signal, report) : undefined; const hardlinks = useHardLinks ? await prepareHardlinks(source, plan, signal, report) : undefined;
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0; const linkTotalBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES; const linkTotalFiles = hardlinks ? hardlinks.size : 0;
const copyTotalBytes = Math.max(0, plan.totalBytes - linkTotalBytes);
const neededBytes = copyTotalBytes + SPARE_BYTES;
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) { if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
throw new AppError('hardlink_file_changed'); throw new AppError('hardlink_file_changed');
} }
@@ -222,11 +222,26 @@ async function copyGame(
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) }); throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
} }
const targetExisted = await exists(target); const targetExisted = await exists(target);
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length }; // Track actual disk-copy bytes in doneBytes/totalBytes so hard-linked resource archives
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals }); // do not inflate the progress bar or cause sudden jumps when links are created.
const totals = {
totalBytes: copyTotalBytes > 0 ? copyTotalBytes : plan.files.length,
totalFiles: plan.files.length,
copyTotalBytes,
...(hardlinks ? { linkTotalBytes, linkTotalFiles } : {}),
};
const toProgress = (done: { doneFiles: number; copiedBytes: number; linkedBytes: number; linkedFiles: number }): InstallProgress => ({
phase: 'copying',
doneBytes: copyTotalBytes > 0 ? done.copiedBytes : done.doneFiles,
doneFiles: done.doneFiles,
copiedBytes: done.copiedBytes,
...(hardlinks ? { linkedBytes: done.linkedBytes, linkedFiles: done.linkedFiles } : {}),
...totals,
});
report(toProgress({ doneFiles: 0, copiedBytes: 0, linkedBytes: 0, linkedFiles: 0 }));
try { try {
await copyPlannedFiles(source, target, plan, signal, await copyPlannedFiles(source, target, plan, signal,
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks); (done) => report(toProgress(done)), hardlinks);
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed'); if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
return { return {
sourceFiles: plan.files.map((file) => file.relativePath), sourceFiles: plan.files.map((file) => file.relativePath),
@@ -241,29 +256,6 @@ async function copyGame(
} }
} }
async function prepareHardlinks(
source: string,
plan: CopyPlan,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<ReadonlyMap<string, BigIntStats>> {
const candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
const totalBytes = candidates.reduce((total, file) => total + file.bytes, 0);
const links = new Map<string, BigIntStats>();
let doneBytes = 0;
let doneFiles = 0;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
for (const file of candidates) {
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
if (verified) links.set(file.relativePath, verified);
doneBytes += file.bytes;
doneFiles += 1;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
}
if (!links.size) throw new AppError('hardlink_no_match');
return links;
}
async function requireGameFolder(path: string) { async function requireGameFolder(path: string) {
const game = await inspectGameFolder(path); const game = await inspectGameFolder(path);
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path }); if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
@@ -0,0 +1,104 @@
import { join, normalize } from 'node:path';
import { rawFs } from '../../util/raw-fs.ts';
/**
* Detection of incomplete optional UHQ texture packs (`uhq_vehicles`, `uhq_aircraft`,
* `uhq_environment`, etc.) inside a War Thunder folder.
*
* War Thunder writes `content/pkg_<name>.rq2` when an optional pack is requested and only writes
* `content/pkg_<name>.ver` once its download finishes (`PACKAGE_STATUS_OK`). However, at startup
* `aces.exe` mounts `content.hq/<name>/res/grp_hdr.vromfs.bin` without requiring the `.ver` file,
* registering every `.dxp.bin` listed in the header and crashing later with fatal error 81110007
* (`Can't open TexPack`) if any texture pack is missing.
*/
const UHQ_PACK_PATTERN = /^uhq_[a-z0-9_]+$/i;
const UHQ_RQ2_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.rq2$/i;
const UHQ_VER_PATTERN = /^pkg_(uhq_[a-z0-9_]+)\.ver$/i;
export interface IncompleteUhqPack {
readonly name: string;
readonly hasHeader: boolean;
}
/**
* Inspects `root` for optional UHQ packs that are incomplete:
* - `content/pkg_<name>.rq2` exists without `content/pkg_<name>.ver` (`PACKAGE_STATUS_REQUESTED`), or
* - `content.hq/<name>/res/grp_hdr.vromfs.bin` exists with no `.dxp.bin` texture packs beside it.
*/
export async function inspectIncompleteUhqPacks(root: string): Promise<IncompleteUhqPack[]> {
const rq2Packs = new Set<string>();
const verPacks = new Set<string>();
const candidates = new Set<string>();
for (const name of await readDirNames(join(root, 'content'))) {
const rq2 = UHQ_RQ2_PATTERN.exec(name);
if (rq2) {
const pack = rq2[1]!.toLowerCase();
rq2Packs.add(pack);
candidates.add(pack);
continue;
}
const ver = UHQ_VER_PATTERN.exec(name);
if (ver) verPacks.add(ver[1]!.toLowerCase());
}
for (const name of await readDirNames(join(root, 'content.hq'))) {
if (UHQ_PACK_PATTERN.test(name)) candidates.add(name.toLowerCase());
}
const incomplete: IncompleteUhqPack[] = [];
for (const pack of [...candidates].sort()) {
const resDir = join(root, 'content.hq', pack, 'res');
const resFiles = await readDirNames(resDir);
const hasHeader = resFiles.some((file) => file.toLowerCase() === 'grp_hdr.vromfs.bin');
const hasDxp = resFiles.some((file) => file.toLowerCase().endsWith('.dxp.bin'));
const requestedWithoutVer = rq2Packs.has(pack) && !verPacks.has(pack);
const emptyHeaderOnly = hasHeader && !hasDxp;
if (requestedWithoutVer || emptyHeaderOnly) {
incomplete.push({ name: pack, hasHeader });
}
}
return incomplete;
}
/** Names of all incomplete optional UHQ packs in `root`. */
export async function findIncompleteUhqPacks(root: string): Promise<string[]> {
return (await inspectIncompleteUhqPacks(root)).map((pack) => pack.name);
}
/**
* Names of incomplete optional UHQ packs in `root` whose `grp_hdr.vromfs.bin` is present,
* which causes `aces.exe` to mount the pack and fail with 81110007 when streaming textures.
*/
export async function findBlockingIncompleteUhqPacks(root: string): Promise<string[]> {
return (await inspectIncompleteUhqPacks(root))
.filter((pack) => pack.hasHeader)
.map((pack) => pack.name);
}
/**
* Whether `relativePath` (relative to the War Thunder root) belongs to any UHQ pack in `packs`:
* `content.hq/<pack>/...`, `patch/content.hq/<pack>/...`, or `content/pkg_<pack>.rq2`.
*/
export function isPathInUhqPacks(relativePath: string, packs: ReadonlySet<string>): boolean {
if (packs.size === 0) return false;
const parts = normalize(relativePath).replace(/\\/g, '/').toLowerCase().split('/').filter(Boolean);
if (parts.length >= 2 && parts[0] === 'content.hq') return packs.has(parts[1]!);
if (parts.length >= 3 && parts[0] === 'patch' && parts[1] === 'content.hq') return packs.has(parts[2]!);
if (parts.length === 2 && parts[0] === 'content') {
const rq2 = UHQ_RQ2_PATTERN.exec(parts[1]!);
return rq2 !== null && packs.has(rq2[1]!);
}
return false;
}
async function readDirNames(folder: string): Promise<string[]> {
try {
const fsPromises = rawFs().promises;
await fsPromises.access(folder);
return await fsPromises.readdir(folder);
} catch {
return [];
}
}
@@ -11,6 +11,8 @@ import type { Settings } from '@shared/schemas/settings.ts';
import { getSettings } from '../config/settings-store.ts'; import { getSettings } from '../config/settings-store.ts';
import { decalCachePath } from '../install/decals.ts'; import { decalCachePath } from '../install/decals.ts';
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts'; import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { findBlockingIncompleteUhqPacks } from '../install/uhq-packages.ts';
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
import { resourcePaths } from '../resources/resource-paths.ts'; import { resourcePaths } from '../resources/resource-paths.ts';
import { saveBackup } from '../saves/save-archive.ts'; import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts'; import { buildCopy } from './build-copy.ts';
@@ -67,10 +69,14 @@ export function startLaunch(report: LaunchJob['report']): LaunchState {
case 'launch_server_exited': case 'launch_server_exited':
update(job, { phase: 'server-exited', ...context }); update(job, { phase: 'server-exited', ...context });
break; break;
default: default: {
update(job, { phase: 'failed', error: code, ...context }); const errorParams = error instanceof AppError && Object.keys(error.params).length > 0
? { errorParams: { ...error.params } }
: {};
update(job, { phase: 'failed', error: code, ...errorParams, ...context });
break; break;
} }
}
}).finally(() => { }).finally(() => {
if (active === job) active = null; if (active === job) active = null;
}); });
@@ -108,7 +114,7 @@ async function launch(job: LaunchJob): Promise<void> {
job.copyId = record.id; job.copyId = record.id;
const plan = await planLaunch(job, record, settings); const plan = await planLaunch(job, record, settings);
if (plan === null) return; if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port } = plan; const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
await buildForLaunch(job, record, plan, settings); await buildForLaunch(job, record, plan, settings);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => { const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
@@ -123,7 +129,15 @@ async function launch(job: LaunchJob): Promise<void> {
update(job, { phase: 'ready' }); update(job, { phase: 'ready' });
return; return;
} }
const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish); const gameExit = await runOrdinaryLaunch(
copyPath,
dataPath,
port,
settings,
signal,
publish,
{ modsDir, enabledModIds },
);
update(job, { phase: 'game-exited', gameExit }); update(job, { phase: 'game-exited', gameExit });
} }
@@ -134,6 +148,8 @@ interface LaunchPlan {
readonly dataPath: string; readonly dataPath: string;
readonly steamLibraryConfirmed: boolean; readonly steamLibraryConfirmed: boolean;
readonly port: number; readonly port: number;
readonly modsDir: string;
readonly enabledModIds: readonly string[];
} }
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> { async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
@@ -183,13 +199,20 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version'); throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
} }
if (games) throw new AppError('launch_game_running'); if (games) throw new AppError('launch_game_running');
const incompleteUhq = await findBlockingIncompleteUhqPacks(copyPath);
if (incompleteUhq.length > 0) {
console.warn(`[launch] incomplete optional UHQ pack(s) detected in ${copyPath}: ${incompleteUhq.join(', ')}`);
throw new AppError('launch_incomplete_uhq_packs', { packs: incompleteUhq.join(', ') });
}
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
const port = await selectPort(requestedPort); const port = await selectPort(requestedPort);
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port }; return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
} }
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> { async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
const signal = job.stop.signal; const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan; const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
if (settings.autoSaveBackups) { if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) { for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted(); signal.throwIfAborted();
@@ -211,6 +234,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}), ...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled, hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
modsDir,
enabledModIds,
}, signal, (filesWritten, filesTotal, file) => { }, signal, (filesWritten, filesTotal, file) => {
writtenFiles = filesWritten; writtenFiles = filesWritten;
if (!signal.aborted) update(job, { if (!signal.aborted) update(job, {
@@ -33,13 +33,22 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
} }
} }
export interface StartLocalServerOptions extends Omit<ServerOptions, 'report' | 'mods'> {
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
}
export async function startLocalServer( export async function startLocalServer(
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal, { gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal,
): Promise<LocalServer> { ): Promise<LocalServer> {
signal.throwIfAborted(); signal.throwIfAborted();
const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'];
if (modsDir && enabledModIds && enabledModIds.length > 0) {
workerArgs.push(modsDir, JSON.stringify(enabledModIds));
}
const worker = utilityProcess.fork( const worker = utilityProcess.fork(
join(import.meta.dirname, 'server-worker.js'), join(import.meta.dirname, 'server-worker.js'),
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'], workerArgs,
{ {
serviceName: 'WTOffline local server', serviceName: 'WTOffline local server',
stdio: 'pipe', stdio: 'pipe',
@@ -45,12 +45,19 @@ type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-r
export async function runOrdinaryLaunch( export async function runOrdinaryLaunch(
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal, copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void, publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void,
mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] },
): Promise<GameExit> { ): Promise<GameExit> {
const args = parseLaunchArguments(settings.launchArguments); const args = parseLaunchArguments(settings.launchArguments);
if (!args) throw new AppError('launch_game_failed'); if (!args) throw new AppError('launch_game_failed');
publish('starting-server'); publish('starting-server');
const server = await startLocalServer( const server = await startLocalServer(
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled }, {
gameFolder: copyPath,
dataFolder: dataPath,
port,
loggingEnabled: settings.loggingEnabled,
...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}),
},
signal, signal,
); );
const stop = new AbortController(); const stop = new AbortController();
@@ -0,0 +1,436 @@
import { randomUUID } from 'node:crypto';
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { app, BrowserWindow, dialog, shell } from 'electron';
import {
computeAutoSortOrder,
discoverMods,
emptyClientModsConfig,
MOD_API_VERSION,
normalizeClientModsConfig,
resolveModLoadOrder,
type ClientModsConfig,
type DiscoveredMod,
type ModPreset,
} from '@wto/mods';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { getSettings, updateSettings } from '../config/settings-store.ts';
import { listCopies } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
const CLIENT_MODS_CONFIG_FILE = 'mods-config.json';
const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded';
const inFlightSeeds = new Map<string, Promise<void>>();
export function defaultModsFolder(): string {
return join(app.getPath('userData'), 'mods');
}
export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> {
const settings = await getSettings();
const defaultModsDir = defaultModsFolder();
const isCustomModsDir = settings.modsFolder !== null;
const modsDir = settings.modsFolder ?? defaultModsDir;
await mkdir(modsDir, { recursive: true });
await seedBundledExampleModsOnce(modsDir);
return { modsDir, defaultModsDir, isCustomModsDir };
}
/**
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
* deleting a bundled template never restores it, while newly added official templates still
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
*/
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
const key = modsDir.toLowerCase();
const pending = inFlightSeeds.get(key);
if (pending) {
await pending;
return;
}
const task = (async () => {
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
try {
const templatesRoot = resourcePaths().modTemplates;
if (!(await pathExists(templatesRoot))) return;
const seeded = await readSeededTemplateNames(markerPath, modsDir);
const templates = await readdir(templatesRoot, { withFileTypes: true });
let changed = false;
for (const entry of templates) {
if (!entry.isDirectory()) continue;
if (seeded.has(entry.name)) continue;
const dest = join(modsDir, entry.name);
if (!(await pathExists(dest))) {
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
}
seeded.add(entry.name);
changed = true;
}
if (changed || !(await pathExists(markerPath))) {
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
}
} catch (error) {
console.warn('[mods] seeding bundled example mods skipped:', error);
}
})().finally(() => {
inFlightSeeds.delete(key);
});
inFlightSeeds.set(key, task);
await task;
}
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
if (!(await pathExists(markerPath))) return new Set();
try {
const raw = (await readFile(markerPath, 'utf8')).trim();
if (raw === '1') {
// Legacy marker from initial 2-template version: mark existing folders as already seeded
// so newly added official templates (e.g. official-map-selector) are still delivered once.
const existing = await readdir(modsDir);
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
for (const name of existing) set.add(name);
return set;
}
const parsed = JSON.parse(raw) as { seeded?: unknown };
if (Array.isArray(parsed.seeded)) {
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
}
} catch { /* ignore */ }
return new Set();
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
export async function openModsFolder(): Promise<void> {
const { modsDir } = await resolveModsFolder();
const failure = await shell.openPath(modsDir);
if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure);
}
export async function getModsState(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next: ClientModsConfig = {
...current,
activePresetId: null,
enabled: { ...current.enabled, [modId]: enabled },
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function setModsOrder(copyId: string, order: readonly string[]): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function autoSortMods(copyId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const sortedOrder = computeAutoSortOrder(discovered.mods, current.order);
const next: ClientModsConfig = {
...current,
activePresetId: null,
order: sortedOrder,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const now = new Date().toISOString();
let presets: ModPreset[];
let presetId: string;
if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) {
presetId = overwriteId;
presets = current.presets.map((preset) => (
preset.id === overwriteId
? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }
: preset
));
} else {
presetId = randomUUID();
presets = [
...current.presets,
{ id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now },
];
}
const next: ClientModsConfig = {
...current,
activePresetId: presetId,
presets,
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function applyModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const next = normalizeClientModsConfig({
...current,
order: preset.order,
enabled: preset.enabled,
activePresetId: preset.id,
}, discovered.mods);
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function deleteModPreset(copyId: string, presetId: string): Promise<ModsStateView> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const next: ClientModsConfig = {
...current,
activePresetId: current.activePresetId === presetId ? null : current.activePresetId,
presets: current.presets.filter((preset) => preset.id !== presetId),
};
await writeClientModsConfig(copy.dataPath, next);
return buildModsStateView(copy, next);
}
export async function exportModPreset(
copyId: string,
presetId: string,
window: BrowserWindow | null,
): Promise<{ readonly path: string | null }> {
const copy = await requireCopy(copyId);
const current = await readClientModsConfig(copy.dataPath);
const preset = current.presets.find((item) => item.id === presetId);
if (!preset) throw new AppError('mods_preset_invalid');
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
const defaultDir = await resolveDialogDefaultPath('mod-preset');
const fileName = `${safeName}.wto-mods-preset.json`;
const dialogOptions = {
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
? await dialog.showSaveDialog(window, dialogOptions)
: await dialog.showSaveDialog(dialogOptions);
if (choice.canceled || !choice.filePath) return { path: null };
const payload = {
format: 1 as const,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
};
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
await rememberDialogPath('mod-preset', choice.filePath);
return { path: choice.filePath };
}
export async function importModPreset(
copyId: string,
window: BrowserWindow | null,
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
const copy = await requireCopy(copyId);
const defaultPath = await resolveDialogDefaultPath('mod-preset');
const dialogOptions = {
properties: ['openFile'] as Array<'openFile'>,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
...(defaultPath ? { defaultPath } : {}),
};
const choice = window
? await dialog.showOpenDialog(window, dialogOptions)
: await dialog.showOpenDialog(dialogOptions);
if (choice.canceled || !choice.filePaths[0]) {
return { imported: false, state: await buildModsStateView(copy) };
}
await rememberDialogPath('mod-preset', choice.filePaths[0]);
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown;
} catch {
throw new AppError('mods_preset_invalid');
}
const validated = ModPresetTransferSchema.safeParse(parsedRaw);
if (!validated.success) throw new AppError('mods_preset_invalid');
const current = await readClientModsConfig(copy.dataPath);
const newPreset: ModPreset = {
id: randomUUID(),
name: validated.data.name,
order: validated.data.order,
enabled: validated.data.enabled,
updatedAt: new Date().toISOString(),
};
const next: ClientModsConfig = {
...current,
presets: [...current.presets, newPreset],
};
await writeClientModsConfig(copy.dataPath, next);
return { imported: true, state: await buildModsStateView(copy, next) };
}
export async function setModsFolder(copyId: string, folderPath: string | null): Promise<ModsStateView> {
if (folderPath !== null) {
if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid');
try {
await mkdir(folderPath, { recursive: true });
const info = await stat(folderPath);
if (!info.isDirectory()) throw new AppError('mods_folder_invalid');
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError('mods_folder_invalid');
}
}
await updateSettings({ modsFolder: folderPath });
if (folderPath !== null) await rememberDialogPath('mods-folder', folderPath);
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */
export async function resolveEnabledModsForLaunch(
dataPath: string,
gameVersion: string | null,
): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> {
const { modsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion);
if (resolved.hasBlockingErrors) {
console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error'));
throw new AppError('mods_blocking_issues');
}
return { modsDir, enabledMods: resolved.enabledMods };
}
async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise<ModsStateView> {
const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder();
const discovered = discoverMods(modsDir);
const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath);
const config = normalizeClientModsConfig(rawConfig, discovered.mods);
const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const orderedMods: ModListItem[] = config.order
.map((id) => byId.get(id))
.filter((mod): mod is DiscoveredMod => mod !== undefined)
.map(toModListItem);
return {
modsDir,
defaultModsDir,
isCustomModsDir,
apiVersion: MOD_API_VERSION,
mods: orderedMods,
discoveryErrors: [...discovered.errors],
order: [...config.order],
enabled: { ...config.enabled },
activePresetId: config.activePresetId,
presets: config.presets.map((preset) => ({
id: preset.id,
name: preset.name,
order: [...preset.order],
enabled: { ...preset.enabled },
updatedAt: preset.updatedAt,
})),
issues: [...resolved.issues],
hasBlockingErrors: resolved.hasBlockingErrors,
};
}
function toModListItem(mod: DiscoveredMod): ModListItem {
return {
id: mod.manifest.id,
folderName: mod.folderName,
rootDir: mod.rootDir,
name: mod.manifest.name,
...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}),
version: mod.manifest.version,
author: mod.manifest.author,
apiVersion: mod.manifest.apiVersion,
gameVersions: [...mod.manifest.gameVersions],
requires: [...mod.manifest.requires],
conflicts: [...mod.manifest.conflicts],
loadAfter: [...mod.manifest.loadAfter],
loadBefore: [...mod.manifest.loadBefore],
badges: [...mod.content.badges],
hasServerScript: mod.content.serverEntry !== undefined,
serverTuningFiles: [...mod.content.serverTuningFiles],
packOperations: [...mod.content.packOperations],
guiPatchCount: mod.content.guiPatchDirs.length,
exePatchCount: mod.content.exePatchDirs.length,
hasClientAddon: mod.content.hasClientAddon,
addonFileCount: mod.content.addonRelativeFiles.length,
clientFileCount: mod.content.clientFiles.length,
hasConfigBlkPatch: mod.content.configBlkPatch !== undefined,
};
}
async function requireCopy(copyId: string): Promise<InstallRecord> {
const copies = await listCopies();
const copy = copies.copies.find((entry) => entry.id === copyId);
if (!copy) throw new AppError('copy_not_found');
return copy;
}
async function readClientModsConfig(dataPath: string): Promise<ClientModsConfig> {
const path = join(dataPath, CLIENT_MODS_CONFIG_FILE);
try {
const raw = await readJsonOr(path, null);
if (!raw || typeof raw !== 'object') return emptyClientModsConfig();
const obj = raw as Partial<ClientModsConfig>;
return {
format: 1,
order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [],
enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {},
activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null,
presets: Array.isArray(obj.presets) ? obj.presets : [],
};
} catch (error) {
console.warn('[mods] unreadable client mods config, using defaults:', path, error);
return emptyClientModsConfig();
}
}
async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise<void> {
try {
await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config);
} catch (error) {
console.error('[mods] writing client mods config failed:', error);
throw new AppError('mods_write_failed');
}
}
@@ -1,6 +1,6 @@
/** /**
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list. * The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
* The project repository is tried first, with an optional player-configured fallback. * The primary release source is tried first, followed by any player-configured mirror and default fallbacks.
*/ */
import { net } from 'electron'; import { net } from 'electron';
import { import {
@@ -62,6 +62,7 @@ export class ReleasePageLimitError extends Error {
} }
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
const MAX_RELEASE_NOTES_CHARS = 64 * 1024;
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() }); const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
const LauncherReleaseEntry = z.object({ const LauncherReleaseEntry = z.object({
draft: z.literal(false), draft: z.literal(false),
@@ -98,19 +99,36 @@ export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
export async function withReleaseSources<T>( export async function withReleaseSources<T>(
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource, read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
): Promise<T> { ): Promise<T> {
const primary = releaseSource(new URL(`https://github.com/${patchPackTuning().repository}`)); const tuning = patchPackTuning();
const repository = releaseRepositoryUrl((await getSettings()).updateMirrorUrl); const candidates: ReleaseSource[] = [];
const mirror = repository ? releaseSource(repository) : null; const add = (url: URL | null): void => {
if (!mirror || sameReleaseSource(primary, mirror)) return read(primary); if (!url) return;
const [first, second] = preferred && sameReleaseSource(preferred, mirror) ? [mirror, primary] : [primary, mirror]; const source = releaseSource(url);
if (!candidates.some((existing) => sameReleaseSource(existing, source))) candidates.push(source);
};
add(releaseRepositoryUrl(tuning.primarySource));
add(releaseRepositoryUrl((await getSettings()).updateMirrorUrl));
for (const fallback of tuning.fallbackSources) add(releaseRepositoryUrl(fallback));
if (candidates.length === 0) throw new FeedUnreachableError('No valid release sources are configured.');
const ordered = preferred
? [preferred, ...candidates.filter((source) => !sameReleaseSource(source, preferred))]
: candidates;
let lastError: unknown;
for (let index = 0; index < ordered.length; index += 1) {
const current = ordered[index]!;
try { try {
return await read(first); return await read(current);
} catch (error) { } catch (error) {
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error; if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
console.info(`[release-feed] ${first.feed.hostname} was unavailable, trying ${second.feed.hostname}.`); lastError = error;
return read(second); const next = ordered[index + 1];
if (next) console.info(`[release-feed] ${current.feed.hostname} was unavailable, trying ${next.feed.hostname}.`);
} }
} }
throw lastError;
}
function listingFor(source: ReleaseSource): Promise<ReleaseListing> { function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
const key = source.feed.href; const key = source.feed.href;
@@ -248,7 +266,7 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
return { return {
source, source,
version, version,
notes: body?.trim().slice(0, 1600) ?? '', notes: body?.trim().slice(0, MAX_RELEASE_NOTES_CHARS) ?? '',
installer, installer,
manifest, manifest,
signature, signature,
@@ -17,6 +17,10 @@ export interface ResourcePaths {
readonly networkHookLibrary: string; readonly networkHookLibrary: string;
/** Multi-resolution Windows icon for the window and system tray. */ /** Multi-resolution Windows icon for the window and system tray. */
readonly appIcon: string; readonly appIcon: string;
/** Bundled example mod templates seeded into an empty mods folder on first use. */
readonly modTemplates: string;
/** Modular ground AI daScript sources injected into `game.vromfs.bin` when active. */
readonly groundAiScripts: string;
} }
export function resourcePaths(): ResourcePaths { export function resourcePaths(): ResourcePaths {
@@ -32,6 +36,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(process.resourcesPath, 'patches'), patches: join(process.resourcesPath, 'patches'),
networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'), networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'),
appIcon: join(process.resourcesPath, 'icon.ico'), appIcon: join(process.resourcesPath, 'icon.ico'),
modTemplates: join(process.resourcesPath, 'mod-templates'),
groundAiScripts: join(process.resourcesPath, 'game-ai', 'ground'),
}; };
} }
// The app path is apps/launcher; the repository is two levels up. // The app path is apps/launcher; the repository is two levels up.
@@ -40,6 +46,8 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(repository, 'patches'), patches: join(repository, 'patches'),
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'), networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
groundAiScripts: join(repository, 'game-ai', 'ground'),
}; };
} }
@@ -6,6 +6,7 @@ import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts'; import type { InstallRecord } from '@shared/schemas/install.ts';
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts'; import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts'; import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts'; import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts'; import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts'; import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
@@ -95,15 +96,27 @@ export async function setSaveCurrencies(copyId: string, userId: string, values:
} }
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> { export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] }; const defaultPath = await resolveDialogDefaultPath('save-archive');
const options = {
properties: ['openFile' as const],
filters: [{ name: 'ZIP', extensions: ['zip'] }],
...(defaultPath ? { defaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : result.filePaths[0] ?? null }; const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('save-archive', chosen);
return { path: chosen };
} }
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> { export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
const copy = await requireCopy(copyId); const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId); await getSaveDetails(copyId, userId);
const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] }; const defaultDir = await resolveDialogDefaultPath('save-archive');
const fileName = `WTOffline-save-${userId}.zip`;
const options = {
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'ZIP', extensions: ['zip'] }],
};
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options); const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
if (result.canceled || !result.filePath) return { path: null }; if (result.canceled || !result.filePath) return { path: null };
try { try {
@@ -113,6 +126,7 @@ export async function exportSave(copyId: string, userId: string, window: Browser
console.error('[saves] could not export the save:', error); console.error('[saves] could not export the save:', error);
throw new AppError('save_operation_failed'); throw new AppError('save_operation_failed');
} }
await rememberDialogPath('save-archive', result.filePath);
return { path: result.filePath }; return { path: result.filePath };
} }
@@ -275,9 +289,16 @@ export async function copyOnlineData(copyId: string, userId: string, accountId:
} }
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> { export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] }; const defaultPath = await resolveDialogDefaultPath('official-backups');
const options = {
properties: ['openFile' as const, 'multiSelections' as const],
filters: [{ name: 'BLK', extensions: ['blk'] }],
...(defaultPath ? { defaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return result.canceled ? [] : result.filePaths; if (result.canceled || result.filePaths.length === 0) return [];
if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]);
return result.filePaths;
} }
export async function previewSelectedBackups( export async function previewSelectedBackups(
+171
View File
@@ -0,0 +1,171 @@
import { stat } from 'node:fs/promises';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { readJsonOr, writeJsonAtomic } from './atomic-json.ts';
/**
* Remembers the last directory chosen in native open/save dialogs, keyed by dialog category,
* persisted to `<userData>/dialog-paths.json`. Read/write errors are swallowed so dialog
* behavior is never disrupted.
*/
export type DialogPathCategory =
| 'folder'
| 'save-archive'
| 'official-backups'
| 'mods-folder'
| 'mod-preset';
export interface DialogPathStore {
resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined>;
rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void>;
}
const DIALOG_PATHS_FILENAME = 'dialog-paths.json';
const LAST_KEY = 'last';
const MAX_ANCESTOR_STEPS = 128;
/**
* Resolve `candidate` to an existing directory:
* - If it is an existing directory, return its normalized path.
* - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory.
* - Return `undefined` when no existing ancestor directory can be reached.
*/
export async function resolveExistingDirectory(candidate: string | null | undefined): Promise<string | undefined> {
if (!candidate) return undefined;
const trimmed = candidate.trim();
if (!trimmed || !isAbsolute(trimmed)) return undefined;
let current = resolve(trimmed);
for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) {
try {
const info = await stat(current);
if (info.isDirectory()) return current;
} catch {
// Missing or inaccessible path; continue walking toward the filesystem root.
}
const parent = dirname(current);
if (parent === current) return undefined;
current = parent;
}
return undefined;
}
/** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */
export function createDialogPathStore(
resolveStorePath: () => Promise<string | null> | string | null,
): DialogPathStore {
let cached: Map<string, string> | null = null;
let loading: Promise<Map<string, string>> | null = null;
let pending: Promise<void> = Promise.resolve();
async function loadMap(): Promise<Map<string, string>> {
if (cached) return cached;
if (loading) return loading;
loading = (async () => {
const map = new Map<string, string>();
const storePath = await resolveStorePath();
if (storePath) {
try {
const raw = await readJsonOr(storePath, null);
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
if (typeof value === 'string' && value.trim().length > 0) {
map.set(key, value);
}
}
}
} catch (error) {
console.warn('[dialog-paths] failed to read dialog paths:', error);
}
}
cached = map;
return map;
})().finally(() => {
loading = null;
});
return loading;
}
return {
async resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
try {
const explicitDir = await resolveExistingDirectory(explicitPath);
if (explicitDir) return explicitDir;
const map = await loadMap();
const categoryPath = map.get(category);
if (categoryPath) {
const resolved = await resolveExistingDirectory(categoryPath);
if (resolved) return resolved;
}
const lastPath = map.get(LAST_KEY);
if (lastPath && lastPath !== categoryPath) {
const resolved = await resolveExistingDirectory(lastPath);
if (resolved) return resolved;
}
} catch (error) {
console.warn('[dialog-paths] failed to resolve default dialog path:', error);
}
return undefined;
},
async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
const dir = await resolveExistingDirectory(selectedPath);
if (!dir) return;
const operation = pending.then(async () => {
const map = await loadMap();
if (map.get(category) === dir && map.get(LAST_KEY) === dir) return;
map.set(category, dir);
map.set(LAST_KEY, dir);
const storePath = await resolveStorePath();
if (!storePath) return;
try {
await writeJsonAtomic(storePath, Object.fromEntries(map));
} catch (error) {
console.warn('[dialog-paths] failed to save dialog paths:', error);
}
});
pending = operation.then(() => undefined, () => undefined);
await operation;
},
};
}
async function defaultStorePath(): Promise<string | null> {
try {
const mod = await import('electron') as {
readonly app?: { getPath?: (name: 'userData') => string };
readonly default?: { app?: { getPath?: (name: 'userData') => string } };
};
const electronApp = mod.app ?? mod.default?.app;
if (typeof electronApp?.getPath !== 'function') return null;
return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME);
} catch {
return null;
}
}
const defaultStore = createDialogPathStore(defaultStorePath);
export function resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
return defaultStore.resolveDialogDefaultPath(category, explicitPath);
}
export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
return defaultStore.rememberDialogPath(category, selectedPath);
}
+23
View File
@@ -0,0 +1,23 @@
import * as nodeFs from 'node:fs';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
let cached: typeof nodeFs | null = null;
/**
* Return Node's unpatched fs module inside Electron.
*
* Electron patches `node:fs` to treat any `.asar` file anywhere on disk as a virtual archive
* directory, which breaks streaming reads, stats and recursive cleanup when copying or managing
* player folders that happen to contain an `.asar` file. Falls back to `node:fs` outside Electron.
*/
export function rawFs(): typeof nodeFs {
if (cached) return cached;
try {
cached = require('original-fs') as typeof nodeFs;
} catch {
cached = nodeFs;
}
return cached;
}
@@ -9,9 +9,12 @@ export interface BuildRequest {
readonly port: number; readonly port: number;
readonly patches: string; readonly patches: string;
readonly networkHookLibrary: string; readonly networkHookLibrary: string;
readonly groundAiScripts: string;
readonly decalCache?: string; readonly decalCache?: string;
readonly hookLogging: boolean; readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[]; readonly acceptedUnavailable: readonly string[];
readonly modsDir?: string;
readonly enabledModIds?: readonly string[];
} }
export type BuildCommand = BuildRequest | { readonly kind: 'write' }; export type BuildCommand = BuildRequest | { readonly kind: 'write' };
+85 -6
View File
@@ -1,14 +1,34 @@
import { readFileSync, realpathSync } from 'node:fs'; import { readFileSync, realpathSync } from 'node:fs';
import { relative } from 'node:path'; import { relative } from 'node:path';
import type { MessageEvent } from 'electron'; import type { MessageEvent } from 'electron';
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher'; import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
import { multiVehiclePackIds } from '@wto/server'; import {
assertWritableCopy,
buildGameCopy,
computeModsBuildFingerprint,
copyPlayerDecalCache,
CORE_BUILD_PACKS,
GAME_PACK_FILE,
isGroundAiActive,
playerDecalCacheProblem,
prepareOptionalStockPacks,
readPlayerDecalIndexFiles,
readStockGameFiles,
syncExternalModFiles,
writeGameCopy,
type GameCopyBuild,
type GameCopyFile,
} from '@wto/patcher';
import { loadGroundAiTuning, multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
let prepared: { let prepared: {
readonly request: BuildRequest; readonly request: BuildRequest;
readonly files: readonly GameCopyFile[]; readonly files: readonly GameCopyFile[];
readonly decalCache: string | undefined; readonly decalCache: string | undefined;
readonly enabledMods: readonly DiscoveredMod[];
readonly optionalPacksInBuild: readonly ModdableClientPack[];
readonly fingerprint: string;
} | null = null; } | null = null;
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void { function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
@@ -31,17 +51,63 @@ function importedDecals(path: string | undefined): string | undefined {
return undefined; return undefined;
} }
function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] {
if (!modsDir || !enabledModIds || enabledModIds.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const ordered: DiscoveredMod[] = [];
for (const id of enabledModIds) {
const mod = byId.get(id);
if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`);
ordered.push(mod);
}
return ordered;
}
function logModBuildSummary(result: GameCopyBuild): void {
if (result.gamePack) {
console.info(`[build] injected ${result.gamePack.modules.length} ground AI module(s) into ${result.gamePack.archiveFolder}`);
}
if (result.mods.enabledModIds.length === 0) return;
console.info(
`[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` +
`(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` +
`gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` +
`exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`,
);
for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) {
console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`);
}
}
function build(request: BuildRequest): void { function build(request: BuildRequest): void {
checkBuildLocation(request); checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache); const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds);
const groundAiConfig = loadGroundAiTuning(request.dataPath, console.info, enabledMods);
const groundAiActive = isGroundAiActive(groundAiConfig);
const touchedSet = new Set<ModdableClientPack>(
touchedClientPacks(enabledMods).filter((pack) => !CORE_BUILD_PACKS.has(pack)),
);
if (groundAiActive) touchedSet.add(GAME_PACK_FILE);
const optionalPacksInBuild = [...touchedSet];
const extraStockPacks = optionalPacksInBuild.length > 0
? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild)
: undefined;
const result = buildGameCopy({ const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath), stock: readStockGameFiles(request.stockPath),
patches: request.patches, patches: request.patches,
networkHookLibrary: readFileSync(request.networkHookLibrary), networkHookLibrary: readFileSync(request.networkHookLibrary),
port: request.port, port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info), multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods),
placeholderDecals: decalCache === undefined, placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging, hookLogging: request.hookLogging,
...(enabledMods.length > 0 ? { mods: enabledMods } : {}),
...(extraStockPacks ? { extraStockPacks } : {}),
groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig },
}); });
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable); const accepted = new Set(request.acceptedUnavailable);
@@ -50,7 +116,13 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' }); send({ kind: 'failed', error: 'launch_build_unavailable' });
return; return;
} }
prepared = { request, files: result.files, decalCache }; logModBuildSummary(result);
const fingerprint = computeModsBuildFingerprint(
enabledMods,
request.port,
`${request.patches}|groundAi=${JSON.stringify(groundAiConfig)}`,
);
prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint };
send({ kind: 'prepared', total: prepared.files.length }); send({ kind: 'prepared', total: prepared.files.length });
} }
@@ -62,15 +134,22 @@ process.parentPort.on('message', (event: MessageEvent) => {
return; return;
} }
if (!prepared) throw new Error('No build is ready to write.'); if (!prepared) throw new Error('No build is ready to write.');
const { request, files, decalCache } = prepared; const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared;
prepared = null; prepared = null;
checkBuildLocation(request); checkBuildLocation(request);
const { copyPath } = request; const { copyPath, stockPath } = request;
if (decalCache) copyPlayerDecalCache(decalCache, copyPath); if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
for (const [index, file] of files.entries()) { for (const [index, file] of files.entries()) {
writeGameCopy(copyPath, [file]); writeGameCopy(copyPath, [file]);
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path }); send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
} }
const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint);
for (const warning of deployResult.warnings) {
console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`);
}
if (deployResult.restoredOptionalPacks.length > 0) {
console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`);
}
send({ kind: 'written' }); send({ kind: 'written' });
} catch (error) { } catch (error) {
console.error('[build] preparing the game copy failed:', error); console.error('[build] preparing the game copy failed:', error);
@@ -1,16 +1,42 @@
import { discoverMods, type DiscoveredMod } from '@wto/mods';
import { startServer } from '@wto/server'; import { startServer } from '@wto/server';
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed'; export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] {
if (!modsDir || !enabledJson) return [];
const ids = JSON.parse(enabledJson) as unknown;
if (!Array.isArray(ids) || ids.length === 0) return [];
const discovered = discoverMods(modsDir);
const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod]));
const mods: DiscoveredMod[] = [];
for (const id of ids) {
if (typeof id !== 'string') continue;
const mod = byId.get(id);
if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`);
mods.push(mod);
}
return mods;
}
async function serve(): Promise<void> { async function serve(): Promise<void> {
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2); const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2);
const port = Number(portText); const port = Number(portText);
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) { if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid local server arguments.'); throw new Error('Invalid local server arguments.');
} }
const loggingEnabled = loggingFlag !== '0'; const loggingEnabled = loggingFlag !== '0';
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info }); const mods = loadOrderedMods(modsDir, enabledModIdsJson);
const server = await startServer({
gameFolder,
dataFolder,
port,
loggingEnabled,
...(mods.length > 0 ? { mods } : {}),
report: console.info,
});
if (server.logFolder) console.info('Traffic log:', server.logFolder); if (server.logFolder) console.info('Traffic log:', server.logFolder);
if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', '));
process.parentPort.once('message', () => { process.parentPort.once('message', () => {
void server.close().then(() => process.exit(0)).catch((error: unknown) => { void server.close().then(() => process.exit(0)).catch((error: unknown) => {
console.error('Could not close the local server:', error); console.error('Could not close the local server:', error);
+13 -2
View File
@@ -10,6 +10,7 @@ import { applyLanguage, resolveLanguage } from './i18n/index.ts';
import { ipcInvoke, ipcOn } from './ipc.ts'; import { ipcInvoke, ipcOn } from './ipc.ts';
import { AboutPage } from './pages/about/AboutPage.tsx'; import { AboutPage } from './pages/about/AboutPage.tsx';
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx'; import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
import { CopyList } from './pages/copies/CopyList.tsx'; import { CopyList } from './pages/copies/CopyList.tsx';
import { CopySummary } from './pages/copies/CopySummary.tsx'; import { CopySummary } from './pages/copies/CopySummary.tsx';
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx'; import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
@@ -21,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx'; import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx'; import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts'; import { wizardBar } from './pages/install/wizard-bar.ts';
import { ModsPage } from './pages/mods/ModsPage.tsx';
import { TuningPage } from './pages/tuning/TuningPage.tsx'; import { TuningPage } from './pages/tuning/TuningPage.tsx';
import { SavesPage } from './pages/saves/SavesPage.tsx'; import { SavesPage } from './pages/saves/SavesPage.tsx';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx'; import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
@@ -31,7 +33,7 @@ import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx'; import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts'; import type { BarModel } from './shell/bar-model.ts';
import { Footer } from './shell/Footer.tsx'; import { Footer } from './shell/Footer.tsx';
import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts'; import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts';
import { SubNav } from './shell/SubNav.tsx'; import { SubNav } from './shell/SubNav.tsx';
import { TitleBar } from './shell/TitleBar.tsx'; import { TitleBar } from './shell/TitleBar.tsx';
import { useBackgrounds } from './shell/useBackgrounds.ts'; import { useBackgrounds } from './shell/useBackgrounds.ts';
@@ -68,6 +70,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
// The setting as the window opened: turning it on later does not check right away. // The setting as the window opened: turning it on later does not check right away.
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report); const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report); const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
const maintenance = useCopyMaintenance(report);
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions; const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) }); const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
@@ -193,6 +196,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
: <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>, : <Sheet title={t(`tuning.sections.${route.tuning}`)}><p className="lead">{t('tuning.noCopy')}</p></Sheet>,
bar: home, bar: home,
}; };
case 'mods':
return {
side: <SubNav sections={MODS_SECTIONS} active={route.mods} label={(section) => t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />,
main: record
? <ModsPage key={record.id} copy={record} section={route.mods} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`mods.sections.${route.mods}`)}><p className="lead">{t('mods.noCopy')}</p></Sheet>,
bar: home,
};
case 'copies': { case 'copies': {
const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />; const side = <SubNav sections={COPY_SECTIONS} active={route.copies} label={(section) => t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />;
if (route.copies === 'list') { if (route.copies === 'list') {
@@ -223,7 +234,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
}; };
} }
if (route.copies === 'maintain') { if (route.copies === 'maintain') {
return { side, main: <CopyMaintenance key={record.id} record={record} onError={report} />, bar: home }; return { side, main: <CopyMaintenance key={record.id} record={record} maintenance={maintenance} onError={report} />, bar: home };
} }
const main = route.copies === 'features' const main = route.copies === 'features'
? <FeatureStatus record={record} supportedVersions={supported} onError={report} /> ? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
@@ -5,16 +5,22 @@ interface FolderFieldProps {
readonly path: string | null; readonly path: string | null;
/** Title of the folder dialog. */ /** Title of the folder dialog. */
readonly dialogTitle: string; readonly dialogTitle: string;
/** Optional starting directory when no path is chosen yet. */
readonly defaultPath?: string | null | undefined;
readonly disabled?: boolean; readonly disabled?: boolean;
readonly onChosen: (path: string) => void; readonly onChosen: (path: string) => void;
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
/** A chosen folder and the button that opens the folder dialog. */ /** A chosen folder and the button that opens the folder dialog. */
export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) { export function FolderField({ path, dialogTitle, defaultPath, disabled = false, onChosen, onError }: FolderFieldProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const choose = (): void => { const choose = (): void => {
ipcInvoke('dialog:pickFolder', { title: dialogTitle }) const startPath = path ?? defaultPath;
ipcInvoke('dialog:pickFolder', {
title: dialogTitle,
...(startPath ? { defaultPath: startPath } : {}),
})
.then(({ path: chosen }) => { .then(({ path: chosen }) => {
if (chosen) onChosen(chosen); if (chosen) onChosen(chosen);
}) })
@@ -0,0 +1,152 @@
import { createElement, Fragment, useMemo, type ReactNode } from 'react';
import { marked, type Token, type Tokens } from 'marked';
const SAFE_EXTERNAL_URL = /^https?:\/\//i;
const HTML_COMMENT = /^<!--[\s\S]*?-->$/;
function isSafeExternalUrl(href: string | undefined): href is string {
return typeof href === 'string' && SAFE_EXTERNAL_URL.test(href.trim());
}
function renderInline(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderInlineToken(token, `${keyPrefix}-${index}`));
}
function renderInlineToken(token: Token, key: string): ReactNode {
switch (token.type) {
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'escape':
return <Fragment key={key}>{(token as Tokens.Escape).text}</Fragment>;
case 'strong':
return <strong key={key}>{renderInline((token as Tokens.Strong).tokens, key)}</strong>;
case 'em':
return <em key={key}>{renderInline((token as Tokens.Em).tokens, key)}</em>;
case 'del':
return <del key={key}>{renderInline((token as Tokens.Del).tokens, key)}</del>;
case 'codespan':
return <code key={key}>{(token as Tokens.Codespan).text}</code>;
case 'br':
return <br key={key} />;
case 'link': {
const link = token as Tokens.Link;
const content = link.tokens.length ? renderInline(link.tokens, key) : link.text;
if (!isSafeExternalUrl(link.href)) return <Fragment key={key}>{content}</Fragment>;
return (
<a key={key} href={link.href} title={link.title ?? undefined} target="_blank" rel="noreferrer">
{content}
</a>
);
}
case 'image':
return <Fragment key={key}>{(token as Tokens.Image).text}</Fragment>;
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <Fragment key={key}>{raw}</Fragment>;
}
default:
return 'raw' in token && typeof token.raw === 'string' ? <Fragment key={key}>{token.raw}</Fragment> : null;
}
}
function renderTable(table: Tokens.Table, key: string): ReactNode {
return (
<div key={key} className="markdown-table-wrap">
<table>
<thead>
<tr>
{table.header.map((cell, column) => (
<th key={`${key}-h-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-h-${column}`)}
</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row, rowIndex) => (
<tr key={`${key}-r-${rowIndex}`}>
{row.map((cell, column) => (
<td key={`${key}-r-${rowIndex}-${column}`} style={cell.align ? { textAlign: cell.align } : undefined}>
{renderInline(cell.tokens, `${key}-r-${rowIndex}-${column}`)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
function renderListItem(item: Tokens.ListItem, key: string): ReactNode {
return (
<li key={key}>
{item.task && <input type="checkbox" checked={Boolean(item.checked)} disabled readOnly className="markdown-task" />}
{renderBlocks(item.tokens, key)}
</li>
);
}
function renderBlock(token: Token, key: string): ReactNode {
switch (token.type) {
case 'space':
case 'def':
case 'checkbox':
return null;
case 'heading': {
const heading = token as Tokens.Heading;
const level = Math.min(6, Math.max(1, heading.depth));
return createElement(`h${level}`, { key }, renderInline(heading.tokens, key));
}
case 'paragraph':
return <p key={key}>{renderInline((token as Tokens.Paragraph).tokens, key)}</p>;
case 'text': {
const textToken = token as Tokens.Text;
if (textToken.tokens?.length) return <Fragment key={key}>{renderInline(textToken.tokens, key)}</Fragment>;
return <Fragment key={key}>{textToken.text}</Fragment>;
}
case 'blockquote':
return <blockquote key={key}>{renderBlocks((token as Tokens.Blockquote).tokens, key)}</blockquote>;
case 'list': {
const list = token as Tokens.List;
const items = list.items.map((item, index) => renderListItem(item, `${key}-i-${index}`));
if (list.ordered) {
return <ol key={key} start={typeof list.start === 'number' && list.start !== 1 ? list.start : undefined}>{items}</ol>;
}
return <ul key={key}>{items}</ul>;
}
case 'code':
return (
<pre key={key}>
<code>{(token as Tokens.Code).text}</code>
</pre>
);
case 'hr':
return <hr key={key} />;
case 'table':
return renderTable(token as Tokens.Table, key);
case 'html': {
const raw = (token as Tokens.HTML).text.trim();
if (!raw || HTML_COMMENT.test(raw)) return null;
return <p key={key}>{raw}</p>;
}
default:
return 'raw' in token && typeof token.raw === 'string' && token.raw.trim()
? <p key={key}>{token.raw}</p>
: null;
}
}
function renderBlocks(tokens: readonly Token[], keyPrefix: string): ReactNode {
return tokens.map((token, index) => renderBlock(token, `${keyPrefix}-${index}`));
}
/** Safe React renderer for GFM Markdown without injecting raw HTML. */
export function MarkdownContent({ markdown }: { readonly markdown: string }) {
const tokens = useMemo(() => marked.lexer(markdown, { gfm: true, breaks: false }), [markdown]);
return <div className="markdown-body">{renderBlocks(tokens, 'md')}</div>;
}
@@ -7,6 +7,7 @@
"home": "Home", "home": "Home",
"saves": "Saves", "saves": "Saves",
"tuning": "Tuning", "tuning": "Tuning",
"mods": "Mods",
"copies": "Clients", "copies": "Clients",
"settings": "Settings", "settings": "Settings",
"about": "About" "about": "About"
@@ -96,7 +97,9 @@
}, },
"decals": { "decals": {
"source": "Decal source", "source": "Decal source",
"hint": "Import the online game's cache/content folder. The client uses placeholder decals when no cache is available.", "hint": "Select the online game root folder, cache, or cache/content for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
"autoDetectedNotice": "Online decal cache detected automatically and will be imported during installation. Click the button above if you prefer placeholder decals.",
"importFromSource": "Import from online source",
"choose": "Choose decal cache…", "choose": "Choose decal cache…",
"useDefault": "Use placeholder decals", "useDefault": "Use placeholder decals",
"importing": "Importing decal cache", "importing": "Importing decal cache",
@@ -157,7 +160,8 @@
"copy": "Copy installation (recommended)", "copy": "Copy installation (recommended)",
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.", "copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
"spaceSaving": "Space-saving copy", "spaceSaving": "Space-saving copy",
"spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.", "spaceSavingBody": "Resource packs are shared with the online client via same-volume hard links, requiring only about {{size}} of additional copying. Windows Explorer Properties counts shared files toward both folders, but only the newly copied files use extra disk space. An in-place update to the online client can change shared files.",
"spaceSavingBreakdown": "Estimated copy: about {{copy}} · Shared via hard links: about {{shared}} (no extra disk space)",
"spaceSavingPending": "Calculating how much space can be saved.", "spaceSavingPending": "Calculating how much space can be saved.",
"spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.", "spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.",
"sameVolumeRequired": "Select a destination on the same volume as the original installation.", "sameVolumeRequired": "Select a destination on the same volume as the original installation.",
@@ -213,6 +217,8 @@
"recording": "Finishing installation" "recording": "Finishing installation"
}, },
"copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", "copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
"copiedActual": "Copied to disk: {{copied}} / {{copyTotal}} ({{copiedFiles}} / {{copyTotalFiles}} files)",
"linkedShared": "Shared via hard links (no extra space): {{linked}} / {{linkTotal}} ({{linkedFiles}} / {{linkTotalFiles}} resource packs)",
"verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", "verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
"prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", "prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files",
"cancelHint": "Can be cancelled at any time; copied files will be deleted", "cancelHint": "Can be cancelled at any time; copied files will be deleted",
@@ -230,11 +236,18 @@
"missingFolder": "Folder missing", "missingFolder": "Folder missing",
"relocate": "Relocate…", "relocate": "Relocate…",
"relocateDialogTitle": "Select the moved client folder", "relocateDialogTitle": "Select the moved client folder",
"list": { "current": "Current", "select": "Set as current" }, "list": {
"current": "Current",
"select": "Set as current"
},
"none": "The offline edition is not installed yet.", "none": "The offline edition is not installed yet.",
"maintenance": { "maintenance": {
"update": "Update from online installation", "update": "Update from online installation",
"updateAction": "Update client", "updateAction": "Update client",
"setSource": "Set source…",
"changeSource": "Change source…",
"chooseSource": "Choose the online installation folder",
"sourceNotSet": "No online installation source is configured.",
"newVersion": "Version {{version}} is available from the installation source.", "newVersion": "Version {{version}} is available from the installation source.",
"updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.", "updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.",
"updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.", "updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.",
@@ -250,16 +263,31 @@
"repair": "Repair client", "repair": "Repair client",
"repairAction": "Repair", "repairAction": "Repair",
"repairHint": "Restore the original files from the backup. Game files will be generated again at launch.", "repairHint": "Restore the original files from the backup. Game files will be generated again at launch.",
"delete": "Delete client", "remove": "Remove client",
"deleteAction": "Delete…", "removeAction": "Remove…",
"deleteHint": "The data folder is kept by default.", "removeCopyHint": "Removes from the launcher list by default without deleting files on disk.",
"unlink": "Remove registration", "removeRestoreHint": "Removes from the launcher list by default; optionally restores original files and removes offline patch files while keeping the base game.",
"unlinkAction": "Remove…", "removeUnlinkHint": "Removes only from the launcher list without deleting game files on disk.",
"unlinkHint": "The launcher keeps the Steam game files and data folder in place.", "removeSteamHint": "Removes only from the launcher list. Steam game files and the data folder stay in place.",
"unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.", "removeCopyNotice": "Removes {{path}} from the launcher list. All game files and data on disk are kept by default.",
"deleteLocation": "Delete the offline client at {{path}}?", "removeListOnlyNotice": "Removes {{path}} from the launcher list only. Game files on disk will not be deleted.",
"deleteData": "Also delete the data folder at {{path}}", "removeSteamNotice": "Removes {{path}} from the launcher list only. Steam game files and data on disk will not be deleted.",
"confirm": "Confirm deletion", "originCopy": "Detected client type: full copy (created as an independent copy by the launcher).",
"originHardlink": "Detected client type: space-saving hard-linked copy (read-only resource packs are shared; deleting this copy does not affect the original game folder).",
"originInPlace": "Detected client type: in-place installation (full folder deletion is disabled to protect the base game).",
"originUnknown": "Detected client type: existing folder of unknown origin (no client identity marker found; full folder deletion is disabled for safety).",
"originUnknownHardlinked": "Detected client type: existing folder of unknown origin (hard-linked resources were detected without a client identity marker; full folder deletion is disabled for safety).",
"deleteFiles": "Also delete the client folder at {{path}}",
"deleteHardlinkHint": "Note: This client shares read-only resource packs via hard links; deleting the copy folder will not affect the original game folder.",
"deleteFilesWarning": "This will permanently delete all files in the copied client folder at {{path}}. This action cannot be undone.",
"deleteHardlinkWarning": "This will permanently delete all files in the hard-linked copy folder at {{path}} (the original game folder is unaffected). This action cannot be undone.",
"restoreStock": "Restore original files and remove offline patch files (keep base game)",
"restoreStockHint": "Restores the 4 original core files from wtoffline\\stock and removes wtoffline\\ along with network hook files (wto_ws.dll / wto_ws.cfg / wto_ws.log). No base game files are deleted.",
"deleteData": "Also delete the data folder at {{path}} (contains saves, settings, and logs)",
"openFolder": "Open folder",
"confirmRemove": "Remove from list",
"confirmRestore": "Restore and remove",
"confirmDelete": "Confirm deletion",
"phase": { "phase": {
"checking": "Checking the client", "checking": "Checking the client",
"copying": "Copying changed files", "copying": "Copying changed files",
@@ -267,11 +295,12 @@
}, },
"result": { "result": {
"confirm-steam": "Steam locations confirmed.", "confirm-steam": "Steam locations confirmed.",
"set-source": "Online installation source saved.",
"check": "Patch check complete.", "check": "Patch check complete.",
"repair": "Original files restored.", "repair": "Original files restored.",
"update": "Client updated.", "update": "Client updated.",
"compact": "Space-saving conversion complete.", "compact": "Space-saving conversion complete.",
"delete": "Client deleted.", "delete": "Client removed.",
"cancelled": "Maintenance cancelled." "cancelled": "Maintenance cancelled."
} }
}, },
@@ -341,8 +370,7 @@
"country": "Country", "country": "Country",
"type": "Vehicle type", "type": "Vehicle type",
"actions": "Bulk actions", "actions": "Bulk actions",
"research": "Research all", "purchase": "Research and buy all",
"purchase": "Grant regular vehicles",
"equipment": "Unlock modifications", "equipment": "Unlock modifications",
"empty": "This client has no eligible research branches.", "empty": "This client has no eligible research branches.",
"rank": "Rank {{rank}}", "rank": "Rank {{rank}}",
@@ -436,7 +464,8 @@
"premiumDays": "Premium account days", "premiumDays": "Premium account days",
"avatar": "Avatar", "avatar": "Avatar",
"avatarUnavailable": "Avatar unavailable", "avatarUnavailable": "Avatar unavailable",
"level": "Account level",␍ "apply": "Save changes", "level": "Account level",
"apply": "Save changes",
"saved": "Changes saved.", "saved": "Changes saved.",
"noBattles": "The save has no recorded battles.", "noBattles": "The save has no recorded battles.",
"win": "Victory", "win": "Victory",
@@ -449,6 +478,7 @@
"sections": { "sections": {
"rewards": "Rewards", "rewards": "Rewards",
"battle": "Battles", "battle": "Battles",
"bots": "Bot parameters",
"newProfile": "New saves", "newProfile": "New saves",
"research": "Research" "research": "Research"
}, },
@@ -460,9 +490,11 @@
"smallTeamsMaxPlayers": "Small teams player limit", "smallTeamsMaxPlayers": "Small teams player limit",
"brSpreadMrank": "Matchmaking BR range", "brSpreadMrank": "Matchmaking BR range",
"subModeChance": "Sub-mode probability", "subModeChance": "Sub-mode probability",
"botPoolLimitPerType": "AI vehicle pool limit per type",
"tankBotRespawns": "AI tank respawns", "tankBotRespawns": "AI tank respawns",
"airBotRespawns": "AI aircraft respawns", "airBotRespawns": "AI aircraft respawns",
"strikeUcavSpawnScore": "Strike UCAV spawn points", "strikeUcavSpawnScore": "Strike UCAV spawn points",
"nuclearEscalationStrategicBombers": "Nuclear Escalation stage-3 strategic bombers (B-52H / Tu-95M)",
"silverLions": "Starting Silver Lions", "silverLions": "Starting Silver Lions",
"goldenEagles": "Starting Golden Eagles", "goldenEagles": "Starting Golden Eagles",
"preferLineSuccessor": "Prefer the next vehicle in the line", "preferLineSuccessor": "Prefer the next vehicle in the line",
@@ -473,6 +505,225 @@
"highestRank": "Highest rank", "highestRank": "Highest rank",
"treeOrder": "Research tree order" "treeOrder": "Research tree order"
}, },
"expandAll": "Expand all advanced",
"collapseAll": "Collapse advanced",
"botModeHint": "Custom ground AI is experimental and under active tuning. Switch to Stock AI if you run into issues. Changes take effect on the next launch.",
"botStockNotice": "Stock AI is active: custom ground AI scripts are not packed, and lineup weights / custom AI parameters below are ignored (respawn counts and pool limit still apply).",
"botModes": {
"full": "Full custom AI (default, experimental)",
"fire": "Perception & fire control only (stock movement)",
"drive": "Commander & driving only (stock aiming/firing)",
"stock": "Stock AI (disable custom ground AI)"
},
"botDriveModes": {
"vehicle_phys": "Physics control (vehicle_phys)",
"movesys": "Stock move system (movesys)"
},
"botSteer": {
"normal": "Normal (1)",
"inverted": "Inverted (-1)"
},
"botGroups": {
"general": "General & mode",
"lineupWeights": "Ground AI vehicle class weights",
"loadout": "Ground AI spawn ammunition",
"commander": "Commander & role quotas",
"macro": "Macro capture & SPAA",
"stateMachine": "Hull state machine & repair",
"perception": "Visual perception & exposure",
"tactics": "Situational awareness & memory",
"estimation": "Lead estimation & aim bias",
"fireControl": "Fire control & fire gate",
"navigation": "Driving & navigation",
"crowd": "Spacing & crowd dispersal",
"terrain": "Terrain & ridge limits",
"runtime": "Tick cadence & diagnostics"
},
"botGroupHints": {
"general": "AI mode selection, respawn limits and candidate pool size",
"lineupWeights": "Relative pick weights by tank class (active outside Stock mode)",
"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",
"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",
"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"
},
"botFields": {
"mode": "Ground AI mode",
"lineupWeights": {
"mediumTank": "Medium / MBT weight",
"heavyTank": "Heavy tank weight",
"tankDestroyer": "Tank destroyer weight",
"lightTank": "Light tank weight",
"spaa": "SPAA weight",
"other": "Other ground vehicles weight"
},
"loadout": {
"lowReadyRackThreshold": "Low ready-rack top-up threshold",
"topUpAmmoCount": "Top-up target shell count",
"primaryAmmoPct": "Primary anti-armor shell share",
"secondaryMinRounds": "Minimum secondary HE / HEAT rounds",
"penetrationCompareDistM": "Penetration comparison distance"
},
"commander": {
"rebalanceSec": "Role rebalance interval",
"roleHoldSec": "Minimum role hold duration",
"bttlAssaultPct": "Battle mode assault share",
"bttlFlankPct": "Battle mode flank share",
"bttlOverwatchPct": "Battle mode overwatch share",
"conqAssaultPct": "Conquest assault share",
"conqFlankPct": "Conquest flank share",
"conqHoldDefendPct": "Conquest hold defend share",
"conqHoldOverwatchPct": "Conquest hold overwatch share",
"domAssaultPct": "Domination assault share",
"domMaxDefendersPerCap": "Domination max defenders per cap",
"overwatchStandOffM": "Overwatch stand-off distance",
"flankStandOffM": "Flank stand-off distance",
"spaaFollowOffsetM": "SPAA follow offset behind push",
"flankMaxLengthRatio": "Flank lane max length ratio",
"flankMinSeparationM": "Flank lane min lateral separation",
"rallyProgressFrac": "Rally point progress fraction (0.1–0.75)",
"rallyWaitSec": "Rally max wait duration",
"rallyMinFrac": "Rally minimum ready fraction",
"rallyRadiusM": "Rally area radius",
"recallSafeHoldSec": "Recall safe hold before resuming attack"
},
"macro": {
"openingSplitSec": "Opening lane split duration",
"capMaxInsiders": "Max friendly bots inside one cap",
"recaptureMinBots": "Min bots sent to recapture",
"recaptureMaxBots": "Max bots sent to recapture",
"capStickyBonusM": "Current cap distance hysteresis",
"deathZoneRadiusM": "Death zone radius",
"deathZoneTtlSec": "Death zone memory lifetime",
"deathZoneMinKills": "Min deaths to mark death zone",
"spaaRearOffsetM": "SPAA rear position offset",
"spaaRelocateSec": "SPAA relocate interval",
"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",
"repositionMinMoveM": "Min move to unlock short halt",
"repositionStepM": "Flank reposition step distance",
"repairSafeEnemyDistM": "Safe enemy distance for repair"
},
"perception": {
"foliageTransparency": "Foliage transparency factor",
"nearSpotRangeM": "Close fast-spot distance",
"firingSpotRangeM": "Enemy firing reveal distance",
"fastSpotSec": "Fast exposure spot time",
"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"
},
"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",
"memoryTtlSec": "Lost target memory duration",
"targetStickinessSec": "Target focus stickiness duration",
"peekCooldownSec": "Peek-and-shoot cooldown"
},
"estimation": {
"watchMinSec": "Min exit watch duration",
"watchMaxSec": "Max exit watch duration",
"velSampleMinSpanSec": "Min velocity sample time span",
"velStableSpanSec": "Stable velocity convergence span",
"velJumpResetMps": "Sudden speed change reset threshold",
"baseAimSigmaM": "Base aim spread sigma",
"leadErrorFrac": "Lead estimation error fraction",
"maxBiasM": "Max per-opportunity aim bias"
},
"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",
"friendlyCorridorM": "Friendly fire corridor width",
"ballisticStepMaxM": "Ballistic occlusion step length",
"ballisticSweepRadiusM": "Ballistic sphere sweep radius",
"maxPreFireChecksPerTick": "Max detailed fire checks per tick"
},
"navigation": {
"driveMode": "Vehicle drive backend",
"maxPhysBots": "Max physics-controlled bots",
"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"
},
"crowd": {
"personalSpaceM": "Personal spacing distance",
"clusterRadiusM": "Ally cluster detection radius",
"clusterMaxAllies": "Max allies before dispersing",
"disperseStepM": "Dispersal step distance",
"disperseHoldSec": "Dispersal order hold time"
},
"terrain": {
"maxClimbSlopeDeg": "Max climbable slope angle",
"maxDropSlopeDeg": "Max drop slope angle",
"maxWaterDepthM": "Max fordable water depth",
"collisionMarginM": "Obstacle collision margin",
"crestLookaheadM": "Ridge crest lookahead distance",
"ridgeMaxDwellSec": "Max ridge dwell duration",
"ridgeMaxShots": "Max shots from ridge"
},
"cadence": {
"maxBots": "Max scripted AI bots",
"macroTickSec": "Commander update interval",
"tacticsTickSec": "Tactics & fire control interval",
"navTickSec": "Navigation & driving interval"
},
"diagnostics": {
"telemetry": "Enable AI telemetry logs",
"telemetryIntervalSec": "Telemetry logging interval"
}
},
"shared": "These settings apply to all saves in this client.", "shared": "These settings apply to all saves in this client.",
"nextLaunch": "Changes take effect the next time the local server starts.", "nextLaunch": "Changes take effect the next time the local server starts.",
"reset": "Restore defaults for this section", "reset": "Restore defaults for this section",
@@ -494,7 +745,7 @@
"appUpdates": "Launcher updates", "appUpdates": "Launcher updates",
"appUpdatesToggle": "Check for launcher updates at start", "appUpdatesToggle": "Check for launcher updates at start",
"patchPacks": "Adaptation pack updates", "patchPacks": "Adaptation pack updates",
"patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.", "patchPacksHint": "After a game update, patches for the new version are released as an adaptation pack.",
"updateMirror": "Update mirror repository", "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.", "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.", "updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.",
@@ -629,6 +880,9 @@
"download": "Download update", "download": "Download update",
"install": "Quit and install", "install": "Quit and install",
"installing": "Opening the installer…", "installing": "Opening the installer…",
"viewNotes": "Release notes",
"notesTitle": "Release notes — v{{version}}",
"closeNotes": "Close",
"errors": { "errors": {
"network": "The update source could not be reached.", "network": "The update source could not be reached.",
"page_limit": "Could not confirm whether a newer version is available.", "page_limit": "Could not confirm whether a newer version is available.",
@@ -638,7 +892,17 @@
} }
}, },
"statement": "Project information", "statement": "Project information",
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files." "statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.",
"homepage": {
"title": "Project homepage",
"hint": "Project overview, release catalog, and community links.",
"open": "Open homepage"
},
"community": {
"discord": "Discord",
"discordHint": "Development discussion, general chat, troubleshooting, and bug reports.",
"openDiscord": "Open Discord"
}
}, },
"features": { "features": {
"A-Offline startup": "Offline startup", "A-Offline startup": "Offline startup",
@@ -661,6 +925,7 @@
"J-Ground arcade and realistic": "Ground battles (arcade, realistic)", "J-Ground arcade and realistic": "Ground battles (arcade, realistic)",
"J-Air arcade and realistic": "Air battles (arcade, realistic)", "J-Air arcade and realistic": "Air battles (arcade, realistic)",
"J-Naval arcade and realistic": "Naval battles (arcade, realistic)", "J-Naval arcade and realistic": "Naval battles (arcade, realistic)",
"E-Crew skills in battle": "Crew skills and qualifications in battle",
"J-Sub-modes": "Additional modes (such as night battles)", "J-Sub-modes": "Additional modes (such as night battles)",
"K-AI opponents and teammates": "AI opponents and allies", "K-AI opponents and teammates": "AI opponents and allies",
"K-Spawn score and respawns": "Spawn points and respawning", "K-Spawn score and respawns": "Spawn points and respawning",
@@ -674,6 +939,96 @@
"L-Debriefing": "Battle results", "L-Debriefing": "Battle results",
"L-Battle awards": "Battle awards" "L-Battle awards": "Battle awards"
}, },
"mods": {
"sections": {
"list": "Mod list",
"presets": "Presets & repository"
},
"loading": "Loading mods…",
"noCopy": "Install or select an offline client first to configure its mods.",
"enabledSummary": "{{enabled}} / {{total}} enabled",
"experimentalChip": "Experimental",
"experimentalTitle": "Experimental mod API notice:",
"experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.",
"readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.",
"searchPlaceholder": "Filter by mod name, ID, or author…",
"autoSort": "Auto-sort by dependencies",
"autoSorted": "Reordered mods based on dependencies and load-order hints.",
"refresh": "Refresh",
"openFolder": "Open mods folder",
"openDocs": "Mod docs",
"discoveryErrorsTitle": "{{count}} mod folder(s) could not be loaded:",
"blockingIssuesTitle": "{{count}} blocking mod error(s) prevent launching:",
"issuesTitle": "{{count}} mod notice(s) or overlap(s):",
"severity": {
"error": "Error",
"warning": "Warning",
"info": "Info"
},
"emptyTitle": "No mods found in the global mods folder yet.",
"emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.",
"noSearchMatch": "No mods match the current search filter.",
"loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)",
"moveUp": "Move up",
"moveDown": "Move down",
"showDetails": "Details",
"hideDetails": "Hide",
"errorCount": "{{count}} error",
"warnCount": "{{count}} warn",
"badges": {
"data": "Data / Assets",
"gui": "GUI Patch",
"script": "Server Script",
"exe": "Exe Patch"
},
"details": {
"folder": "Folder",
"gameVersions": "Declared game versions",
"requires": "Requires",
"conflicts": "Conflicts",
"tuning": "Server tuning overlays: {{count}}",
"serverScript": "Executable server JS/TS script",
"packOps": "Client pack operations: {{count}}",
"addon": "3D model / texture addon: {{count}} file(s)",
"guiPatches": "GUI script patches: {{count}}",
"exePatches": "Declarative exe patches: {{count}}",
"companionFiles": "Companion files: {{count}}",
"configBlk": "Includes config.blk patch"
},
"presets": {
"heading": "Mod presets (saved per client)",
"description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.",
"quickSwitch": "Switch mod preset",
"customOption": "Custom active selection",
"namePlaceholder": "New preset name, e.g. Modern Vehicles",
"saveCurrent": "Save preset",
"import": "Import preset…",
"empty": "No presets saved for this client yet.",
"activeTag": "Active",
"summary": "{{count}} enabled / {{total}} tracked",
"apply": "Apply",
"overwrite": "Update",
"export": "Export",
"delete": "Delete",
"saved": "Saved preset \"{{name}}\".",
"applied": "Applied preset \"{{name}}\".",
"updated": "Updated preset \"{{name}}\" with current setup.",
"exported": "Exported preset to: {{path}}",
"imported": "Imported mod preset."
},
"repo": {
"heading": "Global mods repository",
"description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.",
"pathLabel": "Repository folder",
"defaultNote": "Using launcher default mods folder",
"customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)",
"changeFolder": "Change folder…",
"resetDefault": "Reset to default",
"pickTitle": "Select global mods repository folder",
"updated": "Updated global mods repository folder.",
"resetDone": "Reset to default mods repository folder."
}
},
"errors": { "errors": {
"app_update_unavailable": "There is no launcher update available to install.", "app_update_unavailable": "There is no launcher update available to install.",
"app_update_busy": "A launcher update operation is already in progress.", "app_update_busy": "A launcher update operation is already in progress.",
@@ -697,14 +1052,21 @@
"save_avatar_invalid": "Select an avatar available in this client.", "save_avatar_invalid": "Select an avatar available in this client.",
"save_level_invalid": "Enter a level supported by this client.", "save_level_invalid": "Enter a level supported by this client.",
"tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.", "tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.",
"mods_read_only": "Mods cannot be changed while the game, local server, or maintenance is running.",
"mods_write_failed": "The mod configuration could not be saved. See the launcher log.",
"mods_preset_invalid": "The selected file is not a valid WTOffline mod preset.",
"mods_blocking_issues": "Enabled mods have missing dependencies or conflicts. Resolve them on the Mods page before launching.",
"mods_folder_invalid": "The selected global mods folder is invalid or not writable.",
"copy_not_found": "The selected client is no longer available.", "copy_not_found": "The selected client is no longer available.",
"copies_write_failed": "The client registry could not be saved.", "copies_write_failed": "The client registry could not be saved.",
"copy_location_in_use": "The client or data location overlaps an existing client.", "copy_location_in_use": "The client or data location overlaps an existing client.",
"decal_source_invalid": "The selected folder does not contain a usable decal cache.", "decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose the online game root folder, cache, or cache/content.",
"decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.", "decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.",
"maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.", "maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.",
"maintenance_location": "The operation would affect files outside the registered client or data folder.", "maintenance_location": "The operation would affect files outside the registered client or data folder.",
"maintenance_no_update": "A newer version is unavailable at the installation source.", "maintenance_no_update": "A newer version is unavailable at the installation source.",
"maintenance_source_invalid": "Choose a complete online game installation folder.",
"maintenance_source_overlap": "The online installation source must be separate from the offline client and its data folder.",
"maintenance_cancelled": "The client update was cancelled.", "maintenance_cancelled": "The client update was cancelled.",
"maintenance_failed": "Client maintenance failed. See the launcher log.", "maintenance_failed": "Client maintenance failed. See the launcher log.",
"maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.", "maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.",
@@ -729,6 +1091,7 @@
"launch_server_exited": "The local server is unavailable.", "launch_server_exited": "The local server is unavailable.",
"launch_game_failed": "The game process could not start. See the launcher log.", "launch_game_failed": "The game process could not start. See the launcher log.",
"launch_game_files_missing": "Required game launch files are missing or unreadable (they may have been quarantined by antivirus software). Check your security software and the launcher log.", "launch_game_files_missing": "Required game launch files are missing or unreadable (they may have been quarantined by antivirus software). Check your security software and the launcher log.",
"launch_incomplete_uhq_packs": "This client contains incomplete optional UHQ texture pack(s) ({{packs}}), which causes a texture read crash (81110007). Verify or finish downloading the DLC in Steam or the official launcher and update the offline client, or remove the incomplete content.hq/<pack> folder and content/pkg_<pack>.rq2 from the offline client.",
"settings_write_failed": "The settings could not be saved.", "settings_write_failed": "The settings could not be saved.",
"folder_unreadable": "The folder cannot be read: {{path}}", "folder_unreadable": "The folder cannot be read: {{path}}",
"not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}", "not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}",
@@ -740,6 +1103,7 @@
"essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}", "essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}",
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.", "missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
"patch_check_failed": "An error occurred while checking patches.", "patch_check_failed": "An error occurred while checking patches.",
"launcher_inside_source": "WTOffline Launcher is currently inside the selected War Thunder folder. Move the launcher to a separate folder outside the game directory, then retry.",
"copy_failed": "Copying the game files failed. The copied files have been deleted.", "copy_failed": "Copying the game files failed. The copied files have been deleted.",
"hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.", "hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.",
"hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.", "hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.",
@@ -7,6 +7,7 @@
"home": "首页", "home": "首页",
"saves": "存档", "saves": "存档",
"tuning": "数值", "tuning": "数值",
"mods": "模组",
"copies": "客户端", "copies": "客户端",
"settings": "设置", "settings": "设置",
"about": "关于" "about": "关于"
@@ -96,7 +97,9 @@
}, },
"decals": { "decals": {
"source": "贴花来源", "source": "贴花来源",
"hint": "可导入在线版游戏的 cache/content。未导入时使用占位贴花。", "hint": "可直接选择在线版游戏根目录、cache 或 cache/content,同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
"autoDetectedNotice": "已自动检测到在线版贴花缓存,安装时将一并导入。如需使用占位贴花,可点击上方按钮取消。",
"importFromSource": "从在线版来源导入",
"choose": "选择贴花缓存…", "choose": "选择贴花缓存…",
"useDefault": "使用占位贴花", "useDefault": "使用占位贴花",
"importing": "正在导入贴花缓存", "importing": "正在导入贴花缓存",
@@ -157,7 +160,8 @@
"copy": "复制安装(推荐)", "copy": "复制安装(推荐)",
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。", "copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
"spaceSaving": "节省空间的复制", "spaceSaving": "节省空间的复制",
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。", "spaceSavingBody": "资源包通过同盘硬链接与在线版共享,仅需额外复制约 {{size}};Windows 资源管理器「属性」会重复统计共享文件大小,实际只占新增复制的磁盘空间。原版就地更新可能改变共享文件。",
"spaceSavingBreakdown": "预计实际复制约 {{copy}} · 硬链接共享约 {{shared}}(不额外占用磁盘空间)",
"spaceSavingPending": "正在估算可节省的空间。", "spaceSavingPending": "正在估算可节省的空间。",
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。", "spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。", "sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
@@ -213,6 +217,8 @@
"recording": "完成安装" "recording": "完成安装"
}, },
"copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", "copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
"copiedActual": "实际复制:已复制 {{copied}} / {{copyTotal}}({{copiedFiles}} / {{copyTotalFiles}} 个文件)",
"linkedShared": "硬链接共享(不额外占空间):已链接共享 {{linked}} / {{linkTotal}}({{linkedFiles}} / {{linkTotalFiles}} 个资源包)",
"verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", "verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
"prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", "prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件",
"cancelHint": "可随时取消,已复制的文件将被删除", "cancelHint": "可随时取消,已复制的文件将被删除",
@@ -230,11 +236,18 @@
"missingFolder": "目录不存在", "missingFolder": "目录不存在",
"relocate": "重新定位…", "relocate": "重新定位…",
"relocateDialogTitle": "选择挪动后的客户端文件夹", "relocateDialogTitle": "选择挪动后的客户端文件夹",
"list": { "current": "当前", "select": "设为当前" }, "list": {
"current": "当前",
"select": "设为当前"
},
"none": "尚未安装离线版。", "none": "尚未安装离线版。",
"maintenance": { "maintenance": {
"update": "从在线版更新", "update": "从在线版更新",
"updateAction": "更新客户端", "updateAction": "更新客户端",
"setSource": "设置来源…",
"changeSource": "更换来源…",
"chooseSource": "选择在线版安装目录",
"sourceNotSet": "尚未设置在线版安装来源。",
"newVersion": "安装来源已更新至 {{version}}。", "newVersion": "安装来源已更新至 {{version}}。",
"updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。", "updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。",
"updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。", "updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。",
@@ -250,16 +263,31 @@
"repair": "修复客户端", "repair": "修复客户端",
"repairAction": "修复", "repairAction": "修复",
"repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。", "repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。",
"delete": "删除客户端", "remove": "移除客户端",
"deleteAction": "删除…", "removeAction": "移除…",
"deleteHint": "默认保留数据目录。", "removeCopyHint": "默认仅从启动器列表移除,不会删除磁盘文件。",
"unlink": "解除登记", "removeRestoreHint": "默认仅从启动器列表移除;也可选还原为原版并清理离线补丁文件(保留游戏本体)。",
"unlinkAction": "解除登记…", "removeUnlinkHint": "仅从启动器列表移除,不会删除磁盘上的游戏文件。",
"unlinkHint": "Steam 游戏文件和数据目录将留在原处。", "removeSteamHint": "仅从启动器列表移除,Steam 游戏文件和数据目录将留在原处。",
"unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。", "removeCopyNotice": "将从启动器列表移除 {{path}}。默认保留磁盘上的所有游戏文件和数据。",
"deleteLocation": "确认删除 {{path}} 中的离线客户端?", "removeListOnlyNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的游戏文件。",
"deleteData": "同时删除 {{path}} 中的数据", "removeSteamNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的 Steam 游戏文件和数据目录。",
"confirm": "确认删除", "originCopy": "识别结果:完整复制副本(由启动器独立复制创建)。",
"originHardlink": "识别结果:省空间硬链接副本(只读资源包与原版共享,删除副本不会影响原版游戏目录)。",
"originInPlace": "识别结果:原位安装目录(为保护原版游戏本体,不支持直接删除整个文件夹)。",
"originUnknown": "识别结果:未知来源的已有目录(缺少客户端身份标记,为保护游戏文件不支持直接删除整个文件夹)。",
"originUnknownHardlinked": "识别结果:未知来源的已有目录(检测到硬链接资源包,但缺少客户端身份标记;为保护原版目录不支持直接删除整个文件夹)。",
"deleteFiles": "同时删除客户端文件夹 {{path}}",
"deleteHardlinkHint": "提示:此客户端使用同盘硬链接共享资源包,删除副本文件夹不会影响原版游戏目录。",
"deleteFilesWarning": "将永久删除客户端副本文件夹 {{path}} 中的全部文件,此操作无法撤销。",
"deleteHardlinkWarning": "将永久删除硬链接副本文件夹 {{path}} 中的全部文件(不会影响原版游戏目录),此操作无法撤销。",
"restoreStock": "还原为原版并清理离线补丁文件(保留游戏本体)",
"restoreStockHint": "将从 wtoffline\\stock 恢复原版 4 个核心文件,并删除 wtoffline\\ 目录与网络钩子文件(wto_ws.dll / wto_ws.cfg / wto_ws.log),绝不删除其他游戏本体文件。",
"deleteData": "同时删除数据文件夹 {{path}}(包含存档、配置与日志)",
"openFolder": "打开所在文件夹",
"confirmRemove": "从列表移除",
"confirmRestore": "还原并移除",
"confirmDelete": "确认删除",
"phase": { "phase": {
"checking": "正在检查客户端", "checking": "正在检查客户端",
"copying": "正在复制有变化的文件", "copying": "正在复制有变化的文件",
@@ -267,11 +295,12 @@
}, },
"result": { "result": {
"confirm-steam": "已确认 Steam 目录。", "confirm-steam": "已确认 Steam 目录。",
"set-source": "在线版安装来源已保存。",
"check": "补丁检查已完成。", "check": "补丁检查已完成。",
"repair": "原版文件已还原。", "repair": "原版文件已还原。",
"update": "客户端已更新。", "update": "客户端已更新。",
"compact": "省空间转换已完成。", "compact": "省空间转换已完成。",
"delete": "客户端已删除。", "delete": "客户端已移除。",
"cancelled": "维护已取消。" "cancelled": "维护已取消。"
} }
}, },
@@ -341,8 +370,7 @@
"country": "国家", "country": "国家",
"type": "兵种", "type": "兵种",
"actions": "批量操作", "actions": "批量操作",
"research": "全部研发", "purchase": "全部研发并购买",
"purchase": "获得常规载具",
"equipment": "解锁改装件", "equipment": "解锁改装件",
"empty": "此客户端没有可编辑的研发分支。", "empty": "此客户端没有可编辑的研发分支。",
"rank": "等级 {{rank}}", "rank": "等级 {{rank}}",
@@ -436,7 +464,8 @@
"premiumDays": "高级账户剩余天数", "premiumDays": "高级账户剩余天数",
"avatar": "头像", "avatar": "头像",
"avatarUnavailable": "头像不可用", "avatarUnavailable": "头像不可用",
"level": "账号等级",␍ "apply": "保存更改", "level": "账号等级",
"apply": "保存更改",
"saved": "更改已保存。", "saved": "更改已保存。",
"noBattles": "此存档没有对局记录。", "noBattles": "此存档没有对局记录。",
"win": "胜利", "win": "胜利",
@@ -449,6 +478,7 @@
"sections": { "sections": {
"rewards": "收益", "rewards": "收益",
"battle": "对局", "battle": "对局",
"bots": "Bot 参数",
"newProfile": "新存档", "newProfile": "新存档",
"research": "研发" "research": "研发"
}, },
@@ -460,9 +490,11 @@
"smallTeamsMaxPlayers": "小规模模式人数上限", "smallTeamsMaxPlayers": "小规模模式人数上限",
"brSpreadMrank": "匹配范围", "brSpreadMrank": "匹配范围",
"subModeChance": "附加模式概率", "subModeChance": "附加模式概率",
"botPoolLimitPerType": "每类载具 AI 候选池上限",
"tankBotRespawns": "AI 坦克重生次数", "tankBotRespawns": "AI 坦克重生次数",
"airBotRespawns": "AI 飞机重生次数", "airBotRespawns": "AI 飞机重生次数",
"strikeUcavSpawnScore": "打击无人机所需出生点数", "strikeUcavSpawnScore": "打击无人机所需出生点数",
"nuclearEscalationStrategicBombers": "核战冲突启用第 3 阶段战略核轰炸机(B-52H / Tu-95M)",
"silverLions": "初始银狮", "silverLions": "初始银狮",
"goldenEagles": "初始金鹰", "goldenEagles": "初始金鹰",
"preferLineSuccessor": "优先研发同系载具", "preferLineSuccessor": "优先研发同系载具",
@@ -473,6 +505,225 @@
"highestRank": "最高等级", "highestRank": "最高等级",
"treeOrder": "研发树顺序" "treeOrder": "研发树顺序"
}, },
"expandAll": "展开全部高级项",
"collapseAll": "折叠高级项",
"botModeHint": "新版陆战 AI 处于实验调优阶段;若遇到异常可切回「原版 AI」。修改会在下次启动游戏重建数据包时生效。",
"botStockNotice": "当前为「原版 AI」模式:不注入自定义陆战 AI 脚本,下方出车权重与自定义 AI 参数不会生效(重生次数与候选池上限仍生效)。",
"botModes": {
"full": "完整新版 AI(默认,实验性)",
"fire": "仅火控与感知(原版移动)",
"drive": "仅指挥与机动(原版瞄准开火)",
"stock": "原版 AI(停用自定义陆战 AI)"
},
"botDriveModes": {
"vehicle_phys": "物理操控(vehicle_phys)",
"movesys": "原版移动系统(movesys)"
},
"botSteer": {
"normal": "正向(1)",
"inverted": "反向(-1)"
},
"botGroups": {
"general": "基础与模式",
"lineupWeights": "陆战 AI 出车权重",
"loadout": "陆战 AI 出生携弹",
"commander": "指挥层与分路配额",
"macro": "宏观占点与防空",
"stateMachine": "单车状态机与掩体维修",
"perception": "视觉感知与曝光",
"tactics": "态势感知与目标记忆",
"estimation": "目击测速与瞄准偏差",
"fireControl": "火控与开火许可",
"navigation": "机动与寻路控制",
"crowd": "编队间距与避让",
"terrain": "地形与棱线约束",
"runtime": "运行频率与诊断"
},
"botGroupHints": {
"general": "AI 模式切换、重生次数与候选载具池",
"lineupWeights": "各类地面载具相对抽取权重(非原版模式生效)",
"loadout": "待发架携弹量与主/副弹种分配",
"commander": "各模式进攻 / 侧翼 / 架枪比例、集结与回防",
"macro": "开局分兵、占点人数、死亡区规避与防空站位",
"stateMachine": "短停预算、装填回缩、摆角、换位与受损维修",
"perception": "植被透光、曝光累计速度与衰减",
"tactics": "视距、听觉发现范围、电台共享与记忆时长",
"estimation": "本车目击测速、守出口时长与自然散布",
"fireControl": "距离分档、车速门槛、稳定等待与弹道防误伤",
"navigation": "底层驱动方式、转向刹车与脱困倒车",
"crowd": "友军安全间距与扎堆疏散",
"terrain": "爬坡 / 下坡角度、涉水深度与探头限制",
"runtime": "脚本刷新间隔与调试遥测日志"
},
"botFields": {
"mode": "陆战 AI 模式",
"lineupWeights": {
"mediumTank": "中型坦克 / 主战坦克权重",
"heavyTank": "重型坦克权重",
"tankDestroyer": "坦克歼击车权重",
"lightTank": "轻型坦克权重",
"spaa": "自行防空车权重",
"other": "其他地面载具权重"
},
"loadout": {
"lowReadyRackThreshold": "低待发架补弹阈值(发)",
"topUpAmmoCount": "补弹目标总数(发)",
"primaryAmmoPct": "主穿甲弹携带占比",
"secondaryMinRounds": "副高爆 / 破甲弹最少发数",
"penetrationCompareDistM": "弹种穿深对比距离"
},
"commander": {
"rebalanceSec": "角色重分配周期",
"roleHoldSec": "角色最短保持时间",
"bttlAssaultPct": "坚守模式进攻占比",
"bttlFlankPct": "坚守模式侧翼占比",
"bttlOverwatchPct": "坚守模式架枪占比",
"conqAssaultPct": "征服模式进攻占比",
"conqFlankPct": "征服模式侧翼占比",
"conqHoldDefendPct": "征服持点防守占比",
"conqHoldOverwatchPct": "征服持点架枪占比",
"domAssaultPct": "制霸模式进攻占比",
"domMaxDefendersPerCap": "制霸单点最多守点车数",
"overwatchStandOffM": "架枪掩护距点距离",
"flankStandOffM": "侧翼包抄距点距离",
"spaaFollowOffsetM": "防空车跟随主攻偏移距离",
"flankMaxLengthRatio": "侧路最大绕行倍率",
"flankMinSeparationM": "侧路最小横向间距",
"rallyProgressFrac": "集结点推进比例(0.1–0.75)",
"rallyWaitSec": "集结最长等待时间",
"rallyMinFrac": "集结出发最低成队比例",
"rallyRadiusM": "集结点判定半径",
"recallSafeHoldSec": "点位安全后恢复进攻延迟"
},
"macro": {
"openingSplitSec": "开局分兵持续时间",
"capMaxInsiders": "单占领圈内最多进入车数",
"recaptureMinBots": "抢点 / 回防最少抽调车数",
"recaptureMaxBots": "抢点 / 回防最多抽调车数",
"capStickyBonusM": "当前目标点距离粘性加成",
"deathZoneRadiusM": "高危死亡区半径",
"deathZoneTtlSec": "高危死亡区记忆时长",
"deathZoneMinKills": "触发死亡区最少阵亡数",
"spaaRearOffsetM": "防空车后方阵位距离",
"spaaRelocateSec": "防空车换位周期",
"enemySpawnAvoidM": "敌方出生点规避距离"
},
"stateMachine": {
"preaimAngleDeg": "行进预瞄角度阈值",
"movingShotWaitSec": "转入短停前尝试行进射击的时间",
"shortHaltMaxSec": "单次短停最长时间",
"shortHaltCooldownSec": "短停冷却时间",
"turnLaunchSpeedMps": "甩弯起步目标车速",
"coverMinDistM": "掩体搜索最小距离",
"coverMaxDistM": "掩体搜索最大距离",
"coverRetreatBudgetSec": "装填回缩掩体最长用时",
"reloadAdvanceAngleDeg": "装填折线跃进偏角",
"hullAngleTriggerDeg": "触发车体摆角阈值",
"hullAngleTargetDeg": "车体目标摆角",
"maxTotalHaltSec": "累计停留强制换位上限",
"stalemateMissShots": "无伤害连射触发换位发数",
"stalemateNoShotHalts": "未开火短停触发换位次数",
"repositionMinMoveM": "换位解锁短停最小位移",
"repositionStepM": "侧翼换位步进距离",
"repairSafeEnemyDistM": "维修安全敌距阈值"
},
"perception": {
"foliageTransparency": "植被透光系数",
"nearSpotRangeM": "近距快速发现距离",
"firingSpotRangeM": "敌车开火暴露距离",
"fastSpotSec": "近距 / 开火曝光用时",
"normalSpotSec": "常规曝光用时",
"farSpotSec": "远距曝光用时",
"decayPerSec": "失联曝光每秒衰减率",
"frontConeHalfDeg": "前向主视锥半角",
"peripheralCloseM": "近身余光发现距离"
},
"tactics": {
"visionRangeM": "最大视觉索敌距离",
"visionFovDeg": "视野总张角",
"peripheralRangeM": "外围余光索敌距离",
"engineAudioRangeM": "引擎声听觉距离",
"shotAudioRangeM": "炮声听觉距离",
"radioShareRangeM": "友军电台报点共享距离",
"memoryTtlSec": "目标失联记忆时长",
"targetStickinessSec": "目标锁定粘性时长",
"peekCooldownSec": "探头射击冷却时间"
},
"estimation": {
"watchMinSec": "失联守出口最短时长",
"watchMaxSec": "失联守出口最长时长",
"velSampleMinSpanSec": "测速最小采样跨度",
"velStableSpanSec": "测速稳定收敛跨度",
"velJumpResetMps": "急刹 / 变速重置阈值",
"baseAimSigmaM": "基础瞄准散布标准差",
"leadErrorFrac": "提前量误差比例",
"maxBiasM": "单次射击最大偏移上限"
},
"fireControl": {
"maxEngageRangeM": "最大交战开火距离",
"closeRangeM": "近距交战分界距离",
"midRangeM": "中距交战分界距离",
"longRangeM": "远距交战分界距离",
"midSlowSpeedRatio": "中距行进射击最高车速比",
"midSlowMaxMps": "中距行进射击最高车速",
"closeRangeMaxSpeedKmh": "近距分界处行进射击最高车速",
"pointBlankMaxSpeedKmh": "贴身时行进射击最高车速",
"stopSpeedMaxMps": "停稳判定最高车速",
"longRangeWindowSec": "远距连续射界观察窗",
"baseAlignDeg": "主炮对准允许角误差",
"closeHitRadiusM": "近距命中判定半径",
"barrelSettleDegSec": "近距以外瞄准误差最大变化速度",
"closeSettleHoldSec": "近距稳定保持时间",
"settleHoldSec": "常规稳定保持时间",
"unstabilizedStopSpeedMps": "无稳定器停稳车速上限",
"stabilizedCreepSpeedMps": "带稳定器慢速射击上限",
"friendlyCorridorM": "友军弹道禁射走廊宽度",
"ballisticStepMaxM": "弹道硬遮挡检测步长",
"ballisticSweepRadiusM": "弹道扫掠半径",
"maxPreFireChecksPerTick": "每帧精查开火预算上限"
},
"navigation": {
"driveMode": "车体驱动模式",
"maxPhysBots": "物理接管最大 AI 车数",
"steerSign": "转向输入方向",
"deadEchoSec": "无响应回声判定时长",
"controlTimeoutSec": "原生控制超时归还时长",
"cornerBrakeAccel": "弯道减速制动强度",
"movingFireSpeedRampMps": "行进射击时全油门或全制动对应的速度差",
"pivotAngleDeg": "原地中性转向角度阈值",
"stuckWindowSec": "卡死检测窗口时长",
"stuckMinMoveM": "卡死判定最小位移",
"unstickReverseSec": "脱困倒车持续时长",
"tacticalReverseDistM": "战术倒车最大距离",
"tacticalReverseMaxSec": "战术倒车最长时长"
},
"crowd": {
"personalSpaceM": "单车安全个人空间",
"clusterRadiusM": "扎堆检测半径",
"clusterMaxAllies": "扎堆允许最多友车数",
"disperseStepM": "疏散移动步距",
"disperseHoldSec": "疏散指令保持时长"
},
"terrain": {
"maxClimbSlopeDeg": "最大允许爬坡角度",
"maxDropSlopeDeg": "最大允许下坡角度",
"maxWaterDepthM": "最大允许涉水深度",
"collisionMarginM": "障碍物碰撞安全余量",
"crestLookaheadM": "山脊棱线前瞻距离",
"ridgeMaxDwellSec": "棱线最长停留时长",
"ridgeMaxShots": "棱线最多射击发数"
},
"cadence": {
"maxBots": "脚本托管最大 AI 车数",
"macroTickSec": "指挥层刷新间隔",
"tacticsTickSec": "战术与火控刷新间隔",
"navTickSec": "寻路与驾驶刷新间隔"
},
"diagnostics": {
"telemetry": "输出 AI 诊断遥测日志",
"telemetryIntervalSec": "遥测日志输出间隔"
}
},
"shared": "这些数值适用于此客户端的全部存档。", "shared": "这些数值适用于此客户端的全部存档。",
"nextLaunch": "更改将在下次启动本地服务器时生效。", "nextLaunch": "更改将在下次启动本地服务器时生效。",
"reset": "恢复本页默认值", "reset": "恢复本页默认值",
@@ -494,7 +745,7 @@
"appUpdates": "启动器本体更新", "appUpdates": "启动器本体更新",
"appUpdatesToggle": "启动时检查本体更新", "appUpdatesToggle": "启动时检查本体更新",
"patchPacks": "适配包更新", "patchPacks": "适配包更新",
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。", "patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布。",
"updateMirror": "备用更新仓库", "updateMirror": "备用更新仓库",
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。", "updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。", "updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
@@ -629,6 +880,9 @@
"download": "下载更新", "download": "下载更新",
"install": "退出并安装", "install": "退出并安装",
"installing": "正在打开安装包…", "installing": "正在打开安装包…",
"viewNotes": "查看更新说明",
"notesTitle": "版本 {{version}} 更新说明",
"closeNotes": "关闭",
"errors": { "errors": {
"network": "暂时无法访问更新源。", "network": "暂时无法访问更新源。",
"page_limit": "无法确认是否有新版本。", "page_limit": "无法确认是否有新版本。",
@@ -638,7 +892,17 @@
} }
}, },
"statement": "项目信息", "statement": "项目信息",
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。" "statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。",
"homepage": {
"title": "项目主页",
"hint": "查看项目介绍、全部版本与社区入口。",
"open": "打开主页"
},
"community": {
"discord": "Discord",
"discordHint": "开发讨论、日常交流、使用求助与问题反馈。",
"openDiscord": "打开 Discord"
}
}, },
"features": { "features": {
"A-Offline startup": "离线启动", "A-Offline startup": "离线启动",
@@ -661,6 +925,7 @@
"J-Ground arcade and realistic": "陆战(街机、历史)", "J-Ground arcade and realistic": "陆战(街机、历史)",
"J-Air arcade and realistic": "空战(街机、历史)", "J-Air arcade and realistic": "空战(街机、历史)",
"J-Naval arcade and realistic": "海战(街机、历史)", "J-Naval arcade and realistic": "海战(街机、历史)",
"E-Crew skills in battle": "战局乘员技能与资格",
"J-Sub-modes": "附加模式(如夜战)", "J-Sub-modes": "附加模式(如夜战)",
"K-AI opponents and teammates": "AI 对手与队友", "K-AI opponents and teammates": "AI 对手与队友",
"K-Spawn score and respawns": "出生点数与重生", "K-Spawn score and respawns": "出生点数与重生",
@@ -674,6 +939,96 @@
"L-Debriefing": "战后结算", "L-Debriefing": "战后结算",
"L-Battle awards": "战斗嘉奖" "L-Battle awards": "战斗嘉奖"
}, },
"mods": {
"sections": {
"list": "模组列表",
"presets": "预设与仓库"
},
"loading": "正在读取模组信息…",
"noCopy": "请先安装或选择一个离线客户端,再为它配置模组。",
"enabledSummary": "已启用 {{enabled}} / {{total}}",
"experimentalChip": "实验功能",
"experimentalTitle": "实验期模组接口提示:",
"experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。",
"readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。",
"searchPlaceholder": "搜索模组名称、ID 或作者…",
"autoSort": "按依赖自动排序",
"autoSorted": "已按前置与排序建议重新排列模组顺序。",
"refresh": "刷新",
"openFolder": "打开模组目录",
"openDocs": "开发文档",
"discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:",
"blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):",
"issuesTitle": "检测到 {{count}} 项模组提示或冲突:",
"severity": {
"error": "错误",
"warning": "警告",
"info": "提示"
},
"emptyTitle": "当前模组目录里还没有模组。",
"emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。",
"noSearchMatch": "没有匹配当前搜索条件的模组。",
"loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)",
"moveUp": "上移",
"moveDown": "下移",
"showDetails": "详情",
"hideDetails": "收起",
"errorCount": "{{count}} 错误",
"warnCount": "{{count}} 警告",
"badges": {
"data": "数据/资源",
"gui": "界面补丁",
"script": "服务端脚本",
"exe": "二进制补丁"
},
"details": {
"folder": "目录",
"gameVersions": "声明适配版本",
"requires": "前置依赖",
"conflicts": "已知互斥",
"tuning": "服务端数值叠加:{{count}} 份",
"serverScript": "含可执行服务端 JS/TS 脚本",
"packOps": "客户端数据包操作:{{count}} 项",
"addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件",
"guiPatches": "界面脚本补丁:{{count}} 项",
"exePatches": "声明式 exe 补丁:{{count}} 项",
"companionFiles": "附带外置文件:{{count}} 个",
"configBlk": "含 config.blk 增量补丁"
},
"presets": {
"heading": "模组序列预设(当前客户端独立保存)",
"description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。",
"quickSwitch": "快速切换模组预设",
"customOption": "当前自定义配置",
"namePlaceholder": "输入新预设名称,例如:现代载具包",
"saveCurrent": "保存为预设",
"import": "导入预设…",
"empty": "当前客户端尚未保存任何模组预设。",
"activeTag": "当前使用",
"summary": "启用 {{count}} / 共 {{total}} 个模组",
"apply": "应用",
"overwrite": "覆盖更新",
"export": "导出",
"delete": "删除",
"saved": "已保存预设「{{name}}」。",
"applied": "已切换至预设「{{name}}」。",
"updated": "已用当前配置覆盖预设「{{name}}」。",
"exported": "预设已导出到:{{path}}",
"imported": "已导入模组预设。"
},
"repo": {
"heading": "全局模组仓库位置",
"description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。",
"pathLabel": "当前仓库目录",
"defaultNote": "使用启动器默认模组目录",
"customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)",
"changeFolder": "更改目录…",
"resetDefault": "恢复默认目录",
"pickTitle": "选择全局模组仓库目录",
"updated": "已更新全局模组仓库目录。",
"resetDone": "已恢复为默认模组仓库目录。"
}
},
"errors": { "errors": {
"app_update_unavailable": "当前没有可安装的本体更新。", "app_update_unavailable": "当前没有可安装的本体更新。",
"app_update_busy": "本体更新操作正在进行。", "app_update_busy": "本体更新操作正在进行。",
@@ -697,14 +1052,21 @@
"save_avatar_invalid": "请选择此客户端中可用的头像。", "save_avatar_invalid": "请选择此客户端中可用的头像。",
"save_level_invalid": "请输入此客户端支持的账号等级。", "save_level_invalid": "请输入此客户端支持的账号等级。",
"tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。", "tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。",
"mods_read_only": "游戏、本地服务器或维护任务运行期间无法修改模组配置。",
"mods_write_failed": "无法保存模组配置,请查看启动器日志。",
"mods_preset_invalid": "所选文件不是有效的 WTOffline 模组预设。",
"mods_blocking_issues": "当前启用的模组存在缺失前置或互斥冲突,请先在「模组」页面处理后再启动。",
"mods_folder_invalid": "所选全局模组目录无效或无法写入。",
"copy_not_found": "所选客户端已不可用。", "copy_not_found": "所选客户端已不可用。",
"copies_write_failed": "无法保存客户端记录。", "copies_write_failed": "无法保存客户端记录。",
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。", "copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。", "decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版游戏根目录、cache 或 cache/content。",
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。", "decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。", "maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。", "maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
"maintenance_no_update": "安装来源没有可用的新版本。", "maintenance_no_update": "安装来源没有可用的新版本。",
"maintenance_source_invalid": "请选择完整的在线版游戏安装目录。",
"maintenance_source_overlap": "在线版安装来源必须与离线客户端和数据目录分开。",
"maintenance_cancelled": "客户端更新已取消。", "maintenance_cancelled": "客户端更新已取消。",
"maintenance_failed": "客户端维护失败。请查看启动器日志。", "maintenance_failed": "客户端维护失败。请查看启动器日志。",
"maintenance_source_changed": "安装来源在更新过程中发生变化。请在在线版更新完成后重试。", "maintenance_source_changed": "安装来源在更新过程中发生变化。请在在线版更新完成后重试。",
@@ -729,6 +1091,7 @@
"launch_server_exited": "本地服务器不可用。", "launch_server_exited": "本地服务器不可用。",
"launch_game_failed": "游戏进程无法启动。请查看启动器日志。", "launch_game_failed": "游戏进程无法启动。请查看启动器日志。",
"launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。", "launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。",
"launch_incomplete_uhq_packs": "客户端包含未下载完整的高清材质包({{packs}}),直接启动会导致贴图读取报错(81110007)。请在 Steam 或官方启动器验证并补完文件后再更新离线客户端,或手动移除离线目录内对应的 content.hq/<包名> 与 content/pkg_<包名>.rq2。",
"settings_write_failed": "无法保存设置。", "settings_write_failed": "无法保存设置。",
"folder_unreadable": "无法读取文件夹:{{path}}", "folder_unreadable": "无法读取文件夹:{{path}}",
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}", "not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
@@ -740,6 +1103,7 @@
"essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}", "essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}",
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。", "missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
"patch_check_failed": "检查补丁时出错。", "patch_check_failed": "检查补丁时出错。",
"launcher_inside_source": "启动器当前位于所选的战争雷霆游戏目录内。请先把启动器移动到游戏目录之外的独立文件夹,然后再试。",
"copy_failed": "复制游戏文件失败,已复制的文件已删除。", "copy_failed": "复制游戏文件失败,已复制的文件已删除。",
"hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。", "hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。",
"hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。", "hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。",
@@ -1,13 +1,15 @@
import { useState } from 'react'; import { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx'; import { Notice } from '../../components/Notice.tsx';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx'; import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts'; import { ipcInvoke } from '../../ipc.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts'; import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { AppUpdateSection } from './AppUpdateSection.tsx'; import { AppUpdateSection } from './AppUpdateSection.tsx';
import type { PatchPackState } from '../../shell/usePatchPack.ts'; import type { PatchPackState } from '../../shell/usePatchPack.ts';
const HOMEPAGE_URL = 'https://wto-project.net';
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
interface AboutPageProps { interface AboutPageProps {
readonly launcherVersion: string; readonly launcherVersion: string;
readonly supportedVersions: readonly string[]; readonly supportedVersions: readonly string[];
@@ -17,7 +19,7 @@ interface AboutPageProps {
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
/** The launcher's version, the game versions it supports, adaptation pack updates, log export, and the project statement. */ /** 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, appUpdate, loggingEnabled, onError }: AboutPageProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
@@ -30,15 +32,59 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
{t('about.supported', { versions: supportedVersions.join(', ') })} {t('about.supported', { versions: supportedVersions.join(', ') })}
</div> </div>
</div> </div>
<div className="about-columns">
<div className="about-column">
<AppUpdateSection state={appUpdate} /> <AppUpdateSection state={appUpdate} />
<PatchPackSection state={patchPack} /> <PatchPackSection state={patchPack} />
</div>
<div className="about-column">
<HomepageSection />
<CommunitySection />
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} /> <FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3> <section className="about-card">
<p className="lead">{t('about.statementBody')}</p> <h3 className="about-card-title">{t('about.statement')}</h3>
<p className="about-card-meta">{t('about.statementBody')}</p>
</section>
</div>
</div>
</Sheet> </Sheet>
); );
} }
function HomepageSection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.homepage.title')}</h3>
<div className="about-card-actions">
<a className="button" href={HOMEPAGE_URL} target="_blank" rel="noreferrer">
{t('about.homepage.open')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.homepage.hint')}</p>
</section>
);
}
function CommunitySection() {
const { t } = useTranslation();
return (
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.community.discord')}</h3>
<div className="about-card-actions">
<a className="button" href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
{t('about.community.openDiscord')}
</a>
</div>
</div>
<p className="about-card-meta">{t('about.community.discordHint')}</p>
</section>
);
}
function FeedbackLogsSection({ loggingEnabled, onError }: { function FeedbackLogsSection({ loggingEnabled, onError }: {
readonly loggingEnabled: boolean; readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
@@ -61,16 +107,19 @@ function FeedbackLogsSection({ loggingEnabled, onError }: {
} }
return ( return (
<> <section className="about-card">
<h3 className="section-title section-title-spaced">{t('about.feedback.title')}</h3> <div className="about-card-head">
<Row label={t('about.feedback.export')} hint={t('about.feedback.exportHint')}> <h3 className="about-card-title">{t('about.feedback.title')}</h3>
<div className="about-card-actions">
<button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}> <button type="button" className="button" disabled={exporting} onClick={() => { void save(); }}>
{t('about.feedback.exportButton')} {t('about.feedback.exportButton')}
</button> </button>
</Row> </div>
</div>
<p className="about-card-meta">{t('about.feedback.exportHint')}</p>
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>} {!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>} {savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</> </section>
); );
} }
@@ -85,25 +134,30 @@ function PatchPackSection({ state }: { readonly state: PatchPackState }) {
? t('about.pack.bundledVersion', { version: active.version }) ? t('about.pack.bundledVersion', { version: active.version })
: t('about.pack.bundled'); : t('about.pack.bundled');
return ( return (
<> <section className="about-card">
<h3 className="section-title">{t('about.pack.title')}</h3> <div className="about-card-head">
<Row label={t('about.pack.current')} hint={t('about.pack.currentHint')}> <h3 className="about-card-title">{t('about.pack.title')}</h3>
<span>{current}</span> <div className="about-card-actions">
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
</button>
{active?.source === 'downloaded' && ( {active?.source === 'downloaded' && (
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}> <button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
{t('about.pack.useBundled')} {t('about.pack.useBundled')}
</button> </button>
)} )}
</Row> </div>
<Row label={t('about.pack.check')} hint={t('about.pack.checkHint')}> </div>
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}> <p className="about-card-meta">
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')} <span className="about-card-label">{t('about.pack.current')}</span>
</button> {' · '}
</Row> {current}
</p>
<p className="small">{t('about.pack.currentHint')}</p>
{busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>} {busy === 'applying' && <p className="small">{t('about.pack.applying')}</p>}
{state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>} {state.applyFailure && <Notice tone="error"><p>{t(`about.pack.applyFailed.${state.applyFailure}`)}</p></Notice>}
{check && busy !== 'checking' && <CheckResult state={state} />} {check && busy !== 'checking' && <CheckResult state={state} />}
</> </section>
); );
} }
@@ -1,48 +1,72 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx'; import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx'; import { ProgressBar } from '../../components/ProgressBar.tsx';
import { Row } from '../../components/Row.tsx';
import { formatBytes } from '../../format.ts'; import { formatBytes } from '../../format.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts'; import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { ReleaseNotesModal } from './ReleaseNotesModal.tsx';
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) { export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [notesOpen, setNotesOpen] = useState(false);
if (!state.supported) return null; if (!state.supported) return null;
const { check, busy, progress } = state; const { check, busy, progress } = state;
const available = check?.status === 'available' && busy !== 'checking' ? check : null;
const notes = available?.release.notes.trim() ?? '';
return ( return (
<> <section className="about-card">
<h3 className="section-title">{t('about.update.title')}</h3> <div className="about-card-head">
<Row label={t('about.update.check')}> <h3 className="about-card-title">{t('about.update.title')}</h3>
<div className="about-card-actions">
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}> <button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')} {t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
</button> </button>
</Row> </div>
</div>
<p className="about-card-meta">{t('about.update.check')}</p>
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>} {check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>} {check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
{check?.status === 'available' && busy !== 'checking' && ( {available && (
<Notice tone="info"> <Notice tone="info">
<p>{t('about.update.available', { version: check.release.version, size: formatBytes(check.release.size) })}</p> <p>{t('about.update.available', { version: available.release.version, size: formatBytes(available.release.size) })}</p>
{check.release.notes && <p className="small update-notes">{check.release.notes}</p>} {busy === 'downloading' && (
{busy === 'downloading' ? (
<> <>
<p>{t('about.update.downloading')}</p> <p>{t('about.update.downloading')}</p>
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} /> <ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
</> </>
) : ( )}
{(busy !== 'downloading' || notes) && (
<div className="update-actions">
{busy !== 'downloading' && (
<button <button
type="button" type="button"
className="button button-primary" className="button button-primary"
disabled={busy !== null} disabled={busy !== null}
onClick={() => { onClick={() => {
if (check.ready) state.install(check.release.version); if (available.ready) state.install(available.release.version);
else state.download(check.release.version); else state.download(available.release.version);
}} }}
> >
{t(busy === 'installing' ? 'about.update.installing' : check.ready ? 'about.update.install' : 'about.update.download')} {t(busy === 'installing' ? 'about.update.installing' : available.ready ? 'about.update.install' : 'about.update.download')}
</button> </button>
)} )}
{notes && (
<button type="button" className="button button-compact" onClick={() => setNotesOpen(true)}>
{t('about.update.viewNotes')}
</button>
)}
</div>
)}
</Notice> </Notice>
)} )}
</> {notesOpen && available && notes && (
<ReleaseNotesModal
version={available.release.version}
notes={notes}
onClose={() => setNotesOpen(false)}
/>
)}
</section>
); );
} }
@@ -0,0 +1,57 @@
import { useEffect, useId } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { MarkdownContent } from '../../components/MarkdownContent.tsx';
interface ReleaseNotesModalProps {
readonly version: string;
readonly notes: string;
readonly onClose: () => void;
}
/** Standalone dialog displaying rendered Markdown release notes for an available launcher update. */
export function ReleaseNotesModal({ version, notes, onClose }: ReleaseNotesModalProps) {
const { t } = useTranslation();
const titleId = useId();
useEffect(() => {
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') onClose();
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [onClose]);
return createPortal(
<div
className="modal-backdrop"
role="presentation"
onClick={(event) => {
if (event.target === event.currentTarget) onClose();
}}
>
<div className="modal-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId}>
<header className="modal-head">
<h3 id={titleId} className="modal-title">{t('about.update.notesTitle', { version })}</h3>
<button
type="button"
className="modal-close"
aria-label={t('about.update.closeNotes')}
onClick={onClose}
>
×
</button>
</header>
<div className="modal-body">
<MarkdownContent markdown={notes} />
</div>
<footer className="modal-foot">
<button type="button" className="button" onClick={onClose}>
{t('about.update.closeNotes')}
</button>
</footer>
</div>
</div>,
document.body,
);
}
@@ -1,59 +1,53 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import type { IpcInput } from '@shared/ipc/contract.ts';
import type { InstallRecord } from '@shared/schemas/install.ts'; import type { InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; import type { MaintenanceInfo, MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { ProgressBar } from '../../components/ProgressBar.tsx'; import { ProgressBar } from '../../components/ProgressBar.tsx';
import { Sheet } from '../../components/Sheet.tsx'; import { Sheet } from '../../components/Sheet.tsx';
import { formatBytes } from '../../format.ts'; import { formatBytes } from '../../format.ts';
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts'; import { ipcInvoke } from '../../ipc.ts';
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx'; import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
import type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
interface CopyMaintenanceProps { interface CopyMaintenanceProps {
readonly record: InstallRecord; readonly record: InstallRecord;
readonly maintenance: CopyMaintenanceState;
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
type Operation = MaintenanceRequest['operation']; export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
type OperationOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [info, setInfo] = useState<MaintenanceInfo | null>(null); const [info, setInfo] = useState<MaintenanceInfo | null>(null);
const [working, setWorking] = useState<Operation | null>(null);
const [progress, setProgress] = useState<MaintenanceProgress | null>(null);
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null); const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
const [result, setResult] = useState<Operation | 'cancelled' | null>(null);
useEffect(() => {
setRemoval(null);
}, [record.id]);
useEffect(() => { useEffect(() => {
let mounted = true; let mounted = true;
setInfo(null);
ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => { ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => {
if (mounted) setInfo(value); if (mounted) setInfo(value);
}).catch(onError); }).catch(onError);
return () => { mounted = false; }; return () => { mounted = false; };
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, onError]); }, [record.id, record.gameVersion, record.sourcePath, record.steamLibraryConfirmation, maintenance.revision, onError]);
useEffect(() => ipcOn('event:copy-maintenance', (event) => { const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
if (event.id === record.id) setProgress(event); if (operation === 'delete') setRemoval(null);
}), [record.id]); maintenance.run(record.id, operation, options);
const run = (operation: Operation, options: OperationOptions = {}): void => {
setResult(null);
setWorking(operation);
setProgress(null);
ipcInvoke('copies:maintain', { id: record.id, operation, ...options })
.then(() => {
setResult(operation);
setRemoval(null);
})
.catch((error: unknown) => {
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled');
else onError(error);
})
.finally(() => setWorking(null));
}; };
const busy = working !== null; const chooseUpdateSource = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('copies.maintenance.chooseSource') }).then(({ path }) => {
if (path) run('set-source', { sourcePath: path });
}).catch(onError);
};
const active = maintenance.active;
const busy = active !== null;
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
return ( return (
<Sheet title={t('copies.sections.maintain')} aside={record.name}> <Sheet title={t('copies.sections.maintain')} aside={record.name}>
<CopyMaintenanceActions <CopyMaintenanceActions
@@ -61,6 +55,7 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
info={info} info={info}
busy={busy} busy={busy}
onRun={run} onRun={run}
onChooseSource={chooseUpdateSource}
onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })} onConfirmSteam={(steamLocations) => run('confirm-steam', { steamLocations })}
/> />
<CopyRemoval <CopyRemoval
@@ -69,34 +64,28 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
busy={busy} busy={busy}
options={removal} options={removal}
onOptionsChange={setRemoval} onOptionsChange={setRemoval}
onRemove={(deleteData) => run('delete', { deleteData })} onRemove={(options) => run('delete', options)}
onOpenFolder={() => { ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError); }}
/> />
{working && ( {active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
<MaintenanceStatus
operation={working}
progress={progress}
onCancel={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}
/>
)}
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>} {result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
</Sheet> </Sheet>
); );
} }
interface MaintenanceStatusProps { interface MaintenanceStatusProps {
readonly operation: Operation; readonly progress: MaintenanceProgress;
readonly progress: MaintenanceProgress | null;
readonly onCancel: () => void; readonly onCancel: () => void;
} }
function MaintenanceStatus({ operation, progress, onCancel }: MaintenanceStatusProps) { function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<div className="maintenance-progress" role="status"> <div className="maintenance-progress" role="status">
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p> <p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} /> <ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null} {progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{(operation === 'update' || operation === 'compact') && progress?.phase !== 'applying' && ( {(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
<button type="button" className="button" onClick={onCancel}> <button type="button" className="button" onClick={onCancel}>
{t('wizard.cancel')} {t('wizard.cancel')}
</button> </button>
@@ -12,12 +12,20 @@ interface CopyMaintenanceControlsProps {
interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps { interface CopyMaintenanceActionsProps extends CopyMaintenanceControlsProps {
readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void; readonly onRun: (operation: 'update' | 'compact' | 'check' | 'repair') => void;
readonly onChooseSource: () => void;
readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void; readonly onConfirmSteam: (locations: NonNullable<MaintenanceRequest['steamLocations']>) => void;
} }
export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSteam }: CopyMaintenanceActionsProps) { export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSource, onConfirmSteam }: CopyMaintenanceActionsProps) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const steam = info?.steamLocations; const steam = info?.steamLocations;
const updateHint = info?.sourceVersion
? t(info.updateAvailable
? (record.hardlinkedFiles?.length
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t(record.sourcePath ? (info ? 'copies.maintenance.noSource' : 'copies.maintenance.phase.checking') : 'copies.maintenance.sourceNotSet');
return ( return (
<> <>
{info?.steamConfirmationRequired && steam && ( {info?.steamConfirmationRequired && steam && (
@@ -30,13 +38,10 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
</button> </button>
</Notice> </Notice>
)} )}
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion <Row label={t('copies.maintenance.update')} hint={record.sourcePath ? <>{record.sourcePath}<br />{updateHint}</> : updateHint}>
? t(info.updateAvailable <button type="button" className="button" disabled={busy} onClick={onChooseSource}>
? (record.hardlinkedFiles?.length {t(record.sourcePath ? 'copies.maintenance.changeSource' : 'copies.maintenance.setSource')}
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches') </button>
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t('copies.maintenance.noSource')}>
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'} <button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}> disabled={busy || !info?.updateAvailable} onClick={() => onRun('update')}>
{t('copies.maintenance.updateAction')} {t('copies.maintenance.updateAction')}
@@ -64,44 +69,112 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
} }
export interface CopyRemovalOptions { export interface CopyRemovalOptions {
readonly deleteFiles: boolean;
readonly restoreStock: boolean;
readonly deleteData: boolean; readonly deleteData: boolean;
} }
interface CopyRemovalProps extends CopyMaintenanceControlsProps { interface CopyRemovalProps extends CopyMaintenanceControlsProps {
readonly options: CopyRemovalOptions | null; readonly options: CopyRemovalOptions | null;
readonly onOptionsChange: (options: CopyRemovalOptions | null) => void; readonly onOptionsChange: (options: CopyRemovalOptions | null) => void;
readonly onRemove: (deleteData: boolean) => void; readonly onRemove: (options: CopyRemovalOptions) => void;
readonly onOpenFolder: () => void;
} }
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) { function clientOriginNoteKey(info: MaintenanceInfo): string {
if (info.clientOrigin === 'copy') return 'copies.maintenance.originCopy';
if (info.clientOrigin === 'hardlink') return 'copies.maintenance.originHardlink';
if (info.clientOrigin === 'in-place') return 'copies.maintenance.originInPlace';
return info.hasHardlinkedResources
? 'copies.maintenance.originUnknownHardlinked'
: 'copies.maintenance.originUnknown';
}
export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove, onOpenFolder }: CopyRemovalProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const steam = info?.steamLocations; const steam = info?.steamLocations;
const unlinkOnly = steam?.copyInSteam === true; const copyInSteam = steam?.copyInSteam === true;
const canDeleteData = !unlinkOnly && !steam?.dataInSteam; const dataInSteam = steam?.dataInSteam === true;
const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm'); const canDeleteFiles = info?.canDeleteFiles === true;
const isHardlinkCopy = info?.clientOrigin === 'hardlink';
const canRestoreAndRemove = info !== null && !canDeleteFiles && info.canRestoreAndRemove;
const canDeleteData = info !== null && !copyInSteam && !dataInSteam;
const willDeleteFiles = canDeleteFiles && options?.deleteFiles === true;
const willRestoreStock = canRestoreAndRemove && options?.restoreStock === true;
const willDeleteData = canDeleteData && options?.deleteData === true;
const action = t(
willDeleteFiles || willDeleteData
? 'copies.maintenance.confirmDelete'
: willRestoreStock
? 'copies.maintenance.confirmRestore'
: 'copies.maintenance.confirmRemove',
);
const rowHint = copyInSteam
? t('copies.maintenance.removeSteamHint')
: canDeleteFiles
? t('copies.maintenance.removeCopyHint')
: canRestoreAndRemove
? t('copies.maintenance.removeRestoreHint')
: t('copies.maintenance.removeUnlinkHint');
const confirmNotice = copyInSteam
? t('copies.maintenance.removeSteamNotice', { path: steam?.copyPath ?? record.copyPath })
: canDeleteFiles
? t('copies.maintenance.removeCopyNotice', { path: record.copyPath })
: t('copies.maintenance.removeListOnlyNotice', { path: record.copyPath });
return ( return (
<> <>
<Row label={t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.delete')} <Row label={t('copies.maintenance.remove')} hint={rowHint}>
hint={t(unlinkOnly ? 'copies.maintenance.unlinkHint' : 'copies.maintenance.deleteHint')}> <button type="button" className="button" disabled={busy}
<button type="button" className="button" disabled={busy || !info} onClick={() => onOptionsChange({ deleteFiles: false, restoreStock: false, deleteData: false })}>
onClick={() => onOptionsChange({ deleteData: false })}> {t('copies.maintenance.removeAction')}
{t(unlinkOnly ? 'copies.maintenance.unlinkAction' : 'copies.maintenance.deleteAction')}
</button> </button>
</Row> </Row>
{options && ( {options && (
<section className="maintenance-confirm" role="group" aria-label={action}> <section className="maintenance-confirm" role="group" aria-label={action}>
<p>{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}</p> <p>{confirmNotice}</p>
{info && <p className="small">{t(clientOriginNoteKey(info))}</p>}
{canDeleteFiles && (
<>
<label className="check">
<input type="checkbox" checked={options.deleteFiles} disabled={busy}
onChange={(event) => onOptionsChange({ ...options, deleteFiles: event.target.checked, restoreStock: false })} />
{t('copies.maintenance.deleteFiles', { path: record.copyPath })}
</label>
{isHardlinkCopy && <p className="small">{t('copies.maintenance.deleteHardlinkHint')}</p>}
</>
)}
{willDeleteFiles && (
<Notice tone="warning">
<p>{t(isHardlinkCopy ? 'copies.maintenance.deleteHardlinkWarning' : 'copies.maintenance.deleteFilesWarning', { path: record.copyPath })}</p>
</Notice>
)}
{canRestoreAndRemove && (
<>
<label className="check">
<input type="checkbox" checked={options.restoreStock} disabled={busy}
onChange={(event) => onOptionsChange({ ...options, restoreStock: event.target.checked, deleteFiles: false })} />
{t('copies.maintenance.restoreStock')}
</label>
<p className="small">{t('copies.maintenance.restoreStockHint')}</p>
</>
)}
{canDeleteData && ( {canDeleteData && (
<label className="check"> <label className="check">
<input type="checkbox" checked={options.deleteData} disabled={busy} <input type="checkbox" checked={options.deleteData} disabled={busy}
onChange={(event) => onOptionsChange({ deleteData: event.target.checked })} /> onChange={(event) => onOptionsChange({ ...options, deleteData: event.target.checked })} />
{t('copies.maintenance.deleteData', { path: record.dataPath })} {t('copies.maintenance.deleteData', { path: record.dataPath })}
</label> </label>
)} )}
<div className="copy-list-actions"> <div className="copy-list-actions">
{!canDeleteFiles && (
<button type="button" className="button" disabled={busy || record.folderMissing === true} onClick={onOpenFolder}>
{t('copies.maintenance.openFolder')}
</button>
)}
<button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button> <button type="button" className="button" disabled={busy} onClick={() => onOptionsChange(null)}>{t('wizard.cancel')}</button>
<button type="button" className="button button-primary" disabled={busy} onClick={() => onRemove(canDeleteData && options.deleteData)}> <button type="button" className="button button-primary" disabled={busy}
onClick={() => onRemove({ deleteFiles: willDeleteFiles, restoreStock: willRestoreStock, deleteData: willDeleteData })}>
{action} {action}
</button> </button>
</div> </div>
@@ -20,13 +20,46 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const [name, setName] = useState(record.name); const [name, setName] = useState(record.name);
const [importing, setImporting] = useState(false); const [importing, setImporting] = useState(false);
const [detectedSourceDecals, setDetectedSourceDecals] = useState<string | null>(null);
useEffect(() => setName(record.name), [record.id, record.name]); useEffect(() => setName(record.name), [record.id, record.name]);
// Read-only probe of the copy's registered online source for a usable decal cache.
useEffect(() => {
setDetectedSourceDecals(null);
if (!record.sourcePath) return;
let current = true;
ipcInvoke('decals:detectSource', { path: record.sourcePath })
.then(({ path }) => {
if (current) setDetectedSourceDecals(path);
})
.catch(() => {
if (current) setDetectedSourceDecals(null);
});
return () => {
current = false;
};
}, [record.id, record.sourcePath]);
const missing = missingFeatures(record).length; const missing = missingFeatures(record).length;
const verified = isVerified(record.gameVersion, supportedVersions); const verified = isVerified(record.gameVersion, supportedVersions);
const importFromSource = async (): Promise<void> => {
if (!detectedSourceDecals) return;
setImporting(true);
try {
await ipcInvoke('copies:setDecalSource', { id: record.id, path: detectedSourceDecals });
} catch (error) {
onError(error);
} finally {
setImporting(false);
}
};
const applyDecals = async (chooseFolder: boolean): Promise<void> => { const applyDecals = async (chooseFolder: boolean): Promise<void> => {
setImporting(true); setImporting(true);
try { try {
const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null; const path = chooseFolder
? (await ipcInvoke('dialog:pickFolder', {
title: t('decals.choose'),
...(record.sourcePath ? { defaultPath: record.sourcePath } : {}),
})).path
: null;
if (chooseFolder && path === null) return; if (chooseFolder && path === null) return;
await ipcInvoke('copies:setDecalSource', { id: record.id, path }); await ipcInvoke('copies:setDecalSource', { id: record.id, path });
} catch (error) { } catch (error) {
@@ -71,6 +104,11 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc
<Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row> <Row label={t('copies.summary.data')} hint={t('copies.summary.dataHint')}>{folder(record.dataPath)}</Row>
<Row label={t('decals.source')} hint={t('decals.hint')}> <Row label={t('decals.source')} hint={t('decals.hint')}>
<span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span> <span>{t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')}</span>
{detectedSourceDecals && (
<button type="button" className="button" disabled={importing} onClick={() => { void importFromSource(); }}>
{t('decals.importFromSource')}
</button>
)}
<button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}> <button type="button" className="button" disabled={importing} onClick={() => { void applyDecals(true); }}>
{t('decals.choose')} {t('decals.choose')}
</button> </button>
@@ -0,0 +1,63 @@
import { useCallback, useEffect, useState } from 'react';
import type { IpcInput } from '@shared/ipc/contract.ts';
import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
export type MaintenanceOperation = MaintenanceRequest['operation'];
export type MaintenanceOptions = Pick<
IpcInput<'copies:maintain'>,
'deleteFiles' | 'restoreStock' | 'deleteData' | 'steamLocations' | 'sourcePath'
>;
export interface MaintenanceOutcome {
readonly copyId: string;
readonly outcome: MaintenanceOperation | 'cancelled';
}
/** Tracks copy maintenance across tab switches so progress and busy state survive unmounting the maintenance page. */
export function useCopyMaintenance(onError: (error: unknown) => void) {
const [active, setActive] = useState<MaintenanceProgress | null>(null);
const [lastResult, setLastResult] = useState<MaintenanceOutcome | null>(null);
const [revision, setRevision] = useState(0);
useEffect(() => {
let mounted = true;
let receivedEvent = false;
const dispose = ipcOn('event:copy-maintenance', (event) => {
receivedEvent = true;
setActive(event);
if (event === null) setRevision((value) => value + 1);
});
ipcInvoke('copies:maintenanceState').then((state) => {
if (mounted && !receivedEvent) setActive(state);
}).catch(onError);
return () => { mounted = false; dispose(); };
}, [onError]);
const run = useCallback((id: string, operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
setLastResult(null);
setActive({ id, operation, phase: 'checking', doneBytes: 0, totalBytes: 0 });
ipcInvoke('copies:maintain', { id, operation, ...options })
.then(() => {
setLastResult({ copyId: id, outcome: operation });
})
.catch((error: unknown) => {
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') {
setLastResult({ copyId: id, outcome: 'cancelled' });
} else {
onError(error);
}
})
.finally(() => {
setActive((current) => (current?.id === id && current.operation === operation ? null : current));
});
}, [onError]);
const cancel = useCallback((): void => {
ipcInvoke('copies:cancelMaintenance').catch(onError);
}, [onError]);
return { active, lastResult, revision, run, cancel };
}
export type CopyMaintenanceState = ReturnType<typeof useCopyMaintenance>;
@@ -80,8 +80,10 @@ export function homeBar(
detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }), detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }),
primary: { label: t('launch.check'), onClick: actions.checkVersion }, primary: { label: t('launch.check'), onClick: actions.checkVersion },
}; };
case 'failed': case 'failed': {
return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_failed'}`), primary: retry }; const key = `errors.${state.error ?? 'launch_failed'}` as const;
return { tone: 'bad', title: state.errorParams ? t(key, state.errorParams) : t(key), primary: retry };
}
case 'ready': case 'ready':
break; break;
} }
@@ -8,6 +8,8 @@ interface DataStepProps {
readonly dataPath: string; readonly dataPath: string;
readonly dataProblem: DataFolderProblem | null; readonly dataProblem: DataFolderProblem | null;
readonly decalSource: string | null; readonly decalSource: string | null;
readonly decalAutoDetected: boolean;
readonly defaultDecalPath?: string | null | undefined;
readonly steamDataPath: string | null; readonly steamDataPath: string | null;
readonly steamDataConfirmed: boolean; readonly steamDataConfirmed: boolean;
readonly onSteamDataConfirmed: (confirmed: boolean) => void; readonly onSteamDataConfirmed: (confirmed: boolean) => void;
@@ -17,7 +19,19 @@ interface DataStepProps {
} }
/** Step 3: where saves, caches and logs of the offline version are kept. */ /** Step 3: where saves, caches and logs of the offline version are kept. */
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) { export function DataStep({
dataPath,
dataProblem,
decalSource,
decalAutoDetected,
defaultDecalPath,
steamDataPath,
steamDataConfirmed,
onSteamDataConfirmed,
onDataPath,
onDecalSource,
onError,
}: DataStepProps) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<> <>
@@ -35,9 +49,16 @@ export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, st
</Notice> </Notice>
)} )}
<Row label={t('decals.source')} hint={t('decals.hint')}> <Row label={t('decals.source')} hint={t('decals.hint')}>
<FolderField path={decalSource} dialogTitle={t('decals.choose')} onChosen={onDecalSource} onError={onError} /> <FolderField
path={decalSource}
defaultPath={defaultDecalPath}
dialogTitle={t('decals.choose')}
onChosen={onDecalSource}
onError={onError}
/>
{decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>} {decalSource && <button type="button" className="button" onClick={() => onDecalSource(null)}>{t('decals.useDefault')}</button>}
</Row> </Row>
{decalAutoDetected && decalSource && <Notice tone="info">{t('decals.autoDetectedNotice')}</Notice>}
</> </>
); );
} }
@@ -89,6 +89,14 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me
: t('method.spaceSavingPending')} : t('method.spaceSavingPending')}
onSelect={() => choose('hardlink')} onSelect={() => choose('hardlink')}
> >
{sourceSize && savingAvailable && (
<p className="small">
{t('method.spaceSavingBreakdown', {
copy: formatBytes(bytesToCopy(sourceSize, 'hardlink')),
shared: formatBytes(sourceSize.linkableBytes ?? 0),
})}
</p>
)}
{targetPicker} {targetPicker}
</Choice> </Choice>
<Choice <Choice
@@ -19,6 +19,27 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
const current = phases.indexOf(phase); const current = phases.indexOf(phase);
const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null; const tracking = (phase === 'copying' || phase === 'verifying') && progress !== null;
const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied'; const caption = phase === 'verifying' ? 'progress.verified' : useHardLinks ? 'progress.prepared' : 'progress.copied';
const hardlinkStats = phase === 'copying'
&& useHardLinks
&& progress !== null
&& progress.copiedBytes !== undefined
&& progress.copyTotalBytes !== undefined
&& progress.linkedBytes !== undefined
&& progress.linkTotalBytes !== undefined
&& progress.linkedFiles !== undefined
&& progress.linkTotalFiles !== undefined
&& progress.linkTotalFiles > 0
? {
copiedBytes: progress.copiedBytes,
copyTotalBytes: progress.copyTotalBytes,
linkedBytes: progress.linkedBytes,
linkTotalBytes: progress.linkTotalBytes,
linkedFiles: progress.linkedFiles,
linkTotalFiles: progress.linkTotalFiles,
copiedFiles: Math.max(0, progress.doneFiles - progress.linkedFiles),
copyTotalFiles: Math.max(0, progress.totalFiles - progress.linkTotalFiles),
}
: null;
return ( return (
<> <>
{phases.map((name, position) => { {phases.map((name, position) => {
@@ -32,6 +53,26 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
})} })}
<ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large /> <ProgressBar value={tracking ? progress.doneBytes : 0} max={tracking ? progress.totalBytes : null} large />
{tracking && ( {tracking && (
hardlinkStats ? (
<>
<div className="progress-caption">
{t('progress.copiedActual', {
copied: formatBytes(hardlinkStats.copiedBytes),
copyTotal: formatBytes(hardlinkStats.copyTotalBytes),
copiedFiles: hardlinkStats.copiedFiles.toLocaleString(),
copyTotalFiles: hardlinkStats.copyTotalFiles.toLocaleString(),
})}
</div>
<div className="progress-caption">
{t('progress.linkedShared', {
linked: formatBytes(hardlinkStats.linkedBytes),
linkTotal: formatBytes(hardlinkStats.linkTotalBytes),
linkedFiles: hardlinkStats.linkedFiles.toLocaleString(),
linkTotalFiles: hardlinkStats.linkTotalFiles.toLocaleString(),
})}
</div>
</>
) : (
<div className="progress-caption"> <div className="progress-caption">
{t(caption, { {t(caption, {
done: formatBytes(progress.doneBytes), done: formatBytes(progress.doneBytes),
@@ -40,6 +81,7 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: {
totalFiles: progress.totalFiles.toLocaleString(), totalFiles: progress.totalFiles.toLocaleString(),
})} })}
</div> </div>
)
)} )}
</> </>
); );
@@ -44,6 +44,8 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
steamDataConfirmed={wizard.steamDataConfirmed} steamDataConfirmed={wizard.steamDataConfirmed}
onSteamDataConfirmed={wizard.setSteamDataConfirmed} onSteamDataConfirmed={wizard.setSteamDataConfirmed}
decalSource={wizard.decalSource} decalSource={wizard.decalSource}
decalAutoDetected={wizard.decalAutoDetected}
defaultDecalPath={wizard.decalProbePath}
onDataPath={wizard.setDataPath} onDataPath={wizard.setDataPath}
onDecalSource={wizard.setDecalSource} onDecalSource={wizard.setDecalSource}
onError={wizard.report} onError={wizard.report}
@@ -40,7 +40,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
problem: DataFolderProblem | null; problem: DataFolderProblem | null;
confirmed: boolean; confirmed: boolean;
} | null>(null); } | null>(null);
const [decalSource, setDecalSource] = useState<string | null>(null); const [decalSource, setDecalSourceState] = useState<string | null>(null);
const [decalAutoDetected, setDecalAutoDetected] = useState(false);
const [decalManuallyEdited, setDecalManuallyEdited] = useState(false);
const [check, setCheck] = useState<PatchCheck | null>(null); const [check, setCheck] = useState<PatchCheck | null>(null);
const [missingAccepted, setMissingAccepted] = useState(false); const [missingAccepted, setMissingAccepted] = useState(false);
const [progress, setProgress] = useState<InstallProgress | null>(null); const [progress, setProgress] = useState<InstallProgress | null>(null);
@@ -66,8 +68,34 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
? (source?.path ?? null) ? (source?.path ?? null)
: null; : null;
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null; const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
const decalProbePath = stockSource?.path ?? source?.path ?? null;
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]); const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
// Read-only probe of the player-selected source folder for a usable decal cache.
useEffect(() => {
if (!active || !decalProbePath || decalManuallyEdited) return;
let current = true;
ipcInvoke('decals:detectSource', { path: decalProbePath })
.then(({ path }) => {
if (!current) return;
if (path) {
setDecalSourceState(path);
setDecalAutoDetected(true);
} else {
setDecalSourceState(null);
setDecalAutoDetected(false);
}
})
.catch(() => {
if (!current) return;
setDecalSourceState(null);
setDecalAutoDetected(false);
});
return () => {
current = false;
};
}, [active, decalProbePath, decalManuallyEdited]);
useEffect(() => { useEffect(() => {
if (!active || !dataPath) return; if (!active || !dataPath) return;
let current = true; let current = true;
@@ -119,6 +147,12 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
useEffect(() => ipcOn('event:install-progress', setProgress), []); useEffect(() => ipcOn('event:install-progress', setProgress), []);
const resetDecals = (): void => {
setDecalSourceState(null);
setDecalAutoDetected(false);
setDecalManuallyEdited(false);
};
const start = (): void => { const start = (): void => {
clear(); clear();
setMode('new'); setMode('new');
@@ -130,7 +164,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
setDraftId(null); setDraftId(null);
setDataPath(''); setDataPath('');
setDataInspection(null); setDataInspection(null);
setDecalSource(null); resetDecals();
setActive(true); setActive(true);
ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => { ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => {
setDraftId(id); setDraftId(id);
@@ -145,11 +179,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
setStockSource(null); setStockSource(null);
setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE); setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE);
setName(''); setName('');
resetDecals();
}; };
const chooseSource = (found: GameFolderInspection | null): void => { const chooseSource = (found: GameFolderInspection | null): void => {
setSource(found); setSource(found);
setStockSource(null); setStockSource(null);
resetDecals();
const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource; const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource;
const defaultMethod = isExisting ? 'existing' : 'copy'; const defaultMethod = isExisting ? 'existing' : 'copy';
setChoice({ method: defaultMethod, target: null, steamConfirmed: false }); setChoice({ method: defaultMethod, target: null, steamConfirmed: false });
@@ -166,6 +202,17 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
} }
}; };
const chooseStockSource = (found: GameFolderInspection | null): void => {
setStockSource(found);
resetDecals();
};
const setDecalSource = (path: string | null): void => {
setDecalSourceState(path);
setDecalAutoDetected(false);
setDecalManuallyEdited(true);
};
const install = (): void => { const install = (): void => {
if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return; if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return;
const directFolder = choice.method === 'in-place' || choice.method === 'existing'; const directFolder = choice.method === 'in-place' || choice.method === 'existing';
@@ -230,9 +277,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
}; };
return { return {
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn, active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, decalAutoDetected, decalProbePath, check, missingAccepted, progress, cancelling, message, canGoOn,
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false, steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted, start, back, next, cancel, report, chooseMode, chooseSource, setStockSource: chooseStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
}; };
} }
@@ -0,0 +1,591 @@
import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { ModsSection } from '../../shell/navigation.ts';
const MOD_DOCS_URL = 'https://wto-project.net/mod-docs';
interface Props {
readonly copy: InstallRecord;
readonly section: ModsSection;
readonly readOnly: boolean;
readonly onError: (error: unknown) => void;
}
function localized(value: string | Readonly<Record<string, string>> | undefined, language: string): string {
if (!value) return '';
if (typeof value === 'string') return value;
const exact = value[language];
if (exact) return exact;
const prefix = language.split('-')[0];
if (prefix) {
const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
if (match?.[1]) return match[1];
}
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
}
export function ModsPage({ copy, section, readOnly, onError }: Props) {
const { t, i18n } = useTranslation();
const [state, setState] = useState<ModsStateView | null>(null);
const [busy, setBusy] = useState(false);
const [query, setQuery] = useState('');
const [expandedId, setExpandedId] = useState<string | null>(null);
const [draggedId, setDraggedId] = useState<string | null>(null);
const [presetName, setPresetName] = useState('');
const [notice, setNotice] = useState<string | null>(null);
const load = useCallback(() => {
setBusy(true);
ipcInvoke('mods:getState', { copyId: copy.id })
.then(setState)
.catch(onError)
.finally(() => setBusy(false));
}, [copy.id, onError]);
useEffect(() => {
let mounted = true;
const sync = (): void => {
ipcInvoke('mods:getState', { copyId: copy.id })
.then((result) => { if (mounted) setState(result); })
.catch(onError);
};
sync();
window.addEventListener('focus', sync);
return () => {
mounted = false;
window.removeEventListener('focus', sync);
};
}, [copy.id, onError]);
const runAction = (action: Promise<ModsStateView>, successNotice?: string): void => {
setBusy(true);
setNotice(null);
action
.then((next) => {
setState(next);
if (successNotice) setNotice(successNotice);
})
.catch(onError)
.finally(() => setBusy(false));
};
const issuesByMod = useMemo(() => {
const map = new Map<string, ModIssueView[]>();
for (const issue of state?.issues ?? []) {
const list = map.get(issue.modId) ?? [];
list.push(issue);
map.set(issue.modId, list);
}
return map;
}, [state]);
const title = t(`mods.sections.${section}`);
if (!state) {
return <Sheet title={title} aside={copy.name}><p className="lead">{t('mods.loading')}</p></Sheet>;
}
const disabled = readOnly || busy;
const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length;
const toggleMod = (modId: string, nextEnabled: boolean): void => {
runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled }));
};
const reorder = (nextOrder: string[]): void => {
runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder }));
};
const moveMod = (modId: string, delta: -1 | 1): void => {
const idx = state.order.indexOf(modId);
const target = idx + delta;
if (idx < 0 || target < 0 || target >= state.order.length) return;
const next = [...state.order];
const [item] = next.splice(idx, 1);
next.splice(target, 0, item!);
reorder(next);
};
const handleDrop = (targetId: string, event: DragEvent<HTMLDivElement>): void => {
event.preventDefault();
const sourceId = draggedId;
setDraggedId(null);
if (!sourceId || sourceId === targetId || disabled) return;
const from = state.order.indexOf(sourceId);
const to = state.order.indexOf(targetId);
if (from < 0 || to < 0) return;
const next = [...state.order];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved!);
reorder(next);
};
const savePreset = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const trimmed = presetName.trim();
if (!trimmed) return;
runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }),
t('mods.presets.saved', { name: trimmed }),
);
setPresetName('');
};
const pickCustomFolder = (): void => {
ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') })
.then(({ path }) => {
if (!path) return;
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated'));
})
.catch(onError);
};
const resetFolder = (): void => {
runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone'));
};
const exportPreset = (presetId: string): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId })
.then(({ path }) => {
if (path) setNotice(t('mods.presets.exported', { path }));
})
.catch(onError)
.finally(() => setBusy(false));
};
const importPreset = (): void => {
setBusy(true);
setNotice(null);
ipcInvoke('mods:importPreset', { copyId: copy.id })
.then(({ imported, state: next }) => {
setState(next);
if (imported) setNotice(t('mods.presets.imported'));
})
.catch(onError)
.finally(() => setBusy(false));
};
const normalizedQuery = query.trim().toLowerCase();
const visibleMods = normalizedQuery
? state.mods.filter((mod) => {
const displayName = localized(mod.name, i18n.language).toLowerCase();
return displayName.includes(normalizedQuery)
|| mod.id.toLowerCase().includes(normalizedQuery)
|| mod.author.toLowerCase().includes(normalizedQuery);
})
: state.mods;
const canDrag = !disabled && normalizedQuery.length === 0;
return (
<Sheet
title={title}
aside={(
<span className="mods-aside">
<span>{copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })}</span>
<span
className="mods-exp-chip"
tabIndex={0}
aria-label={t('mods.experimentalBody', { api: state.apiVersion })}
>
<span>{t('mods.experimentalChip')}</span>
<span className="mods-exp-icon" aria-hidden="true">i</span>
<span className="mods-exp-popover" role="tooltip">
<strong>{t('mods.experimentalTitle')}</strong>
<span>{t('mods.experimentalBody', { api: state.apiVersion })}</span>
</span>
</span>
</span>
)}
>
{readOnly && (
<div className="mods-banner mods-banner-warn" role="status">
{t('mods.readOnlyNotice')}
</div>
)}
{notice && (
<div className="mods-banner mods-banner-ok" role="status">
{notice}
</div>
)}
{section === 'list' ? (
<>
<div className="mods-toolbar">
<input
type="search"
className="input mods-search"
placeholder={t('mods.searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
{state.presets.length > 0 && (
<select
className="select mods-preset-select"
aria-label={t('mods.presets.quickSwitch')}
disabled={disabled}
value={state.activePresetId ?? ''}
onChange={(event) => {
const id = event.target.value;
if (id) runAction(ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: id }));
}}
>
<option value="">{t('mods.presets.customOption')}</option>
{state.presets.map((preset) => (
<option key={preset.id} value={preset.id}>{preset.name}</option>
))}
</select>
)}
<button
type="button"
className="button"
disabled={disabled || state.mods.length < 2}
onClick={() => runAction(ipcInvoke('mods:autoSort', { copyId: copy.id }), t('mods.autoSorted'))}
>
{t('mods.autoSort')}
</button>
<button type="button" className="button" disabled={busy} onClick={load}>
{t('mods.refresh')}
</button>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<a className="button" href={MOD_DOCS_URL} target="_blank" rel="noreferrer">
{t('mods.openDocs')}
</a>
</div>
{state.discoveryErrors.length > 0 && (
<div className="mods-issues-box mods-issues-error">
<div className="mods-issues-title">{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}</div>
<ul>
{state.discoveryErrors.map((err) => (
<li key={err.folderName}>
<code>{err.folderName}</code>: {err.reason}
</li>
))}
</ul>
</div>
)}
{state.issues.length > 0 && (
<div className={state.hasBlockingErrors ? 'mods-issues-box mods-issues-error' : 'mods-issues-box mods-issues-warn'}>
<div className="mods-issues-title">
{state.hasBlockingErrors
? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length })
: t('mods.issuesTitle', { count: state.issues.length })}
</div>
<ul>
{state.issues.map((issue, idx) => (
<li key={`${issue.modId}-${issue.kind}-${idx}`} className={`mods-issue-${issue.severity}`}>
<span className="mods-issue-tag">{t(`mods.severity.${issue.severity}`)}</span>
<strong>{issue.modId}</strong>: {issue.detail}
</li>
))}
</ul>
</div>
)}
{visibleMods.length === 0 ? (
<div className="mods-empty">
<p className="lead">{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}</p>
{state.mods.length === 0 && (
<>
<p className="mods-hint">{t('mods.emptyHint', { path: state.modsDir })}</p>
<button type="button" className="button button-primary" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
</>
)}
</div>
) : (
<div className="mods-list">
{visibleMods.map((mod) => {
const index = state.order.indexOf(mod.id);
const isEnabled = state.enabled[mod.id] === true;
const isExpanded = expandedId === mod.id;
const modIssues = issuesByMod.get(mod.id) ?? [];
return (
<ModCard
key={mod.id}
mod={mod}
index={index}
total={state.order.length}
enabled={isEnabled}
expanded={isExpanded}
disabled={disabled}
canDrag={canDrag}
language={i18n.language}
issues={modIssues}
onToggle={(next) => toggleMod(mod.id, next)}
onMove={(delta) => moveMod(mod.id, delta)}
onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)}
onDragStart={() => setDraggedId(mod.id)}
onDrop={(event) => handleDrop(mod.id, event)}
/>
);
})}
</div>
)}
</>
) : (
<>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.presets.heading')}</h3>
<p className="mods-hint">{t('mods.presets.description')}</p>
<form className="mods-preset-form" onSubmit={savePreset}>
<input
type="text"
className="input"
maxLength={80}
disabled={disabled}
placeholder={t('mods.presets.namePlaceholder')}
value={presetName}
onChange={(event) => setPresetName(event.target.value)}
/>
<button type="submit" className="button button-primary" disabled={disabled || !presetName.trim()}>
{t('mods.presets.saveCurrent')}
</button>
<button type="button" className="button" disabled={disabled} onClick={importPreset}>
{t('mods.presets.import')}
</button>
</form>
{state.presets.length === 0 ? (
<p className="mods-hint">{t('mods.presets.empty')}</p>
) : (
<div className="mods-preset-list">
{state.presets.map((preset) => {
const active = state.activePresetId === preset.id;
const count = Object.values(preset.enabled).filter(Boolean).length;
return (
<div key={preset.id} className={active ? 'mods-preset-item mods-preset-active' : 'mods-preset-item'}>
<div className="mods-preset-meta">
<div className="mods-preset-name">
{preset.name}
{active && <span className="mods-badge mods-badge-data">{t('mods.presets.activeTag')}</span>}
</div>
<div className="mods-preset-sub">
{t('mods.presets.summary', { count, total: preset.order.length })}
</div>
</div>
<div className="copy-list-actions">
<button
type="button"
className="button button-primary"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:applyPreset', { copyId: copy.id, presetId: preset.id }),
t('mods.presets.applied', { name: preset.name }),
)}
>
{t('mods.presets.apply')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(
ipcInvoke('mods:savePreset', { copyId: copy.id, name: preset.name, overwriteId: preset.id }),
t('mods.presets.updated', { name: preset.name }),
)}
>
{t('mods.presets.overwrite')}
</button>
<button type="button" className="button" disabled={busy} onClick={() => exportPreset(preset.id)}>
{t('mods.presets.export')}
</button>
<button
type="button"
className="button"
disabled={disabled}
onClick={() => runAction(ipcInvoke('mods:deletePreset', { copyId: copy.id, presetId: preset.id }))}
>
{t('mods.presets.delete')}
</button>
</div>
</div>
);
})}
</div>
)}
</section>
<section className="mods-section">
<h3 className="mods-subheading">{t('mods.repo.heading')}</h3>
<p className="mods-hint">{t('mods.repo.description')}</p>
<Row
label={t('mods.repo.pathLabel')}
hint={state.isCustomModsDir ? t('mods.repo.customNote') : t('mods.repo.defaultNote')}
>
<code className="mods-path">{state.modsDir}</code>
</Row>
<div className="copy-list-actions" style={{ marginTop: 12 }}>
<button type="button" className="button" onClick={() => ipcInvoke('mods:openFolder').catch(onError)}>
{t('mods.openFolder')}
</button>
<button type="button" className="button" disabled={disabled} onClick={pickCustomFolder}>
{t('mods.repo.changeFolder')}
</button>
{state.isCustomModsDir && (
<button type="button" className="button" disabled={disabled} onClick={resetFolder}>
{t('mods.repo.resetDefault')}
</button>
)}
</div>
</section>
</>
)}
</Sheet>
);
}
interface ModCardProps {
readonly mod: ModListItem;
readonly index: number;
readonly total: number;
readonly enabled: boolean;
readonly expanded: boolean;
readonly disabled: boolean;
readonly canDrag: boolean;
readonly language: string;
readonly issues: readonly ModIssueView[];
readonly onToggle: (next: boolean) => void;
readonly onMove: (delta: -1 | 1) => void;
readonly onToggleExpand: () => void;
readonly onDragStart: () => void;
readonly onDrop: (event: DragEvent<HTMLDivElement>) => void;
}
function ModCard({
mod,
index,
total,
enabled,
expanded,
disabled,
canDrag,
language,
issues,
onToggle,
onMove,
onToggleExpand,
onDragStart,
onDrop,
}: ModCardProps) {
const { t } = useTranslation();
const displayName = localized(mod.name, language) || mod.id;
const description = localized(mod.description, language);
const errorCount = issues.filter((i) => i.severity === 'error').length;
const warnCount = issues.filter((i) => i.severity === 'warning').length;
return (
<div
className={`mods-card${enabled ? ' mods-card-enabled' : ''}`}
draggable={canDrag}
onDragStart={onDragStart}
onDragOver={(event) => { if (canDrag) event.preventDefault(); }}
onDrop={onDrop}
>
<div className="mods-card-row">
<span className="mods-order-num" title={t('mods.loadOrderHint')}>#{index + 1}</span>
<input
type="checkbox"
className="mods-checkbox"
checked={enabled}
disabled={disabled}
aria-label={displayName}
onChange={(event) => onToggle(event.target.checked)}
/>
<div className="mods-card-main" onClick={onToggleExpand}>
<div className="mods-card-title">
<span className="mods-name">{displayName}</span>
<span className="mods-version">v{mod.version}</span>
<span className="mods-author">· {mod.author}</span>
<div className="mods-badges">
{mod.badges.map((badge) => (
<span key={badge} className={`mods-badge mods-badge-${badge}`}>
{t(`mods.badges.${badge}`)}
</span>
))}
{errorCount > 0 && <span className="mods-badge mods-badge-error">{t('mods.errorCount', { count: errorCount })}</span>}
{warnCount > 0 && <span className="mods-badge mods-badge-warn">{t('mods.warnCount', { count: warnCount })}</span>}
</div>
</div>
{description && <div className="mods-card-desc">{description}</div>}
</div>
<div className="mods-card-actions">
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index <= 0}
title={t('mods.moveUp')}
onClick={() => onMove(-1)}
>
↑
</button>
<button
type="button"
className="button mods-move-btn"
disabled={disabled || index < 0 || index >= total - 1}
title={t('mods.moveDown')}
onClick={() => onMove(1)}
>
↓
</button>
<button type="button" className="button" onClick={onToggleExpand}>
{expanded ? t('mods.hideDetails') : t('mods.showDetails')}
</button>
</div>
</div>
{expanded && (
<div className="mods-card-details">
<div className="mods-detail-grid">
<div><span>ID:</span> <code>{mod.id}</code></div>
<div><span>API:</span> <code>{mod.apiVersion}</code></div>
<div><span>{t('mods.details.folder')}:</span> <code>{mod.folderName}</code></div>
{mod.gameVersions.length > 0 && (
<div><span>{t('mods.details.gameVersions')}:</span> <code>{mod.gameVersions.join(', ')}</code></div>
)}
{mod.requires.length > 0 && (
<div><span>{t('mods.details.requires')}:</span> <code>{mod.requires.join(', ')}</code></div>
)}
{mod.conflicts.length > 0 && (
<div><span>{t('mods.details.conflicts')}:</span> <code>{mod.conflicts.join(', ')}</code></div>
)}
</div>
<div className="mods-detail-summary">
{mod.serverTuningFiles.length > 0 && (
<span>{t('mods.details.tuning', { count: mod.serverTuningFiles.length })}</span>
)}
{mod.hasServerScript && <span>{t('mods.details.serverScript')}</span>}
{mod.packOperations.length > 0 && (
<span>{t('mods.details.packOps', { count: mod.packOperations.length })}</span>
)}
{mod.hasClientAddon && (
<span>{t('mods.details.addon', { count: mod.addonFileCount })}</span>
)}
{mod.guiPatchCount > 0 && (
<span>{t('mods.details.guiPatches', { count: mod.guiPatchCount })}</span>
)}
{mod.exePatchCount > 0 && (
<span>{t('mods.details.exePatches', { count: mod.exePatchCount })}</span>
)}
{mod.clientFileCount > 0 && (
<span>{t('mods.details.companionFiles', { count: mod.clientFileCount })}</span>
)}
{mod.hasConfigBlkPatch && <span>{t('mods.details.configBlk')}</span>}
</div>
</div>
)}
</div>
);
}
@@ -11,7 +11,7 @@ interface Props {
readonly onError: (error: unknown) => void; readonly onError: (error: unknown) => void;
} }
const ACTIONS = ['research', 'purchase', 'equipment'] as const; const ACTIONS = ['purchase', 'equipment'] as const;
export function SaveResearch({ copyId, userId, readOnly, onError }: Props) { export function SaveResearch({ copyId, userId, readOnly, onError }: Props) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
@@ -0,0 +1,267 @@
import { useState, type FormEvent, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import {
GROUND_AI_DRIVE_MODES,
GROUND_AI_MODES,
TuningPatchSchema,
type GroundAiTuningValues,
type TuningPatch,
type TuningView,
} from '@shared/schemas/tuning.ts';
import { Row } from '../../components/Row.tsx';
import {
ALL_BOT_FIELDS,
BOT_TUNING_GROUPS,
readBotFieldValue,
type BotFieldSpec,
} from './bot-tuning-fields.ts';
type DraftMap = Record<string, string | boolean>;
interface Props {
readonly data: TuningView;
readonly saving: boolean;
readonly onSave: (patch: TuningPatch) => Promise<void>;
}
function toInputValue(value: string | number | boolean): string | boolean {
return typeof value === 'boolean' ? value : String(value);
}
function mergeSection<T extends Record<string, unknown>>(
base: T,
patch: { readonly [K in keyof T]?: T[K] | undefined } | undefined,
): T {
if (!patch) return base;
const next: Record<string, unknown> = { ...base };
for (const [key, value] of Object.entries(patch)) {
if (value !== undefined) next[key] = value;
}
return next as T;
}
function hasValidCrossFieldRules(effective: GroundAiTuningValues, patch: TuningPatch['groundAi']): boolean {
if (!patch) return true;
const cmd = mergeSection(effective.commander, patch.commander);
if (cmd.bttlAssaultPct + cmd.bttlFlankPct + cmd.bttlOverwatchPct > 100) return false;
if (cmd.conqAssaultPct + cmd.conqFlankPct > 100) return false;
if (cmd.conqHoldDefendPct + cmd.conqHoldOverwatchPct > 100) return false;
const macro = mergeSection(effective.macro, patch.macro);
if (macro.recaptureMaxBots < macro.recaptureMinBots) return false;
const sm = mergeSection(effective.stateMachine, patch.stateMachine);
if (sm.coverMaxDistM <= sm.coverMinDistM) return false;
const est = mergeSection(effective.estimation, patch.estimation);
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;
}
export function BotTuningPanel({ data, saving, onSave }: Props) {
const { t, i18n } = useTranslation();
const [draft, setDraft] = useState<DraftMap>({});
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>(() =>
Object.fromEntries(BOT_TUNING_GROUPS.map((group) => [group.id, group.defaultOpen])),
);
const format = new Intl.NumberFormat(i18n.language);
const activeMode = String(draft['groundAi.mode'] ?? data.effective.groundAi.mode);
const allOpen = BOT_TUNING_GROUPS.every((group) => openGroups[group.id]);
const set = (id: string, value: string | boolean): void => {
setMessage(null);
setDraft((previous) => ({ ...previous, [id]: value }));
};
const toggleAllGroups = (): void => {
const nextState = !allOpen;
setOpenGroups(Object.fromEntries(BOT_TUNING_GROUPS.map((group) => [group.id, nextState])));
};
const reset = (): void => {
setMessage(null);
setDraft(Object.fromEntries(
ALL_BOT_FIELDS.map((spec) => [spec.id, toInputValue(readBotFieldValue(data.defaults, spec))]),
));
};
const fieldLabel = (spec: BotFieldSpec): string => {
if (spec.kind === 'flatInt') return t(`tuning.fields.${spec.id}`);
if (spec.kind === 'groundAiMode') return t('tuning.botFields.mode');
return t(`tuning.botFields.${spec.section}.${spec.field}`);
};
const defaultLabel = (spec: BotFieldSpec): string => {
const value = readBotFieldValue(data.defaults, spec);
if (spec.kind === 'groundAiMode') return t(`tuning.botModes.${value}`);
if (spec.kind === 'driveMode') return t(`tuning.botDriveModes.${value}`);
if (spec.kind === 'steerSign') return value === 1 ? t('tuning.botSteer.normal') : t('tuning.botSteer.inverted');
if (typeof value === 'boolean') return t(value ? 'tuning.on' : 'tuning.off');
const formatted = format.format(Number(value));
const unit = 'unit' in spec && spec.unit ? ` ${spec.unit}` : '';
return `${formatted}${unit}`;
};
const renderEditor = (spec: BotFieldSpec): ReactNode => {
const active = draft[spec.id] ?? toInputValue(readBotFieldValue(data.effective, spec));
const label = fieldLabel(spec);
if (spec.kind === 'bool') {
return (
<input
type="checkbox"
aria-label={label}
disabled={saving}
checked={active === true}
onChange={(event) => set(spec.id, event.target.checked)}
/>
);
}
if (spec.kind === 'groundAiMode') {
return (
<select
className="select"
aria-label={label}
disabled={saving}
value={String(active)}
onChange={(event) => set(spec.id, event.target.value)}
>
{GROUND_AI_MODES.map((mode) => (
<option key={mode} value={mode}>{t(`tuning.botModes.${mode}`)}</option>
))}
</select>
);
}
if (spec.kind === 'driveMode') {
return (
<select
className="select"
aria-label={label}
disabled={saving}
value={String(active)}
onChange={(event) => set(spec.id, event.target.value)}
>
{GROUND_AI_DRIVE_MODES.map((mode) => (
<option key={mode} value={mode}>{t(`tuning.botDriveModes.${mode}`)}</option>
))}
</select>
);
}
if (spec.kind === 'steerSign') {
return (
<select
className="select"
aria-label={label}
disabled={saving}
value={String(active)}
onChange={(event) => set(spec.id, event.target.value)}
>
<option value="1">{t('tuning.botSteer.normal')}</option>
<option value="-1">{t('tuning.botSteer.inverted')}</option>
</select>
);
}
const isInt = spec.kind === 'int' || spec.kind === 'flatInt';
const unit = 'unit' in spec ? spec.unit : undefined;
return (
<div className="copy-list-actions">
<input
className="input"
aria-label={label}
type="number"
min={spec.min}
max={spec.max}
step={isInt ? '1' : 'any'}
value={String(active)}
disabled={saving}
onChange={(event) => set(spec.id, event.target.value)}
/>
{unit && <span>{unit}</span>}
</div>
);
};
const submit = (event: FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const rawPatch: Record<string, unknown> = {};
const groundAiPatch: Record<string, unknown> = {};
for (const spec of ALL_BOT_FIELDS) {
if (!(spec.id in draft)) continue;
const raw = draft[spec.id];
if (spec.kind === 'flatInt') {
rawPatch[spec.id] = raw === '' ? NaN : Number(raw);
} else if (spec.kind === 'groundAiMode') {
groundAiPatch['mode'] = raw;
} else {
const parsed = spec.kind === 'bool' || spec.kind === 'driveMode'
? raw
: (raw === '' ? NaN : Number(raw));
const sectionObj = (groundAiPatch[spec.section] as Record<string, unknown> | undefined) ?? {};
sectionObj[spec.field] = parsed;
groundAiPatch[spec.section] = sectionObj;
}
}
if (Object.keys(groundAiPatch).length > 0) rawPatch['groundAi'] = groundAiPatch;
const result = TuningPatchSchema.safeParse(rawPatch);
if (!result.success || !hasValidCrossFieldRules(data.effective.groundAi, result.data.groundAi)) {
setMessage('invalid');
return;
}
setMessage(null);
onSave(result.data).then(() => {
setDraft({});
setMessage('saved');
}).catch(() => undefined);
};
return (
<form onSubmit={submit}>
<div className="tuning-toolbar">
<p className="small">{t('tuning.botModeHint')}</p>
<button type="button" className="button" onClick={toggleAllGroups}>
{t(allOpen ? 'tuning.collapseAll' : 'tuning.expandAll')}
</button>
</div>
{activeMode === 'stock' && (
<p className="notice">{t('tuning.botStockNotice')}</p>
)}
{BOT_TUNING_GROUPS.map((group) => (
<details
key={group.id}
className="tuning-group"
open={openGroups[group.id]}
onToggle={(event) => {
const isOpen = event.currentTarget.open;
setOpenGroups((prev) => (prev[group.id] === isOpen ? prev : { ...prev, [group.id]: isOpen }));
}}
>
<summary className="tuning-group-summary">
<span>{t(`tuning.botGroups.${group.id}`)}</span>
<small>{t(`tuning.botGroupHints.${group.id}`)}</small>
</summary>
<div className="tuning-group-body">
{group.fields.map((spec) => (
<Row
key={spec.id}
label={fieldLabel(spec)}
hint={t('tuning.default', { value: defaultLabel(spec) })}
>
{renderEditor(spec)}
</Row>
))}
</div>
</details>
))}
<div className="copy-list-actions tuning-actions">
<button type="button" className="button" disabled={saving} onClick={reset}>{t('tuning.reset')}</button>
<button type="submit" className="button button-primary" disabled={saving || Object.keys(draft).length === 0}>
{t('saves.apply')}
</button>
</div>
{message && <p className="small" role={message === 'invalid' ? 'alert' : 'status'}>{t(`tuning.${message}`)}</p>}
</form>
);
}
@@ -1,20 +1,22 @@
import { useEffect, useState, type FormEvent, type ReactNode } from 'react'; import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import type { InstallRecord } from '@shared/schemas/install.ts'; import type { InstallRecord } from '@shared/schemas/install.ts';
import { AUTO_TARGET_PICKS, TuningPatchSchema, type TuningValues, type TuningView } from '@shared/schemas/tuning.ts'; import { AUTO_TARGET_PICKS, TuningPatchSchema, type TuningPatch, type TuningValues, type TuningView } from '@shared/schemas/tuning.ts';
import { Row } from '../../components/Row.tsx'; import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx'; import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts'; import { ipcInvoke } from '../../ipc.ts';
import type { TuningSection } from '../../shell/navigation.ts'; import type { TuningSection } from '../../shell/navigation.ts';
import { BotTuningPanel } from './BotTuningPanel.tsx';
type Field = keyof TuningValues; type SimpleSection = Exclude<TuningSection, 'bots'>;
type Field = Exclude<keyof TuningValues, 'groundAi'>;
type Draft = Partial<Record<Field, string | boolean>>; type Draft = Partial<Record<Field, string | boolean>>;
const fields = { const fields = {
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'], rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'], battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'strikeUcavSpawnScore', 'nuclearEscalationStrategicBombers'],
newProfile: ['silverLions', 'goldenEagles'], newProfile: ['silverLions', 'goldenEagles'],
research: ['preferLineSuccessor', 'autoTargetPick'], research: ['preferLineSuccessor', 'autoTargetPick'],
} as const satisfies Record<TuningSection, readonly Field[]>; } as const satisfies Record<SimpleSection, readonly Field[]>;
interface Props { interface Props {
readonly copy: InstallRecord; readonly copy: InstallRecord;
@@ -34,7 +36,6 @@ export function TuningPage({ copy, section, onError }: Props) {
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [message, setMessage] = useState<'invalid' | 'saved' | null>(null); const [message, setMessage] = useState<'invalid' | 'saved' | null>(null);
const title = t(`tuning.sections.${section}`); const title = t(`tuning.sections.${section}`);
const sectionFields: readonly Field[] = fields[section];
useEffect(() => { useEffect(() => {
let mounted = true; let mounted = true;
@@ -46,6 +47,30 @@ export function TuningPage({ copy, section, onError }: Props) {
if (!data) return <Sheet title={title} aside={copy.name}><p className="lead">{t('tuning.loading')}</p></Sheet>; if (!data) return <Sheet title={title} aside={copy.name}><p className="lead">{t('tuning.loading')}</p></Sheet>;
const loaded = data; const loaded = data;
const savePatch = async (patch: TuningPatch): Promise<void> => {
setSaving(true);
try {
const next = await ipcInvoke('tuning:update', { copyId: copy.id, patch });
setData(next);
} catch (error) {
onError(error);
throw error;
} finally {
setSaving(false);
}
};
if (section === 'bots') {
return (
<Sheet title={title} aside={copy.name} foot={t('tuning.nextLaunch')}>
<p className="small">{t('tuning.shared')}</p>
<BotTuningPanel data={loaded} saving={saving} onSave={savePatch} />
</Sheet>
);
}
const sectionFields: readonly Field[] = fields[section];
const format = new Intl.NumberFormat(i18n.language); const format = new Intl.NumberFormat(i18n.language);
const set = (field: Field, value: string | boolean): void => { const set = (field: Field, value: string | boolean): void => {
setMessage(null); setMessage(null);
@@ -70,7 +95,7 @@ export function TuningPage({ copy, section, onError }: Props) {
const editor = (field: Field): ReactNode => { const editor = (field: Field): ReactNode => {
const active = draft[field] ?? inputValue(field, loaded.effective[field]); const active = draft[field] ?? inputValue(field, loaded.effective[field]);
const label = t(`tuning.fields.${field}`); const label = t(`tuning.fields.${field}`);
if (field === 'preferLineSuccessor') { if (typeof loaded.defaults[field] === 'boolean') {
return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />; return <input type="checkbox" aria-label={label} disabled={saving} checked={active === true} onChange={(event) => set(field, event.target.checked)} />;
} }
if (field === 'autoTargetPick') { if (field === 'autoTargetPick') {
@@ -110,13 +135,11 @@ export function TuningPage({ copy, section, onError }: Props) {
setMessage('invalid'); setMessage('invalid');
return; return;
} }
setSaving(true);
setMessage(null); setMessage(null);
ipcInvoke('tuning:update', { copyId: copy.id, patch: result.data }).then((next) => { savePatch(result.data).then(() => {
setData(next);
setDraft({}); setDraft({});
setMessage('saved'); setMessage('saved');
}).catch(onError).finally(() => setSaving(false)); }).catch(() => undefined);
}; };
return ( return (
@@ -0,0 +1,320 @@
import type { GroundAiTuningValues, TuningValues } from '@shared/schemas/tuning.ts';
export type FlatBotFieldKey = 'tankBotRespawns' | 'airBotRespawns' | 'botPoolLimitPerType';
export type GroundAiSectionKey = Exclude<keyof GroundAiTuningValues, 'mode'>;
export type BotFieldSpec =
| {
readonly id: FlatBotFieldKey;
readonly kind: 'flatInt';
readonly min: number;
readonly max: number;
readonly unit?: string;
}
| {
readonly id: 'groundAi.mode';
readonly kind: 'groundAiMode';
}
| {
readonly id: `groundAi.${GroundAiSectionKey}.${string}`;
readonly section: GroundAiSectionKey;
readonly field: string;
readonly kind: 'int' | 'number' | 'bool' | 'driveMode' | 'steerSign';
readonly min?: number;
readonly max?: number;
readonly unit?: string;
};
export interface BotTuningGroup {
readonly id: string;
readonly defaultOpen: boolean;
readonly customOnly?: boolean;
readonly fields: readonly BotFieldSpec[];
}
function num(
section: GroundAiSectionKey,
field: string,
min: number,
max: number,
unit?: string,
): BotFieldSpec {
return {
id: `groundAi.${section}.${field}`,
section,
field,
kind: 'number',
min,
max,
...(unit ? { unit } : {}),
};
}
function int(
section: GroundAiSectionKey,
field: string,
min: number,
max: number,
unit?: string,
): BotFieldSpec {
return {
id: `groundAi.${section}.${field}`,
section,
field,
kind: 'int',
min,
max,
...(unit ? { unit } : {}),
};
}
export const BOT_TUNING_GROUPS: readonly BotTuningGroup[] = [
{
id: 'general',
defaultOpen: true,
fields: [
{ id: 'groundAi.mode', kind: 'groundAiMode' },
{ id: 'tankBotRespawns', kind: 'flatInt', min: 1, max: 10 },
{ id: 'airBotRespawns', kind: 'flatInt', min: 1, max: 10 },
{ id: 'botPoolLimitPerType', kind: 'flatInt', min: 4, max: 200 },
],
},
{
id: 'lineupWeights',
defaultOpen: true,
customOnly: true,
fields: [
num('lineupWeights', 'mediumTank', 0.01, 10),
num('lineupWeights', 'heavyTank', 0.01, 10),
num('lineupWeights', 'tankDestroyer', 0.01, 10),
num('lineupWeights', 'lightTank', 0.01, 10),
num('lineupWeights', 'spaa', 0.01, 10),
num('lineupWeights', 'other', 0.01, 10),
],
},
{
id: 'loadout',
defaultOpen: true,
customOnly: true,
fields: [
int('loadout', 'lowReadyRackThreshold', 1, 60),
int('loadout', 'topUpAmmoCount', 4, 80),
int('loadout', 'primaryAmmoPct', 50, 100, '%'),
int('loadout', 'secondaryMinRounds', 0, 20),
int('loadout', 'penetrationCompareDistM', 100, 2000, 'm'),
],
},
{
id: 'commander',
defaultOpen: false,
customOnly: true,
fields: [
num('commander', 'rebalanceSec', 1, 30, 's'),
num('commander', 'roleHoldSec', 0, 120, 's'),
int('commander', 'bttlAssaultPct', 0, 100, '%'),
int('commander', 'bttlFlankPct', 0, 100, '%'),
int('commander', 'bttlOverwatchPct', 0, 100, '%'),
int('commander', 'conqAssaultPct', 0, 100, '%'),
int('commander', 'conqFlankPct', 0, 100, '%'),
int('commander', 'conqHoldDefendPct', 0, 100, '%'),
int('commander', 'conqHoldOverwatchPct', 0, 100, '%'),
int('commander', 'domAssaultPct', 0, 100, '%'),
int('commander', 'domMaxDefendersPerCap', 0, 4),
num('commander', 'overwatchStandOffM', 25, 350, 'm'),
num('commander', 'flankStandOffM', 25, 300, 'm'),
num('commander', 'spaaFollowOffsetM', 40, 500, 'm'),
num('commander', 'flankMaxLengthRatio', 1.05, 3),
num('commander', 'flankMinSeparationM', 15, 200, 'm'),
num('commander', 'rallyProgressFrac', 0.1, 0.75),
num('commander', 'rallyWaitSec', 3, 60, 's'),
num('commander', 'rallyMinFrac', 0.25, 1),
num('commander', 'rallyRadiusM', 15, 140, 'm'),
num('commander', 'recallSafeHoldSec', 3, 60, 's'),
],
},
{
id: 'macro',
defaultOpen: false,
customOnly: true,
fields: [
num('macro', 'openingSplitSec', 0, 180, 's'),
int('macro', 'capMaxInsiders', 1, 8),
int('macro', 'recaptureMinBots', 1, 8),
int('macro', 'recaptureMaxBots', 1, 12),
num('macro', 'capStickyBonusM', 0, 800, 'm'),
num('macro', 'deathZoneRadiusM', 10, 250, 'm'),
num('macro', 'deathZoneTtlSec', 5, 300, 's'),
int('macro', 'deathZoneMinKills', 1, 16),
num('macro', 'spaaRearOffsetM', 40, 600, 'm'),
num('macro', 'spaaRelocateSec', 5, 180, 's'),
num('macro', 'enemySpawnAvoidM', 60, 600, 'm'),
],
},
{
id: 'stateMachine',
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),
num('stateMachine', 'repositionMinMoveM', 5, 80, 'm'),
num('stateMachine', 'repositionStepM', 15, 120, 'm'),
num('stateMachine', 'repairSafeEnemyDistM', 30, 400, 'm'),
],
},
{
id: 'perception',
defaultOpen: false,
customOnly: true,
fields: [
num('perception', 'foliageTransparency', 0.001, 1),
num('perception', 'nearSpotRangeM', 20, 250, 'm'),
num('perception', 'firingSpotRangeM', 150, 1500, 'm'),
num('perception', 'fastSpotSec', 0.05, 1.5, 's'),
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'),
],
},
{
id: 'tactics',
defaultOpen: false,
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'),
num('tactics', 'memoryTtlSec', 1, 45, 's'),
num('tactics', 'targetStickinessSec', 0.5, 20, 's'),
num('tactics', 'peekCooldownSec', 1, 30, 's'),
],
},
{
id: 'estimation',
defaultOpen: false,
customOnly: true,
fields: [
num('estimation', 'watchMinSec', 0.5, 10, 's'),
num('estimation', 'watchMaxSec', 1, 15, 's'),
num('estimation', 'velSampleMinSpanSec', 0.05, 2, 's'),
num('estimation', 'velStableSpanSec', 0.2, 6, 's'),
num('estimation', 'velJumpResetMps', 1, 20, 'm/s'),
num('estimation', 'baseAimSigmaM', 0, 2, 'm'),
num('estimation', 'leadErrorFrac', 0, 1),
num('estimation', 'maxBiasM', 0, 6, 'm'),
],
},
{
id: 'fireControl',
defaultOpen: false,
customOnly: true,
fields: [
num('fireControl', 'maxEngageRangeM', 150, 3000, 'm'),
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', 'friendlyCorridorM', 1, 10, 'm'),
num('fireControl', 'ballisticStepMaxM', 5, 80, 'm'),
num('fireControl', 'ballisticSweepRadiusM', 0.02, 0.5, 'm'),
int('fireControl', 'maxPreFireChecksPerTick', 1, 16),
],
},
{
id: 'navigation',
defaultOpen: false,
customOnly: true,
fields: [
{ id: 'groundAi.navigation.driveMode', section: 'navigation', field: 'driveMode', kind: 'driveMode' },
int('navigation', 'maxPhysBots', 0, 64),
{ 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: 'crowd',
defaultOpen: false,
customOnly: true,
fields: [
num('crowd', 'personalSpaceM', 6, 40, 'm'),
num('crowd', 'clusterRadiusM', 12, 80, 'm'),
int('crowd', 'clusterMaxAllies', 1, 10),
num('crowd', 'disperseStepM', 8, 65, 'm'),
num('crowd', 'disperseHoldSec', 1, 15, 's'),
],
},
{
id: 'terrain',
defaultOpen: false,
customOnly: true,
fields: [
num('terrain', 'maxClimbSlopeDeg', 10, 42, '°'),
num('terrain', 'maxDropSlopeDeg', 8, 40, '°'),
num('terrain', 'maxWaterDepthM', 0.2, 2.5, 'm'),
num('terrain', 'collisionMarginM', 0.05, 2, 'm'),
num('terrain', 'crestLookaheadM', 8, 80, 'm'),
num('terrain', 'ridgeMaxDwellSec', 2, 60, 's'),
int('terrain', 'ridgeMaxShots', 1, 10),
],
},
{
id: 'runtime',
defaultOpen: false,
customOnly: true,
fields: [
int('cadence', 'maxBots', 1, 64),
num('cadence', 'macroTickSec', 0.1, 5, 's'),
num('cadence', 'tacticsTickSec', 0.05, 2, 's'),
num('cadence', 'navTickSec', 0.05, 2, 's'),
{ id: 'groundAi.diagnostics.telemetry', section: 'diagnostics', field: 'telemetry', kind: 'bool' },
num('diagnostics', 'telemetryIntervalSec', 0.5, 60, 's'),
],
},
];
export const ALL_BOT_FIELDS: readonly BotFieldSpec[] = BOT_TUNING_GROUPS.flatMap((group) => group.fields);
export function readBotFieldValue(values: TuningValues, spec: BotFieldSpec): string | number | boolean {
if (spec.kind === 'flatInt') return values[spec.id];
if (spec.kind === 'groundAiMode') return values.groundAi.mode;
const section = values.groundAi[spec.section] as Record<string, string | number | boolean>;
return section[spec.field]!;
}
@@ -1,17 +1,19 @@
/** /**
* The window's pages and the sections of those that have a section list in the side panel. * The window's pages and the sections of those that have a section list in the side panel.
* Pages for later features (saves, tuning) join this list when they are built.
*/ */
export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const; export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const;
export type PageId = (typeof PAGES)[number]; export 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', 'official', 'backup'] as const;
export type SaveSection = (typeof SAVE_SECTIONS)[number]; export type SaveSection = (typeof SAVE_SECTIONS)[number];
export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const; export const TUNING_SECTIONS = ['rewards', 'battle', 'bots', 'newProfile', 'research'] as const;
export type TuningSection = (typeof TUNING_SECTIONS)[number]; export type TuningSection = (typeof TUNING_SECTIONS)[number];
export const MODS_SECTIONS = ['list', 'presets'] as const;
export type ModsSection = (typeof MODS_SECTIONS)[number];
export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const; export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number]; export type CopySection = (typeof COPY_SECTIONS)[number];
@@ -23,16 +25,25 @@ export interface Route {
readonly copies: CopySection; readonly copies: CopySection;
readonly saves: SaveSection; readonly saves: SaveSection;
readonly tuning: TuningSection; readonly tuning: TuningSection;
readonly mods: ModsSection;
readonly settings: SettingsSection; readonly settings: SettingsSection;
} }
export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' }; export const START_ROUTE: Route = {
page: 'home',
saves: 'list',
tuning: 'rewards',
mods: 'list',
copies: 'list',
settings: 'general',
};
/** Where a link points: a page, and for pages with sections, which one. */ /** Where a link points: a page, and for pages with sections, which one. */
export type Destination = export type Destination =
| { readonly page: 'home' | 'about' } | { readonly page: 'home' | 'about' }
| { readonly page: 'saves'; readonly section?: SaveSection } | { readonly page: 'saves'; readonly section?: SaveSection }
| { readonly page: 'tuning'; readonly section?: TuningSection } | { readonly page: 'tuning'; readonly section?: TuningSection }
| { readonly page: 'mods'; readonly section?: ModsSection }
| { readonly page: 'copies'; readonly section?: CopySection } | { readonly page: 'copies'; readonly section?: CopySection }
| { readonly page: 'settings'; readonly section?: SettingsSection }; | { readonly page: 'settings'; readonly section?: SettingsSection };
@@ -42,6 +53,8 @@ export function navigate(route: Route, to: Destination): Route {
return { ...route, page: 'saves', saves: to.section ?? route.saves }; return { ...route, page: 'saves', saves: to.section ?? route.saves };
case 'tuning': case 'tuning':
return { ...route, page: 'tuning', tuning: to.section ?? route.tuning }; return { ...route, page: 'tuning', tuning: to.section ?? route.tuning };
case 'mods':
return { ...route, page: 'mods', mods: to.section ?? route.mods };
case 'copies': case 'copies':
return { ...route, page: 'copies', copies: to.section ?? route.copies }; return { ...route, page: 'copies', copies: to.section ?? route.copies };
case 'settings': case 'settings':
@@ -215,9 +215,13 @@
/* ===== Buttons and links ===== */ /* ===== Buttons and links ===== */
.button { .button {
display: inline-flex;
align-items: center;
justify-content: center;
font: 500 14px var(--font-display); font: 500 14px var(--font-display);
letter-spacing: 0.04em; letter-spacing: 0.04em;
text-transform: uppercase; text-transform: uppercase;
text-decoration: none;
padding: 7px 16px; padding: 7px 16px;
cursor: pointer; cursor: pointer;
white-space: nowrap; white-space: nowrap;
@@ -248,6 +252,11 @@
background: var(--red); background: var(--red);
} }
.button-compact {
font-size: 13px;
padding: 5px 12px;
}
.link { .link {
font: inherit; font: inherit;
color: var(--white); color: var(--white);
@@ -477,3 +486,245 @@
left: 100%; left: 100%;
} }
} }
/* ===== Modal dialog & Markdown content ===== */
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 40;
display: flex;
align-items: center;
justify-content: center;
padding: 28px;
background: rgba(7, 10, 12, 0.72);
}
.modal-dialog {
width: min(760px, 100%);
max-height: min(600px, 100%);
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--sheet);
border: 1px solid var(--line-strong);
border-radius: var(--radius);
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.65);
}
.modal-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 14px 12px 20px;
background: linear-gradient(180deg, #343a40, #2b3136);
border-bottom: 1px solid #000;
}
.modal-title {
margin: 0;
font: 500 18px var(--font-display);
color: var(--white);
letter-spacing: 0.02em;
}
.modal-close {
flex: none;
width: 28px;
height: 28px;
display: grid;
place-items: center;
padding: 0;
border: 0;
border-radius: var(--radius);
background: none;
color: var(--text-dim);
font-size: 20px;
line-height: 1;
cursor: pointer;
}
.modal-close:hover {
color: var(--white);
background: rgba(255, 255, 255, 0.1);
}
.modal-body {
flex: 1;
min-height: 0;
overflow: auto;
padding: 18px 22px 22px;
user-select: text;
}
.modal-foot {
display: flex;
justify-content: flex-end;
gap: 10px;
padding: 10px 20px;
border-top: 1px solid var(--line);
background: rgba(0, 0, 0, 0.17);
}
.markdown-body {
font-size: 13.5px;
line-height: 1.65;
color: var(--text);
overflow-wrap: anywhere;
}
.markdown-body > :first-child {
margin-top: 0;
}
.markdown-body > :last-child {
margin-bottom: 0;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
margin: 18px 0 8px;
font-family: var(--font-display);
font-weight: 500;
color: var(--white);
line-height: 1.3;
}
.markdown-body h1 {
font-size: 20px;
padding-bottom: 6px;
border-bottom: 1px solid var(--line);
}
.markdown-body h2 {
font-size: 17px;
padding-bottom: 5px;
border-bottom: 1px solid var(--line);
}
.markdown-body h3 {
font-size: 15px;
}
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
font-size: 14px;
color: var(--text);
}
.markdown-body p {
margin: 0 0 10px;
}
.markdown-body strong {
color: var(--white);
font-weight: 600;
}
.markdown-body ul,
.markdown-body ol {
margin: 6px 0 10px;
padding-left: 22px;
}
.markdown-body li {
margin: 4px 0;
}
.markdown-body li > ul,
.markdown-body li > ol {
margin: 4px 0;
}
.markdown-body li > p {
margin: 0 0 4px;
}
.markdown-body li > p:last-child {
margin-bottom: 0;
}
.markdown-body code {
padding: 1px 5px;
font-family: var(--font-mono);
font-size: 12.5px;
color: #e6eff2;
background: rgba(0, 0, 0, 0.34);
border: 1px solid var(--line-soft);
border-radius: 2px;
}
.markdown-body pre {
margin: 10px 0;
padding: 10px 12px;
overflow: auto;
background: rgba(0, 0, 0, 0.38);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.markdown-body pre code {
padding: 0;
background: none;
border: 0;
font-size: 12.5px;
line-height: 1.5;
}
.markdown-body blockquote {
margin: 10px 0;
padding: 6px 12px;
color: var(--text-dim);
background: rgba(255, 255, 255, 0.03);
border-left: 3px solid var(--line-strong);
}
.markdown-body hr {
margin: 16px 0;
border: 0;
border-top: 1px solid var(--line);
}
.markdown-body a {
color: #7feaf2;
text-decoration: none;
border-bottom: 1px solid rgba(127, 234, 242, 0.35);
}
.markdown-body a:hover {
color: var(--white);
border-bottom-color: var(--white);
}
.markdown-table-wrap {
margin: 10px 0;
overflow-x: auto;
}
.markdown-body table {
width: 100%;
border-collapse: collapse;
font-size: 12.5px;
}
.markdown-body th,
.markdown-body td {
padding: 6px 10px;
border: 1px solid var(--line);
text-align: left;
}
.markdown-body th {
color: var(--white);
background: rgba(255, 255, 255, 0.05);
}
.markdown-task {
margin-right: 6px;
vertical-align: middle;
}
+530 -3
View File
@@ -344,9 +344,12 @@
} }
/* ===== About ===== */ /* ===== About ===== */
.update-notes { .update-actions {
white-space: pre-line; display: flex;
overflow-wrap: anywhere; align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-top: 10px;
} }
.about-head { .about-head {
@@ -371,3 +374,527 @@
line-height: 1.6; line-height: 1.6;
color: var(--text-dim); color: var(--text-dim);
} }
.about-columns {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
align-items: start;
}
.about-column {
display: flex;
flex-direction: column;
gap: 14px;
min-width: 0;
}
.about-card {
min-width: 0;
padding: 14px 16px;
background: rgba(0, 0, 0, 0.14);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.about-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
}
.about-card-title {
margin: 0;
font: 500 14px var(--font-display);
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--white);
}
.about-card-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.about-card-meta {
margin: 8px 0 0;
font-size: 13px;
line-height: 1.5;
color: var(--text);
}
.about-card-label {
color: var(--text-dim);
}
.about-card .notice {
margin-top: 10px;
}
.about-card .notice .button {
margin-top: 8px;
}
/* ===== Mods ===== */
.mods-aside {
display: inline-flex;
align-items: center;
gap: 10px;
}
.mods-exp-chip {
position: relative;
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 7px;
font-size: 11.5px;
line-height: 1.3;
color: rgba(255, 227, 163, 0.9);
background: rgba(214, 158, 46, 0.14);
border: 1px solid rgba(214, 158, 46, 0.38);
border-radius: var(--radius);
cursor: help;
user-select: none;
}
.mods-exp-chip:hover,
.mods-exp-chip:focus-visible {
background: rgba(214, 158, 46, 0.22);
border-color: rgba(214, 158, 46, 0.6);
outline: none;
}
.mods-exp-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
font-size: 10px;
font-weight: 700;
font-style: normal;
border-radius: 50%;
border: 1px solid rgba(255, 227, 163, 0.55);
}
.mods-exp-popover {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 40;
width: 340px;
max-width: min(340px, 70vw);
display: flex;
flex-direction: column;
gap: 4px;
padding: 10px 12px;
font-size: 12px;
line-height: 1.5;
text-align: left;
white-space: normal;
color: rgba(255, 244, 218, 0.94);
background: rgba(16, 20, 24, 0.97);
border: 1px solid rgba(214, 158, 46, 0.5);
border-radius: var(--radius);
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55);
opacity: 0;
visibility: hidden;
pointer-events: none;
transform: translateY(-2px);
transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease;
}
.mods-exp-chip:hover .mods-exp-popover,
.mods-exp-chip:focus-visible .mods-exp-popover {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.mods-banner {
display: flex;
flex-direction: column;
gap: 3px;
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
line-height: 1.5;
border: 1px solid var(--line);
border-radius: var(--radius);
}
.mods-banner-warn {
background: rgba(206, 65, 55, 0.16);
border-color: rgba(206, 65, 55, 0.5);
color: #ffd7d4;
}
.mods-banner-ok {
background: rgba(68, 170, 102, 0.16);
border-color: rgba(68, 170, 102, 0.5);
color: #d7ffe4;
}
.mods-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.mods-search {
flex: 1 1 180px;
min-width: 140px;
}
.mods-preset-select {
max-width: 210px;
}
.mods-issues-box {
padding: 10px 12px;
margin-bottom: 12px;
font-size: 12.5px;
border-radius: var(--radius);
border: 1px solid var(--line);
}
.mods-issues-error {
background: rgba(206, 65, 55, 0.15);
border-color: rgba(206, 65, 55, 0.55);
}
.mods-issues-warn {
background: rgba(214, 158, 46, 0.13);
border-color: rgba(214, 158, 46, 0.45);
}
.mods-issues-title {
font-weight: 600;
margin-bottom: 6px;
}
.mods-issues-box ul {
margin: 0;
padding-left: 18px;
display: flex;
flex-direction: column;
gap: 4px;
}
.mods-issue-tag {
display: inline-block;
margin-right: 6px;
padding: 1px 5px;
font-size: 11px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.12);
}
.mods-empty {
padding: 20px 14px;
text-align: center;
border: 1px dashed var(--line);
border-radius: var(--radius);
}
.mods-hint {
font-size: 12.5px;
color: var(--text-dim);
line-height: 1.5;
margin: 6px 0 12px;
}
.mods-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-card {
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
transition: border-color 120ms ease;
}
.mods-card-enabled {
border-left: 3px solid var(--red);
background: rgba(18, 24, 29, 0.78);
}
.mods-card-row {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
}
.mods-order-num {
min-width: 26px;
font-size: 12px;
color: var(--text-dim);
text-align: right;
cursor: grab;
}
.mods-checkbox {
width: 16px;
height: 16px;
flex: none;
cursor: pointer;
}
.mods-card-main {
flex: 1;
min-width: 0;
cursor: pointer;
}
.mods-card-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.mods-name {
font-weight: 600;
color: var(--white);
}
.mods-version,
.mods-author {
font-size: 12px;
color: var(--text-dim);
}
.mods-card-desc {
margin-top: 3px;
font-size: 12px;
color: var(--text-dim);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mods-badges {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
}
.mods-badge {
padding: 1px 6px;
font-size: 11px;
border-radius: 2px;
border: 1px solid rgba(255, 255, 255, 0.16);
}
.mods-badge-data {
background: rgba(88, 166, 255, 0.16);
color: #b7d7ff;
}
.mods-badge-gui {
background: rgba(163, 113, 247, 0.18);
color: #dec8ff;
}
.mods-badge-script {
background: rgba(214, 158, 46, 0.22);
color: #ffe3a3;
}
.mods-badge-exe {
background: rgba(206, 65, 55, 0.28);
color: #ffc2be;
border-color: rgba(206, 65, 55, 0.55);
}
.mods-badge-error {
background: rgba(206, 65, 55, 0.35);
color: #ffd5d2;
}
.mods-badge-warn {
background: rgba(214, 158, 46, 0.25);
color: #ffe8b3;
}
.mods-card-actions {
display: flex;
align-items: center;
gap: 4px;
flex: none;
}
.mods-move-btn {
min-width: 28px;
padding: 4px 6px;
}
.mods-card-details {
padding: 10px 12px 12px 48px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--text-dim);
}
.mods-detail-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 4px 12px;
margin-bottom: 8px;
}
.mods-detail-summary {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.mods-detail-summary span {
padding: 2px 7px;
border-radius: 2px;
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.85);
}
.mods-section {
margin-bottom: 22px;
}
.mods-subheading {
margin: 0 0 4px;
font: 600 15px var(--font-display);
color: var(--white);
}
.mods-preset-form {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 10px 0 14px;
}
.mods-preset-form .input {
flex: 1 1 200px;
}
.mods-preset-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.mods-preset-item {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.62);
}
.mods-preset-active {
border-left: 3px solid var(--red);
}
.mods-preset-meta {
min-width: 0;
}
.mods-preset-name {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: var(--white);
}
.mods-preset-sub {
font-size: 12px;
color: var(--text-dim);
margin-top: 2px;
}
.mods-path {
font-size: 12px;
word-break: break-all;
}
/* ===== Tuning: Bot parameters ===== */
.tuning-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 8px 0 12px;
flex-wrap: wrap;
}
.tuning-toolbar .small {
margin: 0;
}
.tuning-group {
margin-bottom: 10px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(12, 16, 19, 0.56);
}
.tuning-group-summary {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
padding: 10px 14px;
cursor: pointer;
list-style: none;
font: 600 14px var(--font-display);
letter-spacing: 0.04em;
color: var(--white);
}
.tuning-group-summary::-webkit-details-marker {
display: none;
}
.tuning-group-summary::before {
content: '▸';
display: inline-block;
margin-right: 8px;
color: var(--text-dim);
transition: transform 120ms ease;
}
.tuning-group[open] > .tuning-group-summary::before {
transform: rotate(90deg);
}
.tuning-group-summary small {
font: 400 12px var(--font-ui);
letter-spacing: 0;
color: var(--text-dim);
margin-left: auto;
}
.tuning-group-body {
padding: 0 14px 8px;
border-top: 1px solid var(--line);
}
.tuning-actions {
margin-top: 14px;
}
+11
View File
@@ -24,6 +24,11 @@ export const APP_ERROR_CODES = [
'diagnostics_export_failed', 'diagnostics_export_failed',
'copy_not_found', 'copy_not_found',
'tuning_invalid', 'tuning_invalid',
'mods_read_only',
'mods_write_failed',
'mods_preset_invalid',
'mods_blocking_issues',
'mods_folder_invalid',
'save_not_found', 'save_not_found',
'save_archive_invalid', 'save_archive_invalid',
'save_official_invalid', 'save_official_invalid',
@@ -40,6 +45,8 @@ export const APP_ERROR_CODES = [
'maintenance_busy', 'maintenance_busy',
'maintenance_location', 'maintenance_location',
'maintenance_no_update', 'maintenance_no_update',
'maintenance_source_invalid',
'maintenance_source_overlap',
'maintenance_cancelled', 'maintenance_cancelled',
'maintenance_failed', 'maintenance_failed',
'maintenance_source_changed', 'maintenance_source_changed',
@@ -69,6 +76,8 @@ export const APP_ERROR_CODES = [
'launch_game_failed', 'launch_game_failed',
/** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */ /** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */
'launch_game_files_missing', 'launch_game_files_missing',
/** Optional UHQ texture packs have a mounted header without completed files (params: packs). */
'launch_incomplete_uhq_packs',
/** A folder the player chose does not exist or cannot be read (params: path). */ /** A folder the player chose does not exist or cannot be read (params: path). */
'folder_unreadable', 'folder_unreadable',
/** The chosen folder lacks the files of a War Thunder installation (params: path). */ /** The chosen folder lacks the files of a War Thunder installation (params: path). */
@@ -89,6 +98,8 @@ export const APP_ERROR_CODES = [
'missing_features_not_accepted', 'missing_features_not_accepted',
/** Working out which patches fit failed; the details are in the log. */ /** Working out which patches fit failed; the details are in the log. */
'patch_check_failed', 'patch_check_failed',
/** The packaged launcher itself sits inside the selected stock War Thunder folder. */
'launcher_inside_source',
/** Copying the game failed; what was copied has been removed. */ /** Copying the game failed; what was copied has been removed. */
'copy_failed', 'copy_failed',
'hardlink_unavailable', 'hardlink_unavailable',
+4
View File
@@ -14,8 +14,12 @@ export const IPC_CHANNEL_PREFIXES = [
'install:', 'install:',
/** Listing and managing installed copies. */ /** Listing and managing installed copies. */
'copies:', 'copies:',
/** Read-only detection of decal cache folders in player-selected or registered sources. */
'decals:',
/** Settings shared by the saves of a game copy. */ /** Settings shared by the saves of a game copy. */
'tuning:', 'tuning:',
/** Additive mods repository, per-copy ordering/toggles, and presets. */
'mods:',
/** Local account and save management. */ /** Local account and save management. */
'saves:', 'saves:',
/** Starting and stopping the active copy. */ /** Starting and stopping the active copy. */
+60 -3
View File
@@ -17,6 +17,7 @@ import {
} from '../schemas/install.ts'; } from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.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 { 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 { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts'; import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
@@ -64,8 +65,11 @@ export const ipcContract = {
output: z.object({ path: z.string().nullable() }), output: z.object({ path: z.string().nullable() }),
}, },
'dialog:pickFolder': { 'dialog:pickFolder': {
/** The dialog title, already translated by the window. */ /** The dialog title, already translated by the window, and an optional starting path. */
input: z.object({ title: z.string().optional() }), input: z.object({
title: z.string().optional(),
defaultPath: z.string().optional(),
}),
/** The chosen folder, or null when the player cancelled. */ /** The chosen folder, or null when the player cancelled. */
output: z.object({ path: z.string().nullable() }), output: z.object({ path: z.string().nullable() }),
}, },
@@ -154,6 +158,10 @@ export const ipcContract = {
input: z.object({ id: CopyIdSchema }), input: z.object({ id: CopyIdSchema }),
output: MaintenanceInfoSchema, output: MaintenanceInfoSchema,
}, },
'copies:maintenanceState': {
input: z.void(),
output: MaintenanceProgressSchema.nullable(),
},
'copies:maintain': { 'copies:maintain': {
input: MaintenanceRequestSchema, input: MaintenanceRequestSchema,
output: CopiesSchema, output: CopiesSchema,
@@ -162,6 +170,11 @@ export const ipcContract = {
input: z.void(), input: z.void(),
output: z.void(), output: z.void(),
}, },
'decals:detectSource': {
/** Read-only check for a usable decal cache inside a player-chosen or registered folder. */
input: z.object({ path: z.string().min(1) }),
output: z.object({ path: z.string().nullable() }),
},
'saves:list': { 'saves:list': {
input: z.object({ copyId: CopyIdSchema }), input: z.object({ copyId: CopyIdSchema }),
output: SaveListSchema, output: SaveListSchema,
@@ -258,6 +271,50 @@ export const ipcContract = {
input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }), input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }),
output: TuningViewSchema, output: TuningViewSchema,
}, },
'mods:getState': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:setEnabled': {
input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }),
output: ModsStateViewSchema,
},
'mods:setOrder': {
input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }),
output: ModsStateViewSchema,
},
'mods:autoSort': {
input: z.object({ copyId: CopyIdSchema }),
output: ModsStateViewSchema,
},
'mods:savePreset': {
input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }),
output: ModsStateViewSchema,
},
'mods:applyPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:deletePreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: ModsStateViewSchema,
},
'mods:exportPreset': {
input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }),
output: z.object({ path: z.string().nullable() }),
},
'mods:importPreset': {
input: z.object({ copyId: CopyIdSchema }),
output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }),
},
'mods:openFolder': {
input: z.void(),
output: z.void(),
},
'mods:setFolder': {
input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }),
output: ModsStateViewSchema,
},
'launch:getState': { 'launch:getState': {
input: z.void(), input: z.void(),
output: LaunchStateSchema, output: LaunchStateSchema,
@@ -334,7 +391,7 @@ export const ipcEvents = {
'event:app-update-progress': AppUpdateProgressSchema, 'event:app-update-progress': AppUpdateProgressSchema,
'event:launch-state': LaunchStateSchema, 'event:launch-state': LaunchStateSchema,
'event:copies-changed': CopiesSchema, 'event:copies-changed': CopiesSchema,
'event:copy-maintenance': MaintenanceProgressSchema, 'event:copy-maintenance': MaintenanceProgressSchema.nullable(),
/** Another patch set became active (a pack was installed, or the bundled set restored). */ /** Another patch set became active (a pack was installed, or the bundled set restored). */
'event:patch-set-changed': ActivePatchSetSchema, 'event:patch-set-changed': ActivePatchSetSchema,
} as const; } as const;
+24 -1
View File
@@ -1,5 +1,10 @@
import { z } from 'zod'; import { z } from 'zod';
/** Self-described origin of an offline client folder recorded in wtoffline/client.json. */
export const CLIENT_ORIGINS = ['copy', 'hardlink', 'in-place'] as const;
export const ClientOriginSchema = z.enum(CLIENT_ORIGINS);
export type ClientOrigin = z.output<typeof ClientOriginSchema>;
/** What the launcher found in a folder the player chose as their War Thunder installation. */ /** What the launcher found in a folder the player chose as their War Thunder installation. */
export const GameFolderInspectionSchema = z.object({ export const GameFolderInspectionSchema = z.object({
path: z.string(), path: z.string(),
@@ -16,6 +21,10 @@ export const GameFolderInspectionSchema = z.object({
hasOfflineBackup: z.boolean(), hasOfflineBackup: z.boolean(),
/** True when the folder is already patched for offline use but lacks a wtoffline/stock backup. */ /** True when the folder is already patched for offline use but lacks a wtoffline/stock backup. */
needsStockSource: z.boolean(), needsStockSource: z.boolean(),
/** Client origin recorded in wtoffline/client.json when present and valid, or null otherwise. */
clientOrigin: ClientOriginSchema.nullable().optional(),
/** True when at least one eligible read-only resource pack has multiple hard links (nlink >= 2). */
hasHardlinkedResources: z.boolean().optional(),
}); });
export type GameFolderInspection = z.output<typeof GameFolderInspectionSchema>; export type GameFolderInspection = z.output<typeof GameFolderInspectionSchema>;
@@ -143,6 +152,18 @@ export const InstallProgressSchema = z.object({
totalBytes: z.number(), totalBytes: z.number(),
doneFiles: z.number(), doneFiles: z.number(),
totalFiles: z.number(), totalFiles: z.number(),
/** Actual bytes written to disk during copying (excludes hard-linked files). */
copiedBytes: z.number().nonnegative().optional(),
/** Total bytes planned to be written to disk during copying (excludes hard-linked files). */
copyTotalBytes: z.number().nonnegative().optional(),
/** Bytes shared via hard links so far (occupies no extra disk space). */
linkedBytes: z.number().nonnegative().optional(),
/** Total bytes planned to be shared via hard links. */
linkTotalBytes: z.number().nonnegative().optional(),
/** Number of hard-linked files created so far. */
linkedFiles: z.number().nonnegative().optional(),
/** Total number of files planned to be shared via hard links. */
linkTotalFiles: z.number().nonnegative().optional(),
}); });
export type InstallProgress = z.output<typeof InstallProgressSchema>; export type InstallProgress = z.output<typeof InstallProgressSchema>;
@@ -150,7 +171,7 @@ export type InstallProgress = z.output<typeof InstallProgressSchema>;
export const InstallRecordSchema = z.object({ export const InstallRecordSchema = z.object({
id: CopyIdSchema, id: CopyIdSchema,
name: CopyNameSchema, name: CopyNameSchema,
/** Recorded only for a separate source copied during installation. */ /** Separate online installation used as the read-only update source. */
sourcePath: z.string().min(1).nullable(), sourcePath: z.string().min(1).nullable(),
method: z.enum(INSTALL_METHODS), method: z.enum(INSTALL_METHODS),
copyPath: z.string(), copyPath: z.string(),
@@ -173,6 +194,8 @@ export const InstallRecordSchema = z.object({
sourceFiles: z.array(z.string().min(1)).optional(), sourceFiles: z.array(z.string().min(1)).optional(),
/** Relative resource paths linked to the source and detached on a version update. */ /** Relative resource paths linked to the source and detached on a version update. */
hardlinkedFiles: z.array(z.string().min(1)).optional(), hardlinkedFiles: z.array(z.string().min(1)).optional(),
/** Client origin read from wtoffline/client.json when registering an existing folder. */
detectedOrigin: ClientOriginSchema.optional(),
/** Runtime check hydrated when listing copies (never persisted to copies.json): true if copyPath or core game files are missing on disk. */ /** Runtime check hydrated when listing copies (never persisted to copies.json): true if copyPath or core game files are missing on disk. */
folderMissing: z.boolean().optional(), folderMissing: z.boolean().optional(),
}); });
@@ -28,6 +28,7 @@ export const LaunchStateSchema = z.object({
actualVersion: z.string().nullable().optional(), actualVersion: z.string().nullable().optional(),
gameExit: GameExitSchema.optional(), gameExit: GameExitSchema.optional(),
error: z.enum(APP_ERROR_CODES).optional(), error: z.enum(APP_ERROR_CODES).optional(),
errorParams: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
}); });
export type LaunchState = z.output<typeof LaunchStateSchema>; export type LaunchState = z.output<typeof LaunchStateSchema>;
@@ -1,11 +1,14 @@
import { z } from 'zod'; import { z } from 'zod';
import { CopyIdSchema } from './install.ts'; import { ClientOriginSchema, CopyIdSchema } from './install.ts';
export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam']); export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam', 'set-source']);
export const MaintenanceRequestSchema = z.object({ export const MaintenanceRequestSchema = z.object({
id: CopyIdSchema, id: CopyIdSchema,
operation: MaintenanceOperationSchema, operation: MaintenanceOperationSchema,
deleteFiles: z.boolean().default(false),
restoreStock: z.boolean().default(false),
deleteData: z.boolean().default(false), deleteData: z.boolean().default(false),
sourcePath: z.string().min(1).optional(),
steamLocations: z.object({ steamLocations: z.object({
copyPath: z.string().min(1), copyPath: z.string().min(1),
dataPath: z.string().min(1), dataPath: z.string().min(1),
@@ -23,6 +26,10 @@ export const MaintenanceInfoSchema = z.object({
copyInSteam: z.boolean(), copyInSteam: z.boolean(),
dataInSteam: z.boolean(), dataInSteam: z.boolean(),
}).nullable(), }).nullable(),
clientOrigin: ClientOriginSchema.nullable(),
hasHardlinkedResources: z.boolean(),
canDeleteFiles: z.boolean(),
canRestoreAndRemove: z.boolean(),
}); });
export const MaintenanceProgressSchema = z.object({ export const MaintenanceProgressSchema = z.object({
id: CopyIdSchema, id: CopyIdSchema,
+87
View File
@@ -0,0 +1,87 @@
import { z } from 'zod';
export const ModRiskBadgeSchema = z.enum(['data', 'gui', 'script', 'exe']);
export const ModIssueSeveritySchema = z.enum(['error', 'warning', 'info']);
export const LocalizedTextSchema = z.union([z.string(), z.record(z.string(), z.string())]);
export const ModPackOperationSchema = z.object({
pack: z.string(),
targetPath: z.string(),
action: z.enum(['blk-patch', 'csv-patch', 'file']),
sourceRelativePath: z.string(),
});
export const ModListItemSchema = z.object({
id: z.string(),
folderName: z.string(),
rootDir: z.string(),
name: LocalizedTextSchema,
description: LocalizedTextSchema.optional(),
version: z.string(),
author: z.string(),
apiVersion: z.string(),
gameVersions: z.array(z.string()),
requires: z.array(z.string()),
conflicts: z.array(z.string()),
loadAfter: z.array(z.string()),
loadBefore: z.array(z.string()),
badges: z.array(ModRiskBadgeSchema),
hasServerScript: z.boolean(),
serverTuningFiles: z.array(z.string()),
packOperations: z.array(ModPackOperationSchema),
guiPatchCount: z.number().int().nonnegative(),
exePatchCount: z.number().int().nonnegative(),
hasClientAddon: z.boolean(),
addonFileCount: z.number().int().nonnegative(),
clientFileCount: z.number().int().nonnegative(),
hasConfigBlkPatch: z.boolean(),
});
export const ModDiscoveryErrorSchema = z.object({
folderName: z.string(),
rootDir: z.string(),
reason: z.string(),
});
export const ModIssueSchema = z.object({
severity: ModIssueSeveritySchema,
kind: z.string(),
modId: z.string(),
otherModId: z.string().optional(),
detail: z.string(),
});
export const ModPresetSchema = z.object({
id: z.string().min(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
updatedAt: z.string(),
});
export const ModsStateViewSchema = z.object({
modsDir: z.string(),
defaultModsDir: z.string(),
isCustomModsDir: z.boolean(),
apiVersion: z.string(),
mods: z.array(ModListItemSchema),
discoveryErrors: z.array(ModDiscoveryErrorSchema),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
activePresetId: z.string().nullable(),
presets: z.array(ModPresetSchema),
issues: z.array(ModIssueSchema),
hasBlockingErrors: z.boolean(),
});
export const ModPresetTransferSchema = z.object({
format: z.literal(1),
name: z.string().min(1).max(80),
order: z.array(z.string()),
enabled: z.record(z.string(), z.boolean()),
});
export type ModListItem = z.output<typeof ModListItemSchema>;
export type ModPresetView = z.output<typeof ModPresetSchema>;
export type ModIssueView = z.output<typeof ModIssueSchema>;
export type ModsStateView = z.output<typeof ModsStateViewSchema>;
+1 -1
View File
@@ -94,7 +94,7 @@ export const OfficialPreviewSchema = z.object({
omitted: z.array(z.string()), omitted: z.array(z.string()),
}); });
export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) }); export const ResearchBranchSchema = z.object({ country: z.string().min(1), type: z.string().min(1) });
export const ResearchOperationSchema = z.enum(['research', 'purchase', 'equipment']); export const ResearchOperationSchema = z.enum(['purchase', 'equipment']);
export const SaveResearchSchema = z.object({ export const SaveResearchSchema = z.object({
branches: z.array(ResearchBranchSchema), branches: z.array(ResearchBranchSchema),
selected: ResearchBranchSchema.nullable(), selected: ResearchBranchSchema.nullable(),
@@ -37,6 +37,8 @@ export const SettingsSchema = z.object({
developerMode: z.boolean().default(true), developerMode: z.boolean().default(true),
labStockPath: LabPathSchema.default(null), labStockPath: LabPathSchema.default(null),
labDataPath: LabPathSchema.default(null), labDataPath: LabPathSchema.default(null),
/** Custom global mods repository directory; null uses `<userData>/mods`. */
modsFolder: LabPathSchema.default(null),
}); });
export type Settings = z.output<typeof SettingsSchema>; export type Settings = z.output<typeof SettingsSchema>;
@@ -60,6 +62,7 @@ export const SettingsPatchSchema = z.object({
developerMode: z.boolean().optional(), developerMode: z.boolean().optional(),
labStockPath: LabPathSchema.optional(), labStockPath: LabPathSchema.optional(),
labDataPath: LabPathSchema.optional(), labDataPath: LabPathSchema.optional(),
modsFolder: LabPathSchema.optional(),
}); });
export type SettingsPatch = z.output<typeof SettingsPatchSchema>; export type SettingsPatch = z.output<typeof SettingsPatchSchema>;
+227 -1
View File
@@ -1,6 +1,225 @@
import { z } from 'zod'; import { z } from 'zod';
export const AUTO_TARGET_PICKS = ['lowestRank', 'highestRank', 'treeOrder'] as const; export const AUTO_TARGET_PICKS = ['lowestRank', 'highestRank', 'treeOrder'] as const;
export const GROUND_AI_MODES = ['stock', 'fire', 'drive', 'full'] as const;
export const GROUND_AI_DRIVE_MODES = ['vehicle_phys', 'movesys'] as const;
const GroundAiLoadoutSchema = z.object({
lowReadyRackThreshold: z.number().int().min(1).max(60),
topUpAmmoCount: z.number().int().min(4).max(80),
primaryAmmoPct: z.number().int().min(50).max(100),
secondaryMinRounds: z.number().int().min(0).max(20),
penetrationCompareDistM: z.number().int().min(100).max(2000),
});
const GroundAiLineupWeightsSchema = z.object({
spaa: z.number().min(0.01).max(10),
lightTank: z.number().min(0.01).max(10),
tankDestroyer: z.number().min(0.01).max(10),
heavyTank: z.number().min(0.01).max(10),
mediumTank: z.number().min(0.01).max(10),
other: z.number().min(0.01).max(10),
});
const GroundAiCadenceSchema = z.object({
maxBots: z.number().int().min(1).max(64),
macroTickSec: z.number().min(0.1).max(5),
tacticsTickSec: z.number().min(0.05).max(2),
navTickSec: z.number().min(0.05).max(2),
});
const GroundAiCommanderSchema = z.object({
rebalanceSec: z.number().min(1).max(30),
roleHoldSec: z.number().min(0).max(120),
bttlAssaultPct: z.number().int().min(0).max(100),
bttlFlankPct: z.number().int().min(0).max(100),
bttlOverwatchPct: z.number().int().min(0).max(100),
conqAssaultPct: z.number().int().min(0).max(100),
conqFlankPct: z.number().int().min(0).max(100),
conqHoldDefendPct: z.number().int().min(0).max(100),
conqHoldOverwatchPct: z.number().int().min(0).max(100),
domAssaultPct: z.number().int().min(0).max(100),
domMaxDefendersPerCap: z.number().int().min(0).max(4),
overwatchStandOffM: z.number().min(25).max(350),
flankStandOffM: z.number().min(25).max(300),
spaaFollowOffsetM: z.number().min(40).max(500),
flankMaxLengthRatio: z.number().min(1.05).max(3),
flankMinSeparationM: z.number().min(15).max(200),
rallyProgressFrac: z.number().min(0.1).max(0.75),
rallyWaitSec: z.number().min(3).max(60),
rallyMinFrac: z.number().min(0.25).max(1),
rallyRadiusM: z.number().min(15).max(140),
recallSafeHoldSec: z.number().min(3).max(60),
});
const GroundAiMacroSchema = z.object({
openingSplitSec: z.number().min(0).max(180),
capMaxInsiders: z.number().int().min(1).max(8),
recaptureMinBots: z.number().int().min(1).max(8),
recaptureMaxBots: z.number().int().min(1).max(12),
capStickyBonusM: z.number().min(0).max(800),
deathZoneRadiusM: z.number().min(10).max(250),
deathZoneTtlSec: z.number().min(5).max(300),
deathZoneMinKills: z.number().int().min(1).max(16),
spaaRearOffsetM: z.number().min(40).max(600),
spaaRelocateSec: z.number().min(5).max(180),
enemySpawnAvoidM: z.number().min(60).max(600),
});
const GroundAiCrowdSchema = z.object({
personalSpaceM: z.number().min(6).max(40),
clusterRadiusM: z.number().min(12).max(80),
clusterMaxAllies: z.number().int().min(1).max(10),
disperseStepM: z.number().min(8).max(65),
disperseHoldSec: z.number().min(1).max(15),
});
const GroundAiTerrainSchema = z.object({
maxClimbSlopeDeg: z.number().min(10).max(42),
maxDropSlopeDeg: z.number().min(8).max(40),
maxWaterDepthM: z.number().min(0.2).max(2.5),
collisionMarginM: z.number().min(0.05).max(2),
crestLookaheadM: z.number().min(8).max(80),
ridgeMaxDwellSec: z.number().min(2).max(60),
ridgeMaxShots: z.number().int().min(1).max(10),
});
const GroundAiNavigationSchema = z.object({
driveMode: z.enum(GROUND_AI_DRIVE_MODES),
maxPhysBots: z.number().int().min(0).max(64),
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 GroundAiPerceptionSchema = z.object({
foliageTransparency: z.number().min(0.001).max(1),
nearSpotRangeM: z.number().min(20).max(250),
firingSpotRangeM: z.number().min(150).max(1500),
fastSpotSec: z.number().min(0.05).max(1.5),
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),
});
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),
repositionMinMoveM: z.number().min(5).max(80),
repositionStepM: z.number().min(15).max(120),
repairSafeEnemyDistM: z.number().min(30).max(400),
});
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),
memoryTtlSec: z.number().min(1).max(45),
targetStickinessSec: z.number().min(0.5).max(20),
peekCooldownSec: z.number().min(1).max(30),
});
const GroundAiEstimationSchema = z.object({
watchMinSec: z.number().min(0.5).max(10),
watchMaxSec: z.number().min(1).max(15),
velSampleMinSpanSec: z.number().min(0.05).max(2),
velStableSpanSec: z.number().min(0.2).max(6),
velJumpResetMps: z.number().min(1).max(20),
baseAimSigmaM: z.number().min(0).max(2),
leadErrorFrac: z.number().min(0).max(1),
maxBiasM: z.number().min(0).max(6),
});
const GroundAiFireControlSchema = z.object({
maxEngageRangeM: z.number().min(150).max(3000),
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),
friendlyCorridorM: z.number().min(1).max(10),
ballisticStepMaxM: z.number().min(5).max(80),
ballisticSweepRadiusM: z.number().min(0.02).max(0.5),
maxPreFireChecksPerTick: z.number().int().min(1).max(16),
});
const GroundAiDiagnosticsSchema = z.object({
telemetry: z.boolean(),
telemetryIntervalSec: z.number().min(0.5).max(60),
});
export const GroundAiTuningSchema = z.object({
mode: z.enum(GROUND_AI_MODES),
loadout: GroundAiLoadoutSchema,
lineupWeights: GroundAiLineupWeightsSchema,
cadence: GroundAiCadenceSchema,
commander: GroundAiCommanderSchema,
macro: GroundAiMacroSchema,
crowd: GroundAiCrowdSchema,
terrain: GroundAiTerrainSchema,
navigation: GroundAiNavigationSchema,
perception: GroundAiPerceptionSchema,
stateMachine: GroundAiStateMachineSchema,
tactics: GroundAiTacticsSchema,
estimation: GroundAiEstimationSchema,
fireControl: GroundAiFireControlSchema,
diagnostics: GroundAiDiagnosticsSchema,
});
export const GroundAiTuningPatchSchema = z.object({
mode: z.enum(GROUND_AI_MODES).optional(),
loadout: GroundAiLoadoutSchema.partial().optional(),
lineupWeights: GroundAiLineupWeightsSchema.partial().optional(),
cadence: GroundAiCadenceSchema.partial().optional(),
commander: GroundAiCommanderSchema.partial().optional(),
macro: GroundAiMacroSchema.partial().optional(),
crowd: GroundAiCrowdSchema.partial().optional(),
terrain: GroundAiTerrainSchema.partial().optional(),
navigation: GroundAiNavigationSchema.partial().optional(),
perception: GroundAiPerceptionSchema.partial().optional(),
stateMachine: GroundAiStateMachineSchema.partial().optional(),
tactics: GroundAiTacticsSchema.partial().optional(),
estimation: GroundAiEstimationSchema.partial().optional(),
fireControl: GroundAiFireControlSchema.partial().optional(),
diagnostics: GroundAiDiagnosticsSchema.partial().optional(),
});
export const TuningValuesSchema = z.object({ export const TuningValuesSchema = z.object({
rewardMultiplierSilverLions: z.number().min(0).max(100), rewardMultiplierSilverLions: z.number().min(0).max(100),
rewardMultiplierResearchPoints: z.number().min(0).max(100), rewardMultiplierResearchPoints: z.number().min(0).max(100),
@@ -9,16 +228,23 @@ export const TuningValuesSchema = z.object({
smallTeamsMaxPlayers: z.number().int().min(2).max(64), smallTeamsMaxPlayers: z.number().int().min(2).max(64),
brSpreadMrank: z.number().int().min(0).max(12), brSpreadMrank: z.number().int().min(0).max(12),
subModeChance: z.number().min(0).max(1), subModeChance: z.number().min(0).max(1),
botPoolLimitPerType: z.number().int().min(4).max(200),
tankBotRespawns: z.number().int().min(1).max(10), tankBotRespawns: z.number().int().min(1).max(10),
airBotRespawns: z.number().int().min(1).max(10), airBotRespawns: z.number().int().min(1).max(10),
strikeUcavSpawnScore: z.number().int().min(1).max(10000), strikeUcavSpawnScore: z.number().int().min(1).max(10000),
nuclearEscalationStrategicBombers: z.boolean(),
silverLions: z.number().int().nonnegative(), silverLions: z.number().int().nonnegative(),
goldenEagles: z.number().int().min(0).max(0x7fffffff), goldenEagles: z.number().int().min(0).max(0x7fffffff),
preferLineSuccessor: z.boolean(), preferLineSuccessor: z.boolean(),
autoTargetPick: z.enum(AUTO_TARGET_PICKS), autoTargetPick: z.enum(AUTO_TARGET_PICKS),
groundAi: GroundAiTuningSchema,
});
export const TuningPatchSchema = TuningValuesSchema.omit({ groundAi: true }).partial().extend({
groundAi: GroundAiTuningPatchSchema.optional(),
}); });
export const TuningPatchSchema = TuningValuesSchema.partial();
export const TuningViewSchema = z.object({ defaults: TuningValuesSchema, effective: TuningValuesSchema }); export const TuningViewSchema = z.object({ defaults: TuningValuesSchema, effective: TuningValuesSchema });
export type GroundAiTuningValues = z.output<typeof GroundAiTuningSchema>;
export type GroundAiTuningPatch = z.output<typeof GroundAiTuningPatchSchema>;
export type TuningValues = z.output<typeof TuningValuesSchema>; export type TuningValues = z.output<typeof TuningValuesSchema>;
export type TuningPatch = z.output<typeof TuningPatchSchema>; export type TuningPatch = z.output<typeof TuningPatchSchema>;
export type TuningView = z.output<typeof TuningViewSchema>; export type TuningView = z.output<typeof TuningViewSchema>;
+1
View File
@@ -9,6 +9,7 @@
"dependencies": { "dependencies": {
"@wto/blk": "*", "@wto/blk": "*",
"@wto/jsonc": "*", "@wto/jsonc": "*",
"@wto/mods": "*",
"@wto/vromfs": "*" "@wto/vromfs": "*"
} }
} }
@@ -16,6 +16,7 @@ export interface BattleEconomyTuning {
readonly eventScores: Readonly<Record<VictimGroup, Readonly<Record<ScoredEvent, number>>>>; readonly eventScores: Readonly<Record<VictimGroup, Readonly<Record<ScoredEvent, number>>>>;
readonly captureZoneScore: Readonly<Record<VictimGroup, number>>; readonly captureZoneScore: Readonly<Record<VictimGroup, number>>;
readonly navalDamageScorePerPoint: number; readonly navalDamageScorePerPoint: number;
readonly bombingZone: { readonly damageScore: number; readonly destructionScore: number };
readonly referenceScore: Readonly<Record<VictimGroup, number>>; readonly referenceScore: Readonly<Record<VictimGroup, number>>;
readonly friendlyKillPenaltyMul: number; readonly friendlyKillPenaltyMul: number;
} }
@@ -30,6 +31,7 @@ export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuni
for (const expClass of groups.stringList(group)) victimGroups.set(expClass, group); for (const expClass of groups.stringList(group)) victimGroups.set(expClass, group);
} }
const scores = reader.object('eventScores'); const scores = reader.object('eventScores');
const bombingZone = reader.object('bombingZone');
const perGroup = (key: string, min: number): Record<VictimGroup, number> => { const perGroup = (key: string, min: number): Record<VictimGroup, number> => {
const table = reader.object(key); const table = reader.object(key);
return Object.fromEntries(VICTIM_GROUPS.map((group) => [group, table.number(group, { min, max: 100000 })])) as Record<VictimGroup, number>; return Object.fromEntries(VICTIM_GROUPS.map((group) => [group, table.number(group, { min, max: 100000 })])) as Record<VictimGroup, number>;
@@ -42,6 +44,10 @@ export function readBattleEconomyTuning(reader: TuningReader): BattleEconomyTuni
})) as Record<VictimGroup, Record<ScoredEvent, number>>, })) as Record<VictimGroup, Record<ScoredEvent, number>>,
captureZoneScore: perGroup('captureZoneScore', 0), captureZoneScore: perGroup('captureZoneScore', 0),
navalDamageScorePerPoint: reader.number('navalDamageScorePerPoint', { min: 0, max: 100 }), navalDamageScorePerPoint: reader.number('navalDamageScorePerPoint', { min: 0, max: 100 }),
bombingZone: {
damageScore: bombingZone.int('damageScore', { min: 0, max: 100000 }),
destructionScore: bombingZone.int('destructionScore', { min: 0, max: 100000 }),
},
referenceScore: perGroup('referenceScore', 1), referenceScore: perGroup('referenceScore', 1),
friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }), friendlyKillPenaltyMul: reader.number('friendlyKillPenaltyMul', { min: 0, max: 100 }),
}; };
+42 -13
View File
@@ -16,11 +16,13 @@ import { SCORED_EVENTS, VICTIM_GROUPS, type BattleEconomyTuning, type ScoredEven
/** EXP_EVENT_* codes the LocalMP host reports (gui.vromfs.bin globalScripts/expEventConsts.nut). */ /** EXP_EVENT_* codes the LocalMP host reports (gui.vromfs.bin globalScripts/expEventConsts.nut). */
export const ExpEvent = { export const ExpEvent = {
CAPTURE_ZONE: 2, CAPTURE_ZONE: 2,
DESTROY_ZONE: 3,
KILL: 5, KILL: 5,
KILL_GROUND: 6, KILL_GROUND: 6,
ASSIST: 9, ASSIST: 9,
CRITICAL_HIT: 10, CRITICAL_HIT: 10,
HIT: 13, HIT: 13,
DAMAGE_ZONE: 17,
UNIT_DAMAGE: 24, UNIT_DAMAGE: 24,
SEVERE_DAMAGE: 35, SEVERE_DAMAGE: 35,
KILL_HUMAN: 39, KILL_HUMAN: 39,
@@ -30,7 +32,14 @@ export const ExpEvent = {
export type DebriefingRow = export type DebriefingRow =
| 'AirKills' | 'GroundKills' | 'NavalKills' | 'HumanKills' | 'FriendlyKills' | 'AirKills' | 'GroundKills' | 'NavalKills' | 'HumanKills' | 'FriendlyKills'
| 'Assist' | 'AirSevereDamage' | 'ShipSevereDamage' | 'Critical' | 'Hit' | 'Assist' | 'AirSevereDamage' | 'ShipSevereDamage' | 'Critical' | 'Hit'
| 'Captures' | 'AwardDamage'; | 'Captures' | 'Damage' | 'Destruction' | 'AwardDamage';
/** LocalMP reports mini-base health as basis points (local_mp_zones.c). */
const ZONE_HEALTH_SCALE = 10_000;
function isBombingZoneEvent(code: number): boolean {
return code === ExpEvent.DAMAGE_ZONE || code === ExpEvent.DESTROY_ZONE;
}
/** What the client reports for one combat event (patches/gui/battle/record-local-battle-awards). */ /** What the client reports for one combat event (patches/gui/battle/record-local-battle-awards). */
export interface CombatEventFact { export interface CombatEventFact {
@@ -38,12 +47,13 @@ export interface CombatEventFact {
readonly expClass: string; readonly expClass: string;
readonly victimIsPlayer: boolean; readonly victimIsPlayer: boolean;
readonly friendly: boolean; readonly friendly: boolean;
/** Naval damage points or, for DAMAGE_ZONE, basis points of the zone's full health. */
readonly damage: number; readonly damage: number;
} }
export interface PricedEvent { export interface PricedEvent {
readonly row: DebriefingRow; readonly row: DebriefingRow;
/** How much the row's counter grows: 1, or the damage points for AwardDamage. */ /** How much the stock row's counter grows. Damage counts TNT mass, which is unavailable here. */
readonly count: number; readonly count: number;
readonly wp: number; readonly wp: number;
readonly exp: number; readonly exp: number;
@@ -68,6 +78,7 @@ export interface BannerParams {
readonly rpClass: Readonly<Record<string, number>>; readonly rpClass: Readonly<Record<string, number>>;
readonly aiKillK: number; readonly aiKillK: number;
readonly friendlyKillPenaltyMul: number; readonly friendlyKillPenaltyMul: number;
readonly zoneHealthScale: number;
} }
export interface RewardMultipliers { export interface RewardMultipliers {
@@ -128,37 +139,46 @@ export class BattleEconomy {
}; };
} }
price(vehicle: string, difficulty: EconomyDifficulty, fact: CombatEventFact): PricedEvent | undefined { price(vehicle: string, difficulty: EconomyDifficulty, modeName: string, fact: CombatEventFact): PricedEvent | undefined {
const economy = this.vehicle(vehicle); const economy = this.vehicle(vehicle);
if (!economy) return undefined; if (!economy) return undefined;
const isCapture = fact.code === ExpEvent.CAPTURE_ZONE; const isCapture = fact.code === ExpEvent.CAPTURE_ZONE;
const group = isCapture ? this.victimGroup(economy.unitClass) : this.victimGroup(fact.expClass); const isBombingZone = isBombingZoneEvent(fact.code);
const isZoneDamage = fact.code === ExpEvent.DAMAGE_ZONE;
if (isBombingZone && (modeName !== 'air_arcade' || 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);
const row = debriefingRow(fact, group); const row = debriefingRow(fact, group);
const base = this.baseReward(vehicle, difficulty, fact.code, group); const base = this.baseReward(vehicle, difficulty, fact.code, group);
if (!row || !base) return undefined; if (!row || !base) return undefined;
const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1; const count = fact.code === ExpEvent.UNIT_DAMAGE ? Math.max(0, Math.trunc(fact.damage)) : 1;
const ai = isCapture || fact.victimIsPlayer ? 1 : this.data.aiKillK; const quantity = isZoneDamage ? fact.damage / ZONE_HEALTH_SCALE : count;
const slClass = isCapture ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1; const ai = isObjective || fact.victimIsPlayer ? 1 : this.data.aiKillK;
const rpClass = isCapture ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1; const slClass = isObjective ? 1 : this.data.silverLionsClassFactors[fact.expClass] ?? 1;
const rpClass = isObjective ? 1 : this.data.researchClassFactors[fact.expClass] ?? 1;
if (fact.friendly) { if (fact.friendly) {
return { row: 'FriendlyKills', count: 1, wp: -Math.round(base.wp * slClass * ai * this.#tuning.friendlyKillPenaltyMul), exp: 0 }; return { row: 'FriendlyKills', count: 1, wp: -Math.round(base.wp * slClass * ai * this.#tuning.friendlyKillPenaltyMul), exp: 0 };
} }
return { return {
row, row,
count, count: isZoneDamage ? 0 : count,
wp: Math.round(base.wp * slClass * ai * count), wp: Math.round(base.wp * slClass * ai * quantity),
exp: Math.round(base.exp * rpClass * ai * count), exp: Math.round(base.exp * rpClass * ai * quantity),
}; };
} }
bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty): BannerParams { bannerParams(vehicles: Iterable<string>, difficulty: EconomyDifficulty, modeName: string): BannerParams {
const table: Record<string, Record<string, [number, number]>> = {}; const table: Record<string, Record<string, [number, number]>> = {};
for (const name of vehicles) { for (const name of vehicles) {
const economy = this.vehicle(name); const economy = this.vehicle(name);
if (!economy || table[name]) continue; if (!economy || table[name]) continue;
const entries: Record<string, [number, number]> = {}; const entries: Record<string, [number, number]> = {};
for (const code of Object.values(ExpEvent)) { for (const code of Object.values(ExpEvent)) {
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own'] : ['ground', 'air', 'naval', 'human']; const isBombingZone = isBombingZoneEvent(code);
if (isBombingZone && modeName !== 'air_arcade') continue;
const groups: readonly (VictimGroup | 'own')[] = code === ExpEvent.CAPTURE_ZONE ? ['own']
: isBombingZone ? ['ground'] : VICTIM_GROUPS;
for (const group of groups) { for (const group of groups) {
const priceGroup = group === 'own' ? this.victimGroup(economy.unitClass) : group; const priceGroup = group === 'own' ? this.victimGroup(economy.unitClass) : group;
const base = this.baseReward(name, difficulty, code, priceGroup); const base = this.baseReward(name, difficulty, code, priceGroup);
@@ -174,6 +194,7 @@ export class BattleEconomy {
rpClass: this.data.researchClassFactors, rpClass: this.data.researchClassFactors,
aiKillK: this.data.aiKillK, aiKillK: this.data.aiKillK,
friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul, friendlyKillPenaltyMul: this.#tuning.friendlyKillPenaltyMul,
zoneHealthScale: ZONE_HEALTH_SCALE,
}; };
} }
@@ -183,7 +204,7 @@ export class BattleEconomy {
* the official mission scores of tuning/battle-economy.jsonc, and aiKillK for victims that are * the official mission scores of tuning/battle-economy.jsonc, and aiKillK for victims that are
* not players, as in the rewards. * not players, as in the rewards.
*/ */
missionScores(): Readonly<Record<string, number>> { missionScores(modeName: string): Readonly<Record<string, number>> {
const scores: Record<string, number> = {}; const scores: Record<string, number> = {};
for (const group of VICTIM_GROUPS) { for (const group of VICTIM_GROUPS) {
for (const event of SCORED_EVENTS) scores[`wtoScore_${event}_${group}`] = this.#tuning.eventScores[group][event]; for (const event of SCORED_EVENTS) scores[`wtoScore_${event}_${group}`] = this.#tuning.eventScores[group][event];
@@ -191,6 +212,10 @@ export class BattleEconomy {
} }
scores.wtoScore_damagePerPoint = this.#tuning.navalDamageScorePerPoint; scores.wtoScore_damagePerPoint = this.#tuning.navalDamageScorePerPoint;
scores.wtoScore_aiMul = this.data.aiKillK; scores.wtoScore_aiMul = this.data.aiKillK;
if (modeName === 'air_arcade') {
scores.wtoScore_zoneDamage = this.#tuning.bombingZone.damageScore;
scores.wtoScore_zoneDestruction = this.#tuning.bombingZone.destructionScore;
}
return scores; return scores;
} }
@@ -205,6 +230,8 @@ export class BattleEconomy {
case ExpEvent.HIT: return scored('hit'); case ExpEvent.HIT: return scored('hit');
case ExpEvent.SEVERE_DAMAGE: return scored('severeDamage'); case ExpEvent.SEVERE_DAMAGE: return scored('severeDamage');
case ExpEvent.CAPTURE_ZONE: return this.#tuning.captureZoneScore[group]; case ExpEvent.CAPTURE_ZONE: return this.#tuning.captureZoneScore[group];
case ExpEvent.DAMAGE_ZONE: return this.#tuning.bombingZone.damageScore;
case ExpEvent.DESTROY_ZONE: return this.#tuning.bombingZone.destructionScore;
case ExpEvent.UNIT_DAMAGE: return this.#tuning.navalDamageScorePerPoint; case ExpEvent.UNIT_DAMAGE: return this.#tuning.navalDamageScorePerPoint;
default: return undefined; default: return undefined;
} }
@@ -223,6 +250,8 @@ function debriefingRow(fact: CombatEventFact, group: VictimGroup): DebriefingRow
case ExpEvent.HIT: return 'Hit'; case ExpEvent.HIT: return 'Hit';
case ExpEvent.SEVERE_DAMAGE: return group === 'naval' ? 'ShipSevereDamage' : 'AirSevereDamage'; case ExpEvent.SEVERE_DAMAGE: return group === 'naval' ? 'ShipSevereDamage' : 'AirSevereDamage';
case ExpEvent.CAPTURE_ZONE: return 'Captures'; case ExpEvent.CAPTURE_ZONE: return 'Captures';
case ExpEvent.DAMAGE_ZONE: return 'Damage';
case ExpEvent.DESTROY_ZONE: return 'Destruction';
case ExpEvent.UNIT_DAMAGE: return 'AwardDamage'; case ExpEvent.UNIT_DAMAGE: return 'AwardDamage';
default: return undefined; default: return undefined;
} }
+74 -1
View File
@@ -22,6 +22,7 @@
import { randomInt } from 'node:crypto'; import { randomInt } from 'node:crypto';
import type { import type {
BattleSpawnRulesData, BattleSpawnRulesData,
NuclearCarrierUnit,
RandomSpawnGroup, RandomSpawnGroup,
RandomSpawnUnit, RandomSpawnUnit,
SupportPlanePreset, SupportPlanePreset,
@@ -43,6 +44,8 @@ export interface ExtraBattleSlot {
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */ /** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
readonly modifications: readonly string[]; readonly modifications: readonly string[];
readonly forceWeapon?: string; readonly forceWeapon?: string;
/** Restricts the respawn weapon dropdown to these presets when multiple mode presets exist. */
readonly allowedWeapons?: readonly string[];
/** The RandomSpawnUnits group the vehicle was drawn from. */ /** The RandomSpawnUnits group the vehicle was drawn from. */
readonly groupName?: string; readonly groupName?: string;
} }
@@ -56,7 +59,10 @@ export interface ExtraBattleSlotsInput {
readonly sessionMaxMrank: number; readonly sessionMaxMrank: number;
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>; readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
readonly rules: BattleSpawnRulesData; readonly rules: BattleSpawnRulesData;
readonly tuning: Pick<BattleTuning, 'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore'>; readonly tuning: Pick<
BattleTuning,
'strikeUcavModes' | 'strikeUcavSessionMrankAllowance' | 'strikeUcavSpawnScore' | 'nuclearEscalationStrategicBombers'
>;
} }
export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] { export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly ExtraBattleSlot[] {
@@ -68,6 +74,7 @@ export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly E
if (supportPlane) supportSlots.push(supportPlane); if (supportPlane) supportSlots.push(supportPlane);
const ucav = strikeUcavSlot(input); const ucav = strikeUcavSlot(input);
if (ucav) supportSlots.push(ucav); if (ucav) supportSlots.push(ucav);
supportSlots.push(...nuclearEscalationSlots(input));
// Keep room for fixed support vehicles while displaying random vehicle groups first. // Keep room for fixed support vehicles while displaying random vehicle groups first.
const slots: ExtraBattleSlot[] = []; const slots: ExtraBattleSlot[] = [];
@@ -118,6 +125,72 @@ function strikeUcavSlot(input: ExtraBattleSlotsInput): ExtraBattleSlot | undefin
}; };
} }
const NUCLEAR_ESCALATION_TAG_PREFIX = 'nuclear_escalation_';
const GROUND_RB_SUPPORT_MODE = 'tank_event_in_random_battles_historical';
const EASTERN_STRATEGIC_BOMBER_COUNTRIES = new Set(['country_ussr', 'country_china']);
function nuclearEscalationSlots(input: ExtraBattleSlotsInput): ExtraBattleSlot[] {
if (!input.declaration.tag?.startsWith(NUCLEAR_ESCALATION_TAG_PREFIX)) return [];
const slots: ExtraBattleSlot[] = [];
const tactical = selectTacticalNuclearCarrier(input);
if (tactical) {
const weaponNames = tactical.weapons.map((weapon) => weapon.name);
slots.push({
unitName: tactical.unitName,
allModifications: true,
modifications: [],
...(weaponNames.length === 1 ? { forceWeapon: weaponNames[0]! } : { allowedWeapons: weaponNames }),
});
}
if (input.tuning.nuclearEscalationStrategicBombers) {
const strategic = selectStrategicNuclearBomber(input.country, input.rules.nuclearEscalationStrategicBombers);
if (strategic) {
const weapon = strategic.weapons[0];
slots.push({
unitName: strategic.unitName,
allModifications: true,
modifications: [],
...(weapon ? { forceWeapon: weapon.name } : {}),
});
}
}
return slots;
}
function selectTacticalNuclearCarrier(input: ExtraBattleSlotsInput): NuclearCarrierUnit | undefined {
const byCountry = input.rules.nuclearEscalationTacticalCarriers.filter((entry) => entry.country === input.country);
if (byCountry.length === 0) return undefined;
// Prefer the stock Ground RB nuclear carrier for the matching rank bracket when it carries
// Nuclear Escalation 5 kt / 30 kt presets; otherwise pick the country's closest-mrank carrier.
const groundPresets = input.rules.supportPlanes[GROUND_RB_SUPPORT_MODE] ?? [];
const bracket = groundPresets.find((p) => input.sessionMaxMrank >= p.minMrank && input.sessionMaxMrank <= p.maxMrank);
const preferredUnit = bracket?.units[input.country]?.unitName;
if (preferredUnit) {
const matched = byCountry.find((entry) => entry.unitName === preferredUnit);
if (matched) return matched;
}
return [...byCountry].sort((a, b) => {
const distA = Math.abs(a.mrank - input.sessionMaxMrank);
const distB = Math.abs(b.mrank - input.sessionMaxMrank);
if (distA !== distB) return distA - distB;
const underA = a.mrank <= input.sessionMaxMrank ? 0 : 1;
const underB = b.mrank <= input.sessionMaxMrank ? 0 : 1;
if (underA !== underB) return underA - underB;
return a.mrank - b.mrank || a.unitName.localeCompare(b.unitName);
})[0];
}
function selectStrategicNuclearBomber(
country: string,
bombers: readonly NuclearCarrierUnit[],
): NuclearCarrierUnit | undefined {
if (bombers.length === 0) return undefined;
const preferredCountry = EASTERN_STRATEGIC_BOMBER_COUNTRIES.has(country) ? 'country_ussr' : 'country_usa';
return bombers.find((entry) => entry.country === preferredCountry) ?? bombers[0];
}
/** /**
* The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits, * The options of one random group: the group's vehicles inside `randomWindow`, or, when none fits,
* those of the highest rank below it. Vehicles already in the lineup are left out (offline * those of the highest rank below it. Vehicles already in the lineup are left out (offline
+55 -13
View File
@@ -10,7 +10,7 @@ import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-ru
import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts'; import type { MissionHeader } from '../game-data/datasets/multiplayer-missions.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts'; import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { MISSION_DIFFICULTY, SINGLE_SPAWN } from '../game-modes/mode-definition.ts'; import { MISSION_DIFFICULTY, SINGLE_SPAWN, UNLIMITED_RESPAWNS, modeMaxRespawns } from '../game-modes/mode-definition.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts'; import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts'; import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts'; import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
@@ -19,11 +19,13 @@ import {
isModeEligibleForLineup, isModeEligibleForLineup,
lineupMrank, lineupMrank,
selectCustomBots, selectCustomBots,
type TankLineupWeights,
type CustomBotsPool, type CustomBotsPool,
} from './battle-ranks.ts'; } from './battle-ranks.ts';
import type { BattleSessionStore } from './battle-session-store.ts'; import type { BattleSessionStore } from './battle-session-store.ts';
import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts'; import { battleSpawnScore, type BattleSpawnScore } from './battle-spawn-score.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts'; import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
import type { BattleTuning } from './battle-tuning.ts'; import type { BattleTuning } from './battle-tuning.ts';
export interface BattleCrewSlot { export interface BattleCrewSlot {
@@ -37,6 +39,7 @@ export interface EnqueueBattleInput {
readonly modes?: readonly OfferedGameMode[]; readonly modes?: readonly OfferedGameMode[];
readonly country: string; readonly country: string;
readonly slotVehicles: readonly string[]; readonly slotVehicles: readonly string[];
readonly mrankDeltas: ReadonlyMap<string, number>;
readonly selectedSlot?: BattleCrewSlot; readonly selectedSlot?: BattleCrewSlot;
readonly bannedMissions: ReadonlySet<string>; readonly bannedMissions: ReadonlySet<string>;
readonly dislikedMissions: ReadonlySet<string>; readonly dislikedMissions: ReadonlySet<string>;
@@ -46,10 +49,12 @@ export interface BattleLaunchPlan {
readonly sessionId: string; readonly sessionId: string;
readonly modeId: number; readonly modeId: number;
readonly modeName: string; readonly modeName: string;
readonly modeTag?: string;
readonly economicName: string; readonly economicName: string;
readonly missionName: string; readonly missionName: string;
/** The mission as the game describes it, including the parameters copied into the mission settings. */ /** The mission as the game describes it, including the parameters copied into the mission settings. */
readonly mission: MissionHeader; readonly mission: MissionHeader;
readonly missionRuleKeys: readonly string[];
readonly missionFile: string; readonly missionFile: string;
readonly missionType: string; readonly missionType: string;
readonly level?: string; readonly level?: string;
@@ -67,6 +72,8 @@ export interface BattleLaunchPlan {
readonly maxMrank: number; readonly maxMrank: number;
readonly maxPlayers: number; readonly maxPlayers: number;
readonly maxBots: number; readonly maxBots: number;
readonly maxRespawns?: number;
readonly allowSpares: boolean;
readonly tankBotRespawns: number; readonly tankBotRespawns: number;
readonly airBotRespawns: number; readonly airBotRespawns: number;
readonly useTankBots: boolean; readonly useTankBots: boolean;
@@ -82,6 +89,16 @@ export type MatchmakeOutcome =
| { readonly ok: true; readonly launch: BattleLaunchPlan } | { readonly ok: true; readonly launch: BattleLaunchPlan }
| { readonly ok: false; readonly error: string }; | { readonly ok: false; readonly error: string };
export type MissionPoolFilter = (ctx: {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly MissionHeader[];
}) => readonly MissionHeader[];
export class BattleMatchmaker { export class BattleMatchmaker {
readonly #gameModes: GameModes; readonly #gameModes: GameModes;
readonly #vehicles: readonly CatalogueVehicle[]; readonly #vehicles: readonly CatalogueVehicle[];
@@ -90,6 +107,9 @@ export class BattleMatchmaker {
readonly #tuning: BattleTuning; readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData; readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>; readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
readonly #tankWeights: TankLineupWeights | undefined;
readonly #tankLoadouts: ReadonlyMap<string, BotTankLoadout> | undefined;
readonly #filterMissions: MissionPoolFilter | undefined;
constructor( constructor(
gameModes: GameModes, gameModes: GameModes,
@@ -98,6 +118,9 @@ export class BattleMatchmaker {
tuning: BattleTuning, tuning: BattleTuning,
spawnRules: BattleSpawnRulesData, spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>, aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights: TankLineupWeights | undefined,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
filterMissions?: MissionPoolFilter,
) { ) {
this.#gameModes = gameModes; this.#gameModes = gameModes;
this.#vehicles = vehicles; this.#vehicles = vehicles;
@@ -106,6 +129,9 @@ export class BattleMatchmaker {
this.#tuning = tuning; this.#tuning = tuning;
this.#spawnRules = spawnRules; this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts; this.#aircraftLoadouts = aircraftLoadouts;
this.#tankWeights = tankWeights;
this.#tankLoadouts = tankLoadouts;
this.#filterMissions = filterMissions;
} }
enqueue(input: EnqueueBattleInput): MatchmakeOutcome { enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
@@ -117,19 +143,32 @@ export class BattleMatchmaker {
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0, (mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
); );
if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' }; if (pvpModes.length === 0) return { ok: false, error: 'PVE_NOT_SUPPORTED' };
const chosenMode = this.#pickQueuedMode(pvpModes, input.slotVehicles, input.selectedSlot?.unitName); const chosenMode = this.#pickQueuedMode(pvpModes, input);
if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' }; if (!chosenMode) return { ok: false, error: 'BAD_PARAMS' };
const { declaration } = chosenMode; const { declaration } = chosenMode;
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName); const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
const playerMrank = lineupMrank( const playerMrank = lineupMrank(
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses, activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
input.mrankDeltas,
); );
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank); const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity; const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank)); const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
const missions = twoSidedMissionsOf(chosenMode, maxMrank); const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' }; if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const filteredMissions = this.#filterMissions
? this.#filterMissions({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
minMrank,
maxMrank,
missions: rawMissions,
})
: rawMissions;
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions); const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({ const coalitions = selectBattleCoalitions({
vehicles: this.#vehicles, vehicles: this.#vehicles,
@@ -151,21 +190,18 @@ export class BattleMatchmaker {
minMrank, minMrank,
maxMrank, maxMrank,
limitPerType: this.#tuning.botPoolLimitPerType, limitPerType: this.#tuning.botPoolLimitPerType,
}, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts); }, declaration.allowBotAircraftLoadouts === false ? undefined : this.#aircraftLoadouts, this.#tankWeights, this.#tankLoadouts);
return { return {
ok: true, ok: true,
launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots), launch: this.#buildLaunchPlan(input, chosenMode, mission, coalitions, playerMrank, minMrank, maxMrank, customBots),
}; };
} }
#pickQueuedMode( #pickQueuedMode(candidates: readonly OfferedGameMode[], input: EnqueueBattleInput): OfferedGameMode | undefined {
candidates: readonly OfferedGameMode[], const pool = candidates.filter((mode) => isModeEligibleForLineup(
slotVehicles: readonly string[], mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
selectedSlotVehicle: string | undefined, ));
): OfferedGameMode | undefined { if (pool.length === 0) return undefined;
const pool = candidates.filter((mode) =>
isModeEligibleForLineup(mode.declaration, slotVehicles, selectedSlotVehicle, this.#vehiclesByName));
if (pool.length === 0) return candidates.find((mode) => mode.declaration.multiSlot !== false);
const classics = pool.filter((mode) => !mode.declaration.tag); const classics = pool.filter((mode) => !mode.declaration.tag);
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag)); const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
if (subModes.length > 0 && classics.length > 0) { if (subModes.length > 0 && classics.length > 0) {
@@ -190,12 +226,14 @@ export class BattleMatchmaker {
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers; const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers)); const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1)); const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
const maxRespawns = modeMaxRespawns(declaration);
const missionLocName = resolveMissionLocName(mission); const missionLocName = resolveMissionLocName(mission);
const environment = declaration.environmentOverride ?? mission.environment; const environment = declaration.environmentOverride ?? mission.environment;
const session = this.#sessions.create({ const session = this.#sessions.create({
userId: input.userId, userId: input.userId,
modeId: declaration.gameModeId, modeId: declaration.gameModeId,
modeName: declaration.name, modeName: declaration.name,
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
economicName: declaration.economicName, economicName: declaration.economicName,
difficulty: declaration.difficulty, difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass, requiredClass: declaration.requiredClass,
@@ -222,9 +260,11 @@ export class BattleMatchmaker {
sessionId: session.sessionId, sessionId: session.sessionId,
modeId: declaration.gameModeId, modeId: declaration.gameModeId,
modeName: declaration.name, modeName: declaration.name,
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
economicName: declaration.economicName, economicName: declaration.economicName,
missionName: mission.name, missionName: mission.name,
mission, mission,
missionRuleKeys: declaration.missionRuleKeys ?? [],
missionFile: mission.path, missionFile: mission.path,
missionType: mission.type ?? 'domination', missionType: mission.type ?? 'domination',
...(mission.level !== undefined ? { level: mission.level } : {}), ...(mission.level !== undefined ? { level: mission.level } : {}),
@@ -242,6 +282,8 @@ export class BattleMatchmaker {
maxMrank, maxMrank,
maxPlayers, maxPlayers,
maxBots, maxBots,
allowSpares: declaration.multiSlot !== false && maxRespawns !== SINGLE_SPAWN && maxRespawns !== UNLIMITED_RESPAWNS,
...(maxRespawns === undefined ? {} : { maxRespawns }),
tankBotRespawns: this.#tuning.tankBotRespawns, tankBotRespawns: this.#tuning.tankBotRespawns,
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns, airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
useTankBots: allowedSet.has('tank'), useTankBots: allowedSet.has('tank'),
@@ -7,8 +7,8 @@
* copied here from the mission file, base values first and then the sub-block for the battle's * copied here from the mission file, base values first and then the sub-block for the battle's
* difficulty. `_gameMode` is left to the client, which takes it from its own native constants. * difficulty. `_gameMode` is left to the client, which takes it from its own native constants.
*/ */
import { emptyBlock, ensureBlock, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk'; import { emptyBlock, ensureBlock, findParam, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts'; import { UNLIMITED_RESPAWNS } from '../game-modes/mode-definition.ts';
import type { ExtraBattleSlot } from './battle-extra-slots.ts'; import type { ExtraBattleSlot } from './battle-extra-slots.ts';
import type { BattleLaunchPlan } from './battle-matchmaker.ts'; import type { BattleLaunchPlan } from './battle-matchmaker.ts';
import type { CustomBotsPool } from './battle-ranks.ts'; import type { CustomBotsPool } from './battle-ranks.ts';
@@ -23,12 +23,13 @@ const RULE_KEYS: readonly string[] = [
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul', 'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec', 'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord', 'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
'allowedKillStreaks',
]; ];
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */ /** Game type switches of a versus battle with tickets, capture zones and session rewards. */
const VERSUS_SWITCHES: readonly string[] = [ 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', 'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
'isLimitedAmmo', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance', 'allowUseArtillerySupport', 'isBotsAllowed', 'autoBalance',
]; ];
/** /**
@@ -39,6 +40,13 @@ const VERSUS_SWITCHES: readonly string[] = [
export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock { export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<Record<string, number>>): BlkBlock {
const settings = emptyBlock(); const settings = emptyBlock();
copyMissionParams(settings, plan); copyMissionParams(settings, plan);
// Enable Ground Arcade air events when the mission allows killstreaks; the LocalMP host preserves
// MissionSettings.useKillStreaks across prepare_local_mission (local_mp_air_events.c).
const allowedKillStreaks = findParam(settings, 'allowedKillStreaks')?.value;
if (plan.modeName === 'tank_event_in_random_battles_arcade'
&& allowedKillStreaks?.type === 'bool' && allowedKillStreaks.value) {
setParam(settings, 'useKillStreaks', flag(true));
}
if (plan.level !== undefined) setParam(settings, 'level', text(plan.level)); if (plan.level !== undefined) setParam(settings, 'level', text(plan.level));
if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment)); if (plan.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather)); if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
@@ -60,13 +68,19 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams)); setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
setParam(settings, 'gt_mp_solo', flag(false)); setParam(settings, 'gt_mp_solo', flag(false));
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true)); for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
setParam(settings, 'allowSpare', flag(!plan.selectedSlot)); // The native in-flight rearm request and its receiver both require unlimited reserve ammunition.
setParam(settings, 'isLimitedAmmo', flag(plan.modeName !== 'air_arcade'));
// MissionSettings defaults isLimitedFuel to false, which disables fuel consumption and HUD timers.
setParam(settings, 'isLimitedFuel', flag(true));
setParam(settings, 'allowSpare', flag(plan.allowSpares));
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
if (plan.selectedSlot) { if (plan.selectedSlot) {
setParam(settings, 'maxRespawns', integer(SINGLE_SPAWN));
setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true)); setParam(settings, 'ctaInstantDecreaseTicketsWhenNoRespawn', flag(true));
// The native mission loader reads the AI limit at the top level, after its bots.blk default.
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
} }
// MissionSettings::load (2.61.0.37 0x126b1f4..0x126b2e6) reads global config/bots.blk defaults
// first, then overrides aircraft and tank AI respawn limits from the mission root, not customBots.
setParam(settings, 'numBotRespawns', integer(plan.airBotRespawns));
setParam(settings, 'numTankBotRespawns', integer(plan.tankBotRespawns));
setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore)); setParam(settings, 'useSpawnScore', flag(plan.useSpawnScore));
setParam(settings, 'useTankBots', flag(plan.useTankBots)); setParam(settings, 'useTankBots', flag(plan.useTankBots));
setParam(settings, 'useShipBots', flag(plan.useShipBots)); setParam(settings, 'useShipBots', flag(plan.useShipBots));
@@ -88,14 +102,15 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
} }
function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void { function copyMissionParams(settings: BlkBlock, plan: BattleLaunchPlan): void {
const wanted = new Set([...LOCALIZATION_KEYS, ...RULE_KEYS]); const ruleKeys = new Set([...RULE_KEYS, ...plan.missionRuleKeys]);
const wanted = new Set([...LOCALIZATION_KEYS, ...ruleKeys]);
const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => { const copy = (params: readonly BlkParam[] | undefined, keys: ReadonlySet<string>): void => {
for (const param of params ?? []) { for (const param of params ?? []) {
if (keys.has(param.name)) setParam(settings, param.name, param.value); if (keys.has(param.name)) setParam(settings, param.name, param.value);
} }
}; };
copy(plan.mission.missionParams, wanted); copy(plan.mission.missionParams, wanted);
copy(plan.mission.difficultyParams[plan.difficulty], new Set(RULE_KEYS)); copy(plan.mission.difficultyParams[plan.difficulty], ruleKeys);
} }
/** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */ /** Fixed spawn costs of extra slots, read back by the spawn score respondents (customSpawnScore). */
@@ -115,6 +130,8 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam))); setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';'))); setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';'))); setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
if (plan.mission.groundMode !== undefined) setParam(bots, 'wtoGroundMode', text(plan.mission.groundMode));
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns)); setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns)); setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns)); setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
@@ -124,6 +141,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts), poolBlock('allowedAircrafts', 'aircraft', plan.customBots.aircrafts),
poolBlock('allowedShips', 'ship', plan.customBots.ships), poolBlock('allowedShips', 'ship', plan.customBots.ships),
); );
addTankAmmoParams(bots, plan.customBots.tanks);
return bots; return bots;
} }
@@ -139,11 +157,26 @@ function poolBlock(name: string, entryName: string, entries: CustomBotsPool['tan
setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset)); setParam(ensureBlock(block, 'preset'), 'name', text(loadout.preset));
for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification)); for (const modification of loadout.modifications) appendParam(block, 'addModification', text(modification));
} }
if (entry.tankLoadout !== undefined) {
for (const modification of entry.tankLoadout.modifications) appendParam(block, 'addModification', text(modification));
}
pool.blocks.push(block); pool.blocks.push(block);
} }
return pool; return pool;
} }
/** Per-tank bot ammo strings (`weapon|mod0:count0|mod1:count1`) read by local_mp_loadout.c. */
function addTankAmmoParams(bots: BlkBlock, entries: CustomBotsPool['tanks']): void {
const seen = new Set<string>();
for (const entry of entries) {
const loadout = entry.tankLoadout;
if (!loadout || loadout.bullets.length === 0 || seen.has(entry.name)) continue;
seen.add(entry.name);
const parts = [loadout.weaponName, ...loadout.bullets.slice(0, 2).map((s) => `${s.modName}:${s.count}`)];
setParam(bots, `wtoAmmo_${entry.name}`, text(parts.join('|')));
}
}
function text(value: string): BlkValue { function text(value: string): BlkValue {
return { type: 'string', value }; return { type: 'string', value };
} }
+52 -6
View File
@@ -10,6 +10,7 @@ import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.t
import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; import type { GameModeDeclaration, ModeDifficulty, UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts';
import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts'; import { vehicleTypeById, vehicleTypeOfClass, type VehicleType } from '../research/vehicle-types.ts';
import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts'; import type { BotAircraftLoadout } from './bot-aircraft-loadouts.ts';
import type { BotTankLoadout } from './bot-tank-loadouts.ts';
const COUNTRY_PREFIX = 'country_'; const COUNTRY_PREFIX = 'country_';
@@ -23,6 +24,7 @@ export interface BotPoolEntry {
readonly country: string; readonly country: string;
readonly weight: number; readonly weight: number;
readonly aircraftLoadout?: BotAircraftLoadout; readonly aircraftLoadout?: BotAircraftLoadout;
readonly tankLoadout?: BotTankLoadout;
} }
export interface CustomBotsPool { export interface CustomBotsPool {
@@ -31,6 +33,16 @@ export interface CustomBotsPool {
readonly ships: readonly BotPoolEntry[]; readonly ships: readonly BotPoolEntry[];
} }
/** Offline tank pool weights by vehicle class (`tuning/ground-ai.jsonc` `lineupWeights`). */
export interface TankLineupWeights {
readonly spaa: number;
readonly lightTank: number;
readonly tankDestroyer: number;
readonly heavyTank: number;
readonly mediumTank: number;
readonly other: number;
}
export interface BotPoolQuery { export interface BotPoolQuery {
readonly difficulty: ModeDifficulty; readonly difficulty: ModeDifficulty;
readonly requiredClass: UnitClass; readonly requiredClass: UnitClass;
@@ -95,26 +107,47 @@ export function lineupMrank(
difficulty: ModeDifficulty, difficulty: ModeDifficulty,
requiredClass: UnitClass, requiredClass: UnitClass,
allowedClasses: readonly UnitClass[], allowedClasses: readonly UnitClass[],
mrankDeltas: ReadonlyMap<string, number>,
): number { ): number {
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => { const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
const vehicle = byName.get(name); const vehicle = byName.get(name);
if (!vehicle) return []; if (!vehicle) return [];
return [{ return [{
unitClass: unitClassOfExpClass(vehicle.unitClass), unitClass: unitClassOfExpClass(vehicle.unitClass),
mrank: vehicleMrank(vehicle, difficulty, requiredClass), mrank: lineupVehicleMrank(vehicle, difficulty, requiredClass, mrankDeltas),
}]; }];
}); });
return maxModeMrank(crafts, requiredClass, allowedClasses); return maxModeMrank(crafts, requiredClass, allowedClasses);
} }
function lineupVehicleMrank(
vehicle: CatalogueVehicle,
difficulty: ModeDifficulty,
requiredClass: UnitClass,
mrankDeltas: ReadonlyMap<string, number>,
): number {
return vehicleMrank(vehicle, difficulty, requiredClass) + (mrankDeltas.get(vehicle.name) ?? 0);
}
/**
* Without `tankWeights` every pool entry keeps the stock weight of 1.
*/
export function selectCustomBots( export function selectCustomBots(
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>, vehicles: readonly CatalogueVehicle[],
query: BotPoolQuery,
aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
tankWeights?: TankLineupWeights,
tankLoadouts?: ReadonlyMap<string, BotTankLoadout>,
): CustomBotsPool { ): CustomBotsPool {
const allowed = new Set(query.allowedClasses); const allowed = new Set(query.allowedClasses);
const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))]; const orderedCountries = [...new Set(query.countries.map((c) => (c.startsWith(COUNTRY_PREFIX) ? c : `${COUNTRY_PREFIX}${c}`)))];
const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : []; const aircrafts = allowed.has('aircraft') ? pickCategoryPool(vehicles, orderedCountries, 'aircraft', query) : [];
const rawTanks = allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query, tankWeights) : [];
return { return {
tanks: allowed.has('tank') ? pickCategoryPool(vehicles, orderedCountries, 'tank', query) : [], tanks: tankLoadouts ? rawTanks.map((entry) => {
const tankLoadout = tankLoadouts.get(entry.name);
return tankLoadout === undefined ? entry : { ...entry, tankLoadout };
}) : rawTanks,
aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => { aircrafts: query.requiredClass === 'aircraft' && aircraftLoadouts ? aircrafts.map((entry) => {
const aircraftLoadout = aircraftLoadouts.get(entry.name); const aircraftLoadout = aircraftLoadouts.get(entry.name);
return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout }; return aircraftLoadout === undefined ? entry : { ...entry, aircraftLoadout };
@@ -128,6 +161,7 @@ function pickCategoryPool(
orderedCountries: readonly string[], orderedCountries: readonly string[],
category: 'tank' | 'aircraft' | 'ship', category: 'tank' | 'aircraft' | 'ship',
query: BotPoolQuery, query: BotPoolQuery,
tankWeights?: TankLineupWeights,
): BotPoolEntry[] { ): BotPoolEntry[] {
const countrySet = new Set(orderedCountries); const countrySet = new Set(orderedCountries);
const eligible = vehicles.filter((vehicle) => const eligible = vehicles.filter((vehicle) =>
@@ -151,13 +185,14 @@ function pickCategoryPool(
return mrank >= query.minMrank && mrank <= query.maxMrank; return mrank >= query.minMrank && mrank <= query.maxMrank;
}); });
const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType); const source = inWindow.length > 0 ? inWindow : sortedByCloseness.slice(0, query.limitPerType);
return roundRobinByCountry(source, orderedCountries, query.limitPerType); return roundRobinByCountry(source, orderedCountries, query.limitPerType, (vehicle) => tankPoolWeight(vehicle, tankWeights));
} }
function roundRobinByCountry( function roundRobinByCountry(
vehicles: readonly CatalogueVehicle[], vehicles: readonly CatalogueVehicle[],
orderedCountries: readonly string[], orderedCountries: readonly string[],
limit: number, limit: number,
weightOf: (vehicle: CatalogueVehicle) => number,
): BotPoolEntry[] { ): BotPoolEntry[] {
const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []])); const buckets = new Map<string, CatalogueVehicle[]>(orderedCountries.map((country) => [country, []]));
for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle); for (const vehicle of vehicles) buckets.get(vehicle.country)?.push(vehicle);
@@ -167,7 +202,7 @@ function roundRobinByCountry(
for (const country of orderedCountries) { for (const country of orderedCountries) {
const vehicle = buckets.get(country)?.[index]; const vehicle = buckets.get(country)?.[index];
if (!vehicle) continue; if (!vehicle) continue;
out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: 1 }); out.push({ name: vehicle.name, country: stripCountryPrefix(country), weight: weightOf(vehicle) });
added = true; added = true;
if (out.length >= limit) break; if (out.length >= limit) break;
} }
@@ -176,6 +211,16 @@ function roundRobinByCountry(
return out; return out;
} }
function tankPoolWeight(vehicle: CatalogueVehicle, weights: TankLineupWeights | undefined): number {
if (weights === undefined) return 1;
if (vehicle.unitClass === 'exp_SPAA') return weights.spaa;
if (vehicle.isLightTank) return weights.lightTank;
if (vehicle.unitClass === 'exp_tank_destroyer') return weights.tankDestroyer;
if (vehicle.unitClass === 'exp_heavy_tank') return weights.heavyTank;
if (vehicle.unitClass === 'exp_tank') return weights.mediumTank;
return weights.other;
}
function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined { function unitClassOfVehicleType(type: VehicleType | undefined): UnitClass | undefined {
if (type === 'Tank') return 'tank'; if (type === 'Tank') return 'tank';
if (type === 'Aircraft') return 'aircraft'; if (type === 'Aircraft') return 'aircraft';
@@ -203,6 +248,7 @@ export function isModeEligibleForLineup(
slotVehicles: readonly string[], slotVehicles: readonly string[],
selectedSlotVehicle: string | undefined, selectedSlotVehicle: string | undefined,
byName: ReadonlyMap<string, CatalogueVehicle>, byName: ReadonlyMap<string, CatalogueVehicle>,
mrankDeltas: ReadonlyMap<string, number>,
): boolean { ): boolean {
if (!declaration.tag && declaration.multiSlot !== false) return true; if (!declaration.tag && declaration.multiSlot !== false) return true;
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName); const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
@@ -211,7 +257,7 @@ export function isModeEligibleForLineup(
const matchingCount = active.filter((name) => { const matchingCount = active.filter((name) => {
const vehicle = byName.get(name); const vehicle = byName.get(name);
if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false; if (!vehicle || unitClassOfExpClass(vehicle.unitClass) !== declaration.requiredClass) return false;
return vehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass) >= minMrank; return lineupVehicleMrank(vehicle, declaration.difficulty, declaration.requiredClass, mrankDeltas) >= minMrank;
}).length; }).length;
return matchingCount >= minCrafts; return matchingCount >= minCrafts;
} }
+9 -12
View File
@@ -17,10 +17,11 @@
* the final scoreboard * the final scoreboard
* strikes{ s{ time:r } ... } explosions of the local player's * strikes{ s{ time:r } ... } explosions of the local player's
* nuclear bombs (native local_mp_nuke.c) * nuclear bombs (native local_mp_nuke.c)
* spares{ <unit>:i ... } backup vehicles used * spares{ spawn{ slot:i unit:t backup:t } ... } confirmed backup spawns
*/ */
import { findBlock, type BlkBlock } from '@wto/blk'; import { findBlock, type BlkBlock } from '@wto/blk';
import type { CombatEventFact } from './battle-economy.ts'; import type { CombatEventFact } from './battle-economy.ts';
import type { BackupSpawn } from './battle-spares.ts';
export type BattleOutcomeKind = 'win' | 'lose' | 'running'; export type BattleOutcomeKind = 'win' | 'lose' | 'running';
@@ -83,7 +84,7 @@ export interface BattleReport {
readonly players: readonly ScoreboardPlayer[]; readonly players: readonly ScoreboardPlayer[];
/** Mission times at which the local player's nuclear bombs exploded. */ /** Mission times at which the local player's nuclear bombs exploded. */
readonly nuclearStrikes: readonly number[]; readonly nuclearStrikes: readonly number[];
readonly usedSpares: Readonly<Record<string, number>>; readonly spareSpawns: readonly BackupSpawn[];
} }
/** Undefined when the report is malformed; lives and events that make no sense are dropped. */ /** Undefined when the report is malformed; lives and events that make no sense are dropped. */
@@ -139,19 +140,15 @@ export function parseBattleReport(payload: BlkBlock): BattleReport | undefined {
...Object.fromEntries(SCOREBOARD_FIELDS.map((field) => [field, Math.max(0, intOf(block, field))])) as Record<(typeof SCOREBOARD_FIELDS)[number], number>, ...Object.fromEntries(SCOREBOARD_FIELDS.map((field) => [field, Math.max(0, intOf(block, field))])) as Record<(typeof SCOREBOARD_FIELDS)[number], number>,
})), })),
nuclearStrikes: (findBlock(payload, 'strikes')?.blocks ?? []).map((block) => realOf(block, 'time')).sort((a, b) => a - b), nuclearStrikes: (findBlock(payload, 'strikes')?.blocks ?? []).map((block) => realOf(block, 'time')).sort((a, b) => a - b),
usedSpares: parseSpareMap(findBlock(payload, 'spares')), spareSpawns: (findBlock(payload, 'spares')?.blocks ?? []).flatMap((block): BackupSpawn[] => {
const slot = intOf(block, 'slot', -1);
const unit = strOf(block, 'unit');
const backup = strOf(block, 'backup');
return slot >= 0 && unit && backup ? [{ slot, unit, backup }] : [];
}),
}; };
} }
function parseSpareMap(sparesBlk: BlkBlock | undefined): Record<string, number> {
const out: Record<string, number> = {};
for (const param of sparesBlk?.params ?? []) {
const count = param.value.type === 'int' ? param.value.value : 0;
if (param.name && count > 0) out[param.name] = count;
}
return out;
}
function strOf(block: BlkBlock, name: string): string | undefined { function strOf(block: BlkBlock, name: string): string | undefined {
const value = block.params.find((p) => p.name === name)?.value; const value = block.params.find((p) => p.name === name)?.value;
return value?.type === 'string' && value.value !== '' ? value.value : undefined; return value?.type === 'string' && value.value !== '' ? value.value : undefined;
+9 -1
View File
@@ -9,7 +9,8 @@
* container.aircraftsRepaired{ aname<i>:t cost<i>:i } and container.wpExpensesCompensation:i * container.aircraftsRepaired{ aname<i>:t cost<i>:i } and container.wpExpensesCompensation:i
* (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation"). * (userlogviewdata.nut "damaged vehicles", "automatic repair", "expenses compensation").
*/ */
import { emptyBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; import { emptyBlock, findBlock, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { intField, int64Field } from '../profile/blk-fields.ts';
import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts'; import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts'; import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import type { DebriefingRow } from './battle-economy.ts'; import type { DebriefingRow } from './battle-economy.ts';
@@ -18,6 +19,11 @@ import type { ResearchPointsUnit } from './battle-rp-investment.ts';
import type { AutoRepair, VehicleDamage } from './battle-repair.ts'; import type { AutoRepair, VehicleDamage } from './battle-repair.ts';
import type { BattleSession } from './battle-session-store.ts'; import type { BattleSession } from './battle-session-store.ts';
export function hasBattleResultLog(profile: BlkBlock, roomId: bigint): boolean {
return findBlock(profile, 'userlogs')?.blocks.some((log) =>
intField(log, 'type') === EULT_SESSION_RESULT && int64Field(log, 'roomId') === roomId) ?? false;
}
export interface EarnedRpItem { export interface EarnedRpItem {
readonly unit: string; readonly unit: string;
readonly modification?: string; readonly modification?: string;
@@ -58,6 +64,8 @@ const CONTAINER_OF_ROW: Readonly<Record<DebriefingRow, string | undefined>> = {
Critical: 'eventCriticalHit', Critical: 'eventCriticalHit',
Hit: 'eventHit', Hit: 'eventHit',
Captures: 'eventCaptureZone', Captures: 'eventCaptureZone',
Damage: 'eventDamageZone',
Destruction: 'eventDestroyZone',
// No user log list carries naval damage awards; they show in the debriefing table only. // No user log list carries naval damage awards; they show in the debriefing table only.
AwardDamage: undefined, AwardDamage: undefined,
}; };
+2 -1
View File
@@ -84,6 +84,7 @@ export interface BattleRewards {
export interface RewardContext { export interface RewardContext {
readonly difficulty: EconomyDifficulty; readonly difficulty: EconomyDifficulty;
readonly modeName: string;
/** The mode's economic name, which selects rank.blk ExpSkillBonus. */ /** The mode's economic name, which selects rank.blk ExpSkillBonus. */
readonly economicName: string; readonly economicName: string;
readonly premiumAccount: boolean; readonly premiumAccount: boolean;
@@ -133,7 +134,7 @@ export function computeBattleRewards(report: BattleReport, economy: BattleEconom
const events: SettledEvent[] = []; const events: SettledEvent[] = [];
for (const event of report.events) { for (const event of report.events) {
const priced = economy.price(event.unit, ctx.difficulty, event); const priced = economy.price(event.unit, ctx.difficulty, ctx.modeName, event);
if (!priced) continue; if (!priced) continue;
events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp, ctx.boosters.forEvent(event)) }); events.push({ event, priced, bonuses: add(event.unit, priced.row, priced.count, priced.wp, priced.exp, ctx.boosters.forEvent(event)) });
} }
@@ -24,6 +24,8 @@ export interface BattleSession {
readonly missionLocName?: string; readonly missionLocName?: string;
readonly country: string; readonly country: string;
readonly startedAtSec: number; readonly startedAtSec: number;
/** Owned lineup slots that may use a backup in this session. Filled when launch is sent. */
spareSlots?: ReadonlyMap<number, string>;
settled: boolean; settled: boolean;
} }
+10 -2
View File
@@ -35,6 +35,7 @@ import { autoRepairVehicles, damageBattleVehicles, expensesCompensation } from '
import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts'; import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts';
import { computeBattleRewards, type VehicleRewards } from './battle-rewards.ts'; import { computeBattleRewards, type VehicleRewards } from './battle-rewards.ts';
import { investBattleRp, type VehicleRp } from './battle-rp-investment.ts'; import { investBattleRp, type VehicleRp } from './battle-rp-investment.ts';
import { consumeBattleSpares } from './battle-spares.ts';
import { appendStreakLogs } from './battle-streak-log.ts'; import { appendStreakLogs } from './battle-streak-log.ts';
import type { BattleStreaks } from './battle-streaks.ts'; import type { BattleStreaks } from './battle-streaks.ts';
import type { BattleSession } from './battle-session-store.ts'; import type { BattleSession } from './battle-session-store.ts';
@@ -52,6 +53,8 @@ export interface BattleSettlementDeps {
readonly streaks: BattleStreaks; readonly streaks: BattleStreaks;
readonly items: ItemCatalogue; readonly items: ItemCatalogue;
readonly repair: RepairRules; readonly repair: RepairRules;
/** Optional hook receiving total base (unboosted) vehicle RP earned in the battle. */
readonly onBattleRpEarned?: ((baseVehicleRp: number, nowSec: number) => void) | undefined;
} }
const REPAIR_MODE: Readonly<Record<ModeDifficulty, RepairMode>> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' }; const REPAIR_MODE: Readonly<Record<ModeDifficulty, RepairMode>> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' };
@@ -64,6 +67,7 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
const premiumAccount = remainingPremiumDays(profile, now) > 0; const premiumAccount = remainingPremiumDays(profile, now) > 0;
const rewards = computeBattleRewards(report, deps.economy, { const rewards = computeBattleRewards(report, deps.economy, {
difficulty, difficulty,
modeName: session.modeName,
economicName: session.economicName, economicName: session.economicName,
premiumAccount, premiumAccount,
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN), hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
@@ -85,12 +89,15 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul); if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul);
} }
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment); const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), { const vehicleRps = rewards.vehicles.map(vehicleRpOf);
const research = investBattleRp(profile, vehicleRps, {
country: session.country, country: session.country,
requiredClass: session.requiredClass, requiredClass: session.requiredClass,
difficulty, difficulty,
nowUnixSec: log.timeSec, nowUnixSec: log.timeSec,
}, deps); }, deps);
const baseVehicleRp = vehicleRps.reduce((sum, vehicle) => sum + Math.max(0, vehicle.noBonusExp), 0);
if (baseVehicleRp > 0) deps.onBattleRpEarned?.(baseVehicleRp, log.timeSec);
recordBoosterUses(profile, boosters.uses, log); recordBoosterUses(profile, boosters.uses, log);
const wager = activeWager(profile, deps.items); const wager = activeWager(profile, deps.items);
const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, { const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, {
@@ -120,13 +127,14 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B
if (compensation > 0) addSilverLions(profile, compensation); if (compensation > 0) addSilverLions(profile, compensation);
const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation); const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation);
const usedSpares = consumeBattleSpares(profile, session, report.spareSpawns, deps.items, deps.research.techTree);
appendStreakLogs(profile, session, streaks); appendStreakLogs(profile, session, streaks);
appendBattleResultLog(profile, session, { appendBattleResultLog(profile, session, {
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`, country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
rewards, rewards,
unlocksWp: unlocks.wp, unlocksWp: unlocks.wp,
weaponRefillSl, weaponRefillSl,
usedSpares: report.usedSpares, usedSpares,
rpItems: mergeEarnedRpItems(research.rpItems), rpItems: mergeEarnedRpItems(research.rpItems),
researchUnits: research.units, researchUnits: research.units,
affectedBoosters: boosters.applied.map((booster) => booster.id), affectedBoosters: boosters.applied.map((booster) => booster.id),
+59
View File
@@ -0,0 +1,59 @@
import type { BlkBlock } from '@wto/blk';
import type { ItemCatalogue } from '../items/item-catalogue.ts';
import { applyUniversalSpares } from '../items/universal-spares.ts';
import { dailySparesLeft, recordDailySpare, usedDailySpare } from '../profile/profile-daily-spares.ts';
import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts';
import type { TechTree } from '../research/tech-tree.ts';
import type { BattleSession } from './battle-session-store.ts';
/** LocalMP uses a source token for an attached backup and the stock UID for an inventory item. */
const VEHICLE_BACKUP = 'vehicle';
export const DAILY_BACKUP = 'daily_free_spare';
export interface BackupSpawn {
readonly slot: number;
readonly unit: string;
readonly backup: string;
}
/** Strip native model folder prefixes (e.g. "tankModels/cn_type_59" -> "cn_type_59"). */
export function normalizeBackupUnitName(unit: string): string {
const slash = unit.lastIndexOf('/');
return slash >= 0 ? unit.slice(slash + 1) : unit;
}
function receiptKey(session: BattleSession, slot: number): string {
return `${session.sessionId}_${slot}`;
}
export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean {
const unit = normalizeBackupUnitName(spawn.unit);
return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === unit
&& recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot));
}
/** Debit confirmed backup spawns from the lineup that the server sent at launch. */
export function consumeBattleSpares(
profile: BlkBlock, session: BattleSession, spawns: readonly BackupSpawn[], items: ItemCatalogue, techTree: TechTree,
): Readonly<Record<string, number>> {
const seenSlots = new Set<number>();
const consumed = new Map<string, number>();
for (const spawn of spawns) {
const { slot, backup } = spawn;
const unit = normalizeBackupUnitName(spawn.unit);
if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue;
seenSlots.add(slot);
if (backup === DAILY_BACKUP) {
recordDailyBackupSpawn(profile, session, { slot, unit, backup });
continue;
}
if (dailySparesLeft(profile, session.startedAtSec) > 0
|| usedDailySpare(profile, session.startedAtSec, receiptKey(session, slot))) continue;
if (backup !== VEHICLE_BACKUP && !applyUniversalSpares(profile, items, techTree, backup, unit, 1).ok) continue;
const owned = spareCount(profile, unit);
if (owned < 1) continue;
setSpareCount(profile, unit, owned - 1);
consumed.set(unit, (consumed.get(unit) ?? 0) + 1);
}
return Object.fromEntries(consumed);
}
+2 -1
View File
@@ -175,7 +175,8 @@ export function evaluateStreaks(definitions: readonly StreakDefinition[], facts:
for (const time of facts.nuclearStrikes) award(def, time, 1); for (const time of facts.nuclearStrikes) award(def, time, 1);
break; break;
case 'firstKill': { case 'firstKill': {
const first = facts.feed.find((k) => k.killerTeam !== k.victimTeam); // Ignore non-player mission units (air defense SAM/AAA, NPCs) whose HUD feed killer id is -1.
const first = facts.feed.find((k) => k.killer >= 0 && k.killerTeam !== k.victimTeam);
if (first && first.killer === facts.localPlayerId) award(def, first.time, 1); if (first && first.killer === facts.localPlayerId) award(def, first.time, 1);
break; break;
} }
+2
View File
@@ -26,6 +26,7 @@ export interface BattleTuning {
readonly strikeUcavSpawnScore: number; readonly strikeUcavSpawnScore: number;
readonly tankBotRespawns: number; readonly tankBotRespawns: number;
readonly airBotRespawns: number; readonly airBotRespawns: number;
readonly nuclearEscalationStrategicBombers: boolean;
} }
export function readBattleTuning(reader: TuningReader): BattleTuning { export function readBattleTuning(reader: TuningReader): BattleTuning {
@@ -66,5 +67,6 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }), strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }), tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }), airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
nuclearEscalationStrategicBombers: reader.bool('nuclearEscalationStrategicBombers'),
}; };
} }
+135
View File
@@ -0,0 +1,135 @@
/**
* Offline AI tank spawn ammunition selector:
* - Total carried rounds follow the vehicle's first-stage / autoloader ready rack, topped up
* when below the configured threshold (clamped to main gun capacity).
* - Primary shell prefers legal APFSDS, otherwise ranks anti-armor shells by 500 m penetration.
* - Secondary shell carries a small share of HE / HEAT / HESH when available for soft targets.
*/
import type { GroundAiLoadoutConfig } from '@wto/patcher';
import type { TankAmmoProfile, TankBotAmmoData, TankShellChoice } from '../game-data/datasets/tank-bot-ammo.ts';
import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts';
import { vehicleTypeOfClass } from '../research/vehicle-types.ts';
export interface BotTankBulletSlot {
readonly modName: string;
readonly count: number;
}
export interface BotTankLoadout {
readonly weaponName: string;
readonly bullets: readonly BotTankBulletSlot[];
readonly modifications: readonly string[];
}
export function selectBotTankLoadouts(
vehicles: readonly CatalogueVehicle[],
ammoData: TankBotAmmoData,
config: GroundAiLoadoutConfig,
): ReadonlyMap<string, BotTankLoadout> {
const result = new Map<string, BotTankLoadout>();
for (const vehicle of vehicles) {
if (vehicleTypeOfClass(vehicle.unitClass) !== 'Tank' || vehicle.unitClass === 'exp_SPAA') continue;
const profile = ammoData[vehicle.name];
if (!profile || profile.isBelt || profile.maxBullets <= 0) continue;
const loadout = chooseTankLoadout(profile, config);
if (loadout !== undefined) result.set(vehicle.name, loadout);
}
return result;
}
function chooseTankLoadout(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): BotTankLoadout | undefined {
const combatShells = profile.shells.filter((shell) => !isNonCombatShell(shell.bulletType));
if (combatShells.length === 0) return undefined;
const primary = pickPrimaryShell(combatShells);
if (!primary) return undefined;
const totalRounds = computeCarriedRounds(profile, config);
if (totalRounds <= 0) return undefined;
const secondary = pickSecondaryShell(combatShells, primary);
const bullets = splitRounds(primary, secondary, totalRounds, config);
const modSet = new Set<string>();
for (const chosen of [primary, ...(bullets.length > 1 && secondary ? [secondary] : [])]) {
if (chosen.modName) modSet.add(chosen.modName);
for (const req of chosen.requires) modSet.add(req);
}
return {
weaponName: profile.weaponName,
bullets,
modifications: [...modSet].sort(),
};
}
function computeCarriedRounds(profile: TankAmmoProfile, config: GroundAiLoadoutConfig): number {
const want = profile.readyRack >= config.lowReadyRackThreshold
? profile.readyRack
: config.topUpAmmoCount;
return Math.max(1, Math.min(want, profile.maxBullets));
}
function pickPrimaryShell(shells: readonly TankShellChoice[]): TankShellChoice | undefined {
const ranked = [...shells].sort((a, b) => compareAntiArmor(a, b));
return ranked[0];
}
function compareAntiArmor(a: TankShellChoice, b: TankShellChoice): number {
const tierA = antiArmorTier(a.bulletType);
const tierB = antiArmorTier(b.bulletType);
if (tierA !== tierB) return tierB - tierA;
const scoreA = a.pen500Mm + (isApheFamily(a.bulletType) ? 12 : 0);
const scoreB = b.pen500Mm + (isApheFamily(b.bulletType) ? 12 : 0);
if (scoreA !== scoreB) return scoreB - scoreA;
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
return a.modName.localeCompare(b.modName);
}
function antiArmorTier(bulletType: string): number {
if (bulletType.includes('apds_fs')) return 5;
if (bulletType.includes('atgm')) return 4;
if (bulletType.includes('apds')) return 3;
if (bulletType.includes('heat') || isApheFamily(bulletType) || bulletType.startsWith('ap')) return 2;
if (bulletType.includes('hesh')) return 1;
return 0;
}
function pickSecondaryShell(shells: readonly TankShellChoice[], primary: TankShellChoice): TankShellChoice | undefined {
const candidates = shells.filter((shell) => shell.modName !== primary.modName && isSoftTargetShell(shell.bulletType));
if (candidates.length === 0) return undefined;
return [...candidates].sort((a, b) => {
const heA = a.bulletType.includes('he_frag') ? 2 : (a.bulletType.includes('hesh') ? 1 : 0);
const heB = b.bulletType.includes('he_frag') ? 2 : (b.bulletType.includes('hesh') ? 1 : 0);
if (heA !== heB) return heB - heA;
if (a.speedMps !== b.speedMps) return b.speedMps - a.speedMps;
return a.modName.localeCompare(b.modName);
})[0];
}
function splitRounds(
primary: TankShellChoice,
secondary: TankShellChoice | undefined,
totalRounds: number,
config: GroundAiLoadoutConfig,
): BotTankBulletSlot[] {
if (!secondary || config.primaryAmmoPct >= 100 || config.secondaryMinRounds <= 0 || totalRounds < config.secondaryMinRounds * 2 + 2) {
return [{ modName: primary.modName, count: totalRounds }];
}
const wantSec = Math.round((totalRounds * (100 - config.primaryAmmoPct)) / 100);
const secCount = Math.min(totalRounds - 1, Math.max(config.secondaryMinRounds, wantSec));
const priCount = totalRounds - secCount;
return [
{ modName: primary.modName, count: priCount },
{ modName: secondary.modName, count: secCount },
];
}
function isNonCombatShell(bulletType: string): boolean {
return bulletType.includes('smoke') || bulletType.includes('practice') || bulletType.includes('shrapnel');
}
function isSoftTargetShell(bulletType: string): boolean {
return bulletType.includes('he_frag') || bulletType.includes('hesh') || bulletType.includes('heat');
}
function isApheFamily(bulletType: string): boolean {
return bulletType.includes('aphe') || bulletType.includes('apcbc') || bulletType.includes('apbc');
}
+5 -1
View File
@@ -12,6 +12,7 @@ import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue
import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { ResearchRules } from '../../research/research-rules.ts'; import type { ResearchRules } from '../../research/research-rules.ts';
import type { StoreCatalogue } from '../../store/store-catalogue.ts'; import type { StoreCatalogue } from '../../store/store-catalogue.ts';
import type { TrainingCatalogue } from '../../training/training-completion.ts';
import type { UnlockShop } from '../../unlocks/unlock-purchase.ts'; import type { UnlockShop } from '../../unlocks/unlock-purchase.ts';
import type { CharActionHandler } from '../char-action.ts'; import type { CharActionHandler } from '../char-action.ts';
import { acceptEula } from './agreement-actions.ts'; import { acceptEula } from './agreement-actions.ts';
@@ -61,6 +62,7 @@ import {
buyWeaponsAction, buyWeaponsAction,
enableModificationsAction, enableModificationsAction,
saveWeaponPresetsAction, saveWeaponPresetsAction,
setUnitSelectedMrankAction,
} from './modification-actions.ts'; } from './modification-actions.ts';
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts'; import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
@@ -93,6 +95,7 @@ export interface ActionDependencies {
readonly store: StoreCatalogue; readonly store: StoreCatalogue;
readonly inventory: InventoryCatalogue; readonly inventory: InventoryCatalogue;
readonly trophies: TrophyCatalogue; readonly trophies: TrophyCatalogue;
readonly training?: TrainingCatalogue;
readonly clans?: ClanActionDependencies; readonly clans?: ClanActionDependencies;
readonly cloudSettings?: CloudSettingsStore; readonly cloudSettings?: CloudSettingsStore;
readonly battle?: BattleActionDependencies; readonly battle?: BattleActionDependencies;
@@ -117,7 +120,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)], ['cln_get_initial_meta', initialMeta(deps.accounts, deps.cloudSettings)],
['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)], ['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)],
['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)], ['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)],
['cln_update', clientUpdateAction(deps.profiles, deps.accounts)], ['cln_update', clientUpdateAction(deps.profiles, deps.accounts, deps.training)],
['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)], ['cln_accept_eula', acceptEula(deps.profiles, deps.accounts)],
['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)], ['cln_set_starting_info', setStartingInfo(deps.profiles, deps.accounts)],
['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)], ['cln_bulk_train_aircraft', bulkTrainCrews(deps.profiles, deps.accounts, deps.crew)],
@@ -137,6 +140,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_buy_weapon', buyWeaponsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_save_weapon_presets', saveWeaponPresetsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)], ['cln_enable_modifications', enableModificationsAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_set_unit_selected_mrank', setUnitSelectedMrankAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)], ['cln_upgrade_crew', upgradeCrewAction(deps.profiles, deps.accounts, deps.crew)],
['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)], ['cln_purchase_skill_points', purchaseSkillPointsAction(deps.profiles, deps.accounts, deps.crew)],
['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)], ['cln_specialize_crew', specializeCrewAction(deps.profiles, deps.accounts, deps.crew)],
+25 -3
View File
@@ -3,14 +3,17 @@
* settles them into the player's save (battle-settlement.ts) and answers the updated profile, * settles them into the player's save (battle-settlement.ts) and answers the updated profile,
* whose new `EULT_SESSION_RESULT` log carries the debriefing table. * whose new `EULT_SESSION_RESULT` log carries the debriefing table.
*/ */
import type { BattleSettlementContext } from '@wto/mods';
import type { AccountStore } from '../../accounts/account-store.ts'; import type { AccountStore } from '../../accounts/account-store.ts';
import { parseBattleReport } from '../../battle/battle-report.ts'; import { parseBattleReport } from '../../battle/battle-report.ts';
import { hasBattleResultLog } from '../../battle/battle-result-log.ts';
import type { BattleSessionStore } from '../../battle/battle-session-store.ts'; import type { BattleSessionStore } from '../../battle/battle-session-store.ts';
import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts'; import { settleBattle, type BattleSettlementDeps } from '../../battle/battle-settlement.ts';
import type { BattleEconomy } from '../../battle/battle-economy.ts'; import type { BattleEconomy } from '../../battle/battle-economy.ts';
import type { BattleStreaks } from '../../battle/battle-streaks.ts'; import type { BattleStreaks } from '../../battle/battle-streaks.ts';
import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts'; import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts';
import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts'; import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts';
import type { ClanStore } from '../../clans/clan-store.ts';
import type { ItemCatalogue } from '../../items/item-catalogue.ts'; import type { ItemCatalogue } from '../../items/item-catalogue.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { clientProfile } from '../../profile/client-profile.ts'; import { clientProfile } from '../../profile/client-profile.ts';
@@ -28,6 +31,7 @@ export interface BattleActionDependencies {
readonly streaks: BattleStreaks; readonly streaks: BattleStreaks;
/** Units whose lives and events are not settled (battle-support-planes.ts). */ /** Units whose lives and events are not settled (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>; readonly supportPlanes: ReadonlySet<string>;
readonly onAfterSettle?: (ctx: BattleSettlementContext) => void;
} }
export interface FinishBattleContext { export interface FinishBattleContext {
@@ -38,6 +42,7 @@ export interface FinishBattleContext {
readonly crew: CrewSkillCatalogue; readonly crew: CrewSkillCatalogue;
readonly items: ItemCatalogue; readonly items: ItemCatalogue;
readonly repair: RepairRules; readonly repair: RepairRules;
readonly clans?: { readonly store: ClanStore } | undefined;
} }
export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler { export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler {
@@ -60,10 +65,27 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio
if (session.settled) { if (session.settled) {
return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) }; return { kind: 'data', blk: clientProfile(ctx.profiles.profileOf(account.userId), account) };
} }
const updated = ctx.profiles.update(account.userId, (profile) => { const updated = ctx.profiles.updateWhen(account.userId, (profile) => {
settleBattle(profile, report, session, settlementDeps); // The result log and expenses are written together. A retry can arrive after the profile
// was saved but before the session was marked settled.
if (hasBattleResultLog(profile, session.roomId)) return false;
settleBattle(profile, report, session, {
...settlementDeps,
onBattleRpEarned: ctx.clans
? (baseVehicleRp, nowSec) => {
ctx.clans!.store.recordBattleActivity(account.userId, baseVehicleRp, nowSec);
ctx.clans!.store.syncProfile(profile, account, nowSec);
}
: undefined,
});
battle.onAfterSettle?.({
userId: account.userId,
roomId: session.sessionId,
summary: { profile, report, session },
});
return true;
}); });
battle.sessions.markSettled(session.sessionId); battle.sessions.markSettled(session.sessionId);
return { kind: 'data', blk: clientProfile(updated, account) }; return { kind: 'data', blk: clientProfile(updated ?? ctx.profiles.profileOf(account.userId), account) };
}); });
} }
@@ -2,19 +2,50 @@
* `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`): * `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`):
* triggered by `save_online_single_job` when the client marks seen user logs as disabled * triggered by `save_online_single_job` when the client marks seen user logs as disabled
* (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar * (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar
* auto-repair / auto-refill / auto-buy-modifications and map preferences. Answers the whole * auto-repair / auto-refill / auto-buy-modifications, map preferences, and per-vehicle
* updated profile. * preferences (`hangar/<vehicle>` `lastSkin`, `lastWeapon`, `lastBullets0..5`, and flight
* trims `aileronTrim`/`elevatorTrim`/`rudderTrim`). On returning from
* a stock training mission, the client also reports completion in `missionAwards` while
* `pveProgress` is empty. Answers the whole updated profile.
*/ */
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts'; import type { AccountStore } from '../../accounts/account-store.ts';
import { boolField, stringField } from '../../game-data/datasets/blk-fields.ts';
import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts'; import { applyClientProfileUpdate } from '../../profile/profile-client-settings.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { ACCEPTED } from '../../research/rule-outcome.ts'; import { ACCEPTED } from '../../research/rule-outcome.ts';
import type { TrainingCatalogue, TrainingCompletionReport } from '../../training/training-completion.ts';
import type { CharActionHandler } from '../char-action.ts'; import type { CharActionHandler } from '../char-action.ts';
import { ruleAction } from './rule-answer.ts'; import { ruleAction } from './rule-answer.ts';
export function clientUpdateAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { export function clientUpdateAction(
return ruleAction(profiles, accounts, (payload) => (profile) => { profiles: PlayerProfiles,
accounts: AccountStore,
training?: TrainingCatalogue,
): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const completion = training ? readTrainingCompletion(payload) : undefined;
return (profile) => {
applyClientProfileUpdate(profile, payload); applyClientProfileUpdate(profile, payload);
if (completion && training) training.applyCompletion(profile, completion);
return ACCEPTED; return ACCEPTED;
};
}); });
} }
function readTrainingCompletion(request: BlkBlock): TrainingCompletionReport | undefined {
const awards = findBlock(request, 'missionAwards');
if (!awards
|| stringField(awards, 'gameModeName') !== 'training'
|| boolField(awards, 'success') !== true
|| boolField(awards, 'early') !== false
|| boolField(awards, 'onlineGame') !== false) return undefined;
const chapter = stringField(awards, 'chapterName');
const mission = stringField(awards, 'missionName');
const difficulty = findParam(awards, 'difficulty')?.value;
if (!chapter || !mission || difficulty?.type !== 'int'
|| (difficulty.value !== 0 && difficulty.value !== 1 && difficulty.value !== 2)) return undefined;
return { chapter, mission, difficulty: difficulty.value };
}
@@ -8,6 +8,7 @@
* cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i * cln_buy_all_modification: unit:t forceOpen:b cost:i costGold:i
* cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i * cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i
* cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i * cln_buy_weapon: aircraft:t weapon:t count:i cost:i costGold:i
* cln_set_unit_selected_mrank (scripts/unit/unitmrankselectionstate.nut): unit:t addMrank:i
* cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18): * cln_enable_modifications (shop_enable_modifications, 0x17a5020 -> 0x29a890; lab round 18):
* <vehicle>{ <modification>:b=yes ... } ... * <vehicle>{ <modification>:b=yes ... } ...
*/ */
@@ -16,6 +17,7 @@ import type { AccountStore } from '../../accounts/account-store.ts';
import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts';
import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts'; import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts';
import { buySpares } from '../../modifications/spare-purchase.ts'; import { buySpares } from '../../modifications/spare-purchase.ts';
import { selectVehicleMrankDelta } from '../../modifications/vehicle-mrank-selection.ts';
import { saveWeaponPresets } from '../../modifications/weapon-presets.ts'; import { saveWeaponPresets } from '../../modifications/weapon-presets.ts';
import { buyWeapons } from '../../modifications/weapon-purchase.ts'; import { buyWeapons } from '../../modifications/weapon-purchase.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts';
@@ -81,6 +83,15 @@ export function saveWeaponPresetsAction(profiles: PlayerProfiles, accounts: Acco
return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload)); return ruleAction(profiles, accounts, (payload) => (profile) => saveWeaponPresets(profile, equipment, payload));
} }
export function setUnitSelectedMrankAction(profiles: PlayerProfiles, accounts: AccountStore, equipment: EquipmentCatalogue): CharActionHandler {
return ruleAction(profiles, accounts, (payload) => {
const vehicle = stringParam(payload, 'unit');
const delta = intParam(payload, 'addMrank');
if (!vehicle || delta === undefined) return undefined;
return (profile) => selectVehicleMrankDelta(profile, equipment, vehicle, delta);
});
}
function offeredPrice(payload: BlkBlock) { function offeredPrice(payload: BlkBlock) {
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 }; return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
} }
+16 -3
View File
@@ -8,18 +8,24 @@
*/ */
import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk'; import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk';
import type { AccountStore } from '../../accounts/account-store.ts'; import type { AccountStore } from '../../accounts/account-store.ts';
import type { LocalizedText } from '../../game-data/datasets/unit-names.ts';
import { clientProfile } from '../../profile/client-profile.ts'; import { clientProfile } from '../../profile/client-profile.ts';
import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import { serverTimeNow } from '../../profile/server-time.ts'; import { serverTimeNow } from '../../profile/server-time.ts';
import type { RuleOutcome } from '../../research/rule-outcome.ts'; import type { RuleOutcome } from '../../research/rule-outcome.ts';
import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts'; import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts';
import { buyGoldEntitlement } from '../../store/store-purchase.ts'; import { buyGoldEntitlement } from '../../store/store-purchase.ts';
import { freePaymentLabelForStore } from '../../store/store-tuning.ts';
import type { CharActionHandler } from '../char-action.ts'; import type { CharActionHandler } from '../char-action.ts';
import { withAccount } from './account-context.ts'; import { withAccount } from './account-context.ts';
import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts'; import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts';
export function entitlementsPriceEx(store: StoreCatalogue): CharActionHandler { export function entitlementsPriceEx(
const table = buildEntitlementsPriceBlk(store.allProducts()); store: StoreCatalogue,
freePaymentLabel?: LocalizedText,
): CharActionHandler {
const label = freePaymentLabel ?? freePaymentLabelForStore(store);
const table = buildEntitlementsPriceBlk(store.allProducts(), label);
return () => ({ kind: 'data', blk: table }); return () => ({ kind: 'data', blk: table });
} }
@@ -42,8 +48,15 @@ export function buyEntitlementAction(profiles: PlayerProfiles, accounts: Account
}); });
} }
function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock { function buildEntitlementsPriceBlk(
products: readonly StoreProduct[],
freePaymentLabel: LocalizedText,
): BlkBlock {
const root = emptyBlock(); const root = emptyBlock();
// Top-level string params are ignored by stock blockCount() enumeration and read by the
// free-offline-payment-method GUI patch to localize the no-GJN payment option.
setParam(root, 'wtoFreePaymentLabelZh', { type: 'string', value: freePaymentLabel.zh });
setParam(root, 'wtoFreePaymentLabelEn', { type: 'string', value: freePaymentLabel.en });
for (const product of products) { for (const product of products) {
const block = emptyBlock(product.id); const block = emptyBlock(product.id);
setParam(block, 'chapter', { type: 'string', value: product.chapter }); setParam(block, 'chapter', { type: 'string', value: product.chapter });
+53 -2
View File
@@ -13,6 +13,8 @@
* default lets the client continue and reveal what it asks for next. * default lets the client continue and reveal what it asks for next.
*/ */
import { emptyBlock } from '@wto/blk'; import { emptyBlock } from '@wto/blk';
import type { ModCharRequest, ModCharResponse } from '@wto/mods';
import type { ServerModRuntime } from '../mods/server-mod-runtime.ts';
import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts';
import type { CharActionHandler } from './char-action.ts'; import type { CharActionHandler } from './char-action.ts';
import { toResponse, type CharAnswer } from './char-answers.ts'; import { toResponse, type CharAnswer } from './char-answers.ts';
@@ -23,17 +25,26 @@ const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
export class CharService implements Service { export class CharService implements Service {
readonly name = 'char'; readonly name = 'char';
readonly #actions: ReadonlyMap<string, CharActionHandler>; readonly #actions: ReadonlyMap<string, CharActionHandler>;
readonly #modRuntime: ServerModRuntime | undefined;
constructor(actions: ReadonlyMap<string, CharActionHandler>) { constructor(actions: ReadonlyMap<string, CharActionHandler>, modRuntime?: ServerModRuntime) {
this.#actions = actions; this.#actions = actions;
this.#modRuntime = modRuntime;
} }
accepts(request: ServiceRequest): boolean { accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost); return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
} }
handle(request: ServiceRequest): ServiceResponse { handle(request: ServiceRequest): ServiceResponse | Promise<ServiceResponse> {
const action = header(request, 'action') ?? '(no action header)'; const action = header(request, 'action') ?? '(no action header)';
if (this.#modRuntime?.hasCharOverride(action)) {
return this.#handleWithModOverride(action, request);
}
return this.#handleCore(action, request);
}
#handleCore(action: string, request: ServiceRequest): ServiceResponse {
const payload = decodeRequestPayload(request.body); const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action); const handler = this.#actions.get(action);
const answer: CharAnswer = handler const answer: CharAnswer = handler
@@ -56,6 +67,46 @@ export class CharService implements Service {
}, },
}; };
} }
async #handleWithModOverride(action: string, request: ServiceRequest): Promise<ServiceResponse> {
const headers: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(request.headers)) {
headers[key] = Array.isArray(value) ? value[0] : value;
}
const query: Record<string, string> = {};
for (const [key, value] of request.query.entries()) query[key] = value;
const modReq: ModCharRequest = {
action,
userId: header(request, 'uidhint') ?? '',
headers,
body: request.body,
query,
};
const result = await this.#modRuntime!.dispatchCharOverride(action, modReq, async (nextReq): Promise<ModCharResponse> => {
const forwarded: ServiceRequest = { ...request, body: nextReq.body };
const coreResp = this.#handleCore(nextReq.action, forwarded);
return {
status: coreResp.status,
...(coreResp.headers ? { headers: coreResp.headers } : {}),
body: coreResp.body ?? '',
};
});
const responseHeaders: Record<string, string> = { ...(result.headers ?? {}) };
if (result.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) {
responseHeaders['content-type'] = result.contentType;
}
return {
status: result.status ?? 200,
headers: responseHeaders,
body: result.body,
logNotes: {
summary: `${action} [mod handler] -> ${result.status ?? 200}`,
},
};
}
} }
function header(request: ServiceRequest, name: string): string | undefined { function header(request: ServiceRequest, name: string): string | undefined {
+14 -2
View File
@@ -31,6 +31,14 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray<keyof Omit<ClanLogEntry, 'id' | 'e
export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): BlkBlock { export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): BlkBlock {
const todayDay = Math.floor(nowSec / 86400); const todayDay = Math.floor(nowSec / 86400);
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, historyDepthDays } = tuning.activity; const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, historyDepthDays } = tuning.activity;
// `clanInfoTable.nut:269` passes `nextRewardDayId` straight to `time.buildDateTimeStr`
// (`clanAverageActivityModal.nut:60-62`), which expects a Unix timestamp in seconds.
// `clan_get_clan_info` (`aces.exe` 0x1787130) returns the raw DataBlock, and Squirrel
// `sqDataBlock` (`0x460da35`) pushes `TYPE_INT64` as a 64-bit integer.
const anchorDay = clan.lastRewardDay ?? todayDay;
const candidateNextDay = anchorDay + rewardPeriodDays;
const nextRewardDay = candidateNextDay > todayDay ? candidateNextDay : todayDay + rewardPeriodDays;
const nextRewardSec = nextRewardDay * 86400;
return { return {
name: '', name: '',
params: [ params: [
@@ -57,7 +65,7 @@ export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Mat
int('rewardPeriodDays', rewardPeriodDays), int('rewardPeriodDays', rewardPeriodDays),
bool('expRewardEnabled', true), bool('expRewardEnabled', true),
int('historyDepth', historyDepthDays), int('historyDepth', historyDepthDays),
int('nextRewardDayId', todayDay + rewardPeriodDays), int64('nextRewardDayId', BigInt(nextRewardSec)),
], ],
blocks: [ blocks: [
buildAstatBlock(clan, tuning), buildAstatBlock(clan, tuning),
@@ -215,7 +223,7 @@ function statParams(stats: ClanStats): BlkParam[] {
function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock { function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock {
const periods = member.periods.length > 0 const periods = member.periods.length > 0
? member.periods ? member.periods
: [{ day: todayDay, activity: member.curActivity, exp: 20000 }]; : (member.curActivity > 0 ? [{ day: todayDay, activity: member.curActivity, exp: 0 }] : []);
return { return {
name: member.uid, name: member.uid,
@@ -248,6 +256,10 @@ function int(name: string, value: number): BlkParam {
return { name, value: { type: 'int', value: Math.trunc(value) } }; return { name, value: { type: 'int', value: Math.trunc(value) } };
} }
function int64(name: string, value: bigint): BlkParam {
return { name, value: { type: 'int64', value } };
}
function bool(name: string, value: boolean): BlkParam { function bool(name: string, value: boolean): BlkParam {
return { name, value: { type: 'bool', value } }; return { name, value: { type: 'bool', value } };
} }
+4 -2
View File
@@ -54,13 +54,15 @@ export function addMemberToClan(
): void { ): void {
if (clan.members.some((m) => m.uid === uid)) return; if (clan.members.some((m) => m.uid === uid)) return;
const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning); const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning);
const curActivity = Math.min(tuning.activity.maxPerPeriod, tuning.activity.startingActivity);
const periodActivitySum = periods.reduce((s, p) => s + p.activity, 0);
clan.members.push({ clan.members.push({
uid, uid,
nick, nick,
role, role,
joinDateSec: nowSec, joinDateSec: nowSec,
curActivity: tuning.activity.maxPerPeriod, curActivity,
totalActivity: periods.reduce((s, p) => s + p.activity, 0), totalActivity: periods.length > 0 ? periodActivitySum : curActivity,
earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0),
ratingArc: tuning.playerRating.joiner.arc, ratingArc: tuning.playerRating.joiner.arc,
ratingHist: tuning.playerRating.joiner.hist, ratingHist: tuning.playerRating.joiner.hist,
+75
View File
@@ -0,0 +1,75 @@
/**
* Squadron (clan) battle season schedule matching `char.vromfs.bin` `config/clan_rewards.blk`
* (`seasons{}`): six bi-monthly UTC seasons per year starting on the 1st of Jan, Mar, May,
* Jul, Sep, and Nov at 00:00:00 UTC.
*
* Wire contract verified in stock `aces.exe` (2.61.0.58):
* - `GameSaveData::onAsyncEconTransComplete` (`0xebc33c..0xebc7b4`) reads four top-level
* profile parameters on every profile-returning char transaction:
* - `clanDuelNextReward:i64` (`0xebc731..0xebc745`, `DataBlock::getInt64`) -> `rewardDay`
* - `clanSeasonStart:i64` (`0xebc755..0xebc769`, `DataBlock::getInt64`) -> `startDay`
* - `clanSeasonOrdinal:i` (`0xebc778..0xebc78c`, `DataBlock::getInt`) -> `ordinalNumber`
* - `clanSeasonInYear:i` (`0xebc79a..0xebc7ae`, `DataBlock::getInt`) -> `numberInYear`
* - `clan_get_current_season_info` (`0x178aff0..0x178b227`) exposes those four fields verbatim.
* - `gui.vromfs.bin` `scripts/clans/clanseasons.nut:45-54` formats the title using
* `unixtime_to_utc_timetbl(info.startDay).year` and `info.numberInYear + 1`
* (`CLAN_SEASON_NUM_IN_YEAR_SHIFT = 1`, yielding Roman numerals `I`..`VI`), and formats the
* end time with `time.buildDateTimeStr(info.rewardDay, false, false)`.
*/
export interface ClanSeasonInfo {
/** UTC 00:00:00 start of the active season as Unix seconds. */
readonly startDaySec: number;
/** UTC 00:00:00 end/reward timestamp of the active season (start of next season) as Unix seconds. */
readonly rewardDaySec: number;
/** Zero-based season index within the UTC year (`0..5`, displayed as `I..VI`). */
readonly numberInYear: number;
/** Monotonic positive ordinal season number across years. */
readonly ordinalNumber: number;
}
/** Season start month/day pairs from `char.vromfs.bin` `config/clan_rewards.blk` `seasons{}`. */
export const CLAN_SEASON_STARTS: ReadonlyArray<{ readonly month: number; readonly day: number }> = [
{ month: 1, day: 1 },
{ month: 3, day: 1 },
{ month: 5, day: 1 },
{ month: 7, day: 1 },
{ month: 9, day: 1 },
{ month: 11, day: 1 },
];
const SEASON_ORDINAL_BASE_YEAR = 2016;
/** Compute the active squadron battle season for a given Unix timestamp in seconds. */
export function currentClanSeason(nowSec = Math.floor(Date.now() / 1000)): ClanSeasonInfo {
const now = new Date(Math.trunc(nowSec) * 1000);
const year = now.getUTCFullYear();
const seasonCount = CLAN_SEASON_STARTS.length;
let activeIndex = 0;
let startSec = Date.UTC(year, CLAN_SEASON_STARTS[0]!.month - 1, CLAN_SEASON_STARTS[0]!.day) / 1000;
for (let i = seasonCount - 1; i >= 0; i--) {
const entry = CLAN_SEASON_STARTS[i]!;
const candidateSec = Date.UTC(year, entry.month - 1, entry.day) / 1000;
if (nowSec >= candidateSec) {
activeIndex = i;
startSec = candidateSec;
break;
}
}
const nextIndex = (activeIndex + 1) % seasonCount;
const nextYear = activeIndex + 1 >= seasonCount ? year + 1 : year;
const nextEntry = CLAN_SEASON_STARTS[nextIndex]!;
const rewardSec = Date.UTC(nextYear, nextEntry.month - 1, nextEntry.day) / 1000;
const ordinalNumber = Math.max(1, (year - SEASON_ORDINAL_BASE_YEAR) * seasonCount + activeIndex + 1);
return {
startDaySec: startSec,
rewardDaySec: rewardSec,
numberInYear: activeIndex,
ordinalNumber,
};
}
+119 -12
View File
@@ -3,25 +3,75 @@
* The directory is written when the server first creates `<data>/clans.json`. * The directory is written when the server first creates `<data>/clans.json`.
*/ */
import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts'; import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts';
import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts'; import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts';
const SECONDS_PER_DAY = 86400; const SECONDS_PER_DAY = 86400;
export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY; const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY;
return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning)); return tuning.presetClans.clans.map((spec, specIndex) =>
buildSeededClan(spec, specIndex, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning));
} }
/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */ /**
export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] { * The activity periods a member starts with: `periodCount` periods (defaulting to
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity; * `activity.startingPeriods`), each with the given activity and the squadron RP it earns.
*/
export function buildDefaultPeriods(
todayDay: number,
tuning: ClanTuning,
periodActivity = tuning.activity.maxPerPeriod,
periodCount = tuning.activity.startingPeriods,
): ClanActivityPeriodEntry[] {
if (periodCount <= 0) return [];
const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays } = tuning.activity;
const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod); const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod);
return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); return Array.from({ length: periodCount }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp }));
} }
function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord { /**
const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning)); * Idempotently appends deterministic filler NPCs to an existing preset clan whose
* persisted roster is smaller than its configured `targetMemberCount`, without altering
* any existing player or NPC members.
*/
export function backfillPresetClanMembers(
clan: ClanRecord,
spec: PresetClan,
specIndex: number,
todayDay: number,
tuning: ClanTuning,
): boolean {
const targetCount = Math.min(clan.mlimit, spec.targetMemberCount);
if (clan.members.length >= targetCount) return false;
const existingUids = new Set(clan.members.map((m) => m.uid));
const fillerSpecs = buildPresetFillerSpecs(spec, specIndex, tuning);
let added = false;
for (let i = 0; i < fillerSpecs.length && clan.members.length < targetCount; i++) {
const npc = fillerSpecs[i]!;
if (existingUids.has(npc.uid)) continue;
existingUids.add(npc.uid);
const memberIdx = spec.members.length + i;
clan.members.push(buildSeededMember(spec, npc, memberIdx, clan.cdateSec, todayDay, tuning));
added = true;
}
return added;
}
function buildSeededClan(
spec: PresetClan,
specIndex: number,
cdateSec: number,
todayDay: number,
tuning: ClanTuning,
): ClanRecord {
const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal;
const allSpecs: PresetMember[] = [
...spec.members,
...buildPresetFillerSpecs(spec, specIndex, tuning),
].slice(0, mlimit);
const members = allSpecs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning));
const leader = spec.members[0]!; const leader = spec.members[0]!;
return { return {
id: spec.id, id: spec.id,
@@ -35,13 +85,14 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t
region: spec.region, region: spec.region,
status: 'open', status: 'open',
autoaccept: spec.autoAccept, autoaccept: spec.autoAccept,
mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal, mlimit,
mspent: 0, mspent: 0,
cdateSec, cdateSec,
changedByUid: leader.uid, changedByUid: leader.uid,
changedByNick: leader.nick, changedByNick: leader.nick,
changedTimeSec: cdateSec, changedTimeSec: cdateSec,
regionLastUpdatedSec: 0, regionLastUpdatedSec: 0,
lastRewardDay: todayDay,
stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats }, stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats },
members, members,
candidates: [], candidates: [],
@@ -55,8 +106,64 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t
}; };
} }
function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord { function buildPresetFillerSpecs(spec: PresetClan, specIndex: number, tuning: ClanTuning): PresetMember[] {
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity); const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal;
const targetCount = Math.min(mlimit, Math.max(spec.members.length, spec.targetMemberCount));
const needed = targetCount - spec.members.length;
if (needed <= 0) return [];
const filler = tuning.presetClans.fillerMembers;
const clanSlot = presetClanSlot(spec.id, specIndex);
const usedUids = new Set(spec.members.map((m) => m.uid));
const span = Math.max(0, filler.activityMax - filler.activityMin);
const result: PresetMember[] = [];
let ordinal = spec.members.length + 1;
while (result.length < needed) {
const uid = String(filler.uidBase + clanSlot * filler.uidStride + ordinal);
if (usedUids.has(uid)) {
ordinal++;
continue;
}
usedUids.add(uid);
const callsign = filler.callsigns[(clanSlot * 7 + ordinal) % filler.callsigns.length]!;
const title = filler.titles[(clanSlot * 3 + ordinal) % filler.titles.length]!;
const icon = filler.icons[(clanSlot * 5 + ordinal) % filler.icons.length]!;
const unit = filler.units[(clanSlot * 11 + ordinal) % filler.units.length]!;
const activityOffset = span > 0 ? (clanSlot * 13 + ordinal * 17) % (span + 1) : 0;
const activity = Math.min(tuning.activity.maxPerPeriod, filler.activityMin + activityOffset);
result.push({
uid,
nick: `${callsign}_${clanSlot}${String(ordinal).padStart(2, '0')}`,
role: ClanRole.REGULAR,
title,
icon,
unit,
activity,
});
ordinal++;
}
return result;
}
function presetClanSlot(clanId: string, specIndex: number): number {
const parsed = Number(clanId);
if (Number.isSafeInteger(parsed) && parsed > 0) {
const remainder = parsed % 1000;
if (remainder > 0) return remainder;
}
return specIndex + 1;
}
function buildSeededMember(
spec: PresetClan,
npc: PresetMember,
idx: number,
cdateSec: number,
todayDay: number,
tuning: ClanTuning,
): ClanMemberRecord {
const periods = buildDefaultPeriods(todayDay, tuning, npc.activity, tuning.presetClans.npcHistoryPeriods);
const { step, floor } = tuning.presetClans.memberRating; const { step, floor } = tuning.presetClans.memberRating;
return { return {
uid: npc.uid, uid: npc.uid,
@@ -69,7 +176,7 @@ function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cda
npcFrame: '', npcFrame: '',
npcShowcaseUnit: npc.unit, npcShowcaseUnit: npc.unit,
curActivity: npc.activity, curActivity: npc.activity,
totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), totalActivity: periods.length > 0 ? periods.reduce((sum, p) => sum + p.activity, 0) : npc.activity,
earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0),
ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc), ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc),
ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist), ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist),
+187 -27
View File
@@ -39,10 +39,12 @@ import {
type MembershipRequestQuery, type MembershipRequestQuery,
} from './clan-membership.ts'; } from './clan-membership.ts';
import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts'; import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts';
import { createDefaultClans } from './clan-seeds.ts'; import { backfillPresetClanMembers, createDefaultClans } from './clan-seeds.ts';
import type { ClanTuning } from './clan-tuning.ts'; import type { ClanTuning } from './clan-tuning.ts';
import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts'; import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts';
const SECONDS_PER_DAY = 86400;
export type { LeaderboardQuery }; export type { LeaderboardQuery };
export class ClanStore { export class ClanStore {
@@ -51,18 +53,36 @@ export class ClanStore {
readonly tuning: ClanTuning; readonly tuning: ClanTuning;
#state: StoredClansState; #state: StoredClansState;
constructor(dataFolder: string, tuning: ClanTuning) { constructor(dataFolder: string, tuning: ClanTuning, nowSec = nowSeconds()) {
this.#filePath = join(dataFolder, 'clans.json'); this.#filePath = join(dataFolder, 'clans.json');
this.tuning = tuning; this.tuning = tuning;
this.#state = this.#loadOrSeed(); this.#state = this.#loadOrSeed(nowSec);
} }
#loadOrSeed(): StoredClansState { #loadOrSeed(nowSec: number): StoredClansState {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
if (existsSync(this.#filePath)) { if (existsSync(this.#filePath)) {
const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState; const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState;
if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed; if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') {
let mutated = false;
for (let i = 0; i < this.tuning.presetClans.clans.length; i++) {
const spec = this.tuning.presetClans.clans[i]!;
const existing = parsed.clans.find((c) => c.id === spec.id);
if (existing && backfillPresetClanMembers(existing, spec, i, todayDay, this.tuning)) {
mutated = true;
} }
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) }; }
for (const clan of parsed.clans) {
if (clan.lastRewardDay === undefined) {
clan.lastRewardDay = todayDay;
mutated = true;
}
}
if (mutated) this.#save(parsed);
return parsed;
}
}
const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) };
this.#save(seeded); this.#save(seeded);
return seeded; return seeded;
} }
@@ -71,19 +91,7 @@ export class ClanStore {
writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2)); writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2));
} }
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { #findUserClan(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan;
}
byId(clanId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined {
return findClanInList(this.#state.clans, query);
}
clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
for (const clan of this.#state.clans) { for (const clan of this.#state.clans) {
const member = clan.members.find((m) => m.uid === userId); const member = clan.members.find((m) => m.uid === userId);
if (member) return { clan, member }; if (member) return { clan, member };
@@ -91,12 +99,147 @@ export class ClanStore {
return undefined; return undefined;
} }
#resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined {
return clanId && clanId !== '-1'
? this.#state.clans.find((c) => c.id === clanId)
: this.#findUserClan(userId)?.clan;
}
/**
* Lazily settles expired activity reward periods for all squadrons using the stock
* client formula (`clanAverageActivityModal.nut:44-54`):
* `myExp = min(min(1, myPercent / clanPercent) * clanActivity, maxClanActivity)`
* Player members' current-period activity resets to 0 for the new period while NPC
* members keep their active roster contribution.
*/
settleExpiredPeriods(nowSec = nowSeconds()): boolean {
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const {
maxPerPeriod,
squadronRpPerFullPeriod: maxClanActivity,
rewardPeriodDays,
historyDepthDays,
} = this.tuning.activity;
let mutated = false;
for (const clan of this.#state.clans) {
if (clan.lastRewardDay === undefined) {
clan.lastRewardDay = todayDay;
mutated = true;
continue;
}
const elapsedDays = todayDay - clan.lastRewardDay;
if (elapsedDays < rewardPeriodDays) continue;
const anchorDay = clan.lastRewardDay;
const periodsPassed = Math.floor(elapsedDays / rewardPeriodDays);
const settlementDay = anchorDay + rewardPeriodDays;
const nextAnchorDay = anchorDay + periodsPassed * rewardPeriodDays;
const clanActivity = clan.members.reduce((sum, m) => sum + Math.max(0, m.curActivity), 0);
const maxActivity = maxPerPeriod * clan.members.length;
const clanPercent = maxActivity > 0 ? clanActivity / maxActivity : 0;
const minKeptDay = settlementDay - historyDepthDays;
clan.members = clan.members.map((member) => {
const myActivity = Math.max(0, member.curActivity);
const myPercent = maxPerPeriod > 0 ? myActivity / maxPerPeriod : 0;
const myExp = (myPercent > 0 && clanPercent > 0)
? Math.min(maxClanActivity, Math.round(Math.min(1, myPercent / clanPercent) * clanActivity))
: 0;
const pastSettled = member.periods.filter((p) => !(p.exp === 0 && p.day >= anchorDay && p.day <= settlementDay));
const settledEntry = (myActivity > 0 || myExp > 0)
? [{ day: settlementDay, activity: myActivity, exp: myExp }]
: [];
const nextPeriods = [...settledEntry, ...pastSettled].filter((p) => p.day >= minKeptDay);
if (member.isNpc) {
return {
...member,
totalActivity: member.totalActivity + myActivity,
earnedSquadronExp: member.earnedSquadronExp + myExp,
periods: nextPeriods,
};
}
return {
...member,
curActivity: 0,
earnedSquadronExp: member.earnedSquadronExp + myExp,
periods: nextPeriods,
};
});
clan.lastRewardDay = nextAnchorDay;
mutated = true;
}
if (mutated) this.#save();
return mutated;
}
/**
* Accumulates current-period squadron activity from battle base vehicle RP
* (`floor(baseVehicleRp / rpPerActivityPoint)`, capped at `maxPerPeriod`).
* Returns the activity points actually added.
*/
recordBattleActivity(userId: string, baseVehicleRp: number, nowSec = nowSeconds()): number {
this.settleExpiredPeriods(nowSec);
if (!Number.isFinite(baseVehicleRp) || baseVehicleRp <= 0) return 0;
const found = this.#findUserClan(userId);
if (!found) return 0;
const { maxPerPeriod, rpPerActivityPoint } = this.tuning.activity;
const rawGain = Math.floor(baseVehicleRp / rpPerActivityPoint);
if (rawGain <= 0) return 0;
const { clan, member } = found;
const remaining = Math.max(0, maxPerPeriod - member.curActivity);
const added = Math.min(rawGain, remaining);
if (added <= 0) return 0;
const todayDay = Math.floor(nowSec / SECONDS_PER_DAY);
const periodStartDay = clan.lastRewardDay ?? todayDay;
const nextCurActivity = member.curActivity + added;
const nextTotalActivity = member.totalActivity + added;
const existingInProgressIdx = member.periods.findIndex((p) => p.exp === 0 && p.day >= periodStartDay);
const nextPeriods = existingInProgressIdx >= 0
? member.periods.map((p, idx) => (idx === existingInProgressIdx ? { day: todayDay, activity: nextCurActivity, exp: 0 } : p))
: [{ day: todayDay, activity: nextCurActivity, exp: 0 }, ...member.periods];
const memberIdx = clan.members.findIndex((m) => m.uid === userId);
if (memberIdx < 0) return 0;
clan.members[memberIdx] = {
...member,
curActivity: nextCurActivity,
totalActivity: nextTotalActivity,
periods: nextPeriods,
};
this.#save();
return added;
}
byId(clanId: string, nowSec = nowSeconds()): ClanRecord | undefined {
this.settleExpiredPeriods(nowSec);
return this.#state.clans.find((c) => c.id === clanId);
}
findClan(
query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined },
nowSec = nowSeconds(),
): ClanRecord | undefined {
this.settleExpiredPeriods(nowSec);
return findClanInList(this.#state.clans, query);
}
clanOfUser(userId: string, nowSec = nowSeconds()): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
this.settleExpiredPeriods(nowSec);
return this.#findUserClan(userId);
}
pendingRequestOfUser(userId: string): ClanRecord | undefined { pendingRequestOfUser(userId: string): ClanRecord | undefined {
return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId)); return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId));
} }
earnedSquadronExpOf(userId: string): number { earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number {
return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0; return this.clanOfUser(userId, nowSec)?.member.earnedSquadronExp ?? 0;
} }
npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined {
@@ -107,8 +250,8 @@ export class ClanStore {
return undefined; return undefined;
} }
syncProfile(profile: BlkBlock, account: Account): void { syncProfile(profile: BlkBlock, account: Account, nowSec = nowSeconds()): void {
const found = this.clanOfUser(account.userId); const found = this.clanOfUser(account.userId, nowSec);
if (found) { if (found) {
const { clan, member } = found; const { clan, member } = found;
if (member.nick !== account.nick) { if (member.nick !== account.nick) {
@@ -131,15 +274,31 @@ export class ClanStore {
} }
} }
queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { queryLeaderboard(query: LeaderboardQuery, nowSec = nowSeconds()): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> {
this.settleExpiredPeriods(nowSec);
return queryClanLeaderboard(this.#state.clans, query, this.tuning); return queryClanLeaderboard(this.#state.clans, query, this.tuning);
} }
createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome { createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome {
this.settleExpiredPeriods(nowSec);
const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec); const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec);
if (outcome.ok) { if (outcome.ok) {
const created = this.#state.clans[0];
if (created) {
created.lastRewardDay = Math.floor(nowSec / SECONDS_PER_DAY);
const founder = created.members[0];
if (founder && founder.uid === account.userId) {
const curActivity = Math.min(this.tuning.activity.maxPerPeriod, this.tuning.activity.startingActivity);
const periodActivitySum = founder.periods.reduce((s, p) => s + p.activity, 0);
created.members[0] = {
...founder,
curActivity,
totalActivity: founder.periods.length > 0 ? periodActivitySum : curActivity,
};
}
}
this.#save(); this.#save();
this.syncProfile(profile, account); this.syncProfile(profile, account, nowSec);
} }
return outcome; return outcome;
} }
@@ -189,10 +348,11 @@ export class ClanStore {
} }
requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome { requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome {
const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning); this.settleExpiredPeriods(nowSec);
const res = requestOrCancelMembershipInState(this.#state.clans, findClanInList(this.#state.clans, query), Boolean(this.#findUserClan(account.userId)), account, query, nowSec, this.tuning);
if (res.mutated) { if (res.mutated) {
this.#save(); this.#save();
this.syncProfile(profile, account); this.syncProfile(profile, account, nowSec);
} }
return res.outcome; return res.outcome;
} }
+46 -1
View File
@@ -26,6 +26,17 @@ export interface PresetMember {
readonly activity: number; readonly activity: number;
} }
export interface PresetFillerMembers {
readonly activityMin: number;
readonly activityMax: number;
readonly uidBase: number;
readonly uidStride: number;
readonly callsigns: readonly string[];
readonly titles: readonly string[];
readonly icons: readonly string[];
readonly units: readonly string[];
}
export interface PresetClan { export interface PresetClan {
readonly id: string; readonly id: string;
readonly tag: string; readonly tag: string;
@@ -37,6 +48,7 @@ export interface PresetClan {
readonly region: string; readonly region: string;
readonly autoAccept: boolean; readonly autoAccept: boolean;
readonly createdAfterDays: number; readonly createdAfterDays: number;
readonly targetMemberCount: number;
readonly rating: ModeTriple; readonly rating: ModeTriple;
readonly members: readonly PresetMember[]; readonly members: readonly PresetMember[];
} }
@@ -47,6 +59,8 @@ export interface ClanTuning {
readonly squadronRpPerFullPeriod: number; readonly squadronRpPerFullPeriod: number;
readonly rewardPeriodDays: number; readonly rewardPeriodDays: number;
readonly historyDepthDays: number; readonly historyDepthDays: number;
readonly rpPerActivityPoint: number;
readonly startingActivity: number;
readonly startingPeriods: number; readonly startingPeriods: number;
}; };
readonly memberLimits: { readonly normal: number; readonly battalionInitial: number }; readonly memberLimits: { readonly normal: number; readonly battalionInitial: number };
@@ -56,6 +70,8 @@ export interface ClanTuning {
readonly presetClans: { readonly presetClans: {
readonly createdDaysAgo: number; readonly createdDaysAgo: number;
readonly memberJoinSpacingMinutes: number; readonly memberJoinSpacingMinutes: number;
readonly npcHistoryPeriods: number;
readonly fillerMembers: PresetFillerMembers;
readonly stats: PresetClanStats; readonly stats: PresetClanStats;
readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple }; readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple };
readonly clans: readonly PresetClan[]; readonly clans: readonly PresetClan[];
@@ -64,6 +80,7 @@ export interface ClanTuning {
export function readClanTuning(file: TuningReader): ClanTuning { export function readClanTuning(file: TuningReader): ClanTuning {
const activity = file.object('activity'); const activity = file.object('activity');
const maxPerPeriod = activity.int('maxPerPeriod', { min: 1 });
const limits = file.object('memberLimits'); const limits = file.object('memberLimits');
const leaderboard = file.object('leaderboard'); const leaderboard = file.object('leaderboard');
const preset = file.object('presetClans'); const preset = file.object('presetClans');
@@ -71,10 +88,12 @@ export function readClanTuning(file: TuningReader): ClanTuning {
const rating = preset.object('memberRating'); const rating = preset.object('memberRating');
return { return {
activity: { activity: {
maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }), maxPerPeriod,
squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }), squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }),
rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }), rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }),
historyDepthDays: activity.int('historyDepthDays', { min: 1 }), historyDepthDays: activity.int('historyDepthDays', { min: 1 }),
rpPerActivityPoint: activity.int('rpPerActivityPoint', { min: 1 }),
startingActivity: activity.int('startingActivity', { min: 0, max: maxPerPeriod }),
startingPeriods: activity.int('startingPeriods', { min: 0 }), startingPeriods: activity.int('startingPeriods', { min: 0 }),
}, },
memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) }, memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) },
@@ -84,6 +103,8 @@ export function readClanTuning(file: TuningReader): ClanTuning {
presetClans: { presetClans: {
createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }), createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }),
memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }), memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }),
npcHistoryPeriods: preset.int('npcHistoryPeriods', { min: 0 }),
fillerMembers: readFillerMembers(preset.object('fillerMembers'), maxPerPeriod),
stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats, stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats,
memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) }, memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) },
clans: preset.list('clans', readPresetClan), clans: preset.list('clans', readPresetClan),
@@ -91,11 +112,34 @@ export function readClanTuning(file: TuningReader): ClanTuning {
}; };
} }
function readFillerMembers(entry: TuningReader, maxPerPeriod: number): PresetFillerMembers {
const activityMin = entry.int('activityMin', { min: 0, max: maxPerPeriod });
const activityMax = entry.int('activityMax', { min: activityMin, max: maxPerPeriod });
const callsigns = entry.stringList('callsigns');
const titles = entry.stringList('titles');
const icons = entry.stringList('icons');
const units = entry.stringList('units');
if (callsigns.length === 0 || titles.length === 0 || icons.length === 0 || units.length === 0) {
throw new TuningError('tuning file clans.jsonc: presetClans.fillerMembers callsigns, titles, icons, and units must be non-empty');
}
return {
activityMin,
activityMax,
uidBase: entry.int('uidBase', { min: 1 }),
uidStride: entry.int('uidStride', { min: 1 }),
callsigns,
titles,
icons,
units,
};
}
function readPresetClan(entry: TuningReader): PresetClan { function readPresetClan(entry: TuningReader): PresetClan {
const type = entry.string('type'); const type = entry.string('type');
if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`); if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`);
const members = entry.list('members', readPresetMember); const members = entry.list('members', readPresetMember);
if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`); if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`);
const rawTarget = entry.has('targetMemberCount') ? entry.int('targetMemberCount', { min: 1 }) : members.length;
return { return {
id: entry.string('id'), id: entry.string('id'),
tag: entry.string('tag'), tag: entry.string('tag'),
@@ -107,6 +151,7 @@ function readPresetClan(entry: TuningReader): PresetClan {
region: entry.string('region'), region: entry.string('region'),
autoAccept: entry.bool('autoAccept'), autoAccept: entry.bool('autoAccept'),
createdAfterDays: entry.int('createdAfterDays', { min: 0 }), createdAfterDays: entry.int('createdAfterDays', { min: 0 }),
targetMemberCount: Math.max(members.length, rawTarget),
rating: triple(entry.object('rating')), rating: triple(entry.object('rating')),
members, members,
}; };
+2
View File
@@ -171,6 +171,8 @@ export interface ClanRecord {
changedByNick: string; changedByNick: string;
changedTimeSec: number; changedTimeSec: number;
regionLastUpdatedSec: number; regionLastUpdatedSec: number;
/** UTC day index (floor(unixSec / 86400)) when the current activity reward period started. */
lastRewardDay?: number;
stats: ClanStats; stats: ClanStats;
members: ClanMemberRecord[]; members: ClanMemberRecord[];
candidates: ClanCandidateRecord[]; candidates: ClanCandidateRecord[];
Loaded 100 of 329 files, more files were not shown because too many files have changed in this diff. Show more