BlueGit

timfa questward

lots of things

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
07a95f71ac0314e03af268a888fe22a3090a5d17
Parent
8b0ae105
40 files changed +1985 −141
client/assets/items/axe/axe-equip.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/axe/axe.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/pickaxe/pickaxe-equip.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/pickaxe/pickaxe.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/quarterstaff/quarterstaff-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/quarterstaff/quarterstaff.png added Binary file +0 −0

The contents of this binary file are not shown.

client/scripts/convert-dual-channel-png.mjs added +188 −0
@@ -0,0 +1,188 @@
1 /**
2 * Convert item sprites to dual-channel tint masks from magenta + natural art.
3 *
4 * - Magenta-family pixels (R≈B, G<R) → pure blue mask (0, 0, L), L = max(R, B)
5 * - All other opaque pixels → pure red mask (L, 0, 0), L = max(R, G, B)
6 * - Near-white pixels (fletching) are left unchanged
7 *
8 * Usage: node client/scripts/convert-dual-channel-png.mjs <input.png> [output.png]
9 */
10 import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
11 import { dirname } from "node:path";
12 import { deflateSync, inflateSync } from "node:zlib";
13 import { MAGENTA_CHANNEL_TOLERANCE } from "../../shared/render/tint.js";
14
15 function crcTable ()
16 {
17 const table = new Uint32Array(256);
18 for (let n = 0; n < 256; n++)
19 {
20 let c = n;
21 for (let k = 0; k < 8; k++)
22 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
23 table[n] = c >>> 0;
24 }
25 return table;
26 }
27
28 const CRC_TABLE = crcTable();
29
30 function crc32 (buf)
31 {
32 let c = 0xffffffff;
33 for (let i = 0; i < buf.length; i++)
34 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
35 return (c ^ 0xffffffff) >>> 0;
36 }
37
38 function chunk (type, data)
39 {
40 const len = Buffer.alloc(4);
41 len.writeUInt32BE(data.length);
42 const typeBuf = Buffer.from(type, "ascii");
43 const crcBuf = Buffer.alloc(4);
44 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
45 return Buffer.concat([len, typeBuf, data, crcBuf]);
46 }
47
48 function decodePngRgba (buf)
49 {
50 let off = 8;
51 let w = 0;
52 let h = 0;
53 const idat = [];
54 while (off < buf.length)
55 {
56 const len = buf.readUInt32BE(off);
57 const type = buf.slice(off + 4, off + 8).toString("ascii");
58 const data = buf.slice(off + 8, off + 8 + len);
59 if (type === "IHDR")
60 {
61 w = data.readUInt32BE(0);
62 h = data.readUInt32BE(4);
63 }
64 else if (type === "IDAT")
65 { idat.push(data); }
66 else if (type === "IEND")
67 { break; }
68 off += 12 + len;
69 }
70 const raw = inflateSync(Buffer.concat(idat));
71 const stride = 1 + w * 4;
72 const rgba = new Uint8Array(w * h * 4);
73 for (let y = 0; y < h; y++)
74 {
75 for (let x = 0; x < w; x++)
76 {
77 const i = y * stride + 1 + x * 4;
78 const o = (y * w + x) * 4;
79 rgba[o] = raw[i];
80 rgba[o + 1] = raw[i + 1];
81 rgba[o + 2] = raw[i + 2];
82 rgba[o + 3] = raw[i + 3];
83 }
84 }
85 return { width: w, height: h, rgba };
86 }
87
88 function encodePng ({ width, height, rgba })
89 {
90 const raw = Buffer.alloc((width * 4 + 1) * height);
91 for (let y = 0; y < height; y++)
92 {
93 const row = y * (width * 4 + 1);
94 raw[row] = 0;
95 for (let x = 0; x < width; x++)
96 {
97 const i = (y * width + x) * 4;
98 const o = row + 1 + x * 4;
99 raw[o] = rgba[i];
100 raw[o + 1] = rgba[i + 1];
101 raw[o + 2] = rgba[i + 2];
102 raw[o + 3] = rgba[i + 3];
103 }
104 }
105 const ihdr = Buffer.alloc(13);
106 ihdr.writeUInt32BE(width, 0);
107 ihdr.writeUInt32BE(height, 4);
108 ihdr[8] = 8;
109 ihdr[9] = 6;
110 return Buffer.concat([
111 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
112 chunk("IHDR", ihdr),
113 chunk("IDAT", deflateSync(raw, { level: 9 })),
114 chunk("IEND", Buffer.alloc(0))
115 ]);
116 }
117
118 function isMagentaPixel (r, g, b)
119 {
120 return Math.abs(r - b) <= MAGENTA_CHANNEL_TOLERANCE && g < r;
121 }
122
123 function isNeutralWhite (r, g, b)
124 {
125 return r >= 240 && g >= 240 && b >= 240;
126 }
127
128 /** @returns {[number, number, number, number]} */
129 function toDualChannelPixel (r, g, b, a)
130 {
131 if (a < 8)
132 { return [0, 0, 0, 0]; }
133 if (isNeutralWhite(r, g, b))
134 { return [r, g, b, a]; }
135 if (isMagentaPixel(r, g, b))
136 {
137 const L = Math.max(r, b);
138 return [0, 0, L, a];
139 }
140 const L = Math.max(r, g, b);
141 return [L, 0, 0, a];
142 }
143
144 /** @returns {{ red: number, blue: number, white: number, opaque: number }} */
145 function convertDualChannel ({ width, height, rgba })
146 {
147 const stats = { red: 0, blue: 0, white: 0, opaque: 0 };
148 for (let i = 0; i < rgba.length; i += 4)
149 {
150 const r = rgba[i];
151 const g = rgba[i + 1];
152 const b = rgba[i + 2];
153 const a = rgba[i + 3];
154 const next = toDualChannelPixel(r, g, b, a);
155 rgba[i] = next[0];
156 rgba[i + 1] = next[1];
157 rgba[i + 2] = next[2];
158 rgba[i + 3] = next[3];
159 if (a < 8)
160 { continue; }
161 stats.opaque++;
162 if (isNeutralWhite(r, g, b))
163 { stats.white++; }
164 else if (isMagentaPixel(r, g, b))
165 { stats.blue++; }
166 else
167 { stats.red++; }
168 }
169 return stats;
170 }
171
172 const [inputPath, outputPathArg] = process.argv.slice(2);
173 if (!inputPath)
174 {
175 console.error("Usage: node convert-dual-channel-png.mjs <input.png> [output.png]");
176 process.exit(1);
177 }
178
179 const outputPath = outputPathArg ?? inputPath;
180 const image = decodePngRgba(readFileSync(inputPath));
181 const stats = convertDualChannel(image);
182 mkdirSync(dirname(outputPath), { recursive: true });
183 writeFileSync(outputPath, encodePng(image));
184 console.log(
185 `Wrote ${outputPath} (${image.width}×${image.height}) — `
186 + `${stats.opaque} opaque → ${stats.red} red, ${stats.blue} blue`
187 + (stats.white ? `, ${stats.white} white` : "")
188 );
@@ -0,0 +1,188 @@
1/**
2 * Convert item sprites to dual-channel tint masks from magenta + natural art.
3 *
4 * - Magenta-family pixels (R≈B, G<R) → pure blue mask (0, 0, L), L = max(R, B)
5 * - All other opaque pixels → pure red mask (L, 0, 0), L = max(R, G, B)
6 * - Near-white pixels (fletching) are left unchanged
7 *
8 * Usage: node client/scripts/convert-dual-channel-png.mjs <input.png> [output.png]
9 */
10import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
11import { dirname } from "node:path";
12import { deflateSync, inflateSync } from "node:zlib";
13import { MAGENTA_CHANNEL_TOLERANCE } from "../../shared/render/tint.js";
14
15function crcTable ()
16{
17 const table = new Uint32Array(256);
18 for (let n = 0; n < 256; n++)
19 {
20 let c = n;
21 for (let k = 0; k < 8; k++)
22 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
23 table[n] = c >>> 0;
24 }
25 return table;
26}
27
28const CRC_TABLE = crcTable();
29
30function crc32 (buf)
31{
32 let c = 0xffffffff;
33 for (let i = 0; i < buf.length; i++)
34 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
35 return (c ^ 0xffffffff) >>> 0;
36}
37
38function chunk (type, data)
39{
40 const len = Buffer.alloc(4);
41 len.writeUInt32BE(data.length);
42 const typeBuf = Buffer.from(type, "ascii");
43 const crcBuf = Buffer.alloc(4);
44 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
45 return Buffer.concat([len, typeBuf, data, crcBuf]);
46}
47
48function decodePngRgba (buf)
49{
50 let off = 8;
51 let w = 0;
52 let h = 0;
53 const idat = [];
54 while (off < buf.length)
55 {
56 const len = buf.readUInt32BE(off);
57 const type = buf.slice(off + 4, off + 8).toString("ascii");
58 const data = buf.slice(off + 8, off + 8 + len);
59 if (type === "IHDR")
60 {
61 w = data.readUInt32BE(0);
62 h = data.readUInt32BE(4);
63 }
64 else if (type === "IDAT")
65 { idat.push(data); }
66 else if (type === "IEND")
67 { break; }
68 off += 12 + len;
69 }
70 const raw = inflateSync(Buffer.concat(idat));
71 const stride = 1 + w * 4;
72 const rgba = new Uint8Array(w * h * 4);
73 for (let y = 0; y < h; y++)
74 {
75 for (let x = 0; x < w; x++)
76 {
77 const i = y * stride + 1 + x * 4;
78 const o = (y * w + x) * 4;
79 rgba[o] = raw[i];
80 rgba[o + 1] = raw[i + 1];
81 rgba[o + 2] = raw[i + 2];
82 rgba[o + 3] = raw[i + 3];
83 }
84 }
85 return { width: w, height: h, rgba };
86}
87
88function encodePng ({ width, height, rgba })
89{
90 const raw = Buffer.alloc((width * 4 + 1) * height);
91 for (let y = 0; y < height; y++)
92 {
93 const row = y * (width * 4 + 1);
94 raw[row] = 0;
95 for (let x = 0; x < width; x++)
96 {
97 const i = (y * width + x) * 4;
98 const o = row + 1 + x * 4;
99 raw[o] = rgba[i];
100 raw[o + 1] = rgba[i + 1];
101 raw[o + 2] = rgba[i + 2];
102 raw[o + 3] = rgba[i + 3];
103 }
104 }
105 const ihdr = Buffer.alloc(13);
106 ihdr.writeUInt32BE(width, 0);
107 ihdr.writeUInt32BE(height, 4);
108 ihdr[8] = 8;
109 ihdr[9] = 6;
110 return Buffer.concat([
111 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
112 chunk("IHDR", ihdr),
113 chunk("IDAT", deflateSync(raw, { level: 9 })),
114 chunk("IEND", Buffer.alloc(0))
115 ]);
116}
117
118function isMagentaPixel (r, g, b)
119{
120 return Math.abs(r - b) <= MAGENTA_CHANNEL_TOLERANCE && g < r;
121}
122
123function isNeutralWhite (r, g, b)
124{
125 return r >= 240 && g >= 240 && b >= 240;
126}
127
128/** @returns {[number, number, number, number]} */
129function toDualChannelPixel (r, g, b, a)
130{
131 if (a < 8)
132 { return [0, 0, 0, 0]; }
133 if (isNeutralWhite(r, g, b))
134 { return [r, g, b, a]; }
135 if (isMagentaPixel(r, g, b))
136 {
137 const L = Math.max(r, b);
138 return [0, 0, L, a];
139 }
140 const L = Math.max(r, g, b);
141 return [L, 0, 0, a];
142}
143
144/** @returns {{ red: number, blue: number, white: number, opaque: number }} */
145function convertDualChannel ({ width, height, rgba })
146{
147 const stats = { red: 0, blue: 0, white: 0, opaque: 0 };
148 for (let i = 0; i < rgba.length; i += 4)
149 {
150 const r = rgba[i];
151 const g = rgba[i + 1];
152 const b = rgba[i + 2];
153 const a = rgba[i + 3];
154 const next = toDualChannelPixel(r, g, b, a);
155 rgba[i] = next[0];
156 rgba[i + 1] = next[1];
157 rgba[i + 2] = next[2];
158 rgba[i + 3] = next[3];
159 if (a < 8)
160 { continue; }
161 stats.opaque++;
162 if (isNeutralWhite(r, g, b))
163 { stats.white++; }
164 else if (isMagentaPixel(r, g, b))
165 { stats.blue++; }
166 else
167 { stats.red++; }
168 }
169 return stats;
170}
171
172const [inputPath, outputPathArg] = process.argv.slice(2);
173if (!inputPath)
174{
175 console.error("Usage: node convert-dual-channel-png.mjs <input.png> [output.png]");
176 process.exit(1);
177}
178
179const outputPath = outputPathArg ?? inputPath;
180const image = decodePngRgba(readFileSync(inputPath));
181const stats = convertDualChannel(image);
182mkdirSync(dirname(outputPath), { recursive: true });
183writeFileSync(outputPath, encodePng(image));
184console.log(
185 `Wrote ${outputPath} (${image.width}×${image.height}) — `
186 + `${stats.opaque} opaque → ${stats.red} red, ${stats.blue} blue`
187 + (stats.white ? `, ${stats.white} white` : "")
188);
client/scripts/magentaize-png.mjs added +147 −0
@@ -0,0 +1,147 @@
1 /**
2 * Remap opaque pixels in a PNG into the magenta tint family (R≈B, G<R).
3 * Usage: node client/scripts/magentaize-png.mjs <input.png> <output.png>
4 */
5 import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
6 import { dirname } from "node:path";
7 import { deflateSync, inflateSync } from "node:zlib";
8
9 function crcTable ()
10 {
11 const table = new Uint32Array(256);
12 for (let n = 0; n < 256; n++)
13 {
14 let c = n;
15 for (let k = 0; k < 8; k++)
16 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
17 table[n] = c >>> 0;
18 }
19 return table;
20 }
21
22 const CRC_TABLE = crcTable();
23
24 function crc32 (buf)
25 {
26 let c = 0xffffffff;
27 for (let i = 0; i < buf.length; i++)
28 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
29 return (c ^ 0xffffffff) >>> 0;
30 }
31
32 function chunk (type, data)
33 {
34 const len = Buffer.alloc(4);
35 len.writeUInt32BE(data.length);
36 const typeBuf = Buffer.from(type, "ascii");
37 const crcBuf = Buffer.alloc(4);
38 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
39 return Buffer.concat([len, typeBuf, data, crcBuf]);
40 }
41
42 function decodePngRgba (buf)
43 {
44 let off = 8;
45 let w = 0;
46 let h = 0;
47 const idat = [];
48 while (off < buf.length)
49 {
50 const len = buf.readUInt32BE(off);
51 const type = buf.slice(off + 4, off + 8).toString("ascii");
52 const data = buf.slice(off + 8, off + 8 + len);
53 if (type === "IHDR")
54 {
55 w = data.readUInt32BE(0);
56 h = data.readUInt32BE(4);
57 }
58 else if (type === "IDAT")
59 { idat.push(data); }
60 else if (type === "IEND")
61 { break; }
62 off += 12 + len;
63 }
64 const raw = inflateSync(Buffer.concat(idat));
65 const stride = 1 + w * 4;
66 const rgba = new Uint8Array(w * h * 4);
67 for (let y = 0; y < h; y++)
68 {
69 for (let x = 0; x < w; x++)
70 {
71 const i = y * stride + 1 + x * 4;
72 const o = (y * w + x) * 4;
73 rgba[o] = raw[i];
74 rgba[o + 1] = raw[i + 1];
75 rgba[o + 2] = raw[i + 2];
76 rgba[o + 3] = raw[i + 3];
77 }
78 }
79 return { width: w, height: h, rgba };
80 }
81
82 function encodePng ({ width, height, rgba })
83 {
84 const raw = Buffer.alloc((width * 4 + 1) * height);
85 for (let y = 0; y < height; y++)
86 {
87 const row = y * (width * 4 + 1);
88 raw[row] = 0;
89 for (let x = 0; x < width; x++)
90 {
91 const i = (y * width + x) * 4;
92 const o = row + 1 + x * 4;
93 raw[o] = rgba[i];
94 raw[o + 1] = rgba[i + 1];
95 raw[o + 2] = rgba[i + 2];
96 raw[o + 3] = rgba[i + 3];
97 }
98 }
99 const ihdr = Buffer.alloc(13);
100 ihdr.writeUInt32BE(width, 0);
101 ihdr.writeUInt32BE(height, 4);
102 ihdr[8] = 8;
103 ihdr[9] = 6;
104 return Buffer.concat([
105 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
106 chunk("IHDR", ihdr),
107 chunk("IDAT", deflateSync(raw, { level: 9 })),
108 chunk("IEND", Buffer.alloc(0))
109 ]);
110 }
111
112 function toMagenta (r, g, b, a)
113 {
114 if (a < 8)
115 { return [0, 0, 0, 0]; }
116 const L = Math.max(1, Math.max(r, g, b));
117 const minC = Math.min(r, g, b);
118 const chroma = (L - minC) / 255;
119 const gMag = Math.min(L - 1, Math.round(L * (0.08 + (1 - chroma) * 0.22)));
120 return [L, Math.max(0, gMag), L, 255];
121 }
122
123 function magentaize ({ width, height, rgba })
124 {
125 const out = new Uint8Array(rgba.length);
126 for (let i = 0; i < rgba.length; i += 4)
127 {
128 const [r, g, b, a] = toMagenta(rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]);
129 out[i] = r;
130 out[i + 1] = g;
131 out[i + 2] = b;
132 out[i + 3] = a;
133 }
134 return { width, height, rgba: out };
135 }
136
137 const [inputPath, outputPath] = process.argv.slice(2);
138 if (!inputPath || !outputPath)
139 {
140 console.error("Usage: node magentaize-png.mjs <input.png> <output.png>");
141 process.exit(1);
142 }
143
144 const image = magentaize(decodePngRgba(readFileSync(inputPath)));
145 mkdirSync(dirname(outputPath), { recursive: true });
146 writeFileSync(outputPath, encodePng(image));
147 console.log(`Wrote ${outputPath} (${image.width}×${image.height})`);
@@ -0,0 +1,147 @@
1/**
2 * Remap opaque pixels in a PNG into the magenta tint family (R≈B, G<R).
3 * Usage: node client/scripts/magentaize-png.mjs <input.png> <output.png>
4 */
5import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
6import { dirname } from "node:path";
7import { deflateSync, inflateSync } from "node:zlib";
8
9function crcTable ()
10{
11 const table = new Uint32Array(256);
12 for (let n = 0; n < 256; n++)
13 {
14 let c = n;
15 for (let k = 0; k < 8; k++)
16 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
17 table[n] = c >>> 0;
18 }
19 return table;
20}
21
22const CRC_TABLE = crcTable();
23
24function crc32 (buf)
25{
26 let c = 0xffffffff;
27 for (let i = 0; i < buf.length; i++)
28 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
29 return (c ^ 0xffffffff) >>> 0;
30}
31
32function chunk (type, data)
33{
34 const len = Buffer.alloc(4);
35 len.writeUInt32BE(data.length);
36 const typeBuf = Buffer.from(type, "ascii");
37 const crcBuf = Buffer.alloc(4);
38 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
39 return Buffer.concat([len, typeBuf, data, crcBuf]);
40}
41
42function decodePngRgba (buf)
43{
44 let off = 8;
45 let w = 0;
46 let h = 0;
47 const idat = [];
48 while (off < buf.length)
49 {
50 const len = buf.readUInt32BE(off);
51 const type = buf.slice(off + 4, off + 8).toString("ascii");
52 const data = buf.slice(off + 8, off + 8 + len);
53 if (type === "IHDR")
54 {
55 w = data.readUInt32BE(0);
56 h = data.readUInt32BE(4);
57 }
58 else if (type === "IDAT")
59 { idat.push(data); }
60 else if (type === "IEND")
61 { break; }
62 off += 12 + len;
63 }
64 const raw = inflateSync(Buffer.concat(idat));
65 const stride = 1 + w * 4;
66 const rgba = new Uint8Array(w * h * 4);
67 for (let y = 0; y < h; y++)
68 {
69 for (let x = 0; x < w; x++)
70 {
71 const i = y * stride + 1 + x * 4;
72 const o = (y * w + x) * 4;
73 rgba[o] = raw[i];
74 rgba[o + 1] = raw[i + 1];
75 rgba[o + 2] = raw[i + 2];
76 rgba[o + 3] = raw[i + 3];
77 }
78 }
79 return { width: w, height: h, rgba };
80}
81
82function encodePng ({ width, height, rgba })
83{
84 const raw = Buffer.alloc((width * 4 + 1) * height);
85 for (let y = 0; y < height; y++)
86 {
87 const row = y * (width * 4 + 1);
88 raw[row] = 0;
89 for (let x = 0; x < width; x++)
90 {
91 const i = (y * width + x) * 4;
92 const o = row + 1 + x * 4;
93 raw[o] = rgba[i];
94 raw[o + 1] = rgba[i + 1];
95 raw[o + 2] = rgba[i + 2];
96 raw[o + 3] = rgba[i + 3];
97 }
98 }
99 const ihdr = Buffer.alloc(13);
100 ihdr.writeUInt32BE(width, 0);
101 ihdr.writeUInt32BE(height, 4);
102 ihdr[8] = 8;
103 ihdr[9] = 6;
104 return Buffer.concat([
105 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
106 chunk("IHDR", ihdr),
107 chunk("IDAT", deflateSync(raw, { level: 9 })),
108 chunk("IEND", Buffer.alloc(0))
109 ]);
110}
111
112function toMagenta (r, g, b, a)
113{
114 if (a < 8)
115 { return [0, 0, 0, 0]; }
116 const L = Math.max(1, Math.max(r, g, b));
117 const minC = Math.min(r, g, b);
118 const chroma = (L - minC) / 255;
119 const gMag = Math.min(L - 1, Math.round(L * (0.08 + (1 - chroma) * 0.22)));
120 return [L, Math.max(0, gMag), L, 255];
121}
122
123function magentaize ({ width, height, rgba })
124{
125 const out = new Uint8Array(rgba.length);
126 for (let i = 0; i < rgba.length; i += 4)
127 {
128 const [r, g, b, a] = toMagenta(rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]);
129 out[i] = r;
130 out[i + 1] = g;
131 out[i + 2] = b;
132 out[i + 3] = a;
133 }
134 return { width, height, rgba: out };
135}
136
137const [inputPath, outputPath] = process.argv.slice(2);
138if (!inputPath || !outputPath)
139{
140 console.error("Usage: node magentaize-png.mjs <input.png> <output.png>");
141 process.exit(1);
142}
143
144const image = magentaize(decodePngRgba(readFileSync(inputPath)));
145mkdirSync(dirname(outputPath), { recursive: true });
146writeFileSync(outputPath, encodePng(image));
147console.log(`Wrote ${outputPath} (${image.width}×${image.height})`);
client/scripts/purify-dual-channel-png.mjs added +164 −0
@@ -0,0 +1,164 @@
1 /**
2 * Normalize already-dual-channel tint masks: red-dominant → (R,0,0), blue-dominant → (0,0,B).
3 * For first-time conversion from magenta/brown art, use convert-dual-channel-png.mjs instead.
4 *
5 * Usage: node client/scripts/purify-dual-channel-png.mjs <input.png> [output.png]
6 * When output is omitted, overwrites input.
7 */
8 import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
9 import { dirname } from "node:path";
10 import { deflateSync, inflateSync } from "node:zlib";
11
12 function crcTable ()
13 {
14 const table = new Uint32Array(256);
15 for (let n = 0; n < 256; n++)
16 {
17 let c = n;
18 for (let k = 0; k < 8; k++)
19 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
20 table[n] = c >>> 0;
21 }
22 return table;
23 }
24
25 const CRC_TABLE = crcTable();
26
27 function crc32 (buf)
28 {
29 let c = 0xffffffff;
30 for (let i = 0; i < buf.length; i++)
31 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
32 return (c ^ 0xffffffff) >>> 0;
33 }
34
35 function chunk (type, data)
36 {
37 const len = Buffer.alloc(4);
38 len.writeUInt32BE(data.length);
39 const typeBuf = Buffer.from(type, "ascii");
40 const crcBuf = Buffer.alloc(4);
41 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
42 return Buffer.concat([len, typeBuf, data, crcBuf]);
43 }
44
45 function decodePngRgba (buf)
46 {
47 let off = 8;
48 let w = 0;
49 let h = 0;
50 const idat = [];
51 while (off < buf.length)
52 {
53 const len = buf.readUInt32BE(off);
54 const type = buf.slice(off + 4, off + 8).toString("ascii");
55 const data = buf.slice(off + 8, off + 8 + len);
56 if (type === "IHDR")
57 {
58 w = data.readUInt32BE(0);
59 h = data.readUInt32BE(4);
60 }
61 else if (type === "IDAT")
62 { idat.push(data); }
63 else if (type === "IEND")
64 { break; }
65 off += 12 + len;
66 }
67 const raw = inflateSync(Buffer.concat(idat));
68 const stride = 1 + w * 4;
69 const rgba = new Uint8Array(w * h * 4);
70 for (let y = 0; y < h; y++)
71 {
72 for (let x = 0; x < w; x++)
73 {
74 const i = y * stride + 1 + x * 4;
75 const o = (y * w + x) * 4;
76 rgba[o] = raw[i];
77 rgba[o + 1] = raw[i + 1];
78 rgba[o + 2] = raw[i + 2];
79 rgba[o + 3] = raw[i + 3];
80 }
81 }
82 return { width: w, height: h, rgba };
83 }
84
85 function encodePng ({ width, height, rgba })
86 {
87 const raw = Buffer.alloc((width * 4 + 1) * height);
88 for (let y = 0; y < height; y++)
89 {
90 const row = y * (width * 4 + 1);
91 raw[row] = 0;
92 for (let x = 0; x < width; x++)
93 {
94 const i = (y * width + x) * 4;
95 const o = row + 1 + x * 4;
96 raw[o] = rgba[i];
97 raw[o + 1] = rgba[i + 1];
98 raw[o + 2] = rgba[i + 2];
99 raw[o + 3] = rgba[i + 3];
100 }
101 }
102 const ihdr = Buffer.alloc(13);
103 ihdr.writeUInt32BE(width, 0);
104 ihdr.writeUInt32BE(height, 4);
105 ihdr[8] = 8;
106 ihdr[9] = 6;
107 return Buffer.concat([
108 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
109 chunk("IHDR", ihdr),
110 chunk("IDAT", deflateSync(raw, { level: 9 })),
111 chunk("IEND", Buffer.alloc(0))
112 ]);
113 }
114
115 /** @returns {{ redFixed: number, blueFixed: number }} */
116 function purifyDualChannel ({ width, height, rgba })
117 {
118 let redFixed = 0;
119 let blueFixed = 0;
120 for (let i = 0; i < rgba.length; i += 4)
121 {
122 const a = rgba[i + 3];
123 if (a < 8)
124 { continue; }
125 const r = rgba[i];
126 const g = rgba[i + 1];
127 const b = rgba[i + 2];
128 if (r > g && r > b && r >= 8)
129 {
130 if (g !== 0 || b !== 0)
131 {
132 rgba[i] = r;
133 rgba[i + 1] = 0;
134 rgba[i + 2] = 0;
135 redFixed++;
136 }
137 }
138 else if (b > r && b > g && b >= 8)
139 {
140 if (r !== 0 || g !== 0)
141 {
142 rgba[i] = 0;
143 rgba[i + 1] = 0;
144 rgba[i + 2] = b;
145 blueFixed++;
146 }
147 }
148 }
149 return { redFixed, blueFixed };
150 }
151
152 const [inputPath, outputPathArg] = process.argv.slice(2);
153 if (!inputPath)
154 {
155 console.error("Usage: node purify-dual-channel-png.mjs <input.png> [output.png]");
156 process.exit(1);
157 }
158
159 const outputPath = outputPathArg ?? inputPath;
160 const image = decodePngRgba(readFileSync(inputPath));
161 const stats = purifyDualChannel(image);
162 mkdirSync(dirname(outputPath), { recursive: true });
163 writeFileSync(outputPath, encodePng(image));
164 console.log(`Wrote ${outputPath} (${image.width}×${image.height}) — fixed ${stats.redFixed} red, ${stats.blueFixed} blue pixels`);
@@ -0,0 +1,164 @@
1/**
2 * Normalize already-dual-channel tint masks: red-dominant → (R,0,0), blue-dominant → (0,0,B).
3 * For first-time conversion from magenta/brown art, use convert-dual-channel-png.mjs instead.
4 *
5 * Usage: node client/scripts/purify-dual-channel-png.mjs <input.png> [output.png]
6 * When output is omitted, overwrites input.
7 */
8import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
9import { dirname } from "node:path";
10import { deflateSync, inflateSync } from "node:zlib";
11
12function crcTable ()
13{
14 const table = new Uint32Array(256);
15 for (let n = 0; n < 256; n++)
16 {
17 let c = n;
18 for (let k = 0; k < 8; k++)
19 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
20 table[n] = c >>> 0;
21 }
22 return table;
23}
24
25const CRC_TABLE = crcTable();
26
27function crc32 (buf)
28{
29 let c = 0xffffffff;
30 for (let i = 0; i < buf.length; i++)
31 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
32 return (c ^ 0xffffffff) >>> 0;
33}
34
35function chunk (type, data)
36{
37 const len = Buffer.alloc(4);
38 len.writeUInt32BE(data.length);
39 const typeBuf = Buffer.from(type, "ascii");
40 const crcBuf = Buffer.alloc(4);
41 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
42 return Buffer.concat([len, typeBuf, data, crcBuf]);
43}
44
45function decodePngRgba (buf)
46{
47 let off = 8;
48 let w = 0;
49 let h = 0;
50 const idat = [];
51 while (off < buf.length)
52 {
53 const len = buf.readUInt32BE(off);
54 const type = buf.slice(off + 4, off + 8).toString("ascii");
55 const data = buf.slice(off + 8, off + 8 + len);
56 if (type === "IHDR")
57 {
58 w = data.readUInt32BE(0);
59 h = data.readUInt32BE(4);
60 }
61 else if (type === "IDAT")
62 { idat.push(data); }
63 else if (type === "IEND")
64 { break; }
65 off += 12 + len;
66 }
67 const raw = inflateSync(Buffer.concat(idat));
68 const stride = 1 + w * 4;
69 const rgba = new Uint8Array(w * h * 4);
70 for (let y = 0; y < h; y++)
71 {
72 for (let x = 0; x < w; x++)
73 {
74 const i = y * stride + 1 + x * 4;
75 const o = (y * w + x) * 4;
76 rgba[o] = raw[i];
77 rgba[o + 1] = raw[i + 1];
78 rgba[o + 2] = raw[i + 2];
79 rgba[o + 3] = raw[i + 3];
80 }
81 }
82 return { width: w, height: h, rgba };
83}
84
85function encodePng ({ width, height, rgba })
86{
87 const raw = Buffer.alloc((width * 4 + 1) * height);
88 for (let y = 0; y < height; y++)
89 {
90 const row = y * (width * 4 + 1);
91 raw[row] = 0;
92 for (let x = 0; x < width; x++)
93 {
94 const i = (y * width + x) * 4;
95 const o = row + 1 + x * 4;
96 raw[o] = rgba[i];
97 raw[o + 1] = rgba[i + 1];
98 raw[o + 2] = rgba[i + 2];
99 raw[o + 3] = rgba[i + 3];
100 }
101 }
102 const ihdr = Buffer.alloc(13);
103 ihdr.writeUInt32BE(width, 0);
104 ihdr.writeUInt32BE(height, 4);
105 ihdr[8] = 8;
106 ihdr[9] = 6;
107 return Buffer.concat([
108 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
109 chunk("IHDR", ihdr),
110 chunk("IDAT", deflateSync(raw, { level: 9 })),
111 chunk("IEND", Buffer.alloc(0))
112 ]);
113}
114
115/** @returns {{ redFixed: number, blueFixed: number }} */
116function purifyDualChannel ({ width, height, rgba })
117{
118 let redFixed = 0;
119 let blueFixed = 0;
120 for (let i = 0; i < rgba.length; i += 4)
121 {
122 const a = rgba[i + 3];
123 if (a < 8)
124 { continue; }
125 const r = rgba[i];
126 const g = rgba[i + 1];
127 const b = rgba[i + 2];
128 if (r > g && r > b && r >= 8)
129 {
130 if (g !== 0 || b !== 0)
131 {
132 rgba[i] = r;
133 rgba[i + 1] = 0;
134 rgba[i + 2] = 0;
135 redFixed++;
136 }
137 }
138 else if (b > r && b > g && b >= 8)
139 {
140 if (r !== 0 || g !== 0)
141 {
142 rgba[i] = 0;
143 rgba[i + 1] = 0;
144 rgba[i + 2] = b;
145 blueFixed++;
146 }
147 }
148 }
149 return { redFixed, blueFixed };
150}
151
152const [inputPath, outputPathArg] = process.argv.slice(2);
153if (!inputPath)
154{
155 console.error("Usage: node purify-dual-channel-png.mjs <input.png> [output.png]");
156 process.exit(1);
157}
158
159const outputPath = outputPathArg ?? inputPath;
160const image = decodePngRgba(readFileSync(inputPath));
161const stats = purifyDualChannel(image);
162mkdirSync(dirname(outputPath), { recursive: true });
163writeFileSync(outputPath, encodePng(image));
164console.log(`Wrote ${outputPath} (${image.width}×${image.height}) — fixed ${stats.redFixed} red, ${stats.blueFixed} blue pixels`);
client/src/editor/dimensionCombobox.js +32 −2
@@ -22,12 +22,19 @@ export function createDimensionCombobox ({
22 22 input.setAttribute("aria-autocomplete", "list");
23 23 input.setAttribute("aria-expanded", "false");
24 24
25 const toggle = document.createElement("button");
26 toggle.type = "button";
27 toggle.className = "dim-combo-toggle";
28 toggle.tabIndex = -1;
29 toggle.setAttribute("aria-label", "Show dimensions");
30 toggle.textContent = "▾";
31
25 32 const list = document.createElement("ul");
26 33 list.className = "dim-combo-list";
27 34 list.hidden = true;
28 35 list.setAttribute("role", "listbox");
29 36
30 root.append(input, list);
37 root.append(input, toggle, list);
31 38
32 39 /** @type {{ id: string, label: string, disabled?: boolean, hint?: string }[]} */
33 40 let options = [];
@@ -155,9 +162,32 @@ export function createDimensionCombobox ({
155 162
156 163 input.addEventListener("focus", () =>
157 164 {
158 input.select();
159 165 setOpen(true);
160 166 });
167 input.addEventListener("mousedown", (event) =>
168 {
169 if (!open)
170 {
171 event.preventDefault();
172 setOpen(true);
173 input.focus();
174 }
175 });
176 toggle.addEventListener("mousedown", (event) =>
177 {
178 event.preventDefault();
179 if (open)
180 {
181 syncInputFromSelection();
182 setOpen(false);
183 input.blur();
184 }
185 else
186 {
187 setOpen(true);
188 input.focus();
189 }
190 });
161 191 input.addEventListener("input", () =>
162 192 {
163 193 setOpen(true);
@@ -22,12 +22,19 @@ export function createDimensionCombobox ({
22 input.setAttribute("aria-autocomplete", "list");
22 input.setAttribute("aria-autocomplete", "list");
23 input.setAttribute("aria-expanded", "false");
23 input.setAttribute("aria-expanded", "false");
24
24
25 const toggle = document.createElement("button");
26 toggle.type = "button";
27 toggle.className = "dim-combo-toggle";
28 toggle.tabIndex = -1;
29 toggle.setAttribute("aria-label", "Show dimensions");
30 toggle.textContent = "▾";
31
25 const list = document.createElement("ul");
32 const list = document.createElement("ul");
26 list.className = "dim-combo-list";
33 list.className = "dim-combo-list";
27 list.hidden = true;
34 list.hidden = true;
28 list.setAttribute("role", "listbox");
35 list.setAttribute("role", "listbox");
29
36
30 root.append(input, list);
37 root.append(input, toggle, list);
31
38
32 /** @type {{ id: string, label: string, disabled?: boolean, hint?: string }[]} */
39 /** @type {{ id: string, label: string, disabled?: boolean, hint?: string }[]} */
33 let options = [];
40 let options = [];
@@ -155,9 +162,32 @@ export function createDimensionCombobox ({
155
162
156 input.addEventListener("focus", () =>
163 input.addEventListener("focus", () =>
157 {
164 {
158 input.select();
159 setOpen(true);
165 setOpen(true);
160 });
166 });
167 input.addEventListener("mousedown", (event) =>
168 {
169 if (!open)
170 {
171 event.preventDefault();
172 setOpen(true);
173 input.focus();
174 }
175 });
176 toggle.addEventListener("mousedown", (event) =>
177 {
178 event.preventDefault();
179 if (open)
180 {
181 syncInputFromSelection();
182 setOpen(false);
183 input.blur();
184 }
185 else
186 {
187 setOpen(true);
188 input.focus();
189 }
190 });
161 input.addEventListener("input", () =>
191 input.addEventListener("input", () =>
162 {
192 {
163 setOpen(true);
193 setOpen(true);
client/src/editor/main.js +5 −0
@@ -1037,6 +1037,11 @@ async function main ()
1037 1037 });
1038 1038 }
1039 1039 });
1040 dimensionCombo.setOptions([{
1041 id: OVERWORLD_ID,
1042 label: "Overworld"
1043 }]);
1044 dimensionCombo.setValue(OVERWORLD_ID);
1040 1045 dimensionSettings = initDimensionSettings({
1041 1046 socket,
1042 1047 MessageType,
@@ -1037,6 +1037,11 @@ async function main ()
1037 });
1037 });
1038 }
1038 }
1039 });
1039 });
1040 dimensionCombo.setOptions([{
1041 id: OVERWORLD_ID,
1042 label: "Overworld"
1043 }]);
1044 dimensionCombo.setValue(OVERWORLD_ID);
1040 dimensionSettings = initDimensionSettings({
1045 dimensionSettings = initDimensionSettings({
1041 socket,
1046 socket,
1042 MessageType,
1047 MessageType,
client/src/editor/settingsModal.js +262 −4
@@ -11,7 +11,7 @@ import {
11 11 normalizeItemSeedValues,
12 12 effectiveSeedValue
13 13 } from "/shared/shop/pricing.js";
14 import { ITEM_DEFINITIONS } from "/shared/definitions/items.js";
14 import { ITEM_DEFINITIONS, itemAssetPathForStack } from "/shared/definitions/items.js";
15 15 import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
16 16 import {
17 17 normalizeStarterLoadout,
@@ -19,6 +19,14 @@ import {
19 19 DEFAULT_STARTER_EQUIPMENT,
20 20 DEFAULT_STARTER_INVENTORY
21 21 } from "/shared/items/starterLoadout.js";
22 import {
23 EQUIPMENT_STAT_CATEGORIES,
24 normalizeEquipmentStatBonuses,
25 equipmentStatBonusMapsEqual,
26 equipmentStatRowItemId,
27 equipmentStatRowDefaultTier
28 } from "/shared/definitions/equipmentStatCategories.js";
29 import { applyItemIcon } from "/src/render/potionIcon.js";
22 30
23 31 const SEED_PAGE_SIZE = 20;
24 32 const SLOT_LABELS = Object.freeze({
@@ -54,6 +62,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
54 62 starterInventory: DEFAULT_STARTER_INVENTORY
55 63 });
56 64 let starterPanel = null;
65 let draftEquipmentStats = normalizeEquipmentStatBonuses(null);
66 let equipmentStatsPanel = null;
67 let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;
57 68
58 69 buildForm(form, {
59 70 getActiveCategory: () => activeCategory,
@@ -65,6 +76,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
65 76 { renderSeedPanel(); }
66 77 if (id === "starterEquipment")
67 78 { renderStarterPanel(); }
79 if (id === "equipmentStats")
80 { renderEquipmentStatsPanel(); }
68 81 },
69 82 onFieldInput (field)
70 83 {
@@ -78,6 +91,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
78 91 onStarterPanelReady (panel)
79 92 {
80 93 starterPanel = panel;
94 },
95 onEquipmentStatsPanelReady (panel)
96 {
97 equipmentStatsPanel = panel;
81 98 }
82 99 });
83 100
@@ -98,6 +115,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
98 115 { return; }
99 116 if (event.target?.dataset?.starterField)
100 117 { return; }
118 if (event.target?.dataset?.equipStat)
119 { return; }
101 120 refreshDirty();
102 121 });
103 122 form.addEventListener("change", (event) =>
@@ -106,9 +125,17 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
106 125 { return; }
107 126 if (event.target?.dataset?.starterField)
108 127 { return; }
128 if (event.target?.dataset?.equipStat)
129 { return; }
109 130 refreshDirty();
110 131 });
111 132 form.addEventListener("starter-changed", () => refreshDirty());
133 form.addEventListener("equipment-stats-changed", () => refreshDirty());
134 form.addEventListener("equip-stats-category", (event) =>
135 {
136 equipmentStatsCategoryId = event.detail?.id ?? equipmentStatsCategoryId;
137 renderEquipmentStatsPanel();
138 });
112 139 form.addEventListener("starter-add-inv", () =>
113 140 {
114 141 const first = listAllItems()[0];
@@ -129,12 +156,14 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
129 156 fillForm(form, baseline);
130 157 draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
131 158 draftStarter = normalizeStarterLoadout(baseline);
159 draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
132 160 seedQuery = "";
133 161 seedPage = 0;
134 162 if (seedPanel?.search)
135 163 { seedPanel.search.value = ""; }
136 164 renderSeedPanel();
137 165 renderStarterPanel();
166 renderEquipmentStatsPanel();
138 167 refreshDirty();
139 168 }
140 169 open = visible;
@@ -167,7 +196,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
167 196 ...scalarDirtyValues(form, baseline),
168 197 itemSeedValues: draftSeeds,
169 198 starterEquipment: draftStarter.equipment,
170 starterInventory: draftStarter.inventory
199 starterInventory: draftStarter.inventory,
200 equipmentStatBonuses: draftEquipmentStats
171 201 };
172 202 }
173 203
@@ -187,6 +217,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
187 217 changed.starterEquipment = nextStarter.equipment;
188 218 changed.starterInventory = nextStarter.inventory;
189 219 }
220 const nextEquip = normalizeEquipmentStatBonuses(draftEquipmentStats);
221 if (!equipmentStatBonusMapsEqual(baseline.equipmentStatBonuses, nextEquip))
222 { changed.equipmentStatBonuses = nextEquip; }
190 223 return changed;
191 224 }
192 225
@@ -407,6 +440,178 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
407 440 refreshDirty();
408 441 }
409 442
443 function setRowIcon (img, itemId)
444 {
445 if (!img)
446 { return; }
447 if (itemId == null)
448 {
449 img.removeAttribute("src");
450 img.alt = "";
451 return;
452 }
453 const stack = { itemId, quantity: 1 };
454 applyItemIcon(img, stack, itemAssetPathForStack(stack));
455 }
456
457 function renderEquipmentStatsPanel ()
458 {
459 if (!equipmentStatsPanel)
460 { return; }
461 const category = EQUIPMENT_STAT_CATEGORIES.find((entry) => entry.id === equipmentStatsCategoryId)
462 ?? EQUIPMENT_STAT_CATEGORIES[0];
463 if (!category)
464 { return; }
465 equipmentStatsCategoryId = category.id;
466 equipmentStatsPanel.select.value = category.id;
467 const host = equipmentStatsPanel.tables;
468 host.replaceChildren();
469
470 const baselineTable = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
471
472 for (const section of category.sections)
473 {
474 if (section.label)
475 {
476 const heading = document.createElement("h3");
477 heading.textContent = section.label;
478 host.append(heading);
479 }
480 if (!section.rows.length)
481 {
482 const empty = document.createElement("p");
483 empty.className = "hint";
484 empty.textContent = "No items in this category yet.";
485 host.append(empty);
486 continue;
487 }
488
489 const wrap = document.createElement("div");
490 wrap.className = "equip-stats-table-wrap";
491 const table = document.createElement("table");
492 table.className = "equip-stats-table";
493 const thead = document.createElement("thead");
494 const headRow = document.createElement("tr");
495 const itemTh = document.createElement("th");
496 itemTh.textContent = "Item";
497 headRow.append(itemTh);
498 for (const tier of section.tierOrder)
499 {
500 const th = document.createElement("th");
501 th.textContent = section.tierDisplayName(tier);
502 headRow.append(th);
503 }
504 thead.append(headRow);
505 table.append(thead);
506
507 const tbody = document.createElement("tbody");
508 for (const row of section.rows)
509 {
510 const tr = document.createElement("tr");
511 tr.dataset.pieceKey = row.pieceKey;
512 const defaultTier = equipmentStatRowDefaultTier(section, row);
513 const labelTd = document.createElement("td");
514 labelTd.className = "equip-stats-item";
515 const icon = document.createElement("img");
516 icon.className = "equip-stats-icon";
517 icon.width = 16;
518 icon.height = 16;
519 icon.alt = row.label;
520 setRowIcon(icon, equipmentStatRowItemId(row, defaultTier));
521 const name = document.createElement("span");
522 name.textContent = row.label;
523 labelTd.append(icon, name);
524 tr.append(labelTd);
525
526 for (const tier of section.tierOrder)
527 {
528 const td = document.createElement("td");
529 td.className = "equip-stats-cell";
530 td.dataset.tier = tier;
531 const itemId = equipmentStatRowItemId(row, tier);
532 if (itemId == null)
533 {
534 td.classList.add("empty");
535 td.textContent = "—";
536 tr.append(td);
537 continue;
538 }
539
540 const cell = document.createElement("div");
541 cell.className = "equip-stats-cell-inner";
542 const draftCell = draftEquipmentStats[category.id]?.[row.pieceKey]?.[tier] ?? {};
543 const baseCell = baselineTable[category.id]?.[row.pieceKey]?.[tier] ?? {};
544
545 for (const skillId of category.stats)
546 {
547 const line = document.createElement("label");
548 line.className = "equip-stats-stat";
549 const skillIcon = document.createElement("img");
550 skillIcon.src = `/assets/skills/${skillId}.svg`;
551 skillIcon.alt = skillId;
552 skillIcon.width = 14;
553 skillIcon.height = 14;
554 const input = document.createElement("input");
555 input.type = "number";
556 input.min = "0";
557 input.max = "99";
558 input.step = "1";
559 input.dataset.equipStat = "1";
560 input.dataset.categoryId = category.id;
561 input.dataset.pieceKey = row.pieceKey;
562 input.dataset.tier = tier;
563 input.dataset.skillId = skillId;
564 input.value = String(draftCell[skillId] ?? 0);
565 if (!settingsValuesEqual(Number(draftCell[skillId] ?? 0), Number(baseCell[skillId] ?? 0)))
566 { line.classList.add("dirty"); }
567 input.addEventListener("input", () =>
568 {
569 const value = Math.max(0, Math.min(99, Math.floor(Number(input.value) || 0)));
570 input.value = String(value);
571 const nextCat = {
572 ...(draftEquipmentStats[category.id] ?? {}),
573 [row.pieceKey]: {
574 ...(draftEquipmentStats[category.id]?.[row.pieceKey] ?? {}),
575 [tier]: {
576 ...(draftEquipmentStats[category.id]?.[row.pieceKey]?.[tier] ?? {}),
577 [skillId]: value
578 }
579 }
580 };
581 draftEquipmentStats = {
582 ...draftEquipmentStats,
583 [category.id]: nextCat
584 };
585 const baseVal = baselineTable[category.id]?.[row.pieceKey]?.[tier]?.[skillId] ?? 0;
586 line.classList.toggle("dirty", !settingsValuesEqual(value, Number(baseVal)));
587 form.dispatchEvent(new CustomEvent("equipment-stats-changed"));
588 });
589 const previewTier = () => setRowIcon(icon, itemId);
590 const restoreIcon = () =>
591 {
592 if (tr.querySelector("input:focus"))
593 { return; }
594 setRowIcon(icon, equipmentStatRowItemId(row, defaultTier));
595 };
596 td.addEventListener("mouseenter", previewTier);
597 td.addEventListener("mouseleave", restoreIcon);
598 input.addEventListener("focus", previewTier);
599 input.addEventListener("blur", restoreIcon);
600 line.append(skillIcon, input);
601 cell.append(line);
602 }
603 td.append(cell);
604 tr.append(td);
605 }
606 tbody.append(tr);
607 }
608 table.append(tbody);
609 wrap.append(table);
610 host.append(wrap);
611 }
612 refreshDirty();
613 }
614
410 615 function updateSeedRowReadouts (row, itemId, snap = null)
411 616 {
412 617 const resolved = snap ?? itemPriceSnapshot(itemId, {
@@ -436,16 +641,19 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
436 641 loaded = true;
437 642 baseline = {
438 643 ...message.settings,
439 itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues)
644 itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues),
645 equipmentStatBonuses: normalizeEquipmentStatBonuses(message.settings?.equipmentStatBonuses)
440 646 };
441 647 itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"
442 648 ? message.itemLastSales
443 649 : {};
444 650 draftSeeds = { ...baseline.itemSeedValues };
445 651 draftStarter = normalizeStarterLoadout(baseline);
652 draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
446 653 fillForm(form, baseline);
447 654 renderSeedPanel();
448 655 renderStarterPanel();
656 renderEquipmentStatsPanel();
449 657 refreshDirty();
450 658 renderLog(log, message.changelog ?? []);
451 659 onApplied?.(message.settings);
@@ -453,7 +661,14 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
453 661 };
454 662 }
455 663
456 function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady, onStarterPanelReady })
664 function buildForm (form, {
665 getActiveCategory,
666 setActiveCategory,
667 onFieldInput,
668 onSeedPanelReady,
669 onStarterPanelReady,
670 onEquipmentStatsPanelReady
671 })
457 672 {
458 673 form.innerHTML = "";
459 674 const tabs = document.createElement("div");
@@ -498,6 +713,15 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput,
498 713 section.append(panel.root);
499 714 onStarterPanelReady?.(panel);
500 715 }
716 else if (category.panel === "equipmentStats")
717 {
718 const panel = buildEquipmentStatsPanel({
719 onCategoryChange (id)
720 { form.dispatchEvent(new CustomEvent("equip-stats-category", { detail: { id } })); }
721 });
722 section.append(panel.root);
723 onEquipmentStatsPanelReady?.(panel);
724 }
501 725 else
502 726 {
503 727 for (const field of category.fields)
@@ -543,6 +767,40 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput,
543 767 syncTabs(form, getActiveCategory());
544 768 }
545 769
770 function buildEquipmentStatsPanel ({ onCategoryChange })
771 {
772 const root = document.createElement("div");
773 root.className = "equip-stats-panel";
774
775 const toolbar = document.createElement("div");
776 toolbar.className = "equip-stats-toolbar";
777 const label = document.createElement("label");
778 label.className = "equip-stats-category-label";
779 label.textContent = "Category";
780 const select = document.createElement("select");
781 select.className = "equip-stats-category";
782 for (const category of EQUIPMENT_STAT_CATEGORIES)
783 {
784 const option = document.createElement("option");
785 option.value = category.id;
786 option.textContent = category.label;
787 select.append(option);
788 }
789 select.addEventListener("change", () => onCategoryChange(select.value));
790 label.append(select);
791 toolbar.append(label);
792
793 const hint = document.createElement("p");
794 hint.className = "hint";
795 hint.textContent = "Hover or focus a cell to preview that tier’s item icon. Multi-stat cells edit each bonus independently.";
796
797 const tables = document.createElement("div");
798 tables.className = "equip-stats-tables";
799
800 root.append(toolbar, hint, tables);
801 return { root, select, tables };
802 }
803
546 804 function buildSeedPricePanel ({ onSearch, onPrev, onNext })
547 805 {
548 806 const root = document.createElement("div");
@@ -11,7 +11,7 @@ import {
11 normalizeItemSeedValues,
11 normalizeItemSeedValues,
12 effectiveSeedValue
12 effectiveSeedValue
13} from "/shared/shop/pricing.js";
13} from "/shared/shop/pricing.js";
14import { ITEM_DEFINITIONS } from "/shared/definitions/items.js";
14import { ITEM_DEFINITIONS, itemAssetPathForStack } from "/shared/definitions/items.js";
15import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
15import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
16import {
16import {
17 normalizeStarterLoadout,
17 normalizeStarterLoadout,
@@ -19,6 +19,14 @@ import {
19 DEFAULT_STARTER_EQUIPMENT,
19 DEFAULT_STARTER_EQUIPMENT,
20 DEFAULT_STARTER_INVENTORY
20 DEFAULT_STARTER_INVENTORY
21} from "/shared/items/starterLoadout.js";
21} from "/shared/items/starterLoadout.js";
22import {
23 EQUIPMENT_STAT_CATEGORIES,
24 normalizeEquipmentStatBonuses,
25 equipmentStatBonusMapsEqual,
26 equipmentStatRowItemId,
27 equipmentStatRowDefaultTier
28} from "/shared/definitions/equipmentStatCategories.js";
29import { applyItemIcon } from "/src/render/potionIcon.js";
22
30
23const SEED_PAGE_SIZE = 20;
31const SEED_PAGE_SIZE = 20;
24const SLOT_LABELS = Object.freeze({
32const SLOT_LABELS = Object.freeze({
@@ -54,6 +62,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
54 starterInventory: DEFAULT_STARTER_INVENTORY
62 starterInventory: DEFAULT_STARTER_INVENTORY
55 });
63 });
56 let starterPanel = null;
64 let starterPanel = null;
65 let draftEquipmentStats = normalizeEquipmentStatBonuses(null);
66 let equipmentStatsPanel = null;
67 let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;
57
68
58 buildForm(form, {
69 buildForm(form, {
59 getActiveCategory: () => activeCategory,
70 getActiveCategory: () => activeCategory,
@@ -65,6 +76,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
65 { renderSeedPanel(); }
76 { renderSeedPanel(); }
66 if (id === "starterEquipment")
77 if (id === "starterEquipment")
67 { renderStarterPanel(); }
78 { renderStarterPanel(); }
79 if (id === "equipmentStats")
80 { renderEquipmentStatsPanel(); }
68 },
81 },
69 onFieldInput (field)
82 onFieldInput (field)
70 {
83 {
@@ -78,6 +91,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
78 onStarterPanelReady (panel)
91 onStarterPanelReady (panel)
79 {
92 {
80 starterPanel = panel;
93 starterPanel = panel;
94 },
95 onEquipmentStatsPanelReady (panel)
96 {
97 equipmentStatsPanel = panel;
81 }
98 }
82 });
99 });
83
100
@@ -98,6 +115,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
98 { return; }
115 { return; }
99 if (event.target?.dataset?.starterField)
116 if (event.target?.dataset?.starterField)
100 { return; }
117 { return; }
118 if (event.target?.dataset?.equipStat)
119 { return; }
101 refreshDirty();
120 refreshDirty();
102 });
121 });
103 form.addEventListener("change", (event) =>
122 form.addEventListener("change", (event) =>
@@ -106,9 +125,17 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
106 { return; }
125 { return; }
107 if (event.target?.dataset?.starterField)
126 if (event.target?.dataset?.starterField)
108 { return; }
127 { return; }
128 if (event.target?.dataset?.equipStat)
129 { return; }
109 refreshDirty();
130 refreshDirty();
110 });
131 });
111 form.addEventListener("starter-changed", () => refreshDirty());
132 form.addEventListener("starter-changed", () => refreshDirty());
133 form.addEventListener("equipment-stats-changed", () => refreshDirty());
134 form.addEventListener("equip-stats-category", (event) =>
135 {
136 equipmentStatsCategoryId = event.detail?.id ?? equipmentStatsCategoryId;
137 renderEquipmentStatsPanel();
138 });
112 form.addEventListener("starter-add-inv", () =>
139 form.addEventListener("starter-add-inv", () =>
113 {
140 {
114 const first = listAllItems()[0];
141 const first = listAllItems()[0];
@@ -129,12 +156,14 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
129 fillForm(form, baseline);
156 fillForm(form, baseline);
130 draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
157 draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
131 draftStarter = normalizeStarterLoadout(baseline);
158 draftStarter = normalizeStarterLoadout(baseline);
159 draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
132 seedQuery = "";
160 seedQuery = "";
133 seedPage = 0;
161 seedPage = 0;
134 if (seedPanel?.search)
162 if (seedPanel?.search)
135 { seedPanel.search.value = ""; }
163 { seedPanel.search.value = ""; }
136 renderSeedPanel();
164 renderSeedPanel();
137 renderStarterPanel();
165 renderStarterPanel();
166 renderEquipmentStatsPanel();
138 refreshDirty();
167 refreshDirty();
139 }
168 }
140 open = visible;
169 open = visible;
@@ -167,7 +196,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
167 ...scalarDirtyValues(form, baseline),
196 ...scalarDirtyValues(form, baseline),
168 itemSeedValues: draftSeeds,
197 itemSeedValues: draftSeeds,
169 starterEquipment: draftStarter.equipment,
198 starterEquipment: draftStarter.equipment,
170 starterInventory: draftStarter.inventory
199 starterInventory: draftStarter.inventory,
200 equipmentStatBonuses: draftEquipmentStats
171 };
201 };
172 }
202 }
173
203
@@ -187,6 +217,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
187 changed.starterEquipment = nextStarter.equipment;
217 changed.starterEquipment = nextStarter.equipment;
188 changed.starterInventory = nextStarter.inventory;
218 changed.starterInventory = nextStarter.inventory;
189 }
219 }
220 const nextEquip = normalizeEquipmentStatBonuses(draftEquipmentStats);
221 if (!equipmentStatBonusMapsEqual(baseline.equipmentStatBonuses, nextEquip))
222 { changed.equipmentStatBonuses = nextEquip; }
190 return changed;
223 return changed;
191 }
224 }
192
225
@@ -407,6 +440,178 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
407 refreshDirty();
440 refreshDirty();
408 }
441 }
409
442
443 function setRowIcon (img, itemId)
444 {
445 if (!img)
446 { return; }
447 if (itemId == null)
448 {
449 img.removeAttribute("src");
450 img.alt = "";
451 return;
452 }
453 const stack = { itemId, quantity: 1 };
454 applyItemIcon(img, stack, itemAssetPathForStack(stack));
455 }
456
457 function renderEquipmentStatsPanel ()
458 {
459 if (!equipmentStatsPanel)
460 { return; }
461 const category = EQUIPMENT_STAT_CATEGORIES.find((entry) => entry.id === equipmentStatsCategoryId)
462 ?? EQUIPMENT_STAT_CATEGORIES[0];
463 if (!category)
464 { return; }
465 equipmentStatsCategoryId = category.id;
466 equipmentStatsPanel.select.value = category.id;
467 const host = equipmentStatsPanel.tables;
468 host.replaceChildren();
469
470 const baselineTable = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
471
472 for (const section of category.sections)
473 {
474 if (section.label)
475 {
476 const heading = document.createElement("h3");
477 heading.textContent = section.label;
478 host.append(heading);
479 }
480 if (!section.rows.length)
481 {
482 const empty = document.createElement("p");
483 empty.className = "hint";
484 empty.textContent = "No items in this category yet.";
485 host.append(empty);
486 continue;
487 }
488
489 const wrap = document.createElement("div");
490 wrap.className = "equip-stats-table-wrap";
491 const table = document.createElement("table");
492 table.className = "equip-stats-table";
493 const thead = document.createElement("thead");
494 const headRow = document.createElement("tr");
495 const itemTh = document.createElement("th");
496 itemTh.textContent = "Item";
497 headRow.append(itemTh);
498 for (const tier of section.tierOrder)
499 {
500 const th = document.createElement("th");
501 th.textContent = section.tierDisplayName(tier);
502 headRow.append(th);
503 }
504 thead.append(headRow);
505 table.append(thead);
506
507 const tbody = document.createElement("tbody");
508 for (const row of section.rows)
509 {
510 const tr = document.createElement("tr");
511 tr.dataset.pieceKey = row.pieceKey;
512 const defaultTier = equipmentStatRowDefaultTier(section, row);
513 const labelTd = document.createElement("td");
514 labelTd.className = "equip-stats-item";
515 const icon = document.createElement("img");
516 icon.className = "equip-stats-icon";
517 icon.width = 16;
518 icon.height = 16;
519 icon.alt = row.label;
520 setRowIcon(icon, equipmentStatRowItemId(row, defaultTier));
521 const name = document.createElement("span");
522 name.textContent = row.label;
523 labelTd.append(icon, name);
524 tr.append(labelTd);
525
526 for (const tier of section.tierOrder)
527 {
528 const td = document.createElement("td");
529 td.className = "equip-stats-cell";
530 td.dataset.tier = tier;
531 const itemId = equipmentStatRowItemId(row, tier);
532 if (itemId == null)
533 {
534 td.classList.add("empty");
535 td.textContent = "—";
536 tr.append(td);
537 continue;
538 }
539
540 const cell = document.createElement("div");
541 cell.className = "equip-stats-cell-inner";
542 const draftCell = draftEquipmentStats[category.id]?.[row.pieceKey]?.[tier] ?? {};
543 const baseCell = baselineTable[category.id]?.[row.pieceKey]?.[tier] ?? {};
544
545 for (const skillId of category.stats)
546 {
547 const line = document.createElement("label");
548 line.className = "equip-stats-stat";
549 const skillIcon = document.createElement("img");
550 skillIcon.src = `/assets/skills/${skillId}.svg`;
551 skillIcon.alt = skillId;
552 skillIcon.width = 14;
553 skillIcon.height = 14;
554 const input = document.createElement("input");
555 input.type = "number";
556 input.min = "0";
557 input.max = "99";
558 input.step = "1";
559 input.dataset.equipStat = "1";
560 input.dataset.categoryId = category.id;
561 input.dataset.pieceKey = row.pieceKey;
562 input.dataset.tier = tier;
563 input.dataset.skillId = skillId;
564 input.value = String(draftCell[skillId] ?? 0);
565 if (!settingsValuesEqual(Number(draftCell[skillId] ?? 0), Number(baseCell[skillId] ?? 0)))
566 { line.classList.add("dirty"); }
567 input.addEventListener("input", () =>
568 {
569 const value = Math.max(0, Math.min(99, Math.floor(Number(input.value) || 0)));
570 input.value = String(value);
571 const nextCat = {
572 ...(draftEquipmentStats[category.id] ?? {}),
573 [row.pieceKey]: {
574 ...(draftEquipmentStats[category.id]?.[row.pieceKey] ?? {}),
575 [tier]: {
576 ...(draftEquipmentStats[category.id]?.[row.pieceKey]?.[tier] ?? {}),
577 [skillId]: value
578 }
579 }
580 };
581 draftEquipmentStats = {
582 ...draftEquipmentStats,
583 [category.id]: nextCat
584 };
585 const baseVal = baselineTable[category.id]?.[row.pieceKey]?.[tier]?.[skillId] ?? 0;
586 line.classList.toggle("dirty", !settingsValuesEqual(value, Number(baseVal)));
587 form.dispatchEvent(new CustomEvent("equipment-stats-changed"));
588 });
589 const previewTier = () => setRowIcon(icon, itemId);
590 const restoreIcon = () =>
591 {
592 if (tr.querySelector("input:focus"))
593 { return; }
594 setRowIcon(icon, equipmentStatRowItemId(row, defaultTier));
595 };
596 td.addEventListener("mouseenter", previewTier);
597 td.addEventListener("mouseleave", restoreIcon);
598 input.addEventListener("focus", previewTier);
599 input.addEventListener("blur", restoreIcon);
600 line.append(skillIcon, input);
601 cell.append(line);
602 }
603 td.append(cell);
604 tr.append(td);
605 }
606 tbody.append(tr);
607 }
608 table.append(tbody);
609 wrap.append(table);
610 host.append(wrap);
611 }
612 refreshDirty();
613 }
614
410 function updateSeedRowReadouts (row, itemId, snap = null)
615 function updateSeedRowReadouts (row, itemId, snap = null)
411 {
616 {
412 const resolved = snap ?? itemPriceSnapshot(itemId, {
617 const resolved = snap ?? itemPriceSnapshot(itemId, {
@@ -436,16 +641,19 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
436 loaded = true;
641 loaded = true;
437 baseline = {
642 baseline = {
438 ...message.settings,
643 ...message.settings,
439 itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues)
644 itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues),
645 equipmentStatBonuses: normalizeEquipmentStatBonuses(message.settings?.equipmentStatBonuses)
440 };
646 };
441 itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"
647 itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"
442 ? message.itemLastSales
648 ? message.itemLastSales
443 : {};
649 : {};
444 draftSeeds = { ...baseline.itemSeedValues };
650 draftSeeds = { ...baseline.itemSeedValues };
445 draftStarter = normalizeStarterLoadout(baseline);
651 draftStarter = normalizeStarterLoadout(baseline);
652 draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
446 fillForm(form, baseline);
653 fillForm(form, baseline);
447 renderSeedPanel();
654 renderSeedPanel();
448 renderStarterPanel();
655 renderStarterPanel();
656 renderEquipmentStatsPanel();
449 refreshDirty();
657 refreshDirty();
450 renderLog(log, message.changelog ?? []);
658 renderLog(log, message.changelog ?? []);
451 onApplied?.(message.settings);
659 onApplied?.(message.settings);
@@ -453,7 +661,14 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
453 };
661 };
454}
662}
455
663
456function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady, onStarterPanelReady })
664function buildForm (form, {
665 getActiveCategory,
666 setActiveCategory,
667 onFieldInput,
668 onSeedPanelReady,
669 onStarterPanelReady,
670 onEquipmentStatsPanelReady
671})
457{
672{
458 form.innerHTML = "";
673 form.innerHTML = "";
459 const tabs = document.createElement("div");
674 const tabs = document.createElement("div");
@@ -498,6 +713,15 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput,
498 section.append(panel.root);
713 section.append(panel.root);
499 onStarterPanelReady?.(panel);
714 onStarterPanelReady?.(panel);
500 }
715 }
716 else if (category.panel === "equipmentStats")
717 {
718 const panel = buildEquipmentStatsPanel({
719 onCategoryChange (id)
720 { form.dispatchEvent(new CustomEvent("equip-stats-category", { detail: { id } })); }
721 });
722 section.append(panel.root);
723 onEquipmentStatsPanelReady?.(panel);
724 }
501 else
725 else
502 {
726 {
503 for (const field of category.fields)
727 for (const field of category.fields)
@@ -543,6 +767,40 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput,
543 syncTabs(form, getActiveCategory());
767 syncTabs(form, getActiveCategory());
544}
768}
545
769
770function buildEquipmentStatsPanel ({ onCategoryChange })
771{
772 const root = document.createElement("div");
773 root.className = "equip-stats-panel";
774
775 const toolbar = document.createElement("div");
776 toolbar.className = "equip-stats-toolbar";
777 const label = document.createElement("label");
778 label.className = "equip-stats-category-label";
779 label.textContent = "Category";
780 const select = document.createElement("select");
781 select.className = "equip-stats-category";
782 for (const category of EQUIPMENT_STAT_CATEGORIES)
783 {
784 const option = document.createElement("option");
785 option.value = category.id;
786 option.textContent = category.label;
787 select.append(option);
788 }
789 select.addEventListener("change", () => onCategoryChange(select.value));
790 label.append(select);
791 toolbar.append(label);
792
793 const hint = document.createElement("p");
794 hint.className = "hint";
795 hint.textContent = "Hover or focus a cell to preview that tier’s item icon. Multi-stat cells edit each bonus independently.";
796
797 const tables = document.createElement("div");
798 tables.className = "equip-stats-tables";
799
800 root.append(toolbar, hint, tables);
801 return { root, select, tables };
802}
803
546function buildSeedPricePanel ({ onSearch, onPrev, onNext })
804function buildSeedPricePanel ({ onSearch, onPrev, onNext })
547{
805{
548 const root = document.createElement("div");
806 const root = document.createElement("div");
client/src/play/characterPreview.js +22 −4
@@ -1,4 +1,4 @@
1 import { applyMagentaTintToImageData } from "/shared/render/tint.js";
1 import { applyMagentaTintToImageData, applyDualChannelTintToImageData } from "/shared/render/tint.js";
2 2 import { layersForHairPreview } from "/shared/appearance/hair.js";
3 3
4 4 /**
@@ -86,6 +86,7 @@ export function paintLiveEntitySnapshot (canvas, entity, { size = 64 } = {})
86 86 }];
87 87 const overlays = entity.overlays ?? [];
88 88 const tints = entity.overlayTints ?? [];
89 const dualTints = entity.overlayDualTints ?? [];
89 90 for (let index = 0; index < overlays.length; index++)
90 91 {
91 92 const sprite = overlays[index]?.renderer?.sprite;
@@ -94,6 +95,7 @@ export function paintLiveEntitySnapshot (canvas, entity, { size = 64 } = {})
94 95 draws.push({
95 96 entry: sprite,
96 97 tint: tints[index] ?? null,
98 dualTint: dualTints[index] ?? null,
97 99 frame: overlays[index].renderer.subImage | 0
98 100 });
99 101 }
@@ -132,9 +134,11 @@ function paintDrawListSnapshot (canvas, draws, { size = 64 } = {})
132 134 const crop = Math.min(sw, sh);
133 135 const cropSx = sx + Math.floor((sw - crop) / 2);
134 136 const cropSy = sy;
135 const source = draw.tint
136 ? tintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.tint)
137 : null;
137 let source = null;
138 if (draw.dualTint)
139 { source = dualTintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.dualTint); }
140 else if (draw.tint)
141 { source = tintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.tint); }
138 142 if (source)
139 143 { ctx.drawImage(source, 0, 0, size, size); }
140 144 else
@@ -182,3 +186,17 @@ function tintedSubCanvas (sourceImg, sx, sy, sw, sh, tintRgb)
182 186 ctx.putImageData(imageData, 0, 0);
183 187 return canvas;
184 188 }
189
190 function dualTintedSubCanvas (sourceImg, sx, sy, sw, sh, dualTint)
191 {
192 const canvas = document.createElement("canvas");
193 canvas.width = sw;
194 canvas.height = sh;
195 const ctx = canvas.getContext("2d");
196 ctx.imageSmoothingEnabled = false;
197 ctx.drawImage(sourceImg, sx, sy, sw, sh, 0, 0, sw, sh);
198 const imageData = ctx.getImageData(0, 0, sw, sh);
199 applyDualChannelTintToImageData(imageData, dualTint);
200 ctx.putImageData(imageData, 0, 0);
201 return canvas;
202 }
@@ -1,4 +1,4 @@
1import { applyMagentaTintToImageData } from "/shared/render/tint.js";
1import { applyMagentaTintToImageData, applyDualChannelTintToImageData } from "/shared/render/tint.js";
2import { layersForHairPreview } from "/shared/appearance/hair.js";
2import { layersForHairPreview } from "/shared/appearance/hair.js";
3
3
4/**
4/**
@@ -86,6 +86,7 @@ export function paintLiveEntitySnapshot (canvas, entity, { size = 64 } = {})
86 }];
86 }];
87 const overlays = entity.overlays ?? [];
87 const overlays = entity.overlays ?? [];
88 const tints = entity.overlayTints ?? [];
88 const tints = entity.overlayTints ?? [];
89 const dualTints = entity.overlayDualTints ?? [];
89 for (let index = 0; index < overlays.length; index++)
90 for (let index = 0; index < overlays.length; index++)
90 {
91 {
91 const sprite = overlays[index]?.renderer?.sprite;
92 const sprite = overlays[index]?.renderer?.sprite;
@@ -94,6 +95,7 @@ export function paintLiveEntitySnapshot (canvas, entity, { size = 64 } = {})
94 draws.push({
95 draws.push({
95 entry: sprite,
96 entry: sprite,
96 tint: tints[index] ?? null,
97 tint: tints[index] ?? null,
98 dualTint: dualTints[index] ?? null,
97 frame: overlays[index].renderer.subImage | 0
99 frame: overlays[index].renderer.subImage | 0
98 });
100 });
99 }
101 }
@@ -132,9 +134,11 @@ function paintDrawListSnapshot (canvas, draws, { size = 64 } = {})
132 const crop = Math.min(sw, sh);
134 const crop = Math.min(sw, sh);
133 const cropSx = sx + Math.floor((sw - crop) / 2);
135 const cropSx = sx + Math.floor((sw - crop) / 2);
134 const cropSy = sy;
136 const cropSy = sy;
135 const source = draw.tint
137 let source = null;
136 ? tintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.tint)
138 if (draw.dualTint)
137 : null;
139 { source = dualTintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.dualTint); }
140 else if (draw.tint)
141 { source = tintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.tint); }
138 if (source)
142 if (source)
139 { ctx.drawImage(source, 0, 0, size, size); }
143 { ctx.drawImage(source, 0, 0, size, size); }
140 else
144 else
@@ -182,3 +186,17 @@ function tintedSubCanvas (sourceImg, sx, sy, sw, sh, tintRgb)
182 ctx.putImageData(imageData, 0, 0);
186 ctx.putImageData(imageData, 0, 0);
183 return canvas;
187 return canvas;
184}
188}
189
190function dualTintedSubCanvas (sourceImg, sx, sy, sw, sh, dualTint)
191{
192 const canvas = document.createElement("canvas");
193 canvas.width = sw;
194 canvas.height = sh;
195 const ctx = canvas.getContext("2d");
196 ctx.imageSmoothingEnabled = false;
197 ctx.drawImage(sourceImg, sx, sy, sw, sh, 0, 0, sw, sh);
198 const imageData = ctx.getImageData(0, 0, sw, sh);
199 applyDualChannelTintToImageData(imageData, dualTint);
200 ctx.putImageData(imageData, 0, 0);
201 return canvas;
202}
client/src/play/crafting.js +61 −11
@@ -22,7 +22,8 @@ import {
22 22 MATERIAL_DISPLAY_NAME,
23 23 WOOD_TIER_ORDER,
24 24 WoodTier,
25 MaterialTier
25 MaterialTier,
26 woodTierForMetal
26 27 } from "/shared/definitions/materialTiers.js";
27 28 import { craftDurationMs } from "/shared/definitions/gathering.js";
28 29 import { applyItemIcon } from "../render/potionIcon.js";
@@ -80,7 +81,12 @@ export function initCrafting ({
80 81 {
81 82 selectedMaterial = materialTierSelect.value || selectedMaterial;
82 83 if (usesCraftGroups())
83 { syncSelectedRecipeFromMaterial(); }
84 {
85 const rows = groupedDisplayRecipes();
86 if (!rows.some((row) => row.group === selectedCraftGroup))
87 { selectedCraftGroup = rows[0]?.group ?? null; }
88 syncSelectedRecipeFromMaterial();
89 }
84 90 renderRecipeGrid();
85 91 renderDetail();
86 92 });
@@ -113,15 +119,39 @@ export function initCrafting ({
113 119 return stationId === CraftingStationId.craftingBench;
114 120 }
115 121
122 function isCraftingBenchStation ()
123 {
124 return stationId === CraftingStationId.craftingBench;
125 }
126
127 function isSpinningWheelStation ()
128 {
129 return stationId === CraftingStationId.spinningWheel;
130 }
131
132 function isLoomStation ()
133 {
134 return stationId === CraftingStationId.loom;
135 }
136
116 137 function usesMaterialDropdown ()
117 138 {
118 return isTailorStation() || isAnvilStation() || isWoodworkingStation();
139 return isTailorStation()
140 || isAnvilStation()
141 || isWoodworkingStation()
142 || isCraftingBenchStation()
143 || isSpinningWheelStation()
144 || isLoomStation();
119 145 }
120 146
121 /** Anvil / woodworking: one grid cell per craft group, material picks the tier variant. */
147 /** One grid cell per craft group; material dropdown picks the tier variant. */
122 148 function usesCraftGroups ()
123 149 {
124 return isAnvilStation() || isWoodworkingStation();
150 return isAnvilStation()
151 || isWoodworkingStation()
152 || isCraftingBenchStation()
153 || isSpinningWheelStation()
154 || isLoomStation();
125 155 }
126 156
127 157 function craftGroupKey (recipe)
@@ -129,6 +159,21 @@ export function initCrafting ({
129 159 return recipe.craftGroup ?? recipe.recipeId;
130 160 }
131 161
162 /** Map UI material selection to a recipe's xpMaterial tier. */
163 function recipeXpMaterialForSelection (recipe, material = selectedMaterial)
164 {
165 if (isCraftingBenchStation() && recipe.craftGroup === "bow")
166 { return woodTierForMetal(material); }
167 return material;
168 }
169
170 function recipeMatchesMaterial (recipe, material = selectedMaterial)
171 {
172 if (!recipe?.xpMaterial)
173 { return true; }
174 return recipe.xpMaterial === recipeXpMaterialForSelection(recipe, material);
175 }
176
132 177 function selectedRecipe ()
133 178 {
134 179 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
@@ -167,7 +212,7 @@ export function initCrafting ({
167 212
168 213 function materialOptionsForStation ()
169 214 {
170 if (isTailorStation())
215 if (isTailorStation() || isSpinningWheelStation() || isLoomStation())
171 216 {
172 217 return {
173 218 order: CLOTH_TIER_ORDER,
@@ -228,7 +273,9 @@ export function initCrafting ({
228 273 const rows = [];
229 274 for (const [group, variants] of byGroup)
230 275 {
231 const recipe = variants.find((entry) => entry.xpMaterial === selectedMaterial)
276 if (!variants.some((entry) => recipeMatchesMaterial(entry)))
277 { continue; }
278 const recipe = variants.find((entry) => recipeMatchesMaterial(entry))
232 279 ?? variants[0];
233 280 rows.push({ group, recipe, variants });
234 281 }
@@ -242,13 +289,16 @@ export function initCrafting ({
242 289 const variants = recipes.filter((recipe) => craftGroupKey(recipe) === selectedCraftGroup);
243 290 if (!variants.length)
244 291 { return; }
245 let match = variants.find((recipe) => recipe.xpMaterial === selectedMaterial);
292 let match = variants.find((entry) => recipeMatchesMaterial(entry));
246 293 if (!match)
247 294 {
248 295 match = variants[0];
249 selectedMaterial = match.xpMaterial ?? selectedMaterial;
250 if (materialTierSelect)
251 { materialTierSelect.value = selectedMaterial; }
296 if (match?.xpMaterial && !(isCraftingBenchStation() && match.craftGroup === "bow"))
297 {
298 selectedMaterial = match.xpMaterial;
299 if (materialTierSelect)
300 { materialTierSelect.value = selectedMaterial; }
301 }
252 302 }
253 303 selectedRecipeId = match.recipeId;
254 304 }
@@ -22,7 +22,8 @@ import {
22 MATERIAL_DISPLAY_NAME,
22 MATERIAL_DISPLAY_NAME,
23 WOOD_TIER_ORDER,
23 WOOD_TIER_ORDER,
24 WoodTier,
24 WoodTier,
25 MaterialTier
25 MaterialTier,
26 woodTierForMetal
26} from "/shared/definitions/materialTiers.js";
27} from "/shared/definitions/materialTiers.js";
27import { craftDurationMs } from "/shared/definitions/gathering.js";
28import { craftDurationMs } from "/shared/definitions/gathering.js";
28import { applyItemIcon } from "../render/potionIcon.js";
29import { applyItemIcon } from "../render/potionIcon.js";
@@ -80,7 +81,12 @@ export function initCrafting ({
80 {
81 {
81 selectedMaterial = materialTierSelect.value || selectedMaterial;
82 selectedMaterial = materialTierSelect.value || selectedMaterial;
82 if (usesCraftGroups())
83 if (usesCraftGroups())
83 { syncSelectedRecipeFromMaterial(); }
84 {
85 const rows = groupedDisplayRecipes();
86 if (!rows.some((row) => row.group === selectedCraftGroup))
87 { selectedCraftGroup = rows[0]?.group ?? null; }
88 syncSelectedRecipeFromMaterial();
89 }
84 renderRecipeGrid();
90 renderRecipeGrid();
85 renderDetail();
91 renderDetail();
86 });
92 });
@@ -113,15 +119,39 @@ export function initCrafting ({
113 return stationId === CraftingStationId.craftingBench;
119 return stationId === CraftingStationId.craftingBench;
114 }
120 }
115
121
122 function isCraftingBenchStation ()
123 {
124 return stationId === CraftingStationId.craftingBench;
125 }
126
127 function isSpinningWheelStation ()
128 {
129 return stationId === CraftingStationId.spinningWheel;
130 }
131
132 function isLoomStation ()
133 {
134 return stationId === CraftingStationId.loom;
135 }
136
116 function usesMaterialDropdown ()
137 function usesMaterialDropdown ()
117 {
138 {
118 return isTailorStation() || isAnvilStation() || isWoodworkingStation();
139 return isTailorStation()
140 || isAnvilStation()
141 || isWoodworkingStation()
142 || isCraftingBenchStation()
143 || isSpinningWheelStation()
144 || isLoomStation();
119 }
145 }
120
146
121 /** Anvil / woodworking: one grid cell per craft group, material picks the tier variant. */
147 /** One grid cell per craft group; material dropdown picks the tier variant. */
122 function usesCraftGroups ()
148 function usesCraftGroups ()
123 {
149 {
124 return isAnvilStation() || isWoodworkingStation();
150 return isAnvilStation()
151 || isWoodworkingStation()
152 || isCraftingBenchStation()
153 || isSpinningWheelStation()
154 || isLoomStation();
125 }
155 }
126
156
127 function craftGroupKey (recipe)
157 function craftGroupKey (recipe)
@@ -129,6 +159,21 @@ export function initCrafting ({
129 return recipe.craftGroup ?? recipe.recipeId;
159 return recipe.craftGroup ?? recipe.recipeId;
130 }
160 }
131
161
162 /** Map UI material selection to a recipe's xpMaterial tier. */
163 function recipeXpMaterialForSelection (recipe, material = selectedMaterial)
164 {
165 if (isCraftingBenchStation() && recipe.craftGroup === "bow")
166 { return woodTierForMetal(material); }
167 return material;
168 }
169
170 function recipeMatchesMaterial (recipe, material = selectedMaterial)
171 {
172 if (!recipe?.xpMaterial)
173 { return true; }
174 return recipe.xpMaterial === recipeXpMaterialForSelection(recipe, material);
175 }
176
132 function selectedRecipe ()
177 function selectedRecipe ()
133 {
178 {
134 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
179 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
@@ -167,7 +212,7 @@ export function initCrafting ({
167
212
168 function materialOptionsForStation ()
213 function materialOptionsForStation ()
169 {
214 {
170 if (isTailorStation())
215 if (isTailorStation() || isSpinningWheelStation() || isLoomStation())
171 {
216 {
172 return {
217 return {
173 order: CLOTH_TIER_ORDER,
218 order: CLOTH_TIER_ORDER,
@@ -228,7 +273,9 @@ export function initCrafting ({
228 const rows = [];
273 const rows = [];
229 for (const [group, variants] of byGroup)
274 for (const [group, variants] of byGroup)
230 {
275 {
231 const recipe = variants.find((entry) => entry.xpMaterial === selectedMaterial)
276 if (!variants.some((entry) => recipeMatchesMaterial(entry)))
277 { continue; }
278 const recipe = variants.find((entry) => recipeMatchesMaterial(entry))
232 ?? variants[0];
279 ?? variants[0];
233 rows.push({ group, recipe, variants });
280 rows.push({ group, recipe, variants });
234 }
281 }
@@ -242,13 +289,16 @@ export function initCrafting ({
242 const variants = recipes.filter((recipe) => craftGroupKey(recipe) === selectedCraftGroup);
289 const variants = recipes.filter((recipe) => craftGroupKey(recipe) === selectedCraftGroup);
243 if (!variants.length)
290 if (!variants.length)
244 { return; }
291 { return; }
245 let match = variants.find((recipe) => recipe.xpMaterial === selectedMaterial);
292 let match = variants.find((entry) => recipeMatchesMaterial(entry));
246 if (!match)
293 if (!match)
247 {
294 {
248 match = variants[0];
295 match = variants[0];
249 selectedMaterial = match.xpMaterial ?? selectedMaterial;
296 if (match?.xpMaterial && !(isCraftingBenchStation() && match.craftGroup === "bow"))
250 if (materialTierSelect)
297 {
251 { materialTierSelect.value = selectedMaterial; }
298 selectedMaterial = match.xpMaterial;
299 if (materialTierSelect)
300 { materialTierSelect.value = selectedMaterial; }
301 }
252 }
302 }
253 selectedRecipeId = match.recipeId;
303 selectedRecipeId = match.recipeId;
254 }
304 }
client/src/render/worldView.js +35 −7
@@ -762,6 +762,7 @@ export class WorldView
762 762
763 763 const overlays = entity.overlays ?? [];
764 764 const tints = entity.overlayTints ?? [];
765 const dualTints = entity.overlayDualTints ?? [];
765 766 const tight = entity.overlayTightFit ?? [];
766 767 for (let index = 0; index < overlays.length; index++)
767 768 {
@@ -771,7 +772,8 @@ export class WorldView
771 772 pivotX,
772 773 pivotY,
773 774 tints[index] ?? null,
774 !!tight[index]
775 !!tight[index],
776 dualTints[index] ?? null
775 777 );
776 778 }
777 779 this._portraitBodyMap = null;
@@ -835,7 +837,7 @@ export class WorldView
835 837 return true;
836 838 }
837 839
838 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit)
840 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null)
839 841 {
840 842 const sprite = object?.renderer?.sprite;
841 843 if (!sprite?.g_image)
@@ -854,7 +856,21 @@ export class WorldView
854 856 const maskUniforms = tightFit && portraitEntity
855 857 ? this.#tightFitMaskUniforms(object, portraitEntity)
856 858 : null;
857 if (tightFit && bodyHtml && maskUniforms)
859 if (dualTint)
860 {
861 const shaft = normalizeRgb(dualTint.shaft);
862 const tip = normalizeRgb(dualTint.tip);
863 shader = getDualTintLitSpriteShader();
864 uniforms = {
865 u_darkness: 0,
866 u_strength: 0,
867 u_wade: 0,
868 u_spriteHeight: height,
869 u_shaftTint: [shaft.r, shaft.g, shaft.b],
870 u_tipTint: [tip.r, tip.g, tip.b]
871 };
872 }
873 else if (tightFit && bodyHtml && maskUniforms)
858 874 {
859 875 secondaryHtml = bodyHtml;
860 876 if (tint)
@@ -1908,6 +1924,7 @@ export class WorldView
1908 1924 { overlay.destroy(); }
1909 1925 entity.overlays = [];
1910 1926 entity.overlayTints = [];
1927 entity.overlayDualTints = [];
1911 1928 entity.overlayTightFit = [];
1912 1929 entity.bloomOverlays = [];
1913 1930 for (const layer of layers.slice(1))
@@ -1920,10 +1937,16 @@ export class WorldView
1920 1937 entity.overlays.push(object);
1921 1938 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1922 1939 entity.overlayTightFit.push(!!layerDef?.tightFit);
1940 const dualTint = layer.itemId != null
1941 ? resolveItemDualTint({ itemId: layer.itemId }, layerDef)
1942 : null;
1943 entity.overlayDualTints.push(dualTint);
1923 1944 entity.overlayTints.push(
1924 layer.tint
1925 ? normalizeRgb(layer.tint)
1926 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
1945 dualTint
1946 ? null
1947 : (layer.tint
1948 ? normalizeRgb(layer.tint)
1949 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
1927 1950 );
1928 1951 const bloomName = bloomCompanionName(layer.sprite);
1929 1952 const bloomImage = this.game.images[bloomName];
@@ -1966,7 +1989,12 @@ export class WorldView
1966 1989 const overlay = entity.overlays[index];
1967 1990 const overlaySortY = pivotY + 0.5 * (index + 1);
1968 1991 overlay.transform.rotation = walkTilt;
1969 if (entity.overlayTightFit?.[index])
1992 const dualTint = entity.overlayDualTints?.[index] ?? null;
1993 if (dualTint)
1994 {
1995 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade);
1996 }
1997 else if (entity.overlayTightFit?.[index])
1970 1998 {
1971 1999 this.#syncTightFitLitSprite(
1972 2000 overlay,
@@ -762,6 +762,7 @@ export class WorldView
762
762
763 const overlays = entity.overlays ?? [];
763 const overlays = entity.overlays ?? [];
764 const tints = entity.overlayTints ?? [];
764 const tints = entity.overlayTints ?? [];
765 const dualTints = entity.overlayDualTints ?? [];
765 const tight = entity.overlayTightFit ?? [];
766 const tight = entity.overlayTightFit ?? [];
766 for (let index = 0; index < overlays.length; index++)
767 for (let index = 0; index < overlays.length; index++)
767 {
768 {
@@ -771,7 +772,8 @@ export class WorldView
771 pivotX,
772 pivotX,
772 pivotY,
773 pivotY,
773 tints[index] ?? null,
774 tints[index] ?? null,
774 !!tight[index]
775 !!tight[index],
776 dualTints[index] ?? null
775 );
777 );
776 }
778 }
777 this._portraitBodyMap = null;
779 this._portraitBodyMap = null;
@@ -835,7 +837,7 @@ export class WorldView
835 return true;
837 return true;
836 }
838 }
837
839
838 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit)
840 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null)
839 {
841 {
840 const sprite = object?.renderer?.sprite;
842 const sprite = object?.renderer?.sprite;
841 if (!sprite?.g_image)
843 if (!sprite?.g_image)
@@ -854,7 +856,21 @@ export class WorldView
854 const maskUniforms = tightFit && portraitEntity
856 const maskUniforms = tightFit && portraitEntity
855 ? this.#tightFitMaskUniforms(object, portraitEntity)
857 ? this.#tightFitMaskUniforms(object, portraitEntity)
856 : null;
858 : null;
857 if (tightFit && bodyHtml && maskUniforms)
859 if (dualTint)
860 {
861 const shaft = normalizeRgb(dualTint.shaft);
862 const tip = normalizeRgb(dualTint.tip);
863 shader = getDualTintLitSpriteShader();
864 uniforms = {
865 u_darkness: 0,
866 u_strength: 0,
867 u_wade: 0,
868 u_spriteHeight: height,
869 u_shaftTint: [shaft.r, shaft.g, shaft.b],
870 u_tipTint: [tip.r, tip.g, tip.b]
871 };
872 }
873 else if (tightFit && bodyHtml && maskUniforms)
858 {
874 {
859 secondaryHtml = bodyHtml;
875 secondaryHtml = bodyHtml;
860 if (tint)
876 if (tint)
@@ -1908,6 +1924,7 @@ export class WorldView
1908 { overlay.destroy(); }
1924 { overlay.destroy(); }
1909 entity.overlays = [];
1925 entity.overlays = [];
1910 entity.overlayTints = [];
1926 entity.overlayTints = [];
1927 entity.overlayDualTints = [];
1911 entity.overlayTightFit = [];
1928 entity.overlayTightFit = [];
1912 entity.bloomOverlays = [];
1929 entity.bloomOverlays = [];
1913 for (const layer of layers.slice(1))
1930 for (const layer of layers.slice(1))
@@ -1920,10 +1937,16 @@ export class WorldView
1920 entity.overlays.push(object);
1937 entity.overlays.push(object);
1921 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1938 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1922 entity.overlayTightFit.push(!!layerDef?.tightFit);
1939 entity.overlayTightFit.push(!!layerDef?.tightFit);
1940 const dualTint = layer.itemId != null
1941 ? resolveItemDualTint({ itemId: layer.itemId }, layerDef)
1942 : null;
1943 entity.overlayDualTints.push(dualTint);
1923 entity.overlayTints.push(
1944 entity.overlayTints.push(
1924 layer.tint
1945 dualTint
1925 ? normalizeRgb(layer.tint)
1946 ? null
1926 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
1947 : (layer.tint
1948 ? normalizeRgb(layer.tint)
1949 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
1927 );
1950 );
1928 const bloomName = bloomCompanionName(layer.sprite);
1951 const bloomName = bloomCompanionName(layer.sprite);
1929 const bloomImage = this.game.images[bloomName];
1952 const bloomImage = this.game.images[bloomName];
@@ -1966,7 +1989,12 @@ export class WorldView
1966 const overlay = entity.overlays[index];
1989 const overlay = entity.overlays[index];
1967 const overlaySortY = pivotY + 0.5 * (index + 1);
1990 const overlaySortY = pivotY + 0.5 * (index + 1);
1968 overlay.transform.rotation = walkTilt;
1991 overlay.transform.rotation = walkTilt;
1969 if (entity.overlayTightFit?.[index])
1992 const dualTint = entity.overlayDualTints?.[index] ?? null;
1993 if (dualTint)
1994 {
1995 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade);
1996 }
1997 else if (entity.overlayTightFit?.[index])
1970 {
1998 {
1971 this.#syncTightFitLitSprite(
1999 this.#syncTightFitLitSprite(
1972 overlay,
2000 overlay,
client/ui/editor.css +138 −1
@@ -61,11 +61,27 @@ body > aside {
61 61 }
62 62 .dim-combo {
63 63 position: relative;
64 display: flex;
65 align-items: stretch;
64 66 }
65 67 .dim-combo-input {
66 width: 100%;
68 flex: 1 1 auto;
69 width: 0;
70 min-width: 0;
67 71 box-sizing: border-box;
68 72 }
73 .dim-combo-toggle {
74 flex: 0 0 auto;
75 padding: 0 0.45rem;
76 border: 1px solid #3a4250;
77 border-left: none;
78 background: #1a1f28;
79 color: #c8d0dc;
80 cursor: pointer;
81 }
82 .dim-combo-toggle:hover {
83 background: #243044;
84 }
69 85 .dim-combo-list {
70 86 position: absolute;
71 87 left: 0;
@@ -506,6 +522,127 @@ label { display: block; margin: 0.4rem 0; }
506 522 align-items: center;
507 523 }
508 524
525 .equip-stats-panel {
526 display: flex;
527 flex-direction: column;
528 gap: 0.75rem;
529 min-width: 0;
530 }
531
532 .equip-stats-toolbar {
533 display: flex;
534 flex-wrap: wrap;
535 gap: 0.75rem;
536 align-items: center;
537 }
538
539 .equip-stats-category-label {
540 display: flex;
541 align-items: center;
542 gap: 0.5rem;
543 font-size: 0.85rem;
544 color: #c5ccd8;
545 }
546
547 .equip-stats-category {
548 min-width: 12rem;
549 }
550
551 .equip-stats-tables {
552 display: flex;
553 flex-direction: column;
554 gap: 1rem;
555 overflow: auto;
556 max-height: min(62vh, 640px);
557 }
558
559 .equip-stats-table-wrap {
560 overflow: auto;
561 }
562
563 .equip-stats-table {
564 border-collapse: collapse;
565 width: max-content;
566 min-width: 100%;
567 font-size: 0.8rem;
568 }
569
570 .equip-stats-table th,
571 .equip-stats-table td {
572 border: 1px solid #2c3340;
573 padding: 0.35rem 0.45rem;
574 vertical-align: middle;
575 text-align: center;
576 }
577
578 .equip-stats-table th {
579 background: #1a1f28;
580 color: #9aa3b2;
581 font-weight: 600;
582 position: sticky;
583 top: 0;
584 z-index: 1;
585 }
586
587 .equip-stats-table th:first-child,
588 .equip-stats-table td.equip-stats-item {
589 position: sticky;
590 left: 0;
591 z-index: 2;
592 background: #151922;
593 text-align: left;
594 min-width: 9rem;
595 }
596
597 .equip-stats-table th:first-child {
598 z-index: 3;
599 }
600
601 .equip-stats-item {
602 display: flex;
603 align-items: center;
604 gap: 0.45rem;
605 white-space: nowrap;
606 }
607
608 .equip-stats-icon {
609 image-rendering: pixelated;
610 flex-shrink: 0;
611 background: #0e1218;
612 border: 1px solid #2c3340;
613 }
614
615 .equip-stats-cell.empty {
616 color: #5c6575;
617 }
618
619 .equip-stats-cell-inner {
620 display: flex;
621 flex-direction: column;
622 gap: 0.25rem;
623 align-items: stretch;
624 }
625
626 .equip-stats-stat {
627 display: flex;
628 align-items: center;
629 gap: 0.3rem;
630 margin: 0;
631 }
632
633 .equip-stats-stat img {
634 flex-shrink: 0;
635 }
636
637 .equip-stats-stat input {
638 width: 3.2rem;
639 padding: 0.15rem 0.25rem;
640 }
641
642 .equip-stats-stat.dirty input {
643 border-color: #c4a35a;
644 }
645
509 646 #settings-log-wrap {
510 647 width: min(340px, 32vw);
511 648 flex-shrink: 0;
@@ -61,11 +61,27 @@ body > aside {
61}
61}
62.dim-combo {
62.dim-combo {
63 position: relative;
63 position: relative;
64 display: flex;
65 align-items: stretch;
64}
66}
65.dim-combo-input {
67.dim-combo-input {
66 width: 100%;
68 flex: 1 1 auto;
69 width: 0;
70 min-width: 0;
67 box-sizing: border-box;
71 box-sizing: border-box;
68}
72}
73.dim-combo-toggle {
74 flex: 0 0 auto;
75 padding: 0 0.45rem;
76 border: 1px solid #3a4250;
77 border-left: none;
78 background: #1a1f28;
79 color: #c8d0dc;
80 cursor: pointer;
81}
82.dim-combo-toggle:hover {
83 background: #243044;
84}
69.dim-combo-list {
85.dim-combo-list {
70 position: absolute;
86 position: absolute;
71 left: 0;
87 left: 0;
@@ -506,6 +522,127 @@ label { display: block; margin: 0.4rem 0; }
506 align-items: center;
522 align-items: center;
507}
523}
508
524
525.equip-stats-panel {
526 display: flex;
527 flex-direction: column;
528 gap: 0.75rem;
529 min-width: 0;
530}
531
532.equip-stats-toolbar {
533 display: flex;
534 flex-wrap: wrap;
535 gap: 0.75rem;
536 align-items: center;
537}
538
539.equip-stats-category-label {
540 display: flex;
541 align-items: center;
542 gap: 0.5rem;
543 font-size: 0.85rem;
544 color: #c5ccd8;
545}
546
547.equip-stats-category {
548 min-width: 12rem;
549}
550
551.equip-stats-tables {
552 display: flex;
553 flex-direction: column;
554 gap: 1rem;
555 overflow: auto;
556 max-height: min(62vh, 640px);
557}
558
559.equip-stats-table-wrap {
560 overflow: auto;
561}
562
563.equip-stats-table {
564 border-collapse: collapse;
565 width: max-content;
566 min-width: 100%;
567 font-size: 0.8rem;
568}
569
570.equip-stats-table th,
571.equip-stats-table td {
572 border: 1px solid #2c3340;
573 padding: 0.35rem 0.45rem;
574 vertical-align: middle;
575 text-align: center;
576}
577
578.equip-stats-table th {
579 background: #1a1f28;
580 color: #9aa3b2;
581 font-weight: 600;
582 position: sticky;
583 top: 0;
584 z-index: 1;
585}
586
587.equip-stats-table th:first-child,
588.equip-stats-table td.equip-stats-item {
589 position: sticky;
590 left: 0;
591 z-index: 2;
592 background: #151922;
593 text-align: left;
594 min-width: 9rem;
595}
596
597.equip-stats-table th:first-child {
598 z-index: 3;
599}
600
601.equip-stats-item {
602 display: flex;
603 align-items: center;
604 gap: 0.45rem;
605 white-space: nowrap;
606}
607
608.equip-stats-icon {
609 image-rendering: pixelated;
610 flex-shrink: 0;
611 background: #0e1218;
612 border: 1px solid #2c3340;
613}
614
615.equip-stats-cell.empty {
616 color: #5c6575;
617}
618
619.equip-stats-cell-inner {
620 display: flex;
621 flex-direction: column;
622 gap: 0.25rem;
623 align-items: stretch;
624}
625
626.equip-stats-stat {
627 display: flex;
628 align-items: center;
629 gap: 0.3rem;
630 margin: 0;
631}
632
633.equip-stats-stat img {
634 flex-shrink: 0;
635}
636
637.equip-stats-stat input {
638 width: 3.2rem;
639 padding: 0.15rem 0.25rem;
640}
641
642.equip-stats-stat.dirty input {
643 border-color: #c4a35a;
644}
645
509#settings-log-wrap {
646#settings-log-wrap {
510 width: min(340px, 32vw);
647 width: min(340px, 32vw);
511 flex-shrink: 0;
648 flex-shrink: 0;
docs/FEATURES.md +4 −4
@@ -58,8 +58,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
58 58 ## World settings
59 59
60 60 **Status:** full
61 **Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
62 **Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
61 **Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Equipment Stats**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Equipment Stats** edits worn combat bonuses as piece×tier tables (category dropdown: metal armour, leather armour, melee/ranged weapons, magic staves, wizard armour, clothing); multi-stat cells (e.g. leather Agility+Defence) are independent inputs. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
62 **Code:** `shared/definitions/worldSettings.js`, `shared/definitions/equipmentStatCategories.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
63 63
64 64 ## Baked lighting
65 65
@@ -240,10 +240,10 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
240 240 ## Equipment tiers and worn stat bonuses
241 241
242 242 **Status:** partial
243 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
243 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). **Worn combat bonuses** come from live world setting `equipmentStatBonuses` (editor **Equipment Stats** tab); defaults seed from `TIER_STAT_BONUS` (full helms +1 Defence). Leather armour can grant Agility and Defence independently; wizard armour Magic and Defence; clothing Defence. Magic casting uses worn Magic/Mind gear bonuses the same way physical combat uses Strength/Agility/Defence. Tools (pickaxes) gate on Mining and do not use the bonus tables. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
244 244 **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
245 245 **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
246 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
246 **Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentStatCategories.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
247 247
248 248 ## Gathering, crafting, and production skills
249 249
@@ -58,8 +58,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
58## World settings
58## World settings
59
59
60**Status:** full
60**Status:** full
61**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
61**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Equipment Stats**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Equipment Stats** edits worn combat bonuses as piece×tier tables (category dropdown: metal armour, leather armour, melee/ranged weapons, magic staves, wizard armour, clothing); multi-stat cells (e.g. leather Agility+Defence) are independent inputs. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
62**Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
62**Code:** `shared/definitions/worldSettings.js`, `shared/definitions/equipmentStatCategories.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
63
63
64## Baked lighting
64## Baked lighting
65
65
@@ -240,10 +240,10 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
240## Equipment tiers and worn stat bonuses
240## Equipment tiers and worn stat bonuses
241
241
242**Status:** partial
242**Status:** partial
243**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
243**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). **Worn combat bonuses** come from live world setting `equipmentStatBonuses` (editor **Equipment Stats** tab); defaults seed from `TIER_STAT_BONUS` (full helms +1 Defence). Leather armour can grant Agility and Defence independently; wizard armour Magic and Defence; clothing Defence. Magic casting uses worn Magic/Mind gear bonuses the same way physical combat uses Strength/Agility/Defence. Tools (pickaxes) gate on Mining and do not use the bonus tables. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
244**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
244**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
245**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
245**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
246**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
246**Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentStatCategories.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
247
247
248## Gathering, crafting, and production skills
248## Gathering, crafting, and production skills
249
249
server/src/combat/service.js +15 −11
@@ -118,17 +118,17 @@ function attackerSkillLevel (skills, profile, skillId)
118 118 return skillLevel(skills, skillId);
119 119 }
120 120
121 function defenderSkillLevel (skills, skillId, equipment = null)
121 function defenderSkillLevel (skills, skillId, equipment = null, settings = null)
122 122 {
123 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
123 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
124 124 return effectiveSkillLevel(skills, skillId, bonuses);
125 125 }
126 126
127 function playerCombatLevels (ecs, handle, profile)
127 function playerCombatLevels (ecs, handle, profile, settings = null)
128 128 {
129 129 const skills = ecs.get(handle, Component.skills);
130 130 const equipment = ecs.get(handle, Component.equipment);
131 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
131 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
132 132 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
133 133 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
134 134 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
@@ -428,11 +428,11 @@ export function resolveCombatTarget (world, targetId)
428 428 };
429 429 }
430 430
431 function attackerCombatLevels (ecs, attackerHandle, profile)
431 function attackerCombatLevels (ecs, attackerHandle, profile, settings = null)
432 432 {
433 433 const attackerCharacter = ecs.get(attackerHandle, Component.character);
434 434 if (attackerCharacter)
435 { return playerCombatLevels(ecs, attackerHandle, profile); }
435 { return playerCombatLevels(ecs, attackerHandle, profile, settings); }
436 436 const skills = ecs.get(attackerHandle, Component.skills);
437 437 return {
438 438 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
@@ -848,7 +848,7 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
848 848 attackerId,
849 849 targetId,
850 850 profile,
851 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
851 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
852 852 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
853 853 now,
854 854 tileX: snapshot.tileX,
@@ -983,7 +983,7 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
983 983 attackerId,
984 984 targetId,
985 985 profile,
986 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
986 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
987 987 attackerIsPlayer: !!attackerCharacter,
988 988 now,
989 989 tileX: to.tileX,
@@ -1156,19 +1156,23 @@ function applyLocalMeleeHit (
1156 1156 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
1157 1157 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
1158 1158 const attackerLevels = attackerLevelsOverride
1159 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
1159 ?? (attackerHandle != null
1160 ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings)
1161 : null);
1160 1162 if (!attackerLevels)
1161 1163 { return events; }
1162 1164
1163 1165 const agilityLevel = defenderSkillLevel(
1164 1166 defenderSkills,
1165 1167 SkillId.agility,
1166 defenderEquipment
1168 defenderEquipment,
1169 world.settings
1167 1170 );
1168 1171 const defenceLevel = defenderSkillLevel(
1169 1172 defenderSkills,
1170 1173 SkillId.defence,
1171 defenderEquipment
1174 defenderEquipment,
1175 world.settings
1172 1176 );
1173 1177
1174 1178 const resolved = resolvePhysicalAttack({
@@ -118,17 +118,17 @@ function attackerSkillLevel (skills, profile, skillId)
118 return skillLevel(skills, skillId);
118 return skillLevel(skills, skillId);
119}
119}
120
120
121function defenderSkillLevel (skills, skillId, equipment = null)
121function defenderSkillLevel (skills, skillId, equipment = null, settings = null)
122{
122{
123 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
123 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots, settings) : {};
124 return effectiveSkillLevel(skills, skillId, bonuses);
124 return effectiveSkillLevel(skills, skillId, bonuses);
125}
125}
126
126
127function playerCombatLevels (ecs, handle, profile)
127function playerCombatLevels (ecs, handle, profile, settings = null)
128{
128{
129 const skills = ecs.get(handle, Component.skills);
129 const skills = ecs.get(handle, Component.skills);
130 const equipment = ecs.get(handle, Component.equipment);
130 const equipment = ecs.get(handle, Component.equipment);
131 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
131 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
132 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
132 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
133 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
133 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
134 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
134 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
@@ -428,11 +428,11 @@ export function resolveCombatTarget (world, targetId)
428 };
428 };
429}
429}
430
430
431function attackerCombatLevels (ecs, attackerHandle, profile)
431function attackerCombatLevels (ecs, attackerHandle, profile, settings = null)
432{
432{
433 const attackerCharacter = ecs.get(attackerHandle, Component.character);
433 const attackerCharacter = ecs.get(attackerHandle, Component.character);
434 if (attackerCharacter)
434 if (attackerCharacter)
435 { return playerCombatLevels(ecs, attackerHandle, profile); }
435 { return playerCombatLevels(ecs, attackerHandle, profile, settings); }
436 const skills = ecs.get(attackerHandle, Component.skills);
436 const skills = ecs.get(attackerHandle, Component.skills);
437 return {
437 return {
438 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
438 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
@@ -848,7 +848,7 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
848 attackerId,
848 attackerId,
849 targetId,
849 targetId,
850 profile,
850 profile,
851 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
851 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
852 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
852 attackerIsPlayer: !!world.ecs.get(attackerHandle, Component.character),
853 now,
853 now,
854 tileX: snapshot.tileX,
854 tileX: snapshot.tileX,
@@ -983,7 +983,7 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
983 attackerId,
983 attackerId,
984 targetId,
984 targetId,
985 profile,
985 profile,
986 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
986 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings),
987 attackerIsPlayer: !!attackerCharacter,
987 attackerIsPlayer: !!attackerCharacter,
988 now,
988 now,
989 tileX: to.tileX,
989 tileX: to.tileX,
@@ -1156,19 +1156,23 @@ function applyLocalMeleeHit (
1156 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
1156 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
1157 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
1157 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
1158 const attackerLevels = attackerLevelsOverride
1158 const attackerLevels = attackerLevelsOverride
1159 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
1159 ?? (attackerHandle != null
1160 ? attackerCombatLevels(world.ecs, attackerHandle, profile, world.settings)
1161 : null);
1160 if (!attackerLevels)
1162 if (!attackerLevels)
1161 { return events; }
1163 { return events; }
1162
1164
1163 const agilityLevel = defenderSkillLevel(
1165 const agilityLevel = defenderSkillLevel(
1164 defenderSkills,
1166 defenderSkills,
1165 SkillId.agility,
1167 SkillId.agility,
1166 defenderEquipment
1168 defenderEquipment,
1169 world.settings
1167 );
1170 );
1168 const defenceLevel = defenderSkillLevel(
1171 const defenceLevel = defenderSkillLevel(
1169 defenderSkills,
1172 defenderSkills,
1170 SkillId.defence,
1173 SkillId.defence,
1171 defenderEquipment
1174 defenderEquipment,
1175 world.settings
1172 );
1176 );
1173
1177
1174 const resolved = resolvePhysicalAttack({
1178 const resolved = resolvePhysicalAttack({
server/src/editor/service.js +28 −2
@@ -14,6 +14,11 @@ import {
14 14 starterLoadoutsEqual,
15 15 diffStarterLoadout
16 16 } from "../../../shared/items/starterLoadout.js";
17 import {
18 normalizeEquipmentStatBonuses,
19 diffEquipmentStatBonuses,
20 equipmentStatBonusMapsEqual
21 } from "../../../shared/definitions/equipmentStatCategories.js";
17 22 import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
18 23 import {
19 24 OVERWORLD_ID,
@@ -277,6 +282,14 @@ export class EditorService
277 282 next.starterEquipment = loadout.equipment;
278 283 next.starterInventory = loadout.inventory;
279 284 }
285 if (Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses"))
286 {
287 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(partial.equipmentStatBonuses);
288 }
289 else
290 {
291 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);
292 }
280 293 const { bullets: scalarBullets, changed } = diffSettings(current, next);
281 294 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
282 295 ? diffItemSeedValues(
@@ -301,7 +314,18 @@ export class EditorService
301 314 const starterBullets = starterChanged
302 315 ? diffStarterLoadout(current, next)
303 316 : [];
304 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets];
317 const equipmentStatsChanged = Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses")
318 && !equipmentStatBonusMapsEqual(current.equipmentStatBonuses, next.equipmentStatBonuses);
319 if (equipmentStatsChanged)
320 { changed.equipmentStatBonuses = next.equipmentStatBonuses; }
321 const equipmentStatBullets = equipmentStatsChanged
322 ? diffEquipmentStatBonuses(
323 current.equipmentStatBonuses,
324 next.equipmentStatBonuses,
325 (itemId) => itemDefinition(itemId)?.displayName ?? null
326 )
327 : [];
328 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets, ...equipmentStatBullets];
305 329 if (Object.keys(changed).length === 0)
306 330 {
307 331 return {
@@ -319,7 +343,9 @@ export class EditorService
319 343 starterEquipment: changed.starterEquipment ?? current.starterEquipment
320 344 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
321 345 starterInventory: changed.starterInventory ?? current.starterInventory
322 ?? DEFAULT_WORLD_SETTINGS.starterInventory
346 ?? DEFAULT_WORLD_SETTINGS.starterInventory,
347 equipmentStatBonuses: changed.equipmentStatBonuses
348 ?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses)
323 349 };
324 350 const normalized = normalizeStarterLoadout(settings);
325 351 settings.starterEquipment = normalized.equipment;
@@ -14,6 +14,11 @@ import {
14 starterLoadoutsEqual,
14 starterLoadoutsEqual,
15 diffStarterLoadout
15 diffStarterLoadout
16} from "../../../shared/items/starterLoadout.js";
16} from "../../../shared/items/starterLoadout.js";
17import {
18 normalizeEquipmentStatBonuses,
19 diffEquipmentStatBonuses,
20 equipmentStatBonusMapsEqual
21} from "../../../shared/definitions/equipmentStatCategories.js";
17import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
22import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
18import {
23import {
19 OVERWORLD_ID,
24 OVERWORLD_ID,
@@ -277,6 +282,14 @@ export class EditorService
277 next.starterEquipment = loadout.equipment;
282 next.starterEquipment = loadout.equipment;
278 next.starterInventory = loadout.inventory;
283 next.starterInventory = loadout.inventory;
279 }
284 }
285 if (Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses"))
286 {
287 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(partial.equipmentStatBonuses);
288 }
289 else
290 {
291 next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);
292 }
280 const { bullets: scalarBullets, changed } = diffSettings(current, next);
293 const { bullets: scalarBullets, changed } = diffSettings(current, next);
281 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
294 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
282 ? diffItemSeedValues(
295 ? diffItemSeedValues(
@@ -301,7 +314,18 @@ export class EditorService
301 const starterBullets = starterChanged
314 const starterBullets = starterChanged
302 ? diffStarterLoadout(current, next)
315 ? diffStarterLoadout(current, next)
303 : [];
316 : [];
304 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets];
317 const equipmentStatsChanged = Object.prototype.hasOwnProperty.call(partial, "equipmentStatBonuses")
318 && !equipmentStatBonusMapsEqual(current.equipmentStatBonuses, next.equipmentStatBonuses);
319 if (equipmentStatsChanged)
320 { changed.equipmentStatBonuses = next.equipmentStatBonuses; }
321 const equipmentStatBullets = equipmentStatsChanged
322 ? diffEquipmentStatBonuses(
323 current.equipmentStatBonuses,
324 next.equipmentStatBonuses,
325 (itemId) => itemDefinition(itemId)?.displayName ?? null
326 )
327 : [];
328 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets, ...equipmentStatBullets];
305 if (Object.keys(changed).length === 0)
329 if (Object.keys(changed).length === 0)
306 {
330 {
307 return {
331 return {
@@ -319,7 +343,9 @@ export class EditorService
319 starterEquipment: changed.starterEquipment ?? current.starterEquipment
343 starterEquipment: changed.starterEquipment ?? current.starterEquipment
320 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
344 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
321 starterInventory: changed.starterInventory ?? current.starterInventory
345 starterInventory: changed.starterInventory ?? current.starterInventory
322 ?? DEFAULT_WORLD_SETTINGS.starterInventory
346 ?? DEFAULT_WORLD_SETTINGS.starterInventory,
347 equipmentStatBonuses: changed.equipmentStatBonuses
348 ?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses)
323 };
349 };
324 const normalized = normalizeStarterLoadout(settings);
350 const normalized = normalizeStarterLoadout(settings);
325 settings.starterEquipment = normalized.equipment;
351 settings.starterEquipment = normalized.equipment;
server/src/gateway/websocket.js +13 −1
@@ -758,10 +758,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
758 758 });
759 759 break;
760 760 case MessageType.editorListDimensions:
761 case "EDITOR_LIST_DIMENSIONS":
761 762 requireAdmin(session);
762 send(session, { type: MessageType.editorDimensions, ...editor.listDimensions() });
763 try
764 {
765 send(session, { type: MessageType.editorDimensions, ...editor.listDimensions() });
766 }
767 catch (err)
768 {
769 send(session, { type: MessageType.error, message: err.userFacing ? err.message : "Failed to list dimensions." });
770 }
763 771 break;
764 772 case MessageType.editorCreateDimension:
773 case "EDITOR_CREATE_DIMENSION":
765 774 requireAdmin(session);
766 775 send(session, {
767 776 type: MessageType.editorDimensions,
@@ -769,6 +778,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
769 778 });
770 779 break;
771 780 case MessageType.editorSaveDimension:
781 case "EDITOR_SAVE_DIMENSION":
772 782 requireAdmin(session);
773 783 send(session, {
774 784 type: MessageType.editorDimensions,
@@ -776,6 +786,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
776 786 });
777 787 break;
778 788 case MessageType.editorSoftDeleteDimension:
789 case "EDITOR_SOFT_DELETE_DIMENSION":
779 790 requireAdmin(session);
780 791 send(session, {
781 792 type: MessageType.editorDimensions,
@@ -783,6 +794,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
783 794 });
784 795 break;
785 796 case MessageType.editorCancelDimensionDeletion:
797 case "EDITOR_CANCEL_DIMENSION_DELETION":
786 798 requireAdmin(session);
787 799 send(session, {
788 800 type: MessageType.editorDimensions,
@@ -758,10 +758,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
758 });
758 });
759 break;
759 break;
760 case MessageType.editorListDimensions:
760 case MessageType.editorListDimensions:
761 case "EDITOR_LIST_DIMENSIONS":
761 requireAdmin(session);
762 requireAdmin(session);
762 send(session, { type: MessageType.editorDimensions, ...editor.listDimensions() });
763 try
764 {
765 send(session, { type: MessageType.editorDimensions, ...editor.listDimensions() });
766 }
767 catch (err)
768 {
769 send(session, { type: MessageType.error, message: err.userFacing ? err.message : "Failed to list dimensions." });
770 }
763 break;
771 break;
764 case MessageType.editorCreateDimension:
772 case MessageType.editorCreateDimension:
773 case "EDITOR_CREATE_DIMENSION":
765 requireAdmin(session);
774 requireAdmin(session);
766 send(session, {
775 send(session, {
767 type: MessageType.editorDimensions,
776 type: MessageType.editorDimensions,
@@ -769,6 +778,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
769 });
778 });
770 break;
779 break;
771 case MessageType.editorSaveDimension:
780 case MessageType.editorSaveDimension:
781 case "EDITOR_SAVE_DIMENSION":
772 requireAdmin(session);
782 requireAdmin(session);
773 send(session, {
783 send(session, {
774 type: MessageType.editorDimensions,
784 type: MessageType.editorDimensions,
@@ -776,6 +786,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
776 });
786 });
777 break;
787 break;
778 case MessageType.editorSoftDeleteDimension:
788 case MessageType.editorSoftDeleteDimension:
789 case "EDITOR_SOFT_DELETE_DIMENSION":
779 requireAdmin(session);
790 requireAdmin(session);
780 send(session, {
791 send(session, {
781 type: MessageType.editorDimensions,
792 type: MessageType.editorDimensions,
@@ -783,6 +794,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
783 });
794 });
784 break;
795 break;
785 case MessageType.editorCancelDimensionDeletion:
796 case MessageType.editorCancelDimensionDeletion:
797 case "EDITOR_CANCEL_DIMENSION_DELETION":
786 requireAdmin(session);
798 requireAdmin(session);
787 send(session, {
799 send(session, {
788 type: MessageType.editorDimensions,
800 type: MessageType.editorDimensions,
server/src/persistence/worldDb.js +2 −0
@@ -1,5 +1,6 @@
1 1 import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2 2 import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
3 import { normalizeEquipmentStatBonuses } from "../../../shared/definitions/equipmentStatCategories.js";
3 4 import {
4 5 OVERWORLD_ID,
5 6 DIMENSION_PURGE_MS,
@@ -265,6 +266,7 @@ export class WorldDatabase
265 266 const loadout = normalizeStarterLoadout(merged);
266 267 merged.starterEquipment = loadout.equipment;
267 268 merged.starterInventory = loadout.inventory;
269 merged.equipmentStatBonuses = normalizeEquipmentStatBonuses(merged.equipmentStatBonuses);
268 270 return merged;
269 271 }
270 272
@@ -1,5 +1,6 @@
1import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
1import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
2import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
3import { normalizeEquipmentStatBonuses } from "../../../shared/definitions/equipmentStatCategories.js";
3import {
4import {
4 OVERWORLD_ID,
5 OVERWORLD_ID,
5 DIMENSION_PURGE_MS,
6 DIMENSION_PURGE_MS,
@@ -265,6 +266,7 @@ export class WorldDatabase
265 const loadout = normalizeStarterLoadout(merged);
266 const loadout = normalizeStarterLoadout(merged);
266 merged.starterEquipment = loadout.equipment;
267 merged.starterEquipment = loadout.equipment;
267 merged.starterInventory = loadout.inventory;
268 merged.starterInventory = loadout.inventory;
269 merged.equipmentStatBonuses = normalizeEquipmentStatBonuses(merged.equipmentStatBonuses);
268 return merged;
270 return merged;
269 }
271 }
270
272
server/src/simulation/spawners.js +42 −14
@@ -23,7 +23,8 @@ import { itemDefinition } from "../../../shared/definitions/items.js";
23 23 import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
24 24 import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
25 25 import { Component } from "../ecs/components.js";
26 import { tileToChunk, tileToRegion } from "../world/coordinates.js";
26 import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js";
27 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
27 28
28 29 export function collectSpawnRequests (world)
29 30 {
@@ -35,7 +36,8 @@ export function collectSpawnRequests (world)
35 36 {
36 37 if (chunk.replica || !chunk.simulating || !chunk.data.open)
37 38 { continue; }
38 const [chunkX, chunkY] = key.split(",").map(Number);
39 const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key);
40 const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID);
39 41 for (const entry of chunk.data.spawners ?? [])
40 42 {
41 43 const localX = entry.localX;
@@ -59,7 +61,15 @@ export function collectSpawnRequests (world)
59 61 { continue; }
60 62 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
61 63 { break; }
62 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
64 const tile = pickSpawnTile(
65 world,
66 originX,
67 originY,
68 config.spawnRangeTiles,
69 flying,
70 reserved,
71 dimensionId
72 );
63 73 if (!tile)
64 74 { break; }
65 75 reserved.add(`${tile.tileX},${tile.tileY}`);
@@ -67,6 +77,7 @@ export function collectSpawnRequests (world)
67 77 staffAlive.set(config.spawnerId, alive);
68 78 requests.push({
69 79 ...tile,
80 dimensionId,
70 81 mobTypeId: MobId.centralExchange,
71 82 spawnerId: config.spawnerId,
72 83 originTileX: originX,
@@ -94,12 +105,21 @@ export function collectSpawnRequests (world)
94 105
95 106 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
96 107 {
97 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
108 const tile = pickSpawnTile(
109 world,
110 originX,
111 originY,
112 config.spawnRangeTiles,
113 flying,
114 reserved,
115 dimensionId
116 );
98 117 if (!tile)
99 118 { break; }
100 119 reserved.add(`${tile.tileX},${tile.tileY}`);
101 120 requests.push({
102 121 ...tile,
122 dimensionId,
103 123 mobTypeId: config.mobTypeId,
104 124 spawnerId: config.spawnerId,
105 125 originTileX: originX,
@@ -156,7 +176,11 @@ export function mobComponents (request)
156 176
157 177 const maxHp = mobHealthForLevel(def, level);
158 178 const components = {
159 position: { tileX: request.tileX, tileY: request.tileY },
179 position: {
180 tileX: request.tileX,
181 tileY: request.tileY,
182 dimensionId: normalizeDimensionId(request.dimensionId ?? OVERWORLD_ID)
183 },
160 184 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
161 185 path: { tiles: [] },
162 186 appearance,
@@ -330,19 +354,22 @@ function collectAmbientRequests (world, reserved = new Set())
330 354 {
331 355 if (requests.length + alive >= budget)
332 356 { break; }
357 const dim = normalizeDimensionId(loader.position.dimensionId ?? OVERWORLD_ID);
333 358 const tile = pickSpawnTile(
334 359 world,
335 360 loader.position.tileX,
336 361 loader.position.tileY,
337 362 8,
338 363 !!def.flying,
339 reserved
364 reserved,
365 dim
340 366 );
341 367 if (!tile)
342 368 { continue; }
343 369 reserved.add(`${tile.tileX},${tile.tileY}`);
344 370 requests.push({
345 371 ...tile,
372 dimensionId: dim,
346 373 mobTypeId: def.mobTypeId,
347 374 spawnerId: null,
348 375 level: 1,
@@ -395,8 +422,9 @@ function countCreatures (world, mobTypeId)
395 422 return count;
396 423 }
397 424
398 function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
425 function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null, dimensionId = OVERWORLD_ID)
399 426 {
427 const dim = normalizeDimensionId(dimensionId);
400 428 const radius = Math.max(1, range | 0);
401 429 for (let attempt = 0; attempt < 48; attempt++)
402 430 {
@@ -405,24 +433,24 @@ function pickSpawnTile (world, originX, originY, range, flying = false, reserved
405 433 const key = `${tileX},${tileY}`;
406 434 if (reserved?.has(key))
407 435 { continue; }
408 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
436 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY), dim))
409 437 { continue; }
410 438 if (flying)
411 439 {
412 if (!chunkIsOpen(world, tileX, tileY))
440 if (!chunkIsOpen(world, tileX, tileY, dim))
413 441 { continue; }
414 return { tileX, tileY };
442 return { tileX, tileY, dimensionId: dim };
415 443 }
416 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
444 if (!world.isEnterable(tileX, tileY, dim) || world.occupied(tileX, tileY, dim))
417 445 { continue; }
418 return { tileX, tileY };
446 return { tileX, tileY, dimensionId: dim };
419 447 }
420 448 return null;
421 449 }
422 450
423 function chunkIsOpen (world, tileX, tileY)
451 function chunkIsOpen (world, tileX, tileY, dimensionId = OVERWORLD_ID)
424 452 {
425 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
453 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
426 454 return !!data?.open;
427 455 }
428 456
@@ -23,7 +23,8 @@ import { itemDefinition } from "../../../shared/definitions/items.js";
23import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
23import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
24import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
24import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
25import { Component } from "../ecs/components.js";
25import { Component } from "../ecs/components.js";
26import { tileToChunk, tileToRegion } from "../world/coordinates.js";
26import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js";
27import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
27
28
28export function collectSpawnRequests (world)
29export function collectSpawnRequests (world)
29{
30{
@@ -35,7 +36,8 @@ export function collectSpawnRequests (world)
35 {
36 {
36 if (chunk.replica || !chunk.simulating || !chunk.data.open)
37 if (chunk.replica || !chunk.simulating || !chunk.data.open)
37 { continue; }
38 { continue; }
38 const [chunkX, chunkY] = key.split(",").map(Number);
39 const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key);
40 const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID);
39 for (const entry of chunk.data.spawners ?? [])
41 for (const entry of chunk.data.spawners ?? [])
40 {
42 {
41 const localX = entry.localX;
43 const localX = entry.localX;
@@ -59,7 +61,15 @@ export function collectSpawnRequests (world)
59 { continue; }
61 { continue; }
60 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
62 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
61 { break; }
63 { break; }
62 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
64 const tile = pickSpawnTile(
65 world,
66 originX,
67 originY,
68 config.spawnRangeTiles,
69 flying,
70 reserved,
71 dimensionId
72 );
63 if (!tile)
73 if (!tile)
64 { break; }
74 { break; }
65 reserved.add(`${tile.tileX},${tile.tileY}`);
75 reserved.add(`${tile.tileX},${tile.tileY}`);
@@ -67,6 +77,7 @@ export function collectSpawnRequests (world)
67 staffAlive.set(config.spawnerId, alive);
77 staffAlive.set(config.spawnerId, alive);
68 requests.push({
78 requests.push({
69 ...tile,
79 ...tile,
80 dimensionId,
70 mobTypeId: MobId.centralExchange,
81 mobTypeId: MobId.centralExchange,
71 spawnerId: config.spawnerId,
82 spawnerId: config.spawnerId,
72 originTileX: originX,
83 originTileX: originX,
@@ -94,12 +105,21 @@ export function collectSpawnRequests (world)
94
105
95 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
106 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
96 {
107 {
97 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
108 const tile = pickSpawnTile(
109 world,
110 originX,
111 originY,
112 config.spawnRangeTiles,
113 flying,
114 reserved,
115 dimensionId
116 );
98 if (!tile)
117 if (!tile)
99 { break; }
118 { break; }
100 reserved.add(`${tile.tileX},${tile.tileY}`);
119 reserved.add(`${tile.tileX},${tile.tileY}`);
101 requests.push({
120 requests.push({
102 ...tile,
121 ...tile,
122 dimensionId,
103 mobTypeId: config.mobTypeId,
123 mobTypeId: config.mobTypeId,
104 spawnerId: config.spawnerId,
124 spawnerId: config.spawnerId,
105 originTileX: originX,
125 originTileX: originX,
@@ -156,7 +176,11 @@ export function mobComponents (request)
156
176
157 const maxHp = mobHealthForLevel(def, level);
177 const maxHp = mobHealthForLevel(def, level);
158 const components = {
178 const components = {
159 position: { tileX: request.tileX, tileY: request.tileY },
179 position: {
180 tileX: request.tileX,
181 tileY: request.tileY,
182 dimensionId: normalizeDimensionId(request.dimensionId ?? OVERWORLD_ID)
183 },
160 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
184 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
161 path: { tiles: [] },
185 path: { tiles: [] },
162 appearance,
186 appearance,
@@ -330,19 +354,22 @@ function collectAmbientRequests (world, reserved = new Set())
330 {
354 {
331 if (requests.length + alive >= budget)
355 if (requests.length + alive >= budget)
332 { break; }
356 { break; }
357 const dim = normalizeDimensionId(loader.position.dimensionId ?? OVERWORLD_ID);
333 const tile = pickSpawnTile(
358 const tile = pickSpawnTile(
334 world,
359 world,
335 loader.position.tileX,
360 loader.position.tileX,
336 loader.position.tileY,
361 loader.position.tileY,
337 8,
362 8,
338 !!def.flying,
363 !!def.flying,
339 reserved
364 reserved,
365 dim
340 );
366 );
341 if (!tile)
367 if (!tile)
342 { continue; }
368 { continue; }
343 reserved.add(`${tile.tileX},${tile.tileY}`);
369 reserved.add(`${tile.tileX},${tile.tileY}`);
344 requests.push({
370 requests.push({
345 ...tile,
371 ...tile,
372 dimensionId: dim,
346 mobTypeId: def.mobTypeId,
373 mobTypeId: def.mobTypeId,
347 spawnerId: null,
374 spawnerId: null,
348 level: 1,
375 level: 1,
@@ -395,8 +422,9 @@ function countCreatures (world, mobTypeId)
395 return count;
422 return count;
396}
423}
397
424
398function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
425function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null, dimensionId = OVERWORLD_ID)
399{
426{
427 const dim = normalizeDimensionId(dimensionId);
400 const radius = Math.max(1, range | 0);
428 const radius = Math.max(1, range | 0);
401 for (let attempt = 0; attempt < 48; attempt++)
429 for (let attempt = 0; attempt < 48; attempt++)
402 {
430 {
@@ -405,24 +433,24 @@ function pickSpawnTile (world, originX, originY, range, flying = false, reserved
405 const key = `${tileX},${tileY}`;
433 const key = `${tileX},${tileY}`;
406 if (reserved?.has(key))
434 if (reserved?.has(key))
407 { continue; }
435 { continue; }
408 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
436 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY), dim))
409 { continue; }
437 { continue; }
410 if (flying)
438 if (flying)
411 {
439 {
412 if (!chunkIsOpen(world, tileX, tileY))
440 if (!chunkIsOpen(world, tileX, tileY, dim))
413 { continue; }
441 { continue; }
414 return { tileX, tileY };
442 return { tileX, tileY, dimensionId: dim };
415 }
443 }
416 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
444 if (!world.isEnterable(tileX, tileY, dim) || world.occupied(tileX, tileY, dim))
417 { continue; }
445 { continue; }
418 return { tileX, tileY };
446 return { tileX, tileY, dimensionId: dim };
419 }
447 }
420 return null;
448 return null;
421}
449}
422
450
423function chunkIsOpen (world, tileX, tileY)
451function chunkIsOpen (world, tileX, tileY, dimensionId = OVERWORLD_ID)
424{
452{
425 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
453 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
426 return !!data?.open;
454 return !!data?.open;
427}
455}
428
456
server/src/spells/service.js +10 −4
@@ -27,6 +27,8 @@ import {
27 27 } from "../../../shared/combat/magic.js";
28 28 import { mobDefinition } from "../../../shared/definitions/mobs.js";
29 29 import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
30 import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";
31 import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
30 32 import {
31 33 chebyshev,
32 34 hasCombatLineOfSight,
@@ -200,12 +202,16 @@ function cancelArmSpell (world, sessionId, command)
200 202 };
201 203 }
202 204
203 function casterMagicLevels (ecs, handle)
205 function casterMagicLevels (ecs, handle, settings = null)
204 206 {
205 207 const skills = ecs.get(handle, Component.skills);
208 const equipment = ecs.get(handle, Component.equipment);
209 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
210 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
211 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
206 212 return {
207 magic: skillLevel(skills, SkillId.magic),
208 mind: skillLevel(skills, SkillId.mind)
213 magic: effectiveSkillLevel(skills, SkillId.magic, bonuses),
214 mind: effectiveSkillLevel(skills, SkillId.mind, bonuses)
209 215 };
210 216 }
211 217
@@ -350,7 +356,7 @@ function executeCast (world, sessionId, characterId, spellId, target, now)
350 356 throw error;
351 357 }
352 358
353 const levels = casterMagicLevels(world.ecs, handle);
359 const levels = casterMagicLevels(world.ecs, handle, world.settings);
354 360 const difficulty = spellDifficulty(def);
355 361 const cast = resolveSpellCast({
356 362 magicSkillLevel: levels.magic,
@@ -27,6 +27,8 @@ import {
27} from "../../../shared/combat/magic.js";
27} from "../../../shared/combat/magic.js";
28import { mobDefinition } from "../../../shared/definitions/mobs.js";
28import { mobDefinition } from "../../../shared/definitions/mobs.js";
29import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
29import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
30import { equipmentBonusesFromSlots, effectiveSkillLevel } from "../../../shared/equipment/stats.js";
31import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
30import {
32import {
31 chebyshev,
33 chebyshev,
32 hasCombatLineOfSight,
34 hasCombatLineOfSight,
@@ -200,12 +202,16 @@ function cancelArmSpell (world, sessionId, command)
200 };
202 };
201}
203}
202
204
203function casterMagicLevels (ecs, handle)
205function casterMagicLevels (ecs, handle, settings = null)
204{
206{
205 const skills = ecs.get(handle, Component.skills);
207 const skills = ecs.get(handle, Component.skills);
208 const equipment = ecs.get(handle, Component.equipment);
209 const bonuses = equipmentBonusesFromSlots(equipment?.slots, settings);
210 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
211 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
206 return {
212 return {
207 magic: skillLevel(skills, SkillId.magic),
213 magic: effectiveSkillLevel(skills, SkillId.magic, bonuses),
208 mind: skillLevel(skills, SkillId.mind)
214 mind: effectiveSkillLevel(skills, SkillId.mind, bonuses)
209 };
215 };
210}
216}
211
217
@@ -350,7 +356,7 @@ function executeCast (world, sessionId, characterId, spellId, target, now)
350 throw error;
356 throw error;
351 }
357 }
352
358
353 const levels = casterMagicLevels(world.ecs, handle);
359 const levels = casterMagicLevels(world.ecs, handle, world.settings);
354 const difficulty = spellDifficulty(def);
360 const difficulty = spellDifficulty(def);
355 const cast = resolveSpellCast({
361 const cast = resolveSpellCast({
356 magicSkillLevel: levels.magic,
362 magicSkillLevel: levels.magic,
server/tests/craftingStations.test.js +13 −10
@@ -42,10 +42,10 @@ test("canCraftFitInventory accounts for space freed by consumed materials", () =
42 42 {
43 43 const recipe = {
44 44 output: { itemId: ItemId.stick, quantity: 1 },
45 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
45 inputs: [{ itemId: ItemId.pineLog, quantity: 1 }]
46 46 };
47 47 const slots = emptySlots();
48 slots[0] = { itemId: ItemId.paper, quantity: 10 };
48 slots[0] = { itemId: ItemId.pineLog, quantity: 10 };
49 49 for (let i = 1; i < 32; i++)
50 50 { slots[i] = { itemId: ItemId.coins, quantity: 1 }; }
51 51 assert.equal(canCraftFitInventory(slots, recipe), false);
@@ -56,25 +56,28 @@ test("canCraftFitInventory accounts for space freed by consumed materials", () =
56 56 test("canCraftFitInventory rejects missing inputs", () =>
57 57 {
58 58 const slots = emptySlots();
59 slots[0] = { itemId: ItemId.paper, quantity: 1 };
59 slots[0] = { itemId: ItemId.pineLog, quantity: 0 };
60 60 assert.equal(canCraftFitInventory(slots, {
61 61 output: { itemId: ItemId.stick, quantity: 1 },
62 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
62 inputs: [{ itemId: ItemId.pineLog, quantity: 1 }]
63 63 }), false);
64 64 });
65 65
66 test("recipesForStation lists bench recipes", () =>
66 test("recipesForStation lists woodworking stick and quarterstaff recipes", () =>
67 67 {
68 const bench = recipesForStation(CraftingStationId.craftingBench);
69 assert.ok(bench.length >= 1);
70 assert.equal(bench[0].recipeId, "dev-stick-from-paper");
68 const bench = recipesForStation(CraftingStationId.woodworkingBench);
69 assert.ok(bench.some((recipe) => recipe.recipeId === "stick-pine"));
70 assert.ok(bench.some((recipe) => recipe.recipeId === "quarterstaff-birch"));
71 const stick = recipeDefinition("stick-pine");
72 assert.equal(stick.output.itemId, ItemId.stick);
73 assert.deepEqual(stick.inputs, [{ itemId: ItemId.pineLog, quantity: 1 }]);
71 74 });
72 75
73 76 test("canStartCraft enforces minimum skill level", () =>
74 77 {
75 78 const slots = emptySlots();
76 slots[0] = { itemId: ItemId.paper, quantity: 5 };
77 const recipe = recipeDefinition("dev-stick-from-paper");
79 slots[0] = { itemId: ItemId.pineLog, quantity: 5 };
80 const recipe = recipeDefinition("stick-pine");
78 81 assert.equal(canStartCraft(slots, recipe, 1), true);
79 82 assert.equal(canStartCraft(slots, recipe, 0), false);
80 83 });
@@ -42,10 +42,10 @@ test("canCraftFitInventory accounts for space freed by consumed materials", () =
42{
42{
43 const recipe = {
43 const recipe = {
44 output: { itemId: ItemId.stick, quantity: 1 },
44 output: { itemId: ItemId.stick, quantity: 1 },
45 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
45 inputs: [{ itemId: ItemId.pineLog, quantity: 1 }]
46 };
46 };
47 const slots = emptySlots();
47 const slots = emptySlots();
48 slots[0] = { itemId: ItemId.paper, quantity: 10 };
48 slots[0] = { itemId: ItemId.pineLog, quantity: 10 };
49 for (let i = 1; i < 32; i++)
49 for (let i = 1; i < 32; i++)
50 { slots[i] = { itemId: ItemId.coins, quantity: 1 }; }
50 { slots[i] = { itemId: ItemId.coins, quantity: 1 }; }
51 assert.equal(canCraftFitInventory(slots, recipe), false);
51 assert.equal(canCraftFitInventory(slots, recipe), false);
@@ -56,25 +56,28 @@ test("canCraftFitInventory accounts for space freed by consumed materials", () =
56test("canCraftFitInventory rejects missing inputs", () =>
56test("canCraftFitInventory rejects missing inputs", () =>
57{
57{
58 const slots = emptySlots();
58 const slots = emptySlots();
59 slots[0] = { itemId: ItemId.paper, quantity: 1 };
59 slots[0] = { itemId: ItemId.pineLog, quantity: 0 };
60 assert.equal(canCraftFitInventory(slots, {
60 assert.equal(canCraftFitInventory(slots, {
61 output: { itemId: ItemId.stick, quantity: 1 },
61 output: { itemId: ItemId.stick, quantity: 1 },
62 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
62 inputs: [{ itemId: ItemId.pineLog, quantity: 1 }]
63 }), false);
63 }), false);
64});
64});
65
65
66test("recipesForStation lists bench recipes", () =>
66test("recipesForStation lists woodworking stick and quarterstaff recipes", () =>
67{
67{
68 const bench = recipesForStation(CraftingStationId.craftingBench);
68 const bench = recipesForStation(CraftingStationId.woodworkingBench);
69 assert.ok(bench.length >= 1);
69 assert.ok(bench.some((recipe) => recipe.recipeId === "stick-pine"));
70 assert.equal(bench[0].recipeId, "dev-stick-from-paper");
70 assert.ok(bench.some((recipe) => recipe.recipeId === "quarterstaff-birch"));
71 const stick = recipeDefinition("stick-pine");
72 assert.equal(stick.output.itemId, ItemId.stick);
73 assert.deepEqual(stick.inputs, [{ itemId: ItemId.pineLog, quantity: 1 }]);
71});
74});
72
75
73test("canStartCraft enforces minimum skill level", () =>
76test("canStartCraft enforces minimum skill level", () =>
74{
77{
75 const slots = emptySlots();
78 const slots = emptySlots();
76 slots[0] = { itemId: ItemId.paper, quantity: 5 };
79 slots[0] = { itemId: ItemId.pineLog, quantity: 5 };
77 const recipe = recipeDefinition("dev-stick-from-paper");
80 const recipe = recipeDefinition("stick-pine");
78 assert.equal(canStartCraft(slots, recipe, 1), true);
81 assert.equal(canStartCraft(slots, recipe, 1), true);
79 assert.equal(canStartCraft(slots, recipe, 0), false);
82 assert.equal(canStartCraft(slots, recipe, 0), false);
80});
83});
server/tests/equipment.test.js +75 −7
@@ -2,7 +2,9 @@ import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
4 4 import { ArmourItemId } from "../../shared/definitions/armourItems.js";
5 import { MaterialTier, tierStatBonus, tierMinSkillLevel } from "../../shared/definitions/materialTiers.js";
5 import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
6 import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
7 import { MaterialTier, WoodTier, tierStatBonus, tierMinSkillLevel } from "../../shared/definitions/materialTiers.js";
6 8 import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
7 9 import { SkillId } from "../../shared/definitions/skills.js";
8 10 import { normalizePlayerSkills } from "../../shared/skills/state.js";
@@ -13,6 +15,13 @@ import {
13 15 equipmentBonusesFromSlots
14 16 } from "../../shared/equipment/stats.js";
15 17 import { emptyEquipment } from "../../shared/items/inventory.js";
18 import {
19 assertAllBonusGearCategorized,
20 defaultEquipmentStatBonuses,
21 normalizeEquipmentStatBonuses,
22 bonusForEquippedItem,
23 diffEquipmentStatBonuses
24 } from "../../shared/definitions/equipmentStatCategories.js";
16 25
17 26 test("tier stat bonuses scale by material", () =>
18 27 {
@@ -21,6 +30,12 @@ test("tier stat bonuses scale by material", () =>
21 30 assert.ok(tierStatBonus(MaterialTier.orichalcum) > tierStatBonus(MaterialTier.mithril));
22 31 });
23 32
33 test("every bonus-gear item is categorized exactly once", () =>
34 {
35 const result = assertAllBonusGearCategorized();
36 assert.equal(result.ok, true, JSON.stringify(result));
37 });
38
24 39 test("equipped weapons and armour add effective combat stats", () =>
25 40 {
26 41 const skills = normalizePlayerSkills(null);
@@ -30,14 +45,32 @@ test("equipped weapons and armour add effective combat stats", () =>
30 45 chest: { itemId: ItemId.clothShirt, quantity: 1 }
31 46 };
32 47 const bonuses = equipmentBonusesFromSlots(slots);
33 assert.equal(bonuses[SkillId.strength], tierStatBonus(MaterialTier.bronze));
34 assert.equal(bonuses[SkillId.defence], tierStatBonus(MaterialTier.bronze));
48 assert.equal(bonuses[SkillId.strength], tierStatBonus(WoodTier.pine));
49 assert.equal(bonuses[SkillId.defence], 1);
35 50 assert.equal(
36 51 effectiveSkillLevel(skills, SkillId.strength, bonuses),
37 1 + tierStatBonus(MaterialTier.bronze)
52 1 + tierStatBonus(WoodTier.pine)
38 53 );
39 54 });
40 55
56 test("leather shoes grant independent agility and defence from settings", () =>
57 {
58 const settings = normalizeEquipmentStatBonuses({
59 leatherArmour: {
60 shoes: {
61 softLeather: { agility: 3, defence: 1 }
62 }
63 }
64 });
65 const slots = {
66 ...emptyEquipment().slots,
67 boots: { itemId: LeatherItemId.leatherShoes, quantity: 1 }
68 };
69 const bonuses = equipmentBonusesFromSlots(slots, { equipmentStatBonuses: settings });
70 assert.equal(bonuses[SkillId.agility], 3);
71 assert.equal(bonuses[SkillId.defence], 1);
72 });
73
41 74 test("bronze gear equips at level 1", () =>
42 75 {
43 76 const skills = normalizePlayerSkills(null);
@@ -68,9 +101,8 @@ test("full helm grants +1 defence bonus and +1 equip level", () =>
68 101 const horned = itemDefinition(ArmourItemId.bronzeHornedHelm);
69 102 const skills = normalizePlayerSkills(null);
70 103
71 assert.equal(helmet.equipment.bonus, undefined);
72 assert.equal(fullHelm.equipment.bonus, tierStatBonus(MaterialTier.bronze) + 1);
73 assert.equal(horned.equipment.bonus, undefined);
104 assert.equal(fullHelm.equipment.bonus, undefined);
105 assert.equal(fullHelm.equipment.minSkillLevel, tierMinSkillLevel(MaterialTier.bronze) + 1);
74 106
75 107 assert.equal(canEquipItem(skills, helmet).ok, true);
76 108 assert.equal(canEquipItem(skills, fullHelm).ok, false);
@@ -94,3 +126,39 @@ test("full helm grants +1 defence bonus and +1 equip level", () =>
94 126 tierStatBonus(MaterialTier.bronze)
95 127 );
96 128 });
129
130 test("normalizeEquipmentStatBonuses fills defaults and clamps", () =>
131 {
132 const defaults = defaultEquipmentStatBonuses();
133 const normalized = normalizeEquipmentStatBonuses({
134 metalArmour: {
135 chestplate: { bronze: { defence: -3 } }
136 },
137 unknownCategory: { x: 1 }
138 });
139 assert.equal(normalized.metalArmour.chestplate.bronze.defence, 0);
140 assert.equal(normalized.metalArmour.greaves.bronze.defence, defaults.metalArmour.greaves.bronze.defence);
141 assert.equal(normalized.unknownCategory, undefined);
142 });
143
144 test("diffEquipmentStatBonuses reports skill changes", () =>
145 {
146 const prev = defaultEquipmentStatBonuses();
147 const next = normalizeEquipmentStatBonuses({
148 ...prev,
149 metalArmour: {
150 ...prev.metalArmour,
151 chestplate: {
152 ...prev.metalArmour.chestplate,
153 bronze: { defence: 9 }
154 }
155 }
156 });
157 const bullets = diffEquipmentStatBonuses(prev, next, (id) => itemDefinition(id)?.displayName ?? null);
158 assert.ok(bullets.some((line) => line.includes("defence") && line.includes("9")));
159 });
160
161 test("bonusForEquippedItem returns null for tools", () =>
162 {
163 assert.equal(bonusForEquippedItem(itemDefinition(CraftingItemId.bronzePickaxe)), null);
164 });
@@ -2,7 +2,9 @@ import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
3import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
4import { ArmourItemId } from "../../shared/definitions/armourItems.js";
4import { ArmourItemId } from "../../shared/definitions/armourItems.js";
5import { MaterialTier, tierStatBonus, tierMinSkillLevel } from "../../shared/definitions/materialTiers.js";
5import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
6import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
7import { MaterialTier, WoodTier, tierStatBonus, tierMinSkillLevel } from "../../shared/definitions/materialTiers.js";
6import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
8import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
7import { SkillId } from "../../shared/definitions/skills.js";
9import { SkillId } from "../../shared/definitions/skills.js";
8import { normalizePlayerSkills } from "../../shared/skills/state.js";
10import { normalizePlayerSkills } from "../../shared/skills/state.js";
@@ -13,6 +15,13 @@ import {
13 equipmentBonusesFromSlots
15 equipmentBonusesFromSlots
14} from "../../shared/equipment/stats.js";
16} from "../../shared/equipment/stats.js";
15import { emptyEquipment } from "../../shared/items/inventory.js";
17import { emptyEquipment } from "../../shared/items/inventory.js";
18import {
19 assertAllBonusGearCategorized,
20 defaultEquipmentStatBonuses,
21 normalizeEquipmentStatBonuses,
22 bonusForEquippedItem,
23 diffEquipmentStatBonuses
24} from "../../shared/definitions/equipmentStatCategories.js";
16
25
17test("tier stat bonuses scale by material", () =>
26test("tier stat bonuses scale by material", () =>
18{
27{
@@ -21,6 +30,12 @@ test("tier stat bonuses scale by material", () =>
21 assert.ok(tierStatBonus(MaterialTier.orichalcum) > tierStatBonus(MaterialTier.mithril));
30 assert.ok(tierStatBonus(MaterialTier.orichalcum) > tierStatBonus(MaterialTier.mithril));
22});
31});
23
32
33test("every bonus-gear item is categorized exactly once", () =>
34{
35 const result = assertAllBonusGearCategorized();
36 assert.equal(result.ok, true, JSON.stringify(result));
37});
38
24test("equipped weapons and armour add effective combat stats", () =>
39test("equipped weapons and armour add effective combat stats", () =>
25{
40{
26 const skills = normalizePlayerSkills(null);
41 const skills = normalizePlayerSkills(null);
@@ -30,14 +45,32 @@ test("equipped weapons and armour add effective combat stats", () =>
30 chest: { itemId: ItemId.clothShirt, quantity: 1 }
45 chest: { itemId: ItemId.clothShirt, quantity: 1 }
31 };
46 };
32 const bonuses = equipmentBonusesFromSlots(slots);
47 const bonuses = equipmentBonusesFromSlots(slots);
33 assert.equal(bonuses[SkillId.strength], tierStatBonus(MaterialTier.bronze));
48 assert.equal(bonuses[SkillId.strength], tierStatBonus(WoodTier.pine));
34 assert.equal(bonuses[SkillId.defence], tierStatBonus(MaterialTier.bronze));
49 assert.equal(bonuses[SkillId.defence], 1);
35 assert.equal(
50 assert.equal(
36 effectiveSkillLevel(skills, SkillId.strength, bonuses),
51 effectiveSkillLevel(skills, SkillId.strength, bonuses),
37 1 + tierStatBonus(MaterialTier.bronze)
52 1 + tierStatBonus(WoodTier.pine)
38 );
53 );
39});
54});
40
55
56test("leather shoes grant independent agility and defence from settings", () =>
57{
58 const settings = normalizeEquipmentStatBonuses({
59 leatherArmour: {
60 shoes: {
61 softLeather: { agility: 3, defence: 1 }
62 }
63 }
64 });
65 const slots = {
66 ...emptyEquipment().slots,
67 boots: { itemId: LeatherItemId.leatherShoes, quantity: 1 }
68 };
69 const bonuses = equipmentBonusesFromSlots(slots, { equipmentStatBonuses: settings });
70 assert.equal(bonuses[SkillId.agility], 3);
71 assert.equal(bonuses[SkillId.defence], 1);
72});
73
41test("bronze gear equips at level 1", () =>
74test("bronze gear equips at level 1", () =>
42{
75{
43 const skills = normalizePlayerSkills(null);
76 const skills = normalizePlayerSkills(null);
@@ -68,9 +101,8 @@ test("full helm grants +1 defence bonus and +1 equip level", () =>
68 const horned = itemDefinition(ArmourItemId.bronzeHornedHelm);
101 const horned = itemDefinition(ArmourItemId.bronzeHornedHelm);
69 const skills = normalizePlayerSkills(null);
102 const skills = normalizePlayerSkills(null);
70
103
71 assert.equal(helmet.equipment.bonus, undefined);
104 assert.equal(fullHelm.equipment.bonus, undefined);
72 assert.equal(fullHelm.equipment.bonus, tierStatBonus(MaterialTier.bronze) + 1);
105 assert.equal(fullHelm.equipment.minSkillLevel, tierMinSkillLevel(MaterialTier.bronze) + 1);
73 assert.equal(horned.equipment.bonus, undefined);
74
106
75 assert.equal(canEquipItem(skills, helmet).ok, true);
107 assert.equal(canEquipItem(skills, helmet).ok, true);
76 assert.equal(canEquipItem(skills, fullHelm).ok, false);
108 assert.equal(canEquipItem(skills, fullHelm).ok, false);
@@ -94,3 +126,39 @@ test("full helm grants +1 defence bonus and +1 equip level", () =>
94 tierStatBonus(MaterialTier.bronze)
126 tierStatBonus(MaterialTier.bronze)
95 );
127 );
96});
128});
129
130test("normalizeEquipmentStatBonuses fills defaults and clamps", () =>
131{
132 const defaults = defaultEquipmentStatBonuses();
133 const normalized = normalizeEquipmentStatBonuses({
134 metalArmour: {
135 chestplate: { bronze: { defence: -3 } }
136 },
137 unknownCategory: { x: 1 }
138 });
139 assert.equal(normalized.metalArmour.chestplate.bronze.defence, 0);
140 assert.equal(normalized.metalArmour.greaves.bronze.defence, defaults.metalArmour.greaves.bronze.defence);
141 assert.equal(normalized.unknownCategory, undefined);
142});
143
144test("diffEquipmentStatBonuses reports skill changes", () =>
145{
146 const prev = defaultEquipmentStatBonuses();
147 const next = normalizeEquipmentStatBonuses({
148 ...prev,
149 metalArmour: {
150 ...prev.metalArmour,
151 chestplate: {
152 ...prev.metalArmour.chestplate,
153 bronze: { defence: 9 }
154 }
155 }
156 });
157 const bullets = diffEquipmentStatBonuses(prev, next, (id) => itemDefinition(id)?.displayName ?? null);
158 assert.ok(bullets.some((line) => line.includes("defence") && line.includes("9")));
159});
160
161test("bonusForEquippedItem returns null for tools", () =>
162{
163 assert.equal(bonusForEquippedItem(itemDefinition(CraftingItemId.bronzePickaxe)), null);
164});
server/tests/fillCharge.test.js +1 −1
@@ -34,7 +34,7 @@ function potionStack (fillLevel, quantity = 1)
34 34 instance: potionItemInstance({
35 35 potionKey: "lesserHealthTonic",
36 36 displayName: "Lesser health tonic",
37 color: { r: 0.35, g: 0.78, b: 0.42 },
37 color: { r: 0.95, g: 0.38, b: 0.32 },
38 38 fillLevel,
39 39 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
40 40 effectKey: "health-regen"
@@ -34,7 +34,7 @@ function potionStack (fillLevel, quantity = 1)
34 instance: potionItemInstance({
34 instance: potionItemInstance({
35 potionKey: "lesserHealthTonic",
35 potionKey: "lesserHealthTonic",
36 displayName: "Lesser health tonic",
36 displayName: "Lesser health tonic",
37 color: { r: 0.35, g: 0.78, b: 0.42 },
37 color: { r: 0.95, g: 0.38, b: 0.32 },
38 fillLevel,
38 fillLevel,
39 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
39 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
40 effectKey: "health-regen"
40 effectKey: "health-regen"
server/tests/tint.test.js +14 −0
@@ -91,6 +91,20 @@ test("dual-channel arrow tints shaft red and tip blue, leaves white fletching",
91 91 assert.equal(resolveItemTint({ itemId: RangedItemId.bronzeArrow }), null);
92 92 });
93 93
94 test("hafted tools dual-tint wood handle and metal head", () =>
95 {
96 const pickaxe = resolveItemDualTint({ itemId: ItemId.bronzePickaxe });
97 assert.ok(pickaxe?.shaft);
98 assert.ok(pickaxe?.tip);
99 assert.deepEqual(pickaxe.shaft, tierTintColor("pine"));
100 assert.deepEqual(pickaxe.tip, tierTintColor(MaterialTier.bronze));
101 assert.equal(resolveItemTint({ itemId: ItemId.bronzePickaxe }), null);
102
103 const ironAxe = resolveItemDualTint({ itemId: ItemId.ironAxe });
104 assert.deepEqual(ironAxe.shaft, tierTintColor("birch"));
105 assert.deepEqual(ironAxe.tip, tierTintColor(MaterialTier.iron));
106 });
107
94 108 test("material tint hex converts to 0-1 rgb at load", () =>
95 109 {
96 110 assert.deepEqual(MATERIAL_TINT_HEX[MaterialTier.bronze], rgb(184, 122, 71));
@@ -91,6 +91,20 @@ test("dual-channel arrow tints shaft red and tip blue, leaves white fletching",
91 assert.equal(resolveItemTint({ itemId: RangedItemId.bronzeArrow }), null);
91 assert.equal(resolveItemTint({ itemId: RangedItemId.bronzeArrow }), null);
92});
92});
93
93
94test("hafted tools dual-tint wood handle and metal head", () =>
95{
96 const pickaxe = resolveItemDualTint({ itemId: ItemId.bronzePickaxe });
97 assert.ok(pickaxe?.shaft);
98 assert.ok(pickaxe?.tip);
99 assert.deepEqual(pickaxe.shaft, tierTintColor("pine"));
100 assert.deepEqual(pickaxe.tip, tierTintColor(MaterialTier.bronze));
101 assert.equal(resolveItemTint({ itemId: ItemId.bronzePickaxe }), null);
102
103 const ironAxe = resolveItemDualTint({ itemId: ItemId.ironAxe });
104 assert.deepEqual(ironAxe.shaft, tierTintColor("birch"));
105 assert.deepEqual(ironAxe.tip, tierTintColor(MaterialTier.iron));
106});
107
94test("material tint hex converts to 0-1 rgb at load", () =>
108test("material tint hex converts to 0-1 rgb at load", () =>
95{
109{
96 assert.deepEqual(MATERIAL_TINT_HEX[MaterialTier.bronze], rgb(184, 122, 71));
110 assert.deepEqual(MATERIAL_TINT_HEX[MaterialTier.bronze], rgb(184, 122, 71));
shared/crafting/stationRecipes.js +4 −8
@@ -44,6 +44,8 @@ function yarnSpinRecipe (clothTier)
44 44 {
45 45 return Object.freeze({
46 46 recipeId: `yarn-${clothTier}`,
47 craftGroup: "yarn",
48 craftGroupLabel: "Yarn",
47 49 stationId: CraftingStationId.spinningWheel,
48 50 output: { itemId: yarnItemId(clothTier), quantity: 1 },
49 51 inputs: [{ itemId: rawClothItemId(clothTier), quantity: 1 }],
@@ -57,6 +59,8 @@ function clothWeaveRecipe (clothTier)
57 59 {
58 60 return Object.freeze({
59 61 recipeId: `cloth-${clothTier}`,
62 craftGroup: "cloth",
63 craftGroupLabel: "Cloth",
60 64 stationId: CraftingStationId.loom,
61 65 output: { itemId: wovenClothItemId(clothTier), quantity: 1 },
62 66 inputs: [{ itemId: yarnItemId(clothTier), quantity: 1 }],
@@ -82,14 +86,6 @@ const TAILOR_TEMPLATE_RECIPES = Object.values(CLOTHING_TEMPLATES).map((template)
82 86
83 87 /** @type {ReadonlyArray<object>} */
84 88 export const CRAFT_RECIPES = Object.freeze([
85 Object.freeze({
86 recipeId: "dev-stick-from-paper",
87 stationId: CraftingStationId.craftingBench,
88 output: { itemId: ItemId.stick, quantity: 1 },
89 inputs: [{ itemId: ItemId.paper, quantity: 2 }],
90 minSkillLevel: 1
91 }),
92
93 89 smelt(MaterialTier.bronze, "smelt-bronze", [
94 90 { itemId: CraftingItemId.tinOre, quantity: 1 },
95 91 { itemId: CraftingItemId.copperOre, quantity: 1 }
@@ -44,6 +44,8 @@ function yarnSpinRecipe (clothTier)
44{
44{
45 return Object.freeze({
45 return Object.freeze({
46 recipeId: `yarn-${clothTier}`,
46 recipeId: `yarn-${clothTier}`,
47 craftGroup: "yarn",
48 craftGroupLabel: "Yarn",
47 stationId: CraftingStationId.spinningWheel,
49 stationId: CraftingStationId.spinningWheel,
48 output: { itemId: yarnItemId(clothTier), quantity: 1 },
50 output: { itemId: yarnItemId(clothTier), quantity: 1 },
49 inputs: [{ itemId: rawClothItemId(clothTier), quantity: 1 }],
51 inputs: [{ itemId: rawClothItemId(clothTier), quantity: 1 }],
@@ -57,6 +59,8 @@ function clothWeaveRecipe (clothTier)
57{
59{
58 return Object.freeze({
60 return Object.freeze({
59 recipeId: `cloth-${clothTier}`,
61 recipeId: `cloth-${clothTier}`,
62 craftGroup: "cloth",
63 craftGroupLabel: "Cloth",
60 stationId: CraftingStationId.loom,
64 stationId: CraftingStationId.loom,
61 output: { itemId: wovenClothItemId(clothTier), quantity: 1 },
65 output: { itemId: wovenClothItemId(clothTier), quantity: 1 },
62 inputs: [{ itemId: yarnItemId(clothTier), quantity: 1 }],
66 inputs: [{ itemId: yarnItemId(clothTier), quantity: 1 }],
@@ -82,14 +86,6 @@ const TAILOR_TEMPLATE_RECIPES = Object.values(CLOTHING_TEMPLATES).map((template)
82
86
83/** @type {ReadonlyArray<object>} */
87/** @type {ReadonlyArray<object>} */
84export const CRAFT_RECIPES = Object.freeze([
88export const CRAFT_RECIPES = Object.freeze([
85 Object.freeze({
86 recipeId: "dev-stick-from-paper",
87 stationId: CraftingStationId.craftingBench,
88 output: { itemId: ItemId.stick, quantity: 1 },
89 inputs: [{ itemId: ItemId.paper, quantity: 2 }],
90 minSkillLevel: 1
91 }),
92
93 smelt(MaterialTier.bronze, "smelt-bronze", [
89 smelt(MaterialTier.bronze, "smelt-bronze", [
94 { itemId: CraftingItemId.tinOre, quantity: 1 },
90 { itemId: CraftingItemId.tinOre, quantity: 1 },
95 { itemId: CraftingItemId.copperOre, quantity: 1 }
91 { itemId: CraftingItemId.copperOre, quantity: 1 }
shared/crafting/tierRecipes.js +46 −4
@@ -2,11 +2,13 @@ import { CraftingStationId } from "../definitions/craftingStations.js";
2 2 import { ItemId } from "../definitions/items.js";
3 3 import { ItemFamilyId } from "../definitions/tierFamilies.js";
4 4 import { familyItemId } from "../definitions/familyItemIds.js";
5 import { WoodItemId } from "../definitions/woodItems.js";
5 6 import {
6 7 WOOD_TIER_ORDER,
7 8 MATERIAL_TIER_ORDER,
8 9 CLOTH_TIER_ORDER,
9 10 MATERIAL_DISPLAY_NAME,
11 WoodTier,
10 12 woodTierForMetal,
11 13 clothTierForWood,
12 14 tierSmeltSkillLevel,
@@ -70,6 +72,41 @@ function handleRecipes ()
70 72 }));
71 73 }
72 74
75 function stickAndQuarterstaffRecipes ()
76 {
77 const recipes = [
78 Object.freeze({
79 recipeId: "stick-pine",
80 craftGroup: "stick",
81 craftGroupLabel: "Stick",
82 stationId: CraftingStationId.woodworkingBench,
83 output: { itemId: ItemId.stick, quantity: 1 },
84 inputs: [{ itemId: WoodItemId.pineLog, quantity: 1 }],
85 minSkillLevel: 1,
86 skillId: "crafting",
87 xpMaterial: WoodTier.pine
88 })
89 ];
90 for (const woodTier of WOOD_TIER_ORDER)
91 {
92 if (woodTier === WoodTier.pine)
93 { continue; }
94 recipes.push(tierRecipe({
95 recipeId: `quarterstaff-${woodTier}`,
96 craftGroup: "quarterstaff",
97 craftGroupLabel: "Quarterstaff",
98 stationId: CraftingStationId.woodworkingBench,
99 outputFamily: ItemFamilyId.quarterstaff,
100 outputTier: woodTier,
101 inputs: [{ itemId: familyItemId(ItemFamilyId.log, woodTier), quantity: 1 }],
102 minSkillLevel: tierCraftSkillLevel(woodTier),
103 skillId: "crafting",
104 xpMaterial: woodTier
105 }));
106 }
107 return recipes;
108 }
109
73 110 function pickaxeHeadRecipes ()
74 111 {
75 112 return MATERIAL_TIER_ORDER.map((metalTier) => tierRecipe({
@@ -93,6 +130,8 @@ function pickaxeAssembleRecipes ()
93 130 const woodTier = woodTierForMetal(metalTier);
94 131 return tierRecipe({
95 132 recipeId: `pickaxe-${metalTier}`,
133 craftGroup: "pickaxe",
134 craftGroupLabel: "Pickaxe",
96 135 stationId: CraftingStationId.craftingBench,
97 136 outputFamily: ItemFamilyId.pickaxe,
98 137 outputTier: metalTier,
@@ -130,6 +169,8 @@ function axeAssembleRecipes ()
130 169 const woodTier = woodTierForMetal(metalTier);
131 170 return tierRecipe({
132 171 recipeId: `axe-${metalTier}`,
172 craftGroup: "axe",
173 craftGroupLabel: "Axe",
133 174 stationId: CraftingStationId.craftingBench,
134 175 outputFamily: ItemFamilyId.axe,
135 176 outputTier: metalTier,
@@ -201,8 +242,8 @@ function arrowAssembleRecipes ()
201 242 const woodTier = woodTierForMetal(metalTier);
202 243 return tierRecipe({
203 244 recipeId: `arrow-${metalTier}`,
204 craftGroup: `arrow-${metalTier}`,
205 craftGroupLabel: `${MATERIAL_DISPLAY_NAME[metalTier] ?? metalTier} arrow`,
245 craftGroup: "arrow",
246 craftGroupLabel: "Arrow",
206 247 stationId: CraftingStationId.craftingBench,
207 248 outputFamily: ItemFamilyId.arrow,
208 249 outputTier: metalTier,
@@ -257,8 +298,8 @@ function bowAssembleRecipes ()
257 298 const clothTier = clothTierForWood(woodTier);
258 299 return tierRecipe({
259 300 recipeId: `bow-${woodTier}`,
260 craftGroup: `bow-${woodTier}`,
261 craftGroupLabel: `${MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier} bow`,
301 craftGroup: "bow",
302 craftGroupLabel: "Bow",
262 303 stationId: CraftingStationId.craftingBench,
263 304 outputFamily: ItemFamilyId.bow,
264 305 outputTier: woodTier,
@@ -299,6 +340,7 @@ function armourRecipes ()
299 340 /** All recipes driven by tier families (tools, wood/metal intermediates, ranged). */
300 341 export const TIER_FAMILY_RECIPES = Object.freeze([
301 342 ...handleRecipes(),
343 ...stickAndQuarterstaffRecipes(),
302 344 ...pickaxeHeadRecipes(),
303 345 ...pickaxeAssembleRecipes(),
304 346 ...axeHeadRecipes(),
@@ -2,11 +2,13 @@ import { CraftingStationId } from "../definitions/craftingStations.js";
2import { ItemId } from "../definitions/items.js";
2import { ItemId } from "../definitions/items.js";
3import { ItemFamilyId } from "../definitions/tierFamilies.js";
3import { ItemFamilyId } from "../definitions/tierFamilies.js";
4import { familyItemId } from "../definitions/familyItemIds.js";
4import { familyItemId } from "../definitions/familyItemIds.js";
5import { WoodItemId } from "../definitions/woodItems.js";
5import {
6import {
6 WOOD_TIER_ORDER,
7 WOOD_TIER_ORDER,
7 MATERIAL_TIER_ORDER,
8 MATERIAL_TIER_ORDER,
8 CLOTH_TIER_ORDER,
9 CLOTH_TIER_ORDER,
9 MATERIAL_DISPLAY_NAME,
10 MATERIAL_DISPLAY_NAME,
11 WoodTier,
10 woodTierForMetal,
12 woodTierForMetal,
11 clothTierForWood,
13 clothTierForWood,
12 tierSmeltSkillLevel,
14 tierSmeltSkillLevel,
@@ -70,6 +72,41 @@ function handleRecipes ()
70 }));
72 }));
71}
73}
72
74
75function stickAndQuarterstaffRecipes ()
76{
77 const recipes = [
78 Object.freeze({
79 recipeId: "stick-pine",
80 craftGroup: "stick",
81 craftGroupLabel: "Stick",
82 stationId: CraftingStationId.woodworkingBench,
83 output: { itemId: ItemId.stick, quantity: 1 },
84 inputs: [{ itemId: WoodItemId.pineLog, quantity: 1 }],
85 minSkillLevel: 1,
86 skillId: "crafting",
87 xpMaterial: WoodTier.pine
88 })
89 ];
90 for (const woodTier of WOOD_TIER_ORDER)
91 {
92 if (woodTier === WoodTier.pine)
93 { continue; }
94 recipes.push(tierRecipe({
95 recipeId: `quarterstaff-${woodTier}`,
96 craftGroup: "quarterstaff",
97 craftGroupLabel: "Quarterstaff",
98 stationId: CraftingStationId.woodworkingBench,
99 outputFamily: ItemFamilyId.quarterstaff,
100 outputTier: woodTier,
101 inputs: [{ itemId: familyItemId(ItemFamilyId.log, woodTier), quantity: 1 }],
102 minSkillLevel: tierCraftSkillLevel(woodTier),
103 skillId: "crafting",
104 xpMaterial: woodTier
105 }));
106 }
107 return recipes;
108}
109
73function pickaxeHeadRecipes ()
110function pickaxeHeadRecipes ()
74{
111{
75 return MATERIAL_TIER_ORDER.map((metalTier) => tierRecipe({
112 return MATERIAL_TIER_ORDER.map((metalTier) => tierRecipe({
@@ -93,6 +130,8 @@ function pickaxeAssembleRecipes ()
93 const woodTier = woodTierForMetal(metalTier);
130 const woodTier = woodTierForMetal(metalTier);
94 return tierRecipe({
131 return tierRecipe({
95 recipeId: `pickaxe-${metalTier}`,
132 recipeId: `pickaxe-${metalTier}`,
133 craftGroup: "pickaxe",
134 craftGroupLabel: "Pickaxe",
96 stationId: CraftingStationId.craftingBench,
135 stationId: CraftingStationId.craftingBench,
97 outputFamily: ItemFamilyId.pickaxe,
136 outputFamily: ItemFamilyId.pickaxe,
98 outputTier: metalTier,
137 outputTier: metalTier,
@@ -130,6 +169,8 @@ function axeAssembleRecipes ()
130 const woodTier = woodTierForMetal(metalTier);
169 const woodTier = woodTierForMetal(metalTier);
131 return tierRecipe({
170 return tierRecipe({
132 recipeId: `axe-${metalTier}`,
171 recipeId: `axe-${metalTier}`,
172 craftGroup: "axe",
173 craftGroupLabel: "Axe",
133 stationId: CraftingStationId.craftingBench,
174 stationId: CraftingStationId.craftingBench,
134 outputFamily: ItemFamilyId.axe,
175 outputFamily: ItemFamilyId.axe,
135 outputTier: metalTier,
176 outputTier: metalTier,
@@ -201,8 +242,8 @@ function arrowAssembleRecipes ()
201 const woodTier = woodTierForMetal(metalTier);
242 const woodTier = woodTierForMetal(metalTier);
202 return tierRecipe({
243 return tierRecipe({
203 recipeId: `arrow-${metalTier}`,
244 recipeId: `arrow-${metalTier}`,
204 craftGroup: `arrow-${metalTier}`,
245 craftGroup: "arrow",
205 craftGroupLabel: `${MATERIAL_DISPLAY_NAME[metalTier] ?? metalTier} arrow`,
246 craftGroupLabel: "Arrow",
206 stationId: CraftingStationId.craftingBench,
247 stationId: CraftingStationId.craftingBench,
207 outputFamily: ItemFamilyId.arrow,
248 outputFamily: ItemFamilyId.arrow,
208 outputTier: metalTier,
249 outputTier: metalTier,
@@ -257,8 +298,8 @@ function bowAssembleRecipes ()
257 const clothTier = clothTierForWood(woodTier);
298 const clothTier = clothTierForWood(woodTier);
258 return tierRecipe({
299 return tierRecipe({
259 recipeId: `bow-${woodTier}`,
300 recipeId: `bow-${woodTier}`,
260 craftGroup: `bow-${woodTier}`,
301 craftGroup: "bow",
261 craftGroupLabel: `${MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier} bow`,
302 craftGroupLabel: "Bow",
262 stationId: CraftingStationId.craftingBench,
303 stationId: CraftingStationId.craftingBench,
263 outputFamily: ItemFamilyId.bow,
304 outputFamily: ItemFamilyId.bow,
264 outputTier: woodTier,
305 outputTier: woodTier,
@@ -299,6 +340,7 @@ function armourRecipes ()
299/** All recipes driven by tier families (tools, wood/metal intermediates, ranged). */
340/** All recipes driven by tier families (tools, wood/metal intermediates, ranged). */
300export const TIER_FAMILY_RECIPES = Object.freeze([
341export const TIER_FAMILY_RECIPES = Object.freeze([
301 ...handleRecipes(),
342 ...handleRecipes(),
343 ...stickAndQuarterstaffRecipes(),
302 ...pickaxeHeadRecipes(),
344 ...pickaxeHeadRecipes(),
303 ...pickaxeAssembleRecipes(),
345 ...pickaxeAssembleRecipes(),
304 ...axeHeadRecipes(),
346 ...axeHeadRecipes(),
shared/definitions/alchemy.js +1 −1
@@ -35,7 +35,7 @@ export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
35 35 potionKey: "lesserHealthTonic",
36 36 displayName: "Lesser health tonic",
37 37 minAlchemyLevel: 1,
38 color: Object.freeze({ r: 0.35, g: 0.78, b: 0.42 }),
38 color: Object.freeze({ r: 0.95, g: 0.38, b: 0.32 }),
39 39 fillLevel: 4,
40 40 ingredients: Object.freeze([
41 41 Object.freeze({ key: "thyme", quantity: 1 }),
@@ -35,7 +35,7 @@ export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
35 potionKey: "lesserHealthTonic",
35 potionKey: "lesserHealthTonic",
36 displayName: "Lesser health tonic",
36 displayName: "Lesser health tonic",
37 minAlchemyLevel: 1,
37 minAlchemyLevel: 1,
38 color: Object.freeze({ r: 0.35, g: 0.78, b: 0.42 }),
38 color: Object.freeze({ r: 0.95, g: 0.38, b: 0.32 }),
39 fillLevel: 4,
39 fillLevel: 4,
40 ingredients: Object.freeze([
40 ingredients: Object.freeze([
41 Object.freeze({ key: "thyme", quantity: 1 }),
41 Object.freeze({ key: "thyme", quantity: 1 }),
shared/definitions/armourItems.js +1 −3
@@ -3,8 +3,7 @@ import {
3 3 MaterialTier,
4 4 MATERIAL_TIER_ORDER,
5 5 MATERIAL_DISPLAY_NAME,
6 tierMinSkillLevel,
7 tierStatBonus
6 tierMinSkillLevel
8 7 } from "./materialTiers.js";
9 8 import { EquipmentKind } from "./equipmentKinds.js";
10 9 import { equipImageName } from "./tileSprites.js";
@@ -129,7 +128,6 @@ function armourDef (itemId, tier, piece)
129 128 };
130 129 if (piece.fullHelm)
131 130 {
132 equipment.bonus = tierStatBonus(tier) + 1;
133 131 equipment.minSkillLevel = tierMinSkillLevel(tier) + 1;
134 132 }
135 133 return Object.freeze({
@@ -3,8 +3,7 @@ import {
3 MaterialTier,
3 MaterialTier,
4 MATERIAL_TIER_ORDER,
4 MATERIAL_TIER_ORDER,
5 MATERIAL_DISPLAY_NAME,
5 MATERIAL_DISPLAY_NAME,
6 tierMinSkillLevel,
6 tierMinSkillLevel
7 tierStatBonus
8} from "./materialTiers.js";
7} from "./materialTiers.js";
9import { EquipmentKind } from "./equipmentKinds.js";
8import { EquipmentKind } from "./equipmentKinds.js";
10import { equipImageName } from "./tileSprites.js";
9import { equipImageName } from "./tileSprites.js";
@@ -129,7 +128,6 @@ function armourDef (itemId, tier, piece)
129 };
128 };
130 if (piece.fullHelm)
129 if (piece.fullHelm)
131 {
130 {
132 equipment.bonus = tierStatBonus(tier) + 1;
133 equipment.minSkillLevel = tierMinSkillLevel(tier) + 1;
131 equipment.minSkillLevel = tierMinSkillLevel(tier) + 1;
134 }
132 }
135 return Object.freeze({
133 return Object.freeze({
shared/definitions/equipmentStatCategories.js added +564 −0
@@ -0,0 +1,564 @@
1 import { SkillId } from "./skills.js";
2 import { EquipmentKind } from "./equipmentKinds.js";
3 import {
4 MATERIAL_TIER_ORDER,
5 WOOD_TIER_ORDER,
6 CLOTH_TIER_ORDER,
7 LEATHER_TIER_ORDER,
8 MATERIAL_DISPLAY_NAME,
9 CLOTH_DISPLAY_NAME,
10 LEATHER_DISPLAY_NAME,
11 WoodTier,
12 tierStatBonus
13 } from "./materialTiers.js";
14 import { ARMOUR_CRAFT_PIECES, armourItemIdForTier } from "./armourItems.js";
15 import { sweaterItemId } from "./clothItems.js";
16 import { LeatherItemId } from "./leatherItems.js";
17 import { ItemId, itemDefinition, ITEM_DEFINITIONS } from "./items.js";
18 import { quarterstaffItemIdForWood } from "./woodItems.js";
19 import { arrowItemId, bowItemId } from "./rangedItems.js";
20
21 /** Tier key for non-tiered singleton rows (shorts, cloth shirt, …). */
22 export const SINGLETON_TIER_KEY = "_";
23
24 export const EquipmentStatCategoryId = Object.freeze({
25 metalArmour: "metalArmour",
26 leatherArmour: "leatherArmour",
27 meleeWeapons: "meleeWeapons",
28 rangedWeapons: "rangedWeapons",
29 magicStaves: "magicStaves",
30 wizardArmour: "wizardArmour",
31 clothing: "clothing"
32 });
33
34 /**
35 * Equipment kinds that grant worn combat/stat bonuses and must appear in a category.
36 * Tools / lantern are excluded.
37 */
38 export const BONUS_EQUIPMENT_KINDS = Object.freeze(new Set([
39 EquipmentKind.metalWeapon,
40 EquipmentKind.clubWeapon,
41 EquipmentKind.bow,
42 EquipmentKind.arrowAmmo,
43 EquipmentKind.metalArmour,
44 EquipmentKind.leatherArmour,
45 EquipmentKind.clothArmour,
46 EquipmentKind.wizardCloth,
47 EquipmentKind.shield,
48 EquipmentKind.staff
49 ]));
50
51 function woodDisplayName (tier)
52 {
53 return MATERIAL_DISPLAY_NAME[tier] ?? tier;
54 }
55
56 function metalDisplayName (tier)
57 {
58 return MATERIAL_DISPLAY_NAME[tier] ?? tier;
59 }
60
61 /**
62 * @typedef {object} EquipmentStatSection
63 * @property {string} [id]
64 * @property {string} [label]
65 * @property {ReadonlyArray<string>} tierOrder
66 * @property {(tier: string) => string} tierDisplayName
67 * @property {ReadonlyArray<object>} rows
68 */
69
70 /**
71 * @typedef {object} EquipmentStatCategory
72 * @property {string} id
73 * @property {string} label
74 * @property {ReadonlyArray<string>} stats
75 * @property {ReadonlyArray<EquipmentStatSection>} sections
76 */
77
78 /** @type {ReadonlyArray<EquipmentStatCategory>} */
79 export const EQUIPMENT_STAT_CATEGORIES = Object.freeze([
80 Object.freeze({
81 id: EquipmentStatCategoryId.metalArmour,
82 label: "Metal armour",
83 stats: Object.freeze([SkillId.defence]),
84 sections: Object.freeze([
85 Object.freeze({
86 id: "metal",
87 tierOrder: MATERIAL_TIER_ORDER,
88 tierDisplayName: metalDisplayName,
89 rows: Object.freeze(ARMOUR_CRAFT_PIECES.map((piece) => Object.freeze({
90 pieceKey: piece.suffix === "full-helm" ? "fullHelm"
91 : piece.suffix === "horned-helm" ? "hornedHelm"
92 : piece.suffix,
93 label: piece.label.charAt(0).toUpperCase() + piece.label.slice(1),
94 defaultBonusExtra: piece.fullHelm ? 1 : 0,
95 resolveItemId: (tier) => armourItemIdForTier(tier, piece.idKey)
96 })))
97 })
98 ])
99 }),
100 Object.freeze({
101 id: EquipmentStatCategoryId.leatherArmour,
102 label: "Leather armour",
103 stats: Object.freeze([SkillId.agility, SkillId.defence]),
104 sections: Object.freeze([
105 Object.freeze({
106 id: "leather",
107 tierOrder: LEATHER_TIER_ORDER,
108 tierDisplayName: (tier) => LEATHER_DISPLAY_NAME[tier] ?? tier,
109 rows: Object.freeze([
110 Object.freeze({
111 pieceKey: "shoes",
112 label: "Leather shoes",
113 defaultBonus: 0,
114 resolveItemId: (tier) => (tier === "softLeather" ? LeatherItemId.leatherShoes : null)
115 })
116 ])
117 })
118 ])
119 }),
120 Object.freeze({
121 id: EquipmentStatCategoryId.meleeWeapons,
122 label: "Melee weapons",
123 stats: Object.freeze([SkillId.strength]),
124 sections: Object.freeze([
125 Object.freeze({
126 id: "wood",
127 tierOrder: WOOD_TIER_ORDER,
128 tierDisplayName: woodDisplayName,
129 rows: Object.freeze([
130 Object.freeze({
131 pieceKey: "club",
132 label: "Stick / Quarterstaff",
133 resolveItemId: (tier) => (tier === WoodTier.pine
134 ? ItemId.stick
135 : quarterstaffItemIdForWood(tier))
136 })
137 ])
138 })
139 ])
140 }),
141 Object.freeze({
142 id: EquipmentStatCategoryId.rangedWeapons,
143 label: "Ranged weapons",
144 stats: Object.freeze([SkillId.dexterity]),
145 sections: Object.freeze([
146 Object.freeze({
147 id: "bows",
148 label: "Bows",
149 tierOrder: WOOD_TIER_ORDER,
150 tierDisplayName: woodDisplayName,
151 rows: Object.freeze([
152 Object.freeze({
153 pieceKey: "bow",
154 label: "Bow",
155 resolveItemId: (tier) => bowItemId(tier)
156 })
157 ])
158 }),
159 Object.freeze({
160 id: "arrows",
161 label: "Arrows",
162 tierOrder: MATERIAL_TIER_ORDER,
163 tierDisplayName: metalDisplayName,
164 rows: Object.freeze([
165 Object.freeze({
166 pieceKey: "arrow",
167 label: "Arrow",
168 resolveItemId: (tier) => arrowItemId(tier)
169 })
170 ])
171 })
172 ])
173 }),
174 Object.freeze({
175 id: EquipmentStatCategoryId.magicStaves,
176 label: "Magic staves",
177 stats: Object.freeze([SkillId.magic]),
178 sections: Object.freeze([
179 Object.freeze({
180 id: "wood",
181 tierOrder: WOOD_TIER_ORDER,
182 tierDisplayName: woodDisplayName,
183 rows: Object.freeze([])
184 })
185 ])
186 }),
187 Object.freeze({
188 id: EquipmentStatCategoryId.wizardArmour,
189 label: "Wizard armour",
190 stats: Object.freeze([SkillId.magic, SkillId.defence]),
191 sections: Object.freeze([
192 Object.freeze({
193 id: "cloth",
194 tierOrder: CLOTH_TIER_ORDER,
195 tierDisplayName: (tier) => CLOTH_DISPLAY_NAME[tier] ?? tier,
196 rows: Object.freeze([])
197 })
198 ])
199 }),
200 Object.freeze({
201 id: EquipmentStatCategoryId.clothing,
202 label: "Clothing",
203 stats: Object.freeze([SkillId.defence]),
204 sections: Object.freeze([
205 Object.freeze({
206 id: "sweaters",
207 label: "Sweaters",
208 tierOrder: CLOTH_TIER_ORDER,
209 tierDisplayName: (tier) => CLOTH_DISPLAY_NAME[tier] ?? tier,
210 rows: Object.freeze([
211 Object.freeze({
212 pieceKey: "sweater",
213 label: "Sweater",
214 defaultBonus: 0,
215 resolveItemId: (tier) => sweaterItemId(tier)
216 })
217 ])
218 }),
219 Object.freeze({
220 id: "singletons",
221 label: "Other",
222 tierOrder: Object.freeze([SINGLETON_TIER_KEY]),
223 tierDisplayName: () => "—",
224 rows: Object.freeze([
225 Object.freeze({
226 pieceKey: "shorts",
227 label: "Cloth shorts",
228 defaultBonus: 0,
229 singleton: true,
230 itemId: LeatherItemId.clothShorts,
231 resolveItemId: () => LeatherItemId.clothShorts
232 }),
233 Object.freeze({
234 pieceKey: "trousers",
235 label: "Cloth trousers",
236 defaultBonus: 0,
237 singleton: true,
238 itemId: LeatherItemId.clothTrousers,
239 resolveItemId: () => LeatherItemId.clothTrousers
240 }),
241 Object.freeze({
242 pieceKey: "clothShirt",
243 label: "Cloth shirt",
244 defaultBonus: 1,
245 singleton: true,
246 itemId: ItemId.clothShirt,
247 resolveItemId: () => ItemId.clothShirt
248 })
249 ])
250 })
251 ])
252 })
253 ]);
254
255 export function equipmentStatCategory (categoryId)
256 {
257 return EQUIPMENT_STAT_CATEGORIES.find((entry) => entry.id === categoryId) ?? null;
258 }
259
260 /** Flat list of all piece rows with category + section context. */
261 export function listEquipmentStatRows ()
262 {
263 const out = [];
264 for (const category of EQUIPMENT_STAT_CATEGORIES)
265 {
266 for (const section of category.sections)
267 {
268 for (const row of section.rows)
269 {
270 out.push({
271 categoryId: category.id,
272 stats: category.stats,
273 section,
274 row
275 });
276 }
277 }
278 }
279 return out;
280 }
281
282 /**
283 * Map itemId → { categoryId, pieceKey, stats, singleton, section }.
284 * Built lazily so item defs are fully loaded.
285 */
286 let _itemLookup = null;
287
288 export function equipmentStatLookupForItem (itemId)
289 {
290 if (!_itemLookup)
291 { _itemLookup = buildItemLookup(); }
292 return _itemLookup.get(itemId | 0) ?? null;
293 }
294
295 function buildItemLookup ()
296 {
297 const map = new Map();
298 for (const entry of listEquipmentStatRows())
299 {
300 const { categoryId, stats, section, row } = entry;
301 for (const tier of section.tierOrder)
302 {
303 const itemId = row.resolveItemId?.(tier) ?? (row.singleton ? row.itemId : null);
304 if (itemId == null)
305 { continue; }
306 map.set(itemId | 0, Object.freeze({
307 categoryId,
308 pieceKey: row.pieceKey,
309 stats,
310 singleton: !!row.singleton,
311 tierKey: row.singleton ? SINGLETON_TIER_KEY : tier
312 }));
313 }
314 }
315 return map;
316 }
317
318 /** Reset cached lookup (tests). */
319 export function clearEquipmentStatLookupCache ()
320 {
321 _itemLookup = null;
322 }
323
324 function emptyStatBag (stats)
325 {
326 const bag = {};
327 for (const skillId of stats)
328 { bag[skillId] = 0; }
329 return bag;
330 }
331
332 function defaultCellForRow (row, stats, tier)
333 {
334 const cell = emptyStatBag(stats);
335 const base = row.defaultBonus != null
336 ? Number(row.defaultBonus) || 0
337 : tierStatBonus(tier === SINGLETON_TIER_KEY ? null : tier);
338 const extra = Number(row.defaultBonusExtra) || 0;
339 const value = Math.max(0, Math.floor(base + extra));
340 for (const skillId of stats)
341 { cell[skillId] = value; }
342 return cell;
343 }
344
345 /** Seed defaults from current tier curve (full helm +1, cosmetics 0). */
346 export function defaultEquipmentStatBonuses ()
347 {
348 const out = {};
349 for (const category of EQUIPMENT_STAT_CATEGORIES)
350 {
351 const cat = {};
352 for (const section of category.sections)
353 {
354 for (const row of section.rows)
355 {
356 const byTier = {};
357 for (const tier of section.tierOrder)
358 {
359 const itemId = row.resolveItemId?.(tier) ?? (row.singleton ? row.itemId : null);
360 if (itemId == null && !row.singleton)
361 { continue; }
362 byTier[tier] = defaultCellForRow(row, category.stats, tier);
363 }
364 cat[row.pieceKey] = byTier;
365 }
366 }
367 out[category.id] = cat;
368 }
369 return out;
370 }
371
372 function coerceBonusInt (raw)
373 {
374 const n = Math.floor(Number(raw));
375 if (!Number.isFinite(n))
376 { return 0; }
377 return Math.max(0, Math.min(99, n));
378 }
379
380 /**
381 * Merge authored blob with defaults; drop unknown keys; fill missing cells.
382 * @param {object|null|undefined} raw
383 */
384 export function normalizeEquipmentStatBonuses (raw)
385 {
386 const defaults = defaultEquipmentStatBonuses();
387 const src = raw && typeof raw === "object" ? raw : {};
388 const out = {};
389 for (const category of EQUIPMENT_STAT_CATEGORIES)
390 {
391 const srcCat = src[category.id] && typeof src[category.id] === "object"
392 ? src[category.id]
393 : {};
394 const defCat = defaults[category.id] ?? {};
395 const cat = {};
396 for (const section of category.sections)
397 {
398 for (const row of section.rows)
399 {
400 const srcPiece = srcCat[row.pieceKey] && typeof srcCat[row.pieceKey] === "object"
401 ? srcCat[row.pieceKey]
402 : {};
403 const defPiece = defCat[row.pieceKey] ?? {};
404 const byTier = {};
405 for (const tier of section.tierOrder)
406 {
407 const itemId = row.resolveItemId?.(tier) ?? (row.singleton ? row.itemId : null);
408 if (itemId == null && !row.singleton)
409 { continue; }
410 const srcCell = srcPiece[tier] && typeof srcPiece[tier] === "object"
411 ? srcPiece[tier]
412 : null;
413 const defCell = defPiece[tier] ?? defaultCellForRow(row, category.stats, tier);
414 const cell = {};
415 for (const skillId of category.stats)
416 {
417 cell[skillId] = srcCell && Object.prototype.hasOwnProperty.call(srcCell, skillId)
418 ? coerceBonusInt(srcCell[skillId])
419 : coerceBonusInt(defCell[skillId]);
420 }
421 byTier[tier] = cell;
422 }
423 cat[row.pieceKey] = byTier;
424 }
425 }
426 out[category.id] = cat;
427 }
428 return out;
429 }
430
431 /**
432 * Resolve per-skill bonuses for one equipped item def.
433 * @returns {Record<string, number>|null}
434 */
435 export function bonusForEquippedItem (definition, settingsBonuses = null)
436 {
437 const equipment = definition?.equipment;
438 if (!equipment?.kind || !BONUS_EQUIPMENT_KINDS.has(equipment.kind))
439 { return null; }
440 const itemId = definition.itemId;
441 const lookup = equipmentStatLookupForItem(itemId);
442 if (!lookup)
443 { return null; }
444 const table = settingsBonuses && typeof settingsBonuses === "object"
445 ? settingsBonuses
446 : defaultEquipmentStatBonuses();
447 const piece = table[lookup.categoryId]?.[lookup.pieceKey];
448 if (!piece)
449 { return emptyStatBag(lookup.stats); }
450 const tierKey = lookup.singleton
451 ? SINGLETON_TIER_KEY
452 : (equipment.tier ?? definition.tier ?? lookup.tierKey);
453 const cell = piece[tierKey] ?? piece[lookup.tierKey];
454 if (!cell)
455 { return emptyStatBag(lookup.stats); }
456 const out = {};
457 for (const skillId of lookup.stats)
458 { out[skillId] = coerceBonusInt(cell[skillId]); }
459 return out;
460 }
461
462 /**
463 * Changelog bullets for equipmentStatBonuses edits.
464 * @param {(itemId: number) => string|null} [displayNameFor]
465 */
466 export function diffEquipmentStatBonuses (previous, next, displayNameFor = null)
467 {
468 const prev = normalizeEquipmentStatBonuses(previous);
469 const upcoming = normalizeEquipmentStatBonuses(next);
470 const bullets = [];
471 for (const category of EQUIPMENT_STAT_CATEGORIES)
472 {
473 for (const section of category.sections)
474 {
475 for (const row of section.rows)
476 {
477 for (const tier of section.tierOrder)
478 {
479 const from = prev[category.id]?.[row.pieceKey]?.[tier];
480 const to = upcoming[category.id]?.[row.pieceKey]?.[tier];
481 if (!from && !to)
482 { continue; }
483 for (const skillId of category.stats)
484 {
485 const a = coerceBonusInt(from?.[skillId]);
486 const b = coerceBonusInt(to?.[skillId]);
487 if (a === b)
488 { continue; }
489 const itemId = row.resolveItemId?.(tier) ?? row.itemId;
490 const name = (itemId != null && displayNameFor?.(itemId))
491 || `${row.label} (${section.tierDisplayName(tier)})`;
492 bullets.push(`${name} ${skillId} bonus changed from ${a} to ${b}.`);
493 }
494 }
495 }
496 }
497 }
498 return bullets;
499 }
500
501 export function equipmentStatBonusMapsEqual (a, b)
502 {
503 const left = normalizeEquipmentStatBonuses(a);
504 const right = normalizeEquipmentStatBonuses(b);
505 return JSON.stringify(left) === JSON.stringify(right);
506 }
507
508 /**
509 * Every equippable item with a bonus kind must appear in exactly one category row.
510 * @returns {{ ok: true } | { ok: false, missing: number[], duplicates: number[] }}
511 */
512 export function assertAllBonusGearCategorized ()
513 {
514 clearEquipmentStatLookupCache();
515 const seen = new Map();
516 const duplicates = [];
517 for (const entry of listEquipmentStatRows())
518 {
519 for (const tier of entry.section.tierOrder)
520 {
521 const itemId = entry.row.resolveItemId?.(tier) ?? entry.row.itemId;
522 if (itemId == null)
523 { continue; }
524 const id = itemId | 0;
525 if (seen.has(id))
526 { duplicates.push(id); }
527 else
528 { seen.set(id, entry); }
529 }
530 }
531 const missing = [];
532 for (const def of Object.values(ITEM_DEFINITIONS))
533 {
534 const kind = def?.equipment?.kind;
535 if (!kind || !BONUS_EQUIPMENT_KINDS.has(kind))
536 { continue; }
537 if (!seen.has(def.itemId | 0))
538 { missing.push(def.itemId | 0); }
539 }
540 if (missing.length || duplicates.length)
541 { return { ok: false, missing, duplicates }; }
542 return { ok: true };
543 }
544
545 /** Preview item id for a row at tier (editor icon). */
546 export function equipmentStatRowItemId (row, tier)
547 {
548 if (row.singleton)
549 { return row.itemId ?? row.resolveItemId?.(SINGLETON_TIER_KEY) ?? null; }
550 return row.resolveItemId?.(tier) ?? null;
551 }
552
553 export function equipmentStatRowDefaultTier (section, row)
554 {
555 for (const tier of section.tierOrder)
556 {
557 if (equipmentStatRowItemId(row, tier) != null)
558 { return tier; }
559 }
560 return section.tierOrder[0] ?? SINGLETON_TIER_KEY;
561 }
562
563 /** Display helper — re-export itemDefinition for callers that only import this module. */
564 export { itemDefinition };
@@ -0,0 +1,564 @@
1import { SkillId } from "./skills.js";
2import { EquipmentKind } from "./equipmentKinds.js";
3import {
4 MATERIAL_TIER_ORDER,
5 WOOD_TIER_ORDER,
6 CLOTH_TIER_ORDER,
7 LEATHER_TIER_ORDER,
8 MATERIAL_DISPLAY_NAME,
9 CLOTH_DISPLAY_NAME,
10 LEATHER_DISPLAY_NAME,
11 WoodTier,
12 tierStatBonus
13} from "./materialTiers.js";
14import { ARMOUR_CRAFT_PIECES, armourItemIdForTier } from "./armourItems.js";
15import { sweaterItemId } from "./clothItems.js";
16import { LeatherItemId } from "./leatherItems.js";
17import { ItemId, itemDefinition, ITEM_DEFINITIONS } from "./items.js";
18import { quarterstaffItemIdForWood } from "./woodItems.js";
19import { arrowItemId, bowItemId } from "./rangedItems.js";
20
21/** Tier key for non-tiered singleton rows (shorts, cloth shirt, …). */
22export const SINGLETON_TIER_KEY = "_";
23
24export const EquipmentStatCategoryId = Object.freeze({
25 metalArmour: "metalArmour",
26 leatherArmour: "leatherArmour",
27 meleeWeapons: "meleeWeapons",
28 rangedWeapons: "rangedWeapons",
29 magicStaves: "magicStaves",
30 wizardArmour: "wizardArmour",
31 clothing: "clothing"
32});
33
34/**
35 * Equipment kinds that grant worn combat/stat bonuses and must appear in a category.
36 * Tools / lantern are excluded.
37 */
38export const BONUS_EQUIPMENT_KINDS = Object.freeze(new Set([
39 EquipmentKind.metalWeapon,
40 EquipmentKind.clubWeapon,
41 EquipmentKind.bow,
42 EquipmentKind.arrowAmmo,
43 EquipmentKind.metalArmour,
44 EquipmentKind.leatherArmour,
45 EquipmentKind.clothArmour,
46 EquipmentKind.wizardCloth,
47 EquipmentKind.shield,
48 EquipmentKind.staff
49]));
50
51function woodDisplayName (tier)
52{
53 return MATERIAL_DISPLAY_NAME[tier] ?? tier;
54}
55
56function metalDisplayName (tier)
57{
58 return MATERIAL_DISPLAY_NAME[tier] ?? tier;
59}
60
61/**
62 * @typedef {object} EquipmentStatSection
63 * @property {string} [id]
64 * @property {string} [label]
65 * @property {ReadonlyArray<string>} tierOrder
66 * @property {(tier: string) => string} tierDisplayName
67 * @property {ReadonlyArray<object>} rows
68 */
69
70/**
71 * @typedef {object} EquipmentStatCategory
72 * @property {string} id
73 * @property {string} label
74 * @property {ReadonlyArray<string>} stats
75 * @property {ReadonlyArray<EquipmentStatSection>} sections
76 */
77
78/** @type {ReadonlyArray<EquipmentStatCategory>} */
79export const EQUIPMENT_STAT_CATEGORIES = Object.freeze([
80 Object.freeze({
81 id: EquipmentStatCategoryId.metalArmour,
82 label: "Metal armour",
83 stats: Object.freeze([SkillId.defence]),
84 sections: Object.freeze([
85 Object.freeze({
86 id: "metal",
87 tierOrder: MATERIAL_TIER_ORDER,
88 tierDisplayName: metalDisplayName,
89 rows: Object.freeze(ARMOUR_CRAFT_PIECES.map((piece) => Object.freeze({
90 pieceKey: piece.suffix === "full-helm" ? "fullHelm"
91 : piece.suffix === "horned-helm" ? "hornedHelm"
92 : piece.suffix,
93 label: piece.label.charAt(0).toUpperCase() + piece.label.slice(1),
94 defaultBonusExtra: piece.fullHelm ? 1 : 0,
95 resolveItemId: (tier) => armourItemIdForTier(tier, piece.idKey)
96 })))
97 })
98 ])
99 }),
100 Object.freeze({
101 id: EquipmentStatCategoryId.leatherArmour,
102 label: "Leather armour",
103 stats: Object.freeze([SkillId.agility, SkillId.defence]),
104 sections: Object.freeze([
105 Object.freeze({
106 id: "leather",
107 tierOrder: LEATHER_TIER_ORDER,
108 tierDisplayName: (tier) => LEATHER_DISPLAY_NAME[tier] ?? tier,
109 rows: Object.freeze([
110 Object.freeze({
111 pieceKey: "shoes",
112 label: "Leather shoes",
113 defaultBonus: 0,
114 resolveItemId: (tier) => (tier === "softLeather" ? LeatherItemId.leatherShoes : null)
115 })
116 ])
117 })
118 ])
119 }),
120 Object.freeze({
121 id: EquipmentStatCategoryId.meleeWeapons,
122 label: "Melee weapons",
123 stats: Object.freeze([SkillId.strength]),
124 sections: Object.freeze([
125 Object.freeze({
126 id: "wood",
127 tierOrder: WOOD_TIER_ORDER,
128 tierDisplayName: woodDisplayName,
129 rows: Object.freeze([
130 Object.freeze({
131 pieceKey: "club",
132 label: "Stick / Quarterstaff",
133 resolveItemId: (tier) => (tier === WoodTier.pine
134 ? ItemId.stick
135 : quarterstaffItemIdForWood(tier))
136 })
137 ])
138 })
139 ])
140 }),
141 Object.freeze({
142 id: EquipmentStatCategoryId.rangedWeapons,
143 label: "Ranged weapons",
144 stats: Object.freeze([SkillId.dexterity]),
145 sections: Object.freeze([
146 Object.freeze({
147 id: "bows",
148 label: "Bows",
149 tierOrder: WOOD_TIER_ORDER,
150 tierDisplayName: woodDisplayName,
151 rows: Object.freeze([
152 Object.freeze({
153 pieceKey: "bow",
154 label: "Bow",
155 resolveItemId: (tier) => bowItemId(tier)
156 })
157 ])
158 }),
159 Object.freeze({
160 id: "arrows",
161 label: "Arrows",
162 tierOrder: MATERIAL_TIER_ORDER,
163 tierDisplayName: metalDisplayName,
164 rows: Object.freeze([
165 Object.freeze({
166 pieceKey: "arrow",
167 label: "Arrow",
168 resolveItemId: (tier) => arrowItemId(tier)
169 })
170 ])
171 })
172 ])
173 }),
174 Object.freeze({
175 id: EquipmentStatCategoryId.magicStaves,
176 label: "Magic staves",
177 stats: Object.freeze([SkillId.magic]),
178 sections: Object.freeze([
179 Object.freeze({
180 id: "wood",
181 tierOrder: WOOD_TIER_ORDER,
182 tierDisplayName: woodDisplayName,
183 rows: Object.freeze([])
184 })
185 ])
186 }),
187 Object.freeze({
188 id: EquipmentStatCategoryId.wizardArmour,
189 label: "Wizard armour",
190 stats: Object.freeze([SkillId.magic, SkillId.defence]),
191 sections: Object.freeze([
192 Object.freeze({
193 id: "cloth",
194 tierOrder: CLOTH_TIER_ORDER,
195 tierDisplayName: (tier) => CLOTH_DISPLAY_NAME[tier] ?? tier,
196 rows: Object.freeze([])
197 })
198 ])
199 }),
200 Object.freeze({
201 id: EquipmentStatCategoryId.clothing,
202 label: "Clothing",
203 stats: Object.freeze([SkillId.defence]),
204 sections: Object.freeze([
205 Object.freeze({
206 id: "sweaters",
207 label: "Sweaters",
208 tierOrder: CLOTH_TIER_ORDER,
209 tierDisplayName: (tier) => CLOTH_DISPLAY_NAME[tier] ?? tier,
210 rows: Object.freeze([
211 Object.freeze({
212 pieceKey: "sweater",
213 label: "Sweater",
214 defaultBonus: 0,
215 resolveItemId: (tier) => sweaterItemId(tier)
216 })
217 ])
218 }),
219 Object.freeze({
220 id: "singletons",
221 label: "Other",
222 tierOrder: Object.freeze([SINGLETON_TIER_KEY]),
223 tierDisplayName: () => "—",
224 rows: Object.freeze([
225 Object.freeze({
226 pieceKey: "shorts",
227 label: "Cloth shorts",
228 defaultBonus: 0,
229 singleton: true,
230 itemId: LeatherItemId.clothShorts,
231 resolveItemId: () => LeatherItemId.clothShorts
232 }),
233 Object.freeze({
234 pieceKey: "trousers",
235 label: "Cloth trousers",
236 defaultBonus: 0,
237 singleton: true,
238 itemId: LeatherItemId.clothTrousers,
239 resolveItemId: () => LeatherItemId.clothTrousers
240 }),
241 Object.freeze({
242 pieceKey: "clothShirt",
243 label: "Cloth shirt",
244 defaultBonus: 1,
245 singleton: true,
246 itemId: ItemId.clothShirt,
247 resolveItemId: () => ItemId.clothShirt
248 })
249 ])
250 })
251 ])
252 })
253]);
254
255export function equipmentStatCategory (categoryId)
256{
257 return EQUIPMENT_STAT_CATEGORIES.find((entry) => entry.id === categoryId) ?? null;
258}
259
260/** Flat list of all piece rows with category + section context. */
261export function listEquipmentStatRows ()
262{
263 const out = [];
264 for (const category of EQUIPMENT_STAT_CATEGORIES)
265 {
266 for (const section of category.sections)
267 {
268 for (const row of section.rows)
269 {
270 out.push({
271 categoryId: category.id,
272 stats: category.stats,
273 section,
274 row
275 });
276 }
277 }
278 }
279 return out;
280}
281
282/**
283 * Map itemId → { categoryId, pieceKey, stats, singleton, section }.
284 * Built lazily so item defs are fully loaded.
285 */
286let _itemLookup = null;
287
288export function equipmentStatLookupForItem (itemId)
289{
290 if (!_itemLookup)
291 { _itemLookup = buildItemLookup(); }
292 return _itemLookup.get(itemId | 0) ?? null;
293}
294
295function buildItemLookup ()
296{
297 const map = new Map();
298 for (const entry of listEquipmentStatRows())
299 {
300 const { categoryId, stats, section, row } = entry;
301 for (const tier of section.tierOrder)
302 {
303 const itemId = row.resolveItemId?.(tier) ?? (row.singleton ? row.itemId : null);
304 if (itemId == null)
305 { continue; }
306 map.set(itemId | 0, Object.freeze({
307 categoryId,
308 pieceKey: row.pieceKey,
309 stats,
310 singleton: !!row.singleton,
311 tierKey: row.singleton ? SINGLETON_TIER_KEY : tier
312 }));
313 }
314 }
315 return map;
316}
317
318/** Reset cached lookup (tests). */
319export function clearEquipmentStatLookupCache ()
320{
321 _itemLookup = null;
322}
323
324function emptyStatBag (stats)
325{
326 const bag = {};
327 for (const skillId of stats)
328 { bag[skillId] = 0; }
329 return bag;
330}
331
332function defaultCellForRow (row, stats, tier)
333{
334 const cell = emptyStatBag(stats);
335 const base = row.defaultBonus != null
336 ? Number(row.defaultBonus) || 0
337 : tierStatBonus(tier === SINGLETON_TIER_KEY ? null : tier);
338 const extra = Number(row.defaultBonusExtra) || 0;
339 const value = Math.max(0, Math.floor(base + extra));
340 for (const skillId of stats)
341 { cell[skillId] = value; }
342 return cell;
343}
344
345/** Seed defaults from current tier curve (full helm +1, cosmetics 0). */
346export function defaultEquipmentStatBonuses ()
347{
348 const out = {};
349 for (const category of EQUIPMENT_STAT_CATEGORIES)
350 {
351 const cat = {};
352 for (const section of category.sections)
353 {
354 for (const row of section.rows)
355 {
356 const byTier = {};
357 for (const tier of section.tierOrder)
358 {
359 const itemId = row.resolveItemId?.(tier) ?? (row.singleton ? row.itemId : null);
360 if (itemId == null && !row.singleton)
361 { continue; }
362 byTier[tier] = defaultCellForRow(row, category.stats, tier);
363 }
364 cat[row.pieceKey] = byTier;
365 }
366 }
367 out[category.id] = cat;
368 }
369 return out;
370}
371
372function coerceBonusInt (raw)
373{
374 const n = Math.floor(Number(raw));
375 if (!Number.isFinite(n))
376 { return 0; }
377 return Math.max(0, Math.min(99, n));
378}
379
380/**
381 * Merge authored blob with defaults; drop unknown keys; fill missing cells.
382 * @param {object|null|undefined} raw
383 */
384export function normalizeEquipmentStatBonuses (raw)
385{
386 const defaults = defaultEquipmentStatBonuses();
387 const src = raw && typeof raw === "object" ? raw : {};
388 const out = {};
389 for (const category of EQUIPMENT_STAT_CATEGORIES)
390 {
391 const srcCat = src[category.id] && typeof src[category.id] === "object"
392 ? src[category.id]
393 : {};
394 const defCat = defaults[category.id] ?? {};
395 const cat = {};
396 for (const section of category.sections)
397 {
398 for (const row of section.rows)
399 {
400 const srcPiece = srcCat[row.pieceKey] && typeof srcCat[row.pieceKey] === "object"
401 ? srcCat[row.pieceKey]
402 : {};
403 const defPiece = defCat[row.pieceKey] ?? {};
404 const byTier = {};
405 for (const tier of section.tierOrder)
406 {
407 const itemId = row.resolveItemId?.(tier) ?? (row.singleton ? row.itemId : null);
408 if (itemId == null && !row.singleton)
409 { continue; }
410 const srcCell = srcPiece[tier] && typeof srcPiece[tier] === "object"
411 ? srcPiece[tier]
412 : null;
413 const defCell = defPiece[tier] ?? defaultCellForRow(row, category.stats, tier);
414 const cell = {};
415 for (const skillId of category.stats)
416 {
417 cell[skillId] = srcCell && Object.prototype.hasOwnProperty.call(srcCell, skillId)
418 ? coerceBonusInt(srcCell[skillId])
419 : coerceBonusInt(defCell[skillId]);
420 }
421 byTier[tier] = cell;
422 }
423 cat[row.pieceKey] = byTier;
424 }
425 }
426 out[category.id] = cat;
427 }
428 return out;
429}
430
431/**
432 * Resolve per-skill bonuses for one equipped item def.
433 * @returns {Record<string, number>|null}
434 */
435export function bonusForEquippedItem (definition, settingsBonuses = null)
436{
437 const equipment = definition?.equipment;
438 if (!equipment?.kind || !BONUS_EQUIPMENT_KINDS.has(equipment.kind))
439 { return null; }
440 const itemId = definition.itemId;
441 const lookup = equipmentStatLookupForItem(itemId);
442 if (!lookup)
443 { return null; }
444 const table = settingsBonuses && typeof settingsBonuses === "object"
445 ? settingsBonuses
446 : defaultEquipmentStatBonuses();
447 const piece = table[lookup.categoryId]?.[lookup.pieceKey];
448 if (!piece)
449 { return emptyStatBag(lookup.stats); }
450 const tierKey = lookup.singleton
451 ? SINGLETON_TIER_KEY
452 : (equipment.tier ?? definition.tier ?? lookup.tierKey);
453 const cell = piece[tierKey] ?? piece[lookup.tierKey];
454 if (!cell)
455 { return emptyStatBag(lookup.stats); }
456 const out = {};
457 for (const skillId of lookup.stats)
458 { out[skillId] = coerceBonusInt(cell[skillId]); }
459 return out;
460}
461
462/**
463 * Changelog bullets for equipmentStatBonuses edits.
464 * @param {(itemId: number) => string|null} [displayNameFor]
465 */
466export function diffEquipmentStatBonuses (previous, next, displayNameFor = null)
467{
468 const prev = normalizeEquipmentStatBonuses(previous);
469 const upcoming = normalizeEquipmentStatBonuses(next);
470 const bullets = [];
471 for (const category of EQUIPMENT_STAT_CATEGORIES)
472 {
473 for (const section of category.sections)
474 {
475 for (const row of section.rows)
476 {
477 for (const tier of section.tierOrder)
478 {
479 const from = prev[category.id]?.[row.pieceKey]?.[tier];
480 const to = upcoming[category.id]?.[row.pieceKey]?.[tier];
481 if (!from && !to)
482 { continue; }
483 for (const skillId of category.stats)
484 {
485 const a = coerceBonusInt(from?.[skillId]);
486 const b = coerceBonusInt(to?.[skillId]);
487 if (a === b)
488 { continue; }
489 const itemId = row.resolveItemId?.(tier) ?? row.itemId;
490 const name = (itemId != null && displayNameFor?.(itemId))
491 || `${row.label} (${section.tierDisplayName(tier)})`;
492 bullets.push(`${name} ${skillId} bonus changed from ${a} to ${b}.`);
493 }
494 }
495 }
496 }
497 }
498 return bullets;
499}
500
501export function equipmentStatBonusMapsEqual (a, b)
502{
503 const left = normalizeEquipmentStatBonuses(a);
504 const right = normalizeEquipmentStatBonuses(b);
505 return JSON.stringify(left) === JSON.stringify(right);
506}
507
508/**
509 * Every equippable item with a bonus kind must appear in exactly one category row.
510 * @returns {{ ok: true } | { ok: false, missing: number[], duplicates: number[] }}
511 */
512export function assertAllBonusGearCategorized ()
513{
514 clearEquipmentStatLookupCache();
515 const seen = new Map();
516 const duplicates = [];
517 for (const entry of listEquipmentStatRows())
518 {
519 for (const tier of entry.section.tierOrder)
520 {
521 const itemId = entry.row.resolveItemId?.(tier) ?? entry.row.itemId;
522 if (itemId == null)
523 { continue; }
524 const id = itemId | 0;
525 if (seen.has(id))
526 { duplicates.push(id); }
527 else
528 { seen.set(id, entry); }
529 }
530 }
531 const missing = [];
532 for (const def of Object.values(ITEM_DEFINITIONS))
533 {
534 const kind = def?.equipment?.kind;
535 if (!kind || !BONUS_EQUIPMENT_KINDS.has(kind))
536 { continue; }
537 if (!seen.has(def.itemId | 0))
538 { missing.push(def.itemId | 0); }
539 }
540 if (missing.length || duplicates.length)
541 { return { ok: false, missing, duplicates }; }
542 return { ok: true };
543}
544
545/** Preview item id for a row at tier (editor icon). */
546export function equipmentStatRowItemId (row, tier)
547{
548 if (row.singleton)
549 { return row.itemId ?? row.resolveItemId?.(SINGLETON_TIER_KEY) ?? null; }
550 return row.resolveItemId?.(tier) ?? null;
551}
552
553export function equipmentStatRowDefaultTier (section, row)
554{
555 for (const tier of section.tierOrder)
556 {
557 if (equipmentStatRowItemId(row, tier) != null)
558 { return tier; }
559 }
560 return section.tierOrder[0] ?? SINGLETON_TIER_KEY;
561}
562
563/** Display helper — re-export itemDefinition for callers that only import this module. */
564export { itemDefinition };
shared/definitions/familyItemIds.js +3 −2
@@ -1,5 +1,5 @@
1 1 import { ItemFamilyId, itemIdForFamilyTier } from "./tierFamilies.js";
2 import { LOG_ITEM_BY_WOOD, HANDLE_ITEM_BY_WOOD } from "./woodItems.js";
2 import { LOG_ITEM_BY_WOOD, HANDLE_ITEM_BY_WOOD, QUARTERSTAFF_ITEM_BY_WOOD } from "./woodItems.js";
3 3 import {
4 4 BAR_ITEM_BY_METAL,
5 5 PICKAXE_HEAD_ITEM_BY_METAL,
@@ -32,7 +32,8 @@ export const FAMILY_ITEM_IDS = Object.freeze({
32 32 [ItemFamilyId.arrow]: ARROW_BY_METAL,
33 33 [ItemFamilyId.unstrungBow]: UNSTRUNG_BOW_BY_WOOD,
34 34 [ItemFamilyId.bowstring]: BOWSTRING_BY_CLOTH,
35 [ItemFamilyId.bow]: BOW_BY_WOOD
35 [ItemFamilyId.bow]: BOW_BY_WOOD,
36 [ItemFamilyId.quarterstaff]: QUARTERSTAFF_ITEM_BY_WOOD
36 37 });
37 38
38 39 export function familyItemId (familyId, tier)
@@ -1,5 +1,5 @@
1import { ItemFamilyId, itemIdForFamilyTier } from "./tierFamilies.js";
1import { ItemFamilyId, itemIdForFamilyTier } from "./tierFamilies.js";
2import { LOG_ITEM_BY_WOOD, HANDLE_ITEM_BY_WOOD } from "./woodItems.js";
2import { LOG_ITEM_BY_WOOD, HANDLE_ITEM_BY_WOOD, QUARTERSTAFF_ITEM_BY_WOOD } from "./woodItems.js";
3import {
3import {
4 BAR_ITEM_BY_METAL,
4 BAR_ITEM_BY_METAL,
5 PICKAXE_HEAD_ITEM_BY_METAL,
5 PICKAXE_HEAD_ITEM_BY_METAL,
@@ -32,7 +32,8 @@ export const FAMILY_ITEM_IDS = Object.freeze({
32 [ItemFamilyId.arrow]: ARROW_BY_METAL,
32 [ItemFamilyId.arrow]: ARROW_BY_METAL,
33 [ItemFamilyId.unstrungBow]: UNSTRUNG_BOW_BY_WOOD,
33 [ItemFamilyId.unstrungBow]: UNSTRUNG_BOW_BY_WOOD,
34 [ItemFamilyId.bowstring]: BOWSTRING_BY_CLOTH,
34 [ItemFamilyId.bowstring]: BOWSTRING_BY_CLOTH,
35 [ItemFamilyId.bow]: BOW_BY_WOOD
35 [ItemFamilyId.bow]: BOW_BY_WOOD,
36 [ItemFamilyId.quarterstaff]: QUARTERSTAFF_ITEM_BY_WOOD
36});
37});
37
38
38export function familyItemId (familyId, tier)
39export function familyItemId (familyId, tier)
shared/definitions/items.js +2 −2
@@ -1,6 +1,6 @@
1 1 import { equipImageName, spriteImageName } from "./tileSprites.js";
2 2 import { SkillId } from "./skills.js";
3 import { MaterialTier } from "./materialTiers.js";
3 import { MaterialTier, WoodTier } from "./materialTiers.js";
4 4 import { AttackType } from "./attackTypes.js";
5 5 import { EquipmentKind } from "./equipmentKinds.js";
6 6 import { formatQuantity } from "../items/formatQuantity.js";
@@ -123,7 +123,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
123 123 category: "finished",
124 124 equipment: Object.freeze({
125 125 slot: EQUIPMENT_SLOT.weapon,
126 tier: MaterialTier.bronze,
126 tier: WoodTier.pine,
127 127 kind: EquipmentKind.clubWeapon,
128 128 attack: Object.freeze({
129 129 mode: "melee",
@@ -1,6 +1,6 @@
1import { equipImageName, spriteImageName } from "./tileSprites.js";
1import { equipImageName, spriteImageName } from "./tileSprites.js";
2import { SkillId } from "./skills.js";
2import { SkillId } from "./skills.js";
3import { MaterialTier } from "./materialTiers.js";
3import { MaterialTier, WoodTier } from "./materialTiers.js";
4import { AttackType } from "./attackTypes.js";
4import { AttackType } from "./attackTypes.js";
5import { EquipmentKind } from "./equipmentKinds.js";
5import { EquipmentKind } from "./equipmentKinds.js";
6import { formatQuantity } from "../items/formatQuantity.js";
6import { formatQuantity } from "../items/formatQuantity.js";
@@ -123,7 +123,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
123 category: "finished",
123 category: "finished",
124 equipment: Object.freeze({
124 equipment: Object.freeze({
125 slot: EQUIPMENT_SLOT.weapon,
125 slot: EQUIPMENT_SLOT.weapon,
126 tier: MaterialTier.bronze,
126 tier: WoodTier.pine,
127 kind: EquipmentKind.clubWeapon,
127 kind: EquipmentKind.clubWeapon,
128 attack: Object.freeze({
128 attack: Object.freeze({
129 mode: "melee",
129 mode: "melee",
shared/definitions/tierFamilies.js +32 −5
@@ -6,7 +6,7 @@ import {
6 6 MATERIAL_TIER_ORDER,
7 7 CLOTH_TIER_ORDER,
8 8 CLOTH_DISPLAY_NAME,
9 metalTierForWood,
9 woodTierForMetal,
10 10 clothTierForWood
11 11 } from "./materialTiers.js";
12 12 import { EquipmentKind } from "./equipmentKinds.js";
@@ -37,7 +37,8 @@ export const ItemFamilyId = Object.freeze({
37 37 arrow: "arrow",
38 38 unstrungBow: "unstrungBow",
39 39 bow: "bow",
40 bowstring: "bowstring"
40 bowstring: "bowstring",
41 quarterstaff: "quarterstaff"
41 42 });
42 43
43 44 const DEFAULT_STACK = 99;
@@ -163,7 +164,8 @@ export const ITEM_FAMILIES = Object.freeze({
163 164 stackable: false,
164 165 maxStackSize: 1,
165 166 seedValue: 8,
166 tintFromTier: true,
167 dualTintFromTier: true,
168 woodTierFromMetal: true,
167 169 equipmentKind: EquipmentKind.pickaxeTool
168 170 }),
169 171 [ItemFamilyId.axe]: Object.freeze({
@@ -177,7 +179,8 @@ export const ITEM_FAMILIES = Object.freeze({
177 179 stackable: false,
178 180 maxStackSize: 1,
179 181 seedValue: 8,
180 tintFromTier: true,
182 dualTintFromTier: true,
183 woodTierFromMetal: true,
181 184 equipmentKind: EquipmentKind.axeTool
182 185 }),
183 186 [ItemFamilyId.plantClippers]: Object.freeze({
@@ -262,6 +265,30 @@ export const ITEM_FAMILIES = Object.freeze({
262 265 maxStackSize: DEFAULT_STACK,
263 266 seedValue: 2,
264 267 tintFromTier: true
268 }),
269 [ItemFamilyId.quarterstaff]: Object.freeze({
270 familyId: ItemFamilyId.quarterstaff,
271 axis: TierAxis.wood,
272 label: "quarterstaff",
273 description: (name) => `A ${name.toLowerCase()} quarterstaff, long enough to keep foes at a distance.`,
274 category: ItemCategory.finished,
275 iconKey: "quarterstaff",
276 defaultState: "quarterstaff",
277 stackable: false,
278 maxStackSize: 1,
279 seedValue: 8,
280 tintFromTier: true,
281 equipmentKind: EquipmentKind.clubWeapon,
282 equipmentSlot: "weapon",
283 equipmentTintFromTier: true,
284 equipmentAttack: Object.freeze({
285 mode: "melee",
286 rangeTiles: 1,
287 hitSkillId: SkillId.clubfighting,
288 damageSkillId: SkillId.strength,
289 attackType: AttackType.blunt,
290 cooldownMs: 700
291 })
265 292 })
266 293 });
267 294
@@ -336,7 +363,7 @@ export function buildTierItemDef (familyId, tier, itemId, extra = {})
336 363 tier,
337 364 ...(family.tintFromTier ? { tintFromTier: true } : {}),
338 365 ...(family.npcShopAllowed ? { npcShopAllowed: true } : {}),
339 ...(family.woodTierFromMetal ? { woodTier: metalTierForWood(tier), dualTintFromTier: true } : {}),
366 ...(family.woodTierFromMetal ? { woodTier: woodTierForMetal(tier), dualTintFromTier: true } : {}),
340 367 ...(family.dualTintFromTier && !family.woodTierFromMetal ? { dualTintFromTier: true } : {}),
341 368 ...(family.clothTierFromWood ? { clothTier: clothTierForWood(tier) } : {}),
342 369 ...(equipment ? { equipment } : {})
@@ -6,7 +6,7 @@ import {
6 MATERIAL_TIER_ORDER,
6 MATERIAL_TIER_ORDER,
7 CLOTH_TIER_ORDER,
7 CLOTH_TIER_ORDER,
8 CLOTH_DISPLAY_NAME,
8 CLOTH_DISPLAY_NAME,
9 metalTierForWood,
9 woodTierForMetal,
10 clothTierForWood
10 clothTierForWood
11} from "./materialTiers.js";
11} from "./materialTiers.js";
12import { EquipmentKind } from "./equipmentKinds.js";
12import { EquipmentKind } from "./equipmentKinds.js";
@@ -37,7 +37,8 @@ export const ItemFamilyId = Object.freeze({
37 arrow: "arrow",
37 arrow: "arrow",
38 unstrungBow: "unstrungBow",
38 unstrungBow: "unstrungBow",
39 bow: "bow",
39 bow: "bow",
40 bowstring: "bowstring"
40 bowstring: "bowstring",
41 quarterstaff: "quarterstaff"
41});
42});
42
43
43const DEFAULT_STACK = 99;
44const DEFAULT_STACK = 99;
@@ -163,7 +164,8 @@ export const ITEM_FAMILIES = Object.freeze({
163 stackable: false,
164 stackable: false,
164 maxStackSize: 1,
165 maxStackSize: 1,
165 seedValue: 8,
166 seedValue: 8,
166 tintFromTier: true,
167 dualTintFromTier: true,
168 woodTierFromMetal: true,
167 equipmentKind: EquipmentKind.pickaxeTool
169 equipmentKind: EquipmentKind.pickaxeTool
168 }),
170 }),
169 [ItemFamilyId.axe]: Object.freeze({
171 [ItemFamilyId.axe]: Object.freeze({
@@ -177,7 +179,8 @@ export const ITEM_FAMILIES = Object.freeze({
177 stackable: false,
179 stackable: false,
178 maxStackSize: 1,
180 maxStackSize: 1,
179 seedValue: 8,
181 seedValue: 8,
180 tintFromTier: true,
182 dualTintFromTier: true,
183 woodTierFromMetal: true,
181 equipmentKind: EquipmentKind.axeTool
184 equipmentKind: EquipmentKind.axeTool
182 }),
185 }),
183 [ItemFamilyId.plantClippers]: Object.freeze({
186 [ItemFamilyId.plantClippers]: Object.freeze({
@@ -262,6 +265,30 @@ export const ITEM_FAMILIES = Object.freeze({
262 maxStackSize: DEFAULT_STACK,
265 maxStackSize: DEFAULT_STACK,
263 seedValue: 2,
266 seedValue: 2,
264 tintFromTier: true
267 tintFromTier: true
268 }),
269 [ItemFamilyId.quarterstaff]: Object.freeze({
270 familyId: ItemFamilyId.quarterstaff,
271 axis: TierAxis.wood,
272 label: "quarterstaff",
273 description: (name) => `A ${name.toLowerCase()} quarterstaff, long enough to keep foes at a distance.`,
274 category: ItemCategory.finished,
275 iconKey: "quarterstaff",
276 defaultState: "quarterstaff",
277 stackable: false,
278 maxStackSize: 1,
279 seedValue: 8,
280 tintFromTier: true,
281 equipmentKind: EquipmentKind.clubWeapon,
282 equipmentSlot: "weapon",
283 equipmentTintFromTier: true,
284 equipmentAttack: Object.freeze({
285 mode: "melee",
286 rangeTiles: 1,
287 hitSkillId: SkillId.clubfighting,
288 damageSkillId: SkillId.strength,
289 attackType: AttackType.blunt,
290 cooldownMs: 700
291 })
265 })
292 })
266});
293});
267
294
@@ -336,7 +363,7 @@ export function buildTierItemDef (familyId, tier, itemId, extra = {})
336 tier,
363 tier,
337 ...(family.tintFromTier ? { tintFromTier: true } : {}),
364 ...(family.tintFromTier ? { tintFromTier: true } : {}),
338 ...(family.npcShopAllowed ? { npcShopAllowed: true } : {}),
365 ...(family.npcShopAllowed ? { npcShopAllowed: true } : {}),
339 ...(family.woodTierFromMetal ? { woodTier: metalTierForWood(tier), dualTintFromTier: true } : {}),
366 ...(family.woodTierFromMetal ? { woodTier: woodTierForMetal(tier), dualTintFromTier: true } : {}),
340 ...(family.dualTintFromTier && !family.woodTierFromMetal ? { dualTintFromTier: true } : {}),
367 ...(family.dualTintFromTier && !family.woodTierFromMetal ? { dualTintFromTier: true } : {}),
341 ...(family.clothTierFromWood ? { clothTier: clothTierForWood(tier) } : {}),
368 ...(family.clothTierFromWood ? { clothTier: clothTierForWood(tier) } : {}),
342 ...(equipment ? { equipment } : {})
369 ...(equipment ? { equipment } : {})
shared/definitions/woodItems.js +25 −2
@@ -27,7 +27,13 @@ export const WoodItemId = Object.freeze({
27 27 heartwoodLog: 63,
28 28 heartwoodHandle: 64,
29 29 elderLog: 65,
30 elderHandle: 66
30 elderHandle: 66,
31 birchQuarterstaff: 244,
32 oakQuarterstaff: 245,
33 ebonyQuarterstaff: 246,
34 lignumQuarterstaff: 247,
35 heartwoodQuarterstaff: 248,
36 elderQuarterstaff: 249
31 37 });
32 38
33 39 const LOG_IDS = Object.freeze({
@@ -50,8 +56,19 @@ const HANDLE_IDS = Object.freeze({
50 56 [WoodTier.elder]: WoodItemId.elderHandle
51 57 });
52 58
59 /** Quarterstaffs start at birch; pine uses {@link ItemId.stick}. */
60 const QUARTERSTAFF_IDS = Object.freeze({
61 [WoodTier.birch]: WoodItemId.birchQuarterstaff,
62 [WoodTier.oak]: WoodItemId.oakQuarterstaff,
63 [WoodTier.ebony]: WoodItemId.ebonyQuarterstaff,
64 [WoodTier.lignum]: WoodItemId.lignumQuarterstaff,
65 [WoodTier.heartwood]: WoodItemId.heartwoodQuarterstaff,
66 [WoodTier.elder]: WoodItemId.elderQuarterstaff
67 });
68
53 69 export const LOG_ITEM_BY_WOOD = LOG_IDS;
54 70 export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
71 export const QUARTERSTAFF_ITEM_BY_WOOD = QUARTERSTAFF_IDS;
55 72
56 73 export function logItemIdForWood (woodTier)
57 74 {
@@ -63,8 +80,14 @@ export function handleItemIdForWood (woodTier)
63 80 return itemIdForFamilyTier(HANDLE_IDS, woodTier);
64 81 }
65 82
83 export function quarterstaffItemIdForWood (woodTier)
84 {
85 return itemIdForFamilyTier(QUARTERSTAFF_IDS, woodTier);
86 }
87
66 88 /** Full defs for wood family (merged into ITEM_DEFINITIONS). */
67 89 export const WOOD_ITEM_DEFINITIONS = Object.freeze({
68 90 ...buildFamilyDefinitionMap(ItemFamilyId.log, LOG_IDS),
69 ...buildFamilyDefinitionMap(ItemFamilyId.handle, HANDLE_IDS)
91 ...buildFamilyDefinitionMap(ItemFamilyId.handle, HANDLE_IDS),
92 ...buildFamilyDefinitionMap(ItemFamilyId.quarterstaff, QUARTERSTAFF_IDS)
70 93 });
@@ -27,7 +27,13 @@ export const WoodItemId = Object.freeze({
27 heartwoodLog: 63,
27 heartwoodLog: 63,
28 heartwoodHandle: 64,
28 heartwoodHandle: 64,
29 elderLog: 65,
29 elderLog: 65,
30 elderHandle: 66
30 elderHandle: 66,
31 birchQuarterstaff: 244,
32 oakQuarterstaff: 245,
33 ebonyQuarterstaff: 246,
34 lignumQuarterstaff: 247,
35 heartwoodQuarterstaff: 248,
36 elderQuarterstaff: 249
31});
37});
32
38
33const LOG_IDS = Object.freeze({
39const LOG_IDS = Object.freeze({
@@ -50,8 +56,19 @@ const HANDLE_IDS = Object.freeze({
50 [WoodTier.elder]: WoodItemId.elderHandle
56 [WoodTier.elder]: WoodItemId.elderHandle
51});
57});
52
58
59/** Quarterstaffs start at birch; pine uses {@link ItemId.stick}. */
60const QUARTERSTAFF_IDS = Object.freeze({
61 [WoodTier.birch]: WoodItemId.birchQuarterstaff,
62 [WoodTier.oak]: WoodItemId.oakQuarterstaff,
63 [WoodTier.ebony]: WoodItemId.ebonyQuarterstaff,
64 [WoodTier.lignum]: WoodItemId.lignumQuarterstaff,
65 [WoodTier.heartwood]: WoodItemId.heartwoodQuarterstaff,
66 [WoodTier.elder]: WoodItemId.elderQuarterstaff
67});
68
53export const LOG_ITEM_BY_WOOD = LOG_IDS;
69export const LOG_ITEM_BY_WOOD = LOG_IDS;
54export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
70export const HANDLE_ITEM_BY_WOOD = HANDLE_IDS;
71export const QUARTERSTAFF_ITEM_BY_WOOD = QUARTERSTAFF_IDS;
55
72
56export function logItemIdForWood (woodTier)
73export function logItemIdForWood (woodTier)
57{
74{
@@ -63,8 +80,14 @@ export function handleItemIdForWood (woodTier)
63 return itemIdForFamilyTier(HANDLE_IDS, woodTier);
80 return itemIdForFamilyTier(HANDLE_IDS, woodTier);
64}
81}
65
82
83export function quarterstaffItemIdForWood (woodTier)
84{
85 return itemIdForFamilyTier(QUARTERSTAFF_IDS, woodTier);
86}
87
66/** Full defs for wood family (merged into ITEM_DEFINITIONS). */
88/** Full defs for wood family (merged into ITEM_DEFINITIONS). */
67export const WOOD_ITEM_DEFINITIONS = Object.freeze({
89export const WOOD_ITEM_DEFINITIONS = Object.freeze({
68 ...buildFamilyDefinitionMap(ItemFamilyId.log, LOG_IDS),
90 ...buildFamilyDefinitionMap(ItemFamilyId.log, LOG_IDS),
69 ...buildFamilyDefinitionMap(ItemFamilyId.handle, HANDLE_IDS)
91 ...buildFamilyDefinitionMap(ItemFamilyId.handle, HANDLE_IDS),
92 ...buildFamilyDefinitionMap(ItemFamilyId.quarterstaff, QUARTERSTAFF_IDS)
70});
93});
shared/definitions/worldSettings.js +7 −0
@@ -213,6 +213,13 @@ export const WORLD_SETTING_CATEGORIES = [
213 213 panel: "itemSeedPrices",
214 214 fields: []
215 215 },
216 {
217 id: "equipmentStats",
218 label: "Equipment Stats",
219 /** Custom panel: piece × tier bonus tables. */
220 panel: "equipmentStats",
221 fields: []
222 },
216 223 {
217 224 id: "courier",
218 225 label: "Courier",
@@ -213,6 +213,13 @@ export const WORLD_SETTING_CATEGORIES = [
213 panel: "itemSeedPrices",
213 panel: "itemSeedPrices",
214 fields: []
214 fields: []
215 },
215 },
216 {
217 id: "equipmentStats",
218 label: "Equipment Stats",
219 /** Custom panel: piece × tier bonus tables. */
220 panel: "equipmentStats",
221 fields: []
222 },
216 {
223 {
217 id: "courier",
224 id: "courier",
218 label: "Courier",
225 label: "Courier",
shared/equipment/stats.js +16 −23
@@ -1,24 +1,15 @@
1 1 import { SkillId, skillLevel } from "../definitions/skills.js";
2 import { tierMinSkillLevel, tierStatBonus } from "../definitions/materialTiers.js";
2 import { tierMinSkillLevel } from "../definitions/materialTiers.js";
3 3 import { EquipmentKind } from "../definitions/equipmentKinds.js";
4 4 import { itemDefinition } from "../definitions/items.js";
5 import {
6 bonusForEquippedItem,
7 defaultEquipmentStatBonuses
8 } from "../definitions/equipmentStatCategories.js";
5 9
6 10 /** How an equippable item maps to min-level skill and worn stat bonus. */
7 11 export { EquipmentKind } from "../definitions/equipmentKinds.js";
8 12
9 const BONUS_STAT_BY_KIND = Object.freeze({
10 [EquipmentKind.metalWeapon]: SkillId.strength,
11 [EquipmentKind.clubWeapon]: SkillId.strength,
12 [EquipmentKind.bow]: SkillId.dexterity,
13 [EquipmentKind.arrowAmmo]: SkillId.dexterity,
14 [EquipmentKind.metalArmour]: SkillId.defence,
15 [EquipmentKind.leatherArmour]: SkillId.agility,
16 [EquipmentKind.clothArmour]: SkillId.defence,
17 [EquipmentKind.wizardCloth]: SkillId.magic,
18 [EquipmentKind.shield]: SkillId.defence,
19 [EquipmentKind.staff]: SkillId.magic
20 });
21
22 13 export function equipMinSkillId (equipmentDef)
23 14 {
24 15 const kind = equipmentDef?.kind;
@@ -52,23 +43,25 @@ export function equipMinSkillId (equipmentDef)
52 43 }
53 44 }
54 45
55 export function equipmentBonusesFromSlots (slots)
46 /**
47 * Sum worn equipment bonuses from world settings (fallback: built-in defaults).
48 * @param {object} slots
49 * @param {object|null} [settings] world settings (uses settings.equipmentStatBonuses)
50 */
51 export function equipmentBonusesFromSlots (slots, settings = null)
56 52 {
57 53 const bonuses = emptyBonuses();
54 const table = settings?.equipmentStatBonuses ?? defaultEquipmentStatBonuses();
58 55 for (const stack of Object.values(slots ?? {}))
59 56 {
60 57 if (!stack?.itemId)
61 58 { continue; }
62 59 const def = itemDefinition(stack.itemId);
63 const equipment = def?.equipment;
64 if (!equipment)
65 { continue; }
66 const statId = BONUS_STAT_BY_KIND[equipment.kind];
67 if (!statId)
60 const perItem = bonusForEquippedItem(def, table);
61 if (!perItem)
68 62 { continue; }
69 const tier = equipment.tier;
70 const extra = equipment.bonus ?? tierStatBonus(tier);
71 bonuses[statId] = (bonuses[statId] ?? 0) + extra;
63 for (const [skillId, amount] of Object.entries(perItem))
64 { bonuses[skillId] = (bonuses[skillId] ?? 0) + (amount | 0); }
72 65 }
73 66 return bonuses;
74 67 }
@@ -1,24 +1,15 @@
1import { SkillId, skillLevel } from "../definitions/skills.js";
1import { SkillId, skillLevel } from "../definitions/skills.js";
2import { tierMinSkillLevel, tierStatBonus } from "../definitions/materialTiers.js";
2import { tierMinSkillLevel } from "../definitions/materialTiers.js";
3import { EquipmentKind } from "../definitions/equipmentKinds.js";
3import { EquipmentKind } from "../definitions/equipmentKinds.js";
4import { itemDefinition } from "../definitions/items.js";
4import { itemDefinition } from "../definitions/items.js";
5import {
6 bonusForEquippedItem,
7 defaultEquipmentStatBonuses
8} from "../definitions/equipmentStatCategories.js";
5
9
6/** How an equippable item maps to min-level skill and worn stat bonus. */
10/** How an equippable item maps to min-level skill and worn stat bonus. */
7export { EquipmentKind } from "../definitions/equipmentKinds.js";
11export { EquipmentKind } from "../definitions/equipmentKinds.js";
8
12
9const BONUS_STAT_BY_KIND = Object.freeze({
10 [EquipmentKind.metalWeapon]: SkillId.strength,
11 [EquipmentKind.clubWeapon]: SkillId.strength,
12 [EquipmentKind.bow]: SkillId.dexterity,
13 [EquipmentKind.arrowAmmo]: SkillId.dexterity,
14 [EquipmentKind.metalArmour]: SkillId.defence,
15 [EquipmentKind.leatherArmour]: SkillId.agility,
16 [EquipmentKind.clothArmour]: SkillId.defence,
17 [EquipmentKind.wizardCloth]: SkillId.magic,
18 [EquipmentKind.shield]: SkillId.defence,
19 [EquipmentKind.staff]: SkillId.magic
20});
21
22export function equipMinSkillId (equipmentDef)
13export function equipMinSkillId (equipmentDef)
23{
14{
24 const kind = equipmentDef?.kind;
15 const kind = equipmentDef?.kind;
@@ -52,23 +43,25 @@ export function equipMinSkillId (equipmentDef)
52 }
43 }
53}
44}
54
45
55export function equipmentBonusesFromSlots (slots)
46/**
47 * Sum worn equipment bonuses from world settings (fallback: built-in defaults).
48 * @param {object} slots
49 * @param {object|null} [settings] world settings (uses settings.equipmentStatBonuses)
50 */
51export function equipmentBonusesFromSlots (slots, settings = null)
56{
52{
57 const bonuses = emptyBonuses();
53 const bonuses = emptyBonuses();
54 const table = settings?.equipmentStatBonuses ?? defaultEquipmentStatBonuses();
58 for (const stack of Object.values(slots ?? {}))
55 for (const stack of Object.values(slots ?? {}))
59 {
56 {
60 if (!stack?.itemId)
57 if (!stack?.itemId)
61 { continue; }
58 { continue; }
62 const def = itemDefinition(stack.itemId);
59 const def = itemDefinition(stack.itemId);
63 const equipment = def?.equipment;
60 const perItem = bonusForEquippedItem(def, table);
64 if (!equipment)
61 if (!perItem)
65 { continue; }
66 const statId = BONUS_STAT_BY_KIND[equipment.kind];
67 if (!statId)
68 { continue; }
62 { continue; }
69 const tier = equipment.tier;
63 for (const [skillId, amount] of Object.entries(perItem))
70 const extra = equipment.bonus ?? tierStatBonus(tier);
64 { bonuses[skillId] = (bonuses[skillId] ?? 0) + (amount | 0); }
71 bonuses[statId] = (bonuses[statId] ?? 0) + extra;
72 }
65 }
73 return bonuses;
66 return bonuses;
74}
67}
shared/protocol/constants.js +4 −1
@@ -1,4 +1,5 @@
1 1 import { DEFAULT_STARTER_EQUIPMENT, DEFAULT_STARTER_INVENTORY } from "../items/starterLoadout.js";
2 import { defaultEquipmentStatBonuses } from "../definitions/equipmentStatCategories.js";
2 3
3 4 export const CHUNK_SIZE = 16;
4 5 export const REGION_CHUNKS = 4;
@@ -62,7 +63,9 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
62 63 /** New characters only: equipment slot → itemId (or null). */
63 64 starterEquipment: DEFAULT_STARTER_EQUIPMENT,
64 65 /** New characters only: inventory stacks `{ itemId, quantity }[]`. */
65 starterInventory: DEFAULT_STARTER_INVENTORY
66 starterInventory: DEFAULT_STARTER_INVENTORY,
67 /** Piece×tier worn stat bonuses (editor Equipment Stats tab). */
68 equipmentStatBonuses: defaultEquipmentStatBonuses()
66 69 });
67 70
68 71 export const GAIT = Object.freeze({
@@ -1,4 +1,5 @@
1import { DEFAULT_STARTER_EQUIPMENT, DEFAULT_STARTER_INVENTORY } from "../items/starterLoadout.js";
1import { DEFAULT_STARTER_EQUIPMENT, DEFAULT_STARTER_INVENTORY } from "../items/starterLoadout.js";
2import { defaultEquipmentStatBonuses } from "../definitions/equipmentStatCategories.js";
2
3
3export const CHUNK_SIZE = 16;
4export const CHUNK_SIZE = 16;
4export const REGION_CHUNKS = 4;
5export const REGION_CHUNKS = 4;
@@ -62,7 +63,9 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
62 /** New characters only: equipment slot → itemId (or null). */
63 /** New characters only: equipment slot → itemId (or null). */
63 starterEquipment: DEFAULT_STARTER_EQUIPMENT,
64 starterEquipment: DEFAULT_STARTER_EQUIPMENT,
64 /** New characters only: inventory stacks `{ itemId, quantity }[]`. */
65 /** New characters only: inventory stacks `{ itemId, quantity }[]`. */
65 starterInventory: DEFAULT_STARTER_INVENTORY
66 starterInventory: DEFAULT_STARTER_INVENTORY,
67 /** Piece×tier worn stat bonuses (editor Equipment Stats tab). */
68 equipmentStatBonuses: defaultEquipmentStatBonuses()
66});
69});
67
70
68export const GAIT = Object.freeze({
71export const GAIT = Object.freeze({
shared/render/tint.js +9 −7
@@ -1,4 +1,4 @@
1 import { MATERIAL_TIER_ORDER, materialTintColor, GatherMaterialId, metalTierForWood } from "../definitions/materialTiers.js";
1 import { MATERIAL_TIER_ORDER, materialTintColor, GatherMaterialId, woodTierForMetal } from "../definitions/materialTiers.js";
2 2 import { itemDefinition } from "../definitions/items.js";
3 3
4 4 /**
@@ -10,9 +10,9 @@ import { itemDefinition } from "../definitions/items.js";
10 10 * so dark target colours stay dark: mix(tint, vec3(luma(tint)), G/R) * L.
11 11 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
12 12 *
13 * Dual-channel arrows ({@link applyDualChannelTintToImageData}):
14 * - Dominant red (R > G,B): shaft mask; lightness = R; tint with shaft colour.
15 * - Dominant blue (B > R,G): tip mask; lightness = B; tint with tip colour.
13 * Dual-channel arrows / tools ({@link applyDualChannelTintToImageData}):
14 * - Dominant red (R > G,B): shaft / handle mask; lightness = R; tint with shaft colour.
15 * - Dominant blue (B > R,G): tip / metal mask; lightness = B; tint with tip colour.
16 16 * - Neutral / white (fletching): neither channel dominates — RGB unchanged.
17 17 */
18 18
@@ -88,7 +88,7 @@ export function applyDualChannelTintToImageData (imageData, { shaft, tip })
88 88 return imageData;
89 89 }
90 90
91 /** Dual shaft/tip tier tints for assembled arrows (`dualTintFromTier` on item def). */
91 /** Dual shaft/tip tier tints for assembled arrows and hafted tools (`dualTintFromTier`). */
92 92 export function resolveItemDualTint (stackOrDef, def = null)
93 93 {
94 94 const stack = stackOrDef?.itemId != null ? stackOrDef : null;
@@ -98,7 +98,7 @@ export function resolveItemDualTint (stackOrDef, def = null)
98 98 if (!definition?.dualTintFromTier)
99 99 { return null; }
100 100 const metalTier = definition.tier ?? definition.equipment?.tier ?? null;
101 const woodTier = definition.woodTier ?? (metalTier ? metalTierForWood(metalTier) : null);
101 const woodTier = definition.woodTier ?? (metalTier ? woodTierForMetal(metalTier) : null);
102 102 if (!metalTier || !woodTier)
103 103 { return null; }
104 104 return {
@@ -169,8 +169,10 @@ export function resolveEquipTint (itemIdOrDef, instance = null)
169 169 { return null; }
170 170 if (instance?.dyeColor)
171 171 { return normalizeRgb(instance.dyeColor); }
172 if (definition.tint)
172 if (definition?.tint)
173 173 { return normalizeRgb(definition.tint); }
174 if (definition?.dualTintFromTier)
175 { return null; }
174 176 const tier = resolveTintTier(definition);
175 177 if (tier)
176 178 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
@@ -1,4 +1,4 @@
1import { MATERIAL_TIER_ORDER, materialTintColor, GatherMaterialId, metalTierForWood } from "../definitions/materialTiers.js";
1import { MATERIAL_TIER_ORDER, materialTintColor, GatherMaterialId, woodTierForMetal } from "../definitions/materialTiers.js";
2import { itemDefinition } from "../definitions/items.js";
2import { itemDefinition } from "../definitions/items.js";
3
3
4/**
4/**
@@ -10,9 +10,9 @@ import { itemDefinition } from "../definitions/items.js";
10 * so dark target colours stay dark: mix(tint, vec3(luma(tint)), G/R) * L.
10 * so dark target colours stay dark: mix(tint, vec3(luma(tint)), G/R) * L.
11 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
11 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
12 *
12 *
13 * Dual-channel arrows ({@link applyDualChannelTintToImageData}):
13 * Dual-channel arrows / tools ({@link applyDualChannelTintToImageData}):
14 * - Dominant red (R > G,B): shaft mask; lightness = R; tint with shaft colour.
14 * - Dominant red (R > G,B): shaft / handle mask; lightness = R; tint with shaft colour.
15 * - Dominant blue (B > R,G): tip mask; lightness = B; tint with tip colour.
15 * - Dominant blue (B > R,G): tip / metal mask; lightness = B; tint with tip colour.
16 * - Neutral / white (fletching): neither channel dominates — RGB unchanged.
16 * - Neutral / white (fletching): neither channel dominates — RGB unchanged.
17 */
17 */
18
18
@@ -88,7 +88,7 @@ export function applyDualChannelTintToImageData (imageData, { shaft, tip })
88 return imageData;
88 return imageData;
89}
89}
90
90
91/** Dual shaft/tip tier tints for assembled arrows (`dualTintFromTier` on item def). */
91/** Dual shaft/tip tier tints for assembled arrows and hafted tools (`dualTintFromTier`). */
92export function resolveItemDualTint (stackOrDef, def = null)
92export function resolveItemDualTint (stackOrDef, def = null)
93{
93{
94 const stack = stackOrDef?.itemId != null ? stackOrDef : null;
94 const stack = stackOrDef?.itemId != null ? stackOrDef : null;
@@ -98,7 +98,7 @@ export function resolveItemDualTint (stackOrDef, def = null)
98 if (!definition?.dualTintFromTier)
98 if (!definition?.dualTintFromTier)
99 { return null; }
99 { return null; }
100 const metalTier = definition.tier ?? definition.equipment?.tier ?? null;
100 const metalTier = definition.tier ?? definition.equipment?.tier ?? null;
101 const woodTier = definition.woodTier ?? (metalTier ? metalTierForWood(metalTier) : null);
101 const woodTier = definition.woodTier ?? (metalTier ? woodTierForMetal(metalTier) : null);
102 if (!metalTier || !woodTier)
102 if (!metalTier || !woodTier)
103 { return null; }
103 { return null; }
104 return {
104 return {
@@ -169,8 +169,10 @@ export function resolveEquipTint (itemIdOrDef, instance = null)
169 { return null; }
169 { return null; }
170 if (instance?.dyeColor)
170 if (instance?.dyeColor)
171 { return normalizeRgb(instance.dyeColor); }
171 { return normalizeRgb(instance.dyeColor); }
172 if (definition.tint)
172 if (definition?.tint)
173 { return normalizeRgb(definition.tint); }
173 { return normalizeRgb(definition.tint); }
174 if (definition?.dualTintFromTier)
175 { return null; }
174 const tier = resolveTintTier(definition);
176 const tier = resolveTintTier(definition);
175 if (tier)
177 if (tier)
176 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }
178 { return tierTintColor(tier, { ore: isOreItemDefinition(definition) }); }