summaryrefslogtreecommitdiff
path: root/web/src/lib/data/gameData.ts
blob: 10e1c607cd723d5f8bfecaa1b7a3fc3b0fec7a31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/**
 * Loads the campaign/character/monster/scenario data the menus read, from
 * the same JSON files the engine uses (served at `/data/` by the Dart
 * server). The reference app ships these as bundled assets; here the
 * server is the single source and the client fetches on demand and caches.
 */

import type {
	GraphicPositional,
	MonsterAbilityCard
} from '../protocol/types';

// --- Raw JSON shapes (the subset the UI needs) ----------------------------

interface RawClass {
	name: string;
	edition: string;
	health: number[];
	hidden?: boolean;
	color: string | string[];
	colorSecondary?: string | string[];
	/** `adds`/`removes` per perk slot (the reference `PerkModel`). */
	perks?: { text?: string; adds?: string[]; removes?: string[] }[];
	perksFH?: { text?: string; adds?: string[]; removes?: string[] }[];
}

interface RawMonsterStats {
	health: number | string;
	[ key: string ]: unknown;
}
interface RawMonsterLevel {
	level: number;
	normal?: RawMonsterStats;
	elite?: RawMonsterStats;
	boss?: RawMonsterStats;
}
interface RawMonster {
	deck: string;
	count: number;
	levels: RawMonsterLevel[];
	display?: string;
	gfx?: string;
	hidden?: boolean;
	flying?: boolean;
}
interface RawScenario {
	monsters?: string[];
	lootDeck?: Record<string, number>;
	special?: unknown[];
	initialMessage?: string;
}
interface RawEdition {
	edition: string;
	classes: RawClass[];
	monsters: Record<string, RawMonster>;
	scenarios: Record<string, RawScenario>;
	/** Monster ability-card decks (the reference `MonsterAbilityDeckModel`). */
	monsterAbilities?: RawMonsterAbilityDeck[];
}

interface RawMonsterAbilityDeck {
	name: string;
	edition: string;
	cards: unknown[];
}

// --- UI-facing types -------------------------------------------------------

export interface ClassData {
	id: string;
	name: string;
	edition: string;
	hidden: boolean;
	health: number[];
	color: string;
	colorSecondary: string;
	/** `/images/class-icons/<name>.png` */
	icon: string;
	/** The `adds` graphic list per perk slot (the reference `perks`). */
	perks: string[][];
	perksFH: string[][];
	/** The full perk-slot data (text + adds + removes) for the perks menu. */
	perkDetails: PerkDetail[];
	perkDetailsFH: PerkDetail[];
}

/** One perk slot (the reference `PerkModel`). */
export interface PerkDetail {
	text: string;
	adds: string[];
	removes: string[];
}

export interface MonsterData {
	name: string;
	display: string;
	gfx: string;
	deck: string;
	count: number;
	hidden: boolean;
	flying: boolean;
	levels: RawMonsterLevel[];
	maxLevel: number;
	/** The first level has a boss block. */
	isBoss: boolean;
	edition: string;
	/** `/images/monsters/<gfx>.png` */
	portrait: string;
}

export interface ScenarioData {
	name: string;
	monsters: string[];
}

export interface CampaignData {
	edition: string;
	classes: ClassData[];
	monsters: MonsterData[];
	/** Scenario names in file order. */
	scenarios: ScenarioData[];
	/**
	 * Monster ability-card decks, keyed by deck name (the reference
	 * `MonsterAbilityDeckModel`). The client reconstructs full cards from
	 * these when state references a card by `{nr, deck}`.
	 */
	abilityDecks: Record<string, MonsterAbilityCard[]>;
}

export function firstColor(value: string | string[] | undefined, fallback = '000000') {
	const v = Array.isArray(value) ? value[0] : value;
	return v ?? fallback;
}

function escapePathSegment(value: string): string {
	return encodeURIComponent(value);
}

/**
 * Parse one ability-card raw entry into a full {@link MonsterAbilityCard}.
 * Mirrors the reference `MonsterAbilityDeckModel.fromJson`: the card is a
 * JSON array of `[optionalTitle, nr, shuffle, initiative, optionalGraphics,
 * ...lines]` where the title (a leading string) and the graphics list (at
 * index 3, a list of `{gfx,x,y,scale?,angle?}`) are both optional.
 */
