BlueGit

timfa questward

Files

questward / client / scripts / texture-wall-sprites.mjs

texture-wall-sprites.mjs

texture-wall-sprites.mjs 14.9 KiB Download Raw
1/**
2 * Bake wall textures onto thick/thin greyscale face-id shape masks.
3 *
4 * Shape masks (greyscale face-IDs) belong in:
5 * client/assets/blocks/_examples/stone-wall/{thick,thin}-stone-wall*.png
6 *
7 * Workflow when editing shapes in the live gameplay folders:
8 * 1. Paint face-id greys in thick-stone-wall / thin-stone-wall
9 * 2. node client/scripts/texture-wall-sprites.mjs --sync-shapes
10 * (copies live → examples only if files are still face-id greyscale)
11 * 3. node client/scripts/texture-wall-sprites.mjs --variant=…
12 *
13 * Usage:
14 * node client/scripts/texture-wall-sprites.mjs --sync-shapes
15 * node client/scripts/texture-wall-sprites.mjs --variant=cobble|smooth|brick|wood|cliff|--all
16 *
17 * cobble overwrites thick/thin-stone-wall — pass --force (required) so hand tweaks are not clobbered.
18 */
19import { mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync, cpSync } from "node:fs";
20import { deflateSync, inflateSync } from "node:zlib";
21import { fileURLToPath } from "node:url";
22import { dirname, join } from "node:path";
23import { cardinalConnectionSuffix } from "../../shared/world/neighborConnect.js";
24
25const SIZE = 16;
26const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");
27const EXAMPLES = join(ROOT, "_examples/stone-wall");
28const GROUNDS = join(dirname(fileURLToPath(import.meta.url)), "../assets/grounds");
29
30const THICK_ROLE = {
31 0xaf: "N",
32 0x95: "W",
33 0x80: "T",
34 0x6c: "E",
35 0x54: "S",
36 0x40: "O"
37};
38
39const THIN_ROLE = {
40 0xb6: "W",
41 0x95: "N",
42 0x80: "E",
43 0x73: "S",
44 0x40: "O"
45};
46
47function roleOf (prefix, g)
48{
49 const map = prefix.startsWith("thin") ? THIN_ROLE : THICK_ROLE;
50 return map[g] ?? null;
51}
52
53function isTopRole (role)
54{
55 return role === "T" || role === "N";
56}
57
58function crcTable ()
59{
60 const table = new Uint32Array(256);
61 for (let n = 0; n < 256; n++)
62 {
63 let c = n;
64 for (let k = 0; k < 8; k++)
65 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
66 table[n] = c >>> 0;
67 }
68 return table;
69}
70
71const CRC_TABLE = crcTable();
72
73function crc32 (buf)
74{
75 let c = 0xffffffff;
76 for (let i = 0; i < buf.length; i++)
77 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
78 return (c ^ 0xffffffff) >>> 0;
79}
80
81function chunk (type, data)
82{
83 const len = Buffer.alloc(4);
84 len.writeUInt32BE(data.length);
85 const typeBuf = Buffer.from(type, "ascii");
86 const crcBuf = Buffer.alloc(4);
87 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
88 return Buffer.concat([len, typeBuf, data, crcBuf]);
89}
90
91function encodePng (rgba)
92{
93 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
94 for (let y = 0; y < SIZE; y++)
95 {
96 const row = y * (SIZE * 4 + 1);
97 raw[row] = 0;
98 for (let x = 0; x < SIZE; x++)
99 {
100 const i = (y * SIZE + x) * 4;
101 const o = row + 1 + x * 4;
102 raw[o] = rgba[i];
103 raw[o + 1] = rgba[i + 1];
104 raw[o + 2] = rgba[i + 2];
105 raw[o + 3] = rgba[i + 3];
106 }
107 }
108 const ihdr = Buffer.alloc(13);
109 ihdr.writeUInt32BE(SIZE, 0);
110 ihdr.writeUInt32BE(SIZE, 4);
111 ihdr[8] = 8;
112 ihdr[9] = 6;
113 return Buffer.concat([
114 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
115 chunk("IHDR", ihdr),
116 chunk("IDAT", deflateSync(raw, { level: 9 })),
117 chunk("IEND", Buffer.alloc(0))
118 ]);
119}
120
121function decodePngRgba (path)
122{
123 const buf = readFileSync(path);
124 let off = 8;
125 let w = 0;
126 let h = 0;
127 let colorType = 6;
128 const idat = [];
129 while (off < buf.length)
130 {
131 const len = buf.readUInt32BE(off);
132 const type = buf.slice(off + 4, off + 8).toString("ascii");
133 const data = buf.slice(off + 8, off + 8 + len);
134 if (type === "IHDR")
135 {
136 w = data.readUInt32BE(0);
137 h = data.readUInt32BE(4);
138 colorType = data[9];
139 }
140 else if (type === "IDAT")
141 { idat.push(data); }
142 else if (type === "IEND")
143 { break; }
144 off += 12 + len;
145 }
146 const channels = colorType === 2 ? 3 : colorType === 6 ? 4 : 0;
147 if (!channels)
148 { throw new Error(`${path}: unsupported PNG color type ${colorType}`); }
149 const inflated = inflateSync(Buffer.concat(idat));
150 const rgba = new Uint8Array(w * h * 4);
151 let src = 0;
152 const prevRow = new Uint8Array(w * channels);
153 const curRow = new Uint8Array(w * channels);
154 for (let y = 0; y < h; y++)
155 {
156 const filter = inflated[src++];
157 for (let i = 0; i < w * channels; i++)
158 {
159 let v = inflated[src++];
160 if (filter === 1)
161 { v = (v + (i >= channels ? curRow[i - channels] : 0)) & 255; }
162 else if (filter === 2)
163 { v = (v + prevRow[i]) & 255; }
164 else if (filter === 3)
165 {
166 const a = i >= channels ? curRow[i - channels] : 0;
167 v = (v + Math.floor((a + prevRow[i]) / 2)) & 255;
168 }
169 else if (filter === 4)
170 {
171 const a = i >= channels ? curRow[i - channels] : 0;
172 const b = prevRow[i];
173 const c = i >= channels ? prevRow[i - channels] : 0;
174 const p = a + b - c;
175 const pa = Math.abs(p - a);
176 const pb = Math.abs(p - b);
177 const pc = Math.abs(p - c);
178 v = (v + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)) & 255;
179 }
180 curRow[i] = v;
181 }
182 for (let x = 0; x < w; x++)
183 {
184 const si = x * channels;
185 const di = (y * w + x) * 4;
186 rgba[di] = curRow[si];
187 rgba[di + 1] = curRow[si + 1];
188 rgba[di + 2] = curRow[si + 2];
189 rgba[di + 3] = channels === 4 ? curRow[si + 3] : 255;
190 }
191 prevRow.set(curRow);
192 }
193 if (w !== SIZE || h !== SIZE)
194 { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); }
195 return rgba;
196}
197
198function hash2 (x, y)
199{
200 let n = (x * 374761393 + y * 668265263) | 0;
201 n = (n ^ (n >>> 13)) * 1274126177;
202 return (n ^ (n >>> 16)) >>> 0;
203}
204
205function rgba (r, g, b, a = 255)
206{
207 return [r, g, b, a];
208}
209
210function mulRgb (c, factor)
211{
212 return rgba(
213 Math.min(255, Math.round(c[0] * factor)),
214 Math.min(255, Math.round(c[1] * factor)),
215 Math.min(255, Math.round(c[2] * factor)),
216 c[3] ?? 255
217 );
218}
219
220function mixRgb (a, b, t)
221{
222 return rgba(
223 Math.round(a[0] + (b[0] - a[0]) * t),
224 Math.round(a[1] + (b[1] - a[1]) * t),
225 Math.round(a[2] + (b[2] - a[2]) * t),
226 255
227 );
228}
229
230/** Face role → lighting factor (NW light). */
231const ROLE_LIT = { N: 1.15, W: 1.0, T: 1.05, E: 0.82, S: 0.62, O: 0.45 };
232
233function faceLit (role)
234{
235 return ROLE_LIT[role] ?? 0.9;
236}
237
238function loadDirt ()
239{
240 const path = join(GROUNDS, "dirt/dirt.png");
241 if (!existsSync(path))
242 { throw new Error(`Missing dirt texture: ${path}`); }
243 return decodePngRgba(path);
244}
245
246let dirtRgba = null;
247function dirtAt (x, y)
248{
249 if (!dirtRgba)
250 { dirtRgba = loadDirt(); }
251 const i = ((y & 15) * SIZE + (x & 15)) * 4;
252 return rgba(dirtRgba[i], dirtRgba[i + 1], dirtRgba[i + 2]);
253}
254
255/* ---- palettes ---- */
256
257const COBBLE = {
258 N: rgba(198, 198, 202),
259 W: rgba(132, 132, 136),
260 T: rgba(168, 168, 172),
261 E: rgba(112, 112, 116),
262 S: rgba(88, 88, 92),
263 O: rgba(70, 70, 74),
264 mortar: rgba(78, 78, 82),
265 hiN: rgba(210, 210, 214),
266 loS: rgba(78, 78, 82)
267};
268
269const BRICK = {
270 N: rgba(196, 92, 72),
271 W: rgba(168, 72, 56),
272 T: rgba(178, 78, 60),
273 E: rgba(148, 58, 46),
274 S: rgba(118, 48, 38),
275 O: rgba(72, 36, 30),
276 mortar: rgba(92, 78, 68),
277 hi: rgba(210, 110, 88),
278 lo: rgba(100, 42, 34)
279};
280
281function cobbleLike (basePal, x, y, role, gritMask)
282{
283 if (role === "O")
284 {
285 const h = hash2(x, y);
286 return (h & 15) === 0 ? basePal.mortar : basePal.O;
287 }
288 const base = basePal[role] ?? basePal.T;
289 const h = hash2(x, y);
290 const speck = h & gritMask;
291 if (speck === 0)
292 { return basePal.mortar; }
293 if (gritMask === 7)
294 {
295 if (speck === 1 || speck === 2)
296 { return role === "N" || role === "T" ? (basePal.hiN ?? basePal.hi ?? mulRgb(base, 1.12)) : (basePal.hi ?? mulRgb(base, 1.1)); }
297 if (speck === 3)
298 { return role === "S" ? (basePal.loS ?? basePal.lo ?? mulRgb(base, 0.88)) : (basePal.lo ?? mulRgb(base, 0.9)); }
299 }
300 else if (gritMask === 31)
301 {
302 // Smooth: rare soft variation only.
303 if (speck === 1)
304 { return mulRgb(base, 1.06); }
305 if (speck === 2)
306 { return mulRgb(base, 0.94); }
307 }
308 return base;
309}
310
311function brickShade (x, y, role)
312{
313 if (role === "O")
314 { return BRICK.O; }
315 const row = Math.floor(y / 4);
316 const brickX = x + (row & 1) * 3;
317 const onHMortar = (y % 4) === 0;
318 const onVMortar = (brickX % 6) === 0;
319 if (onHMortar || onVMortar)
320 { return BRICK.mortar; }
321 const h = hash2(x, y);
322 if ((h & 15) === 0)
323 { return BRICK.hi; }
324 if ((h & 15) === 1)
325 { return BRICK.lo; }
326 return BRICK[role] ?? BRICK.T;
327}
328
329function woodMagenta (role)
330{
331 // R≈B, G<R — lightness encodes face.
332 const L = {
333 O: 55,
334 S: 95,
335 E: 120,
336 W: 155,
337 T: 185,
338 N: 210
339 }[role] ?? 140;
340 const gHi = role === "N" || role === "T" ? Math.min(L - 20, 50) : 0;
341 return rgba(L, gHi, L);
342}
343
344/**
345 * Cliff magenta tops: thick = plateau only (N is a dirt north face).
346 * Thin has no separate T — ridge top is role N.
347 */
348function isCliffTopRole (role, shapePrefix)
349{
350 if (shapePrefix.startsWith("thin"))
351 { return role === "N"; }
352 return role === "T";
353}
354
355function cliffShade (x, y, role, shapePrefix)
356{
357 if (isCliffTopRole(role, shapePrefix))
358 {
359 // Full magenta top — replaced in-game by ground sample shader.
360 return rgba(255, 0, 255);
361 }
362 if (role === "O")
363 {
364 const d = dirtAt(x, y);
365 return mulRgb(d, 0.35);
366 }
367 const d = dirtAt(x, y);
368 return mulRgb(d, faceLit(role));
369}
370
371function paintPixel (variant, prefix, g, x, y)
372{
373 const role = roleOf(prefix, g);
374 if (!role)
375 {
376 // Unknown grey: luminance fallback toward mid face.
377 const lit = g / 128;
378 if (variant === "wood")
379 { return rgba(Math.round(140 * lit), 0, Math.round(140 * lit)); }
380 if (variant === "cliff")
381 { return mulRgb(dirtAt(x, y), lit); }
382 if (variant === "brick")
383 { return mulRgb(BRICK.T, lit); }
384 return mulRgb(COBBLE.T, lit);
385 }
386 if (variant === "cobble")
387 { return cobbleLike(COBBLE, x, y, role, 7); }
388 if (variant === "smooth")
389 { return cobbleLike(COBBLE, x, y, role, 31); }
390 if (variant === "brick")
391 { return brickShade(x, y, role); }
392 if (variant === "wood")
393 { return woodMagenta(role); }
394 if (variant === "cliff")
395 { return cliffShade(x, y, role, prefix); }
396 throw new Error(`Unknown variant ${variant}`);
397}
398
399function textureMask (rgbaIn, variant, shapePrefix)
400{
401 const out = new Uint8Array(SIZE * SIZE * 4);
402 for (let y = 0; y < SIZE; y++)
403 {
404 for (let x = 0; x < SIZE; x++)
405 {
406 const i = (y * SIZE + x) * 4;
407 if (rgbaIn[i + 3] === 0)
408 { continue; }
409 const color = paintPixel(variant, shapePrefix, rgbaIn[i], x, y);
410 out[i] = color[0];
411 out[i + 1] = color[1];
412 out[i + 2] = color[2];
413 out[i + 3] = 255;
414 }
415 }
416 return out;
417}
418
419const VARIANT_OUT = {
420 cobble: {
421 thick: { dir: "thick-stone-wall", named: true, prefix: "thick-stone-wall" },
422 thin: { dir: "thin-stone-wall", named: true, prefix: "thin-stone-wall" }
423 },
424 smooth: {
425 thick: { dir: "thick-smooth-stone-wall", named: true, prefix: "thick-smooth-stone-wall" },
426 thin: { dir: "thin-smooth-stone-wall", named: true, prefix: "thin-smooth-stone-wall" }
427 },
428 brick: {
429 thick: { dir: "thick-brick-wall", named: true, prefix: "thick-brick-wall" },
430 thin: { dir: "thin-brick-wall", named: true, prefix: "thin-brick-wall" }
431 },
432 wood: {
433 thick: { dir: "thick-wood-wall", named: false, prefix: "thick-stone-wall" },
434 thin: { dir: "thin-wood-wall", named: false, prefix: "thin-stone-wall" }
435 },
436 cliff: {
437 thick: { dir: "thick-cliff", named: true, prefix: "thick-cliff" },
438 thin: { dir: "thin-cliff", named: true, prefix: "thin-cliff" }
439 }
440};
441
442function shapeFiles (shapeKey)
443{
444 return readdirSync(EXAMPLES)
445 .filter((name) => name.startsWith(shapeKey) && name.endsWith(".png") && !name.includes("ref-"))
446 .sort();
447}
448
449function namedOutName (outPrefix, shapeName, shapeKey)
450{
451 // thick-stone-wall-esw.png → thick-smooth-stone-wall-esw.png
452 const suffix = shapeName.slice(shapeKey.length); // "" or "-esw"
453 return `${outPrefix}${suffix}`;
454}
455
456const FACE_ID_GREYS = new Set([
457 0x40, 0x54, 0x6c, 0x73, 0x80, 0x95, 0xaf, 0xb6
458]);
459
460function isFaceIdMask (rgba)
461{
462 for (let i = 0; i < rgba.length; i += 4)
463 {
464 if (rgba[i + 3] === 0)
465 { continue; }
466 if (rgba[i] !== rgba[i + 1] || rgba[i] !== rgba[i + 2])
467 { return false; }
468 if (!FACE_ID_GREYS.has(rgba[i]))
469 { return false; }
470 }
471 return true;
472}
473
474/** Copy face-id greyscale from live thick/thin-stone-wall → _examples (never textured art). */
475function syncShapesFromLive ()
476{
477 mkdirSync(EXAMPLES, { recursive: true });
478 let copied = 0;
479 for (const kind of ["thick", "thin"])
480 {
481 const shapeKey = `${kind}-stone-wall`;
482 const liveDir = join(ROOT, shapeKey);
483 if (!existsSync(liveDir))
484 { throw new Error(`Missing live folder ${liveDir}`); }
485 const files = readdirSync(liveDir)
486 .filter((name) => name.startsWith(shapeKey) && name.endsWith(".png"))
487 .sort();
488 if (files.length !== 16)
489 { throw new Error(`Expected 16 live ${shapeKey} sprites, found ${files.length}`); }
490 for (const name of files)
491 {
492 const rgba = decodePngRgba(join(liveDir, name));
493 if (!isFaceIdMask(rgba))
494 {
495 throw new Error(
496 `${shapeKey}/${name} is not a face-id greyscale mask (already textured?). ` +
497 `Paint face-id greys in the live folder, then re-run --sync-shapes.`
498 );
499 }
500 cpSync(join(liveDir, name), join(EXAMPLES, name));
501 copied++;
502 }
503 console.log(` synced ${kind} → ${EXAMPLES}`);
504 }
505 console.log(`Synced ${copied} face-id masks into examples.`);
506}
507
508function bakeVariant (variant, { force = false } = {})
509{
510 const cfg = VARIANT_OUT[variant];
511 if (!cfg)
512 { throw new Error(`Unknown variant: ${variant}`); }
513 if (variant === "cobble" && !force)
514 {
515 throw new Error(
516 "Refusing to overwrite thick/thin-stone-wall without --force " +
517 "(hand-tweaked gameplay sprites). Sync shapes with --sync-shapes first if needed."
518 );
519 }
520 let wrote = 0;
521 for (const kind of ["thick", "thin"])
522 {
523 const shapeKey = `${kind}-stone-wall`;
524 const out = cfg[kind];
525 const outDir = join(ROOT, out.dir);
526 mkdirSync(outDir, { recursive: true });
527 const files = shapeFiles(shapeKey);
528 if (files.length !== 16)
529 { throw new Error(`Expected 16 ${shapeKey} masks, found ${files.length}`); }
530
531 if (out.named)
532 {
533 for (const name of files)
534 {
535 const shaped = decodePngRgba(join(EXAMPLES, name));
536 const textured = textureMask(shaped, variant, shapeKey);
537 const outName = namedOutName(out.prefix, name, shapeKey);
538 writeFileSync(join(outDir, outName), encodePng(textured));
539 wrote++;
540 }
541 }
542 else
543 {
544 for (let mask = 0; mask < 16; mask++)
545 {
546 const suffix = cardinalConnectionSuffix(mask);
547 const shapeName = suffix ? `${shapeKey}-${suffix}.png` : `${shapeKey}.png`;
548 const shaped = decodePngRgba(join(EXAMPLES, shapeName));
549 const textured = textureMask(shaped, variant, shapeKey);
550 writeFileSync(join(outDir, `${mask}.png`), encodePng(textured));
551 wrote++;
552 }
553 }
554 console.log(` ${variant} ${kind} → ${outDir} (${out.named ? "named" : "0–15"})`);
555 }
556 return wrote;
557}
558
559if (process.argv.includes("--sync-shapes"))
560{
561 syncShapesFromLive();
562 process.exit(0);
563}
564
565const arg = process.argv.find((a) => a.startsWith("--variant="));
566const variant = arg ? arg.slice("--variant=".length) : null;
567if (!variant)
568{
569 console.error("Usage: --sync-shapes | --variant=cobble|smooth|brick|wood|cliff|all [--force]");
570 process.exit(1);
571}
572const force = process.argv.includes("--force");
573const list = variant === "all"
574 ? ["cobble", "smooth", "brick", "wood", "cliff"]
575 : [variant];
576
577if (!existsSync(EXAMPLES))
578{ throw new Error(`Missing ${EXAMPLES}`); }
579
580let total = 0;
581for (const v of list)
582{
583 console.log(`Baking ${v}…`);
584 total += bakeVariant(v, { force });
585}
586console.log(`Done (${total} sprites).`);