BlueGit

timfa questward

Files

questward / client / src / render / sprites.js

sprites.js

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