BlueGit

timfa questward

Files

questward / server / src / assets / spriteCatalog.js

spriteCatalog.js

feat: add sprite average colours and an editor minimap
timfa project_85689633_bot_760517ee9267c86ff1d6c3a0237abf7d · pushed by timfa · 6 weeks ago
8a24eb51 History
spriteCatalog.js 16.7 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 {
9 ORE_BEARING_MATERIALS,
10 oreBoulderState,
11 materialTintColor,
12 WOOD_TIER_ORDER
13 } from "../../../shared/definitions/materialTiers.js";
14import
15 {
16 FLOWER_COLOR_ORDER,
17 flowerBlockState,
18 flowerColorRgb
19 } from "../../../shared/definitions/dyes.js";
20import
21 {
22 bloomImageName,
23 equipBloomImageName,
24 equipImageName,
25 isCompanionSpriteStem,
26 parseSpriteStem,
27 palettePreviewImageName,
28 spriteImageName
29 } from "../../../shared/definitions/tileSprites.js";
30import { attachTileAverageColors } from "./tileAverageColors.js";
31import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
32import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT, definitionUsesMaterialNeighborConnect } from "../../../shared/world/neighborConnect.js";
33import
34 {
35 ITEM_SPAWNER_CONTAINER_APPEARANCES,
36 ITEM_SPAWNER_CONTAINER_ASSET_KEY
37 } from "../../../shared/definitions/itemSpawners.js";
38
39const CHARACTER_DEFINITIONS = Object.freeze({
40 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
41 "player-body-female": Object.freeze({ key: "player-body-female", id: "player-body-female" })
42});
43
44export function buildSpriteCatalog (assetRoot)
45{
46 const blockDefs = Object.fromEntries(
47 Object.entries(BLOCK_DEFINITIONS).filter(([, def]) => def.key !== "herb")
48 );
49 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
50 const blocks = scanLayer(join(assetRoot, "blocks"), blockDefs, "block", "blocks");
51 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
52 const herbs = scanHerbAssets(join(assetRoot, "herbs"));
53 Object.assign(blocks.types, herbs.blockTypes);
54 Object.assign(items.types, herbs.itemTypes);
55 const mobs = scanMobLayers(assetRoot);
56 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
57 const fx = scanFx(join(assetRoot, "fx"));
58 const containers = scanContainerSprites(join(assetRoot, "blocks", ITEM_SPAWNER_CONTAINER_ASSET_KEY));
59 Object.assign(blocks.types, containers.blockTypes);
60 const catalog = {
61 grounds: grounds.types,
62 blocks: blocks.types,
63 items: items.types,
64 mobs: mobs.types,
65 characters: characters.types,
66 fx: fx.types,
67 images: [
68 ...grounds.images,
69 ...blocks.images,
70 ...items.images,
71 ...herbs.images,
72 ...mobs.images,
73 ...characters.images,
74 ...fx.images,
75 ...containers.images
76 ]
77 };
78 attachTileAverageColors(catalog, assetRoot);
79 return catalog;
80}
81
82/**
83 * Magenta container masks (chest/barrel/crate) expanded per wood tier for item spawners.
84 * Not placeable as authored blocks — used for editor preview + runtime overlays.
85 */
86function scanContainerSprites (folder)
87{
88 const stems = new Set(listPngStems(folder));
89 const images = [];
90 const states = [];
91 for (const appearance of ITEM_SPAWNER_CONTAINER_APPEARANCES)
92 {
93 if (!stems.has(appearance))
94 { throw new Error(`Missing container sprite in ${folder}: ${appearance}.png`); }
95 for (const material of WOOD_TIER_ORDER)
96 {
97 const state = `${material}-${appearance}`;
98 states.push(state);
99 const tint = materialTintColor(material);
100 images.push({
101 name: spriteImageName("block", ITEM_SPAWNER_CONTAINER_ASSET_KEY, state),
102 url: `/assets/blocks/${ITEM_SPAWNER_CONTAINER_ASSET_KEY}/${appearance}.png`,
103 subImgTotal: 1,
104 perRow: 1,
105 loop: false,
106 animationSpeed: 0,
107 tint: { r: tint.r, g: tint.g, b: tint.b }
108 });
109 }
110 }
111 const blockTypes = {
112 [ITEM_SPAWNER_CONTAINER_ASSET_KEY]: {
113 key: ITEM_SPAWNER_CONTAINER_ASSET_KEY,
114 typeId: "containers",
115 states,
116 defaultState: states[0] ?? "pine-chest",
117 blooms: {},
118 equips: {},
119 equipBlooms: {},
120 frames: 1,
121 framesPerRow: 1,
122 animationSpeed: 0,
123 outdoor: false,
124 seasonal: false
125 }
126 };
127 return { images, blockTypes };
128}
129
130/**
131 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
132 */
133function scanHerbAssets (herbRoot)
134{
135 const stems = new Set(listPngStems(herbRoot));
136 const missing = HERB_ORDER.filter((id) => !stems.has(id));
137 if (missing.length)
138 { throw new Error(`Missing herb sprites in ${herbRoot}: ${missing.join(", ")}`); }
139
140 const images = [];
141 for (const herbId of HERB_ORDER)
142 {
143 const url = `/assets/herbs/${herbId}.png`;
144 images.push({
145 name: spriteImageName("block", "herb", herbId),
146 url,
147 subImgTotal: 1,
148 perRow: 1,
149 loop: false,
150 animationSpeed: 0
151 });
152 images.push({
153 name: spriteImageName("item", "herbs", herbId),
154 url,
155 subImgTotal: 1,
156 perRow: 1,
157 loop: false,
158 animationSpeed: 0
159 });
160 }
161
162 const blockTypes = {
163 herb: {
164 key: "herb",
165 typeId: BlockType.herbPlant,
166 states: [...HERB_ORDER],
167 defaultState: HERB_ORDER[0],
168 blooms: {},
169 equips: {},
170 equipBlooms: {},
171 frames: 1,
172 framesPerRow: 1,
173 animationSpeed: 0,
174 outdoor: true,
175 seasonal: false
176 }
177 };
178 const itemTypes = {
179 herbs: {
180 key: "herbs",
181 typeId: "herbs",
182 states: [...HERB_ORDER],
183 defaultState: HERB_ORDER[0],
184 blooms: {},
185 equips: {},
186 equipBlooms: {},
187 frames: 1,
188 framesPerRow: 1,
189 animationSpeed: 0,
190 outdoor: false,
191 seasonal: false
192 }
193 };
194 return { images, blockTypes, itemTypes };
195}
196
197function itemScanDefs ()
198{
199 const defs = {};
200 for (const def of Object.values(ITEM_DEFINITIONS))
201 {
202 if (def?.herb)
203 { continue; }
204 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
205 if (!folderKey || defs[folderKey])
206 { continue; }
207 defs[folderKey] = {
208 key: folderKey,
209 id: def.itemId,
210 frames: def.frames ?? 1,
211 framesPerRow: def.framesPerRow ?? 1,
212 animationSpeed: def.animationSpeed ?? 0
213 };
214 }
215 /** Shared metal armour worn overlays (items/armour/*-equip.png). */
216 if (!defs.armour)
217 {
218 defs.armour = {
219 key: "armour",
220 id: "armour-overlays",
221 frames: 1,
222 framesPerRow: 1,
223 animationSpeed: 0
224 };
225 }
226 return defs;
227}
228
229function mobScanDefs ()
230{
231 const defs = {};
232 for (const def of Object.values(MOB_DEFINITIONS))
233 {
234 if (def.usePlayerBody)
235 { continue; }
236 // spriteKey reuses another mob's art folder when set.
237 const key = def.spriteKey ?? def.key ?? def.mobTypeId;
238 if (defs[key])
239 { continue; }
240 defs[key] = {
241 key,
242 id: def.mobTypeId,
243 frames: def.frames ?? 1,
244 framesPerRow: def.framesPerRow ?? 1,
245 animationSpeed: def.animationSpeed ?? 0,
246 bloomFrames: def.bloomFrames ?? null,
247 bloomFramesPerRow: def.bloomFramesPerRow ?? null,
248 bloomAnimationSpeed: def.bloomAnimationSpeed ?? null,
249 assetFolder: def.assetFolder ?? "mobs"
250 };
251 }
252 return defs;
253}
254
255function scanMobLayers (assetRoot)
256{
257 const byFolder = new Map();
258 for (const def of Object.values(mobScanDefs()))
259 {
260 const folder = def.assetFolder ?? "mobs";
261 if (!byFolder.has(folder))
262 { byFolder.set(folder, {}); }
263 byFolder.get(folder)[def.key] = def;
264 }
265 const types = {};
266 const images = [];
267 for (const [folder, defs] of byFolder)
268 {
269 const scanned = scanLayer(join(assetRoot, folder), defs, "mob", folder);
270 Object.assign(types, scanned.types);
271 images.push(...scanned.images);
272 }
273 return { types, images };
274}
275
276function scanFx (fxRoot)
277{
278 const types = {};
279 const images = [];
280 let folders;
281 try
282 { folders = readdirSync(fxRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()); }
283 catch (error)
284 {
285 if (error.code === "ENOENT")
286 { return { types, images }; }
287 throw error;
288 }
289 for (const entry of folders)
290 {
291 const key = entry.name;
292 const defs = {
293 [key]: { key, id: key, frames: 1, framesPerRow: 1, animationSpeed: 0 }
294 };
295 const scanned = scanLayer(fxRoot, defs, "fx", "fx");
296 Object.assign(types, scanned.types);
297 images.push(...scanned.images);
298 }
299 return { types, images };
300}
301
302function scanLayer (layerDir, definitions, layer, urlFolder)
303{
304 const types = {};
305 const images = [];
306 for (const def of Object.values(definitions))
307 {
308 const folder = join(layerDir, def.key);
309 const { states: fileStates, blooms: fileBlooms, equips, equipBlooms, previews } = listVisualStates(folder);
310 if (fileStates.length === 0)
311 { throw new Error(`No PNG states in ${folder}`); }
312
313 const frames = Math.max(1, def.frames ?? 1);
314 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
315 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
316 let states = [...fileStates];
317 let blooms = fileBlooms;
318 const imagesForType = [];
319
320 if (layer === "block" && def.key === "boulder")
321 {
322 states = states.filter((state) => state !== "boulder-ore" && state !== "boulder-ore-winter");
323 if (!states.includes("boulder"))
324 { states.unshift("boulder"); }
325 for (const material of ORE_BEARING_MATERIALS)
326 {
327 const state = oreBoulderState(material);
328 if (!states.includes(state))
329 { states.push(state); }
330 const tint = materialTintColor(material, { ore: true });
331 imagesForType.push({
332 name: spriteImageName(layer, def.key, state),
333 url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
334 subImgTotal: frames,
335 perRow: framesPerRow,
336 loop: animationSpeed > 0,
337 animationSpeed,
338 tint: { r: tint.r, g: tint.g, b: tint.b }
339 });
340 const winterState = `${state}-winter`;
341 if (!states.includes(winterState))
342 { states.push(winterState); }
343 imagesForType.push({
344 name: spriteImageName(layer, def.key, winterState),
345 url: `/assets/${urlFolder}/${def.key}/boulder-ore-winter.png`,
346 subImgTotal: frames,
347 perRow: framesPerRow,
348 loop: animationSpeed > 0,
349 animationSpeed,
350 tint: { r: tint.r, g: tint.g, b: tint.b }
351 });
352 }
353 }
354
355 if (layer === "block" && def.key === "flower")
356 {
357 states = [];
358 for (const colorId of FLOWER_COLOR_ORDER)
359 {
360 const state = flowerBlockState(colorId);
361 states.push(state);
362 const tint = flowerColorRgb(colorId);
363 imagesForType.push({
364 name: spriteImageName(layer, def.key, state),
365 url: `/assets/${urlFolder}/${def.key}/flower.png`,
366 subImgTotal: frames,
367 perRow: framesPerRow,
368 loop: animationSpeed > 0,
369 animationSpeed,
370 tint: { r: tint.r, g: tint.g, b: tint.b }
371 });
372 }
373 }
374
375 if (layer === "block" && def.key === "campfire")
376 {
377 states = [];
378 const nextBlooms = {};
379 for (const material of WOOD_TIER_ORDER)
380 {
381 states.push(material);
382 const tint = materialTintColor(material);
383 imagesForType.push({
384 name: spriteImageName(layer, def.key, material),
385 url: `/assets/${urlFolder}/${def.key}/campfire.png`,
386 subImgTotal: frames,
387 perRow: framesPerRow,
388 loop: animationSpeed > 0,
389 animationSpeed,
390 tint: { r: tint.r, g: tint.g, b: tint.b }
391 });
392 imagesForType.push({
393 name: bloomImageName(layer, def.key, material),
394 url: `/assets/${urlFolder}/${def.key}/campfire-bloom.png`,
395 subImgTotal: frames,
396 perRow: framesPerRow,
397 loop: animationSpeed > 0,
398 animationSpeed
399 });
400 nextBlooms[material] = true;
401 }
402 blooms = nextBlooms;
403 }
404
405 if (layer === "block" && def.door)
406 {
407 states = [];
408 for (const material of WOOD_TIER_ORDER)
409 {
410 for (const facing of ["n", "s"])
411 {
412 for (const openness of ["closed", "open"])
413 {
414 const state = `${material}-${facing}-${openness}`;
415 states.push(state);
416 const tint = materialTintColor(material);
417 imagesForType.push({
418 name: spriteImageName(layer, def.key, state),
419 url: `/assets/${urlFolder}/${def.key}/door-${facing}-${openness}.png`,
420 subImgTotal: frames,
421 perRow: framesPerRow,
422 loop: animationSpeed > 0,
423 animationSpeed,
424 tint: { r: tint.r, g: tint.g, b: tint.b }
425 });
426 }
427 }
428 }
429 }
430
431 if (layer === "block" && definitionUsesMaterialNeighborConnect(def))
432 {
433 // Magenta mask sources `0`–`15`; expand per wood tier (`pine-0` …).
434 states = [];
435 for (const material of WOOD_TIER_ORDER)
436 {
437 for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++)
438 {
439 const state = composeNeighborConnectState(def, material, mask);
440 states.push(state);
441 const tint = materialTintColor(material);
442 imagesForType.push({
443 name: spriteImageName(layer, def.key, state),
444 url: `/assets/${urlFolder}/${def.key}/${mask}.png`,
445 subImgTotal: frames,
446 perRow: framesPerRow,
447 loop: animationSpeed > 0,
448 animationSpeed,
449 tint: { r: tint.r, g: tint.g, b: tint.b }
450 });
451 }
452 }
453 }
454
455 types[def.key] = {
456 key: def.key,
457 typeId: def.id,
458 states,
459 defaultState: def.key === "boulder" && states.includes("boulder")
460 ? "boulder"
461 : def.key === "fishing-spot" && states.includes("fishing-spot")
462 ? "fishing-spot"
463 : def.door && states.includes("pine-s-closed")
464 ? "pine-s-closed"
465 : def.key === "sand" && states.includes("sand")
466 ? "sand"
467 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
468 blooms,
469 equips,
470 equipBlooms,
471 frames,
472 framesPerRow,
473 animationSpeed,
474 outdoor: !!def.outdoor,
475 /** Calendar-driven only when outdoor and summer/fall/winter states exist. */
476 seasonal: !!def.outdoor && typeHasSeasonalStates(states)
477 };
478 for (const state of states)
479 {
480 if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
481 { continue; }
482 /** Seasonal overlays (e.g. frozen water-winter) are static single-frame sprites. */
483 const overlay = isSeasonalOverlayVariant(state);
484 const sheet = {
485 subImgTotal: overlay ? 1 : frames,
486 perRow: overlay ? 1 : framesPerRow,
487 loop: !overlay && animationSpeed > 0,
488 animationSpeed: overlay ? 0 : animationSpeed
489 };
490 images.push({
491 name: spriteImageName(layer, def.key, state),
492 url: `/assets/${urlFolder}/${def.key}/${state}.png`,
493 ...sheet
494 });
495 if (blooms[state])
496 {
497 const bloomFrames = Math.max(1, def.bloomFrames ?? frames);
498 const bloomPerRow = Math.max(1, def.bloomFramesPerRow ?? framesPerRow);
499 const bloomSpeed = Math.max(0, def.bloomAnimationSpeed ?? animationSpeed);
500 images.push({
501 name: bloomImageName(layer, def.key, state),
502 url: `/assets/${urlFolder}/${def.key}/${state}-bloom.png`,
503 subImgTotal: bloomFrames,
504 perRow: bloomPerRow,
505 loop: bloomSpeed > 0,
506 animationSpeed: bloomSpeed
507 });
508 }
509 /** Worn/gather overlays are always single-frame (inventory sheets may differ). */
510 const equipSheet = {
511 subImgTotal: 1,
512 perRow: 1,
513 loop: false,
514 animationSpeed: 0
515 };
516 if (equips[state])
517 {
518 images.push({
519 name: equipImageName(layer, def.key, state),
520 url: `/assets/${urlFolder}/${def.key}/${state}-equip.png`,
521 ...equipSheet
522 });
523 }
524 if (equipBlooms[state])
525 {
526 images.push({
527 name: equipBloomImageName(layer, def.key, state),
528 url: `/assets/${urlFolder}/${def.key}/${state}-equip-bloom.png`,
529 ...equipSheet
530 });
531 }
532 }
533 const previewStem = previews?.[def.key];
534 if (previewStem)
535 {
536 images.push({
537 name: palettePreviewImageName(layer, def.key),
538 url: `/assets/${urlFolder}/${def.key}/${previewStem}.png`,
539 subImgTotal: 1,
540 perRow: 1,
541 loop: false,
542 animationSpeed: 0
543 });
544 }
545 images.push(...imagesForType);
546 }
547 return { types, images };
548}
549
550function listVisualStates (folder)
551{
552 const stems = listPngStems(folder);
553 const blooms = {};
554 const equips = {};
555 const equipBlooms = {};
556 const previews = {};
557 const states = [];
558 for (const stem of stems)
559 {
560 const parsed = parseSpriteStem(stem);
561 if (parsed.companion)
562 {
563 if (!parsed.base)
564 { continue; }
565 if (parsed.preview)
566 { previews[parsed.base] = stem; }
567 else if (parsed.equip && parsed.bloom)
568 { equipBlooms[parsed.base] = true; }
569 else if (parsed.equip)
570 { equips[parsed.base] = true; }
571 else if (parsed.bloom)
572 { blooms[parsed.base] = true; }
573 continue;
574 }
575 if (isCompanionSpriteStem(stem))
576 { continue; }
577 states.push(stem);
578 }
579 const filterMap = (map) =>
580 {
581 const next = {};
582 for (const state of states)
583 {
584 if (map[state])
585 { next[state] = true; }
586 }
587 return next;
588 };
589 return {
590 states,
591 blooms: filterMap(blooms),
592 equips: filterMap(equips),
593 equipBlooms: filterMap(equipBlooms),
594 /** Editor palette thumbs (`water-preview` → base `water`); not placeable states. */
595 previews
596 };
597}
598
599function listPngStems (folder)
600{
601 let entries;
602 try
603 { entries = readdirSync(folder, { withFileTypes: true }); }
604 catch (error)
605 {
606 if (error.code === "ENOENT")
607 { return []; }
608 throw error;
609 }
610
611 return entries
612 .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png")
613 .map((entry) => entry.name.slice(0, -extname(entry.name).length))
614 .filter((stem) => !stem.startsWith("example") && !stem.startsWith("_"))
615 .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));
616}