feat(mods): add battle.onFilterMissions hook and per-template bundled seeding

This commit is contained in:
N0VAN0M4LY committed 2026-12-03 02:40:38 +08:00
1 parent 8636d0b71d
commit 5983e3f3e2
6 files changed
+127 -20

No files matched your search

@@ -40,10 +40,10 @@ export async function resolveModsFolder(): Promise<{ readonly modsDir: string; r
}
/**
* Copy the bundled example mod templates into a fresh mods folder once so players and authors
* have ready-to-inspect templates (disabled by default). Serialized per directory so concurrent
* startup calls (such as React StrictMode double mounts) wait for the copy to finish before
* scanning mods.
* Copy newly shipped bundled template mods into the mods folder once each (disabled by default).
* Tracks which template folder names have already been seeded in `.wto-examples-seeded` so
* deleting a bundled template never restores it, while newly added official templates still
* appear for existing users. Serialized per directory to prevent concurrent seeding races.
*/
async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
const key = modsDir.toLowerCase();
@@ -54,22 +54,25 @@ async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
}
const task = (async () => {
const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER);
if (await pathExists(markerPath)) return;
try {
const existingEntries = await readdir(modsDir);
if (existingEntries.length === 0) {
const templatesRoot = resourcePaths().modTemplates;
if (await pathExists(templatesRoot)) {
const templates = await readdir(templatesRoot, { withFileTypes: true });
for (const entry of templates) {
if (!entry.isDirectory()) continue;
const dest = join(modsDir, entry.name);
if (await pathExists(dest)) continue;
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
}
const templatesRoot = resourcePaths().modTemplates;
if (!(await pathExists(templatesRoot))) return;
const seeded = await readSeededTemplateNames(markerPath, modsDir);
const templates = await readdir(templatesRoot, { withFileTypes: true });
let changed = false;
for (const entry of templates) {
if (!entry.isDirectory()) continue;
if (seeded.has(entry.name)) continue;
const dest = join(modsDir, entry.name);
if (!(await pathExists(dest))) {
await cp(join(templatesRoot, entry.name), dest, { recursive: true });
}
seeded.add(entry.name);
changed = true;
}
if (changed || !(await pathExists(markerPath))) {
await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8');
}
await writeFile(markerPath, '1\n', 'utf8');
} catch (error) {
console.warn('[mods] seeding bundled example mods skipped:', error);
}
@@ -80,6 +83,26 @@ async function seedBundledExampleModsOnce(modsDir: string): Promise<void> {
await task;
}
async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise<Set<string>> {
if (!(await pathExists(markerPath))) return new Set();
try {
const raw = (await readFile(markerPath, 'utf8')).trim();
if (raw === '1') {
// Legacy marker from initial 2-template version: mark existing folders as already seeded
// so newly added official templates (e.g. official-map-selector) are still delivered once.
const existing = await readdir(modsDir);
const set = new Set(['example-vehicle-tweak', 'example-server-script']);
for (const name of existing) set.add(name);
return set;
}
const parsed = JSON.parse(raw) as { seeded?: unknown };
if (Array.isArray(parsed.seeded)) {
return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string'));
}
} catch { /* ignore */ }
return new Set();
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
+27 -2
View File
@@ -85,6 +85,16 @@ export type MatchmakeOutcome =
| { readonly ok: true; readonly launch: BattleLaunchPlan }
| { readonly ok: false; readonly error: string };
export type MissionPoolFilter = (ctx: {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly MissionHeader[];
}) => readonly MissionHeader[];
export class BattleMatchmaker {
readonly #gameModes: GameModes;
readonly #vehicles: readonly CatalogueVehicle[];
@@ -93,6 +103,7 @@ export class BattleMatchmaker {
readonly #tuning: BattleTuning;
readonly #spawnRules: BattleSpawnRulesData;
readonly #aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>;
readonly #filterMissions: MissionPoolFilter | undefined;
constructor(
gameModes: GameModes,
@@ -101,6 +112,7 @@ export class BattleMatchmaker {
tuning: BattleTuning,
spawnRules: BattleSpawnRulesData,
aircraftLoadouts: ReadonlyMap<string, BotAircraftLoadout>,
filterMissions?: MissionPoolFilter,
) {
this.#gameModes = gameModes;
this.#vehicles = vehicles;
@@ -109,6 +121,7 @@ export class BattleMatchmaker {
this.#tuning = tuning;
this.#spawnRules = spawnRules;
this.#aircraftLoadouts = aircraftLoadouts;
this.#filterMissions = filterMissions;
}
enqueue(input: EnqueueBattleInput): MatchmakeOutcome {
@@ -132,8 +145,20 @@ export class BattleMatchmaker {
const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank);
const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity;
const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank));
const missions = twoSidedMissionsOf(chosenMode, maxMrank);
if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank);
if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' };
const filteredMissions = this.#filterMissions
? this.#filterMissions({
userId: input.userId,
modeId: declaration.gameModeId,
modeName: declaration.name,
economicName: declaration.economicName,
minMrank,
maxMrank,
missions: rawMissions,
})
: rawMissions;
const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions;
const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions);
const coalitions = selectBattleCoalitions({
vehicles: this.#vehicles,
@@ -11,8 +11,10 @@ import { pathToFileURL } from 'node:url';
import type { BlkBlock } from '@wto/blk';
import {
MOD_API_VERSION,
type BattleFilterMissionsContext,
type BattleLiveFactContext,
type BattleMatchmakeContext,
type BattleMissionCandidate,
type BattleSettlementContext,
type DiscoveredMod,
type ModCharHandler,
@@ -54,6 +56,7 @@ export class ServerModRuntime {
readonly #onServerClosing: ScopedHandler<() => void | Promise<void>>[] = [];
readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = [];
readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = [];
readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = [];
readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = [];
readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = [];
readonly #charHandlers = new Map<string, ScopedHandler<ModCharHandler>>();
@@ -172,6 +175,30 @@ export class ServerModRuntime {
}
}
runBattleFilterMissions<T extends BattleMissionCandidate>(
ctx: Omit<BattleFilterMissionsContext, 'missions'> & { readonly missions: readonly T[] },
): readonly T[] {
if (this.#onFilterMissions.length === 0) return ctx.missions;
let current: readonly T[] = ctx.missions;
for (const { modId, fn } of this.#onFilterMissions) {
try {
const next = fn({ ...ctx, missions: current });
if (Array.isArray(next)) {
const allowed = new Set(next.map((item) => item.name));
const filtered = current.filter((item) => allowed.has(item.name));
if (filtered.length > 0) {
current = filtered;
} else {
this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`);
}
}
} catch (error) {
this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`);
}
}
return current;
}
runBattleLiveFact(ctx: BattleLiveFactContext): void {
for (const { modId, fn } of this.#onLiveFact) {
try {
@@ -284,6 +311,7 @@ export class ServerModRuntime {
},
battle: {
onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); },
onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); },
onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); },
onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); },
},
+9 -1
View File
@@ -179,7 +179,15 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
matching?.notifyUser(userId, eventName, payload);
};
const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept);
const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules, botAircraftLoadouts);
const battleMatchmaker = new BattleMatchmaker(
gameModes,
vehicles,
battleSessions,
tuning.battle,
spawnRules,
botAircraftLoadouts,
(ctx) => modRuntime.runBattleFilterMissions(ctx),
);
const economy = new BattleEconomy(
economyData,
tuning.battleEconomy,
+2
View File
@@ -54,8 +54,10 @@ export {
export { mergeLocalizationCsv } from './csv-patch.ts';
export { mergeTuningLayer, type TuningListOp } from './tuning-merge.ts';
export type {
BattleFilterMissionsContext,
BattleLiveFactContext,
BattleMatchmakeContext,
BattleMissionCandidate,
BattleSettlementContext,
ModCharHandler,
ModCharRequest,
+21
View File
@@ -73,6 +73,25 @@ export interface BattleMatchmakeContext {
readonly request: Record<string, unknown>;
}
export interface BattleMissionCandidate {
readonly name: string;
readonly path: string;
readonly level?: string;
readonly type?: string;
readonly locName?: string;
readonly postfix?: string;
}
export interface BattleFilterMissionsContext {
readonly userId: string;
readonly modeId: number;
readonly modeName: string;
readonly economicName: string;
readonly minMrank: number;
readonly maxMrank: number;
readonly missions: readonly BattleMissionCandidate[];
}
export interface BattleLiveFactContext {
readonly userId: string;
readonly roomId: string;
@@ -146,6 +165,8 @@ export interface ServerModHooksApi {
};
readonly battle: {
onBeforeMatchmake(handler: (ctx: BattleMatchmakeContext) => void): void;
/** Filter or reorder candidate missions before matchmaking picks one; return the desired subset. */
onFilterMissions(handler: (ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void): void;
onLiveFact(handler: (ctx: BattleLiveFactContext) => void): void;
onAfterSettle(handler: (ctx: BattleSettlementContext) => void): void;
};