BlueGit

timfa questward

Files

questward / client / scripts / generate-stone-wall-sprites.mjs

generate-stone-wall-sprites.mjs

wall texture
timfa Tim Falken · pushed by timfa · 2 months ago
0896e8da History
generate-stone-wall-sprites.mjs 10.7 KiB Download Raw
1/**
2 * Generate thin + thick stone-wall PNGs for the 16 cardinal neighbor masks.
3 *
4 * Naming: `{key}.png` alone, `{key}-{suffix}.png` when connected.
5 * Suffixes: n/e/s/w, ns, we, ne/es/sw/wn, esw/wne/swn/nes, nesw.
6 *
7 * Examples (shape only, no texture) live in
8 * client/assets/blocks/_examples/stone-wall/
9 *
10 * node client/scripts/generate-stone-wall-sprites.mjs
11 */
12import
13 {
14 mkdirSync,
15 writeFileSync,
16 readdirSync,
17 unlinkSync,
18 readFileSync,
19 existsSync,
20 cpSync,
21 rmSync
22 } from "node:fs";
23import { deflateSync, inflateSync } from "node:zlib";
24import { fileURLToPath } from "node:url";
25import { dirname, join } from "node:path";
26import
27 {
28 NeighborBit,
29 cardinalConnectionSuffix,
30 composeNamedNeighborConnectState
31 } from "../../shared/world/neighborConnect.js";
32
33const SIZE = 16;
34const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");
35const EXAMPLES = join(ROOT, "_examples/stone-wall");
36const OUT_THICK = join(ROOT, "thick-stone-wall");
37const OUT_THIN = join(ROOT, "thin-stone-wall");
38
39const THICK = { key: "thick-stone-wall", neighborConnect: true, neighborConnectNamed: true };
40const THIN = { key: "thin-stone-wall", neighborConnect: true, neighborConnectNamed: true };
41
42function crcTable ()
43{
44 const table = new Uint32Array(256);
45 for (let n = 0; n < 256; n++)
46 {
47 let c = n;
48 for (let k = 0; k < 8; k++)
49 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
50 table[n] = c >>> 0;
51 }
52 return table;
53}
54
55const CRC_TABLE = crcTable();
56
57function crc32 (buf)
58{
59 let c = 0xffffffff;
60 for (let i = 0; i < buf.length; i++)
61 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
62 return (c ^ 0xffffffff) >>> 0;
63}
64
65function chunk (type, data)
66{
67 const len = Buffer.alloc(4);
68 len.writeUInt32BE(data.length);
69 const typeBuf = Buffer.from(type, "ascii");
70 const crcBuf = Buffer.alloc(4);
71 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
72 return Buffer.concat([len, typeBuf, data, crcBuf]);
73}
74
75function encodePng (rgba)
76{
77 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
78 for (let y = 0; y < SIZE; y++)
79 {
80 const row = y * (SIZE * 4 + 1);
81 raw[row] = 0;
82 for (let x = 0; x < SIZE; x++)
83 {
84 const i = (y * SIZE + x) * 4;
85 const o = row + 1 + x * 4;
86 raw[o] = rgba[i];
87 raw[o + 1] = rgba[i + 1];
88 raw[o + 2] = rgba[i + 2];
89 raw[o + 3] = rgba[i + 3];
90 }
91 }
92 const ihdr = Buffer.alloc(13);
93 ihdr.writeUInt32BE(SIZE, 0);
94 ihdr.writeUInt32BE(SIZE, 4);
95 ihdr[8] = 8;
96 ihdr[9] = 6;
97 return Buffer.concat([
98 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
99 chunk("IHDR", ihdr),
100 chunk("IDAT", deflateSync(raw, { level: 9 })),
101 chunk("IEND", Buffer.alloc(0))
102 ]);
103}
104
105function decodePngRgba (path)
106{
107 const buf = readFileSync(path);
108 let off = 8;
109 let w = 0;
110 let h = 0;
111 const idat = [];
112 while (off < buf.length)
113 {
114 const len = buf.readUInt32BE(off);
115 const type = buf.slice(off + 4, off + 8).toString("ascii");
116 const data = buf.slice(off + 8, off + 8 + len);
117 if (type === "IHDR")
118 {
119 w = data.readUInt32BE(0);
120 h = data.readUInt32BE(4);
121 if (data[8] !== 8 || data[9] !== 6)
122 { throw new Error(`${path}: expected 8-bit RGBA`); }
123 }
124 else if (type === "IDAT")
125 { idat.push(data); }
126 else if (type === "IEND")
127 { break; }
128 off += 12 + len;
129 }
130 const raw = inflateSync(Buffer.concat(idat));
131 const bpp = 4;
132 const stride = w * bpp;
133 const rgba = new Uint8ClampedArray(w * h * 4);
134 let src = 0;
135 const prev = Buffer.alloc(stride);
136 const cur = Buffer.alloc(stride);
137 for (let y = 0; y < h; y++)
138 {
139 const filter = raw[src++];
140 for (let i = 0; i < stride; i++)
141 { cur[i] = raw[src++]; }
142 for (let i = 0; i < stride; i++)
143 {
144 const left = i >= bpp ? cur[i - bpp] : 0;
145 const up = prev[i];
146 const upLeft = i >= bpp ? prev[i - bpp] : 0;
147 let val = cur[i];
148 if (filter === 1)
149 { val = (val + left) & 255; }
150 else if (filter === 2)
151 { val = (val + up) & 255; }
152 else if (filter === 3)
153 { val = (val + ((left + up) >> 1)) & 255; }
154 else if (filter === 4)
155 {
156 const p = left + up - upLeft;
157 const pa = Math.abs(p - left);
158 const pb = Math.abs(p - up);
159 const pc = Math.abs(p - upLeft);
160 const pr = (pa <= pb && pa <= pc) ? left : (pb <= pc ? up : upLeft);
161 val = (val + pr) & 255;
162 }
163 cur[i] = val;
164 }
165 rgba.set(cur, y * stride);
166 prev.set(cur);
167 }
168 if (w !== SIZE || h !== SIZE)
169 { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); }
170 return rgba;
171}
172
173function loadExample (name)
174{
175 const path = join(EXAMPLES, name);
176 if (!existsSync(path))
177 { return null; }
178 return decodePngRgba(path);
179}
180
181function getPx (rgba, x, y)
182{
183 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
184 { return [0, 0, 0, 0]; }
185 const i = (y * SIZE + x) * 4;
186 return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];
187}
188
189function setPx (rgba, x, y, color)
190{
191 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
192 { return; }
193 const i = (y * SIZE + x) * 4;
194 rgba[i] = color[0];
195 rgba[i + 1] = color[1];
196 rgba[i + 2] = color[2];
197 rgba[i + 3] = color[3];
198}
199
200function opaque (rgba, x, y)
201{
202 return getPx(rgba, x, y)[3] > 128;
203}
204
205function copyRgba (rgba)
206{
207 return new Uint8ClampedArray(rgba);
208}
209
210function clearRgba ()
211{
212 return new Uint8ClampedArray(SIZE * SIZE * 4);
213}
214
215function mirrorX (rgba)
216{
217 const out = clearRgba();
218 for (let y = 0; y < SIZE; y++)
219 {
220 for (let x = 0; x < SIZE; x++)
221 { setPx(out, x, y, getPx(rgba, SIZE - 1 - x, y)); }
222 }
223 return out;
224}
225
226function blit (dst, src)
227{
228 if (!src)
229 { return; }
230 for (let y = 0; y < SIZE; y++)
231 {
232 for (let x = 0; x < SIZE; x++)
233 {
234 const c = getPx(src, x, y);
235 if (c[3] > 128)
236 { setPx(dst, x, y, c); }
237 }
238 }
239}
240
241/** Ensure example folder exists; migrate from legacy stone-wall/ if needed. */
242function ensureExamples ()
243{
244 mkdirSync(EXAMPLES, { recursive: true });
245 const legacy = join(ROOT, "stone-wall");
246 if (!existsSync(legacy))
247 { return; }
248 for (const name of readdirSync(legacy))
249 {
250 if (!name.startsWith("example-") || !name.endsWith(".png"))
251 { continue; }
252 const dest = join(EXAMPLES, name);
253 if (!existsSync(dest))
254 { cpSync(join(legacy, name), dest); }
255 }
256}
257
258function buildPack (kind)
259{
260 const alone = loadExample(`example-stone-${kind}.png`);
261 const east = loadExample(`example-stone-${kind}-connecting.png`);
262 const north = loadExample(`example-stone-${kind}-connecting-up.png`);
263 const south = loadExample(`example-stone-${kind}-connecting-down.png`);
264 const ns = loadExample(`example-stone-${kind}-connecting-updown.png`);
265 const ellNE = loadExample(`example-stone-${kind}-connecting-L.png`);
266 const ellSE = loadExample(`example-stone-${kind}-connecting-Ldownright.png`);
267 const teeESW = loadExample(`example-stone-${kind}-T.png`)
268 ?? loadExample(`example-stone-${kind}-connecting-T.png`);
269 const teeNEW = loadExample(`example-stone-${kind}-connecting-T-upsidedown.png`);
270
271 if (!alone || !east || !north || !ns)
272 { throw new Error(`Missing core ${kind} examples in ${EXAMPLES}`); }
273
274 const west = mirrorX(east);
275 const southFinal = south ?? (() =>
276 {
277 const out = copyRgba(alone);
278 for (let y = 10; y < SIZE; y++)
279 {
280 for (let x = 0; x < SIZE; x++)
281 {
282 if (opaque(ns, x, y))
283 { setPx(out, x, y, getPx(ns, x, y)); }
284 }
285 }
286 return out;
287 })();
288
289 const ellNEFinal = ellNE ?? (() =>
290 {
291 const out = clearRgba();
292 blit(out, north);
293 blit(out, east);
294 return out;
295 })();
296 const ellSEFinal = ellSE ?? (() =>
297 {
298 const out = clearRgba();
299 blit(out, southFinal);
300 blit(out, east);
301 return out;
302 })();
303 const ellNW = mirrorX(ellNEFinal);
304 const ellSW = mirrorX(ellSEFinal);
305
306 const ew = (() =>
307 {
308 const out = clearRgba();
309 blit(out, east);
310 blit(out, west);
311 for (let y = 0; y < SIZE; y++)
312 {
313 if (!opaque(east, SIZE - 1, y))
314 { continue; }
315 let fill = null;
316 for (let x = SIZE - 1; x >= 0; x--)
317 {
318 const c = getPx(east, x, y);
319 if (c[3] > 128)
320 { fill = c; break; }
321 }
322 if (!fill)
323 { continue; }
324 for (let x = 0; x < SIZE; x++)
325 {
326 if (!opaque(out, x, y))
327 { setPx(out, x, y, fill); }
328 }
329 }
330 return out;
331 })();
332
333 const teeESWFinal = teeESW ?? (() =>
334 {
335 const out = clearRgba();
336 blit(out, ew);
337 blit(out, southFinal);
338 return out;
339 })();
340 const teeNEWFinal = teeNEW ?? (() =>
341 {
342 const out = clearRgba();
343 blit(out, ew);
344 blit(out, north);
345 return out;
346 })();
347 const teeNES = (() =>
348 {
349 const out = clearRgba();
350 blit(out, north);
351 blit(out, east);
352 blit(out, southFinal);
353 return out;
354 })();
355 const teeNWS = mirrorX(teeNES);
356 const all = (() =>
357 {
358 const out = clearRgba();
359 blit(out, ns);
360 blit(out, ew);
361 return out;
362 })();
363
364 const byMask = new Map([
365 [0, alone],
366 [NeighborBit.n, north],
367 [NeighborBit.e, east],
368 [NeighborBit.s, southFinal],
369 [NeighborBit.w, west],
370 [NeighborBit.n | NeighborBit.s, ns],
371 [NeighborBit.e | NeighborBit.w, ew],
372 [NeighborBit.n | NeighborBit.e, ellNEFinal],
373 [NeighborBit.e | NeighborBit.s, ellSEFinal],
374 [NeighborBit.s | NeighborBit.w, ellSW],
375 [NeighborBit.w | NeighborBit.n, ellNW],
376 [NeighborBit.e | NeighborBit.s | NeighborBit.w, teeESWFinal],
377 [NeighborBit.w | NeighborBit.n | NeighborBit.e, teeNEWFinal],
378 [NeighborBit.n | NeighborBit.e | NeighborBit.s, teeNES],
379 [NeighborBit.n | NeighborBit.w | NeighborBit.s, teeNWS],
380 [NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w, all]
381 ]);
382
383 return { byMask, alone, east, north, ns, ellNE: ellNEFinal };
384}
385
386function clearGenerated (dir)
387{
388 mkdirSync(dir, { recursive: true });
389 for (const name of readdirSync(dir))
390 {
391 if (!name.endsWith(".png") || name.startsWith("example"))
392 { continue; }
393 unlinkSync(join(dir, name));
394 }
395}
396
397function writeSet (dir, def, pack)
398{
399 clearGenerated(dir);
400 for (let mask = 0; mask < 16; mask++)
401 {
402 const rgba = pack.byMask.get(mask);
403 if (!rgba)
404 { throw new Error(`Missing mask ${mask} for ${def.key}`); }
405 const state = composeNamedNeighborConnectState(def, mask);
406 writeFileSync(join(dir, `${state}.png`), encodePng(rgba));
407 }
408 console.log(`Wrote 16 ${def.key} sprites → ${dir}`);
409}
410
411function removeLegacyFolders ()
412{
413 for (const name of ["stone-wall", "stone-wall-thin"])
414 {
415 const dir = join(ROOT, name);
416 if (!existsSync(dir))
417 { continue; }
418 // Keep examples only in _examples/; remove entire legacy folder.
419 rmSync(dir, { recursive: true, force: true });
420 console.log(`Removed legacy ${name}/`);
421 }
422}
423
424ensureExamples();
425const thin = buildPack("thin");
426const thick = buildPack("thick");
427
428function assertSame (a, b, label)
429{
430 for (let i = 0; i < a.length; i++)
431 {
432 if (a[i] !== b[i])
433 { throw new Error(`Mismatch ${label}`); }
434 }
435}
436assertSame(thin.byMask.get(0), thin.alone, "thin alone");
437assertSame(thin.byMask.get(1), thin.north, "thin n");
438assertSame(thin.byMask.get(2), thin.east, "thin e");
439assertSame(thin.byMask.get(5), thin.ns, "thin ns");
440assertSame(thick.byMask.get(0), thick.alone, "thick alone");
441
442writeSet(OUT_THIN, THIN, thin);
443writeSet(OUT_THICK, THICK, thick);
444removeLegacyFolders();
445
446console.log("Suffixes:", [...Array(16)].map((_, m) => `${m}=${cardinalConnectionSuffix(m) || "(alone)"}`).join(", "));