BlueGit

timfa questward

Files

questward / client / src / render / sprites.js

sprites.js

spawner tweaks
timfa Tim Falken · pushed by timfa · 2 months ago
661b81e5 History
sprites.js 4.1 KiB Download Raw
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
3export const UTILITY_IMAGES = [
4 { name: "night-shade", url: shadeDataUrl("#000000") },
5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
6 { name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
7 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") }
8];
9
10export function playImagesFromCatalog (catalog)
11{
12 return [...(catalog?.images ?? []), ...UTILITY_IMAGES];
13}
14
15export async function loadSpriteCatalog ()
16{
17 const response = await fetch("/assets/catalog.json");
18 if (!response.ok)
19 { throw new Error("Failed to load sprite catalog."); }
20 return response.json();
21}
22
23/**
24 * Load catalog images without aborting the whole client when one file is missing.
25 * Failed entries are logged and omitted from `game.images`.
26 */
27export async function preloadCatalogImages (game, catalog)
28{
29 const failed = [];
30 await Promise.all(playImagesFromCatalog(catalog).map((imageData) => loadOneImage(game, imageData).catch((error) =>
31 {
32 console.error(error.message ?? error);
33 failed.push({ name: imageData.name, url: imageData.url });
34 })));
35 if (failed.length)
36 { console.warn(`Skipped ${failed.length} missing/broken sprite(s).`, failed.map((entry) => entry.name)); }
37 return failed;
38}
39
40function loadOneImage (game, imageData)
41{
42 return new Promise((resolve, reject) =>
43 {
44 const img = new Image();
45 img.onload = () =>
46 {
47 const finalImage = new image(
48 img,
49 imageData.subImgTotal,
50 imageData.perRow,
51 imageData.loop,
52 imageData.chain
53 );
54 finalImage.name = imageData.name;
55 game.images[imageData.name] = finalImage;
56 resolve(finalImage);
57 };
58 img.onerror = () =>
59 {
60 reject(new Error(`Failed to load image '${imageData.name}' from ${imageData.url}`));
61 };
62 img.src = imageData.url;
63 });
64}
65
66export function applySpriteSheets (images, catalog)
67{
68 for (const entry of catalog?.images ?? [])
69 {
70 const sprite = images[entry.name];
71 if (!sprite)
72 { continue; }
73 sprite._animationSpeed = entry.animationSpeed ?? 0;
74 const frames = entry.subImgTotal || 1;
75 if (frames > 1)
76 {
77 sprite.addAnimationCycle(
78 "idle",
79 Array.from({ length: frames }, (_, index) => index),
80 true
81 );
82 }
83 }
84}
85
86export function shadeDataUrl (fill = "#000000")
87{
88 const canvas = document.createElement("canvas");
89 canvas.width = SPRITE_SIZE_PX;
90 canvas.height = SPRITE_SIZE_PX;
91 const context = canvas.getContext("2d");
92 context.fillStyle = fill;
93 context.fillRect(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX);
94 return canvas.toDataURL("image/png");
95}
96
97function setGlNearest (gl, texture)
98{
99 if (!gl || !texture)
100 { return; }
101 gl.bindTexture(gl.TEXTURE_2D, texture);
102 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
103 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
104}
105
106/** Framework defaults to LINEAR; patch uploads so pixel art stays crisp when scaled. */
107export function patchNearestNeighbourTextures (scene)
108{
109 const glContext = scene?.glContext;
110 if (!glContext || glContext._nearestPatched)
111 { return; }
112 const original = glContext.getTexture.bind(glContext);
113 glContext.getTexture = (htmlImage) =>
114 {
115 const texture = original(htmlImage);
116 if (texture)
117 { setGlNearest(glContext.gl, texture); }
118 return texture;
119 };
120 glContext._nearestPatched = true;
121}
122
123/** Canvas atlases and dynamic sprites — call after invalidate/reupload. */
124export function setNearestFilter (scene, source)
125{
126 if (!source)
127 { return; }
128 patchNearestNeighbourTextures(scene);
129 const glContext = scene?.glContext;
130 if (!glContext)
131 { return; }
132 const htmlImage = source.g_image ?? source;
133 const texture = glContext.getTexture(htmlImage);
134 if (texture)
135 { setGlNearest(glContext.gl, texture); }
136}
137
138export function applyNearestToAllTextures (scene, images)
139{
140 patchNearestNeighbourTextures(scene);
141 const glContext = scene?.glContext;
142 if (!glContext)
143 { return; }
144 for (const sprite of Object.values(images ?? {}))
145 {
146 const htmlImage = sprite?.g_image ?? sprite;
147 if (htmlImage)
148 { glContext.getTexture(htmlImage); }
149 }
150}
151
152export function useNearestNeighbour (scene, images)
153{
154 applyNearestToAllTextures(scene, images);
155}