BlueGit

timfa questward

Files

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

texture-wall-sprites.mjs

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