BlueGit

timfa questward

Add herbalism, barber/bounty, status effects, graphics prefs, and starter loadouts.

Ship the next play loop slice: folklore herbs and potions, hair/barber and bounty offices, HUD vitals/effects, viewport culling with client graphics settings, create-character modal with auto-enter, and admin-configurable starter gear for new characters only.

timfa Tim Falken · pushed by timfa

Authored 2026-08-26 · 2 months ago

Hash
46df1261a934fa5fa947d61ef6cdc77a1c4ae956
Parent
7860dd98
107 files changed +5685 −267
client/assets/blocks/barber/barber.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/bounty-office/bounty-office.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-female/hair-1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-female/hair-2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-female/hair-3.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-male/hair-1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-male/hair-2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-male/hair-3.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-male/hair-4.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/aconite.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/belladonna.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/chamomile.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/datura.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/elder.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/foxglove.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/garlic.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/hawthorn.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/henbane.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/juniper.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/lavender.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/mandrake.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/mint.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/mistletoe.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/mugwort.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/nettle.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/rosemary.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/rue.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/sage.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/st-johns-wort.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/thyme.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/valerian.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/wormwood.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/herbs/yarrow.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/green-herb/green-herb.png deleted Binary file +0 −0

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

client/assets/items/red-beet/red-beet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/blind.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/glow.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/health-regen.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/mind-bonus.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/shrink.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/stamina-drain.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/stamina-regen.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/status-effects/strength-bonus.png added Binary file +0 −0

The contents of this binary file are not shown.

client/index.html +114 −11
@@ -15,6 +15,34 @@
15 15 <button id="bag-toggle" type="button">Bag</button>
16 16 <button id="leave" type="button">Leave world</button>
17 17 </div>
18 <button id="settings-toggle" type="button" hidden title="Settings" aria-label="Settings">⚙</button>
19 <aside id="settings-panel" hidden>
20 <header>
21 <h2>Settings</h2>
22 <button id="settings-close" type="button">Close</button>
23 </header>
24 <section class="settings-group">
25 <h3>Viewing distance</h3>
26 <div class="settings-options">
27 <button type="button" data-graphics-key="viewDistance" data-graphics-value="long">Long</button>
28 <button type="button" data-graphics-key="viewDistance" data-graphics-value="short">Short</button>
29 </div>
30 </section>
31 <section class="settings-group">
32 <h3>Lighting</h3>
33 <div class="settings-options">
34 <button type="button" data-graphics-key="lighting" data-graphics-value="soft">Soft</button>
35 <button type="button" data-graphics-key="lighting" data-graphics-value="simple">Simple</button>
36 </div>
37 </section>
38 <section class="settings-group">
39 <h3>Bloom</h3>
40 <div class="settings-options">
41 <button type="button" data-graphics-key="bloom" data-graphics-value="on">On</button>
42 <button type="button" data-graphics-key="bloom" data-graphics-value="off">Off</button>
43 </div>
44 </section>
45 </aside>
18 46 <div id="toast-stack" aria-live="polite"></div>
19 47 <div id="world-tooltip" hidden></div>
20 48 <aside id="bag-panel" hidden>
@@ -338,6 +366,61 @@
338 366 </section>
339 367 </aside>
340 368
369 <div id="bounty-backdrop" class="modal-backdrop" hidden></div>
370 <aside id="bounty-panel" hidden>
371 <header>
372 <h2>Bounty Office</h2>
373 <button id="bounty-close" type="button">Close</button>
374 </header>
375 <div class="bounty-tabs" role="tablist">
376 <button type="button" class="bounty-tab active" data-tab="place" role="tab">Place / raise</button>
377 <button type="button" class="bounty-tab" data-tab="mine" role="tab">My bounty</button>
378 </div>
379 <section class="bounty-pane" data-pane="place">
380 <div class="bounty-search-row">
381 <label>First <input id="bounty-search-first" autocomplete="off" spellcheck="false"></label>
382 <label>Last <input id="bounty-search-last" autocomplete="off" spellcheck="false"></label>
383 <button id="bounty-search" type="button">Search</button>
384 </div>
385 <div class="bounty-target">
386 <div id="bounty-preview"></div>
387 <div>
388 <p id="bounty-target-label">No target selected.</p>
389 <p id="bounty-target-amount" class="hint"></p>
390 </div>
391 </div>
392 <label class="bounty-amount-label">Coins to add
393 <input id="bounty-amount" type="number" min="1" step="1" value="100">
394 </label>
395 <button id="bounty-raise" type="button">Add to bounty</button>
396 <p id="bounty-status" class="hint"></p>
397 </section>
398 <section class="bounty-pane" data-pane="mine" hidden>
399 <p class="hint">Coin currently on your head:</p>
400 <p id="bounty-my-amount" class="bounty-my-amount">None</p>
401 </section>
402 </aside>
403
404 <div id="barber-backdrop" class="modal-backdrop" hidden></div>
405 <aside id="barber-panel" hidden>
406 <header>
407 <h2>Barber</h2>
408 <button id="barber-close" type="button">Close</button>
409 </header>
410 <div class="hair-controls">
411 <canvas data-hair-preview width="64" height="96" aria-label="Hair preview"></canvas>
412 <label>Hair
413 <select data-hair-style></select>
414 </label>
415 <label>Hue <input data-hair-hue type="range" min="0" max="360" value="30"></label>
416 <label>Saturation <input data-hair-saturation type="range" min="0" max="100" value="55"></label>
417 <label>Darkness <input data-hair-darkness type="range" min="0" max="100" value="45"></label>
418 <span data-hair-swatch class="hair-swatch" aria-hidden="true"></span>
419 </div>
420 <button id="barber-apply" type="button">Apply</button>
421 <p id="barber-status" class="hint"></p>
422 </aside>
423
341 424 <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
342 425 <aside id="cauldron-pick-panel" hidden>
343 426 <header>
@@ -372,6 +455,7 @@
372 455 <h2 id="inspect-name">Player</h2>
373 456 <button id="inspect-close" type="button">Close</button>
374 457 </header>
458 <p id="inspect-bounty" class="hint" hidden></p>
375 459 <p id="inspect-error" class="error"></p>
376 460 <div id="inspect-action"></div>
377 461 </div>
@@ -386,21 +470,40 @@
386 470 <h1>Tile MMO</h1>
387 471 <p id="status">Connecting…</p>
388 472 <p id="error" class="error"></p>
389 <form id="create-form">
390 <label>First name <input id="first-name" required></label>
391 <label>Last name <input id="last-name" required></label>
392 <label>Sex
393 <select id="sex">
394 <option value="male">Male</option>
395 <option value="female">Female</option>
396 </select>
397 </label>
398 <button type="submit">Create character</button>
399 </form>
400 473 <div id="character-list"></div>
474 <button id="create-character-open" type="button">Create Character</button>
401 475 <p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p>
402 476 </section>
403 477 </div>
478 <div id="create-backdrop" class="modal-backdrop" hidden></div>
479 <aside id="create-panel" hidden>
480 <header>
481 <h2>Create character</h2>
482 <button id="create-close" type="button">Close</button>
483 </header>
484 <p id="create-error" class="error"></p>
485 <form id="create-form">
486 <label>First name <input id="first-name" required></label>
487 <label>Last name <input id="last-name" required></label>
488 <label>Sex
489 <select id="sex">
490 <option value="male">Male</option>
491 <option value="female">Female</option>
492 </select>
493 </label>
494 <div id="create-hair" class="hair-controls">
495 <canvas id="create-hair-preview" data-hair-preview width="64" height="96" aria-label="Character preview"></canvas>
496 <label>Hair
497 <select id="create-hair-style" data-hair-style></select>
498 </label>
499 <label>Hue <input id="create-hair-hue" data-hair-hue type="range" min="0" max="360" value="30"></label>
500 <label>Saturation <input id="create-hair-saturation" data-hair-saturation type="range" min="0" max="100" value="55"></label>
501 <label>Darkness <input id="create-hair-darkness" data-hair-darkness type="range" min="0" max="100" value="45"></label>
502 <span id="create-hair-swatch" data-hair-swatch class="hair-swatch" aria-hidden="true"></span>
503 </div>
504 <button type="submit">Create &amp; play</button>
505 </form>
506 </aside>
404 507 <script src="/framework/framework.js"></script>
405 508 <script type="module" src="/src/play/main.js"></script>
406 509 </body>
@@ -15,6 +15,34 @@
15 <button id="bag-toggle" type="button">Bag</button>
15 <button id="bag-toggle" type="button">Bag</button>
16 <button id="leave" type="button">Leave world</button>
16 <button id="leave" type="button">Leave world</button>
17 </div>
17 </div>
18 <button id="settings-toggle" type="button" hidden title="Settings" aria-label="Settings">⚙</button>
19 <aside id="settings-panel" hidden>
20 <header>
21 <h2>Settings</h2>
22 <button id="settings-close" type="button">Close</button>
23 </header>
24 <section class="settings-group">
25 <h3>Viewing distance</h3>
26 <div class="settings-options">
27 <button type="button" data-graphics-key="viewDistance" data-graphics-value="long">Long</button>
28 <button type="button" data-graphics-key="viewDistance" data-graphics-value="short">Short</button>
29 </div>
30 </section>
31 <section class="settings-group">
32 <h3>Lighting</h3>
33 <div class="settings-options">
34 <button type="button" data-graphics-key="lighting" data-graphics-value="soft">Soft</button>
35 <button type="button" data-graphics-key="lighting" data-graphics-value="simple">Simple</button>
36 </div>
37 </section>
38 <section class="settings-group">
39 <h3>Bloom</h3>
40 <div class="settings-options">
41 <button type="button" data-graphics-key="bloom" data-graphics-value="on">On</button>
42 <button type="button" data-graphics-key="bloom" data-graphics-value="off">Off</button>
43 </div>
44 </section>
45 </aside>
18 <div id="toast-stack" aria-live="polite"></div>
46 <div id="toast-stack" aria-live="polite"></div>
19 <div id="world-tooltip" hidden></div>
47 <div id="world-tooltip" hidden></div>
20 <aside id="bag-panel" hidden>
48 <aside id="bag-panel" hidden>
@@ -338,6 +366,61 @@
338 </section>
366 </section>
339 </aside>
367 </aside>
340
368
369 <div id="bounty-backdrop" class="modal-backdrop" hidden></div>
370 <aside id="bounty-panel" hidden>
371 <header>
372 <h2>Bounty Office</h2>
373 <button id="bounty-close" type="button">Close</button>
374 </header>
375 <div class="bounty-tabs" role="tablist">
376 <button type="button" class="bounty-tab active" data-tab="place" role="tab">Place / raise</button>
377 <button type="button" class="bounty-tab" data-tab="mine" role="tab">My bounty</button>
378 </div>
379 <section class="bounty-pane" data-pane="place">
380 <div class="bounty-search-row">
381 <label>First <input id="bounty-search-first" autocomplete="off" spellcheck="false"></label>
382 <label>Last <input id="bounty-search-last" autocomplete="off" spellcheck="false"></label>
383 <button id="bounty-search" type="button">Search</button>
384 </div>
385 <div class="bounty-target">
386 <div id="bounty-preview"></div>
387 <div>
388 <p id="bounty-target-label">No target selected.</p>
389 <p id="bounty-target-amount" class="hint"></p>
390 </div>
391 </div>
392 <label class="bounty-amount-label">Coins to add
393 <input id="bounty-amount" type="number" min="1" step="1" value="100">
394 </label>
395 <button id="bounty-raise" type="button">Add to bounty</button>
396 <p id="bounty-status" class="hint"></p>
397 </section>
398 <section class="bounty-pane" data-pane="mine" hidden>
399 <p class="hint">Coin currently on your head:</p>
400 <p id="bounty-my-amount" class="bounty-my-amount">None</p>
401 </section>
402 </aside>
403
404 <div id="barber-backdrop" class="modal-backdrop" hidden></div>
405 <aside id="barber-panel" hidden>
406 <header>
407 <h2>Barber</h2>
408 <button id="barber-close" type="button">Close</button>
409 </header>
410 <div class="hair-controls">
411 <canvas data-hair-preview width="64" height="96" aria-label="Hair preview"></canvas>
412 <label>Hair
413 <select data-hair-style></select>
414 </label>
415 <label>Hue <input data-hair-hue type="range" min="0" max="360" value="30"></label>
416 <label>Saturation <input data-hair-saturation type="range" min="0" max="100" value="55"></label>
417 <label>Darkness <input data-hair-darkness type="range" min="0" max="100" value="45"></label>
418 <span data-hair-swatch class="hair-swatch" aria-hidden="true"></span>
419 </div>
420 <button id="barber-apply" type="button">Apply</button>
421 <p id="barber-status" class="hint"></p>
422 </aside>
423
341 <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
424 <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
342 <aside id="cauldron-pick-panel" hidden>
425 <aside id="cauldron-pick-panel" hidden>
343 <header>
426 <header>
@@ -372,6 +455,7 @@
372 <h2 id="inspect-name">Player</h2>
455 <h2 id="inspect-name">Player</h2>
373 <button id="inspect-close" type="button">Close</button>
456 <button id="inspect-close" type="button">Close</button>
374 </header>
457 </header>
458 <p id="inspect-bounty" class="hint" hidden></p>
375 <p id="inspect-error" class="error"></p>
459 <p id="inspect-error" class="error"></p>
376 <div id="inspect-action"></div>
460 <div id="inspect-action"></div>
377 </div>
461 </div>
@@ -386,21 +470,40 @@
386 <h1>Tile MMO</h1>
470 <h1>Tile MMO</h1>
387 <p id="status">Connecting…</p>
471 <p id="status">Connecting…</p>
388 <p id="error" class="error"></p>
472 <p id="error" class="error"></p>
389 <form id="create-form">
390 <label>First name <input id="first-name" required></label>
391 <label>Last name <input id="last-name" required></label>
392 <label>Sex
393 <select id="sex">
394 <option value="male">Male</option>
395 <option value="female">Female</option>
396 </select>
397 </label>
398 <button type="submit">Create character</button>
399 </form>
400 <div id="character-list"></div>
473 <div id="character-list"></div>
474 <button id="create-character-open" type="button">Create Character</button>
401 <p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p>
475 <p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p>
402 </section>
476 </section>
403 </div>
477 </div>
478 <div id="create-backdrop" class="modal-backdrop" hidden></div>
479 <aside id="create-panel" hidden>
480 <header>
481 <h2>Create character</h2>
482 <button id="create-close" type="button">Close</button>
483 </header>
484 <p id="create-error" class="error"></p>
485 <form id="create-form">
486 <label>First name <input id="first-name" required></label>
487 <label>Last name <input id="last-name" required></label>
488 <label>Sex
489 <select id="sex">
490 <option value="male">Male</option>
491 <option value="female">Female</option>
492 </select>
493 </label>
494 <div id="create-hair" class="hair-controls">
495 <canvas id="create-hair-preview" data-hair-preview width="64" height="96" aria-label="Character preview"></canvas>
496 <label>Hair
497 <select id="create-hair-style" data-hair-style></select>
498 </label>
499 <label>Hue <input id="create-hair-hue" data-hair-hue type="range" min="0" max="360" value="30"></label>
500 <label>Saturation <input id="create-hair-saturation" data-hair-saturation type="range" min="0" max="100" value="55"></label>
501 <label>Darkness <input id="create-hair-darkness" data-hair-darkness type="range" min="0" max="100" value="45"></label>
502 <span id="create-hair-swatch" data-hair-swatch class="hair-swatch" aria-hidden="true"></span>
503 </div>
504 <button type="submit">Create &amp; play</button>
505 </form>
506 </aside>
404 <script src="/framework/framework.js"></script>
507 <script src="/framework/framework.js"></script>
405 <script type="module" src="/src/play/main.js"></script>
508 <script type="module" src="/src/play/main.js"></script>
406</body>
509</body>
client/scripts/generate-herb-sprites.mjs added +226 −0
@@ -0,0 +1,226 @@
1 /**
2 * Temporary unique 16×16 herb sprites under client/assets/herbs/.
3 * One PNG per herbId — shared by world nodes and inventory icons.
4 */
5 import { mkdirSync, writeFileSync } from "node:fs";
6 import { deflateSync } from "node:zlib";
7 import { fileURLToPath } from "node:url";
8 import { dirname, join } from "node:path";
9 import { HERB_ORDER, HERB_DEFINITIONS } from "../../shared/definitions/herbs.js";
10
11 const SIZE = 16;
12 const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/herbs");
13
14 function crcTable ()
15 {
16 const table = new Uint32Array(256);
17 for (let n = 0; n < 256; n++)
18 {
19 let c = n;
20 for (let k = 0; k < 8; k++)
21 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
22 table[n] = c >>> 0;
23 }
24 return table;
25 }
26
27 const CRC_TABLE = crcTable();
28
29 function crc32 (buf)
30 {
31 let c = 0xffffffff;
32 for (let i = 0; i < buf.length; i++)
33 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
34 return (c ^ 0xffffffff) >>> 0;
35 }
36
37 function chunk (type, data)
38 {
39 const len = Buffer.alloc(4);
40 len.writeUInt32BE(data.length);
41 const typeBuf = Buffer.from(type, "ascii");
42 const crcBuf = Buffer.alloc(4);
43 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
44 return Buffer.concat([len, typeBuf, data, crcBuf]);
45 }
46
47 function encodePng (rgba)
48 {
49 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
50 for (let y = 0; y < SIZE; y++)
51 {
52 const row = y * (SIZE * 4 + 1);
53 raw[row] = 0;
54 for (let x = 0; x < SIZE; x++)
55 {
56 const i = (y * SIZE + x) * 4;
57 const o = row + 1 + x * 4;
58 raw[o] = rgba[i];
59 raw[o + 1] = rgba[i + 1];
60 raw[o + 2] = rgba[i + 2];
61 raw[o + 3] = rgba[i + 3];
62 }
63 }
64 const ihdr = Buffer.alloc(13);
65 ihdr.writeUInt32BE(SIZE, 0);
66 ihdr.writeUInt32BE(SIZE, 4);
67 ihdr[8] = 8;
68 ihdr[9] = 6;
69 ihdr[10] = 0;
70 ihdr[11] = 0;
71 ihdr[12] = 0;
72 return Buffer.concat([
73 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
74 chunk("IHDR", ihdr),
75 chunk("IDAT", deflateSync(raw, { level: 9 })),
76 chunk("IEND", Buffer.alloc(0))
77 ]);
78 }
79
80 function setPx (rgba, x, y, color)
81 {
82 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
83 { return; }
84 const i = (y * SIZE + x) * 4;
85 rgba[i] = color[0];
86 rgba[i + 1] = color[1];
87 rgba[i + 2] = color[2];
88 rgba[i + 3] = color[3];
89 }
90
91 function hashString (text)
92 {
93 let h = 2166136261;
94 for (let i = 0; i < text.length; i++)
95 {
96 h ^= text.charCodeAt(i);
97 h = Math.imul(h, 16777619);
98 }
99 return h >>> 0;
100 }
101
102 /** Distinct leaf/flower palettes keyed by herb identity. */
103 function paletteFor (herbId, tier)
104 {
105 const h = hashString(herbId);
106 const hue = (h % 360);
107 const sat = 0.35 + ((h >>> 8) % 40) / 100;
108 const lit = 0.28 + (tier - 1) * 0.04 + ((h >>> 16) % 20) / 100;
109 const flower = hsl(hue, sat, lit);
110 const leaf = hsl((hue + 100) % 360, 0.45, 0.32);
111 const stem = hsl((hue + 90) % 360, 0.35, 0.22);
112 const accent = hsl((hue + 40) % 360, Math.min(0.85, sat + 0.2), Math.min(0.7, lit + 0.15));
113 return { flower, leaf, stem, accent };
114 }
115
116 function hsl (h, s, l)
117 {
118 const a = s * Math.min(l, 1 - l);
119 const f = (n) =>
120 {
121 const k = (n + h / 30) % 12;
122 const c = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
123 return Math.round(255 * Math.min(1, Math.max(0, c)));
124 };
125 return [f(0), f(8), f(4), 255];
126 }
127
128 function drawHerb (herbId, tier)
129 {
130 const rgba = new Uint8Array(SIZE * SIZE * 4);
131 const { flower, leaf, stem, accent } = paletteFor(herbId, tier);
132 const shape = hashString(herbId) % 5;
133
134 // Stem
135 for (let y = 10; y < 15; y++)
136 {
137 setPx(rgba, 7, y, stem);
138 setPx(rgba, 8, y, stem);
139 }
140
141 if (shape === 0)
142 {
143 // Bushy leaves
144 for (const [x, y] of [[4, 8], [5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [11, 8],
145 [5, 9], [6, 8], [9, 8], [10, 9], [6, 10], [9, 10]])
146 { setPx(rgba, x, y, leaf); }
147 for (const [x, y] of [[6, 4], [7, 3], [8, 3], [9, 4], [7, 4], [8, 4]])
148 { setPx(rgba, x, y, flower); }
149 }
150 else if (shape === 1)
151 {
152 // Spike / upright
153 for (let y = 3; y < 11; y++)
154 {
155 setPx(rgba, 7, y, flower);
156 setPx(rgba, 8, y, accent);
157 if (y % 2 === 0)
158 {
159 setPx(rgba, 6, y, leaf);
160 setPx(rgba, 9, y, leaf);
161 }
162 }
163 }
164 else if (shape === 2)
165 {
166 // Bell / hanging
167 for (const [x, y] of [[5, 5], [6, 4], [7, 3], [8, 3], [9, 4], [10, 5]])
168 { setPx(rgba, x, y, leaf); }
169 for (const [x, y] of [[6, 6], [7, 6], [8, 6], [9, 6], [6, 7], [7, 8], [8, 8], [9, 7], [7, 7], [8, 7]])
170 { setPx(rgba, x, y, flower); }
171 setPx(rgba, 7, 9, accent);
172 setPx(rgba, 8, 9, accent);
173 }
174 else if (shape === 3)
175 {
176 // Round bloom
177 for (let dy = -3; dy <= 3; dy++)
178 {
179 for (let dx = -3; dx <= 3; dx++)
180 {
181 if (dx * dx + dy * dy <= 10)
182 { setPx(rgba, 7 + dx, 6 + dy, flower); }
183 if (dx * dx + dy * dy <= 3)
184 { setPx(rgba, 7 + dx, 6 + dy, accent); }
185 }
186 }
187 setPx(rgba, 4, 9, leaf);
188 setPx(rgba, 5, 10, leaf);
189 setPx(rgba, 10, 9, leaf);
190 setPx(rgba, 11, 10, leaf);
191 }
192 else
193 {
194 // Berry cluster / root-ish
195 for (const [x, y] of [[5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [6, 8], [9, 8]])
196 { setPx(rgba, x, y, leaf); }
197 for (const [x, y] of [[6, 9], [7, 8], [8, 8], [9, 9], [7, 9], [8, 9], [7, 10], [8, 10]])
198 { setPx(rgba, x, y, flower); }
199 setPx(rgba, 7, 7, accent);
200 setPx(rgba, 8, 7, accent);
201 }
202
203 // Tier mark (tiny dots for high tiers)
204 if (tier >= 5)
205 {
206 setPx(rgba, 1, 1, accent);
207 setPx(rgba, 2, 1, accent);
208 }
209 if (tier >= 7)
210 {
211 setPx(rgba, 13, 1, accent);
212 setPx(rgba, 14, 1, accent);
213 }
214
215 return rgba;
216 }
217
218 mkdirSync(OUT, { recursive: true });
219 for (const herbId of HERB_ORDER)
220 {
221 const def = HERB_DEFINITIONS[herbId];
222 const png = encodePng(drawHerb(herbId, def.tier));
223 writeFileSync(join(OUT, `${herbId}.png`), png);
224 console.log(`wrote ${herbId}.png (tier ${def.tier})`);
225 }
226 console.log(`Generated ${HERB_ORDER.length} herb sprites → ${OUT}`);
@@ -0,0 +1,226 @@
1/**
2 * Temporary unique 16×16 herb sprites under client/assets/herbs/.
3 * One PNG per herbId — shared by world nodes and inventory icons.
4 */
5import { mkdirSync, writeFileSync } from "node:fs";
6import { deflateSync } from "node:zlib";
7import { fileURLToPath } from "node:url";
8import { dirname, join } from "node:path";
9import { HERB_ORDER, HERB_DEFINITIONS } from "../../shared/definitions/herbs.js";
10
11const SIZE = 16;
12const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/herbs");
13
14function crcTable ()
15{
16 const table = new Uint32Array(256);
17 for (let n = 0; n < 256; n++)
18 {
19 let c = n;
20 for (let k = 0; k < 8; k++)
21 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
22 table[n] = c >>> 0;
23 }
24 return table;
25}
26
27const CRC_TABLE = crcTable();
28
29function crc32 (buf)
30{
31 let c = 0xffffffff;
32 for (let i = 0; i < buf.length; i++)
33 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
34 return (c ^ 0xffffffff) >>> 0;
35}
36
37function chunk (type, data)
38{
39 const len = Buffer.alloc(4);
40 len.writeUInt32BE(data.length);
41 const typeBuf = Buffer.from(type, "ascii");
42 const crcBuf = Buffer.alloc(4);
43 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
44 return Buffer.concat([len, typeBuf, data, crcBuf]);
45}
46
47function encodePng (rgba)
48{
49 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
50 for (let y = 0; y < SIZE; y++)
51 {
52 const row = y * (SIZE * 4 + 1);
53 raw[row] = 0;
54 for (let x = 0; x < SIZE; x++)
55 {
56 const i = (y * SIZE + x) * 4;
57 const o = row + 1 + x * 4;
58 raw[o] = rgba[i];
59 raw[o + 1] = rgba[i + 1];
60 raw[o + 2] = rgba[i + 2];
61 raw[o + 3] = rgba[i + 3];
62 }
63 }
64 const ihdr = Buffer.alloc(13);
65 ihdr.writeUInt32BE(SIZE, 0);
66 ihdr.writeUInt32BE(SIZE, 4);
67 ihdr[8] = 8;
68 ihdr[9] = 6;
69 ihdr[10] = 0;
70 ihdr[11] = 0;
71 ihdr[12] = 0;
72 return Buffer.concat([
73 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
74 chunk("IHDR", ihdr),
75 chunk("IDAT", deflateSync(raw, { level: 9 })),
76 chunk("IEND", Buffer.alloc(0))
77 ]);
78}
79
80function setPx (rgba, x, y, color)
81{
82 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
83 { return; }
84 const i = (y * SIZE + x) * 4;
85 rgba[i] = color[0];
86 rgba[i + 1] = color[1];
87 rgba[i + 2] = color[2];
88 rgba[i + 3] = color[3];
89}
90
91function hashString (text)
92{
93 let h = 2166136261;
94 for (let i = 0; i < text.length; i++)
95 {
96 h ^= text.charCodeAt(i);
97 h = Math.imul(h, 16777619);
98 }
99 return h >>> 0;
100}
101
102/** Distinct leaf/flower palettes keyed by herb identity. */
103function paletteFor (herbId, tier)
104{
105 const h = hashString(herbId);
106 const hue = (h % 360);
107 const sat = 0.35 + ((h >>> 8) % 40) / 100;
108 const lit = 0.28 + (tier - 1) * 0.04 + ((h >>> 16) % 20) / 100;
109 const flower = hsl(hue, sat, lit);
110 const leaf = hsl((hue + 100) % 360, 0.45, 0.32);
111 const stem = hsl((hue + 90) % 360, 0.35, 0.22);
112 const accent = hsl((hue + 40) % 360, Math.min(0.85, sat + 0.2), Math.min(0.7, lit + 0.15));
113 return { flower, leaf, stem, accent };
114}
115
116function hsl (h, s, l)
117{
118 const a = s * Math.min(l, 1 - l);
119 const f = (n) =>
120 {
121 const k = (n + h / 30) % 12;
122 const c = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
123 return Math.round(255 * Math.min(1, Math.max(0, c)));
124 };
125 return [f(0), f(8), f(4), 255];
126}
127
128function drawHerb (herbId, tier)
129{
130 const rgba = new Uint8Array(SIZE * SIZE * 4);
131 const { flower, leaf, stem, accent } = paletteFor(herbId, tier);
132 const shape = hashString(herbId) % 5;
133
134 // Stem
135 for (let y = 10; y < 15; y++)
136 {
137 setPx(rgba, 7, y, stem);
138 setPx(rgba, 8, y, stem);
139 }
140
141 if (shape === 0)
142 {
143 // Bushy leaves
144 for (const [x, y] of [[4, 8], [5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [11, 8],
145 [5, 9], [6, 8], [9, 8], [10, 9], [6, 10], [9, 10]])
146 { setPx(rgba, x, y, leaf); }
147 for (const [x, y] of [[6, 4], [7, 3], [8, 3], [9, 4], [7, 4], [8, 4]])
148 { setPx(rgba, x, y, flower); }
149 }
150 else if (shape === 1)
151 {
152 // Spike / upright
153 for (let y = 3; y < 11; y++)
154 {
155 setPx(rgba, 7, y, flower);
156 setPx(rgba, 8, y, accent);
157 if (y % 2 === 0)
158 {
159 setPx(rgba, 6, y, leaf);
160 setPx(rgba, 9, y, leaf);
161 }
162 }
163 }
164 else if (shape === 2)
165 {
166 // Bell / hanging
167 for (const [x, y] of [[5, 5], [6, 4], [7, 3], [8, 3], [9, 4], [10, 5]])
168 { setPx(rgba, x, y, leaf); }
169 for (const [x, y] of [[6, 6], [7, 6], [8, 6], [9, 6], [6, 7], [7, 8], [8, 8], [9, 7], [7, 7], [8, 7]])
170 { setPx(rgba, x, y, flower); }
171 setPx(rgba, 7, 9, accent);
172 setPx(rgba, 8, 9, accent);
173 }
174 else if (shape === 3)
175 {
176 // Round bloom
177 for (let dy = -3; dy <= 3; dy++)
178 {
179 for (let dx = -3; dx <= 3; dx++)
180 {
181 if (dx * dx + dy * dy <= 10)
182 { setPx(rgba, 7 + dx, 6 + dy, flower); }
183 if (dx * dx + dy * dy <= 3)
184 { setPx(rgba, 7 + dx, 6 + dy, accent); }
185 }
186 }
187 setPx(rgba, 4, 9, leaf);
188 setPx(rgba, 5, 10, leaf);
189 setPx(rgba, 10, 9, leaf);
190 setPx(rgba, 11, 10, leaf);
191 }
192 else
193 {
194 // Berry cluster / root-ish
195 for (const [x, y] of [[5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [6, 8], [9, 8]])
196 { setPx(rgba, x, y, leaf); }
197 for (const [x, y] of [[6, 9], [7, 8], [8, 8], [9, 9], [7, 9], [8, 9], [7, 10], [8, 10]])
198 { setPx(rgba, x, y, flower); }
199 setPx(rgba, 7, 7, accent);
200 setPx(rgba, 8, 7, accent);
201 }
202
203 // Tier mark (tiny dots for high tiers)
204 if (tier >= 5)
205 {
206 setPx(rgba, 1, 1, accent);
207 setPx(rgba, 2, 1, accent);
208 }
209 if (tier >= 7)
210 {
211 setPx(rgba, 13, 1, accent);
212 setPx(rgba, 14, 1, accent);
213 }
214
215 return rgba;
216}
217
218mkdirSync(OUT, { recursive: true });
219for (const herbId of HERB_ORDER)
220{
221 const def = HERB_DEFINITIONS[herbId];
222 const png = encodePng(drawHerb(herbId, def.tier));
223 writeFileSync(join(OUT, `${herbId}.png`), png);
224 console.log(`wrote ${herbId}.png (tier ${def.tier})`);
225}
226console.log(`Generated ${HERB_ORDER.length} herb sprites → ${OUT}`);
client/scripts/generate-status-effect-icons.mjs added +125 −0
@@ -0,0 +1,125 @@
1 /**
2 * Temporary 16×16 status-effect icons (replace with final art later).
3 */
4 import { mkdirSync, writeFileSync } from "node:fs";
5 import { deflateSync } from "node:zlib";
6 import { fileURLToPath } from "node:url";
7 import { dirname, join } from "node:path";
8 import { STATUS_EFFECT_DISPLAY } from "../../shared/statusEffects/display.js";
9
10 const SIZE = 16;
11 const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/status-effects");
12
13 const PALETTE = {
14 "health-regen": [80, 200, 100],
15 "stamina-regen": [90, 200, 170],
16 "strength-bonus": [220, 100, 60],
17 "mind-bonus": [140, 120, 230],
18 "stamina-drain": [180, 60, 90],
19 glow: [240, 220, 90],
20 shrink: [180, 140, 210],
21 blind: [40, 40, 50]
22 };
23
24 function crcTable ()
25 {
26 const table = new Uint32Array(256);
27 for (let n = 0; n < 256; n++)
28 {
29 let c = n;
30 for (let k = 0; k < 8; k++)
31 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
32 table[n] = c >>> 0;
33 }
34 return table;
35 }
36
37 const CRC_TABLE = crcTable();
38
39 function crc32 (buf)
40 {
41 let c = 0xffffffff;
42 for (let i = 0; i < buf.length; i++)
43 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
44 return (c ^ 0xffffffff) >>> 0;
45 }
46
47 function chunk (type, data)
48 {
49 const len = Buffer.alloc(4);
50 len.writeUInt32BE(data.length);
51 const typeBuf = Buffer.from(type, "ascii");
52 const crcBuf = Buffer.alloc(4);
53 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
54 return Buffer.concat([len, typeBuf, data, crcBuf]);
55 }
56
57 function encodePng (rgba)
58 {
59 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
60 for (let y = 0; y < SIZE; y++)
61 {
62 const row = y * (SIZE * 4 + 1);
63 raw[row] = 0;
64 for (let x = 0; x < SIZE; x++)
65 {
66 const i = (y * SIZE + x) * 4;
67 const o = row + 1 + x * 4;
68 raw[o] = rgba[i];
69 raw[o + 1] = rgba[i + 1];
70 raw[o + 2] = rgba[i + 2];
71 raw[o + 3] = rgba[i + 3];
72 }
73 }
74 const ihdr = Buffer.alloc(13);
75 ihdr.writeUInt32BE(SIZE, 0);
76 ihdr.writeUInt32BE(SIZE, 4);
77 ihdr[8] = 8;
78 ihdr[9] = 6;
79 return Buffer.concat([
80 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
81 chunk("IHDR", ihdr),
82 chunk("IDAT", deflateSync(raw, { level: 9 })),
83 chunk("IEND", Buffer.alloc(0))
84 ]);
85 }
86
87 function setPx (rgba, x, y, rgb)
88 {
89 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
90 { return; }
91 const i = (y * SIZE + x) * 4;
92 rgba[i] = rgb[0];
93 rgba[i + 1] = rgb[1];
94 rgba[i + 2] = rgb[2];
95 rgba[i + 3] = 255;
96 }
97
98 function drawIcon (rgb)
99 {
100 const rgba = new Uint8Array(SIZE * SIZE * 4);
101 const rim = [Math.max(0, rgb[0] - 50), Math.max(0, rgb[1] - 50), Math.max(0, rgb[2] - 50)];
102 for (let y = 2; y < 14; y++)
103 {
104 for (let x = 2; x < 14; x++)
105 {
106 const edge = x === 2 || x === 13 || y === 2 || y === 13;
107 setPx(rgba, x, y, edge ? rim : rgb);
108 }
109 }
110 // Simple glyph: plus / diamond / bar
111 for (let i = 5; i < 11; i++)
112 {
113 setPx(rgba, i, 7, [255, 255, 255]);
114 setPx(rgba, 7, i, [255, 255, 255]);
115 }
116 return rgba;
117 }
118
119 mkdirSync(OUT, { recursive: true });
120 for (const display of Object.values(STATUS_EFFECT_DISPLAY))
121 {
122 const rgb = PALETTE[display.iconKey] ?? [160, 160, 160];
123 writeFileSync(join(OUT, `${display.iconKey}.png`), encodePng(drawIcon(rgb)));
124 console.log(`wrote ${display.iconKey}.png`);
125 }
@@ -0,0 +1,125 @@
1/**
2 * Temporary 16×16 status-effect icons (replace with final art later).
3 */
4import { mkdirSync, writeFileSync } from "node:fs";
5import { deflateSync } from "node:zlib";
6import { fileURLToPath } from "node:url";
7import { dirname, join } from "node:path";
8import { STATUS_EFFECT_DISPLAY } from "../../shared/statusEffects/display.js";
9
10const SIZE = 16;
11const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/status-effects");
12
13const PALETTE = {
14 "health-regen": [80, 200, 100],
15 "stamina-regen": [90, 200, 170],
16 "strength-bonus": [220, 100, 60],
17 "mind-bonus": [140, 120, 230],
18 "stamina-drain": [180, 60, 90],
19 glow: [240, 220, 90],
20 shrink: [180, 140, 210],
21 blind: [40, 40, 50]
22};
23
24function crcTable ()
25{
26 const table = new Uint32Array(256);
27 for (let n = 0; n < 256; n++)
28 {
29 let c = n;
30 for (let k = 0; k < 8; k++)
31 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
32 table[n] = c >>> 0;
33 }
34 return table;
35}
36
37const CRC_TABLE = crcTable();
38
39function crc32 (buf)
40{
41 let c = 0xffffffff;
42 for (let i = 0; i < buf.length; i++)
43 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
44 return (c ^ 0xffffffff) >>> 0;
45}
46
47function chunk (type, data)
48{
49 const len = Buffer.alloc(4);
50 len.writeUInt32BE(data.length);
51 const typeBuf = Buffer.from(type, "ascii");
52 const crcBuf = Buffer.alloc(4);
53 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
54 return Buffer.concat([len, typeBuf, data, crcBuf]);
55}
56
57function encodePng (rgba)
58{
59 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
60 for (let y = 0; y < SIZE; y++)
61 {
62 const row = y * (SIZE * 4 + 1);
63 raw[row] = 0;
64 for (let x = 0; x < SIZE; x++)
65 {
66 const i = (y * SIZE + x) * 4;
67 const o = row + 1 + x * 4;
68 raw[o] = rgba[i];
69 raw[o + 1] = rgba[i + 1];
70 raw[o + 2] = rgba[i + 2];
71 raw[o + 3] = rgba[i + 3];
72 }
73 }
74 const ihdr = Buffer.alloc(13);
75 ihdr.writeUInt32BE(SIZE, 0);
76 ihdr.writeUInt32BE(SIZE, 4);
77 ihdr[8] = 8;
78 ihdr[9] = 6;
79 return Buffer.concat([
80 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
81 chunk("IHDR", ihdr),
82 chunk("IDAT", deflateSync(raw, { level: 9 })),
83 chunk("IEND", Buffer.alloc(0))
84 ]);
85}
86
87function setPx (rgba, x, y, rgb)
88{
89 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
90 { return; }
91 const i = (y * SIZE + x) * 4;
92 rgba[i] = rgb[0];
93 rgba[i + 1] = rgb[1];
94 rgba[i + 2] = rgb[2];
95 rgba[i + 3] = 255;
96}
97
98function drawIcon (rgb)
99{
100 const rgba = new Uint8Array(SIZE * SIZE * 4);
101 const rim = [Math.max(0, rgb[0] - 50), Math.max(0, rgb[1] - 50), Math.max(0, rgb[2] - 50)];
102 for (let y = 2; y < 14; y++)
103 {
104 for (let x = 2; x < 14; x++)
105 {
106 const edge = x === 2 || x === 13 || y === 2 || y === 13;
107 setPx(rgba, x, y, edge ? rim : rgb);
108 }
109 }
110 // Simple glyph: plus / diamond / bar
111 for (let i = 5; i < 11; i++)
112 {
113 setPx(rgba, i, 7, [255, 255, 255]);
114 setPx(rgba, 7, i, [255, 255, 255]);
115 }
116 return rgba;
117}
118
119mkdirSync(OUT, { recursive: true });
120for (const display of Object.values(STATUS_EFFECT_DISPLAY))
121{
122 const rgb = PALETTE[display.iconKey] ?? [160, 160, 160];
123 writeFileSync(join(OUT, `${display.iconKey}.png`), encodePng(drawIcon(rgb)));
124 console.log(`wrote ${display.iconKey}.png`);
125}
client/src/editor/settingsModal.js +224 −2
@@ -11,8 +11,24 @@ import {
11 11 normalizeItemSeedValues,
12 12 effectiveSeedValue
13 13 } from "/shared/shop/pricing.js";
14 import { ITEM_DEFINITIONS } from "/shared/definitions/items.js";
15 import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
16 import {
17 normalizeStarterLoadout,
18 starterLoadoutsEqual,
19 DEFAULT_STARTER_EQUIPMENT,
20 DEFAULT_STARTER_INVENTORY
21 } from "/shared/items/starterLoadout.js";
14 22
15 23 const SEED_PAGE_SIZE = 20;
24 const SLOT_LABELS = Object.freeze({
25 head: "Head",
26 chest: "Chest",
27 legs: "Legs",
28 boots: "Boots",
29 weapon: "Weapon",
30 offhand: "Off-hand"
31 });
16 32
17 33 export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
18 34 {
@@ -32,6 +48,12 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
32 48 let seedQuery = "";
33 49 let seedPage = 0;
34 50 let seedPanel = null;
51 /** @type {{ equipment: Record<string, number|null>, inventory: { itemId: number, quantity: number }[] }} */
52 let draftStarter = normalizeStarterLoadout({
53 starterEquipment: DEFAULT_STARTER_EQUIPMENT,
54 starterInventory: DEFAULT_STARTER_INVENTORY
55 });
56 let starterPanel = null;
35 57
36 58 buildForm(form, {
37 59 getActiveCategory: () => activeCategory,
@@ -41,6 +63,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
41 63 syncTabs(form, activeCategory);
42 64 if (id === "basePrices")
43 65 { renderSeedPanel(); }
66 if (id === "starterEquipment")
67 { renderStarterPanel(); }
44 68 },
45 69 onFieldInput (field)
46 70 {
@@ -50,6 +74,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
50 74 onSeedPanelReady (panel)
51 75 {
52 76 seedPanel = panel;
77 },
78 onStarterPanelReady (panel)
79 {
80 starterPanel = panel;
53 81 }
54 82 });
55 83
@@ -68,14 +96,31 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
68 96 {
69 97 if (event.target?.dataset?.seedItemId)
70 98 { return; }
99 if (event.target?.dataset?.starterField)
100 { return; }
71 101 refreshDirty();
72 102 });
73 103 form.addEventListener("change", (event) =>
74 104 {
75 105 if (event.target?.dataset?.seedItemId)
76 106 { return; }
107 if (event.target?.dataset?.starterField)
108 { return; }
77 109 refreshDirty();
78 110 });
111 form.addEventListener("starter-changed", () => refreshDirty());
112 form.addEventListener("starter-add-inv", () =>
113 {
114 const first = listAllItems()[0];
115 if (!first)
116 { return; }
117 draftStarter = {
118 ...draftStarter,
119 inventory: [...draftStarter.inventory, { itemId: first.itemId, quantity: 1 }]
120 };
121 renderStarterPanel();
122 form.dispatchEvent(new CustomEvent("starter-changed"));
123 });
79 124
80 125 function show (visible)
81 126 {
@@ -83,11 +128,13 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
83 128 {
84 129 fillForm(form, baseline);
85 130 draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
131 draftStarter = normalizeStarterLoadout(baseline);
86 132 seedQuery = "";
87 133 seedPage = 0;
88 134 if (seedPanel?.search)
89 135 { seedPanel.search.value = ""; }
90 136 renderSeedPanel();
137 renderStarterPanel();
91 138 refreshDirty();
92 139 }
93 140 open = visible;
@@ -118,7 +165,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
118 165 return {
119 166 ...baseline,
120 167 ...scalarDirtyValues(form, baseline),
121 itemSeedValues: draftSeeds
168 itemSeedValues: draftSeeds,
169 starterEquipment: draftStarter.equipment,
170 starterInventory: draftStarter.inventory
122 171 };
123 172 }
124 173
@@ -129,6 +178,15 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
129 178 const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues);
130 179 if (!itemSeedMapsEqual(prevSeeds, nextSeeds))
131 180 { changed.itemSeedValues = nextSeeds; }
181 const nextStarter = normalizeStarterLoadout({
182 starterEquipment: draftStarter.equipment,
183 starterInventory: draftStarter.inventory
184 });
185 if (!starterLoadoutsEqual(baseline, nextStarter))
186 {
187 changed.starterEquipment = nextStarter.equipment;
188 changed.starterInventory = nextStarter.inventory;
189 }
132 190 return changed;
133 191 }
134 192
@@ -245,6 +303,110 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
245 303 refreshDirty();
246 304 }
247 305
306 function renderStarterPanel ()
307 {
308 if (!starterPanel)
309 { return; }
310 const { equipRoot, invRoot } = starterPanel;
311 equipRoot.innerHTML = "";
312 for (const slot of EQUIPMENT_SLOTS)
313 {
314 const row = document.createElement("label");
315 row.className = "starter-equip-row";
316 row.dataset.slot = slot;
317 const title = document.createElement("span");
318 title.textContent = SLOT_LABELS[slot] ?? slot;
319 const select = document.createElement("select");
320 select.dataset.starterField = "equip";
321 select.dataset.slot = slot;
322 const empty = document.createElement("option");
323 empty.value = "";
324 empty.textContent = "(empty)";
325 select.append(empty);
326 for (const item of listItemsForSlot(slot))
327 {
328 const opt = document.createElement("option");
329 opt.value = String(item.itemId);
330 opt.textContent = item.displayName;
331 select.append(opt);
332 }
333 select.value = draftStarter.equipment[slot] != null
334 ? String(draftStarter.equipment[slot])
335 : "";
336 select.addEventListener("change", () =>
337 {
338 const raw = select.value;
339 draftStarter = {
340 ...draftStarter,
341 equipment: {
342 ...draftStarter.equipment,
343 [slot]: raw === "" ? null : Number(raw)
344 }
345 };
346 form.dispatchEvent(new CustomEvent("starter-changed"));
347 row.classList.toggle("dirty", draftStarter.equipment[slot] !== normalizeStarterLoadout(baseline).equipment[slot]);
348 });
349 row.append(title, select);
350 equipRoot.append(row);
351 }
352
353 invRoot.innerHTML = "";
354 draftStarter.inventory.forEach((entry, index) =>
355 {
356 const row = document.createElement("div");
357 row.className = "starter-inv-row";
358 const select = document.createElement("select");
359 select.dataset.starterField = "inv-item";
360 for (const item of listAllItems())
361 {
362 const opt = document.createElement("option");
363 opt.value = String(item.itemId);
364 opt.textContent = item.displayName;
365 select.append(opt);
366 }
367 select.value = String(entry.itemId);
368 const qty = document.createElement("input");
369 qty.type = "number";
370 qty.min = "1";
371 qty.step = "1";
372 qty.dataset.starterField = "inv-qty";
373 qty.value = String(entry.quantity);
374 const remove = document.createElement("button");
375 remove.type = "button";
376 remove.textContent = "Remove";
377 select.addEventListener("change", () =>
378 {
379 const next = draftStarter.inventory.map((rowEntry, i) => (
380 i === index ? { ...rowEntry, itemId: Number(select.value) } : rowEntry
381 ));
382 draftStarter = { ...draftStarter, inventory: next };
383 form.dispatchEvent(new CustomEvent("starter-changed"));
384 });
385 qty.addEventListener("change", () =>
386 {
387 const quantity = Math.max(1, Math.floor(Number(qty.value) || 1));
388 qty.value = String(quantity);
389 const next = draftStarter.inventory.map((rowEntry, i) => (
390 i === index ? { ...rowEntry, quantity } : rowEntry
391 ));
392 draftStarter = { ...draftStarter, inventory: next };
393 form.dispatchEvent(new CustomEvent("starter-changed"));
394 });
395 remove.addEventListener("click", () =>
396 {
397 draftStarter = {
398 ...draftStarter,
399 inventory: draftStarter.inventory.filter((_, i) => i !== index)
400 };
401 renderStarterPanel();
402 form.dispatchEvent(new CustomEvent("starter-changed"));
403 });
404 row.append(select, qty, remove);
405 invRoot.append(row);
406 });
407 refreshDirty();
408 }
409
248 410 function updateSeedRowReadouts (row, itemId, snap = null)
249 411 {
250 412 const resolved = snap ?? itemPriceSnapshot(itemId, {
@@ -280,8 +442,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
280 442 ? message.itemLastSales
281 443 : {};
282 444 draftSeeds = { ...baseline.itemSeedValues };
445 draftStarter = normalizeStarterLoadout(baseline);
283 446 fillForm(form, baseline);
284 447 renderSeedPanel();
448 renderStarterPanel();
285 449 refreshDirty();
286 450 renderLog(log, message.changelog ?? []);
287 451 onApplied?.(message.settings);
@@ -289,7 +453,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
289 453 };
290 454 }
291 455
292 function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady })
456 function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady, onStarterPanelReady })
293 457 {
294 458 form.innerHTML = "";
295 459 const tabs = document.createElement("div");
@@ -325,6 +489,15 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput,
325 489 section.append(panel.root);
326 490 onSeedPanelReady?.(panel);
327 491 }
492 else if (category.panel === "starterEquipment")
493 {
494 const panel = buildStarterEquipmentPanel({
495 onAddInventory ()
496 { form.dispatchEvent(new CustomEvent("starter-add-inv")); }
497 });
498 section.append(panel.root);
499 onStarterPanelReady?.(panel);
500 }
328 501 else
329 502 {
330 503 for (const field of category.fields)
@@ -417,6 +590,55 @@ function buildSeedPricePanel ({ onSearch, onPrev, onNext })
417 590 return { root, search, meta, list, prev, next, pageLabel };
418 591 }
419 592
593 function buildStarterEquipmentPanel ({ onAddInventory })
594 {
595 const root = document.createElement("div");
596 root.className = "starter-equipment-panel";
597
598 const hint = document.createElement("p");
599 hint.className = "hint";
600 hint.textContent = "Applies only to newly created characters. Items are marked “Received from the gods”. Existing characters are unchanged.";
601
602 const equipTitle = document.createElement("h3");
603 equipTitle.textContent = "Equipped";
604 const equipRoot = document.createElement("div");
605 equipRoot.className = "starter-equip-list";
606
607 const invTitle = document.createElement("h3");
608 invTitle.textContent = "Inventory";
609 const invRoot = document.createElement("div");
610 invRoot.className = "starter-inv-list";
611
612 const add = document.createElement("button");
613 add.type = "button";
614 add.textContent = "Add inventory item";
615 add.addEventListener("click", () => onAddInventory?.());
616
617 root.append(hint, equipTitle, equipRoot, invTitle, invRoot, add);
618 return { root, equipRoot, invRoot };
619 }
620
621 function listAllItems ()
622 {
623 return Object.values(ITEM_DEFINITIONS)
624 .map((def) => ({
625 itemId: def.itemId,
626 displayName: def.displayName ?? `#${def.itemId}`
627 }))
628 .sort((a, b) => a.displayName.localeCompare(b.displayName));
629 }
630
631 function listItemsForSlot (slot)
632 {
633 return Object.values(ITEM_DEFINITIONS)
634 .filter((def) => def.equipment?.slot === slot)
635 .map((def) => ({
636 itemId: def.itemId,
637 displayName: def.displayName ?? `#${def.itemId}`
638 }))
639 .sort((a, b) => a.displayName.localeCompare(b.displayName));
640 }
641
420 642 function syncTabs (form, activeCategory)
421 643 {
422 644 for (const tab of form.querySelectorAll(".settings-tab"))
@@ -11,8 +11,24 @@ import {
11 normalizeItemSeedValues,
11 normalizeItemSeedValues,
12 effectiveSeedValue
12 effectiveSeedValue
13} from "/shared/shop/pricing.js";
13} from "/shared/shop/pricing.js";
14import { ITEM_DEFINITIONS } from "/shared/definitions/items.js";
15import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
16import {
17 normalizeStarterLoadout,
18 starterLoadoutsEqual,
19 DEFAULT_STARTER_EQUIPMENT,
20 DEFAULT_STARTER_INVENTORY
21} from "/shared/items/starterLoadout.js";
14
22
15const SEED_PAGE_SIZE = 20;
23const SEED_PAGE_SIZE = 20;
24const SLOT_LABELS = Object.freeze({
25 head: "Head",
26 chest: "Chest",
27 legs: "Legs",
28 boots: "Boots",
29 weapon: "Weapon",
30 offhand: "Off-hand"
31});
16
32
17export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
33export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
18{
34{
@@ -32,6 +48,12 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
32 let seedQuery = "";
48 let seedQuery = "";
33 let seedPage = 0;
49 let seedPage = 0;
34 let seedPanel = null;
50 let seedPanel = null;
51 /** @type {{ equipment: Record<string, number|null>, inventory: { itemId: number, quantity: number }[] }} */
52 let draftStarter = normalizeStarterLoadout({
53 starterEquipment: DEFAULT_STARTER_EQUIPMENT,
54 starterInventory: DEFAULT_STARTER_INVENTORY
55 });
56 let starterPanel = null;
35
57
36 buildForm(form, {
58 buildForm(form, {
37 getActiveCategory: () => activeCategory,
59 getActiveCategory: () => activeCategory,
@@ -41,6 +63,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
41 syncTabs(form, activeCategory);
63 syncTabs(form, activeCategory);
42 if (id === "basePrices")
64 if (id === "basePrices")
43 { renderSeedPanel(); }
65 { renderSeedPanel(); }
66 if (id === "starterEquipment")
67 { renderStarterPanel(); }
44 },
68 },
45 onFieldInput (field)
69 onFieldInput (field)
46 {
70 {
@@ -50,6 +74,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
50 onSeedPanelReady (panel)
74 onSeedPanelReady (panel)
51 {
75 {
52 seedPanel = panel;
76 seedPanel = panel;
77 },
78 onStarterPanelReady (panel)
79 {
80 starterPanel = panel;
53 }
81 }
54 });
82 });
55
83
@@ -68,14 +96,31 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
68 {
96 {
69 if (event.target?.dataset?.seedItemId)
97 if (event.target?.dataset?.seedItemId)
70 { return; }
98 { return; }
99 if (event.target?.dataset?.starterField)
100 { return; }
71 refreshDirty();
101 refreshDirty();
72 });
102 });
73 form.addEventListener("change", (event) =>
103 form.addEventListener("change", (event) =>
74 {
104 {
75 if (event.target?.dataset?.seedItemId)
105 if (event.target?.dataset?.seedItemId)
76 { return; }
106 { return; }
107 if (event.target?.dataset?.starterField)
108 { return; }
77 refreshDirty();
109 refreshDirty();
78 });
110 });
111 form.addEventListener("starter-changed", () => refreshDirty());
112 form.addEventListener("starter-add-inv", () =>
113 {
114 const first = listAllItems()[0];
115 if (!first)
116 { return; }
117 draftStarter = {
118 ...draftStarter,
119 inventory: [...draftStarter.inventory, { itemId: first.itemId, quantity: 1 }]
120 };
121 renderStarterPanel();
122 form.dispatchEvent(new CustomEvent("starter-changed"));
123 });
79
124
80 function show (visible)
125 function show (visible)
81 {
126 {
@@ -83,11 +128,13 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
83 {
128 {
84 fillForm(form, baseline);
129 fillForm(form, baseline);
85 draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
130 draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
131 draftStarter = normalizeStarterLoadout(baseline);
86 seedQuery = "";
132 seedQuery = "";
87 seedPage = 0;
133 seedPage = 0;
88 if (seedPanel?.search)
134 if (seedPanel?.search)
89 { seedPanel.search.value = ""; }
135 { seedPanel.search.value = ""; }
90 renderSeedPanel();
136 renderSeedPanel();
137 renderStarterPanel();
91 refreshDirty();
138 refreshDirty();
92 }
139 }
93 open = visible;
140 open = visible;
@@ -118,7 +165,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
118 return {
165 return {
119 ...baseline,
166 ...baseline,
120 ...scalarDirtyValues(form, baseline),
167 ...scalarDirtyValues(form, baseline),
121 itemSeedValues: draftSeeds
168 itemSeedValues: draftSeeds,
169 starterEquipment: draftStarter.equipment,
170 starterInventory: draftStarter.inventory
122 };
171 };
123 }
172 }
124
173
@@ -129,6 +178,15 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
129 const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues);
178 const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues);
130 if (!itemSeedMapsEqual(prevSeeds, nextSeeds))
179 if (!itemSeedMapsEqual(prevSeeds, nextSeeds))
131 { changed.itemSeedValues = nextSeeds; }
180 { changed.itemSeedValues = nextSeeds; }
181 const nextStarter = normalizeStarterLoadout({
182 starterEquipment: draftStarter.equipment,
183 starterInventory: draftStarter.inventory
184 });
185 if (!starterLoadoutsEqual(baseline, nextStarter))
186 {
187 changed.starterEquipment = nextStarter.equipment;
188 changed.starterInventory = nextStarter.inventory;
189 }
132 return changed;
190 return changed;
133 }
191 }
134
192
@@ -245,6 +303,110 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
245 refreshDirty();
303 refreshDirty();
246 }
304 }
247
305
306 function renderStarterPanel ()
307 {
308 if (!starterPanel)
309 { return; }
310 const { equipRoot, invRoot } = starterPanel;
311 equipRoot.innerHTML = "";
312 for (const slot of EQUIPMENT_SLOTS)
313 {
314 const row = document.createElement("label");
315 row.className = "starter-equip-row";
316 row.dataset.slot = slot;
317 const title = document.createElement("span");
318 title.textContent = SLOT_LABELS[slot] ?? slot;
319 const select = document.createElement("select");
320 select.dataset.starterField = "equip";
321 select.dataset.slot = slot;
322 const empty = document.createElement("option");
323 empty.value = "";
324 empty.textContent = "(empty)";
325 select.append(empty);
326 for (const item of listItemsForSlot(slot))
327 {
328 const opt = document.createElement("option");
329 opt.value = String(item.itemId);
330 opt.textContent = item.displayName;
331 select.append(opt);
332 }
333 select.value = draftStarter.equipment[slot] != null
334 ? String(draftStarter.equipment[slot])
335 : "";
336 select.addEventListener("change", () =>
337 {
338 const raw = select.value;
339 draftStarter = {
340 ...draftStarter,
341 equipment: {
342 ...draftStarter.equipment,
343 [slot]: raw === "" ? null : Number(raw)
344 }
345 };
346 form.dispatchEvent(new CustomEvent("starter-changed"));
347 row.classList.toggle("dirty", draftStarter.equipment[slot] !== normalizeStarterLoadout(baseline).equipment[slot]);
348 });
349 row.append(title, select);
350 equipRoot.append(row);
351 }
352
353 invRoot.innerHTML = "";
354 draftStarter.inventory.forEach((entry, index) =>
355 {
356 const row = document.createElement("div");
357 row.className = "starter-inv-row";
358 const select = document.createElement("select");
359 select.dataset.starterField = "inv-item";
360 for (const item of listAllItems())
361 {
362 const opt = document.createElement("option");
363 opt.value = String(item.itemId);
364 opt.textContent = item.displayName;
365 select.append(opt);
366 }
367 select.value = String(entry.itemId);
368 const qty = document.createElement("input");
369 qty.type = "number";
370 qty.min = "1";
371 qty.step = "1";
372 qty.dataset.starterField = "inv-qty";
373 qty.value = String(entry.quantity);
374 const remove = document.createElement("button");
375 remove.type = "button";
376 remove.textContent = "Remove";
377 select.addEventListener("change", () =>
378 {
379 const next = draftStarter.inventory.map((rowEntry, i) => (
380 i === index ? { ...rowEntry, itemId: Number(select.value) } : rowEntry
381 ));
382 draftStarter = { ...draftStarter, inventory: next };
383 form.dispatchEvent(new CustomEvent("starter-changed"));
384 });
385 qty.addEventListener("change", () =>
386 {
387 const quantity = Math.max(1, Math.floor(Number(qty.value) || 1));
388 qty.value = String(quantity);
389 const next = draftStarter.inventory.map((rowEntry, i) => (
390 i === index ? { ...rowEntry, quantity } : rowEntry
391 ));
392 draftStarter = { ...draftStarter, inventory: next };
393 form.dispatchEvent(new CustomEvent("starter-changed"));
394 });
395 remove.addEventListener("click", () =>
396 {
397 draftStarter = {
398 ...draftStarter,
399 inventory: draftStarter.inventory.filter((_, i) => i !== index)
400 };
401 renderStarterPanel();
402 form.dispatchEvent(new CustomEvent("starter-changed"));
403 });
404 row.append(select, qty, remove);
405 invRoot.append(row);
406 });
407 refreshDirty();
408 }
409
248 function updateSeedRowReadouts (row, itemId, snap = null)
410 function updateSeedRowReadouts (row, itemId, snap = null)
249 {
411 {
250 const resolved = snap ?? itemPriceSnapshot(itemId, {
412 const resolved = snap ?? itemPriceSnapshot(itemId, {
@@ -280,8 +442,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
280 ? message.itemLastSales
442 ? message.itemLastSales
281 : {};
443 : {};
282 draftSeeds = { ...baseline.itemSeedValues };
444 draftSeeds = { ...baseline.itemSeedValues };
445 draftStarter = normalizeStarterLoadout(baseline);
283 fillForm(form, baseline);
446 fillForm(form, baseline);
284 renderSeedPanel();
447 renderSeedPanel();
448 renderStarterPanel();
285 refreshDirty();
449 refreshDirty();
286 renderLog(log, message.changelog ?? []);
450 renderLog(log, message.changelog ?? []);
287 onApplied?.(message.settings);
451 onApplied?.(message.settings);
@@ -289,7 +453,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
289 };
453 };
290}
454}
291
455
292function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady })
456function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady, onStarterPanelReady })
293{
457{
294 form.innerHTML = "";
458 form.innerHTML = "";
295 const tabs = document.createElement("div");
459 const tabs = document.createElement("div");
@@ -325,6 +489,15 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput,
325 section.append(panel.root);
489 section.append(panel.root);
326 onSeedPanelReady?.(panel);
490 onSeedPanelReady?.(panel);
327 }
491 }
492 else if (category.panel === "starterEquipment")
493 {
494 const panel = buildStarterEquipmentPanel({
495 onAddInventory ()
496 { form.dispatchEvent(new CustomEvent("starter-add-inv")); }
497 });
498 section.append(panel.root);
499 onStarterPanelReady?.(panel);
500 }
328 else
501 else
329 {
502 {
330 for (const field of category.fields)
503 for (const field of category.fields)
@@ -417,6 +590,55 @@ function buildSeedPricePanel ({ onSearch, onPrev, onNext })
417 return { root, search, meta, list, prev, next, pageLabel };
590 return { root, search, meta, list, prev, next, pageLabel };
418}
591}
419
592
593function buildStarterEquipmentPanel ({ onAddInventory })
594{
595 const root = document.createElement("div");
596 root.className = "starter-equipment-panel";
597
598 const hint = document.createElement("p");
599 hint.className = "hint";
600 hint.textContent = "Applies only to newly created characters. Items are marked “Received from the gods”. Existing characters are unchanged.";
601
602 const equipTitle = document.createElement("h3");
603 equipTitle.textContent = "Equipped";
604 const equipRoot = document.createElement("div");
605 equipRoot.className = "starter-equip-list";
606
607 const invTitle = document.createElement("h3");
608 invTitle.textContent = "Inventory";
609 const invRoot = document.createElement("div");
610 invRoot.className = "starter-inv-list";
611
612 const add = document.createElement("button");
613 add.type = "button";
614 add.textContent = "Add inventory item";
615 add.addEventListener("click", () => onAddInventory?.());
616
617 root.append(hint, equipTitle, equipRoot, invTitle, invRoot, add);
618 return { root, equipRoot, invRoot };
619}
620
621function listAllItems ()
622{
623 return Object.values(ITEM_DEFINITIONS)
624 .map((def) => ({
625 itemId: def.itemId,
626 displayName: def.displayName ?? `#${def.itemId}`
627 }))
628 .sort((a, b) => a.displayName.localeCompare(b.displayName));
629}
630
631function listItemsForSlot (slot)
632{
633 return Object.values(ITEM_DEFINITIONS)
634 .filter((def) => def.equipment?.slot === slot)
635 .map((def) => ({
636 itemId: def.itemId,
637 displayName: def.displayName ?? `#${def.itemId}`
638 }))
639 .sort((a, b) => a.displayName.localeCompare(b.displayName));
640}
641
420function syncTabs (form, activeCategory)
642function syncTabs (form, activeCategory)
421{
643{
422 for (const tab of form.querySelectorAll(".settings-tab"))
644 for (const tab of form.querySelectorAll(".settings-tab"))
client/src/play/barber.js added +83 −0
@@ -0,0 +1,83 @@
1 import { bindHairControls } from "./hairControls.js";
2
3 export function initBarber ({
4 socket,
5 MessageType,
6 resolveSpriteUrl,
7 getInventoryBag,
8 onSuppressWorldClick
9 })
10 {
11 const backdrop = document.getElementById("barber-backdrop");
12 const panel = document.getElementById("barber-panel");
13 const statusEl = document.getElementById("barber-status");
14 let open = false;
15 let sex = "male";
16
17 const controls = bindHairControls({
18 root: panel,
19 resolveSpriteUrl,
20 getSex: () => sex,
21 getBag: () => getInventoryBag?.() ?? null,
22 hideHeadgear: true
23 });
24
25 function suppressWorldClick ()
26 {
27 onSuppressWorldClick?.();
28 }
29
30 document.getElementById("barber-close")?.addEventListener("click", () => close());
31 backdrop?.addEventListener("mousedown", (event) =>
32 {
33 event.preventDefault();
34 suppressWorldClick();
35 });
36 backdrop?.addEventListener("click", () => close());
37 panel?.addEventListener("mousedown", (event) =>
38 {
39 event.stopPropagation();
40 suppressWorldClick();
41 });
42 document.getElementById("barber-apply")?.addEventListener("click", () =>
43 {
44 statusEl.textContent = "Saving…";
45 socket.send({
46 type: MessageType.setHair,
47 hair: controls.currentHair()
48 });
49 });
50
51 function close ()
52 {
53 if (!open)
54 { return; }
55 open = false;
56 panel.hidden = true;
57 backdrop.hidden = true;
58 statusEl.textContent = "";
59 socket.send({ type: MessageType.closeBarber });
60 }
61
62 return {
63 isOpen: () => open,
64 isBlocking: () => open,
65 close,
66 handleSnapshot (message)
67 {
68 open = true;
69 panel.hidden = false;
70 backdrop.hidden = false;
71 sex = message.sex === "female" ? "female" : "male";
72 controls.fillStyles();
73 controls.setHair(message.hair);
74 statusEl.textContent = message.message ?? "";
75 },
76 handleClosed ()
77 {
78 open = false;
79 panel.hidden = true;
80 backdrop.hidden = true;
81 }
82 };
83 }
@@ -0,0 +1,83 @@
1import { bindHairControls } from "./hairControls.js";
2
3export function initBarber ({
4 socket,
5 MessageType,
6 resolveSpriteUrl,
7 getInventoryBag,
8 onSuppressWorldClick
9})
10{
11 const backdrop = document.getElementById("barber-backdrop");
12 const panel = document.getElementById("barber-panel");
13 const statusEl = document.getElementById("barber-status");
14 let open = false;
15 let sex = "male";
16
17 const controls = bindHairControls({
18 root: panel,
19 resolveSpriteUrl,
20 getSex: () => sex,
21 getBag: () => getInventoryBag?.() ?? null,
22 hideHeadgear: true
23 });
24
25 function suppressWorldClick ()
26 {
27 onSuppressWorldClick?.();
28 }
29
30 document.getElementById("barber-close")?.addEventListener("click", () => close());
31 backdrop?.addEventListener("mousedown", (event) =>
32 {
33 event.preventDefault();
34 suppressWorldClick();
35 });
36 backdrop?.addEventListener("click", () => close());
37 panel?.addEventListener("mousedown", (event) =>
38 {
39 event.stopPropagation();
40 suppressWorldClick();
41 });
42 document.getElementById("barber-apply")?.addEventListener("click", () =>
43 {
44 statusEl.textContent = "Saving…";
45 socket.send({
46 type: MessageType.setHair,
47 hair: controls.currentHair()
48 });
49 });
50
51 function close ()
52 {
53 if (!open)
54 { return; }
55 open = false;
56 panel.hidden = true;
57 backdrop.hidden = true;
58 statusEl.textContent = "";
59 socket.send({ type: MessageType.closeBarber });
60 }
61
62 return {
63 isOpen: () => open,
64 isBlocking: () => open,
65 close,
66 handleSnapshot (message)
67 {
68 open = true;
69 panel.hidden = false;
70 backdrop.hidden = false;
71 sex = message.sex === "female" ? "female" : "male";
72 controls.fillStyles();
73 controls.setHair(message.hair);
74 statusEl.textContent = message.message ?? "";
75 },
76 handleClosed ()
77 {
78 open = false;
79 panel.hidden = true;
80 backdrop.hidden = true;
81 }
82 };
83}
client/src/play/bounty.js added +191 −0
@@ -0,0 +1,191 @@
1 export function initBounty ({
2 socket,
3 MessageType,
4 resolveSpriteUrl,
5 onSuppressWorldClick
6 })
7 {
8 const backdrop = document.getElementById("bounty-backdrop");
9 const panel = document.getElementById("bounty-panel");
10 const statusEl = document.getElementById("bounty-status");
11 const myAmountEl = document.getElementById("bounty-my-amount");
12 const previewEl = document.getElementById("bounty-preview");
13 const targetLabel = document.getElementById("bounty-target-label");
14 const targetAmount = document.getElementById("bounty-target-amount");
15 const firstInput = document.getElementById("bounty-search-first");
16 const lastInput = document.getElementById("bounty-search-last");
17 const amountInput = document.getElementById("bounty-amount");
18 const tabs = [...document.querySelectorAll(".bounty-tab")];
19 const panes = [...document.querySelectorAll(".bounty-pane")];
20
21 let open = false;
22 /** @type {null | { characterId: number, firstName: string, lastName: string, amountCopper: number }} */
23 let target = null;
24 let activeTab = "place";
25
26 function suppressWorldClick ()
27 {
28 onSuppressWorldClick?.();
29 }
30
31 function setTab (tab)
32 {
33 activeTab = tab;
34 for (const button of tabs)
35 { button.classList.toggle("active", button.dataset.tab === tab); }
36 for (const pane of panes)
37 { pane.hidden = pane.dataset.pane !== tab; }
38 }
39
40 for (const button of tabs)
41 { button.addEventListener("click", () => setTab(button.dataset.tab)); }
42
43 document.getElementById("bounty-close")?.addEventListener("click", () => close());
44 backdrop?.addEventListener("mousedown", (event) =>
45 {
46 event.preventDefault();
47 suppressWorldClick();
48 });
49 backdrop?.addEventListener("click", () => close());
50 panel?.addEventListener("mousedown", (event) =>
51 {
52 event.stopPropagation();
53 suppressWorldClick();
54 });
55
56 document.getElementById("bounty-search")?.addEventListener("click", () =>
57 {
58 const firstName = firstInput.value.trim();
59 const lastName = lastInput.value.trim();
60 if (!firstName || !lastName)
61 {
62 statusEl.textContent = "Enter a first and last name.";
63 return;
64 }
65 statusEl.textContent = "Searching…";
66 socket.send({ type: MessageType.getCharacterBounty, firstName, lastName });
67 });
68
69 document.getElementById("bounty-raise")?.addEventListener("click", () =>
70 {
71 if (!target)
72 {
73 statusEl.textContent = "Search for a target first.";
74 return;
75 }
76 const amountCopper = Math.floor(Number(amountInput.value) || 0);
77 if (amountCopper <= 0)
78 {
79 statusEl.textContent = "Enter a positive coin amount.";
80 return;
81 }
82 statusEl.textContent = "Placing bounty…";
83 socket.send({
84 type: MessageType.raiseBounty,
85 firstName: target.firstName,
86 lastName: target.lastName,
87 amountCopper
88 });
89 });
90
91 function clearTarget ()
92 {
93 target = null;
94 previewEl.replaceChildren();
95 targetLabel.textContent = "No target selected.";
96 targetAmount.textContent = "";
97 }
98
99 function renderPreview (layers)
100 {
101 previewEl.replaceChildren();
102 const wrap = document.createElement("div");
103 wrap.className = "char-preview";
104 for (const layer of layers ?? [])
105 {
106 const url = resolveSpriteUrl?.(layer.sprite);
107 if (!url)
108 { continue; }
109 const img = document.createElement("img");
110 img.src = url;
111 img.alt = "";
112 if (layer.tint)
113 { img.style.filter = `opacity(1)`; }
114 wrap.append(img);
115 }
116 previewEl.append(wrap);
117 }
118
119 function showTarget (entry)
120 {
121 if (!entry)
122 {
123 clearTarget();
124 statusEl.textContent = "No adventurer by that name.";
125 return;
126 }
127 target = {
128 characterId: entry.characterId,
129 firstName: entry.firstName,
130 lastName: entry.lastName,
131 amountCopper: entry.amountCopper | 0
132 };
133 targetLabel.textContent = `${entry.firstName} ${entry.lastName}`;
134 targetAmount.textContent = (entry.amountCopper | 0) > 0
135 ? `Current bounty: ${entry.amountLabel ?? entry.amountCopper}`
136 : "No bounty yet.";
137 renderPreview(entry.layers);
138 statusEl.textContent = "";
139 }
140
141 function close ()
142 {
143 if (!open)
144 { return; }
145 open = false;
146 panel.hidden = true;
147 backdrop.hidden = true;
148 clearTarget();
149 statusEl.textContent = "";
150 socket.send({ type: MessageType.closeBounty });
151 }
152
153 return {
154 isOpen: () => open,
155 isBlocking: () => open,
156 close,
157 handleSnapshot (message)
158 {
159 open = true;
160 panel.hidden = false;
161 backdrop.hidden = false;
162 setTab(activeTab);
163 myAmountEl.textContent = (message.myAmountCopper | 0) > 0
164 ? message.myAmountLabel || String(message.myAmountCopper)
165 : "None";
166 if (message.raised)
167 {
168 statusEl.textContent = message.raised.message ?? "Bounty updated.";
169 if (target && target.characterId === message.raised.characterId)
170 {
171 target.amountCopper = message.raised.amountCopper | 0;
172 targetAmount.textContent = `Current bounty: ${message.raised.amountLabel}`;
173 }
174 }
175 else if (message.message && !(message.myAmountCopper > 0 && activeTab === "mine"))
176 { statusEl.textContent = ""; }
177 },
178 handleCharacterBounty (message)
179 {
180 if (!open)
181 { return; }
182 showTarget(message.target);
183 },
184 handleClosed ()
185 {
186 open = false;
187 panel.hidden = true;
188 backdrop.hidden = true;
189 }
190 };
191 }
@@ -0,0 +1,191 @@
1export function initBounty ({
2 socket,
3 MessageType,
4 resolveSpriteUrl,
5 onSuppressWorldClick
6})
7{
8 const backdrop = document.getElementById("bounty-backdrop");
9 const panel = document.getElementById("bounty-panel");
10 const statusEl = document.getElementById("bounty-status");
11 const myAmountEl = document.getElementById("bounty-my-amount");
12 const previewEl = document.getElementById("bounty-preview");
13 const targetLabel = document.getElementById("bounty-target-label");
14 const targetAmount = document.getElementById("bounty-target-amount");
15 const firstInput = document.getElementById("bounty-search-first");
16 const lastInput = document.getElementById("bounty-search-last");
17 const amountInput = document.getElementById("bounty-amount");
18 const tabs = [...document.querySelectorAll(".bounty-tab")];
19 const panes = [...document.querySelectorAll(".bounty-pane")];
20
21 let open = false;
22 /** @type {null | { characterId: number, firstName: string, lastName: string, amountCopper: number }} */
23 let target = null;
24 let activeTab = "place";
25
26 function suppressWorldClick ()
27 {
28 onSuppressWorldClick?.();
29 }
30
31 function setTab (tab)
32 {
33 activeTab = tab;
34 for (const button of tabs)
35 { button.classList.toggle("active", button.dataset.tab === tab); }
36 for (const pane of panes)
37 { pane.hidden = pane.dataset.pane !== tab; }
38 }
39
40 for (const button of tabs)
41 { button.addEventListener("click", () => setTab(button.dataset.tab)); }
42
43 document.getElementById("bounty-close")?.addEventListener("click", () => close());
44 backdrop?.addEventListener("mousedown", (event) =>
45 {
46 event.preventDefault();
47 suppressWorldClick();
48 });
49 backdrop?.addEventListener("click", () => close());
50 panel?.addEventListener("mousedown", (event) =>
51 {
52 event.stopPropagation();
53 suppressWorldClick();
54 });
55
56 document.getElementById("bounty-search")?.addEventListener("click", () =>
57 {
58 const firstName = firstInput.value.trim();
59 const lastName = lastInput.value.trim();
60 if (!firstName || !lastName)
61 {
62 statusEl.textContent = "Enter a first and last name.";
63 return;
64 }
65 statusEl.textContent = "Searching…";
66 socket.send({ type: MessageType.getCharacterBounty, firstName, lastName });
67 });
68
69 document.getElementById("bounty-raise")?.addEventListener("click", () =>
70 {
71 if (!target)
72 {
73 statusEl.textContent = "Search for a target first.";
74 return;
75 }
76 const amountCopper = Math.floor(Number(amountInput.value) || 0);
77 if (amountCopper <= 0)
78 {
79 statusEl.textContent = "Enter a positive coin amount.";
80 return;
81 }
82 statusEl.textContent = "Placing bounty…";
83 socket.send({
84 type: MessageType.raiseBounty,
85 firstName: target.firstName,
86 lastName: target.lastName,
87 amountCopper
88 });
89 });
90
91 function clearTarget ()
92 {
93 target = null;
94 previewEl.replaceChildren();
95 targetLabel.textContent = "No target selected.";
96 targetAmount.textContent = "";
97 }
98
99 function renderPreview (layers)
100 {
101 previewEl.replaceChildren();
102 const wrap = document.createElement("div");
103 wrap.className = "char-preview";
104 for (const layer of layers ?? [])
105 {
106 const url = resolveSpriteUrl?.(layer.sprite);
107 if (!url)
108 { continue; }
109 const img = document.createElement("img");
110 img.src = url;
111 img.alt = "";
112 if (layer.tint)
113 { img.style.filter = `opacity(1)`; }
114 wrap.append(img);
115 }
116 previewEl.append(wrap);
117 }
118
119 function showTarget (entry)
120 {
121 if (!entry)
122 {
123 clearTarget();
124 statusEl.textContent = "No adventurer by that name.";
125 return;
126 }
127 target = {
128 characterId: entry.characterId,
129 firstName: entry.firstName,
130 lastName: entry.lastName,
131 amountCopper: entry.amountCopper | 0
132 };
133 targetLabel.textContent = `${entry.firstName} ${entry.lastName}`;
134 targetAmount.textContent = (entry.amountCopper | 0) > 0
135 ? `Current bounty: ${entry.amountLabel ?? entry.amountCopper}`
136 : "No bounty yet.";
137 renderPreview(entry.layers);
138 statusEl.textContent = "";
139 }
140
141 function close ()
142 {
143 if (!open)
144 { return; }
145 open = false;
146 panel.hidden = true;
147 backdrop.hidden = true;
148 clearTarget();
149 statusEl.textContent = "";
150 socket.send({ type: MessageType.closeBounty });
151 }
152
153 return {
154 isOpen: () => open,
155 isBlocking: () => open,
156 close,
157 handleSnapshot (message)
158 {
159 open = true;
160 panel.hidden = false;
161 backdrop.hidden = false;
162 setTab(activeTab);
163 myAmountEl.textContent = (message.myAmountCopper | 0) > 0
164 ? message.myAmountLabel || String(message.myAmountCopper)
165 : "None";
166 if (message.raised)
167 {
168 statusEl.textContent = message.raised.message ?? "Bounty updated.";
169 if (target && target.characterId === message.raised.characterId)
170 {
171 target.amountCopper = message.raised.amountCopper | 0;
172 targetAmount.textContent = `Current bounty: ${message.raised.amountLabel}`;
173 }
174 }
175 else if (message.message && !(message.myAmountCopper > 0 && activeTab === "mine"))
176 { statusEl.textContent = ""; }
177 },
178 handleCharacterBounty (message)
179 {
180 if (!open)
181 { return; }
182 showTarget(message.target);
183 },
184 handleClosed ()
185 {
186 open = false;
187 panel.hidden = true;
188 backdrop.hidden = true;
189 }
190 };
191}
client/src/play/characterPreview.js added +68 −0
@@ -0,0 +1,68 @@
1 import { applyMagentaTintToImageData } from "/shared/render/tint.js";
2 import { layersForHairPreview } from "/shared/appearance/hair.js";
3
4 /**
5 * Draw stacked character layers (body + hair + optional gear) onto a canvas.
6 * Magenta hair/gear tints applied in 2D for UI previews.
7 */
8 export async function paintCharacterPreview (canvas, {
9 sex,
10 bag = null,
11 hair = null,
12 hideHeadgear = true,
13 resolveSpriteUrl,
14 scale = 4
15 } = {})
16 {
17 if (!canvas)
18 { return; }
19 const layers = layersForHairPreview(sex, bag, hair, { hideHeadgear });
20 const images = [];
21 for (const layer of layers)
22 {
23 const url = resolveSpriteUrl?.(layer.sprite);
24 if (!url)
25 { continue; }
26 const img = await loadHtmlImage(url);
27 images.push({ img, tint: layer.tint ?? null });
28 }
29 if (!images.length)
30 { return; }
31 const w = images[0].img.naturalWidth || images[0].img.width;
32 const h = images[0].img.naturalHeight || images[0].img.height;
33 canvas.width = w * scale;
34 canvas.height = h * scale;
35 const ctx = canvas.getContext("2d");
36 ctx.imageSmoothingEnabled = false;
37 ctx.clearRect(0, 0, canvas.width, canvas.height);
38 for (const entry of images)
39 {
40 const source = entry.tint ? tintedCanvas(entry.img, entry.tint) : entry.img;
41 ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
42 }
43 }
44
45 function loadHtmlImage (url)
46 {
47 return new Promise((resolve, reject) =>
48 {
49 const img = new Image();
50 img.onload = () => resolve(img);
51 img.onerror = () => reject(new Error(`Failed to load ${url}`));
52 img.src = url;
53 });
54 }
55
56 function tintedCanvas (sourceImg, tintRgb)
57 {
58 const canvas = document.createElement("canvas");
59 canvas.width = sourceImg.naturalWidth || sourceImg.width;
60 canvas.height = sourceImg.naturalHeight || sourceImg.height;
61 const ctx = canvas.getContext("2d");
62 ctx.imageSmoothingEnabled = false;
63 ctx.drawImage(sourceImg, 0, 0);
64 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
65 applyMagentaTintToImageData(imageData, tintRgb);
66 ctx.putImageData(imageData, 0, 0);
67 return canvas;
68 }
@@ -0,0 +1,68 @@
1import { applyMagentaTintToImageData } from "/shared/render/tint.js";
2import { layersForHairPreview } from "/shared/appearance/hair.js";
3
4/**
5 * Draw stacked character layers (body + hair + optional gear) onto a canvas.
6 * Magenta hair/gear tints applied in 2D for UI previews.
7 */
8export async function paintCharacterPreview (canvas, {
9 sex,
10 bag = null,
11 hair = null,
12 hideHeadgear = true,
13 resolveSpriteUrl,
14 scale = 4
15} = {})
16{
17 if (!canvas)
18 { return; }
19 const layers = layersForHairPreview(sex, bag, hair, { hideHeadgear });
20 const images = [];
21 for (const layer of layers)
22 {
23 const url = resolveSpriteUrl?.(layer.sprite);
24 if (!url)
25 { continue; }
26 const img = await loadHtmlImage(url);
27 images.push({ img, tint: layer.tint ?? null });
28 }
29 if (!images.length)
30 { return; }
31 const w = images[0].img.naturalWidth || images[0].img.width;
32 const h = images[0].img.naturalHeight || images[0].img.height;
33 canvas.width = w * scale;
34 canvas.height = h * scale;
35 const ctx = canvas.getContext("2d");
36 ctx.imageSmoothingEnabled = false;
37 ctx.clearRect(0, 0, canvas.width, canvas.height);
38 for (const entry of images)
39 {
40 const source = entry.tint ? tintedCanvas(entry.img, entry.tint) : entry.img;
41 ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
42 }
43}
44
45function loadHtmlImage (url)
46{
47 return new Promise((resolve, reject) =>
48 {
49 const img = new Image();
50 img.onload = () => resolve(img);
51 img.onerror = () => reject(new Error(`Failed to load ${url}`));
52 img.src = url;
53 });
54}
55
56function tintedCanvas (sourceImg, tintRgb)
57{
58 const canvas = document.createElement("canvas");
59 canvas.width = sourceImg.naturalWidth || sourceImg.width;
60 canvas.height = sourceImg.naturalHeight || sourceImg.height;
61 const ctx = canvas.getContext("2d");
62 ctx.imageSmoothingEnabled = false;
63 ctx.drawImage(sourceImg, 0, 0);
64 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
65 applyMagentaTintToImageData(imageData, tintRgb);
66 ctx.putImageData(imageData, 0, 0);
67 return canvas;
68}
client/src/play/graphicsSettings.js added +92 −0
@@ -0,0 +1,92 @@
1 import {
2 ViewDistance,
3 LightingMode,
4 BloomMode,
5 loadGraphicsSettings,
6 saveGraphicsSettings,
7 normalizeGraphicsSettings
8 } from "/shared/graphics/settings.js";
9
10 /**
11 * @param {{
12 * onChange: (settings: { viewDistance: string, lighting: string, bloom: string }) => void
13 * }} options
14 */
15 export function initGraphicsSettings ({ onChange })
16 {
17 const toggle = document.getElementById("settings-toggle");
18 const panel = document.getElementById("settings-panel");
19 const closeBtn = document.getElementById("settings-close");
20 if (!toggle || !panel)
21 {
22 return {
23 getSettings: () => loadGraphicsSettings(),
24 apply: () => {},
25 close: () => {}
26 };
27 }
28
29 let settings = loadGraphicsSettings();
30
31 function syncButtons ()
32 {
33 for (const btn of panel.querySelectorAll("[data-graphics-key]"))
34 {
35 const key = btn.getAttribute("data-graphics-key");
36 const value = btn.getAttribute("data-graphics-value");
37 btn.classList.toggle("active", settings[key] === value);
38 }
39 }
40
41 function emit ()
42 {
43 settings = saveGraphicsSettings(settings);
44 syncButtons();
45 onChange?.(settings);
46 }
47
48 function open ()
49 {
50 panel.hidden = false;
51 syncButtons();
52 }
53
54 function close ()
55 {
56 panel.hidden = true;
57 }
58
59 toggle.addEventListener("click", () =>
60 {
61 if (panel.hidden)
62 { open(); }
63 else
64 { close(); }
65 });
66 closeBtn?.addEventListener("click", close);
67
68 panel.addEventListener("click", (event) =>
69 {
70 const btn = event.target.closest("[data-graphics-key]");
71 if (!btn || !panel.contains(btn))
72 { return; }
73 const key = btn.getAttribute("data-graphics-key");
74 const value = btn.getAttribute("data-graphics-value");
75 if (!key || !value)
76 { return; }
77 settings = normalizeGraphicsSettings({ ...settings, [key]: value });
78 emit();
79 });
80
81 syncButtons();
82
83 return {
84 getSettings: () => ({ ...settings }),
85 /** Re-apply current settings (e.g. after world enter). */
86 apply ()
87 { onChange?.(settings); },
88 close
89 };
90 }
91
92 export { ViewDistance, LightingMode, BloomMode };
@@ -0,0 +1,92 @@
1import {
2 ViewDistance,
3 LightingMode,
4 BloomMode,
5 loadGraphicsSettings,
6 saveGraphicsSettings,
7 normalizeGraphicsSettings
8} from "/shared/graphics/settings.js";
9
10/**
11 * @param {{
12 * onChange: (settings: { viewDistance: string, lighting: string, bloom: string }) => void
13 * }} options
14 */
15export function initGraphicsSettings ({ onChange })
16{
17 const toggle = document.getElementById("settings-toggle");
18 const panel = document.getElementById("settings-panel");
19 const closeBtn = document.getElementById("settings-close");
20 if (!toggle || !panel)
21 {
22 return {
23 getSettings: () => loadGraphicsSettings(),
24 apply: () => {},
25 close: () => {}
26 };
27 }
28
29 let settings = loadGraphicsSettings();
30
31 function syncButtons ()
32 {
33 for (const btn of panel.querySelectorAll("[data-graphics-key]"))
34 {
35 const key = btn.getAttribute("data-graphics-key");
36 const value = btn.getAttribute("data-graphics-value");
37 btn.classList.toggle("active", settings[key] === value);
38 }
39 }
40
41 function emit ()
42 {
43 settings = saveGraphicsSettings(settings);
44 syncButtons();
45 onChange?.(settings);
46 }
47
48 function open ()
49 {
50 panel.hidden = false;
51 syncButtons();
52 }
53
54 function close ()
55 {
56 panel.hidden = true;
57 }
58
59 toggle.addEventListener("click", () =>
60 {
61 if (panel.hidden)
62 { open(); }
63 else
64 { close(); }
65 });
66 closeBtn?.addEventListener("click", close);
67
68 panel.addEventListener("click", (event) =>
69 {
70 const btn = event.target.closest("[data-graphics-key]");
71 if (!btn || !panel.contains(btn))
72 { return; }
73 const key = btn.getAttribute("data-graphics-key");
74 const value = btn.getAttribute("data-graphics-value");
75 if (!key || !value)
76 { return; }
77 settings = normalizeGraphicsSettings({ ...settings, [key]: value });
78 emit();
79 });
80
81 syncButtons();
82
83 return {
84 getSettings: () => ({ ...settings }),
85 /** Re-apply current settings (e.g. after world enter). */
86 apply ()
87 { onChange?.(settings); },
88 close
89 };
90}
91
92export { ViewDistance, LightingMode, BloomMode };
client/src/play/hairControls.js added +136 −0
@@ -0,0 +1,136 @@
1 import {
2 DEFAULT_HAIR_STYLE,
3 DEFAULT_HAIR_HUE,
4 DEFAULT_HAIR_SATURATION,
5 DEFAULT_HAIR_DARKNESS,
6 listHairStyles,
7 normalizeHairSliders,
8 hairColorFromSliders
9 } from "/shared/appearance/hair.js";
10 import { paintCharacterPreview } from "./characterPreview.js";
11
12 /**
13 * Shared hair style + HSL controls with live character preview.
14 */
15 export function bindHairControls ({
16 root,
17 resolveSpriteUrl,
18 getSex,
19 getBag = () => null,
20 hideHeadgear = true,
21 onChange = null
22 })
23 {
24 const preview = root.querySelector("[data-hair-preview]");
25 const styleSelect = root.querySelector("[data-hair-style]");
26 const hue = root.querySelector("[data-hair-hue]");
27 const saturation = root.querySelector("[data-hair-saturation]");
28 const darkness = root.querySelector("[data-hair-darkness]");
29 const swatch = root.querySelector("[data-hair-swatch]");
30 let paintToken = 0;
31
32 function currentHair ()
33 {
34 const style = styleSelect?.value === "none" ? null : (styleSelect?.value || DEFAULT_HAIR_STYLE);
35 const sliders = normalizeHairSliders({
36 hue: hue?.value,
37 saturation: Number(saturation?.value) / 100,
38 darkness: Number(darkness?.value) / 100
39 });
40 return {
41 style,
42 ...sliders,
43 color: hairColorFromSliders(sliders)
44 };
45 }
46
47 function fillStyles ()
48 {
49 if (!styleSelect)
50 { return; }
51 const sex = getSex?.() === "female" ? "female" : "male";
52 const selected = styleSelect.value || DEFAULT_HAIR_STYLE;
53 styleSelect.replaceChildren();
54 const none = document.createElement("option");
55 none.value = "none";
56 none.textContent = "Bald";
57 styleSelect.append(none);
58 for (const style of listHairStyles(sex))
59 {
60 const option = document.createElement("option");
61 option.value = style;
62 option.textContent = style.replace("hair-", "Style ");
63 styleSelect.append(option);
64 }
65 if ([...styleSelect.options].some((option) => option.value === selected))
66 { styleSelect.value = selected; }
67 else
68 { styleSelect.value = DEFAULT_HAIR_STYLE; }
69 }
70
71 function syncSwatch ()
72 {
73 if (!swatch)
74 { return; }
75 const color = hairColorFromSliders(currentHair());
76 swatch.style.background = `rgb(${Math.round(color.r * 255)}, ${Math.round(color.g * 255)}, ${Math.round(color.b * 255)})`;
77 }
78
79 async function refreshPreview ()
80 {
81 const token = ++paintToken;
82 syncSwatch();
83 onChange?.(currentHair());
84 if (!preview)
85 { return; }
86 try
87 {
88 await paintCharacterPreview(preview, {
89 sex: getSex?.() === "female" ? "female" : "male",
90 bag: getBag?.() ?? null,
91 hair: currentHair(),
92 hideHeadgear,
93 resolveSpriteUrl,
94 scale: 4
95 });
96 }
97 catch (error)
98 {
99 if (token === paintToken)
100 { console.warn(error); }
101 }
102 }
103
104 function setHair (hair)
105 {
106 fillStyles();
107 if (styleSelect)
108 { styleSelect.value = hair?.style ?? DEFAULT_HAIR_STYLE; }
109 const sliders = normalizeHairSliders(hair ?? {});
110 if (hue)
111 { hue.value = String(Math.round(sliders.hue)); }
112 if (saturation)
113 { saturation.value = String(Math.round(sliders.saturation * 100)); }
114 if (darkness)
115 { darkness.value = String(Math.round(sliders.darkness * 100)); }
116 void refreshPreview();
117 }
118
119 fillStyles();
120 if (hue && !hue.value)
121 { hue.value = String(DEFAULT_HAIR_HUE); }
122 if (saturation && !saturation.value)
123 { saturation.value = String(Math.round(DEFAULT_HAIR_SATURATION * 100)); }
124 if (darkness && !darkness.value)
125 { darkness.value = String(Math.round(DEFAULT_HAIR_DARKNESS * 100)); }
126
127 for (const el of [styleSelect, hue, saturation, darkness])
128 { el?.addEventListener("input", () => void refreshPreview()); }
129
130 return {
131 currentHair,
132 setHair,
133 fillStyles,
134 refreshPreview
135 };
136 }
@@ -0,0 +1,136 @@
1import {
2 DEFAULT_HAIR_STYLE,
3 DEFAULT_HAIR_HUE,
4 DEFAULT_HAIR_SATURATION,
5 DEFAULT_HAIR_DARKNESS,
6 listHairStyles,
7 normalizeHairSliders,
8 hairColorFromSliders
9} from "/shared/appearance/hair.js";
10import { paintCharacterPreview } from "./characterPreview.js";
11
12/**
13 * Shared hair style + HSL controls with live character preview.
14 */
15export function bindHairControls ({
16 root,
17 resolveSpriteUrl,
18 getSex,
19 getBag = () => null,
20 hideHeadgear = true,
21 onChange = null
22})
23{
24 const preview = root.querySelector("[data-hair-preview]");
25 const styleSelect = root.querySelector("[data-hair-style]");
26 const hue = root.querySelector("[data-hair-hue]");
27 const saturation = root.querySelector("[data-hair-saturation]");
28 const darkness = root.querySelector("[data-hair-darkness]");
29 const swatch = root.querySelector("[data-hair-swatch]");
30 let paintToken = 0;
31
32 function currentHair ()
33 {
34 const style = styleSelect?.value === "none" ? null : (styleSelect?.value || DEFAULT_HAIR_STYLE);
35 const sliders = normalizeHairSliders({
36 hue: hue?.value,
37 saturation: Number(saturation?.value) / 100,
38 darkness: Number(darkness?.value) / 100
39 });
40 return {
41 style,
42 ...sliders,
43 color: hairColorFromSliders(sliders)
44 };
45 }
46
47 function fillStyles ()
48 {
49 if (!styleSelect)
50 { return; }
51 const sex = getSex?.() === "female" ? "female" : "male";
52 const selected = styleSelect.value || DEFAULT_HAIR_STYLE;
53 styleSelect.replaceChildren();
54 const none = document.createElement("option");
55 none.value = "none";
56 none.textContent = "Bald";
57 styleSelect.append(none);
58 for (const style of listHairStyles(sex))
59 {
60 const option = document.createElement("option");
61 option.value = style;
62 option.textContent = style.replace("hair-", "Style ");
63 styleSelect.append(option);
64 }
65 if ([...styleSelect.options].some((option) => option.value === selected))
66 { styleSelect.value = selected; }
67 else
68 { styleSelect.value = DEFAULT_HAIR_STYLE; }
69 }
70
71 function syncSwatch ()
72 {
73 if (!swatch)
74 { return; }
75 const color = hairColorFromSliders(currentHair());
76 swatch.style.background = `rgb(${Math.round(color.r * 255)}, ${Math.round(color.g * 255)}, ${Math.round(color.b * 255)})`;
77 }
78
79 async function refreshPreview ()
80 {
81 const token = ++paintToken;
82 syncSwatch();
83 onChange?.(currentHair());
84 if (!preview)
85 { return; }
86 try
87 {
88 await paintCharacterPreview(preview, {
89 sex: getSex?.() === "female" ? "female" : "male",
90 bag: getBag?.() ?? null,
91 hair: currentHair(),
92 hideHeadgear,
93 resolveSpriteUrl,
94 scale: 4
95 });
96 }
97 catch (error)
98 {
99 if (token === paintToken)
100 { console.warn(error); }
101 }
102 }
103
104 function setHair (hair)
105 {
106 fillStyles();
107 if (styleSelect)
108 { styleSelect.value = hair?.style ?? DEFAULT_HAIR_STYLE; }
109 const sliders = normalizeHairSliders(hair ?? {});
110 if (hue)
111 { hue.value = String(Math.round(sliders.hue)); }
112 if (saturation)
113 { saturation.value = String(Math.round(sliders.saturation * 100)); }
114 if (darkness)
115 { darkness.value = String(Math.round(sliders.darkness * 100)); }
116 void refreshPreview();
117 }
118
119 fillStyles();
120 if (hue && !hue.value)
121 { hue.value = String(DEFAULT_HAIR_HUE); }
122 if (saturation && !saturation.value)
123 { saturation.value = String(Math.round(DEFAULT_HAIR_SATURATION * 100)); }
124 if (darkness && !darkness.value)
125 { darkness.value = String(Math.round(DEFAULT_HAIR_DARKNESS * 100)); }
126
127 for (const el of [styleSelect, hue, saturation, darkness])
128 { el?.addEventListener("input", () => void refreshPreview()); }
129
130 return {
131 currentHair,
132 setHair,
133 fillStyles,
134 refreshPreview
135 };
136}
client/src/play/health.js added +60 −0
@@ -0,0 +1,60 @@
1 export function initHealth ()
2 {
3 let vitals = document.getElementById("vitals");
4 if (!vitals)
5 {
6 vitals = document.createElement("div");
7 vitals.id = "vitals";
8 vitals.hidden = true;
9 document.body.append(vitals);
10 }
11 let bar = document.getElementById("health-bar");
12 if (!bar)
13 {
14 bar = document.createElement("div");
15 bar.id = "health-bar";
16 bar.innerHTML = '<div id="health-bar-fill"></div><span id="health-bar-label" class="health-bar-label"></span>';
17 vitals.prepend(bar);
18 }
19 else if (bar.parentElement !== vitals)
20 { vitals.prepend(bar); }
21 const fill = document.getElementById("health-bar-fill");
22 const label = document.getElementById("health-bar-label");
23
24 let current = 1;
25 let max = 1;
26
27 function render ()
28 {
29 const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;
30 fill.style.transform = `scaleY(${ratio})`;
31 label.textContent = `${Math.ceil(current)}/${max | 0}`;
32 bar.classList.toggle("empty", current <= 0);
33 bar.classList.toggle("low", current > 0 && current / max <= 0.25);
34 }
35
36 return {
37 show ()
38 {
39 vitals.hidden = false;
40 bar.hidden = false;
41 render();
42 },
43 hide ()
44 {
45 bar.hidden = true;
46 },
47 apply (message)
48 {
49 if (message?.max != null)
50 { max = Math.max(1, message.max | 0); }
51 if (message?.current != null)
52 { current = Math.max(0, Number(message.current) || 0); }
53 render();
54 },
55 getCurrent ()
56 { return current; },
57 getMax ()
58 { return max; }
59 };
60 }
@@ -0,0 +1,60 @@
1export function initHealth ()
2{
3 let vitals = document.getElementById("vitals");
4 if (!vitals)
5 {
6 vitals = document.createElement("div");
7 vitals.id = "vitals";
8 vitals.hidden = true;
9 document.body.append(vitals);
10 }
11 let bar = document.getElementById("health-bar");
12 if (!bar)
13 {
14 bar = document.createElement("div");
15 bar.id = "health-bar";
16 bar.innerHTML = '<div id="health-bar-fill"></div><span id="health-bar-label" class="health-bar-label"></span>';
17 vitals.prepend(bar);
18 }
19 else if (bar.parentElement !== vitals)
20 { vitals.prepend(bar); }
21 const fill = document.getElementById("health-bar-fill");
22 const label = document.getElementById("health-bar-label");
23
24 let current = 1;
25 let max = 1;
26
27 function render ()
28 {
29 const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;
30 fill.style.transform = `scaleY(${ratio})`;
31 label.textContent = `${Math.ceil(current)}/${max | 0}`;
32 bar.classList.toggle("empty", current <= 0);
33 bar.classList.toggle("low", current > 0 && current / max <= 0.25);
34 }
35
36 return {
37 show ()
38 {
39 vitals.hidden = false;
40 bar.hidden = false;
41 render();
42 },
43 hide ()
44 {
45 bar.hidden = true;
46 },
47 apply (message)
48 {
49 if (message?.max != null)
50 { max = Math.max(1, message.max | 0); }
51 if (message?.current != null)
52 { current = Math.max(0, Number(message.current) || 0); }
53 render();
54 },
55 getCurrent ()
56 { return current; },
57 getMax ()
58 { return max; }
59 };
60}
client/src/play/inventory.js +4 −0
@@ -861,6 +861,10 @@ export function initInventory ({
861 861 {
862 862 return bag.inventory ?? [];
863 863 },
864 getEquipment ()
865 {
866 return bag.equipment?.slots ?? bag.equipment ?? {};
867 },
864 868 handleInventory (message)
865 869 {
866 870 bag = { ...bag, ...message };
@@ -861,6 +861,10 @@ export function initInventory ({
861 {
861 {
862 return bag.inventory ?? [];
862 return bag.inventory ?? [];
863 },
863 },
864 getEquipment ()
865 {
866 return bag.equipment?.slots ?? bag.equipment ?? {};
867 },
864 handleInventory (message)
868 handleInventory (message)
865 {
869 {
866 bag = { ...bag, ...message };
870 bag = { ...bag, ...message };
client/src/play/main.js +249 −4
@@ -10,11 +10,17 @@ import { initSkills } from "./skills.js";
10 10 import { initCrafting } from "./crafting.js";
11 11 import { initAlchemy } from "./alchemy.js";
12 12 import { initStamina } from "./stamina.js";
13 import { initHealth } from "./health.js";
14 import { initStatusEffects } from "./statusEffects.js";
13 15 import { initContextMenu } from "./contextMenu.js";
14 16 import { initDeath } from "./death.js";
15 17 import { initToasts } from "./toasts.js";
16 18 import { initShop } from "./shop.js";
17 19 import { initMarket } from "./market.js";
20 import { initBounty } from "./bounty.js";
21 import { initBarber } from "./barber.js";
22 import { bindHairControls } from "./hairControls.js";
23 import { initGraphicsSettings } from "./graphicsSettings.js";
18 24 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
19 25 import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
20 26 import { formatQuantity } from "/shared/items/formatQuantity.js";
@@ -33,6 +39,7 @@ let socket;
33 39 let session = null;
34 40 let playing = false;
35 41 let view = null;
42 let graphicsSettingsUi = null;
36 43 let scene = null;
37 44 let gait = GAIT.walk;
38 45 let catalog = { grounds: {}, blocks: {} };
@@ -43,11 +50,16 @@ let skills;
43 50 let crafting;
44 51 let alchemy;
45 52 let staminaUi;
53 let healthUi;
54 let statusEffectsUi;
46 55 let contextMenu;
47 56 let death;
48 57 let toasts;
49 58 let shop;
50 59 let market;
60 let bounty;
61 let barber;
62 let createHairControls;
51 63 let pendingPickup = null;
52 64 /** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
53 65 let pendingInteract = null;
@@ -99,7 +111,20 @@ function uiBlocked ()
99 111 {
100 112 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
101 113 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
102 || market?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
114 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
115 || contextMenu?.isOpen() || death?.isBlocking());
116 }
117
118 function applyGraphicsSettings (settings)
119 {
120 view?.setGraphicsPrefs(settings);
121 if (socket && playing)
122 {
123 socket.send({
124 type: MessageType.setGraphicsSettings,
125 viewDistance: settings.viewDistance
126 });
127 }
103 128 }
104 129
105 130 function clearPendingPickup ()
@@ -197,6 +222,28 @@ function requestOpenMarket (tileX, tileY)
197 222 { approachAdjacentTile(tileX, tileY); }
198 223 }
199 224
225 function requestOpenBounty (tileX, tileY)
226 {
227 clearAllPendingActions();
228 pendingInteract = { kind: "bounty", tileX, tileY };
229 const local = view?.entities.get(view.localEntityId);
230 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
231 { flushPendingInteract(); }
232 else
233 { approachAdjacentTile(tileX, tileY); }
234 }
235
236 function requestOpenBarber (tileX, tileY)
237 {
238 clearAllPendingActions();
239 pendingInteract = { kind: "barber", tileX, tileY };
240 const local = view?.entities.get(view.localEntityId);
241 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
242 { flushPendingInteract(); }
243 else
244 { approachAdjacentTile(tileX, tileY); }
245 }
246
200 247 function requestOpenCauldron (tileX, tileY)
201 248 {
202 249 clearAllPendingActions();
@@ -300,6 +347,24 @@ function flushPendingInteract ()
300 347 return;
301 348 }
302 349
350 if (pendingInteract.kind === "bounty")
351 {
352 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
353 { return; }
354 socket.send({ type: MessageType.openBounty });
355 clearPendingInteract();
356 return;
357 }
358
359 if (pendingInteract.kind === "barber")
360 {
361 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
362 { return; }
363 socket.send({ type: MessageType.openBarber });
364 clearPendingInteract();
365 return;
366 }
367
303 368 if (pendingInteract.kind === "cauldron")
304 369 {
305 370 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -467,6 +532,10 @@ function handleLeftClick (mouseX, mouseY)
467 532 { requestOpenBank(tile.tileX, tile.tileY); }
468 533 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
469 534 { requestOpenMarket(tile.tileX, tile.tileY); }
535 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
536 { requestOpenBounty(tile.tileX, tile.tileY); }
537 else if (isBarberTile(view, tile.tileX, tile.tileY))
538 { requestOpenBarber(tile.tileX, tile.tileY); }
470 539 else if (isCauldronTile(view, tile.tileX, tile.tileY))
471 540 { requestOpenCauldron(tile.tileX, tile.tileY); }
472 541 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
@@ -588,6 +657,22 @@ function handleRightClick (event, mouseX, mouseY)
588 657 });
589 658 }
590 659
660 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
661 {
662 items.push({
663 label: "Bounty Office",
664 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
665 });
666 }
667
668 if (isBarberTile(view, tile.tileX, tile.tileY))
669 {
670 items.push({
671 label: "Barber",
672 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
673 });
674 }
675
591 676 if (isCauldronTile(view, tile.tileX, tile.tileY))
592 677 {
593 678 items.push({
@@ -702,18 +787,31 @@ function startPlay (payload)
702 787 playing = true;
703 788 overlay.hidden = true;
704 789 hud.hidden = false;
790 const settingsToggle = document.getElementById("settings-toggle");
791 if (settingsToggle)
792 { settingsToggle.hidden = false; }
705 793 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
706 794 gait = payload.gait ?? GAIT.walk;
707 795 document.getElementById("gait").textContent = gait;
708 796 staminaUi?.show();
797 healthUi?.show();
798 statusEffectsUi?.show();
709 799 if (payload.stamina != null)
710 800 { staminaUi?.apply(payload.stamina); }
801 if (payload.health != null || payload.maxHealth != null)
802 {
803 healthUi?.apply({
804 current: payload.health ?? healthUi.getCurrent?.(),
805 max: payload.maxHealth ?? healthUi.getMax?.()
806 });
807 }
711 808 if (!scene)
712 809 {
713 810 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
714 811 game.loadScene(scene);
715 812 useNearestNeighbour(scene, game.images);
716 813 view = new WorldView(game, scene, catalog);
814 graphicsSettingsUi?.apply();
717 815 const ticker = new GameObject(0, 0, null, 10);
718 816 ticker.update = (dt) =>
719 817 {
@@ -791,8 +889,11 @@ function startPlay (payload)
791 889 payload.firstName,
792 890 payload.lastName,
793 891 payload.characterId,
794 payload.layers
892 payload.layers,
893 payload.health,
894 payload.maxHealth
795 895 );
896 graphicsSettingsUi?.apply();
796 897 }
797 898
798 899 async function main ()
@@ -800,6 +901,24 @@ async function main ()
800 901 catalog = await loadSpriteCatalog();
801 902 await preloadCatalogImages(game, catalog);
802 903 applySpriteSheets(game.images, catalog);
904 createHairControls = bindHairControls({
905 root: document.getElementById("create-hair"),
906 resolveSpriteUrl (name)
907 {
908 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
909 },
910 getSex: () => document.getElementById("sex")?.value ?? "male",
911 hideHeadgear: true
912 });
913 document.getElementById("sex")?.addEventListener("change", () =>
914 {
915 createHairControls?.fillStyles();
916 void createHairControls?.refreshPreview();
917 });
918 void createHairControls?.refreshPreview();
919 graphicsSettingsUi = initGraphicsSettings({
920 onChange: applyGraphicsSettings
921 });
803 922 social = initSocial({
804 923 socket: { send (payload) { socket.send(payload); } },
805 924 MessageType
@@ -845,6 +964,8 @@ async function main ()
845 964 }
846 965 });
847 966 staminaUi = initStamina();
967 healthUi = initHealth();
968 statusEffectsUi = initStatusEffects();
848 969 toasts = initToasts();
849 970 shop = initShop({
850 971 socket: { send (payload) { socket.send(payload); } },
@@ -872,6 +993,31 @@ async function main ()
872 993 return inventory?.getInventorySlots?.() ?? [];
873 994 }
874 995 });
996 bounty = initBounty({
997 socket: { send (payload) { socket.send(payload); } },
998 MessageType,
999 onSuppressWorldClick: consumeWorldClick,
1000 resolveSpriteUrl (name)
1001 {
1002 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1003 }
1004 });
1005 barber = initBarber({
1006 socket: { send (payload) { socket.send(payload); } },
1007 MessageType,
1008 onSuppressWorldClick: consumeWorldClick,
1009 resolveSpriteUrl (name)
1010 {
1011 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1012 },
1013 getInventoryBag ()
1014 {
1015 return {
1016 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1017 inventory: inventory?.getInventorySlots?.() ?? []
1018 };
1019 }
1020 });
875 1021 chat = initChat({
876 1022 socket: { send (payload) { socket.send(payload); } },
877 1023 MessageType,
@@ -898,6 +1044,7 @@ async function main ()
898 1044 { overlay.hidden = false; }
899 1045 break;
900 1046 case MessageType.enterWorld:
1047 closeCreateModal();
901 1048 startPlay(message);
902 1049 inventory?.setLocalCharacterId(message.characterId);
903 1050 break;
@@ -961,6 +1108,10 @@ async function main ()
961 1108 document.getElementById("gait").textContent = gait;
962 1109 }
963 1110 break;
1111 case MessageType.statusEffects:
1112 view?.setLocalBlind(!!message.blind);
1113 statusEffectsUi?.apply(message);
1114 break;
964 1115 case MessageType.bankSnapshot:
965 1116 inventory?.handleBank(message);
966 1117 break;
@@ -1021,6 +1172,22 @@ async function main ()
1021 1172 market?.handleTrade(message);
1022 1173 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1023 1174 break;
1175 case MessageType.bountySnapshot:
1176 bounty?.handleSnapshot(message);
1177 break;
1178 case MessageType.closeBounty:
1179 bounty?.handleClosed(message);
1180 break;
1181 case MessageType.characterBounty:
1182 bounty?.handleCharacterBounty(message);
1183 social?.handleCharacterBounty(message);
1184 break;
1185 case MessageType.barberSnapshot:
1186 barber?.handleSnapshot(message);
1187 break;
1188 case MessageType.closeBarber:
1189 barber?.handleClosed(message);
1190 break;
1024 1191 case MessageType.itemBubble:
1025 1192 chat?.showItemBubble(message);
1026 1193 break;
@@ -1031,6 +1198,23 @@ async function main ()
1031 1198 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1032 1199 view?.flashDamage(message.targetId);
1033 1200 view?.spawnDamageNumber(message.targetId, message.damage);
1201 if (message.targetId === view?.localEntityId)
1202 {
1203 healthUi?.apply({
1204 current: message.health,
1205 max: message.maxHealth
1206 });
1207 }
1208 break;
1209 case MessageType.entityHealth:
1210 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1211 if (message.entityId === view?.localEntityId)
1212 {
1213 healthUi?.apply({
1214 current: message.health,
1215 max: message.maxHealth
1216 });
1217 }
1034 1218 break;
1035 1219 case MessageType.skillLevelUp:
1036 1220 view?.spawnSkillLevelUp(message.entityId, message);
@@ -1044,10 +1228,22 @@ async function main ()
1044 1228 clearAllPendingActions();
1045 1229 contextMenu?.hide();
1046 1230 death?.show();
1231 if (message.entityId === view?.localEntityId)
1232 {
1233 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
1234 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
1235 }
1047 1236 break;
1048 1237 case MessageType.playerRespawned:
1049 1238 death?.hide();
1050 1239 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1240 if (message.entityId === view?.localEntityId)
1241 {
1242 healthUi?.apply({
1243 current: message.health,
1244 max: message.maxHealth
1245 });
1246 }
1051 1247 if (message.stamina != null || message.maxStamina != null)
1052 1248 {
1053 1249 staminaUi?.apply({
@@ -1060,7 +1256,14 @@ async function main ()
1060 1256 if (playing)
1061 1257 { toasts?.show(message.message); }
1062 1258 else
1063 { showError(message.message); }
1259 {
1260 const createPanel = document.getElementById("create-panel");
1261 const createError = document.getElementById("create-error");
1262 if (createPanel && !createPanel.hidden && createError)
1263 { createError.textContent = message.message ?? ""; }
1264 else
1265 { showError(message.message); }
1266 }
1064 1267 social?.showError(message.message);
1065 1268 break;
1066 1269 case MessageType.toast:
@@ -1098,10 +1301,14 @@ function returnToMenu (reason = "")
1098 1301 crafting?.reset();
1099 1302 alchemy?.reset();
1100 1303 staminaUi?.hide();
1304 healthUi?.hide();
1305 statusEffectsUi?.hide();
1101 1306 skills?.hide();
1102 1307 contextMenu?.hide();
1103 1308 death?.reset();
1104 1309 shop?.close({ notifyServer: false });
1310 bounty?.close();
1311 barber?.close();
1105 1312 hideWorldTooltip();
1106 1313 if (view)
1107 1314 {
@@ -1113,19 +1320,47 @@ function returnToMenu (reason = "")
1113 1320 }
1114 1321 overlay.hidden = false;
1115 1322 hud.hidden = true;
1323 const settingsToggle = document.getElementById("settings-toggle");
1324 if (settingsToggle)
1325 { settingsToggle.hidden = true; }
1326 graphicsSettingsUi?.close();
1116 1327 if (reason)
1117 1328 { statusEl.textContent = reason; }
1118 1329 }
1119 1330
1331 document.getElementById("create-character-open")?.addEventListener("click", () =>
1332 {
1333 showError("");
1334 const createError = document.getElementById("create-error");
1335 if (createError)
1336 { createError.textContent = ""; }
1337 document.getElementById("create-backdrop").hidden = false;
1338 document.getElementById("create-panel").hidden = false;
1339 void createHairControls?.refreshPreview();
1340 });
1341
1342 function closeCreateModal ()
1343 {
1344 document.getElementById("create-backdrop").hidden = true;
1345 document.getElementById("create-panel").hidden = true;
1346 }
1347
1348 document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
1349 document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
1350
1120 1351 document.getElementById("create-form").addEventListener("submit", (event) =>
1121 1352 {
1122 1353 event.preventDefault();
1123 1354 showError("");
1355 const createError = document.getElementById("create-error");
1356 if (createError)
1357 { createError.textContent = ""; }
1124 1358 socket.send({
1125 1359 type: MessageType.createCharacter,
1126 1360 firstName: document.getElementById("first-name").value,
1127 1361 lastName: document.getElementById("last-name").value,
1128 sex: document.getElementById("sex").value
1362 sex: document.getElementById("sex").value,
1363 hair: createHairControls?.currentHair?.() ?? null
1129 1364 });
1130 1365 });
1131 1366
@@ -1151,6 +1386,16 @@ function isMarketplaceTile (view, tileX, tileY)
1151 1386 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1152 1387 }
1153 1388
1389 function isBountyOfficeTile (view, tileX, tileY)
1390 {
1391 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
1392 }
1393
1394 function isBarberTile (view, tileX, tileY)
1395 {
1396 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
1397 }
1398
1154 1399 function isCauldronTile (view, tileX, tileY)
1155 1400 {
1156 1401 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
@@ -10,11 +10,17 @@ import { initSkills } from "./skills.js";
10import { initCrafting } from "./crafting.js";
10import { initCrafting } from "./crafting.js";
11import { initAlchemy } from "./alchemy.js";
11import { initAlchemy } from "./alchemy.js";
12import { initStamina } from "./stamina.js";
12import { initStamina } from "./stamina.js";
13import { initHealth } from "./health.js";
14import { initStatusEffects } from "./statusEffects.js";
13import { initContextMenu } from "./contextMenu.js";
15import { initContextMenu } from "./contextMenu.js";
14import { initDeath } from "./death.js";
16import { initDeath } from "./death.js";
15import { initToasts } from "./toasts.js";
17import { initToasts } from "./toasts.js";
16import { initShop } from "./shop.js";
18import { initShop } from "./shop.js";
17import { initMarket } from "./market.js";
19import { initMarket } from "./market.js";
20import { initBounty } from "./bounty.js";
21import { initBarber } from "./barber.js";
22import { bindHairControls } from "./hairControls.js";
23import { initGraphicsSettings } from "./graphicsSettings.js";
18import { CraftingStationId } from "/shared/definitions/craftingStations.js";
24import { CraftingStationId } from "/shared/definitions/craftingStations.js";
19import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
25import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
20import { formatQuantity } from "/shared/items/formatQuantity.js";
26import { formatQuantity } from "/shared/items/formatQuantity.js";
@@ -33,6 +39,7 @@ let socket;
33let session = null;
39let session = null;
34let playing = false;
40let playing = false;
35let view = null;
41let view = null;
42let graphicsSettingsUi = null;
36let scene = null;
43let scene = null;
37let gait = GAIT.walk;
44let gait = GAIT.walk;
38let catalog = { grounds: {}, blocks: {} };
45let catalog = { grounds: {}, blocks: {} };
@@ -43,11 +50,16 @@ let skills;
43let crafting;
50let crafting;
44let alchemy;
51let alchemy;
45let staminaUi;
52let staminaUi;
53let healthUi;
54let statusEffectsUi;
46let contextMenu;
55let contextMenu;
47let death;
56let death;
48let toasts;
57let toasts;
49let shop;
58let shop;
50let market;
59let market;
60let bounty;
61let barber;
62let createHairControls;
51let pendingPickup = null;
63let pendingPickup = null;
52/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
64/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
53let pendingInteract = null;
65let pendingInteract = null;
@@ -99,7 +111,20 @@ function uiBlocked ()
99{
111{
100 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
112 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
101 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
113 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
102 || market?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
114 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
115 || contextMenu?.isOpen() || death?.isBlocking());
116}
117
118function applyGraphicsSettings (settings)
119{
120 view?.setGraphicsPrefs(settings);
121 if (socket && playing)
122 {
123 socket.send({
124 type: MessageType.setGraphicsSettings,
125 viewDistance: settings.viewDistance
126 });
127 }
103}
128}
104
129
105function clearPendingPickup ()
130function clearPendingPickup ()
@@ -197,6 +222,28 @@ function requestOpenMarket (tileX, tileY)
197 { approachAdjacentTile(tileX, tileY); }
222 { approachAdjacentTile(tileX, tileY); }
198}
223}
199
224
225function requestOpenBounty (tileX, tileY)
226{
227 clearAllPendingActions();
228 pendingInteract = { kind: "bounty", tileX, tileY };
229 const local = view?.entities.get(view.localEntityId);
230 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
231 { flushPendingInteract(); }
232 else
233 { approachAdjacentTile(tileX, tileY); }
234}
235
236function requestOpenBarber (tileX, tileY)
237{
238 clearAllPendingActions();
239 pendingInteract = { kind: "barber", tileX, tileY };
240 const local = view?.entities.get(view.localEntityId);
241 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
242 { flushPendingInteract(); }
243 else
244 { approachAdjacentTile(tileX, tileY); }
245}
246
200function requestOpenCauldron (tileX, tileY)
247function requestOpenCauldron (tileX, tileY)
201{
248{
202 clearAllPendingActions();
249 clearAllPendingActions();
@@ -300,6 +347,24 @@ function flushPendingInteract ()
300 return;
347 return;
301 }
348 }
302
349
350 if (pendingInteract.kind === "bounty")
351 {
352 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
353 { return; }
354 socket.send({ type: MessageType.openBounty });
355 clearPendingInteract();
356 return;
357 }
358
359 if (pendingInteract.kind === "barber")
360 {
361 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
362 { return; }
363 socket.send({ type: MessageType.openBarber });
364 clearPendingInteract();
365 return;
366 }
367
303 if (pendingInteract.kind === "cauldron")
368 if (pendingInteract.kind === "cauldron")
304 {
369 {
305 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
370 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -467,6 +532,10 @@ function handleLeftClick (mouseX, mouseY)
467 { requestOpenBank(tile.tileX, tile.tileY); }
532 { requestOpenBank(tile.tileX, tile.tileY); }
468 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
533 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
469 { requestOpenMarket(tile.tileX, tile.tileY); }
534 { requestOpenMarket(tile.tileX, tile.tileY); }
535 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
536 { requestOpenBounty(tile.tileX, tile.tileY); }
537 else if (isBarberTile(view, tile.tileX, tile.tileY))
538 { requestOpenBarber(tile.tileX, tile.tileY); }
470 else if (isCauldronTile(view, tile.tileX, tile.tileY))
539 else if (isCauldronTile(view, tile.tileX, tile.tileY))
471 { requestOpenCauldron(tile.tileX, tile.tileY); }
540 { requestOpenCauldron(tile.tileX, tile.tileY); }
472 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
541 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
@@ -588,6 +657,22 @@ function handleRightClick (event, mouseX, mouseY)
588 });
657 });
589 }
658 }
590
659
660 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
661 {
662 items.push({
663 label: "Bounty Office",
664 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
665 });
666 }
667
668 if (isBarberTile(view, tile.tileX, tile.tileY))
669 {
670 items.push({
671 label: "Barber",
672 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
673 });
674 }
675
591 if (isCauldronTile(view, tile.tileX, tile.tileY))
676 if (isCauldronTile(view, tile.tileX, tile.tileY))
592 {
677 {
593 items.push({
678 items.push({
@@ -702,18 +787,31 @@ function startPlay (payload)
702 playing = true;
787 playing = true;
703 overlay.hidden = true;
788 overlay.hidden = true;
704 hud.hidden = false;
789 hud.hidden = false;
790 const settingsToggle = document.getElementById("settings-toggle");
791 if (settingsToggle)
792 { settingsToggle.hidden = false; }
705 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
793 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
706 gait = payload.gait ?? GAIT.walk;
794 gait = payload.gait ?? GAIT.walk;
707 document.getElementById("gait").textContent = gait;
795 document.getElementById("gait").textContent = gait;
708 staminaUi?.show();
796 staminaUi?.show();
797 healthUi?.show();
798 statusEffectsUi?.show();
709 if (payload.stamina != null)
799 if (payload.stamina != null)
710 { staminaUi?.apply(payload.stamina); }
800 { staminaUi?.apply(payload.stamina); }
801 if (payload.health != null || payload.maxHealth != null)
802 {
803 healthUi?.apply({
804 current: payload.health ?? healthUi.getCurrent?.(),
805 max: payload.maxHealth ?? healthUi.getMax?.()
806 });
807 }
711 if (!scene)
808 if (!scene)
712 {
809 {
713 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
810 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
714 game.loadScene(scene);
811 game.loadScene(scene);
715 useNearestNeighbour(scene, game.images);
812 useNearestNeighbour(scene, game.images);
716 view = new WorldView(game, scene, catalog);
813 view = new WorldView(game, scene, catalog);
814 graphicsSettingsUi?.apply();
717 const ticker = new GameObject(0, 0, null, 10);
815 const ticker = new GameObject(0, 0, null, 10);
718 ticker.update = (dt) =>
816 ticker.update = (dt) =>
719 {
817 {
@@ -791,8 +889,11 @@ function startPlay (payload)
791 payload.firstName,
889 payload.firstName,
792 payload.lastName,
890 payload.lastName,
793 payload.characterId,
891 payload.characterId,
794 payload.layers
892 payload.layers,
893 payload.health,
894 payload.maxHealth
795 );
895 );
896 graphicsSettingsUi?.apply();
796}
897}
797
898
798async function main ()
899async function main ()
@@ -800,6 +901,24 @@ async function main ()
800 catalog = await loadSpriteCatalog();
901 catalog = await loadSpriteCatalog();
801 await preloadCatalogImages(game, catalog);
902 await preloadCatalogImages(game, catalog);
802 applySpriteSheets(game.images, catalog);
903 applySpriteSheets(game.images, catalog);
904 createHairControls = bindHairControls({
905 root: document.getElementById("create-hair"),
906 resolveSpriteUrl (name)
907 {
908 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
909 },
910 getSex: () => document.getElementById("sex")?.value ?? "male",
911 hideHeadgear: true
912 });
913 document.getElementById("sex")?.addEventListener("change", () =>
914 {
915 createHairControls?.fillStyles();
916 void createHairControls?.refreshPreview();
917 });
918 void createHairControls?.refreshPreview();
919 graphicsSettingsUi = initGraphicsSettings({
920 onChange: applyGraphicsSettings
921 });
803 social = initSocial({
922 social = initSocial({
804 socket: { send (payload) { socket.send(payload); } },
923 socket: { send (payload) { socket.send(payload); } },
805 MessageType
924 MessageType
@@ -845,6 +964,8 @@ async function main ()
845 }
964 }
846 });
965 });
847 staminaUi = initStamina();
966 staminaUi = initStamina();
967 healthUi = initHealth();
968 statusEffectsUi = initStatusEffects();
848 toasts = initToasts();
969 toasts = initToasts();
849 shop = initShop({
970 shop = initShop({
850 socket: { send (payload) { socket.send(payload); } },
971 socket: { send (payload) { socket.send(payload); } },
@@ -872,6 +993,31 @@ async function main ()
872 return inventory?.getInventorySlots?.() ?? [];
993 return inventory?.getInventorySlots?.() ?? [];
873 }
994 }
874 });
995 });
996 bounty = initBounty({
997 socket: { send (payload) { socket.send(payload); } },
998 MessageType,
999 onSuppressWorldClick: consumeWorldClick,
1000 resolveSpriteUrl (name)
1001 {
1002 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1003 }
1004 });
1005 barber = initBarber({
1006 socket: { send (payload) { socket.send(payload); } },
1007 MessageType,
1008 onSuppressWorldClick: consumeWorldClick,
1009 resolveSpriteUrl (name)
1010 {
1011 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1012 },
1013 getInventoryBag ()
1014 {
1015 return {
1016 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1017 inventory: inventory?.getInventorySlots?.() ?? []
1018 };
1019 }
1020 });
875 chat = initChat({
1021 chat = initChat({
876 socket: { send (payload) { socket.send(payload); } },
1022 socket: { send (payload) { socket.send(payload); } },
877 MessageType,
1023 MessageType,
@@ -898,6 +1044,7 @@ async function main ()
898 { overlay.hidden = false; }
1044 { overlay.hidden = false; }
899 break;
1045 break;
900 case MessageType.enterWorld:
1046 case MessageType.enterWorld:
1047 closeCreateModal();
901 startPlay(message);
1048 startPlay(message);
902 inventory?.setLocalCharacterId(message.characterId);
1049 inventory?.setLocalCharacterId(message.characterId);
903 break;
1050 break;
@@ -961,6 +1108,10 @@ async function main ()
961 document.getElementById("gait").textContent = gait;
1108 document.getElementById("gait").textContent = gait;
962 }
1109 }
963 break;
1110 break;
1111 case MessageType.statusEffects:
1112 view?.setLocalBlind(!!message.blind);
1113 statusEffectsUi?.apply(message);
1114 break;
964 case MessageType.bankSnapshot:
1115 case MessageType.bankSnapshot:
965 inventory?.handleBank(message);
1116 inventory?.handleBank(message);
966 break;
1117 break;
@@ -1021,6 +1172,22 @@ async function main ()
1021 market?.handleTrade(message);
1172 market?.handleTrade(message);
1022 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1173 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1023 break;
1174 break;
1175 case MessageType.bountySnapshot:
1176 bounty?.handleSnapshot(message);
1177 break;
1178 case MessageType.closeBounty:
1179 bounty?.handleClosed(message);
1180 break;
1181 case MessageType.characterBounty:
1182 bounty?.handleCharacterBounty(message);
1183 social?.handleCharacterBounty(message);
1184 break;
1185 case MessageType.barberSnapshot:
1186 barber?.handleSnapshot(message);
1187 break;
1188 case MessageType.closeBarber:
1189 barber?.handleClosed(message);
1190 break;
1024 case MessageType.itemBubble:
1191 case MessageType.itemBubble:
1025 chat?.showItemBubble(message);
1192 chat?.showItemBubble(message);
1026 break;
1193 break;
@@ -1031,6 +1198,23 @@ async function main ()
1031 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1198 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1032 view?.flashDamage(message.targetId);
1199 view?.flashDamage(message.targetId);
1033 view?.spawnDamageNumber(message.targetId, message.damage);
1200 view?.spawnDamageNumber(message.targetId, message.damage);
1201 if (message.targetId === view?.localEntityId)
1202 {
1203 healthUi?.apply({
1204 current: message.health,
1205 max: message.maxHealth
1206 });
1207 }
1208 break;
1209 case MessageType.entityHealth:
1210 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1211 if (message.entityId === view?.localEntityId)
1212 {
1213 healthUi?.apply({
1214 current: message.health,
1215 max: message.maxHealth
1216 });
1217 }
1034 break;
1218 break;
1035 case MessageType.skillLevelUp:
1219 case MessageType.skillLevelUp:
1036 view?.spawnSkillLevelUp(message.entityId, message);
1220 view?.spawnSkillLevelUp(message.entityId, message);
@@ -1044,10 +1228,22 @@ async function main ()
1044 clearAllPendingActions();
1228 clearAllPendingActions();
1045 contextMenu?.hide();
1229 contextMenu?.hide();
1046 death?.show();
1230 death?.show();
1231 if (message.entityId === view?.localEntityId)
1232 {
1233 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
1234 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
1235 }
1047 break;
1236 break;
1048 case MessageType.playerRespawned:
1237 case MessageType.playerRespawned:
1049 death?.hide();
1238 death?.hide();
1050 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1239 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1240 if (message.entityId === view?.localEntityId)
1241 {
1242 healthUi?.apply({
1243 current: message.health,
1244 max: message.maxHealth
1245 });
1246 }
1051 if (message.stamina != null || message.maxStamina != null)
1247 if (message.stamina != null || message.maxStamina != null)
1052 {
1248 {
1053 staminaUi?.apply({
1249 staminaUi?.apply({
@@ -1060,7 +1256,14 @@ async function main ()
1060 if (playing)
1256 if (playing)
1061 { toasts?.show(message.message); }
1257 { toasts?.show(message.message); }
1062 else
1258 else
1063 { showError(message.message); }
1259 {
1260 const createPanel = document.getElementById("create-panel");
1261 const createError = document.getElementById("create-error");
1262 if (createPanel && !createPanel.hidden && createError)
1263 { createError.textContent = message.message ?? ""; }
1264 else
1265 { showError(message.message); }
1266 }
1064 social?.showError(message.message);
1267 social?.showError(message.message);
1065 break;
1268 break;
1066 case MessageType.toast:
1269 case MessageType.toast:
@@ -1098,10 +1301,14 @@ function returnToMenu (reason = "")
1098 crafting?.reset();
1301 crafting?.reset();
1099 alchemy?.reset();
1302 alchemy?.reset();
1100 staminaUi?.hide();
1303 staminaUi?.hide();
1304 healthUi?.hide();
1305 statusEffectsUi?.hide();
1101 skills?.hide();
1306 skills?.hide();
1102 contextMenu?.hide();
1307 contextMenu?.hide();
1103 death?.reset();
1308 death?.reset();
1104 shop?.close({ notifyServer: false });
1309 shop?.close({ notifyServer: false });
1310 bounty?.close();
1311 barber?.close();
1105 hideWorldTooltip();
1312 hideWorldTooltip();
1106 if (view)
1313 if (view)
1107 {
1314 {
@@ -1113,19 +1320,47 @@ function returnToMenu (reason = "")
1113 }
1320 }
1114 overlay.hidden = false;
1321 overlay.hidden = false;
1115 hud.hidden = true;
1322 hud.hidden = true;
1323 const settingsToggle = document.getElementById("settings-toggle");
1324 if (settingsToggle)
1325 { settingsToggle.hidden = true; }
1326 graphicsSettingsUi?.close();
1116 if (reason)
1327 if (reason)
1117 { statusEl.textContent = reason; }
1328 { statusEl.textContent = reason; }
1118}
1329}
1119
1330
1331document.getElementById("create-character-open")?.addEventListener("click", () =>
1332{
1333 showError("");
1334 const createError = document.getElementById("create-error");
1335 if (createError)
1336 { createError.textContent = ""; }
1337 document.getElementById("create-backdrop").hidden = false;
1338 document.getElementById("create-panel").hidden = false;
1339 void createHairControls?.refreshPreview();
1340});
1341
1342function closeCreateModal ()
1343{
1344 document.getElementById("create-backdrop").hidden = true;
1345 document.getElementById("create-panel").hidden = true;
1346}
1347
1348document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
1349document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
1350
1120document.getElementById("create-form").addEventListener("submit", (event) =>
1351document.getElementById("create-form").addEventListener("submit", (event) =>
1121{
1352{
1122 event.preventDefault();
1353 event.preventDefault();
1123 showError("");
1354 showError("");
1355 const createError = document.getElementById("create-error");
1356 if (createError)
1357 { createError.textContent = ""; }
1124 socket.send({
1358 socket.send({
1125 type: MessageType.createCharacter,
1359 type: MessageType.createCharacter,
1126 firstName: document.getElementById("first-name").value,
1360 firstName: document.getElementById("first-name").value,
1127 lastName: document.getElementById("last-name").value,
1361 lastName: document.getElementById("last-name").value,
1128 sex: document.getElementById("sex").value
1362 sex: document.getElementById("sex").value,
1363 hair: createHairControls?.currentHair?.() ?? null
1129 });
1364 });
1130});
1365});
1131
1366
@@ -1151,6 +1386,16 @@ function isMarketplaceTile (view, tileX, tileY)
1151 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1386 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1152}
1387}
1153
1388
1389function isBountyOfficeTile (view, tileX, tileY)
1390{
1391 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
1392}
1393
1394function isBarberTile (view, tileX, tileY)
1395{
1396 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
1397}
1398
1154function isCauldronTile (view, tileX, tileY)
1399function isCauldronTile (view, tileX, tileY)
1155{
1400{
1156 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
1401 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
client/src/play/social.js +32 −0
@@ -4,6 +4,7 @@ export function initSocial ({ socket, MessageType })
4 4 const inspect = document.getElementById("inspect-modal");
5 5 const inspectBackdrop = document.getElementById("inspect-backdrop");
6 6 const inspectName = document.getElementById("inspect-name");
7 const inspectBounty = document.getElementById("inspect-bounty");
7 8 const inspectAction = document.getElementById("inspect-action");
8 9 const inspectError = document.getElementById("inspect-error");
9 10 const friendsPanel = document.getElementById("friends-panel");
@@ -28,6 +29,11 @@ export function initSocial ({ socket, MessageType })
28 29 inspect.hidden = true;
29 30 inspectBackdrop.hidden = true;
30 31 inspectError.textContent = "";
32 if (inspectBounty)
33 {
34 inspectBounty.hidden = true;
35 inspectBounty.textContent = "";
36 }
31 37 }
32 38
33 39 function relation (characterId)
@@ -171,9 +177,35 @@ export function initSocial ({ socket, MessageType })
171 177 };
172 178 open = true;
173 179 inspectError.textContent = "";
180 if (inspectBounty)
181 {
182 inspectBounty.hidden = true;
183 inspectBounty.textContent = "";
184 }
174 185 inspect.hidden = false;
175 186 inspectBackdrop.hidden = false;
176 187 renderInspect();
188 socket.send({
189 type: MessageType.getCharacterBounty,
190 characterId: entity.characterId
191 });
192 },
193 handleCharacterBounty (message)
194 {
195 if (!open || !inspected || !inspectBounty)
196 { return; }
197 const target = message.target;
198 if (!target || target.characterId !== inspected.characterId)
199 { return; }
200 const amount = target.amountCopper | 0;
201 if (amount <= 0)
202 {
203 inspectBounty.hidden = true;
204 inspectBounty.textContent = "";
205 return;
206 }
207 inspectBounty.hidden = false;
208 inspectBounty.textContent = `Bounty: ${target.amountLabel ?? amount}`;
177 209 },
178 210 hideInspect,
179 211 reset ()
@@ -4,6 +4,7 @@ export function initSocial ({ socket, MessageType })
4 const inspect = document.getElementById("inspect-modal");
4 const inspect = document.getElementById("inspect-modal");
5 const inspectBackdrop = document.getElementById("inspect-backdrop");
5 const inspectBackdrop = document.getElementById("inspect-backdrop");
6 const inspectName = document.getElementById("inspect-name");
6 const inspectName = document.getElementById("inspect-name");
7 const inspectBounty = document.getElementById("inspect-bounty");
7 const inspectAction = document.getElementById("inspect-action");
8 const inspectAction = document.getElementById("inspect-action");
8 const inspectError = document.getElementById("inspect-error");
9 const inspectError = document.getElementById("inspect-error");
9 const friendsPanel = document.getElementById("friends-panel");
10 const friendsPanel = document.getElementById("friends-panel");
@@ -28,6 +29,11 @@ export function initSocial ({ socket, MessageType })
28 inspect.hidden = true;
29 inspect.hidden = true;
29 inspectBackdrop.hidden = true;
30 inspectBackdrop.hidden = true;
30 inspectError.textContent = "";
31 inspectError.textContent = "";
32 if (inspectBounty)
33 {
34 inspectBounty.hidden = true;
35 inspectBounty.textContent = "";
36 }
31 }
37 }
32
38
33 function relation (characterId)
39 function relation (characterId)
@@ -171,9 +177,35 @@ export function initSocial ({ socket, MessageType })
171 };
177 };
172 open = true;
178 open = true;
173 inspectError.textContent = "";
179 inspectError.textContent = "";
180 if (inspectBounty)
181 {
182 inspectBounty.hidden = true;
183 inspectBounty.textContent = "";
184 }
174 inspect.hidden = false;
185 inspect.hidden = false;
175 inspectBackdrop.hidden = false;
186 inspectBackdrop.hidden = false;
176 renderInspect();
187 renderInspect();
188 socket.send({
189 type: MessageType.getCharacterBounty,
190 characterId: entity.characterId
191 });
192 },
193 handleCharacterBounty (message)
194 {
195 if (!open || !inspected || !inspectBounty)
196 { return; }
197 const target = message.target;
198 if (!target || target.characterId !== inspected.characterId)
199 { return; }
200 const amount = target.amountCopper | 0;
201 if (amount <= 0)
202 {
203 inspectBounty.hidden = true;
204 inspectBounty.textContent = "";
205 return;
206 }
207 inspectBounty.hidden = false;
208 inspectBounty.textContent = `Bounty: ${target.amountLabel ?? amount}`;
177 },
209 },
178 hideInspect,
210 hideInspect,
179 reset ()
211 reset ()
client/src/play/stamina.js +13 −4
@@ -1,14 +1,23 @@
1 1 export function initStamina ()
2 2 {
3 let vitals = document.getElementById("vitals");
4 if (!vitals)
5 {
6 vitals = document.createElement("div");
7 vitals.id = "vitals";
8 vitals.hidden = true;
9 document.body.append(vitals);
10 }
3 11 let bar = document.getElementById("stamina-bar");
4 12 if (!bar)
5 13 {
6 14 bar = document.createElement("div");
7 15 bar.id = "stamina-bar";
8 bar.hidden = true;
9 16 bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';
10 document.body.append(bar);
17 vitals.append(bar);
11 18 }
19 else if (bar.parentElement !== vitals)
20 { vitals.append(bar); }
12 21 const fill = document.getElementById("stamina-bar-fill");
13 22 const label = document.getElementById("stamina-bar-label");
14 23
@@ -27,12 +36,12 @@ export function initStamina ()
27 36 return {
28 37 show ()
29 38 {
30 bar.hidden = false;
39 vitals.hidden = false;
31 40 render();
32 41 },
33 42 hide ()
34 43 {
35 bar.hidden = true;
44 vitals.hidden = true;
36 45 },
37 46 apply (message)
38 47 {
@@ -1,14 +1,23 @@
1export function initStamina ()
1export function initStamina ()
2{
2{
3 let vitals = document.getElementById("vitals");
4 if (!vitals)
5 {
6 vitals = document.createElement("div");
7 vitals.id = "vitals";
8 vitals.hidden = true;
9 document.body.append(vitals);
10 }
3 let bar = document.getElementById("stamina-bar");
11 let bar = document.getElementById("stamina-bar");
4 if (!bar)
12 if (!bar)
5 {
13 {
6 bar = document.createElement("div");
14 bar = document.createElement("div");
7 bar.id = "stamina-bar";
15 bar.id = "stamina-bar";
8 bar.hidden = true;
9 bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';
16 bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';
10 document.body.append(bar);
17 vitals.append(bar);
11 }
18 }
19 else if (bar.parentElement !== vitals)
20 { vitals.append(bar); }
12 const fill = document.getElementById("stamina-bar-fill");
21 const fill = document.getElementById("stamina-bar-fill");
13 const label = document.getElementById("stamina-bar-label");
22 const label = document.getElementById("stamina-bar-label");
14
23
@@ -27,12 +36,12 @@ export function initStamina ()
27 return {
36 return {
28 show ()
37 show ()
29 {
38 {
30 bar.hidden = false;
39 vitals.hidden = false;
31 render();
40 render();
32 },
41 },
33 hide ()
42 hide ()
34 {
43 {
35 bar.hidden = true;
44 vitals.hidden = true;
36 },
45 },
37 apply (message)
46 apply (message)
38 {
47 {
client/src/play/statusEffects.js added +211 −0
@@ -0,0 +1,211 @@
1 import {
2 statusEffectDisplay,
3 statusEffectIconPath,
4 formatStatusRemaining
5 } from "/shared/statusEffects/display.js";
6
7 export function initStatusEffects ()
8 {
9 let vitals = document.getElementById("vitals");
10 if (!vitals)
11 {
12 vitals = document.createElement("div");
13 vitals.id = "vitals";
14 vitals.hidden = true;
15 document.body.append(vitals);
16 }
17
18 let rail = document.getElementById("status-effects");
19 if (!rail)
20 {
21 rail = document.createElement("div");
22 rail.id = "status-effects";
23 rail.setAttribute("aria-label", "Active effects");
24 vitals.prepend(rail);
25 }
26 else if (rail.parentElement !== vitals)
27 { vitals.prepend(rail); }
28
29 let tip = document.getElementById("status-effect-tooltip");
30 if (!tip)
31 {
32 tip = document.createElement("div");
33 tip.id = "status-effect-tooltip";
34 tip.hidden = true;
35 document.body.append(tip);
36 }
37
38 /** @type {Array<{ type: string, expiresAt: number, amount?: number, amountPerSecond?: number, scale?: number }>} */
39 let effects = [];
40 let hoverType = null;
41 let tickId = 0;
42
43 function remainingMs (entry, now = Date.now())
44 {
45 return Math.max(0, (entry.expiresAt | 0) - now);
46 }
47
48 function prune (now = Date.now())
49 {
50 effects = effects.filter((entry) => remainingMs(entry, now) > 0);
51 }
52
53 function hideTip ()
54 {
55 hoverType = null;
56 tip.hidden = true;
57 }
58
59 function showTipFor (entry, anchor)
60 {
61 const display = statusEffectDisplay(entry.type);
62 if (!display)
63 {
64 hideTip();
65 return;
66 }
67 hoverType = entry.type;
68 const left = remainingMs(entry);
69 tip.innerHTML = "";
70 const title = document.createElement("strong");
71 title.textContent = display.title;
72 const body = document.createElement("p");
73 body.textContent = display.describe(entry);
74 const time = document.createElement("p");
75 time.className = "status-effect-tooltip-time";
76 time.textContent = left > 0 ? `${formatStatusRemaining(left)} remaining` : "Expired";
77 tip.append(title, body, time);
78 tip.hidden = false;
79 tip.dataset.polarity = display.polarity;
80 const rect = anchor.getBoundingClientRect();
81 const tipW = tip.offsetWidth || 180;
82 const tipH = tip.offsetHeight || 60;
83 let leftPx = rect.left - tipW - 8;
84 if (leftPx < 8)
85 { leftPx = rect.right + 8; }
86 let topPx = rect.bottom - tipH;
87 if (topPx < 8)
88 { topPx = 8; }
89 if (topPx + tipH > window.innerHeight - 8)
90 { topPx = window.innerHeight - tipH - 8; }
91 tip.style.left = `${leftPx}px`;
92 tip.style.top = `${topPx}px`;
93 }
94
95 function refreshTip ()
96 {
97 if (!hoverType)
98 { return; }
99 const entry = effects.find((row) => row.type === hoverType);
100 const btn = rail.querySelector(`[data-effect-type="${hoverType}"]`);
101 if (!entry || !btn)
102 {
103 hideTip();
104 return;
105 }
106 showTipFor(entry, btn);
107 }
108
109 function render ()
110 {
111 const now = Date.now();
112 prune(now);
113 rail.replaceChildren();
114 for (const entry of effects)
115 {
116 const display = statusEffectDisplay(entry.type);
117 if (!display)
118 { continue; }
119 const btn = document.createElement("button");
120 btn.type = "button";
121 btn.className = `status-effect-icon status-effect-${display.polarity}`;
122 btn.dataset.effectType = entry.type;
123 btn.setAttribute("aria-label", display.title);
124 const img = document.createElement("img");
125 img.src = statusEffectIconPath(entry.type);
126 img.alt = "";
127 img.draggable = false;
128 img.addEventListener("error", () =>
129 {
130 img.remove();
131 btn.classList.add("status-effect-icon-fallback");
132 btn.textContent = display.title.slice(0, 1);
133 }, { once: true });
134 btn.append(img);
135 btn.addEventListener("mouseenter", () => showTipFor(entry, btn));
136 btn.addEventListener("mouseleave", hideTip);
137 btn.addEventListener("focus", () => showTipFor(entry, btn));
138 btn.addEventListener("blur", hideTip);
139 rail.append(btn);
140 }
141 rail.hidden = effects.length === 0;
142 refreshTip();
143 }
144
145 function stopTick ()
146 {
147 if (tickId)
148 {
149 clearInterval(tickId);
150 tickId = 0;
151 }
152 }
153
154 function ensureTick ()
155 {
156 if (tickId || effects.length === 0)
157 { return; }
158 tickId = setInterval(() =>
159 {
160 const before = effects.length;
161 prune();
162 if (effects.length !== before)
163 { render(); }
164 else
165 { refreshTip(); }
166 if (effects.length === 0)
167 { stopTick(); }
168 }, 250);
169 }
170
171 return {
172 apply (message)
173 {
174 const list = Array.isArray(message?.effects) ? message.effects : [];
175 effects = list
176 .filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())
177 .map((entry) => ({
178 type: entry.type,
179 expiresAt: entry.expiresAt | 0,
180 amount: entry.amount | 0,
181 amountPerSecond: Number(entry.amountPerSecond) || 0,
182 scale: entry.scale ?? null,
183 lightRadiusTiles: entry.lightRadiusTiles ?? null
184 }));
185 render();
186 if (effects.length)
187 { ensureTick(); }
188 else
189 {
190 stopTick();
191 hideTip();
192 }
193 },
194 clear ()
195 {
196 effects = [];
197 stopTick();
198 hideTip();
199 render();
200 },
201 show ()
202 {
203 vitals.hidden = false;
204 render();
205 },
206 hide ()
207 {
208 this.clear();
209 }
210 };
211 }
@@ -0,0 +1,211 @@
1import {
2 statusEffectDisplay,
3 statusEffectIconPath,
4 formatStatusRemaining
5} from "/shared/statusEffects/display.js";
6
7export function initStatusEffects ()
8{
9 let vitals = document.getElementById("vitals");
10 if (!vitals)
11 {
12 vitals = document.createElement("div");
13 vitals.id = "vitals";
14 vitals.hidden = true;
15 document.body.append(vitals);
16 }
17
18 let rail = document.getElementById("status-effects");
19 if (!rail)
20 {
21 rail = document.createElement("div");
22 rail.id = "status-effects";
23 rail.setAttribute("aria-label", "Active effects");
24 vitals.prepend(rail);
25 }
26 else if (rail.parentElement !== vitals)
27 { vitals.prepend(rail); }
28
29 let tip = document.getElementById("status-effect-tooltip");
30 if (!tip)
31 {
32 tip = document.createElement("div");
33 tip.id = "status-effect-tooltip";
34 tip.hidden = true;
35 document.body.append(tip);
36 }
37
38 /** @type {Array<{ type: string, expiresAt: number, amount?: number, amountPerSecond?: number, scale?: number }>} */
39 let effects = [];
40 let hoverType = null;
41 let tickId = 0;
42
43 function remainingMs (entry, now = Date.now())
44 {
45 return Math.max(0, (entry.expiresAt | 0) - now);
46 }
47
48 function prune (now = Date.now())
49 {
50 effects = effects.filter((entry) => remainingMs(entry, now) > 0);
51 }
52
53 function hideTip ()
54 {
55 hoverType = null;
56 tip.hidden = true;
57 }
58
59 function showTipFor (entry, anchor)
60 {
61 const display = statusEffectDisplay(entry.type);
62 if (!display)
63 {
64 hideTip();
65 return;
66 }
67 hoverType = entry.type;
68 const left = remainingMs(entry);
69 tip.innerHTML = "";
70 const title = document.createElement("strong");
71 title.textContent = display.title;
72 const body = document.createElement("p");
73 body.textContent = display.describe(entry);
74 const time = document.createElement("p");
75 time.className = "status-effect-tooltip-time";
76 time.textContent = left > 0 ? `${formatStatusRemaining(left)} remaining` : "Expired";
77 tip.append(title, body, time);
78 tip.hidden = false;
79 tip.dataset.polarity = display.polarity;
80 const rect = anchor.getBoundingClientRect();
81 const tipW = tip.offsetWidth || 180;
82 const tipH = tip.offsetHeight || 60;
83 let leftPx = rect.left - tipW - 8;
84 if (leftPx < 8)
85 { leftPx = rect.right + 8; }
86 let topPx = rect.bottom - tipH;
87 if (topPx < 8)
88 { topPx = 8; }
89 if (topPx + tipH > window.innerHeight - 8)
90 { topPx = window.innerHeight - tipH - 8; }
91 tip.style.left = `${leftPx}px`;
92 tip.style.top = `${topPx}px`;
93 }
94
95 function refreshTip ()
96 {
97 if (!hoverType)
98 { return; }
99 const entry = effects.find((row) => row.type === hoverType);
100 const btn = rail.querySelector(`[data-effect-type="${hoverType}"]`);
101 if (!entry || !btn)
102 {
103 hideTip();
104 return;
105 }
106 showTipFor(entry, btn);
107 }
108
109 function render ()
110 {
111 const now = Date.now();
112 prune(now);
113 rail.replaceChildren();
114 for (const entry of effects)
115 {
116 const display = statusEffectDisplay(entry.type);
117 if (!display)
118 { continue; }
119 const btn = document.createElement("button");
120 btn.type = "button";
121 btn.className = `status-effect-icon status-effect-${display.polarity}`;
122 btn.dataset.effectType = entry.type;
123 btn.setAttribute("aria-label", display.title);
124 const img = document.createElement("img");
125 img.src = statusEffectIconPath(entry.type);
126 img.alt = "";
127 img.draggable = false;
128 img.addEventListener("error", () =>
129 {
130 img.remove();
131 btn.classList.add("status-effect-icon-fallback");
132 btn.textContent = display.title.slice(0, 1);
133 }, { once: true });
134 btn.append(img);
135 btn.addEventListener("mouseenter", () => showTipFor(entry, btn));
136 btn.addEventListener("mouseleave", hideTip);
137 btn.addEventListener("focus", () => showTipFor(entry, btn));
138 btn.addEventListener("blur", hideTip);
139 rail.append(btn);
140 }
141 rail.hidden = effects.length === 0;
142 refreshTip();
143 }
144
145 function stopTick ()
146 {
147 if (tickId)
148 {
149 clearInterval(tickId);
150 tickId = 0;
151 }
152 }
153
154 function ensureTick ()
155 {
156 if (tickId || effects.length === 0)
157 { return; }
158 tickId = setInterval(() =>
159 {
160 const before = effects.length;
161 prune();
162 if (effects.length !== before)
163 { render(); }
164 else
165 { refreshTip(); }
166 if (effects.length === 0)
167 { stopTick(); }
168 }, 250);
169 }
170
171 return {
172 apply (message)
173 {
174 const list = Array.isArray(message?.effects) ? message.effects : [];
175 effects = list
176 .filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())
177 .map((entry) => ({
178 type: entry.type,
179 expiresAt: entry.expiresAt | 0,
180 amount: entry.amount | 0,
181 amountPerSecond: Number(entry.amountPerSecond) || 0,
182 scale: entry.scale ?? null,
183 lightRadiusTiles: entry.lightRadiusTiles ?? null
184 }));
185 render();
186 if (effects.length)
187 { ensureTick(); }
188 else
189 {
190 stopTick();
191 hideTip();
192 }
193 },
194 clear ()
195 {
196 effects = [];
197 stopTick();
198 hideTip();
199 render();
200 },
201 show ()
202 {
203 vitals.hidden = false;
204 render();
205 },
206 hide ()
207 {
208 this.clear();
209 }
210 };
211}
client/src/render/worldView.js +198 −17
@@ -203,6 +203,11 @@ export class WorldView
203 203 this.groundItems = new Map();
204 204 this.edges = new Map();
205 205 this.localEntityId = null;
206 this.localBlind = false;
207 /** @type {"soft"|"simple"} */
208 this.lightingMode = "soft";
209 /** @type {boolean} */
210 this.bloomEnabled = true;
206 211 this.settings = { ...DEFAULT_WORLD_SETTINGS };
207 212 this.worldHour = 12;
208 213 /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
@@ -228,6 +233,27 @@ export class WorldView
228 233 this.#syncBloomLayer();
229 234 }
230 235
236 /**
237 * Client graphics prefs (lighting Soft/Simple, bloom On/Off).
238 * @param {{ lighting?: string, bloom?: string }} prefs
239 */
240 setGraphicsPrefs (prefs)
241 {
242 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
243 { this.lightingMode = prefs.lighting; }
244 if (prefs?.bloom === "off" || prefs?.bloom === "on")
245 {
246 const enabled = prefs.bloom !== "off";
247 if (enabled !== this.bloomEnabled)
248 {
249 this.bloomEnabled = enabled;
250 this.#syncBloomLayer();
251 }
252 else
253 { this.bloomEnabled = enabled; }
254 }
255 }
256
231 257 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
232 258 setWorldSeason (season)
233 259 {
@@ -240,7 +266,7 @@ export class WorldView
240 266 this.#rebakeAllChunks();
241 267 }
242 268
243 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
269 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
244 270 {
245 271 this.localEntityId = entityId;
246 272 this.#upsertEntity({
@@ -252,7 +278,9 @@ export class WorldView
252 278 sex,
253 279 firstName,
254 280 lastName,
255 layers: layers ?? undefined
281 layers: layers ?? undefined,
282 ...(health != null ? { health } : {}),
283 ...(maxHealth != null ? { maxHealth } : {})
256 284 });
257 285 }
258 286
@@ -454,6 +482,8 @@ export class WorldView
454 482 if (!existing)
455 483 { return; }
456 484 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
485 if (payload.visualScale != null)
486 { existing.visualScale = Number(payload.visualScale) || 1; }
457 487 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
458 488 this.#placeEntity(existing);
459 489 }
@@ -654,6 +684,7 @@ export class WorldView
654 684 this.#updateDamageNumbers(now);
655 685 this.#updateSkillLevelFloats(now);
656 686 this.#centerCamera();
687 this.#cullOffscreenDrawables();
657 688 this.#updateShade(deltaTime);
658 689 }
659 690
@@ -963,6 +994,82 @@ export class WorldView
963 994 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
964 995 }
965 996
997 /**
998 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
999 * Tiles fully outside this rect are not drawn.
1000 */
1001 #drawBounds ()
1002 {
1003 const pad = this.tileSize() * 0.5;
1004 const camX = this.scene.cameraPosition.x;
1005 const camY = this.scene.cameraPosition.y;
1006 const w = this.scene.real_size.x;
1007 const h = this.scene.real_size.y;
1008 return {
1009 left: -camX - pad,
1010 right: -camX + w + pad,
1011 top: -camY - pad,
1012 bottom: -camY + h + pad
1013 };
1014 }
1015
1016 #rectIntersects (left, top, right, bottom, bounds)
1017 {
1018 return right >= bounds.left
1019 && left <= bounds.right
1020 && bottom >= bounds.top
1021 && top <= bounds.bottom;
1022 }
1023
1024 #setRendererVisible (object, visible)
1025 {
1026 if (object?.renderer)
1027 { object.renderer.visible = !!visible; }
1028 }
1029
1030 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
1031 #cullOffscreenDrawables ()
1032 {
1033 const bounds = this.#drawBounds();
1034 const size = this.tileSize();
1035
1036 for (const baked of this.bakedChunks.values())
1037 {
1038 const left = baked.chunkX * CHUNK_SIZE * size;
1039 const top = baked.chunkY * CHUNK_SIZE * size;
1040 const chunkPx = CHUNK_SIZE * size;
1041 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
1042 this.#setRendererVisible(baked.groundObject, chunkVisible);
1043 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
1044 baked._inViewport = chunkVisible;
1045 for (let row = 0; row < CHUNK_SIZE; row++)
1046 {
1047 const rowTop = top + row * size;
1048 const rowVisible = chunkVisible && this.#rectIntersects(
1049 left, rowTop, left + chunkPx, rowTop + size, bounds
1050 );
1051 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
1052 }
1053 }
1054
1055 for (const objects of this.tiles.values())
1056 {
1057 const left = objects.tileX * size;
1058 const top = objects.tileY * size;
1059 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
1060 objects._inViewport = visible;
1061 this.#setRendererVisible(objects.ground, visible);
1062 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
1063 this.#setRendererVisible(objects.block, visible);
1064 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
1065 if (objects.waterEdges)
1066 {
1067 for (const edge of Object.values(objects.waterEdges))
1068 { this.#setRendererVisible(edge, visible); }
1069 }
1070 }
1071 }
1072
966 1073 #upsertEntity (payload)
967 1074 {
968 1075 const size = this.tileSize();
@@ -995,6 +1102,10 @@ export class WorldView
995 1102 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
996 1103 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
997 1104 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1105 if (payload.visualScale != null)
1106 { entity.visualScale = Number(payload.visualScale) || 1; }
1107 else if (entity.visualScale == null)
1108 { entity.visualScale = 1; }
998 1109 if (payload.health != null)
999 1110 { entity.health = payload.health; }
1000 1111 if (payload.maxHealth != null)
@@ -1147,20 +1258,23 @@ export class WorldView
1147 1258
1148 1259 entity.object.transform.rotation = walkTilt;
1149 1260 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1150 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
1261 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY, entity.visualScale ?? 1);
1151 1262 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1152 1263 {
1153 1264 const overlay = entity.overlays[index];
1154 1265 const overlaySortY = entity.visualY + 0.5 * (index + 1);
1155 1266 overlay.transform.rotation = walkTilt;
1156 1267 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1157 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
1268 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
1158 1269 }
1159 1270 for (const overlay of entity.bloomOverlays ?? [])
1160 1271 {
1272 this.#setRendererVisible(overlay, this.bloomEnabled);
1273 if (!this.bloomEnabled)
1274 { continue; }
1161 1275 overlay.transform.rotation = walkTilt;
1162 1276 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1163 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
1277 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
1164 1278 }
1165 1279 this.#placeHpBar(entity, pivotX, pivotY);
1166 1280 }
@@ -1285,13 +1399,22 @@ export class WorldView
1285 1399 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
1286 1400 const localX = objects.tileX - chunkX * CHUNK_SIZE;
1287 1401 const localY = objects.tileY - chunkY * CHUNK_SIZE;
1288 const corners = chunkBaked
1289 ? this.#tileLitCorners(chunkBaked, localX, localY)
1290 : null;
1402 let litCorners = null;
1403 if (chunkBaked)
1404 {
1405 if (this.lightingMode === "simple")
1406 {
1407 const gridW = CHUNK_SIZE + 2;
1408 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
1409 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
1410 }
1411 else
1412 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
1413 }
1291 1414 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1292 1415 this.#syncWaterGroundSprite(
1293 1416 objects.ground,
1294 corners,
1417 litCorners,
1295 1418 ambientDark,
1296 1419 objects.waterEdges,
1297 1420 timeSec,
@@ -1302,7 +1425,32 @@ export class WorldView
1302 1425 #ambientDarkness ()
1303 1426 {
1304 1427 const hour = this.nightPreview ?? this.worldHour;
1305 return nightFactor(hour, this.settings.nightDarkness);
1428 let dark = nightFactor(hour, this.settings.nightDarkness);
1429 if (this.localBlind)
1430 { dark = Math.min(1, dark + 0.85); }
1431 return dark;
1432 }
1433
1434 setLocalBlind (blind)
1435 {
1436 this.localBlind = !!blind;
1437 }
1438
1439 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
1440 #blindVisionLight ()
1441 {
1442 if (!this.localBlind)
1443 { return null; }
1444 const local = this.entities.get(this.localEntityId);
1445 if (!local)
1446 { return null; }
1447 const tileSize = this.tileSize();
1448 return {
1449 tileX: Math.floor(local.visualX / tileSize),
1450 tileY: Math.floor(local.visualY / tileSize),
1451 range: 2.25,
1452 intensity: 1
1453 };
1306 1454 }
1307 1455
1308 1456 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
@@ -1316,8 +1464,7 @@ export class WorldView
1316 1464 {
1317 1465 const current = entity.health;
1318 1466 const max = entity.maxHealth;
1319 const show = entity.mobTypeId != null
1320 && current != null
1467 const show = current != null
1321 1468 && max != null
1322 1469 && max > 0
1323 1470 && current < max;
@@ -1636,17 +1783,18 @@ export class WorldView
1636 1783 return object;
1637 1784 }
1638 1785
1639 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
1786 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
1640 1787 {
1641 1788 const sprite = object?.renderer?.sprite;
1642 1789 if (!sprite)
1643 1790 { return; }
1644 1791 const zoom = this.zoom;
1645 1792 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1646 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
1793 const factor = Math.max(0.1, Number(scale) || 1);
1794 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
1647 1795 object.transform.position.x = center.x;
1648 1796 object.transform.position.y = center.y;
1649 object.transform.size = new vector(draw.w, draw.h);
1797 object.transform.size = new vector(draw.w * factor, draw.h * factor);
1650 1798 object.layer = ySortLayer(sortY, subOrder);
1651 1799 this.#markSortDirty();
1652 1800 }
@@ -1787,6 +1935,9 @@ export class WorldView
1787 1935
1788 1936 const activeLights = [...this.dynamicLights];
1789 1937 const tileSize = this.tileSize();
1938 const blindLight = this.#blindVisionLight();
1939 if (blindLight)
1940 { activeLights.push(blindLight); }
1790 1941 for (const entity of this.entities.values())
1791 1942 {
1792 1943 const range = entity.lightRadiusTiles ?? 0;
@@ -1804,12 +1955,16 @@ export class WorldView
1804 1955
1805 1956 for (const objects of this.tiles.values())
1806 1957 {
1958 if (objects._inViewport === false)
1959 { continue; }
1807 1960 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
1808 1961 objects.shadeAlpha = ambientDark * (1 - intensity);
1809 1962 }
1810 1963
1811 1964 for (const baked of this.bakedChunks.values())
1812 1965 {
1966 if (baked._inViewport === false)
1967 { continue; }
1813 1968 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
1814 1969 if (baked.groundObject?.renderer?.shaderUniforms)
1815 1970 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
@@ -1823,6 +1978,8 @@ export class WorldView
1823 1978 const timeSec = now / 1000;
1824 1979 for (const objects of this.tiles.values())
1825 1980 {
1981 if (objects._inViewport === false)
1982 { continue; }
1826 1983 if (objects.block)
1827 1984 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1828 1985 if (objects.ground && isWaterGround(objects.groundTypeId))
@@ -1995,18 +2152,37 @@ export class WorldView
1995 2152 const pixels = baked.lightmapPixels;
1996 2153
1997 2154 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
2155 const simple = this.lightingMode === "simple";
1998 2156
1999 2157 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2000 2158 {
2001 2159 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2002 2160 {
2161 const baseX = localX * SPRITE_SIZE_PX;
2162 const baseY = localY * SPRITE_SIZE_PX;
2163 if (simple)
2164 {
2165 const gridW = CHUNK_SIZE + 2;
2166 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
2167 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2168 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2169 {
2170 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2171 {
2172 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2173 pixels[offset] = value;
2174 pixels[offset + 1] = value;
2175 pixels[offset + 2] = value;
2176 pixels[offset + 3] = 255;
2177 }
2178 }
2179 continue;
2180 }
2003 2181 const corners = this.#tileLitCorners(baked, localX, localY);
2004 2182 const nw = corners.nw;
2005 2183 const ne = corners.ne;
2006 2184 const sw = corners.sw;
2007 2185 const se = corners.se;
2008 const baseX = localX * SPRITE_SIZE_PX;
2009 const baseY = localY * SPRITE_SIZE_PX;
2010 2186 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2011 2187 {
2012 2188 const v = (py + 0.5) / SPRITE_SIZE_PX;
@@ -2141,6 +2317,11 @@ export class WorldView
2141 2317
2142 2318 #syncBloomLayer ()
2143 2319 {
2320 if (!this.bloomEnabled)
2321 {
2322 this.scene.setLayers([{ name: "default" }]);
2323 return;
2324 }
2144 2325 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
2145 2326 this.scene.setLayers([
2146 2327 { name: "default" },
@@ -203,6 +203,11 @@ export class WorldView
203 this.groundItems = new Map();
203 this.groundItems = new Map();
204 this.edges = new Map();
204 this.edges = new Map();
205 this.localEntityId = null;
205 this.localEntityId = null;
206 this.localBlind = false;
207 /** @type {"soft"|"simple"} */
208 this.lightingMode = "soft";
209 /** @type {boolean} */
210 this.bloomEnabled = true;
206 this.settings = { ...DEFAULT_WORLD_SETTINGS };
211 this.settings = { ...DEFAULT_WORLD_SETTINGS };
207 this.worldHour = 12;
212 this.worldHour = 12;
208 /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
213 /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
@@ -228,6 +233,27 @@ export class WorldView
228 this.#syncBloomLayer();
233 this.#syncBloomLayer();
229 }
234 }
230
235
236 /**
237 * Client graphics prefs (lighting Soft/Simple, bloom On/Off).
238 * @param {{ lighting?: string, bloom?: string }} prefs
239 */
240 setGraphicsPrefs (prefs)
241 {
242 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
243 { this.lightingMode = prefs.lighting; }
244 if (prefs?.bloom === "off" || prefs?.bloom === "on")
245 {
246 const enabled = prefs.bloom !== "off";
247 if (enabled !== this.bloomEnabled)
248 {
249 this.bloomEnabled = enabled;
250 this.#syncBloomLayer();
251 }
252 else
253 { this.bloomEnabled = enabled; }
254 }
255 }
256
231 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
257 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
232 setWorldSeason (season)
258 setWorldSeason (season)
233 {
259 {
@@ -240,7 +266,7 @@ export class WorldView
240 this.#rebakeAllChunks();
266 this.#rebakeAllChunks();
241 }
267 }
242
268
243 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
269 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
244 {
270 {
245 this.localEntityId = entityId;
271 this.localEntityId = entityId;
246 this.#upsertEntity({
272 this.#upsertEntity({
@@ -252,7 +278,9 @@ export class WorldView
252 sex,
278 sex,
253 firstName,
279 firstName,
254 lastName,
280 lastName,
255 layers: layers ?? undefined
281 layers: layers ?? undefined,
282 ...(health != null ? { health } : {}),
283 ...(maxHealth != null ? { maxHealth } : {})
256 });
284 });
257 }
285 }
258
286
@@ -454,6 +482,8 @@ export class WorldView
454 if (!existing)
482 if (!existing)
455 { return; }
483 { return; }
456 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
484 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
485 if (payload.visualScale != null)
486 { existing.visualScale = Number(payload.visualScale) || 1; }
457 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
487 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
458 this.#placeEntity(existing);
488 this.#placeEntity(existing);
459 }
489 }
@@ -654,6 +684,7 @@ export class WorldView
654 this.#updateDamageNumbers(now);
684 this.#updateDamageNumbers(now);
655 this.#updateSkillLevelFloats(now);
685 this.#updateSkillLevelFloats(now);
656 this.#centerCamera();
686 this.#centerCamera();
687 this.#cullOffscreenDrawables();
657 this.#updateShade(deltaTime);
688 this.#updateShade(deltaTime);
658 }
689 }
659
690
@@ -963,6 +994,82 @@ export class WorldView
963 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
994 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
964 }
995 }
965
996
997 /**
998 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
999 * Tiles fully outside this rect are not drawn.
1000 */
1001 #drawBounds ()
1002 {
1003 const pad = this.tileSize() * 0.5;
1004 const camX = this.scene.cameraPosition.x;
1005 const camY = this.scene.cameraPosition.y;
1006 const w = this.scene.real_size.x;
1007 const h = this.scene.real_size.y;
1008 return {
1009 left: -camX - pad,
1010 right: -camX + w + pad,
1011 top: -camY - pad,
1012 bottom: -camY + h + pad
1013 };
1014 }
1015
1016 #rectIntersects (left, top, right, bottom, bounds)
1017 {
1018 return right >= bounds.left
1019 && left <= bounds.right
1020 && bottom >= bounds.top
1021 && top <= bounds.bottom;
1022 }
1023
1024 #setRendererVisible (object, visible)
1025 {
1026 if (object?.renderer)
1027 { object.renderer.visible = !!visible; }
1028 }
1029
1030 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
1031 #cullOffscreenDrawables ()
1032 {
1033 const bounds = this.#drawBounds();
1034 const size = this.tileSize();
1035
1036 for (const baked of this.bakedChunks.values())
1037 {
1038 const left = baked.chunkX * CHUNK_SIZE * size;
1039 const top = baked.chunkY * CHUNK_SIZE * size;
1040 const chunkPx = CHUNK_SIZE * size;
1041 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
1042 this.#setRendererVisible(baked.groundObject, chunkVisible);
1043 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
1044 baked._inViewport = chunkVisible;
1045 for (let row = 0; row < CHUNK_SIZE; row++)
1046 {
1047 const rowTop = top + row * size;
1048 const rowVisible = chunkVisible && this.#rectIntersects(
1049 left, rowTop, left + chunkPx, rowTop + size, bounds
1050 );
1051 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
1052 }
1053 }
1054
1055 for (const objects of this.tiles.values())
1056 {
1057 const left = objects.tileX * size;
1058 const top = objects.tileY * size;
1059 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
1060 objects._inViewport = visible;
1061 this.#setRendererVisible(objects.ground, visible);
1062 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
1063 this.#setRendererVisible(objects.block, visible);
1064 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
1065 if (objects.waterEdges)
1066 {
1067 for (const edge of Object.values(objects.waterEdges))
1068 { this.#setRendererVisible(edge, visible); }
1069 }
1070 }
1071 }
1072
966 #upsertEntity (payload)
1073 #upsertEntity (payload)
967 {
1074 {
968 const size = this.tileSize();
1075 const size = this.tileSize();
@@ -995,6 +1102,10 @@ export class WorldView
995 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1102 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
996 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1103 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
997 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1104 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1105 if (payload.visualScale != null)
1106 { entity.visualScale = Number(payload.visualScale) || 1; }
1107 else if (entity.visualScale == null)
1108 { entity.visualScale = 1; }
998 if (payload.health != null)
1109 if (payload.health != null)
999 { entity.health = payload.health; }
1110 { entity.health = payload.health; }
1000 if (payload.maxHealth != null)
1111 if (payload.maxHealth != null)
@@ -1147,20 +1258,23 @@ export class WorldView
1147
1258
1148 entity.object.transform.rotation = walkTilt;
1259 entity.object.transform.rotation = walkTilt;
1149 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1260 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1150 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
1261 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY, entity.visualScale ?? 1);
1151 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1262 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1152 {
1263 {
1153 const overlay = entity.overlays[index];
1264 const overlay = entity.overlays[index];
1154 const overlaySortY = entity.visualY + 0.5 * (index + 1);
1265 const overlaySortY = entity.visualY + 0.5 * (index + 1);
1155 overlay.transform.rotation = walkTilt;
1266 overlay.transform.rotation = walkTilt;
1156 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1267 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1157 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
1268 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
1158 }
1269 }
1159 for (const overlay of entity.bloomOverlays ?? [])
1270 for (const overlay of entity.bloomOverlays ?? [])
1160 {
1271 {
1272 this.#setRendererVisible(overlay, this.bloomEnabled);
1273 if (!this.bloomEnabled)
1274 { continue; }
1161 overlay.transform.rotation = walkTilt;
1275 overlay.transform.rotation = walkTilt;
1162 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1276 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1163 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
1277 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
1164 }
1278 }
1165 this.#placeHpBar(entity, pivotX, pivotY);
1279 this.#placeHpBar(entity, pivotX, pivotY);
1166 }
1280 }
@@ -1285,13 +1399,22 @@ export class WorldView
1285 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
1399 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
1286 const localX = objects.tileX - chunkX * CHUNK_SIZE;
1400 const localX = objects.tileX - chunkX * CHUNK_SIZE;
1287 const localY = objects.tileY - chunkY * CHUNK_SIZE;
1401 const localY = objects.tileY - chunkY * CHUNK_SIZE;
1288 const corners = chunkBaked
1402 let litCorners = null;
1289 ? this.#tileLitCorners(chunkBaked, localX, localY)
1403 if (chunkBaked)
1290 : null;
1404 {
1405 if (this.lightingMode === "simple")
1406 {
1407 const gridW = CHUNK_SIZE + 2;
1408 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
1409 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
1410 }
1411 else
1412 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
1413 }
1291 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1414 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1292 this.#syncWaterGroundSprite(
1415 this.#syncWaterGroundSprite(
1293 objects.ground,
1416 objects.ground,
1294 corners,
1417 litCorners,
1295 ambientDark,
1418 ambientDark,
1296 objects.waterEdges,
1419 objects.waterEdges,
1297 timeSec,
1420 timeSec,
@@ -1302,7 +1425,32 @@ export class WorldView
1302 #ambientDarkness ()
1425 #ambientDarkness ()
1303 {
1426 {
1304 const hour = this.nightPreview ?? this.worldHour;
1427 const hour = this.nightPreview ?? this.worldHour;
1305 return nightFactor(hour, this.settings.nightDarkness);
1428 let dark = nightFactor(hour, this.settings.nightDarkness);
1429 if (this.localBlind)
1430 { dark = Math.min(1, dark + 0.85); }
1431 return dark;
1432 }
1433
1434 setLocalBlind (blind)
1435 {
1436 this.localBlind = !!blind;
1437 }
1438
1439 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
1440 #blindVisionLight ()
1441 {
1442 if (!this.localBlind)
1443 { return null; }
1444 const local = this.entities.get(this.localEntityId);
1445 if (!local)
1446 { return null; }
1447 const tileSize = this.tileSize();
1448 return {
1449 tileX: Math.floor(local.visualX / tileSize),
1450 tileY: Math.floor(local.visualY / tileSize),
1451 range: 2.25,
1452 intensity: 1
1453 };
1306 }
1454 }
1307
1455
1308 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
1456 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
@@ -1316,8 +1464,7 @@ export class WorldView
1316 {
1464 {
1317 const current = entity.health;
1465 const current = entity.health;
1318 const max = entity.maxHealth;
1466 const max = entity.maxHealth;
1319 const show = entity.mobTypeId != null
1467 const show = current != null
1320 && current != null
1321 && max != null
1468 && max != null
1322 && max > 0
1469 && max > 0
1323 && current < max;
1470 && current < max;
@@ -1636,17 +1783,18 @@ export class WorldView
1636 return object;
1783 return object;
1637 }
1784 }
1638
1785
1639 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
1786 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
1640 {
1787 {
1641 const sprite = object?.renderer?.sprite;
1788 const sprite = object?.renderer?.sprite;
1642 if (!sprite)
1789 if (!sprite)
1643 { return; }
1790 { return; }
1644 const zoom = this.zoom;
1791 const zoom = this.zoom;
1645 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1792 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1646 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
1793 const factor = Math.max(0.1, Number(scale) || 1);
1794 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
1647 object.transform.position.x = center.x;
1795 object.transform.position.x = center.x;
1648 object.transform.position.y = center.y;
1796 object.transform.position.y = center.y;
1649 object.transform.size = new vector(draw.w, draw.h);
1797 object.transform.size = new vector(draw.w * factor, draw.h * factor);
1650 object.layer = ySortLayer(sortY, subOrder);
1798 object.layer = ySortLayer(sortY, subOrder);
1651 this.#markSortDirty();
1799 this.#markSortDirty();
1652 }
1800 }
@@ -1787,6 +1935,9 @@ export class WorldView
1787
1935
1788 const activeLights = [...this.dynamicLights];
1936 const activeLights = [...this.dynamicLights];
1789 const tileSize = this.tileSize();
1937 const tileSize = this.tileSize();
1938 const blindLight = this.#blindVisionLight();
1939 if (blindLight)
1940 { activeLights.push(blindLight); }
1790 for (const entity of this.entities.values())
1941 for (const entity of this.entities.values())
1791 {
1942 {
1792 const range = entity.lightRadiusTiles ?? 0;
1943 const range = entity.lightRadiusTiles ?? 0;
@@ -1804,12 +1955,16 @@ export class WorldView
1804
1955
1805 for (const objects of this.tiles.values())
1956 for (const objects of this.tiles.values())
1806 {
1957 {
1958 if (objects._inViewport === false)
1959 { continue; }
1807 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
1960 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
1808 objects.shadeAlpha = ambientDark * (1 - intensity);
1961 objects.shadeAlpha = ambientDark * (1 - intensity);
1809 }
1962 }
1810
1963
1811 for (const baked of this.bakedChunks.values())
1964 for (const baked of this.bakedChunks.values())
1812 {
1965 {
1966 if (baked._inViewport === false)
1967 { continue; }
1813 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
1968 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
1814 if (baked.groundObject?.renderer?.shaderUniforms)
1969 if (baked.groundObject?.renderer?.shaderUniforms)
1815 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1970 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
@@ -1823,6 +1978,8 @@ export class WorldView
1823 const timeSec = now / 1000;
1978 const timeSec = now / 1000;
1824 for (const objects of this.tiles.values())
1979 for (const objects of this.tiles.values())
1825 {
1980 {
1981 if (objects._inViewport === false)
1982 { continue; }
1826 if (objects.block)
1983 if (objects.block)
1827 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1984 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1828 if (objects.ground && isWaterGround(objects.groundTypeId))
1985 if (objects.ground && isWaterGround(objects.groundTypeId))
@@ -1995,18 +2152,37 @@ export class WorldView
1995 const pixels = baked.lightmapPixels;
2152 const pixels = baked.lightmapPixels;
1996
2153
1997 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
2154 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
2155 const simple = this.lightingMode === "simple";
1998
2156
1999 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2157 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2000 {
2158 {
2001 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2159 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2002 {
2160 {
2161 const baseX = localX * SPRITE_SIZE_PX;
2162 const baseY = localY * SPRITE_SIZE_PX;
2163 if (simple)
2164 {
2165 const gridW = CHUNK_SIZE + 2;
2166 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
2167 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2168 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2169 {
2170 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2171 {
2172 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2173 pixels[offset] = value;
2174 pixels[offset + 1] = value;
2175 pixels[offset + 2] = value;
2176 pixels[offset + 3] = 255;
2177 }
2178 }
2179 continue;
2180 }
2003 const corners = this.#tileLitCorners(baked, localX, localY);
2181 const corners = this.#tileLitCorners(baked, localX, localY);
2004 const nw = corners.nw;
2182 const nw = corners.nw;
2005 const ne = corners.ne;
2183 const ne = corners.ne;
2006 const sw = corners.sw;
2184 const sw = corners.sw;
2007 const se = corners.se;
2185 const se = corners.se;
2008 const baseX = localX * SPRITE_SIZE_PX;
2009 const baseY = localY * SPRITE_SIZE_PX;
2010 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2186 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2011 {
2187 {
2012 const v = (py + 0.5) / SPRITE_SIZE_PX;
2188 const v = (py + 0.5) / SPRITE_SIZE_PX;
@@ -2141,6 +2317,11 @@ export class WorldView
2141
2317
2142 #syncBloomLayer ()
2318 #syncBloomLayer ()
2143 {
2319 {
2320 if (!this.bloomEnabled)
2321 {
2322 this.scene.setLayers([{ name: "default" }]);
2323 return;
2324 }
2144 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
2325 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
2145 this.scene.setLayers([
2326 this.scene.setLayers([
2146 { name: "default" },
2327 { name: "default" },
client/ui/editor.css +35 −0
@@ -341,6 +341,41 @@ label { display: block; margin: 0.4rem 0; }
341 341 color: #6d6875;
342 342 }
343 343
344 .starter-equipment-panel h3 {
345 margin: 0.85rem 0 0.4rem;
346 font-size: 0.85rem;
347 text-transform: uppercase;
348 letter-spacing: 0.03em;
349 color: #9aa3b2;
350 }
351
352 .starter-equip-list,
353 .starter-inv-list {
354 display: flex;
355 flex-direction: column;
356 gap: 0.4rem;
357 }
358
359 .starter-equip-row {
360 display: grid;
361 grid-template-columns: 5.5rem 1fr;
362 gap: 0.5rem;
363 align-items: center;
364 }
365
366 .starter-equip-row.dirty select,
367 .starter-inv-row.dirty select,
368 .starter-inv-row.dirty input {
369 border-color: #c4a35a;
370 }
371
372 .starter-inv-row {
373 display: grid;
374 grid-template-columns: 1fr 4.5rem auto;
375 gap: 0.4rem;
376 align-items: center;
377 }
378
344 379 #settings-log-wrap {
345 380 width: min(340px, 32vw);
346 381 flex-shrink: 0;
@@ -341,6 +341,41 @@ label { display: block; margin: 0.4rem 0; }
341 color: #6d6875;
341 color: #6d6875;
342}
342}
343
343
344.starter-equipment-panel h3 {
345 margin: 0.85rem 0 0.4rem;
346 font-size: 0.85rem;
347 text-transform: uppercase;
348 letter-spacing: 0.03em;
349 color: #9aa3b2;
350}
351
352.starter-equip-list,
353.starter-inv-list {
354 display: flex;
355 flex-direction: column;
356 gap: 0.4rem;
357}
358
359.starter-equip-row {
360 display: grid;
361 grid-template-columns: 5.5rem 1fr;
362 gap: 0.5rem;
363 align-items: center;
364}
365
366.starter-equip-row.dirty select,
367.starter-inv-row.dirty select,
368.starter-inv-row.dirty input {
369 border-color: #c4a35a;
370}
371
372.starter-inv-row {
373 display: grid;
374 grid-template-columns: 1fr 4.5rem auto;
375 gap: 0.4rem;
376 align-items: center;
377}
378
344#settings-log-wrap {
379#settings-log-wrap {
345 width: min(340px, 32vw);
380 width: min(340px, 32vw);
346 flex-shrink: 0;
381 flex-shrink: 0;
client/ui/play.css +420 −8
@@ -37,6 +37,94 @@ html, body {
37 37 display: none !important;
38 38 }
39 39
40 #settings-toggle {
41 position: fixed;
42 z-index: 4;
43 top: 0.45rem;
44 right: 0.75rem;
45 width: 2.25rem;
46 height: 2.25rem;
47 padding: 0;
48 border: 1px solid #3a4250;
49 border-radius: 0.35rem;
50 background: rgba(18, 22, 28, 0.92);
51 color: #e8e4d9;
52 font-size: 1.15rem;
53 line-height: 1;
54 cursor: pointer;
55 }
56
57 #settings-toggle[hidden] {
58 display: none !important;
59 }
60
61 #settings-panel {
62 position: fixed;
63 z-index: 5;
64 top: 3.1rem;
65 right: 0.75rem;
66 width: min(18rem, calc(100vw - 1.5rem));
67 padding: 0.75rem 0.9rem 1rem;
68 border: 1px solid #3a4250;
69 border-radius: 0.4rem;
70 background: rgba(14, 17, 22, 0.96);
71 box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
72 }
73
74 #settings-panel[hidden] {
75 display: none !important;
76 }
77
78 #settings-panel header {
79 display: flex;
80 align-items: center;
81 justify-content: space-between;
82 gap: 0.75rem;
83 margin-bottom: 0.65rem;
84 }
85
86 #settings-panel h2 {
87 margin: 0;
88 font-size: 1.05rem;
89 font-weight: 600;
90 }
91
92 #settings-panel h3 {
93 margin: 0 0 0.35rem;
94 font-size: 0.8rem;
95 font-weight: 600;
96 letter-spacing: 0.02em;
97 text-transform: uppercase;
98 color: #9aa3b2;
99 }
100
101 .settings-group + .settings-group {
102 margin-top: 0.85rem;
103 }
104
105 .settings-options {
106 display: flex;
107 flex-wrap: wrap;
108 gap: 0.35rem;
109 }
110
111 .settings-options button {
112 flex: 1 1 auto;
113 min-width: 4.5rem;
114 padding: 0.35rem 0.55rem;
115 border: 1px solid #3a4250;
116 border-radius: 0.3rem;
117 background: #1a2029;
118 color: #c8cdd6;
119 cursor: pointer;
120 }
121
122 .settings-options button.active {
123 border-color: #7a91b8;
124 background: #2a3648;
125 color: #f0f2f6;
126 }
127
40 128 #toast-stack {
41 129 position: fixed;
42 130 top: 3.4rem;
@@ -101,6 +189,62 @@ html, body {
101 189 padding: 1.25rem;
102 190 }
103 191
192 #character-list {
193 margin: 0.75rem 0 1rem;
194 max-height: min(40vh, 20rem);
195 overflow: auto;
196 }
197
198 #create-character-open {
199 width: 100%;
200 margin-top: 0.25rem;
201 }
202
203 #create-panel {
204 position: fixed;
205 z-index: 6;
206 top: 50%;
207 left: 50%;
208 transform: translate(-50%, -50%);
209 width: min(420px, 92vw);
210 max-height: min(90vh, 40rem);
211 overflow: auto;
212 padding: 1rem 1.1rem 1.15rem;
213 border: 1px solid #3a4250;
214 border-radius: 0.4rem;
215 background: rgba(18, 22, 28, 0.98);
216 box-shadow: 0 12px 36px rgba(0, 0, 0, 0.5);
217 }
218
219 #create-panel[hidden] {
220 display: none !important;
221 }
222
223 #create-panel header {
224 display: flex;
225 align-items: center;
226 justify-content: space-between;
227 gap: 0.75rem;
228 margin-bottom: 0.5rem;
229 }
230
231 #create-panel h2 {
232 margin: 0;
233 font-size: 1.1rem;
234 }
235
236 #create-panel label {
237 display: flex;
238 gap: 0.5rem;
239 align-items: center;
240 margin: 0.5rem 0;
241 }
242
243 #create-panel #create-form > button[type="submit"] {
244 width: 100%;
245 margin-top: 0.75rem;
246 }
247
104 248 label, .character-row {
105 249 display: flex;
106 250 gap: 0.5rem;
@@ -124,6 +268,65 @@ button {
124 268 .hint { color: #9aa3b2; font-size: 0.9rem; }
125 269 a { color: #d4c48a; }
126 270
271 .hair-controls {
272 display: grid;
273 grid-template-columns: 72px 1fr;
274 gap: 0.45rem 0.75rem;
275 align-items: center;
276 margin: 0.75rem 0;
277 }
278
279 .hair-controls canvas {
280 grid-row: 1 / span 5;
281 width: 64px;
282 height: 96px;
283 image-rendering: pixelated;
284 background: #0c0e12;
285 border: 1px solid #2c3340;
286 }
287
288 .hair-controls label {
289 display: flex;
290 flex-direction: column;
291 align-items: stretch;
292 gap: 0.2rem;
293 margin: 0;
294 font-size: 0.8rem;
295 }
296
297 .hair-controls input[type="range"] {
298 width: 100%;
299 padding: 0;
300 }
301
302 .hair-swatch {
303 display: inline-block;
304 width: 1.25rem;
305 height: 1.25rem;
306 border: 1px solid #3a4250;
307 border-radius: 2px;
308 }
309
310 #barber-panel {
311 position: fixed;
312 z-index: 6;
313 top: 50%;
314 left: 50%;
315 transform: translate(-50%, -50%);
316 width: min(360px, 92vw);
317 background: #1a1e26;
318 border: 1px solid #2c3340;
319 padding: 0.75rem 1rem 1rem;
320 }
321
322 #barber-panel header {
323 display: flex;
324 justify-content: space-between;
325 align-items: center;
326 gap: 0.75rem;
327 margin-bottom: 0.5rem;
328 }
329
127 330 #nametag {
128 331 position: fixed;
129 332 z-index: 4;
@@ -933,11 +1136,113 @@ a { color: #d4c48a; }
933 1136 background: rgba(12, 14, 18, 0.92);
934 1137 }
935 1138
936 #stamina-bar {
1139 #vitals {
937 1140 position: fixed;
938 1141 z-index: 4;
939 1142 right: 1rem;
940 1143 bottom: 1.25rem;
1144 display: flex;
1145 flex-direction: row;
1146 gap: 0.45rem;
1147 align-items: flex-end;
1148 }
1149
1150 #vitals[hidden] {
1151 display: none !important;
1152 }
1153
1154 #status-effects {
1155 display: flex;
1156 flex-direction: column-reverse;
1157 gap: 0.3rem;
1158 align-items: center;
1159 max-height: 120px;
1160 overflow: visible;
1161 }
1162
1163 #status-effects[hidden] {
1164 display: none !important;
1165 }
1166
1167 .status-effect-icon {
1168 width: 28px;
1169 height: 28px;
1170 padding: 2px;
1171 box-sizing: border-box;
1172 border: 1px solid #3a4250;
1173 background: rgba(12, 14, 18, 0.88);
1174 cursor: default;
1175 display: grid;
1176 place-items: center;
1177 image-rendering: pixelated;
1178 }
1179
1180 .status-effect-icon img {
1181 width: 16px;
1182 height: 16px;
1183 image-rendering: pixelated;
1184 pointer-events: none;
1185 }
1186
1187 .status-effect-buff {
1188 border-color: #4a7a58;
1189 }
1190
1191 .status-effect-debuff {
1192 border-color: #7a4a4a;
1193 }
1194
1195 .status-effect-icon-fallback {
1196 font-size: 0.75rem;
1197 font-weight: 700;
1198 color: #d0d6e0;
1199 }
1200
1201 #status-effect-tooltip {
1202 position: fixed;
1203 z-index: 20;
1204 min-width: 10rem;
1205 max-width: 16rem;
1206 padding: 0.45rem 0.55rem;
1207 background: rgba(12, 14, 18, 0.96);
1208 border: 1px solid #3a4250;
1209 color: #d0d6e0;
1210 font-size: 0.78rem;
1211 line-height: 1.35;
1212 pointer-events: none;
1213 }
1214
1215 #status-effect-tooltip[hidden] {
1216 display: none !important;
1217 }
1218
1219 #status-effect-tooltip strong {
1220 display: block;
1221 margin-bottom: 0.2rem;
1222 color: #f0f2f6;
1223 font-size: 0.82rem;
1224 }
1225
1226 #status-effect-tooltip p {
1227 margin: 0.15rem 0 0;
1228 }
1229
1230 #status-effect-tooltip .status-effect-tooltip-time {
1231 color: #9aa3b2;
1232 font-size: 0.72rem;
1233 }
1234
1235 #status-effect-tooltip[data-polarity="buff"] {
1236 border-color: #4a7a58;
1237 }
1238
1239 #status-effect-tooltip[data-polarity="debuff"] {
1240 border-color: #7a4a4a;
1241 }
1242
1243 #stamina-bar,
1244 #health-bar {
1245 position: relative;
941 1246 width: 14px;
942 1247 height: 120px;
943 1248 padding: 3px;
@@ -950,33 +1255,52 @@ a { color: #d4c48a; }
950 1255 align-items: stretch;
951 1256 }
952 1257
953 #stamina-bar[hidden] {
1258 #stamina-bar[hidden],
1259 #health-bar[hidden] {
954 1260 display: none !important;
955 1261 }
956 1262
957 #stamina-bar-fill {
1263 #stamina-bar-fill,
1264 #health-bar-fill {
958 1265 flex: 1;
959 1266 width: 100%;
960 1267 transform-origin: bottom center;
961 1268 transform: scaleY(1);
962 background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
963 1269 border-radius: 1px;
964 1270 transition: transform 80ms linear;
965 1271 }
966 1272
1273 #stamina-bar-fill {
1274 background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
1275 }
1276
1277 #health-bar-fill {
1278 background: linear-gradient(180deg, #e06060 0%, #a02828 100%);
1279 }
1280
967 1281 #stamina-bar.empty #stamina-bar-fill {
968 1282 background: #4a3030;
969 1283 }
970 1284
1285 #health-bar.empty #health-bar-fill {
1286 background: #3a2020;
1287 }
1288
971 1289 #stamina-bar.low #stamina-bar-fill {
972 1290 background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);
973 1291 }
974 1292
975 .stamina-bar-label {
1293 #health-bar.low #health-bar-fill {
1294 background: linear-gradient(180deg, #f0a040 0%, #c05020 100%);
1295 }
1296
1297 .stamina-bar-label,
1298 .health-bar-label {
976 1299 position: absolute;
977 right: calc(100% + 0.4rem);
978 bottom: 0;
979 font-size: 0.75rem;
1300 left: 50%;
1301 top: calc(100% + 0.25rem);
1302 transform: translateX(-50%);
1303 font-size: 0.65rem;
980 1304 color: #9aa3b2;
981 1305 white-space: nowrap;
982 1306 pointer-events: none;
@@ -1364,3 +1688,91 @@ a { color: #d4c48a; }
1364 1688 .item-bubble[hidden] {
1365 1689 display: none !important;
1366 1690 }
1691
1692 #bounty-panel {
1693 position: fixed;
1694 z-index: 6;
1695 top: 50%;
1696 left: 50%;
1697 transform: translate(-50%, -50%);
1698 width: min(420px, 92vw);
1699 max-height: min(70vh, 520px);
1700 overflow: auto;
1701 background: #1a1e26;
1702 border: 1px solid #2c3340;
1703 padding: 0.75rem 1rem 1rem;
1704 }
1705
1706 #bounty-panel header {
1707 display: flex;
1708 justify-content: space-between;
1709 align-items: center;
1710 gap: 0.75rem;
1711 margin-bottom: 0.5rem;
1712 }
1713
1714 .bounty-tabs {
1715 display: flex;
1716 gap: 0.25rem;
1717 margin: 0.5rem 0 0.75rem;
1718 }
1719
1720 .bounty-tab {
1721 flex: 1;
1722 font-size: 0.85rem;
1723 padding: 0.35rem 0.4rem;
1724 background: #12151b;
1725 border: 1px solid #2c3340;
1726 color: inherit;
1727 }
1728
1729 .bounty-tab.active {
1730 outline: 1px solid #6a8caf;
1731 border-color: #6a8caf;
1732 }
1733
1734 .bounty-search-row {
1735 display: flex;
1736 flex-wrap: wrap;
1737 gap: 0.5rem;
1738 align-items: end;
1739 margin-bottom: 0.75rem;
1740 }
1741
1742 .bounty-search-row label {
1743 display: flex;
1744 flex-direction: column;
1745 gap: 0.2rem;
1746 font-size: 0.8rem;
1747 }
1748
1749 .bounty-search-row input,
1750 .bounty-amount-label input {
1751 background: #12151b;
1752 border: 1px solid #2c3340;
1753 color: inherit;
1754 padding: 0.35rem 0.4rem;
1755 min-width: 6rem;
1756 }
1757
1758 .bounty-target {
1759 display: flex;
1760 gap: 0.75rem;
1761 align-items: center;
1762 margin-bottom: 0.75rem;
1763 min-height: 48px;
1764 }
1765
1766 .bounty-amount-label {
1767 display: flex;
1768 flex-direction: column;
1769 gap: 0.25rem;
1770 margin-bottom: 0.75rem;
1771 font-size: 0.85rem;
1772 }
1773
1774 .bounty-my-amount {
1775 font-size: 1.25rem;
1776 font-weight: 700;
1777 margin: 0.5rem 0 0;
1778 }
@@ -37,6 +37,94 @@ html, body {
37 display: none !important;
37 display: none !important;
38}
38}
39
39
40#settings-toggle {
41 position: fixed;
42 z-index: 4;
43 top: 0.45rem;
44 right: 0.75rem;
45 width: 2.25rem;
46 height: 2.25rem;
47 padding: 0;
48 border: 1px solid #3a4250;
49 border-radius: 0.35rem;
50 background: rgba(18, 22, 28, 0.92);
51 color: #e8e4d9;
52 font-size: 1.15rem;
53 line-height: 1;
54 cursor: pointer;
55}
56
57#settings-toggle[hidden] {
58 display: none !important;
59}
60
61#settings-panel {
62 position: fixed;
63 z-index: 5;
64 top: 3.1rem;
65 right: 0.75rem;
66 width: min(18rem, calc(100vw - 1.5rem));
67 padding: 0.75rem 0.9rem 1rem;
68 border: 1px solid #3a4250;
69 border-radius: 0.4rem;
70 background: rgba(14, 17, 22, 0.96);
71 box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
72}
73
74#settings-panel[hidden] {
75 display: none !important;
76}
77
78#settings-panel header {
79 display: flex;
80 align-items: center;
81 justify-content: space-between;
82 gap: 0.75rem;
83 margin-bottom: 0.65rem;
84}
85
86#settings-panel h2 {
87 margin: 0;
88 font-size: 1.05rem;
89 font-weight: 600;
90}
91
92#settings-panel h3 {
93 margin: 0 0 0.35rem;
94 font-size: 0.8rem;
95 font-weight: 600;
96 letter-spacing: 0.02em;
97 text-transform: uppercase;
98 color: #9aa3b2;
99}
100
101.settings-group + .settings-group {
102 margin-top: 0.85rem;
103}
104
105.settings-options {
106 display: flex;
107 flex-wrap: wrap;
108 gap: 0.35rem;
109}
110
111.settings-options button {
112 flex: 1 1 auto;
113 min-width: 4.5rem;
114 padding: 0.35rem 0.55rem;
115 border: 1px solid #3a4250;
116 border-radius: 0.3rem;
117 background: #1a2029;
118 color: #c8cdd6;
119 cursor: pointer;
120}
121
122.settings-options button.active {
123 border-color: #7a91b8;
124 background: #2a3648;
125 color: #f0f2f6;
126}
127
40#toast-stack {
128#toast-stack {
41 position: fixed;
129 position: fixed;
42 top: 3.4rem;
130 top: 3.4rem;
@@ -101,6 +189,62 @@ html, body {
101 padding: 1.25rem;
189 padding: 1.25rem;
102}
190}
103
191
192#character-list {
193 margin: 0.75rem 0 1rem;
194 max-height: min(40vh, 20rem);
195 overflow: auto;
196}
197
198#create-character-open {
199 width: 100%;
200 margin-top: 0.25rem;
201}
202
203#create-panel {
204 position: fixed;
205 z-index: 6;
206 top: 50%;
207 left: 50%;
208 transform: translate(-50%, -50%);
209 width: min(420px, 92vw);
210 max-height: min(90vh, 40rem);
211 overflow: auto;
212 padding: 1rem 1.1rem 1.15rem;
213 border: 1px solid #3a4250;
214 border-radius: 0.4rem;
215 background: rgba(18, 22, 28, 0.98);
216 box-shadow: 0 12px 36px rgba(0, 0, 0, 0.5);
217}
218
219#create-panel[hidden] {
220 display: none !important;
221}
222
223#create-panel header {
224 display: flex;
225 align-items: center;
226 justify-content: space-between;
227 gap: 0.75rem;
228 margin-bottom: 0.5rem;
229}
230
231#create-panel h2 {
232 margin: 0;
233 font-size: 1.1rem;
234}
235
236#create-panel label {
237 display: flex;
238 gap: 0.5rem;
239 align-items: center;
240 margin: 0.5rem 0;
241}
242
243#create-panel #create-form > button[type="submit"] {
244 width: 100%;
245 margin-top: 0.75rem;
246}
247
104label, .character-row {
248label, .character-row {
105 display: flex;
249 display: flex;
106 gap: 0.5rem;
250 gap: 0.5rem;
@@ -124,6 +268,65 @@ button {
124.hint { color: #9aa3b2; font-size: 0.9rem; }
268.hint { color: #9aa3b2; font-size: 0.9rem; }
125a { color: #d4c48a; }
269a { color: #d4c48a; }
126
270
271.hair-controls {
272 display: grid;
273 grid-template-columns: 72px 1fr;
274 gap: 0.45rem 0.75rem;
275 align-items: center;
276 margin: 0.75rem 0;
277}
278
279.hair-controls canvas {
280 grid-row: 1 / span 5;
281 width: 64px;
282 height: 96px;
283 image-rendering: pixelated;
284 background: #0c0e12;
285 border: 1px solid #2c3340;
286}
287
288.hair-controls label {
289 display: flex;
290 flex-direction: column;
291 align-items: stretch;
292 gap: 0.2rem;
293 margin: 0;
294 font-size: 0.8rem;
295}
296
297.hair-controls input[type="range"] {
298 width: 100%;
299 padding: 0;
300}
301
302.hair-swatch {
303 display: inline-block;
304 width: 1.25rem;
305 height: 1.25rem;
306 border: 1px solid #3a4250;
307 border-radius: 2px;
308}
309
310#barber-panel {
311 position: fixed;
312 z-index: 6;
313 top: 50%;
314 left: 50%;
315 transform: translate(-50%, -50%);
316 width: min(360px, 92vw);
317 background: #1a1e26;
318 border: 1px solid #2c3340;
319 padding: 0.75rem 1rem 1rem;
320}
321
322#barber-panel header {
323 display: flex;
324 justify-content: space-between;
325 align-items: center;
326 gap: 0.75rem;
327 margin-bottom: 0.5rem;
328}
329
127#nametag {
330#nametag {
128 position: fixed;
331 position: fixed;
129 z-index: 4;
332 z-index: 4;
@@ -933,11 +1136,113 @@ a { color: #d4c48a; }
933 background: rgba(12, 14, 18, 0.92);
1136 background: rgba(12, 14, 18, 0.92);
934}
1137}
935
1138
936#stamina-bar {
1139#vitals {
937 position: fixed;
1140 position: fixed;
938 z-index: 4;
1141 z-index: 4;
939 right: 1rem;
1142 right: 1rem;
940 bottom: 1.25rem;
1143 bottom: 1.25rem;
1144 display: flex;
1145 flex-direction: row;
1146 gap: 0.45rem;
1147 align-items: flex-end;
1148}
1149
1150#vitals[hidden] {
1151 display: none !important;
1152}
1153
1154#status-effects {
1155 display: flex;
1156 flex-direction: column-reverse;
1157 gap: 0.3rem;
1158 align-items: center;
1159 max-height: 120px;
1160 overflow: visible;
1161}
1162
1163#status-effects[hidden] {
1164 display: none !important;
1165}
1166
1167.status-effect-icon {
1168 width: 28px;
1169 height: 28px;
1170 padding: 2px;
1171 box-sizing: border-box;
1172 border: 1px solid #3a4250;
1173 background: rgba(12, 14, 18, 0.88);
1174 cursor: default;
1175 display: grid;
1176 place-items: center;
1177 image-rendering: pixelated;
1178}
1179
1180.status-effect-icon img {
1181 width: 16px;
1182 height: 16px;
1183 image-rendering: pixelated;
1184 pointer-events: none;
1185}
1186
1187.status-effect-buff {
1188 border-color: #4a7a58;
1189}
1190
1191.status-effect-debuff {
1192 border-color: #7a4a4a;
1193}
1194
1195.status-effect-icon-fallback {
1196 font-size: 0.75rem;
1197 font-weight: 700;
1198 color: #d0d6e0;
1199}
1200
1201#status-effect-tooltip {
1202 position: fixed;
1203 z-index: 20;
1204 min-width: 10rem;
1205 max-width: 16rem;
1206 padding: 0.45rem 0.55rem;
1207 background: rgba(12, 14, 18, 0.96);
1208 border: 1px solid #3a4250;
1209 color: #d0d6e0;
1210 font-size: 0.78rem;
1211 line-height: 1.35;
1212 pointer-events: none;
1213}
1214
1215#status-effect-tooltip[hidden] {
1216 display: none !important;
1217}
1218
1219#status-effect-tooltip strong {
1220 display: block;
1221 margin-bottom: 0.2rem;
1222 color: #f0f2f6;
1223 font-size: 0.82rem;
1224}
1225
1226#status-effect-tooltip p {
1227 margin: 0.15rem 0 0;
1228}
1229
1230#status-effect-tooltip .status-effect-tooltip-time {
1231 color: #9aa3b2;
1232 font-size: 0.72rem;
1233}
1234
1235#status-effect-tooltip[data-polarity="buff"] {
1236 border-color: #4a7a58;
1237}
1238
1239#status-effect-tooltip[data-polarity="debuff"] {
1240 border-color: #7a4a4a;
1241}
1242
1243#stamina-bar,
1244#health-bar {
1245 position: relative;
941 width: 14px;
1246 width: 14px;
942 height: 120px;
1247 height: 120px;
943 padding: 3px;
1248 padding: 3px;
@@ -950,33 +1255,52 @@ a { color: #d4c48a; }
950 align-items: stretch;
1255 align-items: stretch;
951}
1256}
952
1257
953#stamina-bar[hidden] {
1258#stamina-bar[hidden],
1259#health-bar[hidden] {
954 display: none !important;
1260 display: none !important;
955}
1261}
956
1262
957#stamina-bar-fill {
1263#stamina-bar-fill,
1264#health-bar-fill {
958 flex: 1;
1265 flex: 1;
959 width: 100%;
1266 width: 100%;
960 transform-origin: bottom center;
1267 transform-origin: bottom center;
961 transform: scaleY(1);
1268 transform: scaleY(1);
962 background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
963 border-radius: 1px;
1269 border-radius: 1px;
964 transition: transform 80ms linear;
1270 transition: transform 80ms linear;
965}
1271}
966
1272
1273#stamina-bar-fill {
1274 background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
1275}
1276
1277#health-bar-fill {
1278 background: linear-gradient(180deg, #e06060 0%, #a02828 100%);
1279}
1280
967#stamina-bar.empty #stamina-bar-fill {
1281#stamina-bar.empty #stamina-bar-fill {
968 background: #4a3030;
1282 background: #4a3030;
969}
1283}
970
1284
1285#health-bar.empty #health-bar-fill {
1286 background: #3a2020;
1287}
1288
971#stamina-bar.low #stamina-bar-fill {
1289#stamina-bar.low #stamina-bar-fill {
972 background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);
1290 background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);
973}
1291}
974
1292
975.stamina-bar-label {
1293#health-bar.low #health-bar-fill {
1294 background: linear-gradient(180deg, #f0a040 0%, #c05020 100%);
1295}
1296
1297.stamina-bar-label,
1298.health-bar-label {
976 position: absolute;
1299 position: absolute;
977 right: calc(100% + 0.4rem);
1300 left: 50%;
978 bottom: 0;
1301 top: calc(100% + 0.25rem);
979 font-size: 0.75rem;
1302 transform: translateX(-50%);
1303 font-size: 0.65rem;
980 color: #9aa3b2;
1304 color: #9aa3b2;
981 white-space: nowrap;
1305 white-space: nowrap;
982 pointer-events: none;
1306 pointer-events: none;
@@ -1364,3 +1688,91 @@ a { color: #d4c48a; }
1364.item-bubble[hidden] {
1688.item-bubble[hidden] {
1365 display: none !important;
1689 display: none !important;
1366}
1690}
1691
1692#bounty-panel {
1693 position: fixed;
1694 z-index: 6;
1695 top: 50%;
1696 left: 50%;
1697 transform: translate(-50%, -50%);
1698 width: min(420px, 92vw);
1699 max-height: min(70vh, 520px);
1700 overflow: auto;
1701 background: #1a1e26;
1702 border: 1px solid #2c3340;
1703 padding: 0.75rem 1rem 1rem;
1704}
1705
1706#bounty-panel header {
1707 display: flex;
1708 justify-content: space-between;
1709 align-items: center;
1710 gap: 0.75rem;
1711 margin-bottom: 0.5rem;
1712}
1713
1714.bounty-tabs {
1715 display: flex;
1716 gap: 0.25rem;
1717 margin: 0.5rem 0 0.75rem;
1718}
1719
1720.bounty-tab {
1721 flex: 1;
1722 font-size: 0.85rem;
1723 padding: 0.35rem 0.4rem;
1724 background: #12151b;
1725 border: 1px solid #2c3340;
1726 color: inherit;
1727}
1728
1729.bounty-tab.active {
1730 outline: 1px solid #6a8caf;
1731 border-color: #6a8caf;
1732}
1733
1734.bounty-search-row {
1735 display: flex;
1736 flex-wrap: wrap;
1737 gap: 0.5rem;
1738 align-items: end;
1739 margin-bottom: 0.75rem;
1740}
1741
1742.bounty-search-row label {
1743 display: flex;
1744 flex-direction: column;
1745 gap: 0.2rem;
1746 font-size: 0.8rem;
1747}
1748
1749.bounty-search-row input,
1750.bounty-amount-label input {
1751 background: #12151b;
1752 border: 1px solid #2c3340;
1753 color: inherit;
1754 padding: 0.35rem 0.4rem;
1755 min-width: 6rem;
1756}
1757
1758.bounty-target {
1759 display: flex;
1760 gap: 0.75rem;
1761 align-items: center;
1762 margin-bottom: 0.75rem;
1763 min-height: 48px;
1764}
1765
1766.bounty-amount-label {
1767 display: flex;
1768 flex-direction: column;
1769 gap: 0.25rem;
1770 margin-bottom: 0.75rem;
1771 font-size: 0.85rem;
1772}
1773
1774.bounty-my-amount {
1775 font-size: 1.25rem;
1776 font-weight: 700;
1777 margin: 0.5rem 0 0;
1778}
docs/FEATURES.md +62 −20
@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
52 52 ## World settings
53 53
54 54 **Status:** full
55 **Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
55 **Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56 56 **Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
57 57
58 58 ## Baked lighting
@@ -94,8 +94,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
94 94 ## Characters
95 95
96 96 **Status:** full
97 **Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile.
98 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`
97 **Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”); existing characters are unaffected.
98 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`
99 99
100 100 ## Character deletion and inheritance
101 101
@@ -106,8 +106,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
106 106 ## 3×3 chunk replication
107 107
108 108 **Status:** full
109 **Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
110 **Code:** `server/src/simulation/simulation.js` (`snapshotFor`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`)
109 **Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
110 **Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
111 111
112 112 ## Click-to-move and A\* pathfinding
113 113
@@ -130,13 +130,19 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
130 130 ## Play viewport and camera
131 131
132 132 **Status:** full
133 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Hovering another player shows their first name; clicking them inspects instead of issuing move.
134 **Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
133 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
134 **Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
135
136 ## Client graphics settings
137
138 **Status:** full
139 **Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
140 **Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
135 141
136 142 ## Night shading
137 143
138 144 **Status:** full
139 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **animated liquid water** uses the same corner-interpolated lit values via shader uniforms (not a flat per-tile shade). **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
145 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
140 146 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
141 147
142 148 ## FrameworkV3 client bootstrap
@@ -208,7 +214,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
208 214 ## Combat, skills, groups, pigeons
209 215
210 216 **Status:** partial
211 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
217 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
212 218 **Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
213 219
214 220 ## Player death and respawn
@@ -235,7 +241,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
235 241
236 242 ## Gathering, crafting, and production skills
237 243
238 **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live)
244 **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
239 245 **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
240 246 **Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
241 247
@@ -260,14 +266,45 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
260 266 ## Stamina and running
261 267
262 268 **Status:** full
263 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
269 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
264 270 **Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
265 271
266 272 ## Alchemy / cauldron
267 273
268 **Status:** partial (potion scaffolding + flower→dye + dye mixing live)
269 **Spec:** **Herbalism** gathers flowers and cotton (**no tool**; flowers ~1s). Flower nodes respawn with a random colour tint; the visible colour is the flower you receive. **Alchemy** uses a cauldron with tabs **Alchemy** / **Dyes**. Alchemy: insert ingredients then stir/heat/cool (actions unlock after the first insert); step transcript hashes to a flavor line. Opening requires ≥1 empty glass bottle. **Dyes:** up to 6 flower slots of any colours; Create Dye mixes paint-style by quantity and bottles 1 dye per flower (confirm if bottles are short). Dye bottles stack to 16 on exact RGB. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. **Glass bottle** (`ItemId.glassBottle`, sprite `potion-0`) is `npcShopAllowed` for vendor catalogs. **Plant clippers** remain for future herb nodes.
270 **Code:** `shared/definitions/alchemy.js`, `shared/definitions/dyes.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
274 **Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
275 **Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
276 **Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
277
278 ### Folklore herb associations (design only — not in code)
279
280 Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
281
282 | Tier | Herb | Associations |
283 | --- | --- | --- |
284 | 1 | Mint | Refreshment, stamina, antidotes |
285 | 1 | Garlic | Undead protection, disease resistance |
286 | 2 | Thyme | Courage, vitality, resistance |
287 | 2 | Sage | Healing, wisdom, longevity |
288 | 2 | Rosemary | Memory, protection, clarity |
289 | 3 | Lavender | Sleep, calm, dreams |
290 | 3 | Chamomile | Restoration, sleep, soothing |
291 | 3 | Nettle | Vigour, resilience, protection |
292 | 4 | Yarrow | Wound healing, battle medicine |
293 | 4 | Juniper | Purification, disease resistance |
294 | 4 | Elder | Spirits, protection, healing |
295 | 4 | Rue | Curse resistance, purification |
296 | 5 | Valerian | Sleep, sedation, tranquillity |
297 | 5 | Mugwort | Dreams, visions, divination |
298 | 5 | Wormwood | Poison resistance, spirits, bitterness |
299 | 5 | St. John's wort | Holy protection, dispel darkness |
300 | 6 | Hawthorn | Fey, barriers, enchantment |
301 | 6 | Foxglove | Fairy magic, heart magic, poison |
302 | 6 | Mistletoe | Life, fertility, druidic magic |
303 | 6 | Datura | Visions, insanity, spirit walking |
304 | 7 | Belladonna | Poison, hallucination, witchcraft |
305 | 7 | Henbane | Trance, madness, sleep, poison |
306 | 7 | Mandrake | Powerful potions, curses, life magic |
307 | 7 | Aconite | Werewolves, lethal poison, curses |
271 308
272 309 ## Inventory, items, equipment, ground drops
273 310
@@ -287,20 +324,25 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
287 324 **Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
288 325 **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
289 326
327 ## Hair & barber
328
329 **Status:** full
330 **Spec:** Character creation picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the same UI to restyle (preview hides headgear).
331 **Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`
332
290 333 ## Bounty offices
291 334
292 **Status:** not implemented
293 **Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:
335 **Status:** full
336 **Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
294 337
295 1. **Place / raise bounty** — Search a character by name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
338 1. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
296 339 2. **My bounty** — Shows how much coin is currently on **your** head.
297 340
298 **Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
341 **Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
299 342
300 343 **Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
301 344
302 **TODO:** block type + art, modal UI, character search reuse, persistent bounty ledger per character, coin add intent, nearest-office pigeon on PvP kill, vault deposit + letter body, inspect bounty line, tests.
303 **Code:** —
345 **Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
304 346
305 347 ## Banking, cheques, shops, player-driven marketplace
306 348
@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
52## World settings
52## World settings
53
53
54**Status:** full
54**Status:** full
55**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
55**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56**Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
56**Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
57
57
58## Baked lighting
58## Baked lighting
@@ -94,8 +94,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
94## Characters
94## Characters
95
95
96**Status:** full
96**Status:** full
97**Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile.
97**Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”); existing characters are unaffected.
98**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`
98**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`
99
99
100## Character deletion and inheritance
100## Character deletion and inheritance
101
101
@@ -106,8 +106,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
106## 3×3 chunk replication
106## 3×3 chunk replication
107
107
108**Status:** full
108**Status:** full
109**Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
109**Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
110**Code:** `server/src/simulation/simulation.js` (`snapshotFor`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`)
110**Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
111
111
112## Click-to-move and A\* pathfinding
112## Click-to-move and A\* pathfinding
113
113
@@ -130,13 +130,19 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
130## Play viewport and camera
130## Play viewport and camera
131
131
132**Status:** full
132**Status:** full
133**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Hovering another player shows their first name; clicking them inspects instead of issuing move.
133**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
134**Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
134**Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
135
136## Client graphics settings
137
138**Status:** full
139**Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
140**Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
135
141
136## Night shading
142## Night shading
137
143
138**Status:** full
144**Status:** full
139**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **animated liquid water** uses the same corner-interpolated lit values via shader uniforms (not a flat per-tile shade). **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
145**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
146**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
141
147
142## FrameworkV3 client bootstrap
148## FrameworkV3 client bootstrap
@@ -208,7 +214,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
208## Combat, skills, groups, pigeons
214## Combat, skills, groups, pigeons
209
215
210**Status:** partial
216**Status:** partial
211**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
217**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
212**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
218**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
213
219
214## Player death and respawn
220## Player death and respawn
@@ -235,7 +241,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
235
241
236## Gathering, crafting, and production skills
242## Gathering, crafting, and production skills
237
243
238**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live)
244**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
239**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
245**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
240**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
246**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
241
247
@@ -260,14 +266,45 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
260## Stamina and running
266## Stamina and running
261
267
262**Status:** full
268**Status:** full
263**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
269**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
264**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
270**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
265
271
266## Alchemy / cauldron
272## Alchemy / cauldron
267
273
268**Status:** partial (potion scaffolding + flower→dye + dye mixing live)
274**Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
269**Spec:** **Herbalism** gathers flowers and cotton (**no tool**; flowers ~1s). Flower nodes respawn with a random colour tint; the visible colour is the flower you receive. **Alchemy** uses a cauldron with tabs **Alchemy** / **Dyes**. Alchemy: insert ingredients then stir/heat/cool (actions unlock after the first insert); step transcript hashes to a flavor line. Opening requires ≥1 empty glass bottle. **Dyes:** up to 6 flower slots of any colours; Create Dye mixes paint-style by quantity and bottles 1 dye per flower (confirm if bottles are short). Dye bottles stack to 16 on exact RGB. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. **Glass bottle** (`ItemId.glassBottle`, sprite `potion-0`) is `npcShopAllowed` for vendor catalogs. **Plant clippers** remain for future herb nodes.
275**Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
270**Code:** `shared/definitions/alchemy.js`, `shared/definitions/dyes.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
276**Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
277
278### Folklore herb associations (design only — not in code)
279
280Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
281
282| Tier | Herb | Associations |
283| --- | --- | --- |
284| 1 | Mint | Refreshment, stamina, antidotes |
285| 1 | Garlic | Undead protection, disease resistance |
286| 2 | Thyme | Courage, vitality, resistance |
287| 2 | Sage | Healing, wisdom, longevity |
288| 2 | Rosemary | Memory, protection, clarity |
289| 3 | Lavender | Sleep, calm, dreams |
290| 3 | Chamomile | Restoration, sleep, soothing |
291| 3 | Nettle | Vigour, resilience, protection |
292| 4 | Yarrow | Wound healing, battle medicine |
293| 4 | Juniper | Purification, disease resistance |
294| 4 | Elder | Spirits, protection, healing |
295| 4 | Rue | Curse resistance, purification |
296| 5 | Valerian | Sleep, sedation, tranquillity |
297| 5 | Mugwort | Dreams, visions, divination |
298| 5 | Wormwood | Poison resistance, spirits, bitterness |
299| 5 | St. John's wort | Holy protection, dispel darkness |
300| 6 | Hawthorn | Fey, barriers, enchantment |
301| 6 | Foxglove | Fairy magic, heart magic, poison |
302| 6 | Mistletoe | Life, fertility, druidic magic |
303| 6 | Datura | Visions, insanity, spirit walking |
304| 7 | Belladonna | Poison, hallucination, witchcraft |
305| 7 | Henbane | Trance, madness, sleep, poison |
306| 7 | Mandrake | Powerful potions, curses, life magic |
307| 7 | Aconite | Werewolves, lethal poison, curses |
271
308
272## Inventory, items, equipment, ground drops
309## Inventory, items, equipment, ground drops
273
310
@@ -287,20 +324,25 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
287**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
324**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
288**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
325**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
289
326
327## Hair & barber
328
329**Status:** full
330**Spec:** Character creation picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the same UI to restyle (preview hides headgear).
331**Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`
332
290## Bounty offices
333## Bounty offices
291
334
292**Status:** not implemented
335**Status:** full
293**Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:
336**Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
294
337
2951. **Place / raise bounty** — Search a character by name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
3381. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
2962. **My bounty** — Shows how much coin is currently on **your** head.
3392. **My bounty** — Shows how much coin is currently on **your** head.
297
340
298**Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
341**Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
299
342
300**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
343**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
301
344
302**TODO:** block type + art, modal UI, character search reuse, persistent bounty ledger per character, coin add intent, nearest-office pigeon on PvP kill, vault deposit + letter body, inspect bounty line, tests.
345**Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
303**Code:** —
304
346
305## Banking, cheques, shops, player-driven marketplace
347## Banking, cheques, shops, player-driven marketplace
306
348
server/src/assets/spriteCatalog.js +79 −2
@@ -1,8 +1,9 @@
1 1 import { readdirSync } from "node:fs";
2 2 import { extname, join } from "node:path";
3 import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
3 import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS, BlockType } from "../../../shared/definitions/tiles.js";
4 4 import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5 5 import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6 import { HERB_ORDER } from "../../../shared/definitions/herbs.js";
6 7 import {
7 8 ORE_BEARING_MATERIALS,
8 9 oreBoulderState,
@@ -32,9 +33,15 @@ const CHARACTER_DEFINITIONS = Object.freeze({
32 33
33 34 export function buildSpriteCatalog (assetRoot)
34 35 {
36 const blockDefs = Object.fromEntries(
37 Object.entries(BLOCK_DEFINITIONS).filter(([, def]) => def.key !== "herb")
38 );
35 39 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
36 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
40 const blocks = scanLayer(join(assetRoot, "blocks"), blockDefs, "block", "blocks");
37 41 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
42 const herbs = scanHerbAssets(join(assetRoot, "herbs"));
43 Object.assign(blocks.types, herbs.blockTypes);
44 Object.assign(items.types, herbs.itemTypes);
38 45 const mobs = scanMobLayers(assetRoot);
39 46 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
40 47 const fx = scanFx(join(assetRoot, "fx"));
@@ -49,6 +56,7 @@ export function buildSpriteCatalog (assetRoot)
49 56 ...grounds.images,
50 57 ...blocks.images,
51 58 ...items.images,
59 ...herbs.images,
52 60 ...mobs.images,
53 61 ...characters.images,
54 62 ...fx.images
@@ -56,11 +64,80 @@ export function buildSpriteCatalog (assetRoot)
56 64 };
57 65 }
58 66
67 /**
68 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
69 */
70 function scanHerbAssets (herbRoot)
71 {
72 const stems = new Set(listPngStems(herbRoot));
73 const missing = HERB_ORDER.filter((id) => !stems.has(id));
74 if (missing.length)
75 { throw new Error(`Missing herb sprites in ${herbRoot}: ${missing.join(", ")}`); }
76
77 const images = [];
78 for (const herbId of HERB_ORDER)
79 {
80 const url = `/assets/herbs/${herbId}.png`;
81 images.push({
82 name: spriteImageName("block", "herb", herbId),
83 url,
84 subImgTotal: 1,
85 perRow: 1,
86 loop: false,
87 animationSpeed: 0
88 });
89 images.push({
90 name: spriteImageName("item", "herbs", herbId),
91 url,
92 subImgTotal: 1,
93 perRow: 1,
94 loop: false,
95 animationSpeed: 0
96 });
97 }
98
99 const blockTypes = {
100 herb: {
101 key: "herb",
102 typeId: BlockType.herbPlant,
103 states: [...HERB_ORDER],
104 defaultState: HERB_ORDER[0],
105 blooms: {},
106 equips: {},
107 equipBlooms: {},
108 frames: 1,
109 framesPerRow: 1,
110 animationSpeed: 0,
111 outdoor: true,
112 seasonal: false
113 }
114 };
115 const itemTypes = {
116 herbs: {
117 key: "herbs",
118 typeId: "herbs",
119 states: [...HERB_ORDER],
120 defaultState: HERB_ORDER[0],
121 blooms: {},
122 equips: {},
123 equipBlooms: {},
124 frames: 1,
125 framesPerRow: 1,
126 animationSpeed: 0,
127 outdoor: false,
128 seasonal: false
129 }
130 };
131 return { images, blockTypes, itemTypes };
132 }
133
59 134 function itemScanDefs ()
60 135 {
61 136 const defs = {};
62 137 for (const def of Object.values(ITEM_DEFINITIONS))
63 138 {
139 if (def?.herb)
140 { continue; }
64 141 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
65 142 if (!folderKey || defs[folderKey])
66 143 { continue; }
@@ -1,8 +1,9 @@
1import { readdirSync } from "node:fs";
1import { readdirSync } from "node:fs";
2import { extname, join } from "node:path";
2import { extname, join } from "node:path";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS, BlockType } from "../../../shared/definitions/tiles.js";
4import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
4import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
5import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6import { HERB_ORDER } from "../../../shared/definitions/herbs.js";
6import {
7import {
7 ORE_BEARING_MATERIALS,
8 ORE_BEARING_MATERIALS,
8 oreBoulderState,
9 oreBoulderState,
@@ -32,9 +33,15 @@ const CHARACTER_DEFINITIONS = Object.freeze({
32
33
33export function buildSpriteCatalog (assetRoot)
34export function buildSpriteCatalog (assetRoot)
34{
35{
36 const blockDefs = Object.fromEntries(
37 Object.entries(BLOCK_DEFINITIONS).filter(([, def]) => def.key !== "herb")
38 );
35 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
39 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
36 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
40 const blocks = scanLayer(join(assetRoot, "blocks"), blockDefs, "block", "blocks");
37 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
41 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
42 const herbs = scanHerbAssets(join(assetRoot, "herbs"));
43 Object.assign(blocks.types, herbs.blockTypes);
44 Object.assign(items.types, herbs.itemTypes);
38 const mobs = scanMobLayers(assetRoot);
45 const mobs = scanMobLayers(assetRoot);
39 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
46 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
40 const fx = scanFx(join(assetRoot, "fx"));
47 const fx = scanFx(join(assetRoot, "fx"));
@@ -49,6 +56,7 @@ export function buildSpriteCatalog (assetRoot)
49 ...grounds.images,
56 ...grounds.images,
50 ...blocks.images,
57 ...blocks.images,
51 ...items.images,
58 ...items.images,
59 ...herbs.images,
52 ...mobs.images,
60 ...mobs.images,
53 ...characters.images,
61 ...characters.images,
54 ...fx.images
62 ...fx.images
@@ -56,11 +64,80 @@ export function buildSpriteCatalog (assetRoot)
56 };
64 };
57}
65}
58
66
67/**
68 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
69 */
70function scanHerbAssets (herbRoot)
71{
72 const stems = new Set(listPngStems(herbRoot));
73 const missing = HERB_ORDER.filter((id) => !stems.has(id));
74 if (missing.length)
75 { throw new Error(`Missing herb sprites in ${herbRoot}: ${missing.join(", ")}`); }
76
77 const images = [];
78 for (const herbId of HERB_ORDER)
79 {
80 const url = `/assets/herbs/${herbId}.png`;
81 images.push({
82 name: spriteImageName("block", "herb", herbId),
83 url,
84 subImgTotal: 1,
85 perRow: 1,
86 loop: false,
87 animationSpeed: 0
88 });
89 images.push({
90 name: spriteImageName("item", "herbs", herbId),
91 url,
92 subImgTotal: 1,
93 perRow: 1,
94 loop: false,
95 animationSpeed: 0
96 });
97 }
98
99 const blockTypes = {
100 herb: {
101 key: "herb",
102 typeId: BlockType.herbPlant,
103 states: [...HERB_ORDER],
104 defaultState: HERB_ORDER[0],
105 blooms: {},
106 equips: {},
107 equipBlooms: {},
108 frames: 1,
109 framesPerRow: 1,
110 animationSpeed: 0,
111 outdoor: true,
112 seasonal: false
113 }
114 };
115 const itemTypes = {
116 herbs: {
117 key: "herbs",
118 typeId: "herbs",
119 states: [...HERB_ORDER],
120 defaultState: HERB_ORDER[0],
121 blooms: {},
122 equips: {},
123 equipBlooms: {},
124 frames: 1,
125 framesPerRow: 1,
126 animationSpeed: 0,
127 outdoor: false,
128 seasonal: false
129 }
130 };
131 return { images, blockTypes, itemTypes };
132}
133
59function itemScanDefs ()
134function itemScanDefs ()
60{
135{
61 const defs = {};
136 const defs = {};
62 for (const def of Object.values(ITEM_DEFINITIONS))
137 for (const def of Object.values(ITEM_DEFINITIONS))
63 {
138 {
139 if (def?.herb)
140 { continue; }
64 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
141 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
65 if (!folderKey || defs[folderKey])
142 if (!folderKey || defs[folderKey])
66 { continue; }
143 { continue; }
server/src/barber/service.js added +139 −0
@@ -0,0 +1,139 @@
1 import {
2 DEFAULT_HAIR_STYLE,
3 hairFromCharacterRow,
4 isValidHairStyle,
5 listHairStyles,
6 normalizeHairSliders,
7 normalizeHairStyle
8 } from "../../../shared/appearance/hair.js";
9 import { BlockType } from "../../../shared/definitions/tiles.js";
10 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
11 import { tileToChunk, tileToLocal } from "../world/coordinates.js";
12
13 function userError (message)
14 {
15 const error = new Error(message);
16 error.userFacing = true;
17 return error;
18 }
19
20 export class BarberService
21 {
22 constructor (stateDb, simulation)
23 {
24 this.stateDb = stateDb;
25 this.simulation = simulation;
26 }
27
28 handleCommand (sessionId, command)
29 {
30 switch (command.type)
31 {
32 case "open-barber":
33 return this.open(sessionId, command.characterId);
34 case "set-hair":
35 return this.setHair(sessionId, command.characterId, command.hair);
36 case "close-barber":
37 return { events: [{ type: "barber-closed", sessionId, characterId: command.characterId }] };
38 default:
39 return null;
40 }
41 }
42
43 open (sessionId, characterId)
44 {
45 this.#requireNearBarber(characterId);
46 const row = this.stateDb.getCharacter(characterId);
47 if (!row)
48 { throw userError("Character not found."); }
49 const hair = hairFromCharacterRow(row);
50 const sex = row.sex === "female" ? "female" : "male";
51 return {
52 events: [{
53 type: "barber-snapshot",
54 sessionId,
55 characterId,
56 sex,
57 styles: listHairStyles(sex),
58 hair: {
59 style: hair?.style ?? DEFAULT_HAIR_STYLE,
60 hue: hair?.hue ?? 30,
61 saturation: hair?.saturation ?? 0.55,
62 darkness: hair?.darkness ?? 0.45
63 }
64 }]
65 };
66 }
67
68 setHair (sessionId, characterId, hairInput)
69 {
70 this.#requireNearBarber(characterId);
71 const row = this.stateDb.getCharacter(characterId);
72 if (!row)
73 { throw userError("Character not found."); }
74 const sex = row.sex === "female" ? "female" : "male";
75 if (!isValidHairStyle(sex, hairInput?.style))
76 { throw userError("Unknown hair style."); }
77 const style = normalizeHairStyle(sex, hairInput?.style ?? DEFAULT_HAIR_STYLE);
78 const sliders = normalizeHairSliders(hairInput);
79 const hair = {
80 style,
81 hue: sliders.hue,
82 saturation: sliders.saturation,
83 darkness: sliders.darkness
84 };
85 this.simulation.setCharacterHair(characterId, hair);
86 return {
87 events: [{
88 type: "barber-snapshot",
89 sessionId,
90 characterId,
91 sex,
92 styles: listHairStyles(sex),
93 hair,
94 message: "Hair updated."
95 }]
96 };
97 }
98
99 #requireNearBarber (characterId)
100 {
101 const entityId = this.simulation.characterEntities.get(characterId);
102 const position = entityId ? this.simulation.positionOf(entityId) : null;
103 if (!position)
104 { throw userError("Enter the world before visiting the barber."); }
105 if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY))
106 { throw userError("Stand next to a Barber."); }
107 return position;
108 }
109 }
110
111 function isAdjacentToBarber (simulation, tileX, tileY)
112 {
113 for (let dy = -1; dy <= 1; dy++)
114 {
115 for (let dx = -1; dx <= 1; dx++)
116 {
117 if (blockTypeAt(simulation, tileX + dx, tileY + dy) === BlockType.barber)
118 { return true; }
119 }
120 }
121 return false;
122 }
123
124 function blockTypeAt (simulation, tileX, tileY)
125 {
126 const chunkX = tileToChunk(tileX);
127 const chunkY = tileToChunk(tileY);
128 for (const worker of simulation.workers ?? [])
129 {
130 const data = worker.world?.chunkData?.(chunkX, chunkY);
131 if (!data?.blocks)
132 { continue; }
133 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
134 const typeId = data.blocks[index]?.typeId;
135 if (typeId != null)
136 { return typeId; }
137 }
138 return null;
139 }
@@ -0,0 +1,139 @@
1import {
2 DEFAULT_HAIR_STYLE,
3 hairFromCharacterRow,
4 isValidHairStyle,
5 listHairStyles,
6 normalizeHairSliders,
7 normalizeHairStyle
8} from "../../../shared/appearance/hair.js";
9import { BlockType } from "../../../shared/definitions/tiles.js";
10import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
11import { tileToChunk, tileToLocal } from "../world/coordinates.js";
12
13function userError (message)
14{
15 const error = new Error(message);
16 error.userFacing = true;
17 return error;
18}
19
20export class BarberService
21{
22 constructor (stateDb, simulation)
23 {
24 this.stateDb = stateDb;
25 this.simulation = simulation;
26 }
27
28 handleCommand (sessionId, command)
29 {
30 switch (command.type)
31 {
32 case "open-barber":
33 return this.open(sessionId, command.characterId);
34 case "set-hair":
35 return this.setHair(sessionId, command.characterId, command.hair);
36 case "close-barber":
37 return { events: [{ type: "barber-closed", sessionId, characterId: command.characterId }] };
38 default:
39 return null;
40 }
41 }
42
43 open (sessionId, characterId)
44 {
45 this.#requireNearBarber(characterId);
46 const row = this.stateDb.getCharacter(characterId);
47 if (!row)
48 { throw userError("Character not found."); }
49 const hair = hairFromCharacterRow(row);
50 const sex = row.sex === "female" ? "female" : "male";
51 return {
52 events: [{
53 type: "barber-snapshot",
54 sessionId,
55 characterId,
56 sex,
57 styles: listHairStyles(sex),
58 hair: {
59 style: hair?.style ?? DEFAULT_HAIR_STYLE,
60 hue: hair?.hue ?? 30,
61 saturation: hair?.saturation ?? 0.55,
62 darkness: hair?.darkness ?? 0.45
63 }
64 }]
65 };
66 }
67
68 setHair (sessionId, characterId, hairInput)
69 {
70 this.#requireNearBarber(characterId);
71 const row = this.stateDb.getCharacter(characterId);
72 if (!row)
73 { throw userError("Character not found."); }
74 const sex = row.sex === "female" ? "female" : "male";
75 if (!isValidHairStyle(sex, hairInput?.style))
76 { throw userError("Unknown hair style."); }
77 const style = normalizeHairStyle(sex, hairInput?.style ?? DEFAULT_HAIR_STYLE);
78 const sliders = normalizeHairSliders(hairInput);
79 const hair = {
80 style,
81 hue: sliders.hue,
82 saturation: sliders.saturation,
83 darkness: sliders.darkness
84 };
85 this.simulation.setCharacterHair(characterId, hair);
86 return {
87 events: [{
88 type: "barber-snapshot",
89 sessionId,
90 characterId,
91 sex,
92 styles: listHairStyles(sex),
93 hair,
94 message: "Hair updated."
95 }]
96 };
97 }
98
99 #requireNearBarber (characterId)
100 {
101 const entityId = this.simulation.characterEntities.get(characterId);
102 const position = entityId ? this.simulation.positionOf(entityId) : null;
103 if (!position)
104 { throw userError("Enter the world before visiting the barber."); }
105 if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY))
106 { throw userError("Stand next to a Barber."); }
107 return position;
108 }
109}
110
111function isAdjacentToBarber (simulation, tileX, tileY)
112{
113 for (let dy = -1; dy <= 1; dy++)
114 {
115 for (let dx = -1; dx <= 1; dx++)
116 {
117 if (blockTypeAt(simulation, tileX + dx, tileY + dy) === BlockType.barber)
118 { return true; }
119 }
120 }
121 return false;
122}
123
124function blockTypeAt (simulation, tileX, tileY)
125{
126 const chunkX = tileToChunk(tileX);
127 const chunkY = tileToChunk(tileY);
128 for (const worker of simulation.workers ?? [])
129 {
130 const data = worker.world?.chunkData?.(chunkX, chunkY);
131 if (!data?.blocks)
132 { continue; }
133 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
134 const typeId = data.blocks[index]?.typeId;
135 if (typeId != null)
136 { return typeId; }
137 }
138 return null;
139}
server/src/bounty/service.js added +321 −0
@@ -0,0 +1,321 @@
1 import { randomUUID } from "node:crypto";
2 import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";
3 import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";
4 import { layersFromBag } from "../../../shared/appearance/layers.js";
5 import {
6 addCoinsToSlots,
7 normalizeVault,
8 takeCoinsFromSlots
9 } from "../../../shared/items/inventory.js";
10
11 function userError (message)
12 {
13 const error = new Error(message);
14 error.userFacing = true;
15 return error;
16 }
17
18 function chebyshev (ax, ay, bx, by)
19 {
20 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
21 }
22
23 /**
24 * Bounty office: place/raise bounties (near office), settle PvP kills into killer vault + letter.
25 */
26 export class BountyService
27 {
28 constructor (stateDb, simulation, courier)
29 {
30 this.stateDb = stateDb;
31 this.simulation = simulation;
32 this.courier = courier;
33 }
34
35 handleCommand (sessionId, command)
36 {
37 switch (command.type)
38 {
39 case "open-bounty":
40 return this.open(sessionId, command.characterId);
41 case "raise-bounty":
42 return this.placeOrRaise(
43 sessionId,
44 command.characterId,
45 command.firstName,
46 command.lastName,
47 command.amountCopper
48 );
49 case "get-character-bounty":
50 return this.lookup(
51 sessionId,
52 command.characterId,
53 command.targetCharacterId,
54 command.firstName,
55 command.lastName
56 );
57 case "close-bounty":
58 return { events: [{ type: "bounty-closed", sessionId, characterId: command.characterId }] };
59 default:
60 return null;
61 }
62 }
63
64 open (sessionId, characterId)
65 {
66 this.#requireNearOffice(characterId);
67 return {
68 events: [{
69 type: "bounty-snapshot",
70 sessionId,
71 characterId,
72 ...this.#myBountyPayload(characterId)
73 }]
74 };
75 }
76
77 /**
78 * Lookup target by characterId or first+last name. Adjacency not required (inspect UI).
79 */
80 lookup (sessionId, requesterCharacterId, targetCharacterId, firstName, lastName)
81 {
82 let row = null;
83 if (targetCharacterId)
84 { row = this.stateDb.getCharacter(targetCharacterId | 0); }
85 else
86 {
87 const first = String(firstName ?? "").trim();
88 const last = String(lastName ?? "").trim();
89 if (!first || !last)
90 { throw userError("Enter a first and last name."); }
91 row = this.stateDb.getCharacterByName(first, last);
92 }
93 if (!row)
94 { throw userError("No adventurer by that name."); }
95
96 const amountCopper = this.stateDb.getCharacterBounty(row.character_id);
97 const bag = this.#loadBagQuiet(row.character_id);
98 return {
99 events: [{
100 type: "character-bounty",
101 sessionId,
102 characterId: requesterCharacterId,
103 target: {
104 characterId: row.character_id,
105 firstName: row.first_name,
106 lastName: row.last_name,
107 sex: row.sex,
108 layers: layersFromBag(row.sex, bag),
109 amountCopper,
110 amountLabel: formatBountyCopper(amountCopper)
111 }
112 }]
113 };
114 }
115
116 placeOrRaise (sessionId, placerCharacterId, firstName, lastName, amountCopper)
117 {
118 this.#requireNearOffice(placerCharacterId);
119 const first = String(firstName ?? "").trim();
120 const last = String(lastName ?? "").trim();
121 if (!first || !last)
122 { throw userError("Enter a first and last name."); }
123 const copper = Math.floor(Number(amountCopper) || 0);
124 if (!Number.isFinite(copper) || copper <= 0)
125 { throw userError("Enter a positive coin amount."); }
126
127 const target = this.stateDb.getCharacterByName(first, last);
128 if (!target)
129 { throw userError("No adventurer by that name."); }
130 const targetId = target.character_id | 0;
131 if (targetId === (placerCharacterId | 0))
132 { throw userError("You cannot place a bounty on yourself."); }
133
134 const previous = this.stateDb.getCharacterBounty(targetId);
135 const bag = this.#loadBag(placerCharacterId);
136 const paid = takeCoinsFromSlots(bag.inventory ?? [], copper);
137 if (!paid.ok)
138 { throw userError(`Need ${formatQuantity(copper)} in your inventory.`); }
139 bag.inventory = paid.slots;
140 this.#persistBag(placerCharacterId, bag);
141
142 const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
143 this.simulation.pendingPrivate.push({
144 type: "toast",
145 characterId: targetId,
146 message: previous > 0
147 ? `Someone raised the bounty on your head to ${formatBountyCopper(nextAmount)}.`
148 : `A bounty of ${formatBountyCopper(nextAmount)} has been placed on your head.`
149 });
150
151 return {
152 events: [{
153 type: "bounty-snapshot",
154 sessionId,
155 characterId: placerCharacterId,
156 ...this.#myBountyPayload(placerCharacterId),
157 raised: {
158 characterId: targetId,
159 firstName: target.first_name,
160 lastName: target.last_name,
161 amountCopper: nextAmount,
162 amountLabel: formatBountyCopper(nextAmount),
163 addedCopper: copper,
164 message: previous > 0
165 ? `Raised bounty on ${target.first_name} ${target.last_name} to ${formatBountyCopper(nextAmount)}.`
166 : `Placed a ${formatBountyCopper(nextAmount)} bounty on ${target.first_name} ${target.last_name}.`
167 }
168 }]
169 };
170 }
171
172 /**
173 * Called when a player dies. PvP killer collects full bounty into vault + office letter.
174 * @returns {{ paidCopper: number, victimName: string } | null}
175 */
176 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
177 {
178 const attackerId = attackerEntityId | 0;
179 if (!attackerId)
180 { return null; }
181 const attackerRec = this.simulation.directory.get(attackerId);
182 const killerCharacterId = attackerRec?.characterId | 0;
183 if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
184 { return null; }
185
186 const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
187 if (paidCopper <= 0)
188 { return null; }
189
190 const bag = this.#loadBag(killerCharacterId);
191 const vault = normalizeVault(
192 bag.vaultReserved != null
193 ? { slots: bag.vault, reserved: bag.vaultReserved }
194 : bag.vault
195 );
196 const added = addCoinsToSlots(vault.slots, paidCopper, { growable: true });
197 bag.vault = added.slots;
198 bag.vaultReserved = vault.reserved;
199 this.#persistBag(killerCharacterId, bag);
200
201 const victim = this.stateDb.getCharacter(victimCharacterId);
202 const killer = this.stateDb.getCharacter(killerCharacterId);
203 const victimName = victim
204 ? `${victim.first_name} ${victim.last_name}`.trim()
205 : "someone";
206 const killerName = killer
207 ? `${killer.first_name} ${killer.last_name}`.trim()
208 : "Adventurer";
209
210 this.#dispatchPayoutLetter({
211 killerCharacterId,
212 killerName,
213 victimName,
214 paidCopper,
215 deathTileX,
216 deathTileY
217 });
218
219 this.simulation.pendingPrivate.push({
220 type: "toast",
221 characterId: killerCharacterId,
222 message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
223 });
224
225 return { paidCopper, victimName };
226 }
227
228 #myBountyPayload (characterId)
229 {
230 const amountCopper = this.stateDb.getCharacterBounty(characterId);
231 return {
232 myAmountCopper: amountCopper,
233 myAmountLabel: formatBountyCopper(amountCopper),
234 message: amountCopper > 0
235 ? `Bounty on your head: ${formatBountyCopper(amountCopper)}.`
236 : "No bounty on your head."
237 };
238 }
239
240 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY })
241 {
242 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0)
243 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0 };
244 const body = bountyPayoutLetterBody({
245 killerName,
246 victimName,
247 amountCopper: paidCopper
248 }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
249 const stack = {
250 itemId: ItemId.letter,
251 quantity: 1,
252 instance: {
253 kind: "letter",
254 letterId: randomUUID(),
255 authorCharacterId: 0,
256 authorDisplayName: "Bounty Office",
257 body,
258 opened: false,
259 writtenAt: Date.now()
260 }
261 };
262 try
263 {
264 this.courier.dispatchHeldCargo({
265 senderCharacterId: killerCharacterId,
266 originTileX: office.tileX,
267 originTileY: office.tileY,
268 destination: { kind: "bank" },
269 cargo: { kind: "item", stack },
270 vaultCharacterId: killerCharacterId
271 });
272 }
273 catch
274 {
275 /* Coins already vaulted; letter is best-effort if no bank exists. */
276 }
277 }
278
279 #requireNearOffice (characterId)
280 {
281 const entityId = this.simulation.characterEntities.get(characterId);
282 const position = entityId ? this.simulation.positionOf(entityId) : null;
283 if (!position)
284 { throw userError("Enter the world before using a Bounty Office."); }
285 const tiles = this.courier?.bountyOfficeTiles ?? [];
286 if (!tiles.length)
287 { throw userError("No Bounty Office exists in this world yet."); }
288 const near = tiles.some((tile) =>
289 chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
290 if (!near)
291 { throw userError("Stand next to a Bounty Office."); }
292 return position;
293 }
294
295 #loadBagQuiet (characterId)
296 {
297 const onlineId = this.simulation.characterEntities.get(characterId);
298 return onlineId
299 ? this.simulation.bagOf(onlineId)
300 : this.stateDb.getBag(characterId);
301 }
302
303 #loadBag (characterId)
304 {
305 const bag = this.#loadBagQuiet(characterId);
306 if (!bag)
307 { throw userError("No bag."); }
308 return bag;
309 }
310
311 #persistBag (characterId, bag)
312 {
313 this.stateDb.saveBag(characterId, bag);
314 const onlineId = this.simulation.characterEntities.get(characterId);
315 if (onlineId)
316 {
317 this.simulation.applyBag(onlineId, bag);
318 this.simulation.pushInventory(characterId, bag);
319 }
320 }
321 }
@@ -0,0 +1,321 @@
1import { randomUUID } from "node:crypto";
2import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";
3import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";
4import { layersFromBag } from "../../../shared/appearance/layers.js";
5import {
6 addCoinsToSlots,
7 normalizeVault,
8 takeCoinsFromSlots
9} from "../../../shared/items/inventory.js";
10
11function userError (message)
12{
13 const error = new Error(message);
14 error.userFacing = true;
15 return error;
16}
17
18function chebyshev (ax, ay, bx, by)
19{
20 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
21}
22
23/**
24 * Bounty office: place/raise bounties (near office), settle PvP kills into killer vault + letter.
25 */
26export class BountyService
27{
28 constructor (stateDb, simulation, courier)
29 {
30 this.stateDb = stateDb;
31 this.simulation = simulation;
32 this.courier = courier;
33 }
34
35 handleCommand (sessionId, command)
36 {
37 switch (command.type)
38 {
39 case "open-bounty":
40 return this.open(sessionId, command.characterId);
41 case "raise-bounty":
42 return this.placeOrRaise(
43 sessionId,
44 command.characterId,
45 command.firstName,
46 command.lastName,
47 command.amountCopper
48 );
49 case "get-character-bounty":
50 return this.lookup(
51 sessionId,
52 command.characterId,
53 command.targetCharacterId,
54 command.firstName,
55 command.lastName
56 );
57 case "close-bounty":
58 return { events: [{ type: "bounty-closed", sessionId, characterId: command.characterId }] };
59 default:
60 return null;
61 }
62 }
63
64 open (sessionId, characterId)
65 {
66 this.#requireNearOffice(characterId);
67 return {
68 events: [{
69 type: "bounty-snapshot",
70 sessionId,
71 characterId,
72 ...this.#myBountyPayload(characterId)
73 }]
74 };
75 }
76
77 /**
78 * Lookup target by characterId or first+last name. Adjacency not required (inspect UI).
79 */
80 lookup (sessionId, requesterCharacterId, targetCharacterId, firstName, lastName)
81 {
82 let row = null;
83 if (targetCharacterId)
84 { row = this.stateDb.getCharacter(targetCharacterId | 0); }
85 else
86 {
87 const first = String(firstName ?? "").trim();
88 const last = String(lastName ?? "").trim();
89 if (!first || !last)
90 { throw userError("Enter a first and last name."); }
91 row = this.stateDb.getCharacterByName(first, last);
92 }
93 if (!row)
94 { throw userError("No adventurer by that name."); }
95
96 const amountCopper = this.stateDb.getCharacterBounty(row.character_id);
97 const bag = this.#loadBagQuiet(row.character_id);
98 return {
99 events: [{
100 type: "character-bounty",
101 sessionId,
102 characterId: requesterCharacterId,
103 target: {
104 characterId: row.character_id,
105 firstName: row.first_name,
106 lastName: row.last_name,
107 sex: row.sex,
108 layers: layersFromBag(row.sex, bag),
109 amountCopper,
110 amountLabel: formatBountyCopper(amountCopper)
111 }
112 }]
113 };
114 }
115
116 placeOrRaise (sessionId, placerCharacterId, firstName, lastName, amountCopper)
117 {
118 this.#requireNearOffice(placerCharacterId);
119 const first = String(firstName ?? "").trim();
120 const last = String(lastName ?? "").trim();
121 if (!first || !last)
122 { throw userError("Enter a first and last name."); }
123 const copper = Math.floor(Number(amountCopper) || 0);
124 if (!Number.isFinite(copper) || copper <= 0)
125 { throw userError("Enter a positive coin amount."); }
126
127 const target = this.stateDb.getCharacterByName(first, last);
128 if (!target)
129 { throw userError("No adventurer by that name."); }
130 const targetId = target.character_id | 0;
131 if (targetId === (placerCharacterId | 0))
132 { throw userError("You cannot place a bounty on yourself."); }
133
134 const previous = this.stateDb.getCharacterBounty(targetId);
135 const bag = this.#loadBag(placerCharacterId);
136 const paid = takeCoinsFromSlots(bag.inventory ?? [], copper);
137 if (!paid.ok)
138 { throw userError(`Need ${formatQuantity(copper)} in your inventory.`); }
139 bag.inventory = paid.slots;
140 this.#persistBag(placerCharacterId, bag);
141
142 const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
143 this.simulation.pendingPrivate.push({
144 type: "toast",
145 characterId: targetId,
146 message: previous > 0
147 ? `Someone raised the bounty on your head to ${formatBountyCopper(nextAmount)}.`
148 : `A bounty of ${formatBountyCopper(nextAmount)} has been placed on your head.`
149 });
150
151 return {
152 events: [{
153 type: "bounty-snapshot",
154 sessionId,
155 characterId: placerCharacterId,
156 ...this.#myBountyPayload(placerCharacterId),
157 raised: {
158 characterId: targetId,
159 firstName: target.first_name,
160 lastName: target.last_name,
161 amountCopper: nextAmount,
162 amountLabel: formatBountyCopper(nextAmount),
163 addedCopper: copper,
164 message: previous > 0
165 ? `Raised bounty on ${target.first_name} ${target.last_name} to ${formatBountyCopper(nextAmount)}.`
166 : `Placed a ${formatBountyCopper(nextAmount)} bounty on ${target.first_name} ${target.last_name}.`
167 }
168 }]
169 };
170 }
171
172 /**
173 * Called when a player dies. PvP killer collects full bounty into vault + office letter.
174 * @returns {{ paidCopper: number, victimName: string } | null}
175 */
176 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
177 {
178 const attackerId = attackerEntityId | 0;
179 if (!attackerId)
180 { return null; }
181 const attackerRec = this.simulation.directory.get(attackerId);
182 const killerCharacterId = attackerRec?.characterId | 0;
183 if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
184 { return null; }
185
186 const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
187 if (paidCopper <= 0)
188 { return null; }
189
190 const bag = this.#loadBag(killerCharacterId);
191 const vault = normalizeVault(
192 bag.vaultReserved != null
193 ? { slots: bag.vault, reserved: bag.vaultReserved }
194 : bag.vault
195 );
196 const added = addCoinsToSlots(vault.slots, paidCopper, { growable: true });
197 bag.vault = added.slots;
198 bag.vaultReserved = vault.reserved;
199 this.#persistBag(killerCharacterId, bag);
200
201 const victim = this.stateDb.getCharacter(victimCharacterId);
202 const killer = this.stateDb.getCharacter(killerCharacterId);
203 const victimName = victim
204 ? `${victim.first_name} ${victim.last_name}`.trim()
205 : "someone";
206 const killerName = killer
207 ? `${killer.first_name} ${killer.last_name}`.trim()
208 : "Adventurer";
209
210 this.#dispatchPayoutLetter({
211 killerCharacterId,
212 killerName,
213 victimName,
214 paidCopper,
215 deathTileX,
216 deathTileY
217 });
218
219 this.simulation.pendingPrivate.push({
220 type: "toast",
221 characterId: killerCharacterId,
222 message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
223 });
224
225 return { paidCopper, victimName };
226 }
227
228 #myBountyPayload (characterId)
229 {
230 const amountCopper = this.stateDb.getCharacterBounty(characterId);
231 return {
232 myAmountCopper: amountCopper,
233 myAmountLabel: formatBountyCopper(amountCopper),
234 message: amountCopper > 0
235 ? `Bounty on your head: ${formatBountyCopper(amountCopper)}.`
236 : "No bounty on your head."
237 };
238 }
239
240 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY })
241 {
242 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0)
243 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0 };
244 const body = bountyPayoutLetterBody({
245 killerName,
246 victimName,
247 amountCopper: paidCopper
248 }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
249 const stack = {
250 itemId: ItemId.letter,
251 quantity: 1,
252 instance: {
253 kind: "letter",
254 letterId: randomUUID(),
255 authorCharacterId: 0,
256 authorDisplayName: "Bounty Office",
257 body,
258 opened: false,
259 writtenAt: Date.now()
260 }
261 };
262 try
263 {
264 this.courier.dispatchHeldCargo({
265 senderCharacterId: killerCharacterId,
266 originTileX: office.tileX,
267 originTileY: office.tileY,
268 destination: { kind: "bank" },
269 cargo: { kind: "item", stack },
270 vaultCharacterId: killerCharacterId
271 });
272 }
273 catch
274 {
275 /* Coins already vaulted; letter is best-effort if no bank exists. */
276 }
277 }
278
279 #requireNearOffice (characterId)
280 {
281 const entityId = this.simulation.characterEntities.get(characterId);
282 const position = entityId ? this.simulation.positionOf(entityId) : null;
283 if (!position)
284 { throw userError("Enter the world before using a Bounty Office."); }
285 const tiles = this.courier?.bountyOfficeTiles ?? [];
286 if (!tiles.length)
287 { throw userError("No Bounty Office exists in this world yet."); }
288 const near = tiles.some((tile) =>
289 chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
290 if (!near)
291 { throw userError("Stand next to a Bounty Office."); }
292 return position;
293 }
294
295 #loadBagQuiet (characterId)
296 {
297 const onlineId = this.simulation.characterEntities.get(characterId);
298 return onlineId
299 ? this.simulation.bagOf(onlineId)
300 : this.stateDb.getBag(characterId);
301 }
302
303 #loadBag (characterId)
304 {
305 const bag = this.#loadBagQuiet(characterId);
306 if (!bag)
307 { throw userError("No bag."); }
308 return bag;
309 }
310
311 #persistBag (characterId, bag)
312 {
313 this.stateDb.saveBag(characterId, bag);
314 const onlineId = this.simulation.characterEntities.get(characterId);
315 if (onlineId)
316 {
317 this.simulation.applyBag(onlineId, bag);
318 this.simulation.pushInventory(characterId, bag);
319 }
320 }
321}
server/src/characters/service.js +42 −3
@@ -1,5 +1,11 @@
1 1 import { SEX } from "../../../shared/protocol/constants.js";
2 2 import { normalizeName } from "../persistence/stateDb.js";
3 import {
4 DEFAULT_HAIR_STYLE,
5 isValidHairStyle,
6 normalizeHairSliders,
7 normalizeHairStyle
8 } from "../../../shared/appearance/hair.js";
3 9
4 10 export class CharacterService
5 11 {
@@ -14,7 +20,7 @@ export class CharacterService
14 20 return this.stateDb.listCharacters(accountId).map(publicCharacter);
15 21 }
16 22
17 create (account, firstName, lastName, sex)
23 create (account, firstName, lastName, sex, hair = null, starterSettings = null)
18 24 {
19 25 const first = String(firstName ?? "").trim();
20 26 const last = String(lastName ?? "").trim();
@@ -33,7 +39,17 @@ export class CharacterService
33 39 if (existing.some((row) => row.first_normalized === firstNormalized && row.last_normalized === lastNormalized))
34 40 { throw userError("You already have a character with that name."); }
35 41
36 const character = this.stateDb.createCharacter(account.account_id, first, last, sex, 8, 8);
42 const hairFields = normalizeCreateHair(sex, hair);
43 const character = this.stateDb.createCharacter(
44 account.account_id,
45 first,
46 last,
47 sex,
48 8,
49 8,
50 hairFields,
51 starterSettings
52 );
37 53 return publicCharacter(character);
38 54 }
39 55
@@ -91,6 +107,11 @@ export class CharacterService
91 107
92 108 export function publicCharacter (row)
93 109 {
110 const sliders = normalizeHairSliders({
111 hue: row.hair_hue,
112 saturation: row.hair_saturation,
113 darkness: row.hair_darkness
114 });
94 115 return {
95 116 characterId: row.character_id,
96 117 firstName: row.first_name,
@@ -99,7 +120,25 @@ export function publicCharacter (row)
99 120 tileX: row.tile_x,
100 121 tileY: row.tile_y,
101 122 gait: row.gait,
102 deletionScheduledAt: row.deletion_scheduled_at ?? null
123 deletionScheduledAt: row.deletion_scheduled_at ?? null,
124 hairStyle: row.hair_style ?? null,
125 hairHue: sliders.hue,
126 hairSaturation: sliders.saturation,
127 hairDarkness: sliders.darkness
128 };
129 }
130
131 export function normalizeCreateHair (sex, hair)
132 {
133 if (!isValidHairStyle(sex, hair?.style))
134 { throw userError("Unknown hair style."); }
135 const style = normalizeHairStyle(sex, hair?.style ?? DEFAULT_HAIR_STYLE);
136 const sliders = normalizeHairSliders(hair);
137 return {
138 style,
139 hue: sliders.hue,
140 saturation: sliders.saturation,
141 darkness: sliders.darkness
103 142 };
104 143 }
105 144
@@ -1,5 +1,11 @@
1import { SEX } from "../../../shared/protocol/constants.js";
1import { SEX } from "../../../shared/protocol/constants.js";
2import { normalizeName } from "../persistence/stateDb.js";
2import { normalizeName } from "../persistence/stateDb.js";
3import {
4 DEFAULT_HAIR_STYLE,
5 isValidHairStyle,
6 normalizeHairSliders,
7 normalizeHairStyle
8} from "../../../shared/appearance/hair.js";
3
9
4export class CharacterService
10export class CharacterService
5{
11{
@@ -14,7 +20,7 @@ export class CharacterService
14 return this.stateDb.listCharacters(accountId).map(publicCharacter);
20 return this.stateDb.listCharacters(accountId).map(publicCharacter);
15 }
21 }
16
22
17 create (account, firstName, lastName, sex)
23 create (account, firstName, lastName, sex, hair = null, starterSettings = null)
18 {
24 {
19 const first = String(firstName ?? "").trim();
25 const first = String(firstName ?? "").trim();
20 const last = String(lastName ?? "").trim();
26 const last = String(lastName ?? "").trim();
@@ -33,7 +39,17 @@ export class CharacterService
33 if (existing.some((row) => row.first_normalized === firstNormalized && row.last_normalized === lastNormalized))
39 if (existing.some((row) => row.first_normalized === firstNormalized && row.last_normalized === lastNormalized))
34 { throw userError("You already have a character with that name."); }
40 { throw userError("You already have a character with that name."); }
35
41
36 const character = this.stateDb.createCharacter(account.account_id, first, last, sex, 8, 8);
42 const hairFields = normalizeCreateHair(sex, hair);
43 const character = this.stateDb.createCharacter(
44 account.account_id,
45 first,
46 last,
47 sex,
48 8,
49 8,
50 hairFields,
51 starterSettings
52 );
37 return publicCharacter(character);
53 return publicCharacter(character);
38 }
54 }
39
55
@@ -91,6 +107,11 @@ export class CharacterService
91
107
92export function publicCharacter (row)
108export function publicCharacter (row)
93{
109{
110 const sliders = normalizeHairSliders({
111 hue: row.hair_hue,
112 saturation: row.hair_saturation,
113 darkness: row.hair_darkness
114 });
94 return {
115 return {
95 characterId: row.character_id,
116 characterId: row.character_id,
96 firstName: row.first_name,
117 firstName: row.first_name,
@@ -99,7 +120,25 @@ export function publicCharacter (row)
99 tileX: row.tile_x,
120 tileX: row.tile_x,
100 tileY: row.tile_y,
121 tileY: row.tile_y,
101 gait: row.gait,
122 gait: row.gait,
102 deletionScheduledAt: row.deletion_scheduled_at ?? null
123 deletionScheduledAt: row.deletion_scheduled_at ?? null,
124 hairStyle: row.hair_style ?? null,
125 hairHue: sliders.hue,
126 hairSaturation: sliders.saturation,
127 hairDarkness: sliders.darkness
128 };
129}
130
131export function normalizeCreateHair (sex, hair)
132{
133 if (!isValidHairStyle(sex, hair?.style))
134 { throw userError("Unknown hair style."); }
135 const style = normalizeHairStyle(sex, hair?.style ?? DEFAULT_HAIR_STYLE);
136 const sliders = normalizeHairSliders(hair);
137 return {
138 style,
139 hue: sliders.hue,
140 saturation: sliders.saturation,
141 darkness: sliders.darkness
103 };
142 };
104}
143}
105
144
server/src/combat/service.js +4 −0
@@ -14,6 +14,7 @@ import {
14 14 effectiveSkillLevel,
15 15 equipmentBonusesFromSlots
16 16 } from "../../../shared/equipment/stats.js";
17 import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
17 18 import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
18 19 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
19 20 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -78,6 +79,9 @@ function playerCombatLevels (ecs, handle, profile)
78 79 const skills = ecs.get(handle, Component.skills);
79 80 const equipment = ecs.get(handle, Component.equipment);
80 81 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
82 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
83 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
84 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
81 85 return {
82 86 hitLevel: skillLevel(skills, profile.hitSkillId),
83 87 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
@@ -14,6 +14,7 @@ import {
14 effectiveSkillLevel,
14 effectiveSkillLevel,
15 equipmentBonusesFromSlots
15 equipmentBonusesFromSlots
16} from "../../../shared/equipment/stats.js";
16} from "../../../shared/equipment/stats.js";
17import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
17import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
18import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
18import { chunkBoundsAround, findPath } from "../navigation/astar.js";
19import { chunkBoundsAround, findPath } from "../navigation/astar.js";
19import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
20import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -78,6 +79,9 @@ function playerCombatLevels (ecs, handle, profile)
78 const skills = ecs.get(handle, Component.skills);
79 const skills = ecs.get(handle, Component.skills);
79 const equipment = ecs.get(handle, Component.equipment);
80 const equipment = ecs.get(handle, Component.equipment);
80 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
81 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
82 const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
83 bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
84 bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
81 return {
85 return {
82 hitLevel: skillLevel(skills, profile.hitSkillId),
86 hitLevel: skillLevel(skills, profile.hitSkillId),
83 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
87 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
server/src/courier/service.js +37 −9
@@ -26,49 +26,77 @@ export class CourierService
26 26 this.worldDb = worldDb;
27 27 this.simulation = simulation;
28 28 this.bankTiles = [];
29 this.bountyOfficeTiles = [];
29 30 this.refreshBankIndex();
31 this.refreshBountyOfficeIndex();
30 32 }
31 33
32 34 refreshBankIndex ()
35 {
36 this.bankTiles = this.#listBlockTiles(BlockType.bank);
37 }
38
39 refreshBountyOfficeIndex ()
40 {
41 this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
42 }
43
44 #listBlockTiles (typeId)
33 45 {
34 46 const revisionId = this.worldDb.getActiveRevisionId();
35 const banks = [];
47 const tiles = [];
36 48 for (const coord of this.worldDb.listChunkCoords(revisionId))
37 49 {
38 50 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
39 51 if (!row)
40 52 { continue; }
41 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
53 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
42 54 for (let localY = 0; localY < CHUNK_SIZE; localY++)
43 55 {
44 56 for (let localX = 0; localX < CHUNK_SIZE; localX++)
45 57 {
46 58 const block = data.blocks[localY * CHUNK_SIZE + localX];
47 if (block?.typeId !== BlockType.bank)
59 if (block?.typeId !== typeId)
48 60 { continue; }
49 banks.push({
61 tiles.push({
50 62 tileX: coord.chunk_x * CHUNK_SIZE + localX,
51 63 tileY: coord.chunk_y * CHUNK_SIZE + localY
52 64 });
53 65 }
54 66 }
55 67 }
56 this.bankTiles = banks;
68 return tiles;
57 69 }
58 70
59 71 nearestBank (tileX, tileY)
60 72 {
61 if (!this.bankTiles.length)
73 return this.#nearestTile(this.bankTiles, tileX, tileY);
74 }
75
76 nearestBountyOffice (tileX, tileY)
77 {
78 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY);
79 }
80
81 isAdjacentToBountyOffice (tileX, tileY)
82 {
83 return this.bountyOfficeTiles.some((office) =>
84 Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1);
85 }
86
87 #nearestTile (tiles, tileX, tileY)
88 {
89 if (!tiles.length)
62 90 { return null; }
63 91 let best = null;
64 92 let bestDist = Infinity;
65 for (const bank of this.bankTiles)
93 for (const tile of tiles)
66 94 {
67 const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY);
95 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
68 96 if (dist < bestDist)
69 97 {
70 98 bestDist = dist;
71 best = bank;
99 best = tile;
72 100 }
73 101 }
74 102 return best;
@@ -26,49 +26,77 @@ export class CourierService
26 this.worldDb = worldDb;
26 this.worldDb = worldDb;
27 this.simulation = simulation;
27 this.simulation = simulation;
28 this.bankTiles = [];
28 this.bankTiles = [];
29 this.bountyOfficeTiles = [];
29 this.refreshBankIndex();
30 this.refreshBankIndex();
31 this.refreshBountyOfficeIndex();
30 }
32 }
31
33
32 refreshBankIndex ()
34 refreshBankIndex ()
35 {
36 this.bankTiles = this.#listBlockTiles(BlockType.bank);
37 }
38
39 refreshBountyOfficeIndex ()
40 {
41 this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
42 }
43
44 #listBlockTiles (typeId)
33 {
45 {
34 const revisionId = this.worldDb.getActiveRevisionId();
46 const revisionId = this.worldDb.getActiveRevisionId();
35 const banks = [];
47 const tiles = [];
36 for (const coord of this.worldDb.listChunkCoords(revisionId))
48 for (const coord of this.worldDb.listChunkCoords(revisionId))
37 {
49 {
38 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
50 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
39 if (!row)
51 if (!row)
40 { continue; }
52 { continue; }
41 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
53 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
42 for (let localY = 0; localY < CHUNK_SIZE; localY++)
54 for (let localY = 0; localY < CHUNK_SIZE; localY++)
43 {
55 {
44 for (let localX = 0; localX < CHUNK_SIZE; localX++)
56 for (let localX = 0; localX < CHUNK_SIZE; localX++)
45 {
57 {
46 const block = data.blocks[localY * CHUNK_SIZE + localX];
58 const block = data.blocks[localY * CHUNK_SIZE + localX];
47 if (block?.typeId !== BlockType.bank)
59 if (block?.typeId !== typeId)
48 { continue; }
60 { continue; }
49 banks.push({
61 tiles.push({
50 tileX: coord.chunk_x * CHUNK_SIZE + localX,
62 tileX: coord.chunk_x * CHUNK_SIZE + localX,
51 tileY: coord.chunk_y * CHUNK_SIZE + localY
63 tileY: coord.chunk_y * CHUNK_SIZE + localY
52 });
64 });
53 }
65 }
54 }
66 }
55 }
67 }
56 this.bankTiles = banks;
68 return tiles;
57 }
69 }
58
70
59 nearestBank (tileX, tileY)
71 nearestBank (tileX, tileY)
60 {
72 {
61 if (!this.bankTiles.length)
73 return this.#nearestTile(this.bankTiles, tileX, tileY);
74 }
75
76 nearestBountyOffice (tileX, tileY)
77 {
78 return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY);
79 }
80
81 isAdjacentToBountyOffice (tileX, tileY)
82 {
83 return this.bountyOfficeTiles.some((office) =>
84 Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1);
85 }
86
87 #nearestTile (tiles, tileX, tileY)
88 {
89 if (!tiles.length)
62 { return null; }
90 { return null; }
63 let best = null;
91 let best = null;
64 let bestDist = Infinity;
92 let bestDist = Infinity;
65 for (const bank of this.bankTiles)
93 for (const tile of tiles)
66 {
94 {
67 const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY);
95 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
68 if (dist < bestDist)
96 if (dist < bestDist)
69 {
97 {
70 bestDist = dist;
98 bestDist = dist;
71 best = bank;
99 best = tile;
72 }
100 }
73 }
101 }
74 return best;
102 return best;
server/src/ecs/components.js +2 −1
@@ -20,5 +20,6 @@ export const Component = Object.freeze({
20 20 dead: "dead",
21 21 stamina: "stamina",
22 22 gather: "gather",
23 shop: "shop"
23 shop: "shop",
24 statusEffects: "statusEffects"
24 25 });
@@ -20,5 +20,6 @@ export const Component = Object.freeze({
20 dead: "dead",
20 dead: "dead",
21 stamina: "stamina",
21 stamina: "stamina",
22 gather: "gather",
22 gather: "gather",
23 shop: "shop"
23 shop: "shop",
24 statusEffects: "statusEffects"
24});
25});
server/src/ecs/serialize.js +20 −31
@@ -1,16 +1,14 @@
1 1 import { Component } from "./components.js";
2 import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
3 import { resolveEquipTint } from "../../../shared/render/tint.js";
4 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
2 import { equippedLightRadiusTiles } from "../../../shared/definitions/items.js";
3 import {
4 statusExtraLightRadius,
5 statusVisualScale,
6 publicStatusEffectsView
7 } from "../../../shared/statusEffects/rules.js";
5 8 import { mobDefinition } from "../../../shared/definitions/mobs.js";
6 9 import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
7 10 import { shopHasInterface } from "../shop/service.js";
8
9 function bodySprite (sex)
10 {
11 const key = sex === "female" ? "player-body-female" : "player-body-male";
12 return spriteImageName("character", key, key);
13 }
11 import { composeAppearanceLayers } from "../../../shared/appearance/hair.js";
14 12
15 13 export function normalizeMobileComponents (components)
16 14 {
@@ -68,9 +66,13 @@ export function publicEntityView (ecs, entityId)
68 66 const flight = ecs.get(handle, Component.flight);
69 67 const health = ecs.get(handle, Component.health);
70 68 const equipment = ecs.get(handle, Component.equipment);
69 const statusEffects = ecs.get(handle, Component.statusEffects);
70 const now = Date.now();
71 71 const layers = appearanceLayers(ecs, handle, appearance);
72 72 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
73 73 const isMob = !!creature && !character;
74 const gearLight = equippedLightRadiusTiles(equipment);
75 const effectLight = statusExtraLightRadius(statusEffects, now);
74 76 return {
75 77 entityId,
76 78 tileX: position.tileX,
@@ -93,32 +95,16 @@ export function publicEntityView (ecs, entityId)
93 95 maxHealth: health ? health.max : undefined,
94 96 sprite: layers[0]?.sprite ?? null,
95 97 layers,
96 lightRadiusTiles: equippedLightRadiusTiles(equipment)
98 lightRadiusTiles: Math.max(gearLight, effectLight),
99 visualScale: statusVisualScale(statusEffects, now),
100 statusEffects: publicStatusEffectsView(statusEffects, now)
97 101 };
98 102 }
99 103
100 104 export function appearanceLayers (ecs, handle, appearance)
101 105 {
102 const sprite = appearance?.sprite ?? bodySprite(appearance?.sex);
103 const layers = [{ sprite }];
104 106 const equipment = ecs.get(handle, Component.equipment);
105 for (const slot of EQUIPMENT_DRAW_ORDER)
106 {
107 const worn = equipment?.slots?.[slot];
108 if (!worn)
109 { continue; }
110 const overlay = itemEquipSprite(worn.itemId);
111 if (overlay)
112 {
113 const tint = resolveEquipTint(worn.itemId, worn.instance);
114 layers.push({
115 sprite: overlay,
116 itemId: worn.itemId,
117 ...(tint ? { tint } : {})
118 });
119 }
120 }
121 return layers;
107 return composeAppearanceLayers(appearance, equipment?.slots ?? {});
122 108 }
123 109
124 110 export function replicationSpawn (view)
@@ -147,7 +133,9 @@ export function replicationSpawn (view)
147 133 untargetable: !!view.untargetable,
148 134 freeFlight: !!view.freeFlight,
149 135 health: view.health,
150 maxHealth: view.maxHealth
136 maxHealth: view.maxHealth,
137 lightRadiusTiles: view.lightRadiusTiles ?? 0,
138 visualScale: view.visualScale ?? 1
151 139 };
152 140 }
153 141
@@ -180,7 +168,8 @@ export function replicationAppearance (view)
180 168 tileY: view.tileY,
181 169 sprite: view.sprite ?? null,
182 170 layers: view.layers ?? [],
183 lightRadiusTiles: view.lightRadiusTiles ?? 0
171 lightRadiusTiles: view.lightRadiusTiles ?? 0,
172 visualScale: view.visualScale ?? 1
184 173 };
185 174 }
186 175
@@ -1,16 +1,14 @@
1import { Component } from "./components.js";
1import { Component } from "./components.js";
2import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
2import { equippedLightRadiusTiles } from "../../../shared/definitions/items.js";
3import { resolveEquipTint } from "../../../shared/render/tint.js";
3import {
4import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4 statusExtraLightRadius,
5 statusVisualScale,
6 publicStatusEffectsView
7} from "../../../shared/statusEffects/rules.js";
5import { mobDefinition } from "../../../shared/definitions/mobs.js";
8import { mobDefinition } from "../../../shared/definitions/mobs.js";
6import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
9import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
7import { shopHasInterface } from "../shop/service.js";
10import { shopHasInterface } from "../shop/service.js";
8
11import { composeAppearanceLayers } from "../../../shared/appearance/hair.js";
9function bodySprite (sex)
10{
11 const key = sex === "female" ? "player-body-female" : "player-body-male";
12 return spriteImageName("character", key, key);
13}
14
12
15export function normalizeMobileComponents (components)
13export function normalizeMobileComponents (components)
16{
14{
@@ -68,9 +66,13 @@ export function publicEntityView (ecs, entityId)
68 const flight = ecs.get(handle, Component.flight);
66 const flight = ecs.get(handle, Component.flight);
69 const health = ecs.get(handle, Component.health);
67 const health = ecs.get(handle, Component.health);
70 const equipment = ecs.get(handle, Component.equipment);
68 const equipment = ecs.get(handle, Component.equipment);
69 const statusEffects = ecs.get(handle, Component.statusEffects);
70 const now = Date.now();
71 const layers = appearanceLayers(ecs, handle, appearance);
71 const layers = appearanceLayers(ecs, handle, appearance);
72 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
72 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
73 const isMob = !!creature && !character;
73 const isMob = !!creature && !character;
74 const gearLight = equippedLightRadiusTiles(equipment);
75 const effectLight = statusExtraLightRadius(statusEffects, now);
74 return {
76 return {
75 entityId,
77 entityId,
76 tileX: position.tileX,
78 tileX: position.tileX,
@@ -93,32 +95,16 @@ export function publicEntityView (ecs, entityId)
93 maxHealth: health ? health.max : undefined,
95 maxHealth: health ? health.max : undefined,
94 sprite: layers[0]?.sprite ?? null,
96 sprite: layers[0]?.sprite ?? null,
95 layers,
97 layers,
96 lightRadiusTiles: equippedLightRadiusTiles(equipment)
98 lightRadiusTiles: Math.max(gearLight, effectLight),
99 visualScale: statusVisualScale(statusEffects, now),
100 statusEffects: publicStatusEffectsView(statusEffects, now)
97 };
101 };
98}
102}
99
103
100export function appearanceLayers (ecs, handle, appearance)
104export function appearanceLayers (ecs, handle, appearance)
101{
105{
102 const sprite = appearance?.sprite ?? bodySprite(appearance?.sex);
103 const layers = [{ sprite }];
104 const equipment = ecs.get(handle, Component.equipment);
106 const equipment = ecs.get(handle, Component.equipment);
105 for (const slot of EQUIPMENT_DRAW_ORDER)
107 return composeAppearanceLayers(appearance, equipment?.slots ?? {});
106 {
107 const worn = equipment?.slots?.[slot];
108 if (!worn)
109 { continue; }
110 const overlay = itemEquipSprite(worn.itemId);
111 if (overlay)
112 {
113 const tint = resolveEquipTint(worn.itemId, worn.instance);
114 layers.push({
115 sprite: overlay,
116 itemId: worn.itemId,
117 ...(tint ? { tint } : {})
118 });
119 }
120 }
121 return layers;
122}
108}
123
109
124export function replicationSpawn (view)
110export function replicationSpawn (view)
@@ -147,7 +133,9 @@ export function replicationSpawn (view)
147 untargetable: !!view.untargetable,
133 untargetable: !!view.untargetable,
148 freeFlight: !!view.freeFlight,
134 freeFlight: !!view.freeFlight,
149 health: view.health,
135 health: view.health,
150 maxHealth: view.maxHealth
136 maxHealth: view.maxHealth,
137 lightRadiusTiles: view.lightRadiusTiles ?? 0,
138 visualScale: view.visualScale ?? 1
151 };
139 };
152}
140}
153
141
@@ -180,7 +168,8 @@ export function replicationAppearance (view)
180 tileY: view.tileY,
168 tileY: view.tileY,
181 sprite: view.sprite ?? null,
169 sprite: view.sprite ?? null,
182 layers: view.layers ?? [],
170 layers: view.layers ?? [],
183 lightRadiusTiles: view.lightRadiusTiles ?? 0
171 lightRadiusTiles: view.lightRadiusTiles ?? 0,
172 visualScale: view.visualScale ?? 1
184 };
173 };
185}
174}
186
175
server/src/editor/service.js +42 −5
@@ -9,6 +9,11 @@ import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields,
9 9 import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
10 10 import { itemDefinition } from "../../../shared/definitions/items.js";
11 11 import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12 import {
13 normalizeStarterLoadout,
14 starterLoadoutsEqual,
15 diffStarterLoadout
16 } from "../../../shared/items/starterLoadout.js";
12 17
13 18 export class EditorService
14 19 {
@@ -23,14 +28,14 @@ export class EditorService
23 28 const settings = this.worldDb.getLiveSettings();
24 29 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
25 30 const data = row
26 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId)
31 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY)
27 32 : createEmptyChunkData(settings.defaultGroundTypeId);
28 33 const isOpen = (x, y) =>
29 34 {
30 35 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId);
31 36 if (!neighbor)
32 37 { return false; }
33 return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId).open;
38 return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId, x, y).open;
34 39 };
35 40 return {
36 41 chunkX,
@@ -124,6 +129,20 @@ export class EditorService
124 129 {
125 130 next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
126 131 }
132 if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
133 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"))
134 {
135 const loadout = normalizeStarterLoadout({
136 starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
137 ? partial.starterEquipment
138 : current.starterEquipment,
139 starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory")
140 ? partial.starterInventory
141 : current.starterInventory
142 });
143 next.starterEquipment = loadout.equipment;
144 next.starterInventory = loadout.inventory;
145 }
127 146 const { bullets: scalarBullets, changed } = diffSettings(current, next);
128 147 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
129 148 ? diffItemSeedValues(
@@ -137,7 +156,18 @@ export class EditorService
137 156 {
138 157 changed.itemSeedValues = next.itemSeedValues;
139 158 }
140 const bullets = [...scalarBullets, ...seedBullets];
159 const starterChanged = !starterLoadoutsEqual(current, next)
160 && (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
161 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"));
162 if (starterChanged)
163 {
164 changed.starterEquipment = next.starterEquipment;
165 changed.starterInventory = next.starterInventory;
166 }
167 const starterBullets = starterChanged
168 ? diffStarterLoadout(current, next)
169 : [];
170 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets];
141 171 if (Object.keys(changed).length === 0)
142 172 {
143 173 return {
@@ -151,8 +181,15 @@ export class EditorService
151 181 ...changed,
152 182 itemSeedValues: changed.itemSeedValues
153 183 ?? normalizeItemSeedValues(current.itemSeedValues)
154 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }
184 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) },
185 starterEquipment: changed.starterEquipment ?? current.starterEquipment
186 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
187 starterInventory: changed.starterInventory ?? current.starterInventory
188 ?? DEFAULT_WORLD_SETTINGS.starterInventory
155 189 };
190 const normalized = normalizeStarterLoadout(settings);
191 settings.starterEquipment = normalized.equipment;
192 settings.starterInventory = normalized.inventory;
156 193 this.worldDb.saveLiveSettings(settings, editorAdminId);
157 194 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
158 195 return {
@@ -183,7 +220,7 @@ export class EditorService
183 220
184 221 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
185 222 return row
186 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId)
223 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
187 224 : createEmptyChunkData(defaultGroundTypeId);
188 225 }
189 226 }
@@ -9,6 +9,11 @@ import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields,
9import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
9import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
11import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
12import {
13 normalizeStarterLoadout,
14 starterLoadoutsEqual,
15 diffStarterLoadout
16} from "../../../shared/items/starterLoadout.js";
12
17
13export class EditorService
18export class EditorService
14{
19{
@@ -23,14 +28,14 @@ export class EditorService
23 const settings = this.worldDb.getLiveSettings();
28 const settings = this.worldDb.getLiveSettings();
24 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
29 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
25 const data = row
30 const data = row
26 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId)
31 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY)
27 : createEmptyChunkData(settings.defaultGroundTypeId);
32 : createEmptyChunkData(settings.defaultGroundTypeId);
28 const isOpen = (x, y) =>
33 const isOpen = (x, y) =>
29 {
34 {
30 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId);
35 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId);
31 if (!neighbor)
36 if (!neighbor)
32 { return false; }
37 { return false; }
33 return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId).open;
38 return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId, x, y).open;
34 };
39 };
35 return {
40 return {
36 chunkX,
41 chunkX,
@@ -124,6 +129,20 @@ export class EditorService
124 {
129 {
125 next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
130 next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
126 }
131 }
132 if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
133 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"))
134 {
135 const loadout = normalizeStarterLoadout({
136 starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
137 ? partial.starterEquipment
138 : current.starterEquipment,
139 starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory")
140 ? partial.starterInventory
141 : current.starterInventory
142 });
143 next.starterEquipment = loadout.equipment;
144 next.starterInventory = loadout.inventory;
145 }
127 const { bullets: scalarBullets, changed } = diffSettings(current, next);
146 const { bullets: scalarBullets, changed } = diffSettings(current, next);
128 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
147 const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
129 ? diffItemSeedValues(
148 ? diffItemSeedValues(
@@ -137,7 +156,18 @@ export class EditorService
137 {
156 {
138 changed.itemSeedValues = next.itemSeedValues;
157 changed.itemSeedValues = next.itemSeedValues;
139 }
158 }
140 const bullets = [...scalarBullets, ...seedBullets];
159 const starterChanged = !starterLoadoutsEqual(current, next)
160 && (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
161 || Object.prototype.hasOwnProperty.call(partial, "starterInventory"));
162 if (starterChanged)
163 {
164 changed.starterEquipment = next.starterEquipment;
165 changed.starterInventory = next.starterInventory;
166 }
167 const starterBullets = starterChanged
168 ? diffStarterLoadout(current, next)
169 : [];
170 const bullets = [...scalarBullets, ...seedBullets, ...starterBullets];
141 if (Object.keys(changed).length === 0)
171 if (Object.keys(changed).length === 0)
142 {
172 {
143 return {
173 return {
@@ -151,8 +181,15 @@ export class EditorService
151 ...changed,
181 ...changed,
152 itemSeedValues: changed.itemSeedValues
182 itemSeedValues: changed.itemSeedValues
153 ?? normalizeItemSeedValues(current.itemSeedValues)
183 ?? normalizeItemSeedValues(current.itemSeedValues)
154 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }
184 ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) },
185 starterEquipment: changed.starterEquipment ?? current.starterEquipment
186 ?? DEFAULT_WORLD_SETTINGS.starterEquipment,
187 starterInventory: changed.starterInventory ?? current.starterInventory
188 ?? DEFAULT_WORLD_SETTINGS.starterInventory
155 };
189 };
190 const normalized = normalizeStarterLoadout(settings);
191 settings.starterEquipment = normalized.equipment;
192 settings.starterInventory = normalized.inventory;
156 this.worldDb.saveLiveSettings(settings, editorAdminId);
193 this.worldDb.saveLiveSettings(settings, editorAdminId);
157 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
194 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
158 return {
195 return {
@@ -183,7 +220,7 @@ export class EditorService
183
220
184 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
221 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
185 return row
222 return row
186 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId)
223 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
187 : createEmptyChunkData(defaultGroundTypeId);
224 : createEmptyChunkData(defaultGroundTypeId);
188 }
225 }
189}
226}
server/src/gateway/websocket.js +174 −6
@@ -2,6 +2,7 @@ import { WebSocketServer } from "ws";
2 2 import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 4 import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 import { staticChunkRadiusForViewDistance, ViewDistance, normalizeGraphicsSettings } from "../../../shared/graphics/settings.js";
5 6 import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6 7 import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7 8 import { publicSkillsView } from "../../../shared/skills/state.js";
@@ -24,9 +25,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
24 25 authSubject: identity.authSubject,
25 26 characterId: null,
26 27 entityId: null,
28 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
29 viewDistance: ViewDistance.long,
27 30 /** Chunks where entity / ground-item replication is active (3×3). */
28 31 entitySubscribed: new Set(),
29 /** Chunks with map + baked lighting only (5×5). */
32 /** Chunks with map + baked lighting only (5×5 when long). */
30 33 staticSubscribed: new Set()
31 34 };
32 35 auth.register(session);
@@ -82,8 +85,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
82 85 switch (message.type)
83 86 {
84 87 case MessageType.createCharacter:
85 characters.create(session.account, message.firstName, message.lastName, message.sex);
86 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
88 {
89 const created = characters.create(
90 session.account,
91 message.firstName,
92 message.lastName,
93 message.sex,
94 message.hair ?? null,
95 simulation.settings
96 );
97 enterWorld(session, created.characterId);
98 }
87 99 break;
88 100 case MessageType.selectCharacter:
89 101 enterWorld(session, message.characterId);
@@ -204,6 +216,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
204 216 characterId: session.characterId
205 217 });
206 218 break;
219 case MessageType.openBounty:
220 requirePlaying(session);
221 simulation.enqueue(session.id, {
222 type: "open-bounty",
223 characterId: session.characterId
224 });
225 break;
226 case MessageType.raiseBounty:
227 requirePlaying(session);
228 simulation.enqueue(session.id, {
229 type: "raise-bounty",
230 characterId: session.characterId,
231 firstName: message.firstName,
232 lastName: message.lastName,
233 amountCopper: message.amountCopper
234 });
235 break;
236 case MessageType.getCharacterBounty:
237 requirePlaying(session);
238 simulation.enqueue(session.id, {
239 type: "get-character-bounty",
240 characterId: session.characterId,
241 targetCharacterId: message.characterId,
242 firstName: message.firstName,
243 lastName: message.lastName
244 });
245 break;
246 case MessageType.closeBounty:
247 requirePlaying(session);
248 simulation.enqueue(session.id, {
249 type: "close-bounty",
250 characterId: session.characterId
251 });
252 break;
253 case MessageType.openBarber:
254 requirePlaying(session);
255 simulation.enqueue(session.id, {
256 type: "open-barber",
257 characterId: session.characterId
258 });
259 break;
260 case MessageType.setHair:
261 requirePlaying(session);
262 simulation.enqueue(session.id, {
263 type: "set-hair",
264 characterId: session.characterId,
265 hair: message.hair ?? null
266 });
267 break;
268 case MessageType.closeBarber:
269 requirePlaying(session);
270 simulation.enqueue(session.id, {
271 type: "close-barber",
272 characterId: session.characterId
273 });
274 break;
207 275 case MessageType.openCauldron:
208 276 requirePlaying(session);
209 277 simulation.enqueue(session.id, {
@@ -644,6 +712,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
644 712 });
645 713 }
646 714 break;
715 case MessageType.setGraphicsSettings:
716 {
717 const next = normalizeGraphicsSettings({
718 viewDistance: message.viewDistance ?? session.viewDistance
719 });
720 const changed = next.viewDistance !== session.viewDistance;
721 session.viewDistance = next.viewDistance;
722 if (changed && session.entityId)
723 { syncSubscriptions(session, true); }
724 }
725 break;
647 726 default:
648 727 send(session, { type: MessageType.error, message: `Unknown message ${message.type}` });
649 728 }
@@ -682,6 +761,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
682 761 firstName: spawned.firstName,
683 762 lastName: spawned.lastName,
684 763 layers: spawned.layers ?? [],
764 health: spawned.health,
765 maxHealth: spawned.maxHealth,
685 766 settings: simulation.settings,
686 767 worldTime: simulation.worldTime()
687 768 });
@@ -735,8 +816,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
735 816
736 817 const centerChunkX = tileToChunk(position.tileX);
737 818 const centerChunkY = tileToChunk(position.tileY);
819 const mapRadius = staticChunkRadiusForViewDistance(
820 session.viewDistance,
821 STATIC_CHUNK_RADIUS,
822 VISIBLE_CHUNK_RADIUS
823 );
738 824 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
739 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS);
825 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, mapRadius);
740 826 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
741 827 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
742 828
@@ -749,7 +835,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
749 835 }
750 836 }
751 837
752 const snapshots = simulation.snapshotsForView(session.entityId);
838 const snapshots = simulation.snapshotsForView(session.entityId, mapRadius);
753 839 for (const snapshot of snapshots)
754 840 {
755 841 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
@@ -895,6 +981,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
895 981 });
896 982 continue;
897 983 }
984 if (event.type === "status-effects")
985 {
986 const session = event.sessionId != null
987 ? sessions.get(event.sessionId)
988 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
989 if (!session)
990 { continue; }
991 send(session, {
992 type: MessageType.statusEffects,
993 effects: event.effects ?? [],
994 blind: !!event.blind
995 });
996 continue;
997 }
898 998 if (event.type === "toast")
899 999 {
900 1000 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
@@ -1027,6 +1127,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1027 1127 { send(session, { type: MessageType.marketClosed }); }
1028 1128 continue;
1029 1129 }
1130 if (event.type === "bounty-snapshot")
1131 {
1132 const session = sessions.get(event.sessionId);
1133 if (session)
1134 {
1135 send(session, {
1136 type: MessageType.bountySnapshot,
1137 myAmountCopper: event.myAmountCopper | 0,
1138 myAmountLabel: event.myAmountLabel ?? "",
1139 message: event.message ?? "",
1140 raised: event.raised ?? null
1141 });
1142 }
1143 continue;
1144 }
1145 if (event.type === "bounty-closed")
1146 {
1147 const session = sessions.get(event.sessionId);
1148 if (session)
1149 { send(session, { type: MessageType.closeBounty }); }
1150 continue;
1151 }
1152 if (event.type === "character-bounty")
1153 {
1154 const session = sessions.get(event.sessionId);
1155 if (session)
1156 {
1157 send(session, {
1158 type: MessageType.characterBounty,
1159 target: event.target ?? null
1160 });
1161 }
1162 continue;
1163 }
1164 if (event.type === "barber-snapshot")
1165 {
1166 const session = sessions.get(event.sessionId);
1167 if (session)
1168 {
1169 send(session, {
1170 type: MessageType.barberSnapshot,
1171 sex: event.sex,
1172 styles: event.styles ?? [],
1173 hair: event.hair ?? null,
1174 message: event.message ?? ""
1175 });
1176 }
1177 continue;
1178 }
1179 if (event.type === "barber-closed")
1180 {
1181 const session = sessions.get(event.sessionId);
1182 if (session)
1183 { send(session, { type: MessageType.closeBarber }); }
1184 continue;
1185 }
1030 1186 if (event.type === "market-trade")
1031 1187 {
1032 1188 for (const session of sessions.values())
@@ -1085,7 +1241,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1085 1241 }
1086 1242 continue;
1087 1243 }
1088 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 === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1244 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 === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1089 1245 { publishEntity(event); }
1090 1246 }
1091 1247 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1177,6 +1333,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1177 1333 });
1178 1334 continue;
1179 1335 }
1336 if (event.type === "entity-health")
1337 {
1338 if (!seesTo && !seesFrom)
1339 { continue; }
1340 send(session, {
1341 type: MessageType.entityHealth,
1342 entityId: event.entityId,
1343 health: event.health,
1344 maxHealth: event.maxHealth
1345 });
1346 continue;
1347 }
1180 1348 if (event.type === "gather-swing" || event.type === "tile-shove")
1181 1349 {
1182 1350 if (!seesTo && !seesFrom)
@@ -2,6 +2,7 @@ import { WebSocketServer } from "ws";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5import { staticChunkRadiusForViewDistance, ViewDistance, normalizeGraphicsSettings } from "../../../shared/graphics/settings.js";
5import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import { publicSkillsView } from "../../../shared/skills/state.js";
8import { publicSkillsView } from "../../../shared/skills/state.js";
@@ -24,9 +25,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
24 authSubject: identity.authSubject,
25 authSubject: identity.authSubject,
25 characterId: null,
26 characterId: null,
26 entityId: null,
27 entityId: null,
28 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
29 viewDistance: ViewDistance.long,
27 /** Chunks where entity / ground-item replication is active (3×3). */
30 /** Chunks where entity / ground-item replication is active (3×3). */
28 entitySubscribed: new Set(),
31 entitySubscribed: new Set(),
29 /** Chunks with map + baked lighting only (5×5). */
32 /** Chunks with map + baked lighting only (5×5 when long). */
30 staticSubscribed: new Set()
33 staticSubscribed: new Set()
31 };
34 };
32 auth.register(session);
35 auth.register(session);
@@ -82,8 +85,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
82 switch (message.type)
85 switch (message.type)
83 {
86 {
84 case MessageType.createCharacter:
87 case MessageType.createCharacter:
85 characters.create(session.account, message.firstName, message.lastName, message.sex);
88 {
86 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
89 const created = characters.create(
90 session.account,
91 message.firstName,
92 message.lastName,
93 message.sex,
94 message.hair ?? null,
95 simulation.settings
96 );
97 enterWorld(session, created.characterId);
98 }
87 break;
99 break;
88 case MessageType.selectCharacter:
100 case MessageType.selectCharacter:
89 enterWorld(session, message.characterId);
101 enterWorld(session, message.characterId);
@@ -204,6 +216,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
204 characterId: session.characterId
216 characterId: session.characterId
205 });
217 });
206 break;
218 break;
219 case MessageType.openBounty:
220 requirePlaying(session);
221 simulation.enqueue(session.id, {
222 type: "open-bounty",
223 characterId: session.characterId
224 });
225 break;
226 case MessageType.raiseBounty:
227 requirePlaying(session);
228 simulation.enqueue(session.id, {
229 type: "raise-bounty",
230 characterId: session.characterId,
231 firstName: message.firstName,
232 lastName: message.lastName,
233 amountCopper: message.amountCopper
234 });
235 break;
236 case MessageType.getCharacterBounty:
237 requirePlaying(session);
238 simulation.enqueue(session.id, {
239 type: "get-character-bounty",
240 characterId: session.characterId,
241 targetCharacterId: message.characterId,
242 firstName: message.firstName,
243 lastName: message.lastName
244 });
245 break;
246 case MessageType.closeBounty:
247 requirePlaying(session);
248 simulation.enqueue(session.id, {
249 type: "close-bounty",
250 characterId: session.characterId
251 });
252 break;
253 case MessageType.openBarber:
254 requirePlaying(session);
255 simulation.enqueue(session.id, {
256 type: "open-barber",
257 characterId: session.characterId
258 });
259 break;
260 case MessageType.setHair:
261 requirePlaying(session);
262 simulation.enqueue(session.id, {
263 type: "set-hair",
264 characterId: session.characterId,
265 hair: message.hair ?? null
266 });
267 break;
268 case MessageType.closeBarber:
269 requirePlaying(session);
270 simulation.enqueue(session.id, {
271 type: "close-barber",
272 characterId: session.characterId
273 });
274 break;
207 case MessageType.openCauldron:
275 case MessageType.openCauldron:
208 requirePlaying(session);
276 requirePlaying(session);
209 simulation.enqueue(session.id, {
277 simulation.enqueue(session.id, {
@@ -644,6 +712,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
644 });
712 });
645 }
713 }
646 break;
714 break;
715 case MessageType.setGraphicsSettings:
716 {
717 const next = normalizeGraphicsSettings({
718 viewDistance: message.viewDistance ?? session.viewDistance
719 });
720 const changed = next.viewDistance !== session.viewDistance;
721 session.viewDistance = next.viewDistance;
722 if (changed && session.entityId)
723 { syncSubscriptions(session, true); }
724 }
725 break;
647 default:
726 default:
648 send(session, { type: MessageType.error, message: `Unknown message ${message.type}` });
727 send(session, { type: MessageType.error, message: `Unknown message ${message.type}` });
649 }
728 }
@@ -682,6 +761,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
682 firstName: spawned.firstName,
761 firstName: spawned.firstName,
683 lastName: spawned.lastName,
762 lastName: spawned.lastName,
684 layers: spawned.layers ?? [],
763 layers: spawned.layers ?? [],
764 health: spawned.health,
765 maxHealth: spawned.maxHealth,
685 settings: simulation.settings,
766 settings: simulation.settings,
686 worldTime: simulation.worldTime()
767 worldTime: simulation.worldTime()
687 });
768 });
@@ -735,8 +816,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
735
816
736 const centerChunkX = tileToChunk(position.tileX);
817 const centerChunkX = tileToChunk(position.tileX);
737 const centerChunkY = tileToChunk(position.tileY);
818 const centerChunkY = tileToChunk(position.tileY);
819 const mapRadius = staticChunkRadiusForViewDistance(
820 session.viewDistance,
821 STATIC_CHUNK_RADIUS,
822 VISIBLE_CHUNK_RADIUS
823 );
738 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
824 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
739 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS);
825 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, mapRadius);
740 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
826 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
741 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
827 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
742
828
@@ -749,7 +835,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
749 }
835 }
750 }
836 }
751
837
752 const snapshots = simulation.snapshotsForView(session.entityId);
838 const snapshots = simulation.snapshotsForView(session.entityId, mapRadius);
753 for (const snapshot of snapshots)
839 for (const snapshot of snapshots)
754 {
840 {
755 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
841 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
@@ -895,6 +981,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
895 });
981 });
896 continue;
982 continue;
897 }
983 }
984 if (event.type === "status-effects")
985 {
986 const session = event.sessionId != null
987 ? sessions.get(event.sessionId)
988 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
989 if (!session)
990 { continue; }
991 send(session, {
992 type: MessageType.statusEffects,
993 effects: event.effects ?? [],
994 blind: !!event.blind
995 });
996 continue;
997 }
898 if (event.type === "toast")
998 if (event.type === "toast")
899 {
999 {
900 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1000 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
@@ -1027,6 +1127,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1027 { send(session, { type: MessageType.marketClosed }); }
1127 { send(session, { type: MessageType.marketClosed }); }
1028 continue;
1128 continue;
1029 }
1129 }
1130 if (event.type === "bounty-snapshot")
1131 {
1132 const session = sessions.get(event.sessionId);
1133 if (session)
1134 {
1135 send(session, {
1136 type: MessageType.bountySnapshot,
1137 myAmountCopper: event.myAmountCopper | 0,
1138 myAmountLabel: event.myAmountLabel ?? "",
1139 message: event.message ?? "",
1140 raised: event.raised ?? null
1141 });
1142 }
1143 continue;
1144 }
1145 if (event.type === "bounty-closed")
1146 {
1147 const session = sessions.get(event.sessionId);
1148 if (session)
1149 { send(session, { type: MessageType.closeBounty }); }
1150 continue;
1151 }
1152 if (event.type === "character-bounty")
1153 {
1154 const session = sessions.get(event.sessionId);
1155 if (session)
1156 {
1157 send(session, {
1158 type: MessageType.characterBounty,
1159 target: event.target ?? null
1160 });
1161 }
1162 continue;
1163 }
1164 if (event.type === "barber-snapshot")
1165 {
1166 const session = sessions.get(event.sessionId);
1167 if (session)
1168 {
1169 send(session, {
1170 type: MessageType.barberSnapshot,
1171 sex: event.sex,
1172 styles: event.styles ?? [],
1173 hair: event.hair ?? null,
1174 message: event.message ?? ""
1175 });
1176 }
1177 continue;
1178 }
1179 if (event.type === "barber-closed")
1180 {
1181 const session = sessions.get(event.sessionId);
1182 if (session)
1183 { send(session, { type: MessageType.closeBarber }); }
1184 continue;
1185 }
1030 if (event.type === "market-trade")
1186 if (event.type === "market-trade")
1031 {
1187 {
1032 for (const session of sessions.values())
1188 for (const session of sessions.values())
@@ -1085,7 +1241,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1085 }
1241 }
1086 continue;
1242 continue;
1087 }
1243 }
1088 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 === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1244 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 === "entity-health" || event.type === "gather-swing" || event.type === "tile-shove" || event.type === "chunk-delta" || event.type === "skill-level-up")
1089 { publishEntity(event); }
1245 { publishEntity(event); }
1090 }
1246 }
1091 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
1247 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1177,6 +1333,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1177 });
1333 });
1178 continue;
1334 continue;
1179 }
1335 }
1336 if (event.type === "entity-health")
1337 {
1338 if (!seesTo && !seesFrom)
1339 { continue; }
1340 send(session, {
1341 type: MessageType.entityHealth,
1342 entityId: event.entityId,
1343 health: event.health,
1344 maxHealth: event.maxHealth
1345 });
1346 continue;
1347 }
1180 if (event.type === "gather-swing" || event.type === "tile-shove")
1348 if (event.type === "gather-swing" || event.type === "tile-shove")
1181 {
1349 {
1182 if (!seesTo && !seesFrom)
1350 if (!seesTo && !seesFrom)
server/src/gathering/service.js +37 −5
@@ -13,6 +13,7 @@ import {
13 13 resolveMiningPickaxe,
14 14 resolveWoodcuttingAxe,
15 15 resolvePlantClippers,
16 resolveHerbGather,
16 17 woodcuttingDurationMs,
17 18 woodcuttingXpForWood,
18 19 treeExhaustDurationMs,
@@ -27,8 +28,10 @@ import {
27 28 flowerItemInstance,
28 29 flowerColorIdFromBlockState,
29 30 flowerBlockState,
31 flowerColorIdForTile,
30 32 randomFlowerColorId
31 33 } from "../../../shared/definitions/dyes.js";
34 import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";
32 35 import { insertStack } from "../../../shared/items/inventory.js";
33 36 import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
34 37 import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -304,7 +307,7 @@ export function stepPlantRespawns (world, now)
304 307 { continue; }
305 308 const state = entry.typeId === BlockType.flower
306 309 ? flowerBlockState(randomFlowerColorId())
307 : (entry.state ?? "cotton-plant");
310 : (entry.state ?? defaultPlantState(entry.typeId));
308 311 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
309 312 if (delta)
310 313 { events.push(delta); }
@@ -466,8 +469,19 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
466 469 if (!clippers.ok)
467 470 { throw userError(clippers.reason); }
468 471
472 let herbId = null;
473 let herbTier = null;
474 if (plant.kind === "herb")
475 {
476 const gate = resolveHerbGather({ herbId: block.state, skills });
477 if (!gate.ok)
478 { throw userError(gate.reason); }
479 herbId = gate.herb.herbId;
480 herbTier = gate.herb.tier;
481 }
482
469 483 const toolTier = clippers.tool?.tier ?? null;
470 const durationMs = herbalismDurationMs(plant.kind, toolTier);
484 const durationMs = herbalismDurationMs(plant.kind, toolTier, herbTier);
471 485 const toolItemId = clippers.tool?.stack?.itemId ?? null;
472 486 const prefixEvents = [];
473 487 let flowerColorId = null;
@@ -477,7 +491,7 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
477 491 if (!flowerColorId)
478 492 {
479 493 // Legacy / uncoloured placements: lock a colour before the pick starts.
480 flowerColorId = randomFlowerColorId();
494 flowerColorId = flowerColorIdForTile(tileX, tileY);
481 495 const delta = setBlockState(
482 496 world,
483 497 tileX,
@@ -492,6 +506,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
492 506 const started = beginGatherSwing(world, handle, entityId, position, {
493 507 kind: "plant",
494 508 plantKind: plant.kind,
509 herbId,
510 herbTier,
495 511 tileX,
496 512 tileY,
497 513 typeId: block.typeId,
@@ -690,6 +706,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv
690 706 {
691 707 itemId = rawClothItemId(ClothTier.cotton);
692 708 }
709 else if (gather.plantKind === "herb")
710 {
711 const herb = herbDefinition(gather.herbId);
712 itemId = herb?.itemId ?? null;
713 }
693 714 else
694 715 {
695 716 clearGather(world.ecs, handle);
@@ -728,7 +749,7 @@ function completePlant (world, handle, entityId, character, gather, events, priv
728 749 const levelUps = [];
729 750 if (skills?.xp)
730 751 {
731 const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind));
752 const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind, gather.herbTier));
732 753 if (result.changed)
733 754 { skillsChanged = true; }
734 755 if (result.levelUp)
@@ -743,7 +764,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv
743 764 tileY: gather.tileY,
744 765 typeId: gather.typeId,
745 766 // Colour is chosen when the node refreshes (see stepPlantRespawns).
746 state: gather.plantKind === "flower" ? null : "cotton-plant",
767 state: gather.plantKind === "flower"
768 ? null
769 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
770 ? gather.herbId
771 : defaultPlantState(gather.typeId)),
747 772 respawnsAt: now + PLANT_EXHAUST_MS
748 773 });
749 774
@@ -863,3 +888,10 @@ export function handleGatherCommand (world, sessionId, command, now)
863 888 return null;
864 889 }
865 890 }
891
892 function defaultPlantState (typeId)
893 {
894 if (typeId === BlockType.herbPlant)
895 { return "mint"; }
896 return "cotton-plant";
897 }
@@ -13,6 +13,7 @@ import {
13 resolveMiningPickaxe,
13 resolveMiningPickaxe,
14 resolveWoodcuttingAxe,
14 resolveWoodcuttingAxe,
15 resolvePlantClippers,
15 resolvePlantClippers,
16 resolveHerbGather,
16 woodcuttingDurationMs,
17 woodcuttingDurationMs,
17 woodcuttingXpForWood,
18 woodcuttingXpForWood,
18 treeExhaustDurationMs,
19 treeExhaustDurationMs,
@@ -27,8 +28,10 @@ import {
27 flowerItemInstance,
28 flowerItemInstance,
28 flowerColorIdFromBlockState,
29 flowerColorIdFromBlockState,
29 flowerBlockState,
30 flowerBlockState,
31 flowerColorIdForTile,
30 randomFlowerColorId
32 randomFlowerColorId
31} from "../../../shared/definitions/dyes.js";
33} from "../../../shared/definitions/dyes.js";
34import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";
32import { insertStack } from "../../../shared/items/inventory.js";
35import { insertStack } from "../../../shared/items/inventory.js";
33import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
36import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
34import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
37import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -304,7 +307,7 @@ export function stepPlantRespawns (world, now)
304 { continue; }
307 { continue; }
305 const state = entry.typeId === BlockType.flower
308 const state = entry.typeId === BlockType.flower
306 ? flowerBlockState(randomFlowerColorId())
309 ? flowerBlockState(randomFlowerColorId())
307 : (entry.state ?? "cotton-plant");
310 : (entry.state ?? defaultPlantState(entry.typeId));
308 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
311 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
309 if (delta)
312 if (delta)
310 { events.push(delta); }
313 { events.push(delta); }
@@ -466,8 +469,19 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
466 if (!clippers.ok)
469 if (!clippers.ok)
467 { throw userError(clippers.reason); }
470 { throw userError(clippers.reason); }
468
471
472 let herbId = null;
473 let herbTier = null;
474 if (plant.kind === "herb")
475 {
476 const gate = resolveHerbGather({ herbId: block.state, skills });
477 if (!gate.ok)
478 { throw userError(gate.reason); }
479 herbId = gate.herb.herbId;
480 herbTier = gate.herb.tier;
481 }
482
469 const toolTier = clippers.tool?.tier ?? null;
483 const toolTier = clippers.tool?.tier ?? null;
470 const durationMs = herbalismDurationMs(plant.kind, toolTier);
484 const durationMs = herbalismDurationMs(plant.kind, toolTier, herbTier);
471 const toolItemId = clippers.tool?.stack?.itemId ?? null;
485 const toolItemId = clippers.tool?.stack?.itemId ?? null;
472 const prefixEvents = [];
486 const prefixEvents = [];
473 let flowerColorId = null;
487 let flowerColorId = null;
@@ -477,7 +491,7 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
477 if (!flowerColorId)
491 if (!flowerColorId)
478 {
492 {
479 // Legacy / uncoloured placements: lock a colour before the pick starts.
493 // Legacy / uncoloured placements: lock a colour before the pick starts.
480 flowerColorId = randomFlowerColorId();
494 flowerColorId = flowerColorIdForTile(tileX, tileY);
481 const delta = setBlockState(
495 const delta = setBlockState(
482 world,
496 world,
483 tileX,
497 tileX,
@@ -492,6 +506,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
492 const started = beginGatherSwing(world, handle, entityId, position, {
506 const started = beginGatherSwing(world, handle, entityId, position, {
493 kind: "plant",
507 kind: "plant",
494 plantKind: plant.kind,
508 plantKind: plant.kind,
509 herbId,
510 herbTier,
495 tileX,
511 tileX,
496 tileY,
512 tileY,
497 typeId: block.typeId,
513 typeId: block.typeId,
@@ -690,6 +706,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv
690 {
706 {
691 itemId = rawClothItemId(ClothTier.cotton);
707 itemId = rawClothItemId(ClothTier.cotton);
692 }
708 }
709 else if (gather.plantKind === "herb")
710 {
711 const herb = herbDefinition(gather.herbId);
712 itemId = herb?.itemId ?? null;
713 }
693 else
714 else
694 {
715 {
695 clearGather(world.ecs, handle);
716 clearGather(world.ecs, handle);
@@ -728,7 +749,7 @@ function completePlant (world, handle, entityId, character, gather, events, priv
728 const levelUps = [];
749 const levelUps = [];
729 if (skills?.xp)
750 if (skills?.xp)
730 {
751 {
731 const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind));
752 const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind, gather.herbTier));
732 if (result.changed)
753 if (result.changed)
733 { skillsChanged = true; }
754 { skillsChanged = true; }
734 if (result.levelUp)
755 if (result.levelUp)
@@ -743,7 +764,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv
743 tileY: gather.tileY,
764 tileY: gather.tileY,
744 typeId: gather.typeId,
765 typeId: gather.typeId,
745 // Colour is chosen when the node refreshes (see stepPlantRespawns).
766 // Colour is chosen when the node refreshes (see stepPlantRespawns).
746 state: gather.plantKind === "flower" ? null : "cotton-plant",
767 state: gather.plantKind === "flower"
768 ? null
769 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
770 ? gather.herbId
771 : defaultPlantState(gather.typeId)),
747 respawnsAt: now + PLANT_EXHAUST_MS
772 respawnsAt: now + PLANT_EXHAUST_MS
748 });
773 });
749
774
@@ -863,3 +888,10 @@ export function handleGatherCommand (world, sessionId, command, now)
863 return null;
888 return null;
864 }
889 }
865}
890}
891
892function defaultPlantState (typeId)
893{
894 if (typeId === BlockType.herbPlant)
895 { return "mint"; }
896 return "cotton-plant";
897}
server/src/items/bags.js +64 −8
@@ -24,6 +24,11 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
24 24 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25 25 import { randomUUID } from "node:crypto";
26 26 import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
27 import {
28 applyStatusEffect,
29 emptyStatusEffects,
30 StatusEffectType
31 } from "../../../shared/statusEffects/rules.js";
27 32
28 33 export function publicGroundItem (item)
29 34 {
@@ -350,7 +355,11 @@ function eatItem (world, sessionId, command)
350 355 { throw userError("That inventory slot is empty."); }
351 356 inventory.slots = taken.slots;
352 357 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
353 return { events: [], private: bagView(world.ecs, handle) };
358 return {
359 events: [],
360 private: bagView(world.ecs, handle),
361 healthChanged: true
362 };
354 363 }
355 364
356 365 function drinkItem (world, sessionId, command)
@@ -378,27 +387,74 @@ function drinkItem (world, sessionId, command)
378 387 throw userError("That inventory slot is empty.");
379 388 }
380 389 inventory.slots = consumed.slots;
381 applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
382 return { events: [], private: bagView(world.ecs, handle) };
390 const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
391 return {
392 events: effectResult.events ?? [],
393 private: bagView(world.ecs, handle),
394 healthChanged: !!effectResult.healthChanged,
395 appearanceChanged: !!effectResult.appearanceChanged,
396 statusEffectsChanged: !!effectResult.statusEffectsChanged
397 };
398 }
399
400 function ensureStatusEffects (ecs, handle)
401 {
402 let component = ecs.get(handle, Component.statusEffects);
403 if (!component)
404 { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
405 if (!Array.isArray(component.effects))
406 { component.effects = []; }
407 return component;
383 408 }
384 409
385 410 function applyPotionEffect (ecs, handle, effect)
386 411 {
412 const result = {
413 healthChanged: false,
414 appearanceChanged: false,
415 statusEffectsChanged: false,
416 events: []
417 };
387 418 if (!effect || typeof effect !== "object")
388 { return; }
419 { return result; }
420
389 421 const health = ecs.get(handle, Component.health);
390 if (effect.type === "heal" && health)
422 const type = effect.type;
423
424 if (type === "heal" && health)
391 425 {
392 426 const amount = Math.max(0, effect.amount | 0 || 0);
393 427 health.current = Math.min(health.max | 0, (health.current | 0) + amount);
394 return;
428 result.healthChanged = true;
429 return result;
395 430 }
396 if (effect.type === "damage" && health)
431 if (type === "damage" && health)
397 432 {
398 433 const amount = Math.max(0, effect.amount | 0 || 0);
399 434 health.current = Math.max(0, (health.current | 0) - amount);
435 result.healthChanged = true;
436 return result;
400 437 }
401 // slow / blind / queasy: stub until status-effect systems exist
438
439 const timed = {
440 [StatusEffectType.healthRegen]: true,
441 [StatusEffectType.staminaRegen]: true,
442 [StatusEffectType.strengthBonus]: true,
443 [StatusEffectType.mindBonus]: true,
444 [StatusEffectType.staminaDrain]: true,
445 [StatusEffectType.glow]: true,
446 [StatusEffectType.shrink]: true,
447 [StatusEffectType.blind]: true
448 };
449 if (!timed[type])
450 { return result; }
451
452 const component = ensureStatusEffects(ecs, handle);
453 applyStatusEffect(component, effect, Date.now());
454 result.statusEffectsChanged = true;
455 if (type === StatusEffectType.glow || type === StatusEffectType.shrink)
456 { result.appearanceChanged = true; }
457 return result;
402 458 }
403 459
404 460 function openBank (world, sessionId, command)
@@ -24,6 +24,11 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25import { randomUUID } from "node:crypto";
25import { randomUUID } from "node:crypto";
26import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
26import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
27import {
28 applyStatusEffect,
29 emptyStatusEffects,
30 StatusEffectType
31} from "../../../shared/statusEffects/rules.js";
27
32
28export function publicGroundItem (item)
33export function publicGroundItem (item)
29{
34{
@@ -350,7 +355,11 @@ function eatItem (world, sessionId, command)
350 { throw userError("That inventory slot is empty."); }
355 { throw userError("That inventory slot is empty."); }
351 inventory.slots = taken.slots;
356 inventory.slots = taken.slots;
352 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
357 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
353 return { events: [], private: bagView(world.ecs, handle) };
358 return {
359 events: [],
360 private: bagView(world.ecs, handle),
361 healthChanged: true
362 };
354}
363}
355
364
356function drinkItem (world, sessionId, command)
365function drinkItem (world, sessionId, command)
@@ -378,27 +387,74 @@ function drinkItem (world, sessionId, command)
378 throw userError("That inventory slot is empty.");
387 throw userError("That inventory slot is empty.");
379 }
388 }
380 inventory.slots = consumed.slots;
389 inventory.slots = consumed.slots;
381 applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
390 const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
382 return { events: [], private: bagView(world.ecs, handle) };
391 return {
392 events: effectResult.events ?? [],
393 private: bagView(world.ecs, handle),
394 healthChanged: !!effectResult.healthChanged,
395 appearanceChanged: !!effectResult.appearanceChanged,
396 statusEffectsChanged: !!effectResult.statusEffectsChanged
397 };
398}
399
400function ensureStatusEffects (ecs, handle)
401{
402 let component = ecs.get(handle, Component.statusEffects);
403 if (!component)
404 { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
405 if (!Array.isArray(component.effects))
406 { component.effects = []; }
407 return component;
383}
408}
384
409
385function applyPotionEffect (ecs, handle, effect)
410function applyPotionEffect (ecs, handle, effect)
386{
411{
412 const result = {
413 healthChanged: false,
414 appearanceChanged: false,
415 statusEffectsChanged: false,
416 events: []
417 };
387 if (!effect || typeof effect !== "object")
418 if (!effect || typeof effect !== "object")
388 { return; }
419 { return result; }
420
389 const health = ecs.get(handle, Component.health);
421 const health = ecs.get(handle, Component.health);
390 if (effect.type === "heal" && health)
422 const type = effect.type;
423
424 if (type === "heal" && health)
391 {
425 {
392 const amount = Math.max(0, effect.amount | 0 || 0);
426 const amount = Math.max(0, effect.amount | 0 || 0);
393 health.current = Math.min(health.max | 0, (health.current | 0) + amount);
427 health.current = Math.min(health.max | 0, (health.current | 0) + amount);
394 return;
428 result.healthChanged = true;
429 return result;
395 }
430 }
396 if (effect.type === "damage" && health)
431 if (type === "damage" && health)
397 {
432 {
398 const amount = Math.max(0, effect.amount | 0 || 0);
433 const amount = Math.max(0, effect.amount | 0 || 0);
399 health.current = Math.max(0, (health.current | 0) - amount);
434 health.current = Math.max(0, (health.current | 0) - amount);
435 result.healthChanged = true;
436 return result;
400 }
437 }
401 // slow / blind / queasy: stub until status-effect systems exist
438
439 const timed = {
440 [StatusEffectType.healthRegen]: true,
441 [StatusEffectType.staminaRegen]: true,
442 [StatusEffectType.strengthBonus]: true,
443 [StatusEffectType.mindBonus]: true,
444 [StatusEffectType.staminaDrain]: true,
445 [StatusEffectType.glow]: true,
446 [StatusEffectType.shrink]: true,
447 [StatusEffectType.blind]: true
448 };
449 if (!timed[type])
450 { return result; }
451
452 const component = ensureStatusEffects(ecs, handle);
453 applyStatusEffect(component, effect, Date.now());
454 result.statusEffectsChanged = true;
455 if (type === StatusEffectType.glow || type === StatusEffectType.shrink)
456 { result.appearanceChanged = true; }
457 return result;
402}
458}
403
459
404function openBank (world, sessionId, command)
460function openBank (world, sessionId, command)
server/src/market/service.js +1 −1
@@ -70,7 +70,7 @@ export class MarketService
70 70 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
71 71 if (!row)
72 72 { continue; }
73 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
73 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
74 74 for (let localY = 0; localY < CHUNK_SIZE; localY++)
75 75 {
76 76 for (let localX = 0; localX < CHUNK_SIZE; localX++)
@@ -70,7 +70,7 @@ export class MarketService
70 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
70 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
71 if (!row)
71 if (!row)
72 { continue; }
72 { continue; }
73 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
73 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
74 for (let localY = 0; localY < CHUNK_SIZE; localY++)
74 for (let localY = 0; localY < CHUNK_SIZE; localY++)
75 {
75 {
76 for (let localX = 0; localX < CHUNK_SIZE; localX++)
76 for (let localX = 0; localX < CHUNK_SIZE; localX++)
server/src/persistence/stateDb.js +98 −19
@@ -1,6 +1,7 @@
1 1 import { openDatabase } from "./database.js";
2 2 import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3 import { STARTER_ITEMS, ItemId, itemDefinition } from "../../../shared/definitions/items.js";
3 import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4 import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
4 5 import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
5 6
6 7 const STATE_SCHEMA = `
@@ -28,7 +29,11 @@ CREATE TABLE IF NOT EXISTS characters (
28 29 tile_y INTEGER NOT NULL DEFAULT 8,
29 30 gait TEXT NOT NULL DEFAULT 'walk',
30 31 is_dead INTEGER NOT NULL DEFAULT 0,
31 deletion_scheduled_at INTEGER
32 deletion_scheduled_at INTEGER,
33 hair_style TEXT,
34 hair_hue REAL NOT NULL DEFAULT 30,
35 hair_saturation REAL NOT NULL DEFAULT 0.55,
36 hair_darkness REAL NOT NULL DEFAULT 0.45
32 37 );
33 38 CREATE TABLE IF NOT EXISTS friend_requests (
34 39 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -150,6 +155,11 @@ CREATE TABLE IF NOT EXISTS held_courier_deliveries (
150 155 cargo_blob TEXT NOT NULL,
151 156 created_at INTEGER NOT NULL
152 157 );
158
159 CREATE TABLE IF NOT EXISTS character_bounties (
160 character_id INTEGER PRIMARY KEY,
161 amount INTEGER NOT NULL DEFAULT 0
162 );
153 163 `;
154 164
155 165 export class StateDatabase
@@ -171,6 +181,13 @@ export class StateDatabase
171 181 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
172 182 if (!characterColumns.some((column) => column.name === "is_dead"))
173 183 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
184 if (!characterColumns.some((column) => column.name === "hair_style"))
185 {
186 this.db.exec("ALTER TABLE characters ADD COLUMN hair_style TEXT");
187 this.db.exec("ALTER TABLE characters ADD COLUMN hair_hue REAL NOT NULL DEFAULT 30");
188 this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
189 this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
190 }
174 191 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
175 192 if (!courierColumns.some((column) => column.name === "vault_character_id"))
176 193 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
@@ -253,18 +270,36 @@ export class StateDatabase
253 270 return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
254 271 }
255 272
256 createCharacter (accountId, firstName, lastName, sex, tileX, tileY)
273 createCharacter (accountId, firstName, lastName, sex, tileX, tileY, hair = null, starterSettings = null)
257 274 {
258 275 const firstNormalized = normalizeName(firstName);
259 276 const lastNormalized = normalizeName(lastName);
277 const hairStyle = hair?.style ?? null;
278 const hairHue = Number(hair?.hue) || 30;
279 const hairSaturation = Number(hair?.saturation);
280 const hairDarkness = Number(hair?.darkness);
260 281 this.db.exec("BEGIN");
261 282 try
262 283 {
263 284 this.db.prepare(`
264 285 INSERT INTO characters (
265 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y
266 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
267 `).run(accountId, firstName, lastName, firstNormalized, lastNormalized, sex, tileX, tileY);
286 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
287 hair_style, hair_hue, hair_saturation, hair_darkness
288 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
289 `).run(
290 accountId,
291 firstName,
292 lastName,
293 firstNormalized,
294 lastNormalized,
295 sex,
296 tileX,
297 tileY,
298 hairStyle,
299 hairHue,
300 Number.isFinite(hairSaturation) ? hairSaturation : 0.55,
301 Number.isFinite(hairDarkness) ? hairDarkness : 0.45
302 );
268 303 const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
269 304
270 305 const claim = this.findSurnameClaim(lastNormalized);
@@ -277,7 +312,7 @@ export class StateDatabase
277 312 }
278 313
279 314 this.db.exec("COMMIT");
280 this.#ensureBag(characterId);
315 this.#ensureBag(characterId, starterSettings);
281 316 return this.getCharacter(characterId);
282 317 }
283 318 catch (error)
@@ -287,6 +322,22 @@ export class StateDatabase
287 322 }
288 323 }
289 324
325 updateCharacterHair (characterId, { style, hue, saturation, darkness })
326 {
327 this.db.prepare(`
328 UPDATE characters
329 SET hair_style = ?, hair_hue = ?, hair_saturation = ?, hair_darkness = ?
330 WHERE character_id = ?
331 `).run(
332 style ?? null,
333 Number(hue) || 30,
334 Number.isFinite(Number(saturation)) ? Number(saturation) : 0.55,
335 Number.isFinite(Number(darkness)) ? Number(darkness) : 0.45,
336 characterId | 0
337 );
338 return this.getCharacter(characterId);
339 }
340
290 341 scheduleDeletion (characterId, at)
291 342 {
292 343 this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
@@ -371,6 +422,42 @@ export class StateDatabase
371 422 `).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
372 423 }
373 424
425 getCharacterBounty (characterId)
426 {
427 const row = this.db.prepare(`
428 SELECT amount FROM character_bounties WHERE character_id = ?
429 `).get(characterId | 0);
430 return Math.max(0, row?.amount | 0);
431 }
432
433 /** Add coins to a bounty; returns the new total. */
434 addCharacterBounty (characterId, amount)
435 {
436 const id = characterId | 0;
437 const add = Math.max(0, amount | 0);
438 if (add <= 0)
439 { return this.getCharacterBounty(id); }
440 this.db.prepare(`
441 INSERT INTO character_bounties (character_id, amount) VALUES (?, ?)
442 ON CONFLICT(character_id) DO UPDATE SET amount = amount + excluded.amount
443 `).run(id, add);
444 return this.getCharacterBounty(id);
445 }
446
447 /** Zero out and return the previous bounty amount. */
448 takeCharacterBounty (characterId)
449 {
450 const id = characterId | 0;
451 const amount = this.getCharacterBounty(id);
452 if (amount <= 0)
453 { return 0; }
454 this.db.prepare(`
455 INSERT INTO character_bounties (character_id, amount) VALUES (?, 0)
456 ON CONFLICT(character_id) DO UPDATE SET amount = 0
457 `).run(id);
458 return amount;
459 }
460
374 461 listFriendRecords (characterId)
375 462 {
376 463 return this.db.prepare(`
@@ -492,28 +579,20 @@ export class StateDatabase
492 579 }
493 580 }
494 581
495 #ensureBag (characterId)
582 #ensureBag (characterId, starterSettings = null)
496 583 {
497 584 const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
498 585 if (existing)
499 586 { return parseBag(existing, characterId); }
500 const slots = emptySlots();
501 for (const starter of STARTER_ITEMS)
502 {
503 const result = insertStack(slots, { ...starter }, itemDefinition(starter.itemId));
504 if (result.ok)
505 { slots.splice(0, slots.length, ...result.slots); }
506 }
507 const equipment = emptyEquipment();
508 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
587 const contents = buildStarterBagContents(starterSettings);
509 588 this.db.prepare(`
510 589 INSERT INTO character_bags (
511 590 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
512 591 ) VALUES (?, ?, ?, 0, ?, 0, ?)
513 592 `).run(
514 593 characterId,
515 JSON.stringify(slots),
516 JSON.stringify(equipment),
594 JSON.stringify(contents.slots),
595 JSON.stringify(contents.equipment),
517 596 JSON.stringify({ slots: [], reserved: [] }),
518 597 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
519 598 );
@@ -1,6 +1,7 @@
1import { openDatabase } from "./database.js";
1import { openDatabase } from "./database.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3import { STARTER_ITEMS, ItemId, itemDefinition } from "../../../shared/definitions/items.js";
3import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
4import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
5import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
5
6
6const STATE_SCHEMA = `
7const STATE_SCHEMA = `
@@ -28,7 +29,11 @@ CREATE TABLE IF NOT EXISTS characters (
28 tile_y INTEGER NOT NULL DEFAULT 8,
29 tile_y INTEGER NOT NULL DEFAULT 8,
29 gait TEXT NOT NULL DEFAULT 'walk',
30 gait TEXT NOT NULL DEFAULT 'walk',
30 is_dead INTEGER NOT NULL DEFAULT 0,
31 is_dead INTEGER NOT NULL DEFAULT 0,
31 deletion_scheduled_at INTEGER
32 deletion_scheduled_at INTEGER,
33 hair_style TEXT,
34 hair_hue REAL NOT NULL DEFAULT 30,
35 hair_saturation REAL NOT NULL DEFAULT 0.55,
36 hair_darkness REAL NOT NULL DEFAULT 0.45
32);
37);
33CREATE TABLE IF NOT EXISTS friend_requests (
38CREATE TABLE IF NOT EXISTS friend_requests (
34 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
39 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -150,6 +155,11 @@ CREATE TABLE IF NOT EXISTS held_courier_deliveries (
150 cargo_blob TEXT NOT NULL,
155 cargo_blob TEXT NOT NULL,
151 created_at INTEGER NOT NULL
156 created_at INTEGER NOT NULL
152);
157);
158
159CREATE TABLE IF NOT EXISTS character_bounties (
160 character_id INTEGER PRIMARY KEY,
161 amount INTEGER NOT NULL DEFAULT 0
162);
153`;
163`;
154
164
155export class StateDatabase
165export class StateDatabase
@@ -171,6 +181,13 @@ export class StateDatabase
171 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
181 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
172 if (!characterColumns.some((column) => column.name === "is_dead"))
182 if (!characterColumns.some((column) => column.name === "is_dead"))
173 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
183 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
184 if (!characterColumns.some((column) => column.name === "hair_style"))
185 {
186 this.db.exec("ALTER TABLE characters ADD COLUMN hair_style TEXT");
187 this.db.exec("ALTER TABLE characters ADD COLUMN hair_hue REAL NOT NULL DEFAULT 30");
188 this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
189 this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
190 }
174 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
191 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
175 if (!courierColumns.some((column) => column.name === "vault_character_id"))
192 if (!courierColumns.some((column) => column.name === "vault_character_id"))
176 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
193 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
@@ -253,18 +270,36 @@ export class StateDatabase
253 return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
270 return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
254 }
271 }
255
272
256 createCharacter (accountId, firstName, lastName, sex, tileX, tileY)
273 createCharacter (accountId, firstName, lastName, sex, tileX, tileY, hair = null, starterSettings = null)
257 {
274 {
258 const firstNormalized = normalizeName(firstName);
275 const firstNormalized = normalizeName(firstName);
259 const lastNormalized = normalizeName(lastName);
276 const lastNormalized = normalizeName(lastName);
277 const hairStyle = hair?.style ?? null;
278 const hairHue = Number(hair?.hue) || 30;
279 const hairSaturation = Number(hair?.saturation);
280 const hairDarkness = Number(hair?.darkness);
260 this.db.exec("BEGIN");
281 this.db.exec("BEGIN");
261 try
282 try
262 {
283 {
263 this.db.prepare(`
284 this.db.prepare(`
264 INSERT INTO characters (
285 INSERT INTO characters (
265 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y
286 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
266 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
287 hair_style, hair_hue, hair_saturation, hair_darkness
267 `).run(accountId, firstName, lastName, firstNormalized, lastNormalized, sex, tileX, tileY);
288 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
289 `).run(
290 accountId,
291 firstName,
292 lastName,
293 firstNormalized,
294 lastNormalized,
295 sex,
296 tileX,
297 tileY,
298 hairStyle,
299 hairHue,
300 Number.isFinite(hairSaturation) ? hairSaturation : 0.55,
301 Number.isFinite(hairDarkness) ? hairDarkness : 0.45
302 );
268 const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
303 const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
269
304
270 const claim = this.findSurnameClaim(lastNormalized);
305 const claim = this.findSurnameClaim(lastNormalized);
@@ -277,7 +312,7 @@ export class StateDatabase
277 }
312 }
278
313
279 this.db.exec("COMMIT");
314 this.db.exec("COMMIT");
280 this.#ensureBag(characterId);
315 this.#ensureBag(characterId, starterSettings);
281 return this.getCharacter(characterId);
316 return this.getCharacter(characterId);
282 }
317 }
283 catch (error)
318 catch (error)
@@ -287,6 +322,22 @@ export class StateDatabase
287 }
322 }
288 }
323 }
289
324
325 updateCharacterHair (characterId, { style, hue, saturation, darkness })
326 {
327 this.db.prepare(`
328 UPDATE characters
329 SET hair_style = ?, hair_hue = ?, hair_saturation = ?, hair_darkness = ?
330 WHERE character_id = ?
331 `).run(
332 style ?? null,
333 Number(hue) || 30,
334 Number.isFinite(Number(saturation)) ? Number(saturation) : 0.55,
335 Number.isFinite(Number(darkness)) ? Number(darkness) : 0.45,
336 characterId | 0
337 );
338 return this.getCharacter(characterId);
339 }
340
290 scheduleDeletion (characterId, at)
341 scheduleDeletion (characterId, at)
291 {
342 {
292 this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
343 this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
@@ -371,6 +422,42 @@ export class StateDatabase
371 `).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
422 `).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
372 }
423 }
373
424
425 getCharacterBounty (characterId)
426 {
427 const row = this.db.prepare(`
428 SELECT amount FROM character_bounties WHERE character_id = ?
429 `).get(characterId | 0);
430 return Math.max(0, row?.amount | 0);
431 }
432
433 /** Add coins to a bounty; returns the new total. */
434 addCharacterBounty (characterId, amount)
435 {
436 const id = characterId | 0;
437 const add = Math.max(0, amount | 0);
438 if (add <= 0)
439 { return this.getCharacterBounty(id); }
440 this.db.prepare(`
441 INSERT INTO character_bounties (character_id, amount) VALUES (?, ?)
442 ON CONFLICT(character_id) DO UPDATE SET amount = amount + excluded.amount
443 `).run(id, add);
444 return this.getCharacterBounty(id);
445 }
446
447 /** Zero out and return the previous bounty amount. */
448 takeCharacterBounty (characterId)
449 {
450 const id = characterId | 0;
451 const amount = this.getCharacterBounty(id);
452 if (amount <= 0)
453 { return 0; }
454 this.db.prepare(`
455 INSERT INTO character_bounties (character_id, amount) VALUES (?, 0)
456 ON CONFLICT(character_id) DO UPDATE SET amount = 0
457 `).run(id);
458 return amount;
459 }
460
374 listFriendRecords (characterId)
461 listFriendRecords (characterId)
375 {
462 {
376 return this.db.prepare(`
463 return this.db.prepare(`
@@ -492,28 +579,20 @@ export class StateDatabase
492 }
579 }
493 }
580 }
494
581
495 #ensureBag (characterId)
582 #ensureBag (characterId, starterSettings = null)
496 {
583 {
497 const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
584 const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
498 if (existing)
585 if (existing)
499 { return parseBag(existing, characterId); }
586 { return parseBag(existing, characterId); }
500 const slots = emptySlots();
587 const contents = buildStarterBagContents(starterSettings);
501 for (const starter of STARTER_ITEMS)
502 {
503 const result = insertStack(slots, { ...starter }, itemDefinition(starter.itemId));
504 if (result.ok)
505 { slots.splice(0, slots.length, ...result.slots); }
506 }
507 const equipment = emptyEquipment();
508 equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
509 this.db.prepare(`
588 this.db.prepare(`
510 INSERT INTO character_bags (
589 INSERT INTO character_bags (
511 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
590 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
512 ) VALUES (?, ?, ?, 0, ?, 0, ?)
591 ) VALUES (?, ?, ?, 0, ?, 0, ?)
513 `).run(
592 `).run(
514 characterId,
593 characterId,
515 JSON.stringify(slots),
594 JSON.stringify(contents.slots),
516 JSON.stringify(equipment),
595 JSON.stringify(contents.equipment),
517 JSON.stringify({ slots: [], reserved: [] }),
596 JSON.stringify({ slots: [], reserved: [] }),
518 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
597 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
519 );
598 );
server/src/persistence/worldDb.js +6 −1
@@ -1,4 +1,5 @@
1 1 import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2 import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
2 3 import { openDatabase, withTransaction } from "./database.js";
3 4
4 5 const WORLD_SCHEMA = `
@@ -100,9 +101,13 @@ export class WorldDatabase
100 101 {
101 102 this.#ensureLiveSettings();
102 103 const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get();
103 return row
104 const merged = row
104 105 ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }
105 106 : { ...DEFAULT_WORLD_SETTINGS };
107 const loadout = normalizeStarterLoadout(merged);
108 merged.starterEquipment = loadout.equipment;
109 merged.starterInventory = loadout.inventory;
110 return merged;
106 111 }
107 112
108 113 saveLiveSettings (settings, updatedBy)
@@ -1,4 +1,5 @@
1import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
1import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
2import { openDatabase, withTransaction } from "./database.js";
3import { openDatabase, withTransaction } from "./database.js";
3
4
4const WORLD_SCHEMA = `
5const WORLD_SCHEMA = `
@@ -100,9 +101,13 @@ export class WorldDatabase
100 {
101 {
101 this.#ensureLiveSettings();
102 this.#ensureLiveSettings();
102 const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get();
103 const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get();
103 return row
104 const merged = row
104 ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }
105 ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }
105 : { ...DEFAULT_WORLD_SETTINGS };
106 : { ...DEFAULT_WORLD_SETTINGS };
107 const loadout = normalizeStarterLoadout(merged);
108 merged.starterEquipment = loadout.equipment;
109 merged.starterInventory = loadout.inventory;
110 return merged;
106 }
111 }
107
112
108 saveLiveSettings (settings, updatedBy)
113 saveLiveSettings (settings, updatedBy)
server/src/simulation/protocol.js +2 −1
@@ -36,5 +36,6 @@ export const WorkerMessage = Object.freeze({
36 36 clearCombat: "clearCombat",
37 37 setItemLastSales: "setItemLastSales",
38 38 stationExchangeClerk: "stationExchangeClerk",
39 releaseExchangeClerk: "releaseExchangeClerk"
39 releaseExchangeClerk: "releaseExchangeClerk",
40 applyAppearance: "applyAppearance"
40 41 });
@@ -36,5 +36,6 @@ export const WorkerMessage = Object.freeze({
36 clearCombat: "clearCombat",
36 clearCombat: "clearCombat",
37 setItemLastSales: "setItemLastSales",
37 setItemLastSales: "setItemLastSales",
38 stationExchangeClerk: "stationExchangeClerk",
38 stationExchangeClerk: "stationExchangeClerk",
39 releaseExchangeClerk: "releaseExchangeClerk"
39 releaseExchangeClerk: "releaseExchangeClerk",
40 applyAppearance: "applyAppearance"
40});
41});
server/src/simulation/simulation.js +93 −5
@@ -37,7 +37,11 @@ import { ItemId } from "../../../shared/definitions/items.js";
37 37 import { seasonIdAt } from "../../../shared/world/season.js";
38 38 import { CourierService } from "../courier/service.js";
39 39 import { MarketService } from "../market/service.js";
40 import { BountyService } from "../bounty/service.js";
41 import { BarberService } from "../barber/service.js";
40 42 import { findReservedChequeIndex } from "../items/bags.js";
43 import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
44
41 45
42 46 export class Simulation
43 47 {
@@ -99,6 +103,8 @@ export class Simulation
99 103 worldDb: this.worldDb,
100 104 simulation: this
101 105 });
106 this.bounty = new BountyService(this.stateDb, this, this.courier);
107 this.barber = new BarberService(this.stateDb, this);
102 108 this.#refreshAltarIndex();
103 109 }
104 110
@@ -149,6 +155,7 @@ export class Simulation
149 155 }
150 156 this.#syncAllReplicas();
151 157 this.courier?.refreshBankIndex();
158 this.courier?.refreshBountyOfficeIndex();
152 159 this.market?.refreshIndex();
153 160 this.#refreshAltarIndex();
154 161 }
@@ -346,7 +353,8 @@ export class Simulation
346 353 appearance: {
347 354 sex: character.sex ?? row.sex,
348 355 firstName: character.first_name ?? row.first_name,
349 lastName: character.last_name ?? row.last_name
356 lastName: character.last_name ?? row.last_name,
357 ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character))
350 358 },
351 359 character: {
352 360 characterId: character.character_id ?? row.character_id,
@@ -507,6 +515,38 @@ export class Simulation
507 515 });
508 516 }
509 517
518 /**
519 * Persist hair + patch live appearance; returns public view.
520 */
521 setCharacterHair (characterId, hair)
522 {
523 const row = this.stateDb.updateCharacterHair(characterId, hair);
524 const entityId = this.characterEntities.get(characterId);
525 if (!entityId)
526 { return { row, view: null }; }
527 const fields = appearanceHairFields({
528 sex: row.sex,
529 style: hair.style,
530 hue: hair.hue,
531 saturation: hair.saturation,
532 darkness: hair.darkness
533 });
534 const record = this.directory.get(entityId);
535 if (!record)
536 { return { row, view: null }; }
537 const view = this.workers[record.workerId].call({
538 type: WorkerMessage.applyAppearance,
539 entityId,
540 appearance: fields
541 });
542 if (view)
543 {
544 this.#remember(view, record.workerId);
545 this.#queueReplication(replicationAppearance(view));
546 }
547 return { row, view };
548 }
549
510 550 pushSkills (characterId, skills)
511 551 {
512 552 this.pendingPrivate.push({
@@ -688,19 +728,20 @@ export class Simulation
688 728 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
689 729 }
690 730
691 /** Client view: 5×5 map ring; inner 3×3 includes entities and ground items. */
692 snapshotsForView (entityId)
731 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
732 snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS)
693 733 {
694 734 const record = this.directory.get(entityId);
695 735 if (!record)
696 736 { return []; }
697 737 const centerChunkX = tileToChunk(record.tileX);
698 738 const centerChunkY = tileToChunk(record.tileY);
739 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
699 740 const entityKeys = new Set(
700 741 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
701 742 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
702 743 );
703 return visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS)
744 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
704 745 .map((coord) =>
705 746 {
706 747 const key = chunkKey(coord.chunkX, coord.chunkY);
@@ -853,6 +894,25 @@ export class Simulation
853 894 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
854 895 return result?.events ?? [];
855 896 }
897 if (
898 item.command.type === "open-bounty"
899 || item.command.type === "raise-bounty"
900 || item.command.type === "get-character-bounty"
901 || item.command.type === "close-bounty"
902 )
903 {
904 const result = this.bounty.handleCommand(item.sessionId, item.command);
905 return result?.events ?? [];
906 }
907 if (
908 item.command.type === "open-barber"
909 || item.command.type === "set-hair"
910 || item.command.type === "close-barber"
911 )
912 {
913 const result = this.barber.handleCommand(item.sessionId, item.command);
914 return result?.events ?? [];
915 }
856 916 const entityId = this.characterEntities.get(item.command.characterId);
857 917 const record = entityId ? this.directory.get(entityId) : null;
858 918 if (!record)
@@ -927,6 +987,28 @@ export class Simulation
927 987 ...result.private
928 988 });
929 989 }
990 if (result?.statusEffectsChanged && view)
991 {
992 events.push({
993 type: "status-effects",
994 sessionId: item.sessionId,
995 characterId: view.characterId ?? item.command.characterId,
996 effects: view.statusEffects ?? [],
997 blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
998 });
999 }
1000 if (result?.healthChanged && view)
1001 {
1002 events.push({
1003 type: "entity-health",
1004 entityId: view.entityId,
1005 characterId: view.characterId ?? item.command.characterId,
1006 health: view.health,
1007 maxHealth: view.maxHealth,
1008 tileX: view.tileX,
1009 tileY: view.tileY
1010 });
1011 }
930 1012 return events;
931 1013 }
932 1014
@@ -997,6 +1079,12 @@ export class Simulation
997 1079 event.tileY,
998 1080 record.gait ?? GAIT.walk
999 1081 );
1082 this.bounty?.settleKill(
1083 event.characterId,
1084 event.attackerId,
1085 event.tileX,
1086 event.tileY
1087 );
1000 1088 for (const worker of this.workers)
1001 1089 {
1002 1090 worker.call({
@@ -1558,7 +1646,7 @@ export class Simulation
1558 1646 { return this.authoredCache.get(key); }
1559 1647 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1560 1648 const data = row
1561 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
1649 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId, chunkX, chunkY)
1562 1650 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1563 1651 this.authoredCache.set(key, data);
1564 1652 return data;
@@ -37,7 +37,11 @@ import { ItemId } from "../../../shared/definitions/items.js";
37import { seasonIdAt } from "../../../shared/world/season.js";
37import { seasonIdAt } from "../../../shared/world/season.js";
38import { CourierService } from "../courier/service.js";
38import { CourierService } from "../courier/service.js";
39import { MarketService } from "../market/service.js";
39import { MarketService } from "../market/service.js";
40import { BountyService } from "../bounty/service.js";
41import { BarberService } from "../barber/service.js";
40import { findReservedChequeIndex } from "../items/bags.js";
42import { findReservedChequeIndex } from "../items/bags.js";
43import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
44
41
45
42export class Simulation
46export class Simulation
43{
47{
@@ -99,6 +103,8 @@ export class Simulation
99 worldDb: this.worldDb,
103 worldDb: this.worldDb,
100 simulation: this
104 simulation: this
101 });
105 });
106 this.bounty = new BountyService(this.stateDb, this, this.courier);
107 this.barber = new BarberService(this.stateDb, this);
102 this.#refreshAltarIndex();
108 this.#refreshAltarIndex();
103 }
109 }
104
110
@@ -149,6 +155,7 @@ export class Simulation
149 }
155 }
150 this.#syncAllReplicas();
156 this.#syncAllReplicas();
151 this.courier?.refreshBankIndex();
157 this.courier?.refreshBankIndex();
158 this.courier?.refreshBountyOfficeIndex();
152 this.market?.refreshIndex();
159 this.market?.refreshIndex();
153 this.#refreshAltarIndex();
160 this.#refreshAltarIndex();
154 }
161 }
@@ -346,7 +353,8 @@ export class Simulation
346 appearance: {
353 appearance: {
347 sex: character.sex ?? row.sex,
354 sex: character.sex ?? row.sex,
348 firstName: character.first_name ?? row.first_name,
355 firstName: character.first_name ?? row.first_name,
349 lastName: character.last_name ?? row.last_name
356 lastName: character.last_name ?? row.last_name,
357 ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character))
350 },
358 },
351 character: {
359 character: {
352 characterId: character.character_id ?? row.character_id,
360 characterId: character.character_id ?? row.character_id,
@@ -507,6 +515,38 @@ export class Simulation
507 });
515 });
508 }
516 }
509
517
518 /**
519 * Persist hair + patch live appearance; returns public view.
520 */
521 setCharacterHair (characterId, hair)
522 {
523 const row = this.stateDb.updateCharacterHair(characterId, hair);
524 const entityId = this.characterEntities.get(characterId);
525 if (!entityId)
526 { return { row, view: null }; }
527 const fields = appearanceHairFields({
528 sex: row.sex,
529 style: hair.style,
530 hue: hair.hue,
531 saturation: hair.saturation,
532 darkness: hair.darkness
533 });
534 const record = this.directory.get(entityId);
535 if (!record)
536 { return { row, view: null }; }
537 const view = this.workers[record.workerId].call({
538 type: WorkerMessage.applyAppearance,
539 entityId,
540 appearance: fields
541 });
542 if (view)
543 {
544 this.#remember(view, record.workerId);
545 this.#queueReplication(replicationAppearance(view));
546 }
547 return { row, view };
548 }
549
510 pushSkills (characterId, skills)
550 pushSkills (characterId, skills)
511 {
551 {
512 this.pendingPrivate.push({
552 this.pendingPrivate.push({
@@ -688,19 +728,20 @@ export class Simulation
688 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
728 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
689 }
729 }
690
730
691 /** Client view: 5×5 map ring; inner 3×3 includes entities and ground items. */
731 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
692 snapshotsForView (entityId)
732 snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS)
693 {
733 {
694 const record = this.directory.get(entityId);
734 const record = this.directory.get(entityId);
695 if (!record)
735 if (!record)
696 { return []; }
736 { return []; }
697 const centerChunkX = tileToChunk(record.tileX);
737 const centerChunkX = tileToChunk(record.tileX);
698 const centerChunkY = tileToChunk(record.tileY);
738 const centerChunkY = tileToChunk(record.tileY);
739 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
699 const entityKeys = new Set(
740 const entityKeys = new Set(
700 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
741 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
701 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
742 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
702 );
743 );
703 return visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS)
744 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
704 .map((coord) =>
745 .map((coord) =>
705 {
746 {
706 const key = chunkKey(coord.chunkX, coord.chunkY);
747 const key = chunkKey(coord.chunkX, coord.chunkY);
@@ -853,6 +894,25 @@ export class Simulation
853 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
894 const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
854 return result?.events ?? [];
895 return result?.events ?? [];
855 }
896 }
897 if (
898 item.command.type === "open-bounty"
899 || item.command.type === "raise-bounty"
900 || item.command.type === "get-character-bounty"
901 || item.command.type === "close-bounty"
902 )
903 {
904 const result = this.bounty.handleCommand(item.sessionId, item.command);
905 return result?.events ?? [];
906 }
907 if (
908 item.command.type === "open-barber"
909 || item.command.type === "set-hair"
910 || item.command.type === "close-barber"
911 )
912 {
913 const result = this.barber.handleCommand(item.sessionId, item.command);
914 return result?.events ?? [];
915 }
856 const entityId = this.characterEntities.get(item.command.characterId);
916 const entityId = this.characterEntities.get(item.command.characterId);
857 const record = entityId ? this.directory.get(entityId) : null;
917 const record = entityId ? this.directory.get(entityId) : null;
858 if (!record)
918 if (!record)
@@ -927,6 +987,28 @@ export class Simulation
927 ...result.private
987 ...result.private
928 });
988 });
929 }
989 }
990 if (result?.statusEffectsChanged && view)
991 {
992 events.push({
993 type: "status-effects",
994 sessionId: item.sessionId,
995 characterId: view.characterId ?? item.command.characterId,
996 effects: view.statusEffects ?? [],
997 blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
998 });
999 }
1000 if (result?.healthChanged && view)
1001 {
1002 events.push({
1003 type: "entity-health",
1004 entityId: view.entityId,
1005 characterId: view.characterId ?? item.command.characterId,
1006 health: view.health,
1007 maxHealth: view.maxHealth,
1008 tileX: view.tileX,
1009 tileY: view.tileY
1010 });
1011 }
930 return events;
1012 return events;
931 }
1013 }
932
1014
@@ -997,6 +1079,12 @@ export class Simulation
997 event.tileY,
1079 event.tileY,
998 record.gait ?? GAIT.walk
1080 record.gait ?? GAIT.walk
999 );
1081 );
1082 this.bounty?.settleKill(
1083 event.characterId,
1084 event.attackerId,
1085 event.tileX,
1086 event.tileY
1087 );
1000 for (const worker of this.workers)
1088 for (const worker of this.workers)
1001 {
1089 {
1002 worker.call({
1090 worker.call({
@@ -1558,7 +1646,7 @@ export class Simulation
1558 { return this.authoredCache.get(key); }
1646 { return this.authoredCache.get(key); }
1559 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1647 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
1560 const data = row
1648 const data = row
1561 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
1649 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId, chunkX, chunkY)
1562 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1650 : createEmptyChunkData(this.settings.defaultGroundTypeId);
1563 this.authoredCache.set(key, data);
1651 this.authoredCache.set(key, data);
1564 return data;
1652 return data;
server/src/simulation/spawners.js +6 −1
@@ -11,6 +11,7 @@ import {
11 11 import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
12 12 import { emptyEquipment } from "../../../shared/items/inventory.js";
13 13 import { itemDefinition } from "../../../shared/definitions/items.js";
14 import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
14 15 import { Component } from "../ecs/components.js";
15 16 import { tileToChunk, tileToRegion } from "../world/coordinates.js";
16 17
@@ -117,7 +118,11 @@ export function mobComponents (request)
117 118 firstName: displayName,
118 119 lastName: ""
119 120 };
120 if (!def.usePlayerBody)
121 if (def.usePlayerBody)
122 {
123 Object.assign(appearance, appearanceHairFields(hairFromNameSeed(displayName, sex)));
124 }
125 else
121 126 {
122 127 const sprite = mobSpriteName(def.mobTypeId);
123 128 if (sprite)
@@ -11,6 +11,7 @@ import {
11import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
11import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
12import { emptyEquipment } from "../../../shared/items/inventory.js";
12import { emptyEquipment } from "../../../shared/items/inventory.js";
13import { itemDefinition } from "../../../shared/definitions/items.js";
13import { itemDefinition } from "../../../shared/definitions/items.js";
14import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
14import { Component } from "../ecs/components.js";
15import { Component } from "../ecs/components.js";
15import { tileToChunk, tileToRegion } from "../world/coordinates.js";
16import { tileToChunk, tileToRegion } from "../world/coordinates.js";
16
17
@@ -117,7 +118,11 @@ export function mobComponents (request)
117 firstName: displayName,
118 firstName: displayName,
118 lastName: ""
119 lastName: ""
119 };
120 };
120 if (!def.usePlayerBody)
121 if (def.usePlayerBody)
122 {
123 Object.assign(appearance, appearanceHairFields(hairFromNameSeed(displayName, sex)));
124 }
125 else
121 {
126 {
122 const sprite = mobSpriteName(def.mobTypeId);
127 const sprite = mobSpriteName(def.mobTypeId);
123 if (sprite)
128 if (sprite)
server/src/simulation/workerWorld.js +16 −0
@@ -62,6 +62,7 @@ import {
62 62 } from "../../../shared/stamina/rules.js";
63 63 import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
64 64 import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
65 import { stepStatusEffects } from "../statusEffects/service.js";
65 66
66 67 export class WorkerWorld
67 68 {
@@ -127,6 +128,8 @@ export class WorkerWorld
127 128 return this.#inspectStamina(message.entityId);
128 129 case WorkerMessage.applyBag:
129 130 return this.#applyBag(message.entityId, message.bag);
131 case WorkerMessage.applyAppearance:
132 return this.#applyAppearance(message.entityId, message.appearance);
130 133 case WorkerMessage.updateFlight:
131 134 return this.#updateFlight(message.entityId, message.flight, message.now);
132 135 case WorkerMessage.chunkIsSimulating:
@@ -572,6 +575,18 @@ export class WorkerWorld
572 575 return applyBagView(this.ecs, handle, bag);
573 576 }
574 577
578 #applyAppearance (entityId, appearancePatch)
579 {
580 const handle = this.ecs.handleOf(entityId);
581 if (handle == null)
582 { return null; }
583 const appearance = this.ecs.get(handle, Component.appearance);
584 if (!appearance)
585 { return null; }
586 Object.assign(appearance, appearancePatch ?? {});
587 return publicEntityView(this.ecs, entityId);
588 }
589
575 590 #updateFlight (entityId, flightPatch, now = Date.now())
576 591 {
577 592 const handle = this.ecs.handleOf(entityId);
@@ -945,6 +960,7 @@ export class WorkerWorld
945 960 const events = [];
946 961 const transferRequests = [];
947 962 this.#regenStamina(dt, events);
963 events.push(...stepStatusEffects(this, now, dt));
948 964 const flight = stepFreeFlight(this, now);
949 965 for (const event of flight)
950 966 {
@@ -62,6 +62,7 @@ import {
62} from "../../../shared/stamina/rules.js";
62} from "../../../shared/stamina/rules.js";
63import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
63import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
64import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
64import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
65import { stepStatusEffects } from "../statusEffects/service.js";
65
66
66export class WorkerWorld
67export class WorkerWorld
67{
68{
@@ -127,6 +128,8 @@ export class WorkerWorld
127 return this.#inspectStamina(message.entityId);
128 return this.#inspectStamina(message.entityId);
128 case WorkerMessage.applyBag:
129 case WorkerMessage.applyBag:
129 return this.#applyBag(message.entityId, message.bag);
130 return this.#applyBag(message.entityId, message.bag);
131 case WorkerMessage.applyAppearance:
132 return this.#applyAppearance(message.entityId, message.appearance);
130 case WorkerMessage.updateFlight:
133 case WorkerMessage.updateFlight:
131 return this.#updateFlight(message.entityId, message.flight, message.now);
134 return this.#updateFlight(message.entityId, message.flight, message.now);
132 case WorkerMessage.chunkIsSimulating:
135 case WorkerMessage.chunkIsSimulating:
@@ -572,6 +575,18 @@ export class WorkerWorld
572 return applyBagView(this.ecs, handle, bag);
575 return applyBagView(this.ecs, handle, bag);
573 }
576 }
574
577
578 #applyAppearance (entityId, appearancePatch)
579 {
580 const handle = this.ecs.handleOf(entityId);
581 if (handle == null)
582 { return null; }
583 const appearance = this.ecs.get(handle, Component.appearance);
584 if (!appearance)
585 { return null; }
586 Object.assign(appearance, appearancePatch ?? {});
587 return publicEntityView(this.ecs, entityId);
588 }
589
575 #updateFlight (entityId, flightPatch, now = Date.now())
590 #updateFlight (entityId, flightPatch, now = Date.now())
576 {
591 {
577 const handle = this.ecs.handleOf(entityId);
592 const handle = this.ecs.handleOf(entityId);
@@ -945,6 +960,7 @@ export class WorkerWorld
945 const events = [];
960 const events = [];
946 const transferRequests = [];
961 const transferRequests = [];
947 this.#regenStamina(dt, events);
962 this.#regenStamina(dt, events);
963 events.push(...stepStatusEffects(this, now, dt));
948 const flight = stepFreeFlight(this, now);
964 const flight = stepFreeFlight(this, now);
949 for (const event of flight)
965 for (const event of flight)
950 {
966 {
server/src/statusEffects/service.js added +124 −0
@@ -0,0 +1,124 @@
1 import { Component } from "../ecs/components.js";
2 import {
3 activeStatusEffects,
4 pruneStatusEffects,
5 StatusEffectType,
6 publicStatusEffectsView,
7 hasStatusEffect
8 } from "../../../shared/statusEffects/rules.js";
9 import { publicEntityView } from "../ecs/serialize.js";
10 import { syncPlayerHealth } from "../skills/service.js";
11
12 /**
13 * Tick timed potion effects: health/stamina regen & drain.
14 * Returns replication events (health/stamina/appearance/status-effects).
15 */
16 export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
17 {
18 const events = [];
19 for (const entity of world.ecs.query(Component.character, Component.statusEffects))
20 {
21 const { handle, entityId, character, statusEffects } = entity;
22 if (world.ecs.has(handle, Component.dead))
23 { continue; }
24
25 const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
26 const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
27 const beforeBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);
28 pruneStatusEffects(statusEffects, now);
29 const afterScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
30 const afterGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
31 const afterBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);
32
33 let healthChanged = false;
34 let staminaChanged = false;
35 const health = world.ecs.get(handle, Component.health);
36 const stamina = world.ecs.get(handle, Component.stamina);
37
38 for (const entry of activeStatusEffects(statusEffects, now))
39 {
40 const rate = Number(entry.amountPerSecond) || 0;
41 if (!rate)
42 { continue; }
43 if (entry.type === StatusEffectType.healthRegen && health)
44 {
45 const before = health.current | 0;
46 health.current = Math.min(health.max | 0, (health.current | 0) + rate * dt);
47 if ((health.current | 0) !== before)
48 { healthChanged = true; }
49 }
50 if (entry.type === StatusEffectType.staminaRegen && stamina)
51 {
52 const before = Number(stamina.current) || 0;
53 stamina.current = Math.min(stamina.max, before + rate * dt);
54 if (Math.ceil(before) !== Math.ceil(stamina.current))
55 { staminaChanged = true; }
56 }
57 if (entry.type === StatusEffectType.staminaDrain && stamina)
58 {
59 const before = Number(stamina.current) || 0;
60 stamina.current = Math.max(0, before - rate * dt);
61 if (Math.ceil(before) !== Math.ceil(stamina.current))
62 { staminaChanged = true; }
63 }
64 }
65
66 if (healthChanged)
67 {
68 syncPlayerHealth(world.ecs, handle);
69 const view = publicEntityView(world.ecs, entityId);
70 if (view)
71 {
72 events.push({
73 type: "entity-health",
74 entityId,
75 characterId: character.characterId,
76 health: view.health,
77 maxHealth: view.maxHealth,
78 tileX: view.tileX,
79 tileY: view.tileY
80 });
81 }
82 }
83
84 if (staminaChanged)
85 {
86 events.push({
87 type: "stamina",
88 characterId: character.characterId,
89 current: Number(stamina.current) || 0,
90 max: Math.max(1, stamina.max | 0)
91 });
92 }
93
94 const appearanceChanged = beforeScale !== afterScale || beforeGlow !== afterGlow;
95 const statusChanged = appearanceChanged || beforeBlind !== afterBlind;
96 if (appearanceChanged)
97 {
98 const view = publicEntityView(world.ecs, entityId);
99 if (view)
100 {
101 events.push({
102 type: "entity-appearance",
103 entityId: view.entityId,
104 tileX: view.tileX,
105 tileY: view.tileY,
106 sprite: view.sprite ?? null,
107 layers: view.layers ?? [],
108 lightRadiusTiles: view.lightRadiusTiles ?? 0,
109 visualScale: view.visualScale ?? 1
110 });
111 }
112 }
113 if (statusChanged || healthChanged)
114 {
115 events.push({
116 type: "status-effects",
117 characterId: character.characterId,
118 effects: publicStatusEffectsView(statusEffects, now),
119 blind: hasStatusEffect(statusEffects, StatusEffectType.blind, now)
120 });
121 }
122 }
123 return events;
124 }
@@ -0,0 +1,124 @@
1import { Component } from "../ecs/components.js";
2import {
3 activeStatusEffects,
4 pruneStatusEffects,
5 StatusEffectType,
6 publicStatusEffectsView,
7 hasStatusEffect
8} from "../../../shared/statusEffects/rules.js";
9import { publicEntityView } from "../ecs/serialize.js";
10import { syncPlayerHealth } from "../skills/service.js";
11
12/**
13 * Tick timed potion effects: health/stamina regen & drain.
14 * Returns replication events (health/stamina/appearance/status-effects).
15 */
16export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
17{
18 const events = [];
19 for (const entity of world.ecs.query(Component.character, Component.statusEffects))
20 {
21 const { handle, entityId, character, statusEffects } = entity;
22 if (world.ecs.has(handle, Component.dead))
23 { continue; }
24
25 const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
26 const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
27 const beforeBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);
28 pruneStatusEffects(statusEffects, now);
29 const afterScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
30 const afterGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
31 const afterBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);
32
33 let healthChanged = false;
34 let staminaChanged = false;
35 const health = world.ecs.get(handle, Component.health);
36 const stamina = world.ecs.get(handle, Component.stamina);
37
38 for (const entry of activeStatusEffects(statusEffects, now))
39 {
40 const rate = Number(entry.amountPerSecond) || 0;
41 if (!rate)
42 { continue; }
43 if (entry.type === StatusEffectType.healthRegen && health)
44 {
45 const before = health.current | 0;
46 health.current = Math.min(health.max | 0, (health.current | 0) + rate * dt);
47 if ((health.current | 0) !== before)
48 { healthChanged = true; }
49 }
50 if (entry.type === StatusEffectType.staminaRegen && stamina)
51 {
52 const before = Number(stamina.current) || 0;
53 stamina.current = Math.min(stamina.max, before + rate * dt);
54 if (Math.ceil(before) !== Math.ceil(stamina.current))
55 { staminaChanged = true; }
56 }
57 if (entry.type === StatusEffectType.staminaDrain && stamina)
58 {
59 const before = Number(stamina.current) || 0;
60 stamina.current = Math.max(0, before - rate * dt);
61 if (Math.ceil(before) !== Math.ceil(stamina.current))
62 { staminaChanged = true; }
63 }
64 }
65
66 if (healthChanged)
67 {
68 syncPlayerHealth(world.ecs, handle);
69 const view = publicEntityView(world.ecs, entityId);
70 if (view)
71 {
72 events.push({
73 type: "entity-health",
74 entityId,
75 characterId: character.characterId,
76 health: view.health,
77 maxHealth: view.maxHealth,
78 tileX: view.tileX,
79 tileY: view.tileY
80 });
81 }
82 }
83
84 if (staminaChanged)
85 {
86 events.push({
87 type: "stamina",
88 characterId: character.characterId,
89 current: Number(stamina.current) || 0,
90 max: Math.max(1, stamina.max | 0)
91 });
92 }
93
94 const appearanceChanged = beforeScale !== afterScale || beforeGlow !== afterGlow;
95 const statusChanged = appearanceChanged || beforeBlind !== afterBlind;
96 if (appearanceChanged)
97 {
98 const view = publicEntityView(world.ecs, entityId);
99 if (view)
100 {
101 events.push({
102 type: "entity-appearance",
103 entityId: view.entityId,
104 tileX: view.tileX,
105 tileY: view.tileY,
106 sprite: view.sprite ?? null,
107 layers: view.layers ?? [],
108 lightRadiusTiles: view.lightRadiusTiles ?? 0,
109 visualScale: view.visualScale ?? 1
110 });
111 }
112 }
113 if (statusChanged || healthChanged)
114 {
115 events.push({
116 type: "status-effects",
117 characterId: character.characterId,
118 effects: publicStatusEffectsView(statusEffects, now),
119 blind: hasStatusEffect(statusEffects, StatusEffectType.blind, now)
120 });
121 }
122 }
123 return events;
124}
server/src/world/chunkData.js +18 −2
@@ -10,6 +10,11 @@ import {
10 10 normalizeGround,
11 11 normalizeBlock
12 12 } from "../../../shared/definitions/tiles.js";
13 import {
14 flowerBlockState,
15 flowerColorIdFromBlockState,
16 flowerColorIdForTile
17 } from "../../../shared/definitions/dyes.js";
13 18 import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
14 19 import { tileIndex } from "./coordinates.js";
15 20
@@ -50,7 +55,7 @@ export function encodeChunkBlob (data)
50 55 });
51 56 }
52 57
53 export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
58 export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId, chunkX = 0, chunkY = 0)
54 59 {
55 60 if (!blob)
56 61 { return createEmptyChunkData(groundTypeId); }
@@ -70,14 +75,25 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
70 75 { light.push(0); }
71 76
72 77 const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
78 const originX = (chunkX | 0) * CHUNK_SIZE;
79 const originY = (chunkY | 0) * CHUNK_SIZE;
73 80
74 81 return {
75 82 open: !!parsed.open,
76 83 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
77 blocks: blocks.map((block) => {
84 blocks: blocks.map((block, index) =>
85 {
78 86 const normalized = normalizeBlock(block);
79 87 if (normalized?.typeId === BlockType.spawner)
80 88 { return null; }
89 if (normalized?.typeId === BlockType.flower && !flowerColorIdFromBlockState(normalized.state))
90 {
91 const localX = index % CHUNK_SIZE;
92 const localY = (index / CHUNK_SIZE) | 0;
93 normalized.state = flowerBlockState(
94 flowerColorIdForTile(originX + localX, originY + localY)
95 );
96 }
81 97 return normalized;
82 98 }),
83 99 light,
@@ -10,6 +10,11 @@ import {
10 normalizeGround,
10 normalizeGround,
11 normalizeBlock
11 normalizeBlock
12} from "../../../shared/definitions/tiles.js";
12} from "../../../shared/definitions/tiles.js";
13import {
14 flowerBlockState,
15 flowerColorIdFromBlockState,
16 flowerColorIdForTile
17} from "../../../shared/definitions/dyes.js";
13import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
18import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
14import { tileIndex } from "./coordinates.js";
19import { tileIndex } from "./coordinates.js";
15
20
@@ -50,7 +55,7 @@ export function encodeChunkBlob (data)
50 });
55 });
51}
56}
52
57
53export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
58export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId, chunkX = 0, chunkY = 0)
54{
59{
55 if (!blob)
60 if (!blob)
56 { return createEmptyChunkData(groundTypeId); }
61 { return createEmptyChunkData(groundTypeId); }
@@ -70,14 +75,25 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
70 { light.push(0); }
75 { light.push(0); }
71
76
72 const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
77 const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
78 const originX = (chunkX | 0) * CHUNK_SIZE;
79 const originY = (chunkY | 0) * CHUNK_SIZE;
73
80
74 return {
81 return {
75 open: !!parsed.open,
82 open: !!parsed.open,
76 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
83 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
77 blocks: blocks.map((block) => {
84 blocks: blocks.map((block, index) =>
85 {
78 const normalized = normalizeBlock(block);
86 const normalized = normalizeBlock(block);
79 if (normalized?.typeId === BlockType.spawner)
87 if (normalized?.typeId === BlockType.spawner)
80 { return null; }
88 { return null; }
89 if (normalized?.typeId === BlockType.flower && !flowerColorIdFromBlockState(normalized.state))
90 {
91 const localX = index % CHUNK_SIZE;
92 const localY = (index / CHUNK_SIZE) | 0;
93 normalized.state = flowerBlockState(
94 flowerColorIdForTile(originX + localX, originY + localY)
95 );
96 }
81 return normalized;
97 return normalized;
82 }),
98 }),
83 light,
99 light,
server/tests/alchemy.test.js +20 −25
@@ -41,27 +41,26 @@ function countItem (slots, itemId)
41 41 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
42 42 }
43 43
44 test("green draught ratios and steps evaluate to a success batch", () =>
44 test("lesser health tonic ratios and steps evaluate to a success batch", () =>
45 45 {
46 const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught");
46 const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic");
47 47 assert.ok(potion);
48 48 const evaluation = evaluateAlchemyBottle({
49 49 skills: { levels: { alchemy: 1 } },
50 50 brewStacks: [
51 { itemId: ItemId.greenHerb, quantity: 4 },
52 { itemId: ItemId.apple, quantity: 2 }
51 { itemId: ItemId.thyme, quantity: 2 },
52 { itemId: ItemId.mint, quantity: 2 }
53 53 ],
54 54 takenSteps: [
55 { kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },
55 { kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
56 56 { kind: AlchemyStepKind.heat },
57 { kind: AlchemyStepKind.stir },
58 { kind: AlchemyStepKind.insert, itemId: ItemId.apple },
59 { kind: AlchemyStepKind.cool }
57 { kind: AlchemyStepKind.insert, itemId: ItemId.mint },
58 { kind: AlchemyStepKind.stir }
60 59 ]
61 60 });
62 61 assert.equal(evaluation.success, true);
63 62 assert.equal(evaluation.batch, 2);
64 assert.equal(evaluation.result.potionKey, "greenDraught");
63 assert.equal(evaluation.result.potionKey, "lesserHealthTonic");
65 64 });
66 65
67 66 test("same wrong steps hash to the same unstable potion", () =>
@@ -75,9 +74,10 @@ test("same wrong steps hash to the same unstable potion", () =>
75 74 const b = unstablePotionFromSteps(steps);
76 75 assert.equal(a.potionKey, b.potionKey);
77 76 assert.equal(a.stepsHash, hashAlchemySteps(steps));
77 assert.ok(["stamina-drain", "glow", "shrink", "blind"].includes(a.effectKey));
78 78 });
79 79
80 test("cauldron bottles green draught when steps and ratios match", () =>
80 test("cauldron bottles lesser health tonic when steps and ratios match", () =>
81 81 {
82 82 const harness = makeSimulation({ workerCount: 1 });
83 83 try
@@ -86,8 +86,8 @@ test("cauldron bottles green draught when steps and ratios match", () =>
86 86 harness.simulation.reloadWorld();
87 87 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
88 88 const inventory = emptySlots();
89 inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 };
90 inventory[1] = { itemId: ItemId.apple, quantity: 2 };
89 inventory[0] = { itemId: ItemId.thyme, quantity: 2 };
90 inventory[1] = { itemId: ItemId.mint, quantity: 2 };
91 91 inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 };
92 92 inventory[3] = { itemId: ItemId.paper, quantity: 1 };
93 93 harness.stateDb.saveBag(character.character_id, {
@@ -106,14 +106,14 @@ test("cauldron bottles green draught when steps and ratios match", () =>
106 106 type: "cauldron-set-slot",
107 107 characterId: cid,
108 108 slotIndex: 0,
109 itemId: ItemId.greenHerb,
110 quantity: 4
109 itemId: ItemId.thyme,
110 quantity: 2
111 111 });
112 112 harness.simulation.enqueue(1, {
113 113 type: "cauldron-set-slot",
114 114 characterId: cid,
115 115 slotIndex: 1,
116 itemId: ItemId.apple,
116 itemId: ItemId.mint,
117 117 quantity: 2
118 118 });
119 119 harness.simulation.step();
@@ -124,27 +124,22 @@ test("cauldron bottles green draught when steps and ratios match", () =>
124 124 characterId: cid,
125 125 action: AlchemyStepKind.heat
126 126 });
127 harness.simulation.enqueue(1, {
128 type: "cauldron-action",
129 characterId: cid,
130 action: AlchemyStepKind.stir
131 });
132 127 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
133 128 harness.simulation.enqueue(1, {
134 129 type: "cauldron-action",
135 130 characterId: cid,
136 action: AlchemyStepKind.cool
131 action: AlchemyStepKind.stir
137 132 });
138 133 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
139 134 harness.simulation.step();
140 135
141 136 const bag = harness.simulation.bagOf(entityId);
142 assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0);
143 assert.equal(countItem(bag.inventory, ItemId.apple), 0);
137 assert.equal(countItem(bag.inventory, ItemId.thyme), 0);
138 assert.equal(countItem(bag.inventory, ItemId.mint), 0);
144 139 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
145 140 assert.equal(countItem(bag.inventory, ItemId.potion), 2);
146 141 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
147 assert.equal(potion.instance?.potionKey, "greenDraught");
142 assert.equal(potion.instance?.potionKey, "lesserHealthTonic");
148 143 assert.equal(potion.instance?.unstable, false);
149 144
150 145 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
@@ -153,7 +148,7 @@ test("cauldron bottles green draught when steps and ratios match", () =>
153 148 assert.equal(countItem(after.inventory, ItemId.paper), 0);
154 149 assert.equal(countItem(after.inventory, ItemId.recipePaper), 1);
155 150 const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper);
156 assert.match(recipe.instance?.body ?? "", /Green draught/);
151 assert.match(recipe.instance?.body ?? "", /Lesser health tonic/);
157 152 assert.match(recipe.instance?.body ?? "", /Alchemy level required/);
158 153 }
159 154 finally
@@ -41,27 +41,26 @@ function countItem (slots, itemId)
41 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
41 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
42}
42}
43
43
44test("green draught ratios and steps evaluate to a success batch", () =>
44test("lesser health tonic ratios and steps evaluate to a success batch", () =>
45{
45{
46 const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught");
46 const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic");
47 assert.ok(potion);
47 assert.ok(potion);
48 const evaluation = evaluateAlchemyBottle({
48 const evaluation = evaluateAlchemyBottle({
49 skills: { levels: { alchemy: 1 } },
49 skills: { levels: { alchemy: 1 } },
50 brewStacks: [
50 brewStacks: [
51 { itemId: ItemId.greenHerb, quantity: 4 },
51 { itemId: ItemId.thyme, quantity: 2 },
52 { itemId: ItemId.apple, quantity: 2 }
52 { itemId: ItemId.mint, quantity: 2 }
53 ],
53 ],
54 takenSteps: [
54 takenSteps: [
55 { kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },
55 { kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
56 { kind: AlchemyStepKind.heat },
56 { kind: AlchemyStepKind.heat },
57 { kind: AlchemyStepKind.stir },
57 { kind: AlchemyStepKind.insert, itemId: ItemId.mint },
58 { kind: AlchemyStepKind.insert, itemId: ItemId.apple },
58 { kind: AlchemyStepKind.stir }
59 { kind: AlchemyStepKind.cool }
60 ]
59 ]
61 });
60 });
62 assert.equal(evaluation.success, true);
61 assert.equal(evaluation.success, true);
63 assert.equal(evaluation.batch, 2);
62 assert.equal(evaluation.batch, 2);
64 assert.equal(evaluation.result.potionKey, "greenDraught");
63 assert.equal(evaluation.result.potionKey, "lesserHealthTonic");
65});
64});
66
65
67test("same wrong steps hash to the same unstable potion", () =>
66test("same wrong steps hash to the same unstable potion", () =>
@@ -75,9 +74,10 @@ test("same wrong steps hash to the same unstable potion", () =>
75 const b = unstablePotionFromSteps(steps);
74 const b = unstablePotionFromSteps(steps);
76 assert.equal(a.potionKey, b.potionKey);
75 assert.equal(a.potionKey, b.potionKey);
77 assert.equal(a.stepsHash, hashAlchemySteps(steps));
76 assert.equal(a.stepsHash, hashAlchemySteps(steps));
77 assert.ok(["stamina-drain", "glow", "shrink", "blind"].includes(a.effectKey));
78});
78});
79
79
80test("cauldron bottles green draught when steps and ratios match", () =>
80test("cauldron bottles lesser health tonic when steps and ratios match", () =>
81{
81{
82 const harness = makeSimulation({ workerCount: 1 });
82 const harness = makeSimulation({ workerCount: 1 });
83 try
83 try
@@ -86,8 +86,8 @@ test("cauldron bottles green draught when steps and ratios match", () =>
86 harness.simulation.reloadWorld();
86 harness.simulation.reloadWorld();
87 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
87 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
88 const inventory = emptySlots();
88 const inventory = emptySlots();
89 inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 };
89 inventory[0] = { itemId: ItemId.thyme, quantity: 2 };
90 inventory[1] = { itemId: ItemId.apple, quantity: 2 };
90 inventory[1] = { itemId: ItemId.mint, quantity: 2 };
91 inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 };
91 inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 };
92 inventory[3] = { itemId: ItemId.paper, quantity: 1 };
92 inventory[3] = { itemId: ItemId.paper, quantity: 1 };
93 harness.stateDb.saveBag(character.character_id, {
93 harness.stateDb.saveBag(character.character_id, {
@@ -106,14 +106,14 @@ test("cauldron bottles green draught when steps and ratios match", () =>
106 type: "cauldron-set-slot",
106 type: "cauldron-set-slot",
107 characterId: cid,
107 characterId: cid,
108 slotIndex: 0,
108 slotIndex: 0,
109 itemId: ItemId.greenHerb,
109 itemId: ItemId.thyme,
110 quantity: 4
110 quantity: 2
111 });
111 });
112 harness.simulation.enqueue(1, {
112 harness.simulation.enqueue(1, {
113 type: "cauldron-set-slot",
113 type: "cauldron-set-slot",
114 characterId: cid,
114 characterId: cid,
115 slotIndex: 1,
115 slotIndex: 1,
116 itemId: ItemId.apple,
116 itemId: ItemId.mint,
117 quantity: 2
117 quantity: 2
118 });
118 });
119 harness.simulation.step();
119 harness.simulation.step();
@@ -124,27 +124,22 @@ test("cauldron bottles green draught when steps and ratios match", () =>
124 characterId: cid,
124 characterId: cid,
125 action: AlchemyStepKind.heat
125 action: AlchemyStepKind.heat
126 });
126 });
127 harness.simulation.enqueue(1, {
128 type: "cauldron-action",
129 characterId: cid,
130 action: AlchemyStepKind.stir
131 });
132 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
127 harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
133 harness.simulation.enqueue(1, {
128 harness.simulation.enqueue(1, {
134 type: "cauldron-action",
129 type: "cauldron-action",
135 characterId: cid,
130 characterId: cid,
136 action: AlchemyStepKind.cool
131 action: AlchemyStepKind.stir
137 });
132 });
138 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
133 harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
139 harness.simulation.step();
134 harness.simulation.step();
140
135
141 const bag = harness.simulation.bagOf(entityId);
136 const bag = harness.simulation.bagOf(entityId);
142 assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0);
137 assert.equal(countItem(bag.inventory, ItemId.thyme), 0);
143 assert.equal(countItem(bag.inventory, ItemId.apple), 0);
138 assert.equal(countItem(bag.inventory, ItemId.mint), 0);
144 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
139 assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
145 assert.equal(countItem(bag.inventory, ItemId.potion), 2);
140 assert.equal(countItem(bag.inventory, ItemId.potion), 2);
146 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
141 const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
147 assert.equal(potion.instance?.potionKey, "greenDraught");
142 assert.equal(potion.instance?.potionKey, "lesserHealthTonic");
148 assert.equal(potion.instance?.unstable, false);
143 assert.equal(potion.instance?.unstable, false);
149
144
150 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
145 harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
@@ -153,7 +148,7 @@ test("cauldron bottles green draught when steps and ratios match", () =>
153 assert.equal(countItem(after.inventory, ItemId.paper), 0);
148 assert.equal(countItem(after.inventory, ItemId.paper), 0);
154 assert.equal(countItem(after.inventory, ItemId.recipePaper), 1);
149 assert.equal(countItem(after.inventory, ItemId.recipePaper), 1);
155 const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper);
150 const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper);
156 assert.match(recipe.instance?.body ?? "", /Green draught/);
151 assert.match(recipe.instance?.body ?? "", /Lesser health tonic/);
157 assert.match(recipe.instance?.body ?? "", /Alchemy level required/);
152 assert.match(recipe.instance?.body ?? "", /Alchemy level required/);
158 }
153 }
159 finally
154 finally
server/tests/bounty.test.js added +194 −0
@@ -0,0 +1,194 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import { ItemId } from "../../shared/definitions/items.js";
5 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
6 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7 import { Component } from "../src/ecs/components.js";
8 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9
10 function placeBlock (worldDb, tileX, tileY, typeId)
11 {
12 const chunkX = Math.floor(tileX / 16);
13 const chunkY = Math.floor(tileY / 16);
14 const data = createEmptyChunkData();
15 data.open = true;
16 const localX = tileX - chunkX * 16;
17 const localY = tileY - chunkY * 16;
18 data.blocks[localY * 16 + localX] = { typeId, state: 0 };
19 worldDb.saveChunkVersion(
20 chunkX,
21 chunkY,
22 worldDb.getActiveRevisionId(),
23 true,
24 encodeChunkBlob(data)
25 );
26 }
27
28 function countCoins (slots)
29 {
30 return (slots ?? [])
31 .filter((slot) => slot?.itemId === ItemId.coins)
32 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
33 }
34
35 function giveCoins (harness, entityId, amount)
36 {
37 const bag = harness.simulation.bagOf(entityId);
38 bag.inventory = emptySlots();
39 bag.inventory[0] = { itemId: ItemId.coins, quantity: amount };
40 bag.equipment = emptyEquipment();
41 harness.simulation.applyBag(entityId, bag);
42 harness.stateDb.saveBag(
43 harness.simulation.directory.get(entityId).characterId,
44 bag
45 );
46 }
47
48 function componentsOf (simulation, entityId)
49 {
50 const record = simulation.entityRecord(entityId);
51 const worker = simulation.workers[record.workerId];
52 const handle = worker.world.ecs.handleOf(entityId);
53 return worker.world.ecs.componentsOf(handle);
54 }
55
56 function withDeterministicCombat (fn)
57 {
58 const random = Math.random;
59 Math.random = () => 0;
60 try
61 { fn(); }
62 finally
63 { Math.random = random; }
64 }
65
66 test("raise bounty spends inventory coins and tracks ledger", () =>
67 {
68 const harness = makeSimulation({ workerCount: 1 });
69 try
70 {
71 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
72 harness.simulation.reloadWorld();
73 const placer = makeCharacter(harness.stateDb, {
74 firstName: "Place",
75 lastName: "R",
76 tileX: 8,
77 tileY: 9
78 });
79 const target = makeCharacter(harness.stateDb, {
80 firstName: "Mark",
81 lastName: "Ed",
82 tileX: 10,
83 tileY: 10
84 });
85 const placerId = harness.simulation.spawnCharacter(1, placer);
86 giveCoins(harness, placerId, 500);
87
88 harness.simulation.enqueue(1, {
89 type: "raise-bounty",
90 characterId: placer.character_id,
91 firstName: "Mark",
92 lastName: "Ed",
93 amountCopper: 250
94 });
95 const result = harness.simulation.step();
96 const snap = result.events.find((event) => event.type === "bounty-snapshot");
97 assert.ok(snap?.raised);
98 assert.equal(snap.raised.amountCopper, 250);
99 assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 250);
100 assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 250);
101
102 harness.simulation.enqueue(1, {
103 type: "raise-bounty",
104 characterId: placer.character_id,
105 firstName: "Mark",
106 lastName: "Ed",
107 amountCopper: 100
108 });
109 harness.simulation.step();
110 assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 350);
111 assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 150);
112 }
113 finally
114 { harness.close(); }
115 });
116
117 test("open bounty requires standing next to a bounty office", () =>
118 {
119 const harness = makeSimulation({ workerCount: 1 });
120 try
121 {
122 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
123 harness.simulation.reloadWorld();
124 const character = makeCharacter(harness.stateDb, { tileX: 12, tileY: 12 });
125 harness.simulation.spawnCharacter(1, character);
126 harness.simulation.enqueue(1, {
127 type: "open-bounty",
128 characterId: character.character_id
129 });
130 const result = harness.simulation.step();
131 const error = result.events.find((event) => event.type === "command-error");
132 assert.ok(error);
133 assert.match(error.message, /Bounty Office/i);
134 }
135 finally
136 { harness.close(); }
137 });
138
139 test("PvP kill pays bounty into killer vault and clears ledger", () =>
140 {
141 withDeterministicCombat(() =>
142 {
143 const harness = makeSimulation({ workerCount: 1 });
144 try
145 {
146 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
147 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
148 harness.simulation.reloadWorld();
149
150 const victim = makeCharacter(harness.stateDb, {
151 firstName: "Vic",
152 lastName: "Tim",
153 tileX: 9,
154 tileY: 9
155 });
156 const killer = makeCharacter(harness.stateDb, {
157 firstName: "Kill",
158 lastName: "Er",
159 tileX: 10,
160 tileY: 9
161 });
162 harness.stateDb.addCharacterBounty(victim.character_id, 400);
163
164 const victimId = harness.simulation.spawnCharacter(1, victim);
165 const killerId = harness.simulation.spawnCharacter(2, killer);
166 const victimComps = componentsOf(harness.simulation, victimId);
167 victimComps.health.current = 1;
168 const killerComps = componentsOf(harness.simulation, killerId);
169 killerComps.health.current = 1_000_000;
170 killerComps.health.max = 1_000_000;
171
172 harness.simulation.enqueue(2, {
173 type: "attack",
174 characterId: killer.character_id,
175 targetEntityId: victimId
176 });
177
178 let died = null;
179 for (let i = 0; i < 200; i++)
180 {
181 harness.advance(50);
182 const events = harness.simulation.step().events;
183 died = events.find((event) => event.type === "player-died");
184 if (died)
185 { break; }
186 }
187 assert.ok(died, "victim should die");
188 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
189 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
190 }
191 finally
192 { harness.close(); }
193 });
194 });
@@ -0,0 +1,194 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
6import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7import { Component } from "../src/ecs/components.js";
8import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9
10function placeBlock (worldDb, tileX, tileY, typeId)
11{
12 const chunkX = Math.floor(tileX / 16);
13 const chunkY = Math.floor(tileY / 16);
14 const data = createEmptyChunkData();
15 data.open = true;
16 const localX = tileX - chunkX * 16;
17 const localY = tileY - chunkY * 16;
18 data.blocks[localY * 16 + localX] = { typeId, state: 0 };
19 worldDb.saveChunkVersion(
20 chunkX,
21 chunkY,
22 worldDb.getActiveRevisionId(),
23 true,
24 encodeChunkBlob(data)
25 );
26}
27
28function countCoins (slots)
29{
30 return (slots ?? [])
31 .filter((slot) => slot?.itemId === ItemId.coins)
32 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
33}
34
35function giveCoins (harness, entityId, amount)
36{
37 const bag = harness.simulation.bagOf(entityId);
38 bag.inventory = emptySlots();
39 bag.inventory[0] = { itemId: ItemId.coins, quantity: amount };
40 bag.equipment = emptyEquipment();
41 harness.simulation.applyBag(entityId, bag);
42 harness.stateDb.saveBag(
43 harness.simulation.directory.get(entityId).characterId,
44 bag
45 );
46}
47
48function componentsOf (simulation, entityId)
49{
50 const record = simulation.entityRecord(entityId);
51 const worker = simulation.workers[record.workerId];
52 const handle = worker.world.ecs.handleOf(entityId);
53 return worker.world.ecs.componentsOf(handle);
54}
55
56function withDeterministicCombat (fn)
57{
58 const random = Math.random;
59 Math.random = () => 0;
60 try
61 { fn(); }
62 finally
63 { Math.random = random; }
64}
65
66test("raise bounty spends inventory coins and tracks ledger", () =>
67{
68 const harness = makeSimulation({ workerCount: 1 });
69 try
70 {
71 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
72 harness.simulation.reloadWorld();
73 const placer = makeCharacter(harness.stateDb, {
74 firstName: "Place",
75 lastName: "R",
76 tileX: 8,
77 tileY: 9
78 });
79 const target = makeCharacter(harness.stateDb, {
80 firstName: "Mark",
81 lastName: "Ed",
82 tileX: 10,
83 tileY: 10
84 });
85 const placerId = harness.simulation.spawnCharacter(1, placer);
86 giveCoins(harness, placerId, 500);
87
88 harness.simulation.enqueue(1, {
89 type: "raise-bounty",
90 characterId: placer.character_id,
91 firstName: "Mark",
92 lastName: "Ed",
93 amountCopper: 250
94 });
95 const result = harness.simulation.step();
96 const snap = result.events.find((event) => event.type === "bounty-snapshot");
97 assert.ok(snap?.raised);
98 assert.equal(snap.raised.amountCopper, 250);
99 assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 250);
100 assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 250);
101
102 harness.simulation.enqueue(1, {
103 type: "raise-bounty",
104 characterId: placer.character_id,
105 firstName: "Mark",
106 lastName: "Ed",
107 amountCopper: 100
108 });
109 harness.simulation.step();
110 assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 350);
111 assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 150);
112 }
113 finally
114 { harness.close(); }
115});
116
117test("open bounty requires standing next to a bounty office", () =>
118{
119 const harness = makeSimulation({ workerCount: 1 });
120 try
121 {
122 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
123 harness.simulation.reloadWorld();
124 const character = makeCharacter(harness.stateDb, { tileX: 12, tileY: 12 });
125 harness.simulation.spawnCharacter(1, character);
126 harness.simulation.enqueue(1, {
127 type: "open-bounty",
128 characterId: character.character_id
129 });
130 const result = harness.simulation.step();
131 const error = result.events.find((event) => event.type === "command-error");
132 assert.ok(error);
133 assert.match(error.message, /Bounty Office/i);
134 }
135 finally
136 { harness.close(); }
137});
138
139test("PvP kill pays bounty into killer vault and clears ledger", () =>
140{
141 withDeterministicCombat(() =>
142 {
143 const harness = makeSimulation({ workerCount: 1 });
144 try
145 {
146 placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
147 placeBlock(harness.worldDb, 7, 8, BlockType.bank);
148 harness.simulation.reloadWorld();
149
150 const victim = makeCharacter(harness.stateDb, {
151 firstName: "Vic",
152 lastName: "Tim",
153 tileX: 9,
154 tileY: 9
155 });
156 const killer = makeCharacter(harness.stateDb, {
157 firstName: "Kill",
158 lastName: "Er",
159 tileX: 10,
160 tileY: 9
161 });
162 harness.stateDb.addCharacterBounty(victim.character_id, 400);
163
164 const victimId = harness.simulation.spawnCharacter(1, victim);
165 const killerId = harness.simulation.spawnCharacter(2, killer);
166 const victimComps = componentsOf(harness.simulation, victimId);
167 victimComps.health.current = 1;
168 const killerComps = componentsOf(harness.simulation, killerId);
169 killerComps.health.current = 1_000_000;
170 killerComps.health.max = 1_000_000;
171
172 harness.simulation.enqueue(2, {
173 type: "attack",
174 characterId: killer.character_id,
175 targetEntityId: victimId
176 });
177
178 let died = null;
179 for (let i = 0; i < 200; i++)
180 {
181 harness.advance(50);
182 const events = harness.simulation.step().events;
183 died = events.find((event) => event.type === "player-died");
184 if (died)
185 { break; }
186 }
187 assert.ok(died, "victim should die");
188 assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
189 assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
190 }
191 finally
192 { harness.close(); }
193 });
194});
server/tests/fillCharge.test.js +5 −5
@@ -32,12 +32,12 @@ function potionStack (fillLevel, quantity = 1)
32 32 itemId: ItemId.potion,
33 33 quantity,
34 34 instance: potionItemInstance({
35 potionKey: "greenDraught",
36 displayName: "Green draught",
37 color: { r: 0.25, g: 0.72, b: 0.35 },
35 potionKey: "lesserHealthTonic",
36 displayName: "Lesser health tonic",
37 color: { r: 0.35, g: 0.78, b: 0.42 },
38 38 fillLevel,
39 effect: { type: "heal", amount: 5 },
40 effectKey: "heal"
39 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
40 effectKey: "health-regen"
41 41 })
42 42 };
43 43 }
@@ -32,12 +32,12 @@ function potionStack (fillLevel, quantity = 1)
32 itemId: ItemId.potion,
32 itemId: ItemId.potion,
33 quantity,
33 quantity,
34 instance: potionItemInstance({
34 instance: potionItemInstance({
35 potionKey: "greenDraught",
35 potionKey: "lesserHealthTonic",
36 displayName: "Green draught",
36 displayName: "Lesser health tonic",
37 color: { r: 0.25, g: 0.72, b: 0.35 },
37 color: { r: 0.35, g: 0.78, b: 0.42 },
38 fillLevel,
38 fillLevel,
39 effect: { type: "heal", amount: 5 },
39 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
40 effectKey: "heal"
40 effectKey: "health-regen"
41 })
41 })
42 };
42 };
43}
43}
server/tests/herbalism.test.js added +142 −0
@@ -0,0 +1,142 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import { ItemId } from "../../shared/definitions/items.js";
5 import { HerbId } from "../../shared/definitions/herbs.js";
6 import { SkillId } from "../../shared/definitions/skills.js";
7 import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
8 import { evaluateAlchemyBottle, resolvedAlchemyPotions } from "../../shared/alchemy/recipes.js";
9 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10 import { totalXpForLevel } from "../../shared/skills/progression.js";
11 import { Component } from "../src/ecs/components.js";
12 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
13 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
14
15 function placeBlock (worldDb, tileX, tileY, typeId, state = 0)
16 {
17 const chunkX = Math.floor(tileX / 16);
18 const chunkY = Math.floor(tileY / 16);
19 const data = createEmptyChunkData();
20 data.open = true;
21 const localX = tileX - chunkX * 16;
22 const localY = tileY - chunkY * 16;
23 data.blocks[localY * 16 + localX] = { typeId, state };
24 worldDb.saveChunkVersion(
25 chunkX,
26 chunkY,
27 worldDb.getActiveRevisionId(),
28 true,
29 encodeChunkBlob(data)
30 );
31 }
32
33 function countItem (slots, itemId)
34 {
35 return (slots ?? [])
36 .filter((slot) => slot?.itemId === itemId)
37 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
38 }
39
40 test("sage herb plant yields sage with clippers", () =>
41 {
42 const harness = makeSimulation({ workerCount: 1 });
43 try
44 {
45 placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.sage);
46 harness.simulation.reloadWorld();
47 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
48 const entityId = harness.simulation.spawnCharacter(1, character);
49 const bag = harness.simulation.bagOf(entityId);
50 bag.inventory = emptySlots();
51 bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
52 bag.equipment = emptyEquipment();
53 harness.simulation.applyBag(entityId, bag);
54
55 const record = harness.simulation.entityRecord(entityId);
56 const worker = harness.simulation.workers[record.workerId];
57 const handle = worker.world.ecs.handleOf(entityId);
58 const skills = worker.world.ecs.get(handle, Component.skills);
59 skills.xp[SkillId.herbalism] = totalXpForLevel(5);
60
61 harness.simulation.enqueue(1, {
62 type: "pick",
63 characterId: character.character_id,
64 tileX: 8,
65 tileY: 8
66 });
67 harness.simulation.step();
68 harness.advance(4000);
69 harness.simulation.step();
70 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.sage), 1);
71 }
72 finally
73 { harness.close(); }
74 });
75
76 test("aconite herb plant rejects low herbalism", () =>
77 {
78 const harness = makeSimulation({ workerCount: 1 });
79 try
80 {
81 placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.aconite);
82 harness.simulation.reloadWorld();
83 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
84 const entityId = harness.simulation.spawnCharacter(1, character);
85 const bag = harness.simulation.bagOf(entityId);
86 bag.inventory = emptySlots();
87 bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
88 bag.equipment = emptyEquipment();
89 harness.simulation.applyBag(entityId, bag);
90
91 harness.simulation.enqueue(1, {
92 type: "pick",
93 characterId: character.character_id,
94 tileX: 8,
95 tileY: 8
96 });
97 const result = harness.simulation.step();
98 const error = result.events.find((event) => event.type === "command-error");
99 assert.ok(error);
100 assert.match(error.message, /Herbalism 45/i);
101 }
102 finally
103 { harness.close(); }
104 });
105
106 test("starter potions evaluate with herb recipes", () =>
107 {
108 const tonic = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic");
109 assert.ok(tonic);
110 const evaluation = evaluateAlchemyBottle({
111 skills: { levels: { alchemy: 1 } },
112 brewStacks: [
113 { itemId: ItemId.thyme, quantity: 1 },
114 { itemId: ItemId.mint, quantity: 1 }
115 ],
116 takenSteps: [
117 { kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
118 { kind: AlchemyStepKind.heat },
119 { kind: AlchemyStepKind.insert, itemId: ItemId.mint },
120 { kind: AlchemyStepKind.stir }
121 ]
122 });
123 assert.equal(evaluation.success, true);
124 assert.equal(evaluation.result.potionKey, "lesserHealthTonic");
125 assert.equal(evaluation.result.effect.type, "health-regen");
126
127 const strength = evaluateAlchemyBottle({
128 skills: { levels: { alchemy: 1 } },
129 brewStacks: [
130 { itemId: ItemId.thyme, quantity: 3 },
131 { itemId: ItemId.nettle, quantity: 2 }
132 ],
133 takenSteps: [
134 { kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
135 { kind: AlchemyStepKind.stir },
136 { kind: AlchemyStepKind.insert, itemId: ItemId.nettle },
137 { kind: AlchemyStepKind.heat }
138 ]
139 });
140 assert.equal(strength.success, true);
141 assert.equal(strength.result.potionKey, "strengthPotion");
142 });
@@ -0,0 +1,142 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { HerbId } from "../../shared/definitions/herbs.js";
6import { SkillId } from "../../shared/definitions/skills.js";
7import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
8import { evaluateAlchemyBottle, resolvedAlchemyPotions } from "../../shared/alchemy/recipes.js";
9import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
10import { totalXpForLevel } from "../../shared/skills/progression.js";
11import { Component } from "../src/ecs/components.js";
12import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
13import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
14
15function placeBlock (worldDb, tileX, tileY, typeId, state = 0)
16{
17 const chunkX = Math.floor(tileX / 16);
18 const chunkY = Math.floor(tileY / 16);
19 const data = createEmptyChunkData();
20 data.open = true;
21 const localX = tileX - chunkX * 16;
22 const localY = tileY - chunkY * 16;
23 data.blocks[localY * 16 + localX] = { typeId, state };
24 worldDb.saveChunkVersion(
25 chunkX,
26 chunkY,
27 worldDb.getActiveRevisionId(),
28 true,
29 encodeChunkBlob(data)
30 );
31}
32
33function countItem (slots, itemId)
34{
35 return (slots ?? [])
36 .filter((slot) => slot?.itemId === itemId)
37 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
38}
39
40test("sage herb plant yields sage with clippers", () =>
41{
42 const harness = makeSimulation({ workerCount: 1 });
43 try
44 {
45 placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.sage);
46 harness.simulation.reloadWorld();
47 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
48 const entityId = harness.simulation.spawnCharacter(1, character);
49 const bag = harness.simulation.bagOf(entityId);
50 bag.inventory = emptySlots();
51 bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
52 bag.equipment = emptyEquipment();
53 harness.simulation.applyBag(entityId, bag);
54
55 const record = harness.simulation.entityRecord(entityId);
56 const worker = harness.simulation.workers[record.workerId];
57 const handle = worker.world.ecs.handleOf(entityId);
58 const skills = worker.world.ecs.get(handle, Component.skills);
59 skills.xp[SkillId.herbalism] = totalXpForLevel(5);
60
61 harness.simulation.enqueue(1, {
62 type: "pick",
63 characterId: character.character_id,
64 tileX: 8,
65 tileY: 8
66 });
67 harness.simulation.step();
68 harness.advance(4000);
69 harness.simulation.step();
70 assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.sage), 1);
71 }
72 finally
73 { harness.close(); }
74});
75
76test("aconite herb plant rejects low herbalism", () =>
77{
78 const harness = makeSimulation({ workerCount: 1 });
79 try
80 {
81 placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.aconite);
82 harness.simulation.reloadWorld();
83 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
84 const entityId = harness.simulation.spawnCharacter(1, character);
85 const bag = harness.simulation.bagOf(entityId);
86 bag.inventory = emptySlots();
87 bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
88 bag.equipment = emptyEquipment();
89 harness.simulation.applyBag(entityId, bag);
90
91 harness.simulation.enqueue(1, {
92 type: "pick",
93 characterId: character.character_id,
94 tileX: 8,
95 tileY: 8
96 });
97 const result = harness.simulation.step();
98 const error = result.events.find((event) => event.type === "command-error");
99 assert.ok(error);
100 assert.match(error.message, /Herbalism 45/i);
101 }
102 finally
103 { harness.close(); }
104});
105
106test("starter potions evaluate with herb recipes", () =>
107{
108 const tonic = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic");
109 assert.ok(tonic);
110 const evaluation = evaluateAlchemyBottle({
111 skills: { levels: { alchemy: 1 } },
112 brewStacks: [
113 { itemId: ItemId.thyme, quantity: 1 },
114 { itemId: ItemId.mint, quantity: 1 }
115 ],
116 takenSteps: [
117 { kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
118 { kind: AlchemyStepKind.heat },
119 { kind: AlchemyStepKind.insert, itemId: ItemId.mint },
120 { kind: AlchemyStepKind.stir }
121 ]
122 });
123 assert.equal(evaluation.success, true);
124 assert.equal(evaluation.result.potionKey, "lesserHealthTonic");
125 assert.equal(evaluation.result.effect.type, "health-regen");
126
127 const strength = evaluateAlchemyBottle({
128 skills: { levels: { alchemy: 1 } },
129 brewStacks: [
130 { itemId: ItemId.thyme, quantity: 3 },
131 { itemId: ItemId.nettle, quantity: 2 }
132 ],
133 takenSteps: [
134 { kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
135 { kind: AlchemyStepKind.stir },
136 { kind: AlchemyStepKind.insert, itemId: ItemId.nettle },
137 { kind: AlchemyStepKind.heat }
138 ]
139 });
140 assert.equal(strength.success, true);
141 assert.equal(strength.result.potionKey, "strengthPotion");
142});
server/tests/tile-states.test.js +29 −0
@@ -62,6 +62,35 @@ test("state cycling wraps and unknown values fall back to default", () =>
62 62 assert.equal(cycleState(["1", "2"], "1", -1), "2");
63 63 });
64 64
65 test("legacy flower blocks get a tile-seeded colour on decode", () =>
66 {
67 const data = decodeChunkBlob({
68 open: true,
69 grounds: [],
70 blocks: [{ typeId: BlockType.flower, state: "flower", config: null }],
71 light: []
72 }, undefined, 0, 0);
73 assert.notEqual(data.blocks[0].state, "flower");
74 assert.ok(
75 ["red", "blue", "cyan", "violet", "yellow", "magenta", "white", "black", "pink"]
76 .includes(data.blocks[0].state)
77 );
78 const again = decodeChunkBlob({
79 open: true,
80 grounds: [],
81 blocks: [{ typeId: BlockType.flower, state: "flower", config: null }],
82 light: []
83 }, undefined, 0, 0);
84 assert.equal(again.blocks[0].state, data.blocks[0].state);
85 const coloured = decodeChunkBlob({
86 open: true,
87 grounds: [],
88 blocks: [{ typeId: BlockType.flower, state: "blue", config: null }],
89 light: []
90 }, undefined, 0, 0);
91 assert.equal(coloured.blocks[0].state, "blue");
92 });
93
65 94 test("old numeric grounds decode as default visual state", () =>
66 95 {
67 96 const data = decodeChunkBlob({
@@ -62,6 +62,35 @@ test("state cycling wraps and unknown values fall back to default", () =>
62 assert.equal(cycleState(["1", "2"], "1", -1), "2");
62 assert.equal(cycleState(["1", "2"], "1", -1), "2");
63});
63});
64
64
65test("legacy flower blocks get a tile-seeded colour on decode", () =>
66{
67 const data = decodeChunkBlob({
68 open: true,
69 grounds: [],
70 blocks: [{ typeId: BlockType.flower, state: "flower", config: null }],
71 light: []
72 }, undefined, 0, 0);
73 assert.notEqual(data.blocks[0].state, "flower");
74 assert.ok(
75 ["red", "blue", "cyan", "violet", "yellow", "magenta", "white", "black", "pink"]
76 .includes(data.blocks[0].state)
77 );
78 const again = decodeChunkBlob({
79 open: true,
80 grounds: [],
81 blocks: [{ typeId: BlockType.flower, state: "flower", config: null }],
82 light: []
83 }, undefined, 0, 0);
84 assert.equal(again.blocks[0].state, data.blocks[0].state);
85 const coloured = decodeChunkBlob({
86 open: true,
87 grounds: [],
88 blocks: [{ typeId: BlockType.flower, state: "blue", config: null }],
89 light: []
90 }, undefined, 0, 0);
91 assert.equal(coloured.blocks[0].state, "blue");
92});
93
65test("old numeric grounds decode as default visual state", () =>
94test("old numeric grounds decode as default visual state", () =>
66{
95{
67 const data = decodeChunkBlob({
96 const data = decodeChunkBlob({
shared/appearance/hair.js added +296 −0
@@ -0,0 +1,296 @@
1 import { spriteImageName } from "../definitions/tileSprites.js";
2 import {
3 EQUIPMENT_SLOT,
4 EQUIPMENT_DRAW_ORDER,
5 itemDefinition,
6 itemEquipSprite
7 } from "../definitions/items.js";
8 import { normalizeRgb, resolveEquipTint } from "../render/tint.js";
9
10 /** Hair style ids per sex (PNG stems under `characters/player-body-*`). */
11 export const HAIR_STYLES_BY_SEX = Object.freeze({
12 male: Object.freeze(["hair-1", "hair-2", "hair-3", "hair-4"]),
13 female: Object.freeze(["hair-1", "hair-2", "hair-3"])
14 });
15
16 export const DEFAULT_HAIR_STYLE = "hair-1";
17 export const DEFAULT_HAIR_HUE = 30;
18 export const DEFAULT_HAIR_SATURATION = 0.55;
19 export const DEFAULT_HAIR_DARKNESS = 0.45;
20
21 /**
22 * Curated NPC hair tints (linear RGB 0–1). Seeded picks only — no random rainbow hues.
23 * Order is stable so name-hash indices stay consistent across builds.
24 */
25 export const NPC_HAIR_COLORS = Object.freeze([
26 Object.freeze({ r: 0.07, g: 0.05, b: 0.04 }), // near-black
27 Object.freeze({ r: 0.16, g: 0.10, b: 0.07 }), // dark brown
28 Object.freeze({ r: 0.28, g: 0.17, b: 0.10 }), // medium brown
29 Object.freeze({ r: 0.40, g: 0.26, b: 0.14 }), // light brown
30 Object.freeze({ r: 0.48, g: 0.24, b: 0.12 }), // chestnut
31 Object.freeze({ r: 0.55, g: 0.22, b: 0.10 }), // auburn
32 Object.freeze({ r: 0.62, g: 0.28, b: 0.12 }), // copper
33 Object.freeze({ r: 0.72, g: 0.32, b: 0.14 }), // ginger
34 Object.freeze({ r: 0.58, g: 0.42, b: 0.22 }), // dirty blonde
35 Object.freeze({ r: 0.72, g: 0.58, b: 0.32 }), // blonde
36 Object.freeze({ r: 0.82, g: 0.72, b: 0.48 }), // light blonde
37 Object.freeze({ r: 0.55, g: 0.52, b: 0.48 }), // ash / salt-and-pepper
38 Object.freeze({ r: 0.70, g: 0.70, b: 0.68 }), // silver-gray
39 Object.freeze({ r: 0.88, g: 0.86, b: 0.82 }) // white / pale gray
40 ]);
41
42 /** FNV-1a 32-bit — stable seed from display name. */
43 export function hashString (value)
44 {
45 const text = String(value ?? "");
46 let hash = 0x811c9dc5;
47 for (let i = 0; i < text.length; i++)
48 {
49 hash ^= text.charCodeAt(i);
50 hash = Math.imul(hash, 0x01000193);
51 }
52 return hash >>> 0;
53 }
54
55 /**
56 * Deterministic hair for NPCs: style + palette colour from name seed.
57 * @returns {{ style: string, color: { r: number, g: number, b: number }, sex: string }}
58 */
59 export function hairFromNameSeed (displayName, sex)
60 {
61 const resolvedSex = sex === "female" ? "female" : "male";
62 const seed = hashString(String(displayName ?? "").trim().toLowerCase() || "npc");
63 const styles = listHairStyles(resolvedSex);
64 const style = styles[seed % styles.length];
65 const color = normalizeRgb(NPC_HAIR_COLORS[(seed >>> 8) % NPC_HAIR_COLORS.length]);
66 return { style, color, sex: resolvedSex };
67 }
68
69 export function bodySpriteName (sex)
70 {
71 const key = sex === "female" ? "player-body-female" : "player-body-male";
72 return spriteImageName("character", key, key);
73 }
74
75 export function listHairStyles (sex)
76 {
77 return HAIR_STYLES_BY_SEX[sex === "female" ? "female" : "male"] ?? HAIR_STYLES_BY_SEX.male;
78 }
79
80 export function isValidHairStyle (sex, styleId)
81 {
82 if (styleId == null || styleId === "" || styleId === "none")
83 { return true; }
84 return listHairStyles(sex).includes(String(styleId));
85 }
86
87 export function normalizeHairStyle (sex, styleId)
88 {
89 if (styleId == null || styleId === "" || styleId === "none")
90 { return null; }
91 const id = String(styleId);
92 return listHairStyles(sex).includes(id) ? id : DEFAULT_HAIR_STYLE;
93 }
94
95 export function clamp01 (value)
96 {
97 const n = Number(value);
98 if (!Number.isFinite(n))
99 { return 0; }
100 return Math.min(1, Math.max(0, n));
101 }
102
103 export function normalizeHairSliders ({ hue, saturation, darkness } = {})
104 {
105 let h = Number(hue);
106 if (!Number.isFinite(h))
107 { h = DEFAULT_HAIR_HUE; }
108 h = ((h % 360) + 360) % 360;
109 return {
110 hue: h,
111 saturation: clamp01(saturation ?? DEFAULT_HAIR_SATURATION),
112 darkness: clamp01(darkness ?? DEFAULT_HAIR_DARKNESS)
113 };
114 }
115
116 /** Convert hair sliders to RGB for magenta tint (darkness 1 → near-black). */
117 export function hairColorFromSliders (sliders)
118 {
119 const { hue, saturation, darkness } = normalizeHairSliders(sliders);
120 const lightness = clamp01(1 - darkness * 0.85);
121 return normalizeRgb(hslToRgb(hue, saturation, lightness));
122 }
123
124 export function hairSpriteName (sex, styleId)
125 {
126 const style = normalizeHairStyle(sex, styleId);
127 if (!style)
128 { return null; }
129 const bodyKey = sex === "female" ? "player-body-female" : "player-body-male";
130 return spriteImageName("character", bodyKey, style);
131 }
132
133 export function hairFromCharacterRow (row)
134 {
135 if (!row)
136 { return null; }
137 const sex = row.sex === "female" ? "female" : "male";
138 const style = normalizeHairStyle(sex, row.hair_style);
139 if (!style)
140 { return null; }
141 const sliders = normalizeHairSliders({
142 hue: row.hair_hue,
143 saturation: row.hair_saturation,
144 darkness: row.hair_darkness
145 });
146 return {
147 style,
148 ...sliders,
149 color: hairColorFromSliders(sliders)
150 };
151 }
152
153 export function appearanceHairFields (hair)
154 {
155 if (!hair?.style)
156 {
157 return {
158 hairStyle: null,
159 hairHue: DEFAULT_HAIR_HUE,
160 hairSaturation: DEFAULT_HAIR_SATURATION,
161 hairDarkness: DEFAULT_HAIR_DARKNESS,
162 hairColor: null
163 };
164 }
165 const sex = hair.sex === "female" ? "female" : "male";
166 const style = normalizeHairStyle(sex, hair.style);
167 const sliders = normalizeHairSliders(hair);
168 return {
169 hairStyle: style,
170 hairHue: sliders.hue,
171 hairSaturation: sliders.saturation,
172 hairDarkness: sliders.darkness,
173 hairColor: hair.color ?? hairColorFromSliders(sliders)
174 };
175 }
176
177 /** Headgear hides hair unless `equipment.keepHair` is set on the item def. */
178 export function headgearKeepsHair (wornHead)
179 {
180 if (!wornHead)
181 { return true; }
182 const def = itemDefinition(wornHead.itemId);
183 return !!def?.equipment?.keepHair;
184 }
185
186 export function shouldShowHair (appearance, equipmentSlots)
187 {
188 const style = appearance?.hairStyle ?? null;
189 if (!style)
190 { return false; }
191 const head = equipmentSlots?.[EQUIPMENT_SLOT.head] ?? null;
192 return headgearKeepsHair(head);
193 }
194
195 export function hairLayerFromAppearance (appearance)
196 {
197 const style = appearance?.hairStyle ?? null;
198 if (!style)
199 { return null; }
200 const sex = appearance?.sex === "female" ? "female" : "male";
201 const sprite = hairSpriteName(sex, style);
202 if (!sprite)
203 { return null; }
204 const color = appearance?.hairColor
205 ? normalizeRgb(appearance.hairColor)
206 : hairColorFromSliders({
207 hue: appearance?.hairHue,
208 saturation: appearance?.hairSaturation,
209 darkness: appearance?.hairDarkness
210 });
211 return { sprite, tint: color, hair: true };
212 }
213
214 /**
215 * Shared draw order: body → boots/legs/chest → hair (if visible) → head → offhand → weapon.
216 */
217 export function composeAppearanceLayers (appearance, equipmentSlots)
218 {
219 const sex = appearance?.sex === "female" ? "female" : "male";
220 const layers = [{ sprite: appearance?.sprite ?? bodySpriteName(sex) }];
221 const slots = equipmentSlots ?? {};
222 for (const slot of EQUIPMENT_DRAW_ORDER)
223 {
224 if (slot === EQUIPMENT_SLOT.head && shouldShowHair(appearance, slots))
225 {
226 const hair = hairLayerFromAppearance(appearance);
227 if (hair)
228 { layers.push(hair); }
229 }
230 const worn = slots[slot];
231 if (!worn)
232 { continue; }
233 const overlay = itemEquipSprite(worn.itemId);
234 if (!overlay)
235 { continue; }
236 const tint = resolveEquipTint(worn.itemId, worn.instance);
237 layers.push({
238 sprite: overlay,
239 itemId: worn.itemId,
240 ...(tint ? { tint } : {})
241 });
242 }
243 return layers;
244 }
245
246 /**
247 * Preview layers for creation/barber UI.
248 * @param {{ hideHeadgear?: boolean }} [options]
249 */
250 export function layersForHairPreview (sex, bag, hair, { hideHeadgear = true } = {})
251 {
252 const slots = { ...(bag?.equipment?.slots ?? {}) };
253 if (hideHeadgear)
254 { slots[EQUIPMENT_SLOT.head] = null; }
255 const style = normalizeHairStyle(sex, hair?.style);
256 const appearance = {
257 sex,
258 sprite: bodySpriteName(sex),
259 ...appearanceHairFields(style ? { ...hair, style, sex } : null)
260 };
261 if (style)
262 { appearance.hairStyle = style; }
263 return composeAppearanceLayers(appearance, slots);
264 }
265
266 function hslToRgb (h, s, l)
267 {
268 const hue = ((h % 360) + 360) % 360 / 360;
269 const sat = clamp01(s);
270 const light = clamp01(l);
271 if (sat === 0)
272 { return { r: light, g: light, b: light }; }
273 const q = light < 0.5 ? light * (1 + sat) : light + sat - light * sat;
274 const p = 2 * light - q;
275 return {
276 r: hueToChannel(p, q, hue + 1 / 3),
277 g: hueToChannel(p, q, hue),
278 b: hueToChannel(p, q, hue - 1 / 3)
279 };
280 }
281
282 function hueToChannel (p, q, t)
283 {
284 let tt = t;
285 if (tt < 0)
286 { tt += 1; }
287 if (tt > 1)
288 { tt -= 1; }
289 if (tt < 1 / 6)
290 { return p + (q - p) * 6 * tt; }
291 if (tt < 1 / 2)
292 { return q; }
293 if (tt < 2 / 3)
294 { return p + (q - p) * (2 / 3 - tt) * 6; }
295 return p;
296 }
@@ -0,0 +1,296 @@
1import { spriteImageName } from "../definitions/tileSprites.js";
2import {
3 EQUIPMENT_SLOT,
4 EQUIPMENT_DRAW_ORDER,
5 itemDefinition,
6 itemEquipSprite
7} from "../definitions/items.js";
8import { normalizeRgb, resolveEquipTint } from "../render/tint.js";
9
10/** Hair style ids per sex (PNG stems under `characters/player-body-*`). */
11export const HAIR_STYLES_BY_SEX = Object.freeze({
12 male: Object.freeze(["hair-1", "hair-2", "hair-3", "hair-4"]),
13 female: Object.freeze(["hair-1", "hair-2", "hair-3"])
14});
15
16export const DEFAULT_HAIR_STYLE = "hair-1";
17export const DEFAULT_HAIR_HUE = 30;
18export const DEFAULT_HAIR_SATURATION = 0.55;
19export const DEFAULT_HAIR_DARKNESS = 0.45;
20
21/**
22 * Curated NPC hair tints (linear RGB 0–1). Seeded picks only — no random rainbow hues.
23 * Order is stable so name-hash indices stay consistent across builds.
24 */
25export const NPC_HAIR_COLORS = Object.freeze([
26 Object.freeze({ r: 0.07, g: 0.05, b: 0.04 }), // near-black
27 Object.freeze({ r: 0.16, g: 0.10, b: 0.07 }), // dark brown
28 Object.freeze({ r: 0.28, g: 0.17, b: 0.10 }), // medium brown
29 Object.freeze({ r: 0.40, g: 0.26, b: 0.14 }), // light brown
30 Object.freeze({ r: 0.48, g: 0.24, b: 0.12 }), // chestnut
31 Object.freeze({ r: 0.55, g: 0.22, b: 0.10 }), // auburn
32 Object.freeze({ r: 0.62, g: 0.28, b: 0.12 }), // copper
33 Object.freeze({ r: 0.72, g: 0.32, b: 0.14 }), // ginger
34 Object.freeze({ r: 0.58, g: 0.42, b: 0.22 }), // dirty blonde
35 Object.freeze({ r: 0.72, g: 0.58, b: 0.32 }), // blonde
36 Object.freeze({ r: 0.82, g: 0.72, b: 0.48 }), // light blonde
37 Object.freeze({ r: 0.55, g: 0.52, b: 0.48 }), // ash / salt-and-pepper
38 Object.freeze({ r: 0.70, g: 0.70, b: 0.68 }), // silver-gray
39 Object.freeze({ r: 0.88, g: 0.86, b: 0.82 }) // white / pale gray
40]);
41
42/** FNV-1a 32-bit — stable seed from display name. */
43export function hashString (value)
44{
45 const text = String(value ?? "");
46 let hash = 0x811c9dc5;
47 for (let i = 0; i < text.length; i++)
48 {
49 hash ^= text.charCodeAt(i);
50 hash = Math.imul(hash, 0x01000193);
51 }
52 return hash >>> 0;
53}
54
55/**
56 * Deterministic hair for NPCs: style + palette colour from name seed.
57 * @returns {{ style: string, color: { r: number, g: number, b: number }, sex: string }}
58 */
59export function hairFromNameSeed (displayName, sex)
60{
61 const resolvedSex = sex === "female" ? "female" : "male";
62 const seed = hashString(String(displayName ?? "").trim().toLowerCase() || "npc");
63 const styles = listHairStyles(resolvedSex);
64 const style = styles[seed % styles.length];
65 const color = normalizeRgb(NPC_HAIR_COLORS[(seed >>> 8) % NPC_HAIR_COLORS.length]);
66 return { style, color, sex: resolvedSex };
67}
68
69export function bodySpriteName (sex)
70{
71 const key = sex === "female" ? "player-body-female" : "player-body-male";
72 return spriteImageName("character", key, key);
73}
74
75export function listHairStyles (sex)
76{
77 return HAIR_STYLES_BY_SEX[sex === "female" ? "female" : "male"] ?? HAIR_STYLES_BY_SEX.male;
78}
79
80export function isValidHairStyle (sex, styleId)
81{
82 if (styleId == null || styleId === "" || styleId === "none")
83 { return true; }
84 return listHairStyles(sex).includes(String(styleId));
85}
86
87export function normalizeHairStyle (sex, styleId)
88{
89 if (styleId == null || styleId === "" || styleId === "none")
90 { return null; }
91 const id = String(styleId);
92 return listHairStyles(sex).includes(id) ? id : DEFAULT_HAIR_STYLE;
93}
94
95export function clamp01 (value)
96{
97 const n = Number(value);
98 if (!Number.isFinite(n))
99 { return 0; }
100 return Math.min(1, Math.max(0, n));
101}
102
103export function normalizeHairSliders ({ hue, saturation, darkness } = {})
104{
105 let h = Number(hue);
106 if (!Number.isFinite(h))
107 { h = DEFAULT_HAIR_HUE; }
108 h = ((h % 360) + 360) % 360;
109 return {
110 hue: h,
111 saturation: clamp01(saturation ?? DEFAULT_HAIR_SATURATION),
112 darkness: clamp01(darkness ?? DEFAULT_HAIR_DARKNESS)
113 };
114}
115
116/** Convert hair sliders to RGB for magenta tint (darkness 1 → near-black). */
117export function hairColorFromSliders (sliders)
118{
119 const { hue, saturation, darkness } = normalizeHairSliders(sliders);
120 const lightness = clamp01(1 - darkness * 0.85);
121 return normalizeRgb(hslToRgb(hue, saturation, lightness));
122}
123
124export function hairSpriteName (sex, styleId)
125{
126 const style = normalizeHairStyle(sex, styleId);
127 if (!style)
128 { return null; }
129 const bodyKey = sex === "female" ? "player-body-female" : "player-body-male";
130 return spriteImageName("character", bodyKey, style);
131}
132
133export function hairFromCharacterRow (row)
134{
135 if (!row)
136 { return null; }
137 const sex = row.sex === "female" ? "female" : "male";
138 const style = normalizeHairStyle(sex, row.hair_style);
139 if (!style)
140 { return null; }
141 const sliders = normalizeHairSliders({
142 hue: row.hair_hue,
143 saturation: row.hair_saturation,
144 darkness: row.hair_darkness
145 });
146 return {
147 style,
148 ...sliders,
149 color: hairColorFromSliders(sliders)
150 };
151}
152
153export function appearanceHairFields (hair)
154{
155 if (!hair?.style)
156 {
157 return {
158 hairStyle: null,
159 hairHue: DEFAULT_HAIR_HUE,
160 hairSaturation: DEFAULT_HAIR_SATURATION,
161 hairDarkness: DEFAULT_HAIR_DARKNESS,
162 hairColor: null
163 };
164 }
165 const sex = hair.sex === "female" ? "female" : "male";
166 const style = normalizeHairStyle(sex, hair.style);
167 const sliders = normalizeHairSliders(hair);
168 return {
169 hairStyle: style,
170 hairHue: sliders.hue,
171 hairSaturation: sliders.saturation,
172 hairDarkness: sliders.darkness,
173 hairColor: hair.color ?? hairColorFromSliders(sliders)
174 };
175}
176
177/** Headgear hides hair unless `equipment.keepHair` is set on the item def. */
178export function headgearKeepsHair (wornHead)
179{
180 if (!wornHead)
181 { return true; }
182 const def = itemDefinition(wornHead.itemId);
183 return !!def?.equipment?.keepHair;
184}
185
186export function shouldShowHair (appearance, equipmentSlots)
187{
188 const style = appearance?.hairStyle ?? null;
189 if (!style)
190 { return false; }
191 const head = equipmentSlots?.[EQUIPMENT_SLOT.head] ?? null;
192 return headgearKeepsHair(head);
193}
194
195export function hairLayerFromAppearance (appearance)
196{
197 const style = appearance?.hairStyle ?? null;
198 if (!style)
199 { return null; }
200 const sex = appearance?.sex === "female" ? "female" : "male";
201 const sprite = hairSpriteName(sex, style);
202 if (!sprite)
203 { return null; }
204 const color = appearance?.hairColor
205 ? normalizeRgb(appearance.hairColor)
206 : hairColorFromSliders({
207 hue: appearance?.hairHue,
208 saturation: appearance?.hairSaturation,
209 darkness: appearance?.hairDarkness
210 });
211 return { sprite, tint: color, hair: true };
212}
213
214/**
215 * Shared draw order: body → boots/legs/chest → hair (if visible) → head → offhand → weapon.
216 */
217export function composeAppearanceLayers (appearance, equipmentSlots)
218{
219 const sex = appearance?.sex === "female" ? "female" : "male";
220 const layers = [{ sprite: appearance?.sprite ?? bodySpriteName(sex) }];
221 const slots = equipmentSlots ?? {};
222 for (const slot of EQUIPMENT_DRAW_ORDER)
223 {
224 if (slot === EQUIPMENT_SLOT.head && shouldShowHair(appearance, slots))
225 {
226 const hair = hairLayerFromAppearance(appearance);
227 if (hair)
228 { layers.push(hair); }
229 }
230 const worn = slots[slot];
231 if (!worn)
232 { continue; }
233 const overlay = itemEquipSprite(worn.itemId);
234 if (!overlay)
235 { continue; }
236 const tint = resolveEquipTint(worn.itemId, worn.instance);
237 layers.push({
238 sprite: overlay,
239 itemId: worn.itemId,
240 ...(tint ? { tint } : {})
241 });
242 }
243 return layers;
244}
245
246/**
247 * Preview layers for creation/barber UI.
248 * @param {{ hideHeadgear?: boolean }} [options]
249 */
250export function layersForHairPreview (sex, bag, hair, { hideHeadgear = true } = {})
251{
252 const slots = { ...(bag?.equipment?.slots ?? {}) };
253 if (hideHeadgear)
254 { slots[EQUIPMENT_SLOT.head] = null; }
255 const style = normalizeHairStyle(sex, hair?.style);
256 const appearance = {
257 sex,
258 sprite: bodySpriteName(sex),
259 ...appearanceHairFields(style ? { ...hair, style, sex } : null)
260 };
261 if (style)
262 { appearance.hairStyle = style; }
263 return composeAppearanceLayers(appearance, slots);
264}
265
266function hslToRgb (h, s, l)
267{
268 const hue = ((h % 360) + 360) % 360 / 360;
269 const sat = clamp01(s);
270 const light = clamp01(l);
271 if (sat === 0)
272 { return { r: light, g: light, b: light }; }
273 const q = light < 0.5 ? light * (1 + sat) : light + sat - light * sat;
274 const p = 2 * light - q;
275 return {
276 r: hueToChannel(p, q, hue + 1 / 3),
277 g: hueToChannel(p, q, hue),
278 b: hueToChannel(p, q, hue - 1 / 3)
279 };
280}
281
282function hueToChannel (p, q, t)
283{
284 let tt = t;
285 if (tt < 0)
286 { tt += 1; }
287 if (tt > 1)
288 { tt -= 1; }
289 if (tt < 1 / 6)
290 { return p + (q - p) * 6 * tt; }
291 if (tt < 1 / 2)
292 { return q; }
293 if (tt < 2 / 3)
294 { return p + (q - p) * (2 / 3 - tt) * 6; }
295 return p;
296}
shared/appearance/layers.js +14 −26
@@ -1,30 +1,18 @@
1 import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../definitions/items.js";
2 import { resolveEquipTint } from "../render/tint.js";
1 import { composeAppearanceLayers, bodySpriteName } from "./hair.js";
3 2
4 export function bodySpriteName (sex)
5 {
6 return sex === "female" ? "player-body-female" : "player-body-male";
7 }
3 export { bodySpriteName } from "./hair.js";
8 4
9 /** Build public draw layers from sex + bag equipment (no ECS). */
10 export function layersFromBag (sex, bag)
5 /** Build public draw layers from sex + bag equipment + hair (no ECS). */
6 export function layersFromBag (sex, bag, hair = null)
11 7 {
12 const layers = [{ sprite: bodySpriteName(sex) }];
13 const slots = bag?.equipment?.slots ?? {};
14 for (const slot of EQUIPMENT_DRAW_ORDER)
15 {
16 const worn = slots[slot];
17 if (!worn)
18 { continue; }
19 const overlay = itemEquipSprite(worn.itemId);
20 if (!overlay)
21 { continue; }
22 const tint = resolveEquipTint(worn.itemId, worn.instance);
23 layers.push({
24 sprite: overlay,
25 itemId: worn.itemId,
26 ...(tint ? { tint } : {})
27 });
28 }
29 return layers;
8 const appearance = {
9 sex,
10 sprite: bodySpriteName(sex),
11 hairStyle: hair?.style ?? null,
12 hairHue: hair?.hue,
13 hairSaturation: hair?.saturation,
14 hairDarkness: hair?.darkness,
15 hairColor: hair?.color ?? null
16 };
17 return composeAppearanceLayers(appearance, bag?.equipment?.slots ?? {});
30 18 }
@@ -1,30 +1,18 @@
1import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../definitions/items.js";
1import { composeAppearanceLayers, bodySpriteName } from "./hair.js";
2import { resolveEquipTint } from "../render/tint.js";
3
2
4export function bodySpriteName (sex)
3export { bodySpriteName } from "./hair.js";
5{
6 return sex === "female" ? "player-body-female" : "player-body-male";
7}
8
4
9/** Build public draw layers from sex + bag equipment (no ECS). */
5/** Build public draw layers from sex + bag equipment + hair (no ECS). */
10export function layersFromBag (sex, bag)
6export function layersFromBag (sex, bag, hair = null)
11{
7{
12 const layers = [{ sprite: bodySpriteName(sex) }];
8 const appearance = {
13 const slots = bag?.equipment?.slots ?? {};
9 sex,
14 for (const slot of EQUIPMENT_DRAW_ORDER)
10 sprite: bodySpriteName(sex),
15 {
11 hairStyle: hair?.style ?? null,
16 const worn = slots[slot];
12 hairHue: hair?.hue,
17 if (!worn)
13 hairSaturation: hair?.saturation,
18 { continue; }
14 hairDarkness: hair?.darkness,
19 const overlay = itemEquipSprite(worn.itemId);
15 hairColor: hair?.color ?? null
20 if (!overlay)
16 };
21 { continue; }
17 return composeAppearanceLayers(appearance, bag?.equipment?.slots ?? {});
22 const tint = resolveEquipTint(worn.itemId, worn.instance);
23 layers.push({
24 sprite: overlay,
25 itemId: worn.itemId,
26 ...(tint ? { tint } : {})
27 });
28 }
29 return layers;
30}
18}
shared/bounty/pricing.js added +26 −0
@@ -0,0 +1,26 @@
1 import { formatQuantity } from "../definitions/items.js";
2
3 /** @param {number} copper */
4 export function formatBountyCopper (copper)
5 {
6 const amount = Math.max(0, Math.floor(Number(copper) || 0));
7 return formatQuantity(amount);
8 }
9
10 /**
11 * @param {{ killerName: string, victimName: string, amountCopper: number }} opts
12 */
13 export function bountyPayoutLetterBody ({ killerName, victimName, amountCopper })
14 {
15 const killer = String(killerName ?? "Adventurer").trim() || "Adventurer";
16 const victim = String(victimName ?? "someone").trim() || "someone";
17 const amount = formatBountyCopper(amountCopper);
18 return [
19 `Dear ${killer},`,
20 "",
21 `For defeating ${victim}, a bounty of ${amount} has been paid into your bank vault.`,
22 "",
23 "Signed,",
24 "Bounty Office"
25 ].join("\n");
26 }
@@ -0,0 +1,26 @@
1import { formatQuantity } from "../definitions/items.js";
2
3/** @param {number} copper */
4export function formatBountyCopper (copper)
5{
6 const amount = Math.max(0, Math.floor(Number(copper) || 0));
7 return formatQuantity(amount);
8}
9
10/**
11 * @param {{ killerName: string, victimName: string, amountCopper: number }} opts
12 */
13export function bountyPayoutLetterBody ({ killerName, victimName, amountCopper })
14{
15 const killer = String(killerName ?? "Adventurer").trim() || "Adventurer";
16 const victim = String(victimName ?? "someone").trim() || "someone";
17 const amount = formatBountyCopper(amountCopper);
18 return [
19 `Dear ${killer},`,
20 "",
21 `For defeating ${victim}, a bounty of ${amount} has been paid into your bank vault.`,
22 "",
23 "Signed,",
24 "Bounty Office"
25 ].join("\n");
26}
shared/definitions/alchemy.js +123 −14
@@ -28,38 +28,147 @@ export const CAULDRON_EMPTY_FLAVOR = "The cauldron is empty";
28 28 /**
29 29 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
30 30 * A potion may never use more than 4 unique ingredients (ratio units).
31 * Step `insert` is once per ingredient addition; quantity lives in `ingredients`.
31 32 */
32 33 export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
33 greenDraught: Object.freeze({
34 potionKey: "greenDraught",
35 displayName: "Green draught",
34 lesserHealthTonic: Object.freeze({
35 potionKey: "lesserHealthTonic",
36 displayName: "Lesser health tonic",
36 37 minAlchemyLevel: 1,
37 color: Object.freeze({ r: 0.25, g: 0.72, b: 0.35 }),
38 color: Object.freeze({ r: 0.35, g: 0.78, b: 0.42 }),
38 39 fillLevel: 4,
39 40 ingredients: Object.freeze([
40 Object.freeze({ key: "green-herb", quantity: 2 }),
41 Object.freeze({ key: "apple", quantity: 1 })
41 Object.freeze({ key: "thyme", quantity: 1 }),
42 Object.freeze({ key: "mint", quantity: 1 })
42 43 ]),
43 44 steps: Object.freeze([
44 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "green-herb" }),
45 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "thyme" }),
46 Object.freeze({ kind: AlchemyStepKind.heat }),
47 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "mint" }),
48 Object.freeze({ kind: AlchemyStepKind.stir })
49 ]),
50 effect: Object.freeze({
51 type: "health-regen",
52 amountPerSecond: 1,
53 durationMs: 10_000
54 })
55 }),
56 lesserHasteDraught: Object.freeze({
57 potionKey: "lesserHasteDraught",
58 displayName: "Lesser haste draught",
59 minAlchemyLevel: 1,
60 color: Object.freeze({ r: 0.45, g: 0.85, b: 0.75 }),
61 fillLevel: 4,
62 ingredients: Object.freeze([
63 Object.freeze({ key: "mint", quantity: 2 }),
64 Object.freeze({ key: "lavender", quantity: 1 })
65 ]),
66 steps: Object.freeze([
67 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "mint" }),
45 68 Object.freeze({ kind: AlchemyStepKind.heat }),
46 69 Object.freeze({ kind: AlchemyStepKind.stir }),
47 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "apple" }),
70 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "lavender" }),
48 71 Object.freeze({ kind: AlchemyStepKind.cool })
49 72 ]),
50 effect: Object.freeze({ type: "heal", amount: 5 })
73 effect: Object.freeze({
74 type: "stamina-regen",
75 amountPerSecond: 1,
76 durationMs: 10_000
77 })
78 }),
79 strengthPotion: Object.freeze({
80 potionKey: "strengthPotion",
81 displayName: "Strength potion",
82 minAlchemyLevel: 1,
83 color: Object.freeze({ r: 0.82, g: 0.32, b: 0.18 }),
84 fillLevel: 4,
85 ingredients: Object.freeze([
86 Object.freeze({ key: "thyme", quantity: 3 }),
87 Object.freeze({ key: "nettle", quantity: 2 })
88 ]),
89 steps: Object.freeze([
90 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "thyme" }),
91 Object.freeze({ kind: AlchemyStepKind.stir }),
92 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "nettle" }),
93 Object.freeze({ kind: AlchemyStepKind.heat })
94 ]),
95 effect: Object.freeze({
96 type: "strength-bonus",
97 amount: 5,
98 durationMs: 60_000
99 })
100 }),
101 clarityPotion: Object.freeze({
102 potionKey: "clarityPotion",
103 displayName: "Clarity potion",
104 minAlchemyLevel: 1,
105 color: Object.freeze({ r: 0.55, g: 0.45, b: 0.92 }),
106 fillLevel: 4,
107 ingredients: Object.freeze([
108 Object.freeze({ key: "rosemary", quantity: 1 }),
109 Object.freeze({ key: "chamomile", quantity: 2 })
110 ]),
111 steps: Object.freeze([
112 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "rosemary" }),
113 Object.freeze({ kind: AlchemyStepKind.cool }),
114 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "chamomile" }),
115 Object.freeze({ kind: AlchemyStepKind.stir })
116 ]),
117 effect: Object.freeze({
118 type: "mind-bonus",
119 amount: 5,
120 durationMs: 60_000
121 })
51 122 })
52 123 });
53 124
54 125 /**
55 126 * Failure (unstable) potions chosen by hashing the step transcript.
56 * Effects are stubs for later systems.
57 127 */
58 128 export const UNSTABLE_POTION_EFFECTS = Object.freeze([
59 Object.freeze({ effectKey: "slow", displayName: "Unstable draught (sluggish)", color: { r: 0.45, g: 0.35, b: 0.55 }, fillLevel: 3, effect: { type: "slow", durationMs: 60_000 } }),
60 Object.freeze({ effectKey: "harm", displayName: "Unstable draught (bitter)", color: { r: 0.7, g: 0.2, b: 0.15 }, fillLevel: 2, effect: { type: "damage", amount: 4 } }),
61 Object.freeze({ effectKey: "blind", displayName: "Unstable draught (murky)", color: { r: 0.15, g: 0.15, b: 0.2 }, fillLevel: 3, effect: { type: "blind", durationMs: 30_000 } }),
62 Object.freeze({ effectKey: "queasy", displayName: "Unstable draught (queasy)", color: { r: 0.55, g: 0.65, b: 0.2 }, fillLevel: 2, effect: { type: "queasy", durationMs: 45_000 } })
129 Object.freeze({
130 effectKey: "stamina-drain",
131 displayName: "Unstable draught (leeching)",
132 color: { r: 0.55, g: 0.2, b: 0.35 },
133 fillLevel: 3,
134 effect: Object.freeze({
135 type: "stamina-drain",
136 amountPerSecond: 1,
137 durationMs: 15_000
138 })
139 }),
140 Object.freeze({
141 effectKey: "glow",
142 displayName: "Unstable draught (glowing)",
143 color: { r: 0.95, g: 0.9, b: 0.45 },
144 fillLevel: 3,
145 effect: Object.freeze({
146 type: "glow",
147 lightRadiusTiles: 2,
148 durationMs: 10_000
149 })
150 }),
151 Object.freeze({
152 effectKey: "shrink",
153 displayName: "Unstable draught (diminishing)",
154 color: { r: 0.7, g: 0.55, b: 0.85 },
155 fillLevel: 2,
156 effect: Object.freeze({
157 type: "shrink",
158 scale: 0.5,
159 durationMs: 30_000
160 })
161 }),
162 Object.freeze({
163 effectKey: "blind",
164 displayName: "Unstable draught (murky)",
165 color: { r: 0.12, g: 0.12, b: 0.16 },
166 fillLevel: 3,
167 effect: Object.freeze({
168 type: "blind",
169 durationMs: 20_000
170 })
171 })
63 172 ]);
64 173
65 174 export function alchemyPotionDefinition (potionKey)
@@ -28,38 +28,147 @@ export const CAULDRON_EMPTY_FLAVOR = "The cauldron is empty";
28/**
28/**
29 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
29 * Known successful potions. Ingredient `key` matches item def keys (resolved to itemId at runtime).
30 * A potion may never use more than 4 unique ingredients (ratio units).
30 * A potion may never use more than 4 unique ingredients (ratio units).
31 * Step `insert` is once per ingredient addition; quantity lives in `ingredients`.
31 */
32 */
32export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
33export const ALCHEMY_POTION_DEFINITIONS = Object.freeze({
33 greenDraught: Object.freeze({
34 lesserHealthTonic: Object.freeze({
34 potionKey: "greenDraught",
35 potionKey: "lesserHealthTonic",
35 displayName: "Green draught",
36 displayName: "Lesser health tonic",
36 minAlchemyLevel: 1,
37 minAlchemyLevel: 1,
37 color: Object.freeze({ r: 0.25, g: 0.72, b: 0.35 }),
38 color: Object.freeze({ r: 0.35, g: 0.78, b: 0.42 }),
38 fillLevel: 4,
39 fillLevel: 4,
39 ingredients: Object.freeze([
40 ingredients: Object.freeze([
40 Object.freeze({ key: "green-herb", quantity: 2 }),
41 Object.freeze({ key: "thyme", quantity: 1 }),
41 Object.freeze({ key: "apple", quantity: 1 })
42 Object.freeze({ key: "mint", quantity: 1 })
42 ]),
43 ]),
43 steps: Object.freeze([
44 steps: Object.freeze([
44 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "green-herb" }),
45 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "thyme" }),
46 Object.freeze({ kind: AlchemyStepKind.heat }),
47 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "mint" }),
48 Object.freeze({ kind: AlchemyStepKind.stir })
49 ]),
50 effect: Object.freeze({
51 type: "health-regen",
52 amountPerSecond: 1,
53 durationMs: 10_000
54 })
55 }),
56 lesserHasteDraught: Object.freeze({
57 potionKey: "lesserHasteDraught",
58 displayName: "Lesser haste draught",
59 minAlchemyLevel: 1,
60 color: Object.freeze({ r: 0.45, g: 0.85, b: 0.75 }),
61 fillLevel: 4,
62 ingredients: Object.freeze([
63 Object.freeze({ key: "mint", quantity: 2 }),
64 Object.freeze({ key: "lavender", quantity: 1 })
65 ]),
66 steps: Object.freeze([
67 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "mint" }),
45 Object.freeze({ kind: AlchemyStepKind.heat }),
68 Object.freeze({ kind: AlchemyStepKind.heat }),
46 Object.freeze({ kind: AlchemyStepKind.stir }),
69 Object.freeze({ kind: AlchemyStepKind.stir }),
47 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "apple" }),
70 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "lavender" }),
48 Object.freeze({ kind: AlchemyStepKind.cool })
71 Object.freeze({ kind: AlchemyStepKind.cool })
49 ]),
72 ]),
50 effect: Object.freeze({ type: "heal", amount: 5 })
73 effect: Object.freeze({
74 type: "stamina-regen",
75 amountPerSecond: 1,
76 durationMs: 10_000
77 })
78 }),
79 strengthPotion: Object.freeze({
80 potionKey: "strengthPotion",
81 displayName: "Strength potion",
82 minAlchemyLevel: 1,
83 color: Object.freeze({ r: 0.82, g: 0.32, b: 0.18 }),
84 fillLevel: 4,
85 ingredients: Object.freeze([
86 Object.freeze({ key: "thyme", quantity: 3 }),
87 Object.freeze({ key: "nettle", quantity: 2 })
88 ]),
89 steps: Object.freeze([
90 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "thyme" }),
91 Object.freeze({ kind: AlchemyStepKind.stir }),
92 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "nettle" }),
93 Object.freeze({ kind: AlchemyStepKind.heat })
94 ]),
95 effect: Object.freeze({
96 type: "strength-bonus",
97 amount: 5,
98 durationMs: 60_000
99 })
100 }),
101 clarityPotion: Object.freeze({
102 potionKey: "clarityPotion",
103 displayName: "Clarity potion",
104 minAlchemyLevel: 1,
105 color: Object.freeze({ r: 0.55, g: 0.45, b: 0.92 }),
106 fillLevel: 4,
107 ingredients: Object.freeze([
108 Object.freeze({ key: "rosemary", quantity: 1 }),
109 Object.freeze({ key: "chamomile", quantity: 2 })
110 ]),
111 steps: Object.freeze([
112 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "rosemary" }),
113 Object.freeze({ kind: AlchemyStepKind.cool }),
114 Object.freeze({ kind: AlchemyStepKind.insert, itemKey: "chamomile" }),
115 Object.freeze({ kind: AlchemyStepKind.stir })
116 ]),
117 effect: Object.freeze({
118 type: "mind-bonus",
119 amount: 5,
120 durationMs: 60_000
121 })
51 })
122 })
52});
123});
53
124
54/**
125/**
55 * Failure (unstable) potions chosen by hashing the step transcript.
126 * Failure (unstable) potions chosen by hashing the step transcript.
56 * Effects are stubs for later systems.
57 */
127 */
58export const UNSTABLE_POTION_EFFECTS = Object.freeze([
128export const UNSTABLE_POTION_EFFECTS = Object.freeze([
59 Object.freeze({ effectKey: "slow", displayName: "Unstable draught (sluggish)", color: { r: 0.45, g: 0.35, b: 0.55 }, fillLevel: 3, effect: { type: "slow", durationMs: 60_000 } }),
129 Object.freeze({
60 Object.freeze({ effectKey: "harm", displayName: "Unstable draught (bitter)", color: { r: 0.7, g: 0.2, b: 0.15 }, fillLevel: 2, effect: { type: "damage", amount: 4 } }),
130 effectKey: "stamina-drain",
61 Object.freeze({ effectKey: "blind", displayName: "Unstable draught (murky)", color: { r: 0.15, g: 0.15, b: 0.2 }, fillLevel: 3, effect: { type: "blind", durationMs: 30_000 } }),
131 displayName: "Unstable draught (leeching)",
62 Object.freeze({ effectKey: "queasy", displayName: "Unstable draught (queasy)", color: { r: 0.55, g: 0.65, b: 0.2 }, fillLevel: 2, effect: { type: "queasy", durationMs: 45_000 } })
132 color: { r: 0.55, g: 0.2, b: 0.35 },
133 fillLevel: 3,
134 effect: Object.freeze({
135 type: "stamina-drain",
136 amountPerSecond: 1,
137 durationMs: 15_000
138 })
139 }),
140 Object.freeze({
141 effectKey: "glow",
142 displayName: "Unstable draught (glowing)",
143 color: { r: 0.95, g: 0.9, b: 0.45 },
144 fillLevel: 3,
145 effect: Object.freeze({
146 type: "glow",
147 lightRadiusTiles: 2,
148 durationMs: 10_000
149 })
150 }),
151 Object.freeze({
152 effectKey: "shrink",
153 displayName: "Unstable draught (diminishing)",
154 color: { r: 0.7, g: 0.55, b: 0.85 },
155 fillLevel: 2,
156 effect: Object.freeze({
157 type: "shrink",
158 scale: 0.5,
159 durationMs: 30_000
160 })
161 }),
162 Object.freeze({
163 effectKey: "blind",
164 displayName: "Unstable draught (murky)",
165 color: { r: 0.12, g: 0.12, b: 0.16 },
166 fillLevel: 3,
167 effect: Object.freeze({
168 type: "blind",
169 durationMs: 20_000
170 })
171 })
63]);
172]);
64
173
65export function alchemyPotionDefinition (potionKey)
174export function alchemyPotionDefinition (potionKey)
shared/definitions/dyes.js +9 −0
@@ -69,6 +69,15 @@ export function randomFlowerColorId (rng = Math.random)
69 69 return FLOWER_COLOR_ORDER[index];
70 70 }
71 71
72 /** Stable colour from world tile coords (legacy / uncoloured flower nodes). */
73 export function flowerColorIdForTile (tileX, tileY)
74 {
75 const x = tileX | 0;
76 const y = tileY | 0;
77 const hash = Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(x ^ y, 83492791);
78 return FLOWER_COLOR_ORDER[(hash >>> 0) % FLOWER_COLOR_ORDER.length];
79 }
80
72 81 /** Block visual state for a flower colour (catalog tint alias). */
73 82 export function flowerBlockState (colorId)
74 83 {
@@ -69,6 +69,15 @@ export function randomFlowerColorId (rng = Math.random)
69 return FLOWER_COLOR_ORDER[index];
69 return FLOWER_COLOR_ORDER[index];
70}
70}
71
71
72/** Stable colour from world tile coords (legacy / uncoloured flower nodes). */
73export function flowerColorIdForTile (tileX, tileY)
74{
75 const x = tileX | 0;
76 const y = tileY | 0;
77 const hash = Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(x ^ y, 83492791);
78 return FLOWER_COLOR_ORDER[(hash >>> 0) % FLOWER_COLOR_ORDER.length];
79}
80
72/** Block visual state for a flower colour (catalog tint alias). */
81/** Block visual state for a flower colour (catalog tint alias). */
73export function flowerBlockState (colorId)
82export function flowerBlockState (colorId)
74{
83{
shared/definitions/gathering.js +31 −4
@@ -23,6 +23,7 @@ import {
23 23 materialFromOreBoulderState,
24 24 isOreBoulderState
25 25 } from "./materialTiers.js";
26 import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
26 27
27 28 export {
28 29 ORE_BEARING_MATERIALS,
@@ -228,18 +229,44 @@ export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills,
228 229 return { ok: true, tool: tools[0] };
229 230 }
230 231
231 /** Herbalism gather duration. Flowers are quick (~1s); cotton a bit longer. */
232 export function herbalismDurationMs (plantKind = null, toolTier = null)
232 /**
233 * Skill gate for folklore herb nodes (`BlockType.herbPlant`, state = herbId).
234 * @returns {{ ok: true, herb: object } | { ok: false, reason: string }}
235 */
236 export function resolveHerbGather ({ herbId, skills })
237 {
238 const herb = herbDefinition(herbId);
239 if (!herb)
240 { return { ok: false, reason: "There is nothing to pick there." }; }
241 const need = herbGatherSkillLevel(herb.tier);
242 const level = skillLevel(skills, SkillId.herbalism);
243 if (level < need)
244 { return { ok: false, reason: `Requires Herbalism ${need}.` }; }
245 return { ok: true, herb };
246 }
247
248 /** Herbalism gather duration. Flowers are quick (~1s); cotton a bit longer; clipper herbs mid. */
249 export function herbalismDurationMs (plantKind = null, toolTier = null, herbTier = null)
233 250 {
234 251 if (plantKind === "flower")
235 252 { return 1000; }
253 if (plantKind === "herb")
254 {
255 const tier = Math.max(1, herbTier | 0 || 1);
256 const rank = toolTier ? tierRank(toolTier) : 1;
257 return Math.max(800, 1600 + tier * 250 - (rank - 1) * 150);
258 }
236 259 const rank = toolTier ? tierRank(toolTier) : 1;
237 260 return Math.max(500, 2500 - (rank - 1) * 250);
238 261 }
239 262
240 export function herbalismXpForPick (kind)
263 export function herbalismXpForPick (kind, herbTier = null)
241 264 {
242 return kind === "flower" ? 4 : 3;
265 if (kind === "flower")
266 { return 4; }
267 if (kind === "herb")
268 { return 4 + Math.max(1, herbTier | 0 || 1) * 2; }
269 return 3;
243 270 }
244 271
245 272 /** Plant node exhaust then respawn (ms). */
@@ -23,6 +23,7 @@ import {
23 materialFromOreBoulderState,
23 materialFromOreBoulderState,
24 isOreBoulderState
24 isOreBoulderState
25} from "./materialTiers.js";
25} from "./materialTiers.js";
26import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
26
27
27export {
28export {
28 ORE_BEARING_MATERIALS,
29 ORE_BEARING_MATERIALS,
@@ -228,18 +229,44 @@ export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills,
228 return { ok: true, tool: tools[0] };
229 return { ok: true, tool: tools[0] };
229}
230}
230
231
231/** Herbalism gather duration. Flowers are quick (~1s); cotton a bit longer. */
232/**
232export function herbalismDurationMs (plantKind = null, toolTier = null)
233 * Skill gate for folklore herb nodes (`BlockType.herbPlant`, state = herbId).
234 * @returns {{ ok: true, herb: object } | { ok: false, reason: string }}
235 */
236export function resolveHerbGather ({ herbId, skills })
237{
238 const herb = herbDefinition(herbId);
239 if (!herb)
240 { return { ok: false, reason: "There is nothing to pick there." }; }
241 const need = herbGatherSkillLevel(herb.tier);
242 const level = skillLevel(skills, SkillId.herbalism);
243 if (level < need)
244 { return { ok: false, reason: `Requires Herbalism ${need}.` }; }
245 return { ok: true, herb };
246}
247
248/** Herbalism gather duration. Flowers are quick (~1s); cotton a bit longer; clipper herbs mid. */
249export function herbalismDurationMs (plantKind = null, toolTier = null, herbTier = null)
233{
250{
234 if (plantKind === "flower")
251 if (plantKind === "flower")
235 { return 1000; }
252 { return 1000; }
253 if (plantKind === "herb")
254 {
255 const tier = Math.max(1, herbTier | 0 || 1);
256 const rank = toolTier ? tierRank(toolTier) : 1;
257 return Math.max(800, 1600 + tier * 250 - (rank - 1) * 150);
258 }
236 const rank = toolTier ? tierRank(toolTier) : 1;
259 const rank = toolTier ? tierRank(toolTier) : 1;
237 return Math.max(500, 2500 - (rank - 1) * 250);
260 return Math.max(500, 2500 - (rank - 1) * 250);
238}
261}
239
262
240export function herbalismXpForPick (kind)
263export function herbalismXpForPick (kind, herbTier = null)
241{
264{
242 return kind === "flower" ? 4 : 3;
265 if (kind === "flower")
266 { return 4; }
267 if (kind === "herb")
268 { return 4 + Math.max(1, herbTier | 0 || 1) * 2; }
269 return 3;
243}
270}
244
271
245/** Plant node exhaust then respawn (ms). */
272/** Plant node exhaust then respawn (ms). */
shared/definitions/herbs.js added +331 −0
@@ -0,0 +1,331 @@
1 import { spriteImageName } from "./tileSprites.js";
2 import { ItemCategory } from "./itemCategories.js";
3
4 /**
5 * Folklore herb catalog for Herbalism nodes + alchemy ingredients.
6 * Fantasy associations live in docs/FEATURES.md (not code) for later potion design.
7 *
8 * Tier spread (24 herbs): 2 / 3 / 3 / 4 / 4 / 4 / 4 for tiers 1–7.
9 */
10
11 export const HerbId = Object.freeze({
12 mint: "mint",
13 garlic: "garlic",
14 thyme: "thyme",
15 sage: "sage",
16 rosemary: "rosemary",
17 lavender: "lavender",
18 chamomile: "chamomile",
19 nettle: "nettle",
20 yarrow: "yarrow",
21 juniper: "juniper",
22 elder: "elder",
23 rue: "rue",
24 valerian: "valerian",
25 mugwort: "mugwort",
26 wormwood: "wormwood",
27 stJohnsWort: "st-johns-wort",
28 hawthorn: "hawthorn",
29 foxglove: "foxglove",
30 mistletoe: "mistletoe",
31 datura: "datura",
32 belladonna: "belladonna",
33 henbane: "henbane",
34 mandrake: "mandrake",
35 aconite: "aconite"
36 });
37
38 /** Numeric item IDs (160–183). Keys are camelCase for `ItemId` spread. */
39 export const HerbItemId = Object.freeze({
40 mint: 160,
41 garlic: 161,
42 thyme: 162,
43 sage: 163,
44 rosemary: 164,
45 lavender: 165,
46 chamomile: 166,
47 nettle: 167,
48 yarrow: 168,
49 juniper: 169,
50 elder: 170,
51 rue: 171,
52 valerian: 172,
53 mugwort: 173,
54 wormwood: 174,
55 stJohnsWort: 175,
56 hawthorn: 176,
57 foxglove: 177,
58 mistletoe: 178,
59 datura: 179,
60 belladonna: 180,
61 henbane: 181,
62 mandrake: 182,
63 aconite: 183
64 });
65
66 /** Map herbId string → ItemId number. */
67 const HERB_ITEM_ID_BY_KEY = Object.freeze({
68 [HerbId.mint]: HerbItemId.mint,
69 [HerbId.garlic]: HerbItemId.garlic,
70 [HerbId.thyme]: HerbItemId.thyme,
71 [HerbId.sage]: HerbItemId.sage,
72 [HerbId.rosemary]: HerbItemId.rosemary,
73 [HerbId.lavender]: HerbItemId.lavender,
74 [HerbId.chamomile]: HerbItemId.chamomile,
75 [HerbId.nettle]: HerbItemId.nettle,
76 [HerbId.yarrow]: HerbItemId.yarrow,
77 [HerbId.juniper]: HerbItemId.juniper,
78 [HerbId.elder]: HerbItemId.elder,
79 [HerbId.rue]: HerbItemId.rue,
80 [HerbId.valerian]: HerbItemId.valerian,
81 [HerbId.mugwort]: HerbItemId.mugwort,
82 [HerbId.wormwood]: HerbItemId.wormwood,
83 [HerbId.stJohnsWort]: HerbItemId.stJohnsWort,
84 [HerbId.hawthorn]: HerbItemId.hawthorn,
85 [HerbId.foxglove]: HerbItemId.foxglove,
86 [HerbId.mistletoe]: HerbItemId.mistletoe,
87 [HerbId.datura]: HerbItemId.datura,
88 [HerbId.belladonna]: HerbItemId.belladonna,
89 [HerbId.henbane]: HerbItemId.henbane,
90 [HerbId.mandrake]: HerbItemId.mandrake,
91 [HerbId.aconite]: HerbItemId.aconite
92 });
93
94 /**
95 * Gather skill gates by herb tier (aligned with mining: ceil(equipGate/2)).
96 * Tier 1→1, 2→5, 3→10, 4→18, 5→25, 6→35, 7→45.
97 */
98 export const HERB_GATHER_SKILL_LEVEL = Object.freeze({
99 1: 1,
100 2: 5,
101 3: 10,
102 4: 18,
103 5: 25,
104 6: 35,
105 7: 45
106 });
107
108 const DEFAULT_STACK = 99;
109
110 function herb (
111 herbId,
112 tier,
113 displayName,
114 description,
115 { seedValue = 2 } = {}
116 )
117 {
118 const itemId = HERB_ITEM_ID_BY_KEY[herbId];
119 return Object.freeze({
120 herbId,
121 itemId,
122 key: herbId,
123 tier,
124 displayName,
125 description,
126 seedValue,
127 stackable: true,
128 maxStackSize: DEFAULT_STACK,
129 uniqueInstance: false,
130 category: ItemCategory.ingredient,
131 herb: true,
132 /** Shared folder `assets/herbs/<key>.png` — catalog registers block + item. */
133 iconKey: "herbs",
134 defaultState: herbId,
135 sprite: spriteImageName("item", "herbs", herbId)
136 });
137 }
138
139 export const HERB_DEFINITIONS = Object.freeze({
140 // Tier 1 — kitchen & common garden
141 [HerbId.mint]: herb(
142 HerbId.mint,
143 1,
144 "Mint",
145 "Cool green leaves that freshen the breath and settle a heavy stomach."
146 ),
147 [HerbId.garlic]: herb(
148 HerbId.garlic,
149 1,
150 "Garlic",
151 "Pungent bulbs prized in kitchens and hung in doorways against unwelcome guests."
152 ),
153 // Tier 2 — household remedies
154 [HerbId.thyme]: herb(
155 HerbId.thyme,
156 2,
157 "Thyme",
158 "A hardy herb of the hills, used to clear the chest and steel the nerves."
159 ),
160 [HerbId.sage]: herb(
161 HerbId.sage,
162 2,
163 "Sage",
164 "Silvery leaves long trusted as a general cure and a mark of a clear mind."
165 ),
166 [HerbId.rosemary]: herb(
167 HerbId.rosemary,
168 2,
169 "Rosemary",
170 "Needle-leafed sprigs that sharpen memory and are said to ward off ill spirits."
171 ),
172 // Tier 3 — calming & common wild
173 [HerbId.lavender]: herb(
174 HerbId.lavender,
175 3,
176 "Lavender",
177 "Fragrant purple spikes laid under pillows and pressed into wound wraps."
178 ),
179 [HerbId.chamomile]: herb(
180 HerbId.chamomile,
181 3,
182 "Chamomile",
183 "Daisy-like blooms brewed for restless bellies and quiet evenings."
184 ),
185 [HerbId.nettle]: herb(
186 HerbId.nettle,
187 3,
188 "Nettle",
189 "Stinging greens that nourish when cooked and toughen those who handle them."
190 ),
191 // Tier 4 — battle & boundary herbs
192 [HerbId.yarrow]: herb(
193 HerbId.yarrow,
194 4,
195 "Yarrow",
196 "Feathery battlefield herb bound into bandages to stop a soldier's bleeding."
197 ),
198 [HerbId.juniper]: herb(
199 HerbId.juniper,
200 4,
201 "Juniper",
202 "Dark berries whose smoke is burned to purify rooms and drive out sickness."
203 ),
204 [HerbId.elder]: herb(
205 HerbId.elder,
206 4,
207 "Elder",
208 "Blossom and berry of a tree whispered to house spirits of its own."
209 ),
210 [HerbId.rue]: herb(
211 HerbId.rue,
212 4,
213 "Rue",
214 "Bitter leaves carried against curses and the stare of the evil eye."
215 ),
216 // Tier 5 — dream & bitter medicine
217 [HerbId.valerian]: herb(
218 HerbId.valerian,
219 5,
220 "Valerian",
221 "Earthy roots that pull the weary toward deep, untroubled sleep."
222 ),
223 [HerbId.mugwort]: herb(
224 HerbId.mugwort,
225 5,
226 "Mugwort",
227 "Roadside herb of dreamers, travellers, and those who seek visions."
228 ),
229 [HerbId.wormwood]: herb(
230 HerbId.wormwood,
231 5,
232 "Wormwood",
233 "A bitter grey-green plant used against parasites and haunted moods."
234 ),
235 [HerbId.stJohnsWort]: herb(
236 HerbId.stJohnsWort,
237 5,
238 "St. John's wort",
239 "Sunny yellow blooms carried as a charm against demons and dark hours."
240 ),
241 // Tier 6 — fey & perilous
242 [HerbId.hawthorn]: herb(
243 HerbId.hawthorn,
244 6,
245 "Hawthorn",
246 "Thorny blossom of sacred hedges and places best left undisturbed."
247 ),
248 [HerbId.foxglove]: herb(
249 HerbId.foxglove,
250 6,
251 "Foxglove",
252 "Tall bells said to be fairy gloves — beautiful, and deadly if mishandled."
253 ),
254 [HerbId.mistletoe]: herb(
255 HerbId.mistletoe,
256 6,
257 "Mistletoe",
258 "Pale berries of the oak-parasite, gathered for rites of life and fertility."
259 ),
260 [HerbId.datura]: herb(
261 HerbId.datura,
262 6,
263 "Datura",
264 "Trumpet flowers that open the mind to visions — and to madness."
265 ),
266 // Tier 7 — witches' garden
267 [HerbId.belladonna]: herb(
268 HerbId.belladonna,
269 7,
270 "Belladonna",
271 "Glossy black berries of the nightshade, linked to witch-flight and poison."
272 ),
273 [HerbId.henbane]: herb(
274 HerbId.henbane,
275 7,
276 "Henbane",
277 "Sickly nightshade that dulls the senses and invites strange trances."
278 ),
279 [HerbId.mandrake]: herb(
280 HerbId.mandrake,
281 7,
282 "Mandrake",
283 "A man-shaped root said to scream when torn from the earth."
284 ),
285 [HerbId.aconite]: herb(
286 HerbId.aconite,
287 7,
288 "Aconite",
289 "Monkshood — also called wolfsbane — a lethal flower of curses and beasts."
290 )
291 });
292
293 export const HERB_ORDER = Object.freeze(Object.keys(HERB_DEFINITIONS));
294
295 export function herbDefinition (herbId)
296 {
297 return HERB_DEFINITIONS[herbId] ?? null;
298 }
299
300 export function herbDefinitionByItemId (itemId)
301 {
302 const id = itemId | 0;
303 for (const def of Object.values(HERB_DEFINITIONS))
304 {
305 if (def.itemId === id)
306 { return def; }
307 }
308 return null;
309 }
310
311 export function isHerbId (value)
312 {
313 return !!HERB_DEFINITIONS[value];
314 }
315
316 export function herbGatherSkillLevel (tier)
317 {
318 return HERB_GATHER_SKILL_LEVEL[tier | 0] ?? HERB_GATHER_SKILL_LEVEL[1];
319 }
320
321 export function herbBlockState (herbId)
322 {
323 return isHerbId(herbId) ? herbId : HerbId.mint;
324 }
325
326 /** Item definition stubs merged into ITEM_DEFINITIONS. */
327 export const HERB_ITEM_DEFINITIONS = Object.freeze(
328 Object.fromEntries(
329 Object.values(HERB_DEFINITIONS).map((def) => [def.itemId, def])
330 )
331 );
@@ -0,0 +1,331 @@
1import { spriteImageName } from "./tileSprites.js";
2import { ItemCategory } from "./itemCategories.js";
3
4/**
5 * Folklore herb catalog for Herbalism nodes + alchemy ingredients.
6 * Fantasy associations live in docs/FEATURES.md (not code) for later potion design.
7 *
8 * Tier spread (24 herbs): 2 / 3 / 3 / 4 / 4 / 4 / 4 for tiers 1–7.
9 */
10
11export const HerbId = Object.freeze({
12 mint: "mint",
13 garlic: "garlic",
14 thyme: "thyme",
15 sage: "sage",
16 rosemary: "rosemary",
17 lavender: "lavender",
18 chamomile: "chamomile",
19 nettle: "nettle",
20 yarrow: "yarrow",
21 juniper: "juniper",
22 elder: "elder",
23 rue: "rue",
24 valerian: "valerian",
25 mugwort: "mugwort",
26 wormwood: "wormwood",
27 stJohnsWort: "st-johns-wort",
28 hawthorn: "hawthorn",
29 foxglove: "foxglove",
30 mistletoe: "mistletoe",
31 datura: "datura",
32 belladonna: "belladonna",
33 henbane: "henbane",
34 mandrake: "mandrake",
35 aconite: "aconite"
36});
37
38/** Numeric item IDs (160–183). Keys are camelCase for `ItemId` spread. */
39export const HerbItemId = Object.freeze({
40 mint: 160,
41 garlic: 161,
42 thyme: 162,
43 sage: 163,
44 rosemary: 164,
45 lavender: 165,
46 chamomile: 166,
47 nettle: 167,
48 yarrow: 168,
49 juniper: 169,
50 elder: 170,
51 rue: 171,
52 valerian: 172,
53 mugwort: 173,
54 wormwood: 174,
55 stJohnsWort: 175,
56 hawthorn: 176,
57 foxglove: 177,
58 mistletoe: 178,
59 datura: 179,
60 belladonna: 180,
61 henbane: 181,
62 mandrake: 182,
63 aconite: 183
64});
65
66/** Map herbId string → ItemId number. */
67const HERB_ITEM_ID_BY_KEY = Object.freeze({
68 [HerbId.mint]: HerbItemId.mint,
69 [HerbId.garlic]: HerbItemId.garlic,
70 [HerbId.thyme]: HerbItemId.thyme,
71 [HerbId.sage]: HerbItemId.sage,
72 [HerbId.rosemary]: HerbItemId.rosemary,
73 [HerbId.lavender]: HerbItemId.lavender,
74 [HerbId.chamomile]: HerbItemId.chamomile,
75 [HerbId.nettle]: HerbItemId.nettle,
76 [HerbId.yarrow]: HerbItemId.yarrow,
77 [HerbId.juniper]: HerbItemId.juniper,
78 [HerbId.elder]: HerbItemId.elder,
79 [HerbId.rue]: HerbItemId.rue,
80 [HerbId.valerian]: HerbItemId.valerian,
81 [HerbId.mugwort]: HerbItemId.mugwort,
82 [HerbId.wormwood]: HerbItemId.wormwood,
83 [HerbId.stJohnsWort]: HerbItemId.stJohnsWort,
84 [HerbId.hawthorn]: HerbItemId.hawthorn,
85 [HerbId.foxglove]: HerbItemId.foxglove,
86 [HerbId.mistletoe]: HerbItemId.mistletoe,
87 [HerbId.datura]: HerbItemId.datura,
88 [HerbId.belladonna]: HerbItemId.belladonna,
89 [HerbId.henbane]: HerbItemId.henbane,
90 [HerbId.mandrake]: HerbItemId.mandrake,
91 [HerbId.aconite]: HerbItemId.aconite
92});
93
94/**
95 * Gather skill gates by herb tier (aligned with mining: ceil(equipGate/2)).
96 * Tier 1→1, 2→5, 3→10, 4→18, 5→25, 6→35, 7→45.
97 */
98export const HERB_GATHER_SKILL_LEVEL = Object.freeze({
99 1: 1,
100 2: 5,
101 3: 10,
102 4: 18,
103 5: 25,
104 6: 35,
105 7: 45
106});
107
108const DEFAULT_STACK = 99;
109
110function herb (
111 herbId,
112 tier,
113 displayName,
114 description,
115 { seedValue = 2 } = {}
116)
117{
118 const itemId = HERB_ITEM_ID_BY_KEY[herbId];
119 return Object.freeze({
120 herbId,
121 itemId,
122 key: herbId,
123 tier,
124 displayName,
125 description,
126 seedValue,
127 stackable: true,
128 maxStackSize: DEFAULT_STACK,
129 uniqueInstance: false,
130 category: ItemCategory.ingredient,
131 herb: true,
132 /** Shared folder `assets/herbs/<key>.png` — catalog registers block + item. */
133 iconKey: "herbs",
134 defaultState: herbId,
135 sprite: spriteImageName("item", "herbs", herbId)
136 });
137}
138
139export const HERB_DEFINITIONS = Object.freeze({
140 // Tier 1 — kitchen & common garden
141 [HerbId.mint]: herb(
142 HerbId.mint,
143 1,
144 "Mint",
145 "Cool green leaves that freshen the breath and settle a heavy stomach."
146 ),
147 [HerbId.garlic]: herb(
148 HerbId.garlic,
149 1,
150 "Garlic",
151 "Pungent bulbs prized in kitchens and hung in doorways against unwelcome guests."
152 ),
153 // Tier 2 — household remedies
154 [HerbId.thyme]: herb(
155 HerbId.thyme,
156 2,
157 "Thyme",
158 "A hardy herb of the hills, used to clear the chest and steel the nerves."
159 ),
160 [HerbId.sage]: herb(
161 HerbId.sage,
162 2,
163 "Sage",
164 "Silvery leaves long trusted as a general cure and a mark of a clear mind."
165 ),
166 [HerbId.rosemary]: herb(
167 HerbId.rosemary,
168 2,
169 "Rosemary",
170 "Needle-leafed sprigs that sharpen memory and are said to ward off ill spirits."
171 ),
172 // Tier 3 — calming & common wild
173 [HerbId.lavender]: herb(
174 HerbId.lavender,
175 3,
176 "Lavender",
177 "Fragrant purple spikes laid under pillows and pressed into wound wraps."
178 ),
179 [HerbId.chamomile]: herb(
180 HerbId.chamomile,
181 3,
182 "Chamomile",
183 "Daisy-like blooms brewed for restless bellies and quiet evenings."
184 ),
185 [HerbId.nettle]: herb(
186 HerbId.nettle,
187 3,
188 "Nettle",
189 "Stinging greens that nourish when cooked and toughen those who handle them."
190 ),
191 // Tier 4 — battle & boundary herbs
192 [HerbId.yarrow]: herb(
193 HerbId.yarrow,
194 4,
195 "Yarrow",
196 "Feathery battlefield herb bound into bandages to stop a soldier's bleeding."
197 ),
198 [HerbId.juniper]: herb(
199 HerbId.juniper,
200 4,
201 "Juniper",
202 "Dark berries whose smoke is burned to purify rooms and drive out sickness."
203 ),
204 [HerbId.elder]: herb(
205 HerbId.elder,
206 4,
207 "Elder",
208 "Blossom and berry of a tree whispered to house spirits of its own."
209 ),
210 [HerbId.rue]: herb(
211 HerbId.rue,
212 4,
213 "Rue",
214 "Bitter leaves carried against curses and the stare of the evil eye."
215 ),
216 // Tier 5 — dream & bitter medicine
217 [HerbId.valerian]: herb(
218 HerbId.valerian,
219 5,
220 "Valerian",
221 "Earthy roots that pull the weary toward deep, untroubled sleep."
222 ),
223 [HerbId.mugwort]: herb(
224 HerbId.mugwort,
225 5,
226 "Mugwort",
227 "Roadside herb of dreamers, travellers, and those who seek visions."
228 ),
229 [HerbId.wormwood]: herb(
230 HerbId.wormwood,
231 5,
232 "Wormwood",
233 "A bitter grey-green plant used against parasites and haunted moods."
234 ),
235 [HerbId.stJohnsWort]: herb(
236 HerbId.stJohnsWort,
237 5,
238 "St. John's wort",
239 "Sunny yellow blooms carried as a charm against demons and dark hours."
240 ),
241 // Tier 6 — fey & perilous
242 [HerbId.hawthorn]: herb(
243 HerbId.hawthorn,
244 6,
245 "Hawthorn",
246 "Thorny blossom of sacred hedges and places best left undisturbed."
247 ),
248 [HerbId.foxglove]: herb(
249 HerbId.foxglove,
250 6,
251 "Foxglove",
252 "Tall bells said to be fairy gloves — beautiful, and deadly if mishandled."
253 ),
254 [HerbId.mistletoe]: herb(
255 HerbId.mistletoe,
256 6,
257 "Mistletoe",
258 "Pale berries of the oak-parasite, gathered for rites of life and fertility."
259 ),
260 [HerbId.datura]: herb(
261 HerbId.datura,
262 6,
263 "Datura",
264 "Trumpet flowers that open the mind to visions — and to madness."
265 ),
266 // Tier 7 — witches' garden
267 [HerbId.belladonna]: herb(
268 HerbId.belladonna,
269 7,
270 "Belladonna",
271 "Glossy black berries of the nightshade, linked to witch-flight and poison."
272 ),
273 [HerbId.henbane]: herb(
274 HerbId.henbane,
275 7,
276 "Henbane",
277 "Sickly nightshade that dulls the senses and invites strange trances."
278 ),
279 [HerbId.mandrake]: herb(
280 HerbId.mandrake,
281 7,
282 "Mandrake",
283 "A man-shaped root said to scream when torn from the earth."
284 ),
285 [HerbId.aconite]: herb(
286 HerbId.aconite,
287 7,
288 "Aconite",
289 "Monkshood — also called wolfsbane — a lethal flower of curses and beasts."
290 )
291});
292
293export const HERB_ORDER = Object.freeze(Object.keys(HERB_DEFINITIONS));
294
295export function herbDefinition (herbId)
296{
297 return HERB_DEFINITIONS[herbId] ?? null;
298}
299
300export function herbDefinitionByItemId (itemId)
301{
302 const id = itemId | 0;
303 for (const def of Object.values(HERB_DEFINITIONS))
304 {
305 if (def.itemId === id)
306 { return def; }
307 }
308 return null;
309}
310
311export function isHerbId (value)
312{
313 return !!HERB_DEFINITIONS[value];
314}
315
316export function herbGatherSkillLevel (tier)
317{
318 return HERB_GATHER_SKILL_LEVEL[tier | 0] ?? HERB_GATHER_SKILL_LEVEL[1];
319}
320
321export function herbBlockState (herbId)
322{
323 return isHerbId(herbId) ? herbId : HerbId.mint;
324}
325
326/** Item definition stubs merged into ITEM_DEFINITIONS. */
327export const HERB_ITEM_DEFINITIONS = Object.freeze(
328 Object.fromEntries(
329 Object.values(HERB_DEFINITIONS).map((def) => [def.itemId, def])
330 )
331);
shared/definitions/items.js +9 −25
@@ -11,6 +11,7 @@ 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 13 import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
14 import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
14 15 import { POTION_MAX_STACK } from "./alchemy.js";
15 16
16 17 export const ItemId = Object.freeze({
@@ -27,8 +28,6 @@ export const ItemId = Object.freeze({
27 28 bones: 27,
28 29 skull: 28,
29 30 glassBottle: 29,
30 greenHerb: 30,
31 redBeet: 31,
32 31 potion: 32,
33 32 recipePaper: 33,
34 33 bronzePlantClippers: 34,
@@ -36,7 +35,8 @@ export const ItemId = Object.freeze({
36 35 ...WoodItemId,
37 36 ...ArmourItemId,
38 37 ...ClothItemId,
39 ...DyeItemId
38 ...DyeItemId,
39 ...HerbItemId
40 40 });
41 41
42 42 export const EQUIPMENT_SLOT = Object.freeze({
@@ -241,28 +241,6 @@ export const ITEM_DEFINITIONS = Object.freeze({
241 241 defaultState: "potion-0",
242 242 npcShopAllowed: true
243 243 }),
244 [ItemId.greenHerb]: Object.freeze({
245 itemId: ItemId.greenHerb,
246 key: "green-herb",
247 displayName: "Green herb",
248 description: "A fragrant common herb.",
249 seedValue: 2,
250 stackable: true,
251 maxStackSize: DEFAULT_MAX_STACK,
252 uniqueInstance: false,
253 category: "ingredient"
254 }),
255 [ItemId.redBeet]: Object.freeze({
256 itemId: ItemId.redBeet,
257 key: "red-beet",
258 displayName: "Red beet",
259 description: "A root vegetable.",
260 seedValue: 1,
261 stackable: true,
262 maxStackSize: DEFAULT_MAX_STACK,
263 uniqueInstance: false,
264 category: "ingredient"
265 }),
266 244 [ItemId.potion]: Object.freeze({
267 245 itemId: ItemId.potion,
268 246 key: "potion",
@@ -312,6 +290,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
312 290 ...WOOD_ITEM_DEFINITIONS,
313 291 ...ARMOUR_ITEM_DEFINITIONS,
314 292 ...CLOTH_ITEM_DEFINITIONS,
293 ...HERB_ITEM_DEFINITIONS,
315 294 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
316 295 [DyeItemId.dye]: DYE_ITEM_DEFINITION
317 296 });
@@ -466,6 +445,11 @@ export function letterVisualState (instance)
466 445 export function itemAssetPath (itemId, companion = null, instance = null)
467 446 {
468 447 const def = itemDefinition(itemId);
448 if (def?.herb)
449 {
450 const suffix = companion ? `-${companion}` : "";
451 return `/assets/herbs/${def.key}${suffix}.png`;
452 }
469 453 const key = def?.iconKey ?? def?.key ?? "paper";
470 454 const state = itemId === ItemId.letter
471 455 ? letterVisualState(instance)
@@ -11,6 +11,7 @@ import { 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 { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
13import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
14import { HERB_ITEM_DEFINITIONS, HerbItemId } from "./herbs.js";
14import { POTION_MAX_STACK } from "./alchemy.js";
15import { POTION_MAX_STACK } from "./alchemy.js";
15
16
16export const ItemId = Object.freeze({
17export const ItemId = Object.freeze({
@@ -27,8 +28,6 @@ export const ItemId = Object.freeze({
27 bones: 27,
28 bones: 27,
28 skull: 28,
29 skull: 28,
29 glassBottle: 29,
30 glassBottle: 29,
30 greenHerb: 30,
31 redBeet: 31,
32 potion: 32,
31 potion: 32,
33 recipePaper: 33,
32 recipePaper: 33,
34 bronzePlantClippers: 34,
33 bronzePlantClippers: 34,
@@ -36,7 +35,8 @@ export const ItemId = Object.freeze({
36 ...WoodItemId,
35 ...WoodItemId,
37 ...ArmourItemId,
36 ...ArmourItemId,
38 ...ClothItemId,
37 ...ClothItemId,
39 ...DyeItemId
38 ...DyeItemId,
39 ...HerbItemId
40});
40});
41
41
42export const EQUIPMENT_SLOT = Object.freeze({
42export const EQUIPMENT_SLOT = Object.freeze({
@@ -241,28 +241,6 @@ export const ITEM_DEFINITIONS = Object.freeze({
241 defaultState: "potion-0",
241 defaultState: "potion-0",
242 npcShopAllowed: true
242 npcShopAllowed: true
243 }),
243 }),
244 [ItemId.greenHerb]: Object.freeze({
245 itemId: ItemId.greenHerb,
246 key: "green-herb",
247 displayName: "Green herb",
248 description: "A fragrant common herb.",
249 seedValue: 2,
250 stackable: true,
251 maxStackSize: DEFAULT_MAX_STACK,
252 uniqueInstance: false,
253 category: "ingredient"
254 }),
255 [ItemId.redBeet]: Object.freeze({
256 itemId: ItemId.redBeet,
257 key: "red-beet",
258 displayName: "Red beet",
259 description: "A root vegetable.",
260 seedValue: 1,
261 stackable: true,
262 maxStackSize: DEFAULT_MAX_STACK,
263 uniqueInstance: false,
264 category: "ingredient"
265 }),
266 [ItemId.potion]: Object.freeze({
244 [ItemId.potion]: Object.freeze({
267 itemId: ItemId.potion,
245 itemId: ItemId.potion,
268 key: "potion",
246 key: "potion",
@@ -312,6 +290,7 @@ export const ITEM_DEFINITIONS = Object.freeze({
312 ...WOOD_ITEM_DEFINITIONS,
290 ...WOOD_ITEM_DEFINITIONS,
313 ...ARMOUR_ITEM_DEFINITIONS,
291 ...ARMOUR_ITEM_DEFINITIONS,
314 ...CLOTH_ITEM_DEFINITIONS,
292 ...CLOTH_ITEM_DEFINITIONS,
293 ...HERB_ITEM_DEFINITIONS,
315 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
294 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
316 [DyeItemId.dye]: DYE_ITEM_DEFINITION
295 [DyeItemId.dye]: DYE_ITEM_DEFINITION
317});
296});
@@ -466,6 +445,11 @@ export function letterVisualState (instance)
466export function itemAssetPath (itemId, companion = null, instance = null)
445export function itemAssetPath (itemId, companion = null, instance = null)
467{
446{
468 const def = itemDefinition(itemId);
447 const def = itemDefinition(itemId);
448 if (def?.herb)
449 {
450 const suffix = companion ? `-${companion}` : "";
451 return `/assets/herbs/${def.key}${suffix}.png`;
452 }
469 const key = def?.iconKey ?? def?.key ?? "paper";
453 const key = def?.iconKey ?? def?.key ?? "paper";
470 const state = itemId === ItemId.letter
454 const state = itemId === ItemId.letter
471 ? letterVisualState(instance)
455 ? letterVisualState(instance)
shared/definitions/tiles.js +74 −1
@@ -11,6 +11,11 @@ import {
11 11 FLOWER_COLOR_DISPLAY,
12 12 flowerBlockState
13 13 } from "./dyes.js";
14 import {
15 HERB_ORDER,
16 HERB_DEFINITIONS,
17 herbDefinition
18 } from "./herbs.js";
14 19 import { spriteImageName, resolveState } from "./tileSprites.js";
15 20 import { isSeasonalStumpState, SeasonId } from "../world/season.js";
16 21 import {
@@ -45,7 +50,11 @@ export const BlockType = Object.freeze({
45 50 cottonPlant: 16,
46 51 spinningWheel: 17,
47 52 loom: 18,
48 tailorBench: 19
53 tailorBench: 19,
54 bountyOffice: 20,
55 barber: 23,
56 /** Folklore herbs — state is herbId (`sage`, `mint`, …); sprites in `assets/herbs/`. */
57 herbPlant: 24
49 58 });
50 59
51 60 export const GROUND_DEFINITIONS = Object.freeze({
@@ -351,6 +360,50 @@ export const BLOCK_DEFINITIONS = Object.freeze({
351 360 animationSpeed: 0,
352 361 craftingStationId: "tailor-bench",
353 362 outdoor: false
363 }),
364 [BlockType.bountyOffice]: Object.freeze({
365 id: BlockType.bountyOffice,
366 key: "bounty-office",
367 displayName: "Bounty office",
368 passable: false,
369 blocksLight: false,
370 lightRangeTiles: 0,
371 frames: 1,
372 framesPerRow: 1,
373 animationSpeed: 0,
374 outdoor: false
375 }),
376 [BlockType.barber]: Object.freeze({
377 id: BlockType.barber,
378 key: "barber",
379 displayName: "Barber",
380 passable: false,
381 blocksLight: false,
382 lightRangeTiles: 0,
383 frames: 1,
384 framesPerRow: 1,
385 animationSpeed: 0,
386 outdoor: false
387 }),
388 [BlockType.herbPlant]: Object.freeze({
389 id: BlockType.herbPlant,
390 key: "herb",
391 displayName: "Herb",
392 passable: true,
393 blocksLight: false,
394 lightRangeTiles: 0,
395 frames: 1,
396 framesPerRow: 1,
397 animationSpeed: 0,
398 outdoor: true,
399 gatherable: true,
400 /** Sprites live under `assets/herbs/` (shared with items), not `blocks/herb/`. */
401 assetFolder: "herbs",
402 plantGather: Object.freeze({
403 kind: "herb",
404 requiresClippers: true,
405 skillId: "herbalism"
406 })
354 407 })
355 408 });
356 409
@@ -398,6 +451,11 @@ export function resourceNodeDisplayName (block)
398 451 }
399 452 if (block.typeId === BlockType.cottonPlant)
400 453 { return "Cotton plant"; }
454 if (block.typeId === BlockType.herbPlant)
455 {
456 const herb = herbDefinition(block.state);
457 return herb ? herb.displayName : "Herb";
458 }
401 459 return null;
402 460 }
403 461
@@ -476,6 +534,21 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
476 534 }
477 535 continue;
478 536 }
537 if (def.id === BlockType.herbPlant)
538 {
539 for (const herbId of HERB_ORDER)
540 {
541 const herb = HERB_DEFINITIONS[herbId];
542 entries.push({
543 typeId: def.id,
544 state: herbId,
545 key: def.key,
546 displayName: herb?.displayName ?? herbId,
547 spriteName: spriteImageName("block", def.key, herbId)
548 });
549 }
550 continue;
551 }
479 552 if (def.neighborConnect)
480 553 {
481 554 if (definitionUsesMaterialNeighborConnect(def))
@@ -11,6 +11,11 @@ import {
11 FLOWER_COLOR_DISPLAY,
11 FLOWER_COLOR_DISPLAY,
12 flowerBlockState
12 flowerBlockState
13} from "./dyes.js";
13} from "./dyes.js";
14import {
15 HERB_ORDER,
16 HERB_DEFINITIONS,
17 herbDefinition
18} from "./herbs.js";
14import { spriteImageName, resolveState } from "./tileSprites.js";
19import { spriteImageName, resolveState } from "./tileSprites.js";
15import { isSeasonalStumpState, SeasonId } from "../world/season.js";
20import { isSeasonalStumpState, SeasonId } from "../world/season.js";
16import {
21import {
@@ -45,7 +50,11 @@ export const BlockType = Object.freeze({
45 cottonPlant: 16,
50 cottonPlant: 16,
46 spinningWheel: 17,
51 spinningWheel: 17,
47 loom: 18,
52 loom: 18,
48 tailorBench: 19
53 tailorBench: 19,
54 bountyOffice: 20,
55 barber: 23,
56 /** Folklore herbs — state is herbId (`sage`, `mint`, …); sprites in `assets/herbs/`. */
57 herbPlant: 24
49});
58});
50
59
51export const GROUND_DEFINITIONS = Object.freeze({
60export const GROUND_DEFINITIONS = Object.freeze({
@@ -351,6 +360,50 @@ export const BLOCK_DEFINITIONS = Object.freeze({
351 animationSpeed: 0,
360 animationSpeed: 0,
352 craftingStationId: "tailor-bench",
361 craftingStationId: "tailor-bench",
353 outdoor: false
362 outdoor: false
363 }),
364 [BlockType.bountyOffice]: Object.freeze({
365 id: BlockType.bountyOffice,
366 key: "bounty-office",
367 displayName: "Bounty office",
368 passable: false,
369 blocksLight: false,
370 lightRangeTiles: 0,
371 frames: 1,
372 framesPerRow: 1,
373 animationSpeed: 0,
374 outdoor: false
375 }),
376 [BlockType.barber]: Object.freeze({
377 id: BlockType.barber,
378 key: "barber",
379 displayName: "Barber",
380 passable: false,
381 blocksLight: false,
382 lightRangeTiles: 0,
383 frames: 1,
384 framesPerRow: 1,
385 animationSpeed: 0,
386 outdoor: false
387 }),
388 [BlockType.herbPlant]: Object.freeze({
389 id: BlockType.herbPlant,
390 key: "herb",
391 displayName: "Herb",
392 passable: true,
393 blocksLight: false,
394 lightRangeTiles: 0,
395 frames: 1,
396 framesPerRow: 1,
397 animationSpeed: 0,
398 outdoor: true,
399 gatherable: true,
400 /** Sprites live under `assets/herbs/` (shared with items), not `blocks/herb/`. */
401 assetFolder: "herbs",
402 plantGather: Object.freeze({
403 kind: "herb",
404 requiresClippers: true,
405 skillId: "herbalism"
406 })
354 })
407 })
355});
408});
356
409
@@ -398,6 +451,11 @@ export function resourceNodeDisplayName (block)
398 }
451 }
399 if (block.typeId === BlockType.cottonPlant)
452 if (block.typeId === BlockType.cottonPlant)
400 { return "Cotton plant"; }
453 { return "Cotton plant"; }
454 if (block.typeId === BlockType.herbPlant)
455 {
456 const herb = herbDefinition(block.state);
457 return herb ? herb.displayName : "Herb";
458 }
401 return null;
459 return null;
402}
460}
403
461
@@ -476,6 +534,21 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
476 }
534 }
477 continue;
535 continue;
478 }
536 }
537 if (def.id === BlockType.herbPlant)
538 {
539 for (const herbId of HERB_ORDER)
540 {
541 const herb = HERB_DEFINITIONS[herbId];
542 entries.push({
543 typeId: def.id,
544 state: herbId,
545 key: def.key,
546 displayName: herb?.displayName ?? herbId,
547 spriteName: spriteImageName("block", def.key, herbId)
548 });
549 }
550 continue;
551 }
479 if (def.neighborConnect)
552 if (def.neighborConnect)
480 {
553 {
481 if (definitionUsesMaterialNeighborConnect(def))
554 if (definitionUsesMaterialNeighborConnect(def))
shared/definitions/worldSettings.js +7 −0
@@ -156,6 +156,13 @@ export const WORLD_SETTING_CATEGORIES = [
156 156 }
157 157 ]
158 158 },
159 {
160 id: "starterEquipment",
161 label: "Starter Equipment",
162 /** Custom panel: equipped + inventory for new characters only. */
163 panel: "starterEquipment",
164 fields: []
165 },
159 166 {
160 167 id: "communication",
161 168 label: "Communication",
@@ -156,6 +156,13 @@ export const WORLD_SETTING_CATEGORIES = [
156 }
156 }
157 ]
157 ]
158 },
158 },
159 {
160 id: "starterEquipment",
161 label: "Starter Equipment",
162 /** Custom panel: equipped + inventory for new characters only. */
163 panel: "starterEquipment",
164 fields: []
165 },
159 {
166 {
160 id: "communication",
167 id: "communication",
161 label: "Communication",
168 label: "Communication",
shared/graphics/settings.js added +70 −0
@@ -0,0 +1,70 @@
1 /** Client graphics preferences (persisted in localStorage). */
2
3 export const ViewDistance = Object.freeze({
4 long: "long",
5 short: "short"
6 });
7
8 export const LightingMode = Object.freeze({
9 soft: "soft",
10 simple: "simple"
11 });
12
13 export const BloomMode = Object.freeze({
14 on: "on",
15 off: "off"
16 });
17
18 export const DEFAULT_GRAPHICS_SETTINGS = Object.freeze({
19 viewDistance: ViewDistance.long,
20 lighting: LightingMode.soft,
21 bloom: BloomMode.on
22 });
23
24 const STORAGE_KEY = "tile-mmo-graphics-settings";
25
26 export function normalizeGraphicsSettings (value)
27 {
28 const raw = value && typeof value === "object" ? value : {};
29 const viewDistance = raw.viewDistance === ViewDistance.short
30 ? ViewDistance.short
31 : ViewDistance.long;
32 const lighting = raw.lighting === LightingMode.simple
33 ? LightingMode.simple
34 : LightingMode.soft;
35 const bloom = raw.bloom === BloomMode.off
36 ? BloomMode.off
37 : BloomMode.on;
38 return { viewDistance, lighting, bloom };
39 }
40
41 export function loadGraphicsSettings ()
42 {
43 try
44 {
45 const text = localStorage.getItem(STORAGE_KEY);
46 if (!text)
47 { return { ...DEFAULT_GRAPHICS_SETTINGS }; }
48 return normalizeGraphicsSettings(JSON.parse(text));
49 }
50 catch
51 {
52 return { ...DEFAULT_GRAPHICS_SETTINGS };
53 }
54 }
55
56 export function saveGraphicsSettings (settings)
57 {
58 const next = normalizeGraphicsSettings(settings);
59 try
60 { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); }
61 catch
62 { /* ignore quota / private mode */ }
63 return next;
64 }
65
66 /** Map-ring Chebyshev radius for chunk subscriptions (entities always use VISIBLE_CHUNK_RADIUS). */
67 export function staticChunkRadiusForViewDistance (viewDistance, longRadius, shortRadius)
68 {
69 return viewDistance === ViewDistance.short ? shortRadius : longRadius;
70 }
@@ -0,0 +1,70 @@
1/** Client graphics preferences (persisted in localStorage). */
2
3export const ViewDistance = Object.freeze({
4 long: "long",
5 short: "short"
6});
7
8export const LightingMode = Object.freeze({
9 soft: "soft",
10 simple: "simple"
11});
12
13export const BloomMode = Object.freeze({
14 on: "on",
15 off: "off"
16});
17
18export const DEFAULT_GRAPHICS_SETTINGS = Object.freeze({
19 viewDistance: ViewDistance.long,
20 lighting: LightingMode.soft,
21 bloom: BloomMode.on
22});
23
24const STORAGE_KEY = "tile-mmo-graphics-settings";
25
26export function normalizeGraphicsSettings (value)
27{
28 const raw = value && typeof value === "object" ? value : {};
29 const viewDistance = raw.viewDistance === ViewDistance.short
30 ? ViewDistance.short
31 : ViewDistance.long;
32 const lighting = raw.lighting === LightingMode.simple
33 ? LightingMode.simple
34 : LightingMode.soft;
35 const bloom = raw.bloom === BloomMode.off
36 ? BloomMode.off
37 : BloomMode.on;
38 return { viewDistance, lighting, bloom };
39}
40
41export function loadGraphicsSettings ()
42{
43 try
44 {
45 const text = localStorage.getItem(STORAGE_KEY);
46 if (!text)
47 { return { ...DEFAULT_GRAPHICS_SETTINGS }; }
48 return normalizeGraphicsSettings(JSON.parse(text));
49 }
50 catch
51 {
52 return { ...DEFAULT_GRAPHICS_SETTINGS };
53 }
54}
55
56export function saveGraphicsSettings (settings)
57{
58 const next = normalizeGraphicsSettings(settings);
59 try
60 { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); }
61 catch
62 { /* ignore quota / private mode */ }
63 return next;
64}
65
66/** Map-ring Chebyshev radius for chunk subscriptions (entities always use VISIBLE_CHUNK_RADIUS). */
67export function staticChunkRadiusForViewDistance (viewDistance, longRadius, shortRadius)
68{
69 return viewDistance === ViewDistance.short ? shortRadius : longRadius;
70}
shared/items/origin.js +9 −0
@@ -2,6 +2,7 @@ export const ItemOriginKind = Object.freeze({
2 2 crafted: "crafted",
3 3 shop: "shop",
4 4 gathered: "gathered",
5 gods: "gods",
5 6 unknown: "unknown"
6 7 });
7 8
@@ -71,6 +72,8 @@ export function originLabel (origin)
71 72 const name = origin.displayName?.trim() || "someone";
72 73 return `${verb} by ${name}`;
73 74 }
75 if (origin.kind === ItemOriginKind.gods)
76 { return "Received from the gods"; }
74 77 return "unknown origin";
75 78 }
76 79
@@ -94,6 +97,12 @@ export function gatherOrigin (verb, displayName)
94 97 };
95 98 }
96 99
100 /** Starter gear granted at character creation. */
101 export function godsOrigin ()
102 {
103 return { kind: ItemOriginKind.gods };
104 }
105
97 106 /** @returns {{ origin: object|null, quantity: number }[]} */
98 107 export function normalizeOrigins (stack)
99 108 {
@@ -2,6 +2,7 @@ export const ItemOriginKind = Object.freeze({
2 crafted: "crafted",
2 crafted: "crafted",
3 shop: "shop",
3 shop: "shop",
4 gathered: "gathered",
4 gathered: "gathered",
5 gods: "gods",
5 unknown: "unknown"
6 unknown: "unknown"
6});
7});
7
8
@@ -71,6 +72,8 @@ export function originLabel (origin)
71 const name = origin.displayName?.trim() || "someone";
72 const name = origin.displayName?.trim() || "someone";
72 return `${verb} by ${name}`;
73 return `${verb} by ${name}`;
73 }
74 }
75 if (origin.kind === ItemOriginKind.gods)
76 { return "Received from the gods"; }
74 return "unknown origin";
77 return "unknown origin";
75}
78}
76
79
@@ -94,6 +97,12 @@ export function gatherOrigin (verb, displayName)
94 };
97 };
95}
98}
96
99
100/** Starter gear granted at character creation. */
101export function godsOrigin ()
102{
103 return { kind: ItemOriginKind.gods };
104}
105
97/** @returns {{ origin: object|null, quantity: number }[]} */
106/** @returns {{ origin: object|null, quantity: number }[]} */
98export function normalizeOrigins (stack)
107export function normalizeOrigins (stack)
99{
108{
shared/items/starterLoadout.js added +163 −0
@@ -0,0 +1,163 @@
1 /**
2 * New-character starter inventory + equipment from world settings.
3 * Existing characters are unaffected; only applied when a bag is first created.
4 */
5
6 import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../definitions/items.js";
7 import { EQUIPMENT_SLOTS, emptyEquipment, emptySlots, insertStack } from "./inventory.js";
8 import { godsOrigin, attachOrigins } from "./origin.js";
9
10 /** Defaults match the previous hard-coded starter kit. */
11 export const DEFAULT_STARTER_EQUIPMENT = Object.freeze({
12 [EQUIPMENT_SLOT.head]: null,
13 [EQUIPMENT_SLOT.chest]: null,
14 [EQUIPMENT_SLOT.legs]: null,
15 [EQUIPMENT_SLOT.boots]: null,
16 [EQUIPMENT_SLOT.weapon]: null,
17 [EQUIPMENT_SLOT.offhand]: ItemId.lantern
18 });
19
20 export const DEFAULT_STARTER_INVENTORY = Object.freeze([
21 Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
22 Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
23 Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
24 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 }),
25 Object.freeze({ itemId: ItemId.coins, quantity: 25 })
26 ]);
27
28 export function normalizeStarterEquipment (raw)
29 {
30 const source = raw && typeof raw === "object" ? raw : {};
31 const slots = {};
32 for (const slot of EQUIPMENT_SLOTS)
33 {
34 const value = source[slot];
35 if (value == null || value === "" || value === 0)
36 {
37 slots[slot] = null;
38 continue;
39 }
40 const itemId = Number(typeof value === "object" ? value.itemId : value);
41 const def = itemDefinition(itemId);
42 if (!def?.equipment?.slot || def.equipment.slot !== slot)
43 {
44 slots[slot] = null;
45 continue;
46 }
47 slots[slot] = itemId;
48 }
49 return slots;
50 }
51
52 export function normalizeStarterInventory (raw)
53 {
54 if (!Array.isArray(raw))
55 { return DEFAULT_STARTER_INVENTORY.map((entry) => ({ ...entry })); }
56 const out = [];
57 for (const entry of raw)
58 {
59 if (!entry || typeof entry !== "object")
60 { continue; }
61 const itemId = Number(entry.itemId);
62 const quantity = Math.max(1, Math.floor(Number(entry.quantity) || 1));
63 if (!itemDefinition(itemId))
64 { continue; }
65 out.push({ itemId, quantity });
66 }
67 return out;
68 }
69
70 export function normalizeStarterLoadout (settings)
71 {
72 const equipment = normalizeStarterEquipment(
73 settings?.starterEquipment ?? DEFAULT_STARTER_EQUIPMENT
74 );
75 const inventory = normalizeStarterInventory(
76 settings?.starterInventory ?? DEFAULT_STARTER_INVENTORY
77 );
78 return { equipment, inventory };
79 }
80
81 export function starterLoadoutsEqual (a, b)
82 {
83 const left = normalizeStarterLoadout(a);
84 const right = normalizeStarterLoadout(b);
85 for (const slot of EQUIPMENT_SLOTS)
86 {
87 if (left.equipment[slot] !== right.equipment[slot])
88 { return false; }
89 }
90 if (left.inventory.length !== right.inventory.length)
91 { return false; }
92 for (let i = 0; i < left.inventory.length; i++)
93 {
94 if (left.inventory[i].itemId !== right.inventory[i].itemId)
95 { return false; }
96 if (left.inventory[i].quantity !== right.inventory[i].quantity)
97 { return false; }
98 }
99 return true;
100 }
101
102 export function diffStarterLoadout (previous, next)
103 {
104 const bullets = [];
105 const prev = normalizeStarterLoadout(previous);
106 const upcoming = normalizeStarterLoadout(next);
107 for (const slot of EQUIPMENT_SLOTS)
108 {
109 if (prev.equipment[slot] === upcoming.equipment[slot])
110 { continue; }
111 const fromName = prev.equipment[slot]
112 ? (itemDefinition(prev.equipment[slot])?.displayName ?? `#${prev.equipment[slot]}`)
113 : "empty";
114 const toName = upcoming.equipment[slot]
115 ? (itemDefinition(upcoming.equipment[slot])?.displayName ?? `#${upcoming.equipment[slot]}`)
116 : "empty";
117 bullets.push(`Starter ${slot} changed from ${fromName} to ${toName}.`);
118 }
119 const prevInv = JSON.stringify(prev.inventory);
120 const nextInv = JSON.stringify(upcoming.inventory);
121 if (prevInv !== nextInv)
122 { bullets.push("Starter inventory list changed."); }
123 return bullets;
124 }
125
126 /** Build bag contents for a brand-new character. */
127 export function buildStarterBagContents (settings)
128 {
129 const { equipment: equipIds, inventory } = normalizeStarterLoadout(settings);
130 const origin = godsOrigin();
131 const slots = emptySlots();
132 for (const entry of inventory)
133 {
134 const def = itemDefinition(entry.itemId);
135 if (!def)
136 { continue; }
137 const stack = attachOrigins({
138 itemId: entry.itemId,
139 quantity: entry.quantity,
140 origins: [{ origin, quantity: entry.quantity }]
141 });
142 const result = insertStack(slots, stack, def);
143 if (result.ok)
144 { slots.splice(0, slots.length, ...result.slots); }
145 }
146
147 const equipment = emptyEquipment();
148 for (const slot of EQUIPMENT_SLOTS)
149 {
150 const itemId = equipIds[slot];
151 if (itemId == null)
152 {
153 equipment.slots[slot] = null;
154 continue;
155 }
156 equipment.slots[slot] = attachOrigins({
157 itemId,
158 quantity: 1,
159 origins: [{ origin, quantity: 1 }]
160 });
161 }
162 return { slots, equipment };
163 }
@@ -0,0 +1,163 @@
1/**
2 * New-character starter inventory + equipment from world settings.
3 * Existing characters are unaffected; only applied when a bag is first created.
4 */
5
6import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "../definitions/items.js";
7import { EQUIPMENT_SLOTS, emptyEquipment, emptySlots, insertStack } from "./inventory.js";
8import { godsOrigin, attachOrigins } from "./origin.js";
9
10/** Defaults match the previous hard-coded starter kit. */
11export const DEFAULT_STARTER_EQUIPMENT = Object.freeze({
12 [EQUIPMENT_SLOT.head]: null,
13 [EQUIPMENT_SLOT.chest]: null,
14 [EQUIPMENT_SLOT.legs]: null,
15 [EQUIPMENT_SLOT.boots]: null,
16 [EQUIPMENT_SLOT.weapon]: null,
17 [EQUIPMENT_SLOT.offhand]: ItemId.lantern
18});
19
20export const DEFAULT_STARTER_INVENTORY = Object.freeze([
21 Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
22 Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
23 Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
24 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 }),
25 Object.freeze({ itemId: ItemId.coins, quantity: 25 })
26]);
27
28export function normalizeStarterEquipment (raw)
29{
30 const source = raw && typeof raw === "object" ? raw : {};
31 const slots = {};
32 for (const slot of EQUIPMENT_SLOTS)
33 {
34 const value = source[slot];
35 if (value == null || value === "" || value === 0)
36 {
37 slots[slot] = null;
38 continue;
39 }
40 const itemId = Number(typeof value === "object" ? value.itemId : value);
41 const def = itemDefinition(itemId);
42 if (!def?.equipment?.slot || def.equipment.slot !== slot)
43 {
44 slots[slot] = null;
45 continue;
46 }
47 slots[slot] = itemId;
48 }
49 return slots;
50}
51
52export function normalizeStarterInventory (raw)
53{
54 if (!Array.isArray(raw))
55 { return DEFAULT_STARTER_INVENTORY.map((entry) => ({ ...entry })); }
56 const out = [];
57 for (const entry of raw)
58 {
59 if (!entry || typeof entry !== "object")
60 { continue; }
61 const itemId = Number(entry.itemId);
62 const quantity = Math.max(1, Math.floor(Number(entry.quantity) || 1));
63 if (!itemDefinition(itemId))
64 { continue; }
65 out.push({ itemId, quantity });
66 }
67 return out;
68}
69
70export function normalizeStarterLoadout (settings)
71{
72 const equipment = normalizeStarterEquipment(
73 settings?.starterEquipment ?? DEFAULT_STARTER_EQUIPMENT
74 );
75 const inventory = normalizeStarterInventory(
76 settings?.starterInventory ?? DEFAULT_STARTER_INVENTORY
77 );
78 return { equipment, inventory };
79}
80
81export function starterLoadoutsEqual (a, b)
82{
83 const left = normalizeStarterLoadout(a);
84 const right = normalizeStarterLoadout(b);
85 for (const slot of EQUIPMENT_SLOTS)
86 {
87 if (left.equipment[slot] !== right.equipment[slot])
88 { return false; }
89 }
90 if (left.inventory.length !== right.inventory.length)
91 { return false; }
92 for (let i = 0; i < left.inventory.length; i++)
93 {
94 if (left.inventory[i].itemId !== right.inventory[i].itemId)
95 { return false; }
96 if (left.inventory[i].quantity !== right.inventory[i].quantity)
97 { return false; }
98 }
99 return true;
100}
101
102export function diffStarterLoadout (previous, next)
103{
104 const bullets = [];
105 const prev = normalizeStarterLoadout(previous);
106 const upcoming = normalizeStarterLoadout(next);
107 for (const slot of EQUIPMENT_SLOTS)
108 {
109 if (prev.equipment[slot] === upcoming.equipment[slot])
110 { continue; }
111 const fromName = prev.equipment[slot]
112 ? (itemDefinition(prev.equipment[slot])?.displayName ?? `#${prev.equipment[slot]}`)
113 : "empty";
114 const toName = upcoming.equipment[slot]
115 ? (itemDefinition(upcoming.equipment[slot])?.displayName ?? `#${upcoming.equipment[slot]}`)
116 : "empty";
117 bullets.push(`Starter ${slot} changed from ${fromName} to ${toName}.`);
118 }
119 const prevInv = JSON.stringify(prev.inventory);
120 const nextInv = JSON.stringify(upcoming.inventory);
121 if (prevInv !== nextInv)
122 { bullets.push("Starter inventory list changed."); }
123 return bullets;
124}
125
126/** Build bag contents for a brand-new character. */
127export function buildStarterBagContents (settings)
128{
129 const { equipment: equipIds, inventory } = normalizeStarterLoadout(settings);
130 const origin = godsOrigin();
131 const slots = emptySlots();
132 for (const entry of inventory)
133 {
134 const def = itemDefinition(entry.itemId);
135 if (!def)
136 { continue; }
137 const stack = attachOrigins({
138 itemId: entry.itemId,
139 quantity: entry.quantity,
140 origins: [{ origin, quantity: entry.quantity }]
141 });
142 const result = insertStack(slots, stack, def);
143 if (result.ok)
144 { slots.splice(0, slots.length, ...result.slots); }
145 }
146
147 const equipment = emptyEquipment();
148 for (const slot of EQUIPMENT_SLOTS)
149 {
150 const itemId = equipIds[slot];
151 if (itemId == null)
152 {
153 equipment.slots[slot] = null;
154 continue;
155 }
156 equipment.slots[slot] = attachOrigins({
157 itemId,
158 quantity: 1,
159 origins: [{ origin, quantity: 1 }]
160 });
161 }
162 return { slots, equipment };
163}
shared/protocol/constants.js +20 −1
@@ -1,3 +1,5 @@
1 import { DEFAULT_STARTER_EQUIPMENT, DEFAULT_STARTER_INVENTORY } from "../items/starterLoadout.js";
2
1 3 export const CHUNK_SIZE = 16;
2 4 export const REGION_CHUNKS = 4;
3 5 export const SPRITE_SIZE_PX = 16;
@@ -50,7 +52,11 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
50 52 pigeonTakeoffTilesPerSec: 3,
51 53 pigeonCruiseTilesPerSec: 8,
52 54 pigeonLandingTilesPerSec: 3,
53 pigeonPhaseTiles: 5
55 pigeonPhaseTiles: 5,
56 /** New characters only: equipment slot → itemId (or null). */
57 starterEquipment: DEFAULT_STARTER_EQUIPMENT,
58 /** New characters only: inventory stacks `{ itemId, quantity }[]`. */
59 starterInventory: DEFAULT_STARTER_INVENTORY
54 60 });
55 61
56 62 export const GAIT = Object.freeze({
@@ -111,6 +117,16 @@ export const MessageType = Object.freeze({
111 117 bankSnapshot: "BANK_SNAPSHOT",
112 118 bankDeposit: "BANK_DEPOSIT",
113 119 bankWithdraw: "BANK_WITHDRAW",
120 openBounty: "OPEN_BOUNTY",
121 bountySnapshot: "BOUNTY_SNAPSHOT",
122 raiseBounty: "RAISE_BOUNTY",
123 getCharacterBounty: "GET_CHARACTER_BOUNTY",
124 characterBounty: "CHARACTER_BOUNTY",
125 closeBounty: "CLOSE_BOUNTY",
126 openBarber: "OPEN_BARBER",
127 barberSnapshot: "BARBER_SNAPSHOT",
128 setHair: "SET_HAIR",
129 closeBarber: "CLOSE_BARBER",
114 130 getBlankCheques: "GET_BLANK_CHEQUES",
115 131 returnBlankCheques: "RETURN_BLANK_CHEQUES",
116 132 writeCheque: "WRITE_CHEQUE",
@@ -123,6 +139,7 @@ export const MessageType = Object.freeze({
123 139 combatHit: "COMBAT_HIT",
124 140 combatMiss: "COMBAT_MISS",
125 141 combatBlock: "COMBAT_BLOCK",
142 entityHealth: "ENTITY_HEALTH",
126 143 playerDied: "PLAYER_DIED",
127 144 respawn: "RESPAWN",
128 145 playerRespawned: "PLAYER_RESPAWNED",
@@ -138,6 +155,8 @@ export const MessageType = Object.freeze({
138 155 openLetter: "OPEN_LETTER",
139 156 skills: "SKILLS",
140 157 stamina: "STAMINA",
158 statusEffects: "STATUS_EFFECTS",
159 setGraphicsSettings: "SET_GRAPHICS_SETTINGS",
141 160 eatItem: "EAT_ITEM",
142 161 drinkItem: "DRINK_ITEM",
143 162 startCraft: "START_CRAFT",
@@ -1,3 +1,5 @@
1import { DEFAULT_STARTER_EQUIPMENT, DEFAULT_STARTER_INVENTORY } from "../items/starterLoadout.js";
2
1export const CHUNK_SIZE = 16;
3export const CHUNK_SIZE = 16;
2export const REGION_CHUNKS = 4;
4export const REGION_CHUNKS = 4;
3export const SPRITE_SIZE_PX = 16;
5export const SPRITE_SIZE_PX = 16;
@@ -50,7 +52,11 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
50 pigeonTakeoffTilesPerSec: 3,
52 pigeonTakeoffTilesPerSec: 3,
51 pigeonCruiseTilesPerSec: 8,
53 pigeonCruiseTilesPerSec: 8,
52 pigeonLandingTilesPerSec: 3,
54 pigeonLandingTilesPerSec: 3,
53 pigeonPhaseTiles: 5
55 pigeonPhaseTiles: 5,
56 /** New characters only: equipment slot → itemId (or null). */
57 starterEquipment: DEFAULT_STARTER_EQUIPMENT,
58 /** New characters only: inventory stacks `{ itemId, quantity }[]`. */
59 starterInventory: DEFAULT_STARTER_INVENTORY
54});
60});
55
61
56export const GAIT = Object.freeze({
62export const GAIT = Object.freeze({
@@ -111,6 +117,16 @@ export const MessageType = Object.freeze({
111 bankSnapshot: "BANK_SNAPSHOT",
117 bankSnapshot: "BANK_SNAPSHOT",
112 bankDeposit: "BANK_DEPOSIT",
118 bankDeposit: "BANK_DEPOSIT",
113 bankWithdraw: "BANK_WITHDRAW",
119 bankWithdraw: "BANK_WITHDRAW",
120 openBounty: "OPEN_BOUNTY",
121 bountySnapshot: "BOUNTY_SNAPSHOT",
122 raiseBounty: "RAISE_BOUNTY",
123 getCharacterBounty: "GET_CHARACTER_BOUNTY",
124 characterBounty: "CHARACTER_BOUNTY",
125 closeBounty: "CLOSE_BOUNTY",
126 openBarber: "OPEN_BARBER",
127 barberSnapshot: "BARBER_SNAPSHOT",
128 setHair: "SET_HAIR",
129 closeBarber: "CLOSE_BARBER",
114 getBlankCheques: "GET_BLANK_CHEQUES",
130 getBlankCheques: "GET_BLANK_CHEQUES",
115 returnBlankCheques: "RETURN_BLANK_CHEQUES",
131 returnBlankCheques: "RETURN_BLANK_CHEQUES",
116 writeCheque: "WRITE_CHEQUE",
132 writeCheque: "WRITE_CHEQUE",
@@ -123,6 +139,7 @@ export const MessageType = Object.freeze({
123 combatHit: "COMBAT_HIT",
139 combatHit: "COMBAT_HIT",
124 combatMiss: "COMBAT_MISS",
140 combatMiss: "COMBAT_MISS",
125 combatBlock: "COMBAT_BLOCK",
141 combatBlock: "COMBAT_BLOCK",
142 entityHealth: "ENTITY_HEALTH",
126 playerDied: "PLAYER_DIED",
143 playerDied: "PLAYER_DIED",
127 respawn: "RESPAWN",
144 respawn: "RESPAWN",
128 playerRespawned: "PLAYER_RESPAWNED",
145 playerRespawned: "PLAYER_RESPAWNED",
@@ -138,6 +155,8 @@ export const MessageType = Object.freeze({
138 openLetter: "OPEN_LETTER",
155 openLetter: "OPEN_LETTER",
139 skills: "SKILLS",
156 skills: "SKILLS",
140 stamina: "STAMINA",
157 stamina: "STAMINA",
158 statusEffects: "STATUS_EFFECTS",
159 setGraphicsSettings: "SET_GRAPHICS_SETTINGS",
141 eatItem: "EAT_ITEM",
160 eatItem: "EAT_ITEM",
142 drinkItem: "DRINK_ITEM",
161 drinkItem: "DRINK_ITEM",
143 startCraft: "START_CRAFT",
162 startCraft: "START_CRAFT",
shared/statusEffects/display.js added +108 −0
@@ -0,0 +1,108 @@
1 import { StatusEffectType } from "./rules.js";
2
3 /**
4 * Player-facing copy + icon paths for HUD buff/debuff icons.
5 * Art lives under `client/assets/status-effects/<iconKey>.png` (placeholders until final art).
6 */
7 export const STATUS_EFFECT_DISPLAY = Object.freeze({
8 [StatusEffectType.healthRegen]: Object.freeze({
9 iconKey: "health-regen",
10 title: "Health regeneration",
11 polarity: "buff",
12 describe (effect)
13 {
14 const rate = Number(effect?.amountPerSecond) || 1;
15 return `Restores ${rate} health each second.`;
16 }
17 }),
18 [StatusEffectType.staminaRegen]: Object.freeze({
19 iconKey: "stamina-regen",
20 title: "Stamina regeneration",
21 polarity: "buff",
22 describe (effect)
23 {
24 const rate = Number(effect?.amountPerSecond) || 1;
25 return `Restores ${rate} stamina each second.`;
26 }
27 }),
28 [StatusEffectType.strengthBonus]: Object.freeze({
29 iconKey: "strength-bonus",
30 title: "Strength",
31 polarity: "buff",
32 describe (effect)
33 {
34 const amount = effect?.amount | 0 || 0;
35 return `Increases Strength by ${amount}.`;
36 }
37 }),
38 [StatusEffectType.mindBonus]: Object.freeze({
39 iconKey: "mind-bonus",
40 title: "Clarity",
41 polarity: "buff",
42 describe (effect)
43 {
44 const amount = effect?.amount | 0 || 0;
45 return `Increases Mind by ${amount}.`;
46 }
47 }),
48 [StatusEffectType.staminaDrain]: Object.freeze({
49 iconKey: "stamina-drain",
50 title: "Stamina drain",
51 polarity: "debuff",
52 describe (effect)
53 {
54 const rate = Number(effect?.amountPerSecond) || 1;
55 return `Drains ${rate} stamina each second.`;
56 }
57 }),
58 [StatusEffectType.glow]: Object.freeze({
59 iconKey: "glow",
60 title: "Glow",
61 polarity: "debuff",
62 describe ()
63 {
64 return "You cast a faint light around yourself.";
65 }
66 }),
67 [StatusEffectType.shrink]: Object.freeze({
68 iconKey: "shrink",
69 title: "Diminished",
70 polarity: "debuff",
71 describe (effect)
72 {
73 const scale = Math.round((Number(effect?.scale) || 0.5) * 100);
74 return `Your body is shrunk to ${scale}% size.`;
75 }
76 }),
77 [StatusEffectType.blind]: Object.freeze({
78 iconKey: "blind",
79 title: "Blindness",
80 polarity: "debuff",
81 describe ()
82 {
83 return "Darkness closes in; you can barely see what is next to you.";
84 }
85 })
86 });
87
88 export function statusEffectDisplay (type)
89 {
90 return STATUS_EFFECT_DISPLAY[type] ?? null;
91 }
92
93 export function statusEffectIconPath (type)
94 {
95 const display = statusEffectDisplay(type);
96 const key = display?.iconKey ?? String(type ?? "unknown");
97 return `/assets/status-effects/${key}.png`;
98 }
99
100 export function formatStatusRemaining (ms)
101 {
102 const total = Math.max(0, Math.ceil((ms | 0) / 1000));
103 if (total < 60)
104 { return `${total}s`; }
105 const minutes = (total / 60) | 0;
106 const seconds = total % 60;
107 return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
108 }
@@ -0,0 +1,108 @@
1import { StatusEffectType } from "./rules.js";
2
3/**
4 * Player-facing copy + icon paths for HUD buff/debuff icons.
5 * Art lives under `client/assets/status-effects/<iconKey>.png` (placeholders until final art).
6 */
7export const STATUS_EFFECT_DISPLAY = Object.freeze({
8 [StatusEffectType.healthRegen]: Object.freeze({
9 iconKey: "health-regen",
10 title: "Health regeneration",
11 polarity: "buff",
12 describe (effect)
13 {
14 const rate = Number(effect?.amountPerSecond) || 1;
15 return `Restores ${rate} health each second.`;
16 }
17 }),
18 [StatusEffectType.staminaRegen]: Object.freeze({
19 iconKey: "stamina-regen",
20 title: "Stamina regeneration",
21 polarity: "buff",
22 describe (effect)
23 {
24 const rate = Number(effect?.amountPerSecond) || 1;
25 return `Restores ${rate} stamina each second.`;
26 }
27 }),
28 [StatusEffectType.strengthBonus]: Object.freeze({
29 iconKey: "strength-bonus",
30 title: "Strength",
31 polarity: "buff",
32 describe (effect)
33 {
34 const amount = effect?.amount | 0 || 0;
35 return `Increases Strength by ${amount}.`;
36 }
37 }),
38 [StatusEffectType.mindBonus]: Object.freeze({
39 iconKey: "mind-bonus",
40 title: "Clarity",
41 polarity: "buff",
42 describe (effect)
43 {
44 const amount = effect?.amount | 0 || 0;
45 return `Increases Mind by ${amount}.`;
46 }
47 }),
48 [StatusEffectType.staminaDrain]: Object.freeze({
49 iconKey: "stamina-drain",
50 title: "Stamina drain",
51 polarity: "debuff",
52 describe (effect)
53 {
54 const rate = Number(effect?.amountPerSecond) || 1;
55 return `Drains ${rate} stamina each second.`;
56 }
57 }),
58 [StatusEffectType.glow]: Object.freeze({
59 iconKey: "glow",
60 title: "Glow",
61 polarity: "debuff",
62 describe ()
63 {
64 return "You cast a faint light around yourself.";
65 }
66 }),
67 [StatusEffectType.shrink]: Object.freeze({
68 iconKey: "shrink",
69 title: "Diminished",
70 polarity: "debuff",
71 describe (effect)
72 {
73 const scale = Math.round((Number(effect?.scale) || 0.5) * 100);
74 return `Your body is shrunk to ${scale}% size.`;
75 }
76 }),
77 [StatusEffectType.blind]: Object.freeze({
78 iconKey: "blind",
79 title: "Blindness",
80 polarity: "debuff",
81 describe ()
82 {
83 return "Darkness closes in; you can barely see what is next to you.";
84 }
85 })
86});
87
88export function statusEffectDisplay (type)
89{
90 return STATUS_EFFECT_DISPLAY[type] ?? null;
91}
92
93export function statusEffectIconPath (type)
94{
95 const display = statusEffectDisplay(type);
96 const key = display?.iconKey ?? String(type ?? "unknown");
97 return `/assets/status-effects/${key}.png`;
98}
99
100export function formatStatusRemaining (ms)
101{
102 const total = Math.max(0, Math.ceil((ms | 0) / 1000));
103 if (total < 60)
104 { return `${total}s`; }
105 const minutes = (total / 60) | 0;
106 const seconds = total % 60;
107 return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
108}
shared/statusEffects/rules.js added +137 −0
@@ -0,0 +1,137 @@
1 /**
2 * Timed status effects from potions (and later other sources).
3 * Server applies; clients get visual fields via entity replication + private blind flag.
4 */
5
6 export const StatusEffectType = Object.freeze({
7 healthRegen: "health-regen",
8 staminaRegen: "stamina-regen",
9 strengthBonus: "strength-bonus",
10 mindBonus: "mind-bonus",
11 staminaDrain: "stamina-drain",
12 glow: "glow",
13 shrink: "shrink",
14 blind: "blind"
15 });
16
17 /** Effects where drinking again extends remaining duration instead of replacing. */
18 const EXTEND_TYPES = new Set([
19 StatusEffectType.healthRegen,
20 StatusEffectType.staminaRegen
21 ]);
22
23 export function emptyStatusEffects ()
24 {
25 return { effects: [] };
26 }
27
28 export function pruneStatusEffects (component, now)
29 {
30 if (!component?.effects)
31 { return component; }
32 component.effects = component.effects.filter((entry) => (entry.expiresAt | 0) > now);
33 return component;
34 }
35
36 export function activeStatusEffects (component, now)
37 {
38 pruneStatusEffects(component, now);
39 return component?.effects ?? [];
40 }
41
42 /**
43 * Apply a potion/status effect definition `{ type, durationMs, ... }`.
44 * Regen effects stack duration; others refresh the same type.
45 */
46 export function applyStatusEffect (component, effect, now = Date.now())
47 {
48 if (!component || !effect?.type)
49 { return component; }
50 const type = effect.type;
51 const durationMs = Math.max(0, effect.durationMs | 0);
52 if (!component.effects)
53 { component.effects = []; }
54 pruneStatusEffects(component, now);
55
56 const existing = component.effects.find((entry) => entry.type === type);
57 if (existing && EXTEND_TYPES.has(type) && durationMs > 0)
58 {
59 existing.expiresAt = Math.max(existing.expiresAt | 0, now) + durationMs;
60 if (effect.amountPerSecond != null)
61 { existing.amountPerSecond = Number(effect.amountPerSecond) || existing.amountPerSecond; }
62 if (effect.amount != null)
63 { existing.amount = effect.amount | 0; }
64 return component;
65 }
66
67 if (existing)
68 {
69 existing.expiresAt = now + durationMs;
70 existing.amount = effect.amount | 0 || existing.amount;
71 existing.amountPerSecond = Number(effect.amountPerSecond) || existing.amountPerSecond;
72 existing.lightRadiusTiles = effect.lightRadiusTiles ?? existing.lightRadiusTiles;
73 existing.scale = effect.scale ?? existing.scale;
74 return component;
75 }
76
77 component.effects.push({
78 type,
79 expiresAt: now + durationMs,
80 amount: effect.amount | 0 || 0,
81 amountPerSecond: Number(effect.amountPerSecond) || 0,
82 lightRadiusTiles: effect.lightRadiusTiles ?? null,
83 scale: effect.scale ?? null
84 });
85 return component;
86 }
87
88 export function statusSkillBonuses (component, now = Date.now())
89 {
90 const bonuses = { strength: 0, mind: 0 };
91 for (const entry of activeStatusEffects(component, now))
92 {
93 if (entry.type === StatusEffectType.strengthBonus)
94 { bonuses.strength += entry.amount | 0; }
95 if (entry.type === StatusEffectType.mindBonus)
96 { bonuses.mind += entry.amount | 0; }
97 }
98 return bonuses;
99 }
100
101 export function statusVisualScale (component, now = Date.now())
102 {
103 for (const entry of activeStatusEffects(component, now))
104 {
105 if (entry.type === StatusEffectType.shrink && entry.scale != null)
106 { return Number(entry.scale) || 1; }
107 }
108 return 1;
109 }
110
111 export function statusExtraLightRadius (component, now = Date.now())
112 {
113 let best = 0;
114 for (const entry of activeStatusEffects(component, now))
115 {
116 if (entry.type === StatusEffectType.glow)
117 { best = Math.max(best, Number(entry.lightRadiusTiles) || 0); }
118 }
119 return best;
120 }
121
122 export function hasStatusEffect (component, type, now = Date.now())
123 {
124 return activeStatusEffects(component, now).some((entry) => entry.type === type);
125 }
126
127 export function publicStatusEffectsView (component, now = Date.now())
128 {
129 return activeStatusEffects(component, now).map((entry) => ({
130 type: entry.type,
131 expiresAt: entry.expiresAt | 0,
132 amount: entry.amount | 0,
133 amountPerSecond: Number(entry.amountPerSecond) || 0,
134 lightRadiusTiles: entry.lightRadiusTiles,
135 scale: entry.scale
136 }));
137 }
@@ -0,0 +1,137 @@
1/**
2 * Timed status effects from potions (and later other sources).
3 * Server applies; clients get visual fields via entity replication + private blind flag.
4 */
5
6export const StatusEffectType = Object.freeze({
7 healthRegen: "health-regen",
8 staminaRegen: "stamina-regen",
9 strengthBonus: "strength-bonus",
10 mindBonus: "mind-bonus",
11 staminaDrain: "stamina-drain",
12 glow: "glow",
13 shrink: "shrink",
14 blind: "blind"
15});
16
17/** Effects where drinking again extends remaining duration instead of replacing. */
18const EXTEND_TYPES = new Set([
19 StatusEffectType.healthRegen,
20 StatusEffectType.staminaRegen
21]);
22
23export function emptyStatusEffects ()
24{
25 return { effects: [] };
26}
27
28export function pruneStatusEffects (component, now)
29{
30 if (!component?.effects)
31 { return component; }
32 component.effects = component.effects.filter((entry) => (entry.expiresAt | 0) > now);
33 return component;
34}
35
36export function activeStatusEffects (component, now)
37{
38 pruneStatusEffects(component, now);
39 return component?.effects ?? [];
40}
41
42/**
43 * Apply a potion/status effect definition `{ type, durationMs, ... }`.
44 * Regen effects stack duration; others refresh the same type.
45 */
46export function applyStatusEffect (component, effect, now = Date.now())
47{
48 if (!component || !effect?.type)
49 { return component; }
50 const type = effect.type;
51 const durationMs = Math.max(0, effect.durationMs | 0);
52 if (!component.effects)
53 { component.effects = []; }
54 pruneStatusEffects(component, now);
55
56 const existing = component.effects.find((entry) => entry.type === type);
57 if (existing && EXTEND_TYPES.has(type) && durationMs > 0)
58 {
59 existing.expiresAt = Math.max(existing.expiresAt | 0, now) + durationMs;
60 if (effect.amountPerSecond != null)
61 { existing.amountPerSecond = Number(effect.amountPerSecond) || existing.amountPerSecond; }
62 if (effect.amount != null)
63 { existing.amount = effect.amount | 0; }
64 return component;
65 }
66
67 if (existing)
68 {
69 existing.expiresAt = now + durationMs;
70 existing.amount = effect.amount | 0 || existing.amount;
71 existing.amountPerSecond = Number(effect.amountPerSecond) || existing.amountPerSecond;
72 existing.lightRadiusTiles = effect.lightRadiusTiles ?? existing.lightRadiusTiles;
73 existing.scale = effect.scale ?? existing.scale;
74 return component;
75 }
76
77 component.effects.push({
78 type,
79 expiresAt: now + durationMs,
80 amount: effect.amount | 0 || 0,
81 amountPerSecond: Number(effect.amountPerSecond) || 0,
82 lightRadiusTiles: effect.lightRadiusTiles ?? null,
83 scale: effect.scale ?? null
84 });
85 return component;
86}
87
88export function statusSkillBonuses (component, now = Date.now())
89{
90 const bonuses = { strength: 0, mind: 0 };
91 for (const entry of activeStatusEffects(component, now))
92 {
93 if (entry.type === StatusEffectType.strengthBonus)
94 { bonuses.strength += entry.amount | 0; }
95 if (entry.type === StatusEffectType.mindBonus)
96 { bonuses.mind += entry.amount | 0; }
97 }
98 return bonuses;
99}
100
101export function statusVisualScale (component, now = Date.now())
102{
103 for (const entry of activeStatusEffects(component, now))
104 {
105 if (entry.type === StatusEffectType.shrink && entry.scale != null)
106 { return Number(entry.scale) || 1; }
107 }
108 return 1;
109}
110
111export function statusExtraLightRadius (component, now = Date.now())
112{
113 let best = 0;
114 for (const entry of activeStatusEffects(component, now))
115 {
116 if (entry.type === StatusEffectType.glow)
117 { best = Math.max(best, Number(entry.lightRadiusTiles) || 0); }
118 }
119 return best;
120}
121
122export function hasStatusEffect (component, type, now = Date.now())
123{
124 return activeStatusEffects(component, now).some((entry) => entry.type === type);
125}
126
127export function publicStatusEffectsView (component, now = Date.now())
128{
129 return activeStatusEffects(component, now).map((entry) => ({
130 type: entry.type,
131 expiresAt: entry.expiresAt | 0,
132 amount: entry.amount | 0,
133 amountPerSecond: Number(entry.amountPerSecond) || 0,
134 lightRadiusTiles: entry.lightRadiusTiles,
135 scale: entry.scale
136 }));
137}