function parseAbilityCard(raw: unknown[], deckName: string): MonsterAbilityCard {
	let title = deckName;
	let arr = raw;
	if (typeof arr[0] === 'string') {
		title = arr[0] as string;
		arr = arr.slice(1);
	}
	const nr = arr[0] as number;
	const shuffle = arr[1] as boolean;
	const initiative = arr[2] as number;
	let rest = arr.slice(3);
	let graphics: GraphicPositional[] = [];
	if (Array.isArray(rest[0])) {
		graphics = (rest[0] as Array<Record<string, unknown>>).map((g) => ({
			gfx: g.gfx as string,
			x: g.x as number,
			y: g.y as number,
			scale: (g.scale as number | undefined) ?? 1,
			angle: (g.angle as number | undefined) ?? 0
		}));
		rest = rest.slice(1);
	}
	return {
		title,
		nr,
		shuffle,
		initiative,
		lines: rest as string[],
		deck: deckName,
		graphics
	};
}

// --- The loader ------------------------------------------------------------

export class GameDataClient {
	private campaignsPromise: Promise<string[]> | null = null;
	private campaignsCache: string[] | null = null;
	private readonly cache = new Map<string, Promise<CampaignData>>();
	/** Resolved campaign data (populated as each fetch lands) for sync lookups. */
	private readonly loaded = new Map<string, CampaignData>();
	private readonly roomsCache = new Map<string, Promise<Record<string, Record<string, unknown>[]> | null>>();

	constructor(private readonly base = '/data') {}

	/** The list of campaign/edition names (order from `editions.json`). */
	campaigns(): Promise<string[]> {
		if (this.campaignsCache) return Promise.resolve(this.campaignsCache);
		if (this.campaignsPromise) return this.campaignsPromise;
		this.campaignsPromise = fetch(`${this.base}/editions/editions.json`)
			.then((r) => r.json())
			.then((d: { editions: string[] }) => {
				this.campaignsCache = d.editions;
				return d.editions;
			});
		return this.campaignsPromise;
	}

	/** Character classes, monsters, and scenario names for a campaign. */
	loadCampaign(campaign: string): Promise<CampaignData> {
		const cached = this.cache.get(campaign);
		if (cached) return cached;
		const promise = fetch(
			`${this.base}/editions/${escapePathSegment(campaign)}.json`
		)
			.then((r) => {
				if (!r.ok) throw new Error(`failed to load campaign ${campaign}`);
				return r.json();
			})
			.then((raw: RawEdition) => {
				const abilityDecks: Record<string, MonsterAbilityCard[]> = {};
				for (const deck of raw.monsterAbilities ?? []) {
					abilityDecks[deck.name] = deck.cards.map((c) =>
						parseAbilityCard(c as unknown[], deck.name)
					);
				}
				const data: CampaignData = {
					edition: raw.edition,
					classes: raw.classes.map((c) => this.toClass(c)),
					monsters: Object.entries(raw.monsters).map(([name, m]) =>
						this.toMonster(name, m, raw.edition)
					),
					scenarios: Object.entries(raw.scenarios).map(([name, s]) => ({
						name,
						monsters: s.monsters ?? []
					})),
					abilityDecks
				};
				this.loaded.set(campaign, data);
				return data;
			});
		this.cache.set(campaign, promise);
		return promise;
	}

	/**
	 * The monster model for [name] in [campaign] (by name or display name),
	 * or null when the campaign data is not yet loaded. Used to resolve a
	 * state monster (keyed by model name) to its stats, deck, and art.
	 */
	findMonster(campaign: string, name: string): MonsterData | null {
		const data = this.loaded.get(campaign);
		if (!data) return null;
		return (
			data.monsters.find((m) => m.name === name || m.display === name) ?? null
		);
	}

	/** The ability cards for a monster-ability [deck] in [campaign]. */
	abilityCards(campaign: string, deck: string): MonsterAbilityCard[] {
		return this.loaded.get(campaign)?.abilityDecks[deck] ?? [];
	}

