BlueGit

timfa questward

Add spellcasting, leather crafting, and combat approach polish.

Spells with favourites bar, tile/entity targeting, Light and Spark, server-authoritative casts with auto-walk into range, and crafting stations/tables that no longer block ranged or magic line of sight. Skill XP growth uses 10% per level instead of doubling; leather legwear, NPC auto-equip, and assorted test fixes included.

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
2bedcc4919555f6ca94a29b3c53c7820be0f91b8
Parent
70f66bcc
65 files changed +3148 −122
client/assets/blocks/leatherworking-table/leatherworking-table.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/projectile/spell-light-0.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/projectile/spell-light-1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/projectile/spell-light-2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/projectile/spell-spark-0.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/projectile/spell-spark-1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/fx/projectile/spell-spark-2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/clothing/leather-shoes-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/clothing/leather-shoes.png added Binary file +0 −0

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

client/assets/spells/light.svg added +4 −0
@@ -0,0 +1,4 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2 <rect width="32" height="32" rx="6" fill="#c8a840"/>
3 <text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">LT</text>
4 </svg>
@@ -0,0 +1,4 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2<rect width="32" height="32" rx="6" fill="#c8a840"/>
3<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">LT</text>
4</svg>
client/assets/spells/spark.svg added +4 −0
@@ -0,0 +1,4 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2 <rect width="32" height="32" rx="6" fill="#e06030"/>
3 <text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SP</text>
4 </svg>
@@ -0,0 +1,4 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
2<rect width="32" height="32" rx="6" fill="#e06030"/>
3<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SP</text>
4</svg>
client/index.html +11 −5
@@ -12,6 +12,7 @@
12 12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 13 <button id="friends-toggle" type="button">Friends</button>
14 14 <button id="skills-toggle" type="button">Skills</button>
15 <button id="spells-toggle" type="button">Spells</button>
15 16 <button id="bag-toggle" type="button">Bag</button>
16 17 <button id="leave" type="button">Leave world</button>
17 18 </div>
@@ -50,11 +51,7 @@
50 51 <p id="bag-coins" hidden>0 coins</p>
51 52 <div id="equip-grid" class="item-grid equip"></div>
52 53 <div id="bag-grid" class="item-grid"></div>
53 <p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
54 <div class="bag-actions">
55 <button id="bag-drop" type="button">Drop</button>
56 <button id="bag-equip" type="button">Equip</button>
57 </div>
54 <p id="bag-hint" class="hint">Left-click to select. Right-click for other options.</p>
58 55 </aside>
59 56 <aside id="bank-panel" hidden>
60 57 <header>
@@ -94,6 +91,15 @@
94 91 <h2>Skills</h2>
95 92 <div id="skills-list" class="skills-grid"></div>
96 93 </aside>
94 <aside id="spells-panel" hidden>
95 <h2>Spells</h2>
96 <label class="spell-autocast-row">
97 <input id="spell-autocast-toggle" type="checkbox">
98 Auto-cast (repeat on target)
99 </label>
100 <div id="spells-list" class="spells-grid"></div>
101 </aside>
102 <div id="spell-favorites-bar" hidden></div>
97 103
98 104 <div id="send-backdrop" class="modal-backdrop" hidden></div>
99 105 <aside id="send-panel" hidden>
@@ -12,6 +12,7 @@
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 <button id="friends-toggle" type="button">Friends</button>
13 <button id="friends-toggle" type="button">Friends</button>
14 <button id="skills-toggle" type="button">Skills</button>
14 <button id="skills-toggle" type="button">Skills</button>
15 <button id="spells-toggle" type="button">Spells</button>
15 <button id="bag-toggle" type="button">Bag</button>
16 <button id="bag-toggle" type="button">Bag</button>
16 <button id="leave" type="button">Leave world</button>
17 <button id="leave" type="button">Leave world</button>
17 </div>
18 </div>
@@ -50,11 +51,7 @@
50 <p id="bag-coins" hidden>0 coins</p>
51 <p id="bag-coins" hidden>0 coins</p>
51 <div id="equip-grid" class="item-grid equip"></div>
52 <div id="equip-grid" class="item-grid equip"></div>
52 <div id="bag-grid" class="item-grid"></div>
53 <div id="bag-grid" class="item-grid"></div>
53 <p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
54 <p id="bag-hint" class="hint">Left-click to select. Right-click for other options.</p>
54 <div class="bag-actions">
55 <button id="bag-drop" type="button">Drop</button>
56 <button id="bag-equip" type="button">Equip</button>
57 </div>
58 </aside>
55 </aside>
59 <aside id="bank-panel" hidden>
56 <aside id="bank-panel" hidden>
60 <header>
57 <header>
@@ -94,6 +91,15 @@
94 <h2>Skills</h2>
91 <h2>Skills</h2>
95 <div id="skills-list" class="skills-grid"></div>
92 <div id="skills-list" class="skills-grid"></div>
96 </aside>
93 </aside>
94 <aside id="spells-panel" hidden>
95 <h2>Spells</h2>
96 <label class="spell-autocast-row">
97 <input id="spell-autocast-toggle" type="checkbox">
98 Auto-cast (repeat on target)
99 </label>
100 <div id="spells-list" class="spells-grid"></div>
101 </aside>
102 <div id="spell-favorites-bar" hidden></div>
97
103
98 <div id="send-backdrop" class="modal-backdrop" hidden></div>
104 <div id="send-backdrop" class="modal-backdrop" hidden></div>
99 <aside id="send-panel" hidden>
105 <aside id="send-panel" hidden>
client/scripts/write-legwear-sprites.mjs added +153 −0
@@ -0,0 +1,153 @@
1 /**
2 * Derive cloth shorts/trousers and leather-shoe sprites from greaves/boots overlays.
3 * Shorts: greaves with the bottom few rows cleared.
4 */
5 import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6 import { deflateSync, inflateSync } from "node:zlib";
7 import { dirname, join } from "node:path";
8 import { fileURLToPath } from "node:url";
9
10 const SIZE = 16;
11 const SHORTS_TRIM_ROWS = 4;
12 const root = join(dirname(fileURLToPath(import.meta.url)), "../assets/items");
13 const armour = join(root, "armour");
14 const clothing = join(root, "clothing");
15
16 function crcTable ()
17 {
18 const table = new Uint32Array(256);
19 for (let n = 0; n < 256; n++)
20 {
21 let c = n;
22 for (let k = 0; k < 8; k++)
23 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
24 table[n] = c >>> 0;
25 }
26 return table;
27 }
28
29 const CRC_TABLE = crcTable();
30
31 function crc32 (buf)
32 {
33 let c = 0xffffffff;
34 for (let i = 0; i < buf.length; i++)
35 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
36 return (c ^ 0xffffffff) >>> 0;
37 }
38
39 function chunk (type, data)
40 {
41 const len = Buffer.alloc(4);
42 len.writeUInt32BE(data.length);
43 const typeBuf = Buffer.from(type, "ascii");
44 const crcBuf = Buffer.alloc(4);
45 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
46 return Buffer.concat([len, typeBuf, data, crcBuf]);
47 }
48
49 function encodePng (rgba, width = SIZE, height = SIZE)
50 {
51 const raw = Buffer.alloc((width * 4 + 1) * height);
52 for (let y = 0; y < height; y++)
53 {
54 const row = y * (width * 4 + 1);
55 raw[row] = 0;
56 for (let x = 0; x < width; x++)
57 {
58 const i = (y * width + x) * 4;
59 const o = row + 1 + x * 4;
60 raw[o] = rgba[i];
61 raw[o + 1] = rgba[i + 1];
62 raw[o + 2] = rgba[i + 2];
63 raw[o + 3] = rgba[i + 3];
64 }
65 }
66 const ihdr = Buffer.alloc(13);
67 ihdr.writeUInt32BE(width, 0);
68 ihdr.writeUInt32BE(height, 4);
69 ihdr[8] = 8;
70 ihdr[9] = 6;
71 return Buffer.concat([
72 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
73 chunk("IHDR", ihdr),
74 chunk("IDAT", deflateSync(raw, { level: 9 })),
75 chunk("IEND", Buffer.alloc(0))
76 ]);
77 }
78
79 function decodePngRgba (buf)
80 {
81 let off = 8;
82 let w = 0;
83 let h = 0;
84 const idat = [];
85 while (off < buf.length)
86 {
87 const len = buf.readUInt32BE(off);
88 const type = buf.slice(off + 4, off + 8).toString("ascii");
89 const data = buf.slice(off + 8, off + 8 + len);
90 if (type === "IHDR")
91 {
92 w = data.readUInt32BE(0);
93 h = data.readUInt32BE(4);
94 }
95 else if (type === "IDAT")
96 { idat.push(data); }
97 else if (type === "IEND")
98 { break; }
99 off += 12 + len;
100 }
101 const raw = inflateSync(Buffer.concat(idat));
102 const stride = 1 + w * 4;
103 const rgba = new Uint8Array(w * h * 4);
104 for (let y = 0; y < h; y++)
105 {
106 for (let x = 0; x < w; x++)
107 {
108 const i = y * stride + 1 + x * 4;
109 const o = (y * w + x) * 4;
110 rgba[o] = raw[i];
111 rgba[o + 1] = raw[i + 1];
112 rgba[o + 2] = raw[i + 2];
113 rgba[o + 3] = raw[i + 3];
114 }
115 }
116 return { width: w, height: h, rgba };
117 }
118
119 function writePair (name, rgba)
120 {
121 mkdirSync(clothing, { recursive: true });
122 writeFileSync(join(clothing, `${name}.png`), encodePng(rgba));
123 writeFileSync(join(clothing, `${name}-equip.png`), encodePng(rgba));
124 }
125
126 function trimBottomRows (rgba, width, height, rows)
127 {
128 const next = new Uint8Array(rgba);
129 for (let y = height - rows; y < height; y++)
130 {
131 for (let x = 0; x < width; x++)
132 {
133 const o = (y * width + x) * 4;
134 next[o] = 0;
135 next[o + 1] = 0;
136 next[o + 2] = 0;
137 next[o + 3] = 0;
138 }
139 }
140 return next;
141 }
142
143 const greaves = decodePngRgba(readFileSync(join(armour, "greaves.png")));
144 const boots = decodePngRgba(readFileSync(join(armour, "boots.png")));
145
146 writePair("trousers", greaves.rgba);
147 writePair("shorts", trimBottomRows(greaves.rgba, greaves.width, greaves.height, SHORTS_TRIM_ROWS));
148 writePair("leather-shoes", boots.rgba);
149
150 mkdirSync(join(root, "leather"), { recursive: true });
151 writeFileSync(join(root, "leather", "leather.png"), encodePng(greaves.rgba));
152
153 console.log("Wrote shorts, trousers, leather-shoes, and leather icon sprites");
@@ -0,0 +1,153 @@
1/**
2 * Derive cloth shorts/trousers and leather-shoe sprites from greaves/boots overlays.
3 * Shorts: greaves with the bottom few rows cleared.
4 */
5import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6import { deflateSync, inflateSync } from "node:zlib";
7import { dirname, join } from "node:path";
8import { fileURLToPath } from "node:url";
9
10const SIZE = 16;
11const SHORTS_TRIM_ROWS = 4;
12const root = join(dirname(fileURLToPath(import.meta.url)), "../assets/items");
13const armour = join(root, "armour");
14const clothing = join(root, "clothing");
15
16function crcTable ()
17{
18 const table = new Uint32Array(256);
19 for (let n = 0; n < 256; n++)
20 {
21 let c = n;
22 for (let k = 0; k < 8; k++)
23 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
24 table[n] = c >>> 0;
25 }
26 return table;
27}
28
29const CRC_TABLE = crcTable();
30
31function crc32 (buf)
32{
33 let c = 0xffffffff;
34 for (let i = 0; i < buf.length; i++)
35 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
36 return (c ^ 0xffffffff) >>> 0;
37}
38
39function chunk (type, data)
40{
41 const len = Buffer.alloc(4);
42 len.writeUInt32BE(data.length);
43 const typeBuf = Buffer.from(type, "ascii");
44 const crcBuf = Buffer.alloc(4);
45 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
46 return Buffer.concat([len, typeBuf, data, crcBuf]);
47}
48
49function encodePng (rgba, width = SIZE, height = SIZE)
50{
51 const raw = Buffer.alloc((width * 4 + 1) * height);
52 for (let y = 0; y < height; y++)
53 {
54 const row = y * (width * 4 + 1);
55 raw[row] = 0;
56 for (let x = 0; x < width; x++)
57 {
58 const i = (y * width + x) * 4;
59 const o = row + 1 + x * 4;
60 raw[o] = rgba[i];
61 raw[o + 1] = rgba[i + 1];
62 raw[o + 2] = rgba[i + 2];
63 raw[o + 3] = rgba[i + 3];
64 }
65 }
66 const ihdr = Buffer.alloc(13);
67 ihdr.writeUInt32BE(width, 0);
68 ihdr.writeUInt32BE(height, 4);
69 ihdr[8] = 8;
70 ihdr[9] = 6;
71 return Buffer.concat([
72 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
73 chunk("IHDR", ihdr),
74 chunk("IDAT", deflateSync(raw, { level: 9 })),
75 chunk("IEND", Buffer.alloc(0))
76 ]);
77}
78
79function decodePngRgba (buf)
80{
81 let off = 8;
82 let w = 0;
83 let h = 0;
84 const idat = [];
85 while (off < buf.length)
86 {
87 const len = buf.readUInt32BE(off);
88 const type = buf.slice(off + 4, off + 8).toString("ascii");
89 const data = buf.slice(off + 8, off + 8 + len);
90 if (type === "IHDR")
91 {
92 w = data.readUInt32BE(0);
93 h = data.readUInt32BE(4);
94 }
95 else if (type === "IDAT")
96 { idat.push(data); }
97 else if (type === "IEND")
98 { break; }
99 off += 12 + len;
100 }
101 const raw = inflateSync(Buffer.concat(idat));
102 const stride = 1 + w * 4;
103 const rgba = new Uint8Array(w * h * 4);
104 for (let y = 0; y < h; y++)
105 {
106 for (let x = 0; x < w; x++)
107 {
108 const i = y * stride + 1 + x * 4;
109 const o = (y * w + x) * 4;
110 rgba[o] = raw[i];
111 rgba[o + 1] = raw[i + 1];
112 rgba[o + 2] = raw[i + 2];
113 rgba[o + 3] = raw[i + 3];
114 }
115 }
116 return { width: w, height: h, rgba };
117}
118
119function writePair (name, rgba)
120{
121 mkdirSync(clothing, { recursive: true });
122 writeFileSync(join(clothing, `${name}.png`), encodePng(rgba));
123 writeFileSync(join(clothing, `${name}-equip.png`), encodePng(rgba));
124}
125
126function trimBottomRows (rgba, width, height, rows)
127{
128 const next = new Uint8Array(rgba);
129 for (let y = height - rows; y < height; y++)
130 {
131 for (let x = 0; x < width; x++)
132 {
133 const o = (y * width + x) * 4;
134 next[o] = 0;
135 next[o + 1] = 0;
136 next[o + 2] = 0;
137 next[o + 3] = 0;
138 }
139 }
140 return next;
141}
142
143const greaves = decodePngRgba(readFileSync(join(armour, "greaves.png")));
144const boots = decodePngRgba(readFileSync(join(armour, "boots.png")));
145
146writePair("trousers", greaves.rgba);
147writePair("shorts", trimBottomRows(greaves.rgba, greaves.width, greaves.height, SHORTS_TRIM_ROWS));
148writePair("leather-shoes", boots.rgba);
149
150mkdirSync(join(root, "leather"), { recursive: true });
151writeFileSync(join(root, "leather", "leather.png"), encodePng(greaves.rgba));
152
153console.log("Wrote shorts, trousers, leather-shoes, and leather icon sprites");
client/scripts/write-spell-projectile-template.mjs added +74 −0
@@ -0,0 +1,74 @@
1 import { mkdirSync, writeFileSync } from "node:fs";
2 import { deflateSync } from "node:zlib";
3
4 const spells = [
5 { id: "spell-light", rgb: [255, 248, 192] },
6 { id: "spell-spark", rgb: [255, 144, 64] }
7 ];
8
9 mkdirSync(new URL("../assets/fx/projectile/", import.meta.url), { recursive: true });
10
11 for (const spell of spells)
12 {
13 for (let frame = 0; frame < 3; frame++)
14 {
15 const png = buildPng5(spell.rgb);
16 writeFileSync(
17 new URL(`../assets/fx/projectile/${spell.id}-${frame}.png`, import.meta.url),
18 png
19 );
20 }
21 }
22
23 function buildPng5 ([r, g, b])
24 {
25 const row = Buffer.alloc(1 + 5 * 4);
26 row[0] = 0;
27 for (let x = 0; x < 5; x++)
28 {
29 const i = 1 + x * 4;
30 row[i] = r;
31 row[i + 1] = g;
32 row[i + 2] = b;
33 row[i + 3] = x === 0 || x === 4 ? 0 : 255;
34 }
35 const raw = Buffer.concat(Array.from({ length: 5 }, () => row));
36 return encodePng(5, 5, deflateSync(raw));
37 }
38
39 function encodePng (w, h, idat)
40 {
41 const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
42 const ihdr = chunk("IHDR", (() =>
43 {
44 const buf = Buffer.alloc(13);
45 buf.writeUInt32BE(w, 0);
46 buf.writeUInt32BE(h, 4);
47 buf[8] = 8; buf[9] = 6;
48 return buf;
49 })());
50 return Buffer.concat([signature, ihdr, chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]);
51 }
52
53 function chunk (type, data)
54 {
55 const len = Buffer.alloc(4);
56 len.writeUInt32BE(data.length, 0);
57 const t = Buffer.from(type);
58 const crc = crc32(Buffer.concat([t, data]));
59 const c = Buffer.alloc(4);
60 c.writeUInt32BE(crc >>> 0, 0);
61 return Buffer.concat([len, t, data, c]);
62 }
63
64 function crc32 (buf)
65 {
66 let c = ~0;
67 for (let i = 0; i < buf.length; i++)
68 {
69 c ^= buf[i];
70 for (let k = 0; k < 8; k++)
71 { c = (c >>> 1) ^ (c & 1 ? 0xedb88320 : 0); }
72 }
73 return ~c;
74 }
@@ -0,0 +1,74 @@
1import { mkdirSync, writeFileSync } from "node:fs";
2import { deflateSync } from "node:zlib";
3
4const spells = [
5 { id: "spell-light", rgb: [255, 248, 192] },
6 { id: "spell-spark", rgb: [255, 144, 64] }
7];
8
9mkdirSync(new URL("../assets/fx/projectile/", import.meta.url), { recursive: true });
10
11for (const spell of spells)
12{
13 for (let frame = 0; frame < 3; frame++)
14 {
15 const png = buildPng5(spell.rgb);
16 writeFileSync(
17 new URL(`../assets/fx/projectile/${spell.id}-${frame}.png`, import.meta.url),
18 png
19 );
20 }
21}
22
23function buildPng5 ([r, g, b])
24{
25 const row = Buffer.alloc(1 + 5 * 4);
26 row[0] = 0;
27 for (let x = 0; x < 5; x++)
28 {
29 const i = 1 + x * 4;
30 row[i] = r;
31 row[i + 1] = g;
32 row[i + 2] = b;
33 row[i + 3] = x === 0 || x === 4 ? 0 : 255;
34 }
35 const raw = Buffer.concat(Array.from({ length: 5 }, () => row));
36 return encodePng(5, 5, deflateSync(raw));
37}
38
39function encodePng (w, h, idat)
40{
41 const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
42 const ihdr = chunk("IHDR", (() =>
43 {
44 const buf = Buffer.alloc(13);
45 buf.writeUInt32BE(w, 0);
46 buf.writeUInt32BE(h, 4);
47 buf[8] = 8; buf[9] = 6;
48 return buf;
49 })());
50 return Buffer.concat([signature, ihdr, chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]);
51}
52
53function chunk (type, data)
54{
55 const len = Buffer.alloc(4);
56 len.writeUInt32BE(data.length, 0);
57 const t = Buffer.from(type);
58 const crc = crc32(Buffer.concat([t, data]));
59 const c = Buffer.alloc(4);
60 c.writeUInt32BE(crc >>> 0, 0);
61 return Buffer.concat([len, t, data, c]);
62}
63
64function crc32 (buf)
65{
66 let c = ~0;
67 for (let i = 0; i < buf.length; i++)
68 {
69 c ^= buf[i];
70 for (let k = 0; k < 8; k++)
71 { c = (c >>> 1) ^ (c & 1 ? 0xedb88320 : 0); }
72 }
73 return ~c;
74}
client/src/play/inventory.js +7 −12
@@ -74,18 +74,6 @@ export function initInventory ({
74 74 {
75 75 bagPanel.hidden = !bagPanel.hidden;
76 76 });
77 document.getElementById("bag-drop").addEventListener("click", () =>
78 {
79 if (selected == null)
80 { return; }
81 socket.send({ type: MessageType.dropItem, slotIndex: selected });
82 });
83 document.getElementById("bag-equip").addEventListener("click", () =>
84 {
85 if (selected == null)
86 { return; }
87 socket.send({ type: MessageType.equipItem, slotIndex: selected });
88 });
89 77 document.getElementById("bank-close").addEventListener("click", () => closeBank());
90 78 document.getElementById("bank-claim").addEventListener("click", () =>
91 79 {
@@ -265,6 +253,13 @@ export function initInventory ({
265 253 });
266 254 }
267 255 }
256 if (slot.instance?.kind === "spellbook")
257 {
258 items.push({
259 label: "Study",
260 onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })
261 });
262 }
268 263 if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
269 264 {
270 265 items.push({
@@ -74,18 +74,6 @@ export function initInventory ({
74 {
74 {
75 bagPanel.hidden = !bagPanel.hidden;
75 bagPanel.hidden = !bagPanel.hidden;
76 });
76 });
77 document.getElementById("bag-drop").addEventListener("click", () =>
78 {
79 if (selected == null)
80 { return; }
81 socket.send({ type: MessageType.dropItem, slotIndex: selected });
82 });
83 document.getElementById("bag-equip").addEventListener("click", () =>
84 {
85 if (selected == null)
86 { return; }
87 socket.send({ type: MessageType.equipItem, slotIndex: selected });
88 });
89 document.getElementById("bank-close").addEventListener("click", () => closeBank());
77 document.getElementById("bank-close").addEventListener("click", () => closeBank());
90 document.getElementById("bank-claim").addEventListener("click", () =>
78 document.getElementById("bank-claim").addEventListener("click", () =>
91 {
79 {
@@ -265,6 +253,13 @@ export function initInventory ({
265 });
253 });
266 }
254 }
267 }
255 }
256 if (slot.instance?.kind === "spellbook")
257 {
258 items.push({
259 label: "Study",
260 onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })
261 });
262 }
268 if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
263 if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
269 {
264 {
270 items.push({
265 items.push({
client/src/play/main.js +89 −3
@@ -1,4 +1,5 @@
1 1 import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2 import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
2 3 import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3 4 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4 5 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
@@ -7,6 +8,7 @@ import { initSocial } from "./social.js";
7 8 import { initChat } from "./chat.js";
8 9 import { initInventory } from "./inventory.js";
9 10 import { initSkills } from "./skills.js";
11 import { initSpells } from "./spells.js";
10 12 import { initCrafting } from "./crafting.js";
11 13 import { initAlchemy } from "./alchemy.js";
12 14 import { initStamina } from "./stamina.js";
@@ -47,6 +49,7 @@ let social;
47 49 let chat;
48 50 let inventory;
49 51 let skills;
52 let spells;
50 53 let crafting;
51 54 let alchemy;
52 55 let staminaUi;
@@ -112,7 +115,16 @@ function uiBlocked ()
112 115 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
113 116 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
114 117 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
115 || contextMenu?.isOpen() || death?.isBlocking());
118 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
119 || pointerOverSpellUi());
120 }
121
122 function pointerOverSpellUi ()
123 {
124 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
125 if (!el)
126 { return false; }
127 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
116 128 }
117 129
118 130 function applyGraphicsSettings (settings)
@@ -500,6 +512,11 @@ function isAttackableEntity (entity)
500 512
501 513 function handleLeftClick (mouseX, mouseY)
502 514 {
515 const tile = view.screenToTile(mouseX, mouseY);
516 const armed = spells?.getArmedSpell?.();
517 if (armed?.target === "tile" && armed.canCast && spells.tryCastAtTile(tile.tileX, tile.tileY))
518 { return; }
519
503 520 const entity = view.entityAtScreen(mouseX, mouseY);
504 521 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
505 522 {
@@ -517,6 +534,8 @@ function handleLeftClick (mouseX, mouseY)
517 534 }
518 535 if (isAttackableEntity(entity))
519 536 {
537 if (spells?.tryCastAtEntity?.(entity.entityId))
538 { return; }
520 539 requestAttack(entity.entityId);
521 540 return;
522 541 }
@@ -524,7 +543,6 @@ function handleLeftClick (mouseX, mouseY)
524 543 return;
525 544 }
526 545
527 const tile = view.screenToTile(mouseX, mouseY);
528 546 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
529 547 if (ground)
530 548 { requestPickup(ground); }
@@ -568,6 +586,12 @@ function handleLeftClick (mouseX, mouseY)
568 586 function handleRightClick (event, mouseX, mouseY)
569 587 {
570 588 event.preventDefault();
589 if (spells?.isTargeting?.())
590 {
591 spells.cancelTargeting();
592 view?.clearSpellTargetHighlight();
593 return;
594 }
571 595 const tile = view.screenToTile(mouseX, mouseY);
572 596 const items = [];
573 597 const walkTileX = tile.tileX;
@@ -847,10 +871,14 @@ function startPlay (payload)
847 871 flushPendingInteract();
848 872 social?.updateNametag(view, scene, view.localEntityId);
849 873 chat?.update(view, scene);
874 updateSpellTargetHighlight();
850 875 updateWorldTooltip();
851 876 }
852 877 else
853 { hideWorldTooltip(); }
878 {
879 hideWorldTooltip();
880 view?.clearSpellTargetHighlight();
881 }
854 882 view.update(dt);
855 883 };
856 884 scene.addObject(ticker);
@@ -943,6 +971,10 @@ async function main ()
943 971 }
944 972 });
945 973 skills = initSkills();
974 spells = initSpells({
975 socket: { send (payload) { socket.send(payload); } },
976 MessageType
977 });
946 978 crafting = initCrafting({
947 979 socket: { send (payload) { socket.send(payload); } },
948 980 MessageType,
@@ -1100,6 +1132,34 @@ async function main ()
1100 1132 skills?.render(message.skills);
1101 1133 crafting?.refresh();
1102 1134 break;
1135 case MessageType.spells:
1136 case MessageType.spellsUpdated:
1137 spells?.render(message);
1138 break;
1139 case MessageType.spellArmed:
1140 spells?.handleSpellArmed(message);
1141 break;
1142 case MessageType.spellDisarmed:
1143 spells?.handleSpellDisarmed();
1144 break;
1145 case MessageType.spellProjectile:
1146 view?.spawnSpellProjectileFx(message);
1147 break;
1148 case MessageType.spellFizzle:
1149 view?.spawnSpellFizzleFx(message);
1150 if (message.casterId === view?.localEntityId)
1151 { toasts?.show("Failed to cast spell"); }
1152 break;
1153 case MessageType.spellCastFlash:
1154 view?.spawnSpellCastFlash(message);
1155 break;
1156 case MessageType.spellLightAppear:
1157 case MessageType.spellLightUpdate:
1158 view?.setSpellLight(message);
1159 break;
1160 case MessageType.spellLightRemove:
1161 view?.removeSpellLight(message);
1162 break;
1103 1163 case MessageType.stamina:
1104 1164 staminaUi?.apply(message);
1105 1165 if (message.gait)
@@ -1313,6 +1373,7 @@ function returnToMenu (reason = "")
1313 1373 healthUi?.hide();
1314 1374 statusEffectsUi?.hide();
1315 1375 skills?.hide();
1376 spells?.hide();
1316 1377 contextMenu?.hide();
1317 1378 death?.reset();
1318 1379 shop?.close({ notifyServer: false });
@@ -1461,6 +1522,31 @@ function isPickablePlantTile (view, tileX, tileY)
1461 1522 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1462 1523 }
1463 1524
1525 function updateSpellTargetHighlight ()
1526 {
1527 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
1528 {
1529 view?.clearSpellTargetHighlight();
1530 return;
1531 }
1532 const canvas = scene?.canvas;
1533 if (!canvas)
1534 { return; }
1535 const rect = canvas.getBoundingClientRect();
1536 const mouseX = GameInput.mousePosition.x - rect.left;
1537 const mouseY = GameInput.mousePosition.y - rect.top;
1538 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1539 {
1540 view.clearSpellTargetHighlight();
1541 return;
1542 }
1543 const tile = view.screenToTile(mouseX, mouseY);
1544 const local = view.entities.get(view.localEntityId);
1545 const inRange = !local
1546 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
1547 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
1548 }
1549
1464 1550 function hideWorldTooltip ()
1465 1551 {
1466 1552 if (worldTooltip)
@@ -1,4 +1,5 @@
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
2import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
@@ -7,6 +8,7 @@ import { initSocial } from "./social.js";
7import { initChat } from "./chat.js";
8import { initChat } from "./chat.js";
8import { initInventory } from "./inventory.js";
9import { initInventory } from "./inventory.js";
9import { initSkills } from "./skills.js";
10import { initSkills } from "./skills.js";
11import { initSpells } from "./spells.js";
10import { initCrafting } from "./crafting.js";
12import { initCrafting } from "./crafting.js";
11import { initAlchemy } from "./alchemy.js";
13import { initAlchemy } from "./alchemy.js";
12import { initStamina } from "./stamina.js";
14import { initStamina } from "./stamina.js";
@@ -47,6 +49,7 @@ let social;
47let chat;
49let chat;
48let inventory;
50let inventory;
49let skills;
51let skills;
52let spells;
50let crafting;
53let crafting;
51let alchemy;
54let alchemy;
52let staminaUi;
55let staminaUi;
@@ -112,7 +115,16 @@ function uiBlocked ()
112 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
115 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
113 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
116 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
114 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
117 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
115 || contextMenu?.isOpen() || death?.isBlocking());
118 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
119 || pointerOverSpellUi());
120}
121
122function pointerOverSpellUi ()
123{
124 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
125 if (!el)
126 { return false; }
127 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
116}
128}
117
129
118function applyGraphicsSettings (settings)
130function applyGraphicsSettings (settings)
@@ -500,6 +512,11 @@ function isAttackableEntity (entity)
500
512
501function handleLeftClick (mouseX, mouseY)
513function handleLeftClick (mouseX, mouseY)
502{
514{
515 const tile = view.screenToTile(mouseX, mouseY);
516 const armed = spells?.getArmedSpell?.();
517 if (armed?.target === "tile" && armed.canCast && spells.tryCastAtTile(tile.tileX, tile.tileY))
518 { return; }
519
503 const entity = view.entityAtScreen(mouseX, mouseY);
520 const entity = view.entityAtScreen(mouseX, mouseY);
504 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
521 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
505 {
522 {
@@ -517,6 +534,8 @@ function handleLeftClick (mouseX, mouseY)
517 }
534 }
518 if (isAttackableEntity(entity))
535 if (isAttackableEntity(entity))
519 {
536 {
537 if (spells?.tryCastAtEntity?.(entity.entityId))
538 { return; }
520 requestAttack(entity.entityId);
539 requestAttack(entity.entityId);
521 return;
540 return;
522 }
541 }
@@ -524,7 +543,6 @@ function handleLeftClick (mouseX, mouseY)
524 return;
543 return;
525 }
544 }
526
545
527 const tile = view.screenToTile(mouseX, mouseY);
528 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
546 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
529 if (ground)
547 if (ground)
530 { requestPickup(ground); }
548 { requestPickup(ground); }
@@ -568,6 +586,12 @@ function handleLeftClick (mouseX, mouseY)
568function handleRightClick (event, mouseX, mouseY)
586function handleRightClick (event, mouseX, mouseY)
569{
587{
570 event.preventDefault();
588 event.preventDefault();
589 if (spells?.isTargeting?.())
590 {
591 spells.cancelTargeting();
592 view?.clearSpellTargetHighlight();
593 return;
594 }
571 const tile = view.screenToTile(mouseX, mouseY);
595 const tile = view.screenToTile(mouseX, mouseY);
572 const items = [];
596 const items = [];
573 const walkTileX = tile.tileX;
597 const walkTileX = tile.tileX;
@@ -847,10 +871,14 @@ function startPlay (payload)
847 flushPendingInteract();
871 flushPendingInteract();
848 social?.updateNametag(view, scene, view.localEntityId);
872 social?.updateNametag(view, scene, view.localEntityId);
849 chat?.update(view, scene);
873 chat?.update(view, scene);
874 updateSpellTargetHighlight();
850 updateWorldTooltip();
875 updateWorldTooltip();
851 }
876 }
852 else
877 else
853 { hideWorldTooltip(); }
878 {
879 hideWorldTooltip();
880 view?.clearSpellTargetHighlight();
881 }
854 view.update(dt);
882 view.update(dt);
855 };
883 };
856 scene.addObject(ticker);
884 scene.addObject(ticker);
@@ -943,6 +971,10 @@ async function main ()
943 }
971 }
944 });
972 });
945 skills = initSkills();
973 skills = initSkills();
974 spells = initSpells({
975 socket: { send (payload) { socket.send(payload); } },
976 MessageType
977 });
946 crafting = initCrafting({
978 crafting = initCrafting({
947 socket: { send (payload) { socket.send(payload); } },
979 socket: { send (payload) { socket.send(payload); } },
948 MessageType,
980 MessageType,
@@ -1100,6 +1132,34 @@ async function main ()
1100 skills?.render(message.skills);
1132 skills?.render(message.skills);
1101 crafting?.refresh();
1133 crafting?.refresh();
1102 break;
1134 break;
1135 case MessageType.spells:
1136 case MessageType.spellsUpdated:
1137 spells?.render(message);
1138 break;
1139 case MessageType.spellArmed:
1140 spells?.handleSpellArmed(message);
1141 break;
1142 case MessageType.spellDisarmed:
1143 spells?.handleSpellDisarmed();
1144 break;
1145 case MessageType.spellProjectile:
1146 view?.spawnSpellProjectileFx(message);
1147 break;
1148 case MessageType.spellFizzle:
1149 view?.spawnSpellFizzleFx(message);
1150 if (message.casterId === view?.localEntityId)
1151 { toasts?.show("Failed to cast spell"); }
1152 break;
1153 case MessageType.spellCastFlash:
1154 view?.spawnSpellCastFlash(message);
1155 break;
1156 case MessageType.spellLightAppear:
1157 case MessageType.spellLightUpdate:
1158 view?.setSpellLight(message);
1159 break;
1160 case MessageType.spellLightRemove:
1161 view?.removeSpellLight(message);
1162 break;
1103 case MessageType.stamina:
1163 case MessageType.stamina:
1104 staminaUi?.apply(message);
1164 staminaUi?.apply(message);
1105 if (message.gait)
1165 if (message.gait)
@@ -1313,6 +1373,7 @@ function returnToMenu (reason = "")
1313 healthUi?.hide();
1373 healthUi?.hide();
1314 statusEffectsUi?.hide();
1374 statusEffectsUi?.hide();
1315 skills?.hide();
1375 skills?.hide();
1376 spells?.hide();
1316 contextMenu?.hide();
1377 contextMenu?.hide();
1317 death?.reset();
1378 death?.reset();
1318 shop?.close({ notifyServer: false });
1379 shop?.close({ notifyServer: false });
@@ -1461,6 +1522,31 @@ function isPickablePlantTile (view, tileX, tileY)
1461 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1522 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1462}
1523}
1463
1524
1525function updateSpellTargetHighlight ()
1526{
1527 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
1528 {
1529 view?.clearSpellTargetHighlight();
1530 return;
1531 }
1532 const canvas = scene?.canvas;
1533 if (!canvas)
1534 { return; }
1535 const rect = canvas.getBoundingClientRect();
1536 const mouseX = GameInput.mousePosition.x - rect.left;
1537 const mouseY = GameInput.mousePosition.y - rect.top;
1538 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1539 {
1540 view.clearSpellTargetHighlight();
1541 return;
1542 }
1543 const tile = view.screenToTile(mouseX, mouseY);
1544 const local = view.entities.get(view.localEntityId);
1545 const inRange = !local
1546 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
1547 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
1548}
1549
1464function hideWorldTooltip ()
1550function hideWorldTooltip ()
1465{
1551{
1466 if (worldTooltip)
1552 if (worldTooltip)
client/src/play/spells.js added +227 −0
@@ -0,0 +1,227 @@
1 export function initSpells ({ socket, MessageType })
2 {
3 const panel = document.getElementById("spells-panel");
4 const list = document.getElementById("spells-list");
5 const bar = document.getElementById("spell-favorites-bar");
6 const autoCastToggle = document.getElementById("spell-autocast-toggle");
7 let spells = [];
8 let autoCast = false;
9 let armedSpellId = null;
10
11 document.getElementById("spells-toggle")?.addEventListener("click", () =>
12 {
13 panel.hidden = !panel.hidden;
14 });
15
16 autoCastToggle?.addEventListener("change", () =>
17 {
18 socket.send({
19 type: MessageType.setSpellAutoCast,
20 enabled: autoCastToggle.checked
21 });
22 });
23
24 function disarmLocal ()
25 {
26 if (!armedSpellId)
27 { return; }
28 armedSpellId = null;
29 renderList();
30 renderBar();
31 }
32
33 function render (payload)
34 {
35 spells = payload?.spells ?? [];
36 autoCast = !!payload?.autoCast;
37 if (payload?.armedSpellId !== undefined)
38 { armedSpellId = payload.armedSpellId; }
39 if (autoCastToggle)
40 { autoCastToggle.checked = autoCast; }
41 renderList();
42 renderBar();
43 }
44
45 function renderList ()
46 {
47 list.replaceChildren();
48 for (const spell of spells)
49 {
50 list.append(renderSpellRow(spell));
51 }
52 }
53
54 function renderSpellRow (spell)
55 {
56 const row = document.createElement("div");
57 row.className = "spell-row";
58 if (spell.spellId === armedSpellId)
59 { row.classList.add("armed"); }
60
61 const icon = document.createElement("img");
62 icon.className = "spell-icon";
63 icon.src = spell.icon;
64 icon.alt = "";
65 icon.loading = "lazy";
66
67 const body = document.createElement("div");
68 body.className = "spell-body";
69
70 const title = document.createElement("div");
71 title.className = "spell-title";
72 title.textContent = spell.displayName;
73
74 const desc = document.createElement("div");
75 desc.className = "spell-desc hint";
76 desc.textContent = spell.description ?? "";
77
78 const actions = document.createElement("div");
79 actions.className = "spell-actions";
80
81 const favorite = document.createElement("button");
82 favorite.type = "button";
83 favorite.className = "spell-favorite-btn";
84 favorite.textContent = spell.favorite ? "★" : "☆";
85 favorite.title = spell.canFavorite
86 ? (spell.favorite ? "Remove from favourites" : "Add to favourites")
87 : "Magic level too low to favourite";
88 favorite.disabled = !spell.canFavorite;
89 favorite.addEventListener("click", () =>
90 {
91 socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
92 });
93
94 const arm = document.createElement("button");
95 arm.type = "button";
96 arm.className = "spell-arm-btn";
97 arm.textContent = spell.spellId === armedSpellId ? "Armed" : "Arm";
98 arm.disabled = !spell.canCast;
99 arm.addEventListener("click", () =>
100 {
101 if (spell.spellId === armedSpellId)
102 { cancelTargeting(); }
103 else
104 { socket.send({ type: MessageType.armSpell, spellId: spell.spellId }); }
105 });
106
107 actions.append(favorite, arm);
108 body.append(title, desc, actions);
109 row.append(icon, body);
110 return row;
111 }
112
113 function renderBar ()
114 {
115 const favorites = spells.filter((entry) => entry.favorite);
116 bar.replaceChildren();
117 bar.hidden = favorites.length === 0;
118 for (const spell of favorites)
119 {
120 const btn = document.createElement("button");
121 btn.type = "button";
122 btn.className = "spell-favorite-slot";
123 if (spell.spellId === armedSpellId)
124 { btn.classList.add("armed"); }
125 btn.title = spell.displayName;
126 btn.disabled = !spell.canCast;
127
128 const icon = document.createElement("img");
129 icon.src = spell.icon;
130 icon.alt = "";
131 btn.append(icon);
132
133 btn.addEventListener("click", () =>
134 {
135 if (spell.spellId === armedSpellId)
136 { return; }
137 socket.send({ type: MessageType.armSpell, spellId: spell.spellId });
138 });
139 btn.addEventListener("contextmenu", (event) =>
140 {
141 event.preventDefault();
142 socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
143 });
144 bar.append(btn);
145 }
146 }
147
148 function getArmedSpell ()
149 {
150 if (!armedSpellId)
151 { return null; }
152 return spells.find((entry) => entry.spellId === armedSpellId) ?? null;
153 }
154
155 function tryCastAtTile (tileX, tileY)
156 {
157 const armed = getArmedSpell();
158 if (!armed || armed.target !== "tile" || !armed.canCast)
159 { return false; }
160 socket.send({
161 type: MessageType.castSpellTile,
162 spellId: armed.spellId,
163 tileX,
164 tileY
165 });
166 return true;
167 }
168
169 function tryCastAtEntity (targetEntityId)
170 {
171 const armed = getArmedSpell();
172 if (!armed || armed.target !== "entity" || !armed.canCast)
173 { return false; }
174 socket.send({
175 type: MessageType.castSpellEntity,
176 spellId: armed.spellId,
177 targetEntityId
178 });
179 return true;
180 }
181
182 function cancelTargeting ()
183 {
184 if (!armedSpellId)
185 { return; }
186 socket.send({ type: MessageType.cancelArmSpell });
187 disarmLocal();
188 }
189
190 return {
191 render,
192 getArmedSpell,
193 tryCastAtTile,
194 tryCastAtEntity,
195 cancelTargeting,
196 isBlocking ()
197 {
198 return panel != null && !panel.hidden;
199 },
200 isTargeting ()
201 {
202 return armedSpellId != null;
203 },
204 handleSpellArmed (message)
205 {
206 armedSpellId = message.spellId ?? null;
207 renderList();
208 renderBar();
209 },
210 handleSpellDisarmed ()
211 {
212 disarmLocal();
213 },
214 hide ()
215 {
216 panel.hidden = true;
217 spells = [];
218 autoCast = false;
219 armedSpellId = null;
220 if (autoCastToggle)
221 { autoCastToggle.checked = false; }
222 list.replaceChildren();
223 bar.replaceChildren();
224 bar.hidden = true;
225 }
226 };
227 }
@@ -0,0 +1,227 @@
1export function initSpells ({ socket, MessageType })
2{
3 const panel = document.getElementById("spells-panel");
4 const list = document.getElementById("spells-list");
5 const bar = document.getElementById("spell-favorites-bar");
6 const autoCastToggle = document.getElementById("spell-autocast-toggle");
7 let spells = [];
8 let autoCast = false;
9 let armedSpellId = null;
10
11 document.getElementById("spells-toggle")?.addEventListener("click", () =>
12 {
13 panel.hidden = !panel.hidden;
14 });
15
16 autoCastToggle?.addEventListener("change", () =>
17 {
18 socket.send({
19 type: MessageType.setSpellAutoCast,
20 enabled: autoCastToggle.checked
21 });
22 });
23
24 function disarmLocal ()
25 {
26 if (!armedSpellId)
27 { return; }
28 armedSpellId = null;
29 renderList();
30 renderBar();
31 }
32
33 function render (payload)
34 {
35 spells = payload?.spells ?? [];
36 autoCast = !!payload?.autoCast;
37 if (payload?.armedSpellId !== undefined)
38 { armedSpellId = payload.armedSpellId; }
39 if (autoCastToggle)
40 { autoCastToggle.checked = autoCast; }
41 renderList();
42 renderBar();
43 }
44
45 function renderList ()
46 {
47 list.replaceChildren();
48 for (const spell of spells)
49 {
50 list.append(renderSpellRow(spell));
51 }
52 }
53
54 function renderSpellRow (spell)
55 {
56 const row = document.createElement("div");
57 row.className = "spell-row";
58 if (spell.spellId === armedSpellId)
59 { row.classList.add("armed"); }
60
61 const icon = document.createElement("img");
62 icon.className = "spell-icon";
63 icon.src = spell.icon;
64 icon.alt = "";
65 icon.loading = "lazy";
66
67 const body = document.createElement("div");
68 body.className = "spell-body";
69
70 const title = document.createElement("div");
71 title.className = "spell-title";
72 title.textContent = spell.displayName;
73
74 const desc = document.createElement("div");
75 desc.className = "spell-desc hint";
76 desc.textContent = spell.description ?? "";
77
78 const actions = document.createElement("div");
79 actions.className = "spell-actions";
80
81 const favorite = document.createElement("button");
82 favorite.type = "button";
83 favorite.className = "spell-favorite-btn";
84 favorite.textContent = spell.favorite ? "★" : "☆";
85 favorite.title = spell.canFavorite
86 ? (spell.favorite ? "Remove from favourites" : "Add to favourites")
87 : "Magic level too low to favourite";
88 favorite.disabled = !spell.canFavorite;
89 favorite.addEventListener("click", () =>
90 {
91 socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
92 });
93
94 const arm = document.createElement("button");
95 arm.type = "button";
96 arm.className = "spell-arm-btn";
97 arm.textContent = spell.spellId === armedSpellId ? "Armed" : "Arm";
98 arm.disabled = !spell.canCast;
99 arm.addEventListener("click", () =>
100 {
101 if (spell.spellId === armedSpellId)
102 { cancelTargeting(); }
103 else
104 { socket.send({ type: MessageType.armSpell, spellId: spell.spellId }); }
105 });
106
107 actions.append(favorite, arm);
108 body.append(title, desc, actions);
109 row.append(icon, body);
110 return row;
111 }
112
113 function renderBar ()
114 {
115 const favorites = spells.filter((entry) => entry.favorite);
116 bar.replaceChildren();
117 bar.hidden = favorites.length === 0;
118 for (const spell of favorites)
119 {
120 const btn = document.createElement("button");
121 btn.type = "button";
122 btn.className = "spell-favorite-slot";
123 if (spell.spellId === armedSpellId)
124 { btn.classList.add("armed"); }
125 btn.title = spell.displayName;
126 btn.disabled = !spell.canCast;
127
128 const icon = document.createElement("img");
129 icon.src = spell.icon;
130 icon.alt = "";
131 btn.append(icon);
132
133 btn.addEventListener("click", () =>
134 {
135 if (spell.spellId === armedSpellId)
136 { return; }
137 socket.send({ type: MessageType.armSpell, spellId: spell.spellId });
138 });
139 btn.addEventListener("contextmenu", (event) =>
140 {
141 event.preventDefault();
142 socket.send({ type: MessageType.setSpellFavorite, spellId: spell.spellId });
143 });
144 bar.append(btn);
145 }
146 }
147
148 function getArmedSpell ()
149 {
150 if (!armedSpellId)
151 { return null; }
152 return spells.find((entry) => entry.spellId === armedSpellId) ?? null;
153 }
154
155 function tryCastAtTile (tileX, tileY)
156 {
157 const armed = getArmedSpell();
158 if (!armed || armed.target !== "tile" || !armed.canCast)
159 { return false; }
160 socket.send({
161 type: MessageType.castSpellTile,
162 spellId: armed.spellId,
163 tileX,
164 tileY
165 });
166 return true;
167 }
168
169 function tryCastAtEntity (targetEntityId)
170 {
171 const armed = getArmedSpell();
172 if (!armed || armed.target !== "entity" || !armed.canCast)
173 { return false; }
174 socket.send({
175 type: MessageType.castSpellEntity,
176 spellId: armed.spellId,
177 targetEntityId
178 });
179 return true;
180 }
181
182 function cancelTargeting ()
183 {
184 if (!armedSpellId)
185 { return; }
186 socket.send({ type: MessageType.cancelArmSpell });
187 disarmLocal();
188 }
189
190 return {
191 render,
192 getArmedSpell,
193 tryCastAtTile,
194 tryCastAtEntity,
195 cancelTargeting,
196 isBlocking ()
197 {
198 return panel != null && !panel.hidden;
199 },
200 isTargeting ()
201 {
202 return armedSpellId != null;
203 },
204 handleSpellArmed (message)
205 {
206 armedSpellId = message.spellId ?? null;
207 renderList();
208 renderBar();
209 },
210 handleSpellDisarmed ()
211 {
212 disarmLocal();
213 },
214 hide ()
215 {
216 panel.hidden = true;
217 spells = [];
218 autoCast = false;
219 armedSpellId = null;
220 if (autoCastToggle)
221 { autoCastToggle.checked = false; }
222 list.replaceChildren();
223 bar.replaceChildren();
224 bar.hidden = true;
225 }
226 };
227}
client/src/play/statusEffects.js +3 −3
@@ -42,7 +42,7 @@ export function initStatusEffects ()
42 42
43 43 function remainingMs (entry, now = Date.now())
44 44 {
45 return Math.max(0, (entry.expiresAt | 0) - now);
45 return Math.max(0, Number(entry.expiresAt) - now);
46 46 }
47 47
48 48 function prune (now = Date.now())
@@ -173,10 +173,10 @@ export function initStatusEffects ()
173 173 {
174 174 const list = Array.isArray(message?.effects) ? message.effects : [];
175 175 effects = list
176 .filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())
176 .filter((entry) => entry?.type && Number(entry.expiresAt) > Date.now())
177 177 .map((entry) => ({
178 178 type: entry.type,
179 expiresAt: entry.expiresAt | 0,
179 expiresAt: Number(entry.expiresAt) || 0,
180 180 amount: entry.amount | 0,
181 181 amountPerSecond: Number(entry.amountPerSecond) || 0,
182 182 scale: entry.scale ?? null,
@@ -42,7 +42,7 @@ export function initStatusEffects ()
42
42
43 function remainingMs (entry, now = Date.now())
43 function remainingMs (entry, now = Date.now())
44 {
44 {
45 return Math.max(0, (entry.expiresAt | 0) - now);
45 return Math.max(0, Number(entry.expiresAt) - now);
46 }
46 }
47
47
48 function prune (now = Date.now())
48 function prune (now = Date.now())
@@ -173,10 +173,10 @@ export function initStatusEffects ()
173 {
173 {
174 const list = Array.isArray(message?.effects) ? message.effects : [];
174 const list = Array.isArray(message?.effects) ? message.effects : [];
175 effects = list
175 effects = list
176 .filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())
176 .filter((entry) => entry?.type && Number(entry.expiresAt) > Date.now())
177 .map((entry) => ({
177 .map((entry) => ({
178 type: entry.type,
178 type: entry.type,
179 expiresAt: entry.expiresAt | 0,
179 expiresAt: Number(entry.expiresAt) || 0,
180 amount: entry.amount | 0,
180 amount: entry.amount | 0,
181 amountPerSecond: Number(entry.amountPerSecond) || 0,
181 amountPerSecond: Number(entry.amountPerSecond) || 0,
182 scale: entry.scale ?? null,
182 scale: entry.scale ?? null,
client/src/render/sprites.js +3 −1
@@ -5,7 +5,9 @@ export const UTILITY_IMAGES = [
5 5 { name: "night-shade", url: shadeDataUrl("#000000") },
6 6 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
7 7 { name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
8 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") }
8 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") },
9 { name: "spell-target-tile", url: shadeDataUrl("rgba(110, 220, 255, 0.62)") },
10 { name: "spell-target-invalid", url: shadeDataUrl("rgba(255, 72, 72, 0.48)") }
9 11 ];
10 12
11 13 export function playImagesFromCatalog (catalog)
@@ -5,7 +5,9 @@ export const UTILITY_IMAGES = [
5 { name: "night-shade", url: shadeDataUrl("#000000") },
5 { name: "night-shade", url: shadeDataUrl("#000000") },
6 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
6 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
7 { name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
7 { name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
8 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") }
8 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") },
9 { name: "spell-target-tile", url: shadeDataUrl("rgba(110, 220, 255, 0.62)") },
10 { name: "spell-target-invalid", url: shadeDataUrl("rgba(255, 72, 72, 0.48)") }
9];
11];
10
12
11export function playImagesFromCatalog (catalog)
13export function playImagesFromCatalog (catalog)
client/src/render/worldView.js +46 −0
@@ -360,6 +360,7 @@ export class WorldView
360 360 this.editorSpawners = new Map();
361 361 this.spawnRangeHighlight = null;
362 362 this.wanderRangeHighlight = null;
363 this.spellTargetHighlight = null;
363 364 this.#syncBloomLayer();
364 365 }
365 366
@@ -725,6 +726,7 @@ export class WorldView
725 726 this.#redrawPreview();
726 727 this.#relayoutEditorSpawners();
727 728 this.#relayoutSpawnRangeHighlight();
729 this.#relayoutSpellTargetHighlight();
728 730 applyNearestToAllTextures(this.scene, this.game.images);
729 731 }
730 732
@@ -1246,6 +1248,50 @@ export class WorldView
1246 1248 this.wanderRangeHighlight = null;
1247 1249 }
1248 1250
1251 setSpellTargetHighlight (tileX, tileY, inRange = true)
1252 {
1253 if (
1254 this.spellTargetHighlight
1255 && this.spellTargetHighlight.tileX === tileX
1256 && this.spellTargetHighlight.tileY === tileY
1257 && this.spellTargetHighlight.inRange === inRange
1258 )
1259 {
1260 this.#relayoutSpellTargetHighlight();
1261 return;
1262 }
1263 this.clearSpellTargetHighlight();
1264 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1265 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1266 if (!object)
1267 { return; }
1268 this.#markUnlit(object);
1269 object.renderer.alpha = 1;
1270 this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName };
1271 this.#relayoutSpellTargetHighlight();
1272 }
1273
1274 clearSpellTargetHighlight ()
1275 {
1276 this.spellTargetHighlight?.object?.destroy();
1277 this.spellTargetHighlight = null;
1278 }
1279
1280 #relayoutSpellTargetHighlight ()
1281 {
1282 const highlight = this.spellTargetHighlight;
1283 if (!highlight?.object)
1284 { return; }
1285 const size = this.tileSize();
1286 const left = highlight.tileX * size;
1287 const top = highlight.tileY * size;
1288 highlight.object.transform.position.x = left + size / 2;
1289 highlight.object.transform.position.y = top + size / 2;
1290 highlight.object.transform.size = new vector(size, size);
1291 highlight.object.layer = LAYER_EDGE - 1;
1292 this.#markSortDirty();
1293 }
1294
1249 1295 #relayoutSpawnRangeHighlight ()
1250 1296 {
1251 1297 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
@@ -360,6 +360,7 @@ export class WorldView
360 this.editorSpawners = new Map();
360 this.editorSpawners = new Map();
361 this.spawnRangeHighlight = null;
361 this.spawnRangeHighlight = null;
362 this.wanderRangeHighlight = null;
362 this.wanderRangeHighlight = null;
363 this.spellTargetHighlight = null;
363 this.#syncBloomLayer();
364 this.#syncBloomLayer();
364 }
365 }
365
366
@@ -725,6 +726,7 @@ export class WorldView
725 this.#redrawPreview();
726 this.#redrawPreview();
726 this.#relayoutEditorSpawners();
727 this.#relayoutEditorSpawners();
727 this.#relayoutSpawnRangeHighlight();
728 this.#relayoutSpawnRangeHighlight();
729 this.#relayoutSpellTargetHighlight();
728 applyNearestToAllTextures(this.scene, this.game.images);
730 applyNearestToAllTextures(this.scene, this.game.images);
729 }
731 }
730
732
@@ -1246,6 +1248,50 @@ export class WorldView
1246 this.wanderRangeHighlight = null;
1248 this.wanderRangeHighlight = null;
1247 }
1249 }
1248
1250
1251 setSpellTargetHighlight (tileX, tileY, inRange = true)
1252 {
1253 if (
1254 this.spellTargetHighlight
1255 && this.spellTargetHighlight.tileX === tileX
1256 && this.spellTargetHighlight.tileY === tileY
1257 && this.spellTargetHighlight.inRange === inRange
1258 )
1259 {
1260 this.#relayoutSpellTargetHighlight();
1261 return;
1262 }
1263 this.clearSpellTargetHighlight();
1264 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1265 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1266 if (!object)
1267 { return; }
1268 this.#markUnlit(object);
1269 object.renderer.alpha = 1;
1270 this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName };
1271 this.#relayoutSpellTargetHighlight();
1272 }
1273
1274 clearSpellTargetHighlight ()
1275 {
1276 this.spellTargetHighlight?.object?.destroy();
1277 this.spellTargetHighlight = null;
1278 }
1279
1280 #relayoutSpellTargetHighlight ()
1281 {
1282 const highlight = this.spellTargetHighlight;
1283 if (!highlight?.object)
1284 { return; }
1285 const size = this.tileSize();
1286 const left = highlight.tileX * size;
1287 const top = highlight.tileY * size;
1288 highlight.object.transform.position.x = left + size / 2;
1289 highlight.object.transform.position.y = top + size / 2;
1290 highlight.object.transform.size = new vector(size, size);
1291 highlight.object.layer = LAYER_EDGE - 1;
1292 this.#markSortDirty();
1293 }
1294
1249 #relayoutSpawnRangeHighlight ()
1295 #relayoutSpawnRangeHighlight ()
1250 {
1296 {
1251 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
1297 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
client/ui/play.css +147 −0
@@ -509,6 +509,151 @@ a { color: #d4c48a; }
509 509 transition: width 0.25s ease-out;
510 510 }
511 511
512 #spells-panel {
513 position: fixed;
514 z-index: 5;
515 top: 50%;
516 left: 50%;
517 transform: translate(-50%, -50%);
518 width: min(520px, 94vw);
519 max-height: calc(100vh - 80px);
520 overflow: auto;
521 background: #1a1e26;
522 border: 1px solid #2c3340;
523 padding: 0.75rem;
524 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
525 }
526
527 .spell-autocast-row {
528 display: flex;
529 align-items: center;
530 gap: 0.5rem;
531 margin: 0.35rem 0 0.75rem;
532 font-size: 0.92rem;
533 color: #c8d0dc;
534 }
535
536 .spells-grid {
537 display: grid;
538 grid-template-columns: 1fr;
539 gap: 0.55rem;
540 margin: 0.5rem 0;
541 }
542
543 .spell-row {
544 display: flex;
545 gap: 0.55rem;
546 align-items: stretch;
547 min-width: 0;
548 padding: 0.45rem;
549 border: 1px solid #2c3340;
550 border-radius: 8px;
551 background: #12151b;
552 }
553
554 .spell-row.armed {
555 border-color: #6eb5ff;
556 box-shadow: 0 0 0 1px rgba(110, 181, 255, 0.35);
557 }
558
559 .spell-icon {
560 flex: 0 0 36px;
561 width: 36px;
562 height: 36px;
563 border-radius: 6px;
564 background: #101216;
565 border: 1px solid #3a4250;
566 }
567
568 .spell-body {
569 flex: 1;
570 display: flex;
571 flex-direction: column;
572 gap: 0.25rem;
573 min-width: 0;
574 }
575
576 .spell-title {
577 font-weight: 600;
578 color: #eef2f8;
579 }
580
581 .spell-desc {
582 margin: 0;
583 font-size: 0.86rem;
584 line-height: 1.35;
585 }
586
587 .spell-actions {
588 display: flex;
589 gap: 0.4rem;
590 margin-top: 0.15rem;
591 }
592
593 .spell-favorite-btn,
594 .spell-arm-btn {
595 font: inherit;
596 font-size: 0.85rem;
597 padding: 0.2rem 0.55rem;
598 border-radius: 6px;
599 border: 1px solid #3a4250;
600 background: #1f2430;
601 color: #eef2f8;
602 cursor: pointer;
603 }
604
605 .spell-favorite-btn:disabled,
606 .spell-arm-btn:disabled {
607 opacity: 0.45;
608 cursor: not-allowed;
609 }
610
611 #spell-favorites-bar {
612 position: fixed;
613 z-index: 5;
614 left: 0.75rem;
615 bottom: 0.65rem;
616 display: flex;
617 gap: 0.35rem;
618 padding: 0.35rem;
619 border-radius: 10px;
620 background: rgba(18, 21, 27, 0.94);
621 border: 1px solid #2c3340;
622 box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);
623 }
624
625 .spell-favorite-slot {
626 width: 44px;
627 height: 44px;
628 padding: 0;
629 border-radius: 8px;
630 border: 2px solid #3a4250;
631 background: #1a1e26;
632 cursor: pointer;
633 transition: border-color 0.12s ease, box-shadow 0.12s ease, transform 0.12s ease;
634 }
635
636 .spell-favorite-slot.armed {
637 border-color: #8fd0ff;
638 background: #1e2a38;
639 box-shadow:
640 0 0 0 2px rgba(143, 208, 255, 0.45),
641 0 0 14px rgba(110, 181, 255, 0.55);
642 transform: translateY(-2px);
643 }
644
645 .spell-favorite-slot img {
646 width: 100%;
647 height: 100%;
648 object-fit: contain;
649 border-radius: 6px;
650 }
651
652 .spell-favorite-slot:disabled {
653 opacity: 0.45;
654 cursor: not-allowed;
655 }
656
512 657 #bag-panel, #bank-panel {
513 658 position: fixed;
514 659 z-index: 5;
@@ -1137,6 +1282,8 @@ a { color: #d4c48a; }
1137 1282 #death-backdrop[hidden],
1138 1283 #friends-panel[hidden],
1139 1284 #skills-panel[hidden],
1285 #spells-panel[hidden],
1286 #spell-favorites-bar[hidden],
1140 1287 #bag-panel[hidden],
1141 1288 #bank-panel[hidden],
1142 1289 #craft-panel[hidden],
@@ -509,6 +509,151 @@ a { color: #d4c48a; }
509 transition: width 0.25s ease-out;
509 transition: width 0.25s ease-out;
510}
510}
511
511
512#spells-panel {
513 position: fixed;
514 z-index: 5;
515 top: 50%;
516 left: 50%;
517 transform: translate(-50%, -50%);
518 width: min(520px, 94vw);
519 max-height: calc(100vh - 80px);
520 overflow: auto;
521 background: #1a1e26;
522 border: 1px solid #2c3340;
523 padding: 0.75rem;
524 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
525}
526
527.spell-autocast-row {
528 display: flex;
529 align-items: center;
530 gap: 0.5rem;
531 margin: 0.35rem 0 0.75rem;
532 font-size: 0.92rem;
533 color: #c8d0dc;
534}
535
536.spells-grid {
537 display: grid;
538 grid-template-columns: 1fr;
539 gap: 0.55rem;
540 margin: 0.5rem 0;
541}
542
543.spell-row {
544 display: flex;
545 gap: 0.55rem;
546 align-items: stretch;
547 min-width: 0;
548 padding: 0.45rem;
549 border: 1px solid #2c3340;
550 border-radius: 8px;
551 background: #12151b;
552}
553
554.spell-row.armed {
555 border-color: #6eb5ff;
556 box-shadow: 0 0 0 1px rgba(110, 181, 255, 0.35);
557}
558
559.spell-icon {
560 flex: 0 0 36px;
561 width: 36px;
562 height: 36px;
563 border-radius: 6px;
564 background: #101216;
565 border: 1px solid #3a4250;
566}
567
568.spell-body {
569 flex: 1;
570 display: flex;
571 flex-direction: column;
572 gap: 0.25rem;
573 min-width: 0;
574}
575
576.spell-title {
577 font-weight: 600;
578 color: #eef2f8;
579}
580
581.spell-desc {
582 margin: 0;
583 font-size: 0.86rem;
584 line-height: 1.35;
585}
586
587.spell-actions {
588 display: flex;
589 gap: 0.4rem;
590 margin-top: 0.15rem;
591}
592
593.spell-favorite-btn,
594.spell-arm-btn {
595 font: inherit;
596 font-size: 0.85rem;
597 padding: 0.2rem 0.55rem;
598 border-radius: 6px;
599 border: 1px solid #3a4250;
600 background: #1f2430;
601 color: #eef2f8;
602 cursor: pointer;
603}
604
605.spell-favorite-btn:disabled,
606.spell-arm-btn:disabled {
607 opacity: 0.45;
608 cursor: not-allowed;
609}
610
611#spell-favorites-bar {
612 position: fixed;
613 z-index: 5;
614 left: 0.75rem;
615 bottom: 0.65rem;
616 display: flex;
617 gap: 0.35rem;
618 padding: 0.35rem;
619 border-radius: 10px;
620 background: rgba(18, 21, 27, 0.94);
621 border: 1px solid #2c3340;
622 box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);
623}
624
625.spell-favorite-slot {
626 width: 44px;
627 height: 44px;
628 padding: 0;
629 border-radius: 8px;
630 border: 2px solid #3a4250;
631 background: #1a1e26;
632 cursor: pointer;
633 transition: border-color 0.12s ease, box-shadow 0.12s ease, transform 0.12s ease;
634}
635
636.spell-favorite-slot.armed {
637 border-color: #8fd0ff;
638 background: #1e2a38;
639 box-shadow:
640 0 0 0 2px rgba(143, 208, 255, 0.45),
641 0 0 14px rgba(110, 181, 255, 0.55);
642 transform: translateY(-2px);
643}
644
645.spell-favorite-slot img {
646 width: 100%;
647 height: 100%;
648 object-fit: contain;
649 border-radius: 6px;
650}
651
652.spell-favorite-slot:disabled {
653 opacity: 0.45;
654 cursor: not-allowed;
655}
656
512#bag-panel, #bank-panel {
657#bag-panel, #bank-panel {
513 position: fixed;
658 position: fixed;
514 z-index: 5;
659 z-index: 5;
@@ -1137,6 +1282,8 @@ a { color: #d4c48a; }
1137#death-backdrop[hidden],
1282#death-backdrop[hidden],
1138#friends-panel[hidden],
1283#friends-panel[hidden],
1139#skills-panel[hidden],
1284#skills-panel[hidden],
1285#spells-panel[hidden],
1286#spell-favorites-bar[hidden],
1140#bag-panel[hidden],
1287#bag-panel[hidden],
1141#bank-panel[hidden],
1288#bank-panel[hidden],
1142#craft-panel[hidden],
1289#craft-panel[hidden],
server/src/combat/service.js +75 −15
@@ -25,6 +25,7 @@ import {
25 25 equipmentBonusesFromSlots
26 26 } from "../../../shared/equipment/stats.js";
27 27 import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
28 import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS } from "../../../shared/spells/constants.js";
28 29 import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
29 30 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
30 31 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -144,7 +145,10 @@ export function clearEngage (ecs, entityId)
144 145
145 146 export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
146 147 {
147 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
148 const isClear = world.isClearForRangedAttack
149 ? (x, y) => world.isClearForRangedAttack(x, y)
150 : (x, y) => world.isEnterable(x, y);
151 return rayReaches(fromX, fromY, toX, toY, isClear);
148 152 }
149 153
150 154 /** Target-tile lighting 0–1 (baked + entity lights + time of day). */
@@ -395,7 +399,7 @@ export function stepCombat (world, now = Date.now())
395 399 if (profile.mode === "ranged")
396 400 {
397 401 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
398 const maxRange = profile.rangeTiles | 0 || 8;
402 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
399 403 const equipment = world.ecs.get(entity.handle, Component.equipment);
400 404 const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
401 405 const inRange = dist >= 1 && dist <= maxRange
@@ -460,7 +464,7 @@ function clearCombatApproachPath (ecs, handle)
460 464 { path.tiles = []; }
461 465 }
462 466
463 function queueMeleeApproach (world, entityId, handle, position, targetPos)
467 export function queueMeleeApproach (world, entityId, handle, position, targetPos)
464 468 {
465 469 if (world.frozen?.has?.(entityId))
466 470 { return; }
@@ -525,7 +529,36 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
525 529 { movement.walkCarry = 0; }
526 530 }
527 531
528 function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
532 function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
533 {
534 const dest = path.tiles[path.tiles.length - 1];
535 if (dest.x !== goal.x || dest.y !== goal.y)
536 { return true; }
537 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
538 if (standOff < minStandDist || standOff > maxRange)
539 { return true; }
540 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
541 { return true; }
542 const next = path.tiles[0];
543 if (!next)
544 { return true; }
545 return !world.walkableFor(entityId, next.x, next.y);
546 }
547
548 /**
549 * Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.
550 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
551 */
552 export function queueStandInRangeApproach (
553 world,
554 entityId,
555 handle,
556 position,
557 targetTileX,
558 targetTileY,
559 maxRange,
560 minStandDist = 1
561 )
529 562 {
530 563 if (world.frozen?.has?.(entityId))
531 564 { return; }
@@ -533,10 +566,12 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
533 566 if (!path)
534 567 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
535 568
536 const dist = chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY);
537 if (dist >= 1 && dist <= maxRange && hasCombatLineOfSight(
538 world, position.tileX, position.tileY, targetPos.tileX, targetPos.tileY
539 ))
569 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
570 if (
571 distToTarget <= maxRange
572 && distToTarget >= minStandDist
573 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
574 )
540 575 {
541 576 path.tiles = [];
542 577 return;
@@ -548,14 +583,14 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
548 583 {
549 584 for (let dx = -maxRange; dx <= maxRange; dx++)
550 585 {
551 const x = targetPos.tileX + dx;
552 const y = targetPos.tileY + dy;
553 const toTarget = chebyshev(x, y, targetPos.tileX, targetPos.tileY);
554 if (toTarget < 1 || toTarget > maxRange)
586 const x = targetTileX + dx;
587 const y = targetTileY + dy;
588 const standOff = chebyshev(x, y, targetTileX, targetTileY);
589 if (standOff < minStandDist || standOff > maxRange)
555 590 { continue; }
556 591 if (!world.walkableFor(entityId, x, y))
557 592 { continue; }
558 if (!hasCombatLineOfSight(world, x, y, targetPos.tileX, targetPos.tileY))
593 if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))
559 594 { continue; }
560 595 const d = chebyshev(position.tileX, position.tileY, x, y);
561 596 if (d < bestDist)
@@ -575,6 +610,17 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
575 610 path.tiles = [];
576 611 return;
577 612 }
613 if (path.tiles?.length && !standInRangePathStale(
614 world,
615 entityId,
616 path,
617 bestGoal,
618 targetTileX,
619 targetTileY,
620 maxRange,
621 minStandDist
622 ))
623 { return; }
578 624 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
579 625 const preferVertical = !!world.ecs.get(handle, Component.character);
580 626 const tiles = findPath(
@@ -595,6 +641,20 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
595 641 { movement.walkCarry = 0; }
596 642 }
597 643
644 function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
645 {
646 queueStandInRangeApproach(
647 world,
648 entityId,
649 handle,
650 position,
651 targetPos.tileX,
652 targetPos.tileY,
653 maxRange,
654 1
655 );
656 }
657
598 658 export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
599 659 {
600 660 const events = [];
@@ -668,7 +728,7 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
668 728 fromTileY: from.tileY,
669 729 tileX: endX,
670 730 tileY: endY,
671 durationMs: 400,
731 durationMs: RANGED_PROJECTILE_MS,
672 732 ...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}
673 733 });
674 734 return events.concat(hitEvents);
@@ -827,7 +887,7 @@ export function applyRemoteRangedShot (world, payload)
827 887 fromTileY: payload.fromTileY,
828 888 tileX: endX,
829 889 tileY: endY,
830 durationMs: 400,
890 durationMs: RANGED_PROJECTILE_MS,
831 891 shaftTint: payload.shaftTint ?? null,
832 892 tipTint: payload.tipTint ?? null
833 893 }, ...hitEvents];
@@ -25,6 +25,7 @@ import {
25 equipmentBonusesFromSlots
25 equipmentBonusesFromSlots
26} from "../../../shared/equipment/stats.js";
26} from "../../../shared/equipment/stats.js";
27import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
27import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
28import { COMBAT_RANGE_TILES, RANGED_PROJECTILE_MS } from "../../../shared/spells/constants.js";
28import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
29import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
29import { chunkBoundsAround, findPath } from "../navigation/astar.js";
30import { chunkBoundsAround, findPath } from "../navigation/astar.js";
30import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
31import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -144,7 +145,10 @@ export function clearEngage (ecs, entityId)
144
145
145export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
146export function hasCombatLineOfSight (world, fromX, fromY, toX, toY)
146{
147{
147 return rayReaches(fromX, fromY, toX, toY, (x, y) => world.isEnterable(x, y));
148 const isClear = world.isClearForRangedAttack
149 ? (x, y) => world.isClearForRangedAttack(x, y)
150 : (x, y) => world.isEnterable(x, y);
151 return rayReaches(fromX, fromY, toX, toY, isClear);
148}
152}
149
153
150/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
154/** Target-tile lighting 0–1 (baked + entity lights + time of day). */
@@ -395,7 +399,7 @@ export function stepCombat (world, now = Date.now())
395 if (profile.mode === "ranged")
399 if (profile.mode === "ranged")
396 {
400 {
397 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
401 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
398 const maxRange = profile.rangeTiles | 0 || 8;
402 const maxRange = profile.rangeTiles | 0 || COMBAT_RANGE_TILES;
399 const equipment = world.ecs.get(entity.handle, Component.equipment);
403 const equipment = world.ecs.get(entity.handle, Component.equipment);
400 const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
404 const hasArrows = arrowStackInOffhand(equipment) && stackQuantity(arrowStackInOffhand(equipment).quantity) > 0;
401 const inRange = dist >= 1 && dist <= maxRange
405 const inRange = dist >= 1 && dist <= maxRange
@@ -460,7 +464,7 @@ function clearCombatApproachPath (ecs, handle)
460 { path.tiles = []; }
464 { path.tiles = []; }
461}
465}
462
466
463function queueMeleeApproach (world, entityId, handle, position, targetPos)
467export function queueMeleeApproach (world, entityId, handle, position, targetPos)
464{
468{
465 if (world.frozen?.has?.(entityId))
469 if (world.frozen?.has?.(entityId))
466 { return; }
470 { return; }
@@ -525,7 +529,36 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
525 { movement.walkCarry = 0; }
529 { movement.walkCarry = 0; }
526}
530}
527
531
528function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
532function standInRangePathStale (world, entityId, path, goal, targetTileX, targetTileY, maxRange, minStandDist)
533{
534 const dest = path.tiles[path.tiles.length - 1];
535 if (dest.x !== goal.x || dest.y !== goal.y)
536 { return true; }
537 const standOff = chebyshev(dest.x, dest.y, targetTileX, targetTileY);
538 if (standOff < minStandDist || standOff > maxRange)
539 { return true; }
540 if (!hasCombatLineOfSight(world, dest.x, dest.y, targetTileX, targetTileY))
541 { return true; }
542 const next = path.tiles[0];
543 if (!next)
544 { return true; }
545 return !world.walkableFor(entityId, next.x, next.y);
546}
547
548/**
549 * Path toward the nearest tile from which `targetTile` is in Chebyshev range with LOS.
550 * @param {number} minStandDist Minimum stand-off from target (0 = may stand on target tile).
551 */
552export function queueStandInRangeApproach (
553 world,
554 entityId,
555 handle,
556 position,
557 targetTileX,
558 targetTileY,
559 maxRange,
560 minStandDist = 1
561)
529{
562{
530 if (world.frozen?.has?.(entityId))
563 if (world.frozen?.has?.(entityId))
531 { return; }
564 { return; }
@@ -533,10 +566,12 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
533 if (!path)
566 if (!path)
534 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
567 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
535
568
536 const dist = chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY);
569 const distToTarget = chebyshev(position.tileX, position.tileY, targetTileX, targetTileY);
537 if (dist >= 1 && dist <= maxRange && hasCombatLineOfSight(
570 if (
538 world, position.tileX, position.tileY, targetPos.tileX, targetPos.tileY
571 distToTarget <= maxRange
539 ))
572 && distToTarget >= minStandDist
573 && hasCombatLineOfSight(world, position.tileX, position.tileY, targetTileX, targetTileY)
574 )
540 {
575 {
541 path.tiles = [];
576 path.tiles = [];
542 return;
577 return;
@@ -548,14 +583,14 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
548 {
583 {
549 for (let dx = -maxRange; dx <= maxRange; dx++)
584 for (let dx = -maxRange; dx <= maxRange; dx++)
550 {
585 {
551 const x = targetPos.tileX + dx;
586 const x = targetTileX + dx;
552 const y = targetPos.tileY + dy;
587 const y = targetTileY + dy;
553 const toTarget = chebyshev(x, y, targetPos.tileX, targetPos.tileY);
588 const standOff = chebyshev(x, y, targetTileX, targetTileY);
554 if (toTarget < 1 || toTarget > maxRange)
589 if (standOff < minStandDist || standOff > maxRange)
555 { continue; }
590 { continue; }
556 if (!world.walkableFor(entityId, x, y))
591 if (!world.walkableFor(entityId, x, y))
557 { continue; }
592 { continue; }
558 if (!hasCombatLineOfSight(world, x, y, targetPos.tileX, targetPos.tileY))
593 if (!hasCombatLineOfSight(world, x, y, targetTileX, targetTileY))
559 { continue; }
594 { continue; }
560 const d = chebyshev(position.tileX, position.tileY, x, y);
595 const d = chebyshev(position.tileX, position.tileY, x, y);
561 if (d < bestDist)
596 if (d < bestDist)
@@ -575,6 +610,17 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
575 path.tiles = [];
610 path.tiles = [];
576 return;
611 return;
577 }
612 }
613 if (path.tiles?.length && !standInRangePathStale(
614 world,
615 entityId,
616 path,
617 bestGoal,
618 targetTileX,
619 targetTileY,
620 maxRange,
621 minStandDist
622 ))
623 { return; }
578 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
624 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
579 const preferVertical = !!world.ecs.get(handle, Component.character);
625 const preferVertical = !!world.ecs.get(handle, Component.character);
580 const tiles = findPath(
626 const tiles = findPath(
@@ -595,6 +641,20 @@ function queueRangedApproach (world, entityId, handle, position, targetPos, maxR
595 { movement.walkCarry = 0; }
641 { movement.walkCarry = 0; }
596}
642}
597
643
644function queueRangedApproach (world, entityId, handle, position, targetPos, maxRange)
645{
646 queueStandInRangeApproach(
647 world,
648 entityId,
649 handle,
650 position,
651 targetPos.tileX,
652 targetPos.tileY,
653 maxRange,
654 1
655 );
656}
657
598export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
658export function resolveRangedShot (world, attackerId, targetId, profile, now = Date.now(), targetPos)
599{
659{
600 const events = [];
660 const events = [];
@@ -668,7 +728,7 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
668 fromTileY: from.tileY,
728 fromTileY: from.tileY,
669 tileX: endX,
729 tileX: endX,
670 tileY: endY,
730 tileY: endY,
671 durationMs: 400,
731 durationMs: RANGED_PROJECTILE_MS,
672 ...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}
732 ...publicDualTint(projectileDualTintFromAttacker(world.ecs, attackerHandle)) ?? {}
673 });
733 });
674 return events.concat(hitEvents);
734 return events.concat(hitEvents);
@@ -827,7 +887,7 @@ export function applyRemoteRangedShot (world, payload)
827 fromTileY: payload.fromTileY,
887 fromTileY: payload.fromTileY,
828 tileX: endX,
888 tileX: endX,
829 tileY: endY,
889 tileY: endY,
830 durationMs: 400,
890 durationMs: RANGED_PROJECTILE_MS,
831 shaftTint: payload.shaftTint ?? null,
891 shaftTint: payload.shaftTint ?? null,
832 tipTint: payload.tipTint ?? null
892 tipTint: payload.tipTint ?? null
833 }, ...hitEvents];
893 }, ...hitEvents];
server/src/ecs/components.js +3 −1
@@ -21,5 +21,7 @@ export const Component = Object.freeze({
21 21 stamina: "stamina",
22 22 gather: "gather",
23 23 shop: "shop",
24 statusEffects: "statusEffects"
24 statusEffects: "statusEffects",
25 spells: "spells",
26 spellcasting: "spellcasting"
25 27 });
@@ -21,5 +21,7 @@ export const Component = Object.freeze({
21 stamina: "stamina",
21 stamina: "stamina",
22 gather: "gather",
22 gather: "gather",
23 shop: "shop",
23 shop: "shop",
24 statusEffects: "statusEffects"
24 statusEffects: "statusEffects",
25 spells: "spells",
26 spellcasting: "spellcasting"
25});
27});
server/src/gateway/websocket.js +177 −1
@@ -515,6 +515,64 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
515 515 characterId: session.characterId
516 516 });
517 517 break;
518 case MessageType.setSpellFavorite:
519 requirePlaying(session);
520 simulation.enqueue(session.id, {
521 type: "set-spell-favorite",
522 characterId: session.characterId,
523 spellId: message.spellId
524 });
525 break;
526 case MessageType.setSpellAutoCast:
527 requirePlaying(session);
528 simulation.enqueue(session.id, {
529 type: "set-spell-autocast",
530 characterId: session.characterId,
531 enabled: !!message.enabled
532 });
533 break;
534 case MessageType.armSpell:
535 requirePlaying(session);
536 simulation.enqueue(session.id, {
537 type: "arm-spell",
538 characterId: session.characterId,
539 spellId: message.spellId
540 });
541 break;
542 case MessageType.cancelArmSpell:
543 requirePlaying(session);
544 simulation.enqueue(session.id, {
545 type: "cancel-arm-spell",
546 characterId: session.characterId
547 });
548 break;
549 case MessageType.castSpellTile:
550 requirePlaying(session);
551 simulation.enqueue(session.id, {
552 type: "cast-spell-tile",
553 characterId: session.characterId,
554 spellId: message.spellId,
555 tileX: message.tileX | 0,
556 tileY: message.tileY | 0
557 });
558 break;
559 case MessageType.castSpellEntity:
560 requirePlaying(session);
561 simulation.enqueue(session.id, {
562 type: "cast-spell-entity",
563 characterId: session.characterId,
564 spellId: message.spellId,
565 targetEntityId: message.targetEntityId | 0
566 });
567 break;
568 case MessageType.readSpellbook:
569 requirePlaying(session);
570 simulation.enqueue(session.id, {
571 type: "read-spellbook",
572 characterId: session.characterId,
573 slotIndex: message.slotIndex | 0
574 });
575 break;
518 576 case MessageType.interact:
519 577 requirePlaying(session);
520 578 simulation.enqueue(session.id, {
@@ -776,6 +834,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
776 834 const skills = simulation.skillsOf(session.entityId);
777 835 if (skills)
778 836 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
837 const spellView = simulation.spellsOf(session.entityId);
838 if (spellView)
839 {
840 send(session, {
841 type: MessageType.spells,
842 spells: spellView.spells,
843 autoCast: spellView.autoCast,
844 armedSpellId: spellView.armedSpellId ?? null
845 });
846 }
779 847 const stamina = simulation.staminaOf(session.entityId);
780 848 if (stamina)
781 849 {
@@ -970,6 +1038,38 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
970 1038 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
971 1039 continue;
972 1040 }
1041 if (event.type === "spells")
1042 {
1043 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1044 if (!session)
1045 { continue; }
1046 send(session, {
1047 type: MessageType.spellsUpdated,
1048 spells: event.spells ?? [],
1049 autoCast: !!event.autoCast,
1050 armedSpellId: event.armedSpellId ?? null
1051 });
1052 continue;
1053 }
1054 if (event.type === "spell-armed")
1055 {
1056 const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);
1057 if (!session)
1058 { continue; }
1059 send(session, {
1060 type: MessageType.spellArmed,
1061 spellId: event.spellId
1062 });
1063 continue;
1064 }
1065 if (event.type === "spell-disarmed")
1066 {
1067 const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);
1068 if (!session)
1069 { continue; }
1070 send(session, { type: MessageType.spellDisarmed });
1071 continue;
1072 }
973 1073 if (event.type === "stamina")
974 1074 {
975 1075 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
@@ -1251,7 +1351,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1251 1351 }
1252 1352 continue;
1253 1353 }
1254 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1354 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1255 1355 { publishEntity(event); }
1256 1356 }
1257 1357 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1361,6 +1461,82 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1361 1461 });
1362 1462 continue;
1363 1463 }
1464 if (event.type === "spell-projectile")
1465 {
1466 if (!seesTo && !seesFrom)
1467 { continue; }
1468 send(session, {
1469 type: MessageType.spellProjectile,
1470 casterId: event.casterId,
1471 spellId: event.spellId,
1472 fromTileX: event.fromTileX,
1473 fromTileY: event.fromTileY,
1474 tileX: event.tileX,
1475 tileY: event.tileY,
1476 durationMs: event.durationMs ?? 2000,
1477 sprite: event.sprite ?? null
1478 });
1479 continue;
1480 }
1481 if (event.type === "spell-fizzle")
1482 {
1483 if (!seesTo && !seesFrom)
1484 { continue; }
1485 send(session, {
1486 type: MessageType.spellFizzle,
1487 casterId: event.casterId,
1488 spellId: event.spellId,
1489 fromTileX: event.fromTileX,
1490 fromTileY: event.fromTileY,
1491 tileX: event.tileX,
1492 tileY: event.tileY
1493 });
1494 continue;
1495 }
1496 if (event.type === "spell-cast-flash")
1497 {
1498 if (!seesTo)
1499 { continue; }
1500 send(session, {
1501 type: MessageType.spellCastFlash,
1502 casterId: event.casterId,
1503 tileX: event.tileX,
1504 tileY: event.tileY,
1505 radiusTiles: event.radiusTiles ?? 1,
1506 durationMs: event.durationMs ?? 500,
1507 tier: event.tier ?? 1
1508 });
1509 continue;
1510 }
1511 if (event.type === "spell-light-appear" || event.type === "spell-light-update")
1512 {
1513 if (!seesTo)
1514 { continue; }
1515 send(session, {
1516 type: event.type === "spell-light-appear"
1517 ? MessageType.spellLightAppear
1518 : MessageType.spellLightUpdate,
1519 tileX: event.tileX,
1520 tileY: event.tileY,
1521 ownerEntityId: event.ownerEntityId,
1522 remainingMs: event.remainingMs ?? 0,
1523 rangeTiles: event.rangeTiles ?? 0,
1524 intensity: event.intensity ?? 0,
1525 expiresAt: event.expiresAt ?? 0
1526 });
1527 continue;
1528 }
1529 if (event.type === "spell-light-remove")
1530 {
1531 if (!seesTo)
1532 { continue; }
1533 send(session, {
1534 type: MessageType.spellLightRemove,
1535 tileX: event.tileX,
1536 tileY: event.tileY
1537 });
1538 continue;
1539 }
1364 1540 if (event.type === "entity-health")
1365 1541 {
1366 1542 if (!seesTo && !seesFrom)
@@ -515,6 +515,64 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
515 characterId: session.characterId
515 characterId: session.characterId
516 });
516 });
517 break;
517 break;
518 case MessageType.setSpellFavorite:
519 requirePlaying(session);
520 simulation.enqueue(session.id, {
521 type: "set-spell-favorite",
522 characterId: session.characterId,
523 spellId: message.spellId
524 });
525 break;
526 case MessageType.setSpellAutoCast:
527 requirePlaying(session);
528 simulation.enqueue(session.id, {
529 type: "set-spell-autocast",
530 characterId: session.characterId,
531 enabled: !!message.enabled
532 });
533 break;
534 case MessageType.armSpell:
535 requirePlaying(session);
536 simulation.enqueue(session.id, {
537 type: "arm-spell",
538 characterId: session.characterId,
539 spellId: message.spellId
540 });
541 break;
542 case MessageType.cancelArmSpell:
543 requirePlaying(session);
544 simulation.enqueue(session.id, {
545 type: "cancel-arm-spell",
546 characterId: session.characterId
547 });
548 break;
549 case MessageType.castSpellTile:
550 requirePlaying(session);
551 simulation.enqueue(session.id, {
552 type: "cast-spell-tile",
553 characterId: session.characterId,
554 spellId: message.spellId,
555 tileX: message.tileX | 0,
556 tileY: message.tileY | 0
557 });
558 break;
559 case MessageType.castSpellEntity:
560 requirePlaying(session);
561 simulation.enqueue(session.id, {
562 type: "cast-spell-entity",
563 characterId: session.characterId,
564 spellId: message.spellId,
565 targetEntityId: message.targetEntityId | 0
566 });
567 break;
568 case MessageType.readSpellbook:
569 requirePlaying(session);
570 simulation.enqueue(session.id, {
571 type: "read-spellbook",
572 characterId: session.characterId,
573 slotIndex: message.slotIndex | 0
574 });
575 break;
518 case MessageType.interact:
576 case MessageType.interact:
519 requirePlaying(session);
577 requirePlaying(session);
520 simulation.enqueue(session.id, {
578 simulation.enqueue(session.id, {
@@ -776,6 +834,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
776 const skills = simulation.skillsOf(session.entityId);
834 const skills = simulation.skillsOf(session.entityId);
777 if (skills)
835 if (skills)
778 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
836 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
837 const spellView = simulation.spellsOf(session.entityId);
838 if (spellView)
839 {
840 send(session, {
841 type: MessageType.spells,
842 spells: spellView.spells,
843 autoCast: spellView.autoCast,
844 armedSpellId: spellView.armedSpellId ?? null
845 });
846 }
779 const stamina = simulation.staminaOf(session.entityId);
847 const stamina = simulation.staminaOf(session.entityId);
780 if (stamina)
848 if (stamina)
781 {
849 {
@@ -970,6 +1038,38 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
970 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
1038 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
971 continue;
1039 continue;
972 }
1040 }
1041 if (event.type === "spells")
1042 {
1043 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1044 if (!session)
1045 { continue; }
1046 send(session, {
1047 type: MessageType.spellsUpdated,
1048 spells: event.spells ?? [],
1049 autoCast: !!event.autoCast,
1050 armedSpellId: event.armedSpellId ?? null
1051 });
1052 continue;
1053 }
1054 if (event.type === "spell-armed")
1055 {
1056 const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);
1057 if (!session)
1058 { continue; }
1059 send(session, {
1060 type: MessageType.spellArmed,
1061 spellId: event.spellId
1062 });
1063 continue;
1064 }
1065 if (event.type === "spell-disarmed")
1066 {
1067 const session = [...sessions.values()].find((entry) => entry.entityId === event.entityId);
1068 if (!session)
1069 { continue; }
1070 send(session, { type: MessageType.spellDisarmed });
1071 continue;
1072 }
973 if (event.type === "stamina")
1073 if (event.type === "stamina")
974 {
1074 {
975 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1075 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
@@ -1251,7 +1351,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1251 }
1351 }
1252 continue;
1352 continue;
1253 }
1353 }
1254 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1354 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block" || event.type === "combat-projectile" || event.type === "spell-projectile" || event.type === "spell-fizzle" || event.type === "spell-cast-flash" || event.type === "spell-light-appear" || event.type === "spell-light-update" || event.type === "spell-light-remove" || event.type === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1255 { publishEntity(event); }
1355 { publishEntity(event); }
1256 }
1356 }
1257 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
1357 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1361,6 +1461,82 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1361 });
1461 });
1362 continue;
1462 continue;
1363 }
1463 }
1464 if (event.type === "spell-projectile")
1465 {
1466 if (!seesTo && !seesFrom)
1467 { continue; }
1468 send(session, {
1469 type: MessageType.spellProjectile,
1470 casterId: event.casterId,
1471 spellId: event.spellId,
1472 fromTileX: event.fromTileX,
1473 fromTileY: event.fromTileY,
1474 tileX: event.tileX,
1475 tileY: event.tileY,
1476 durationMs: event.durationMs ?? 2000,
1477 sprite: event.sprite ?? null
1478 });
1479 continue;
1480 }
1481 if (event.type === "spell-fizzle")
1482 {
1483 if (!seesTo && !seesFrom)
1484 { continue; }
1485 send(session, {
1486 type: MessageType.spellFizzle,
1487 casterId: event.casterId,
1488 spellId: event.spellId,
1489 fromTileX: event.fromTileX,
1490 fromTileY: event.fromTileY,
1491 tileX: event.tileX,
1492 tileY: event.tileY
1493 });
1494 continue;
1495 }
1496 if (event.type === "spell-cast-flash")
1497 {
1498 if (!seesTo)
1499 { continue; }
1500 send(session, {
1501 type: MessageType.spellCastFlash,
1502 casterId: event.casterId,
1503 tileX: event.tileX,
1504 tileY: event.tileY,
1505 radiusTiles: event.radiusTiles ?? 1,
1506 durationMs: event.durationMs ?? 500,
1507 tier: event.tier ?? 1
1508 });
1509 continue;
1510 }
1511 if (event.type === "spell-light-appear" || event.type === "spell-light-update")
1512 {
1513 if (!seesTo)
1514 { continue; }
1515 send(session, {
1516 type: event.type === "spell-light-appear"
1517 ? MessageType.spellLightAppear
1518 : MessageType.spellLightUpdate,
1519 tileX: event.tileX,
1520 tileY: event.tileY,
1521 ownerEntityId: event.ownerEntityId,
1522 remainingMs: event.remainingMs ?? 0,
1523 rangeTiles: event.rangeTiles ?? 0,
1524 intensity: event.intensity ?? 0,
1525 expiresAt: event.expiresAt ?? 0
1526 });
1527 continue;
1528 }
1529 if (event.type === "spell-light-remove")
1530 {
1531 if (!seesTo)
1532 { continue; }
1533 send(session, {
1534 type: MessageType.spellLightRemove,
1535 tileX: event.tileX,
1536 tileY: event.tileY
1537 });
1538 continue;
1539 }
1364 if (event.type === "entity-health")
1540 if (event.type === "entity-health")
1365 {
1541 {
1366 if (!seesTo && !seesFrom)
1542 if (!seesTo && !seesFrom)
server/src/items/bags.js +2 −1
@@ -26,6 +26,7 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
26 26 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
27 27 import { randomUUID } from "node:crypto";
28 28 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
29 import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";
29 30 import {
30 31 applyStatusEffect,
31 32 emptyStatusEffects,
@@ -435,7 +436,7 @@ function drinkItem (world, sessionId, command)
435 436 throw userError("That inventory slot is empty.");
436 437 }
437 438 inventory.slots = consumed.slots;
438 const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
439 const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance));
439 440 return {
440 441 events: effectResult.events ?? [],
441 442 private: bagView(world.ecs, handle),
@@ -26,6 +26,7 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
26import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
26import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
27import { randomUUID } from "node:crypto";
27import { randomUUID } from "node:crypto";
28import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
28import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
29import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js";
29import {
30import {
30 applyStatusEffect,
31 applyStatusEffect,
31 emptyStatusEffects,
32 emptyStatusEffects,
@@ -435,7 +436,7 @@ function drinkItem (world, sessionId, command)
435 throw userError("That inventory slot is empty.");
436 throw userError("That inventory slot is empty.");
436 }
437 }
437 inventory.slots = consumed.slots;
438 inventory.slots = consumed.slots;
438 const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
439 const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance));
439 return {
440 return {
440 events: effectResult.events ?? [],
441 events: effectResult.events ?? [],
441 private: bagView(world.ecs, handle),
442 private: bagView(world.ecs, handle),
server/src/persistence/stateDb.js +38 −0
@@ -3,6 +3,7 @@ import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalize
3 3 import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4 4 import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
5 5 import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
6 import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
6 7
7 8 const STATE_SCHEMA = `
8 9 CREATE TABLE IF NOT EXISTS accounts (
@@ -191,6 +192,12 @@ export class StateDatabase
191 192 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
192 193 if (!courierColumns.some((column) => column.name === "vault_character_id"))
193 194 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
195 if (!bagColumns.some((column) => column.name === "spells_blob"))
196 {
197 this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
198 }
199 if (!characterColumns.some((column) => column.name === "health_current"))
200 { this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }
194 201 this.#grantLanternsToExistingCharacters();
195 202 }
196 203
@@ -398,6 +405,14 @@ export class StateDatabase
398 405 );
399 406 }
400 407
408 saveCharacterHealth (characterId, current)
409 {
410 this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
411 Math.max(0, current | 0),
412 characterId
413 );
414 }
415
401 416 setCharacterDead (characterId, isDead)
402 417 {
403 418 this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
@@ -675,6 +690,29 @@ export class StateDatabase
675 690 );
676 691 }
677 692
693 getSpells (characterId)
694 {
695 const row = this.db.prepare("SELECT spells_blob FROM character_bags WHERE character_id = ?").get(characterId);
696 if (row)
697 {
698 return normalizePlayerSpells(JSON.parse(row.spells_blob || "{}"));
699 }
700 if (this.getCharacter(characterId))
701 {
702 this.#ensureBag(characterId);
703 return this.getSpells(characterId);
704 }
705 return null;
706 }
707
708 saveSpells (characterId, spells)
709 {
710 this.#ensureBag(characterId);
711 this.db.prepare("UPDATE character_bags SET spells_blob = ? WHERE character_id = ?").run(
712 JSON.stringify(storedPlayerSpells(spells)),
713 characterId
714 );
715 }
678 716 getInheritance (accountId)
679 717 {
680 718 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
@@ -3,6 +3,7 @@ import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalize
3import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
3import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
4import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
5import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
5import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
6import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
6
7
7const STATE_SCHEMA = `
8const STATE_SCHEMA = `
8CREATE TABLE IF NOT EXISTS accounts (
9CREATE TABLE IF NOT EXISTS accounts (
@@ -191,6 +192,12 @@ export class StateDatabase
191 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
192 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
192 if (!courierColumns.some((column) => column.name === "vault_character_id"))
193 if (!courierColumns.some((column) => column.name === "vault_character_id"))
193 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
194 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
195 if (!bagColumns.some((column) => column.name === "spells_blob"))
196 {
197 this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
198 }
199 if (!characterColumns.some((column) => column.name === "health_current"))
200 { this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }
194 this.#grantLanternsToExistingCharacters();
201 this.#grantLanternsToExistingCharacters();
195 }
202 }
196
203
@@ -398,6 +405,14 @@ export class StateDatabase
398 );
405 );
399 }
406 }
400
407
408 saveCharacterHealth (characterId, current)
409 {
410 this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
411 Math.max(0, current | 0),
412 characterId
413 );
414 }
415
401 setCharacterDead (characterId, isDead)
416 setCharacterDead (characterId, isDead)
402 {
417 {
403 this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
418 this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
@@ -675,6 +690,29 @@ export class StateDatabase
675 );
690 );
676 }
691 }
677
692
693 getSpells (characterId)
694 {
695 const row = this.db.prepare("SELECT spells_blob FROM character_bags WHERE character_id = ?").get(characterId);
696 if (row)
697 {
698 return normalizePlayerSpells(JSON.parse(row.spells_blob || "{}"));
699 }
700 if (this.getCharacter(characterId))
701 {
702 this.#ensureBag(characterId);
703 return this.getSpells(characterId);
704 }
705 return null;
706 }
707
708 saveSpells (characterId, spells)
709 {
710 this.#ensureBag(characterId);
711 this.db.prepare("UPDATE character_bags SET spells_blob = ? WHERE character_id = ?").run(
712 JSON.stringify(storedPlayerSpells(spells)),
713 characterId
714 );
715 }
678 getInheritance (accountId)
716 getInheritance (accountId)
679 {
717 {
680 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
718 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
server/src/simulation/protocol.js +1 −0
@@ -21,6 +21,7 @@ export const WorkerMessage = Object.freeze({
21 21 inspect: "inspect",
22 22 inspectBag: "inspectBag",
23 23 inspectSkills: "inspectSkills",
24 inspectSpells: "inspectSpells",
24 25 applyBag: "applyBag",
25 26 updateFlight: "updateFlight",
26 27 chunkIsSimulating: "chunkIsSimulating",
@@ -21,6 +21,7 @@ export const WorkerMessage = Object.freeze({
21 inspect: "inspect",
21 inspect: "inspect",
22 inspectBag: "inspectBag",
22 inspectBag: "inspectBag",
23 inspectSkills: "inspectSkills",
23 inspectSkills: "inspectSkills",
24 inspectSpells: "inspectSpells",
24 applyBag: "applyBag",
25 applyBag: "applyBag",
25 updateFlight: "updateFlight",
26 updateFlight: "updateFlight",
26 chunkIsSimulating: "chunkIsSimulating",
27 chunkIsSimulating: "chunkIsSimulating",
server/src/simulation/simulation.js +81 −2
@@ -31,6 +31,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
31 31 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
32 32 import { mobComponents } from "./spawners.js";
33 33 import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
34 import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
34 35 import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
35 36 import { BlockType } from "../../../shared/definitions/tiles.js";
36 37 import { ItemId } from "../../../shared/definitions/items.js";
@@ -224,6 +225,11 @@ export class Simulation
224 225 events.push(...this.#skillLevelUpEvents(event));
225 226 continue;
226 227 }
228 if (event.type === "spells-updated")
229 {
230 this.#applySpellsUpdated(event);
231 continue;
232 }
227 233 if (event.type === "inventory" && event.characterId)
228 234 {
229 235 this.#saveBagFromView(event.characterId, {
@@ -276,6 +282,11 @@ export class Simulation
276 282 events.push(...this.#skillLevelUpEvents(event));
277 283 continue;
278 284 }
285 if (event.type === "spells-updated")
286 {
287 this.#applySpellsUpdated(event);
288 continue;
289 }
279 290 this.#persistGroundEvent(event);
280 291 if (event.type !== "skills-updated")
281 292 { events.push(event); }
@@ -347,12 +358,19 @@ export class Simulation
347 358 vaultReserved: []
348 359 };
349 360 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
361 const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells();
350 362 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
351 363 if (enforceMinimumSkillLevels(skills))
352 364 { this.stateDb.saveSkills(character.character_id, skills); }
353 365 const maxHealth = playerMaxHealth(skills);
354 366 const maxStamina = playerMaxStamina(skills);
355 367 const isDead = !!row.is_dead;
368 const savedHealth = row.health_current;
369 const currentHealth = isDead
370 ? 0
371 : savedHealth != null
372 ? Math.max(0, Math.min(maxHealth, savedHealth | 0))
373 : maxHealth;
356 374 const entityId = this.nextEntityId++;
357 375 const components = {
358 376 position: { tileX, tileY },
@@ -376,10 +394,17 @@ export class Simulation
376 394 slots: bag.vault ?? [],
377 395 reserved: bag.vaultReserved ?? []
378 396 },
379 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
397 health: { current: currentHealth, max: maxHealth },
380 398 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
381 399 combat: { targetEntityId: null, nextSwingAt: 0 },
382 400 skills,
401 spells,
402 spellcasting: {
403 armedSpellId: null,
404 repeatSpellId: null,
405 repeatTargetEntityId: null,
406 nextCastAt: 0
407 },
383 408 };
384 409 if (isDead)
385 410 { components.dead = {}; }
@@ -564,6 +589,15 @@ export class Simulation
564 589 });
565 590 }
566 591
592 pushSpells (characterId, payload)
593 {
594 this.pendingPrivate.push({
595 type: "spells",
596 characterId,
597 ...payload
598 });
599 }
600
567 601 skillsOf (entityId)
568 602 {
569 603 const record = this.directory.get(entityId);
@@ -575,6 +609,17 @@ export class Simulation
575 609 });
576 610 }
577 611
612 spellsOf (entityId)
613 {
614 const record = this.directory.get(entityId);
615 if (!record)
616 { return null; }
617 return this.workers[record.workerId].call({
618 type: WorkerMessage.inspectSpells,
619 entityId
620 });
621 }
622
578 623 staminaOf (entityId)
579 624 {
580 625 const record = this.directory.get(entityId);
@@ -692,6 +737,8 @@ export class Simulation
692 737 dropped.tileY,
693 738 dropped.gait ?? GAIT.walk
694 739 );
740 if (dropped.health != null)
741 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
695 742 this.#queueReplication(replicationDespawn(dropped));
696 743 }
697 744 this.#forget(entityId);
@@ -982,7 +1029,16 @@ export class Simulation
982 1029 }
983 1030 for (const event of result?.events ?? [])
984 1031 { this.#persistGroundEvent(event); }
985 const events = [...(result?.events ?? [])];
1032 const events = [];
1033 for (const event of result?.events ?? [])
1034 {
1035 if (event.type === "spells-updated")
1036 {
1037 this.#applySpellsUpdated(event);
1038 continue;
1039 }
1040 events.push(event);
1041 }
986 1042 if (result?.private)
987 1043 {
988 1044 events.push({
@@ -1040,6 +1096,11 @@ export class Simulation
1040 1096 events.push(...this.#skillLevelUpEvents(event));
1041 1097 continue;
1042 1098 }
1099 if (event.type === "spells-updated")
1100 {
1101 this.#applySpellsUpdated(event);
1102 continue;
1103 }
1043 1104 if (event.type === "player-died")
1044 1105 {
1045 1106 events.push(...this.#applyPlayerDeath(event));
@@ -1096,6 +1157,11 @@ export class Simulation
1096 1157 events.push(...this.#skillLevelUpEvents(event));
1097 1158 continue;
1098 1159 }
1160 if (event.type === "spells-updated")
1161 {
1162 this.#applySpellsUpdated(event);
1163 continue;
1164 }
1099 1165 if (event.type === "player-died")
1100 1166 {
1101 1167 events.push(...this.#applyPlayerDeath(event));
@@ -1241,6 +1307,8 @@ export class Simulation
1241 1307 throw error;
1242 1308 }
1243 1309 this.stateDb.setCharacterDead(characterId, false);
1310 const respawnHealth = playerMaxHealth(skills);
1311 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
1244 1312 this.stateDb.saveCharacterPosition(
1245 1313 characterId,
1246 1314 destination.tileX,
@@ -1827,6 +1895,17 @@ export class Simulation
1827 1895 this.pushSkills(event.characterId, event.skills ?? []);
1828 1896 }
1829 1897
1898 #applySpellsUpdated (event)
1899 {
1900 if (!event?.characterId || !event.stored)
1901 { return; }
1902 this.stateDb.saveSpells(event.characterId, event.stored);
1903 this.pushSpells(event.characterId, {
1904 spells: event.spells ?? [],
1905 autoCast: !!event.autoCast
1906 });
1907 }
1908
1830 1909 #skillLevelUpEvents (event)
1831 1910 {
1832 1911 const levelUps = event?.levelUps ?? [];
@@ -31,6 +31,7 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
31import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
32import { mobComponents } from "./spawners.js";
32import { mobComponents } from "./spawners.js";
33import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
33import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
34import { defaultPlayerSpells, publicSpellsView } from "../../../shared/spells/state.js";
34import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
35import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
35import { BlockType } from "../../../shared/definitions/tiles.js";
36import { BlockType } from "../../../shared/definitions/tiles.js";
36import { ItemId } from "../../../shared/definitions/items.js";
37import { ItemId } from "../../../shared/definitions/items.js";
@@ -224,6 +225,11 @@ export class Simulation
224 events.push(...this.#skillLevelUpEvents(event));
225 events.push(...this.#skillLevelUpEvents(event));
225 continue;
226 continue;
226 }
227 }
228 if (event.type === "spells-updated")
229 {
230 this.#applySpellsUpdated(event);
231 continue;
232 }
227 if (event.type === "inventory" && event.characterId)
233 if (event.type === "inventory" && event.characterId)
228 {
234 {
229 this.#saveBagFromView(event.characterId, {
235 this.#saveBagFromView(event.characterId, {
@@ -276,6 +282,11 @@ export class Simulation
276 events.push(...this.#skillLevelUpEvents(event));
282 events.push(...this.#skillLevelUpEvents(event));
277 continue;
283 continue;
278 }
284 }
285 if (event.type === "spells-updated")
286 {
287 this.#applySpellsUpdated(event);
288 continue;
289 }
279 this.#persistGroundEvent(event);
290 this.#persistGroundEvent(event);
280 if (event.type !== "skills-updated")
291 if (event.type !== "skills-updated")
281 { events.push(event); }
292 { events.push(event); }
@@ -347,12 +358,19 @@ export class Simulation
347 vaultReserved: []
358 vaultReserved: []
348 };
359 };
349 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
360 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
361 const spells = this.stateDb.getSpells(character.character_id) ?? defaultPlayerSpells();
350 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
362 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
351 if (enforceMinimumSkillLevels(skills))
363 if (enforceMinimumSkillLevels(skills))
352 { this.stateDb.saveSkills(character.character_id, skills); }
364 { this.stateDb.saveSkills(character.character_id, skills); }
353 const maxHealth = playerMaxHealth(skills);
365 const maxHealth = playerMaxHealth(skills);
354 const maxStamina = playerMaxStamina(skills);
366 const maxStamina = playerMaxStamina(skills);
355 const isDead = !!row.is_dead;
367 const isDead = !!row.is_dead;
368 const savedHealth = row.health_current;
369 const currentHealth = isDead
370 ? 0
371 : savedHealth != null
372 ? Math.max(0, Math.min(maxHealth, savedHealth | 0))
373 : maxHealth;
356 const entityId = this.nextEntityId++;
374 const entityId = this.nextEntityId++;
357 const components = {
375 const components = {
358 position: { tileX, tileY },
376 position: { tileX, tileY },
@@ -376,10 +394,17 @@ export class Simulation
376 slots: bag.vault ?? [],
394 slots: bag.vault ?? [],
377 reserved: bag.vaultReserved ?? []
395 reserved: bag.vaultReserved ?? []
378 },
396 },
379 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
397 health: { current: currentHealth, max: maxHealth },
380 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
398 stamina: { current: maxStamina, max: maxStamina, xpDebt: 0 },
381 combat: { targetEntityId: null, nextSwingAt: 0 },
399 combat: { targetEntityId: null, nextSwingAt: 0 },
382 skills,
400 skills,
401 spells,
402 spellcasting: {
403 armedSpellId: null,
404 repeatSpellId: null,
405 repeatTargetEntityId: null,
406 nextCastAt: 0
407 },
383 };
408 };
384 if (isDead)
409 if (isDead)
385 { components.dead = {}; }
410 { components.dead = {}; }
@@ -564,6 +589,15 @@ export class Simulation
564 });
589 });
565 }
590 }
566
591
592 pushSpells (characterId, payload)
593 {
594 this.pendingPrivate.push({
595 type: "spells",
596 characterId,
597 ...payload
598 });
599 }
600
567 skillsOf (entityId)
601 skillsOf (entityId)
568 {
602 {
569 const record = this.directory.get(entityId);
603 const record = this.directory.get(entityId);
@@ -575,6 +609,17 @@ export class Simulation
575 });
609 });
576 }
610 }
577
611
612 spellsOf (entityId)
613 {
614 const record = this.directory.get(entityId);
615 if (!record)
616 { return null; }
617 return this.workers[record.workerId].call({
618 type: WorkerMessage.inspectSpells,
619 entityId
620 });
621 }
622
578 staminaOf (entityId)
623 staminaOf (entityId)
579 {
624 {
580 const record = this.directory.get(entityId);
625 const record = this.directory.get(entityId);
@@ -692,6 +737,8 @@ export class Simulation
692 dropped.tileY,
737 dropped.tileY,
693 dropped.gait ?? GAIT.walk
738 dropped.gait ?? GAIT.walk
694 );
739 );
740 if (dropped.health != null)
741 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
695 this.#queueReplication(replicationDespawn(dropped));
742 this.#queueReplication(replicationDespawn(dropped));
696 }
743 }
697 this.#forget(entityId);
744 this.#forget(entityId);
@@ -982,7 +1029,16 @@ export class Simulation
982 }
1029 }
983 for (const event of result?.events ?? [])
1030 for (const event of result?.events ?? [])
984 { this.#persistGroundEvent(event); }
1031 { this.#persistGroundEvent(event); }
985 const events = [...(result?.events ?? [])];
1032 const events = [];
1033 for (const event of result?.events ?? [])
1034 {
1035 if (event.type === "spells-updated")
1036 {
1037 this.#applySpellsUpdated(event);
1038 continue;
1039 }
1040 events.push(event);
1041 }
986 if (result?.private)
1042 if (result?.private)
987 {
1043 {
988 events.push({
1044 events.push({
@@ -1040,6 +1096,11 @@ export class Simulation
1040 events.push(...this.#skillLevelUpEvents(event));
1096 events.push(...this.#skillLevelUpEvents(event));
1041 continue;
1097 continue;
1042 }
1098 }
1099 if (event.type === "spells-updated")
1100 {
1101 this.#applySpellsUpdated(event);
1102 continue;
1103 }
1043 if (event.type === "player-died")
1104 if (event.type === "player-died")
1044 {
1105 {
1045 events.push(...this.#applyPlayerDeath(event));
1106 events.push(...this.#applyPlayerDeath(event));
@@ -1096,6 +1157,11 @@ export class Simulation
1096 events.push(...this.#skillLevelUpEvents(event));
1157 events.push(...this.#skillLevelUpEvents(event));
1097 continue;
1158 continue;
1098 }
1159 }
1160 if (event.type === "spells-updated")
1161 {
1162 this.#applySpellsUpdated(event);
1163 continue;
1164 }
1099 if (event.type === "player-died")
1165 if (event.type === "player-died")
1100 {
1166 {
1101 events.push(...this.#applyPlayerDeath(event));
1167 events.push(...this.#applyPlayerDeath(event));
@@ -1241,6 +1307,8 @@ export class Simulation
1241 throw error;
1307 throw error;
1242 }
1308 }
1243 this.stateDb.setCharacterDead(characterId, false);
1309 this.stateDb.setCharacterDead(characterId, false);
1310 const respawnHealth = playerMaxHealth(skills);
1311 this.stateDb.saveCharacterHealth(characterId, respawnHealth);
1244 this.stateDb.saveCharacterPosition(
1312 this.stateDb.saveCharacterPosition(
1245 characterId,
1313 characterId,
1246 destination.tileX,
1314 destination.tileX,
@@ -1827,6 +1895,17 @@ export class Simulation
1827 this.pushSkills(event.characterId, event.skills ?? []);
1895 this.pushSkills(event.characterId, event.skills ?? []);
1828 }
1896 }
1829
1897
1898 #applySpellsUpdated (event)
1899 {
1900 if (!event?.characterId || !event.stored)
1901 { return; }
1902 this.stateDb.saveSpells(event.characterId, event.stored);
1903 this.pushSpells(event.characterId, {
1904 spells: event.spells ?? [],
1905 autoCast: !!event.autoCast
1906 });
1907 }
1908
1830 #skillLevelUpEvents (event)
1909 #skillLevelUpEvents (event)
1831 {
1910 {
1832 const levelUps = event?.levelUps ?? [];
1911 const levelUps = event?.levelUps ?? [];
server/src/simulation/spawners.js +10 −1
@@ -8,10 +8,12 @@ import {
8 8 MobId,
9 9 spawnerEquipmentSlot
10 10 } from "../../../shared/definitions/mobs.js";
11 import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";
11 12 import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
12 13 import { emptyEquipment } from "../../../shared/items/inventory.js";
13 14 import { itemDefinition } from "../../../shared/definitions/items.js";
14 15 import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
16 import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
15 17 import { Component } from "../ecs/components.js";
16 18 import { tileToChunk, tileToRegion } from "../world/coordinates.js";
17 19
@@ -171,9 +173,16 @@ export function mobComponents (request)
171 173
172 174 const equipmentSlots = emptyEquipment().slots;
173 175 const authored = request.equipment ?? {};
176 const defaults = def.usePlayerBody ? npcDefaultEquipment(displayName, sex) : null;
174 177 for (const slot of Object.keys(equipmentSlots))
175 178 {
176 const { itemId, dyeColor } = spawnerEquipmentSlot(authored[slot]);
179 const authoredEntry = authored[slot];
180 let { itemId, dyeColor } = spawnerEquipmentSlot(authoredEntry);
181 if (!itemId && defaults?.[slot])
182 {
183 itemId = defaults[slot].itemId;
184 dyeColor = defaults[slot].dyeColor ?? null;
185 }
177 186 if (!itemId)
178 187 { continue; }
179 188 const itemDef = itemDefinition(itemId);
@@ -8,10 +8,12 @@ import {
8 MobId,
8 MobId,
9 spawnerEquipmentSlot
9 spawnerEquipmentSlot
10} from "../../../shared/definitions/mobs.js";
10} from "../../../shared/definitions/mobs.js";
11import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";
11import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
12import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
12import { emptyEquipment } from "../../../shared/items/inventory.js";
13import { emptyEquipment } from "../../../shared/items/inventory.js";
13import { itemDefinition } from "../../../shared/definitions/items.js";
14import { itemDefinition } from "../../../shared/definitions/items.js";
14import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
15import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
16import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
15import { Component } from "../ecs/components.js";
17import { Component } from "../ecs/components.js";
16import { tileToChunk, tileToRegion } from "../world/coordinates.js";
18import { tileToChunk, tileToRegion } from "../world/coordinates.js";
17
19
@@ -171,9 +173,16 @@ export function mobComponents (request)
171
173
172 const equipmentSlots = emptyEquipment().slots;
174 const equipmentSlots = emptyEquipment().slots;
173 const authored = request.equipment ?? {};
175 const authored = request.equipment ?? {};
176 const defaults = def.usePlayerBody ? npcDefaultEquipment(displayName, sex) : null;
174 for (const slot of Object.keys(equipmentSlots))
177 for (const slot of Object.keys(equipmentSlots))
175 {
178 {
176 const { itemId, dyeColor } = spawnerEquipmentSlot(authored[slot]);
179 const authoredEntry = authored[slot];
180 let { itemId, dyeColor } = spawnerEquipmentSlot(authoredEntry);
181 if (!itemId && defaults?.[slot])
182 {
183 itemId = defaults[slot].itemId;
184 dyeColor = defaults[slot].dyeColor ?? null;
185 }
177 if (!itemId)
186 if (!itemId)
178 { continue; }
187 { continue; }
179 const itemDef = itemDefinition(itemId);
188 const itemDef = itemDefinition(itemId);
server/src/simulation/workerWorld.js +73 −7
@@ -9,7 +9,7 @@ import {
9 9 tileToLocal,
10 10 tileToRegion
11 11 } from "../world/coordinates.js";
12 import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
12 import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
13 13 import { closedNeighborEdges } from "../world/chunkFlags.js";
14 14 import { EcsWorld } from "../ecs/world.js";
15 15 import { Component } from "../ecs/components.js";
@@ -30,7 +30,8 @@ import {
30 30 publicGroundItem,
31 31 setGroundItemsForRegion
32 32 } from "../items/bags.js";
33 import { handleAlchemyCommand } from "../alchemy/service.js";
33 import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";
34 import { publicSpellsView } from "../../../shared/spells/state.js";
34 35 import {
35 36 handleGatherCommand,
36 37 stepGather,
@@ -40,14 +41,18 @@ import {
40 41 clearPlantRespawnsForChunk
41 42 } from "../gathering/service.js";
42 43 import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
44 import { handleAlchemyCommand } from "../alchemy/service.js";
43 45 import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
44 46 import {
45 47 applyRemoteMeleeSwing,
46 48 applyRemoteRangedShot,
49 attackProfileOf,
47 50 clearEngage,
48 51 engageTarget,
49 52 ensureMobCombat,
50 53 isUntargetable,
54 queueMeleeApproach,
55 queueStandInRangeApproach,
51 56 resolveCombatTarget,
52 57 stepAggression,
53 58 stepCombat
@@ -82,6 +87,7 @@ export class WorkerWorld
82 87 this.groundByTile = new Map();
83 88 this.oreRespawns = new Map();
84 89 this.treeRespawns = new Map();
90 this.pendingSpellImpacts = [];
85 91 this.settings = { ...DEFAULT_WORLD_SETTINGS };
86 92 this.activeRevisionId = 1;
87 93 }
@@ -125,6 +131,8 @@ export class WorkerWorld
125 131 return this.#inspectBag(message.entityId);
126 132 case WorkerMessage.inspectSkills:
127 133 return this.#inspectSkills(message.entityId);
134 case WorkerMessage.inspectSpells:
135 return this.#inspectSpells(message.entityId);
128 136 case WorkerMessage.inspectStamina:
129 137 return this.#inspectStamina(message.entityId);
130 138 case WorkerMessage.applyBag:
@@ -418,6 +426,14 @@ export class WorkerWorld
418 426 return this.#follow(sessionId, command.characterId, command.targetEntityId);
419 427 case "cancel-follow":
420 428 return this.#cancelFollow(sessionId, command.characterId);
429 case "set-spell-favorite":
430 case "set-spell-autocast":
431 case "arm-spell":
432 case "cancel-arm-spell":
433 case "cast-spell-tile":
434 case "cast-spell-entity":
435 case "read-spellbook":
436 return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
421 437 default:
422 438 {
423 439 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
@@ -554,6 +570,23 @@ export class WorkerWorld
554 570 return skills;
555 571 }
556 572
573 #inspectSpells (entityId)
574 {
575 const handle = this.ecs.handleOf(entityId);
576 if (handle == null)
577 { return null; }
578 const spells = this.ecs.get(handle, Component.spells);
579 const skills = this.ecs.get(handle, Component.skills);
580 const casting = this.ecs.get(handle, Component.spellcasting);
581 if (!spells)
582 { return null; }
583 return {
584 spells: publicSpellsView(spells, skills),
585 autoCast: !!spells.autoCast,
586 armedSpellId: casting?.armedSpellId ?? null
587 };
588 }
589
557 590 #inspectStamina (entityId)
558 591 {
559 592 const handle = this.ecs.handleOf(entityId);
@@ -653,6 +686,9 @@ export class WorkerWorld
653 686 clearEngage(this.ecs, entityId);
654 687 clearFollow(this.ecs, entityId);
655 688 cancelGather(this.ecs, handle);
689 const casting = this.ecs.get(handle, Component.spellcasting);
690 if (casting)
691 { casting.pendingCast = null; }
656 692 const position = this.ecs.get(handle, Component.position);
657 693 const movement = this.ecs.get(handle, Component.movement);
658 694 let path = this.ecs.get(handle, Component.path);
@@ -700,11 +736,29 @@ export class WorkerWorld
700 736 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
701 737 clearFollow(this.ecs, entityId);
702 738 cancelGather(this.ecs, handle);
703 // Engage only the attacker. Targets retaliate on the first resolved swing.
704 739 engageTarget(this.ecs, entityId, targetEntityId, now);
705 const path = this.ecs.get(handle, Component.path);
706 if (path)
707 { path.tiles = []; }
740 const position = this.ecs.get(handle, Component.position);
741 const profile = attackProfileOf(this.ecs, handle);
742 if (position && target.pos)
743 {
744 if (profile.mode === "ranged")
745 {
746 queueStandInRangeApproach(
747 this,
748 entityId,
749 handle,
750 position,
751 target.pos.tileX,
752 target.pos.tileY,
753 profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
754 1
755 );
756 }
757 else if (profile.mode === "melee")
758 {
759 queueMeleeApproach(this, entityId, handle, position, target.pos);
760 }
761 }
708 762 return { events: [] };
709 763 }
710 764
@@ -991,6 +1045,10 @@ export class WorkerWorld
991 1045 }
992 1046 stepAggression(this, now);
993 1047 events.push(...stepCombat(this, now));
1048 events.push(...stepPendingSpellCast(this, now));
1049 events.push(...processSpellImpacts(this, now));
1050 events.push(...stepSpellAutoCast(this, now));
1051 events.push(...tickSpellLights(this, now));
994 1052 stepFollow(this);
995 1053 const gather = stepGather(this, now);
996 1054 events.push(...gather.events);
@@ -1154,7 +1212,7 @@ export class WorkerWorld
1154 1212 position.tileY,
1155 1213 goal.x,
1156 1214 goal.y,
1157 (x, y) => this.walkableFor(entityId, x, y),
1215 (x, y) => this.isClearStanding(entityId, x, y),
1158 1216 bounds.minX,
1159 1217 bounds.minY,
1160 1218 bounds.maxX,
@@ -1585,6 +1643,14 @@ export class WorkerWorld
1585 1643 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1586 1644 }
1587 1645
1646 isClearForRangedAttack (tileX, tileY)
1647 {
1648 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1649 if (!data.open)
1650 { return false; }
1651 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
1652 }
1653
1588 1654 #walkableFor (entityId, tileX, tileY)
1589 1655 {
1590 1656 return this.walkableFor(entityId, tileX, tileY);
@@ -9,7 +9,7 @@ import {
9 tileToLocal,
9 tileToLocal,
10 tileToRegion
10 tileToRegion
11} from "../world/coordinates.js";
11} from "../world/coordinates.js";
12import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
12import { cloneChunkData, createEmptyChunkData, isChunkTilePassable, isChunkTileClearForRangedAttacks } from "../world/chunkData.js";
13import { closedNeighborEdges } from "../world/chunkFlags.js";
13import { closedNeighborEdges } from "../world/chunkFlags.js";
14import { EcsWorld } from "../ecs/world.js";
14import { EcsWorld } from "../ecs/world.js";
15import { Component } from "../ecs/components.js";
15import { Component } from "../ecs/components.js";
@@ -30,7 +30,8 @@ import {
30 publicGroundItem,
30 publicGroundItem,
31 setGroundItemsForRegion
31 setGroundItemsForRegion
32} from "../items/bags.js";
32} from "../items/bags.js";
33import { handleAlchemyCommand } from "../alchemy/service.js";
33import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights } from "../spells/service.js";
34import { publicSpellsView } from "../../../shared/spells/state.js";
34import {
35import {
35 handleGatherCommand,
36 handleGatherCommand,
36 stepGather,
37 stepGather,
@@ -40,14 +41,18 @@ import {
40 clearPlantRespawnsForChunk
41 clearPlantRespawnsForChunk
41} from "../gathering/service.js";
42} from "../gathering/service.js";
42import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
43import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
44import { handleAlchemyCommand } from "../alchemy/service.js";
43import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
45import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
44import {
46import {
45 applyRemoteMeleeSwing,
47 applyRemoteMeleeSwing,
46 applyRemoteRangedShot,
48 applyRemoteRangedShot,
49 attackProfileOf,
47 clearEngage,
50 clearEngage,
48 engageTarget,
51 engageTarget,
49 ensureMobCombat,
52 ensureMobCombat,
50 isUntargetable,
53 isUntargetable,
54 queueMeleeApproach,
55 queueStandInRangeApproach,
51 resolveCombatTarget,
56 resolveCombatTarget,
52 stepAggression,
57 stepAggression,
53 stepCombat
58 stepCombat
@@ -82,6 +87,7 @@ export class WorkerWorld
82 this.groundByTile = new Map();
87 this.groundByTile = new Map();
83 this.oreRespawns = new Map();
88 this.oreRespawns = new Map();
84 this.treeRespawns = new Map();
89 this.treeRespawns = new Map();
90 this.pendingSpellImpacts = [];
85 this.settings = { ...DEFAULT_WORLD_SETTINGS };
91 this.settings = { ...DEFAULT_WORLD_SETTINGS };
86 this.activeRevisionId = 1;
92 this.activeRevisionId = 1;
87 }
93 }
@@ -125,6 +131,8 @@ export class WorkerWorld
125 return this.#inspectBag(message.entityId);
131 return this.#inspectBag(message.entityId);
126 case WorkerMessage.inspectSkills:
132 case WorkerMessage.inspectSkills:
127 return this.#inspectSkills(message.entityId);
133 return this.#inspectSkills(message.entityId);
134 case WorkerMessage.inspectSpells:
135 return this.#inspectSpells(message.entityId);
128 case WorkerMessage.inspectStamina:
136 case WorkerMessage.inspectStamina:
129 return this.#inspectStamina(message.entityId);
137 return this.#inspectStamina(message.entityId);
130 case WorkerMessage.applyBag:
138 case WorkerMessage.applyBag:
@@ -418,6 +426,14 @@ export class WorkerWorld
418 return this.#follow(sessionId, command.characterId, command.targetEntityId);
426 return this.#follow(sessionId, command.characterId, command.targetEntityId);
419 case "cancel-follow":
427 case "cancel-follow":
420 return this.#cancelFollow(sessionId, command.characterId);
428 return this.#cancelFollow(sessionId, command.characterId);
429 case "set-spell-favorite":
430 case "set-spell-autocast":
431 case "arm-spell":
432 case "cancel-arm-spell":
433 case "cast-spell-tile":
434 case "cast-spell-entity":
435 case "read-spellbook":
436 return handleSpellCommand(this, sessionId, command, message.now ?? Date.now()) ?? { events: [] };
421 default:
437 default:
422 {
438 {
423 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
439 const gather = handleGatherCommand(this, sessionId, command, message.now ?? Date.now());
@@ -554,6 +570,23 @@ export class WorkerWorld
554 return skills;
570 return skills;
555 }
571 }
556
572
573 #inspectSpells (entityId)
574 {
575 const handle = this.ecs.handleOf(entityId);
576 if (handle == null)
577 { return null; }
578 const spells = this.ecs.get(handle, Component.spells);
579 const skills = this.ecs.get(handle, Component.skills);
580 const casting = this.ecs.get(handle, Component.spellcasting);
581 if (!spells)
582 { return null; }
583 return {
584 spells: publicSpellsView(spells, skills),
585 autoCast: !!spells.autoCast,
586 armedSpellId: casting?.armedSpellId ?? null
587 };
588 }
589
557 #inspectStamina (entityId)
590 #inspectStamina (entityId)
558 {
591 {
559 const handle = this.ecs.handleOf(entityId);
592 const handle = this.ecs.handleOf(entityId);
@@ -653,6 +686,9 @@ export class WorkerWorld
653 clearEngage(this.ecs, entityId);
686 clearEngage(this.ecs, entityId);
654 clearFollow(this.ecs, entityId);
687 clearFollow(this.ecs, entityId);
655 cancelGather(this.ecs, handle);
688 cancelGather(this.ecs, handle);
689 const casting = this.ecs.get(handle, Component.spellcasting);
690 if (casting)
691 { casting.pendingCast = null; }
656 const position = this.ecs.get(handle, Component.position);
692 const position = this.ecs.get(handle, Component.position);
657 const movement = this.ecs.get(handle, Component.movement);
693 const movement = this.ecs.get(handle, Component.movement);
658 let path = this.ecs.get(handle, Component.path);
694 let path = this.ecs.get(handle, Component.path);
@@ -700,11 +736,29 @@ export class WorkerWorld
700 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
736 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
701 clearFollow(this.ecs, entityId);
737 clearFollow(this.ecs, entityId);
702 cancelGather(this.ecs, handle);
738 cancelGather(this.ecs, handle);
703 // Engage only the attacker. Targets retaliate on the first resolved swing.
704 engageTarget(this.ecs, entityId, targetEntityId, now);
739 engageTarget(this.ecs, entityId, targetEntityId, now);
705 const path = this.ecs.get(handle, Component.path);
740 const position = this.ecs.get(handle, Component.position);
706 if (path)
741 const profile = attackProfileOf(this.ecs, handle);
707 { path.tiles = []; }
742 if (position && target.pos)
743 {
744 if (profile.mode === "ranged")
745 {
746 queueStandInRangeApproach(
747 this,
748 entityId,
749 handle,
750 position,
751 target.pos.tileX,
752 target.pos.tileY,
753 profile.rangeTiles | 0 || COMBAT_RANGE_TILES,
754 1
755 );
756 }
757 else if (profile.mode === "melee")
758 {
759 queueMeleeApproach(this, entityId, handle, position, target.pos);
760 }
761 }
708 return { events: [] };
762 return { events: [] };
709 }
763 }
710
764
@@ -991,6 +1045,10 @@ export class WorkerWorld
991 }
1045 }
992 stepAggression(this, now);
1046 stepAggression(this, now);
993 events.push(...stepCombat(this, now));
1047 events.push(...stepCombat(this, now));
1048 events.push(...stepPendingSpellCast(this, now));
1049 events.push(...processSpellImpacts(this, now));
1050 events.push(...stepSpellAutoCast(this, now));
1051 events.push(...tickSpellLights(this, now));
994 stepFollow(this);
1052 stepFollow(this);
995 const gather = stepGather(this, now);
1053 const gather = stepGather(this, now);
996 events.push(...gather.events);
1054 events.push(...gather.events);
@@ -1154,7 +1212,7 @@ export class WorkerWorld
1154 position.tileY,
1212 position.tileY,
1155 goal.x,
1213 goal.x,
1156 goal.y,
1214 goal.y,
1157 (x, y) => this.walkableFor(entityId, x, y),
1215 (x, y) => this.isClearStanding(entityId, x, y),
1158 bounds.minX,
1216 bounds.minX,
1159 bounds.minY,
1217 bounds.minY,
1160 bounds.maxX,
1218 bounds.maxX,
@@ -1585,6 +1643,14 @@ export class WorkerWorld
1585 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1643 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1586 }
1644 }
1587
1645
1646 isClearForRangedAttack (tileX, tileY)
1647 {
1648 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1649 if (!data.open)
1650 { return false; }
1651 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
1652 }
1653
1588 #walkableFor (entityId, tileX, tileY)
1654 #walkableFor (entityId, tileX, tileY)
1589 {
1655 {
1590 return this.walkableFor(entityId, tileX, tileY);
1656 return this.walkableFor(entityId, tileX, tileY);
server/src/spells/lights.js added +168 −0
@@ -0,0 +1,168 @@
1 import { Component } from "../ecs/components.js";
2 import { tileKey } from "../world/coordinates.js";
3 import {
4 LIGHT_FADE_MS,
5 LIGHT_MAX_DURATION_MS,
6 LIGHT_OWNER_DISTANCE_CAP_MS,
7 SPELL_LIGHT_INTENSITY,
8 SPELL_LIGHT_RANGE_TILES,
9 COMBAT_RANGE_TILES
10 } from "../../../shared/spells/constants.js";
11
12 /**
13 * Authoritative temporary spell lights keyed by tile.
14 * @typedef {object} SpellLight
15 * @property {number} tileX
16 * @property {number} tileY
17 * @property {number} ownerEntityId
18 * @property {number} expiresAt
19 * @property {number} maxDurationMs
20 * @property {number} baseRange
21 * @property {number} baseIntensity
22 */
23
24 export class SpellLightRegistry
25 {
26 constructor ()
27 {
28 /** @type {Map<string, SpellLight>} */
29 this.byTile = new Map();
30 this.nextLightId = 1;
31 }
32
33 getAt (tileX, tileY)
34 {
35 return this.byTile.get(tileKey(tileX, tileY)) ?? null;
36 }
37
38 /** @returns {{ light: SpellLight, extended: boolean }} */
39 placeOrExtend ({
40 tileX,
41 tileY,
42 ownerEntityId,
43 durationMs,
44 now = Date.now()
45 })
46 {
47 const key = tileKey(tileX, tileY);
48 const addMs = Math.max(0, Math.min(LIGHT_MAX_DURATION_MS, durationMs | 0));
49 const existing = this.byTile.get(key);
50 if (existing)
51 {
52 const remaining = Math.max(0, existing.expiresAt - now);
53 const next = Math.min(LIGHT_MAX_DURATION_MS, remaining + addMs);
54 existing.expiresAt = now + next;
55 existing.maxDurationMs = Math.max(existing.maxDurationMs, next);
56 existing.ownerEntityId = ownerEntityId;
57 return { light: existing, extended: true };
58 }
59 const light = {
60 lightId: this.nextLightId++,
61 tileX,
62 tileY,
63 ownerEntityId,
64 expiresAt: now + addMs,
65 maxDurationMs: addMs,
66 baseRange: SPELL_LIGHT_RANGE_TILES,
67 baseIntensity: SPELL_LIGHT_INTENSITY
68 };
69 this.byTile.set(key, light);
70 return { light, extended: false };
71 }
72
73 removeAt (tileX, tileY)
74 {
75 const key = tileKey(tileX, tileY);
76 const existing = this.byTile.get(key);
77 if (!existing)
78 { return null; }
79 this.byTile.delete(key);
80 return existing;
81 }
82
83 /** Tick ownership distance penalty and expiry. Returns replication events. */
84 tick (world, now = Date.now())
85 {
86 const events = [];
87 for (const [, light] of [...this.byTile.entries()])
88 {
89 if (now >= light.expiresAt)
90 {
91 this.byTile.delete(tileKey(light.tileX, light.tileY));
92 events.push({ type: "spell-light-remove", tileX: light.tileX, tileY: light.tileY });
93 continue;
94 }
95 const ownerHandle = world.ecs.handleOf(light.ownerEntityId);
96 const ownerPos = ownerHandle != null ? world.ecs.get(ownerHandle, Component.position) : null;
97 if (ownerPos)
98 {
99 const dist = Math.max(
100 Math.abs(ownerPos.tileX - light.tileX),
101 Math.abs(ownerPos.tileY - light.tileY)
102 );
103 if (dist > COMBAT_RANGE_TILES)
104 {
105 const remaining = light.expiresAt - now;
106 const capped = Math.min( remaining, LIGHT_OWNER_DISTANCE_CAP_MS);
107 if (capped !== remaining)
108 {
109 light.expiresAt = now + capped;
110 events.push({ type: "spell-light-update", ...publicSpellLight(light, now) });
111 }
112 }
113 }
114 }
115 return events;
116 }
117
118 listInBounds (minX, minY, maxX, maxY, now = Date.now())
119 {
120 const out = [];
121 for (const light of this.byTile.values())
122 {
123 if (light.tileX < minX || light.tileX > maxX || light.tileY < minY || light.tileY > maxY)
124 { continue; }
125 if (now >= light.expiresAt)
126 { continue; }
127 out.push(publicSpellLight(light, now));
128 }
129 return out;
130 }
131 }
132
133 export function publicSpellLight (light, now = Date.now())
134 {
135 const remainingMs = Math.max(0, light.expiresAt - now);
136 const fadeT = remainingMs <= LIGHT_FADE_MS ? remainingMs / LIGHT_FADE_MS : 1;
137 const range = light.baseRange * fadeT;
138 const intensity = light.baseIntensity * fadeT;
139 return {
140 tileX: light.tileX,
141 tileY: light.tileY,
142 ownerEntityId: light.ownerEntityId,
143 remainingMs,
144 rangeTiles: range,
145 intensity,
146 expiresAt: light.expiresAt
147 };
148 }
149
150 export function spellLightsForDynamicLighting (registry, now = Date.now())
151 {
152 const out = [];
153 for (const light of registry.byTile.values())
154 {
155 if (now >= light.expiresAt)
156 { continue; }
157 const pub = publicSpellLight(light, now);
158 if (pub.intensity <= 0 || pub.rangeTiles <= 0)
159 { continue; }
160 out.push({
161 tileX: light.tileX,
162 tileY: light.tileY,
163 range: pub.rangeTiles,
164 intensity: pub.intensity
165 });
166 }
167 return out;
168 }
@@ -0,0 +1,168 @@
1import { Component } from "../ecs/components.js";
2import { tileKey } from "../world/coordinates.js";
3import {
4 LIGHT_FADE_MS,
5 LIGHT_MAX_DURATION_MS,
6 LIGHT_OWNER_DISTANCE_CAP_MS,
7 SPELL_LIGHT_INTENSITY,
8 SPELL_LIGHT_RANGE_TILES,
9 COMBAT_RANGE_TILES
10} from "../../../shared/spells/constants.js";
11
12/**
13 * Authoritative temporary spell lights keyed by tile.
14 * @typedef {object} SpellLight
15 * @property {number} tileX
16 * @property {number} tileY
17 * @property {number} ownerEntityId
18 * @property {number} expiresAt
19 * @property {number} maxDurationMs
20 * @property {number} baseRange
21 * @property {number} baseIntensity
22 */
23
24export class SpellLightRegistry
25{
26 constructor ()
27 {
28 /** @type {Map<string, SpellLight>} */
29 this.byTile = new Map();
30 this.nextLightId = 1;
31 }
32
33 getAt (tileX, tileY)
34 {
35 return this.byTile.get(tileKey(tileX, tileY)) ?? null;
36 }
37
38 /** @returns {{ light: SpellLight, extended: boolean }} */
39 placeOrExtend ({
40 tileX,
41 tileY,
42 ownerEntityId,
43 durationMs,
44 now = Date.now()
45 })
46 {
47 const key = tileKey(tileX, tileY);
48 const addMs = Math.max(0, Math.min(LIGHT_MAX_DURATION_MS, durationMs | 0));
49 const existing = this.byTile.get(key);
50 if (existing)
51 {
52 const remaining = Math.max(0, existing.expiresAt - now);
53 const next = Math.min(LIGHT_MAX_DURATION_MS, remaining + addMs);
54 existing.expiresAt = now + next;
55 existing.maxDurationMs = Math.max(existing.maxDurationMs, next);
56 existing.ownerEntityId = ownerEntityId;
57 return { light: existing, extended: true };
58 }
59 const light = {
60 lightId: this.nextLightId++,
61 tileX,
62 tileY,
63 ownerEntityId,
64 expiresAt: now + addMs,
65 maxDurationMs: addMs,
66 baseRange: SPELL_LIGHT_RANGE_TILES,
67 baseIntensity: SPELL_LIGHT_INTENSITY
68 };
69 this.byTile.set(key, light);
70 return { light, extended: false };
71 }
72
73 removeAt (tileX, tileY)
74 {
75 const key = tileKey(tileX, tileY);
76 const existing = this.byTile.get(key);
77 if (!existing)
78 { return null; }
79 this.byTile.delete(key);
80 return existing;
81 }
82
83 /** Tick ownership distance penalty and expiry. Returns replication events. */
84 tick (world, now = Date.now())
85 {
86 const events = [];
87 for (const [, light] of [...this.byTile.entries()])
88 {
89 if (now >= light.expiresAt)
90 {
91 this.byTile.delete(tileKey(light.tileX, light.tileY));
92 events.push({ type: "spell-light-remove", tileX: light.tileX, tileY: light.tileY });
93 continue;
94 }
95 const ownerHandle = world.ecs.handleOf(light.ownerEntityId);
96 const ownerPos = ownerHandle != null ? world.ecs.get(ownerHandle, Component.position) : null;
97 if (ownerPos)
98 {
99 const dist = Math.max(
100 Math.abs(ownerPos.tileX - light.tileX),
101 Math.abs(ownerPos.tileY - light.tileY)
102 );
103 if (dist > COMBAT_RANGE_TILES)
104 {
105 const remaining = light.expiresAt - now;
106 const capped = Math.min( remaining, LIGHT_OWNER_DISTANCE_CAP_MS);
107 if (capped !== remaining)
108 {
109 light.expiresAt = now + capped;
110 events.push({ type: "spell-light-update", ...publicSpellLight(light, now) });
111 }
112 }
113 }
114 }
115 return events;
116 }
117
118 listInBounds (minX, minY, maxX, maxY, now = Date.now())
119 {
120 const out = [];
121 for (const light of this.byTile.values())
122 {
123 if (light.tileX < minX || light.tileX > maxX || light.tileY < minY || light.tileY > maxY)
124 { continue; }
125 if (now >= light.expiresAt)
126 { continue; }
127 out.push(publicSpellLight(light, now));
128 }
129 return out;
130 }
131}
132
133export function publicSpellLight (light, now = Date.now())
134{
135 const remainingMs = Math.max(0, light.expiresAt - now);
136 const fadeT = remainingMs <= LIGHT_FADE_MS ? remainingMs / LIGHT_FADE_MS : 1;
137 const range = light.baseRange * fadeT;
138 const intensity = light.baseIntensity * fadeT;
139 return {
140 tileX: light.tileX,
141 tileY: light.tileY,
142 ownerEntityId: light.ownerEntityId,
143 remainingMs,
144 rangeTiles: range,
145 intensity,
146 expiresAt: light.expiresAt
147 };
148}
149
150export function spellLightsForDynamicLighting (registry, now = Date.now())
151{
152 const out = [];
153 for (const light of registry.byTile.values())
154 {
155 if (now >= light.expiresAt)
156 { continue; }
157 const pub = publicSpellLight(light, now);
158 if (pub.intensity <= 0 || pub.rangeTiles <= 0)
159 { continue; }
160 out.push({
161 tileX: light.tileX,
162 tileY: light.tileY,
163 range: pub.rangeTiles,
164 intensity: pub.intensity
165 });
166 }
167 return out;
168}
server/src/spells/service.js added +707 −0
@@ -0,0 +1,707 @@
1 import { Component } from "../ecs/components.js";
2 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
3 import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";
4 import {
5 canCastSpell,
6 defaultPlayerSpells,
7 normalizePlayerSpells,
8 publicSpellsView,
9 storedPlayerSpells,
10 toggleFavorite,
11 learnSpell
12 } from "../../../shared/spells/state.js";
13 import {
14 CAST_FLASH_MS,
15 COMBAT_RANGE_TILES,
16 LIGHT_DURATION_MS_PER_MIND,
17 SPELL_COOLDOWN_MS,
18 SPELL_PROJECTILE_MS,
19 castFlashRadiusTiles
20 } from "../../../shared/spells/constants.js";
21 import {
22 mobElementAffinities,
23 ElementMultiplier,
24 resolveMagicAttack,
25 resolveSpellCast,
26 resolveSpellPotency
27 } from "../../../shared/combat/magic.js";
28 import { mobDefinition } from "../../../shared/definitions/mobs.js";
29 import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
30 import {
31 chebyshev,
32 hasCombatLineOfSight,
33 queueStandInRangeApproach,
34 resolveCombatTarget
35 } from "../combat/service.js";
36 import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
37 import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
38 import { publicSpellLight, SpellLightRegistry } from "./lights.js";
39 import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";
40 import { bagView } from "../items/bags.js";
41
42 const MAGIC_ATTACK_PROFILE = Object.freeze({
43 hitSkillId: SkillId.magic,
44 damageSkillId: SkillId.mind
45 });
46
47 export function ensureSpellComponents (ecs, handle, storedSpells = null)
48 {
49 if (!ecs.get(handle, Component.spells))
50 {
51 ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));
52 }
53 if (!ecs.get(handle, Component.spellcasting))
54 {
55 ecs.add(handle, Component.spellcasting, {
56 armedSpellId: null,
57 repeatSpellId: null,
58 repeatTargetEntityId: null,
59 nextCastAt: 0
60 });
61 }
62 }
63
64 export function handleSpellCommand (world, sessionId, command, now = Date.now())
65 {
66 switch (command.type)
67 {
68 case "set-spell-favorite":
69 return setSpellFavorite(world, sessionId, command, now);
70 case "set-spell-autocast":
71 return setSpellAutoCast(world, sessionId, command, now);
72 case "arm-spell":
73 return armSpell(world, sessionId, command, now);
74 case "cancel-arm-spell":
75 return cancelArmSpell(world, sessionId, command, now);
76 case "cast-spell-tile":
77 return castSpellAtTile(world, sessionId, command, now);
78 case "cast-spell-entity":
79 return castSpellAtEntity(world, sessionId, command, now);
80 case "read-spellbook":
81 return readSpellbook(world, sessionId, command, now);
82 default:
83 return null;
84 }
85 }
86
87 function requirePlayer (world, sessionId, characterId)
88 {
89 for (const entity of world.ecs.query(Component.networkIdentity, Component.character))
90 {
91 if (entity.networkIdentity.sessionId !== sessionId)
92 { continue; }
93 if (entity.character.characterId !== characterId)
94 { continue; }
95 return { handle: entity.handle, entityId: entity.entityId, character: entity.character };
96 }
97 const error = new Error("Character not found.");
98 error.userFacing = true;
99 throw error;
100 }
101
102 function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])
103 {
104 return {
105 type: "spells-updated",
106 entityId,
107 characterId,
108 spells: publicSpellsView(spells, skills),
109 stored: storedPlayerSpells(spells),
110 autoCast: !!spells.autoCast,
111 levelUps
112 };
113 }
114
115 function setSpellFavorite (world, sessionId, command, now)
116 {
117 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
118 ensureSpellComponents(world.ecs, handle);
119 const skills = world.ecs.get(handle, Component.skills);
120 const spells = world.ecs.get(handle, Component.spells);
121 const result = toggleFavorite(spells, command.spellId, skills);
122 if (result.error)
123 {
124 const error = new Error(result.error);
125 error.userFacing = true;
126 throw error;
127 }
128 Object.assign(spells, result.spells);
129 const events = [];
130 if (result.changed)
131 {
132 events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));
133 }
134 return { events };
135 }
136
137 function setSpellAutoCast (world, sessionId, command, now)
138 {
139 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
140 ensureSpellComponents(world.ecs, handle);
141 const skills = world.ecs.get(handle, Component.skills);
142 const spells = world.ecs.get(handle, Component.spells);
143 spells.autoCast = !!command.enabled;
144 const casting = world.ecs.get(handle, Component.spellcasting);
145 if (!spells.autoCast)
146 {
147 casting.repeatSpellId = null;
148 casting.repeatTargetEntityId = null;
149 }
150 return {
151 events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]
152 };
153 }
154
155 function armSpell (world, sessionId, command, now)
156 {
157 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
158 ensureSpellComponents(world.ecs, handle);
159 const skills = world.ecs.get(handle, Component.skills);
160 const spells = world.ecs.get(handle, Component.spells);
161 const check = canCastSpell(skills, spells, command.spellId);
162 if (!check.ok)
163 {
164 const error = new Error(check.reason);
165 error.userFacing = true;
166 throw error;
167 }
168 const casting = world.ecs.get(handle, Component.spellcasting);
169 casting.armedSpellId = command.spellId;
170 casting.repeatSpellId = null;
171 casting.repeatTargetEntityId = null;
172 casting.pendingCast = null;
173 return {
174 events: [{
175 type: "spell-armed",
176 entityId,
177 characterId: character.characterId,
178 spellId: command.spellId
179 }]
180 };
181 }
182
183 function cancelArmSpell (world, sessionId, command)
184 {
185 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
186 const casting = world.ecs.get(handle, Component.spellcasting);
187 if (!casting)
188 { return { events: [] }; }
189 casting.armedSpellId = null;
190 casting.repeatSpellId = null;
191 casting.repeatTargetEntityId = null;
192 casting.pendingCast = null;
193 return {
194 events: [{
195 type: "spell-disarmed",
196 entityId,
197 characterId: character.characterId
198 }]
199 };
200 }
201
202 function casterMagicLevels (ecs, handle)
203 {
204 const skills = ecs.get(handle, Component.skills);
205 return {
206 magic: skillLevel(skills, SkillId.magic),
207 mind: skillLevel(skills, SkillId.mind)
208 };
209 }
210
211 function validateCastRange (world, handle, tileX, tileY, now)
212 {
213 const pos = world.ecs.get(handle, Component.position);
214 if (!pos)
215 { return { ok: false, reason: "You are not in the world." }; }
216 const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);
217 if (dist > COMBAT_RANGE_TILES)
218 { return { ok: false, reason: "That is out of range." }; }
219 if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))
220 { return { ok: false, reason: "You cannot see that spot." }; }
221 return { ok: true };
222 }
223
224 function resolvePendingCastTarget (world, pending)
225 {
226 if (pending.targetEntityId == null)
227 {
228 return {
229 tileX: pending.tileX | 0,
230 tileY: pending.tileY | 0,
231 targetEntityId: null
232 };
233 }
234 const target = resolveCombatTarget(world, pending.targetEntityId);
235 if (!target)
236 { return null; }
237 return {
238 tileX: target.pos.tileX,
239 tileY: target.pos.tileY,
240 targetEntityId: pending.targetEntityId
241 };
242 }
243
244 function queueSpellApproach (world, handle, entityId, target, minStandDist)
245 {
246 const position = world.ecs.get(handle, Component.position);
247 if (!position)
248 { return; }
249 queueStandInRangeApproach(
250 world,
251 entityId,
252 handle,
253 position,
254 target.tileX,
255 target.tileY,
256 COMBAT_RANGE_TILES,
257 minStandDist
258 );
259 }
260
261 function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)
262 {
263 const { handle, entityId } = requirePlayer(world, sessionId, characterId);
264 ensureSpellComponents(world.ecs, handle);
265 const casting = world.ecs.get(handle, Component.spellcasting);
266 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
267 if (!rangeCheck.ok)
268 {
269 casting.pendingCast = {
270 spellId,
271 tileX: target.tileX,
272 tileY: target.tileY,
273 targetEntityId: target.targetEntityId ?? null
274 };
275 queueSpellApproach(world, handle, entityId, target, minStandDist);
276 return { events: [] };
277 }
278 casting.pendingCast = null;
279 return executeCast(world, sessionId, characterId, spellId, target, now);
280 }
281
282 function castSpellAtTile (world, sessionId, command, now)
283 {
284 const spellId = command.spellId;
285 const def = spellDefinition(spellId);
286 if (!def || def.target !== "tile")
287 {
288 const error = new Error("That spell needs a different target.");
289 error.userFacing = true;
290 throw error;
291 }
292 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
293 tileX: command.tileX | 0,
294 tileY: command.tileY | 0,
295 targetEntityId: null
296 }, now, 0);
297 }
298
299 function castSpellAtEntity (world, sessionId, command, now)
300 {
301 const spellId = command.spellId;
302 const def = spellDefinition(spellId);
303 if (!def || def.target !== "entity")
304 {
305 const error = new Error("That spell needs a tile target.");
306 error.userFacing = true;
307 throw error;
308 }
309 const target = resolveCombatTarget(world, command.targetEntityId);
310 if (!target)
311 {
312 const error = new Error("Target is not here.");
313 error.userFacing = true;
314 throw error;
315 }
316 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
317 tileX: target.pos.tileX,
318 tileY: target.pos.tileY,
319 targetEntityId: command.targetEntityId
320 }, now, 1);
321 }
322
323 function executeCast (world, sessionId, characterId, spellId, target, now)
324 {
325 const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);
326 ensureSpellComponents(world.ecs, handle);
327 const skills = world.ecs.get(handle, Component.skills);
328 const spells = world.ecs.get(handle, Component.spells);
329 const casting = world.ecs.get(handle, Component.spellcasting);
330 const def = spellDefinition(spellId);
331 const check = canCastSpell(skills, spells, spellId);
332 if (!check.ok)
333 {
334 const error = new Error(check.reason);
335 error.userFacing = true;
336 throw error;
337 }
338 if (now < (casting.nextCastAt || 0))
339 {
340 const error = new Error("You are not ready to cast yet.");
341 error.userFacing = true;
342 throw error;
343 }
344 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
345 if (!rangeCheck.ok)
346 {
347 const error = new Error(rangeCheck.reason);
348 error.userFacing = true;
349 throw error;
350 }
351
352 const levels = casterMagicLevels(world.ecs, handle);
353 const difficulty = spellDifficulty(def);
354 const cast = resolveSpellCast({
355 magicSkillLevel: levels.magic,
356 spellDifficulty: difficulty
357 });
358
359 const events = [];
360 const from = world.ecs.get(handle, Component.position);
361 casting.armedSpellId = null;
362 casting.repeatSpellId = null;
363 casting.repeatTargetEntityId = null;
364 casting.nextCastAt = now + SPELL_COOLDOWN_MS;
365 events.push({
366 type: "spell-disarmed",
367 entityId,
368 characterId: character.characterId
369 });
370
371 if (!cast.success)
372 {
373 events.push({
374 type: "spell-fizzle",
375 casterId: entityId,
376 spellId,
377 fromTileX: from.tileX,
378 fromTileY: from.tileY,
379 tileX: target.tileX,
380 tileY: target.tileY
381 });
382 return { events };
383 }
384
385 const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
386 if (xpAward)
387 {
388 events.push({
389 type: "skills-updated",
390 entityId,
391 characterId: character.characterId,
392 skills: xpAward.view,
393 stored: xpAward.stored,
394 levelUps: xpAward.levelUps ?? []
395 });
396 }
397
398 const flashRadius = castFlashRadiusTiles(def.tier);
399 events.push({
400 type: "spell-cast-flash",
401 casterId: entityId,
402 tileX: from.tileX,
403 tileY: from.tileY,
404 radiusTiles: flashRadius,
405 durationMs: CAST_FLASH_MS,
406 tier: def.tier
407 });
408
409 world.pendingSpellImpacts.push({
410 executeAt: now + SPELL_PROJECTILE_MS,
411 casterEntityId: entityId,
412 casterCharacterId: character.characterId,
413 spellId,
414 targetTileX: target.tileX,
415 targetTileY: target.tileY,
416 targetEntityId: target.targetEntityId,
417 levels
418 });
419
420 events.push({
421 type: "spell-projectile",
422 casterId: entityId,
423 spellId,
424 fromTileX: from.tileX,
425 fromTileY: from.tileY,
426 tileX: target.tileX,
427 tileY: target.tileY,
428 durationMs: SPELL_PROJECTILE_MS,
429 sprite: def.projectileSprite
430 });
431
432 if (def.autoRepeat && spells.autoCast && target.targetEntityId != null)
433 {
434 casting.repeatSpellId = spellId;
435 casting.repeatTargetEntityId = target.targetEntityId;
436 }
437 else
438 {
439 casting.repeatSpellId = null;
440 casting.repeatTargetEntityId = null;
441 }
442
443 return { events };
444 }
445
446 function targetAffinitiesForEntity (world, entityId)
447 {
448 if (entityId == null)
449 { return {}; }
450 const handle = world.ecs.handleOf(entityId);
451 if (handle == null)
452 { return {}; }
453 const creature = world.ecs.get(handle, Component.creature);
454 if (!creature)
455 { return {}; }
456 return mobElementAffinities(mobDefinition(creature.mobTypeId));
457 }
458
459 export function processSpellImpacts (world, now = Date.now())
460 {
461 const queue = world.pendingSpellImpacts ?? [];
462 if (!queue.length)
463 { return []; }
464 const events = [];
465 const keep = [];
466 for (const impact of queue)
467 {
468 if (impact.executeAt > now)
469 {
470 keep.push(impact);
471 continue;
472 }
473 events.push(...applySpellImpact(world, impact, now));
474 }
475 world.pendingSpellImpacts = keep;
476 return events;
477 }
478
479 function applySpellImpact (world, impact, now)
480 {
481 const def = spellDefinition(impact.spellId);
482 if (!def)
483 { return []; }
484 const events = [];
485 events.push({
486 type: "spell-cast-flash",
487 casterId: impact.casterEntityId,
488 tileX: impact.targetTileX,
489 tileY: impact.targetTileY,
490 radiusTiles: castFlashRadiusTiles(def.tier),
491 durationMs: CAST_FLASH_MS,
492 tier: def.tier
493 });
494
495 if (impact.spellId === SpellId.light)
496 {
497 world.spellLights = world.spellLights ?? new SpellLightRegistry();
498 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
499 const durationMs = mindRoll * LIGHT_DURATION_MS_PER_MIND;
500 const { light, extended } = world.spellLights.placeOrExtend({
501 tileX: impact.targetTileX,
502 tileY: impact.targetTileY,
503 ownerEntityId: impact.casterEntityId,
504 durationMs,
505 now
506 });
507 events.push({
508 type: extended ? "spell-light-update" : "spell-light-appear",
509 ...publicSpellLight(light, now)
510 });
511 return events;
512 }
513
514 if (impact.spellId === SpellId.spark && impact.targetEntityId != null)
515 {
516 const targetHandle = world.ecs.handleOf(impact.targetEntityId);
517 if (targetHandle == null)
518 { return events; }
519 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
520 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
521 let multiplier = ElementMultiplier.neutral;
522 const affinity = affinities[def.element ?? "fire"];
523 if (affinity === "weak")
524 { multiplier = ElementMultiplier.weak; }
525 else if (affinity === "resistant")
526 { multiplier = ElementMultiplier.resistant; }
527 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
528 const health = world.ecs.get(targetHandle, Component.health);
529 if (health)
530 {
531 health.current = Math.max(0, (health.current | 0) - damage);
532 }
533 events.push({
534 type: "combat-hit",
535 attackerId: impact.casterEntityId,
536 targetId: impact.targetEntityId,
537 damage,
538 tileX: impact.targetTileX,
539 tileY: impact.targetTileY,
540 health: health?.current ?? 0,
541 maxHealth: health?.max ?? 0
542 });
543 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
544 if (casterHandle != null)
545 {
546 const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
547 if (xp)
548 {
549 events.push({
550 type: "skills-updated",
551 entityId: impact.casterEntityId,
552 characterId: impact.casterCharacterId,
553 skills: xp.view,
554 stored: xp.stored,
555 levelUps: xp.levelUps ?? []
556 });
557 }
558 }
559 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
560 if (healthXp)
561 {
562 events.push({
563 type: "skills-updated",
564 entityId: impact.targetEntityId,
565 characterId: healthXp.characterId,
566 skills: healthXp.view,
567 stored: healthXp.stored,
568 levelUps: healthXp.levelUps ?? []
569 });
570 }
571 }
572 return events;
573 }
574
575 export function stepPendingSpellCast (world, now = Date.now())
576 {
577 const events = [];
578 for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
579 {
580 const casting = entity.spellcasting;
581 if (!casting?.pendingCast)
582 { continue; }
583 const pending = casting.pendingCast;
584 const target = resolvePendingCastTarget(world, pending);
585 if (!target)
586 {
587 casting.pendingCast = null;
588 continue;
589 }
590 const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
591 if (!rangeCheck.ok)
592 {
593 const minStandDist = target.targetEntityId != null ? 1 : 0;
594 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
595 continue;
596 }
597 casting.pendingCast = null;
598 const result = executeCast(
599 world,
600 entity.networkIdentity.sessionId,
601 entity.character.characterId,
602 pending.spellId,
603 target,
604 now
605 );
606 events.push(...(result.events ?? []));
607 }
608 return events;
609 }
610
611 export function stepSpellAutoCast (world, now = Date.now())
612 {
613 const events = [];
614 for (const entity of world.ecs.query(Component.spellcasting, Component.spells, Component.character))
615 {
616 const casting = entity.spellcasting;
617 const spells = entity.spells;
618 if (!spells.autoCast || !casting.repeatSpellId || casting.repeatTargetEntityId == null)
619 { continue; }
620 if (now < (casting.nextCastAt || 0))
621 { continue; }
622 const def = spellDefinition(casting.repeatSpellId);
623 if (!def?.autoRepeat)
624 { continue; }
625 const target = resolveCombatTarget(world, casting.repeatTargetEntityId);
626 if (!target || (target.health && target.health.current <= 0))
627 {
628 casting.repeatSpellId = null;
629 casting.repeatTargetEntityId = null;
630 continue;
631 }
632 const range = validateCastRange(world, entity.handle, target.pos.tileX, target.pos.tileY, now);
633 if (!range.ok)
634 { continue; }
635 const sessionId = entity.networkIdentity?.sessionId;
636 if (!sessionId)
637 { continue; }
638 const result = executeCast(
639 world,
640 sessionId,
641 entity.character.characterId,
642 casting.repeatSpellId,
643 {
644 tileX: target.pos.tileX,
645 tileY: target.pos.tileY,
646 targetEntityId: casting.repeatTargetEntityId
647 },
648 now
649 );
650 events.push(...(result.events ?? []));
651 }
652 return events;
653 }
654
655 export function tickSpellLights (world, now = Date.now())
656 {
657 if (!world.spellLights)
658 { return []; }
659 return world.spellLights.tick(world, now);
660 }
661
662 function readSpellbook (world, sessionId, command, now)
663 {
664 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
665 ensureSpellComponents(world.ecs, handle);
666 const inventory = world.ecs.get(handle, Component.inventory);
667 const slotIndex = command.slotIndex | 0;
668 const slot = inventory?.slots?.[slotIndex];
669 if (!slot?.instance || slot.instance.kind !== "spellbook")
670 {
671 const error = new Error("That is not a spellbook.");
672 error.userFacing = true;
673 throw error;
674 }
675 const spellId = slot.instance.spellId;
676 const spells = world.ecs.get(handle, Component.spells);
677 const skills = world.ecs.get(handle, Component.skills);
678 const learned = learnSpell(spells, spellId);
679 if (!learned.changed)
680 {
681 const error = new Error("You already know that spell.");
682 error.userFacing = true;
683 throw error;
684 }
685 Object.assign(spells, learned.spells);
686 inventory.slots[slotIndex] = null;
687 const events = [
688 spellsUpdatedEvent(entityId, character.characterId, spells, skills)
689 ];
690 return {
691 events,
692 private: bagView(world.ecs, handle)
693 };
694 }
695
696 export function createSpellbookStack (spellId)
697 {
698 const instance = spellbookInstance(spellId);
699 if (!instance)
700 { return null; }
701 const itemId = spellId === SpellId.spark
702 ? SpellbookItemId.sparkSpellbook
703 : null;
704 if (itemId == null)
705 { return null; }
706 return { itemId, quantity: 1, instance };
707 }
@@ -0,0 +1,707 @@
1import { Component } from "../ecs/components.js";
2import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
3import { SpellId, spellDefinition, spellDifficulty } from "../../../shared/definitions/spells.js";
4import {
5 canCastSpell,
6 defaultPlayerSpells,
7 normalizePlayerSpells,
8 publicSpellsView,
9 storedPlayerSpells,
10 toggleFavorite,
11 learnSpell
12} from "../../../shared/spells/state.js";
13import {
14 CAST_FLASH_MS,
15 COMBAT_RANGE_TILES,
16 LIGHT_DURATION_MS_PER_MIND,
17 SPELL_COOLDOWN_MS,
18 SPELL_PROJECTILE_MS,
19 castFlashRadiusTiles
20} from "../../../shared/spells/constants.js";
21import {
22 mobElementAffinities,
23 ElementMultiplier,
24 resolveMagicAttack,
25 resolveSpellCast,
26 resolveSpellPotency
27} from "../../../shared/combat/magic.js";
28import { mobDefinition } from "../../../shared/definitions/mobs.js";
29import { awardCombatHitXp, awardDamageHealthXp, awardSpellCastXp, syncPlayerHealth } from "../skills/service.js";
30import {
31 chebyshev,
32 hasCombatLineOfSight,
33 queueStandInRangeApproach,
34 resolveCombatTarget
35} from "../combat/service.js";
36import { publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
37import { spellCastXpFromDifficulty } from "../../../shared/skills/progression.js";
38import { publicSpellLight, SpellLightRegistry } from "./lights.js";
39import { SpellbookItemId, spellbookInstance } from "../../../shared/definitions/spellItems.js";
40import { bagView } from "../items/bags.js";
41
42const MAGIC_ATTACK_PROFILE = Object.freeze({
43 hitSkillId: SkillId.magic,
44 damageSkillId: SkillId.mind
45});
46
47export function ensureSpellComponents (ecs, handle, storedSpells = null)
48{
49 if (!ecs.get(handle, Component.spells))
50 {
51 ecs.add(handle, Component.spells, normalizePlayerSpells(storedSpells ?? defaultPlayerSpells()));
52 }
53 if (!ecs.get(handle, Component.spellcasting))
54 {
55 ecs.add(handle, Component.spellcasting, {
56 armedSpellId: null,
57 repeatSpellId: null,
58 repeatTargetEntityId: null,
59 nextCastAt: 0
60 });
61 }
62}
63
64export function handleSpellCommand (world, sessionId, command, now = Date.now())
65{
66 switch (command.type)
67 {
68 case "set-spell-favorite":
69 return setSpellFavorite(world, sessionId, command, now);
70 case "set-spell-autocast":
71 return setSpellAutoCast(world, sessionId, command, now);
72 case "arm-spell":
73 return armSpell(world, sessionId, command, now);
74 case "cancel-arm-spell":
75 return cancelArmSpell(world, sessionId, command, now);
76 case "cast-spell-tile":
77 return castSpellAtTile(world, sessionId, command, now);
78 case "cast-spell-entity":
79 return castSpellAtEntity(world, sessionId, command, now);
80 case "read-spellbook":
81 return readSpellbook(world, sessionId, command, now);
82 default:
83 return null;
84 }
85}
86
87function requirePlayer (world, sessionId, characterId)
88{
89 for (const entity of world.ecs.query(Component.networkIdentity, Component.character))
90 {
91 if (entity.networkIdentity.sessionId !== sessionId)
92 { continue; }
93 if (entity.character.characterId !== characterId)
94 { continue; }
95 return { handle: entity.handle, entityId: entity.entityId, character: entity.character };
96 }
97 const error = new Error("Character not found.");
98 error.userFacing = true;
99 throw error;
100}
101
102function spellsUpdatedEvent (entityId, characterId, spells, skills, levelUps = [])
103{
104 return {
105 type: "spells-updated",
106 entityId,
107 characterId,
108 spells: publicSpellsView(spells, skills),
109 stored: storedPlayerSpells(spells),
110 autoCast: !!spells.autoCast,
111 levelUps
112 };
113}
114
115function setSpellFavorite (world, sessionId, command, now)
116{
117 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
118 ensureSpellComponents(world.ecs, handle);
119 const skills = world.ecs.get(handle, Component.skills);
120 const spells = world.ecs.get(handle, Component.spells);
121 const result = toggleFavorite(spells, command.spellId, skills);
122 if (result.error)
123 {
124 const error = new Error(result.error);
125 error.userFacing = true;
126 throw error;
127 }
128 Object.assign(spells, result.spells);
129 const events = [];
130 if (result.changed)
131 {
132 events.push(spellsUpdatedEvent(entityId, character.characterId, spells, skills));
133 }
134 return { events };
135}
136
137function setSpellAutoCast (world, sessionId, command, now)
138{
139 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
140 ensureSpellComponents(world.ecs, handle);
141 const skills = world.ecs.get(handle, Component.skills);
142 const spells = world.ecs.get(handle, Component.spells);
143 spells.autoCast = !!command.enabled;
144 const casting = world.ecs.get(handle, Component.spellcasting);
145 if (!spells.autoCast)
146 {
147 casting.repeatSpellId = null;
148 casting.repeatTargetEntityId = null;
149 }
150 return {
151 events: [spellsUpdatedEvent(entityId, character.characterId, spells, skills)]
152 };
153}
154
155function armSpell (world, sessionId, command, now)
156{
157 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
158 ensureSpellComponents(world.ecs, handle);
159 const skills = world.ecs.get(handle, Component.skills);
160 const spells = world.ecs.get(handle, Component.spells);
161 const check = canCastSpell(skills, spells, command.spellId);
162 if (!check.ok)
163 {
164 const error = new Error(check.reason);
165 error.userFacing = true;
166 throw error;
167 }
168 const casting = world.ecs.get(handle, Component.spellcasting);
169 casting.armedSpellId = command.spellId;
170 casting.repeatSpellId = null;
171 casting.repeatTargetEntityId = null;
172 casting.pendingCast = null;
173 return {
174 events: [{
175 type: "spell-armed",
176 entityId,
177 characterId: character.characterId,
178 spellId: command.spellId
179 }]
180 };
181}
182
183function cancelArmSpell (world, sessionId, command)
184{
185 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
186 const casting = world.ecs.get(handle, Component.spellcasting);
187 if (!casting)
188 { return { events: [] }; }
189 casting.armedSpellId = null;
190 casting.repeatSpellId = null;
191 casting.repeatTargetEntityId = null;
192 casting.pendingCast = null;
193 return {
194 events: [{
195 type: "spell-disarmed",
196 entityId,
197 characterId: character.characterId
198 }]
199 };
200}
201
202function casterMagicLevels (ecs, handle)
203{
204 const skills = ecs.get(handle, Component.skills);
205 return {
206 magic: skillLevel(skills, SkillId.magic),
207 mind: skillLevel(skills, SkillId.mind)
208 };
209}
210
211function validateCastRange (world, handle, tileX, tileY, now)
212{
213 const pos = world.ecs.get(handle, Component.position);
214 if (!pos)
215 { return { ok: false, reason: "You are not in the world." }; }
216 const dist = chebyshev(pos.tileX, pos.tileY, tileX, tileY);
217 if (dist > COMBAT_RANGE_TILES)
218 { return { ok: false, reason: "That is out of range." }; }
219 if (!hasCombatLineOfSight(world, pos.tileX, pos.tileY, tileX, tileY))
220 { return { ok: false, reason: "You cannot see that spot." }; }
221 return { ok: true };
222}
223
224function resolvePendingCastTarget (world, pending)
225{
226 if (pending.targetEntityId == null)
227 {
228 return {
229 tileX: pending.tileX | 0,
230 tileY: pending.tileY | 0,
231 targetEntityId: null
232 };
233 }
234 const target = resolveCombatTarget(world, pending.targetEntityId);
235 if (!target)
236 { return null; }
237 return {
238 tileX: target.pos.tileX,
239 tileY: target.pos.tileY,
240 targetEntityId: pending.targetEntityId
241 };
242}
243
244function queueSpellApproach (world, handle, entityId, target, minStandDist)
245{
246 const position = world.ecs.get(handle, Component.position);
247 if (!position)
248 { return; }
249 queueStandInRangeApproach(
250 world,
251 entityId,
252 handle,
253 position,
254 target.tileX,
255 target.tileY,
256 COMBAT_RANGE_TILES,
257 minStandDist
258 );
259}
260
261function beginCastOrApproach (world, sessionId, characterId, spellId, target, now, minStandDist = 0)
262{
263 const { handle, entityId } = requirePlayer(world, sessionId, characterId);
264 ensureSpellComponents(world.ecs, handle);
265 const casting = world.ecs.get(handle, Component.spellcasting);
266 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
267 if (!rangeCheck.ok)
268 {
269 casting.pendingCast = {
270 spellId,
271 tileX: target.tileX,
272 tileY: target.tileY,
273 targetEntityId: target.targetEntityId ?? null
274 };
275 queueSpellApproach(world, handle, entityId, target, minStandDist);
276 return { events: [] };
277 }
278 casting.pendingCast = null;
279 return executeCast(world, sessionId, characterId, spellId, target, now);
280}
281
282function castSpellAtTile (world, sessionId, command, now)
283{
284 const spellId = command.spellId;
285 const def = spellDefinition(spellId);
286 if (!def || def.target !== "tile")
287 {
288 const error = new Error("That spell needs a different target.");
289 error.userFacing = true;
290 throw error;
291 }
292 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
293 tileX: command.tileX | 0,
294 tileY: command.tileY | 0,
295 targetEntityId: null
296 }, now, 0);
297}
298
299function castSpellAtEntity (world, sessionId, command, now)
300{
301 const spellId = command.spellId;
302 const def = spellDefinition(spellId);
303 if (!def || def.target !== "entity")
304 {
305 const error = new Error("That spell needs a tile target.");
306 error.userFacing = true;
307 throw error;
308 }
309 const target = resolveCombatTarget(world, command.targetEntityId);
310 if (!target)
311 {
312 const error = new Error("Target is not here.");
313 error.userFacing = true;
314 throw error;
315 }
316 return beginCastOrApproach(world, sessionId, command.characterId, spellId, {
317 tileX: target.pos.tileX,
318 tileY: target.pos.tileY,
319 targetEntityId: command.targetEntityId
320 }, now, 1);
321}
322
323function executeCast (world, sessionId, characterId, spellId, target, now)
324{
325 const { handle, entityId, character } = requirePlayer(world, sessionId, characterId);
326 ensureSpellComponents(world.ecs, handle);
327 const skills = world.ecs.get(handle, Component.skills);
328 const spells = world.ecs.get(handle, Component.spells);
329 const casting = world.ecs.get(handle, Component.spellcasting);
330 const def = spellDefinition(spellId);
331 const check = canCastSpell(skills, spells, spellId);
332 if (!check.ok)
333 {
334 const error = new Error(check.reason);
335 error.userFacing = true;
336 throw error;
337 }
338 if (now < (casting.nextCastAt || 0))
339 {
340 const error = new Error("You are not ready to cast yet.");
341 error.userFacing = true;
342 throw error;
343 }
344 const rangeCheck = validateCastRange(world, handle, target.tileX, target.tileY, now);
345 if (!rangeCheck.ok)
346 {
347 const error = new Error(rangeCheck.reason);
348 error.userFacing = true;
349 throw error;
350 }
351
352 const levels = casterMagicLevels(world.ecs, handle);
353 const difficulty = spellDifficulty(def);
354 const cast = resolveSpellCast({
355 magicSkillLevel: levels.magic,
356 spellDifficulty: difficulty
357 });
358
359 const events = [];
360 const from = world.ecs.get(handle, Component.position);
361 casting.armedSpellId = null;
362 casting.repeatSpellId = null;
363 casting.repeatTargetEntityId = null;
364 casting.nextCastAt = now + SPELL_COOLDOWN_MS;
365 events.push({
366 type: "spell-disarmed",
367 entityId,
368 characterId: character.characterId
369 });
370
371 if (!cast.success)
372 {
373 events.push({
374 type: "spell-fizzle",
375 casterId: entityId,
376 spellId,
377 fromTileX: from.tileX,
378 fromTileY: from.tileY,
379 tileX: target.tileX,
380 tileY: target.tileY
381 });
382 return { events };
383 }
384
385 const xpAward = awardSpellCastXp(world.ecs, handle, difficulty);
386 if (xpAward)
387 {
388 events.push({
389 type: "skills-updated",
390 entityId,
391 characterId: character.characterId,
392 skills: xpAward.view,
393 stored: xpAward.stored,
394 levelUps: xpAward.levelUps ?? []
395 });
396 }
397
398 const flashRadius = castFlashRadiusTiles(def.tier);
399 events.push({
400 type: "spell-cast-flash",
401 casterId: entityId,
402 tileX: from.tileX,
403 tileY: from.tileY,
404 radiusTiles: flashRadius,
405 durationMs: CAST_FLASH_MS,
406 tier: def.tier
407 });
408
409 world.pendingSpellImpacts.push({
410 executeAt: now + SPELL_PROJECTILE_MS,
411 casterEntityId: entityId,
412 casterCharacterId: character.characterId,
413 spellId,
414 targetTileX: target.tileX,
415 targetTileY: target.tileY,
416 targetEntityId: target.targetEntityId,
417 levels
418 });
419
420 events.push({
421 type: "spell-projectile",
422 casterId: entityId,
423 spellId,
424 fromTileX: from.tileX,
425 fromTileY: from.tileY,
426 tileX: target.tileX,
427 tileY: target.tileY,
428 durationMs: SPELL_PROJECTILE_MS,
429 sprite: def.projectileSprite
430 });
431
432 if (def.autoRepeat && spells.autoCast && target.targetEntityId != null)
433 {
434 casting.repeatSpellId = spellId;
435 casting.repeatTargetEntityId = target.targetEntityId;
436 }
437 else
438 {
439 casting.repeatSpellId = null;
440 casting.repeatTargetEntityId = null;
441 }
442
443 return { events };
444}
445
446function targetAffinitiesForEntity (world, entityId)
447{
448 if (entityId == null)
449 { return {}; }
450 const handle = world.ecs.handleOf(entityId);
451 if (handle == null)
452 { return {}; }
453 const creature = world.ecs.get(handle, Component.creature);
454 if (!creature)
455 { return {}; }
456 return mobElementAffinities(mobDefinition(creature.mobTypeId));
457}
458
459export function processSpellImpacts (world, now = Date.now())
460{
461 const queue = world.pendingSpellImpacts ?? [];
462 if (!queue.length)
463 { return []; }
464 const events = [];
465 const keep = [];
466 for (const impact of queue)
467 {
468 if (impact.executeAt > now)
469 {
470 keep.push(impact);
471 continue;
472 }
473 events.push(...applySpellImpact(world, impact, now));
474 }
475 world.pendingSpellImpacts = keep;
476 return events;
477}
478
479function applySpellImpact (world, impact, now)
480{
481 const def = spellDefinition(impact.spellId);
482 if (!def)
483 { return []; }
484 const events = [];
485 events.push({
486 type: "spell-cast-flash",
487 casterId: impact.casterEntityId,
488 tileX: impact.targetTileX,
489 tileY: impact.targetTileY,
490 radiusTiles: castFlashRadiusTiles(def.tier),
491 durationMs: CAST_FLASH_MS,
492 tier: def.tier
493 });
494
495 if (impact.spellId === SpellId.light)
496 {
497 world.spellLights = world.spellLights ?? new SpellLightRegistry();
498 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
499 const durationMs = mindRoll * LIGHT_DURATION_MS_PER_MIND;
500 const { light, extended } = world.spellLights.placeOrExtend({
501 tileX: impact.targetTileX,
502 tileY: impact.targetTileY,
503 ownerEntityId: impact.casterEntityId,
504 durationMs,
505 now
506 });
507 events.push({
508 type: extended ? "spell-light-update" : "spell-light-appear",
509 ...publicSpellLight(light, now)
510 });
511 return events;
512 }
513
514 if (impact.spellId === SpellId.spark && impact.targetEntityId != null)
515 {
516 const targetHandle = world.ecs.handleOf(impact.targetEntityId);
517 if (targetHandle == null)
518 { return events; }
519 const affinities = targetAffinitiesForEntity(world, impact.targetEntityId);
520 const mindRoll = resolveSpellPotency({ mindSkillLevel: impact.levels.mind }).mindRoll;
521 let multiplier = ElementMultiplier.neutral;
522 const affinity = affinities[def.element ?? "fire"];
523 if (affinity === "weak")
524 { multiplier = ElementMultiplier.weak; }
525 else if (affinity === "resistant")
526 { multiplier = ElementMultiplier.resistant; }
527 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
528 const health = world.ecs.get(targetHandle, Component.health);
529 if (health)
530 {
531 health.current = Math.max(0, (health.current | 0) - damage);
532 }
533 events.push({
534 type: "combat-hit",
535 attackerId: impact.casterEntityId,
536 targetId: impact.targetEntityId,
537 damage,
538 tileX: impact.targetTileX,
539 tileY: impact.targetTileY,
540 health: health?.current ?? 0,
541 maxHealth: health?.max ?? 0
542 });
543 const casterHandle = world.ecs.handleOf(impact.casterEntityId);
544 if (casterHandle != null)
545 {
546 const xp = awardCombatHitXp(world.ecs, casterHandle, MAGIC_ATTACK_PROFILE, damage);
547 if (xp)
548 {
549 events.push({
550 type: "skills-updated",
551 entityId: impact.casterEntityId,
552 characterId: impact.casterCharacterId,
553 skills: xp.view,
554 stored: xp.stored,
555 levelUps: xp.levelUps ?? []
556 });
557 }
558 }
559 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
560 if (healthXp)
561 {
562 events.push({
563 type: "skills-updated",
564 entityId: impact.targetEntityId,
565 characterId: healthXp.characterId,
566 skills: healthXp.view,
567 stored: healthXp.stored,
568 levelUps: healthXp.levelUps ?? []
569 });
570 }
571 }
572 return events;
573}
574
575export function stepPendingSpellCast (world, now = Date.now())
576{
577 const events = [];
578 for (const entity of world.ecs.query(Component.spellcasting, Component.character, Component.networkIdentity))
579 {
580 const casting = entity.spellcasting;
581 if (!casting?.pendingCast)
582 { continue; }
583 const pending = casting.pendingCast;
584 const target = resolvePendingCastTarget(world, pending);
585 if (!target)
586 {
587 casting.pendingCast = null;
588 continue;
589 }
590 const rangeCheck = validateCastRange(world, entity.handle, target.tileX, target.tileY, now);
591 if (!rangeCheck.ok)
592 {
593 const minStandDist = target.targetEntityId != null ? 1 : 0;
594 queueSpellApproach(world, entity.handle, entity.entityId, target, minStandDist);
595 continue;
596 }
597 casting.pendingCast = null;
598 const result = executeCast(
599 world,
600 entity.networkIdentity.sessionId,
601 entity.character.characterId,
602 pending.spellId,
603 target,
604 now
605 );
606 events.push(...(result.events ?? []));
607 }
608 return events;
609}
610
611export function stepSpellAutoCast (world, now = Date.now())
612{
613 const events = [];
614 for (const entity of world.ecs.query(Component.spellcasting, Component.spells, Component.character))
615 {
616 const casting = entity.spellcasting;
617 const spells = entity.spells;
618 if (!spells.autoCast || !casting.repeatSpellId || casting.repeatTargetEntityId == null)
619 { continue; }
620 if (now < (casting.nextCastAt || 0))
621 { continue; }
622 const def = spellDefinition(casting.repeatSpellId);
623 if (!def?.autoRepeat)
624 { continue; }
625 const target = resolveCombatTarget(world, casting.repeatTargetEntityId);
626 if (!target || (target.health && target.health.current <= 0))
627 {
628 casting.repeatSpellId = null;
629 casting.repeatTargetEntityId = null;
630 continue;
631 }
632 const range = validateCastRange(world, entity.handle, target.pos.tileX, target.pos.tileY, now);
633 if (!range.ok)
634 { continue; }
635 const sessionId = entity.networkIdentity?.sessionId;
636 if (!sessionId)
637 { continue; }
638 const result = executeCast(
639 world,
640 sessionId,
641 entity.character.characterId,
642 casting.repeatSpellId,
643 {
644 tileX: target.pos.tileX,
645 tileY: target.pos.tileY,
646 targetEntityId: casting.repeatTargetEntityId
647 },
648 now
649 );
650 events.push(...(result.events ?? []));
651 }
652 return events;
653}
654
655export function tickSpellLights (world, now = Date.now())
656{
657 if (!world.spellLights)
658 { return []; }
659 return world.spellLights.tick(world, now);
660}
661
662function readSpellbook (world, sessionId, command, now)
663{
664 const { handle, entityId, character } = requirePlayer(world, sessionId, command.characterId);
665 ensureSpellComponents(world.ecs, handle);
666 const inventory = world.ecs.get(handle, Component.inventory);
667 const slotIndex = command.slotIndex | 0;
668 const slot = inventory?.slots?.[slotIndex];
669 if (!slot?.instance || slot.instance.kind !== "spellbook")
670 {
671 const error = new Error("That is not a spellbook.");
672 error.userFacing = true;
673 throw error;
674 }
675 const spellId = slot.instance.spellId;
676 const spells = world.ecs.get(handle, Component.spells);
677 const skills = world.ecs.get(handle, Component.skills);
678 const learned = learnSpell(spells, spellId);
679 if (!learned.changed)
680 {
681 const error = new Error("You already know that spell.");
682 error.userFacing = true;
683 throw error;
684 }
685 Object.assign(spells, learned.spells);
686 inventory.slots[slotIndex] = null;
687 const events = [
688 spellsUpdatedEvent(entityId, character.characterId, spells, skills)
689 ];
690 return {
691 events,
692 private: bagView(world.ecs, handle)
693 };
694}
695
696export function createSpellbookStack (spellId)
697{
698 const instance = spellbookInstance(spellId);
699 if (!instance)
700 { return null; }
701 const itemId = spellId === SpellId.spark
702 ? SpellbookItemId.sparkSpellbook
703 : null;
704 if (itemId == null)
705 { return null; }
706 return { itemId, quantity: 1, instance };
707}
server/src/world/chunkData.js +12 −0
@@ -3,6 +3,7 @@ import {
3 3 GroundType,
4 4 BlockType,
5 5 isBlockPassable,
6 blockBlocksRangedAttacks,
6 7 blockLightOcclusionForBlock,
7 8 LightOcclusion,
8 9 isGroundPassable,
@@ -191,6 +192,17 @@ export function isChunkTileClearForLight (data, localX, localY)
191 192 return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;
192 193 }
193 194
195 /** True when ranged attacks and spell casts may trace a ray through this tile. */
196 export function isChunkTileClearForRangedAttacks (data, localX, localY)
197 {
198 const index = tileIndex(localX, localY);
199 const ground = normalizeGround(data.grounds[index]);
200 if (!isGroundPassable(ground.typeId))
201 { return false; }
202 const block = data.blocks[index];
203 return !blockBlocksRangedAttacks(block?.typeId ?? null);
204 }
205
194 206 export function collectLightSources (chunkX, chunkY, data)
195 207 {
196 208 const sources = [];
@@ -3,6 +3,7 @@ import {
3 GroundType,
3 GroundType,
4 BlockType,
4 BlockType,
5 isBlockPassable,
5 isBlockPassable,
6 blockBlocksRangedAttacks,
6 blockLightOcclusionForBlock,
7 blockLightOcclusionForBlock,
7 LightOcclusion,
8 LightOcclusion,
8 isGroundPassable,
9 isGroundPassable,
@@ -191,6 +192,17 @@ export function isChunkTileClearForLight (data, localX, localY)
191 return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;
192 return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;
192}
193}
193
194
195/** True when ranged attacks and spell casts may trace a ray through this tile. */
196export function isChunkTileClearForRangedAttacks (data, localX, localY)
197{
198 const index = tileIndex(localX, localY);
199 const ground = normalizeGround(data.grounds[index]);
200 if (!isGroundPassable(ground.typeId))
201 { return false; }
202 const block = data.blocks[index];
203 return !blockBlocksRangedAttacks(block?.typeId ?? null);
204}
205
194export function collectLightSources (chunkX, chunkY, data)
206export function collectLightSources (chunkX, chunkY, data)
195{
207{
196 const sources = [];
208 const sources = [];
server/tests/alchemy.test.js +56 −3
@@ -7,13 +7,17 @@ import {
7 7 evaluateAlchemyBottle,
8 8 hashAlchemySteps,
9 9 resolvedAlchemyPotions,
10 unstablePotionFromSteps
10 unstablePotionFromSteps,
11 potionItemInstance
11 12 } from "../../shared/alchemy/recipes.js";
12 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
13 import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";
14 import { itemDefinition } from "../../shared/definitions/items.js";
13 15 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
16 import { Component } from "../src/ecs/components.js";
14 17 import {
15 18 makeCharacter,
16 makeSimulation
19 makeSimulation,
20 stepTimes
17 21 } from "./helpers/simulationHarness.js";
18 22
19 23 function placeCauldron (worldDb, tileX, tileY)
@@ -156,3 +160,52 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
156 160 finally
157 161 { harness.close(); }
158 162 });
163
164 test("drinking a lesser health tonic applies health regen", () =>
165 {
166 const harness = makeSimulation({ workerCount: 1 });
167 try
168 {
169 const character = makeCharacter(harness.stateDb);
170 const inventory = emptySlots();
171 const instance = potionItemInstance({
172 potionKey: "lesserHealthTonic",
173 displayName: "Lesser health tonic",
174 unstable: false,
175 color: { r: 0.35, g: 0.78, b: 0.42 },
176 fillLevel: 4,
177 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
178 effectKey: "health-regen"
179 });
180 const inserted = insertStack(
181 inventory,
182 { itemId: ItemId.potion, quantity: 1, instance },
183 itemDefinition(ItemId.potion)
184 );
185 harness.stateDb.saveBag(character.character_id, {
186 inventory: inserted.slots,
187 equipment: emptyEquipment(),
188 vault: [],
189 vaultReserved: []
190 });
191 const entityId = harness.simulation.spawnCharacter(1, character);
192 const record = harness.simulation.directory.get(entityId);
193 const worker = harness.simulation.workers[record.workerId];
194 const handle = worker.world.ecs.handleOf(entityId);
195 const health = worker.world.ecs.get(handle, Component.health);
196 health.current = 5;
197
198 const slotIndex = inserted.slots.findIndex((slot) => slot?.itemId === ItemId.potion);
199 harness.simulation.enqueue(1, { type: "drink-item", characterId: character.character_id, slotIndex });
200 const drink = harness.simulation.step();
201 assert.equal(drink.events.some((event) => event.type === "command-error"), false, JSON.stringify(drink.events));
202 assert.ok(drink.events.some((event) => event.type === "status-effects"));
203 const status = worker.world.ecs.get(handle, Component.statusEffects);
204 assert.ok(status?.effects?.some((entry) => entry.type === "health-regen"));
205
206 stepTimes(harness.simulation, 25);
207 assert.ok(Number(worker.world.ecs.get(handle, Component.health)?.current) > 5);
208 }
209 finally
210 { harness.close(); }
211 });
@@ -7,13 +7,17 @@ import {
7 evaluateAlchemyBottle,
7 evaluateAlchemyBottle,
8 hashAlchemySteps,
8 hashAlchemySteps,
9 resolvedAlchemyPotions,
9 resolvedAlchemyPotions,
10 unstablePotionFromSteps
10 unstablePotionFromSteps,
11 potionItemInstance
11} from "../../shared/alchemy/recipes.js";
12} from "../../shared/alchemy/recipes.js";
12import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
13import { emptyEquipment, emptySlots, insertStack } from "../../shared/items/inventory.js";
14import { itemDefinition } from "../../shared/definitions/items.js";
13import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
15import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
16import { Component } from "../src/ecs/components.js";
14import {
17import {
15 makeCharacter,
18 makeCharacter,
16 makeSimulation
19 makeSimulation,
20 stepTimes
17} from "./helpers/simulationHarness.js";
21} from "./helpers/simulationHarness.js";
18
22
19function placeCauldron (worldDb, tileX, tileY)
23function placeCauldron (worldDb, tileX, tileY)
@@ -156,3 +160,52 @@ test("cauldron bottles lesser health tonic when steps and ratios match", () =>
156 finally
160 finally
157 { harness.close(); }
161 { harness.close(); }
158});
162});
163
164test("drinking a lesser health tonic applies health regen", () =>
165{
166 const harness = makeSimulation({ workerCount: 1 });
167 try
168 {
169 const character = makeCharacter(harness.stateDb);
170 const inventory = emptySlots();
171 const instance = potionItemInstance({
172 potionKey: "lesserHealthTonic",
173 displayName: "Lesser health tonic",
174 unstable: false,
175 color: { r: 0.35, g: 0.78, b: 0.42 },
176 fillLevel: 4,
177 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
178 effectKey: "health-regen"
179 });
180 const inserted = insertStack(
181 inventory,
182 { itemId: ItemId.potion, quantity: 1, instance },
183 itemDefinition(ItemId.potion)
184 );
185 harness.stateDb.saveBag(character.character_id, {
186 inventory: inserted.slots,
187 equipment: emptyEquipment(),
188 vault: [],
189 vaultReserved: []
190 });
191 const entityId = harness.simulation.spawnCharacter(1, character);
192 const record = harness.simulation.directory.get(entityId);
193 const worker = harness.simulation.workers[record.workerId];
194 const handle = worker.world.ecs.handleOf(entityId);
195 const health = worker.world.ecs.get(handle, Component.health);
196 health.current = 5;
197
198 const slotIndex = inserted.slots.findIndex((slot) => slot?.itemId === ItemId.potion);
199 harness.simulation.enqueue(1, { type: "drink-item", characterId: character.character_id, slotIndex });
200 const drink = harness.simulation.step();
201 assert.equal(drink.events.some((event) => event.type === "command-error"), false, JSON.stringify(drink.events));
202 assert.ok(drink.events.some((event) => event.type === "status-effects"));
203 const status = worker.world.ecs.get(handle, Component.statusEffects);
204 assert.ok(status?.effects?.some((entry) => entry.type === "health-regen"));
205
206 stepTimes(harness.simulation, 25);
207 assert.ok(Number(worker.world.ecs.get(handle, Component.health)?.current) > 5);
208 }
209 finally
210 { harness.close(); }
211});
server/tests/character-resume.test.js +27 −0
@@ -1,5 +1,6 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import { Component } from "../src/ecs/components.js";
3 4 import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4 5
5 6 test("logout saves tile and login resumes nearby that tile", () =>
@@ -47,3 +48,29 @@ test("login prefers a nearby free tile over a distant world spawn when blocked",
47 48 finally
48 49 { harness.close(); }
49 50 });
51
52 test("logout saves current health and login restores it", () =>
53 {
54 const harness = makeSimulation({ workerCount: 1 });
55 try
56 {
57 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
58 const entityId = harness.simulation.spawnCharacter(1, character);
59 const record = harness.simulation.directory.get(entityId);
60 const worker = harness.simulation.workers[record.workerId];
61 const handle = worker.world.ecs.handleOf(entityId);
62 const health = worker.world.ecs.get(handle, Component.health);
63 health.current = 4;
64
65 harness.simulation.despawnCharacter(character.character_id);
66 const saved = harness.stateDb.getCharacter(character.character_id);
67 assert.equal(saved.health_current, 4);
68
69 const again = harness.simulation.spawnCharacter(2, saved);
70 const resumed = harness.simulation.entityRecord(again);
71 assert.equal(resumed.health, 4);
72 assert.equal(resumed.maxHealth, 10);
73 }
74 finally
75 { harness.close(); }
76 });
@@ -1,5 +1,6 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { Component } from "../src/ecs/components.js";
3import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4
5
5test("logout saves tile and login resumes nearby that tile", () =>
6test("logout saves tile and login resumes nearby that tile", () =>
@@ -47,3 +48,29 @@ test("login prefers a nearby free tile over a distant world spawn when blocked",
47 finally
48 finally
48 { harness.close(); }
49 { harness.close(); }
49});
50});
51
52test("logout saves current health and login restores it", () =>
53{
54 const harness = makeSimulation({ workerCount: 1 });
55 try
56 {
57 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
58 const entityId = harness.simulation.spawnCharacter(1, character);
59 const record = harness.simulation.directory.get(entityId);
60 const worker = harness.simulation.workers[record.workerId];
61 const handle = worker.world.ecs.handleOf(entityId);
62 const health = worker.world.ecs.get(handle, Component.health);
63 health.current = 4;
64
65 harness.simulation.despawnCharacter(character.character_id);
66 const saved = harness.stateDb.getCharacter(character.character_id);
67 assert.equal(saved.health_current, 4);
68
69 const again = harness.simulation.spawnCharacter(2, saved);
70 const resumed = harness.simulation.entityRecord(again);
71 assert.equal(resumed.health, 4);
72 assert.equal(resumed.maxHealth, 10);
73 }
74 finally
75 { harness.close(); }
76});
server/tests/combat.test.js +43 −2
@@ -3,14 +3,14 @@ import assert from "node:assert/strict";
3 3 import { mobComponents } from "../src/simulation/spawners.js";
4 4 import { MobId } from "../../shared/definitions/mobs.js";
5 5 import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6 import { BlockType } from "../../shared/definitions/tiles.js";
6 import { BlockType, blockBlocksRangedAttacks } from "../../shared/definitions/tiles.js";
7 7 import { Component } from "../src/ecs/components.js";
8 8 import { tileKey } from "../src/world/coordinates.js";
9 9 import { WorkerMessage } from "../src/simulation/protocol.js";
10 10 import { tileToRegion } from "../src/world/coordinates.js";
11 11 import { SkillId } from "../../shared/definitions/skills.js";
12 12 import { totalXpForLevel } from "../../shared/skills/progression.js";
13 import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
13 import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight } from "../src/combat/service.js";
14 14 import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
15 15
16 16 function workerOf (simulation, entityId)
@@ -622,6 +622,47 @@ test("aggressive rats do not aggro through walls or beyond range", () =>
622 622 { harness.close(); }
623 623 });
624 624
625 test("crafting stations and tables do not block ranged or spell line of sight", () =>
626 {
627 assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
628 assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
629 assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
630 assert.equal(blockBlocksRangedAttacks(null), false);
631
632 const harness = makeSimulation({ workerCount: 1 });
633 try
634 {
635 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
636 const playerId = harness.simulation.spawnCharacter(1, character);
637 const worker = workerOf(harness.simulation, playerId);
638 const data = worker.world.chunkData(0, 0);
639 const blockIndex = (localY, localX) => localY * 16 + localX;
640
641 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
642 assert.equal(
643 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
644 true,
645 "furnace between caster and target should not block"
646 );
647
648 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
649 assert.equal(
650 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
651 true,
652 "table between caster and target should not block"
653 );
654
655 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
656 assert.equal(
657 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
658 false,
659 "stone wall should still block"
660 );
661 }
662 finally
663 { harness.close(); }
664 });
665
625 666 test("attacker keeps pursuing and can swing after the target moves", () =>
626 667 {
627 668 const harness = makeSimulation({ workerCount: 1 });
@@ -3,14 +3,14 @@ import assert from "node:assert/strict";
3import { mobComponents } from "../src/simulation/spawners.js";
3import { mobComponents } from "../src/simulation/spawners.js";
4import { MobId } from "../../shared/definitions/mobs.js";
4import { MobId } from "../../shared/definitions/mobs.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
6import { BlockType, blockBlocksRangedAttacks } from "../../shared/definitions/tiles.js";
7import { Component } from "../src/ecs/components.js";
7import { Component } from "../src/ecs/components.js";
8import { tileKey } from "../src/world/coordinates.js";
8import { tileKey } from "../src/world/coordinates.js";
9import { WorkerMessage } from "../src/simulation/protocol.js";
9import { WorkerMessage } from "../src/simulation/protocol.js";
10import { tileToRegion } from "../src/world/coordinates.js";
10import { tileToRegion } from "../src/world/coordinates.js";
11import { SkillId } from "../../shared/definitions/skills.js";
11import { SkillId } from "../../shared/definitions/skills.js";
12import { totalXpForLevel } from "../../shared/skills/progression.js";
12import { totalXpForLevel } from "../../shared/skills/progression.js";
13import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
13import { resolveMeleeSwing, attackProfileOf, hasCombatLineOfSight } from "../src/combat/service.js";
14import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
14import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
15
15
16function workerOf (simulation, entityId)
16function workerOf (simulation, entityId)
@@ -622,6 +622,47 @@ test("aggressive rats do not aggro through walls or beyond range", () =>
622 { harness.close(); }
622 { harness.close(); }
623});
623});
624
624
625test("crafting stations and tables do not block ranged or spell line of sight", () =>
626{
627 assert.equal(blockBlocksRangedAttacks(BlockType.stoneWall), true);
628 assert.equal(blockBlocksRangedAttacks(BlockType.furnace), false);
629 assert.equal(blockBlocksRangedAttacks(BlockType.table), false);
630 assert.equal(blockBlocksRangedAttacks(null), false);
631
632 const harness = makeSimulation({ workerCount: 1 });
633 try
634 {
635 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
636 const playerId = harness.simulation.spawnCharacter(1, character);
637 const worker = workerOf(harness.simulation, playerId);
638 const data = worker.world.chunkData(0, 0);
639 const blockIndex = (localY, localX) => localY * 16 + localX;
640
641 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.furnace, state: null, config: null };
642 assert.equal(
643 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
644 true,
645 "furnace between caster and target should not block"
646 );
647
648 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.table, state: null, config: null };
649 assert.equal(
650 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
651 true,
652 "table between caster and target should not block"
653 );
654
655 data.blocks[blockIndex(8, 10)] = { typeId: BlockType.stoneWall, state: null, config: null };
656 assert.equal(
657 hasCombatLineOfSight(worker.world, 8, 8, 12, 8),
658 false,
659 "stone wall should still block"
660 );
661 }
662 finally
663 { harness.close(); }
664});
665
625test("attacker keeps pursuing and can swing after the target moves", () =>
666test("attacker keeps pursuing and can swing after the target moves", () =>
626{
667{
627 const harness = makeSimulation({ workerCount: 1 });
668 const harness = makeSimulation({ workerCount: 1 });
server/tests/magic.test.js +7 −8
@@ -1,7 +1,7 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";
4 import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";
4 import { spellDefinition, spellDifficulty, SpellId } from "../../shared/definitions/spells.js";
5 5
6 6 test("spell cast fails when difficulty roll beats magic roll", () =>
7 7 {
@@ -30,7 +30,6 @@ test("fizzled magic attack deals no damage", () =>
30 30 magicSkillLevel: 3,
31 31 spellDifficulty: 10,
32 32 mindSkillLevel: 10,
33 mindBonus: 5,
34 33 element: "fire",
35 34 rng
36 35 });
@@ -41,26 +40,25 @@ test("fizzled magic attack deals no damage", () =>
41 40 test("successful magic attack rolls mind damage and elemental multiplier", () =>
42 41 {
43 42 let i = 0;
44 const rng = () => [0.9, 0, 0, 0][i++];
43 const rng = () => [0.9, 0, 0][i++];
45 44 const neutral = resolveMagicAttack({
46 45 magicSkillLevel: 10,
47 46 spellDifficulty: 1,
48 47 mindSkillLevel: 5,
49 mindBonus: 2,
50 48 element: "fire",
51 49 targetAffinities: {},
52 50 rng
53 51 });
54 52 assert.equal(neutral.outcome, "hit");
55 53 assert.equal(neutral.multiplier, 1);
54 assert.equal(neutral.damage, 1);
56 55
57 56 let j = 0;
58 const rngWeak = () => [0.9, 0, 0, 0][j++];
57 const rngWeak = () => [0.9, 0, 0][j++];
59 58 const weak = resolveMagicAttack({
60 59 magicSkillLevel: 10,
61 60 spellDifficulty: 1,
62 61 mindSkillLevel: 5,
63 mindBonus: 2,
64 62 element: "fire",
65 63 targetAffinities: { fire: "weak" },
66 64 rng: rngWeak
@@ -83,9 +81,10 @@ test("non-damage spell applies effect only after a successful cast roll", () =>
83 81 assert.equal(result.effectId, "slow");
84 82 });
85 83
86 test("spell definitions expose per-spell difficulty", () =>
84 test("spell definitions expose tier-based difficulty", () =>
87 85 {
88 86 const spark = spellDefinition(SpellId.spark);
89 assert.equal(spark.difficulty, 4);
87 assert.equal(spellDifficulty(spark), 4);
90 88 assert.equal(spark.element, "fire");
89 assert.ok(spellDefinition(SpellId.light));
91 90 });
@@ -1,7 +1,7 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";
3import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";
4import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";
4import { spellDefinition, spellDifficulty, SpellId } from "../../shared/definitions/spells.js";
5
5
6test("spell cast fails when difficulty roll beats magic roll", () =>
6test("spell cast fails when difficulty roll beats magic roll", () =>
7{
7{
@@ -30,7 +30,6 @@ test("fizzled magic attack deals no damage", () =>
30 magicSkillLevel: 3,
30 magicSkillLevel: 3,
31 spellDifficulty: 10,
31 spellDifficulty: 10,
32 mindSkillLevel: 10,
32 mindSkillLevel: 10,
33 mindBonus: 5,
34 element: "fire",
33 element: "fire",
35 rng
34 rng
36 });
35 });
@@ -41,26 +40,25 @@ test("fizzled magic attack deals no damage", () =>
41test("successful magic attack rolls mind damage and elemental multiplier", () =>
40test("successful magic attack rolls mind damage and elemental multiplier", () =>
42{
41{
43 let i = 0;
42 let i = 0;
44 const rng = () => [0.9, 0, 0, 0][i++];
43 const rng = () => [0.9, 0, 0][i++];
45 const neutral = resolveMagicAttack({
44 const neutral = resolveMagicAttack({
46 magicSkillLevel: 10,
45 magicSkillLevel: 10,
47 spellDifficulty: 1,
46 spellDifficulty: 1,
48 mindSkillLevel: 5,
47 mindSkillLevel: 5,
49 mindBonus: 2,
50 element: "fire",
48 element: "fire",
51 targetAffinities: {},
49 targetAffinities: {},
52 rng
50 rng
53 });
51 });
54 assert.equal(neutral.outcome, "hit");
52 assert.equal(neutral.outcome, "hit");
55 assert.equal(neutral.multiplier, 1);
53 assert.equal(neutral.multiplier, 1);
54 assert.equal(neutral.damage, 1);
56
55
57 let j = 0;
56 let j = 0;
58 const rngWeak = () => [0.9, 0, 0, 0][j++];
57 const rngWeak = () => [0.9, 0, 0][j++];
59 const weak = resolveMagicAttack({
58 const weak = resolveMagicAttack({
60 magicSkillLevel: 10,
59 magicSkillLevel: 10,
61 spellDifficulty: 1,
60 spellDifficulty: 1,
62 mindSkillLevel: 5,
61 mindSkillLevel: 5,
63 mindBonus: 2,
64 element: "fire",
62 element: "fire",
65 targetAffinities: { fire: "weak" },
63 targetAffinities: { fire: "weak" },
66 rng: rngWeak
64 rng: rngWeak
@@ -83,9 +81,10 @@ test("non-damage spell applies effect only after a successful cast roll", () =>
83 assert.equal(result.effectId, "slow");
81 assert.equal(result.effectId, "slow");
84});
82});
85
83
86test("spell definitions expose per-spell difficulty", () =>
84test("spell definitions expose tier-based difficulty", () =>
87{
85{
88 const spark = spellDefinition(SpellId.spark);
86 const spark = spellDefinition(SpellId.spark);
89 assert.equal(spark.difficulty, 4);
87 assert.equal(spellDifficulty(spark), 4);
90 assert.equal(spark.element, "fire");
88 assert.equal(spark.element, "fire");
89 assert.ok(spellDefinition(SpellId.light));
91});
90});
server/tests/npc-equipment.test.js added +62 −0
@@ -0,0 +1,62 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { npcDefaultEquipment, npcClothDyeFromSeed, NPC_CLOTH_DYE_BYTE_MIN } from "../../shared/appearance/npcEquipment.js";
4 import { ItemId } from "../../shared/definitions/items.js";
5 import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
6 import { mobComponents } from "../src/simulation/spawners.js";
7 import { MobId } from "../../shared/definitions/mobs.js";
8
9 test("npcDefaultEquipment picks deterministic garments from display name", () =>
10 {
11 const a = npcDefaultEquipment("Ada Lovelace", "female");
12 const b = npcDefaultEquipment("Ada Lovelace", "female");
13 assert.deepEqual(a, b);
14 assert.ok(a.chest?.itemId);
15 assert.ok([LeatherItemId.clothShorts, LeatherItemId.clothTrousers].includes(a.legs?.itemId));
16 assert.equal(a.boots?.itemId, LeatherItemId.leatherShoes);
17 assert.ok(a.chest.dyeColor);
18 assert.ok(a.legs.dyeColor);
19 });
20
21 test("npc cloth dyes stay above minimum channel", () =>
22 {
23 const dye = npcClothDyeFromSeed("Test NPC", 3);
24 const min = NPC_CLOTH_DYE_BYTE_MIN / 255;
25 assert.ok(dye.r >= min);
26 assert.ok(dye.g >= min);
27 assert.ok(dye.b >= min);
28 });
29
30 test("humanoid spawner without equipment gets default clothing", () =>
31 {
32 const components = mobComponents({
33 mobTypeId: MobId.humanoid,
34 tileX: 8,
35 tileY: 8,
36 displayName: "Village Guard",
37 sex: "male",
38 equipment: {},
39 spawnerId: "test"
40 });
41 const slots = components.equipment?.slots ?? {};
42 assert.ok(slots.chest?.itemId);
43 assert.ok(slots.legs?.itemId);
44 assert.equal(slots.boots?.itemId, LeatherItemId.leatherShoes);
45 assert.equal(slots.chest?.instance?.kind, "clothing");
46 assert.equal(slots.legs?.instance?.kind, "clothing");
47 });
48
49 test("authored spawner chest overrides default clothing", () =>
50 {
51 const components = mobComponents({
52 mobTypeId: MobId.humanoid,
53 tileX: 8,
54 tileY: 8,
55 displayName: "Tailor",
56 sex: "female",
57 equipment: { chest: ItemId.clothShirt },
58 spawnerId: "test"
59 });
60 assert.equal(components.equipment.slots.chest.itemId, ItemId.clothShirt);
61 assert.equal(components.equipment.slots.chest.instance, undefined);
62 });
@@ -0,0 +1,62 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { npcDefaultEquipment, npcClothDyeFromSeed, NPC_CLOTH_DYE_BYTE_MIN } from "../../shared/appearance/npcEquipment.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
6import { mobComponents } from "../src/simulation/spawners.js";
7import { MobId } from "../../shared/definitions/mobs.js";
8
9test("npcDefaultEquipment picks deterministic garments from display name", () =>
10{
11 const a = npcDefaultEquipment("Ada Lovelace", "female");
12 const b = npcDefaultEquipment("Ada Lovelace", "female");
13 assert.deepEqual(a, b);
14 assert.ok(a.chest?.itemId);
15 assert.ok([LeatherItemId.clothShorts, LeatherItemId.clothTrousers].includes(a.legs?.itemId));
16 assert.equal(a.boots?.itemId, LeatherItemId.leatherShoes);
17 assert.ok(a.chest.dyeColor);
18 assert.ok(a.legs.dyeColor);
19});
20
21test("npc cloth dyes stay above minimum channel", () =>
22{
23 const dye = npcClothDyeFromSeed("Test NPC", 3);
24 const min = NPC_CLOTH_DYE_BYTE_MIN / 255;
25 assert.ok(dye.r >= min);
26 assert.ok(dye.g >= min);
27 assert.ok(dye.b >= min);
28});
29
30test("humanoid spawner without equipment gets default clothing", () =>
31{
32 const components = mobComponents({
33 mobTypeId: MobId.humanoid,
34 tileX: 8,
35 tileY: 8,
36 displayName: "Village Guard",
37 sex: "male",
38 equipment: {},
39 spawnerId: "test"
40 });
41 const slots = components.equipment?.slots ?? {};
42 assert.ok(slots.chest?.itemId);
43 assert.ok(slots.legs?.itemId);
44 assert.equal(slots.boots?.itemId, LeatherItemId.leatherShoes);
45 assert.equal(slots.chest?.instance?.kind, "clothing");
46 assert.equal(slots.legs?.instance?.kind, "clothing");
47});
48
49test("authored spawner chest overrides default clothing", () =>
50{
51 const components = mobComponents({
52 mobTypeId: MobId.humanoid,
53 tileX: 8,
54 tileY: 8,
55 displayName: "Tailor",
56 sex: "female",
57 equipment: { chest: ItemId.clothShirt },
58 spawnerId: "test"
59 });
60 assert.equal(components.equipment.slots.chest.itemId, ItemId.clothShirt);
61 assert.equal(components.equipment.slots.chest.instance, undefined);
62});
server/tests/skills.test.js +5 −4
@@ -4,6 +4,7 @@ import {
4 4 SKILL_XP_BASE,
5 5 xpToAdvanceFromLevel,
6 6 totalXpForLevel,
7 maxTotalSkillXp,
7 8 xpProgress,
8 9 levelFromTotalXp,
9 10 combatDamageXp,
@@ -86,11 +87,11 @@ test("legacy empty skills_blob loads as Health level 10 max HP", () =>
86 87 { harness.close(); }
87 88 });
88 89
89 test("xp to advance doubles each level starting at 50", () =>
90 test("xp to advance grows 10% per level starting at 50", () =>
90 91 {
91 92 assert.equal(xpToAdvanceFromLevel(1), 50);
92 assert.equal(xpToAdvanceFromLevel(2), 100);
93 assert.equal(xpToAdvanceFromLevel(3), 200);
93 assert.equal(xpToAdvanceFromLevel(2), 55);
94 assert.equal(xpToAdvanceFromLevel(3), 60);
94 95 assert.equal(xpToAdvanceFromLevel(99), 0);
95 96 });
96 97
@@ -105,7 +106,7 @@ test("level is derived from total xp", () =>
105 106
106 107 test("skills cap at level 99", () =>
107 108 {
108 const capped = totalXpForLevel(100) - 1;
109 const capped = maxTotalSkillXp();
109 110 assert.equal(levelFromTotalXp(capped), 99);
110 111 const progress = xpProgress(capped);
111 112 assert.equal(progress.level, 99);
@@ -4,6 +4,7 @@ import {
4 SKILL_XP_BASE,
4 SKILL_XP_BASE,
5 xpToAdvanceFromLevel,
5 xpToAdvanceFromLevel,
6 totalXpForLevel,
6 totalXpForLevel,
7 maxTotalSkillXp,
7 xpProgress,
8 xpProgress,
8 levelFromTotalXp,
9 levelFromTotalXp,
9 combatDamageXp,
10 combatDamageXp,
@@ -86,11 +87,11 @@ test("legacy empty skills_blob loads as Health level 10 max HP", () =>
86 { harness.close(); }
87 { harness.close(); }
87});
88});
88
89
89test("xp to advance doubles each level starting at 50", () =>
90test("xp to advance grows 10% per level starting at 50", () =>
90{
91{
91 assert.equal(xpToAdvanceFromLevel(1), 50);
92 assert.equal(xpToAdvanceFromLevel(1), 50);
92 assert.equal(xpToAdvanceFromLevel(2), 100);
93 assert.equal(xpToAdvanceFromLevel(2), 55);
93 assert.equal(xpToAdvanceFromLevel(3), 200);
94 assert.equal(xpToAdvanceFromLevel(3), 60);
94 assert.equal(xpToAdvanceFromLevel(99), 0);
95 assert.equal(xpToAdvanceFromLevel(99), 0);
95});
96});
96
97
@@ -105,7 +106,7 @@ test("level is derived from total xp", () =>
105
106
106test("skills cap at level 99", () =>
107test("skills cap at level 99", () =>
107{
108{
108 const capped = totalXpForLevel(100) - 1;
109 const capped = maxTotalSkillXp();
109 assert.equal(levelFromTotalXp(capped), 99);
110 assert.equal(levelFromTotalXp(capped), 99);
110 const progress = xpProgress(capped);
111 const progress = xpProgress(capped);
111 assert.equal(progress.level, 99);
112 assert.equal(progress.level, 99);
server/tests/spells.test.js added +104 −0
@@ -0,0 +1,104 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { SpellId } from "../../shared/definitions/spells.js";
4 import { SPELL_PROJECTILE_MS } from "../../shared/spells/constants.js";
5 import { mobComponents } from "../src/simulation/spawners.js";
6 import { MobId } from "../../shared/definitions/mobs.js";
7 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8
9 test("cast light resolves without command error and can place a spell light", () =>
10 {
11 const harness = makeSimulation({ workerCount: 1 });
12 try
13 {
14 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
15 harness.simulation.spawnCharacter(1, character);
16
17 harness.simulation.enqueue(1, {
18 type: "cast-spell-tile",
19 characterId: character.character_id,
20 spellId: SpellId.light,
21 tileX: 10,
22 tileY: 8
23 });
24 const cast = harness.simulation.step();
25 assert.equal(
26 cast.events.some((event) => event.type === "command-error"),
27 false,
28 JSON.stringify(cast.events)
29 );
30 assert.ok(
31 cast.events.some((event) => event.type === "spell-fizzle" || event.type === "spell-projectile"),
32 "expected fizzle or projectile"
33 );
34
35 if (!cast.events.some((event) => event.type === "spell-projectile"))
36 { return; }
37
38 harness.advance(SPELL_PROJECTILE_MS + 50);
39 const impact = harness.simulation.step();
40 assert.ok(
41 impact.events.some((event) => event.type === "spell-light-appear"),
42 JSON.stringify(impact.events.map((event) => event.type))
43 );
44 }
45 finally
46 { harness.close(); }
47 });
48
49 test("out-of-range spell cast paths toward the nearest in-range tile", () =>
50 {
51 const harness = makeSimulation({ workerCount: 1 });
52 try
53 {
54 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
55 const playerId = harness.simulation.spawnCharacter(1, character);
56 harness.simulation.enqueue(1, {
57 type: "cast-spell-tile",
58 characterId: character.character_id,
59 spellId: SpellId.light,
60 tileX: 30,
61 tileY: 8
62 });
63 const cast = harness.simulation.step();
64 assert.equal(cast.events.some((event) => event.type === "command-error"), false);
65 const start = harness.simulation.entityRecord(playerId);
66 for (let i = 0; i < 80; i++)
67 { harness.simulation.step(); }
68 const moved = harness.simulation.entityRecord(playerId);
69 assert.ok(
70 moved.tileX !== start.tileX || moved.tileY !== start.tileY,
71 `expected movement from (${start.tileX},${start.tileY}), got (${moved.tileX},${moved.tileY})`
72 );
73 }
74 finally
75 { harness.close(); }
76 });
77
78 test("attack from out of range paths toward the target", () =>
79 {
80 const harness = makeSimulation({ workerCount: 1 });
81 try
82 {
83 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
84 const playerId = harness.simulation.spawnCharacter(1, character);
85 const deerId = harness.simulation.spawnEntity(mobComponents({
86 tileX: 24,
87 tileY: 8,
88 mobTypeId: MobId.deer
89 }));
90 harness.simulation.enqueue(1, {
91 type: "attack",
92 characterId: character.character_id,
93 targetEntityId: deerId
94 });
95 harness.simulation.step();
96 const record = harness.simulation.entityRecord(playerId);
97 assert.ok(record.tileX < 24);
98 for (let i = 0; i < 80 && record.tileX < 20; i++)
99 { harness.simulation.step(); }
100 assert.ok(harness.simulation.entityRecord(playerId).tileX > 8);
101 }
102 finally
103 { harness.close(); }
104 });
@@ -0,0 +1,104 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { SpellId } from "../../shared/definitions/spells.js";
4import { SPELL_PROJECTILE_MS } from "../../shared/spells/constants.js";
5import { mobComponents } from "../src/simulation/spawners.js";
6import { MobId } from "../../shared/definitions/mobs.js";
7import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8
9test("cast light resolves without command error and can place a spell light", () =>
10{
11 const harness = makeSimulation({ workerCount: 1 });
12 try
13 {
14 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
15 harness.simulation.spawnCharacter(1, character);
16
17 harness.simulation.enqueue(1, {
18 type: "cast-spell-tile",
19 characterId: character.character_id,
20 spellId: SpellId.light,
21 tileX: 10,
22 tileY: 8
23 });
24 const cast = harness.simulation.step();
25 assert.equal(
26 cast.events.some((event) => event.type === "command-error"),
27 false,
28 JSON.stringify(cast.events)
29 );
30 assert.ok(
31 cast.events.some((event) => event.type === "spell-fizzle" || event.type === "spell-projectile"),
32 "expected fizzle or projectile"
33 );
34
35 if (!cast.events.some((event) => event.type === "spell-projectile"))
36 { return; }
37
38 harness.advance(SPELL_PROJECTILE_MS + 50);
39 const impact = harness.simulation.step();
40 assert.ok(
41 impact.events.some((event) => event.type === "spell-light-appear"),
42 JSON.stringify(impact.events.map((event) => event.type))
43 );
44 }
45 finally
46 { harness.close(); }
47});
48
49test("out-of-range spell cast paths toward the nearest in-range tile", () =>
50{
51 const harness = makeSimulation({ workerCount: 1 });
52 try
53 {
54 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
55 const playerId = harness.simulation.spawnCharacter(1, character);
56 harness.simulation.enqueue(1, {
57 type: "cast-spell-tile",
58 characterId: character.character_id,
59 spellId: SpellId.light,
60 tileX: 30,
61 tileY: 8
62 });
63 const cast = harness.simulation.step();
64 assert.equal(cast.events.some((event) => event.type === "command-error"), false);
65 const start = harness.simulation.entityRecord(playerId);
66 for (let i = 0; i < 80; i++)
67 { harness.simulation.step(); }
68 const moved = harness.simulation.entityRecord(playerId);
69 assert.ok(
70 moved.tileX !== start.tileX || moved.tileY !== start.tileY,
71 `expected movement from (${start.tileX},${start.tileY}), got (${moved.tileX},${moved.tileY})`
72 );
73 }
74 finally
75 { harness.close(); }
76});
77
78test("attack from out of range paths toward the target", () =>
79{
80 const harness = makeSimulation({ workerCount: 1 });
81 try
82 {
83 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
84 const playerId = harness.simulation.spawnCharacter(1, character);
85 const deerId = harness.simulation.spawnEntity(mobComponents({
86 tileX: 24,
87 tileY: 8,
88 mobTypeId: MobId.deer
89 }));
90 harness.simulation.enqueue(1, {
91 type: "attack",
92 characterId: character.character_id,
93 targetEntityId: deerId
94 });
95 harness.simulation.step();
96 const record = harness.simulation.entityRecord(playerId);
97 assert.ok(record.tileX < 24);
98 for (let i = 0; i < 80 && record.tileX < 20; i++)
99 { harness.simulation.step(); }
100 assert.ok(harness.simulation.entityRecord(playerId).tileX > 8);
101 }
102 finally
103 { harness.close(); }
104});
server/tests/worker-transfer.test.js +7 −4
@@ -1,5 +1,6 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
3 4 import {
4 5 makeCharacter,
5 6 makeSimulation,
@@ -65,18 +66,20 @@ test("a blocked destination rejects the transfer and leaves one copy on the sour
65 66 try
66 67 {
67 68 const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });
68 const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });
69 const anchor = makeCharacter(harness.stateDb, { tileX: 70, tileY: 8, firstName: "Bob" });
69 70 const walkerId = harness.simulation.spawnCharacter(1, walker);
70 const blockerId = harness.simulation.spawnCharacter(2, blocker);
71 harness.simulation.spawnCharacter(2, anchor);
71 72 assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
72 assert.equal(harness.simulation.entityRecord(blockerId).workerId, 1);
73
74 const eastWorker = harness.simulation.workers[1];
75 const data = eastWorker.world.chunkData(4, 0);
76 data.blocks[8 * 16 + 0] = { typeId: BlockType.stoneWall, state: null, config: null };
73 77
74 78 harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
75 79 stepTimes(harness.simulation, walkTicks(3));
76 80 const walking = harness.simulation.entityRecord(walkerId);
77 81 assert.ok(walking.tileX < 64);
78 82 assert.equal(walking.workerId, 0);
79 assert.equal(harness.simulation.entityRecord(blockerId).tileX, 64);
80 83 assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);
81 84 }
82 85 finally
@@ -1,5 +1,6 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
3import {
4import {
4 makeCharacter,
5 makeCharacter,
5 makeSimulation,
6 makeSimulation,
@@ -65,18 +66,20 @@ test("a blocked destination rejects the transfer and leaves one copy on the sour
65 try
66 try
66 {
67 {
67 const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });
68 const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });
68 const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });
69 const anchor = makeCharacter(harness.stateDb, { tileX: 70, tileY: 8, firstName: "Bob" });
69 const walkerId = harness.simulation.spawnCharacter(1, walker);
70 const walkerId = harness.simulation.spawnCharacter(1, walker);
70 const blockerId = harness.simulation.spawnCharacter(2, blocker);
71 harness.simulation.spawnCharacter(2, anchor);
71 assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
72 assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
72 assert.equal(harness.simulation.entityRecord(blockerId).workerId, 1);
73
74 const eastWorker = harness.simulation.workers[1];
75 const data = eastWorker.world.chunkData(4, 0);
76 data.blocks[8 * 16 + 0] = { typeId: BlockType.stoneWall, state: null, config: null };
73
77
74 harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
78 harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
75 stepTimes(harness.simulation, walkTicks(3));
79 stepTimes(harness.simulation, walkTicks(3));
76 const walking = harness.simulation.entityRecord(walkerId);
80 const walking = harness.simulation.entityRecord(walkerId);
77 assert.ok(walking.tileX < 64);
81 assert.ok(walking.tileX < 64);
78 assert.equal(walking.workerId, 0);
82 assert.equal(walking.workerId, 0);
79 assert.equal(harness.simulation.entityRecord(blockerId).tileX, 64);
80 assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);
83 assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);
81 }
84 }
82 finally
85 finally
shared/alchemy/recipes.js +20 −1
@@ -1,4 +1,4 @@
1 import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS, CAULDRON_FLAVOR_LINES, CAULDRON_EMPTY_FLAVOR } from "../definitions/alchemy.js";
1 import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS, CAULDRON_FLAVOR_LINES, CAULDRON_EMPTY_FLAVOR, alchemyPotionDefinition } from "../definitions/alchemy.js";
2 2 import { ITEM_DEFINITIONS, itemDefinition } from "../definitions/items.js";
3 3 import { skillLevel, SkillId } from "../definitions/skills.js";
4 4
@@ -250,3 +250,22 @@ export function potionItemInstance (result)
250 250 minAlchemyLevel: result.minAlchemyLevel ?? null
251 251 };
252 252 }
253
254 /** Resolve a potion instance's gameplay effect (legacy rows may omit `effect`). */
255 export function resolvePotionEffect (instance)
256 {
257 if (!instance || instance.kind !== "potion")
258 { return null; }
259 if (instance.effect && typeof instance.effect === "object")
260 { return instance.effect; }
261 const potionKey = instance.potionKey;
262 if (!potionKey)
263 { return null; }
264 if (potionKey.startsWith("unstable:"))
265 {
266 const effectKey = potionKey.slice("unstable:".length) || instance.effectKey;
267 const entry = UNSTABLE_POTION_EFFECTS.find((row) => row.effectKey === effectKey);
268 return entry?.effect ?? null;
269 }
270 return alchemyPotionDefinition(potionKey)?.effect ?? null;
271 }
@@ -1,4 +1,4 @@
1import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS, CAULDRON_FLAVOR_LINES, CAULDRON_EMPTY_FLAVOR } from "../definitions/alchemy.js";
1import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS, CAULDRON_FLAVOR_LINES, CAULDRON_EMPTY_FLAVOR, alchemyPotionDefinition } from "../definitions/alchemy.js";
2import { ITEM_DEFINITIONS, itemDefinition } from "../definitions/items.js";
2import { ITEM_DEFINITIONS, itemDefinition } from "../definitions/items.js";
3import { skillLevel, SkillId } from "../definitions/skills.js";
3import { skillLevel, SkillId } from "../definitions/skills.js";
4
4
@@ -250,3 +250,22 @@ export function potionItemInstance (result)
250 minAlchemyLevel: result.minAlchemyLevel ?? null
250 minAlchemyLevel: result.minAlchemyLevel ?? null
251 };
251 };
252}
252}
253
254/** Resolve a potion instance's gameplay effect (legacy rows may omit `effect`). */
255export function resolvePotionEffect (instance)
256{
257 if (!instance || instance.kind !== "potion")
258 { return null; }
259 if (instance.effect && typeof instance.effect === "object")
260 { return instance.effect; }
261 const potionKey = instance.potionKey;
262 if (!potionKey)
263 { return null; }
264 if (potionKey.startsWith("unstable:"))
265 {
266 const effectKey = potionKey.slice("unstable:".length) || instance.effectKey;
267 const entry = UNSTABLE_POTION_EFFECTS.find((row) => row.effectKey === effectKey);
268 return entry?.effect ?? null;
269 }
270 return alchemyPotionDefinition(potionKey)?.effect ?? null;
271}
shared/appearance/npcEquipment.js added +51 −0
@@ -0,0 +1,51 @@
1 import { hashString } from "./hair.js";
2 import { ItemId } from "../definitions/items.js";
3 import { sweaterItemId } from "../definitions/clothItems.js";
4 import { CLOTH_TIER_ORDER } from "../definitions/materialTiers.js";
5 import { LeatherItemId } from "../definitions/leatherItems.js";
6 import { normalizeRgb } from "../render/tint.js";
7
8 /** Minimum byte channel when rolling random NPC cloth dyes (avoids near-black). */
9 export const NPC_CLOTH_DYE_BYTE_MIN = 40;
10
11 /**
12 * Deterministic dye from a display name (+ optional salt).
13 * @returns {{ r: number, g: number, b: number }} linear RGB 0–1
14 */
15 export function npcClothDyeFromSeed (displayName, salt = 0)
16 {
17 const seed = hashString(`${String(displayName ?? "").trim().toLowerCase() || "npc"}:${salt}`);
18 const span = 256 - NPC_CLOTH_DYE_BYTE_MIN;
19 const r = NPC_CLOTH_DYE_BYTE_MIN + (seed % span);
20 const g = NPC_CLOTH_DYE_BYTE_MIN + ((seed >>> 8) % span);
21 const b = NPC_CLOTH_DYE_BYTE_MIN + ((seed >>> 16) % span);
22 return normalizeRgb({ r: r / 255, g: g / 255, b: b / 255 });
23 }
24
25 /**
26 * Default humanoid spawner clothing when a slot is left empty.
27 * Chest/legs use random dyes; boots are soft-leather shoes (tier tint).
28 *
29 * @returns {Partial<Record<"chest"|"legs"|"boots", { itemId: number, dyeColor: object|null }>>}
30 */
31 export function npcDefaultEquipment (displayName, sex = "male")
32 {
33 const name = String(displayName ?? "").trim().toLowerCase() || "npc";
34 const seed = hashString(name);
35
36 const wantsSweater = (seed >>> 12) % 5 === 0;
37 const chestTier = CLOTH_TIER_ORDER[(seed >>> 6) % CLOTH_TIER_ORDER.length];
38 const chestItemId = wantsSweater
39 ? sweaterItemId(chestTier)
40 : ItemId.clothShirt;
41
42 const legsItemId = (seed & 1) === 0
43 ? LeatherItemId.clothShorts
44 : LeatherItemId.clothTrousers;
45
46 return {
47 chest: { itemId: chestItemId, dyeColor: npcClothDyeFromSeed(name, 1) },
48 legs: { itemId: legsItemId, dyeColor: npcClothDyeFromSeed(name, 2) },
49 boots: { itemId: LeatherItemId.leatherShoes, dyeColor: null }
50 };
51 }
@@ -0,0 +1,51 @@
1import { hashString } from "./hair.js";
2import { ItemId } from "../definitions/items.js";
3import { sweaterItemId } from "../definitions/clothItems.js";
4import { CLOTH_TIER_ORDER } from "../definitions/materialTiers.js";
5import { LeatherItemId } from "../definitions/leatherItems.js";
6import { normalizeRgb } from "../render/tint.js";
7
8/** Minimum byte channel when rolling random NPC cloth dyes (avoids near-black). */
9export const NPC_CLOTH_DYE_BYTE_MIN = 40;
10
11/**
12 * Deterministic dye from a display name (+ optional salt).
13 * @returns {{ r: number, g: number, b: number }} linear RGB 0–1
14 */
15export function npcClothDyeFromSeed (displayName, salt = 0)
16{
17 const seed = hashString(`${String(displayName ?? "").trim().toLowerCase() || "npc"}:${salt}`);
18 const span = 256 - NPC_CLOTH_DYE_BYTE_MIN;
19 const r = NPC_CLOTH_DYE_BYTE_MIN + (seed % span);
20 const g = NPC_CLOTH_DYE_BYTE_MIN + ((seed >>> 8) % span);
21 const b = NPC_CLOTH_DYE_BYTE_MIN + ((seed >>> 16) % span);
22 return normalizeRgb({ r: r / 255, g: g / 255, b: b / 255 });
23}
24
25/**
26 * Default humanoid spawner clothing when a slot is left empty.
27 * Chest/legs use random dyes; boots are soft-leather shoes (tier tint).
28 *
29 * @returns {Partial<Record<"chest"|"legs"|"boots", { itemId: number, dyeColor: object|null }>>}
30 */
31export function npcDefaultEquipment (displayName, sex = "male")
32{
33 const name = String(displayName ?? "").trim().toLowerCase() || "npc";
34 const seed = hashString(name);
35
36 const wantsSweater = (seed >>> 12) % 5 === 0;
37 const chestTier = CLOTH_TIER_ORDER[(seed >>> 6) % CLOTH_TIER_ORDER.length];
38 const chestItemId = wantsSweater
39 ? sweaterItemId(chestTier)
40 : ItemId.clothShirt;
41
42 const legsItemId = (seed & 1) === 0
43 ? LeatherItemId.clothShorts
44 : LeatherItemId.clothTrousers;
45
46 return {
47 chest: { itemId: chestItemId, dyeColor: npcClothDyeFromSeed(name, 1) },
48 legs: { itemId: legsItemId, dyeColor: npcClothDyeFromSeed(name, 2) },
49 boots: { itemId: LeatherItemId.leatherShoes, dyeColor: null }
50 };
51}
shared/combat/magic.js +15 −13
@@ -20,7 +20,7 @@ export const ElementMultiplier = Object.freeze({
20 20
21 21 /**
22 22 * Whether the caster successfully channels the spell.
23 * Magic roll vs a difficulty roll sized by spell.difficulty.
23 * Magic roll vs a difficulty roll sized by spell tier.
24 24 * Succeeds on tie or higher (same rule as physical hit vs Agility).
25 25 */
26 26 export function resolveSpellCast ({
@@ -50,21 +50,12 @@ function elementalMultiplier (element, targetAffinities = {})
50 50 }
51 51
52 52 /**
53 * Full magic attack resolution (shared rules, not wired to server combat yet).
54 * @param {object} params
55 * @param {number} params.magicSkillLevel
56 * @param {number} params.spellDifficulty
57 * @param {number} params.mindSkillLevel
58 * @param {number} [params.mindBonus]
59 * @param {SpellElement} [params.element]
60 * @param {Partial<Record<SpellElement, "weak"|"resistant"|"neutral">>} [params.targetAffinities]
61 * @param {() => number} [params.rng]
53 * Full magic attack resolution (shared rules).
62 54 */
63 55 export function resolveMagicAttack ({
64 56 magicSkillLevel,
65 57 spellDifficulty,
66 58 mindSkillLevel,
67 mindBonus = 0,
68 59 element = "none",
69 60 targetAffinities = {},
70 61 rng = Math.random
@@ -83,9 +74,8 @@ export function resolveMagicAttack ({
83 74 }
84 75
85 76 const mindRoll = rollSkill(mindSkillLevel, rng);
86 const rawDamage = Math.max(1, (mindBonus | 0) + mindRoll - (mindBonus ? 1 : 0));
87 77 const multiplier = elementalMultiplier(element, targetAffinities);
88 const damage = Math.max(1, Math.floor(rawDamage * multiplier));
78 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
89 79
90 80 return {
91 81 outcome: "hit",
@@ -97,6 +87,13 @@ export function resolveMagicAttack ({
97 87 };
98 88 }
99 89
90 /** Potency roll for non-damage spells (e.g. Light duration = mindRoll × 5 seconds). */
91 export function resolveSpellPotency ({ mindSkillLevel, rng = Math.random })
92 {
93 const mindRoll = rollSkill(mindSkillLevel, rng);
94 return { mindRoll };
95 }
96
100 97 /**
101 98 * Non-damage spells: Magic vs spell difficulty, then apply effectId.
102 99 */
@@ -124,3 +121,8 @@ export function resolveMagicEffect ({
124 121 effectId: effectId ?? null
125 122 };
126 123 }
124
125 export function mobElementAffinities (mobDef)
126 {
127 return mobDef?.elementAffinities ?? {};
128 }
@@ -20,7 +20,7 @@ export const ElementMultiplier = Object.freeze({
20
20
21/**
21/**
22 * Whether the caster successfully channels the spell.
22 * Whether the caster successfully channels the spell.
23 * Magic roll vs a difficulty roll sized by spell.difficulty.
23 * Magic roll vs a difficulty roll sized by spell tier.
24 * Succeeds on tie or higher (same rule as physical hit vs Agility).
24 * Succeeds on tie or higher (same rule as physical hit vs Agility).
25 */
25 */
26export function resolveSpellCast ({
26export function resolveSpellCast ({
@@ -50,21 +50,12 @@ function elementalMultiplier (element, targetAffinities = {})
50}
50}
51
51
52/**
52/**
53 * Full magic attack resolution (shared rules, not wired to server combat yet).
53 * Full magic attack resolution (shared rules).
54 * @param {object} params
55 * @param {number} params.magicSkillLevel
56 * @param {number} params.spellDifficulty
57 * @param {number} params.mindSkillLevel
58 * @param {number} [params.mindBonus]
59 * @param {SpellElement} [params.element]
60 * @param {Partial<Record<SpellElement, "weak"|"resistant"|"neutral">>} [params.targetAffinities]
61 * @param {() => number} [params.rng]
62 */
54 */
63export function resolveMagicAttack ({
55export function resolveMagicAttack ({
64 magicSkillLevel,
56 magicSkillLevel,
65 spellDifficulty,
57 spellDifficulty,
66 mindSkillLevel,
58 mindSkillLevel,
67 mindBonus = 0,
68 element = "none",
59 element = "none",
69 targetAffinities = {},
60 targetAffinities = {},
70 rng = Math.random
61 rng = Math.random
@@ -83,9 +74,8 @@ export function resolveMagicAttack ({
83 }
74 }
84
75
85 const mindRoll = rollSkill(mindSkillLevel, rng);
76 const mindRoll = rollSkill(mindSkillLevel, rng);
86 const rawDamage = Math.max(1, (mindBonus | 0) + mindRoll - (mindBonus ? 1 : 0));
87 const multiplier = elementalMultiplier(element, targetAffinities);
77 const multiplier = elementalMultiplier(element, targetAffinities);
88 const damage = Math.max(1, Math.floor(rawDamage * multiplier));
78 const damage = Math.max(1, Math.floor(mindRoll * multiplier));
89
79
90 return {
80 return {
91 outcome: "hit",
81 outcome: "hit",
@@ -97,6 +87,13 @@ export function resolveMagicAttack ({
97 };
87 };
98}
88}
99
89
90/** Potency roll for non-damage spells (e.g. Light duration = mindRoll × 5 seconds). */
91export function resolveSpellPotency ({ mindSkillLevel, rng = Math.random })
92{
93 const mindRoll = rollSkill(mindSkillLevel, rng);
94 return { mindRoll };
95}
96
100/**
97/**
101 * Non-damage spells: Magic vs spell difficulty, then apply effectId.
98 * Non-damage spells: Magic vs spell difficulty, then apply effectId.
102 */
99 */
@@ -124,3 +121,8 @@ export function resolveMagicEffect ({
124 effectId: effectId ?? null
121 effectId: effectId ?? null
125 };
122 };
126}
123}
124
125export function mobElementAffinities (mobDef)
126{
127 return mobDef?.elementAffinities ?? {};
128}
shared/crafting/stationRecipes.js +54 −7
@@ -2,19 +2,17 @@ import { CraftingStationId } from "../definitions/craftingStations.js";
2 2 import { ItemId } from "../definitions/items.js";
3 3 import { CraftingItemId } from "../definitions/craftingItems.js";
4 4 import { MetalItemId } from "../definitions/metalItems.js";
5 import { LeatherItemId } from "../definitions/leatherItems.js";
6 import { ClothItemId, wovenClothItemId, rawClothItemId, yarnItemId, CLOTHING_TEMPLATES } from "../definitions/clothItems.js";
5 7 import {
6 8 MaterialTier,
7 9 GatherMaterialId,
8 10 CLOTH_TIER_ORDER,
11 ClothTier,
12 LeatherTier,
9 13 tierSmeltSkillLevel,
10 14 tierCraftSkillLevel
11 15 } from "../definitions/materialTiers.js";
12 import {
13 rawClothItemId,
14 yarnItemId,
15 wovenClothItemId,
16 CLOTHING_TEMPLATES
17 } from "../definitions/clothItems.js";
18 16 import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
19 17
20 18 /**
@@ -136,7 +134,56 @@ export const CRAFT_RECIPES = Object.freeze([
136 134 ...TIER_FAMILY_RECIPES,
137 135 ...YARN_SPIN_RECIPES,
138 136 ...CLOTH_WEAVE_RECIPES,
139 ...TAILOR_TEMPLATE_RECIPES
137 ...TAILOR_TEMPLATE_RECIPES,
138
139 Object.freeze({
140 recipeId: "smith-steel-stud",
141 stationId: CraftingStationId.anvil,
142 output: { itemId: LeatherItemId.steelStud, quantity: 6 },
143 inputs: [{ itemId: MetalItemId.steelBar, quantity: 1 }],
144 minSkillLevel: tierCraftSkillLevel(MaterialTier.steel),
145 skillId: "smithing",
146 xpMaterial: MaterialTier.steel
147 }),
148
149 Object.freeze({
150 recipeId: "leather-hard",
151 stationId: CraftingStationId.leatherworkingStation,
152 output: { itemId: LeatherItemId.hardLeather, quantity: 1 },
153 inputs: [
154 { itemId: LeatherItemId.softLeather, quantity: 1 },
155 { itemId: LeatherItemId.tanningBrew, quantity: 1 }
156 ],
157 minSkillLevel: tierCraftSkillLevel(LeatherTier.hardLeather),
158 skillId: "leatherworking",
159 xpMaterial: LeatherTier.hardLeather
160 }),
161
162 Object.freeze({
163 recipeId: "leather-studded",
164 stationId: CraftingStationId.leatherworkingStation,
165 output: { itemId: LeatherItemId.studdedLeather, quantity: 1 },
166 inputs: [
167 { itemId: LeatherItemId.hardLeather, quantity: 1 },
168 { itemId: LeatherItemId.steelStud, quantity: 2 }
169 ],
170 minSkillLevel: tierCraftSkillLevel(LeatherTier.studdedLeather),
171 skillId: "leatherworking",
172 xpMaterial: LeatherTier.studdedLeather
173 }),
174
175 Object.freeze({
176 recipeId: "leather-reinforced",
177 stationId: CraftingStationId.leatherworkingStation,
178 output: { itemId: LeatherItemId.reinforcedLeather, quantity: 1 },
179 inputs: [
180 { itemId: LeatherItemId.studdedLeather, quantity: 1 },
181 { itemId: wovenClothItemId(ClothTier.cashmere), quantity: 1 }
182 ],
183 minSkillLevel: tierCraftSkillLevel(LeatherTier.reinforcedLeather),
184 skillId: "leatherworking",
185 xpMaterial: LeatherTier.reinforcedLeather
186 })
140 187 ]);
141 188
142 189 const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
@@ -2,19 +2,17 @@ import { CraftingStationId } from "../definitions/craftingStations.js";
2import { ItemId } from "../definitions/items.js";
2import { ItemId } from "../definitions/items.js";
3import { CraftingItemId } from "../definitions/craftingItems.js";
3import { CraftingItemId } from "../definitions/craftingItems.js";
4import { MetalItemId } from "../definitions/metalItems.js";
4import { MetalItemId } from "../definitions/metalItems.js";
5import { LeatherItemId } from "../definitions/leatherItems.js";
6import { ClothItemId, wovenClothItemId, rawClothItemId, yarnItemId, CLOTHING_TEMPLATES } from "../definitions/clothItems.js";
5import {
7import {
6 MaterialTier,
8 MaterialTier,
7 GatherMaterialId,
9 GatherMaterialId,
8 CLOTH_TIER_ORDER,
10 CLOTH_TIER_ORDER,
11 ClothTier,
12 LeatherTier,
9 tierSmeltSkillLevel,
13 tierSmeltSkillLevel,
10 tierCraftSkillLevel
14 tierCraftSkillLevel
11} from "../definitions/materialTiers.js";
15} from "../definitions/materialTiers.js";
12import {
13 rawClothItemId,
14 yarnItemId,
15 wovenClothItemId,
16 CLOTHING_TEMPLATES
17} from "../definitions/clothItems.js";
18import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
16import { TIER_FAMILY_RECIPES } from "./tierRecipes.js";
19
17
20/**
18/**
@@ -136,7 +134,56 @@ export const CRAFT_RECIPES = Object.freeze([
136 ...TIER_FAMILY_RECIPES,
134 ...TIER_FAMILY_RECIPES,
137 ...YARN_SPIN_RECIPES,
135 ...YARN_SPIN_RECIPES,
138 ...CLOTH_WEAVE_RECIPES,
136 ...CLOTH_WEAVE_RECIPES,
139 ...TAILOR_TEMPLATE_RECIPES
137 ...TAILOR_TEMPLATE_RECIPES,
138
139 Object.freeze({
140 recipeId: "smith-steel-stud",
141 stationId: CraftingStationId.anvil,
142 output: { itemId: LeatherItemId.steelStud, quantity: 6 },
143 inputs: [{ itemId: MetalItemId.steelBar, quantity: 1 }],
144 minSkillLevel: tierCraftSkillLevel(MaterialTier.steel),
145 skillId: "smithing",
146 xpMaterial: MaterialTier.steel
147 }),
148
149 Object.freeze({
150 recipeId: "leather-hard",
151 stationId: CraftingStationId.leatherworkingStation,
152 output: { itemId: LeatherItemId.hardLeather, quantity: 1 },
153 inputs: [
154 { itemId: LeatherItemId.softLeather, quantity: 1 },
155 { itemId: LeatherItemId.tanningBrew, quantity: 1 }
156 ],
157 minSkillLevel: tierCraftSkillLevel(LeatherTier.hardLeather),
158 skillId: "leatherworking",
159 xpMaterial: LeatherTier.hardLeather
160 }),
161
162 Object.freeze({
163 recipeId: "leather-studded",
164 stationId: CraftingStationId.leatherworkingStation,
165 output: { itemId: LeatherItemId.studdedLeather, quantity: 1 },
166 inputs: [
167 { itemId: LeatherItemId.hardLeather, quantity: 1 },
168 { itemId: LeatherItemId.steelStud, quantity: 2 }
169 ],
170 minSkillLevel: tierCraftSkillLevel(LeatherTier.studdedLeather),
171 skillId: "leatherworking",
172 xpMaterial: LeatherTier.studdedLeather
173 }),
174
175 Object.freeze({
176 recipeId: "leather-reinforced",
177 stationId: CraftingStationId.leatherworkingStation,
178 output: { itemId: LeatherItemId.reinforcedLeather, quantity: 1 },
179 inputs: [
180 { itemId: LeatherItemId.studdedLeather, quantity: 1 },
181 { itemId: wovenClothItemId(ClothTier.cashmere), quantity: 1 }
182 ],
183 minSkillLevel: tierCraftSkillLevel(LeatherTier.reinforcedLeather),
184 skillId: "leatherworking",
185 xpMaterial: LeatherTier.reinforcedLeather
186 })
140]);
187]);
141
188
142const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
189const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
shared/definitions/craftingItems.js +0 −3
@@ -101,9 +101,6 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
101 101 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
102 102 description: "Meat roasted until tender."
103 103 }),
104 [CraftingItemId.leather]: stub(CraftingItemId.leather, "leather", "Leather", ItemCategory.ingredient, {
105 description: "Cured hide, stout enough for armour and straps."
106 }),
107 104 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
108 105 stackable: false,
109 106 maxStackSize: 1,
@@ -101,9 +101,6 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
101 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
101 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
102 description: "Meat roasted until tender."
102 description: "Meat roasted until tender."
103 }),
103 }),
104 [CraftingItemId.leather]: stub(CraftingItemId.leather, "leather", "Leather", ItemCategory.ingredient, {
105 description: "Cured hide, stout enough for armour and straps."
106 }),
107 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
104 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
108 stackable: false,
105 stackable: false,
109 maxStackSize: 1,
106 maxStackSize: 1,
shared/definitions/items.js +6 −0
@@ -10,10 +10,12 @@ import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
10 10 import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
11 11 import { ArmourItemId, ARMOUR_ITEM_DEFINITIONS } from "./armourItems.js";
12 12 import { ClothItemId, CLOTH_ITEM_DEFINITIONS } from "./clothItems.js";
13 import { LeatherItemId, LEATHER_ITEM_DEFINITIONS } from "./leatherItems.js";
13 14 import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
14 15 import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
15 16 import { RANGED_ITEM_DEFINITIONS, RangedItemId } from "./rangedItems.js";
16 17 import { POTION_MAX_STACK } from "./alchemy.js";
18 import { SpellbookItemId, SPELLBOOK_ITEM_DEFINITIONS } from "./spellItems.js";
17 19
18 20 export const ItemId = Object.freeze({
19 21 paper: 1,
@@ -31,10 +33,12 @@ export const ItemId = Object.freeze({
31 33 glassBottle: 29,
32 34 potion: 32,
33 35 recipePaper: 33,
36 ...SpellbookItemId,
34 37 ...MetalItemId,
35 38 ...WoodItemId,
36 39 ...ArmourItemId,
37 40 ...ClothItemId,
41 ...LeatherItemId,
38 42 ...DyeItemId,
39 43 ...HerbItemId,
40 44 ...RangedItemId
@@ -269,12 +273,14 @@ export const ITEM_DEFINITIONS = Object.freeze({
269 273 iconKey: "paper"
270 274 }),
271 275 ...CRAFTING_ITEM_STUBS,
276 ...LEATHER_ITEM_DEFINITIONS,
272 277 ...METAL_ITEM_DEFINITIONS,
273 278 ...WOOD_ITEM_DEFINITIONS,
274 279 ...ARMOUR_ITEM_DEFINITIONS,
275 280 ...CLOTH_ITEM_DEFINITIONS,
276 281 ...HERB_ITEM_DEFINITIONS,
277 282 ...RANGED_ITEM_DEFINITIONS,
283 ...SPELLBOOK_ITEM_DEFINITIONS,
278 284 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
279 285 [DyeItemId.dye]: DYE_ITEM_DEFINITION
280 286 });
@@ -10,10 +10,12 @@ import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
10import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
10import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
11import { ArmourItemId, ARMOUR_ITEM_DEFINITIONS } from "./armourItems.js";
11import { ArmourItemId, ARMOUR_ITEM_DEFINITIONS } from "./armourItems.js";
12import { ClothItemId, CLOTH_ITEM_DEFINITIONS } from "./clothItems.js";
12import { ClothItemId, CLOTH_ITEM_DEFINITIONS } from "./clothItems.js";
13import { LeatherItemId, LEATHER_ITEM_DEFINITIONS } from "./leatherItems.js";
13import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
14import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
14import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
15import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
15import { RANGED_ITEM_DEFINITIONS, RangedItemId } from "./rangedItems.js";
16import { RANGED_ITEM_DEFINITIONS, RangedItemId } from "./rangedItems.js";
16import { POTION_MAX_STACK } from "./alchemy.js";
17import { POTION_MAX_STACK } from "./alchemy.js";
18import { SpellbookItemId, SPELLBOOK_ITEM_DEFINITIONS } from "./spellItems.js";
17
19
18export const ItemId = Object.freeze({
20export const ItemId = Object.freeze({
19 paper: 1,
21 paper: 1,
@@ -31,10 +33,12 @@ export const ItemId = Object.freeze({
31 glassBottle: 29,
33 glassBottle: 29,
32 potion: 32,
34 potion: 32,
33 recipePaper: 33,
35 recipePaper: 33,
36 ...SpellbookItemId,
34 ...MetalItemId,
37 ...MetalItemId,
35 ...WoodItemId,
38 ...WoodItemId,
36 ...ArmourItemId,
39 ...ArmourItemId,
37 ...ClothItemId,
40 ...ClothItemId,
41 ...LeatherItemId,
38 ...DyeItemId,
42 ...DyeItemId,
39 ...HerbItemId,
43 ...HerbItemId,
40 ...RangedItemId
44 ...RangedItemId
@@ -269,12 +273,14 @@ export const ITEM_DEFINITIONS = Object.freeze({
269 iconKey: "paper"
273 iconKey: "paper"
270 }),
274 }),
271 ...CRAFTING_ITEM_STUBS,
275 ...CRAFTING_ITEM_STUBS,
276 ...LEATHER_ITEM_DEFINITIONS,
272 ...METAL_ITEM_DEFINITIONS,
277 ...METAL_ITEM_DEFINITIONS,
273 ...WOOD_ITEM_DEFINITIONS,
278 ...WOOD_ITEM_DEFINITIONS,
274 ...ARMOUR_ITEM_DEFINITIONS,
279 ...ARMOUR_ITEM_DEFINITIONS,
275 ...CLOTH_ITEM_DEFINITIONS,
280 ...CLOTH_ITEM_DEFINITIONS,
276 ...HERB_ITEM_DEFINITIONS,
281 ...HERB_ITEM_DEFINITIONS,
277 ...RANGED_ITEM_DEFINITIONS,
282 ...RANGED_ITEM_DEFINITIONS,
283 ...SPELLBOOK_ITEM_DEFINITIONS,
278 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
284 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
279 [DyeItemId.dye]: DYE_ITEM_DEFINITION
285 [DyeItemId.dye]: DYE_ITEM_DEFINITION
280});
286});
shared/definitions/leatherItems.js added +176 −0
@@ -0,0 +1,176 @@
1 import { ItemCategory } from "./itemCategories.js";
2 import { EquipmentKind } from "./equipmentKinds.js";
3 import { equipImageName } from "./tileSprites.js";
4 import { CraftingItemId } from "./craftingItems.js";
5 import {
6 LeatherTier,
7 LEATHER_TIER_ORDER,
8 LEATHER_DISPLAY_NAME,
9 tierMinSkillLevel
10 } from "./materialTiers.js";
11
12 /** Leather materials, garments, and leatherworking intermediates. */
13 export const LeatherItemId = Object.freeze({
14 softLeather: CraftingItemId.leather,
15 hardLeather: 233,
16 studdedLeather: 234,
17 reinforcedLeather: 235,
18 scaledLeather: 236,
19 wyvernHide: 237,
20 dragonhide: 238,
21 clothShorts: 239,
22 clothTrousers: 240,
23 leatherShoes: 241,
24 steelStud: 242,
25 tanningBrew: 243
26 });
27
28 const LEATHER_MATERIAL_ID = Object.freeze({
29 [LeatherTier.softLeather]: LeatherItemId.softLeather,
30 [LeatherTier.hardLeather]: LeatherItemId.hardLeather,
31 [LeatherTier.studdedLeather]: LeatherItemId.studdedLeather,
32 [LeatherTier.reinforcedLeather]: LeatherItemId.reinforcedLeather,
33 [LeatherTier.scaledLeather]: LeatherItemId.scaledLeather,
34 [LeatherTier.wyvernHide]: LeatherItemId.wyvernHide,
35 [LeatherTier.dragonhide]: LeatherItemId.dragonhide
36 });
37
38 function leatherMaterialDef (itemId, tier, key)
39 {
40 const name = LEATHER_DISPLAY_NAME[tier] ?? tier;
41 return Object.freeze({
42 itemId,
43 key,
44 displayName: name,
45 description: tier === LeatherTier.softLeather
46 ? "Supple hide, warm from the field and ready for curing."
47 : `Cured ${name.toLowerCase()}, tough enough for straps and armour.`,
48 seedValue: tier === LeatherTier.softLeather ? 3 : 6,
49 stackable: true,
50 maxStackSize: 99,
51 uniqueInstance: false,
52 category: ItemCategory.ingredient,
53 iconKey: "leather",
54 defaultState: "leather",
55 tier,
56 tintFromTier: true
57 });
58 }
59
60 function buildLeatherMaterialDefinitions ()
61 {
62 const defs = {};
63 for (const tier of LEATHER_TIER_ORDER)
64 {
65 const itemId = LEATHER_MATERIAL_ID[tier];
66 if (itemId == null)
67 { throw new Error(`Missing leather item id for ${tier}`); }
68 const key = tier === LeatherTier.softLeather ? "soft-leather" : tier.replace(/([A-Z])/g, "-$1").toLowerCase();
69 defs[itemId] = leatherMaterialDef(itemId, tier, key);
70 }
71 return defs;
72 }
73
74 const LEGWEAR_BASE = Object.freeze({
75 stackable: false,
76 maxStackSize: 1,
77 uniqueInstance: false,
78 category: ItemCategory.finished,
79 iconKey: "clothing",
80 dyeable: true,
81 tightFit: true,
82 clothing: Object.freeze({ style: true }),
83 equipment: Object.freeze({
84 slot: "legs",
85 kind: EquipmentKind.clothArmour,
86 bonus: 0,
87 minSkillLevel: 1,
88 tintFromTier: false
89 })
90 });
91
92 /** @type {Record<number, object>} */
93 export const LEATHER_ITEM_DEFINITIONS = Object.freeze({
94 ...buildLeatherMaterialDefinitions(),
95 [LeatherItemId.clothShorts]: Object.freeze({
96 ...LEGWEAR_BASE,
97 itemId: LeatherItemId.clothShorts,
98 key: "cloth-shorts",
99 displayName: "Cloth shorts",
100 description: "Light cloth shorts cut for warm days on the road.",
101 seedValue: 4,
102 defaultState: "shorts",
103 equipment: Object.freeze({
104 ...LEGWEAR_BASE.equipment,
105 equipSprite: equipImageName("item", "clothing", "shorts")
106 })
107 }),
108 [LeatherItemId.clothTrousers]: Object.freeze({
109 ...LEGWEAR_BASE,
110 itemId: LeatherItemId.clothTrousers,
111 key: "cloth-trousers",
112 displayName: "Cloth trousers",
113 description: "Plain cloth trousers, sturdy enough for travel.",
114 seedValue: 5,
115 defaultState: "trousers",
116 equipment: Object.freeze({
117 ...LEGWEAR_BASE.equipment,
118 equipSprite: equipImageName("item", "clothing", "trousers")
119 })
120 }),
121 [LeatherItemId.leatherShoes]: Object.freeze({
122 itemId: LeatherItemId.leatherShoes,
123 key: "leather-shoes",
124 displayName: "Leather shoes",
125 description: "Simple soft-leather shoes, broken in from long walks.",
126 seedValue: 6,
127 stackable: false,
128 maxStackSize: 1,
129 uniqueInstance: false,
130 category: ItemCategory.finished,
131 iconKey: "clothing",
132 defaultState: "leather-shoes",
133 tier: LeatherTier.softLeather,
134 tintFromTier: true,
135 equipment: Object.freeze({
136 slot: "boots",
137 tier: LeatherTier.softLeather,
138 kind: EquipmentKind.leatherArmour,
139 bonus: 0,
140 minSkillLevel: tierMinSkillLevel(LeatherTier.softLeather),
141 tintFromTier: true,
142 equipSprite: equipImageName("item", "clothing", "leather-shoes")
143 })
144 }),
145 [LeatherItemId.steelStud]: Object.freeze({
146 itemId: LeatherItemId.steelStud,
147 key: "steel-stud",
148 displayName: "Steel stud",
149 description: "A small steel rivet for reinforcing leather.",
150 seedValue: 2,
151 stackable: true,
152 maxStackSize: 99,
153 uniqueInstance: false,
154 category: ItemCategory.intermediate,
155 iconKey: "metal",
156 defaultState: "stud"
157 }),
158 [LeatherItemId.tanningBrew]: Object.freeze({
159 itemId: LeatherItemId.tanningBrew,
160 key: "tanning-brew",
161 displayName: "Tanning brew",
162 description: "A sharp-smelling alchemy wash that cures hide into hard leather.",
163 seedValue: 8,
164 stackable: true,
165 maxStackSize: 99,
166 uniqueInstance: false,
167 category: ItemCategory.ingredient,
168 iconKey: "potion",
169 defaultState: "potion"
170 })
171 });
172
173 export function leatherMaterialItemId (tier)
174 {
175 return LEATHER_MATERIAL_ID[tier] ?? null;
176 }
@@ -0,0 +1,176 @@
1import { ItemCategory } from "./itemCategories.js";
2import { EquipmentKind } from "./equipmentKinds.js";
3import { equipImageName } from "./tileSprites.js";
4import { CraftingItemId } from "./craftingItems.js";
5import {
6 LeatherTier,
7 LEATHER_TIER_ORDER,
8 LEATHER_DISPLAY_NAME,
9 tierMinSkillLevel
10} from "./materialTiers.js";
11
12/** Leather materials, garments, and leatherworking intermediates. */
13export const LeatherItemId = Object.freeze({
14 softLeather: CraftingItemId.leather,
15 hardLeather: 233,
16 studdedLeather: 234,
17 reinforcedLeather: 235,
18 scaledLeather: 236,
19 wyvernHide: 237,
20 dragonhide: 238,
21 clothShorts: 239,
22 clothTrousers: 240,
23 leatherShoes: 241,
24 steelStud: 242,
25 tanningBrew: 243
26});
27
28const LEATHER_MATERIAL_ID = Object.freeze({
29 [LeatherTier.softLeather]: LeatherItemId.softLeather,
30 [LeatherTier.hardLeather]: LeatherItemId.hardLeather,
31 [LeatherTier.studdedLeather]: LeatherItemId.studdedLeather,
32 [LeatherTier.reinforcedLeather]: LeatherItemId.reinforcedLeather,
33 [LeatherTier.scaledLeather]: LeatherItemId.scaledLeather,
34 [LeatherTier.wyvernHide]: LeatherItemId.wyvernHide,
35 [LeatherTier.dragonhide]: LeatherItemId.dragonhide
36});
37
38function leatherMaterialDef (itemId, tier, key)
39{
40 const name = LEATHER_DISPLAY_NAME[tier] ?? tier;
41 return Object.freeze({
42 itemId,
43 key,
44 displayName: name,
45 description: tier === LeatherTier.softLeather
46 ? "Supple hide, warm from the field and ready for curing."
47 : `Cured ${name.toLowerCase()}, tough enough for straps and armour.`,
48 seedValue: tier === LeatherTier.softLeather ? 3 : 6,
49 stackable: true,
50 maxStackSize: 99,
51 uniqueInstance: false,
52 category: ItemCategory.ingredient,
53 iconKey: "leather",
54 defaultState: "leather",
55 tier,
56 tintFromTier: true
57 });
58}
59
60function buildLeatherMaterialDefinitions ()
61{
62 const defs = {};
63 for (const tier of LEATHER_TIER_ORDER)
64 {
65 const itemId = LEATHER_MATERIAL_ID[tier];
66 if (itemId == null)
67 { throw new Error(`Missing leather item id for ${tier}`); }
68 const key = tier === LeatherTier.softLeather ? "soft-leather" : tier.replace(/([A-Z])/g, "-$1").toLowerCase();
69 defs[itemId] = leatherMaterialDef(itemId, tier, key);
70 }
71 return defs;
72}
73
74const LEGWEAR_BASE = Object.freeze({
75 stackable: false,
76 maxStackSize: 1,
77 uniqueInstance: false,
78 category: ItemCategory.finished,
79 iconKey: "clothing",
80 dyeable: true,
81 tightFit: true,
82 clothing: Object.freeze({ style: true }),
83 equipment: Object.freeze({
84 slot: "legs",
85 kind: EquipmentKind.clothArmour,
86 bonus: 0,
87 minSkillLevel: 1,
88 tintFromTier: false
89 })
90});
91
92/** @type {Record<number, object>} */
93export const LEATHER_ITEM_DEFINITIONS = Object.freeze({
94 ...buildLeatherMaterialDefinitions(),
95 [LeatherItemId.clothShorts]: Object.freeze({
96 ...LEGWEAR_BASE,
97 itemId: LeatherItemId.clothShorts,
98 key: "cloth-shorts",
99 displayName: "Cloth shorts",
100 description: "Light cloth shorts cut for warm days on the road.",
101 seedValue: 4,
102 defaultState: "shorts",
103 equipment: Object.freeze({
104 ...LEGWEAR_BASE.equipment,
105 equipSprite: equipImageName("item", "clothing", "shorts")
106 })
107 }),
108 [LeatherItemId.clothTrousers]: Object.freeze({
109 ...LEGWEAR_BASE,
110 itemId: LeatherItemId.clothTrousers,
111 key: "cloth-trousers",
112 displayName: "Cloth trousers",
113 description: "Plain cloth trousers, sturdy enough for travel.",
114 seedValue: 5,
115 defaultState: "trousers",
116 equipment: Object.freeze({
117 ...LEGWEAR_BASE.equipment,
118 equipSprite: equipImageName("item", "clothing", "trousers")
119 })
120 }),
121 [LeatherItemId.leatherShoes]: Object.freeze({
122 itemId: LeatherItemId.leatherShoes,
123 key: "leather-shoes",
124 displayName: "Leather shoes",
125 description: "Simple soft-leather shoes, broken in from long walks.",
126 seedValue: 6,
127 stackable: false,
128 maxStackSize: 1,
129 uniqueInstance: false,
130 category: ItemCategory.finished,
131 iconKey: "clothing",
132 defaultState: "leather-shoes",
133 tier: LeatherTier.softLeather,
134 tintFromTier: true,
135 equipment: Object.freeze({
136 slot: "boots",
137 tier: LeatherTier.softLeather,
138 kind: EquipmentKind.leatherArmour,
139 bonus: 0,
140 minSkillLevel: tierMinSkillLevel(LeatherTier.softLeather),
141 tintFromTier: true,
142 equipSprite: equipImageName("item", "clothing", "leather-shoes")
143 })
144 }),
145 [LeatherItemId.steelStud]: Object.freeze({
146 itemId: LeatherItemId.steelStud,
147 key: "steel-stud",
148 displayName: "Steel stud",
149 description: "A small steel rivet for reinforcing leather.",
150 seedValue: 2,
151 stackable: true,
152 maxStackSize: 99,
153 uniqueInstance: false,
154 category: ItemCategory.intermediate,
155 iconKey: "metal",
156 defaultState: "stud"
157 }),
158 [LeatherItemId.tanningBrew]: Object.freeze({
159 itemId: LeatherItemId.tanningBrew,
160 key: "tanning-brew",
161 displayName: "Tanning brew",
162 description: "A sharp-smelling alchemy wash that cures hide into hard leather.",
163 seedValue: 8,
164 stackable: true,
165 maxStackSize: 99,
166 uniqueInstance: false,
167 category: ItemCategory.ingredient,
168 iconKey: "potion",
169 defaultState: "potion"
170 })
171});
172
173export function leatherMaterialItemId (tier)
174{
175 return LEATHER_MATERIAL_ID[tier] ?? null;
176}
shared/definitions/materialTiers.js +66 −4
@@ -73,6 +73,40 @@ export const CLOTH_TIER_ORDER = Object.freeze([
73 73 ClothTier.dragonweave
74 74 ]);
75 75
76 /**
77 * Leather tiers (leatherworking). Rank gates mirror cloth/metal families.
78 */
79 export const LeatherTier = Object.freeze({
80 softLeather: "softLeather",
81 hardLeather: "hardLeather",
82 studdedLeather: "studdedLeather",
83 reinforcedLeather: "reinforcedLeather",
84 scaledLeather: "scaledLeather",
85 wyvernHide: "wyvernHide",
86 dragonhide: "dragonhide"
87 });
88
89 /** Ordered low → high (leatherworking). */
90 export const LEATHER_TIER_ORDER = Object.freeze([
91 LeatherTier.softLeather,
92 LeatherTier.hardLeather,
93 LeatherTier.studdedLeather,
94 LeatherTier.reinforcedLeather,
95 LeatherTier.scaledLeather,
96 LeatherTier.wyvernHide,
97 LeatherTier.dragonhide
98 ]);
99
100 export const LEATHER_DISPLAY_NAME = Object.freeze({
101 [LeatherTier.softLeather]: "Soft leather",
102 [LeatherTier.hardLeather]: "Hard leather",
103 [LeatherTier.studdedLeather]: "Studded leather",
104 [LeatherTier.reinforcedLeather]: "Reinforced leather",
105 [LeatherTier.scaledLeather]: "Scaled leather",
106 [LeatherTier.wyvernHide]: "Wyvern hide",
107 [LeatherTier.dragonhide]: "Dragonhide"
108 });
109
76 110 /**
77 111 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
78 112 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
@@ -112,7 +146,14 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
112 146 [ClothTier.cashmere]: 35,
113 147 [ClothTier.silk]: 50,
114 148 [ClothTier.fairySilk]: 70,
115 [ClothTier.dragonweave]: 90
149 [ClothTier.dragonweave]: 90,
150 [LeatherTier.softLeather]: 1,
151 [LeatherTier.hardLeather]: 10,
152 [LeatherTier.studdedLeather]: 20,
153 [LeatherTier.reinforcedLeather]: 35,
154 [LeatherTier.scaledLeather]: 50,
155 [LeatherTier.wyvernHide]: 70,
156 [LeatherTier.dragonhide]: 90
116 157 });
117 158
118 159 /** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
@@ -139,7 +180,14 @@ export const TIER_RANK = Object.freeze({
139 180 [ClothTier.cashmere]: 4,
140 181 [ClothTier.silk]: 5,
141 182 [ClothTier.fairySilk]: 6,
142 [ClothTier.dragonweave]: 7
183 [ClothTier.dragonweave]: 7,
184 [LeatherTier.softLeather]: 1,
185 [LeatherTier.hardLeather]: 2,
186 [LeatherTier.studdedLeather]: 3,
187 [LeatherTier.reinforcedLeather]: 4,
188 [LeatherTier.scaledLeather]: 5,
189 [LeatherTier.wyvernHide]: 6,
190 [LeatherTier.dragonhide]: 7
143 191 });
144 192
145 193 /** Stat bonus granted by tier for the equipment's bonus category. */
@@ -164,7 +212,14 @@ export const TIER_STAT_BONUS = Object.freeze({
164 212 [ClothTier.cashmere]: 6,
165 213 [ClothTier.silk]: 8,
166 214 [ClothTier.fairySilk]: 10,
167 [ClothTier.dragonweave]: 12
215 [ClothTier.dragonweave]: 12,
216 [LeatherTier.softLeather]: 1,
217 [LeatherTier.hardLeather]: 2,
218 [LeatherTier.studdedLeather]: 4,
219 [LeatherTier.reinforcedLeather]: 6,
220 [LeatherTier.scaledLeather]: 8,
221 [LeatherTier.wyvernHide]: 10,
222 [LeatherTier.dragonhide]: 12
168 223 });
169 224
170 225 /** Display names for UI / editor. */
@@ -246,7 +301,14 @@ export const MATERIAL_TINT_HEX = Object.freeze({
246 301 [ClothTier.cashmere]: rgb(210, 175, 150),
247 302 [ClothTier.silk]: rgb(230, 220, 240),
248 303 [ClothTier.fairySilk]: rgb(180, 230, 255),
249 [ClothTier.dragonweave]: rgb(200, 60, 50)
304 [ClothTier.dragonweave]: rgb(200, 60, 50),
305 [LeatherTier.softLeather]: rgb(210, 180, 140),
306 [LeatherTier.hardLeather]: rgb(140, 90, 50),
307 [LeatherTier.studdedLeather]: rgb(110, 70, 40),
308 [LeatherTier.reinforcedLeather]: rgb(120, 100, 85),
309 [LeatherTier.scaledLeather]: rgb(150, 70, 55),
310 [LeatherTier.wyvernHide]: rgb(70, 85, 75),
311 [LeatherTier.dragonhide]: rgb(180, 40, 35)
250 312 });
251 313
252 314 /**
@@ -73,6 +73,40 @@ export const CLOTH_TIER_ORDER = Object.freeze([
73 ClothTier.dragonweave
73 ClothTier.dragonweave
74]);
74]);
75
75
76/**
77 * Leather tiers (leatherworking). Rank gates mirror cloth/metal families.
78 */
79export const LeatherTier = Object.freeze({
80 softLeather: "softLeather",
81 hardLeather: "hardLeather",
82 studdedLeather: "studdedLeather",
83 reinforcedLeather: "reinforcedLeather",
84 scaledLeather: "scaledLeather",
85 wyvernHide: "wyvernHide",
86 dragonhide: "dragonhide"
87});
88
89/** Ordered low → high (leatherworking). */
90export const LEATHER_TIER_ORDER = Object.freeze([
91 LeatherTier.softLeather,
92 LeatherTier.hardLeather,
93 LeatherTier.studdedLeather,
94 LeatherTier.reinforcedLeather,
95 LeatherTier.scaledLeather,
96 LeatherTier.wyvernHide,
97 LeatherTier.dragonhide
98]);
99
100export const LEATHER_DISPLAY_NAME = Object.freeze({
101 [LeatherTier.softLeather]: "Soft leather",
102 [LeatherTier.hardLeather]: "Hard leather",
103 [LeatherTier.studdedLeather]: "Studded leather",
104 [LeatherTier.reinforcedLeather]: "Reinforced leather",
105 [LeatherTier.scaledLeather]: "Scaled leather",
106 [LeatherTier.wyvernHide]: "Wyvern hide",
107 [LeatherTier.dragonhide]: "Dragonhide"
108});
109
76/**
110/**
77 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
111 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
78 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
112 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
@@ -112,7 +146,14 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
112 [ClothTier.cashmere]: 35,
146 [ClothTier.cashmere]: 35,
113 [ClothTier.silk]: 50,
147 [ClothTier.silk]: 50,
114 [ClothTier.fairySilk]: 70,
148 [ClothTier.fairySilk]: 70,
115 [ClothTier.dragonweave]: 90
149 [ClothTier.dragonweave]: 90,
150 [LeatherTier.softLeather]: 1,
151 [LeatherTier.hardLeather]: 10,
152 [LeatherTier.studdedLeather]: 20,
153 [LeatherTier.reinforcedLeather]: 35,
154 [LeatherTier.scaledLeather]: 50,
155 [LeatherTier.wyvernHide]: 70,
156 [LeatherTier.dragonhide]: 90
116});
157});
117
158
118/** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
159/** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
@@ -139,7 +180,14 @@ export const TIER_RANK = Object.freeze({
139 [ClothTier.cashmere]: 4,
180 [ClothTier.cashmere]: 4,
140 [ClothTier.silk]: 5,
181 [ClothTier.silk]: 5,
141 [ClothTier.fairySilk]: 6,
182 [ClothTier.fairySilk]: 6,
142 [ClothTier.dragonweave]: 7
183 [ClothTier.dragonweave]: 7,
184 [LeatherTier.softLeather]: 1,
185 [LeatherTier.hardLeather]: 2,
186 [LeatherTier.studdedLeather]: 3,
187 [LeatherTier.reinforcedLeather]: 4,
188 [LeatherTier.scaledLeather]: 5,
189 [LeatherTier.wyvernHide]: 6,
190 [LeatherTier.dragonhide]: 7
143});
191});
144
192
145/** Stat bonus granted by tier for the equipment's bonus category. */
193/** Stat bonus granted by tier for the equipment's bonus category. */
@@ -164,7 +212,14 @@ export const TIER_STAT_BONUS = Object.freeze({
164 [ClothTier.cashmere]: 6,
212 [ClothTier.cashmere]: 6,
165 [ClothTier.silk]: 8,
213 [ClothTier.silk]: 8,
166 [ClothTier.fairySilk]: 10,
214 [ClothTier.fairySilk]: 10,
167 [ClothTier.dragonweave]: 12
215 [ClothTier.dragonweave]: 12,
216 [LeatherTier.softLeather]: 1,
217 [LeatherTier.hardLeather]: 2,
218 [LeatherTier.studdedLeather]: 4,
219 [LeatherTier.reinforcedLeather]: 6,
220 [LeatherTier.scaledLeather]: 8,
221 [LeatherTier.wyvernHide]: 10,
222 [LeatherTier.dragonhide]: 12
168});
223});
169
224
170/** Display names for UI / editor. */
225/** Display names for UI / editor. */
@@ -246,7 +301,14 @@ export const MATERIAL_TINT_HEX = Object.freeze({
246 [ClothTier.cashmere]: rgb(210, 175, 150),
301 [ClothTier.cashmere]: rgb(210, 175, 150),
247 [ClothTier.silk]: rgb(230, 220, 240),
302 [ClothTier.silk]: rgb(230, 220, 240),
248 [ClothTier.fairySilk]: rgb(180, 230, 255),
303 [ClothTier.fairySilk]: rgb(180, 230, 255),
249 [ClothTier.dragonweave]: rgb(200, 60, 50)
304 [ClothTier.dragonweave]: rgb(200, 60, 50),
305 [LeatherTier.softLeather]: rgb(210, 180, 140),
306 [LeatherTier.hardLeather]: rgb(140, 90, 50),
307 [LeatherTier.studdedLeather]: rgb(110, 70, 40),
308 [LeatherTier.reinforcedLeather]: rgb(120, 100, 85),
309 [LeatherTier.scaledLeather]: rgb(150, 70, 55),
310 [LeatherTier.wyvernHide]: rgb(70, 85, 75),
311 [LeatherTier.dragonhide]: rgb(180, 40, 35)
250});
312});
251
313
252/**
314/**
shared/definitions/mobs.js +5 −1
@@ -1,5 +1,6 @@
1 1 import { spriteImageName } from "./tileSprites.js";
2 2 import { centralExchangeStaffCount } from "../market/exchange.js";
3 import { LeatherItemId } from "./leatherItems.js";
3 4 import { RangedItemId } from "./rangedItems.js";
4 5
5 6 export const MobId = Object.freeze({
@@ -36,7 +37,9 @@ export const MOB_DEFINITIONS = Object.freeze({
36 37 maxHealth: 8,
37 38 attackSkill: 2,
38 39 attackCooldownMs: 1000,
39 drops: Object.freeze([]),
40 drops: Object.freeze([
41 { itemId: LeatherItemId.softLeather, chance: 1 }
42 ]),
40 43 sells: Object.freeze([]),
41 44 dialogue: Object.freeze([]),
42 45 persistent: false,
@@ -99,6 +102,7 @@ export const MOB_DEFINITIONS = Object.freeze({
99 102 /** Auto-engage nearby players when in range with line of sight. */
100 103 aggressive: true,
101 104 aggroRangeTiles: 5,
105 elementAffinities: Object.freeze({ fire: "weak" }),
102 106 gait: "walk",
103 107 sex: "male",
104 108 frames: 1,
@@ -1,5 +1,6 @@
1import { spriteImageName } from "./tileSprites.js";
1import { spriteImageName } from "./tileSprites.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
3import { LeatherItemId } from "./leatherItems.js";
3import { RangedItemId } from "./rangedItems.js";
4import { RangedItemId } from "./rangedItems.js";
4
5
5export const MobId = Object.freeze({
6export const MobId = Object.freeze({
@@ -36,7 +37,9 @@ export const MOB_DEFINITIONS = Object.freeze({
36 maxHealth: 8,
37 maxHealth: 8,
37 attackSkill: 2,
38 attackSkill: 2,
38 attackCooldownMs: 1000,
39 attackCooldownMs: 1000,
39 drops: Object.freeze([]),
40 drops: Object.freeze([
41 { itemId: LeatherItemId.softLeather, chance: 1 }
42 ]),
40 sells: Object.freeze([]),
43 sells: Object.freeze([]),
41 dialogue: Object.freeze([]),
44 dialogue: Object.freeze([]),
42 persistent: false,
45 persistent: false,
@@ -99,6 +102,7 @@ export const MOB_DEFINITIONS = Object.freeze({
99 /** Auto-engage nearby players when in range with line of sight. */
102 /** Auto-engage nearby players when in range with line of sight. */
100 aggressive: true,
103 aggressive: true,
101 aggroRangeTiles: 5,
104 aggroRangeTiles: 5,
105 elementAffinities: Object.freeze({ fire: "weak" }),
102 gait: "walk",
106 gait: "walk",
103 sex: "male",
107 sex: "male",
104 frames: 1,
108 frames: 1,
shared/definitions/spellItems.js added +46 −0
@@ -0,0 +1,46 @@
1 import { ItemCategory } from "./itemCategories.js";
2 import { SpellId, spellDefinition } from "./spells.js";
3
4 export const SpellbookItemId = Object.freeze({
5 sparkSpellbook: 134
6 });
7
8 export function spellbookInstance (spellId)
9 {
10 const def = spellDefinition(spellId);
11 if (!def)
12 { return null; }
13 return Object.freeze({
14 kind: "spellbook",
15 spellId,
16 displayName: `${def.displayName} spellbook`
17 });
18 }
19
20 /** @type {Record<number, object>} */
21 export const SPELLBOOK_ITEM_DEFINITIONS = Object.freeze({
22 [SpellbookItemId.sparkSpellbook]: Object.freeze({
23 itemId: SpellbookItemId.sparkSpellbook,
24 key: "spellbook-spark",
25 displayName: "Spellbook: Spark",
26 description: "A charred pamphlet of sigils. Study it carefully to learn the Spark cantrip.",
27 seedValue: 40,
28 stackable: false,
29 maxStackSize: 1,
30 uniqueInstance: true,
31 category: ItemCategory.finished,
32 iconKey: "spellbook",
33 defaultState: "spark",
34 consumableSpellId: SpellId.spark
35 })
36 });
37
38 export function spellbookItemForSpell (spellId)
39 {
40 for (const def of Object.values(SPELLBOOK_ITEM_DEFINITIONS))
41 {
42 if (def.consumableSpellId === spellId)
43 { return def; }
44 }
45 return null;
46 }
@@ -0,0 +1,46 @@
1import { ItemCategory } from "./itemCategories.js";
2import { SpellId, spellDefinition } from "./spells.js";
3
4export const SpellbookItemId = Object.freeze({
5 sparkSpellbook: 134
6});
7
8export function spellbookInstance (spellId)
9{
10 const def = spellDefinition(spellId);
11 if (!def)
12 { return null; }
13 return Object.freeze({
14 kind: "spellbook",
15 spellId,
16 displayName: `${def.displayName} spellbook`
17 });
18}
19
20/** @type {Record<number, object>} */
21export const SPELLBOOK_ITEM_DEFINITIONS = Object.freeze({
22 [SpellbookItemId.sparkSpellbook]: Object.freeze({
23 itemId: SpellbookItemId.sparkSpellbook,
24 key: "spellbook-spark",
25 displayName: "Spellbook: Spark",
26 description: "A charred pamphlet of sigils. Study it carefully to learn the Spark cantrip.",
27 seedValue: 40,
28 stackable: false,
29 maxStackSize: 1,
30 uniqueInstance: true,
31 category: ItemCategory.finished,
32 iconKey: "spellbook",
33 defaultState: "spark",
34 consumableSpellId: SpellId.spark
35 })
36});
37
38export function spellbookItemForSpell (spellId)
39{
40 for (const def of Object.values(SPELLBOOK_ITEM_DEFINITIONS))
41 {
42 if (def.consumableSpellId === spellId)
43 { return def; }
44 }
45 return null;
46}
shared/definitions/spells.js +31 −12
@@ -1,32 +1,46 @@
1 import { spellDifficultyFromTier } from "../spells/constants.js";
2
1 3 /**
2 * Minimal spell content definitions. Gameplay wiring (casting UI, ECS) comes later.
3 *
4 4 * @typedef {object} SpellDefinition
5 5 * @property {string} spellId
6 6 * @property {string} displayName
7 * @property {number} difficulty Roll contest die size (1..difficulty) rolled against Magic
8 * @property {number} [mindBonus] Added to the Mind damage roll on a successful cast
7 * @property {number} tier Spell tier (sets difficulty and cast flash radius)
9 8 * @property {import("../combat/magic.js").SpellElement} [element]
10 * @property {string|null} [effectId] Non-damage spells apply this when cast succeeds
11 * @property {number} [rangeTiles]
12 * @property {number} [minMagicLevel]
9 * @property {"tile"|"entity"} target
10 * @property {boolean} [autoRepeat] Auto-cast repeats while target stays in range
11 * @property {number} [minMagicLevel] Minimum Magic level to cast / favourite
12 * @property {string} description In-world spell description
13 * @property {string} [projectileSprite] fx:projectile:spell-* base name
13 14 */
14 15
15 16 export const SpellId = Object.freeze({
17 light: "light",
16 18 spark: "spark"
17 19 });
18 20
19 21 /** @type {Record<string, SpellDefinition>} */
20 22 export const SPELL_DEFINITIONS = Object.freeze({
23 [SpellId.light]: Object.freeze({
24 spellId: SpellId.light,
25 displayName: "Light",
26 tier: 1,
27 element: "none",
28 target: "tile",
29 autoRepeat: false,
30 minMagicLevel: 1,
31 projectileSprite: "fx:projectile:spell-light",
32 description: "A whisper of radiance that settles on stone or grass, holding back the dark for a while."
33 }),
21 34 [SpellId.spark]: Object.freeze({
22 35 spellId: SpellId.spark,
23 36 displayName: "Spark",
24 difficulty: 4,
25 mindBonus: 2,
37 tier: 2,
26 38 element: "fire",
27 effectId: null,
28 rangeTiles: 4,
29 minMagicLevel: 1
39 target: "entity",
40 autoRepeat: true,
41 minMagicLevel: 2,
42 projectileSprite: "fx:projectile:spell-spark",
43 description: "A snapping mote of flame that leaps at a foe and bites on arrival."
30 44 })
31 45 });
32 46
@@ -34,3 +48,8 @@ export function spellDefinition (spellId)
34 48 {
35 49 return SPELL_DEFINITIONS[spellId] ?? null;
36 50 }
51
52 export function spellDifficulty (spellDef)
53 {
54 return spellDifficultyFromTier(spellDef?.tier ?? 1);
55 }
@@ -1,32 +1,46 @@
1import { spellDifficultyFromTier } from "../spells/constants.js";
2
1/**
3/**
2 * Minimal spell content definitions. Gameplay wiring (casting UI, ECS) comes later.
3 *
4 * @typedef {object} SpellDefinition
4 * @typedef {object} SpellDefinition
5 * @property {string} spellId
5 * @property {string} spellId
6 * @property {string} displayName
6 * @property {string} displayName
7 * @property {number} difficulty Roll contest die size (1..difficulty) rolled against Magic
7 * @property {number} tier Spell tier (sets difficulty and cast flash radius)
8 * @property {number} [mindBonus] Added to the Mind damage roll on a successful cast
9 * @property {import("../combat/magic.js").SpellElement} [element]
8 * @property {import("../combat/magic.js").SpellElement} [element]
10 * @property {string|null} [effectId] Non-damage spells apply this when cast succeeds
9 * @property {"tile"|"entity"} target
11 * @property {number} [rangeTiles]
10 * @property {boolean} [autoRepeat] Auto-cast repeats while target stays in range
12 * @property {number} [minMagicLevel]
11 * @property {number} [minMagicLevel] Minimum Magic level to cast / favourite
12 * @property {string} description In-world spell description
13 * @property {string} [projectileSprite] fx:projectile:spell-* base name
13 */
14 */
14
15
15export const SpellId = Object.freeze({
16export const SpellId = Object.freeze({
17 light: "light",
16 spark: "spark"
18 spark: "spark"
17});
19});
18
20
19/** @type {Record<string, SpellDefinition>} */
21/** @type {Record<string, SpellDefinition>} */
20export const SPELL_DEFINITIONS = Object.freeze({
22export const SPELL_DEFINITIONS = Object.freeze({
23 [SpellId.light]: Object.freeze({
24 spellId: SpellId.light,
25 displayName: "Light",
26 tier: 1,
27 element: "none",
28 target: "tile",
29 autoRepeat: false,
30 minMagicLevel: 1,
31 projectileSprite: "fx:projectile:spell-light",
32 description: "A whisper of radiance that settles on stone or grass, holding back the dark for a while."
33 }),
21 [SpellId.spark]: Object.freeze({
34 [SpellId.spark]: Object.freeze({
22 spellId: SpellId.spark,
35 spellId: SpellId.spark,
23 displayName: "Spark",
36 displayName: "Spark",
24 difficulty: 4,
37 tier: 2,
25 mindBonus: 2,
26 element: "fire",
38 element: "fire",
27 effectId: null,
39 target: "entity",
28 rangeTiles: 4,
40 autoRepeat: true,
29 minMagicLevel: 1
41 minMagicLevel: 2,
42 projectileSprite: "fx:projectile:spell-spark",
43 description: "A snapping mote of flame that leaps at a foe and bites on arrival."
30 })
44 })
31});
45});
32
46
@@ -34,3 +48,8 @@ export function spellDefinition (spellId)
34{
48{
35 return SPELL_DEFINITIONS[spellId] ?? null;
49 return SPELL_DEFINITIONS[spellId] ?? null;
36}
50}
51
52export function spellDifficulty (spellDef)
53{
54 return spellDifficultyFromTier(spellDef?.tier ?? 1);
55}
shared/definitions/tierFamilies.js +2 −1
@@ -12,6 +12,7 @@ import {
12 12 import { EquipmentKind } from "./equipmentKinds.js";
13 13 import { AttackType } from "./attackTypes.js";
14 14 import { SkillId } from "./skills.js";
15 import { COMBAT_RANGE_TILES } from "../spells/constants.js";
15 16
16 17 /** Which tier list drives a family (`wood` → pine…elder, `metal` → bronze…dragon). */
17 18 export const TierAxis = Object.freeze({
@@ -242,7 +243,7 @@ export const ITEM_FAMILIES = Object.freeze({
242 243 equipmentTintFromTier: true,
243 244 equipmentAttack: Object.freeze({
244 245 mode: "ranged",
245 rangeTiles: 8,
246 rangeTiles: COMBAT_RANGE_TILES,
246 247 hitSkillId: SkillId.archery,
247 248 damageSkillId: SkillId.dexterity,
248 249 attackType: AttackType.piercing,
@@ -12,6 +12,7 @@ import {
12import { EquipmentKind } from "./equipmentKinds.js";
12import { EquipmentKind } from "./equipmentKinds.js";
13import { AttackType } from "./attackTypes.js";
13import { AttackType } from "./attackTypes.js";
14import { SkillId } from "./skills.js";
14import { SkillId } from "./skills.js";
15import { COMBAT_RANGE_TILES } from "../spells/constants.js";
15
16
16/** Which tier list drives a family (`wood` → pine…elder, `metal` → bronze…dragon). */
17/** Which tier list drives a family (`wood` → pine…elder, `metal` → bronze…dragon). */
17export const TierAxis = Object.freeze({
18export const TierAxis = Object.freeze({
@@ -242,7 +243,7 @@ export const ITEM_FAMILIES = Object.freeze({
242 equipmentTintFromTier: true,
243 equipmentTintFromTier: true,
243 equipmentAttack: Object.freeze({
244 equipmentAttack: Object.freeze({
244 mode: "ranged",
245 mode: "ranged",
245 rangeTiles: 8,
246 rangeTiles: COMBAT_RANGE_TILES,
246 hitSkillId: SkillId.archery,
247 hitSkillId: SkillId.archery,
247 damageSkillId: SkillId.dexterity,
248 damageSkillId: SkillId.dexterity,
248 attackType: AttackType.piercing,
249 attackType: AttackType.piercing,
shared/definitions/tiles.js +39 −1
@@ -60,7 +60,8 @@ export const BlockType = Object.freeze({
60 60 ebonyTree: 25,
61 61 lignumTree: 26,
62 62 heartwoodTree: 27,
63 elderTree: 28
63 elderTree: 28,
64 leatherworkingTable: 29
64 65 });
65 66
66 67 export const GROUND_DEFINITIONS = Object.freeze({
@@ -300,6 +301,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
300 301 displayName: "Table",
301 302 passable: false,
302 303 blocksLight: false,
304 blocksRangedAttacks: false,
303 305 lightRangeTiles: 0,
304 306 frames: 1,
305 307 framesPerRow: 1,
@@ -378,6 +380,19 @@ export const BLOCK_DEFINITIONS = Object.freeze({
378 380 craftingStationId: "tailor-bench",
379 381 outdoor: false
380 382 }),
383 [BlockType.leatherworkingTable]: Object.freeze({
384 id: BlockType.leatherworkingTable,
385 key: "leatherworking-table",
386 displayName: "Leatherworking table",
387 passable: false,
388 blocksLight: false,
389 lightRangeTiles: 0,
390 frames: 1,
391 framesPerRow: 1,
392 animationSpeed: 0,
393 craftingStationId: "leatherworking-station",
394 outdoor: false
395 }),
381 396 [BlockType.bountyOffice]: Object.freeze({
382 397 id: BlockType.bountyOffice,
383 398 key: "bounty-office",
@@ -662,6 +677,27 @@ export function isBlockPassable (typeId)
662 677 return def ? def.passable : false;
663 678 }
664 679
680 /**
681 * Whether a block stops ranged attack / spell line of sight.
682 * `blocksRangedAttacks`: explicit override; `craftingStationId` defaults to clear;
683 * otherwise impassable blocks block and passable blocks do not.
684 */
685 export function blockBlocksRangedAttacks (typeId)
686 {
687 if (typeId == null)
688 { return false; }
689 const def = blockDefinition(typeId);
690 if (!def)
691 { return true; }
692 if (def.blocksRangedAttacks === false)
693 { return false; }
694 if (def.blocksRangedAttacks === true)
695 { return true; }
696 if (def.craftingStationId)
697 { return false; }
698 return def.passable === false;
699 }
700
665 701 /**
666 702 * Light ray occlusion for a block tile.
667 703 * - `clear` (0): no effect (default for passable; set `blocksLight: false` for furniture)
@@ -690,6 +726,8 @@ export function blockLightOcclusionForBlock (block)
690 726 /**
691 727 * Resolve light occlusion for a block type id.
692 728 * `blocksLight`: `true` | `false` | `"partial"`; omitted → solid iff `!passable`.
729 * `blocksRangedAttacks`: `true` | `false`; omitted → false when `craftingStationId` is set,
730 * otherwise blocks iff `!passable` (furniture/stations may block movement but not magic/ranged).
693 731 * Prefer {@link blockLightOcclusionForBlock} when block state is known.
694 732 */
695 733 export function blockLightOcclusion (typeId)
@@ -60,7 +60,8 @@ export const BlockType = Object.freeze({
60 ebonyTree: 25,
60 ebonyTree: 25,
61 lignumTree: 26,
61 lignumTree: 26,
62 heartwoodTree: 27,
62 heartwoodTree: 27,
63 elderTree: 28
63 elderTree: 28,
64 leatherworkingTable: 29
64});
65});
65
66
66export const GROUND_DEFINITIONS = Object.freeze({
67export const GROUND_DEFINITIONS = Object.freeze({
@@ -300,6 +301,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
300 displayName: "Table",
301 displayName: "Table",
301 passable: false,
302 passable: false,
302 blocksLight: false,
303 blocksLight: false,
304 blocksRangedAttacks: false,
303 lightRangeTiles: 0,
305 lightRangeTiles: 0,
304 frames: 1,
306 frames: 1,
305 framesPerRow: 1,
307 framesPerRow: 1,
@@ -378,6 +380,19 @@ export const BLOCK_DEFINITIONS = Object.freeze({
378 craftingStationId: "tailor-bench",
380 craftingStationId: "tailor-bench",
379 outdoor: false
381 outdoor: false
380 }),
382 }),
383 [BlockType.leatherworkingTable]: Object.freeze({
384 id: BlockType.leatherworkingTable,
385 key: "leatherworking-table",
386 displayName: "Leatherworking table",
387 passable: false,
388 blocksLight: false,
389 lightRangeTiles: 0,
390 frames: 1,
391 framesPerRow: 1,
392 animationSpeed: 0,
393 craftingStationId: "leatherworking-station",
394 outdoor: false
395 }),
381 [BlockType.bountyOffice]: Object.freeze({
396 [BlockType.bountyOffice]: Object.freeze({
382 id: BlockType.bountyOffice,
397 id: BlockType.bountyOffice,
383 key: "bounty-office",
398 key: "bounty-office",
@@ -662,6 +677,27 @@ export function isBlockPassable (typeId)
662 return def ? def.passable : false;
677 return def ? def.passable : false;
663}
678}
664
679
680/**
681 * Whether a block stops ranged attack / spell line of sight.
682 * `blocksRangedAttacks`: explicit override; `craftingStationId` defaults to clear;
683 * otherwise impassable blocks block and passable blocks do not.
684 */
685export function blockBlocksRangedAttacks (typeId)
686{
687 if (typeId == null)
688 { return false; }
689 const def = blockDefinition(typeId);
690 if (!def)
691 { return true; }
692 if (def.blocksRangedAttacks === false)
693 { return false; }
694 if (def.blocksRangedAttacks === true)
695 { return true; }
696 if (def.craftingStationId)
697 { return false; }
698 return def.passable === false;
699}
700
665/**
701/**
666 * Light ray occlusion for a block tile.
702 * Light ray occlusion for a block tile.
667 * - `clear` (0): no effect (default for passable; set `blocksLight: false` for furniture)
703 * - `clear` (0): no effect (default for passable; set `blocksLight: false` for furniture)
@@ -690,6 +726,8 @@ export function blockLightOcclusionForBlock (block)
690/**
726/**
691 * Resolve light occlusion for a block type id.
727 * Resolve light occlusion for a block type id.
692 * `blocksLight`: `true` | `false` | `"partial"`; omitted → solid iff `!passable`.
728 * `blocksLight`: `true` | `false` | `"partial"`; omitted → solid iff `!passable`.
729 * `blocksRangedAttacks`: `true` | `false`; omitted → false when `craftingStationId` is set,
730 * otherwise blocks iff `!passable` (furniture/stations may block movement but not magic/ranged).
693 * Prefer {@link blockLightOcclusionForBlock} when block state is known.
731 * Prefer {@link blockLightOcclusionForBlock} when block state is known.
694 */
732 */
695export function blockLightOcclusion (typeId)
733export function blockLightOcclusion (typeId)
shared/protocol/constants.js +17 −0
@@ -207,6 +207,23 @@ export const MessageType = Object.freeze({
207 207 cancelMarketOrder: "CANCEL_MARKET_ORDER",
208 208 marketTrade: "MARKET_TRADE",
209 209 skillLevelUp: "SKILL_LEVEL_UP",
210 spells: "spells",
211 setSpellFavorite: "SET_SPELL_FAVORITE",
212 setSpellAutoCast: "SET_SPELL_AUTOCAST",
213 armSpell: "ARM_SPELL",
214 cancelArmSpell: "CANCEL_ARM_SPELL",
215 castSpellTile: "CAST_SPELL_TILE",
216 castSpellEntity: "CAST_SPELL_ENTITY",
217 readSpellbook: "READ_SPELLBOOK",
218 spellsUpdated: "SPELLS_UPDATED",
219 spellArmed: "SPELL_ARMED",
220 spellDisarmed: "SPELL_DISARMED",
221 spellProjectile: "SPELL_PROJECTILE",
222 spellFizzle: "SPELL_FIZZLE",
223 spellCastFlash: "SPELL_CAST_FLASH",
224 spellLightAppear: "SPELL_LIGHT_APPEAR",
225 spellLightUpdate: "SPELL_LIGHT_UPDATE",
226 spellLightRemove: "SPELL_LIGHT_REMOVE",
210 227 toast: "TOAST"
211 228 });
212 229
@@ -207,6 +207,23 @@ export const MessageType = Object.freeze({
207 cancelMarketOrder: "CANCEL_MARKET_ORDER",
207 cancelMarketOrder: "CANCEL_MARKET_ORDER",
208 marketTrade: "MARKET_TRADE",
208 marketTrade: "MARKET_TRADE",
209 skillLevelUp: "SKILL_LEVEL_UP",
209 skillLevelUp: "SKILL_LEVEL_UP",
210 spells: "spells",
211 setSpellFavorite: "SET_SPELL_FAVORITE",
212 setSpellAutoCast: "SET_SPELL_AUTOCAST",
213 armSpell: "ARM_SPELL",
214 cancelArmSpell: "CANCEL_ARM_SPELL",
215 castSpellTile: "CAST_SPELL_TILE",
216 castSpellEntity: "CAST_SPELL_ENTITY",
217 readSpellbook: "READ_SPELLBOOK",
218 spellsUpdated: "SPELLS_UPDATED",
219 spellArmed: "SPELL_ARMED",
220 spellDisarmed: "SPELL_DISARMED",
221 spellProjectile: "SPELL_PROJECTILE",
222 spellFizzle: "SPELL_FIZZLE",
223 spellCastFlash: "SPELL_CAST_FLASH",
224 spellLightAppear: "SPELL_LIGHT_APPEAR",
225 spellLightUpdate: "SPELL_LIGHT_UPDATE",
226 spellLightRemove: "SPELL_LIGHT_REMOVE",
210 toast: "TOAST"
227 toast: "TOAST"
211});
228});
212
229
shared/skills/progression.js +7 −3
@@ -1,8 +1,8 @@
1 1 export const MAX_SKILL_LEVEL = 99;
2 2
3 /** XP needed to advance from level L to L+1 (doubles each level). */
3 /** XP needed to advance from level L to L+1 (+10% per level). */
4 4 export const SKILL_XP_BASE = 50;
5 export const SKILL_XP_GROWTH = 2;
5 export const SKILL_XP_GROWTH = 1.1;
6 6
7 7 export function xpToAdvanceFromLevel (level)
8 8 {
@@ -25,7 +25,11 @@ export function totalXpForLevel (level)
25 25 /** Total XP while still at max level (extra XP is discarded). */
26 26 export function maxTotalSkillXp ()
27 27 {
28 return totalXpForLevel(MAX_SKILL_LEVEL + 1) - 1;
28 const lastAdvance = Math.max(
29 1,
30 Math.floor(SKILL_XP_BASE * (SKILL_XP_GROWTH ** (MAX_SKILL_LEVEL - 1)))
31 );
32 return totalXpForLevel(MAX_SKILL_LEVEL) + lastAdvance - 1;
29 33 }
30 34
31 35 /** Derive level and in-level progress from lifetime XP. */
@@ -1,8 +1,8 @@
1export const MAX_SKILL_LEVEL = 99;
1export const MAX_SKILL_LEVEL = 99;
2
2
3/** XP needed to advance from level L to L+1 (doubles each level). */
3/** XP needed to advance from level L to L+1 (+10% per level). */
4export const SKILL_XP_BASE = 50;
4export const SKILL_XP_BASE = 50;
5export const SKILL_XP_GROWTH = 2;
5export const SKILL_XP_GROWTH = 1.1;
6
6
7export function xpToAdvanceFromLevel (level)
7export function xpToAdvanceFromLevel (level)
8{
8{
@@ -25,7 +25,11 @@ export function totalXpForLevel (level)
25/** Total XP while still at max level (extra XP is discarded). */
25/** Total XP while still at max level (extra XP is discarded). */
26export function maxTotalSkillXp ()
26export function maxTotalSkillXp ()
27{
27{
28 return totalXpForLevel(MAX_SKILL_LEVEL + 1) - 1;
28 const lastAdvance = Math.max(
29 1,
30 Math.floor(SKILL_XP_BASE * (SKILL_XP_GROWTH ** (MAX_SKILL_LEVEL - 1)))
31 );
32 return totalXpForLevel(MAX_SKILL_LEVEL) + lastAdvance - 1;
29}
33}
30
34
31/** Derive level and in-level progress from lifetime XP. */
35/** Derive level and in-level progress from lifetime XP. */
shared/spells/constants.js added +31 −0
@@ -0,0 +1,31 @@
1 /** Universal Chebyshev range for ranged weapons and magic (players and mobs). */
2 export const COMBAT_RANGE_TILES = 15;
3
4 export const RANGED_PROJECTILE_MS = 1000;
5 export const SPELL_PROJECTILE_MS = 2000;
6 export const SPELL_COOLDOWN_MS = 2000;
7 export const MAX_FAVORITE_SPELLS = 6;
8
9 /** Torch blocks use 8 tiles; spell lights are slightly dimmer. */
10 export const SPELL_LIGHT_RANGE_TILES = 6;
11 export const SPELL_LIGHT_INTENSITY = 0.88;
12
13 export const LIGHT_DURATION_MS_PER_MIND = 5000;
14 export const LIGHT_MAX_DURATION_MS = 3 * 60 * 1000;
15 export const LIGHT_FADE_MS = 3000;
16 export const LIGHT_OWNER_DISTANCE_CAP_MS = 5000;
17
18 export const CAST_FLASH_MS = 500;
19 export const SPELL_PROJECTILE_FRAME_MS = 250;
20
21 /** Magic contest die size from spell tier (tier 1 → 2, tier 2 → 4, …). */
22 export function spellDifficultyFromTier (tier)
23 {
24 return Math.max(1, Math.floor(Number(tier) || 1) * 2);
25 }
26
27 /** Cast flash radius in tiles = tier / 2. */
28 export function castFlashRadiusTiles (tier)
29 {
30 return Math.max(0.5, (Number(tier) || 1) / 2);
31 }
@@ -0,0 +1,31 @@
1/** Universal Chebyshev range for ranged weapons and magic (players and mobs). */
2export const COMBAT_RANGE_TILES = 15;
3
4export const RANGED_PROJECTILE_MS = 1000;
5export const SPELL_PROJECTILE_MS = 2000;
6export const SPELL_COOLDOWN_MS = 2000;
7export const MAX_FAVORITE_SPELLS = 6;
8
9/** Torch blocks use 8 tiles; spell lights are slightly dimmer. */
10export const SPELL_LIGHT_RANGE_TILES = 6;
11export const SPELL_LIGHT_INTENSITY = 0.88;
12
13export const LIGHT_DURATION_MS_PER_MIND = 5000;
14export const LIGHT_MAX_DURATION_MS = 3 * 60 * 1000;
15export const LIGHT_FADE_MS = 3000;
16export const LIGHT_OWNER_DISTANCE_CAP_MS = 5000;
17
18export const CAST_FLASH_MS = 500;
19export const SPELL_PROJECTILE_FRAME_MS = 250;
20
21/** Magic contest die size from spell tier (tier 1 → 2, tier 2 → 4, …). */
22export function spellDifficultyFromTier (tier)
23{
24 return Math.max(1, Math.floor(Number(tier) || 1) * 2);
25}
26
27/** Cast flash radius in tiles = tier / 2. */
28export function castFlashRadiusTiles (tier)
29{
30 return Math.max(0.5, (Number(tier) || 1) / 2);
31}
shared/spells/state.js added +153 −0
@@ -0,0 +1,153 @@
1 import { SpellId, spellDefinition } from "../definitions/spells.js";
2 import { MAX_FAVORITE_SPELLS } from "./constants.js";
3 import { skillLevel } from "../definitions/skills.js";
4 import { SkillId } from "../definitions/skills.js";
5
6 export const DEFAULT_KNOWN_SPELLS = Object.freeze([SpellId.light]);
7
8 export function defaultPlayerSpells ()
9 {
10 return {
11 known: [...DEFAULT_KNOWN_SPELLS],
12 favorites: [],
13 autoCast: false
14 };
15 }
16
17 export function normalizeKnownSpells (raw)
18 {
19 const known = new Set(DEFAULT_KNOWN_SPELLS);
20 if (Array.isArray(raw))
21 {
22 for (const id of raw)
23 {
24 if (spellDefinition(id))
25 { known.add(id); }
26 }
27 }
28 else if (raw && typeof raw === "object" && Array.isArray(raw.known))
29 {
30 for (const id of raw.known)
31 {
32 if (spellDefinition(id))
33 { known.add(id); }
34 }
35 }
36 return [...known];
37 }
38
39 export function normalizeFavoriteSpells (raw, known)
40 {
41 const knownSet = new Set(known);
42 const favorites = [];
43 const source = Array.isArray(raw) ? raw : (raw?.favorites ?? []);
44 for (const id of source)
45 {
46 if (!knownSet.has(id) || !spellDefinition(id))
47 { continue; }
48 if (favorites.includes(id))
49 { continue; }
50 favorites.push(id);
51 if (favorites.length >= MAX_FAVORITE_SPELLS)
52 { break; }
53 }
54 return favorites;
55 }
56
57 export function normalizePlayerSpells (stored)
58 {
59 const known = normalizeKnownSpells(stored);
60 return {
61 known,
62 favorites: normalizeFavoriteSpells(stored, known),
63 autoCast: !!(stored && typeof stored === "object" && stored.autoCast)
64 };
65 }
66
67 export function storedPlayerSpells (component)
68 {
69 const normalized = normalizePlayerSpells(component);
70 return {
71 known: normalized.known,
72 favorites: normalized.favorites,
73 autoCast: normalized.autoCast
74 };
75 }
76
77 export function playerKnowsSpell (spells, spellId)
78 {
79 return normalizeKnownSpells(spells).includes(spellId);
80 }
81
82 export function canCastSpell (skills, spells, spellId)
83 {
84 const def = spellDefinition(spellId);
85 if (!def || !playerKnowsSpell(spells, spellId))
86 { return { ok: false, reason: "You do not know that spell." }; }
87 const magicLevel = skillLevel(skills, SkillId.magic);
88 const need = def.minMagicLevel ?? def.tier ?? 1;
89 if (magicLevel < need)
90 {
91 return { ok: false, reason: `Requires Magic level ${need}.` };
92 }
93 return { ok: true };
94 }
95
96 export function canFavoriteSpell (skills, spells, spellId)
97 {
98 return canCastSpell(skills, spells, spellId).ok;
99 }
100
101 export function learnSpell (spells, spellId)
102 {
103 const normalized = normalizePlayerSpells(spells);
104 if (!spellDefinition(spellId))
105 { return { changed: false, spells: normalized }; }
106 if (normalized.known.includes(spellId))
107 { return { changed: false, spells: normalized }; }
108 normalized.known.push(spellId);
109 return { changed: true, spells: normalized };
110 }
111
112 export function toggleFavorite (spells, spellId, skills)
113 {
114 const normalized = normalizePlayerSpells(spells);
115 if (!normalized.known.includes(spellId))
116 { return { changed: false, spells: normalized, error: "Unknown spell." }; }
117 if (!canFavoriteSpell(skills, normalized, spellId))
118 { return { changed: false, spells: normalized, error: "Magic level too low to favourite this spell." }; }
119 const idx = normalized.favorites.indexOf(spellId);
120 if (idx >= 0)
121 {
122 normalized.favorites.splice(idx, 1);
123 return { changed: true, spells: normalized };
124 }
125 if (normalized.favorites.length >= MAX_FAVORITE_SPELLS)
126 {
127 return { changed: false, spells: normalized, error: "You can only favourite six spells." };
128 }
129 normalized.favorites.push(spellId);
130 return { changed: true, spells: normalized };
131 }
132
133 export function publicSpellsView (spells, skills)
134 {
135 const normalized = normalizePlayerSpells(spells);
136 return normalized.known.map((spellId) =>
137 {
138 const def = spellDefinition(spellId);
139 const cast = canCastSpell(skills, normalized, spellId);
140 return {
141 spellId,
142 displayName: def?.displayName ?? spellId,
143 tier: def?.tier ?? 1,
144 description: def?.description ?? "",
145 target: def?.target ?? "tile",
146 autoRepeat: !!def?.autoRepeat,
147 icon: `/assets/spells/${spellId}.svg`,
148 canCast: cast.ok,
149 canFavorite: cast.ok,
150 favorite: normalized.favorites.includes(spellId)
151 };
152 });
153 }
@@ -0,0 +1,153 @@
1import { SpellId, spellDefinition } from "../definitions/spells.js";
2import { MAX_FAVORITE_SPELLS } from "./constants.js";
3import { skillLevel } from "../definitions/skills.js";
4import { SkillId } from "../definitions/skills.js";
5
6export const DEFAULT_KNOWN_SPELLS = Object.freeze([SpellId.light]);
7
8export function defaultPlayerSpells ()
9{
10 return {
11 known: [...DEFAULT_KNOWN_SPELLS],
12 favorites: [],
13 autoCast: false
14 };
15}
16
17export function normalizeKnownSpells (raw)
18{
19 const known = new Set(DEFAULT_KNOWN_SPELLS);
20 if (Array.isArray(raw))
21 {
22 for (const id of raw)
23 {
24 if (spellDefinition(id))
25 { known.add(id); }
26 }
27 }
28 else if (raw && typeof raw === "object" && Array.isArray(raw.known))
29 {
30 for (const id of raw.known)
31 {
32 if (spellDefinition(id))
33 { known.add(id); }
34 }
35 }
36 return [...known];
37}
38
39export function normalizeFavoriteSpells (raw, known)
40{
41 const knownSet = new Set(known);
42 const favorites = [];
43 const source = Array.isArray(raw) ? raw : (raw?.favorites ?? []);
44 for (const id of source)
45 {
46 if (!knownSet.has(id) || !spellDefinition(id))
47 { continue; }
48 if (favorites.includes(id))
49 { continue; }
50 favorites.push(id);
51 if (favorites.length >= MAX_FAVORITE_SPELLS)
52 { break; }
53 }
54 return favorites;
55}
56
57export function normalizePlayerSpells (stored)
58{
59 const known = normalizeKnownSpells(stored);
60 return {
61 known,
62 favorites: normalizeFavoriteSpells(stored, known),
63 autoCast: !!(stored && typeof stored === "object" && stored.autoCast)
64 };
65}
66
67export function storedPlayerSpells (component)
68{
69 const normalized = normalizePlayerSpells(component);
70 return {
71 known: normalized.known,
72 favorites: normalized.favorites,
73 autoCast: normalized.autoCast
74 };
75}
76
77export function playerKnowsSpell (spells, spellId)
78{
79 return normalizeKnownSpells(spells).includes(spellId);
80}
81
82export function canCastSpell (skills, spells, spellId)
83{
84 const def = spellDefinition(spellId);
85 if (!def || !playerKnowsSpell(spells, spellId))
86 { return { ok: false, reason: "You do not know that spell." }; }
87 const magicLevel = skillLevel(skills, SkillId.magic);
88 const need = def.minMagicLevel ?? def.tier ?? 1;
89 if (magicLevel < need)
90 {
91 return { ok: false, reason: `Requires Magic level ${need}.` };
92 }
93 return { ok: true };
94}
95
96export function canFavoriteSpell (skills, spells, spellId)
97{
98 return canCastSpell(skills, spells, spellId).ok;
99}
100
101export function learnSpell (spells, spellId)
102{
103 const normalized = normalizePlayerSpells(spells);
104 if (!spellDefinition(spellId))
105 { return { changed: false, spells: normalized }; }
106 if (normalized.known.includes(spellId))
107 { return { changed: false, spells: normalized }; }
108 normalized.known.push(spellId);
109 return { changed: true, spells: normalized };
110}
111
112export function toggleFavorite (spells, spellId, skills)
113{
114 const normalized = normalizePlayerSpells(spells);
115 if (!normalized.known.includes(spellId))
116 { return { changed: false, spells: normalized, error: "Unknown spell." }; }
117 if (!canFavoriteSpell(skills, normalized, spellId))
118 { return { changed: false, spells: normalized, error: "Magic level too low to favourite this spell." }; }
119 const idx = normalized.favorites.indexOf(spellId);
120 if (idx >= 0)
121 {
122 normalized.favorites.splice(idx, 1);
123 return { changed: true, spells: normalized };
124 }
125 if (normalized.favorites.length >= MAX_FAVORITE_SPELLS)
126 {
127 return { changed: false, spells: normalized, error: "You can only favourite six spells." };
128 }
129 normalized.favorites.push(spellId);
130 return { changed: true, spells: normalized };
131}
132
133export function publicSpellsView (spells, skills)
134{
135 const normalized = normalizePlayerSpells(spells);
136 return normalized.known.map((spellId) =>
137 {
138 const def = spellDefinition(spellId);
139 const cast = canCastSpell(skills, normalized, spellId);
140 return {
141 spellId,
142 displayName: def?.displayName ?? spellId,
143 tier: def?.tier ?? 1,
144 description: def?.description ?? "",
145 target: def?.target ?? "tile",
146 autoRepeat: !!def?.autoRepeat,
147 icon: `/assets/spells/${spellId}.svg`,
148 canCast: cast.ok,
149 canFavorite: cast.ok,
150 favorite: normalized.favorites.includes(spellId)
151 };
152 });
153}
shared/statusEffects/rules.js +3 −3
@@ -29,7 +29,7 @@ export function pruneStatusEffects (component, now)
29 29 {
30 30 if (!component?.effects)
31 31 { return component; }
32 component.effects = component.effects.filter((entry) => (entry.expiresAt | 0) > now);
32 component.effects = component.effects.filter((entry) => Number(entry.expiresAt) > now);
33 33 return component;
34 34 }
35 35
@@ -56,7 +56,7 @@ export function applyStatusEffect (component, effect, now = Date.now())
56 56 const existing = component.effects.find((entry) => entry.type === type);
57 57 if (existing && EXTEND_TYPES.has(type) && durationMs > 0)
58 58 {
59 existing.expiresAt = Math.max(existing.expiresAt | 0, now) + durationMs;
59 existing.expiresAt = Math.max(Number(existing.expiresAt) || 0, now) + durationMs;
60 60 if (effect.amountPerSecond != null)
61 61 { existing.amountPerSecond = Number(effect.amountPerSecond) || existing.amountPerSecond; }
62 62 if (effect.amount != null)
@@ -128,7 +128,7 @@ export function publicStatusEffectsView (component, now = Date.now())
128 128 {
129 129 return activeStatusEffects(component, now).map((entry) => ({
130 130 type: entry.type,
131 expiresAt: entry.expiresAt | 0,
131 expiresAt: Number(entry.expiresAt) || 0,
132 132 amount: entry.amount | 0,
133 133 amountPerSecond: Number(entry.amountPerSecond) || 0,
134 134 lightRadiusTiles: entry.lightRadiusTiles,
@@ -29,7 +29,7 @@ export function pruneStatusEffects (component, now)
29{
29{
30 if (!component?.effects)
30 if (!component?.effects)
31 { return component; }
31 { return component; }
32 component.effects = component.effects.filter((entry) => (entry.expiresAt | 0) > now);
32 component.effects = component.effects.filter((entry) => Number(entry.expiresAt) > now);
33 return component;
33 return component;
34}
34}
35
35
@@ -56,7 +56,7 @@ export function applyStatusEffect (component, effect, now = Date.now())
56 const existing = component.effects.find((entry) => entry.type === type);
56 const existing = component.effects.find((entry) => entry.type === type);
57 if (existing && EXTEND_TYPES.has(type) && durationMs > 0)
57 if (existing && EXTEND_TYPES.has(type) && durationMs > 0)
58 {
58 {
59 existing.expiresAt = Math.max(existing.expiresAt | 0, now) + durationMs;
59 existing.expiresAt = Math.max(Number(existing.expiresAt) || 0, now) + durationMs;
60 if (effect.amountPerSecond != null)
60 if (effect.amountPerSecond != null)
61 { existing.amountPerSecond = Number(effect.amountPerSecond) || existing.amountPerSecond; }
61 { existing.amountPerSecond = Number(effect.amountPerSecond) || existing.amountPerSecond; }
62 if (effect.amount != null)
62 if (effect.amount != null)
@@ -128,7 +128,7 @@ export function publicStatusEffectsView (component, now = Date.now())
128{
128{
129 return activeStatusEffects(component, now).map((entry) => ({
129 return activeStatusEffects(component, now).map((entry) => ({
130 type: entry.type,
130 type: entry.type,
131 expiresAt: entry.expiresAt | 0,
131 expiresAt: Number(entry.expiresAt) || 0,
132 amount: entry.amount | 0,
132 amount: entry.amount | 0,
133 amountPerSecond: Number(entry.amountPerSecond) || 0,
133 amountPerSecond: Number(entry.amountPerSecond) || 0,
134 lightRadiusTiles: entry.lightRadiusTiles,
134 lightRadiusTiles: entry.lightRadiusTiles,