feat(mods): add official map selector mod template and move templates into mod-dev-docs

This commit is contained in:
N0VAN0M4LY committed 2026-12-03 03:01:18 +08:00
1 parent aa952e7cca
commit 6e65cec4c0
19 files changed
+574 -2

No files matched your search

@@ -46,7 +46,7 @@ export function bundledResourcePaths(): ResourcePaths {
patches: join(repository, 'patches'),
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'),
modTemplates: join(repository, 'dev-docs', 'templates', 'mods'),
modTemplates: join(repository, 'mod-dev-docs', 'templates'),
modDocs: join(repository, 'build', 'mod-dev-docs'),
};
}
@@ -0,0 +1 @@
@import "missions\mapPreferences.css"
@@ -0,0 +1,20 @@
// Register the Custom Map Pool Selector DaGui stylesheet in the root CSS manifest.
{
"id": "official-map-selector/register-css",
"title": "Include wtomapselector.css in gui/css.css",
"features": [
"Custom Map Pool Selector"
],
"variants": [
{
"written_for": "2.61.0.58",
"file": "gui/css.css",
"edits": [
{
"find": "find-css.css",
"replace": "replace-css.css"
}
]
}
]
}
@@ -0,0 +1,2 @@
@import "missions\mapPreferences.css"
@import "missions\wtomapselector.css"
@@ -0,0 +1,4 @@
function updateButtons() {
let wikiLinkBtn = showObjById("wiki_link", hasFeature("AllowExternalLink"), this.scene)
wikiLinkBtn.link = getCurCircuitOverride("wikiMatchmakerURL", loc("url/wiki_matchmaker"))
}
@@ -0,0 +1,3 @@
from "dagor.workcycle" import defer
import "%scripts/missions/mapPreferencesModal.nut" as mapPreferencesModal
import "%scripts/missions/mapPreferencesParams.nut" as mapPreferencesParams
@@ -0,0 +1,25 @@
// Wire the Custom Map Pool button in GameModeSelect to open the native WtoMapSelectorModal
// for the currently selected game mode and display the target mode name on the button.
{
"id": "official-map-selector/mode-select-button-script",
"title": "Wire Custom Map Pool button in GameModeSelect handler",
"features": [
"Custom Map Pool Selector"
],
"variants": [
{
"written_for": "2.61.0.58",
"file": "scripts/gamemodes/gamemodeselect.nut",
"edits": [
{
"find": "find-imports.nut",
"replace": "replace-imports.nut"
},
{
"find": "find-buttons.nut",
"replace": "replace-buttons.nut"
}
]
}
]
}
@@ -0,0 +1,31 @@
function updateButtons() {
let wikiLinkBtn = showObjById("wiki_link", hasFeature("AllowExternalLink"), this.scene)
wikiLinkBtn.link = getCurCircuitOverride("wikiMatchmakerURL", loc("url/wiki_matchmaker"))
this.updateWtoMapSelectorButton()
}
function updateWtoMapSelectorButton() {
let btnObj = this.scene.findObject("wto_map_selector_button")
if (!checkObj(btnObj))
return
let curGm = getCurrentGameMode()
let hasMode = curGm != null
btnObj.show(hasMode)
btnObj.enable(hasMode)
if (!hasMode)
return
let modeTitle = (curGm?.getText != null) ? curGm.getText() : (curGm?.id ?? "")
btnObj.setValue(modeTitle != ""
? loc("wto/mapSelector/btnWithMode", { mode = modeTitle })
: loc("wto/mapSelector/btnTitle"))
btnObj.tooltip = modeTitle != ""
? loc("wto/mapSelector/btnTooltipWithMode", { mode = modeTitle })
: loc("wto/mapSelector/btnTooltip")
}
function onOpenWtoMapSelector(_obj) {
let curGm = getCurrentGameMode()
if (curGm == null)
return
wtoMapSelectorModal.open({ gameMode = curGm })
}
@@ -0,0 +1,4 @@
from "dagor.workcycle" import defer
import "%scripts/missions/mapPreferencesModal.nut" as mapPreferencesModal
import "%scripts/missions/mapPreferencesParams.nut" as mapPreferencesParams
import "%scripts/missions/wtomapselectormodal.nut" as wtoMapSelectorModal
@@ -0,0 +1,7 @@
Button_text {
id:t='back_button'
text:t = '#mainmenu/btnBack'
_on_click:t = 'goBack'
btnName:t='B'
ButtonImg {}
}
@@ -0,0 +1,20 @@
// Add the Custom Map Pool button on the right side of the Mode Selection footer bar.
{
"id": "official-map-selector/mode-select-button-tpl",
"title": "Add Custom Map Pool button to Mode Selection template",
"features": [
"Custom Map Pool Selector"
],
"variants": [
{
"written_for": "2.61.0.58",
"file": "gui/gamemodeselect/gamemodeselect.tpl",
"edits": [
{
"find": "find-nav-right.tpl",
"replace": "replace-nav-right.tpl"
}
]
}
]
}
@@ -0,0 +1,16 @@
Button_text {
id:t='wto_map_selector_button'
text:t='#wto/mapSelector/btnTitle'
tooltip:t='#wto/mapSelector/btnTooltip'
on_click:t='onOpenWtoMapSelector'
visualStyle:t='secondary'
ButtonImg {}
}
Button_text {
id:t='back_button'
text:t = '#mainmenu/btnBack'
_on_click:t = 'goBack'
btnName:t='B'
ButtonImg {}
}
@@ -0,0 +1,19 @@
// Official bundled additive mod: Custom Map Pool Selector.
// Adds a native DaGui map pool selector modal to the Mode Selection UI and enforces per-mode
// whitelist / unlimited blacklist rules during local battle matchmaking.
{
"format": 1,
"id": "official.map-selector",
"name": {
"zh-CN": "官方模组:自定义匹配地图池",
"en": "Official Mod: Custom Map Pool Selector"
},
"version": "0.1.0",
"author": "WTOffline",
"description": {
"zh-CN": "在模式选择界面新增自定义地图池弹窗,支持按模式设置全部地图、白名单(仅匹配所选)或无上限黑名单(排除所选),并附带原生小地图预览。",
"en": "Adds a native Custom Map Pool modal to the Mode Selection screen with per-mode All, Whitelist (only selected), and unlimited Blacklist (exclude selected) rules plus native map thumbnails."
},
"api_version": "0.1-experimental",
"game_versions": ["2.61.0.*"]
}
@@ -0,0 +1,420 @@
/**
* 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;
});
},
};
+1 -1
View File
@@ -71,7 +71,7 @@ async function stageInstaller(stage: string, manifest: LauncherManifest): Promis
await cp(join(launcher, 'resources', 'icon.png'), join(resources, 'icon.png'));
await cp(join(repository, 'LICENSE'), join(resources, 'LICENSE-WTOffline'));
await cp(join(native, 'wto_ws.dll'), join(resources, 'native', 'wto_ws.dll'));
await cp(join(repository, 'dev-docs', 'templates', 'mods'), join(resources, 'mod-templates'), { recursive: true });
await cp(join(repository, 'mod-dev-docs', 'templates'), join(resources, 'mod-templates'), { recursive: true });
buildOfflineModDocs(join(repository, 'mod-dev-docs'), join(resources, 'mod-dev-docs'));
for (const folder of ['exe', 'gui', 'native', 'versions']) {
await cp(join(repository, 'patches', folder), join(resources, 'patches', folder), { recursive: true });