lots of things
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -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 unchanged7
*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
else167
{ 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,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
*/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,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
*/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`);@@ -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
else186
{187
setOpen(true);188
input.focus();189
}190
});161
input.addEventListener("input", () =>191
input.addEventListener("input", () =>162
{192
{163
setOpen(true);193
setOpen(true);@@ -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,@@ -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
effectiveSeedValue12
effectiveSeedValue13
} from "/shared/shop/pricing.js";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
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";15
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";16
import {16
import {17
normalizeStarterLoadout,17
normalizeStarterLoadout,@@ -19,6 +19,14 @@ import {19
DEFAULT_STARTER_EQUIPMENT,19
DEFAULT_STARTER_EQUIPMENT,20
DEFAULT_STARTER_INVENTORY20
DEFAULT_STARTER_INVENTORY21
} from "/shared/items/starterLoadout.js";21
} from "/shared/items/starterLoadout.js";22
import {23
EQUIPMENT_STAT_CATEGORIES,24
normalizeEquipmentStatBonuses,25
equipmentStatBonusMapsEqual,26
equipmentStatRowItemId,27
equipmentStatRowDefaultTier28
} from "/shared/definitions/equipmentStatCategories.js";29
import { applyItemIcon } from "/src/render/potionIcon.js";22
30
23
const SEED_PAGE_SIZE = 20;31
const SEED_PAGE_SIZE = 20;24
const SLOT_LABELS = Object.freeze({32
const SLOT_LABELS = Object.freeze({@@ -54,6 +62,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi54
starterInventory: DEFAULT_STARTER_INVENTORY62
starterInventory: DEFAULT_STARTER_INVENTORY55
});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, onPreviewNi65
{ 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, onPreviewNi78
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, onPreviewNi98
{ 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, onPreviewNi106
{ 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, onPreviewNi129
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, onPreviewNi167
...scalarDirtyValues(form, baseline),196
...scalarDirtyValues(form, baseline),168
itemSeedValues: draftSeeds,197
itemSeedValues: draftSeeds,169
starterEquipment: draftStarter.equipment,198
starterEquipment: draftStarter.equipment,170
starterInventory: draftStarter.inventory199
starterInventory: draftStarter.inventory,200
equipmentStatBonuses: draftEquipmentStats171
};201
};172
}202
}173
203
@@ -187,6 +217,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi187
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, onPreviewNi407
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]: value578
}579
}580
};581
draftEquipmentStats = {582
...draftEquipmentStats,583
[category.id]: nextCat584
};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, onPreviewNi436
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.itemLastSales648
? message.itemLastSales443
: {};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, onPreviewNi453
};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
onEquipmentStatsPanelReady671
})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
else725
else502
{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
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
function buildSeedPricePanel ({ onSearch, onPrev, onNext })804
function buildSeedPricePanel ({ onSearch, onPrev, onNext })547
{805
{548
const root = document.createElement("div");806
const root = document.createElement("div");@@ -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 @@1
import { applyMagentaTintToImageData } from "/shared/render/tint.js";1
import { applyMagentaTintToImageData, applyDualChannelTintToImageData } from "/shared/render/tint.js";2
import { layersForHairPreview } from "/shared/appearance/hair.js";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
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 | 099
frame: overlays[index].renderer.subImage | 098
});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.tint137
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
else144
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
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
}@@ -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
MaterialTier25
MaterialTier,26
woodTierForMetal26
} from "/shared/definitions/materialTiers.js";27
} from "/shared/definitions/materialTiers.js";27
import { craftDurationMs } from "/shared/definitions/gathering.js";28
import { craftDurationMs } from "/shared/definitions/gathering.js";28
import { applyItemIcon } from "../render/potionIcon.js";29
import { 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
}@@ -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 WorldView762
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 WorldView771
pivotX,772
pivotX,772
pivotY,773
pivotY,773
tints[index] ?? null,774
tints[index] ?? null,774
!!tight[index]775
!!tight[index],776
dualTints[index] ?? null775
);777
);776
}778
}777
this._portraitBodyMap = null;779
this._portraitBodyMap = null;@@ -835,7 +837,7 @@ export class WorldView835
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 WorldView854
const maskUniforms = tightFit && portraitEntity856
const maskUniforms = tightFit && portraitEntity855
? 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 WorldView1908
{ 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 WorldView1920
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 != null1941
? resolveItemDualTint({ itemId: layer.itemId }, layerDef)1942
: null;1943
entity.overlayDualTints.push(dualTint);1923
entity.overlayTints.push(1944
entity.overlayTints.push(1924
layer.tint1945
dualTint1925
? normalizeRgb(layer.tint)1946
? null1926
: (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)1947
: (layer.tint1948
? 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 WorldView1966
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,@@ -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;@@ -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 fi58
## 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 fi240
## 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
@@ -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
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
return effectiveSkillLevel(skills, skillId, bonuses);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
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
431
function attackerCombatLevels (ecs, attackerHandle, profile)431
function 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 = D848
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 = D983
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 = attackerLevelsOverride1158
const attackerLevels = attackerLevelsOverride1159
?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);1159
?? (attackerHandle != null1160
? 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
defenderEquipment1168
defenderEquipment,1169
world.settings1167
);1170
);1168
const defenceLevel = defenderSkillLevel(1171
const defenceLevel = defenderSkillLevel(1169
defenderSkills,1172
defenderSkills,1170
SkillId.defence,1173
SkillId.defence,1171
defenderEquipment1174
defenderEquipment,1175
world.settings1172
);1176
);1173
1177
1174
const resolved = resolvePhysicalAttack({1178
const resolved = resolvePhysicalAttack({@@ -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
diffStarterLoadout15
diffStarterLoadout16
} from "../../../shared/items/starterLoadout.js";16
} from "../../../shared/items/starterLoadout.js";17
import {18
normalizeEquipmentStatBonuses,19
diffEquipmentStatBonuses,20
equipmentStatBonusMapsEqual21
} from "../../../shared/definitions/equipmentStatCategories.js";17
import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";22
import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";18
import {23
import {19
OVERWORLD_ID,24
OVERWORLD_ID,@@ -277,6 +282,14 @@ export class EditorService277
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
else290
{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 EditorService301
const starterBullets = starterChanged314
const starterBullets = starterChanged302
? 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 = equipmentStatsChanged322
? diffEquipmentStatBonuses(323
current.equipmentStatBonuses,324
next.equipmentStatBonuses,325
(itemId) => itemDefinition(itemId)?.displayName ?? null326
)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 EditorService319
starterEquipment: changed.starterEquipment ?? current.starterEquipment343
starterEquipment: changed.starterEquipment ?? current.starterEquipment320
?? DEFAULT_WORLD_SETTINGS.starterEquipment,344
?? DEFAULT_WORLD_SETTINGS.starterEquipment,321
starterInventory: changed.starterInventory ?? current.starterInventory345
starterInventory: changed.starterInventory ?? current.starterInventory322
?? DEFAULT_WORLD_SETTINGS.starterInventory346
?? DEFAULT_WORLD_SETTINGS.starterInventory,347
equipmentStatBonuses: changed.equipmentStatBonuses348
?? 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;@@ -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
try764
{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,@@ -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 @@1
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";1
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";2
import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";2
import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";3
import { normalizeEquipmentStatBonuses } from "../../../shared/definitions/equipmentStatCategories.js";3
import {4
import {4
OVERWORLD_ID,5
OVERWORLD_ID,5
DIMENSION_PURGE_MS,6
DIMENSION_PURGE_MS,@@ -265,6 +266,7 @@ export class WorldDatabase265
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
@@ -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";23
import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";23
import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";24
import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";24
import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";25
import { Component } from "../ecs/components.js";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
export function collectSpawnRequests (world)29
export 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
dimensionId72
);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
dimensionId116
);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
reserved364
reserved,365
dim340
);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
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
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, reserved405
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
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
return !!data?.open;454
return !!data?.open;427
}455
}428
456
@@ -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";28
import { mobDefinition } from "../../../shared/definitions/mobs.js";28
import { mobDefinition } from "../../../shared/definitions/mobs.js";29
import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";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
import {32
import {31
chebyshev,33
chebyshev,32
hasCombatLineOfSight,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
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,@@ -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", () =56
test("canCraftFitInventory rejects missing inputs", () =>56
test("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
66
test("recipesForStation lists bench recipes", () =>66
test("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
73
test("canStartCraft enforces minimum skill level", () =>76
test("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
});@@ -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";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";3
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";4
import { ArmourItemId } from "../../shared/definitions/armourItems.js";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
import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";8
import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";7
import { SkillId } from "../../shared/definitions/skills.js";9
import { SkillId } from "../../shared/definitions/skills.js";8
import { normalizePlayerSkills } from "../../shared/skills/state.js";10
import { normalizePlayerSkills } from "../../shared/skills/state.js";@@ -13,6 +15,13 @@ import {13
equipmentBonusesFromSlots15
equipmentBonusesFromSlots14
} from "../../shared/equipment/stats.js";16
} from "../../shared/equipment/stats.js";15
import { emptyEquipment } from "../../shared/items/inventory.js";17
import { emptyEquipment } from "../../shared/items/inventory.js";18
import {19
assertAllBonusGearCategorized,20
defaultEquipmentStatBonuses,21
normalizeEquipmentStatBonuses,22
bonusForEquippedItem,23
diffEquipmentStatBonuses24
} from "../../shared/definitions/equipmentStatCategories.js";16
25
17
test("tier stat bonuses scale by material", () =>26
test("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
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
test("equipped weapons and armour add effective combat stats", () =>39
test("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
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
test("bronze gear equips at level 1", () =>74
test("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
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
});@@ -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"@@ -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
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
test("material tint hex converts to 0-1 rgb at load", () =>108
test("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));