33 Commits
Author SHA1 Message Date
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 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 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 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
N0VAN0M4LY fb7d07f4f9 feat(launcher): add About log export shortcut and runtime logging toggle
Launcher release / release (push) Waiting to run
Add a quick ZIP log export button to the About page (also bundling the latest embedded browser -browser.log while excluding player saves) and add a runtime logging toggle under Settings -> Diagnostics that controls launcher file logs, local server traffic logs, and wto_ws.log via log=0 in wto_ws.cfg. Update the v0.1.2 release note accordingly.
2026-12-02 17:41:49 +08:00
N0VAN0M4LY 2d5e268083 chore(launcher): bump version to 0.1.2 and add release note
Bump @wto/launcher to 0.1.2 in apps/launcher/package.json and package-lock.json, and add the bilingual release note in .github/release-notes/v0.1.2.md.
2026-12-02 17:23:13 +08:00
N0VAN0M4LY 66bbdf7192 fix(launcher): prevent false maintenance_location errors and log details
Exclude stray top-level wtoffline folders when scanning stock sources, block selecting a data folder that equals or contains the client folder during installation (with inline Step 3 feedback), avoid false maintenance_location blocks when an existing installation placed dataPath at an ancestor of copyPath while still protecting nested data folders and data entries, and log the specific reason and paths on every maintenance_location failure.
2026-12-02 17:10:58 +08:00
N0VAN0M4LY bf2ce539e7 feat(launcher): use version-independent rules for space-saving copies
Replace the single-version 2.61.0.43 SHA-256 hardlink manifest with declarative read-only asset rules in packages/patcher/tuning/hardlink-resources.jsonc (content/ and content.hq/ .dxp.bin and .grp archives with no minimum size cutoff). Space-saving installs and conversions now work across minor updates, and updating a space-saving client from a same-volume source preserves or creates hard links instead of detaching them into full copies.
2026-12-02 17:04:36 +08:00
N0VAN0M4LY 3ed41bdd60 feat(patches): add 2.61.0.58 version check record
Adaptation pack / release (push) Waiting to run
Verified all 13 exe patches, 46 GUI patches (Quirrel bytecode check), and 11 native modules against Steam 2.61.0.58 with zero struct offset changes from 2.61.0.55 and a clean temporary copy build.
2026-12-02 16:54:56 +08:00
N0VAN0M4LY a23629fe69 docs(release): refine wording in v0.1.1 release notes
Launcher release / release (push) Waiting to run
2026-12-02 10:46:46 +08:00
N0VAN0M4LY 1535bd032b docs(release): emphasize v0.1.1 upgrade for standalone and official-launcher users 2026-12-02 10:33:28 +08:00
N0VAN0M4LY de9ba52b85 fix(isolation): skip package validation and block official launcher spawns
Add -skip_pkg_validation to the shared offline launch arguments so aces.exe
skips the startup content/warthunder.blk file-size check, and add the
isolation/never-launch-official-launcher exe patch to NOP the os_shell_execute
call in the official launcher spawner while preserving its exit logging and
ExitProcess(1).
2026-12-02 10:18:54 +08:00
N0VAN0M4LY 82ec1c47ff feat(launcher): support signed in-place updates for portable builds 2026-12-02 09:37:05 +08:00
N0VAN0M4LY e284ea7ed6 chore(launcher): bump version to 0.1.1 and add release note
Bump @wto/launcher to 0.1.1 in apps/launcher/package.json and package-lock.json, and add the bilingual release note in .github/release-notes/v0.1.1.md.

Checked: root and launcher typechecks pass.
2026-12-02 09:21:35 +08:00
N0VAN0M4LY ae1e5ec65b feat(repo): package portable zip in local Windows builds
Clean and generate wtoffline-launcher-<version>-win-x64-portable.zip from win-unpacked directly inside scripts/build-windows-installer.ts so local package:win builds produce both the NSIS installer and the portable archive.

Checked: root and launcher typechecks pass.
2026-12-02 09:20:32 +08:00
N0VAN0M4LY c55ec4ed57 fix(launcher): detect stale stock backups and distinguish missing backups on launch
Read the live executable version in inspectGameFolder instead of masking externally updated folders behind an older wtoffline/stock backup, and atomically refresh stale or unreadable backups during install, external stock import, and relocation. Log exact copy/stock/recorded versions on launch mismatches and report a dedicated launch_stock_missing error when wtoffline/stock/win64/aces.exe is missing or unreadable.

Checked: root typecheck, launcher typecheck, zh-CN/en locale key parity (616/616), and launcher electron-vite build.
2026-12-02 09:06:28 +08:00
N0VAN0M4LY f3d04d137f fix(native): filter avionics damage notices and enemy parts feedback
Replace the ineffective hero_unit comparison with producer-side hooks on the two stock LocalMP leaks:
1) Avionics/electronics failure dispatcher (2.61.0.37 0xfca8b0, .43 0xfce8e0): track the damaged Unit* from [component + unit] on the current thread and suppress HUD_MSG_DAMAGE notices and optic-view exits (0x15cd9c0) for non-local units while keeping native failure effects intact.
2) Unit::onEvent hit-parts fallthrough (2.61.0.37 0x103fbc0, .43 0x1043fe0): track the hit event on the current thread and filter enqueue_enemy_parts, hit_cam_important, and naval_hit_state to attacks from the local controlled unit, local MPlayer's units (in-flight munitions after switching), or the watched spectator unit.

Checked: native/wto-net/build.ps1 compiles with zero warnings in project sources; checkPatchSet, root and launcher typechecks, 2.61.0.37 check-patches, and native module resolution on both 2.61.0.37 and 2.61.0.43 (11/11 modules ready, 0 failures) pass. In-game verification pending.
2026-12-02 08:14:54 +08:00
N0VAN0M4LY 96077153c6 refactor(native): batch MinHook enable calls and log status codes
Switch ws2_32 and LocalMP hook installers to MH_QueueEnableHook with two MH_ApplyQueued passes (mandatory network hooks first, then all LocalMP modules), reducing DllMain thread-freeze cycles from 26 to 2. Roll back partial module hooks on error and log MH_StatusToString diagnostics to wto_ws.log.

Checked: native/wto-net/build.ps1 compiles cleanly with zero warnings in project sources, and PE inspection confirms WS2_32/KERNEL32 imports and 49 exports. In-game verification pending.
2026-12-02 07:24:27 +08:00
N0VAN0M4LY 90bd5a315d fix(patcher): replace built game files atomically with retry
Write rebuilt game files to sibling temporary files, flush to disk, and replace targets via rename with bounded retries on transient EPERM/EBUSY/EACCES errors (clearing read-only attributes when needed). This prevents antivirus scans or interrupted writes from leaving missing or truncated client files while keeping hard-linked stock files untouched.

Checked: root typecheck, launcher typecheck, and atomic replacement runtime check on read-only and new files.
2026-12-02 07:20:43 +08:00
N0VAN0M4LY 1c6f5c9fc4 feat(launcher): verify launch files and log post-exit diagnostics
Check that win64/aces.exe, wto_ws.dll, and wto_ws.cfg exist and are readable immediately before spawning the game, surfacing a dedicated error when security software removes them. On unexpected non-zero exits, log a compact read-only snapshot of hook file presence, wto_ws.log tail lines, and newly created .game_logs entries.

Checked: root typecheck, launcher typecheck, and zh-CN/en locale key parity.
2026-12-02 07:18:27 +08:00
N0VAN0M4LY cab73f92f9 feat(launcher): include client logs in diagnostics and format exit codes
Export the active client's wto_ws.log, latest .clog (bounded to 16 MiB), and a client-logs/summary.json metadata snapshot in diagnostics ZIPs without touching player saves. Log build completion, game launch arguments, PID, runtime duration, and hex-annotated Windows NTSTATUS/HRESULT exit codes in the launcher log and status bar.

