421 lines
14 KiB
TypeScript
421 lines
14 KiB
TypeScript
/**
|
|
* Official WTOffline Mod: Custom Map Pool Selector (`official.map-selector`).
|
|
*
|
|
* Indexes each offered PvP game mode's playable two-sided missions grouped by location/level id,
|
|
* exposes matching RPC endpoints (`wto_mod.map_selector.get` / `wto_mod.map_selector.set`) backed
|
|
* by per-account isolated mod storage, and enforces whitelist/blacklist rules via
|
|
* `battle.onFilterMissions`.
|
|
*/
|
|
|
|
type FilterMode = 'all' | 'include' | 'exclude';
|
|
|
|
interface ModeMapRule {
|
|
filterMode: FilterMode;
|
|
selectedMaps: string[];
|
|
}
|
|
|
|
interface PlayerMapSelectorStore {
|
|
version: 1;
|
|
modes: Record<string, ModeMapRule>;
|
|
}
|
|
|
|
interface MissionSlotsView {
|
|
readonly teamA: number;
|
|
readonly teamB: number;
|
|
}
|
|
|
|
interface MissionHeaderView {
|
|
readonly name: string;
|
|
readonly path: string;
|
|
readonly level?: string;
|
|
readonly playerSlots?: MissionSlotsView;
|
|
}
|
|
|
|
interface GameModeDeclarationView {
|
|
readonly gameModeId: number;
|
|
readonly name: string;
|
|
readonly tag?: string;
|
|
readonly economicName: string;
|
|
readonly displayType?: string;
|
|
}
|
|
|
|
interface OfferedGameModeView {
|
|
readonly declaration: GameModeDeclarationView;
|
|
readonly missions: readonly MissionHeaderView[];
|
|
}
|
|
|
|
interface GameModesCatalogueView {
|
|
ids(): number[];
|
|
byId(id: number): OfferedGameModeView | undefined;
|
|
byName(name: string): OfferedGameModeView | undefined;
|
|
byEconomicName(economicName: string): readonly OfferedGameModeView[];
|
|
}
|
|
|
|
interface MapPoolItem {
|
|
readonly id: string;
|
|
readonly sampleMission: string;
|
|
readonly missionCount: number;
|
|
}
|
|
|
|
interface ModeMapPool {
|
|
readonly modeName: string;
|
|
readonly economicName: string;
|
|
readonly maps: readonly MapPoolItem[];
|
|
readonly mapIdSet: ReadonlySet<string>;
|
|
}
|
|
|
|
interface BattleMissionCandidateView {
|
|
readonly name: string;
|
|
readonly path: string;
|
|
readonly level?: string;
|
|
}
|
|
|
|
interface BattleFilterContextView {
|
|
readonly userId: string;
|
|
readonly modeId: number;
|
|
readonly modeName: string;
|
|
readonly economicName: string;
|
|
readonly minMrank: number;
|
|
readonly maxMrank: number;
|
|
readonly missions: readonly BattleMissionCandidateView[];
|
|
}
|
|
|
|
interface ModMatchingRequestView {
|
|
readonly method: string;
|
|
readonly params: Readonly<Record<string, unknown>>;
|
|
readonly userId: string | undefined;
|
|
}
|
|
|
|
interface ServerModContextView {
|
|
readonly logger: {
|
|
info(message: string): void;
|
|
warn(message: string): void;
|
|
error(message: string): void;
|
|
};
|
|
readonly storage: {
|
|
forPlayer(userId: string): {
|
|
read<T = unknown>(): T | undefined;
|
|
write(value: unknown): void;
|
|
};
|
|
};
|
|
readonly hooks: {
|
|
onCataloguesReady(handler: (catalogues: { readonly gameModes: unknown }) => void): void;
|
|
readonly battle: {
|
|
onFilterMissions(
|
|
handler: (ctx: BattleFilterContextView) => readonly BattleMissionCandidateView[] | void,
|
|
): void;
|
|
};
|
|
};
|
|
readonly routes: {
|
|
readonly matching: {
|
|
register(method: string, handler: (request: ModMatchingRequestView) => Record<string, unknown>): void;
|
|
};
|
|
};
|
|
}
|
|
|
|
const VALID_FILTER_MODES = new Set<FilterMode>(['all', 'include', 'exclude']);
|
|
|
|
/**
|
|
* Normalize a mission's `level` path (e.g. `levels/avg_poland.bin`) into a lowercase location id
|
|
* (`avg_poland`). Falls back to the mission name when `level` is absent.
|
|
*/
|
|
function normalizeMapId(level: string | undefined, missionName: string): string {
|
|
const raw = typeof level === 'string' ? level.trim() : '';
|
|
if (raw.length > 0) {
|
|
const unified = raw.replaceAll('\\', '/');
|
|
const slashIdx = unified.lastIndexOf('/');
|
|
const baseName = slashIdx >= 0 ? unified.slice(slashIdx + 1) : unified;
|
|
const withoutBin = baseName.toLowerCase().endsWith('.bin')
|
|
? baseName.slice(0, -4)
|
|
: baseName;
|
|
const normalized = withoutBin.trim().toLowerCase();
|
|
if (normalized.length > 0) return normalized;
|
|
}
|
|
return missionName.trim().toLowerCase();
|
|
}
|
|
|
|
function isTwoSidedMission(mission: MissionHeaderView): boolean {
|
|
if (!mission.playerSlots) return true;
|
|
return mission.playerSlots.teamA > 0 && mission.playerSlots.teamB > 0;
|
|
}
|
|
|
|
function isGameModesCatalogue(value: unknown): value is GameModesCatalogueView {
|
|
if (typeof value !== 'object' || value === null) return false;
|
|
const candidate = value as Record<string, unknown>;
|
|
return (
|
|
typeof candidate.ids === 'function' &&
|
|
typeof candidate.byId === 'function' &&
|
|
typeof candidate.byName === 'function' &&
|
|
typeof candidate.byEconomicName === 'function'
|
|
);
|
|
}
|
|
|
|
function sanitizeFilterMode(raw: unknown): FilterMode | undefined {
|
|
if (typeof raw !== 'string') return undefined;
|
|
const lowered = raw.trim().toLowerCase() as FilterMode;
|
|
return VALID_FILTER_MODES.has(lowered) ? lowered : undefined;
|
|
}
|
|
|
|
function sanitizeSelectedMaps(raw: unknown): string[] {
|
|
if (!Array.isArray(raw)) return [];
|
|
const seen = new Set<string>();
|
|
const out: string[] = [];
|
|
for (const item of raw) {
|
|
if (typeof item !== 'string') continue;
|
|
const id = item.trim().toLowerCase();
|
|
if (id.length === 0 || seen.has(id)) continue;
|
|
seen.add(id);
|
|
out.push(id);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function readPlayerStore(
|
|
storage: ServerModContextView['storage'],
|
|
userId: string,
|
|
): PlayerMapSelectorStore {
|
|
const raw = storage.forPlayer(userId).read<unknown>();
|
|
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
return { version: 1, modes: {} };
|
|
}
|
|
const obj = raw as Record<string, unknown>;
|
|
const rawModes = obj.modes;
|
|
if (typeof rawModes !== 'object' || rawModes === null || Array.isArray(rawModes)) {
|
|
return { version: 1, modes: {} };
|
|
}
|
|
const modes: Record<string, ModeMapRule> = {};
|
|
for (const [modeKey, entry] of Object.entries(rawModes as Record<string, unknown>)) {
|
|
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) continue;
|
|
const rec = entry as Record<string, unknown>;
|
|
const filterMode = sanitizeFilterMode(rec.filterMode) ?? 'all';
|
|
const selectedMaps = sanitizeSelectedMaps(rec.selectedMaps);
|
|
modes[modeKey] = { filterMode, selectedMaps };
|
|
}
|
|
return { version: 1, modes };
|
|
}
|
|
|
|
function buildModePools(gameModes: GameModesCatalogueView): {
|
|
readonly byModeName: Map<string, ModeMapPool>;
|
|
readonly byEconomicName: Map<string, ModeMapPool>;
|
|
} {
|
|
const byModeName = new Map<string, ModeMapPool>();
|
|
const byEconomicName = new Map<string, ModeMapPool>();
|
|
|
|
// Group offered PvP modes by their primary mode name, keeping primary (untagged) modes first
|
|
// so sample missions come from the classic pool before sub-mode additions.
|
|
const groupedModes = new Map<string, OfferedGameModeView[]>();
|
|
for (const id of gameModes.ids()) {
|
|
const offered = gameModes.byId(id);
|
|
if (!offered) continue;
|
|
if (offered.declaration.displayType === 'pve_battle') continue;
|
|
const key = offered.declaration.name;
|
|
const bucket = groupedModes.get(key) ?? [];
|
|
bucket.push(offered);
|
|
groupedModes.set(key, bucket);
|
|
}
|
|
|
|
for (const [modeName, modes] of groupedModes) {
|
|
modes.sort((left, right) => {
|
|
const leftTagged = left.declaration.tag ? 1 : 0;
|
|
const rightTagged = right.declaration.tag ? 1 : 0;
|
|
return leftTagged - rightTagged || left.declaration.gameModeId - right.declaration.gameModeId;
|
|
});
|
|
|
|
const economicName = modes[0]!.declaration.economicName;
|
|
const byMapId = new Map<string, { sampleMission: string; missionNames: Set<string> }>();
|
|
|
|
for (const offered of modes) {
|
|
for (const mission of offered.missions) {
|
|
if (!isTwoSidedMission(mission)) continue;
|
|
const mapId = normalizeMapId(mission.level, mission.name);
|
|
const existing = byMapId.get(mapId);
|
|
if (existing) {
|
|
existing.missionNames.add(mission.name);
|
|
} else {
|
|
byMapId.set(mapId, {
|
|
sampleMission: mission.name,
|
|
missionNames: new Set([mission.name]),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
if (byMapId.size === 0) continue;
|
|
|
|
const maps: MapPoolItem[] = [...byMapId.entries()]
|
|
.sort(([leftId], [rightId]) => leftId.localeCompare(rightId))
|
|
.map(([id, info]) => ({
|
|
id,
|
|
sampleMission: info.sampleMission,
|
|
missionCount: info.missionNames.size,
|
|
}));
|
|
|
|
const pool: ModeMapPool = {
|
|
modeName,
|
|
economicName,
|
|
maps,
|
|
mapIdSet: new Set(maps.map((item) => item.id)),
|
|
};
|
|
|
|
byModeName.set(modeName, pool);
|
|
if (!byEconomicName.has(economicName)) {
|
|
byEconomicName.set(economicName, pool);
|
|
}
|
|
}
|
|
|
|
return { byModeName, byEconomicName };
|
|
}
|
|
|
|
function readOptionalString(params: Readonly<Record<string, unknown>>, key: string): string {
|
|
const value = params[key];
|
|
return typeof value === 'string' ? value.trim() : '';
|
|
}
|
|
|
|
export default {
|
|
setup(ctx: ServerModContextView) {
|
|
let poolsByModeName = new Map<string, ModeMapPool>();
|
|
let poolsByEconomicName = new Map<string, ModeMapPool>();
|
|
|
|
const resolvePool = (modeName: string, economicName: string): ModeMapPool | undefined => {
|
|
if (modeName) {
|
|
const direct = poolsByModeName.get(modeName) ?? poolsByEconomicName.get(modeName);
|
|
if (direct) return direct;
|
|
}
|
|
if (economicName) {
|
|
return poolsByEconomicName.get(economicName) ?? poolsByModeName.get(economicName);
|
|
}
|
|
return undefined;
|
|
};
|
|
|
|
const lookupSavedRule = (
|
|
store: PlayerMapSelectorStore,
|
|
modeName: string,
|
|
economicName: string,
|
|
): ModeMapRule | undefined => {
|
|
if (modeName && store.modes[modeName]) return store.modes[modeName];
|
|
if (economicName && store.modes[economicName]) return store.modes[economicName];
|
|
return undefined;
|
|
};
|
|
|
|
ctx.hooks.onCataloguesReady((catalogues) => {
|
|
if (!isGameModesCatalogue(catalogues.gameModes)) {
|
|
ctx.logger.warn('gameModes catalogue did not match expected shape; map selector pools remain empty');
|
|
return;
|
|
}
|
|
const indexed = buildModePools(catalogues.gameModes);
|
|
poolsByModeName = indexed.byModeName;
|
|
poolsByEconomicName = indexed.byEconomicName;
|
|
ctx.logger.info(`indexed map pools for ${poolsByModeName.size} game modes`);
|
|
});
|
|
|
|
ctx.routes.matching.register('wto_mod.map_selector.get', (request) => {
|
|
const userId = request.userId;
|
|
if (!userId) {
|
|
return {
|
|
ok: false,
|
|
error: 'AUTH_REQUIRED',
|
|
modeName: '',
|
|
filterMode: 'all',
|
|
selectedMaps: [],
|
|
maps: [],
|
|
};
|
|
}
|
|
|
|
const requestedMode = readOptionalString(request.params, 'modeName');
|
|
const requestedEconomic = readOptionalString(request.params, 'economicName');
|
|
const pool = resolvePool(requestedMode, requestedEconomic);
|
|
if (!pool) {
|
|
return {
|
|
ok: true,
|
|
modeName: requestedMode || requestedEconomic,
|
|
filterMode: 'all',
|
|
selectedMaps: [],
|
|
maps: [],
|
|
};
|
|
}
|
|
|
|
const store = readPlayerStore(ctx.storage, userId);
|
|
const saved = lookupSavedRule(store, pool.modeName, pool.economicName);
|
|
const filterMode: FilterMode = saved?.filterMode ?? 'all';
|
|
const selectedMaps = saved
|
|
? saved.selectedMaps.filter((mapId) => pool.mapIdSet.has(mapId))
|
|
: [];
|
|
|
|
return {
|
|
ok: true,
|
|
modeName: pool.modeName,
|
|
economicName: pool.economicName,
|
|
filterMode,
|
|
selectedMaps,
|
|
maps: pool.maps.map((item) => ({
|
|
id: item.id,
|
|
sampleMission: item.sampleMission,
|
|
missionCount: item.missionCount,
|
|
})),
|
|
};
|
|
});
|
|
|
|
ctx.routes.matching.register('wto_mod.map_selector.set', (request) => {
|
|
const userId = request.userId;
|
|
if (!userId) {
|
|
return { ok: false, error: 'AUTH_REQUIRED' };
|
|
}
|
|
|
|
const requestedMode = readOptionalString(request.params, 'modeName');
|
|
const requestedEconomic = readOptionalString(request.params, 'economicName');
|
|
const pool = resolvePool(requestedMode, requestedEconomic);
|
|
const canonicalMode = pool?.modeName ?? requestedMode;
|
|
if (!canonicalMode) {
|
|
return { ok: false, error: 'INVALID_MODE' };
|
|
}
|
|
|
|
const filterMode = sanitizeFilterMode(request.params.filterMode);
|
|
if (!filterMode) {
|
|
return { ok: false, error: 'INVALID_FILTER_MODE' };
|
|
}
|
|
|
|
const rawSelected = sanitizeSelectedMaps(request.params.selectedMaps);
|
|
const selectedMaps = pool
|
|
? rawSelected.filter((mapId) => pool.mapIdSet.has(mapId))
|
|
: rawSelected;
|
|
|
|
const store = readPlayerStore(ctx.storage, userId);
|
|
store.modes[canonicalMode] = { filterMode, selectedMaps };
|
|
ctx.storage.forPlayer(userId).write(store);
|
|
|
|
ctx.logger.info(
|
|
`saved map rule for user=${userId} mode=${canonicalMode} filter=${filterMode} selected=${selectedMaps.length}`,
|
|
);
|
|
return {
|
|
ok: true,
|
|
modeName: canonicalMode,
|
|
filterMode,
|
|
selectedMaps,
|
|
};
|
|
});
|
|
|
|
ctx.hooks.battle.onFilterMissions((battleCtx) => {
|
|
const store = readPlayerStore(ctx.storage, battleCtx.userId);
|
|
const rule = lookupSavedRule(store, battleCtx.modeName, battleCtx.economicName);
|
|
if (!rule || rule.filterMode === 'all' || rule.selectedMaps.length === 0) {
|
|
return undefined;
|
|
}
|
|
|
|
const selectedSet = new Set(rule.selectedMaps);
|
|
const filtered = battleCtx.missions.filter((mission) => {
|
|
const mapId = normalizeMapId(mission.level, mission.name);
|
|
return rule.filterMode === 'include' ? selectedSet.has(mapId) : !selectedSet.has(mapId);
|
|
});
|
|
|
|
if (filtered.length === 0) {
|
|
ctx.logger.warn(
|
|
`map filter (${rule.filterMode}, ${rule.selectedMaps.length} selected) matched 0/${battleCtx.missions.length} missions for ${battleCtx.modeName} (mrank ${battleCtx.minMrank}..${battleCtx.maxMrank}); falling back to full pool`,
|
|
);
|
|
return undefined;
|
|
}
|
|
|
|
return filtered;
|
|
});
|
|
},
|
|
};
|