BlueGit

timfa questward

Files

questward / client / src / render / sprites.js

sprites.js

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