	/**
	 * The full ability card for a state reference `{deck, nr}` in [campaign] —
	 * the client reconstructs it from the edition data (state carries only the
	 * reference). Null when the campaign is not loaded or the card is unknown.
	 */
	abilityCard(
		campaign: string,
		deck: string,
		nr: number
	): MonsterAbilityCard | null {
		const cards = this.loaded.get(campaign)?.abilityDecks[deck];
		if (!cards) return null;
		return cards.find((c) => c.nr === nr) ?? null;
	}

	/**
	 * The addable section names for a scenario, mirroring the server's
	 * `ScenarioModel`: the rooms file is keyed by the scenario number (the
	 * `#` and name stripped — `"#0 Howling in the Snow"` → `"0"`); the first
	 * room is the scenario start (skipped) and each remaining room's name is
	 * an addable section. Names containing "spawn" are excluded.
	 */
	sections(campaign: string, scenario: string): Promise<string[]> {
		const key = `${campaign}::${scenario}`;
		const cached = this.roomsCache.get(campaign);
		const roomsPromise = cached ??
			fetch(`${this.base}/rooms/${escapePathSegment(campaign)}.json`)
				.then((r) => (r.ok ? r.json() : null))
				.then(
					(rooms: Record<string, Record<string, unknown>[]> | null) => {
						this.roomsCache.set(campaign, Promise.resolve(rooms));
						return rooms;
					}
				);
		const promise = roomsPromise.then((rooms) => {
			if (!rooms) return [];
			// The rooms key is the scenario number after `#` (first token):
			// `"#1 A Town in Flames"` → `"1"`, `"#4A …"` → `"4A"`.
			const nr = scenario.startsWith('#')
				? scenario.slice(1).split(/\s/)[0]
				: scenario;
			const entry = rooms[nr] ?? rooms[scenario] ?? null;
			if (!Array.isArray(entry)) return [];
			return entry
				.slice(1) // skip the scenario start room
				.map((room) => Object.keys(room)[0] ?? '')
				.filter((name) => name && !name.toLowerCase().includes('spawn'));
		});
		this.roomsCache.set(campaign, roomsPromise);
		void key; // (cache key kept for a possible per-scenario variant)
		return promise;
	}

	private toClass(c: RawClass): ClassData {
		const name = c.name;
		const toDetails = (
			perks: RawClass['perks']
		): PerkDetail[] =>
			(perks ?? []).map((p) => ({
				text: p.text ?? '',
				adds: p.adds ?? [],
				removes: p.removes ?? []
			}));
		return {
			id: name,
			name,
			edition: c.edition,
			hidden: c.hidden ?? false,
			health: c.health,
			color: firstColor(c.color),
			colorSecondary: firstColor(c.colorSecondary, firstColor(c.color)),
			icon: `/images/class-icons/${escapePathSegment(name)}.png`,
			perks: (c.perks ?? []).map((p) => p.adds ?? []),
			perksFH: (c.perksFH ?? []).map((p) => p.adds ?? []),
			perkDetails: toDetails(c.perks),
			perkDetailsFH: toDetails(c.perksFH)
		};
	}

	/**
	 * The character class for [name] in [campaign] (by name or display
	 * name), or null when the campaign data is not yet loaded. Used by the
	 * modifier-card gfx resolver for perk (`P<n>`) graphics.
	 */
	classByName(campaign: string, name: string): ClassData | null {
		const data = this.loaded.get(campaign);
		if (!data) return null;
		return (
			data.classes.find((c) => c.name === name || c.id === name) ?? null
		);
	}

	private toMonster(name: string, m: RawMonster, edition: string): MonsterData {
		const display = m.display ?? name;
		const gfx = m.gfx ?? display;
		const levels = m.levels ?? [];
		const maxLevel = levels.reduce(
			(max, l) => Math.max(max, l.level),
			levels.length ? 0 : 1
		);
		return {
			name,
			display,
			gfx,
			deck: m.deck,
			count: m.count,
			hidden: m.hidden ?? false,
			flying: m.flying ?? false,
			levels,
			maxLevel,
			isBoss: levels.some((l) => l.boss != null),
			edition,
			portrait: `/images/monsters/${escapePathSegment(gfx)}.png`
		};
	}
}

/** The default shared client. */
export const gameData = new GameDataClient();