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/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/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}`); +}