diff --git a/.github/release-notes/v0.1.4.md b/.github/release-notes/v0.1.4.md index 5281575..38af939 100644 --- a/.github/release-notes/v0.1.4.md +++ b/.github/release-notes/v0.1.4.md @@ -12,6 +12,7 @@ - **实验性新版陆战 AI(第一阶段,默认启用)。** - 引入全新的模块化陆战 AI 架构:包含整队指挥层与任务单(按坚守 / 征服 / 制霸模式分配进攻、侧翼、架枪与防空角色,支持分路包抄、集结出发、占点回防与防空阵位)、曝光积分视觉感知与唯一弹道开火许可门(含植被透光、硬遮挡弹道扫掠与友军走廊防误伤)、单车车体状态机(短停射击预算、掩体装填回缩、摆角、僵持换位与受损维修)、本车目击测速提前量与失联守出口,以及按待发架容量配置主/副双弹种出生装弹与局内自动切弹。 - 当前为第一阶段实验版本,默认以完整模式(`full`)运行并持续调优中;若遇到寻路或行为异常,可随时在启动器「数值 → Bot 参数」切回「原版 AI(`stock`)」。 + - 移动射击的车速上限随距离缩短而提高。车辆会主动减速,持续无法开火时可短停争取一炮,瞄准也改为按跟踪目标的误差判断。同步更新了出车权重、感知、占点与车体动作的默认参数。 - **启动器新增「数值 → Bot 参数」页面。** - 统一集中管理陆战 AI 模式切换、AI 坦克 / 飞机重生次数、每类载具候选池上限、**陆战 AI 出车权重**(中坦 / 主战、重坦、坦歼、轻坦、防空车、其他)与出生携弹策略。 - 同时以折叠分组开放全部陆战 AI 进阶参数(指挥配额、占点宏观、状态机、视觉感知、测速偏差、火控开火门、机动寻路、编队避让与地形约束),支持参数校验与一键恢复默认值。 @@ -25,9 +26,14 @@ - 修复空战右下角敌机部件受损播报串台(仅显示本机及观战目标,不再混入 AI 互打记录)以及空战持续命中时重复普通命中丢失的问题; - 修正普通命中与跳弹等引擎判定无效命中的奖励分类,并修正右侧部件受损反馈的攻击者与收件人归属; - 修复机库一键「购买所有已研发改装件」时因前置依赖状态与价格核算不一致报「角色服务器内部错误」的问题。 +- **对局奖励与备用载具** + - 空战街机可因伤害或摧毁敌方小基地获得个人分,摧毁奖励也会列入战后明细。 + - 修复重生界面中已购买的单车备用载具显示。每日免费出击、单车备用和通用备用按实际成功出击结算。 + - 修复部分任务单位击杀被误计为首杀的问题,并加固助攻事件处理。 - **启动器维护、便携版更新与界面**: - 客户端维护页新增「设置 / 更换在线版安装来源」,方便在线版移动目录后继续一键增量更新; - 复制安装与「从在线版更新」自动跳过并保留玩家自定义内容目录(`UserSkins`、`UserSights`、`WarThunderCDK` 与启动器日志),避免更新覆盖自制涂装或瞄具; + - 复制安装与增量更新会跳过下载不完整的超清材质包(UHQ)。已有离线客户端遇到残缺材质包时,启动器会在启动前提示处理。 - 修复便携版原地更新在 Windows 下的文件复制、Electron `.asar` 检查冲突与进程分离重启问题,并防止客户端或数据目录嵌套于启动器安装目录内; - 更新日志改为支持 Markdown 排版的弹窗展示。 @@ -58,6 +64,7 @@ - **Experimental Ground AI Rebuild (Phase 1, enabled by default).** - Introduces a modular custom ground AI architecture: a team commander & task orders (mode-aware Assault / Flank / Overwatch / SPAA role quotas for Battle, Conquest, and Domination with flank lanes, rally staging, cap recall, and air-aware SPAA positioning), exposure-based visual perception and a single ballistic fire gate (foliage transparency, hard-cover ballistic sweeps, and friendly-fire corridor protection), a hull state machine (short-halt budget, cover reload retreat, angling, stalemate repositioning, and damage repair), sample-based velocity lead estimation with last-seen exit watch, and ready-rack dual-ammo bot spawn loadouts with automatic shell switching. - Ships in `full` mode by default for testing and live tuning; if you run into pathing or behavior issues, you can switch back to **Stock AI (`stock`)** anytime under **Tuning → Bot parameters**. + - The speed limit for firing on the move rises as targets get closer. Bots slow down and can briefly stop when they cannot fire while moving. Aim stability now uses tracking error. Vehicle weights, perception, capture assignments, and hull behavior also have updated defaults. - **New "Tuning → Bot parameters" page in the launcher.** - Brings together ground AI mode selection, AI tank / aircraft respawn limits, per-type AI pool cap, **ground AI vehicle class weights** (Medium/MBT, Heavy, TD, Light, SPAA, Other), and spawn ammunition rules in one place. - Exposes all advanced ground AI tuning sections in collapsible groups (commander, macro, state machine, perception, tactics, estimation, fire control, navigation, crowd, terrain, and runtime cadence/diagnostics) with validation and one-click section reset. @@ -71,9 +78,14 @@ - Fixed Air battle bottom-right enemy part damage feed bleed-through from AI-vs-AI fights (now filtered to the local player or spectated unit) and stopped dropping repeated normal hits on aircraft. - Corrected normal hit vs. ineffective hit (e.g., ricochet) award classification and right-side component damage feedback ownership. - Fixed "Internal character server error" when clicking **Buy all researched modifications** by emitting native `RESEARCHED` status for prerequisite chains and aligning bulk pricing. +- **Battle rewards and backups** + - Damaging or destroying enemy mini-bases in Air Arcade now awards personal score. Base destruction rewards appear in the post-battle breakdown. + - Fixed how purchased vehicle backups appear in the respawn screen. Daily free spawns, vehicle backups, and universal backups are accounted for after a confirmed spawn. + - Fixed some mission-unit kills being counted as the first player kill and tightened assist event handling. - **Launcher maintenance, portable updater & UI**: - Added support for setting or changing the online client update source on the client maintenance page. - Skipped and preserved player-created folders (`UserSkins`, `UserSights`, `WarThunderCDK`, and launcher logs) when copying or updating from the online client. + - Copy installs and incremental updates skip incomplete Ultra High Quality (UHQ) texture packs. The launcher flags incomplete packs in existing offline installations before starting the client. - Fixed portable in-place updates on Windows (`original-fs`, removing unused `default_app.asar`, detached `Start-Process` relaunch) and guarded against nested launcher/data directories. - Rendered launcher release notes in a dedicated Markdown modal. diff --git a/.github/release-notes/v0.1.5.md b/.github/release-notes/v0.1.5.md new file mode 100644 index 0000000..0059f9c --- /dev/null +++ b/.github/release-notes/v0.1.5.md @@ -0,0 +1,89 @@ +## 简体中文 + +`v0.1.5` 是一次集中维护与修复版本,重点解决 **空战坠机后偶发崩溃(`0xC0000374`)**、**备用载具无法出击与扣减失效**、**单车涂装/挂载/弹链与配平未保存**、**联队时间与 20,000 研发点上限异常**、**贴花缓存缺失导致大面积无法显示**,以及 **启动器客户端移除防误删与安装体验改进**。 + +### 该下载哪一个文件? + +- **绝大多数玩家(推荐)**:下载 **`wtoffline-launcher-0.1.5-win-x64.exe`**,直接覆盖安装即可(保留全部存档与配置)。 +- **想要免安装 / 解压即用**:下载 **`wtoffline-launcher-0.1.5-win-x64-portable.zip`**,解压到任意目录后运行其中的启动器即可。 + +### 重点修复 + +- **对局与战斗**: + - 修复空战与核战冲突中飞机坠毁后 0.1–4 秒内偶发堆损坏崩溃(`0xC0000374`)的问题:新增原生模块 `local_mp_air_ai_sync`,在本地主机下串行化 AI 飞机队列扩容操作,同时保留多核并行物理更新; + - 修复战局内选择备用载具后无法点击出击,以及陆战 / 海战载具因内部路径前缀导致备用载具结算扣减失效、未修车槽位被误拦的问题; + - 修复新版陆战 AI 在单人试驾中错误接管靶车的问题,限定仅在多人对局中运行。 +- **档案、联队与商店**: + - 修复载具涂装、挂载预设、弹链选择以及试飞配平(副翼 / 升降舵 / 方向舵)在重启后未保存的问题(感谢 `duduyagame`); + - 修复联队活跃度下次结算时间与排行榜赛季时间显示为 1970 年的问题;预置普通联队补齐 58–60 名 NPC 成员以恢复 20,000 周期研发点上限,接通对局活跃度累计与 3 天周期结算,并在 `tuning/clans.jsonc` 开放初始周期与初始活跃度配置(默认 `0`); + - 解除部分联动促销载具(`bf-109c_1_promo`、`us_m4_sherman_promo`、`jp_destroyer_hatsuzuki`)的跨平台促销锁定,支持在科技树直接订购; + - 免扣款支付按钮默认名称改为「直接获取」(`Direct Claim`),并可在 `tuning/store.jsonc`(`freePaymentLabel`)中自定义,同步热生效于游戏内支付弹窗、内置商城和内置交易所。 +- **贴花缓存与涂装索引**: + - 修复从在线版导入贴花缓存时因部分 `.ddsx` 文件尚未缓存而导致贴花大面积读取失败的问题:构建时自动按实际缓存文件过滤索引、自动补齐缺失 LOD、未缓存标准贴花回退内置占位图并丢弃残缺涂装; + - 支持直接选择游戏根目录识别贴花缓存,安装向导可自动探测并预填在线版贴花缓存,客户端详情页新增一键从在线版来源导入贴花缓存。 + +### 启动器改进 + +- **更安全的客户端移除与还原流程**: + - 彻底拆分「从列表移除客户端」与「删除磁盘文件」,默认均不勾选;坏记录或已移动目录可直接安全移出列表; + - 新增 `wtoffline/client.json` 来源标记,仅允许对明确标记为独立副本 / 硬链接副本、非 Steam 且不与其他客户端来源目录重叠的目录执行删除;原地安装或无标记目录提供原子「还原原版文件并清理离线补丁」与「打开所在文件夹」入口。 +- **安装进度与对话框体验**: + - 省空间复制进度条拆分展示实际写入字节与硬链接共享字节,并补充 Windows 资源管理器属性会重复统计硬链接空间的说明; + - 启动器所有分类文件 / 目录选择与导出对话框自动记住上次路径,并在原路径不存在时回退至最近的现存父目录。 + +### 社区交流与反馈 + +欢迎加入 WTOffline 官方 Discord 服务器反馈问题、分享调参配置或自制模组,并关注最新客户端适配进度: + +- **Discord 社区**:https://discord.gg/P566xWNpEs +- **项目主页**:https://wto-project.net + +### 客户端兼容性 + +支持已核对版本 `2.61.0.37`、`2.61.0.43`、`2.61.0.55` 和 `2.61.0.58`,并支持按特征码自动适配后续小版本(已在 `2.61.0.60` 通过静态与构建核对)。 + +--- + +## English + +`v0.1.5` is a maintenance and bug-fix release addressing the **Air battle post-crash heap corruption (`0xC0000374`)**, **backup vehicle respawn and accounting issues**, **vehicle camouflage/loadout/trim persistence**, **squadron timestamps and 20,000 RP cap**, **decal cache missing-file failures**, and **safer launcher client removal and installation UX**. + +### Which file should I download? + +- **Most players (Recommended)**: Download **`wtoffline-launcher-0.1.5-win-x64.exe`** — the standard Windows installer with built-in automatic update checks (safe to install over previous versions; preserves all saves and tuning). +- **No-install / Portable**: Download **`wtoffline-launcher-0.1.5-win-x64-portable.zip`** — extract anywhere and run the launcher directly. + +### Key Fixes + +- **Battles & gameplay**: + - Fixed intermittent heap corruption crashes (`0xC0000374`) 0.1–4 seconds after aircraft crashes in Air battles and Nuclear Escalation via a new native module (`local_mp_air_ai_sync`) that serializes `TeamAiManager::addToUnsortedPlanes` on the local host while keeping multi-threaded aircraft updates intact. + - Fixed backup vehicles failing to respawn in LocalMP battles, normalized ground/naval unit path prefixes so backup deductions match correctly after battle, and stopped unrepaired crew slots from blocking backup spawns. + - Restricted the custom ground AI runtime to multiplayer battles so it no longer takes over target vehicles in single-player test drives. +- **Profile, squadrons & store**: + - Persisted per-vehicle camouflage, weapon preset, ammo belt selections, and test-flight trim preferences across restarts (thanks to `duduyagame`). + - Fixed 1970 timestamps for squadron activity rewards and leaderboard seasons, backfilled preset normal squadrons to 58–60 NPC members to restore the 20,000 RP period cap, wired battle RP into 3-day squadron activity cycles, and made initial periods/activity configurable in `tuning/clans.jsonc` (defaulting to `0`). + - Stripped cross-promotion locks from promo gift vehicles (`bf-109c_1_promo`, `us_m4_sherman_promo`, `jp_destroyer_hatsuzuki`) so they can be ordered directly from the tech tree. + - Changed the default free offline payment button label to **Direct Claim** (Chinese: 「直接获取」) and made it tunable via `tuning/store.jsonc` (`freePaymentLabel`) across the in-game payment dialog, local store, and local marketplace. +- **Decal & skin cache**: + - Fixed widespread decal load failures when importing partially cached online `cache/content` folders by filtering against locally present `.ddsx` files, repairing single-LOD hits, falling back uncached stock decals to built-in placeholders, and dropping incomplete downloadable skins. + - Added support for picking a game root folder directly, auto-detecting decal cache in the install wizard, and one-click import from the recorded online source in client details. + +### Launcher Improvements + +- **Safer client removal & stock restore**: + - Separated removing a client from the launcher list from deleting files on disk (both unchecked by default), allowing broken or missing entries to be removed cleanly. + - Added a `wtoffline/client.json` origin marker so disk deletion is only permitted for verified copy/hardlink clients outside Steam that do not overlap any registered source folder, plus an atomic **Restore stock files & clean offline patches** flow and **Open folder** action for in-place or unmarked directories. +- **Install progress & file pickers**: + - Split actual disk-copied bytes from hardlinked shared bytes in space-saving install progress, with a note explaining that Windows Explorer properties double-count hardlinked space. + - Remembered the last selected directory per category across all file/folder picker and export dialogs with automatic parent fallback. + +### Community & Feedback + +Join the official WTOffline Discord server to report issues, share custom tuning presets or mods, and follow client adaptation updates: + +- **Discord**: https://discord.gg/P566xWNpEs +- **Homepage**: https://wto-project.net + +### Client compatibility + +Verified with client versions `2.61.0.37`, `2.61.0.43`, `2.61.0.55`, and `2.61.0.58`, with signature-based matching for later minor updates (static and build checks pass on `2.61.0.60`). diff --git a/README.md b/README.md index 0248886..1913a67 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线项目。本地服务器模拟 Gaijin 的线上服务,客户端的所有请求都发到本机。客户端照常登录、读取档案、进入机库、提交玩家操作,游戏规则、存档和对局结算都在本地服务器上完成,对手和队友全部是 AI。 +> **项目定位**:WTOffline 是为了方便玩家离线游玩的**单机**《战争雷霆》项目。为保持项目边界清晰、避免争议,项目组**不会提供也不会制作包括局域网联机在内的任何形式联机功能**。 + 仓库只包含源码和补丁定义,不包含任何游戏文件。构建时从玩家本机的原版安装读取文件,生成一份独立的游戏副本。 ## 状态 @@ -41,7 +43,7 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线 | 战后 | 结算页、战斗历史、个人统计、战斗奖章、加成道具与合同结算、修理费与自动修理 | | 回放 | 录制与回放,回放中切换到 AI 视角 | -尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。好友、组队等多人社交功能不适用,只保证界面不报错。 +尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。本项目仅面向单人离线游玩,不制作包括局域网联机在内的任何联机功能;好友、组队等多人社交功能不适用,只保证界面不报错。 AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不足。 @@ -261,7 +263,7 @@ tools/ wtotools,补丁检查工具(Python) ## 声明 -本项目是同人爱好项目,与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。 +本项目是面向单人离线游玩的非商业同人爱好项目,项目组不会主动制作包括局域网联机在内的任何联机功能。本项目与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。 --- @@ -273,6 +275,8 @@ tools/ wtotools,补丁检查工具(Python) WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI. +> **Project scope**: WTOffline is a **single-player offline** War Thunder project built to make offline play convenient for players. The project team **will not develop or provided any kind of multiplayer or networking features, including LAN multiplayer**. + The repository contains source code and patch definitions only. It does not contain any game files. The build reads files from the player's own installation and produces a separate game copy. ## Status @@ -306,7 +310,7 @@ Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general d | After battle | Debriefing, battle history, personal statistics, battle awards, booster and contract settlement, repair costs and auto-repair | | Replays | Recording and playback, switching to AI vehicles during playback | -Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. Social multiplayer features such as friends and squads do not apply; the interface is only kept from breaking. +Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. This project is strictly for single-player offline play and will not develop any multiplayer features (including LAN multiplayer); social multiplayer features such as friends and squads do not apply and are only kept from breaking the interface. AI driving, pathfinding, and tactics come from the game's built-in AI and still have clear shortcomings. @@ -526,4 +530,4 @@ This project is released under the [GNU Affero General Public License v3.0](LICE ## Disclaimer -This is a non-commercial fan project. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client. +This is a non-commercial fan project built strictly for single-player offline play; the project team will not actively develop any multiplayer features, including LAN multiplayer. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client. diff --git a/apps/launcher/package.json b/apps/launcher/package.json index db53139..508f332 100644 --- a/apps/launcher/package.json +++ b/apps/launcher/package.json @@ -1,7 +1,7 @@ { "name": "@wto/launcher", "productName": "WTOffline Launcher", - "version": "0.1.4", + "version": "0.1.5", "private": true, "description": "Installer and launcher of the War Thunder offline project.", "type": "module", diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index f08af21..1429b20 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -11,7 +11,7 @@ import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagn 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 { changeDecalSource, decalImportInProgress, detectDecalCacheSource } from '../services/install/decals.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'; @@ -32,6 +32,7 @@ import { } from '../services/mods/mods-service.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts'; import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; +import { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts'; import { broadcast, handle } from './register.ts'; /** Registers the handler of every contract channel. One line per channel; the work is in services/. */ @@ -68,11 +69,18 @@ export function registerIpcHandlers(): void { BrowserWindow.fromWebContents(sender)?.close(); }); - handle('dialog:pickFolder', async ({ title }, sender) => { + handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => { const window = BrowserWindow.fromWebContents(sender); - const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) }; + const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath); + const options = { + properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, + ...(title ? { title } : {}), + ...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}), + }; const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); - return { path: result.canceled ? null : (result.filePaths[0] ?? null) }; + const chosen = result.canceled ? null : (result.filePaths[0] ?? null); + if (chosen) await rememberDialogPath('folder', chosen); + return { path: chosen }; }); handle('install:prepareCopy', () => createCopyDraft()); @@ -156,6 +164,7 @@ export function registerIpcHandlers(): void { return updated; }); handle('copies:cancelMaintenance', () => cancelMaintenance()); + handle('decals:detectSource', async ({ path }) => ({ path: await detectDecalCacheSource(path) })); handle('saves:list', ({ copyId }) => getSaveList(copyId)); handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId)); diff --git a/apps/launcher/src/main/services/copies/copy-file-maintenance.ts b/apps/launcher/src/main/services/copies/copy-file-maintenance.ts index 6744074..ffa511f 100644 --- a/apps/launcher/src/main/services/copies/copy-file-maintenance.ts +++ b/apps/launcher/src/main/services/copies/copy-file-maintenance.ts @@ -7,6 +7,7 @@ import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schema import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts'; import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; import { sameVolume } from '../game-folder/inspect-target-folder.ts'; +import { readClientMarker, writeClientMarker } from '../install/client-marker.ts'; import { copyPlannedFiles, isInSkippedSourceFolder, planCopy, type CopyPlan } from '../install/copy-game.ts'; import { fileHash, @@ -69,7 +70,7 @@ export async function updateFromSource(record: InstallRecord, root: string, sign signal.throwIfAborted(); const check = await checkPatches(game.path, record.dataPath); signal.throwIfAborted(); - return changeCopyFiles(root, async (incoming) => { + const updated = await changeCopyFiles(root, async (incoming) => { report('copying', 0, copy.totalBytes); let lastReport = 0; await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => { @@ -104,6 +105,13 @@ export async function updateFromSource(record: InstallRecord, root: string, sign lastCheckedAt: new Date().toISOString(), sourceFiles: inventory, ...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}), }))); + if (!preserveHardlinks && linked.length > 0) { + const marker = await readClientMarker(root); + if (marker?.origin === 'hardlink' || (marker === null && record.method === 'copy')) { + await writeClientMarker(root, 'copy'); + } + } + return updated; } interface UpdateFilePlan { @@ -188,7 +196,7 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A 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) => { + const updated = await changeCopyFiles(root, async (incoming) => { const replacements: string[] = []; const unchanged = new Map(); let checked = 0; @@ -225,6 +233,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A report('applying', total, total); return { replace: replacements, remove: [] }; }, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] }))); + await writeClientMarker(root, 'hardlink'); + return updated; } async function canShareVolume(sourcePath: string, root: string): Promise { diff --git a/apps/launcher/src/main/services/copies/copy-maintenance.ts b/apps/launcher/src/main/services/copies/copy-maintenance.ts index db6521d..0323406 100644 --- a/apps/launcher/src/main/services/copies/copy-maintenance.ts +++ b/apps/launcher/src/main/services/copies/copy-maintenance.ts @@ -1,21 +1,29 @@ -import { readdir, rm } from 'node:fs/promises'; -import { isAbsolute, join, parse, relative } from 'node:path'; -import { app } from 'electron'; +import { isAbsolute, relative } from 'node:path'; import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { Copies, InstallRecord } from '@shared/schemas/install.ts'; import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; +import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts'; import { installationInProgress } from '../install/install-game.ts'; -import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts'; +import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts'; import { checkPatches } from '../install/patch-check.ts'; -import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts'; 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, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts'; +import { + canDeleteCopyFiles, + canRestoreStock, + checkedRoot, + failLocation, + removeCopy, + resolveClientOrigin, + withCanonicalSources, +} from './copy-removal.ts'; import { readSource, setCopySource } from './copy-source.ts'; +export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts'; + let current: { stop: AbortController; interruptible: boolean; @@ -35,9 +43,23 @@ export function cancelMaintenance(): void { } export async function maintenanceInfo(id: string): Promise { - const record = await requireCopy(id); - const source = await readSource(record); - const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]); + const registry = await listCopies(); + const record = registry.copies.find((copy) => copy.id === id); + if (!record) throw new AppError('copy_not_found'); + const [source, copyPath, dataPath, canonicalCopies] = await Promise.all([ + readSource(record), + canonicalCopyPath(record.copyPath), + canonicalCopyPath(record.dataPath), + withCanonicalSources(registry.copies), + ]); + const [diskMarker, hasHardlinkedResources, canRestoreAndRemove] = await Promise.all([ + readClientMarker(copyPath), + detectHardlinkedResources(copyPath), + canRestoreStock(record, copyPath), + ]); + const clientOrigin = resolveClientOrigin(record, diskMarker); + const canDeleteFiles = canDeleteCopyFiles(record, copyPath, clientOrigin, registry.copies) && + canDeleteCopyFiles(record, copyPath, clientOrigin, canonicalCopies); const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath); const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath); return { @@ -47,6 +69,10 @@ export async function maintenanceInfo(id: string): Promise { spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath), steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath), steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null, + clientOrigin, + hasHardlinkedResources, + canDeleteFiles, + canRestoreAndRemove, }; } @@ -94,6 +120,19 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign const { id, operation, steamLocations } = request; const record = await requireCopy(id); if (operation === 'set-source') return setCopySource(record, request.sourcePath); + if (operation === 'delete') { + return removeCopy( + record, + { + deleteFiles: request.deleteFiles === true, + restoreStock: request.restoreStock === true, + deleteData: request.deleteData === true, + }, + signal, + report, + labServerUses, + ); + } const root = await checkedRoot(record); const dataPath = await canonicalCopyPath(record.dataPath); @@ -101,7 +140,7 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy'); signal.throwIfAborted(); - if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) { + if (operation !== 'confirm-steam' && needsConfirmation) { throw new AppError('launch_steam_confirmation_required'); } @@ -123,9 +162,6 @@ async function performMaintenance(request: MaintenanceRequest, signal: AbortSign return updateFromSource(record, root, signal, report); case 'compact': return compactCopy(record, root, signal, report); - case 'delete': - report('applying'); - return remove(record, root, request.deleteData); } } @@ -135,42 +171,6 @@ async function requireCopy(id: string): Promise { return record; } -function failLocation(reason: string, details: Record): never { - console.warn('[copies] maintenance_location:', reason, details); - throw new AppError('maintenance_location'); -} - -async function checkedRoot(record: InstallRecord): Promise { - const root = await safeFolder(record.copyPath, true); - const backup = await canonicalCopyPath(record.stockBackupPath); - const expectedBackup = join(root, STOCK_BACKUP_FOLDER); - if (relative(expectedBackup, backup) !== '') { - failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath }); - } - if (record.sourcePath) { - const source = await canonicalCopyPath(record.sourcePath); - if (copyPathContains(source, root) || copyPathContains(root, source)) { - failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath }); - } - } - return root; -} - -async function safeFolder(path: string, steamAllowed = false): Promise { - const root = await canonicalCopyPath(path); - const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root); - const appPath = await canonicalCopyPath(app.getAppPath()); - const userDataPath = await canonicalCopyPath(app.getPath('userData')); - if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) || - copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) { - failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath }); - } - if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) { - failLocation('folder_is_symlink', { path, root }); - } - return root; -} - async function labServerUses(root: string): Promise { const lab = await readInstalledLab().catch(() => null); if (!lab || relative(lab.copyPath, root) !== '') return false; @@ -183,38 +183,3 @@ async function recordCheck(record: InstallRecord, folder: string): Promise { - if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) { - if (deleteData) failLocation('delete_data_blocked_in_steam', { copyPath: record.copyPath, root }); - return removeCopyRecord(record.id); - } - - const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath); - const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null; - if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) || - (relative(data, root) !== '' && copyPathContains(data, root)))) { - failLocation('delete_data_overlaps_source_or_copy', { root, data, source }); - } - if (!deleteData && copyPathContains(root, data)) { - await removeExcept(root, data); - } else { - await rm(root, { recursive: true, force: true }); - } - if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true }); - return removeCopyRecord(record.id); -} - -/** Keep the data folder in place when it was chosen inside this copy. */ -async function removeExcept(folder: string, kept: string): Promise { - if (relative(folder, kept) === '' || !(await fileInfo(folder))) return; - for (const entry of await readdir(folder, { withFileTypes: true })) { - const path = join(folder, entry.name); - if (copyPathContains(path, kept)) { - if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path }); - await removeExcept(path, kept); - } else { - await rm(path, { recursive: true, force: true }); - } - } -} diff --git a/apps/launcher/src/main/services/copies/copy-removal.ts b/apps/launcher/src/main/services/copies/copy-removal.ts new file mode 100644 index 0000000..a900b86 --- /dev/null +++ b/apps/launcher/src/main/services/copies/copy-removal.ts @@ -0,0 +1,272 @@ +import { constants } from 'node:fs'; +import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path'; +import { app } from 'electron'; +import { GAME_FILES, isInSteamLibrary } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import type { ClientOrigin, Copies, InstallRecord } from '@shared/schemas/install.ts'; +import { rawFs } from '../../util/raw-fs.ts'; +import { readClientMarker, type ClientMarker } from '../install/client-marker.ts'; +import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord } from '../install/install-record.ts'; +import { requireStockBackupLocation, STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; +import { gameProcessRunning } from '../launch/launch-controller.ts'; +import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts'; +import type { Report } from './copy-file-maintenance.ts'; + +const OFFLINE_HOOK_FILES = ['wto_ws.dll', 'wto_ws.cfg', 'wto_ws.log'] as const; + +export interface RemoveCopyOptions { + readonly deleteFiles: boolean; + readonly restoreStock: boolean; + readonly deleteData: boolean; +} + +export function failLocation(reason: string, details: Record): never { + console.warn('[copies] maintenance_location:', reason, details); + throw new AppError('maintenance_location'); +} + +/** + * Resolve the effective client origin by preferring a valid on-disk marker while + * keeping in-place registrations conservatively locked as `in-place`. + */ +export function resolveClientOrigin( + record: InstallRecord, + diskMarker: ClientMarker | null, +): ClientOrigin | null { + if (record.method === 'in-place') return 'in-place'; + if (diskMarker) return diskMarker.origin; + if (record.method === 'copy') return record.hardlinkedFiles?.length ? 'hardlink' : 'copy'; + return null; +} + +/** + * Only launcher-created copies or existing folders carrying a valid copy/hardlink marker + * outside any Steam library and disjoint from every registered copy's sourcePath may be deleted. + */ +export function canDeleteCopyFiles( + record: InstallRecord, + root: string, + effectiveOrigin: ClientOrigin | null, + allCopies: readonly InstallRecord[] = [], +): boolean { + if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) return false; + if (effectiveOrigin !== 'copy' && effectiveOrigin !== 'hardlink') return false; + const normalizedRoot = resolve(root); + const normalizedCopyPath = resolve(record.copyPath); + const sources = record.sourcePath + ? [record.sourcePath, ...allCopies.map((copy) => copy.sourcePath)] + : allCopies.map((copy) => copy.sourcePath); + for (const candidate of sources) { + if (!candidate) continue; + const source = resolve(candidate); + if (pathsOverlap(normalizedRoot, source) || pathsOverlap(normalizedCopyPath, source)) { + return false; + } + } + return true; +} + +/** Check that `record` has a safe root and all four original core files readable in wtoffline/stock. */ +export async function canRestoreStock(record: InstallRecord, root: string): Promise { + try { + const safeRoot = await checkedRoot(record); + const canonicalRoot = await canonicalCopyPath(root); + if (relative(safeRoot, canonicalRoot) !== '') return false; + const backup = await requireStockBackupLocation(safeRoot); + const fsPromises = rawFs().promises; + for (const file of Object.values(GAME_FILES)) { + const stockFile = join(backup, file); + const info = await fileInfo(stockFile); + if (!info?.isFile()) return false; + await fsPromises.access(stockFile, constants.R_OK); + } + return true; + } catch { + return false; + } +} + +/** Resolve every copy's `sourcePath` through symlinks/junctions for overlap checks. */ +export async function withCanonicalSources(copies: readonly InstallRecord[]): Promise { + return Promise.all(copies.map(async (copy) => ( + copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy + ))); +} + +export async function checkedRoot(record: InstallRecord): Promise { + const root = await safeFolder(record.copyPath, true); + const backup = await canonicalCopyPath(record.stockBackupPath); + const expectedBackup = join(root, STOCK_BACKUP_FOLDER); + if (relative(expectedBackup, backup) !== '') { + failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath }); + } + if (record.sourcePath) { + const source = await canonicalCopyPath(record.sourcePath); + if (pathsOverlap(source, root)) { + failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath }); + } + } + return root; +} + +export async function safeFolder(path: string, steamAllowed = false): Promise { + const root = await canonicalCopyPath(path); + const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root); + const appPath = await canonicalCopyPath(app.getAppPath()); + const userDataPath = await canonicalCopyPath(app.getPath('userData')); + if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) || + copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) { + failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath }); + } + if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) { + failLocation('folder_is_symlink', { path, root }); + } + return root; +} + +export async function removeCopy( + record: InstallRecord, + options: RemoveCopyOptions, + signal: AbortSignal, + report: Report, + labServerUses: (root: string) => Promise, +): Promise { + const { deleteFiles, restoreStock, deleteData } = options; + if (deleteFiles && restoreStock) { + failLocation('delete_files_and_restore_stock_conflict', { id: record.id }); + } + + const canonicalRoot = await canonicalCopyPath(record.copyPath); + if (await gameProcessRunning(signal) || await labServerUses(canonicalRoot)) { + throw new AppError('maintenance_busy'); + } + signal.throwIfAborted(); + + // Pure list removal touches no files on disk and skips copyPath/stockBackup checks + // so missing, moved, or damaged client registrations can always be removed safely. + if (!deleteFiles && !deleteData && !restoreStock) { + report('applying'); + return removeCopyRecord(record.id); + } + + const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot); + if ((deleteFiles || deleteData) && copyInSteam) { + failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', { + method: record.method, + copyPath: record.copyPath, + root: canonicalRoot, + }); + } + + let root = canonicalRoot; + if (deleteFiles) { + const allCopies = (await listCopies()).copies; + const canonicalCopies = await withCanonicalSources(allCopies); + const initialOrigin = resolveClientOrigin(record, await readClientMarker(canonicalRoot)); + if (!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, allCopies) || + !canDeleteCopyFiles(record, canonicalRoot, initialOrigin, canonicalCopies)) { + failLocation('delete_files_blocked', { method: record.method, origin: initialOrigin, copyPath: record.copyPath, root: canonicalRoot }); + } + root = await checkedRoot(record); + const verifiedOrigin = resolveClientOrigin(record, await readClientMarker(root)); + if (!canDeleteCopyFiles(record, root, verifiedOrigin, allCopies) || + !canDeleteCopyFiles(record, root, verifiedOrigin, canonicalCopies)) { + failLocation('delete_files_blocked', { method: record.method, origin: verifiedOrigin, copyPath: record.copyPath, root }); + } + } else if (restoreStock) { + root = await checkedRoot(record); + if (!(await canRestoreStock(record, root))) { + failLocation('restore_stock_unavailable', { copyPath: record.copyPath, root, stockBackupPath: record.stockBackupPath }); + } + } + + const data = deleteData ? await safeFolder(record.dataPath, false) : await canonicalCopyPath(record.dataPath); + const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null; + const stockBackup = await canonicalCopyPath(record.stockBackupPath); + if (deleteData) { + const rawRoot = resolve(record.copyPath); + const overlapsSource = source !== null && pathsOverlap(data, source); + const containsCopy = deleteFiles + ? relative(data, root) !== '' && copyPathContains(data, root) + : copyPathContains(data, root) || copyPathContains(data, rawRoot) || copyPathContains(data, stockBackup); + if (overlapsSource || containsCopy) { + failLocation('delete_data_overlaps_source_or_copy', { root, data, source, stockBackup, deleteFiles, restoreStock }); + } + } + + report('applying'); + const fsPromises = rawFs().promises; + if (restoreStock) { + await restoreStockAndCleanOfflineFiles(root, data, deleteData); + } else if (deleteFiles) { + if (!deleteData && copyPathContains(root, data)) { + await removeExcept(root, data); + } else { + await fsPromises.rm(root, { recursive: true, force: true }); + } + } + if (deleteData && (!deleteFiles || !copyPathContains(root, data))) { + await fsPromises.rm(data, { recursive: true, force: true }); + } + return removeCopyRecord(record.id); +} + +/** + * Atomically restore the four stock core files from `wtoffline/stock`, then remove + * only launcher-created hook files and the `wtoffline` folder without touching base game files. + */ +async function restoreStockAndCleanOfflineFiles(root: string, data: string, deleteData: boolean): Promise { + const fsPromises = rawFs().promises; + const backup = await requireStockBackupLocation(root); + await changeCopyFiles(root, async (incoming) => { + const files = Object.values(GAME_FILES); + for (const file of files) { + const sourceFile = join(backup, file); + if (!(await fileInfo(sourceFile))?.isFile()) { + failLocation('stock_backup_source_missing', { root, file, sourceFile }); + } + const targetFile = join(incoming, file); + await fsPromises.mkdir(dirname(targetFile), { recursive: true }); + await fsPromises.copyFile(sourceFile, targetFile); + } + return { replace: files, remove: [] }; + }, async () => undefined); + + const exeDir = dirname(GAME_FILES.executable); + for (const name of OFFLINE_HOOK_FILES) { + const hookFile = await stagedPath(root, join(exeDir, name)); + const info = await fileInfo(hookFile); + if (info && !info.isDirectory()) { + await fsPromises.rm(hookFile, { force: true }); + } + } + + const wtofflineFolder = await stagedPath(root, dirname(STOCK_BACKUP_FOLDER)); + const wtofflineInfo = await fileInfo(wtofflineFolder); + if (wtofflineInfo?.isDirectory()) { + if (!deleteData && copyPathContains(wtofflineFolder, data)) { + await removeExcept(wtofflineFolder, data); + } else { + await fsPromises.rm(wtofflineFolder, { recursive: true, force: true }); + } + } +} + +function pathsOverlap(left: string, right: string): boolean { + return copyPathContains(left, right) || copyPathContains(right, left); +} + +/** Keep the data folder in place when it was chosen inside this copy. */ +async function removeExcept(folder: string, kept: string): Promise { + if (relative(folder, kept) === '' || !(await fileInfo(folder))) return; + const fsPromises = rawFs().promises; + for (const entry of await fsPromises.readdir(folder, { withFileTypes: true })) { + const path = join(folder, entry.name); + if (copyPathContains(path, kept)) { + if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path }); + await removeExcept(path, kept); + } else { + await fsPromises.rm(path, { recursive: true, force: true }); + } + } +} diff --git a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts index d1aa5dd..0567d14 100644 --- a/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts +++ b/apps/launcher/src/main/services/game-folder/inspect-game-folder.ts @@ -3,6 +3,7 @@ import { dirname, join } from 'node:path'; import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { GameFolderInspection } from '@shared/schemas/install.ts'; +import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts'; import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; @@ -61,6 +62,10 @@ export async function inspectGameFolder(path: string): Promise; + +/** Cap on qualifying resource files inspected when sampling for hard links. */ +const MAX_RESOURCE_SAMPLES = 64; + +export function clientMarkerPath(copyFolder: string): string { + return join(copyFolder, CLIENT_MARKER_FILE); +} + +/** + * Safely read and validate `/wtoffline/client.json`. + * Returns `null` when missing, unreadable, malformed, or schema-invalid without throwing. + */ +export async function readClientMarker(copyFolder: string): Promise { + try { + const text = await rawFs().promises.readFile(clientMarkerPath(copyFolder), 'utf8'); + const parsed = ClientMarkerSchema.safeParse(JSON.parse(text) as unknown); + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} + +/** + * Atomically write `/wtoffline/client.json`. + * Preserves `createdAt` and records `updatedAt` when updating an existing valid marker. + */ +export async function writeClientMarker(copyFolder: string, origin: ClientOrigin): Promise { + const existing = await readClientMarker(copyFolder); + const now = new Date().toISOString(); + const marker: ClientMarker = existing + ? { + format: 1, + origin, + createdBy: 'wtoffline-launcher', + createdAt: existing.createdAt, + updatedAt: now, + } + : { + format: 1, + origin, + createdBy: 'wtoffline-launcher', + createdAt: now, + }; + await writeJsonAtomic(clientMarkerPath(copyFolder), marker); + return marker; +} + +/** + * Lightweight probe for hard-linked read-only resource packs under allowed content directories. + * Returns `true` as soon as a single qualifying resource reports `nlink >= 2`, or `false` on + * missing/unreadable directories or when no sampled resource is hard-linked. + */ +export async function detectHardlinkedResources(copyFolder: string): Promise { + const fsPromises = rawFs().promises; + const rules = hardlinkResourceRules(); + const queue: Array<{ absDir: string; relDir: string }> = rules.allowedDirectories.map((dir) => { + const clean = dir.replace(/\/+$/, ''); + return { absDir: join(copyFolder, clean), relDir: clean }; + }); + let sampled = 0; + + while (queue.length > 0 && sampled < MAX_RESOURCE_SAMPLES) { + const current = queue.shift()!; + let entries; + try { + entries = await fsPromises.readdir(current.absDir, { withFileTypes: true }); + } catch { + continue; + } + + for (const entry of entries) { + if (entry.isSymbolicLink()) continue; + const absPath = join(current.absDir, entry.name); + const relPath = `${current.relDir}/${entry.name}`; + if (entry.isDirectory()) { + queue.push({ absDir: absPath, relDir: relPath }); + continue; + } + if (!entry.isFile()) continue; + + const lower = entry.name.toLowerCase(); + if (!rules.allowedExtensions.some((ext) => lower.endsWith(ext))) continue; + + try { + const stats = await fsPromises.lstat(absPath); + if (!stats.isFile() || !isHardlinkableResource(relPath, stats.size)) continue; + if (stats.nlink >= 2) return true; + sampled += 1; + if (sampled >= MAX_RESOURCE_SAMPLES) return false; + } catch { + continue; + } + } + } + return false; +} diff --git a/apps/launcher/src/main/services/install/copy-game.ts b/apps/launcher/src/main/services/install/copy-game.ts index fd46653..9c75fd5 100644 --- a/apps/launcher/src/main/services/install/copy-game.ts +++ b/apps/launcher/src/main/services/install/copy-game.ts @@ -68,6 +68,12 @@ export interface CopyPlan { export interface CopyProgress { readonly doneBytes: number; readonly doneFiles: number; + /** Bytes actually written to disk so far (excludes hard-linked files). */ + readonly copiedBytes: number; + /** Bytes shared via hard links so far (occupies no extra disk space). */ + readonly linkedBytes: number; + /** Number of hard-linked files created so far. */ + readonly linkedFiles: number; } /** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */ @@ -129,12 +135,19 @@ export async function copyPlannedFiles( for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true }); const linkedTargets = hardlinks ? new Map() : undefined; let next = 0; - let doneBytes = 0; + let copiedBytes = 0; + let linkedBytes = 0; + let linkedFiles = 0; let doneFiles = 0; + const emitProgress = (): void => { + // Keep doneBytes aligned with actual bytes written to disk so hard-linked files + // do not inflate copy progress. + onProgress({ doneBytes: copiedBytes, doneFiles, copiedBytes, linkedBytes, linkedFiles }); + }; const countBytes = (): Transform => new Transform({ transform(chunk: Buffer, _encoding, callback) { - doneBytes += chunk.length; - onProgress({ doneBytes, doneFiles }); + copiedBytes += chunk.length; + emitProgress(); callback(null, chunk); }, }); @@ -155,7 +168,8 @@ export async function copyPlannedFiles( if (verified) { const linked = await linkVerifiedResource(from, to, verified); linkedTargets?.set(to, linked); - doneBytes += file.bytes; + linkedBytes += file.bytes; + linkedFiles += 1; } else { await pipeline( fs.createReadStream(from), @@ -168,7 +182,7 @@ export async function copyPlannedFiles( await fsPromises.utimes(to, modified, modified); } doneFiles += 1; - onProgress({ doneBytes, doneFiles }); + emitProgress(); } } catch (error) { if (!hasError && !stop.signal.aborted && !signal.aborted) { diff --git a/apps/launcher/src/main/services/install/data-location.ts b/apps/launcher/src/main/services/install/data-location.ts index b4a00d1..defa9a5 100644 --- a/apps/launcher/src/main/services/install/data-location.ts +++ b/apps/launcher/src/main/services/install/data-location.ts @@ -1,6 +1,31 @@ import { readdir } from 'node:fs/promises'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { AppError } from '@shared/errors.ts'; +import type { DataFolderProblem } from '@shared/schemas/install.ts'; +import { copyPathContains } from './install-record.ts'; +import { STOCK_BACKUP_FOLDER } from './stock-backup.ts'; + +/** + * Validate where the offline data folder sits relative to the client and stock folders. + * A subfolder inside the client (outside wtoffline/) is allowed, while setting dataPath to the + * client folder itself or an ancestor of it would mix game files into the data root. + */ +export function dataFolderProblem( + dataPath: string, + copyPath: string | null, + sourcePath: string | null, + externalStockPath: string | null, +): DataFolderProblem | null { + if (copyPath && (copyPathContains(dataPath, copyPath) || + copyPathContains(join(copyPath, dirname(STOCK_BACKUP_FOLDER)), dataPath))) { + return 'overlaps_client'; + } + if ((sourcePath && copyPathContains(sourcePath, dataPath)) || + (externalStockPath && copyPathContains(externalStockPath, dataPath))) { + return 'overlaps_stock'; + } + return null; +} /** A data tree must keep the server's saves, logs and caches inside the selected folder. */ export async function requireUnredirectedData(root: string): Promise { diff --git a/apps/launcher/src/main/services/install/decals.ts b/apps/launcher/src/main/services/install/decals.ts index e9eafe0..0c57305 100644 --- a/apps/launcher/src/main/services/install/decals.ts +++ b/apps/launcher/src/main/services/install/decals.ts @@ -22,6 +22,25 @@ export function decalCachePath(dataPath: string, cacheId: string): string { return join(dataPath, CACHE_FOLDER, cacheId); } +/** + * Read-only check whether a player-chosen or registered folder contains a usable decal cache + * (, /cache, or /cache/content). Returns the canonical cache/content path when + * valid, or null when absent, invalid, or unreadable. + */ +export async function detectDecalCacheSource(folderPath: string): Promise { + if (!folderPath || !isAbsolute(folderPath)) return null; + try { + const rawSource = await realpath(folderPath).catch(() => null); + if (!rawSource) return null; + const resolved = resolvePlayerDecalCacheFolder(rawSource); + const canonical = await realpath(resolved).catch(() => null); + if (!canonical) return null; + return playerDecalCacheProblem(canonical) === undefined ? canonical : null; + } catch { + return null; + } +} + async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise { if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed'); const data = await canonicalCopyPath(dataPath); diff --git a/apps/launcher/src/main/services/install/hardlink-files.ts b/apps/launcher/src/main/services/install/hardlink-files.ts index b3199d7..0d0c424 100644 --- a/apps/launcher/src/main/services/install/hardlink-files.ts +++ b/apps/launcher/src/main/services/install/hardlink-files.ts @@ -1,7 +1,11 @@ import { createHash } from 'node:crypto'; import { createReadStream, type BigIntStats } from 'node:fs'; import { link, lstat } from 'node:fs/promises'; +import { join } from 'node:path'; +import { isHardlinkableResource } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; +import type { InstallProgress } from '@shared/schemas/install.ts'; +import type { CopyPlan } from './copy-game.ts'; export type ResourceMatchResult = | { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats } @@ -83,3 +87,27 @@ function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean return right.isFile() && left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeNs === right.mtimeNs; } + +/** Collect and stat every eligible read-only resource pack in `plan` before hard-linking. */ +export async function prepareHardlinks( + source: string, + plan: CopyPlan, + signal: AbortSignal, + report: (progress: InstallProgress) => void, +): Promise> { + 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(); + let doneBytes = 0; + let doneFiles = 0; + report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length }); + for (const file of candidates) { + const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal); + if (verified) links.set(file.relativePath, verified); + doneBytes += file.bytes; + doneFiles += 1; + report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length }); + } + if (!links.size) throw new AppError('hardlink_no_match'); + return links; +} diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index ea86232..2255285 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -1,19 +1,21 @@ -import type { BigIntStats } from 'node:fs'; import { access, mkdir } from 'node:fs/promises'; -import { dirname, isAbsolute, join, relative } from 'node:path'; +import { dirname, isAbsolute, relative } from 'node:path'; import { app } from 'electron'; -import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher'; +import { isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; -import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; +import type { ClientOrigin, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; import { 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 { readClientMarker, writeClientMarker } from './client-marker.ts'; +import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts'; +import { dataFolderProblem, requireUnredirectedData } from './data-location.ts'; import { discardDecalCache, importDecalCache } from './decals.ts'; -import { statHardlinkResource } from './hardlink-files.ts'; +import { prepareHardlinks } from './hardlink-files.ts'; import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts'; import { checkPatches } from './patch-check.ts'; -import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, STOCK_BACKUP_FOLDER } from './stock-backup.ts'; +import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation } from './stock-backup.ts'; + +export { dataFolderProblem } from './data-location.ts'; /** * Install the offline version: check the patches against the player's game, @@ -101,6 +103,16 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr ? await refreshStockBackup(copyPath) : await backUpStockFiles(copyPath); + // Record launcher-created client origin on disk; never overwrite or fabricate a marker for existing folders. + let detectedOrigin: ClientOrigin | undefined; + if (request.method === 'copy') { + await writeClientMarker(copyPath, useHardLinks ? 'hardlink' : 'copy'); + } else if (request.method === 'in-place') { + await writeClientMarker(copyPath, 'in-place'); + } else { + detectedOrigin = (await readClientMarker(copyPath))?.origin; + } + report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const record: InstallRecord = { id: request.id, @@ -116,6 +128,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr installedAt: new Date().toISOString(), lastCheckedAt: new Date().toISOString(), ...(decalCacheId ? { decalCacheId } : {}), + ...(detectedOrigin ? { detectedOrigin } : {}), ...copied, }; await writeInstallRecord(record); @@ -176,28 +189,6 @@ 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'); @@ -219,8 +210,10 @@ async function copyGame( report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const plan = await planCopy(source); 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; + const linkTotalBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0; + const linkTotalFiles = hardlinks ? hardlinks.size : 0; + const copyTotalBytes = Math.max(0, plan.totalBytes - linkTotalBytes); + const neededBytes = copyTotalBytes + SPARE_BYTES; if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) { throw new AppError('hardlink_file_changed'); } @@ -229,11 +222,26 @@ async function copyGame( throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) }); } const targetExisted = await exists(target); - const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length }; - report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals }); + // Track actual disk-copy bytes in doneBytes/totalBytes so hard-linked resource archives + // do not inflate the progress bar or cause sudden jumps when links are created. + const totals = { + totalBytes: copyTotalBytes > 0 ? copyTotalBytes : plan.files.length, + totalFiles: plan.files.length, + copyTotalBytes, + ...(hardlinks ? { linkTotalBytes, linkTotalFiles } : {}), + }; + const toProgress = (done: { doneFiles: number; copiedBytes: number; linkedBytes: number; linkedFiles: number }): InstallProgress => ({ + phase: 'copying', + doneBytes: copyTotalBytes > 0 ? done.copiedBytes : done.doneFiles, + doneFiles: done.doneFiles, + copiedBytes: done.copiedBytes, + ...(hardlinks ? { linkedBytes: done.linkedBytes, linkedFiles: done.linkedFiles } : {}), + ...totals, + }); + report(toProgress({ doneFiles: 0, copiedBytes: 0, linkedBytes: 0, linkedFiles: 0 })); try { await copyPlannedFiles(source, target, plan, signal, - (done) => report({ phase: 'copying', ...done, ...totals }), hardlinks); + (done) => report(toProgress(done)), hardlinks); if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed'); return { sourceFiles: plan.files.map((file) => file.relativePath), @@ -248,29 +256,6 @@ async function copyGame( } } -async function prepareHardlinks( - source: string, - plan: CopyPlan, - signal: AbortSignal, - report: (progress: InstallProgress) => void, -): Promise> { - 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(); - let doneBytes = 0; - let doneFiles = 0; - report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length }); - for (const file of candidates) { - const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal); - if (verified) links.set(file.relativePath, verified); - doneBytes += file.bytes; - doneFiles += 1; - report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length }); - } - if (!links.size) throw new AppError('hardlink_no_match'); - return links; -} - async function requireGameFolder(path: string) { const game = await inspectGameFolder(path); if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path }); diff --git a/apps/launcher/src/main/services/mods/mods-service.ts b/apps/launcher/src/main/services/mods/mods-service.ts index 46dc6af..e722056 100644 --- a/apps/launcher/src/main/services/mods/mods-service.ts +++ b/apps/launcher/src/main/services/mods/mods-service.ts @@ -17,6 +17,7 @@ import { AppError } from '@shared/errors.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts'; import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; +import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts'; import { getSettings, updateSettings } from '../config/settings-store.ts'; import { listCopies } from '../install/install-record.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; @@ -236,8 +237,10 @@ export async function exportModPreset( if (!preset) throw new AppError('mods_preset_invalid'); const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset'; + const defaultDir = await resolveDialogDefaultPath('mod-preset'); + const fileName = `${safeName}.wto-mods-preset.json`; const dialogOptions = { - defaultPath: `${safeName}.wto-mods-preset.json`, + defaultPath: defaultDir ? join(defaultDir, fileName) : fileName, filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }], }; const choice = window @@ -252,6 +255,7 @@ export async function exportModPreset( enabled: { ...preset.enabled }, }; await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8'); + await rememberDialogPath('mod-preset', choice.filePath); return { path: choice.filePath }; } @@ -260,9 +264,11 @@ export async function importModPreset( window: BrowserWindow | null, ): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> { const copy = await requireCopy(copyId); + const defaultPath = await resolveDialogDefaultPath('mod-preset'); const dialogOptions = { properties: ['openFile'] as Array<'openFile'>, filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }], + ...(defaultPath ? { defaultPath } : {}), }; const choice = window ? await dialog.showOpenDialog(window, dialogOptions) @@ -270,6 +276,7 @@ export async function importModPreset( if (choice.canceled || !choice.filePaths[0]) { return { imported: false, state: await buildModsStateView(copy) }; } + await rememberDialogPath('mod-preset', choice.filePaths[0]); let parsedRaw: unknown; try { @@ -309,6 +316,7 @@ export async function setModsFolder(copyId: string, folderPath: string | null): } } await updateSettings({ modsFolder: folderPath }); + if (folderPath !== null) await rememberDialogPath('mods-folder', folderPath); const copy = await requireCopy(copyId); return buildModsStateView(copy); } diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index c505131..c3a6831 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -6,6 +6,7 @@ import { AppError } from '@shared/errors.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts'; import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts'; +import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts'; import { maintenanceInProgress } from '../copies/copy-maintenance.ts'; import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts'; import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts'; @@ -95,15 +96,27 @@ export async function setSaveCurrencies(copyId: string, userId: string, values: } export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> { - const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] }; + const defaultPath = await resolveDialogDefaultPath('save-archive'); + const options = { + properties: ['openFile' as const], + filters: [{ name: 'ZIP', extensions: ['zip'] }], + ...(defaultPath ? { defaultPath } : {}), + }; const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); - return { path: result.canceled ? null : result.filePaths[0] ?? null }; + const chosen = result.canceled ? null : (result.filePaths[0] ?? null); + if (chosen) await rememberDialogPath('save-archive', chosen); + return { path: chosen }; } export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> { const copy = await requireCopy(copyId); await getSaveDetails(copyId, userId); - const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] }; + const defaultDir = await resolveDialogDefaultPath('save-archive'); + const fileName = `WTOffline-save-${userId}.zip`; + const options = { + defaultPath: defaultDir ? join(defaultDir, fileName) : fileName, + filters: [{ name: 'ZIP', extensions: ['zip'] }], + }; const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options); if (result.canceled || !result.filePath) return { path: null }; try { @@ -113,6 +126,7 @@ export async function exportSave(copyId: string, userId: string, window: Browser console.error('[saves] could not export the save:', error); throw new AppError('save_operation_failed'); } + await rememberDialogPath('save-archive', result.filePath); return { path: result.filePath }; } @@ -275,9 +289,16 @@ export async function copyOnlineData(copyId: string, userId: string, accountId: } export async function pickOfficialBackups(window: BrowserWindow | null): Promise { - const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] }; + const defaultPath = await resolveDialogDefaultPath('official-backups'); + const options = { + properties: ['openFile' as const, 'multiSelections' as const], + filters: [{ name: 'BLK', extensions: ['blk'] }], + ...(defaultPath ? { defaultPath } : {}), + }; const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options); - return result.canceled ? [] : result.filePaths; + if (result.canceled || result.filePaths.length === 0) return []; + if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]); + return result.filePaths; } export async function previewSelectedBackups( diff --git a/apps/launcher/src/main/util/dialog-paths.ts b/apps/launcher/src/main/util/dialog-paths.ts new file mode 100644 index 0000000..ef8fd3a --- /dev/null +++ b/apps/launcher/src/main/util/dialog-paths.ts @@ -0,0 +1,171 @@ +import { stat } from 'node:fs/promises'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { readJsonOr, writeJsonAtomic } from './atomic-json.ts'; + +/** + * Remembers the last directory chosen in native open/save dialogs, keyed by dialog category, + * persisted to `/dialog-paths.json`. Read/write errors are swallowed so dialog + * behavior is never disrupted. + */ + +export type DialogPathCategory = + | 'folder' + | 'save-archive' + | 'official-backups' + | 'mods-folder' + | 'mod-preset'; + +export interface DialogPathStore { + resolveDialogDefaultPath( + category: DialogPathCategory, + explicitPath?: string | null, + ): Promise; + rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise; +} + +const DIALOG_PATHS_FILENAME = 'dialog-paths.json'; +const LAST_KEY = 'last'; +const MAX_ANCESTOR_STEPS = 128; + +/** + * Resolve `candidate` to an existing directory: + * - If it is an existing directory, return its normalized path. + * - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory. + * - Return `undefined` when no existing ancestor directory can be reached. + */ +export async function resolveExistingDirectory(candidate: string | null | undefined): Promise { + if (!candidate) return undefined; + const trimmed = candidate.trim(); + if (!trimmed || !isAbsolute(trimmed)) return undefined; + + let current = resolve(trimmed); + for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { + try { + const info = await stat(current); + if (info.isDirectory()) return current; + } catch { + // Missing or inaccessible path; continue walking toward the filesystem root. + } + const parent = dirname(current); + if (parent === current) return undefined; + current = parent; + } + return undefined; +} + +/** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */ +export function createDialogPathStore( + resolveStorePath: () => Promise | string | null, +): DialogPathStore { + let cached: Map | null = null; + let loading: Promise> | null = null; + let pending: Promise = Promise.resolve(); + + async function loadMap(): Promise> { + if (cached) return cached; + if (loading) return loading; + + loading = (async () => { + const map = new Map(); + const storePath = await resolveStorePath(); + if (storePath) { + try { + const raw = await readJsonOr(storePath, null); + if (raw && typeof raw === 'object' && !Array.isArray(raw)) { + for (const [key, value] of Object.entries(raw as Record)) { + if (typeof value === 'string' && value.trim().length > 0) { + map.set(key, value); + } + } + } + } catch (error) { + console.warn('[dialog-paths] failed to read dialog paths:', error); + } + } + cached = map; + return map; + })().finally(() => { + loading = null; + }); + + return loading; + } + + return { + async resolveDialogDefaultPath( + category: DialogPathCategory, + explicitPath?: string | null, + ): Promise { + try { + const explicitDir = await resolveExistingDirectory(explicitPath); + if (explicitDir) return explicitDir; + + const map = await loadMap(); + const categoryPath = map.get(category); + if (categoryPath) { + const resolved = await resolveExistingDirectory(categoryPath); + if (resolved) return resolved; + } + + const lastPath = map.get(LAST_KEY); + if (lastPath && lastPath !== categoryPath) { + const resolved = await resolveExistingDirectory(lastPath); + if (resolved) return resolved; + } + } catch (error) { + console.warn('[dialog-paths] failed to resolve default dialog path:', error); + } + return undefined; + }, + + async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise { + const dir = await resolveExistingDirectory(selectedPath); + if (!dir) return; + + const operation = pending.then(async () => { + const map = await loadMap(); + if (map.get(category) === dir && map.get(LAST_KEY) === dir) return; + + map.set(category, dir); + map.set(LAST_KEY, dir); + + const storePath = await resolveStorePath(); + if (!storePath) return; + try { + await writeJsonAtomic(storePath, Object.fromEntries(map)); + } catch (error) { + console.warn('[dialog-paths] failed to save dialog paths:', error); + } + }); + pending = operation.then(() => undefined, () => undefined); + await operation; + }, + }; +} + +async function defaultStorePath(): Promise { + try { + const mod = await import('electron') as { + readonly app?: { getPath?: (name: 'userData') => string }; + readonly default?: { app?: { getPath?: (name: 'userData') => string } }; + }; + const electronApp = mod.app ?? mod.default?.app; + if (typeof electronApp?.getPath !== 'function') return null; + return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME); + } catch { + return null; + } +} + +const defaultStore = createDialogPathStore(defaultStorePath); + +export function resolveDialogDefaultPath( + category: DialogPathCategory, + explicitPath?: string | null, +): Promise { + return defaultStore.resolveDialogDefaultPath(category, explicitPath); +} + +export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise { + return defaultStore.rememberDialogPath(category, selectedPath); +} diff --git a/apps/launcher/src/renderer/src/components/FolderField.tsx b/apps/launcher/src/renderer/src/components/FolderField.tsx index fa85583..8b93c39 100644 --- a/apps/launcher/src/renderer/src/components/FolderField.tsx +++ b/apps/launcher/src/renderer/src/components/FolderField.tsx @@ -5,16 +5,22 @@ interface FolderFieldProps { readonly path: string | null; /** Title of the folder dialog. */ readonly dialogTitle: string; + /** Optional starting directory when no path is chosen yet. */ + readonly defaultPath?: string | null | undefined; readonly disabled?: boolean; readonly onChosen: (path: string) => void; readonly onError: (error: unknown) => void; } /** A chosen folder and the button that opens the folder dialog. */ -export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) { +export function FolderField({ path, dialogTitle, defaultPath, disabled = false, onChosen, onError }: FolderFieldProps) { const { t } = useTranslation(); const choose = (): void => { - ipcInvoke('dialog:pickFolder', { title: dialogTitle }) + const startPath = path ?? defaultPath; + ipcInvoke('dialog:pickFolder', { + title: dialogTitle, + ...(startPath ? { defaultPath: startPath } : {}), + }) .then(({ path: chosen }) => { if (chosen) onChosen(chosen); }) diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index e4f6b74..b63dfd4 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -97,7 +97,9 @@ }, "decals": { "source": "Decal source", - "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.", + "hint": "Select the online game root folder, cache, or cache/content for cached decals and downloadable skins. Placeholder decals are used when no cache is available.", + "autoDetectedNotice": "Online decal cache detected automatically and will be imported during installation. Click the button above if you prefer placeholder decals.", + "importFromSource": "Import from online source", "choose": "Choose decal cache…", "useDefault": "Use placeholder decals", "importing": "Importing decal cache", @@ -158,7 +160,8 @@ "copy": "Copy installation (recommended)", "copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.", "spaceSaving": "Space-saving copy", - "spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.", + "spaceSavingBody": "Resource packs are shared with the online client via same-volume hard links, requiring only about {{size}} of additional copying. Windows Explorer Properties counts shared files toward both folders, but only the newly copied files use extra disk space. An in-place update to the online client can change shared files.", + "spaceSavingBreakdown": "Estimated copy: about {{copy}} · Shared via hard links: about {{shared}} (no extra disk space)", "spaceSavingPending": "Calculating how much space can be saved.", "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.", @@ -214,6 +217,8 @@ "recording": "Finishing installation" }, "copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", + "copiedActual": "Copied to disk: {{copied}} / {{copyTotal}} ({{copiedFiles}} / {{copyTotalFiles}} files)", + "linkedShared": "Shared via hard links (no extra space): {{linked}} / {{linkTotal}} ({{linkedFiles}} / {{linkTotalFiles}} resource packs)", "verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", "prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", "cancelHint": "Can be cancelled at any time; copied files will be deleted", @@ -258,16 +263,31 @@ "repair": "Repair client", "repairAction": "Repair", "repairHint": "Restore the original files from the backup. Game files will be generated again at launch.", - "delete": "Delete client", - "deleteAction": "Delete…", - "deleteHint": "The data folder is kept by default.", - "unlink": "Remove registration", - "unlinkAction": "Remove…", - "unlinkHint": "The launcher keeps the Steam game files and data folder in place.", - "unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.", - "deleteLocation": "Delete the offline client at {{path}}?", - "deleteData": "Also delete the data folder at {{path}}", - "confirm": "Confirm deletion", + "remove": "Remove client", + "removeAction": "Remove…", + "removeCopyHint": "Removes from the launcher list by default without deleting files on disk.", + "removeRestoreHint": "Removes from the launcher list by default; optionally restores original files and removes offline patch files while keeping the base game.", + "removeUnlinkHint": "Removes only from the launcher list without deleting game files on disk.", + "removeSteamHint": "Removes only from the launcher list. Steam game files and the data folder stay in place.", + "removeCopyNotice": "Removes {{path}} from the launcher list. All game files and data on disk are kept by default.", + "removeListOnlyNotice": "Removes {{path}} from the launcher list only. Game files on disk will not be deleted.", + "removeSteamNotice": "Removes {{path}} from the launcher list only. Steam game files and data on disk will not be deleted.", + "originCopy": "Detected client type: full copy (created as an independent copy by the launcher).", + "originHardlink": "Detected client type: space-saving hard-linked copy (read-only resource packs are shared; deleting this copy does not affect the original game folder).", + "originInPlace": "Detected client type: in-place installation (full folder deletion is disabled to protect the base game).", + "originUnknown": "Detected client type: existing folder of unknown origin (no client identity marker found; full folder deletion is disabled for safety).", + "originUnknownHardlinked": "Detected client type: existing folder of unknown origin (hard-linked resources were detected without a client identity marker; full folder deletion is disabled for safety).", + "deleteFiles": "Also delete the client folder at {{path}}", + "deleteHardlinkHint": "Note: This client shares read-only resource packs via hard links; deleting the copy folder will not affect the original game folder.", + "deleteFilesWarning": "This will permanently delete all files in the copied client folder at {{path}}. This action cannot be undone.", + "deleteHardlinkWarning": "This will permanently delete all files in the hard-linked copy folder at {{path}} (the original game folder is unaffected). This action cannot be undone.", + "restoreStock": "Restore original files and remove offline patch files (keep base game)", + "restoreStockHint": "Restores the 4 original core files from wtoffline\\stock and removes wtoffline\\ along with network hook files (wto_ws.dll / wto_ws.cfg / wto_ws.log). No base game files are deleted.", + "deleteData": "Also delete the data folder at {{path}} (contains saves, settings, and logs)", + "openFolder": "Open folder", + "confirmRemove": "Remove from list", + "confirmRestore": "Restore and remove", + "confirmDelete": "Confirm deletion", "phase": { "checking": "Checking the client", "copying": "Copying changed files", @@ -280,7 +300,7 @@ "repair": "Original files restored.", "update": "Client updated.", "compact": "Space-saving conversion complete.", - "delete": "Client deleted.", + "delete": "Client removed.", "cancelled": "Maintenance cancelled." } }, @@ -1118,7 +1138,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. Log into the online hangar once to populate it, then choose cache/content (or cache).", + "decal_source_invalid": "The selected folder does not contain a usable decal cache. Log into the online hangar once to populate it, then choose the online game root folder, cache, or cache/content.", "decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.", "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.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 5c6abf9..a209d6d 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -97,7 +97,9 @@ }, "decals": { "source": "贴花来源", - "hint": "可导入在线版游戏的 cache/content(或 cache),同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。", + "hint": "可直接选择在线版游戏根目录、cache 或 cache/content,同时支持已缓存的真实贴花与可下载涂装。未导入时使用占位贴花。", + "autoDetectedNotice": "已自动检测到在线版贴花缓存,安装时将一并导入。如需使用占位贴花,可点击上方按钮取消。", + "importFromSource": "从在线版来源导入", "choose": "选择贴花缓存…", "useDefault": "使用占位贴花", "importing": "正在导入贴花缓存", @@ -158,7 +160,8 @@ "copy": "复制安装(推荐)", "copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。", "spaceSaving": "节省空间的复制", - "spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。", + "spaceSavingBody": "资源包通过同盘硬链接与在线版共享,仅需额外复制约 {{size}};Windows 资源管理器「属性」会重复统计共享文件大小,实际只占新增复制的磁盘空间。原版就地更新可能改变共享文件。", + "spaceSavingBreakdown": "预计实际复制约 {{copy}} · 硬链接共享约 {{shared}}(不额外占用磁盘空间)", "spaceSavingPending": "正在估算可节省的空间。", "spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。", "sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。", @@ -214,6 +217,8 @@ "recording": "完成安装" }, "copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", + "copiedActual": "实际复制:已复制 {{copied}} / {{copyTotal}}({{copiedFiles}} / {{copyTotalFiles}} 个文件)", + "linkedShared": "硬链接共享(不额外占空间):已链接共享 {{linked}} / {{linkTotal}}({{linkedFiles}} / {{linkTotalFiles}} 个资源包)", "verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", "prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", "cancelHint": "可随时取消,已复制的文件将被删除", @@ -258,16 +263,31 @@ "repair": "修复客户端", "repairAction": "修复", "repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。", - "delete": "删除客户端", - "deleteAction": "删除…", - "deleteHint": "默认保留数据目录。", - "unlink": "解除登记", - "unlinkAction": "解除登记…", - "unlinkHint": "Steam 游戏文件和数据目录将留在原处。", - "unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。", - "deleteLocation": "确认删除 {{path}} 中的离线客户端?", - "deleteData": "同时删除 {{path}} 中的数据", - "confirm": "确认删除", + "remove": "移除客户端", + "removeAction": "移除…", + "removeCopyHint": "默认仅从启动器列表移除,不会删除磁盘文件。", + "removeRestoreHint": "默认仅从启动器列表移除;也可选还原为原版并清理离线补丁文件(保留游戏本体)。", + "removeUnlinkHint": "仅从启动器列表移除,不会删除磁盘上的游戏文件。", + "removeSteamHint": "仅从启动器列表移除,Steam 游戏文件和数据目录将留在原处。", + "removeCopyNotice": "将从启动器列表移除 {{path}}。默认保留磁盘上的所有游戏文件和数据。", + "removeListOnlyNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的游戏文件。", + "removeSteamNotice": "将仅从启动器列表移除 {{path}},不会删除磁盘上的 Steam 游戏文件和数据目录。", + "originCopy": "识别结果:完整复制副本(由启动器独立复制创建)。", + "originHardlink": "识别结果:省空间硬链接副本(只读资源包与原版共享,删除副本不会影响原版游戏目录)。", + "originInPlace": "识别结果:原位安装目录(为保护原版游戏本体,不支持直接删除整个文件夹)。", + "originUnknown": "识别结果:未知来源的已有目录(缺少客户端身份标记,为保护游戏文件不支持直接删除整个文件夹)。", + "originUnknownHardlinked": "识别结果:未知来源的已有目录(检测到硬链接资源包,但缺少客户端身份标记;为保护原版目录不支持直接删除整个文件夹)。", + "deleteFiles": "同时删除客户端文件夹 {{path}}", + "deleteHardlinkHint": "提示:此客户端使用同盘硬链接共享资源包,删除副本文件夹不会影响原版游戏目录。", + "deleteFilesWarning": "将永久删除客户端副本文件夹 {{path}} 中的全部文件,此操作无法撤销。", + "deleteHardlinkWarning": "将永久删除硬链接副本文件夹 {{path}} 中的全部文件(不会影响原版游戏目录),此操作无法撤销。", + "restoreStock": "还原为原版并清理离线补丁文件(保留游戏本体)", + "restoreStockHint": "将从 wtoffline\\stock 恢复原版 4 个核心文件,并删除 wtoffline\\ 目录与网络钩子文件(wto_ws.dll / wto_ws.cfg / wto_ws.log),绝不删除其他游戏本体文件。", + "deleteData": "同时删除数据文件夹 {{path}}(包含存档、配置与日志)", + "openFolder": "打开所在文件夹", + "confirmRemove": "从列表移除", + "confirmRestore": "还原并移除", + "confirmDelete": "确认删除", "phase": { "checking": "正在检查客户端", "copying": "正在复制有变化的文件", @@ -280,7 +300,7 @@ "repair": "原版文件已还原。", "update": "客户端已更新。", "compact": "省空间转换已完成。", - "delete": "客户端已删除。", + "delete": "客户端已移除。", "cancelled": "维护已取消。" } }, @@ -1118,7 +1138,7 @@ "copy_not_found": "所选客户端已不可用。", "copies_write_failed": "无法保存客户端记录。", "copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。", - "decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版目录中的 cache/content(或 cache)。", + "decal_source_invalid": "选定的目录缺少有效的贴花缓存。请先登录过在线版机库生成缓存,再选择在线版游戏根目录、cache 或 cache/content。", "decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。", "maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。", "maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。", diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx index 5bb637a..48634c3 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx @@ -20,6 +20,10 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc const [info, setInfo] = useState(null); const [removal, setRemoval] = useState(null); + useEffect(() => { + setRemoval(null); + }, [record.id]); + useEffect(() => { let mounted = true; setInfo(null); @@ -60,7 +64,8 @@ export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanc busy={busy} options={removal} onOptionsChange={setRemoval} - onRemove={(deleteData) => run('delete', { deleteData })} + onRemove={(options) => run('delete', options)} + onOpenFolder={() => { ipcInvoke('app:openFolder', { path: record.copyPath }).catch(onError); }} /> {active && } {result &&

{t(`copies.maintenance.result.${result}`)}

} diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx index f66cd7d..f8c7a7f 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenanceControls.tsx @@ -69,44 +69,112 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onChooseSour } export interface CopyRemovalOptions { + readonly deleteFiles: boolean; + readonly restoreStock: boolean; readonly deleteData: boolean; } interface CopyRemovalProps extends CopyMaintenanceControlsProps { readonly options: CopyRemovalOptions | null; readonly onOptionsChange: (options: CopyRemovalOptions | null) => void; - readonly onRemove: (deleteData: boolean) => void; + readonly onRemove: (options: CopyRemovalOptions) => void; + readonly onOpenFolder: () => void; } -export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove }: CopyRemovalProps) { +function clientOriginNoteKey(info: MaintenanceInfo): string { + if (info.clientOrigin === 'copy') return 'copies.maintenance.originCopy'; + if (info.clientOrigin === 'hardlink') return 'copies.maintenance.originHardlink'; + if (info.clientOrigin === 'in-place') return 'copies.maintenance.originInPlace'; + return info.hasHardlinkedResources + ? 'copies.maintenance.originUnknownHardlinked' + : 'copies.maintenance.originUnknown'; +} + +export function CopyRemoval({ record, info, busy, options, onOptionsChange, onRemove, onOpenFolder }: CopyRemovalProps) { const { t } = useTranslation(); const steam = info?.steamLocations; - const unlinkOnly = steam?.copyInSteam === true; - const canDeleteData = !unlinkOnly && !steam?.dataInSteam; - const action = t(unlinkOnly ? 'copies.maintenance.unlink' : 'copies.maintenance.confirm'); + const copyInSteam = steam?.copyInSteam === true; + const dataInSteam = steam?.dataInSteam === true; + const canDeleteFiles = info?.canDeleteFiles === true; + const isHardlinkCopy = info?.clientOrigin === 'hardlink'; + const canRestoreAndRemove = info !== null && !canDeleteFiles && info.canRestoreAndRemove; + const canDeleteData = info !== null && !copyInSteam && !dataInSteam; + const willDeleteFiles = canDeleteFiles && options?.deleteFiles === true; + const willRestoreStock = canRestoreAndRemove && options?.restoreStock === true; + const willDeleteData = canDeleteData && options?.deleteData === true; + const action = t( + willDeleteFiles || willDeleteData + ? 'copies.maintenance.confirmDelete' + : willRestoreStock + ? 'copies.maintenance.confirmRestore' + : 'copies.maintenance.confirmRemove', + ); + const rowHint = copyInSteam + ? t('copies.maintenance.removeSteamHint') + : canDeleteFiles + ? t('copies.maintenance.removeCopyHint') + : canRestoreAndRemove + ? t('copies.maintenance.removeRestoreHint') + : t('copies.maintenance.removeUnlinkHint'); + const confirmNotice = copyInSteam + ? t('copies.maintenance.removeSteamNotice', { path: steam?.copyPath ?? record.copyPath }) + : canDeleteFiles + ? t('copies.maintenance.removeCopyNotice', { path: record.copyPath }) + : t('copies.maintenance.removeListOnlyNotice', { path: record.copyPath }); return ( <> - - {options && (
-

{t(unlinkOnly ? 'copies.maintenance.unlinkLocation' : 'copies.maintenance.deleteLocation', { path: steam?.copyPath ?? record.copyPath })}

+

{confirmNotice}

+ {info &&

{t(clientOriginNoteKey(info))}

} + {canDeleteFiles && ( + <> + + {isHardlinkCopy &&

{t('copies.maintenance.deleteHardlinkHint')}

} + + )} + {willDeleteFiles && ( + +

{t(isHardlinkCopy ? 'copies.maintenance.deleteHardlinkWarning' : 'copies.maintenance.deleteFilesWarning', { path: record.copyPath })}

+
+ )} + {canRestoreAndRemove && ( + <> + +

{t('copies.maintenance.restoreStockHint')}

+ + )} {canDeleteData && ( )}
+ {!canDeleteFiles && ( + + )} -
diff --git a/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx b/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx index 062aa85..b8ca539 100644 --- a/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx +++ b/apps/launcher/src/renderer/src/pages/copies/CopySummary.tsx @@ -20,13 +20,46 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc const { t, i18n } = useTranslation(); const [name, setName] = useState(record.name); const [importing, setImporting] = useState(false); + const [detectedSourceDecals, setDetectedSourceDecals] = useState(null); useEffect(() => setName(record.name), [record.id, record.name]); + // Read-only probe of the copy's registered online source for a usable decal cache. + useEffect(() => { + setDetectedSourceDecals(null); + if (!record.sourcePath) return; + let current = true; + ipcInvoke('decals:detectSource', { path: record.sourcePath }) + .then(({ path }) => { + if (current) setDetectedSourceDecals(path); + }) + .catch(() => { + if (current) setDetectedSourceDecals(null); + }); + return () => { + current = false; + }; + }, [record.id, record.sourcePath]); const missing = missingFeatures(record).length; const verified = isVerified(record.gameVersion, supportedVersions); + const importFromSource = async (): Promise => { + if (!detectedSourceDecals) return; + setImporting(true); + try { + await ipcInvoke('copies:setDecalSource', { id: record.id, path: detectedSourceDecals }); + } catch (error) { + onError(error); + } finally { + setImporting(false); + } + }; const applyDecals = async (chooseFolder: boolean): Promise => { setImporting(true); try { - const path = chooseFolder ? (await ipcInvoke('dialog:pickFolder', { title: t('decals.choose') })).path : null; + const path = chooseFolder + ? (await ipcInvoke('dialog:pickFolder', { + title: t('decals.choose'), + ...(record.sourcePath ? { defaultPath: record.sourcePath } : {}), + })).path + : null; if (chooseFolder && path === null) return; await ipcInvoke('copies:setDecalSource', { id: record.id, path }); } catch (error) { @@ -71,6 +104,11 @@ export function CopySummary({ record, supportedVersions, onShowFeatures, onReloc {folder(record.dataPath)} {t(importing ? 'decals.importing' : record.decalCacheId ? 'decals.imported' : 'decals.default')} + {detectedSourceDecals && ( + + )} diff --git a/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts b/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts index 4ed7b99..6c198fe 100644 --- a/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts +++ b/apps/launcher/src/renderer/src/pages/copies/useCopyMaintenance.ts @@ -4,7 +4,10 @@ import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/ma import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts'; export type MaintenanceOperation = MaintenanceRequest['operation']; -export type MaintenanceOptions = Pick, 'deleteData' | 'steamLocations' | 'sourcePath'>; +export type MaintenanceOptions = Pick< + IpcInput<'copies:maintain'>, + 'deleteFiles' | 'restoreStock' | 'deleteData' | 'steamLocations' | 'sourcePath' +>; export interface MaintenanceOutcome { readonly copyId: string; diff --git a/apps/launcher/src/renderer/src/pages/install/DataStep.tsx b/apps/launcher/src/renderer/src/pages/install/DataStep.tsx index 2172f4c..ea9266e 100644 --- a/apps/launcher/src/renderer/src/pages/install/DataStep.tsx +++ b/apps/launcher/src/renderer/src/pages/install/DataStep.tsx @@ -8,6 +8,8 @@ interface DataStepProps { readonly dataPath: string; readonly dataProblem: DataFolderProblem | null; readonly decalSource: string | null; + readonly decalAutoDetected: boolean; + readonly defaultDecalPath?: string | null | undefined; readonly steamDataPath: string | null; readonly steamDataConfirmed: boolean; readonly onSteamDataConfirmed: (confirmed: boolean) => void; @@ -17,7 +19,19 @@ interface DataStepProps { } /** Step 3: where saves, caches and logs of the offline version are kept. */ -export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, steamDataConfirmed, onSteamDataConfirmed, onDataPath, onDecalSource, onError }: DataStepProps) { +export function DataStep({ + dataPath, + dataProblem, + decalSource, + decalAutoDetected, + defaultDecalPath, + steamDataPath, + steamDataConfirmed, + onSteamDataConfirmed, + onDataPath, + onDecalSource, + onError, +}: DataStepProps) { const { t } = useTranslation(); return ( <> @@ -35,9 +49,16 @@ export function DataStep({ dataPath, dataProblem, decalSource, steamDataPath, st )} - + {decalSource && } + {decalAutoDetected && decalSource && {t('decals.autoDetectedNotice')}} ); } diff --git a/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx b/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx index f92ce7d..fff0d8c 100644 --- a/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx +++ b/apps/launcher/src/renderer/src/pages/install/MethodStep.tsx @@ -89,6 +89,14 @@ export function MethodStep({ source, sourceSize, choice, onChoice, onError }: Me : t('method.spaceSavingPending')} onSelect={() => choose('hardlink')} > + {sourceSize && savingAvailable && ( +

+ {t('method.spaceSavingBreakdown', { + copy: formatBytes(bytesToCopy(sourceSize, 'hardlink')), + shared: formatBytes(sourceSize.linkableBytes ?? 0), + })} +

+ )} {targetPicker} 0 + ? { + copiedBytes: progress.copiedBytes, + copyTotalBytes: progress.copyTotalBytes, + linkedBytes: progress.linkedBytes, + linkTotalBytes: progress.linkTotalBytes, + linkedFiles: progress.linkedFiles, + linkTotalFiles: progress.linkTotalFiles, + copiedFiles: Math.max(0, progress.doneFiles - progress.linkedFiles), + copyTotalFiles: Math.max(0, progress.totalFiles - progress.linkTotalFiles), + } + : null; return ( <> {phases.map((name, position) => { @@ -32,14 +53,35 @@ export function ProgressStep({ progress, useHardLinks, importDecals }: { })} {tracking && ( -
- {t(caption, { - done: formatBytes(progress.doneBytes), - total: formatBytes(progress.totalBytes), - doneFiles: progress.doneFiles.toLocaleString(), - totalFiles: progress.totalFiles.toLocaleString(), - })} -
+ hardlinkStats ? ( + <> +
+ {t('progress.copiedActual', { + copied: formatBytes(hardlinkStats.copiedBytes), + copyTotal: formatBytes(hardlinkStats.copyTotalBytes), + copiedFiles: hardlinkStats.copiedFiles.toLocaleString(), + copyTotalFiles: hardlinkStats.copyTotalFiles.toLocaleString(), + })} +
+
+ {t('progress.linkedShared', { + linked: formatBytes(hardlinkStats.linkedBytes), + linkTotal: formatBytes(hardlinkStats.linkTotalBytes), + linkedFiles: hardlinkStats.linkedFiles.toLocaleString(), + linkTotalFiles: hardlinkStats.linkTotalFiles.toLocaleString(), + })} +
+ + ) : ( +
+ {t(caption, { + done: formatBytes(progress.doneBytes), + total: formatBytes(progress.totalBytes), + doneFiles: progress.doneFiles.toLocaleString(), + totalFiles: progress.totalFiles.toLocaleString(), + })} +
+ ) )} ); diff --git a/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx b/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx index 88a24d8..166b184 100644 --- a/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx +++ b/apps/launcher/src/renderer/src/pages/install/WizardMain.tsx @@ -44,6 +44,8 @@ export function WizardMain({ wizard, supportedVersions }: { readonly wizard: Ins steamDataConfirmed={wizard.steamDataConfirmed} onSteamDataConfirmed={wizard.setSteamDataConfirmed} decalSource={wizard.decalSource} + decalAutoDetected={wizard.decalAutoDetected} + defaultDecalPath={wizard.decalProbePath} onDataPath={wizard.setDataPath} onDecalSource={wizard.setDecalSource} onError={wizard.report} diff --git a/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts b/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts index db26eab..2b28307 100644 --- a/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts +++ b/apps/launcher/src/renderer/src/pages/install/useInstallWizard.ts @@ -40,7 +40,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { problem: DataFolderProblem | null; confirmed: boolean; } | null>(null); - const [decalSource, setDecalSource] = useState(null); + const [decalSource, setDecalSourceState] = useState(null); + const [decalAutoDetected, setDecalAutoDetected] = useState(false); + const [decalManuallyEdited, setDecalManuallyEdited] = useState(false); const [check, setCheck] = useState(null); const [missingAccepted, setMissingAccepted] = useState(false); const [progress, setProgress] = useState(null); @@ -66,8 +68,34 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { ? (source?.path ?? null) : null; const plannedStockSourcePath = source?.needsStockSource ? (stockSource?.path ?? null) : null; + const decalProbePath = stockSource?.path ?? source?.path ?? null; const dataInspectionKey = JSON.stringify([dataPath, plannedCopyPath, plannedSourcePath, plannedStockSourcePath]); + // Read-only probe of the player-selected source folder for a usable decal cache. + useEffect(() => { + if (!active || !decalProbePath || decalManuallyEdited) return; + let current = true; + ipcInvoke('decals:detectSource', { path: decalProbePath }) + .then(({ path }) => { + if (!current) return; + if (path) { + setDecalSourceState(path); + setDecalAutoDetected(true); + } else { + setDecalSourceState(null); + setDecalAutoDetected(false); + } + }) + .catch(() => { + if (!current) return; + setDecalSourceState(null); + setDecalAutoDetected(false); + }); + return () => { + current = false; + }; + }, [active, decalProbePath, decalManuallyEdited]); + useEffect(() => { if (!active || !dataPath) return; let current = true; @@ -119,6 +147,12 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { useEffect(() => ipcOn('event:install-progress', setProgress), []); + const resetDecals = (): void => { + setDecalSourceState(null); + setDecalAutoDetected(false); + setDecalManuallyEdited(false); + }; + const start = (): void => { clear(); setMode('new'); @@ -130,7 +164,7 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { setDraftId(null); setDataPath(''); setDataInspection(null); - setDecalSource(null); + resetDecals(); setActive(true); ipcInvoke('install:prepareCopy').then(({ id, dataPath: folder }) => { setDraftId(id); @@ -145,11 +179,13 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { setStockSource(null); setChoice(nextMode === 'existing' ? { method: 'existing', target: null, steamConfirmed: false } : NO_CHOICE); setName(''); + resetDecals(); }; const chooseSource = (found: GameFolderInspection | null): void => { setSource(found); setStockSource(null); + resetDecals(); const isExisting = mode === 'existing' || found?.hasOfflineBackup || found?.needsStockSource; const defaultMethod = isExisting ? 'existing' : 'copy'; setChoice({ method: defaultMethod, target: null, steamConfirmed: false }); @@ -166,6 +202,17 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { } }; + const chooseStockSource = (found: GameFolderInspection | null): void => { + setStockSource(found); + resetDecals(); + }; + + const setDecalSource = (path: string | null): void => { + setDecalSourceState(path); + setDecalAutoDetected(false); + setDecalManuallyEdited(true); + }; + const install = (): void => { if (!sourceUsable(source, stockSource) || !draftId || !dataReady) return; const directFolder = choice.method === 'in-place' || choice.method === 'existing'; @@ -230,9 +277,9 @@ export function useInstallWizard({ onInstalled }: WizardOptions) { }; return { - active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, check, missingAccepted, progress, cancelling, message, canGoOn, + active, mode, step, index, source, stockSource, sourceSize, choice, name, dataPath, dataProblem, decalSource, decalAutoDetected, decalProbePath, check, missingAccepted, progress, cancelling, message, canGoOn, steamDataPath: dataChecked?.inSteam ? dataChecked.path : null, steamDataConfirmed: dataChecked?.confirmed ?? false, - start, back, next, cancel, report, chooseMode, chooseSource, setStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted, + start, back, next, cancel, report, chooseMode, chooseSource, setStockSource: chooseStockSource, setChoice, setName, setDataPath, setSteamDataConfirmed, setDecalSource, setMissingAccepted, }; } diff --git a/apps/launcher/src/shared/ipc/channels.ts b/apps/launcher/src/shared/ipc/channels.ts index c6c433e..20beb28 100644 --- a/apps/launcher/src/shared/ipc/channels.ts +++ b/apps/launcher/src/shared/ipc/channels.ts @@ -14,6 +14,8 @@ export const IPC_CHANNEL_PREFIXES = [ 'install:', /** Listing and managing installed copies. */ 'copies:', + /** Read-only detection of decal cache folders in player-selected or registered sources. */ + 'decals:', /** Settings shared by the saves of a game copy. */ 'tuning:', /** Additive mods repository, per-copy ordering/toggles, and presets. */ diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index d87aa0f..b941720 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -65,8 +65,11 @@ export const ipcContract = { output: z.object({ path: z.string().nullable() }), }, 'dialog:pickFolder': { - /** The dialog title, already translated by the window. */ - input: z.object({ title: z.string().optional() }), + /** The dialog title, already translated by the window, and an optional starting path. */ + input: z.object({ + title: z.string().optional(), + defaultPath: z.string().optional(), + }), /** The chosen folder, or null when the player cancelled. */ output: z.object({ path: z.string().nullable() }), }, @@ -167,6 +170,11 @@ export const ipcContract = { input: z.void(), output: z.void(), }, + 'decals:detectSource': { + /** Read-only check for a usable decal cache inside a player-chosen or registered folder. */ + input: z.object({ path: z.string().min(1) }), + output: z.object({ path: z.string().nullable() }), + }, 'saves:list': { input: z.object({ copyId: CopyIdSchema }), output: SaveListSchema, diff --git a/apps/launcher/src/shared/schemas/install.ts b/apps/launcher/src/shared/schemas/install.ts index 3981ff7..9aa4254 100644 --- a/apps/launcher/src/shared/schemas/install.ts +++ b/apps/launcher/src/shared/schemas/install.ts @@ -1,5 +1,10 @@ import { z } from 'zod'; +/** Self-described origin of an offline client folder recorded in wtoffline/client.json. */ +export const CLIENT_ORIGINS = ['copy', 'hardlink', 'in-place'] as const; +export const ClientOriginSchema = z.enum(CLIENT_ORIGINS); +export type ClientOrigin = z.output; + /** What the launcher found in a folder the player chose as their War Thunder installation. */ export const GameFolderInspectionSchema = z.object({ path: z.string(), @@ -16,6 +21,10 @@ export const GameFolderInspectionSchema = z.object({ hasOfflineBackup: z.boolean(), /** True when the folder is already patched for offline use but lacks a wtoffline/stock backup. */ needsStockSource: z.boolean(), + /** Client origin recorded in wtoffline/client.json when present and valid, or null otherwise. */ + clientOrigin: ClientOriginSchema.nullable().optional(), + /** True when at least one eligible read-only resource pack has multiple hard links (nlink >= 2). */ + hasHardlinkedResources: z.boolean().optional(), }); export type GameFolderInspection = z.output; @@ -143,6 +152,18 @@ export const InstallProgressSchema = z.object({ totalBytes: z.number(), doneFiles: z.number(), totalFiles: z.number(), + /** Actual bytes written to disk during copying (excludes hard-linked files). */ + copiedBytes: z.number().nonnegative().optional(), + /** Total bytes planned to be written to disk during copying (excludes hard-linked files). */ + copyTotalBytes: z.number().nonnegative().optional(), + /** Bytes shared via hard links so far (occupies no extra disk space). */ + linkedBytes: z.number().nonnegative().optional(), + /** Total bytes planned to be shared via hard links. */ + linkTotalBytes: z.number().nonnegative().optional(), + /** Number of hard-linked files created so far. */ + linkedFiles: z.number().nonnegative().optional(), + /** Total number of files planned to be shared via hard links. */ + linkTotalFiles: z.number().nonnegative().optional(), }); export type InstallProgress = z.output; @@ -173,6 +194,8 @@ export const InstallRecordSchema = z.object({ sourceFiles: z.array(z.string().min(1)).optional(), /** Relative resource paths linked to the source and detached on a version update. */ hardlinkedFiles: z.array(z.string().min(1)).optional(), + /** Client origin read from wtoffline/client.json when registering an existing folder. */ + detectedOrigin: ClientOriginSchema.optional(), /** Runtime check hydrated when listing copies (never persisted to copies.json): true if copyPath or core game files are missing on disk. */ folderMissing: z.boolean().optional(), }); diff --git a/apps/launcher/src/shared/schemas/maintenance.ts b/apps/launcher/src/shared/schemas/maintenance.ts index 7e06f85..b07ff33 100644 --- a/apps/launcher/src/shared/schemas/maintenance.ts +++ b/apps/launcher/src/shared/schemas/maintenance.ts @@ -1,10 +1,12 @@ import { z } from 'zod'; -import { CopyIdSchema } from './install.ts'; +import { ClientOriginSchema, CopyIdSchema } from './install.ts'; export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'compact', 'delete', 'confirm-steam', 'set-source']); export const MaintenanceRequestSchema = z.object({ id: CopyIdSchema, operation: MaintenanceOperationSchema, + deleteFiles: z.boolean().default(false), + restoreStock: z.boolean().default(false), deleteData: z.boolean().default(false), sourcePath: z.string().min(1).optional(), steamLocations: z.object({ @@ -24,6 +26,10 @@ export const MaintenanceInfoSchema = z.object({ copyInSteam: z.boolean(), dataInSteam: z.boolean(), }).nullable(), + clientOrigin: ClientOriginSchema.nullable(), + hasHardlinkedResources: z.boolean(), + canDeleteFiles: z.boolean(), + canRestoreAndRemove: z.boolean(), }); export const MaintenanceProgressSchema = z.object({ id: CopyIdSchema, diff --git a/apps/server/src/battle/battle-settlement.ts b/apps/server/src/battle/battle-settlement.ts index dd99412..258d490 100644 --- a/apps/server/src/battle/battle-settlement.ts +++ b/apps/server/src/battle/battle-settlement.ts @@ -53,6 +53,8 @@ export interface BattleSettlementDeps { readonly streaks: BattleStreaks; readonly items: ItemCatalogue; readonly repair: RepairRules; + /** Optional hook receiving total base (unboosted) vehicle RP earned in the battle. */ + readonly onBattleRpEarned?: ((baseVehicleRp: number, nowSec: number) => void) | undefined; } const REPAIR_MODE: Readonly> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' }; @@ -87,12 +89,15 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul); } const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment); - const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), { + const vehicleRps = rewards.vehicles.map(vehicleRpOf); + const research = investBattleRp(profile, vehicleRps, { country: session.country, requiredClass: session.requiredClass, difficulty, nowUnixSec: log.timeSec, }, deps); + const baseVehicleRp = vehicleRps.reduce((sum, vehicle) => sum + Math.max(0, vehicle.noBonusExp), 0); + if (baseVehicleRp > 0) deps.onBattleRpEarned?.(baseVehicleRp, log.timeSec); recordBoosterUses(profile, boosters.uses, log); const wager = activeWager(profile, deps.items); const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, { diff --git a/apps/server/src/battle/battle-spares.ts b/apps/server/src/battle/battle-spares.ts index ae326b9..f306f76 100644 --- a/apps/server/src/battle/battle-spares.ts +++ b/apps/server/src/battle/battle-spares.ts @@ -16,12 +16,19 @@ export interface BackupSpawn { readonly backup: string; } +/** Strip native model folder prefixes (e.g. "tankModels/cn_type_59" -> "cn_type_59"). */ +export function normalizeBackupUnitName(unit: string): string { + const slash = unit.lastIndexOf('/'); + return slash >= 0 ? unit.slice(slash + 1) : unit; +} + function receiptKey(session: BattleSession, slot: number): string { return `${session.sessionId}_${slot}`; } export function recordDailyBackupSpawn(profile: BlkBlock, session: BattleSession, spawn: BackupSpawn): boolean { - return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === spawn.unit + const unit = normalizeBackupUnitName(spawn.unit); + return spawn.backup === DAILY_BACKUP && session.spareSlots?.get(spawn.slot) === unit && recordDailySpare(profile, session.startedAtSec, receiptKey(session, spawn.slot)); } @@ -32,11 +39,12 @@ export function consumeBattleSpares( const seenSlots = new Set(); const consumed = new Map(); for (const spawn of spawns) { - const { slot, unit, backup } = spawn; + const { slot, backup } = spawn; + const unit = normalizeBackupUnitName(spawn.unit); if (session.spareSlots?.get(slot) !== unit || seenSlots.has(slot)) continue; seenSlots.add(slot); if (backup === DAILY_BACKUP) { - recordDailyBackupSpawn(profile, session, spawn); + recordDailyBackupSpawn(profile, session, { slot, unit, backup }); continue; } if (dailySparesLeft(profile, session.startedAtSec) > 0 diff --git a/apps/server/src/char/actions/battle-actions.ts b/apps/server/src/char/actions/battle-actions.ts index c99ab72..0be7ecb 100644 --- a/apps/server/src/char/actions/battle-actions.ts +++ b/apps/server/src/char/actions/battle-actions.ts @@ -13,6 +13,7 @@ import type { BattleEconomy } from '../../battle/battle-economy.ts'; import type { BattleStreaks } from '../../battle/battle-streaks.ts'; import { withoutSupportPlanes } from '../../battle/battle-support-planes.ts'; import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts'; +import type { ClanStore } from '../../clans/clan-store.ts'; import type { ItemCatalogue } from '../../items/item-catalogue.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import { clientProfile } from '../../profile/client-profile.ts'; @@ -41,6 +42,7 @@ export interface FinishBattleContext { readonly crew: CrewSkillCatalogue; readonly items: ItemCatalogue; readonly repair: RepairRules; + readonly clans?: { readonly store: ClanStore } | undefined; } export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler { @@ -67,7 +69,15 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio // The result log and expenses are written together. A retry can arrive after the profile // was saved but before the session was marked settled. if (hasBattleResultLog(profile, session.roomId)) return false; - settleBattle(profile, report, session, settlementDeps); + settleBattle(profile, report, session, { + ...settlementDeps, + onBattleRpEarned: ctx.clans + ? (baseVehicleRp, nowSec) => { + ctx.clans!.store.recordBattleActivity(account.userId, baseVehicleRp, nowSec); + ctx.clans!.store.syncProfile(profile, account, nowSec); + } + : undefined, + }); battle.onAfterSettle?.({ userId: account.userId, roomId: session.sessionId, diff --git a/apps/server/src/char/actions/client-update-actions.ts b/apps/server/src/char/actions/client-update-actions.ts index cb818f4..ed7316d 100644 --- a/apps/server/src/char/actions/client-update-actions.ts +++ b/apps/server/src/char/actions/client-update-actions.ts @@ -2,7 +2,9 @@ * `cln_update` (aces.exe 2.61.0.37 0x29f3ee, job type 3 -> `onUpdateProfile`): * triggered by `save_online_single_job` when the client marks seen user logs as disabled * (`scripts/userLog/userlogUtils.nut` `disableSeenUserlogs`, tag 223) or updates hangar - * auto-repair / auto-refill / auto-buy-modifications and map preferences. On returning from + * auto-repair / auto-refill / auto-buy-modifications, map preferences, and per-vehicle + * preferences (`hangar/` `lastSkin`, `lastWeapon`, `lastBullets0..5`, and flight + * trims `aileronTrim`/`elevatorTrim`/`rudderTrim`). On returning from * a stock training mission, the client also reports completion in `missionAwards` while * `pveProgress` is empty. Answers the whole updated profile. */ diff --git a/apps/server/src/char/actions/store-actions.ts b/apps/server/src/char/actions/store-actions.ts index 1a2b2ba..59dc2bd 100644 --- a/apps/server/src/char/actions/store-actions.ts +++ b/apps/server/src/char/actions/store-actions.ts @@ -8,18 +8,24 @@ */ import { appendParam, emptyBlock, setParam, type BlkBlock } from '@wto/blk'; import type { AccountStore } from '../../accounts/account-store.ts'; +import type { LocalizedText } from '../../game-data/datasets/unit-names.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import { serverTimeNow } from '../../profile/server-time.ts'; import type { RuleOutcome } from '../../research/rule-outcome.ts'; import type { StoreCatalogue, StoreProduct } from '../../store/store-catalogue.ts'; import { buyGoldEntitlement } from '../../store/store-purchase.ts'; +import { freePaymentLabelForStore } from '../../store/store-tuning.ts'; import type { CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; import { headerOrPayloadInt, headerOrPayloadString } from './payload-params.ts'; -export function entitlementsPriceEx(store: StoreCatalogue): CharActionHandler { - const table = buildEntitlementsPriceBlk(store.allProducts()); +export function entitlementsPriceEx( + store: StoreCatalogue, + freePaymentLabel?: LocalizedText, +): CharActionHandler { + const label = freePaymentLabel ?? freePaymentLabelForStore(store); + const table = buildEntitlementsPriceBlk(store.allProducts(), label); return () => ({ kind: 'data', blk: table }); } @@ -42,8 +48,15 @@ export function buyEntitlementAction(profiles: PlayerProfiles, accounts: Account }); } -function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock { +function buildEntitlementsPriceBlk( + products: readonly StoreProduct[], + freePaymentLabel: LocalizedText, +): BlkBlock { const root = emptyBlock(); + // Top-level string params are ignored by stock blockCount() enumeration and read by the + // free-offline-payment-method GUI patch to localize the no-GJN payment option. + setParam(root, 'wtoFreePaymentLabelZh', { type: 'string', value: freePaymentLabel.zh }); + setParam(root, 'wtoFreePaymentLabelEn', { type: 'string', value: freePaymentLabel.en }); for (const product of products) { const block = emptyBlock(product.id); setParam(block, 'chapter', { type: 'string', value: product.chapter }); diff --git a/apps/server/src/clans/clan-blk.ts b/apps/server/src/clans/clan-blk.ts index aa78a01..c79e100 100644 --- a/apps/server/src/clans/clan-blk.ts +++ b/apps/server/src/clans/clan-blk.ts @@ -31,6 +31,14 @@ const OPTIONAL_LOG_STRING_KEYS: ReadonlyArray todayDay ? candidateNextDay : todayDay + rewardPeriodDays; + const nextRewardSec = nextRewardDay * 86400; return { name: '', params: [ @@ -57,7 +65,7 @@ export function toClanInfoBlk(clan: ClanRecord, tuning: ClanTuning, nowSec = Mat int('rewardPeriodDays', rewardPeriodDays), bool('expRewardEnabled', true), int('historyDepth', historyDepthDays), - int('nextRewardDayId', todayDay + rewardPeriodDays), + int64('nextRewardDayId', BigInt(nextRewardSec)), ], blocks: [ buildAstatBlock(clan, tuning), @@ -215,7 +223,7 @@ function statParams(stats: ClanStats): BlkParam[] { function buildMemberActivityBlock(member: ClanMemberRecord, todayDay: number): BlkBlock { const periods = member.periods.length > 0 ? member.periods - : [{ day: todayDay, activity: member.curActivity, exp: 20000 }]; + : (member.curActivity > 0 ? [{ day: todayDay, activity: member.curActivity, exp: 0 }] : []); return { name: member.uid, @@ -248,6 +256,10 @@ function int(name: string, value: number): BlkParam { return { name, value: { type: 'int', value: Math.trunc(value) } }; } +function int64(name: string, value: bigint): BlkParam { + return { name, value: { type: 'int64', value } }; +} + function bool(name: string, value: boolean): BlkParam { return { name, value: { type: 'bool', value } }; } diff --git a/apps/server/src/clans/clan-membership.ts b/apps/server/src/clans/clan-membership.ts index 0abd231..287cdc6 100644 --- a/apps/server/src/clans/clan-membership.ts +++ b/apps/server/src/clans/clan-membership.ts @@ -54,13 +54,15 @@ export function addMemberToClan( ): void { if (clan.members.some((m) => m.uid === uid)) return; const periods = buildDefaultPeriods(Math.floor(nowSec / 86400), tuning); + const curActivity = Math.min(tuning.activity.maxPerPeriod, tuning.activity.startingActivity); + const periodActivitySum = periods.reduce((s, p) => s + p.activity, 0); clan.members.push({ uid, nick, role, joinDateSec: nowSec, - curActivity: tuning.activity.maxPerPeriod, - totalActivity: periods.reduce((s, p) => s + p.activity, 0), + curActivity, + totalActivity: periods.length > 0 ? periodActivitySum : curActivity, earnedSquadronExp: periods.reduce((s, p) => s + p.exp, 0), ratingArc: tuning.playerRating.joiner.arc, ratingHist: tuning.playerRating.joiner.hist, diff --git a/apps/server/src/clans/clan-season.ts b/apps/server/src/clans/clan-season.ts new file mode 100644 index 0000000..113079b --- /dev/null +++ b/apps/server/src/clans/clan-season.ts @@ -0,0 +1,75 @@ +/** + * Squadron (clan) battle season schedule matching `char.vromfs.bin` `config/clan_rewards.blk` + * (`seasons{}`): six bi-monthly UTC seasons per year starting on the 1st of Jan, Mar, May, + * Jul, Sep, and Nov at 00:00:00 UTC. + * + * Wire contract verified in stock `aces.exe` (2.61.0.58): + * - `GameSaveData::onAsyncEconTransComplete` (`0xebc33c..0xebc7b4`) reads four top-level + * profile parameters on every profile-returning char transaction: + * - `clanDuelNextReward:i64` (`0xebc731..0xebc745`, `DataBlock::getInt64`) -> `rewardDay` + * - `clanSeasonStart:i64` (`0xebc755..0xebc769`, `DataBlock::getInt64`) -> `startDay` + * - `clanSeasonOrdinal:i` (`0xebc778..0xebc78c`, `DataBlock::getInt`) -> `ordinalNumber` + * - `clanSeasonInYear:i` (`0xebc79a..0xebc7ae`, `DataBlock::getInt`) -> `numberInYear` + * - `clan_get_current_season_info` (`0x178aff0..0x178b227`) exposes those four fields verbatim. + * - `gui.vromfs.bin` `scripts/clans/clanseasons.nut:45-54` formats the title using + * `unixtime_to_utc_timetbl(info.startDay).year` and `info.numberInYear + 1` + * (`CLAN_SEASON_NUM_IN_YEAR_SHIFT = 1`, yielding Roman numerals `I`..`VI`), and formats the + * end time with `time.buildDateTimeStr(info.rewardDay, false, false)`. + */ + +export interface ClanSeasonInfo { + /** UTC 00:00:00 start of the active season as Unix seconds. */ + readonly startDaySec: number; + /** UTC 00:00:00 end/reward timestamp of the active season (start of next season) as Unix seconds. */ + readonly rewardDaySec: number; + /** Zero-based season index within the UTC year (`0..5`, displayed as `I..VI`). */ + readonly numberInYear: number; + /** Monotonic positive ordinal season number across years. */ + readonly ordinalNumber: number; +} + +/** Season start month/day pairs from `char.vromfs.bin` `config/clan_rewards.blk` `seasons{}`. */ +export const CLAN_SEASON_STARTS: ReadonlyArray<{ readonly month: number; readonly day: number }> = [ + { month: 1, day: 1 }, + { month: 3, day: 1 }, + { month: 5, day: 1 }, + { month: 7, day: 1 }, + { month: 9, day: 1 }, + { month: 11, day: 1 }, +]; + +const SEASON_ORDINAL_BASE_YEAR = 2016; + +/** Compute the active squadron battle season for a given Unix timestamp in seconds. */ +export function currentClanSeason(nowSec = Math.floor(Date.now() / 1000)): ClanSeasonInfo { + const now = new Date(Math.trunc(nowSec) * 1000); + const year = now.getUTCFullYear(); + const seasonCount = CLAN_SEASON_STARTS.length; + + let activeIndex = 0; + let startSec = Date.UTC(year, CLAN_SEASON_STARTS[0]!.month - 1, CLAN_SEASON_STARTS[0]!.day) / 1000; + + for (let i = seasonCount - 1; i >= 0; i--) { + const entry = CLAN_SEASON_STARTS[i]!; + const candidateSec = Date.UTC(year, entry.month - 1, entry.day) / 1000; + if (nowSec >= candidateSec) { + activeIndex = i; + startSec = candidateSec; + break; + } + } + + const nextIndex = (activeIndex + 1) % seasonCount; + const nextYear = activeIndex + 1 >= seasonCount ? year + 1 : year; + const nextEntry = CLAN_SEASON_STARTS[nextIndex]!; + const rewardSec = Date.UTC(nextYear, nextEntry.month - 1, nextEntry.day) / 1000; + + const ordinalNumber = Math.max(1, (year - SEASON_ORDINAL_BASE_YEAR) * seasonCount + activeIndex + 1); + + return { + startDaySec: startSec, + rewardDaySec: rewardSec, + numberInYear: activeIndex, + ordinalNumber, + }; +} diff --git a/apps/server/src/clans/clan-seeds.ts b/apps/server/src/clans/clan-seeds.ts index f37e4ae..72f0f1b 100644 --- a/apps/server/src/clans/clan-seeds.ts +++ b/apps/server/src/clans/clan-seeds.ts @@ -3,25 +3,75 @@ * The directory is written when the server first creates `/clans.json`. */ import type { ClanTuning, PresetClan, PresetMember } from './clan-tuning.ts'; -import type { ClanActivityPeriodEntry, ClanMemberRecord, ClanRecord } from './clan-types.ts'; +import { ClanRole, type ClanActivityPeriodEntry, type ClanMemberRecord, type ClanRecord } from './clan-types.ts'; const SECONDS_PER_DAY = 86400; export function createDefaultClans(tuning: ClanTuning, nowSec = Math.floor(Date.now() / 1000)): ClanRecord[] { const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); const createdBase = nowSec - tuning.presetClans.createdDaysAgo * SECONDS_PER_DAY; - return tuning.presetClans.clans.map((spec) => buildSeededClan(spec, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning)); + return tuning.presetClans.clans.map((spec, specIndex) => + buildSeededClan(spec, specIndex, createdBase + spec.createdAfterDays * SECONDS_PER_DAY, todayDay, tuning)); } -/** The activity periods a member starts with: startingPeriods periods, each with the given activity and the squadron RP it earns. */ -export function buildDefaultPeriods(todayDay: number, tuning: ClanTuning, periodActivity = tuning.activity.maxPerPeriod): ClanActivityPeriodEntry[] { - const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays, startingPeriods } = tuning.activity; +/** + * The activity periods a member starts with: `periodCount` periods (defaulting to + * `activity.startingPeriods`), each with the given activity and the squadron RP it earns. + */ +export function buildDefaultPeriods( + todayDay: number, + tuning: ClanTuning, + periodActivity = tuning.activity.maxPerPeriod, + periodCount = tuning.activity.startingPeriods, +): ClanActivityPeriodEntry[] { + if (periodCount <= 0) return []; + const { maxPerPeriod, squadronRpPerFullPeriod, rewardPeriodDays } = tuning.activity; const exp = Math.round((periodActivity / maxPerPeriod) * squadronRpPerFullPeriod); - return Array.from({ length: startingPeriods }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); + return Array.from({ length: periodCount }, (_, idx) => ({ day: todayDay - idx * rewardPeriodDays, activity: periodActivity, exp })); } -function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanRecord { - const members = spec.members.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning)); +/** + * Idempotently appends deterministic filler NPCs to an existing preset clan whose + * persisted roster is smaller than its configured `targetMemberCount`, without altering + * any existing player or NPC members. + */ +export function backfillPresetClanMembers( + clan: ClanRecord, + spec: PresetClan, + specIndex: number, + todayDay: number, + tuning: ClanTuning, +): boolean { + const targetCount = Math.min(clan.mlimit, spec.targetMemberCount); + if (clan.members.length >= targetCount) return false; + + const existingUids = new Set(clan.members.map((m) => m.uid)); + const fillerSpecs = buildPresetFillerSpecs(spec, specIndex, tuning); + let added = false; + for (let i = 0; i < fillerSpecs.length && clan.members.length < targetCount; i++) { + const npc = fillerSpecs[i]!; + if (existingUids.has(npc.uid)) continue; + existingUids.add(npc.uid); + const memberIdx = spec.members.length + i; + clan.members.push(buildSeededMember(spec, npc, memberIdx, clan.cdateSec, todayDay, tuning)); + added = true; + } + return added; +} + +function buildSeededClan( + spec: PresetClan, + specIndex: number, + cdateSec: number, + todayDay: number, + tuning: ClanTuning, +): ClanRecord { + const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal; + const allSpecs: PresetMember[] = [ + ...spec.members, + ...buildPresetFillerSpecs(spec, specIndex, tuning), + ].slice(0, mlimit); + const members = allSpecs.map((npc, idx) => buildSeededMember(spec, npc, idx, cdateSec, todayDay, tuning)); const leader = spec.members[0]!; return { id: spec.id, @@ -35,13 +85,14 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t region: spec.region, status: 'open', autoaccept: spec.autoAccept, - mlimit: spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal, + mlimit, mspent: 0, cdateSec, changedByUid: leader.uid, changedByNick: leader.nick, changedTimeSec: cdateSec, regionLastUpdatedSec: 0, + lastRewardDay: todayDay, stats: { dr_era5_arc: spec.rating.arc, dr_era5_hist: spec.rating.hist, dr_era5_sim: spec.rating.sim, ...tuning.presetClans.stats }, members, candidates: [], @@ -55,8 +106,64 @@ function buildSeededClan(spec: PresetClan, cdateSec: number, todayDay: number, t }; } -function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cdateSec: number, todayDay: number, tuning: ClanTuning): ClanMemberRecord { - const periods = buildDefaultPeriods(todayDay, tuning, npc.activity); +function buildPresetFillerSpecs(spec: PresetClan, specIndex: number, tuning: ClanTuning): PresetMember[] { + const mlimit = spec.type === 'battalion' ? tuning.memberLimits.battalionInitial : tuning.memberLimits.normal; + const targetCount = Math.min(mlimit, Math.max(spec.members.length, spec.targetMemberCount)); + const needed = targetCount - spec.members.length; + if (needed <= 0) return []; + + const filler = tuning.presetClans.fillerMembers; + const clanSlot = presetClanSlot(spec.id, specIndex); + const usedUids = new Set(spec.members.map((m) => m.uid)); + const span = Math.max(0, filler.activityMax - filler.activityMin); + const result: PresetMember[] = []; + + let ordinal = spec.members.length + 1; + while (result.length < needed) { + const uid = String(filler.uidBase + clanSlot * filler.uidStride + ordinal); + if (usedUids.has(uid)) { + ordinal++; + continue; + } + usedUids.add(uid); + const callsign = filler.callsigns[(clanSlot * 7 + ordinal) % filler.callsigns.length]!; + const title = filler.titles[(clanSlot * 3 + ordinal) % filler.titles.length]!; + const icon = filler.icons[(clanSlot * 5 + ordinal) % filler.icons.length]!; + const unit = filler.units[(clanSlot * 11 + ordinal) % filler.units.length]!; + const activityOffset = span > 0 ? (clanSlot * 13 + ordinal * 17) % (span + 1) : 0; + const activity = Math.min(tuning.activity.maxPerPeriod, filler.activityMin + activityOffset); + result.push({ + uid, + nick: `${callsign}_${clanSlot}${String(ordinal).padStart(2, '0')}`, + role: ClanRole.REGULAR, + title, + icon, + unit, + activity, + }); + ordinal++; + } + return result; +} + +function presetClanSlot(clanId: string, specIndex: number): number { + const parsed = Number(clanId); + if (Number.isSafeInteger(parsed) && parsed > 0) { + const remainder = parsed % 1000; + if (remainder > 0) return remainder; + } + return specIndex + 1; +} + +function buildSeededMember( + spec: PresetClan, + npc: PresetMember, + idx: number, + cdateSec: number, + todayDay: number, + tuning: ClanTuning, +): ClanMemberRecord { + const periods = buildDefaultPeriods(todayDay, tuning, npc.activity, tuning.presetClans.npcHistoryPeriods); const { step, floor } = tuning.presetClans.memberRating; return { uid: npc.uid, @@ -69,7 +176,7 @@ function buildSeededMember(spec: PresetClan, npc: PresetMember, idx: number, cda npcFrame: '', npcShowcaseUnit: npc.unit, curActivity: npc.activity, - totalActivity: periods.reduce((sum, p) => sum + p.activity, 0), + totalActivity: periods.length > 0 ? periods.reduce((sum, p) => sum + p.activity, 0) : npc.activity, earnedSquadronExp: periods.reduce((sum, p) => sum + p.exp, 0), ratingArc: Math.max(floor.arc, spec.rating.arc - idx * step.arc), ratingHist: Math.max(floor.hist, spec.rating.hist - idx * step.hist), diff --git a/apps/server/src/clans/clan-store.ts b/apps/server/src/clans/clan-store.ts index 032b26a..5104585 100644 --- a/apps/server/src/clans/clan-store.ts +++ b/apps/server/src/clans/clan-store.ts @@ -39,10 +39,12 @@ import { type MembershipRequestQuery, } from './clan-membership.ts'; import { findClanInList, queryClanLeaderboard, type LeaderboardQuery } from './clan-queries.ts'; -import { createDefaultClans } from './clan-seeds.ts'; +import { backfillPresetClanMembers, createDefaultClans } from './clan-seeds.ts'; import type { ClanTuning } from './clan-tuning.ts'; import type { ClanBestReward, ClanMemberRecord, ClanRecord } from './clan-types.ts'; +const SECONDS_PER_DAY = 86400; + export type { LeaderboardQuery }; export class ClanStore { @@ -51,18 +53,36 @@ export class ClanStore { readonly tuning: ClanTuning; #state: StoredClansState; - constructor(dataFolder: string, tuning: ClanTuning) { + constructor(dataFolder: string, tuning: ClanTuning, nowSec = nowSeconds()) { this.#filePath = join(dataFolder, 'clans.json'); this.tuning = tuning; - this.#state = this.#loadOrSeed(); + this.#state = this.#loadOrSeed(nowSec); } - #loadOrSeed(): StoredClansState { + #loadOrSeed(nowSec: number): StoredClansState { + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); if (existsSync(this.#filePath)) { const parsed = JSON.parse(readFileSync(this.#filePath, 'utf8')) as StoredClansState; - if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') return parsed; + if (Array.isArray(parsed.clans) && typeof parsed.nextClanId === 'number') { + let mutated = false; + for (let i = 0; i < this.tuning.presetClans.clans.length; i++) { + const spec = this.tuning.presetClans.clans[i]!; + const existing = parsed.clans.find((c) => c.id === spec.id); + if (existing && backfillPresetClanMembers(existing, spec, i, todayDay, this.tuning)) { + mutated = true; + } + } + for (const clan of parsed.clans) { + if (clan.lastRewardDay === undefined) { + clan.lastRewardDay = todayDay; + mutated = true; + } + } + if (mutated) this.#save(parsed); + return parsed; + } } - const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning) }; + const seeded: StoredClansState = { nextClanId: this.tuning.firstNewClanId, clans: createDefaultClans(this.tuning, nowSec) }; this.#save(seeded); return seeded; } @@ -71,19 +91,7 @@ export class ClanStore { writeFileAtomic(this.#filePath, JSON.stringify(state, null, 2)); } - #resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { - return clanId && clanId !== '-1' ? this.byId(clanId) : this.clanOfUser(userId)?.clan; - } - - byId(clanId: string): ClanRecord | undefined { - return this.#state.clans.find((c) => c.id === clanId); - } - - findClan(query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }): ClanRecord | undefined { - return findClanInList(this.#state.clans, query); - } - - clanOfUser(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + #findUserClan(userId: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { for (const clan of this.#state.clans) { const member = clan.members.find((m) => m.uid === userId); if (member) return { clan, member }; @@ -91,12 +99,147 @@ export class ClanStore { return undefined; } + #resolveClan(clanId: string | undefined, userId: string): ClanRecord | undefined { + return clanId && clanId !== '-1' + ? this.#state.clans.find((c) => c.id === clanId) + : this.#findUserClan(userId)?.clan; + } + + /** + * Lazily settles expired activity reward periods for all squadrons using the stock + * client formula (`clanAverageActivityModal.nut:44-54`): + * `myExp = min(min(1, myPercent / clanPercent) * clanActivity, maxClanActivity)` + * Player members' current-period activity resets to 0 for the new period while NPC + * members keep their active roster contribution. + */ + settleExpiredPeriods(nowSec = nowSeconds()): boolean { + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); + const { + maxPerPeriod, + squadronRpPerFullPeriod: maxClanActivity, + rewardPeriodDays, + historyDepthDays, + } = this.tuning.activity; + + let mutated = false; + for (const clan of this.#state.clans) { + if (clan.lastRewardDay === undefined) { + clan.lastRewardDay = todayDay; + mutated = true; + continue; + } + const elapsedDays = todayDay - clan.lastRewardDay; + if (elapsedDays < rewardPeriodDays) continue; + + const anchorDay = clan.lastRewardDay; + const periodsPassed = Math.floor(elapsedDays / rewardPeriodDays); + const settlementDay = anchorDay + rewardPeriodDays; + const nextAnchorDay = anchorDay + periodsPassed * rewardPeriodDays; + const clanActivity = clan.members.reduce((sum, m) => sum + Math.max(0, m.curActivity), 0); + const maxActivity = maxPerPeriod * clan.members.length; + const clanPercent = maxActivity > 0 ? clanActivity / maxActivity : 0; + const minKeptDay = settlementDay - historyDepthDays; + + clan.members = clan.members.map((member) => { + const myActivity = Math.max(0, member.curActivity); + const myPercent = maxPerPeriod > 0 ? myActivity / maxPerPeriod : 0; + const myExp = (myPercent > 0 && clanPercent > 0) + ? Math.min(maxClanActivity, Math.round(Math.min(1, myPercent / clanPercent) * clanActivity)) + : 0; + const pastSettled = member.periods.filter((p) => !(p.exp === 0 && p.day >= anchorDay && p.day <= settlementDay)); + const settledEntry = (myActivity > 0 || myExp > 0) + ? [{ day: settlementDay, activity: myActivity, exp: myExp }] + : []; + const nextPeriods = [...settledEntry, ...pastSettled].filter((p) => p.day >= minKeptDay); + if (member.isNpc) { + return { + ...member, + totalActivity: member.totalActivity + myActivity, + earnedSquadronExp: member.earnedSquadronExp + myExp, + periods: nextPeriods, + }; + } + return { + ...member, + curActivity: 0, + earnedSquadronExp: member.earnedSquadronExp + myExp, + periods: nextPeriods, + }; + }); + + clan.lastRewardDay = nextAnchorDay; + mutated = true; + } + + if (mutated) this.#save(); + return mutated; + } + + /** + * Accumulates current-period squadron activity from battle base vehicle RP + * (`floor(baseVehicleRp / rpPerActivityPoint)`, capped at `maxPerPeriod`). + * Returns the activity points actually added. + */ + recordBattleActivity(userId: string, baseVehicleRp: number, nowSec = nowSeconds()): number { + this.settleExpiredPeriods(nowSec); + if (!Number.isFinite(baseVehicleRp) || baseVehicleRp <= 0) return 0; + const found = this.#findUserClan(userId); + if (!found) return 0; + + const { maxPerPeriod, rpPerActivityPoint } = this.tuning.activity; + const rawGain = Math.floor(baseVehicleRp / rpPerActivityPoint); + if (rawGain <= 0) return 0; + + const { clan, member } = found; + const remaining = Math.max(0, maxPerPeriod - member.curActivity); + const added = Math.min(rawGain, remaining); + if (added <= 0) return 0; + + const todayDay = Math.floor(nowSec / SECONDS_PER_DAY); + const periodStartDay = clan.lastRewardDay ?? todayDay; + const nextCurActivity = member.curActivity + added; + const nextTotalActivity = member.totalActivity + added; + const existingInProgressIdx = member.periods.findIndex((p) => p.exp === 0 && p.day >= periodStartDay); + const nextPeriods = existingInProgressIdx >= 0 + ? member.periods.map((p, idx) => (idx === existingInProgressIdx ? { day: todayDay, activity: nextCurActivity, exp: 0 } : p)) + : [{ day: todayDay, activity: nextCurActivity, exp: 0 }, ...member.periods]; + + const memberIdx = clan.members.findIndex((m) => m.uid === userId); + if (memberIdx < 0) return 0; + clan.members[memberIdx] = { + ...member, + curActivity: nextCurActivity, + totalActivity: nextTotalActivity, + periods: nextPeriods, + }; + this.#save(); + return added; + } + + byId(clanId: string, nowSec = nowSeconds()): ClanRecord | undefined { + this.settleExpiredPeriods(nowSec); + return this.#state.clans.find((c) => c.id === clanId); + } + + findClan( + query: { readonly clanId?: string | undefined; readonly clanName?: string | undefined; readonly clanTag?: string | undefined }, + nowSec = nowSeconds(), + ): ClanRecord | undefined { + this.settleExpiredPeriods(nowSec); + return findClanInList(this.#state.clans, query); + } + + clanOfUser(userId: string, nowSec = nowSeconds()): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { + this.settleExpiredPeriods(nowSec); + return this.#findUserClan(userId); + } + pendingRequestOfUser(userId: string): ClanRecord | undefined { return this.#state.clans.find((c) => c.candidates.some((cand) => cand.uid === userId)); } - earnedSquadronExpOf(userId: string): number { - return this.clanOfUser(userId)?.member.earnedSquadronExp ?? 0; + earnedSquadronExpOf(userId: string, nowSec = nowSeconds()): number { + return this.clanOfUser(userId, nowSec)?.member.earnedSquadronExp ?? 0; } npcMemberByUid(uid: string): { readonly clan: ClanRecord; readonly member: ClanMemberRecord } | undefined { @@ -107,8 +250,8 @@ export class ClanStore { return undefined; } - syncProfile(profile: BlkBlock, account: Account): void { - const found = this.clanOfUser(account.userId); + syncProfile(profile: BlkBlock, account: Account, nowSec = nowSeconds()): void { + const found = this.clanOfUser(account.userId, nowSec); if (found) { const { clan, member } = found; if (member.nick !== account.nick) { @@ -131,15 +274,31 @@ export class ClanStore { } } - queryLeaderboard(query: LeaderboardQuery): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { + queryLeaderboard(query: LeaderboardQuery, nowSec = nowSeconds()): ReadonlyArray<{ readonly clan: ClanRecord; readonly pos: number }> { + this.settleExpiredPeriods(nowSec); return queryClanLeaderboard(this.#state.clans, query, this.tuning); } createClan(profile: BlkBlock, account: Account, economy: ClanEconomy, input: CreateClanInput, nowSec = nowSeconds()): RuleOutcome { + this.settleExpiredPeriods(nowSec); const outcome = createClanInState(this.#state, profile, account, economy, this.tuning, input, nowSec); if (outcome.ok) { + const created = this.#state.clans[0]; + if (created) { + created.lastRewardDay = Math.floor(nowSec / SECONDS_PER_DAY); + const founder = created.members[0]; + if (founder && founder.uid === account.userId) { + const curActivity = Math.min(this.tuning.activity.maxPerPeriod, this.tuning.activity.startingActivity); + const periodActivitySum = founder.periods.reduce((s, p) => s + p.activity, 0); + created.members[0] = { + ...founder, + curActivity, + totalActivity: founder.periods.length > 0 ? periodActivitySum : curActivity, + }; + } + } this.#save(); - this.syncProfile(profile, account); + this.syncProfile(profile, account, nowSec); } return outcome; } @@ -189,10 +348,11 @@ export class ClanStore { } requestOrCancelMembership(profile: BlkBlock, account: Account, query: MembershipRequestQuery, nowSec = nowSeconds()): RuleOutcome { - const res = requestOrCancelMembershipInState(this.#state.clans, this.findClan(query), Boolean(this.clanOfUser(account.userId)), account, query, nowSec, this.tuning); + this.settleExpiredPeriods(nowSec); + const res = requestOrCancelMembershipInState(this.#state.clans, findClanInList(this.#state.clans, query), Boolean(this.#findUserClan(account.userId)), account, query, nowSec, this.tuning); if (res.mutated) { this.#save(); - this.syncProfile(profile, account); + this.syncProfile(profile, account, nowSec); } return res.outcome; } diff --git a/apps/server/src/clans/clan-tuning.ts b/apps/server/src/clans/clan-tuning.ts index 8a2e063..cd7b521 100644 --- a/apps/server/src/clans/clan-tuning.ts +++ b/apps/server/src/clans/clan-tuning.ts @@ -26,6 +26,17 @@ export interface PresetMember { readonly activity: number; } +export interface PresetFillerMembers { + readonly activityMin: number; + readonly activityMax: number; + readonly uidBase: number; + readonly uidStride: number; + readonly callsigns: readonly string[]; + readonly titles: readonly string[]; + readonly icons: readonly string[]; + readonly units: readonly string[]; +} + export interface PresetClan { readonly id: string; readonly tag: string; @@ -37,6 +48,7 @@ export interface PresetClan { readonly region: string; readonly autoAccept: boolean; readonly createdAfterDays: number; + readonly targetMemberCount: number; readonly rating: ModeTriple; readonly members: readonly PresetMember[]; } @@ -47,6 +59,8 @@ export interface ClanTuning { readonly squadronRpPerFullPeriod: number; readonly rewardPeriodDays: number; readonly historyDepthDays: number; + readonly rpPerActivityPoint: number; + readonly startingActivity: number; readonly startingPeriods: number; }; readonly memberLimits: { readonly normal: number; readonly battalionInitial: number }; @@ -56,6 +70,8 @@ export interface ClanTuning { readonly presetClans: { readonly createdDaysAgo: number; readonly memberJoinSpacingMinutes: number; + readonly npcHistoryPeriods: number; + readonly fillerMembers: PresetFillerMembers; readonly stats: PresetClanStats; readonly memberRating: { readonly step: ModeTriple; readonly floor: ModeTriple }; readonly clans: readonly PresetClan[]; @@ -64,6 +80,7 @@ export interface ClanTuning { export function readClanTuning(file: TuningReader): ClanTuning { const activity = file.object('activity'); + const maxPerPeriod = activity.int('maxPerPeriod', { min: 1 }); const limits = file.object('memberLimits'); const leaderboard = file.object('leaderboard'); const preset = file.object('presetClans'); @@ -71,10 +88,12 @@ export function readClanTuning(file: TuningReader): ClanTuning { const rating = preset.object('memberRating'); return { activity: { - maxPerPeriod: activity.int('maxPerPeriod', { min: 1 }), + maxPerPeriod, squadronRpPerFullPeriod: activity.int('squadronRpPerFullPeriod', { min: 0 }), rewardPeriodDays: activity.int('rewardPeriodDays', { min: 1 }), historyDepthDays: activity.int('historyDepthDays', { min: 1 }), + rpPerActivityPoint: activity.int('rpPerActivityPoint', { min: 1 }), + startingActivity: activity.int('startingActivity', { min: 0, max: maxPerPeriod }), startingPeriods: activity.int('startingPeriods', { min: 0 }), }, memberLimits: { normal: limits.int('normal', { min: 1 }), battalionInitial: limits.int('battalionInitial', { min: 1 }) }, @@ -84,6 +103,8 @@ export function readClanTuning(file: TuningReader): ClanTuning { presetClans: { createdDaysAgo: preset.int('createdDaysAgo', { min: 0 }), memberJoinSpacingMinutes: preset.int('memberJoinSpacingMinutes', { min: 0 }), + npcHistoryPeriods: preset.int('npcHistoryPeriods', { min: 0 }), + fillerMembers: readFillerMembers(preset.object('fillerMembers'), maxPerPeriod), stats: Object.fromEntries(STAT_KEYS.map((key) => [key, stats.int(key, { min: 0 })])) as unknown as PresetClanStats, memberRating: { step: triple(rating.object('step')), floor: triple(rating.object('floor')) }, clans: preset.list('clans', readPresetClan), @@ -91,11 +112,34 @@ export function readClanTuning(file: TuningReader): ClanTuning { }; } +function readFillerMembers(entry: TuningReader, maxPerPeriod: number): PresetFillerMembers { + const activityMin = entry.int('activityMin', { min: 0, max: maxPerPeriod }); + const activityMax = entry.int('activityMax', { min: activityMin, max: maxPerPeriod }); + const callsigns = entry.stringList('callsigns'); + const titles = entry.stringList('titles'); + const icons = entry.stringList('icons'); + const units = entry.stringList('units'); + if (callsigns.length === 0 || titles.length === 0 || icons.length === 0 || units.length === 0) { + throw new TuningError('tuning file clans.jsonc: presetClans.fillerMembers callsigns, titles, icons, and units must be non-empty'); + } + return { + activityMin, + activityMax, + uidBase: entry.int('uidBase', { min: 1 }), + uidStride: entry.int('uidStride', { min: 1 }), + callsigns, + titles, + icons, + units, + }; +} + function readPresetClan(entry: TuningReader): PresetClan { const type = entry.string('type'); if (type !== 'normal' && type !== 'battalion') throw new TuningError(`tuning file clans.jsonc: clan type must be normal or battalion (found "${type}")`); const members = entry.list('members', readPresetMember); if (members.length === 0) throw new TuningError(`tuning file clans.jsonc: preset clan ${entry.string('id')} needs at least one member (the first is its leader)`); + const rawTarget = entry.has('targetMemberCount') ? entry.int('targetMemberCount', { min: 1 }) : members.length; return { id: entry.string('id'), tag: entry.string('tag'), @@ -107,6 +151,7 @@ function readPresetClan(entry: TuningReader): PresetClan { region: entry.string('region'), autoAccept: entry.bool('autoAccept'), createdAfterDays: entry.int('createdAfterDays', { min: 0 }), + targetMemberCount: Math.max(members.length, rawTarget), rating: triple(entry.object('rating')), members, }; diff --git a/apps/server/src/clans/clan-types.ts b/apps/server/src/clans/clan-types.ts index c07ad84..9024419 100644 --- a/apps/server/src/clans/clan-types.ts +++ b/apps/server/src/clans/clan-types.ts @@ -171,6 +171,8 @@ export interface ClanRecord { changedByNick: string; changedTimeSec: number; regionLastUpdatedSec: number; + /** UTC day index (floor(unixSec / 86400)) when the current activity reward period started. */ + lastRewardDay?: number; stats: ClanStats; members: ClanMemberRecord[]; candidates: ClanCandidateRecord[]; diff --git a/apps/server/src/inventory/marketplace-service.ts b/apps/server/src/inventory/marketplace-service.ts index 4ce1904..92cb5be 100644 --- a/apps/server/src/inventory/marketplace-service.ts +++ b/apps/server/src/inventory/marketplace-service.ts @@ -4,8 +4,10 @@ * `extInventory` and pushing `mrpc.generic_notify` (`inventory.changed`) to active game clients. */ import { gjnText } from '../store/redeem-codes.ts'; +import { DEFAULT_FREE_PAYMENT_LABEL } from '../store/store-tuning.ts'; import type { BlkBlock } from '@wto/blk'; import type { AccountStore } from '../accounts/account-store.ts'; +import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts'; import { balanceOf } from '../profile/profile-currency.ts'; import { externalInventoryItems } from '../profile/profile-external-inventory.ts'; @@ -36,6 +38,7 @@ export class MarketplaceService implements Service { readonly #notifyInventoryChanged: () => void; readonly #maxPerPurchase: number; readonly #sellFeeRate: number; + readonly #freePaymentLabel: LocalizedText; constructor( accounts: AccountStore, @@ -43,6 +46,7 @@ export class MarketplaceService implements Service { catalogue: InventoryCatalogue, notifyInventoryChanged: () => void, tuning: Pick, + freePaymentLabel: LocalizedText = DEFAULT_FREE_PAYMENT_LABEL, ) { this.#accounts = accounts; this.#profiles = profiles; @@ -50,6 +54,7 @@ export class MarketplaceService implements Service { this.#notifyInventoryChanged = notifyInventoryChanged; this.#maxPerPurchase = tuning.maxPerPurchase; this.#sellFeeRate = tuning.sellFeeRate; + this.#freePaymentLabel = freePaymentLabel; } accepts(request: ServiceRequest): boolean { @@ -96,6 +101,7 @@ export class MarketplaceService implements Service { currentUserId: account?.userId ?? '', balance, sellFeeRate: this.#sellFeeRate, + freePaymentLabel: this.#freePaymentLabel, listings, }, `marketplace state (${account?.userId ?? 'no-account'})`); } @@ -158,7 +164,13 @@ export class MarketplaceService implements Service { }); if (errorReason === 'NOT_ENOUGH_GJN') { - return jsonResponse({ ok: false, message: { zh: 'GJN 不够。可直接点「老福爷付过了」,或在商店的"兑换码"页用 GJN 充值码补充。', en: 'Not enough GJN. Use "老福爷付过了" or a GJN code on the Redeem tab of the store.' } }, `marketplace buy ${itemdefId}: NOMONEY`); + return jsonResponse({ + ok: false, + message: { + zh: `GJN 不够。可直接点「${this.#freePaymentLabel.zh}」,或在商店的"兑换码"页用 GJN 充值码补充。`, + en: `Not enough GJN. Use "${this.#freePaymentLabel.en}" or a GJN code on the Redeem tab of the store.`, + }, + }, `marketplace buy ${itemdefId}: NOMONEY`); } if (errorReason) { return jsonResponse({ ok: false, message: { zh: '购买失败。', en: 'Purchase failed.' } }, `marketplace buy ${itemdefId}: ${errorReason}`); @@ -166,15 +178,23 @@ export class MarketplaceService implements Service { this.#notifyInventoryChanged(); const costSummary = isFree ? 'free' : `${gjnText(listing.gjnCostCents * quantity)} GJN`; - return jsonResponse({ ok: true, message: buySuccessMessage(listing, quantity, isFree) }, `marketplace buy ${itemdefId} x${quantity} (${costSummary})`); + return jsonResponse( + { ok: true, message: buySuccessMessage(listing, quantity, isFree, this.#freePaymentLabel) }, + `marketplace buy ${itemdefId} x${quantity} (${costSummary})`, + ); } } -function buySuccessMessage(listing: MarketplaceListing, quantity: number, isFree: boolean): { zh: string; en: string } { +function buySuccessMessage( + listing: MarketplaceListing, + quantity: number, + isFree: boolean, + freePaymentLabel: LocalizedText, +): LocalizedText { return isFree ? { - zh: `老福爷付过了!「${listing.title.zh}」兑换券 ×${quantity} 已放进游戏库存,可在机库的"道具 → 库存"里使用。`, - en: `Paid by 老福爷! ${quantity} × "${listing.title.en}" coupon is in your inventory (Items → Inventory in the hangar).`, + zh: `已通过「${freePaymentLabel.zh}」获得「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`, + en: `Claimed ${quantity} × "${listing.title.en}" coupon via "${freePaymentLabel.en}". It is in your inventory (Items → Inventory in the hangar).`, } : { zh: `已购买「${listing.title.zh}」兑换券 ×${quantity},已放进游戏库存,可在机库的"道具 → 库存"里使用。`, diff --git a/apps/server/src/inventory/web/app.js b/apps/server/src/inventory/web/app.js index b1e1b0d..c88eb9f 100644 --- a/apps/server/src/inventory/web/app.js +++ b/apps/server/src/inventory/web/app.js @@ -9,7 +9,7 @@ const T = { heldOnly: '只看我的库存', search: '搜索', sortPopular: '人气', sortName: '名称(从 A 到 Z)', sortPriceAsc: '价格(从低到高)', sortPriceDesc: '价格(从高到低)', catVehicle: '载具', catSkin: '涂装', catAttachable: '装饰挂件', catDecal: '贴花', catUnlock: '头像', allCountries: '全部国家', allClasses: '全部', rank: '{rank} 级', from: '从', held: '库存 ×{n}', owned: '已拥有', - buy: '购买', freeBuy: '老福爷付过了', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品', + buy: '购买', freeBuy: '直接获取', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品', buyPrice: '系统售价:{price} GJN', sellPrice: '卖给系统:{price} GJN(扣 {fee}% 手续费)', youHave: '你拥有:{n}', tradeUnconfirmed: '无法确认交易结果,请先查看余额和库存。', tagType: '物品类型', tagRarity: '稀有度', tagCountry: '国家', ticker: '离线交易所:按固定价格与系统交易,价格取自官方交易所快照。', @@ -19,7 +19,7 @@ const T = { heldOnly: 'Only my inventory', search: 'Search', sortPopular: 'Popular', sortName: 'Name (A to Z)', sortPriceAsc: 'Price (low to high)', sortPriceDesc: 'Price (high to low)', catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Avatars', allCountries: 'All countries', allClasses: 'All', rank: 'Rank {rank}', from: 'from', held: 'Owned ×{n}', owned: 'Owned', - buy: 'Buy', freeBuy: '老福爷付过了', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters', + buy: 'Buy', freeBuy: 'Direct Claim', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters', buyPrice: 'System price: {price} GJN', sellPrice: 'Sell to system: {price} GJN ({fee}% fee)', youHave: 'You own: {n}', tradeUnconfirmed: 'Could not confirm the trade. Check your balance and inventory.', tagType: 'Item type', tagRarity: 'Rarity', tagCountry: 'Country', ticker: 'Offline market: fixed-price trades with the system, prices from an official market snapshot.', @@ -33,7 +33,11 @@ const t = (key, params) => WtoUi.tr(T, key, params); const $ = (id) => document.getElementById(id); const wantedItem = WtoUi.query.get('n') || ''; -let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [] }; +let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, listings: [], freePaymentLabel: null }; + +function freePaymentLabel() { + return WtoUi.text(state.freePaymentLabel) || t('freeBuy'); +} const activeCats = new Set(); let openedWanted = false; let tradeNoticeId = 0; @@ -173,7 +177,7 @@ function fillOrderColumns(detail, listing) { sellCol.append(sellBtn, html('totals', t('sellPrice', { price: WtoUi.gjn(listing.sellCents), fee })), html('totals', t('youHave', { n: listing.couponCount || 0 }))); const buyBtn = Object.assign(document.createElement('button'), { className: 'big buy', textContent: noAccount ? t('pickAccount') : t('buy'), disabled: noAccount }); buyBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'gjn' }, listing); - const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: t('freeBuy'), disabled: noAccount }); + const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: freePaymentLabel(), disabled: noAccount }); freeBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'free' }, listing); buyCol.append(buyBtn, freeBtn, html('totals', t('buyPrice', { price: WtoUi.gjn(listing.gjnCostCents) }))); } diff --git a/apps/server/src/matching/battle-queue-requests.ts b/apps/server/src/matching/battle-queue-requests.ts index e1b49fa..9f884c8 100644 --- a/apps/server/src/matching/battle-queue-requests.ts +++ b/apps/server/src/matching/battle-queue-requests.ts @@ -12,7 +12,7 @@ import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy. import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts'; import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts'; import type { BattleSession, BattleSessionStore } from '../battle/battle-session-store.ts'; -import { DAILY_BACKUP, recordDailyBackupSpawn } from '../battle/battle-spares.ts'; +import { DAILY_BACKUP, normalizeBackupUnitName, recordDailyBackupSpawn } from '../battle/battle-spares.ts'; import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts'; import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts'; import { dailySparesLeft } from '../profile/profile-daily-spares.ts'; @@ -50,8 +50,9 @@ export function battleQueueRequests(deps: BattleQueueDependencies): Array<[strin return { error: 'BAD_PARAMS' }; } const battle = deps.sessions.findForUser(sessionId, userId); - if (!battle || battle.settled || battle.spareSlots?.get(slot) !== unit) return { error: 'BAD_PARAMS' }; - deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit, backup: DAILY_BACKUP })); + const normalizedUnit = normalizeBackupUnitName(unit); + if (!battle || battle.settled || battle.spareSlots?.get(slot) !== normalizedUnit) return { error: 'BAD_PARAMS' }; + deps.profiles.updateWhen(userId, (profile) => recordDailyBackupSpawn(profile, battle, { slot, unit: normalizedUnit, backup: DAILY_BACKUP })); return {}; }], ]; diff --git a/apps/server/src/profile/client-profile.ts b/apps/server/src/profile/client-profile.ts index da812bc..9a39f34 100644 --- a/apps/server/src/profile/client-profile.ts +++ b/apps/server/src/profile/client-profile.ts @@ -1,22 +1,30 @@ /** * The profile as the char service hands it to the client: the saved profile plus the - * account data and server clock the char server attaches on the wire. + * account data, server clock, and active squadron season metadata the char server attaches + * on the wire. * * charDrivenNick: the client reads the player's nick from this top-level string when it * loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d). * * serverTime:i64: the char server's clock; without it the client * takes the server time as 0 and every expiry and time limit is wrong. + * + * clanDuelNextReward:i64, clanSeasonStart:i64, clanSeasonOrdinal:i, clanSeasonInYear:i: + * parsed by GameSaveData::onAsyncEconTransComplete (aces.exe 2.61.0.58 0xebc728..0xebc7b4) + * on every profile-returning char response and exposed by clan_get_current_season_info + * (0x178aff0..0x178b227). Without them all fields default to 0, causing the squadron + * leaderboard to display "1970-I" and "1970-01-01". */ import { setParam, type BlkBlock } from '@wto/blk'; import type { Account } from '../accounts/account-store.ts'; +import { currentClanSeason } from '../clans/clan-season.ts'; import { appearance, DEFAULT_PILOT_ICON } from './profile-appearance.ts'; import { DAILY_SPARES_BLOCK } from './profile-daily-spares.ts'; import { clearStoreCart } from './profile-store-cart.ts'; import { clientHangarSpares } from './profile-vehicle-state.ts'; -import { serverTimeNow } from './server-time.ts'; +import { serverTimeFromUnixMs } from './server-time.ts'; -export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { +export function clientProfile(saved: BlkBlock, account: Account, nowMs = Date.now()): BlkBlock { // Clone the hangar entries whose spare count has a different wire representation. const profile: BlkBlock = { name: saved.name, @@ -26,8 +34,13 @@ export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { }; clearStoreCart(profile); const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON; + const season = currentClanSeason(Math.floor(nowMs / 1000)); setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon }); setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick }); - setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() }); + setParam(profile, 'serverTime', { type: 'int64', value: serverTimeFromUnixMs(nowMs) }); + setParam(profile, 'clanDuelNextReward', { type: 'int64', value: BigInt(season.rewardDaySec) }); + setParam(profile, 'clanSeasonStart', { type: 'int64', value: BigInt(season.startDaySec) }); + setParam(profile, 'clanSeasonOrdinal', { type: 'int', value: season.ordinalNumber }); + setParam(profile, 'clanSeasonInYear', { type: 'int', value: season.numberInYear }); return profile; } diff --git a/apps/server/src/profile/profile-client-settings.ts b/apps/server/src/profile/profile-client-settings.ts index 730e69d..40d4b26 100644 --- a/apps/server/src/profile/profile-client-settings.ts +++ b/apps/server/src/profile/profile-client-settings.ts @@ -5,7 +5,14 @@ * - hangar toggles `autoRefillWeapons:b`, `autoRepairAircrafts:b`, `autoBuyModifications:b` (0x918ef0); * - privacy / save metadata `onlineSaveVersion:i`, `allowToBeAddedToContacts:b`, `allowToBeAddedToLB:b` (0x9179d4..0x917a4c); * - `classinessMarkPriorities:i64` (0x92b2cb); - * - sub-block `mapPreferences` (0x927530 -> 0x9483d0). + * - sub-block `mapPreferences` (0x927530 -> 0x9483d0); + * - per-vehicle `hangar/` client preferences (`AircraftInfo::serialize` mode 0x20/0x80, + * owned vehicles only per the stock chard guard at 0x938081): + * - `lastSkin:t` (2.61.0.37 0x940fbc/0x94111b, 2.61.0.58 0x943a2f/0x943b8e); + * - `lastWeapon:t` (2.61.0.37 0x940ff4/0x941084, 2.61.0.58 0x943a67/0x943af7); + * - `lastBullets0..5:t` (2.61.0.37 0x94078d..0x940914 / 0x940b2c..0x940f8d, 2.61.0.58 0x943200..0x94393e); + * - `aileronTrim:r`, `elevatorTrim:r`, `rudderTrim:r` (2.61.0.37 0x941682..0x941720 / 0x9411e7..0x9412db, + * 2.61.0.58 0x943c7a..0x944119). * * Empty shell blocks that `saveOnline` (mode 0x20) also emits (`entitlementsInfo{}`, * `pveProgress{}`, `weaponPresets{}` — custom weapon presets use `cln_save_weapon_presets`, and @@ -13,6 +20,7 @@ * state is preserved. */ import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import { updateOwnedVehicle } from './profile-hangar.ts'; import { disableUserLogs } from './profile-trophies-log.ts'; const BOOL_SETTINGS = [ @@ -23,6 +31,23 @@ const BOOL_SETTINGS = [ 'allowToBeAddedToLB', ] as const; +const VEHICLE_STRING_SETTINGS = [ + 'lastSkin', + 'lastWeapon', + 'lastBullets0', + 'lastBullets1', + 'lastBullets2', + 'lastBullets3', + 'lastBullets4', + 'lastBullets5', +] as const; + +const VEHICLE_TRIM_SETTINGS = [ + 'aileronTrim', + 'elevatorTrim', + 'rudderTrim', +] as const; + /** * Whether hangar ammunition/expendable auto-refill is enabled (`EconomicState` +0xe979). * Defaults to `true` when absent from `profile.blk`, matching `aces.exe` 0x90b6a0 and 0x918ef0. @@ -57,6 +82,10 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock): target.blocks = cloned.blocks; } + for (const vehicle of findBlock(request, 'hangar')?.blocks ?? []) { + applyVehicleClientSettings(profile, vehicle); + } + const userlogs = findBlock(request, 'userlogs'); if (userlogs) { const idsToDisable = userlogs.blocks @@ -68,3 +97,16 @@ export function applyClientProfileUpdate(profile: BlkBlock, request: BlkBlock): if (idsToDisable.length > 0) disableUserLogs(profile, idsToDisable); } } + +function applyVehicleClientSettings(profile: BlkBlock, vehicle: BlkBlock): void { + updateOwnedVehicle(profile, vehicle.name, (entry) => { + for (const name of VEHICLE_STRING_SETTINGS) { + const param = findParam(vehicle, name)?.value; + if (param?.type === 'string') setParam(entry, name, param); + } + for (const name of VEHICLE_TRIM_SETTINGS) { + const param = findParam(vehicle, name)?.value; + if (param?.type === 'real' && Number.isFinite(param.value)) setParam(entry, name, param); + } + }); +} diff --git a/apps/server/src/profile/profile-hangar.ts b/apps/server/src/profile/profile-hangar.ts index d569b9a..d983e24 100644 --- a/apps/server/src/profile/profile-hangar.ts +++ b/apps/server/src/profile/profile-hangar.ts @@ -31,6 +31,12 @@ export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void { if (!hangar.blocks.some((owned) => owned.name === vehicle)) hangar.blocks.push({ name: vehicle, params: [], blocks: [] }); } +/** Update an owned vehicle's hangar entry in place; ignores vehicles the player does not own. */ +export function updateOwnedVehicle(profile: BlkBlock, vehicle: string, update: (entry: BlkBlock) => void): void { + const entry = ownedVehicle(profile, vehicle); + if (entry) update(entry); +} + /** 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)); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index b58597d..848e2f1 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -60,6 +60,7 @@ import { Router } from './transport/router.ts'; import { loadOrCreateCredentials } from './transport/tls/tls-certificate.ts'; import { StoreCatalogue } from './store/store-catalogue.ts'; import { StoreService } from './store/store-service.ts'; +import { bindStoreFreePaymentLabel } from './store/store-tuning.ts'; import { TrainingCatalogue } from './training/training-completion.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts'; import { loadTuning, type Tuning } from './tuning/tuning.ts'; @@ -235,7 +236,7 @@ export async function startServer(options: ServerOptions): Promise(); + +/** Associate a configured free payment label with a StoreCatalogue instance. */ +export function bindStoreFreePaymentLabel(store: object, label: LocalizedText): void { + freePaymentLabelsByStore.set(store, label); +} + +/** Return the configured free payment label for a StoreCatalogue instance, falling back to the default. */ +export function freePaymentLabelForStore(store: object): LocalizedText { + return freePaymentLabelsByStore.get(store) ?? DEFAULT_FREE_PAYMENT_LABEL; +} + export interface StoreTuning { + /** Localized label for the no-GJN offline payment button in the game dialog, local store, and marketplace. */ + readonly freePaymentLabel: LocalizedText; readonly goldenEaglePacks: readonly GoldenEaglePack[]; readonly silverLionPacks: readonly SilverLionPack[]; readonly premiumForGoldenEagles: readonly PremiumTier[]; @@ -53,6 +73,7 @@ export interface StoreTuning { } export function readStoreTuning(file: TuningReader): StoreTuning { + const freePaymentLabel = readFreePaymentLabel(file); const packs = file.object('vehiclePacks'); const byRank = packs.list('byRank', (entry) => ({ upToRank: entry.int('upToRank', { min: 1 }), ...packContent(entry) })) .sort((a, b) => a.upToRank - b.upToRank); @@ -66,6 +87,7 @@ export function readStoreTuning(file: TuningReader): StoreTuning { validateStoreUniqueness(goldenEaglePacks, silverLionPacks, premiumForGoldenEagles, premiumForGjn, multiVehiclePacks); return { + freePaymentLabel, goldenEaglePacks, silverLionPacks, premiumForGoldenEagles, @@ -76,6 +98,27 @@ export function readStoreTuning(file: TuningReader): StoreTuning { }; } +function readFreePaymentLabel(file: TuningReader): LocalizedText { + const labelObj = file.object('freePaymentLabel'); + return { + zh: readFreePaymentLabelPart(labelObj, 'zh'), + en: readFreePaymentLabelPart(labelObj, 'en'), + }; +} + +function readFreePaymentLabelPart(entry: TuningReader, key: 'zh' | 'en'): string { + const trimmed = entry.string(key).trim(); + if (trimmed === '') { + throw new TuningError(`tuning file store.jsonc: freePaymentLabel.${key} must not be blank`); + } + if (trimmed.length > MAX_FREE_PAYMENT_LABEL_LENGTH) { + throw new TuningError( + `tuning file store.jsonc: freePaymentLabel.${key} must be at most ${MAX_FREE_PAYMENT_LABEL_LENGTH} characters`, + ); + } + return trimmed; +} + /** The pack content for a vehicle: its own entry over the first rank tier that covers its rank (the last tier above the highest). */ export function vehiclePackContent(tuning: StoreTuning, vehicle: string, rank: number): VehiclePackContent { const tier = tuning.vehiclePacksByRank.find((entry) => rank <= entry.upToRank) ?? tuning.vehiclePacksByRank[tuning.vehiclePacksByRank.length - 1]!; diff --git a/apps/server/src/store/store-web-api.ts b/apps/server/src/store/store-web-api.ts index eadec17..02a2929 100644 --- a/apps/server/src/store/store-web-api.ts +++ b/apps/server/src/store/store-web-api.ts @@ -20,6 +20,7 @@ import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } fro import type { RedeemTuning } from './redeem-tuning.ts'; import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; import { buyFreeStoreProduct, buyGjnProduct, buyStoreCart, canBuyGjnProduct, type GjnPurchaseOutcome, type StoreCheckoutOutcome } from './store-purchase.ts'; +import { freePaymentLabelForStore } from './store-tuning.ts'; const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' }; @@ -31,12 +32,20 @@ export class StoreWebApi { readonly #profiles: PlayerProfiles; readonly #catalogue: StoreCatalogue; readonly #redeemCodes: RedeemTuning; + readonly #freePaymentLabel: LocalizedText; - constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue, redeemCodes: RedeemTuning) { + constructor( + accounts: AccountStore, + profiles: PlayerProfiles, + catalogue: StoreCatalogue, + redeemCodes: RedeemTuning, + freePaymentLabel?: LocalizedText, + ) { this.#accounts = accounts; this.#profiles = profiles; this.#catalogue = catalogue; this.#redeemCodes = redeemCodes; + this.#freePaymentLabel = freePaymentLabel ?? freePaymentLabelForStore(catalogue); } /** The answer for /store/api/, or undefined when it is not an API request. */ @@ -64,6 +73,7 @@ export class StoreWebApi { products, cartProductIds: profile ? storeCartIds(profile) : [], redeemHelp: describeRedeemCodes(this.#redeemCodes), + freePaymentLabel: this.#freePaymentLabel, }, `store web state (${account?.userId ?? 'no account'})`); } @@ -94,7 +104,10 @@ export class StoreWebApi { return true; }); const modeTag = isFree ? 'free' : 'gjn'; - return jsonResponse({ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`); + return jsonResponse( + { ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree, this.#freePaymentLabel) }, + `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`, + ); } #cart(request: ServiceRequest): ServiceResponse { @@ -153,7 +166,7 @@ export class StoreWebApi { return false; } const outcome = buyStoreCart(profile, products, payMethod, now); - message = checkoutMessage(outcome, products, payMethod); + message = checkoutMessage(outcome, products, payMethod, this.#freePaymentLabel); if (!outcome.ok) return false; clearStoreCart(profile); cartProductIds = []; @@ -177,13 +190,18 @@ export class StoreWebApi { } } -function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isFree: boolean): LocalizedText { +function purchaseMessage( + outcome: GjnPurchaseOutcome, + product: StoreProduct, + isFree: boolean, + freePaymentLabel: LocalizedText, +): LocalizedText { const cost = gjnText(product.gjnCostCents ?? 0); if (outcome.ok) { return isFree ? { - zh: `老福爷付过了!已直接获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`, - en: `Paid by 老福爷! Claimed "${product.title.en}". Close the store window to refresh the hangar.`, + zh: `已通过「${freePaymentLabel.zh}」获得「${product.title.zh}」。关闭商店窗口后机库会自动刷新。`, + en: `Claimed "${product.title.en}" via "${freePaymentLabel.en}". Close the store window to refresh the hangar.`, } : { zh: `已购买「${product.title.zh}」,花费 ${cost} GJN。关闭商店窗口后机库会自动刷新。`, @@ -191,7 +209,10 @@ function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isF }; } if (outcome.reason === 'NOT_ENOUGH_GJN') { - return { zh: `GJN 不够:需要 ${cost} GJN。可直接点「老福爷付过了」,或在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. Use "老福爷付过了" or a GJN code on the Redeem tab.` }; + return { + zh: `GJN 不够:需要 ${cost} GJN。可直接点「${freePaymentLabel.zh}」,或在"兑换码"页用 GJN 充值码补充。`, + en: `Not enough GJN: ${cost} GJN needed. Use "${freePaymentLabel.en}" or a GJN code on the Redeem tab.`, + }; } if (outcome.reason === 'ALREADY_BOUGHT') return alreadyBoughtMessage(product); return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' }; @@ -208,19 +229,23 @@ function checkoutMessage( outcome: StoreCheckoutOutcome, products: readonly StoreProduct[], payMethod: 'gjn' | 'free', + freePaymentLabel: LocalizedText, ): LocalizedText { if (outcome.ok) { const count = products.length; const cost = gjnText(outcome.costCents); return payMethod === 'free' - ? { zh: `老福爷付过了!已领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`, - en: `Paid by 老福爷! Claimed ${count} items. Close the store to refresh the hangar.` } + ? { zh: `已通过「${freePaymentLabel.zh}」领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`, + en: `Claimed ${count} items via "${freePaymentLabel.en}". Close the store to refresh the hangar.` } : { zh: `已购买 ${count} 件商品,花费 ${cost} GJN。关闭商城窗口后机库会自动刷新。`, en: `Bought ${count} items for ${cost} GJN. Close the store to refresh the hangar.` }; } if (outcome.reason === 'NOT_ENOUGH_GJN') { const cost = gjnText(outcome.costCents); - return { zh: `购物车共需 ${cost} GJN,当前余额不足。`, en: `Your cart costs ${cost} GJN. Your balance is too low.` }; + return { + zh: `购物车共需 ${cost} GJN,当前余额不足。可直接点「${freePaymentLabel.zh}」。`, + en: `Your cart costs ${cost} GJN. Your balance is too low. Use "${freePaymentLabel.en}" instead.`, + }; } const product = products.find((item) => item.id === outcome.productId); return outcome.reason === 'ALREADY_BOUGHT' && product ? alreadyBoughtMessage(product) : NO_PRODUCT; diff --git a/apps/server/src/store/web/app.js b/apps/server/src/store/web/app.js index e52699f..9a57e3d 100644 --- a/apps/server/src/store/web/app.js +++ b/apps/server/src/store/web/app.js @@ -9,7 +9,7 @@ const T = { search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级', sort: '商品排序', sortBest: '最畅销', sortNewest: '最新上架', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低', containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户', - buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先选择账号', + buy: '购买', freeBuy: '直接获取', owned: '已拥有', pickAccount: '请先选择账号', redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品', featured: '推荐礼包', bestSeller: '畅销', viewPack: '查看礼包', related: '更多推荐', packPrice: '礼包价格', includes: '礼包内容', back: '返回目录', bonusTitle: '高级载具权益', @@ -31,7 +31,7 @@ const T = { search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}', sort: 'Sort products', sortBest: 'Top sellers', sortNewest: 'Newest', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low', containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account', - buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account first', + buy: 'Buy', freeBuy: 'Direct Claim', owned: 'Owned', pickAccount: 'Pick an account first', redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters', featured: 'Featured packs', bestSeller: 'Top seller', viewPack: 'View pack', related: 'Explore other packs', packPrice: 'Pack price', includes: 'Pack contents', back: 'Back to catalog', bonusTitle: 'Premium bonuses', @@ -53,7 +53,7 @@ const t = (key, params) => WtoUi.tr(T, key, params); const $ = (id) => document.getElementById(id); let initialGuid = (WtoUi.query.get('item') || '').toUpperCase(); -let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [] }; +let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [], freePaymentLabel: null }; let currentTab = 'vehicle-pack'; let detailId = ''; let catalogScroll = 0; @@ -61,9 +61,14 @@ let loadVersion = 0; let loading = true; const checkout = createStoreCheckout(loadState); +function freePaymentLabel() { + return WtoUi.text(state.freePaymentLabel) || t('freeBuy'); +} + function applyStaticTexts() { for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t); for (const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label', t(el.dataset.label)); + $('payFree').textContent = freePaymentLabel(); $('searchInput').placeholder = t('search'); $('codeInput').placeholder = t('codePlaceholder'); $('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/'); @@ -88,6 +93,7 @@ async function loadState(userId) { return await loadState(''); } state = next; + $('payFree').textContent = freePaymentLabel(); WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId); $('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents); $('goldVal').textContent = WtoUi.num(state.balance.goldenEagles); diff --git a/apps/server/tuning/clans.jsonc b/apps/server/tuning/clans.jsonc index d84dae5..a80b239 100644 --- a/apps/server/tuning/clans.jsonc +++ b/apps/server/tuning/clans.jsonc @@ -2,19 +2,25 @@ { // Set activity and squadron RP. The service reports maxActivityPerPeriod, maxClanActivity, rewardPeriodDays, and historyDepth in squadron replies. "activity": { - "maxPerPeriod": 360, // Activity cap per reward period. + "maxPerPeriod": 360, // Activity cap per reward period. "squadronRpPerFullPeriod": 20000, // Squadron RP awarded for a full activity period. "rewardPeriodDays": 3, // Reward period in days. "historyDepthDays": 14, // Activity history displayed by the client, in days. - // Seed full periods on creation or joining so squadron research can start immediately. - "startingPeriods": 3 + // Base vehicle RP from battles required for 1 squadron activity point (stock rule: 200 RP = 1 point). + "rpPerActivityPoint": 200, + // Starting current-period activity for a player creating or joining a squadron (0..maxPerPeriod). + // Set to 360 together with startingPeriods > 0 in /tuning/clans.jsonc to start at full activity immediately. + "startingActivity": 0, + // Full past activity periods granted on creation or joining (default 0: earn activity through battles). + // Increase (e.g. 1 or 3) in /tuning/clans.jsonc to grant immediate squadron RP on joining. + "startingPeriods": 0 }, // Set the full squadron cap and initial battalion cap. Expansion cost and step size are read from warpoints.blk. "memberLimits": { "normal": 128, "battalionInitial": 10 }, - // Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier), so small NPC rosters can represent full squadrons. - "leaderboard": { "activityMultiplier": 10, "maxActivity": 100000 }, + // Displayed leaderboard activity is min(maxActivity, summed member activity * activityMultiplier). + "leaderboard": { "activityMultiplier": 1, "maxActivity": 100000 }, // Starting ID for player-created squadrons. "firstNewClanId": 600001, @@ -29,6 +35,37 @@ "presetClans": { "createdDaysAgo": 180, // Age of the first seeded squadron before applying each squadron's createdAfterDays offset. "memberJoinSpacingMinutes": 60, + "npcHistoryPeriods": 3, // Past activity periods seeded for preset NPC members. + // Deterministic filler NPC pool used when a preset clan's targetMemberCount exceeds its named roster. + "fillerMembers": { + "activityMin": 340, + "activityMax": 360, + "uidBase": 900000000, + "uidStride": 1000, + "callsigns": [ + "Vanguard", "Falcon", "Striker", "Sentinel", "Raptor", "Valkyrie", + "Tempest", "Bastion", "Corsair", "Drago", "Harrier", "Kestrel", + "Lancer", "Mirage", "Nomad", "Osprey", "Paladin", "Reaper", + "Sabre", "Talon", "Vector", "Warden", "Zephyr", "Aegis", + "Cobra", "Hornet", "Jaguar", "Lynx", "Mantis", "Puma" + ], + "titles": [ + "title_pilot", "title_tankman", "title_ace", "title_sniper", + "title_scout", "title_eagle", "title_tank_destroyer", "title_jet_powered" + ], + "icons": [ + "cardicon_03", "cardicon_05", "cardicon_07", "cardicon_08", + "cardicon_09", "cardicon_11", "cardicon_12", "cardicon_14", + "cardicon_15", "cardicon_16", "cardicon_18", "cardicon_19", + "cardicon_20", "cardicon_22", "cardicon_25", "cardicon_28" + ], + "units": [ + "cn_ztz_99a", "su_27sm", "germ_leopard_2a7v", "f_14b", + "jp_destroyer_shimakaze", "sw_strv_122b_plus", "j_11a", "jh_7a", + "cn_vt_4a1", "f_15j_kai", "ussr_t_90m", "us_m1a2_sep2_abrams", + "uk_challenger_2_black_night", "us_hstvl", "it_centauro_rgo_120" + ] + }, // Lifetime stats displayed for each seeded squadron. "stats": { "akills_arc": 4280, "akills_hist": 6150, "akills_sim": 1420, @@ -45,7 +82,7 @@ "slogan": "离线天空与钢铁防线 · 自由研发全部联队载具", "desc": "War Thunder Offline 官方预置主力联队。开启自动审批,加入即可获得完整联队活跃度与联队研发点支持。", "announcement": "欢迎加入 [WTOF]!可在联队页面右上角点击「联队载具」或「活跃度」查看研发进度。", - "region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, + "region": "CN / Global", "autoAccept": true, "createdAfterDays": 0, "targetMemberCount": 60, "rating": { "arc": 1840, "hist": 2150, "sim": 1620 }, "members": [ { "uid": "900001001", "nick": "Lin_Wei", "role": "LEADER", "title": "title_marshall", "icon": "cardicon_28", "unit": "cn_ztz_99a", "activity": 360 }, @@ -61,7 +98,7 @@ "slogan": "鹰击长空 · 现代喷气空战与陆空协同联队", "desc": "专注于高阶喷气机与现代主战坦克联合作战的离线联队,支持自动入队与高活跃度加成。", "announcement": "本期联队研发推荐:F-16A OCU、苏-33、豹 2PL、M1A1 AIM。", - "region": "Asia", "autoAccept": true, "createdAfterDays": 12, + "region": "Asia", "autoAccept": true, "createdAfterDays": 12, "targetMemberCount": 60, "rating": { "arc": 1690, "hist": 2040, "sim": 1780 }, "members": [ { "uid": "900002001", "nick": "SkyDragon_J20", "role": "LEADER", "title": "title_ace", "icon": "cardicon_25", "unit": "j_11a", "activity": 360 }, @@ -75,7 +112,7 @@ "slogan": "Steel & Fire — Heavy Armor Historical Squadron", "desc": "Classic and modern armored warfare squadron. Open auto-accept recruitment for all tank commanders.", "announcement": "Squadron vehicles ready for research at full 20,000 RP per period.", - "region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, + "region": "EU / Global", "autoAccept": true, "createdAfterDays": 24, "targetMemberCount": 60, "rating": { "arc": 1920, "hist": 1980, "sim": 1510 }, "members": [ { "uid": "900003001", "nick": "Kommissar_KVs", "role": "LEADER", "title": "title_hero", "icon": "cardicon_22", "unit": "ussr_t_90m", "activity": 360 }, @@ -88,7 +125,7 @@ "slogan": "All The Way — Air, Ground & Naval Task Force", "desc": "需要审批模式的示例联队(用于测试发送与撤回入队申请流程)。若想立即加入联队,请选择 [WTOF]、=PLAF= 或 -1STG-。", "announcement": "Manual application review enabled for testing request/cancel workflow.", - "region": "NA", "autoAccept": false, "createdAfterDays": 35, + "region": "NA", "autoAccept": false, "createdAfterDays": 35, "targetMemberCount": 58, "rating": { "arc": 1550, "hist": 1760, "sim": 1490 }, "members": [ { "uid": "900004001", "nick": "Major_Winters", "role": "LEADER", "title": "title_brother_in_arms", "icon": "cardicon_03", "unit": "us_m1a2_sep2_abrams", "activity": 360 }, @@ -100,7 +137,7 @@ "slogan": "轻量级战术分队 · 侦察与快速反应", "desc": "战斗群(Battalion)类型预置联队,开启自动加入,支持体验战斗群架构与联队扩编。", "announcement": "轻装侦察分队常驻开放。", - "region": "Global", "autoAccept": true, "createdAfterDays": 48, + "region": "Global", "autoAccept": true, "createdAfterDays": 48, "targetMemberCount": 2, "rating": { "arc": 1410, "hist": 1610, "sim": 1320 }, "members": [ { "uid": "900005001", "nick": "Ghost_Scout", "role": "LEADER", "title": "title_scout", "icon": "cardicon_15", "unit": "us_hstvl", "activity": 360 }, diff --git a/apps/server/tuning/store.jsonc b/apps/server/tuning/store.jsonc index e620eb5..5bc9e7e 100644 --- a/apps/server/tuning/store.jsonc +++ b/apps/server/tuning/store.jsonc @@ -1,6 +1,10 @@ // Local store products and prices. // The client receives these prices from the local server. { + // Button label for the no-GJN offline payment method shown in the in-game payment dialog, + // local web store, and local marketplace. Players can override it in /tuning/store.jsonc. + "freePaymentLabel": { "zh": "直接获取", "en": "Direct Claim" }, + // GJN prices use the official USD prices at 1 GJN per USD. // Golden Eagle packs use GJN in both the in-game payment dialog and the local web store. diff --git a/game-ai/ground/wto_ai_combat_types_common.das b/game-ai/ground/wto_ai_combat_types_common.das index c9e88ae..14a0301 100644 --- a/game-ai/ground/wto_ai_combat_types_common.das +++ b/game-ai/ground/wto_ai_combat_types_common.das @@ -29,6 +29,7 @@ let public WTO_DENY_MUZZLE_HARD = 8 let public WTO_DENY_ARC_HARD = 9 let public WTO_DENY_FRIENDLY = 10 let public WTO_DENY_MULTI_GUN = 11 +let public WTO_DENY_TRAVERSE = 12 [safe_when_uninitialized] struct public WtoShellProfile @@ -76,9 +77,21 @@ struct public WtoPerceiveState expScore : float[8] expGoodLosSec : float[8] +[safe_when_uninitialized] +struct public WtoGunTraverse + known : bool = false + yaw : float2 = float2(0.0, 0.0) + pitch : float2 = float2(1.0, 0.0) + hasPitchTable : bool = false + pitchSector : float4 = float4(1.0, 0.0, 1.0, 0.0) + [safe_when_uninitialized] struct public WtoFireState turretNo : int = -1 + traverseTurretNo : int = -1 + traverse : WtoGunTraverse = WtoGunTraverse() + hullAimTarget : EntityId = INVALID_ENTITY_ID + hullAimDir : float3 = float3(0.0, 0.0, 0.0) gunReady : bool = false reloading : bool = false gunDamaged : bool = false @@ -89,8 +102,6 @@ struct public WtoFireState activeCaliberM : float = 0.09 pitchBlocked : bool = false pitchClampSec : float = 0.0 - cmdYawDeg : float = 0.0 - cmdPitchDeg : float = 0.0 curYawDeg : float = 0.0 curPitchDeg : float = 0.0 prevPitchDeg : float = 0.0 diff --git a/game-ai/ground/wto_ai_drive_common.das b/game-ai/ground/wto_ai_drive_common.das index f0d0b57..a9fa33d 100644 --- a/game-ai/ground/wto_ai_drive_common.das +++ b/game-ai/ground/wto_ai_drive_common.das @@ -71,6 +71,15 @@ def private wto_check_echo_watchdog(unitMissionName : string; var actor : Vehicl st.deadEchoSec = 0.0 return true +def public wto_pivot_drive_mode(spec : WtoVehicleSpec const&; frontClearM, rearClearM : float; preferNeutral : bool) : int + let openFront = frontClearM >= spec.halfLen + 3.5 + let neutralTurn = spec.canPivot && frontClearM >= spec.halfLen + 1.2 && rearClearM >= spec.halfLen + 1.0 + if neutralTurn && (preferNeutral || !openFront) + return WTO_DRIVE_PIVOT + if openFront + return WTO_DRIVE_CRUISE + return rearClearM >= spec.halfLen + WTO_AI_TERRAIN_MARGIN_M ? WTO_DRIVE_REVERSE : WTO_DRIVE_HALT + [never_inline] def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; fwd, left : float3; vFwd, omega : float; @@ -83,15 +92,18 @@ def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSp outBrk = 1.0 outStr = turnSign * WTO_AI_NAV_STEER_SIGN return - let openFront = cmd.frontClearM >= spec.halfLen + 3.5 - if openFront + let mode = wto_pivot_drive_mode(spec, cmd.frontClearM, cmd.rearClearM, cmd.speedMps <= 0.0) + if mode == WTO_DRIVE_PIVOT + let response = errRad / (WTO_AI_NAV_PIVOT_ANGLE_DEG * WTO_DEG_TO_RAD) + outStr = clamp(response - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN + return + if mode == WTO_DRIVE_CRUISE // Two-beat turn micro: launch straight to 2nd gear before applying full steering. outThr = 1.0 outStr = abs(vFwd) < WTO_AI_SM_TURN_LAUNCH_MPS ? 0.0 : (turnSign * WTO_AI_NAV_STEER_SIGN) return - if spec.canPivot && cmd.frontClearM >= spec.halfLen + 1.2 && cmd.rearClearM >= spec.halfLen + 1.0 - outThr = 0.0 - outStr = clamp(turnSign - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN + if mode == WTO_DRIVE_HALT + outBrk = 1.0 return // Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall. outThr = vFwd > -WTO_AI_SM_TURN_LAUNCH_MPS ? -1.0 : -0.6 @@ -176,7 +188,7 @@ def private wto_ensure_phys_owner(gm : IGroundModel const?; var actor : VehicleP return false if !st.routeBOwned slot.spec.isTracked = actor.phys.trackWidth > 0.01 - slot.spec.canPivot = slot.spec.isTracked && actor.phys.haveSeparateBrakes + slot.spec.canPivot = slot.spec.canPivot && slot.spec.isTracked && actor.phys.haveSeparateBrakes st.routeBOwned = true return st.routeBOwned @@ -190,12 +202,12 @@ def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, veloci var str = 0.0 var brk = 0.0 var hand = 0.0 - if cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05 + if cmd.mode == WTO_DRIVE_PIVOT + wto_compute_pivot_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk) + elif cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05 thr = abs(vFwd) > 0.35 ? (vFwd > 0.0 ? -1.0 : 1.0) : 0.0 brk = 1.0 hand = abs(vFwd) > 0.35 ? 0.0 : 1.0 - elif cmd.mode == WTO_DRIVE_PIVOT - wto_compute_pivot_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk) elif cmd.mode == WTO_DRIVE_REVERSE wto_compute_reverse_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk, hand) else diff --git a/game-ai/ground/wto_ai_fire_common.das b/game-ai/ground/wto_ai_fire_common.das index d44f0d3..73bfcbd 100644 --- a/game-ai/ground/wto_ai_fire_common.das +++ b/game-ai/ground/wto_ai_fire_common.das @@ -22,31 +22,7 @@ require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_fire_gate_common - -[never_inline] -def private wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3; - var outYawDeg, outPitchDeg : float&) - let len = length(worldDir) - if len < 1.0e-5 - outYawDeg = 0.0 - outPitchDeg = 0.0 - return - let d = worldDir / len - let f = dot(d, hullFwd) - let u = dot(d, hullUp) - let l = dot(d, hullLeft) - let horiz = sqrt(f * f + l * l) - outYawDeg = horiz > 1.0e-5 ? (-atan2(l, f) * WTO_RAD_TO_DEG) : 0.0 - outPitchDeg = clamp(atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG, -24.0, 65.0) - -[never_inline] -def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3 - let yr = yawDeg * WTO_DEG_TO_RAD - let pr = pitchDeg * WTO_DEG_TO_RAD - let cp = cos(pr) - let dir = hullFwd * (cp * cos(yr)) - hullLeft * (cp * sin(yr)) + hullUp * sin(pr) - let l = length(dir) - return l > 1.0e-5 ? (dir / l) : hullFwd +require %appGame.wtoai.wto_ai_traverse_common [never_inline] def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&) @@ -111,18 +87,23 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const& [never_inline] def private wto_inspect_primary_weapon(var unit : Unit?; now : float; spec : WtoVehicleSpec const&; wantSoftShell : bool; - var fc : WtoFireState&) + var fc : WtoFireState&) : int + let previousTurret = fc.turretNo fc.turretNo = -1 fc.gunReady = false fc.reloading = false fc.gunDamaged = false if unit == null || unit.weap == null - return + return -1 + var selected = -1 + var nextIndex = 0 var anyGun = false var anyAlive = false var anyReserve = false var totalLoaded = 0 foreach_primary_gun(unit.weap.Weapons) <| $(var weapon) + let index = nextIndex + nextIndex++ if weapon == null || weapon.isDummyGun return var gun = as_gun(weapon) @@ -131,7 +112,8 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; anyGun = true anyAlive = true anyReserve = true - if fc.turretNo < 0 + if selected < 0 + selected = index fc.turretNo = weapon.turretNo fc.gunReady = true totalLoaded += weapon.countBullets @@ -140,8 +122,11 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; if gun.isInoperable return anyAlive = true - if fc.turretNo < 0 + if selected < 0 + selected = index fc.turretNo = weapon.turretNo + if fc.turretNo != previousTurret + fc.loadedBulletIdx = -1 wto_select_next_shell(gun, spec, wantSoftShell) wto_sync_active_shell(gun, spec, fc) if gun.isReadyToShoot @@ -158,6 +143,7 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float; elif (now - fc.pendingShotAt) > 0.35 fc.pendingShotConfirm = false fc.prevLoadedAmmo = totalLoaded + return selected [never_inline] def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&; @@ -178,63 +164,24 @@ def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBot return rawDist [never_inline] -def private wto_sample_turret_muzzle(unit : Unit const?; turretNo : int; - var outPos, outDir : float3&) : bool - if unit == null || unit.weap == null +def private wto_sample_muzzle(unit : Unit const?; primaryIndex : int; + var outPos, outDir : float3&) : bool + if unit == null || unit.weap == null || primaryIndex < 0 return false - for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret - if (turretNo >= 0 && tIdx != turretNo) || (turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) - continue - let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex)) + var sampled = false + get_weapons_by_trigger_group(unit.weap.Weapons, WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) <| $(weapons : array const#) + if primaryIndex >= length(weapons) + return + assume weapon = weapons[primaryIndex] if weapon == null - continue + return var gunTm : float3x4 weapon_calcShootTm(weapon, unit.unitTm, gunTm) if length_sq(gunTm[0]) > 0.25 outPos = gunTm[3] outDir = normalize(gunTm[0]) - return true - return false - -[never_inline] -def private wto_drive_turret_and_sample_barrel(var unit : Unit?; dt : float; - wishYawDeg, wishPitchDeg : float; - var slot : WtoBotSlot&; - var outMuzzlePos, outLiveDir : float3&) - assume fc = slot.fire - let dtStep = clamp(dt, 0.005, 0.12) - for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret - if (fc.turretNo >= 0 && tIdx != fc.turretNo) || (fc.turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) - continue - fc.curYawDeg = turret.currentState.yaw - fc.curPitchDeg = turret.currentState.pitch - if !fc.servoInit - fc.cmdYawDeg = fc.curYawDeg - fc.cmdPitchDeg = fc.curPitchDeg - fc.prevPitchDeg = fc.curPitchDeg - fc.servoInit = true - let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep - fc.prevPitchDeg = fc.curPitchDeg - if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8 - fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep) - fc.pitchBlocked = fc.pitchClampSec >= 0.75 - else - fc.pitchClampSec = max(0.0, fc.pitchClampSec - dtStep * 2.5) - if fc.pitchClampSec <= 0.05 - fc.pitchBlocked = false - let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep - let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep - let yawDelta = clamp(wto_wrap_deg(wishYawDeg - fc.curYawDeg), -maxYawStep, maxYawStep) - let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep) - fc.cmdYawDeg = wto_wrap_deg(fc.curYawDeg + yawDelta) - fc.cmdPitchDeg = clamp(fc.curPitchDeg + pitchDelta, slot.spec.minPitchDeg - 2.0, slot.spec.maxPitchDeg + 2.0) - turret.yawLim = fc.cmdYawDeg - turret.pitchLim = fc.cmdPitchDeg - break - var uPos = unit.pos - updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos) - if !wto_sample_turret_muzzle(unit, fc.turretNo, outMuzzlePos, outLiveDir) - outLiveDir = wto_hull_deg_to_world(fc.curYawDeg, fc.curPitchDeg, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2]) + sampled = true + return sampled def private wto_clear_aim_tracking(var fc : WtoFireState&) fc.aimTargetEid = INVALID_ENTITY_ID @@ -244,12 +191,13 @@ def private wto_clear_aim_tracking(var fc : WtoFireState&) fc.lastDenyReason = WTO_DENY_NO_TARGET [never_inline] -def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; +def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; className : string; now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&) if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null return // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). if slot.tactics.spaaYieldAir + wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot) wto_clear_aim_tracking(slot.fire) var gm = as_gm(unit) if gm != null @@ -263,10 +211,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid) if tgtIdx >= 0 wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35 - wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire) + let primaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire) var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0) var liveBarrelDir = unit.unitTm[0] - let _preSample = wto_sample_turret_muzzle(unit, slot.fire.turretNo, muzzlePos, liveBarrelDir) + let _preSample = wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) let hFwd = unit.unitTm[0] var wishWorldDir = hFwd @@ -287,8 +235,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; var wishYaw = 0.0 var wishPitch = 0.0 wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) - wto_drive_turret_and_sample_barrel(unit, dt, wishYaw, wishPitch, slot, muzzlePos, liveBarrelDir) - if !engageValid || distToTgt > WTO_AI_FC_MAX_RANGE_M + wto_drive_mounted_gun(unit, className, dt, wishYaw, wishPitch, slot) + let canEngage = engageValid && distToTgt <= WTO_AI_FC_MAX_RANGE_M && wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir) + wto_set_hull_aim(unit, canEngage, wishYaw, liveBarrelDir, slot) + if !canEngage wto_clear_aim_tracking(slot.fire) return let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) diff --git a/game-ai/ground/wto_ai_fire_gate_common.das b/game-ai/ground/wto_ai_fire_gate_common.das index bbbaaef..d39b049 100644 --- a/game-ai/ground/wto_ai_fire_gate_common.das +++ b/game-ai/ground/wto_ai_fire_gate_common.das @@ -186,12 +186,15 @@ def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit? let speedOk = measuredSpeed <= speedLimit let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distXZ, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4) - wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, aimErrDeg <= allowErrDeg && speedOk, close, fc) + let withinTraverse = fc.hullAimTarget == INVALID_ENTITY_ID + wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, withinTraverse && aimErrDeg <= allowErrDeg && speedOk, close, fc) let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65 let reqHold = close ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC var deny = WTO_DENY_OK - if !fc.gunReady || (now - fc.lastShotAt) < minCadence + if !withinTraverse + deny = WTO_DENY_TRAVERSE + elif !fc.gunReady || (now - fc.lastShotAt) < minCadence deny = WTO_DENY_NOT_READY elif !speedOk deny = WTO_DENY_SPEED diff --git a/game-ai/ground/wto_ai_nav_common.das b/game-ai/ground/wto_ai_nav_common.das index bb58bde..4320754 100644 --- a/game-ai/ground/wto_ai_nav_common.das +++ b/game-ai/ground/wto_ai_nav_common.das @@ -14,6 +14,7 @@ require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_nav_types_common +require %appGame.wtoai.wto_ai_drive_common require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_navquery_common require %appGame.wtoai.wto_ai_navmesh_common @@ -30,18 +31,21 @@ def private wto_nav_halt(myPos, hullFwd : float3; var slot : WtoBotSlot&) wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) slot.nav.bumperBlockedSince = -100.0 +// A target outside the gun's traverse: the fire layer asks for the hull to turn to it, and the +// chassis pivots in place where it has room (wto_ai_traverse_common.das). [never_inline] -def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : WtoBotSlot&) - // Casemate / limited-traverse TDs rotate hull ONLY while target is outside 78% of gun arc. - if slot.spec.isLimitedTraverse && !!slot.perceive.targetEid - let toTgt = wto_xz_normalize(slot.perceive.knownPos - myPos, hullFwd) - let angDeg = acos(clamp(dot(toTgt, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG - if angDeg > slot.spec.yawLimitDeg * 0.78 - slot.nav.stuckCheckAt = -100.0 - wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM) - return - // Turreted tanks (and aligned TDs) hold the chassis still so the barrel settles cleanly. - wto_nav_halt(myPos, hullFwd, slot) +def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool + let state = slot.tactics.state + if state != WTO_STATE_MARCH && state != WTO_STATE_RUN_AND_GUN && state != WTO_STATE_PREAIM && state != WTO_STATE_SHORT_HALT + return false + if !slot.fire.hullAimTarget || slot.fire.hullAimTarget != slot.perceive.targetEid || slot.tactics.immobilized + return false + if wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) == WTO_DRIVE_HALT + return false + slot.nav.stuckCheckAt = -100.0 + let direction = wto_xz_normalize(slot.fire.hullAimDir, hullFwd) + wto_drive_cmd_set(slot.driveCmd, WTO_DRIVE_PIVOT, myPos, direction, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) + return true [never_inline] def private wto_nav_hull_angle(myPos, hullFwd : float3; var slot : WtoBotSlot&) @@ -185,8 +189,10 @@ def public wto_nav_update(var world : WtoWorldSnap&; navState, slotIdx : int; no if st == WTO_STATE_HULL_ANGLE wto_nav_hull_angle(myPos, hullFwd, slot) return + if wto_try_hull_aim(myPos, hullFwd, slot) + return if st == WTO_STATE_SHORT_HALT || st == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 - wto_handle_stationary_engage(myPos, hullFwd, slot) + wto_nav_halt(myPos, hullFwd, slot) return if wto_nav_tactical_reverse(navState, myPos, hullFwd, slot) || wto_unstick_reversing(now, myPos, slot) return diff --git a/game-ai/ground/wto_ai_runtime.das b/game-ai/ground/wto_ai_runtime.das index c4912f6..d5f3309 100644 --- a/game-ai/ground/wto_ai_runtime.das +++ b/game-ai/ground/wto_ai_runtime.das @@ -53,8 +53,12 @@ var private g_fire_budget : int = 0 var private g_next_diag_at : float = 0.0 var private @safe_when_uninitialized g_navmesh : WtoNavmeshBattle +// Custom ground AI must only run inside a real multiplayer battle. Single-player test +// drives also dispatch tag=server ECS, but their target vehicles must never be taken over. def private wto_any_layer_active() : bool - return WTO_AI_ENABLED && (WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL) + if !WTO_AI_ENABLED || !get_app().isMultiplayerGame + return false + return WTO_AI_LAYER_MACRO || WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_NAVIGATION || WTO_AI_LAYER_FIRE_CONTROL [init] def wto_ai_script_init() @@ -263,11 +267,11 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) + wto_fire_update(g_world, unit, unit__className, now, act.dt, slot, g_fire_budget) // A failed pack with navEngine.allowFallback off leaves every bot standing for the battle. if now >= slot.nextNavAt && g_navmesh.state != WTO_NAVMESH_FAILED slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC wto_nav_update(g_world, g_navmesh.state, idx, now, unit.pos, unit.unitTm[0], slot) - wto_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget) [es(tag=server, after=wto_ai_pipeline_es)] def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; diff --git a/game-ai/ground/wto_ai_specs_common.das b/game-ai/ground/wto_ai_specs_common.das index b7e9339..f132497 100644 --- a/game-ai/ground/wto_ai_specs_common.das +++ b/game-ai/ground/wto_ai_specs_common.das @@ -1,6 +1,6 @@ // Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per -// spawned bot (`gamedata/units/.blk`) to extract exact role, gun stabilizer, -// traverse limits, turret slew rates, shell muzzle velocity, and reverse speed capability. +// spawned bot (`gamedata/units/.blk`) to extract role, gun stabilizer, +// turret slew rates, shell muzzle velocity, and chassis capabilities. options indenting = 2 options no_global_heap = true module wto_ai_specs_common shared @@ -19,6 +19,7 @@ require %game.utils.utils_common require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_traverse_common [never_inline] def private wto_parse_role_strings(unitType : string; expClass : string; isLightTag : bool) : int @@ -32,40 +33,6 @@ def private wto_parse_role_strings(unitType : string; expClass : string; isLight return WTO_ROLE_LIGHT return WTO_ROLE_MEDIUM -[never_inline] -def private wto_parse_turret_limits(turretBlk : DataBlock const?; var spec : WtoVehicleSpec&) - if turretBlk == null - return - let lim1 = *turretBlk |> datablock_getPoint4("lim1", float4(0.0, 0.0, 0.0, 0.0)) - let lim2 = *turretBlk |> datablock_getPoint4("lim2", float4(0.0, 0.0, 0.0, 0.0)) - var maxAbsYaw = 0.0 - var minPitch = 0.0 - var maxPitch = 0.0 - if abs(lim1.x) > 0.1 || abs(lim1.y) > 0.1 - maxAbsYaw = max(maxAbsYaw, max(abs(lim1.x), abs(lim1.y))) - minPitch = min(minPitch, lim1.z) - maxPitch = max(maxPitch, lim1.w) - if abs(lim2.x) > 0.1 || abs(lim2.y) > 0.1 - maxAbsYaw = max(maxAbsYaw, max(abs(lim2.x), abs(lim2.y))) - minPitch = min(minPitch, lim2.z) - maxPitch = max(maxPitch, lim2.w) - let limitsBlk = *turretBlk |> datablock_get_block_by_name("limits") - if limitsBlk != null - let yawRange = *limitsBlk |> datablock_getPoint2("yaw", float2(0.0, 0.0)) - let pitchRange = *limitsBlk |> datablock_getPoint2("pitch", float2(0.0, 0.0)) - if abs(yawRange.x) > 0.1 || abs(yawRange.y) > 0.1 - maxAbsYaw = max(maxAbsYaw, max(abs(yawRange.x), abs(yawRange.y))) - if pitchRange.x < -0.1 || pitchRange.y > 0.1 - minPitch = min(minPitch, pitchRange.x) - maxPitch = max(maxPitch, pitchRange.y) - if maxAbsYaw > 0.5 - spec.yawLimitDeg = clamp(maxAbsYaw, 4.0, 180.0) - spec.isLimitedTraverse = spec.yawLimitDeg < 75.0 - if minPitch < -0.5 - spec.minPitchDeg = clamp(minPitch, -25.0, -2.0) - if maxPitch > 1.0 - spec.maxPitchDeg = clamp(maxPitch, 8.0, 88.0) - [never_inline] def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicleSpec&; isDefault : bool) let spd = bBlk |> datablock_getReal("speed", 0.0) @@ -122,7 +89,7 @@ def private wto_parse_weapon_blk(weapBlkPath : string; var spec : WtoVehicleSpec def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : WtoVehicleSpec&) : bool if empty(className) return false - let relPath = find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk") + let relPath = wto_unit_model_path(className) var loaded = false datablock_load_cached(relPath, DataBlockReadFlag.ROBUST) <| $(mBlk) if mBlk.paramCount == 0u && mBlk.blockCount == 0u @@ -137,6 +104,11 @@ def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : spec.vMaxFwd = clamp(fwdKmh / 3.6, 4.0, 28.0) if revKmh > 1.0 spec.vMaxRev = clamp(revKmh / 3.6, 1.0, 16.0) + let physBlk = mBlk |> datablock_get_block_by_name("VehiclePhys") + if physBlk != null + let mechanics = *physBlk |> datablock_get_block_by_name("mechanics") + if mechanics != null + spec.canPivot = (*mechanics |> datablock_getReal("neutralGearRatio", 0.0)) > 0.0 let commonBlk = mBlk |> datablock_get_block_by_name("commonWeapons") if commonBlk == null return @@ -156,7 +128,6 @@ def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer") if stabBlk != null spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false) - wto_parse_turret_limits(weapBlk |> datablock_get_block_by_name("turret"), spec) wto_parse_weapon_blk(wPath, spec) return loaded @@ -182,11 +153,8 @@ def private wto_apply_runtime_fallbacks(unit : Unit const?; gm : IGroundModel co elif as_gun(weapon) != null gunCount++ spec.isPureLauncher = gunCount == 0 && launcherCount > 0 - if length(unit.weap.turret) == 0 && gunCount > 0 - spec.isLimitedTraverse = true - spec.yawLimitDeg = min(spec.yawLimitDeg, 12.0) if !blkLoaded - if spec.isLimitedTraverse + if length(unit.weap.turret) == 0 && gunCount > 0 spec.role = WTO_ROLE_TD elif isLightTag spec.role = WTO_ROLE_LIGHT diff --git a/game-ai/ground/wto_ai_tactics_common.das b/game-ai/ground/wto_ai_tactics_common.das index 6e684c0..53db140 100644 --- a/game-ai/ground/wto_ai_tactics_common.das +++ b/game-ai/ground/wto_ai_tactics_common.das @@ -140,8 +140,7 @@ def private wto_sm_handle_combat(world : WtoWorldSnap const&; now : float; let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0 let canHalt = now >= tac.shortHaltCooldownUntil && !tac.repositionActive && wto_sm_stop_range_allowed(distXZ, slot) - let aimReady = (fc.gunReady && fc.aimTargetEid == slot.perceive.targetEid && - (fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG || slot.spec.isLimitedTraverse)) + let aimReady = (fc.gunReady && fc.aimTargetEid == slot.perceive.targetEid && fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG) if marchSpd > 0.0 && (close || (distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush)) if wto_sm_waited_for_moving_shot(now, aimReady, slot) && canHalt wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "moving_shot_halt", distXZ, slot) diff --git a/game-ai/ground/wto_ai_traverse_common.das b/game-ai/ground/wto_ai_traverse_common.das new file mode 100644 index 0000000..e24d3a6 --- /dev/null +++ b/game-ai/ground/wto_ai_traverse_common.das @@ -0,0 +1,202 @@ +// Mechanical angles of the selected ground weapon, read from the original mount definition. +options indenting = 2 +options no_global_heap = true +module wto_ai_traverse_common shared + +require ecs +require app +require math +require strings +require DagorMath +require DagorDataBlock +require Unit +require Weapon +require %game.utils.utils_common +require %appGame.wtoai.wto_ai_config_common +require %appGame.wtoai.wto_ai_math_common +require %appGame.wtoai.wto_ai_types_common +require %appGame.wtoai.wto_ai_combat_types_common + +// The engine's weapon trigger parser maps "gunnerN" to N + 0x13. +let private WTO_FIRST_GUNNER_TRIGGER = int(0x13) + +def public wto_unit_model_path(className : string) : string + return find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk") + +def private wto_valid_angle_range(angles : float2) : bool + return wto_is_finite(angles.x) && wto_is_finite(angles.y) && angles.x <= angles.y + +[never_inline] +def private wto_read_gunner_mount(className : string; triggerNo, weaponIndex : int; + readMount : block<(mount : DataBlock) : void>) + if empty(className) || triggerNo < WTO_FIRST_GUNNER_TRIGGER || weaponIndex < 0 + return + let trigger = "gunner{triggerNo - WTO_FIRST_GUNNER_TRIGGER}" + datablock_load_cached(wto_unit_model_path(className), DataBlockReadFlag.ROBUST) <| $(unitBlk) + let common = unitBlk |> datablock_get_block_by_name("commonWeapons") + if common == null + return + var index = 0 + datablock_for_each_block(*common, "Weapon") <| $(mount) + if (mount |> datablock_getStr("trigger", "")) != trigger + return + if index == weaponIndex && (mount |> datablock_getStr("triggerGroup", "primary")) == "primary" + invoke(readMount, mount) + index++ + +[never_inline] +def private wto_load_gun_traverse(className : string; triggerNo, weaponIndex : int; var traverse : WtoGunTraverse&) + traverse = WtoGunTraverse() + wto_read_gunner_mount(className, triggerNo, weaponIndex) <| $(mount) + let limits = mount |> datablock_get_block_by_name("limits") + if limits == null + return + let yaw = *limits |> datablock_getPoint2("yaw", float2(1.0, 0.0)) + if !wto_valid_angle_range(yaw) || abs(yaw.x) > 360.0 || abs(yaw.y) > 360.0 + return + traverse.known = true + traverse.yaw = yaw + let pitch = *limits |> datablock_getPoint2("pitch", float2(1.0, 0.0)) + if wto_valid_angle_range(pitch) + traverse.pitch = pitch + let sectors = mount |> datablock_get_block_by_name("limitsTable") + traverse.hasPitchTable = sectors != null && sectors.paramCount > 0u + +def private wto_full_gun_traverse(yaw : float2) : bool + return yaw.y - yaw.x >= 360.0 + +def private wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float + let center = (arc.x + arc.y) * 0.5 + return center + wto_wrap_deg(yaw - center) + +[never_inline] +def private wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float; + var traverse : WtoGunTraverse&) : float2 + if !traverse.hasPitchTable + return traverse.pitch + if yaw >= traverse.pitchSector.x && yaw < traverse.pitchSector.y + return float2(traverse.pitchSector.z, traverse.pitchSector.w) + var sector = float4(traverse.yaw.x, traverse.yaw.y, traverse.pitch.x, traverse.pitch.y) + wto_read_gunner_mount(className, triggerNo, weaponIndex) <| $(mount) + let sectors = mount |> datablock_get_block_by_name("limitsTable") + if sectors == null + return + // A DataBlock can repeat a parameter name. Read each sector by its original index. + for index in 0u..sectors.paramCount + if (*sectors |> datablock_getParamType(index)) != int(DataBlockParamType.TYPE_POINT4) + continue + let entry = *sectors |> datablock_getPoint4(int(index)) + if !wto_valid_angle_range(float2(entry.x, entry.y)) || !wto_valid_angle_range(float2(entry.z, entry.w)) + continue + if yaw < entry.x + sector.y = min(sector.y, entry.x) + elif yaw > entry.y + sector.x = max(sector.x, entry.y) + else + sector = entry + break + traverse.pitchSector = sector + return float2(sector.z, sector.w) + +[never_inline] +def public wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3; + var outYawDeg, outPitchDeg : float&) + let len = length(worldDir) + if !wto_is_finite3(worldDir) || len < 1.0e-5 + outYawDeg = 0.0 + outPitchDeg = 0.0 + return + let d = worldDir / len + let f = dot(d, hullFwd) + let u = dot(d, hullUp) + let l = dot(d, hullLeft) + let horiz = sqrt(f * f + l * l) + outYawDeg = horiz > 1.0e-5 ? (-atan2(l, f) * WTO_RAD_TO_DEG) : 0.0 + outPitchDeg = atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG + +[never_inline] +def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3 + let yr = yawDeg * WTO_DEG_TO_RAD + let pr = pitchDeg * WTO_DEG_TO_RAD + let cp = cos(pr) + let dir = hullFwd * (cp * cos(yr)) - hullLeft * (cp * sin(yr)) + hullUp * sin(pr) + let l = length(dir) + return l > 1.0e-5 ? (dir / l) : hullFwd + +def private wto_step_mounted_yaw(current, desired, step : float; arc : float2) : float + if wto_full_gun_traverse(arc) + return wto_wrap_deg(current + clamp(wto_wrap_deg(desired - current), -step, step)) + let clampedCurrent = clamp(wto_yaw_in_mount_coordinates(current, arc), arc.x, arc.y) + let clampedTarget = clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y) + return clamp(clampedCurrent + clamp(clampedTarget - clampedCurrent, -step, step), arc.x, arc.y) + +def private wto_track_blocked_pitch(wishPitchDeg, dtStep : float; var slot : WtoBotSlot&) + assume fc = slot.fire + let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep + fc.prevPitchDeg = fc.curPitchDeg + if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8 + fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep) + fc.pitchBlocked = fc.pitchClampSec >= 0.75 + else + fc.pitchClampSec = max(0.0, fc.pitchClampSec - dtStep * 2.5) + if fc.pitchClampSec <= 0.05 + fc.pitchBlocked = false + +[never_inline] +def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : float; + wishYawDeg, wishPitchDeg : float; var slot : WtoBotSlot&) + assume fc = slot.fire + let dtStep = clamp(dt, 0.005, 0.12) + if fc.traverseTurretNo != fc.turretNo + fc.traverseTurretNo = fc.turretNo + fc.traverse = WtoGunTraverse() + fc.servoInit = false + fc.pitchBlocked = false + fc.pitchClampSec = 0.0 + for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret + if tIdx != fc.turretNo + continue + let triggerNo = int(turret.triggerNo) + let weaponIndex = int(turret.weaponIndex) + if !fc.servoInit + wto_load_gun_traverse(className, triggerNo, weaponIndex, fc.traverse) + fc.prevPitchDeg = turret.currentState.pitch + fc.servoInit = true + fc.curYawDeg = turret.currentState.yaw + fc.curPitchDeg = turret.currentState.pitch + if !fc.traverse.known + return + wto_track_blocked_pitch(wishPitchDeg, dtStep, slot) + let yaw = fc.traverse.yaw + let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep + let cmdYaw = wto_step_mounted_yaw(fc.curYawDeg, wishYawDeg, maxYawStep, yaw) + let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep + let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, fc.traverse) + turret.yawLim = cmdYaw + if pitch.x <= pitch.y + let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep) + turret.pitchLim = clamp(fc.curPitchDeg + pitchDelta, pitch.x, pitch.y) + break + if fc.traverse.known + var uPos = unit.pos + updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos) + +def public wto_set_hull_aim(unit : Unit const?; active : bool; wishYaw : float; liveBarrelDir : float3; + var slot : WtoBotSlot&) + assume fc = slot.fire + var target = INVALID_ENTITY_ID + if active + var arc = fc.traverse.yaw + if !fc.traverse.known + var fixedYaw, pitch : float + wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, pitch) + arc = float2(fixedYaw, fixedYaw) + let aimYaw = wto_yaw_in_mount_coordinates(wishYaw, arc) + let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0 + if !wto_full_gun_traverse(arc) && (aimYaw < arc.x - tolerance || aimYaw > arc.y + tolerance) + target = slot.perceive.targetEid + let yawToTurn = wto_wrap_deg(wishYaw - (arc.x + arc.y) * 0.5) + fc.hullAimDir = wto_hull_deg_to_world(yawToTurn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2]) + if target != fc.hullAimTarget + slot.nextNavAt = 0.0 + fc.hullAimTarget = target diff --git a/game-ai/ground/wto_ai_types_common.das b/game-ai/ground/wto_ai_types_common.das index ca95f11..d5ea123 100644 --- a/game-ai/ground/wto_ai_types_common.das +++ b/game-ai/ground/wto_ai_types_common.das @@ -45,10 +45,6 @@ struct public WtoVehicleSpec ready : bool = false role : int = 0 hasVertStab : bool = false - isLimitedTraverse : bool = false - yawLimitDeg : float = 180.0 - minPitchDeg : float = -8.0 - maxPitchDeg : float = 22.0 turretYawSpd : float = 24.0 turretPitchSpd : float = 8.0 muzzleSpeedMps : float = 880.0 diff --git a/mod-dev-docs/en/01-quick-start.md b/mod-dev-docs/en/01-quick-start.md index 28d6287..4fd5cfe 100644 --- a/mod-dev-docs/en/01-quick-start.md +++ b/mod-dev-docs/en/01-quick-start.md @@ -141,6 +141,7 @@ Manifest parsing enforces **strict whitelist validation**: typos or unknown keys | `conflicts` | No | `string[]` | Mutually incompatible mod IDs; enabling both raises a **blocking error** | | `load_after` | No | `string[]` | Optional mods this mod should load after (lower in the list = higher priority); does not require them to be enabled, and participates in order hints & **Auto-Sort** | | `load_before` | No | `string[]` | Optional mods this mod should load before; also participates in order hints & **Auto-Sort** | +| `tech_tree_insertions` | No | `{ vehicle: string, after: string, before: string }[]` | Inserts vehicles into an existing research link in mod load order. [Example](02-client-packs-and-blk.md#63-inserting-vehicles-into-the-same-research-link) | | `server` | No | `{ entry?: string, tuning?: string }` | Explicit relative paths (no `..`) overriding default auto-detection of `server/index.{ts,mjs,js}` and `server/tuning` | --- diff --git a/mod-dev-docs/en/02-client-packs-and-blk.md b/mod-dev-docs/en/02-client-packs-and-blk.md index eb979cf..018b4a3 100644 --- a/mod-dev-docs/en/02-client-packs-and-blk.md +++ b/mod-dev-docs/en/02-client-packs-and-blk.md @@ -328,7 +328,7 @@ Keep three rules in mind when writing `shop.blk.patch.blk` (or `.patch.jsonc`): 2. **Collapsible folder groups (`*_group`)**: when multiple variants share one tech-tree folder, `range` contains a child block ending in `_group` (e.g. `us_sherman_group`) whose children are the grouped vehicles; the folder's display label comes from `shop/group/` in `units.csv`; 3. **Why is the prerequisite arrow field named `reqAir` even on tanks and ships?** War Thunder began life as an aviation-only game (*World of Planes*), so `air` / `aircraft` remained the universal internal noun for any unit. Consequently, **`reqAir` defines the research prerequisite vehicle across tanks, helicopters, aircraft, and ships alike**! - - Setting `reqAir:t="us_m2a4"` in `wpcost.blk` requires owning `us_m2a4` before researching the unit; + - With `reqAir:t="us_m2a4"` in `wpcost.blk`, completing research on `us_m2a4` unlocks research on this vehicle. Buying this vehicle requires owning `us_m2a4`. - Inside a `range` column in `shop.blk`: consecutive vehicles with no `reqAir` property automatically connect with vertical arrows; `reqAir:t="us_m2a4"` draws an explicit arrow from `us_m2a4`; and **`reqAir:t=""` (empty string) explicitly breaks the arrow from the vehicle above it** (used at mid-column gaps and throughout the right-hand premium/pack columns). ### 6.2 All 4 `lang/units.csv` Keys & Incremental CSV Merging @@ -357,6 +357,20 @@ Example `client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`: --- +### 6.3 Inserting Vehicles into the Same Research Link + +Supply the vehicle definition and its `wpcost.blk` entry, then declare the research link in `mod.jsonc`. In 2.61.0.64, the F-15C MSIP II follows the F-15A. + +```jsonc +"tech_tree_insertions": [ + { "vehicle": "my_fighter", "after": "f_15a", "before": "f_15c_msip2" } +] +``` + +- `vehicle` is the mod vehicle ID. `after` and `before` are the existing predecessor and successor IDs. The builder checks that `before` requires `after` in `wpcost.blk` after the ordinary overlays. When migrating a manual insertion, remove the successor's manual `reqAir` edits so the builder can handle the link. +- Use regular vehicles from the same nation and branch, with ranks in nondecreasing order. The builder creates a shop entry or reuses one already declared on the same page. An insertion between members of a folder goes inside that folder. An insertion across columns goes in the successor's column. +- Multiple mods targeting the same link compose `A → X → Y → B` in the launcher's top-to-bottom order. Reordering or toggling mods rebuilds the chain from stock and the current selection. A missing anchor, a changed link, or a cycle produces a build error naming the mod and vehicles. + ## 7. Patching Root `config.blk` (`client/config-blk.patch.blk` / `.jsonc`) If your mod needs to adjust the client root `config.blk` (for example enabling sound mods via `sound{ enable_mod:b=yes }` or setting a custom hangar `hangarBlk:t="..."`), place a BLK patch at `client/config-blk.patch.blk` (recommended; `client/config-blk.patch.jsonc` is also supported): diff --git a/mod-dev-docs/zh-CN/01-quick-start.md b/mod-dev-docs/zh-CN/01-quick-start.md index f29e087..e22ec58 100644 --- a/mod-dev-docs/zh-CN/01-quick-start.md +++ b/mod-dev-docs/zh-CN/01-quick-start.md @@ -141,6 +141,7 @@ console.log(formatBlkText(decodeBlk(getFile(ar, 'config/wpcost.blk'), { names: a | `conflicts` | 否 | `string[]` | 已知互斥模组 ID 列表;同时启用时作为**阻塞错误**阻止启动 | | `load_after` | 否 | `string[]` | 建议排在这些可选模组 ID 之后(越靠下越晚加载、优先级越高);不强制要求对方启用,若同时启用则参与顺序提示与「按依赖自动排序」 | | `load_before` | 否 | `string[]` | 建议排在这些可选模组 ID 之前;同样参与顺序提示与「按依赖自动排序」 | +| `tech_tree_insertions` | 否 | `{ vehicle: string, after: string, before: string }[]` | 按加载顺序把新载具插进指定的研发关系。 [写法](02-client-packs-and-blk.md#63-多个模组插入同一段研发线) | | `server` | 否 | `{ entry?: string, tuning?: string }` | 显式覆盖服务端入口文件(相对路径,不得含 `..`)和 `tuning` 目录路径(默认自动探测 `server/index.{ts,mjs,js}` 与 `server/tuning`) | --- diff --git a/mod-dev-docs/zh-CN/02-client-packs-and-blk.md b/mod-dev-docs/zh-CN/02-client-packs-and-blk.md index 87a2a9d..55ff886 100644 --- a/mod-dev-docs/zh-CN/02-client-packs-and-blk.md +++ b/mod-dev-docs/zh-CN/02-client-packs-and-blk.md @@ -328,7 +328,7 @@ country_usa (或 country_germany / country_ussr / country_britain / country_japa 2. **折叠文件夹(`*_group`)**:当同一格折叠了多辆同系载具时,`range` 下会放一个以 `_group` 结尾的子块(例如 `us_sherman_group`),里面再嵌套各辆具体载具子块,折叠封面标题来自 `units.csv` 的 `shop/group/<组名>`; 3. **为什么坦克和军舰的前置研发箭头也叫 `reqAir`?** 因为《战争雷霆》最早立项时是纯空战游戏(*World of Planes*),所有载具在底层代码里都沿用了 `air` / `aircraft` 命名,因此**无论是坦克、直升机还是战列舰,指定“上一辆前置研发载具”的字段一律叫 `reqAir`**! - - 在 `wpcost.blk` 中设置 `reqAir:t="us_m2a4"`:声明玩家必须先拥有 `us_m2a4` 才能研发本车; + - 在 `wpcost.blk` 中设置 `reqAir:t="us_m2a4"`:研发完 `us_m2a4` 才能研发本车,购买本车前须拥有 `us_m2a4`; - 在 `shop.blk` 的同一 `range` 列中:连续排列且未写 `reqAir` 的两辆车默认自动画纵向实线箭头;写 `reqAir:t="us_m2a4"` 会显式从 `us_m2a4` 连出箭头;而写 **`reqAir:t=""`(空字符串)则会显式断开与上方载具的箭头连接**(科技树断线处以及右侧金币/礼包列里的车都用 `reqAir:t=""`)。 ### 6.2 `lang/units.csv` 的 4 个载具译名后缀与 CSV 增量合并 @@ -357,6 +357,20 @@ CSV 补丁文件写法示例(`client/packs/lang.vromfs.bin/lang/units.csv.patc --- +### 6.3 多个模组插入同一段研发线 + +给新载具准备好游戏定义和 `wpcost.blk` 条目,在 `mod.jsonc` 加上要插入的研发关系。例如 2.61.0.64 中,F-15C MSIP II 的前置是 F-15A。 + +```jsonc +"tech_tree_insertions": [ + { "vehicle": "my_fighter", "after": "f_15a", "before": "f_15c_msip2" } +] +``` + +- `vehicle` 是模组载具 ID。`after`、`before` 是已有的前置和后继 ID。构建器在普通补丁叠加后核对 `before` 的 `reqAir` 是否指向 `after`。从手工接线迁移时,把后继载具对 `reqAir` 的手工覆写删掉,让构建器处理这条关系。 +- 锚点和新载具须为同一国家、同一兵种的常规载具,沿线大等级按顺序递增或相等。构建器可以创建 `shop.blk` 格子,也会复用你已经在同一页声明的格子。插入折叠组内的两个成员之间时,新车进入该组。跨列时,新车在后继载具所在列。 +- 多个模组声明同一段时,按启动器列表从上到下接成 `A → X → Y → B`。重新排序或调整启用项后,下次构建会从原版和当前模组重新接线。找不到锚点、原连接被改写或组合成循环时,构建错误会指出模组和载具。 + ## 7. 修改游戏根目录 `config.blk`(`client/config-blk.patch.blk` / `.jsonc`) 如果模组需要调整游戏根目录的 `config.blk`(例如开启音效模组开关 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份 BLK 补丁到 `client/config-blk.patch.blk`(推荐,同样兼容 `client/config-blk.patch.jsonc`)即可: diff --git a/native/wto-net/build.ps1 b/native/wto-net/build.ps1 index 79c979d..2138e2d 100644 --- a/native/wto-net/build.ps1 +++ b/native/wto-net/build.ps1 @@ -31,7 +31,7 @@ function Quote($paths) { $paths | ForEach-Object { '"' + (Resolve-Path $_) + '"' $sources = Quote @( "$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_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", + "$src\local_mp_damage_notifications.c", "$src\local_mp_hit_feedback.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", "$src\local_mp_captures.c", "$src\local_mp_air_ai_sync.c", "$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" ) diff --git a/native/wto-net/src/local_mp_air_ai_sync.c b/native/wto-net/src/local_mp_air_ai_sync.c new file mode 100644 index 0000000..0879459 --- /dev/null +++ b/native/wto-net/src/local_mp_air_ai_sync.c @@ -0,0 +1,48 @@ +/* + * Thread synchronization for the shared air-AI `unsortedPlanes` vector on a LocalMP host. + * + * Aircraft physics and AI updates run across worker threads via `threadpool::parallel_for` + * (2.61.0.60: 0x373e51 -> 0x39f5d0 -> 0xdf52b0 -> 0xe48740 -> 0xe42db0 -> 0x31a23e0 -> + * 0xdb07e0 -> 0x7fba00). When a bot plane finishes its behavior tree, AirAi::update tail-calls + * TeamAiManager::addToUnsortedPlanes (0x8007b0 -> 0x80a150 on 2.61.0.60). That function locks + * the global unit table while resolving the unit, then mutates the team's shared + * `unsortedPlanes` dag::Vector (including reserve/HeapReAlloc) without any lock. + * + * Online clients skip this path (isHost == 0), and retail matches rarely run 31 bot aircraft on + * one host. In LocalMP air battles, multiple same-team bots finishing tasks right after an + * aircraft crash race on the vector and corrupt the Windows heap (0xC0000374). + * + * Wrapping the function with an exclusive SRWLOCK on LocalMP hosts keeps parallel physics intact + * while serializing mutations of `unsortedPlanes`. The target performs no callbacks or re-entrant + * calls and acquires only the global unit-table lock after ours, so lock ordering is fixed. + */ +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_values.h" + +typedef void (__fastcall *AddUnsortedPlaneFn)(void *team_mgr, uint32_t unit_no); + +static AddUnsortedPlaneFn orig_add_unsorted_plane; +static SRWLOCK g_unsorted_planes_lock = SRWLOCK_INIT; + +static void __fastcall hook_add_unsorted_plane(void *team_mgr, uint32_t unit_no) +{ + if (!local_mp_is_host()) { + orig_add_unsorted_plane(team_mgr, unit_no); + return; + } + AcquireSRWLockExclusive(&g_unsorted_planes_lock); + orig_add_unsorted_plane(team_mgr, unit_no); + ReleaseSRWLockExclusive(&g_unsorted_planes_lock); +} + +int install_local_mp_air_ai_sync_hooks(void) +{ + const LocalMpHookSpec hook = { + "air_ai_add_unsorted_plane", + g_lmp.air_ai_add_unsorted_plane, + (void *)&hook_add_unsorted_plane, + (void **)&orig_add_unsorted_plane, + }; + return local_mp_queue_hooks("local_mp_air_ai_sync", &hook, 1); +} diff --git a/native/wto-net/src/local_mp_awards.c b/native/wto-net/src/local_mp_awards.c index a82c1cc..c3919ce 100644 --- a/native/wto-net/src/local_mp_awards.c +++ b/native/wto-net/src/local_mp_awards.c @@ -58,7 +58,13 @@ const char *local_mp_unit_exp_class(const uint8_t *unit) return (exp_class != NULL && exp_class[0] != '\0') ? exp_class : NULL; } -void local_mp_report_award_event(const LocalMpAwardEvent *ev) +static const char *bare_unit_name(const char *unit_name) +{ + const char *slash = strrchr(unit_name, '/'); + return (slash != NULL && slash[1] != '\0') ? slash + 1 : unit_name; +} + +static void report_award_event(const LocalMpAwardEvent *ev, const char *source_unit) { __declspec(align(16)) uint8_t blk[LMP_BLK_SIZE]; uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL; @@ -72,6 +78,8 @@ void local_mp_report_award_event(const LocalMpAwardEvent *ev) fn_blk_set_str(blk, "expClass", victim_class ? victim_class : ""); fn_blk_set_str(blk, "victim", victim_name ? victim_name : ""); fn_blk_set_str(blk, "messageModifier", ev->modifier ? ev->modifier : ""); + if (source_unit != NULL) + fn_blk_set_str(blk, "unit", bare_unit_name(source_unit)); blk_set_int(blk, "messageCode", (int32_t)ev->exp_event); blk_set_int(blk, "victimIsPlayer", ev->victim_is_player ? 1 : 0); blk_set_int(blk, "friendly", ev->friendly ? 1 : 0); @@ -80,6 +88,17 @@ void local_mp_report_award_event(const LocalMpAwardEvent *ev) fn_blk_dtor(blk); } +void local_mp_report_award_event(const LocalMpAwardEvent *ev) +{ + report_award_event(ev, NULL); +} + +void local_mp_report_capture(const char *unit_name) +{ + const LocalMpAwardEvent award = { LMP_EXP_EVENT_CAPTURE_ZONE, NULL, 0, 0, NULL, 0 }; + report_award_event(&award, unit_name); +} + /* The fact behind the award killStreak_bomber_nuclear_success, which online the battle server * judges itself; the event carries no fields. */ void local_mp_report_nuclear_strike(void) @@ -114,12 +133,11 @@ void local_mp_report_backup_spawn(const char *unit_name, int32_t slot_id, const { __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) return; memset(blk, 0, sizeof(blk)); fn_blk_ctor(blk); - fn_blk_set_str(blk, "unit", unit_name); + fn_blk_set_str(blk, "unit", bare_unit_name(unit_name)); fn_blk_set_str(blk, "backup", backup); blk_set_int(blk, "slot", slot_id); fn_hud_notify_script(gsd + LMP_GSD_OFF_HUD_QUEUE, "wtoLocalMpBackupSpawn", blk); diff --git a/native/wto-net/src/local_mp_captures.c b/native/wto-net/src/local_mp_captures.c new file mode 100644 index 0000000..49c52c5 --- /dev/null +++ b/native/wto-net/src/local_mp_captures.c @@ -0,0 +1,108 @@ +/* Credit completed captures using the mission engine's own unit eligibility checks. */ +#include "hook_config.h" +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include +#include + +typedef void (__fastcall *SetZoneOwnerFn)(uint8_t *zone, int32_t team); +typedef float (__fastcall *TeamCapturePowerFn)(int32_t team, uint8_t *zone, int32_t *count); +typedef float (__fastcall *UnitCapturePowerFn)(uint8_t *zone, const uint8_t *unit); + +typedef struct CaptureAward { + uint8_t *player; + const char *unit_name; + float power; + float score; +} CaptureAward; + +typedef struct CaptureScan { + const uint8_t *zone; + int32_t team; + CaptureAward awards[UINT8_MAX + 1]; +} CaptureScan; + +static __declspec(thread) CaptureScan *active_scan; +static SetZoneOwnerFn original_set_owner; +static UnitCapturePowerFn original_unit_power; +static uintptr_t cta_end; + +static float __fastcall hook_unit_power(uint8_t *zone, const uint8_t *unit) +{ + float power = original_unit_power(zone, unit); + CaptureScan *scan = active_scan; + if (scan == NULL || scan->zone != zone || unit == NULL || !(power > 0.0f)) + return power; + + uint8_t *player = *(uint8_t *const *)(unit + LMP_UNIT_OFF_MPLAYER); + if (player == NULL || player[LMP_MP_OFF_TEAM] != scan->team) + return power; + + CaptureAward *award = &scan->awards[player[LMP_MP_OFF_PID]]; + if (power > award->power) { + award->player = player; + award->unit_name = local_mp_unit_name(unit); + award->power = power; + award->score = local_mp_event_score("capture", unit, 1); + } + return power; +} + +static int is_capture_completion(uintptr_t return_address) +{ + return return_address == (uintptr_t)g_lmp.capture_complete_call + LMP_REL32_CALL_SIZE || + (return_address >= (uintptr_t)g_lmp.capture_cta_logic && return_address < cta_end); +} + +static void credit_capture(const CaptureAward *award) +{ + uint8_t *player = award->player; + local_mp_inc_mplayer_stat(player, LMP_MP_OFF_CAPTURE_ZONE); + local_mp_add_personal_score(player, award->score, LMP_EXP_EVENT_CAPTURE_ZONE); + local_mp_mark_mplayer_dirty(player); + if (local_mp_is_local_mplayer(player)) + local_mp_report_capture(award->unit_name); +} + +static void __fastcall hook_set_owner(uint8_t *zone, int32_t team) +{ + if (!local_mp_is_host() || !is_capture_completion((uintptr_t)_ReturnAddress()) || + (team != 1 && team != 2) || zone[g_lmp.capture_owner] == team) { + original_set_owner(zone, team); + return; + } + + /* Run the same side's eligibility walk immediately before the ownership commit. A player + can have several eligible units in that walk, so credit their strongest one once. */ + CaptureScan scan = { .zone = zone, .team = team }; + CaptureScan *previous = active_scan; + int32_t count = 0; + active_scan = &scan; + ((TeamCapturePowerFn)g_lmp.capture_team_power)(team, zone, &count); + active_scan = previous; + + original_set_owner(zone, team); + if (zone[g_lmp.capture_owner] != team) + return; + for (size_t pid = 0; pid < sizeof(scan.awards) / sizeof(scan.awards[0]); ++pid) { + if (scan.awards[pid].player != NULL) + credit_capture(&scan.awards[pid]); + } +} + +int install_local_mp_capture_hooks(void) +{ + DWORD64 base; + const RUNTIME_FUNCTION *cta = RtlLookupFunctionEntry((DWORD64)g_lmp.capture_cta_logic, &base, NULL); + if (cta == NULL || g_lmp.capture_complete_set_owner != g_lmp.capture_set_owner) { + log_line("local_mp: local_mp_captures skipped: inconsistent ownership call sites"); + return 0; + } + cta_end = (uintptr_t)(base + cta->EndAddress); + const LocalMpHookSpec hooks[] = { + { "capture_set_owner", g_lmp.capture_set_owner, (void *)&hook_set_owner, (void **)&original_set_owner }, + { "capture_unit_power", g_lmp.capture_unit_power, (void *)&hook_unit_power, (void **)&original_unit_power }, + }; + return local_mp_queue_hooks("local_mp_captures", hooks, sizeof(hooks) / sizeof(hooks[0])); +} diff --git a/native/wto-net/src/local_mp_core.c b/native/wto-net/src/local_mp_core.c index 8b47fba..93d3b9e 100644 --- a/native/wto-net/src/local_mp_core.c +++ b/native/wto-net/src/local_mp_core.c @@ -139,12 +139,15 @@ static const LocalMpModule MODULES[] = { { "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_captures", install_local_mp_capture_hooks }, { "local_mp_zones", install_local_mp_zone_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_hit_feedback", install_local_mp_hit_feedback_hooks }, { "local_mp_air_events", install_local_mp_air_event_hooks }, { "local_mp_ground_ai", install_local_mp_ground_ai_hooks }, + { "local_mp_air_ai_sync", install_local_mp_air_ai_sync_hooks }, }; static void use_core_values(void) diff --git a/native/wto-net/src/local_mp_damage_notifications.c b/native/wto-net/src/local_mp_damage_notifications.c index cab1823..0302a4d 100644 --- a/native/wto-net/src/local_mp_damage_notifications.c +++ b/native/wto-net/src/local_mp_damage_notifications.c @@ -56,6 +56,7 @@ static int suppressed_avionics_logged; static int suppressed_optic_logged; static int suppressed_parts_logged; static int suppressed_enemy_mpi_logged; +static int damage_hooks_queued; static const uint8_t *local_mplayer(void) { @@ -99,17 +100,29 @@ static const uint8_t *watched_unit(const uint8_t *mplayer) } /* The owner check also covers projectiles fired before switching to a support vehicle. */ -static int is_local_enemy_hit(const uint8_t *attacker, const uint8_t *victim) +int local_mp_is_view_hit(const uint8_t *attacker, const uint8_t *victim) { const uint8_t *mplayer = local_mplayer(); if (attacker == NULL || attacker == victim || mplayer == NULL) return 0; - if (victim[LMP_UNIT_OFF_ARMY] != 0 && victim[LMP_UNIT_OFF_ARMY] == attacker[LMP_UNIT_OFF_ARMY]) + + const uint8_t *owner = owning_mplayer(attacker); + if (owner != NULL && owner == owning_mplayer(victim)) return 0; - return owning_mplayer(attacker) == mplayer || attacker == controlled_unit(mplayer) + return owner == mplayer || attacker == controlled_unit(mplayer) || attacker == watched_unit(mplayer); } +int local_mp_has_enemy_hit_feedback(void) +{ + return active_hit_victim != NULL; +} + +int local_mp_damage_notifications_ready(void) +{ + return damage_hooks_queued; +} + static uint8_t __fastcall hook_barrel_damage(void *damage, const uint8_t *impact) { /* The stock handler resolves the reference before it emits the notice and tags it in bit 0. */ @@ -202,7 +215,9 @@ static uint64_t __fastcall hook_unit_on_event(void *unit, const uint8_t *event, if (unit != NULL && event != NULL && local_mp_is_host() && *(const uint16_t *)(event + g_lmp.mpi_msg_id_off) == LMP_MPI_MSG_HIT_FEEDBACK) { const uint8_t *attacker = *(const uint8_t *const *)(event + g_lmp.hit_event_offender); - if (is_local_enemy_hit(attacker, unit)) + const uint8_t *victim = unit; + if (local_mp_is_view_hit(attacker, victim) && + (victim[LMP_UNIT_OFF_ARMY] == 0 || victim[LMP_UNIT_OFF_ARMY] != attacker[LMP_UNIT_OFF_ARMY])) active_hit_victim = unit; } result = original_unit_on_event(unit, event, arg3, arg4); @@ -288,5 +303,6 @@ int install_local_mp_damage_notification_hooks(void) log_line("local_mp: local_mp_damage_notifications skipped: barrel and breech deliver addresses differ"); return 0; } - return local_mp_queue_hooks("local_mp_damage_notifications", hooks, sizeof(hooks) / sizeof(hooks[0])); + damage_hooks_queued = local_mp_queue_hooks("local_mp_damage_notifications", hooks, sizeof(hooks) / sizeof(hooks[0])); + return damage_hooks_queued; } diff --git a/native/wto-net/src/local_mp_events.c b/native/wto-net/src/local_mp_events.c index 2777b47..b230ab3 100644 --- a/native/wto-net/src/local_mp_events.c +++ b/native/wto-net/src/local_mp_events.c @@ -1,6 +1,6 @@ /* * LocalMP non-fatal combat event dispatchers: deduplicated assists across air/ground/naval, - * zone captures, hit results, severe damage, and naval damage awards. + * hit results, severe damage, and naval damage awards. * * `IGroundModel::onBecameDead` calls both `IGroundModel::awardAssists` (`0x465540`) and * `Unit::awardAssists` (`0xe5b200` -> `dispatchAssist` `0x35beb0`); deduplicating `(victim, mp)` @@ -27,7 +27,6 @@ typedef struct AssistDedupRecord { typedef void (__fastcall *IGroundAwardAssistsFn)(uint8_t *victim); typedef void (__fastcall *DispatchAssistFn)(int64_t uid, uint8_t *victim, uint8_t *offender, float share, int32_t extra); -typedef void (__fastcall *DispatchCaptureZoneFn)(int64_t uid, uint8_t *capturer_unit); typedef void (__fastcall *DispatchHitFn)( int64_t uid, uint8_t *victim, uint8_t *offender, float dmg, uint8_t repeat_flush, uint8_t effective_hit, uint8_t extra); typedef void (__fastcall *DispatchSevereDamageFn)(int64_t uid, uint8_t *victim, uint8_t *offender); @@ -35,7 +34,6 @@ typedef void (__fastcall *DispatchNavalDamageFn)(int64_t uid, uint8_t *victim, u static IGroundAwardAssistsFn orig_iground_award_assists; static DispatchAssistFn orig_dispatch_assist; -static DispatchCaptureZoneFn orig_dispatch_capture_zone; static DispatchHitFn orig_dispatch_hit; static DispatchSevereDamageFn orig_dispatch_severe_damage; static DispatchNavalDamageFn orig_dispatch_naval_damage; @@ -135,27 +133,6 @@ static void __fastcall hook_dispatch_assist(int64_t uid, uint8_t *victim, uint8_ orig_dispatch_assist(uid, victim, offender, share, extra); } -static void __fastcall hook_dispatch_capture_zone(int64_t uid, uint8_t *capturer_unit) -{ - if (local_mp_is_host()) { - uint8_t *mp = local_mp_find_mplayer(uid, 0xffu); - if (mp == NULL && capturer_unit != NULL) - mp = *(uint8_t **)(capturer_unit + LMP_UNIT_OFF_MPLAYER); - if (mp != NULL) { - const uint8_t *own_unit = capturer_unit != NULL ? capturer_unit - : (g_lmp_get_unit_by_eid ? (const uint8_t *)g_lmp_get_unit_by_eid(*(uint32_t *)(mp + LMP_MP_OFF_UNIT_EID)) : NULL); - local_mp_inc_mplayer_stat(mp, LMP_MP_OFF_CAPTURE_ZONE); - local_mp_add_mplayer_score(mp, local_mp_event_score("capture", own_unit, 1), LMP_EXP_EVENT_CAPTURE_ZONE); - local_mp_mark_mplayer_dirty(mp); - if (local_mp_is_local_mplayer(mp)) { - LocalMpAwardEvent award = { LMP_EXP_EVENT_CAPTURE_ZONE, NULL, 0, 0, NULL, 0 }; - local_mp_report_award_event(&award); - } - } - } - orig_dispatch_capture_zone(uid, capturer_unit); -} - /* * Unit::flushOffenderHitAward passes a repeat marker and an effective-hit flag. Its stock * single-player path (.58 0xffd369) selects HIT / INEFFECTIVE_HIT from that same flag. The @@ -240,7 +217,6 @@ int install_local_mp_event_hooks(void) 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", g_lmp.dispatch_hit, (void *)&hook_dispatch_hit, (void **)&orig_dispatch_hit }, { "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 }, diff --git a/native/wto-net/src/local_mp_hit_feedback.c b/native/wto-net/src/local_mp_hit_feedback.c new file mode 100644 index 0000000..d215f6d --- /dev/null +++ b/native/wto-net/src/local_mp_hit_feedback.c @@ -0,0 +1,63 @@ +/* Validate recipient ownership at the two outgoing hit-feedback dispatch points. */ +#include "local_mp_internal.h" +#include "local_mp_offsets.h" + +#include + +typedef void (__fastcall *SendScriptNetEventFn)(void *manager, uint8_t broadcast, uint32_t destination, + const void *event, const char *event_name, const void *recipient_args, const void *recipient_filter); +typedef void (__fastcall *NotifyHudScriptFn)(void *hud, int32_t event_id, const void *data); + +/* The CmdShowHitMark unicast constructor writes 0x0001001c6c52bfea followed by its victim EID. + * The stock sender handles event destruction when its flags require it. This event is plain data. */ +typedef struct HitMarkEvent { + uint32_t type; + uint16_t size; + uint16_t flags; + uint32_t victim; +} HitMarkEvent; + +enum { HIT_MARK_EVENT_TYPE = 0x6c52bfea, HIT_MARK_EVENT_SIZE = 0x1c, ECS_EVENT_UNICAST = 1 }; +enum { HUD_HINT_CHANGE_SHELL_TYPE = 0xc5 }; + +static SendScriptNetEventFn original_send_script_event; +static NotifyHudScriptFn original_notify_hud_script; + +static int should_drop_hit_mark(uint8_t broadcast, uint32_t destination, const HitMarkEvent *event) +{ + if (event == NULL || event->type != HIT_MARK_EVENT_TYPE || event->size != HIT_MARK_EVENT_SIZE || + event->flags != ECS_EVENT_UNICAST || broadcast || !local_mp_is_host()) + return 0; + + const uint8_t *attacker = g_lmp_get_unit_by_eid(destination); + const uint8_t *victim = g_lmp_get_unit_by_eid(event->victim); + return !local_mp_is_view_hit(attacker, victim); +} + +static void __fastcall hook_send_script_event(void *manager, uint8_t broadcast, uint32_t destination, + const void *event, const char *event_name, const void *recipient_args, const void *recipient_filter) +{ + if (!should_drop_hit_mark(broadcast, destination, event)) + original_send_script_event(manager, broadcast, destination, event, event_name, recipient_args, recipient_filter); +} + +static void __fastcall hook_notify_hud_script(void *hud, int32_t event_id, const void *data) +{ + if (event_id == HUD_HINT_CHANGE_SHELL_TYPE && + (uintptr_t)_ReturnAddress() == (uintptr_t)g_lmp.hit_shell_hint_call + LMP_REL32_CALL_SIZE && + local_mp_is_host() && !local_mp_has_enemy_hit_feedback()) + return; + original_notify_hud_script(hud, event_id, data); +} + +int install_local_mp_hit_feedback_hooks(void) +{ + if (!local_mp_damage_notifications_ready()) + return 0; + + const LocalMpHookSpec hooks[] = { + { "send_script_net_event", g_lmp.hit_mark_send, (void *)&hook_send_script_event, (void **)&original_send_script_event }, + { "notify_shell_hint", g_lmp.hit_shell_hint_notify, (void *)&hook_notify_hud_script, (void **)&original_notify_hud_script }, + }; + return local_mp_queue_hooks("local_mp_hit_feedback", hooks, sizeof(hooks) / sizeof(hooks[0])); +} diff --git a/native/wto-net/src/local_mp_internal.h b/native/wto-net/src/local_mp_internal.h index fba5627..aaf1f32 100644 --- a/native/wto-net/src/local_mp_internal.h +++ b/native/wto-net/src/local_mp_internal.h @@ -62,6 +62,7 @@ void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t b /* 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_capture(const char *unit_name); void local_mp_report_nuclear_strike(void); void local_mp_report_airfield_spawn(const char *unit_name, int32_t base_id); void local_mp_report_backup_spawn(const char *unit_name, int32_t slot_id, const char *backup); @@ -103,15 +104,21 @@ int install_local_mp_action_hooks(void); int install_local_mp_award_hooks(void); int install_local_mp_kill_hooks(void); int install_local_mp_event_hooks(void); +int install_local_mp_capture_hooks(void); 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_hit_feedback_hooks(void); +int local_mp_damage_notifications_ready(void); +int local_mp_is_view_hit(const uint8_t *attacker, const uint8_t *victim); +int local_mp_has_enemy_hit_feedback(void); int install_local_mp_zone_hooks(void); void local_mp_zones_reset(void); int install_local_mp_air_event_hooks(void); int install_local_mp_ground_ai_hooks(void); void local_mp_ground_ai_update(float dt); +int install_local_mp_air_ai_sync_hooks(void); /* "wtoNav" requests of the ground AI script and the battle's navigation pack (local_mp_nav.c). */ void local_mp_nav_request(void *blk); diff --git a/native/wto-net/src/local_mp_kills.c b/native/wto-net/src/local_mp_kills.c index b6259b4..3ced280 100644 --- a/native/wto-net/src/local_mp_kills.c +++ b/native/wto-net/src/local_mp_kills.c @@ -147,9 +147,12 @@ static void process_unit_death(uint8_t *victim, uint8_t *killer_mp, int32_t kill } } +/* Stack buffer for Unit::chooseOffender; stock writes 0x124 bytes on 2.61.0.37/.58/.60. */ +#define LMP_OFFENDER_BUF_SIZE 0x180u + static uint8_t *resolve_offender_killer(uint8_t *victim, int32_t *out_army) { - __declspec(align(16)) uint8_t offender[0x180]; + __declspec(align(16)) uint8_t offender[LMP_OFFENDER_BUF_SIZE]; uintptr_t vtbl = victim ? *(uintptr_t *)victim : 0; ChooseOffenderVfn choose_fn; @@ -209,6 +212,11 @@ int install_local_mp_kill_hooks(void) { "on_unit_dead_once", g_lmp.on_unit_dead_once, (void *)&hook_on_unit_dead_once, (void **)&orig_on_unit_dead_once }, }; + if (LMP_OFFENDER_STRIDE > LMP_OFFENDER_BUF_SIZE) { + log_line("local_mp: Offender stride 0x%zx exceeds the 0x%x-byte stack buffer", + LMP_OFFENDER_STRIDE, LMP_OFFENDER_BUF_SIZE); + return 0; + } fn_mplayer_add_score = (MPlayerAddScoreFn)g_lmp.mplayer_add_score; fn_net_mark_dirty = (NetMarkDirtyFn)g_lmp.net_mark_dirty; diff --git a/native/wto-net/src/local_mp_offsets.h b/native/wto-net/src/local_mp_offsets.h index 7532513..857ed03 100644 --- a/native/wto-net/src/local_mp_offsets.h +++ b/native/wto-net/src/local_mp_offsets.h @@ -15,6 +15,8 @@ #include "local_mp_values.h" +#define LMP_REL32_CALL_SIZE (1 + sizeof(int32_t)) /* x64 E8 + signed displacement */ + #define LMP_GUI_STATE_PILOT_CONTROL 2 #define LMP_GUI_STATE_CA_SELECT 6 #define LMP_GUI_STATE_CA_READY 8 diff --git a/native/wto-net/src/local_mp_players.c b/native/wto-net/src/local_mp_players.c index fc82a55..cd2d26c 100644 --- a/native/wto-net/src/local_mp_players.c +++ b/native/wto-net/src/local_mp_players.c @@ -244,7 +244,8 @@ static uint8_t __fastcall hook_is_slot_ready_at_host(int32_t slot_id, const char mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL; if (mplayer == NULL) return 1; - return (*(uint32_t *)(mplayer + LMP_MP_OFF_BROKEN_SLOTS_MASK) & (1u << (uint32_t)slot_id)) == 0 ? 1 : 0; + /* Allow broken slots whose backup has not been used yet; isCrewAvailableInSession enforces backup eligibility. */ + return (*(uint32_t *)(mplayer + LMP_MP_OFF_USED_SPARES_MASK) & (1u << (uint32_t)slot_id)) == 0 ? 1 : 0; } int install_local_mp_player_hooks(void) diff --git a/native/wto-net/src/local_mp_values.c b/native/wto-net/src/local_mp_values.c index 2fd244a..15afa69 100644 --- a/native/wto-net/src/local_mp_values.c +++ b/native/wto-net/src/local_mp_values.c @@ -37,12 +37,15 @@ typedef struct LmpValueSpec { #define SCORES "local_mp_scores" #define KILLS "local_mp_kills" #define EVENTS "local_mp_events" +#define CAPTURES "local_mp_captures" #define ZONES "local_mp_zones" #define NUKE "local_mp_nuke" #define SUPPORT "local_mp_support" #define DAMAGE_NOTICES "local_mp_damage_notifications" +#define HIT_FEEDBACK "local_mp_hit_feedback" #define AIR_EVENTS "local_mp_air_events" #define GROUND_AI "local_mp_ground_ai" +#define AIR_AI_SYNC "local_mp_air_ai_sync" static const LmpValueSpec SPECS[] = { A(ZONES, "apply_zone_damage", apply_zone_damage), @@ -137,10 +140,16 @@ static const LmpValueSpec SPECS[] = { O(KILLS, "stat_award_damage.field", mp_award_damage), O(KILLS, "stat_air_severe.field", mp_air_severe_dmg), O(KILLS, "stat_ship_severe.field", mp_ship_severe_dmg), - A(EVENTS, "dispatch_assist", dispatch_assist), A(EVENTS, "caller_capture_zone.call", dispatch_capture_zone), + A(EVENTS, "dispatch_assist", dispatch_assist), A(EVENTS, "caller_hit_crit.call", dispatch_hit), A(EVENTS, "caller_severe_damage.call", dispatch_severe_damage), A(EVENTS, "caller_naval_damage.call", dispatch_naval_damage), O(EVENTS, "offender_assist.assist_sent", offender_assist_sent), + A(CAPTURES, "capture_cta_logic", capture_cta_logic), + A(CAPTURES, "capture_set_owner", capture_set_owner), O(CAPTURES, "capture_set_owner.owner", capture_owner), + A(CAPTURES, "capture_complete_call", capture_complete_call), + A(CAPTURES, "capture_complete_call.set_owner", capture_complete_set_owner), + A(CAPTURES, "capture_team_power", capture_team_power), A(CAPTURES, "capture_unit_power_call.function", capture_unit_power), + A(NUKE, "shell_launch", shell_launch), A(NUKE, "shell_explode", shell_explode), A(NUKE, "cta_logic_action", cta_logic_action), O(NUKE, "shell_instant_win.record", shell_launch_record), O(NUKE, "shell_instant_win.instant_win", shell_rec_instant_win), O(NUKE, "mission_vars_data.data", mission_vars_data), O(NUKE, "mission_vars_walk.count", mission_vars_count), @@ -171,6 +180,10 @@ static const LmpValueSpec SPECS[] = { O(DAMAGE_NOTICES, "enemy_part_damage_mpi.msg_id", enemy_part_dmg_mpi_id), O(DAMAGE_NOTICES, "enemy_part_hit_mpi.msg_id", enemy_part_hit_mpi_id), + A(HIT_FEEDBACK, "hit_mark_send.send", hit_mark_send), + A(HIT_FEEDBACK, "hit_shell_hint_call", hit_shell_hint_call), + A(HIT_FEEDBACK, "hit_shell_hint_call.notify", hit_shell_hint_notify), + O(AIR_EVENTS, "mission_mode_name.mode_name", mis_mode_name), A(AIR_EVENTS, "prepare_local_mission", prepare_local_mission), A(AIR_EVENTS, "prepare_local_mission_clear.use_kill_streaks", use_kill_streaks), @@ -200,6 +213,8 @@ static const LmpValueSpec SPECS[] = { A(GROUND_AI, "ground_ai_drive_to_pos_update", ground_ai_drive_to_pos_update), O(GROUND_AI, "ground_ai_move_properties.move_system", ground_ai_move_system), O(GROUND_AI, "ground_ai_move_annotation.inactive", ground_ai_move_inactive), + + A(AIR_AI_SYNC, "air_ai_add_unsorted_plane", air_ai_add_unsorted_plane), }; static void store(const LmpValueSpec *spec, int64_t value, uint8_t *base) diff --git a/native/wto-net/src/local_mp_values.h b/native/wto-net/src/local_mp_values.h index 2c79ad3..f6a0bf6 100644 --- a/native/wto-net/src/local_mp_values.h +++ b/native/wto-net/src/local_mp_values.h @@ -61,9 +61,14 @@ typedef struct LmpValues { size_t mp_award_damage, mp_air_severe_dmg, mp_ship_severe_dmg; /* local_mp_events */ - uint8_t *dispatch_assist, *dispatch_capture_zone, *dispatch_hit, *dispatch_severe_damage, *dispatch_naval_damage; + uint8_t *dispatch_assist, *dispatch_hit, *dispatch_severe_damage, *dispatch_naval_damage; size_t offender_assist_sent; + /* local_mp_captures */ + uint8_t *capture_cta_logic, *capture_set_owner, *capture_complete_call, *capture_complete_set_owner; + uint8_t *capture_team_power, *capture_unit_power; + size_t capture_owner; + /* local_mp_nuke */ uint8_t *shell_launch, *shell_explode, *cta_logic_action; size_t shell_launch_record, shell_rec_instant_win, mission_vars_data, mission_vars_count, mission_var_stride; @@ -82,6 +87,9 @@ typedef struct LmpValues { size_t barrel_unit_ref, breech_unit, barrel_notice_id, breech_notice_id, avionics_unit, hit_event_offender; size_t mpi_msg_id_off, enemy_part_dmg_mpi_id, enemy_part_hit_mpi_id; + /* local_mp_hit_feedback */ + uint8_t *hit_mark_send, *hit_shell_hint_call, *hit_shell_hint_notify; + /* local_mp_zones */ uint8_t *apply_zone_damage; size_t zone_health, zone_max_health, zone_team, zone_flags, zone_airfield_mask; @@ -95,6 +103,8 @@ typedef struct LmpValues { /* local_mp_ground_ai */ uint8_t *ground_ai_mission_action, *ground_ai_as_ground_model, *ground_ai_drive_to_pos_update; size_t ground_ai_move_system, ground_ai_move_inactive; + /* local_mp_air_ai_sync */ + uint8_t *air_ai_add_unsorted_plane; } LmpValues; extern LmpValues g_lmp; diff --git a/package-lock.json b/package-lock.json index bc7e563..877165f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,7 @@ }, "apps/launcher": { "name": "@wto/launcher", - "version": "0.1.4", + "version": "0.1.5", "dependencies": { "@fontsource/roboto-condensed": "^5.3.0", "@wto/mods": "*", diff --git a/packages/mods/src/discovery.ts b/packages/mods/src/discovery.ts index 422f99b..f62d20a 100644 --- a/packages/mods/src/discovery.ts +++ b/packages/mods/src/discovery.ts @@ -109,7 +109,8 @@ export function inspectModContent(rootDir: string, manifest: ModManifest): ModCo : undefined; const badges = computeRiskBadges({ - hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined, + hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 + || configBlkPatch !== undefined || !!manifest.techTreeInsertions?.length, hasGui: guiPatchDirs.length > 0, hasScript: serverEntry !== undefined, hasExe: exePatchDirs.length > 0, @@ -270,6 +271,7 @@ export function touchedClientPacks(mods: readonly DiscoveredMod[]): ModdableClie const set = new Set(); for (const mod of mods) { for (const op of mod.content.packOperations) set.add(op.pack); + if (mod.manifest.techTreeInsertions?.length) set.add('char.vromfs.bin'); if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin'); if (mod.content.hasClientAddon) set.add('aces.vromfs.bin'); } diff --git a/packages/mods/src/index.ts b/packages/mods/src/index.ts index c2eb7f5..67ce4f2 100644 --- a/packages/mods/src/index.ts +++ b/packages/mods/src/index.ts @@ -22,6 +22,7 @@ export { type ModPreset, type ModRiskBadge, type ModServerConfig, + type ModTechTreeInsertion, type ModdableClientPack, type PackFileAction, type ResolvedModLoadOrder, diff --git a/packages/mods/src/manifest.ts b/packages/mods/src/manifest.ts index d521e07..3397d81 100644 --- a/packages/mods/src/manifest.ts +++ b/packages/mods/src/manifest.ts @@ -4,7 +4,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { parseJsonc } from '@wto/jsonc'; -import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig } from './types.ts'; +import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig, type ModTechTreeInsertion } from './types.ts'; export const MOD_MANIFEST_FILE = 'mod.jsonc'; @@ -22,9 +22,11 @@ const ALLOWED_ROOT_KEYS = new Set([ 'conflicts', 'load_after', 'load_before', + 'tech_tree_insertions', 'server', ]); const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']); +const TECH_TREE_INSERTION_KEYS = new Set(['vehicle', 'after', 'before']); export class ModManifestError extends Error { override name = 'ModManifestError'; @@ -62,6 +64,7 @@ export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModMa const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id); const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id); const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id); + const techTreeInsertions = parseTechTreeInsertions(obj.tech_tree_insertions, `${where} "tech_tree_insertions"`); const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`); return { @@ -77,10 +80,31 @@ export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModMa conflicts, loadAfter, loadBefore, + ...(techTreeInsertions.length > 0 ? { techTreeInsertions } : {}), ...(server !== undefined ? { server } : {}), }; } +function parseTechTreeInsertions(raw: unknown, where: string): ModTechTreeInsertion[] { + if (raw === undefined) return []; + if (!Array.isArray(raw)) throw new ModManifestError(`${where}: expected an array`); + const seen = new Set(); + return raw.map((item, index) => { + const location = `${where}[${index}]`; + const value = expectObject(item, location); + rejectUnknownKeys(value, TECH_TREE_INSERTION_KEYS, location); + const vehicle = expectString(value.vehicle, `${location}.vehicle`); + const after = expectString(value.after, `${location}.after`); + const before = expectString(value.before, `${location}.before`); + if (new Set([vehicle, after, before]).size !== 3) { + throw new ModManifestError(`${location}: vehicle, after, and before must be different vehicles`); + } + if (seen.has(vehicle)) throw new ModManifestError(`${location}: duplicate insertion for "${vehicle}"`); + seen.add(vehicle); + return { vehicle, after, before }; + }); +} + function parseServerConfig(raw: unknown, where: string): ModServerConfig { const obj = expectObject(raw, where); rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where); diff --git a/packages/mods/src/types.ts b/packages/mods/src/types.ts index 85463d4..35737d4 100644 --- a/packages/mods/src/types.ts +++ b/packages/mods/src/types.ts @@ -33,6 +33,12 @@ export interface ModServerConfig { readonly tuning?: string; } +export interface ModTechTreeInsertion { + readonly vehicle: string; + readonly after: string; + readonly before: string; +} + export interface ModManifest { readonly format: 1; readonly id: string; @@ -46,6 +52,7 @@ export interface ModManifest { readonly conflicts: readonly string[]; readonly loadAfter: readonly string[]; readonly loadBefore: readonly string[]; + readonly techTreeInsertions?: readonly ModTechTreeInsertion[]; readonly server?: ModServerConfig; } diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index de01a2f..a072794 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -61,6 +61,10 @@ export interface GameCopyInputs { readonly placeholderDecals: boolean; /** Real dldata/downloadable_decals.blk and downloadable_skins.blk extracted from the player's cache. */ readonly decalIndexFiles?: readonly AddedFile[]; + /** Optional player decal cache folder used to filter cached .ddsx textures when embedding indexes. */ + readonly decalCache?: string; + /** Optional pre-scanned set of cached .ddsx relative paths ("/.ddsx", lowercased). */ + readonly cachedDdsx?: ReadonlySet; /** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */ readonly hookLogging?: boolean; /** Ordered list of enabled additive mods to overlay onto this build. */ @@ -194,6 +198,8 @@ function buildCorePacks( const { pack: coreCharPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, { placeholderDecals: inputs.placeholderDecals, ...(inputs.decalIndexFiles ? { decalIndexFiles: inputs.decalIndexFiles } : {}), + ...(inputs.decalCache ? { decalCache: inputs.decalCache } : {}), + ...(inputs.cachedDdsx ? { cachedDdsx: inputs.cachedDdsx } : {}), localRegistration, }); const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods); diff --git a/packages/patcher/src/char-pack.ts b/packages/patcher/src/char-pack.ts index 883f0df..8fe6a40 100644 --- a/packages/patcher/src/char-pack.ts +++ b/packages/patcher/src/char-pack.ts @@ -4,7 +4,19 @@ * tech tree (config/shop.blk), and, unless the player gave a decal source, placeholder decal * and skin indexes (decals/offline-decal-index.ts). */ -import { DECALS_CONFIG_PATH, offlineDecalIndex } from './decals/offline-decal-index.ts'; +import { decodeBlk, emptyBlock, encodeBlk } from '@wto/blk'; +import { + DECALS_CONFIG_PATH, + DECALS_INDEX_PATH, + mergePlayerDecalIndex, + offlineDecalIndex, + SKINS_INDEX_PATH, +} from './decals/offline-decal-index.ts'; +import { + filterPlayerDecalIndexFiles, + readPlayerDecalIndexFiles, + scanCachedDdsxFiles, +} from './decals/player-decal-cache.ts'; import { enableFeaturesForEveryone, GAME_SETTINGS_PATH, OFFLINE_FEATURES } from './features/offline-features.ts'; import type { LocalEndpoint } from './network/local-endpoint.ts'; import { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts'; @@ -20,8 +32,12 @@ export interface CharPackResult { readonly features: readonly string[]; /** Vehicles that were hidden from players who had not researched or bought them. */ readonly revealedVehicles: number; - /** Decals in the placeholder index; undefined when the player's own decal cache is used. */ + /** Decals using placeholder textures; undefined when a legacy web cache supplies its own index. */ readonly placeholderDecals: number | undefined; + /** Decals resolved from locally cached .ddsx textures; undefined unless a player index is merged. */ + readonly cachedDecals?: number; + /** Downloadable skins resolved from locally cached .ddsx textures; undefined unless a player index is merged. */ + readonly cachedSkins?: number; } export interface CharPackOptions { @@ -29,22 +45,84 @@ export interface CharPackOptions { readonly placeholderDecals: boolean; /** Real dldata/downloadable_decals.blk and downloadable_skins.blk extracted from the player's cache. */ readonly decalIndexFiles?: readonly AddedFile[]; + /** Optional player decal cache folder (cache/content, cache, or imported snapshot) used to filter cached .ddsx files. */ + readonly decalCache?: string; + /** Optional pre-scanned set of cached .ddsx relative paths ("/.ddsx", lowercased). */ + readonly cachedDdsx?: ReadonlySet; readonly localRegistration: boolean; } +interface DecalOverlay { + readonly files: readonly AddedFile[]; + readonly placeholderDecals: number | undefined; + readonly cachedDecals?: number; + readonly cachedSkins?: number; +} + export function rebuildCharPack(stockPack: Uint8Array, endpoint: LocalEndpoint, options: CharPackOptions): CharPackResult { let network: NetworkRedirectReport | undefined; let features: string[] = []; let revealedVehicles = 0; - const usePlayerIndex = (options.decalIndexFiles?.length ?? 0) > 0; - const decals = !usePlayerIndex && options.placeholderDecals - ? offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH)) - : undefined; - const addedFiles = usePlayerIndex ? options.decalIndexFiles! : (decals?.files ?? []); + const decals = resolveDecalOverlay(stockPack, options); const pack = editPackBlks(stockPack, [ { path: NETWORK_CONFIG_PATH, edit: (root) => { network = redirectNetworkConfig(root, endpoint, options.localRegistration); } }, { path: GAME_SETTINGS_PATH, edit: (root) => { features = enableFeaturesForEveryone(root, OFFLINE_FEATURES); } }, { path: SHOP_PATH, edit: (root) => { revealedVehicles = revealHiddenVehicles(root); } }, - ], addedFiles); - return { pack, network: network!, features, revealedVehicles, placeholderDecals: decals?.decals }; + ], decals.files); + return { + pack, + network: network!, + features, + revealedVehicles, + placeholderDecals: decals.placeholderDecals, + ...(decals.cachedDecals !== undefined ? { cachedDecals: decals.cachedDecals } : {}), + ...(decals.cachedSkins !== undefined ? { cachedSkins: decals.cachedSkins } : {}), + }; +} + +function resolveDecalOverlay(stockPack: Uint8Array, options: CharPackOptions): DecalOverlay { + const playerIndexFiles = resolvePlayerIndexFiles(options); + if (playerIndexFiles !== undefined && playerIndexFiles.length > 0) { + const decalsConfig = readPackBlk(stockPack, DECALS_CONFIG_PATH); + const decalsFile = playerIndexFiles.find((file) => file.path === DECALS_INDEX_PATH); + const skinsFile = playerIndexFiles.find((file) => file.path === SKINS_INDEX_PATH); + const otherFiles = playerIndexFiles.filter((file) => file.path !== DECALS_INDEX_PATH && file.path !== SKINS_INDEX_PATH); + const merged = mergePlayerDecalIndex( + decalsConfig, + decalsFile ? decodeBlk(decalsFile.content) : emptyBlock(), + ); + const skinsContent = skinsFile ? skinsFile.content : encodeBlk(emptyBlock()); + const cachedSkins = skinsFile ? decodeBlk(skinsFile.content).blocks.length : 0; + return { + files: [ + { path: SKINS_INDEX_PATH, content: skinsContent }, + { path: DECALS_INDEX_PATH, content: merged.content }, + ...otherFiles, + ], + placeholderDecals: merged.placeholderDecals, + cachedDecals: merged.cachedDecals, + cachedSkins, + }; + } + if (options.placeholderDecals) { + const offline = offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH)); + return { files: offline.files, placeholderDecals: offline.decals }; + } + return { files: [], placeholderDecals: undefined }; +} + +function resolvePlayerIndexFiles(options: CharPackOptions): readonly AddedFile[] | undefined { + if (options.decalIndexFiles !== undefined) { + if (options.cachedDdsx !== undefined) { + return filterPlayerDecalIndexFiles(options.decalIndexFiles, options.cachedDdsx); + } + if (options.decalCache !== undefined) { + return filterPlayerDecalIndexFiles(options.decalIndexFiles, scanCachedDdsxFiles(options.decalCache)); + } + return options.decalIndexFiles; + } + if (options.decalCache !== undefined) { + return readPlayerDecalIndexFiles(options.decalCache); + } + return undefined; } diff --git a/packages/patcher/src/decals/offline-decal-index.ts b/packages/patcher/src/decals/offline-decal-index.ts index bd88c4b..3ece545 100644 --- a/packages/patcher/src/decals/offline-decal-index.ts +++ b/packages/patcher/src/decals/offline-decal-index.ts @@ -58,17 +58,35 @@ export interface OfflineDecalIndex { readonly decals: number; } +export interface MergedDecalIndex { + readonly index: BlkBlock; + readonly content: Uint8Array; + /** Total decals backed by locally cached .ddsx textures (stock + extra). */ + readonly cachedDecals: number; + /** Stock config/decals.blk entries resolved from cached .ddsx textures. */ + readonly cachedStockDecals: number; + /** Extra entries outside config/decals.blk kept because their .ddsx textures are cached. */ + readonly cachedExtraDecals: number; + /** Stock config/decals.blk entries that fell back to built-in placeholder textures. */ + readonly placeholderDecals: number; +} + +const SQUARE_PARAMS = textureParams(SQUARE_PLACEHOLDER); +const WIDE_PARAMS = textureParams(WIDE_PLACEHOLDER); + +export function placeholderDecalBlock(decal: BlkBlock): BlkBlock { + return { + name: decal.name, + params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? WIDE_PARAMS : SQUARE_PARAMS, + blocks: [], + }; +} + export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex { - const square = textureParams(SQUARE_PLACEHOLDER); - const wide = textureParams(WIDE_PLACEHOLDER); const index: BlkBlock = { name: '', params: [], - blocks: decalsConfig.blocks.map((decal) => ({ - name: decal.name, - params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? wide : square, - blocks: [], - })), + blocks: decalsConfig.blocks.map(placeholderDecalBlock), }; return { files: [ @@ -79,6 +97,64 @@ export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex { }; } +/** + * Merge a filtered player downloadable_decals.blk (containing only decals with locally cached + * .ddsx textures) with stock config/decals.blk: + * - Every stock decal present in cachedPlayerDecals keeps its real entry. + * - Every stock decal missing from cachedPlayerDecals falls back to a built-in placeholder + * texture (star/panther) so it never fails to load offline. + * - Extra decals outside config/decals.blk that survived cache filtering are appended. + */ +export function mergePlayerDecalIndex( + decalsConfig: BlkBlock, + cachedPlayerDecals: BlkBlock, +): MergedDecalIndex { + const cachedByName = new Map(); + for (const block of cachedPlayerDecals.blocks) { + cachedByName.set(block.name, block); + } + + const stockNames = new Set(); + const blocks: BlkBlock[] = []; + let cachedStockDecals = 0; + let placeholderDecals = 0; + + for (const decal of decalsConfig.blocks) { + stockNames.add(decal.name); + const cached = cachedByName.get(decal.name); + if (cached !== undefined) { + blocks.push(cached); + cachedStockDecals += 1; + } else { + blocks.push(placeholderDecalBlock(decal)); + placeholderDecals += 1; + } + } + + const emittedExtra = new Set(); + let cachedExtraDecals = 0; + for (const block of cachedPlayerDecals.blocks) { + if (stockNames.has(block.name) || emittedExtra.has(block.name)) continue; + emittedExtra.add(block.name); + blocks.push(block); + cachedExtraDecals += 1; + } + + const index: BlkBlock = { + name: '', + params: cachedPlayerDecals.params, + blocks, + }; + return { + index, + content: encodeBlk(index), + cachedDecals: cachedStockDecals + cachedExtraDecals, + cachedStockDecals, + cachedExtraDecals, + placeholderDecals, + }; +} + function aspectRatio(decal: BlkBlock): number { const value = decal.params.find((param) => param.name === 'aspect_ratio')?.value; return value?.type === 'real' && Number.isFinite(value.value) && value.value > 0 ? value.value : 1; diff --git a/packages/patcher/src/decals/player-decal-cache.ts b/packages/patcher/src/decals/player-decal-cache.ts index 8d1d50d..3a7afe3 100644 --- a/packages/patcher/src/decals/player-decal-cache.ts +++ b/packages/patcher/src/decals/player-decal-cache.ts @@ -1,25 +1,28 @@ /** * Decals and downloadable skins from the player's own online client: the player names the web - * cache folder of an installation they have played online with (/cache/content, or its - * parent /cache), and the build copies the cached textures into the game copy's - * cache/content. The offline version never looks for that folder itself. + * cache folder of an installation they have played online with (/cache/content, its parent + * /cache, or the game root ), and the build copies the cached textures into the game + * copy's cache/content. The offline version never looks for that folder itself. * * Two layouts exist across War Thunder builds (verified on 2.61.0.37 and 2.61.0.58): * 1. Modern vromfs-indexed cache (2.61+): cache/content/ holds dldata_s.info and the downloaded - * /.ddsx textures, while the decal and skin indexes (dldata/downloadable_decals.blk - * and dldata/downloadable_skins.blk) ship inside sibling cache/binary./regional.vromfs.bin - * (mounted by webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client - * reads the vromfs index first, it never writes downloadable_decals..blk into cache/content/. - * We extract both index BLKs into a self-contained snapshot (.wto-index/) on import and embed - * them into char.vromfs.bin during build so webdlcontent::init mounts cache/content/ (0xd3ca11) - * and loads the real hashes from vromfs without signature checks (0xd3cb6b). + * /.ddsx textures (where the first 2 characters of each base32 hash form the + * bucket directory and the remaining characters plus ".ddsx" form the filename), while the + * decal and skin indexes (dldata/downloadable_decals.blk and dldata/downloadable_skins.blk) + * ship inside sibling cache/binary./regional.vromfs.bin (mounted by + * webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client reads + * the vromfs index first, it never writes downloadable_decals..blk into cache/content/. + * We extract both raw index BLKs into a self-contained snapshot (.wto-index/) on import; when + * building char.vromfs.bin, we filter both indexes against the .ddsx files actually present + * in the cache (backfilling missing single-LOD references from the cached LOD) so uncached + * entries do not fail to load offline. * 2. Legacy webcache-indexed cache: cache/content/ holds dldata_s.info and signed * downloadable_decals..blk directly; char.vromfs.bin omits dldata/ so the client reads * the cached index from cache/content/. */ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'; import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'; -import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap } from '@wto/blk'; +import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap, type BlkBlock, type BlkParam } from '@wto/blk'; import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs'; import type { AddedFile } from '../pack-edit.ts'; import { compareVersions } from '../version-record.ts'; @@ -33,6 +36,9 @@ const REGIONAL_PACK_NAME = 'regional.vromfs.bin'; const SNAPSHOT_INDEX_DIR = '.wto-index'; const SNAPSHOT_DECALS_FILE = 'downloadable_decals.blk'; const SNAPSHOT_SKINS_FILE = 'downloadable_skins.blk'; +const DDSX_EXTENSION = '.ddsx'; +const LOD_PARAM = /^lod(\d+)$/; +const HDR_PARAM = /^hdr(\d+)$/; export interface PlayerDecalCache { readonly copiedTo: string; @@ -40,15 +46,16 @@ export interface PlayerDecalCache { } /** - * Resolve the actual cache/content folder when the player selects either /cache/content - * or its parent /cache folder. + * Resolve the actual cache/content folder when the player selects /cache/content, + * its parent /cache folder, or the game root . */ export function resolvePlayerDecalCacheFolder(source: string): string { if (!existsSync(source) || !statSync(source).isDirectory()) return source; if (directDecalCacheProblem(source) === undefined) return source; - const nested = join(source, 'content'); - if (existsSync(nested) && statSync(nested).isDirectory() && directDecalCacheProblem(nested) === undefined) { - return nested; + for (const candidate of [join(source, 'content'), join(source, WEB_CACHE_FOLDER)]) { + if (existsSync(candidate) && statSync(candidate).isDirectory() && directDecalCacheProblem(candidate) === undefined) { + return candidate; + } } return source; } @@ -60,27 +67,133 @@ export function playerDecalCacheProblem(source: string): string | undefined { } /** - * Read real dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into - * char.vromfs.bin when the cache uses either an imported snapshot index or a sibling - * binary./regional.vromfs.bin. Returns undefined for legacy downloadable_decals..blk - * caches, which supply their index directly inside cache/content/. + * Map a downloadable texture hash (e.g. "nhy6...cyii") to its cache-relative .ddsx path + * ("nh/y6...cyii.ddsx", lowercased). Returns undefined for non-hash values. */ -export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined { - const folder = resolvePlayerDecalCacheFolder(source); - const snapshot = readSnapshotIndexFiles(folder); - if (snapshot) return snapshot; - if (decalIndexes(folder).length > 0) return undefined; - const regional = findRegionalPack(folder); - if (!regional) return undefined; - return extractRegionalIndexFiles(regional); +export function ddsxPathForHash(hash: string): string | undefined { + const normalized = hash.trim().toLowerCase(); + if (normalized.length < 3 || normalized.includes('/') || normalized.includes('\\')) return undefined; + return `${normalized.slice(0, 2)}/${normalized.slice(2)}${DDSX_EXTENSION}`; } /** - * Persist extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent + * Scan a player decal cache folder (cache/content, its parent cache folder, the game root, or an + * imported snapshot) and collect the normalized relative paths ("/.ddsx", lowercased) + * of all cached .ddsx files, skipping .wto-index. + */ +export function scanCachedDdsxFiles(source: string): ReadonlySet { + const folder = resolvePlayerDecalCacheFolder(source); + const cached = new Set(); + if (!existsSync(folder) || !statSync(folder).isDirectory()) return cached; + for (const entry of readdirSync(folder, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue; + const bucket = entry.name.toLowerCase(); + if (bucket.length !== 2) continue; + const sub = join(folder, entry.name); + for (const child of readdirSync(sub, { withFileTypes: true })) { + if (!child.isFile()) continue; + const name = child.name.toLowerCase(); + if (name.endsWith(DDSX_EXTENSION)) cached.add(`${bucket}/${name}`); + } + } + return cached; +} + +/** + * Filter a downloadable_decals.blk root block to only decals with at least one cached LOD + * texture in cachedDdsx, backfilling any missing lodN/hdrN from the best cached LOD. + */ +export function filterDownloadableDecalsBlock( + decalsBlk: BlkBlock, + cachedDdsx: ReadonlySet, +): BlkBlock { + const blocks: BlkBlock[] = []; + for (const decal of decalsBlk.blocks) { + const normalized = normalizeTextureBlockLods(decal, cachedDdsx); + if (normalized !== undefined) blocks.push(normalized); + } + return { name: decalsBlk.name, params: decalsBlk.params, blocks }; +} + +/** + * Filter a downloadable_skins.blk root block to only skins whose texture entries all have at + * least one cached LOD texture in cachedDdsx, backfilling missing lodN (and hdrN if present) + * from the best cached LOD. + */ +export function filterDownloadableSkinsBlock( + skinsBlk: BlkBlock, + cachedDdsx: ReadonlySet, +): BlkBlock { + const blocks: BlkBlock[] = []; + for (const skin of skinsBlk.blocks) { + if (skin.blocks.length > 0) { + const nextChildren: BlkBlock[] = []; + let allCached = true; + let hasTextureChild = false; + for (const child of skin.blocks) { + if (hasLodParams(child)) { + hasTextureChild = true; + const normalized = normalizeTextureBlockLods(child, cachedDdsx); + if (normalized === undefined) { + allCached = false; + break; + } + nextChildren.push(normalized); + } else { + nextChildren.push(child); + } + } + if (allCached && hasTextureChild) { + blocks.push({ name: skin.name, params: skin.params, blocks: nextChildren }); + } + } else { + const normalized = normalizeTextureBlockLods(skin, cachedDdsx); + if (normalized !== undefined) blocks.push(normalized); + } + } + return { name: skinsBlk.name, params: skinsBlk.params, blocks }; +} + +/** + * Filter encoded dldata/downloadable_decals.blk and dldata/downloadable_skins.blk entries + * against the set of locally cached .ddsx relative paths. + */ +export function filterPlayerDecalIndexFiles( + files: readonly AddedFile[], + cachedDdsx: ReadonlySet, +): readonly AddedFile[] { + return files.map((file) => { + if (file.path === DECALS_INDEX_PATH) { + return { path: file.path, content: encodeBlk(filterDownloadableDecalsBlock(decodeBlk(file.content), cachedDdsx)) }; + } + if (file.path === SKINS_INDEX_PATH) { + return { path: file.path, content: encodeBlk(filterDownloadableSkinsBlock(decodeBlk(file.content), cachedDdsx)) }; + } + return file; + }); +} + +/** + * Read dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into + * char.vromfs.bin when the cache uses either an imported snapshot index or a sibling + * binary./regional.vromfs.bin, filtered to entries whose .ddsx textures actually exist in + * the cache folder (with single-LOD fallback). Returns undefined for legacy + * downloadable_decals..blk caches, which supply their index directly inside cache/content/. + */ +export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined { + const folder = resolvePlayerDecalCacheFolder(source); + const raw = readRawPlayerDecalIndexFiles(folder); + if (!raw) return undefined; + return filterPlayerDecalIndexFiles(raw, scanCachedDdsxFiles(folder)); +} + +/** + * Persist raw extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent * launches are completely self-contained and never touch the online client directory. */ export function writeDecalCacheIndexSnapshot(source: string, target: string): void { - const files = readPlayerDecalIndexFiles(source); + const folder = resolvePlayerDecalCacheFolder(source); + const files = readRawPlayerDecalIndexFiles(folder); if (!files) return; const indexDir = join(target, SNAPSHOT_INDEX_DIR); mkdirSync(indexDir, { recursive: true }); @@ -140,6 +253,78 @@ function directDecalCacheProblem(folder: string): string | undefined { return `${folder} has no downloadable_decals..blk and no sibling binary.*/${REGIONAL_PACK_NAME}`; } +function readRawPlayerDecalIndexFiles(folder: string): readonly AddedFile[] | undefined { + const snapshot = readSnapshotIndexFiles(folder); + if (snapshot) return snapshot; + if (decalIndexes(folder).length > 0) return undefined; + const regional = findRegionalPack(folder); + if (!regional) return undefined; + return extractRegionalIndexFiles(regional); +} + +function hasLodParams(block: BlkBlock): boolean { + return block.params.some((param) => param.value.type === 'string' && LOD_PARAM.test(param.name)); +} + +function normalizeTextureBlockLods( + block: BlkBlock, + cachedDdsx: ReadonlySet, +): BlkBlock | undefined { + const lods: Array<{ readonly index: number; readonly value: string; readonly cached: boolean }> = []; + const hdrs = new Map(); + for (const param of block.params) { + if (param.value.type !== 'string') continue; + const lodMatch = LOD_PARAM.exec(param.name); + if (lodMatch) { + const rel = ddsxPathForHash(param.value.value); + lods.push({ + index: Number(lodMatch[1]), + value: param.value.value, + cached: rel !== undefined && cachedDdsx.has(rel), + }); + continue; + } + const hdrMatch = HDR_PARAM.exec(param.name); + if (hdrMatch) { + hdrs.set(Number(hdrMatch[1]), param.value.value); + } + } + if (lods.length === 0) return undefined; + lods.sort((a, b) => a.index - b.index); + const best = lods.find((entry) => entry.cached); + if (!best) return undefined; + if (lods.every((entry) => entry.cached)) return block; + + const missingIndices = new Set(lods.filter((entry) => !entry.cached).map((entry) => entry.index)); + const bestHdr = hdrs.get(best.index); + const nextParams: BlkParam[] = []; + for (const param of block.params) { + if (param.value.type === 'string') { + const hdrMatch = HDR_PARAM.exec(param.name); + if (hdrMatch) { + const idx = Number(hdrMatch[1]); + if (missingIndices.has(idx) && bestHdr !== undefined) { + nextParams.push({ name: param.name, value: { type: 'string', value: bestHdr } }); + continue; + } + } + const lodMatch = LOD_PARAM.exec(param.name); + if (lodMatch) { + const idx = Number(lodMatch[1]); + if (missingIndices.has(idx)) { + if (bestHdr !== undefined && !hdrs.has(idx)) { + nextParams.push({ name: `hdr${idx}`, value: { type: 'string', value: bestHdr } }); + } + nextParams.push({ name: param.name, value: { type: 'string', value: best.value } }); + continue; + } + } + } + nextParams.push(param); + } + return { name: block.name, params: nextParams, blocks: block.blocks }; +} + function readSnapshotIndexFiles(folder: string): readonly AddedFile[] | undefined { const decalsPath = join(folder, SNAPSHOT_INDEX_DIR, SNAPSHOT_DECALS_FILE); if (!statSync(decalsPath, { throwIfNoEntry: false })?.isFile()) return undefined; @@ -154,11 +339,23 @@ function readSnapshotIndexFiles(folder: string): readonly AddedFile[] | undefine } function hasCachedDdsxTextures(folder: string): boolean { - for (const entry of readdirSync(folder, { withFileTypes: true })) { + let entries; + try { + entries = readdirSync(folder, { withFileTypes: true }); + } catch { + return false; + } + for (const entry of entries) { if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue; const sub = join(folder, entry.name); - for (const child of readdirSync(sub, { withFileTypes: true })) { - if (child.isFile() && child.name.endsWith('.ddsx')) return true; + let children; + try { + children = readdirSync(sub, { withFileTypes: true }); + } catch { + continue; + } + for (const child of children) { + if (child.isFile() && child.name.toLowerCase().endsWith(DDSX_EXTENSION)) return true; } } return false; @@ -167,8 +364,14 @@ function hasCachedDdsxTextures(folder: string): boolean { function findRegionalPack(contentFolder: string): string | undefined { const parent = dirname(contentFolder); if (parent === contentFolder || !existsSync(parent)) return undefined; + let entries; + try { + entries = readdirSync(parent, { withFileTypes: true }); + } catch { + return undefined; + } const candidates: Array<{ readonly path: string; readonly version: string; readonly mtimeMs: number }> = []; - for (const entry of readdirSync(parent, { withFileTypes: true })) { + for (const entry of entries) { if (!entry.isDirectory() || entry.isSymbolicLink()) continue; const match = BINARY_CACHE_DIR.exec(entry.name); if (!match) continue; @@ -211,7 +414,11 @@ function contains(parent: string, child: string): boolean { } function decalIndexes(folder: string): string[] { - return readdirSync(folder, { withFileTypes: true }) - .filter((entry) => entry.isFile() && DECALS_INDEX_FILE.test(entry.name)) - .map((entry) => entry.name); + try { + return readdirSync(folder, { withFileTypes: true }) + .filter((entry) => entry.isFile() && DECALS_INDEX_FILE.test(entry.name)) + .map((entry) => entry.name); + } catch { + return []; + } } diff --git a/packages/patcher/src/mods/deploy-external.ts b/packages/patcher/src/mods/deploy-external.ts index b16c5a8..1d8ec01 100644 --- a/packages/patcher/src/mods/deploy-external.ts +++ b/packages/patcher/src/mods/deploy-external.ts @@ -226,6 +226,9 @@ export function computeModsBuildFingerprint( hash.update(`port=${port};salt=${extraSalt}\n`); for (const mod of mods) { hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`); + if (mod.manifest.techTreeInsertions?.length) { + hash.update(`tech_tree_insertions=${JSON.stringify(mod.manifest.techTreeInsertions)}\n`); + } const filesToStamp = [ ...mod.content.packOperations.map((op) => op.sourceRelativePath), ...mod.content.guiPatchDirs, diff --git a/packages/patcher/src/mods/pack-overlay.ts b/packages/patcher/src/mods/pack-overlay.ts index e50ff75..a8bf5ba 100644 --- a/packages/patcher/src/mods/pack-overlay.ts +++ b/packages/patcher/src/mods/pack-overlay.ts @@ -4,7 +4,7 @@ */ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; -import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap } from '@wto/blk'; +import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap, type SharedNameContext } from '@wto/blk'; import { applyBlkPatch, applyBlkTextPatch, @@ -18,6 +18,8 @@ import { type ModdableClientPack, } from '@wto/mods'; import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs'; +import { composeTechTreeInsertions, VEHICLE_ECONOMY_PATH } from '../tech-tree/compose-insertions.ts'; +import { SHOP_PATH } from '../tech-tree/reveal-hidden-vehicles.ts'; export interface PackOverlayReport { readonly pack: ModdableClientPack; @@ -35,7 +37,10 @@ export function applyModPackOverlays( ops: mod.content.packOperations.filter((op) => op.pack === packName), })) .filter((entry) => entry.ops.length > 0); - const totalOps = relevantMods.reduce((sum, entry) => sum + entry.ops.length, 0); + const insertions = packName === 'char.vromfs.bin' + ? mods.flatMap(({ manifest }) => (manifest.techTreeInsertions ?? []).map((entry) => ({ ...entry, modId: manifest.id }))) + : []; + const totalOps = relevantMods.reduce((sum, entry) => sum + entry.ops.length, insertions.length); if (totalOps === 0) { return { pack: basePack, report: { pack: packName, operationsApplied: 0 } }; } @@ -74,10 +79,7 @@ export function applyModPackOverlays( if (!resolvedPath) { throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`); } - const raw = getFile(archive, resolvedPath); - const root = isBinaryBlk(raw) - ? decodeBlk(raw, { names, dictionary }) - : parseBlkText(Buffer.from(raw).toString('utf8')); + const root = readOverlayBlk(archive, resolvedPath, { names, dictionary }); const patchText = readFileSync(sourcePath, 'utf8'); if (op.sourceRelativePath.toLowerCase().endsWith('.patch.blk')) { applyBlkTextPatch(root, patchText, { @@ -123,12 +125,25 @@ export function applyModPackOverlays( } } + if (insertions.length > 0) { + const shop = readOverlayBlk(archive, SHOP_PATH, { names, dictionary }); + const economy = readOverlayBlk(archive, VEHICLE_ECONOMY_PATH, { names, dictionary }); + composeTechTreeInsertions(shop, economy, insertions); + putFile(archive, SHOP_PATH, encodeBlk(shop)); + putFile(archive, VEHICLE_ECONOMY_PATH, encodeBlk(economy)); + } + return { pack: writeArchive(archive), report: { pack: packName, operationsApplied: totalOps }, }; } +function readOverlayBlk(archive: Archive, path: string, shared: SharedNameContext) { + const raw = getFile(archive, path); + return isBinaryBlk(raw) ? decodeBlk(raw, shared) : parseBlkText(Buffer.from(raw).toString('utf8')); +} + function createArchiveIncludeResolver(params: { readonly archive: Archive; readonly names: readonly string[]; diff --git a/packages/patcher/src/tech-tree/compose-insertions.ts b/packages/patcher/src/tech-tree/compose-insertions.ts new file mode 100644 index 0000000..1041cf0 --- /dev/null +++ b/packages/patcher/src/tech-tree/compose-insertions.ts @@ -0,0 +1,221 @@ +/** Compose opt-in research links after the normal BLK overlays have supplied the vehicles. */ +import { emptyBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import type { ModTechTreeInsertion } from '@wto/mods'; + +export const VEHICLE_ECONOMY_PATH = 'config/wpcost.blk'; + +export interface RequestedTechTreeInsertion extends ModTechTreeInsertion { + readonly modId: string; +} + +interface ShopPosition { + readonly entry: BlkBlock; + readonly page: BlkBlock; + readonly country: string; + readonly column: BlkBlock; + readonly group?: BlkBlock; +} + +interface InsertionPlan { + readonly destination: BlkBlock; + readonly anchor: BlkBlock; + readonly successor: ShopPosition; + readonly updateGroupLink: boolean; + readonly entries: readonly { entry: BlkBlock; from: ShopPosition | undefined; rank: number; previous: string }[]; + readonly lastVehicle: string; +} + +export function composeTechTreeInsertions( + shop: BlkBlock, + economy: BlkBlock, + requests: readonly RequestedTechTreeInsertion[], +): void { + const catalog = indexByName(economy.blocks); + const positions = indexShop(shop); + const owners = new Map(); + const bySuccessor = new Map(); + for (const request of requests) { + const owner = owners.get(request.vehicle); + if (owner !== undefined) throw invalid(request, `"${request.vehicle}" is already inserted by mod "${owner}"`); + owners.set(request.vehicle, request.modId); + addToIndex(bySuccessor, request.before, request); + } + + const links = new Map(); + const plans: InsertionPlan[] = []; + for (const group of bySuccessor.values()) { + const first = group[0]!; + for (const request of group) { + if (owners.has(request.after) || owners.has(request.before)) { + throw invalid(request, 'insertion anchors must belong to the existing line'); + } + if (request.after !== first.after) throw invalid(request, `mod "${first.modId}" names a different predecessor of "${request.before}"`); + } + const plan = planInsertion(catalog, positions, group); + for (const [index, entry] of plan.entries.entries()) { + links.set(entry.entry.name, { previous: entry.previous, request: group[index]! }); + } + links.set(first.before, { previous: plan.lastVehicle, request: first }); + plans.push(plan); + } + validateAcyclicLinks(catalog, links); + + for (const [name, { previous, request }] of links) { + setParam(requireOne(catalog, name, VEHICLE_ECONOMY_PATH, request), 'reqAir', { type: 'string', value: previous }); + } + for (const plan of plans) applyPlacement(plan); +} + +function planInsertion( + catalog: ReadonlyMap, + positions: ReadonlyMap, + requests: readonly RequestedTechTreeInsertion[], +): InsertionPlan { + const first = requests[0]!; + const predecessor = requireOne(positions, first.after, 'config/shop.blk', first); + const successor = requireOne(positions, first.before, 'config/shop.blk', first); + if (predecessor.page !== successor.page) throw invalid(first, 'the two anchors must belong to the same country and branch'); + const after = requireOne(catalog, first.after, VEHICLE_ECONOMY_PATH, first); + const before = requireOne(catalog, first.before, VEHICLE_ECONOMY_PATH, first); + const declaredPredecessor = textParam(before, 'reqAir'); + if (declaredPredecessor !== first.after) { + throw invalid(first, `"${first.before}" requires ${declaredPredecessor ? `"${declaredPredecessor}"` : 'no vehicle'} in ${VEHICLE_ECONOMY_PATH}`); + } + const withinGroup = successor.group !== undefined && predecessor.group === successor.group; + const anchor = withinGroup ? successor.entry : successor.group ?? successor.entry; + if (successor.group && !withinGroup && successor.group.blocks[0] !== successor.entry) { + throw invalid(first, 'the link enters a non-leading variant of another folder'); + } + validateShopPredecessor(anchor, first); + const maxRank = researchRank(before, successor, successor.country, first); + let lastRank = researchRank(after, predecessor, successor.country, first); + let lastVehicle = first.after; + + const entries = requests.map((request) => { + const source = requireOne(catalog, request.vehicle, VEHICLE_ECONOMY_PATH, request); + const from = optionalOne(positions, request.vehicle, 'config/shop.blk', request); + if (from && from.page !== successor.page) throw invalid(request, `"${request.vehicle}" is placed in a different country or branch`); + if (from?.group && (!withinGroup || from.group !== successor.group)) { + throw invalid(request, `"${request.vehicle}" is already inside a different folder`); + } + const rank = researchRank(source, from, successor.country, request); + if (rank < lastRank || rank > maxRank) { + throw invalid(request, `rank ${rank} must be between ${lastRank} and ${maxRank} in mod load order`); + } + const entry = { entry: from?.entry ?? emptyBlock(request.vehicle), from, rank, previous: lastVehicle }; + lastRank = rank; + lastVehicle = request.vehicle; + return entry; + }); + return { destination: withinGroup ? successor.group! : successor.column, anchor, successor, updateGroupLink: anchor !== successor.entry, entries, lastVehicle }; +} + +function validateShopPredecessor(anchor: BlkBlock, request: RequestedTechTreeInsertion): void { + for (const key of ['reqAir', 'futureReqAir']) { + const value = findParam(anchor, key)?.value; + if (value !== undefined && (value.type !== 'string' || value.value !== request.after)) { + throw invalid(request, `"${anchor.name}" has a different ${key} in config/shop.blk`); + } + } +} + +function applyPlacement(plan: InsertionPlan): void { + for (const item of plan.entries) { + if (item.from) { + const parent = item.from.group ?? item.from.column; + parent.blocks.splice(parent.blocks.indexOf(item.entry), 1); + } + setParam(item.entry, 'rank', { type: 'int', value: item.rank }); + setPrerequisite(item.entry, item.previous); + } + plan.destination.blocks.splice(plan.destination.blocks.indexOf(plan.anchor), 0, ...plan.entries.map(({ entry }) => entry)); + setPrerequisite(plan.successor.entry, plan.lastVehicle); + if (plan.updateGroupLink) setPrerequisite(plan.anchor, plan.lastVehicle); +} + +function setPrerequisite(block: BlkBlock, previous: string): void { + setParam(block, 'reqAir', { type: 'string', value: previous }); + if (findParam(block, 'futureReqAir')) setParam(block, 'futureReqAir', { type: 'string', value: previous }); +} + +function researchRank(entry: BlkBlock, position: ShopPosition | undefined, country: string, request: RequestedTechTreeInsertion): number { + const rank = findParam(entry, 'rank')?.value; + const gold = findParam(entry, 'costGold')?.value; + if (textParam(entry, 'country') !== country || rank?.type !== 'int' || rank.value < 1) { + throw invalid(request, `"${entry.name}" must have a valid rank in ${country} in ${VEHICLE_ECONOMY_PATH}`); + } + if (textParam(entry, 'gift') !== undefined || textParam(entry, 'event') !== undefined || textParam(entry, 'researchType') === 'clanVehicle' + || findParam(entry, 'premPackAir')?.value.value === true || (gold?.type === 'int' && gold.value > 0) + || (position && findParam(position.entry, 'showOnlyWhenBought')?.value.value === true)) { + throw invalid(request, `"${entry.name}" must be a regular vehicle in the research line`); + } + return rank.value; +} + +function validateAcyclicLinks( + catalog: ReadonlyMap, + links: ReadonlyMap, +): void { + const checked = new Set(); + for (const [vehicle, { request }] of links) { + const path = new Set(); + let name: string | undefined = vehicle; + while (name !== undefined && !checked.has(name)) { + if (path.has(name)) throw invalid(request, `research prerequisites form a cycle at "${name}"`); + path.add(name); + const existing: BlkBlock | undefined = catalog.get(name)?.[0]; + name = links.get(name)?.previous ?? (existing ? textParam(existing, 'reqAir') : undefined); + } + for (const visited of path) checked.add(visited); + } +} + +function indexShop(shop: BlkBlock): Map { + const positions = new Map(); + for (const country of shop.blocks) { + for (const page of country.blocks) { + for (const column of page.blocks) { + for (const entry of column.blocks) { + addToIndex(positions, entry.name, { entry, page, country: country.name, column }); + for (const variant of entry.blocks) { + addToIndex(positions, variant.name, { entry: variant, page, country: country.name, column, group: entry }); + } + } + } + } + } + return positions; +} + +function indexByName(blocks: readonly BlkBlock[]): Map { + const entries = new Map(); + for (const block of blocks) addToIndex(entries, block.name, block); + return entries; +} + +function addToIndex(index: Map, key: string, entry: T): void { + const list = index.get(key); + if (list) list.push(entry); + else index.set(key, [entry]); +} + +function requireOne(index: ReadonlyMap, name: string, where: string, request: RequestedTechTreeInsertion): T { + const entry = optionalOne(index, name, where, request); + if (entry === undefined) throw invalid(request, `"${name}" is missing from ${where}`); + return entry; +} + +function optionalOne(index: ReadonlyMap, name: string, where: string, request: RequestedTechTreeInsertion): T | undefined { + const entries = index.get(name); + if (entries && entries.length > 1) throw invalid(request, `"${name}" is ambiguous in ${where}`); + return entries?.[0]; +} + +function textParam(block: BlkBlock, name: string): string | undefined { + const value = findParam(block, name)?.value; + return value?.type === 'string' ? value.value : undefined; +} + +function invalid(request: RequestedTechTreeInsertion, reason: string): Error { + return new Error(`mod "${request.modId}" tech_tree_insertions (${request.after} -> ${request.vehicle} -> ${request.before}): ${reason}`); +} diff --git a/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts b/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts index 8237776..50be1a1 100644 --- a/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts +++ b/packages/patcher/src/tech-tree/reveal-hidden-vehicles.ts @@ -15,21 +15,45 @@ * not been given them: event and promotion prizes, mission copies of tree vehicles (nt_f_4e, * f_4e_event ...), the drones of the premium columns, the floatplanes that come with ships, * and the launchers of the split air-defence systems (lab round 20, user feedback). + * + * Cross-promotion gift vehicles (e.g. us_m4_sherman_promo, bf-109c_1_promo, + * jp_destroyer_hatsuzuki) also carry `isCrossPromo:b` and `crossPromoBanner:t`. When + * `isCrossPromo` is true, stock client scripts (availabilitybuyonline.nut, unitcontextmenu.nut, + * slotactions.nut) hide the "Order" action and show a cross-promo locked banner instead of + * routing to the local store pack and bundle GUID generated for gift vehicles. Both parameters + * are stripped here so those vehicles can be ordered directly from the tech tree. */ import type { BlkBlock } from '@wto/blk'; export const SHOP_PATH = 'config/shop.blk'; const HIDING_FLAGS = new Set(['showOnlyWhenResearch', 'showOnlyWhenAvailableForPurchase']); +const CROSS_PROMO_PARAMS = new Set(['isCrossPromo', 'crossPromoBanner']); -/** Remove the hiding flags in place; returns how many vehicles were hidden before. */ +/** + * Remove tech-tree hiding flags and cross-promo lock parameters in place. + * Returns how many vehicles had a hiding flag removed (cross-promo unlocks are not counted). + */ export function revealHiddenVehicles(shop: BlkBlock): number { let revealed = 0; for (const entry of shopEntries(shop)) { - const kept = entry.params.filter((param) => !HIDING_FLAGS.has(param.name)); - if (kept.length === entry.params.length) continue; + let wasHidden = false; + let stripped = false; + const kept = entry.params.filter((param) => { + if (HIDING_FLAGS.has(param.name)) { + wasHidden = true; + stripped = true; + return false; + } + if (CROSS_PROMO_PARAMS.has(param.name)) { + stripped = true; + return false; + } + return true; + }); + if (!stripped) continue; entry.params = kept; - revealed++; + if (wasHidden) revealed++; } return revealed; } diff --git a/patches/gui/battle/pass-spawn-modifications-blk/find-backup-field.nut b/patches/gui/battle/pass-spawn-modifications-blk/find-backup-field.nut new file mode 100644 index 0000000..6d51012 --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/find-backup-field.nut @@ -0,0 +1,2 @@ + lastRequestData = null + lastSpawnUnitName = "" diff --git a/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc b/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc index 8087edc..a10ad25 100644 --- a/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc +++ b/patches/gui/battle/pass-spawn-modifications-blk/patch.jsonc @@ -13,6 +13,7 @@ "written_for": "2.61.0.37", "file": "scripts/respawn/respawn.nut", "edits": [ + { "find": "find-backup-field.nut", "replace": "replace-backup-field.nut" }, { "find": "find.nut", "replace": "replace.nut" diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace-backup-field.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace-backup-field.nut new file mode 100644 index 0000000..8e43f12 --- /dev/null +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace-backup-field.nut @@ -0,0 +1,3 @@ + lastRequestData = null + wtoLastBackup = null + lastSpawnUnitName = "" diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace-confirm-spawn.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace-confirm-spawn.nut index 122aeed..e51e71b 100644 --- a/patches/gui/battle/pass-spawn-modifications-blk/replace-confirm-spawn.nut +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace-confirm-spawn.nut @@ -3,8 +3,9 @@ let source = request == null ? null : this.getWtoBackupSourceForRequest(request) if (source != null) { let backup = this.getWtoBackupToken(request, source) - if (backup == null || request?.wtoBackup != backup) { + if (backup == null || this.wtoLastBackup != backup) { this.lastRequestData = null + this.wtoLastBackup = null this.isApplyPressed = false this.checkReady() this.doSelectAircraft() diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace-used-item.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace-used-item.nut index a34da6f..5637c33 100644 --- a/patches/gui/battle/pass-spawn-modifications-blk/replace-used-item.nut +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace-used-item.nut @@ -1,3 +1,3 @@ - if (this.lastRequestData?.wtoBackup == null) + if (this.wtoLastBackup == null) markUsedItemCount(itemType.UNIVERSAL_SPARE, this.lastRequestData.spareUid) this.universalSpareUidForRespawn = "" diff --git a/patches/gui/battle/pass-spawn-modifications-blk/replace.nut b/patches/gui/battle/pass-spawn-modifications-blk/replace.nut index 1fd7089..85842ab 100644 --- a/patches/gui/battle/pass-spawn-modifications-blk/replace.nut +++ b/patches/gui/battle/pass-spawn-modifications-blk/replace.nut @@ -1,8 +1,10 @@ function sendWtoAircraftAndWeaponRequest(requestData, isSilent = false) { let wtoNdb = require("nestdb") - if (!wtoNdb.ndbExists(["wto", "activeBattle"])) + if (!wtoNdb.ndbExists(["wto", "activeBattle"])) { + this.wtoLastBackup = null return requestAircraftAndWeaponWithSpare(requestData, requestData.idInCountry, requestData.respBaseId, requestData.spareUid) + } let wtoBattle = wtoNdb.ndbTryRead(["wto", "activeBattle"]) let wtoGuiRespawn = require("guiRespawn") let wtoChardRes = require("chardResearch") @@ -86,20 +88,27 @@ wtoBlk.enabledMods = ";".join(wtoEnabledMods) wtoBlk.disabledMods = ";".join(wtoDisabledMods) wtoBlk.isSilentPreview = isSilent ? "1" : "0" + // Keep backup metadata off requestData so checkReady()'s u.isEqual(lastRequestData, getSelectedRequestData()) stays true. + local wtoBackupToken = null if (!isSilent) { let source = this.getWtoBackupSourceForRequest(requestData) let backup = this.getWtoBackupToken(requestData, source) if (backup == null) return -1 if (backup != "") { - requestData.wtoBackup <- backup + wtoBackupToken = backup wtoBlk.wtoBackup = backup } - if (source == "vehicle") + if (source == "vehicle") { + this.universalSpareUidForRespawn = "" requestData.spareUid = "" + } } - return wtoGuiRespawn.requestAircraftAndWeaponWithSlots(requestData, requestData.idInCountry, + let wtoTaskId = wtoGuiRespawn.requestAircraftAndWeaponWithSlots(requestData, requestData.idInCountry, requestData.respBaseId, requestData.spareUid, wtoBlk, DataBlock()) + if (wtoTaskId >= 0) + this.wtoLastBackup = wtoBackupToken + return wtoTaskId } function requestAircraftAndWeapon(requestData) { diff --git a/patches/gui/battle/record-local-battle-awards/replace.nut b/patches/gui/battle/record-local-battle-awards/replace.nut index bc844b0..a60e687 100644 --- a/patches/gui/battle/record-local-battle-awards/replace.nut +++ b/patches/gui/battle/record-local-battle-awards/replace.nut @@ -82,7 +82,9 @@ function wtoOnLocalMpExpEvent(ev) { if (battle == null) return let wtoMission = require("mission") - let unit = ndbTryRead(["wto", "battleLog", "openLife"])?.unit ?? require("unit").get_player_unit_name() + let sourceUnit = ev?.unit ?? "" + let unit = battle?.awards?.vehicles?[sourceUnit] != null ? sourceUnit + : ndbTryRead(["wto", "battleLog", "openLife"])?.unit ?? require("unit").get_player_unit_name() let entry = { time = wtoMission.get_mission_time() unit @@ -172,20 +174,23 @@ function wtoOnLocalMpNuclearStrike(_ev) { function wtoOnLocalMpBackupSpawn(ev) { let { ndbTryRead, ndbWrite } = require("nestdb") let battle = ndbTryRead(["wto", "activeBattle"]) - if (battle?.backups == null || (ev?.unit ?? "") == "" || (ev?.backup ?? "") == "") + // Native UnitInfo::name prefixes ground/naval units (e.g. "tankModels/cn_type_59"); keep the bare unit id. + let parts = (ev?.unit ?? "").split("/") + let unit = parts.len() > 0 ? parts.top() : "" + if (battle?.backups == null || unit == "" || (ev?.backup ?? "") == "") return let slot = ev?.slot ?? -1 let spawns = ndbTryRead(["wto", "battleLog", "spares"]) ?? [] if (slot < 0 || spawns.findvalue(@(spawn) spawn.slot == slot) != null) return - wtoAppendBattleLog("spares", { slot, unit = ev.unit, backup = ev.backup }) + wtoAppendBattleLog("spares", { slot, unit, backup = ev.backup }) let { DAILY_FREE_SPARE_UID } = require("%scripts/respawn/respawnDailyFreeSpare.nut") if (ev.backup == DAILY_FREE_SPARE_UID) { let path = ["wto", "battleLog", "dailyBackupsUsed"] ndbWrite(path, (ndbTryRead(path) ?? 0) + 1) let { matchingApiFunc } = require("%scripts/matching/api.nut") - matchingApiFunc("wto_battle.daily_spare", @(_response) null, { sessionId = battle.sessionId, slot, unit = ev.unit }) + matchingApiFunc("wto_battle.daily_spare", @(_response) null, { sessionId = battle.sessionId, slot, unit }) } else if (ev.backup != "vehicle") { let { markUsedItemCount } = require("%scripts/items/usedItemsInBattle.nut") diff --git a/patches/gui/online-shop/free-offline-payment-method/patch.jsonc b/patches/gui/online-shop/free-offline-payment-method/patch.jsonc index daac78f..9ef33f9 100644 --- a/patches/gui/online-shop/free-offline-payment-method/patch.jsonc +++ b/patches/gui/online-shop/free-offline-payment-method/patch.jsonc @@ -3,7 +3,7 @@ // Without it: the in-game payment window offers no free offline purchase. { "id": "online-shop/free-offline-payment-method", - "title": "游戏内支付方式窗口增加「老福爷付过了」免 GJN 直接购买选项", + "title": "Add a no-GJN direct claim option to the in-game payment dialog", "features": [ "G-Currencies", "G-Premium account", diff --git a/patches/gui/online-shop/free-offline-payment-method/replace.nut b/patches/gui/online-shop/free-offline-payment-method/replace.nut index e1fd249..4e14406 100644 --- a/patches/gui/online-shop/free-offline-payment-method/replace.nut +++ b/patches/gui/online-shop/free-offline-payment-method/replace.nut @@ -1,4 +1,11 @@ - let freePayName = "老福爷付过了" + let { isChineseVersion, isChineseHarmonized } = require("%scripts/langUtils/language.nut") + let { getShopPriceBlk } = require("%scripts/onlineShop/onlineShopState.nut") + let isChinese = isChineseVersion() || isChineseHarmonized() + let priceBlk = getShopPriceBlk() + let customFreePayName = isChinese ? priceBlk?.wtoFreePaymentLabelZh : priceBlk?.wtoFreePaymentLabelEn + let freePayName = (type(customFreePayName) == "string" && customFreePayName != "") + ? customFreePayName + : (isChinese ? "直接获取" : "Direct Claim") items.append({ name = freePayName icon = "" diff --git a/patches/native/local_mp_air_ai_sync.jsonc b/patches/native/local_mp_air_ai_sync.jsonc new file mode 100644 index 0000000..8b4b9e5 --- /dev/null +++ b/patches/native/local_mp_air_ai_sync.jsonc @@ -0,0 +1,28 @@ +// Serialize concurrent updates to the team AI unsortedPlanes list on a LocalMP host. +// The local server cannot add locking inside the client's parallel aircraft physics threads. +// Without it: concurrent HeapReAlloc calls on the shared vector corrupt the heap (0xC0000374). +{ + "module": "local_mp_air_ai_sync", + "features": [ + "K-AI opponents and teammates" + ], + "requires": [ + "local_mp_core" + ], + "sites": { + // TeamAiManager::addToUnsortedPlanes; unique reference to "unsortedPlanes". + // Verified at 2.61.0.37 0x807be0, 2.61.0.58 0x80a2b0, 2.61.0.60 0x80a150. + "air_ai_add_unsorted_plane": { + "variants": [ + { + "written_for": "2.61.0.37", + "locate": { + "method": "string_ref", + "string": "unsortedPlanes", + "target": "function" + } + } + ] + } + } +} diff --git a/patches/native/local_mp_captures.jsonc b/patches/native/local_mp_captures.jsonc new file mode 100644 index 0000000..4c89359 --- /dev/null +++ b/patches/native/local_mp_captures.jsonc @@ -0,0 +1,65 @@ +// Award capture credit to players whose units contribute to a completed LocalMP capture. +// Only the mission engine knows when a zone changes owner and which units it counted. +// Without this module, the scoreboard and settlement miss completed captures. +{ + "module": "local_mp_captures", + "features": ["K-Kill, assist and capture scoring"], + "requires": ["local_mp_core", "local_mp_kills", "local_mp_scores", "local_mp_awards"], + "sites": { + // cta_logic_action contains the zone-update timing diagnostic and the inline airfield completion path. + "capture_cta_logic": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { "method": "string_ref", "string": "update_capture_zones", "target": "function" } + }] + }, + // CaptureZone::setArmy. Read the old owner before the native replicated setter runs. + // 2.61.0.37: 0x11b7f70; 2.61.0.60: 0x11bcba0. + "capture_set_owner": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 28 01 00 00 0f 29 b4 24 10 01 00 00 0f b6 71 ?? 89 54 24 2c 39 f2 0f 84 ?? ?? ?? ?? 49 89 cd", + "captures": { "owner": { "offset": 30, "type": "u8" } } + } + }] + }, + // The setArmy call made when the ordinary progress helper reaches the capturing team's limit. + // 2.61.0.37: 0x11c2095; 2.61.0.60: 0x11c7605. + "capture_complete_call": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "pattern": "e8 ?? ?? ?? ?? 48 8b 0d ?? ?? ?? ?? 48 8b 05 ?? ?? ?? ?? 48 85 c0 74 ?? 80 3d ?? ?? ?? ?? 00 75 ?? 80 3d ?? ?? ?? ?? 00 75 ?? 48 8d 50 70", + "captures": { "set_owner": { "offset": 1, "type": "rel32" } } + } + }] + }, + // sumCapturePower(army, zone, &count) walks eligible mission units for one team. + // 2.61.0.37: 0x11b90a0; 2.61.0.60: 0x11bdd30. + "capture_team_power": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "signature", + "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec b8 00 00 00 0f 29 b4 24 a0 00 00 00 48 89 d7 89 4c 24 3c 4c 89 44 24 40 41 c7 00 00 00 00 00 48 b8 32 00 00 00 ff ff ff ff" + } + }] + }, + // sumCapturePower calls this helper after accepting a unit and increments its count. + // 2.61.0.37: 0x11b9214 -> 0x11b8f10; 2.61.0.60: 0x11bdea4 -> 0x11bdba0. + "capture_unit_power_call": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "within", + "in": "capture_team_power", + "pattern": "ff 00 48 89 f9 48 89 ea e8 ?? ?? ?? ?? f3 0f 58 f0", + "captures": { "function": { "offset": 9, "type": "rel32" } } + } + }] + } + } +} diff --git a/patches/native/local_mp_events.jsonc b/patches/native/local_mp_events.jsonc index 62a4a42..932b761 100644 --- a/patches/native/local_mp_events.jsonc +++ b/patches/native/local_mp_events.jsonc @@ -1,6 +1,6 @@ -// Combat events on the LocalMP host (native/wto-net/src/local_mp_events.c): assists, captures, +// Combat events on the LocalMP host (native/wto-net/src/local_mp_events.c): assists, // effective and ineffective hits, and severe damage, reported as award facts. -// Without it: assists, captures and damage events score nothing in LocalMP battles. +// Without it: assists and damage events score nothing in LocalMP battles. { "module": "local_mp_events", "features": [ @@ -26,25 +26,6 @@ } ] }, - // A caller of the capture zone dispatch; captures the callee. - // 2.61.0.37: 0x3db0e0 - "caller_capture_zone": { - "variants": [ - { - "written_for": "2.61.0.37", - "locate": { - "method": "signature", - "pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 38 44 0f b7 72 02 44 8b 7a 04 4c 8b 62 08 4c 8b 6a 18 49 8d 85 88 06 00 00 48 89 44 24 30 49 8d 85 50 06 00 00 48 89 44 24 28 eb ?? 48 8b 90 08 0e 00 00 89 d1 83 e1 01 0b 0d ?? ?? ?? ?? 3b 88 14 0e 00 00 0f 85 ?? ?? ?? ?? 48 83 e2 fe 48 8b 82 98 0f 00 00 48 8b 88 b8 00 00 00 e8 ?? ?? ?? ??", - "captures": { - "call": { - "offset": 108, - "type": "rel32" - } - } - } - } - ] - }, // Flushes effective / ineffective hits. The site key also identifies this capture in version records. // 2.61.0.37: 0xff85ea "caller_hit_crit": { diff --git a/patches/native/local_mp_hit_feedback.jsonc b/patches/native/local_mp_hit_feedback.jsonc new file mode 100644 index 0000000..b6eba6f --- /dev/null +++ b/patches/native/local_mp_hit_feedback.jsonc @@ -0,0 +1,38 @@ +// Keep outgoing hit markers and shell advice tied to the firing unit on a LocalMP host. +// The local daScript send path bypasses the recipient filter. The native shell hint has its own dispatch. +// Without this module, impacts by other units can reach the local attack feedback paths. +{ + "module": "local_mp_hit_feedback", + "features": ["K-Player damage notices"], + "requires": ["local_mp_core", "local_mp_damage_notifications"], + "sites": { + // CmdShowHitMark unicast wrapper calls the common daScript network event sender. The inline + // damage script and the interpreted wrapper use that same sender. + // 2.61.0.37: 0x1eaa106 -> 0x50a06e0; 2.61.0.60: 0x1eb79b6 -> 0x50b13c0. + "hit_mark_send": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "string_ref", + "string": "CmdShowHitMark", + "lea_at": 0, + "pattern": "48 8d 15 ?? ?? ?? ?? 66 48 0f 6e ca 66 0f 7f 8c 24 f0 00 00 00 66 0f 7f 84 24 00 01 00 00 41 0f 10 01 4c 8d 4c 24 70 4c 89 4c 24 40 4c 8d 4c 24 40 4c 89 4c 24 50 4c 8d 0d ?? ?? ?? ?? 4c 89 4c 24 48 c6 44 24 68 01 0f 11 44 24 58 48 8b 89 30 03 00 00 4c 8d 4c 24 48 4c 89 4c 24 30 4c 8d 4c 24 58 4c 89 4c 24 28 48 89 54 24 20 31 d2 49 89 c1 e8 ?? ?? ?? ??", + "captures": { "send": { "offset": 114, "type": "rel32" } } + } + }] + }, + // The shell-change hint's call in Unit::onEvent, just before it queues enemy damage parts. + // 2.61.0.37: 0x1045fbe -> 0x183bcc0; 2.61.0.60: 0x104a8e4 -> 0x1844c30. + "hit_shell_hint_call": { + "variants": [{ + "written_for": "2.61.0.37", + "locate": { + "method": "within", + "in": "unit_on_event", + "pattern": "e8 ?? ?? ?? ?? 48 8b 0d ?? ?? ?? ?? 4c 8d b4 24 00 01 00 00 4c 89 ea 4d 89 f0 e8 ?? ?? ?? ??", + "captures": { "notify": { "offset": 1, "type": "rel32" } } + } + }] + } + } +} diff --git a/patches/versions/2.61.0.64.jsonc b/patches/versions/2.61.0.64.jsonc new file mode 100644 index 0000000..ab1af5c --- /dev/null +++ b/patches/versions/2.61.0.64.jsonc @@ -0,0 +1,730 @@ +// Patch check results for this game build; written by scripts/record-game-version.ts. +{ + "game_version": "2.61.0.64", + "executable_sha256": "f6252ec29d977227bc7b23330aae20b0bd8d06efe3c575f271088b37ef652455", + "gui_pack_sha256": "c3d2d4daf20935dafaa1cd1161a566d472cbf43d15610ccbc527547d0aa458e5", + "exe_patches": { + "battle/allow-local-host-bot-spawns": { + "variant": "2.61.0.37", + "rva": "0x11b78fa" + }, + "battle/allow-local-host-player-respawn": { + "variant": "2.61.0.37", + "rva": "0x1049a2c" + }, + "battle/allow-local-host-ucav-launch": { + "variant": "2.61.0.37", + "rva": "0x1021823" + }, + "battle/count-bots-as-active-players": { + "variant": "2.61.0.37", + "rva": "0x11bea38" + }, + "battle/load-local-host-player-crew": { + "variant": "2.61.0.37", + "rva": "0x10070dd" + }, + "isolation/never-launch-official-launcher": { + "variant": "2.61.0.37", + "rva": "0xef23a7" + }, + "isolation/never-load-battleye": { + "variant": "2.61.0.37", + "rva": "0x30d613c" + }, + "isolation/never-upload-crash-reports": { + "variant": "2.61.0.37", + "rva": "0x4104e1a" + }, + "isolation/registry-key": { + "variant": "2.61.0.37", + "rva": "0x7a4b1c4" + }, + "isolation/user-data-folder-name": { + "variant": "2.61.0.37", + "rva": "0x778f2b0" + }, + "online/accept-local-tls-certificate": { + "variant": "2.61.0.37", + "rva": "0x56557c2" + }, + "online/matching-server-public-key": { + "variant": "2.61.0.37", + "rva": "0x73526a0" + }, + "online/network-hook-library": { + "variant": "2.61.0.37", + "rva": "0x7a5c642" + }, + "startup/skip-resource-archive-signature-check": { + "variant": "2.61.0.37", + "rva": "0x4082f10" + } + }, + "gui_patches": { + "agreement/require-explicit-acceptance": { + "variant": "2.61.0.37" + }, + "agreement/show-offline-terms": { + "variant": "2.61.0.37" + }, + "battle/append-extra-battle-slots": { + "variant": "2.61.0.37" + }, + "battle/available-local-backups": { + "variant": "2.61.0.37" + }, + "battle/filter-extra-slot-weapons": { + "variant": "2.61.0.37" + }, + "battle/force-extra-slot-weapons": { + "variant": "2.61.0.37" + }, + "battle/launch-local-battle-from-queue": { + "variant": "2.61.0.37" + }, + "battle/lineup-br-for-submodes": { + "variant": "2.61.0.37" + }, + "battle/local-host-spawn-score": { + "variant": "2.61.0.37" + }, + "battle/lock-single-slot-lineup": { + "variant": "2.61.0.37" + }, + "battle/match-settled-battle-room-logs": { + "variant": "2.61.0.37" + }, + "battle/open-replay-from-battle-log": { + "variant": "2.61.0.37" + }, + "battle/pass-spawn-modifications-blk": { + "variant": "2.61.0.37" + }, + "battle/play-local-battle-replay": { + "variant": "2.61.0.37" + }, + "battle/quit-local-host-spectator-to-debriefing": { + "variant": "2.61.0.37" + }, + "battle/quit-local-host-to-debriefing": { + "variant": "2.61.0.37" + }, + "battle/ready-local-host-respawn": { + "variant": "2.61.0.37" + }, + "battle/record-local-battle-awards": { + "variant": "2.61.0.37" + }, + "battle/report-local-battle-settlement": { + "variant": "2.61.0.37" + }, + "battle/scoreboard-team-country-flags": { + "variant": "2.61.0.37" + }, + "battle/stabilize-respawn-countdown-button": { + "variant": "2.61.0.37" + }, + "battle/tag-local-battle-replay": { + "variant": "2.61.0.37" + }, + "battle/track-local-airfield-departures": { + "variant": "2.61.0.58" + }, + "battle/use-local-airfield-respawn-delay": { + "variant": "2.61.0.58" + }, + "battle/use-settled-debriefing-stats": { + "variant": "2.61.0.37" + }, + "inventory/local-content-public-key": { + "variant": "2.61.0.37" + }, + "inventory/show-coupon-redemption-reward": { + "variant": "2.61.0.37" + }, + "online-shop/bypass-external-sso-for-local-urls": { + "variant": "2.61.0.37" + }, + "online-shop/collect-entitlement-purchase-rewards": { + "variant": "2.61.0.37" + }, + "online-shop/defer-explicit-browser-update-to-close": { + "variant": "2.61.0.37" + }, + "online-shop/free-offline-payment-method": { + "variant": "2.61.0.37" + }, + "online-shop/localize-vehicle-pack-titles": { + "variant": "2.61.0.37" + }, + "online-shop/open-entitlement-purchase-receipts": { + "variant": "2.61.0.37" + }, + "online-shop/present-saved-entitlement-grants": { + "variant": "2.61.0.37" + }, + "online-shop/refresh-profile-after-browser-close": { + "variant": "2.61.0.37" + }, + "online-shop/refresh-profile-after-currency-shop-close": { + "variant": "2.61.0.37" + }, + "online-shop/refresh-profile-after-premium-shop-close": { + "variant": "2.61.0.37" + }, + "online-shop/render-retired-entitlement-log": { + "variant": "2.61.0.37" + }, + "online-shop/resume-purchase-receipts-after-price-update": { + "variant": "2.61.0.37" + }, + "online-shop/return-entitlement-reward-handler": { + "variant": "2.61.0.37" + }, + "online-shop/show-direct-entitlement-gift-icons": { + "variant": "2.61.0.37" + }, + "online-shop/show-direct-entitlement-gifts": { + "variant": "2.61.0.37" + }, + "online-shop/show-entitlement-purchase-rewards": { + "variant": "2.61.0.37" + }, + "online-shop/use-entitlement-receipt-for-native-payment": { + "variant": "2.61.0.37" + }, + "registration/keep-local-page-embedded": { + "variant": "2.61.0.37" + }, + "registration/open-local-page": { + "variant": "2.61.0.37" + }, + "tutorials/cancel-guide-without-target": { + "variant": "2.61.0.37" + }, + "tutorials/guard-crew-training-intro": { + "variant": "2.61.0.37" + }, + "tutorials/immediate-save-skip-tutorial": { + "variant": "2.61.0.37" + }, + "tutorials/save-crew-training-completion": { + "variant": "2.61.0.37" + } + }, + "native_modules": { + "local_mp_core": { + "disabled_slots_mask": "2.61.0.37", + "do_respawn_player": "2.61.0.37", + "get_player_country": "2.61.0.37", + "sq_local_country": "2.61.0.37", + "refl_dtor": "2.61.0.37", + "aircraft_change_result": "2.61.0.37", + "set_player_gui_state": "2.61.0.37", + "get_unit_by_eid": "2.61.0.37", + "set_owning_mplayer": "2.61.0.37", + "iground_on_dead": "2.61.0.37", + "datablock_get_str": "2.61.0.37", + "datablock_set_from": "2.61.0.37", + "mp_construct_local": "2.61.0.37", + "gui_state_update": "2.61.0.37", + "app_econ_state": "2.61.0.37", + "mplayer_matching": "2.61.0.37", + "unit_change_aircraft": "2.61.0.37", + "unit_type": "2.61.0.37", + "unit_info_name": "2.61.0.37", + "unit_mplayer": "2.61.0.37", + "refl_stdmem": "2.61.0.37", + "mission_settings_load": "2.61.0.37", + "mission_custom_bots": "2.61.0.37", + "scoreboard_rows": "2.61.0.37", + "mplayer_unit_eid": "2.61.0.37", + "unit_on_event": "2.61.0.37" + }, + "local_mp_actions": { + "mp_init_chat": "2.61.0.37", + "mp_chat": "2.61.0.37", + "bot_system_setup": "2.61.0.37", + "mp_team_countries": "2.61.0.37" + }, + "local_mp_air_ai_sync": { + "air_ai_add_unsorted_plane": "2.61.0.37" + }, + "local_mp_awards": { + "add_score_message": "2.61.0.37", + "score_msg_blk_ctor": "2.61.0.37", + "score_msg_blk_set_str": "2.61.0.37", + "score_msg_blk_to_owned": "2.61.0.37", + "score_msg_blk_set_int": "2.61.0.37", + "score_msg_hud_queue": "2.61.0.37", + "score_msg_blk_dtor": "2.61.0.37", + "score_msg_exp_class": "2.61.0.37", + "game_save_data": "2.61.0.37" + }, + "local_mp_scores": { + "datablock_get_real": "2.61.0.37", + "mission_score_params": "2.61.0.37" + }, + "local_mp_kills": { + "mplayer_add_score": "2.61.0.37", + "mplayer_score": "2.61.0.37", + "mplayer_stat_sync": "2.61.0.37", + "net_mark_dirty": "2.61.0.37", + "on_unit_dead_once": "2.61.0.37", + "unit_severe": "2.61.0.37", + "ground_death_flags": "2.61.0.37", + "ground_bailout": "2.61.0.37", + "ground_offenders": "2.61.0.37", + "iground_award_assists": "2.61.0.37", + "offender_fields": "2.61.0.37", + "stat_kills": "2.61.0.37", + "stat_ground_kills": "2.61.0.37", + "stat_human_kills": "2.61.0.37", + "stat_naval_kills": "2.61.0.37", + "stat_team_kills": "2.61.0.37", + "stat_ai_kills": "2.61.0.37", + "stat_ai_ground_kills": "2.61.0.37", + "stat_ai_naval_kills": "2.61.0.37", + "stat_assists": "2.61.0.37", + "stat_deaths": "2.61.0.37", + "stat_capture_zone": "2.61.0.37", + "stat_score": "2.61.0.37", + "stat_award_damage": "2.61.0.37", + "stat_air_severe": "2.61.0.37", + "stat_ship_severe": "2.61.0.37" + }, + "local_mp_air_events": { + "mission_mode_name": "2.61.0.58", + "prepare_local_mission": "2.61.0.58", + "prepare_local_mission_clear": "2.61.0.58", + "kill_streak_revert": "2.61.0.58", + "kill_streak_rules": "2.61.0.58", + "add_kill_streak_points": "2.61.0.58", + "mplayer_streak_progress": "2.61.0.58", + "kill_streak_ai_mults": "2.61.0.58", + "air_event_initiate": "2.61.0.58", + "air_event_spawn_table": "2.61.0.58", + "air_event_terrain": "2.61.0.58", + "air_event_switch_unit": "2.61.0.58", + "air_event_orientation": "2.61.0.58", + "send_unit_respawn": "2.61.0.58", + "send_unit_respawn_broadcast": "2.61.0.58" + }, + "local_mp_players": { + "mplayer_init_matching": "2.61.0.37", + "is_slot_ready_at_host": "2.61.0.37", + "mplayer_gui_state": "2.61.0.37", + "mplayer_clear_before_lobby": "2.61.0.37", + "mplayer_used_spares": "2.61.0.37", + "mission_allies_country": "2.61.0.37", + "mission_axis_country": "2.61.0.37", + "mission_arcade_country": "2.61.0.37" + }, + "local_mp_damage_notifications": { + "barrel_damage": "2.61.0.37", + "barrel_damage_notice": "2.61.0.37", + "breech_fire_update": "2.61.0.37", + "breech_damage_notice": "2.61.0.37", + "mplayer_controlled_unit": "2.61.0.37", + "hud_damage_deliver": "2.61.0.37", + "avionics_damage": "2.61.0.37", + "avionics_exit_optic": "2.61.0.37", + "hit_event_offender": "2.61.0.37", + "hit_watched_hero": "2.61.0.37", + "respawn_spectator": "2.61.0.37", + "hit_parts_feedback": "2.61.0.37", + "local_mpi_dispatch": "2.61.0.37", + "mpi_msg_id": "2.61.0.37", + "enemy_part_damage_mpi": "2.61.0.37", + "enemy_part_hit_mpi": "2.61.0.37" + }, + "local_mp_events": { + "dispatch_assist": "2.61.0.37", + "caller_capture_zone": "2.61.0.37", + "caller_hit_crit": "2.61.0.37", + "caller_severe_damage": "2.61.0.37", + "caller_naval_damage": "2.61.0.37", + "offender_assist": "2.61.0.37" + }, + "local_mp_ground_ai": { + "ground_ai_mission_binding": "2.61.0.37", + "ground_ai_as_ground_model": "2.61.0.37", + "ground_ai_move_properties": "2.61.0.37", + "ground_ai_move_annotation": "2.61.0.37", + "ground_ai_drive_to_pos_update": "2.61.0.37" + }, + "local_mp_loadout": { + "sem_change_aircraft_send": "2.61.0.37", + "refl_ctor": "2.61.0.37", + "datablock_dtor": "2.61.0.37", + "bullet_vec_assign": "2.61.0.37", + "get_decals_blk": "2.61.0.37", + "get_attachables_blk": "2.61.0.37", + "str_hash_fnv1": "2.61.0.37", + "namemap_add_name_id": "2.61.0.37", + "crew_skills_init": "2.61.0.37", + "refl_objects": "2.61.0.37", + "refl_names": "2.61.0.37", + "refl_flags": "2.61.0.37", + "refl_targeting": "2.61.0.37", + "refl_vertical_targeting": "2.61.0.37", + "refl_bomb_fuse": "2.61.0.37", + "respawn_spawn": "2.61.0.37", + "unit_spawn_state": "2.61.0.37", + "change_req_slot": "2.61.0.37", + "econ_clear": "2.61.0.37", + "change_req_bullets": "2.61.0.37", + "unit_crew_skills": "2.61.0.37" + }, + "local_mp_nuke": { + "shell_launch": "2.61.0.37", + "shell_instant_win": "2.61.0.37", + "shell_explode": "2.61.0.37", + "cta_logic_action": "2.61.0.37", + "mission_vars_data": "2.61.0.37", + "mission_vars_walk": "2.61.0.37", + "mission_vars_step": "2.61.0.37", + "mission_vars_value": "2.61.0.37" + }, + "local_mp_support": { + "set_controlled_unit": "2.61.0.37", + "mplayer_update": "2.61.0.37", + "mplayer_support_unit": "2.61.0.37" + }, + "local_mp_zones": { + "apply_zone_damage": "2.61.0.37", + "zone_damage_health": "2.61.0.37", + "zone_damage_team": "2.61.0.37", + "zone_damage_airfield": "2.61.0.37" + } + }, + "native_values": { + "add_kill_streak_points": "0x59e900", + "add_score_message": "0x18a2a60", + "air_ai_add_unsorted_plane": "0x80a310", + "air_event_initiate": "0x1283ce0", + "air_event_orientation": "0x12873d9", + "air_event_orientation.call": "0x280710", + "air_event_spawn_table": "0x1283ed5", + "air_event_spawn_table.battle_center": "0x1284210", + "air_event_spawn_table.max_rank": "0x7bc66bc", + "air_event_spawn_table.spawn_pos": "0x50", + "air_event_spawn_table.spawn_pos_count": "0x60", + "air_event_spawn_table.spawn_pos_stride": "0x64", + "air_event_switch_unit": "0x12870f0", + "air_event_terrain": "0x1284065", + "air_event_terrain.app_terrain": "0x3d8", + "air_event_terrain.terrain_height": "0xf9bda0", + "aircraft_change_result": "0xec0af0", + "aircraft_change_result.econ_change_req": "0xf578", + "app_econ_state": "0x1565c47", + "app_econ_state.econ_holder": "0x3f0", + "app_econ_state.econ_state": "0x9a8", + "apply_zone_damage": "0x11b21c0", + "avionics_damage": "0xfcf030", + "avionics_damage.unit": "0x8", + "avionics_exit_optic": "0xfcf28b", + "avionics_exit_optic.call": "0x15d4330", + "barrel_damage": "0x398b10", + "barrel_damage_notice": "0x398d3f", + "barrel_damage_notice.deliver": "0x19b9c00", + "barrel_damage_notice.id": "0x1e2", + "barrel_damage.unit": "0x18", + "bot_system_setup": "0x11b40b0", + "breech_damage_notice": "0x13e7888", + "breech_damage_notice.deliver": "0x19b9c00", + "breech_damage_notice.id": "0x1e4", + "breech_fire_update": "0x13e62d0", + "breech_fire_update.unit": "0x8", + "bullet_vec_assign": "0x4f1a20", + "caller_capture_zone": "0x3db470", + "caller_capture_zone.call": "0x3576a0", + "caller_hit_crit": "0xffd0ea", + "caller_hit_crit.call": "0x35bfb0", + "caller_naval_damage": "0xd087aa", + "caller_naval_damage.call": "0x35a980", + "caller_severe_damage": "0xe59b1a", + "caller_severe_damage.call": "0x35c6a0", + "change_req_bullets": "0x2dd43f", + "change_req_bullets.bullets_begin": "0xf608", + "change_req_bullets.bullets_end": "0xf610", + "change_req_slot": "0xec0cb7", + "change_req_slot.slot_id": "0xf65c", + "crew_skills_init": "0x1036c90", + "cta_logic_action": "0x11c12c0", + "datablock_dtor": "0x30a2a40", + "datablock_get_real": "0x5454620", + "datablock_get_str": "0x30a33e0", + "datablock_set_from": "0x30a21f0", + "datablock_set_from.dagmem_alloc": "0x6c04f2c", + "disabled_slots_mask": "0x6bdb80", + "disabled_slots_mask.app": "0x7bbc898", + "disabled_slots_mask.local_mplayer": "0x7b92840", + "disabled_slots_mask.mplayer_broken_slots": "0x4d0", + "disabled_slots_mask.multiplayer": "0x7b94d30", + "dispatch_assist": "0x35c240", + "do_respawn_player": "0xc6fe10", + "do_respawn_player.app_score_rules": "0x3e0", + "do_respawn_player.hero": "0x7bbe8a8", + "econ_clear": "0x2dd2e0", + "enemy_part_damage_mpi": "0xe1dc5b", + "enemy_part_damage_mpi.msg_id": "0xf104", + "enemy_part_hit_mpi": "0xe6d74f", + "enemy_part_hit_mpi.msg_id": "0xf118", + "game_save_data": "0x428419", + "game_save_data.game_save_data": "0x7c05e48", + "get_attachables_blk": "0x2e08d0", + "get_decals_blk": "0x2df980", + "get_player_country": "0x127d1c0", + "get_player_country.mp_is_local_mp": "0x61", + "get_player_country.player_count": "0x7b92860", + "get_player_country.player_table": "0x7b92850", + "get_unit_by_eid": "0x1110530", + "ground_ai_as_ground_model": "0xa21f00", + "ground_ai_drive_to_pos_update": "0x863af0", + "ground_ai_mission_binding": "0xa6eb6d", + "ground_ai_mission_binding.action": "0xa66470", + "ground_ai_move_annotation": "0xa1f084", + "ground_ai_move_annotation.inactive": "0x51", + "ground_ai_move_properties": "0x424934", + "ground_ai_move_properties.move_system": "0x20f0", + "ground_bailout": "0x428061", + "ground_bailout.bailout_dead": "0x3888", + "ground_death_flags": "0x427a90", + "ground_death_flags.already_dead": "0x2101", + "ground_death_flags.dead_silent": "0x1c19", + "ground_offenders": "0x4280ad", + "ground_offenders.killer": "0x19e8", + "ground_offenders.killer_pid": "0x1a08", + "ground_offenders.killer_uid": "0x1a40", + "ground_offenders.offender_size": "0x160", + "ground_offenders.offenders": "0x17c0", + "ground_offenders.offenders_count": "0x17d0", + "ground_offenders.unit_type": "0x8c", + "gui_state_update": "0x1565b20", + "hit_event_offender": "0x10494bd", + "hit_event_offender.offender": "0xd0", + "hit_parts_feedback": "0x104ab19", + "hit_parts_feedback.enqueue_enemy_parts": "0x189f940", + "hit_parts_feedback.hit_cam_important": "0x189fe40", + "hit_parts_feedback.naval_hit_state": "0x189ebc0", + "hit_watched_hero": "0x104950b", + "hit_watched_hero.watched_hero": "0x7bbe8b0", + "hud_damage_deliver": "0x19b96f0", + "iground_award_assists": "0x465b40", + "iground_award_assists.choose_offender": "0x498", + "iground_on_dead": "0x427a00", + "is_slot_ready_at_host": "0x17a9f30", + "kill_streak_ai_mults": "0xeb09dd", + "kill_streak_ai_mults.air_ai_mult": "0x28", + "kill_streak_ai_mults.ground_ai_mult": "0x2c", + "kill_streak_revert": "0x33ca30", + "kill_streak_rules": "0x33cad2", + "kill_streak_rules.gameplay": "0x7bbe780", + "kill_streak_rules.name_map": "0x7bbe6c0", + "kill_streak_rules.rule_count": "0x3818", + "kill_streak_rules.rule_tag": "0x3c", + "kill_streak_rules.rules": "0x3808", + "local_mpi_dispatch": "0xca17d0", + "mission_allies_country": "0x127d310", + "mission_allies_country.allies_country": "0xd0", + "mission_arcade_country": "0x127d29a", + "mission_arcade_country.arcade_country": "0x1d0", + "mission_axis_country": "0x127d328", + "mission_axis_country.axis_country": "0xc8", + "mission_custom_bots": "0x1274d9d", + "mission_custom_bots.custom_bots": "0x718", + "mission_mode_name": "0x126c598", + "mission_mode_name.mode_name": "0x48", + "mission_score_params": "0x1273572", + "mission_score_params.custom_score_params": "0x6d8", + "mission_settings_load": "0x126b5b0", + "mission_vars_data": "0x11c13b6", + "mission_vars_data.data": "0x40", + "mission_vars_step": "0x11c2040", + "mission_vars_step.name": "-0x8", + "mission_vars_step.stride": "0x20", + "mission_vars_value": "0x11c2066", + "mission_vars_value.value": "0x8", + "mission_vars_walk": "0x11c2014", + "mission_vars_walk.count": "0x50", + "mission_vars_walk.entry_bias": "0x8", + "mp_chat": "0x5be492", + "mp_chat.mp_chat": "0x1f0", + "mp_construct_local": "0x5be6c0", + "mp_construct_local.mp_chat_host": "0xf8", + "mp_construct_local.mp_is_host": "0x60", + "mp_init_chat": "0x5be400", + "mp_team_countries": "0x11b4a5f", + "mp_team_countries.team1_countries": "0x150", + "mp_team_countries.team2_countries": "0x170", + "mpi_msg_id": "0x30a0826", + "mpi_msg_id.id_offset": "0x20", + "mplayer_add_score": "0x5a0040", + "mplayer_clear_before_lobby": "0x59a3f0", + "mplayer_controlled_unit": "0x599930", + "mplayer_gui_state": "0x1565d81", + "mplayer_gui_state.gui_state": "0x640", + "mplayer_init_matching": "0x59f3d0", + "mplayer_matching": "0x59f6cf", + "mplayer_matching.match_team": "0x4", + "mplayer_matching.mp_team": "0x228", + "mplayer_matching.mp_user_id": "0xb8", + "mplayer_score": "0x5a007d", + "mplayer_score.score": "0x8f8", + "mplayer_stat_sync": "0x5a0368", + "mplayer_stat_sync.dirty": "0xa10", + "mplayer_stat_sync.payload": "0xa30", + "mplayer_streak_progress": "0x59e9ee", + "mplayer_streak_progress.progress": "0x788", + "mplayer_support_unit": "0x59e7ac", + "mplayer_support_unit.eid": "0xb58", + "mplayer_support_unit.unit": "0xb50", + "mplayer_unit_eid": "0x1298a6b", + "mplayer_unit_eid.controlled_eid": "0x880", + "mplayer_unit_eid.unit_eid": "0x850", + "mplayer_update": "0x59dfe0", + "mplayer_used_spares": "0x59ae72", + "mplayer_used_spares.used_spares": "0x520", + "namemap_add_name_id": "0xed4b0", + "net_mark_dirty": "0x3112080", + "offender_assist": "0x465e96", + "offender_assist.assist_sent": "0x148", + "offender_fields": "0x465e32", + "offender_fields.army": "0x1c", + "offender_fields.pid": "0x20", + "offender_fields.uid": "0x58", + "offender_fields.unit_army": "0x1010", + "on_unit_dead_once": "0xe5f230", + "on_unit_dead_once.skip_kill": "0x3058", + "prepare_local_mission": "0x12bf610", + "prepare_local_mission_clear": "0x12bf6a6", + "prepare_local_mission_clear.use_kill_streaks": "0x7bc6707", + "refl_bomb_fuse": "0xff5ef3", + "refl_bomb_fuse.bomb_fuse": "0xe4", + "refl_ctor": "0xcd0c60", + "refl_dtor": "0x549530", + "refl_flags": "0xff5e4a", + "refl_flags.flags": "0xd0", + "refl_names": "0x5495b2", + "refl_names.custom_skin": "0x68", + "refl_names.skin": "0x60", + "refl_names.unit": "0x50", + "refl_names.weapon": "0x58", + "refl_objects": "0x549555", + "refl_objects.attachables": "0x90", + "refl_objects.bullets": "0x190", + "refl_objects.custom_preset": "0xb0", + "refl_objects.decals": "0x70", + "refl_objects.disabled_mods": "0x140", + "refl_objects.enabled_mods": "0xf0", + "refl_stdmem": "0x5495bb", + "refl_stdmem.stdmem": "0x8036bd8", + "refl_targeting": "0xff5e7e", + "refl_targeting.gun_convergence": "0xdc", + "refl_vertical_targeting": "0xff5ebe", + "refl_vertical_targeting.vertical_targeting": "0xe0", + "respawn_spawn": "0xc7028a", + "respawn_spawn.resp_base_id": "0xbd8", + "respawn_spawn.spawn_delay_a": "0xbf4", + "respawn_spawn.spawn_pos_x": "0xbfc", + "respawn_spawn.spawn_pos_y": "0xc00", + "respawn_spawn.spawn_pos_z": "0xc04", + "respawn_spectator": "0x1a4e930", + "respawn_spectator.active": "0x7bcb2f6", + "score_msg_blk_ctor": "0x18a3b1c", + "score_msg_blk_ctor.call": "0x30a1fe0", + "score_msg_blk_dtor": "0x18a4010", + "score_msg_blk_dtor.call": "0x30a2a40", + "score_msg_blk_set_int": "0x18a3be8", + "score_msg_blk_set_int.call": "0x30a4110", + "score_msg_blk_set_str": "0x18a3bb4", + "score_msg_blk_set_str.call": "0x30a3930", + "score_msg_blk_to_owned": "0x18a3bcf", + "score_msg_blk_to_owned.call": "0x30a88a0", + "score_msg_exp_class": "0x18a3c99", + "score_msg_exp_class.exp_class": "0x38", + "score_msg_exp_class.unit_info": "0x1020", + "score_msg_hud_queue": "0x18a3fbb", + "score_msg_hud_queue.call": "0x180bf10", + "score_msg_hud_queue.queue": "0xb10", + "scoreboard_rows": "0x1298860", + "sem_change_aircraft_send": "0xccf8c0", + "send_unit_respawn": "0xff1470", + "send_unit_respawn_broadcast": "0xff1871", + "send_unit_respawn_broadcast.mpi_sendto": "0x30a0750", + "set_controlled_unit": "0x5997e0", + "set_owning_mplayer": "0xfd2b90", + "set_owning_mplayer.mp_pid": "0x8", + "set_player_gui_state": "0x1565c80", + "shell_explode": "0xbeb9f0", + "shell_instant_win": "0x14392bd", + "shell_instant_win.instant_win": "0x70", + "shell_instant_win.record": "0x18", + "shell_launch": "0x1437bd0", + "sq_local_country": "0x17a6160", + "sq_local_country.mission_settings": "0x7bc6508", + "stat_ai_ground_kills": "0x1123d8e", + "stat_ai_ground_kills.field": "0x9e6", + "stat_ai_kills": "0x1123d77", + "stat_ai_kills.field": "0x9e4", + "stat_ai_naval_kills": "0x1123da5", + "stat_ai_naval_kills.field": "0x9e8", + "stat_air_severe": "0x129930c", + "stat_air_severe.field": "0xa06", + "stat_assists": "0x1123dbc", + "stat_assists.field": "0x9ec", + "stat_award_damage": "0x1123e3b", + "stat_award_damage.field": "0xa00", + "stat_capture_zone": "0x1123dea", + "stat_capture_zone.field": "0x9ee", + "stat_deaths": "0x1123dd3", + "stat_deaths.field": "0x9dc", + "stat_ground_kills": "0x1123d1b", + "stat_ground_kills.field": "0x9de", + "stat_human_kills": "0x1123d32", + "stat_human_kills.field": "0x9e0", + "stat_kills": "0x1123d04", + "stat_kills.field": "0x9d8", + "stat_naval_kills": "0x1123d49", + "stat_naval_kills.field": "0x9e2", + "stat_score": "0x1123e17", + "stat_score.fallback": "0x2d8", + "stat_score.score": "0x8f8", + "stat_ship_severe": "0x1299338", + "stat_ship_severe.field": "0xa08", + "stat_team_kills": "0x1123d60", + "stat_team_kills.field": "0x9da", + "str_hash_fnv1": "0x21b670", + "unit_change_aircraft": "0xff5ad0", + "unit_crew_skills": "0x485e50", + "unit_crew_skills.crew_skills": "0x10a8", + "unit_info_name": "0xff5d55", + "unit_info_name.info_name": "0x10", + "unit_info_name.unit_info": "0x1020", + "unit_mplayer": "0xfd2e98", + "unit_mplayer.unit_mplayer": "0xf98", + "unit_on_event": "0x1044720", + "unit_severe": "0xe5f2f7", + "unit_severe.severe_idx": "0x6b0", + "unit_severe.severe_pid": "0x6d0", + "unit_severe.severe_uid": "0x708", + "unit_spawn_state": "0x1049b51", + "unit_spawn_state.resp_base_id": "0xbd8", + "unit_spawn_state.spawn_delay_a": "0xbf4", + "unit_spawn_state.spawn_delay_b": "0xbf8", + "unit_spawn_state.unit_mplayer": "0xf98", + "unit_type": "0xff5cbf", + "unit_type.unit_type": "0x8c", + "zone_damage_airfield": "0x11b22b7", + "zone_damage_airfield.airfield_mask": "0x4", + "zone_damage_airfield.flags": "0x98", + "zone_damage_health": "0x11b221a", + "zone_damage_health.health": "0xbc", + "zone_damage_health.max_health": "0xc0", + "zone_damage_team": "0x11b227b", + "zone_damage_team.team": "0x70" + }, + "unavailable": {} +} diff --git a/tools/src/wtotools/cli/__init__.py b/tools/src/wtotools/cli/__init__.py index f3fe7f5..70d0f76 100644 --- a/tools/src/wtotools/cli/__init__.py +++ b/tools/src/wtotools/cli/__init__.py @@ -6,7 +6,7 @@ from __future__ import annotations import argparse -from . import exe_commands, gui_commands +from . import exe_commands, gui_commands, log_commands def main(argv: list[str] | None = None) -> int: @@ -16,7 +16,7 @@ def main(argv: list[str] | None = None) -> int: formatter_class=argparse.RawDescriptionHelpFormatter, ) commands = parser.add_subparsers(dest="command", required=True) - for group in (exe_commands, gui_commands): + for group in (exe_commands, gui_commands, log_commands): group.register(commands) args = parser.parse_args(argv) return args.handler(args)