BlueGit

timfa questward

Files

questward / client / src / render / sprites.js

sprites.js

feat: add sprite average colours and an editor minimap
timfa project_85689633_bot_760517ee9267c86ff1d6c3a0237abf7d · pushed by timfa · 6 weeks ago
8a24eb51 History
sprites.js 6.4 KiB Download Raw
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { applyMagentaTintToImageData } from "/shared/render/tint.js";
3import { installTileAverageColors } from "/shared/render/tileAverageColors.js";
4
5export const UTILITY_IMAGES = [
6 { name: "night-shade", url: shadeDataUrl("#000000") },
7 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
8 { name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
9 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") },
10 { name: "spell-target-tile", url: shadeDataUrl("rgba(110, 220, 255, 0.62)") },
11 { name: "spell-target-invalid", url: shadeDataUrl("rgba(255, 72, 72, 0.48)") },
12 { name: "spell-target-entity", url: outlineDataUrl("rgba(110, 220, 255, 0.95)") },
13 { name: "spell-target-entity-invalid", url: outlineDataUrl("rgba(255, 72, 72, 0.9)") }
14];
15
16export function playImagesFromCatalog (catalog)
17{
18 return [...(catalog?.images ?? []), ...UTILITY_IMAGES];
19}
20
21export async function loadSpriteCatalog ()
22{
23 const response = await fetch("/assets/catalog.json");
24 if (!response.ok)
25 { throw new Error("Failed to load sprite catalog."); }
26 const catalog = await response.json();
27 installTileAverageColors(catalog);
28 return catalog;
29}
30
31/**
32 * Load catalog images without aborting the whole client when one file is missing.
33 * Failed entries are logged and omitted from `game.images`.
34 */
35export async function preloadCatalogImages (game, catalog, { onProgress } = {})
36{
37 const images = playImagesFromCatalog(catalog);
38 const total = images.length;
39 let loaded = 0;
40 const failed = [];
41 const report = (name) =>
42 {
43 loaded += 1;
44 onProgress?.({ loaded, total, name });
45 };
46 await Promise.all(images.map((imageData) => loadOneImage(game, imageData).then((sprite) =>
47 {
48 report(imageData.name);
49 return sprite;
50 }).catch((error) =>
51 {
52 console.error(error.message ?? error);
53 failed.push({ name: imageData.name, url: imageData.url });
54 report(imageData.name);
55 })));
56 if (failed.length)
57 { console.warn(`Skipped ${failed.length} missing/broken sprite(s).`, failed.map((entry) => entry.name)); }
58 return failed;
59}
60
61function loadOneImage (game, imageData)
62{
63 return new Promise((resolve, reject) =>
64 {
65 const img = new Image();
66 img.onload = () =>
67 {
68 const source = imageData.tint
69 ? tintedHtmlImage(img, imageData.tint)
70 : img;
71 const finalImage = new image(
72 source,
73 imageData.subImgTotal,
74 imageData.perRow,
75 imageData.loop,
76 imageData.chain
77 );
78 finalImage.name = imageData.name;
79 game.images[imageData.name] = finalImage;
80 resolve(finalImage);
81 };
82 img.onerror = () =>
83 {
84 reject(new Error(`Failed to load image '${imageData.name}' from ${imageData.url}`));
85 };
86 img.src = imageData.url;
87 });
88}
89
90function tintedHtmlImage (sourceImg, tintRgb)
91{
92 const canvas = document.createElement("canvas");
93 canvas.width = sourceImg.naturalWidth || sourceImg.width;
94 canvas.height = sourceImg.naturalHeight || sourceImg.height;
95 const ctx = canvas.getContext("2d");
96 ctx.imageSmoothingEnabled = false;
97 ctx.drawImage(sourceImg, 0, 0);
98 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
99 applyMagentaTintToImageData(imageData, tintRgb);
100 ctx.putImageData(imageData, 0, 0);
101 return canvas;
102}
103
104export function applySpriteSheets (images, catalog)
105{
106 for (const entry of catalog?.images ?? [])
107 {
108 const sprite = images[entry.name];
109 if (!sprite)
110 { continue; }
111 sprite._animationSpeed = entry.animationSpeed ?? 0;
112 const frames = entry.subImgTotal || 1;
113 if (frames > 1)
114 {
115 sprite.addAnimationCycle(
116 "idle",
117 Array.from({ length: frames }, (_, index) => index),
118 true
119 );
120 }
121 }
122}
123
124export function shadeDataUrl (fill = "#000000")
125{
126 const canvas = document.createElement("canvas");
127 canvas.width = SPRITE_SIZE_PX;
128 canvas.height = SPRITE_SIZE_PX;
129 const context = canvas.getContext("2d");
130 context.fillStyle = fill;
131 context.fillRect(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX);
132 return canvas.toDataURL("image/png");
133}
134
135/** Hollow square for entity spell targeting (box around a mob / item). */
136export function outlineDataUrl (stroke = "rgba(110, 220, 255, 0.95)", lineWidth = 3)
137{
138 const canvas = document.createElement("canvas");
139 canvas.width = SPRITE_SIZE_PX;
140 canvas.height = SPRITE_SIZE_PX;
141 const context = canvas.getContext("2d");
142 context.strokeStyle = stroke;
143 context.lineWidth = lineWidth;
144 const inset = lineWidth / 2;
145 context.strokeRect(inset, inset, SPRITE_SIZE_PX - lineWidth, SPRITE_SIZE_PX - lineWidth);
146 return canvas.toDataURL("image/png");
147}
148
149function setGlNearest (gl, texture)
150{
151 if (!gl || !texture)
152 { return; }
153 gl.bindTexture(gl.TEXTURE_2D, texture);
154 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
155 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
156}
157
158/** Framework defaults to LINEAR; set NEAREST once at upload for pixel-art games. */
159export function patchNearestNeighbourTextures (scene)
160{
161 const glContext = scene?.glContext;
162 if (!glContext || glContext._nearestPatched)
163 { return; }
164 const gl = glContext.gl;
165 if (typeof glContext.setDefaultTextureFilter === "function")
166 {
167 glContext.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
168 glContext._nearestPatched = true;
169 return;
170 }
171 // Legacy Framework: apply NEAREST once per texture object, not every getTexture hit.
172 const original = glContext.getTexture.bind(glContext);
173 const nearestOnce = new WeakSet();
174 glContext.getTexture = (htmlImage) =>
175 {
176 const texture = original(htmlImage);
177 if (texture && !nearestOnce.has(texture))
178 {
179 setGlNearest(gl, texture);
180 nearestOnce.add(texture);
181 }
182 return texture;
183 };
184 glContext._nearestPatched = true;
185}
186
187/** Canvas atlases and dynamic sprites — call after invalidate/reupload. */
188export function setNearestFilter (scene, source)
189{
190 if (!source)
191 { return; }
192 patchNearestNeighbourTextures(scene);
193 const glContext = scene?.glContext;
194 if (!glContext)
195 { return; }
196 const htmlImage = source.g_image ?? source;
197 const texture = glContext.getTexture(htmlImage);
198 // Text-assert for textures uploaded before NEAREST was the default.
199 if (texture)
200 { setGlNearest(glContext.gl, texture); }
201}
202
203export function applyNearestToAllTextures (scene, images)
204{
205 patchNearestNeighbourTextures(scene);
206 const glContext = scene?.glContext;
207 if (!glContext)
208 { return; }
209 for (const sprite of Object.values(images ?? {}))
210 {
211 const htmlImage = sprite?.g_image ?? sprite;
212 if (htmlImage)
213 { glContext.getTexture(htmlImage); }
214 }
215}
216
217export function useNearestNeighbour (scene, images)
218{
219 applyNearestToAllTextures(scene, images);
220}