BlueGit

timfa questward

Files

questward / server / src / assets / spriteCatalog.js

spriteCatalog.js

spriteCatalog.js 12.8 KiB Download Raw
1import { readdirSync } from "node:fs";
2import { extname, join } from "node:path";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS, BlockType } from "../../../shared/definitions/tiles.js";
4import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6import { HERB_ORDER } from "../../../shared/definitions/herbs.js";
7import {
8 ORE_BEARING_MATERIALS,
9 oreBoulderState,
10 materialTintColor,
11 WOOD_TIER_ORDER
12} from "../../../shared/definitions/materialTiers.js";
13import {
14 FLOWER_COLOR_ORDER,
15 flowerBlockState,
16 flowerColorRgb
17} from "../../../shared/definitions/dyes.js";
18import {
19 bloomImageName,
20 equipBloomImageName,
21 equipImageName,
22 isCompanionSpriteStem,
23 parseSpriteStem,
24 spriteImageName
25} from "../../../shared/definitions/tileSprites.js";
26import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
27import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT } from "../../../shared/world/neighborConnect.js";
28
29const CHARACTER_DEFINITIONS = Object.freeze({
30 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
31 "player-body-female": Object.freeze({ key: "player-body-female", id: "player-body-female" })
32});
33
34export function buildSpriteCatalog (assetRoot)
35{
36 const blockDefs = Object.fromEntries(
37 Object.entries(BLOCK_DEFINITIONS).filter(([, def]) => def.key !== "herb")
38 );
39 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
40 const blocks = scanLayer(join(assetRoot, "blocks"), blockDefs, "block", "blocks");
41 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
42 const herbs = scanHerbAssets(join(assetRoot, "herbs"));
43 Object.assign(blocks.types, herbs.blockTypes);
44 Object.assign(items.types, herbs.itemTypes);
45 const mobs = scanMobLayers(assetRoot);
46 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
47 const fx = scanFx(join(assetRoot, "fx"));
48 return {
49 grounds: grounds.types,
50 blocks: blocks.types,
51 items: items.types,
52 mobs: mobs.types,
53 characters: characters.types,
54 fx: fx.types,
55 images: [
56 ...grounds.images,
57 ...blocks.images,
58 ...items.images,
59 ...herbs.images,
60 ...mobs.images,
61 ...characters.images,
62 ...fx.images
63 ]
64 };
65}
66
67/**
68 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
69 */
70function scanHerbAssets (herbRoot)
71{
72 const stems = new Set(listPngStems(herbRoot));
73 const missing = HERB_ORDER.filter((id) => !stems.has(id));
74 if (missing.length)
75 { throw new Error(`Missing herb sprites in ${herbRoot}: ${missing.join(", ")}`); }
76
77 const images = [];
78 for (const herbId of HERB_ORDER)
79 {
80 const url = `/assets/herbs/${herbId}.png`;
81 images.push({
82 name: spriteImageName("block", "herb", herbId),
83 url,
84 subImgTotal: 1,
85 perRow: 1,
86 loop: false,
87 animationSpeed: 0
88 });
89 images.push({
90 name: spriteImageName("item", "herbs", herbId),
91 url,
92 subImgTotal: 1,
93 perRow: 1,
94 loop: false,
95 animationSpeed: 0
96 });
97 }
98
99 const blockTypes = {
100 herb: {
101 key: "herb",
102 typeId: BlockType.herbPlant,
103 states: [...HERB_ORDER],
104 defaultState: HERB_ORDER[0],
105 blooms: {},
106 equips: {},
107 equipBlooms: {},
108 frames: 1,
109 framesPerRow: 1,
110 animationSpeed: 0,
111 outdoor: true,
112 seasonal: false
113 }
114 };
115 const itemTypes = {
116 herbs: {
117 key: "herbs",
118 typeId: "herbs",
119 states: [...HERB_ORDER],
120 defaultState: HERB_ORDER[0],
121 blooms: {},
122 equips: {},
123 equipBlooms: {},
124 frames: 1,
125 framesPerRow: 1,
126 animationSpeed: 0,
127 outdoor: false,
128 seasonal: false
129 }
130 };
131 return { images, blockTypes, itemTypes };
132}
133
134function itemScanDefs ()
135{
136 const defs = {};
137 for (const def of Object.values(ITEM_DEFINITIONS))
138 {
139 if (def?.herb)
140 { continue; }
141 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
142 if (!folderKey || defs[folderKey])
143 { continue; }
144 defs[folderKey] = {
145 key: folderKey,
146 id: def.itemId,
147 frames: def.frames ?? 1,
148 framesPerRow: def.framesPerRow ?? 1,
149 animationSpeed: def.animationSpeed ?? 0
150 };
151 }
152 /** Shared metal armour worn overlays (items/armour/*-equip.png). */
153 if (!defs.armour)
154 {
155 defs.armour = {
156 key: "armour",
157 id: "armour-overlays",
158 frames: 1,
159 framesPerRow: 1,
160 animationSpeed: 0
161 };
162 }
163 return defs;
164}
165
166function mobScanDefs ()
167{
168 const defs = {};
169 for (const def of Object.values(MOB_DEFINITIONS))
170 {
171 if (def.usePlayerBody)
172 { continue; }
173 const key = def.key ?? def.mobTypeId;
174 defs[key] = {
175 key,
176 id: def.mobTypeId,
177 frames: def.frames ?? 1,
178 framesPerRow: def.framesPerRow ?? 1,
179 animationSpeed: def.animationSpeed ?? 0,
180 assetFolder: def.assetFolder ?? "mobs"
181 };
182 }
183 return defs;
184}
185
186function scanMobLayers (assetRoot)
187{
188 const byFolder = new Map();
189 for (const def of Object.values(mobScanDefs()))
190 {
191 const folder = def.assetFolder ?? "mobs";
192 if (!byFolder.has(folder))
193 { byFolder.set(folder, {}); }
194 byFolder.get(folder)[def.key] = def;
195 }
196 const types = {};
197 const images = [];
198 for (const [folder, defs] of byFolder)
199 {
200 const scanned = scanLayer(join(assetRoot, folder), defs, "mob", folder);
201 Object.assign(types, scanned.types);
202 images.push(...scanned.images);
203 }
204 return { types, images };
205}
206
207function scanFx (fxRoot)
208{
209 const types = {};
210 const images = [];
211 let folders;
212 try
213 { folders = readdirSync(fxRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()); }
214 catch (error)
215 {
216 if (error.code === "ENOENT")
217 { return { types, images }; }
218 throw error;
219 }
220 for (const entry of folders)
221 {
222 const key = entry.name;
223 const defs = {
224 [key]: { key, id: key, frames: 1, framesPerRow: 1, animationSpeed: 0 }
225 };
226 const scanned = scanLayer(fxRoot, defs, "fx", "fx");
227 Object.assign(types, scanned.types);
228 images.push(...scanned.images);
229 }
230 return { types, images };
231}
232
233function scanLayer (layerDir, definitions, layer, urlFolder)
234{
235 const types = {};
236 const images = [];
237 for (const def of Object.values(definitions))
238 {
239 const folder = join(layerDir, def.key);
240 const { states: fileStates, blooms: fileBlooms, equips, equipBlooms } = listVisualStates(folder);
241 if (fileStates.length === 0)
242 { throw new Error(`No PNG states in ${folder}`); }
243
244 const frames = Math.max(1, def.frames ?? 1);
245 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
246 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
247 let states = [...fileStates];
248 let blooms = fileBlooms;
249 const imagesForType = [];
250
251 if (layer === "block" && def.key === "boulder")
252 {
253 states = states.filter((state) => state !== "boulder-ore" && state !== "boulder-ore-winter");
254 if (!states.includes("boulder"))
255 { states.unshift("boulder"); }
256 for (const material of ORE_BEARING_MATERIALS)
257 {
258 const state = oreBoulderState(material);
259 if (!states.includes(state))
260 { states.push(state); }
261 const tint = materialTintColor(material, { ore: true });
262 imagesForType.push({
263 name: spriteImageName(layer, def.key, state),
264 url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
265 subImgTotal: frames,
266 perRow: framesPerRow,
267 loop: animationSpeed > 0,
268 animationSpeed,
269 tint: { r: tint.r, g: tint.g, b: tint.b }
270 });
271 const winterState = `${state}-winter`;
272 if (!states.includes(winterState))
273 { states.push(winterState); }
274 imagesForType.push({
275 name: spriteImageName(layer, def.key, winterState),
276 url: `/assets/${urlFolder}/${def.key}/boulder-ore-winter.png`,
277 subImgTotal: frames,
278 perRow: framesPerRow,
279 loop: animationSpeed > 0,
280 animationSpeed,
281 tint: { r: tint.r, g: tint.g, b: tint.b }
282 });
283 }
284 }
285
286 if (layer === "block" && def.key === "flower")
287 {
288 states = [];
289 for (const colorId of FLOWER_COLOR_ORDER)
290 {
291 const state = flowerBlockState(colorId);
292 states.push(state);
293 const tint = flowerColorRgb(colorId);
294 imagesForType.push({
295 name: spriteImageName(layer, def.key, state),
296 url: `/assets/${urlFolder}/${def.key}/flower.png`,
297 subImgTotal: frames,
298 perRow: framesPerRow,
299 loop: animationSpeed > 0,
300 animationSpeed,
301 tint: { r: tint.r, g: tint.g, b: tint.b }
302 });
303 }
304 }
305
306 if (layer === "block" && def.key === "campfire")
307 {
308 states = [];
309 const nextBlooms = {};
310 for (const material of WOOD_TIER_ORDER)
311 {
312 states.push(material);
313 const tint = materialTintColor(material);
314 imagesForType.push({
315 name: spriteImageName(layer, def.key, material),
316 url: `/assets/${urlFolder}/${def.key}/campfire.png`,
317 subImgTotal: frames,
318 perRow: framesPerRow,
319 loop: animationSpeed > 0,
320 animationSpeed,
321 tint: { r: tint.r, g: tint.g, b: tint.b }
322 });
323 imagesForType.push({
324 name: bloomImageName(layer, def.key, material),
325 url: `/assets/${urlFolder}/${def.key}/campfire-bloom.png`,
326 subImgTotal: frames,
327 perRow: framesPerRow,
328 loop: animationSpeed > 0,
329 animationSpeed
330 });
331 nextBlooms[material] = true;
332 }
333 blooms = nextBlooms;
334 }
335
336 if (layer === "block" && def.key === "table")
337 {
338 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
339 states = [];
340 for (const material of WOOD_TIER_ORDER)
341 {
342 for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++)
343 {
344 const state = composeNeighborConnectState(def, material, mask);
345 states.push(state);
346 const tint = materialTintColor(material);
347 imagesForType.push({
348 name: spriteImageName(layer, def.key, state),
349 url: `/assets/${urlFolder}/${def.key}/${mask}.png`,
350 subImgTotal: frames,
351 perRow: framesPerRow,
352 loop: animationSpeed > 0,
353 animationSpeed,
354 tint: { r: tint.r, g: tint.g, b: tint.b }
355 });
356 }
357 }
358 }
359
360 types[def.key] = {
361 key: def.key,
362 typeId: def.id,
363 states,
364 defaultState: def.key === "boulder" && states.includes("boulder")
365 ? "boulder"
366 : def.key === "fishing-spot" && states.includes("fishing-spot")
367 ? "fishing-spot"
368 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
369 blooms,
370 equips,
371 equipBlooms,
372 frames,
373 framesPerRow,
374 animationSpeed,
375 outdoor: !!def.outdoor,
376 /** Calendar-driven only when outdoor and summer/fall/winter states exist. */
377 seasonal: !!def.outdoor && typeHasSeasonalStates(states)
378 };
379 for (const state of states)
380 {
381 if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
382 { continue; }
383 /** Seasonal overlays (e.g. frozen water-winter) are static single-frame sprites. */
384 const overlay = isSeasonalOverlayVariant(state);
385 const sheet = {
386 subImgTotal: overlay ? 1 : frames,
387 perRow: overlay ? 1 : framesPerRow,
388 loop: !overlay && animationSpeed > 0,
389 animationSpeed: overlay ? 0 : animationSpeed
390 };
391 images.push({
392 name: spriteImageName(layer, def.key, state),
393 url: `/assets/${urlFolder}/${def.key}/${state}.png`,
394 ...sheet
395 });
396 if (blooms[state])
397 {
398 images.push({
399 name: bloomImageName(layer, def.key, state),
400 url: `/assets/${urlFolder}/${def.key}/${state}-bloom.png`,
401 ...sheet
402 });
403 }
404 if (equips[state])
405 {
406 images.push({
407 name: equipImageName(layer, def.key, state),
408 url: `/assets/${urlFolder}/${def.key}/${state}-equip.png`,
409 ...sheet
410 });
411 }
412 if (equipBlooms[state])
413 {
414 images.push({
415 name: equipBloomImageName(layer, def.key, state),
416 url: `/assets/${urlFolder}/${def.key}/${state}-equip-bloom.png`,
417 ...sheet
418 });
419 }
420 }
421 images.push(...imagesForType);
422 }
423 return { types, images };
424}
425
426function listVisualStates (folder)
427{
428 const stems = listPngStems(folder);
429 const blooms = {};
430 const equips = {};
431 const equipBlooms = {};
432 const states = [];
433 for (const stem of stems)
434 {
435 const parsed = parseSpriteStem(stem);
436 if (parsed.companion)
437 {
438 if (!parsed.base)
439 { continue; }
440 if (parsed.equip && parsed.bloom)
441 { equipBlooms[parsed.base] = true; }
442 else if (parsed.equip)
443 { equips[parsed.base] = true; }
444 else if (parsed.bloom)
445 { blooms[parsed.base] = true; }
446 continue;
447 }
448 if (isCompanionSpriteStem(stem))
449 { continue; }
450 states.push(stem);
451 }
452 const filterMap = (map) =>
453 {
454 const next = {};
455 for (const state of states)
456 {
457 if (map[state])
458 { next[state] = true; }
459 }
460 return next;
461 };
462 return {
463 states,
464 blooms: filterMap(blooms),
465 equips: filterMap(equips),
466 equipBlooms: filterMap(equipBlooms)
467 };
468}
469
470function listPngStems (folder)
471{
472 let entries;
473 try
474 { entries = readdirSync(folder, { withFileTypes: true }); }
475 catch (error)
476 {
477 if (error.code === "ENOENT")
478 { return []; }
479 throw error;
480 }
481
482 return entries
483 .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png")
484 .map((entry) => entry.name.slice(0, -extname(entry.name).length))
485 .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));
486}