BlueGit

timfa questward

Files

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

generate-stone-wall-sprites.mjs

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