Checked: root typecheck, launcher typecheck, launcher electron-vite build, and exit code formatter runtime check.
2026-12-02 07:15:37 +08:00
N0VAN0M4LY 1c24adbd83 feat(repo): attach a portable zip to launcher releases
Adaptation pack / release (push) Waiting to run
Zip the unpacked app after packaging and upload it as a fourth release asset for manual download. The zip is unsigned; only the installer is Ed25519-signed for the update check.
2026-12-01 22:37:07 +08:00
142 changed files with 4733 additions and 3373 deletions

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
## 简体中文
> **重要升级提示:** 所有使用 **Gaijin 官方独立版客户端**,或者 **Steam 版但曾经通过官方启动器(更新器)启动过游戏** 的用户,**必须更新到 `v0.1.1` 启动器**(更新后请对已有离线副本重新执行一次「构建客户端」)。旧版启动器在存在官方清单 `content/warthunder.blk` 时会触发游戏拉起官方启动器并还原离线补丁,导致启动闪退、弹出官服更新或报原版备份不一致。
`v0.1.1` 是 WTOffline 启动器的重要维护更新,重点修复官方客户端/官方启动器用户无法正常启动的问题、修复对局中非本机载具受损提示串台,并增强启动稳定性与故障诊断能力。
### 修复与改进
- **解决官方独立版 / 官方启动器拉起官服更新的问题。** 启动参数新增 `-skip_pkg_validation`,跳过 `aces.exe` 启动时对官方 `content/warthunder.blk` 的文件体积校验;同时新增可执行文件隔离补丁,阻止游戏在异常情况下拉起官方 `launcher.exe -fullcheck` 联网覆盖离线文件,修复“启动数秒后以退出码 `1` 退出 → 弹出官服更新 → 离线文件被还原/报备份不一致”的死循环。
- **局内受损提示与敌方部件归属。** 修复空战与现代陆战中 AI 载具航电、传感器、雷达、红外干扰和瞄准吊舱受损时错误向玩家弹出白字提示(及误退光电视角)的问题;过滤陆战与海战右侧敌方部件损毁列表及特殊命中反馈中的非本机攻击记录,保留本机在途弹药与观战视角显示。
- **启动与写盘稳定性。** 游戏补丁文件写入改为临时文件原子替换并带短暂占用重试,降低安全软件实时扫描导致写入失败的风险;优化 `wto_ws.dll` 加载时的钩子批量启用流程,减少初始化期的线程冻结次数并记录详细错误码。
- **原版备份检测与报错。** 修复旧版 `wtoffline\stock` 备份在客户端更新后遮蔽实际版本、无法自动刷新的问题;启动时区分「原版文件备份缺失/损坏」与「版本不一致」,并在日志中记录双方实际版本号。
- **启动前检查与诊断导出。** 启动游戏前核对核心文件是否可读(提前提示可能被安全软件隔离);异常退出时在启动器日志记录现场文件状态与带十六进制的系统退出码;导出的诊断 ZIP 自动附带 `wto_ws.log`、最新一份游戏 `.clog` 日志和环境摘要(不含玩家存档)。
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
## English
> **Important upgrade notice:** All users on the **standalone Gaijin client**, as well as **Steam users who have ever launched the game through the official Gaijin launcher/updater**, **must upgrade to `v0.1.1`** (and rebuild existing offline copies after updating). On earlier launcher versions, the presence of `content/warthunder.blk` causes `aces.exe` to spawn the official launcher and overwrite patched offline files, resulting in startup exit code `1`, official updater popups, or stock-backup version mismatches.
`v0.1.1` is an important maintenance release of the WTOffline Launcher that fixes startup failures on standalone/official-launcher clients, fixes cross-unit battle damage notices, improves launch reliability, and strengthens crash diagnostics.
### Fixes and improvements
- **Skip startup package validation and block official launcher spawns.** Added `-skip_pkg_validation` to offline launch arguments so `aces.exe` skips the startup `content/warthunder.blk` file-size integrity check, and added an executable isolation patch that blocks `aces.exe` from spawning the official `launcher.exe -fullcheck` updater. This eliminates the loop where the game exits with code `1`, opens the official launcher, and overwrites offline files back to the online build.
- **In-battle damage notices and enemy parts feedback.** Fixed AI avionics, sensor, radar, RWR/countermeasures, and targeting-pod failures in air and modern ground battles incorrectly showing white damage notices (or forcing the player out of optic view). Filtered non-local AI-on-AI hits out of the ground/naval enemy damaged-parts list and special hit-camera events while preserving in-flight player munitions and spectator views.
- **Launch and file-write reliability.** Rebuilt game files are now written via temporary files with atomic rename and brief retry on transient antivirus locks. Batched MinHook activation in `wto_ws.dll` into two passes to cut startup thread-freeze cycles and log detailed `MH_STATUS` diagnostics on failure.
- **Stock backup detection and errors.** Fixed stale `wtoffline\stock` backups masking an externally updated client and blocking backup refresh. Launch checks now distinguish missing/unreadable backups from version mismatches and log the exact copy and backup versions.
- **Pre-launch checks and richer diagnostics.** Verify core launch files before starting `aces.exe` (flagging possible antivirus quarantine early), log post-exit file snapshots and hex-annotated Windows exit codes, and include `wto_ws.log`, the latest `.clog`, and a metadata summary (without player saves) in exported diagnostic ZIPs.
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
+27
View File
@@ -0,0 +1,27 @@
## 简体中文
`v0.1.2` 是 WTOffline 启动器的维护更新,重点放开「节省空间的复制」对游戏版本的硬锁定、修复维护页更新客户端时的路径校验误报,并内置 `2.61.0.58` 版本核对记录。
### 修复与改进
- **省空间复制改为跨版本规则。** 取消原先绑定单一版本号(`2.61.0.43`)与 8 MiB 体积门槛的静态哈希清单,改为基于只读资源规则自动共用 `content/` 与 `content.hq/` 下的 `.dxp.bin` 和 `.grp` 资源包;小版本更新后无需等待新清单即可继续省空间安装或转换,且同卷省空间客户端执行「从在线版更新」时会保持或重建硬链接,不再拆分为完整复制。
- **修复维护页「从在线版更新」误报路径越界。** 扫描安装来源时排除顶层残留的 `wtoffline` 目录;安装向导第 3 步与后台同步拦截将数据目录设为客户端目录或其父目录的配置,并解除旧安装把数据目录放在客户端父目录时的误报;所有路径安全校验失败均在启动器日志中记录具体原因与路径以便排查。
- **「关于」页快速导出日志与关闭日志开关。** 在「关于」页新增「保存日志 ZIP…」快捷按钮(导出内容同时纳入最新一份内置浏览器 `-browser.log`,仍不含玩家存档),并在「设置 → 诊断」新增「生成运行日志」开关,允许关闭启动器日志、本地服务器流量日志及 `wto_ws.log` 的磁盘写入。
### 客户端兼容性
支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
## English
`v0.1.2` is a maintenance release of the WTOffline Launcher that makes space-saving copies resilient across minor game updates, fixes false path-scope errors during client updates, and bundles the `2.61.0.58` version check record.
### Fixes and improvements
- **Version-independent space-saving copies.** Replaced the single-version (`2.61.0.43`) SHA-256 manifest and 8 MiB cutoff with declarative read-only asset rules covering `.dxp.bin` and `.grp` archives under `content/` and `content.hq/`. Space-saving installs and conversions now keep working across minor updates, and updating a same-volume space-saving client preserves or recreates hard links instead of detaching them into full copies.
- **Fix false `maintenance_location` errors when updating.** Ignore stray top-level `wtoffline` folders when scanning a stock source, prevent picking a data folder that equals or contains the client folder during installation (with inline Step 3 validation), stop blocking updates when an existing installation placed `dataPath` at an ancestor of the client folder, and log the exact reason and paths on every path-scope rejection.
- **Quick log ZIP export on About and runtime logging toggle.** Added a quick "Save log ZIP…" button on the About page (now also bundling the latest embedded browser `-browser.log`, still excluding saves), and added a "Record runtime logs" toggle under Settings → Diagnostics to stop writing launcher logs, local server traffic logs, and `wto_ws.log`.
### Client compatibility
Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
+8 -4
View File
@@ -1,7 +1,8 @@
# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release
# tagged v<version>. The launcher's update check reads v<version> releases and expects all three
# files (installer, manifest, signature); a release missing any of them breaks the check for
# already-installed launchers.
# tagged v<version>. The launcher's update check reads v<version> releases and expects the three
# signed files (installer, manifest, signature); a release missing any of them breaks the check
# for already-installed launchers. The workflow also packages and signs the portable zip with its
# own manifest and signature so portable installations can update in place.
#
# Start it either way:
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
@@ -67,7 +68,7 @@ jobs:
npm run typecheck
npm run typecheck --workspace "@wto/launcher"
- name: Build and package the Windows installer
- name: Build and package the Windows installer and portable archive
run: npm --workspace "@wto/launcher" run package:win
- name: Sign the release
@@ -87,6 +88,9 @@ jobs:
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.exe" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json.sig" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.zip" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json" \
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json.sig" \
"${flags[@]}" \
--title "WTOffline Launcher $VERSION" \
--notes-file ".github/release-notes/v$VERSION.md" \
+16 -6
View File
@@ -2,7 +2,7 @@
<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 模块按特征码、字符串引用和从代码中读出的值定位,不依赖固定地址,小版本更新后通常仍能命中,但没有核对记录的版本不保证功能正确。
## 开发讨论、交流与求助
欢迎加入 [WTOffline Discord 服务器](https://discord.gg/P566xWNpEs),用于日常交流、使用求助、问题反馈、调参分享以及开发和版本适配讨论。
## 功能
| 领域 | 已实现 |
@@ -73,7 +77,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
- **服务地址**:`config/network.blk`(`char.vromfs.bin`)和 `config/settings.blk`(`aces.vromfs.bin`)中所有 Gaijin 地址改写为 `127.0.0.1:<端口>`。端口在构建时写入,因此服务器必须使用相同的端口。
- **配置表**:开启离线需要的功能开关,放出隐藏载具,写入贴花索引,为本地商店的礼包登记 GUID。
- **exe 补丁**:`patches/exe/` 下共 12 项,见下表。
- **exe 补丁**:`patches/exe/` 下共 13 项,见下表。
- **界面脚本补丁**:`patches/gui/` 下共 40 项,用于本地账号注册、本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
- **网络钩子库**:exe 的导入表把 `WS2_32.dll` 改为同长度的 `wto_ws.dll`。该库转发系统 `ws2_32.dll` 的全部导出,并用 MinHook 挂钩域名解析(`getaddrinfo` 等)、连接(`connect`、`ConnectEx` 等)和 UDP 发送,把所有外部连接重定向到本地服务器端口。端口从 exe 旁的 `wto_ws.cfg` 读取。
@@ -84,6 +88,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
| `isolation/registry-key` | 注册表位置改为 `Software\WTOffline` |
| `isolation/never-load-battleye` | 不加载 BattlEye |
| `isolation/never-upload-crash-reports` | 不上传崩溃报告 |
| `isolation/never-launch-official-launcher` | 不拉起官方启动器 `launcher.exe` |
| `online/network-hook-library` | 加载 `wto_ws.dll` 代替 `WS2_32.dll` |
| `online/accept-local-tls-certificate` | 让 libcurl 接受本地服务器的自签名证书 |
| `online/matching-server-public-key` | 匹配服务器公钥替换为本地服务器的公钥,用于解出会话密钥 |
@@ -150,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)。
### 环境要求
@@ -264,7 +269,7 @@ tools/ wtotools,补丁检查工具(Python)
# 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.
@@ -281,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.
## Community
Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general discussion, troubleshooting, bug reports, and development or patch adaptation discussions.
## Features
| Area | Implemented |
@@ -333,7 +342,7 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
- **Service addresses**: every Gaijin address in `config/network.blk` (`char.vromfs.bin`) and `config/settings.blk` (`aces.vromfs.bin`) is rewritten to `127.0.0.1:<port>`. The port is written at build time, so the server must use the same port.
- **Config tables**: enables feature flags the offline copy needs, reveals hidden vehicles, adds a decal index, and registers GUIDs for local store packs.
- **exe patches**: 12 patches under `patches/exe/`, listed below.
- **exe patches**: 13 patches under `patches/exe/`, listed below.
- **UI script patches**: 40 patches under `patches/gui/`, covering local account registration, battle start and settlement, store purchase receipts, and the inventory signing key.
- **Network hook library**: the import table entry `WS2_32.dll` is renamed to `wto_ws.dll`, which has the same length. The library forwards every export of the system `ws2_32.dll` and uses MinHook to hook name resolution (`getaddrinfo` and others), connections (`connect`, `ConnectEx`, and others), and UDP sends, redirecting every external connection to the local server port. The port is read from `wto_ws.cfg` next to the exe.
@@ -344,6 +353,7 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
| `isolation/registry-key` | Moves registry settings to `Software\WTOffline` |
| `isolation/never-load-battleye` | Never loads BattlEye |
| `isolation/never-upload-crash-reports` | Never uploads crash reports |
| `isolation/never-launch-official-launcher` | Never launches the official `launcher.exe` |
| `online/network-hook-library` | Loads `wto_ws.dll` instead of `WS2_32.dll` |
| `online/accept-local-tls-certificate` | Makes libcurl accept the local server's self-signed certificate |
| `online/matching-server-public-key` | Replaces the matching server public key with the local server's, so it can decrypt the session key |
@@ -410,7 +420,7 @@ To override defaults, create `tuning/<same file name>.jsonc` in the data folder
## 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
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@wto/launcher",
"productName": "WTOffline Launcher",
"version": "0.1.0",
"version": "0.1.2",
"private": true,
"description": "Installer and launcher of the War Thunder offline project.",
"type": "module",
+17 -7
View File
@@ -5,14 +5,14 @@ import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdat
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.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 { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectPickedTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts';
import { cancelInstall, checkGameFolder, 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 { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
@@ -66,14 +66,23 @@ export function registerIpcHandlers(): void {
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
handle('install:inspectTargetFolder', ({ path, stockPath, version }) =>
inspectPickedTargetFolder(path, stockPath, version ?? null));
handle('install:inspectDataFolder', async ({ path }) => {
const resolved = await canonicalCopyPath(path);
return { path: resolved, inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved) };
handle('install:inspectDataFolder', async ({ path, copyPath, sourcePath, stockSourcePath }) => {
const [resolved, resolvedCopy, resolvedSource, resolvedStock] = await Promise.all([
canonicalCopyPath(path),
copyPath ? canonicalCopyPath(copyPath) : Promise.resolve(null),
sourcePath ? canonicalCopyPath(sourcePath) : Promise.resolve(null),
stockSourcePath ? canonicalCopyPath(stockSourcePath) : Promise.resolve(null),
]);
return {
path: resolved,
inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved),
problem: dataFolderProblem(resolved, resolvedCopy, resolvedSource, resolvedStock),
};
});
handle('install:measureFolder', async ({ path, version }) => {
handle('install:measureFolder', async ({ path }) => {
await requireFolder(path);
try {
return await measureFolder(path, version);
return await measureFolder(path);
} catch (error) {
console.warn('[install] measuring the folder failed:', error);
throw new AppError('folder_unreadable', { path });
@@ -126,6 +135,7 @@ export function registerIpcHandlers(): void {
return updated;
});
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
handle('copies:maintenanceState', () => maintenanceState());
handle('copies:maintain', async (request) => {
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
@@ -11,6 +11,7 @@ import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuni
import { AppError } from '@shared/errors.ts';
import {
LauncherReleaseManifest,
PortableReleaseManifest,
type AppUpdateCheck, type AppUpdateProgress,
} from '@shared/schemas/app-update.ts';
import { gameProcessRunning } from '../launch/game-process.ts';
@@ -20,11 +21,15 @@ import {
import {
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
} from '../patch-pack/release-assets.ts';
import { installerDigest, launcherSignaturePayload } from './installer-integrity.ts';
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
type UpdateMode = 'installer' | 'portable';
interface OfferedUpdate {
readonly mode: UpdateMode;
readonly release: LauncherRelease;
readonly manifest: LauncherReleaseManifest;
readonly manifest: LauncherReleaseManifest | PortableReleaseManifest;
}
class ManifestSignatureError extends Error {}
@@ -46,11 +51,15 @@ async function exclusively<T>(action: () => Promise<T>): Promise<T> {
}
}
function stagedInstaller(): string {
return join(app.getPath('userData'), 'launcher-updates', 'installer.exe');
function updatesRoot(): string {
return join(app.getPath('userData'), 'launcher-updates');
}
async function matchesInstaller(path: string, manifest: LauncherReleaseManifest): Promise<boolean> {
function stagedArtifact(mode: UpdateMode): string {
return join(updatesRoot(), mode === 'portable' ? 'portable.zip' : 'installer.exe');
}
async function matchesArtifact(path: string, manifest: LauncherReleaseManifest | PortableReleaseManifest): Promise<boolean> {
try {
const digest = await installerDigest(path, manifest.size);
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
@@ -76,6 +85,18 @@ function selectedOffer(version: string): OfferedUpdate {
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
if (isPortableLauncher(app.isPackaged) && release.portable) {
const [bytes, signature] = await Promise.all([
readReleaseAsset(release.portable.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
readReleaseAsset(release.portable.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
]);
if (!verifyEd25519(portableSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
throw new ManifestSignatureError('The portable release manifest signature does not match.');
}
const manifest = PortableReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
if (manifest.version !== release.version) throw new Error('The signed portable manifest version does not match the release tag.');
return { mode: 'portable', release, manifest };
}
const [bytes, signature] = await Promise.all([
readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
@@ -85,7 +106,7 @@ async function signedOffer(release: LauncherRelease, key: string): Promise<Offer
}
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.');
return { release, manifest };
return { mode: 'installer', release, manifest };
}
export function checkAppUpdate(): Promise<AppUpdateCheck> {
@@ -102,7 +123,7 @@ export function checkAppUpdate(): Promise<AppUpdateCheck> {
});
if (!offer) return { status: 'current' };
offered = offer;
return offerResult(offer, await matchesInstaller(stagedInstaller(), offer.manifest));
return offerResult(offer, await matchesArtifact(stagedArtifact(offer.mode), offer.manifest));
} catch (error) {
console.warn('[app-update] checking the release failed:', error);
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
@@ -121,24 +142,26 @@ export function downloadAppUpdate(
): Promise<AppUpdateCheck> {
return exclusively(async () => {
const offer = selectedOffer(version);
const target = stagedInstaller();
if (await matchesInstaller(target, offer.manifest)) return offerResult(offer, true);
const target = stagedArtifact(offer.mode);
if (await matchesArtifact(target, offer.manifest)) return offerResult(offer, true);
try {
await withReleaseSources(async (source) => {
const release = sameReleaseSource(source, offer.release.source)
? offer.release : await projectReleaseVersion('launcher', version, source);
await stageInstaller(release, offer.manifest, target, report);
const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer;
if (!assetUrl) throw new FeedUnreachableError(`This update source does not have the ${offer.mode} asset for ${version}.`);
await stageArtifact(assetUrl, release.source, offer.manifest, target, report);
}, offer.release.source);
return offerResult(offer, true);
} catch (error) {
console.warn('[app-update] preparing the installer failed:', error);
console.warn('[app-update] preparing the update asset failed:', error);
throw new AppError('app_update_download_failed');
}
});
}
async function stageInstaller(
release: LauncherRelease, manifest: LauncherReleaseManifest, target: string,
async function stageArtifact(
assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string,
report: (progress: AppUpdateProgress) => void,
): Promise<void> {
const partial = `${target}.partial`;
@@ -151,12 +174,12 @@ async function stageInstaller(
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
});
const response = await requestReleaseAsset(release.installer, deadline, release.source);
const response = await requestReleaseAsset(assetUrl, deadline, source);
const monitor = new Transform({
transform(chunk: Buffer, _encoding, done) {
size += chunk.length;
if (size > manifest.size) {
done(new Error('The download is larger than the signed installer size.'));
done(new Error('The download is larger than the signed release size.'));
return;
}
hash.update(chunk);
@@ -168,11 +191,11 @@ async function stageInstaller(
},
});
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
if (size !== manifest.size) throw new FeedUnreachableError('The installer download is incomplete.');
if (hash.digest('hex') !== manifest.sha256) throw new Error('The installer download does not match the signed release.');
if (size !== manifest.size) throw new FeedUnreachableError('The update download is incomplete.');
if (hash.digest('hex') !== manifest.sha256) throw new Error('The update download does not match the signed release.');
await rename(partial, target);
} catch (error) {
if (deadline.aborted) throw new FeedUnreachableError('The installer download timed out.', { cause: error });
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
throw error;
} finally {
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
@@ -185,17 +208,23 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
return exclusively(async () => {
const offer = selectedOffer(version);
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
const path = stagedInstaller();
if (!await matchesInstaller(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
const path = stagedArtifact(offer.mode);
if (!await matchesArtifact(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
const signal = AbortSignal.timeout(5000);
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
try {
if (offer.mode === 'portable') {
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
launchPortableUpdater(prepared);
app.quit();
return;
}
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
await once(installer, 'spawn');
installer.unref();
app.quit();
} catch (error) {
console.warn('[app-update] starting the installer failed:', error);
console.warn('[app-update] starting the update failed:', error);
throw new AppError('app_update_install_failed');
}
});
@@ -3,11 +3,16 @@ import { createReadStream } from 'node:fs';
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
const PORTABLE_SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher portable release v1\n', 'utf8');
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
}
export function portableSignaturePayload(manifest: Uint8Array): Uint8Array {
return Buffer.concat([PORTABLE_SIGNATURE_DOMAIN, manifest]);
}
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
const hash = createHash('sha256');
let size = 0;
@@ -0,0 +1,283 @@
/**
* In-place updater for portable (unpacked ZIP) launcher builds on Windows.
*
* Extraction and path validation happen while the launcher is still running so a bad archive or
* read-only folder fails cleanly before quitting. Once staged, a detached PowerShell helper waits
* for this process to exit, overwrites only files listed in the new portable inventory, removes
* only obsolete files listed in the previous portable inventory (never touching unrelated user
* files in the same folder), and restarts the updated executable.
*/
import { execFile, spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { existsSync } from 'node:fs';
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { promisify } from 'node:util';
import { z } from 'zod';
const execute = promisify(execFile);
export const PORTABLE_MARKER_FILE = 'portable-mode';
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
const PortableInventorySchema = z.object({
format: z.literal(1),
version: z.string().min(1),
files: z.array(z.string().min(1)).min(1),
});
export interface PreparedPortableUpdate {
readonly scriptPath: string;
readonly planPath: string;
readonly stagingDir: string;
}
export interface PortableUpdatePlan {
readonly pid: number;
readonly installDir: string;
readonly stagingDir: string;
readonly archivePath: string;
readonly logPath: string;
readonly executable: string;
readonly newFiles: readonly string[];
readonly staleFiles: readonly string[];
}
export function isPortableLauncher(isPackaged: boolean): boolean {
if (!isPackaged || process.platform !== 'win32') return false;
if (existsSync(join(process.resourcesPath, PORTABLE_MARKER_FILE))) return true;
return !existsSync(join(dirname(process.execPath), UNINSTALLER_EXECUTABLE));
}
/** Validate a POSIX-style relative path from a portable inventory against traversal or drive prefixes. */
export function isSafePortableRelativePath(entry: string): boolean {
if (!entry || entry.includes('\\') || entry.includes(':') || entry.startsWith('/')) return false;
if (/[\0-\x1f]/.test(entry)) return false;
const parts = entry.split('/');
return parts.every((part) => part.length > 0 && part !== '.' && part !== '..');
}
function resolveInside(root: string, relPosix: string): string {
if (!isSafePortableRelativePath(relPosix)) throw new Error(`Unsafe portable path: ${relPosix}`);
const target = resolve(root, ...relPosix.split('/'));
const rel = relative(root, target);
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
throw new Error(`Portable path escapes root: ${relPosix}`);
}
return target;
}
async function readPortableInventory(resourcesDir: string): Promise<readonly string[] | null> {
try {
const raw = await readFile(join(resourcesDir, PORTABLE_FILES_MANIFEST), 'utf8');
const parsed = PortableInventorySchema.parse(JSON.parse(raw));
return parsed.files.filter(isSafePortableRelativePath);
} catch {
return null;
}
}
async function assertWritableFolder(folder: string): Promise<void> {
const probe = join(folder, `.wto-update-probe-${randomUUID()}.tmp`);
await writeFile(probe, '', { flag: 'wx' });
await rm(probe, { force: true });
}
async function extractPortableArchive(zipPath: string, stagingDir: string, updatesRoot: string): Promise<void> {
const extractScriptPath = join(updatesRoot, `extract-portable-${randomUUID()}.ps1`);
const script = [
'param([string]$ZipPath, [string]$DestDir)',
"$ErrorActionPreference = 'Stop'",
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
'$destFull = [System.IO.Path]::GetFullPath($DestDir)',
'if (-not $destFull.EndsWith([System.IO.Path]::DirectorySeparatorChar)) { $destFull += [System.IO.Path]::DirectorySeparatorChar }',
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
'try {',
' foreach ($entry in $zip.Entries) {',
' $name = $entry.FullName',
' if ([string]::IsNullOrEmpty($name) -or $name.EndsWith("/") -or $name.EndsWith("\\")) { continue }',
' if ($name.Contains("..") -or $name.StartsWith("/") -or $name.StartsWith("\\") -or $name.Contains(":")) {',
' throw "Unsafe zip entry: $name"',
' }',
' $target = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($destFull, $name))',
' if (-not $target.StartsWith($destFull, [System.StringComparison]::OrdinalIgnoreCase)) {',
' throw "Zip entry escapes destination: $name"',
' }',
' $parent = [System.IO.Path]::GetDirectoryName($target)',
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)',
' }',
'} finally {',
' $zip.Dispose()',
'}',
].join('\r\n');
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
await writeFile(extractScriptPath, `\uFEFF${script}\r\n`, 'utf8');
try {
await execute('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', extractScriptPath, zipPath, stagingDir,
], { windowsHide: true, timeout: 180_000 });
} finally {
await rm(extractScriptPath, { force: true }).catch(() => undefined);
}
}
export function buildPortableApplyScript(): string {
return [
'param([string]$PlanPath)',
"$ErrorActionPreference = 'Stop'",
'$utf8 = New-Object System.Text.UTF8Encoding($false)',
'$plan = [System.IO.File]::ReadAllText($PlanPath, $utf8) | ConvertFrom-Json',
'function Write-Log([string]$msg) {',
' try {',
' $line = "$(Get-Date -Format o) $msg`r`n"',
' [System.IO.File]::AppendAllText($plan.logPath, $line, $utf8)',
' } catch {}',
'}',
'try {',
' Write-Log "Starting portable update in $($plan.installDir) (waiting for pid $($plan.pid))"',
' $deadline = (Get-Date).AddSeconds(30)',
' while ((Get-Date) -lt $deadline) {',
' if (-not (Get-Process -Id $plan.pid -ErrorAction SilentlyContinue)) { break }',
' Start-Sleep -Milliseconds 200',
' }',
' Start-Sleep -Milliseconds 400',
' foreach ($rel in $plan.newFiles) {',
' $winRel = $rel -replace "/", "\\"',
' $src = [System.IO.Path]::Combine($plan.stagingDir, $winRel)',
' $dst = [System.IO.Path]::Combine($plan.installDir, $winRel)',
' $parent = [System.IO.Path]::GetDirectoryName($dst)',
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
' $copied = $false',
' for ($attempt = 1; $attempt -le 20; $attempt++) {',
' try {',
' if ([System.IO.File]::Exists($dst)) { [System.IO.File]::SetAttributes($dst, [System.IO.FileAttributes]::Normal) }',
' [System.IO.File]::Copy($src, $dst, $true)',
' $copied = $true',
' break',
' } catch {',
' if ($attempt -eq 20) { throw }',
' Start-Sleep -Milliseconds 300',
' }',
' }',
' if (-not $copied) { throw "Failed to copy $rel" }',
' }',
' $installRoot = [System.IO.Path]::GetFullPath($plan.installDir).TrimEnd("\\")',
' foreach ($rel in $plan.staleFiles) {',
' $winRel = $rel -replace "/", "\\"',
' $old = [System.IO.Path]::Combine($plan.installDir, $winRel)',
' if ([System.IO.File]::Exists($old)) {',
' try {',
' [System.IO.File]::SetAttributes($old, [System.IO.FileAttributes]::Normal)',
' [System.IO.File]::Delete($old)',
' } catch { Write-Log "Could not remove stale file ${rel}: $_" }',
' }',
' $dir = [System.IO.Path]::GetDirectoryName($old)',
' while ($dir -and ($dir.TrimEnd("\\") -ne $installRoot)) {',
' if (-not [System.IO.Directory]::Exists($dir)) { break }',
' $entries = [System.IO.Directory]::GetFileSystemEntries($dir)',
' if ($entries.Length -gt 0) { break }',
' try { [System.IO.Directory]::Delete($dir) } catch { break }',
' $dir = [System.IO.Path]::GetDirectoryName($dir)',
' }',
' }',
' Write-Log "Replaced $($plan.newFiles.Count) files and cleaned $($plan.staleFiles.Count) obsolete files."',
' if ($plan.stagingDir -and [System.IO.Directory]::Exists($plan.stagingDir)) {',
' try { Remove-Item -LiteralPath $plan.stagingDir -Recurse -Force } catch {}',
' }',
' if ($plan.archivePath -and [System.IO.File]::Exists($plan.archivePath)) {',
' try { Remove-Item -LiteralPath $plan.archivePath -Force } catch {}',
' }',
' if ([System.IO.File]::Exists($PlanPath)) {',
' try { Remove-Item -LiteralPath $PlanPath -Force } catch {}',
' }',
' $exe = [System.IO.Path]::Combine($plan.installDir, $plan.executable)',
' if ([System.IO.File]::Exists($exe)) {',
' Start-Process -FilePath $exe -WorkingDirectory $plan.installDir',
' Write-Log "Relaunched $exe"',
' }',
'} catch {',
' Write-Log "Portable update failed: $_"',
' exit 1',
'}',
].join('\r\n');
}
export async function preparePortableInstall(
archivePath: string,
expectedVersion: string,
updatesRoot: string,
installDir = dirname(process.execPath),
resourcesDir = process.resourcesPath,
parentPid = process.pid,
): Promise<PreparedPortableUpdate> {
await assertWritableFolder(installDir);
await mkdir(updatesRoot, { recursive: true });
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
await mkdir(stagingDir, { recursive: true });
try {
await extractPortableArchive(archivePath, stagingDir, updatesRoot);
const stagedInventoryRaw = await readFile(join(stagingDir, 'resources', PORTABLE_FILES_MANIFEST), 'utf8');
const stagedInventory = PortableInventorySchema.parse(JSON.parse(stagedInventoryRaw));
if (stagedInventory.version !== expectedVersion) {
throw new Error(`Portable archive inventory version ${stagedInventory.version} does not match ${expectedVersion}.`);
}
const newFiles = stagedInventory.files;
const newSet = new Set(newFiles);
const requiredEntries = [
LAUNCHER_EXECUTABLE,
`resources/${PORTABLE_MARKER_FILE}`,
`resources/${PORTABLE_FILES_MANIFEST}`,
];
for (const required of requiredEntries) {
if (!newSet.has(required)) throw new Error(`Portable archive inventory is missing ${required}.`);
}
for (const rel of newFiles) {
const stagedPath = resolveInside(stagingDir, rel);
const stats = await lstat(stagedPath);
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
}
const oldFiles = await readPortableInventory(resourcesDir);
const staleFiles = oldFiles
? oldFiles.filter((rel) => !newSet.has(rel) && isSafePortableRelativePath(rel))
: [];
const planPath = join(updatesRoot, `portable-plan-${randomUUID()}.json`);
const scriptPath = join(updatesRoot, 'apply-portable-update.ps1');
const plan: PortableUpdatePlan = {
pid: parentPid,
installDir: resolve(installDir),
stagingDir,
archivePath,
logPath: join(updatesRoot, 'portable-update.log'),
executable: LAUNCHER_EXECUTABLE,
newFiles,
staleFiles,
};
await writeFile(planPath, `${JSON.stringify(plan, null, 2)}\n`, 'utf8');
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
return { scriptPath, planPath, stagingDir };
} catch (error) {
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
throw error;
}
}
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
const child = spawn('powershell.exe', [
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
'-File', prepared.scriptPath, prepared.planPath,
], {
cwd: dirname(prepared.scriptPath),
detached: true,
stdio: 'ignore',
windowsHide: true,
shell: false,
});
child.unref();
}
@@ -4,6 +4,7 @@ import { app } from 'electron';
import { AppError } from '@shared/errors.ts';
import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts';
/**
* The launcher's settings file, `<user data>/settings.json`. Read once and cached; every change is
@@ -47,6 +48,7 @@ export function updateSettings(patch: SettingsPatch): Promise<Settings> {
throw new AppError('settings_write_failed');
}
cached = merged;
setLauncherLoggingEnabled(merged.loggingEnabled);
return merged;
});
pending = operation.then(() => undefined, () => undefined);
@@ -1,14 +1,22 @@
import type { BigIntStats } from 'node:fs';
import { copyFile, lstat, mkdir } from 'node:fs/promises';
import { dirname, join, normalize } from 'node:path';
import { compareVersions, GAME_FILES } from '@wto/patcher';
import { dirname, join, normalize, relative, sep } from 'node:path';
import { compareVersions, GAME_FILES, isHardlinkableResource } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts';
import {
fileHash,
linkVerifiedResource,
sameInode,
sameResource,
statFile,
statHardlinkResource,
verifyMatchingResource,
} from '../install/hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
@@ -40,6 +48,14 @@ export async function repair(record: InstallRecord, root: string, applying: () =
}, listCopies);
}
export async function updatePreservesSpaceSaving(
record: InstallRecord,
source: GameFolderInspection,
root: string,
): Promise<boolean> {
return (record.hardlinkedFiles?.length ?? 0) > 0 && await canShareVolume(source.path, root);
}
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const game = await readSource(record);
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
@@ -50,8 +66,11 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
const found = new Set(inventory.map(key));
const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key));
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
const copy = await planChangedFiles(game.path, root, dataPath, plan, linkedPaths, signal);
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
);
for (const file of remove) await scopedInstallFile(dataPath, root, file);
signal.throwIfAborted();
@@ -66,43 +85,86 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
report('copying', doneBytes, copy.totalBytes);
}
});
const stagedLinks = new Map<string, BigIntStats>();
for (const [relativePath, sourceStamp] of linksToStage) {
signal.throwIfAborted();
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const linkedStamp = await linkVerifiedResource(join(game.path, relativePath), staged, sourceStamp);
stagedLinks.set(staged, linkedStamp);
}
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
signal.throwIfAborted();
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
}
await verifySourceFiles(game.path, plan, signal);
if (stagedLinks.size > 0) await verifyStagedLinks(record, game.version, stagedLinks, signal);
signal.throwIfAborted();
report('applying', copy.totalBytes, copy.totalBytes);
return { replace: [...copy.files.map(({ relativePath }) => relativePath), ...stockFiles], remove };
return {
replace: [...copy.files.map(({ relativePath }) => relativePath), ...linksToStage.keys(), ...stockFiles],
remove,
};
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(linked.length ? { hardlinkedFiles: [] } : {}),
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
})));
}
async function planChangedFiles(
source: string, root: string, dataPath: string, plan: CopyPlan, linked: ReadonlySet<string>, signal: AbortSignal,
): Promise<CopyPlan> {
interface UpdateFilePlan {
readonly copy: CopyPlan;
readonly linksToStage: ReadonlyMap<string, BigIntStats>;
readonly hardlinkedFiles: string[];
}
async function planUpdateFiles(
source: string,
root: string,
dataPath: string,
plan: CopyPlan,
linked: ReadonlySet<string>,
preserveHardlinks: boolean,
signal: AbortSignal,
): Promise<UpdateFilePlan> {
const changed: CopyPlan['files'][number][] = [];
const linksToStage = new Map<string, BigIntStats>();
const hardlinkedFiles: string[] = [];
for (const file of plan.files) {
signal.throwIfAborted();
const target = await scopedInstallFile(dataPath, root, file.relativePath);
const old = await fileInfo(target);
if (linked.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) {
const sourceFile = join(source, file.relativePath);
const old = await statFile(target);
if (preserveHardlinks && isHardlinkableResource(file.relativePath, file.bytes)) {
const sourceStamp = await statHardlinkResource(sourceFile, file.bytes, signal);
if (!sourceStamp) throw new AppError('maintenance_source_changed');
if (!old || !sameResource(old, sourceStamp)) linksToStage.set(file.relativePath, sourceStamp);
hardlinkedFiles.push(file.relativePath);
continue;
}
const sourceStamp = await statFile(sourceFile);
if (!sourceStamp?.isFile() || sourceStamp.size !== BigInt(file.bytes)) {
throw new AppError('maintenance_source_changed');
}
if (linked.has(key(file.relativePath)) || !old?.isFile() || sameInode(old, sourceStamp) ||
old.size !== BigInt(file.bytes)) {
changed.push(file);
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
} else if (Math.trunc(Number(old.mtimeMs)) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
fileHash(target, signal), fileHash(join(source, file.relativePath), signal),
fileHash(target, signal), fileHash(sourceFile, signal),
]);
if (targetHash !== sourceHash) changed.push(file);
}
}
return {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
copy: {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
},
linksToStage,
hardlinkedFiles,
};
}
@@ -117,8 +179,8 @@ async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSi
}
export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
return record.method === 'copy' && source.version === record.gameVersion &&
hasHardlinkEvidence(source.version) && await sameVolume(source.path, root);
return record.method === 'copy' && source.version !== null &&
source.version === record.gameVersion && await canShareVolume(source.path, root);
}
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
@@ -129,11 +191,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
}
const plan = await planCopy(source.path);
const candidates = plan.files.flatMap(({ relativePath, bytes }) => {
const evidence = hardlinkResource(source.version, relativePath, bytes);
return evidence ? [{ relativePath, evidence }] : [];
});
const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0);
const candidates = plan.files.filter(({ relativePath, bytes }) => isHardlinkableResource(relativePath, bytes));
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
const dataPath = await canonicalCopyPath(record.dataPath);
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
return changeCopyFiles(root, async (incoming) => {
@@ -143,24 +202,24 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
let matches = 0;
let lastReport = 0;
report('checking', 0, total);
for (const { relativePath, evidence } of candidates) {
for (const { relativePath, bytes } of candidates) {
const target = await scopedInstallFile(dataPath, root, relativePath);
const original = join(source.path, relativePath);
const copyStamp = await verifyHardlinkResource(target, evidence, signal);
const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null;
if (copyStamp && sourceStamp) {
if (!sameResource(copyStamp, sourceStamp)) {
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp);
unchanged.set(target, copyStamp);
unchanged.set(staged, stagedStamp);
replacements.push(relativePath);
}
const match = await verifyMatchingResource(target, original, bytes, signal);
if (match.status === 'already-linked') {
linked.set(key(relativePath), relativePath);
matches += 1;
} else if (match.status === 'matched') {
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const stagedStamp = await linkVerifiedResource(original, staged, match.sourceStamp);
unchanged.set(target, match.copyStamp);
unchanged.set(staged, stagedStamp);
replacements.push(relativePath);
linked.set(key(relativePath), relativePath);
matches += 1;
}
checked += evidence.bytes;
checked += bytes;
if (checked === total || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('checking', checked, total);
@@ -175,6 +234,10 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
}
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
return await sameVolume(sourcePath, root) && await sameVolume(sourcePath, dirname(root));
}
async function verifyStagedLinks(
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
): Promise<void> {
@@ -191,11 +254,32 @@ function key(path: string): string {
return process.platform === 'win32' ? name.toLowerCase() : name;
}
const OFFLINE_DATA_ENTRIES = new Set(['accounts.json', 'saves', 'tuning', 'logs', 'asset-pack', 'decals', 'cache']);
function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
const target = await stagedPath(root, name);
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
copyPathContains(dataPath, target)) {
throw new AppError('maintenance_location');
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target)) {
failLocation('target_inside_wtoffline', { root, target, name });
}
// Protect the data folder when it is nested inside the client folder. If an older installation
// placed dataPath at an ancestor of the client folder, files inside the client folder do not
// overlap data files stored at the ancestor root.
if (copyPathContains(root, dataPath)) {
if (relative(root, dataPath) !== '') {
if (copyPathContains(dataPath, target)) {
failLocation('target_inside_nested_data_folder', { root, dataPath, target, name });
}
} else {
const topSegment = normalize(name).split(sep)[0]?.toLowerCase() ?? '';
if (OFFLINE_DATA_ENTRIES.has(topSegment)) {
failLocation('target_collides_with_data_entry', { root, dataPath, target, name });
}
}
}
return target;
}
@@ -203,6 +287,8 @@ async function scopedInstallFile(dataPath: string, root: string, name: string):
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
await mkdir(dirname(target), { recursive: true });
const source = join(folder, file);
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
if (!(await fileInfo(source))?.isFile()) {
failLocation('stock_backup_source_missing', { folder, file, source });
}
await copyFile(source, target);
}
@@ -13,14 +13,22 @@ import { gameProcessRunning, launchInProgress } from '../launch/launch-controlle
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, type Report } from './copy-file-maintenance.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
let current: { stop: AbortController; interruptible: boolean } | null = null;
let current: {
stop: AbortController;
interruptible: boolean;
progress: MaintenanceProgress;
} | null = null;
export function maintenanceInProgress(): boolean {
return current !== null;
}
export function maintenanceState(): MaintenanceProgress | null {
return current ? { ...current.progress } : null;
}
export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort();
}
@@ -34,6 +42,7 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
return {
sourceVersion: source?.version ?? null,
updateAvailable: isNewer(source, record.gameVersion),
updatePreservesSpaceSaving: source !== null && await updatePreservesSpaceSaving(record, source, record.copyPath),
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
@@ -42,18 +51,28 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
export async function maintainCopy(
request: MaintenanceRequest,
publish: (progress: MaintenanceProgress) => void,
publish: (progress: MaintenanceProgress | null) => void,
): Promise<Copies> {
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 = {
stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact',
progress: initial,
};
current = job;
const signal = job.stop.signal;
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
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 {
@@ -66,6 +85,7 @@ export async function maintainCopy(
throw new AppError('maintenance_failed');
} finally {
current = null;
publish(null);
}
}
@@ -86,7 +106,7 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign
case 'confirm-steam':
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
throw new AppError('maintenance_location');
failLocation('steam_confirmation_mismatch', { root, dataPath, steamLocations });
}
if (!needsConfirmation) return listCopies();
return updateCopyRecord(id, (copy) => ({
@@ -112,13 +132,23 @@ async function requireCopy(id: string): Promise<InstallRecord> {
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);
if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location');
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)) throw new AppError('maintenance_location');
if (copyPathContains(source, root) || copyPathContains(root, source)) {
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
}
}
return root;
}
@@ -126,12 +156,15 @@ async function checkedRoot(record: InstallRecord): Promise<string> {
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, await canonicalCopyPath(app.getAppPath())) ||
copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) {
throw new AppError('maintenance_location');
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 });
}
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
return root;
}
@@ -150,7 +183,7 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
if (deleteData) throw new AppError('maintenance_location');
if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root });
return removeCopyRecord(record.id);
}
@@ -158,7 +191,7 @@ async function remove(record: InstallRecord, root: string, deleteData: boolean):
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
throw new AppError('maintenance_location');
failLocation('delete_data_overlaps_source_or_copy', { root, data, source });
}
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
@@ -175,7 +208,7 @@ async function removeExcept(folder: string, kept: string): Promise<void> {
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) throw new AppError('maintenance_location');
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
await removeExcept(path, kept);
} else {
await rm(path, { recursive: true, force: true });
@@ -2,7 +2,7 @@ import { AppError } from '@shared/errors.ts';
import type { Copies } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { hydrateCopiesStatus, relocateCopyRecord } from '../install/install-record.ts';
import { backUpStockFiles } from '../install/stock-backup.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup } from '../install/stock-backup.ts';
/**
* Re-point an existing registered client to its moved folder while keeping its id, name, saves,
@@ -12,7 +12,10 @@ export async function relocateCopy(id: string, newPath: string): Promise<Copies>
const game = await inspectGameFolder(newPath);
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path: newPath });
if (game.needsStockSource) throw new AppError('stock_source_invalid');
const stockBackupPath = await backUpStockFiles(game.resolvedPath);
const stock = await installStockSource(game.resolvedPath, game.version);
const stockBackupPath = stock.refresh
? await refreshStockBackup(game.resolvedPath)
: await backUpStockFiles(game.resolvedPath);
const updated = await relocateCopyRecord(id, {
copyPath: newPath,
stockBackupPath,
@@ -1,15 +1,31 @@
import { randomUUID } from 'node:crypto';
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { release } from 'node:os';
import { dirname, join } from 'node:path';
import { app, dialog, shell, type BrowserWindow } from 'electron';
import { zipSync } from 'fflate';
import { GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { getSettings } from '../config/settings-store.ts';
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
type ArchiveFiles = Record<string, Uint8Array>;
/** Bound individual client log files so a huge crash dump or session log cannot exhaust memory. */
const MAX_CLIENT_LOG_BYTES = 16 * 1024 * 1024;
/** Number of recent .game_logs entries listed in client-logs/summary.json. */
const RECENT_GAME_LOGS_LIMIT = 10;
const HOOK_LOG_FILENAME = 'wto_ws.log';
const HOOK_CONFIG_FILENAME = 'wto_ws.cfg';
interface ListedFile {
readonly name: string;
readonly size: number;
readonly modifiedAt: string;
}
export async function openLogsFolder(): Promise<void> {
const path = launcherLogFolder();
try {
@@ -45,6 +61,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
if (dataPath) await addServerLogs(files, dataPath);
if (record) await addClientLogs(files, record, settings.loggingEnabled);
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
try {
@@ -73,6 +90,173 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<voi
}
}
/**
* Include the hook library log, the latest game .clog and embedded browser log, and a small
* metadata summary for the active client so crashes and web-UI issues can be diagnosed without
* touching player saves.
*/
async function addClientLogs(files: ArchiveFiles, record: InstallRecord, loggingEnabled: boolean): Promise<void> {
const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable));
const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME);
const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME);
const gameLogsFolder = join(record.copyPath, '.game_logs');
const [hookLogStat, hookConfigStat] = await Promise.all([
readRegularFileStat(hookLogPath),
readRegularFileStat(hookConfigPath),
]);
let hookLogIncluded = false;
let hookLogOmittedReason: string | null = null;
if (hookLogStat) {
const added = await addBoundedClientFile(files, `client-logs/${HOOK_LOG_FILENAME}`, hookLogPath, hookLogStat.size);
hookLogIncluded = added.included;
hookLogOmittedReason = added.omittedReason;
}
const recentGameLogs: ListedFile[] = [];
let latestClog: ListedFile | null = null;
let latestClogIncluded = false;
let latestClogOmittedReason: string | null = null;
let latestBrowserLog: ListedFile | null = null;
let latestBrowserLogIncluded = false;
let latestBrowserLogOmittedReason: string | null = null;
const gameLogsDirStat = await safeStat(gameLogsFolder);
if (gameLogsDirStat?.isDirectory()) {
const entries = await safeReadDir(gameLogsFolder);
const inspected: Array<ListedFile & { readonly mtimeMs: number }> = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
const stats = await readRegularFileStat(join(gameLogsFolder, entry.name));
if (!stats) continue;
inspected.push({
name: entry.name,
size: stats.size,
modifiedAt: new Date(stats.mtimeMs).toISOString(),
mtimeMs: stats.mtimeMs,
});
}
inspected.sort((left, right) => right.mtimeMs - left.mtimeMs);
for (const item of inspected.slice(0, RECENT_GAME_LOGS_LIMIT)) {
recentGameLogs.push({ name: item.name, size: item.size, modifiedAt: item.modifiedAt });
}
const newestClog = inspected.find((item) => item.name.toLowerCase().endsWith('.clog')) ?? null;
if (newestClog) {
latestClog = { name: newestClog.name, size: newestClog.size, modifiedAt: newestClog.modifiedAt };
const added = await addBoundedClientFile(
files,
`client-logs/game-logs/${newestClog.name}`,
join(gameLogsFolder, newestClog.name),
newestClog.size,
);
latestClogIncluded = added.included;
latestClogOmittedReason = added.omittedReason;
}
const newestBrowserLog = inspected.find((item) => item.name.toLowerCase().endsWith('-browser.log')) ?? null;
if (newestBrowserLog) {
latestBrowserLog = {
name: newestBrowserLog.name,
size: newestBrowserLog.size,
modifiedAt: newestBrowserLog.modifiedAt,
};
const added = await addBoundedClientFile(
files,
`client-logs/game-logs/${newestBrowserLog.name}`,
join(gameLogsFolder, newestBrowserLog.name),
newestBrowserLog.size,
);
latestBrowserLogIncluded = added.included;
latestBrowserLogOmittedReason = added.omittedReason;
}
}
const summary = {
exportedAt: new Date().toISOString(),
launcherVersion: app.getVersion(),
loggingEnabled,
platform: process.platform,
arch: process.arch,
osRelease: release(),
copyId: record.id,
gameVersion: record.gameVersion,
hookConfig: hookConfigStat
? { present: true, size: hookConfigStat.size, modifiedAt: new Date(hookConfigStat.mtimeMs).toISOString() }
: { present: false },
hookLog: hookLogStat
? {
present: true,
size: hookLogStat.size,
modifiedAt: new Date(hookLogStat.mtimeMs).toISOString(),
included: hookLogIncluded,
...(hookLogOmittedReason ? { omittedReason: hookLogOmittedReason } : {}),
}
: { present: false },
gameLogsFolderPresent: gameLogsDirStat?.isDirectory() ?? false,
recentGameLogs,
latestClog: latestClog
? {
...latestClog,
included: latestClogIncluded,
...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}),
}
: null,
latestBrowserLog: latestBrowserLog
? {
...latestBrowserLog,
included: latestBrowserLogIncluded,
...(latestBrowserLogOmittedReason ? { omittedReason: latestBrowserLogOmittedReason } : {}),
}
: null,
};
files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`);
}
async function addBoundedClientFile(
files: ArchiveFiles,
entry: string,
path: string,
size: number,
): Promise<{ readonly included: boolean; readonly omittedReason: string | null }> {
if (size > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
try {
const bytes = await readFile(path);
if (bytes.byteLength > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
files[entry] = bytes;
return { included: true, omittedReason: null };
} catch (error) {
console.warn('[diagnostics] could not read client log:', path, error);
return { included: false, omittedReason: 'unreadable' };
}
}
async function readRegularFileStat(path: string) {
const stats = await safeStat(path);
return stats?.isFile() ? stats : null;
}
async function safeStat(path: string) {
try {
return await lstat(path);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('[diagnostics] could not inspect path:', path, error);
}
return null;
}
}
async function safeReadDir(path: string) {
try {
return await readdir(path, { withFileTypes: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn('[diagnostics] could not read folder:', path, error);
}
return [];
}
}
async function addFile(files: ArchiveFiles, entry: string, path: string): Promise<void> {
if (!(await ifPresent(() => lstat(path)))?.isFile()) return;
const bytes = await ifPresent(() => readFile(path));
@@ -1,5 +1,5 @@
import { Console } from 'node:console';
import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { Writable } from 'node:stream';
import { app } from 'electron';
@@ -12,13 +12,26 @@ export const LAUNCHER_LOG_FILES = [
'launcher.4.log',
] as const;
let loggingEnabled = true;
let activeLogPath: string | null = null;
let fileFailed = false;
let originalConsole = console;
export function launcherLogFolder(): string {
return join(app.getPath('userData'), 'logs');
}
/** Rotate after taking the single-instance lock and keep the original console destinations. */
export function startLauncherLogging(): void {
const originalConsole = console;
function readInitialLoggingEnabled(): boolean {
try {
const raw = JSON.parse(readFileSync(join(app.getPath('userData'), 'settings.json'), 'utf8')) as { loggingEnabled?: unknown };
return raw?.loggingEnabled !== false;
} catch {
return true;
}
}
function ensureLogFileReady(): boolean {
if (activeLogPath) return !fileFailed;
const folder = launcherLogFolder();
const active = join(folder, LAUNCHER_LOG_FILES[0]);
try {
@@ -28,17 +41,37 @@ export function startLauncherLogging(): void {
if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!));
}
writeFileSync(active, '', { flag: 'wx' });
activeLogPath = active;
fileFailed = false;
return true;
} catch (error) {
fileFailed = true;
originalConsole.error('[logs] opening the launcher log failed:', error);
return;
return false;
}
}
/** Enable or disable writing launcher console output to launcher.log at runtime. */
export function setLauncherLoggingEnabled(enabled: boolean): void {
loggingEnabled = enabled;
if (enabled && !activeLogPath && !fileFailed) {
if (ensureLogFileReady()) {
console.info(`WTOffline Launcher ${app.getVersion()} logging enabled.`);
}
}
}
/** Rotate after taking the single-instance lock and keep the original console destinations. */
export function startLauncherLogging(): void {
originalConsole = console;
loggingEnabled = readInitialLoggingEnabled();
if (loggingEnabled) ensureLogFileReady();
let fileFailed = false;
const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({
write(chunk: Buffer, _encoding, done) {
if (!fileFailed) {
if (loggingEnabled && activeLogPath && !fileFailed) {
try {
appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`);
} catch (error) {
fileFailed = true;
originalConsole.error('[logs] writing the launcher log failed:', error);
@@ -1,11 +1,11 @@
import { isHardlinkableResource } from '@wto/patcher';
import type { FolderSize } from '@shared/schemas/install.ts';
import { planCopy } from '../install/copy-game.ts';
import { hardlinkResource } from '../install/hardlink-files.ts';
/** Estimate the installation size and the bytes eligible for content verification. */
export async function measureFolder(root: string, version?: string | null): Promise<FolderSize> {
/** Estimate the installation size and the bytes eligible for space-saving hard links. */
export async function measureFolder(root: string): Promise<FolderSize> {
const plan = await planCopy(root);
const linkableBytes = plan.files.reduce((total, file) =>
total + (hardlinkResource(version, file.relativePath, file.bytes)?.bytes ?? 0), 0);
total + (isHardlinkableResource(file.relativePath, file.bytes) ? file.bytes : 0), 0);
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
}
@@ -23,28 +23,43 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
}
const stockRoot = join(resolved, STOCK_BACKUP_FOLDER);
let hasOfflineBackup = true;
let hasStockFiles = true;
for (const file of required) {
if (!(await exists(join(stockRoot, file)))) {
hasOfflineBackup = false;
hasStockFiles = false;
break;
}
}
const resources = resourcePaths();
const executablePath = hasOfflineBackup
? join(stockRoot, GAME_FILES.executable)
: join(resolved, GAME_FILES.executable);
const executableBytes = (!hasOfflineBackup && missingFiles.includes(GAME_FILES.executable))
const liveExeBytes = missingFiles.includes(GAME_FILES.executable)
? null
: await readBytes(executablePath);
const version = executableBytes ? readVersionFromBytes(executableBytes) : null;
: await readBytes(join(resolved, GAME_FILES.executable));
const liveVersion = liveExeBytes ? readVersionFromBytes(liveExeBytes) : null;
const backupExeBytes = hasStockFiles
? await readBytes(join(stockRoot, GAME_FILES.executable))
: null;
const backupVersion = backupExeBytes ? readVersionFromBytes(backupExeBytes) : null;
// Always report the live executable's version when readable so an externally updated client
// (for example, an in-place folder updated by the official launcher) is never masked by a stale
// wtoffline/stock backup.
const version = liveVersion ?? backupVersion;
const hasOfflineBackup = hasStockFiles && backupVersion !== null && (liveVersion === null || backupVersion === liveVersion);
const liveExePatched = liveExeBytes !== null && liveExeBytes.includes(PATCHED_EXE_MARKER);
let needsStockSource = false;
if (!hasOfflineBackup && missingFiles.length === 0) {
const exeDir = join(resolved, dirname(GAME_FILES.executable));
const hasMarkerFile = (await Promise.all(
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
)).some(Boolean);
needsStockSource = hasMarkerFile || (executableBytes !== null && executableBytes.includes(PATCHED_EXE_MARKER));
if (hasStockFiles && backupVersion !== null && liveVersion !== null && backupVersion !== liveVersion) {
// A stale stock backup only needs an external stock source if the live executable is already
// patched; an unpatched live executable can refresh wtoffline/stock directly during install.
needsStockSource = liveExePatched;
} else {
const exeDir = join(resolved, dirname(GAME_FILES.executable));
const hasMarkerFile = (await Promise.all(
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
)).some(Boolean);
needsStockSource = hasMarkerFile || liveExePatched;
}
}
return {
path,
@@ -18,6 +18,8 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
* game creates these folders again when it needs them.
*/
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
/** Top-level folders ignored when scanning a stock source, including any stray offline backup directory. */
const SKIPPED_SOURCE_FOLDERS = new Set([...PLAYER_DATA_FOLDERS, 'wtoffline']);
interface CopyEntry {
readonly relativePath: string;
@@ -46,7 +48,7 @@ export async function planCopy(source: string): Promise<CopyPlan> {
const folder = pending.pop()!;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (folder === source && PLAYER_DATA_FOLDERS.has(entry.name.toLowerCase())) continue;
if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue;
if (entry.isDirectory()) {
folders.push(relative(source, path));
pending.push(path);
@@ -1,7 +1,12 @@
import { randomUUID } from 'node:crypto';
import { cp, lstat, mkdir, realpath, rm } from 'node:fs/promises';
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 type { Copies } from '@shared/schemas/install.ts';
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
@@ -33,8 +38,13 @@ export async function importDecalCache(
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
): Promise<string> {
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
const source = await realpath(sourcePath).catch(() => null);
if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid');
const rawSource = await realpath(sourcePath).catch(() => null);
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);
if (copyPathContains(source, root) || copyPathContains(root, source)) {
@@ -56,7 +66,12 @@ export async function importDecalCache(
},
});
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;
} catch (error) {
await discardDecalCache(dataPath, id, steamDataConfirmed);
@@ -2,30 +2,11 @@ import { createHash } from 'node:crypto';
import { createReadStream, type BigIntStats } from 'node:fs';
import { link, lstat } from 'node:fs/promises';
import { AppError } from '@shared/errors.ts';
import evidence from './hardlink-resources-2.61.0.43.json' with { type: 'json' };
interface ResourceEvidence {
readonly bytes: number;
readonly sha256: string;
}
const resources: Readonly<Record<string, ResourceEvidence>> = evidence.files;
export function hasHardlinkEvidence(version: string | null | undefined): boolean {
return version === evidence.gameVersion;
}
/** Only an exact path and size from the sampled build can be offered as a candidate. */
export function hardlinkResource(
version: string | null | undefined,
relativePath: string,
bytes: number,
): ResourceEvidence | undefined {
if (!hasHardlinkEvidence(version)) return undefined;
const path = relativePath.replaceAll('\\', '/').toLowerCase();
const resource = Object.hasOwn(resources, path) ? resources[path] : undefined;
return resource?.bytes === bytes ? resource : undefined;
}
export type ResourceMatchResult =
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
| { readonly status: 'matched'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
| { readonly status: 'mismatch' };
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
const hash = createHash('sha256');
@@ -33,22 +14,56 @@ export async function fileHash(path: string, signal: AbortSignal): Promise<strin
return hash.digest('hex');
}
/** Read the measured bytes and retain the observed file identity until the link is created. */
export async function verifyHardlinkResource(
path: string,
resource: ResourceEvidence,
signal: AbortSignal,
): Promise<BigIntStats | null> {
signal.throwIfAborted();
const before = await lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
export async function statFile(path: string): Promise<BigIntStats | null> {
return lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return null;
throw error;
});
if (!before?.isFile() || before.size !== BigInt(resource.bytes)) return null;
const checksum = await fileHash(path, signal);
const after = await lstat(path, { bigint: true });
if (!sameResource(before, after)) throw new AppError('hardlink_file_changed');
return checksum === resource.sha256 ? after : null;
}
/** Capture the file identity of a stock asset right before hardlinking it. */
export async function statHardlinkResource(
path: string,
expectedBytes: number,
signal: AbortSignal,
): Promise<BigIntStats | null> {
signal.throwIfAborted();
const stats = await statFile(path);
if (!stats?.isFile() || stats.size !== BigInt(expectedBytes)) return null;
return stats;
}
/**
* Verify that an existing copy file and stock file have identical contents before replacing the
* copy file with a hard link. Already-linked pairs return immediately without re-hashing.
*/
export async function verifyMatchingResource(
copyPath: string,
sourcePath: string,
expectedBytes: number,
signal: AbortSignal,
): Promise<ResourceMatchResult> {
signal.throwIfAborted();
const [copyBefore, sourceBefore] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
const size = BigInt(expectedBytes);
if (!copyBefore?.isFile() || !sourceBefore?.isFile() || copyBefore.size !== size || sourceBefore.size !== size) {
return { status: 'mismatch' };
}
if (sameResource(copyBefore, sourceBefore)) {
return { status: 'already-linked', copyStamp: copyBefore, sourceStamp: sourceBefore };
}
const [copyHash, sourceHash] = await Promise.all([fileHash(copyPath, signal), fileHash(sourcePath, signal)]);
const [copyAfter, sourceAfter] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
if (!copyAfter || !sourceAfter || !sameResource(copyBefore, copyAfter) || !sameResource(sourceBefore, sourceAfter)) {
throw new AppError('hardlink_file_changed');
}
return copyHash === sourceHash
? { status: 'matched', copyStamp: copyAfter, sourceStamp: sourceAfter }
: { status: 'mismatch' };
}
export function sameInode(left: BigIntStats, right: BigIntStats): boolean {
return left.isFile() && right.isFile() && left.dev === right.dev && left.ino === right.ino;
}
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
File diff suppressed because it is too large. Load diff
@@ -1,18 +1,18 @@
import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises';
import { isAbsolute, join, relative } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import { dirname, isAbsolute, join, relative } from 'node:path';
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
import { requireUnredirectedData } from './data-location.ts';
import { discardDecalCache, importDecalCache } from './decals.ts';
import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts';
import { statHardlinkResource } from './hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, backUpStockFilesFrom, installStockSource, refreshStockBackup, requireStockBackupLocation, stockBackupPath } from './stock-backup.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts';
/**
* Install the offline version: check the patches against the player's game,
@@ -90,12 +90,12 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
}
try {
const copied = request.method === 'copy'
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks ? version : null, signal, report)
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks, version, signal, report)
: undefined;
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stockBackup = externalStockPath
? await backUpStockFilesFrom(copyPath, externalStockPath)
? await refreshStockBackupFrom(copyPath, externalStockPath)
: (request.method === 'in-place' || request.method === 'existing') && stock.refresh
? await refreshStockBackup(copyPath)
: await backUpStockFiles(copyPath);
@@ -141,16 +141,20 @@ async function inspectInstallation(request: InstallRequest) {
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
]);
await requireAvailableCopy(request.id, copyPath, dataPath);
if (!isAbsolute(request.dataPath) || copyPathContains(stockBackupPath(copyPath), dataPath) ||
(request.method === 'copy' && copyPathContains(sourcePath, dataPath)) ||
(externalStockPath && copyPathContains(externalStockPath, dataPath))) {
throw new AppError('target_not_usable', { problem: 'overlaps_stock' });
const dataProblem = dataFolderProblem(
dataPath,
copyPath,
request.method === 'copy' ? sourcePath : null,
externalStockPath,
);
if (!isAbsolute(request.dataPath) || dataProblem !== null) {
throw new AppError('target_not_usable', { problem: dataProblem ?? 'overlaps_stock' });
}
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
if (useHardLinks && (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version))) {
if (useHardLinks && !target?.sameDriveAsStock) {
throw new AppError('hardlink_unavailable');
}
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
@@ -165,6 +169,28 @@ async function inspectInstallation(request: InstallRequest) {
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) {
const stockGame = await requireGameFolder(stockSourcePath);
if (stockGame.needsStockSource) throw new AppError('stock_source_invalid');
@@ -178,16 +204,17 @@ async function copyGame(
source: string,
target: string,
initialFreeBytes: number | null,
hardlinkVersion: string | null,
useHardLinks: boolean,
sourceVersion: string | null,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source);
const hardlinks = hardlinkVersion ? await confirmHardlinks(source, hardlinkVersion, 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 neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== hardlinkVersion)) {
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
throw new AppError('hardlink_file_changed');
}
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
@@ -200,7 +227,7 @@ async function copyGame(
try {
await copyPlannedFiles(source, target, plan, signal,
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
if (hardlinks && (await inspectGameFolder(source)).version !== hardlinkVersion) throw new AppError('hardlink_file_changed');
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
return {
sourceFiles: plan.files.map((file) => file.relativePath),
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
@@ -214,26 +241,22 @@ async function copyGame(
}
}
async function confirmHardlinks(
async function prepareHardlinks(
source: string,
version: string,
plan: CopyPlan,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<ReadonlyMap<string, BigIntStats>> {
const candidates = plan.files.flatMap((file) => {
const evidence = hardlinkResource(version, file.relativePath, file.bytes);
return evidence ? [{ path: file.relativePath, evidence }] : [];
});
const totalBytes = candidates.reduce((total, file) => total + file.evidence.bytes, 0);
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 { path, evidence } of candidates) {
const verified = await verifyHardlinkResource(join(source, path), evidence, signal);
if (verified) links.set(path, verified);
doneBytes += evidence.bytes;
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 });
}
@@ -50,22 +50,36 @@ export async function backUpStockFilesFrom(copyFolder: string, sourceFolder: str
return backup;
}
/** A new game version must pass the patch checks before replacing an existing stock backup. */
/** A new game version or damaged backup must pass the patch checks before replacing wtoffline/stock. */
export async function installStockSource(copyFolder: string, version: string | null) {
const backup = await requireStockBackupLocation(copyFolder);
if (!await exists(join(backup, GAME_FILES.executable))) return { path: copyFolder, refresh: await exists(backup) };
const backedUpVersion = executableVersion(await readFile(join(backup, GAME_FILES.executable)));
return version !== null && backedUpVersion !== version ? { path: copyFolder, refresh: true } : { path: backup, refresh: false };
const backupExe = join(backup, GAME_FILES.executable);
if (!await exists(backupExe)) return { path: copyFolder, refresh: await exists(backup) };
let backedUpVersion: string | null = null;
try {
backedUpVersion = executableVersion(await readFile(backupExe));
} catch (error) {
console.warn('[stock-backup] unreadable backed-up executable, will refresh:', backupExe, error);
return { path: copyFolder, refresh: true };
}
return backedUpVersion === null || (version !== null && backedUpVersion !== version)
? { path: copyFolder, refresh: true }
: { path: backup, refresh: false };
}
export async function refreshStockBackup(copyFolder: string): Promise<string> {
return refreshStockBackupFrom(copyFolder, copyFolder);
}
/** Replace wtoffline/stock atomically with the four stock files from `sourceFolder`. */
export async function refreshStockBackupFrom(copyFolder: string, sourceFolder: string): Promise<string> {
const backup = await requireStockBackupLocation(copyFolder);
return await changeCopyFiles(copyFolder, async (incoming) => {
const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
const target = join(incoming, STOCK_BACKUP_FOLDER, file);
await mkdir(dirname(target), { recursive: true });
await copyFile(join(copyFolder, file), target);
await copyFile(join(sourceFolder, file), target);
}
return { replace, remove: [] };
}, async () => backup);
@@ -1,12 +1,22 @@
import { execFile, spawn } from 'node:child_process';
import { join } from 'node:path';
import { constants } from 'node:fs';
import { access, lstat, open, readdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
import { GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import offlineGameArguments from '@shared/offline-game-arguments.json';
import type { GameExit } from '@shared/schemas/launch.ts';
import { formatExitCode, type GameExit } from '@shared/schemas/launch.ts';
const execute = promisify(execFile);
const HOOK_DLL_FILENAME = 'wto_ws.dll';
const HOOK_CFG_FILENAME = 'wto_ws.cfg';
const HOOK_LOG_FILENAME = 'wto_ws.log';
const HOOK_LOG_TAIL_BYTES = 8 * 1024;
const HOOK_LOG_TAIL_LINES = 8;
const HOOK_LOG_LINE_LIMIT = 200;
/** Allow small filesystem timestamp skew when matching newly created .game_logs entries. */
const MTIME_SKEW_MS = 2000;
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
if (process.platform !== 'win32') return false;
@@ -18,8 +28,13 @@ export async function runGameProcess(
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
): Promise<GameExit> {
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
await verifyLaunchFiles(copyPath);
signal.throwIfAborted();
const child = spawn(join(copyPath, GAME_FILES.executable), [...offlineGameArguments, ...additionalArguments], {
const executable = join(copyPath, GAME_FILES.executable);
const args = [...offlineGameArguments, ...additionalArguments];
const startedAt = Date.now();
console.info('[game] starting:', executable, args);
const child = spawn(executable, args, {
cwd: copyPath, shell: false, stdio: 'ignore',
});
const stop = (): void => { child.kill(); };
@@ -27,6 +42,7 @@ export async function runGameProcess(
try {
return await new Promise<GameExit>((resolve, reject) => {
child.once('spawn', () => {
console.info('[game] process started, pid:', child.pid ?? 'unknown');
if (signal.aborted) stop();
else onStart();
});
@@ -36,9 +52,16 @@ export async function runGameProcess(
});
child.once('close', (code, reason) => {
const logFolder = join(copyPath, '.game_logs');
const elapsedMs = Date.now() - startedAt;
const summary = code !== null ? formatExitCode(code) : (reason ?? 'unknown');
if (code !== 0 && !signal.aborted) {
console.warn('[game] process exited:', code ?? reason, logFolder);
console.warn('[game] process exited:', summary, `after ${elapsedMs} ms`, logFolder);
void logAbnormalExitContext(copyPath, startedAt)
.catch((error: unknown) => console.warn('[game] inspecting post-exit files failed:', error))
.finally(() => resolve({ code, signal: reason, logFolder }));
return;
}
console.info('[game] process exited:', summary, `after ${elapsedMs} ms`);
resolve({ code, signal: reason, logFolder });
});
signal.addEventListener('abort', stop, { once: true });
@@ -47,3 +70,103 @@ export async function runGameProcess(
signal.removeEventListener('abort', stop);
}
}
/** Verify the patched executable and hook files are still present and readable right before spawn. */
async function verifyLaunchFiles(copyPath: string): Promise<void> {
const exeFolder = dirname(GAME_FILES.executable);
const required = [
GAME_FILES.executable,
join(exeFolder, HOOK_DLL_FILENAME),
join(exeFolder, HOOK_CFG_FILENAME),
];
const missing: string[] = [];
for (const relativePath of required) {
const fullPath = join(copyPath, relativePath);
try {
const stats = await lstat(fullPath);
if (!stats.isFile() || stats.size === 0) {
missing.push(`${relativePath} (not a non-empty file)`);
continue;
}
await access(fullPath, constants.R_OK);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code ?? 'error';
missing.push(`${relativePath} (${code})`);
}
}
if (missing.length > 0) {
console.error('[game] required launch files unavailable before start:', missing.join(', '));
throw new AppError('launch_game_files_missing');
}
}
/** Record a compact read-only snapshot of hook and game log files after an unexpected non-zero exit. */
async function logAbnormalExitContext(copyPath: string, startedAt: number): Promise<void> {
const exeFolder = join(copyPath, dirname(GAME_FILES.executable));
const [dllState, cfgState, hookLogStat, newGameLogs] = await Promise.all([
describeFile(join(exeFolder, HOOK_DLL_FILENAME)),
describeFile(join(exeFolder, HOOK_CFG_FILENAME)),
safeRegularStat(join(exeFolder, HOOK_LOG_FILENAME)),
listNewGameLogs(join(copyPath, '.game_logs'), startedAt),
]);
const hookLogDesc = hookLogStat
? `${hookLogStat.size} bytes (${hookLogStat.mtimeMs >= startedAt - MTIME_SKEW_MS ? 'updated' : 'stale'})`
: 'missing';
console.warn(
`[game] post-exit check: ${HOOK_DLL_FILENAME}=${dllState}, ${HOOK_CFG_FILENAME}=${cfgState}, ` +
`${HOOK_LOG_FILENAME}=${hookLogDesc}, newGameLogs=${newGameLogs}`,
);
if (hookLogStat && hookLogStat.size > 0) {
const tail = await readTailLines(join(exeFolder, HOOK_LOG_FILENAME), hookLogStat.size);
if (tail.length > 0) {
console.warn(`[game] ${HOOK_LOG_FILENAME} tail:\n ${tail.join('\n ')}`);
}
}
}
async function describeFile(path: string): Promise<string> {
const stats = await safeRegularStat(path);
return stats ? `${stats.size} bytes` : 'missing';
}
async function safeRegularStat(path: string) {
try {
const stats = await lstat(path);
return stats.isFile() ? stats : null;
} catch {
return null;
}
}
async function listNewGameLogs(folder: string, startedAt: number): Promise<string> {
try {
const entries = await readdir(folder, { withFileTypes: true });
const recent: string[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
const stats = await safeRegularStat(join(folder, entry.name));
if (!stats || stats.mtimeMs < startedAt - MTIME_SKEW_MS) continue;
recent.push(`${entry.name} (${stats.size} bytes)`);
}
return recent.length > 0 ? recent.slice(0, 6).join(', ') : 'none';
} catch {
return 'unavailable';
}
}
async function readTailLines(path: string, fileSize: number): Promise<string[]> {
const length = Math.min(fileSize, HOOK_LOG_TAIL_BYTES);
const start = fileSize - length;
const handle = await open(path, 'r');
try {
const buffer = Buffer.alloc(length);
const { bytesRead } = await handle.read(buffer, 0, length, start);
const text = buffer.subarray(0, bytesRead).toString('utf8');
const lines = text.split(/\r?\n/).filter((line) => line.length > 0);
return lines.slice(-HOOK_LOG_TAIL_LINES).map((line) => (
line.length > HOOK_LOG_LINE_LIMIT ? `${line.slice(0, HOOK_LOG_LINE_LIMIT)}…` : line
));
} finally {
await handle.close();
}
}
@@ -109,7 +109,7 @@ async function launch(job: LaunchJob): Promise<void> {
const plan = await planLaunch(job, record, settings);
if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port } = plan;
await buildForLaunch(job, record, plan, settings.autoSaveBackups);
await buildForLaunch(job, record, plan, settings);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
if (signal.aborted) return;
@@ -144,6 +144,10 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
}
const currentVersion = await readVersion(record.copyPath, signal);
if (!currentVersion || currentVersion !== record.gameVersion) {
console.warn(
`[launch] client version changed: recorded=${record.gameVersion ?? 'unknown'}, ` +
`actual=${currentVersion ?? 'missing'} (${record.copyPath})`,
);
update(job, { phase: 'version-changed', actualVersion: currentVersion });
return null;
}
@@ -171,6 +175,11 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
]);
signal.throwIfAborted();
if (!copyVersion || copyVersion !== stockVersion) {
console.warn(
`[launch] copy/stock version mismatch: copy=${copyVersion ?? 'missing'} (${copyPath}), ` +
`stock=${stockVersion ?? 'missing'} (${stockPath})`,
);
if (!lab && !stockVersion) throw new AppError('launch_stock_missing');
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
}
if (games) throw new AppError('launch_game_running');
@@ -178,10 +187,10 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
}
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise<void> {
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
if (autoSaveBackups) {
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
await saveBackup({ ...record, dataPath }, userId, 'launch');
@@ -189,6 +198,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
}
signal.throwIfAborted();
update(job, { phase: 'building', port });
const buildStart = Date.now();
let writtenFiles = 0;
await buildCopy({
kind: 'build',
stockPath,
@@ -198,12 +209,15 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
steamLibraryConfirmed,
...resourcePaths(),
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
}, signal, (filesWritten, filesTotal, file) => {
writtenFiles = filesWritten;
if (!signal.aborted) update(job, {
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
});
});
console.info(`[launch] prepared ${writtenFiles} game files for port ${port} in ${Date.now() - buildStart} ms`);
}
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
@@ -34,13 +34,17 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor
}
export async function startLocalServer(
{ gameFolder, dataFolder, port }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
{ gameFolder, dataFolder, port, loggingEnabled = true }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
): Promise<LocalServer> {
signal.throwIfAborted();
const worker = utilityProcess.fork(join(import.meta.dirname, 'server-worker.js'), [gameFolder, dataFolder, String(port)], {
serviceName: 'WTOffline local server',
stdio: 'pipe',
});
const worker = utilityProcess.fork(
join(import.meta.dirname, 'server-worker.js'),
[gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'],
{
serviceName: 'WTOffline local server',
stdio: 'pipe',
},
);
forwardProcessOutput(worker.stdout, 'server', 'info');
forwardProcessOutput(worker.stderr, 'server', 'error');
@@ -49,7 +49,10 @@ export async function runOrdinaryLaunch(
const args = parseLaunchArguments(settings.launchArguments);
if (!args) throw new AppError('launch_game_failed');
publish('starting-server');
const server = await startLocalServer({ gameFolder: copyPath, dataFolder: dataPath, port }, signal);
const server = await startLocalServer(
{ gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled },
signal,
);
const stop = new AbortController();
const runSignal = AbortSignal.any([signal, stop.signal]);
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
@@ -7,7 +7,7 @@ import {
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
} from '@wto/patcher';
import { z } from 'zod';
import { AppReleaseVersionSchema, launcherReleaseFiles } from '@shared/schemas/app-update.ts';
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
import { releaseRepositoryUrl } from '@shared/update-source.ts';
import { getSettings } from '../config/settings-store.ts';
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
@@ -17,6 +17,12 @@ export interface ReleaseSource {
readonly githubDownloads: URL | null;
}
export interface PortableReleaseAssets {
readonly archive: URL;
readonly manifest: URL;
readonly signature: URL;
}
export interface LauncherRelease {
readonly source: ReleaseSource;
readonly version: string;
@@ -24,6 +30,7 @@ export interface LauncherRelease {
readonly installer: URL;
readonly manifest: URL;
readonly signature: URL;
readonly portable?: PortableReleaseAssets;
}
export interface PackReleaseFiles {
@@ -226,12 +233,27 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
if (!parsed.success) return null;
const { assets, body } = parsed.data;
const names = launcherReleaseFiles(version);
const portableNames = portableLauncherReleaseFiles(version);
const urls = assetUrls(assets, `v${version}`, source);
const installer = urls.get(names.installer);
const manifest = urls.get(names.manifest);
const signature = urls.get(names.signature);
if (!installer || !manifest || !signature) return null;
return { source, version, notes: body?.trim().slice(0, 1600) ?? '', installer, manifest, signature };
const portableArchive = urls.get(portableNames.archive);
const portableManifest = urls.get(portableNames.manifest);
const portableSignature = urls.get(portableNames.signature);
const portable = portableArchive && portableManifest && portableSignature
? { archive: portableArchive, manifest: portableManifest, signature: portableSignature }
: undefined;
return {
source,
version,
notes: body?.trim().slice(0, 1600) ?? '',
installer,
manifest,
signature,
...(portable ? { portable } : {}),
};
}
function packRelease(release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null {
@@ -10,6 +10,7 @@ export interface BuildRequest {
readonly patches: string;
readonly networkHookLibrary: string;
readonly decalCache?: string;
readonly hookLogging: boolean;
readonly acceptedUnavailable: readonly string[];
}
@@ -1,7 +1,7 @@
import { readFileSync, realpathSync } from 'node:fs';
import { relative } from 'node:path';
import type { MessageEvent } from 'electron';
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readPlayerDecalIndexFiles, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
@@ -34,6 +34,7 @@ function importedDecals(path: string | undefined): string | undefined {
function build(request: BuildRequest): void {
checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache);
const decalIndexFiles = decalCache ? readPlayerDecalIndexFiles(decalCache) : undefined;
const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath),
patches: request.patches,
@@ -41,6 +42,8 @@ function build(request: BuildRequest): void {
port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
placeholderDecals: decalCache === undefined,
...(decalIndexFiles ? { decalIndexFiles } : {}),
hookLogging: request.hookLogging,
});
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable);
@@ -3,13 +3,14 @@ import { startServer } from '@wto/server';
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
async function serve(): Promise<void> {
const [gameFolder, dataFolder, portText] = process.argv.slice(2);
const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2);
const port = Number(portText);
if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid local server arguments.');
}
const server = await startServer({ gameFolder, dataFolder, port, report: console.info });
console.info('Traffic log:', server.logFolder);
const loggingEnabled = loggingFlag !== '0';
const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info });
if (server.logFolder) console.info('Traffic log:', server.logFolder);
process.parentPort.once('message', () => {
void server.close().then(() => process.exit(0)).catch((error: unknown) => {
console.error('Could not close the local server:', error);
+18 -3
View File
@@ -10,6 +10,7 @@ import { applyLanguage, resolveLanguage } from './i18n/index.ts';
import { ipcInvoke, ipcOn } from './ipc.ts';
import { AboutPage } from './pages/about/AboutPage.tsx';
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
import { CopyList } from './pages/copies/CopyList.tsx';
import { CopySummary } from './pages/copies/CopySummary.tsx';
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
@@ -68,6 +69,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
// The setting as the window opened: turning it on later does not check right away.
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
const maintenance = useCopyMaintenance(report);
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
@@ -149,13 +151,26 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
bar: home,
};
case 'about':
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} appUpdate={appUpdate} />, bar: home };
return {
side: homeSide,
main: (
<AboutPage
launcherVersion={info.version}
supportedVersions={supported}
patchPack={patchPack}
appUpdate={appUpdate}
loggingEnabled={settings.loggingEnabled}
onError={report}
/>
),
bar: home,
};
case 'settings': {
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
const content = {
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
diag: <DiagnosticsSettings settings={settings} onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
dev: <DeveloperSettings settings={settings} onError={report} />,
};
return {
@@ -210,7 +225,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
};
}
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'
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
@@ -96,7 +96,7 @@
},
"decals": {
"source": "Decal source",
"hint": "Import the online game's cache/content folder. The client uses placeholder decals when no cache is available.",
"hint": "Import the online game's cache/content (or cache) folder for cached decals and downloadable skins. Placeholder decals are used when no cache is available.",
"choose": "Choose decal cache…",
"useDefault": "Use placeholder decals",
"importing": "Importing decal cache",
@@ -157,9 +157,9 @@
"copy": "Copy installation (recommended)",
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
"spaceSaving": "Space-saving copy",
"spaceSavingBody": "Shares verified large resources on the same volume. Estimated space required is {{size}}. A Steam update in place can change shared files in the client.",
"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.",
"spaceSavingPending": "Calculating how much space can be saved.",
"spaceSavingUnavailable": "This installation has no large resources 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.",
"targetTitle": "Select an install location (a WTOffline subfolder will be created)",
"targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.",
@@ -188,7 +188,11 @@
},
"data": {
"body": "Select a folder for saves, caches, and logs.",
"dialogTitle": "Select the data folder"
"dialogTitle": "Select the data folder",
"problem": {
"overlaps_client": "The data folder cannot be the client folder, contain the client folder, or lie inside its wtoffline folder. Choose a separate folder or a dedicated subfolder inside the client (for example, data).",
"overlaps_stock": "The data folder cannot lie inside the online installation folder."
}
},
"check": {
"running": "Checking patches for the selected game version.",
@@ -232,12 +236,13 @@
"update": "Update from online installation",
"updateAction": "Update client",
"newVersion": "Version {{version}} is available from the installation source.",
"updateDetaches": "Version {{version}} is available. Updating copies shared resources into independent files and requires additional space.",
"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.",
"currentVersion": "Installation source version {{version}}",
"noSource": "Installation source unavailable",
"spaceSaving": "Save space",
"spaceSavingHint": "Share identical verified resources with the source. A Steam update in place can change the shared files.",
"spaceSavingUnavailable": "Requires a client and source installation of the same checked version on the same volume.",
"spaceSavingHint": "Share identical read-only resource archives with the source. An in-place update to the source client can change the shared files.",
"spaceSavingUnavailable": "Requires a client and source installation of the same version on the same volume.",
"compactAction": "Convert",
"check": "Recheck patches",
"checkHint": "Check the original file backup.",
@@ -336,8 +341,7 @@
"country": "Country",
"type": "Vehicle type",
"actions": "Bulk actions",
"research": "Research all",
"purchase": "Grant regular vehicles",
"purchase": "Research and buy all",
"equipment": "Unlock modifications",
"empty": "This client has no eligible research branches.",
"rank": "Rank {{rank}}",
@@ -458,6 +462,7 @@
"tankBotRespawns": "AI tank respawns",
"airBotRespawns": "AI aircraft respawns",
"strikeUcavSpawnScore": "Strike UCAV spawn points",
"nuclearEscalationStrategicBombers": "Nuclear Escalation stage-3 strategic bombers (B-52H / Tu-95M)",
"silverLions": "Starting Silver Lions",
"goldenEagles": "Starting Golden Eagles",
"preferLineSuccessor": "Prefer the next vehicle in the line",
@@ -489,7 +494,7 @@
"appUpdates": "Launcher updates",
"appUpdatesToggle": "Check for launcher updates at start",
"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",
"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.",
@@ -524,11 +529,15 @@
"reset": "Restore default"
},
"diagnostics": {
"recordLogs": "Record runtime logs",
"recordLogsToggle": "Write launcher, local server, and hook logs",
"recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.",
"loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.",
"logs": "Logs",
"logsHint": "Logs recorded by the launcher",
"openLogs": "Open log folder",
"export": "Export diagnostics",
"exportHint": "Save logs, settings and the installation record to a ZIP file",
"exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)",
"save": "Export…",
"saved": "Diagnostics saved to {{path}}.",
"serverStatus": "Local server status",
@@ -566,6 +575,12 @@
"about": {
"launcher": "Launcher {{version}}",
"supported": "Supported game versions: {{versions}}",
"feedback": {
"title": "Feedback and logs",
"export": "Save all logs",
"exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).",
"exportButton": "Save log ZIP…"
},
"pack": {
"title": "Adaptation data",
"current": "In use",
@@ -623,7 +638,12 @@
}
},
"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.",
"community": {
"discord": "Discord",
"discordHint": "Development discussion, general chat, troubleshooting, and bug reports.",
"openDiscord": "Open Discord"
}
},
"features": {
"A-Offline startup": "Offline startup",
@@ -646,6 +666,7 @@
"J-Ground arcade and realistic": "Ground battles (arcade, realistic)",
"J-Air arcade and realistic": "Air 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)",
"K-AI opponents and teammates": "AI opponents and allies",
"K-Spawn score and respawns": "Spawn points and respawning",
@@ -685,7 +706,7 @@
"copy_not_found": "The selected client is no longer available.",
"copies_write_failed": "The client registry could not be saved.",
"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 cache/content (or cache).",
"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_location": "The operation would affect files outside the registered client or data folder.",
@@ -706,12 +727,14 @@
"launch_steam_confirmation_required": "Confirm the Steam locations in Client Maintenance before launching.",
"launch_location": "The client, stock backup, or data folder location is invalid.",
"launch_stock_version": "The stock backup and client versions do not match.",
"launch_stock_missing": "The original file backup (wtoffline\\stock) is missing or unreadable. Check your security software, or remove this client entry and add it again.",
"launch_build_failed": "The game files could not be generated.",
"launch_build_unavailable": "The build found unavailable patches that require review.",
"launch_port_busy": "The local server port is already in use.",
"launch_server_failed": "The local server could not be started. See the launcher log.",
"launch_server_exited": "The local server is unavailable.",
"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.",
"settings_write_failed": "The settings could not be saved.",
"folder_unreadable": "The folder cannot be read: {{path}}",
"not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}",
@@ -724,8 +747,8 @@
"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.",
"copy_failed": "Copying the game files failed. The copied files have been deleted.",
"hardlink_unavailable": "Space-saving copying requires a verified game version and a destination on the same volume.",
"hardlink_no_match": "The files do not match the verified resources for space-saving copying.",
"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_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.",
"install_cancelled": "Installation cancelled. The copied files have been deleted.",
"install_busy": "An installation is already in progress.",
@@ -96,7 +96,7 @@
},
"decals": {
"source": "贴花来源",
"hint": "可导入在线版游戏的 cache/content。未导入时使用占位贴花。",
"hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。",
"choose": "选择贴花缓存…",
"useDefault": "使用占位贴花",
"importing": "正在导入贴花缓存",
@@ -157,9 +157,9 @@
"copy": "复制安装(推荐)",
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
"spaceSaving": "节省空间的复制",
"spaceSavingBody": "与同一磁盘卷上的原版共用已核对的大资源,预计需要 {{size}}。Steam 就地更新可能改变客户端中的共享文件。",
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。",
"spaceSavingPending": "正在估算可节省的空间。",
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的大型资源。",
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
"targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)",
"targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。",
@@ -188,7 +188,11 @@
},
"data": {
"body": "选择用于保存存档、缓存和日志的文件夹。",
"dialogTitle": "选择数据目录"
"dialogTitle": "选择数据目录",
"problem": {
"overlaps_client": "数据目录不能与客户端目录相同、包含客户端目录,或位于客户端的 wtoffline 目录内。请选择独立文件夹或客户端内的专用子文件夹(例如 data)。",
"overlaps_stock": "数据目录不能位于在线版安装目录内。"
}
},
"check": {
"running": "正在检查所选游戏版本的补丁。",
@@ -232,12 +236,13 @@
"update": "从在线版更新",
"updateAction": "更新客户端",
"newVersion": "安装来源已更新至 {{version}}。",
"updateDetaches": "安装来源中有新版本 {{version}}。更新会把共享资源复制为独立文件,需要额外空间。",
"updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。",
"updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。",
"currentVersion": "安装来源版本 {{version}}",
"noSource": "安装来源不可用",
"spaceSaving": "节省空间",
"spaceSavingHint": "将内容一致且已核对的资源与原版共用。Steam 就地更新可能改变这些文件。",
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且使用相同的已核对版本。",
"spaceSavingHint": "将内容一致的只读资源包与原版共用。原版就地更新可能改变这些文件。",
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且版本一致。",
"compactAction": "转换",
"check": "重新检查补丁",
"checkHint": "核对原版文件备份。",
@@ -336,8 +341,7 @@
"country": "国家",
"type": "兵种",
"actions": "批量操作",
"research": "全部研发",
"purchase": "获得常规载具",
"purchase": "全部研发并购买",
"equipment": "解锁改装件",
"empty": "此客户端没有可编辑的研发分支。",
"rank": "等级 {{rank}}",
@@ -458,6 +462,7 @@
"tankBotRespawns": "AI 坦克重生次数",
"airBotRespawns": "AI 飞机重生次数",
"strikeUcavSpawnScore": "打击无人机所需出生点数",
"nuclearEscalationStrategicBombers": "核战冲突启用第 3 阶段战略核轰炸机(B-52H / Tu-95M)",
"silverLions": "初始银狮",
"goldenEagles": "初始金鹰",
"preferLineSuccessor": "优先研发同系载具",
@@ -489,7 +494,7 @@
"appUpdates": "启动器本体更新",
"appUpdatesToggle": "启动时检查本体更新",
"patchPacks": "适配包更新",
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。",
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布。",
"updateMirror": "备用更新仓库",
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
@@ -524,11 +529,15 @@
"reset": "恢复默认"
},
"diagnostics": {
"recordLogs": "生成运行日志",
"recordLogsToggle": "记录启动器、本地服务器和钩子日志",
"recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。",
"loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。",
"logs": "日志",
"logsHint": "启动器运行日志",
"openLogs": "打开日志文件夹",
"export": "导出诊断信息",
"exportHint": "导出包含日志、设置和安装记录的 ZIP 文件",
"exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)",
"save": "导出…",
"saved": "诊断信息已保存到 {{path}}。",
"serverStatus": "本地服务器状态页",
@@ -566,6 +575,12 @@
"about": {
"launcher": "启动器 {{version}}",
"supported": "支持的游戏版本:{{versions}}",
"feedback": {
"title": "问题反馈",
"export": "保存全部日志",
"exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。",
"exportButton": "保存日志 ZIP…"
},
"pack": {
"title": "适配数据",
"current": "当前使用",
@@ -623,7 +638,12 @@
}
},
"statement": "项目信息",
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。"
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。",
"community": {
"discord": "Discord",
"discordHint": "开发讨论、日常交流、使用求助与问题反馈。",
"openDiscord": "打开 Discord"
}
},
"features": {
"A-Offline startup": "离线启动",
@@ -646,6 +666,7 @@
"J-Ground arcade and realistic": "陆战(街机、历史)",
"J-Air arcade and realistic": "空战(街机、历史)",
"J-Naval arcade and realistic": "海战(街机、历史)",
"E-Crew skills in battle": "战局乘员技能与资格",
"J-Sub-modes": "附加模式(如夜战)",
"K-AI opponents and teammates": "AI 对手与队友",
"K-Spawn score and respawns": "出生点数与重生",
@@ -685,7 +706,7 @@
"copy_not_found": "所选客户端已不可用。",
"copies_write_failed": "无法保存客户端记录。",
"copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。",
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。",
"decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。",
"decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。",
"maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。",
"maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。",
@@ -706,12 +727,14 @@
"launch_steam_confirmation_required": "请在客户端维护中确认 Steam 目录后再启动。",
"launch_location": "客户端、原版文件备份或数据目录的位置无效。",
"launch_stock_version": "原版文件备份的版本与客户端不一致。",
"launch_stock_missing": "缺少或无法读取原版文件备份(wtoffline\\stock)。请检查安全软件拦截记录,或移除此客户端登记后重新添加。",
"launch_build_failed": "无法生成游戏文件。",
"launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。",
"launch_port_busy": "本地服务器端口已被占用。",
"launch_server_failed": "无法启动本地服务器。请查看启动器日志。",
"launch_server_exited": "本地服务器不可用。",
"launch_game_failed": "游戏进程无法启动。请查看启动器日志。",
"launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。",
"settings_write_failed": "无法保存设置。",
"folder_unreadable": "无法读取文件夹:{{path}}",
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
@@ -724,8 +747,8 @@
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
"patch_check_failed": "检查补丁时出错。",
"copy_failed": "复制游戏文件失败,已复制的文件已删除。",
"hardlink_unavailable": "省空间复制需要已核对的游戏版本,并且目标与原版位于同一磁盘卷。",
"hardlink_no_match": "文件内容与可共用的实测资源不一致。",
"hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。",
"hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。",
"hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。",
"install_cancelled": "安装已取消,已复制的文件已删除。",
"install_busy": "已有安装正在进行。",
@@ -1,20 +1,25 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
import { AppUpdateSection } from './AppUpdateSection.tsx';
import type { PatchPackState } from '../../shell/usePatchPack.ts';
const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs';
interface AboutPageProps {
readonly launcherVersion: string;
readonly supportedVersions: readonly string[];
readonly patchPack: PatchPackState;
readonly appUpdate: AppUpdateState;
readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void;
}
/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate }: AboutPageProps) {
/** 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) {
const { t } = useTranslation();
return (
<Sheet title={t('nav.about')}>
@@ -26,14 +31,79 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
{t('about.supported', { versions: supportedVersions.join(', ') })}
</div>
</div>
<AppUpdateSection state={appUpdate} />
<PatchPackSection state={patchPack} />
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3>
<p className="lead">{t('about.statementBody')}</p>
<div className="about-columns">
<div className="about-column">
<AppUpdateSection state={appUpdate} />
<PatchPackSection state={patchPack} />
</div>
<div className="about-column">
<CommunitySection />
<FeedbackLogsSection loggingEnabled={loggingEnabled} onError={onError} />
<section className="about-card">
<h3 className="about-card-title">{t('about.statement')}</h3>
<p className="about-card-meta">{t('about.statementBody')}</p>
</section>
</div>
</div>
</Sheet>
);
}
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 }: {
readonly loggingEnabled: boolean;
readonly onError: (error: unknown) => void;
}) {
const { t } = useTranslation();
const [exporting, setExporting] = useState(false);
const [savedPath, setSavedPath] = useState<string | null>(null);
async function save(): Promise<void> {
setExporting(true);
setSavedPath(null);
try {
const result = await ipcInvoke('app:exportDiagnostics');
setSavedPath(result.path);
} catch (error) {
onError(error);
} finally {
setExporting(false);
}
}
return (
<section className="about-card">
<div className="about-card-head">
<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(); }}>
{t('about.feedback.exportButton')}
</button>
</div>
</div>
<p className="about-card-meta">{t('about.feedback.exportHint')}</p>
{!loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</section>
);
}
function PatchPackSection({ state }: { readonly state: PatchPackState }) {
const { t } = useTranslation();
const { active, check, busy } = state;
@@ -45,25 +115,30 @@ function PatchPackSection({ state }: { readonly state: PatchPackState }) {
? t('about.pack.bundledVersion', { version: active.version })
: t('about.pack.bundled');
return (
<>
<h3 className="section-title">{t('about.pack.title')}</h3>
<Row label={t('about.pack.current')} hint={t('about.pack.currentHint')}>
<span>{current}</span>
{active?.source === 'downloaded' && (
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
{t('about.pack.useBundled')}
<section className="about-card">
<div className="about-card-head">
<h3 className="about-card-title">{t('about.pack.title')}</h3>
<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>
)}
</Row>
<Row label={t('about.pack.check')} hint={t('about.pack.checkHint')}>
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{busy === 'checking' ? t('about.pack.checking') : t('about.pack.checkButton')}
</button>
</Row>
{active?.source === 'downloaded' && (
<button type="button" className="button" disabled={busy !== null} onClick={state.useBundled}>
{t('about.pack.useBundled')}
</button>
)}
</div>
</div>
<p className="about-card-meta">
<span className="about-card-label">{t('about.pack.current')}</span>
{' · '}
{current}
</p>
<p className="small">{t('about.pack.currentHint')}</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>}
{check && busy !== 'checking' && <CheckResult state={state} />}
</>
</section>
);
}
@@ -1,7 +1,6 @@
import { useTranslation } from 'react-i18next';
import { Notice } from '../../components/Notice.tsx';
import { ProgressBar } from '../../components/ProgressBar.tsx';
import { Row } from '../../components/Row.tsx';
import { formatBytes } from '../../format.ts';
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
@@ -10,13 +9,16 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
if (!state.supported) return null;
const { check, busy, progress } = state;
return (
<>
<h3 className="section-title">{t('about.update.title')}</h3>
<Row label={t('about.update.check')}>
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
</button>
</Row>
<section className="about-card">
<div className="about-card-head">
<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}>
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
</button>
</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 === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
{check?.status === 'available' && busy !== 'checking' && (
@@ -43,6 +45,6 @@ export function AppUpdateSection({ state }: { readonly state: AppUpdateState })
)}
</Notice>
)}
</>
</section>
);
}
@@ -1,29 +1,24 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { IpcInput } from '@shared/ipc/contract.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 { Sheet } from '../../components/Sheet.tsx';
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 type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
interface CopyMaintenanceProps {
readonly record: InstallRecord;
readonly maintenance: CopyMaintenanceState;
readonly onError: (error: unknown) => void;
}
type Operation = MaintenanceRequest['operation'];
type OperationOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
const { t } = useTranslation();
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 [result, setResult] = useState<Operation | 'cancelled' | null>(null);
useEffect(() => {
let mounted = true;
@@ -31,29 +26,17 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
if (mounted) setInfo(value);
}).catch(onError);
return () => { mounted = false; };
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, onError]);
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
useEffect(() => ipcOn('event:copy-maintenance', (event) => {
if (event.id === record.id) setProgress(event);
}), [record.id]);
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 run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
if (operation === 'delete') setRemoval(null);
maintenance.run(record.id, operation, options);
};
const busy = working !== null;
const active = maintenance.active;
const busy = active !== null;
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
return (
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
<CopyMaintenanceActions
@@ -71,32 +54,25 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
onOptionsChange={setRemoval}
onRemove={(deleteData) => run('delete', { deleteData })}
/>
{working && (
<MaintenanceStatus
operation={working}
progress={progress}
onCancel={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}
/>
)}
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
</Sheet>
);
}
interface MaintenanceStatusProps {
readonly operation: Operation;
readonly progress: MaintenanceProgress | null;
readonly progress: MaintenanceProgress;
readonly onCancel: () => void;
}
function MaintenanceStatus({ operation, progress, onCancel }: MaintenanceStatusProps) {
function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
const { t } = useTranslation();
return (
<div className="maintenance-progress" role="status">
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p>
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} />
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{(operation === 'update' || operation === 'compact') && progress?.phase !== 'applying' && (
<p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
<ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
{progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
<button type="button" className="button" onClick={onCancel}>
{t('wizard.cancel')}
</button>
@@ -32,7 +32,9 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
)}
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
? t(info.updateAvailable
? (record.hardlinkedFiles?.length ? 'copies.maintenance.updateDetaches' : 'copies.maintenance.newVersion')
? (record.hardlinkedFiles?.length
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
: 'copies.maintenance.newVersion')
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
: t('copies.maintenance.noSource')}>
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
@@ -0,0 +1,60 @@
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'>, 'deleteData' | 'steamLocations'>;
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>;
@@ -1,6 +1,6 @@
import type { TFunction } from 'i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { LaunchState } from '@shared/schemas/launch.ts';
import { formatExitCode, type LaunchState } from '@shared/schemas/launch.ts';
import type { BarModel } from '../../shell/bar-model.ts';
import { missingFeatures } from '../copies/missing-features.ts';
@@ -24,8 +24,11 @@ export function homeBar(
const starting = { label: t('launch.starting'), disabled: true };
const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null };
const { gameExit } = state;
const exitCodeLabel = gameExit
? (gameExit.code !== null ? formatExitCode(gameExit.code) : (gameExit.signal ?? t('launch.exitCodeUnknown')))
: undefined;
const exitDetail = gameExit && gameExit.code !== 0
? t('launch.exitDetail', { code: gameExit.code ?? gameExit.signal ?? t('launch.exitCodeUnknown'), path: gameExit.logFolder })
? t('launch.exitDetail', { code: exitCodeLabel, path: gameExit.logFolder })
: undefined;
switch (state.phase) {
case 'checking':
@@ -1,10 +1,12 @@
import { useTranslation } from 'react-i18next';
import type { DataFolderProblem } from '@shared/schemas/install.ts';
import { FolderField } from '../../components/FolderField.tsx';
import { Notice } from '../../components/Notice.tsx';
import { Row } from '../../components/Row.tsx';
interface DataStepProps {
readonly dataPath: string;
readonly dataProblem: DataFolderProblem | null;
readonly decalSource: string | null;
readonly steamDataPath: string | null;
readonly steamDataConfirmed: boolean;
@@ -15,13 +17,14 @@ interface DataStepProps {
}
/** Step 3: where saves, caches and logs of the offline version are kept. */
export function DataStep({ dataPath, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) {
const { t } = useTranslation();
return (
<>
<p className="lead">{t('data.body')}</p>
<FolderField path={dataPath} dialogTitle={t('data.dialogTitle')} onChosen={onDataPath} onError={onError} />
{steamDataPath && (
{dataProblem && <Notice tone="error">{t(`data.problem.${dataProblem}`)}</Notice>}
{!dataProblem && steamDataPath && (
<Notice tone="warning">
<p>{t('steam.dataWarning')}</p>
<p className="small">{steamDataPath}</p>
@@ -39,6 +39,7 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins
{step === 'data' && (
<DataStep
dataPath={wizard.dataPath}
dataProblem={wizard.dataProblem}
steamDataPath={wizard.steamDataPath}
steamDataConfirmed={wizard.steamDataConfirmed}
onSteamDataConfirmed={wizard.setSteamDataConfirmed}
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import type { FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import type { DataFolderProblem, FolderSize, GameFolderInspection, InstallProgress, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { ipcInvoke, ipcOn } from '../../ipc.ts';
import { useErrorMessage } from '../../useErrorMessage.ts';
import { checkUsable } from './CheckStep.tsx';
@@ -33,7 +33,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
const [draftId, setDraftId] = useState<string | null>(null);
const [name, setName] = useState('');
const [dataPath, setDataPath] = useState('');
const [dataInspection, setDataInspection] = useState<{ picked: string; path: string; inSteam: boolean; confirmed: boolean } | null>(null);
const [dataInspection, setDataInspection] = useState<{
key: string;
path: string;
inSteam: boolean;
problem: DataFolderProblem | null;
confirmed: boolean;
} | null>(null);
const [decalSource, setDecalSource] = useState<string | null>(null);
const [check, setCheck] = useState<PatchCheck | null>(null);
const [missingAccepted, setMissingAccepted] = useState(false);
@@ -53,22 +59,38 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
};
}, [source, report]);
const plannedCopyPath = choice.method === 'in-place' || choice.method === 'existing'
? (source?.path ?? null)
: (choice.target?.path ?? null);
const plannedSourcePath = choice.method === 'copy' || choice.method === 'hardlink'
? (source?.path ?? null)
: null;
const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null;
const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]);
useEffect(() => {
if (!active || !dataPath) return;
let current = true;
ipcInvoke('install:inspectDataFolder', { path: dataPath })
.then(({ path, inSteam }) => {
ipcInvoke('install:inspectDataFolder', {
path: dataPath,
...(plannedCopyPath ? { copyPath: plannedCopyPath } : {}),
...(plannedSourcePath ? { sourcePath: plannedSourcePath } : {}),
...(plannedStockSourcePath ? { stockSourcePath: plannedStockSourcePath } : {}),
})
.then(({ path, inSteam, problem }) => {
if (!current) return;
setDataInspection((previous) => previous?.picked === dataPath && previous.path === path && previous.inSteam === inSteam
setDataInspection((previous) => previous?.key === dataInspectionKey && previous.path === path &&
previous.inSteam === inSteam && previous.problem === problem
? previous
: { picked: dataPath, path, inSteam, confirmed: false });
: { key: dataInspectionKey, path, inSteam, problem, confirmed: false });
})
.catch((error: unknown) => current && report(error));
return () => { current = false; };
}, [active, dataPath, report]);
}, [active, dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath, dataInspectionKey, report]);
const dataChecked = dataInspection?.picked === dataPath ? dataInspection : null;
const dataReady = dataChecked !== null && (!dataChecked.inSteam || dataChecked.confirmed);
const dataChecked = dataInspection?.key === dataInspectionKey ? dataInspection : null;
const dataProblem = dataChecked?.problem ?? null;
const dataReady = dataChecked !== null && dataProblem === null && (!dataChecked.inSteam || dataChecked.confirmed);
const setSteamDataConfirmed = (confirmed: boolean): void => {
setDataInspection((inspection) => inspection ? { ...inspection, confirmed } : null);
};
@@ -208,7 +230,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) {
};
return {
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn,
steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false,
start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted,
};
@@ -11,7 +11,7 @@ interface Props {
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) {
const { t, i18n } = useTranslation();
@@ -1,19 +1,25 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { Settings } from '@shared/schemas/settings.ts';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
interface DiagnosticsSettingsProps {
readonly settings: Settings;
readonly serverRunning: boolean;
readonly onError: (error: unknown) => void;
}
export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) {
export function DiagnosticsSettings({ settings, onError, serverRunning }: DiagnosticsSettingsProps) {
const { t } = useTranslation();
const [exporting, setExporting] = useState(false);
const [savedPath, setSavedPath] = useState<string | null>(null);
const updateLogging = (loggingEnabled: boolean): void => {
ipcInvoke('settings:update', { loggingEnabled }).catch(onError);
};
async function save(): Promise<void> {
setExporting(true);
setSavedPath(null);
@@ -29,6 +35,16 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
return (
<Sheet title={t('settings.sections.diag')}>
<Row label={t('settings.diagnostics.recordLogs')} hint={t('settings.diagnostics.recordLogsHint')}>
<label className="check check-inline">
<input
type="checkbox"
checked={settings.loggingEnabled}
onChange={(event) => updateLogging(event.target.checked)}
/>
{t('settings.diagnostics.recordLogsToggle')}
</label>
</Row>
<Row label={t('settings.diagnostics.logs')} hint={t('settings.diagnostics.logsHint')}>
<button type="button" className="button" onClick={() => ipcInvoke('app:openLogsFolder').catch(onError)}>
{t('settings.diagnostics.openLogs')}
@@ -44,6 +60,7 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti
{t('settings.diagnostics.openStatus')}
</button>
</Row>
{!settings.loggingEnabled && <p className="small">{t('settings.diagnostics.loggingDisabledNotice')}</p>}
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</Sheet>
);
@@ -11,7 +11,7 @@ type Field = keyof TuningValues;
type Draft = Partial<Record<Field, string | boolean>>;
const fields = {
rewards: ['rewardMultiplierSilverLions', 'rewardMultiplierResearchPoints', 'friendlyKillPenaltyMul'],
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore'],
battle: ['maxPlayers', 'smallTeamsMaxPlayers', 'brSpreadMrank', 'subModeChance', 'tankBotRespawns', 'airBotRespawns', 'strikeUcavSpawnScore', 'nuclearEscalationStrategicBombers'],
newProfile: ['silverLions', 'goldenEagles'],
research: ['preferLineSuccessor', 'autoTargetPick'],
} as const satisfies Record<TuningSection, readonly Field[]>;
@@ -70,7 +70,7 @@ export function TuningPage({ copy, section, onError }: Props) {
const editor = (field: Field): ReactNode => {
const active = draft[field] ?? inputValue(field, loaded.effective[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)} />;
}
if (field === 'autoTargetPick') {
@@ -215,9 +215,13 @@
/* ===== Buttons and links ===== */
.button {
display: inline-flex;
align-items: center;
justify-content: center;
font: 500 14px var(--font-display);
letter-spacing: 0.04em;
text-transform: uppercase;
text-decoration: none;
padding: 7px 16px;
cursor: pointer;
white-space: nowrap;
@@ -371,3 +371,67 @@
line-height: 1.6;
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;
}
+4
View File
@@ -59,12 +59,16 @@ export const APP_ERROR_CODES = [
'launch_steam_confirmation_required',
'launch_location',
'launch_stock_version',
/** The wtoffline/stock backup executable is missing or unreadable before launch. */
'launch_stock_missing',
'launch_build_failed',
'launch_build_unavailable',
'launch_port_busy',
'launch_server_failed',
'launch_server_exited',
'launch_game_failed',
/** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */
'launch_game_files_missing',
/** A folder the player chose does not exist or cannot be read (params: path). */
'folder_unreadable',
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
+17 -3
View File
@@ -5,6 +5,7 @@ import {
CopiesSchema,
CopyIdSchema,
CopyNameSchema,
DATA_FOLDER_PROBLEMS,
FolderSizeSchema,
GameFolderInspectionSchema,
InstallProgressSchema,
@@ -85,8 +86,17 @@ export const ipcContract = {
output: TargetFolderInspectionSchema,
},
'install:inspectDataFolder': {
input: z.object({ path: z.string().min(1) }),
output: z.object({ path: z.string(), inSteam: z.boolean() }),
input: z.object({
path: z.string().min(1),
copyPath: z.string().min(1).optional(),
sourcePath: z.string().min(1).optional(),
stockSourcePath: z.string().min(1).optional(),
}),
output: z.object({
path: z.string(),
inSteam: z.boolean(),
problem: z.enum(DATA_FOLDER_PROBLEMS).nullable(),
}),
},
'install:measureFolder': {
input: z.object({ path: z.string().min(1), version: z.string().nullable().optional() }),
@@ -144,6 +154,10 @@ export const ipcContract = {
input: z.object({ id: CopyIdSchema }),
output: MaintenanceInfoSchema,
},
'copies:maintenanceState': {
input: z.void(),
output: MaintenanceProgressSchema.nullable(),
},
'copies:maintain': {
input: MaintenanceRequestSchema,
output: CopiesSchema,
@@ -324,7 +338,7 @@ export const ipcEvents = {
'event:app-update-progress': AppUpdateProgressSchema,
'event:launch-state': LaunchStateSchema,
'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). */
'event:patch-set-changed': ActivePatchSetSchema,
} as const;
@@ -1,5 +1,6 @@
[
"-forcestart",
"-skip_pkg_validation",
"-nobeac",
"-crashpad-disable-upload",
"--nosteam"
@@ -9,6 +9,11 @@ export function launcherReleaseFiles(version: string) {
return { installer: `${base}.exe`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
}
export function portableLauncherReleaseFiles(version: string) {
const base = `wtoffline-launcher-${AppReleaseVersionSchema.parse(version)}-win-x64-portable`;
return { archive: `${base}.zip`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
}
export const LauncherReleaseManifest = z.strictObject({
kind: z.literal('wto-launcher-release'),
format: z.literal(1),
@@ -19,6 +24,16 @@ export const LauncherReleaseManifest = z.strictObject({
});
export type LauncherReleaseManifest = z.output<typeof LauncherReleaseManifest>;
export const PortableReleaseManifest = z.strictObject({
kind: z.literal('wto-launcher-portable-release'),
format: z.literal(1),
version: AppReleaseVersionSchema,
platform: z.literal('win32-x64'),
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
});
export type PortableReleaseManifest = z.output<typeof PortableReleaseManifest>;
const AppUpdateReleaseSchema = z.object({
version: AppReleaseVersionSchema,
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
@@ -41,6 +41,15 @@ export const TargetFolderInspectionSchema = z.object({
});
export type TargetFolderInspection = z.output<typeof TargetFolderInspectionSchema>;
/** Why a folder cannot hold the offline client's saves, caches, and logs. */
export const DATA_FOLDER_PROBLEMS = [
/** The data folder is the client folder itself, contains it, or lies inside its wtoffline folder. */
'overlaps_client',
/** The data folder lies inside the stock source folder. */
'overlaps_stock',
] as const;
export type DataFolderProblem = (typeof DATA_FOLDER_PROBLEMS)[number];
export const FolderSizeSchema = z.object({
bytes: z.number(),
files: z.number(),
@@ -9,6 +9,12 @@ const GameExitSchema = z.object({
export type GameExit = z.output<typeof GameExitSchema>;
/** Append the unsigned 32-bit hex form for Windows NTSTATUS/HRESULT exit codes. */
export function formatExitCode(code: number): string {
if (code >= 0 && code <= 0xffff) return String(code);
return `${code} (0x${(code >>> 0).toString(16).toUpperCase().padStart(8, '0')})`;
}
export const LaunchStateSchema = z.object({
phase: z.enum([
'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running',
@@ -14,6 +14,7 @@ export const MaintenanceRequestSchema = z.object({
export const MaintenanceInfoSchema = z.object({
sourceVersion: z.string().nullable(),
updateAvailable: z.boolean(),
updatePreservesSpaceSaving: z.boolean(),
spaceSavingAvailable: z.boolean(),
steamConfirmationRequired: z.boolean(),
steamLocations: z.object({
+1 -1
View File
@@ -94,7 +94,7 @@ export const OfficialPreviewSchema = z.object({
omitted: z.array(z.string()),
});
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({
branches: z.array(ResearchBranchSchema),
selected: ResearchBranchSchema.nullable(),
@@ -28,6 +28,8 @@ export const SettingsSchema = z.object({
windowClose: WindowCloseSchema.default('quit'),
afterGameStarts: AfterGameStartsSchema.default('minimize'),
autoSaveBackups: z.boolean().default(true),
/** Write launcher, local server traffic, and wto_ws.log files; does not affect game .game_logs. */
loggingEnabled: z.boolean().default(true),
launchPortMode: PortModeSchema.default('auto'),
launchPort: PortSchema.default(27015),
closeServerOnGameExit: z.boolean().default(true),
@@ -50,6 +52,7 @@ export const SettingsPatchSchema = z.object({
windowClose: WindowCloseSchema.optional(),
afterGameStarts: AfterGameStartsSchema.optional(),
autoSaveBackups: z.boolean().optional(),
loggingEnabled: z.boolean().optional(),
launchPortMode: PortModeSchema.optional(),
launchPort: PortSchema.optional(),
closeServerOnGameExit: z.boolean().optional(),
@@ -12,6 +12,7 @@ export const TuningValuesSchema = z.object({
tankBotRespawns: z.number().int().min(1).max(10),
airBotRespawns: z.number().int().min(1).max(10),
strikeUcavSpawnScore: z.number().int().min(1).max(10000),
nuclearEscalationStrategicBombers: z.boolean(),
silverLions: z.number().int().nonnegative(),
goldenEagles: z.number().int().min(0).max(0x7fffffff),
preferLineSuccessor: z.boolean(),
+74 -1
View File
@@ -22,6 +22,7 @@
import { randomInt } from 'node:crypto';
import type {
BattleSpawnRulesData,
NuclearCarrierUnit,
RandomSpawnGroup,
RandomSpawnUnit,
SupportPlanePreset,
@@ -43,6 +44,8 @@ export interface ExtraBattleSlot {
/** The modifications enabled when not `allModifications`; the unit is otherwise stock. */
readonly modifications: readonly 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. */
readonly groupName?: string;
}
@@ -56,7 +59,10 @@ export interface ExtraBattleSlotsInput {
readonly sessionMaxMrank: number;
readonly vehiclesByName: ReadonlyMap<string, CatalogueVehicle>;
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[] {
@@ -68,6 +74,7 @@ export function selectExtraBattleSlots(input: ExtraBattleSlotsInput): readonly E
if (supportPlane) supportSlots.push(supportPlane);
const ucav = strikeUcavSlot(input);
if (ucav) supportSlots.push(ucav);
supportSlots.push(...nuclearEscalationSlots(input));
// Keep room for fixed support vehicles while displaying random vehicle groups first.
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,
* those of the highest rank below it. Vehicles already in the lineup are left out (offline
+17 -10
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 { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.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, modeMaxRespawns } from '../game-modes/mode-definition.ts';
import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import { selectBattleCoalitions, type CoalitionPairing } from './battle-coalitions.ts';
import { selectExtraBattleSlots, type ExtraBattleSlot } from './battle-extra-slots.ts';
@@ -37,6 +37,7 @@ export interface EnqueueBattleInput {
readonly modes?: readonly OfferedGameMode[];
readonly country: string;
readonly slotVehicles: readonly string[];
readonly mrankDeltas: ReadonlyMap<string, number>;
readonly selectedSlot?: BattleCrewSlot;
readonly bannedMissions: ReadonlySet<string>;
readonly dislikedMissions: ReadonlySet<string>;
@@ -46,10 +47,12 @@ export interface BattleLaunchPlan {
readonly sessionId: string;
readonly modeId: number;
readonly modeName: string;
readonly modeTag?: string;
readonly economicName: string;
readonly missionName: string;
/** The mission as the game describes it, including the parameters copied into the mission settings. */
readonly mission: MissionHeader;
readonly missionRuleKeys: readonly string[];
readonly missionFile: string;
readonly missionType: string;
readonly level?: string;
@@ -67,6 +70,7 @@ export interface BattleLaunchPlan {
readonly maxMrank: number;
readonly maxPlayers: number;
readonly maxBots: number;
readonly maxRespawns?: number;
readonly tankBotRespawns: number;
readonly airBotRespawns: number;
readonly useTankBots: boolean;
@@ -117,13 +121,14 @@ export class BattleMatchmaker {
(mode) => mode.declaration.displayType !== 'pve_battle' && twoSidedMissionsOf(mode).length > 0,
);
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' };
const { declaration } = chosenMode;
const activeVehicles = activeVehiclesForMode(declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName);
const playerMrank = lineupMrank(
activeVehicles, this.#vehiclesByName, declaration.difficulty, declaration.requiredClass, declaration.allowedClasses,
input.mrankDeltas,
);
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
@@ -158,14 +163,11 @@ export class BattleMatchmaker {
};
}
#pickQueuedMode(
candidates: readonly OfferedGameMode[],
slotVehicles: readonly string[],
selectedSlotVehicle: string | undefined,
): OfferedGameMode | 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);
#pickQueuedMode(candidates: readonly OfferedGameMode[], input: EnqueueBattleInput): OfferedGameMode | undefined {
const pool = candidates.filter((mode) => isModeEligibleForLineup(
mode.declaration, input.slotVehicles, input.selectedSlot?.unitName, this.#vehiclesByName, input.mrankDeltas,
));
if (pool.length === 0) return undefined;
const classics = pool.filter((mode) => !mode.declaration.tag);
const subModes = pool.filter((mode) => Boolean(mode.declaration.tag));
if (subModes.length > 0 && classics.length > 0) {
@@ -190,12 +192,14 @@ export class BattleMatchmaker {
const desiredPlayers = declaration.isSmallTeams ? this.#tuning.smallTeamsMaxPlayers : this.#tuning.maxPlayers;
const maxPlayers = Math.min(desiredPlayers, maxSlotsForMission(mission, desiredPlayers));
const maxBots = Math.min(this.#tuning.maxBots, Math.max(1, maxPlayers - 1));
const maxRespawns = modeMaxRespawns(declaration);
const missionLocName = resolveMissionLocName(mission);
const environment = declaration.environmentOverride ?? mission.environment;
const session = this.#sessions.create({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
economicName: declaration.economicName,
difficulty: declaration.difficulty,
requiredClass: declaration.requiredClass,
@@ -222,9 +226,11 @@ export class BattleMatchmaker {
sessionId: session.sessionId,
modeId: declaration.gameModeId,
modeName: declaration.name,
...(declaration.tag !== undefined ? { modeTag: declaration.tag } : {}),
economicName: declaration.economicName,
missionName: mission.name,
mission,
missionRuleKeys: declaration.missionRuleKeys ?? [],
missionFile: mission.path,
missionType: mission.type ?? 'domination',
...(mission.level !== undefined ? { level: mission.level } : {}),
@@ -242,6 +248,7 @@ export class BattleMatchmaker {
maxMrank,
maxPlayers,
maxBots,
...(maxRespawns === undefined ? {} : { maxRespawns }),
tankBotRespawns: this.#tuning.tankBotRespawns,
airBotRespawns: declaration.multiSlot === false ? SINGLE_SPAWN : this.#tuning.airBotRespawns,
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
* 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 { SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
import { emptyBlock, ensureBlock, findParam, setParam, appendParam, type BlkBlock, type BlkParam, type BlkValue } from '@wto/blk';
import { UNLIMITED_RESPAWNS } from '../game-modes/mode-definition.ts';
import type { ExtraBattleSlot } from './battle-extra-slots.ts';
import type { BattleLaunchPlan } from './battle-matchmaker.ts';
import type { CustomBotsPool } from './battle-ranks.ts';
@@ -23,12 +23,13 @@ const RULE_KEYS: readonly string[] = [
'scoreLimit', 'timeLimit', 'killLimit', 'deathPenaltyMul',
'ctaCaptureZoneEqualPenaltyMul', 'ctaCaptureZonePenaltyMul', 'captureZonePenaltyMul', 'scorePerSec',
'ctaInstantDecreaseTicketsWhenNoRespawn', 'randomSpawnTeams', 'remapAiTankModels', 'useAlternativeMapCoord',
'allowedKillStreaks',
];
/** Game type switches of a versus battle with tickets, capture zones and session rewards. */
const VERSUS_SWITCHES: readonly string[] = [
'gt_versus', 'gt_mp_tickets', 'gt_mp_capture', 'gt_use_wp', 'gt_use_xp', 'gt_use_stats', 'gt_use_unlocks',
'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 {
const settings = emptyBlock();
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.environment !== undefined) setParam(settings, 'environment', text(plan.environment));
if (plan.weather !== undefined) setParam(settings, 'weather', text(plan.weather));
@@ -60,9 +68,13 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
setParam(settings, 'symmetricTeams', flag(plan.symmetricTeams));
setParam(settings, 'gt_mp_solo', flag(false));
for (const name of VERSUS_SWITCHES) setParam(settings, name, flag(true));
setParam(settings, '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.selectedSlot && plan.maxRespawns !== UNLIMITED_RESPAWNS));
if (plan.maxRespawns !== undefined) setParam(settings, 'maxRespawns', integer(plan.maxRespawns));
if (plan.selectedSlot) {
setParam(settings, 'maxRespawns', integer(SINGLE_SPAWN));
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));
@@ -88,14 +100,15 @@ export function battleMissionSettings(plan: BattleLaunchPlan, scores: Readonly<R
}
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 => {
for (const param of params ?? []) {
if (keys.has(param.name)) setParam(settings, param.name, param.value);
}
};
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). */
@@ -115,6 +128,7 @@ function customBotsBlock(plan: BattleLaunchPlan): BlkBlock {
setParam(bots, 'wtoPlayerTeam', text(String(plan.playerTeam)));
setParam(bots, 'wtoTeamACountries', text(plan.countriesAllies.join(';')));
setParam(bots, 'wtoTeamBCountries', text(plan.countriesAxis.join(';')));
if (plan.maxRespawns === UNLIMITED_RESPAWNS) setParam(bots, 'wtoUnlimitedRespawns', text('1'));
setParam(bots, 'numBotRespawnsInMultiSlot', integer(plan.airBotRespawns));
setParam(bots, 'numTankBotRespawnsInMultiSlot', integer(plan.tankBotRespawns));
setParam(bots, 'numBotRespawnsInVersus', integer(plan.airBotRespawns));
+13 -2
View File
@@ -95,18 +95,28 @@ export function lineupMrank(
difficulty: ModeDifficulty,
requiredClass: UnitClass,
allowedClasses: readonly UnitClass[],
mrankDeltas: ReadonlyMap<string, number>,
): number {
const crafts: CraftRankEntry[] = vehicleNames.flatMap((name) => {
const vehicle = byName.get(name);
if (!vehicle) return [];
return [{
unitClass: unitClassOfExpClass(vehicle.unitClass),
mrank: vehicleMrank(vehicle, difficulty, requiredClass),
mrank: lineupVehicleMrank(vehicle, difficulty, requiredClass, mrankDeltas),
}];
});
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);
}
export function selectCustomBots(
vehicles: readonly CatalogueVehicle[], query: BotPoolQuery, aircraftLoadouts?: ReadonlyMap<string, BotAircraftLoadout>,
): CustomBotsPool {
@@ -203,6 +213,7 @@ export function isModeEligibleForLineup(
slotVehicles: readonly string[],
selectedSlotVehicle: string | undefined,
byName: ReadonlyMap<string, CatalogueVehicle>,
mrankDeltas: ReadonlyMap<string, number>,
): boolean {
if (!declaration.tag && declaration.multiSlot !== false) return true;
const active = activeVehiclesForMode(declaration, slotVehicles, selectedSlotVehicle, byName);
@@ -211,7 +222,7 @@ export function isModeEligibleForLineup(
const matchingCount = active.filter((name) => {
const vehicle = byName.get(name);
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;
return matchingCount >= minCrafts;
}
+2
View File
@@ -26,6 +26,7 @@ export interface BattleTuning {
readonly strikeUcavSpawnScore: number;
readonly tankBotRespawns: number;
readonly airBotRespawns: number;
readonly nuclearEscalationStrategicBombers: boolean;
}
export function readBattleTuning(reader: TuningReader): BattleTuning {
@@ -66,5 +67,6 @@ export function readBattleTuning(reader: TuningReader): BattleTuning {
strikeUcavSpawnScore: reader.int('strikeUcavSpawnScore', { min: 1, max: 10000 }),
tankBotRespawns: reader.int('tankBotRespawns', { min: 1, max: 10 }),
airBotRespawns: reader.int('airBotRespawns', { min: 1, max: 10 }),
nuclearEscalationStrategicBombers: reader.bool('nuclearEscalationStrategicBombers'),
};
}
@@ -61,6 +61,7 @@ import {
buyWeaponsAction,
enableModificationsAction,
saveWeaponPresetsAction,
setUnitSelectedMrankAction,
} from './modification-actions.ts';
import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts';
import { savePilotAppearanceAction, saveShowcaseAction, selectTitleAction, showcasesAction, usersTerseInfoAction } from './player-card-actions.ts';
@@ -137,6 +138,7 @@ function coreActionEntries(deps: ActionDependencies): Array<[string, CharActionH
['cln_buy_weapon', buyWeaponsAction(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_set_unit_selected_mrank', setUnitSelectedMrankAction(deps.profiles, deps.accounts, deps.equipment)],
['cln_upgrade_crew', upgradeCrewAction(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)],
@@ -8,6 +8,7 @@
* 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_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):
* <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 { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-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 { buyWeapons } from '../../modifications/weapon-purchase.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));
}
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) {
return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 };
}
@@ -14,12 +14,14 @@
* char.vromfs.bin config/wpcost.blk
* ucav_*_killstreak{ country:t ... }
* The strike UCAVs, one per country.
* *_killstreak / nt_* with weapons.<preset>.totalNuclearYield:i
* Tactical (5 kt / 30 kt) and strategic (>= 1000 kt) nuclear carriers for Nuclear Escalation.
* char.vromfs.bin config/warpoints.blk respawn_points / TankHistorical
* Starting points and unit cost parameters for Ground Realistic Battles.
*/
import type { BlkBlock } from '@wto/blk';
import { findParam } from '@wto/blk';
import { blockAt, numberField, stringField, stringList } from './blk-fields.ts';
import { blockAt, boolField, numberField, stringField, stringList } from './blk-fields.ts';
import type { Dataset } from './dataset.ts';
export interface SupportPlaneUnit {
@@ -43,6 +45,18 @@ export interface StrikeUcav {
readonly unitName: string;
}
export interface NuclearCarrierWeapon {
readonly name: string;
readonly yieldKt: number;
}
export interface NuclearCarrierUnit {
readonly country: string;
readonly unitName: string;
readonly mrank: number;
readonly weapons: readonly NuclearCarrierWeapon[];
}
export interface RandomSpawnUnit {
readonly unitName: string;
readonly addModifications: readonly string[];
@@ -76,22 +90,31 @@ export interface BattleSpawnRulesData {
/** By event name (`missionSupportPlane` keys are game mode names). */
readonly supportPlanes: Readonly<Record<string, readonly SupportPlanePreset[]>>;
readonly strikeUcavs: readonly StrikeUcav[];
/** Killstreak nuclear carriers carrying 5 kt / 30 kt Nuclear Escalation presets. */
readonly nuclearEscalationTacticalCarriers: readonly NuclearCarrierUnit[];
/** Megaton-class strategic nuclear bombers (`nt_*` with totalNuclearYield >= 1000 kt). */
readonly nuclearEscalationStrategicBombers: readonly NuclearCarrierUnit[];
readonly spawnScore: SpawnScoreRules;
/** By event economic name, then country. */
readonly randomSpawnUnits: Readonly<Record<string, Readonly<Record<string, readonly RandomSpawnGroup[]>>>>;
}
const STRIKE_UCAV_PATTERN = /^ucav_.*_killstreak$/;
const KILLSTREAK_PATTERN = /_killstreak$/;
const STRATEGIC_BOMBER_PATTERN = /^nt_/;
const STRATEGIC_YIELD_MIN_KT = 1000;
export const battleSpawnRules: Dataset<BattleSpawnRulesData> = {
id: 'battle-spawn-rules',
version: 3,
version: 4,
extract: (source) => {
const gameplay = source.readBlk('aces.vromfs.bin', 'config/gameplay.blk');
const wpcost = source.readBlk('char.vromfs.bin', 'config/wpcost.blk');
return {
supportPlanes: extractSupportPlanes(blockAt(gameplay, 'missionSupportPlane')),
strikeUcavs: extractStrikeUcavs(wpcost.blocks),
nuclearEscalationTacticalCarriers: extractNuclearCarriers(wpcost.blocks, 'tactical'),
nuclearEscalationStrategicBombers: extractNuclearCarriers(wpcost.blocks, 'strategic'),
spawnScore: extractSpawnScore(blockAt(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'respawn_points')),
randomSpawnUnits: extractRandomSpawnUnits(blockAt(gameplay, 'RandomSpawnUnits')),
};
@@ -162,6 +185,38 @@ function extractStrikeUcavs(wpcostBlocks: readonly BlkBlock[]): StrikeUcav[] {
});
}
function extractNuclearCarriers(
wpcostBlocks: readonly BlkBlock[],
kind: 'tactical' | 'strategic',
): NuclearCarrierUnit[] {
const carriers: NuclearCarrierUnit[] = [];
for (const unitBlk of wpcostBlocks) {
const country = stringField(unitBlk, 'country') ?? '';
if (!country.startsWith('country_')) continue;
if (kind === 'tactical' && !KILLSTREAK_PATTERN.test(unitBlk.name)) continue;
if (kind === 'strategic' && !STRATEGIC_BOMBER_PATTERN.test(unitBlk.name)) continue;
const weaponsBlk = blockAt(unitBlk, 'weapons');
if (!weaponsBlk) continue;
const weapons: NuclearCarrierWeapon[] = [];
for (const weaponBlk of weaponsBlk.blocks) {
if (boolField(weaponBlk, 'isWeaponForCustomSlot') === true) continue;
if (boolField(weaponBlk, 'hideInGui') === true) continue;
if (weaponBlk.name.includes('without_countermeasures')) continue;
const yieldKt = numberField(weaponBlk, 'totalNuclearYield') ?? 0;
if (yieldKt <= 0) continue;
if (kind === 'tactical' && yieldKt >= STRATEGIC_YIELD_MIN_KT) continue;
if (kind === 'strategic' && yieldKt < STRATEGIC_YIELD_MIN_KT) continue;
weapons.push({ name: weaponBlk.name, yieldKt });
}
if (weapons.length === 0) continue;
weapons.sort((a, b) => a.yieldKt - b.yieldKt || a.name.localeCompare(b.name));
const mrank = numberField(unitBlk, 'economicRankHistorical') ?? numberField(unitBlk, 'economicRank') ?? 0;
carriers.push({ country, unitName: unitBlk.name, mrank, weapons });
}
carriers.sort((a, b) => a.country.localeCompare(b.country) || a.mrank - b.mrank || a.unitName.localeCompare(b.unitName));
return carriers;
}
function extractRandomSpawnUnits(
root: BlkBlock | undefined,
): Record<string, Record<string, RandomSpawnGroup[]>> {
@@ -5,7 +5,7 @@
* char.vromfs.bin config/wpcost.blk, per vehicle:
* needBuyToOpenNextInTier<N>:i researched modifications of tier N needed to open tier N+1
* modifications{ <name>{ tier:i reqExp:i value:i costGold:i openCostGold:i
* reqModification:t (repeated) maxCount:i ammoCount:i ... } }
* reqModification:t (repeated) maxCount:i ammoCount:i addMrank:i ... } }
* Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount).
* weapons{ <preset>{ value:i costGold:i maxCount:i reqModification:t ... } }
* Paid presets (bombs, rockets) are bought by the piece, up to maxCount; the rest are free,
@@ -39,6 +39,8 @@ export interface ModificationFacts {
readonly maxCount: number;
/** ammoCount present: an ammunition belt or shell type. */
readonly ammunition: boolean;
/** addMrank: selectable matchmaking rank increase unlocked by owning this modification. */
readonly addMrank?: number;
/** Initial enabled state when acquired (`turn_it_off` / `isEnabledByDefaultForAddMrank`). */
readonly defaultEnabled: boolean;
/** Non-bullet `group` name when modifications in the same group are mutually exclusive. */
@@ -78,7 +80,7 @@ interface GlobalModificationMeta {
export const vehicleEquipment: Dataset<readonly VehicleEquipment[]> = {
id: 'vehicle-equipment',
version: 4,
version: 5,
extract: (source) => {
const modMeta = readGlobalModificationMeta(source.readBlk('char.vromfs.bin', MODIFICATIONS_CONFIG));
return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => equipmentOf(vehicle, modMeta));
@@ -119,6 +121,7 @@ function equipmentOf(vehicle: BlkBlock, modMeta: ReadonlyMap<string, GlobalModif
function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | undefined): ModificationFacts {
const ammunition = numberField(modification, 'ammoCount') !== undefined;
const addMrank = numberField(modification, 'addMrank');
const defaultEnabled = !(meta?.turnOffByDefault ?? false) && (boolField(modification, 'isEnabledByDefaultForAddMrank') ?? true);
const group = stringField(modification, 'group') ?? meta?.group;
const exclusiveGroup = !ammunition && !(meta?.bulletGroup ?? false) ? group : undefined;
@@ -132,6 +135,7 @@ function modificationOf(modification: BlkBlock, meta: GlobalModificationMeta | u
requires: stringList(modification, 'reqModification'),
maxCount: numberField(modification, 'maxCount') ?? 0,
ammunition,
...(addMrank !== undefined ? { addMrank } : {}),
defaultEnabled,
...(exclusiveGroup !== undefined ? { exclusiveGroup } : {}),
};
@@ -50,6 +50,10 @@ export interface GameModeDeclaration {
* `true`; `false` for single-slot modes (`air_realistic` and its `small_teams_` sub-mode).
*/
readonly multiSlot?: boolean;
/** Stock maxRespawns value when this mode specifies its own respawn count. */
readonly maxRespawns?: number;
/** Additional scalar settings the local host needs from this mode's missions. */
readonly missionRuleKeys?: readonly string[];
/** False for modes whose native weapon rules replace combat presets. Defaults to true. */
readonly allowBotAircraftLoadouts?: boolean;
/** Minimum `mrank` exposed on the parent mode for Night Battles (`scripts/events/eventinfo.nut:134-136`). */
@@ -11,6 +11,7 @@
* AB/RB get Enduring Confrontation; Ground AB and Air AB get none);
* - `queueEvent.nut` includes or excludes its `gameModeId` in `match.enqueue` `game_modes_list`.
*/
import { UNLIMITED_RESPAWNS } from '../mode-definition.ts';
import type { GameModeDeclaration } from './game-mode-declaration.ts';
import {
AIR_REALISTIC_MISSIONS,
@@ -69,6 +70,15 @@ export const SUB_GAME_MODES: readonly GameModeDeclaration[] = [
displayType: 'random_battle',
allowedCraftMinMrank: { aircraft: MIN_MRANK_NUCLEAR_ESCALATION },
minQueueMrank: MIN_MRANK_NUCLEAR_ESCALATION,
maxRespawns: UNLIMITED_RESPAWNS,
// mission_settings.mission in mis.vromfs.bin gamedata/missions/cta/planes/nuclear_escalation/.
missionRuleKeys: [
'customHUD', 'nuclearEscalationStage1', 'nuclearEscalationStage2', 'nuclearEscalationStage3',
'useSpawnDelay', 'afterRespawnDelaySec', 'overrideMaxActiveUnitsWeight', 'scheduleBasedGmUpdateMaxInterval',
'disableFallingTrees', 'alwaysSendAllyGMData', 'isAlwaysShowCollectiveDetectedUnits', 'useAIForCollectiveDetection',
'allowToChooseHUDIconPreset', 'showAIKilllog', 'showUnitTooltipOnMap', 'disableMfdForPrevgenConsoles',
'clientReplayMaxSizeMb', 'timeToLoseInstantDetection', 'showTacticalMapCellSize',
],
requiredClass: 'aircraft',
allowedClasses: ['aircraft'],
missions: NUCLEAR_ESCALATION_MISSIONS,
@@ -41,8 +41,13 @@ export const MISSION_DIFFICULTY: Readonly<Record<ModeDifficulty, string>> = {
simulator: 'hardcore',
};
// globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.SINGLE_SPAWN.
// globals/missions/respawnCountModes.nut: RESPAWN_COUNT_MODE.
export const SINGLE_SPAWN = 1;
export const UNLIMITED_RESPAWNS = -2;
export function modeMaxRespawns(mode: GameModeDeclaration): number | undefined {
return mode.maxRespawns ?? (mode.multiSlot === false ? SINGLE_SPAWN : undefined);
}
export type ModeDefinition = Readonly<Record<string, unknown>>;
@@ -50,6 +55,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
countries: readonly string[], missionRanks?: MissionRotationRanks): ModeDefinition {
const minTeamSize = mode.teamSizeOverride?.min ?? 1;
const maxTeamSize = mode.teamSizeOverride?.max ?? teamSize(mode, missions);
const maxRespawns = modeMaxRespawns(mode);
const team = {
countries: [...countries],
allowedCrafts: mode.allowedClasses.map((unitClass) => {
@@ -83,7 +89,7 @@ export function buildModeDefinition(mode: GameModeDeclaration, missions: readonl
teamB: structuredClone(team),
mission_decl: {
difficulty: MISSION_DIFFICULTY[mode.difficulty],
...(mode.multiSlot === false ? { maxRespawns: SINGLE_SPAWN } : {}),
...(maxRespawns === undefined ? {} : { maxRespawns }),
missions_list: Object.fromEntries(missions.map((mission) => {
const ranges = missionRanks?.byMission.get(mission.name);
return [mission.name, ranges?.length === 1 ? { enableIf: ranges[0] } : {}];
@@ -16,7 +16,6 @@ import type { BlkBlock, BlkValue } from '@wto/blk';
import type { BannerParams } from '../battle/battle-economy.ts';
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
import { SINGLE_SPAWN } from '../game-modes/mode-definition.ts';
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
@@ -52,12 +51,13 @@ export function battleLaunchNotify(
mission: {
name: plan.missionName,
difficulty: plan.difficulty,
...(plan.selectedSlot ? { maxRespawns: SINGLE_SPAWN } : {}),
...(plan.maxRespawns === undefined ? {} : { maxRespawns: plan.maxRespawns }),
},
},
battle: {
sessionId: plan.sessionId,
modeName: plan.modeName,
...(plan.modeTag ? { modeTag: plan.modeTag } : {}),
economicName: plan.economicName,
country: plan.country,
missionName: plan.missionName,
@@ -12,6 +12,7 @@ import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankE
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import { vehicleMrankDelta } from '../profile/profile-hangar.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
import type { MatchingRequestHandler } from './matching-requests.ts';
@@ -90,6 +91,7 @@ function handleEnqueue(
modes,
country: playerEntry.country,
slotVehicles,
mrankDeltas: new Map(slotVehicles.map((vehicle) => [vehicle, vehicleMrankDelta(profile, vehicle)])),
...(idInCountry !== undefined && selectedSlotVehicle ? { selectedSlot: { idInCountry, unitName: selectedSlotVehicle } } : {}),
bannedMissions: playerEntry.bannedMissions,
dislikedMissions: playerEntry.dislikedMissions,
@@ -4,7 +4,12 @@
* carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N).
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk';
import { recordName, type ModificationRecord } from '../profile/profile-modifications.ts';
import {
allModificationBlocks,
MAX_MODIFICATION_BLOCK_ENTRIES,
recordName,
type ModificationRecord,
} from '../profile/profile-modifications.ts';
import type { WeaponRecord } from '../profile/profile-weapons.ts';
const HANGAR = 'hangar';
@@ -21,7 +26,7 @@ export class ProfileEquipmentIndex {
readonly #weapons = new Map<string, BlkBlock>();
readonly #modsResearch = new Map<string, BlkBlock>();
readonly #removedResearch = new Set<string>();
#modificationsBlock: BlkBlock | undefined;
readonly #modificationsBlocks: BlkBlock[];
#weaponsBlock: BlkBlock | undefined;
#modsResearchBlock: BlkBlock | undefined;
@@ -30,9 +35,9 @@ export class ProfileEquipmentIndex {
const hangar = findBlock(profile, HANGAR);
if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry);
this.#modificationsBlock = findBlock(profile, MODIFICATIONS);
if (this.#modificationsBlock) {
for (const entry of this.#modificationsBlock.blocks) this.#modifications.set(entry.name, entry);
this.#modificationsBlocks = allModificationBlocks(profile);
for (const chunk of this.#modificationsBlocks) {
for (const entry of chunk.blocks) this.#modifications.set(entry.name, entry);
}
this.#weaponsBlock = findBlock(profile, WEAPONS);
@@ -103,14 +108,32 @@ export class ProfileEquipmentIndex {
const key = recordName(vehicle, modification);
let block = this.#modifications.get(key);
if (!block) {
this.#modificationsBlock ??= ensureBlock(this.#profile, MODIFICATIONS);
block = { name: key, params: [], blocks: [] };
this.#modificationsBlock.blocks.push(block);
this.#appendModificationBlock(block);
this.#modifications.set(key, block);
}
block.params = orderedModParams(record);
}
#appendModificationBlock(entry: BlkBlock): void {
for (let index = this.#modificationsBlocks.length - 1; index >= 0; index--) {
const chunk = this.#modificationsBlocks[index]!;
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
chunk.blocks.push(entry);
return;
}
}
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
const lastChunk = this.#modificationsBlocks[this.#modificationsBlocks.length - 1];
if (lastChunk) {
const insertAt = this.#profile.blocks.lastIndexOf(lastChunk) + 1;
this.#profile.blocks.splice(insertAt, 0, nextChunk);
} else {
this.#profile.blocks.push(nextChunk);
}
this.#modificationsBlocks.push(nextChunk);
}
weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined {
const block = this.#weapons.get(`${vehicle}_${weapon}`);
if (!block) return undefined;
@@ -11,7 +11,7 @@
*/
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts';
import { recordName } from '../profile/profile-modifications.ts';
import { allModificationBlocks, appendModificationEntry, recordName } from '../profile/profile-modifications.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
export interface SupportPlaneModification {
@@ -31,7 +31,10 @@ export interface SupportUnitEquipmentGrants {
}
export function supportPlaneModifications(
rules: Pick<BattleSpawnRulesData, 'supportPlanes' | 'strikeUcavs'>,
rules: Pick<
BattleSpawnRulesData,
'supportPlanes' | 'strikeUcavs' | 'nuclearEscalationTacticalCarriers' | 'nuclearEscalationStrategicBombers'
>,
catalogue: EquipmentCatalogue,
): SupportUnitEquipmentGrants {
const seenMods = new Set<string>();
@@ -53,21 +56,34 @@ export function supportPlaneModifications(
weapons.push({ vehicle, weapon, count: Math.max(1, count) });
};
const grantWeaponPreset = (unitName: string, weapon: string): void => {
const facts = catalogue.weapon(unitName, weapon);
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
for (const container of facts?.sumWeapons ?? []) {
const containerFacts = catalogue.weapon(unitName, container);
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
}
};
for (const presets of Object.values(rules.supportPlanes)) {
for (const preset of presets) {
for (const { unitName, weapon } of Object.values(preset.units)) {
const facts = catalogue.weapon(unitName, weapon);
addWeapon(unitName, weapon, facts?.maxCount ?? 1);
for (const modification of facts?.requires ?? []) addMod(unitName, modification);
for (const container of facts?.sumWeapons ?? []) {
const containerFacts = catalogue.weapon(unitName, container);
addWeapon(unitName, container, containerFacts?.maxCount ?? 1);
for (const modification of containerFacts?.requires ?? []) addMod(unitName, modification);
}
grantWeaponPreset(unitName, weapon);
}
}
}
for (const carrier of [
...rules.nuclearEscalationTacticalCarriers,
...rules.nuclearEscalationStrategicBombers,
]) {
for (const weapon of carrier.weapons) {
grantWeaponPreset(carrier.unitName, weapon.name);
}
}
for (const ucav of rules.strikeUcavs) {
const vehicle = catalogue.vehicle(ucav.unitName);
if (!vehicle) continue;
@@ -82,13 +98,14 @@ export function supportPlaneModifications(
export function grantSupportPlaneModifications(profile: BlkBlock, grants: SupportUnitEquipmentGrants): void {
if (grants.modifications.length > 0) {
let modsBlock = findBlock(profile, 'modifications');
const existing = new Set((modsBlock?.blocks ?? []).map((entry) => entry.name));
const existing = new Set<string>();
for (const chunk of allModificationBlocks(profile)) {
for (const entry of chunk.blocks) existing.add(entry.name);
}
for (const { vehicle, modification } of grants.modifications) {
const key = recordName(vehicle, modification);
if (existing.has(key)) continue;
modsBlock ??= ensureBlock(profile, 'modifications');
modsBlock.blocks.push({ name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
appendModificationEntry(profile, { name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] });
existing.add(key);
}
}
@@ -0,0 +1,21 @@
import type { BlkBlock } from '@wto/blk';
import { ownsVehicle, setVehicleMrankDelta } from '../profile/profile-hangar.ts';
import { modificationRecord } from '../profile/profile-modifications.ts';
import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts';
import type { EquipmentCatalogue } from './equipment-catalogue.ts';
export function selectVehicleMrankDelta(
profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, delta: number,
): RuleOutcome {
const equipment = catalogue.vehicle(vehicle);
if (!equipment || !ownsVehicle(profile, vehicle) || !Number.isInteger(delta) || delta < 0) return refused('BAD_PARAMS');
// Stock getSelectableAddMranks offers zero and each positive addMrank on an owned modification.
if (delta > 0 && !equipment.modifications.some((modification) =>
modification.addMrank === delta && (modificationRecord(profile, vehicle, modification.name)?.count ?? 0) > 0)) {
return refused('NOT_AVAILABLE');
}
setVehicleMrankDelta(profile, vehicle, delta);
return ACCEPTED;
}
+20 -5
View File
@@ -1,19 +1,24 @@
/**
* Owned vehicles in the profile, as in Gaijin's
* config/default_user.blk: one empty sub-block per vehicle the player owns.
* The profile's hangar has one sub-block per owned vehicle, as in config/default_user.blk.
*
* hangar{
* bf2c_1{
* }
* }
*/
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
import { intField } from './blk-fields.ts';
const HANGAR = 'hangar';
const MRANK_DELTA = 'mrankDelta';
function ownedVehicle(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
const hangar = findBlock(profile, HANGAR);
return hangar && findBlock(hangar, vehicle);
}
export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean {
const hangar = findBlock(profile, HANGAR);
return hangar !== undefined && findBlock(hangar, vehicle) !== undefined;
return ownedVehicle(profile, vehicle) !== undefined;
}
export function ownedVehicles(profile: BlkBlock): Set<string> {
@@ -25,3 +30,13 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
const hangar = ensureBlock(profile, HANGAR);
if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] });
}
/** The stock client uses the base rank until it has a non-negative selection. */
export function vehicleMrankDelta(profile: BlkBlock, vehicle: string): number {
return Math.max(0, intField(ownedVehicle(profile, vehicle), MRANK_DELTA));
}
export function setVehicleMrankDelta(profile: BlkBlock, vehicle: string, delta: number): void {
const entry = ownedVehicle(profile, vehicle);
if (entry) setParam(entry, MRANK_DELTA, { type: 'int', value: delta });
}
@@ -12,11 +12,19 @@
* the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole:
* wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i
* Absent values are left out; enabled is only written when false (the default is enabled).
*
* Dagor's binary DataBlock stores child block counts in a uint16 (65,535 max). Because the full
* vehicle catalogue exceeds 65,535 modifications, aces.exe splits modifications across up to 3
* sibling top-level `modifications` blocks of at most 65,535 entries each (2.61.0.37 0x938fae..0x9397e6,
* 2.61.0.58 0x93ba70 / 0x93bb53). All readers and writers here span every sibling block.
*/
import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk';
import type { BlkBlock, BlkParam } from '@wto/blk';
const MODIFICATIONS = 'modifications';
/** Maximum entries per `modifications` DataBlock (uint16 child count limit in aces.exe 0x939000 / 0x93ba70). */
export const MAX_MODIFICATION_BLOCK_ENTRIES = 0xffff;
export interface ModificationRecord {
readonly silverLionsSpent: number;
readonly goldenEaglesSpent: number;
@@ -29,9 +37,66 @@ export function recordName(vehicle: string, modification: string): string {
return `${vehicle}_${modification}`;
}
/** Every top-level `modifications` chunk in the profile, in document order. */
export function allModificationBlocks(profile: BlkBlock): BlkBlock[] {
return profile.blocks.filter((block) => block.name === MODIFICATIONS);
}
/** Append a new modification entry to a chunk with spare capacity, opening a sibling chunk when full. */
export function appendModificationEntry(profile: BlkBlock, entry: BlkBlock): void {
const chunks = allModificationBlocks(profile);
for (let index = chunks.length - 1; index >= 0; index--) {
const chunk = chunks[index]!;
if (chunk.blocks.length < MAX_MODIFICATION_BLOCK_ENTRIES) {
chunk.blocks.push(entry);
return;
}
}
const nextChunk: BlkBlock = { name: MODIFICATIONS, params: [], blocks: [entry] };
const lastChunk = chunks[chunks.length - 1];
if (lastChunk) {
const insertAt = profile.blocks.lastIndexOf(lastChunk) + 1;
profile.blocks.splice(insertAt, 0, nextChunk);
} else {
profile.blocks.push(nextChunk);
}
}
/** Ensure every top-level `modifications` chunk stays within the 65,535-child DataBlock limit. */
export function normalizeModificationBlocks(profile: BlkBlock): void {
const chunks = allModificationBlocks(profile);
if (chunks.length === 0) return;
const needsRebalance = chunks.some((chunk) => chunk.blocks.length > MAX_MODIFICATION_BLOCK_ENTRIES)
|| (chunks.length > 1 && chunks.some((chunk) => chunk.blocks.length === 0));
if (!needsRebalance) return;
const firstIndex = profile.blocks.findIndex((block) => block.name === MODIFICATIONS);
const entries = chunks.flatMap((chunk) => chunk.blocks);
profile.blocks = profile.blocks.filter((block) => block.name !== MODIFICATIONS);
if (entries.length === 0) return;
const rebuilt: BlkBlock[] = [];
for (let offset = 0; offset < entries.length; offset += MAX_MODIFICATION_BLOCK_ENTRIES) {
rebuilt.push({
name: MODIFICATIONS,
params: [],
blocks: entries.slice(offset, offset + MAX_MODIFICATION_BLOCK_ENTRIES),
});
}
profile.blocks.splice(Math.max(0, firstIndex), 0, ...rebuilt);
}
function findModificationEntry(profile: BlkBlock, key: string): BlkBlock | undefined {
for (const chunk of profile.blocks) {
if (chunk.name !== MODIFICATIONS) continue;
const found = chunk.blocks.find((entry) => entry.name === key);
if (found) return found;
}
return undefined;
}
export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined {
const block = findBlock(profile, MODIFICATIONS);
const record = block && findBlock(block, recordName(vehicle, modification));
const record = findModificationEntry(profile, recordName(vehicle, modification));
if (!record) return undefined;
return {
silverLionsSpent: intOf(record, 'wpSpent'),
@@ -42,12 +107,17 @@ export function modificationRecord(profile: BlkBlock, vehicle: string, modificat
}
export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean {
return modificationRecord(profile, vehicle, modification) !== undefined;
return findModificationEntry(profile, recordName(vehicle, modification)) !== undefined;
}
export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void {
const block = ensureBlock(ensureBlock(profile, MODIFICATIONS), recordName(vehicle, modification));
block.params = orderedParams(record);
const key = recordName(vehicle, modification);
const existing = findModificationEntry(profile, key);
if (existing) {
existing.params = orderedParams(record);
return;
}
appendModificationEntry(profile, { name: key, params: orderedParams(record), blocks: [] });
}
function orderedParams(record: ModificationRecord): BlkParam[] {
+7 -9
View File
@@ -3,9 +3,9 @@ import { ClanStore } from '../clans/clan-store.ts';
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts';
import { GameFiles } from '../game-data/game-files.ts';
import { ProfileEquipmentIndex } from '../modifications/profile-equipment-index.ts';
import { addOwnedVehicle, ownedVehicles } from '../profile/profile-hangar.ts';
import { ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts';
import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts';
import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
import { setUpProfiles } from '../profiles-setup.ts';
import { TechTree } from '../research/tech-tree.ts';
import { loadTuning } from '../tuning/tuning.ts';
@@ -15,7 +15,7 @@ export interface ResearchBranch {
readonly country: string;
readonly type: string;
}
export type ResearchOperation = 'research' | 'purchase' | 'equipment';
export type ResearchOperation = 'purchase' | 'equipment';
function tree(location: SaveLocation) {
const gameFiles = new GameFiles(location.gameFolder);
@@ -52,21 +52,19 @@ export function editSaveResearch(location: SaveLocation, userId: string, branch:
const { profiles, equipment } = setUpProfiles(location.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles);
profiles.update(userId, (profile) => {
const owned = ownedVehicles(profile);
const index = operation === 'equipment' ? new ProfileEquipmentIndex(profile) : undefined;
for (const unit of units) {
if (operation === 'research' && unit.kind === 'research' && !owned.has(unit.name)) {
setResearchPoints(profile, unit.name, Math.max(researchPointsOf(profile, unit.name), unit.researchPoints));
}
if (operation === 'purchase' && (unit.kind === 'research' || unit.kind === 'purchase')) {
addOwnedVehicle(profile, unit.name);
for (const part of unit.parts) addOwnedVehicle(profile, part);
}
if (operation === 'equipment' && owned.has(unit.name)) {
if (index && owned.has(unit.name)) {
const enabledGroups = new Set<string>();
for (const mod of equipment.vehicle(unit.name)?.modifications ?? []) {
if (mod.name === 'premExpMul' || mod.goldenEagles > 0 || ownsModification(profile, unit.name, mod.name)) continue;
if (mod.name === 'premExpMul' || mod.goldenEagles > 0 || index.ownsModification(unit.name, mod.name)) continue;
const enable = mod.defaultEnabled && (!mod.exclusiveGroup || !enabledGroups.has(mod.exclusiveGroup));
if (enable && mod.exclusiveGroup) enabledGroups.add(mod.exclusiveGroup);
writeModificationRecord(profile, unit.name, mod.name, {
index.writeModificationRecord(unit.name, mod.name, {
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: enable, count: Math.max(1, mod.maxCount),
});
}
+2
View File
@@ -11,6 +11,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { normalizeModificationBlocks } from '../profile/profile-modifications.ts';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import type { SaveUpgrades } from './save-upgrades.ts';
@@ -44,6 +45,7 @@ export class SaveStore {
saveProfile(userId: string, profile: BlkBlock): void {
const now = new Date().toISOString();
const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined;
normalizeModificationBlocks(profile);
writeFileAtomic(this.#profilePath(userId), encodeBlk(profile));
const info: SaveInfo = { formatVersion: this.#upgrades.currentFormat, created: previous?.created ?? now, updated: now };
writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2));
+7 -3
View File
@@ -10,7 +10,7 @@ import { InventoryCatalogue } from '../inventory/itemdef-catalogue.ts';
import { intField, stringField } from '../profile/blk-fields.ts';
import { allCrews } from '../profile/profile-crews.ts';
import { ACTIVE_LISTS } from '../profile/profile-items.ts';
import { recordName } from '../profile/profile-modifications.ts';
import { normalizeModificationBlocks, recordName } from '../profile/profile-modifications.ts';
import { loadTuning } from '../tuning/tuning.ts';
import type { SaveLocation } from './save-editor.ts';
@@ -38,9 +38,13 @@ export function prepareTransferredProfile(location: SaveLocation, bytes: Uint8Ar
['modifications', modifications], ['modsResearch', modifications], ['weapons', weapons],
] as const;
for (const [key, allowed] of blockKeys) {
const collection = findBlock(profile, key);
if (collection) collection.blocks = collection.blocks.filter((entry) => allowed.has(entry.name));
for (const collection of profile.blocks) {
if (collection.name === key) {
collection.blocks = collection.blocks.filter((entry) => allowed.has(entry.name));
}
}
}
normalizeModificationBlocks(profile);
for (const crew of allCrews(profile)) {
const aircraft = findBlock(crew, 'aircrafts');
if (aircraft) {
+3 -1
View File
@@ -69,6 +69,8 @@ export interface ServerOptions {
readonly port: number;
/** Start-up progress lines (static data extraction, game modes). */
readonly report?: (line: string) => void;
/** Whether to write traffic logs under `<dataFolder>/logs`; defaults to true. */
readonly loggingEnabled?: boolean;
}
export const LOOPBACK = '127.0.0.1';
@@ -143,7 +145,7 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
})),
new DownloadableContentService(),
]);
const log = new TrafficLog(options.dataFolder);
const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true);
const listener = createPortListener(
router,
matchingRequests({
+11 -2
View File
@@ -20,11 +20,19 @@ export interface MatchingLogEntry {
export class TrafficLog {
readonly folder: string;
readonly #enabled: boolean;
readonly #linesPath: string;
readonly #bodiesFolder: string;
#sequence = 0;
constructor(dataFolder: string) {
constructor(dataFolder: string, enabled = true) {
this.#enabled = enabled;
if (!enabled) {
this.folder = '';
this.#linesPath = '';
this.#bodiesFolder = '';
return;
}
this.folder = join(dataFolder, 'logs', new Date().toISOString().replace(/[:.]/g, '-'));
this.#linesPath = join(this.folder, 'requests.jsonl');
this.#bodiesFolder = join(this.folder, 'bodies');
@@ -96,11 +104,12 @@ export class TrafficLog {
}
#append(line: object): void {
if (!this.#enabled) return;
appendFileSync(this.#linesPath, JSON.stringify(line) + '\n');
}
#writeBody(id: number, suffix: string, content: Uint8Array | string | undefined): string | null {
if (content === undefined || byteLength(content) === 0) return null;
if (!this.#enabled || content === undefined || byteLength(content) === 0) return null;
const name = `${String(id).padStart(6, '0')}.${suffix}`;
writeFileSync(join(this.#bodiesFolder, name), content);
return name;
@@ -25,6 +25,7 @@ function values(files: TuningFiles) {
tankBotRespawns: battle.tankBotRespawns,
airBotRespawns: battle.airBotRespawns,
strikeUcavSpawnScore: battle.strikeUcavSpawnScore,
nuclearEscalationStrategicBombers: battle.nuclearEscalationStrategicBombers,
silverLions: newProfile.silverLions,
goldenEagles: newProfile.goldenEagles,
preferLineSuccessor: research.preferLineSuccessor,
@@ -46,6 +47,7 @@ const fileOf = {
tankBotRespawns: 'battle',
airBotRespawns: 'battle',
strikeUcavSpawnScore: 'battle',
nuclearEscalationStrategicBombers: 'battle',
silverLions: 'new-profile',
goldenEagles: 'new-profile',
preferLineSuccessor: 'research',
+6 -1
View File
@@ -47,5 +47,10 @@
// AI bot respawn limits per battle in multi-slot versus modes.
"tankBotRespawns": 3,
"airBotRespawns": 2
"airBotRespawns": 2,
// Offer a stage-3 megaton strategic bomber (B-52H / Tu-95M) alongside the tactical nuclear
// carrier in Air RB Nuclear Escalation (sub-mode 103). Disable to use tactical 5 kt / 30 kt
// carriers only, matching the regular live rotation.
"nuclearEscalationStrategicBombers": true
}
+1 -1
View File
@@ -23,7 +23,7 @@ New-Item -ItemType Directory -Force $obj | Out-Null
$sources = @(
"$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c",
"$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c",
"$src\local_mp_damage_notifications.c",
"$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c",
"$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c"
) | ForEach-Object { '"' + (Resolve-Path $_) + '"' }
+25 -3
View File
@@ -20,12 +20,20 @@ static HMODULE g_ws2;
int hook_export(const char *name, void *replacement, void **original)
{
void *target = (void *)GetProcAddress(g_ws2, name);
MH_STATUS status;
if (target == NULL) {
log_line("hook %s: not exported by ws2_32.dll", name);
return 0;
}
if (MH_CreateHook(target, replacement, original) != MH_OK || MH_EnableHook(target) != MH_OK) {
log_line("hook %s: failed", name);
status = MH_CreateHook(target, replacement, original);
if (status != MH_OK) {
log_line("hook %s: MH_CreateHook failed (%s)", name, MH_StatusToString(status));
return 0;
}
status = MH_QueueEnableHook(target);
if (status != MH_OK) {
log_line("hook %s: MH_QueueEnableHook failed (%s)", name, MH_StatusToString(status));
MH_RemoveHook(target);
return 0;
}
return 1;
@@ -33,12 +41,26 @@ int hook_export(const char *name, void *replacement, void **original)
static int install(void)
{
MH_STATUS status;
/* ws2_32.dll is already loaded: this DLL links against it. */
g_ws2 = GetModuleHandleW(L"ws2_32.dll");
if (g_ws2 == NULL || MH_Initialize() != MH_OK)
if (g_ws2 == NULL) {
log_line("wto_ws: ws2_32.dll module handle unavailable");
return 0;
}
status = MH_Initialize();
if (status != MH_OK) {
log_line("wto_ws: MH_Initialize failed (%s)", MH_StatusToString(status));
return 0;
}
if (!install_resolver_hooks() || !install_connection_hooks())
return 0;
/* Enable all mandatory network hooks in one thread-freeze pass before touching LocalMP hooks. */
status = MH_ApplyQueued();
if (status != MH_OK) {
log_line("wto_ws: MH_ApplyQueued for ws2_32 failed (%s)", MH_StatusToString(status));
return 0;
}
install_local_mp_hooks();
return 1;
}
+5 -1
View File
@@ -4,6 +4,7 @@
* wto_ws.cfg, written by the build into the game copy (@wto/patcher network-hook.ts):
* port=<local server port> without a valid port the hooks still answer every host name
* locally but refuse every connection that would leave the machine
* log=0|1 optional, defaults to 1; when 0, wto_ws.log is not opened
* exe.time_date_stamp=0x... the executable the native values were resolved for
* exe.size_of_image=0x...
* native.<name>=<value> what the LocalMP modules need from the executable: RVAs of
@@ -33,6 +34,7 @@ typedef struct NativeValue {
static wchar_t g_folder[MAX_PATH];
static CRITICAL_SECTION g_log_lock;
static FILE *g_log;
static int g_log_enabled = 1;
static NativeValue g_native[NATIVE_VALUES_MAX];
static size_t g_native_count;
static int64_t g_exe_time_date_stamp = -1;
@@ -98,6 +100,8 @@ static void read_settings(void)
line[strcspn(line, "\r\n")] = '\0';
if (strncmp(line, "port=", 5) == 0)
read_port(line + 5);
else if (strncmp(line, "log=", 4) == 0)
g_log_enabled = atoi(line + 4) != 0;
else if (strncmp(line, "exe.time_date_stamp=", 20) == 0)
parse_value(line + 20, &g_exe_time_date_stamp);
else if (strncmp(line, "exe.size_of_image=", 18) == 0)
@@ -140,7 +144,7 @@ void config_load(HMODULE self)
InitializeCriticalSection(&g_log_lock);
find_folder(self);
read_settings();
if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0)
if (g_log_enabled && _snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0)
g_log = _wfsopen(path, L"w", _SH_DENYWR);
log_line("wto_ws: local server port %u%s", g_service_port, g_service_port ? "" : " (none: outside connections are refused)");
log_line("wto_ws: %u native value(s) for the LocalMP modules", (unsigned)g_native_count);
+4 -7
View File
@@ -125,15 +125,12 @@ static uint8_t __fastcall hook_mp_construct_local(uint8_t *mp, void *mis, void *
int install_local_mp_action_hooks(void)
{
uint8_t *p_construct = g_lmp.mp_construct_local;
const LocalMpHookSpec hooks[] = {
{ "mp_construct_local", g_lmp.mp_construct_local, (void *)&hook_mp_construct_local, (void **)&orig_mp_construct_local },
};
fn_mp_init_chat = (MpInitChatFn)g_lmp.mp_init_chat;
fn_dagmem_alloc = (DagmemAllocFn)g_lmp.dagmem_alloc;
if (MH_CreateHook(p_construct, (void *)&hook_mp_construct_local, (void **)&orig_mp_construct_local) != MH_OK ||
MH_EnableHook(p_construct) != MH_OK) {
log_line("local_mp: failed to install the LocalMP construction hook");
return 0;
}
return 1;
return local_mp_queue_hooks("local_mp_actions", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+323
View File
@@ -0,0 +1,323 @@
/*
* Ground Arcade air events (fighter/attacker/bomber killstreaks) on a LocalMP host.
*
* Four gaps keep stock Ground Arcade air events from running in LocalMP:
* 1. prepare_local_mission clears MissionSettings.useKillStreaks during LocalMP setup.
* 2. Local AI kills go through local_mp_kills.c and do not advance native killstreak counters.
* 3. BombingKillStreakEvent::switchPlayerUnit spawns the aircraft only by broadcasting
* UnitRespawn (0xf030) through mpi::sendto, which has no local receiver on a LocalMP host.
* 4. If a LocalMP air-event respawn ever supplies a ground-level pose, we rebuild an airborne
* approach using the stock gameplay.blk spawnPos parameters for the match rank.
*/
#include "hooks.h"
#include "hook_config.h"
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include "local_mp_values.h"
#include <windows.h>
#include <math.h>
#include <stddef.h>
#include <string.h>
typedef struct LocalMpAirSpawn {
double position[3];
float orientation[4];
float velocity[3];
uint8_t options[0x14];
} LocalMpAirSpawn;
C_ASSERT(offsetof(LocalMpAirSpawn, orientation) == 0x18);
C_ASSERT(offsetof(LocalMpAirSpawn, velocity) == 0x28);
C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);
typedef void (__fastcall *PrepareLocalMissionFn)(void *mission);
typedef void (__fastcall *AddKillStreakPointsFn)(uint8_t *player, uint32_t rule, int32_t points, int32_t related_rule);
typedef void (__fastcall *SwitchPlayerUnitFn)(void *event_mgr, void *participant, uint8_t to_air);
typedef void (__fastcall *SendUnitRespawnFn)(uint8_t *unit, const LocalMpAirSpawn *spawn);
typedef void (__fastcall *MpiSendToFn)(void *message, uint8_t recipient);
typedef uint64_t (__fastcall *UnitOnEventFn)(void *unit, const void *event, void *arg3, void *arg4);
typedef void (__fastcall *GetBattleCenterFn)(float center[2]);
typedef uint8_t (__fastcall *GetTerrainHeightFn)(const void *terrain, float x, float z, float *height,
void *normal, void *material);
typedef void (__fastcall *GetOrientationFn)(float quaternion[4], const float transform[12]);
static PrepareLocalMissionFn orig_prepare_local_mission;
static SwitchPlayerUnitFn orig_switch_player_unit;
static SendUnitRespawnFn orig_send_unit_respawn;
static MpiSendToFn orig_mpi_sendto;
static __declspec(thread) int g_in_air_event_switch;
static __declspec(thread) uint8_t *g_respawn_unit;
static int g_air_events_active;
static int g_credit_log_count;
enum { AIR_EVENT_CREDIT_LOG_LIMIT = 12 };
static int ground_arcade_air_events_enabled(void)
{
const uint8_t *settings = g_local_mp_mission_settings;
const char *mode;
if (!g_air_events_active || settings == NULL || !local_mp_is_host())
return 0;
if (*g_lmp.use_kill_streaks != 1)
return 0;
mode = *(const char *const *)(settings + LMP_MIS_OFF_MODE_NAME);
return mode != NULL && strcmp(mode, "tank_event_in_random_battles_arcade") == 0;
}
/* Resolve a killstreak tag id through Dagor's FastNameMap string table layout. */
static const char *kill_streak_rule_tag(uint32_t id)
{
const uint8_t *nm = g_lmp.kill_streak_name_map;
const uint64_t *entries;
uint32_t count, packed, page, page_count;
unsigned shift;
const uint8_t *pages, *page_slot;
const char *strings;
if (nm == NULL)
return NULL;
entries = *(const uint64_t *const *)(nm + LMP_NAMEMAP_OFF_ENTRIES);
count = *(const uint32_t *)(nm + LMP_NAMEMAP_OFF_COUNT);
shift = nm[LMP_NAMEMAP_OFF_SHIFT];
if (entries == NULL || id >= count || shift >= 32u)
return NULL;
packed = (uint32_t)entries[id];
page = packed >> shift;
page_count = *(const uint32_t *)(nm + LMP_NAMEMAP_OFF_PAGE_COUNT);
pages = *(const uint8_t *const *)(nm + LMP_NAMEMAP_OFF_PAGES);
if (page == page_count)
page_slot = nm + LMP_NAMEMAP_OFF_TAIL_PAGE;
else if (page < page_count && pages != NULL)
page_slot = pages + (size_t)page * 16u;
else
return NULL;
strings = *(const char *const *)page_slot;
return strings != NULL ? strings + (packed & ((1u << shift) - 1u)) : NULL;
}
static int is_air_event_tag(const char *tag)
{
return tag != NULL && (strcmp(tag, "fighter") == 0 || strcmp(tag, "attacker") == 0 || strcmp(tag, "bomber") == 0);
}
static float surface_height(const void *terrain, float x, float z)
{
float height = 0.0f;
GetTerrainHeightFn query = (GetTerrainHeightFn)g_lmp.air_event_terrain_height;
if (query != NULL && query(terrain, x, z, &height, NULL, NULL) && isfinite(height) && height > 0.0f)
return height;
return 0.0f;
}
/* Read stock spawn distance, altitude and speed from gameplay.blk's spawnPos table for this rank. */
static int lookup_stock_spawn_params(float *out_dist, float *out_alt, float *out_speed_mps)
{
const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
const uint8_t *rules;
uint32_t rule_count, i;
int32_t rank;
if (gameplay == NULL || g_lmp.mission_max_rank == NULL || LMP_KS_SPAWN_POS_STRIDE < 0x50u)
return 0;
rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
rank = *(const int32_t *)g_lmp.mission_max_rank;
if (rules == NULL || rule_count > 256u)
return 0;
for (i = 0; i < rule_count; i++) {
const uint8_t *rule = rules + (size_t)i * LMP_KS_RULE_STRIDE;
const char *tag = kill_streak_rule_tag(*(const uint32_t *)(rule + LMP_KS_RULE_OFF_TAG));
const uint8_t *table;
uint32_t count, j;
if (tag == NULL || (strcmp(tag, "attacker") != 0 && strcmp(tag, "bomber") != 0))
continue;
table = *(const uint8_t *const *)(rule + LMP_KS_RULE_OFF_SPAWN_POS);
count = *(const uint32_t *)(rule + LMP_KS_RULE_OFF_SPAWN_POS_CNT);
if (table == NULL || count > 64u)
continue;
for (j = 0; j < count; j++) {
const uint8_t *row = table + (size_t)j * LMP_KS_SPAWN_POS_STRIDE;
int32_t min_r = *(const int32_t *)(row + LMP_KS_SP_OFF_MIN_RANK);
int32_t max_r = *(const int32_t *)(row + LMP_KS_SP_OFF_MAX_RANK);
if (rank >= min_r && rank <= max_r) {
float dist = *(const float *)(row + LMP_KS_SP_OFF_INIT_DIST);
float alt = *(const float *)(row + LMP_KS_SP_OFF_INIT_ALT);
float kmh = *(const float *)(row + LMP_KS_SP_OFF_INIT_SPEED_KMH);
if (isfinite(dist) && dist > 100.0f && isfinite(alt) && alt > 100.0f && isfinite(kmh) && kmh > 50.0f) {
*out_dist = dist;
*out_alt = alt;
*out_speed_mps = kmh / 3.6f;
return 1;
}
}
}
}
return 0;
}
/* Rebuild an airborne pose from stock gameplay.blk spawnPos only when LocalMP supplied a surface pose. */
static int repair_air_spawn_if_invalid(LocalMpAirSpawn *spawn)
{
const uint8_t *app = g_local_mp_app ? *g_local_mp_app : NULL;
const void *terrain = app ? *(const void *const *)(app + LMP_APP_OFF_TERRAIN) : NULL;
float x = (float)spawn->position[0], y = (float)spawn->position[1], z = (float)spawn->position[2];
float dx = spawn->velocity[0], dz = spawn->velocity[2];
float speed = sqrtf(dx * dx + dz * dz);
int valid_speed = isfinite(speed) && speed >= 25.0f;
float center[2], approach, alt, stock_speed, highest = 0.0f;
float transform[12];
unsigned i;
if (terrain == NULL || *(const void *const *)(app + LMP_APP_OFF_SCORE_RULES) == NULL)
return 0;
if (valid_speed && fabsf(x) < 1e7f && fabsf(z) < 1e7f && isfinite(y) &&
y >= surface_height(terrain, x, z) + 100.0f)
return 0;
if (!lookup_stock_spawn_params(&approach, &alt, &stock_speed))
return 0;
((GetBattleCenterFn)g_lmp.air_event_battle_center)(center);
if (!isfinite(center[0]) || !isfinite(center[1]))
return 0;
dx = valid_speed ? dx / speed : 1.0f;
dz = valid_speed ? dz / speed : 0.0f;
for (i = 0; i <= 14u; i++) {
float d = approach * (float)i / 14.0f;
float h = surface_height(terrain, center[0] - dx * d, center[1] - dz * d);
if (h > highest)
highest = h;
}
x = center[0] - dx * approach;
y = highest + alt;
z = center[1] - dz * approach;
speed = valid_speed ? speed : stock_speed;
memset(transform, 0, sizeof(transform));
transform[0] = dx; transform[2] = dz; transform[4] = 1.0f;
transform[6] = -dz; transform[8] = dx;
transform[9] = x; transform[10] = y; transform[11] = z;
((GetOrientationFn)g_lmp.air_event_orientation)(spawn->orientation, transform);
spawn->position[0] = x;
spawn->position[1] = y;
spawn->position[2] = z;
spawn->velocity[0] = dx * speed;
spawn->velocity[1] = 0.0f;
spawn->velocity[2] = dz * speed;
return 1;
}
static void __fastcall hook_prepare_local_mission(void *mission)
{
int restore = ground_arcade_air_events_enabled();
orig_prepare_local_mission(mission);
if (restore && local_mp_is_host()) {
*g_lmp.use_kill_streaks = 1;
log_line("local_mp: preserved MissionSettings.useKillStreaks for Ground Arcade");
}
}
static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
{
int previous = g_in_air_event_switch;
if (to_air != 0 && ground_arcade_air_events_enabled())
g_in_air_event_switch = 1;
orig_switch_player_unit(event_mgr, participant, to_air);
g_in_air_event_switch = previous;
}
static void __fastcall hook_send_unit_respawn(uint8_t *unit, const LocalMpAirSpawn *spawn)
{
uint8_t *previous;
__declspec(align(16)) LocalMpAirSpawn recovered;
if (!g_in_air_event_switch || unit == NULL || spawn == NULL || !ground_arcade_air_events_enabled()) {
orig_send_unit_respawn(unit, spawn);
return;
}
previous = g_respawn_unit;
g_respawn_unit = unit;
recovered = *spawn;
if (repair_air_spawn_if_invalid(&recovered)) {
log_line("local_mp: rebuilt Ground Arcade air spawn from (%.1f, %.1f, %.1f) to (%.1f, %.1f, %.1f)",
spawn->position[0], spawn->position[1], spawn->position[2],
recovered.position[0], recovered.position[1], recovered.position[2]);
spawn = &recovered;
}
orig_send_unit_respawn(unit, spawn);
g_respawn_unit = previous;
}
static void __fastcall hook_mpi_sendto(void *message, uint8_t recipient)
{
uint8_t *unit = g_respawn_unit;
const uint8_t *packet = (const uint8_t *)message;
if (unit == NULL || recipient != 0xffu || packet == NULL ||
*(uint8_t *const *)(packet + LMP_MPI_MSG_OFF_OBJ) != unit ||
*(const uint16_t *)(packet + LMP_MPI_MSG_OFF_ID) != LMP_MPI_MSG_UNIT_RESPAWN) {
orig_mpi_sendto(message, recipient);
return;
}
/* Clear scope while delivering so nested messages follow the normal mpi::sendto path. */
g_respawn_unit = NULL;
((UnitOnEventFn)g_lmp.unit_on_event)(unit, message, NULL, NULL);
g_respawn_unit = unit;
}
void local_mp_credit_air_event_kill(uint8_t *player, int aircraft_victim)
{
const uint8_t *gameplay, *rules, *progress;
uint32_t rule_count, player_rule_count, i;
AddKillStreakPointsFn add_points = (AddKillStreakPointsFn)g_lmp.add_kill_streak_points;
if (add_points == NULL || player == NULL || !ground_arcade_air_events_enabled())
return;
gameplay = *(const uint8_t *const *)g_lmp.gameplay;
progress = *(const uint8_t *const *)(player + LMP_MP_OFF_KS_PROGRESS + LMP_TAB_OFF_DATA);
player_rule_count = *(const uint32_t *)(player + LMP_MP_OFF_KS_PROGRESS + LMP_TAB_OFF_COUNT);
if (gameplay == NULL || progress == NULL || player_rule_count == 0u)
return;
rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
if (rules == NULL || rule_count > 256u || player_rule_count > rule_count)
return;
for (i = 0; i < player_rule_count; i++) {
const uint8_t *rule = rules + (size_t)i * LMP_KS_RULE_STRIDE;
const char *tag = kill_streak_rule_tag(*(const uint32_t *)(rule + LMP_KS_RULE_OFF_TAG));
int32_t points;
if (!is_air_event_tag(tag))
continue;
points = *(const int32_t *)(rule + (aircraft_victim ? LMP_KS_RULE_OFF_AIR_AI_MULT : LMP_KS_RULE_OFF_GROUND_AI_MULT));
if (points > 0) {
add_points(player, i, points, -1);
if (g_credit_log_count < AIR_EVENT_CREDIT_LOG_LIMIT) {
++g_credit_log_count;
log_line("local_mp: Ground Arcade air event %s +%d (counter %u)", tag, (int)points,
(unsigned)progress[(size_t)i * LMP_KS_PROGRESS_STRIDE]);
}
}
}
}
int install_local_mp_air_event_hooks(void)
{
const LocalMpHookSpec hooks[] = {
{ "prepare_local_mission", g_lmp.prepare_local_mission, (void *)&hook_prepare_local_mission, (void **)&orig_prepare_local_mission },
{ "air_event_switch_unit", g_lmp.air_event_switch_unit, (void *)&hook_switch_player_unit, (void **)&orig_switch_player_unit },
{ "send_unit_respawn", g_lmp.send_unit_respawn, (void *)&hook_send_unit_respawn, (void **)&orig_send_unit_respawn },
{ "mpi_sendto", g_lmp.mpi_sendto, (void *)&hook_mpi_sendto, (void **)&orig_mpi_sendto },
};
if (!local_mp_queue_hooks("local_mp_air_events", hooks, sizeof(hooks) / sizeof(hooks[0])))
return 0;
g_air_events_active = 1;
return 1;
}
+16 -1
View File
@@ -1,5 +1,5 @@
/*
* Reports the local player's combat events to the GUI scripts.
* Reports the local player's combat events and confirmed airfield departures to the GUI scripts.
*
* Online, the battle server prices every combat event and sends it to the client
* (packet 0xb03d -> GameSaveData::addScoreMessage), which raises the HUD script event
@@ -95,6 +95,21 @@ void local_mp_report_nuclear_strike(void)
fn_blk_dtor(blk);
}
void local_mp_report_airfield_spawn(const char *unit_name, int32_t base_id)
{
__declspec(align(16)) uint8_t blk[LMP_BLK_SIZE];
uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL;
if (gsd == NULL || fn_hud_notify_script == NULL || unit_name == NULL || base_id < 0)
return;
memset(blk, 0, sizeof(blk));
fn_blk_ctor(blk);
fn_blk_set_str(blk, "unitName", unit_name);
blk_set_int(blk, "baseId", base_id);
fn_hud_notify_script(gsd + LMP_GSD_OFF_HUD_QUEUE, "wtoLocalMpAirfieldSpawn", blk);
fn_blk_dtor(blk);
}
int install_local_mp_award_hooks(void)
{
g_game_save_data = (uint8_t **)g_lmp.game_save_data;
+38 -1
View File
@@ -6,6 +6,7 @@
#include "hook_config.h"
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include "MinHook.h"
#include <string.h>
@@ -131,16 +132,17 @@ typedef struct LocalMpModule {
} LocalMpModule;
static const LocalMpModule MODULES[] = {
{ "local_mp_awards", install_local_mp_award_hooks },
{ "local_mp_players", install_local_mp_player_hooks },
{ "local_mp_loadout", install_local_mp_loadout_hooks },
{ "local_mp_actions", install_local_mp_action_hooks },
{ "local_mp_awards", install_local_mp_award_hooks },
{ "local_mp_scores", install_local_mp_score_reader },
{ "local_mp_kills", install_local_mp_kill_hooks },
{ "local_mp_events", install_local_mp_event_hooks },
{ "local_mp_nuke", install_local_mp_nuke_hooks },
{ "local_mp_support", install_local_mp_support_hooks },
{ "local_mp_damage_notifications", install_local_mp_damage_notification_hooks },
{ "local_mp_air_events", install_local_mp_air_event_hooks },
};
static void use_core_values(void)
@@ -162,10 +164,38 @@ static void use_core_values(void)
g_lmp_datablock_get_str = (LmpDataBlockGetStrFn)g_lmp.datablock_get_str;
}
int local_mp_queue_hooks(const char *module, const LocalMpHookSpec *specs, size_t count)
{
size_t created = 0;
while (created < count) {
MH_STATUS status = MH_CreateHook(specs[created].target, specs[created].detour, specs[created].original);
if (status != MH_OK) {
log_line("local_mp: %s hook %s MH_CreateHook failed (%s)",
module, specs[created].name, MH_StatusToString(status));
goto failed;
}
++created;
status = MH_QueueEnableHook(specs[created - 1].target);
if (status != MH_OK) {
log_line("local_mp: %s hook %s MH_QueueEnableHook failed (%s)",
module, specs[created - 1].name, MH_StatusToString(status));
goto failed;
}
}
return 1;
failed:
while (created != 0)
MH_RemoveHook(specs[--created].target);
return 0;
}
void install_local_mp_hooks(void)
{
size_t i;
unsigned installed = 0;
MH_STATUS status;
if (!config_native_matches_executable()) {
log_line("local_mp: wto_ws.cfg was built for another aces.exe, LocalMP bridge disabled");
@@ -184,5 +214,12 @@ void install_local_mp_hooks(void)
else
log_line("local_mp: %s failed to install its hooks", MODULES[i].name);
}
if (installed > 0) {
status = MH_ApplyQueued();
if (status != MH_OK) {
log_line("local_mp: MH_ApplyQueued failed (%s), LocalMP hooks not enabled", MH_StatusToString(status));
return;
}
}
log_line("local_mp: %u of %u LocalMP modules installed", installed, (unsigned)(sizeof(MODULES) / sizeof(MODULES[0])));
}
@@ -1,11 +1,11 @@
/*
* Bind the stock damage and control-loss HUD notices to the unit they describe on a LocalMP host.
* The native damage and firing handlers retain their normal effects.
* Bind self damage, avionics failure and hit-parts feedback to the local player on a LocalMP host.
* All native damage, avionics failure and firing effects remain unchanged for every unit.
*/
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include "local_mp_values.h"
#include "hook_config.h"
#include "MinHook.h"
typedef uint8_t (__fastcall *BarrelDamageFn)(void *damage, const uint8_t *impact);
typedef void (__fastcall *FireUpdateFn)(
@@ -15,18 +15,15 @@ typedef void (__fastcall *DeliverHudFn)(
int32_t type, int32_t id, int32_t arg3, int32_t arg4, int32_t arg5,
float arg6, float arg7, uint8_t arg8);
typedef void (__fastcall *DeliverDamageHudFn)(int32_t type, int32_t text_id, int32_t id);
typedef void (__fastcall *AvionicsDamageFn)(const uint8_t *component, uint32_t kind);
typedef uint64_t (__fastcall *ExitOpticViewFn)(void *camera, int32_t arg2, uint8_t arg3);
typedef uint64_t (__fastcall *UnitOnEventFn)(void *unit, const uint8_t *event, void *arg3, void *arg4);
typedef void (__fastcall *HitPartsFeedbackFn)(void *hud, const uint8_t *victim, const void *info);
typedef const uint8_t *(__fastcall *ControlledUnitFn)(const uint8_t *mplayer);
/* HUD message types, registered in the stock hudMessages module. */
enum { HUD_MSG_DAMAGE = 4, HUD_MSG_EVENT = 9 };
/*
* Control-loss hints of aircraft and helicopters: indices 261..283 in the stock HUD text table
* (tail, wing and flight controls, weapon and guided-weapon control, sensors, radar, RWR, TWS,
* optics, targeting pod, countermeasures, laser designator, night vision, indicators, snapped-off
* surfaces). The stock code emits them from the current hero unit's module state.
*/
enum { CONTROL_HINT_FIRST = 261, CONTROL_HINT_LAST = 283 };
/* Diagnostics are bounded so a long battle cannot flood the run log. */
enum { SUPPRESSED_LOG_LIMIT = 12 };
@@ -37,13 +34,77 @@ typedef struct DamageNotice {
int32_t id;
} DamageNotice;
/* Both producers deliver synchronously. Keep nested events and simulation threads independent. */
/* All hooked producers deliver synchronously; thread-local slots keep nested calls isolated. */
static __declspec(thread) const DamageNotice *active_notice;
static __declspec(thread) const uint8_t *active_avionics_unit;
static __declspec(thread) const uint8_t *active_hit_event;
static BarrelDamageFn original_barrel_damage;
static FireUpdateFn original_fire_update;
static DeliverHudFn original_deliver_hud;
static DeliverDamageHudFn original_damage_deliver_hud;
static int suppressed_logged;
static AvionicsDamageFn original_avionics_damage;
static ExitOpticViewFn original_exit_optic_view;
static UnitOnEventFn original_unit_on_event;
static HitPartsFeedbackFn original_enqueue_enemy_parts;
static HitPartsFeedbackFn original_hit_cam_important;
static HitPartsFeedbackFn original_naval_hit_state;
static int suppressed_avionics_logged;
static int suppressed_optic_logged;
static int suppressed_parts_logged;
/* The unit the local player's MPlayer controls, falling back to g_hero when MPlayer is absent. */
static const uint8_t *local_controlled_unit(void)
{
const uint8_t *mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL;
const uint8_t *unit = mplayer != NULL ? (const uint8_t *)((ControlledUnitFn)g_lmp.mplayer_controlled_unit)(mplayer) : NULL;
if (unit != NULL)
return unit;
return g_local_mp_hero != NULL ? *g_local_mp_hero : NULL;
}
static int is_local_controlled_unit(const uint8_t *unit)
{
const uint8_t *controlled;
if (unit == NULL)
return 0;
controlled = local_controlled_unit();
return controlled != NULL && unit == controlled;
}
static int is_controlled_damage(const DamageNotice *notice)
{
uintptr_t unit;
if (notice->context == NULL)
return 0;
unit = *(const uintptr_t *)(notice->context + notice->unit_offset) & ~notice->unit_tag;
return is_local_controlled_unit((const uint8_t *)unit);
}
/*
* Enemy parts-list and hit-camera special-event feedback belong to the local player's own attacks
* (including in-flight munitions fired before switching to a drone or support plane) or to the
* watched unit while spectating.
*/
static int is_local_or_watched_attacker(const uint8_t *offender)
{
const uint8_t *owner_mp;
const uint8_t *watched;
if (offender == NULL)
return 0;
if (is_local_controlled_unit(offender))
return 1;
owner_mp = *(const uint8_t *const *)(offender + LMP_UNIT_OFF_MPLAYER);
if (local_mp_is_local_mplayer(owner_mp))
return 1;
watched = g_lmp.watched_hero != NULL ? *(const uint8_t *const *)g_lmp.watched_hero : NULL;
return watched != NULL && offender == watched;
}
static uint8_t __fastcall hook_barrel_damage(void *damage, const uint8_t *impact)
{
@@ -72,24 +133,6 @@ static void __fastcall hook_fire_update(
active_notice = previous;
}
/* The unit the local player's MPlayer controls, as the stock lookup resolves it. */
static const uint8_t *local_controlled_unit(void)
{
const uint8_t *mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL;
return mplayer != NULL ? (const uint8_t *)((ControlledUnitFn)g_lmp.mplayer_controlled_unit)(mplayer) : NULL;
}
static int is_controlled_damage(const DamageNotice *notice)
{
uintptr_t unit;
if (notice->context == NULL)
return 0;
unit = *(const uintptr_t *)(notice->context + notice->unit_offset) & ~notice->unit_tag;
return unit != 0 && (const uint8_t *)unit == local_controlled_unit();
}
static void __fastcall hook_deliver_hud(
int32_t type, int32_t id, int32_t arg3, int32_t arg4, int32_t arg5,
float arg6, float arg7, uint8_t arg8)
@@ -103,54 +146,117 @@ static void __fastcall hook_deliver_hud(
}
/*
* The control-loss hints describe the unit in the stock hero manager's current-hero cell. That cell
* is one process-wide slot, and on a LocalMP host the local HUD can be handed another unit's hints.
* Drop a hint whose described unit is not the one the local player controls; the local player's own
* hints stay untouched.
* Track the unit whose avionics/electronics component is failing. The stock dispatcher checks the
* unit's hero flag only for night-vision failure and emits HUD_MSG_DAMAGE (and optic-view exits)
* unconditionally for all other cases (guidance, sensors, radar, RWR, TWS, optics, targeting pod,
* laser designator, indicators).
*/
static void __fastcall hook_avionics_damage(const uint8_t *component, uint32_t kind)
{
const uint8_t *previous = active_avionics_unit;
if (component != NULL && local_mp_is_host())
active_avionics_unit = *(const uint8_t *const *)(component + g_lmp.avionics_unit);
original_avionics_damage(component, kind);
active_avionics_unit = previous;
}
static void __fastcall hook_deliver_damage_hud(int32_t type, int32_t text_id, int32_t id)
{
if (type == HUD_MSG_DAMAGE && text_id >= CONTROL_HINT_FIRST && text_id <= CONTROL_HINT_LAST
&& local_mp_is_host()) {
const uint8_t *described = g_lmp.hero_unit != NULL ? *(const uint8_t *const *)g_lmp.hero_unit : NULL;
const uint8_t *controlled = local_controlled_unit();
const uint8_t *unit = active_avionics_unit;
if (described != NULL && controlled != NULL && described != controlled) {
if (suppressed_logged < SUPPRESSED_LOG_LIMIT) {
++suppressed_logged;
log_line("local_mp: dropped control hint %d of a unit the local player does not control",
(int)text_id);
}
return;
if (unit != NULL && type == HUD_MSG_DAMAGE && local_mp_is_host() && !is_local_controlled_unit(unit)) {
if (suppressed_avionics_logged < SUPPRESSED_LOG_LIMIT) {
++suppressed_avionics_logged;
log_line("local_mp: dropped avionics damage notice %d of a non-local unit", (int)text_id);
}
return;
}
original_damage_deliver_hud(type, text_id, id);
}
static uint64_t __fastcall hook_exit_optic_view(void *camera, int32_t arg2, uint8_t arg3)
{
const uint8_t *unit = active_avionics_unit;
if (unit != NULL && local_mp_is_host() && !is_local_controlled_unit(unit)) {
if (suppressed_optic_logged < 4) {
++suppressed_optic_logged;
log_line("local_mp: prevented optic view exit triggered by a non-local unit");
}
return 0;
}
return original_exit_optic_view(camera, arg2, arg3);
}
static uint64_t __fastcall hook_unit_on_event(void *unit, const uint8_t *event, void *arg3, void *arg4)
{
const uint8_t *previous = active_hit_event;
uint64_t result;
if (event != NULL && local_mp_is_host())
active_hit_event = event;
result = original_unit_on_event(unit, event, arg3, arg4);
active_hit_event = previous;
return result;
}
static int should_drop_hit_parts_feedback(void)
{
const uint8_t *event = active_hit_event;
const uint8_t *offender;
if (event == NULL || !local_mp_is_host())
return 0;
offender = *(const uint8_t *const *)(event + g_lmp.hit_event_offender);
if (is_local_or_watched_attacker(offender))
return 0;
if (suppressed_parts_logged < SUPPRESSED_LOG_LIMIT) {
++suppressed_parts_logged;
log_line("local_mp: dropped enemy parts feedback from a non-local attacker");
}
return 1;
}
static void __fastcall hook_enqueue_enemy_parts(void *hud, const uint8_t *victim, const void *info)
{
if (should_drop_hit_parts_feedback())
return;
original_enqueue_enemy_parts(hud, victim, info);
}
static void __fastcall hook_hit_cam_important(void *hud, const uint8_t *victim, const void *info)
{
if (should_drop_hit_parts_feedback())
return;
original_hit_cam_important(hud, victim, info);
}
static void __fastcall hook_naval_hit_state(void *hud, const uint8_t *victim, const void *info)
{
if (should_drop_hit_parts_feedback())
return;
original_naval_hit_state(hud, victim, info);
}
int install_local_mp_damage_notification_hooks(void)
{
const struct { void *target, *detour, **original; } hooks[] = {
{ g_lmp.barrel_notice_deliver, (void *)&hook_deliver_hud, (void **)&original_deliver_hud },
{ g_lmp.barrel_damage, (void *)&hook_barrel_damage, (void **)&original_barrel_damage },
{ g_lmp.breech_fire_update, (void *)&hook_fire_update, (void **)&original_fire_update },
{ g_lmp.hud_damage_deliver, (void *)&hook_deliver_damage_hud, (void **)&original_damage_deliver_hud },
const LocalMpHookSpec hooks[] = {
{ "barrel_notice_deliver", g_lmp.barrel_notice_deliver, (void *)&hook_deliver_hud, (void **)&original_deliver_hud },
{ "barrel_damage", g_lmp.barrel_damage, (void *)&hook_barrel_damage, (void **)&original_barrel_damage },
{ "breech_fire_update", g_lmp.breech_fire_update, (void *)&hook_fire_update, (void **)&original_fire_update },
{ "hud_damage_deliver", g_lmp.hud_damage_deliver, (void *)&hook_deliver_damage_hud, (void **)&original_damage_deliver_hud },
{ "avionics_damage", g_lmp.avionics_damage, (void *)&hook_avionics_damage, (void **)&original_avionics_damage },
{ "avionics_exit_optic", g_lmp.avionics_exit_optic, (void *)&hook_exit_optic_view, (void **)&original_exit_optic_view },
{ "unit_on_event", g_lmp.unit_on_event, (void *)&hook_unit_on_event, (void **)&original_unit_on_event },
{ "enqueue_enemy_parts", g_lmp.enqueue_enemy_parts, (void *)&hook_enqueue_enemy_parts, (void **)&original_enqueue_enemy_parts },
{ "hit_cam_important", g_lmp.hit_cam_important, (void *)&hook_hit_cam_important, (void **)&original_hit_cam_important },
{ "naval_hit_state", g_lmp.naval_hit_state, (void *)&hook_naval_hit_state, (void **)&original_naval_hit_state },
};
size_t created = 0;
if (g_lmp.barrel_notice_deliver != g_lmp.breech_notice_deliver)
if (g_lmp.barrel_notice_deliver != g_lmp.breech_notice_deliver) {
log_line("local_mp: local_mp_damage_notifications skipped: barrel and breech deliver addresses differ");
return 0;
while (created < sizeof(hooks) / sizeof(hooks[0])) {
if (MH_CreateHook(hooks[created].target, hooks[created].detour, hooks[created].original) != MH_OK)
goto failed;
++created;
if (MH_QueueEnableHook(hooks[created - 1].target) != MH_OK)
goto failed;
}
if (MH_ApplyQueued() == MH_OK)
return 1;
failed:
while (created != 0)
MH_RemoveHook(hooks[--created].target);
return 0;
return local_mp_queue_hooks("local_mp_damage_notifications", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+9 -22
View File
@@ -226,27 +226,14 @@ static void __fastcall hook_dispatch_naval_damage(int64_t uid, uint8_t *victim,
int install_local_mp_event_hooks(void)
{
uint8_t *p_igm_ass = g_lmp.iground_award_assists;
uint8_t *p_assist = g_lmp.dispatch_assist;
uint8_t *p_cap = g_lmp.dispatch_capture_zone;
uint8_t *p_hit = g_lmp.dispatch_hit_crit;
uint8_t *p_sev = g_lmp.dispatch_severe_damage;
uint8_t *p_nav = g_lmp.dispatch_naval_damage;
const LocalMpHookSpec hooks[] = {
{ "iground_award_assists", g_lmp.iground_award_assists, (void *)&hook_iground_award_assists, (void **)&orig_iground_award_assists },
{ "dispatch_assist", g_lmp.dispatch_assist, (void *)&hook_dispatch_assist, (void **)&orig_dispatch_assist },
{ "dispatch_capture_zone", g_lmp.dispatch_capture_zone, (void *)&hook_dispatch_capture_zone, (void **)&orig_dispatch_capture_zone },
{ "dispatch_hit_crit", g_lmp.dispatch_hit_crit, (void *)&hook_dispatch_hit_crit, (void **)&orig_dispatch_hit_crit },
{ "dispatch_severe_damage", g_lmp.dispatch_severe_damage, (void *)&hook_dispatch_severe_damage, (void **)&orig_dispatch_severe_damage },
{ "dispatch_naval_damage", g_lmp.dispatch_naval_damage, (void *)&hook_dispatch_naval_damage, (void **)&orig_dispatch_naval_damage },
};
if (MH_CreateHook(p_igm_ass, (void *)&hook_iground_award_assists, (void **)&orig_iground_award_assists) != MH_OK ||
MH_EnableHook(p_igm_ass) != MH_OK ||
MH_CreateHook(p_assist, (void *)&hook_dispatch_assist, (void **)&orig_dispatch_assist) != MH_OK ||
MH_EnableHook(p_assist) != MH_OK ||
MH_CreateHook(p_cap, (void *)&hook_dispatch_capture_zone, (void **)&orig_dispatch_capture_zone) != MH_OK ||
MH_EnableHook(p_cap) != MH_OK ||
MH_CreateHook(p_hit, (void *)&hook_dispatch_hit_crit, (void **)&orig_dispatch_hit_crit) != MH_OK ||
MH_EnableHook(p_hit) != MH_OK ||
MH_CreateHook(p_sev, (void *)&hook_dispatch_severe_damage, (void **)&orig_dispatch_severe_damage) != MH_OK ||
MH_EnableHook(p_sev) != MH_OK ||
MH_CreateHook(p_nav, (void *)&hook_dispatch_naval_damage, (void **)&orig_dispatch_naval_damage) != MH_OK ||
MH_EnableHook(p_nav) != MH_OK) {
log_line("local_mp: failed to install combat event hooks");
return 0;
}
return 1;
return local_mp_queue_hooks("local_mp_events", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+15 -2
View File
@@ -58,15 +58,17 @@ char *local_mp_strdup(const char *s);
const char *local_mp_unit_name(const uint8_t *unit);
/* Player state & slot tracking notifications shared with loadout module. */
void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int is_silent);
void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t base_id, int is_silent);
/* Combat event reporting to the GUI scripts (local_mp_awards.c). */
/* Local player events sent to the GUI scripts (local_mp_awards.c). */
void local_mp_report_award_event(const LocalMpAwardEvent *ev);
void local_mp_report_nuclear_strike(void);
void local_mp_report_airfield_spawn(const char *unit_name, int32_t base_id);
/* A destroyed unit that is some player's mission support unit: its reference is freed once the
* player has been given back control (local_mp_support.c). */
void local_mp_support_unit_dead(const uint8_t *victim);
void local_mp_credit_air_event_kill(uint8_t *player, int aircraft_victim);
const char *local_mp_unit_exp_class(const uint8_t *unit);
/* Mission scores of combat events from the mission settings (local_mp_scores.c). */
@@ -82,6 +84,16 @@ void local_mp_add_mplayer_score(uint8_t *mp, float delta, uint32_t event_id);
void local_mp_mark_mplayer_dirty(uint8_t *mp);
void local_mp_inc_mplayer_stat(uint8_t *mp, size_t off);
/* Hook descriptor queued by a LocalMP module and enabled in a single batch by local_mp_core.c. */
typedef struct LocalMpHookSpec {
const char *name;
void *target;
void *detour;
void **original;
} LocalMpHookSpec;
int local_mp_queue_hooks(const char *module, const LocalMpHookSpec *specs, size_t count);
/* Module hook installers, called by install_local_mp_hooks() once the module's values are loaded. */
int install_local_mp_player_hooks(void);
int install_local_mp_loadout_hooks(void);
@@ -93,3 +105,4 @@ int install_local_mp_score_reader(void);
int install_local_mp_nuke_hooks(void);
int install_local_mp_support_hooks(void);
int install_local_mp_damage_notification_hooks(void);
int install_local_mp_air_event_hooks(void);
+7 -10
View File
@@ -95,6 +95,8 @@ static void record_enemy_kill(uint8_t *killer_mp, uint8_t *victim, int is_pvp)
if (local_mp_is_local_mplayer(killer_mp)) {
LocalMpAwardEvent award = { ev, victim, is_pvp, 0, own_sev ? "from_severe_damage" : NULL, 0 };
if (!is_ship && !is_human)
local_mp_credit_air_event_kill(killer_mp, is_air);
local_mp_report_award_event(&award);
}
}
@@ -192,18 +194,13 @@ static void __fastcall hook_on_unit_dead_once(uint8_t *victim)
int install_local_mp_kill_hooks(void)
{
uint8_t *p_ground_dead = g_lmp.iground_on_dead;
uint8_t *p_dead = g_lmp.on_unit_dead_once;
const LocalMpHookSpec hooks[] = {
{ "iground_on_dead", g_lmp.iground_on_dead, (void *)&hook_iground_on_became_dead, (void **)&orig_iground_on_dead },
{ "on_unit_dead_once", g_lmp.on_unit_dead_once, (void *)&hook_on_unit_dead_once, (void **)&orig_on_unit_dead_once },
};
fn_mplayer_add_score = (MPlayerAddScoreFn)g_lmp.mplayer_add_score;
fn_net_mark_dirty = (NetMarkDirtyFn)g_lmp.net_mark_dirty;
if (MH_CreateHook(p_ground_dead, (void *)&hook_iground_on_became_dead, (void **)&orig_iground_on_dead) != MH_OK ||
MH_EnableHook(p_ground_dead) != MH_OK ||
MH_CreateHook(p_dead, (void *)&hook_on_unit_dead_once, (void **)&orig_on_unit_dead_once) != MH_OK ||
MH_EnableHook(p_dead) != MH_OK) {
log_line("local_mp: failed to install unit-death scoring hooks");
return 0;
}
return 1;
return local_mp_queue_hooks("local_mp_kills", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+7 -17
View File
@@ -1,10 +1,10 @@
/*
* LocalMP vehicle loadout, modification map, decals, 3D attachables, and crew-skill bridge.
* LocalMP vehicle loadout, modification map, decals, and 3D attachables.
*
* The 2.61.0.37 client has no receiver for its own vehicle change request (0xb01d,
* SemChangeAircraftRequest) on a host; hook_sem_change_aircraft_send builds the
* ChangeUnitReflection from the request (weapon, modifications, bullets, skin, decals,
* attachables, crew skills, spawn base) and calls Unit::changeAircraft itself.
* attachables, spawn base) and calls Unit::changeAircraft itself.
*/
#include "hooks.h"
#include "hook_config.h"
@@ -37,7 +37,6 @@ typedef const void *(__fastcall *GetAttachablesBlkFn)(
);
typedef uint64_t (__fastcall *StrHashFnv1Fn)(const char *str, size_t len);
typedef int32_t (__fastcall *NameMapAddNameIdFn)(void *map, const char *str, size_t len, uint64_t hash);
typedef void (__fastcall *CrewSkillsInitFn)(void *crew_skills, void *econ_state, const char *unit_name, float mult);
static SemChangeAircraftSendFn orig_sem_send;
static ReflCtorFn fn_refl_ctor;
@@ -50,7 +49,6 @@ static GetDecalsBlkFn fn_get_decals_blk;
static GetAttachablesBlkFn fn_get_attachables_blk;
static StrHashFnv1Fn fn_str_hash;
static NameMapAddNameIdFn fn_namemap_add;
static CrewSkillsInitFn fn_crew_skills_init;
static void populate_namemap_csv(void *map, const char *csv)
{
@@ -133,7 +131,6 @@ static void __fastcall hook_sem_change_aircraft_send(
{
uint8_t *hero, *mplayer, *econ_state, *req;
const void *bullets_begin, *bullets_end;
void *crew_skills;
int32_t req_slot_id, req_base_id, req_spare_type;
int is_silent;
__declspec(align(16)) uint8_t refl[LMP_REFL_SIZE];
@@ -188,21 +185,20 @@ static void __fastcall hook_sem_change_aircraft_send(
fn_unit_change_aircraft(hero, refl, 1);
fn_refl_dtor(refl);
crew_skills = *(void **)(hero + LMP_UNIT_OFF_CREW_SKILLS);
if (crew_skills != NULL && unit_name != NULL && unit_name[0] != '\0')
fn_crew_skills_init(crew_skills, econ_state, unit_name, 1.0f);
if (mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_PILOT_CONTROL &&
mplayer[LMP_MP_OFF_GUI_STATE] != LMP_GUI_STATE_CA_READY)
g_lmp_set_player_gui_state((int32_t)mplayer[LMP_MP_OFF_PID], LMP_GUI_STATE_CA_READY);
local_mp_players_queue_spawn(req_slot_id, req_spare_type, is_silent);
local_mp_players_queue_spawn(req_slot_id, req_spare_type, req_base_id, is_silent);
log_line("local_mp: configured unit='%s' weapon='%s' slot=%d silent=%d",
unit_name ? unit_name : "", weapon_name ? weapon_name : "", (int)req_slot_id, is_silent);
}
int install_local_mp_loadout_hooks(void)
{
uint8_t *p_sem_send = g_lmp.sem_change_aircraft_send;
const LocalMpHookSpec hooks[] = {
{ "sem_change_aircraft_send", g_lmp.sem_change_aircraft_send, (void *)&hook_sem_change_aircraft_send, (void **)&orig_sem_send },
};
/* The reflection is built in a fixed stack buffer; its bullet sets vector is its last member. */
if (LMP_REFL_OFF_BULLETS_VEC + 0x20u > LMP_REFL_SIZE) {
@@ -220,12 +216,6 @@ int install_local_mp_loadout_hooks(void)
fn_get_attachables_blk = (GetAttachablesBlkFn)g_lmp.get_attachables_blk;
fn_str_hash = (StrHashFnv1Fn)g_lmp.str_hash_fnv1;
fn_namemap_add = (NameMapAddNameIdFn)g_lmp.namemap_add_name_id;
fn_crew_skills_init = (CrewSkillsInitFn)g_lmp.crew_skills_init;
if (MH_CreateHook(p_sem_send, (void *)&hook_sem_change_aircraft_send, (void **)&orig_sem_send) != MH_OK ||
MH_EnableHook(p_sem_send) != MH_OK) {
log_line("local_mp: failed to install SemChangeAircraftRequest::send hook");
return 0;
}
return 1;
return local_mp_queue_hooks("local_mp_loadout", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+7 -13
View File
@@ -129,17 +129,11 @@ static uint64_t __fastcall hook_cta_logic(uint8_t *ctx, void *a2, void *a3, void
int install_local_mp_nuke_hooks(void)
{
uint8_t *p_launch = g_lmp.shell_launch;
uint8_t *p_explode = g_lmp.shell_explode;
uint8_t *p_cta = g_lmp.cta_logic_action;
if (MH_CreateHook(p_launch, (void *)&hook_shell_launch, (void **)&orig_shell_launch) != MH_OK ||
MH_CreateHook(p_explode, (void *)&hook_shell_explode, (void **)&orig_shell_explode) != MH_OK ||
MH_CreateHook(p_cta, (void *)&hook_cta_logic, (void **)&orig_cta_logic) != MH_OK ||
MH_EnableHook(p_launch) != MH_OK ||
MH_EnableHook(p_explode) != MH_OK ||
MH_EnableHook(p_cta) != MH_OK) {
log_line("local_mp: failed to install the nuclear instant-win hooks");
return 0;
}
return 1;
const LocalMpHookSpec hooks[] = {
{ "shell_launch", g_lmp.shell_launch, (void *)&hook_shell_launch, (void **)&orig_shell_launch },
{ "shell_explode", g_lmp.shell_explode, (void *)&hook_shell_explode, (void **)&orig_shell_explode },
{ "cta_logic_action", g_lmp.cta_logic_action, (void *)&hook_cta_logic, (void **)&orig_cta_logic },
};
return local_mp_queue_hooks("local_mp_nuke", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+34 -1
View File
@@ -55,6 +55,10 @@
#define LMP_REQ_OFF_RESP_BASE_ID 0x00b8u
#define LMP_REQ_OFF_SPARE_TYPE 0x00c0u
/* First field of the matching info passed to MPlayer::initFromMatching (0x59ead4 on 2.61.0.37,
* 0x59f7e4 on 2.61.0.58), copied into MPlayer+0xab0 and read by the 0xf10f squad target relay. */
#define LMP_MATCH_INFO_OFF_SQUAD_ID 0x0000u
/* Multiplayer */
#define LMP_MP_MGR_OFF_IS_HOST (g_lmp.mp_is_host)
#define LMP_MP_MGR_OFF_IS_LOCAL_MP (g_lmp.mp_is_local_mp)
@@ -64,6 +68,7 @@
#define LMP_MP_MGR_OFF_CHAT_HOST (g_lmp.mp_chat_host)
/* App and the economic state */
#define LMP_APP_OFF_TERRAIN (g_lmp.app_terrain)
#define LMP_APP_OFF_SCORE_RULES (g_lmp.app_score_rules)
#define LMP_APP_OFF_ECON_HOLDER (g_lmp.app_econ_holder)
#define LMP_ECON_HOLDER_OFF_STATE (g_lmp.econ_state)
@@ -73,6 +78,7 @@
#define LMP_REQ_OFF_SLOT_ID (g_lmp.req_slot_id)
/* MissionSettings and the matching info */
#define LMP_MIS_OFF_MODE_NAME (g_lmp.mis_mode_name)
#define LMP_MIS_OFF_AXIS_COUNTRY (g_lmp.mis_axis_country)
#define LMP_MIS_OFF_ALLIES_COUNTRY (g_lmp.mis_allies_country)
#define LMP_MIS_OFF_ARCADE_COUNTRY (g_lmp.mis_arcade_country)
@@ -125,7 +131,6 @@
#define LMP_UNIT_OFF_INFO (g_lmp.unit_info)
#define LMP_UNIT_INFO_OFF_NAME (g_lmp.unit_info_name)
#define LMP_UNIT_INFO_OFF_EXP_CLASS (g_lmp.unit_info_exp_class)
#define LMP_UNIT_OFF_CREW_SKILLS (g_lmp.unit_crew_skills)
#define LMP_UNIT_VTF_CHOOSE_OFFENDER (g_lmp.unit_vtf_choose_offender)
#define LMP_UNIT_OFF_SKIP_KILL (g_lmp.unit_skip_kill)
#define LMP_IGM_OFF_OFFENDERS_PTR (g_lmp.igm_offenders)
@@ -170,3 +175,31 @@
/* GameSaveData HUD script event queue */
#define LMP_GSD_OFF_HUD_QUEUE (g_lmp.gsd_hud_queue)
/* Ground Arcade air events: DagorEngine library layouts (mpi::Message, FastNameMap) and captured
* gameplay/MPlayer killstreak fields (local_mp_air_events.c). */
#define LMP_MPI_MSG_OFF_OBJ 0x08u
#define LMP_MPI_MSG_OFF_ID 0x20u
#define LMP_MPI_MSG_UNIT_RESPAWN 0xf030u
#define LMP_NAMEMAP_OFF_ENTRIES 0x00u
#define LMP_NAMEMAP_OFF_COUNT 0x08u
#define LMP_NAMEMAP_OFF_TAIL_PAGE 0x10u
#define LMP_NAMEMAP_OFF_PAGES 0x20u
#define LMP_NAMEMAP_OFF_PAGE_COUNT 0x28u
#define LMP_NAMEMAP_OFF_SHIFT 0x32u
#define LMP_KS_RULE_STRIDE 0x90u
#define LMP_KS_PROGRESS_STRIDE 0x10u
#define LMP_KS_SP_OFF_MIN_RANK 0x00u
#define LMP_KS_SP_OFF_MAX_RANK 0x04u
#define LMP_KS_SP_OFF_INIT_DIST 0x08u
#define LMP_KS_SP_OFF_INIT_ALT 0x0cu
#define LMP_KS_SP_OFF_INIT_SPEED_KMH 0x48u
#define LMP_GP_OFF_KS_RULES (g_lmp.gp_ks_rules)
#define LMP_GP_OFF_KS_RULE_COUNT (g_lmp.gp_ks_rule_count)
#define LMP_KS_RULE_OFF_TAG (g_lmp.ks_rule_tag)
#define LMP_KS_RULE_OFF_AIR_AI_MULT (g_lmp.ks_rule_air_ai_mult)
#define LMP_KS_RULE_OFF_GROUND_AI_MULT (g_lmp.ks_rule_ground_ai_mult)
#define LMP_KS_RULE_OFF_SPAWN_POS (g_lmp.ks_rule_spawn_pos)
#define LMP_KS_RULE_OFF_SPAWN_POS_CNT (g_lmp.ks_rule_spawn_pos_count)
#define LMP_KS_SPAWN_POS_STRIDE (g_lmp.ks_spawn_pos_stride)
#define LMP_MP_OFF_KS_PROGRESS (g_lmp.mp_ks_progress)
+33 -23
View File
@@ -25,12 +25,14 @@ static int g_accept_pending = 0;
static int g_respawn_dispatched = 0;
static int32_t g_pending_slot_id = -1;
static int32_t g_pending_spare_type = -1;
static int32_t g_pending_base_id = -1;
void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int is_silent)
void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t base_id, int is_silent)
{
if (!is_silent || g_pending_slot_id < 0) {
g_pending_slot_id = slot_id;
g_pending_spare_type = spare_type;
g_pending_base_id = base_id;
}
if (!is_silent)
g_respawn_dispatched = 0;
@@ -106,14 +108,27 @@ static void __fastcall hook_mplayer_init_from_matching(uint8_t *mplayer, uint8_t
int32_t desired_team = resolve_configured_player_team();
if (desired_team == 1 || desired_team == 2)
*(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM) = desired_team;
if (*(int32_t *)(info + LMP_MATCH_INFO_OFF_SQUAD_ID) == 0)
*(int32_t *)(info + LMP_MATCH_INFO_OFF_SQUAD_ID) = 1;
local_mp_events_reset();
log_line("local_mp: initialized local player team=%d",
(int)(*(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM)));
log_line("local_mp: initialized local player team=%d squad=%d",
(int)(*(int32_t *)(info + LMP_MATCH_INFO_OFF_TEAM)),
(int)(*(int32_t *)(info + LMP_MATCH_INFO_OFF_SQUAD_ID)));
}
orig_mplayer_init_matching(mplayer, info, uid);
}
static void consume_pending_slot_if_spawned(uint8_t *mplayer)
static int has_unlimited_respawns(void)
{
const char *value;
if (g_local_mp_mission_settings == NULL || g_lmp_datablock_get_str == NULL)
return 0;
value = g_lmp_datablock_get_str(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, "wtoUnlimitedRespawns", "0");
return value != NULL && strcmp(value, "1") == 0;
}
static void finish_pending_spawn(uint8_t *mplayer)
{
const char *hero_name;
@@ -131,7 +146,9 @@ static void consume_pending_slot_if_spawned(uint8_t *mplayer)
if (g_pending_slot_id >= 0 && g_pending_slot_id < 32) {
uint32_t bit = 1u << (uint32_t)g_pending_slot_id;
if (g_pending_spare_type < 0)
if (has_unlimited_respawns())
local_mp_report_airfield_spawn(hero_name, g_pending_base_id);
else if (g_pending_spare_type < 0)
*(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK) |= bit;
else
*(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK) |= bit;
@@ -140,6 +157,7 @@ static void consume_pending_slot_if_spawned(uint8_t *mplayer)
*(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK),
*(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK));
g_pending_slot_id = -1;
g_pending_base_id = -1;
}
}
@@ -153,12 +171,13 @@ static void __fastcall hook_gui_state_update(uint8_t *gui_state_obj, float dt)
g_accept_pending = 0;
g_respawn_dispatched = 0;
g_pending_slot_id = -1;
g_pending_base_id = -1;
return;
}
bind_ai_mplayer_units();
mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL;
consume_pending_slot_if_spawned(mplayer);
finish_pending_spawn(mplayer);
if (g_accept_pending && gui_state_obj != NULL) {
uint8_t *econ_state = local_mp_econ_state();
@@ -185,7 +204,7 @@ static int64_t __fastcall hook_do_respawn_player(void *app)
g_respawn_dispatched = 1;
result = orig_do_respawn(app);
consume_pending_slot_if_spawned(mplayer);
finish_pending_spawn(mplayer);
bind_ai_mplayer_units();
return result;
}
@@ -208,21 +227,12 @@ static uint8_t __fastcall hook_is_slot_ready_at_host(int32_t slot_id, const char
int install_local_mp_player_hooks(void)
{
uint8_t *p_gui_update = g_lmp.gui_state_update;
uint8_t *p_mp_init = g_lmp.mplayer_init_matching;
uint8_t *p_do_respawn = g_lmp.do_respawn_player;
uint8_t *p_slot_ready = g_lmp.is_slot_ready_at_host;
const LocalMpHookSpec hooks[] = {
{ "gui_state_update", g_lmp.gui_state_update, (void *)&hook_gui_state_update, (void **)&orig_gui_state_update },
{ "mplayer_init_matching", g_lmp.mplayer_init_matching, (void *)&hook_mplayer_init_from_matching, (void **)&orig_mplayer_init_matching },
{ "do_respawn_player", g_lmp.do_respawn_player, (void *)&hook_do_respawn_player, (void **)&orig_do_respawn },
{ "is_slot_ready_at_host", g_lmp.is_slot_ready_at_host, (void *)&hook_is_slot_ready_at_host, (void **)&orig_is_slot_ready_at_host },
};
if (MH_CreateHook(p_gui_update, (void *)&hook_gui_state_update, (void **)&orig_gui_state_update) != MH_OK ||
MH_EnableHook(p_gui_update) != MH_OK ||
MH_CreateHook(p_mp_init, (void *)&hook_mplayer_init_from_matching, (void **)&orig_mplayer_init_matching) != MH_OK ||
MH_EnableHook(p_mp_init) != MH_OK ||
MH_CreateHook(p_do_respawn, (void *)&hook_do_respawn_player, (void **)&orig_do_respawn) != MH_OK ||
MH_EnableHook(p_do_respawn) != MH_OK ||
MH_CreateHook(p_slot_ready, (void *)&hook_is_slot_ready_at_host, (void **)&orig_is_slot_ready_at_host) != MH_OK ||
MH_EnableHook(p_slot_ready) != MH_OK) {
log_line("local_mp: failed to install player state hooks");
return 0;
}
return 1;
return local_mp_queue_hooks("local_mp_players", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+5 -7
View File
@@ -100,11 +100,9 @@ static void __fastcall hook_set_controlled_unit(uint8_t *mp, uint32_t eid)
int install_local_mp_support_hooks(void)
{
uint8_t *p_set = g_lmp.set_controlled_unit;
if (MH_CreateHook(p_set, (void *)&hook_set_controlled_unit, (void **)&orig_set_controlled_unit) != MH_OK ||
MH_EnableHook(p_set) != MH_OK) {
log_line("local_mp: failed to install the support unit hook");
return 0;
}
return 1;
const LocalMpHookSpec hooks[] = {
{ "set_controlled_unit", g_lmp.set_controlled_unit, (void *)&hook_set_controlled_unit, (void **)&orig_set_controlled_unit },
};
return local_mp_queue_hooks("local_mp_support", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more